{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ghost-trail-line-chart",
  "title": "Ghost Trail Line Chart",
  "description": "Compare periods by flipping through them: the line swings to its new shape and leaves fading ghosts behind, with earlier periods kept as faint traces.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/new-york/ghost-trail-line-chart/ghost-trail-line-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface GhostPeriod {\n  label: string;\n  /** One value per day. Periods of different lengths are fine. */\n  values: number[];\n}\n\nexport interface GhostTrailLineChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"section\">,\n  \"title\"\n> {\n  theme?: \"dark\" | \"light\";\n  title?: string;\n  subtitle?: string;\n  /** Newest first. The others stay behind the line as faint traces. */\n  periods?: GhostPeriod[];\n  /** Index of the period shown first. */\n  defaultIndex?: number;\n  /** Colour of the line and cells. */\n  color?: string;\n  /** Height of the plot, in px. */\n  height?: number;\n  /** Word after the value in the readout. */\n  unit?: string;\n  formatValue?: (value: number) => string;\n  onPeriodChange?: (period: GhostPeriod) => void;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#08090A\",\n    border: \"rgba(255,255,255,0.08)\",\n    grid: \"rgba(255,255,255,0.05)\",\n    text: \"#F7F8F8\",\n    sub: \"#8A8F98\",\n    faint: \"#62666D\",\n    empty: \"#16171A\",\n    tip: \"#161718\",\n    tipShadow: \"0 4px 24px rgba(0,0,0,0.4)\",\n    chip: \"rgba(255,255,255,0.05)\",\n    chipOn: \"rgba(255,255,255,0.1)\",\n    ring: \"#F7F8F8\",\n    accent: \"#2EE6A8\",\n    glow: 0.8,\n  },\n  light: {\n    card: \"#FFFFFF\",\n    border: \"rgba(8,9,10,0.08)\",\n    grid: \"rgba(8,9,10,0.06)\",\n    text: \"#08090A\",\n    sub: \"#62666D\",\n    faint: \"#8A8F98\",\n    empty: \"#EEEFF1\",\n    tip: \"#FFFFFF\",\n    tipShadow: \"0 3px 12px rgba(8,9,10,0.09)\",\n    chip: \"rgba(8,9,10,0.04)\",\n    chipOn: \"#FFFFFF\",\n    ring: \"#08090A\",\n    accent: \"#0E9F6E\",\n    glow: 0.35,\n  },\n};\n\ntype Palette = (typeof PALETTES)[\"dark\"];\n\nconst LEFT = 40;\nconst RIGHT = 8;\nconst TOP = 10;\n\n/** A fixed, believable daily series: a trend, a weekly rhythm and integer noise, so server and client agree. */\nfunction makeSeries(seed: number, length: number, base: number, rise: number) {\n  const week = [0, 12, 18, 16, 10, -24, -30];\n  const end = Date.UTC(2025, 11, 31);\n  let state = seed;\n  return Array.from({ length }, (_, i) => {\n    state = (state * 9301 + 49297) % 233280;\n    const noise = Math.round((state / 233280 - 0.5) * 34);\n    const when = new Date(end - (length - 1 - i) * 86400000);\n    return {\n      date: when.toISOString().slice(0, 10),\n      value: Math.round(\n        (base + (rise * i) / length) *\n          (1 + (week[when.getUTCDay()] + noise) / 100),\n      ),\n    };\n  });\n}\n\nfunction mix(a: string, b: string, t: number) {\n  const channels = (hex: string) =>\n    [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));\n  const [x, y] = [channels(a), channels(b)];\n  return `rgb(${x.map((v, i) => Math.round(v + (y[i] - v) * t)).join(\",\")})`;\n}\n\n/** Five levels from the quartiles, so one huge day does not wash out the rest. */\nfunction levels(values: number[]) {\n  const sorted = [...values].sort((a, b) => a - b);\n  const at = (p: number) => sorted[Math.floor(p * (sorted.length - 1))] ?? 0;\n  const cuts = [at(0.2), at(0.45), at(0.7), at(0.9)];\n  return values.map((v) => cuts.filter((c) => v > c).length);\n}\n\nconst LEVEL_MIX = [0.12, 0.3, 0.52, 0.76, 1];\n\n// Monotone cubic interpolation preserves local extrema and never overshoots the data.\nfunction curve(points: [number, number][]) {\n  if (points.length < 2) return \"\";\n  const slopes = points\n    .slice(1)\n    .map((p, i) => (p[1] - points[i][1]) / (p[0] - points[i][0]));\n  const tangents = points.map((_, i) =>\n    i === 0\n      ? slopes[0]\n      : i === points.length - 1\n        ? slopes[i - 1]\n        : slopes[i - 1] * slopes[i] <= 0\n          ? 0\n          : (slopes[i - 1] + slopes[i]) / 2,\n  );\n  return (\n    `M${points[0][0].toFixed(1)},${points[0][1].toFixed(1)}` +\n    points\n      .slice(1)\n      .map((p, i) => {\n        const prev = points[i];\n        const dx = (p[0] - prev[0]) / 3;\n        return `C${(prev[0] + dx).toFixed(1)},${(prev[1] + dx * tangents[i]).toFixed(1)} ${(p[0] - dx).toFixed(1)},${(p[1] - dx * tangents[i + 1]).toFixed(1)} ${p[0].toFixed(1)},${p[1].toFixed(1)}`;\n      })\n      .join(\"\")\n  );\n}\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n/** The chart is drawn at its real width, so its text stays the same size on a phone. */\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(700);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(Math.max(240, Math.round(entry.contentRect.width))),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\nfunction Stat({\n  value,\n  label,\n  pal,\n}: {\n  value: string;\n  label: string;\n  pal: Palette;\n}) {\n  return (\n    <div className=\"text-left sm:text-right\">\n      <p className=\"m-0 text-[18px] leading-[1.2] font-[510] tracking-[-0.018em] tabular-nums\">\n        {value}\n      </p>\n      <p\n        className=\"m-0 mt-0.5 text-[12px] tracking-[-0.011em]\"\n        style={{ color: pal.sub }}\n      >\n        {label}\n      </p>\n    </div>\n  );\n}\n\nfunction Legend({ pal, accent }: { pal: Palette; accent: string }) {\n  return (\n    <div\n      className=\"flex items-center gap-1 text-[12px]\"\n      style={{ color: pal.sub }}\n    >\n      <span className=\"mr-1\">Less</span>\n      {LEVEL_MIX.map((t) => (\n        <span\n          key={t}\n          className=\"size-2.5 rounded-[3px]\"\n          style={{ background: mix(pal.empty, accent, t) }}\n        />\n      ))}\n      <span className=\"ml-1\">More</span>\n    </div>\n  );\n}\n\nfunction Tip({\n  x,\n  y,\n  width,\n  pal,\n  children,\n}: {\n  x: number;\n  y: number;\n  width: number;\n  pal: Palette;\n  children: React.ReactNode;\n}) {\n  return (\n    <div\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute z-10 -translate-x-1/2 rounded-lg px-2.5 py-1.5 text-[12px] tracking-[-0.011em] whitespace-nowrap\"\n      style={{\n        left: Math.max(92, Math.min(width - 92, x)),\n        top: Math.max(0, y - 42),\n        background: pal.tip,\n        color: pal.sub,\n        boxShadow: `inset 0 0 0 1px ${pal.border}, ${pal.tipShadow}`,\n      }}\n    >\n      {children}\n    </div>\n  );\n}\n\nconst CARD_FONT =\n  '\"Inter Variable\", Inter, \"SF Pro Display\", -apple-system, BlinkMacSystemFont, sans-serif';\n\nconst DEFAULT_PERIODS: GhostPeriod[] = [\n  { label: \"Dec\", values: makeSeries(7, 30, 520, 180).map((d) => d.value) },\n  { label: \"Nov\", values: makeSeries(53, 30, 430, 90).map((d) => d.value) },\n  { label: \"Oct\", values: makeSeries(91, 30, 470, -80).map((d) => d.value) },\n  { label: \"Sep\", values: makeSeries(17, 30, 350, 60).map((d) => d.value) },\n];\nconst FORMAT = (n: number) => Math.round(n).toLocaleString(\"en-US\");\n\n/** How long the line takes to change shape, and how long each ghost it drops takes to fade. */\nconst MORPH = 720;\nconst FADE = 900;\n\ninterface Ghost {\n  values: number[];\n  opacity: number;\n}\n\nconst fit = (values: number[], length: number) =>\n  Array.from({ length }, (_, i) => values[Math.min(i, values.length - 1)] ?? 0);\n\nexport function GhostTrailLineChart({\n  theme = \"dark\",\n  title = \"Daily sessions\",\n  subtitle = \"Each month leaves a trace behind the one you are reading.\",\n  periods = DEFAULT_PERIODS,\n  defaultIndex = 0,\n  color,\n  height = 200,\n  unit = \"sessions\",\n  formatValue = FORMAT,\n  onPeriodChange,\n  className,\n  style,\n  ...props\n}: GhostTrailLineChartProps) {\n  const pal = PALETTES[theme];\n  const accent = color ?? pal.accent;\n  const reduce = useReducedMotion();\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(boxRef);\n  const [index, setIndex] = React.useState(defaultIndex);\n  const period = periods[index] ?? periods[0];\n  const count = Math.max(0, ...periods.map((p) => p.values.length));\n  const target = React.useMemo(\n    () => fit(period?.values ?? [], count),\n    [period, count],\n  );\n  const [shown, setShown] = React.useState(target);\n  const [ghosts, setGhosts] = React.useState<Ghost[]>([]);\n  const [active, setActive] = React.useState<number | null>(null);\n  const currentRef = React.useRef(target);\n\n  // The line eases to its new shape and drops a copy of itself every few frames. Each copy fades on its own.\n  React.useEffect(() => {\n    const from = currentRef.current;\n    if (from === target) return;\n    if (reduce) {\n      currentRef.current = target;\n      const still = requestAnimationFrame(() => setShown(target));\n      return () => cancelAnimationFrame(still);\n    }\n    let raf = 0;\n    let start = 0;\n    let dropped = 0;\n    let trail: { values: number[]; born: number }[] = [];\n    const frame = (now: number) => {\n      start = start || now;\n      const k = Math.min(1, (now - start) / MORPH);\n      const e = 1 - Math.pow(1 - k, 3);\n      const next = target.map(\n        (v, i) => (from[i] ?? v) + (v - (from[i] ?? v)) * e,\n      );\n      currentRef.current = k < 1 ? next : target;\n      if (k < 1 && now - dropped > 60) {\n        dropped = now;\n        trail.push({ values: next, born: now });\n      }\n      trail = trail.filter((g) => now - g.born < FADE);\n      setShown(currentRef.current);\n      setGhosts(\n        trail.map((g) => ({\n          values: g.values,\n          opacity: 0.32 * (1 - (now - g.born) / FADE),\n        })),\n      );\n      if (k < 1 || trail.length) raf = requestAnimationFrame(frame);\n    };\n    raf = requestAnimationFrame(frame);\n    return () => cancelAnimationFrame(raf);\n  }, [target, reduce]);\n\n  const max = Math.max(1, ...periods.flatMap((p) => p.values), ...shown) * 1.08;\n  const span = width - LEFT - RIGHT;\n  const x = (i: number) => LEFT + ((i + 0.5) / Math.max(1, count)) * span;\n  const y = (v: number) => height - 2 - (v / max) * (height - TOP - 2);\n  const path = (list: number[]) =>\n    curve(list.map((v, i) => [x(i), y(v)] as [number, number]));\n  const values = period?.values ?? [];\n  const level = levels(target);\n  const every = Math.max(1, Math.ceil(count / Math.floor(width / 72)));\n  const days = Array.from({ length: count }, (_, i) => `Day ${i + 1}`);\n  const total = values.reduce((n, v) => n + v, 0);\n  const average = total / Math.max(1, values.length);\n  const older = periods[index + 1];\n  const before = older\n    ? older.values.reduce((n, v) => n + v, 0) / Math.max(1, older.values.length)\n    : 0;\n  const change = before ? ((average - before) / before) * 100 : null;\n  const current = active === null ? null : (target[active] ?? 0);\n\n  return (\n    <section\n      className={`w-full rounded-2xl p-5 sm:p-6 ${className ?? \"\"}`}\n      style={{\n        background: pal.card,\n        boxShadow: `inset 0 0 0 1px ${pal.border}`,\n        color: pal.text,\n        fontFamily: CARD_FONT,\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-x-8 gap-y-3\">\n        <div>\n          <h3 className=\"m-0 text-[17px] leading-[1.33] font-[590] tracking-[-0.012em]\">\n            {title}\n          </h3>\n          <p\n            className=\"m-0 mt-0.5 text-[13px] tracking-[-0.011em]\"\n            style={{ color: pal.sub }}\n          >\n            {subtitle}\n          </p>\n        </div>\n        <div className=\"flex gap-7\">\n          <Stat value={formatValue(average)} label=\"Daily average\" pal={pal} />\n          <Stat\n            value={formatValue(Math.max(0, ...values))}\n            label=\"Best day\"\n            pal={pal}\n          />\n          <Stat\n            value={\n              change === null\n                ? \"—\"\n                : `${change >= 0 ? \"+\" : \"−\"}${Math.abs(change).toFixed(1)}%`\n            }\n            label={older ? `vs ${older.label}` : \"No earlier data\"}\n            pal={pal}\n          />\n        </div>\n      </div>\n\n      {!count ? (\n        <p className=\"py-16 text-center text-sm\" style={{ color: pal.sub }}>\n          No data available.\n        </p>\n      ) : (\n        <div\n          ref={boxRef}\n          className=\"relative mt-5 rounded-lg outline-none focus-visible:ring-2\"\n          tabIndex={0}\n          role=\"group\"\n          aria-label={`${title}. Use left and right arrow keys to read each day.`}\n          onPointerMove={(e) => {\n            const r = e.currentTarget.getBoundingClientRect();\n            const i = Math.floor(((e.clientX - r.left - LEFT) / span) * count);\n            setActive(Math.max(0, Math.min(count - 1, i)));\n          }}\n          onPointerLeave={() => setActive(null)}\n          onBlur={() => setActive(null)}\n          onKeyDown={(e) => {\n            if (e.key !== \"ArrowLeft\" && e.key !== \"ArrowRight\") return;\n            e.preventDefault();\n            const dir = e.key === \"ArrowRight\" ? 1 : -1;\n            setActive((a) =>\n              Math.max(0, Math.min(count - 1, (a ?? count) + dir)),\n            );\n          }}\n        >\n          <svg\n            viewBox={`0 0 ${width} ${height}`}\n            className=\"block w-full\"\n            style={{ height }}\n            role=\"img\"\n            aria-label={`${period?.label}: daily average ${formatValue(average)} ${unit}`}\n          >\n            {[0, 0.5, 1].map((t) => (\n              <g key={t}>\n                <line\n                  x1={LEFT}\n                  x2={width - RIGHT}\n                  y1={y(max * t)}\n                  y2={y(max * t)}\n                  stroke={pal.grid}\n                />\n                <text\n                  x={LEFT - 8}\n                  y={y(max * t) + 4}\n                  textAnchor=\"end\"\n                  fontSize=\"11\"\n                  fill={pal.faint}\n                >\n                  {formatValue(max * t)}\n                </text>\n              </g>\n            ))}\n            {/* The other periods, fainter the further they are from the one on show. */}\n            {periods.map((p, i) =>\n              i === index ? null : (\n                <path\n                  key={p.label}\n                  d={path(fit(p.values, count))}\n                  fill=\"none\"\n                  stroke={pal.sub}\n                  strokeWidth=\"1\"\n                  opacity={Math.max(0.1, 0.34 - Math.abs(i - index) * 0.08)}\n                />\n              ),\n            )}\n            {ghosts.map((g, i) => (\n              <path\n                key={i}\n                d={path(g.values)}\n                fill=\"none\"\n                stroke={accent}\n                strokeWidth=\"1.25\"\n                opacity={g.opacity}\n              />\n            ))}\n            <path\n              d={path(shown)}\n              fill=\"none\"\n              stroke={accent}\n              strokeWidth=\"2\"\n              strokeLinecap=\"round\"\n            />\n            {active !== null && current !== null && (\n              <g>\n                <line\n                  x1={x(active)}\n                  x2={x(active)}\n                  y1={TOP}\n                  y2={height}\n                  stroke={pal.border}\n                />\n                {periods.map((p, i) =>\n                  i === index ? null : (\n                    <circle\n                      key={p.label}\n                      cx={x(active)}\n                      cy={y(fit(p.values, count)[active])}\n                      r=\"2\"\n                      fill={pal.sub}\n                    />\n                  ),\n                )}\n                <circle\n                  cx={x(active)}\n                  cy={y(current)}\n                  r=\"3.5\"\n                  fill={accent}\n                  stroke={pal.card}\n                  strokeWidth=\"2\"\n                />\n              </g>\n            )}\n          </svg>\n\n          <div\n            aria-hidden=\"true\"\n            className=\"mt-2 flex gap-[3px]\"\n            style={{ marginLeft: LEFT, marginRight: RIGHT }}\n          >\n            {target.map((v, i) => (\n              <span\n                key={i}\n                className=\"h-3.5 min-w-0 flex-1 rounded-[3px] transition-colors duration-300\"\n                style={{\n                  background: mix(pal.empty, accent, LEVEL_MIX[level[i]]),\n                  boxShadow: active === i ? `0 0 0 1px ${pal.ring}` : undefined,\n                }}\n              />\n            ))}\n          </div>\n          <div\n            aria-hidden=\"true\"\n            className=\"relative mt-1.5 h-4 text-[11px]\"\n            style={{ color: pal.faint, marginLeft: LEFT, marginRight: RIGHT }}\n          >\n            {days.map(\n              (date, i) =>\n                i % every === 0 && (\n                  <span\n                    key={date}\n                    className=\"absolute top-0 whitespace-nowrap\"\n                    style={{ left: `${(i / count) * 100}%` }}\n                  >\n                    {date}\n                  </span>\n                ),\n            )}\n          </div>\n\n          {active !== null && current !== null && (\n            <Tip x={x(active)} y={y(current)} width={width} pal={pal}>\n              <span className=\"font-[510]\" style={{ color: pal.text }}>\n                {formatValue(current)} {unit}\n              </span>{\" \"}\n              on {period?.label} {active + 1}\n            </Tip>\n          )}\n        </div>\n      )}\n\n      <div className=\"mt-3 flex flex-wrap items-center justify-between gap-2\">\n        <div\n          className=\"flex rounded-full p-0.5\"\n          style={{ background: pal.chip }}\n          role=\"radiogroup\"\n          aria-label=\"Period\"\n        >\n          {periods.map((p, i) => (\n            <button\n              key={p.label}\n              type=\"button\"\n              role=\"radio\"\n              aria-checked={i === index}\n              onClick={() => {\n                setIndex(i);\n                onPeriodChange?.(p);\n              }}\n              className=\"h-7 cursor-pointer rounded-full px-3 text-[13px] font-[510] tracking-[-0.011em] transition-colors outline-none focus-visible:ring-2\"\n              style={{\n                background: i === index ? pal.chipOn : \"transparent\",\n                color: i === index ? pal.text : pal.sub,\n              }}\n            >\n              {p.label}\n            </button>\n          ))}\n        </div>\n        <Legend pal={pal} accent={accent} />\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}