{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-crosshair",
  "type": "registry:component",
  "title": "Chart Crosshair",
  "description": "Finance-style crosshair with a y-axis value pill that fades nearby YAxis ticks",
  "dependencies": [
    "@number-flow/react",
    "motion"
  ],
  "registryDependencies": [
    "@bklit/chart-context",
    "@bklit/chart-tooltip",
    "@bklit/chart-stat-flow",
    "@bklit/y-axis"
  ],
  "files": [
    {
      "path": "src/charts/chart-crosshair.tsx",
      "content": "\"use client\";\n\nimport NumberFlow from \"@number-flow/react\";\nimport { m, useReducedMotion, useSpring } from \"motion/react\";\nimport { memo, useEffect, useMemo, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { type SpringConfig, useChartConfig } from \"./chart-config-context\";\nimport {\n  chartCssVars,\n  useChartHoverStore,\n  useChartPortalContainer,\n  useChartStable,\n} from \"./chart-context\";\nimport {\n  type ChartStatFlowFormat,\n  useNumberFlowElementReady,\n} from \"./chart-stat-flow\";\nimport { setCrosshairY } from \"./crosshair-store\";\nimport { normalizeYAxisId } from \"./y-axis-scales\";\n\nexport interface ChartCrosshairProps {\n  /** Draw the horizontal line at the cursor's y. Default: `true` */\n  horizontal?: boolean;\n  /** Draw the vertical line. Default: `true` */\n  vertical?: boolean;\n  /**\n   * Vertical line snaps to the hovered column (the tooltip's x) instead of\n   * following the cursor freely. Default: `true`\n   */\n  snap?: boolean;\n  /** Axis whose scale converts the cursor y into the pill value. Default: `\"left\"` */\n  yAxisId?: string | number;\n  /** Which plot edge the value pill sits on. Default: `\"right\"` for the right axis, else `\"left\"`. */\n  side?: \"left\" | \"right\";\n  /** Show the y-value pill on the axis. Default: `true` */\n  showValueLabel?: boolean;\n  /**\n   * Roll digits with NumberFlow as the value changes. Uses `format` / `prefix`\n   * / `suffix` (`formatValue` is ignored). Default: `false`\n   */\n  numberFlow?: boolean;\n  /** `Intl.NumberFormat` options for the pill. Default: up to 2 fraction digits. */\n  format?: ChartStatFlowFormat;\n  /** Text before the value (e.g. `\"$\"`). */\n  prefix?: string;\n  /** Text after the value (e.g. `\"%\"`). */\n  suffix?: string;\n  /** Custom formatter for the static (non-NumberFlow) pill. */\n  formatValue?: (value: number) => string;\n  /** Line colour. Default: `var(--chart-crosshair)` */\n  stroke?: string;\n  /** Line dash pattern. Default: `\"3,3\"` */\n  strokeDasharray?: string;\n  /** Line width. Default: `1` */\n  strokeWidth?: number;\n  /** Spring for the lines and pill. Default: the chart's tooltip spring. */\n  springConfig?: SpringConfig;\n}\n\ntype Spring = ReturnType<typeof useSpring>;\n\nconst DEFAULT_FORMAT: ChartStatFlowFormat = { maximumFractionDigits: 2 };\n\n/**\n * Pill offset from the plot edge: its text lines up with the `YAxis` labels\n * (8px gutter) and the 16px padding overlaps the plot.\n */\nconst PILL_TEXT_INSET = 8 - 16;\n\n/**\n * Minimum gap (ms) between NumberFlow value updates. Each update starts a\n * digit animation; updating on every pointer move restarts them every frame.\n */\nconst NUMBER_FLOW_UPDATE_MS = 120;\n\n/**\n * Shorter than NumberFlow's default (~900ms): a crosshair value changes many\n * times a second, and long spins pile up overlapping digit animations.\n */\nconst NUMBER_FLOW_TIMING: EffectTiming = {\n  duration: 350,\n  easing: \"cubic-bezier(0.23, 1, 0.32, 1)\",\n};\n\nfunction drive(value: Spring, target: number, instant: boolean) {\n  if (instant) {\n    value.jump(target);\n  } else {\n    value.set(target);\n  }\n}\n\n/**\n * Finance-style crosshair: a horizontal line that tracks the cursor's y, with\n * the axis value in a pill styled like the x-axis date ticker, and a vertical\n * line on the hovered column. A `YAxis` on the same axis fades the ticks the\n * pill covers. Pair with `<ChartTooltip showCrosshair={false} />`.\n *\n * Pointer moves never re-render React: the lines and pill follow motion\n * values, the static label is written to the DOM, and only NumberFlow (when\n * enabled) re-renders, throttled.\n */\nexport function ChartCrosshair(props: ChartCrosshairProps) {\n  const { containerRef } = useChartStable();\n  const container = useChartPortalContainer(containerRef);\n  if (!container) {\n    return null;\n  }\n  return <ChartCrosshairInner {...props} container={container} />;\n}\n\nChartCrosshair.displayName = \"ChartCrosshair\";\n\nconst ChartCrosshairInner = memo(function ChartCrosshairInner({\n  container,\n  yAxisId,\n  horizontal = true,\n  vertical = true,\n  snap = true,\n  side,\n  showValueLabel = true,\n  numberFlow = false,\n  format = DEFAULT_FORMAT,\n  prefix,\n  suffix,\n  formatValue,\n  stroke = chartCssVars.crosshair,\n  strokeDasharray = \"3,3\",\n  strokeWidth = 1,\n  springConfig,\n}: ChartCrosshairProps & { container: HTMLDivElement }) {\n  const { margin, innerWidth, innerHeight, yScales, yScale } = useChartStable();\n  const hoverStore = useChartHoverStore();\n  const { tooltipSpring } = useChartConfig();\n  const reduceMotion = useReducedMotion() === true;\n  const numberFlowReady = useNumberFlowElementReady();\n  const spring = springConfig ?? tooltipSpring;\n\n  const axisId = normalizeYAxisId(yAxisId);\n  const scale = yScales[axisId] ?? yScale;\n  const resolvedSide = side ?? (axisId === \"right\" ? \"right\" : \"left\");\n  const showPill = horizontal && showValueLabel;\n  const useFlow = showPill && numberFlow && numberFlowReady;\n\n  const springX = useSpring(0, spring);\n  const springY = useSpring(0, spring);\n  const rootRef = useRef<HTMLDivElement>(null);\n  const labelRef = useRef<HTMLSpanElement>(null);\n  const [flowValue, setFlowValue] = useState(0);\n\n  const formatLabel = useMemo(() => {\n    if (formatValue) {\n      return formatValue;\n    }\n    const intl = new Intl.NumberFormat(undefined, format);\n    return (value: number) =>\n      `${prefix ?? \"\"}${intl.format(value)}${suffix ?? \"\"}`;\n  }, [formatValue, format, prefix, suffix]);\n\n  // Everything the pointer handler reads, kept current without re-binding.\n  const latest = {\n    scale,\n    margin,\n    innerWidth,\n    innerHeight,\n    snap,\n    axisId,\n    showPill,\n    useFlow,\n    reduceMotion,\n    formatLabel,\n  };\n  const live = useRef(latest);\n  live.current = latest;\n\n  useEffect(() => {\n    let rect: DOMRect | null = null;\n    let visible = false;\n    let lastLabel = \"\";\n    let lastFlowAt = 0;\n    let flowTimer: ReturnType<typeof setTimeout> | undefined;\n    let pendingFlow: number | null = null;\n\n    const snappedX = () => hoverStore?.getSnapshot().tooltipData?.x ?? null;\n\n    const flushFlow = () => {\n      flowTimer = undefined;\n      if (pendingFlow !== null) {\n        lastFlowAt = performance.now();\n        setFlowValue(pendingFlow);\n        pendingFlow = null;\n      }\n    };\n\n    const setVisible = (next: boolean) => {\n      if (visible === next) {\n        return;\n      }\n      visible = next;\n      if (rootRef.current) {\n        rootRef.current.style.visibility = next ? \"visible\" : \"hidden\";\n      }\n      if (!next) {\n        lastLabel = \"\";\n        setCrosshairY(container, null);\n      }\n    };\n\n    const updateLabel = (y: number) => {\n      const s = live.current;\n      setCrosshairY(container, { y, axisId: s.axisId });\n      const value = s.scale.invert(y);\n      const label = s.formatLabel(value);\n      if (label === lastLabel) {\n        return;\n      }\n      lastLabel = label;\n      if (!s.useFlow) {\n        if (labelRef.current) {\n          labelRef.current.textContent = label;\n        }\n        return;\n      }\n      pendingFlow = value;\n      const wait = NUMBER_FLOW_UPDATE_MS - (performance.now() - lastFlowAt);\n      if (wait <= 0) {\n        flushFlow();\n      } else {\n        flowTimer ??= setTimeout(flushFlow, wait);\n      }\n    };\n\n    const onMove = (event: PointerEvent) => {\n      rect ??= container.getBoundingClientRect();\n      const s = live.current;\n      const x = event.clientX - rect.left - s.margin.left;\n      const y = event.clientY - rect.top - s.margin.top;\n      if (x < 0 || x > s.innerWidth || y < 0 || y > s.innerHeight) {\n        setVisible(false);\n        return;\n      }\n      // First frame on entry jumps, so the lines don't sweep in from 0.\n      const instant = !visible || s.reduceMotion;\n      drive(springY, y, instant);\n      drive(springX, s.snap ? (snappedX() ?? x) : x, instant);\n      setVisible(true);\n      if (s.showPill) {\n        updateLabel(y);\n      }\n    };\n\n    const onLeave = () => {\n      rect = null;\n      setVisible(false);\n    };\n    // Scrolling / resizing moves the container — re-measure on the next move.\n    const invalidate = () => {\n      rect = null;\n    };\n\n    // Snapped vertical line follows the hovered column without re-rendering.\n    const unsubscribe = hoverStore?.subscribe(() => {\n      if (!(visible && live.current.snap)) {\n        return;\n      }\n      const x = snappedX();\n      if (x !== null) {\n        drive(springX, x, live.current.reduceMotion);\n      }\n    });\n\n    container.addEventListener(\"pointermove\", onMove);\n    container.addEventListener(\"pointerleave\", onLeave);\n    window.addEventListener(\"scroll\", invalidate, {\n      capture: true,\n      passive: true,\n    });\n    window.addEventListener(\"resize\", invalidate, { passive: true });\n    return () => {\n      container.removeEventListener(\"pointermove\", onMove);\n      container.removeEventListener(\"pointerleave\", onLeave);\n      window.removeEventListener(\"scroll\", invalidate, { capture: true });\n      window.removeEventListener(\"resize\", invalidate);\n      unsubscribe?.();\n      clearTimeout(flowTimer);\n      setCrosshairY(container, null);\n    };\n  }, [container, hoverStore, springX, springY]);\n\n  return createPortal(\n    <div\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute inset-0\"\n      ref={rootRef}\n      style={{ visibility: \"hidden\" }}\n    >\n      <svg\n        aria-hidden=\"true\"\n        className=\"absolute inset-0 overflow-visible\"\n        height=\"100%\"\n        width=\"100%\"\n      >\n        <g\n          shapeRendering=\"crispEdges\"\n          stroke={stroke}\n          strokeDasharray={strokeDasharray}\n          strokeWidth={strokeWidth}\n          transform={`translate(${margin.left},${margin.top})`}\n        >\n          {horizontal && (\n            <m.line x1={0} x2={innerWidth} y1={springY} y2={springY} />\n          )}\n          {vertical && (\n            <m.line x1={springX} x2={springX} y1={0} y2={innerHeight} />\n          )}\n        </g>\n      </svg>\n      {showPill && (\n        <m.div\n          className=\"absolute z-50 w-max\"\n          style={{\n            top: margin.top,\n            y: springY,\n            ...(resolvedSide === \"right\"\n              ? { left: margin.left + innerWidth + PILL_TEXT_INSET }\n              : { right: `calc(100% - ${margin.left - PILL_TEXT_INSET}px)` }),\n          }}\n        >\n          <div className=\"-translate-y-1/2 overflow-hidden rounded-full bg-zinc-900 px-4 py-1 text-white shadow-lg dark:bg-zinc-100 dark:text-zinc-900\">\n            <div className=\"flex h-6 items-center whitespace-nowrap font-medium text-sm tabular-nums\">\n              {useFlow ? (\n                <NumberFlow\n                  format={format}\n                  isolate\n                  prefix={prefix}\n                  spinTiming={NUMBER_FLOW_TIMING}\n                  suffix={suffix}\n                  transformTiming={NUMBER_FLOW_TIMING}\n                  value={flowValue}\n                />\n              ) : (\n                <span ref={labelRef} />\n              )}\n            </div>\n          </div>\n        </m.div>\n      )}\n    </div>,\n    container\n  );\n});\n",
      "type": "registry:component",
      "target": "components/charts/chart-crosshair.tsx"
    }
  ]
}