{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "trend-line",
  "type": "registry:component",
  "title": "Trend Line",
  "description": "Linear least-squares trend line for a series on line, area, bar, and composed charts",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "@bklit/chart-context",
    "@bklit/chart-series"
  ],
  "files": [
    {
      "path": "src/charts/trend-line.tsx",
      "content": "\"use client\";\n\nimport {\n  animate as animateValue,\n  m,\n  type Transition,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { chartCssVars, useChartStable, useYScale } from \"./chart-context\";\nimport { type FadeEdges, type FadeSides, resolveFadeSides } from \"./fade-edges\";\nimport { LINE_LOADING_PULSE_EASE } from \"./line-loading-timing\";\nimport {\n  computeTrendSegment,\n  interpolateTrendSegment,\n  type TrendPoint,\n  type TrendSegment,\n} from \"./trend-line-utils\";\n\nexport type TrendLineStrokeStyle = \"solid\" | \"gradient\" | \"dashed\";\n\nexport interface TrendLineProps {\n  /** Series key to fit (linear least-squares). */\n  dataKey: string;\n  /** Stroke color. Default: var(--chart-line-primary) */\n  stroke?: string;\n  /** Stroke width. Default: 2 */\n  strokeWidth?: number;\n  /** Solid, dashed, or path-aligned gradient stroke. Default: dashed */\n  strokeStyle?: TrendLineStrokeStyle;\n  /** Dash pattern when `strokeStyle` is `\"dashed\"`. Default: \"6,4\" */\n  strokeDasharray?: string;\n  /** Gradient start color when `strokeStyle` is gradient. Default: `stroke` */\n  gradientStart?: string;\n  /** Gradient end color when `strokeStyle` is gradient. Default: var(--chart-5) */\n  gradientEnd?: string;\n  /** Fade the line ends to transparent. Default: false */\n  fadeEdges?: FadeEdges;\n  /** Fade zone as % of line length per faded end. Default: 15 */\n  fadeEdgesLength?: number;\n  /** Line opacity. Default: 1 */\n  opacity?: number;\n  /** Y-scale group id. Default: `\"left\"`. */\n  yAxisId?: string;\n  /** Fade in on reveal and tween on data change. Default: true */\n  animate?: boolean;\n  className?: string;\n}\n\nconst ENTER_FADE_MS = 420;\n\nfunction clampFadeLength(length: number): number {\n  return Math.min(50, Math.max(0, length));\n}\n\nfunction isVisiblePhase(phase: string): boolean {\n  return phase === \"revealing\" || phase === \"ready\" || phase === \"exitingReady\";\n}\n\nfunction resolveFadeTransition(\n  skipMotion: boolean,\n  enterTransition: Transition | undefined\n): Transition {\n  if (skipMotion) {\n    return { duration: 0 };\n  }\n  return enterTransition && typeof enterTransition === \"object\"\n    ? enterTransition\n    : { duration: ENTER_FADE_MS / 1000, ease: \"easeOut\" };\n}\n\nfunction segmentSignature(segment: TrendSegment | null): string {\n  return segment\n    ? `${segment.x1}|${segment.y1}|${segment.x2}|${segment.y2}`\n    : \"\";\n}\n\n/** Data-space segment → plot pixels. Horizontal bars swap the axes. */\nfunction projectTrendSegment(\n  segment: TrendSegment,\n  mapAlong: (x: number) => number,\n  valueScale: (value: number) => number | undefined,\n  swapAxes: boolean\n): TrendSegment {\n  const along1 = mapAlong(segment.x1);\n  const along2 = mapAlong(segment.x2);\n  const value1 = valueScale(segment.y1) ?? 0;\n  const value2 = valueScale(segment.y2) ?? 0;\n  return swapAxes\n    ? { x1: value1, y1: along1, x2: value2, y2: along2 }\n    : { x1: along1, y1: value1, x2: along2, y2: value2 };\n}\n\n/** Gradient vector pinned to the line endpoints (start → end). */\nfunction lineGradientVector(pixels: TrendSegment) {\n  return {\n    gradientUnits: \"userSpaceOnUse\" as const,\n    x1: pixels.x1,\n    x2: pixels.x2,\n    y1: pixels.y1,\n    y2: pixels.y2,\n  };\n}\n\n/**\n * Luminance mask fading the line ends along its own direction, so the fade\n * composes with gradient and dashed strokes.\n */\nfunction TrendLineFadeMask({\n  fadeLength,\n  id,\n  pad,\n  pixels,\n  sides,\n}: {\n  fadeLength: number;\n  id: string;\n  pad: number;\n  pixels: TrendSegment;\n  sides: FadeSides;\n}) {\n  const gradientId = `${id}-gradient`;\n  const x = Math.min(pixels.x1, pixels.x2) - pad;\n  const y = Math.min(pixels.y1, pixels.y2) - pad;\n  const width = Math.abs(pixels.x2 - pixels.x1) + pad * 2;\n  const height = Math.abs(pixels.y2 - pixels.y1) + pad * 2;\n  return (\n    <>\n      <linearGradient id={gradientId} {...lineGradientVector(pixels)}>\n        <stop\n          offset=\"0%\"\n          style={{ stopColor: \"white\", stopOpacity: sides.left ? 0 : 1 }}\n        />\n        <stop\n          offset={`${sides.left ? fadeLength : 0}%`}\n          style={{ stopColor: \"white\", stopOpacity: 1 }}\n        />\n        <stop\n          offset={`${sides.right ? 100 - fadeLength : 100}%`}\n          style={{ stopColor: \"white\", stopOpacity: 1 }}\n        />\n        <stop\n          offset=\"100%\"\n          style={{ stopColor: \"white\", stopOpacity: sides.right ? 0 : 1 }}\n        />\n      </linearGradient>\n      {/* userSpaceOnUse: a horizontal line has a zero-height bbox. */}\n      <mask\n        height={height}\n        id={id}\n        maskUnits=\"userSpaceOnUse\"\n        width={width}\n        x={x}\n        y={y}\n      >\n        <rect\n          fill={`url(#${gradientId})`}\n          height={height}\n          width={width}\n          x={x}\n          y={y}\n        />\n      </mask>\n    </>\n  );\n}\n\n/**\n * Pixel endpoints, tweened when the fitted segment changes. Mirrors\n * `useAnimatedSeriesPath`: the target is read live each frame so a\n * concurrent y-domain tween (new scale per frame) doesn't stop the tween.\n */\nfunction useAnimatedTrendPixels({\n  dataSignature,\n  durationMs,\n  enabled,\n  targetPixels,\n}: {\n  dataSignature: string;\n  durationMs: number;\n  enabled: boolean;\n  targetPixels: TrendSegment | null;\n}): TrendSegment | null {\n  const reducedMotion = useReducedMotion();\n  const [animated, setAnimated] = useState<TrendSegment | null>(null);\n  const displayedRef = useRef<TrendSegment | null>(targetPixels);\n  const animatingRef = useRef(false);\n  const prevSignatureRef = useRef(dataSignature);\n  const latestTargetRef = useRef(targetPixels);\n  // Synced before the tween layout effect below (not during render).\n  useLayoutEffect(() => {\n    latestTargetRef.current = targetPixels;\n  });\n\n  const shouldAnimate = enabled && !reducedMotion && durationMs > 0;\n\n  // Layout effect so frame 0 (previous endpoints) commits before paint.\n  // Target pixels are read live via latestTargetRef (the y-domain tween\n  // rebuilds scales every frame); only a new fit should restart the tween.\n  useLayoutEffect(() => {\n    const dataChanged = prevSignatureRef.current !== dataSignature;\n    prevSignatureRef.current = dataSignature;\n\n    const from = displayedRef.current;\n    const target = latestTargetRef.current;\n    if (!(shouldAnimate && dataChanged && from && target)) {\n      animatingRef.current = false;\n      displayedRef.current = target;\n      setAnimated(null);\n      return;\n    }\n\n    animatingRef.current = true;\n    const renderFrame = (progress: number) => {\n      const to = latestTargetRef.current;\n      if (!to) {\n        return;\n      }\n      const next = interpolateTrendSegment(from, to, progress);\n      displayedRef.current = next;\n      setAnimated(next);\n    };\n    renderFrame(0);\n\n    const control = animateValue(0, 1, {\n      duration: durationMs / 1000,\n      ease: [...LINE_LOADING_PULSE_EASE],\n      onUpdate: renderFrame,\n      onComplete: () => {\n        animatingRef.current = false;\n        displayedRef.current = latestTargetRef.current;\n        setAnimated(null);\n      },\n    });\n\n    return () => {\n      control.stop();\n      animatingRef.current = false;\n    };\n  }, [dataSignature, durationMs, shouldAnimate]);\n\n  // After the tween effect: a data change needs the old endpoints as `from`.\n  useEffect(() => {\n    if (!animatingRef.current) {\n      displayedRef.current = targetPixels;\n    }\n  }, [targetPixels]);\n\n  return animated ?? targetPixels;\n}\n\nexport function TrendLine({\n  dataKey,\n  stroke = chartCssVars.linePrimary,\n  strokeWidth = 2,\n  strokeStyle = \"dashed\",\n  strokeDasharray = \"6,4\",\n  gradientStart,\n  gradientEnd = \"var(--chart-5)\",\n  fadeEdges = false,\n  fadeEdgesLength = 15,\n  opacity = 1,\n  yAxisId,\n  animate = true,\n  className,\n}: TrendLineProps) {\n  const {\n    data,\n    xScale,\n    xAccessor,\n    barScale,\n    barXAccessor,\n    bandWidth = 0,\n    orientation,\n    chartPhase,\n    enterTransition,\n    isLoaded,\n    yDomainTweenDuration,\n  } = useChartStable();\n  const valueScale = useYScale(yAxisId);\n  const uniqueId = useId().replace(/:/g, \"\");\n  const gradientId = `chart-trend-line-gradient-${uniqueId}`;\n  const maskId = `chart-trend-line-fade-${uniqueId}`;\n\n  // BarChart exposes a band scale; regression x is the category index there.\n  const isBar = barScale != null && barXAccessor != null;\n  const isHorizontal = isBar && orientation === \"horizontal\";\n\n  const points = useMemo<TrendPoint[]>(\n    () =>\n      data.map((d, index) => {\n        const value = d[dataKey];\n        return {\n          x: isBar ? index : xAccessor(d).getTime(),\n          y: typeof value === \"number\" ? value : Number.NaN,\n        };\n      }),\n    [data, dataKey, isBar, xAccessor]\n  );\n\n  const segment = useMemo(() => computeTrendSegment(points), [points]);\n\n  const targetPixels = useMemo<TrendSegment | null>(() => {\n    if (!segment) {\n      return null;\n    }\n    let mapAlong: (x: number) => number;\n    if (isBar) {\n      // Bands are evenly spaced, so centers are linear in the index.\n      const bandCenter = (d: Record<string, unknown> | undefined) =>\n        (d ? (barScale(barXAccessor(d)) ?? 0) : 0) + bandWidth / 2;\n      const firstCenter = bandCenter(data[0]);\n      const lastCenter = bandCenter(data.at(-1));\n      const span = Math.max(1, data.length - 1);\n      mapAlong = (x) => firstCenter + ((lastCenter - firstCenter) * x) / span;\n    } else {\n      mapAlong = (x) => xScale(new Date(x)) ?? 0;\n    }\n    return projectTrendSegment(segment, mapAlong, valueScale, isHorizontal);\n  }, [\n    bandWidth,\n    barScale,\n    barXAccessor,\n    data,\n    isBar,\n    isHorizontal,\n    segment,\n    valueScale,\n    xScale,\n  ]);\n\n  const reducedMotion = useReducedMotion();\n  const pixels = useAnimatedTrendPixels({\n    dataSignature: segmentSignature(segment),\n    durationMs: yDomainTweenDuration,\n    enabled: animate && chartPhase === \"ready\",\n    targetPixels,\n  });\n\n  if (!pixels) {\n    return null;\n  }\n\n  // Bars grow in first; the trend line fades in once they've landed.\n  const visible =\n    isVisiblePhase(chartPhase) && (!isBar || isLoaded || !animate);\n  const skipMotion = !animate || reducedMotion === true;\n  const fadeTransition = resolveFadeTransition(skipMotion, enterTransition);\n\n  const fadeSides = resolveFadeSides(fadeEdges);\n  const fadeLength = clampFadeLength(fadeEdgesLength);\n  const gradientVector = lineGradientVector(pixels);\n  const isGradient = strokeStyle === \"gradient\";\n\n  return (\n    <m.g\n      animate={{ opacity: visible ? opacity : 0 }}\n      aria-hidden=\"true\"\n      className={className ?? \"chart-trend-line\"}\n      initial={skipMotion ? false : { opacity: 0 }}\n      transition={fadeTransition}\n    >\n      {isGradient || fadeSides.any ? (\n        <defs>\n          {isGradient ? (\n            <linearGradient id={gradientId} {...gradientVector}>\n              <stop offset=\"0%\" stopColor={gradientStart ?? stroke} />\n              <stop offset=\"100%\" stopColor={gradientEnd} />\n            </linearGradient>\n          ) : null}\n          {fadeSides.any ? (\n            <TrendLineFadeMask\n              fadeLength={fadeLength}\n              id={maskId}\n              pad={strokeWidth + 2}\n              pixels={pixels}\n              sides={fadeSides}\n            />\n          ) : null}\n        </defs>\n      ) : null}\n      <line\n        fill=\"none\"\n        mask={fadeSides.any ? `url(#${maskId})` : undefined}\n        stroke={isGradient ? `url(#${gradientId})` : stroke}\n        strokeDasharray={strokeStyle === \"dashed\" ? strokeDasharray : undefined}\n        strokeLinecap=\"round\"\n        strokeWidth={strokeWidth}\n        x1={pixels.x1}\n        x2={pixels.x2}\n        y1={pixels.y1}\n        y2={pixels.y2}\n      />\n    </m.g>\n  );\n}\n\nTrendLine.displayName = \"TrendLine\";\n\nexport default TrendLine;\n",
      "type": "registry:component",
      "target": "components/charts/trend-line.tsx"
    },
    {
      "path": "src/charts/trend-line-utils.ts",
      "content": "export interface TrendPoint {\n  x: number;\n  y: number;\n}\n\nexport interface LinearRegression {\n  slope: number;\n  intercept: number;\n}\n\n/** Fitted segment endpoints in data space (regression x units → value). */\nexport interface TrendSegment {\n  x1: number;\n  y1: number;\n  x2: number;\n  y2: number;\n}\n\n/**\n * Ordinary least-squares fit `y = slope * x + intercept`.\n * Non-finite points are skipped. Returns `null` for fewer than two finite\n * points or zero x-variance (vertical / single-x data).\n *\n * Mean-centered so large x values (epoch ms) don't lose precision.\n */\nexport function computeLinearRegression(\n  points: TrendPoint[]\n): LinearRegression | null {\n  let n = 0;\n  let sumX = 0;\n  let sumY = 0;\n  for (const { x, y } of points) {\n    if (Number.isFinite(x) && Number.isFinite(y)) {\n      n += 1;\n      sumX += x;\n      sumY += y;\n    }\n  }\n  if (n < 2) {\n    return null;\n  }\n  const meanX = sumX / n;\n  const meanY = sumY / n;\n  let covXY = 0;\n  let varX = 0;\n  for (const { x, y } of points) {\n    if (Number.isFinite(x) && Number.isFinite(y)) {\n      const dx = x - meanX;\n      covXY += dx * (y - meanY);\n      varX += dx * dx;\n    }\n  }\n  if (varX === 0) {\n    return null;\n  }\n  const slope = covXY / varX;\n  return { slope, intercept: meanY - slope * meanX };\n}\n\n/** Regression line evaluated at the min / max finite x of `points`. */\nexport function computeTrendSegment(points: TrendPoint[]): TrendSegment | null {\n  const fit = computeLinearRegression(points);\n  if (!fit) {\n    return null;\n  }\n  let minX = Number.POSITIVE_INFINITY;\n  let maxX = Number.NEGATIVE_INFINITY;\n  for (const { x, y } of points) {\n    if (Number.isFinite(x) && Number.isFinite(y)) {\n      minX = Math.min(minX, x);\n      maxX = Math.max(maxX, x);\n    }\n  }\n  return {\n    x1: minX,\n    y1: fit.slope * minX + fit.intercept,\n    x2: maxX,\n    y2: fit.slope * maxX + fit.intercept,\n  };\n}\n\n/** Linear blend between two segments (`t` in 0…1). */\nexport function interpolateTrendSegment(\n  from: TrendSegment,\n  to: TrendSegment,\n  t: number\n): TrendSegment {\n  return {\n    x1: from.x1 + (to.x1 - from.x1) * t,\n    y1: from.y1 + (to.y1 - from.y1) * t,\n    x2: from.x2 + (to.x2 - from.x2) * t,\n    y2: from.y2 + (to.y2 - from.y2) * t,\n  };\n}\n",
      "type": "registry:component",
      "target": "components/charts/trend-line-utils.ts"
    }
  ]
}