{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "band",
  "type": "registry:component",
  "title": "Band",
  "description": "Shaded range between per-row upper and lower values on a line chart, with a Bollinger bands helper",
  "dependencies": [
    "d3-shape",
    "motion"
  ],
  "registryDependencies": [
    "@bklit/chart-context",
    "@bklit/line-chart",
    "@bklit/background"
  ],
  "files": [
    {
      "path": "src/charts/band.tsx",
      "content": "\"use client\";\n\nimport { type CurveFactory, curveLinear, curveNatural } from \"d3-shape\";\nimport { type ReactNode, useId, useMemo } from \"react\";\nimport {\n  type BandFadeEdges,\n  type BandFadeStop,\n  type BandSegment,\n  bandAreaPath,\n  bandEdgeClipPath,\n  bandEdgePath,\n  bandFadeStops,\n  bandPixelExtent,\n  resolveBandFadeSides,\n} from \"./band-geometry\";\nimport { chartCssVars, useChartStable, useYScale } from \"./chart-context\";\nimport { type PatternPresetId, renderPatternPreset } from \"./pattern-preset\";\nimport { useAnimatedBand } from \"./use-animated-band\";\n\nexport type { BandFadeEdges } from \"./band-geometry\";\n\nexport type BandFillType = \"solid\" | \"gradient\" | \"pattern\";\n\nexport interface BandStrokeProps {\n  /** Default: Band `stroke` ?? `fill`. */\n  stroke?: string;\n  /** Default: Band `strokeWidth`. */\n  strokeWidth?: number;\n  /** Default: Band `strokeDasharray`. */\n  strokeDasharray?: string;\n  /** Default: Band `strokeOpacity`. */\n  strokeOpacity?: number;\n}\n\nexport interface BandProps {\n  /** Data key for the band's upper edge. */\n  upperKey: string;\n  /** Data key for the band's lower edge. */\n  lowerKey: string;\n  /** Y-scale group id. Default: `\"left\"`. */\n  yAxisId?: string;\n  /**\n   * Tooltip row label. Default: `\"lowerKey – upperKey\"` (or the key when both\n   * edges share one key).\n   */\n  label?: string;\n  /**\n   * Add a `low – high` row (and dots on both edges) to `ChartTooltip`.\n   * Default: true\n   */\n  showInTooltip?: boolean;\n  /** Curve function. Default: curveNatural (same as Line). */\n  curve?: CurveFactory;\n  /** Band colour. Default: var(--chart-line-primary) */\n  fill?: string;\n  /** Default: `\"solid\"`. */\n  fillType?: BandFillType;\n  /** Solid opacity, or gradient opacity at the upper edge. Default: 0.15 */\n  fillOpacity?: number;\n  /**\n   * Fill wherever the upper key drops below the lower key (the two series\n   * cross) — e.g. actual below projection, this year behind last year. Uses\n   * the same `fillType`, opacities and pattern as `fill`. The colour switches\n   * exactly where the edges cross. Default: undefined (one fill throughout).\n   */\n  negativeFill?: string;\n  /** Gradient opacity at the lower edge. Default: 0 */\n  gradientToOpacity?: number;\n  /** Pattern preset when `fillType` is `\"pattern\"`. Default: `\"diagonal-up\"`. */\n  pattern?: PatternPresetId;\n  /** Default: `fill`. */\n  patternColor?: string;\n  patternScale?: number;\n  patternStrokeWidth?: number;\n  /** Opacity applied to the pattern fill. Default: 1 */\n  patternOpacity?: number;\n  /** Shared edge stroke colour. Default: `fill`. */\n  stroke?: string;\n  /** Default: 1 */\n  strokeWidth?: number;\n  /** Default: undefined (solid). */\n  strokeDasharray?: string;\n  /** Default: 1 */\n  strokeOpacity?: number;\n  /** `false` hides the top edge; an object overrides the shared stroke. */\n  upperStroke?: BandStrokeProps | false;\n  /** `false` hides the bottom edge; an object overrides the shared stroke. */\n  lowerStroke?: BandStrokeProps | false;\n  /**\n   * Fade fill and strokes to transparent at the given sides. Horizontal fades\n   * span the plot width; vertical fades span the band's own pixel extent.\n   * Default: false\n   */\n  fadeEdges?: BandFadeEdges;\n  /** Fraction (0–0.5) of the width / height each fade covers. Default: 0.15 */\n  fadeSize?: number;\n  className?: string;\n}\n\ninterface ResolvedBandStroke {\n  stroke: string;\n  strokeWidth: number;\n  strokeDasharray?: string;\n  strokeOpacity: number;\n}\n\nfunction resolveEdgeStroke(\n  override: BandStrokeProps | false | undefined,\n  base: ResolvedBandStroke\n): ResolvedBandStroke | null {\n  if (override === false) {\n    return null;\n  }\n  const resolved: ResolvedBandStroke = {\n    stroke: override?.stroke ?? base.stroke,\n    strokeWidth: override?.strokeWidth ?? base.strokeWidth,\n    strokeDasharray: override?.strokeDasharray ?? base.strokeDasharray,\n    strokeOpacity: override?.strokeOpacity ?? base.strokeOpacity,\n  };\n  return resolved.strokeWidth > 0 ? resolved : null;\n}\n\nfunction FadeMaskStops({ stops }: { stops: BandFadeStop[] }) {\n  return stops.map((stop, index) => (\n    <stop\n      key={index}\n      offset={stop.offset}\n      style={{ stopColor: \"white\", stopOpacity: stop.opacity }}\n    />\n  ));\n}\n\ninterface BandAreaFillStyle {\n  /** `\"gradient\"` only when the band has a vertical extent. */\n  fillType: BandFillType;\n  extent: { top: number; bottom: number } | null;\n  fillOpacity: number;\n  gradientToOpacity: number;\n  pattern: PatternPresetId;\n  /** Pattern colour override; falls back to the layer colour. */\n  patternColor?: string;\n  patternScale?: number;\n  patternStrokeWidth?: number;\n  patternOpacity: number;\n}\n\n/** The band area in one colour, with its own gradient / pattern defs. */\nfunction BandAreaFill({\n  d,\n  color,\n  clipPath,\n  style,\n}: {\n  d: string;\n  color: string;\n  clipPath?: string;\n  style: BandAreaFillStyle;\n}) {\n  const uniqueId = useId().replace(/:/g, \"\");\n  const paintId = `chart-band-paint-${uniqueId}`;\n  const { extent } = style;\n  const usesPattern = style.fillType === \"pattern\" && style.pattern !== \"none\";\n  const usesGradient = style.fillType === \"gradient\" && extent != null;\n\n  let paint: ReactNode = null;\n  let fill = color;\n  let opacity = style.fillOpacity;\n  if (usesPattern) {\n    paint = renderPatternPreset(style.pattern, paintId, {\n      color: style.patternColor ?? color,\n      scale: style.patternScale,\n      strokeWidth: style.patternStrokeWidth,\n    });\n    fill = `url(#${paintId})`;\n    opacity = style.patternOpacity;\n  } else if (usesGradient) {\n    paint = (\n      <linearGradient\n        gradientUnits=\"userSpaceOnUse\"\n        id={paintId}\n        x1={0}\n        x2={0}\n        y1={extent.top}\n        y2={extent.bottom}\n      >\n        <stop\n          offset={0}\n          style={{ stopColor: color, stopOpacity: style.fillOpacity }}\n        />\n        <stop\n          offset={1}\n          style={{ stopColor: color, stopOpacity: style.gradientToOpacity }}\n        />\n      </linearGradient>\n    );\n    fill = `url(#${paintId})`;\n    opacity = 1;\n  }\n\n  return (\n    <>\n      {paint ? <defs>{paint}</defs> : null}\n      <path clipPath={clipPath} d={d} fill={fill} fillOpacity={opacity} />\n    </>\n  );\n}\n\n/**\n * `negativeFill`: the area drawn twice, clipped above the lower edge in `fill`\n * and below it in `negativeFill`, so the colour flips where the edges cross.\n */\nfunction BandSplitFill({\n  d,\n  fill,\n  negativeFill,\n  segments,\n  curve,\n  innerHeight,\n  style,\n}: {\n  d: string;\n  fill: string;\n  negativeFill: string;\n  segments: BandSegment[];\n  curve: CurveFactory;\n  innerHeight: number;\n  style: BandAreaFillStyle;\n}) {\n  const uniqueId = useId().replace(/:/g, \"\");\n  const aboveId = `chart-band-above-${uniqueId}`;\n  const belowId = `chart-band-below-${uniqueId}`;\n  const clips = useMemo(() => {\n    // Far enough past the plot that a panned / overshooting band stays inside.\n    const far = Math.max(innerHeight, 1) * 3;\n    return {\n      above: bandEdgeClipPath(segments, \"lower\", \"above\", curve, far),\n      below: bandEdgeClipPath(segments, \"lower\", \"below\", curve, far),\n    };\n  }, [segments, curve, innerHeight]);\n\n  return (\n    <>\n      <defs>\n        <clipPath id={aboveId}>\n          <path d={clips.above} />\n        </clipPath>\n        <clipPath id={belowId}>\n          <path d={clips.below} />\n        </clipPath>\n      </defs>\n      <BandAreaFill\n        clipPath={`url(#${aboveId})`}\n        color={fill}\n        d={d}\n        style={style}\n      />\n      <BandAreaFill\n        clipPath={`url(#${belowId})`}\n        color={negativeFill}\n        d={d}\n        style={{ ...style, patternColor: undefined }}\n      />\n    </>\n  );\n}\n\n/** Phases where series strokes are drawn (matches `<Line>`). */\nfunction isBandVisiblePhase(phase: string): boolean {\n  return phase === \"revealing\" || phase === \"ready\" || phase === \"exitingReady\";\n}\n\nexport function Band({\n  upperKey,\n  lowerKey,\n  yAxisId,\n  // `label` / `showInTooltip` are read from props by the chart shell\n  // (`extractBandConfigs`) for tooltip rows.\n  curve = curveNatural,\n  fill = chartCssVars.linePrimary,\n  fillType = \"solid\",\n  fillOpacity = 0.15,\n  negativeFill,\n  gradientToOpacity = 0,\n  pattern = \"diagonal-up\",\n  patternColor,\n  patternScale,\n  patternStrokeWidth,\n  patternOpacity = 1,\n  stroke,\n  strokeWidth = 1,\n  strokeDasharray,\n  strokeOpacity = 1,\n  upperStroke,\n  lowerStroke,\n  fadeEdges = false,\n  fadeSize = 0.15,\n  className,\n}: BandProps) {\n  const {\n    renderData,\n    xScale,\n    innerWidth,\n    innerHeight,\n    xAccessor,\n    chartPhase,\n    yDomainTweenDuration,\n  } = useChartStable();\n  const yScale = useYScale(yAxisId);\n\n  // Same tween inputs as `<Line>` (animate + ready phase, yDomainTweenDuration)\n  // so band edges morph in lockstep with lines on data changes.\n  const displayed = useAnimatedBand({\n    chartPhase,\n    curve,\n    durationMs: yDomainTweenDuration,\n    enabled: chartPhase === \"ready\",\n    innerWidth,\n    lowerKey,\n    renderData,\n    upperKey,\n    xAccessor,\n    xScale,\n    yScale,\n  });\n  const { segments, polyline } = displayed;\n\n  const paths = useMemo(() => {\n    const pathCurve = polyline ? curveLinear : curve;\n    return {\n      area: bandAreaPath(segments, pathCurve),\n      upper: bandEdgePath(segments, \"upper\", pathCurve),\n      lower: bandEdgePath(segments, \"lower\", pathCurve),\n      extent: bandPixelExtent(segments),\n    };\n  }, [segments, polyline, curve]);\n\n  const uniqueId = useId().replace(/:/g, \"\");\n  const hMaskId = `chart-band-fade-x-${uniqueId}`;\n  const vMaskId = `chart-band-fade-y-${uniqueId}`;\n\n  if (!isBandVisiblePhase(chartPhase) || paths.area === \"\") {\n    return null;\n  }\n\n  const { extent } = paths;\n  const hasExtent = extent != null && extent.bottom - extent.top > 0;\n  const fadeSides = resolveBandFadeSides(fadeEdges);\n  const fadeX = fadeSides.horizontal && innerWidth > 0;\n  const fadeY = fadeSides.vertical && hasExtent;\n  const fillStyle: BandAreaFillStyle = {\n    extent: hasExtent ? extent : null,\n    fillOpacity,\n    fillType,\n    gradientToOpacity,\n    pattern,\n    patternColor,\n    patternOpacity,\n    patternScale,\n    patternStrokeWidth,\n  };\n\n  const baseStroke: ResolvedBandStroke = {\n    stroke: stroke ?? fill,\n    strokeWidth,\n    strokeDasharray,\n    strokeOpacity,\n  };\n  const upperEdge = resolveEdgeStroke(upperStroke, baseStroke);\n  const lowerEdge = resolveEdgeStroke(lowerStroke, baseStroke);\n\n  // Generous user-space mask region: series extend past the plot while an\n  // `xDomain` viewport pans; the gradients pad their end stops beyond it.\n  const maskRegion = {\n    height: innerHeight * 3,\n    maskUnits: \"userSpaceOnUse\" as const,\n    width: innerWidth * 3,\n    x: -innerWidth,\n    y: -innerHeight,\n  };\n  const maskRect = {\n    height: maskRegion.height,\n    width: maskRegion.width,\n    x: maskRegion.x,\n    y: maskRegion.y,\n  };\n\n  const content = (\n    <>\n      {negativeFill ? (\n        <BandSplitFill\n          curve={polyline ? curveLinear : curve}\n          d={paths.area}\n          fill={fill}\n          innerHeight={innerHeight}\n          negativeFill={negativeFill}\n          segments={segments}\n          style={fillStyle}\n        />\n      ) : (\n        <BandAreaFill color={fill} d={paths.area} style={fillStyle} />\n      )}\n      {lowerEdge ? (\n        <path\n          d={paths.lower}\n          fill=\"none\"\n          stroke={lowerEdge.stroke}\n          strokeDasharray={lowerEdge.strokeDasharray}\n          strokeLinecap=\"round\"\n          strokeOpacity={lowerEdge.strokeOpacity}\n          strokeWidth={lowerEdge.strokeWidth}\n        />\n      ) : null}\n      {upperEdge ? (\n        <path\n          d={paths.upper}\n          fill=\"none\"\n          stroke={upperEdge.stroke}\n          strokeDasharray={upperEdge.strokeDasharray}\n          strokeLinecap=\"round\"\n          strokeOpacity={upperEdge.strokeOpacity}\n          strokeWidth={upperEdge.strokeWidth}\n        />\n      ) : null}\n    </>\n  );\n\n  return (\n    // biome-ignore lint/a11y/noAriaHiddenOnFocusable: decorative band\n    <g\n      aria-hidden=\"true\"\n      className={className ?? \"chart-band\"}\n      pointerEvents=\"none\"\n    >\n      <defs>\n        {fadeX ? (\n          <>\n            <linearGradient\n              gradientUnits=\"userSpaceOnUse\"\n              id={`${hMaskId}-gradient`}\n              x1={0}\n              x2={innerWidth}\n              y1={0}\n              y2={0}\n            >\n              <FadeMaskStops\n                stops={bandFadeStops(fadeSides.left, fadeSides.right, fadeSize)}\n              />\n            </linearGradient>\n            <mask id={hMaskId} {...maskRegion}>\n              <rect fill={`url(#${hMaskId}-gradient)`} {...maskRect} />\n            </mask>\n          </>\n        ) : null}\n        {fadeY && extent ? (\n          <>\n            <linearGradient\n              gradientUnits=\"userSpaceOnUse\"\n              id={`${vMaskId}-gradient`}\n              x1={0}\n              x2={0}\n              y1={extent.top}\n              y2={extent.bottom}\n            >\n              <FadeMaskStops\n                stops={bandFadeStops(fadeSides.top, fadeSides.bottom, fadeSize)}\n              />\n            </linearGradient>\n            <mask id={vMaskId} {...maskRegion}>\n              <rect fill={`url(#${vMaskId}-gradient)`} {...maskRect} />\n            </mask>\n          </>\n        ) : null}\n      </defs>\n      <g mask={fadeX ? `url(#${hMaskId})` : undefined}>\n        <g mask={fadeY ? `url(#${vMaskId})` : undefined}>{content}</g>\n      </g>\n    </g>\n  );\n}\n\nBand.displayName = \"Band\";\n\nexport default Band;\n",
      "type": "registry:component",
      "target": "components/charts/band.tsx"
    },
    {
      "path": "src/charts/band-geometry.ts",
      "content": "import { type CurveFactory, area as d3Area, line as d3Line } from \"d3-shape\";\nimport {\n  flattenSeriesPath,\n  interpolateSeriesPathPoints,\n  type SeriesPathPoint,\n  samplePolylineY,\n} from \"./series-path-utils\";\n\n/** One plotted row of a band, in pixels. */\nexport interface BandPoint {\n  x: number;\n  upper: number;\n  lower: number;\n  key: string;\n}\n\n/** Contiguous run of defined rows (gaps split the band into segments). */\nexport type BandSegment = BandPoint[];\n\nfunction finiteNumber(value: unknown): value is number {\n  return typeof value === \"number\" && Number.isFinite(value);\n}\n\n/**\n * Pixel band segments. Rows where either edge is null / undefined / NaN end\n * the current segment (e.g. Bollinger warm-up rows).\n */\nexport function computeBandSegments(\n  data: Record<string, unknown>[],\n  xAccessor: (datum: Record<string, unknown>) => Date,\n  xScale: (value: Date) => number | undefined,\n  yScale: (value: number) => number | undefined,\n  upperKey: string,\n  lowerKey: string\n): BandSegment[] {\n  const segments: BandSegment[] = [];\n  let current: BandSegment = [];\n\n  data.forEach((datum, index) => {\n    const upper = datum[upperKey];\n    const lower = datum[lowerKey];\n    if (!(finiteNumber(upper) && finiteNumber(lower))) {\n      if (current.length > 0) {\n        segments.push(current);\n        current = [];\n      }\n      return;\n    }\n    const xValue = xAccessor(datum);\n    current.push({\n      x: xScale(xValue) ?? 0,\n      upper: yScale(upper) ?? 0,\n      lower: yScale(lower) ?? 0,\n      key: String(xValue.getTime?.() ?? index),\n    });\n  });\n\n  if (current.length > 0) {\n    segments.push(current);\n  }\n  return segments;\n}\n\nfunction edgePoints(\n  segment: BandSegment,\n  edge: \"upper\" | \"lower\"\n): SeriesPathPoint[] {\n  return segment.map((point) => ({\n    x: point.x,\n    y: point[edge],\n    key: point.key,\n  }));\n}\n\n/** Closed area path between the edges, one sub-path per segment. */\nexport function bandAreaPath(\n  segments: BandSegment[],\n  curve: CurveFactory\n): string {\n  const generator = d3Area<BandPoint>()\n    .x((point) => point.x)\n    .y0((point) => point.lower)\n    .y1((point) => point.upper)\n    .curve(curve);\n  return segments\n    .filter((segment) => segment.length > 1)\n    .map((segment) => generator(segment) ?? \"\")\n    .join(\"\");\n}\n\n/** Open stroke path along one edge, one sub-path per segment. */\nexport function bandEdgePath(\n  segments: BandSegment[],\n  edge: \"upper\" | \"lower\",\n  curve: CurveFactory\n): string {\n  const generator = d3Line<BandPoint>()\n    .x((point) => point.x)\n    .y((point) => point[edge])\n    .curve(curve);\n  return segments\n    .filter((segment) => segment.length > 1)\n    .map((segment) => generator(segment) ?? \"\")\n    .join(\"\");\n}\n\n/**\n * Clip region on one side of a band edge: each segment's edge curve, closed\n * `far` px off the top (`\"above\"`) or bottom (`\"below\"`) of the plot. Used by\n * `negativeFill` to split the fill where the upper key crosses the lower key.\n */\nexport function bandEdgeClipPath(\n  segments: BandSegment[],\n  edge: \"upper\" | \"lower\",\n  side: \"above\" | \"below\",\n  curve: CurveFactory,\n  far: number\n): string {\n  const generator = d3Line<BandPoint>()\n    .x((point) => point.x)\n    .y((point) => point[edge])\n    .curve(curve);\n  const y = side === \"above\" ? -far : far;\n  return segments\n    .filter((segment) => segment.length > 1)\n    .map((segment) => {\n      const path = generator(segment);\n      const first = segment[0];\n      const last = segment.at(-1);\n      if (!(path && first && last)) {\n        return \"\";\n      }\n      return `${path}L${last.x},${y}L${first.x},${y}Z`;\n    })\n    .join(\"\");\n}\n\n/** Vertical pixel extent covered by both edges (top < bottom in SVG space). */\nexport function bandPixelExtent(\n  segments: BandSegment[]\n): { top: number; bottom: number } | null {\n  let top = Number.POSITIVE_INFINITY;\n  let bottom = Number.NEGATIVE_INFINITY;\n  for (const segment of segments) {\n    for (const point of segment) {\n      top = Math.min(top, point.upper, point.lower);\n      bottom = Math.max(bottom, point.upper, point.lower);\n    }\n  }\n  return Number.isFinite(top) ? { top, bottom } : null;\n}\n\n/** Dense polylines of both edges, all segments concatenated and sorted by x. */\nexport interface BandEdgePolylines {\n  upper: SeriesPathPoint[];\n  lower: SeriesPathPoint[];\n}\n\nexport function flattenBandEdges(\n  segments: BandSegment[],\n  curve: CurveFactory,\n  alreadyPolyline: boolean\n): BandEdgePolylines {\n  const flatten = (edge: \"upper\" | \"lower\") =>\n    segments\n      .flatMap((segment) => {\n        const points = edgePoints(segment, edge);\n        return alreadyPolyline ? points : flattenSeriesPath(points, curve);\n      })\n      .sort((a, b) => a.x - b.x);\n  return { upper: flatten(\"upper\"), lower: flatten(\"lower\") };\n}\n\n/**\n * Vertical morph (same approach as `morphSeriesPolylines`): both edges are\n * sampled on a shared x grid per target segment and only y is interpolated,\n * so the band rises and falls into shape alongside morphing lines. Result is\n * a polyline — render with `curveLinear`.\n */\nexport function morphBandSegments(\n  from: BandEdgePolylines,\n  targets: BandSegment[],\n  curve: CurveFactory,\n  progress: number,\n  sampleSpacingPx = 2\n): BandSegment[] {\n  if (from.upper.length === 0 || from.lower.length === 0) {\n    return targets;\n  }\n  return targets.map((segment) => {\n    const first = segment[0];\n    const last = segment.at(-1);\n    if (!(first && last) || segment.length < 2) {\n      return segment;\n    }\n    const toUpper = flattenSeriesPath(edgePoints(segment, \"upper\"), curve);\n    const toLower = flattenSeriesPath(edgePoints(segment, \"lower\"), curve);\n    const span = last.x - first.x;\n    const count = Math.max(2, Math.ceil(span / sampleSpacingPx) + 1);\n    const result: BandSegment = new Array(count);\n    for (let index = 0; index < count; index++) {\n      const x = first.x + (span * index) / (count - 1);\n      const fromUpper = samplePolylineY(from.upper, x);\n      const fromLower = samplePolylineY(from.lower, x);\n      result[index] = {\n        x,\n        upper: fromUpper + (samplePolylineY(toUpper, x) - fromUpper) * progress,\n        lower: fromLower + (samplePolylineY(toLower, x) - fromLower) * progress,\n        key: \"\",\n      };\n    }\n    return result;\n  });\n}\n\n/**\n * Keyed slide (same approach as `interpolateSeriesPathPoints`) for viewport\n * changes on unchanged data, e.g. brush pan / resize.\n */\nexport function interpolateBandSegments(\n  from: BandSegment[],\n  targets: BandSegment[],\n  progress: number\n): BandSegment[] {\n  if (progress >= 1 || from.length === 0) {\n    return targets;\n  }\n  const fromUpper = from.flatMap((segment) => edgePoints(segment, \"upper\"));\n  const fromLower = from.flatMap((segment) => edgePoints(segment, \"lower\"));\n  return targets.map((segment) => {\n    const upper = interpolateSeriesPathPoints(\n      fromUpper,\n      edgePoints(segment, \"upper\"),\n      progress\n    );\n    const lower = interpolateSeriesPathPoints(\n      fromLower,\n      edgePoints(segment, \"lower\"),\n      progress\n    );\n    return upper.map((point, index) => ({\n      x: point.x,\n      upper: point.y,\n      lower: lower[index]?.y ?? point.y,\n      key: point.key,\n    }));\n  });\n}\n\n/** Signature of both edge values per row (ignores scales / width). */\nexport function bandDataSignature(\n  renderData: Record<string, unknown>[],\n  xAccessor: (datum: Record<string, unknown>) => Date,\n  upperKey: string,\n  lowerKey: string\n): string {\n  return renderData\n    .map((datum) => {\n      const upper = datum[upperKey];\n      const lower = datum[lowerKey];\n      return `${xAccessor(datum).getTime()}:${finiteNumber(upper) ? upper : \"\"}:${finiteNumber(lower) ? lower : \"\"}`;\n    })\n    .join(\",\");\n}\n\nexport type BandFadeEdges =\n  | boolean\n  | \"left\"\n  | \"right\"\n  | { top?: boolean; right?: boolean; bottom?: boolean; left?: boolean };\n\nexport interface BandFadeSides {\n  top: boolean;\n  right: boolean;\n  bottom: boolean;\n  left: boolean;\n  horizontal: boolean;\n  vertical: boolean;\n}\n\nexport function resolveBandFadeSides(\n  fade: BandFadeEdges | undefined\n): BandFadeSides {\n  let sides = { top: false, right: false, bottom: false, left: false };\n  if (fade === true) {\n    sides = { top: true, right: true, bottom: true, left: true };\n  } else if (fade === \"left\") {\n    sides.left = true;\n  } else if (fade === \"right\") {\n    sides.right = true;\n  } else if (fade && typeof fade === \"object\") {\n    sides = {\n      top: fade.top === true,\n      right: fade.right === true,\n      bottom: fade.bottom === true,\n      left: fade.left === true,\n    };\n  }\n  return {\n    ...sides,\n    horizontal: sides.left || sides.right,\n    vertical: sides.top || sides.bottom,\n  };\n}\n\nexport interface BandFadeStop {\n  offset: number;\n  opacity: number;\n}\n\n/**\n * Mask stops along one axis: transparent at faded ends, opaque in between.\n * `size` is the fraction (0–0.5) of the axis each fade occupies.\n */\nexport function bandFadeStops(\n  startFaded: boolean,\n  endFaded: boolean,\n  size: number\n): BandFadeStop[] {\n  const span = Math.min(0.5, Math.max(0, size));\n  return [\n    { offset: 0, opacity: startFaded ? 0 : 1 },\n    { offset: span, opacity: 1 },\n    { offset: 1 - span, opacity: 1 },\n    { offset: 1, opacity: endFaded ? 0 : 1 },\n  ];\n}\n",
      "type": "registry:component",
      "target": "components/charts/band-geometry.ts"
    },
    {
      "path": "src/charts/use-animated-band.ts",
      "content": "\"use client\";\n\nimport type { CurveFactory } from \"d3-shape\";\nimport { animate, useReducedMotion } from \"motion/react\";\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport {\n  type BandSegment,\n  bandDataSignature,\n  computeBandSegments,\n  flattenBandEdges,\n  interpolateBandSegments,\n  morphBandSegments,\n} from \"./band-geometry\";\nimport { LINE_LOADING_PULSE_EASE } from \"./line-loading-timing\";\n\nexport interface UseAnimatedBandOptions {\n  renderData: Record<string, unknown>[];\n  xAccessor: (datum: Record<string, unknown>) => Date;\n  xScale: (value: Date) => number | undefined;\n  yScale: (value: number) => number | undefined;\n  upperKey: string;\n  lowerKey: string;\n  curve: CurveFactory;\n  chartPhase: string;\n  durationMs: number;\n  innerWidth: number;\n  enabled: boolean;\n}\n\n/** Band currently on screen. `polyline` frames render with `curveLinear`. */\nexport interface DisplayedBand {\n  segments: BandSegment[];\n  polyline: boolean;\n}\n\ntype LatestBandInputs = Pick<\n  UseAnimatedBandOptions,\n  | \"renderData\"\n  | \"xAccessor\"\n  | \"xScale\"\n  | \"yScale\"\n  | \"upperKey\"\n  | \"lowerKey\"\n  | \"curve\"\n>;\n\nfunction segmentsFor(inputs: LatestBandInputs): BandSegment[] {\n  return computeBandSegments(\n    inputs.renderData,\n    inputs.xAccessor,\n    inputs.xScale,\n    inputs.yScale,\n    inputs.upperKey,\n    inputs.lowerKey\n  );\n}\n\n/**\n * Band counterpart of `useAnimatedSeriesPath`: same trigger signatures,\n * duration (`yDomainTweenDuration`), easing and morph-vs-slide rule, so a\n * band tweens frame-for-frame with the `<Line>`s it is composed with.\n */\nexport function useAnimatedBand({\n  renderData,\n  xAccessor,\n  xScale,\n  yScale,\n  upperKey,\n  lowerKey,\n  curve,\n  chartPhase,\n  durationMs,\n  innerWidth,\n  enabled,\n}: UseAnimatedBandOptions): DisplayedBand {\n  const reducedMotion = useReducedMotion();\n  const [animatedBand, setAnimatedBand] = useState<DisplayedBand | null>(null);\n  const displayedRef = useRef<DisplayedBand | null>(null);\n  const animatingRef = useRef(false);\n\n  const xScaleDomain = useMemo(() => {\n    const scaleWithDomain = xScale as { domain?: () => [Date, Date] };\n    return scaleWithDomain.domain?.() ?? [new Date(0), new Date(0)];\n  }, [xScale]);\n\n  const dataSignature = useMemo(\n    () => bandDataSignature(renderData, xAccessor, upperKey, lowerKey),\n    [renderData, xAccessor, upperKey, lowerKey]\n  );\n\n  const transitionSignature = `${innerWidth}|${xScaleDomain[0]?.getTime?.() ?? 0}|${xScaleDomain[1]?.getTime?.() ?? 0}|${dataSignature}`;\n\n  const targetSegments = useMemo(\n    () =>\n      segmentsFor({\n        curve,\n        lowerKey,\n        renderData,\n        upperKey,\n        xAccessor,\n        xScale,\n        yScale,\n      }),\n    [renderData, xAccessor, xScale, yScale, upperKey, lowerKey, curve]\n  );\n\n  const prevTransitionSignatureRef = useRef(transitionSignature);\n  const prevDataSignatureRef = useRef(dataSignature);\n\n  // Live inputs for the running tween — the y-domain tween rebuilds `yScale`\n  // every frame, so these must not be effect deps (see useAnimatedSeriesPath).\n  const latestRef = useRef<LatestBandInputs>({\n    renderData,\n    xAccessor,\n    xScale,\n    yScale,\n    upperKey,\n    lowerKey,\n    curve,\n  });\n  // Synced in a layout effect declared before the tween effect (not during\n  // render) so `renderFrame(0)` and every animation frame see this commit's\n  // inputs.\n  useLayoutEffect(() => {\n    latestRef.current = {\n      renderData,\n      xAccessor,\n      xScale,\n      yScale,\n      upperKey,\n      lowerKey,\n      curve,\n    };\n  });\n\n  const shouldAnimate =\n    enabled &&\n    !reducedMotion &&\n    chartPhase === \"ready\" &&\n    durationMs > 0 &&\n    renderData.length > 0;\n\n  // Drop a stale tween frame as soon as animation is no longer allowed —\n  // adjusted during render rather than via setState in the effect below.\n  if (!shouldAnimate && animatedBand !== null) {\n    setAnimatedBand(null);\n  }\n\n  // Scales / targets are read live via latestRef: only a new signature should\n  // restart the tween (a dep on per-frame `yScale` would stop it each frame).\n  useLayoutEffect(() => {\n    const computeLatestTarget = () => segmentsFor(latestRef.current);\n\n    const dataChanged = prevDataSignatureRef.current !== dataSignature;\n    prevDataSignatureRef.current = dataSignature;\n\n    if (!shouldAnimate) {\n      animatingRef.current = false;\n      displayedRef.current = {\n        segments: computeLatestTarget(),\n        polyline: false,\n      };\n      prevTransitionSignatureRef.current = transitionSignature;\n      return;\n    }\n\n    if (prevTransitionSignatureRef.current === transitionSignature) {\n      return;\n    }\n    prevTransitionSignatureRef.current = transitionSignature;\n\n    const from = displayedRef.current ?? {\n      segments: computeLatestTarget(),\n      polyline: false,\n    };\n    if (from.segments.length === 0) {\n      displayedRef.current = {\n        segments: computeLatestTarget(),\n        polyline: false,\n      };\n      return;\n    }\n\n    animatingRef.current = true;\n    const morph = dataChanged || from.polyline;\n    const fromPolylines = morph\n      ? flattenBandEdges(from.segments, latestRef.current.curve, from.polyline)\n      : null;\n\n    const renderFrame = (progress: number) => {\n      const currentTarget = computeLatestTarget();\n      const next: DisplayedBand = fromPolylines\n        ? {\n            segments: morphBandSegments(\n              fromPolylines,\n              currentTarget,\n              latestRef.current.curve,\n              progress\n            ),\n            polyline: true,\n          }\n        : {\n            segments: interpolateBandSegments(\n              from.segments,\n              currentTarget,\n              progress\n            ),\n            polyline: false,\n          };\n      displayedRef.current = next;\n      setAnimatedBand(next);\n    };\n    renderFrame(0);\n\n    const control = animate(0, 1, {\n      duration: durationMs / 1000,\n      ease: [...LINE_LOADING_PULSE_EASE],\n      onUpdate: renderFrame,\n      onComplete: () => {\n        animatingRef.current = false;\n        displayedRef.current = {\n          segments: computeLatestTarget(),\n          polyline: false,\n        };\n        setAnimatedBand(null);\n      },\n    });\n\n    return () => {\n      control.stop();\n      animatingRef.current = false;\n    };\n  }, [\n    transitionSignature,\n    dataSignature,\n    shouldAnimate,\n    chartPhase,\n    durationMs,\n    enabled,\n    reducedMotion,\n    renderData.length,\n  ]);\n\n  // After the tween effect: a data change needs the previously displayed\n  // segments as its `from`, not the new target.\n  useEffect(() => {\n    if (!animatingRef.current) {\n      displayedRef.current = { segments: targetSegments, polyline: false };\n    }\n  }, [targetSegments]);\n\n  return animatedBand ?? { segments: targetSegments, polyline: false };\n}\n",
      "type": "registry:component",
      "target": "components/charts/use-animated-band.ts"
    },
    {
      "path": "src/charts/bollinger.ts",
      "content": "export interface BollingerBandsOptions {\n  /** Numeric key to compute bands for. */\n  dataKey: string;\n  /** Rolling window length. Default: 20 */\n  period?: number;\n  /** Standard deviations above / below the SMA. Default: 2 */\n  multiplier?: number;\n  /**\n   * Minimum finite values in the window needed to emit a row (pandas\n   * `min_periods`). Clamped to [1, `period`]. Default: `period` — a gap until\n   * the window fills. Use `1` to warm up from the first row over a partial\n   * window.\n   */\n  minPeriods?: number;\n  /** Default: `${dataKey}Upper` */\n  upperKey?: string;\n  /** Default: `${dataKey}Lower` */\n  lowerKey?: string;\n  /** Default: `${dataKey}Sma` */\n  middleKey?: string;\n}\n\n/**\n * Adds Bollinger band keys to each row: rolling SMA over the last `period`\n * rows ± `multiplier` × population standard deviation, computed over the\n * finite numeric values in that window. Rows whose window has fewer than\n * `minPeriods` such values (by default: before the window fills, or when it\n * contains a non-numeric value) get `null` for all three keys, which\n * `<Band>` / `<Line>` treat as gaps.\n */\nexport function withBollingerBands<T extends Record<string, unknown>>(\n  data: T[],\n  options: BollingerBandsOptions\n): (T & Record<string, number | null>)[] {\n  const {\n    dataKey,\n    period = 20,\n    multiplier = 2,\n    upperKey = `${dataKey}Upper`,\n    lowerKey = `${dataKey}Lower`,\n    middleKey = `${dataKey}Sma`,\n    minPeriods = period,\n  } = options;\n  const windowSize = Math.max(1, Math.floor(period));\n  const requiredCount = Math.min(\n    windowSize,\n    Math.max(\n      1,\n      Number.isFinite(minPeriods) ? Math.floor(minPeriods) : windowSize\n    )\n  );\n\n  return data.map((row, index) => {\n    let upper: number | null = null;\n    let lower: number | null = null;\n    let middle: number | null = null;\n\n    const values: number[] = [];\n    for (\n      let offset = Math.max(0, index - windowSize + 1);\n      offset <= index;\n      offset++\n    ) {\n      const value = data[offset]?.[dataKey];\n      if (typeof value === \"number\" && Number.isFinite(value)) {\n        values.push(value);\n      }\n    }\n    if (values.length >= requiredCount) {\n      const count = values.length;\n      const mean = values.reduce((sum, value) => sum + value, 0) / count;\n      const variance =\n        values.reduce((sum, value) => sum + (value - mean) ** 2, 0) / count;\n      const spread = multiplier * Math.sqrt(variance);\n      middle = mean;\n      upper = mean + spread;\n      lower = mean - spread;\n    }\n\n    return {\n      ...row,\n      [upperKey]: upper,\n      [lowerKey]: lower,\n      [middleKey]: middle,\n    } as T & Record<string, number | null>;\n  });\n}\n",
      "type": "registry:component",
      "target": "components/charts/bollinger.ts"
    }
  ]
}