OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat: add bklit to overview
Carl-Gerhard Lindesvärd4ccb7960e04b
diff --git a/apps/start/components.json b/apps/start/components.jsonindex 58bb3a273..b4c1b2e41 100644--- a/apps/start/components.json+++ b/apps/start/components.json@@ -10,6 +10,7 @@"cssVariables": true,"prefix": ""},+ "iconLibrary": "lucide","aliases": {"components": "@/components","utils": "@/lib/utils",@@ -17,5 +18,7 @@"lib": "@/lib","hooks": "@/hooks"},- "iconLibrary": "lucide"+ "registries": {+ "@bklit": "https://ui.bklit.com/r/{name}.json"+ }}diff --git a/apps/start/package.json b/apps/start/package.jsonindex 8c4c699a0..1714f66bc 100644--- a/apps/start/package.json+++ b/apps/start/package.json@@ -87,12 +87,21 @@"@trpc/server": "^11.17.0","@trpc/tanstack-react-query": "^11.6.0","@types/d3": "^7.4.3",+ "@visx/curve": "4.0.1-alpha.0",+ "@visx/event": "4.0.1-alpha.0",+ "@visx/gradient": "4.0.1-alpha.0",+ "@visx/grid": "4.0.1-alpha.0",+ "@visx/pattern": "4.0.1-alpha.0",+ "@visx/responsive": "4.0.1-alpha.0",+ "@visx/scale": "4.0.1-alpha.0",+ "@visx/shape": "4.0.1-alpha.0","bind-event-listener": "^3.0.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^0.2.1","codemirror": "^6.0.1","d3": "^7.8.5",+ "d3-array": "^3.2.4","date-fns": "^3.3.1","debounce": "^2.2.0","embla-carousel-autoplay": "^8.6.0",@@ -109,6 +118,7 @@"lottie-react": "^2.4.0","lucide-react": "^0.476.0","mitt": "^3.0.1",+ "motion": "^12.40.0","nuqs": "^2.5.2","prisma-error-enum": "^0.1.3","pushmodal": "^1.0.3",@@ -145,7 +155,7 @@"sonner": "^1.4.0","sqlstring": "^2.3.3","superjson": "^2.2.2",- "tailwind-merge": "^3.0.2",+ "tailwind-merge": "^3.3.1","tailwindcss": "^4.0.6","tailwindcss-animate": "^1.0.7","tw-animate-css": "^1.3.6",@@ -162,6 +172,7 @@"@tanstack/devtools-event-client": "^0.3.3","@testing-library/dom": "^10.4.0","@testing-library/react": "^16.2.0",+ "@types/d3-array": "^3.2.2","@types/lodash.debounce": "^4.0.9","@types/lodash.isequal": "^4.5.8","@types/lodash.throttle": "^4.1.9",diff --git a/apps/start/src/components/charts/animation.ts b/apps/start/src/components/charts/animation.tsnew file mode 100644index 000000000..f33492c19--- /dev/null+++ b/apps/start/src/components/charts/animation.ts@@ -0,0 +1,33 @@+import type { Transition } from "motion/react";++/** Default clip-reveal easing for cartesian charts. */+export const DEFAULT_ANIMATION_EASING = "cubic-bezier(0.85, 0, 0.15, 1)";++export const DEFAULT_ANIMATION_DURATION_MS = 1100;++/** Default enter transition — matches the original line chart reveal. */+export const DEFAULT_CHART_ENTER_TRANSITION: Transition = {+ type: "tween",+ duration: DEFAULT_ANIMATION_DURATION_MS / 1000,+ ease: [0.85, 0, 0.15, 1],+};++/**+ * Clip-path width reveal must use tween — spring does not reliably animate SVG width.+ */+export function clipRevealTransition(enterTransition?: Transition): Transition {+ if (enterTransition?.type === "tween") {+ return enterTransition;+ }++ const duration =+ typeof enterTransition?.duration === "number"+ ? enterTransition.duration+ : DEFAULT_ANIMATION_DURATION_MS / 1000;++ return {+ type: "tween",+ duration,+ ease: DEFAULT_CHART_ENTER_TRANSITION.ease,+ };+}diff --git a/apps/start/src/components/charts/area-chart.tsx b/apps/start/src/components/charts/area-chart.tsxnew file mode 100644index 000000000..b919ab430--- /dev/null+++ b/apps/start/src/components/charts/area-chart.tsx@@ -0,0 +1,177 @@+"use client";++import { ParentSize } from "@visx/responsive";+import type { Transition } from "motion/react";+import {+ Children,+ isValidElement,+ type ReactNode,+ useMemo,+ useRef,+} from "react";+import { cn } from "@/lib/utils";+import { Area, type AreaProps } from "./area";+import type { LineConfig, Margin } from "./chart-context";+import { PatternArea } from "./pattern-area";+import { TimeSeriesChartInner } from "./time-series-chart-shell";++export interface AreaChartProps {+ /** Data array - each item should have a date field and numeric values */+ data: Record<string, unknown>[];+ /** Key in data for the x-axis (date). Default: "date" */+ xDataKey?: string;+ /** Chart margins */+ margin?: Partial<Margin>;+ /** Animation duration in milliseconds. Default: 1100 */+ animationDuration?: number;+ /** CSS easing for clip-reveal. Default: cubic-bezier(0.85, 0, 0.15, 1) */+ animationEasing?: string;+ /** Motion enter transition (spring or cubic-bezier tween). */+ enterTransition?: Transition;+ /** Signature of motion URL state — triggers reveal replay when it changes. */+ revealSignature?: string;+ /** Aspect ratio as "width / height". Default: "2 / 1" */+ aspectRatio?: string;+ /** Additional class name for the container */+ className?: string;+ /** Child components (Area, Grid, ChartTooltip, etc.) */+ children: ReactNode;+}++const DEFAULT_MARGIN: Margin = { top: 40, right: 40, bottom: 40, left: 40 };++function extractAreaConfigs(children: ReactNode): LineConfig[] {+ const configs: LineConfig[] = [];++ Children.forEach(children, (child) => {+ if (!isValidElement(child)) {+ return;+ }++ const childType = child.type as {+ displayName?: string;+ name?: string;+ };+ const componentName =+ typeof child.type === "function"+ ? childType.displayName || childType.name || ""+ : "";++ const props = child.props as AreaProps | undefined;+ const isPatternArea =+ componentName === "PatternArea" || child.type === PatternArea;+ const isAreaComponent =+ componentName === "Area" ||+ child.type === Area ||+ (props &&+ typeof props.dataKey === "string" &&+ props.dataKey.length > 0 &&+ !isPatternArea);++ if (isAreaComponent && props?.dataKey) {+ configs.push({+ dataKey: props.dataKey,+ stroke: props.stroke || props.fill || "var(--chart-line-primary)",+ strokeWidth: props.strokeWidth || 2,+ });+ }+ });++ return configs;+}++interface ChartInnerProps {+ width: number;+ height: number;+ data: Record<string, unknown>[];+ xDataKey: string;+ margin: Margin;+ animationDuration: number;+ animationEasing?: string;+ enterTransition?: Transition;+ revealSignature?: string;+ children: ReactNode;+ containerRef: React.RefObject<HTMLDivElement | null>;+}++function ChartInner({+ width,+ height,+ data,+ xDataKey,+ margin,+ animationDuration,+ animationEasing,+ enterTransition,+ revealSignature,+ children,+ containerRef,+}: ChartInnerProps) {+ const lines = useMemo(() => extractAreaConfigs(children), [children]);++ return (+ <TimeSeriesChartInner+ animationDuration={animationDuration}+ animationEasing={animationEasing}+ clipPathId="chart-area-grow-clip"+ containerRef={containerRef}+ data={data}+ enterTransition={enterTransition}+ height={height}+ lines={lines}+ margin={margin}+ revealSignature={revealSignature}+ width={width}+ xDataKey={xDataKey}+ >+ {children}+ </TimeSeriesChartInner>+ );+}++export function AreaChart({+ data,+ xDataKey = "date",+ margin: marginProp,+ animationDuration = 1100,+ animationEasing,+ enterTransition,+ revealSignature,+ aspectRatio = "2 / 1",+ className = "",+ children,+}: AreaChartProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const margin = { ...DEFAULT_MARGIN, ...marginProp };++ return (+ <div+ className={cn("relative w-full", className)}+ ref={containerRef}+ style={{ aspectRatio, touchAction: "none" }}+ >+ <ParentSize debounceTime={10}>+ {({ width, height }) => (+ <ChartInner+ animationDuration={animationDuration}+ animationEasing={animationEasing}+ containerRef={containerRef}+ data={data}+ enterTransition={enterTransition}+ height={height}+ margin={margin}+ revealSignature={revealSignature}+ width={width}+ xDataKey={xDataKey}+ >+ {children}+ </ChartInner>+ )}+ </ParentSize>+ </div>+ );+}++export { Area, type AreaProps } from "./area";++export default AreaChart;diff --git a/apps/start/src/components/charts/area-gradient-defs.tsx b/apps/start/src/components/charts/area-gradient-defs.tsxnew file mode 100644index 000000000..8615ff3f3--- /dev/null+++ b/apps/start/src/components/charts/area-gradient-defs.tsx@@ -0,0 +1,95 @@+import {+ type FadeEdges,+ fadeGradientStops,+ resolveFadeSides,+} from "./fade-edges";++interface AreaGradientDefsProps {+ gradientId: string;+ strokeGradientId: string;+ edgeMaskId: string;+ edgeGradientId: string;+ fill: string;+ fillOpacity: number;+ gradientToOpacity: number;+ resolvedStroke: string;+ isPatternFill: boolean;+ fadeEdges: FadeEdges;+ innerWidth: number;+ innerHeight: number;+}++export function AreaGradientDefs({+ gradientId,+ strokeGradientId,+ edgeMaskId,+ edgeGradientId,+ fill,+ fillOpacity,+ gradientToOpacity,+ resolvedStroke,+ isPatternFill,+ fadeEdges,+ innerWidth,+ innerHeight,+}: AreaGradientDefsProps) {+ const sides = resolveFadeSides(fadeEdges);+ // Stroke gradient mirrors the area's edge fade so the line doesn't pop in+ // past the faded fill. Skip emitting it when neither edge fades — the line+ // can then paint a solid stroke instead of an unnecessary url(#...) ref.+ const strokeStops = sides.any ? fadeGradientStops(sides) : null;+ const showEdgeMask = sides.any && !isPatternFill;+ const edgeStops = showEdgeMask ? fadeGradientStops(sides) : null;++ return (+ <defs>+ {isPatternFill ? null : (+ <linearGradient id={gradientId} x1="0%" x2="0%" y1="0%" y2="100%">+ <stop+ offset="0%"+ style={{ stopColor: fill, stopOpacity: fillOpacity }}+ />+ <stop+ offset="100%"+ style={{ stopColor: fill, stopOpacity: gradientToOpacity }}+ />+ </linearGradient>+ )}++ {strokeStops ? (+ <linearGradient id={strokeGradientId} x1="0%" x2="100%" y1="0%" y2="0%">+ {strokeStops.map((stop) => (+ <stop+ key={stop.offset}+ offset={stop.offset}+ style={{ stopColor: resolvedStroke, stopOpacity: stop.opacity }}+ />+ ))}+ </linearGradient>+ ) : null}++ {edgeStops ? (+ <>+ <linearGradient id={edgeGradientId} x1="0%" x2="100%" y1="0%" y2="0%">+ {edgeStops.map((stop) => (+ <stop+ key={stop.offset}+ offset={stop.offset}+ style={{ stopColor: "white", stopOpacity: stop.opacity }}+ />+ ))}+ </linearGradient>+ <mask id={edgeMaskId}>+ <rect+ fill={`url(#${edgeGradientId})`}+ height={innerHeight}+ width={innerWidth}+ x="0"+ y="0"+ />+ </mask>+ </>+ ) : null}+ </defs>+ );+}diff --git a/apps/start/src/components/charts/area.tsx b/apps/start/src/components/charts/area.tsxnew file mode 100644index 000000000..f1f9e77d2--- /dev/null+++ b/apps/start/src/components/charts/area.tsx@@ -0,0 +1,227 @@+"use client";++import { curveMonotoneX } from "@visx/curve";+import { AreaClosed, LinePath } from "@visx/shape";++// CurveFactory type - simplified version compatible with visx+// biome-ignore lint/suspicious/noExplicitAny: d3 curve factory type+type CurveFactory = any;++import { useCallback, useId, useRef } from "react";+import { AreaGradientDefs } from "./area-gradient-defs";+import { chartCssVars, useChartStable } from "./chart-context";+import { type FadeEdges, resolveFadeSides } from "./fade-edges";+import {+ resolveDashTailBounds,+ usePathStrokeMetrics,+} from "./path-stroke-utils";+import { SeriesDashTailOverlay } from "./series-dash-tail-overlay";+import { SeriesHighlightLayer } from "./series-highlight-layer";+import { SeriesHoverDim } from "./series-hover-dim";+import { SeriesMarkers } from "./series-markers";+import type { SeriesPointMarkerStyle } from "./series-point-marker";++export interface AreaProps {+ /** Key in data to use for y values */+ dataKey: string;+ /** Fill color for the area gradient start. Default: var(--chart-line-primary) */+ fill?: string;+ /** Fill opacity at the top of the area. Default: 0.4 */+ fillOpacity?: number;+ /** Stroke color for the line. Default: same as fill */+ stroke?: string;+ /** Stroke width. Default: 2 */+ strokeWidth?: number;+ /** Curve function. Default: curveMonotoneX */+ curve?: CurveFactory;+ /** Whether to animate the area. Default: true */+ animate?: boolean;+ /** Whether to show the stroke line. Default: true */+ showLine?: boolean;+ /** Whether to show highlight segment on hover. Default: true */+ showHighlight?: boolean;+ /** Gradient opacity at bottom (0 = fully transparent). Default: 0 */+ gradientToOpacity?: number;+ /**+ * Fade the area fill (and stroke) toward transparent at the chart edges.+ * - `true` fades both edges, `false` disables the fade entirely.+ * - `"left"` / `"right"` fades only that side — useful when the opposite+ * edge butts up against another element you don't want to fade into.+ * Default: false+ */+ fadeEdges?: FadeEdges;+ /** Render scatter-style circle markers at each data point. Default: false */+ showMarkers?: boolean;+ /** Marker styling (same options as Scatter). */+ markers?: SeriesPointMarkerStyle;+ /**+ * Data index from which the line stroke becomes dashed (inclusive).+ * Useful for projecting incomplete periods, e.g. dashed from yesterday through today.+ */+ dashFromIndex?: number;+ /** Dash pattern for the tail segment when `dashFromIndex` is set. Default: "6,4" */+ dashArray?: string;+}++export function Area({+ dataKey,+ fill = chartCssVars.linePrimary,+ fillOpacity = 0.4,+ stroke,+ strokeWidth = 2,+ curve = curveMonotoneX,+ animate = true,+ showLine = true,+ showHighlight = true,+ gradientToOpacity = 0,+ fadeEdges = false,+ showMarkers = false,+ markers,+ dashFromIndex,+ dashArray = "6,4",+}: AreaProps) {+ // Stable slice only: hover state lives inside `<SeriesHoverDim>` and+ // `<SeriesHighlightLayer>` so this component (and its expensive+ // <SeriesDashTailOverlay> child) does not re-render on cursor motion.+ // The reveal-clip is now a single shared clipPath at the chart-shell+ // level (`time-series-chart-shell.tsx`); we no longer render a per-area+ // `<ChartRevealClip>` or read `revealEpoch` here.+ const {+ data,+ renderData,+ xScale,+ yScale,+ innerHeight,+ innerWidth,+ xAccessor,+ } = useChartStable();++ const pathRef = useRef<SVGPathElement>(null);+ const pathMetricsKey = `${renderData.length}:${innerWidth}:${dashFromIndex}:${showLine}`;+ const { pathLength, pathD } = usePathStrokeMetrics(pathRef, pathMetricsKey);++ // Unique IDs for this area+ const uniqueId = useId();+ const gradientId = `area-gradient-${dataKey}-${uniqueId}`;+ const strokeGradientId = `area-stroke-gradient-${dataKey}-${uniqueId}`;+ const edgeMaskId = `area-edge-mask-${dataKey}-${uniqueId}`;+ const edgeGradientId = `${edgeMaskId}-gradient`;++ const isPatternFill = fill.startsWith("url(");+ const showAreaFill = isPatternFill || fillOpacity > 0;+ const areaFill = isPatternFill ? fill : `url(#${gradientId})`;++ // Resolved stroke color (defaults to fill; pattern URLs need a real color)+ const resolvedStroke =+ stroke || (isPatternFill ? chartCssVars.linePrimary : fill);++ const getY = useCallback(+ (d: Record<string, unknown>) => {+ const value = d[dataKey];+ return typeof value === "number" ? (yScale(value) ?? 0) : 0;+ },+ [dataKey, yScale]+ );++ const hasDashTail = resolveDashTailBounds(dashFromIndex, data.length);+ // The stroke gradient is only emitted when at least one edge fades, so fall+ // back to the resolved solid color otherwise — avoids an invalid url(#...).+ const fadeSides = resolveFadeSides(fadeEdges);+ const strokePaint = fadeSides.any+ ? `url(#${strokeGradientId})`+ : resolvedStroke;+ const highlightEnabled = showHighlight && showLine;++ return (+ <>+ <AreaGradientDefs+ edgeGradientId={edgeGradientId}+ edgeMaskId={edgeMaskId}+ fadeEdges={fadeEdges}+ fill={fill}+ fillOpacity={fillOpacity}+ gradientId={gradientId}+ gradientToOpacity={gradientToOpacity}+ innerHeight={innerHeight}+ innerWidth={innerWidth}+ isPatternFill={isPatternFill}+ resolvedStroke={resolvedStroke}+ strokeGradientId={strokeGradientId}+ />++ <SeriesHoverDim dimOpacity={0.6} enabled={showHighlight}>+ {/* Area fill */}+ {showAreaFill ? (+ <g+ mask={+ fadeSides.any && !isPatternFill+ ? `url(#${edgeMaskId})`+ : undefined+ }+ >+ <AreaClosed+ curve={curve}+ data={renderData}+ fill={areaFill}+ x={(d) => xScale(xAccessor(d)) ?? 0}+ y={getY}+ yScale={yScale}+ />+ </g>+ ) : null}++ {/* Stroke line on top of area */}+ {showLine ? (+ <>+ <LinePath+ curve={curve}+ data={renderData}+ innerRef={pathRef}+ stroke={hasDashTail ? "transparent" : strokePaint}+ strokeLinecap="round"+ strokeWidth={strokeWidth}+ x={(d) => xScale(xAccessor(d)) ?? 0}+ y={getY}+ />+ <SeriesDashTailOverlay+ dashArray={dashArray}+ dashFromIndex={dashFromIndex}+ data={data}+ innerHeight={innerHeight}+ innerWidth={innerWidth}+ pathD={pathD}+ pathLength={pathLength}+ stroke={strokePaint}+ strokeWidth={strokeWidth}+ xAccessor={xAccessor}+ xScale={xScale}+ />+ </>+ ) : null}+ </SeriesHoverDim>++ {/* Highlight segment on hover — isolated hover subscriber. */}+ <SeriesHighlightLayer+ enabled={highlightEnabled}+ height={innerHeight}+ pathRef={pathRef}+ stroke={resolvedStroke}+ strokeWidth={strokeWidth}+ />++ {showMarkers ? (+ <SeriesMarkers+ animate={animate}+ dataKey={dataKey}+ {...markers}+ fill={markers?.fill ?? resolvedStroke}+ stroke={markers?.stroke ?? markers?.fill ?? resolvedStroke}+ />+ ) : null}+ </>+ );+}++Area.displayName = "Area";++export default Area;diff --git a/apps/start/src/components/charts/bar-chart.tsx b/apps/start/src/components/charts/bar-chart.tsxnew file mode 100644index 000000000..3a2ad5164--- /dev/null+++ b/apps/start/src/components/charts/bar-chart.tsx@@ -0,0 +1,611 @@+"use client";++import { localPoint } from "@visx/event";+import { ParentSize } from "@visx/responsive";+import { scaleBand, scaleLinear } from "@visx/scale";+import type { Transition } from "motion/react";+import {+ Children,+ isValidElement,+ memo,+ type ReactElement,+ type ReactNode,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { cn } from "@/lib/utils";+import { DEFAULT_ANIMATION_EASING } from "./animation";+import type { BarProps } from "./bar";+import {+ ChartProvider,+ type LineConfig,+ type Margin,+ type TooltipData,+} from "./chart-context";+import { isGradientDefComponent, isPatternDefComponent } from "./chart-defs";+import { shortDateFmt } from "./chart-formatters";+import { useScheduledTooltip } from "./use-scheduled-tooltip";++export type BarOrientation = "vertical" | "horizontal";++export interface BarChartProps {+ /** Data array - each item should have an x-axis key and numeric values */+ data: Record<string, unknown>[];+ /** Key in data for the categorical axis. Default: "name" */+ xDataKey?: string;+ /** Chart margins */+ margin?: Partial<Margin>;+ /** Animation duration in milliseconds. Default: 1100 */+ animationDuration?: number;+ /** CSS easing for bar grow transitions. */+ animationEasing?: string;+ /** Motion enter transition (spring or cubic-bezier tween). */+ enterTransition?: Transition;+ /** Signature of motion URL state — triggers enter replay when it changes. */+ revealSignature?: string;+ /** Aspect ratio as "width / height". Default: "2 / 1" */+ aspectRatio?: string;+ /** Additional class name for the container */+ className?: string;+ /** Gap between bar groups as a fraction of band width (0-1). Default: 0.2 */+ barGap?: number;+ /** Fixed bar width in pixels. If not set, bars auto-size to fill the band. */+ barWidth?: number;+ /** Bar chart orientation. Default: "vertical" */+ orientation?: BarOrientation;+ /** Whether to stack bars instead of grouping them. Default: false */+ stacked?: boolean;+ /** Gap between stacked bar segments in pixels. Default: 0 */+ stackGap?: number;+ /** Child components (Bar, Grid, ChartTooltip, etc.) */+ children: ReactNode;+}++const DEFAULT_MARGIN: Margin = { top: 40, right: 40, bottom: 40, left: 40 };++// Extract bar configs from children synchronously+function extractBarConfigs(children: ReactNode): LineConfig[] {+ const configs: LineConfig[] = [];++ Children.forEach(children, (child) => {+ if (!isValidElement(child)) {+ return;+ }++ const childType = child.type as {+ displayName?: string;+ name?: string;+ };+ const componentName =+ typeof child.type === "function"+ ? childType.displayName || childType.name || ""+ : "";++ const props = child.props as BarProps | undefined;+ const isBarComponent =+ componentName === "Bar" ||+ (props && typeof props.dataKey === "string" && props.dataKey.length > 0);++ if (isBarComponent && props?.dataKey) {+ // Use stroke for tooltip dot color if provided, otherwise fall back to fill+ // This allows gradient/pattern fills to have a solid dot color+ const dotColor =+ props.stroke || props.fill || "var(--chart-line-primary)";+ configs.push({+ dataKey: props.dataKey,+ stroke: dotColor,+ strokeWidth: 0,+ });+ }+ });++ return configs;+}++// Check if a component should render after the mouse overlay+function isPostOverlayComponent(child: ReactElement): boolean {+ const childType = child.type as {+ displayName?: string;+ name?: string;+ __isChartMarkers?: boolean;+ };++ if (childType.__isChartMarkers) {+ return true;+ }++ const componentName =+ typeof child.type === "function"+ ? childType.displayName || childType.name || ""+ : "";++ return componentName === "ChartMarkers" || componentName === "MarkerGroup";+}++interface ChartInnerProps {+ width: number;+ height: number;+ data: Record<string, unknown>[];+ xDataKey: string;+ margin: Margin;+ animationDuration: number;+ animationEasing: string;+ enterTransition?: Transition;+ revealSignature?: string;+ barGap: number;+ barWidthProp?: number;+ orientation: BarOrientation;+ stacked: boolean;+ stackGap: number;+ children: ReactNode;+ containerRef: React.RefObject<HTMLDivElement | null>;+}++function ChartInner(props: ChartInnerProps) {+ const { width, height } = props;+ if (width < 10 || height < 10) {+ return null;+ }+ return <ChartCore {...props} />;+}++const ChartCore = memo(function ChartCore({+ width,+ height,+ data,+ xDataKey,+ margin,+ animationDuration,+ animationEasing,+ enterTransition,+ revealSignature = "",+ barGap,+ barWidthProp,+ orientation,+ stacked,+ stackGap,+ children,+ containerRef,+}: ChartInnerProps) {+ const { tooltipData, setTooltipData, scheduleTooltip, clearTooltip } =+ useScheduledTooltip<TooltipData>();+ const [isLoaded, setIsLoaded] = useState(false);+ const [revealEpoch, setRevealEpoch] = useState(0);+ const hoveredBarIndex = tooltipData?.index ?? null;++ const isHorizontal = orientation === "horizontal";++ // Extract bar configs synchronously from children+ const lines = useMemo(() => extractBarConfigs(children), [children]);++ const innerWidth = width - margin.left - margin.right;+ const innerHeight = height - margin.top - margin.bottom;++ // Category accessor function - returns string for categorical scale+ const categoryAccessor = useCallback(+ (d: Record<string, unknown>): string => {+ const value = d[xDataKey];+ if (value instanceof Date) {+ return shortDateFmt.format(value);+ }+ return String(value ?? "");+ },+ [xDataKey]+ );++ // For compatibility with ChartContext, provide a Date-based xAccessor+ const xAccessorDate = useCallback(+ (d: Record<string, unknown>): Date => {+ const value = d[xDataKey];+ if (value instanceof Date) {+ return value;+ }+ return new Date();+ },+ [xDataKey]+ );++ // Category scale (band) - for the categorical axis+ const categoryScale = useMemo(() => {+ const domain = data.map((d) => categoryAccessor(d));+ const range: [number, number] = isHorizontal+ ? [0, innerHeight]+ : [0, innerWidth];+ return scaleBand<string>({+ range,+ domain,+ padding: barGap,+ });+ }, [innerWidth, innerHeight, data, categoryAccessor, barGap, isHorizontal]);++ // Band width for bars - use prop if provided, otherwise use scale's bandwidth+ const bandWidth = barWidthProp ?? categoryScale.bandwidth();++ // Compute max value considering stacking+ const maxValue = useMemo(() => {+ if (stacked) {+ // For stacked bars, sum all values at each data point+ let max = 0;+ for (const d of data) {+ let sum = 0;+ for (const line of lines) {+ const value = d[line.dataKey];+ if (typeof value === "number") {+ sum += value;+ }+ }+ if (sum > max) {+ max = sum;+ }+ }+ return max || 100;+ }+ // For grouped bars, find max single value+ let max = 0;+ for (const line of lines) {+ for (const d of data) {+ const value = d[line.dataKey];+ if (typeof value === "number" && value > max) {+ max = value;+ }+ }+ }+ return max || 100;+ }, [data, lines, stacked]);++ // Value scale (linear) - for the value axis+ const valueScale = useMemo(() => {+ const range = isHorizontal ? [0, innerWidth] : [innerHeight, 0];+ return scaleLinear({+ range,+ domain: [0, maxValue * 1.1],+ nice: true,+ });+ }, [innerWidth, innerHeight, maxValue, isHorizontal]);++ // Compute stack offsets for stacked bars+ const stackOffsets = useMemo(() => {+ if (!stacked) {+ return undefined;+ }+ const offsets = new Map<number, Map<string, number>>();+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ if (!d) {+ continue;+ }+ const pointOffsets = new Map<string, number>();+ let cumulative = 0;+ for (const line of lines) {+ pointOffsets.set(line.dataKey, cumulative);+ const value = d[line.dataKey];+ if (typeof value === "number") {+ cumulative += value;+ }+ }+ offsets.set(i, pointOffsets);+ }+ return offsets;+ }, [data, lines, stacked]);++ // Column width for tooltip indicator+ const columnWidth = useMemo(() => {+ if (data.length < 1) {+ return 0;+ }+ return isHorizontal ? innerHeight / data.length : innerWidth / data.length;+ }, [innerWidth, innerHeight, data.length, isHorizontal]);++ // Pre-compute labels for ticker animation+ const dateLabels = useMemo(+ () => data.map((d) => categoryAccessor(d)),+ [data, categoryAccessor]+ );++ // Create a fake time scale for compatibility with ChartContext+ const fakeTimeScale = useMemo(() => {+ const now = Date.now();+ const start = now - data.length * 24 * 60 * 60 * 1000;+ const scale = {+ ...categoryScale,+ domain: () => [new Date(start), new Date(now)],+ range: () => [0, innerWidth] as [number, number],+ invert: (x: number) => new Date(start + (x / innerWidth) * (now - start)),+ copy: () => scale,+ };+ return scale;+ }, [categoryScale, innerWidth, data.length]);++ // Animation timing — replay when motion settings change+ // biome-ignore lint/correctness/useExhaustiveDependencies: revealSignature+ useEffect(() => {+ setRevealEpoch((n) => n + 1);+ setIsLoaded(false);+ const timer = setTimeout(() => {+ setIsLoaded(true);+ }, animationDuration);+ return () => clearTimeout(timer);+ }, [animationDuration, revealSignature]);++ // Mouse move handler+ const handleMouseMove = useCallback(+ (event: React.MouseEvent<SVGGElement>) => {+ const point = localPoint(event);+ if (!point) {+ return;+ }++ const pos = isHorizontal ? point.y - margin.top : point.x - margin.left;++ // Find which band the mouse is over+ const bandIndex = Math.floor(pos / columnWidth);+ const clampedIndex = Math.max(0, Math.min(data.length - 1, bandIndex));+ const d = data[clampedIndex];++ if (!d) {+ return;+ }++ // Calculate positions for each bar+ const yPositions: Record<string, number> = {};+ const xPositions: Record<string, number> = {};+ const barPos = categoryScale(categoryAccessor(d)) ?? 0;++ if (isHorizontal) {+ // Horizontal bars: dots at end of bar (x = value), centered vertically in band+ const seriesCount = lines.length;+ const groupGap = seriesCount > 1 ? 4 : 0;+ const individualBarHeight =+ seriesCount > 0+ ? (bandWidth - groupGap * (seriesCount - 1)) / seriesCount+ : bandWidth;++ if (stacked) {+ // Stacked horizontal: all bars same y, x at cumulative end+ let cumulative = 0;+ for (const line of lines) {+ const value = d[line.dataKey];+ if (typeof value === "number") {+ cumulative += value;+ xPositions[line.dataKey] = valueScale(cumulative) ?? 0;+ yPositions[line.dataKey] = barPos + bandWidth / 2;+ }+ }+ } else {+ // Grouped horizontal: each bar at its own y position+ lines.forEach((line, idx) => {+ const value = d[line.dataKey];+ if (typeof value === "number") {+ xPositions[line.dataKey] = valueScale(value) ?? 0;+ yPositions[line.dataKey] =+ barPos ++ idx * (individualBarHeight + groupGap) ++ individualBarHeight / 2;+ }+ });+ }+ } else if (stacked) {+ // Vertical stacked bars+ let cumulative = 0;+ let seriesIdx = 0;+ for (const line of lines) {+ const value = d[line.dataKey];+ if (typeof value === "number") {+ cumulative += value;+ const gapOffset = seriesIdx * stackGap;+ yPositions[line.dataKey] =+ (valueScale(cumulative) ?? 0) - gapOffset;+ seriesIdx++;+ }+ }+ } else {+ // Vertical grouped bars+ const seriesCount = lines.length;+ const groupGap = seriesCount > 1 ? 4 : 0;+ const individualBarWidth =+ seriesCount > 0+ ? (bandWidth - groupGap * (seriesCount - 1)) / seriesCount+ : bandWidth;++ lines.forEach((line, idx) => {+ const value = d[line.dataKey];+ if (typeof value === "number") {+ yPositions[line.dataKey] = valueScale(value) ?? 0;+ xPositions[line.dataKey] =+ barPos ++ idx * (individualBarWidth + groupGap) ++ individualBarWidth / 2;+ }+ });+ }++ // Tooltip position: for horizontal, position at max bar end; for vertical, center of band+ let tooltipX: number;+ if (isHorizontal) {+ // Position tooltip at the end of the longest bar+ const maxX = Math.max(...Object.values(xPositions), 0);+ tooltipX = maxX;+ } else {+ tooltipX = barPos + bandWidth / 2;+ }++ scheduleTooltip({+ point: d,+ index: clampedIndex,+ x: tooltipX,+ yPositions,+ xPositions: Object.keys(xPositions).length > 0 ? xPositions : undefined,+ });+ },+ [+ categoryScale,+ valueScale,+ data,+ lines,+ margin.left,+ margin.top,+ categoryAccessor,+ columnWidth,+ bandWidth,+ isHorizontal,+ stacked,+ stackGap,+ scheduleTooltip,+ ]+ );++ const handleMouseLeave = useCallback(() => {+ clearTooltip();+ }, [clearTooltip]);++ const canInteract = isLoaded;++ // Separate children into defs, pre-overlay, and post-overlay+ const defsChildren: ReactElement[] = [];+ const preOverlayChildren: ReactElement[] = [];+ const postOverlayChildren: ReactElement[] = [];++ Children.forEach(children, (child) => {+ if (!isValidElement(child)) {+ return;+ }++ if (isGradientDefComponent(child)) {+ defsChildren.push(child);+ } else if (isPatternDefComponent(child)) {+ preOverlayChildren.push(child);+ } else if (isPostOverlayComponent(child)) {+ postOverlayChildren.push(child);+ } else {+ preOverlayChildren.push(child);+ }+ });++ const contextValue = {+ data,+ renderData: data,+ xScale: fakeTimeScale as unknown as ReturnType<+ typeof import("@visx/scale").scaleTime<number>+ >,+ yScale: valueScale,+ width,+ height,+ innerWidth,+ innerHeight,+ margin,+ columnWidth,+ tooltipData,+ setTooltipData,+ containerRef,+ lines,+ isLoaded,+ animationDuration,+ animationEasing,+ enterTransition,+ revealEpoch,+ xAccessor: xAccessorDate,+ dateLabels,+ // Bar-specific properties+ barScale: categoryScale,+ bandWidth,+ hoveredBarIndex,+ barXAccessor: categoryAccessor,+ orientation,+ stacked,+ stackOffsets,+ };++ return (+ <ChartProvider value={contextValue}>+ <svg aria-hidden="true" height={height} width={width}>+ {/* Gradient and pattern definitions */}+ {defsChildren.length > 0 && <defs>{defsChildren}</defs>}++ <rect fill="transparent" height={height} width={width} x={0} y={0} />++ {/* biome-ignore lint/a11y/noStaticElementInteractions: Chart interaction area */}+ <g+ onMouseLeave={canInteract ? handleMouseLeave : undefined}+ onMouseMove={canInteract ? handleMouseMove : undefined}+ style={{ cursor: canInteract ? "crosshair" : "default" }}+ transform={`translate(${margin.left},${margin.top})`}+ >+ {/* Background rect for mouse event detection */}+ <rect+ fill="transparent"+ height={innerHeight}+ width={innerWidth}+ x={0}+ y={0}+ />++ {/* SVG children rendered before markers */}+ {preOverlayChildren}++ {/* Markers rendered last so they're on top for interaction */}+ {postOverlayChildren}+ </g>+ </svg>+ </ChartProvider>+ );+});++export function BarChart({+ data,+ xDataKey = "name",+ margin: marginProp,+ animationDuration = 1100,+ animationEasing = DEFAULT_ANIMATION_EASING,+ enterTransition,+ revealSignature,+ aspectRatio = "2 / 1",+ className = "",+ barGap = 0.2,+ barWidth,+ orientation = "vertical",+ stacked = false,+ stackGap = 0,+ children,+}: BarChartProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const margin = { ...DEFAULT_MARGIN, ...marginProp };++ return (+ <div+ className={cn("relative w-full", className)}+ ref={containerRef}+ style={{ aspectRatio }}+ >+ <ParentSize debounceTime={10}>+ {({ width, height }) => (+ <ChartInner+ animationDuration={animationDuration}+ animationEasing={animationEasing}+ barGap={barGap}+ barWidthProp={barWidth}+ containerRef={containerRef}+ data={data}+ enterTransition={enterTransition}+ height={height}+ margin={margin}+ orientation={orientation}+ revealSignature={revealSignature}+ stacked={stacked}+ stackGap={stackGap}+ width={width}+ xDataKey={xDataKey}+ >+ {children}+ </ChartInner>+ )}+ </ParentSize>+ </div>+ );+}++BarChart.displayName = "BarChart";++export default BarChart;diff --git a/apps/start/src/components/charts/bar-x-axis.tsx b/apps/start/src/components/charts/bar-x-axis.tsxnew file mode 100644index 000000000..2fbfa5f91--- /dev/null+++ b/apps/start/src/components/charts/bar-x-axis.tsx@@ -0,0 +1,153 @@+"use client";++import { motion } from "motion/react";+import { memo, useEffect, useMemo, useState } from "react";+import { createPortal } from "react-dom";+import { cn } from "@/lib/utils";+import { useChart, useChartStable } from "./chart-context";++export interface BarXAxisProps {+ /** Width of the date ticker box for fade calculation. Default: 50 */+ tickerHalfWidth?: number;+ /** Whether to show all labels or skip some for dense data. Default: false */+ showAllLabels?: boolean;+ /** Maximum number of labels to show. Default: 12 */+ maxLabels?: number;+}++interface BarXAxisLabelProps {+ label: string;+ x: number;+ crosshairX: number | null;+ isHovering: boolean;+ tickerHalfWidth: number;+}++function BarXAxisLabel({+ label,+ x,+ crosshairX,+ isHovering,+ tickerHalfWidth,+}: BarXAxisLabelProps) {+ const fadeBuffer = 20;+ const fadeRadius = tickerHalfWidth + fadeBuffer;++ let opacity = 1;+ if (isHovering && crosshairX !== null) {+ const distance = Math.abs(x - crosshairX);+ if (distance < tickerHalfWidth) {+ opacity = 0;+ } else if (distance < fadeRadius) {+ opacity = (distance - tickerHalfWidth) / fadeBuffer;+ }+ }++ // Zero-width container approach for perfect centering+ return (+ <div+ className="absolute"+ style={{+ left: x,+ bottom: 12,+ width: 0,+ display: "flex",+ justifyContent: "center",+ }}+ >+ <motion.span+ animate={{ opacity }}+ className={cn("whitespace-nowrap text-chart-label text-xs")}+ initial={{ opacity: 1 }}+ transition={{ duration: 0.4, ease: "easeInOut" }}+ >+ {label}+ </motion.span>+ </div>+ );+}++export function BarXAxis(props: BarXAxisProps) {+ const { containerRef, barScale } = useChartStable();+ const [mounted, setMounted] = useState(false);++ useEffect(() => {+ setMounted(true);+ }, []);++ const container = containerRef.current;+ if (!(mounted && container)) {+ return null;+ }++ if (!barScale) {+ return null;+ }++ return <BarXAxisInner {...props} container={container} />;+}++const BarXAxisInner = memo(function BarXAxisInner({+ tickerHalfWidth = 50,+ showAllLabels = false,+ maxLabels = 12,+ container,+}: BarXAxisProps & { container: HTMLDivElement }) {+ const { margin, tooltipData, barScale, bandWidth, barXAccessor, data } =+ useChart();++ // Generate labels for each bar+ const labelsToShow = useMemo(() => {+ if (!(barScale && bandWidth && barXAccessor)) {+ return [];+ }++ const allLabels = data.map((d) => {+ const label = barXAccessor(d);+ const bandX = barScale(label) ?? 0;+ // Center the label under the bar group+ const x = bandX + bandWidth / 2 + margin.left;+ return { label, x };+ });++ // If showAllLabels is true or we have fewer than maxLabels, show all+ if (showAllLabels || allLabels.length <= maxLabels) {+ return allLabels;+ }++ // Otherwise, skip some labels to avoid crowding+ const step = Math.ceil(allLabels.length / maxLabels);+ return allLabels.filter((_, i) => i % step === 0);+ }, [+ barScale,+ bandWidth,+ barXAccessor,+ data,+ margin.left,+ showAllLabels,+ maxLabels,+ ]);++ const isHovering = tooltipData !== null;+ const crosshairX = tooltipData ? tooltipData.x + margin.left : null;++ return createPortal(+ <div className="pointer-events-none absolute inset-0">+ {labelsToShow.map((item) => (+ <BarXAxisLabel+ crosshairX={crosshairX}+ isHovering={isHovering}+ key={`${item.label}-${item.x}`}+ label={item.label}+ tickerHalfWidth={tickerHalfWidth}+ x={item.x}+ />+ ))}+ </div>,+ container+ );+});++BarXAxis.displayName = "BarXAxis";++export default BarXAxis;diff --git a/apps/start/src/components/charts/bar-y-axis.tsx b/apps/start/src/components/charts/bar-y-axis.tsxnew file mode 100644index 000000000..95400e5c7--- /dev/null+++ b/apps/start/src/components/charts/bar-y-axis.tsx@@ -0,0 +1,142 @@+"use client";++import { motion } from "motion/react";+import { memo, useEffect, useMemo, useState } from "react";+import { createPortal } from "react-dom";+import { cn } from "@/lib/utils";+import { useChart, useChartStable } from "./chart-context";++export interface BarYAxisProps {+ /** Whether to show all labels or skip some for dense data. Default: true */+ showAllLabels?: boolean;+ /** Maximum number of labels to show. Default: 20 */+ maxLabels?: number;+}++interface BarYAxisLabelProps {+ label: string;+ y: number;+ bandHeight: number;+ isHovered: boolean;+}++function BarYAxisLabel({+ label,+ y,+ bandHeight,+ isHovered,+}: BarYAxisLabelProps) {+ return (+ <div+ className="absolute right-0 flex items-center justify-end pr-2"+ style={{+ top: y,+ height: bandHeight,+ }}+ >+ <motion.span+ animate={{+ opacity: isHovered ? 1 : 0.7,+ color: isHovered+ ? "var(--foreground)"+ : "var(--chart-label, var(--color-zinc-500))",+ }}+ className={cn("truncate whitespace-nowrap text-right text-xs")}+ initial={{+ opacity: 0.7,+ color: "var(--chart-label, var(--color-zinc-500))",+ }}+ style={{ maxWidth: 70 }}+ transition={{ duration: 0.15 }}+ >+ {label}+ </motion.span>+ </div>+ );+}++export function BarYAxis(props: BarYAxisProps) {+ const { containerRef, barScale } = useChartStable();+ const [mounted, setMounted] = useState(false);++ useEffect(() => {+ setMounted(true);+ }, []);++ const container = containerRef.current;+ if (!(mounted && container)) {+ return null;+ }++ if (!barScale) {+ return null;+ }++ return <BarYAxisInner {...props} container={container} />;+}++const BarYAxisInner = memo(function BarYAxisInner({+ showAllLabels = true,+ maxLabels = 20,+ container,+}: BarYAxisProps & { container: HTMLDivElement }) {+ const { margin, barScale, bandWidth, barXAccessor, data, hoveredBarIndex } =+ useChart();++ // Generate labels for each bar+ const labelsToShow = useMemo(() => {+ if (!(barScale && bandWidth && barXAccessor)) {+ return [];+ }++ const allLabels = data.map((d, i) => {+ const label = barXAccessor(d);+ const bandY = barScale(label) ?? 0;+ // Center the label vertically within the band+ const y = bandY + margin.top;+ return { label, y, bandHeight: bandWidth, index: i };+ });++ // If showAllLabels is true or we have fewer than maxLabels, show all+ if (showAllLabels || allLabels.length <= maxLabels) {+ return allLabels;+ }++ // Otherwise, skip some labels to avoid crowding+ const step = Math.ceil(allLabels.length / maxLabels);+ return allLabels.filter((_, i) => i % step === 0);+ }, [+ barScale,+ bandWidth,+ barXAccessor,+ data,+ margin.top,+ showAllLabels,+ maxLabels,+ ]);++ return createPortal(+ <div+ className="pointer-events-none absolute top-0 bottom-0"+ style={{+ left: 0,+ width: margin.left,+ }}+ >+ {labelsToShow.map((item) => (+ <BarYAxisLabel+ bandHeight={item.bandHeight}+ isHovered={hoveredBarIndex === item.index}+ key={`${item.label}-${item.y}`}+ label={item.label}+ y={item.y}+ />+ ))}+ </div>,+ container+ );+});++BarYAxis.displayName = "BarYAxis";++export default BarYAxis;diff --git a/apps/start/src/components/charts/bar.tsx b/apps/start/src/components/charts/bar.tsxnew file mode 100644index 000000000..784f2416f--- /dev/null+++ b/apps/start/src/components/charts/bar.tsx@@ -0,0 +1,354 @@+"use client";++import type { scaleBand } from "@visx/scale";+import type { Transition } from "motion/react";+import { motion } from "motion/react";+import { memo, useId, useMemo } from "react";+import { chartCssVars, useChart, useChartStable } from "./chart-context";+import { transitionWithDelay } from "./motion-utils";++type ScaleBand<Domain extends { toString(): string }> = ReturnType<+ typeof scaleBand<Domain>+>;++export type BarLineCap = "round" | "butt" | number;+export type BarAnimationType = "grow" | "fade";++export interface BarProps {+ /** Key in data to use for y values */+ dataKey: string;+ /** Fill color for the bar. Can be a color, gradient url, or pattern url. Default: var(--chart-line-primary) */+ fill?: string;+ /** Color for tooltip dot. Use when fill is a gradient/pattern. Default: uses fill value */+ stroke?: string;+ /** Line cap style for bar ends: "round", "butt", or a number for custom radius. Default: "round" */+ lineCap?: BarLineCap;+ /** Whether to animate the bars. Default: true */+ animate?: boolean;+ /** Animation type: "grow" (height) or "fade" (opacity + blur). Default: "grow" */+ animationType?: BarAnimationType;+ /** Opacity when not hovered (when another bar is hovered). Default: 0.3 */+ fadedOpacity?: number;+ /** Stagger delay between bars in seconds. Auto-calculated if not provided. */+ staggerDelay?: number;+ /** Gap between stacked bars in pixels. Default: 0 */+ stackGap?: number;+ /** Gap between grouped bars in pixels. Default: 4 */+ groupGap?: number;+}++interface BarInnerProps extends BarProps {+ barScale: ScaleBand<string>;+ bandWidth: number;+ barXAccessor: (d: Record<string, unknown>) => string;+}++interface AnimatedBarProps {+ x: number;+ y: number;+ width: number;+ height: number;+ fill: string;+ rx: number;+ ry: number;+ index: number;+ isFaded: boolean;+ animationType: BarAnimationType;+ innerHeight: number;+ fadedOpacity: number;+ staggerDelay: number;+ enterTransition?: Transition;+ revealEpoch: number;+ isHorizontal: boolean;+}++function AnimatedBar({+ x,+ y,+ width,+ height,+ fill,+ rx,+ ry,+ index,+ isFaded,+ animationType,+ innerHeight,+ fadedOpacity,+ staggerDelay,+ enterTransition,+ revealEpoch,+ isHorizontal,+}: AnimatedBarProps) {+ const enterAnim = transitionWithDelay(enterTransition, index * staggerDelay);++ if (animationType === "fade") {+ return (+ <motion.rect+ animate={{+ opacity: isFaded ? fadedOpacity : 1,+ filter: "blur(0px)",+ }}+ fill={fill}+ height={height}+ initial={{ opacity: 0, filter: "blur(2px)" }}+ key={`fade-${index}-${revealEpoch}`}+ rx={rx}+ ry={ry}+ transition={enterAnim}+ width={width}+ x={x}+ y={y}+ />+ );+ }++ const initial = isHorizontal+ ? { width: 0, height, x: 0, y }+ : { width, height: 0, x, y: innerHeight };+ const target = isHorizontal+ ? { width, height, x: 0, y }+ : { width, height, x, y };++ return (+ <g+ opacity={isFaded ? fadedOpacity : 1}+ style={{ transition: "opacity 0.15s ease-in-out" }}+ >+ <motion.rect+ animate={target}+ fill={fill}+ initial={initial}+ key={`grow-${index}-${revealEpoch}`}+ rx={rx}+ ry={ry}+ transition={enterAnim}+ />+ </g>+ );+}++const BarInner = memo(function BarInner({+ dataKey,+ fill = chartCssVars.linePrimary,+ lineCap = "round",+ animate = true,+ animationType = "grow",+ fadedOpacity = 0.3,+ staggerDelay,+ stackGap = 0,+ groupGap = 4,+ barScale,+ bandWidth,+ barXAccessor,+}: BarInnerProps) {+ const {+ data,+ yScale,+ innerHeight,+ isLoaded,+ hoveredBarIndex,+ lines,+ orientation,+ stacked,+ stackOffsets,+ animationDuration,+ enterTransition,+ revealEpoch = 0,+ } = useChart();++ // Calculate stagger delay automatically if not provided+ // Total animation duration is ~1200ms, with 40% for stagger spread and 60% for bar animation+ const totalAnimDuration = animationDuration || 1100;+ const staggerSpread = totalAnimDuration * 0.4; // 40% of time for stagger spread+ const calculatedStaggerDelay =+ staggerDelay ?? (data.length > 1 ? staggerSpread / 1000 / data.length : 0);+ const uniqueId = useId();++ const isHorizontal = orientation === "horizontal";++ // Find the index of this bar series among all bar series+ const seriesIndex = useMemo(() => {+ const idx = lines.findIndex((l) => l.dataKey === dataKey);+ return idx >= 0 ? idx : 0;+ }, [lines, dataKey]);++ const seriesCount = lines.length;+ const isLastSeries = seriesIndex === seriesCount - 1;++ // Calculate the width for each bar within a group (for non-stacked)+ const barWidth = useMemo(() => {+ if (!bandWidth || seriesCount === 0) {+ return 0;+ }+ if (stacked) {+ // Stacked bars use full band width+ return bandWidth;+ }+ // Leave a gap between grouped bars (controlled by groupGap prop)+ const effectiveGroupGap = seriesCount > 1 ? groupGap : 0;+ return (bandWidth - effectiveGroupGap * (seriesCount - 1)) / seriesCount;+ }, [bandWidth, seriesCount, stacked, groupGap]);++ // Calculate corner radius based on lineCap+ const cornerRadius = useMemo(() => {+ if (typeof lineCap === "number") {+ return lineCap;+ }+ if (lineCap === "round" && barWidth) {+ return Math.min(barWidth / 2, 8);+ }+ return 0;+ }, [lineCap, barWidth]);++ return (+ <g className={`bar-series-${uniqueId}`}>+ {data.map((d, i) => {+ const value = d[dataKey];+ if (typeof value !== "number") {+ return null;+ }++ const categoryValue = barXAccessor(d);+ const bandPos = barScale(categoryValue) ?? 0;++ let x: number;+ let y: number;+ let barHeight: number;+ let barW: number;++ if (isHorizontal) {+ // Horizontal bars: category on y-axis, value on x-axis+ const valuePos = yScale(value) ?? 0;+ barW = valuePos; // Width is the value position (grows from left)+ barHeight = barWidth;++ if (stacked && stackOffsets) {+ const offset = stackOffsets.get(i)?.get(dataKey) ?? 0;+ x = yScale(offset) ?? 0;+ barW = valuePos - x;+ // Apply stack gap for horizontal: shift right and reduce width+ const gapOffset = seriesIndex * stackGap;+ x += gapOffset;+ if (!isLastSeries && stackGap > 0) {+ barW = Math.max(0, barW - stackGap);+ }+ } else {+ x = 0;+ // For grouped bars, offset y position+ const effectiveGroupGap = seriesCount > 1 ? groupGap : 0;+ y = bandPos + seriesIndex * (barWidth + effectiveGroupGap);+ }+ y = stacked+ ? bandPos+ : bandPos ++ seriesIndex * (barWidth + (seriesCount > 1 ? groupGap : 0));+ } else {+ // Vertical bars: category on x-axis, value on y-axis+ const valuePos = yScale(value) ?? 0;+ barHeight = innerHeight - valuePos;+ barW = barWidth;++ if (stacked && stackOffsets) {+ const offset = stackOffsets.get(i)?.get(dataKey) ?? 0;+ const offsetY = yScale(offset) ?? innerHeight;+ // Apply stack gap: shift up and reduce height+ const gapOffset = seriesIndex * stackGap;+ y = offsetY - barHeight - gapOffset;+ // Reduce height slightly for non-last bars to create visual gap+ if (!isLastSeries && stackGap > 0) {+ barHeight = Math.max(0, barHeight - stackGap);+ }+ } else {+ y = valuePos;+ // For grouped bars, offset x position+ const effectiveGroupGap = seriesCount > 1 ? groupGap : 0;+ x = bandPos + seriesIndex * (barWidth + effectiveGroupGap);+ }+ x = stacked+ ? bandPos+ : bandPos ++ seriesIndex * (barWidth + (seriesCount > 1 ? groupGap : 0));+ }++ const isFaded = hoveredBarIndex !== null && hoveredBarIndex !== i;++ // Use categoryValue as key since it's the unique identifier from data+ const barKey = `bar-${dataKey}-${categoryValue}`;++ // Apply rounded corners:+ // - For non-stacked: always apply+ // - For stacked with gap: apply to all bars+ // - For stacked without gap: only apply to the last series+ const applyRounding = !stacked || stackGap > 0 || isLastSeries;+ const effectiveRx = applyRounding ? cornerRadius : 0;+ const effectiveRy = applyRounding ? cornerRadius : 0;++ if (animate && !isLoaded) {+ return (+ <AnimatedBar+ animationType={animationType}+ enterTransition={enterTransition}+ fadedOpacity={fadedOpacity}+ fill={fill}+ height={barHeight}+ index={i}+ innerHeight={innerHeight}+ isFaded={isFaded}+ isHorizontal={isHorizontal}+ key={barKey}+ revealEpoch={revealEpoch}+ rx={effectiveRx}+ ry={effectiveRy}+ staggerDelay={calculatedStaggerDelay}+ width={barW}+ x={x}+ y={y}+ />+ );+ }++ // Static bar after animation completes+ return (+ <rect+ fill={fill}+ height={barHeight}+ key={barKey}+ opacity={isFaded ? fadedOpacity : 1}+ rx={effectiveRx}+ ry={effectiveRy}+ style={{+ cursor: "default",+ transition: "opacity 0.15s ease-in-out",+ }}+ width={barW}+ x={x}+ y={y}+ />+ );+ })}+ </g>+ );+});++export function Bar(props: BarProps) {+ const { barScale, bandWidth, barXAccessor } = useChartStable();++ if (!(barScale && bandWidth && barXAccessor)) {+ console.warn("Bar component must be used within a BarChart");+ return null;+ }++ return (+ <BarInner+ {...props}+ bandWidth={bandWidth}+ barScale={barScale}+ barXAccessor={barXAccessor}+ />+ );+}++Bar.displayName = "Bar";++export default Bar;diff --git a/apps/start/src/components/charts/chart-config-context.tsx b/apps/start/src/components/charts/chart-config-context.tsxnew file mode 100644index 000000000..779b1d3c8--- /dev/null+++ b/apps/start/src/components/charts/chart-config-context.tsx@@ -0,0 +1,53 @@+"use client";++import { createContext, type ReactNode, useContext, useMemo } from "react";++export interface SpringConfig {+ stiffness: number;+ damping: number;+}++export interface ChartConfigValue {+ /** Crosshair indicator, tooltip dot, date pill. */+ tooltipSpring: SpringConfig;+ /** Floating tooltip panel. */+ tooltipBoxSpring: SpringConfig;+ /** Line/area hover-highlight band (x + width). */+ highlightSpring: SpringConfig;+}++export const DEFAULT_CHART_CONFIG: ChartConfigValue = {+ tooltipSpring: { stiffness: 300, damping: 30 },+ tooltipBoxSpring: { stiffness: 100, damping: 20 },+ highlightSpring: { stiffness: 180, damping: 28 },+};++const ChartConfigContext = createContext<ChartConfigValue | null>(null);++export interface ChartConfigProviderProps {+ value?: Partial<ChartConfigValue>;+ children: ReactNode;+}++export function ChartConfigProvider({+ value,+ children,+}: ChartConfigProviderProps) {+ const merged = useMemo<ChartConfigValue>(+ () => ({+ ...DEFAULT_CHART_CONFIG,+ ...value,+ }),+ [value]+ );++ return (+ <ChartConfigContext.Provider value={merged}>+ {children}+ </ChartConfigContext.Provider>+ );+}++export function useChartConfig(): ChartConfigValue {+ return useContext(ChartConfigContext) ?? DEFAULT_CHART_CONFIG;+}diff --git a/apps/start/src/components/charts/chart-context.tsx b/apps/start/src/components/charts/chart-context.tsxnew file mode 100644index 000000000..703c57099--- /dev/null+++ b/apps/start/src/components/charts/chart-context.tsx@@ -0,0 +1,361 @@+"use client";++import type { scaleBand, scaleLinear, scaleTime } from "@visx/scale";++type ScaleLinear<Output, _Input = number> = ReturnType<+ typeof scaleLinear<Output>+>;+type ScaleTime<Output, _Input = Date | number> = ReturnType<+ typeof scaleTime<Output>+>;+type ScaleBand<Domain extends { toString(): string }> = ReturnType<+ typeof scaleBand<Domain>+>;++import type { Transition } from "motion/react";+import {+ createContext,+ type Dispatch,+ type ReactNode,+ type RefObject,+ type SetStateAction,+ useContext,+ useMemo,+} from "react";+import type { ChartSelection } from "./use-chart-interaction";++// CSS variable references for theming+export const chartCssVars = {+ background: "var(--chart-background)",+ foreground: "var(--chart-foreground)",+ foregroundMuted: "var(--chart-foreground-muted)",+ label: "var(--chart-label)",+ linePrimary: "var(--chart-line-primary)",+ lineSecondary: "var(--chart-line-secondary)",+ crosshair: "var(--chart-crosshair)",+ grid: "var(--chart-grid)",+ indicatorColor: "var(--chart-indicator-color)",+ indicatorSecondaryColor: "var(--chart-indicator-secondary-color)",+ markerBackground: "var(--chart-marker-background)",+ markerBorder: "var(--chart-marker-border)",+ markerForeground: "var(--chart-marker-foreground)",+ badgeBackground: "var(--chart-marker-badge-background)",+ badgeForeground: "var(--chart-marker-badge-foreground)",+ segmentBackground: "var(--chart-segment-background)",+ segmentLine: "var(--chart-segment-line)",+};++/** Default scatter series colors from the chart palette (`--chart-1` … `--chart-5`). */+export const defaultScatterColors = [+ "var(--chart-1)",+ "var(--chart-2)",+ "var(--chart-3)",+ "var(--chart-4)",+ "var(--chart-5)",+] as const;++export interface Margin {+ top: number;+ right: number;+ bottom: number;+ left: number;+}++export interface TooltipData {+ /** The data point being hovered */+ point: Record<string, unknown>;+ /** Index in the data array */+ index: number;+ /** X position in pixels (relative to chart area) */+ x: number;+ /** Y positions for each line, keyed by dataKey */+ yPositions: Record<string, number>;+ /** X positions for each series (for grouped bars), keyed by dataKey */+ xPositions?: Record<string, number>;+}++export interface LineConfig {+ dataKey: string;+ stroke: string;+ strokeWidth: number;+}++/**+ * Hover/selection state — every field here changes on mouse movement.+ * Lives in its own context so cold consumers (Grid, YAxis, PatternArea, …)+ * can subscribe to the stable slice and skip re-rendering on every hover.+ */+export interface ChartHoverContextValue {+ // Tooltip state+ tooltipData: TooltipData | null;+ setTooltipData: Dispatch<SetStateAction<TooltipData | null>>;++ // Selection state (optional - only present when useChartInteraction is used)+ /** Current drag/pinch selection range */+ selection?: ChartSelection | null;+ /** Clear the current selection */+ clearSelection?: () => void;++ // Bar chart hover (optional - only present in BarChart)+ /** Index of currently hovered bar */+ hoveredBarIndex?: number | null;+ /** Setter for hovered bar index */+ setHoveredBarIndex?: (index: number | null) => void;++ // Candlestick hover (optional - only present in CandlestickChart)+ /** Index of currently hovered candle */+ hoveredCandleIndex?: number | null;+ /** Setter for hovered candle index */+ setHoveredCandleIndex?: (index: number | null) => void;+}++export interface ChartContextValue extends ChartHoverContextValue {+ // Data+ data: Record<string, unknown>[];+ /** Decimated subset for SVG path rendering; equals `data` when no decimation is needed. */+ renderData: Record<string, unknown>[];++ // Scales+ xScale: ScaleTime<number, number>;+ yScale: ScaleLinear<number, number>;++ // Dimensions+ width: number;+ height: number;+ innerWidth: number;+ innerHeight: number;+ margin: Margin;++ // Column width for spacing calculations+ columnWidth: number;++ // Container ref for portals+ containerRef: RefObject<HTMLDivElement | null>;++ // Line configurations (extracted from children)+ lines: LineConfig[];++ // Animation state+ isLoaded: boolean;+ animationDuration: number;+ /** CSS easing for clip-reveal / line draw (cartesian charts). */+ animationEasing?: string;+ /** Motion enter transition (spring or tween) — drives clip reveal when spring. */+ enterTransition?: Transition;+ /** Increments when enter animation should replay. */+ revealEpoch?: number;++ // X accessor - how to get the x value from data points+ xAccessor: (d: Record<string, unknown>) => Date;++ // Pre-computed date labels for ticker animation+ dateLabels: string[];++ // Bar chart specific (optional - only present in BarChart)+ /** Band scale for categorical x-axis (bar charts) */+ barScale?: ScaleBand<string>;+ /** Width of each bar band */+ bandWidth?: number;+ /** X accessor for bar charts (returns string instead of Date) */+ barXAccessor?: (d: Record<string, unknown>) => string;+ /** Bar chart orientation */+ orientation?: "vertical" | "horizontal";+ /** Whether bars are stacked */+ stacked?: boolean;+ /** Stack offsets: Map of data index -> Map of dataKey -> cumulative offset */+ stackOffsets?: Map<number, Map<string, number>>;++ // ComposedChart + SeriesBar (optional)+ /** `SeriesBar` dataKeys in tree order, for grouped columns at each x */+ composedBarDataKeys?: string[];+ /** Target bar width in px (Recharts `barSize` style). */+ composedBarSize?: number;+ /** Max bar width in px (Recharts `maxBarSize`). */+ composedMaxBarSize?: number;+ /** Gap between grouped `SeriesBar` columns in px. */+ composedBarGap?: number;+ /** When true, `SeriesBar` segments stack in child order at each x. */+ composedStacked?: boolean;+ /** Per-row cumulative offsets for stacked `SeriesBar` (data index → dataKey → offset). */+ composedStackOffsets?: Map<number, Map<string, number>>;+ /** Vertical gap in px between stacked `SeriesBar` segments. Default: 0 */+ composedStackGap?: number;+}++/**+ * Stable slice of the chart context — everything that doesn't change on hover+ * (data, scales, dimensions, animation state, layout config). Consumers that+ * subscribe via `useChartStable()` skip re-renders on every mouse move.+ */+export type ChartStableContextValue = Omit<+ ChartContextValue,+ keyof ChartHoverContextValue+>;++const ChartStableContext = createContext<ChartStableContextValue | null>(null);+const ChartHoverContext = createContext<ChartHoverContextValue | null>(null);++/**+ * Splits the merged `value` into a stable slice and a volatile hover slice,+ * publishing each to its own context. Each slice is memoized on its own+ * field identities, so changing `tooltipData` does not bust the stable+ * slice — consumers of `useChartStable()` skip re-renders on hover.+ */+export function ChartProvider({+ children,+ value,+}: {+ children: ReactNode;+ value: ChartContextValue;+}) {+ const stable = useMemo<ChartStableContextValue>(+ () => ({+ data: value.data,+ renderData: value.renderData,+ xScale: value.xScale,+ yScale: value.yScale,+ width: value.width,+ height: value.height,+ innerWidth: value.innerWidth,+ innerHeight: value.innerHeight,+ margin: value.margin,+ columnWidth: value.columnWidth,+ containerRef: value.containerRef,+ lines: value.lines,+ isLoaded: value.isLoaded,+ animationDuration: value.animationDuration,+ animationEasing: value.animationEasing,+ enterTransition: value.enterTransition,+ revealEpoch: value.revealEpoch,+ xAccessor: value.xAccessor,+ dateLabels: value.dateLabels,+ barScale: value.barScale,+ bandWidth: value.bandWidth,+ barXAccessor: value.barXAccessor,+ orientation: value.orientation,+ stacked: value.stacked,+ stackOffsets: value.stackOffsets,+ composedBarDataKeys: value.composedBarDataKeys,+ composedBarSize: value.composedBarSize,+ composedMaxBarSize: value.composedMaxBarSize,+ composedBarGap: value.composedBarGap,+ composedStacked: value.composedStacked,+ composedStackOffsets: value.composedStackOffsets,+ composedStackGap: value.composedStackGap,+ }),+ [+ value.data,+ value.renderData,+ value.xScale,+ value.yScale,+ value.width,+ value.height,+ value.innerWidth,+ value.innerHeight,+ value.margin,+ value.columnWidth,+ value.containerRef,+ value.lines,+ value.isLoaded,+ value.animationDuration,+ value.animationEasing,+ value.enterTransition,+ value.revealEpoch,+ value.xAccessor,+ value.dateLabels,+ value.barScale,+ value.bandWidth,+ value.barXAccessor,+ value.orientation,+ value.stacked,+ value.stackOffsets,+ value.composedBarDataKeys,+ value.composedBarSize,+ value.composedMaxBarSize,+ value.composedBarGap,+ value.composedStacked,+ value.composedStackOffsets,+ value.composedStackGap,+ ]+ );++ const hover = useMemo<ChartHoverContextValue>(+ () => ({+ tooltipData: value.tooltipData,+ setTooltipData: value.setTooltipData,+ selection: value.selection,+ clearSelection: value.clearSelection,+ hoveredBarIndex: value.hoveredBarIndex,+ setHoveredBarIndex: value.setHoveredBarIndex,+ hoveredCandleIndex: value.hoveredCandleIndex,+ setHoveredCandleIndex: value.setHoveredCandleIndex,+ }),+ [+ value.tooltipData,+ value.setTooltipData,+ value.selection,+ value.clearSelection,+ value.hoveredBarIndex,+ value.setHoveredBarIndex,+ value.hoveredCandleIndex,+ value.setHoveredCandleIndex,+ ]+ );++ return (+ <ChartStableContext.Provider value={stable}>+ <ChartHoverContext.Provider value={hover}>+ {children}+ </ChartHoverContext.Provider>+ </ChartStableContext.Provider>+ );+}++/**+ * Stable slice — data, scales, dimensions, animation state, layout config.+ * Subscribers skip re-renders on hover (the hover slice lives in a separate+ * context). Prefer this in cold consumers like axes, grid, pattern fills.+ */+export function useChartStable(): ChartStableContextValue {+ const context = useContext(ChartStableContext);+ if (!context) {+ throw new Error(+ "useChartStable must be used within a ChartProvider. " ++ "Make sure your component is wrapped in <LineChart>, <AreaChart>, <BarChart>, or <ComposedChart>."+ );+ }+ return context;+}++/**+ * Hover slice — tooltipData, selection, hovered bar / candle indices.+ * Subscribers re-render on every mouse move. Use only when the component+ * actually reads hover state.+ */+export function useChartHover(): ChartHoverContextValue {+ const context = useContext(ChartHoverContext);+ if (!context) {+ throw new Error(+ "useChartHover must be used within a ChartProvider. " ++ "Make sure your component is wrapped in <LineChart>, <AreaChart>, <BarChart>, or <ComposedChart>."+ );+ }+ return context;+}++/**+ * Merged stable + hover context. Convenient for components that need both,+ * but re-renders on every hover (because hover changes). Prefer+ * `useChartStable()` or `useChartHover()` for hot consumers that only need+ * one slice.+ */+export function useChart(): ChartContextValue {+ const stable = useChartStable();+ const hover = useChartHover();+ // Identity changes on every hover (hover is the volatile slice) — that's+ // fine for consumers using this merged hook; they explicitly opted in to+ // re-rendering on hover.+ return { ...stable, ...hover };+}++export default ChartStableContext;diff --git a/apps/start/src/components/charts/chart-defs.ts b/apps/start/src/components/charts/chart-defs.tsnew file mode 100644index 000000000..6dd941a60--- /dev/null+++ b/apps/start/src/components/charts/chart-defs.ts@@ -0,0 +1,72 @@+import {+ Children,+ isValidElement,+ type ReactElement,+ type ReactNode,+} from "react";++export function getChartChildComponentName(child: ReactElement): string {+ const childType = child.type as { displayName?: string; name?: string };+ return typeof child.type === "function"+ ? childType.displayName || childType.name || ""+ : "";+}++const VISX_PATTERN_COMPONENT_NAMES = new Set([+ "Lines",+ "Circles",+ "Waves",+ "Hexagons",+ "Path",+ "Pattern",+]);++/** @visx/pattern default exports use short names (e.g. `Lines`); also match *Pattern* displayNames. */+export function isPatternDefComponent(child: ReactElement): boolean {+ const name = getChartChildComponentName(child);+ return name.includes("Pattern") || VISX_PATTERN_COMPONENT_NAMES.has(name);+}++export function isGradientDefComponent(child: ReactElement): boolean {+ const name = getChartChildComponentName(child);+ return (+ name.includes("Gradient") ||+ name === "LinearGradient" ||+ name === "RadialGradient"+ );+}++export function isChartDefsComponent(child: ReactElement): boolean {+ return isPatternDefComponent(child) || isGradientDefComponent(child);+}++/** Split hoisted defs: @visx/pattern nodes already wrap `<defs>` and render at the svg root. */+export function partitionChartDefNodes(defNodes: ReactElement[]): {+ patternDefNodes: ReactElement[];+ gradientDefNodes: ReactElement[];+} {+ const patternDefNodes: ReactElement[] = [];+ const gradientDefNodes: ReactElement[] = [];++ for (const node of defNodes) {+ if (isPatternDefComponent(node)) {+ patternDefNodes.push(node);+ } else {+ gradientDefNodes.push(node);+ }+ }++ return { patternDefNodes, gradientDefNodes };+}++export function collectChartDefsChildren(children: ReactNode): ReactElement[] {+ const defNodes: ReactElement[] = [];++ Children.forEach(children, (child) => {+ if (isValidElement(child) && isChartDefsComponent(child)) {+ defNodes.push(child);+ }+ });++ return defNodes;+}diff --git a/apps/start/src/components/charts/chart-formatters.ts b/apps/start/src/components/charts/chart-formatters.tsnew file mode 100644index 000000000..d8b007047--- /dev/null+++ b/apps/start/src/components/charts/chart-formatters.ts@@ -0,0 +1,20 @@+export const shortDateFmt = new Intl.DateTimeFormat("en-US", {+ month: "short",+ day: "numeric",+});++export const weekdayDateFmt = new Intl.DateTimeFormat("en-US", {+ weekday: "short",+ month: "short",+ day: "numeric",+});++export const hmsTimeFmt = new Intl.DateTimeFormat("en-US", {+ hour: "2-digit",+ minute: "2-digit",+ second: "2-digit",+ hour12: false,+});++// `Intl.NumberFormat.prototype.format` is a bound getter — safe to extract.+export const intFmt = new Intl.NumberFormat("en-US").format;diff --git a/apps/start/src/components/charts/chart-reveal-clip.tsx b/apps/start/src/components/charts/chart-reveal-clip.tsxnew file mode 100644index 000000000..3a8591a0c--- /dev/null+++ b/apps/start/src/components/charts/chart-reveal-clip.tsx@@ -0,0 +1,48 @@+"use client";++import type { Transition } from "motion/react";+import { motion } from "motion/react";+import { clipRevealTransition } from "./animation";++export interface ChartRevealClipProps {+ clipPathId: string;+ height: number;+ targetWidth: number;+ enterTransition?: Transition;+ /** Bumps when motion settings change to replay the reveal. */+ revealEpoch: number;+ /** Extra inset around the clip rect so edge glyphs are not cut off. */+ padding?: number;+}++/**+ * Left-to-right clip reveal for cartesian series.+ * Grows clip rect width from 0 → full (true LTR; scaleX is avoided — it reveals from center).+ */+export function ChartRevealClip({+ clipPathId,+ height,+ targetWidth,+ enterTransition,+ revealEpoch,+ padding = 0,+}: ChartRevealClipProps) {+ const transition = clipRevealTransition(enterTransition);+ const paddedWidth = Math.max(0, targetWidth + padding * 2);+ const paddedHeight = height + padding * 2;++ return (+ <clipPath id={clipPathId}>+ <motion.rect+ animate={{ width: paddedWidth }}+ height={paddedHeight}+ initial={{ width: 0 }}+ key={`reveal-${revealEpoch}`}+ transition={transition}+ width={paddedWidth}+ x={-padding}+ y={-padding}+ />+ </clipPath>+ );+}diff --git a/apps/start/src/components/charts/chart-stat-flow.tsx b/apps/start/src/components/charts/chart-stat-flow.tsxnew file mode 100644index 000000000..93b5ff9a3--- /dev/null+++ b/apps/start/src/components/charts/chart-stat-flow.tsx@@ -0,0 +1,76 @@+"use client";++import NumberFlow from "@number-flow/react";+import type { ReactNode } from "react";+import { cn } from "@/lib/utils";++/** Subset of `Intl.NumberFormatOptions` supported by NumberFlow */+export interface ChartStatFlowFormat {+ notation?: "standard" | "compact";+ compactDisplay?: "short" | "long";+ minimumFractionDigits?: number;+ maximumFractionDigits?: number;+ minimumIntegerDigits?: number;+ minimumSignificantDigits?: number;+ maximumSignificantDigits?: number;+ style?: "decimal" | "percent" | "currency";+ currency?: string;+ currencyDisplay?: "symbol" | "narrowSymbol" | "code" | "name";+ unit?: string;+ unitDisplay?: "short" | "long" | "narrow";+}++export const defaultChartStatFlowFormat: ChartStatFlowFormat = {+ notation: "standard",+ maximumFractionDigits: 0,+};++export interface ChartStatFlowProps {+ value: number;+ label: string;+ formatOptions?: ChartStatFlowFormat;+ prefix?: string;+ suffix?: string;+ valueClassName?: string;+ labelClassName?: string;+ icon?: ReactNode;+}++/**+ * Shared value + label stack using NumberFlow (same layout as pie / ring centers).+ * Parent should provide flex alignment and sizing when needed.+ */+export function ChartStatFlow({+ value,+ label,+ formatOptions = defaultChartStatFlowFormat,+ prefix,+ suffix,+ valueClassName = "text-2xl font-bold",+ labelClassName = "text-xs",+ icon,+}: ChartStatFlowProps) {+ return (+ <>+ {icon ? (+ <div className="mb-2 flex h-12 w-12 items-center justify-center rounded-full bg-muted/50">+ {icon}+ </div>+ ) : null}+ <span className={cn("text-foreground tabular-nums", valueClassName)}>+ <NumberFlow+ format={formatOptions}+ prefix={prefix}+ suffix={suffix}+ value={value}+ willChange+ />+ </span>+ <span className={cn("mt-0.5 text-chart-label", labelClassName)}>+ {label}+ </span>+ </>+ );+}++ChartStatFlow.displayName = "ChartStatFlow";diff --git a/apps/start/src/components/charts/composed-chart.tsx b/apps/start/src/components/charts/composed-chart.tsxnew file mode 100644index 000000000..77fe6b537--- /dev/null+++ b/apps/start/src/components/charts/composed-chart.tsx@@ -0,0 +1,329 @@+"use client";++import { ParentSize } from "@visx/responsive";+import type { Transition } from "motion/react";+import {+ Children,+ isValidElement,+ type ReactElement,+ type ReactNode,+ useMemo,+ useRef,+} from "react";+import { cn } from "@/lib/utils";+import { Area, type AreaProps } from "./area";+import type { LineConfig, Margin } from "./chart-context";+import { Line, type LineProps } from "./line";+import { SeriesBar, type SeriesBarProps } from "./series-bar";+import { TimeSeriesChartInner } from "./time-series-chart-shell";++export interface ComposedChartProps {+ /** Data array — each row typically has a date and multiple numeric series */+ data: Record<string, unknown>[];+ /** Key for the x-axis (time). Default: "date" */+ xDataKey?: string;+ margin?: Partial<Margin>;+ animationDuration?: number;+ animationEasing?: string;+ enterTransition?: Transition;+ /** Signature of motion URL state — triggers reveal replay when it changes. */+ revealSignature?: string;+ aspectRatio?: string;+ className?: string;+ children: ReactNode;+ /** Target bar width in px (Recharts-style `barSize`). */+ barSize?: number;+ /** Maximum bar width in px (`maxBarSize`). */+ maxBarSize?: number;+ /** Gap between grouped `SeriesBar` series in px. Default: 4 */+ barGap?: number;+ /** Stack `SeriesBar` segments in child order at each x (line/area are not stacked). */+ stacked?: boolean;+ /** Gap in px between stacked segments. Default: 0 */+ stackGap?: number;+}++const DEFAULT_MARGIN: Margin = { top: 40, right: 40, bottom: 40, left: 40 };++function getChildComponentName(child: ReactElement): string {+ const childType = child.type as { displayName?: string; name?: string };+ return typeof child.type === "function"+ ? childType.displayName || childType.name || ""+ : "";+}++function upsertLineConfig(lines: LineConfig[], config: LineConfig): void {+ const index = lines.findIndex((line) => line.dataKey === config.dataKey);+ if (index === -1) {+ lines.push(config);+ return;+ }+ // Area+Line pairs share a dataKey — keep the later config (Line over Area).+ lines[index] = config;+}++function tryAppendSeriesBar(+ child: ReactElement,+ lines: LineConfig[],+ barDataKeys: string[]+): boolean {+ const name = getChildComponentName(child);+ if (!(child.type === SeriesBar || name === "SeriesBar")) {+ return false;+ }+ const props = child.props as SeriesBarProps;+ if (!props.dataKey) {+ return true;+ }+ barDataKeys.push(props.dataKey);+ upsertLineConfig(lines, {+ dataKey: props.dataKey,+ stroke: props.stroke || props.fill || "var(--chart-line-primary)",+ strokeWidth: 0,+ });+ return true;+}++function tryAppendLine(child: ReactElement, lines: LineConfig[]): boolean {+ const name = getChildComponentName(child);+ if (!(child.type === Line || name === "Line")) {+ return false;+ }+ const props = child.props as LineProps;+ if (props.dataKey) {+ upsertLineConfig(lines, {+ dataKey: props.dataKey,+ stroke: props.stroke || "var(--chart-line-primary)",+ strokeWidth: props.strokeWidth ?? 2.5,+ });+ }+ return true;+}++function tryAppendArea(child: ReactElement, lines: LineConfig[]): boolean {+ const name = getChildComponentName(child);+ if (!(child.type === Area || name === "Area")) {+ return false;+ }+ const props = child.props as AreaProps;+ if (props.dataKey) {+ upsertLineConfig(lines, {+ dataKey: props.dataKey,+ stroke: props.stroke || props.fill || "var(--chart-line-primary)",+ strokeWidth: props.strokeWidth ?? 2,+ });+ }+ return true;+}++function extractComposedSeries(children: ReactNode): {+ lines: LineConfig[];+ barDataKeys: string[];+} {+ const lines: LineConfig[] = [];+ const barDataKeys: string[] = [];++ Children.forEach(children, (child) => {+ if (!isValidElement(child)) {+ return;+ }+ if (tryAppendSeriesBar(child, lines, barDataKeys)) {+ return;+ }+ if (tryAppendLine(child, lines)) {+ return;+ }+ tryAppendArea(child, lines);+ });++ return { lines, barDataKeys };+}++function computeComposedYScaleDomainMax(+ data: Record<string, unknown>[],+ lines: LineConfig[],+ barDataKeys: string[]+): number | undefined {+ const barSet = new Set(barDataKeys);+ let max = 0;+ for (const d of data) {+ let barSum = 0;+ for (const k of barDataKeys) {+ const v = d[k];+ if (typeof v === "number") {+ barSum += v;+ }+ }+ let rowMaxOther = 0;+ for (const line of lines) {+ if (barSet.has(line.dataKey)) {+ continue;+ }+ const v = d[line.dataKey];+ if (typeof v === "number") {+ rowMaxOther = Math.max(rowMaxOther, v);+ }+ }+ max = Math.max(max, barSum, rowMaxOther);+ }+ return max > 0 ? max : undefined;+}++interface ChartInnerProps {+ width: number;+ height: number;+ data: Record<string, unknown>[];+ xDataKey: string;+ margin: Margin;+ animationDuration: number;+ animationEasing?: string;+ enterTransition?: Transition;+ revealSignature?: string;+ children: ReactNode;+ containerRef: React.RefObject<HTMLDivElement | null>;+ barSize?: number;+ maxBarSize?: number;+ barGap?: number;+ stacked?: boolean;+ stackGap?: number;+}++function ChartInner({+ width,+ height,+ data,+ xDataKey,+ margin,+ animationDuration,+ animationEasing,+ enterTransition,+ revealSignature,+ children,+ containerRef,+ barSize,+ maxBarSize,+ barGap,+ stacked = false,+ stackGap = 0,+}: ChartInnerProps) {+ const { lines, barDataKeys } = useMemo(+ () => extractComposedSeries(children),+ [children]+ );++ const composedStackOffsets = useMemo(() => {+ if (!(stacked && barDataKeys.length > 0)) {+ return undefined;+ }+ const offsets = new Map<number, Map<string, number>>();+ for (let i = 0; i < data.length; i++) {+ const d = data[i];+ if (!d) {+ continue;+ }+ const pointOffsets = new Map<string, number>();+ let cumulative = 0;+ for (const key of barDataKeys) {+ pointOffsets.set(key, cumulative);+ const v = d[key];+ if (typeof v === "number") {+ cumulative += v;+ }+ }+ offsets.set(i, pointOffsets);+ }+ return offsets;+ }, [data, barDataKeys, stacked]);++ const yScaleDomainMax = useMemo(+ () =>+ stacked && barDataKeys.length > 0+ ? computeComposedYScaleDomainMax(data, lines, barDataKeys)+ : undefined,+ [data, lines, barDataKeys, stacked]+ );++ return (+ <TimeSeriesChartInner+ animationDuration={animationDuration}+ animationEasing={animationEasing}+ clipPathId="composed-chart-grow-clip"+ composedBarDataKeys={barDataKeys.length > 0 ? barDataKeys : undefined}+ composedBarGap={barGap}+ composedBarSize={barSize}+ composedMaxBarSize={maxBarSize}+ composedStacked={stacked}+ composedStackGap={stackGap}+ composedStackOffsets={composedStackOffsets}+ containerRef={containerRef}+ data={data}+ enterTransition={enterTransition}+ height={height}+ lines={lines}+ margin={margin}+ revealSignature={revealSignature}+ width={width}+ xDataKey={xDataKey}+ yScaleDomainMax={yScaleDomainMax}+ >+ {children}+ </TimeSeriesChartInner>+ );+}++export function ComposedChart({+ data,+ xDataKey = "date",+ margin: marginProp,+ animationDuration = 1100,+ animationEasing,+ enterTransition,+ revealSignature,+ aspectRatio = "2 / 1",+ className = "",+ children,+ barSize,+ maxBarSize,+ barGap = 4,+ stacked = false,+ stackGap = 0,+}: ComposedChartProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const margin = { ...DEFAULT_MARGIN, ...marginProp };++ return (+ <div+ className={cn("relative w-full", className)}+ ref={containerRef}+ style={{ aspectRatio, touchAction: "none" }}+ >+ <ParentSize debounceTime={10}>+ {({ width, height }) => (+ <ChartInner+ animationDuration={animationDuration}+ animationEasing={animationEasing}+ barGap={barGap}+ barSize={barSize}+ containerRef={containerRef}+ data={data}+ enterTransition={enterTransition}+ height={height}+ margin={margin}+ maxBarSize={maxBarSize}+ revealSignature={revealSignature}+ stacked={stacked}+ stackGap={stackGap}+ width={width}+ xDataKey={xDataKey}+ >+ {children}+ </ChartInner>+ )}+ </ParentSize>+ </div>+ );+}++ComposedChart.displayName = "ComposedChart";++export default ComposedChart;diff --git a/apps/start/src/components/charts/dash-tail-stroke.tsx b/apps/start/src/components/charts/dash-tail-stroke.tsxnew file mode 100644index 000000000..becbca5fa--- /dev/null+++ b/apps/start/src/components/charts/dash-tail-stroke.tsx@@ -0,0 +1,75 @@+"use client";++import { useId } from "react";++export interface DashTailStrokeProps {+ /** SVG path `d` for the full series (single curved path). */+ pathD: string | null;+ /** Total length of `pathD` in user units. */+ pathLength: number;+ /** Path length at which the dashed tail begins. */+ dashStartLength: number;+ /** X coordinate (chart inner space) where the tail clip begins. */+ dashStartX: number;+ innerWidth: number;+ innerHeight: number;+ /** Stroke paint — solid color or gradient url. */+ stroke: string;+ strokeWidth: number;+ dashArray: string;+}++export function DashTailStroke({+ pathD,+ pathLength,+ dashStartLength,+ dashStartX,+ innerWidth,+ innerHeight,+ stroke,+ strokeWidth,+ dashArray,+}: DashTailStrokeProps) {+ const clipPathId = useId().replace(/:/g, "");++ if (!pathD || pathLength <= 0 || dashStartLength >= pathLength) {+ return null;+ }++ const pad = strokeWidth * 2;+ const tailWidth = Math.max(0, innerWidth - dashStartX + pad);++ return (+ <>+ <defs>+ <clipPath id={clipPathId}>+ <rect+ height={innerHeight + pad}+ width={tailWidth}+ x={dashStartX - strokeWidth}+ y={-strokeWidth}+ />+ </clipPath>+ </defs>+ {/* Solid head — same curved path, gradient/fade preserved */}+ <path+ d={pathD}+ fill="none"+ stroke={stroke}+ strokeDasharray={`${dashStartLength} ${Math.max(1, pathLength - dashStartLength)}`}+ strokeLinecap="round"+ strokeWidth={strokeWidth}+ />+ {/* Dashed tail — clipped to x ≥ dashStartX so dashes follow the curve */}+ <path+ clipPath={`url(#${clipPathId})`}+ d={pathD}+ fill="none"+ stroke={stroke}+ strokeDasharray={dashArray}+ strokeLinecap="round"+ strokeWidth={strokeWidth}+ />+ </>+ );+}diff --git a/apps/start/src/components/charts/decimate-time-series.ts b/apps/start/src/components/charts/decimate-time-series.tsnew file mode 100644index 000000000..7749a0c2a--- /dev/null+++ b/apps/start/src/components/charts/decimate-time-series.ts@@ -0,0 +1,136 @@+export function decimateTimeSeries<T extends Record<string, unknown>>(+ data: T[],+ maxPoints: number,+ valueKeys: string[] = []+): T[] {+ const len = data.length;+ if (maxPoints >= len || maxPoints < 3) {+ return data;+ }++ const getY = (point: T, index: number): number => {+ if (valueKeys.length === 0) {+ for (const val of Object.values(point)) {+ if (typeof val === "number") {+ return val;+ }+ }+ return index;+ }++ let sum = 0;+ let count = 0;+ for (const key of valueKeys) {+ const val = point[key];+ if (typeof val === "number") {+ sum += val;+ count++;+ }+ }+ return count > 0 ? sum / count : index;+ };++ const sampled: T[] = [data[0] as T];+ const bucketSize = (len - 2) / (maxPoints - 2);+ let previousIndex = 0;++ for (let i = 0; i < maxPoints - 2; i++) {+ const rangeStart = Math.floor((i + 1) * bucketSize) + 1;+ const rangeEnd = Math.min(Math.floor((i + 2) * bucketSize) + 1, len - 1);++ const nextRangeStart = Math.floor((i + 2) * bucketSize) + 1;+ const nextRangeEnd = Math.min(Math.floor((i + 3) * bucketSize) + 1, len);+ const nextCount = Math.max(0, nextRangeEnd - nextRangeStart);++ let avgX = len - 1;+ let avgY = getY(data[len - 1] as T, len - 1);+ if (nextCount > 0) {+ avgX = 0;+ avgY = 0;+ for (let j = nextRangeStart; j < nextRangeEnd; j++) {+ avgX += j;+ avgY += getY(data[j] as T, j);+ }+ avgX /= nextCount;+ avgY /= nextCount;+ }++ const pointA = data[previousIndex] as T;+ const ax = previousIndex;+ const ay = getY(pointA, previousIndex);++ let maxArea = -1;+ let maxIndex = rangeStart;++ for (let j = rangeStart; j < rangeEnd; j++) {+ const area =+ Math.abs(+ (ax - avgX) * (getY(data[j] as T, j) - ay) - (ax - j) * (avgY - ay)+ ) * 0.5;+ if (area > maxArea) {+ maxArea = area;+ maxIndex = j;+ }+ }++ sampled.push(data[maxIndex] as T);+ previousIndex = maxIndex;+ }++ sampled.push(data[len - 1] as T);+ return sampled;+}++/** ~1.5 points per pixel — enough for crisp curves without over-drawing. */+export function maxRenderPointsForWidth(innerWidth: number): number {+ return Math.max(64, Math.ceil(innerWidth * 1.5));+}++/** Bucket OHLC rows into fewer candles while preserving high/low extremes. */+export function decimateOhlcData<T extends Record<string, unknown>>(+ data: T[],+ maxPoints: number+): T[] {+ const len = data.length;+ if (maxPoints >= len || maxPoints < 2) {+ return data;+ }++ const bucketSize = len / maxPoints;+ const sampled: T[] = [];++ for (let i = 0; i < maxPoints; i++) {+ const start = Math.floor(i * bucketSize);+ const end = Math.min(len, Math.floor((i + 1) * bucketSize));+ if (start >= end) {+ continue;+ }++ const bucket = data.slice(start, end);+ const first = bucket[0] as T;+ const last = bucket.at(-1) as T;++ let high = Number.NEGATIVE_INFINITY;+ let low = Number.POSITIVE_INFINITY;+ for (const row of bucket) {+ const rowHigh = row.high;+ const rowLow = row.low;+ if (typeof rowHigh === "number" && rowHigh > high) {+ high = rowHigh;+ }+ if (typeof rowLow === "number" && rowLow < low) {+ low = rowLow;+ }+ }++ sampled.push({+ ...last,+ open: first.open,+ high: Number.isFinite(high) ? high : last.high,+ low: Number.isFinite(low) ? low : last.low,+ close: last.close,+ } as T);+ }++ return sampled;+}diff --git a/apps/start/src/components/charts/fade-edges.ts b/apps/start/src/components/charts/fade-edges.tsnew file mode 100644index 000000000..99cbad07b--- /dev/null+++ b/apps/start/src/components/charts/fade-edges.ts@@ -0,0 +1,41 @@+export type FadeEdges = boolean | "left" | "right";++export interface FadeSides {+ /** Whether the left edge should fade out. */+ left: boolean;+ /** Whether the right edge should fade out. */+ right: boolean;+ /** True if either side fades — use to gate gradient/mask defs. */+ any: boolean;+}++export function resolveFadeSides(fade: FadeEdges): FadeSides {+ if (fade === false) {+ return { left: false, right: false, any: false };+ }+ if (fade === "left") {+ return { left: true, right: false, any: true };+ }+ if (fade === "right") {+ return { left: false, right: true, any: true };+ }+ return { left: true, right: true, any: true };+}++export interface FadeGradientStop {+ offset: string;+ opacity: number;+}++/**+ * Stops for a horizontal fade gradient with opacity 0 at the faded side(s)+ * and opacity 1 in the middle. Matches the historic 0/15/85/100 pattern.+ */+export function fadeGradientStops(sides: FadeSides): FadeGradientStop[] {+ return [+ { offset: "0%", opacity: sides.left ? 0 : 1 },+ { offset: "15%", opacity: 1 },+ { offset: "85%", opacity: 1 },+ { offset: "100%", opacity: sides.right ? 0 : 1 },+ ];+}diff --git a/apps/start/src/components/charts/grid.tsx b/apps/start/src/components/charts/grid.tsxnew file mode 100644index 000000000..08bf38377--- /dev/null+++ b/apps/start/src/components/charts/grid.tsx@@ -0,0 +1,188 @@+"use client";++import { GridColumns, GridRows } from "@visx/grid";+import { useId } from "react";+import { chartCssVars, useChartStable } from "./chart-context";++export interface GridProps {+ /** Show horizontal grid lines. Default: true */+ horizontal?: boolean;+ /** Show vertical grid lines. Default: false */+ vertical?: boolean;+ /** Number of horizontal grid lines. Default: 5 */+ numTicksRows?: number;+ /** Number of vertical grid lines. Default: 10 */+ numTicksColumns?: number;+ /** Explicit tick values for horizontal grid lines. Overrides numTicksRows. */+ rowTickValues?: number[];+ /** Grid line stroke color. Default: var(--chart-grid) */+ stroke?: string;+ /** Grid line stroke opacity. Default: 1 */+ strokeOpacity?: number;+ /** Grid line stroke width. Default: 1 */+ strokeWidth?: number;+ /** Grid line dash array. Default: "4,4" for dashed lines */+ strokeDasharray?: string;+ /** Horizontal row values rendered with alternate styling (e.g. zero baseline). */+ highlightRowValues?: number[];+ /** Stroke for highlighted rows. Default: var(--chart-foreground-muted) */+ highlightRowStroke?: string;+ /** Stroke opacity for highlighted rows. Default: 1 */+ highlightRowStrokeOpacity?: number;+ /** Stroke width for highlighted rows. Default: 1 */+ highlightRowStrokeWidth?: number;+ /** Dash array for highlighted rows. Default: solid line */+ highlightRowStrokeDasharray?: string;+ /** Enable horizontal fade effect on grid rows (fades at left/right). Default: true */+ fadeHorizontal?: boolean;+ /** Enable vertical fade effect on grid columns (fades at top/bottom). Default: false */+ fadeVertical?: boolean;+}++export function Grid({+ horizontal = true,+ vertical = false,+ numTicksRows = 5,+ numTicksColumns = 10,+ rowTickValues,+ stroke = chartCssVars.grid,+ strokeOpacity = 1,+ strokeWidth = 1,+ strokeDasharray = "4,4",+ highlightRowValues,+ highlightRowStroke = chartCssVars.foregroundMuted,+ highlightRowStrokeOpacity = 1,+ highlightRowStrokeWidth = 1,+ highlightRowStrokeDasharray = "0",+ fadeHorizontal = true,+ fadeVertical = false,+}: GridProps) {+ const { xScale, yScale, innerWidth, innerHeight, orientation, barScale } =+ useChartStable();++ // For bar charts, determine which scale to use for grid lines+ // Horizontal bar charts: vertical grid should use yScale (value scale)+ // Vertical bar charts: horizontal grid uses yScale (value scale)+ const isHorizontalBarChart = orientation === "horizontal" && barScale;++ // For vertical grid lines in horizontal bar charts, use yScale (the value scale)+ // For time-based charts, use xScale+ const columnScale = isHorizontalBarChart ? yScale : xScale;+ const uniqueId = useId();++ // Horizontal fade mask (for grid rows - fades left/right)+ const hMaskId = `grid-rows-fade-${uniqueId}`;+ const hGradientId = `${hMaskId}-gradient`;++ // Vertical fade mask (for grid columns - fades top/bottom)+ const vMaskId = `grid-cols-fade-${uniqueId}`;+ const vGradientId = `${vMaskId}-gradient`;++ return (+ <g className="chart-grid">+ {/* Gradient mask for horizontal grid lines - fades at left/right */}+ {horizontal && fadeHorizontal && (+ <defs>+ <linearGradient id={hGradientId} x1="0%" x2="100%" y1="0%" y2="0%">+ <stop offset="0%" style={{ stopColor: "white", stopOpacity: 0 }} />+ <stop offset="10%" style={{ stopColor: "white", stopOpacity: 1 }} />+ <stop offset="90%" style={{ stopColor: "white", stopOpacity: 1 }} />+ <stop+ offset="100%"+ style={{ stopColor: "white", stopOpacity: 0 }}+ />+ </linearGradient>+ <mask id={hMaskId}>+ <rect+ fill={`url(#${hGradientId})`}+ height={innerHeight}+ width={innerWidth}+ x="0"+ y="0"+ />+ </mask>+ </defs>+ )}++ {/* Gradient mask for vertical grid lines - fades at top/bottom */}+ {vertical && fadeVertical && (+ <defs>+ <linearGradient id={vGradientId} x1="0%" x2="0%" y1="0%" y2="100%">+ <stop offset="0%" style={{ stopColor: "white", stopOpacity: 0 }} />+ <stop offset="10%" style={{ stopColor: "white", stopOpacity: 1 }} />+ <stop offset="90%" style={{ stopColor: "white", stopOpacity: 1 }} />+ <stop+ offset="100%"+ style={{ stopColor: "white", stopOpacity: 0 }}+ />+ </linearGradient>+ <mask id={vMaskId}>+ <rect+ fill={`url(#${vGradientId})`}+ height={innerHeight}+ width={innerWidth}+ x="0"+ y="0"+ />+ </mask>+ </defs>+ )}++ {horizontal && (+ <g mask={fadeHorizontal ? `url(#${hMaskId})` : undefined}>+ <GridRows+ numTicks={rowTickValues ? undefined : numTicksRows}+ scale={yScale}+ stroke={stroke}+ strokeDasharray={strokeDasharray}+ strokeOpacity={strokeOpacity}+ strokeWidth={strokeWidth}+ tickValues={rowTickValues}+ width={innerWidth}+ />+ </g>+ )}+ {horizontal && highlightRowValues && highlightRowValues.length > 0 ? (+ <g className="chart-grid-highlight-rows">+ {highlightRowValues.map((value) => {+ const y = yScale(value);+ if (y == null || !Number.isFinite(y)) {+ return null;+ }++ return (+ <line+ key={value}+ stroke={highlightRowStroke}+ strokeDasharray={highlightRowStrokeDasharray}+ strokeOpacity={highlightRowStrokeOpacity}+ strokeWidth={highlightRowStrokeWidth}+ x1={0}+ x2={innerWidth}+ y1={y}+ y2={y}+ />+ );+ })}+ </g>+ ) : null}+ {vertical && columnScale && typeof columnScale === "function" && (+ <g mask={fadeVertical ? `url(#${vMaskId})` : undefined}>+ <GridColumns+ height={innerHeight}+ numTicks={numTicksColumns}+ scale={columnScale}+ stroke={stroke}+ strokeDasharray={strokeDasharray}+ strokeOpacity={strokeOpacity}+ strokeWidth={strokeWidth}+ />+ </g>+ )}+ </g>+ );+}++Grid.displayName = "Grid";++export default Grid;diff --git a/apps/start/src/components/charts/highlight-segment-bounds.ts b/apps/start/src/components/charts/highlight-segment-bounds.tsnew file mode 100644index 000000000..19e66a912--- /dev/null+++ b/apps/start/src/components/charts/highlight-segment-bounds.ts@@ -0,0 +1,71 @@+import type { TooltipData } from "./chart-context";+import type { ChartSelection } from "./use-chart-interaction";++// Pure geometry for the hover-highlight band, split out from the hook so it can+// be unit-tested without React/motion (see __tests__).+//+// The band is the pixel x-range one data point either side of the hovered point:+// [ xScale(t(idx-1)), xScale(t(idx+1)) ]+// `<HighlightSegment>` then re-strokes the base path clipped to that band, so the+// highlight always traces the line itself. Selecting the band by data index+// assumes x is monotone along the path, which holds for a time series. On a curve+// that overshoots in x (curveNatural, curveBasis) a band edge can land a few+// pixels short, slightly narrowing the bright slice but never detaching it.++export interface SegmentBounds {+ /** Left edge of the highlight band, in pixels. */+ x: number;+ /** Width of the highlight band, in pixels. */+ width: number;+ isActive: boolean;+}++export const INACTIVE_SEGMENT: SegmentBounds = {+ x: 0,+ width: 0,+ isActive: false,+};++/**+ * The highlight band `{x, width}` in pixel space, from the data + `xScale` plus+ * the current hover/selection. Hover spans one data point either side of the dot+ * (clamped to the ends); an active drag-selection uses the dragged pixel range+ * directly and takes priority over hover.+ */+export function computeSegmentBounds(+ data: Record<string, unknown>[],+ xScale: (value: Date) => number | undefined,+ xAccessor: (d: Record<string, unknown>) => Date,+ tooltipData: Pick<TooltipData, "index"> | null | undefined,+ selection:+ | Pick<ChartSelection, "active" | "startX" | "endX">+ | null+ | undefined+): SegmentBounds {+ if (data.length === 0) {+ return INACTIVE_SEGMENT;+ }++ if (selection?.active) {+ const x = Math.min(selection.startX, selection.endX);+ const width = Math.abs(selection.endX - selection.startX);+ return { x, width, isActive: true };+ }++ if (!tooltipData) {+ return INACTIVE_SEGMENT;+ }++ const idx = tooltipData.index;+ const startIdx = Math.max(0, idx - 1);+ const endIdx = Math.min(data.length - 1, idx + 1);+ const startPoint = data[startIdx];+ const endPoint = data[endIdx];+ if (!(startPoint && endPoint)) {+ return INACTIVE_SEGMENT;+ }++ const startX = xScale(xAccessor(startPoint)) ?? 0;+ const endX = xScale(xAccessor(endPoint)) ?? 0;+ return { x: startX, width: Math.max(0, endX - startX), isActive: true };+}diff --git a/apps/start/src/components/charts/highlight-segment.tsx b/apps/start/src/components/charts/highlight-segment.tsxnew file mode 100644index 000000000..aa6295ab1--- /dev/null+++ b/apps/start/src/components/charts/highlight-segment.tsx@@ -0,0 +1,65 @@+"use client";++import { type MotionValue, motion } from "motion/react";+import { type RefObject, useId } from "react";++// Hover-highlight overlay: re-strokes the base path `d`, clipped to a vertical+// band whose x/width spring to track the hovered point, so only the segment+// around the dot shows brighter. The band comes from `useHighlightSegment`;+// because the bright stroke reuses the base `d`, it follows whatever curve is+// drawn (see `highlight-segment-bounds.ts` for the band-extent caveat).++export interface HighlightSegmentProps {+ /** Ref to the rendered base stroke `<path>` — its `d` is re-used verbatim. */+ pathRef: RefObject<SVGPathElement | null>;+ /** Whether to render (caller gates on showHighlight + active + loaded). */+ visible: boolean;+ stroke: string;+ strokeWidth: number;+ /** Plot height — the clip band spans it fully. */+ height: number;+ /** Spring-eased left edge of the clip band (px). */+ x: MotionValue<number>;+ /** Spring-eased width of the clip band (px). */+ width: MotionValue<number>;+}++export function HighlightSegment({+ pathRef,+ visible,+ stroke,+ strokeWidth,+ height,+ x,+ width,+}: HighlightSegmentProps) {+ const clipId = useId();+ if (!(visible && pathRef.current)) {+ return null;+ }+ return (+ <>+ <defs>+ <clipPath id={clipId}>+ <motion.rect height={height} width={width} x={x} y={0} />+ </clipPath>+ </defs>+ <motion.path+ animate={{ opacity: 1 }}+ clipPath={`url(#${clipId})`}+ d={pathRef.current.getAttribute("d") || ""}+ exit={{ opacity: 0 }}+ fill="none"+ initial={{ opacity: 0 }}+ stroke={stroke}+ strokeLinecap="round"+ strokeWidth={strokeWidth}+ transition={{ duration: 0.4, ease: "easeInOut" }}+ />+ </>+ );+}++HighlightSegment.displayName = "HighlightSegment";++export default HighlightSegment;diff --git a/apps/start/src/components/charts/line-chart.tsx b/apps/start/src/components/charts/line-chart.tsxnew file mode 100644index 000000000..baea6d28a--- /dev/null+++ b/apps/start/src/components/charts/line-chart.tsx@@ -0,0 +1,203 @@+"use client";++import { ParentSize } from "@visx/responsive";+import type { Transition } from "motion/react";+import {+ Children,+ isValidElement,+ type ReactElement,+ type ReactNode,+ useMemo,+ useRef,+} from "react";+import { cn } from "@/lib/utils";+import type { LineConfig, Margin } from "./chart-context";+import { Line, type LineProps } from "./line";+import { TimeSeriesChartInner } from "./time-series-chart-shell";++export interface LineChartProps {+ /** Data array - each item should have a date field and numeric values */+ data: Record<string, unknown>[];+ /** Key in data for the x-axis (date). Default: "date" */+ xDataKey?: string;+ /** Chart margins */+ margin?: Partial<Margin>;+ /** Animation duration in milliseconds. Default: 1100 */+ animationDuration?: number;+ /** CSS easing for clip-reveal. Default: cubic-bezier(0.85, 0, 0.15, 1) */+ animationEasing?: string;+ enterTransition?: Transition;+ revealSignature?: string;+ /** Aspect ratio as "width / height". Default: "2 / 1" */+ aspectRatio?: string;+ /** Additional class name for the container */+ className?: string;+ /** Child components (Line, Grid, ChartTooltip, etc.) */+ children: ReactNode;+}++const DEFAULT_MARGIN: Margin = { top: 40, right: 40, bottom: 40, left: 40 };++/** Series renderers that carry a dataKey but must not drive the shared y-domain. */+const LINE_DOMAIN_EXCLUDED_NAMES = new Set([+ "ProfitLossLine",+ "Area",+ "SeriesBar",+ "Scatter",+ "Candlestick",+ "Bar",+ "PatternArea",+]);++function getChildComponentName(child: ReactElement) {+ const childType = child.type as { displayName?: string; name?: string };+ return typeof child.type === "function"+ ? childType.displayName || childType.name || ""+ : "";+}++function registersLineDomain(+ child: ReactElement,+ props: LineProps | undefined+) {+ if (!props?.dataKey) {+ return false;+ }++ const componentName = getChildComponentName(child);+ if (componentName === "Line" || child.type === Line) {+ return true;+ }+ if (LINE_DOMAIN_EXCLUDED_NAMES.has(componentName)) {+ return false;+ }+ // MDX / duplicate bundle instances may not share the same `Line` reference.+ return typeof props.dataKey === "string" && props.dataKey.length > 0;+}++function extractLineConfigs(children: ReactNode): LineConfig[] {+ const configs: LineConfig[] = [];++ const visit = (node: ReactNode) => {+ Children.forEach(node, (child) => {+ if (!isValidElement(child)) {+ return;+ }++ const props = child.props as LineProps | undefined;++ if (registersLineDomain(child, props) && props?.dataKey) {+ configs.push({+ dataKey: props.dataKey,+ stroke: props.stroke || "var(--chart-line-primary)",+ strokeWidth: props.strokeWidth || 2.5,+ });+ return;+ }++ const childProps = child.props as { children?: ReactNode } | undefined;+ if (childProps?.children) {+ visit(childProps.children);+ }+ });+ };++ visit(children);+ return configs;+}++interface ChartInnerProps {+ width: number;+ height: number;+ data: Record<string, unknown>[];+ xDataKey: string;+ margin: Margin;+ animationDuration: number;+ animationEasing?: string;+ enterTransition?: Transition;+ revealSignature?: string;+ children: ReactNode;+ containerRef: React.RefObject<HTMLDivElement | null>;+}++function ChartInner({+ width,+ height,+ data,+ xDataKey,+ margin,+ animationDuration,+ animationEasing,+ enterTransition,+ revealSignature,+ children,+ containerRef,+}: ChartInnerProps) {+ const lines = useMemo(() => extractLineConfigs(children), [children]);++ return (+ <TimeSeriesChartInner+ animationDuration={animationDuration}+ animationEasing={animationEasing}+ clipPathId="chart-grow-clip"+ containerRef={containerRef}+ data={data}+ enterTransition={enterTransition}+ height={height}+ lines={lines}+ margin={margin}+ revealSignature={revealSignature}+ width={width}+ xDataKey={xDataKey}+ >+ {children}+ </TimeSeriesChartInner>+ );+}++export function LineChart({+ data,+ xDataKey = "date",+ margin: marginProp,+ animationDuration = 1100,+ animationEasing,+ enterTransition,+ revealSignature,+ aspectRatio = "2 / 1",+ className = "",+ children,+}: LineChartProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const margin = { ...DEFAULT_MARGIN, ...marginProp };++ return (+ <div+ className={cn("relative w-full", className)}+ ref={containerRef}+ style={{ aspectRatio, touchAction: "none" }}+ >+ <ParentSize debounceTime={10}>+ {({ width, height }) => (+ <ChartInner+ animationDuration={animationDuration}+ animationEasing={animationEasing}+ containerRef={containerRef}+ data={data}+ enterTransition={enterTransition}+ height={height}+ margin={margin}+ revealSignature={revealSignature}+ width={width}+ xDataKey={xDataKey}+ >+ {children}+ </ChartInner>+ )}+ </ParentSize>+ </div>+ );+}++export { Line, type LineProps } from "./line";++export default LineChart;diff --git a/apps/start/src/components/charts/line.tsx b/apps/start/src/components/charts/line.tsxnew file mode 100644index 000000000..673f84dff--- /dev/null+++ b/apps/start/src/components/charts/line.tsx@@ -0,0 +1,175 @@+"use client";++import { curveNatural } from "@visx/curve";+import { LinePath } from "@visx/shape";++// CurveFactory type - simplified version compatible with visx+// biome-ignore lint/suspicious/noExplicitAny: d3 curve factory type+type CurveFactory = any;++import { useCallback, useId, useRef } from "react";+import { chartCssVars, useChartStable } from "./chart-context";+import {+ type FadeEdges,+ fadeGradientStops,+ resolveFadeSides,+} from "./fade-edges";+import {+ resolveDashTailBounds,+ usePathStrokeMetrics,+} from "./path-stroke-utils";+import { SeriesDashTailOverlay } from "./series-dash-tail-overlay";+import { SeriesHighlightLayer } from "./series-highlight-layer";+import { SeriesHoverDim } from "./series-hover-dim";+import { SeriesMarkers } from "./series-markers";+import type { SeriesPointMarkerStyle } from "./series-point-marker";++export interface LineProps {+ /** Key in data to use for y values */+ dataKey: string;+ /** Stroke color. Default: var(--chart-line-primary) */+ stroke?: string;+ /** Stroke width. Default: 2.5 */+ strokeWidth?: number;+ /** Curve function. Default: curveNatural */+ curve?: CurveFactory;+ /** Whether to animate the line. Default: true */+ animate?: boolean;+ /**+ * Fade the line stroke toward transparent at the chart edges.+ * - `true` fades both edges, `false` disables the fade entirely.+ * - `"left"` / `"right"` fades only that side.+ * Default: true+ */+ fadeEdges?: FadeEdges;+ /** Whether to show highlight segment on hover. Default: true */+ showHighlight?: boolean;+ /** Render scatter-style circle markers at each data point. Default: false */+ showMarkers?: boolean;+ /** Marker styling (same options as Scatter). */+ markers?: SeriesPointMarkerStyle;+ /**+ * Data index from which the line stroke becomes dashed (inclusive).+ * Useful for projecting incomplete periods, e.g. dashed from yesterday through today.+ */+ dashFromIndex?: number;+ /** Dash pattern for the tail segment when `dashFromIndex` is set. Default: "6,4" */+ dashArray?: string;+}++export function Line({+ dataKey,+ stroke = chartCssVars.linePrimary,+ strokeWidth = 2.5,+ curve = curveNatural,+ animate = true,+ fadeEdges = true,+ showHighlight = true,+ showMarkers = false,+ markers,+ dashFromIndex,+ dashArray = "6,4",+}: LineProps) {+ // Stable slice only: hover state lives inside `<SeriesHoverDim>` and+ // `<SeriesHighlightLayer>` so this component (and its expensive+ // <SeriesDashTailOverlay> child) does not re-render on cursor motion.+ // The reveal-clip is now a single shared clipPath at the chart-shell+ // level (`time-series-chart-shell.tsx`); we no longer render a per-line+ // `<ChartRevealClip>` or read `revealEpoch` here.+ const {+ data,+ renderData,+ xScale,+ yScale,+ innerHeight,+ innerWidth,+ xAccessor,+ } = useChartStable();++ const pathRef = useRef<SVGPathElement>(null);+ const pathMetricsKey = `${renderData.length}:${innerWidth}:${dashFromIndex}:${animate}`;+ const { pathLength, pathD } = usePathStrokeMetrics(pathRef, pathMetricsKey);++ const reactId = useId();+ const gradientId = `line-gradient-${dataKey}-${reactId}`;++ const getY = useCallback(+ (d: Record<string, unknown>) => {+ const value = d[dataKey];+ return typeof value === "number" ? (yScale(value) ?? 0) : 0;+ },+ [dataKey, yScale]+ );++ const hasDashTail = resolveDashTailBounds(dashFromIndex, data.length);+ const fadeSides = resolveFadeSides(fadeEdges);+ const lineStroke = fadeSides.any ? `url(#${gradientId})` : stroke;+ const fadeStops = fadeSides.any ? fadeGradientStops(fadeSides) : null;++ return (+ <>+ {fadeStops ? (+ <defs>+ <linearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">+ {fadeStops.map((stop) => (+ <stop+ key={stop.offset}+ offset={stop.offset}+ style={{ stopColor: stroke, stopOpacity: stop.opacity }}+ />+ ))}+ </linearGradient>+ </defs>+ ) : null}++ <SeriesHoverDim dimOpacity={0.3} enabled={showHighlight}>+ <LinePath+ curve={curve}+ data={renderData}+ innerRef={pathRef}+ stroke={hasDashTail ? "transparent" : lineStroke}+ strokeLinecap="round"+ strokeWidth={strokeWidth}+ x={(d) => xScale(xAccessor(d)) ?? 0}+ y={getY}+ />++ <SeriesDashTailOverlay+ dashArray={dashArray}+ dashFromIndex={dashFromIndex}+ data={data}+ innerHeight={innerHeight}+ innerWidth={innerWidth}+ pathD={pathD}+ pathLength={pathLength}+ stroke={lineStroke}+ strokeWidth={strokeWidth}+ xAccessor={xAccessor}+ xScale={xScale}+ />+ </SeriesHoverDim>++ {showMarkers ? (+ <SeriesMarkers+ animate={animate}+ dataKey={dataKey}+ {...markers}+ fill={markers?.fill ?? stroke}+ stroke={markers?.stroke ?? markers?.fill ?? stroke}+ />+ ) : null}++ <SeriesHighlightLayer+ enabled={showHighlight}+ height={innerHeight}+ pathRef={pathRef}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ </>+ );+}++Line.displayName = "Line";++export default Line;diff --git a/apps/start/src/components/charts/markers/chart-markers.tsx b/apps/start/src/components/charts/markers/chart-markers.tsxnew file mode 100644index 000000000..0c31906ee--- /dev/null+++ b/apps/start/src/components/charts/markers/chart-markers.tsx@@ -0,0 +1,214 @@+"use client";++import { useCallback, useMemo } from "react";+import { chartCssVars, useChart } from "../chart-context";+import { type ChartMarker, MarkerGroup } from "./marker-group";++export interface ChartMarkersProps {+ /** Array of markers to display */+ items: ChartMarker[];+ /** Size of each marker circle. Default: 28 */+ size?: number;+ /** Whether to show vertical guide lines. Default: true */+ showLines?: boolean;+ /** Whether to animate markers on entrance. Default: true */+ animate?: boolean;+}++// Tooltip content for markers+export interface MarkerTooltipContentProps {+ markers: ChartMarker[];+}++const MAX_TOOLTIP_MARKERS = 2;++export function MarkerTooltipContent({ markers }: MarkerTooltipContentProps) {+ if (markers.length === 0) {+ return null;+ }++ const visibleMarkers = markers.slice(0, MAX_TOOLTIP_MARKERS);+ const hiddenCount = markers.length - MAX_TOOLTIP_MARKERS;++ return (+ <div className="mt-2 space-y-2 border-chart-tooltip-muted border-t pt-2">+ {visibleMarkers.map((marker) => {+ const isClickable = !!(marker.onClick || marker.href);+ return (+ <div className="flex items-start gap-2" key={marker.title}>+ <div+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full"+ style={{+ backgroundColor: marker.color || chartCssVars.markerBackground,+ border: `1px solid ${chartCssVars.markerBorder}`,+ }}+ >+ <span+ className="text-xs"+ style={{ color: chartCssVars.markerForeground }}+ >+ {marker.icon}+ </span>+ </div>+ <div className="min-w-0 flex-1">+ {marker.content ? (+ marker.content+ ) : (+ <>+ <div className="flex items-center gap-1.5 truncate font-medium text-chart-tooltip-foreground text-sm">+ {marker.title}+ {isClickable && (+ <span className="text-[10px] text-chart-tooltip-muted">+ ↗+ </span>+ )}+ </div>+ {marker.description && (+ <div className="truncate text-chart-tooltip-muted text-xs">+ {marker.description}+ </div>+ )}+ </>+ )}+ </div>+ </div>+ );+ })}+ {hiddenCount > 0 && (+ <div className="pl-7 text-chart-tooltip-muted text-xs">+ +{hiddenCount} more...+ </div>+ )}+ </div>+ );+}++export function ChartMarkers({+ items,+ size = 28,+ showLines = true,+ animate = true,+}: ChartMarkersProps) {+ const {+ xScale,+ innerHeight,+ margin,+ containerRef,+ tooltipData,+ setTooltipData,+ animationDuration,+ } = useChart();++ // Hide the crosshair when hovering markers (matching original behavior)+ const handleMarkerHover = useCallback(+ (markers: ChartMarker[] | null) => {+ if (markers) {+ // Hide crosshair when hovering a marker+ setTooltipData(null);+ }+ },+ [setTooltipData]+ );++ // Group markers by date+ const markersByDate = useMemo(() => {+ const grouped = new Map<string, ChartMarker[]>();+ for (const marker of items) {+ const dateKey = marker.date.toDateString();+ const existing = grouped.get(dateKey) || [];+ grouped.set(dateKey, [...existing, marker]);+ }+ return grouped;+ }, [items]);++ // Get markers for currently hovered date+ const _activeMarkers = useMemo(() => {+ if (!tooltipData) {+ return [];+ }+ const point = tooltipData.point;+ const date =+ point.date instanceof Date+ ? point.date+ : new Date(point.date as string | number);+ const dateKey = date.toDateString();+ return markersByDate.get(dateKey) || [];+ }, [tooltipData, markersByDate]);++ // Y position for markers (above chart area)+ const markerY = -8;++ return (+ <>+ {/* SVG markers rendered in chart space */}+ {Array.from(markersByDate.entries()).map(+ ([dateKey, dateMarkers], groupIndex) => {+ const markerDate = dateMarkers[0]?.date;+ if (!markerDate) {+ return null;+ }++ const markerX = xScale(markerDate) ?? 0;+ const isActive = tooltipData+ ? (() => {+ const point = tooltipData.point;+ const date =+ point.date instanceof Date+ ? point.date+ : new Date(point.date as string | number);+ return date.toDateString() === dateKey;+ })()+ : undefined;++ const markerDelay = animate+ ? animationDuration / 1000 + groupIndex * 0.1+ : 0;++ return (+ <MarkerGroup+ animate={animate}+ animationDelay={markerDelay}+ containerRef={containerRef}+ isActive={isActive}+ key={dateKey}+ lineHeight={innerHeight}+ marginLeft={margin.left}+ marginTop={margin.top}+ markers={dateMarkers}+ onHover={handleMarkerHover}+ showLine={showLines}+ size={size}+ x={markerX}+ y={markerY}+ />+ );+ }+ )}+ </>+ );+}++// Hook to get active markers for tooltip+export function useActiveMarkers(items: ChartMarker[]) {+ const { tooltipData } = useChart();++ return useMemo(() => {+ if (!tooltipData) {+ return [];+ }+ const point = tooltipData.point;+ const date =+ point.date instanceof Date+ ? point.date+ : new Date(point.date as string | number);+ const dateKey = date.toDateString();+ return items.filter((m) => m.date.toDateString() === dateKey);+ }, [tooltipData, items]);+}++ChartMarkers.displayName = "ChartMarkers";+// Marker for SVG component detection (renders after mouse overlay for interaction)+(ChartMarkers as { __isChartMarkers?: boolean }).__isChartMarkers = true;+MarkerTooltipContent.displayName = "MarkerTooltipContent";++export default ChartMarkers;diff --git a/apps/start/src/components/charts/markers/index.ts b/apps/start/src/components/charts/markers/index.tsnew file mode 100644index 000000000..32b9f1f7f--- /dev/null+++ b/apps/start/src/components/charts/markers/index.ts@@ -0,0 +1,12 @@+export {+ ChartMarkers,+ type ChartMarkersProps,+ MarkerTooltipContent,+ type MarkerTooltipContentProps,+ useActiveMarkers,+} from "./chart-markers";+export {+ type ChartMarker,+ MarkerGroup,+ type MarkerGroupProps,+} from "./marker-group";diff --git a/apps/start/src/components/charts/markers/marker-group.tsx b/apps/start/src/components/charts/markers/marker-group.tsxnew file mode 100644index 000000000..73c6c6138--- /dev/null+++ b/apps/start/src/components/charts/markers/marker-group.tsx@@ -0,0 +1,528 @@+"use client";++import { AnimatePresence, motion } from "motion/react";+import type * as React from "react";+import { useState } from "react";+import { createPortal } from "react-dom";+import { cn } from "@/lib/utils";+import { chartCssVars } from "../chart-context";++// Fan configuration+const FAN_RADIUS = 50;+const FAN_ANGLE = 160;++export interface ChartMarker {+ /** Date for this marker (will be matched to nearest data point) */+ date: Date;+ /** Icon to display in the marker circle */+ icon: React.ReactNode;+ /** Title shown in tooltip */+ title: string;+ /** Optional description */+ description?: string;+ /** Optional custom content for tooltip (overrides title/description) */+ content?: React.ReactNode;+ /** Optional color override for the marker circle */+ color?: string;+ /** Click handler */+ onClick?: () => void;+ /** URL to navigate to when clicked */+ href?: string;+ /** Open href in new tab. Default: false */+ target?: "_blank" | "_self";+}++export interface MarkerGroupProps {+ /** X position in pixels */+ x: number;+ /** Y position (top of chart area) */+ y: number;+ /** Markers at this position */+ markers: ChartMarker[];+ /** Whether this marker group is currently hovered (via chart hover) */+ isActive?: boolean;+ /** Size of each marker circle */+ size?: number;+ /** Callback when marker group is hovered */+ onHover?: (markers: ChartMarker[] | null) => void;+ /** Reference to chart container for portal positioning */+ containerRef?: React.RefObject<HTMLDivElement | null>;+ /** Margin left offset from chart container */+ marginLeft?: number;+ /** Margin top offset from chart container */+ marginTop?: number;+ /** Delay before entrance animation starts */+ animationDelay?: number;+ /** Whether the marker should animate in */+ animate?: boolean;+ /** Height of the vertical guide line below the marker */+ lineHeight?: number;+ /** Whether to show the vertical guide line. Default: true */+ showLine?: boolean;+ /**+ * Force the marker fan to open even when the user isn't hovering this+ * group directly. Used by OPMarkerLayer to fan out a cluster when the+ * chart's main crosshair lands on one of the cluster's buckets.+ */+ forceOpen?: boolean;+ /**+ * Make the icon `foreignObject` fill the entire circle (no 4px inset)+ * so favicon-style icons sit edge-to-edge with the marker border.+ */+ iconFill?: boolean;+ /**+ * Override the marker circle's stroke color. Falls back to+ * `chartCssVars.markerBorder` when not set.+ */+ borderColor?: string;+ /**+ * Marker circle stroke width in px. Default 1.5.+ */+ borderWidth?: number;+ /**+ * Cap the number of markers rendered in the fan-out arc. The count+ * badge still reflects the full cluster size. Without this, large+ * clusters (e.g. 20+ spikes) collapse the fan angular spacing to+ * essentially zero and the markers stack on top of each other.+ */+ maxFanned?: number;+ /**+ * Fade this marker group when another cluster has focus. Used by+ * OPMarkerLayer to spotlight the active cluster.+ */+ isMuted?: boolean;+ /** Count-badge circle radius in px. Default 9. */+ badgeRadius?: number;+ /** Count-badge text size in px. Default 11. */+ badgeFontSize?: number;+ /** Offset of badge from marker corner along x/-y. Default 2. */+ badgeOffset?: number;+}++// Entrance + fanned + muted variants. `fanned` shrinks and dims the+// collapsed marker while its siblings are flying out in the portal, so+// users only see the fan and not a duplicate icon sitting underneath.+// `muted` fades non-active clusters when one cluster is being focused —+// see OPMarkerLayer.+const markerEntranceVariants = {+ hidden: {+ scale: 0.85,+ opacity: 0,+ filter: "blur(2px)",+ },+ visible: {+ scale: 1,+ opacity: 1,+ filter: "blur(0px)",+ },+ fanned: {+ scale: 0.6,+ opacity: 0,+ filter: "blur(2px)",+ },+ muted: {+ scale: 1,+ opacity: 0.4,+ filter: "blur(0px)",+ },+};++export function MarkerGroup({+ x,+ y,+ markers,+ isActive = false,+ size = 28,+ onHover,+ containerRef,+ marginLeft = 0,+ marginTop = 0,+ animationDelay = 0,+ animate = true,+ lineHeight = 0,+ showLine = true,+ forceOpen = false,+ iconFill = false,+ borderColor,+ borderWidth = 1.5,+ maxFanned,+ isMuted = false,+ badgeRadius = 9,+ badgeFontSize = 11,+ badgeOffset = 2,+}: MarkerGroupProps) {+ const [isHovered, setIsHovered] = useState(false);+ const shouldFan = (isHovered || forceOpen) && markers.length > 1;+ const hasMultiple = markers.length > 1;+ const fannedMarkers =+ maxFanned !== undefined ? markers.slice(0, maxFanned) : markers;+ const currentVariant = shouldFan+ ? "fanned"+ : isMuted+ ? "muted"+ : "visible";++ const getCirclePosition = (index: number, total: number) => {+ const startAngle = -90 - FAN_ANGLE / 2;+ const angleStep = total > 1 ? FAN_ANGLE / (total - 1) : 0;+ const angle = startAngle + index * angleStep;+ const radians = (angle * Math.PI) / 180;++ return {+ x: Math.cos(radians) * FAN_RADIUS,+ y: Math.sin(radians) * FAN_RADIUS,+ };+ };++ const handleMouseEnter = (e: React.MouseEvent) => {+ e.stopPropagation(); // Prevent chart from handling this event+ setIsHovered(true);+ onHover?.(markers);+ };++ const handleMouseLeave = (e: React.MouseEvent) => {+ e.stopPropagation(); // Prevent chart from handling this event+ setIsHovered(false);+ onHover?.(null);+ };++ const handleMouseMove = (e: React.MouseEvent) => {+ e.stopPropagation(); // Prevent chart crosshair from moving while hovering markers+ };++ const portalX = x + marginLeft;+ const portalY = y + marginTop;++ return (+ <>+ {/* Position group - no interaction */}+ <g transform={`translate(${x}, ${y})`}>+ {/* Vertical guide line - non-interactive, rendered first (behind marker) */}+ {showLine && lineHeight > 0 && (+ <motion.line+ animate={{+ strokeOpacity: (() => {+ if (isHovered) {+ return 1;+ }+ if (isActive) {+ return 0;+ }+ return 0.6;+ })(),+ }}+ initial={{ strokeOpacity: 0.6 }}+ stroke={chartCssVars.markerBorder}+ strokeDasharray="4,4"+ strokeLinecap="round"+ strokeWidth={1}+ style={{ pointerEvents: "none" }}+ transition={{ duration: 0.2, ease: "easeOut" }}+ x1={0}+ x2={0}+ y1={size / 2 + 4}+ y2={lineHeight + Math.abs(y)}+ />+ )}++ {/* Interactive marker group */}+ {/* biome-ignore lint/a11y/noStaticElementInteractions: Chart marker interaction */}+ <g+ onMouseEnter={handleMouseEnter}+ onMouseLeave={handleMouseLeave}+ onMouseMove={handleMouseMove}+ style={{ cursor: "pointer" }}+ >+ <motion.g+ animate={currentVariant}+ initial={animate ? "hidden" : currentVariant}+ transition={{+ type: "spring",+ stiffness: 300,+ damping: 25,+ delay: animationDelay,+ }}+ variants={markerEntranceVariants}+ >+ {/* Hit area - covers marker circle with padding for count badge above */}+ <rect+ fill="transparent"+ height={size * 1.5}+ width={size * 1.5}+ x={-size * 0.75}+ y={-size}+ />++ {/* Main marker */}+ <MarkerCircle+ borderColor={borderColor}+ borderWidth={borderWidth}+ color={markers[0]?.color}+ icon={markers[0]?.icon}+ iconFill={iconFill}+ size={size}+ />++ {/* Count badge */}+ <AnimatePresence>+ {hasMultiple && !shouldFan && (+ <motion.g+ animate={{ scale: 1, opacity: 1 }}+ exit={{ scale: 0, opacity: 0 }}+ initial={{ scale: 0, opacity: 0 }}+ transition={{ type: "spring", stiffness: 400, damping: 20 }}+ >+ <circle+ cx={size / 2 + badgeOffset}+ cy={-size / 2 - badgeOffset}+ r={badgeRadius}+ style={{ fill: chartCssVars.badgeBackground }}+ />+ <text+ dominantBaseline="central"+ fontSize={badgeFontSize}+ fontWeight={600}+ style={{ fill: chartCssVars.badgeForeground }}+ textAnchor="middle"+ x={size / 2 + badgeOffset}+ y={-size / 2 - badgeOffset}+ >+ {markers.length}+ </text>+ </motion.g>+ )}+ </AnimatePresence>+ </motion.g>+ </g>+ </g>++ {/* Portal for fanned circles */}+ {containerRef?.current &&+ createPortal(+ // biome-ignore lint/a11y/noStaticElementInteractions: Marker hover portal+ // biome-ignore lint/a11y/noNoninteractiveElementInteractions: Marker hover portal+ <div+ className="absolute"+ onMouseEnter={handleMouseEnter}+ onMouseLeave={handleMouseLeave}+ onMouseMove={handleMouseMove}+ style={{+ // Position the div so its center is at the marker position+ // The div covers the entire fan area to prevent mouseLeave when moving between markers+ left: portalX - (FAN_RADIUS + size / 2),+ top: portalY - (FAN_RADIUS + size / 2),+ width: FAN_RADIUS * 2 + size,+ height: FAN_RADIUS * 2 + size,+ zIndex: 100,+ pointerEvents: shouldFan ? "auto" : "none",+ }}+ >+ {/* Center point offset - all fanned markers are positioned relative to this */}+ <div+ className="absolute"+ style={{+ left: FAN_RADIUS + size / 2,+ top: FAN_RADIUS + size / 2,+ }}+ >+ <AnimatePresence mode="sync">+ {shouldFan &&+ fannedMarkers.map((marker, index) => {+ const position = getCirclePosition(+ index,+ fannedMarkers.length+ );+ return (+ <motion.div+ animate={{+ x: position.x,+ y: position.y,+ scale: 1,+ opacity: 1,+ }}+ className="absolute"+ exit={{ x: 0, y: 0, scale: 0, opacity: 0 }}+ initial={{ x: 0, y: 0, scale: 0, opacity: 0 }}+ key={`fan-${marker.title}`}+ style={{+ width: size,+ height: size,+ left: -size / 2,+ top: -size / 2,+ }}+ transition={{+ type: "spring",+ stiffness: 400,+ damping: 22,+ delay: index * 0.04,+ }}+ >+ <MarkerCircleHTML+ borderColor={borderColor}+ borderWidth={borderWidth}+ color={marker.color}+ href={marker.href}+ icon={marker.icon}+ iconFill={iconFill}+ isClickable={!!(marker.onClick || marker.href)}+ onClick={marker.onClick}+ size={size}+ target={marker.target}+ />+ </motion.div>+ );+ })}+ </AnimatePresence>++ <AnimatePresence>+ {shouldFan && (+ <motion.div+ animate={{ scale: 1, opacity: 0.5 }}+ className="absolute"+ exit={{ scale: 0, opacity: 0 }}+ initial={{ scale: 0, opacity: 0 }}+ style={{+ width: size * 0.5,+ height: size * 0.5,+ left: -size * 0.25,+ top: -size * 0.25,+ }}+ transition={{ type: "spring", stiffness: 400, damping: 20 }}+ >+ <div+ className="h-full w-full rounded-full"+ style={{ backgroundColor: chartCssVars.markerBorder }}+ />+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ </div>,+ containerRef.current+ )}+ </>+ );+}++interface MarkerCircleProps {+ icon: React.ReactNode;+ size: number;+ color?: string;+ onClick?: () => void;+ href?: string;+ target?: "_blank" | "_self";+ isClickable?: boolean;+ /** Edge-to-edge icon (no 4px inset). */+ iconFill?: boolean;+ /** Override circle stroke color. */+ borderColor?: string;+ /** Circle stroke width. */+ borderWidth?: number;+}++function MarkerCircle({+ icon,+ size,+ color,+ iconFill = false,+ borderColor,+ borderWidth = 1.5,+}: MarkerCircleProps) {+ const inset = iconFill ? 0 : 4;+ return (+ <g>+ <circle cx={0} cy={2} fill="black" opacity={0.15} r={size / 2} />+ <circle+ cx={0}+ cy={0}+ fill={color || chartCssVars.markerBackground}+ r={size / 2}+ stroke={borderColor ?? chartCssVars.markerBorder}+ strokeWidth={borderWidth}+ />+ <foreignObject+ height={size - inset * 2}+ width={size - inset * 2}+ x={-size / 2 + inset}+ y={-size / 2 + inset}+ >+ <div+ style={{+ width: "100%",+ height: "100%",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ color: chartCssVars.markerForeground,+ fontSize: size * 0.5,+ overflow: "hidden",+ borderRadius: "50%",+ }}+ >+ {icon}+ </div>+ </foreignObject>+ </g>+ );+}++function MarkerCircleHTML({+ icon,+ size,+ color,+ onClick,+ href,+ target = "_self",+ isClickable = false,+ iconFill = false,+ borderColor,+ borderWidth = 1.5,+}: MarkerCircleProps) {+ const hasAction = isClickable || onClick || href;+ const inset = iconFill ? 0 : 4;++ const handleClick = (e: React.MouseEvent) => {+ e.stopPropagation();+ if (onClick) {+ onClick();+ } else if (href) {+ if (target === "_blank") {+ window.open(href, "_blank", "noopener,noreferrer");+ } else {+ window.location.href = href;+ }+ }+ };++ // Note: color and CSS vars must remain inline styles as they're dynamic+ return (+ <motion.div+ className={cn(+ "relative flex h-full w-full items-center justify-center rounded-full shadow-lg",+ hasAction && "cursor-pointer"+ )}+ onClick={hasAction ? handleClick : undefined}+ style={{+ backgroundColor: color || chartCssVars.markerBackground,+ border: `${borderWidth}px solid ${borderColor ?? chartCssVars.markerBorder}`,+ fontSize: size * 0.5,+ color: chartCssVars.markerForeground,+ padding: inset,+ overflow: "hidden",+ }}+ transition={{ type: "spring", stiffness: 400, damping: 17 }}+ whileHover={+ hasAction+ ? { scale: 1.15, boxShadow: "0 4px 20px rgba(0,0,0,0.25)" }+ : undefined+ }+ whileTap={hasAction ? { scale: 0.95 } : undefined}+ >+ {icon}+ </motion.div>+ );+}++MarkerGroup.displayName = "MarkerGroup";++export default MarkerGroup;diff --git a/apps/start/src/components/charts/motion-utils.ts b/apps/start/src/components/charts/motion-utils.tsnew file mode 100644index 000000000..77a79fe6c--- /dev/null+++ b/apps/start/src/components/charts/motion-utils.ts@@ -0,0 +1,58 @@+import type { Transition } from "motion/react";+import { DEFAULT_CHART_ENTER_TRANSITION } from "./animation";++export function transitionWithDelay(+ transition: Transition | undefined,+ delaySeconds: number,+ fallback: Transition = DEFAULT_CHART_ENTER_TRANSITION+): Transition {+ const base = transition ?? fallback;+ return { ...base, delay: delaySeconds };+}++export interface SpringOptions {+ stiffness: number;+ damping: number;+ mass?: number;+}++export function springOptionsFromTransition(+ transition?: Transition,+ fallback: SpringOptions = { stiffness: 60, damping: 20 }+): SpringOptions {+ if (!transition) {+ return fallback;+ }+ if (transition.type === "spring") {+ const bounce =+ typeof transition.bounce === "number" ? transition.bounce : undefined;+ const baseStiffness =+ typeof transition.stiffness === "number"+ ? transition.stiffness+ : fallback.stiffness;+ const baseDamping =+ typeof transition.damping === "number"+ ? transition.damping+ : fallback.damping;+ return {+ stiffness:+ bounce == null+ ? baseStiffness+ : Math.min(400, Math.max(80, baseStiffness * (1 + bounce * 0.35))),+ damping:+ bounce == null+ ? baseDamping+ : Math.max(8, baseDamping * (1 - bounce * 0.25)),+ mass:+ typeof transition.mass === "number" ? transition.mass : fallback.mass,+ };+ }+ const duration =+ "duration" in transition && typeof transition.duration === "number"+ ? transition.duration+ : 0.8;+ return {+ stiffness: Math.min(500, Math.max(40, 280 / duration)),+ damping: Math.min(40, Math.max(12, 18 + duration * 4)),+ };+}diff --git a/apps/start/src/components/charts/op-dashed-tail.ts b/apps/start/src/components/charts/op-dashed-tail.tsnew file mode 100644index 000000000..f04629974--- /dev/null+++ b/apps/start/src/components/charts/op-dashed-tail.ts@@ -0,0 +1,81 @@+import type { IInterval } from '@openpanel/validation';++interface UseDashedTailOptions<T extends { date: string | Date }> {+ data: T[];+ range: string | null | undefined;+ interval: IInterval;+}++/**+ * Returns the `dashFromIndex` to pass to a bklit `<Line>` / `<Area>` /+ * `<SeriesBar>` so the in-progress current period (and any future-extending+ * buckets that haven't happened yet) render as a dashed tail.+ *+ * Two cases:+ * - Data ends in the past or at the current bucket (e.g. `30d` ending today).+ * We dash the very last segment so today's incomplete bucket reads as+ * "not done yet" → `dashFromIndex = data.length - 2`.+ * - Data extends into the future (e.g. `today` with hourly buckets — there's+ * a bucket per hour through midnight). We dash everything from the+ * current-hour bucket onward → `dashFromIndex = currentBucketIndex`.+ *+ * Returns `undefined` when there's nothing to dash (too little data or+ * "now" hasn't reached the first bucket yet).+ */+export function useDashedTail<T extends { date: string | Date }>({+ data,+ range,+ interval: _interval,+}: UseDashedTailOptions<T>): number | undefined {+ if (data.length < 2) return undefined;++ const now = Date.now();+ let currentIdx = -1;+ for (let i = 0; i < data.length; i++) {+ const item = data[i];+ if (!item) continue;+ const t =+ item.date instanceof Date ? item.date.getTime() : new Date(item.date).getTime();+ if (t <= now) {+ currentIdx = i;+ } else {+ break;+ }+ }++ if (currentIdx < 0) {+ // All buckets are in the future — nothing to dash.+ return undefined;+ }++ if (currentIdx === data.length - 1) {+ // Data ends at "now" (or in the past). Dash only the last segment so the+ // current-period bucket reads as incomplete. Skip dashing entirely if the+ // last bucket sits well in the past (i.e. no in-progress period at all).+ return range === 'today' || isLastBucketInProgress(data, now)+ ? data.length - 2+ : undefined;+ }++ // Data extends into the future — dash from one bucket *before* the segment+ // leading into the in-progress bucket so the full descent into zero reads+ // as "incomplete + future" rather than ending mid-cliff with a solid line.+ return Math.max(0, currentIdx - 2);+}++function isLastBucketInProgress<T extends { date: string | Date }>(+ data: T[],+ now: number,+): boolean {+ const last = data[data.length - 1];+ const prev = data[data.length - 2];+ if (!(last && prev)) return false;+ const lastT =+ last.date instanceof Date ? last.date.getTime() : new Date(last.date).getTime();+ const prevT =+ prev.date instanceof Date ? prev.date.getTime() : new Date(prev.date).getTime();+ // Bucket width = gap between consecutive points. If "now" lies within the+ // last bucket's window, it's in progress.+ const bucketMs = lastT - prevT;+ return now >= lastT && now < lastT + bucketMs;+}diff --git a/apps/start/src/components/charts/op-date-pill.tsx b/apps/start/src/components/charts/op-date-pill.tsxnew file mode 100644index 000000000..3622cd838--- /dev/null+++ b/apps/start/src/components/charts/op-date-pill.tsx@@ -0,0 +1,168 @@+import { motion, useSpring } from 'motion/react';+import { useEffect, useMemo, useState } from 'react';+import { createPortal } from 'react-dom';+import { differenceInHours, getISOWeek } from 'date-fns';+import type { IInterval } from '@openpanel/validation';+import {+ type TooltipData,+ useChartHover,+ useChartStable,+} from './chart-context';++// Near-instant — original 300/30 felt sluggish snapping between data points.+const SPRING = { stiffness: 1000, damping: 60 };++interface OPDatePillProps {+ /** Interval drives format selection together with the data span. */+ interval?: IInterval;+}++/**+ * Compact date pill drawn at the bottom of the chart, replacing bklit's+ * `<DateTicker>` so we can (a) format the label based on `interval` + data span,+ * and (b) use OpenPanel's smaller type scale.+ *+ * Visibility guard sits in the outer wrapper; the inner component (which+ * owns the `useSpring`) only mounts when `tooltipData` exists, so the+ * spring initializes at the cursor's actual position. Without this split+ * the spring would init at `margin.left` (with `tooltipData` null) and+ * have to slide across the chart on first hover — pill looks like it+ * "fades in from the left edge".+ */+export function OPDatePill({ interval }: OPDatePillProps) {+ const { containerRef } = useChartStable();+ const { tooltipData } = useChartHover();+ const [mounted, setMounted] = useState(false);+ useEffect(() => {+ setMounted(true);+ }, []);++ if (!mounted || !containerRef.current || !tooltipData) {+ return null;+ }++ return (+ <OPDatePillInner+ container={containerRef.current}+ interval={interval}+ tooltipData={tooltipData}+ />+ );+}++OPDatePill.displayName = 'OPDatePill';++function OPDatePillInner({+ container,+ interval,+ tooltipData,+}: {+ container: HTMLElement;+ interval?: IInterval;+ tooltipData: TooltipData;+}) {+ const { data, xAccessor, margin, width } = useChartStable();++ const xCenter = tooltipData.x + margin.left;+ const animatedX = useSpring(xCenter, SPRING);+ animatedX.set(xCenter);++ const label = useMemo(+ () =>+ formatPillDate(+ xAccessor(tooltipData.point),+ interval ?? 'day',+ data,+ xAccessor,+ ),+ [tooltipData, data, xAccessor, interval],+ );++ // Stable across hovers — depends only on chart dimensions.+ const maxWidth = useMemo(+ () => Math.max(120, width - margin.left - margin.right),+ [width, margin.left, margin.right],+ );++ if (!label) return null;++ return createPortal(+ <motion.div+ className="pointer-events-none absolute z-50"+ style={{+ left: animatedX,+ bottom: 4,+ transform: 'translateX(-50%)',+ maxWidth,+ }}+ >+ <div className="rounded-full bg-foreground px-2.5 py-1 text-[11px] font-medium tracking-tight text-background shadow-md whitespace-nowrap">+ {label}+ </div>+ </motion.div>,+ container,+ );+}++const SHORT_WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];+const SHORT_MONTHS = [+ 'Jan',+ 'Feb',+ 'Mar',+ 'Apr',+ 'May',+ 'Jun',+ 'Jul',+ 'Aug',+ 'Sep',+ 'Oct',+ 'Nov',+ 'Dec',+];++function pad(n: number) {+ return n < 10 ? `0${n}` : String(n);+}++function formatPillDate(+ date: Date,+ interval: IInterval,+ data: Record<string, unknown>[],+ xAccessor: (d: Record<string, unknown>) => Date,+): string {+ const first = data[0] ? xAccessor(data[0]) : date;+ const last = data[data.length - 1] ? xAccessor(data[data.length - 1]!) : date;+ const spanHours = Math.max(0, differenceInHours(last, first));++ const dayMonth = `${SHORT_MONTHS[date.getMonth()]} ${date.getDate()}`;+ const time = `${pad(date.getHours())}:${pad(date.getMinutes())}`;++ switch (interval) {+ case 'minute':+ if (spanHours <= 1) return time;+ if (spanHours <= 24) return time;+ return `${dayMonth} ${time}`;++ case 'hour':+ // ≤ ~25h span → single day, show only the hour+ if (spanHours <= 25) return `${pad(date.getHours())}:00`;+ // Otherwise include the date+ return `${dayMonth} ${pad(date.getHours())}:00`;++ case 'day':+ // ≤ 14 days → include weekday, otherwise just the date+ if (spanHours <= 24 * 14) {+ return `${SHORT_WEEKDAYS[date.getDay()]}, ${dayMonth}`;+ }+ return dayMonth;++ case 'week':+ return `W${getISOWeek(date)} · ${dayMonth}`;++ case 'month':+ return `${SHORT_MONTHS[date.getMonth()]} ${date.getFullYear()}`;++ default:+ return dayMonth;+ }+}diff --git a/apps/start/src/components/charts/op-hover-probe.tsx b/apps/start/src/components/charts/op-hover-probe.tsxnew file mode 100644index 000000000..6045e3ea0--- /dev/null+++ b/apps/start/src/components/charts/op-hover-probe.tsx@@ -0,0 +1,20 @@+import { useEffect } from 'react';+import { useChart } from './chart-context';++interface OPHoverProbeProps {+ /** Called whenever the hovered data-point index changes. */+ onChange: (index: number | null) => void;+}++/**+ * Tiny no-render child that exposes a bklit chart's hovered index via callback.+ * Drop inside any bklit time-series / bar chart to wire it up to external state.+ */+export function OPHoverProbe({ onChange }: OPHoverProbeProps) {+ const { tooltipData } = useChart();+ const index = tooltipData?.index ?? null;+ useEffect(() => {+ onChange(index);+ }, [index, onChange]);+ return null;+}diff --git a/apps/start/src/components/charts/op-marker-layer.tsx b/apps/start/src/components/charts/op-marker-layer.tsxnew file mode 100644index 000000000..e21265279--- /dev/null+++ b/apps/start/src/components/charts/op-marker-layer.tsx@@ -0,0 +1,379 @@+'use client';++import { memo, type ReactNode, useCallback, useMemo } from 'react';+import {+ type TooltipData,+ useChartHover,+ useChartStable,+} from './chart-context';+import { type ChartMarker, MarkerGroup } from './markers/marker-group';++export interface OPMarkerItem {+ date: Date | string;+ icon: ReactNode;+ title: string;+ description?: string;+ content?: ReactNode;+ color?: string;+ onClick?: () => void;+ href?: string;+ target?: '_blank' | '_self';+}++/**+ * A group of related markers that render together. Single-item clusters are+ * just one marker; multi-item clusters get a count badge and fan out on+ * hover (or when the chart's crosshair lands on one of the cluster's+ * bucket indices).+ */+export interface OPMarkerCluster {+ /**+ * Date that drives the marker's x position on the chart. For multi-item+ * clusters, this is typically the most important item's date.+ */+ anchorDate: Date | string;+ /** Items in this cluster. The first item's icon is what shows when collapsed. */+ items: OPMarkerItem[];+}++interface OPMarkerLayerProps {+ clusters: OPMarkerCluster[] | null | undefined;+ /** Marker circle size in px. Default 18 (matches favicon pills elsewhere). */+ size?: number;+ /** Show vertical guide line below each cluster. Default false. */+ showLines?: boolean;+ /**+ * Merge clusters whose anchor x-positions are within this pixel distance.+ * Scales sensibly with the chart's xScale: a year of daily data on a+ * narrow chart clusters aggressively; a month of daily data on a wide+ * chart barely clusters at all. Default 32 (marker width + small gap).+ * Pass 0 to disable.+ */+ clusterPixelDistance?: number;+ /** Count-badge circle radius in px. Default 6. */+ badgeRadius?: number;+ /** Count-badge text size in px. Default 8. */+ badgeFontSize?: number;+ /** Offset of badge from marker corner along x/-y. Default 0. */+ badgeOffset?: number;+}++// Markers in this layer use a clean "app icon" look: the icon fills the+// circle edge-to-edge with a high-contrast border (foreground token =+// white in dark mode, dark in light mode). Callers pass fill-aware icons+// (e.g. `<SerieIcon fill />`) so they actually fill the larger+// foreignObject the iconFill flag opens up.+const MARKER_BORDER_COLOR = 'var(--foreground)';+// Cap fanned markers — beyond ~8 the semicircular arc gets too tight and+// markers stack visually. The count badge still shows the true cluster+// size, and the tooltip lists all referrers via its "+ also" line.+const MAX_FANNED_MARKERS = 8;++/**+ * Unified annotation layer for the chart. Both user-curated references and+ * auto-detected referrer spikes route through this — new annotation types+ * (GitHub commits, deploys, etc.) plug in the same way by adapting their+ * data into `OPMarkerCluster[]`.+ *+ * Hover behavior is bidirectional:+ * - Hovering a marker writes tooltipData for the cluster's anchor bucket,+ * so the main chart tooltip + crosshair light up as if the user hovered+ * the chart at that point.+ * - When the chart's crosshair lands on a bucket covered by any item in a+ * cluster, that cluster's MarkerGroup fans out automatically.+ */+export function OPMarkerLayer({+ clusters,+ size = 18,+ showLines = false,+ clusterPixelDistance = 32,+ badgeRadius = 6,+ badgeFontSize = 8,+ badgeOffset = 0,+}: OPMarkerLayerProps) {+ const merged = usePixelClusters(clusters, clusterPixelDistance);+ if (merged.length === 0) {+ return null;+ }+ return (+ <>+ {merged.map((cluster, index) => (+ <OPMarkerClusterRenderer+ badgeFontSize={badgeFontSize}+ badgeOffset={badgeOffset}+ badgeRadius={badgeRadius}+ cluster={cluster}+ index={index}+ key={getClusterKey(cluster)}+ showLine={showLines}+ size={size}+ />+ ))}+ </>+ );+}++/**+ * Merge input clusters whose anchor x-positions fall within+ * `pixelDistance` of each other. Walks the input sorted by pixel x,+ * accumulating into the current merge group while distance allows. Merged+ * clusters preserve item order (first input's items first) and keep the+ * first input's anchorDate as the merged anchor.+ */+function usePixelClusters(+ clusters: OPMarkerCluster[] | null | undefined,+ pixelDistance: number+): OPMarkerCluster[] {+ const { xScale } = useChartStable();+ return useMemo(() => {+ if (!clusters || clusters.length === 0) {+ return [];+ }+ if (pixelDistance <= 0) {+ return clusters;+ }++ // Resolve anchor dates + pixel x once, then sort by x so merging is a+ // single pass. Inputs with no resolvable x are dropped.+ const positioned = clusters+ .map((cluster) => {+ const anchorDate =+ typeof cluster.anchorDate === 'string'+ ? new Date(cluster.anchorDate)+ : cluster.anchorDate;+ const x = xScale(anchorDate);+ return x == null ? null : { cluster, anchorDate, x };+ })+ .filter(+ (p): p is { cluster: OPMarkerCluster; anchorDate: Date; x: number } =>+ p !== null+ )+ .sort((a, b) => a.x - b.x);++ if (positioned.length === 0) {+ return [];+ }++ const merged: OPMarkerCluster[] = [];+ let currentItems: OPMarkerItem[] = [...positioned[0]!.cluster.items];+ let currentAnchor: Date | string = positioned[0]!.anchorDate;+ let currentX = positioned[0]!.x;++ for (let i = 1; i < positioned.length; i++) {+ const next = positioned[i]!;+ if (next.x - currentX <= pixelDistance) {+ // Merge into the current cluster — concat items, keep anchor of+ // the earliest member (also gives the visible icon a stable+ // identity across renders).+ currentItems = currentItems.concat(next.cluster.items);+ } else {+ merged.push({ anchorDate: currentAnchor, items: currentItems });+ currentItems = [...next.cluster.items];+ currentAnchor = next.anchorDate;+ currentX = next.x;+ }+ }+ merged.push({ anchorDate: currentAnchor, items: currentItems });+ return merged;+ }, [clusters, xScale, pixelDistance]);+}++OPMarkerLayer.displayName = 'OPMarkerLayer';+// Render after the mouse overlay so markers stay clickable.+(OPMarkerLayer as { __isChartMarkers?: boolean }).__isChartMarkers = true;++function getClusterKey(cluster: OPMarkerCluster): string {+ const anchor =+ typeof cluster.anchorDate === 'string'+ ? cluster.anchorDate+ : cluster.anchorDate.toISOString();+ return `${anchor}-${cluster.items[0]?.title ?? ''}`;+}++interface OPMarkerClusterRendererProps {+ cluster: OPMarkerCluster;+ index: number;+ size: number;+ showLine: boolean;+ badgeRadius: number;+ badgeFontSize: number;+ badgeOffset: number;+}++const OPMarkerClusterRenderer = memo(function OPMarkerClusterRenderer({+ cluster,+ index,+ size,+ showLine,+ badgeRadius,+ badgeFontSize,+ badgeOffset,+}: OPMarkerClusterRendererProps) {+ const {+ data,+ xScale,+ yScale,+ xAccessor,+ lines,+ innerHeight,+ innerWidth,+ margin,+ containerRef,+ animationDuration,+ } = useChartStable();+ const { tooltipData, setTooltipData } = useChartHover();++ const anchorDate = useMemo(+ () =>+ typeof cluster.anchorDate === 'string'+ ? new Date(cluster.anchorDate)+ : cluster.anchorDate,+ [cluster.anchorDate]+ );++ // Pre-compute which data bucket indices this cluster's items map to.+ // On hover the chart provides tooltipData.index; we just check membership.+ const matchingIndices = useMemo(() => {+ const set = new Set<number>();+ for (const item of cluster.items) {+ const itemDate =+ typeof item.date === 'string' ? new Date(item.date) : item.date;+ const idx = findNearestIndex(itemDate, data, xAccessor);+ if (idx >= 0) {+ set.add(idx);+ }+ }+ return set;+ }, [cluster.items, data, xAccessor]);++ const isActive = tooltipData ? matchingIndices.has(tooltipData.index) : false;+ // Fade this cluster whenever the user is interacting with the chart but+ // not on this cluster's bucket — keeps the spotlight on whichever one is+ // active so adjacent clusters don't visually crowd the open fan.+ const isMuted = tooltipData !== null && !isActive;++ // Convert items to ChartMarker payloads — stable per cluster so MarkerGroup+ // doesn't see fresh references on every render.+ const markers = useMemo<ChartMarker[]>(+ () =>+ cluster.items.map((item) => ({+ date: typeof item.date === 'string' ? new Date(item.date) : item.date,+ icon: item.icon,+ title: item.title,+ description: item.description,+ content: item.content,+ color: item.color,+ onClick: item.onClick,+ href: item.href,+ target: item.target,+ })),+ [cluster.items]+ );++ // Marker hover writes the cluster's anchor bucket into the chart's+ // tooltipData. We don't clear on leave — let the chart's own mouseleave+ // handle that, so moving from a marker into the chart doesn't flicker.+ const handleHover = useCallback(+ (hovered: ChartMarker[] | null) => {+ if (!hovered) {+ return;+ }+ const anchorIdx = findNearestIndex(anchorDate, data, xAccessor);+ if (anchorIdx < 0) {+ return;+ }+ // Skip the setState entirely if the chart is already on this bucket.+ if (tooltipData?.index === anchorIdx) {+ return;+ }+ const point = data[anchorIdx];+ if (!point) {+ return;+ }+ const yPositions: Record<string, number> = {};+ for (const line of lines) {+ const value = point[line.dataKey];+ if (typeof value === 'number') {+ yPositions[line.dataKey] = yScale(value) ?? 0;+ }+ }+ const next: TooltipData = {+ point,+ index: anchorIdx,+ x: xScale(anchorDate) ?? 0,+ yPositions,+ };+ setTooltipData(next);+ },+ [+ anchorDate,+ data,+ xAccessor,+ xScale,+ yScale,+ lines,+ tooltipData,+ setTooltipData,+ ]+ );++ // Clamp x so the marker (and its badge) stay fully inside the plot area —+ // otherwise a marker on the first/last bucket gets half-clipped by the SVG+ // and the `overflow-clip` chart wrapper.+ const rawX = xScale(anchorDate) ?? 0;+ const edgePadding = size / 2 + badgeRadius + badgeOffset;+ const x = Math.min(Math.max(rawX, edgePadding), innerWidth - edgePadding);+ const delay = animationDuration / 1000 + index * 0.05;++ return (+ <MarkerGroup+ animate+ animationDelay={delay}+ badgeFontSize={badgeFontSize}+ badgeOffset={badgeOffset}+ badgeRadius={badgeRadius}+ borderColor={MARKER_BORDER_COLOR}+ borderWidth={1}+ containerRef={containerRef}+ forceOpen={isActive}+ iconFill+ isActive={isActive}+ isMuted={isMuted}+ lineHeight={innerHeight}+ marginLeft={margin.left}+ marginTop={margin.top}+ markers={markers}+ maxFanned={MAX_FANNED_MARKERS}+ onHover={handleHover}+ showLine={showLine}+ size={size}+ x={x}+ y={16}+ />+ );+});++function findNearestIndex(+ target: Date,+ data: Record<string, unknown>[],+ xAccessor: (d: Record<string, unknown>) => Date+): number {+ if (data.length === 0) {+ return -1;+ }+ const targetTime = target.getTime();+ let nearestIdx = 0;+ let minDiff = Number.POSITIVE_INFINITY;+ for (let i = 0; i < data.length; i++) {+ const point = data[i];+ if (!point) {+ continue;+ }+ const diff = Math.abs(xAccessor(point).getTime() - targetTime);+ if (diff < minDiff) {+ minDiff = diff;+ nearestIdx = i;+ }+ }+ return nearestIdx;+}diff --git a/apps/start/src/components/charts/op-references.tsx b/apps/start/src/components/charts/op-references.tsxnew file mode 100644index 000000000..441d008a1--- /dev/null+++ b/apps/start/src/components/charts/op-references.tsx@@ -0,0 +1,68 @@+import { FlagIcon } from 'lucide-react';+import { useMemo } from 'react';+import type { ChartMarker } from './markers/marker-group';+import {+ OPMarkerLayer,+ type OPMarkerCluster,+ type OPMarkerItem,+} from './op-marker-layer';++export interface OPReferenceItem {+ id: string;+ date: Date | string;+ title: string;+ description?: string | null;+}++/**+ * Convert OpenPanel reference rows into ChartMarker[] for use by the+ * tooltip's `useReferencesForHoveredPoint` lookup (independent of the chart+ * marker rendering, which goes through OPMarkerLayer).+ */+export function toChartMarkers(+ items: OPReferenceItem[] | null | undefined,+): ChartMarker[] {+ if (!items || items.length === 0) return [];+ return items.map((item) => ({+ date: typeof item.date === 'string' ? new Date(item.date) : item.date,+ icon: <FlagIcon className="size-2.5" />,+ title: item.title,+ description: item.description ?? undefined,+ }));+}++interface OPReferencesProps {+ items: OPReferenceItem[] | null | undefined;+ /** Marker circle size in px. Defaults via OPMarkerLayer. */+ size?: number;+ /** Show vertical guide line under each marker. Default: true. */+ showLines?: boolean;+}++/**+ * Renders user-curated reference annotations through the shared marker+ * layer. One cluster per reference — OPMarkerLayer handles visual density+ * via pixel-based merging using the live chart xScale, so dense ranges+ * naturally fan instead of overlapping. Inherits bidirectional hover+ * (marker ↔ chart tooltip) from OPMarkerLayer.+ */+export function OPReferences({+ items,+ size,+ showLines = true,+}: OPReferencesProps) {+ const clusters = useMemo<OPMarkerCluster[]>(() => {+ if (!items || items.length === 0) return [];+ return items.map((ref) => {+ const date = typeof ref.date === 'string' ? new Date(ref.date) : ref.date;+ const item: OPMarkerItem = {+ date,+ icon: <FlagIcon className="size-2.5" />,+ title: ref.title,+ description: ref.description ?? undefined,+ };+ return { anchorDate: date, items: [item] };+ });+ }, [items]);+ return <OPMarkerLayer clusters={clusters} showLines={showLines} size={size} />;+}diff --git a/apps/start/src/components/charts/op-referrer-spikes.tsx b/apps/start/src/components/charts/op-referrer-spikes.tsxnew file mode 100644index 000000000..7edb8ad72--- /dev/null+++ b/apps/start/src/components/charts/op-referrer-spikes.tsx@@ -0,0 +1,70 @@+'use client';++import { useMemo } from 'react';+import { SerieIcon } from '@/components/report-chart/common/serie-icon';+import {+ OPMarkerLayer,+ type OPMarkerCluster,+ type OPMarkerItem,+} from './op-marker-layer';++export interface OPReferrerSpikeItem {+ date: string | Date;+ referrer_name: string;+ sessions: number;+ baseline: number;+ ratio: number;+ share: number;+ isNew: boolean;+ others: Array<{ referrer_name: string; sessions: number; ratio: number }>;+}++export interface OPReferrerSpikeCluster {+ /** Top-score spike's date — drives marker x position. */+ anchorDate: string | Date;+ /** Spikes in this cluster, sorted by score descending. Length >= 1. */+ spikes: OPReferrerSpikeItem[];+}++interface OPReferrerSpikesProps {+ items: OPReferrerSpikeCluster[] | null | undefined;+ /** Marker circle size in px. Defaults via OPMarkerLayer. */+ size?: number;+ /**+ * Fired when the user clicks a spike marker (collapsed favicon, or any+ * fanned-out individual marker). Receives the referrer's name so the+ * caller can drive a filter, navigation, etc.+ */+ onSpikeClick?: (referrerName: string) => void;+}++/**+ * Renders auto-detected referrer spike clusters through the shared marker+ * layer. Multi-spike clusters get count badges and fan out (either via+ * direct hover or when the chart's crosshair lands on one of their buckets).+ * Bidirectional hover is inherited from OPMarkerLayer. The favicon fills+ * the marker circle (see OPMarkerLayer's iconFill default).+ */+export function OPReferrerSpikes({+ items,+ size,+ onSpikeClick,+}: OPReferrerSpikesProps) {+ const clusters = useMemo<OPMarkerCluster[]>(() => {+ if (!items || items.length === 0) return [];+ return items.map((cluster) => {+ const markerItems: OPMarkerItem[] = cluster.spikes.map((spike) => ({+ date:+ typeof spike.date === 'string' ? new Date(spike.date) : spike.date,+ icon: <SerieIcon fill name={spike.referrer_name} />,+ title: spike.referrer_name,+ onClick: onSpikeClick+ ? () => onSpikeClick(spike.referrer_name)+ : undefined,+ }));+ return { anchorDate: cluster.anchorDate, items: markerItems };+ });+ }, [items, onSpikeClick]);++ return <OPMarkerLayer clusters={clusters} size={size} />;+}diff --git a/apps/start/src/components/charts/op-series-dots.tsx b/apps/start/src/components/charts/op-series-dots.tsxnew file mode 100644index 000000000..e7989380d--- /dev/null+++ b/apps/start/src/components/charts/op-series-dots.tsx@@ -0,0 +1,106 @@+import { motion, useSpring } from 'motion/react';+import { useEffect, useState } from 'react';+import { createPortal } from 'react-dom';+import { useChart } from './chart-context';++const SPRING = { stiffness: 1000, damping: 60 };++export interface OPSeriesDotConfig {+ /** dataKey of the series this dot belongs to. */+ dataKey: string;+ /** Fill color of the dot. */+ color: string;+ /** Optional 1-character label (e.g. "$") drawn inside the dot. */+ label?: string;+ /** Dot radius. Defaults to 5 (8 when `label` is set). */+ radius?: number;+}++interface OPSeriesDotsProps {+ dots: OPSeriesDotConfig[];+}++/**+ * Custom hover dots for bklit charts. Use when you need per-series styling+ * (e.g. a "$" inside the revenue dot) — bklit's `<TooltipDot>` is fixed-shape.+ *+ * Portals to the chart container above the crosshair (z-[51] > bklit's z-50)+ * so dots stay visible on top of the vertical crosshair indicator.+ *+ * Pair with `showDots={false}` on `<OPChartTooltip>` so dots aren't drawn twice.+ */+export function OPSeriesDots({ dots }: OPSeriesDotsProps) {+ const { tooltipData, containerRef, margin } = useChart();+ const [mounted, setMounted] = useState(false);+ useEffect(() => {+ setMounted(true);+ }, []);++ if (!mounted || !containerRef.current || !tooltipData) return null;++ return createPortal(+ <svg+ aria-hidden="true"+ className="pointer-events-none absolute inset-0 z-[51]"+ width="100%"+ height="100%"+ >+ <g transform={`translate(${margin.left}, ${margin.top})`}>+ {dots.map((dot) => {+ const xPos = tooltipData.xPositions?.[dot.dataKey] ?? tooltipData.x;+ const yPos = tooltipData.yPositions[dot.dataKey];+ if (yPos == null) return null;+ const radius = dot.radius ?? (dot.label ? 8 : 5);+ return (+ <OPDot+ key={dot.dataKey}+ x={xPos}+ y={yPos}+ color={dot.color}+ label={dot.label}+ radius={radius}+ />+ );+ })}+ </g>+ </svg>,+ containerRef.current,+ );+}++interface OPDotProps {+ x: number;+ y: number;+ color: string;+ label?: string;+ radius: number;+}++function OPDot({ x, y, color, label, radius }: OPDotProps) {+ const animatedX = useSpring(x, SPRING);+ const animatedY = useSpring(y, SPRING);+ animatedX.set(x);+ animatedY.set(y);++ return (+ <motion.g style={{ x: animatedX, y: animatedY }}>+ <circle+ r={radius}+ fill={color}+ stroke="var(--chart-background)"+ strokeWidth={2}+ />+ {label && (+ <text+ dy={radius * 0.35}+ textAnchor="middle"+ fill="white"+ fontSize={radius * 1.2}+ fontWeight={700}+ >+ {label}+ </text>+ )}+ </motion.g>+ );+}diff --git a/apps/start/src/components/charts/op-stat-hover-bridge.tsx b/apps/start/src/components/charts/op-stat-hover-bridge.tsxnew file mode 100644index 000000000..a19d8cc46--- /dev/null+++ b/apps/start/src/components/charts/op-stat-hover-bridge.tsx@@ -0,0 +1,37 @@+import { useEffect } from 'react';+import { useChart } from './chart-context';++export interface OPStatHoverState<T extends Record<string, unknown>> {+ /** Index of the hovered data point (null on mouse-leave). */+ index: number | null;+ /** The hovered data point (null on mouse-leave). */+ point: T | null;+}++interface OPStatHoverBridgeProps<T extends Record<string, unknown>> {+ onHoverChange: (state: OPStatHoverState<T>) => void;+}++/**+ * Tiny no-render child that lifts a bklit chart's hovered point out of context+ * and into parent state. Pair with `<ChartStatFlow>` (or any other display+ * primitive) to swap the visible value to the hovered one — used by stat cards+ * that don't want a popup tooltip.+ *+ * Modeled on bklit's `StatCardHoverBridge` from+ * `/Users/lindesvard/Projects/bklit-ui/apps/web/blocks/stat-card-area-01/`.+ */+export function OPStatHoverBridge<T extends Record<string, unknown>>({+ onHoverChange,+}: OPStatHoverBridgeProps<T>) {+ const { tooltipData } = useChart();+ const index = tooltipData?.index ?? null;+ const point = (tooltipData?.point as T | undefined) ?? null;++ // biome-ignore lint/correctness/useExhaustiveDependencies: only fire when hovered point changes+ useEffect(() => {+ onHoverChange({ index, point });+ }, [index, point]);++ return null;+}diff --git a/apps/start/src/components/charts/op-tooltip.tsx b/apps/start/src/components/charts/op-tooltip.tsxnew file mode 100644index 000000000..dd74dab7b--- /dev/null+++ b/apps/start/src/components/charts/op-tooltip.tsx@@ -0,0 +1,469 @@+import { getPreviousMetric } from '@openpanel/common';+import type { IInterval } from '@openpanel/validation';+import { type ReactNode, useMemo } from 'react';+import { SerieIcon } from '@/components/report-chart/common/serie-icon';+import { PreviousDiffIndicatorPure } from '../report-chart/common/previous-diff-indicator';+import { useChart } from './chart-context';+import type { ChartMarker } from './markers/marker-group';+import type { OPReferrerSpikeItem } from './op-referrer-spikes';+import { type OPReferenceItem, toChartMarkers } from './op-references';+import { ChartTooltip, type ChartTooltipProps } from './tooltip/chart-tooltip';+import { useFormatDateInterval } from '@/hooks/use-format-date-interval';+import { fancyMinutes, useNumber } from '@/hooks/use-numer-formatter';+import { cn } from '@/utils/cn';++export type OPTooltipUnit =+ | 'currency'+ | 'min'+ | 'pct'+ | 'count'+ | 'raw'+ | string;++export interface OPTooltipRow {+ /** Color of the left strip — typically getChartColor(index) */+ color: string;+ /** Row label / series name */+ label: ReactNode;+ /** Primary numeric value. Omit for rows that only use `sub`. */+ value?: number | null;+ /** How to format `value`. Default: 'count' (locale string). */+ unit?: OPTooltipUnit;+ /** Optional previous-period value — shown as "(prev)" next to value */+ previous?: number | null;+ /** Whether higher previous is better (e.g. bounce rate is inverted) */+ inverted?: boolean;+ /** Whether to render the percentage diff badge */+ showDiff?: boolean;+ /** Optional percentage to append after the value, e.g. "12.3 (45%)" */+ percentage?: number | null;+ /** Optional icon shown before the label */+ icon?: ReactNode;+ /** Sub-rows shown below the main row (no left strip color) */+ sub?: Array<{+ label: ReactNode;+ value: number | string | null | undefined;+ unit?: OPTooltipUnit;+ color?: string;+ }>;+}++export interface OPChartTooltipProps<T extends Record<string, unknown>>+ extends Omit<ChartTooltipProps, 'content' | 'rows'> {+ /** Interval drives the date format in the title (when title is omitted). */+ interval?: IInterval;+ /** Override the default date title. Return null to hide it. */+ title?: (point: T) => ReactNode;+ /** Map a hovered point to one or more tooltip rows. */+ rows: (point: T) => OPTooltipRow[];+ /** Render extra content below the rows (e.g. referrer breakdown). */+ extra?: (point: T) => ReactNode;+ /** Min width of the tooltip card. Default 200. */+ minWidth?: number;+ /** When set, references matching the hovered date are listed below the rows. */+ references?: OPReferenceItem[] | null;+ /** Max references to list in the tooltip. Default 3. */+ referencesLimit?: number;+ /** Auto-detected referrer spikes; the matching bucket's spike is shown below. */+ spikes?: OPReferrerSpikeItem[] | null;+}++export function OPChartTooltip<T extends Record<string, unknown>>({+ interval,+ title,+ rows,+ extra,+ minWidth = 200,+ references,+ referencesLimit = 3,+ spikes,+ ...rest+}: OPChartTooltipProps<T>) {+ const referenceMarkers = useMemo(+ () => toChartMarkers(references),+ [references]+ );++ return (+ <ChartTooltip+ {...rest}+ content={({ point }) => (+ <OPTooltipBody+ extra={extra ? extra(point as T) : null}+ interval={interval}+ minWidth={minWidth}+ point={point as T}+ referenceMarkers={referenceMarkers}+ referencesLimit={referencesLimit}+ rows={rows(point as T)}+ spikes={spikes ?? null}+ title={title ? title(point as T) : undefined}+ />+ )}+ />+ );+}++interface OPTooltipBodyProps<T> {+ point: T;+ interval?: IInterval;+ title?: ReactNode;+ rows: OPTooltipRow[];+ extra?: ReactNode;+ minWidth: number;+ referenceMarkers: ChartMarker[];+ referencesLimit: number;+ spikes: OPReferrerSpikeItem[] | null;+}++function OPTooltipBody<T extends Record<string, unknown>>({+ point,+ interval,+ title,+ rows,+ extra,+ minWidth,+ referenceMarkers,+ referencesLimit,+ spikes,+}: OPTooltipBodyProps<T>) {+ const formatDate = useFormatDateInterval({+ interval: interval ?? 'day',+ short: false,+ });+ const activeReferences = useReferencesForHoveredPoint(referenceMarkers);+ const activeSpike = useSpikeForHoveredPoint(spikes);++ const resolvedTitle = useMemo(() => {+ if (title === null) {+ return null;+ }+ if (title !== undefined) {+ return title;+ }+ const dateValue = point.date as Date | string | number | undefined;+ if (!dateValue) {+ return null;+ }+ return formatDate(new Date(dateValue));+ }, [title, point, formatDate]);++ return (+ <OPTooltipCard style={{ minWidth }}>+ {resolvedTitle != null && (+ <div className="flex justify-between gap-8 text-muted-foreground">+ <div>{resolvedTitle}</div>+ </div>+ )}+ {rows.map((row, index) => (+ <OPTooltipRowView key={`${row.label}-${index}`} row={row} />+ ))}+ {extra}+ <OPAnnotationsBlock+ references={activeReferences}+ referencesLimit={referencesLimit}+ spike={activeSpike}+ />+ </OPTooltipCard>+ );+}++/**+ * Returns references whose timestamp falls in the bucket of the currently+ * hovered data point. We snap each reference to its nearest data index and+ * compare against `tooltipData.index` — fine-grained enough for hourly /+ * minute intervals (bklit's built-in `useActiveMarkers` only matches by day).+ *+ * The nearest-index pass is O(refs × data) and only depends on inputs that+ * change rarely (refs, data), so it's precomputed once and cached. Hover+ * filtering then runs in O(refs) per mouse move instead of O(refs × data).+ */+function useReferencesForHoveredPoint(+ references: ChartMarker[]+): ChartMarker[] {+ const { tooltipData, data, xAccessor } = useChart();++ const nearestIndices = useMemo(+ () => computeNearestIndices(references, data, xAccessor, (m) => m.date),+ [references, data, xAccessor]+ );++ return useMemo(() => {+ if (!tooltipData || references.length === 0) {+ return [];+ }+ const hoveredIndex = tooltipData.index;+ return references.filter(+ (_, refIdx) => nearestIndices[refIdx] === hoveredIndex+ );+ }, [tooltipData, references, nearestIndices]);+}++function useSpikeForHoveredPoint(+ spikes: OPReferrerSpikeItem[] | null,+): OPReferrerSpikeItem | null {+ const { tooltipData, data, xAccessor } = useChart();++ const nearestIndices = useMemo(+ () =>+ computeNearestIndices(spikes ?? [], data, xAccessor, (s) =>+ typeof s.date === 'string' ? new Date(s.date) : s.date,+ ),+ [spikes, data, xAccessor],+ );++ return useMemo(() => {+ if (!tooltipData || !spikes || spikes.length === 0) {+ return null;+ }+ const hoveredIndex = tooltipData.index;+ for (let i = 0; i < spikes.length; i++) {+ if (nearestIndices[i] === hoveredIndex) {+ return spikes[i] ?? null;+ }+ }+ return null;+ }, [tooltipData, spikes, nearestIndices]);+}++/**+ * For each item, return the index of the nearest data point by xAccessor time.+ * Pre-computed once per (items, data, xAccessor) so hover handlers can do O(1)+ * lookups instead of O(items × data) scans on every mouse move.+ */+function computeNearestIndices<T>(+ items: T[],+ data: Record<string, unknown>[],+ xAccessor: (d: Record<string, unknown>) => Date,+ getDate: (item: T) => Date,+): number[] {+ if (items.length === 0 || data.length === 0) {+ return [];+ }+ const dataTimes = new Float64Array(data.length);+ for (let i = 0; i < data.length; i++) {+ const point = data[i];+ dataTimes[i] = point ? xAccessor(point).getTime() : Number.NaN;+ }+ return items.map((item) => {+ const target = getDate(item).getTime();+ let nearestIdx = 0;+ let minDiff = Number.POSITIVE_INFINITY;+ for (let i = 0; i < dataTimes.length; i++) {+ const t = dataTimes[i]!;+ if (Number.isNaN(t)) continue;+ const diff = Math.abs(t - target);+ if (diff < minDiff) {+ minDiff = diff;+ nearestIdx = i;+ }+ }+ return nearestIdx;+ });+}++function OPAnnotationsBlock({+ references,+ referencesLimit,+ spike,+}: {+ references: ChartMarker[];+ referencesLimit: number;+ spike: OPReferrerSpikeItem | null;+}) {+ const visibleRefs = references.slice(0, referencesLimit);+ const hiddenRefs = Math.max(0, references.length - referencesLimit);+ if (visibleRefs.length === 0 && !spike) return null;++ return (+ <div className="col mt-1 gap-2 border-border border-t pt-2">+ {visibleRefs.map((marker) => (+ <OPAnnotationRow+ key={marker.title}+ icon={marker.icon}+ title={marker.title}+ description={marker.description}+ />+ ))}+ {hiddenRefs > 0 && (+ <div className="pl-8 text-muted-foreground text-xs">+ +{hiddenRefs} more+ </div>+ )}+ {spike && <OPSpikeAnnotation spike={spike} />}+ </div>+ );+}++function OPSpikeAnnotation({ spike }: { spike: OPReferrerSpikeItem }) {+ const number = useNumber();+ const sessionsLabel = `${number.short(spike.sessions)} sessions`;+ const comparison = spike.isNew+ ? 'first time this period'+ : `${spike.ratio.toFixed(1)}× typical`;+ const sharePct = `${Math.round(spike.share * 100)}% of bucket`;++ const description = (+ <>+ <div className="truncate">+ {sessionsLabel} · {comparison} · {sharePct}+ </div>+ {spike.others.length > 0 && (+ <div className="mt-0.5 truncate">+ + also: {spike.others.map((o) => o.referrer_name).join(', ')}+ </div>+ )}+ </>+ );++ return (+ <OPAnnotationRow+ icon={<SerieIcon fill name={spike.referrer_name} />}+ title={`Spike from ${spike.referrer_name}`}+ description={description}+ />+ );+}++/**+ * Single row used for every tooltip annotation (user references + auto-+ * detected referrer spikes). Matches the chart-marker visual: the icon+ * fills the circle, surrounded by a high-contrast border. Callers pass+ * fill-aware icons (e.g. `<SerieIcon fill />` or a sized Lucide icon).+ */+function OPAnnotationRow({+ icon,+ title,+ description,+}: {+ icon: ReactNode;+ title: ReactNode;+ description?: ReactNode;+}) {+ return (+ <div className="flex items-start gap-2">+ <div className="mt-0.5 flex size-5 shrink-0 items-center justify-center overflow-hidden rounded-full border border-foreground text-foreground">+ {icon}+ </div>+ <div className="col min-w-0 flex-1 gap-0.5">+ <div className="truncate font-medium text-sm leading-tight">+ {title}+ </div>+ {description && (+ <div className="truncate text-muted-foreground text-xs leading-snug">+ {description}+ </div>+ )}+ </div>+ </div>+ );+}++export function OPTooltipCard({+ children,+ className,+ style,+}: {+ children: ReactNode;+ className?: string;+ style?: React.CSSProperties;+}) {+ return (+ <div+ className={cn(+ 'col gap-2 rounded-xl border border-border/60 p-3 text-foreground shadow-xl',+ className+ )}+ style={style}+ >+ {children}+ </div>+ );+}++function OPTooltipRowView({ row }: { row: OPTooltipRow }) {+ const number = useNumber();+ const hasValue = row.value != null;+ const prev = row.previous ?? null;+ const showPrev = prev != null && prev !== 0;+ const showDiff = row.showDiff !== false && showPrev;+ const diff =+ showDiff && hasValue ? getPreviousMetric(row.value!, prev) : null;++ return (+ <div className="flex gap-2">+ <div className="w-[3px] rounded-full" style={{ background: row.color }} />+ <div className="col min-w-0 flex-1 gap-1">+ <div className="flex min-w-0 items-center gap-1">+ {row.icon && (+ <span className="flex shrink-0 items-center">{row.icon}</span>+ )}+ <span className="truncate font-medium">{row.label}</span>+ </div>+ {hasValue && (+ <div className="flex items-center justify-between gap-8 font-medium font-mono">+ <div className="row items-baseline gap-1">+ <span>{formatOPValue(row.value!, row.unit, number)}</span>+ {showPrev && (+ <span className="text-muted-foreground">+ ({formatOPValue(prev, row.unit, number)})+ </span>+ )}+ {row.percentage != null && (+ <span className="text-muted-foreground">+ ({number.format(row.percentage)}%)+ </span>+ )}+ </div>+ {diff && (+ <PreviousDiffIndicatorPure {...diff} inverted={row.inverted} />+ )}+ </div>+ )}++ {row.sub && row.sub.length > 0 && (+ <div className="col gap-1 text-sm">+ {row.sub.map((s, i) => (+ <div+ className="flex justify-between gap-8 font-medium font-mono"+ key={`${typeof s.label === 'string' ? s.label : i}-${i}`}+ >+ <span className="text-muted-foreground">{s.label}</span>+ <span style={s.color ? { color: s.color } : undefined}>+ {formatOPValue(s.value as number | string, s.unit, number)}+ </span>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ );+}++function formatOPValue(+ value: number | string | null | undefined,+ unit: OPTooltipUnit | undefined,+ number: ReturnType<typeof useNumber>+): string {+ if (value == null) {+ return '–';+ }+ if (typeof value === 'string') {+ return value;+ }++ switch (unit) {+ case 'currency':+ // Stored in cents — convert to dollars+ return number.currency(value / 100, { short: true });+ case 'min':+ return fancyMinutes(value);+ case 'pct':+ return `${number.format(value)} %`;+ case 'raw':+ return String(value);+ default:+ return number.short(value);+ }+}diff --git a/apps/start/src/components/charts/path-stroke-utils.ts b/apps/start/src/components/charts/path-stroke-utils.tsnew file mode 100644index 000000000..90adc88dd--- /dev/null+++ b/apps/start/src/components/charts/path-stroke-utils.ts@@ -0,0 +1,75 @@+import { type RefObject, useEffect, useState } from "react";++export function findPathLengthAtX(+ path: SVGPathElement | null,+ pathLength: number,+ targetX: number+): number {+ if (!path || pathLength === 0) {+ return 0;+ }+ let low = 0;+ let high = pathLength;+ const tolerance = 0.5;++ while (high - low > tolerance) {+ const mid = (low + high) / 2;+ const point = path.getPointAtLength(mid);+ if (point.x < targetX) {+ low = mid;+ } else {+ high = mid;+ }+ }+ return (low + high) / 2;+}++export function usePathStrokeMetrics(+ pathRef: RefObject<SVGPathElement | null>,+ remeasureKey: string+) {+ const [pathLength, setPathLength] = useState(0);+ const [pathD, setPathD] = useState<string | null>(null);++ // biome-ignore lint/correctness/useExhaustiveDependencies: remeasure when series geometry changes+ useEffect(() => {+ const path = pathRef.current;+ if (!path) {+ return;+ }+ const len = path.getTotalLength();+ const d = path.getAttribute("d");+ if (len > 0) {+ setPathLength(len);+ }+ if (d) {+ setPathD(d);+ }+ }, [remeasureKey, pathRef]);++ return { pathLength, pathD };+}++export function resolveDashTailBounds(+ dashFromIndex: number | undefined,+ dataLength: number+): boolean {+ return (+ dashFromIndex != null &&+ dashFromIndex >= 0 &&+ dashFromIndex < dataLength - 1+ );+}++export function resolveDashStartX(+ data: Record<string, unknown>[],+ dashFromIndex: number,+ xScale: (value: Date | number) => number | undefined,+ xAccessor: (datum: Record<string, unknown>) => Date | number+): number {+ const dashFromPoint = data[dashFromIndex];+ if (!dashFromPoint) {+ return 0;+ }+ return xScale(xAccessor(dashFromPoint)) ?? 0;+}diff --git a/apps/start/src/components/charts/pattern-area.tsx b/apps/start/src/components/charts/pattern-area.tsxnew file mode 100644index 000000000..99a317c81--- /dev/null+++ b/apps/start/src/components/charts/pattern-area.tsx@@ -0,0 +1,49 @@+"use client";++import { curveMonotoneX } from "@visx/curve";+import { AreaClosed } from "@visx/shape";+import { useChartStable } from "./chart-context";++// biome-ignore lint/suspicious/noExplicitAny: d3 curve factory type+type CurveFactory = any;++export interface PatternAreaProps {+ /** Key in data to use for y values */+ dataKey: string;+ /** Fill color or pattern URL (e.g. `url(#pattern-id)`) */+ fill: string;+ /** Curve function. Default: curveMonotoneX */+ curve?: CurveFactory;+ /** @deprecated Pattern fill is not clip-revealed; only the stroke `Area` animates. */+ animate?: boolean;+}++/**+ * Filled area using an SVG pattern (`url(#id)`).+ * Pair with `PatternLines` in `AreaChart` children and an `Area` with `fillOpacity={0}` for the stroke line.+ */+export function PatternArea({+ dataKey,+ fill,+ curve = curveMonotoneX,+}: PatternAreaProps) {+ const { data, xScale, yScale, xAccessor } = useChartStable();++ return (+ <AreaClosed+ curve={curve}+ data={data}+ fill={fill}+ x={(d) => xScale(xAccessor(d)) ?? 0}+ y={(d) => {+ const v = d[dataKey];+ return typeof v === "number" ? (yScale(v) ?? 0) : 0;+ }}+ yScale={yScale}+ />+ );+}++PatternArea.displayName = "PatternArea";++export default PatternArea;diff --git a/apps/start/src/components/charts/series-bar-layout.ts b/apps/start/src/components/charts/series-bar-layout.tsnew file mode 100644index 000000000..ed2249b85--- /dev/null+++ b/apps/start/src/components/charts/series-bar-layout.ts@@ -0,0 +1,61 @@+export function computeSeriesBarWidth(input: {+ innerWidth: number;+ dataLength: number;+ columnWidth: number;+ seriesCount: number;+ composedBarSize?: number;+ composedMaxBarSize?: number;+ composedBarGap?: number;+ stacked?: boolean;+}): number {+ const {+ innerWidth,+ dataLength,+ columnWidth,+ seriesCount,+ composedBarSize,+ composedMaxBarSize,+ composedBarGap = 4,+ stacked = false,+ } = input;++ const gap = composedBarGap;+ const groupCount = stacked ? 1 : Math.max(1, seriesCount);+ let slot = columnWidth;+ if (slot <= 0) {+ slot = dataLength < 2 ? innerWidth : innerWidth / (dataLength - 1);+ }++ let width =+ composedBarSize ??+ Math.min(slot * 0.88, composedMaxBarSize ?? Number.POSITIVE_INFINITY);+ if (composedMaxBarSize != null) {+ width = Math.min(width, composedMaxBarSize);+ }+ if (groupCount > 1) {+ const maxGroup = slot * 0.92;+ const needed = groupCount * width + (groupCount - 1) * gap;+ if (needed > maxGroup && maxGroup > 0) {+ width = Math.max(4, (maxGroup - (groupCount - 1) * gap) / groupCount);+ }+ }++ return Math.max(2, width);+}++/** Half-width of the bar group at each x — used to pad reveal clips. */+export function computeSeriesBarRevealClipPadding(input: {+ barWidth: number;+ seriesCount: number;+ gap?: number;+ stacked?: boolean;+}): number {+ const { barWidth, seriesCount, gap = 4, stacked = false } = input;++ if (stacked || seriesCount <= 1) {+ return Math.ceil(barWidth / 2);+ }++ const groupWidth = seriesCount * barWidth + (seriesCount - 1) * gap;+ return Math.ceil(groupWidth / 2);+}diff --git a/apps/start/src/components/charts/series-bar.tsx b/apps/start/src/components/charts/series-bar.tsxnew file mode 100644index 000000000..1da6b55fa--- /dev/null+++ b/apps/start/src/components/charts/series-bar.tsx@@ -0,0 +1,316 @@+"use client";++import type { Transition } from "motion/react";+import { motion } from "motion/react";+import { useMemo } from "react";+import { chartCssVars, useChart } from "./chart-context";+import { transitionWithDelay } from "./motion-utils";+import { computeSeriesBarWidth } from "./series-bar-layout";++function computeSeriesBarLayout(input: {+ stacked: boolean;+ composedStackOffsets: Map<number, Map<string, number>> | undefined;+ rowIndex: number;+ dataKey: string;+ value: number;+ yScale: (n: number) => number | undefined;+ innerHeight: number;+ xCenter: number;+ barWidth: number;+ seriesCount: number;+ gap: number;+ seriesIndex: number;+ stackGap: number;+ isLastSeries: boolean;+ radius: number;+}): {+ barLeft: number;+ barHeight: number;+ effectiveRadius: number;+ valueY: number;+} {+ const {+ stacked,+ composedStackOffsets,+ rowIndex,+ dataKey,+ value,+ yScale,+ innerHeight,+ xCenter,+ barWidth,+ seriesCount,+ gap,+ seriesIndex,+ stackGap,+ isLastSeries,+ radius,+ } = input;++ if (stacked && composedStackOffsets) {+ const offset = composedStackOffsets.get(rowIndex)?.get(dataKey) ?? 0;+ const valuePos = yScale(value) ?? 0;+ let barHeight = innerHeight - valuePos;+ const offsetY = yScale(offset) ?? innerHeight;+ const gapOffset = seriesIndex * stackGap;+ const valueY = offsetY - barHeight - gapOffset;+ if (!isLastSeries && stackGap > 0) {+ barHeight = Math.max(0, barHeight - stackGap);+ }+ const barLeft = xCenter - barWidth / 2;+ const applyRounding = stackGap > 0 || isLastSeries;+ return {+ barLeft,+ barHeight,+ effectiveRadius: applyRounding ? radius : 0,+ valueY,+ };+ }++ const groupWidth =+ seriesCount * barWidth + (seriesCount > 1 ? (seriesCount - 1) * gap : 0);+ const valueY = yScale(value) ?? innerHeight;+ return {+ barLeft: xCenter - groupWidth / 2 + seriesIndex * (barWidth + gap),+ barHeight: innerHeight - valueY,+ effectiveRadius: radius,+ valueY,+ };+}++export interface SeriesBarProps {+ /** Key in data for bar height (y value) */+ dataKey: string;+ /** Fill color. Default: var(--chart-line-primary) */+ fill?: string;+ /** Tooltip dot color when fill is gradient/pattern. Default: fill */+ stroke?: string;+ /** Corner radius for bar top corners. Default: 0 (square tops, similar to Bar lineCap="butt") */+ radius?: number;+ /** Animate grow from baseline. Default: true */+ animate?: boolean;+ /** Opacity for non-hovered bars when another point is hovered (matches BarChart). Default: 0.3 */+ fadedOpacity?: number;+}++export function SeriesBar({+ dataKey,+ fill = chartCssVars.linePrimary,+ radius = 0,+ animate = true,+ fadedOpacity = 0.3,+}: SeriesBarProps) {+ const {+ data,+ xScale,+ yScale,+ xAccessor,+ innerHeight,+ innerWidth,+ columnWidth,+ isLoaded,+ animationDuration,+ enterTransition,+ revealEpoch = 0,+ barScale,+ composedBarDataKeys,+ composedBarSize,+ composedMaxBarSize,+ composedBarGap,+ composedStacked,+ composedStackOffsets,+ composedStackGap,+ tooltipData,+ } = useChart();++ const barKeys = useMemo(() => {+ if (composedBarDataKeys && composedBarDataKeys.length > 0) {+ return composedBarDataKeys;+ }+ return [dataKey];+ }, [composedBarDataKeys, dataKey]);++ const seriesIndex = useMemo(() => {+ const idx = barKeys.indexOf(dataKey);+ return idx >= 0 ? idx : 0;+ }, [barKeys, dataKey]);++ const n = barKeys.length;+ const gap = composedBarGap ?? 4;+ const stackGap = composedStackGap ?? 0;++ const stacked =+ Boolean(composedStacked) &&+ composedStackOffsets != null &&+ composedBarDataKeys != null &&+ composedBarDataKeys.length > 0;++ const isLastSeries = seriesIndex === n - 1;++ const barWidth = useMemo(+ () =>+ computeSeriesBarWidth({+ innerWidth,+ dataLength: data.length,+ columnWidth,+ seriesCount: n,+ composedBarSize,+ composedMaxBarSize,+ composedBarGap: gap,+ stacked,+ }),+ [+ columnWidth,+ composedBarSize,+ composedMaxBarSize,+ data.length,+ gap,+ innerWidth,+ n,+ stacked,+ ]+ );++ const totalAnimDuration = animationDuration || 1100;+ const staggerSpread = totalAnimDuration * 0.4;+ const calculatedStaggerDelay =+ data.length > 1 ? staggerSpread / 1000 / data.length : 0;+ if (barScale) {+ console.warn(+ "SeriesBar is for time-based ComposedChart / LineChart context. Use Bar inside BarChart for categorical x."+ );+ return null;+ }++ const hoveredIndex = tooltipData?.index ?? null;++ return (+ <g className="series-bar">+ {data.map((d, i) => {+ const value = d[dataKey];+ if (typeof value !== "number") {+ return null;+ }++ const xCenter = xScale(xAccessor(d)) ?? 0;++ const { barLeft, valueY, barHeight, effectiveRadius } =+ computeSeriesBarLayout({+ stacked,+ composedStackOffsets,+ rowIndex: i,+ dataKey,+ value,+ yScale,+ innerHeight,+ xCenter,+ barWidth,+ seriesCount: n,+ gap,+ seriesIndex,+ stackGap,+ isLastSeries,+ radius,+ });++ const categoryLabel = String(xAccessor(d).getTime());+ const isFaded = hoveredIndex !== null && hoveredIndex !== i;++ if (animate && !isLoaded) {+ return (+ <SeriesBarRect+ barHeight={barHeight}+ barWidth={barWidth}+ calculatedStaggerDelay={calculatedStaggerDelay}+ enterTransition={enterTransition}+ fadedOpacity={fadedOpacity}+ fill={fill}+ index={i}+ innerHeight={innerHeight}+ isFaded={isFaded}+ key={`${dataKey}-${categoryLabel}-${revealEpoch}`}+ radius={effectiveRadius}+ revealEpoch={revealEpoch}+ x={barLeft}+ y={valueY}+ />+ );+ }++ return (+ <motion.rect+ animate={{ opacity: isFaded ? fadedOpacity : 1 }}+ fill={fill}+ height={barHeight}+ key={`${dataKey}-${categoryLabel}`}+ rx={effectiveRadius}+ ry={effectiveRadius}+ transition={{ opacity: { duration: 0.12 } }}+ width={barWidth}+ x={barLeft}+ y={valueY}+ />+ );+ })}+ </g>+ );+}++SeriesBar.displayName = "SeriesBar";++interface SeriesBarRectProps {+ x: number;+ y: number;+ barWidth: number;+ barHeight: number;+ fill: string;+ radius: number;+ index: number;+ innerHeight: number;+ calculatedStaggerDelay: number;+ enterTransition?: Transition;+ revealEpoch: number;+ isFaded: boolean;+ fadedOpacity: number;+}++function SeriesBarRect({+ x,+ y,+ barWidth,+ barHeight,+ fill,+ radius,+ index,+ innerHeight,+ calculatedStaggerDelay,+ enterTransition,+ revealEpoch,+ isFaded,+ fadedOpacity,+}: SeriesBarRectProps) {+ const enterAnim = transitionWithDelay(+ enterTransition,+ index * calculatedStaggerDelay+ );++ return (+ <motion.rect+ animate={{+ height: barHeight,+ y,+ opacity: isFaded ? fadedOpacity : 1,+ }}+ fill={fill}+ initial={{ height: 0, y: innerHeight, opacity: 1 }}+ key={`series-bar-${index}-${revealEpoch}`}+ rx={radius}+ ry={radius}+ transition={enterAnim}+ width={barWidth}+ x={x}+ />+ );+}++export default SeriesBar;diff --git a/apps/start/src/components/charts/series-dash-tail-overlay.tsx b/apps/start/src/components/charts/series-dash-tail-overlay.tsxnew file mode 100644index 000000000..514e2d7d5--- /dev/null+++ b/apps/start/src/components/charts/series-dash-tail-overlay.tsx@@ -0,0 +1,82 @@+"use client";++import { memo, useMemo } from "react";+import { DashTailStroke } from "./dash-tail-stroke";+import { resolveDashStartX, resolveDashTailBounds } from "./path-stroke-utils";++interface SeriesDashTailOverlayProps {+ dashFromIndex?: number;+ dashArray: string;+ data: Record<string, unknown>[];+ pathD: string | null;+ pathLength: number;+ innerWidth: number;+ innerHeight: number;+ stroke: string;+ strokeWidth: number;+ xScale: (value: Date | number) => number | undefined;+ xAccessor: (datum: Record<string, unknown>) => Date | number;+}++function SeriesDashTailOverlayImpl({+ dashFromIndex,+ dashArray,+ data,+ pathD,+ pathLength,+ innerWidth,+ innerHeight,+ stroke,+ strokeWidth,+ xScale,+ xAccessor,+}: SeriesDashTailOverlayProps) {+ const hasDashTail = resolveDashTailBounds(dashFromIndex, data.length);++ const dashStartX = useMemo(() => {+ if (!hasDashTail || dashFromIndex == null) {+ return 0;+ }+ return resolveDashStartX(data, dashFromIndex, xScale, xAccessor);+ }, [hasDashTail, dashFromIndex, data, xScale, xAccessor]);++ // Linear (index-based) approximation of the path length at `dashFromIndex`.+ // The accurate version (`findPathLengthAtX` binary search via+ // `getPointAtLength`) is exact but cost ~40 ms per series on a 365-point+ // bezier — for charts with ~10 series that synchronously blocks the main+ // thread for ~400 ms on the post-measurement re-render, swallowing the first+ // second of the entrance animation.+ //+ // For evenly-spaced time-series data — the standard case — this is exact at+ // flat regions of the curve and only differs by a pixel or two where the+ // curve has steep y-variation, which is imperceptible at the dash boundary.+ const dashStartLength = useMemo(() => {+ if (!hasDashTail || dashFromIndex == null || pathLength <= 0) {+ return 0;+ }+ return (dashFromIndex / Math.max(1, data.length - 1)) * pathLength;+ }, [hasDashTail, dashFromIndex, data.length, pathLength]);++ if (!hasDashTail || dashFromIndex == null || pathLength <= 0) {+ return null;+ }++ return (+ <DashTailStroke+ dashArray={dashArray}+ dashStartLength={dashStartLength}+ dashStartX={dashStartX}+ innerHeight={innerHeight}+ innerWidth={innerWidth}+ pathD={pathD}+ pathLength={pathLength}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ );+}++// All props originate from the chart's stable context slice (data, xScale,+// xAccessor, …) or are mount-stable strings (gradient `url(#…)` ids). Shallow+// compare lets us skip the path-length binary search on every cursor move.+export const SeriesDashTailOverlay = memo(SeriesDashTailOverlayImpl);diff --git a/apps/start/src/components/charts/series-highlight-layer.tsx b/apps/start/src/components/charts/series-highlight-layer.tsxnew file mode 100644index 000000000..c2dbb3cb3--- /dev/null+++ b/apps/start/src/components/charts/series-highlight-layer.tsx@@ -0,0 +1,49 @@+"use client";++import type { RefObject } from "react";+import { useChartStable } from "./chart-context";+import { HighlightSegment } from "./highlight-segment";+import { useHighlightSegment } from "./use-highlight-segment";++interface SeriesHighlightLayerProps {+ /** Caller already gated `showHighlight && showLine`; this just routes through. */+ enabled: boolean;+ height: number;+ pathRef: RefObject<SVGPathElement | null>;+ stroke: string;+ strokeWidth: number;+}++/**+ * Self-contained hover-highlight band over a series stroke.+ *+ * Owns the `useHighlightSegment` subscription (which reads both stable + hover+ * context) so the parent <Area> / <Line> can stay on the stable slice. This+ * component still re-renders on hover — that's the price of driving the+ * highlight band — but it's a tiny leaf so the cost is bounded to itself.+ */+export function SeriesHighlightLayer({+ enabled,+ height,+ pathRef,+ stroke,+ strokeWidth,+}: SeriesHighlightLayerProps) {+ const { isLoaded } = useChartStable();+ const { xSpring, widthSpring, isActive } = useHighlightSegment({ enabled });+ return (+ <HighlightSegment+ height={height}+ pathRef={pathRef}+ stroke={stroke}+ strokeWidth={strokeWidth}+ visible={enabled && isActive && isLoaded}+ width={widthSpring}+ x={xSpring}+ />+ );+}++SeriesHighlightLayer.displayName = "SeriesHighlightLayer";++export default SeriesHighlightLayer;diff --git a/apps/start/src/components/charts/series-hover-dim.tsx b/apps/start/src/components/charts/series-hover-dim.tsxnew file mode 100644index 000000000..eb935a3dc--- /dev/null+++ b/apps/start/src/components/charts/series-hover-dim.tsx@@ -0,0 +1,50 @@+"use client";++import { motion } from "motion/react";+import type { ReactNode } from "react";+import { useChartHover } from "./chart-context";++interface SeriesHoverDimProps {+ /** Skip the dim entirely. */+ enabled?: boolean;+ /** Opacity to fade to while the chart is being hovered. */+ dimOpacity?: number;+ /** Tween duration in seconds. */+ durationSec?: number;+ /** Stable chart visuals — area fill, stroke line, dashed tail, etc. */+ children: ReactNode;+}++/**+ * Wraps stable series visuals with a hover-driven opacity animation.+ *+ * The wrapper subscribes to chart hover state internally so the parent (Area /+ * Line) can stay on the stable context slice. Children come in as a React prop:+ * because the parent is not re-rendering on hover, the children element+ * reference stays identical and React skips re-rendering them when this+ * wrapper re-renders. That keeps expensive subtrees (`SeriesDashTailOverlay`+ * and its `getPointAtLength` binary search) quiescent on cursor motion.+ */+export function SeriesHoverDim({+ enabled = true,+ dimOpacity = 0.5,+ durationSec = 0.4,+ children,+}: SeriesHoverDimProps) {+ const { tooltipData, selection } = useChartHover();+ const isHovering = tooltipData !== null || selection?.active === true;+ const opacity = enabled && isHovering ? dimOpacity : 1;+ return (+ <motion.g+ animate={{ opacity }}+ initial={{ opacity: 1 }}+ transition={{ duration: durationSec, ease: "easeInOut" }}+ >+ {children}+ </motion.g>+ );+}++SeriesHoverDim.displayName = "SeriesHoverDim";++export default SeriesHoverDim;diff --git a/apps/start/src/components/charts/series-markers.tsx b/apps/start/src/components/charts/series-markers.tsxnew file mode 100644index 000000000..7372f5d46--- /dev/null+++ b/apps/start/src/components/charts/series-markers.tsx@@ -0,0 +1,286 @@+"use client";++import { type ReactNode, useCallback, useMemo } from "react";+import { clipRevealTransition } from "./animation";+import {+ defaultScatterColors,+ useChartHover,+ useChartStable,+} from "./chart-context";+import {+ getSeriesMarkerVisualExtent,+ SeriesPointMarker,+ type SeriesPointMarkerStyle,+ StaticSeriesPointMarker,+} from "./series-point-marker";++export interface SeriesMarkersProps extends SeriesPointMarkerStyle {+ dataKey: string;+ /** Marker fill color. Defaults to series stroke or chart palette color. */+ fill?: string;+ /** Whether to animate markers with clip reveal. Default: true */+ animate?: boolean;+}++interface PointAt {+ index: number;+ cx: number;+ cy: number;+ revealDelay: number;+}++interface MarkerStyle {+ fill: string;+ stroke: string;+ strokeWidth: number;+ ringGap: number;+ outlineWidth: number;+ outlineColor?: string;+ radius: number;+}++export function SeriesMarkers({+ dataKey,+ fill,+ stroke,+ strokeWidth = 2,+ ringGap = 2,+ outlineWidth = 0,+ outlineColor,+ radius = 5,+ animate = true,+ fadeOnHover = true,+ inactiveOpacity = 0.5,+ inactiveBlur = 2,+ enterBlur = 2,+ showActiveHighlight = true,+}: SeriesMarkersProps) {+ // Stable slice only. Hover-driven dim + active-highlight live in the inner+ // <SeriesMarkersDimWrapper> / <SeriesMarkersActiveHighlight> components, so+ // mouse motion does not re-render the full point grid.+ const {+ data,+ xScale,+ yScale,+ innerWidth,+ enterTransition,+ animationDuration,+ revealEpoch,+ isLoaded,+ xAccessor,+ lines,+ } = useChartStable();++ const seriesIndex = useMemo(() => {+ const index = lines.findIndex((line) => line.dataKey === dataKey);+ return index >= 0 ? index : 0;+ }, [lines, dataKey]);++ const seriesConfig = lines[seriesIndex];+ const seriesColor =+ defaultScatterColors[seriesIndex % defaultScatterColors.length] ??+ defaultScatterColors[0];++ const resolvedFill = fill ?? seriesConfig?.stroke ?? seriesColor;+ const resolvedStroke = stroke ?? resolvedFill;++ const visualExtent = useMemo(+ () =>+ getSeriesMarkerVisualExtent({+ radius,+ strokeWidth,+ ringGap,+ outlineWidth,+ showActiveHighlight,+ }),+ [radius, strokeWidth, ringGap, outlineWidth, showActiveHighlight]+ );++ const revealDurationSec =+ clipRevealTransition(enterTransition).duration ?? animationDuration / 1000;+ const enterDuration = 0.5;+ const isRevealing = animate && !isLoaded;++ const getY = useCallback(+ (d: Record<string, unknown>) => {+ const value = d[dataKey];+ return typeof value === "number" ? (yScale(value) ?? 0) : null;+ },+ [dataKey, yScale]+ );++ const points = useMemo<PointAt[]>(+ () =>+ data.flatMap((d, index) => {+ const cy = getY(d);+ if (cy === null) {+ return [];+ }+ const cx = xScale(xAccessor(d)) ?? 0;+ const leadingEdge = Math.max(0, cx - visualExtent);+ const revealDelay =+ innerWidth > 0 && isRevealing+ ? (leadingEdge / innerWidth) * revealDurationSec+ : 0;++ return [{ index, cx, cy, revealDelay }];+ }),+ [+ data,+ getY,+ xScale,+ xAccessor,+ innerWidth,+ isRevealing,+ revealDurationSec,+ visualExtent,+ ]+ );++ // Memo so the inner <SeriesMarkersActiveHighlight> sees a stable prop and+ // can be cheaply re-rendered on hover without re-creating the spread.+ const markerStyle = useMemo<MarkerStyle>(+ () => ({+ fill: resolvedFill,+ stroke: resolvedStroke,+ strokeWidth,+ ringGap,+ outlineWidth,+ outlineColor,+ radius,+ }),+ [+ resolvedFill,+ resolvedStroke,+ strokeWidth,+ ringGap,+ outlineWidth,+ outlineColor,+ radius,+ ]+ );++ if (isRevealing) {+ return (+ <g>+ {points.map((point) => (+ <SeriesPointMarker+ cx={point.cx}+ cy={point.cy}+ dataKey={dataKey}+ enterBlur={enterBlur}+ enterDuration={enterDuration}+ index={point.index}+ key={`${dataKey}-${point.index}`}+ revealDelay={point.revealDelay}+ revealEpoch={revealEpoch ?? 0}+ {...markerStyle}+ />+ ))}+ </g>+ );+ }++ // Stable base layer — its children come from the parent and stay+ // referentially identical when the dim wrapper re-renders for hover.+ const baseMarkers = points.map((point) => (+ <StaticSeriesPointMarker+ cx={point.cx}+ cy={point.cy}+ key={`${dataKey}-${point.index}`}+ {...markerStyle}+ />+ ));+ const activeScale = showActiveHighlight ? 1.35 : 1;++ return (+ <g>+ <SeriesMarkersDimWrapper+ enabled={fadeOnHover}+ inactiveBlur={inactiveBlur}+ inactiveOpacity={inactiveOpacity}+ >+ {baseMarkers}+ </SeriesMarkersDimWrapper>+ <SeriesMarkersActiveHighlight+ activeScale={activeScale}+ enabled={fadeOnHover}+ markerStyle={markerStyle}+ points={points}+ />+ </g>+ );+}++SeriesMarkers.displayName = "SeriesMarkers";++interface SeriesMarkersDimWrapperProps {+ enabled: boolean;+ inactiveOpacity: number;+ inactiveBlur: number;+ children: ReactNode;+}++/**+ * Wraps the stable point grid with hover-driven opacity + blur. Subscribes to+ * hover internally so the grid (passed as `children`) keeps a stable reference+ * and React skips reconciling it when this wrapper re-renders.+ */+function SeriesMarkersDimWrapper({+ enabled,+ inactiveOpacity,+ inactiveBlur,+ children,+}: SeriesMarkersDimWrapperProps) {+ const { tooltipData } = useChartHover();+ const dimBase = enabled && tooltipData !== null;+ return (+ <g+ opacity={dimBase ? inactiveOpacity : 1}+ style={{+ transition: "opacity 0.15s ease-in-out, filter 0.15s ease-in-out",+ filter:+ dimBase && inactiveBlur > 0 ? `blur(${inactiveBlur}px)` : "none",+ }}+ >+ {children}+ </g>+ );+}++interface SeriesMarkersActiveHighlightProps {+ enabled: boolean;+ points: PointAt[];+ markerStyle: MarkerStyle;+ activeScale: number;+}++/**+ * Renders the scaled "active" marker on top of the base grid. Subscribes to+ * hover internally; the parent doesn't re-render on cursor motion.+ */+function SeriesMarkersActiveHighlight({+ enabled,+ points,+ markerStyle,+ activeScale,+}: SeriesMarkersActiveHighlightProps) {+ const { tooltipData } = useChartHover();+ if (!enabled || tooltipData === null) {+ return null;+ }+ const activePoint = points.find((point) => point.index === tooltipData.index);+ if (!activePoint) {+ return null;+ }+ return (+ <StaticSeriesPointMarker+ cx={activePoint.cx}+ cy={activePoint.cy}+ scale={activeScale}+ {...markerStyle}+ />+ );+}++export default SeriesMarkers;diff --git a/apps/start/src/components/charts/series-point-marker.tsx b/apps/start/src/components/charts/series-point-marker.tsxnew file mode 100644index 000000000..d352bd3db--- /dev/null+++ b/apps/start/src/components/charts/series-point-marker.tsx@@ -0,0 +1,209 @@+"use client";++import type { Variants } from "motion/react";+import { motion } from "motion/react";+import { memo } from "react";+import { DEFAULT_CHART_ENTER_TRANSITION } from "./animation";++export interface SeriesPointMarkerStyle {+ /** Fill color for the inner circle */+ fill?: string;+ /** Outer ring stroke color. Default: same as `fill` */+ stroke?: string;+ /** Outer ring stroke width in px. Default: 2. Set to 0 to disable. */+ strokeWidth?: number;+ /** Gap between the inner fill and outer ring in px. Default: 2 */+ ringGap?: number;+ /** Optional outer outline beyond the ring. Default: 0 */+ outlineWidth?: number;+ /** Outer outline color. Default: same as `stroke` */+ outlineColor?: string;+ /** Point radius in px. Default: 5 */+ radius?: number;+ /** Dim non-active points while hovering. Default: true */+ fadeOnHover?: boolean;+ /** Opacity for non-hovered points when `fadeOnHover` is true. Default: 0.5 */+ inactiveOpacity?: number;+ /**+ * Blur in px for non-hovered points when `fadeOnHover` is true.+ * Applied once on the dimmed layer (not per dot) for performance. Default: 2+ */+ inactiveBlur?: number;+ /** Initial blur in px during enter animation. Default: 2 */+ enterBlur?: number;+ /** Enlarge the active point while hovering. Default: true */+ showActiveHighlight?: boolean;+}++interface MarkerCirclesProps {+ fill?: string;+ stroke?: string;+ strokeWidth: number;+ ringGap: number;+ outlineWidth: number;+ outlineColor?: string;+ radius: number;+}++function MarkerCircles({+ fill,+ stroke,+ strokeWidth,+ ringGap,+ outlineWidth,+ outlineColor,+ radius,+}: MarkerCirclesProps) {+ const resolvedStroke = stroke ?? fill ?? "currentColor";+ const resolvedOutlineColor = outlineColor ?? resolvedStroke;+ const ringOuter = strokeWidth > 0 ? radius + ringGap + strokeWidth : radius;+ const outlineRadius = outlineWidth > 0 ? ringOuter + outlineWidth / 2 : 0;++ return (+ <>+ {outlineWidth > 0 ? (+ <circle+ cx={0}+ cy={0}+ fill="none"+ r={outlineRadius}+ stroke={resolvedOutlineColor}+ strokeWidth={outlineWidth}+ />+ ) : null}+ <circle cx={0} cy={0} fill={fill} r={radius} />+ {strokeWidth > 0 ? (+ <circle+ cx={0}+ cy={0}+ fill="none"+ r={radius + ringGap + strokeWidth / 2}+ stroke={resolvedStroke}+ strokeWidth={strokeWidth}+ />+ ) : null}+ </>+ );+}++export interface StaticSeriesPointMarkerProps extends SeriesPointMarkerStyle {+ cx: number;+ cy: number;+ scale?: number;+}++export const StaticSeriesPointMarker = memo(function StaticSeriesPointMarker({+ cx,+ cy,+ scale = 1,+ fill,+ stroke,+ strokeWidth = 2,+ ringGap = 2,+ outlineWidth = 0,+ outlineColor,+ radius = 5,+}: StaticSeriesPointMarkerProps) {+ return (+ <g transform={`translate(${cx}, ${cy}) scale(${scale})`}>+ <MarkerCircles+ fill={fill}+ outlineColor={outlineColor}+ outlineWidth={outlineWidth}+ radius={radius}+ ringGap={ringGap}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ </g>+ );+});++export interface SeriesPointMarkerProps extends SeriesPointMarkerStyle {+ dataKey: string;+ index: number;+ cx: number;+ cy: number;+ revealDelay: number;+ revealEpoch: number;+ enterDuration: number;+}++/** Motion enter marker — used only while the chart reveal is running. */+export function SeriesPointMarker({+ dataKey,+ index,+ cx,+ cy,+ enterBlur = 2,+ revealDelay,+ revealEpoch,+ enterDuration,+ fill,+ stroke,+ strokeWidth = 2,+ ringGap = 2,+ outlineWidth = 0,+ outlineColor,+ radius = 5,+}: SeriesPointMarkerProps) {+ const variants: Variants = {+ hidden: {+ opacity: 0,+ filter: `blur(${enterBlur}px)`,+ scale: 1,+ },+ visible: {+ opacity: 1,+ filter: "blur(0px)",+ scale: 1,+ transition: {+ delay: revealDelay,+ duration: enterDuration,+ ease: DEFAULT_CHART_ENTER_TRANSITION.ease,+ },+ },+ };++ return (+ <g transform={`translate(${cx}, ${cy})`}>+ <motion.g+ animate="visible"+ initial="hidden"+ key={`${dataKey}-${index}-${revealEpoch}`}+ variants={variants}+ >+ <MarkerCircles+ fill={fill}+ outlineColor={outlineColor}+ outlineWidth={outlineWidth}+ radius={radius}+ ringGap={ringGap}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ </motion.g>+ </g>+ );+}++export function getSeriesMarkerVisualExtent(+ style: Pick<+ SeriesPointMarkerStyle,+ | "radius"+ | "strokeWidth"+ | "ringGap"+ | "outlineWidth"+ | "showActiveHighlight"+ >+): number {+ const radius = style.radius ?? 5;+ const strokeWidth = style.strokeWidth ?? 2;+ const ringGap = style.ringGap ?? 2;+ const outlineWidth = style.outlineWidth ?? 0;+ const showActiveHighlight = style.showActiveHighlight ?? true;+ const ring = strokeWidth > 0 ? ringGap + strokeWidth : 0;+ const outline = outlineWidth > 0 ? outlineWidth : 0;+ const highlightPad = showActiveHighlight ? radius * 0.35 : 0;+ return radius + ring + outline + highlightPad + 2;+}diff --git a/apps/start/src/components/charts/time-series-chart-shell.tsx b/apps/start/src/components/charts/time-series-chart-shell.tsxnew file mode 100644index 000000000..70ef5702e--- /dev/null+++ b/apps/start/src/components/charts/time-series-chart-shell.tsx@@ -0,0 +1,440 @@+"use client";++import { scaleLinear, scaleTime } from "@visx/scale";+import { bisector, extent } from "d3-array";+import type { Transition } from "motion/react";+import {+ Children,+ cloneElement,+ isValidElement,+ memo,+ type ReactElement,+ type ReactNode,+ useCallback,+ useEffect,+ useMemo,+ useState,+} from "react";+import { DEFAULT_ANIMATION_EASING } from "./animation";+import { ChartProvider, type LineConfig, type Margin } from "./chart-context";+import { isGradientDefComponent, isPatternDefComponent } from "./chart-defs";+import { shortDateFmt } from "./chart-formatters";+import { ChartRevealClip } from "./chart-reveal-clip";+import {+ decimateTimeSeries,+ maxRenderPointsForWidth,+} from "./decimate-time-series";+import {+ computeSeriesBarRevealClipPadding,+ computeSeriesBarWidth,+} from "./series-bar-layout";+import { useChartInteraction } from "./use-chart-interaction";++function collectNumericExtents(+ data: Record<string, unknown>[],+ dataKeys: string[]+) {+ let minValue = Number.POSITIVE_INFINITY;+ let maxValue = Number.NEGATIVE_INFINITY;++ for (const d of data) {+ for (const key of dataKeys) {+ const value = d[key];+ if (typeof value === "number") {+ if (value < minValue) {+ minValue = value;+ }+ if (value > maxValue) {+ maxValue = value;+ }+ }+ }+ }++ if (minValue === Number.POSITIVE_INFINITY) {+ return { minValue: 0, maxValue: 100 };+ }++ return { minValue, maxValue };+}++function resolveTimeSeriesYDomain(+ data: Record<string, unknown>[],+ dataKeys: string[],+ yScaleDomainMax: number | undefined+): [number, number] {+ if (yScaleDomainMax != null && yScaleDomainMax > 0) {+ return [0, yScaleDomainMax * 1.1];+ }++ const { minValue, maxValue } = collectNumericExtents(data, dataKeys);++ if (minValue >= 0) {+ const top = maxValue <= 0 ? 100 : maxValue * 1.1;+ return [0, top];+ }++ const padding = (maxValue - minValue) * 0.05 || 1;+ return [minValue - padding, maxValue + padding];+}++/** Markers render after the interaction overlay so they stay clickable. */+export function isPostOverlayComponent(child: ReactElement): boolean {+ const childType = child.type as {+ displayName?: string;+ name?: string;+ __isChartMarkers?: boolean;+ };++ if (childType.__isChartMarkers) {+ return true;+ }++ const componentName =+ typeof child.type === "function"+ ? childType.displayName || childType.name || ""+ : "";++ return componentName === "ChartMarkers" || componentName === "MarkerGroup";+}++function ensureChildKey(child: ReactElement, index: number): ReactElement {+ if (child.key != null) {+ return child;+ }+ return cloneElement(child, { key: `chart-child-${index}` });+}++export interface TimeSeriesChartInnerProps {+ width: number;+ height: number;+ data: Record<string, unknown>[];+ xDataKey: string;+ margin: Margin;+ animationDuration: number;+ animationEasing?: string;+ enterTransition?: Transition;+ /** Signature of motion URL state — triggers reveal replay when it changes. */+ revealSignature?: string;+ children: ReactNode;+ containerRef: React.RefObject<HTMLDivElement | null>;+ /** Series keys driving y-domain and tooltip (Line / Area / SeriesBar configs). */+ lines: LineConfig[];+ /** SVG clipPath id for grow animation. */+ clipPathId: string;+ /** Optional ComposedChart bar layout (forwarded into context). */+ composedBarDataKeys?: string[];+ composedBarSize?: number;+ composedMaxBarSize?: number;+ composedBarGap?: number;+ composedStacked?: boolean;+ composedStackOffsets?: Map<number, Map<string, number>>;+ composedStackGap?: number;+ /** When set, drives the y-axis max instead of scanning `lines` (e.g. stacked bar totals). */+ yScaleDomainMax?: number;+}++export function TimeSeriesChartInner(props: TimeSeriesChartInnerProps) {+ const { width, height } = props;+ if (width < 10 || height < 10) {+ return null;+ }+ return <TimeSeriesChartCore {...props} />;+}++const TimeSeriesChartCore = memo(function TimeSeriesChartCore({+ width,+ height,+ data,+ xDataKey,+ margin,+ animationDuration,+ animationEasing = DEFAULT_ANIMATION_EASING,+ enterTransition,+ revealSignature = "",+ children,+ containerRef,+ lines,+ clipPathId,+ composedBarDataKeys,+ composedBarSize,+ composedMaxBarSize,+ composedBarGap,+ composedStacked,+ composedStackOffsets,+ composedStackGap,+ yScaleDomainMax,+}: TimeSeriesChartInnerProps) {+ const [isLoaded, setIsLoaded] = useState(false);+ const [revealEpoch, setRevealEpoch] = useState(0);++ const innerWidth = width - margin.left - margin.right;+ const innerHeight = height - margin.top - margin.bottom;++ const xAccessor = useCallback(+ (d: Record<string, unknown>): Date => {+ const value = d[xDataKey];+ return value instanceof Date ? value : new Date(value as string | number);+ },+ [xDataKey]+ );++ const bisectDate = useMemo(+ () => bisector<Record<string, unknown>, Date>((d) => xAccessor(d)).left,+ [xAccessor]+ );++ const xScale = useMemo(() => {+ const timeExtent = extent(data, (d) => xAccessor(d).getTime());+ const minTime = timeExtent[0] ?? 0;+ const maxTime = timeExtent[1] ?? minTime;++ return scaleTime({+ range: [0, innerWidth],+ domain: [minTime, maxTime],+ });+ }, [innerWidth, data, xAccessor]);++ const renderData = useMemo(() => {+ const valueKeys = lines.map((line) => line.dataKey);+ return decimateTimeSeries(+ data,+ maxRenderPointsForWidth(innerWidth),+ valueKeys+ );+ }, [data, innerWidth, lines]);++ const columnWidth = useMemo(() => {+ if (data.length < 2) {+ return 0;+ }+ return innerWidth / (data.length - 1);+ }, [innerWidth, data.length]);++ const yScale = useMemo(() => {+ const dataKeys = lines.map((line) => line.dataKey);+ const domain = resolveTimeSeriesYDomain(data, dataKeys, yScaleDomainMax);++ return scaleLinear({+ range: [innerHeight, 0],+ domain,+ nice: true,+ });+ }, [innerHeight, data, lines, yScaleDomainMax]);++ const dateLabels = useMemo(+ () => data.map((d) => shortDateFmt.format(xAccessor(d))),+ [data, xAccessor]+ );++ // biome-ignore lint/correctness/useExhaustiveDependencies: revealSignature+ useEffect(() => {+ setRevealEpoch((n) => n + 1);+ setIsLoaded(false);+ const timer = setTimeout(() => {+ setIsLoaded(true);+ }, animationDuration);+ return () => clearTimeout(timer);+ }, [animationDuration, revealSignature]);++ const canInteract = isLoaded;++ const {+ tooltipData,+ setTooltipData,+ selection,+ clearSelection,+ interactionHandlers,+ interactionStyle,+ } = useChartInteraction({+ xScale,+ yScale,+ data,+ lines,+ margin,+ xAccessor,+ bisectDate,+ canInteract,+ });++ const defsChildren: ReactElement[] = [];+ const preOverlayChildren: ReactElement[] = [];+ const postOverlayChildren: ReactElement[] = [];++ Children.forEach(children, (child, index) => {+ if (!isValidElement(child)) {+ return;+ }++ const keyedChild = ensureChildKey(child, index);++ if (isGradientDefComponent(keyedChild)) {+ defsChildren.push(keyedChild);+ } else if (isPatternDefComponent(keyedChild)) {+ // Keep pattern defs in the plot <g> (same as main) — hoisting breaks url(#id) fills.+ preOverlayChildren.push(keyedChild);+ } else if (isPostOverlayComponent(keyedChild)) {+ postOverlayChildren.push(keyedChild);+ } else {+ preOverlayChildren.push(keyedChild);+ }+ });++ const contextValue = useMemo(+ () => ({+ data,+ renderData,+ xScale,+ yScale,+ width,+ height,+ innerWidth,+ innerHeight,+ margin,+ columnWidth,+ tooltipData,+ setTooltipData,+ containerRef,+ lines,+ isLoaded,+ animationDuration,+ animationEasing,+ enterTransition,+ revealEpoch,+ xAccessor,+ dateLabels,+ selection,+ clearSelection,+ composedBarDataKeys,+ composedBarSize,+ composedMaxBarSize,+ composedBarGap,+ composedStacked,+ composedStackOffsets,+ composedStackGap,+ }),+ [+ data,+ renderData,+ xScale,+ yScale,+ width,+ height,+ innerWidth,+ innerHeight,+ margin,+ columnWidth,+ tooltipData,+ setTooltipData,+ containerRef,+ lines,+ isLoaded,+ animationDuration,+ animationEasing,+ enterTransition,+ revealEpoch,+ xAccessor,+ dateLabels,+ selection,+ clearSelection,+ composedBarDataKeys,+ composedBarSize,+ composedMaxBarSize,+ composedBarGap,+ composedStacked,+ composedStackOffsets,+ composedStackGap,+ ]+ );++ // Single shared reveal clip for every series. Replaces the per-<Line> /+ // per-<Area> `<ChartRevealClip>` motion.rects: one motion-driven attribute+ // animation instead of N, with all series referencing the same `<clipPath>`.+ // The wipe semantics (left-to-right unveil of static path geometry) are+ // identical to the previous per-series clips.+ // animationDuration === 0 truly disables the reveal (no clipPath wrapper),+ // so consumers can opt out without having to also pass enterTransition.+ const showReveal =+ renderData.length > 1 && innerWidth > 0 && animationDuration > 0;+ // If the consumer didn't pass an explicit enterTransition, derive one from+ // animationDuration so clipRevealTransition picks up the override instead+ // of falling back to its 1100ms default.+ const effectiveEnterTransition: Transition = enterTransition ?? {+ type: "tween",+ duration: animationDuration / 1000,+ };++ const revealClipPadding = useMemo(() => {+ if (!composedBarDataKeys?.length) {+ return 0;+ }+ const barWidth = computeSeriesBarWidth({+ innerWidth,+ dataLength: data.length,+ columnWidth,+ seriesCount: composedBarDataKeys.length,+ composedBarSize,+ composedMaxBarSize,+ composedBarGap,+ stacked: composedStacked,+ });+ return computeSeriesBarRevealClipPadding({+ barWidth,+ seriesCount: composedBarDataKeys.length,+ gap: composedBarGap,+ stacked: composedStacked,+ });+ }, [+ columnWidth,+ composedBarDataKeys,+ composedBarGap,+ composedBarSize,+ composedMaxBarSize,+ composedStacked,+ data.length,+ innerWidth,+ ]);++ return (+ <ChartProvider value={contextValue}>+ <svg aria-hidden="true" height={height} width={width}>+ <defs>+ {defsChildren}+ {showReveal ? (+ <ChartRevealClip+ clipPathId={clipPathId}+ enterTransition={effectiveEnterTransition}+ height={innerHeight + 20}+ padding={revealClipPadding}+ revealEpoch={revealEpoch}+ targetWidth={innerWidth}+ />+ ) : null}+ </defs>++ <rect fill="transparent" height={height} width={width} x={0} y={0} />++ <g+ {...interactionHandlers}+ style={interactionStyle}+ transform={`translate(${margin.left},${margin.top})`}+ >+ <rect+ fill="transparent"+ height={innerHeight}+ width={innerWidth}+ x={0}+ y={0}+ />++ {showReveal ? (+ <g clipPath={`url(#${clipPathId})`}>{preOverlayChildren}</g>+ ) : (+ preOverlayChildren+ )}+ {postOverlayChildren}+ </g>+ </svg>+ </ChartProvider>+ );+});diff --git a/apps/start/src/components/charts/tooltip/chart-tooltip.tsx b/apps/start/src/components/charts/tooltip/chart-tooltip.tsxnew file mode 100644index 000000000..e9237d255--- /dev/null+++ b/apps/start/src/components/charts/tooltip/chart-tooltip.tsx@@ -0,0 +1,326 @@+"use client";++import { motion, useSpring } from "motion/react";+import { memo, useEffect, useMemo, useState } from "react";+import { createPortal } from "react-dom";+import { type SpringConfig, useChartConfig } from "../chart-config-context";+import {+ chartCssVars,+ type LineConfig,+ useChart,+ useChartStable,+} from "../chart-context";+import { weekdayDateFmt } from "../chart-formatters";+import { DateTicker } from "./date-ticker";+import { TooltipBox } from "./tooltip-box";+import { TooltipContent, type TooltipRow } from "./tooltip-content";+import { TooltipDot } from "./tooltip-dot";+import { TooltipIndicator } from "./tooltip-indicator";++export interface ChartTooltipProps {+ /** Whether to show the date pill at bottom. Default: true */+ showDatePill?: boolean;+ /** Whether to show the vertical crosshair line. Default: true */+ showCrosshair?: boolean;+ /** Whether to show dots on the lines. Default: true */+ showDots?: boolean;+ /**+ * Color for the crosshair/indicator line. When a function, receives the hovered point+ * (e.g. for candlestick: match candle color from close vs open). Default: --chart-crosshair.+ */+ indicatorColor?: string | ((point: Record<string, unknown>) => string);+ /** Custom content renderer for the tooltip box */+ content?: (props: {+ point: Record<string, unknown>;+ index: number;+ }) => React.ReactNode;+ /** Custom row renderer - return array of TooltipRow */+ rows?: (point: Record<string, unknown>) => TooltipRow[];+ /**+ * Override tooltip dot fill. When omitted and `rows` is set, dot colors match row colors.+ * When a function, receives the hovered point and line config.+ */+ dotColor?:+ | string+ | ((point: Record<string, unknown>, line: LineConfig) => string);+ /** Additional content to show below rows (e.g., markers) */+ children?: React.ReactNode;+ /** Custom class name */+ className?: string;+ /** Per-chart override for the crosshair / dot / date-pill spring. */+ springConfig?: SpringConfig;+ /** Per-chart override for the floating-panel spring. */+ boxSpringConfig?: SpringConfig;+}++interface ChartTooltipInnerProps extends ChartTooltipProps {+ container: HTMLElement;+}++const ChartTooltipInner = memo(function ChartTooltipInner({+ showDatePill = true,+ showCrosshair = true,+ showDots = true,+ indicatorColor: indicatorColorProp,+ content,+ rows: rowsRenderer,+ dotColor: dotColorProp,+ children,+ className = "",+ container,+ springConfig,+ boxSpringConfig,+}: ChartTooltipInnerProps) {+ const {+ tooltipData,+ width,+ height,+ innerHeight,+ margin,+ columnWidth,+ lines,+ xAccessor,+ dateLabels,+ containerRef,+ orientation,+ barXAccessor,+ } = useChart();++ const isHorizontal = orientation === "horizontal";+ const discreteInteraction = dateLabels.length > 60;++ const visible = tooltipData !== null;+ const x = tooltipData?.x ?? 0;+ const xWithMargin = x + margin.left;++ // For horizontal charts, get the y position from the first line's yPosition (center of bar)+ const firstLineDataKey = lines[0]?.dataKey;+ const firstLineY = firstLineDataKey+ ? (tooltipData?.yPositions[firstLineDataKey] ?? 0)+ : 0;+ const yWithMargin = firstLineY + margin.top;++ const tooltipRows = useMemo(() => {+ if (!tooltipData) {+ return [];+ }++ if (rowsRenderer) {+ return rowsRenderer(tooltipData.point);+ }++ // Default: generate rows from registered lines+ return lines.map((line) => ({+ color: line.stroke,+ label: line.dataKey,+ value: (tooltipData.point[line.dataKey] as number) ?? 0,+ }));+ }, [tooltipData, lines, rowsRenderer]);++ const resolveDotColor = useMemo(() => {+ return (line: LineConfig, index: number): string => {+ if (rowsRenderer && tooltipRows[index]?.color) {+ return tooltipRows[index].color;+ }+ if (dotColorProp != null) {+ if (typeof dotColorProp === "function" && tooltipData) {+ return dotColorProp(tooltipData.point, line);+ }+ if (typeof dotColorProp === "string") {+ return dotColorProp;+ }+ }+ return line.stroke;+ };+ }, [dotColorProp, rowsRenderer, tooltipData, tooltipRows]);++ // Resolve indicator color (static or from hovered point)+ const indicatorColor = useMemo(() => {+ if (indicatorColorProp == null) {+ return chartCssVars.crosshair;+ }+ if (typeof indicatorColorProp === "function") {+ return tooltipData+ ? indicatorColorProp(tooltipData.point)+ : chartCssVars.crosshair;+ }+ return indicatorColorProp;+ }, [indicatorColorProp, tooltipData]);++ // Title from date or category+ const title = useMemo(() => {+ if (!tooltipData) {+ return undefined;+ }+ // For bar charts (horizontal or vertical), use the category name+ if (barXAccessor) {+ return barXAccessor(tooltipData.point);+ }+ // For line/area charts, use the date+ return weekdayDateFmt.format(xAccessor(tooltipData.point));+ }, [tooltipData, barXAccessor, xAccessor]);++ const tooltipContent = (+ <>+ {/* Crosshair indicator - rendered as SVG overlay */}+ {showCrosshair && (+ <svg+ aria-hidden="true"+ className="pointer-events-none absolute inset-0"+ height="100%"+ width="100%"+ >+ <g transform={`translate(${margin.left},${margin.top})`}>+ <TooltipIndicator+ animate={!discreteInteraction}+ colorEdge={indicatorColor}+ colorMid={indicatorColor}+ columnWidth={columnWidth}+ fadeEdges+ height={innerHeight}+ springConfig={springConfig}+ visible={visible}+ width="line"+ x={x}+ />+ </g>+ </svg>+ )}++ {/* Dots on bars/lines - show for vertical charts only */}+ {showDots && visible && !isHorizontal && (+ <svg+ aria-hidden="true"+ className="pointer-events-none absolute inset-0"+ height="100%"+ width="100%"+ >+ <g transform={`translate(${margin.left},${margin.top})`}>+ {lines.map((line, index) => (+ <TooltipDot+ color={resolveDotColor(line, index)}+ key={line.dataKey}+ springConfig={springConfig}+ strokeColor={chartCssVars.background}+ visible={visible}+ x={tooltipData?.xPositions?.[line.dataKey] ?? x}+ y={tooltipData?.yPositions[line.dataKey] ?? 0}+ />+ ))}+ </g>+ </svg>+ )}++ {/* Tooltip Box */}+ <TooltipBox+ className={className}+ containerHeight={height}+ containerRef={containerRef}+ containerWidth={width}+ springConfig={boxSpringConfig}+ top={isHorizontal ? undefined : margin.top}+ visible={visible}+ x={xWithMargin}+ y={isHorizontal ? yWithMargin : margin.top}+ >+ {content && tooltipData+ ? content({+ point: tooltipData.point,+ index: tooltipData.index,+ })+ : !content && (+ <TooltipContent rows={tooltipRows} title={title}>+ {children}+ </TooltipContent>+ )}+ </TooltipBox>++ {/* Date/Category Ticker - only show for vertical charts */}+ <DatePillTracker+ currentIndex={tooltipData?.index ?? 0}+ discreteInteraction={discreteInteraction}+ enabled={showDatePill && !isHorizontal}+ labels={dateLabels}+ springConfig={springConfig}+ visible={visible}+ xWithMargin={xWithMargin}+ />+ </>+ );++ return createPortal(tooltipContent, container);+});++export function ChartTooltip(props: ChartTooltipProps) {+ const { containerRef } = useChartStable();+ const [mounted, setMounted] = useState(false);++ // Only render portals on client side after mount+ useEffect(() => {+ setMounted(true);+ }, []);++ const container = containerRef.current;+ if (!(mounted && container)) {+ return null;+ }++ return <ChartTooltipInner {...props} container={container} />;+}++ChartTooltip.displayName = "ChartTooltip";++interface DatePillTrackerProps {+ enabled: boolean;+ visible: boolean;+ labels: string[];+ currentIndex: number;+ xWithMargin: number;+ discreteInteraction: boolean;+ springConfig?: SpringConfig;+}++// Inner-only-on-visible so `useSpring` initializes at the real cursor x+// instead of `margin.left` on first hover.+function DatePillTracker(props: DatePillTrackerProps) {+ if (!(props.enabled && props.visible && props.labels.length > 0)) {+ return null;+ }+ return <DatePillTrackerInner {...props} />;+}++function DatePillTrackerInner({+ labels,+ currentIndex,+ xWithMargin,+ discreteInteraction,+ springConfig,+ visible,+}: DatePillTrackerProps) {+ const { tooltipSpring } = useChartConfig();+ const effectiveSpring = springConfig ?? tooltipSpring;+ const animatedX = useSpring(xWithMargin, effectiveSpring);++ if (!discreteInteraction) {+ animatedX.set(xWithMargin);+ }++ return (+ <motion.div+ className="pointer-events-none absolute z-50"+ style={{+ left: discreteInteraction ? xWithMargin : animatedX,+ transform: "translateX(-50%)",+ bottom: 4,+ }}+ >+ <DateTicker+ currentIndex={currentIndex}+ labels={labels}+ visible={visible}+ />+ </motion.div>+ );+}++export default ChartTooltip;diff --git a/apps/start/src/components/charts/tooltip/date-ticker.tsx b/apps/start/src/components/charts/tooltip/date-ticker.tsxnew file mode 100644index 000000000..d4a99e061--- /dev/null+++ b/apps/start/src/components/charts/tooltip/date-ticker.tsx@@ -0,0 +1,150 @@+"use client";++import { motion, useSpring } from "motion/react";+import { memo, useMemo, useRef } from "react";++const TICKER_ITEM_HEIGHT = 24;+/** Full scroll stacks are skipped above this count — single label + instant updates. */+const COMPACT_TICKER_THRESHOLD = 60;++export interface DateTickerProps {+ currentIndex: number;+ labels: string[];+ visible: boolean;+}++const DateTickerCompact = memo(function DateTickerCompact({+ currentIndex,+ labels,+}: Omit<DateTickerProps, "visible">) {+ const label = labels[currentIndex] ?? labels[0] ?? "";++ return (+ <div className="overflow-hidden rounded-full bg-zinc-900 px-4 py-1 text-white shadow-lg dark:bg-zinc-100 dark:text-zinc-900">+ <div className="flex h-6 items-center justify-center">+ <span className="whitespace-nowrap font-medium text-sm">{label}</span>+ </div>+ </div>+ );+});++const DateTickerInner = memo(function DateTickerInner({+ currentIndex,+ labels,+}: Omit<DateTickerProps, "visible">) {+ // Parse labels into month and day parts+ const parsedLabels = useMemo(() => {+ return labels.map((label, index) => {+ const parts = label.split(" ");+ const month = parts[0] || "";+ const day = parts[1] || "";+ return { month, day, full: label, key: `${label}::${index}` };+ });+ }, [labels]);++ // Month segments: one entry per consecutive run (Jan → Feb → …), keyed by start index+ const monthSegments = useMemo(() => {+ const segments: { month: string; key: string; startIndex: number }[] = [];++ parsedLabels.forEach((label, index) => {+ const prev = segments.at(-1);+ if (!prev || prev.month !== label.month) {+ segments.push({+ month: label.month,+ key: `${label.month}-${index}`,+ startIndex: index,+ });+ }+ });++ return segments;+ }, [parsedLabels]);++ // Index into monthSegments for the current data point+ const currentMonthIndex = useMemo(() => {+ if (currentIndex < 0 || currentIndex >= parsedLabels.length) {+ return 0;+ }+ for (let i = monthSegments.length - 1; i >= 0; i--) {+ const segment = monthSegments[i];+ if (segment && segment.startIndex <= currentIndex) {+ return i;+ }+ }+ return 0;+ }, [currentIndex, parsedLabels.length, monthSegments]);++ // Track previous month index+ const prevMonthIndexRef = useRef(-1);++ // Animated Y offsets+ const dayY = useSpring(0, { stiffness: 400, damping: 35 });+ const monthY = useSpring(0, { stiffness: 400, damping: 35 });++ dayY.set(-currentIndex * TICKER_ITEM_HEIGHT);++ if (currentMonthIndex >= 0) {+ const isFirstRender = prevMonthIndexRef.current === -1;+ const monthChanged = prevMonthIndexRef.current !== currentMonthIndex;+ if (isFirstRender || monthChanged) {+ monthY.set(-currentMonthIndex * TICKER_ITEM_HEIGHT);+ prevMonthIndexRef.current = currentMonthIndex;+ }+ }++ return (+ <div className="overflow-hidden rounded-full bg-zinc-900 px-4 py-1 text-white shadow-lg dark:bg-zinc-100 dark:text-zinc-900">+ <div className="relative h-6 overflow-hidden">+ <div className="flex items-center justify-center gap-1">+ {/* Month stack */}+ <div className="relative h-6 overflow-hidden">+ <motion.div className="flex flex-col" style={{ y: monthY }}>+ {monthSegments.map((segment) => (+ <div+ className="flex h-6 shrink-0 items-center justify-center"+ key={segment.key}+ >+ <span className="whitespace-nowrap font-medium text-sm">+ {segment.month}+ </span>+ </div>+ ))}+ </motion.div>+ </div>++ {/* Day stack */}+ <div className="relative h-6 overflow-hidden">+ <motion.div className="flex flex-col" style={{ y: dayY }}>+ {parsedLabels.map((label) => (+ <div+ className="flex h-6 shrink-0 items-center justify-center"+ key={label.key}+ >+ <span className="whitespace-nowrap font-medium text-sm">+ {label.day}+ </span>+ </div>+ ))}+ </motion.div>+ </div>+ </div>+ </div>+ </div>+ );+});++export function DateTicker({ currentIndex, labels, visible }: DateTickerProps) {+ if (!visible || labels.length === 0) {+ return null;+ }++ if (labels.length > COMPACT_TICKER_THRESHOLD) {+ return <DateTickerCompact currentIndex={currentIndex} labels={labels} />;+ }++ return <DateTickerInner currentIndex={currentIndex} labels={labels} />;+}++DateTicker.displayName = "DateTicker";++export default DateTicker;diff --git a/apps/start/src/components/charts/tooltip/index.ts b/apps/start/src/components/charts/tooltip/index.tsnew file mode 100644index 000000000..5b4dafcf0--- /dev/null+++ b/apps/start/src/components/charts/tooltip/index.ts@@ -0,0 +1,14 @@+export { ChartTooltip, type ChartTooltipProps } from "./chart-tooltip";+export { DateTicker, type DateTickerProps } from "./date-ticker";+export { TooltipBox, type TooltipBoxProps } from "./tooltip-box";+export {+ TooltipContent,+ type TooltipContentProps,+ type TooltipRow,+} from "./tooltip-content";+export { TooltipDot, type TooltipDotProps } from "./tooltip-dot";+export {+ type IndicatorWidth,+ TooltipIndicator,+ type TooltipIndicatorProps,+} from "./tooltip-indicator";diff --git a/apps/start/src/components/charts/tooltip/tooltip-box.tsx b/apps/start/src/components/charts/tooltip/tooltip-box.tsxnew file mode 100644index 000000000..af6a04496--- /dev/null+++ b/apps/start/src/components/charts/tooltip/tooltip-box.tsx@@ -0,0 +1,181 @@+"use client";++import { motion, useSpring } from "motion/react";+import type { RefObject } from "react";+import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { createPortal } from "react-dom";+import { cn } from "@/lib/utils";+import { type SpringConfig, useChartConfig } from "../chart-config-context";++export interface TooltipBoxProps {+ /** X position in pixels (relative to container) */+ x: number;+ /** Y position in pixels (relative to container) */+ y: number;+ /** Whether the tooltip is visible */+ visible: boolean;+ /** Container ref for portal rendering */+ containerRef: RefObject<HTMLDivElement | null>;+ /** Container width for flip detection */+ containerWidth: number;+ /** Container height for bounds clamping */+ containerHeight: number;+ /** Offset from the target position */+ offset?: number;+ /** Custom class name */+ className?: string;+ /** Tooltip content */+ children: React.ReactNode;+ /** Override left position (bypasses internal calculation) */+ left?: number | ReturnType<typeof useSpring>;+ /** Override top position (bypasses internal calculation) */+ top?: number | ReturnType<typeof useSpring>;+ /** Force flip direction (for custom positioning) */+ flipped?: boolean;+ /** Per-chart override; falls back to `ChartConfigProvider.tooltipBoxSpring`. */+ springConfig?: SpringConfig;+}++// Inner-only-on-visible so `useSpring` initializes at the cursor's actual x/y+// instead of (0, 0) on first hover.+export function TooltipBox(props: TooltipBoxProps) {+ const [mounted, setMounted] = useState(false);++ useEffect(() => {+ setMounted(true);+ }, []);++ const container = props.containerRef.current;+ if (!(mounted && container)) {+ return null;+ }+ if (!props.visible) {+ return null;+ }+ return <TooltipBoxInner {...props} container={container} />;+}++function TooltipBoxInner({+ x,+ y,+ containerWidth,+ containerHeight,+ offset = 16,+ className = "",+ children,+ left: leftOverride,+ top: topOverride,+ flipped: flippedOverride,+ springConfig,+ container,+}: Omit<TooltipBoxProps, "visible" | "containerRef"> & {+ container: HTMLElement;+}) {+ const { tooltipBoxSpring } = useChartConfig();+ const effectiveSpring = springConfig ?? tooltipBoxSpring;++ const tooltipRef = useRef<HTMLDivElement>(null);+ const tooltipWidthRef = useRef(180);+ const tooltipHeightRef = useRef(80);++ const tw = tooltipWidthRef.current;+ const th = tooltipHeightRef.current;+ const shouldFlipX = x + tw + offset > containerWidth;+ const targetX = shouldFlipX ? x - offset - tw : x + offset;+ const targetY = Math.max(+ offset,+ Math.min(y - th / 2, containerHeight - th - offset)+ );++ const animatedLeft = useSpring(targetX, effectiveSpring);+ const animatedTop = useSpring(targetY, effectiveSpring);++ if (leftOverride === undefined) {+ animatedLeft.set(targetX);+ }+ if (topOverride === undefined) {+ animatedTop.set(targetY);+ }++ useLayoutEffect(() => {+ if (!tooltipRef.current) {+ return;+ }+ const el = tooltipRef.current;+ const w = el.offsetWidth;+ const h = el.offsetHeight;+ if (w > 0) {+ tooltipWidthRef.current = w;+ }+ if (h > 0) {+ tooltipHeightRef.current = h;+ }+ const w2 = tooltipWidthRef.current;+ const h2 = tooltipHeightRef.current;+ const flip = x + w2 + offset > containerWidth;+ const tx = flip ? x - offset - w2 : x + offset;+ const ty = Math.max(+ offset,+ Math.min(y - h2 / 2, containerHeight - h2 - offset)+ );+ if (leftOverride === undefined) {+ animatedLeft.set(tx);+ }+ if (topOverride === undefined) {+ animatedTop.set(ty);+ }+ }, [+ x,+ y,+ containerWidth,+ containerHeight,+ offset,+ leftOverride,+ topOverride,+ animatedLeft,+ animatedTop,+ ]);++ const prevFlipRef = useRef(shouldFlipX);+ const [flipKey, setFlipKey] = useState(0);++ useEffect(() => {+ if (prevFlipRef.current !== shouldFlipX) {+ setFlipKey((k) => k + 1);+ prevFlipRef.current = shouldFlipX;+ }+ }, [shouldFlipX]);++ const finalLeft = leftOverride ?? animatedLeft;+ const finalTop = topOverride ?? animatedTop;+ const isFlipped = flippedOverride ?? shouldFlipX;+ const transformOrigin = isFlipped ? "right top" : "left top";++ return createPortal(+ <motion.div+ animate={{ opacity: 1 }}+ className={cn("pointer-events-none absolute z-50", className)}+ exit={{ opacity: 0 }}+ initial={{ opacity: 0 }}+ ref={tooltipRef}+ style={{ left: finalLeft, top: finalTop }}+ transition={{ duration: 0.1 }}+ >+ <motion.div+ animate={{ scale: 1, opacity: 1, x: 0 }}+ className="min-w-[140px] overflow-hidden rounded-lg bg-chart-tooltip-background text-chart-tooltip-foreground shadow-lg backdrop-blur-md"+ initial={{ scale: 0.85, opacity: 0, x: isFlipped ? 20 : -20 }}+ key={flipKey}+ style={{ transformOrigin }}+ transition={{ type: "spring", stiffness: 300, damping: 25 }}+ >+ {children}+ </motion.div>+ </motion.div>,+ container+ );+}++TooltipBox.displayName = "TooltipBox";++export default TooltipBox;diff --git a/apps/start/src/components/charts/tooltip/tooltip-content.tsx b/apps/start/src/components/charts/tooltip/tooltip-content.tsxnew file mode 100644index 000000000..7e071190e--- /dev/null+++ b/apps/start/src/components/charts/tooltip/tooltip-content.tsx@@ -0,0 +1,62 @@+"use client";++import type { ReactNode } from "react";+import { intFmt } from "../chart-formatters";++export interface TooltipRow {+ color: string;+ label: string;+ value: string | number;+}++export interface TooltipContentProps {+ title?: string;+ rows: TooltipRow[];+ /** Optional additional content (e.g., markers) */+ children?: ReactNode;+}++export function TooltipContent({ title, rows, children }: TooltipContentProps) {+ return (+ <div className="overflow-hidden">+ <div className="px-3 py-2.5">+ {title && (+ <div className="mb-2 font-medium text-chart-tooltip-foreground text-xs">+ {title}+ </div>+ )}+ <div className="space-y-1.5">+ {rows.map((row) => (+ <div+ className="flex items-center justify-between gap-4"+ key={`${row.label}-${row.color}`}+ >+ <div className="flex items-center gap-2">+ <span+ className="h-2.5 w-2.5 shrink-0 rounded-full"+ style={{ backgroundColor: row.color }}+ />+ <span className="text-chart-tooltip-muted text-sm">+ {row.label}+ </span>+ </div>+ <span className="font-medium text-chart-tooltip-foreground text-sm tabular-nums">+ {typeof row.value === "number" ? intFmt(row.value) : row.value}+ </span>+ </div>+ ))}+ </div>++ {children && (+ <div className="mt-2 transition-opacity duration-200 ease-out">+ {children}+ </div>+ )}+ </div>+ </div>+ );+}++TooltipContent.displayName = "TooltipContent";++export default TooltipContent;diff --git a/apps/start/src/components/charts/tooltip/tooltip-dot.tsx b/apps/start/src/components/charts/tooltip/tooltip-dot.tsxnew file mode 100644index 000000000..f360a1f60--- /dev/null+++ b/apps/start/src/components/charts/tooltip/tooltip-dot.tsx@@ -0,0 +1,55 @@+"use client";++import { motion, useSpring } from "motion/react";+import { type SpringConfig, useChartConfig } from "../chart-config-context";+import { chartCssVars } from "../chart-context";++export interface TooltipDotProps {+ x: number;+ y: number;+ visible: boolean;+ color: string;+ size?: number;+ strokeColor?: string;+ strokeWidth?: number;+ /** Per-chart override; falls back to `ChartConfigProvider.tooltipSpring`. */+ springConfig?: SpringConfig;+}++export function TooltipDot({+ x,+ y,+ visible,+ color,+ size = 5,+ strokeColor = chartCssVars.background,+ strokeWidth = 2,+ springConfig,+}: TooltipDotProps) {+ const { tooltipSpring } = useChartConfig();+ const effectiveSpring = springConfig ?? tooltipSpring;+ const animatedX = useSpring(x, effectiveSpring);+ const animatedY = useSpring(y, effectiveSpring);++ animatedX.set(x);+ animatedY.set(y);++ if (!visible) {+ return null;+ }++ return (+ <motion.circle+ cx={animatedX}+ cy={animatedY}+ fill={color}+ r={size}+ stroke={strokeColor}+ strokeWidth={strokeWidth}+ />+ );+}++TooltipDot.displayName = "TooltipDot";++export default TooltipDot;diff --git a/apps/start/src/components/charts/tooltip/tooltip-indicator.tsx b/apps/start/src/components/charts/tooltip/tooltip-indicator.tsxnew file mode 100644index 000000000..446c815ab--- /dev/null+++ b/apps/start/src/components/charts/tooltip/tooltip-indicator.tsx@@ -0,0 +1,144 @@+"use client";++import { motion, useSpring } from "motion/react";+import { type SpringConfig, useChartConfig } from "../chart-config-context";+import { chartCssVars } from "../chart-context";++export type IndicatorWidth =+ | number // Pixel width+ | "line" // 1px line (default)+ | "thin" // 2px+ | "medium" // 4px+ | "thick"; // 8px++export interface TooltipIndicatorProps {+ /** X position in pixels (center of the indicator) */+ x: number;+ /** Height of the indicator */+ height: number;+ /** Whether the indicator is visible */+ visible: boolean;+ /**+ * Width of the indicator - number (pixels) or preset.+ * Ignored if `span` is provided.+ */+ width?: IndicatorWidth;+ /**+ * Number of columns/days to span, with current point centered.+ * Requires `columnWidth` to be set.+ */+ span?: number;+ /** Width of a single column/day in pixels. Required when using `span`. */+ columnWidth?: number;+ /** Primary color at edges (10% and 90%) */+ colorEdge?: string;+ /** Secondary color at center (50%) */+ colorMid?: string;+ /** Whether to fade to transparent at 0% and 100% */+ fadeEdges?: boolean;+ /** Animate position with a spring. Default: true */+ animate?: boolean;+ /** Unique ID for the gradient */+ gradientId?: string;+ /** Per-chart override; falls back to `ChartConfigProvider.tooltipSpring`. */+ springConfig?: SpringConfig;+}++function resolveWidth(width: IndicatorWidth): number {+ if (typeof width === "number") {+ return width;+ }+ switch (width) {+ case "line":+ return 1;+ case "thin":+ return 2;+ case "medium":+ return 4;+ case "thick":+ return 8;+ default:+ return 1;+ }+}++// Inner-only-on-visible so `useSpring` initializes at the real cursor x+// instead of 0 on first hover.+export function TooltipIndicator(props: TooltipIndicatorProps) {+ if (!props.visible) {+ return null;+ }+ return <TooltipIndicatorInner {...props} />;+}++function TooltipIndicatorInner({+ x,+ height,+ width = "line",+ span,+ columnWidth,+ colorEdge = chartCssVars.crosshair,+ colorMid = chartCssVars.crosshair,+ fadeEdges = true,+ animate = true,+ gradientId = "tooltip-indicator-gradient",+ springConfig,+}: Omit<TooltipIndicatorProps, "visible">) {+ const { tooltipSpring } = useChartConfig();+ const effectiveSpring = springConfig ?? tooltipSpring;++ const pixelWidth =+ span !== undefined && columnWidth !== undefined+ ? span * columnWidth+ : resolveWidth(width);++ const rectX = x - pixelWidth / 2;+ const animatedX = useSpring(rectX, effectiveSpring);++ if (animate) {+ animatedX.set(rectX);+ }++ const edgeOpacity = fadeEdges ? 0 : 1;++ return (+ <g>+ <defs>+ <linearGradient id={gradientId} x1="0%" x2="0%" y1="0%" y2="100%">+ <stop+ offset="0%"+ style={{ stopColor: colorEdge, stopOpacity: edgeOpacity }}+ />+ <stop offset="10%" style={{ stopColor: colorEdge, stopOpacity: 1 }} />+ <stop offset="50%" style={{ stopColor: colorMid, stopOpacity: 1 }} />+ <stop offset="90%" style={{ stopColor: colorEdge, stopOpacity: 1 }} />+ <stop+ offset="100%"+ style={{ stopColor: colorEdge, stopOpacity: edgeOpacity }}+ />+ </linearGradient>+ </defs>+ {animate ? (+ <motion.rect+ fill={`url(#${gradientId})`}+ height={height}+ width={pixelWidth}+ x={animatedX}+ y={0}+ />+ ) : (+ <rect+ fill={`url(#${gradientId})`}+ height={height}+ width={pixelWidth}+ x={rectX}+ y={0}+ />+ )}+ </g>+ );+}++TooltipIndicator.displayName = "TooltipIndicator";++export default TooltipIndicator;diff --git a/apps/start/src/components/charts/use-area-segment-highlight.ts b/apps/start/src/components/charts/use-area-segment-highlight.tsnew file mode 100644index 000000000..2a4327285--- /dev/null+++ b/apps/start/src/components/charts/use-area-segment-highlight.ts@@ -0,0 +1,163 @@+"use client";++import { useCallback, useMemo } from "react";+import type { TooltipData } from "./chart-context";+import type { ChartSelection } from "./use-chart-interaction";++interface UseAreaSegmentHighlightOptions {+ data: Record<string, unknown>[];+ dataKey: string;+ tooltipData: TooltipData | null;+ selection: ChartSelection | null | undefined;+ xScale: (value: Date | number) => number | undefined;+ yScale: (value: number) => number | undefined;+ xAccessor: (datum: Record<string, unknown>) => Date | number;+}++function buildChordMetrics(+ data: Record<string, unknown>[],+ getY: (datum: Record<string, unknown>) => number,+ xScale: (value: Date | number) => number | undefined,+ xAccessor: (datum: Record<string, unknown>) => Date | number+) {+ const cumulative: number[] = [0];+ let total = 0;+ for (let i = 1; i < data.length; i++) {+ const d0 = data[i - 1];+ const d1 = data[i];+ if (!(d0 && d1)) {+ continue;+ }+ const x0 = xScale(xAccessor(d0)) ?? 0;+ const x1 = xScale(xAccessor(d1)) ?? 0;+ const y0 = getY(d0);+ const y1 = getY(d1);+ total += Math.hypot(x1 - x0, y1 - y0);+ cumulative.push(total);+ }+ return { cumulative, total };+}++function approximateLengthAtX(+ targetX: number,+ data: Record<string, unknown>[],+ chordMetrics: { cumulative: number[]; total: number },+ xScale: (value: Date | number) => number | undefined,+ xAccessor: (datum: Record<string, unknown>) => Date | number+) {+ if (data.length < 2) {+ return 0;+ }+ const { cumulative } = chordMetrics;+ for (let i = 1; i < data.length; i++) {+ const dPrev = data[i - 1];+ const dCur = data[i];+ if (!(dPrev && dCur)) {+ continue;+ }+ const x0 = xScale(xAccessor(dPrev)) ?? 0;+ const x1 = xScale(xAccessor(dCur)) ?? 0;+ const atLast = i === data.length - 1;+ const spanEnd = Math.max(x0, x1);+ if (targetX <= spanEnd || atLast) {+ const prev = cumulative[i - 1] ?? 0;+ const segLen = (cumulative[i] ?? 0) - prev;+ const denom = x1 - x0;+ if (Math.abs(denom) < 1e-6) {+ return prev;+ }+ const t = Math.max(0, Math.min(1, (targetX - x0) / denom));+ return prev + t * segLen;+ }+ }+ return chordMetrics.total;+}++export function useAreaSegmentHighlight({+ data,+ dataKey,+ tooltipData,+ selection,+ xScale,+ yScale,+ xAccessor,+}: UseAreaSegmentHighlightOptions) {+ const getY = useCallback(+ (d: Record<string, unknown>) => {+ const value = d[dataKey];+ return typeof value === "number" ? (yScale(value) ?? 0) : 0;+ },+ [dataKey, yScale]+ );++ const chordMetrics = useMemo(+ () => buildChordMetrics(data, getY, xScale, xAccessor),+ [data, getY, xScale, xAccessor]+ );++ const segmentBounds = useMemo(() => {+ if (data.length < 2 || chordMetrics.total <= 0) {+ return { startLength: 0, segmentLength: 0, isActive: false };+ }++ if (selection?.active) {+ const startLength = approximateLengthAtX(+ selection.startX,+ data,+ chordMetrics,+ xScale,+ xAccessor+ );+ const endLength = approximateLengthAtX(+ selection.endX,+ data,+ chordMetrics,+ xScale,+ xAccessor+ );+ return {+ startLength,+ segmentLength: Math.max(0, endLength - startLength),+ isActive: true,+ };+ }++ if (!tooltipData) {+ return { startLength: 0, segmentLength: 0, isActive: false };+ }++ const idx = tooltipData.index;+ const startIdx = Math.max(0, idx - 1);+ const endIdx = Math.min(data.length - 1, idx + 1);+ const startPoint = data[startIdx];+ const endPoint = data[endIdx];+ if (!(startPoint && endPoint)) {+ return { startLength: 0, segmentLength: 0, isActive: false };+ }++ const startX = xScale(xAccessor(startPoint)) ?? 0;+ const endX = xScale(xAccessor(endPoint)) ?? 0;+ const startLength = approximateLengthAtX(+ startX,+ data,+ chordMetrics,+ xScale,+ xAccessor+ );+ const endLength = approximateLengthAtX(+ endX,+ data,+ chordMetrics,+ xScale,+ xAccessor+ );++ return {+ startLength,+ segmentLength: Math.max(0, endLength - startLength),+ isActive: true,+ };+ }, [tooltipData, selection, data, xScale, xAccessor, chordMetrics]);++ return { chordMetrics, segmentBounds, getY };+}diff --git a/apps/start/src/components/charts/use-chart-interaction.ts b/apps/start/src/components/charts/use-chart-interaction.tsnew file mode 100644index 000000000..e1b3c0629--- /dev/null+++ b/apps/start/src/components/charts/use-chart-interaction.ts@@ -0,0 +1,330 @@+"use client";++import { localPoint } from "@visx/event";+import type { scaleLinear, scaleTime } from "@visx/scale";+import { useCallback, useRef, useState } from "react";+import type { LineConfig, Margin, TooltipData } from "./chart-context";+import { useScheduledTooltip } from "./use-scheduled-tooltip";++type ScaleTime = ReturnType<typeof scaleTime<number>>;+type ScaleLinear = ReturnType<typeof scaleLinear<number>>;++export interface ChartSelection {+ startX: number;+ endX: number;+ startIndex: number;+ endIndex: number;+ active: boolean;+}++interface UseChartInteractionParams {+ xScale: ScaleTime;+ yScale: ScaleLinear;+ data: Record<string, unknown>[];+ lines: LineConfig[];+ margin: Margin;+ xAccessor: (d: Record<string, unknown>) => Date;+ bisectDate: (+ data: Record<string, unknown>[],+ date: Date,+ lo: number+ ) => number;+ canInteract: boolean;+}++interface ChartInteractionResult {+ tooltipData: TooltipData | null;+ setTooltipData: React.Dispatch<React.SetStateAction<TooltipData | null>>;+ selection: ChartSelection | null;+ clearSelection: () => void;+ interactionHandlers: {+ onMouseMove?: (event: React.MouseEvent<SVGGElement>) => void;+ onMouseLeave?: () => void;+ onMouseDown?: (event: React.MouseEvent<SVGGElement>) => void;+ onMouseUp?: () => void;+ onTouchStart?: (event: React.TouchEvent<SVGGElement>) => void;+ onTouchMove?: (event: React.TouchEvent<SVGGElement>) => void;+ onTouchEnd?: () => void;+ };+ interactionStyle: React.CSSProperties;+}++export function useChartInteraction({+ xScale,+ yScale,+ data,+ lines,+ margin,+ xAccessor,+ bisectDate,+ canInteract,+}: UseChartInteractionParams): ChartInteractionResult {+ const [selection, setSelection] = useState<ChartSelection | null>(null);+ const {+ tooltipData,+ setTooltipData,+ scheduleTooltip,+ clearTooltip,+ resetTooltipDedupe,+ } = useScheduledTooltip<TooltipData>();++ const isDraggingRef = useRef(false);+ const dragStartXRef = useRef<number>(0);++ const resolveTooltipFromX = useCallback(+ (pixelX: number): TooltipData | null => {+ const x0 = xScale.invert(pixelX);+ const index = bisectDate(data, x0, 1);+ const d0 = data[index - 1];+ const d1 = data[index];++ if (!d0) {+ return null;+ }++ let d = d0;+ let finalIndex = index - 1;+ if (d1) {+ const d0Time = xAccessor(d0).getTime();+ const d1Time = xAccessor(d1).getTime();+ if (x0.getTime() - d0Time > d1Time - x0.getTime()) {+ d = d1;+ finalIndex = index;+ }+ }++ const yPositions: Record<string, number> = {};+ for (const line of lines) {+ const value = d[line.dataKey];+ if (typeof value === "number") {+ yPositions[line.dataKey] = yScale(value) ?? 0;+ }+ }++ return {+ point: d,+ index: finalIndex,+ x: xScale(xAccessor(d)) ?? 0,+ yPositions,+ };+ },+ [xScale, yScale, data, lines, xAccessor, bisectDate]+ );++ const resolveIndexFromX = useCallback(+ (pixelX: number): number => {+ const x0 = xScale.invert(pixelX);+ const index = bisectDate(data, x0, 1);+ const d0 = data[index - 1];+ const d1 = data[index];+ if (!d0) {+ return 0;+ }+ if (d1) {+ const d0Time = xAccessor(d0).getTime();+ const d1Time = xAccessor(d1).getTime();+ if (x0.getTime() - d0Time > d1Time - x0.getTime()) {+ return index;+ }+ }+ return index - 1;+ },+ [xScale, data, xAccessor, bisectDate]+ );++ const getChartX = useCallback(+ (+ event: React.MouseEvent<SVGGElement> | React.TouchEvent<SVGGElement>,+ touchIndex = 0+ ): number | null => {+ let point: { x: number; y: number } | null = null;++ if ("touches" in event) {+ const touch = event.touches[touchIndex];+ if (!touch) {+ return null;+ }+ const svg = event.currentTarget.ownerSVGElement;+ if (!svg) {+ return null;+ }+ point = localPoint(svg, touch as unknown as MouseEvent);+ } else {+ point = localPoint(event);+ }++ if (!point) {+ return null;+ }+ return point.x - margin.left;+ },+ [margin.left]+ );++ const handleMouseMove = useCallback(+ (event: React.MouseEvent<SVGGElement>) => {+ const chartX = getChartX(event);+ if (chartX === null) {+ return;+ }++ if (isDraggingRef.current) {+ const startX = Math.min(dragStartXRef.current, chartX);+ const endX = Math.max(dragStartXRef.current, chartX);+ setSelection({+ startX,+ endX,+ startIndex: resolveIndexFromX(startX),+ endIndex: resolveIndexFromX(endX),+ active: true,+ });+ return;+ }++ const tooltip = resolveTooltipFromX(chartX);+ if (tooltip) {+ scheduleTooltip(tooltip);+ }+ },+ [getChartX, resolveTooltipFromX, resolveIndexFromX, scheduleTooltip]+ );++ const handleMouseLeave = useCallback(() => {+ clearTooltip();+ if (isDraggingRef.current) {+ isDraggingRef.current = false;+ }+ setSelection(null);+ }, [clearTooltip]);++ const handleMouseDown = useCallback(+ (event: React.MouseEvent<SVGGElement>) => {+ const chartX = getChartX(event);+ if (chartX === null) {+ return;+ }+ isDraggingRef.current = true;+ dragStartXRef.current = chartX;+ clearTooltip();+ setSelection(null);+ },+ [getChartX, clearTooltip]+ );++ const handleMouseUp = useCallback(() => {+ if (isDraggingRef.current) {+ isDraggingRef.current = false;+ }+ setSelection(null);+ }, []);++ const handleTouchStart = useCallback(+ (event: React.TouchEvent<SVGGElement>) => {+ if (event.touches.length === 1) {+ event.preventDefault();+ const chartX = getChartX(event, 0);+ if (chartX === null) {+ return;+ }+ const tooltip = resolveTooltipFromX(chartX);+ if (tooltip) {+ scheduleTooltip(tooltip);+ }+ } else if (event.touches.length === 2) {+ event.preventDefault();+ resetTooltipDedupe();+ clearTooltip();+ const x0 = getChartX(event, 0);+ const x1 = getChartX(event, 1);+ if (x0 === null || x1 === null) {+ return;+ }+ const startX = Math.min(x0, x1);+ const endX = Math.max(x0, x1);+ setSelection({+ startX,+ endX,+ startIndex: resolveIndexFromX(startX),+ endIndex: resolveIndexFromX(endX),+ active: true,+ });+ }+ },+ [+ getChartX,+ resolveTooltipFromX,+ resolveIndexFromX,+ scheduleTooltip,+ resetTooltipDedupe,+ clearTooltip,+ ]+ );++ const handleTouchMove = useCallback(+ (event: React.TouchEvent<SVGGElement>) => {+ if (event.touches.length === 1) {+ event.preventDefault();+ const chartX = getChartX(event, 0);+ if (chartX === null) {+ return;+ }+ const tooltip = resolveTooltipFromX(chartX);+ if (tooltip) {+ scheduleTooltip(tooltip);+ }+ } else if (event.touches.length === 2) {+ event.preventDefault();+ const x0 = getChartX(event, 0);+ const x1 = getChartX(event, 1);+ if (x0 === null || x1 === null) {+ return;+ }+ const startX = Math.min(x0, x1);+ const endX = Math.max(x0, x1);+ setSelection({+ startX,+ endX,+ startIndex: resolveIndexFromX(startX),+ endIndex: resolveIndexFromX(endX),+ active: true,+ });+ }+ },+ [getChartX, resolveTooltipFromX, resolveIndexFromX, scheduleTooltip]+ );++ const handleTouchEnd = useCallback(() => {+ clearTooltip();+ setSelection(null);+ }, [clearTooltip]);++ const clearSelection = useCallback(() => {+ setSelection(null);+ }, []);++ const interactionHandlers = canInteract+ ? {+ onMouseMove: handleMouseMove,+ onMouseLeave: handleMouseLeave,+ onMouseDown: handleMouseDown,+ onMouseUp: handleMouseUp,+ onTouchStart: handleTouchStart,+ onTouchMove: handleTouchMove,+ onTouchEnd: handleTouchEnd,+ }+ : {};++ const interactionStyle: React.CSSProperties = {+ cursor: canInteract ? "crosshair" : "default",+ touchAction: "none",+ };++ return {+ tooltipData,+ setTooltipData,+ selection,+ clearSelection,+ interactionHandlers,+ interactionStyle,+ };+}diff --git a/apps/start/src/components/charts/use-highlight-segment.ts b/apps/start/src/components/charts/use-highlight-segment.tsnew file mode 100644index 000000000..f5cb8bce0--- /dev/null+++ b/apps/start/src/components/charts/use-highlight-segment.ts@@ -0,0 +1,61 @@+"use client";++import { useSpring } from "motion/react";+import { useMemo, useRef } from "react";+import { useChartConfig } from "./chart-config-context";+import { useChartHover, useChartStable } from "./chart-context";+import {+ computeSegmentBounds,+ INACTIVE_SEGMENT,+} from "./highlight-segment-bounds";++// Hover-highlight band for `line.tsx` and `area.tsx`. Computes the segment+// bounds and springs its x/width; `<HighlightSegment>` renders the clipped+// re-stroke. Spring tuning comes from `ChartConfigProvider.highlightSpring`.+// Stable + hover slices are read separately so callers can see the exact+// subscription surface (anything calling this hook will re-render on hover).++export interface HighlightSegmentResult {+ xSpring: ReturnType<typeof useSpring>;+ widthSpring: ReturnType<typeof useSpring>;+ isActive: boolean;+}++/**+ * @param enabled set false when there is no stroke to highlight (e.g. an area+ * with `showLine={false}`); defaults true.+ */+export function useHighlightSegment({+ enabled = true,+}: {+ enabled?: boolean;+} = {}): HighlightSegmentResult {+ const { data, xScale, xAccessor } = useChartStable();+ const { tooltipData, selection } = useChartHover();+ const { highlightSpring } = useChartConfig();++ const bounds = useMemo(+ () =>+ enabled+ ? computeSegmentBounds(data, xScale, xAccessor, tooltipData, selection)+ : INACTIVE_SEGMENT,+ [enabled, data, xScale, xAccessor, tooltipData, selection]+ );++ const xSpring = useSpring(0, highlightSpring);+ const widthSpring = useSpring(0, highlightSpring);++ // Jump on inactive→active so the band appears at the hovered point instead+ // of sliding in from x=0; ease on subsequent moves.+ const wasActive = useRef(false);+ if (bounds.isActive && !wasActive.current) {+ xSpring.jump(bounds.x);+ widthSpring.jump(bounds.width);+ } else {+ xSpring.set(bounds.x);+ widthSpring.set(bounds.width);+ }+ wasActive.current = bounds.isActive;++ return { xSpring, widthSpring, isActive: bounds.isActive };+}diff --git a/apps/start/src/components/charts/use-line-segment-highlight.ts b/apps/start/src/components/charts/use-line-segment-highlight.tsnew file mode 100644index 000000000..5b9740d07--- /dev/null+++ b/apps/start/src/components/charts/use-line-segment-highlight.ts@@ -0,0 +1,115 @@+"use client";++import { useMemo } from "react";+import type { TooltipData } from "./chart-context";+import type { ChartSelection } from "./use-chart-interaction";++interface UseLineSegmentHighlightOptions {+ pathLength: number;+ data: Record<string, unknown>[];+ tooltipData: TooltipData | null;+ selection: ChartSelection | null | undefined;+ xScale: (value: Date | number) => number | undefined;+ yScale: (value: number) => number | undefined;+ xAccessor: (datum: Record<string, unknown>) => Date | number;+ dataKey: string;+}++/**+ * Highlight bounds for the hover/selection overlay.+ *+ * The naive implementation called `path.getPointAtLength` inside a binary+ * search per call — ~30-60 DOM measurements per Line/Area per hover bucket,+ * which made the chart jank on every bucket boundary. This version computes+ * cumulative chord lengths between data points in pixel space (pure+ * arithmetic, memoized on `(data, scales, dataKey)`), then scales them to+ * the real SVG path length so the dasharray offsets still line up with the+ * curved stroke. Same approach as bklit-ui issue #54's approximation.+ */+export function useLineSegmentHighlight({+ pathLength,+ data,+ tooltipData,+ selection,+ xScale,+ yScale,+ xAccessor,+ dataKey,+}: UseLineSegmentHighlightOptions) {+ const chordLengths = useMemo(() => {+ if (data.length < 2) {+ return { lengths: new Float64Array(0), total: 0 };+ }+ const lengths = new Float64Array(data.length);+ lengths[0] = 0;+ let total = 0;++ let prevX = xScale(xAccessor(data[0]!)) ?? 0;+ const firstValue = data[0]![dataKey];+ let prevY =+ typeof firstValue === "number"+ ? (yScale(firstValue) ?? yScale(0) ?? 0)+ : (yScale(0) ?? 0);++ for (let i = 1; i < data.length; i++) {+ const point = data[i]!;+ const x = xScale(xAccessor(point)) ?? 0;+ const value = point[dataKey];+ const y =+ typeof value === "number"+ ? (yScale(value) ?? yScale(0) ?? 0)+ : (yScale(0) ?? 0);+ const dx = x - prevX;+ const dy = y - prevY;+ total += Math.sqrt(dx * dx + dy * dy);+ lengths[i] = total;+ prevX = x;+ prevY = y;+ }+ return { lengths, total };+ }, [data, xScale, yScale, xAccessor, dataKey]);++ return useMemo(() => {+ const { lengths, total: chordTotal } = chordLengths;+ if (lengths.length === 0 || pathLength === 0 || chordTotal === 0) {+ return { startLength: 0, segmentLength: 0, isActive: false };+ }+ // Scale chord-space lengths into SVG path-space so the dasharray on the+ // curved stroke lines up. Assumes roughly uniform curvature — accurate+ // within a couple of pixels for typical chart curves.+ const scale = pathLength / chordTotal;++ if (selection?.active) {+ const startIdx = clampIndex(selection.startIndex, lengths.length);+ const endIdx = clampIndex(selection.endIndex, lengths.length);+ const startLength = (lengths[startIdx] ?? 0) * scale;+ const endLength = (lengths[endIdx] ?? 0) * scale;+ return {+ startLength,+ segmentLength: Math.max(0, endLength - startLength),+ isActive: true,+ };+ }++ if (!tooltipData) {+ return { startLength: 0, segmentLength: 0, isActive: false };+ }++ const idx = tooltipData.index;+ const startIdx = clampIndex(idx - 1, lengths.length);+ const endIdx = clampIndex(idx + 1, lengths.length);+ const startLength = (lengths[startIdx] ?? 0) * scale;+ const endLength = (lengths[endIdx] ?? 0) * scale;+ return {+ startLength,+ segmentLength: Math.max(0, endLength - startLength),+ isActive: true,+ };+ }, [chordLengths, pathLength, tooltipData, selection]);+}++function clampIndex(idx: number, length: number): number {+ if (idx < 0) return 0;+ if (idx >= length) return length - 1;+ return idx;+}diff --git a/apps/start/src/components/charts/use-mount-progress.ts b/apps/start/src/components/charts/use-mount-progress.tsnew file mode 100644index 000000000..cf7bf64c5--- /dev/null+++ b/apps/start/src/components/charts/use-mount-progress.ts@@ -0,0 +1,29 @@+"use client";++import { animate, type Transition, useMotionValue } from "motion/react";+import { useEffect, useRef } from "react";+import { DEFAULT_CHART_ENTER_TRANSITION } from "./animation";++/** Drives 0→1 enter progress using the studio motion transition (spring or tween). */+export function useMountProgress(+ enterTransition: Transition | undefined,+ delaySeconds: number,+ replayKey: number | string+) {+ const progress = useMotionValue(0);+ const transitionRef = useRef(enterTransition);+ transitionRef.current = enterTransition;++ // replayKey intentionally retriggers enter when motion settings change+ // biome-ignore lint/correctness/useExhaustiveDependencies: replayKey+ useEffect(() => {+ progress.set(0);+ const controls = animate(progress, 1, {+ ...(transitionRef.current ?? DEFAULT_CHART_ENTER_TRANSITION),+ delay: delaySeconds,+ });+ return () => controls.stop();+ }, [delaySeconds, replayKey, progress]);++ return progress;+}diff --git a/apps/start/src/components/charts/use-scheduled-tooltip.ts b/apps/start/src/components/charts/use-scheduled-tooltip.tsnew file mode 100644index 000000000..6c4175edd--- /dev/null+++ b/apps/start/src/components/charts/use-scheduled-tooltip.ts@@ -0,0 +1,93 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";++export interface ScheduledTooltipControls<T> {+ tooltipData: T | null;+ setTooltipData: React.Dispatch<React.SetStateAction<T | null>>;+ scheduleTooltip: (tooltip: T, dedupeKey?: string) => void;+ clearTooltip: () => void;+ resetTooltipDedupe: () => void;+}++function defaultDedupeKey<T>(tooltip: T): string {+ if (+ typeof tooltip === "object" &&+ tooltip !== null &&+ "index" in tooltip &&+ typeof (tooltip as { index: unknown }).index === "number"+ ) {+ return String((tooltip as { index: number }).index);+ }+ return JSON.stringify(tooltip);+}++export function useScheduledTooltip<T>(): ScheduledTooltipControls<T> {+ const [tooltipData, setTooltipData] = useState<T | null>(null);+ const lastKeyRef = useRef<string | null>(null);+ const pendingRef = useRef<T | null>(null);+ const rafRef = useRef<number | null>(null);+ const pendingKeyRef = useRef<string | null>(null);++ useEffect(() => {+ return () => {+ if (rafRef.current !== null) {+ cancelAnimationFrame(rafRef.current);+ }+ };+ }, []);++ const commitTooltip = useCallback((tooltip: T, dedupeKey: string) => {+ if (dedupeKey === lastKeyRef.current) {+ return;+ }+ lastKeyRef.current = dedupeKey;+ setTooltipData(tooltip);+ }, []);++ const scheduleTooltip = useCallback(+ (tooltip: T, dedupeKey?: string) => {+ const key = dedupeKey ?? defaultDedupeKey(tooltip);+ pendingRef.current = tooltip;+ pendingKeyRef.current = key;+ if (key === lastKeyRef.current) {+ return;+ }+ if (rafRef.current !== null) {+ return;+ }+ rafRef.current = requestAnimationFrame(() => {+ rafRef.current = null;+ const next = pendingRef.current;+ const nextKey = pendingKeyRef.current;+ if (next && nextKey) {+ commitTooltip(next, nextKey);+ }+ });+ },+ [commitTooltip]+ );++ const clearTooltip = useCallback(() => {+ if (rafRef.current !== null) {+ cancelAnimationFrame(rafRef.current);+ rafRef.current = null;+ }+ pendingRef.current = null;+ pendingKeyRef.current = null;+ lastKeyRef.current = null;+ setTooltipData(null);+ }, []);++ const resetTooltipDedupe = useCallback(() => {+ lastKeyRef.current = null;+ }, []);++ return {+ tooltipData,+ setTooltipData,+ scheduleTooltip,+ clearTooltip,+ resetTooltipDedupe,+ };+}diff --git a/apps/start/src/components/charts/x-axis.tsx b/apps/start/src/components/charts/x-axis.tsxnew file mode 100644index 000000000..1e23ba33f--- /dev/null+++ b/apps/start/src/components/charts/x-axis.tsx@@ -0,0 +1,162 @@+"use client";++import { memo, useEffect, useMemo, useState } from "react";+import { createPortal } from "react-dom";+import { cn } from "@/lib/utils";+import { useChart, useChartStable } from "./chart-context";+import { shortDateFmt } from "./chart-formatters";++export interface XAxisProps {+ /** Number of ticks to show (including first and last). Default: 5. Used when `tickMode` is `"domain"`. */+ numTicks?: number;+ /** Width of the date ticker box for fade calculation. Default: 50 */+ tickerHalfWidth?: number;+ /**+ * `"domain"` — evenly spaced ticks across the time domain (default).+ * `"data"` — one label per data row at its x value (better with sparse or monthly bars).+ */+ tickMode?: "domain" | "data";+}++interface XAxisLabelProps {+ label: string;+ x: number;+ crosshairX: number | null;+ isHovering: boolean;+ tickerHalfWidth: number;+}++function XAxisLabel({+ label,+ x,+ crosshairX,+ isHovering,+ tickerHalfWidth,+}: XAxisLabelProps) {+ const fadeBuffer = 20;+ const fadeRadius = tickerHalfWidth + fadeBuffer;++ let opacity = 1;+ if (isHovering && crosshairX !== null) {+ const distance = Math.abs(x - crosshairX);+ if (distance < tickerHalfWidth) {+ opacity = 0;+ } else if (distance < fadeRadius) {+ opacity = (distance - tickerHalfWidth) / fadeBuffer;+ }+ }++ // Zero-width container approach for perfect centering+ // The wrapper is positioned exactly at x with width:0+ // The inner span overflows and is centered via text-align+ return (+ <div+ className="absolute"+ style={{+ left: x,+ bottom: 12,+ width: 0,+ display: "flex",+ justifyContent: "center",+ }}+ >+ <span+ className={cn("whitespace-nowrap text-chart-label text-xs")}+ style={{+ opacity,+ transition: "opacity 0.4s ease-in-out",+ }}+ >+ {label}+ </span>+ </div>+ );+}++export function XAxis(props: XAxisProps) {+ const { containerRef } = useChartStable();+ const [mounted, setMounted] = useState(false);++ useEffect(() => {+ setMounted(true);+ }, []);++ const container = containerRef.current;+ if (!(mounted && container)) {+ return null;+ }++ return <XAxisInner {...props} container={container} />;+}++const XAxisInner = memo(function XAxisInner({+ numTicks = 5,+ tickerHalfWidth = 50,+ tickMode = "domain",+ container,+}: XAxisProps & { container: HTMLDivElement }) {+ const { xScale, margin, tooltipData, data, xAccessor, dateLabels } =+ useChart();++ // Generate tick labels: evenly spaced along the domain, or one per data row+ const labelsToShow = useMemo(() => {+ if (tickMode === "data") {+ return data.map((d, i) => ({+ date: xAccessor(d),+ x: (xScale(xAccessor(d)) ?? 0) + margin.left,+ label: dateLabels[i] ?? shortDateFmt.format(xAccessor(d)),+ }));+ }++ const domain = xScale.domain();+ const startDate = domain[0];+ const endDate = domain[1];++ if (!(startDate && endDate)) {+ return [];+ }++ const startTime = startDate.getTime();+ const endTime = endDate.getTime();+ const timeRange = endTime - startTime;++ // Create evenly spaced dates from start to end+ const tickCount = Math.max(2, numTicks); // At least first and last+ const dates: Date[] = [];++ for (let i = 0; i < tickCount; i++) {+ const t = i / (tickCount - 1); // 0 to 1+ const time = startTime + t * timeRange;+ dates.push(new Date(time));+ }++ return dates.map((date) => ({+ date,+ x: (xScale(date) ?? 0) + margin.left,+ label: shortDateFmt.format(date),+ }));+ }, [tickMode, data, xAccessor, xScale, margin.left, dateLabels, numTicks]);++ const isHovering = tooltipData !== null;+ const crosshairX = tooltipData ? tooltipData.x + margin.left : null;++ return createPortal(+ <div className="pointer-events-none absolute inset-0">+ {labelsToShow.map((item) => (+ <XAxisLabel+ crosshairX={crosshairX}+ isHovering={isHovering}+ key={`${item.date.getTime()}-${item.x}`}+ label={item.label}+ tickerHalfWidth={tickerHalfWidth}+ x={item.x}+ />+ ))}+ </div>,+ container+ );+});++XAxis.displayName = "XAxis";++export default XAxis;diff --git a/apps/start/src/components/charts/y-axis.tsx b/apps/start/src/components/charts/y-axis.tsxnew file mode 100644index 000000000..691f3c29e--- /dev/null+++ b/apps/start/src/components/charts/y-axis.tsx@@ -0,0 +1,84 @@+"use client";++import { memo, useEffect, useMemo, useState } from "react";+import { createPortal } from "react-dom";+import { useChartStable } from "./chart-context";++export interface YAxisProps {+ /** Number of ticks to show. Default: 5 */+ numTicks?: number;+ /** Format large numbers (e.g. 1000 as "1k"). Default: true */+ formatLargeNumbers?: boolean;+ /** Custom formatter for tick labels (e.g. USD). Overrides formatLargeNumbers when set. */+ formatValue?: (value: number) => string;+}++function formatLabel(+ value: number,+ formatLargeNumbers: boolean,+ formatValue?: (value: number) => string+): string {+ if (formatValue) {+ return formatValue(value);+ }+ if (formatLargeNumbers && value >= 1000) {+ return `${(value / 1000).toFixed(0)}k`;+ }+ return String(value);+}++export function YAxis(props: YAxisProps) {+ const { containerRef } = useChartStable();+ const [mounted, setMounted] = useState(false);++ useEffect(() => {+ setMounted(true);+ }, []);++ const container = containerRef.current;+ if (!(mounted && container)) {+ return null;+ }++ return <YAxisInner {...props} container={container} />;+}++const YAxisInner = memo(function YAxisInner({+ numTicks = 5,+ formatLargeNumbers = true,+ formatValue,+ container,+}: YAxisProps & { container: HTMLDivElement }) {+ const { yScale, margin } = useChartStable();++ const ticks = useMemo(() => {+ const tickValues = yScale.ticks(numTicks);+ return tickValues.map((value) => ({+ value,+ y: (yScale(value) ?? 0) + margin.top,+ label: formatLabel(value, formatLargeNumbers, formatValue),+ }));+ }, [yScale, margin.top, numTicks, formatLargeNumbers, formatValue]);++ return createPortal(+ <div+ className="pointer-events-none absolute top-0 bottom-0"+ style={{ left: 0, width: margin.left }}+ >+ {ticks.map((tick) => (+ <div+ className="absolute right-0 flex items-center justify-end pr-2"+ key={tick.value}+ style={{ top: tick.y, transform: "translateY(-50%)" }}+ >+ <span className="text-chart-label text-xs">{tick.label}</span>+ </div>+ ))}+ </div>,+ container+ );+});++YAxis.displayName = "YAxis";++export default YAxis;diff --git a/apps/start/src/components/overview/overview-line-chart-tooltip.tsx b/apps/start/src/components/overview/overview-line-chart-tooltip.tsxdeleted file mode 100644index b03bcbdda..000000000--- a/apps/start/src/components/overview/overview-line-chart-tooltip.tsx+++ /dev/null@@ -1,153 +0,0 @@-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';-import { useNumber } from '@/hooks/use-numer-formatter';-import React from 'react';--import {- ChartTooltipContainer,- ChartTooltipHeader,- ChartTooltipItem,- createChartTooltip,-} from '@/components/charts/chart-tooltip';-import type { IInterval } from '@openpanel/validation';-import { SerieIcon } from '../report-chart/common/serie-icon';--type Data = {- date: string;- timestamp: number;- [key: `${string}:sessions`]: number;- [key: `${string}:pageviews`]: number;- [key: `${string}:revenue`]: number | undefined;- [key: `${string}:payload`]: {- name: string;- prefix?: string;- color: string;- };-};--type Context = {- interval: IInterval;-};--export const OverviewLineChartTooltip = createChartTooltip<Data, Context>(- ({ context: { interval }, data }) => {- const formatDate = useFormatDateInterval({- interval,- short: false,- });- const number = useNumber();-- if (!data || data.length === 0) {- return null;- }-- const firstItem = data[0];-- // Get all payload items from the first data point- // Keys are in format "prefix:name:payload" or "name:payload"- const payloadItems = Object.keys(firstItem)- .filter((key) => key.endsWith(':payload'))- .map((key) => {- const payload = firstItem[key as keyof typeof firstItem] as {- name: string;- prefix?: string;- color: string;- };- // Extract the base key (without :payload) to access sessions/pageviews/revenue- const baseKey = key.replace(':payload', '');- return {- payload,- baseKey,- };- })- .filter(- (item) =>- item.payload &&- typeof item.payload === 'object' &&- 'name' in item.payload,- );-- // Sort by sessions (descending)- const sorted = payloadItems.sort((a, b) => {- const aSessions =- (firstItem[- `${a.baseKey}:sessions` as keyof typeof firstItem- ] as number) ?? 0;- const bSessions =- (firstItem[- `${b.baseKey}:sessions` as keyof typeof firstItem- ] as number) ?? 0;- return bSessions - aSessions;- });-- const limit = 3;- const visible = sorted.slice(0, limit);- const hidden = sorted.slice(limit);-- return (- <>- {visible.map((item, index) => {- const sessions =- (firstItem[- `${item.baseKey}:sessions` as keyof typeof firstItem- ] as number) ?? 0;- const pageviews =- (firstItem[- `${item.baseKey}:pageviews` as keyof typeof firstItem- ] as number) ?? 0;- const revenue = firstItem[- `${item.baseKey}:revenue` as keyof typeof firstItem- ] as number | undefined;-- return (- <React.Fragment key={item.baseKey}>- {index === 0 && firstItem.date && (- <ChartTooltipHeader>- <div>{formatDate(new Date(firstItem.date))}</div>- </ChartTooltipHeader>- )}- <ChartTooltipItem color={item.payload.color}>- <div className="flex items-center gap-1">- <SerieIcon name={item.payload.prefix || item.payload.name} />- <div className="font-medium">- {item.payload.prefix && (- <>- <span className="text-muted-foreground">- {item.payload.prefix}- </span>- <span className="mx-1">/</span>- </>- )}- {item.payload.name || 'Not set'}- </div>- </div>- <div className="col gap-1 text-sm">- {revenue !== undefined && revenue > 0 && (- <div className="flex justify-between gap-8 font-mono font-medium">- <span className="text-muted-foreground">Revenue</span>- <span style={{ color: '#3ba974' }}>- {number.currency(revenue / 100, { short: true })}- </span>- </div>- )}- <div className="flex justify-between gap-8 font-mono font-medium">- <span className="text-muted-foreground">Pageviews</span>- <span>{number.short(pageviews)}</span>- </div>- <div className="flex justify-between gap-8 font-mono font-medium">- <span className="text-muted-foreground">Sessions</span>- <span>{number.short(sessions)}</span>- </div>- </div>- </ChartTooltipItem>- </React.Fragment>- );- })}- {hidden.length > 0 && (- <div className="text-muted-foreground text-sm">- and {hidden.length} more {hidden.length === 1 ? 'item' : 'items'}- </div>- )}- </>- );- },-);diff --git a/apps/start/src/components/overview/overview-line-chart.tsx b/apps/start/src/components/overview/overview-line-chart.tsxindex 423fa5c4d..5ad30012d 100644--- a/apps/start/src/components/overview/overview-line-chart.tsx+++ b/apps/start/src/components/overview/overview-line-chart.tsx@@ -1,22 +1,19 @@-import { useNumber } from '@/hooks/use-numer-formatter';-import { cn } from '@/utils/cn';-import { getChartColor } from '@/utils/theme';-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import {- CartesianGrid,- Line,- LineChart,- ResponsiveContainer,- Tooltip,- XAxis,- YAxis,-} from 'recharts';--import type { RouterOutputs } from '@/trpc/client';+import type { timeWindows } from '@openpanel/constants';import type { IInterval } from '@openpanel/validation';-import { useXAxisProps, useYAxisProps } from '../report-chart/common/axis';+import { curveMonotoneX } from '@visx/curve';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { Grid } from '../charts/grid';+import { Line } from '../charts/line';+import { LineChart } from '../charts/line-chart';+import { useDashedTail } from '../charts/op-dashed-tail';+import { OPDatePill } from '../charts/op-date-pill';+import { OPChartTooltip } from '../charts/op-tooltip';+import { XAxis } from '../charts/x-axis';+import { YAxis } from '../charts/y-axis';import { SerieIcon } from '../report-chart/common/serie-icon';-import { OverviewLineChartTooltip } from './overview-line-chart-tooltip';+import type { RouterOutputs } from '@/trpc/client';+import { cn } from '@/utils/cn';+import { getChartColor } from '@/utils/theme';type SeriesData =RouterOutputs['overview']['topGenericSeries']['items'][number];@@ -24,113 +21,94 @@ type SeriesData =interface OverviewLineChartProps {data: RouterOutputs['overview']['topGenericSeries'];interval: IInterval;+ range?: keyof typeof timeWindows;searchQuery?: string;className?: string;}-function transformDataForRecharts(- items: SeriesData[],- searchQuery?: string,-): Array<{+const VISIBLE_LIMIT = 5;+const TOOLTIP_LIMIT = 3;++interface SeriesMeta {+ key: string;+ name: string;+ prefix?: string;+ color: string;+}++interface ChartPoint {date: string;- timestamp: number;- [key: `${string}:sessions`]: number;- [key: `${string}:pageviews`]: number;- [key: `${string}:revenue`]: number | undefined;- [key: `${string}:payload`]: {- name: string;- prefix?: string;- color: string;- };-}> {- // Filter items by search query- const filteredItems = searchQuery- ? items.filter((item) => {- const queryLower = searchQuery.toLowerCase();- return (- (item.name?.toLowerCase().includes(queryLower) ?? false) ||- (item.prefix?.toLowerCase().includes(queryLower) ?? false)- );- })- : items;+ [key: string]: unknown;+}- // Limit to top 15- const topItems = filteredItems.slice(0, 15);+function getSeriesKey(item: SeriesData): string {+ return item.prefix ? `${item.prefix}:${item.name}` : item.name;+}- // Get all unique dates from all items+function transformData(+ items: SeriesData[],+ visibleSeries: SeriesMeta[]+): ChartPoint[] {const allDates = new Set<string>();- topItems.forEach((item) => {+ items.forEach((item) => {item.data.forEach((d) => allDates.add(d.date));});- const sortedDates = Array.from(allDates).sort();-- // Transform to recharts format- return sortedDates.map((date) => {- const timestamp = new Date(date).getTime();- const result: Record<string, any> = {- date,- timestamp,- };-- topItems.forEach((item, index) => {- const dataPoint = item.data.find((d) => d.date === date);- if (dataPoint) {- // Use prefix:name as key to avoid collisions when same name exists with different prefixes- const key = item.prefix ? `${item.prefix}:${item.name}` : item.name;- result[`${key}:sessions`] = dataPoint.sessions;- result[`${key}:pageviews`] = dataPoint.pageviews;- if (dataPoint.revenue !== undefined) {- result[`${key}:revenue`] = dataPoint.revenue;+ return Array.from(allDates)+ .sort()+ .map<ChartPoint>((date) => {+ const result: ChartPoint = { date };+ visibleSeries.forEach((series) => {+ const item = items.find((i) => getSeriesKey(i) === series.key);+ const dataPoint = item?.data.find((d) => d.date === date);+ // Always populate — bklit's Line/Area plots undefined values at SVG y=0+ // (chart top), so sparse series would visually shoot to the ceiling.+ result[`${series.key}:sessions`] = dataPoint?.sessions ?? 0;+ result[`${series.key}:pageviews`] = dataPoint?.pageviews ?? 0;+ if (dataPoint?.revenue !== undefined) {+ result[`${series.key}:revenue`] = dataPoint.revenue;}- result[`${key}:payload`] = {- name: item.name,- prefix: item.prefix,- color: getChartColor(index),- };- }+ });+ return result;});-- return result as typeof result & {- date: string;- timestamp: number;- };- });}export function OverviewLineChart({data,interval,+ range,searchQuery,className,}: OverviewLineChartProps) {- const number = useNumber();-- const chartData = useMemo(- () => transformDataForRecharts(data.items, searchQuery),- [data.items, searchQuery],- );-- const visibleItems = useMemo(() => {+ const visibleSeries: SeriesMeta[] = useMemo(() => {const filtered = searchQuery? data.items.filter((item) => {- const queryLower = searchQuery.toLowerCase();+ const q = searchQuery.toLowerCase();return (- (item.name?.toLowerCase().includes(queryLower) ?? false) ||- (item.prefix?.toLowerCase().includes(queryLower) ?? false)+ (item.name?.toLowerCase().includes(q) ?? false) ||+ (item.prefix?.toLowerCase().includes(q) ?? false));}): data.items;- return filtered.slice(0, 15);+ return filtered.slice(0, VISIBLE_LIMIT).map((item, index) => ({+ key: getSeriesKey(item),+ name: item.name,+ prefix: item.prefix ?? undefined,+ color: getChartColor(index),+ }));}, [data.items, searchQuery]);- const xAxisProps = useXAxisProps({ interval, hide: false });- const yAxisProps = useYAxisProps({});+ const chartData = useMemo(+ () => transformData(data.items, visibleSeries),+ [data.items, visibleSeries]+ );- if (visibleItems.length === 0) {+ const dashFromIndex = useDashedTail({ data: chartData, range, interval });++ if (visibleSeries.length === 0) {return (<div- className={cn('flex items-center justify-center h-[358px]', className)}+ className={cn('flex h-[358px] items-center justify-center', className)}><div className="text-muted-foreground text-sm">{searchQuery ? 'No results found' : 'No data available'}@@ -141,73 +119,133 @@ export function OverviewLineChart({return (<div className={cn('w-full p-4', className)}>- <div className="h-[358px] w-full">- <OverviewLineChartTooltip.TooltipProvider interval={interval}>- <ResponsiveContainer>- <LineChart data={chartData}>- <CartesianGrid- strokeDasharray="3 3"- horizontal={true}- vertical={false}- className="stroke-border"- />- <XAxis {...xAxisProps} />- <YAxis {...yAxisProps} />- <Tooltip content={<OverviewLineChartTooltip.Tooltip />} />- {visibleItems.map((item, index) => {- const color = getChartColor(index);- // Use prefix:name as key to avoid collisions when same name exists with different prefixes- const key = item.prefix- ? `${item.prefix}:${item.name}`- : item.name;- return (- <Line- key={key}- type="monotone"- dataKey={`${key}:sessions`}- stroke={color}- strokeWidth={2}- dot={false}- isAnimationActive={false}- />- );- })}- </LineChart>- </ResponsiveContainer>- </OverviewLineChartTooltip.TooltipProvider>+ <div className="h-[300px] w-full">+ <LineChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-full"+ data={chartData}+ margin={{ top: 8, right: 12, bottom: 40, left: 32 }}+ xDataKey="date"+ >+ <Grid horizontal />+ <YAxis />+ <XAxis />+ {visibleSeries.map((series) => (+ <Line+ animate={false}+ curve={curveMonotoneX}+ dashArray="4,4"+ dashFromIndex={dashFromIndex}+ dataKey={`${series.key}:pageviews`}+ fadeEdges="left"+ key={series.key}+ stroke={series.color}+ strokeWidth={1.5}+ />+ ))}+ <OPDatePill interval={interval} />+ <OPChartTooltip<ChartPoint>+ extra={() => {+ const total = visibleSeries.length;+ const hidden = Math.max(0, total - TOOLTIP_LIMIT);+ if (hidden === 0) {+ return null;+ }+ return (+ <div className="text-muted-foreground text-sm">+ and {hidden} more {hidden === 1 ? 'item' : 'items'}+ </div>+ );+ }}+ interval={interval}+ rows={(point) => {+ const ranked = visibleSeries+ .map((series) => {+ const sessions =+ (point[`${series.key}:sessions`] as number | undefined) ??+ 0;+ const pageviews =+ (point[`${series.key}:pageviews`] as number | undefined) ??+ 0;+ const revenue = point[`${series.key}:revenue`] as+ | number+ | undefined;+ return { series, sessions, pageviews, revenue };+ })+ .sort((a, b) => b.pageviews - a.pageviews);++ const top = ranked.slice(0, TOOLTIP_LIMIT);++ return top.map(({ series, sessions, pageviews, revenue }) => ({+ color: series.color,+ icon: <SerieIcon name={series.prefix || series.name} />,+ label: (+ <>+ {series.prefix && (+ <>+ <span className="text-muted-foreground">+ {series.prefix}+ </span>+ <span className="mx-1">/</span>+ </>+ )}+ {series.name || 'Not set'}+ </>+ ),+ sub: [+ ...(revenue !== undefined && revenue > 0+ ? [+ {+ label: 'Revenue',+ value: revenue,+ unit: 'currency' as const,+ color: 'var(--chart-8)',+ },+ ]+ : []),+ { label: 'Pageviews', value: pageviews },+ { label: 'Sessions', value: sessions },+ ],+ }));+ }}+ showCrosshair+ showDatePill={false}+ showDots+ />+ </LineChart></div>- {/* Legend */}- <LegendScrollable items={visibleItems} />+ <LegendScrollable items={visibleSeries} /></div>);}-function LegendScrollable({- items,-}: {- items: SeriesData[];-}) {+function LegendScrollable({ items }: { items: SeriesMeta[] }) {const scrollRef = useRef<HTMLDivElement>(null);const [showLeftGradient, setShowLeftGradient] = useState(false);const [showRightGradient, setShowRightGradient] = useState(false);const updateGradients = useCallback(() => {const el = scrollRef.current;- if (!el) return;+ if (!el) {+ return;+ }const { scrollLeft, scrollWidth, clientWidth } = el;const hasOverflow = scrollWidth > clientWidth;setShowLeftGradient(hasOverflow && scrollLeft > 0);setShowRightGradient(- hasOverflow && scrollLeft < scrollWidth - clientWidth - 1,+ hasOverflow && scrollLeft < scrollWidth - clientWidth - 1);}, []);useEffect(() => {const el = scrollRef.current;- if (!el) return;+ if (!el) {+ return;+ }updateGradients();@@ -220,54 +258,47 @@ function LegendScrollable({};}, [updateGradients]);- // Update gradients when items changeuseEffect(() => {requestAnimationFrame(updateGradients);}, [items, updateGradients]);return (<div className="relative mt-4 -mb-2">- {/* Left gradient */}<divclassName={cn(- 'pointer-events-none absolute left-0 top-0 z-10 h-full w-8 bg-gradient-to-r from-card to-transparent transition-opacity duration-200',- showLeftGradient ? 'opacity-100' : 'opacity-0',+ 'pointer-events-none absolute top-0 left-0 z-10 h-full w-8 bg-gradient-to-r from-card to-transparent transition-opacity duration-200',+ showLeftGradient ? 'opacity-100' : 'opacity-0')}/>- {/* Scrollable legend */}<div+ className="hide-scrollbar flex gap-x-4 gap-y-1 overflow-x-auto px-2 py-1 text-xs"ref={scrollRef}- className="flex gap-x-4 gap-y-1 overflow-x-auto px-2 py-1 hide-scrollbar text-xs">- {items.map((item, index) => {- const color = getChartColor(index);- return (- <div- className="flex shrink-0 items-center gap-1"- key={item.prefix ? `${item.prefix}:${item.name}` : item.name}- style={{ color }}- >- <SerieIcon name={item.prefix || item.name} />- <span className="font-semibold whitespace-nowrap">- {item.prefix && (- <>- <span className="text-muted-foreground">{item.prefix}</span>- <span className="mx-1">/</span>- </>- )}- {item.name || 'Not set'}- </span>- </div>- );- })}+ {items.map((series) => (+ <div+ className="flex shrink-0 items-center gap-1"+ key={series.key}+ style={{ color: series.color }}+ >+ <SerieIcon name={series.prefix || series.name} />+ <span className="whitespace-nowrap font-semibold">+ {series.prefix && (+ <>+ <span className="text-muted-foreground">{series.prefix}</span>+ <span className="mx-1">/</span>+ </>+ )}+ {series.name || 'Not set'}+ </span>+ </div>+ ))}</div>- {/* Right gradient */}<divclassName={cn(- 'pointer-events-none absolute right-0 top-0 z-10 h-full w-8 bg-gradient-to-l from-card to-transparent transition-opacity duration-200',- showRightGradient ? 'opacity-100' : 'opacity-0',+ 'pointer-events-none absolute top-0 right-0 z-10 h-full w-8 bg-gradient-to-l from-card to-transparent transition-opacity duration-200',+ showRightGradient ? 'opacity-100' : 'opacity-0')}/></div>@@ -281,21 +312,17 @@ export function OverviewLineChartLoading({}) {return (<div- className={cn('flex items-center justify-center h-[358px]', className)}+ className={cn('flex h-[358px] items-center justify-center', className)}><div className="text-muted-foreground text-sm">Loading...</div></div>);}-export function OverviewLineChartEmpty({- className,-}: {- className?: string;-}) {+export function OverviewLineChartEmpty({ className }: { className?: string }) {return (<div- className={cn('flex items-center justify-center h-[358px]', className)}+ className={cn('flex h-[358px] items-center justify-center', className)}><div className="text-muted-foreground text-sm">No data available</div></div>diff --git a/apps/start/src/components/overview/overview-live-histogram.tsx b/apps/start/src/components/overview/overview-live-histogram.tsxindex 6de8030ca..9632b4a75 100644--- a/apps/start/src/components/overview/overview-live-histogram.tsx+++ b/apps/start/src/components/overview/overview-live-histogram.tsx@@ -1,45 +1,59 @@import { useTRPC } from '@/integrations/trpc/react';-import { useQuery } from '@tanstack/react-query';-import { useNumber } from '@/hooks/use-numer-formatter';-import { getChartColor } from '@/utils/theme';-import * as Portal from '@radix-ui/react-portal';-import { bind } from 'bind-event-listener';-import throttle from 'lodash.throttle';-import React, { useEffect, useState } from 'react';+import { cn } from '@/utils/cn';+import { useQuery } from '@tanstack/react-query';+import { useState } from 'react';+import { Bar } from '../charts/bar';+import { BarChart } from '../charts/bar-chart';import {- Bar,- BarChart,- ResponsiveContainer,- Tooltip,- XAxis,- YAxis,-} from 'recharts';+ OPStatHoverBridge,+ type OPStatHoverState,+} from '../charts/op-stat-hover-bridge';import { SerieIcon } from '../report-chart/common/serie-icon';+import { Skeleton } from '../skeleton';+import { MetricCardShell } from './overview-metric-card';+interface OverviewLiveHistogramProps {projectId: string;shareId?: string;}+const PRIMARY_COLOR = 'var(--chart-0)';++interface MinutePoint {+ time: string;+ sessionCount: number;+ /** Synthetic per-minute date so bklit's time-based AreaChart can scale the X. */+ date: Date;+ [key: string]: unknown;+}+export function OverviewLiveHistogram({projectId,shareId,}: OverviewLiveHistogramProps) {const trpc = useTRPC();+ const number = useNumber();- // Use the new liveData endpoint instead of chart propsconst { data: liveData, isLoading } = useQuery(trpc.overview.liveData.queryOptions({ projectId, shareId }),);- const totalSessions = liveData?.totalSessions ?? 0;- const chartData = liveData?.minuteCounts ?? [];+ const [hover, setHover] = useState<OPStatHoverState<MinutePoint>>({+ index: null,+ point: null,+ });if (isLoading) {return (- <Wrapper count={0}>- <div className="h-full w-full animate-pulse bg-def-200 rounded" />- </Wrapper>+ <MetricCardShell>+ <div className="px-3 pt-2.5">+ <Skeleton className="h-3 w-24" />+ <Skeleton className="mt-1 h-6 w-12" />+ <Skeleton className="mt-0.5 h-3 w-32" />+ </div>+ <div className="mt-1.5 h-[40px] animate-pulse bg-def-200/40" />+ </MetricCardShell>);}@@ -47,189 +61,84 @@ export function OverviewLiveHistogram({return null;}- const maxDomain =- Math.max(...chartData.map((item) => item.sessionCount)) * 1.2;+ const rawMinutes = liveData.minuteCounts ?? [];+ const now = Date.now();+ const chartData: MinutePoint[] = rawMinutes.map((point, i) => ({+ ...point,+ date: new Date(now - (rawMinutes.length - 1 - i) * 60_000),+ }));+ const totalSessions = liveData.totalSessions ?? 0;+ const displayCount = hover.point?.sessionCount ?? totalSessions;+ const displayLabel = hover.point ? hover.point.time : 'Last 30 min';+ const referrers = liveData.referrers ?? [];return (- <Wrapper- count={totalSessions}- icons={- <div className="row gap-2 shrink-0">- {liveData.referrers.slice(0, 3).map((ref, index) => (- <div- key={`${ref.referrer}-${ref.count}-${index}`}- className="font-bold text-xs row gap-1 items-center"- >- <SerieIcon name={ref.referrer} />- <span>{ref.count}</span>- </div>- ))}- </div>- }- >- <div className="h-full w-full">- <ResponsiveContainer width="100%" height="100%">- <BarChart- data={chartData}- margin={{ top: 0, right: 0, left: 0, bottom: 0 }}- >- <Tooltip- content={CustomTooltip}- cursor={{- fill: 'var(--def-200)',- }}+ <MetricCardShell>+ <div className="px-3 pt-2.5">+ <div className="flex items-start justify-between gap-2">+ <span className="truncate text-[10px] font-medium uppercase tracking-wider text-muted-foreground">+ Live · 30 min+ </span>+ <span className="relative flex h-2 w-2 items-center justify-center">+ <span+ className={cn(+ 'absolute inline-flex h-full w-full rounded-full opacity-75',+ totalSessions > 0 ? 'bg-emerald-500 animate-ping' : 'bg-destructive',+ )}/>- <XAxis dataKey="time" axisLine={false} tickLine={false} hide />- <YAxis hide domain={[0, maxDomain]} />- <Bar- dataKey="sessionCount"- className="fill-chart-0"- isAnimationActive={false}+ <span+ className={cn(+ 'relative inline-flex h-2 w-2 rounded-full',+ totalSessions > 0 ? 'bg-emerald-500' : 'bg-destructive',+ )}/>- </BarChart>- </ResponsiveContainer>- </div>- </Wrapper>- );-}--interface WrapperProps {- children: React.ReactNode;- count: number;- icons?: React.ReactNode;-}--function Wrapper({ children, count, icons }: WrapperProps) {- return (- <div className="flex h-full flex-col">- <div className="row gap-2 justify-between items-center">- <div className="relative text-xs font-medium text-muted-foreground">- {count} sessions last 30 min+ </span></div>- {icons}- </div>- <div className="relative flex h-full w-full flex-1 items-end justify-center gap-2">- {children}- </div>- </div>- );-}--// Custom tooltip component that uses portals to escape overflow hidden-const CustomTooltip = ({ active, payload, coordinate }: any) => {- const number = useNumber();- const [position, setPosition] = useState<{ x: number; y: number } | null>(- null,- );-- const inactive = !active || !payload?.length;- useEffect(() => {- const setPositionThrottled = throttle(setPosition, 50);- const unsubMouseMove = bind(window, {- type: 'mousemove',- listener(event) {- if (!inactive) {- setPositionThrottled({ x: event.clientX, y: event.clientY + 20 });- }- },- });- const unsubDragEnter = bind(window, {- type: 'pointerdown',- listener() {- setPosition(null);- },- });-- return () => {- unsubMouseMove();- unsubDragEnter();- };- }, [inactive]);-- if (inactive) {- return null;- }-- if (!active || !payload || !payload.length) {- return null;- }-- const data = payload[0].payload;-- const tooltipWidth = 200;- const correctXPosition = (x: number | undefined) => {- if (!x) {- return undefined;- }-- const screenWidth = window.innerWidth;- const newX = x;-- if (newX + tooltipWidth > screenWidth) {- return screenWidth - tooltipWidth;- }- return newX;- };-- return (- <Portal.Portal- style={{- position: 'fixed',- top: position?.y,- left: correctXPosition(position?.x),- zIndex: 1000,- width: tooltipWidth,- }}- className="bg-background/80 p-3 rounded-md border shadow-xl backdrop-blur-sm"- >- <div className="flex justify-between gap-8 text-muted-foreground">- <div>{data.time}</div>- </div>- <React.Fragment>- <div className="flex gap-2">- <div- className="w-[3px] rounded-full"- style={{ background: getChartColor(0) }}- />- <div className="col flex-1 gap-1">- <div className="flex items-center gap-1">Sessions</div>- <div className="flex justify-between gap-8 font-mono font-medium">- <div className="row gap-1">- {number.formatWithUnit(data.sessionCount)}- </div>- </div>- </div>+ <div className="mt-1 flex items-baseline gap-0.5 leading-none">+ <span className="truncate font-mono font-semibold text-xl text-foreground tracking-tight tabular-nums">+ {number.short(displayCount)}+ </span></div>- {data.referrers && data.referrers.length > 0 && (- <div className="mt-2 pt-2 border-t border-border">- <div className="text-xs text-muted-foreground mb-2">Referrers:</div>- <div className="space-y-1">- {data.referrers.slice(0, 3).map((ref: any, index: number) => (+ <div className="mt-0.5 flex items-center justify-between gap-2 truncate text-[11px] leading-none text-muted-foreground">+ <span className="truncate">{displayLabel}</span>+ {referrers.length > 0 && (+ <div className="flex shrink-0 items-center gap-1.5">+ {referrers.slice(0, 3).map((ref, index) => (<divkey={`${ref.referrer}-${ref.count}-${index}`}- className="row items-center justify-between text-xs"+ className="flex items-center gap-0.5"+ title={`${ref.referrer} · ${ref.count}`}>- <div className="row items-center gap-1">- <SerieIcon name={ref.referrer} />- <span- className="truncate max-w-[120px]"- title={ref.referrer}- >- {ref.referrer}- </span>- </div>- <span className="font-mono">{ref.count}</span>+ <SerieIcon name={ref.referrer} />+ <span className="font-mono tabular-nums">{ref.count}</span></div>))}- {data.referrers.length > 3 && (- <div className="text-xs text-muted-foreground">- +{data.referrers.length - 3} more- </div>- )}</div>- </div>+ )}+ </div>+ </div>++ <div className="mt-1.5 h-[40px]">+ {chartData.length > 0 && (+ <BarChart+ data={chartData}+ xDataKey="time"+ aspectRatio="auto"+ className="h-full"+ margin={{ top: 6, right: 0, bottom: 4, left: 0 }}+ animationDuration={0}+ barGap={0.25}+ >+ <OPStatHoverBridge onHoverChange={setHover} />+ <Bar+ dataKey="sessionCount"+ fill={PRIMARY_COLOR}+ animate={false}+ lineCap={2}+ />+ </BarChart>)}- </React.Fragment>- </Portal.Portal>+ </div>+ </MetricCardShell>);-};+}diff --git a/apps/start/src/components/overview/overview-metric-card.tsx b/apps/start/src/components/overview/overview-metric-card.tsxindex a2ea8310f..aa129fd4c 100644--- a/apps/start/src/components/overview/overview-metric-card.tsx+++ b/apps/start/src/components/overview/overview-metric-card.tsx@@ -1,16 +1,25 @@+import { useFormatDateInterval } from '@/hooks/use-format-date-interval';+import { fancyMinutes, useNumber } from '@/hooks/use-numer-formatter';+import { cn } from '@/utils/cn';+import { timeWindows } from '@openpanel/constants';import { getPreviousMetric } from '@openpanel/common';-import { useEffect, useRef, useState } from 'react';-import AutoSizer from 'react-virtualized-auto-sizer';-import { Bar, BarChart, Tooltip } from 'recharts';+import type { IInterval } from '@openpanel/validation';+import { curveMonotoneX } from '@visx/curve';+import { type ReactNode, useState } from 'react';+import { Area } from '../charts/area';+import { AreaChart } from '../charts/area-chart';+import { useDashedTail } from '../charts/op-dashed-tail';import {- getDiffIndicator,- PreviousDiffIndicatorPure,-} from '../report-chart/common/previous-diff-indicator';+ OPStatHoverBridge,+ type OPStatHoverState,+} from '../charts/op-stat-hover-bridge';+import { PreviousDiffIndicatorPure } from '../report-chart/common/previous-diff-indicator';import { Skeleton } from '../skeleton';-import { Tooltiper } from '../ui/tooltip';-import { fancyMinutes, useNumber } from '@/hooks/use-numer-formatter';-import { cn } from '@/utils/cn';-import { formatDate, timeAgo } from '@/utils/date';+import { formatDate as formatAbsoluteDate, timeAgo } from '@/utils/date';++const PRIMARY_COLOR = 'var(--chart-0)';++export type MetricUnit = '' | 'date' | 'timeAgo' | 'min' | '%' | 'currency';interface MetricCardProps {id: string;@@ -23,12 +32,16 @@ interface MetricCardProps {current: number;previous?: number | null;};- unit?: '' | 'date' | 'timeAgo' | 'min' | '%' | 'currency';+ unit?: MetricUnit;label: string;onClick?: () => void;active?: boolean;inverted?: boolean;isLoading?: boolean;+ /** Interval drives the hover-label date format. */+ interval?: IInterval;+ /** Range drives the default label ("Last 30 days") and dashed-tail logic. */+ range?: keyof typeof timeWindows;}export function OverviewMetricCard({@@ -41,187 +54,166 @@ export function OverviewMetricCard({active,inverted = false,isLoading = false,+ interval = 'day',+ range,}: MetricCardProps) {- const [currentIndex, setCurrentIndex] = useState<number | null>(null);- const number = useNumber();- const { current, previous } = metric;- const timer = useRef<NodeJS.Timeout | null>(null);-- useEffect(() => {- if (timer.current) {- clearTimeout(timer.current);- }-- if (currentIndex) {- timer.current = setTimeout(() => {- setCurrentIndex(null);- }, 1000);- }-- return () => {- if (timer.current) {- clearTimeout(timer.current);- }- };- }, [currentIndex]);-- const renderValue = (value: number, unitClassName?: string, short = true) => {- if (unit === 'date') {- return <>{formatDate(new Date(value))}</>;- }-- if (unit === 'timeAgo') {- if (!value) {- return <>{'N/A'}</>;- }- return <>{timeAgo(new Date(value))}</>;- }-- if (unit === 'min') {- return <>{fancyMinutes(value)}</>;- }-- if (unit === 'currency') {- // Revenue is stored in cents, convert to dollars- return <>{number.currency(value / 100)}</>;- }+ const formatDate = useFormatDateInterval({ interval, short: false });+ const [hover, setHover] = useState<+ OPStatHoverState<{ date: string; current: number; previous?: number }>+ >({ index: null, point: null });- return (- <>- {short ? number.short(value) : number.format(value)}- {unit && <span className={unitClassName}>{unit}</span>}- </>- );- };+ const hovered = hover.point;+ const displayValue = hovered ? (hovered.current ?? 0) : metric.current;+ const displayPrev = hovered+ ? (hovered.previous ?? null)+ : (metric.previous ?? null);+ const displayLabel = hovered+ ? formatDate(new Date(hovered.date))+ : (range ? timeWindows[range]?.label : 'Total') || 'Total';- const graphColors = getDiffIndicator(- inverted,- getPreviousMetric(current, previous)?.state,- '#6ee7b7', // green- '#fda4af', // red- '#93c5fd' // blue- );+ const diff = getPreviousMetric(displayValue, displayPrev);+ const dashFromIndex = useDashedTail({ data, range, interval });- const renderTooltip = () => {- if (currentIndex) {- return (- <span>- {formatDate(new Date(data[currentIndex]?.date))}:{' '}- <span className="font-semibold">- {renderValue(- data[currentIndex].current,- 'ml-1 font-light text-xl',- false- )}+ return (+ <MetricCardShell active={active} onClick={onClick}>+ <div className="px-3 pt-2.5">+ <div className="flex items-start justify-between gap-2">+ <span className="truncate text-[10px] font-medium uppercase tracking-wider text-muted-foreground">+ {label}</span>- </span>- );- }+ {isLoading ? null : (+ <PreviousDiffIndicatorPure+ {...diff}+ inverted={inverted}+ size="xs"+ />+ )}+ </div>+ <div className="mt-1 flex items-baseline gap-0.5 leading-none">+ {isLoading ? (+ <Skeleton className="h-5 w-20" />+ ) : (+ <MetricValue value={displayValue} unit={unit} />+ )}+ </div>+ <div className="mt-0.5 truncate text-[11px] leading-none text-muted-foreground">+ {displayLabel}+ </div>+ </div>- return (- <span>- {label}:{' '}- <span className="font-semibold">- {renderValue(metric.current, 'ml-1 font-light text-xl', false)}- </span>- </span>- );- };- return (- <Tooltiper asChild content={renderTooltip()} sideOffset={-20}>- <button- className={cn(- 'col-span-2 flex-1 shadow-[0_0_0_0.5px] shadow-border md:col-span-1',- active && 'bg-def-100'- )}- onClick={onClick}- type="button"- >- <div className={cn('group relative p-4')}>- <div- className={cn(- 'absolute right-4 bottom-0 left-4 z-0 opacity-50 transition-opacity duration-300 group-hover:opacity-100'- )}+ <div className="mt-1.5 h-[40px]">+ {data.length > 0 && (+ <AreaChart+ data={data}+ xDataKey="date"+ aspectRatio="auto"+ className="h-full"+ margin={{ top: 6, right: 0, bottom: 4, left: 0 }}+ animationDuration={0}>- <AutoSizer style={{ height: 20 }}>- {({ width }) => (- <BarChart- data={data}- height={20}- margin={{ top: 0, right: 0, left: 0, bottom: 0 }}- onMouseMove={(event) => {- setCurrentIndex(event.activeTooltipIndex ?? null);- }}- style={{- background: 'transparent',- }}- width={width}- >- <Tooltip content={() => null} cursor={false} />- <Bar- dataKey={'current'}- fill={graphColors}- fillOpacity={1}- isAnimationActive={false}- strokeWidth={0}- type="step"- />- </BarChart>- )}- </AutoSizer>- </div>- <OverviewMetricCardNumber- enhancer={- <PreviousDiffIndicatorPure- className="text-sm"- inverted={inverted}- size="sm"- {...getPreviousMetric(current, previous)}- />- }- isLoading={isLoading}- label={label}- value={renderValue(current, 'ml-1 font-light text-xl')}- />- </div>- </button>- </Tooltiper>+ <OPStatHoverBridge onHoverChange={setHover} />+ <Area+ dataKey="current"+ stroke={PRIMARY_COLOR}+ fill={PRIMARY_COLOR}+ fillOpacity={active ? 0.25 : 0.16}+ gradientToOpacity={0}+ strokeWidth={1.5}+ curve={curveMonotoneX}+ fadeEdges={false}+ animate={false}+ dashFromIndex={dashFromIndex}+ dashArray="3,3"+ />+ </AreaChart>+ )}+ </div>+ </MetricCardShell>);}-export function OverviewMetricCardNumber({- label,- value,- enhancer,+/**+ * Outer chrome shared by the metric cards and the live histogram card —+ * fixed-height button with hover/active states and a left-bar accent. The+ * sparkline is expected to be the last child and bleed to the bottom edge.+ */+export function MetricCardShell({+ children,+ active,+ onClick,className,- isLoading,}: {- label: React.ReactNode;- value: React.ReactNode;- enhancer?: React.ReactNode;+ children: ReactNode;+ active?: boolean;+ onClick?: () => void;className?: string;- isLoading?: boolean;}) {+ const Tag: 'button' | 'div' = onClick ? 'button' : 'div';return (- <div className={cn('col min-w-0 gap-2', className)}>- <div className="flex min-w-0 items-center gap-2 text-left">- <span className="truncate font-medium text-muted-foreground text-sm leading-[1.1]">- {label}- </span>- </div>- {isLoading ? (- <div className="flex items-end justify-between gap-4">- <Skeleton className="h-6 w-16" />- <Skeleton className="h-6 w-12" />- </div>- ) : (- <div className="w-full truncate text-left font-bold font-mono text-3xl leading-[1.1]">- {value}- </div>+ <Tag+ type={onClick ? 'button' : undefined}+ onClick={onClick}+ className={cn(+ 'group relative flex flex-col overflow-hidden text-left',+ 'shadow-[0_0_0_0.5px] shadow-border transition-colors',+ active ? 'bg-def-100' : 'bg-card hover:bg-def-100/50',+ onClick && 'cursor-pointer',+ className,)}- <div className="center col absolute top-0 right-0 bottom-0 justify-center pr-4">- {enhancer}- </div>- </div>+ >+ {active && (+ <span+ aria-hidden+ className="absolute inset-y-0 left-0 w-[2px] bg-chart-0"+ />+ )}+ {children}+ </Tag>);}++const VALUE_CLASS =+ 'truncate font-mono font-semibold text-xl text-foreground tracking-tight tabular-nums';++function MetricValue({ value, unit }: { value: number; unit?: MetricUnit }) {+ const number = useNumber();++ if (unit === 'date') {+ return (+ <span className={VALUE_CLASS}>+ {value ? formatAbsoluteDate(new Date(value)) : 'N/A'}+ </span>+ );+ }++ if (unit === 'timeAgo') {+ return (+ <span className={VALUE_CLASS}>{value ? timeAgo(new Date(value)) : 'N/A'}</span>+ );+ }++ if (unit === 'min') {+ return <span className={VALUE_CLASS}>{fancyMinutes(value)}</span>;+ }++ if (unit === 'currency') {+ return (+ <span className={VALUE_CLASS}>+ {number.currency(value / 100, { short: true })}+ </span>+ );+ }++ if (unit === '%') {+ return (+ <>+ <span className={VALUE_CLASS}>{number.format(value)}</span>+ <span className="font-mono font-medium text-sm text-muted-foreground">+ %+ </span>+ </>+ );+ }++ return <span className={VALUE_CLASS}>{number.short(value)}</span>;+}diff --git a/apps/start/src/components/overview/overview-metrics.tsx b/apps/start/src/components/overview/overview-metrics.tsxindex 7ffed140c..8e7b07e7d 100644--- a/apps/start/src/components/overview/overview-metrics.tsx+++ b/apps/start/src/components/overview/overview-metrics.tsx@@ -1,44 +1,41 @@-import { useOverviewOptions } from '@/components/overview/useOverviewOptions';-import { useEventQueryFilters } from '@/hooks/use-event-query-filters';-import { cn } from '@/utils/cn';--import { useDashedStroke } from '@/hooks/use-dashed-stroke';-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';-import { useNumber } from '@/hooks/use-numer-formatter';-import { useTRPC } from '@/integrations/trpc/react';-import type { RouterOutputs } from '@/trpc/client';-import { getChartColor } from '@/utils/theme';-import { getPreviousMetric } from '@openpanel/common';import type { IInterval } from '@openpanel/validation';import { useQuery } from '@tanstack/react-query';-import { isSameDay, isSameHour, isSameMonth, isSameWeek } from 'date-fns';-import { last } from 'ramda';-import React, { useState } from 'react';-import {- Area,- Bar,- CartesianGrid,- Cell,- ComposedChart,- Customized,- Line,- ReferenceLine,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';-import { createChartTooltip } from '../charts/chart-tooltip';-import { useXAxisProps, useYAxisProps } from '../report-chart/common/axis';-import { PreviousDiffIndicatorPure } from '../report-chart/common/previous-diff-indicator';+import { curveMonotoneX } from '@visx/curve';+import { DollarSignIcon } from 'lucide-react';+import { useCallback, useMemo, useState } from 'react';+import { Area } from '../charts/area';+import { ComposedChart } from '../charts/composed-chart';+import { Grid } from '../charts/grid';+import { Line } from '../charts/line';+import { useDashedTail } from '../charts/op-dashed-tail';+import { OPDatePill } from '../charts/op-date-pill';+import { OPReferences } from '../charts/op-references';+import { OPReferrerSpikes } from '../charts/op-referrer-spikes';+import { OPSeriesDots } from '../charts/op-series-dots';+import { OPChartTooltip } from '../charts/op-tooltip';+import { XAxis } from '../charts/x-axis';+import { YAxis } from '../charts/y-axis';import { Skeleton } from '../skeleton';import { OverviewLiveHistogram } from './overview-live-histogram';import { OverviewMetricCard } from './overview-metric-card';+import { useOverviewOptions } from '@/components/overview/useOverviewOptions';+import { useEventQueryFilters } from '@/hooks/use-event-query-filters';+import { useTRPC } from '@/integrations/trpc/react';+import type { RouterOutputs } from '@/trpc/client';+import { cn } from '@/utils/cn';+import { getChartColor } from '@/utils/theme';interface OverviewMetricsProps {projectId: string;shareId?: string;}+// Softer than --chart-8's electric emerald, still clearly "green = money".+const REVENUE_COLOR = 'oklch(0.68 0.11 158)';+// Bump alpha (0.2 → 0.4) so the bklit hover highlight — which inherits the+// line's stroke color — has enough body to be perceptible on hover.+const PREV_LINE_COLOR = 'oklch(from var(--foreground) l c h / 0.4)';+const TITLES = [{title: 'Unique Visitors',@@ -103,164 +100,122 @@ export default function OverviewMetrics({filters,startDate,endDate,- }),+ }));- const data =- overviewQuery.data?.series?.map((item) => ({- ...item,- timestamp: new Date(item.date).getTime(),- })) || [];+ const series = overviewQuery.data?.series ?? [];+ const [mockRevenue, setMockRevenue] = useState(false);+ const data = useMemo(+ () => (mockRevenue ? injectMockRevenue(series) : series),+ [series, mockRevenue]+ );return (- <>- <div className="relative -top-0.5 col-span-6 mb-0 mt-0 md:m-0">- <div className="card mb-2 grid grid-cols-4 overflow-hidden rounded-md">- {TITLES.map((title, index) => (- <OverviewMetricCard- key={title.key}- id={title.key}- onClick={() => setMetric(index)}- label={title.title}- metric={{- current: overviewQuery.data?.metrics[title.key] ?? 0,- previous: overviewQuery.data?.metrics[`prev_${title.key}`],- }}- unit={title.unit}- data={data.map((item) => ({- date: item.date,- current: item[title.key],- previous: item[`prev_${title.key}`],- }))}- active={metric === index}- isLoading={overviewQuery.isLoading}- inverted={title.inverted}- />- ))}-- <div- className={cn(- 'col-span-4 min-h-16 flex-1 p-4 pb-0 shadow-[0_0_0_0.5px] shadow-border max-md:row-start-1 md:col-span-1',- )}- >- <OverviewLiveHistogram projectId={projectId} shareId={shareId} />- </div>- </div>+ <div className="relative -top-0.5 col-span-6 mt-0 mb-0 md:m-0">+ <div className="card mb-2 grid grid-cols-2 overflow-hidden rounded-md md:grid-cols-4">+ {TITLES.map((title, index) => (+ <OverviewMetricCard+ active={metric === index}+ data={data.map((item) => ({+ date: item.date,+ current: item[title.key],+ previous: item[`prev_${title.key}`],+ }))}+ id={title.key}+ interval={interval}+ inverted={title.inverted}+ isLoading={overviewQuery.isLoading}+ key={title.key}+ label={title.title}+ metric={{+ current: overviewQuery.data?.metrics[title.key] ?? 0,+ previous: overviewQuery.data?.metrics[`prev_${title.key}`],+ }}+ onClick={() => setMetric(index)}+ range={range}+ unit={title.unit}+ />+ ))}++ <OverviewLiveHistogram projectId={projectId} shareId={shareId} />+ </div>- <div className="card p-4">- <div className="flex items-center justify-between mb-3 -mt-1">- <div className="text-sm font-medium text-muted-foreground">- {activeMetric.title}- </div>+ <div className="card p-4">+ <div className="-mt-1 flex items-center justify-between">+ <div className="font-medium text-muted-foreground text-sm">+ {activeMetric.title}</div>- <div className="w-full h-[150px]">- {overviewQuery.isLoading && <Skeleton className="h-full w-full" />}+ {import.meta.env.DEV && (+ <button+ className={cn(+ 'flex items-center gap-1 rounded-md border px-2 py-1 font-medium text-xs transition-colors',+ mockRevenue+ ? 'border-chart-8 bg-chart-8/10 text-chart-8'+ : 'border-border text-muted-foreground hover:bg-def-100'+ )}+ onClick={() => setMockRevenue((p) => !p)}+ title="Toggle mock revenue (dev only)"+ type="button"+ >+ <DollarSignIcon className="size-3" />+ {mockRevenue ? 'Mock revenue on' : 'Mock revenue'}+ </button>+ )}+ </div>+ <div className="h-[190px] w-full">+ {overviewQuery.isLoading && <Skeleton className="h-full w-full" />}+ {!overviewQuery.isLoading && data.length > 0 && (<ChartactiveMetric={activeMetric}- interval={interval}data={data}+ interval={interval}projectId={projectId}/>- </div>+ )}</div></div>- </>+ </div>);}-const { Tooltip, TooltipProvider } = createChartTooltip<- RouterOutputs['overview']['stats']['series'][number],- {- anyMetric?: boolean;- metric: (typeof TITLES)[number];- interval: IInterval;+type SeriesItem = RouterOutputs['overview']['stats']['series'][number];++/**+ * Synthesize plausible-looking revenue (in cents) so we can preview the+ * normalized revenue bars without paying customers. Deterministic per row+ * via a tiny hash so toggling on/off doesn't reshuffle the bars.+ */+function injectMockRevenue(series: SeriesItem[]): SeriesItem[] {+ if (series.length === 0) {+ return series;}->(({ context: { metric, interval, anyMetric }, data: dataArray }) => {- const data = dataArray[0];- const formatDate = useFormatDateInterval({- interval,- short: false,+ return series.map((item, i) => {+ const seed = hashStr(String(item.date)) + i;+ const wave = (Math.sin(seed * 0.7) + 1) / 2; // 0..1+ const jitter = ((seed * 9301 + 49_297) % 233_280) / 233_280; // 0..1+ const revenueCents = Math.round(50_000 + wave * 250_000 + jitter * 80_000);+ const prevCents = Math.round(revenueCents * (0.6 + jitter * 0.6));+ return {+ ...item,+ total_revenue: revenueCents,+ prev_total_revenue: prevCents,+ };});- const number = useNumber();+}- if (!data) {- return null;+function hashStr(s: string): number {+ let h = 0;+ for (let i = 0; i < s.length; i++) {+ h = (h << 5) - h + s.charCodeAt(i);+ h |= 0;}+ return Math.abs(h);+}- const revenue = data.total_revenue ?? 0;- const prevRevenue = data.prev_total_revenue ?? 0;-- return (- <>- <div className="flex justify-between gap-8 text-muted-foreground">- <div>{formatDate(new Date(data.date))}</div>- </div>- <React.Fragment>- <div className="flex gap-2">- <div- className="w-[3px] rounded-full"- style={{ background: anyMetric ? getChartColor(0) : '#3ba974' }}- />- <div className="col flex-1 gap-1">- <div className="flex items-center gap-1">{metric.title}</div>- <div className="flex justify-between gap-8 font-mono font-medium">- <div className="row gap-1">- {metric.unit === 'currency'- ? number.currency((data[metric.key] ?? 0) / 100)- : number.formatWithUnit(data[metric.key], metric.unit)}- {!!data[`prev_${metric.key}`] && (- <span className="text-muted-foreground">- (- {metric.unit === 'currency'- ? number.currency((data[`prev_${metric.key}`] ?? 0) / 100)- : number.formatWithUnit(- data[`prev_${metric.key}`],- metric.unit,- )}- )- </span>- )}- </div>-- <PreviousDiffIndicatorPure- {...getPreviousMetric(- data[metric.key],- data[`prev_${metric.key}`],- )}- />- </div>- </div>- </div>- {anyMetric && revenue > 0 && (- <div className="flex gap-2 mt-2">- <div- className="w-[3px] rounded-full"- style={{ background: '#3ba974' }}- />- <div className="col flex-1 gap-1">- <div className="flex items-center gap-1">Revenue</div>- <div className="flex justify-between gap-8 font-mono font-medium">- <div className="row gap-1">- {number.currency(revenue / 100)}- {prevRevenue > 0 && (- <span className="text-muted-foreground">- ({number.currency(prevRevenue / 100)})- </span>- )}- </div>- {prevRevenue > 0 && (- <PreviousDiffIndicatorPure- {...getPreviousMetric(revenue, prevRevenue)}- />- )}- </div>- </div>- </div>- )}- </React.Fragment>- </>- );-});+type ChartPoint = SeriesItem & {+ /** Normalized revenue so bars share the primary metric's Y domain. */+ revenue_norm?: number;+};function Chart({activeMetric,@@ -270,19 +225,13 @@ function Chart({}: {activeMetric: (typeof TITLES)[number];interval: IInterval;- data: RouterOutputs['overview']['stats']['series'];+ data: SeriesItem[];projectId: string;}) {- const xAxisProps = useXAxisProps({ interval });- const yAxisProps = useYAxisProps();- const number = useNumber();- const revenueYAxisProps = useYAxisProps({- tickFormatter: (value) => number.short(value / 100),- });- const [activeBar, setActiveBar] = useState(-1);const { range, startDate, endDate } = useOverviewOptions();-const trpc = useTRPC();+ const isRevenueTab = activeMetric.key === 'total_revenue';+const references = useQuery(trpc.reference.getChartReferences.queryOptions({@@ -291,334 +240,211 @@ function Chart({endDate,range,},+ { staleTime: 1000 * 60 * 10 }+ )+ );++ const [filters, setFilter] = useEventQueryFilters();+ const referrerSpikes = useQuery(+ trpc.overview.getReferrerSpikes.queryOptions({- staleTime: 1000 * 60 * 10,+ projectId,+ startDate,+ endDate,+ range,+ interval,+ filters,},- ),+ { staleTime: 1000 * 60 * 10 }+ )+ );+ // Click a spike's favicon → drop a referrer_name filter on the chart.+ // The query above already includes `filters`, so the chart re-fetches+ // with the new filter applied (which also re-computes spike detection+ // within that filtered slice).+ const handleSpikeClick = useCallback(+ (referrerName: string) => {+ setFilter('referrer_name', referrerName);+ },+ [setFilter]+ );+ // Flatten clusters → individual spikes for the tooltip's bucket-match+ // lookup. The chart marker layer keeps the cluster shape (one marker per+ // cluster); the tooltip works at spike granularity so any hovered bucket+ // can surface its spike, even one that's not the cluster's anchor.+ const flatSpikes = useMemo(+ () => referrerSpikes.data?.flatMap((c) => c.spikes) ?? null,+ [referrerSpikes.data]);- // Line chart specific logic- let dotIndex = undefined;- if (interval === 'hour') {- // Find closest index based on times- dotIndex = data.findIndex((item) => {- return isSameHour(item.date, new Date());- });- }-- const { calcStrokeDasharray, handleAnimationEnd, getStrokeDasharray } =- useDashedStroke({- dotIndex,- });-- const lastSerieDataItem = last(data)?.date || new Date();- const useDashedLastLine = (() => {- if (range === 'today') {- return true;- }-- if (interval === 'hour') {- return isSameHour(lastSerieDataItem, new Date());- }-- if (interval === 'day') {- return isSameDay(lastSerieDataItem, new Date());+ const { chartData, showRevenue } = useMemo(() => {+ if (isRevenueTab) {+ return {+ chartData: data as ChartPoint[],+ showRevenue: false,+ };}- if (interval === 'month') {- return isSameMonth(lastSerieDataItem, new Date());+ let maxPrimary = 0;+ let maxRevenue = 0;+ for (const item of data) {+ const primary = (item[activeMetric.key] as number | undefined) ?? 0;+ const revenue = (item.total_revenue as number | undefined) ?? 0;+ if (primary > maxPrimary) {+ maxPrimary = primary;+ }+ if (revenue > maxRevenue) {+ maxRevenue = revenue;+ }}- if (interval === 'week') {- return isSameWeek(lastSerieDataItem, new Date());+ if (maxRevenue === 0 || maxPrimary === 0) {+ return {+ chartData: data as ChartPoint[],+ showRevenue: false,+ };}- return false;- })();-- if (activeMetric.key === 'total_revenue') {- return (- <TooltipProvider metric={activeMetric} interval={interval}>- <ResponsiveContainer width="100%" height="100%">- <ComposedChart data={data}>- <Customized component={calcStrokeDasharray} />- <Line- dataKey="calcStrokeDasharray"- legendType="none"- animationDuration={0}- onAnimationEnd={handleAnimationEnd}- />- <Tooltip />- <YAxis {...yAxisProps} width={25} />- <XAxis {...xAxisProps} />- <CartesianGrid- strokeDasharray="3 3"- horizontal={true}- vertical={false}- className="stroke-border"- />-- <defs>- <filter- id="rainbow-line-glow"- x="-20%"- y="-20%"- width="140%"- height="140%"- >- <feGaussianBlur stdDeviation="5" result="blur" />- <feComponentTransfer in="blur" result="dimmedBlur">- <feFuncA type="linear" slope="0.5" />- </feComponentTransfer>- <feComposite- in="SourceGraphic"- in2="dimmedBlur"- operator="over"- />- </filter>- </defs>-- <Line- key={'prev_total_revenue'}- type="monotone"- dataKey={'prev_total_revenue'}- stroke={'oklch(from var(--foreground) l c h / 0.1)'}- strokeWidth={2}- isAnimationActive={false}- dot={- data.length > 90- ? false- : {- stroke: 'oklch(from var(--foreground) l c h / 0.1)',- fill: 'transparent',- strokeWidth: 1.5,- r: 2,- }- }- activeDot={{- stroke: 'oklch(from var(--foreground) l c h / 0.2)',- fill: 'transparent',- strokeWidth: 1.5,- r: 3,- }}- />-- <Area- key={'total_revenue'}- type="monotone"- dataKey={'total_revenue'}- stroke={'#3ba974'}- fill={'#3ba974'}- fillOpacity={0.05}- strokeWidth={2}- strokeDasharray={- useDashedLastLine- ? getStrokeDasharray(activeMetric.key)- : undefined- }- isAnimationActive={false}- dot={- data.length > 90- ? false- : {- stroke: '#3ba974',- fill: '#3ba974',- strokeWidth: 1.5,- r: 3,- }- }- activeDot={{- stroke: '#3ba974',- fill: 'var(--def-100)',- strokeWidth: 2,- r: 4,- }}- filter="url(#rainbow-line-glow)"- />-- {references.data?.map((ref) => (- <ReferenceLine- key={ref.id}- x={ref.date.getTime()}- stroke={'oklch(from var(--foreground) l c h / 0.1)'}- strokeDasharray={'3 3'}- label={{- value: ref.title,- position: 'centerTop',- fill: '#334155',- fontSize: 12,- }}- fontSize={10}- />- ))}- </ComposedChart>- </ResponsiveContainer>- </TooltipProvider>- );- }+ // Pin revenue peak at ~60% of the primary metric's peak so bars stay+ // legible without overshadowing the line/area.+ const scale = (maxPrimary * 0.4) / maxRevenue;+ return {+ chartData: data.map((item) => ({+ ...item,+ revenue_norm: ((item.total_revenue as number | undefined) ?? 0) * scale,+ })) as ChartPoint[],+ showRevenue: true,+ };+ }, [data, activeMetric.key, isRevenueTab]);++ const dashFromIndex = useDashedTail({ data, range, interval });+ const primaryColor = isRevenueTab ? REVENUE_COLOR : getChartColor(0);return (- <TooltipProvider metric={activeMetric} interval={interval} anyMetric={true}>- <ResponsiveContainer width="100%" height="100%">- <ComposedChart- data={data}- onMouseMove={(e) => {- setActiveBar(e.activeTooltipIndex ?? -1);- }}- >- <Customized component={calcStrokeDasharray} />- <Line- dataKey="calcStrokeDasharray"- legendType="none"- animationDuration={0}- onAnimationEnd={handleAnimationEnd}- />- <Tooltip />- <YAxis- {...yAxisProps}- domain={[- 0,- activeMetric.key === 'bounce_rate'- ? 100- : (dataMax: number) => Math.max(dataMax, 1),- ]}- width={25}- />- <YAxis- {...revenueYAxisProps}- yAxisId="right"- orientation="right"- domain={[- 0,- Math.max(- data.reduce(- (max, item) => Math.max(max, item.total_revenue ?? 0),- 0,- ) * 1.2,- 1,- ),- ]}- width={30}- allowDataOverflow={false}- />- <XAxis {...xAxisProps} padding={{ left: 10, right: 10 }} />-- <CartesianGrid- strokeDasharray="3 3"- horizontal={true}- vertical={false}- className="stroke-border"- />-- <defs>- <filter- id="rainbow-line-glow"- x="-20%"- y="-20%"- width="140%"- height="140%"- >- <feGaussianBlur stdDeviation="5" result="blur" />- <feComponentTransfer in="blur" result="dimmedBlur">- <feFuncA type="linear" slope="0.5" />- </feComponentTransfer>- <feComposite- in="SourceGraphic"- in2="dimmedBlur"- operator="over"- />- </filter>- </defs>-- <Line- key={`prev_${activeMetric.key}`}- type="monotone"- dataKey={`prev_${activeMetric.key}`}- stroke={'oklch(from var(--foreground) l c h / 0.1)'}- strokeWidth={2}- isAnimationActive={false}- dot={false}- activeDot={{- stroke: 'oklch(from var(--foreground) l c h / 0.2)',- fill: 'var(--def-100)',- fillOpacity: 1,- strokeWidth: 1.5,- r: 3,- }}- />- <Bar- key="total_revenue"- dataKey="total_revenue"- yAxisId="right"- stackId="revenue"- isAnimationActive={false}- radius={5}- maxBarSize={20}- >- {data.map((item, index) => {- return (- <Cell- key={item.date}- className={cn(- index === activeBar- ? 'fill-emerald-700/100'- : 'fill-emerald-700/80',- )}- />- );- })}- </Bar>- <Area- key={activeMetric.key}- type="monotone"- dataKey={activeMetric.key}- stroke={getChartColor(0)}- fill={getChartColor(0)}- fillOpacity={0.05}- strokeWidth={2}- strokeDasharray={- useDashedLastLine- ? getStrokeDasharray(activeMetric.key)- : undefined+ <ComposedChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-full"+ data={chartData}+ margin={{ top: 0, right: 20, bottom: 40, left: 20 }}+ xDataKey="date"+ >+ <Grid horizontal />+ <YAxis numTicks={4} />+ <XAxis />++ <Area+ animate={false}+ dashArray="4,4"+ dashFromIndex={dashFromIndex}+ dataKey={activeMetric.key}+ fadeEdges="left"+ fill={primaryColor}+ fillOpacity={0.18}+ gradientToOpacity={0}+ key={activeMetric.key}+ stroke={primaryColor}+ strokeWidth={2}+ />++ <Line+ curve={curveMonotoneX}+ dataKey={`prev_${activeMetric.key}`}+ fadeEdges+ key={`prev-${activeMetric.key}`}+ stroke={PREV_LINE_COLOR}+ strokeWidth={2}+ />++ {showRevenue && (+ <Line+ curve={curveMonotoneX}+ dataKey="revenue_norm"+ fadeEdges+ stroke={REVENUE_COLOR}+ strokeWidth={1.5}+ />+ )}++ <OPDatePill interval={interval} />+ <OPSeriesDots+ dots={[+ { dataKey: activeMetric.key, color: primaryColor },+ { dataKey: `prev_${activeMetric.key}`, color: 'var(--foreground)' },+ ...(showRevenue+ ? [+ {+ dataKey: 'revenue_norm',+ color: REVENUE_COLOR,+ label: '$',+ },+ ]+ : []),+ ]}+ />++ <OPChartTooltip<ChartPoint>+ indicatorColor={primaryColor}+ interval={interval}+ references={references.data}+ rows={(point) => {+ const primaryVal = point[activeMetric.key] as number | undefined;+ const primaryPrev = point[`prev_${activeMetric.key}`] as+ | number+ | undefined;++ const rows = [+ {+ color: primaryColor,+ label: activeMetric.title,+ value: primaryVal,+ previous: primaryPrev,+ inverted: activeMetric.inverted,+ unit: tooltipUnitFor(activeMetric.unit),+ },+ ];++ if (!isRevenueTab) {+ const revenue = (point.total_revenue as number | undefined) ?? 0;+ const prevRevenue =+ (point.prev_total_revenue as number | undefined) ?? 0;+ if (revenue > 0) {+ rows.push({+ color: REVENUE_COLOR,+ label: 'Revenue',+ value: revenue,+ previous: prevRevenue > 0 ? prevRevenue : undefined,+ inverted: false,+ unit: 'currency',+ });}- isAnimationActive={false}- dot={- data.length > 90- ? false- : {- stroke: getChartColor(0),- fill: 'var(--def-100)',- fillOpacity: 1,- strokeWidth: 1.5,- r: 3,- }- }- activeDot={{- stroke: getChartColor(0),- fill: 'var(--def-100)',- strokeWidth: 2,- r: 4,- }}- filter="url(#rainbow-line-glow)"- />-- {references.data?.map((ref) => (- <ReferenceLine- key={ref.id}- x={ref.date.getTime()}- stroke={'oklch(from var(--foreground) l c h / 0.1)'}- strokeDasharray={'3 3'}- label={{- value: ref.title,- position: 'centerTop',- fill: '#334155',- fontSize: 12,- }}- fontSize={10}- />- ))}- </ComposedChart>- </ResponsiveContainer>- </TooltipProvider>+ }++ return rows;+ }}+ showDatePill={false}+ showDots={false}+ spikes={flatSpikes}+ />++ <OPReferences items={references.data} />+ <OPReferrerSpikes+ items={referrerSpikes.data}+ onSpikeClick={handleSpikeClick}+ />+ </ComposedChart>);}++function tooltipUnitFor(unit: (typeof TITLES)[number]['unit']) {+ if (unit === 'currency') {+ return 'currency' as const;+ }+ if (unit === 'min') {+ return 'min' as const;+ }+ if (unit === '%') {+ return 'pct' as const;+ }+ return undefined;+}diff --git a/apps/start/src/components/overview/overview-top-devices.tsx b/apps/start/src/components/overview/overview-top-devices.tsxindex a9d3e7f7f..9605a63d4 100644--- a/apps/start/src/components/overview/overview-top-devices.tsx+++ b/apps/start/src/components/overview/overview-top-devices.tsx@@ -388,6 +388,7 @@ export default function OverviewTopDevices({<OverviewLineChartdata={seriesQuery.data}interval={interval}+ range={range}searchQuery={searchQuery}/>) : (diff --git a/apps/start/src/components/overview/overview-top-geo.tsx b/apps/start/src/components/overview/overview-top-geo.tsxindex a08d8556b..eb2409e15 100644--- a/apps/start/src/components/overview/overview-top-geo.tsx+++ b/apps/start/src/components/overview/overview-top-geo.tsx@@ -134,6 +134,7 @@ export default function OverviewTopGeo({<OverviewLineChartdata={seriesQuery.data}interval={interval}+ range={range}searchQuery={searchQuery}/>) : (diff --git a/apps/start/src/components/overview/overview-top-sources.tsx b/apps/start/src/components/overview/overview-top-sources.tsxindex 41a498b9e..4c8513814 100644--- a/apps/start/src/components/overview/overview-top-sources.tsx+++ b/apps/start/src/components/overview/overview-top-sources.tsx@@ -134,6 +134,7 @@ export default function OverviewTopSources({<OverviewLineChartdata={seriesQuery.data}interval={interval}+ range={range}searchQuery={searchQuery}/>) : (diff --git a/apps/start/src/components/report-chart/common/serie-icon.tsx b/apps/start/src/components/report-chart/common/serie-icon.tsxindex 85b67dcaa..043285960 100644--- a/apps/start/src/components/report-chart/common/serie-icon.tsx+++ b/apps/start/src/components/report-chart/common/serie-icon.tsx@@ -27,8 +27,15 @@ import iconsWithUrls from './serie-icon.urls';// Types// ============================================================================-type SerieIconProps = Omit<LucideProps, 'name'> & {+type SerieIconProps = Omit<LucideProps, 'name' | 'fill'> & {name?: string | string[];+ /**+ * When true, render the icon at the size of its parent container instead+ * of the default max-h-4 cap. Use for circular/full-bleed contexts like+ * chart markers where the favicon should fill the surrounding circle.+ * Overrides Lucide's `fill` prop semantics for this component.+ */+ fill?: boolean;};type IconType = 'lucide' | 'image' | 'flag';@@ -279,15 +286,24 @@ function resolveIcon(name: string): ResolvedIcon {return null;}-function IconWrapper({ children }: { children: React.ReactNode }) {+function IconWrapper({+ children,+ fill,+}: { children: React.ReactNode; fill?: boolean }) {return (- <div className={'relative max-h-4 flex-shrink-0 [&_svg]:!rounded-[2px]'}>+ <div+ className={+ fill+ ? 'relative size-full flex-shrink-0 [&_svg]:!rounded-[2px]'+ : 'relative max-h-4 flex-shrink-0 [&_svg]:!rounded-[2px]'+ }+ >{children}</div>);}-function ImageIcon({ url }: { url: string }) {+function ImageIcon({ url, fill }: { url: string; fill?: boolean }) {const context = useAppContext();const [hasError, setHasError] = useState(false);@@ -298,11 +314,15 @@ function ImageIcon({ url }: { url: string }) {const fullUrl = context.apiUrl?.replace(/\/$/, '') + url;return (- <IconWrapper>+ <IconWrapper fill={fill}><imgsrc={fullUrl}alt=""- className="w-full max-h-4 rounded-[2px] object-contain"+ className={+ fill+ ? 'size-full rounded-full object-cover'+ : 'w-full max-h-4 rounded-[2px] object-contain'+ }loading="lazy"decoding="async"onError={() => setHasError(true)}@@ -311,11 +331,15 @@ function ImageIcon({ url }: { url: string }) {);}-function FlagIcon({ code }: { code: string }) {+function FlagIcon({ code, fill }: { code: string; fill?: boolean }) {return (- <IconWrapper>+ <IconWrapper fill={fill}><span- className={`fi !block aspect-[1.33] overflow-hidden rounded-[2px] fi-${code}`}+ className={+ fill+ ? `fi !block size-full overflow-hidden rounded-full fi-${code}`+ : `fi !block aspect-[1.33] overflow-hidden rounded-[2px] fi-${code}`+ }/></IconWrapper>);@@ -323,18 +347,22 @@ function FlagIcon({ code }: { code: string }) {function LucideIconWrapper({Icon,+ fill,...props-}: { Icon: React.ComponentType<LucideProps> } & LucideProps) {+}: {+ Icon: React.ComponentType<LucideProps>;+ fill?: boolean;+} & Omit<LucideProps, 'fill'>) {return (- <IconWrapper>- <Icon size={16} {...props} />+ <IconWrapper fill={fill}>+ <Icon size={fill ? undefined : 16} {...props} /></IconWrapper>);}// Main component-export function SerieIcon({ name: names, ...props }: SerieIconProps) {+export function SerieIcon({ name: names, fill, ...props }: SerieIconProps) {const name = Array.isArray(names) ? names[0] : names;if (!name) {@@ -349,10 +377,10 @@ export function SerieIcon({ name: names, ...props }: SerieIconProps) {switch (resolved.type) {case 'lucide':- return <LucideIconWrapper Icon={resolved.Icon} {...props} />;+ return <LucideIconWrapper Icon={resolved.Icon} fill={fill} {...props} />;case 'image':- return <ImageIcon url={resolved.url} />;+ return <ImageIcon url={resolved.url} fill={fill} />;case 'flag':- return <FlagIcon code={resolved.code} />;+ return <FlagIcon code={resolved.code} fill={fill} />;}}diff --git a/apps/start/src/lib/utils.ts b/apps/start/src/lib/utils.tsindex 9ad0df426..365058ceb 100644--- a/apps/start/src/lib/utils.ts+++ b/apps/start/src/lib/utils.ts@@ -1,5 +1,5 @@-import { type ClassValue, clsx } from 'clsx';-import { twMerge } from 'tailwind-merge';+import { type ClassValue, clsx } from "clsx";+import { twMerge } from "tailwind-merge";export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs));diff --git a/apps/start/src/styles.css b/apps/start/src/styles.cssindex 85a64b470..2b5731eea 100644--- a/apps/start/src/styles.css+++ b/apps/start/src/styles.css@@ -21,13 +21,13 @@ code {:root {/* Core colors converted from HSL to OKLCH using convert-to-oklch tool */--highlight: oklch(55.1% 0.21 262); /* hsl(220, 84%, 53%) -> #2266ec */-+/* def- color scale converted from HSL to OKLCH */--def-100: oklch(98.4% 0 248); /* hsl(210, 40%, 98%) -> #F0F4F9 */--def-200: oklch(96.8% 0 248); /* hsl(210, 40%, 96.1%) -> #E7ECF2 */--def-300: oklch(91.7% 0 248); /* hsl(210, 15.14%, 89.41%) -> #DDE3E9 */--def-400: oklch(80.3% 0 248); /* hsl(210, 9.08%, 75.05%) -> #B3BDC7 */-+/* foregroundish converted from HSL to OKLCH */--foregroundish: oklch(34.4% 0 273); /* hsl(226.49, 3.06%, 22.62%) */@@ -50,7 +50,7 @@ code {--border: oklch(92.9% 0.01 256); /* hsl(214.3, 31.8%, 91.4%) -> #E8EBF1 */--input: oklch(92.9% 0.01 256); /* hsl(214.3, 31.8%, 91.4%) -> #E8EBF1 */--ring: oklch(86.9% 0.02 253); /* hsl(212.73, 26.83%, 83.92%) -> #CDD6E2 */-+/* Chart colors converted to OKLCH for consistency */--chart-0: oklch(54.6% 0.22 263); /* #2563EB */--chart-1: oklch(72.2% 0.17 33.7); /* #ff7557 */@@ -65,20 +65,47 @@ code {--chart-10: oklch(71.1% 0.15 320); /* #cb80dc */--chart-11: oklch(72.1% 0.09 188); /* #5cb7af */--chart-12: oklch(58.7% 0.24 286); /* #7856ff */-+--radius: 0.5rem;++ /* Bklit chart tokens — single-series defaults pick OpenPanel brand palette.+ We deliberately do NOT redefine --chart-1..5 (OpenPanel uses them as a 13-color+ fixed palette via --chart-0..12); for multi-series charts we always pass+ explicit colors via getChartColor(i). */+ --chart-background: var(--card);+ --chart-foreground: var(--foreground);+ --chart-foreground-muted: var(--muted-foreground);+ --chart-line-primary: var(--chart-0);+ --chart-line-secondary: var(--chart-1);+ --chart-crosshair: oklch(from var(--foreground) l c h / 0.4);+ --chart-grid: var(--border);+ /* Outer tooltip box is transparent — OPTooltipCard owns the visible card. */+ --chart-tooltip-background: transparent;+ --chart-tooltip-foreground: var(--background);+ --chart-tooltip-muted: oklch(from var(--background) l c h / 0.6);+ --chart-marker-background: var(--def-100);+ --chart-marker-border: var(--border);+ --chart-marker-foreground: var(--foreground);+ /* Notification-pill style: high-contrast against the marker circle. Auto-+ adapts to light/dark via the foreground/background tokens. Without+ these the SVG <circle> / <text> in MarkerGroup fall back to black on+ black and the count badge renders as a black dot. */+ --chart-marker-badge-background: var(--foreground);+ --chart-marker-badge-foreground: var(--background);+ --chart-ring-background: oklch(from var(--foreground) l c h / 0.12);+ --chart-label: var(--muted-foreground);}.dark {/* Core colors converted from HSL to OKLCH for dark mode using convert-to-oklch tool */--highlight: oklch(61.3% 0.21 263); /* hsl(221.44, 100%, 62.04%) */-+/* def- color scale converted from HSL to OKLCH for dark mode */--def-100: oklch(19.3% 0 0); /* hsl(0, 0%, 8%) -> #0f0f0f */--def-200: oklch(25% 0 0); /* hsl(0, 0%, 13.12%) -> #212121 */--def-300: oklch(27.1% 0 0); /* hsl(0, 0%, 15.1%) -> #262626 */--def-400: oklch(37.3% 0 0); /* hsl(0, 0%, 25.23%) -> #404040 */-+--foregroundish: oklch(83.9% 0 0); /* hsl(0, 0%, 79.23%) */--background: oklch(23.8% 0 0); /* hsl(0, 0%, 12.02%) -> #1e1e1e */@@ -100,6 +127,27 @@ code {--border: oklch(27.1% 0 0); /* hsl(0, 0%, 15.1%) -> #262626 */--input: oklch(27.1% 0 0); /* hsl(0, 0%, 15.1%) -> #262626 */--ring: oklch(87.6% 0 0); /* hsl(0, 0%, 83.9%) -> #d6d6d6 */++ /* Bklit chart tokens (dark) — OpenPanel chart palette (--chart-0..12) stays+ theme-agnostic and is defined in :root only, so we do NOT redefine it here. */+ --chart-tooltip-background: transparent;+ --chart-tooltip-foreground: var(--background);+ --chart-tooltip-muted: oklch(from var(--background) l c h / 0.6);+ --chart-1: oklch(1 0 none);+ --chart-2: oklch(0.73 0 none);+ --chart-3: oklch(0.51 0 none);+ --chart-4: oklch(0.39 0 none);+ --chart-5: oklch(0.32 0 none);+ --chart-background: oklch(0.145 0 0);+ --chart-foreground: oklch(0.45 0 0);+ --chart-foreground-muted: oklch(0.65 0.01 260);+ --chart-crosshair: oklch(0.45 0 0);+ --chart-grid: oklch(0.25 0 0);+ --chart-marker-background: oklch(0.25 0.01 260);+ --chart-marker-border: oklch(0.4 0.01 260);+ --chart-marker-foreground: oklch(0.9 0 0);+ --chart-ring-background: oklch(0.35 0.01 260 / 0.25);+ --chart-label: oklch(0.75 0.01 260);}@theme {@@ -151,7 +199,7 @@ code {--color-border: var(--border);--color-input: var(--input);--color-ring: var(--ring);-+/* Extended chart colors */--color-chart-0: var(--chart-0);--color-chart-1: var(--chart-1);@@ -166,23 +214,23 @@ code {--color-chart-10: var(--chart-10);--color-chart-11: var(--chart-11);--color-chart-12: var(--chart-12);-+/* Additional colors */--color-highlight: var(--highlight);--color-foregroundish: var(--foregroundish);-+/* def color scale - properly defined for all variants */--color-def-100: var(--def-100);--color-def-200: var(--def-200);--color-def-300: var(--def-300);--color-def-400: var(--def-400);-+/* Radius variables */--radius-sm: calc(var(--radius) - 4px);--radius-md: calc(var(--radius) - 2px);--radius-lg: var(--radius);--radius-xl: calc(var(--radius) + 4px);-+/* Sidebar colors */--color-sidebar: var(--sidebar);--color-sidebar-foreground: var(--sidebar-foreground);@@ -234,7 +282,7 @@ code {.subtitle {@apply text-base font-medium;}-+.card {@apply rounded-md border border-border bg-card;}@@ -272,7 +320,6 @@ button {@apply cursor-pointer;}-.hide-scrollbar::-webkit-scrollbar {display: none;}@@ -452,4 +499,27 @@ button {animation: sticky-shadow linear both;animation-timeline: scroll();animation-range: 0 1px;+}++@theme inline {+ --color-chart-1: var(----chart-1);+ --color-chart-2: var(----chart-2);+ --color-chart-3: var(----chart-3);+ --color-chart-4: var(----chart-4);+ --color-chart-5: var(----chart-5);+ --color-chart-background: var(----chart-background);+ --color-chart-foreground: var(----chart-foreground);+ --color-chart-foreground-muted: var(----chart-foreground-muted);+ --chart-line-primary: var(----chart-line-primary);+ --chart-line-secondary: var(----chart-line-secondary);+ --color-chart-crosshair: var(----chart-crosshair);+ --color-chart-grid: var(----chart-grid);+ --color-chart-tooltip-background: var(----chart-tooltip-background);+ --color-chart-tooltip-foreground: var(----chart-tooltip-foreground);+ --color-chart-tooltip-muted: var(----chart-tooltip-muted);+ --color-chart-marker-background: var(----chart-marker-background);+ --color-chart-marker-border: var(----chart-marker-border);+ --color-chart-marker-foreground: var(----chart-marker-foreground);+ --color-chart-ring-background: var(----chart-ring-background);+ --color-chart-label: var(----chart-label);}\ No newline at end of filediff --git a/bklit-issues.md b/bklit-issues.mdnew file mode 100644index 000000000..2d94e085a--- /dev/null+++ b/bklit-issues.md@@ -0,0 +1,565 @@+# bklit-ui Issues & Patches++Tracking upstream bugs in `@bklitui/ui` (https://ui.bklit.com / `/Users/lindesvard/Projects/bklit-ui`) that we have patched locally after `shadcn add`. Re-running `shadcn add` will regress these fixes — re-apply from this file.++---++## 1. `require("react-dom")` breaks under Vite / ESM bundlers++**Symptom**++```+ReferenceError: require is not defined+ at ChartTooltip (chart-tooltip.tsx:146:28)+```++Thrown at runtime in the browser. The chart renders blank or unmounts.++**Cause**++Six chart components dodge SSR by lazily resolving `createPortal` with CommonJS:++```ts+// Dynamic import to avoid SSR issues+const { createPortal } = require("react-dom") as typeof import("react-dom");+```++This works under Next.js (which polyfills CommonJS in client chunks) but fails under Vite / TanStack Start where browser code stays pure ESM. The lazy resolution isn't even needed — every call site is already guarded by a `mounted` state that flips `true` only inside `useEffect`, so `createPortal` only runs on the client.++**Affected files** (in `apps/start/src/components/charts/`)++- `tooltip/chart-tooltip.tsx`+- `tooltip/tooltip-box.tsx`+- `x-axis.tsx`+- `y-axis.tsx`+- `bar-x-axis.tsx`+- `bar-y-axis.tsx`++**Fix**++Replace the lazy `require` with a top-level static import:++```ts+import { createPortal } from "react-dom";+```++…and delete the inline `const { createPortal } = require(...)` line just before each `createPortal(...)` call. The existing `mounted && container` guard above the call site already prevents SSR execution.++**Upstream**++Present in both the live registry (`https://ui.bklit.com/r/*.json`) and the local source (`/Users/lindesvard/Projects/bklit-ui/packages/ui/src/charts/`). Worth filing / PR'ing upstream.++---++## 2. Registry lags the local `bklit-ui` source++The shadcn registry build at `apps/web/public/r/*.json` is missing newer features (e.g. `dashFromIndex` on `<Line>` / `<Area>`, `<SeriesMarkers>`, `<SeriesDashTailOverlay>`, etc.) that exist in `packages/ui/src/charts/`. We synced these by hand:++- `path-stroke-utils.ts`+- `dash-tail-stroke.tsx`+- `series-dash-tail-overlay.tsx`+- `series-markers.tsx`+- `series-point-marker.tsx`+- `area-gradient-defs.tsx`+- `use-line-segment-highlight.ts`+- `use-area-segment-highlight.ts`+- newer `area.tsx`, `line.tsx`++Until the registry is rebuilt, re-running `shadcn add line-chart` (or similar) will overwrite our patched copies with the older versions and drop these helpers. Sync from local source after each re-install.++---++## 3. `chart-context` cssVars overwrite OpenPanel palette in `.dark`++When `shadcn add` injects the `chart-context` registry item, it appends bklit's grayscale `--chart-1` … `--chart-5` overrides into the `.dark { ... }` block in `styles.css`. OpenPanel's existing palette (`--chart-0` … `--chart-12` defined in `:root` only) is intentionally theme-agnostic; the bklit overrides turn `bg-chart-1`, `text-chart-2`, etc. gray in dark mode across the rest of the app (`billing-usage.tsx`, `__root.tsx`, `report-chart/common/loading.tsx`).++The injection also collapses onto a single line, mangling the `.dark` block formatting.++**Fix**++After re-installing, manually remove the appended `--chart-1..5`, `--chart-background`, `--chart-foreground`, `--chart-grid`, `--chart-crosshair`, `--chart-marker-*`, `--chart-ring-background`, `--chart-label`, `--chart-foreground-muted` lines from `.dark`. Keep only:++```css+--chart-tooltip-background: oklch(from var(--foreground) l c h / 0.92);+--chart-tooltip-foreground: var(--background);+--chart-tooltip-muted: oklch(from var(--background) l c h / 0.6);+```++OpenPanel's bklit tokens in `:root` map back to existing vars so a single `:root` block is enough — see the head of `apps/start/src/styles.css`.++---++## 4. No dual Y-axis (`<ComposedChart>` is single-scale)++Bklit's `ComposedChart` (and every other cartesian shell) computes a single linear Y scale from `max(all series values)`. There is no `yAxisId` / `orientation="right"` equivalent — you cannot mount a second axis with a different domain.++This is a regression vs. recharts, which we relied on in `overview-metrics.tsx` to plot revenue (in cents, e.g. 0–5,000,000) alongside a primary metric (e.g. unique visitors, 0–1,000) on the same chart.++**Workaround in this codebase**++`overview-metrics.tsx` pre-scales `total_revenue` into a derived `revenue_norm` field so the bars share the primary metric's Y domain:++```ts+const scale = (maxPrimary * 0.6) / maxRevenue;+chartData = data.map((item) => ({+ ...item,+ revenue_norm: (item.total_revenue ?? 0) * scale,+}));+```++Bars render at `revenue_norm`; the tooltip shows the real `total_revenue` formatted as currency. Bar height is relative/lossy but visually fits the line/area without dominating.++**Alternatives** if normalization isn't acceptable for a future chart:++- Two stacked bklit charts sharing the X domain (height-split, one per scale).+- Render revenue in a separate widget below the primary chart.+- Patch `composed-chart.tsx` / `time-series-chart-shell.tsx` to accept a second `yScale` (non-trivial — would need a new axis component, new context fields, and changes to tooltip positioning).++---++## 5. X-axis ticks don't line up with data points (default `tickMode="domain"`)++`<XAxis>` defaults to `tickMode="domain"`, which places `numTicks` (default 5) evenly spaced labels across the time domain. Those positions are computed from `xScale.domain()`, not from the actual data points — so the labels rarely coincide with a real tick on the chart. For sparse / non-uniform data (monthly bars, irregular event days) this looks visually off: a label sitting between two bars, or in the middle of a gap.++**Fix**++Pass `tickMode="data"` on the `<XAxis>`:++```tsx+<XAxis tickMode="data" />+```++This emits one label per data row at the row's x position. Matches the recharts behavior we replaced and is the right default for almost every OpenPanel chart.++Not yet applied — should be retrofitted onto `overview-metrics.tsx` and `overview-line-chart.tsx`, and made the default for any new chart.++---++## 6. `<ChartMarkers>` get clipped by the chart `<svg>`++Bklit's `MarkerGroup` renders as SVG (`<g transform="translate(x, y)">`) inside the chart's own `<svg>`, **not** as an HTML portal. With marker `y=-8` and `size=24`, the circle's top edge sits at SVG y = `margin.top - 20`. Anything less than `margin.top: 20` clips the marker.++Bumping `margin.top` works but introduces dead headroom on charts that don't have references on every render.++**Fix (applied)**++Patched both chart shells to render their `<svg>` with `overflow: visible`:++- `apps/start/src/components/charts/time-series-chart-shell.tsx`+- `apps/start/src/components/charts/bar-chart.tsx`++```tsx+<svg aria-hidden="true" height={height} width={width} style={{ overflow: 'visible' }}>+```++With this, markers can render above the chart's bounding box without clipping, regardless of `margin.top`. Restored `margin.top: 16` in `overview-metrics.tsx` so the chart isn't visually top-heavy.++Re-running `shadcn add` will revert these two files.++---++## 7. `<ChartTooltip>` doesn't pick up `<ChartMarkers>` automatically++Bklit's `MarkerTooltipContent` exists, but bklit's `<ChartTooltip>` does not auto-include matched markers — you have to assemble it yourself.++The naive way uses bklit's `useActiveMarkers(markers)` hook. **Don't.** That hook matches by `marker.date.toDateString()`, which is *day*-granular: on an hourly chart every hour of the marker's day shows the reference in the tooltip, even though the visual marker only sits on one hour.++**Fix in OpenPanel**++`<OPChartTooltip>` accepts a `references` prop (same `OPReferenceItem[]` shape as `<OPReferences>`). When set, the tooltip body lists references whose timestamp falls in the bucket of the currently hovered data point — we snap each reference to its nearest data index and compare against `tooltipData.index`, so it works for hourly / minute intervals. See `useReferencesForHoveredPoint` in `apps/start/src/components/charts/op-tooltip.tsx`.++```tsx+<OPChartTooltip+ references={references.data}+ rows={(point) => [...]}+/>+```++Always pass `references` to both `<OPReferences>` (visual marker on the chart) and `<OPChartTooltip>` (text breakdown in the tooltip).++---++## 8. `<Line>` / `<Area>` plot missing values at the chart top (SVG y=0)++bklit's `getY` in both `line.tsx` and `area.tsx`:++```ts+return typeof value === "number" ? (yScale(value) ?? 0) : 0;+```++The fallback `0` is a raw SVG y coordinate, not a data-domain zero. In SVG y=0 is the **top** of the chart, not the baseline — so a series with sparse data (some rows missing `dataKey`) renders the missing points at the ceiling, producing a flat line plastered to the top of the chart.++**Symptom:** in `OverviewLineChart`, hovering at a date where one of the series has no datapoint shows tooltip value `0` for that series, but its hover dot sits at the very top of the chart at Y=max instead of at Y=0.++**Fix (applied locally)** in `apps/start/src/components/charts/line.tsx` and `area.tsx`:++```ts+const getY = useCallback((d) => {+ const value = d[dataKey];+ if (typeof value === "number") {+ return yScale(value) ?? yScale(0) ?? 0;+ }+ return yScale(0) ?? 0;+}, [dataKey, yScale]);+```++`shadcn add` will revert these — re-patch from this file.++---++## 9. Hover springs are tuned slow upstream++Bklit ships hover-related springs that feel sluggish compared to recharts' no-animation defaults — the tooltip box, dot, crosshair, and line/area highlight all visibly ease between data points. OpenPanel charts hover dense time series, so the smoothing reads as lag.++**Files patched to `{ stiffness: 1000, damping: 60 }`** (was 100–300 / 20–30):++- `apps/start/src/components/charts/tooltip/tooltip-box.tsx` (`springConfig`)+- `apps/start/src/components/charts/tooltip/tooltip-dot.tsx` (`crosshairSpringConfig`)+- `apps/start/src/components/charts/tooltip/tooltip-indicator.tsx` (`crosshairSpringConfig`)+- `apps/start/src/components/charts/line.tsx` (highlight `springConfig`)+- `apps/start/src/components/charts/area.tsx` (highlight `springConfig`)++Plus our own `apps/start/src/components/charts/op-date-pill.tsx` (`SPRING`).++`shadcn add` reverts the bklit ones. If hover ever starts feeling laggy again, re-tune these spring constants.++---++## 10. Hover fires `setTooltipData` on every mouse pixel++**Symptom**++Hover over the chart feels sluggish; React DevTools profiler shows the entire chart subtree re-rendering hundreds of times per second during continuous mouse motion.++**Cause**++`use-chart-interaction.ts`'s `handleMouseMove` calls `setTooltipData(resolvedTooltipFromX(chartX))` on every `mousemove` event. But `resolveTooltipFromX` snaps the tooltip to the nearest data bucket — it returns an identical `{ point, index, x, yPositions }` for every pixel inside the same bucket. React still proceeds with the update because the new object reference !== the old one, so every pixel of mouse motion triggers a full chart re-render for no behavioral reason.++**Affected files**++- `apps/start/src/components/charts/use-chart-interaction.ts`++**Fix (applied)**++Wrap `setTooltipData` with a `commitTooltip(next)` helper that tracks the last committed index in a ref and bails out when `next.index === lastTooltipIndexRef.current`. Reset the ref to `-1` on tooltip clear so the next entry into the chart commits fresh. Route every internal call site through `commitTooltip` (handleMouseMove, handleMouseLeave, handleMouseDown, handleTouchStart, handleTouchMove, handleTouchEnd). The exported `setTooltipData` is preserved for external consumers (ChartMarkers, etc.).++State updates drop from ~hundreds/sec → ~tens/sec (only when crossing bucket boundaries).++`shadcn add` reverts.++---++## 11. `useLineSegmentHighlight` does ~30-60 DOM measurements per Line/Area per hover++**Symptom**++Hover is slow on dense data. Profiler shows Line/Area each taking 30-100ms per render with `findPathLengthAtX` dominating.++**Cause**++The shared `use-line-segment-highlight.ts` hook computes the highlight overlay bounds by calling `findPathLengthAtX(targetX)` twice (startX, endX) per render. That function runs a binary search calling `path.getPointAtLength()` per iteration (~10-20 DOM calls per search, each ~1-3ms). With 2 series and per-bucket hover re-renders, this single pattern dominates hover cost.++**Upstream**++Bklit issue #54 (closed) fixed this in `area.tsx`'s old inline `findLengthAtX` callback by switching to chord-length approximation — but the shared hook was never updated, and `line.tsx` continued calling the slow path through the hook.++**Affected files**++- `apps/start/src/components/charts/use-line-segment-highlight.ts` (rewrite)+- `apps/start/src/components/charts/line.tsx` (caller — drop `pathRef`, pass `yScale`/`dataKey`)+- `apps/start/src/components/charts/area.tsx` (caller — drop `pathRef`, pass `yScale`/`dataKey`)++**Fix (applied)**++Rewrote the hook to pre-compute cumulative chord lengths between data points in pixel space (pure arithmetic), then scale them by `pathLength / totalChordLength` so the dasharray still aligns with the real curved SVG path. The chord pass is memoized on `(data, scales, dataKey)` — runs once on data change, never on hover. Removed the `pathRef` parameter; added `yScale` and `dataKey` (needed for y-pixel computation).++`SeriesDashTailOverlay` still uses `findPathLengthAtX` separately (see item 13). The remaining direct usage is fine because that component runs once per geometry change, not per hover.++`shadcn add` reverts.++---++## 12. `line.tsx` uses `useEffect` to set highlight springs (double-render cycle)++**Symptom**++Every hover bucket boundary triggers two render cycles per Line.++**Cause**++```ts+useEffect(() => {+ offsetSpring.set(-segmentBounds.startLength);+ segmentLengthSpring.set(segmentBounds.segmentLength);+}, [segmentBounds.startLength, segmentBounds.segmentLength, ...]);+```++The effect fires after paint, calling `spring.set()` which schedules its own frame — but the effect itself ran inside a React commit, so React's reconciler does a second render to settle. Motion's `useSpring` is designed to be set imperatively in render, no effect needed.++**Upstream**++Bklit issue #54 (closed) fixed this pattern across `area.tsx`, `tooltip-dot.tsx`, `tooltip-indicator.tsx`, `tooltip/chart-tooltip.tsx`, `date-ticker.tsx`, `tooltip-box.tsx` — but missed `line.tsx`.++**Affected files**++- `apps/start/src/components/charts/line.tsx`++**Fix (applied)**++Inline the spring calls directly in the render body (no useEffect):++```ts+const offsetSpring = useSpring(0, springConfig);+const segmentLengthSpring = useSpring(0, springConfig);+offsetSpring.set(-segmentBounds.startLength);+segmentLengthSpring.set(segmentBounds.segmentLength);+```++`shadcn add` reverts.++---++## 13. `SeriesDashTailOverlay` re-runs `findPathLengthAtX` on every Area re-render++**Symptom**++Profiler showed `SeriesDashTailOverlay` at ~72ms self-time per hover bucket on dense series, dominating Area's total render cost.++**Cause**++The overlay calls `findPathLengthAtX(pathRef.current, pathLength, dashStartX)` in its render body. Its props (data, pathLength, scales, dashFromIndex) are all stable on hover, but the component re-renders every time Area re-renders, re-running the ~30-60 DOM-call binary search for no reason.++**Affected files**++- `apps/start/src/components/charts/series-dash-tail-overlay.tsx`++**Fix (applied)**++Wrap the component in `React.memo`. With stable props on hover, shallow comparison lets Area's per-bucket re-render skip the entire subtree. The binary search now runs only when path geometry actually changes (data swap, resize).++`shadcn add` reverts.++---++## 14. Implicit `Intl` constructors + `Math.random()` IDs in render path++**Symptom**++Constant allocation pressure during interaction; SSR hydration mismatch hazard from gradient IDs.++**Cause**++Two related issues:++- `.toLocaleDateString("en-US", { ... })` and `.toLocaleString()` inside `.map()` loops allocate a fresh `Intl.DateTimeFormat` / `Intl.NumberFormat` per call (each ~10-50× slower than reusing one).+- `area.tsx` and `line.tsx` generate SVG gradient IDs with `\`...-${Math.random().toString(36).slice(2, 9)}\`` inside a `useMemo`. Violates render purity (memoized values must be deterministic) and is a documented SSR hydration-mismatch source.++**Upstream**++Bklit issue #64 (open).++**Affected files**++New shared module:+- `apps/start/src/components/charts/chart-formatters.ts` — exports module-scope `shortDateFmt`, `weekdayDateFmt`, `hmsTimeFmt`, `intFmt`.++Call sites patched to import from `chart-formatters`:+- `apps/start/src/components/charts/area.tsx` (`useId()` for gradient IDs)+- `apps/start/src/components/charts/line.tsx` (`useId()` for gradient IDs)+- `apps/start/src/components/charts/x-axis.tsx` (`shortDateFmt`)+- `apps/start/src/components/charts/time-series-chart-shell.tsx` (`shortDateFmt`)+- `apps/start/src/components/charts/tooltip/chart-tooltip.tsx` (`weekdayDateFmt`)+- `apps/start/src/components/charts/tooltip/tooltip-content.tsx` (`intFmt`)++**Fix (applied)**++Created `chart-formatters.ts` with module-scope formatters. Replaced each `.toLocaleX(...)` call site with `<formatter>.format(value)` / `intFmt(value)`. Replaced `Math.random()` ID generators with `useId()`.++Output strings are byte-equivalent; SVG attribute shape changes (`:r1:` style instead of base36 random) but never user-visible.++`shadcn add` reverts.++---++## 15. Components run expensive `useMemo` work before their early-return guard++**Symptom**++Wasted scale/tick/label computation on pre-mount renders, hidden charts, and renders where the container ref hasn't attached yet.++**Cause**++```tsx+function XAxis(props) {+ const labelsToShow = useMemo(/* expensive */, [...]); // runs first+ if (!(mounted && container)) return null; // …then bails+ return /* render */;+}+```++Rules of Hooks forbids hoisting the guard above the memos. Result: every render where the guard fails still pays for the memos.++**Upstream**++Bklit issue #65 (open).++**Affected files**++Patched with the wrapper / memoized-inner split:+- `apps/start/src/components/charts/x-axis.tsx`+- `apps/start/src/components/charts/y-axis.tsx`+- `apps/start/src/components/charts/tooltip/chart-tooltip.tsx`+- `apps/start/src/components/charts/time-series-chart-shell.tsx`++**Fix (applied)**++Extract a thin outer wrapper that owns the guard, and move all expensive hooks into a `React.memo`-wrapped `*Inner` component:++```tsx+export function XAxis(props) {+ const { mounted, container } = ... ; // only the guard's own hooks+ if (!(mounted && container)) return null;+ return <XAxisInner container={container} {...props} />;+}++const XAxisInner = memo(function XAxisInner({ container, ...props }) {+ const labelsToShow = useMemo(/* expensive */, [...]);+ return /* render */;+});+```++`time-series-chart-shell.tsx` additionally wraps its `contextValue` in `useMemo` so consumers don't re-render from a fresh object identity when no actual state moved.++`shadcn add` reverts.++---++## 16. Monolithic `ChartContext` re-renders every consumer on every hover++**Symptom**++Hover bucket changes re-render the entire chart subtree — Grid, YAxis, PatternArea, OPReferrerSpikes, etc. — even though none of them read tooltip/selection state.++**Cause**++`tooltipData`, `setTooltipData`, `selection`, `clearSelection` (and bar/candle hover indices) live in the same `ChartContextValue` as `data`, `xScale`, `yScale`, dimensions, etc. React context propagates by object identity, so any hover state change → new context value → all `useChart()` consumers re-render.++**Affected files**++- `apps/start/src/components/charts/chart-context.tsx` (split)+- `apps/start/src/components/charts/grid.tsx` (migrate to `useChartStable`)+- `apps/start/src/components/charts/pattern-area.tsx` (migrate to `useChartStable`)+- `apps/start/src/components/charts/y-axis.tsx` (migrate to `useChartStable`)++Plus our own `apps/start/src/components/charts/op-referrer-spikes.tsx` (migrate to `useChartStable`).++**Fix (applied)**++Split `ChartContext` into two underlying contexts:++- `ChartContext` — stable slice (data, scales, dimensions, accessors).+- `ChartHoverContext` — volatile slice (tooltipData, selection, hover indices).++Exported hooks:++- `useChart()` — merged, backward-compat (re-renders on either change).+- `useChartStable()` — stable slice only, never re-renders on hover.+- `useChartHover()` — volatile slice only.++`ChartProvider` splits the input `value` into the two slices via two `useMemo`s keyed on individual field identities. When only `tooltipData` changes, the stable slice keeps its identity and stable consumers skip the re-render.++Then migrated every chart consumer that does NOT read tooltip/selection to `useChartStable()` (Grid, YAxis, PatternArea, OPReferrerSpikes). Consumers that need hover state (Line, Area, ChartTooltip, OPDatePill, OPSeriesDots, markers) keep `useChart()` for now — could be further split into `useChartStable()` + `useChartHover()` if profiling shows them still hot.++When re-adding any of these files via `shadcn add`, also re-add the `useChartStable` import swap.++---++## 17. Hot-path components recreate `motion` variants and inline styles per render++**Symptom**++Allocation churn in `motion` variants; framer re-evaluates animation state on every render even though the variants are identical.++**Affected files**++- `apps/start/src/components/charts/series-point-marker.tsx` — `variants` object rebuilt on every render (this component fans out across every data point in series with markers).++Plus our own:+- `apps/start/src/components/charts/op-date-pill.tsx` — `maxWidth` recomputed inline.+- `apps/start/src/components/charts/op-tooltip.tsx` — `OPAnnotationRow.badgeStyle` recomputed inline per annotation per render.++**Fix (applied)**++Wrap each in `useMemo` keyed on the actual style inputs. For `series-point-marker.tsx`: `[enterBlur, revealDelay, enterDuration, inactiveOpacity, inactiveBlur, showActiveHighlight, hoverEase]`.++`shadcn add` reverts the bklit file. Our two files have no regression risk.++---++## 18. Stray `console.log` in `time-series-chart-shell.tsx`++**Symptom**++Console spam during interaction; possible noticeable cost in DevTools-open sessions.++**Cause**++Debug log left in from an earlier optimization pass:++```ts+console.log('re-render TimeSeriesChartCore');+```++Fired on every render of the memoized core (and is itself a meaningful per-render cost in dev with console open).++**Affected files**++- `apps/start/src/components/charts/time-series-chart-shell.tsx`++**Fix (applied)**++Deleted the line. If re-applying after `shadcn add`, just verify no stray debug logs were re-introduced.++---++## 19. MarkerGroup doesn't support filled-icon or custom-border markers++**Symptom**++Bklit's marker icons render small (16px) inside a 24px circle with a fixed amber/theme-border outline — no way to render an "app icon" style marker where the favicon fills the circle and the border picks up a custom color.++**Cause**++`MarkerCircle` and `MarkerCircleHTML` in `marker-group.tsx` hard-code:+- `foreignObject` size = `size - 8` with a 4px inset, leaving the icon visibly smaller than the circle.+- `stroke` = `chartCssVars.markerBorder` (no override).++**Affected files**++- `apps/start/src/components/charts/markers/marker-group.tsx`++**Fix (applied)**++Added two optional props to `MarkerGroupProps` (forwarded to both `MarkerCircle` and `MarkerCircleHTML`):++```ts+iconFill?: boolean; // foreignObject = size × size, clips to circle+borderColor?: string; // overrides stroke color+```++Implementation:++```tsx+const inset = iconFill ? 0 : 4;+const foSize = size - inset * 2;+// ...+stroke={borderColor || chartCssVars.markerBorder}+// foreignObject uses foSize / inset+// inner div: overflow: 'hidden', borderRadius: iconFill ? '50%' : undefined+```++Backward compat preserved (defaults off). Used by `op-marker-layer.tsx` to give all OpenPanel chart annotations the "app icon" look (favicon edge-to-edge with a foreground-colored border).++Also requires `report-chart/common/serie-icon.tsx`'s `fill?: boolean` prop (our own file, no shadcn regression risk) — when set, images render `size-full rounded-full object-cover` instead of the default `max-h-4` cap so they actually fill the larger `foreignObject`.++`shadcn add` reverts the bklit patch.diff --git a/bklit-upstream-issues.md b/bklit-upstream-issues.mdnew file mode 100644index 000000000..18fd64b38--- /dev/null+++ b/bklit-upstream-issues.md@@ -0,0 +1,341 @@+# bklit-ui — Upstream Issues to File++Ready-to-post GitHub issues for `bklit-ui`. Each block below has a title and a body; copy/paste into the repo.++Local notes / source: `bklit-issues.md`.+Already filed upstream and excluded from this list: items #14 (= bklit #64) and #15 (= bklit #65).++---++## Issue 1++**Title:** `require("react-dom")` in chart components breaks under Vite / pure-ESM bundlers++**Body:**++Six chart components use a runtime `require` to lazily resolve `createPortal`:++```ts+// Dynamic import to avoid SSR issues+const { createPortal } = require("react-dom") as typeof import("react-dom");+```++Under Next.js this works because Next polyfills CommonJS in client chunks. Under Vite / TanStack Start / any pure-ESM client bundler, `require` is not defined at runtime and the chart blows up:++```+ReferenceError: require is not defined+ at ChartTooltip (chart-tooltip.tsx:146:28)+```++The chart then renders blank.++The lazy resolution isn't actually needed — every call site is already guarded by a `mounted` state that flips `true` only inside `useEffect`, so `createPortal` only runs on the client anyway.++**Affected files** (`packages/ui/src/charts/`)++- `tooltip/chart-tooltip.tsx`+- `tooltip/tooltip-box.tsx`+- `x-axis.tsx`+- `y-axis.tsx`+- `bar-x-axis.tsx`+- `bar-y-axis.tsx`++**Suggested fix**++Replace the lazy `require` with a top-level static import:++```ts+import { createPortal } from "react-dom";+```++…and delete the inline `const { createPortal } = require(...)` line just before each `createPortal(...)` call. The existing `mounted && container` guard above the call site already prevents SSR execution.++---++## Issue 2++**Title:** Registry (`apps/web/public/r/*.json`) lags `packages/ui/src/charts/` source++The shadcn registry build under `apps/web/public/r/*.json` is missing newer features that exist in `packages/ui/src/charts/`. Examples observed:++- `dashFromIndex` prop on `<Line>` / `<Area>`+- `<SeriesMarkers>`+- `<SeriesDashTailOverlay>`+- `path-stroke-utils.ts`+- `dash-tail-stroke.tsx`+- `series-point-marker.tsx`+- `area-gradient-defs.tsx`+- `use-line-segment-highlight.ts`+- `use-area-segment-highlight.ts`+- newer revisions of `area.tsx`, `line.tsx`++Because the registry is the source of truth for `shadcn add`, consumers running `shadcn add line-chart` (or similar) get the older code and either silently miss features or fail to compile when other registry items reference symbols that aren't there.++**Suggested fix**++Rebuild the registry after merges so it tracks `packages/ui/src/charts/`, ideally via CI on push to main.++---++## Issue 3++**Title:** `chart-context` registry item overwrites consumer chart palette in `.dark`++When `shadcn add chart-context` (or any item that depends on it) is run, it appends bklit's grayscale `--chart-1` … `--chart-5` overrides into the `.dark { ... }` block of the consumer's `styles.css`.++Two problems:++1. The injection collapses onto a single line, mangling the `.dark` block formatting.+2. Apps that already define their own `--chart-*` palette in `:root` (theme-agnostic) get those tokens silently overridden inside `.dark`. The result is that `bg-chart-1`, `text-chart-2`, etc. turn gray in dark mode across the entire app, including pages and components that have nothing to do with bklit charts.++In our case the conflicting tokens were:++- `--chart-1` … `--chart-5`+- `--chart-background`, `--chart-foreground`, `--chart-grid`, `--chart-crosshair`+- `--chart-marker-*`+- `--chart-ring-background`+- `--chart-label`+- `--chart-foreground-muted`++The only tokens that genuinely need to be theme-aware are the tooltip ones:++```css+--chart-tooltip-background: oklch(from var(--foreground) l c h / 0.92);+--chart-tooltip-foreground: var(--background);+--chart-tooltip-muted: oklch(from var(--background) l c h / 0.6);+```++**Suggested fixes (any of)**++- Namespace bklit's chart tokens (e.g. `--bk-chart-1`) so they can't collide with a consumer's `--chart-*` scale.+- Only emit the tooltip vars into `.dark` and keep the palette in `:root` only.+- Preserve formatting in the `.dark` block when appending (don't collapse to one line).++---++## Issue 4++**Title:** No dual Y-axis support in `<ComposedChart>` / cartesian shells++`ComposedChart` (and every other cartesian shell) computes a single linear Y scale from `max(all series values)`. There's no `yAxisId` / `orientation="right"` equivalent — you can't mount a second axis with an independent domain.++This is a regression vs. recharts and blocks a common analytics chart: showing a small-magnitude metric (e.g. unique visitors, 0–1,000) alongside a high-magnitude metric (e.g. revenue in cents, 0–5,000,000) on the same time series.++Current workarounds all have downsides:++- Pre-scaling the second series into the primary series' domain (lossy, requires reformatting in tooltip).+- Two stacked charts sharing the X domain (vertical real estate cost, complex sync).+- Rendering the second metric in a separate widget (loses correlation context).++**Suggested fix**++Add an optional `yScaleRight` (or `axes={[{ id: 'left', ... }, { id: 'right', ... }]}`) to `composed-chart.tsx` / `time-series-chart-shell.tsx`, plus a `yAxisId` prop on `<Line>` / `<Area>` / `<Bar>` to pick which scale they map against. Tooltip would need to read the right scale for series bound to it.++Non-trivial but high-value for analytics workloads.++---++## Issue 5++**Title:** `<XAxis>` default `tickMode="domain"` misaligns labels with data points++`<XAxis>` defaults to `tickMode="domain"`, which places `numTicks` (default 5) evenly across the time domain. Those positions are computed from `xScale.domain()`, not from real data points — so labels almost never coincide with an actual tick on the chart.++For sparse or non-uniform data (monthly bars, irregular event days, weekly aggregates), this looks visually off: a label sitting between two bars, or in the middle of a gap with no datum nearby.++`tickMode="data"` (one label per data row at the row's x position) is almost always the right behavior — it matches recharts and most analytics conventions.++**Suggested fix**++Either flip the default to `"data"`, or document `tickMode` prominently so consumers know to set it explicitly. The current default is a footgun for time-series charts with non-uniform data.++---++## Issue 6++**Title:** `<ChartMarkers>` get clipped by the chart `<svg>` element++`MarkerGroup` renders as SVG (`<g transform="translate(x, y)">`) inside the chart's own `<svg>`, not as an HTML portal. With marker `y=-8` and `size=24`, the top edge sits at SVG y = `margin.top - 20`. Anything less than `margin.top: 20` clips the marker.++Bumping `margin.top` works but introduces dead headroom on charts that don't have references on every render.++**Suggested fix**++Render the chart `<svg>` with `style={{ overflow: 'visible' }}` in both `time-series-chart-shell.tsx` and `bar-chart.tsx`. With that, markers can render above the chart's bounding box without clipping regardless of `margin.top`:++```tsx+<svg aria-hidden="true" height={height} width={width} style={{ overflow: 'visible' }}>+```++Verified locally — no observed downside (the parent container still clips so it doesn't bleed across the page).++---++## Issue 7++**Title:** `useActiveMarkers` matches references by day, not by hover bucket++`useActiveMarkers(markers)` matches `marker.date.toDateString()` against the active tooltip date. That's day-granular: on an hourly chart, every hour of the marker's day shows the reference in the tooltip even though the visual marker only sits on one hour. The tooltip and the chart disagree.++Repro: render an hourly time series with a marker at `2026-05-20T14:00:00Z`. Hover at `2026-05-20T03:00:00Z`. The reference still appears in the tooltip even though no marker is visible there.++**Suggested fix**++Match by bucket index instead of date string: snap each marker to its nearest data index and compare against the currently hovered point's index. This works for hourly / minute / arbitrary intervals.++Alternatively, accept the comparator as an option so consumers can opt into bucket-level matching.++Related: it would be nice for `<ChartTooltip>` to accept a `markers`/`references` prop and handle the matching itself, instead of consumers having to compose `useActiveMarkers` + `MarkerTooltipContent` manually.++---++## Issue 8++**Title:** `<Line>` and `<Area>` plot missing values at SVG y=0 (top of chart)++`getY` in both `line.tsx` and `area.tsx`:++```ts+return typeof value === "number" ? (yScale(value) ?? 0) : 0;+```++The fallback `0` is a raw SVG y coordinate, not a data-domain zero. In SVG, y=0 is the **top** of the chart, not the baseline — so a series with sparse data renders the missing rows at the ceiling, producing a flat line plastered to the top of the chart.++**Repro**++Render `<Line>` over an array where some rows are missing the line's `dataKey`. Hover at a missing row — the tooltip shows `0` but the hover dot is pinned to Y=max instead of Y=0.++**Suggested fix**++Fall back to `yScale(0)` (data-domain zero in pixel space) instead of raw SVG `0`:++```ts+const getY = useCallback((d) => {+ const value = d[dataKey];+ if (typeof value === "number") {+ return yScale(value) ?? yScale(0) ?? 0;+ }+ return yScale(0) ?? 0;+}, [dataKey, yScale]);+```++This places missing points on the baseline, matching recharts and visual expectations.++Alternative: emit `null` and have the path generator skip undefined points (true gaps). That's a bigger change but arguably more correct.++---++## Issue 9++**Title:** Hover spring constants feel sluggish on dense time series++Hover-related springs (`tooltip-box`, `tooltip-dot`, `tooltip-indicator`, line/area highlight) ship with constants around `{ stiffness: 100–300, damping: 20–30 }`. On dense time series with many data points, this reads as visible lag between the cursor and the indicator — by the time the tooltip catches up, the user is already two buckets past.++Locally we re-tuned to `{ stiffness: 1000, damping: 60 }` across:++- `tooltip/tooltip-box.tsx` (`springConfig`)+- `tooltip/tooltip-dot.tsx` (`crosshairSpringConfig`)+- `tooltip/tooltip-indicator.tsx` (`crosshairSpringConfig`)+- `line.tsx` (highlight `springConfig`)+- `area.tsx` (highlight `springConfig`)++Hover now feels precise and the indicator visibly leads to the next bucket on the same frame the user crosses the boundary.++**Suggested fix**++Either raise the defaults, or expose the spring config on the relevant components / via theme so consumers can tune without forking.++---++## Issue 10 (combined performance pass)++**Title:** Chart hover hot-path: multiple per-pixel re-render and DOM-measurement issues++While profiling hover on dense time-series charts (~200 points, 2 series), we found a stack of issues that compound — together they cause the entire chart subtree to re-render hundreds of times per second during continuous mouse motion, with each render doing 30–100ms of binary-search DOM measurement. Filing them together since they touch the same hot path.++Each item below is independent and can be fixed in isolation, but the cumulative effect is what makes hover feel laggy in production.++### 10a. `setTooltipData` fires on every mousemove pixel, not on bucket change++`use-chart-interaction.ts` → `handleMouseMove` calls `setTooltipData(resolveTooltipFromX(chartX))` on every `mousemove`. But `resolveTooltipFromX` snaps to the nearest data bucket — it returns an identical `{ point, index, x, yPositions }` for every pixel inside the same bucket. React still proceeds with the update because the new object reference !== the old, so every pixel of mouse motion triggers a full chart re-render for no behavioral reason.++**Fix:** wrap `setTooltipData` with a `commitTooltip(next)` helper that tracks the last committed `index` in a ref and bails out when `next.index === lastTooltipIndexRef.current`. Reset to `-1` on tooltip clear so the next entry commits fresh. Route every internal call site through `commitTooltip` (mousemove, mouseleave, mousedown, touchstart, touchmove, touchend). Keep the exported `setTooltipData` for external consumers.++State updates drop from ~hundreds/sec → ~tens/sec.++### 10b. `useLineSegmentHighlight` does 30–60 DOM measurements per hover per series++The shared `use-line-segment-highlight.ts` hook computes the highlight overlay bounds by calling `findPathLengthAtX(targetX)` twice (startX, endX) per render. That function runs a binary search calling `path.getPointAtLength()` per iteration (~10–20 DOM calls per search, each ~1–3ms). With 2 series and per-bucket hover re-renders, this dominates hover cost — 30–100ms per Line/Area per render.++Bklit #54 (closed) fixed this in `area.tsx`'s old inline `findLengthAtX` callback by switching to chord-length approximation — but the shared hook was never updated, and `line.tsx` continued calling the slow path through the hook.++**Fix:** rewrite the hook to pre-compute cumulative chord lengths between data points in pixel space (pure arithmetic), then scale them by `pathLength / totalChordLength` so the dasharray still aligns with the real curved SVG path. Memoize the chord pass on `(data, scales, dataKey)` so it runs once on data change, never on hover. Remove the `pathRef` parameter; add `yScale` and `dataKey`.++### 10c. `line.tsx` uses `useEffect` to set highlight springs (double-render cycle)++Every hover bucket boundary triggers two render cycles per `<Line>`:++```ts+useEffect(() => {+ offsetSpring.set(-segmentBounds.startLength);+ segmentLengthSpring.set(segmentBounds.segmentLength);+}, [segmentBounds.startLength, segmentBounds.segmentLength, ...]);+```++The effect fires after paint, calling `spring.set()` which schedules its own frame — but the effect itself ran inside a React commit, so React's reconciler does a second render to settle. Motion's `useSpring` is designed to be set imperatively in render.++Bklit #54 (closed) fixed this across `area.tsx`, `tooltip-dot.tsx`, `tooltip-indicator.tsx`, `tooltip/chart-tooltip.tsx`, `date-ticker.tsx`, `tooltip-box.tsx` — but missed `line.tsx`.++**Fix:** inline the spring calls in the render body:++```ts+const offsetSpring = useSpring(0, springConfig);+const segmentLengthSpring = useSpring(0, springConfig);+offsetSpring.set(-segmentBounds.startLength);+segmentLengthSpring.set(segmentBounds.segmentLength);+```++### 10d. `SeriesDashTailOverlay` re-runs `findPathLengthAtX` on every Area re-render++`SeriesDashTailOverlay` calls `findPathLengthAtX(pathRef.current, pathLength, dashStartX)` in its render body. Its props (data, pathLength, scales, dashFromIndex) are all stable on hover, but the component re-renders every time Area re-renders, re-running the ~30–60 DOM-call binary search for no reason. Profiler shows it at ~72ms self-time per hover bucket on dense series.++**Fix:** wrap the component in `React.memo`. With stable props, shallow comparison lets Area's per-bucket re-render skip the entire subtree. The binary search then runs only on actual geometry changes (data swap, resize).++### 10e. Monolithic `ChartContext` re-renders every consumer on every hover++`tooltipData`, `setTooltipData`, `selection`, `clearSelection` (and bar/candle hover indices) live in the same `ChartContextValue` as `data`, `xScale`, `yScale`, dimensions, etc. React context propagates by object identity, so any hover state change → new context value → all `useChart()` consumers re-render (Grid, YAxis, PatternArea, etc.) even though they read nothing volatile.++**Fix:** split into two contexts.++- `ChartContext` — stable slice (data, scales, dimensions, accessors).+- `ChartHoverContext` — volatile slice (tooltipData, selection, hover indices).++Exported hooks:++- `useChart()` — merged, backward-compatible (re-renders on either).+- `useChartStable()` — stable slice only, never re-renders on hover.+- `useChartHover()` — volatile slice only.++In `ChartProvider`, split the input `value` into two slices via two `useMemo`s keyed on individual field identities. When only `tooltipData` changes, the stable slice keeps its identity and stable consumers skip the re-render.++Then migrate consumers that don't read tooltip/selection (Grid, YAxis, PatternArea) to `useChartStable()`. Leave hover-dependent consumers (Line, Area, ChartTooltip, marker components) on `useChart()` for compatibility.++### 10f. Hot-path components recreate `motion` variants per render++`series-point-marker.tsx` rebuilds its `variants` object on every render. This component fans out across every data point in series with markers — for a 200-point series, that's 200 instances allocating fresh variants per hover bucket re-render. Framer re-evaluates animation state on every render even though the variants are identical.++**Fix:** wrap the variants in `useMemo` keyed on `[enterBlur, revealDelay, enterDuration, inactiveOpacity, inactiveBlur, showActiveHighlight, hoverEase]`.++### 10g. Stray `console.log` in `time-series-chart-shell.tsx`++```ts+console.log('re-render TimeSeriesChartCore');+```++Fires on every render of the memoized core. With DevTools open, this is itself a meaningful per-render cost; in any case it's debug spam in production builds.++**Fix:** delete the line.++---++End of list.diff --git a/packages/db/index.ts b/packages/db/index.tsindex cb8e52831..727ea5663 100644--- a/packages/db/index.ts+++ b/packages/db/index.ts@@ -30,6 +30,7 @@ export * from './src/services/pages.service';export * from './src/services/profile.service';export * from './src/services/project.service';export * from './src/services/reference.service';+export * from './src/services/referrer-spikes.service';export * from './src/services/reports.service';export * from './src/services/retention.service';export * from './src/services/salt.service';diff --git a/packages/db/src/services/referrer-spikes.service.ts b/packages/db/src/services/referrer-spikes.service.tsnew file mode 100644index 000000000..a5092add7--- /dev/null+++ b/packages/db/src/services/referrer-spikes.service.ts@@ -0,0 +1,305 @@+import type { IChartEventFilter, IInterval } from '@openpanel/validation';+import {+ TABLE_NAMES,+ ch,+ convertClickhouseDateToJs,+} from '../clickhouse/client';+import { clix } from '../clickhouse/query-builder';+import { overviewService } from './overview.service';++// Spike detection thresholds. Conservative defaults — markers should be rare+// and obviously meaningful when they appear. Tune here if real usage shows+// too many / too few annotations.+const MIN_SESSIONS_FLOOR = 10;+const RATIO_MULTIPLIER = 3;+const P75_MULTIPLIER = 2;+const MIN_SHARE = 0.15;+const MIN_BUCKETS_FOR_BASELINE = 5;+const MAX_REFERRERS = 50;+const MAX_OTHERS_IN_TOOLTIP = 3;+// Hard cap as a safety bound. The relative filter below usually keeps the+// return count well under this for any real project.+const MAX_SPIKE_BUCKETS = 30;+// Relative "stand-out" filter: only return spikes whose score sits above+// `median(scores) * SIGNIFICANCE_MULTIPLIER`. Self-adjusting — if every+// candidate has a similar score (median is high), most get filtered out;+// if one clearly dominates (median is low), it passes easily.+const SIGNIFICANCE_MULTIPLIER = 1.5;+// Skip the relative filter when we have very few candidates — at low N+// the median is unstable and everything is "notable" anyway.+const MIN_CANDIDATES_FOR_RELATIVE_FILTER = 4;++export interface ReferrerSpike {+ /** Bucket start, ISO string. Frontend reformats to match overview.stats series. */+ date: string;+ referrer_name: string;+ sessions: number;+ /** Median sessions per bucket for this referrer in the range. 0 when isNew. */+ baseline: number;+ /** sessions / max(baseline, 1). For isNew, equals sessions. */+ ratio: number;+ /** This referrer's fraction of total sessions in this bucket (0..1). */+ share: number;+ /** True when the referrer only appears in this single bucket across the range. */+ isNew: boolean;+ /** Secondary spikes that hit on the same bucket, ranked by score. */+ others: Array<{ referrer_name: string; sessions: number; ratio: number }>;+}++/**+ * One bucket's worth of spike data. The wire format keeps the cluster+ * shape (anchorDate + spikes array) for forward-compatibility, but the+ * backend no longer groups across buckets — every entry has+ * `spikes.length === 1`. Visual density grouping happens on the frontend,+ * where the live `xScale` knows actual pixel distances and the right+ * threshold doesn't depend on the chosen interval.+ */+export interface ReferrerSpikeCluster {+ /** Bucket date — used to position the marker. */+ anchorDate: string;+ /** Spikes for this bucket. Currently always length 1; shape kept for forward-compat. */+ spikes: ReferrerSpike[];+}++export interface GetReferrerSpikesInput {+ projectId: string;+ filters: IChartEventFilter[];+ startDate: string;+ endDate: string;+ interval: IInterval;+ timezone: string;+}++export async function getReferrerSpikes(+ input: GetReferrerSpikesInput,+): Promise<ReferrerSpikeCluster[]> {+ const { projectId, filters, startDate, endDate, interval, timezone } = input;+ const filtersWhere = overviewService.getRawWhereClause('sessions', filters);++ // Step 1: top non-direct referrers by total range volume. Bounds the+ // expensive per-bucket query — long-tail referrers can't produce+ // meaningful spikes anyway because they fail the absolute floor.+ const topReferrers = await clix(ch, timezone)+ .select<{ referrer_name: string; total: number }>([+ 'referrer_name',+ 'sum(sign) AS total',+ ])+ .from(TABLE_NAMES.sessions, true)+ .where('project_id', '=', projectId)+ .where('created_at', 'BETWEEN', [+ clix.datetime(startDate, 'toDateTime'),+ clix.datetime(endDate, 'toDateTime'),+ ])+ .where('referrer_name', '!=', '')+ .where('referrer_name', 'IS NOT NULL')+ .rawWhere(filtersWhere)+ .groupBy(['referrer_name'])+ .having('sum(sign)', '>=', MIN_SESSIONS_FLOOR)+ .orderBy('total', 'DESC')+ .limit(MAX_REFERRERS)+ .execute();++ if (topReferrers.length === 0) {+ return [];+ }++ const referrerNames = topReferrers.map((r) => r.referrer_name);++ // Step 2: per-bucket sessions for top referrers + bucket totals (including+ // direct traffic) for the share-of-bucket denominator. Run in parallel.+ const [spikeRows, bucketTotalRows] = await Promise.all([+ clix(ch, timezone)+ .select<{ date: string; referrer_name: string; sessions: number }>([+ `${clix.toStartOf('created_at', interval as any, timezone)} AS date`,+ 'referrer_name',+ 'sum(sign) AS sessions',+ ])+ .from(TABLE_NAMES.sessions, true)+ .where('project_id', '=', projectId)+ .where('created_at', 'BETWEEN', [+ clix.datetime(startDate, 'toDateTime'),+ clix.datetime(endDate, 'toDateTime'),+ ])+ .where('referrer_name', 'IN', referrerNames)+ .rawWhere(filtersWhere)+ .groupBy(['date', 'referrer_name'])+ .having('sum(sign)', '>', 0)+ .orderBy('date', 'ASC')+ .transform({+ date: (item) => convertClickhouseDateToJs(item.date).toISOString(),+ })+ .execute(),++ clix(ch, timezone)+ .select<{ date: string; total: number }>([+ `${clix.toStartOf('created_at', interval as any, timezone)} AS date`,+ 'sum(sign) AS total',+ ])+ .from(TABLE_NAMES.sessions, true)+ .where('project_id', '=', projectId)+ .where('created_at', 'BETWEEN', [+ clix.datetime(startDate, 'toDateTime'),+ clix.datetime(endDate, 'toDateTime'),+ ])+ .rawWhere(filtersWhere)+ .groupBy(['date'])+ .having('sum(sign)', '>', 0)+ .transform({+ date: (item) => convertClickhouseDateToJs(item.date).toISOString(),+ })+ .execute(),+ ]);++ // Bail when the range doesn't have enough buckets to form a stable baseline.+ // Median over <5 points is meaningless and produces noisy spikes.+ const bucketCount = new Set(bucketTotalRows.map((r) => r.date)).size;+ if (bucketCount < MIN_BUCKETS_FOR_BASELINE) {+ return [];+ }++ const bucketTotalByDate = new Map(+ bucketTotalRows.map((r) => [r.date, r.total]),+ );++ const rowsByReferrer = new Map<+ string,+ Array<{ date: string; sessions: number }>+ >();+ for (const row of spikeRows) {+ const arr = rowsByReferrer.get(row.referrer_name) ?? [];+ arr.push({ date: row.date, sessions: row.sessions });+ rowsByReferrer.set(row.referrer_name, arr);+ }++ interface Candidate {+ date: string;+ referrer_name: string;+ sessions: number;+ baseline: number;+ ratio: number;+ share: number;+ isNew: boolean;+ score: number;+ }+ const candidates: Candidate[] = [];++ for (const [referrer, rows] of rowsByReferrer) {+ const sorted = rows.map((r) => r.sessions).sort((a, b) => a - b);+ const isNewReferrer = sorted.length === 1;+ const median = percentile(sorted, 0.5);+ const p75 = percentile(sorted, 0.75);+ const ratioThreshold = Math.max(+ median * RATIO_MULTIPLIER,+ p75 * P75_MULTIPLIER,+ );++ for (const row of rows) {+ if (row.sessions < MIN_SESSIONS_FLOOR) continue;++ const total = bucketTotalByDate.get(row.date) ?? row.sessions;+ const share = total > 0 ? row.sessions / total : 0;+ if (share < MIN_SHARE) continue;++ const baseline = isNewReferrer ? 0 : median;+ const ratio = isNewReferrer+ ? row.sessions+ : row.sessions / Math.max(median, 1);++ const isSpike = isNewReferrer || row.sessions >= ratioThreshold;+ if (!isSpike) continue;++ candidates.push({+ date: row.date,+ referrer_name: referrer,+ sessions: row.sessions,+ baseline,+ ratio,+ share,+ isNew: isNewReferrer,+ score: ratio * share,+ });+ }+ }++ const byBucket = new Map<string, Candidate[]>();+ for (const c of candidates) {+ const arr = byBucket.get(c.date) ?? [];+ arr.push(c);+ byBucket.set(c.date, arr);+ }++ // Per-bucket: pick the top-scoring referrer as the bucket's spike, keep+ // a few secondary ones for the tooltip's "+ also" line.+ interface PerBucketSpike {+ date: string;+ top: Candidate;+ others: Candidate[];+ }+ const perBucketSpikes: PerBucketSpike[] = [];+ for (const [date, arr] of byBucket) {+ arr.sort((a, b) => b.score - a.score);+ const top = arr[0];+ if (!top) continue;+ perBucketSpikes.push({+ date,+ top,+ others: arr.slice(1, 1 + MAX_OTHERS_IN_TOOLTIP),+ });+ }++ // Relative "stand-out" filter. Drops spikes whose scores cluster near the+ // typical spike score in this range — those aren't really notable+ // relative to everything else happening, even though they cleared the+ // absolute floors. Always keeps the top spike as a fallback so we never+ // return zero when there's at least one candidate.+ perBucketSpikes.sort((a, b) => b.top.score - a.top.score);++ let filtered = perBucketSpikes;+ if (perBucketSpikes.length >= MIN_CANDIDATES_FOR_RELATIVE_FILTER) {+ const sortedScoresAsc = perBucketSpikes+ .map((s) => s.top.score)+ .sort((a, b) => a - b);+ const medianScore = percentile(sortedScoresAsc, 0.5);+ const threshold = medianScore * SIGNIFICANCE_MULTIPLIER;+ const standouts = perBucketSpikes.filter((s) => s.top.score > threshold);+ filtered = standouts.length > 0 ? standouts : perBucketSpikes.slice(0, 1);+ }++ const capped = filtered.slice(0, MAX_SPIKE_BUCKETS);+ capped.sort((a, b) => a.date.localeCompare(b.date));++ return capped.map(({ date, top, others }) => ({+ anchorDate: date,+ spikes: [+ {+ date,+ referrer_name: top.referrer_name,+ sessions: top.sessions,+ baseline: round(top.baseline, 2),+ ratio: round(top.ratio, 2),+ share: round(top.share, 4),+ isNew: top.isNew,+ others: others.map((o) => ({+ referrer_name: o.referrer_name,+ sessions: o.sessions,+ ratio: round(o.ratio, 2),+ })),+ },+ ],+ }));+}++function percentile(sortedAsc: number[], p: number): number {+ if (sortedAsc.length === 0) return 0;+ if (sortedAsc.length === 1) return sortedAsc[0]!;+ const idx = (sortedAsc.length - 1) * p;+ const lo = Math.floor(idx);+ const hi = Math.ceil(idx);+ if (lo === hi) return sortedAsc[lo]!;+ return sortedAsc[lo]! * (hi - idx) + sortedAsc[hi]! * (idx - lo);+}++function round(value: number, decimals: number): number {+ const factor = 10 ** decimals;+ return Math.round(value * factor) / factor;+}diff --git a/packages/trpc/src/routers/overview.ts b/packages/trpc/src/routers/overview.tsindex c1a7af5ec..422ff366d 100644--- a/packages/trpc/src/routers/overview.ts+++ b/packages/trpc/src/routers/overview.ts@@ -7,6 +7,7 @@ import {getChartStartEndDate,getConversionEventNames,getOrganizationSubscriptionChartEndDate,+ getReferrerSpikes,getSettingsForProject,overviewService,validateOverviewShareAccess,@@ -297,6 +298,41 @@ export const overviewRouter = createTRPCRouter({};}),+ getReferrerSpikes: overviewProcedure+ .input(+ zGetMetricsInput.omit({ startDate: true, endDate: true }).extend({+ startDate: z.string().nullish(),+ endDate: z.string().nullish(),+ range: zRange,+ shareId: z.string().optional(),+ }),+ )+ .use(cacher)+ .query(async ({ input }) => {+ const { timezone } = await getSettingsForProject(input.projectId);+ const { startDate, endDate } = getChartStartEndDate(input, timezone);+ const clusters = await getReferrerSpikes({+ projectId: input.projectId,+ filters: input.filters,+ interval: input.interval,+ startDate,+ endDate,+ timezone,+ });+ // Reformat every spike date (and the cluster's anchor) to match+ // overview.stats' series date format, so markers x-align with the+ // chart's data points (xScale matches by Date identity).+ const fmt = (iso: string) =>+ format(new Date(iso), 'yyyy-MM-dd HH:mm:ss');+ return clusters.map((cluster) => ({+ anchorDate: fmt(cluster.anchorDate),+ spikes: cluster.spikes.map((spike) => ({+ ...spike,+ date: fmt(spike.date),+ })),+ }));+ }),+topPages: overviewProcedure.input(zGetTopPagesInput.omit({ startDate: true, endDate: true }).extend({diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 7241166c6..d99f95000 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -581,7 +581,7 @@ importers:version: 1.2.8(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])'@reduxjs/toolkit':specifier: ^2.8.2- version: 2.8.2([email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))([email protected])([email protected]))([email protected])+ version: 2.8.2([email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))([email protected])([email protected]))([email protected])'@sentry/tanstackstart-react':specifier: ^9.12.0version: 9.46.0([email protected])@@ -651,6 +651,30 @@ importers:'@types/d3':specifier: ^7.4.3version: 7.4.3+ '@visx/curve':+ specifier: 4.0.1-alpha.0+ version: 4.0.1-alpha.0+ '@visx/event':+ specifier: 4.0.1-alpha.0+ version: 4.0.1-alpha.0+ '@visx/gradient':+ specifier: 4.0.1-alpha.0+ version: 4.0.1-alpha.0([email protected])+ '@visx/grid':+ specifier: 4.0.1-alpha.0+ version: 4.0.1-alpha.0([email protected])+ '@visx/pattern':+ specifier: 4.0.1-alpha.0+ version: 4.0.1-alpha.0([email protected])+ '@visx/responsive':+ specifier: 4.0.1-alpha.0+ version: 4.0.1-alpha.0([email protected])+ '@visx/scale':+ specifier: 4.0.1-alpha.0+ version: 4.0.1-alpha.0+ '@visx/shape':+ specifier: 4.0.1-alpha.0+ version: 4.0.1-alpha.0([email protected])bind-event-listener:specifier: ^3.0.0version: 3.0.0@@ -669,6 +693,9 @@ importers:d3:specifier: ^7.8.5version: 7.8.5+ d3-array:+ specifier: ^3.2.4+ version: 3.2.4date-fns:specifier: ^3.3.1version: 3.3.1@@ -717,9 +744,12 @@ importers:mitt:specifier: ^3.0.1version: 3.0.1+ motion:+ specifier: ^12.40.0+ version: 12.40.0(@emotion/[email protected])([email protected]([email protected]))([email protected])nuqs:specifier: ^2.5.2- version: 2.5.2(patch_hash=4f93812bf7a04685f9477b2935e3acbf2aa24dfbb1b00b9ae0ed8f7a2877a98e)(@tanstack/[email protected]([email protected]([email protected]))([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])+ version: 2.5.2(patch_hash=4f93812bf7a04685f9477b2935e3acbf2aa24dfbb1b00b9ae0ed8f7a2877a98e)(@tanstack/[email protected]([email protected]([email protected]))([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])prisma-error-enum:specifier: ^0.1.3version: 0.1.3@@ -764,7 +794,7 @@ importers:version: 10.1.0(@types/[email protected])([email protected])react-redux:specifier: ^8.1.3- version: 8.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))([email protected])([email protected])+ version: 8.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))([email protected])([email protected])react-resizable:specifier: ^3.0.5@@ -826,7 +856,7 @@ importers:specifier: ^2.2.2version: 2.2.2tailwind-merge:- specifier: ^3.0.2+ specifier: ^3.3.1version: 3.3.1tailwindcss:specifier: ^4.0.6@@ -871,6 +901,9 @@ importers:'@testing-library/react':specifier: ^16.2.0version: 16.3.0(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@types/d3-array':+ specifier: ^3.2.2+ version: 3.2.2'@types/lodash.debounce':specifier: ^4.0.9version: 4.0.9@@ -9599,8 +9632,11 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-nl09VhutdjINdWyXxHWN/w9zlNCfr60JUqJbd24YXUuCwgeL0TpFSdElCwb6cxfB6ybE19Gjj4g0jsgkXxKv1Q==}- '@types/[email protected]':- resolution: {integrity: sha512-Y2Jn2idRrLzUfAKV2LyRImR+y4oa2AntrgID95SHJxuMUrkNXmanDSed71sRNZysveJVt1hLLemQZIady0FpEg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==}'@types/[email protected]':resolution: {integrity: sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==}@@ -9614,12 +9650,18 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-tbaFGDmJWHqnenvk3QGSvD3RVwr631BjKRD7Sc7VLRgrdX5mk5hTyoeBL6rXZaeoXzmZwIl1D2HPogEdt1rHBg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA==}+'@types/[email protected]':resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==}'@types/[email protected]':resolution: {integrity: sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-tLxQ2sfT0p6sxdG75c6f/ekqxjyYR0+LwPrsO1mbC9YDBzPJhs2HbJJRrn8Ez1DBoHRo2yx7YEATI+8V1nGMnQ==}+'@types/[email protected]':resolution: {integrity: sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==}@@ -9641,6 +9683,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-IKtvyFdb4Q0LWna6ymywQsEYjK/94SGhPrMfEr1TIc5OBeziTi+1jcCvttts8e0UWZIxpasjnQk9MNk/3iS+kA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg==}+'@types/[email protected]':resolution: {integrity: sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==}@@ -9656,6 +9701,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-UINE41RDaUMbulp+bxQMDnhOi51rh5lA2dG+dWZU0UY/IwQiG/u2x8TfnWYU9+xwGdXsJoAvrBYUEQl0r91atg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-jx5leotSeac3jr0RePOH1KdR9rISG91QIE4Q2PYTu4OymLTZfA3SrnURSLzKH48HmXVUru50b8nje4E79oQSQw==}+'@types/[email protected]':resolution: {integrity: sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==}@@ -9665,6 +9713,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-P2dlU/q51fkOc/Gfl3Ul9kicV7l+ra934qBFXCFhrZMOL6du1TM0pm1ThYvENukyOn5h9v+yMJ9Fn5JK4QozrQ==}+ '@types/[email protected]':+ resolution: {integrity: sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==}+'@types/[email protected]':resolution: {integrity: sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==}@@ -9680,6 +9731,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-laXM4+1o5ImZv3RpFAsTRn3TEkzqkytiOY0Dz0sq5cnd1dtNlk6sHLon4OvqaiJb28T0S/TdsBI3Sjsy+keJrw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA==}+'@types/[email protected]':resolution: {integrity: sha512-gkK1VVTr5iNiYJ7vWDI+yUFFlszhNMtVeneJ6lUTKPjprsvLLI9/tgEGiXJOnlINJA8FyA88gfnQsHbybVZrYQ==}@@ -9695,9 +9749,18 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-5KKk5aKGu2I+O6SONMYSNflgiP0WfZIQvVUMan50wHsLG1G94JlxEVnCpQARfTtzytuY0p/9PXXZb3I7giofIA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-/myT3I7EwlukNOX2xVdMzb8FRgNzRMpsZddwst9Ld/VFe6LyJyRp0s32l/V9XoUzk+Gqu56F/oGk6507+8BxrA==}+'@types/[email protected]':resolution: {integrity: sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==}+'@types/[email protected]':resolution: {integrity: sha512-2p6olUZ4w3s+07q3Tm2dbiMZy5pCDfYwtLXXHUnVzXgQlZ/OyPtUz6OL382BkOuGlLXqfT+wqv8Fw2v8/0geBw==}@@ -9812,6 +9875,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-OvlIYQK9tNneDlS0VN54LLd5uiPCBOp7gS5Z0f1mjoJYBrtStzgmJBxONW3U6OZqdtNzZPmn9BS/7WI7BFFcFQ==}+ '@types/[email protected]':+ resolution: {integrity: sha512-gIW7lQLZbue7lRSWEFql49QJJWThrTFFeIMJdp3eH4tKoxm1OvEPg02rm4wCCSHS0cL3/Fizimb35b7k8atwsQ==}+'@types/[email protected]':resolution: {integrity: sha512-H3iskjFIAn5SlJU7OuxUmTEpebK6TKB8rxZShDslBMZJ5u9S//KM1sbdAisiSrqwLQncVjnpi2OK2J51h+4lsg==}@@ -10055,6 +10121,51 @@ packages:engines: {node: '>=18'}hasBin: true+ '@visx/[email protected]':+ resolution: {integrity: sha512-jRu61Uz274pV1zyioXmboyrLutYbnKsgjj4njSGCnhdXj5GkZvZbg+ThDb6oOzoAnJOBRLz4rzPlWvNJOzuVMg==}++ '@visx/[email protected]':+ resolution: {integrity: sha512-EQqCMSv/s8NbFjo+hz3FKsvvYfP+2QslsFJ/24/O5l/W+7UC6J6aAvO0ujVwrTwdYbuQ+vhxKi1xdPdKR/qj1g==}++ '@visx/[email protected]':+ resolution: {integrity: sha512-HxkxLdThV/gPaulw+t7/ESo7AtqIBq9IlHIkHi7lQqXe0Yl+x8rpM3KYlYqEZjtihD9CeEaVJjBbdY7fQb54IA==}+ peerDependencies:+ react: ^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0++ '@visx/[email protected]':+ resolution: {integrity: sha512-rycutGmTHO+znNdPumheWMglm7YfpffvRwUkVy5zy4WoORIuKTMkDxwnOzHG2xMxU3EE/YCd37xFV5AxA30yeg==}+ peerDependencies:+ react: ^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0++ '@visx/[email protected]':+ resolution: {integrity: sha512-V19l7iQ7jccBv8kao/EByuI6o4xtxzzLV9nqVI1hRvmdzTVsuLpqlwzYCZUXJaTVvUWf8s4D2SQFjGkj/Nw+0w==}+ peerDependencies:+ react: ^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0++ '@visx/[email protected]':+ resolution: {integrity: sha512-KCqHpjtHdu95uqamc5PIYG55Xp0w+7/Zz63k4eeZErwK1o0PN2rZiBiuodNtENL8NqIU2b5AP+XI/xXaUH0M4Q==}+ peerDependencies:+ react: ^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0++ '@visx/[email protected]':+ resolution: {integrity: sha512-ijTfr/Nx09f03vIj9nyTr3z4Xth4Y75427UaogJh6dnIRLMEFHQOwNu791sbfiNj0a+ZXuaE32h0vKrFe4/8Qg==}++ '@visx/[email protected]':+ resolution: {integrity: sha512-o+1zGywQZY0+yOx3Iw87wc4bbPJRr/HnIukTwfOz4UVyj9pB1OQNVHB7OORO1+LBHJceWpB31co/ZV9KHncKrA==}+ peerDependencies:+ react: ^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0++ '@visx/[email protected]':+ resolution: {integrity: sha512-nzjeE87vFSAXGWFiiNfBpNLAf0Q8Qmf6syvKLjqNi4kGZkdhbUll3E/59YsgWXmjM8+llPLWzGsP+JPvo5eq1A==}++ '@visx/[email protected]':+ resolution: {integrity: sha512-62QeiVNmPlterQGwhkEDcbq7M0MqY0lBsK5QKXtM9ZoPZWkuGV3aykA3+Xu20B2FAvyJq4LqJzBc7Sxr+EAdbA==}+ peerDependencies:+ react: ^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0++ '@visx/[email protected]':+ resolution: {integrity: sha512-6I+MuqXBcv9jnlcVowHoHKSdk9gXTWkHLKyqBwRWg7LY6A3Ei8SHfubpqGV5rBUSppxMq2RszPJUS6w+H0YgmQ==}+'@vitejs/[email protected]':resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==}engines: {node: ^14.18.0 || >=16.0.0}@@ -11481,6 +11592,10 @@ packages:resolution: {integrity: sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==}+ resolution: {integrity: sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==}engines: {node: '>=12'}@@ -11508,6 +11623,10 @@ packages:resolution: {integrity: sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==}engines: {node: '>=12'}+ resolution: {integrity: sha512-IMLNldruDQScrcfT+MWnazhHbDJhcRJyOEBAJfwQnHle1RPh6WDuLvxNArUju2VSMSUuKlY5BGHRJ2cYyoFLQQ==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==}engines: {node: '>=12'}@@ -12829,6 +12948,20 @@ packages:react-dom:optional: true+ resolution: {integrity: sha512-uaBd3qC1v3KQqBEjwTUd183K6PbS+j0yR9w9VmEOLWA/tnUcSn8Xa3uck7t4dgpDoUss8xQTcj8W2L07lrnLFg==}+ peerDependencies:+ '@emotion/is-prop-valid': '*'+ react: ^18.0.0 || ^19.0.0+ react-dom: ^18.0.0 || ^19.0.0+ peerDependenciesMeta:+ '@emotion/is-prop-valid':+ optional: true+ react:+ optional: true+ react-dom:+ optional: true+resolution: {integrity: sha512-K7od3Uw45AJg00XUmy15+Hae2hOcgKcmN3/EF6Y7i01O0gaqiRx8sUSpsb9+BRNL8RPBrhzPsVfy8q9ADlJuWQ==}engines: {node: '>=8'}@@ -15167,6 +15300,9 @@ packages:resolution: {integrity: sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA==}+ resolution: {integrity: sha512-HxU3ZaBwNPVQUBQf1xxgq+7JrPNZvjLVxgbpEZL7RrWJnsxOf0/OM+yrHG9ogLQ31Do/r57Oz2gQWPK+6q62mg==}+resolution: {integrity: sha512-49Kt+HKjtbJKLtgO/LKj9Ld+6vw9BjH5d9sc40R/kVyH8GLAXgT42M2NnuPcJNuA3s9ZfZBUcwIgpmZWGEE+hA==}@@ -15176,6 +15312,9 @@ packages:resolution: {integrity: sha512-eHWisygbiwVvf6PZ1vhaHCLamvkSbPIeAYxWUuL3a2PD/TROgE7FvfHWTIH4vMl798QLfMw15nRqIaRDXTlYRg==}+ resolution: {integrity: sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ==}+resolution: {integrity: sha512-JLjvFDuFr42NFtcVoMAyC2sEjnpA8xpy6qWPyzQvCloznAyQ8FIXioxWfHiLtgYhoVpfUqSWpn1h9++skj9+Wg==}peerDependencies:@@ -15204,6 +15343,20 @@ packages:react-dom:optional: true+ resolution: {integrity: sha512-yjrHUrBFW6kQvjJwRsoiPSAhC5tRwRqNGJWmiJ4CrGnbKp0V88AdzkhBmDoqIsIPfarOe0Uddd37Xq43/gIocA==}+ peerDependencies:+ '@emotion/is-prop-valid': '*'+ react: ^18.0.0 || ^19.0.0+ react-dom: ^18.0.0 || ^19.0.0+ peerDependenciesMeta:+ '@emotion/is-prop-valid':+ optional: true+ react:+ optional: true+ react-dom:+ optional: true+resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==}engines: {node: '>=10'}@@ -18908,6 +19061,7 @@ packages:resolution: {integrity: sha512-DPSke0pXhTZgoF/d+WSt2QaKMCFSfx7QegxEWT+JOuHF5aWrKEn0G+ztjuJg/gG8/ItK+rbPCD/yNv8yyih6Cg==}+ deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).hasBin: true@@ -18917,6 +19071,7 @@ packages:resolution: {integrity: sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==}+ deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).hasBin: true@@ -20712,20 +20867,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- '@babel/helper-member-expression-to-functions': 7.28.5- '@babel/helper-optimise-call-expression': 7.27.1- '@babel/helper-replace-supers': 7.27.1(@babel/[email protected])- '@babel/helper-skip-transparent-expression-wrappers': 7.27.1- '@babel/traverse': 7.29.0- semver: 6.3.1- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -20752,20 +20893,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- '@babel/helper-member-expression-to-functions': 7.28.5- '@babel/helper-optimise-call-expression': 7.27.1- '@babel/helper-replace-supers': 7.28.6(@babel/[email protected])- '@babel/helper-skip-transparent-expression-wrappers': 7.27.1- '@babel/traverse': 7.29.0- semver: 6.3.1- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -20779,14 +20906,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- regexpu-core: 5.3.2- semver: 6.3.1- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -20794,14 +20913,6 @@ snapshots:regexpu-core: 5.3.2semver: 6.3.1- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- regexpu-core: 6.4.0- semver: 6.3.1- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -20809,18 +20920,6 @@ snapshots:regexpu-core: 6.4.0semver: 6.3.1- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-compilation-targets': 7.28.6- '@babel/helper-plugin-utils': 7.28.6- debug: 4.4.3- lodash.debounce: 4.0.8- resolve: 1.22.12- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -20832,18 +20931,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-compilation-targets': 7.28.6- '@babel/helper-plugin-utils': 7.28.6- debug: 4.4.3- lodash.debounce: 4.0.8- resolve: 1.22.12- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -20926,16 +21013,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-module-imports': 7.28.6- '@babel/helper-validator-identifier': 7.28.5- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -20962,14 +21039,6 @@ snapshots:'@babel/[email protected]': {}- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- '@babel/helper-environment-visitor': 7.22.20- '@babel/helper-wrap-function': 7.22.20- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -20977,16 +21046,6 @@ snapshots:'@babel/helper-environment-visitor': 7.22.20'@babel/helper-wrap-function': 7.22.20- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- '@babel/helper-wrap-function': 7.28.6- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -20996,16 +21055,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-member-expression-to-functions': 7.27.1- '@babel/helper-optimise-call-expression': 7.27.1- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21024,16 +21073,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-member-expression-to-functions': 7.28.5- '@babel/helper-optimise-call-expression': 7.27.1- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21129,27 +21168,11 @@ snapshots:dependencies:'@babel/types': 7.29.0- '@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@7.27.1(@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@7.27.1(@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-skip-transparent-expression-wrappers': 7.27.1- '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/[email protected])- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21159,15 +21182,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21176,15 +21190,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-environment-visitor': 7.22.20- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-remap-async-to-generator': 7.22.20(@babel/[email protected])- '@babel/plugin-syntax-async-generators': 7.8.4(@babel/[email protected])- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21193,15 +21198,6 @@ snapshots:'@babel/helper-remap-async-to-generator': 7.22.20(@babel/[email protected])'@babel/plugin-syntax-async-generators': 7.8.4(@babel/[email protected])- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-class-features-plugin': 7.28.5(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21227,55 +21223,24 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/plugin-syntax-export-default-from': 7.23.3(@babel/[email protected])- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6'@babel/plugin-syntax-export-default-from': 7.23.3(@babel/[email protected])- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/[email protected])- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6'@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/[email protected])- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/[email protected])- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6'@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/[email protected])- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/compat-data': 7.29.0- '@babel/core': 7.28.3- '@babel/helper-compilation-targets': 7.28.6- '@babel/helper-plugin-utils': 7.28.6- '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/[email protected])- '@babel/plugin-transform-parameters': 7.23.3(@babel/[email protected])- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/compat-data': 7.29.0@@ -21294,29 +21259,12 @@ snapshots:'@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/[email protected])'@babel/plugin-transform-parameters': 7.23.3(@babel/[email protected])- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/[email protected])- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6'@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/[email protected])- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-skip-transparent-expression-wrappers': 7.27.1- '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/[email protected])- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21326,32 +21274,15 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2(@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- optional: true-'@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2(@babel/[email protected])':dependencies:'@babel/core': 7.28.5- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21362,12 +21293,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21378,45 +21303,21 @@ snapshots:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21427,45 +21328,21 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21491,45 +21368,21 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21540,45 +21393,21 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21599,36 +21428,17 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.27.1- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21639,16 +21449,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-remap-async-to-generator': 7.27.1(@babel/[email protected])- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21658,16 +21458,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-module-imports': 7.28.6- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-remap-async-to-generator': 7.22.20(@babel/[email protected])- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21677,16 +21467,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-module-imports': 7.28.6- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-remap-async-to-generator': 7.27.1(@babel/[email protected])- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21696,12 +21476,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21712,23 +21486,11 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21739,15 +21501,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21756,15 +21509,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21773,21 +21517,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- '@babel/helper-compilation-targets': 7.28.6- '@babel/helper-environment-visitor': 7.22.20- '@babel/helper-function-name': 7.23.0- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-replace-supers': 7.27.1(@babel/[email protected])- '@babel/helper-split-export-declaration': 7.22.6- globals: 11.12.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21802,19 +21531,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- '@babel/helper-compilation-targets': 7.28.6- '@babel/helper-globals': 7.28.0- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-replace-supers': 7.28.6(@babel/[email protected])- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21839,26 +21555,12 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/template': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6'@babel/template': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/template': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21871,26 +21573,11 @@ snapshots:'@babel/helper-plugin-utils': 7.28.6'@babel/template': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21907,70 +21594,32 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/plugin-syntax-flow': 7.23.3(@babel/[email protected])- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -21983,15 +21632,6 @@ snapshots:'@babel/helper-plugin-utils': 7.28.6'@babel/plugin-syntax-flow': 7.28.6(@babel/[email protected])- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-skip-transparent-expression-wrappers': 7.27.1- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22008,14 +21648,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-compilation-targets': 7.28.6- '@babel/helper-function-name': 7.23.0- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22023,16 +21655,6 @@ snapshots:'@babel/helper-function-name': 7.23.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-compilation-targets': 7.28.6- '@babel/helper-plugin-utils': 7.28.6- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22051,34 +21673,16 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22089,23 +21693,11 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22116,15 +21708,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-module-transforms': 7.28.6(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22133,15 +21716,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-module-transforms': 7.28.6(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22150,15 +21724,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-module-transforms': 7.28.6(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22175,17 +21740,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-module-transforms': 7.28.6(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-validator-identifier': 7.28.5- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22196,15 +21750,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-module-transforms': 7.28.6(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22213,77 +21758,33 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-regexp-features-plugin': 7.22.15(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-create-regexp-features-plugin': 7.22.15(@babel/[email protected])'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-compilation-targets': 7.28.6- '@babel/helper-plugin-utils': 7.28.6- '@babel/plugin-transform-destructuring': 7.28.5(@babel/[email protected])- '@babel/plugin-transform-parameters': 7.27.7(@babel/[email protected])- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22295,15 +21796,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-replace-supers': 7.28.6(@babel/[email protected])- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22320,26 +21812,11 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-skip-transparent-expression-wrappers': 7.27.1- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22348,12 +21825,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22364,12 +21835,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22380,15 +21845,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-class-features-plugin': 7.28.5(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22397,15 +21853,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22414,17 +21861,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- '@babel/helper-create-class-features-plugin': 7.28.5(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/[email protected])- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22435,16 +21871,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- '@babel/helper-create-class-features-plugin': 7.28.6(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22454,12 +21880,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22470,12 +21890,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22498,12 +21912,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22514,12 +21922,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22530,18 +21932,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- '@babel/helper-module-imports': 7.28.6- '@babel/helper-plugin-utils': 7.28.6- '@babel/plugin-syntax-jsx': 7.27.1(@babel/[email protected])- '@babel/types': 7.29.0- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22581,41 +21971,16 @@ snapshots:'@babel/helper-annotate-as-pure': 7.27.3'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-module-imports': 7.28.6- '@babel/helper-plugin-utils': 7.28.6- babel-plugin-polyfill-corejs2: 0.4.8(@babel/[email protected])- babel-plugin-polyfill-corejs3: 0.9.0(@babel/[email protected])- babel-plugin-polyfill-regenerator: 0.5.5(@babel/[email protected])- semver: 6.3.1- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22628,23 +21993,11 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22655,15 +22008,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-skip-transparent-expression-wrappers': 7.27.1- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22672,15 +22016,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-skip-transparent-expression-wrappers': 7.27.1- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22697,34 +22032,16 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22735,12 +22052,6 @@ snapshots:'@babel/core': 7.29.0'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22757,18 +22068,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-annotate-as-pure': 7.27.3- '@babel/helper-create-class-features-plugin': 7.28.5(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-skip-transparent-expression-wrappers': 7.27.1- '@babel/plugin-syntax-typescript': 7.27.1(@babel/[email protected])- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -22791,156 +22090,35 @@ snapshots:transitivePeerDependencies:- supports-color- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-regexp-features-plugin': 7.22.15(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-create-regexp-features-plugin': 7.22.15(@babel/[email protected])'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])- '@babel/helper-plugin-utils': 7.28.6- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5'@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])'@babel/helper-plugin-utils': 7.28.6- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/compat-data': 7.29.0- '@babel/core': 7.28.3- '@babel/helper-compilation-targets': 7.28.6- '@babel/helper-plugin-utils': 7.28.6- '@babel/helper-validator-option': 7.27.1- '@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression': 7.27.1(@babel/[email protected])- '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining': 7.27.1(@babel/[email protected])- '@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly': 7.28.6(@babel/[email protected])- '@babel/plugin-proposal-private-property-in-object': 7.21.0-placeholder-for-preset-env.2(@babel/[email protected])- '@babel/plugin-syntax-async-generators': 7.8.4(@babel/[email protected])- '@babel/plugin-syntax-class-properties': 7.12.13(@babel/[email protected])- '@babel/plugin-syntax-class-static-block': 7.14.5(@babel/[email protected])- '@babel/plugin-syntax-dynamic-import': 7.8.3(@babel/[email protected])- '@babel/plugin-syntax-export-namespace-from': 7.8.3(@babel/[email protected])- '@babel/plugin-syntax-import-assertions': 7.28.6(@babel/[email protected])- '@babel/plugin-syntax-import-attributes': 7.28.6(@babel/[email protected])- '@babel/plugin-syntax-import-meta': 7.10.4(@babel/[email protected])- '@babel/plugin-syntax-json-strings': 7.8.3(@babel/[email protected])- '@babel/plugin-syntax-logical-assignment-operators': 7.10.4(@babel/[email protected])- '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/[email protected])- '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/[email protected])- '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/[email protected])- '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/[email protected])- '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/[email protected])- '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/[email protected])- '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/[email protected])- '@babel/plugin-syntax-unicode-sets-regex': 7.18.6(@babel/[email protected])- '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-async-generator-functions': 7.29.0(@babel/[email protected])- '@babel/plugin-transform-async-to-generator': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-block-scoped-functions': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-block-scoping': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-class-properties': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-class-static-block': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-classes': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-computed-properties': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-destructuring': 7.28.5(@babel/[email protected])- '@babel/plugin-transform-dotall-regex': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-duplicate-keys': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-dynamic-import': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-exponentiation-operator': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-for-of': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-function-name': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-json-strings': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-literals': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-logical-assignment-operators': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-member-expression-literals': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-modules-amd': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-modules-systemjs': 7.29.0(@babel/[email protected])- '@babel/plugin-transform-modules-umd': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-named-capturing-groups-regex': 7.29.0(@babel/[email protected])- '@babel/plugin-transform-new-target': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-nullish-coalescing-operator': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-numeric-separator': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-object-super': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-optional-catch-binding': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-parameters': 7.27.7(@babel/[email protected])- '@babel/plugin-transform-private-methods': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-private-property-in-object': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-property-literals': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-regenerator': 7.29.0(@babel/[email protected])- '@babel/plugin-transform-reserved-words': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-shorthand-properties': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-spread': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-sticky-regex': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-template-literals': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-typeof-symbol': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-unicode-escapes': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-unicode-property-regex': 7.28.6(@babel/[email protected])- '@babel/plugin-transform-unicode-regex': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-unicode-sets-regex': 7.28.6(@babel/[email protected])- '@babel/preset-modules': 0.1.6-no-external-plugins(@babel/[email protected])- babel-plugin-polyfill-corejs2: 0.4.17(@babel/[email protected])- babel-plugin-polyfill-corejs3: 0.9.0(@babel/[email protected])- babel-plugin-polyfill-regenerator: 0.5.5(@babel/[email protected])- core-js-compat: 3.49.0- semver: 6.3.1- transitivePeerDependencies:- - supports-color- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/compat-data': 7.29.0@@ -23034,14 +22212,6 @@ snapshots:'@babel/helper-validator-option': 7.27.1'@babel/plugin-transform-flow-strip-types': 7.23.3(@babel/[email protected])- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.28.3- '@babel/helper-plugin-utils': 7.28.6- '@babel/types': 7.29.0- esutils: 2.0.3- optional: true-'@babel/[email protected](@babel/[email protected])':dependencies:'@babel/core': 7.28.5@@ -25140,7 +24310,7 @@ snapshots:'@nivo/theming': 0.99.0([email protected])- lodash: 4.17.21+ lodash: 4.18.1react: 19.2.3transitivePeerDependencies:- react-dom@@ -25155,7 +24325,7 @@ snapshots:d3-color: 3.1.0d3-scale: 4.0.2d3-scale-chromatic: 3.0.0- lodash: 4.17.21+ lodash: 4.18.1react: 19.2.3transitivePeerDependencies:- react-dom@@ -25173,7 +24343,7 @@ snapshots:d3-scale-chromatic: 3.0.0d3-shape: 3.2.0d3-time-format: 3.0.0- lodash: 4.17.21+ lodash: 4.18.1react: 19.2.3use-debounce: 10.0.6([email protected])@@ -25238,7 +24408,7 @@ snapshots:'@nivo/[email protected]([email protected])':dependencies:- lodash: 4.17.21+ lodash: 4.18.1react: 19.2.3@@ -28110,14 +27280,6 @@ snapshots:'@react-native/[email protected]': {}- dependencies:- '@react-native/codegen': 0.73.3(@babel/[email protected](@babel/[email protected]))- transitivePeerDependencies:- - '@babel/preset-env'- - supports-color- optional: true-dependencies:'@react-native/codegen': 0.73.3(@babel/[email protected](@babel/[email protected]))@@ -28125,55 +27287,6 @@ snapshots:- '@babel/preset-env'- supports-color- '@react-native/[email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))':- dependencies:- '@babel/core': 7.28.3- '@babel/plugin-proposal-async-generator-functions': 7.20.7(@babel/[email protected])- '@babel/plugin-proposal-class-properties': 7.18.6(@babel/[email protected])- '@babel/plugin-proposal-export-default-from': 7.23.3(@babel/[email protected])- '@babel/plugin-proposal-nullish-coalescing-operator': 7.18.6(@babel/[email protected])- '@babel/plugin-proposal-numeric-separator': 7.18.6(@babel/[email protected])- '@babel/plugin-proposal-object-rest-spread': 7.20.7(@babel/[email protected])- '@babel/plugin-proposal-optional-catch-binding': 7.18.6(@babel/[email protected])- '@babel/plugin-proposal-optional-chaining': 7.21.0(@babel/[email protected])- '@babel/plugin-syntax-dynamic-import': 7.8.3(@babel/[email protected])- '@babel/plugin-syntax-export-default-from': 7.23.3(@babel/[email protected])- '@babel/plugin-syntax-flow': 7.23.3(@babel/[email protected])- '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/[email protected])- '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/[email protected])- '@babel/plugin-transform-arrow-functions': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-async-to-generator': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-block-scoping': 7.23.4(@babel/[email protected])- '@babel/plugin-transform-classes': 7.23.8(@babel/[email protected])- '@babel/plugin-transform-computed-properties': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-destructuring': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-flow-strip-types': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-function-name': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-literals': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-modules-commonjs': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-named-capturing-groups-regex': 7.22.5(@babel/[email protected])- '@babel/plugin-transform-parameters': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-private-methods': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-private-property-in-object': 7.23.4(@babel/[email protected])- '@babel/plugin-transform-react-display-name': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-react-jsx': 7.23.4(@babel/[email protected])- '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/[email protected])- '@babel/plugin-transform-runtime': 7.23.9(@babel/[email protected])- '@babel/plugin-transform-shorthand-properties': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-spread': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-sticky-regex': 7.23.3(@babel/[email protected])- '@babel/plugin-transform-typescript': 7.28.5(@babel/[email protected])- '@babel/plugin-transform-unicode-regex': 7.23.3(@babel/[email protected])- '@babel/template': 7.28.6- '@react-native/babel-plugin-codegen': 0.73.4(@babel/[email protected](@babel/[email protected]))- babel-plugin-transform-flow-enums: 0.0.2(@babel/[email protected])- react-refresh: 0.14.0- transitivePeerDependencies:- - '@babel/preset-env'- - supports-color- optional: true-'@react-native/[email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))':dependencies:'@babel/core': 7.28.5@@ -28222,20 +27335,6 @@ snapshots:- '@babel/preset-env'- supports-color- dependencies:- '@babel/parser': 7.28.5- '@babel/preset-env': 7.23.9(@babel/[email protected])- flow-parser: 0.206.0- glob: 7.2.3- invariant: 2.2.4- jscodeshift: 0.14.0(@babel/[email protected](@babel/[email protected]))- mkdirp: 0.5.6- nullthrows: 1.1.1- transitivePeerDependencies:- - supports-color- optional: true-dependencies:'@babel/parser': 7.28.5@@ -28249,28 +27348,6 @@ snapshots:transitivePeerDependencies:- supports-color- '@react-native/[email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))':- dependencies:- '@react-native-community/cli-server-api': 12.3.6- '@react-native-community/cli-tools': 12.3.6- '@react-native/dev-middleware': 0.73.8- '@react-native/metro-babel-transformer': 0.73.15(@babel/[email protected])(@babel/[email protected](@babel/[email protected]))- chalk: 4.1.2- execa: 5.1.1- metro: 0.80.6- metro-config: 0.80.6- metro-core: 0.80.6- node-fetch: 2.7.0- readline: 1.3.0- transitivePeerDependencies:- - '@babel/core'- - '@babel/preset-env'- - bufferutil- - encoding- - supports-color- - utf-8-validate- optional: true-'@react-native/[email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))':dependencies:'@react-native-community/cli-server-api': 12.3.6@@ -28317,17 +27394,6 @@ snapshots:'@react-native/[email protected]': {}- '@react-native/[email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))':- dependencies:- '@babel/core': 7.28.3- '@react-native/babel-preset': 0.73.21(@babel/[email protected])(@babel/[email protected](@babel/[email protected]))- hermes-parser: 0.15.0- nullthrows: 1.1.1- transitivePeerDependencies:- - '@babel/preset-env'- - supports-color- optional: true-'@react-native/[email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))':dependencies:'@babel/core': 7.28.5@@ -28342,13 +27408,6 @@ snapshots:'@react-native/[email protected]': {}- '@react-native/[email protected]([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))':- dependencies:- invariant: 2.2.4- nullthrows: 1.1.1- react-native: 0.73.6(@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected])- optional: true-'@react-native/[email protected]([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))':dependencies:invariant: 2.2.4@@ -28413,7 +27472,7 @@ snapshots:dependencies:'@redis/client': 1.6.0- '@reduxjs/[email protected]([email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))([email protected])([email protected]))([email protected])':+ '@reduxjs/[email protected]([email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))([email protected])([email protected]))([email protected])':dependencies:'@standard-schema/spec': 1.0.0'@standard-schema/utils': 0.3.0@@ -28423,7 +27482,7 @@ snapshots:reselect: 5.1.1optionalDependencies:react: 19.2.3- react-redux: 8.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))([email protected])([email protected])+ react-redux: 8.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))([email protected])([email protected])'@rolldown/[email protected]':optional: true@@ -30111,7 +29170,9 @@ snapshots:'@types/[email protected]': {}- '@types/[email protected]': {}+ '@types/[email protected]': {}++ '@types/[email protected]': {}'@types/[email protected]':dependencies:@@ -30125,13 +29186,17 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]':dependencies:- '@types/d3-array': 3.2.1+ '@types/d3-array': 3.2.2'@types/geojson': 7946.0.14+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -30150,6 +29215,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]':@@ -30166,6 +29233,10 @@ snapshots:dependencies:'@types/d3-color': 2.0.6+ '@types/[email protected]':+ dependencies:+ '@types/d3-color': 3.1.3+'@types/[email protected]':dependencies:'@types/d3-color': 3.1.3@@ -30174,6 +29245,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -30186,6 +29259,10 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]':+ dependencies:+ '@types/d3-time': 3.0.3+'@types/[email protected]':dependencies:'@types/d3-time': 3.0.3@@ -30202,8 +29279,16 @@ snapshots:dependencies:'@types/d3-path': 3.1.0+ '@types/[email protected]':+ dependencies:+ '@types/d3-path': 3.1.1++ '@types/[email protected]': {}+'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}@@ -30224,7 +29309,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/d3-array': 3.2.1+ '@types/d3-array': 3.2.2'@types/d3-axis': 3.0.6'@types/d3-brush': 3.0.6'@types/d3-chord': 3.0.6@@ -30375,6 +29460,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]':@@ -30664,6 +29751,94 @@ snapshots:- rollup- supports-color+ '@visx/[email protected]':+ dependencies:+ '@visx/vendor': 4.0.0-alpha.0++ '@visx/[email protected]':+ dependencies:+ '@types/react': 19.2.7+ '@visx/point': 4.0.1-alpha.0++ '@visx/[email protected]([email protected])':+ dependencies:+ '@types/react': 19.2.7+ react: 19.2.3++ '@visx/[email protected]([email protected])':+ dependencies:+ '@types/react': 19.2.7+ '@visx/curve': 4.0.1-alpha.0+ '@visx/group': 4.0.1-alpha.0([email protected])+ '@visx/point': 4.0.1-alpha.0+ '@visx/scale': 4.0.1-alpha.0+ '@visx/shape': 4.0.1-alpha.0([email protected])+ classnames: 2.5.1+ react: 19.2.3++ '@visx/[email protected]([email protected])':+ dependencies:+ '@types/react': 19.2.7+ classnames: 2.5.1+ react: 19.2.3++ '@visx/[email protected]([email protected])':+ dependencies:+ '@types/react': 19.2.7+ classnames: 2.5.1+ react: 19.2.3++ '@visx/[email protected]': {}++ '@visx/[email protected]([email protected])':+ dependencies:+ '@types/lodash': 4.17.24+ '@types/react': 19.2.7+ lodash: 4.18.1+ react: 19.2.3++ '@visx/[email protected]':+ dependencies:+ '@visx/vendor': 4.0.0-alpha.0++ '@visx/[email protected]([email protected])':+ dependencies:+ '@types/lodash': 4.17.24+ '@types/react': 19.2.7+ '@visx/curve': 4.0.1-alpha.0+ '@visx/group': 4.0.1-alpha.0([email protected])+ '@visx/scale': 4.0.1-alpha.0+ '@visx/vendor': 4.0.0-alpha.0+ classnames: 2.5.1+ lodash: 4.18.1+ react: 19.2.3++ '@visx/[email protected]':+ dependencies:+ '@types/d3-array': 3.0.3+ '@types/d3-color': 3.1.0+ '@types/d3-delaunay': 6.0.1+ '@types/d3-format': 3.0.1+ '@types/d3-geo': 3.1.0+ '@types/d3-interpolate': 3.0.1+ '@types/d3-path': 3.1.1+ '@types/d3-scale': 4.0.2+ '@types/d3-shape': 3.1.7+ '@types/d3-time': 3.0.0+ '@types/d3-time-format': 2.1.0+ d3-array: 3.2.1+ d3-color: 3.1.0+ d3-delaunay: 6.0.2+ d3-format: 3.1.0+ d3-geo: 3.1.0+ d3-interpolate: 3.0.1+ d3-path: 3.1.0+ d3-scale: 4.0.2+ d3-shape: 3.2.0+ d3-time: 3.1.0+ d3-time-format: 4.1.0+ internmap: 2.0.3+'@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@babel/core': 7.28.5@@ -31111,7 +30286,7 @@ snapshots:graceful-fs: 4.2.11is-stream: 2.0.1lazystream: 1.0.1- lodash: 4.17.21+ lodash: 4.18.1normalize-path: 3.0.0readable-stream: 4.5.2@@ -31406,16 +30581,6 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@babel/[email protected]):- dependencies:- '@babel/compat-data': 7.29.0- '@babel/core': 7.28.3- '@babel/helper-define-polyfill-provider': 0.6.8(@babel/[email protected])- semver: 6.3.1- transitivePeerDependencies:- - supports-color- optional: true-[email protected](@babel/[email protected]):dependencies:'@babel/compat-data': 7.29.0@@ -31425,16 +30590,6 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@babel/[email protected]):- dependencies:- '@babel/compat-data': 7.29.0- '@babel/core': 7.28.3- '@babel/helper-define-polyfill-provider': 0.5.0(@babel/[email protected])- semver: 6.3.1- transitivePeerDependencies:- - supports-color- optional: true-[email protected](@babel/[email protected]):dependencies:'@babel/compat-data': 7.29.0@@ -31444,15 +30599,6 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@babel/[email protected]):- dependencies:- '@babel/core': 7.28.3- '@babel/helper-define-polyfill-provider': 0.5.0(@babel/[email protected])- core-js-compat: 3.36.0- transitivePeerDependencies:- - supports-color- optional: true-[email protected](@babel/[email protected]):dependencies:'@babel/core': 7.28.5@@ -31461,14 +30607,6 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@babel/[email protected]):- dependencies:- '@babel/core': 7.28.3- '@babel/helper-define-polyfill-provider': 0.5.0(@babel/[email protected])- transitivePeerDependencies:- - supports-color- optional: true-[email protected](@babel/[email protected]):dependencies:'@babel/core': 7.28.5@@ -31480,13 +30618,6 @@ snapshots:- [email protected](@babel/[email protected]):- dependencies:- '@babel/plugin-syntax-flow': 7.23.3(@babel/[email protected])- transitivePeerDependencies:- - '@babel/core'- optional: true-[email protected](@babel/[email protected]):dependencies:'@babel/plugin-syntax-flow': 7.23.3(@babel/[email protected])@@ -32524,6 +31655,10 @@ snapshots:dependencies:internmap: 1.0.1+ dependencies:+ internmap: 2.0.3+dependencies:internmap: 2.0.3@@ -32550,6 +31685,10 @@ snapshots:dependencies:d3-array: 3.2.4+ dependencies:+ delaunator: 5.0.1+dependencies:delaunator: 5.0.1@@ -34420,6 +33559,16 @@ snapshots:react: 19.2.3react-dom: 19.2.3([email protected])+ [email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]):+ dependencies:+ motion-dom: 12.40.0+ motion-utils: 12.39.0+ tslib: 2.8.1+ optionalDependencies:+ '@emotion/is-prop-valid': 0.8.8+ react: 19.2.3+ react-dom: 19.2.3([email protected])+@@ -35865,32 +35014,6 @@ snapshots:- dependencies:- '@babel/core': 7.28.5- '@babel/parser': 7.29.2- '@babel/plugin-proposal-class-properties': 7.18.6(@babel/[email protected])- '@babel/plugin-proposal-nullish-coalescing-operator': 7.18.6(@babel/[email protected])- '@babel/plugin-proposal-optional-chaining': 7.21.0(@babel/[email protected])- '@babel/plugin-transform-modules-commonjs': 7.27.1(@babel/[email protected])- '@babel/preset-env': 7.23.9(@babel/[email protected])- '@babel/preset-flow': 7.23.3(@babel/[email protected])- '@babel/preset-typescript': 7.27.1(@babel/[email protected])- '@babel/register': 7.23.7(@babel/[email protected])- babel-core: 7.0.0-bridge.0(@babel/[email protected])- chalk: 4.1.2- flow-parser: 0.206.0- graceful-fs: 4.2.11- micromatch: 4.0.8- neo-async: 2.6.2- node-dir: 0.1.17- recast: 0.21.5- temp: 0.8.4- write-file-atomic: 2.4.3- transitivePeerDependencies:- - supports-color- optional: true-dependencies:'@babel/core': 7.28.5@@ -37326,12 +36449,18 @@ snapshots:dependencies:motion-utils: 12.36.0+ dependencies:+ motion-utils: 12.39.0++ [email protected]: {}+[email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]):dependencies:framer-motion: 11.18.2(@emotion/[email protected])([email protected]([email protected]))([email protected])@@ -37350,6 +36479,15 @@ snapshots:react: 19.2.3react-dom: 19.2.3([email protected])+ [email protected](@emotion/[email protected])([email protected]([email protected]))([email protected]):+ dependencies:+ framer-motion: 12.40.0(@emotion/[email protected])([email protected]([email protected]))([email protected])+ tslib: 2.8.1+ optionalDependencies:+ '@emotion/is-prop-valid': 0.8.8+ react: 19.2.3+ react-dom: 19.2.3([email protected])+@@ -37469,7 +36607,7 @@ snapshots:- '@babel/core'- babel-plugin-macros- [email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]):+ [email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]):dependencies:'@next/env': 16.0.7'@swc/helpers': 0.5.15@@ -37477,7 +36615,7 @@ snapshots:postcss: 8.4.31react: 19.2.3react-dom: 19.2.3([email protected])- styled-jsx: 5.1.6(@babel/[email protected])([email protected])+ styled-jsx: 5.1.6(@babel/[email protected])([email protected])optionalDependencies:'@next/swc-darwin-arm64': 16.0.7'@next/swc-darwin-x64': 16.0.7@@ -37824,13 +36962,13 @@ snapshots:dependencies:esm-env: [email protected]- [email protected](patch_hash=4f93812bf7a04685f9477b2935e3acbf2aa24dfbb1b00b9ae0ed8f7a2877a98e)(@tanstack/[email protected]([email protected]([email protected]))([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected]):+ [email protected](patch_hash=4f93812bf7a04685f9477b2935e3acbf2aa24dfbb1b00b9ae0ed8f7a2877a98e)(@tanstack/[email protected]([email protected]([email protected]))([email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected]):dependencies:'@standard-schema/spec': 1.0.0react: 19.2.3optionalDependencies:- next: 16.0.7(@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])+ next: 16.0.7(@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])@@ -39166,56 +38304,6 @@ snapshots:react: 19.2.3react-dom: 19.2.3([email protected])- [email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]):- dependencies:- '@jest/create-cache-key-function': 29.7.0- '@react-native-community/cli': 12.3.6- '@react-native-community/cli-platform-android': 12.3.6- '@react-native-community/cli-platform-ios': 12.3.6- '@react-native/assets-registry': 0.73.1- '@react-native/codegen': 0.73.3(@babel/[email protected](@babel/[email protected]))- '@react-native/community-cli-plugin': 0.73.17(@babel/[email protected])(@babel/[email protected](@babel/[email protected]))- '@react-native/gradle-plugin': 0.73.4- '@react-native/js-polyfills': 0.73.1- '@react-native/normalize-colors': 0.73.2- '@react-native/virtualized-lists': 0.73.4([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))- abort-controller: 3.0.0- anser: 1.4.10- ansi-regex: 5.0.1- base64-js: 1.5.1- chalk: 4.1.2- deprecated-react-native-prop-types: 5.0.0- event-target-shim: 5.0.1- flow-enums-runtime: 0.0.6- invariant: 2.2.4- jest-environment-node: 29.7.0- jsc-android: 250231.0.0- memoize-one: 5.2.1- metro-runtime: 0.80.6- metro-source-map: 0.80.6- mkdirp: 0.5.6- nullthrows: 1.1.1- pretty-format: 26.6.2- promise: 8.3.0- react: 19.2.3- react-devtools-core: 4.28.5- react-refresh: 0.14.0- react-shallow-renderer: 16.15.0([email protected])- regenerator-runtime: 0.13.11- scheduler: 0.24.0-canary-efb381bbf-20230505- stacktrace-parser: 0.1.10- whatwg-fetch: 3.6.20- ws: 6.2.2- yargs: 17.7.2- transitivePeerDependencies:- - '@babel/core'- - '@babel/preset-env'- - bufferutil- - encoding- - supports-color- - utf-8-validate- optional: true-[email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]):dependencies:'@jest/create-cache-key-function': 29.7.0@@ -39274,7 +38362,7 @@ snapshots:dependencies:fast-deep-equal: 2.0.1- [email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))([email protected])([email protected]):+ [email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected]))([email protected])([email protected]):dependencies:'@babel/runtime': 7.23.9'@types/hoist-non-react-statics': 3.3.5@@ -39287,7 +38375,7 @@ snapshots:'@types/react': 19.2.7'@types/react-dom': 19.2.3(@types/[email protected])react-dom: 19.2.3([email protected])- react-native: 0.73.6(@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected])+ react-native: 0.73.6(@babel/[email protected])(@babel/[email protected](@babel/[email protected]))([email protected])redux: 5.0.1@@ -39550,7 +38638,7 @@ snapshots:dependencies:- lodash: 4.17.21+ lodash: 4.18.1dependencies:@@ -40836,12 +39924,12 @@ snapshots:optionalDependencies:'@babel/core': 7.24.5dependencies:client-only: 0.0.1react: 19.2.3optionalDependencies:- '@babel/core': 7.28.3+ '@babel/core': 7.28.5optional: true@@ -41925,7 +41013,7 @@ snapshots:dependencies:- '@types/d3-array': 3.2.1+ '@types/d3-array': 3.2.2'@types/d3-ease': 3.0.2'@types/d3-interpolate': 3.0.4'@types/d3-scale': 4.0.8