OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat(dashboard): new report charts and tables, resizable dashboard tiles (#544)
Carl-Gerhard Lindesvärd7020a8edc55c
diff --git a/apps/start/e2e/overview-helpers.ts b/apps/start/e2e/overview-helpers.tsindex c5c40e85c..085fc0c90 100644--- a/apps/start/e2e/overview-helpers.ts+++ b/apps/start/e2e/overview-helpers.ts@@ -1,7 +1,8 @@import type { Page, TestInfo } from '@playwright/test';export const SHOTS_DIR = 'test-results/overview-shots';-export const API_URL = 'https://api.main.local.openpanel.cc';+export const API_URL =+ process.env.API_URL ?? 'https://api.main.local.openpanel.cc';const API_TIMEOUT_MS = 60_000;export const PROJECT_IDS = ['acme-web',diff --git a/apps/start/e2e/reports-builder.spec.ts b/apps/start/e2e/reports-builder.spec.tsindex 9c5748fbb..53f012507 100644--- a/apps/start/e2e/reports-builder.spec.ts+++ b/apps/start/e2e/reports-builder.spec.ts@@ -242,7 +242,7 @@ test('retention on acme-saas shows the cohort sizes the API returns', async ({const editor = page.locator('#report-editor');for (const cohort of api.slice(1, 6)) {const row = editor- .locator('tr')+ .locator('[data-report-table-row]').filter({ hasText: cohort.cohort_interval }).first();await expect(row).toContainText(String(cohort.sum));diff --git a/apps/start/e2e/reports-helpers.ts b/apps/start/e2e/reports-helpers.tsindex 371fc6f6f..578f63841 100644--- a/apps/start/e2e/reports-helpers.ts+++ b/apps/start/e2e/reports-helpers.ts@@ -1,6 +1,7 @@import type { Page } from '@playwright/test';-export const API_URL = 'https://api.main.local.openpanel.cc';+export const API_URL =+ process.env.API_URL ?? 'https://api.main.local.openpanel.cc';export const ORGANIZATION_ID = 'acme';export const SHOTS_DIR = 'test-results/reports/shots';diff --git a/apps/start/e2e/reports-series-toggle.spec.ts b/apps/start/e2e/reports-series-toggle.spec.tsnew file mode 100644index 000000000..445d66f2d--- /dev/null+++ b/apps/start/e2e/reports-series-toggle.spec.ts@@ -0,0 +1,126 @@+// Toggling a series re-fits the y-axis with a short tween. The visible stroke+// of a series with a dashed tail is drawn from a measured copy of the path,+// so it must be re-measured once the tween settles or it stays where the old+// axis put it while the fill follows the new one.++import type { Locator, Page } from '@playwright/test';+import { expect, test } from './fixtures';+import {+ createDashboard,+ deleteDashboard,+ eventSeries,+ hideFeedbackPrompt,+ reportInput,+ shot,+ trpcMutation,+ waitForChart,+} from './reports-helpers';++const SHOP = 'acme-shop';+const Y_DOMAIN_TWEEN_SETTLE_MS = 1200;++interface StrokePaths {+ measured: string[];+ overlay: string[];+}++/**+ * The series stroke is split in two: a transparent path laid out from the+ * live scales (the measurement source) and the dashed-tail overlay that+ * paints the stroke from the last measurement. Both must agree.+ */+function strokePaths(chart: Locator): Promise<StrokePaths> {+ return chart+ .locator('svg')+ .first()+ .evaluate((svg) => {+ const paths = [...svg.querySelectorAll('path')];+ const unfilled = new Set(['none', 'transparent']);+ const measured = paths+ .filter(+ (path) =>+ path.getAttribute('stroke') === 'transparent' &&+ unfilled.has(path.getAttribute('fill') ?? 'none') &&+ !path.getAttribute('stroke-dasharray')+ )+ .map((path) => path.getAttribute('d') ?? '');+ const overlay = paths+ .filter((path) => path.getAttribute('stroke-dasharray'))+ .map((path) => path.getAttribute('d') ?? '');+ return { measured, overlay };+ });+}++async function expectStrokeFollowsScale(chart: Locator) {+ const { measured, overlay } = await strokePaths(chart);+ expect(overlay.length).toBeGreaterThan(0);+ for (const d of overlay) {+ expect(measured).toContain(d);+ }+}++async function createTwoSeriesReport(+ page: Page,+ dashboardId: string,+ chartType: 'linear' | 'area'+) {+ const { projectId: _projectId, ...report } = reportInput(SHOP, {+ chartType,+ series: eventSeries(['screen_view']),+ breakdowns: [{ id: 'b', name: 'device' }],+ });+ return trpcMutation<{ id: string }>(page, 'report.create', {+ dashboardId,+ report: { ...report, name: `E2E series toggle ${chartType}` },+ });+}++test.use({ actionTimeout: 15_000 });++test.beforeEach(async ({ page }) => {+ test.setTimeout(240_000);+ await hideFeedbackPrompt(page);+ await page.setViewportSize({ width: 1440, height: 1100 });+});++for (const chartType of ['linear', 'area'] as const) {+ test(`${chartType} report: the stroke follows the axis after a series toggle`, async ({+ page,+ }) => {+ const dashboard = await createDashboard(page, SHOP, 'series-toggle');+ try {+ const report = await createTwoSeriesReport(page, dashboard.id, chartType);+ await page.goto(`/acme/${SHOP}/reports/${report.id}`);+ await page.waitForLoadState('networkidle');+ await waitForChart(page);+ const editor = page.locator('#report-editor');+ const chart = editor.locator(`[data-report-chart="${chartType}"]`);+ const visibleSeries = Number(+ await chart.getAttribute('data-visible-series')+ );+ expect(visibleSeries).toBeGreaterThan(1);+ await expectStrokeFollowsScale(chart);++ // The first row is the largest series, so hiding it moves the y-axis the most.+ await editor.getByRole('checkbox').first().click();+ await expect(chart).toHaveAttribute(+ 'data-visible-series',+ String(visibleSeries - 1)+ );+ await page.waitForTimeout(Y_DOMAIN_TWEEN_SETTLE_MS);+ await shot(page, `series-toggle-${chartType}-hidden`);+ await expectStrokeFollowsScale(chart);++ await editor.getByRole('checkbox').first().click();+ await expect(chart).toHaveAttribute(+ 'data-visible-series',+ String(visibleSeries)+ );+ await page.waitForTimeout(Y_DOMAIN_TWEEN_SETTLE_MS);+ await shot(page, `series-toggle-${chartType}-restored`);+ await expectStrokeFollowsScale(chart);+ } finally {+ await deleteDashboard(page, dashboard.id);+ }+ });+}diff --git a/apps/start/e2e/reports-share.spec.ts b/apps/start/e2e/reports-share.spec.tsindex bccca8fa1..9d52171db 100644--- a/apps/start/e2e/reports-share.spec.ts+++ b/apps/start/e2e/reports-share.spec.ts@@ -14,7 +14,8 @@ import {} from './reports-helpers';const SHOP = 'acme-shop';-const DASHBOARD_URL = 'https://main.local.openpanel.cc';+const DASHBOARD_URL =+ process.env.DASHBOARD_URL ?? 'https://main.local.openpanel.cc';const PASSWORD = 'e2e-share-secret';interface ShareSettings {@@ -239,7 +240,7 @@ test('share reports of several chart types and open them logged out', async ({anonymous.page.getByText('E2E reports shared linear')).toBeVisible({ timeout: 45_000 });await expect(- anonymous.page.locator('svg.recharts-surface').first()+ anonymous.page.locator('[data-report-chart="linear"] svg').first()).toBeVisible({ timeout: 45_000 });await shot(anonymous.page, 'share-11-public-report');expect(problems.responses).toEqual([]);diff --git a/apps/start/e2e/verify-b-helpers.ts b/apps/start/e2e/verify-b-helpers.tsindex 1e0d9cef1..8f56017df 100644--- a/apps/start/e2e/verify-b-helpers.ts+++ b/apps/start/e2e/verify-b-helpers.ts@@ -1,8 +1,10 @@import type { Browser, Page } from '@playwright/test';export const SHOTS_DIR = 'test-results/verify-b/shots';-export const API_URL = 'https://api.main.local.openpanel.cc';-export const DASHBOARD_URL = 'https://main.local.openpanel.cc';+export const API_URL =+ process.env.API_URL ?? 'https://api.main.local.openpanel.cc';+export const DASHBOARD_URL =+ process.env.DASHBOARD_URL ?? 'https://main.local.openpanel.cc';export function shot(page: Page, name: string, fullPage = true) {return page.screenshot({ path: `${SHOTS_DIR}/${name}.png`, fullPage });diff --git a/apps/start/e2e/verify-b-interactions.spec.ts b/apps/start/e2e/verify-b-interactions.spec.tsindex 40b37f4ab..257542e88 100644--- a/apps/start/e2e/verify-b-interactions.spec.ts+++ b/apps/start/e2e/verify-b-interactions.spec.ts@@ -55,8 +55,12 @@ function tableRows(editor: Locator) {);}-const drawnLines = (editor: Locator) =>- editor.locator('path.recharts-line-curve').count();+const drawnLines = async (editor: Locator) =>+ Number(+ await editor+ .locator('[data-report-chart="linear"]')+ .getAttribute('data-visible-series')+ );test.use({ actionTimeout: 15_000 });@@ -89,7 +93,7 @@ test('report page: view users from a chart point, series toggles, sorting, searcconst editor = page.locator('#report-editor');// --- view users from a chart point- const surface = editor.locator('svg.recharts-surface').first();+ const surface = editor.locator('[data-report-chart="linear"] svg').first();const box = await surface.boundingBox();if (!box) {throw new Error('chart not drawn');@@ -123,12 +127,11 @@ test('report page: view users from a chart point, series toggles, sorting, searc// --- series toggles (the chart legend itself is not interactive)const before = await tableRows(editor);const checkedBefore = before.filter((row) => row.checked).length;- // Each visible series draws one curve; the chart adds one helper curve.- await expect.poll(() => drawnLines(editor)).toBe(checkedBefore + 1);- await editor.getByRole('checkbox').first().click();await expect.poll(() => drawnLines(editor)).toBe(checkedBefore);await editor.getByRole('checkbox').first().click();- await expect.poll(() => drawnLines(editor)).toBe(checkedBefore + 1);+ await expect.poll(() => drawnLines(editor)).toBe(checkedBefore - 1);+ await editor.getByRole('checkbox').first().click();+ await expect.poll(() => drawnLines(editor)).toBe(checkedBefore);await editor.getByRole('button', { name: 'Unselect All' }).click();await expect.poll(() => drawnLines(editor)).toBe(0);await shot(page, 'item13-unselect-all');@@ -136,7 +139,7 @@ test('report page: view users from a chart point, series toggles, sorting, searcfor (const index of [0, 1]) {await editor.getByRole('checkbox').nth(index).click();}- await expect.poll(() => drawnLines(editor)).toBe(3);+ await expect.poll(() => drawnLines(editor)).toBe(2);// --- sorting on Sum, in the default flat viewconst sumHeader = editor.getByRole('button', { name: /^Sum/i }).first();@@ -166,16 +169,8 @@ test('report page: view users from a chart point, series toggles, sorting, searcapi.series.map((serie) => serie.metrics.sum).sort((a, b) => a - b));- // --- grouped view folds the rows under their series- await editor.getByRole('button', { name: 'Flat', exact: true }).click();- await expect(- editor.getByRole('button', { name: 'Grouped', exact: true })- ).toBeVisible();- await shot(page, 'item13-grouped');- await editor.getByRole('button', { name: 'Grouped', exact: true }).click();-// --- search narrows the rows- await editor.getByPlaceholder('Search...').fill('tablet');+ await editor.getByPlaceholder(/Search/).fill('tablet');await expect.poll(async () => (await tableRows(editor)).map((row) => row.device)).toEqual(['tablet', 'tablet']);@@ -215,9 +210,9 @@ test('dashboard grid: drag, resize, persist, reset layout', async ({// --- resize card one from its bottom-right handleconst layoutSaved = () =>page.waitForResponse((response) =>- response.url().includes('/trpc/report.updateLayout')+ response.url().includes('/trpc/report.updateLayouts'));- const handle = one.locator('.react-resizable-handle').last();+ const handle = one.locator('.react-resizable-handle-se');const handleBox = await handle.boundingBox();if (!(handleBox && initial.one && initial.two)) {throw new Error('grid not laid out');diff --git a/apps/start/e2e/verify-b-share.spec.ts b/apps/start/e2e/verify-b-share.spec.tsindex 44c34f774..0cc97c72d 100644--- a/apps/start/e2e/verify-b-share.spec.ts+++ b/apps/start/e2e/verify-b-share.spec.ts@@ -221,7 +221,9 @@ test('a shared dashboard renders every chart type for an anonymous visitor', asyawait expect(chartCard, chartType).not.toContainText('Select 2 events');}await expect(- card(visitor.page, 'linear').locator('svg.recharts-surface')+ card(visitor.page, 'linear')+ .locator('[data-report-chart="linear"] svg')+ .first()).toBeVisible();await expect(card(visitor.page, 'funnel')).toContainText('product_viewed');await expect(card(visitor.page, 'retention')).toContainText(@@ -261,7 +263,9 @@ test('range and interval controls on a shared dashboard drive the chart queries'});await openShareClientSide(visitor.page, `/share/dashboard/${share.id}`);await expect(- card(visitor.page, 'linear').locator('svg.recharts-surface')+ card(visitor.page, 'linear')+ .locator('[data-report-chart="linear"] svg')+ .first()).toBeVisible({ timeout: 45_000 });await visitor.page@@ -523,7 +527,7 @@ for (const kind of ['dashboard', 'report'] as const) {visitor.page.getByText(reportName('linear'), { exact: true })).toBeVisible({ timeout: 45_000 });await expect(- visitor.page.locator('svg.recharts-surface').first()+ visitor.page.locator('[data-report-chart="linear"] svg').first()).toBeVisible({ timeout: 45_000 });await shot(visitor.page, `item4-${kind}-unlocked`, false);@@ -560,7 +564,9 @@ test('clicking a chart point on a shared report keeps the visitor on the share',});await openShareClientSide(visitor.page, `/share/report/${share.id}`);- const surface = visitor.page.locator('svg.recharts-surface').first();+ const surface = visitor.page+ .locator('[data-report-chart="linear"] svg')+ .first();await expect(surface).toBeVisible({ timeout: 45_000 });await visitor.page.waitForLoadState('networkidle');const box = await surface.boundingBox();diff --git a/apps/start/package.json b/apps/start/package.jsonindex 8d0351d6b..d9df49dd9 100644--- a/apps/start/package.json+++ b/apps/start/package.json@@ -18,6 +18,7 @@"with-env": "dotenv -e ../../.env -c --"},"dependencies": {+ "@base-ui/react": "1.9.0","@better-agent/client": "0.1.0-beta.3","@codemirror/commands": "6.10.1","@codemirror/lang-javascript": "6.2.4",@@ -85,12 +86,17 @@"@trpc/tanstack-react-query": "11.6.0","@visx/curve": "4.0.1-alpha.0","@visx/event": "4.0.1-alpha.0",+ "@visx/geo": "4.0.1-alpha.0","@visx/gradient": "4.0.1-alpha.0","@visx/grid": "4.0.1-alpha.0",+ "@visx/group": "4.0.1-alpha.0",+ "@visx/heatmap": "4.0.1-alpha.0","@visx/pattern": "4.0.1-alpha.0","@visx/responsive": "4.0.1-alpha.0",+ "@visx/sankey": "4.0.1-alpha.0","@visx/scale": "4.0.1-alpha.0","@visx/shape": "4.0.1-alpha.0",+ "@visx/zoom": "4.0.1-alpha.0","bind-event-listener": "3.0.0","class-variance-authority": "0.7.1","clsx": "2.1.1",@@ -98,6 +104,9 @@"codemirror": "6.0.2","d3": "7.8.5","d3-array": "3.2.4",+ "d3-geo": "3.1.1",+ "d3-sankey": "0.12.3",+ "d3-shape": "3.2.0","date-fns": "3.3.1","debounce": "2.2.0","embla-carousel-autoplay": "8.6.0",@@ -126,19 +135,17 @@"react-animated-numbers": "1.1.1","react-day-picker": "9.9.0","react-dom": "catalog:",- "react-grid-layout": "1.5.2",+ "react-grid-layout": "2.3.0","react-hook-form": "7.50.1","react-in-viewport": "1.0.0-beta.8","react-markdown": "10.1.0","react-redux": "8.1.3",- "react-resizable": "3.0.5","react-responsive": "9.0.2","react-simple-maps": "3.0.0","react-svg-worldmap": "2.0.0-alpha.16","react-syntax-highlighter": "15.5.0","react-use-websocket": "4.7.0","react-virtualized-auto-sizer": "1.0.22",- "recharts": "2.15.4","rehype-katex": "7.0.1","remark-gfm": "4.0.1","remark-highlight": "0.1.1",@@ -168,13 +175,16 @@"@testing-library/react": "16.3.0","@types/d3": "7.4.3","@types/d3-array": "3.2.2",+ "@types/d3-geo": "3.1.1",+ "@types/d3-sankey": "0.12.5",+ "@types/d3-shape": "3.2.0",+ "@types/geojson": "7946.0.16","@types/lodash.debounce": "4.0.9","@types/lodash.isequal": "4.5.8","@types/lodash.throttle": "4.1.9","@types/ramda": "0.31.0","@types/react": "catalog:","@types/react-dom": "catalog:",- "@types/react-grid-layout": "1.3.5","@types/react-simple-maps": "3.0.4","@types/react-syntax-highlighter": "15.5.11","@vitejs/plugin-react": "5.2.0",diff --git a/apps/start/src/components/charts/animation.ts b/apps/start/src/components/charts/animation.tsindex 81e42b8d3..186708f5f 100644--- a/apps/start/src/components/charts/animation.ts+++ b/apps/start/src/components/charts/animation.ts@@ -17,7 +17,10 @@ export const DEFAULT_CHART_ENTER_TRANSITION: Transition = {*/export function clipRevealTransition(enterTransition?: Transition): Transition {if (enterTransition?.type === 'tween') {- return enterTransition;+ return {+ ...enterTransition,+ ease: enterTransition.ease ?? DEFAULT_CHART_ENTER_TRANSITION.ease,+ };}const duration =diff --git a/apps/start/src/components/charts/area-chart-loading.tsx b/apps/start/src/components/charts/area-chart-loading.tsxnew file mode 100644index 000000000..2f92d3bd5--- /dev/null+++ b/apps/start/src/components/charts/area-chart-loading.tsx@@ -0,0 +1,116 @@+'use client';++import { curveNatural } from '@visx/curve';+import { useMemo } from 'react';+import { Area } from './area';+import { AreaChart } from './area-chart';+import type { Margin } from './chart-context';+import type { LoadingStyle } from './chart-phase';+import {+ DEFAULT_SKELETON_DATA_KEY,+ DEFAULT_SKELETON_POINT_COUNT,+ generateChartSkeletonData,+} from './generate-chart-skeleton-data';+import { Grid } from './grid';++const LOADING_DATA_KEY = DEFAULT_SKELETON_DATA_KEY;+const DEFAULT_LOADING_STROKE = 'var(--foreground)';+const DEFAULT_LOADING_GRID_STROKE =+ 'color-mix(in oklch, var(--chart-grid) 50%, transparent)';+const DEFAULT_LOADING_GRID_SHIMMER_STROKE =+ 'color-mix(in oklch, var(--foreground) 68%, transparent)';+const DEFAULT_LOADING_STROKE_OPACITY = 0.5;++export interface AreaChartLoadingProps {+ /** Chart margins */+ margin?: Partial<Margin>;+ /** Stroke color for the animated loading segment. */+ stroke?: string;+ /** Stroke opacity for the animated loading segment. Default: 0.5 */+ strokeOpacity?: number;+ /** Grid line stroke (color and opacity via color-mix or oklch alpha). */+ gridStroke?: string;+ /** Shimmer band stroke (color and opacity via color-mix or oklch alpha). */+ gridShimmerStroke?: string;+ /** Animate a shimmer band across grid lines. Default: true */+ gridShimmer?: boolean;+ /** Shimmer band width in pixels. Default: 140 */+ gridShimmerLength?: number;+ /** Shimmer speed multiplier (higher = faster). Default: 1 */+ gridShimmerSpeed?: number;+ /** Match shimmer loop to the loading line pulse (cycle + inter-loop pause). */+ gridShimmerSync?: boolean;+ /** Loading animation: `"pulse"` (default traveling pulse) or `"sweep"` (a+ * diagonal shimmer across the skeleton area). Default: `"pulse"`. */+ loadingStyle?: LoadingStyle;+ /** Centered shimmer label text. Default: "Loading" */+ label?: string;+ /** Aspect ratio as "width / height". Default: "2 / 1" */+ aspectRatio?: string;+ /** Additional class name for the container */+ className?: string;+}++export function AreaChartLoading({+ margin,+ stroke = DEFAULT_LOADING_STROKE,+ strokeOpacity = DEFAULT_LOADING_STROKE_OPACITY,+ gridStroke = DEFAULT_LOADING_GRID_STROKE,+ gridShimmerStroke = DEFAULT_LOADING_GRID_SHIMMER_STROKE,+ gridShimmer = true,+ gridShimmerLength,+ gridShimmerSpeed,+ gridShimmerSync = false,+ loadingStyle = 'pulse',+ label = 'Loading',+ aspectRatio = '2 / 1',+ className = '',+}: AreaChartLoadingProps) {+ const data = useMemo(+ () =>+ generateChartSkeletonData({+ dataKey: DEFAULT_SKELETON_DATA_KEY,+ pointCount: DEFAULT_SKELETON_POINT_COUNT,+ }),+ []+ );++ return (+ <AreaChart+ animationDuration={0}+ aspectRatio={aspectRatio}+ className={className}+ data={data}+ loadingLabel={label}+ margin={margin}+ status="loading"+ >+ <Grid+ horizontal+ shimmer={loadingStyle === 'sweep' ? false : gridShimmer}+ shimmerLength={gridShimmerLength}+ shimmerSpeed={gridShimmerSpeed}+ shimmerStroke={gridShimmerStroke}+ shimmerSync={gridShimmerSync}+ stroke={gridStroke}+ />+ <Area+ curve={curveNatural}+ dataKey={LOADING_DATA_KEY}+ fadeEdges={false}+ fill="transparent"+ fillOpacity={0}+ loading+ loadingStroke={stroke}+ loadingStrokeOpacity={strokeOpacity}+ loadingStyle={loadingStyle}+ showHighlight={false}+ showLine+ stroke="transparent"+ strokeWidth={2}+ />+ </AreaChart>+ );+}++export default AreaChartLoading;diff --git a/apps/start/src/components/charts/area-chart.tsx b/apps/start/src/components/charts/area-chart.tsxindex 9be5d28df..53d1b76bf 100644--- a/apps/start/src/components/charts/area-chart.tsx+++ b/apps/start/src/components/charts/area-chart.tsx@@ -1,16 +1,27 @@'use client';-import { ParentSize } from '@visx/responsive';import type { Transition } from 'motion/react';import {Children,+ type CSSProperties,isValidElement,type ReactNode,+ useCallback,useMemo,useRef,+ useState,} from 'react';import { Area, type AreaProps } from './area';import type { LineConfig, Margin } from './chart-context';+import { ChartLoadingLabel } from './chart-loading-label';+import { ParentSize } from './chart-parent-size';+import {+ type ChartPhase,+ type ChartStatus,+ DEFAULT_CHART_STATUS,+ DEFAULT_Y_DOMAIN_TWEEN_MS,+ resolveRestingChartPhase,+} from './chart-phase';import { PatternArea } from './pattern-area';import { TimeSeriesChartInner } from './time-series-chart-shell';import { cn } from '@/lib/utils';@@ -34,6 +45,26 @@ export interface AreaChartProps {aspectRatio?: string;/** Additional class name for the container */className?: string;+ /** Loading vs ready — drives chart phase and loading chrome. Default: `"ready"`. */+ status?: ChartStatus;+ /** Centered shimmer label while loading. */+ loadingLabel?: string;+ /** Animate y-domain over this duration (ms) on status transitions. Default: 500. */+ yDomainTweenDuration?: number;+ /** Animate y-domain when status or target domain changes. Default: true */+ yDomainTween?: boolean;+ /** Visible x-domain for brush zoom. */+ xDomain?: [Date, Date];+ /** Full dataset length for x-scale padding when `xDomain` is set. */+ xDomainSlotCount?: number;+ /** Tween y-domain when brush changes the visible x-range. Default: false */+ tweenYDomainOnXDomainChange?: boolean;+ /** Inline container styles (e.g. fixed height for brush strip). */+ style?: CSSProperties;+ /** Fires when the internal chart phase changes (e.g. OG capture readiness). */+ onPhaseChange?: (phase: ChartPhase) => void;+ /** Formats the x-axis and crosshair date labels. Default: `shortDateFmt`. */+ formatDateLabel?: (date: Date) => string;/** Child components (Area, Grid, ChartTooltip, etc.) */children: ReactNode;}@@ -73,6 +104,7 @@ function extractAreaConfigs(children: ReactNode): LineConfig[] {dataKey: props.dataKey,stroke: props.stroke || props.fill || 'var(--chart-line-primary)',strokeWidth: props.strokeWidth || 2,+ yAxisId: props.yAxisId,});}});@@ -90,8 +122,17 @@ interface ChartInnerProps {animationEasing?: string;enterTransition?: Transition;revealSignature?: string;+ chartStatus: ChartStatus;+ loadingLabel?: string;+ yDomainTweenDuration: number;+ yDomainTween: boolean;+ xDomain?: [Date, Date];+ xDomainSlotCount?: number;+ tweenYDomainOnXDomainChange?: boolean;children: ReactNode;containerRef: React.RefObject<HTMLDivElement | null>;+ onPhaseChange: (phase: ChartPhase) => void;+ formatDateLabel?: (date: Date) => string;}function ChartInner({@@ -104,8 +145,17 @@ function ChartInner({animationEasing,enterTransition,revealSignature,+ chartStatus,+ loadingLabel,+ yDomainTweenDuration,+ yDomainTween,+ xDomain,+ xDomainSlotCount,+ tweenYDomainOnXDomainChange,children,containerRef,+ onPhaseChange,+ formatDateLabel,}: ChartInnerProps) {const lines = useMemo(() => extractAreaConfigs(children), [children]);@@ -113,16 +163,25 @@ function ChartInner({<TimeSeriesChartInneranimationDuration={animationDuration}animationEasing={animationEasing}+ chartStatus={chartStatus}clipPathId="chart-area-grow-clip"containerRef={containerRef}data={data}enterTransition={enterTransition}+ formatDateLabel={formatDateLabel}height={height}lines={lines}+ loadingLabel={loadingLabel}margin={margin}+ onPhaseChange={onPhaseChange}revealSignature={revealSignature}+ tweenYDomainOnXDomainChange={tweenYDomainOnXDomainChange}width={width}xDataKey={xDataKey}+ xDomain={xDomain}+ xDomainSlotCount={xDomainSlotCount}+ yDomainTween={yDomainTween}+ yDomainTweenDuration={yDomainTweenDuration}>{children}</TimeSeriesChartInner>@@ -139,35 +198,78 @@ export function AreaChart({revealSignature,aspectRatio = '2 / 1',className = '',+ status = DEFAULT_CHART_STATUS,+ loadingLabel,+ yDomainTweenDuration = DEFAULT_Y_DOMAIN_TWEEN_MS,+ yDomainTween = true,+ xDomain,+ xDomainSlotCount,+ tweenYDomainOnXDomainChange = false,+ style,+ onPhaseChange,+ formatDateLabel,children,}: AreaChartProps) {const containerRef = useRef<HTMLDivElement>(null);const margin = { ...DEFAULT_MARGIN, ...marginProp };+ const [chartPhase, setChartPhase] = useState<ChartPhase>(() =>+ resolveRestingChartPhase(status)+ );+ const handlePhaseChange = useCallback(+ (phase: ChartPhase) => {+ setChartPhase(phase);+ onPhaseChange?.(phase);+ },+ [onPhaseChange]+ );++ const showLoadingLabel = Boolean(+ loadingLabel?.trim() &&+ (chartPhase === 'loading' ||+ chartPhase === 'exiting' ||+ chartPhase === 'gridTweenReady' ||+ chartPhase === 'revealingLoading')+ );return (<divclassName={cn('relative w-full', className)}ref={containerRef}- style={{ aspectRatio, touchAction: 'none' }}+ style={{ aspectRatio, touchAction: 'none', ...style }}><ParentSize debounceTime={10}>{({ width, height }) => (<ChartInneranimationDuration={animationDuration}animationEasing={animationEasing}+ chartStatus={status}containerRef={containerRef}data={data}enterTransition={enterTransition}+ formatDateLabel={formatDateLabel}height={height}+ loadingLabel={loadingLabel}margin={margin}+ onPhaseChange={handlePhaseChange}revealSignature={revealSignature}+ tweenYDomainOnXDomainChange={tweenYDomainOnXDomainChange}width={width}xDataKey={xDataKey}+ xDomain={xDomain}+ xDomainSlotCount={xDomainSlotCount}+ yDomainTween={yDomainTween}+ yDomainTweenDuration={yDomainTweenDuration}>{children}</ChartInner>)}</ParentSize>+ {showLoadingLabel ? (+ <ChartLoadingLabel+ exiting={chartPhase !== 'loading'}+ text={loadingLabel}+ />+ ) : null}</div>);}diff --git a/apps/start/src/components/charts/area-gradient-defs.tsx b/apps/start/src/components/charts/area-gradient-defs.tsxindex 26f589d22..4da7c7bb6 100644--- a/apps/start/src/components/charts/area-gradient-defs.tsx+++ b/apps/start/src/components/charts/area-gradient-defs.tsx@@ -2,6 +2,7 @@ import {type FadeEdges,fadeGradientStops,resolveFadeSides,+ viewportFadeGradientAttrs,} from './fade-edges';interface AreaGradientDefsProps {@@ -12,6 +13,8 @@ interface AreaGradientDefsProps {fill: string;fillOpacity: number;gradientToOpacity: number;+ /** 0–1: where the bottom stop sits (1 = full-height gradient). */+ gradientSpan?: number;resolvedStroke: string;isPatternFill: boolean;fadeEdges: FadeEdges;@@ -27,6 +30,7 @@ export function AreaGradientDefs({fill,fillOpacity,gradientToOpacity,+ gradientSpan = 1,resolvedStroke,isPatternFill,fadeEdges,@@ -40,6 +44,8 @@ export function AreaGradientDefs({const strokeStops = sides.any ? fadeGradientStops(sides) : null;const showEdgeMask = sides.any && !isPatternFill;const edgeStops = showEdgeMask ? fadeGradientStops(sides) : null;+ const span = Math.min(1, Math.max(0.01, gradientSpan));+ const midOffset = `${span * 100}%`;return (<defs>@@ -50,14 +56,23 @@ export function AreaGradientDefs({style={{ stopColor: fill, stopOpacity: fillOpacity }}/><stop- offset="100%"+ offset={midOffset}style={{ stopColor: fill, stopOpacity: gradientToOpacity }}/>+ {span < 1 ? (+ <stop+ offset="100%"+ style={{ stopColor: fill, stopOpacity: gradientToOpacity }}+ />+ ) : null}</linearGradient>)}{strokeStops ? (- <linearGradient id={strokeGradientId} x1="0%" x2="100%" y1="0%" y2="0%">+ <linearGradient+ id={strokeGradientId}+ {...viewportFadeGradientAttrs(innerWidth)}+ >{strokeStops.map((stop) => (<stopkey={stop.offset}@@ -70,7 +85,10 @@ export function AreaGradientDefs({{edgeStops ? (<>- <linearGradient id={edgeGradientId} x1="0%" x2="100%" y1="0%" y2="0%">+ <linearGradient+ id={edgeGradientId}+ {...viewportFadeGradientAttrs(innerWidth)}+ >{edgeStops.map((stop) => (<stopkey={stop.offset}diff --git a/apps/start/src/components/charts/area.tsx b/apps/start/src/components/charts/area.tsxindex 3758e5930..1d2b9d80a 100644--- a/apps/start/src/components/charts/area.tsx+++ b/apps/start/src/components/charts/area.tsx@@ -7,10 +7,18 @@ import { AreaClosed, LinePath } from '@visx/shape';// biome-ignore lint/suspicious/noExplicitAny: d3 curve factory typetype CurveFactory = any;-import { useCallback, useId, useRef } from 'react';+import { useCallback, useId, useMemo, useRef, useState } from 'react';import { AreaGradientDefs } from './area-gradient-defs';-import { chartCssVars, useChartStable } from './chart-context';+import { chartCssVars, useChartStable, useYScale } from './chart-context';+import type { ChartPhase, LoadingStyle } from './chart-phase';import { type FadeEdges, resolveFadeSides } from './fade-edges';+import {+ type LineLoadingPulseMode,+ LineLoadingPulseStroke,+ resolveLineLoadingPulseMode,+} from './line-loading-pulse';+import { LINE_LOADING_LOOP_PAUSE_MS } from './line-loading-timing';+import { LineLoadingSweep } from './loading-sweep';import {resolveDashTailBounds,usePathStrokeMetrics,@@ -24,6 +32,10 @@ import type { SeriesPointMarkerStyle } from './series-point-marker';export interface AreaProps {/** Key in data to use for y values */dataKey: string;+ /** Key holding each point's baseline, for stacked areas. Default: the chart's zero line. */+ baselineKey?: string;+ /** Y-scale group id (Recharts `yAxisId`). Default: `"left"`. */+ yAxisId?: string | number;/** 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 */@@ -42,6 +54,11 @@ export interface AreaProps {showHighlight?: boolean;/** Gradient opacity at bottom (0 = fully transparent). Default: 0 */gradientToOpacity?: number;+ /**+ * Vertical extent of the fill gradient (0–1). `1` fades across the full+ * height; lower values compress the gradient toward the top.+ */+ gradientSpan?: number;/*** Fade the area fill (and stroke) toward transparent at the chart edges.* - `true` fades both edges, `false` disables the fade entirely.@@ -61,10 +78,67 @@ export interface AreaProps {dashFromIndex?: number;/** Dash pattern for the tail segment when `dashFromIndex` is set. Default: "6,4" */dashArray?: string;+ /** Pulse stroke color while chart is loading. Default: var(--foreground) */+ loadingStroke?: string;+ /** Pulse stroke opacity while chart is loading. Default: 0.5 */+ loadingStrokeOpacity?: number;+ /**+ * Show the loading pulse overlay. Default: follows chart loading phase.+ * Set `false` to disable even during loading.+ */+ loading?: boolean;+ /** Override pulse animation mode (loop / exit / enter). */+ loadingPulseMode?: LineLoadingPulseMode;+ /**+ * Loading animation while the chart is in loading status: the default+ * traveling `"pulse"`, or a diagonal `"sweep"` shimmer across the skeleton+ * area. Default: `"pulse"`.+ */+ loadingStyle?: LoadingStyle;}+function useAreaLoadingPulseState(+ chartPhase: ChartPhase,+ loading: boolean | undefined,+ loadingPulseMode: LineLoadingPulseMode | undefined,+ notifyLoadingPulseComplete?: () => void+) {+ const phasePulseMode = resolveLineLoadingPulseMode(chartPhase);+ const pulseMode =+ loading === false+ ? null+ : (loadingPulseMode ?? (loading === true ? 'loop' : phasePulseMode));+ const showLoadingPulse = pulseMode != null;+ const showSeriesContent =+ chartPhase === 'revealing' ||+ chartPhase === 'ready' ||+ chartPhase === 'exitingReady';+ const [pulseEpoch, setPulseEpoch] = useState(0);++ const handleLoadingPulseComplete = useCallback(() => {+ if (pulseMode === 'loop') {+ window.setTimeout(() => {+ setPulseEpoch((epoch) => epoch + 1);+ }, LINE_LOADING_LOOP_PAUSE_MS);+ return;+ }+ notifyLoadingPulseComplete?.();+ }, [notifyLoadingPulseComplete, pulseMode]);++ return {+ handleLoadingPulseComplete,+ pulseMode,+ pulseEpoch,+ showLoadingPulse,+ showSeriesContent,+ };+}++// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: mirrors Line series layout (fill, stroke, dash, markers, pulse)export function Area({dataKey,+ baselineKey,+ yAxisId,fill = chartCssVars.linePrimary,fillOpacity = 0.4,stroke,@@ -74,31 +148,67 @@ export function Area({showLine = true,showHighlight = true,gradientToOpacity = 0,+ gradientSpan = 1,fadeEdges = false,showMarkers = false,markers,dashFromIndex,dashArray = '6,4',+ loading,+ loadingStroke = chartCssVars.foreground,+ loadingStrokeOpacity = 0.5,+ loadingPulseMode,+ loadingStyle = 'pulse',}: 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 a single shared clipPath at the chart-shell level- // (`time-series-chart-shell.tsx`).+ // 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,+ lines,+ chartPhase,+ notifyLoadingPulseComplete,} = useChartStable();+ const yScale = useYScale(yAxisId);+ const {+ handleLoadingPulseComplete,+ pulseMode,+ pulseEpoch,+ showLoadingPulse,+ showSeriesContent,+ } = useAreaLoadingPulseState(+ chartPhase,+ loading,+ loadingPulseMode,+ notifyLoadingPulseComplete+ );++ const seriesIndex = useMemo(() => {+ const index = lines.findIndex((line) => line.dataKey === dataKey);+ return index >= 0 ? index : 0;+ }, [lines, dataKey]);const pathRef = useRef<SVGPathElement>(null);- const pathMetricsKey = `${renderData.length}:${innerWidth}:${dashFromIndex}:${showLine}`;- const { pathLength, pathD } = usePathStrokeMetrics(pathRef, pathMetricsKey);+ const { pathLength, pathD } = usePathStrokeMetrics(pathRef, [+ renderData,+ innerWidth,+ innerHeight,+ yScale,+ dashFromIndex,+ showLine,+ showSeriesContent,+ showLoadingPulse,+ ]);+ // Unique IDs for this areaconst uniqueId = useId();const gradientId = `area-gradient-${dataKey}-${uniqueId}`;const strokeGradientId = `area-stroke-gradient-${dataKey}-${uniqueId}`;@@ -120,6 +230,15 @@ export function Area({},[dataKey, yScale]);++ const getBaseline = useCallback(+ (d: Record<string, unknown>) => {+ const value = baselineKey ? d[baselineKey] : undefined;+ return yScale(typeof value === 'number' ? value : 0) ?? 0;+ },+ [baselineKey, yScale]+ );+const hasValue = useCallback((d: Record<string, unknown>) => typeof d[dataKey] === 'number',[dataKey]@@ -129,10 +248,73 @@ export function Area({// 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;+ const useViewportEdgeFade = fadeSides.any && !isPatternFill;+ let strokePaint = resolvedStroke;+ if (!useViewportEdgeFade && fadeSides.any) {+ strokePaint = `url(#${strokeGradientId})`;+ }+ const highlightEnabled =+ showHighlight && showLine && !showLoadingPulse && showSeriesContent;+ const showSeriesStroke = showSeriesContent && showLine;+ let visibleStroke = 'transparent';+ if (showSeriesStroke && !hasDashTail) {+ visibleStroke = strokePaint;+ }+ const shouldMeasurePath = showLine && (showSeriesContent || showLoadingPulse);++ const seriesLayers = (+ <>+ {showSeriesContent && showAreaFill ? (+ <AreaClosed+ curve={curve}+ data={renderData}+ defined={hasValue}+ fill={areaFill}+ x={(d) => xScale(xAccessor(d)) ?? 0}+ y={getY}+ y0={baselineKey ? getBaseline : undefined}+ yScale={yScale}+ />+ ) : null}++ {shouldMeasurePath ? (+ <>+ <LinePath+ curve={curve}+ data={renderData}+ defined={hasValue}+ innerRef={pathRef}+ stroke={visibleStroke}+ strokeLinecap="round"+ strokeWidth={strokeWidth}+ x={(d) => xScale(xAccessor(d)) ?? 0}+ y={getY}+ />+ {showSeriesStroke ? (+ <SeriesDashTailOverlay+ dashArray={dashArray}+ dashFromIndex={dashFromIndex}+ data={data}+ innerHeight={innerHeight}+ innerWidth={innerWidth}+ pathD={pathD}+ pathLength={pathLength}+ stroke={strokePaint}+ strokeWidth={strokeWidth}+ xAccessor={xAccessor}+ xScale={xScale}+ />+ ) : null}+ </>+ ) : null}+ </>+ );++ // Sweep style owns all loading modes (loop + the exit/enter transitions),+ // drawing its own silhouette; the pulse covers the default style.+ const sweepLoading =+ showLoadingPulse && innerWidth > 0 && loadingStyle === 'sweep';+ const pulseLoading = showLoadingPulse && innerWidth > 0 && !sweepLoading;return (<>@@ -143,6 +325,7 @@ export function Area({fill={fill}fillOpacity={fillOpacity}gradientId={gradientId}+ gradientSpan={gradientSpan}gradientToOpacity={gradientToOpacity}innerHeight={innerHeight}innerWidth={innerWidth}@@ -151,55 +334,16 @@ export function Area({strokeGradientId={strokeGradientId}/>- <SeriesHoverDim dimOpacity={0.6} enabled={showHighlight}>- {showAreaFill ? (- <g- mask={- fadeSides.any && !isPatternFill- ? `url(#${edgeMaskId})`- : undefined- }- >- <AreaClosed- curve={curve}- data={renderData}- defined={hasValue}- fill={areaFill}- x={(d) => xScale(xAccessor(d)) ?? 0}- y={getY}- yScale={yScale}- />- </g>- ) : null}-- {showLine ? (- <>- <LinePath- curve={curve}- data={renderData}- defined={hasValue}- 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+ dimOpacity={0.6}+ enabled={showHighlight}+ seriesIndex={seriesIndex}+ >+ {useViewportEdgeFade ? (+ <g mask={`url(#${edgeMaskId})`}>{seriesLayers}</g>+ ) : (+ seriesLayers+ )}</SeriesHoverDim>{/* Highlight segment on hover — isolated hover subscriber. */}@@ -211,7 +355,7 @@ export function Area({strokeWidth={strokeWidth}/>- {showMarkers ? (+ {showMarkers && showSeriesContent ? (<SeriesMarkersanimate={animate}dataKey={dataKey}@@ -220,6 +364,31 @@ export function Area({stroke={markers?.stroke ?? markers?.fill ?? resolvedStroke}/>) : null}++ {sweepLoading ? (+ <LineLoadingSweep+ curve={curve}+ key="loading-sweep"+ mode={pulseMode ?? 'loop'}+ onTransitionComplete={handleLoadingPulseComplete}+ stroke={loadingStroke}+ strokeOpacity={loadingStrokeOpacity}+ strokeWidth={strokeWidth}+ withArea+ />+ ) : null}+ {pulseLoading && pathD ? (+ <LineLoadingPulseStroke+ key="loading-pulse"+ loopEpoch={pulseEpoch}+ mode={pulseMode ?? undefined}+ onCycleComplete={handleLoadingPulseComplete}+ pathD={pathD}+ stroke={loadingStroke}+ strokeOpacity={loadingStrokeOpacity}+ strokeWidth={strokeWidth}+ />+ ) : null}</>);}diff --git a/apps/start/src/components/charts/background.tsx b/apps/start/src/components/charts/background.tsxnew file mode 100644index 000000000..f969c83cd--- /dev/null+++ b/apps/start/src/components/charts/background.tsx@@ -0,0 +1,219 @@+'use client';++import { motion } from 'motion/react';+import { useId, useMemo } from 'react';+import { useChartStable } from './chart-context';+import {+ type PatternPresetId,+ type PatternPresetOptions,+ renderPatternPreset,+} from './pattern-preset';++export type BackgroundPatternPreset = PatternPresetId;++export interface BackgroundProps extends PatternPresetOptions {+ /** Pattern preset. `"none"` renders nothing. */+ pattern?: BackgroundPatternPreset;+ /** Pattern stroke color. Default: `var(--chart-grid)` */+ color?: string;+ /** Apply the pattern texture to the plot area. Default: true */+ showFill?: boolean;+ /** Pattern fill opacity. Default: 1 */+ opacity?: number;+ /** Fade pattern at the left and right chart edges. Default: true */+ fadeHorizontal?: boolean;+ /** Fade pattern at the top and bottom chart edges. Default: true */+ fadeVertical?: boolean;+ /** Horizontal fade zone as % of plot width per edge. Default: 10 */+ fadeHorizontalLength?: number;+ /** Vertical fade zone as % of plot height per edge. Default: 10 */+ fadeVerticalLength?: number;+}++const BACKGROUND_ENTER_FADE_MS = 420;++function clampFadeLength(length: number): number {+ return Math.min(45, Math.max(0, length));+}++function fadeMaskStops(lengthPercent: number): Array<{+ offset: string;+ opacity: number;+}> {+ const edge = clampFadeLength(lengthPercent);+ return [+ { offset: '0%', opacity: 0 },+ { offset: `${edge}%`, opacity: 1 },+ { offset: `${100 - edge}%`, opacity: 1 },+ { offset: '100%', opacity: 0 },+ ];+}++/** Plot-area pattern fill for charts without a grid. Renders behind series layers. */+export function Background({+ pattern = 'diagonal',+ color = 'var(--chart-grid)',+ scale = 1,+ strokeWidth,+ radius,+ complement,+ fill,+ dotFill,+ tileBackground,+ showFill = true,+ opacity = 1,+ fadeHorizontal = true,+ fadeVertical = true,+ fadeHorizontalLength = 10,+ fadeVerticalLength = 10,+}: BackgroundProps) {+ const { innerWidth, innerHeight, isLoaded, enterTransition } =+ useChartStable();+ const uniqueId = useId();+ const patternId = `chart-background-${uniqueId.replace(/:/g, '')}`;++ const hStops = useMemo(+ () => fadeMaskStops(fadeHorizontalLength),+ [fadeHorizontalLength]+ );+ const vStops = useMemo(+ () => fadeMaskStops(fadeVerticalLength),+ [fadeVerticalLength]+ );++ if (pattern === 'none' || !showFill || innerWidth <= 0 || innerHeight <= 0) {+ return null;+ }++ const patternNode = renderPatternPreset(pattern, patternId, {+ color,+ scale,+ strokeWidth,+ radius,+ complement,+ fill,+ dotFill,+ tileBackground,+ });+ if (!patternNode) {+ return null;+ }++ const fadeMask = fadeHorizontal || fadeVertical;+ const hMaskId = `chart-background-fade-h-${uniqueId.replace(/:/g, '')}`;+ const hGradientId = `${hMaskId}-gradient`;+ const vMaskId = `chart-background-fade-v-${uniqueId.replace(/:/g, '')}`;+ const vGradientId = `${vMaskId}-gradient`;+ const combinedMaskId = `chart-background-fade-${uniqueId.replace(/:/g, '')}`;++ let maskRef: string | undefined;+ if (fadeHorizontal && fadeVertical) {+ maskRef = `url(#${combinedMaskId})`;+ } else if (fadeHorizontal) {+ maskRef = `url(#${hMaskId})`;+ } else if (fadeVertical) {+ maskRef = `url(#${vMaskId})`;+ }++ const targetOpacity = opacity;+ const revealOpacity = isLoaded ? targetOpacity : 0;+ const enterFade =+ enterTransition && typeof enterTransition === 'object'+ ? enterTransition+ : { duration: BACKGROUND_ENTER_FADE_MS / 1000, ease: 'easeOut' as const };++ return (+ // biome-ignore lint/a11y/noAriaHiddenOnFocusable: decorative plot-area pattern layer+ <g aria-hidden="true" className="chart-background">+ {fadeMask ? (+ <defs>+ {fadeHorizontal ? (+ <>+ <linearGradient+ id={hGradientId}+ x1="0%"+ x2="100%"+ y1="0%"+ y2="0%"+ >+ {hStops.map((stop) => (+ <stop+ key={stop.offset}+ offset={stop.offset}+ style={{ stopColor: 'white', stopOpacity: stop.opacity }}+ />+ ))}+ </linearGradient>+ <mask id={hMaskId}>+ <rect+ fill={`url(#${hGradientId})`}+ height={innerHeight}+ width={innerWidth}+ x={0}+ y={0}+ />+ </mask>+ </>+ ) : null}+ {fadeVertical ? (+ <>+ <linearGradient+ id={vGradientId}+ x1="0%"+ x2="0%"+ y1="0%"+ y2="100%"+ >+ {vStops.map((stop) => (+ <stop+ key={stop.offset}+ offset={stop.offset}+ style={{ stopColor: 'white', stopOpacity: stop.opacity }}+ />+ ))}+ </linearGradient>+ <mask id={vMaskId}>+ <rect+ fill={`url(#${vGradientId})`}+ height={innerHeight}+ width={innerWidth}+ x={0}+ y={0}+ />+ </mask>+ </>+ ) : null}+ {fadeHorizontal && fadeVertical ? (+ <mask id={combinedMaskId}>+ <g mask={`url(#${hMaskId})`}>+ <rect+ fill={`url(#${vGradientId})`}+ height={innerHeight}+ width={innerWidth}+ x={0}+ y={0}+ />+ </g>+ </mask>+ ) : null}+ </defs>+ ) : null}+ <defs>{patternNode}</defs>+ <motion.rect+ animate={{ opacity: revealOpacity }}+ fill={`url(#${patternId})`}+ height={innerHeight}+ initial={{ opacity: 0 }}+ mask={maskRef}+ transition={isLoaded ? enterFade : { duration: 0 }}+ width={innerWidth}+ x={0}+ y={0}+ />+ </g>+ );+}++Background.displayName = 'Background';++export default Background;diff --git a/apps/start/src/components/charts/bar-chart-loading.tsx b/apps/start/src/components/charts/bar-chart-loading.tsxnew file mode 100644index 000000000..b82d058c7--- /dev/null+++ b/apps/start/src/components/charts/bar-chart-loading.tsx@@ -0,0 +1,38 @@+'use client';++import { BarChart } from './bar-chart';+import type { Margin } from './chart-context';++const EMPTY_DATA: Record<string, unknown>[] = [];++export interface BarChartLoadingProps {+ /** Chart margins. */+ margin?: Partial<Margin>;+ /** Aspect ratio as "width / height". Default: "2 / 1" */+ aspectRatio?: string;+ /** Additional class name for the container. */+ className?: string;+}++/**+ * Turnkey loading skeleton for bar charts, a thin shortcut for+ * `<BarChart status="loading" />`. Renders shimmer-swept placeholder bars while+ * data is fetching; swap in a real `<BarChart>` once it resolves.+ */+export function BarChartLoading({+ margin,+ aspectRatio = '2 / 1',+ className = '',+}: BarChartLoadingProps) {+ return (+ <BarChart+ aspectRatio={aspectRatio}+ className={className}+ data={EMPTY_DATA}+ margin={margin}+ status="loading"+ />+ );+}++export default BarChartLoading;diff --git a/apps/start/src/components/charts/bar-chart.tsx b/apps/start/src/components/charts/bar-chart.tsxindex 6633b3387..512ad24a9 100644--- a/apps/start/src/components/charts/bar-chart.tsx+++ b/apps/start/src/components/charts/bar-chart.tsx@@ -1,12 +1,9 @@'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,@@ -18,6 +15,16 @@ import {} from 'react';import { DEFAULT_ANIMATION_EASING } from './animation';import type { BarProps } from './bar';+import { topSquareCenterY } from './bar-squares-layout';+import {+ forEachChartChild,+ isChartClipPassthrough,+ isClipExcludedComponent,+ isPostOverlayComponent,+ isUnderlayComponent,+ renderKeyedChartLayers,+ resolveChartChildElement,+} from './chart-child-passthrough';import {ChartProvider,type LineConfig,@@ -26,9 +33,27 @@ import {} from './chart-context';import { isGradientDefComponent, isPatternDefComponent } from './chart-defs';import { shortDateFmt } from './chart-formatters';+import { ParentSize } from './chart-parent-size';+import {+ type ChartPhase,+ type ChartStatus,+ DEFAULT_CHART_LIFECYCLE,+ resolveRestingChartPhase,+} from './chart-phase';+import { BarLoadingSkeleton } from './loading-sweep';+import { extractReferenceAreaConfigs } from './reference-area-config';import { useScheduledTooltip } from './use-scheduled-tooltip';+import {+ buildYScalesForLines,+ getPrimaryYScale,+ normalizeYAxisId,+ wrapSingleYScale,+} from './y-axis-scales';import { cn } from '@/lib/utils';+/** Skeleton bars to show when `status="loading"` and `data` is empty. */+const FALLBACK_LOADING_BARS = 12;+export type BarOrientation = 'vertical' | 'horizontal';export interface BarChartProps {@@ -60,24 +85,36 @@ export interface BarChartProps {stacked?: boolean;/** Gap between stacked bar segments in pixels. Default: 0 */stackGap?: number;- /** Child components (Bar, Grid, ChartTooltip, etc.) */- children: ReactNode;+ /** When set, tooltip Y positions snap to the top square center (shape variant). */+ squareSnap?: { squareGap: number; groupGap?: number; fit?: boolean };+ /** Child components (Bar, Grid, ChartTooltip, etc.). Optional — omit for a+ * pure `status="loading"` skeleton. */+ children?: ReactNode;+ /** Reports reveal lifecycle for OG screenshots and loading orchestration. */+ onPhaseChange?: (phase: ChartPhase) => void;+ /** Fetch / display status. When `"loading"`, a shimmer skeleton replaces the+ * bars (no chart data required). Default: `"ready"`. */+ status?: ChartStatus;}const DEFAULT_MARGIN: Margin = { top: 40, right: 40, bottom: 40, left: 40 };+// Extract bar configs from children synchronouslyfunction extractBarConfigs(children: ReactNode): LineConfig[] {const configs: LineConfig[] = [];- Children.forEach(children, (child) => {- if (!isValidElement(child)) {- return;- }-+ forEachChartChild(children, (child) => {const childType = child.type as {displayName?: string;name?: string;+ __isBarDepthLayer?: boolean;};+ // Bar-depth surface layers (BarDepthBack/Front, BarPulse) carry a+ // `dataKey` to pair with a Bar but are not series themselves — skip them+ // so they don't inflate the series count and shrink the real bars.+ if (childType.__isBarDepthLayer) {+ return;+ }const componentName =typeof child.type === 'function'? childType.displayName || childType.name || ''@@ -86,6 +123,7 @@ function extractBarConfigs(children: ReactNode): LineConfig[] {const props = child.props as BarProps | undefined;const isBarComponent =componentName === 'Bar' ||+ componentName === 'BarSquares' ||(props && typeof props.dataKey === 'string' && props.dataKey.length > 0);if (isBarComponent && props?.dataKey) {@@ -97,6 +135,7 @@ function extractBarConfigs(children: ReactNode): LineConfig[] {dataKey: props.dataKey,stroke: dotColor,strokeWidth: 0,+ yAxisId: props.yAxisId,});}});@@ -104,25 +143,6 @@ function extractBarConfigs(children: ReactNode): LineConfig[] {return configs;}-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;@@ -138,8 +158,11 @@ interface ChartInnerProps {orientation: BarOrientation;stacked: boolean;stackGap: number;+ squareSnap?: { squareGap: number; groupGap?: number; fit?: boolean };children: ReactNode;containerRef: React.RefObject<HTMLDivElement | null>;+ onPhaseChange?: (phase: ChartPhase) => void;+ status: ChartStatus;}function ChartInner(props: ChartInnerProps) {@@ -165,8 +188,11 @@ const ChartCore = memo(function ChartCore({orientation,stacked,stackGap,+ squareSnap,children,containerRef,+ onPhaseChange,+ status,}: ChartInnerProps) {const { tooltipData, setTooltipData, scheduleTooltip, clearTooltip } =useScheduledTooltip<TooltipData>();@@ -176,11 +202,13 @@ const ChartCore = memo(function ChartCore({const isHorizontal = orientation === 'horizontal';+ // Extract bar configs synchronously from childrenconst 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 scaleconst categoryAccessor = useCallback((d: Record<string, unknown>): string => {const value = d[xDataKey];@@ -204,6 +232,7 @@ const ChartCore = memo(function ChartCore({[xDataKey]);+ // Category scale (band) - for the categorical axisconst categoryScale = useMemo(() => {const domain = data.map((d) => categoryAccessor(d));const range: [number, number] = isHorizontal@@ -216,10 +245,13 @@ const ChartCore = memo(function ChartCore({});}, [innerWidth, innerHeight, data, categoryAccessor, barGap, isHorizontal]);+ // Band width for bars - use prop if provided, otherwise use scale's bandwidthconst bandWidth = barWidthProp ?? categoryScale.bandwidth();+ // Compute max value considering stackingconst maxValue = useMemo(() => {if (stacked) {+ // For stacked bars, sum all values at each data pointlet max = 0;for (const d of data) {let sum = 0;@@ -235,6 +267,7 @@ const ChartCore = memo(function ChartCore({}return max || 100;}+ // For grouped bars, find max single valuelet max = 0;for (const line of lines) {for (const d of data) {@@ -247,6 +280,7 @@ const ChartCore = memo(function ChartCore({return max || 100;}, [data, lines, stacked]);+ // Value scale (linear) - for the value axisconst valueScale = useMemo(() => {const range = isHorizontal ? [0, innerWidth] : [innerHeight, 0];return scaleLinear({@@ -256,6 +290,32 @@ const ChartCore = memo(function ChartCore({});}, [innerWidth, innerHeight, maxValue, isHorizontal]);+ const yScales = useMemo(() => {+ if (isHorizontal) {+ return wrapSingleYScale(valueScale);+ }+ return buildYScalesForLines({+ lines,+ data,+ innerHeight,+ resolveDomain: (dataKeys) => {+ let max = 0;+ for (const d of data) {+ for (const key of dataKeys) {+ const value = d[key];+ if (typeof value === 'number' && value > max) {+ max = value;+ }+ }+ }+ return [0, (max || 100) * 1.1];+ },+ });+ }, [data, innerHeight, isHorizontal, lines, valueScale]);++ const primaryYScale = getPrimaryYScale(yScales, valueScale);++ // Compute stack offsets for stacked barsconst stackOffsets = useMemo(() => {if (!stacked) {return undefined;@@ -313,12 +373,23 @@ const ChartCore = memo(function ChartCore({useEffect(() => {setRevealEpoch((n) => n + 1);setIsLoaded(false);+ // While loading, hold the skeleton (no reveal, no interaction). When+ // status flips to "ready" this effect re-runs and plays the grow reveal.+ if (status === 'loading') {+ return;+ }+ const staggerMs = data.length > 1 ? animationDuration * 0.4 : 0;const timer = setTimeout(() => {setIsLoaded(true);- }, animationDuration);+ }, animationDuration + staggerMs);return () => clearTimeout(timer);- }, [animationDuration, revealSignature]);+ }, [animationDuration, revealSignature, status]);++ useEffect(() => {+ onPhaseChange?.(isLoaded ? 'ready' : 'revealing');+ }, [isLoaded, onPhaseChange]);+ // Mouse move handlerconst handleMouseMove = useCallback((event: React.MouseEvent<SVGGElement>) => {const point = localPoint(event);@@ -328,6 +399,7 @@ const ChartCore = memo(function ChartCore({const pos = isHorizontal ? point.y - margin.top : point.x - margin.left;+ // Find which band the mouse is overconst bandIndex = Math.floor(pos / columnWidth);const clampedIndex = Math.max(0, Math.min(data.length - 1, bandIndex));const d = data[clampedIndex];@@ -336,6 +408,7 @@ const ChartCore = memo(function ChartCore({return;}+ // Calculate positions for each barconst yPositions: Record<string, number> = {};const xPositions: Record<string, number> = {};const barPos = categoryScale(categoryAccessor(d)) ?? 0;@@ -356,7 +429,9 @@ const ChartCore = memo(function ChartCore({const value = d[line.dataKey];if (typeof value === 'number') {cumulative += value;- xPositions[line.dataKey] = valueScale(cumulative) ?? 0;+ const axisScale =+ yScales[normalizeYAxisId(line.yAxisId)] ?? valueScale;+ xPositions[line.dataKey] = axisScale(cumulative) ?? 0;yPositions[line.dataKey] = barPos + bandWidth / 2;}}@@ -365,7 +440,9 @@ const ChartCore = memo(function ChartCore({lines.forEach((line, idx) => {const value = d[line.dataKey];if (typeof value === 'number') {- xPositions[line.dataKey] = valueScale(value) ?? 0;+ const axisScale =+ yScales[normalizeYAxisId(line.yAxisId)] ?? valueScale;+ xPositions[line.dataKey] = axisScale(value) ?? 0;yPositions[line.dataKey] =barPos +idx * (individualBarHeight + groupGap) +@@ -374,19 +451,22 @@ const ChartCore = memo(function ChartCore({});}} else if (stacked) {+ // Vertical stacked barslet cumulative = 0;let seriesIdx = 0;for (const line of lines) {const value = d[line.dataKey];if (typeof value === 'number') {cumulative += value;+ const axisScale =+ yScales[normalizeYAxisId(line.yAxisId)] ?? primaryYScale;const gapOffset = seriesIdx * stackGap;- yPositions[line.dataKey] =- (valueScale(cumulative) ?? 0) - gapOffset;+ yPositions[line.dataKey] = (axisScale(cumulative) ?? 0) - gapOffset;seriesIdx++;}}} else {+ // Vertical grouped barsconst seriesCount = lines.length;const groupGap = seriesCount > 1 ? 4 : 0;const individualBarWidth =@@ -397,7 +477,24 @@ const ChartCore = memo(function ChartCore({lines.forEach((line, idx) => {const value = d[line.dataKey];if (typeof value === 'number') {- yPositions[line.dataKey] = valueScale(value) ?? 0;+ const axisScale =+ yScales[normalizeYAxisId(line.yAxisId)] ?? primaryYScale;+ const baselineY = axisScale(0) ?? innerHeight;+ const valueY = axisScale(value) ?? 0;+ const barLengthPx = baselineY - valueY;++ if (squareSnap && !isHorizontal && value > 0) {+ yPositions[line.dataKey] = topSquareCenterY({+ baselineY,+ barLengthPx,+ squareSize: individualBarWidth,+ gap: squareSnap.squareGap,+ fit: squareSnap.fit,+ });+ } else {+ yPositions[line.dataKey] = valueY;+ }+xPositions[line.dataKey] =barPos +idx * (individualBarWidth + groupGap) +@@ -409,6 +506,7 @@ const ChartCore = memo(function ChartCore({// Tooltip position: for horizontal, position at max bar end; for vertical, center of bandlet tooltipX: number;if (isHorizontal) {+ // Position tooltip at the end of the longest barconst maxX = Math.max(...Object.values(xPositions), 0);tooltipX = maxX;} else {@@ -437,6 +535,10 @@ const ChartCore = memo(function ChartCore({stacked,stackGap,scheduleTooltip,+ yScales,+ primaryYScale,+ squareSnap,+ innerHeight,]);@@ -446,33 +548,49 @@ const ChartCore = memo(function ChartCore({const canInteract = isLoaded;+ // Separate children into defs, pre-overlay, and post-overlayconst defsChildren: ReactElement[] = [];+ const clipExcludedChildren: ReactElement[] = [];+ const underlayChildren: ReactElement[] = [];const preOverlayChildren: ReactElement[] = [];const postOverlayChildren: ReactElement[] = [];- Children.forEach(children, (child) => {- if (!isValidElement(child)) {- return;- }+ forEachChartChild(children, (child) => {+ const resolvedChild = resolveChartChildElement(child);if (isGradientDefComponent(child)) {defsChildren.push(child);} else if (isPatternDefComponent(child)) {preOverlayChildren.push(child);- } else if (isPostOverlayComponent(child)) {- postOverlayChildren.push(child);+ } else if (isPostOverlayComponent(resolvedChild)) {+ postOverlayChildren.push(resolvedChild);+ } else if (isClipExcludedComponent(resolvedChild)) {+ clipExcludedChildren.push(+ isChartClipPassthrough(child.type) ? resolvedChild : child+ );+ } else if (isUnderlayComponent(resolvedChild)) {+ underlayChildren.push(resolvedChild);} else {preOverlayChildren.push(child);}});+ const referenceAreas = useMemo(+ () => extractReferenceAreaConfigs(children),+ [children]+ );+const contextValue = {+ ...DEFAULT_CHART_LIFECYCLE,+ chartPhase: resolveRestingChartPhase(status),+ chartStatus: status,data,renderData: data,xScale: fakeTimeScale as unknown as ReturnType<typeof import('@visx/scale').scaleTime<number>>,- yScale: valueScale,+ yScale: isHorizontal ? valueScale : primaryYScale,+ yScales,width,height,innerWidth,@@ -483,6 +601,7 @@ const ChartCore = memo(function ChartCore({setTooltipData,containerRef,lines,+ referenceAreas,isLoaded,animationDuration,animationEasing,@@ -498,11 +617,18 @@ const ChartCore = memo(function ChartCore({orientation,stacked,stackOffsets,+ squareSnap,};return (<ChartProvider value={contextValue}>- <svg aria-hidden="true" height={height} width={width}>+ <svg+ aria-hidden="true"+ className="overflow-visible"+ 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} />@@ -514,6 +640,7 @@ const ChartCore = memo(function ChartCore({style={{ cursor: canInteract ? 'crosshair' : 'default' }}transform={`translate(${margin.left},${margin.top})`}>+ {/* Background rect for mouse event detection */}<rectfill="transparent"height={innerHeight}@@ -522,10 +649,20 @@ const ChartCore = memo(function ChartCore({y={0}/>- {preOverlayChildren}+ {renderKeyedChartLayers(clipExcludedChildren)}+ {renderKeyedChartLayers(underlayChildren)}+ {status === 'loading' ? (+ <BarLoadingSkeleton+ barCount={data.length || FALLBACK_LOADING_BARS}+ innerHeight={innerHeight}+ innerWidth={innerWidth}+ />+ ) : (+ renderKeyedChartLayers(preOverlayChildren)+ )}{/* Markers rendered last so they're on top for interaction */}- {postOverlayChildren}+ {renderKeyedChartLayers(postOverlayChildren)}</g></svg></ChartProvider>@@ -547,14 +684,17 @@ export function BarChart({orientation = 'vertical',stacked = false,stackGap = 0,+ squareSnap,children,+ onPhaseChange,+ status = 'ready',}: BarChartProps) {const containerRef = useRef<HTMLDivElement>(null);const margin = { ...DEFAULT_MARGIN, ...marginProp };return (<div- className={cn('relative w-full', className)}+ className={cn('relative w-full overflow-visible', className)}ref={containerRef}style={{ aspectRatio }}>@@ -570,10 +710,13 @@ export function BarChart({enterTransition={enterTransition}height={height}margin={margin}+ onPhaseChange={onPhaseChange}orientation={orientation}revealSignature={revealSignature}+ squareSnap={squareSnap}stacked={stacked}stackGap={stackGap}+ status={status}width={width}xDataKey={xDataKey}>diff --git a/apps/start/src/components/charts/bar-depth-geometry.ts b/apps/start/src/components/charts/bar-depth-geometry.tsnew file mode 100644index 000000000..91f76f7e5--- /dev/null+++ b/apps/start/src/components/charts/bar-depth-geometry.ts@@ -0,0 +1,44 @@+/**+ * Shared 3D bar-depth geometry — the single source of truth for the+ * perspective math used by BOTH `<Bar perspective>` (which shrinks a+ * bar's front-face top) AND the bar-depth surfaces (`<BarDepthBack>`'s side ++ * lid). Keeping the formula here means the front face and the 3D lid can never+ * drift out of alignment.+ */++/** Hard ceiling on side-face thickness in px. Capped further by the column gap+ * so depth never bleeds past the next bar's leading edge. */+export const BAR_DEPTH_MAX_PX = 7;+/** The side parallelogram's back edge lifts by `depth * this ratio`, giving a+ * subtle head-on perspective slope. */+export const BAR_DEPTH_PERSPECTIVE_RATIO = 0.45;++/**+ * Maximum side-face depth in px for a chart, clamped so depth never spills past+ * the gap between bars. `stepWidth` is d3-scaleBand's `step()` (bandwidth ++ * gap); `bandWidth` is a single bar's width. Returns 0 for gapless/dense charts.+ */+export function barDepthMaxDepth(stepWidth: number, bandWidth: number): number {+ const gap = Math.max(0, stepWidth - bandWidth);+ return Math.min(bandWidth * 0.22, Math.max(0, gap - 1), BAR_DEPTH_MAX_PX);+}++/**+ * Per-bar side-face depth + perspective rise.+ *+ * - `absOffset` ∈ [0, 1]: the bar's normalized distance from the chart's+ * horizontal center. 0 = dead center (no depth); 1 = chart edge (full depth).+ * - `naturalHeight`: the bar's pixel height. Depth is capped by it so a short+ * bar's side never reads wider than the bar is tall.+ * - `maxDepth`: from `barDepthMaxDepth`.+ */+export function barDepthAndRise(+ absOffset: number,+ naturalHeight: number,+ maxDepth: number+): { depth: number; perspectiveRise: number } {+ const offset = Math.min(1, Math.max(0, absOffset));+ const cappedMaxDepth = Math.min(maxDepth, Math.max(0, naturalHeight));+ const depth = offset * cappedMaxDepth;+ return { depth, perspectiveRise: depth * BAR_DEPTH_PERSPECTIVE_RATIO };+}diff --git a/apps/start/src/components/charts/bar-squares-layout.ts b/apps/start/src/components/charts/bar-squares-layout.tsnew file mode 100644index 000000000..956155119--- /dev/null+++ b/apps/start/src/components/charts/bar-squares-layout.ts@@ -0,0 +1,99 @@+export interface SquareColumnLayout {+ /** Number of squares in the column */+ count: number;+ /** Top-left Y of each square, bottom square first (relative to bar top at 0) */+ positions: number[];+ /** Quantized column height in pixels */+ columnHeight: number;+ squareSize: number;+ /** Effective gap between squares (may differ when fit mode redistributes) */+ gap: number;+}++export interface SquareColumnInput {+ /** Raw bar length in pixels (baseline − value) */+ barLengthPx: number;+ /** Square width/height — typically equals bar width */+ squareSize: number;+ /** Gap between stacked squares in pixels */+ gap: number;+ /** When true, redistribute gap so column height matches barLengthPx exactly */+ fit?: boolean;+}++/** Quantize bar length into a stack of square cells. */+export function computeSquareColumn({+ barLengthPx,+ squareSize,+ gap,+ fit = false,+}: SquareColumnInput): SquareColumnLayout {+ if (barLengthPx <= 0 || squareSize <= 0) {+ return { count: 0, positions: [], columnHeight: 0, squareSize, gap };+ }++ if (fit) {+ const count = Math.max(+ 1,+ Math.floor((barLengthPx + gap) / (squareSize + gap))+ );+ const effectiveGap =+ count > 1+ ? Math.max(0, (barLengthPx - count * squareSize) / (count - 1))+ : 0;+ const step = squareSize + effectiveGap;+ const columnHeight = barLengthPx;+ const positions: number[] = [];++ for (let i = 0; i < count; i++) {+ positions.push(columnHeight - squareSize - i * step);+ }++ return {+ count,+ positions,+ columnHeight,+ squareSize,+ gap: effectiveGap,+ };+ }++ const step = squareSize + gap;+ const count = Math.max(1, Math.round(barLengthPx / step));+ const columnHeight = count * squareSize + Math.max(0, count - 1) * gap;++ const positions: number[] = [];+ for (let i = 0; i < count; i++) {+ const offsetFromBottom = i * step;+ positions.push(columnHeight - squareSize - offsetFromBottom);+ }++ return { count, positions, columnHeight, squareSize, gap };+}++/** Y center of the topmost square in a vertical column. */+export function topSquareCenterY({+ baselineY,+ barLengthPx,+ squareSize,+ gap,+ fit = false,+}: SquareColumnInput & { baselineY: number }): number {+ const {+ count,+ squareSize: size,+ columnHeight,+ } = computeSquareColumn({+ barLengthPx,+ squareSize,+ gap,+ fit,+ });++ if (count === 0) {+ return baselineY;+ }++ const topY = baselineY - columnHeight;+ return topY + size / 2;+}diff --git a/apps/start/src/components/charts/bar-squares.tsx b/apps/start/src/components/charts/bar-squares.tsxnew file mode 100644index 000000000..b442349f3--- /dev/null+++ b/apps/start/src/components/charts/bar-squares.tsx@@ -0,0 +1,644 @@+'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 { computeSquareColumn } from './bar-squares-layout';+import {+ chartCssVars,+ useChart,+ useChartStable,+ useYScale,+} from './chart-context';+import { useChartLegendHover } from './chart-legend-hover';+import { transitionWithDelay } from './motion-utils';+import { type PatternPresetId, renderPatternPreset } from './pattern-preset';++type ScaleBand<Domain extends { toString(): string }> = ReturnType<+ typeof scaleBand<Domain>+>;++export interface GradientStop {+ offset: number;+ color: string;+}++export interface BarSquaresProps {+ dataKey: string;+ yAxisId?: string | number;+ /** Fill color, gradient url, or pattern url. Default: var(--chart-line-primary) */+ fill?: string;+ /**+ * Datum key holding a per-column color. When the datum has a string there,+ * it replaces `fill` for that column and solid-fills it (no gradient).+ */+ colorKey?: string;+ /** Tooltip dot / ring stroke color when fill is gradient/pattern */+ stroke?: string;+ /** Gap between stacked squares in pixels. Default: 3 */+ squareGap?: number;+ /** Corner radius as a fraction of square size (0 = flat, 0.5 = circle). Default: 0.25 */+ squareRadius?: number;+ /** Redistribute gap so columns fit bar height exactly */+ squareFit?: boolean;+ /** Apply bar-spanning gradient from gradientStops */+ useGradient?: boolean;+ gradientStops?: GradientStop[];+ /** Pattern preset when fill is a pattern (for gradient tinting) */+ patternPreset?: PatternPresetId;+ animate?: boolean;+ fadedOpacity?: number;+ staggerDelay?: number;+ groupGap?: number;+}++export interface BarColumnTrackProps {+ /** Fill color or pattern url. Default: var(--chart-grid) */+ fill?: string;+ opacity?: number;+ squareGap?: number;+ /** Corner radius fraction (matches squares). Default: 0.25 */+ squareRadius?: number;+ groupGap?: number;+ squareFit?: boolean;+ staggerDelay?: number;+}++interface BarSquaresInnerProps extends BarSquaresProps {+ barScale: ScaleBand<string>;+ bandWidth: number;+ barXAccessor: (d: Record<string, unknown>) => string;+}++interface SquareColumnProps {+ x: number;+ baselineY: number;+ barLengthPx: number;+ squareSize: number;+ squareGap: number;+ squareRadius: number;+ squareFit: boolean;+ fill: string;+ useGradient: boolean;+ gradientStops: GradientStop[];+ patternPreset?: PatternPresetId;+ index: number;+ isFaded: boolean;+ fadedOpacity: number;+ animate: boolean;+ staggerDelay: number;+ animationDuration: number;+ enterTransition?: Transition;+ revealEpoch: number;+}++function isPatternFill(fill: string): boolean {+ return fill.startsWith('url(');+}++/** Delay between stacked squares within one column (bottom → top). */+function squareCascadeStepSeconds(+ enterTransition: Transition | undefined,+ animationDurationMs: number,+ squareCount: number+): number {+ if (squareCount <= 1) {+ return 0;+ }+ const durationMs =+ enterTransition?.type === 'tween' &&+ typeof enterTransition.duration === 'number'+ ? enterTransition.duration * 1000+ : animationDurationMs;+ const cascadeSpreadMs = durationMs * 0.4;+ return cascadeSpreadMs / 1000 / (squareCount - 1);+}++function cascadeColumnTransition(+ enterTransition: Transition | undefined,+ animationDurationMs: number,+ columnIndex: number,+ columnStaggerDelay: number,+ squareCount: number+): Transition {+ const cascadeStep = squareCascadeStepSeconds(+ enterTransition,+ animationDurationMs,+ squareCount+ );+ const base = transitionWithDelay(+ enterTransition,+ columnIndex * columnStaggerDelay+ );+ if (squareCount <= 1 || base.type !== 'tween') {+ return base;+ }+ const baseDuration =+ typeof base.duration === 'number'+ ? base.duration+ : animationDurationMs / 1000;+ return {+ ...base,+ duration: baseDuration + cascadeStep * (squareCount - 1),+ };+}++function SquareColumn({+ x,+ baselineY,+ barLengthPx,+ squareSize,+ squareGap,+ squareRadius,+ squareFit,+ fill,+ useGradient,+ gradientStops,+ patternPreset,+ index,+ isFaded,+ fadedOpacity,+ animate,+ staggerDelay,+ animationDuration,+ enterTransition,+ revealEpoch,+}: SquareColumnProps) {+ const layout = useMemo(+ () =>+ computeSquareColumn({+ barLengthPx,+ squareSize,+ gap: squareGap,+ fit: squareFit,+ }),+ [barLengthPx, squareSize, squareGap, squareFit]+ );++ const rx = squareSize * squareRadius;+ const columnTop = baselineY - layout.columnHeight;+ const gradientId = `bar-squares-gradient-${index}-${revealEpoch}`;+ const patternFill = isPatternFill(fill);+ const patternId = `bar-squares-pattern-${index}-${revealEpoch}`;++ const effectiveFill = useMemo(() => {+ if (useGradient) {+ if (patternFill && patternPreset && patternPreset !== 'none') {+ return `url(#${patternId})`;+ }+ return `url(#${gradientId})`;+ }+ return fill;+ }, [useGradient, patternFill, patternPreset, fill, gradientId, patternId]);++ const cascadeStep = squareCascadeStepSeconds(+ enterTransition,+ animationDuration,+ layout.count+ );+ const squareOpacity = isFaded ? fadedOpacity : 1;++ const gradientPatternNode =+ useGradient && patternFill && patternPreset && patternPreset !== 'none'+ ? renderPatternPreset(patternPreset, patternId, {+ color: `url(#${gradientId})`,+ })+ : null;++ const gradientDefs = useGradient ? (+ <defs>+ <linearGradient+ gradientUnits="userSpaceOnUse"+ id={gradientId}+ x1={0}+ x2={0}+ y1={baselineY}+ y2={columnTop}+ >+ {gradientStops.map((stop) => (+ <stop+ key={`${stop.offset}-${stop.color}`}+ offset={`${stop.offset}%`}+ stopColor={stop.color}+ />+ ))}+ </linearGradient>+ {gradientPatternNode}+ </defs>+ ) : null;++ const squares = layout.positions.map((relY, squareIndex) => {+ const y = columnTop + relY;+ const bottomY = y + squareSize;+ const key = `sq-${index}-${squareIndex}-${revealEpoch}`;++ if (!animate) {+ return (+ <rect+ fill={effectiveFill}+ height={squareSize}+ key={key}+ opacity={squareOpacity}+ rx={rx}+ ry={rx}+ width={squareSize}+ x={x}+ y={y}+ />+ );+ }++ return (+ <motion.rect+ animate={{ attrY: y, height: squareSize, opacity: squareOpacity }}+ fill={effectiveFill}+ height={squareSize}+ initial={{ attrY: bottomY, height: 0, opacity: 1 }}+ key={key}+ rx={rx}+ ry={rx}+ transition={{+ ...transitionWithDelay(+ enterTransition,+ index * staggerDelay + squareIndex * cascadeStep+ ),+ opacity: { duration: 0.15 },+ }}+ width={squareSize}+ x={x}+ />+ );+ });++ return (+ <>+ {gradientDefs}+ {squares}+ </>+ );+}++const BarSquaresInner = memo(function BarSquaresInner({+ dataKey,+ yAxisId,+ fill = chartCssVars.linePrimary,+ colorKey,+ squareGap = 3,+ squareRadius = 0.25,+ squareFit = false,+ useGradient = false,+ gradientStops = [],+ patternPreset,+ animate = true,+ fadedOpacity = 0.3,+ staggerDelay,+ groupGap = 4,+ barScale,+ bandWidth,+ barXAccessor,+}: BarSquaresInnerProps) {+ const {+ data,+ innerHeight,+ hoveredBarIndex,+ lines,+ orientation,+ stacked,+ animationDuration,+ enterTransition,+ revealEpoch = 0,+ } = useChart();++ const { hoveredIndex: legendHoveredIndex } = useChartLegendHover();+ const uniqueId = useId();++ const isHorizontal = orientation === 'horizontal';+ const isUnsupported = isHorizontal || stacked;++ const seriesIndex = useMemo(() => {+ const idx = lines.findIndex((l) => l.dataKey === dataKey);+ return idx >= 0 ? idx : 0;+ }, [lines, dataKey]);++ const seriesConfig = lines[seriesIndex];+ const valueScale = useYScale(yAxisId ?? seriesConfig?.yAxisId);++ const isLegendDimmed =+ legendHoveredIndex !== null && legendHoveredIndex !== seriesIndex;++ const seriesCount = lines.length;+ const squareSize = useMemo(() => {+ if (!bandWidth || seriesCount === 0) {+ return 0;+ }+ const effectiveGroupGap = seriesCount > 1 ? groupGap : 0;+ return (bandWidth - effectiveGroupGap * (seriesCount - 1)) / seriesCount;+ }, [bandWidth, seriesCount, groupGap]);++ const totalAnimDuration = animationDuration || 1100;+ const staggerSpread = totalAnimDuration * 0.4;+ const calculatedStaggerDelay =+ staggerDelay ?? (data.length > 1 ? staggerSpread / 1000 / data.length : 0);++ const baselineY = valueScale(0) ?? innerHeight;+ const stops =+ gradientStops.length >= 2+ ? gradientStops+ : [+ { offset: 0, color: fill },+ { offset: 100, color: fill },+ ];++ if (isUnsupported) {+ return null;+ }++ return (+ <g className={`bar-squares-${uniqueId}`}>+ {data.map((d, i) => {+ const value = d[dataKey];+ if (typeof value !== 'number' || value <= 0) {+ return null;+ }++ const categoryValue = barXAccessor(d);+ const bandPos = barScale(categoryValue) ?? 0;+ const effectiveGroupGap = seriesCount > 1 ? groupGap : 0;+ const x = bandPos + seriesIndex * (squareSize + effectiveGroupGap);++ const valuePos = valueScale(value) ?? 0;+ const barLengthPx = baselineY - valuePos;++ const isFaded =+ (hoveredBarIndex !== null && hoveredBarIndex !== i) || isLegendDimmed;++ const columnColor = colorKey ? d[colorKey] : undefined;+ const hasColumnColor = typeof columnColor === 'string';++ return (+ <SquareColumn+ animate={animate}+ animationDuration={animationDuration || 1100}+ barLengthPx={barLengthPx}+ baselineY={baselineY}+ enterTransition={enterTransition}+ fadedOpacity={fadedOpacity}+ fill={hasColumnColor ? columnColor : fill}+ gradientStops={stops}+ index={i}+ isFaded={isFaded}+ key={`bar-squares-${dataKey}-${categoryValue}`}+ patternPreset={patternPreset}+ revealEpoch={revealEpoch}+ squareFit={squareFit}+ squareGap={squareGap}+ squareRadius={squareRadius}+ squareSize={squareSize}+ staggerDelay={calculatedStaggerDelay}+ useGradient={useGradient && !hasColumnColor}+ x={x}+ />+ );+ })}+ </g>+ );+});++export function BarSquares(props: BarSquaresProps) {+ const { barScale, bandWidth, barXAccessor } = useChartStable();++ if (!(barScale && bandWidth && barXAccessor)) {+ console.warn('BarSquares must be used within a BarChart');+ return null;+ }++ return (+ <BarSquaresInner+ {...props}+ bandWidth={bandWidth}+ barScale={barScale}+ barXAccessor={barXAccessor}+ />+ );+}++BarSquares.displayName = 'BarSquares';++const BarColumnTrackInner = memo(function BarColumnTrackInner({+ fill = chartCssVars.grid,+ opacity = 0.3,+ squareGap = 3,+ squareRadius = 0.25,+ squareFit = false,+ groupGap = 4,+ staggerDelay,+ barScale,+ bandWidth,+ barXAccessor,+}: BarColumnTrackProps & {+ barScale: ScaleBand<string>;+ bandWidth: number;+ barXAccessor: (d: Record<string, unknown>) => string;+}) {+ const {+ data,+ lines,+ orientation,+ stacked,+ hoveredBarIndex,+ animationDuration,+ enterTransition,+ revealEpoch = 0,+ } = useChart();+ const uniqueId = useId();++ const isHorizontal = orientation === 'horizontal';+ const isUnsupported = isHorizontal || stacked;+ const seriesCount = lines.length;++ const squareSize = useMemo(() => {+ if (!bandWidth || seriesCount === 0) {+ return 0;+ }+ const effectiveGroupGap = seriesCount > 1 ? groupGap : 0;+ return (bandWidth - effectiveGroupGap * (seriesCount - 1)) / seriesCount;+ }, [bandWidth, seriesCount, groupGap]);++ const totalAnimDuration = animationDuration || 1100;+ const staggerSpread = totalAnimDuration * 0.4;+ const calculatedStaggerDelay =+ staggerDelay ?? (data.length > 1 ? staggerSpread / 1000 / data.length : 0);++ if (isUnsupported) {+ return null;+ }++ const rx = squareSize * squareRadius;+ const effectiveOpacity = hoveredBarIndex === null ? opacity : 0;++ return (+ <g+ className={`bar-column-track-${uniqueId}`}+ style={{ transition: 'opacity 0.15s ease-in-out' }}+ >+ {data.map((d, i) => {+ const categoryValue = barXAccessor(d);+ const bandPos = barScale(categoryValue) ?? 0;+ const effectiveGroupGap = seriesCount > 1 ? groupGap : 0;++ return lines.map((line, seriesIndex) => (+ <TrackColumn+ animate+ bandPos={bandPos}+ d={d}+ dataKey={line.dataKey}+ effectiveGroupGap={effectiveGroupGap}+ effectiveOpacity={effectiveOpacity}+ enterTransition={enterTransition}+ fill={fill}+ index={i}+ key={`track-${i}-${line.dataKey}`}+ revealEpoch={revealEpoch}+ rx={rx}+ seriesIndex={seriesIndex}+ squareFit={squareFit}+ squareGap={squareGap}+ squareSize={squareSize}+ staggerDelay={calculatedStaggerDelay}+ yAxisId={line.yAxisId}+ />+ ));+ })}+ </g>+ );+});++function TrackColumn({+ d,+ dataKey,+ yAxisId,+ bandPos,+ seriesIndex,+ effectiveGroupGap,+ squareSize,+ squareGap,+ squareFit,+ fill,+ rx,+ effectiveOpacity,+ index,+ staggerDelay,+ animate,+ enterTransition,+ revealEpoch,+}: {+ d: Record<string, unknown>;+ dataKey: string;+ yAxisId?: string | number;+ bandPos: number;+ seriesIndex: number;+ effectiveGroupGap: number;+ squareSize: number;+ squareGap: number;+ squareFit: boolean;+ fill: string;+ rx: number;+ effectiveOpacity: number;+ index: number;+ staggerDelay: number;+ animate: boolean;+ enterTransition?: Transition;+ revealEpoch: number;+}) {+ const { innerHeight, animationDuration: chartAnimationDuration } = useChart();+ const valueScale = useYScale(yAxisId);+ const value = d[dataKey];++ if (typeof value !== 'number' || value <= 0) {+ return null;+ }++ const baselineY = valueScale(0) ?? innerHeight;+ const valuePos = valueScale(value) ?? 0;+ const barLengthPx = baselineY - valuePos;+ const layout = computeSquareColumn({+ barLengthPx,+ squareSize,+ gap: squareGap,+ fit: squareFit,+ });+ const columnTop = baselineY - layout.columnHeight;+ const trackHeight = Math.max(0, columnTop);++ if (trackHeight <= 0 && !animate) {+ return null;+ }++ const x = bandPos + seriesIndex * (squareSize + effectiveGroupGap);+ const enterAnim = cascadeColumnTransition(+ enterTransition,+ chartAnimationDuration || 1100,+ index,+ staggerDelay,+ layout.count+ );+ const animatedHeight = trackHeight > 0 ? trackHeight : 0;++ if (animate) {+ return (+ <motion.rect+ animate={{ height: animatedHeight, y: 0 }}+ fill={fill}+ height={animatedHeight}+ initial={{ height: baselineY, y: 0 }}+ key={`track-${index}-${seriesIndex}-${revealEpoch}`}+ opacity={effectiveOpacity}+ rx={rx}+ ry={rx}+ transition={enterAnim}+ width={squareSize}+ x={x}+ />+ );+ }++ if (trackHeight <= 0) {+ return null;+ }++ return (+ <rect+ fill={fill}+ height={trackHeight}+ opacity={effectiveOpacity}+ rx={rx}+ ry={rx}+ width={squareSize}+ x={x}+ y={0}+ />+ );+}++export function BarColumnTrack(props: BarColumnTrackProps) {+ const { barScale, bandWidth, barXAccessor } = useChartStable();++ if (!(barScale && bandWidth && barXAccessor)) {+ console.warn('BarColumnTrack must be used within a BarChart');+ return null;+ }++ return (+ <BarColumnTrackInner+ {...props}+ bandWidth={bandWidth}+ barScale={barScale}+ barXAccessor={barXAccessor}+ />+ );+}++BarColumnTrack.displayName = 'BarColumnTrack';++export default BarSquares;diff --git a/apps/start/src/components/charts/bar.tsx b/apps/start/src/components/charts/bar.tsxindex fc2b4848e..8fe28ec3d 100644--- a/apps/start/src/components/charts/bar.tsx+++ b/apps/start/src/components/charts/bar.tsx@@ -4,7 +4,14 @@ 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 { barDepthAndRise, barDepthMaxDepth } from './bar-depth-geometry';+import {+ chartCssVars,+ useChart,+ useChartStable,+ useYScale,+} from './chart-context';+import { useChartLegendHover } from './chart-legend-hover';import { transitionWithDelay } from './motion-utils';type ScaleBand<Domain extends { toString(): string }> = ReturnType<@@ -14,9 +21,41 @@ type ScaleBand<Domain extends { toString(): string }> = ReturnType<export type BarLineCap = 'round' | 'butt' | number;export type BarAnimationType = 'grow' | 'fade';+// ── Bar-depth perspective trim ───────────────────────────────────────────+// Uses the SHARED geometry (`bar-depth-geometry.ts`) so a+// `<Bar perspective>` front face lines up exactly with+// `<BarDepthBack>`'s lid — the formula lives in one place for both.++/** perspectiveRise for a positive bar whose visual top sits at `topY`.+ * Returns 0 for a dead-center bar or a dense chart (degenerate depth). */+function barDepthPerspectiveRise(+ barScale: ScaleBand<string>,+ bandWidth: number,+ barXAccessor: (d: Record<string, unknown>) => string,+ innerWidth: number,+ datum: Record<string, unknown>,+ topY: number,+ baselineY: number+): number {+ const centerX = innerWidth / 2;+ if (centerX <= 0) {+ return 0;+ }+ const step =+ (barScale as unknown as { step?: () => number }).step?.() ?? bandWidth;+ const maxDepth = barDepthMaxDepth(step, bandWidth);+ const bandX = barScale(barXAccessor(datum)) ?? 0;+ const cx = bandX + bandWidth / 2;+ const absOffset = Math.min(1, Math.abs((cx - centerX) / centerX));+ const naturalHeight = Math.abs(baselineY - topY);+ return barDepthAndRise(absOffset, naturalHeight, maxDepth).perspectiveRise;+}+export interface BarProps {/** Key in data to use for y values */dataKey: string;+ /** Y-scale group id for vertical bars (Recharts `yAxisId`). Default: `"left"`. */+ yAxisId?: string | number;/** 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 */@@ -35,6 +74,15 @@ export interface BarProps {stackGap?: number;/** Gap between grouped bars in pixels. Default: 4 */groupGap?: number;+ /** Shrink each positive bar's top by its perspective rise so the front face+ * lines up with `<BarDepthBack>`'s lid (instead of the lid sitting above the+ * front face). Pass `true` whenever the chart also renders the bar-depth 3D+ * surfaces. Default: false */+ perspective?: boolean;+ /** Minimum rendered bar height in px (non-stacked, vertical). Floors short or+ * zero-value bars so they stay visible. Pair with the same value on+ * `<BarDepthProvider minBarHeight>` when using the 3D surfaces. Default: 0 */+ minBarHeight?: number;}interface BarInnerProps extends BarProps {@@ -130,6 +178,7 @@ function AnimatedBar({const BarInner = memo(function BarInner({dataKey,+ yAxisId,fill = chartCssVars.linePrimary,lineCap = 'round',animate = true,@@ -138,14 +187,17 @@ const BarInner = memo(function BarInner({staggerDelay,stackGap = 0,groupGap = 4,+ perspective = false,+ minBarHeight = 0,barScale,bandWidth,barXAccessor,}: BarInnerProps) {const {data,- yScale,+ yScale: chartYScale,innerHeight,+ innerWidth,isLoaded,hoveredBarIndex,lines,@@ -157,35 +209,54 @@ const BarInner = memo(function BarInner({revealEpoch = 0,} = useChart();+ // Calculate stagger delay automatically if not provided// Total animation duration is ~1200ms, with 40% for stagger spread and 60% for bar animationconst totalAnimDuration = animationDuration || 1100;- const staggerSpread = totalAnimDuration * 0.4;+ const staggerSpread = totalAnimDuration * 0.4; // 40% of time for stagger spreadconst 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 { hoveredIndex: legendHoveredIndex } = useChartLegendHover();+const seriesIndex = useMemo(() => {const idx = lines.findIndex((l) => l.dataKey === dataKey);return idx >= 0 ? idx : 0;}, [lines, dataKey]);+ const seriesConfig = lines[seriesIndex];+ const valueScale = useYScale(yAxisId ?? seriesConfig?.yAxisId);++ const isLegendDimmed =+ legendHoveredIndex !== null && legendHoveredIndex !== seriesIndex;+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 widthreturn 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. Perspective bars force a flat+ // top (radius 0) so the 3D lid from `<BarDepthBack>` meets the bar with no+ // gap — rounded corners would leave a wedge, so `perspective` overrides it.const cornerRadius = useMemo(() => {+ if (perspective) {+ return 0;+ }if (typeof lineCap === 'number') {return lineCap;}@@ -193,7 +264,7 @@ const BarInner = memo(function BarInner({return Math.min(barWidth / 2, 8);}return 0;- }, [lineCap, barWidth]);+ }, [lineCap, barWidth, perspective]);return (<g className={`bar-series-${uniqueId}`}>@@ -211,16 +282,19 @@ const BarInner = memo(function BarInner({let barHeight: number;let barW: number;+ const scale = isHorizontal ? chartYScale : valueScale;+if (isHorizontal) {// Horizontal bars: category on y-axis, value on x-axis- const valuePos = yScale(value) ?? 0;+ const valuePos = scale(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;+ x = scale(offset) ?? 0;barW = valuePos - x;+ // Apply stack gap for horizontal: shift right and reduce widthconst gapOffset = seriesIndex * stackGap;x += gapOffset;if (!isLastSeries && stackGap > 0) {@@ -228,6 +302,7 @@ const BarInner = memo(function BarInner({}} else {x = 0;+ // For grouped bars, offset y positionconst effectiveGroupGap = seriesCount > 1 ? groupGap : 0;y = bandPos + seriesIndex * (barWidth + effectiveGroupGap);}@@ -237,13 +312,14 @@ const BarInner = memo(function BarInner({seriesIndex * (barWidth + (seriesCount > 1 ? groupGap : 0));} else {// Vertical bars: category on x-axis, value on y-axis- const valuePos = yScale(value) ?? 0;+ const valuePos = scale(value) ?? 0;barHeight = innerHeight - valuePos;barW = barWidth;if (stacked && stackOffsets) {const offset = stackOffsets.get(i)?.get(dataKey) ?? 0;- const offsetY = yScale(offset) ?? innerHeight;+ const offsetY = scale(offset) ?? innerHeight;+ // Apply stack gap: shift up and reduce heightconst gapOffset = seriesIndex * stackGap;y = offsetY - barHeight - gapOffset;// Reduce height slightly for non-last bars to create visual gap@@ -252,6 +328,7 @@ const BarInner = memo(function BarInner({}} else {y = valuePos;+ // For grouped bars, offset x positionconst effectiveGroupGap = seriesCount > 1 ? groupGap : 0;x = bandPos + seriesIndex * (barWidth + effectiveGroupGap);}@@ -259,9 +336,54 @@ const BarInner = memo(function BarInner({? bandPos: bandPos +seriesIndex * (barWidth + (seriesCount > 1 ? groupGap : 0));++ // Minimum visible height — floor short/zero non-stacked bars so a+ // zero-value data point still reads as a tiny bar instead of+ // vanishing. Grows up from the baseline. Floored bars skip the+ // perspective trim (sub-pixel on a 3px bar; keeps the front aligned+ // with bar-depth, which also skips trim for floored bars).+ let isFloored = false;+ if (+ !stacked &&+ minBarHeight > 0 &&+ value >= 0 &&+ barHeight < minBarHeight+ ) {+ const baselineY = scale(0) ?? innerHeight;+ barHeight = minBarHeight;+ y = baselineY - minBarHeight;+ isFloored = true;+ }++ // Perspective trim — shrink the topmost positive bar's front-face+ // top down by its perspective rise so it meets `<BarDepthBack>`'s+ // lid back edge. Stacked: only the last (topmost) series; grouped or+ // single: every positive bar. Clamped to `barHeight - 1` so very+ // short bars keep a positive height (matches bar-depth's clamp).+ if (+ perspective &&+ value > 0 &&+ !isFloored &&+ (!stacked || isLastSeries)+ ) {+ const baselineY = scale(0) ?? innerHeight;+ const rise = barDepthPerspectiveRise(+ barScale,+ bandWidth,+ barXAccessor,+ innerWidth,+ d,+ y,+ baselineY+ );+ const trim = Math.min(rise, Math.max(0, barHeight - 1));+ y += trim;+ barHeight -= trim;+ }}- const isFaded = hoveredBarIndex !== null && hoveredBarIndex !== i;+ const isFaded =+ (hoveredBarIndex !== null && hoveredBarIndex !== i) || isLegendDimmed;// Use categoryValue as key since it's the unique identifier from dataconst barKey = `bar-${dataKey}-${categoryValue}`;diff --git a/apps/start/src/components/charts/chart-center-typography.ts b/apps/start/src/components/charts/chart-center-typography.tsnew file mode 100644index 000000000..b1be1cfa1--- /dev/null+++ b/apps/start/src/components/charts/chart-center-typography.ts@@ -0,0 +1,16 @@+/**+ * Fluid typography for pie / ring / gauge center labels.+ *+ * Uses CSS container query units (`cqw`) so values scale with the center+ * hole — not the viewport — which keeps stat text readable on small charts.+ */+export const chartCenterContainerClassName =+ '@container/chart-center size-full min-w-0';++/** Primary stat — ~22% of center width, clamped between text-sm and text-3xl. */+export const chartCenterValueClassName =+ 'font-bold tabular-nums leading-none text-[clamp(0.75rem,22cqw,1.875rem)]';++/** Supporting label — ~9% of center width, clamped between 10px and text-xs. */+export const chartCenterLabelClassName =+ 'max-w-full truncate leading-tight text-[clamp(0.625rem,9cqw,0.75rem)]';diff --git a/apps/start/src/components/charts/chart-child-passthrough.ts b/apps/start/src/components/charts/chart-child-passthrough.tsnew file mode 100644index 000000000..8aae73c92--- /dev/null+++ b/apps/start/src/components/charts/chart-child-passthrough.ts@@ -0,0 +1,169 @@+import {+ Children,+ cloneElement,+ createElement,+ Fragment,+ isValidElement,+ type ReactElement,+ type ReactNode,+} from 'react';++/** Marker on wrapper components whose single child should inherit clip classification. */+export const CHART_CLIP_PASSTHROUGH = '__chartClipPassthrough' as const;++export function isChartClipPassthrough(type: unknown): boolean {+ return (+ typeof type === 'function' &&+ (type as { [CHART_CLIP_PASSTHROUGH]?: boolean })[CHART_CLIP_PASSTHROUGH] ===+ true+ );+}++const REACT_LAZY_TYPE = Symbol.for('react.lazy');++interface LazyComponentType {+ $$typeof: symbol;+ _init: (payload: unknown) => unknown;+ _payload: unknown;+}++function isLazyComponentType(type: unknown): type is LazyComponentType {+ return (+ typeof type === 'object' &&+ type !== null &&+ (type as { $$typeof?: unknown }).$$typeof === REACT_LAZY_TYPE &&+ typeof (type as { _init?: unknown })._init === 'function'+ );+}++/**+ * Unwrap a `React.lazy` element type to the component it resolves to.+ *+ * Chart children written in a Server Component (e.g. MDX docs) reach the+ * client chart as lazy client references, which hide `displayName` and the+ * `__isChartMarkers` / `__isPostOverlay` flags. Without unwrapping, markers,+ * axes and grids are classified as series and end up inside the reveal clip,+ * which cuts off marker count badges above the plot.+ */+export function resolveLazyChartChild(child: ReactElement): ReactElement {+ const type: unknown = child.type;+ if (!isLazyComponentType(type)) {+ return child;+ }+ let resolved: unknown;+ try {+ resolved = type._init(type._payload);+ } catch {+ // Module still loading (lazy init throws a thenable) — keep the lazy element.+ return child;+ }+ if (+ typeof resolved !== 'function' &&+ !(typeof resolved === 'object' && resolved !== null)+ ) {+ return child;+ }+ return createElement(resolved as Parameters<typeof createElement>[0], {+ ...(child.props as object),+ key: child.key,+ });+}++/** Unwrap visibility wrappers so `Grid` / axes stay outside the series clip. */+export function resolveChartChildElement(child: ReactElement): ReactElement {+ const element = resolveLazyChartChild(child);+ if (isChartClipPassthrough(element.type)) {+ const inner = (element.props as { children?: unknown }).children;+ if (isValidElement(inner)) {+ return resolveChartChildElement(inner);+ }+ }+ return element;+}++/** Walk chart children, flattening React fragments (studio often groups layers in `<>...</>`). */+export function forEachChartChild(+ children: ReactNode,+ callback: (child: ReactElement, index: number) => void+) {+ let index = 0;+ const visit = (nodes: ReactNode) => {+ Children.forEach(nodes, (child) => {+ if (!isValidElement(child)) {+ return;+ }+ if (child.type === Fragment) {+ visit((child.props as { children?: ReactNode }).children);+ return;+ }+ callback(resolveLazyChartChild(child), index);+ index += 1;+ });+ };+ visit(children);+}++const CLIP_EXCLUDED_COMPONENT_NAMES = new Set([+ 'Background',+ 'Grid',+ 'XAxis',+ 'YAxis',+ 'BarXAxis',+ 'BarYAxis',+ 'LiveXAxis',+ 'LiveYAxis',+]);++const UNDERLAY_COMPONENT_NAMES = new Set(['ReferenceArea', 'BarColumnTrack']);++/** 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;+ __isPostOverlay?: boolean;+ };++ if (childType.__isChartMarkers || childType.__isPostOverlay) {+ return true;+ }++ const componentName =+ typeof child.type === 'function'+ ? childType.displayName || childType.name || ''+ : '';++ return (+ componentName === 'ChartMarkers' ||+ componentName === 'MarkerGroup' ||+ componentName === 'ChartBrush'+ );+}++/** Renders above grid/axes but below series; excluded from grow-clip reveal. */+export function isUnderlayComponent(child: ReactElement): boolean {+ const childType = child.type as { displayName?: string; name?: string };+ const componentName =+ typeof child.type === 'function'+ ? childType.displayName || childType.name || ''+ : '';+ return UNDERLAY_COMPONENT_NAMES.has(componentName);+}++/** Grid and axes stay visible during series clip reveal (e.g. loading → ready). */+export function isClipExcludedComponent(child: ReactElement): boolean {+ const childType = child.type as { displayName?: string; name?: string };+ const componentName =+ typeof child.type === 'function'+ ? childType.displayName || childType.name || ''+ : '';+ return CLIP_EXCLUDED_COMPONENT_NAMES.has(componentName);+}++/** SVG layer lists from chart shells need stable keys when rendered as arrays. */+export function renderKeyedChartLayers(children: ReactElement[]) {+ return children.map((child, index) =>+ cloneElement(child, { key: child.key ?? `chart-layer-${index}` })+ );+}diff --git a/apps/start/src/components/charts/chart-config-context.tsx b/apps/start/src/components/charts/chart-config-context.tsxindex 41d00c5e1..ccbefc2ce 100644--- a/apps/start/src/components/charts/chart-config-context.tsx+++ b/apps/start/src/components/charts/chart-config-context.tsx@@ -51,3 +51,42 @@ export function ChartConfigProvider({export function useChartConfig(): ChartConfigValue {return useContext(ChartConfigContext) ?? DEFAULT_CHART_CONFIG;}++const DEFAULT_TOOLTIP_BOX_DAMPING =+ DEFAULT_CHART_CONFIG.tooltipBoxSpring.damping;++/** Maps a damping slider to the floating tooltip panel follow spring. `0` = instant. */+export function resolveTooltipBoxMotion(damping?: number): {+ animate: boolean;+ springConfig: SpringConfig;+} {+ if (damping === 0) {+ return {+ animate: false,+ springConfig: DEFAULT_CHART_CONFIG.tooltipBoxSpring,+ };+ }++ const effectiveDamping = damping ?? DEFAULT_TOOLTIP_BOX_DAMPING;+ let stiffness = DEFAULT_CHART_CONFIG.tooltipBoxSpring.stiffness;++ if (effectiveDamping < DEFAULT_TOOLTIP_BOX_DAMPING) {+ const t =+ (DEFAULT_TOOLTIP_BOX_DAMPING - effectiveDamping) /+ DEFAULT_TOOLTIP_BOX_DAMPING;+ stiffness += t * 400;+ } else if (effectiveDamping > DEFAULT_TOOLTIP_BOX_DAMPING) {+ const t =+ (effectiveDamping - DEFAULT_TOOLTIP_BOX_DAMPING) /+ (100 - DEFAULT_TOOLTIP_BOX_DAMPING);+ stiffness -= t * 85;+ }++ return {+ animate: true,+ springConfig: {+ stiffness: Math.max(12, Math.round(stiffness)),+ damping: effectiveDamping,+ },+ };+}diff --git a/apps/start/src/components/charts/chart-context.tsx b/apps/start/src/components/charts/chart-context.tsxindex 6eb1f8fc9..7bafbed3a 100644--- a/apps/start/src/components/charts/chart-context.tsx+++ b/apps/start/src/components/charts/chart-context.tsx@@ -22,7 +22,11 @@ import {useContext,useMemo,} from 'react';+import type { ChartPhase, ChartStatus } from './chart-phase';+import type { ReferenceAreaConfig } from './reference-area-config';import type { ChartSelection } from './use-chart-interaction';+import { DEFAULT_Y_AXIS_ID } from './y-axis-scales';+import type { YDomain } from './y-domain-utils';// CSS variable references for themingexport const chartCssVars = {@@ -43,6 +47,8 @@ export const chartCssVars = {badgeForeground: 'var(--chart-marker-badge-foreground)',segmentBackground: 'var(--chart-segment-background)',segmentLine: 'var(--chart-segment-line)',+ brushBorder: 'var(--chart-brush-border)',+ tooltipBackground: 'var(--chart-tooltip-background)',};/** Default scatter series colors from the chart palette (`--chart-1` … `--chart-5`). */@@ -78,6 +84,8 @@ export interface LineConfig {dataKey: string;stroke: string;strokeWidth: number;+ /** Scale group id (Recharts `yAxisId`). Default: `"left"`. */+ yAxisId?: string | number;}/**@@ -117,7 +125,10 @@ export interface ChartContextValue extends ChartHoverContextValue {// ScalesxScale: ScaleTime<number, number>;+ /** Primary (left) y-scale — alias for `yScales[DEFAULT_Y_AXIS_ID]`. */yScale: ScaleLinear<number, number>;+ /** Per-axis y-scales keyed by `yAxisId`. */+ yScales: Record<string, ScaleLinear<number, number>>;// Dimensionswidth: number;@@ -135,6 +146,21 @@ export interface ChartContextValue extends ChartHoverContextValue {// Line configurations (extracted from children)lines: LineConfig[];+ /** {@link ReferenceArea} bands — drives y-axis label colors in range. */+ referenceAreas: ReferenceAreaConfig[];++ // Loading / lifecycle (LineChart status transitions)+ chartPhase: ChartPhase;+ chartStatus: ChartStatus;+ /** Centered label while `chartPhase` shows loading chrome. */+ loadingLabel?: string;+ /** Y-domain tween duration when transitioning loading ↔ ready (ms). */+ yDomainTweenDuration: number;+ /** Nice’d y-domains per axis from skeleton data (placeholder). */+ yDomainSkeletonByAxis: Record<string, YDomain>;+ /** Nice’d y-domains per axis from the current target data. */+ yDomainTargetByAxis: Record<string, YDomain>;+// Animation stateisLoaded: boolean;animationDuration: number;@@ -144,6 +170,8 @@ export interface ChartContextValue extends ChartHoverContextValue {enterTransition?: Transition;/** Increments when enter animation should replay. */revealEpoch?: number;+ /** Fired when a one-shot loading pulse (exit / enter) completes. */+ notifyLoadingPulseComplete?: () => void;// X accessor - how to get the x value from data pointsxAccessor: (d: Record<string, unknown>) => Date;@@ -151,6 +179,11 @@ export interface ChartContextValue extends ChartHoverContextValue {// Pre-computed date labels for ticker animationdateLabels: string[];+ /** Active brush zoom range — when set, axis ticks align to visible data rows. */+ xDomain?: [Date, Date];+ /** Full dataset length when brush zoom is enabled (for zoom vs full-range detection). */+ xDomainSlotCount?: number;+// Bar chart specific (optional - only present in BarChart)/** Band scale for categorical x-axis (bar charts) */barScale?: ScaleBand<string>;@@ -164,6 +197,8 @@ export interface ChartContextValue extends ChartHoverContextValue {stacked?: boolean;/** Stack offsets: Map of data index -> Map of dataKey -> cumulative offset */stackOffsets?: Map<number, Map<string, number>>;+ /** Squares variant — snap tooltip to top square and size ring dots. */+ squareSnap?: { squareGap: number; groupGap?: number; fit?: boolean };// ComposedChart + SeriesBar (optional)/** `SeriesBar` dataKeys in tree order, for grouped columns at each x */@@ -214,6 +249,7 @@ export function ChartProvider({renderData: value.renderData,xScale: value.xScale,yScale: value.yScale,+ yScales: value.yScales,width: value.width,height: value.height,innerWidth: value.innerWidth,@@ -222,13 +258,23 @@ export function ChartProvider({columnWidth: value.columnWidth,containerRef: value.containerRef,lines: value.lines,+ referenceAreas: value.referenceAreas,+ chartPhase: value.chartPhase,+ chartStatus: value.chartStatus,+ loadingLabel: value.loadingLabel,+ yDomainTweenDuration: value.yDomainTweenDuration,+ yDomainSkeletonByAxis: value.yDomainSkeletonByAxis,+ yDomainTargetByAxis: value.yDomainTargetByAxis,isLoaded: value.isLoaded,animationDuration: value.animationDuration,animationEasing: value.animationEasing,enterTransition: value.enterTransition,revealEpoch: value.revealEpoch,+ notifyLoadingPulseComplete: value.notifyLoadingPulseComplete,xAccessor: value.xAccessor,dateLabels: value.dateLabels,+ xDomain: value.xDomain,+ xDomainSlotCount: value.xDomainSlotCount,barScale: value.barScale,bandWidth: value.bandWidth,barXAccessor: value.barXAccessor,@@ -248,6 +294,7 @@ export function ChartProvider({value.renderData,value.xScale,value.yScale,+ value.yScales,value.width,value.height,value.innerWidth,@@ -256,13 +303,23 @@ export function ChartProvider({value.columnWidth,value.containerRef,value.lines,+ value.referenceAreas,+ value.chartPhase,+ value.chartStatus,+ value.loadingLabel,+ value.yDomainTweenDuration,+ value.yDomainSkeletonByAxis,+ value.yDomainTargetByAxis,value.isLoaded,value.animationDuration,value.animationEasing,value.enterTransition,value.revealEpoch,+ value.notifyLoadingPulseComplete,value.xAccessor,value.dateLabels,+ value.xDomain,+ value.xDomainSlotCount,value.barScale,value.bandWidth,value.barXAccessor,@@ -327,6 +384,16 @@ export function useChartStable(): ChartStableContextValue {return context;}+/** Y-scale for a series axis (`yAxisId` on Line / Area / YAxis). */+export function useYScale(+ yAxisId?: string | number+): ScaleLinear<number, number> {+ const { yScales, yScale } = useChartStable();+ const id =+ yAxisId == null || yAxisId === '' ? DEFAULT_Y_AXIS_ID : String(yAxisId);+ return yScales[id] ?? yScale;+}+/*** Hover slice — tooltipData, selection, hovered bar / candle indices.* Subscribers re-render on every mouse move. Use only when the componentdiff --git a/apps/start/src/components/charts/chart-legend-hover.tsx b/apps/start/src/components/charts/chart-legend-hover.tsxnew file mode 100644index 000000000..a4965ea98--- /dev/null+++ b/apps/start/src/components/charts/chart-legend-hover.tsx@@ -0,0 +1,44 @@+'use client';++import { createContext, type ReactNode, useContext, useMemo } from 'react';++interface ChartLegendHoverContextValue {+ hoveredIndex: number | null;+ setHoveredIndex: (index: number | null) => void;+}++const ChartLegendHoverContext =+ createContext<ChartLegendHoverContextValue | null>(null);++export function ChartLegendHoverProvider({+ hoveredIndex,+ onHoverChange,+ children,+}: {+ hoveredIndex: number | null;+ onHoverChange: (index: number | null) => void;+ children: ReactNode;+}) {+ const value = useMemo(+ () => ({ hoveredIndex, setHoveredIndex: onHoverChange }),+ [hoveredIndex, onHoverChange]+ );++ return (+ <ChartLegendHoverContext.Provider value={value}>+ {children}+ </ChartLegendHoverContext.Provider>+ );+}++export function useChartLegendHover(): ChartLegendHoverContextValue {+ const context = useContext(ChartLegendHoverContext);+ return (+ context ?? {+ hoveredIndex: null,+ setHoveredIndex: () => {+ /* noop outside ChartLegendHoverProvider */+ },+ }+ );+}diff --git a/apps/start/src/components/charts/chart-loading-label.tsx b/apps/start/src/components/charts/chart-loading-label.tsxnew file mode 100644index 000000000..66ce6a802--- /dev/null+++ b/apps/start/src/components/charts/chart-loading-label.tsx@@ -0,0 +1,56 @@+'use client';++import { motion } from 'motion/react';+import { ShimmeringText } from '../shimmering-text';+import {+ LINE_LOADING_PULSE_EASE,+ LOADING_LABEL_EXIT_S,+ LOADING_LABEL_EXIT_Y_PX,+} from './line-loading-timing';+import { cn } from '@/lib/utils';++export interface ChartLoadingLabelProps {+ /** Label shown centered over the chart. */+ text?: string;+ className?: string;+ /** Animate down, fade, and blur during loading → ready handoff. */+ exiting?: boolean;+}++export function ChartLoadingLabel({+ text = 'Loading',+ className,+ exiting = false,+}: ChartLoadingLabelProps) {+ if (!text.trim()) {+ return null;+ }++ return (+ <motion.div+ animate={{+ y: exiting ? LOADING_LABEL_EXIT_Y_PX : 0,+ opacity: exiting ? 0 : 1,+ filter: exiting ? 'blur(2px)' : 'blur(0px)',+ }}+ aria-live="polite"+ className={cn(+ 'pointer-events-none absolute inset-0 flex items-center justify-center',+ className+ )}+ initial={false}+ role="status"+ transition={{+ duration: LOADING_LABEL_EXIT_S,+ ease: [...LINE_LOADING_PULSE_EASE],+ }}+ >+ <ShimmeringText+ className="font-medium text-sm tracking-wide [--color:var(--muted-foreground)] [--shimmering-color:var(--foreground)]"+ text={text}+ />+ </motion.div>+ );+}++export default ChartLoadingLabel;diff --git a/apps/start/src/components/charts/chart-parent-size.tsx b/apps/start/src/components/charts/chart-parent-size.tsxnew file mode 100644index 000000000..1bd45494d--- /dev/null+++ b/apps/start/src/components/charts/chart-parent-size.tsx@@ -0,0 +1,34 @@+'use client';++import { useParentSize } from '@visx/responsive';+import type { CSSProperties, ReactNode } from 'react';++export interface ChartParentSizeProps {+ children: (size: { width: number; height: number }) => ReactNode;+ className?: string;+ debounceTime?: number;+ style?: CSSProperties;+}++/**+ * Drop-in for visx `<ParentSize>` without its `overflow: hidden` measuring+ * layer, so tooltips, markers, and strokes at the chart edge aren't clipped.+ */+export function ParentSize({+ children,+ className,+ debounceTime,+ style,+}: ChartParentSizeProps) {+ const { parentRef, width, height } = useParentSize({ debounceTime });+ return (+ <div+ className={className}+ style={{ position: 'relative', width: '100%', height: '100%', ...style }}+ >+ <div ref={parentRef} style={{ position: 'absolute', inset: 0 }}>+ {children({ width, height })}+ </div>+ </div>+ );+}diff --git a/apps/start/src/components/charts/chart-phase.ts b/apps/start/src/components/charts/chart-phase.tsnew file mode 100644index 000000000..8c9b1154a--- /dev/null+++ b/apps/start/src/components/charts/chart-phase.ts@@ -0,0 +1,53 @@+/** Consumer-facing fetch / display status on time-series charts. */+export type ChartStatus = 'loading' | 'ready';++/** Loading animation style: the default traveling pulse, or a diagonal+ * shimmer that sweeps across the skeleton. */+export type LoadingStyle = 'pulse' | 'sweep';++/**+ * Internal visual lifecycle phase. Forward and reverse transitions add+ * intermediate phases in later stack branches.+ */+export type ChartPhase =+ | 'loading'+ | 'exiting'+ | 'gridTweenReady'+ | 'revealing'+ | 'ready'+ | 'exitingReady'+ | 'gridTweenLoading'+ | 'revealingLoading';++export const DEFAULT_CHART_STATUS: ChartStatus = 'ready';++/** Default Y-domain tween when transitioning loading ↔ ready (ms). */+export const DEFAULT_Y_DOMAIN_TWEEN_MS = 500;++/** Relative domain delta below which Y tween may be skipped (see plan). */+export const Y_DOMAIN_TWEEN_SKIP_THRESHOLD = 0.02;++/** Resting phase for a given status before transition orchestration runs. */+export function resolveRestingChartPhase(status: ChartStatus): ChartPhase {+ return status === 'loading' ? 'loading' : 'ready';+}++export function isChartInteractionPhase(phase: ChartPhase): boolean {+ return phase === 'ready';+}++export const DEFAULT_CHART_LIFECYCLE = {+ chartPhase: 'ready',+ chartStatus: 'ready',+ loadingLabel: undefined,+ yDomainTweenDuration: DEFAULT_Y_DOMAIN_TWEEN_MS,+ yDomainSkeletonByAxis: { left: [0, 100] as [number, number] },+ yDomainTargetByAxis: { left: [0, 100] as [number, number] },+} as const satisfies {+ chartPhase: ChartPhase;+ chartStatus: ChartStatus;+ loadingLabel: undefined;+ yDomainTweenDuration: number;+ yDomainSkeletonByAxis: Record<string, [number, number]>;+ yDomainTargetByAxis: Record<string, [number, number]>;+};diff --git a/apps/start/src/components/charts/chart-reveal-clip.tsx b/apps/start/src/components/charts/chart-reveal-clip.tsxindex 6736aa4b6..1b5e1084d 100644--- a/apps/start/src/components/charts/chart-reveal-clip.tsx+++ b/apps/start/src/components/charts/chart-reveal-clip.tsx@@ -4,6 +4,8 @@ import type { Transition } from 'motion/react';import { motion } from 'motion/react';import { clipRevealTransition } from './animation';+export type ChartRevealClipMode = 'reveal' | 'conceal';+export interface ChartRevealClipProps {clipPathId: string;height: number;@@ -13,6 +15,18 @@ export interface ChartRevealClipProps {revealEpoch: number;/** Extra inset around the clip rect so edge glyphs are not cut off. */padding?: number;+ /**+ * Vertical inset above and below the clip rect. Defaults to `padding`.+ * The reveal only animates x, so this can be larger than `padding` to let+ * point markers and strokes at the top/bottom of the plot render in full.+ */+ paddingY?: number;+ /** When false, clip stays at full width (no grow animation). */+ animating?: boolean;+ /** Reveal grows 0 → full; conceal shrinks full → 0 (ready → loading). */+ mode?: ChartRevealClipMode;+ /** Called when a conceal animation finishes. */+ onComplete?: () => void;}/**@@ -26,10 +40,47 @@ export function ChartRevealClip({enterTransition,revealEpoch,padding = 0,+ paddingY = padding,+ animating = true,+ mode = 'reveal',+ onComplete,}: ChartRevealClipProps) {const transition = clipRevealTransition(enterTransition);const paddedWidth = Math.max(0, targetWidth + padding * 2);- const paddedHeight = height + padding * 2;+ const paddedHeight = height + paddingY * 2;++ if (!animating) {+ return (+ <clipPath id={clipPathId}>+ <rect+ height={paddedHeight}+ width={paddedWidth}+ x={-padding}+ y={-paddingY}+ />+ </clipPath>+ );+ }++ if (mode === 'conceal') {+ // Mirror the LTR reveal: advance the clip's left edge rightward while width+ // shrinks (same geometry as `LineLoadingPulseStroke` exit half-cycle).+ const rightEdge = -padding + paddedWidth;++ return (+ <clipPath id={clipPathId}>+ <motion.rect+ animate={{ width: 0, x: rightEdge }}+ height={paddedHeight}+ initial={{ width: paddedWidth, x: -padding }}+ key={`conceal-${revealEpoch}`}+ onAnimationComplete={() => onComplete?.()}+ transition={transition}+ y={-paddingY}+ />+ </clipPath>+ );+ }return (<clipPath id={clipPathId}>@@ -41,7 +92,7 @@ export function ChartRevealClip({transition={transition}width={paddedWidth}x={-padding}- y={-padding}+ y={-paddingY}/></clipPath>);diff --git a/apps/start/src/components/charts/chart-scale.ts b/apps/start/src/components/charts/chart-scale.tsnew file mode 100644index 000000000..64f1fe58a--- /dev/null+++ b/apps/start/src/components/charts/chart-scale.ts@@ -0,0 +1,19 @@+/** Sequential scale CSS variables for heatmaps, choropleths, and binned data (01 = lowest, 05 = highest). */+export const CHART_SCALE_VARS = [+ 'var(--chart-scale-01)',+ 'var(--chart-scale-02)',+ 'var(--chart-scale-03)',+ 'var(--chart-scale-04)',+ 'var(--chart-scale-05)',+] as const;++export type ChartScaleVars = typeof CHART_SCALE_VARS;++export const chartScaleCssVars = {+ scale01: CHART_SCALE_VARS[0],+ scale02: CHART_SCALE_VARS[1],+ scale03: CHART_SCALE_VARS[2],+ scale04: CHART_SCALE_VARS[3],+ scale05: CHART_SCALE_VARS[4],+ patternColor: 'var(--chart-scale-pattern-color)',+} as const;diff --git a/apps/start/src/components/charts/chart-stat-flow.tsx b/apps/start/src/components/charts/chart-stat-flow.tsxindex b6e3e3d50..49f9192b8 100644--- a/apps/start/src/components/charts/chart-stat-flow.tsx+++ b/apps/start/src/components/charts/chart-stat-flow.tsx@@ -1,7 +1,7 @@'use client';import NumberFlow from '@number-flow/react';-import type { ReactNode } from 'react';+import { type ReactNode, useEffect, useMemo, useState } from 'react';import { cn } from '@/lib/utils';/** Subset of `Intl.NumberFormatOptions` supported by NumberFlow */@@ -25,6 +25,43 @@ export const defaultChartStatFlowFormat: ChartStatFlowFormat = {maximumFractionDigits: 0,};+function formatStatValue(+ value: number,+ formatOptions: ChartStatFlowFormat,+ prefix?: string,+ suffix?: string+): string {+ const formatted = new Intl.NumberFormat(undefined, formatOptions).format(+ value+ );+ return `${prefix ?? ''}${formatted}${suffix ?? ''}`;+}++function useNumberFlowElementReady(): boolean {+ const [ready, setReady] = useState(+ () =>+ typeof customElements !== 'undefined' &&+ Boolean(customElements.get('number-flow-react'))+ );++ useEffect(() => {+ if (ready) {+ return;+ }+ let cancelled = false;+ customElements.whenDefined('number-flow-react').then(() => {+ if (!cancelled) {+ setReady(true);+ }+ });+ return () => {+ cancelled = true;+ };+ }, [ready]);++ return ready;+}+export interface ChartStatFlowProps {value: number;label: string;@@ -50,6 +87,12 @@ export function ChartStatFlow({labelClassName = 'text-xs',icon,}: ChartStatFlowProps) {+ const numberFlowReady = useNumberFlowElementReady();+ const staticValue = useMemo(+ () => formatStatValue(value, formatOptions, prefix, suffix),+ [value, formatOptions, prefix, suffix]+ );+return (<>{icon ? (@@ -58,13 +101,18 @@ export function ChartStatFlow({</div>) : null}<span className={cn('text-foreground tabular-nums', valueClassName)}>- <NumberFlow- format={formatOptions}- prefix={prefix}- suffix={suffix}- value={value}- willChange- />+ {numberFlowReady ? (+ <NumberFlow+ format={formatOptions}+ isolate+ prefix={prefix}+ suffix={suffix}+ value={value}+ willChange+ />+ ) : (+ staticValue+ )}</span><span className={cn('mt-0.5 text-chart-label', labelClassName)}>{label}diff --git a/apps/start/src/components/charts/chart-tooltip.tsx b/apps/start/src/components/charts/chart-tooltip.tsxindex abf61b181..b65421b9d 100644--- a/apps/start/src/components/charts/chart-tooltip.tsx+++ b/apps/start/src/components/charts/chart-tooltip.tsx@@ -1,5 +1,3 @@-import { createContext, useContext as useBaseContext } from 'react';-import { Tooltip as RechartsTooltip, type TooltipProps } from 'recharts';import { cn } from '@/utils/cn';export const ChartTooltipContainer = ({@@ -47,59 +45,3 @@ export const ChartTooltipItem = ({</div>);};--export function createChartTooltip<- PropsFromTooltip,- PropsFromContext extends Record<string, unknown>,->(- Tooltip: React.ComponentType<- {- context: PropsFromContext;- data: PropsFromTooltip[];- } & TooltipProps<number, string>- >-) {- const context = createContext<PropsFromContext | null>(null);- const useContext = () => {- const value = useBaseContext(context);- if (!value) {- throw new Error('ChartTooltip context not found');- }- return value;- };-- const InnerTooltip = (tooltip: TooltipProps<number, string>) => {- const context = useContext();- const data = tooltip.payload?.map((p) => p.payload) ?? [];-- if (!(data && tooltip.active)) {- return null;- }-- return (- <ChartTooltipContainer>- <Tooltip context={context} data={data} {...tooltip} />- </ChartTooltipContainer>- );- };-- return {- TooltipProvider: ({- children,- ...value- }: {- children: React.ReactNode;- } & PropsFromContext) => {- return (- <context.Provider value={value as unknown as PropsFromContext}>- {children}- </context.Provider>- );- },- Tooltip: (props: TooltipProps<number, string>) => {- return (- <RechartsTooltip {...props} content={<InnerTooltip {...props} />} />- );- },- };-}diff --git a/apps/start/src/components/charts/choropleth/choropleth-chart.tsx b/apps/start/src/components/charts/choropleth/choropleth-chart.tsxnew file mode 100644index 000000000..944ebfcfc--- /dev/null+++ b/apps/start/src/components/charts/choropleth/choropleth-chart.tsx@@ -0,0 +1,512 @@+'use client';++import { Mercator } from '@visx/geo';+import type { TransformMatrix } from '@visx/zoom';+import { Zoom } from '@visx/zoom';+import type { FeatureCollection, Geometry } from 'geojson';+import type { Transition } from 'motion/react';+import React, {+ memo,+ type ReactNode,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import { ParentSize } from '../chart-parent-size';+import {+ type ChoroplethFeature,+ type ChoroplethFeatureProperties,+ ChoroplethInteractionShell,+ ChoroplethStableProvider,+ ChoroplethZoomContext,+ type Margin,+ useChoroplethInteraction,+ type ZoomInstance,+} from './choropleth-context';+import { ChoroplethFeature as ChoroplethFeatureLayer } from './choropleth-feature';+import { ChoroplethGraticule as ChoroplethGraticuleLayer } from './choropleth-graticule';+import { ChoroplethTooltip as ChoroplethTooltipLayer } from './choropleth-tooltip';+import { cn } from '@/lib/utils';++export interface ChoroplethChartProps {+ /** GeoJSON FeatureCollection data */+ data: FeatureCollection<Geometry, ChoroplethFeatureProperties>;+ /** Chart margins */+ margin?: Partial<Margin>;+ /** Animation duration in milliseconds. Default: 800 */+ animationDuration?: number;+ /** 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: "16 / 9" */+ aspectRatio?: string;+ /** Projection scale. If not provided, auto-calculated based on width */+ scale?: number;+ /** Center coordinates [longitude, latitude]. Default: [0, 20] */+ center?: [number, number];+ /** Translate offset [x, y]. If not provided, auto-calculated to center */+ translate?: [number, number];+ /** Enable zoom and pan. Default: false */+ zoomEnabled?: boolean;+ /** Minimum zoom scale. Default: 0.5 */+ zoomMin?: number;+ /** Maximum zoom scale. Default: 4 */+ zoomMax?: number;+ /** Initial zoom transform */+ initialZoom?: TransformMatrix;+ /** Additional class name for the container */+ className?: string;+ /** Child components (ChoroplethFeature, ChoroplethGraticule, ChoroplethTooltip) */+ children: ReactNode;+}++const DEFAULT_MARGIN: Margin = { top: 0, right: 0, bottom: 0, left: 0 };++// Known SVG component displayNames+const SVG_COMPONENT_NAMES = new Set([+ 'ChoroplethFeature',+ 'ChoroplethGraticule',+ 'ChoroplethTooltip',+]);++const SVG_COMPONENT_TYPES = new Set([+ ChoroplethFeatureLayer,+ ChoroplethGraticuleLayer,+ ChoroplethTooltipLayer,+]);++function resolveComponentType(type: unknown): unknown {+ if (+ typeof type === 'object' &&+ type !== null &&+ 'type' in type &&+ (type as { type?: unknown }).type+ ) {+ return (type as { type: unknown }).type;+ }+ return type;+}++function getComponentDisplayName(type: unknown): string | null {+ if (typeof type === 'function') {+ const fn = type as { displayName?: string; name?: string };+ return fn.displayName ?? fn.name ?? null;+ }+ if (typeof type === 'object' && type !== null) {+ const wrapped = type as {+ displayName?: string;+ type?: { displayName?: string; name?: string };+ };+ if (wrapped.displayName) {+ return wrapped.displayName;+ }+ const inner = wrapped.type;+ if (typeof inner === 'function') {+ const innerFn = inner as { displayName?: string; name?: string };+ return innerFn.displayName ?? innerFn.name ?? null;+ }+ }+ return null;+}++function isChoroplethSvgChild(type: unknown): boolean {+ if (SVG_COMPONENT_TYPES.has(type as never)) {+ return true;+ }+ const resolved = resolveComponentType(type);+ if (resolved !== type && SVG_COMPONENT_TYPES.has(resolved as never)) {+ return true;+ }+ const displayName = getComponentDisplayName(type);+ return displayName !== null && SVG_COMPONENT_NAMES.has(displayName);+}++// HTML elements that should render in overlay layer+const HTML_ELEMENTS = new Set(['div', 'span', 'button', 'p', 'a']);++// Separate children into SVG and overlay layers+function separateChildren(children: ReactNode): {+ svgChildren: React.ReactNode[];+ overlayChildren: React.ReactNode[];+} {+ const childArray = React.Children.toArray(children);+ const svgChildren: React.ReactNode[] = [];+ const overlayChildren: React.ReactNode[] = [];++ for (const child of childArray) {+ if (!React.isValidElement(child)) {+ svgChildren.push(child);+ continue;+ }++ if (isChoroplethSvgChild(child.type)) {+ svgChildren.push(child);+ } else if (typeof child.type === 'string') {+ if (HTML_ELEMENTS.has(child.type)) {+ overlayChildren.push(child);+ } else {+ svgChildren.push(child);+ }+ } else {+ overlayChildren.push(child);+ }+ }++ return { svgChildren, overlayChildren };+}++const DEFAULT_INITIAL_ZOOM: TransformMatrix = {+ scaleX: 1,+ scaleY: 1,+ translateX: 0,+ translateY: 0,+ skewX: 0,+ skewY: 0,+};++interface MercatorRenderProps {+ // biome-ignore lint/suspicious/noExplicitAny: visx geo projection bundle+ path: (geo: any) => string | null;+ projection: (coords: [number, number]) => [number, number] | null | undefined;+}++interface ChoroplethMercatorContentProps {+ mercator: MercatorRenderProps;+ data: FeatureCollection<Geometry, ChoroplethFeatureProperties>;+ width: number;+ height: number;+ innerWidth: number;+ innerHeight: number;+ margin: Margin;+ animationDuration: number;+ enterTransition?: Transition;+ revealEpoch: number;+ isLoaded: boolean;+ containerRef: React.RefObject<HTMLDivElement | null>;+ svgChildren: React.ReactNode[];+ overlayChildren: React.ReactNode[];+ zoom?: ZoomInstance<SVGSVGElement>;+}++const ChoroplethSvg = memo(function ChoroplethSvg({+ height,+ width,+ svgChildren,+ zoom,+}: {+ height: number;+ width: number;+ svgChildren: React.ReactNode[];+ zoom?: ZoomInstance<SVGSVGElement>;+}) {+ const { setHoveredFeatureIndex, setTooltipData } = useChoroplethInteraction();++ const handleMouseLeave = useCallback(() => {+ setHoveredFeatureIndex(null);+ setTooltipData(null);+ }, [setHoveredFeatureIndex, setTooltipData]);++ return (+ <svg+ aria-hidden="true"+ height={height}+ onMouseLeave={handleMouseLeave}+ ref={zoom?.containerRef}+ style={{+ contain: 'layout style paint',+ cursor: zoom?.isDragging ? 'grabbing' : 'grab',+ touchAction: 'none',+ }}+ width={width}+ >+ <g+ style={{+ transition: zoom?.isDragging ? 'none' : 'transform 0.18s ease-out',+ }}+ transform={zoom ? zoom.toString() : undefined}+ >+ {svgChildren}+ </g>+ </svg>+ );+});++const ChoroplethMercatorContent = memo(function ChoroplethMercatorContent({+ mercator,+ data,+ width,+ height,+ innerWidth,+ innerHeight,+ margin,+ animationDuration,+ enterTransition,+ revealEpoch,+ isLoaded,+ containerRef,+ svgChildren,+ overlayChildren,+ zoom,+}: ChoroplethMercatorContentProps) {+ const featurePaths = data.features.map(+ (feature) => mercator.path(feature) ?? null+ ) as (string | null)[];++ const pathGenerator = useCallback(+ (feature: ChoroplethFeature) => mercator.path(feature) ?? undefined,+ [mercator]+ );++ const rawPathGenerator = useCallback(+ // biome-ignore lint/suspicious/noExplicitAny: GeoJSON types are complex+ (geo: any) => mercator.path(geo),+ [mercator]+ );++ const projectPoint = useCallback(+ (coords: [number, number]): [number, number] | null => {+ const projected = mercator.projection(coords);+ if (!projected) {+ return null;+ }+ return projected as [number, number];+ },+ [mercator]+ );++ const stableValue = useMemo(+ () => ({+ features: data.features,+ featureCollection: data,+ featurePaths,+ pathGenerator,+ rawPathGenerator,+ projectPoint,+ width,+ height,+ innerWidth,+ innerHeight,+ margin,+ containerRef,+ isLoaded,+ animationDuration,+ enterTransition,+ revealEpoch,+ }),+ [+ animationDuration,+ containerRef,+ data,+ enterTransition,+ featurePaths,+ height,+ innerHeight,+ innerWidth,+ isLoaded,+ margin,+ pathGenerator,+ projectPoint,+ rawPathGenerator,+ revealEpoch,+ width,+ ]+ );++ return (+ <ChoroplethZoomContext.Provider value={{ zoom: zoom ?? null }}>+ <ChoroplethStableProvider value={stableValue}>+ <ChoroplethInteractionShell>+ <div className="relative h-full w-full" ref={containerRef}>+ <ChoroplethSvg+ height={height}+ svgChildren={svgChildren}+ width={width}+ zoom={zoom}+ />+ {overlayChildren}+ </div>+ </ChoroplethInteractionShell>+ </ChoroplethStableProvider>+ </ChoroplethZoomContext.Provider>+ );+});++function ChoroplethChartInner({+ data,+ width,+ height,+ margin,+ animationDuration,+ enterTransition,+ revealSignature = '',+ scale: scaleProp,+ center,+ translate: translateProp,+ zoomEnabled,+ zoomMin,+ zoomMax,+ initialZoom,+ children,+}: {+ data: FeatureCollection<Geometry, ChoroplethFeatureProperties>;+ width: number;+ height: number;+ margin: Margin;+ animationDuration: number;+ enterTransition?: Transition;+ revealSignature?: string;+ scale?: number;+ center: [number, number];+ translate?: [number, number];+ zoomEnabled: boolean;+ zoomMin: number;+ zoomMax: number;+ initialZoom: TransformMatrix;+ children: ReactNode;+}) {+ const containerRef = useRef<HTMLDivElement>(null);+ 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 scale = scaleProp ?? (innerWidth / 630) * 100;++ const translate = translateProp ?? [+ innerWidth / 2 + margin.left,+ innerHeight / 2 + margin.top + 50,+ ];++ const { svgChildren, overlayChildren } = useMemo(+ () => separateChildren(children),+ [children]+ );++ // biome-ignore lint/correctness/useExhaustiveDependencies: revealSignature+ useEffect(() => {+ setRevealEpoch((n) => n + 1);+ setIsLoaded(false);+ const timeout = setTimeout(() => {+ setIsLoaded(true);+ }, animationDuration);+ return () => clearTimeout(timeout);+ }, [animationDuration, revealSignature]);++ if (width < 10 || height < 10) {+ return null;+ }++ const mercatorContentProps = {+ animationDuration,+ containerRef,+ data,+ enterTransition,+ height,+ innerHeight,+ innerWidth,+ isLoaded,+ margin,+ overlayChildren,+ revealEpoch,+ svgChildren,+ width,+ };++ return (+ <Mercator+ center={center}+ data={data.features}+ scale={scale}+ translate={translate as [number, number]}+ >+ {(mercator) => {+ const content = (zoom?: ZoomInstance<SVGSVGElement>) => (+ <ChoroplethMercatorContent+ {...mercatorContentProps}+ mercator={mercator}+ zoom={zoom}+ />+ );++ if (zoomEnabled) {+ return (+ <Zoom<SVGSVGElement>+ height={height}+ initialTransformMatrix={initialZoom}+ scaleXMax={zoomMax}+ scaleXMin={zoomMin}+ scaleYMax={zoomMax}+ scaleYMin={zoomMin}+ wheelDelta={(event) => {+ const zoomScale = event.deltaY > 0 ? 0.95 : 1.05;+ return { scaleX: zoomScale, scaleY: zoomScale };+ }}+ width={width}+ >+ {(zoom) => content(zoom)}+ </Zoom>+ );+ }++ return content();+ }}+ </Mercator>+ );+}++export function ChoroplethChart({+ data,+ margin: marginProp,+ animationDuration = 800,+ enterTransition,+ revealSignature,+ aspectRatio = '16 / 9',+ scale,+ center = [0, 20],+ translate,+ zoomEnabled = false,+ zoomMin = 0.5,+ zoomMax = 4,+ initialZoom = DEFAULT_INITIAL_ZOOM,+ className = '',+ children,+}: ChoroplethChartProps) {+ const margin = { ...DEFAULT_MARGIN, ...marginProp };++ return (+ <div className={cn('relative w-full', className)} style={{ aspectRatio }}>+ <ParentSize debounceTime={10}>+ {({ width, height }) =>+ width > 0 && height > 0 ? (+ <ChoroplethChartInner+ animationDuration={animationDuration}+ center={center}+ data={data}+ enterTransition={enterTransition}+ height={height}+ initialZoom={initialZoom}+ margin={margin}+ revealSignature={revealSignature}+ scale={scale}+ translate={translate}+ width={width}+ zoomEnabled={zoomEnabled}+ zoomMax={zoomMax}+ zoomMin={zoomMin}+ >+ {children}+ </ChoroplethChartInner>+ ) : null+ }+ </ParentSize>+ </div>+ );+}++ChoroplethChart.displayName = 'ChoroplethChart';++export default ChoroplethChart;diff --git a/apps/start/src/components/charts/choropleth/choropleth-context.tsx b/apps/start/src/components/charts/choropleth/choropleth-context.tsxnew file mode 100644index 000000000..53bf6b295--- /dev/null+++ b/apps/start/src/components/charts/choropleth/choropleth-context.tsx@@ -0,0 +1,262 @@+'use client';++import type { ProvidedZoom, TransformMatrix } from '@visx/zoom';+import type { Feature, FeatureCollection, Geometry } from 'geojson';+import type { Transition } from 'motion/react';+import {+ createContext,+ type Dispatch,+ type RefObject,+ type SetStateAction,+ useContext,+ useMemo,+ useState,+} from 'react';++// ZoomState from visx/zoom that includes isDragging+interface ZoomState {+ initialTransformMatrix: TransformMatrix;+ transformMatrix: TransformMatrix;+ isDragging: boolean;+}++// Combined type from visx Zoom children prop+export type ZoomInstance<E extends Element> = ProvidedZoom<E> & ZoomState;++// Zoom context to share zoom controls with child components+interface ChoroplethZoomContextValue {+ zoom: ZoomInstance<SVGSVGElement> | null;+}++export const ChoroplethZoomContext = createContext<ChoroplethZoomContextValue>({+ zoom: null,+});++export function useChoroplethZoom() {+ return useContext(ChoroplethZoomContext);+}++export interface Margin {+ top: number;+ right: number;+ bottom: number;+ left: number;+}++export interface ChoroplethFeatureProperties {+ name?: string;+ id?: string | number;+ [key: string]: unknown;+}++export type ChoroplethFeature = Feature<Geometry, ChoroplethFeatureProperties>;++export interface ChoroplethTooltipData {+ featureIndex: number;+ x: number;+ y: number;+ feature: ChoroplethFeature;+}++export interface ChoroplethInteractionContextValue {+ hoveredFeatureIndex: number | null;+ setHoveredFeatureIndex: (index: number | null) => void;+ tooltipData: ChoroplethTooltipData | null;+ setTooltipData: Dispatch<SetStateAction<ChoroplethTooltipData | null>>;+}++export interface ChoroplethStableContextValue {+ // Geo data+ features: ChoroplethFeature[];+ featureCollection: FeatureCollection<Geometry, ChoroplethFeatureProperties>;++ /** Precomputed SVG path strings — one per feature index. */+ featurePaths: readonly (string | null)[];++ // Projection function (returns path string)+ pathGenerator: (feature: ChoroplethFeature) => string | undefined;++ // Raw path function for graticule (accepts any geo object)+ // biome-ignore lint/suspicious/noExplicitAny: GeoJSON types are complex+ rawPathGenerator: (geo: any) => string | null;++ // Project geo coordinates to screen coordinates+ projectPoint: (coords: [number, number]) => [number, number] | null;++ // Dimensions+ width: number;+ height: number;+ innerWidth: number;+ innerHeight: number;+ margin: Margin;++ containerRef: RefObject<HTMLDivElement | null>;++ // Animation+ isLoaded: boolean;+ animationDuration: number;+ enterTransition?: Transition;+ revealEpoch: number;+}++export type ChoroplethContextValue = ChoroplethStableContextValue &+ ChoroplethInteractionContextValue;++const ChoroplethStableContext =+ createContext<ChoroplethStableContextValue | null>(null);+const ChoroplethInteractionContext =+ createContext<ChoroplethInteractionContextValue | null>(null);++export function ChoroplethStableProvider({+ children,+ value,+}: {+ children: React.ReactNode;+ value: ChoroplethStableContextValue;+}) {+ return (+ <ChoroplethStableContext.Provider value={value}>+ {children}+ </ChoroplethStableContext.Provider>+ );+}++export function ChoroplethInteractionShell({+ children,+}: {+ children: React.ReactNode;+}) {+ const [hoveredFeatureIndex, setHoveredFeatureIndex] = useState<number | null>(+ null+ );+ const [tooltipData, setTooltipData] = useState<ChoroplethTooltipData | null>(+ null+ );++ const interaction = useMemo<ChoroplethInteractionContextValue>(+ () => ({+ hoveredFeatureIndex,+ setHoveredFeatureIndex,+ tooltipData,+ setTooltipData,+ }),+ [hoveredFeatureIndex, tooltipData]+ );++ return (+ <ChoroplethInteractionContext.Provider value={interaction}>+ {children}+ </ChoroplethInteractionContext.Provider>+ );+}++export function ChoroplethProvider({+ children,+ value,+}: {+ children: React.ReactNode;+ value: ChoroplethContextValue;+}) {+ const stable = useMemo<ChoroplethStableContextValue>(+ () => ({+ features: value.features,+ featureCollection: value.featureCollection,+ featurePaths: value.featurePaths,+ pathGenerator: value.pathGenerator,+ rawPathGenerator: value.rawPathGenerator,+ projectPoint: value.projectPoint,+ width: value.width,+ height: value.height,+ innerWidth: value.innerWidth,+ innerHeight: value.innerHeight,+ margin: value.margin,+ containerRef: value.containerRef,+ isLoaded: value.isLoaded,+ animationDuration: value.animationDuration,+ enterTransition: value.enterTransition,+ revealEpoch: value.revealEpoch,+ }),+ [+ value.features,+ value.featureCollection,+ value.featurePaths,+ value.pathGenerator,+ value.rawPathGenerator,+ value.projectPoint,+ value.width,+ value.height,+ value.innerWidth,+ value.innerHeight,+ value.margin,+ value.containerRef,+ value.isLoaded,+ value.animationDuration,+ value.enterTransition,+ value.revealEpoch,+ ]+ );++ const interaction = useMemo<ChoroplethInteractionContextValue>(+ () => ({+ hoveredFeatureIndex: value.hoveredFeatureIndex,+ setHoveredFeatureIndex: value.setHoveredFeatureIndex,+ tooltipData: value.tooltipData,+ setTooltipData: value.setTooltipData,+ }),+ [+ value.hoveredFeatureIndex,+ value.setHoveredFeatureIndex,+ value.tooltipData,+ value.setTooltipData,+ ]+ );++ return (+ <ChoroplethStableProvider value={stable}>+ <ChoroplethInteractionContext.Provider value={interaction}>+ {children}+ </ChoroplethInteractionContext.Provider>+ </ChoroplethStableProvider>+ );+}++export function useChoroplethStable(): ChoroplethStableContextValue {+ const context = useContext(ChoroplethStableContext);+ if (!context) {+ throw new Error(+ 'useChoroplethStable must be used within a ChoroplethProvider'+ );+ }+ return context;+}++export function useChoroplethInteraction(): ChoroplethInteractionContextValue {+ const context = useContext(ChoroplethInteractionContext);+ if (!context) {+ throw new Error(+ 'useChoroplethInteraction must be used within a ChoroplethProvider'+ );+ }+ return context;+}++export function useChoropleth(): ChoroplethContextValue {+ return { ...useChoroplethStable(), ...useChoroplethInteraction() };+}++import { CHART_SCALE_VARS, chartScaleCssVars } from '../chart-scale';++// CSS variables for choropleth theming+export const choroplethCssVars = {+ scale01: chartScaleCssVars.scale01,+ scale02: chartScaleCssVars.scale02,+ scale03: chartScaleCssVars.scale03,+ scale04: chartScaleCssVars.scale04,+ scale05: chartScaleCssVars.scale05,+ patternColor: chartScaleCssVars.patternColor,+ stroke: 'var(--chart-grid)',+ background: 'var(--background)',+};++// Default colors array for cycling through features+export const defaultChoroplethColors = [...CHART_SCALE_VARS];diff --git a/apps/start/src/components/charts/choropleth/choropleth-feature.tsx b/apps/start/src/components/charts/choropleth/choropleth-feature.tsxnew file mode 100644index 000000000..b8e1feebc--- /dev/null+++ b/apps/start/src/components/charts/choropleth/choropleth-feature.tsx@@ -0,0 +1,339 @@+'use client';++import { geoCentroid } from 'd3-geo';+import { motion, useTransform } from 'motion/react';+import { memo, useCallback, useMemo } from 'react';+import { useEnterComplete } from '../use-enter-complete';+import { useMountProgress } from '../use-mount-progress';+import {+ type ChoroplethFeature as ChoroplethFeatureType,+ defaultChoroplethColors,+ useChoroplethInteraction,+ useChoroplethStable,+} from './choropleth-context';++export interface ChoroplethFeatureProps {+ fill?: string;+ stroke?: string;+ strokeWidth?: number;+ fadedOpacity?: number;+ getFeatureColor?: (feature: ChoroplethFeatureType, index: number) => string;+ patterns?: React.ReactNode;+ getFeaturePattern?: (+ feature: ChoroplethFeatureType,+ index: number+ ) => string | null | undefined;+}++interface FeatureRecord {+ index: number;+ path: string;+ fill: string;+ feature: ChoroplethFeatureType;+ centroid: { x: number; y: number } | null;+}++function resolveFeatureFill(+ feature: ChoroplethFeatureType,+ index: number,+ fill: string | undefined,+ getFeatureColor: ChoroplethFeatureProps['getFeatureColor'],+ getFeaturePattern: ChoroplethFeatureProps['getFeaturePattern']+): string {+ const patternId = getFeaturePattern?.(feature, index);+ if (patternId) {+ return `url(#${patternId})`;+ }+ if (fill) {+ return fill;+ }+ if (getFeatureColor) {+ return getFeatureColor(feature, index);+ }+ return (+ defaultChoroplethColors[index % defaultChoroplethColors.length] ??+ 'var(--chart-1)'+ );+}++const StaticFeatureLayer = memo(function StaticFeatureLayer({+ records,+ stroke,+ strokeWidth,+ baseOpacity,+ dimOpacity,+ hoveredIndex,+ onFeatureEnter,+ onFeatureLeave,+}: {+ records: FeatureRecord[];+ stroke: string;+ strokeWidth: number;+ baseOpacity: number;+ dimOpacity: number;+ hoveredIndex: number | null;+ onFeatureEnter: (record: FeatureRecord) => void;+ onFeatureLeave: () => void;+}) {+ const isDimmed = hoveredIndex !== null;++ if (!isDimmed) {+ return (+ <g opacity={baseOpacity}>+ {records.map((record) => (+ // biome-ignore lint/a11y/noStaticElementInteractions: SVG path used as hover hitbox+ <path+ className="cursor-pointer"+ d={record.path}+ fill={record.fill}+ key={`base-${record.index}`}+ onMouseEnter={() => onFeatureEnter(record)}+ onMouseLeave={onFeatureLeave}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ ))}+ </g>+ );+ }++ const highlighted = records.find((record) => record.index === hoveredIndex);++ return (+ <>+ <g opacity={dimOpacity} style={{ transition: 'opacity 0.18s ease-out' }}>+ {records+ .filter((record) => record.index !== hoveredIndex)+ .map((record) => (+ // biome-ignore lint/a11y/noStaticElementInteractions: SVG path used as hover hitbox+ <path+ className="cursor-pointer"+ d={record.path}+ fill={record.fill}+ key={`base-${record.index}`}+ onMouseEnter={() => onFeatureEnter(record)}+ onMouseLeave={onFeatureLeave}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ ))}+ </g>+ {highlighted ? (+ // biome-ignore lint/a11y/noStaticElementInteractions: SVG path used as hover hitbox+ <path+ className="cursor-pointer"+ d={highlighted.path}+ fill={highlighted.fill}+ key={`highlight-${highlighted.index}`}+ onMouseEnter={() => onFeatureEnter(highlighted)}+ onMouseLeave={onFeatureLeave}+ opacity={1}+ stroke={stroke}+ strokeWidth={strokeWidth}+ style={{ transition: 'opacity 0.18s ease-out' }}+ />+ ) : null}+ </>+ );+});++const EnterFeatureLayer = memo(function EnterFeatureLayer({+ records,+ stroke,+ strokeWidth,+ baseOpacity,+ dimOpacity,+ hoveredIndex,+ onFeatureEnter,+ onFeatureLeave,+ revealEpoch,+}: {+ records: FeatureRecord[];+ stroke: string;+ strokeWidth: number;+ baseOpacity: number;+ dimOpacity: number;+ hoveredIndex: number | null;+ onFeatureEnter: (record: FeatureRecord) => void;+ onFeatureLeave: () => void;+ revealEpoch: number;+}) {+ const { enterTransition, animationDuration } = useChoroplethStable();+ const mountProgress = useMountProgress(+ enterTransition,+ 0,+ `choropleth-layer-${revealEpoch}`+ );+ const enterComplete = useEnterComplete(mountProgress);+ const layerOpacity = useTransform(mountProgress, (t) => t * baseOpacity);++ if (enterComplete) {+ return (+ <StaticFeatureLayer+ baseOpacity={baseOpacity}+ dimOpacity={dimOpacity}+ hoveredIndex={hoveredIndex}+ onFeatureEnter={onFeatureEnter}+ onFeatureLeave={onFeatureLeave}+ records={records}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ );+ }++ return (+ <motion.g+ key={`enter-${revealEpoch}`}+ opacity={layerOpacity}+ transition={{+ duration: animationDuration / 1000,+ ease: 'easeOut',+ }}+ >+ {records.map((record) => (+ // biome-ignore lint/a11y/noStaticElementInteractions: SVG path used as hover hitbox+ <path+ className="cursor-pointer"+ d={record.path}+ fill={record.fill}+ key={`enter-${record.index}`}+ onMouseEnter={() => onFeatureEnter(record)}+ onMouseLeave={onFeatureLeave}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ ))}+ </motion.g>+ );+});++export const ChoroplethFeature = memo(function ChoroplethFeature({+ fill,+ stroke = 'var(--background)',+ strokeWidth = 0.5,+ fadedOpacity = 0.4,+ getFeatureColor,+ patterns,+ getFeaturePattern,+}: ChoroplethFeatureProps) {+ const {+ features,+ featurePaths,+ pathGenerator,+ projectPoint,+ isLoaded,+ revealEpoch,+ width,+ height,+ } = useChoroplethStable();+ const { hoveredFeatureIndex, setHoveredFeatureIndex, setTooltipData } =+ useChoroplethInteraction();++ const featureCentroids = useMemo(() => {+ return features.map((feature) => {+ try {+ const centroid = geoCentroid(feature);+ if (+ centroid &&+ !Number.isNaN(centroid[0]) &&+ !Number.isNaN(centroid[1])+ ) {+ const projected = projectPoint(centroid as [number, number]);+ if (projected) {+ const padding = 60;+ return {+ x: Math.max(padding, Math.min(width - padding, projected[0])),+ y: Math.max(padding, Math.min(height - padding, projected[1])),+ };+ }+ }+ } catch {+ // Some geometries may not have valid centroids+ }+ return null;+ });+ }, [features, projectPoint, width, height]);++ const records = useMemo(() => {+ const items: FeatureRecord[] = [];+ for (let index = 0; index < features.length; index++) {+ const feature = features[index];+ if (!feature) {+ continue;+ }++ const path = featurePaths[index] ?? pathGenerator(feature);+ if (!path) {+ continue;+ }++ items.push({+ index,+ path,+ fill: resolveFeatureFill(+ feature,+ index,+ fill,+ getFeatureColor,+ getFeaturePattern+ ),+ feature,+ centroid: featureCentroids[index] ?? null,+ });+ }+ return items;+ }, [+ featureCentroids,+ featurePaths,+ features,+ fill,+ getFeatureColor,+ getFeaturePattern,+ pathGenerator,+ ]);++ const handleFeatureEnter = useCallback(+ (record: FeatureRecord) => {+ setHoveredFeatureIndex(record.index);+ setTooltipData({+ featureIndex: record.index,+ x: record.centroid?.x ?? width / 2,+ y: record.centroid?.y ?? height / 2,+ feature: record.feature,+ });+ },+ [height, setHoveredFeatureIndex, setTooltipData, width]+ );++ const handleFeatureLeave = useCallback(() => {+ setHoveredFeatureIndex(null);+ setTooltipData(null);+ }, [setHoveredFeatureIndex, setTooltipData]);++ const layerProps = {+ baseOpacity: 0.85,+ dimOpacity: fadedOpacity,+ hoveredIndex: hoveredFeatureIndex,+ onFeatureEnter: handleFeatureEnter,+ onFeatureLeave: handleFeatureLeave,+ records,+ stroke,+ strokeWidth,+ };++ return (+ <g className="choropleth-features">+ {patterns ? <defs>{patterns}</defs> : null}+ {isLoaded ? (+ <StaticFeatureLayer {...layerProps} />+ ) : (+ <EnterFeatureLayer {...layerProps} revealEpoch={revealEpoch} />+ )}+ </g>+ );+});++ChoroplethFeature.displayName = 'ChoroplethFeature';++export default ChoroplethFeature;diff --git a/apps/start/src/components/charts/choropleth/choropleth-graticule.tsx b/apps/start/src/components/charts/choropleth/choropleth-graticule.tsxnew file mode 100644index 000000000..46c242618--- /dev/null+++ b/apps/start/src/components/charts/choropleth/choropleth-graticule.tsx@@ -0,0 +1,35 @@+'use client';++import { Graticule } from '@visx/geo';+import { memo } from 'react';+import { useChoroplethStable } from './choropleth-context';++export interface ChoroplethGraticuleProps {+ /** Stroke color for graticule lines. Default: rgba(255,255,255,0.1) */+ stroke?: string;+ /** Stroke width for graticule lines. Default: 0.5 */+ strokeWidth?: number;+ /** Step intervals for graticule lines [longitude, latitude] in degrees. Default: [10, 10] */+ step?: [number, number];+}++export const ChoroplethGraticule = memo(function ChoroplethGraticule({+ stroke = 'rgba(255,255,255,0.1)',+ strokeWidth = 0.5,+ step,+}: ChoroplethGraticuleProps) {+ const { rawPathGenerator } = useChoroplethStable();++ return (+ <Graticule+ graticule={(g) => rawPathGenerator(g) || ''}+ step={step}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ );+});++ChoroplethGraticule.displayName = 'ChoroplethGraticule';++export default ChoroplethGraticule;diff --git a/apps/start/src/components/charts/choropleth/choropleth-tooltip.tsx b/apps/start/src/components/charts/choropleth/choropleth-tooltip.tsxnew file mode 100644index 000000000..da715e87f--- /dev/null+++ b/apps/start/src/components/charts/choropleth/choropleth-tooltip.tsx@@ -0,0 +1,131 @@+'use client';++import { intFmt } from '../chart-formatters';+import { TooltipBox } from '../tooltip/tooltip-box';+import { TooltipContent, type TooltipRow } from '../tooltip/tooltip-content';+import {+ type ChoroplethFeature,+ useChoroplethInteraction,+ useChoroplethStable,+ useChoroplethZoom,+} from './choropleth-context';++export interface ChoroplethTooltipProps {+ /** Custom content renderer for feature tooltips */+ content?: (props: {+ feature: ChoroplethFeature;+ index: number;+ }) => React.ReactNode;+ /** Value formatter function */+ formatValue?: (value: number) => string;+ /** Get the display name for a feature. Default: uses feature.properties.name */+ getFeatureName?: (feature: ChoroplethFeature, index: number) => string;+ /** Get the value for a feature (for display in tooltip) */+ getFeatureValue?: (+ feature: ChoroplethFeature,+ index: number+ ) => number | undefined;+ /** Label for the value row. Default: "Value" */+ valueLabel?: string;+ /** Custom class name */+ className?: string;+ /** Inline styles for the tooltip panel (background, blur, etc.). */+ panelStyle?: React.CSSProperties;+ /**+ * Tooltip panel background color (CSS variable or color value).+ * Default: `var(--chart-tooltip-background)`.+ */+ backgroundColor?: string;+}++export function ChoroplethTooltip({+ content,+ formatValue = intFmt,+ getFeatureName,+ getFeatureValue,+ valueLabel = 'Value',+ className = '',+ panelStyle,+ backgroundColor,+}: ChoroplethTooltipProps) {+ const { containerRef, width, height, features } = useChoroplethStable();+ const { tooltipData } = useChoroplethInteraction();+ const { zoom } = useChoroplethZoom();++ if (!tooltipData) {+ return null;+ }++ // Apply zoom transform to centroid position+ let x = tooltipData.x;+ let y = tooltipData.y;++ if (zoom) {+ // Apply the zoom transform matrix to the tooltip position+ const transformed = zoom.applyToPoint({ x, y });+ x = transformed.x;+ y = transformed.y;+ }++ const feature = features[tooltipData.featureIndex];+ if (!feature) {+ return null;+ }++ // Get feature name+ const featureName = getFeatureName+ ? getFeatureName(feature, tooltipData.featureIndex)+ : (feature.properties?.name ?? `Feature ${tooltipData.featureIndex}`);++ // Custom content+ if (content) {+ return (+ <TooltipBox+ backgroundColor={backgroundColor}+ className={className}+ containerHeight={height}+ containerRef={containerRef}+ containerWidth={width}+ panelStyle={panelStyle}+ visible+ x={x}+ y={y}+ >+ {content({ feature, index: tooltipData.featureIndex })}+ </TooltipBox>+ );+ }++ // Default tooltip with optional value+ const value = getFeatureValue?.(feature, tooltipData.featureIndex);+ const rows: TooltipRow[] =+ value === undefined+ ? []+ : [+ {+ color: 'var(--chart-1)',+ label: valueLabel,+ value: formatValue(value),+ },+ ];++ return (+ <TooltipBox+ backgroundColor={backgroundColor}+ className={className}+ containerHeight={height}+ containerRef={containerRef}+ containerWidth={width}+ panelStyle={panelStyle}+ visible+ x={x}+ y={y}+ >+ <TooltipContent rows={rows} title={featureName} />+ </TooltipBox>+ );+}++ChoroplethTooltip.displayName = 'ChoroplethTooltip';++export default ChoroplethTooltip;diff --git a/apps/start/src/components/charts/choropleth/index.ts b/apps/start/src/components/charts/choropleth/index.tsnew file mode 100644index 000000000..e920ee93a--- /dev/null+++ b/apps/start/src/components/charts/choropleth/index.ts@@ -0,0 +1,26 @@+export type { TransformMatrix } from '@visx/zoom';+export { ChoroplethChart, type ChoroplethChartProps } from './choropleth-chart';+export {+ type ChoroplethContextValue,+ type ChoroplethFeature,+ type ChoroplethFeatureProperties,+ ChoroplethProvider,+ type ChoroplethTooltipData,+ choroplethCssVars,+ defaultChoroplethColors,+ type Margin,+ useChoropleth,+ useChoroplethZoom,+} from './choropleth-context';+export {+ ChoroplethFeature as ChoroplethFeatureComponent,+ type ChoroplethFeatureProps,+} from './choropleth-feature';+export {+ ChoroplethGraticule,+ type ChoroplethGraticuleProps,+} from './choropleth-graticule';+export {+ ChoroplethTooltip,+ type ChoroplethTooltipProps,+} from './choropleth-tooltip';diff --git a/apps/start/src/components/charts/common-bar.tsx b/apps/start/src/components/charts/common-bar.tsxdeleted file mode 100644index 6538fa2db..000000000--- a/apps/start/src/components/charts/common-bar.tsx+++ /dev/null@@ -1,108 +0,0 @@-import { getChartColor, getChartTranslucentColor } from '@/utils/theme';--type Options = {- borderHeight: number;- border: string;- fill: string;- active: { border: string; fill: string };-};--export const BarWithBorder = (options: Options) => {- return (props: any) => {- const { x, y, width, height, value, isActive } = props;-- const fill =- options.fill === 'props'- ? props.fill- : isActive- ? options.active.fill- : options.fill;- const border =- options.border === 'props'- ? props.stroke- : isActive- ? options.active.border- : options.border;-- const withActive = (color: string) => {- if (color.startsWith('rgba')) {- return isActive ? color.replace(/, 0.\d+\)$/, ', 0.4)') : color;- }- return color;- };-- return (- <g>- <rect- fill={withActive(fill)}- height={height}- rx={3}- stroke="none"- width={width}- x={x}- y={y}- />- {value > 0 && (- <rect- fill={withActive(border)}- height={options.borderHeight}- rx={2}- stroke="none"- width={width}- x={x}- y={y - options.borderHeight - 1}- />- )}- </g>- );- };-};--export const BarShapeGrey = BarWithBorder({- borderHeight: 2,- border: 'rgba(100, 100, 100, 1)',- fill: 'rgba(100, 100, 100, 0.3)',- active: {- border: 'rgba(100, 100, 100, 1)',- fill: 'rgba(100, 100, 100, 0.4)',- },-});-export const BarShapeBlue = BarWithBorder({- borderHeight: 2,- border: 'rgba(59, 121, 255, 1)',- fill: 'rgba(59, 121, 255, 0.3)',- active: {- border: 'rgba(59, 121, 255, 1)',- fill: 'rgba(59, 121, 255, 0.4)',- },-});-export const BarShapeGreen = BarWithBorder({- borderHeight: 2,- border: 'rgba(59, 169, 116, 1)',- fill: 'rgba(59, 169, 116, 0.3)',- active: {- border: 'rgba(59, 169, 116, 1)',- fill: 'rgba(59, 169, 116, 0.4)',- },-});-export const BarShapeProps = BarWithBorder({- borderHeight: 2,- border: 'props',- fill: 'props',- active: {- border: 'props',- fill: 'props',- },-});--const BarShapes = [...new Array(13)].map((_, index) =>- BarWithBorder({- borderHeight: 2,- border: getChartColor(index),- fill: getChartTranslucentColor(index),- active: {- border: getChartColor(index),- fill: getChartTranslucentColor(index),- },- })-);diff --git a/apps/start/src/components/charts/composed-chart.tsx b/apps/start/src/components/charts/composed-chart.tsxindex 7fd777b6f..99d04be82 100644--- a/apps/start/src/components/charts/composed-chart.tsx+++ b/apps/start/src/components/charts/composed-chart.tsx@@ -41,6 +41,10 @@ export interface ComposedChartProps {stacked?: boolean;/** Gap in px between stacked segments. Default: 0 */stackGap?: number;+ /** Formats the x-axis and crosshair date labels. Default: `shortDateFmt`. */+ formatDateLabel?: (date: Date) => string;+ /** Fixed y domain per `yAxisId`; axes not listed keep their data-driven domain. */+ yDomains?: Record<string, [number, number]>;}const DEFAULT_MARGIN: Margin = { top: 40, right: 40, bottom: 40, left: 40 };@@ -80,6 +84,7 @@ function tryAppendSeriesBar(dataKey: props.dataKey,stroke: props.stroke || props.fill || 'var(--chart-line-primary)',strokeWidth: 0,+ yAxisId: props.yAxisId,});return true;}@@ -95,6 +100,7 @@ function tryAppendLine(child: ReactElement, lines: LineConfig[]): boolean {dataKey: props.dataKey,stroke: props.stroke || 'var(--chart-line-primary)',strokeWidth: props.strokeWidth ?? 2.5,+ yAxisId: props.yAxisId,});}return true;@@ -111,6 +117,7 @@ function tryAppendArea(child: ReactElement, lines: LineConfig[]): boolean {dataKey: props.dataKey,stroke: props.stroke || props.fill || 'var(--chart-line-primary)',strokeWidth: props.strokeWidth ?? 2,+ yAxisId: props.yAxisId,});}return true;@@ -186,6 +193,8 @@ interface ChartInnerProps {barGap?: number;stacked?: boolean;stackGap?: number;+ formatDateLabel?: (date: Date) => string;+ yDomains?: Record<string, [number, number]>;}function ChartInner({@@ -205,6 +214,8 @@ function ChartInner({barGap,stacked = false,stackGap = 0,+ formatDateLabel,+ yDomains,}: ChartInnerProps) {const { lines, barDataKeys } = useMemo(() => extractComposedSeries(children),@@ -258,12 +269,14 @@ function ChartInner({containerRef={containerRef}data={data}enterTransition={enterTransition}+ formatDateLabel={formatDateLabel}height={height}lines={lines}margin={margin}revealSignature={revealSignature}width={width}xDataKey={xDataKey}+ yDomains={yDomains}yScaleDomainMax={yScaleDomainMax}>{children}@@ -287,6 +300,8 @@ export function ComposedChart({barGap = 4,stacked = false,stackGap = 0,+ formatDateLabel,+ yDomains,}: ComposedChartProps) {const containerRef = useRef<HTMLDivElement>(null);const margin = { ...DEFAULT_MARGIN, ...marginProp };@@ -295,7 +310,7 @@ export function ComposedChart({<divclassName={cn('relative w-full', className)}ref={containerRef}- style={{ aspectRatio, touchAction: 'none' }}+ style={{ aspectRatio, touchAction: 'pan-y' }}><ParentSize debounceTime={10}>{({ width, height }) => (@@ -307,6 +322,7 @@ export function ComposedChart({containerRef={containerRef}data={data}enterTransition={enterTransition}+ formatDateLabel={formatDateLabel}height={height}margin={margin}maxBarSize={maxBarSize}@@ -315,6 +331,7 @@ export function ComposedChart({stackGap={stackGap}width={width}xDataKey={xDataKey}+ yDomains={yDomains}>{children}</ChartInner>diff --git a/apps/start/src/components/charts/dash-tail-stroke.tsx b/apps/start/src/components/charts/dash-tail-stroke.tsxindex 099407067..4d71b9828 100644--- a/apps/start/src/components/charts/dash-tail-stroke.tsx+++ b/apps/start/src/components/charts/dash-tail-stroke.tsx@@ -5,11 +5,7 @@ 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. */+ /** X coordinate (chart inner space) where the dashed tail begins. */dashStartX: number;innerWidth: number;innerHeight: number;@@ -19,10 +15,11 @@ export interface DashTailStrokeProps {dashArray: string;}+// Both halves are clipped at the same x. Splitting by path length instead+// needs the length at that x, which only an expensive search gets right on+// steep curves; an estimate drew the solid head on top of the dashed tail.export function DashTailStroke({pathD,- pathLength,- dashStartLength,dashStartX,innerWidth,innerHeight,@@ -30,39 +27,43 @@ export function DashTailStroke({strokeWidth,dashArray,}: DashTailStrokeProps) {- const clipPathId = useId().replace(/:/g, '');+ const id = useId().replace(/:/g, '');+ const headClipId = `${id}-head`;+ const tailClipId = `${id}-tail`;- if (!pathD || pathLength <= 0 || dashStartLength >= pathLength) {+ if (!pathD) {return null;}const pad = strokeWidth * 2;- const tailWidth = Math.max(0, innerWidth - dashStartX + pad);+ const top = -pad;+ const height = innerHeight + pad * 2;return (<><defs>- <clipPath id={clipPathId}>+ <clipPath id={headClipId}>+ <rect height={height} width={dashStartX + pad} x={-pad} y={top} />+ </clipPath>+ <clipPath id={tailClipId}><rect- height={innerHeight + pad}- width={tailWidth}- x={dashStartX - strokeWidth}- y={-strokeWidth}+ height={height}+ width={Math.max(0, innerWidth - dashStartX + pad)}+ x={dashStartX}+ y={top}/></clipPath></defs>- {/* Solid head — same curved path, gradient/fade preserved */}<path+ clipPath={`url(#${headClipId})`}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})`}+ clipPath={`url(#${tailClipId})`}d={pathD}fill="none"stroke={stroke}diff --git a/apps/start/src/components/charts/decimate-time-series.ts b/apps/start/src/components/charts/decimate-time-series.tsindex c0b298c6c..d39ff3ebe 100644--- a/apps/start/src/components/charts/decimate-time-series.ts+++ b/apps/start/src/components/charts/decimate-time-series.ts@@ -1,3 +1,7 @@+/**+ * Largest-Triangle-Three-Buckets downsampling for time-series SVG paths.+ * Keeps first/last points and picks visually significant points per bucket.+ */export function decimateTimeSeries<T extends Record<string, unknown>>(data: T[],maxPoints: number,diff --git a/apps/start/src/components/charts/fade-edges.ts b/apps/start/src/components/charts/fade-edges.tsindex 8d1c50a68..b78f32b26 100644--- a/apps/start/src/components/charts/fade-edges.ts+++ b/apps/start/src/components/charts/fade-edges.ts@@ -1,3 +1,9 @@+/**+ * Which side(s) of a series should fade to transparent at the chart edges.+ * - `true` → fade both edges (default for `<Line>`)+ * - `false` → no fade (default for `<Area>`)+ * - `"left"` / `"right"` → fade only that side+ */export type FadeEdges = boolean | 'left' | 'right';export interface FadeSides {@@ -39,3 +45,14 @@ export function fadeGradientStops(sides: FadeSides): FadeGradientStop[] {{ offset: '100%', opacity: sides.right ? 0 : 1 },];}++/** Horizontal fade gradient pinned to the chart viewport (not the series path bounds). */+export function viewportFadeGradientAttrs(innerWidth: number) {+ return {+ gradientUnits: 'userSpaceOnUse' as const,+ x1: 0,+ x2: innerWidth,+ y1: 0,+ y2: 0,+ };+}diff --git a/apps/start/src/components/charts/filter-data-by-x-domain.ts b/apps/start/src/components/charts/filter-data-by-x-domain.tsnew file mode 100644index 000000000..6c7227972--- /dev/null+++ b/apps/start/src/components/charts/filter-data-by-x-domain.ts@@ -0,0 +1,59 @@+export function filterDataByXDomain(+ data: Record<string, unknown>[],+ xDomain: [Date, Date],+ xAccessor: (d: Record<string, unknown>) => Date+): Record<string, unknown>[] {+ const start = xDomain[0].getTime();+ const end = xDomain[1].getTime();+ const minTime = Math.min(start, end);+ const maxTime = Math.max(start, end);++ return data.filter((d) => {+ const time = xAccessor(d).getTime();+ return time >= minTime && time <= maxTime;+ });+}++export function resolveDataXExtent(+ data: Record<string, unknown>[],+ xAccessor: (d: Record<string, unknown>) => Date+): [Date, Date] | null {+ if (data.length === 0) {+ return null;+ }++ let minTime = Number.POSITIVE_INFINITY;+ let maxTime = Number.NEGATIVE_INFINITY;++ for (const point of data) {+ const time = xAccessor(point).getTime();+ if (time < minTime) {+ minTime = time;+ }+ if (time > maxTime) {+ maxTime = time;+ }+ }++ if (minTime === Number.POSITIVE_INFINITY) {+ return null;+ }++ return [new Date(minTime), new Date(maxTime)];+}++/** Brush track extent — optionally extends past the last data row (e.g. projections). */+export function resolveBrushTrackXExtent(+ data: Record<string, unknown>[],+ xAccessor: (d: Record<string, unknown>) => Date,+ xExtentMax?: Date+): [Date, Date] | null {+ const extent = resolveDataXExtent(data, xAccessor);+ if (!extent) {+ return null;+ }+ if (!xExtentMax || xExtentMax.getTime() <= extent[1].getTime()) {+ return extent;+ }+ return [extent[0], xExtentMax];+}diff --git a/apps/start/src/components/charts/funnel-chart.tsx b/apps/start/src/components/charts/funnel-chart.tsxnew file mode 100644index 000000000..5e59684be--- /dev/null+++ b/apps/start/src/components/charts/funnel-chart.tsx@@ -0,0 +1,1041 @@+'use client';++import type { Transition } from 'motion/react';+import { motion, useTransform } from 'motion/react';+import {+ type CSSProperties,+ type ReactNode,+ useCallback,+ useEffect,+ useRef,+ useState,+} from 'react';+import { useEnterComplete } from './use-enter-complete';+import { useMountProgress } from './use-mount-progress';+import { cn } from '@/lib/utils';++// ─── Public types ───────────────────────────────────────────────────++export interface FunnelGradientStop {+ offset: string | number;+ color: string;+}++export interface FunnelStage {+ label: string;+ value: number;+ displayValue?: string;+ /** Override the chart-level color for this segment */+ color?: string;+ /**+ * Apply a linear gradient to this segment.+ * Provide an array of color stops, e.g. `[{ offset: "0%", color: "#8B5CF6" }, { offset: "100%", color: "#3B82F6" }]`.+ * When set, this takes priority over the segment and chart-level `color` for the innermost ring.+ * Outer halo rings use the first stop color as their solid color.+ */+ gradient?: FunnelGradientStop[];+}++export interface FunnelChartProps {+ data: FunnelStage[];+ orientation?: 'horizontal' | 'vertical';+ color?: string;+ layers?: number;+ className?: string;+ style?: CSSProperties;+ showPercentage?: boolean;+ showValues?: boolean;+ showLabels?: boolean;+ /** Controlled hover state — index of the hovered segment */+ hoveredIndex?: number | null;+ /** Callback when hover state changes */+ onHoverChange?: (index: number | null) => void;+ formatPercentage?: (pct: number) => string;+ formatValue?: (value: number) => string;+ /** Stagger delay between segments in seconds. Default 0.12 */+ staggerDelay?: number;+ /** Framer Motion transition for segment enter animation */+ enterTransition?: Transition;+ /** Gap between segments in pixels. Default 4 */+ gap?: number;+ /**+ * Render a visx pattern definition. Receives a unique `id` string per segment+ * and the resolved `color`. Return a `<PatternLines>` (or any visx pattern)+ * inside an SVG `<defs>`. The component will use `fill="url(#id)"` on the+ * innermost ring while keeping outer halo rings as solid color.+ */+ renderPattern?: (id: string, color: string) => ReactNode;+ /** Edge style for the funnel segments. Default "curved" */+ edges?: 'curved' | 'straight';+ /**+ * Controls how segment labels (value, percentage, stage name) are arranged.+ * - "spread": Value/percentage/label are spread apart (top/center/bottom for horizontal,+ * left/center/right for vertical). This is the default.+ * - "grouped": All label items stack together in a tight group.+ *+ * When "grouped", use `labelOrientation` and `labelAlign` for full control.+ */+ labelLayout?: 'spread' | 'grouped';+ /**+ * Stack direction of the label group. Only applies when `labelLayout="grouped"`.+ * - "vertical": Items stack top-to-bottom. Default for horizontal funnels.+ * - "horizontal": Items stack left-to-right. Default for vertical funnels.+ */+ labelOrientation?: 'vertical' | 'horizontal';+ /**+ * Where the label group sits within the segment cell.+ * - "center" (default), "start", "end"+ * For horizontal funnel: start=top, end=bottom.+ * For vertical funnel: start=left, end=right.+ */+ labelAlign?: 'center' | 'start' | 'end';+ /** Grid configuration. Pass `true` for default bands + lines, or an object for fine control. */+ grid?:+ | boolean+ | {+ /** Show alternating background bands behind each segment. Default true */+ bands?: boolean;+ /** Color of the background bands. Default "var(--color-muted)" */+ bandColor?: string;+ /** Show grid lines at each gap between segments. Default true */+ lines?: boolean;+ /** Color of the grid lines. Default "var(--chart-grid)" */+ lineColor?: string;+ /** Opacity of the grid lines. Default 1 */+ lineOpacity?: number;+ /** Width of the grid lines in pixels. Default 1 */+ lineWidth?: number;+ };+}++// ─── Defaults ───────────────────────────────────────────────────────++import { intFmt } from './chart-formatters';++const fmtPct = (p: number) => `${Math.round(p)}%`;+const fmtVal = intFmt;++// ─── SVG helpers ────────────────────────────────────────────────────++/**+ * Builds a single segment path for one stage in the funnel.+ * Each segment is a smooth trapezoid-like shape transitioning from+ * the height of the current norm to the next norm.+ */+function hSegmentPath(+ normStart: number,+ normEnd: number,+ segW: number,+ H: number,+ layerScale: number,+ straight = false+) {+ const my = H / 2;+ const h0 = normStart * H * 0.44 * layerScale;+ const h1 = normEnd * H * 0.44 * layerScale;++ if (straight) {+ return `M 0 ${my - h0} L ${segW} ${my - h1} L ${segW} ${my + h1} L 0 ${my + h0} Z`;+ }++ const cx = segW * 0.55;+ const top = `M 0 ${my - h0} C ${cx} ${my - h0}, ${segW - cx} ${my - h1}, ${segW} ${my - h1}`;+ const bot = `L ${segW} ${my + h1} C ${segW - cx} ${my + h1}, ${cx} ${my + h0}, 0 ${my + h0}`;+ return `${top} ${bot} Z`;+}++function vSegmentPath(+ normStart: number,+ normEnd: number,+ segH: number,+ W: number,+ layerScale: number,+ straight = false+) {+ const mx = W / 2;+ const w0 = normStart * W * 0.44 * layerScale;+ const w1 = normEnd * W * 0.44 * layerScale;++ if (straight) {+ return `M ${mx - w0} 0 L ${mx - w1} ${segH} L ${mx + w1} ${segH} L ${mx + w0} 0 Z`;+ }++ const cy = segH * 0.55;+ const left = `M ${mx - w0} 0 C ${mx - w0} ${cy}, ${mx - w1} ${segH - cy}, ${mx - w1} ${segH}`;+ const right = `L ${mx + w1} ${segH} C ${mx + w1} ${segH - cy}, ${mx + w0} ${cy}, ${mx + w0} 0`;+ return `${left} ${right} Z`;+}++// ─── Animated Segment ───────────────────────────────────────────────++function HRing({+ d,+ color,+ fill,+ opacity,+ hovered,+ ringIndex,+ totalRings,+}: {+ d: string;+ color: string;+ fill?: string;+ opacity: number;+ hovered: boolean;+ ringIndex: number;+ totalRings: number;+}) {+ const extraScale = 1 + (ringIndex / Math.max(totalRings - 1, 1)) * 0.12;++ return (+ <motion.path+ animate={{ scaleY: hovered ? extraScale : 1 }}+ d={d}+ fill={fill ?? color}+ opacity={opacity}+ style={{ transformOrigin: 'center center' }}+ transition={{+ type: 'spring',+ stiffness: 300 - ringIndex * 60,+ damping: 24 - ringIndex * 3,+ }}+ />+ );+}++function HSegment({+ index,+ normStart,+ normEnd,+ segW,+ fullH,+ color,+ layers,+ staggerDelay,+ enterTransition,+ hovered,+ dimmed,+ renderPattern,+ straight,+ gradientStops,+}: {+ index: number;+ normStart: number;+ normEnd: number;+ segW: number;+ fullH: number;+ color: string;+ layers: number;+ staggerDelay: number;+ enterTransition?: Transition;+ hovered: boolean;+ dimmed: boolean;+ renderPattern?: (id: string, color: string) => ReactNode;+ straight: boolean;+ gradientStops?: FunnelGradientStop[];+}) {+ const patternId = `funnel-h-pattern-${index}`;+ const gradientId = `funnel-h-grad-${index}`;+ const mountProgress = useMountProgress(+ enterTransition,+ index * staggerDelay,+ index+ );+ const enterComplete = useEnterComplete(mountProgress);+ const entranceScaleX = useTransform(mountProgress, [0, 1], [0, 1]);+ const entranceScaleY = useTransform(mountProgress, [0, 1], [0, 1]);++ const rings = Array.from({ length: layers }, (_, l) => {+ const scale = 1 - (l / layers) * 0.35;+ const opacity = 0.18 + (l / (layers - 1 || 1)) * 0.65;+ return {+ d: hSegmentPath(normStart, normEnd, segW, fullH, scale, straight),+ opacity,+ };+ });++ return (+ <motion.div+ animate={{ opacity: dimmed ? 0.4 : 1 }}+ className="pointer-events-none relative shrink-0 overflow-visible"+ style={{+ width: segW,+ height: fullH,+ zIndex: hovered ? 10 : 1,+ }}+ transition={{ opacity: { duration: 0.15 } }}+ >+ {enterComplete ? (+ <div className="absolute inset-0 overflow-visible">+ <svg+ aria-hidden="true"+ className="absolute inset-0 h-full w-full overflow-visible"+ preserveAspectRatio="none"+ role="presentation"+ viewBox={`0 0 ${segW} ${fullH}`}+ >+ <defs>+ {gradientStops && (+ <linearGradient id={gradientId} x1="0" x2="1" y1="0" y2="0">+ {gradientStops.map((stop) => (+ <stop+ key={`${stop.offset}-${stop.color}`}+ offset={+ typeof stop.offset === 'number'+ ? `${stop.offset * 100}%`+ : stop.offset+ }+ stopColor={stop.color}+ />+ ))}+ </linearGradient>+ )}+ {renderPattern?.(patternId, color)}+ </defs>+ {rings.map((r, i) => {+ const isInnermost = i === rings.length - 1;+ let ringFill: string | undefined;+ if (isInnermost && renderPattern) {+ ringFill = `url(#${patternId})`;+ } else if (isInnermost && gradientStops) {+ ringFill = `url(#${gradientId})`;+ }+ const ringKey = `h-ring-${r.opacity.toFixed(2)}`;+ return (+ <HRing+ color={color}+ d={r.d}+ fill={ringFill}+ hovered={hovered}+ key={ringKey}+ opacity={r.opacity}+ ringIndex={i}+ totalRings={layers}+ />+ );+ })}+ </svg>+ </div>+ ) : (+ <motion.div+ className="absolute inset-0 overflow-visible"+ style={{+ scaleX: entranceScaleX,+ scaleY: entranceScaleY,+ transformOrigin: 'left center',+ }}+ >+ <svg+ aria-hidden="true"+ className="absolute inset-0 h-full w-full overflow-visible"+ preserveAspectRatio="none"+ role="presentation"+ viewBox={`0 0 ${segW} ${fullH}`}+ >+ <defs>+ {gradientStops && (+ <linearGradient id={gradientId} x1="0" x2="1" y1="0" y2="0">+ {gradientStops.map((stop) => (+ <stop+ key={`${stop.offset}-${stop.color}`}+ offset={+ typeof stop.offset === 'number'+ ? `${stop.offset * 100}%`+ : stop.offset+ }+ stopColor={stop.color}+ />+ ))}+ </linearGradient>+ )}+ {renderPattern?.(patternId, color)}+ </defs>+ {rings.map((r, i) => {+ const isInnermost = i === rings.length - 1;+ let ringFill: string | undefined;+ if (isInnermost && renderPattern) {+ ringFill = `url(#${patternId})`;+ } else if (isInnermost && gradientStops) {+ ringFill = `url(#${gradientId})`;+ }+ const ringKey = `h-ring-${r.opacity.toFixed(2)}`;+ return (+ <HRing+ color={color}+ d={r.d}+ fill={ringFill}+ hovered={hovered}+ key={ringKey}+ opacity={r.opacity}+ ringIndex={i}+ totalRings={layers}+ />+ );+ })}+ </svg>+ </motion.div>+ )}+ </motion.div>+ );+}++function VRing({+ d,+ color,+ fill,+ opacity,+ hovered,+ ringIndex,+ totalRings,+}: {+ d: string;+ color: string;+ fill?: string;+ opacity: number;+ hovered: boolean;+ ringIndex: number;+ totalRings: number;+}) {+ const extraScale = 1 + (ringIndex / Math.max(totalRings - 1, 1)) * 0.12;++ return (+ <motion.path+ animate={{ scaleX: hovered ? extraScale : 1 }}+ d={d}+ fill={fill ?? color}+ opacity={opacity}+ style={{ transformOrigin: 'center center' }}+ transition={{+ type: 'spring',+ stiffness: 300 - ringIndex * 60,+ damping: 24 - ringIndex * 3,+ }}+ />+ );+}++function VSegment({+ index,+ normStart,+ normEnd,+ segH,+ fullW,+ color,+ layers,+ staggerDelay,+ enterTransition,+ hovered,+ dimmed,+ renderPattern,+ straight,+ gradientStops,+}: {+ index: number;+ normStart: number;+ normEnd: number;+ segH: number;+ fullW: number;+ color: string;+ layers: number;+ staggerDelay: number;+ enterTransition?: Transition;+ hovered: boolean;+ dimmed: boolean;+ renderPattern?: (id: string, color: string) => ReactNode;+ straight: boolean;+ gradientStops?: FunnelGradientStop[];+}) {+ const patternId = `funnel-v-pattern-${index}`;+ const gradientId = `funnel-v-grad-${index}`;+ const mountProgress = useMountProgress(+ enterTransition,+ index * staggerDelay,+ index+ );+ const enterComplete = useEnterComplete(mountProgress);+ const entranceScaleY = useTransform(mountProgress, [0, 1], [0, 1]);+ const entranceScaleX = useTransform(mountProgress, [0, 1], [0, 1]);++ const rings = Array.from({ length: layers }, (_, l) => {+ const scale = 1 - (l / layers) * 0.35;+ const opacity = 0.18 + (l / (layers - 1 || 1)) * 0.65;+ return {+ d: vSegmentPath(normStart, normEnd, segH, fullW, scale, straight),+ opacity,+ };+ });++ return (+ <motion.div+ animate={{ opacity: dimmed ? 0.4 : 1 }}+ className="pointer-events-none relative shrink-0 overflow-visible"+ style={{+ width: fullW,+ height: segH,+ zIndex: hovered ? 10 : 1,+ }}+ transition={{ opacity: { duration: 0.15 } }}+ >+ {enterComplete ? (+ <div className="absolute inset-0 overflow-visible">+ <svg+ aria-hidden="true"+ className="absolute inset-0 h-full w-full overflow-visible"+ preserveAspectRatio="none"+ role="presentation"+ viewBox={`0 0 ${fullW} ${segH}`}+ >+ <defs>+ {gradientStops && (+ <linearGradient id={gradientId} x1="0" x2="0" y1="0" y2="1">+ {gradientStops.map((stop) => (+ <stop+ key={`${stop.offset}-${stop.color}`}+ offset={+ typeof stop.offset === 'number'+ ? `${stop.offset * 100}%`+ : stop.offset+ }+ stopColor={stop.color}+ />+ ))}+ </linearGradient>+ )}+ {renderPattern?.(patternId, color)}+ </defs>+ {rings.map((r, i) => {+ const isInnermost = i === rings.length - 1;+ let ringFill: string | undefined;+ if (isInnermost && renderPattern) {+ ringFill = `url(#${patternId})`;+ } else if (isInnermost && gradientStops) {+ ringFill = `url(#${gradientId})`;+ }+ const ringKey = `v-ring-${r.opacity.toFixed(2)}`;+ return (+ <VRing+ color={color}+ d={r.d}+ fill={ringFill}+ hovered={hovered}+ key={ringKey}+ opacity={r.opacity}+ ringIndex={i}+ totalRings={layers}+ />+ );+ })}+ </svg>+ </div>+ ) : (+ <motion.div+ className="absolute inset-0 overflow-visible"+ style={{+ scaleY: entranceScaleY,+ scaleX: entranceScaleX,+ transformOrigin: 'center top',+ }}+ >+ <svg+ aria-hidden="true"+ className="absolute inset-0 h-full w-full overflow-visible"+ preserveAspectRatio="none"+ role="presentation"+ viewBox={`0 0 ${fullW} ${segH}`}+ >+ <defs>+ {gradientStops && (+ <linearGradient id={gradientId} x1="0" x2="0" y1="0" y2="1">+ {gradientStops.map((stop) => (+ <stop+ key={`${stop.offset}-${stop.color}`}+ offset={+ typeof stop.offset === 'number'+ ? `${stop.offset * 100}%`+ : stop.offset+ }+ stopColor={stop.color}+ />+ ))}+ </linearGradient>+ )}+ {renderPattern?.(patternId, color)}+ </defs>+ {rings.map((r, i) => {+ const isInnermost = i === rings.length - 1;+ let ringFill: string | undefined;+ if (isInnermost && renderPattern) {+ ringFill = `url(#${patternId})`;+ } else if (isInnermost && gradientStops) {+ ringFill = `url(#${gradientId})`;+ }+ const ringKey = `v-ring-${r.opacity.toFixed(2)}`;+ return (+ <VRing+ color={color}+ d={r.d}+ fill={ringFill}+ hovered={hovered}+ key={ringKey}+ opacity={r.opacity}+ ringIndex={i}+ totalRings={layers}+ />+ );+ })}+ </svg>+ </motion.div>+ )}+ </motion.div>+ );+}++// ─── Label overlay ──────────────────────────────────────────────────++function SegmentLabel({+ stage,+ pct,+ isHorizontal,+ showValues,+ showPercentage,+ showLabels,+ formatPercentage,+ formatValue,+ index,+ staggerDelay,+ layout = 'spread',+ orientation,+ align = 'center',+}: {+ stage: FunnelStage;+ pct: number;+ isHorizontal: boolean;+ showValues: boolean;+ showPercentage: boolean;+ showLabels: boolean;+ formatPercentage: (p: number) => string;+ formatValue: (v: number) => string;+ index: number;+ staggerDelay: number;+ layout?: 'spread' | 'grouped';+ orientation?: 'vertical' | 'horizontal';+ align?: 'center' | 'start' | 'end';+}) {+ const display = stage.displayValue ?? formatValue(stage.value);++ const valueEl = showValues && (+ <span className="whitespace-nowrap font-semibold text-foreground text-sm">+ {display}+ </span>+ );+ const pctEl = showPercentage && (+ <span className="rounded-full bg-foreground px-3 py-1 font-bold text-background text-xs shadow-sm">+ {formatPercentage(pct)}+ </span>+ );+ const labelEl = showLabels && (+ <span className="whitespace-nowrap font-medium text-muted-foreground text-xs">+ {stage.label}+ </span>+ );++ // ── Spread layout (default): items pushed to edges with center element ──+ if (layout === 'spread') {+ return (+ <motion.div+ animate={{ opacity: 1 }}+ className={cn(+ 'absolute inset-0 flex',+ isHorizontal ? 'flex-col items-center' : 'flex-row items-center'+ )}+ initial={{ opacity: 0 }}+ transition={{+ delay: index * staggerDelay + 0.25,+ duration: 0.35,+ ease: 'easeOut',+ }}+ >+ {isHorizontal ? (+ <>+ <div className="flex h-[16%] items-end justify-center pb-1">+ {valueEl}+ </div>+ <div className="flex flex-1 items-center justify-center">+ {pctEl}+ </div>+ <div className="flex h-[16%] items-start justify-center pt-1">+ {labelEl}+ </div>+ </>+ ) : (+ <>+ <div className="flex w-[16%] items-center justify-end pr-2">+ {valueEl}+ </div>+ <div className="flex flex-1 items-center justify-center">+ {pctEl}+ </div>+ <div className="flex w-[16%] items-center justify-start pl-2">+ {labelEl}+ </div>+ </>+ )}+ </motion.div>+ );+ }++ // ── Grouped layout: items stacked tightly together ──+ const resolvedOrientation =+ orientation ?? (isHorizontal ? 'vertical' : 'horizontal');+ const isVerticalStack = resolvedOrientation === 'vertical';++ // Map align to flexbox alignment on the cross axes+ const justifyMap = {+ start: 'justify-start',+ center: 'justify-center',+ end: 'justify-end',+ } as const;+ const itemsMap = {+ start: 'items-start',+ center: 'items-center',+ end: 'items-end',+ } as const;++ // The outer container uses the chart orientation to position the group,+ // and the inner group uses the label orientation for stacking.+ return (+ <motion.div+ animate={{ opacity: 1 }}+ className={cn(+ 'absolute inset-0 flex',+ // For horizontal funnel, align controls vertical placement+ // For vertical funnel, align controls horizontal placement+ isHorizontal+ ? cn('flex-col items-center', justifyMap[align])+ : cn('flex-row items-center', justifyMap[align])+ )}+ initial={{ opacity: 0 }}+ style={{+ padding: isHorizontal ? '8% 0' : '0 8%',+ }}+ transition={{+ delay: index * staggerDelay + 0.25,+ duration: 0.35,+ ease: 'easeOut',+ }}+ >+ <div+ className={cn(+ 'flex gap-1.5',+ isVerticalStack+ ? cn('flex-col', itemsMap[isHorizontal ? 'center' : align])+ : cn('flex-row', itemsMap.center)+ )}+ >+ {valueEl}+ {pctEl}+ {labelEl}+ </div>+ </motion.div>+ );+}++// ─── Main Component ─────────────────────────────────────────────────++export function FunnelChart({+ data,+ orientation = 'horizontal',+ color = 'var(--chart-1)',+ layers = 3,+ className,+ style,+ showPercentage = true,+ showValues = true,+ showLabels = true,+ hoveredIndex: hoveredIndexProp,+ onHoverChange,+ formatPercentage = fmtPct,+ formatValue = fmtVal,+ staggerDelay = 0.12,+ enterTransition,+ gap = 4,+ renderPattern,+ edges = 'curved',+ labelLayout = 'spread',+ labelOrientation,+ labelAlign = 'center',+ grid: gridProp = false,+}: FunnelChartProps) {+ const ref = useRef<HTMLDivElement>(null);+ const [sz, setSz] = useState({ w: 0, h: 0 });+ const [internalHoveredIndex, setInternalHoveredIndex] = useState<+ number | null+ >(null);++ const isControlled = hoveredIndexProp !== undefined;+ const hoveredIndex = isControlled ? hoveredIndexProp : internalHoveredIndex;+ const setHoveredIndex = useCallback(+ (index: number | null) => {+ if (isControlled) {+ onHoverChange?.(index);+ } else {+ setInternalHoveredIndex(index);+ }+ },+ [isControlled, onHoverChange]+ );++ const measure = useCallback(() => {+ if (!ref.current) {+ return;+ }+ const { width: w, height: h } = ref.current.getBoundingClientRect();+ if (w > 0 && h > 0) {+ setSz({ w, h });+ }+ }, []);++ useEffect(() => {+ measure();+ const ro = new ResizeObserver(measure);+ if (ref.current) {+ ro.observe(ref.current);+ }+ return () => ro.disconnect();+ }, [measure]);++ if (!data.length) {+ return null;+ }++ const first = data[0];+ if (!first) {+ return null;+ }+ const max = first.value;+ const n = data.length;+ const norms = data.map((d) => d.value / max);+ const horiz = orientation === 'horizontal';+ const { w: W, h: H } = sz;++ const totalGap = gap * (n - 1);+ const segW = (W - (horiz ? totalGap : 0)) / n;+ const segH = (H - (horiz ? 0 : totalGap)) / n;++ // Resolve grid config+ const gridEnabled = gridProp !== false;+ const gridCfg = typeof gridProp === 'object' ? gridProp : {};+ const showBands = gridEnabled && (gridCfg.bands ?? true);+ const bandColor = gridCfg.bandColor ?? 'var(--color-muted)';+ const showGridLines = gridEnabled && (gridCfg.lines ?? true);+ const gridLineColor = gridCfg.lineColor ?? 'var(--chart-grid)';+ const gridLineOpacity = gridCfg.lineOpacity ?? 1;+ const gridLineWidth = gridCfg.lineWidth ?? 1;++ return (+ <div+ className={cn('relative w-full select-none overflow-visible', className)}+ ref={ref}+ style={{+ aspectRatio: horiz ? '2.2 / 1' : '1 / 1.8',+ ...style,+ }}+ >+ {W > 0 && H > 0 && (+ <>+ {/* Grid layer: background bands + grid lines */}+ {gridEnabled && (+ <svg+ aria-hidden="true"+ className="pointer-events-none absolute inset-0 h-full w-full"+ preserveAspectRatio="none"+ role="presentation"+ viewBox={`0 0 ${W} ${H}`}+ >+ {/* Background bands — alternating on even segments */}+ {showBands &&+ data.map((stage, i) => {+ if (i % 2 !== 0) {+ return null;+ }+ if (horiz) {+ const x = (segW + gap) * i;+ return (+ <rect+ fill={bandColor}+ height={H}+ key={`band-${stage.label}`}+ width={segW}+ x={x}+ y={0}+ />+ );+ }+ const y = (segH + gap) * i;+ return (+ <rect+ fill={bandColor}+ height={segH}+ key={`band-${stage.label}`}+ width={W}+ x={0}+ y={y}+ />+ );+ })}+ </svg>+ )}++ {/* Segments container — overflow-visible so hover scale is not clipped */}+ <div+ className={cn(+ 'absolute inset-0 flex overflow-visible',+ horiz ? 'flex-row' : 'flex-col'+ )}+ style={{ gap }}+ >+ {data.map((stage, i) => {+ const normStart = norms[i] ?? 0;+ const normEnd = norms[Math.min(i + 1, n - 1)] ?? 0;+ const firstStop = stage.gradient?.[0];+ const segColor = firstStop+ ? firstStop.color+ : (stage.color ?? color);++ return horiz ? (+ <HSegment+ color={segColor}+ dimmed={hoveredIndex !== null && hoveredIndex !== i}+ enterTransition={enterTransition}+ fullH={H}+ gradientStops={stage.gradient}+ hovered={hoveredIndex === i}+ index={i}+ key={stage.label}+ layers={layers}+ normEnd={normEnd}+ normStart={normStart}+ renderPattern={renderPattern}+ segW={segW}+ staggerDelay={staggerDelay}+ straight={edges === 'straight'}+ />+ ) : (+ <VSegment+ color={segColor}+ dimmed={hoveredIndex !== null && hoveredIndex !== i}+ enterTransition={enterTransition}+ fullW={W}+ gradientStops={stage.gradient}+ hovered={hoveredIndex === i}+ index={i}+ key={stage.label}+ layers={layers}+ normEnd={normEnd}+ normStart={normStart}+ renderPattern={renderPattern}+ segH={segH}+ staggerDelay={staggerDelay}+ straight={edges === 'straight'}+ />+ );+ })}+ </div>++ {/* Grid lines — rendered above segments so they're visible */}+ {gridEnabled && showGridLines && (+ <svg+ aria-hidden="true"+ className="pointer-events-none absolute inset-0 h-full w-full"+ preserveAspectRatio="none"+ role="presentation"+ viewBox={`0 0 ${W} ${H}`}+ >+ {Array.from({ length: n - 1 }, (_, i) => {+ const idx = i + 1;+ const gridKey = `grid-${idx}`;+ if (horiz) {+ const x = segW * idx + gap * i + gap / 2;+ return (+ <line+ key={gridKey}+ stroke={gridLineColor}+ strokeOpacity={gridLineOpacity}+ strokeWidth={gridLineWidth}+ x1={x}+ x2={x}+ y1={0}+ y2={H}+ />+ );+ }+ const y = segH * idx + gap * i + gap / 2;+ return (+ <line+ key={gridKey}+ stroke={gridLineColor}+ strokeOpacity={gridLineOpacity}+ strokeWidth={gridLineWidth}+ x1={0}+ x2={W}+ y1={y}+ y2={y}+ />+ );+ })}+ </svg>+ )}++ {/* Label overlays — one per segment, positioned over each segment cell.+ These are the hover triggers for each segment. */}+ {data.map((stage, i) => {+ const pct = (stage.value / max) * 100;+ const posStyle: CSSProperties = horiz+ ? {+ left: (segW + gap) * i,+ width: segW,+ top: 0,+ height: H,+ }+ : {+ top: (segH + gap) * i,+ height: segH,+ left: 0,+ width: W,+ };++ const isDimmed = hoveredIndex !== null && hoveredIndex !== i;++ return (+ <motion.div+ animate={{ opacity: isDimmed ? 0.4 : 1 }}+ className="absolute cursor-pointer"+ key={`lbl-${stage.label}`}+ onMouseEnter={() => setHoveredIndex(i)}+ onMouseLeave={() => setHoveredIndex(null)}+ style={{ ...posStyle, zIndex: 20 }}+ transition={{ type: 'spring', stiffness: 300, damping: 24 }}+ >+ <SegmentLabel+ align={labelAlign}+ formatPercentage={formatPercentage}+ formatValue={formatValue}+ index={i}+ isHorizontal={horiz}+ layout={labelLayout}+ orientation={labelOrientation}+ pct={pct}+ showLabels={showLabels}+ showPercentage={showPercentage}+ showValues={showValues}+ stage={stage}+ staggerDelay={staggerDelay}+ />+ </motion.div>+ );+ })}+ </>+ )}+ </div>+ );+}diff --git a/apps/start/src/components/charts/generate-chart-skeleton-data.ts b/apps/start/src/components/charts/generate-chart-skeleton-data.tsnew file mode 100644index 000000000..06be3d16a--- /dev/null+++ b/apps/start/src/components/charts/generate-chart-skeleton-data.ts@@ -0,0 +1,42 @@+const DEFAULT_SKELETON_DATA_KEY = 'value';+const DEFAULT_SKELETON_POINT_COUNT = 7;++export interface GenerateChartSkeletonDataOptions {+ /** Key used for y values in each row. Default: `"value"`. */+ dataKey?: string;+ /** Number of points. Default: 7. */+ pointCount?: number;+ /** Start date for the x axis. Default: 2025-01-01. */+ baseDate?: Date;+}++/** Placeholder series used while `status="loading"` and data is empty. */+export function generateChartSkeletonData(+ options: GenerateChartSkeletonDataOptions = {}+): Record<string, unknown>[] {+ const dataKey = options.dataKey ?? DEFAULT_SKELETON_DATA_KEY;+ const pointCount = options.pointCount ?? DEFAULT_SKELETON_POINT_COUNT;+ const baseDate = options.baseDate ?? new Date('2025-01-01');++ return Array.from({ length: pointCount }, (_, index) => {+ const date = new Date(baseDate);+ date.setDate(baseDate.getDate() + index);+ return {+ date,+ [dataKey]: Math.round(110 + Math.sin(index * 1.15) * 36 + index * 9),+ };+ });+}++/** Skeleton rows that mirror target dates/count with lower magnitudes for Y tween. */+export function generateChartSkeletonFromTarget(+ targetData: Record<string, unknown>[],+ dataKey: string+): Record<string, unknown>[] {+ return targetData.map((row, index) => ({+ ...row,+ [dataKey]: Math.round(95 + Math.sin(index * 1.05) * 28 + index * 7),+ }));+}++export { DEFAULT_SKELETON_DATA_KEY, DEFAULT_SKELETON_POINT_COUNT };diff --git a/apps/start/src/components/charts/grid.tsx b/apps/start/src/components/charts/grid.tsxindex b63cf7945..1db103f8a 100644--- a/apps/start/src/components/charts/grid.tsx+++ b/apps/start/src/components/charts/grid.tsx@@ -1,8 +1,19 @@'use client';import { GridColumns, GridRows } from '@visx/grid';+import { motion } from 'motion/react';import { useId } from 'react';-import { chartCssVars, useChartStable } from './chart-context';+import { chartCssVars, useChartStable, useYScale } from './chart-context';+import { useGridShimmer } from './use-grid-shimmer';+import {+ isLoadingChromePhase,+ isLoadingGridChromePhase,+} from './y-domain-utils';++const DEFAULT_SHIMMER_LENGTH_PX = 140;+const DEFAULT_SHIMMER_SPEED = 1;+const DEFAULT_SHIMMER_STROKE =+ 'color-mix(in oklch, var(--foreground) 68%, transparent)';export interface GridProps {/** Show horizontal grid lines. Default: true */@@ -17,6 +28,8 @@ export interface GridProps {rowTickValues?: number[];/** Grid line stroke color. Default: var(--chart-grid) */stroke?: string;+ /** Grid stroke while loading chrome is active. Falls back to `stroke`. */+ loadingStroke?: string;/** Grid line stroke opacity. Default: 1 */strokeOpacity?: number;/** Grid line stroke width. Default: 1 */@@ -37,8 +50,49 @@ export interface GridProps {fadeHorizontal?: boolean;/** Enable vertical fade effect on grid columns (fades at top/bottom). Default: false */fadeVertical?: boolean;+ /** Omit the first and last horizontal grid lines. Default: false */+ hideHorizontalEdgeLines?: boolean;+ /** Omit the first and last vertical grid lines. Default: false */+ hideVerticalEdgeLines?: boolean;+ /** Y-scale for horizontal grid lines. Default: primary (`"left"`) axis. */+ yAxisId?: string | number;+ /** Animate a shimmer band across horizontal grid lines. Default: false */+ shimmer?: boolean;+ /** Shimmer band stroke (color and opacity via color-mix or oklch alpha). */+ shimmerStroke?: string;+ /** Shimmer band width in pixels. Default: 140 */+ shimmerLength?: number;+ /** Shimmer speed multiplier (higher = faster). Default: 1 */+ shimmerSpeed?: number;+ /** Match loop timing to the loading line pulse (cycle + inter-loop pause). */+ shimmerSync?: boolean;+}++function hideEdgeTicks<T>(ticks: T[], hideEdgeLines: boolean): T[] {+ if (!hideEdgeLines || ticks.length <= 2) {+ return ticks;+ }+ return ticks.slice(1, -1);}+function resolveRowTickValues(options: {+ hideHorizontalEdgeLines: boolean;+ numTicksRows: number;+ rowTickValues?: number[];+ yScale: { ticks?: (count: number) => number[] };+}): number[] | undefined {+ const { hideHorizontalEdgeLines, numTicksRows, rowTickValues, yScale } =+ options;+ const ticks =+ rowTickValues ?? (yScale.ticks ? yScale.ticks(numTicksRows) : []);+ const filtered = hideEdgeTicks(ticks, hideHorizontalEdgeLines);+ if (filtered === ticks && !rowTickValues && !hideHorizontalEdgeLines) {+ return undefined;+ }+ return filtered.length > 0 ? filtered : undefined;+}++// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: grid fade masks and shimmer share one layer treeexport function Grid({horizontal = true,vertical = false,@@ -46,6 +100,7 @@ export function Grid({numTicksColumns = 10,rowTickValues,stroke = chartCssVars.grid,+ loadingStroke,strokeOpacity = 1,strokeWidth = 1,strokeDasharray = '4,4',@@ -56,26 +111,72 @@ export function Grid({highlightRowStrokeDasharray = '0',fadeHorizontal = true,fadeVertical = false,+ hideHorizontalEdgeLines = false,+ hideVerticalEdgeLines = false,+ yAxisId,+ shimmer = false,+ shimmerStroke = DEFAULT_SHIMMER_STROKE,+ shimmerLength = DEFAULT_SHIMMER_LENGTH_PX,+ shimmerSpeed = DEFAULT_SHIMMER_SPEED,+ shimmerSync = false,}: GridProps) {- const { xScale, yScale, innerWidth, innerHeight, orientation, barScale } =+ const { xScale, innerWidth, innerHeight, orientation, barScale, chartPhase } =useChartStable();+ const yScale = useYScale(yAxisId);+ const shimmerActive = shimmer && isLoadingChromePhase(chartPhase);+ const gridStroke =+ isLoadingGridChromePhase(chartPhase) && loadingStroke != null+ ? loadingStroke+ : stroke;+ const { shimmerEnabled, shimmerTransform } = useGridShimmer({+ innerWidth,+ shimmer,+ shimmerLength,+ shimmerSpeed,+ shimmerSync,+ active: shimmerActive,+ });- // Bar charts swap axes: for a horizontal bar chart the vertical grid needs- // the value scale (yScale), not the category scale.+ // 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 xScaleconst columnScale = isHorizontalBarChart ? yScale : xScale;+ const rowTickValuesResolved = resolveRowTickValues({+ hideHorizontalEdgeLines,+ numTicksRows,+ rowTickValues,+ yScale,+ });+ const columnTickValuesResolved =+ vertical &&+ columnScale &&+ typeof columnScale === 'function' &&+ hideVerticalEdgeLines+ ? (() => {+ const ticks = columnScale.ticks?.(numTicksColumns) ?? [];+ const filtered = hideEdgeTicks<number | Date>(ticks, true);+ return filtered.length > 0 ? filtered : undefined;+ })()+ : undefined;const uniqueId = useId();// Horizontal fade mask (for grid rows - fades left/right)const hMaskId = `grid-rows-fade-${uniqueId}`;const hGradientId = `${hMaskId}-gradient`;+ const shimmerGradientId = `grid-shimmer-${uniqueId}`;// Vertical fade mask (for grid columns - fades top/bottom)const vMaskId = `grid-cols-fade-${uniqueId}`;const vGradientId = `${vMaskId}-gradient`;+ const horizontalFadeMask = fadeHorizontal ? `url(#${hMaskId})` : undefined;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%">@@ -99,6 +200,27 @@ export function Grid({</defs>)}+ {horizontal && shimmerEnabled ? (+ <defs>+ <motion.linearGradient+ gradientTransform={shimmerTransform}+ gradientUnits="userSpaceOnUse"+ id={shimmerGradientId}+ x1={0}+ x2={shimmerLength}+ y1={0}+ y2={0}+ >+ <stop offset="0%" stopColor={shimmerStroke} stopOpacity={0} />+ <stop offset="35%" stopColor={shimmerStroke} stopOpacity={0.45} />+ <stop offset="50%" stopColor={shimmerStroke} stopOpacity={1} />+ <stop offset="65%" stopColor={shimmerStroke} stopOpacity={0.45} />+ <stop offset="100%" stopColor={shimmerStroke} stopOpacity={0} />+ </motion.linearGradient>+ </defs>+ ) : null}++ {/* Gradient mask for vertical grid lines - fades at top/bottom */}{vertical && fadeVertical && (<defs><linearGradient id={vGradientId} x1="0%" x2="0%" y1="0%" y2="100%">@@ -123,17 +245,29 @@ export function Grid({)}{horizontal && (- <g mask={fadeHorizontal ? `url(#${hMaskId})` : undefined}>+ <g mask={horizontalFadeMask}><GridRows- numTicks={rowTickValues ? undefined : numTicksRows}+ numTicks={rowTickValuesResolved ? undefined : numTicksRows}scale={yScale}- stroke={stroke}+ stroke={gridStroke}strokeDasharray={strokeDasharray}strokeOpacity={strokeOpacity}strokeWidth={strokeWidth}- tickValues={rowTickValues}+ tickValues={rowTickValuesResolved}width={innerWidth}/>+ {shimmerEnabled ? (+ <GridRows+ numTicks={rowTickValuesResolved ? undefined : numTicksRows}+ scale={yScale}+ stroke={`url(#${shimmerGradientId})`}+ strokeDasharray={strokeDasharray}+ strokeOpacity={1}+ strokeWidth={strokeWidth}+ tickValues={rowTickValuesResolved}+ width={innerWidth}+ />+ ) : null}</g>)}{horizontal && highlightRowValues && highlightRowValues.length > 0 ? (@@ -164,12 +298,13 @@ export function Grid({<g mask={fadeVertical ? `url(#${vMaskId})` : undefined}><GridColumnsheight={innerHeight}- numTicks={numTicksColumns}+ numTicks={columnTickValuesResolved ? undefined : numTicksColumns}scale={columnScale}stroke={stroke}strokeDasharray={strokeDasharray}strokeOpacity={strokeOpacity}strokeWidth={strokeWidth}+ tickValues={columnTickValuesResolved}/></g>)}diff --git a/apps/start/src/components/charts/heatmap/generate-heatmap-skeleton-data.ts b/apps/start/src/components/charts/heatmap/generate-heatmap-skeleton-data.tsnew file mode 100644index 000000000..3ad18d8c7--- /dev/null+++ b/apps/start/src/components/charts/heatmap/generate-heatmap-skeleton-data.ts@@ -0,0 +1,15 @@+import type { HeatmapColumn } from './heatmap-context';++/** Placeholder grid with the same week/day shape as target data (all empty cells). */+export function generateHeatmapSkeletonFromTarget(+ target: HeatmapColumn[]+): HeatmapColumn[] {+ return target.map((column) => ({+ bin: column.bin,+ bins: column.bins.map((bin) => ({+ bin: bin.bin,+ count: 0,+ date: bin.date,+ })),+ }));+}diff --git a/apps/start/src/components/charts/heatmap/heatmap-animation.ts b/apps/start/src/components/charts/heatmap/heatmap-animation.tsnew file mode 100644index 000000000..ae4f25331--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-animation.ts@@ -0,0 +1,142 @@+import type { Transition } from 'motion/react';+import type { HeatmapColumn } from './heatmap-context';+import { getHeatmapContributionLevel } from './heatmap-utils';++/** Default enter duration when no motion props are passed (ms). */+export const HEATMAP_DEFAULT_ENTER_DURATION_MS = 1600;++/** Default cubic-bezier for heatmap cell enter / loading transitions. */+export const HEATMAP_DEFAULT_ENTER_EASE = [0.85, 0, 0.916, 0.282] as const;++/** Default enter transition for {@link HeatmapChart}. */+export const HEATMAP_DEFAULT_ENTER_TRANSITION: Transition = {+ type: 'tween',+ duration: HEATMAP_DEFAULT_ENTER_DURATION_MS / 1000,+ ease: HEATMAP_DEFAULT_ENTER_EASE,+};++/** Chart opacity while `status="loading"`. */+export const HEATMAP_LOADING_CHART_OPACITY = 1;++/** Default max per-cell opacity during loading shimmer. */+export const HEATMAP_DEFAULT_LOADING_CELL_MAX_OPACITY = 0.85;++/** Default share of cells that participate in loading shimmer (0–1). */+export const HEATMAP_DEFAULT_LOADING_CELL_RANDOMNESS = 1;++/** Opacity for loading cells that do not participate in shimmer. */+export const HEATMAP_LOADING_BASE_CELL_OPACITY = 0.2;++/** Duration for ready → loading cell conceal before shimmer resumes (ms). */+export const HEATMAP_LOADING_CONCEAL_MS = 450;++/** Share of the enter window used for random fade-in delays. */+export const HEATMAP_ENTER_STAGGER_SPREAD = 0.6;++function seededRandom(seed: number): () => number {+ let state = seed % 2_147_483_647;+ if (state <= 0) {+ state += 2_147_483_646;+ }+ return () => {+ state = (state * 16_807) % 2_147_483_647;+ return (state - 1) / 2_147_483_646;+ };+}++export function heatmapCellSeed(column: number, row: number): number {+ return column * 1009 + row * 9176;+}++export interface HeatmapLevelRange {+ min: number;+ max: number;+}++/** Min/max contribution levels present in the dataset. */+export function computeHeatmapLevelRange(+ data: HeatmapColumn[]+): HeatmapLevelRange {+ let min = Number.POSITIVE_INFINITY;+ let max = Number.NEGATIVE_INFINITY;++ for (const column of data) {+ for (const bin of column.bins) {+ const level = getHeatmapContributionLevel(bin.count);+ if (level < min) {+ min = level;+ }+ if (level > max) {+ max = level;+ }+ }+ }++ if (!(Number.isFinite(min) && Number.isFinite(max))) {+ return { min: 0, max: 4 };+ }++ return { min, max };+}++/** Per-cell fade duration derived from the motion enter transition. */+export function resolveHeatmapEnterFadeDurationSec(+ enterTransition: Transition | undefined,+ animationDurationMs: number+): number {+ if (+ enterTransition &&+ 'duration' in enterTransition &&+ typeof enterTransition.duration === 'number'+ ) {+ return enterTransition.duration;+ }++ return Math.min(0.45, (animationDurationMs / 1000) * 0.3);+}++/** Random delay so all cells finish fading in within `animationDurationMs`. */+export function computeHeatmapEnterFadeDelayMs({+ column,+ row,+ revealEpoch,+ animationDurationMs,+ enterStaggerScale,+ fadeDurationSec,+}: {+ column: number;+ row: number;+ revealEpoch: number;+ animationDurationMs: number;+ enterStaggerScale: number;+ fadeDurationSec: number;+}): number {+ const random = seededRandom(+ heatmapCellSeed(column, row) + revealEpoch * 524_287+ );+ const fadeMs = fadeDurationSec * 1000;+ const maxDelayMs = Math.max(0, animationDurationMs - fadeMs);+ const spreadMs =+ maxDelayMs *+ HEATMAP_ENTER_STAGGER_SPREAD *+ Math.max(enterStaggerScale, 0.25);++ return random() * spreadMs;+}++/** Whether a cell participates in loading shimmer for a given randomness (0–1). */+export function heatmapLoadingCellParticipates(+ column: number,+ row: number,+ randomness: number+): boolean {+ if (randomness >= 1) {+ return true;+ }+ if (randomness <= 0) {+ return false;+ }++ const random = seededRandom(heatmapCellSeed(column, row) + 73_133);+ return random() < randomness;+}diff --git a/apps/start/src/components/charts/heatmap/heatmap-cells.tsx b/apps/start/src/components/charts/heatmap/heatmap-cells.tsxnew file mode 100644index 000000000..fdf2f4c40--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-cells.tsx@@ -0,0 +1,578 @@+'use client';++import { Group } from '@visx/group';+import { HeatmapRect } from '@visx/heatmap';+import {+ animate,+ type MotionValue,+ motion,+ type Transition,+ useMotionValue,+} from 'motion/react';+import { memo, useCallback, useEffect, useMemo, useRef } from 'react';+import type { ChartStatus } from '../chart-phase';+import { transitionWithDelay } from '../motion-utils';+import {+ computeHeatmapEnterFadeDelayMs,+ HEATMAP_DEFAULT_ENTER_EASE,+ HEATMAP_LOADING_BASE_CELL_OPACITY,+ HEATMAP_LOADING_CONCEAL_MS,+ heatmapLoadingCellParticipates,+ resolveHeatmapEnterFadeDurationSec,+} from './heatmap-animation';+import { heatmapLevelCellFillOpacity } from './heatmap-colors';+import {+ type HeatmapBin,+ type HeatmapColumn,+ useHeatmap,+ useHeatmapInteraction,+} from './heatmap-context';+import {+ getHeatmapContributionLevel,+ isHeatmapGhostBin,+ isHeatmapHoverEffectEnabled,+ resolveHeatmapDisplayRange,+ resolveHeatmapHoverStyle,+ resolveHeatmapRowOpacity,+} from './heatmap-utils';++const HEATMAP_INACTIVE_OPACITY = 0.3;+/** Smooth tween for inactive opacity + scale on hover. */+const HEATMAP_INACTIVE_TRANSITION = {+ duration: 0.22,+ ease: [0.4, 0, 0.2, 1] as const,+};+const HEATMAP_CONCEAL_TRANSITION = {+ duration: HEATMAP_LOADING_CONCEAL_MS / 1000,+ ease: HEATMAP_DEFAULT_ENTER_EASE,+};++function computeHeatmapCellFaded(+ isCellHovering: boolean,+ isLevelHovering: boolean,+ hoveredCell: { column: number; row: number } | null,+ hoveredLegendLevel: number | null,+ cell: { column: number; row: number },+ count: number+): { isHighlighted: boolean; isDimmed: boolean } {+ if (isCellHovering && hoveredCell) {+ const isHighlighted =+ hoveredCell.column === cell.column && hoveredCell.row === cell.row;+ return { isHighlighted, isDimmed: !isHighlighted };+ }+ if (isLevelHovering && hoveredLegendLevel !== null) {+ const isHighlighted =+ getHeatmapContributionLevel(count) === hoveredLegendLevel;+ return { isHighlighted, isDimmed: !isHighlighted };+ }+ return { isHighlighted: false, isDimmed: false };+}++interface SyncCellLayerParams {+ animateCells: boolean;+ chartStatus: ChartStatus;+ dataOpacity: MotionValue<number>;+ isAwaitingLoadingConceal: boolean;+ isExitingToLoading: boolean;+ isLoadingResting: boolean;+ isReadyResting: boolean;+ isRevealActive: boolean;+ participates: boolean;+ pulseOpacity: MotionValue<number>;+ readyDataOpacity: number;+ shimmerOpacity: MotionValue<number>;+ showLoadingCellsLayer: boolean;+ showShimmerPulse: boolean;+ staggeredTransition: Transition;+}++function syncHeatmapCellLayerOpacities(params: SyncCellLayerParams) {+ const {+ animateCells,+ chartStatus,+ dataOpacity,+ isAwaitingLoadingConceal,+ isExitingToLoading,+ isLoadingResting,+ isReadyResting,+ isRevealActive,+ participates,+ pulseOpacity,+ readyDataOpacity,+ shimmerOpacity,+ showLoadingCellsLayer,+ showShimmerPulse,+ staggeredTransition,+ } = params;++ if (!animateCells) {+ if (isReadyResting) {+ dataOpacity.set(readyDataOpacity);+ shimmerOpacity.set(0);+ pulseOpacity.set(0);+ } else if (chartStatus === 'loading') {+ dataOpacity.set(0);+ pulseOpacity.set(0);+ shimmerOpacity.set(+ participates && showLoadingCellsLayer+ ? 0+ : HEATMAP_LOADING_BASE_CELL_OPACITY+ );+ }+ return;+ }++ if (isLoadingResting) {+ animate(dataOpacity, 0, { duration: 0 });+ if (!showShimmerPulse) {+ animate(shimmerOpacity, HEATMAP_LOADING_BASE_CELL_OPACITY, {+ duration: 0,+ });+ }+ return;+ }++ if (isRevealActive) {+ pulseOpacity.set(0);+ shimmerOpacity.set(0);+ animate(dataOpacity, readyDataOpacity, staggeredTransition);+ return;+ }++ if (isAwaitingLoadingConceal || isExitingToLoading) {+ animate(dataOpacity, 0, HEATMAP_CONCEAL_TRANSITION);+ animate(shimmerOpacity, 0, { duration: 0 });+ return;+ }++ if (isReadyResting) {+ animate(dataOpacity, readyDataOpacity, HEATMAP_INACTIVE_TRANSITION);+ animate(shimmerOpacity, 0, { duration: 0 });+ pulseOpacity.set(0);+ }+}++export interface HeatmapCellsProps {+ /** Corner radius for each cell. Default: 2 */+ cornerRadius?: number;+ /** Override the default GitHub-style green color scale. */+ colorScale?: (count: number | null | undefined) => string;+ /** Opacity for inactive cells while hovering. Default: 0.3 */+ inactiveOpacity?: number;+ /** Scale for inactive cells while hovering. Default: 1 */+ inactiveScale?: number;+ /** Scale for the highlighted cell while hovering. Default: 1 */+ activeScale?: number;+ /** Per-row opacity multiplier (display row index). Default: 1 */+ rowOpacity?: number | readonly number[];+ /** Pointer hover + dimming. Default: true */+ interactive?: boolean;+ /** Hide out-of-range bins (GitHub-style ghost cells). Default: true */+ hideGhostCells?: boolean;+}++interface HeatmapCellRectProps {+ cell: {+ column: number;+ row: number;+ x: number;+ y: number;+ width: number;+ height: number;+ color?: string;+ opacity?: number;+ };+ bin: HeatmapBin;+ cornerRadius: number;+ interactive: boolean;+ inactiveOpacity: number;+ inactiveScale: number;+ activeScale: number;+ rowOpacity: number | readonly number[] | undefined;+ hoverState: { isHighlighted: boolean; isDimmed: boolean };+ onEnter: (+ column: number,+ row: number,+ bin: HeatmapBin,+ x: number,+ y: number+ ) => void;+ onLeave: () => void;+}++const HeatmapMotionCell = memo(function HeatmapMotionCell({+ cell,+ bin,+ cornerRadius,+ fillScale,+ interactive,+ inactiveOpacity,+ inactiveScale,+ activeScale,+ rowOpacity,+ hoverState,+ onEnter,+ onLeave,+}: HeatmapCellRectProps & {+ fillScale: (count: number | null | undefined) => string;+}) {+ const {+ chartStatus,+ chartPhase,+ isLoaded,+ revealMode,+ revealEpoch,+ animationDuration,+ enterTransition,+ enterStaggerScale,+ animateCells,+ showLoadingCells: showLoadingCellsLayer,+ loadingCellMaxOpacity,+ loadingCellRandomness,+ levelStyles,+ } = useHeatmap();++ const levelStyle =+ levelStyles[getHeatmapContributionLevel(bin.count ?? 0)] ?? levelStyles[0];+ const targetFill = fillScale(bin.count);+ const emptyFill = fillScale(0);+ const patternFillOpacity = heatmapLevelCellFillOpacity(levelStyle);+ const dataOpacity = useMotionValue(0);+ /** Orchestration layer: conceal, static loading base. */+ const shimmerOpacity = useMotionValue(0);+ /** Pulse loop only — kept separate so stagger tweens don't break re-entry. */+ const pulseOpacity = useMotionValue(0);+ const wasShimmerPulsingRef = useRef(false);++ const isLoadingResting =+ chartStatus === 'loading' && chartPhase === 'loading';+ const isAwaitingLoadingConceal =+ chartStatus === 'loading' && chartPhase === 'ready';+ const isExitingToLoading = chartPhase === 'exitingReady';+ const isRevealActive =+ chartPhase === 'revealing' &&+ !isLoaded &&+ (revealMode === 'fromLoading' || revealMode === 'enter');+ const isReadyResting =+ chartStatus === 'ready' && chartPhase === 'ready' && isLoaded;++ const participates = useMemo(+ () =>+ heatmapLoadingCellParticipates(+ cell.column,+ cell.row,+ loadingCellRandomness+ ),+ [cell.column, cell.row, loadingCellRandomness]+ );++ const showShimmerPulse =+ animateCells && showLoadingCellsLayer && participates && isLoadingResting;++ const fadeDurationSec = resolveHeatmapEnterFadeDurationSec(+ enterTransition,+ animationDuration+ );+ const delayMs = computeHeatmapEnterFadeDelayMs({+ column: cell.column,+ row: cell.row,+ revealEpoch,+ animationDurationMs: animationDuration,+ enterStaggerScale,+ fadeDurationSec,+ });+ const staggeredTransition = transitionWithDelay(+ enterTransition,+ delayMs / 1000+ );++ const readyHoverStyle = resolveHeatmapHoverStyle(+ hoverState.isHighlighted,+ hoverState.isDimmed,+ { inactiveOpacity, inactiveScale, activeScale }+ );+ const rowOpacityMultiplier = resolveHeatmapRowOpacity(cell.row, rowOpacity);+ const readyDataOpacity = readyHoverStyle.opacity;+ const readyScale = isReadyResting ? readyHoverStyle.scale : 1;+ const transformOrigin = `${cell.x + cell.width / 2}px ${cell.y + cell.height / 2}px`;++ useEffect(() => {+ if (!showShimmerPulse) {+ wasShimmerPulsingRef.current = false;+ pulseOpacity.set(0);+ return;+ }++ const isFreshLoadingPulse =+ isLoadingResting && !wasShimmerPulsingRef.current;+ wasShimmerPulsingRef.current = true;++ if (isFreshLoadingPulse) {+ pulseOpacity.set(0);+ }++ let cancelled = false;+ let current: ReturnType<typeof animate> | undefined;++ const pulse = async () => {+ while (!cancelled) {+ const target = Math.random() * loadingCellMaxOpacity;+ const duration = 0.35 + Math.random() * 0.85;+ current = animate(pulseOpacity, target, {+ duration,+ ease: [0.45, 0, 0.55, 1],+ });++ try {+ await current;+ } catch {+ break;+ }++ if (cancelled) {+ break;+ }++ await new Promise<void>((resolve) => {+ window.setTimeout(resolve, 80 + Math.random() * 420);+ });+ }+ };++ pulse().catch(() => undefined);++ return () => {+ cancelled = true;+ current?.stop();+ };+ }, [isLoadingResting, loadingCellMaxOpacity, pulseOpacity, showShimmerPulse]);++ useEffect(() => {+ syncHeatmapCellLayerOpacities({+ animateCells,+ chartStatus,+ dataOpacity,+ isAwaitingLoadingConceal,+ isExitingToLoading,+ isLoadingResting,+ isReadyResting,+ isRevealActive,+ participates,+ pulseOpacity,+ readyDataOpacity,+ shimmerOpacity,+ showLoadingCellsLayer,+ showShimmerPulse,+ staggeredTransition,+ });+ }, [+ animateCells,+ chartStatus,+ dataOpacity,+ isAwaitingLoadingConceal,+ isExitingToLoading,+ isLoadingResting,+ isReadyResting,+ isRevealActive,+ participates,+ pulseOpacity,+ readyDataOpacity,+ shimmerOpacity,+ showLoadingCellsLayer,+ showShimmerPulse,+ staggeredTransition,+ ]);++ const cellProps = {+ className: 'visx-heatmap-rect',+ height: cell.height,+ rx: cornerRadius,+ ry: cornerRadius,+ width: cell.width,+ x: cell.x,+ y: cell.y,+ };++ return (+ <motion.g+ animate={{ scale: readyScale }}+ style={{ transformOrigin }}+ transition={HEATMAP_INACTIVE_TRANSITION}+ >+ <motion.rect+ {...cellProps}+ fill={targetFill}+ fillOpacity={+ (cell.opacity ?? 1) * patternFillOpacity * rowOpacityMultiplier+ }+ onPointerEnter={() =>+ onEnter(cell.column, cell.row, bin, cell.x, cell.y)+ }+ onPointerLeave={onLeave}+ style={{+ cursor: interactive ? 'pointer' : undefined,+ opacity: dataOpacity,+ }}+ />+ <motion.rect+ {...cellProps}+ fill={emptyFill}+ pointerEvents="none"+ style={{+ opacity: showShimmerPulse ? pulseOpacity : shimmerOpacity,+ }}+ />+ </motion.g>+ );+});++export const HeatmapCells = memo(function HeatmapCells({+ cornerRadius = 2,+ colorScale: colorScaleProp,+ inactiveOpacity = HEATMAP_INACTIVE_OPACITY,+ inactiveScale = 1,+ activeScale = 1,+ rowOpacity,+ interactive = true,+ hideGhostCells = true,+}: HeatmapCellsProps) {+ const {+ data,+ binWidth,+ binHeight,+ gap,+ margin,+ xScale,+ yScale,+ chartStatus,+ colorScale: contextColorScale,+ fillScale: contextFillScale,+ } = useHeatmap();+ const colorScale = colorScaleProp ?? contextColorScale;+ const fillScale = contextFillScale;+ const cellsInteractive = interactive && chartStatus !== 'loading';+ const {+ hoveredCell,+ hoveredLegendLevel,+ setHoveredCell,+ setHoveredLegendLevel,+ setTooltipData,+ } = useHeatmapInteraction();++ const handleCellEnter = useCallback(+ (column: number, row: number, bin: HeatmapBin, x: number, y: number) => {+ if (!cellsInteractive) {+ return;+ }++ setHoveredLegendLevel(null);+ setHoveredCell({ column, row });+ setTooltipData({+ column,+ row,+ count: bin.count,+ date: bin.date,+ x: margin.left + x + binWidth / 2,+ y: margin.top + y + binHeight / 2,+ });+ },+ [+ binHeight,+ binWidth,+ cellsInteractive,+ margin.left,+ margin.top,+ setHoveredCell,+ setHoveredLegendLevel,+ setTooltipData,+ ]+ );++ const handleCellLeave = useCallback(() => {+ if (!cellsInteractive) {+ return;+ }++ setHoveredCell(null);+ setTooltipData(null);+ }, [cellsInteractive, setHoveredCell, setTooltipData]);++ const inactiveEnabled = isHeatmapHoverEffectEnabled({+ inactiveOpacity,+ inactiveScale,+ activeScale,+ });+ const isCellHovering =+ cellsInteractive && hoveredCell !== null && inactiveEnabled;+ const isLevelHovering =+ cellsInteractive && hoveredLegendLevel !== null && inactiveEnabled;++ const displayRange = useMemo(+ () => (hideGhostCells ? resolveHeatmapDisplayRange(data) : null),+ [data, hideGhostCells]+ );++ return (+ <HeatmapRect<HeatmapColumn, HeatmapBin>+ binHeight={binHeight}+ bins={(column) => column.bins}+ binWidth={binWidth}+ colorScale={(count) =>+ colorScale(typeof count === 'number' ? count : count?.valueOf())+ }+ count={(bin) => bin.count}+ data={data}+ gap={gap}+ xScale={xScale}+ yScale={yScale}+ >+ {(cells) => (+ <Group className="visx-heatmap-rects">+ {cells.flatMap((column) =>+ column.map((cell) => {+ const bin = data[cell.column]?.bins[cell.row];+ if (!bin) {+ return null;+ }++ if (displayRange && isHeatmapGhostBin(bin, displayRange)) {+ return null;+ }++ const hoverState = computeHeatmapCellFaded(+ isCellHovering,+ isLevelHovering,+ hoveredCell,+ hoveredLegendLevel,+ cell,+ bin.count+ );++ return (+ <HeatmapMotionCell+ activeScale={activeScale}+ bin={bin}+ cell={cell}+ cornerRadius={cornerRadius}+ fillScale={fillScale}+ hoverState={hoverState}+ inactiveOpacity={inactiveOpacity}+ inactiveScale={inactiveScale}+ interactive={cellsInteractive}+ key={`heatmap-cell-${cell.column}-${cell.row}`}+ onEnter={handleCellEnter}+ onLeave={handleCellLeave}+ rowOpacity={rowOpacity}+ />+ );+ })+ )}+ </Group>+ )}+ </HeatmapRect>+ );+});++HeatmapCells.displayName = 'HeatmapCells';++export default HeatmapCells;diff --git a/apps/start/src/components/charts/heatmap/heatmap-chart-loading.tsx b/apps/start/src/components/charts/heatmap/heatmap-chart-loading.tsxnew file mode 100644index 000000000..b352cea5a--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-chart-loading.tsx@@ -0,0 +1,60 @@+'use client';++import { useMemo } from 'react';+import type { Margin } from '../chart-context';+import { generateHeatmapSkeletonFromTarget } from './generate-heatmap-skeleton-data';+import { HeatmapCells } from './heatmap-cells';+import { HeatmapChart } from './heatmap-chart';+import type { HeatmapColumn } from './heatmap-context';+import { HeatmapXAxis } from './heatmap-x-axis';+import { HeatmapYAxis } from './heatmap-y-axis';++export interface HeatmapChartLoadingProps {+ /** Target column data used to size the skeleton grid. */+ data: HeatmapColumn[];+ /** Visible time range — filters week columns that overlap the domain. */+ xDomain?: [Date, Date];+ /** Chart margins */+ margin?: Partial<Margin>;+ /** Gap between cells in pixels. Default: 2 */+ gap?: number;+ /** Corner radius for each cell. Default: 2 */+ cornerRadius?: number;+ /** Centered shimmer label text. Default: "Loading" */+ label?: string;+ /** Additional class name for the container */+ className?: string;+}++export function HeatmapChartLoading({+ data,+ xDomain,+ margin,+ gap = 2,+ cornerRadius = 2,+ label = 'Loading',+ className = '',+}: HeatmapChartLoadingProps) {+ const skeletonData = useMemo(+ () => generateHeatmapSkeletonFromTarget(data),+ [data]+ );++ return (+ <HeatmapChart+ className={className}+ data={skeletonData}+ gap={gap}+ loadingLabel={label}+ margin={margin}+ status="loading"+ xDomain={xDomain}+ >+ <HeatmapCells cornerRadius={cornerRadius} interactive={false} />+ <HeatmapXAxis />+ <HeatmapYAxis />+ </HeatmapChart>+ );+}++export default HeatmapChartLoading;diff --git a/apps/start/src/components/charts/heatmap/heatmap-chart.tsx b/apps/start/src/components/charts/heatmap/heatmap-chart.tsxnew file mode 100644index 000000000..33b527b46--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-chart.tsx@@ -0,0 +1,735 @@+'use client';++import { useParentSize } from '@visx/responsive';+import { scaleLinear, scaleTime } from '@visx/scale';+import type { Transition } from 'motion/react';+import { useReducedMotion } from 'motion/react';+import {+ type ReactNode,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import type { Margin } from '../chart-context';+import { ChartLoadingLabel } from '../chart-loading-label';+import {+ type ChartPhase,+ type ChartStatus,+ DEFAULT_CHART_STATUS,+ resolveRestingChartPhase,+} from '../chart-phase';+import {+ HEATMAP_DEFAULT_ENTER_DURATION_MS,+ HEATMAP_DEFAULT_ENTER_TRANSITION,+ HEATMAP_DEFAULT_LOADING_CELL_MAX_OPACITY,+ HEATMAP_DEFAULT_LOADING_CELL_RANDOMNESS,+ HEATMAP_LOADING_CHART_OPACITY,+ HEATMAP_LOADING_CONCEAL_MS,+} from './heatmap-animation';+import type { HeatmapLevelColors, HeatmapLevelStyles } from './heatmap-colors';+import {+ buildHeatmapColorScaleFromStyles,+ buildHeatmapFillScale,+ resolveHeatmapLevelStyles,+} from './heatmap-colors';+import {+ type HeatmapColumn,+ type HeatmapContextValue,+ HeatmapInteractionRoot,+ HeatmapProvider,+ type HeatmapRevealMode,+ useHeatmap,+ useHeatmapInteraction,+} from './heatmap-context';+import { HeatmapPatternDefs } from './heatmap-pattern-defs';+import { resolveHeatmapSeparatorConfigWithData } from './heatmap-resolve-separator';+import {+ filterHeatmapColumns,+ getHeatmapColumnXOffset,+ getHeatmapPlotInnerWidth,+ getHeatmapSeparatorCount,+ getHeatmapTimeExtent,+ type HeatmapSeparatorLayout,+ type HeatmapSeparatorParsedConfig,+ type HeatmapWeekStartDay,+ rotateHeatmapColumnBins,+} from './heatmap-utils';+import { cn } from '@/lib/utils';++export type HeatmapLayout = 'fluid' | 'fill';++export interface HeatmapChartProps {+ /** Column data — one entry per week (or category) with row bins inside. */+ data: HeatmapColumn[];+ /** Visible time range — filters week columns that overlap the domain. */+ xDomain?: [Date, Date];+ /**+ * Week columns used for cell sizing when `xDomain` is set. Keeps bin height+ * stable while scrubbing (filtered columns can vary by ±1 at boundaries).+ */+ sizingColumnCount?: number;+ /**+ * `fluid` — width drives square cells; chart height hugs the grid (GitHub-style).+ * `fill` — expands cells to fill the parent.+ */+ layout?: HeatmapLayout;+ /** Chart margins */+ margin?: Partial<Margin>;+ /** Fixed cell size in pixels. When 0, cells are square and sized to fit the plot. Default: 0 */+ binSize?: number;+ /** Gap between cells in pixels. Default: 2 */+ gap?: number;+ /** Override the default color scale. */+ colorScale?: (count: number | null | undefined) => string;+ /** Per-level colors for the Less → More scale (5 entries). */+ levelColors?: HeatmapLevelColors;+ /** Per-level fill styles (color and optional pattern). Takes precedence over `levelColors`. */+ levelStyles?: HeatmapLevelStyles;+ /** Optional outer aspect ratio (e.g. "2 / 1"). Omit to fill the parent. */+ aspectRatio?: string;+ /** Additional class name for the container */+ className?: string;+ /** Fetch / display status. Default: `"ready"`. */+ status?: ChartStatus;+ /** Centered label while loading. */+ loadingLabel?: string;+ /** Enter animation duration in milliseconds. Default: 1600 */+ animationDuration?: number;+ /** Motion enter transition (spring or cubic-bezier tween). */+ enterTransition?: Transition;+ /** Signature of motion URL state — triggers enter replay when it changes. */+ revealSignature?: string;+ /** Scales wave stagger delays (1 = default). */+ enterStaggerScale?: number;+ /** Play enter fade-in / loading shimmer animations. Default: true */+ animate?: boolean;+ /** Chart opacity while loading. Default: 0.5 */+ loadingOpacity?: number;+ /** Show loading cell shimmer while loading. Default: true */+ showLoadingCells?: boolean;+ /** Max opacity loading cells animate toward (0–1). Default: 0.5 */+ loadingCellMaxOpacity?: number;+ /** Share of cells that participate in loading shimmer (0–1). Default: 0.65 */+ loadingCellRandomness?: number;+ /**+ * Inserts horizontal gaps between column groups. Overridden when a+ * {@link HeatmapSeparator} child sets `every` / `spacing`.+ */+ columnSeparators?: HeatmapSeparatorParsedConfig;+ /**+ * First row of the grid — `0` = Sunday (GitHub default), `1` = Monday, etc.+ * Rotates column bins for display without reshaping source data.+ */+ weekStartDay?: HeatmapWeekStartDay;+ /** Child components (HeatmapCells, HeatmapXAxis, HeatmapYAxis) */+ children: ReactNode;+}++const DEFAULT_MARGIN: Margin = { top: 28, right: 16, bottom: 0, left: 40 };++function computeHeatmapDimensions({+ width,+ parentHeight,+ margin,+ columnCount,+ rowCount,+ binSize,+ layout,+ separator,+}: {+ width: number;+ parentHeight: number;+ margin: Margin;+ columnCount: number;+ rowCount: number;+ binSize: number;+ layout: HeatmapLayout;+ separator: Pick<HeatmapSeparatorLayout, 'spacing' | 'atColumns'> | null;+}) {+ const innerWidth = Math.max(width - margin.left - margin.right, 0);+ const availableHeight = Math.max(+ parentHeight - margin.top - margin.bottom,+ 0+ );+ const separatorCount = separator ? getHeatmapSeparatorCount(separator) : 0;+ const totalSpacing = separatorCount * (separator?.spacing ?? 0);++ let binWidth: number;+ let binHeight: number;++ if (binSize > 0) {+ binWidth = binSize;+ binHeight = binSize;+ } else if (layout === 'fluid') {+ const cellSize = Math.max((innerWidth - totalSpacing) / columnCount, 0);+ binWidth = cellSize;+ binHeight = cellSize;+ } else {+ const cellSize = Math.min(+ Math.max((innerWidth - totalSpacing) / columnCount, 0),+ availableHeight / rowCount+ );+ binWidth = cellSize;+ binHeight = cellSize;+ }++ const plotInnerWidth = getHeatmapPlotInnerWidth(+ columnCount,+ binWidth,+ separator+ );+ const innerHeight = rowCount * binHeight;+ const height =+ layout === 'fluid'+ ? margin.top + innerHeight + margin.bottom+ : Math.max(parentHeight, margin.top + innerHeight + margin.bottom);+ const chartWidth =+ binSize > 0 && layout === 'fluid'+ ? margin.left + plotInnerWidth + margin.right+ : width;++ return {+ binWidth,+ binHeight,+ innerWidth: plotInnerWidth,+ innerHeight,+ height,+ width: chartWidth,+ };+}++interface HeatmapChartInnerProps {+ width: number;+ height: number;+ data: HeatmapColumn[];+ xDomain?: [Date, Date];+ sizingColumnCount?: number;+ margin: Margin;+ binSize: number;+ gap: number;+ layout: HeatmapLayout;+ colorScale: (count: number | null | undefined) => string;+ fillScale: (count: number | null | undefined) => string;+ levelStyles: HeatmapLevelStyles;+ chartStatus: ChartStatus;+ chartPhase: ChartPhase;+ isLoaded: boolean;+ revealEpoch: number;+ animationDuration: number;+ enterTransition?: Transition;+ enterStaggerScale: number;+ animateCells: boolean;+ loadingOpacity: number;+ showLoadingCells: boolean;+ loadingCellMaxOpacity: number;+ loadingCellRandomness: number;+ revealMode: HeatmapRevealMode;+ loadingLabel?: string;+ showLoadingLabel: boolean;+ columnSeparators?: HeatmapSeparatorParsedConfig;+ weekStartDay: HeatmapWeekStartDay;+ children: ReactNode;+}++function HeatmapChartInner({+ width,+ height: parentHeight,+ data,+ xDomain,+ sizingColumnCount: sizingColumnCountProp,+ margin,+ binSize,+ gap,+ layout,+ colorScale,+ fillScale,+ levelStyles,+ chartStatus,+ chartPhase,+ isLoaded,+ revealEpoch,+ animationDuration,+ enterTransition,+ enterStaggerScale,+ animateCells,+ loadingOpacity,+ showLoadingCells,+ loadingCellMaxOpacity,+ loadingCellRandomness,+ revealMode,+ loadingLabel,+ showLoadingLabel,+ columnSeparators,+ weekStartDay,+ children,+}: HeatmapChartInnerProps) {+ const containerRef = useRef<HTMLDivElement>(null);++ const filteredData = useMemo(+ () => filterHeatmapColumns(data, xDomain),+ [data, xDomain]+ );++ const visibleData = useMemo(+ () => rotateHeatmapColumnBins(filteredData, weekStartDay),+ [filteredData, weekStartDay]+ );++ const visibleColumnCount = Math.max(visibleData.length, 1);+ const columnCount =+ xDomain && sizingColumnCountProp != null+ ? Math.max(sizingColumnCountProp, 1)+ : visibleColumnCount;+ const rowCount = Math.max(visibleData[0]?.bins.length ?? 7, 1);++ const separatorLayout = useMemo(+ () =>+ resolveHeatmapSeparatorConfigWithData(+ children,+ visibleData,+ columnSeparators+ ),+ [children, columnSeparators, visibleData]+ );++ const {+ binWidth,+ binHeight,+ innerWidth,+ innerHeight,+ height,+ width: chartWidth,+ } = useMemo(+ () =>+ computeHeatmapDimensions({+ width,+ parentHeight,+ margin,+ columnCount,+ rowCount,+ binSize,+ layout,+ separator: separatorLayout,+ }),+ [+ binSize,+ columnCount,+ layout,+ margin,+ parentHeight,+ rowCount,+ separatorLayout,+ width,+ ]+ );++ const xScale = useMemo(+ () => (columnIndex: number) =>+ columnIndex * binWidth ++ getHeatmapColumnXOffset(columnIndex, separatorLayout),+ [binWidth, separatorLayout]+ );+ const yScale = useMemo(+ () => (rowIndex: number) => rowIndex * binHeight,+ [binHeight]+ );++ const timeExtent = useMemo(() => getHeatmapTimeExtent(data), [data]);++ const timeXScale = useMemo(() => {+ const domain = timeExtent ?? [new Date(), new Date()];+ return scaleTime({+ domain,+ range: [0, innerWidth],+ });+ }, [innerWidth, timeExtent]);++ const brushYScale = useMemo(+ () =>+ scaleLinear({+ domain: [0, 1],+ range: [innerHeight, 0],+ }),+ [innerHeight]+ );++ const contextValue = useMemo<HeatmapContextValue>(+ () => ({+ data: visibleData,+ width: chartWidth,+ height,+ innerWidth,+ innerHeight,+ margin,+ binWidth,+ binHeight,+ gap,+ weekStartDay,+ xScale,+ yScale,+ separatorLayout,+ timeXScale,+ brushYScale,+ isReady: chartWidth >= 10 && height >= 10,+ colorScale,+ fillScale,+ levelStyles,+ containerRef,+ chartStatus,+ chartPhase,+ isLoaded,+ revealEpoch,+ animationDuration,+ enterTransition,+ enterStaggerScale,+ animateCells,+ loadingOpacity,+ showLoadingCells,+ loadingCellMaxOpacity,+ loadingCellRandomness,+ revealMode,+ loadingLabel,+ showLoadingLabel,+ }),+ [+ animateCells,+ animationDuration,+ binHeight,+ binWidth,+ brushYScale,+ chartPhase,+ chartStatus,+ chartWidth,+ colorScale,+ fillScale,+ enterStaggerScale,+ enterTransition,+ gap,+ height,+ innerHeight,+ innerWidth,+ isLoaded,+ loadingCellMaxOpacity,+ loadingCellRandomness,+ loadingLabel,+ levelStyles,+ loadingOpacity,+ margin,+ revealMode,+ separatorLayout,+ showLoadingCells,+ showLoadingLabel,+ revealEpoch,+ timeXScale,+ visibleData,+ weekStartDay,+ xScale,+ yScale,+ ]+ );++ if (chartWidth < 10 || height < 10) {+ return null;+ }++ return (+ <HeatmapProvider value={contextValue}>+ <HeatmapInteractionRoot>+ <HeatmapChartSurface layout={layout}>{children}</HeatmapChartSurface>+ </HeatmapInteractionRoot>+ </HeatmapProvider>+ );+}++function HeatmapChartSurface({+ layout,+ children,+}: {+ layout: HeatmapLayout;+ children: ReactNode;+}) {+ const {+ containerRef,+ height,+ width,+ margin,+ levelStyles,+ chartPhase,+ loadingOpacity,+ loadingLabel,+ showLoadingLabel,+ } = useHeatmap();+ const { clearInteraction } = useHeatmapInteraction();+ const reducedOpacity =+ chartPhase === 'loading' || chartPhase === 'exitingReady'+ ? loadingOpacity+ : 1;++ return (+ <div+ className={cn('relative w-full', layout === 'fill' && 'h-full')}+ onPointerLeave={clearInteraction}+ ref={containerRef}+ style={{ opacity: reducedOpacity }}+ >+ <svg+ aria-hidden="true"+ className="overflow-visible"+ height={height}+ width={width}+ >+ <HeatmapPatternDefs levelStyles={levelStyles} />+ <g transform={`translate(${margin.left},${margin.top})`}>{children}</g>+ </svg>+ {showLoadingLabel && loadingLabel?.trim() ? (+ <div+ className="pointer-events-none absolute"+ style={{+ top: margin.top,+ left: margin.left,+ width: Math.max(width - margin.left - margin.right, 0),+ height: Math.max(height - margin.top - margin.bottom, 0),+ }}+ >+ <ChartLoadingLabel+ exiting={chartPhase !== 'loading'}+ text={loadingLabel}+ />+ </div>+ ) : null}+ </div>+ );+}++function useHeatmapChartLifecycle({+ chartStatus,+ animationDuration,+ revealSignature = '',+ animate,+}: {+ chartStatus: ChartStatus;+ animationDuration: number;+ revealSignature?: string;+ animate: boolean;+}) {+ const reducedMotion = useReducedMotion();+ const [chartPhase, setChartPhase] = useState<ChartPhase>(() =>+ resolveRestingChartPhase(chartStatus)+ );+ const [isLoaded, setIsLoaded] = useState(+ () => chartStatus === 'ready' && (!animate || animationDuration <= 0)+ );+ const [revealEpoch, setRevealEpoch] = useState(0);+ const [revealMode, setRevealMode] = useState<HeatmapRevealMode>(null);+ const prevStatusRef = useRef(chartStatus);+ const phaseRef = useRef(chartPhase);+ phaseRef.current = chartPhase;++ const animateCells = animate && !reducedMotion;+ const animateEnter = animateCells && animationDuration > 0;++ const finishReveal = useCallback(() => {+ setIsLoaded(true);+ setChartPhase('ready');+ setRevealMode(null);+ }, []);++ const beginReveal = useCallback(() => {+ setRevealMode('enter');+ setRevealEpoch((epoch) => epoch + 1);+ setIsLoaded(false);+ setChartPhase('revealing');+ if (!animateEnter) {+ finishReveal();+ }+ }, [animateEnter, finishReveal]);++ useLayoutEffect(() => {+ const prevStatus = prevStatusRef.current;+ if (prevStatus === chartStatus) {+ return;+ }+ prevStatusRef.current = chartStatus;++ if (chartStatus === 'ready' && prevStatus === 'loading') {+ setRevealMode('fromLoading');+ setIsLoaded(false);+ setChartPhase('revealing');+ return;+ }++ if (chartStatus === 'loading' && prevStatus === 'ready') {+ setRevealMode(null);+ setIsLoaded(false);+ setChartPhase('exitingReady');+ }+ }, [chartStatus]);++ useEffect(() => {+ if (chartPhase !== 'exitingReady') {+ return;+ }++ const timer = window.setTimeout(() => {+ setChartPhase('loading');+ }, HEATMAP_LOADING_CONCEAL_MS);++ return () => window.clearTimeout(timer);+ }, [chartPhase]);++ // biome-ignore lint/correctness/useExhaustiveDependencies: revealSignature replays enter+ useEffect(() => {+ if (!animateEnter) {+ setIsLoaded(true);+ setChartPhase(resolveRestingChartPhase(chartStatus));+ return;+ }+ if (chartStatus !== 'ready') {+ return;+ }+ if (phaseRef.current !== 'ready') {+ return;+ }++ beginReveal();+ }, [+ animateEnter,+ animationDuration,+ beginReveal,+ chartStatus,+ revealSignature,+ ]);++ // biome-ignore lint/correctness/useExhaustiveDependencies: revealEpoch replays finish timer+ useEffect(() => {+ if (!animateEnter || chartPhase !== 'revealing') {+ return;+ }++ const finishTimer = window.setTimeout(finishReveal, animationDuration);+ return () => window.clearTimeout(finishTimer);+ }, [animateEnter, animationDuration, chartPhase, finishReveal, revealEpoch]);++ return {+ chartPhase,+ isLoaded,+ revealEpoch,+ revealMode,+ animateCells,+ };+}++export function HeatmapChart({+ data,+ xDomain,+ sizingColumnCount,+ layout = 'fluid',+ margin: marginProp,+ binSize = 0,+ gap = 2,+ colorScale: colorScaleProp,+ levelColors,+ levelStyles: levelStylesProp,+ aspectRatio,+ className = '',+ status = DEFAULT_CHART_STATUS,+ loadingLabel,+ animationDuration = HEATMAP_DEFAULT_ENTER_DURATION_MS,+ enterTransition = HEATMAP_DEFAULT_ENTER_TRANSITION,+ revealSignature = '',+ enterStaggerScale = 1,+ animate = true,+ loadingOpacity = HEATMAP_LOADING_CHART_OPACITY,+ showLoadingCells = true,+ loadingCellMaxOpacity = HEATMAP_DEFAULT_LOADING_CELL_MAX_OPACITY,+ loadingCellRandomness = HEATMAP_DEFAULT_LOADING_CELL_RANDOMNESS,+ columnSeparators,+ weekStartDay = 0,+ children,+}: HeatmapChartProps) {+ const margin = { ...DEFAULT_MARGIN, ...marginProp };+ const levelStyles = useMemo(+ () => resolveHeatmapLevelStyles(levelColors, levelStylesProp),+ [levelColors, levelStylesProp]+ );+ const colorScale = useMemo(+ () => colorScaleProp ?? buildHeatmapColorScaleFromStyles(levelStyles),+ [colorScaleProp, levelStyles]+ );+ const fillScale = useMemo(+ () => buildHeatmapFillScale(levelStyles),+ [levelStyles]+ );++ const { chartPhase, isLoaded, revealEpoch, revealMode, animateCells } =+ useHeatmapChartLifecycle({+ chartStatus: status,+ animationDuration,+ revealSignature,+ animate,+ });++ const showLoadingLabel = Boolean(+ loadingLabel?.trim() &&+ status === 'loading' &&+ (chartPhase === 'loading' || chartPhase === 'exitingReady')+ );++ // Measure this container directly: visx 4's <ParentSize> renders children in+ // an absolutely positioned box, which collapses the content-sized fluid+ // layout to zero height.+ const { parentRef, width, height: parentHeight } = useParentSize();++ return (+ <div+ className={cn(+ 'relative w-full',+ layout === 'fill' && 'h-full min-h-0',+ className+ )}+ ref={parentRef}+ style={aspectRatio ? { aspectRatio } : undefined}+ >+ <HeatmapChartInner+ animateCells={animateCells}+ animationDuration={animationDuration}+ binSize={binSize}+ chartPhase={chartPhase}+ chartStatus={status}+ colorScale={colorScale}+ columnSeparators={columnSeparators}+ data={data}+ enterStaggerScale={enterStaggerScale}+ enterTransition={enterTransition}+ fillScale={fillScale}+ gap={gap}+ height={parentHeight}+ isLoaded={isLoaded}+ layout={layout}+ levelStyles={levelStyles}+ loadingCellMaxOpacity={loadingCellMaxOpacity}+ loadingCellRandomness={loadingCellRandomness}+ loadingLabel={loadingLabel}+ loadingOpacity={loadingOpacity}+ margin={margin}+ revealEpoch={revealEpoch}+ revealMode={revealMode}+ showLoadingCells={showLoadingCells}+ showLoadingLabel={showLoadingLabel}+ sizingColumnCount={sizingColumnCount}+ weekStartDay={weekStartDay}+ width={width}+ xDomain={xDomain}+ >+ {children}+ </HeatmapChartInner>+ </div>+ );+}++HeatmapChart.displayName = 'HeatmapChart';++export default HeatmapChart;diff --git a/apps/start/src/components/charts/heatmap/heatmap-colors.ts b/apps/start/src/components/charts/heatmap/heatmap-colors.tsnew file mode 100644index 000000000..5cb4b7fca--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-colors.ts@@ -0,0 +1,188 @@+import { CHART_SCALE_VARS } from '../chart-scale';+import type { PatternPresetId } from '../pattern-preset';+import { getHeatmapContributionLevel } from './heatmap-utils';++/** Default Less → More scale using {@link CHART_SCALE_VARS}. */+export const HEATMAP_DEFAULT_LEVEL_COLORS = CHART_SCALE_VARS;++export type HeatmapLevelColors = readonly [+ string,+ string,+ string,+ string,+ string,+];++export type HeatmapLevelFillMode = 'solid' | 'pattern';++export interface HeatmapLevelStyle {+ color: string;+ fillMode?: HeatmapLevelFillMode;+ pattern?: PatternPresetId;+ patternColor?: string;+ patternScale?: number;+ patternStrokeWidth?: number;+ patternRadius?: number;+ patternComplement?: boolean;+ patternFill?: string;+ patternTileBackground?: string;+ patternOpacity?: number;+ patternDotsFill?: boolean;+}++export type HeatmapLevelStyles = readonly [+ HeatmapLevelStyle,+ HeatmapLevelStyle,+ HeatmapLevelStyle,+ HeatmapLevelStyle,+ HeatmapLevelStyle,+];++export const HEATMAP_DEFAULT_LEVEL_STYLES = [+ {+ color: HEATMAP_DEFAULT_LEVEL_COLORS[0],+ fillMode: 'solid',+ pattern: 'none',+ },+ {+ color: HEATMAP_DEFAULT_LEVEL_COLORS[1],+ fillMode: 'solid',+ pattern: 'none',+ },+ {+ color: HEATMAP_DEFAULT_LEVEL_COLORS[2],+ fillMode: 'solid',+ pattern: 'none',+ },+ {+ color: HEATMAP_DEFAULT_LEVEL_COLORS[3],+ fillMode: 'solid',+ pattern: 'none',+ },+ {+ color: HEATMAP_DEFAULT_LEVEL_COLORS[4],+ fillMode: 'solid',+ pattern: 'none',+ },+] as const satisfies HeatmapLevelStyles;++export function heatmapLevelPatternId(level: number): string {+ return `heatmap-level-${level}`;+}++export function isHeatmapLevelPattern(style: HeatmapLevelStyle): boolean {+ return (+ style.fillMode === 'pattern' &&+ style.pattern != null &&+ style.pattern !== 'none'+ );+}++export function heatmapPatternStrokeFallback(color: string): string {+ return `color-mix(in oklch, ${color} 45%, white)`;+}++export function heatmapLevelPatternRenderOptions(style: HeatmapLevelStyle) {+ const preset = style.pattern ?? 'diagonal';+ let defaultScale = 1;+ if (preset === 'cross') {+ defaultScale = 1.33;+ }++ return {+ color:+ style.patternColor?.trim() ||+ (preset === 'accent'+ ? '#e879f9'+ : heatmapPatternStrokeFallback(style.color)),+ tileBackground: style.patternTileBackground?.trim() || style.color,+ scale: style.patternScale ?? defaultScale,+ strokeWidth: style.patternStrokeWidth,+ radius: style.patternRadius,+ complement: style.patternComplement,+ fill: style.patternFill?.trim() || undefined,+ dotFill: style.patternDotsFill,+ };+}++export function heatmapLevelCellFillOpacity(style: HeatmapLevelStyle): number {+ if (!isHeatmapLevelPattern(style)) {+ return 1;+ }+ return style.patternOpacity ?? 1;+}++export function levelColorsFromStyles(+ levelStyles: HeatmapLevelStyles+): HeatmapLevelColors {+ return [+ levelStyles[0].color,+ levelStyles[1].color,+ levelStyles[2].color,+ levelStyles[3].color,+ levelStyles[4].color,+ ];+}++export function levelStylesFromColors(+ levelColors: HeatmapLevelColors+): HeatmapLevelStyles {+ return [+ { color: levelColors[0], fillMode: 'solid', pattern: 'none' },+ { color: levelColors[1], fillMode: 'solid', pattern: 'none' },+ { color: levelColors[2], fillMode: 'solid', pattern: 'none' },+ { color: levelColors[3], fillMode: 'solid', pattern: 'none' },+ { color: levelColors[4], fillMode: 'solid', pattern: 'none' },+ ];+}++export function resolveHeatmapLevelStyles(+ levelColors?: HeatmapLevelColors,+ levelStyles?: HeatmapLevelStyles+): HeatmapLevelStyles {+ if (levelStyles) {+ return levelStyles;+ }+ if (levelColors) {+ return levelStylesFromColors(levelColors);+ }+ return HEATMAP_DEFAULT_LEVEL_STYLES;+}++export function buildHeatmapColorScale(+ levelColors: HeatmapLevelColors+): (count: number | null | undefined) => string {+ return buildHeatmapColorScaleFromStyles(levelStylesFromColors(levelColors));+}++export function buildHeatmapColorScaleFromStyles(+ levelStyles: HeatmapLevelStyles+): (count: number | null | undefined) => string {+ return (count: number | null | undefined) => {+ const level = getHeatmapContributionLevel(count ?? 0);+ return levelStyles[level]?.color ?? levelStyles[0].color;+ };+}++export function buildHeatmapFillScale(+ levelStyles: HeatmapLevelStyles+): (count: number | null | undefined) => string {+ return (count: number | null | undefined) => {+ const level = getHeatmapContributionLevel(count ?? 0);+ const style = levelStyles[level] ?? levelStyles[0];++ if (isHeatmapLevelPattern(style)) {+ return `url(#${heatmapLevelPatternId(level)})`;+ }++ return style.color;+ };+}++export const defaultHeatmapColorScale = buildHeatmapColorScale(+ HEATMAP_DEFAULT_LEVEL_COLORS+);++export const defaultHeatmapFillScale = buildHeatmapFillScale(+ HEATMAP_DEFAULT_LEVEL_STYLES+);diff --git a/apps/start/src/components/charts/heatmap/heatmap-context.tsx b/apps/start/src/components/charts/heatmap/heatmap-context.tsxnew file mode 100644index 000000000..2335e2343--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-context.tsx@@ -0,0 +1,218 @@+'use client';++import type { scaleLinear, scaleTime } from '@visx/scale';+import type { Transition } from 'motion/react';+import {+ createContext,+ type Dispatch,+ type ReactNode,+ type RefObject,+ type SetStateAction,+ useCallback,+ useContext,+ useMemo,+ useState,+} from 'react';+import type { Margin } from '../chart-context';+import type { ChartPhase, ChartStatus } from '../chart-phase';+import {+ HEATMAP_DEFAULT_LEVEL_COLORS,+ type HeatmapLevelStyles,+} from './heatmap-colors';+import type {+ HeatmapSeparatorLayout,+ HeatmapWeekStartDay,+} from './heatmap-utils';+import { cn } from '@/lib/utils';++type HeatmapTimeScale = ReturnType<typeof scaleTime<number>>;+type HeatmapLinearScale = ReturnType<typeof scaleLinear<number>>;++export interface HeatmapBin {+ count: number;+ bin: number;+ date: Date;+}++export interface HeatmapColumn {+ bin: number;+ bins: HeatmapBin[];+}++export interface HeatmapTooltipData {+ column: number;+ row: number;+ count: number;+ date: Date;+ x: number;+ y: number;+}++export interface HeatmapInteractionContextValue {+ hoveredCell: { column: number; row: number } | null;+ hoveredLegendLevel: number | null;+ tooltipData: HeatmapTooltipData | null;+ setHoveredCell: (cell: { column: number; row: number } | null) => void;+ setHoveredLegendLevel: (level: number | null) => void;+ setTooltipData: Dispatch<SetStateAction<HeatmapTooltipData | null>>;+ clearInteraction: () => void;+}++export interface HeatmapContextValue {+ data: HeatmapColumn[];+ width: number;+ height: number;+ innerWidth: number;+ innerHeight: number;+ margin: Margin;+ binWidth: number;+ binHeight: number;+ gap: number;+ weekStartDay: HeatmapWeekStartDay;+ xScale: (columnIndex: number) => number;+ yScale: (rowIndex: number) => number;+ separatorLayout: HeatmapSeparatorLayout | null;+ timeXScale: HeatmapTimeScale;+ brushYScale: HeatmapLinearScale;+ isReady: boolean;+ colorScale: (count: number | null | undefined) => string;+ fillScale: (count: number | null | undefined) => string;+ levelStyles: HeatmapLevelStyles;+ containerRef: RefObject<HTMLDivElement | null>;+ chartStatus: ChartStatus;+ chartPhase: ChartPhase;+ isLoaded: boolean;+ revealEpoch: number;+ animationDuration: number;+ enterTransition?: Transition;+ enterStaggerScale: number;+ animateCells: boolean;+ loadingOpacity: number;+ showLoadingCells: boolean;+ loadingCellMaxOpacity: number;+ loadingCellRandomness: number;+ revealMode: HeatmapRevealMode;+ loadingLabel?: string;+ showLoadingLabel: boolean;+}++/** How cells transition into view after loading or on first mount. */+export type HeatmapRevealMode = 'enter' | 'fromLoading' | null;++const HeatmapContext = createContext<HeatmapContextValue | null>(null);+const HeatmapInteractionContext =+ createContext<HeatmapInteractionContextValue | null>(null);++export function HeatmapInteractionProvider({+ children,+}: {+ children: ReactNode;+}) {+ const [hoveredCell, setHoveredCell] = useState<{+ column: number;+ row: number;+ } | null>(null);+ const [hoveredLegendLevel, setHoveredLegendLevel] = useState<number | null>(+ null+ );+ const [tooltipData, setTooltipData] = useState<HeatmapTooltipData | null>(+ null+ );++ const clearInteraction = useCallback(() => {+ setHoveredCell(null);+ setHoveredLegendLevel(null);+ setTooltipData(null);+ }, []);++ const value = useMemo<HeatmapInteractionContextValue>(+ () => ({+ hoveredCell,+ hoveredLegendLevel,+ tooltipData,+ setHoveredCell,+ setHoveredLegendLevel,+ setTooltipData,+ clearInteraction,+ }),+ [clearInteraction, hoveredCell, hoveredLegendLevel, tooltipData]+ );++ return (+ <HeatmapInteractionContext.Provider value={value}>+ {children}+ </HeatmapInteractionContext.Provider>+ );+}++export function HeatmapProvider({+ children,+ value,+}: {+ children: ReactNode;+ value: HeatmapContextValue;+}) {+ return (+ <HeatmapContext.Provider value={value}>{children}</HeatmapContext.Provider>+ );+}++export function useHeatmap(): HeatmapContextValue {+ const context = useContext(HeatmapContext);+ if (!context) {+ throw new Error('useHeatmap must be used within a HeatmapProvider');+ }+ return context;+}++export function useHeatmapInteraction(): HeatmapInteractionContextValue {+ const context = useContext(HeatmapInteractionContext);+ if (!context) {+ throw new Error(+ 'useHeatmapInteraction must be used within a HeatmapInteractionProvider'+ );+ }+ return context;+}++export function useHeatmapInteractionOptional(): HeatmapInteractionContextValue | null {+ return useContext(HeatmapInteractionContext);+}++/** Clears hover state when the pointer leaves chart + legend. */+export function HeatmapInteractionBoundary({+ children,+ className,+}: {+ children: ReactNode;+ className?: string;+}) {+ const { clearInteraction } = useHeatmapInteraction();++ return (+ <div+ className={cn('size-full min-h-0 min-w-0', className)}+ onPointerLeave={clearInteraction}+ >+ {children}+ </div>+ );+}++/** Nests a provider only when one is not already present upstream. */+export function HeatmapInteractionRoot({ children }: { children: ReactNode }) {+ const existing = useContext(HeatmapInteractionContext);+ if (existing) {+ return children;+ }+ return <HeatmapInteractionProvider>{children}</HeatmapInteractionProvider>;+}++/** @deprecated Use {@link HEATMAP_DEFAULT_LEVEL_COLORS} */+export const heatmapCssVars = {+ empty: HEATMAP_DEFAULT_LEVEL_COLORS[0],+ level1: HEATMAP_DEFAULT_LEVEL_COLORS[1],+ level2: HEATMAP_DEFAULT_LEVEL_COLORS[2],+ level3: HEATMAP_DEFAULT_LEVEL_COLORS[3],+ level4: HEATMAP_DEFAULT_LEVEL_COLORS[4],+} as const;diff --git a/apps/start/src/components/charts/heatmap/heatmap-legend-gradient.tsx b/apps/start/src/components/charts/heatmap/heatmap-legend-gradient.tsxnew file mode 100644index 000000000..15c95dff2--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-legend-gradient.tsx@@ -0,0 +1,111 @@+'use client';++import { motion } from 'motion/react';+import { memo } from 'react';+import type { HeatmapLevelStyles } from './heatmap-colors';+import {+ buildHeatmapLegendGradient,+ resolveHeatmapHoverStyle,+} from './heatmap-utils';++const HEATMAP_INACTIVE_TRANSITION = {+ duration: 0.22,+ ease: [0.4, 0, 0.2, 1] as const,+};++export interface HeatmapLegendGradientProps {+ levels: readonly number[];+ levelStyles: HeatmapLevelStyles;+ cellSize: number;+ gap: number;+ cornerRadius: number;+ gradientSpan: number;+ highlightedLevel: number | null;+ isDimming: boolean;+ inactiveOpacity: number;+ inactiveScale: number;+ activeScale: number;+ isInteractive: boolean;+ onEnter: (level: number) => void;+ onLeave: () => void;+}++export const HeatmapLegendGradient = memo(function HeatmapLegendGradient({+ levels,+ levelStyles,+ cellSize,+ gap,+ cornerRadius,+ gradientSpan,+ highlightedLevel,+ isDimming,+ inactiveOpacity,+ inactiveScale,+ activeScale,+ isInteractive,+ onEnter,+ onLeave,+}: HeatmapLegendGradientProps) {+ const barWidth = gradientSpan * cellSize + (gradientSpan - 1) * gap;+ const barHeight = cellSize;+ const pillRadius = Math.min(cornerRadius, barHeight / 2);+ const segmentWidth = barWidth / levels.length;+ const gradient = buildHeatmapLegendGradient(levelStyles);++ return (+ <div+ className="relative shrink-0"+ style={{ width: barWidth, height: barHeight }}+ >+ <motion.div+ animate={{+ opacity: isDimming && highlightedLevel === null ? inactiveOpacity : 1,+ scale: 1,+ }}+ aria-hidden="true"+ className="absolute inset-0"+ initial={{ opacity: 1, scale: 1 }}+ style={{+ borderRadius: pillRadius,+ background: gradient,+ }}+ transition={HEATMAP_INACTIVE_TRANSITION}+ />+ {levels.map((level, index) => {+ const isHighlighted = highlightedLevel === level;+ const isDimmed = isDimming && !isHighlighted;+ const hoverStyle = resolveHeatmapHoverStyle(isHighlighted, isDimmed, {+ inactiveOpacity,+ inactiveScale,+ activeScale,+ });++ return (+ <motion.span+ animate={{+ opacity: hoverStyle.opacity,+ scale: hoverStyle.scale,+ }}+ className="absolute top-0 block"+ initial={{ opacity: 1, scale: 1 }}+ key={level}+ onPointerEnter={() => onEnter(level)}+ onPointerLeave={onLeave}+ style={{+ left: index * segmentWidth,+ width: segmentWidth,+ height: barHeight,+ cursor: isInteractive ? 'pointer' : undefined,+ transformOrigin: 'center center',+ }}+ transition={HEATMAP_INACTIVE_TRANSITION}+ />+ );+ })}+ </div>+ );+});++HeatmapLegendGradient.displayName = 'HeatmapLegendGradient';++export default HeatmapLegendGradient;diff --git a/apps/start/src/components/charts/heatmap/heatmap-legend-swatch.tsx b/apps/start/src/components/charts/heatmap/heatmap-legend-swatch.tsxnew file mode 100644index 000000000..d37619dea--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-legend-swatch.tsx@@ -0,0 +1,76 @@+'use client';++import { memo } from 'react';+import { renderPatternPreset } from '../pattern-preset';+import {+ type HeatmapLevelStyle,+ heatmapLevelPatternId,+ heatmapLevelPatternRenderOptions,+ isHeatmapLevelPattern,+} from './heatmap-colors';++export const HeatmapLegendSwatch = memo(function HeatmapLegendSwatch({+ level,+ style,+ cellSize,+ cornerRadius,+}: {+ level: number;+ style: HeatmapLevelStyle;+ cellSize: number;+ cornerRadius: number;+}) {+ const shellStyle = {+ width: cellSize,+ height: cellSize,+ borderRadius: cornerRadius,+ };++ if (isHeatmapLevelPattern(style) && style.pattern) {+ const patternId = heatmapLevelPatternId(level);+ const patternNode = renderPatternPreset(+ style.pattern,+ patternId,+ heatmapLevelPatternRenderOptions(style)+ );+ const opacity = style.patternOpacity ?? 1;++ return (+ <span+ aria-hidden="true"+ className="block shrink-0 overflow-hidden"+ style={{ ...shellStyle, opacity }}+ >+ <svg+ aria-hidden="true"+ className="block size-full"+ viewBox={`0 0 ${cellSize} ${cellSize}`}+ >+ {patternNode ? <defs>{patternNode}</defs> : null}+ <rect+ fill={patternNode ? `url(#${patternId})` : style.color}+ height={cellSize}+ rx={cornerRadius}+ ry={cornerRadius}+ width={cellSize}+ />+ </svg>+ </span>+ );+ }++ return (+ <span+ aria-hidden="true"+ className="block shrink-0"+ style={{+ ...shellStyle,+ backgroundColor: style.color,+ border: level === 0 ? `1px solid ${style.color}` : undefined,+ boxSizing: 'border-box',+ }}+ />+ );+});++HeatmapLegendSwatch.displayName = 'HeatmapLegendSwatch';diff --git a/apps/start/src/components/charts/heatmap/heatmap-legend.tsx b/apps/start/src/components/charts/heatmap/heatmap-legend.tsxnew file mode 100644index 000000000..a44e23cab--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-legend.tsx@@ -0,0 +1,216 @@+'use client';++import { motion } from 'motion/react';+import { memo, useCallback } from 'react';+import {+ defaultHeatmapColorScale,+ type HeatmapLevelStyles,+} from './heatmap-colors';+import { useHeatmapInteractionOptional } from './heatmap-context';+import { HeatmapLegendGradient } from './heatmap-legend-gradient';+import { HeatmapLegendSwatch } from './heatmap-legend-swatch';+import {+ getHeatmapContributionLevel,+ isHeatmapHoverEffectEnabled,+ resolveHeatmapHoverStyle,+} from './heatmap-utils';+import { cn } from '@/lib/utils';++export const HEATMAP_LEGEND_LEVELS = [0, 1, 2, 3, 4] as const;++const HEATMAP_INACTIVE_OPACITY = 0.3;+/** Smooth tween for inactive opacity + scale on hover. */+const HEATMAP_INACTIVE_TRANSITION = {+ duration: 0.22,+ ease: [0.4, 0, 0.2, 1] as const,+};++export type HeatmapLegendVariant = 'swatches' | 'gradient';++export interface HeatmapLegendProps {+ /** Side label before the swatches. Default: "Less" */+ lessLabel?: string;+ /** Side label after the swatches. Default: "More" */+ moreLabel?: string;+ /** Swatch size in pixels. Default: 11 */+ cellSize?: number;+ /** Gap between swatches. Default: 2 */+ gap?: number;+ /** Corner radius for swatches. Default: 2 */+ cornerRadius?: number;+ /** Horizontal alignment within the legend cell. Default: "end" */+ align?: 'start' | 'center' | 'end';+ /** Legend layout — discrete swatches or a continuous gradient bar. Default: `"swatches"` */+ variant?: HeatmapLegendVariant;+ /** Gradient bar width in swatch units when `variant="gradient"`. Default: 5 */+ gradientSpan?: number;+ /** Font size in pixels for side labels. */+ fontSize?: number;+ /** Additional class name for less/more labels. */+ labelClassName?: string;+ /** Shared level styles for cells and legend swatches. */+ levelStyles?: HeatmapLevelStyles;+ /** Override the default color scale (used when `levelStyles` is omitted). */+ colorScale?: (count: number | null | undefined) => string;+ /** Opacity for inactive swatches while interacting. Default: 0.3 */+ inactiveOpacity?: number;+ /** Scale for inactive swatches while interacting. Default: 1 */+ inactiveScale?: number;+ /** Scale for the highlighted swatch while interacting. Default: 1 */+ activeScale?: number;+ /** Sync dimming with chart hover. Default: true when inside HeatmapInteractionProvider */+ interactive?: boolean;+ className?: string;+}++export const HeatmapLegend = memo(function HeatmapLegend({+ lessLabel = 'Less',+ moreLabel = 'More',+ cellSize = 11,+ gap = 2,+ cornerRadius = 2,+ align = 'end',+ variant = 'swatches',+ gradientSpan = 5,+ fontSize,+ labelClassName,+ levelStyles: levelStylesProp,+ colorScale = defaultHeatmapColorScale,+ inactiveOpacity = HEATMAP_INACTIVE_OPACITY,+ inactiveScale = 1,+ activeScale = 1,+ interactive,+ className,+}: HeatmapLegendProps) {+ const interaction = useHeatmapInteractionOptional();+ const isInteractive = interactive ?? interaction != null;+ const levelStyles =+ levelStylesProp ??+ (HEATMAP_LEGEND_LEVELS.map((level) => ({+ color: colorScale(level),+ fillMode: 'solid' as const,+ pattern: 'none' as const,+ })) as unknown as HeatmapLevelStyles);++ const {+ hoveredLegendLevel,+ tooltipData,+ setHoveredCell,+ setHoveredLegendLevel,+ setTooltipData,+ } = interaction ?? {+ hoveredLegendLevel: null,+ tooltipData: null,+ setHoveredCell: () => undefined,+ setHoveredLegendLevel: () => undefined,+ setTooltipData: () => undefined,+ };++ const highlightedLevel =+ hoveredLegendLevel ??+ (tooltipData ? getHeatmapContributionLevel(tooltipData.count) : null);+ const hoverParams = { inactiveOpacity, inactiveScale, activeScale };+ const inactiveEnabled = isHeatmapHoverEffectEnabled(hoverParams);+ const isDimming =+ isInteractive && highlightedLevel !== null && inactiveEnabled;++ const handleLegendEnter = useCallback(+ (level: number) => {+ if (!isInteractive) {+ return;+ }++ setHoveredLegendLevel(level);+ setHoveredCell(null);+ setTooltipData(null);+ },+ [isInteractive, setHoveredCell, setHoveredLegendLevel, setTooltipData]+ );++ const handleLegendLeave = useCallback(() => {+ if (!isInteractive) {+ return;+ }++ setHoveredLegendLevel(null);+ }, [isInteractive, setHoveredLegendLevel]);++ const labelStyle = fontSize == null ? undefined : { fontSize };++ return (+ <div+ className={cn(+ 'flex w-full items-center gap-1.5 text-chart-label text-xs',+ align === 'start' && 'justify-start',+ align === 'center' && 'justify-center',+ align === 'end' && 'justify-end',+ className+ )}+ style={labelStyle}+ >+ <span className={labelClassName}>{lessLabel}</span>+ {variant === 'gradient' ? (+ <HeatmapLegendGradient+ activeScale={activeScale}+ cellSize={cellSize}+ cornerRadius={cornerRadius}+ gap={gap}+ gradientSpan={gradientSpan}+ highlightedLevel={highlightedLevel}+ inactiveOpacity={inactiveOpacity}+ inactiveScale={inactiveScale}+ isDimming={isDimming}+ isInteractive={isInteractive}+ levelStyles={levelStyles}+ levels={HEATMAP_LEGEND_LEVELS}+ onEnter={handleLegendEnter}+ onLeave={handleLegendLeave}+ />+ ) : (+ <div className="flex items-center" style={{ gap }}>+ {HEATMAP_LEGEND_LEVELS.map((level) => {+ const isHighlighted = highlightedLevel === level;+ const isDimmed = isDimming && !isHighlighted;+ const hoverStyle = resolveHeatmapHoverStyle(+ isHighlighted,+ isDimmed,+ hoverParams+ );+ const style = levelStyles[level];++ return (+ <motion.span+ animate={{+ opacity: hoverStyle.opacity,+ scale: hoverStyle.scale,+ }}+ aria-hidden="true"+ className="block shrink-0 leading-none"+ initial={{ opacity: 1, scale: 1 }}+ key={level}+ onPointerEnter={() => handleLegendEnter(level)}+ onPointerLeave={handleLegendLeave}+ style={{+ cursor: isInteractive ? 'pointer' : undefined,+ }}+ transition={HEATMAP_INACTIVE_TRANSITION}+ >+ <HeatmapLegendSwatch+ cellSize={cellSize}+ cornerRadius={cornerRadius}+ level={level}+ style={style}+ />+ </motion.span>+ );+ })}+ </div>+ )}+ <span className={labelClassName}>{moreLabel}</span>+ </div>+ );+});++HeatmapLegend.displayName = 'HeatmapLegend';++export default HeatmapLegend;diff --git a/apps/start/src/components/charts/heatmap/heatmap-pattern-defs.tsx b/apps/start/src/components/charts/heatmap/heatmap-pattern-defs.tsxnew file mode 100644index 000000000..0dca215a2--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-pattern-defs.tsx@@ -0,0 +1,44 @@+'use client';++import { Fragment, memo } from 'react';+import { renderPatternPreset } from '../pattern-preset';+import {+ type HeatmapLevelStyles,+ heatmapLevelPatternId,+ heatmapLevelPatternRenderOptions,+ isHeatmapLevelPattern,+} from './heatmap-colors';++export const HeatmapPatternDefs = memo(function HeatmapPatternDefs({+ levelStyles,+}: {+ levelStyles: HeatmapLevelStyles;+}) {+ const nodes = levelStyles.flatMap((style, level) => {+ if (!isHeatmapLevelPattern(style)) {+ return [];+ }++ const id = heatmapLevelPatternId(level);+ const pattern = style.pattern;+ if (!pattern) {+ return [];+ }++ const node = renderPatternPreset(+ pattern,+ id,+ heatmapLevelPatternRenderOptions(style)+ );++ return node ? [<Fragment key={id}>{node}</Fragment>] : [];+ });++ if (nodes.length === 0) {+ return null;+ }++ return <defs>{nodes}</defs>;+});++HeatmapPatternDefs.displayName = 'HeatmapPatternDefs';diff --git a/apps/start/src/components/charts/heatmap/heatmap-resolve-separator.ts b/apps/start/src/components/charts/heatmap/heatmap-resolve-separator.tsnew file mode 100644index 000000000..27eb7e50b--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-resolve-separator.ts@@ -0,0 +1,127 @@+import type { ReactElement, ReactNode } from 'react';+import { Children, isValidElement } from 'react';+import { resolveChartChildElement } from '../chart-child-passthrough';+import type { HeatmapColumn } from './heatmap-context';+import {+ HEATMAP_SEPARATOR_MARKER,+ HeatmapSeparator,+} from './heatmap-separator';+import type {+ HeatmapSeparatorGroupBy,+ HeatmapSeparatorLayout,+ HeatmapSeparatorParsedConfig,+} from './heatmap-utils';+import { resolveHeatmapSeparatorLayout } from './heatmap-utils';++function getChildComponentName(child: ReactElement): string {+ const childType = child.type as { displayName?: string; name?: string };+ return typeof child.type === 'function'+ ? childType.displayName || childType.name || ''+ : '';+}++function isHeatmapSeparatorElement(child: ReactElement): boolean {+ const resolved = resolveChartChildElement(child);+ const type = resolved.type as { [HEATMAP_SEPARATOR_MARKER]?: boolean };+ return (+ resolved.type === HeatmapSeparator ||+ type[HEATMAP_SEPARATOR_MARKER] === true ||+ getChildComponentName(resolved) === 'HeatmapSeparator'+ );+}++function readHeatmapSeparatorConfig(+ child: ReactElement+): HeatmapSeparatorParsedConfig | null {+ const props = resolveChartChildElement(child).props as {+ every?: number;+ groupBy?: HeatmapSeparatorGroupBy;+ spacing?: number;+ };+ const groupBy = props.groupBy ?? 'every';++ if (groupBy === 'quarter') {+ return {+ groupBy: 'quarter',+ spacing: props.spacing ?? 0,+ };+ }++ if (props.every == null || props.every <= 0) {+ return null;+ }++ return {+ groupBy: 'every',+ every: props.every,+ spacing: props.spacing ?? 0,+ };+}++/** Reads the first {@link HeatmapSeparator} child for separator config. */+export function resolveHeatmapSeparatorConfig(+ children: ReactNode,+ chartSeparators?: HeatmapSeparatorParsedConfig | null+): HeatmapSeparatorParsedConfig | null {+ let config: HeatmapSeparatorParsedConfig | null = null;++ const visit = (node: ReactNode) => {+ if (config) {+ return;+ }++ Children.forEach(node, (child) => {+ if (config || !isValidElement(child)) {+ return;+ }++ if (isHeatmapSeparatorElement(child)) {+ config = readHeatmapSeparatorConfig(child);+ return;+ }++ const childProps = child.props as { children?: ReactNode } | undefined;+ if (childProps?.children) {+ visit(childProps.children);+ }+ });+ };++ visit(children);+ return config ?? normalizeHeatmapSeparatorConfig(chartSeparators);+}++function normalizeHeatmapSeparatorConfig(+ config?: HeatmapSeparatorParsedConfig | null+): HeatmapSeparatorParsedConfig | null {+ if (!config) {+ return null;+ }++ if (config.groupBy === 'quarter') {+ return {+ groupBy: 'quarter',+ spacing: config.spacing ?? 0,+ };+ }++ if (!config.every || config.every <= 0) {+ return null;+ }++ return {+ groupBy: 'every',+ every: config.every,+ spacing: config.spacing ?? 0,+ };+}++/** Merges chart prop and child-derived config, then resolves column indices from data. */+export function resolveHeatmapSeparatorConfigWithData(+ children: ReactNode,+ columns: HeatmapColumn[],+ chartSeparators?: HeatmapSeparatorParsedConfig | null+): HeatmapSeparatorLayout | null {+ const config = resolveHeatmapSeparatorConfig(children, chartSeparators);+ return resolveHeatmapSeparatorLayout(config, columns);+}diff --git a/apps/start/src/components/charts/heatmap/heatmap-separator.tsx b/apps/start/src/components/charts/heatmap/heatmap-separator.tsxnew file mode 100644index 000000000..4a30a4358--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-separator.tsx@@ -0,0 +1,246 @@+'use client';++import { memo, useEffect, useId, useMemo, useState } from 'react';+import { createPortal } from 'react-dom';+import { useHeatmap } from './heatmap-context';+import {+ buildHeatmapSeparatorGradientStops,+ getHeatmapSeparatorLineY,+ getHeatmapSeparatorX,+ type HeatmapSeparatorGradient,+ type HeatmapSeparatorStrokeStyle,+ resolveHeatmapSeparatorStrokeDasharray,+} from './heatmap-utils';+import { cn } from '@/lib/utils';++/** Marker for reliably identifying {@link HeatmapSeparator} in chart child trees. */+export const HEATMAP_SEPARATOR_MARKER = '__isHeatmapSeparator' as const;++export interface HeatmapSeparatorProps {+ /**+ * Insert a separator before every Nth column (e.g. 4 = divide every four weeks).+ * Used when `groupBy="every"`. When omitted, uses `columnSeparators` from+ * {@link HeatmapChart} or a sibling {@link HeatmapSeparator} parsed for layout.+ */+ every?: number;+ /**+ * Group columns by fixed interval (`every`) or calendar quarter (`quarter`).+ * Default: `"every"`.+ */+ groupBy?: 'every' | 'quarter';+ /** Additional class name for each separator group. */+ className?: string;+ /**+ * Extra horizontal gap between column groups in pixels (shifts cells apart).+ * Parsed from this component by {@link HeatmapChart} for layout. Default: 0+ */+ spacing?: number;+ /** Half-width of the line band in pixels (line is centered). Default: 0 */+ paddingX?: number;+ /** Inset from the bottom of the plot in pixels. Default: 0 */+ paddingY?: number;+ /**+ * Distance from the chart container top to the line start, in pixels.+ * Use to align with {@link HeatmapXAxis} labels (e.g. `14`). The line always+ * extends to the plot bottom. Default: plot top (`margin.top`).+ */+ startOffset?: number;+ /**+ * Distance below the separator line top to place quarter labels.+ * `0` aligns labels with the line top. Default: 0.+ */+ labelOffset?: number;+ /** Draw Q1–Q4 labels at the start of each quarter group. Default: false */+ showLabels?: boolean;+ /** Format quarter group labels. Default: `Q{n}` */+ labelFormat?: (quarter: number, startDate: Date) => string;+ /** Additional class name for quarter labels */+ labelClassName?: string;+ /** Solid or dashed separator line. Default: `"solid"` */+ strokeStyle?: HeatmapSeparatorStrokeStyle;+ /** Dash pattern when `strokeStyle="dashed"`. Default: `"4,4"` */+ strokeDasharray?: string;+ /** Line stroke color when `gradient` is omitted. Default: `var(--border)` */+ stroke?: string;+ /**+ * Vertical stroke gradient aligned to each line's span.+ * Use matching `from`/`via`/`to` colors with fading opacities to soften the+ * top and bottom (e.g. `{ fromOpacity: 0, viaOpacity: 1, toOpacity: 0 }`).+ */+ gradient?: HeatmapSeparatorGradient;+ /** Line stroke width in pixels. Default: 1 */+ strokeWidth?: number;+ /** Multiplier applied to solid strokes or gradient stop opacities. Default: 1 */+ strokeOpacity?: number;+}++export const HeatmapSeparator = memo(function HeatmapSeparator({+ className,+ paddingX = 0,+ paddingY = 0,+ startOffset,+ labelOffset = 0,+ showLabels = false,+ labelFormat = (quarter) => `Q${quarter}`,+ labelClassName,+ strokeStyle = 'solid',+ strokeDasharray,+ stroke = 'var(--border)',+ gradient,+ strokeWidth = 1,+ strokeOpacity = 1,+}: HeatmapSeparatorProps) {+ const { gap, innerHeight, margin, separatorLayout, xScale, containerRef } =+ useHeatmap();++ const [mounted, setMounted] = useState(false);+ const reactId = useId().replace(/:/g, '');+ const gradientId = `heatmap-separator-gradient-${reactId}`;++ useEffect(() => {+ setMounted(true);+ }, []);++ const separators = useMemo(() => {+ if (!separatorLayout) {+ return [];+ }++ return separatorLayout.atColumns.map((columnIndex) => ({+ columnIndex,+ x: getHeatmapSeparatorX(columnIndex, gap, separatorLayout, xScale),+ }));+ }, [gap, separatorLayout, xScale]);++ const labels = useMemo(() => {+ if (!(showLabels && separatorLayout?.groups.length)) {+ return [];+ }++ return separatorLayout.groups.map((group) => ({+ key: `${group.year}-Q${group.quarter}-${group.startColumnIndex}`,+ label: labelFormat(group.quarter, group.startDate),+ x: margin.left + xScale(group.startColumnIndex),+ }));+ }, [labelFormat, margin.left, separatorLayout, showLabels, xScale]);++ if (!separatorLayout) {+ return null;+ }++ const { y1: lineY1, y2: lineY2 } = getHeatmapSeparatorLineY({+ innerHeight,+ marginTop: margin.top,+ startOffset,+ paddingY,+ });++ const separatorTop = startOffset ?? margin.top;+ const labelTop = separatorTop + labelOffset;+ const resolvedStroke = gradient ? `url(#${gradientId})` : stroke;+ const resolvedStrokeDasharray = resolveHeatmapSeparatorStrokeDasharray(+ strokeStyle,+ strokeDasharray+ );+ const gradientStops = gradient+ ? buildHeatmapSeparatorGradientStops(gradient, strokeOpacity)+ : null;++ const container = containerRef.current;+ const labelPortal =+ mounted && container && labels.length > 0+ ? createPortal(+ labels.map((tick) => (+ <div+ className="pointer-events-none absolute"+ key={tick.key}+ style={{+ top: labelTop,+ left: tick.x,+ width: 0,+ display: 'flex',+ justifyContent: 'flex-start',+ }}+ >+ <span+ className={cn(+ 'whitespace-nowrap text-chart-label text-xs',+ labelClassName+ )}+ >+ {tick.label}+ </span>+ </div>+ )),+ container+ )+ : null;++ if (separators.length === 0) {+ return labelPortal;+ }++ return (+ <>+ {gradientStops ? (+ <defs>+ <linearGradient+ gradientUnits="userSpaceOnUse"+ id={gradientId}+ x1={0}+ x2={0}+ y1={lineY1}+ y2={lineY2}+ >+ {gradientStops.map((stop) => (+ <stop+ key={stop.offset}+ offset={stop.offset}+ stopColor={stop.color}+ stopOpacity={stop.opacity}+ />+ ))}+ </linearGradient>+ </defs>+ ) : null}+ <g>+ {separators.map((separator) => (+ <g+ className={cn(className)}+ key={separator.columnIndex}+ transform={`translate(${separator.x}, 0)`}+ >+ {paddingX > 0 ? (+ <rect+ fill="transparent"+ height={lineY2 - lineY1}+ width={paddingX * 2}+ x={-paddingX}+ y={lineY1}+ />+ ) : null}+ <line+ stroke={resolvedStroke}+ strokeDasharray={resolvedStrokeDasharray}+ strokeOpacity={gradient ? undefined : strokeOpacity}+ strokeWidth={strokeWidth}+ x1={0}+ x2={0}+ y1={lineY1}+ y2={lineY2}+ />+ </g>+ ))}+ </g>+ {labelPortal}+ </>+ );+});++(HeatmapSeparator as unknown as Record<string, boolean>)[+ HEATMAP_SEPARATOR_MARKER+] = true;++HeatmapSeparator.displayName = 'HeatmapSeparator';++export default HeatmapSeparator;diff --git a/apps/start/src/components/charts/heatmap/heatmap-tooltip.tsx b/apps/start/src/components/charts/heatmap/heatmap-tooltip.tsxnew file mode 100644index 000000000..284e11244--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-tooltip.tsx@@ -0,0 +1,90 @@+'use client';++import { memo } from 'react';+import { TooltipBox } from '../tooltip/tooltip-box';+import { TooltipHeader } from '../tooltip/tooltip-content';+import { useHeatmap, useHeatmapInteraction } from './heatmap-context';+import {+ formatHeatmapContributionLabel,+ formatHeatmapTooltipDate,+ formatHeatmapTooltipWeekday,+} from './heatmap-utils';+import { useDelayedTooltipData } from './use-delayed-tooltip-data';++export interface HeatmapTooltipProps {+ /** Custom contribution line (bottom section). Default: `N contribution(s)`. */+ formatLabel?: (count: number, date: Date) => string;+ /** Custom class name */+ className?: string;+ /** Inline styles for the tooltip panel (background, blur, etc.). */+ panelStyle?: React.CSSProperties;+ /**+ * Tooltip panel background color (CSS variable or color value).+ * Default: `var(--chart-tooltip-background)`.+ */+ backgroundColor?: string;+ /**+ * Delay before showing the tooltip on first hover (ms).+ * Moving between cells updates immediately once visible.+ */+ showDelay?: number;+ /**+ * Grace period before hiding when the pointer leaves a cell (ms).+ * Helps avoid flicker when moving quickly between adjacent cells.+ */+ hideDelay?: number;+ /**+ * When true, the tooltip appears and disappears instantly with no motion.+ */+ instant?: boolean;+}++export const HeatmapTooltip = memo(function HeatmapTooltip({+ formatLabel = formatHeatmapContributionLabel,+ className = '',+ panelStyle,+ backgroundColor,+ showDelay = 0,+ hideDelay = 120,+ instant = false,+}: HeatmapTooltipProps) {+ const { containerRef, width, height } = useHeatmap();+ const { tooltipData } = useHeatmapInteraction();+ const displayData = useDelayedTooltipData(tooltipData, showDelay, hideDelay);++ if (!displayData) {+ return null;+ }++ const { count, date } = displayData;++ return (+ <TooltipBox+ animate={false}+ backgroundColor={backgroundColor}+ className={className}+ containerHeight={height}+ containerRef={containerRef}+ containerWidth={width}+ entrance={!instant}+ panelStyle={panelStyle}+ visible+ x={displayData.x}+ y={displayData.y}+ >+ <TooltipHeader>+ {formatHeatmapTooltipDate(date)}+ <div className="mt-0.5 font-normal text-chart-tooltip-muted text-xs">+ {formatHeatmapTooltipWeekday(date)}+ </div>+ </TooltipHeader>+ <div className="px-3.5 py-3 text-left text-chart-tooltip-foreground text-sm">+ {formatLabel(count, date)}+ </div>+ </TooltipBox>+ );+});++HeatmapTooltip.displayName = 'HeatmapTooltip';++export default HeatmapTooltip;diff --git a/apps/start/src/components/charts/heatmap/heatmap-utils.ts b/apps/start/src/components/charts/heatmap/heatmap-utils.tsnew file mode 100644index 000000000..21e2c9cba--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-utils.ts@@ -0,0 +1,955 @@+import type { HeatmapLevelStyles } from './heatmap-colors';+import type { HeatmapBin, HeatmapColumn } from './heatmap-context';++/** Calendar months shown in default one-year contribution grids. */+export const HEATMAP_MONTHS_ONE_YEAR = 12;++/** Half-year contribution grids (gallery card demos). */+export const HEATMAP_MONTHS_SIX = 6;++/** Nominal week count for one year (~52). Default data uses calendar-month math instead. */+export const HEATMAP_WEEKS_ONE_YEAR = 52;++const MS_PER_DAY = 24 * 60 * 60 * 1000;+const MS_PER_WEEK = MS_PER_DAY * 7;++export function getHeatmapCalendarRangeStart(+ today: Date,+ months: number+): Date {+ const monthOffset = months === HEATMAP_MONTHS_SIX ? months : months - 1;+ const start = new Date(+ today.getFullYear(),+ today.getMonth() - monthOffset,+ 1+ );+ start.setHours(0, 0, 0, 0);+ return start;+}++export function getHeatmapYearStartMonth(today: Date): Date {+ return getHeatmapCalendarRangeStart(today, HEATMAP_MONTHS_ONE_YEAR);+}++export function getHeatmapWeekStartSunday(date: Date): Date {+ const sunday = new Date(date);+ sunday.setDate(sunday.getDate() - sunday.getDay());+ sunday.setHours(0, 0, 0, 0);+ return sunday;+}++export function getHeatmapWeekCount(startSunday: Date, endDate: Date): number {+ const endSunday = getHeatmapWeekStartSunday(endDate);+ return (+ Math.floor((endSunday.getTime() - startSunday.getTime()) / MS_PER_WEEK) + 1+ );+}++/** Days in a Sun–Sat column on or after `threshold` (for trimming partial lead weeks). */+export function countHeatmapWeekDaysOnOrAfter(+ weekStart: Date,+ threshold: Date+): number {+ const day = new Date(weekStart);+ day.setHours(0, 0, 0, 0);+ const cutoff = new Date(threshold);+ cutoff.setHours(0, 0, 0, 0);+ let count = 0;++ for (let i = 0; i < 7; i++) {+ if (day >= cutoff) {+ count++;+ }+ day.setDate(day.getDate() + 1);+ }++ return count;+}++/**+ * First Sunday week column where enough days fall on/after `rangeStart`.+ * Skips a lead week that is mostly before the range (e.g. late July before Aug 1).+ */+export function getHeatmapWeekStartAlignedToRange(+ rangeStart: Date,+ minDaysInFirstWeek = 4+): Date {+ const startDate = getHeatmapWeekStartSunday(rangeStart);+ const weekEnd = new Date(startDate);+ weekEnd.setDate(weekEnd.getDate() + 6);++ // Keep the Sun–Sat column that contains the 1st (e.g. Jan 1 in a partial lead week).+ if (rangeStart >= startDate && rangeStart <= weekEnd) {+ return startDate;+ }++ while (+ countHeatmapWeekDaysOnOrAfter(startDate, rangeStart) < minDaysInFirstWeek+ ) {+ startDate.setDate(startDate.getDate() + 7);+ }++ return startDate;+}++/** Column index for a month label — snaps to separator group start when layout is set. */+export function getHeatmapMonthLabelColumnIndex(+ columnIndex: number,+ separatorLayout: Pick<HeatmapSeparatorLayout, 'atColumns'> | null+): number {+ if (!separatorLayout?.atColumns.length) {+ return columnIndex;+ }++ return getHeatmapSeparatorGroupStartColumn(+ columnIndex,+ separatorLayout.atColumns+ );+}++export interface HeatmapWeekRange {+ startDate: Date;+ weekCount: number;+ /** First in-range calendar day; bins before this are empty in default year grids. */+ rangeStart: Date | null;+}++/** Default `weeks` uses 12 calendar months; other values use a rolling week window. */+export function resolveHeatmapWeekRange(+ today: Date,+ weeks: number = HEATMAP_WEEKS_ONE_YEAR+): HeatmapWeekRange {+ const endDate = new Date(today);+ endDate.setHours(0, 0, 0, 0);++ if (weeks === HEATMAP_WEEKS_ONE_YEAR) {+ const rangeStart = getHeatmapYearStartMonth(endDate);+ const startDate = getHeatmapWeekStartAlignedToRange(rangeStart);+ return {+ startDate,+ weekCount: getHeatmapWeekCount(startDate, endDate),+ rangeStart,+ };+ }++ const startDate = new Date(endDate);+ startDate.setDate(startDate.getDate() - (weeks - 1) * 7);+ startDate.setDate(startDate.getDate() - startDate.getDay());+ startDate.setHours(0, 0, 0, 0);++ return {+ startDate,+ weekCount: weeks,+ rangeStart: null,+ };+}++/** Month label anchor for a week column — prefers the 1st, else the 1st of the first bin's month. */+export function getHeatmapColumnMonthAnchor(+ column: HeatmapColumn+): Date | null {+ for (const bin of column.bins) {+ if (bin.date && bin.date.getDate() === 1) {+ return bin.date;+ }+ }++ const firstDate = column.bins[0]?.date;+ if (!firstDate) {+ return null;+ }++ return new Date(firstDate.getFullYear(), firstDate.getMonth(), 1);+}++export function getHeatmapColumnStartDate(column: HeatmapColumn): Date | null {+ return column.bins[0]?.date ?? null;+}++export function getHeatmapColumnEndDate(column: HeatmapColumn): Date | null {+ const lastBin = column.bins.at(-1);+ return lastBin?.date ?? null;+}++export function getHeatmapTimeExtent(+ columns: HeatmapColumn[]+): [Date, Date] | null {+ if (columns.length === 0) {+ return null;+ }++ const firstColumn = columns[0];+ if (!firstColumn) {+ return null;+ }+ const start = getHeatmapColumnStartDate(firstColumn);+ const lastColumn = columns.at(-1);+ if (!lastColumn) {+ return null;+ }+ const end = getHeatmapColumnEndDate(lastColumn);+ if (!(start && end)) {+ return null;+ }++ return [start, end];+}++export function filterHeatmapColumns(+ columns: HeatmapColumn[],+ xDomain?: [Date, Date]+): HeatmapColumn[] {+ if (!xDomain) {+ return columns;+ }++ const start = Math.min(xDomain[0].getTime(), xDomain[1].getTime());+ const end = Math.max(xDomain[0].getTime(), xDomain[1].getTime());++ return columns.filter((column) => {+ const weekStart = getHeatmapColumnStartDate(column)?.getTime();+ const weekEnd = getHeatmapColumnEndDate(column)?.getTime();+ if (weekStart == null || weekEnd == null) {+ return false;+ }+ return weekEnd >= start && weekStart <= end;+ });+}++const heatmapTooltipMonthFmt = new Intl.DateTimeFormat('en-US', {+ month: 'long',+});++const heatmapTooltipWeekdayFmt = new Intl.DateTimeFormat('en-US', {+ weekday: 'long',+});++function formatHeatmapOrdinalDay(day: number): string {+ if (day >= 11 && day <= 13) {+ return `${day}th`;+ }++ switch (day % 10) {+ case 1:+ return `${day}st`;+ case 2:+ return `${day}nd`;+ case 3:+ return `${day}rd`;+ default:+ return `${day}th`;+ }+}++/** Tooltip header date — e.g. `January 20th 2026`. */+export function formatHeatmapTooltipDate(date: Date): string {+ const month = heatmapTooltipMonthFmt.format(date);+ const day = formatHeatmapOrdinalDay(date.getDate());+ return `${month} ${day} ${date.getFullYear()}`;+}++/** Tooltip weekday line — e.g. `Monday`. */+export function formatHeatmapTooltipWeekday(date: Date): string {+ return heatmapTooltipWeekdayFmt.format(date);+}++/** Tooltip contribution line — e.g. `3 contributions`. */+export function formatHeatmapContributionLabel(+ count: number,+ _date?: Date+): string {+ const word = count === 1 ? 'contribution' : 'contributions';+ return `${count} ${word}`;+}++/** Sunday-first day labels for heatmap row bins. */+export const HEATMAP_DAY_LABELS = [+ 'Sun',+ 'Mon',+ 'Tue',+ 'Wed',+ 'Thu',+ 'Fri',+ 'Sat',+] as const;++/** First row of the grid — `0` = Sunday (GitHub default). */+export type HeatmapWeekStartDay = 0 | 1 | 2 | 3 | 4 | 5 | 6;++/** Day labels with row 0 aligned to `weekStartDay`. */+export function getHeatmapDayLabels(+ weekStartDay: HeatmapWeekStartDay = 0+): readonly string[] {+ if (weekStartDay === 0) {+ return HEATMAP_DAY_LABELS;+ }++ return [+ ...HEATMAP_DAY_LABELS.slice(weekStartDay),+ ...HEATMAP_DAY_LABELS.slice(0, weekStartDay),+ ];+}++/** Rotates Sun-first column bins so display row 0 starts on `weekStartDay`. */+export function rotateHeatmapColumnBins(+ columns: HeatmapColumn[],+ weekStartDay: HeatmapWeekStartDay = 0+): HeatmapColumn[] {+ if (weekStartDay === 0) {+ return columns;+ }++ return columns.map((column) => ({+ ...column,+ bins: [+ ...column.bins.slice(weekStartDay),+ ...column.bins.slice(0, weekStartDay),+ ],+ }));+}++/** Which Y-axis row ticks to display. */+export type HeatmapYAxisTickFilter = 'all' | 'odd' | 'even';++/** Y-axis label display — `initial` shows the first letter only (Mon → M). */+export type HeatmapYAxisLabelFormat = 'full' | 'initial';++export function formatHeatmapYAxisLabel(+ label: string,+ labelFormat: HeatmapYAxisLabelFormat+): string {+ return labelFormat === 'initial' ? label.charAt(0) : label;+}++export function shouldShowHeatmapYAxisTick(+ row: number,+ tickFilter: HeatmapYAxisTickFilter+): boolean {+ switch (tickFilter) {+ case 'all':+ return true;+ case 'odd':+ return row % 2 === 1;+ case 'even':+ return row % 2 === 0;+ default:+ return row % 2 === 1;+ }+}++/** Layout spacing parsed from {@link HeatmapSeparator}. */+export type HeatmapSeparatorGroupBy = 'every' | 'quarter';++/** Separator config from props — resolved to column indices once data is known. */+export interface HeatmapSeparatorParsedConfig {+ groupBy: HeatmapSeparatorGroupBy;+ every?: number;+ spacing: number;+}++export interface HeatmapSeparatorGroup {+ startColumnIndex: number;+ quarter: number;+ year: number;+ startDate: Date;+ label: string;+}++/** Resolved separator layout used for column offsets and rendering. */+export interface HeatmapSeparatorLayout {+ spacing: number;+ atColumns: number[];+ groups: HeatmapSeparatorGroup[];+}++/** Separator line style. */+export type HeatmapSeparatorStrokeStyle = 'solid' | 'dashed';++/** Vertical stroke gradient for separator lines (`from` → optional `via` → `to`). */+export interface HeatmapSeparatorGradient {+ from: string;+ via?: string;+ to: string;+ fromOpacity?: number;+ viaOpacity?: number;+ toOpacity?: number;+}++export interface HeatmapSeparatorGradientStop {+ offset: string;+ color: string;+ opacity: number;+}++/** Builds SVG gradient stops for a vertical separator line. */+export function buildHeatmapSeparatorGradientStops(+ gradient: HeatmapSeparatorGradient,+ strokeOpacity = 1+): HeatmapSeparatorGradientStop[] {+ const scaleOpacity = (value: number | undefined, fallback = 1) =>+ (value ?? fallback) * strokeOpacity;++ if (gradient.via != null) {+ return [+ {+ offset: '0%',+ color: gradient.from,+ opacity: scaleOpacity(gradient.fromOpacity),+ },+ {+ offset: '50%',+ color: gradient.via,+ opacity: scaleOpacity(gradient.viaOpacity),+ },+ {+ offset: '100%',+ color: gradient.to,+ opacity: scaleOpacity(gradient.toOpacity),+ },+ ];+ }++ return [+ {+ offset: '0%',+ color: gradient.from,+ opacity: scaleOpacity(gradient.fromOpacity),+ },+ {+ offset: '100%',+ color: gradient.to,+ opacity: scaleOpacity(gradient.toOpacity),+ },+ ];+}++export function resolveHeatmapSeparatorStrokeDasharray(+ strokeStyle: HeatmapSeparatorStrokeStyle = 'solid',+ strokeDasharray?: string+): string | undefined {+ if (strokeStyle !== 'dashed') {+ return undefined;+ }+ return strokeDasharray ?? '4,4';+}++/** Calendar quarter (1–4) for Jan–Mar, Apr–Jun, Jul–Sep, Oct–Dec. */+export function getCalendarQuarter(date: Date): number {+ return Math.floor(date.getMonth() / 3) + 1;+}++const CALENDAR_QUARTER_START_MONTHS = [0, 3, 6, 9] as const;++/** Jan/Apr/Jul/Oct 1 dates strictly after `gridStart` and on or before `gridEnd`. */+export function getCalendarQuarterStartDatesBetween(+ gridStart: Date,+ gridEnd: Date+): Date[] {+ const startTime = gridStart.getTime();+ const endTime = gridEnd.getTime();+ const dates: Date[] = [];++ for (+ let year = gridStart.getFullYear();+ year <= gridEnd.getFullYear();+ year+++ ) {+ for (const month of CALENDAR_QUARTER_START_MONTHS) {+ const date = new Date(year, month, 1);+ date.setHours(0, 0, 0, 0);+ const time = date.getTime();+ if (time > startTime && time <= endTime) {+ dates.push(date);+ }+ }+ }++ return dates;+}++/** Week column index whose Sun–Sat span contains `date`. */+export function findHeatmapColumnIndexForDate(+ columns: HeatmapColumn[],+ date: Date+): number | null {+ const target = new Date(date);+ target.setHours(0, 0, 0, 0);+ const targetTime = target.getTime();++ for (let columnIndex = 0; columnIndex < columns.length; columnIndex++) {+ const column = columns[columnIndex];+ if (!column) {+ continue;+ }++ const weekStart = getHeatmapColumnStartDate(column);+ const weekEnd = getHeatmapColumnEndDate(column);+ if (!(weekStart && weekEnd)) {+ continue;+ }++ weekStart.setHours(0, 0, 0, 0);+ weekEnd.setHours(0, 0, 0, 0);+ if (targetTime >= weekStart.getTime() && targetTime <= weekEnd.getTime()) {+ return columnIndex;+ }+ }++ return null;+}++/** Quarter anchor for a week column — prefers the 1st of a quarter month, else the quarter of the first bin. */+export function getHeatmapColumnQuarterAnchor(column: HeatmapColumn): {+ quarter: number;+ year: number;+ date: Date;+} | null {+ for (const bin of column.bins) {+ if (!bin.date) {+ continue;+ }+ const month = bin.date.getMonth();+ if (bin.date.getDate() === 1 && month % 3 === 0) {+ return {+ quarter: month / 3 + 1,+ year: bin.date.getFullYear(),+ date: bin.date,+ };+ }+ }++ const firstDate = column.bins[0]?.date;+ if (!firstDate) {+ return null;+ }++ const quarter = getCalendarQuarter(firstDate);+ return {+ quarter,+ year: firstDate.getFullYear(),+ date: new Date(firstDate.getFullYear(), (quarter - 1) * 3, 1),+ };+}++/** Label column snapped to the start of a separator group. */+export function getHeatmapSeparatorGroupStartColumn(+ columnIndex: number,+ atColumns: number[]+): number {+ let groupStart = 0;++ for (const start of atColumns) {+ if (start <= columnIndex) {+ groupStart = start;+ } else {+ break;+ }+ }++ return groupStart;+}++/** Column indices (0-based) where a vertical separator is drawn (fixed interval). */+export function getHeatmapSeparatorColumnIndices(+ columnCount: number,+ every: number+): number[] {+ if (every <= 0 || columnCount <= every) {+ return [];+ }++ const indices: number[] = [];+ for (+ let columnIndex = every;+ columnIndex < columnCount;+ columnIndex += every+ ) {+ indices.push(columnIndex);+ }+ return indices;+}++/** Matches demo-style calendar grids to their range start (Jan 1, etc.). */+export function inferHeatmapCalendarRangeStart(+ columns: HeatmapColumn[]+): Date | null {+ const firstColumn = columns[0];+ if (!firstColumn) {+ return null;+ }++ const gridStart = getHeatmapColumnStartDate(firstColumn);+ if (!gridStart) {+ return null;+ }++ const today = new Date();+ today.setHours(0, 0, 0, 0);++ for (const months of [HEATMAP_MONTHS_SIX, HEATMAP_MONTHS_ONE_YEAR]) {+ const rangeStart = getHeatmapCalendarRangeStart(today, months);+ const alignedStart = getHeatmapWeekStartAlignedToRange(rangeStart);+ if (gridStart.getTime() === alignedStart.getTime()) {+ return rangeStart;+ }+ }++ return null;+}++export function buildHeatmapQuarterSeparatorGroups(+ columns: HeatmapColumn[]+): HeatmapSeparatorGroup[] {+ if (columns.length === 0) {+ return [];+ }++ const extent = getHeatmapTimeExtent(columns);+ if (!extent) {+ return [];+ }++ const [extentStart, gridEnd] = extent;+ const displayRange = resolveHeatmapDisplayRange(columns);+ const quarterRangeStart =+ displayRange.start ??+ inferHeatmapCalendarRangeStart(columns) ??+ extentStart;+ const firstQuarter = getCalendarQuarter(quarterRangeStart);++ const groups: HeatmapSeparatorGroup[] = [+ {+ startColumnIndex: 0,+ quarter: firstQuarter,+ year: quarterRangeStart.getFullYear(),+ startDate: quarterRangeStart,+ label: `Q${firstQuarter}`,+ },+ ];++ const usedColumns = new Set<number>([0]);+ const quarterStarts = getCalendarQuarterStartDatesBetween(+ quarterRangeStart,+ gridEnd+ );++ for (const quarterStart of quarterStarts) {+ const columnIndex = findHeatmapColumnIndexForDate(columns, quarterStart);+ if (+ columnIndex == null ||+ columnIndex === 0 ||+ usedColumns.has(columnIndex)+ ) {+ continue;+ }++ usedColumns.add(columnIndex);+ const quarter = getCalendarQuarter(quarterStart);+ groups.push({+ startColumnIndex: columnIndex,+ quarter,+ year: quarterStart.getFullYear(),+ startDate: quarterStart,+ label: `Q${quarter}`,+ });+ }++ groups.sort((a, b) => a.startColumnIndex - b.startColumnIndex);+ return groups;+}++export function resolveHeatmapSeparatorLayout(+ config: HeatmapSeparatorParsedConfig | null,+ columns: HeatmapColumn[]+): HeatmapSeparatorLayout | null {+ if (!config) {+ return null;+ }++ if (config.groupBy === 'quarter') {+ const groups = buildHeatmapQuarterSeparatorGroups(columns);+ if (groups.length === 0) {+ return null;+ }++ return {+ spacing: config.spacing,+ atColumns: groups+ .map((group) => group.startColumnIndex)+ .filter((columnIndex) => columnIndex > 0),+ groups,+ };+ }++ if (!config.every || config.every <= 0) {+ return null;+ }++ const atColumns = getHeatmapSeparatorColumnIndices(+ columns.length,+ config.every+ );++ return {+ spacing: config.spacing,+ atColumns,+ groups: [],+ };+}++export function getHeatmapSeparatorCount(+ separator: Pick<HeatmapSeparatorLayout, 'atColumns'> | null+): number {+ return separator?.atColumns.length ?? 0;+}++/** Extra x-offset for a column when separator spacing is enabled. */+export function getHeatmapColumnXOffset(+ columnIndex: number,+ separator: Pick<HeatmapSeparatorLayout, 'spacing' | 'atColumns'> | null+): number {+ if (!separator || separator.spacing <= 0) {+ return 0;+ }+ if (columnIndex <= 0) {+ return 0;+ }++ const separatorCount = separator.atColumns.filter(+ (atColumn) => atColumn <= columnIndex+ ).length;+ return separatorCount * separator.spacing;+}++export function getHeatmapPlotInnerWidth(+ columnCount: number,+ binWidth: number,+ separator: Pick<HeatmapSeparatorLayout, 'spacing' | 'atColumns'> | null+): number {+ const separatorCount = separator ? getHeatmapSeparatorCount(separator) : 0;+ return columnCount * binWidth + separatorCount * (separator?.spacing ?? 0);+}++/** Vertical span for a separator line in plot coordinates. */+export function getHeatmapSeparatorLineY({+ innerHeight,+ marginTop,+ startOffset,+ paddingY = 0,+}: {+ innerHeight: number;+ marginTop: number;+ /** Distance from the chart container top to the line start. Default: plot top. */+ startOffset?: number;+ paddingY?: number;+}): { y1: number; y2: number } {+ const resolvedStart = startOffset ?? marginTop;+ const y1 = resolvedStart - marginTop + paddingY;+ const y2 = Math.max(innerHeight - paddingY, y1);+ return { y1, y2 };+}++/** X position for a separator line (centered in the gutter when spacing > 0). */+export function getHeatmapSeparatorX(+ columnIndex: number,+ gap: number,+ separator: Pick<HeatmapSeparatorLayout, 'spacing'>,+ xScale: (columnIndex: number) => number+): number {+ if (separator.spacing > 0) {+ return xScale(columnIndex) - separator.spacing / 2;+ }+ return xScale(columnIndex) - gap / 2;+}++export interface HeatmapDisplayRange {+ start: Date | null;+ end: Date | null;+}++/** Whether a bin falls outside the contribution display window (not merely inactive). */+export function isHeatmapGhostBin(+ bin: HeatmapBin,+ range: HeatmapDisplayRange+): boolean {+ const time = bin.date.getTime();+ if (range.end && time > range.end.getTime()) {+ return true;+ }+ if (range.start && time < range.start.getTime()) {+ return true;+ }+ return false;+}++/**+ * Infers GitHub-style display range for calendar-month contribution grids.+ * Custom data that does not match a known grid shape returns null bounds (show all).+ */+export function resolveHeatmapDisplayRange(+ columns: HeatmapColumn[]+): HeatmapDisplayRange {+ if (columns.length === 0) {+ return { start: null, end: null };+ }++ const extent = getHeatmapTimeExtent(columns);+ if (!extent) {+ return { start: null, end: null };+ }++ const today = new Date();+ today.setHours(0, 0, 0, 0);++ const firstColumn = columns[0];+ if (!firstColumn) {+ return { start: null, end: null };+ }++ const gridStart = getHeatmapColumnStartDate(firstColumn);+ if (!gridStart) {+ return { start: null, end: null };+ }++ const inferredStart = inferHeatmapCalendarRangeStart(columns);++ if (inferredStart && extent[1].getTime() >= today.getTime()) {+ return { start: inferredStart, end: today };+ }++ return { start: null, end: null };+}++/** Maps a contribution count to the GitHub-style legend level (0–4). */+export function getHeatmapContributionLevel(count: number): number {+ if (count <= 0) {+ return 0;+ }+ if (count === 1) {+ return 1;+ }+ if (count === 2) {+ return 2;+ }+ if (count === 3) {+ return 3;+ }+ return 4;+}++export interface HeatmapHoverStyleParams {+ inactiveOpacity: number;+ inactiveScale: number;+ activeScale: number;+}++/** Whether hover styling runs (disabled when all scale/opacity props are 1). */+export function isHeatmapHoverEffectEnabled(+ params: HeatmapHoverStyleParams+): boolean {+ return (+ params.inactiveOpacity !== 1 ||+ params.inactiveScale !== 1 ||+ params.activeScale !== 1+ );+}++/** Whether inactive hover styling runs (disabled when both props are 1). */+export function isHeatmapInactiveEffectEnabled(+ inactiveOpacity: number,+ inactiveScale: number+): boolean {+ return isHeatmapHoverEffectEnabled({+ inactiveOpacity,+ inactiveScale,+ activeScale: 1,+ });+}++/** Opacity and scale for highlighted vs dimmed cells and legend swatches. */+export function resolveHeatmapHoverStyle(+ isHighlighted: boolean,+ isDimmed: boolean,+ params: HeatmapHoverStyleParams+): { opacity: number; scale: number } {+ if (isHighlighted && params.activeScale !== 1) {+ return { opacity: 1, scale: params.activeScale };+ }++ if (isDimmed) {+ return {+ opacity: params.inactiveOpacity,+ scale: params.inactiveScale,+ };+ }++ return { opacity: 1, scale: 1 };+}++/** Opacity and scale for an inactive cell or legend swatch. */+export function resolveHeatmapInactiveStyle(+ isInactive: boolean,+ inactiveOpacity: number,+ inactiveScale: number+): { opacity: number; scale: number } {+ return resolveHeatmapHoverStyle(false, isInactive, {+ inactiveOpacity,+ inactiveScale,+ activeScale: 1,+ });+}++/** Per-row opacity multiplier for display rows (default 1). */+export function resolveHeatmapRowOpacity(+ row: number,+ rowOpacity?: number | readonly number[]+): number {+ if (rowOpacity == null) {+ return 1;+ }++ if (typeof rowOpacity === 'number') {+ return rowOpacity;+ }++ return rowOpacity[row] ?? 1;+}++/**+ * Builds a per-row opacity map for {@link HeatmapCells} and {@link HeatmapYAxis}.+ * Pass explicit row indices (e.g. `[5, 6]` for display Sat/Sun when `weekStartDay={1}`)+ * or a predicate — `(row) => row >= 5` fades the last two rows.+ */+export function buildHeatmapRowOpacity(+ match: readonly number[] | ((row: number) => boolean),+ fadedOpacity = 0.35,+ activeOpacity = 1,+ rowCount = 7+): number[] {+ if (typeof match === 'function') {+ return Array.from({ length: rowCount }, (_, row) =>+ match(row) ? fadedOpacity : activeOpacity+ );+ }++ const opacity = new Array<number>(rowCount).fill(activeOpacity);+ for (const row of match) {+ if (row >= 0 && row < rowCount) {+ opacity[row] = fadedOpacity;+ }+ }+ return opacity;+}++/** CSS `linear-gradient` for a continuous legend bar from level styles. */+export function buildHeatmapLegendGradient(+ levelStyles: HeatmapLevelStyles+): string {+ const lastIndex = levelStyles.length - 1;+ const stops = levelStyles.map((style, index) => {+ const offset = lastIndex === 0 ? 0 : (index / lastIndex) * 100;+ return `${style.color} ${offset}%`;+ });++ return `linear-gradient(to right, ${stops.join(', ')})`;+}diff --git a/apps/start/src/components/charts/heatmap/heatmap-x-axis.tsx b/apps/start/src/components/charts/heatmap/heatmap-x-axis.tsxnew file mode 100644index 000000000..642619766--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-x-axis.tsx@@ -0,0 +1,91 @@+'use client';++import { memo, useEffect, useMemo, useState } from 'react';+import { createPortal } from 'react-dom';+import { useHeatmap } from './heatmap-context';+import { getHeatmapColumnMonthAnchor } from './heatmap-utils';+import { cn } from '@/lib/utils';++export interface HeatmapXAxisProps {+ /** Additional class name for labels */+ className?: string;+}++const monthFmt = new Intl.DateTimeFormat('en-US', { month: 'short' });++export const HeatmapXAxis = memo(function HeatmapXAxis({+ className,+}: HeatmapXAxisProps) {+ const { containerRef, data, margin, xScale } = useHeatmap();+ const [mounted, setMounted] = useState(false);++ useEffect(() => {+ setMounted(true);+ }, []);++ const labels = useMemo(() => {+ const ticks: { label: string; x: number; key: string }[] = [];+ let lastMonthKey = '';++ for (let columnIndex = 0; columnIndex < data.length; columnIndex++) {+ const column = data[columnIndex];+ if (!column) {+ continue;+ }++ const monthAnchor = getHeatmapColumnMonthAnchor(column);+ if (!monthAnchor) {+ continue;+ }++ const monthKey = `${monthAnchor.getFullYear()}-${monthAnchor.getMonth()}`;+ if (monthKey === lastMonthKey) {+ continue;+ }++ ticks.push({+ label: monthFmt.format(monthAnchor),+ x: margin.left + xScale(columnIndex),+ key: monthKey,+ });+ lastMonthKey = monthKey;+ }++ return ticks;+ }, [data, margin.left, xScale]);++ const container = containerRef.current;+ if (!(mounted && container)) {+ return null;+ }++ return createPortal(+ labels.map((tick) => (+ <div+ className="pointer-events-none absolute"+ key={tick.key}+ style={{+ top: 0,+ left: tick.x,+ width: 0,+ display: 'flex',+ justifyContent: 'flex-start',+ }}+ >+ <span+ className={cn(+ 'whitespace-nowrap text-chart-label text-xs',+ className+ )}+ >+ {tick.label}+ </span>+ </div>+ )),+ container+ );+});++HeatmapXAxis.displayName = 'HeatmapXAxis';++export default HeatmapXAxis;diff --git a/apps/start/src/components/charts/heatmap/heatmap-y-axis.tsx b/apps/start/src/components/charts/heatmap/heatmap-y-axis.tsxnew file mode 100644index 000000000..29d1536c7--- /dev/null+++ b/apps/start/src/components/charts/heatmap/heatmap-y-axis.tsx@@ -0,0 +1,90 @@+'use client';++import { memo, useEffect, useMemo, useState } from 'react';+import { createPortal } from 'react-dom';+import { useHeatmap } from './heatmap-context';+import {+ formatHeatmapYAxisLabel,+ getHeatmapDayLabels,+ type HeatmapYAxisLabelFormat,+ type HeatmapYAxisTickFilter,+ resolveHeatmapRowOpacity,+ shouldShowHeatmapYAxisTick,+} from './heatmap-utils';+import { cn } from '@/lib/utils';++export interface HeatmapYAxisProps {+ /** Additional class name for labels */+ className?: string;+ /** Which row ticks to display. Default: `"odd"` (Mon / Wed / Fri). */+ tickFilter?: HeatmapYAxisTickFilter;+ /** Label format — `"initial"` shows the first letter only (Mon → M). Default: `"full"`. */+ labelFormat?: HeatmapYAxisLabelFormat;+ /** Per-row label opacity — mirrors {@link HeatmapCells} `rowOpacity`. */+ rowOpacity?: number | readonly number[];+}++export const HeatmapYAxis = memo(function HeatmapYAxis({+ className,+ tickFilter = 'odd',+ labelFormat = 'full',+ rowOpacity,+}: HeatmapYAxisProps) {+ const { containerRef, margin, binHeight, gap, yScale, weekStartDay } =+ useHeatmap();+ const [mounted, setMounted] = useState(false);++ useEffect(() => {+ setMounted(true);+ }, []);++ const labels = useMemo(+ () =>+ getHeatmapDayLabels(weekStartDay)+ .map((label, row) => ({+ row,+ label: formatHeatmapYAxisLabel(label, labelFormat),+ y: margin.top + yScale(row) + (binHeight - gap) / 2,+ }))+ .filter((tick) => shouldShowHeatmapYAxisTick(tick.row, tickFilter)),+ [binHeight, gap, labelFormat, margin.top, tickFilter, weekStartDay, yScale]+ );++ const container = containerRef.current;+ if (!(mounted && container)) {+ return null;+ }++ return createPortal(+ labels.map((tick) => (+ <div+ className="pointer-events-none absolute"+ key={tick.row}+ style={{+ top: tick.y,+ left: 4,+ width: Math.max(margin.left - 12, 0),+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'flex-end',+ transform: 'translateY(-50%)',+ }}+ >+ <span+ className={cn(+ 'whitespace-nowrap text-chart-label text-xs',+ className+ )}+ style={{ opacity: resolveHeatmapRowOpacity(tick.row, rowOpacity) }}+ >+ {tick.label}+ </span>+ </div>+ )),+ container+ );+});++HeatmapYAxis.displayName = 'HeatmapYAxis';++export default HeatmapYAxis;diff --git a/apps/start/src/components/charts/heatmap/index.ts b/apps/start/src/components/charts/heatmap/index.tsnew file mode 100644index 000000000..ac7497b7d--- /dev/null+++ b/apps/start/src/components/charts/heatmap/index.ts@@ -0,0 +1,139 @@+export { generateHeatmapSkeletonFromTarget } from './generate-heatmap-skeleton-data';+export {+ computeHeatmapEnterFadeDelayMs,+ computeHeatmapLevelRange,+ HEATMAP_DEFAULT_ENTER_DURATION_MS,+ HEATMAP_DEFAULT_ENTER_EASE,+ HEATMAP_DEFAULT_ENTER_TRANSITION,+ HEATMAP_DEFAULT_LOADING_CELL_MAX_OPACITY,+ HEATMAP_DEFAULT_LOADING_CELL_RANDOMNESS,+ HEATMAP_ENTER_STAGGER_SPREAD,+ HEATMAP_LOADING_BASE_CELL_OPACITY,+ HEATMAP_LOADING_CHART_OPACITY,+ HEATMAP_LOADING_CONCEAL_MS,+ type HeatmapLevelRange,+ heatmapLoadingCellParticipates,+ resolveHeatmapEnterFadeDurationSec,+} from './heatmap-animation';+export { HeatmapCells, type HeatmapCellsProps } from './heatmap-cells';+export {+ HeatmapChart,+ type HeatmapChartProps,+ type HeatmapLayout,+} from './heatmap-chart';+export {+ HeatmapChartLoading,+ type HeatmapChartLoadingProps,+} from './heatmap-chart-loading';+export {+ buildHeatmapColorScale,+ buildHeatmapColorScaleFromStyles,+ buildHeatmapFillScale,+ defaultHeatmapColorScale,+ defaultHeatmapFillScale,+ HEATMAP_DEFAULT_LEVEL_COLORS,+ HEATMAP_DEFAULT_LEVEL_STYLES,+ type HeatmapLevelColors,+ type HeatmapLevelFillMode,+ type HeatmapLevelStyle,+ type HeatmapLevelStyles,+ heatmapLevelPatternId,+ isHeatmapLevelPattern,+ levelColorsFromStyles,+ levelStylesFromColors,+ resolveHeatmapLevelStyles,+} from './heatmap-colors';+export {+ type HeatmapBin,+ type HeatmapColumn,+ type HeatmapContextValue,+ HeatmapInteractionBoundary,+ HeatmapInteractionProvider,+ HeatmapInteractionRoot,+ HeatmapProvider,+ type HeatmapRevealMode,+ heatmapCssVars,+ useHeatmap,+ useHeatmapInteraction,+ useHeatmapInteractionOptional,+} from './heatmap-context';+export {+ HEATMAP_LEGEND_LEVELS,+ HeatmapLegend,+ type HeatmapLegendProps,+ type HeatmapLegendVariant,+} from './heatmap-legend';+export {+ resolveHeatmapSeparatorConfig,+ resolveHeatmapSeparatorConfigWithData,+} from './heatmap-resolve-separator';+export {+ HeatmapSeparator,+ type HeatmapSeparatorProps,+} from './heatmap-separator';+export { HeatmapTooltip, type HeatmapTooltipProps } from './heatmap-tooltip';+export {+ buildHeatmapLegendGradient,+ buildHeatmapQuarterSeparatorGroups,+ buildHeatmapRowOpacity,+ buildHeatmapSeparatorGradientStops,+ countHeatmapWeekDaysOnOrAfter,+ filterHeatmapColumns,+ findHeatmapColumnIndexForDate,+ formatHeatmapContributionLabel,+ formatHeatmapTooltipDate,+ formatHeatmapTooltipWeekday,+ formatHeatmapYAxisLabel,+ getCalendarQuarter,+ getCalendarQuarterStartDatesBetween,+ getHeatmapCalendarRangeStart,+ getHeatmapColumnMonthAnchor,+ getHeatmapColumnQuarterAnchor,+ getHeatmapColumnXOffset,+ getHeatmapContributionLevel,+ getHeatmapDayLabels,+ getHeatmapMonthLabelColumnIndex,+ getHeatmapPlotInnerWidth,+ getHeatmapSeparatorColumnIndices,+ getHeatmapSeparatorCount,+ getHeatmapSeparatorGroupStartColumn,+ getHeatmapSeparatorLineY,+ getHeatmapSeparatorX,+ getHeatmapTimeExtent,+ getHeatmapWeekCount,+ getHeatmapWeekStartAlignedToRange,+ getHeatmapWeekStartSunday,+ getHeatmapYearStartMonth,+ HEATMAP_DAY_LABELS,+ HEATMAP_MONTHS_ONE_YEAR,+ HEATMAP_MONTHS_SIX,+ HEATMAP_WEEKS_ONE_YEAR,+ type HeatmapDisplayRange,+ type HeatmapHoverStyleParams,+ type HeatmapSeparatorGradient,+ type HeatmapSeparatorGradientStop,+ type HeatmapSeparatorGroup,+ type HeatmapSeparatorGroupBy,+ type HeatmapSeparatorLayout,+ type HeatmapSeparatorParsedConfig,+ type HeatmapSeparatorStrokeStyle,+ type HeatmapWeekRange,+ type HeatmapWeekStartDay,+ type HeatmapYAxisLabelFormat,+ type HeatmapYAxisTickFilter,+ inferHeatmapCalendarRangeStart,+ isHeatmapGhostBin,+ isHeatmapHoverEffectEnabled,+ isHeatmapInactiveEffectEnabled,+ resolveHeatmapDisplayRange,+ resolveHeatmapHoverStyle,+ resolveHeatmapInactiveStyle,+ resolveHeatmapRowOpacity,+ resolveHeatmapSeparatorLayout,+ resolveHeatmapSeparatorStrokeDasharray,+ resolveHeatmapWeekRange,+ rotateHeatmapColumnBins,+ shouldShowHeatmapYAxisTick,+} from './heatmap-utils';+export { HeatmapXAxis, type HeatmapXAxisProps } from './heatmap-x-axis';+export { HeatmapYAxis, type HeatmapYAxisProps } from './heatmap-y-axis';diff --git a/apps/start/src/components/charts/heatmap/use-delayed-tooltip-data.ts b/apps/start/src/components/charts/heatmap/use-delayed-tooltip-data.tsnew file mode 100644index 000000000..3fd0d84db--- /dev/null+++ b/apps/start/src/components/charts/heatmap/use-delayed-tooltip-data.ts@@ -0,0 +1,76 @@+'use client';++import { useEffect, useRef, useState } from 'react';+import type { HeatmapTooltipData } from './heatmap-context';++export function useDelayedTooltipData(+ tooltipData: HeatmapTooltipData | null,+ showDelay: number,+ hideDelay: number+): HeatmapTooltipData | null {+ const [displayData, setDisplayData] = useState<HeatmapTooltipData | null>(+ null+ );+ const isShowingRef = useRef(false);+ const showTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(+ undefined+ );+ const hideTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(+ undefined+ );++ useEffect(() => {+ if (showTimerRef.current) {+ clearTimeout(showTimerRef.current);+ showTimerRef.current = undefined;+ }+ if (hideTimerRef.current) {+ clearTimeout(hideTimerRef.current);+ hideTimerRef.current = undefined;+ }++ if (tooltipData) {+ if (isShowingRef.current) {+ setDisplayData(tooltipData);+ return;+ }++ if (showDelay === 0) {+ isShowingRef.current = true;+ setDisplayData(tooltipData);+ return;+ }++ showTimerRef.current = setTimeout(() => {+ isShowingRef.current = true;+ setDisplayData(tooltipData);+ }, showDelay);+ return;+ }++ if (hideDelay === 0) {+ isShowingRef.current = false;+ setDisplayData(null);+ return;+ }++ hideTimerRef.current = setTimeout(() => {+ isShowingRef.current = false;+ setDisplayData(null);+ }, hideDelay);+ }, [tooltipData, showDelay, hideDelay]);++ useEffect(+ () => () => {+ if (showTimerRef.current) {+ clearTimeout(showTimerRef.current);+ }+ if (hideTimerRef.current) {+ clearTimeout(hideTimerRef.current);+ }+ },+ []+ );++ return displayData;+}diff --git a/apps/start/src/components/charts/highlight-segment-bounds.ts b/apps/start/src/components/charts/highlight-segment-bounds.tsindex bd15301f6..4fc0a9136 100644--- a/apps/start/src/components/charts/highlight-segment-bounds.ts+++ b/apps/start/src/components/charts/highlight-segment-bounds.ts@@ -2,7 +2,7 @@ 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.+// 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)) ]diff --git a/apps/start/src/components/charts/highlight-segment.tsx b/apps/start/src/components/charts/highlight-segment.tsxindex defdf404a..d6cc752e7 100644--- a/apps/start/src/components/charts/highlight-segment.tsx+++ b/apps/start/src/components/charts/highlight-segment.tsx@@ -3,8 +3,11 @@import { type MotionValue, motion } from 'motion/react';import { type RefObject, useId } from 'react';-// Re-strokes the base path `d` clipped to the hover band, so the highlight-// follows whatever curve is drawn (see `highlight-segment-bounds.ts`).+// 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. */@@ -38,7 +41,13 @@ export function HighlightSegment({<><defs><clipPath id={clipId}>- <motion.rect height={height} width={width} x={x} y={0} />+ {/* Bleed by strokeWidth so a stroke at the min/max value keeps its full width. */}+ <motion.rect+ height={height + strokeWidth * 2}+ width={width}+ x={x}+ y={-strokeWidth}+ /></clipPath></defs><motion.pathdiff --git a/apps/start/src/components/charts/indicator-fade.ts b/apps/start/src/components/charts/indicator-fade.tsnew file mode 100644index 000000000..b40466e17--- /dev/null+++ b/apps/start/src/components/charts/indicator-fade.ts@@ -0,0 +1,65 @@+/** Vertical fade on the tooltip crosshair indicator. */+export type IndicatorFadeEdges = 'both' | 'none' | 'top' | 'bottom';++export interface VerticalFadeSides {+ top: boolean;+ bottom: boolean;+ any: boolean;+}++export function resolveVerticalFadeSides(+ fade: IndicatorFadeEdges | boolean+): VerticalFadeSides {+ if (fade === false || fade === 'none') {+ return { top: false, bottom: false, any: false };+ }+ if (fade === true || fade === 'both') {+ return { top: true, bottom: true, any: true };+ }+ if (fade === 'top') {+ return { top: true, bottom: false, any: true };+ }+ return { top: false, bottom: true, any: true };+}++export interface IndicatorFadeGradientStop {+ offset: string;+ opacity: number;+}++/** Opacity stops for the crosshair vertical gradient. */+export function indicatorFadeGradientStops(+ sides: VerticalFadeSides,+ fadeLengthPercent = 10+): IndicatorFadeGradientStop[] {+ const fade = Math.min(40, Math.max(2, fadeLengthPercent));+ const innerEnd = 100 - fade;++ if (!sides.any) {+ return [{ offset: '0%', opacity: 1 }];+ }++ if (sides.top && sides.bottom) {+ return [+ { offset: '0%', opacity: 0 },+ { offset: `${fade}%`, opacity: 1 },+ { offset: '50%', opacity: 1 },+ { offset: `${innerEnd}%`, opacity: 1 },+ { offset: '100%', opacity: 0 },+ ];+ }++ if (sides.top) {+ return [+ { offset: '0%', opacity: 0 },+ { offset: `${fade}%`, opacity: 1 },+ { offset: '100%', opacity: 1 },+ ];+ }++ return [+ { offset: '0%', opacity: 1 },+ { offset: `${innerEnd}%`, opacity: 1 },+ { offset: '100%', opacity: 0 },+ ];+}diff --git a/apps/start/src/components/charts/legend/index.ts b/apps/start/src/components/charts/legend/index.tsnew file mode 100644index 000000000..8534d3b7b--- /dev/null+++ b/apps/start/src/components/charts/legend/index.ts@@ -0,0 +1,17 @@+// Legend context and hooks++// Legend components+export { Legend, type LegendProps } from './legend';+export {+ type LegendContextValue,+ type LegendItemContextValue,+ type LegendItemData,+ legendCssVars,+ useLegend,+ useLegendItem,+} from './legend-context';+export { LegendItem, type LegendItemProps } from './legend-item';+export { LegendLabel, type LegendLabelProps } from './legend-label';+export { LegendMarker, type LegendMarkerProps } from './legend-marker';+export { LegendProgress, type LegendProgressProps } from './legend-progress';+export { LegendValue, type LegendValueProps } from './legend-value';diff --git a/apps/start/src/components/charts/legend/legend-context.tsx b/apps/start/src/components/charts/legend/legend-context.tsxnew file mode 100644index 000000000..4348b9bd1--- /dev/null+++ b/apps/start/src/components/charts/legend/legend-context.tsx@@ -0,0 +1,92 @@+'use client';++import { createContext, useContext } from 'react';++// CSS variable references for legend theming+export const legendCssVars = {+ background: 'var(--legend)',+ foreground: 'var(--legend-foreground)',+ muted: 'var(--legend-muted)',+ mutedForeground: 'var(--legend-muted-foreground)',+ track: 'var(--legend-track)',+};++export interface LegendItemData {+ /** Display label */+ label: string;+ /** Current value */+ value: number;+ /** Maximum value (for progress/percentage calculation) */+ maxValue?: number;+ /** Item color */+ color: string;+}++export interface LegendContextValue {+ /** All legend items */+ items: LegendItemData[];+ /** Currently hovered index */+ hoveredIndex: number | null;+ /** Set hovered index */+ setHoveredIndex: (index: number | null) => void;+}++export interface LegendItemContextValue {+ /** The current item data */+ item: LegendItemData;+ /** Index of this item */+ index: number;+ /** Whether this item is hovered */+ isHovered: boolean;+ /** Whether this item is faded (another item is hovered) */+ isFaded: boolean;+ /** Percentage value (value / maxValue * 100) */+ percentage: number;+}++const LegendContext = createContext<LegendContextValue | null>(null);+const LegendItemContext = createContext<LegendItemContextValue | null>(null);++export function LegendProvider({+ children,+ value,+}: {+ children: React.ReactNode;+ value: LegendContextValue;+}) {+ return (+ <LegendContext.Provider value={value}>{children}</LegendContext.Provider>+ );+}++export function LegendItemProvider({+ children,+ value,+}: {+ children: React.ReactNode;+ value: LegendItemContextValue;+}) {+ return (+ <LegendItemContext.Provider value={value}>+ {children}+ </LegendItemContext.Provider>+ );+}++export function useLegend(): LegendContextValue {+ const context = useContext(LegendContext);+ if (!context) {+ throw new Error('useLegend must be used within a <Legend> component.');+ }+ return context;+}++export function useLegendItem(): LegendItemContextValue {+ const context = useContext(LegendItemContext);+ if (!context) {+ throw new Error(+ 'useLegendItem must be used within a <LegendItem> component.'+ );+ }+ return context;+}diff --git a/apps/start/src/components/charts/legend/legend-item.tsx b/apps/start/src/components/charts/legend/legend-item.tsxnew file mode 100644index 000000000..7f5939fa8--- /dev/null+++ b/apps/start/src/components/charts/legend/legend-item.tsx@@ -0,0 +1,36 @@+'use client';++import type { ReactNode } from 'react';+import { useLegend, useLegendItem } from './legend-context';+import { cn } from '@/lib/utils';++export interface LegendItemProps {+ /** Container class name */+ className?: string;+ /** Children components (LegendMarker, LegendLabel, LegendValue, LegendProgress) */+ children: ReactNode;+}++export function LegendItem({ className = '', children }: LegendItemProps) {+ const { setHoveredIndex } = useLegend();+ const { index, isHovered } = useLegendItem();++ return (+ // biome-ignore lint/a11y/noNoninteractiveElementInteractions: Legend item hover interaction+ // biome-ignore lint/a11y/noStaticElementInteractions: Legend item hover interaction+ <div+ className={cn(+ 'cursor-pointer rounded-lg px-2 py-1.5 transition-all duration-150 ease-out',+ isHovered && 'bg-legend-muted',+ className+ )}+ data-hovered={isHovered ? '' : undefined}+ onMouseEnter={() => setHoveredIndex(index)}+ onMouseLeave={() => setHoveredIndex(null)}+ >+ {children}+ </div>+ );+}++LegendItem.displayName = 'LegendItem';diff --git a/apps/start/src/components/charts/legend/legend-label.tsx b/apps/start/src/components/charts/legend/legend-label.tsxnew file mode 100644index 000000000..7999f774d--- /dev/null+++ b/apps/start/src/components/charts/legend/legend-label.tsx@@ -0,0 +1,23 @@+'use client';++import { useLegendItem } from './legend-context';+import { cn } from '@/lib/utils';++export interface LegendLabelProps {+ /** Label class name. Default: "text-sm font-medium" */+ className?: string;+}++export function LegendLabel({+ className = 'text-sm font-medium',+}: LegendLabelProps) {+ const { item } = useLegendItem();++ return (+ <span className={cn('text-legend-foreground', className)}>+ {item.label}+ </span>+ );+}++LegendLabel.displayName = 'LegendLabel';diff --git a/apps/start/src/components/charts/legend/legend-marker.tsx b/apps/start/src/components/charts/legend/legend-marker.tsxnew file mode 100644index 000000000..192ea2cb6--- /dev/null+++ b/apps/start/src/components/charts/legend/legend-marker.tsx@@ -0,0 +1,23 @@+'use client';++import { useLegendItem } from './legend-context';+import { cn } from '@/lib/utils';++export interface LegendMarkerProps {+ /** Marker size class. Default: "h-2.5 w-2.5" */+ className?: string;+}++export function LegendMarker({ className = 'h-2.5 w-2.5' }: LegendMarkerProps) {+ const { item } = useLegendItem();++ // Note: backgroundColor must remain inline style as item.color is dynamic data+ return (+ <div+ className={cn('shrink-0 rounded-full', className)}+ style={{ backgroundColor: item.color }}+ />+ );+}++LegendMarker.displayName = 'LegendMarker';diff --git a/apps/start/src/components/charts/legend/legend-progress.tsx b/apps/start/src/components/charts/legend/legend-progress.tsxnew file mode 100644index 000000000..86a01390d--- /dev/null+++ b/apps/start/src/components/charts/legend/legend-progress.tsx@@ -0,0 +1,49 @@+'use client';++import { Progress } from '@base-ui/react/progress';+import { useLegendItem } from './legend-context';+import { cn } from '@/lib/utils';++export interface LegendProgressProps {+ /** Track class name */+ trackClassName?: string;+ /** Indicator class name */+ indicatorClassName?: string;+ /** Track height. Default: "h-1.5" */+ height?: string;+}++export function LegendProgress({+ trackClassName = '',+ indicatorClassName = '',+ height = 'h-1.5',+}: LegendProgressProps) {+ const { item } = useLegendItem();++ if (!item.maxValue) {+ return null;+ }++ // Note: item.color must remain inline style as it's dynamic data+ return (+ <Progress.Root max={item.maxValue} value={item.value}>+ <Progress.Track+ className={cn(+ 'w-full overflow-hidden rounded-full bg-legend-track',+ height,+ trackClassName+ )}+ >+ <Progress.Indicator+ className={cn(+ 'h-full rounded-full transition-all duration-500',+ indicatorClassName+ )}+ style={{ backgroundColor: item.color }}+ />+ </Progress.Track>+ </Progress.Root>+ );+}++LegendProgress.displayName = 'LegendProgress';diff --git a/apps/start/src/components/charts/legend/legend-value.tsx b/apps/start/src/components/charts/legend/legend-value.tsxnew file mode 100644index 000000000..7002b1ba1--- /dev/null+++ b/apps/start/src/components/charts/legend/legend-value.tsx@@ -0,0 +1,46 @@+'use client';++import { intFmt } from '../chart-formatters';+import { useLegendItem } from './legend-context';+import { cn } from '@/lib/utils';++export interface LegendValueProps {+ /** Value class name. Default: "text-sm tabular-nums" */+ className?: string;+ /** Show percentage alongside value. Default: false */+ showPercentage?: boolean;+ /** Percentage class name. Default: "text-xs tabular-nums" */+ percentageClassName?: string;+ /** Format function for the value. Default: toLocaleString() */+ formatValue?: (value: number) => string;+ /** Format function for percentage. Default: (p) => `${p.toFixed(0)}%` */+ formatPercentage?: (percentage: number) => string;+}++export function LegendValue({+ className = 'text-sm tabular-nums',+ showPercentage = false,+ percentageClassName = 'text-xs tabular-nums',+ formatValue = intFmt,+ formatPercentage = (p) => `${p.toFixed(0)}%`,+}: LegendValueProps) {+ const { item, percentage } = useLegendItem();++ return (+ <span+ className={cn(+ 'flex items-center gap-2 text-legend-muted-foreground',+ className+ )}+ >+ <span>{formatValue(item.value)}</span>+ {showPercentage && item.maxValue && (+ <span className={percentageClassName}>+ {formatPercentage(percentage)}+ </span>+ )}+ </span>+ );+}++LegendValue.displayName = 'LegendValue';diff --git a/apps/start/src/components/charts/legend/legend.tsx b/apps/start/src/components/charts/legend/legend.tsxnew file mode 100644index 000000000..41ed3c079--- /dev/null+++ b/apps/start/src/components/charts/legend/legend.tsx@@ -0,0 +1,104 @@+'use client';++import {+ cloneElement,+ isValidElement,+ type ReactElement,+ useState,+} from 'react';+import {+ type LegendItemData,+ LegendItemProvider,+ LegendProvider,+} from './legend-context';+import { cn } from '@/lib/utils';++export interface LegendProps {+ /** Legend items data */+ items: LegendItemData[];+ /** Controlled hover state */+ hoveredIndex?: number | null;+ /** Hover state change callback */+ onHoverChange?: (index: number | null) => void;+ /** Title shown above the legend */+ title?: string;+ /** Title class name */+ titleClassName?: string;+ /** Container class name */+ className?: string;+ /** Children - should contain a single LegendItem that will be mapped for each item */+ children: ReactElement;+}++export function Legend({+ items,+ hoveredIndex: controlledHoveredIndex,+ onHoverChange,+ title,+ titleClassName = 'text-sm font-semibold',+ className = '',+ children,+}: LegendProps) {+ const [internalHoveredIndex, setInternalHoveredIndex] = useState<+ number | null+ >(null);++ // Controlled or uncontrolled hover state+ const isControlled = controlledHoveredIndex !== undefined;+ const hoveredIndex = isControlled+ ? controlledHoveredIndex+ : internalHoveredIndex;+ const setHoveredIndex = (index: number | null) => {+ if (isControlled) {+ onHoverChange?.(index);+ } else {+ setInternalHoveredIndex(index);+ }+ };++ const contextValue = {+ items,+ hoveredIndex,+ setHoveredIndex,+ };++ return (+ <LegendProvider value={contextValue}>+ <div className={cn('legend-container flex flex-col gap-2', className)}>+ {title && (+ <h3 className={cn('mb-1 text-legend-foreground', titleClassName)}>+ {title}+ </h3>+ )}+ {items.map((item, index) => {+ const isHovered = hoveredIndex === index;+ const isFaded = hoveredIndex !== null && hoveredIndex !== index;+ const percentage = item.maxValue+ ? (item.value / item.maxValue) * 100+ : 0;++ const itemContext = {+ item,+ index,+ isHovered,+ isFaded,+ percentage,+ };++ // Clone the child element for each item+ if (isValidElement(children)) {+ return (+ <LegendItemProvider key={item.label} value={itemContext}>+ {cloneElement(children)}+ </LegendItemProvider>+ );+ }++ return null;+ })}+ </div>+ </LegendProvider>+ );+}++Legend.displayName = 'Legend';diff --git a/apps/start/src/components/charts/line-chart-loading.tsx b/apps/start/src/components/charts/line-chart-loading.tsxnew file mode 100644index 000000000..dbfe9db67--- /dev/null+++ b/apps/start/src/components/charts/line-chart-loading.tsx@@ -0,0 +1,112 @@+'use client';++import { curveNatural } from '@visx/curve';+import { useMemo } from 'react';+import type { Margin } from './chart-context';+import type { LoadingStyle } from './chart-phase';+import {+ DEFAULT_SKELETON_DATA_KEY,+ DEFAULT_SKELETON_POINT_COUNT,+ generateChartSkeletonData,+} from './generate-chart-skeleton-data';+import { Grid } from './grid';+import { Line } from './line';+import { LineChart } from './line-chart';++const LOADING_DATA_KEY = DEFAULT_SKELETON_DATA_KEY;+const DEFAULT_LOADING_STROKE = 'var(--foreground)';+const DEFAULT_LOADING_GRID_STROKE =+ 'color-mix(in oklch, var(--chart-grid) 50%, transparent)';+const DEFAULT_LOADING_GRID_SHIMMER_STROKE =+ 'color-mix(in oklch, var(--foreground) 68%, transparent)';+const DEFAULT_LOADING_STROKE_OPACITY = 0.5;++export interface LineChartLoadingProps {+ /** Chart margins */+ margin?: Partial<Margin>;+ /** Stroke color for the animated loading segment. */+ stroke?: string;+ /** Stroke opacity for the animated loading segment. Default: 0.5 */+ strokeOpacity?: number;+ /** Grid line stroke (color and opacity via color-mix or oklch alpha). */+ gridStroke?: string;+ /** Shimmer band stroke (color and opacity via color-mix or oklch alpha). */+ gridShimmerStroke?: string;+ /** Animate a shimmer band across grid lines. Default: true */+ gridShimmer?: boolean;+ /** Shimmer band width in pixels. Default: 140 */+ gridShimmerLength?: number;+ /** Shimmer speed multiplier (higher = faster). Default: 1 */+ gridShimmerSpeed?: number;+ /** Match shimmer loop to the loading line pulse (cycle + inter-loop pause). */+ gridShimmerSync?: boolean;+ /** Loading animation: `"pulse"` (default traveling pulse) or `"sweep"` (a+ * diagonal shimmer across the skeleton line). Default: `"pulse"`. */+ loadingStyle?: LoadingStyle;+ /** Centered shimmer label text. Default: "Loading" */+ label?: string;+ /** Aspect ratio as "width / height". Default: "2 / 1" */+ aspectRatio?: string;+ /** Additional class name for the container */+ className?: string;+}++export function LineChartLoading({+ margin,+ stroke = DEFAULT_LOADING_STROKE,+ strokeOpacity = DEFAULT_LOADING_STROKE_OPACITY,+ gridStroke = DEFAULT_LOADING_GRID_STROKE,+ gridShimmerStroke = DEFAULT_LOADING_GRID_SHIMMER_STROKE,+ gridShimmer = true,+ gridShimmerLength,+ gridShimmerSpeed,+ gridShimmerSync = false,+ loadingStyle = 'pulse',+ label = 'Loading',+ aspectRatio = '2 / 1',+ className = '',+}: LineChartLoadingProps) {+ const data = useMemo(+ () =>+ generateChartSkeletonData({+ dataKey: DEFAULT_SKELETON_DATA_KEY,+ pointCount: DEFAULT_SKELETON_POINT_COUNT,+ }),+ []+ );++ return (+ <LineChart+ animationDuration={0}+ aspectRatio={aspectRatio}+ className={className}+ data={data}+ loadingLabel={label}+ margin={margin}+ status="loading"+ >+ <Grid+ horizontal+ shimmer={loadingStyle === 'sweep' ? false : gridShimmer}+ shimmerLength={gridShimmerLength}+ shimmerSpeed={gridShimmerSpeed}+ shimmerStroke={gridShimmerStroke}+ shimmerSync={gridShimmerSync}+ stroke={gridStroke}+ />+ <Line+ curve={curveNatural}+ dataKey={LOADING_DATA_KEY}+ fadeEdges={false}+ loadingStroke={stroke}+ loadingStrokeOpacity={strokeOpacity}+ loadingStyle={loadingStyle}+ showHighlight={false}+ stroke="transparent"+ strokeWidth={2.5}+ />+ </LineChart>+ );+}++export default LineChartLoading;diff --git a/apps/start/src/components/charts/line-chart.tsx b/apps/start/src/components/charts/line-chart.tsxindex edba28501..30bbb62a0 100644--- a/apps/start/src/components/charts/line-chart.tsx+++ b/apps/start/src/components/charts/line-chart.tsx@@ -1,16 +1,27 @@'use client';-import { ParentSize } from '@visx/responsive';import type { Transition } from 'motion/react';import {Children,+ type CSSProperties,isValidElement,type ReactElement,type ReactNode,+ useCallback,useMemo,useRef,+ useState,} from 'react';import type { LineConfig, Margin } from './chart-context';+import { ChartLoadingLabel } from './chart-loading-label';+import { ParentSize } from './chart-parent-size';+import {+ type ChartPhase,+ type ChartStatus,+ DEFAULT_CHART_STATUS,+ DEFAULT_Y_DOMAIN_TWEEN_MS,+ resolveRestingChartPhase,+} from './chart-phase';import { Line, type LineProps } from './line';import { TimeSeriesChartInner } from './time-series-chart-shell';import { cn } from '@/lib/utils';@@ -28,10 +39,34 @@ export interface LineChartProps {animationEasing?: string;enterTransition?: Transition;revealSignature?: string;- /** Aspect ratio as "width / height". Default: "2 / 1" */+ /** Aspect ratio as "width / height". Default: "2 / 1". Omit to fill a sized parent. */aspectRatio?: string;/** Additional class name for the container */className?: string;+ /** Loading vs ready — drives chart phase and loading chrome. Default: `"ready"`. */+ status?: ChartStatus;+ /** Centered shimmer label while loading. */+ loadingLabel?: string;+ /** Animate y-domain over this duration (ms) on status transitions. Default: 500. */+ yDomainTweenDuration?: number;+ /** Animate y-domain when status or target domain changes. Default: true */+ yDomainTween?: boolean;+ /** Visible x-domain for brush zoom. */+ xDomain?: [Date, Date];+ /** Full dataset length for x-scale padding when `xDomain` is set. */+ xDomainSlotCount?: number;+ /** Tween y-domain when brush changes the visible x-range. Default: false */+ tweenYDomainOnXDomainChange?: boolean;+ /** Inline container styles (e.g. fixed height for brush strip). */+ style?: CSSProperties;+ /** Fires when the internal chart phase changes (e.g. OG capture readiness). */+ onPhaseChange?: (phase: ChartPhase) => void;+ /** Formats the x-axis and crosshair date labels. Default: `shortDateFmt`. */+ formatDateLabel?: (date: Date) => string;+ /** Fixed y domain, used as is: no headroom and no rounding. */+ yDomain?: [number, number];+ /** Smallest value at the top, for "lower is better" metrics. */+ yReversed?: boolean;/** Child components (Line, Grid, ChartTooltip, etc.) */children: ReactNode;}@@ -41,6 +76,7 @@ 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',+ 'LineSeriesTerminalMarker','Area','SeriesBar','Scatter',@@ -91,6 +127,7 @@ function extractLineConfigs(children: ReactNode): LineConfig[] {dataKey: props.dataKey,stroke: props.stroke || 'var(--chart-line-primary)',strokeWidth: props.strokeWidth || 2.5,+ yAxisId: props.yAxisId,});return;}@@ -116,8 +153,19 @@ interface ChartInnerProps {animationEasing?: string;enterTransition?: Transition;revealSignature?: string;+ chartStatus: ChartStatus;+ loadingLabel?: string;+ yDomainTweenDuration: number;+ yDomainTween: boolean;+ xDomain?: [Date, Date];+ xDomainSlotCount?: number;+ tweenYDomainOnXDomainChange?: boolean;children: ReactNode;containerRef: React.RefObject<HTMLDivElement | null>;+ onPhaseChange: (phase: ChartPhase) => void;+ formatDateLabel?: (date: Date) => string;+ yDomain?: [number, number];+ yReversed?: boolean;}function ChartInner({@@ -130,8 +178,19 @@ function ChartInner({animationEasing,enterTransition,revealSignature,+ chartStatus,+ loadingLabel,+ yDomainTweenDuration,+ yDomainTween,+ xDomain,+ xDomainSlotCount,+ tweenYDomainOnXDomainChange,children,containerRef,+ onPhaseChange,+ formatDateLabel,+ yDomain,+ yReversed,}: ChartInnerProps) {const lines = useMemo(() => extractLineConfigs(children), [children]);@@ -139,16 +198,27 @@ function ChartInner({<TimeSeriesChartInneranimationDuration={animationDuration}animationEasing={animationEasing}+ chartStatus={chartStatus}clipPathId="chart-grow-clip"containerRef={containerRef}data={data}enterTransition={enterTransition}+ formatDateLabel={formatDateLabel}height={height}lines={lines}+ loadingLabel={loadingLabel}margin={margin}+ onPhaseChange={onPhaseChange}revealSignature={revealSignature}+ tweenYDomainOnXDomainChange={tweenYDomainOnXDomainChange}width={width}xDataKey={xDataKey}+ xDomain={xDomain}+ xDomainSlotCount={xDomainSlotCount}+ yDomain={yDomain}+ yDomainTween={yDomainTween}+ yDomainTweenDuration={yDomainTweenDuration}+ yReversed={yReversed}>{children}</TimeSeriesChartInner>@@ -165,35 +235,86 @@ export function LineChart({revealSignature,aspectRatio = '2 / 1',className = '',+ status = DEFAULT_CHART_STATUS,+ loadingLabel,+ yDomainTweenDuration = DEFAULT_Y_DOMAIN_TWEEN_MS,+ yDomainTween = true,+ xDomain,+ xDomainSlotCount,+ tweenYDomainOnXDomainChange = false,+ style,+ onPhaseChange,+ formatDateLabel,+ yDomain,+ yReversed,children,}: LineChartProps) {const containerRef = useRef<HTMLDivElement>(null);const margin = { ...DEFAULT_MARGIN, ...marginProp };+ const [chartPhase, setChartPhase] = useState<ChartPhase>(() =>+ resolveRestingChartPhase(status)+ );+ const handlePhaseChange = useCallback(+ (phase: ChartPhase) => {+ setChartPhase(phase);+ onPhaseChange?.(phase);+ },+ [onPhaseChange]+ );++ const showLoadingLabel = Boolean(+ loadingLabel?.trim() &&+ (chartPhase === 'loading' ||+ chartPhase === 'exiting' ||+ chartPhase === 'gridTweenReady' ||+ chartPhase === 'revealingLoading')+ );return (<divclassName={cn('relative w-full', className)}ref={containerRef}- style={{ aspectRatio, touchAction: 'none' }}+ style={{+ ...(aspectRatio ? { aspectRatio } : undefined),+ touchAction: 'none',+ ...style,+ }}><ParentSize debounceTime={10}>{({ width, height }) => (<ChartInneranimationDuration={animationDuration}animationEasing={animationEasing}+ chartStatus={status}containerRef={containerRef}data={data}enterTransition={enterTransition}+ formatDateLabel={formatDateLabel}height={height}+ loadingLabel={loadingLabel}margin={margin}+ onPhaseChange={handlePhaseChange}revealSignature={revealSignature}+ tweenYDomainOnXDomainChange={tweenYDomainOnXDomainChange}width={width}xDataKey={xDataKey}+ xDomain={xDomain}+ xDomainSlotCount={xDomainSlotCount}+ yDomain={yDomain}+ yDomainTween={yDomainTween}+ yDomainTweenDuration={yDomainTweenDuration}+ yReversed={yReversed}>{children}</ChartInner>)}</ParentSize>+ {showLoadingLabel ? (+ <ChartLoadingLabel+ exiting={chartPhase !== 'loading'}+ text={loadingLabel}+ />+ ) : null}</div>);}diff --git a/apps/start/src/components/charts/line-loading-pulse.tsx b/apps/start/src/components/charts/line-loading-pulse.tsxnew file mode 100644index 000000000..93e187ed8--- /dev/null+++ b/apps/start/src/components/charts/line-loading-pulse.tsx@@ -0,0 +1,218 @@+'use client';++import { animate, motion, useMotionValue, useTransform } from 'motion/react';+import { useEffect, useId } from 'react';+import { chartCssVars, useChartStable } from './chart-context';+import type { ChartPhase } from './chart-phase';+import {+ fadeGradientStops,+ resolveFadeSides,+ viewportFadeGradientAttrs,+} from './fade-edges';+import {+ LINE_LOADING_PULSE_CYCLE_S,+ LINE_LOADING_PULSE_EASE,+} from './line-loading-timing';++const CLIP_PADDING = 10;++export type LineLoadingPulseMode = 'loop' | 'exit' | 'enter';++export function resolveLineLoadingPulseMode(+ phase: ChartPhase+): LineLoadingPulseMode | null {+ switch (phase) {+ case 'loading':+ return 'loop';+ case 'exiting':+ return 'exit';+ case 'revealingLoading':+ return 'enter';+ default:+ return null;+ }+}++export interface LineLoadingPulseStrokeProps {+ pathD: string;+ mode?: LineLoadingPulseMode;+ /** Bumps to restart loop cycles without remounting the stroke. */+ loopEpoch?: number;+ stroke?: string;+ /** Stroke opacity for the animated segment. Default: 0.5 */+ strokeOpacity?: number;+ strokeWidth?: number;+ onCycleComplete?: () => void;+}++function useGrowExitClip(+ innerWidth: number,+ mode: LineLoadingPulseMode,+ loopEpoch: number,+ onComplete?: () => void+) {+ const progress = useMotionValue(0);+ const paddedFullWidth = innerWidth + CLIP_PADDING * 2;+ const rightEdge = innerWidth + CLIP_PADDING;++ const clipWidth = useTransform(progress, (p) => {+ if (p <= 0.5) {+ return (p / 0.5) * paddedFullWidth;+ }+ const shrink = (p - 0.5) / 0.5;+ return (1 - shrink) * paddedFullWidth;+ });++ const clipX = useTransform(progress, (p) => {+ if (p <= 0.5) {+ return -CLIP_PADDING;+ }+ const shrink = (p - 0.5) / 0.5;+ return rightEdge - (1 - shrink) * paddedFullWidth;+ });++ // biome-ignore lint/correctness/useExhaustiveDependencies: loopEpoch restarts pulse when orchestrator advances+ useEffect(() => {+ if (innerWidth <= 0) {+ return;+ }++ const halfCycleS = LINE_LOADING_PULSE_CYCLE_S / 2;+ let cancelled = false;+ let controls: ReturnType<typeof animate> | undefined;++ const finish = () => {+ if (!cancelled) {+ onComplete?.();+ }+ };++ const runShrink = (from: number) => {+ const shrinkDuration = halfCycleS * ((1 - from) / 0.5);+ controls = animate(progress, 1, {+ duration: Math.max(shrinkDuration, 0.01),+ ease: [...LINE_LOADING_PULSE_EASE],+ onComplete: finish,+ });+ };++ if (mode === 'loop') {+ progress.set(0);+ controls = animate(progress, 1, {+ duration: LINE_LOADING_PULSE_CYCLE_S,+ ease: [...LINE_LOADING_PULSE_EASE],+ onComplete: finish,+ });+ return () => {+ cancelled = true;+ controls?.stop();+ };+ }++ if (mode === 'exit') {+ const current = progress.get();++ if (current < 0.5) {+ const growDuration = halfCycleS * ((0.5 - current) / 0.5);+ controls = animate(progress, 0.5, {+ duration: Math.max(growDuration, 0.01),+ ease: [...LINE_LOADING_PULSE_EASE],+ onComplete: () => {+ if (!cancelled) {+ runShrink(0.5);+ }+ },+ });+ } else {+ runShrink(current);+ }++ return () => {+ cancelled = true;+ controls?.stop();+ };+ }++ if (mode === 'enter') {+ progress.set(0);+ controls = animate(progress, 0.5, {+ duration: halfCycleS,+ ease: [...LINE_LOADING_PULSE_EASE],+ onComplete: finish,+ });+ return () => {+ cancelled = true;+ controls?.stop();+ };+ }+ }, [innerWidth, loopEpoch, mode, onComplete, progress]);++ return { clipX, clipWidth };+}++export function LineLoadingPulseStroke({+ pathD,+ mode = 'loop',+ loopEpoch = 0,+ stroke = chartCssVars.foreground,+ strokeOpacity = 0.5,+ strokeWidth = 2.5,+ onCycleComplete,+}: LineLoadingPulseStrokeProps) {+ const { innerWidth, innerHeight } = useChartStable();+ const reactId = useId();+ const clipPathId = `line-loading-clip-${reactId}`;+ const gradientId = `line-loading-gradient-${reactId}`;+ const fadeStops = fadeGradientStops(resolveFadeSides(true));+ const clipHeight = innerHeight + CLIP_PADDING * 2;+ const { clipX, clipWidth } = useGrowExitClip(+ innerWidth,+ mode,+ loopEpoch,+ onCycleComplete+ );++ if (innerWidth <= 0) {+ return null;+ }++ return (+ <>+ <defs>+ <clipPath id={clipPathId}>+ <motion.rect+ height={clipHeight}+ style={{ width: clipWidth, x: clipX }}+ y={-CLIP_PADDING}+ />+ </clipPath>+ <linearGradient+ id={gradientId}+ {...viewportFadeGradientAttrs(innerWidth)}+ >+ {fadeStops.map((stop) => (+ <stop+ key={stop.offset}+ offset={stop.offset}+ stopColor={stroke}+ stopOpacity={stop.opacity}+ />+ ))}+ </linearGradient>+ </defs>+ <path+ clipPath={`url(#${clipPathId})`}+ d={pathD}+ fill="none"+ opacity={strokeOpacity}+ stroke={`url(#${gradientId})`}+ strokeLinecap="round"+ strokeWidth={strokeWidth}+ />+ </>+ );+}++LineLoadingPulseStroke.displayName = 'LineLoadingPulseStroke';++export default LineLoadingPulseStroke;diff --git a/apps/start/src/components/charts/line-loading-timing.ts b/apps/start/src/components/charts/line-loading-timing.tsnew file mode 100644index 000000000..425c37bda--- /dev/null+++ b/apps/start/src/components/charts/line-loading-timing.ts@@ -0,0 +1,13 @@+/** Grow + exit timeline for `LineLoadingPulse` (seconds). */+export const LINE_LOADING_PULSE_CYCLE_S = 2.2;++/** Idle gap before the loading line pulse restarts (milliseconds). */+export const LINE_LOADING_LOOP_PAUSE_MS = 280;++/** Loading label exit on loading → ready (seconds). */+export const LOADING_LABEL_EXIT_S = 0.45;++/** Loading label drops this many pixels while exiting. */+export const LOADING_LABEL_EXIT_Y_PX = 30;++export const LINE_LOADING_PULSE_EASE = [0.85, 0, 0.15, 1] as const;diff --git a/apps/start/src/components/charts/line-series-terminal-marker.tsx b/apps/start/src/components/charts/line-series-terminal-marker.tsxnew file mode 100644index 000000000..d5841295a--- /dev/null+++ b/apps/start/src/components/charts/line-series-terminal-marker.tsx@@ -0,0 +1,94 @@+'use client';++import { motion } from 'motion/react';+import { useMemo } from 'react';+import { useChartStable, useYScale } from './chart-context';+import { StaticSeriesPointMarker } from './series-point-marker';++export interface LineSeriesTerminalMarkerProps {+ dataKey: string;+ yAxisId?: string | number;+ fill?: string;+ stroke?: string;+ radius?: number;+ ringGap?: number;+ strokeWidth?: number;+}++function isTerminalMarkerPhaseVisible(phase: string): boolean {+ return phase === 'ready' || phase === 'exitingReady';+}++/** Hollow ring at the last data point — shared anchor for projection lines. */+export function LineSeriesTerminalMarker({+ dataKey,+ yAxisId,+ fill = 'transparent',+ stroke = 'var(--chart-1)',+ radius = 5,+ ringGap = 0,+ strokeWidth = 1.5,+}: LineSeriesTerminalMarkerProps) {+ const { data, xScale, xAccessor, chartPhase, revealEpoch, enterTransition } =+ useChartStable();+ const yScale = useYScale(yAxisId);++ const point = useMemo(() => {+ const lastRow = data.at(-1);+ if (!lastRow) {+ return null;+ }+ const value = lastRow[dataKey];+ if (typeof value !== 'number') {+ return null;+ }+ return {+ cx: xScale(xAccessor(lastRow)) ?? 0,+ cy: yScale(value) ?? 0,+ };+ }, [data, dataKey, xAccessor, xScale, yScale]);++ const visible = isTerminalMarkerPhaseVisible(chartPhase);+ const fadeTransition =+ enterTransition && typeof enterTransition === 'object'+ ? enterTransition+ : { duration: 0.28, ease: [0.22, 1, 0.36, 1] as const };++ if (!point) {+ return null;+ }++ return (+ <motion.g+ animate={{+ opacity: visible ? 1 : 0,+ scale: visible ? 1 : 0.55,+ }}+ initial={{ opacity: 0, scale: 0.55 }}+ key={revealEpoch ?? 0}+ style={{+ transformBox: 'fill-box' as const,+ transformOrigin: `${point.cx}px ${point.cy}px`,+ }}+ transition={fadeTransition}+ >+ <StaticSeriesPointMarker+ cx={point.cx}+ cy={point.cy}+ fill={fill}+ radius={radius}+ ringGap={ringGap}+ stroke={stroke}+ strokeWidth={strokeWidth}+ />+ </motion.g>+ );+}++LineSeriesTerminalMarker.displayName = 'LineSeriesTerminalMarker';++(+ LineSeriesTerminalMarker as unknown as Record<string, boolean>+).__isPostOverlay = true;++export default LineSeriesTerminalMarker;diff --git a/apps/start/src/components/charts/line.tsx b/apps/start/src/components/charts/line.tsxindex 3eb346e93..7559b5767 100644--- a/apps/start/src/components/charts/line.tsx+++ b/apps/start/src/components/charts/line.tsx@@ -7,13 +7,29 @@ import { LinePath } from '@visx/shape';// biome-ignore lint/suspicious/noExplicitAny: d3 curve factory typetype CurveFactory = any;-import { useCallback, useId, useRef } from 'react';-import { chartCssVars, useChartStable } from './chart-context';+import {+ type RefObject,+ useCallback,+ useId,+ useMemo,+ useRef,+ useState,+} from 'react';+import { chartCssVars, useChartStable, useYScale } from './chart-context';+import type { LoadingStyle } from './chart-phase';import {type FadeEdges,fadeGradientStops,resolveFadeSides,+ viewportFadeGradientAttrs,} from './fade-edges';+import {+ type LineLoadingPulseMode,+ LineLoadingPulseStroke,+ resolveLineLoadingPulseMode,+} from './line-loading-pulse';+import { LINE_LOADING_LOOP_PAUSE_MS } from './line-loading-timing';+import { LineLoadingSweep } from './loading-sweep';import {resolveDashTailBounds,usePathStrokeMetrics,@@ -23,10 +39,13 @@ import { SeriesHighlightLayer } from './series-highlight-layer';import { SeriesHoverDim } from './series-hover-dim';import { SeriesMarkers } from './series-markers';import type { SeriesPointMarkerStyle } from './series-point-marker';+import { useAnimatedSeriesPath } from './use-animated-series-path';export interface LineProps {/** Key in data to use for y values */dataKey: string;+ /** Y-scale group id (Recharts `yAxisId`). Default: `"left"`. */+ yAxisId?: string | number;/** Stroke color. Default: var(--chart-line-primary) */stroke?: string;/** Stroke width. Default: 2.5 */@@ -55,10 +74,141 @@ export interface LineProps {dashFromIndex?: number;/** Dash pattern for the tail segment when `dashFromIndex` is set. Default: "6,4" */dashArray?: string;+ /**+ * Show the loading pulse overlay. Default: follows chart loading phase.+ * Set `false` to disable even during loading.+ */+ loading?: boolean;+ /** Stroke color for the loading pulse overlay. Default: var(--foreground) */+ loadingStroke?: string;+ /** Loading pulse stroke opacity. Default: 0.5 */+ loadingStrokeOpacity?: number;+ /** Override pulse animation mode (loop / exit / enter). */+ loadingPulseMode?: LineLoadingPulseMode;+ /** Called when a loop-mode pulse cycle completes. */+ onLoadingPulseCycleComplete?: () => void;+ /**+ * Loading animation while the chart is in loading status: the default+ * traveling `"pulse"`, or a diagonal `"sweep"` shimmer across the skeleton+ * line. Default: `"pulse"`.+ */+ loadingStyle?: LoadingStyle;+}++function LineSeriesStroke({+ animatedPathD,+ curve,+ getY,+ hasValue,+ pathRef,+ renderData,+ strokeWidth,+ useDataTransitionPath,+ visibleStroke,+ xAccessor,+ xScale,+}: {+ animatedPathD: string;+ curve: CurveFactory;+ getY: (datum: Record<string, unknown>) => number;+ hasValue: (datum: Record<string, unknown>) => boolean;+ pathRef: RefObject<SVGPathElement | null>;+ renderData: Record<string, unknown>[];+ strokeWidth: number;+ useDataTransitionPath: boolean;+ visibleStroke: string;+ xAccessor: (datum: Record<string, unknown>) => Date;+ xScale: (value: Date) => number | undefined;+}) {+ if (useDataTransitionPath && animatedPathD) {+ return (+ <path+ d={animatedPathD}+ fill="none"+ ref={pathRef}+ stroke={visibleStroke}+ strokeLinecap="round"+ strokeWidth={strokeWidth}+ />+ );+ }++ return (+ <LinePath+ curve={curve}+ data={renderData}+ defined={hasValue}+ innerRef={pathRef}+ stroke={visibleStroke}+ strokeLinecap="round"+ strokeWidth={strokeWidth}+ x={(d) => xScale(xAccessor(d)) ?? 0}+ y={getY}+ />+ );+}++function LineLoadingOverlays({+ curve,+ handleLoadingPulseComplete,+ innerWidth,+ loadingStroke,+ loadingStrokeOpacity,+ loadingStyle,+ pathD,+ pulseEpoch,+ pulseMode,+ showLoadingPulse,+ strokeWidth,+}: {+ curve: CurveFactory;+ handleLoadingPulseComplete: () => void;+ innerWidth: number;+ loadingStroke: string;+ loadingStrokeOpacity: number;+ loadingStyle: LoadingStyle;+ pathD: string | null;+ pulseEpoch: number;+ pulseMode: LineLoadingPulseMode | null;+ showLoadingPulse: boolean;+ strokeWidth: number;+}) {+ const sweepLoading =+ showLoadingPulse && innerWidth > 0 && loadingStyle === 'sweep';+ const pulseLoading = showLoadingPulse && innerWidth > 0 && !sweepLoading;++ return (+ <>+ {sweepLoading ? (+ <LineLoadingSweep+ curve={curve}+ key="loading-sweep"+ mode={pulseMode ?? 'loop'}+ onTransitionComplete={handleLoadingPulseComplete}+ stroke={loadingStroke}+ strokeOpacity={loadingStrokeOpacity}+ strokeWidth={strokeWidth}+ />+ ) : null}+ {pulseLoading && pathD ? (+ <LineLoadingPulseStroke+ key="loading-pulse"+ loopEpoch={pulseEpoch}+ mode={pulseMode ?? undefined}+ onCycleComplete={handleLoadingPulseComplete}+ pathD={pathD}+ stroke={loadingStroke}+ strokeOpacity={loadingStrokeOpacity}+ strokeWidth={strokeWidth}+ />+ ) : null}+ </>+ );}export function Line({dataKey,+ yAxisId,stroke = chartCssVars.linePrimary,strokeWidth = 2.5,curve = curveNatural,@@ -69,25 +219,81 @@ export function Line({markers,dashFromIndex,dashArray = '6,4',+ loading,+ loadingStroke = chartCssVars.foreground,+ loadingStrokeOpacity = 0.5,+ loadingPulseMode,+ onLoadingPulseCycleComplete,+ loadingStyle = 'pulse',}: 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 a single shared clipPath at the chart-shell level- // (`time-series-chart-shell.tsx`).+ // 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,+ lines,+ chartPhase,+ notifyLoadingPulseComplete,+ yDomainTweenDuration,} = useChartStable();+ const yScale = useYScale(yAxisId);+ const useDataTransitionPath = animate && chartPhase === 'ready';+ const { pathD: animatedPathD } = useAnimatedSeriesPath({+ chartPhase,+ curve,+ dataKey,+ durationMs: yDomainTweenDuration,+ enabled: useDataTransitionPath,+ innerWidth,+ renderData,+ xAccessor,+ xScale,+ yScale,+ });++ const phasePulseMode = resolveLineLoadingPulseMode(chartPhase);+ const pulseMode =+ loading === false+ ? null+ : (loadingPulseMode ?? (loading === true ? 'loop' : phasePulseMode));+ const showLoadingPulse = pulseMode != null;+ const [pulseEpoch, setPulseEpoch] = useState(0);+ const effectiveShowHighlight = showHighlight && !showLoadingPulse;++ const handleLoadingPulseComplete = useCallback(() => {+ onLoadingPulseCycleComplete?.();+ if (pulseMode === 'loop') {+ window.setTimeout(() => {+ setPulseEpoch((epoch) => epoch + 1);+ }, LINE_LOADING_LOOP_PAUSE_MS);+ return;+ }+ notifyLoadingPulseComplete?.();+ }, [notifyLoadingPulseComplete, onLoadingPulseCycleComplete, pulseMode]);++ const seriesIndex = useMemo(() => {+ const index = lines.findIndex((line) => line.dataKey === dataKey);+ return index >= 0 ? index : 0;+ }, [lines, dataKey]);const pathRef = useRef<SVGPathElement>(null);- const pathMetricsKey = `${renderData.length}:${innerWidth}:${dashFromIndex}:${animate}`;- const { pathLength, pathD } = usePathStrokeMetrics(pathRef, pathMetricsKey);+ const { pathLength, pathD } = usePathStrokeMetrics(pathRef, [+ renderData,+ innerWidth,+ innerHeight,+ yScale,+ dashFromIndex,+ animate,+ useDataTransitionPath ? animatedPathD : null,+ ]);const reactId = useId();const gradientId = `line-gradient-${dataKey}-${reactId}`;@@ -99,6 +305,7 @@ export function Line({},[dataKey, yScale]);+const hasValue = useCallback((d: Record<string, unknown>) => typeof d[dataKey] === 'number',[dataKey]@@ -108,12 +315,23 @@ export function Line({const fadeSides = resolveFadeSides(fadeEdges);const lineStroke = fadeSides.any ? `url(#${gradientId})` : stroke;const fadeStops = fadeSides.any ? fadeGradientStops(fadeSides) : null;+ const showSeriesStroke =+ chartPhase === 'revealing' ||+ chartPhase === 'ready' ||+ chartPhase === 'exitingReady';+ let visibleStroke = 'transparent';+ if (showSeriesStroke && !hasDashTail) {+ visibleStroke = lineStroke;+ }return (<>{fadeStops ? (<defs>- <linearGradient id={gradientId} x1="0%" x2="100%" y1="0%" y2="0%">+ <linearGradient+ id={gradientId}+ {...viewportFadeGradientAttrs(innerWidth)}+ >{fadeStops.map((stop) => (<stopkey={stop.offset}@@ -125,17 +343,23 @@ export function Line({</defs>) : null}- <SeriesHoverDim dimOpacity={0.3} enabled={showHighlight}>- <LinePath+ <SeriesHoverDim+ dimOpacity={0.3}+ enabled={effectiveShowHighlight}+ seriesIndex={seriesIndex}+ >+ <LineSeriesStroke+ animatedPathD={animatedPathD}curve={curve}- data={renderData}- defined={hasValue}- innerRef={pathRef}- stroke={hasDashTail ? 'transparent' : lineStroke}- strokeLinecap="round"+ getY={getY}+ hasValue={hasValue}+ pathRef={pathRef}+ renderData={renderData}strokeWidth={strokeWidth}- x={(d) => xScale(xAccessor(d)) ?? 0}- y={getY}+ useDataTransitionPath={useDataTransitionPath}+ visibleStroke={visibleStroke}+ xAccessor={xAccessor}+ xScale={xScale}/><SeriesDashTailOverlay@@ -164,12 +388,26 @@ export function Line({) : null}<SeriesHighlightLayer- enabled={showHighlight}+ enabled={effectiveShowHighlight}height={innerHeight}pathRef={pathRef}stroke={stroke}strokeWidth={strokeWidth}/>++ <LineLoadingOverlays+ curve={curve}+ handleLoadingPulseComplete={handleLoadingPulseComplete}+ innerWidth={innerWidth}+ loadingStroke={loadingStroke}+ loadingStrokeOpacity={loadingStrokeOpacity}+ loadingStyle={loadingStyle}+ pathD={pathD}+ pulseEpoch={pulseEpoch}+ pulseMode={pulseMode}+ showLoadingPulse={showLoadingPulse}+ strokeWidth={strokeWidth}+ /></>);}diff --git a/apps/start/src/components/charts/loading-sweep.tsx b/apps/start/src/components/charts/loading-sweep.tsxnew file mode 100644index 000000000..33b360db5--- /dev/null+++ b/apps/start/src/components/charts/loading-sweep.tsx@@ -0,0 +1,488 @@+'use client';++import { scaleLinear } from '@visx/scale';+import { AreaClosed, LinePath } from '@visx/shape';+import { motion, useReducedMotion } from 'motion/react';+import {+ useCallback,+ useEffect,+ useId,+ useMemo,+ useRef,+ useState,+} from 'react';+import { chartCssVars, useChartStable } from './chart-context';+import {+ LINE_LOADING_PULSE_EASE,+ LOADING_LABEL_EXIT_S,+} from './line-loading-timing';++/**+ * Shared "sweep" loading visuals. A soft diagonal shimmer band travels across a+ * self-contained skeleton silhouette on a loop, painted via an SVG mask. The+ * silhouette re-randomizes between passes (held steady during a pass, re-rolled+ * once the band clears the right edge) so it reads as live and still loading,+ * without warping mid-sweep. Used as the `loadingStyle="sweep"` alternative to+ * the traveling pulse on `<Line>` and `<Area>`, and as the skeleton for+ * `<BarChart status="loading">`.+ */++// CurveFactory type - simplified version compatible with visx+// biome-ignore lint/suspicious/noExplicitAny: d3 curve factory type+type CurveFactory = any;++/** One shimmer sweep, in seconds. */+const DEFAULT_SWEEP_DURATION_S = 2;+/** Sweep travel in objectBoundingBox space: off the left edge to off the right. */+const SWEEP_START_X = -1;+const SWEEP_END_X = 2;+/** Diagonal tilt of the shimmer band, in degrees. */+const SWEEP_ANGLE_DEG = 25;+const HEIGHT_MIN_PCT = 20;+const HEIGHT_MAX_PCT = 80;+const DEFAULT_POINT_COUNT = 14;+const BAR_CORNER_RADIUS = 2;+const DEFAULT_BAR_COUNT = 12;+const DEFAULT_FILL = 'var(--foreground)';+const DEFAULT_BAR_FILL_OPACITY = 0.45;+const LINE_STROKE_OPACITY = 0.55;+const AREA_FILL_TOP_OPACITY = 0.18;+const AREA_FILL_BOTTOM_OPACITY = 0.02;+/** Bar width as a fraction of its band (the rest is the inter-bar gap). */+const DEFAULT_BAR_FRACTION = 0.7;++// ─── Pure, SSR-safe helpers ──────────────────────────────────────────────+// Heights come from a deterministic hash of (index, seed), never+// `Math.random()`, so the first server render and first client render agree+// (no Next.js hydration mismatch). Re-randomizing only bumps the numeric seed+// on the client, after a sweep completes.++/** Cheap deterministic hash to a fractional part in [0, 1). */+function hashFract(n: number): number {+ const x = Math.sin(n) * 43_758.5453;+ return x - Math.floor(x);+}++/** Deterministic heights (percentages of the available height) for a seed. */+export function getSkeletonHeights(+ count: number,+ seed = 0,+ min = HEIGHT_MIN_PCT,+ max = HEIGHT_MAX_PCT+): number[] {+ const range = max - min;+ return Array.from(+ { length: count },+ (_, i) => min + Math.floor(hashFract((i + 1) * 12.9898 + seed) * range)+ );+}++/** Deterministic up/down (±1) per bar for the "center" baseline. */+function getSkeletonSigns(count: number, seed = 0): number[] {+ return Array.from({ length: count }, (_, i) =>+ hashFract((i + 1) * 78.233 + seed) < 0.5 ? -1 : 1+ );+}++/** Bell-curve opacity stops (sin squared) for the shimmer band's soft edges. */+function generateEasedGradientStops(+ steps = 17,+ minOpacity = 0.05,+ maxOpacity = 0.9+) {+ return Array.from({ length: steps }, (_, i) => {+ const t = i / (steps - 1);+ const eased = Math.sin(t * Math.PI) ** 2;+ const opacity = minOpacity + eased * (maxOpacity - minOpacity);+ return {+ offset: `${(t * 100).toFixed(0)}%`,+ opacity: Number(opacity.toFixed(3)),+ };+ });+}++// ─── Shared mask defs (`${chartId}-mask` is the mask id) ─────────────────────++function LoadingSweepMask({+ chartId,+ width,+ height,+ durationSeconds,+ onSweepComplete,+}: {+ chartId: string;+ width: number;+ height: number;+ durationSeconds: number;+ onSweepComplete: () => void;+}) {+ const gradientStops = useMemo(() => generateEasedGradientStops(), []);+ const lastXRef = useRef(SWEEP_START_X);++ const handleUpdate = useCallback(+ (latest: { x?: number }) => {+ const xValue = typeof latest.x === 'number' ? latest.x : SWEEP_START_X;+ // Re-roll once the band has cleared the visible area (crossed past 1),+ // so the silhouette never changes shape under the user's eye.+ if (xValue >= 1 && lastXRef.current < 1) {+ onSweepComplete();+ }+ lastXRef.current = xValue;+ },+ [onSweepComplete]+ );++ return (+ <>+ <linearGradient id={`${chartId}-grad`} x1="0" x2="1" y1="0" y2="0">+ {gradientStops.map(({ offset, opacity }) => (+ <stop+ key={offset}+ offset={offset}+ stopColor="white"+ stopOpacity={opacity}+ />+ ))}+ </linearGradient>+ <pattern+ height="1"+ id={`${chartId}-pattern`}+ patternContentUnits="objectBoundingBox"+ patternTransform={`rotate(${SWEEP_ANGLE_DEG})`}+ patternUnits="objectBoundingBox"+ width={3}+ x="0"+ y="0"+ >+ <motion.rect+ animate={{ x: SWEEP_END_X }}+ fill={`url(#${chartId}-grad)`}+ height="1"+ initial={{ x: SWEEP_START_X }}+ onUpdate={handleUpdate}+ transition={{+ duration: durationSeconds,+ ease: 'linear',+ repeat: Number.POSITIVE_INFINITY,+ repeatType: 'loop',+ }}+ width="1"+ y="0"+ />+ </pattern>+ <mask id={`${chartId}-mask`} maskUnits="userSpaceOnUse">+ <rect fill={`url(#${chartId}-pattern)`} height={height} width={width} />+ </mask>+ </>+ );+}++// ─── Line / Area loading sweep (its own re-randomizing silhouette) ───────────++export interface LineLoadingSweepProps {+ /** Curve factory from the host `<Line>` / `<Area>`, so the silhouette matches+ * the chart's interpolation (step, smooth, linear, …). */+ curve: CurveFactory;+ /** Fill the silhouette as an area (for `<Area>`); otherwise stroke only. */+ withArea?: boolean;+ /** Loading phase: `"loop"` (steady), `"exit"` (loading → ready), or `"enter"`+ * (ready → loading). Exit/enter fade the silhouette and then signal the chart+ * to continue its reveal. Default: `"loop"`. */+ mode?: 'loop' | 'exit' | 'enter';+ /** Fired when an exit/enter transition finishes, to advance the chart phase. */+ onTransitionComplete?: () => void;+ stroke?: string;+ strokeOpacity?: number;+ strokeWidth?: number;+ pointCount?: number;+ durationSeconds?: number;+}++/**+ * Renders a placeholder line/area silhouette (its own, not the chart's skeleton)+ * with the shimmer sweeping across it. The silhouette re-randomizes between+ * passes. Reads inner dimensions from chart context.+ */+export function LineLoadingSweep({+ curve,+ withArea = false,+ mode = 'loop',+ onTransitionComplete,+ stroke = chartCssVars.foreground,+ strokeOpacity = LINE_STROKE_OPACITY,+ strokeWidth = 2,+ pointCount = DEFAULT_POINT_COUNT,+ durationSeconds = DEFAULT_SWEEP_DURATION_S,+}: LineLoadingSweepProps) {+ const { innerWidth, innerHeight } = useChartStable();+ const reduceMotion = useReducedMotion();+ const reactId = useId();+ const chartId = `line-sweep-${reactId.replace(/[^a-zA-Z0-9_-]/g, '')}`;+ const isLoop = mode === 'loop';++ const [tick, setTick] = useState(0);+ // Re-randomize only while looping; hold the silhouette steady through a+ // transition so it fades out (or in) as one piece.+ const onSweepComplete = useCallback(() => {+ if (isLoop) {+ setTick((prev) => prev + 1);+ }+ }, [isLoop]);+ const heights = useMemo(+ () => getSkeletonHeights(pointCount, tick),+ [pointCount, tick]+ );++ // With reduced motion there is no fade to await, so signal the handoff+ // immediately or the phase machine would stall mid-transition.+ useEffect(() => {+ if (reduceMotion && !isLoop) {+ onTransitionComplete?.();+ }+ }, [reduceMotion, isLoop, onTransitionComplete]);++ if (innerWidth <= 0 || innerHeight <= 0 || heights.length < 2) {+ return null;+ }++ const xScale = scaleLinear({+ domain: [0, heights.length - 1],+ range: [0, innerWidth],+ });+ const yScale = scaleLinear({ domain: [0, 100], range: [innerHeight, 0] });+ const points = heights.map((value, index) => ({ index, value }));+ const getX = (d: { index: number }) => xScale(d.index);+ const getY = (d: { value: number }) => yScale(d.value);++ const silhouette = (+ <>+ {withArea ? (+ <AreaClosed+ curve={curve}+ data={points}+ fill={`url(#${chartId}-area)`}+ x={getX}+ y={getY}+ yScale={yScale}+ />+ ) : null}+ <LinePath+ curve={curve}+ data={points}+ fill="none"+ stroke={stroke}+ strokeLinecap="round"+ strokeOpacity={strokeOpacity}+ strokeWidth={strokeWidth}+ x={getX}+ y={getY}+ />+ </>+ );++ const areaGradient = withArea ? (+ <linearGradient id={`${chartId}-area`} x1="0" x2="0" y1="0" y2="1">+ <stop+ offset="0%"+ stopColor={stroke}+ stopOpacity={AREA_FILL_TOP_OPACITY}+ />+ <stop+ offset="100%"+ stopColor={stroke}+ stopOpacity={AREA_FILL_BOTTOM_OPACITY}+ />+ </linearGradient>+ ) : null;++ if (reduceMotion) {+ return (+ <>+ {areaGradient ? <defs>{areaGradient}</defs> : null}+ {silhouette}+ </>+ );+ }++ const maskUrl = `url(#${chartId}-mask)`;+ const defs = (+ <defs>+ {areaGradient}+ <LoadingSweepMask+ chartId={chartId}+ durationSeconds={durationSeconds}+ height={innerHeight}+ onSweepComplete={onSweepComplete}+ width={innerWidth}+ />+ </defs>+ );++ if (isLoop) {+ return (+ <>+ {defs}+ <g mask={maskUrl}>{silhouette}</g>+ </>+ );+ }++ // Transition: fade the swept silhouette out (exit) or in (enter), then hand+ // off to the chart so it can reveal the real series.+ return (+ <>+ {defs}+ <motion.g+ animate={{ opacity: mode === 'exit' ? 0 : 1 }}+ initial={{ opacity: mode === 'exit' ? 1 : 0 }}+ mask={maskUrl}+ onAnimationComplete={onTransitionComplete}+ transition={{+ duration: LOADING_LABEL_EXIT_S,+ ease: [...LINE_LOADING_PULSE_EASE],+ }}+ >+ {silhouette}+ </motion.g>+ </>+ );+}++LineLoadingSweep.displayName = 'LineLoadingSweep';++// ─── Bar loading skeleton (seeded bars under the sweep, inner coords) ─────────++function SkeletonBars({+ heights,+ signs,+ innerWidth,+ innerHeight,+ baseline,+ barFraction,+ fill,+ fillOpacity,+}: {+ heights: number[];+ signs: number[];+ innerWidth: number;+ innerHeight: number;+ baseline: 'bottom' | 'center';+ barFraction: number;+ fill: string;+ fillOpacity: number;+}) {+ const bandWidth = innerWidth / heights.length;+ const barW = bandWidth * barFraction;+ const xOffset = (bandWidth * (1 - barFraction)) / 2;+ const isCenter = baseline === 'center';+ const baselineY = isCenter ? innerHeight / 2 : innerHeight;+ const halfBarH = isCenter ? innerHeight / 2 : innerHeight;++ return (+ <>+ {heights.map((value, i) => {+ const sign = isCenter ? (signs[i] ?? 1) : 1;+ const barH = Math.max(1, halfBarH * (value / 100));+ const x = i * bandWidth + xOffset;+ const y = sign === 1 ? baselineY - barH : baselineY;+ return (+ <rect+ fill={fill}+ fillOpacity={fillOpacity}+ height={barH}+ key={`${x.toFixed(2)}-${value}`}+ rx={BAR_CORNER_RADIUS}+ width={barW}+ x={x}+ y={y}+ />+ );+ })}+ </>+ );+}++export interface BarLoadingSkeletonProps {+ innerWidth: number;+ innerHeight: number;+ /** Number of skeleton bars. Default: 12 */+ barCount?: number;+ /** Bar fill color. Default: `var(--foreground)` */+ fill?: string;+ /** Bar fill opacity. Default: 0.45 */+ fillOpacity?: number;+ /** Bars rise from the bottom or diverge from the vertical center. Default: `"bottom"` */+ baseline?: 'bottom' | 'center';+ /** Bar width as a fraction of its band (0–1). Default: 0.7 */+ barFraction?: number;+ /** One shimmer sweep, in seconds. Default: 2 */+ durationSeconds?: number;+}++/**+ * Skeleton bars masked by the shimmer sweep, re-randomizing between passes.+ * Rendered in the chart's inner coordinate space (origin at the inner top-left),+ * so a `BarChart` drops it inside its margin-translated group.+ */+export function BarLoadingSkeleton({+ innerWidth,+ innerHeight,+ barCount = DEFAULT_BAR_COUNT,+ fill = DEFAULT_FILL,+ fillOpacity = DEFAULT_BAR_FILL_OPACITY,+ baseline = 'bottom',+ barFraction = DEFAULT_BAR_FRACTION,+ durationSeconds = DEFAULT_SWEEP_DURATION_S,+}: BarLoadingSkeletonProps) {+ const reduceMotion = useReducedMotion();+ const reactId = useId();+ const chartId = `bar-sweep-${reactId.replace(/[^a-zA-Z0-9_-]/g, '')}`;+ const [tick, setTick] = useState(0);+ const onSweepComplete = useCallback(() => setTick((prev) => prev + 1), []);+ const heights = useMemo(+ () => getSkeletonHeights(barCount, tick),+ [barCount, tick]+ );+ const signs = useMemo(+ () => getSkeletonSigns(barCount, tick),+ [barCount, tick]+ );++ if (innerWidth <= 0 || innerHeight <= 0) {+ return null;+ }++ const bars = (+ <SkeletonBars+ barFraction={barFraction}+ baseline={baseline}+ fill={fill}+ fillOpacity={fillOpacity}+ heights={heights}+ innerHeight={innerHeight}+ innerWidth={innerWidth}+ signs={signs}+ />+ );++ if (reduceMotion) {+ return bars;+ }++ return (+ <>+ <defs>+ <LoadingSweepMask+ chartId={chartId}+ durationSeconds={durationSeconds}+ height={innerHeight}+ onSweepComplete={onSweepComplete}+ width={innerWidth}+ />+ </defs>+ <g mask={`url(#${chartId}-mask)`}>{bars}</g>+ </>+ );+}++BarLoadingSkeleton.displayName = 'BarLoadingSkeleton';diff --git a/apps/start/src/components/charts/markers/chart-markers.tsx b/apps/start/src/components/charts/markers/chart-markers.tsxindex c1a155620..2e29246a9 100644--- a/apps/start/src/components/charts/markers/chart-markers.tsx+++ b/apps/start/src/components/charts/markers/chart-markers.tsx@@ -1,7 +1,7 @@'use client';import { useCallback, useMemo } from 'react';-import { chartCssVars, useChart } from '../chart-context';+import { chartCssVars, useChart, useChartHover } from '../chart-context';import { type ChartMarker, MarkerGroup } from './marker-group';export interface ChartMarkersProps {@@ -31,7 +31,7 @@ export function MarkerTooltipContent({ markers }: MarkerTooltipContentProps) {const hiddenCount = markers.length - MAX_TOOLTIP_MARKERS;return (- <div className="mt-2 space-y-2 border-chart-tooltip-muted border-t pt-2">+ <div className="mt-2 space-y-2 border-t pt-2">{visibleMarkers.map((marker) => {const isClickable = !!(marker.onClick || marker.href);return (@@ -83,6 +83,12 @@ export function MarkerTooltipContent({ markers }: MarkerTooltipContentProps) {);}+/**+ * Date markers drawn above the plot. Markers sit 8px above the plot top and+ * the count badge reaches ~33px above it (at the default `size`), so keep+ * `margin.top` ≥ 36 if the chart's container clips its overflow. Chart SVGs+ * are `overflow: visible` and markers render outside the series reveal clip.+ */export function ChartMarkers({items,size = 28,@@ -190,7 +196,7 @@ export function ChartMarkers({// Hook to get active markers for tooltipexport function useActiveMarkers(items: ChartMarker[]) {- const { tooltipData } = useChart();+ const { tooltipData } = useChartHover();return useMemo(() => {if (!tooltipData) {diff --git a/apps/start/src/components/charts/op-date-pill.tsx b/apps/start/src/components/charts/op-date-pill.tsxindex 50afefc5b..2d16b5c06 100644--- a/apps/start/src/components/charts/op-date-pill.tsx+++ b/apps/start/src/components/charts/op-date-pill.tsx@@ -61,22 +61,25 @@ function OPDatePillInner({interval?: IInterval;tooltipData: TooltipData;}) {- const { data, xAccessor, margin, width } = useChartStable();+ const { data, xAccessor, margin, width, barScale, barXAccessor } =+ 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]- );+ const label = useMemo(() => {+ // A category bar chart has no dates; its x value is the category name.+ if (barScale && barXAccessor) {+ return barXAccessor(tooltipData.point);+ }+ return formatPillDate(+ xAccessor(tooltipData.point),+ interval ?? 'day',+ data,+ xAccessor+ );+ }, [tooltipData, data, xAccessor, interval, barScale, barXAccessor]);// Stable across hovers — depends only on chart dimensions.const maxWidth = useMemo(@@ -133,7 +136,8 @@ function formatPillDate(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 lastPoint = data.at(-1);+ const last = lastPoint ? xAccessor(lastPoint) : date;const spanHours = Math.max(0, differenceInHours(last, first));const dayMonth = `${SHORT_MONTHS[date.getMonth()]} ${date.getDate()}`;diff --git a/apps/start/src/components/charts/op-line-chart.tsx b/apps/start/src/components/charts/op-line-chart.tsxnew file mode 100644index 000000000..401ea7704--- /dev/null+++ b/apps/start/src/components/charts/op-line-chart.tsx@@ -0,0 +1,119 @@+import type { IInterval } from '@openpanel/core/modules/report/report.constants';+import { curveMonotoneX } from 'd3-shape';+import { useCallback } from 'react';+import { Grid } from './grid';+import { Line, LineChart } from './line-chart';+import { OPChartTooltip, type OPTooltipRow } from './op-tooltip';+import { XAxis } from './x-axis';+import { YAxis } from './y-axis';+import { formatDateInterval } from '@/hooks/use-format-date-interval';+import { useNumber } from '@/hooks/use-numer-formatter';++const MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };+const STROKE_WIDTH = 2;++export interface OPLineChartSeries {+ dataKey: string;+ label: string;+ color: string;+ /** Series on their own scale stay readable next to a much larger one. */+ yAxisId?: string;+ /** Tooltip value format. Default: the full locale number. */+ format?: (value: number) => string;+}++export type OPLineChartPoint = Record<string, unknown> & { date: string };++interface OPLineChartProps<T extends OPLineChartPoint> {+ data: T[];+ series: OPLineChartSeries[];+ interval: IInterval;+ height: number;+ /** Fixed y domain for the primary axis. */+ yDomain?: [number, number];+ /** Smallest value at the top, for "lower is better" metrics. */+ yReversed?: boolean;+ formatAxisValue?: (value: number) => string;+}++/** A small card line chart: a few date series, a left axis and the shared tooltip. */+export function OPLineChart<T extends OPLineChartPoint>({+ data,+ series,+ interval,+ height,+ yDomain,+ yReversed,+ formatAxisValue,+}: OPLineChartProps<T>) {+ const number = useNumber();+ const formatDateLabel = useCallback(+ (date: Date) => formatDateInterval({ interval, date, short: true }),+ [interval]+ );+ const rows = useCallback(+ (point: T): OPTooltipRow[] =>+ series.map((serie) => {+ const value = point[serie.dataKey];+ return {+ color: serie.color,+ label: serie.label,+ value: typeof value === 'number' ? value : null,+ format: serie.format ?? number.format,+ };+ }),+ [series, number.format]+ );++ return (+ <LineChart+ animationDuration={0}+ aspectRatio="auto"+ data={data}+ formatDateLabel={formatDateLabel}+ margin={MARGIN}+ style={{ height }}+ xDataKey="date"+ yDomain={yDomain}+ yReversed={yReversed}+ >+ <Grid horizontal />+ <YAxis formatValue={formatAxisValue ?? number.short} />+ <XAxis />+ {series.map((serie) => (+ <Line+ animate={false}+ curve={curveMonotoneX}+ dataKey={serie.dataKey}+ key={serie.dataKey}+ stroke={serie.color}+ strokeWidth={STROKE_WIDTH}+ yAxisId={serie.yAxisId}+ />+ ))}+ <OPChartTooltip<T>+ interval={interval}+ rows={rows}+ showCrosshair+ showDots+ />+ </LineChart>+ );+}++/** Inline legend for a card header, one swatch per series. */+export function OPLineChartLegend({ series }: { series: OPLineChartSeries[] }) {+ return (+ <div className="flex items-center gap-4 text-muted-foreground text-xs">+ {series.map((serie) => (+ <span className="flex items-center gap-1.5" key={serie.dataKey}>+ <span+ className="h-0.5 w-3 rounded-full"+ style={{ backgroundColor: serie.color }}+ />+ {serie.label}+ </span>+ ))}+ </div>+ );+}diff --git a/apps/start/src/components/charts/op-tooltip.tsx b/apps/start/src/components/charts/op-tooltip.tsxindex 9eab395bd..a21f2eee7 100644--- a/apps/start/src/components/charts/op-tooltip.tsx+++ b/apps/start/src/components/charts/op-tooltip.tsx@@ -4,6 +4,7 @@ import { getPreviousMetric } from '../../utils/previous-metric';import { PreviousDiffIndicatorPure } from '../report-chart/common/previous-diff-indicator';import { useChart } from './chart-context';import type { ChartMarker } from './markers/marker-group';+import { OPDatePill } from './op-date-pill';import { type OPReferenceItem, toChartMarkers } from './op-references';import type { OPReferrerSpikeItem } from './op-referrer-spikes';import { ChartTooltip, type ChartTooltipProps } from './tooltip/chart-tooltip';@@ -29,6 +30,8 @@ export interface OPTooltipRow {value?: number | null;/** How to format `value`. Default: 'count' (locale string). */unit?: OPTooltipUnit;+ /** Formats `value` and `previous`; wins over `unit`. */+ format?: (value: number) => string;/** Optional previous-period value — shown as "(prev)" next to value */previous?: number | null;/** Whether higher previous is better (e.g. bounce rate is inverted) */@@ -66,6 +69,8 @@ export interface OPChartTooltipProps<T extends Record<string, unknown>>referencesLimit?: number;/** Auto-detected referrer spikes; the matching bucket's spike is shown below. */spikes?: OPReferrerSpikeItem[] | null;+ /** Show the hovered date (or category) in a pill on the x axis. Default: true. */+ datePill?: boolean;}export function OPChartTooltip<T extends Record<string, unknown>>({@@ -77,6 +82,7 @@ export function OPChartTooltip<T extends Record<string, unknown>>({references,referencesLimit = 3,spikes,+ datePill = true,...rest}: OPChartTooltipProps<T>) {const referenceMarkers = useMemo(@@ -85,22 +91,26 @@ export function OPChartTooltip<T extends Record<string, unknown>>({);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}- />- )}- />+ <>+ <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}+ />+ )}+ showDatePill={false}+ />+ {datePill && <OPDatePill interval={interval} />}+ </>);}@@ -374,10 +384,7 @@ export function OPTooltipCard({}) {return (<div- className={cn(- 'col gap-2 rounded-xl border border-border/60 p-3 text-foreground shadow-xl',- className- )}+ className={cn('col gap-2 p-3 text-foreground', className)}style={style}>{children}@@ -389,10 +396,13 @@ 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 showPrev = prev != null;+ // A change from zero has no percentage.+ const showDiff = row.showDiff !== false && showPrev && prev !== 0;const diff =showDiff && hasValue ? getPreviousMetric(row.value!, prev) : null;+ const formatValue = (value: number) =>+ row.format ? row.format(value) : formatOPValue(value, row.unit, number);return (<div className="flex gap-2">@@ -407,10 +417,10 @@ function OPTooltipRowView({ row }: { row: OPTooltipRow }) {{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>+ <span>{formatValue(row.value!)}</span>{showPrev && (<span className="text-muted-foreground">- ({formatOPValue(prev, row.unit, number)})+ ({formatValue(prev)})</span>)}{row.percentage != null && (diff --git a/apps/start/src/components/charts/path-stroke-utils.ts b/apps/start/src/components/charts/path-stroke-utils.tsindex d928ae2b3..6723ed312 100644--- a/apps/start/src/components/charts/path-stroke-utils.ts+++ b/apps/start/src/components/charts/path-stroke-utils.ts@@ -1,53 +1,46 @@+// biome-ignore-all lint/correctness/useExhaustiveDependencies: usePathStrokeMetrics intentionally accepts caller-controlled depsimport { 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;+interface PathStrokeMetrics {+ pathD: string | null;+ pathLength: number;}+const EMPTY_METRICS: PathStrokeMetrics = { pathD: null, pathLength: 0 };++/**+ * Caller passes the references that drive the rendered path (renderData,+ * innerWidth, etc.) as `deps`. A stringified summary like+ * `${renderData.length}:${innerWidth}` is *not* safe here — same-length+ * in-place mutations of `renderData` keep the summary identical, so the+ * effect would never re-fire and `pathD`/`pathLength` would stay frozen on+ * the previous geometry (the area fill repaints from `renderData` directly+ * and would diverge from the stroke). The y-scale belongs in `deps` too: it+ * is rebuilt on every frame of the y-domain tween and on height changes, and+ * the dashed-tail stroke is drawn from the measured `pathD`, so a stale+ * measurement leaves the stroke behind while the fill follows the scale.+ */export function usePathStrokeMetrics(pathRef: RefObject<SVGPathElement | null>,- remeasureKey: string-) {- const [pathLength, setPathLength] = useState(0);- const [pathD, setPathD] = useState<string | null>(null);+ deps: readonly unknown[]+): PathStrokeMetrics {+ const [metrics, setMetrics] = useState<PathStrokeMetrics>(EMPTY_METRICS);- // biome-ignore lint/correctness/useExhaustiveDependencies: remeasure when series geometry changesuseEffect(() => {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]);+ const len = d ? path.getTotalLength() : 0;+ setMetrics((prev) =>+ prev.pathD === d && prev.pathLength === len+ ? prev+ : { pathD: d, pathLength: len }+ );+ }, deps);- return { pathLength, pathD };+ return metrics;}export function resolveDashTailBounds(diff --git a/apps/start/src/components/charts/pattern-area.tsx b/apps/start/src/components/charts/pattern-area.tsxindex e188af089..13e634510 100644--- a/apps/start/src/components/charts/pattern-area.tsx+++ b/apps/start/src/components/charts/pattern-area.tsx@@ -27,12 +27,12 @@ export function PatternArea({fill,curve = curveMonotoneX,}: PatternAreaProps) {- const { data, xScale, yScale, xAccessor } = useChartStable();+ const { renderData, xScale, yScale, xAccessor } = useChartStable();return (<AreaClosedcurve={curve}- data={data}+ data={renderData}fill={fill}x={(d) => xScale(xAccessor(d)) ?? 0}y={(d) => {diff --git a/apps/start/src/components/charts/pattern-preset.tsx b/apps/start/src/components/charts/pattern-preset.tsxnew file mode 100644index 000000000..23419d62f--- /dev/null+++ b/apps/start/src/components/charts/pattern-preset.tsx@@ -0,0 +1,186 @@+'use client';++import type { ReactNode } from 'react';+import { PatternCircles, PatternLines } from './visx-pattern';++export const PATTERN_PRESET_IDS = [+ 'none',+ 'diagonal',+ 'horizontal',+ 'vertical',+ 'cross',+ 'dots',+ 'circles',+ 'accent',+] as const;++export type PatternPresetId = (typeof PATTERN_PRESET_IDS)[number];++export interface PatternPresetOptions {+ color?: string;+ scale?: number;+ strokeWidth?: number;+ radius?: number;+ complement?: boolean;+ fill?: string;+ /** Dot grid only — when false, render hollow dots (stroke only). Default: true */+ dotFill?: boolean;+ tileBackground?: string;+}++/** Presets rendered with @visx/pattern `PatternCircles`. */+export function isCirclePattern(preset: PatternPresetId): boolean {+ return preset === 'circles' || preset === 'dots';+}++/** @deprecated Use `isCirclePattern`. */+export function isCirclesPattern(preset: PatternPresetId): boolean {+ return isCirclePattern(preset);+}++export function patternPresetTileSize(+ preset: PatternPresetId,+ scale = 1+): { width: number; height: number; strokeWidth: number } {+ let base = { width: 6, height: 6, strokeWidth: 1 };+ if (preset === 'dots') {+ base = { width: 10, height: 10, strokeWidth: 0 };+ } else if (preset === 'cross') {+ base = { width: 8, height: 8, strokeWidth: 1 };+ } else if (preset === 'circles') {+ base = { width: 6, height: 6, strokeWidth: 1 };+ }++ return {+ width: base.width * scale,+ height: base.height * scale,+ strokeWidth: base.strokeWidth * scale,+ };+}++function renderPatternCircles(+ preset: 'dots' | 'circles',+ _id: string,+ color: string,+ common: {+ id: string;+ height: number;+ width: number;+ strokeWidth: number;+ background?: string;+ },+ options: PatternPresetOptions,+ scale: number+) {+ const isDotGrid = preset === 'dots';+ const radius =+ options.radius ?? (isDotGrid ? Math.max(0.5, 1.5 * scale) : 2 * scale);+ const dotFillEnabled = options.dotFill !== false;++ if (isDotGrid) {+ const dotFill = dotFillEnabled ? options.fill || color : undefined;+ return (+ <PatternCircles+ {...common}+ complement={options.complement}+ fill={dotFill}+ radius={radius}+ stroke={dotFillEnabled && options.fill ? undefined : color}+ strokeWidth={+ dotFillEnabled && !options.fill+ ? (options.strokeWidth ?? 0)+ : (options.strokeWidth ?? 1)+ }+ />+ );+ }++ return (+ <PatternCircles+ {...common}+ complement={options.complement}+ fill={options.fill || undefined}+ radius={radius}+ stroke={color}+ strokeWidth={options.strokeWidth ?? common.strokeWidth}+ />+ );+}++/** Renders a @visx/pattern definition node for the given preset. */+export function renderPatternPreset(+ preset: PatternPresetId,+ id: string,+ options: PatternPresetOptions = {}+): ReactNode {+ if (preset === 'none') {+ return null;+ }++ const color = options.color ?? 'var(--chart-1)';+ const scale = options.scale ?? 1;+ const tile = patternPresetTileSize(preset, scale);+ const common = {+ id,+ height: tile.height,+ width: tile.width,+ strokeWidth: tile.strokeWidth,+ ...(options.tileBackground ? { background: options.tileBackground } : {}),+ };++ if (preset === 'dots' || preset === 'circles') {+ return renderPatternCircles(preset, id, color, common, options, scale);+ }++ const strokeWidth = options.strokeWidth ?? tile.strokeWidth;++ switch (preset) {+ case 'diagonal':+ return (+ <PatternLines+ {...common}+ orientation={['diagonal']}+ stroke={color}+ strokeWidth={strokeWidth}+ />+ );+ case 'horizontal':+ return (+ <PatternLines+ {...common}+ orientation={['horizontal']}+ stroke={color}+ strokeWidth={strokeWidth}+ />+ );+ case 'vertical':+ return (+ <PatternLines+ {...common}+ orientation={['vertical']}+ stroke={color}+ strokeWidth={strokeWidth}+ />+ );+ case 'cross':+ return (+ <PatternLines+ {...common}+ orientation={['diagonal', 'diagonalRightToLeft']}+ stroke={color}+ strokeWidth={strokeWidth}+ />+ );+ case 'accent':+ return (+ <PatternLines+ {...common}+ orientation={['diagonal']}+ stroke="#e879f9"+ strokeWidth={strokeWidth}+ />+ );+ default:+ return null;+ }+}diff --git a/apps/start/src/components/charts/patterns/LICENSE-visx-pattern b/apps/start/src/components/charts/patterns/LICENSE-visx-patternnew file mode 100644index 000000000..3ea864f49--- /dev/null+++ b/apps/start/src/components/charts/patterns/LICENSE-visx-pattern@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2017-2018 Harrison Shoff++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/apps/start/src/components/charts/patterns/circles.tsx b/apps/start/src/components/charts/patterns/circles.tsxnew file mode 100644index 000000000..64a7bc97f--- /dev/null+++ b/apps/start/src/components/charts/patterns/circles.tsx@@ -0,0 +1,87 @@+/**+ * Ported from @visx/pattern 4.0.0 (https://github.com/airbnb/visx).+ * MIT License — Copyright (c) 2017-2018 Harrison Shoff. See ./LICENSE-visx-pattern.+ */++import { Pattern } from './pattern';+import { cn } from '@/lib/utils';++export interface PatternCirclesProps {+ /** Unique id for the pattern. */+ id: string;+ /** Width of the pattern element. */+ width: number;+ /** Height of the pattern element. */+ height: number;+ /** Radius of the pattern circles. */+ radius?: number;+ /** Fill applied to circles. */+ fill?: string;+ /** className applied to circles. */+ className?: string;+ /** stroke applied to circles. */+ stroke?: string;+ /** strokeWidth applied to circles. */+ strokeWidth?: number | string;+ /** strokeDasharray applied to circles. */+ strokeDasharray?: number | string;+ /** Whether to fill in circles within the pattern gaps to increase pattern density. */+ complement?: boolean;+ /** Background color applied behind circles. */+ background?: string;+}++export function Circles({+ id,+ width,+ height,+ radius = 2,+ fill,+ stroke,+ strokeWidth,+ strokeDasharray,+ background,+ complement = false,+ className,+}: PatternCirclesProps) {+ let corners: [number, number][] | undefined;+ if (complement) {+ corners = [+ [0, 0],+ [0, height],+ [width, 0],+ [width, height],+ ];+ }+ return (+ <Pattern height={height} id={id} width={width}>+ {!!background && <rect fill={background} height={height} width={width} />}+ <circle+ className={cn('visx-pattern-circle', className)}+ cx={width / 2}+ cy={height / 2}+ fill={fill}+ r={radius}+ stroke={stroke}+ strokeDasharray={strokeDasharray}+ strokeWidth={strokeWidth}+ />+ {corners?.map(([cornerX, cornerY]) => (+ <circle+ className={cn(+ 'visx-pattern-circle visx-pattern-circle-complement',+ className+ )}+ cx={cornerX}+ cy={cornerY}+ fill={fill}+ key={`${id}-complement-${cornerX}-${cornerY}`}+ r={radius}+ stroke={stroke}+ strokeDasharray={strokeDasharray}+ strokeWidth={strokeWidth}+ />+ ))}+ </Pattern>+ );+}diff --git a/apps/start/src/components/charts/patterns/constants.ts b/apps/start/src/components/charts/patterns/constants.tsnew file mode 100644index 000000000..6dcd2bc2a--- /dev/null+++ b/apps/start/src/components/charts/patterns/constants.ts@@ -0,0 +1,14 @@+/**+ * Ported from @visx/pattern 4.0.0 (https://github.com/airbnb/visx).+ * MIT License — Copyright (c) 2017-2018 Harrison Shoff. See ./LICENSE-visx-pattern.+ */++export const PatternOrientation = {+ horizontal: 'horizontal',+ vertical: 'vertical',+ diagonal: 'diagonal',+ diagonalRightToLeft: 'diagonalRightToLeft',+} as const;++export type PatternOrientationType =+ (typeof PatternOrientation)[keyof typeof PatternOrientation];diff --git a/apps/start/src/components/charts/patterns/hexagons.tsx b/apps/start/src/components/charts/patterns/hexagons.tsxnew file mode 100644index 000000000..df30d5cda--- /dev/null+++ b/apps/start/src/components/charts/patterns/hexagons.tsx@@ -0,0 +1,64 @@+/**+ * Ported from @visx/pattern 4.0.0 (https://github.com/airbnb/visx).+ * MIT License — Copyright (c) 2017-2018 Harrison Shoff. See ./LICENSE-visx-pattern.+ */++import { Path } from './path';+import { cn } from '@/lib/utils';++export interface PatternHexagonsProps {+ /** Unique id for the pattern. */+ id: string;+ /** Height of the pattern element. */+ height: number;+ /** Size of the hexagon shape. */+ size?: number;+ /** Fill applied to hexagons. */+ fill?: string;+ /** className applied to hexagon path element. */+ className?: string;+ /** Background color applied behind hexagons. */+ background?: string;+ /** Stroke color applied to hexagon paths. */+ stroke?: string;+ /** strokeWidth applied to hexagon paths. */+ strokeWidth?: number | string;+ /** strokeDasharray applied to hexagon paths. */+ strokeDasharray?: string | number;+ /** strokeLinecap applied to hexagon paths. */+ strokeLinecap?: 'square' | 'butt' | 'round' | 'inherit';+ /** shapeRendering applied to hexagon paths. */+ shapeRendering?: string | number;+}++export function Hexagons({+ id,+ height,+ fill,+ stroke,+ strokeWidth,+ strokeDasharray,+ strokeLinecap,+ shapeRendering,+ background,+ className,+ size = 3,+}: PatternHexagonsProps) {+ const sqrtSize = Math.sqrt(size);+ return (+ <Path+ background={background}+ className={cn('visx-pattern-hexagon', className)}+ fill={fill}+ height={sqrtSize}+ id={id}+ path={`M ${height},0 l ${height},0 l ${height / 2},${(height * sqrtSize) / 2} l ${-height / 2},${(height * sqrtSize) / 2} l ${-height},0 l ${-height / 2},${(-height * sqrtSize) / 2} Z M 0,${(height * sqrtSize) / 2} l ${height / 2},0 M ${3 * height},${(height * sqrtSize) / 2} l ${-height / 2},0`}+ shapeRendering={shapeRendering}+ stroke={stroke}+ strokeDasharray={strokeDasharray}+ strokeLinecap={strokeLinecap}+ strokeWidth={strokeWidth}+ width={size}+ />+ );+}diff --git a/apps/start/src/components/charts/patterns/index.ts b/apps/start/src/components/charts/patterns/index.tsnew file mode 100644index 000000000..4dd33d107--- /dev/null+++ b/apps/start/src/components/charts/patterns/index.ts@@ -0,0 +1,19 @@+/**+ * Ported from @visx/pattern 4.0.0 (https://github.com/airbnb/visx).+ * MIT License — Copyright (c) 2017-2018 Harrison Shoff. See ./LICENSE-visx-pattern.+ */++export type { PatternCirclesProps } from './circles';+export { Circles as PatternCircles } from './circles';+export type { PatternOrientationType } from './constants';+export { PatternOrientation } from './constants';+export type { PatternHexagonsProps } from './hexagons';+export { Hexagons as PatternHexagons } from './hexagons';+export type { PatternLinesProps } from './lines';+export { Lines as PatternLines } from './lines';+export type { PatternPathProps } from './path';+export { Path as PatternPath } from './path';+export type { PatternProps } from './pattern';+export { Pattern } from './pattern';+export type { PatternWavesProps } from './waves';+export { Waves as PatternWaves } from './waves';diff --git a/apps/start/src/components/charts/patterns/lines.tsx b/apps/start/src/components/charts/patterns/lines.tsxnew file mode 100644index 000000000..d368d2624--- /dev/null+++ b/apps/start/src/components/charts/patterns/lines.tsx@@ -0,0 +1,98 @@+/**+ * Ported from @visx/pattern 4.0.0 (https://github.com/airbnb/visx).+ * MIT License — Copyright (c) 2017-2018 Harrison Shoff. See ./LICENSE-visx-pattern.+ */++import { PatternOrientation, type PatternOrientationType } from './constants';+import { Pattern } from './pattern';+import { cn } from '@/lib/utils';++export function pathForOrientation({+ height,+ orientation,+}: {+ height: number;+ orientation: PatternOrientationType;+}): string {+ switch (orientation) {+ case PatternOrientation.horizontal:+ return `M 0,${height / 2} l ${height},0`;+ case PatternOrientation.diagonal:+ return `M 0,${height} l ${height},${-height} M ${-height / 4},${height / 4} l ${height / 2},${-height / 2}+ M ${(3 / 4) * height},${(5 / 4) * height} l ${height / 2},${-height / 2}`;+ case PatternOrientation.diagonalRightToLeft:+ return `M 0,0 l ${height},${height}+ M ${-height / 4},${(3 / 4) * height} l ${height / 2},${height / 2}+ M ${(3 / 4) * height},${-height / 4} l ${height / 2},${height / 2}`;+ default:+ return `M ${height / 2}, 0 l 0, ${height}`;+ }+}++export interface PatternLinesProps {+ /** Unique id for the pattern. */+ id: string;+ /** Width of the pattern element. */+ width: number;+ /** Height of the pattern element. */+ height: number;+ /** className applied to line path element. */+ className?: string;+ /** Background color applied behind lines. */+ background?: string;+ /** Stroke color applied to path elements. */+ stroke?: string;+ /** strokeWidth applied to path elements. */+ strokeWidth?: number | string;+ /** strokeDasharray applied to path elements. */+ strokeDasharray?: string | number;+ /** strokeLinecap applied to path elements. */+ strokeLinecap?: 'square' | 'butt' | 'round' | 'inherit';+ /** shapeRendering applied to path elements. */+ shapeRendering?: string | number;+ /** Array of orientations to render (can mix multiple). */+ orientation?: PatternOrientationType[];+}++export function Lines({+ id,+ width,+ height,+ stroke,+ strokeWidth,+ strokeDasharray,+ strokeLinecap = 'square',+ shapeRendering = 'auto',+ orientation = ['vertical'],+ background,+ className,+}: PatternLinesProps) {+ const orientations = Array.isArray(orientation)+ ? orientation+ : [orientation as PatternOrientationType];+ return (+ <Pattern height={height} id={id} width={width}>+ {!!background && (+ <rect+ className={cn('visx-pattern-line-background')}+ fill={background}+ height={height}+ width={width}+ />+ )}+ {orientations.map((o, i) => (+ <path+ className={cn('visx-pattern-line', className)}+ d={pathForOrientation({ orientation: o, height })}+ // biome-ignore lint/suspicious/noArrayIndexKey: duplicate orientations are allowed; matches upstream key.+ key={`visx-${id}-line-${o}-${i}`}+ shapeRendering={shapeRendering}+ stroke={stroke}+ strokeDasharray={strokeDasharray}+ strokeLinecap={strokeLinecap}+ strokeWidth={strokeWidth}+ />+ ))}+ </Pattern>+ );+}diff --git a/apps/start/src/components/charts/patterns/path.tsx b/apps/start/src/components/charts/patterns/path.tsxnew file mode 100644index 000000000..05309f78b--- /dev/null+++ b/apps/start/src/components/charts/patterns/path.tsx@@ -0,0 +1,65 @@+/**+ * Ported from @visx/pattern 4.0.0 (https://github.com/airbnb/visx).+ * MIT License — Copyright (c) 2017-2018 Harrison Shoff. See ./LICENSE-visx-pattern.+ */++import { Pattern } from './pattern';+import { cn } from '@/lib/utils';++export interface PatternPathProps {+ /** Unique id for the pattern. */+ id: string;+ /** Width of the pattern element. */+ width: number;+ /** Height of the pattern element. */+ height: number;+ /** d attribute of the path element */+ path?: string;+ /** fill color applied to path. */+ fill?: string;+ /** className applied to the path element. */+ className?: string;+ /** Background color applied behind path. */+ background?: string;+ /** Stroke color applied to path. */+ stroke?: string;+ /** strokeWidth applied to path. */+ strokeWidth?: number | string;+ /** strokeDasharray applied to path. */+ strokeDasharray?: string | number;+ /** strokeLinecap applied to path. */+ strokeLinecap?: 'square' | 'butt' | 'round' | 'inherit';+ /** shapeRendering applied to path. */+ shapeRendering?: string | number;+}++export function Path({+ id,+ width,+ height,+ path,+ fill = 'transparent',+ stroke,+ strokeWidth,+ strokeDasharray,+ strokeLinecap = 'square',+ shapeRendering = 'auto',+ background,+ className,+}: PatternPathProps) {+ return (+ <Pattern height={height} id={id} width={width}>+ {!!background && <rect fill={background} height={height} width={width} />}+ <path+ className={cn('visx-pattern-path', className)}+ d={path}+ fill={fill}+ shapeRendering={shapeRendering}+ stroke={stroke}+ strokeDasharray={strokeDasharray}+ strokeLinecap={strokeLinecap}+ strokeWidth={strokeWidth}+ />+ </Pattern>+ );+}diff --git a/apps/start/src/components/charts/patterns/pattern.tsx b/apps/start/src/components/charts/patterns/pattern.tsxnew file mode 100644index 000000000..d93f8cc3f--- /dev/null+++ b/apps/start/src/components/charts/patterns/pattern.tsx@@ -0,0 +1,32 @@+/**+ * Ported from @visx/pattern 4.0.0 (https://github.com/airbnb/visx).+ * MIT License — Copyright (c) 2017-2018 Harrison Shoff. See ./LICENSE-visx-pattern.+ */++import type { ReactNode } from 'react';++export interface PatternProps {+ /** Unique id of the pattern element. */+ id: string;+ /** Width of the pattern. */+ width: number;+ /** Height of the pattern. */+ height: number;+ /** Children of pattern element to render. */+ children: ReactNode;+}++export function Pattern({ id, width, height, children }: PatternProps) {+ return (+ <defs>+ <pattern+ height={height}+ id={id}+ patternUnits="userSpaceOnUse"+ width={width}+ >+ {children}+ </pattern>+ </defs>+ );+}diff --git a/apps/start/src/components/charts/patterns/waves.tsx b/apps/start/src/components/charts/patterns/waves.tsxnew file mode 100644index 000000000..b9c7a4b4d--- /dev/null+++ b/apps/start/src/components/charts/patterns/waves.tsx@@ -0,0 +1,66 @@+/**+ * Ported from @visx/pattern 4.0.0 (https://github.com/airbnb/visx).+ * MIT License — Copyright (c) 2017-2018 Harrison Shoff. See ./LICENSE-visx-pattern.+ */++import { Path } from './path';+import { cn } from '@/lib/utils';++export interface PatternWavesProps {+ /** Unique id for the pattern. */+ id: string;+ /** Width of the pattern element. */+ width: number;+ /** Height of the pattern element. */+ height: number;+ /** fill color applied to path. */+ fill?: string;+ /** className applied to the path element. */+ className?: string;+ /** Background color applied behind path. */+ background?: string;+ /** Stroke color applied to path. */+ stroke?: string;+ /** strokeWidth applied to path. */+ strokeWidth?: number | string;+ /** strokeDasharray applied to path. */+ strokeDasharray?: string | number;+ /** strokeLinecap applied to path. */+ strokeLinecap?: 'square' | 'butt' | 'round' | 'inherit';+ /** shapeRendering applied to path. */+ shapeRendering?: string | number;+}++export function Waves({+ id,+ width,+ height,+ fill,+ stroke,+ strokeWidth,+ strokeDasharray,+ strokeLinecap,+ shapeRendering,+ background,+ className,+}: PatternWavesProps) {+ return (+ <Path+ background={background}+ className={cn('visx-pattern-wave', className)}+ fill={fill}+ height={height}+ id={id}+ path={`M 0 ${height / 2} c ${height / 8} ${-height / 4} , ${(height * 3) / 8} ${-height / 4} , ${height / 2} 0+ c ${height / 8} ${height / 4} , ${(height * 3) / 8} ${height / 4} , ${height / 2} 0 M ${-height / 2} ${height / 2}+ c ${height / 8} ${height / 4} , ${(height * 3) / 8} ${height / 4} , ${height / 2} 0 M ${height} ${height / 2}+ c ${height / 8} ${-height / 4} , ${(height * 3) / 8} ${-height / 4} , ${height / 2} 0`}+ shapeRendering={shapeRendering}+ stroke={stroke}+ strokeDasharray={strokeDasharray}+ strokeLinecap={strokeLinecap}+ strokeWidth={strokeWidth}+ width={width}+ />+ );+}diff --git a/apps/start/src/components/charts/pie-center-shell.tsx b/apps/start/src/components/charts/pie-center-shell.tsxnew file mode 100644index 000000000..cf39795c7--- /dev/null+++ b/apps/start/src/components/charts/pie-center-shell.tsx@@ -0,0 +1,175 @@+'use client';++import { pie as d3Pie } from 'd3-shape';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { PieCenter, type PieCenterProps } from './pie-center';+import {+ defaultPieColors,+ type PieArcData,+ type PieContextValue,+ type PieData,+ PieProvider,+} from './pie-context';++const SHELL_HOVER_OFFSET = 10;++export type PieCenterShellProps = Omit<PieCenterProps, 'children'> & {+ /** Value shown with NumberFlow (same role as pie total when not hovering) */+ centerValue: number;+ /** Square reference size for pie context (matches `PieChart` `size`) */+ contextSize: number;+ /** Inner radius in px — must be > 0 so `PieCenter` renders */+ innerRadiusPx: number;+ /**+ * When true (default), the first paint uses `0` then updates to `centerValue`+ * on the next frame so NumberFlow can run an entrance transition. Subsequent+ * `centerValue` updates animate as usual.+ */+ animateEntrance?: boolean;+};++/**+ * Renders {@link PieCenter} with a minimal {@link PieProvider} so you can reuse+ * the same center layout as a donut pie without mounting slices or a full {@link PieChart}.+ */+export function PieCenterShell({+ centerValue,+ contextSize,+ innerRadiusPx,+ animateEntrance = true,+ ...pieCenterProps+}: PieCenterShellProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const introStartedRef = useRef(false);++ const [flowTotal, setFlowTotal] = useState(() =>+ animateEntrance ? 0 : centerValue+ );++ useEffect(() => {+ if (!animateEntrance) {+ setFlowTotal(centerValue);+ return;+ }++ if (!introStartedRef.current) {+ introStartedRef.current = true;+ setFlowTotal(0);+ let innerRaf = 0;+ const outerRaf = requestAnimationFrame(() => {+ innerRaf = requestAnimationFrame(() => setFlowTotal(centerValue));+ });+ return () => {+ cancelAnimationFrame(outerRaf);+ cancelAnimationFrame(innerRaf);+ introStartedRef.current = false;+ };+ }++ setFlowTotal(centerValue);+ }, [animateEntrance, centerValue]);++ const data: PieData[] = useMemo(+ () => [{ label: '_pieCenterShell', value: Math.max(flowTotal, 0) }],+ [flowTotal]+ );++ const totalValue = flowTotal;++ const arcs = useMemo((): PieArcData[] => {+ const v = data[0]?.value ?? 0;+ if (v > 0) {+ const pieGenerator = d3Pie<PieData>()+ .value((d) => d.value)+ .startAngle(-Math.PI / 2)+ .endAngle((3 * Math.PI) / 2)+ .padAngle(0)+ .sort(null);+ const computed = pieGenerator(data);+ return computed.map((arc, index) => ({+ data: arc.data,+ index,+ startAngle: arc.startAngle,+ endAngle: arc.endAngle,+ padAngle: arc.padAngle,+ value: arc.value,+ })) as PieArcData[];+ }+ const d0 = data[0];+ if (!d0) {+ return [];+ }+ return [+ {+ data: d0,+ index: 0,+ startAngle: -Math.PI / 2,+ endAngle: (3 * Math.PI) / 2,+ padAngle: 0,+ value: 0,+ },+ ];+ }, [data]);++ const getColor = useCallback((index: number) => {+ return defaultPieColors[index % defaultPieColors.length] as string;+ }, []);++ const getFill = useCallback(+ (index: number) => {+ const item = data[index];+ if (item?.fill) {+ return item.fill;+ }+ return getColor(index);+ },+ [data, getColor]+ );++ const center = contextSize / 2;+ const outerRadius = center - SHELL_HOVER_OFFSET;++ const contextValue: PieContextValue = useMemo(+ () => ({+ data,+ arcs,+ size: contextSize,+ center,+ outerRadius,+ innerRadius: innerRadiusPx,+ padAngle: 0,+ cornerRadius: 0,+ hoverOffset: SHELL_HOVER_OFFSET,+ hoveredIndex: null,+ setHoveredIndex: () => undefined,+ animationKey: 0,+ isLoaded: true,+ enterStaggerScale: 1,+ containerRef,+ totalValue,+ getColor,+ getFill,+ geometryScrubbing: false,+ scrubSlicePaths: null,+ }),+ [+ data,+ arcs,+ contextSize,+ center,+ outerRadius,+ innerRadiusPx,+ totalValue,+ getColor,+ getFill,+ ]+ );++ return (+ <PieProvider value={contextValue}>+ <PieCenter {...pieCenterProps} />+ </PieProvider>+ );+}++PieCenterShell.displayName = 'PieCenterShell';diff --git a/apps/start/src/components/charts/pie-center.tsx b/apps/start/src/components/charts/pie-center.tsxnew file mode 100644index 000000000..0a35095b9--- /dev/null+++ b/apps/start/src/components/charts/pie-center.tsx@@ -0,0 +1,126 @@+'use client';++import type { ReactNode } from 'react';+import {+ chartCenterContainerClassName,+ chartCenterLabelClassName,+ chartCenterValueClassName,+} from './chart-center-typography';+import {+ ChartStatFlow,+ type ChartStatFlowFormat,+ defaultChartStatFlowFormat,+} from './chart-stat-flow';+import { usePieHover, usePieStable } from './pie-context';+import { cn } from '@/lib/utils';++export interface PieCenterProps {+ /** Label shown below the value. Default: "Total" when not hovering */+ defaultLabel?: string;+ /** Format options for NumberFlow. Default: standard notation */+ formatOptions?: ChartStatFlowFormat;+ /** Custom render function for complete control over center content */+ children?: (props: {+ value: number;+ label: string;+ isHovered: boolean;+ data: { label: string; value: number; color?: string; fill?: string };+ }) => ReactNode;+ /** Additional class name for the container */+ className?: string;+ /** Class name for the value text. Scales with center size via container queries. */+ valueClassName?: string;+ /** Class name for the label text. Scales with center size via container queries. */+ labelClassName?: string;+ /** Prefix to show before the number (e.g., "$") */+ prefix?: string;+ /** Suffix to show after the number (e.g., "%") */+ suffix?: string;+}++/**+ * PieCenter displays content in the center of a donut/pie chart.+ *+ * This component renders as pure HTML (not inside SVG foreignObject) to avoid+ * Safari's WebKit bug #23113 where HTML content with CSS transforms/opacity+ * inside foreignObject renders at incorrect positions.+ *+ * The parent PieChart uses CSS Grid stacking to overlay this HTML content+ * on top of the SVG slices.+ */+export function PieCenter({+ defaultLabel = 'Total',+ formatOptions = defaultChartStatFlowFormat,+ children,+ className = '',+ valueClassName = chartCenterValueClassName,+ labelClassName = chartCenterLabelClassName,+ prefix,+ suffix,+}: PieCenterProps) {+ const { data, totalValue, innerRadius, geometryScrubbing } = usePieStable();+ const { hoveredIndex } = usePieHover();++ const effectiveHoveredIndex = geometryScrubbing ? null : hoveredIndex;+ const hoveredData =+ effectiveHoveredIndex === null ? null : data[effectiveHoveredIndex];+ const displayValue = hoveredData ? hoveredData.value : totalValue;+ const displayLabel = hoveredData ? hoveredData.label : defaultLabel;++ // Calculate center area size based on inner radius+ // Leave some padding so text doesn't touch the inner edge+ const centerSize = innerRadius * 2 - 16;++ // Don't render if there's no inner radius (solid pie, not donut)+ if (innerRadius <= 0) {+ return null;+ }++ // If custom render function is provided, use it+ if (children && hoveredData) {+ return (+ <div+ className={cn(+ chartCenterContainerClassName,+ 'flex items-center justify-center',+ className+ )}+ style={{ width: centerSize, height: centerSize }}+ >+ {children({+ value: displayValue,+ label: displayLabel,+ isHovered: effectiveHoveredIndex !== null,+ data: hoveredData,+ })}+ </div>+ );+ }++ // Default center content with NumberFlow animations+ // Now renders as pure HTML, avoiding Safari's foreignObject bugs+ return (+ <div+ className={cn(+ chartCenterContainerClassName,+ 'flex flex-col items-center justify-center text-center',+ className+ )}+ style={{ width: centerSize, height: centerSize }}+ >+ <ChartStatFlow+ formatOptions={formatOptions}+ label={displayLabel}+ labelClassName={labelClassName}+ prefix={prefix}+ suffix={suffix}+ value={displayValue}+ valueClassName={valueClassName}+ />+ </div>+ );+}++PieCenter.displayName = 'PieCenter';++export default PieCenter;diff --git a/apps/start/src/components/charts/pie-chart.tsx b/apps/start/src/components/charts/pie-chart.tsxnew file mode 100644index 000000000..ce961e041--- /dev/null+++ b/apps/start/src/components/charts/pie-chart.tsx@@ -0,0 +1,534 @@+'use client';++import { Group } from '@visx/group';+import { arc as arcGenerator } from '@visx/shape';+import { pie as d3Pie } from 'd3-shape';+import type { Transition } from 'motion/react';+import {+ Children,+ isValidElement,+ memo,+ type ReactElement,+ type ReactNode,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import { ParentSize } from './chart-parent-size';+import {+ defaultPieColors,+ type PieArcData,+ type PieContextValue,+ type PieData,+ PieProvider,+} from './pie-context';+import { cn } from '@/lib/utils';++/** Default hover offset in pixels */+export const DEFAULT_HOVER_OFFSET = 10;++export interface PieChartProps {+ /** Data array - each item represents a slice */+ data: PieData[];+ /** Chart size in pixels. If not provided, uses parent container size */+ size?: number;+ /** Inner radius for donut charts. Default: 0 (solid pie) */+ innerRadius?: number;+ /** Padding angle between slices in radians. Default: 0 */+ padAngle?: number;+ /** Corner radius for rounded slice edges. Default: 0 */+ cornerRadius?: number;+ /** Start angle in radians. Default: -PI/2 (top) */+ startAngle?: number;+ /** End angle in radians. Default: 3*PI/2 (full circle from top) */+ endAngle?: number;+ /** Additional class name for the container */+ className?: string;+ /** Controlled hover state - index of hovered slice */+ hoveredIndex?: number | null;+ /** Callback when hover state changes */+ onHoverChange?: (index: number | null) => void;+ /**+ * Hover offset in pixels for slice hover effects.+ * This also determines the padding around the chart to prevent clipping.+ * Default: 10+ */+ hoverOffset?: number;+ /** Child components (PieSlice, PieCenter, patterns, gradients, etc.) */+ children: ReactNode;+ /** Framer Motion transition for slice enter animation */+ enterTransition?: Transition;+ /** Scales slice stagger delays (1 = default). */+ enterStaggerScale?: number;+ /**+ * High-frequency geometry updates (e.g. studio NumberField scrub).+ * Uses plain SVG paths instead of Motion `d` / spring hover morphing.+ */+ geometryScrubbing?: boolean;+}++interface PieChartInnerProps {+ width: number;+ height: number;+ data: PieData[];+ innerRadius: number;+ padAngle: number;+ cornerRadius: number;+ startAngle: number;+ endAngle: number;+ hoverOffset: number;+ children: ReactNode;+ containerRef: React.RefObject<HTMLDivElement | null>;+ hoveredIndexProp?: number | null;+ onHoverChange?: (index: number | null) => void;+ enterTransition?: Transition;+ enterStaggerScale: number;+ geometryScrubbing: boolean;+}++function generatePieArcPath(+ innerRadius: number,+ outerRadius: number,+ startAngle: number,+ endAngle: number,+ cornerRadius: number,+ padAngle: number+): string {+ const generator = arcGenerator<unknown>({+ innerRadius,+ outerRadius,+ cornerRadius,+ padAngle,+ });+ return generator({ startAngle, endAngle } as unknown as null) || '';+}++// Helper to check if a child is a PieCenter component+function isPieCenter(child: ReactNode): boolean {+ return (+ isValidElement(child) &&+ typeof child.type === 'function' &&+ ((child.type as { displayName?: string }).displayName === 'PieCenter' ||+ (child.type as { name?: string }).name === 'PieCenter')+ );+}++function isPieSlice(child: ReactNode): boolean {+ return (+ isValidElement(child) &&+ typeof child.type === 'function' &&+ ((child.type as { displayName?: string }).displayName === 'PieSlice' ||+ (child.type as { name?: string }).name === 'PieSlice')+ );+}++// Helper to check if a component is a gradient or pattern definition+function isDefsComponent(child: ReactElement): boolean {+ const displayName =+ (child.type as { displayName?: string })?.displayName ||+ (child.type as { name?: string })?.name ||+ '';+ return (+ displayName.includes('Gradient') ||+ displayName.includes('Pattern') ||+ displayName === 'LinearGradient' ||+ displayName === 'RadialGradient'+ );+}++function PieChartInner(props: PieChartInnerProps) {+ const size = Math.min(props.width, props.height);++ if (size < 10) {+ return null;+ }++ return <PieChartCore {...props} />;+}++const PieChartCore = memo(function PieChartCore({+ width,+ height,+ data,+ innerRadius: innerRadiusProp,+ padAngle,+ cornerRadius,+ startAngle,+ endAngle,+ hoverOffset,+ children,+ containerRef,+ hoveredIndexProp,+ onHoverChange,+ enterTransition,+ enterStaggerScale,+ geometryScrubbing,+}: PieChartInnerProps) {+ const [internalHoveredIndex, setInternalHoveredIndex] = useState<+ number | null+ >(null);+ const [animationKey] = useState(0);+ const [isLoaded, setIsLoaded] = useState(false);++ // Use controlled or uncontrolled hover state+ const isControlled = hoveredIndexProp !== undefined;+ const hoveredIndex = isControlled ? hoveredIndexProp : internalHoveredIndex;+ const setHoveredIndex = useCallback(+ (index: number | null) => {+ if (isControlled) {+ onHoverChange?.(index);+ } else {+ setInternalHoveredIndex(index);+ }+ },+ [isControlled, onHoverChange]+ );++ // Use the smaller dimension to ensure the chart fits+ const size = Math.min(width, height);+ const center = size / 2;++ // Calculate radii with padding based on hover offset to prevent clipping+ const padding = hoverOffset;+ const outerRadius = center - padding;+ const innerRadius = innerRadiusProp;++ // Calculate total value+ const totalValue = useMemo(+ () => data.reduce((sum, d) => sum + d.value, 0),+ [data]+ );++ // Get color for a slice index+ const getColor = useCallback(+ (index: number) => {+ const item = data[index];+ if (item?.color) {+ return item.color;+ }+ return defaultPieColors[index % defaultPieColors.length] as string;+ },+ [data]+ );++ // Get fill for a slice index (supports patterns/gradients)+ const getFill = useCallback(+ (index: number) => {+ const item = data[index];+ // Check for explicit fill (pattern/gradient URL)+ if (item?.fill) {+ return item.fill;+ }+ // Fall back to color+ return getColor(index);+ },+ [data, getColor]+ );++ // Compute arcs using d3-shape pie+ const arcs = useMemo(() => {+ const pieGenerator = d3Pie<PieData>()+ .value((d) => d.value)+ .startAngle(startAngle)+ .endAngle(endAngle)+ .padAngle(padAngle)+ .sort(null); // Maintain data order++ const computed = pieGenerator(data);++ return computed.map((arc, index) => ({+ data: arc.data,+ index,+ startAngle: arc.startAngle,+ endAngle: arc.endAngle,+ padAngle: arc.padAngle,+ value: arc.value,+ })) as PieArcData[];+ }, [data, startAngle, endAngle, padAngle]);++ const scrubSlicePaths = useMemo((): readonly string[] | null => {+ if (!geometryScrubbing) {+ return null;+ }+ return arcs.map((arc) =>+ generatePieArcPath(+ innerRadius,+ outerRadius,+ arc.startAngle,+ arc.endAngle,+ cornerRadius,+ arc.padAngle+ )+ );+ }, [geometryScrubbing, arcs, innerRadius, outerRadius, cornerRadius]);++ const effectiveIsLoaded = geometryScrubbing || isLoaded;++ // biome-ignore lint/correctness/useExhaustiveDependencies: enterTransition+ useEffect(() => {+ if (geometryScrubbing) {+ return;+ }+ setIsLoaded(false);+ const timer = setTimeout(() => {+ setIsLoaded(true);+ }, 100);+ return () => clearTimeout(timer);+ }, [enterTransition, enterStaggerScale, geometryScrubbing]);++ // Separate children into categories+ const { svgChildren, centerChildren, defsChildren } = useMemo(() => {+ const svgNodes: ReactNode[] = [];+ const centerNodes: ReactNode[] = [];+ const defsNodes: ReactElement[] = [];++ Children.forEach(children, (child) => {+ if (!isValidElement(child)) {+ svgNodes.push(child);+ return;+ }++ if (isPieCenter(child)) {+ centerNodes.push(child);+ } else if (isDefsComponent(child)) {+ defsNodes.push(child);+ } else if (geometryScrubbing && isPieSlice(child)) {+ return;+ } else {+ svgNodes.push(child);+ }+ });++ return {+ svgChildren: svgNodes,+ centerChildren: centerNodes,+ defsChildren: defsNodes,+ };+ }, [children, geometryScrubbing]);++ const scrubSliceFills = useMemo(() => {+ if (!(geometryScrubbing && scrubSlicePaths)) {+ return null;+ }+ return scrubSlicePaths.map((_, index) => getFill(index));+ }, [geometryScrubbing, scrubSlicePaths, getFill]);++ const contextValue: PieContextValue = useMemo(+ () => ({+ data,+ arcs,+ size,+ center,+ outerRadius,+ innerRadius,+ padAngle,+ cornerRadius,+ hoverOffset,+ hoveredIndex,+ setHoveredIndex,+ animationKey,+ isLoaded: effectiveIsLoaded,+ enterTransition,+ enterStaggerScale,+ containerRef,+ totalValue,+ getColor,+ getFill,+ geometryScrubbing,+ scrubSlicePaths,+ }),+ [+ data,+ arcs,+ size,+ center,+ outerRadius,+ innerRadius,+ padAngle,+ cornerRadius,+ hoverOffset,+ hoveredIndex,+ setHoveredIndex,+ animationKey,+ effectiveIsLoaded,+ enterTransition,+ enterStaggerScale,+ containerRef,+ totalValue,+ getColor,+ getFill,+ geometryScrubbing,+ scrubSlicePaths,+ ]+ );++ // Use CSS Grid stacking to layer SVG and HTML content+ // This avoids Safari's foreignObject rendering bugs+ return (+ <PieProvider value={contextValue}>+ <div+ className="grid"+ style={{+ gridTemplateColumns: '1fr',+ gridTemplateRows: '1fr',+ width: size,+ height: size,+ }}+ >+ {/* SVG layer with pie slices */}+ <svg+ aria-hidden="true"+ height={size}+ style={{+ gridArea: '1 / 1',+ // No `paint` containment: it clips hover glow at the svg box.+ contain: 'layout style',+ overflow: 'visible',+ }}+ width={size}+ >+ {/* Defs for patterns and gradients */}+ {defsChildren.length > 0 && <defs>{defsChildren}</defs>}++ <Group left={center} top={center}>+ {scrubSlicePaths && scrubSliceFills+ ? scrubSlicePaths.map((d, index) =>+ d ? (+ <path+ d={d}+ fill={scrubSliceFills[index]}+ key={data[index]?.label ?? index}+ pointerEvents="none"+ />+ ) : null+ )+ : null}+ {svgChildren}+ </Group>+ </svg>++ {/* HTML layer with center content - stacked on top via grid */}+ {centerChildren.length > 0 && (+ <div+ className="pointer-events-none flex items-center justify-center"+ style={{ gridArea: '1 / 1' }}+ >+ {centerChildren}+ </div>+ )}+ </div>+ </PieProvider>+ );+}, pieChartCorePropsEqual);++function pieChartCorePropsEqual(+ prev: PieChartInnerProps,+ next: PieChartInnerProps+): boolean {+ return (+ prev.width === next.width &&+ prev.height === next.height &&+ prev.data === next.data &&+ prev.innerRadius === next.innerRadius &&+ prev.padAngle === next.padAngle &&+ prev.cornerRadius === next.cornerRadius &&+ prev.startAngle === next.startAngle &&+ prev.endAngle === next.endAngle &&+ prev.hoverOffset === next.hoverOffset &&+ prev.hoveredIndexProp === next.hoveredIndexProp &&+ prev.onHoverChange === next.onHoverChange &&+ prev.enterTransition === next.enterTransition &&+ prev.enterStaggerScale === next.enterStaggerScale &&+ prev.geometryScrubbing === next.geometryScrubbing &&+ prev.children === next.children+ );+}++export function PieChart({+ data,+ size: fixedSize,+ innerRadius = 0,+ padAngle = 0,+ cornerRadius = 0,+ startAngle = -Math.PI / 2,+ endAngle = (3 * Math.PI) / 2,+ className = '',+ hoveredIndex,+ onHoverChange,+ hoverOffset = DEFAULT_HOVER_OFFSET,+ enterTransition,+ enterStaggerScale = 1,+ geometryScrubbing = false,+ children,+}: PieChartProps) {+ const containerRef = useRef<HTMLDivElement>(null);++ // If fixed size is provided, use it directly+ if (fixedSize) {+ return (+ <div+ className={cn('relative flex items-center justify-center', className)}+ ref={containerRef}+ style={{ width: fixedSize, height: fixedSize }}+ >+ <PieChartInner+ containerRef={containerRef}+ cornerRadius={cornerRadius}+ data={data}+ endAngle={endAngle}+ enterStaggerScale={enterStaggerScale}+ enterTransition={enterTransition}+ geometryScrubbing={geometryScrubbing}+ height={fixedSize}+ hoveredIndexProp={hoveredIndex}+ hoverOffset={hoverOffset}+ innerRadius={innerRadius}+ onHoverChange={onHoverChange}+ padAngle={padAngle}+ startAngle={startAngle}+ width={fixedSize}+ >+ {children}+ </PieChartInner>+ </div>+ );+ }++ // Otherwise use ParentSize for responsive sizing+ return (+ <div+ className={cn('relative aspect-square w-full', className)}+ ref={containerRef}+ >+ <ParentSize debounceTime={10}>+ {({ width, height }) => (+ <PieChartInner+ containerRef={containerRef}+ cornerRadius={cornerRadius}+ data={data}+ endAngle={endAngle}+ enterStaggerScale={enterStaggerScale}+ enterTransition={enterTransition}+ geometryScrubbing={geometryScrubbing}+ height={height}+ hoveredIndexProp={hoveredIndex}+ hoverOffset={hoverOffset}+ innerRadius={innerRadius}+ onHoverChange={onHoverChange}+ padAngle={padAngle}+ startAngle={startAngle}+ width={width}+ >+ {children}+ </PieChartInner>+ )}+ </ParentSize>+ </div>+ );+}++PieChart.displayName = 'PieChart';++export default PieChart;diff --git a/apps/start/src/components/charts/pie-context.tsx b/apps/start/src/components/charts/pie-context.tsxnew file mode 100644index 000000000..6ac9d0233--- /dev/null+++ b/apps/start/src/components/charts/pie-context.tsx@@ -0,0 +1,205 @@+'use client';++import type { Transition } from 'motion/react';+import {+ createContext,+ type ReactNode,+ type RefObject,+ useContext,+ useMemo,+} from 'react';++// CSS variable references for pie chart theming+export const pieCssVars = {+ background: 'var(--chart-background)',+ foreground: 'var(--chart-foreground)',+ foregroundMuted: 'var(--chart-foreground-muted)',+ label: 'var(--chart-label)',+ // Default slice colors from chart palette+ slice1: 'var(--chart-1)',+ slice2: 'var(--chart-2)',+ slice3: 'var(--chart-3)',+ slice4: 'var(--chart-4)',+ slice5: 'var(--chart-5)',+};++// Default slice color palette+export const defaultPieColors = [+ pieCssVars.slice1,+ pieCssVars.slice2,+ pieCssVars.slice3,+ pieCssVars.slice4,+ pieCssVars.slice5,+];++export interface PieData {+ /** Display label for the slice */+ label: string;+ /** Value for the slice (determines slice size relative to total) */+ value: number;+ /** Optional color override - falls back to palette */+ color?: string;+ /** Optional fill override for patterns/gradients (e.g., "url(#patternId)") */+ fill?: string;+}++/** Arc data computed by visx Pie */+export interface PieArcData {+ data: PieData;+ index: number;+ startAngle: number;+ endAngle: number;+ padAngle: number;+ value: number;+}++export interface PieHoverContextValue {+ hoveredIndex: number | null;+ setHoveredIndex: (index: number | null) => void;+}++export interface PieStableContextValue {+ // Data+ data: PieData[];+ arcs: PieArcData[];++ // Dimensions+ size: number;+ center: number;+ outerRadius: number;+ innerRadius: number;+ padAngle: number;+ cornerRadius: number;++ // Hover effect+ hoverOffset: number;++ // Animation state+ animationKey: number;+ isLoaded: boolean;+ enterTransition?: Transition;+ enterStaggerScale: number;++ // Container ref for portals+ containerRef: RefObject<HTMLDivElement | null>;++ // Computed values+ totalValue: number;++ // Get color for a slice index+ getColor: (index: number) => string;++ // Get fill for a slice index (supports patterns/gradients)+ getFill: (index: number) => string;++ /**+ * Studio geometry scrub — skip Motion path morphing and use plain SVG paths.+ * @default false+ */+ geometryScrubbing: boolean;++ /** Precomputed slice paths during geometry scrub (one per arc). */+ scrubSlicePaths: readonly string[] | null;+}++export type PieContextValue = PieStableContextValue & PieHoverContextValue;++const PieStableContext = createContext<PieStableContextValue | null>(null);+const PieHoverContext = createContext<PieHoverContextValue | null>(null);++export function PieProvider({+ children,+ value,+}: {+ children: ReactNode;+ value: PieContextValue;+}) {+ const stable = useMemo<PieStableContextValue>(+ () => ({+ data: value.data,+ arcs: value.arcs,+ size: value.size,+ center: value.center,+ outerRadius: value.outerRadius,+ innerRadius: value.innerRadius,+ padAngle: value.padAngle,+ cornerRadius: value.cornerRadius,+ hoverOffset: value.hoverOffset,+ animationKey: value.animationKey,+ isLoaded: value.isLoaded,+ enterTransition: value.enterTransition,+ enterStaggerScale: value.enterStaggerScale,+ containerRef: value.containerRef,+ totalValue: value.totalValue,+ getColor: value.getColor,+ getFill: value.getFill,+ geometryScrubbing: value.geometryScrubbing,+ scrubSlicePaths: value.scrubSlicePaths,+ }),+ [+ value.data,+ value.arcs,+ value.size,+ value.center,+ value.outerRadius,+ value.innerRadius,+ value.padAngle,+ value.cornerRadius,+ value.hoverOffset,+ value.animationKey,+ value.isLoaded,+ value.enterTransition,+ value.enterStaggerScale,+ value.containerRef,+ value.totalValue,+ value.getColor,+ value.getFill,+ value.geometryScrubbing,+ value.scrubSlicePaths,+ ]+ );++ const hover = useMemo<PieHoverContextValue>(+ () => ({+ hoveredIndex: value.hoveredIndex,+ setHoveredIndex: value.setHoveredIndex,+ }),+ [value.hoveredIndex, value.setHoveredIndex]+ );++ return (+ <PieStableContext.Provider value={stable}>+ <PieHoverContext.Provider value={hover}>+ {children}+ </PieHoverContext.Provider>+ </PieStableContext.Provider>+ );+}++export function usePieStable(): PieStableContextValue {+ const context = useContext(PieStableContext);+ if (!context) {+ throw new Error(+ 'usePieStable must be used within a PieProvider. ' ++ 'Make sure your component is wrapped in <PieChart>.'+ );+ }+ return context;+}++export function usePieHover(): PieHoverContextValue {+ const context = useContext(PieHoverContext);+ if (!context) {+ throw new Error(+ 'usePieHover must be used within a PieProvider. ' ++ 'Make sure your component is wrapped in <PieChart>.'+ );+ }+ return context;+}++export function usePie(): PieContextValue {+ return { ...usePieStable(), ...usePieHover() };+}++export default PieStableContext;diff --git a/apps/start/src/components/charts/pie-slice.tsx b/apps/start/src/components/charts/pie-slice.tsxnew file mode 100644index 000000000..1811de3f9--- /dev/null+++ b/apps/start/src/components/charts/pie-slice.tsx@@ -0,0 +1,511 @@+'use client';++import { arc as arcGenerator } from '@visx/shape';+import { motion, useSpring, useTransform } from 'motion/react';+import { memo, useEffect } from 'react';+import { usePieHover, usePieStable } from './pie-context';+import { useEnterComplete } from './use-enter-complete';+import { useMountProgress } from './use-mount-progress';++// Helper to generate arc path using d3 arc generator+function generateArcPath(+ innerRadius: number,+ outerRadius: number,+ startAngle: number,+ endAngle: number,+ cornerRadius: number,+ padAngle: number+): string {+ const generator = arcGenerator<unknown>({+ innerRadius,+ outerRadius,+ cornerRadius,+ padAngle,+ });+ return generator({ startAngle, endAngle } as unknown as null) || '';+}++// Calculate the translation offset for a slice to "pop out" along its radial axis+function getSliceOffset(+ startAngle: number,+ endAngle: number,+ distance: number+): { x: number; y: number } {+ // Calculate the midpoint angle of the slice+ const midAngle = (startAngle + endAngle) / 2;+ // In d3-shape, 0 radians is at 12 o'clock, angles increase clockwise+ // So the outward direction is: x = sin(angle), y = -cos(angle)+ return {+ x: Math.sin(midAngle) * distance,+ y: -Math.cos(midAngle) * distance,+ };+}++/** Hover effect types */+export type PieSliceHoverEffect = 'translate' | 'grow' | 'none';++export interface PieSliceProps {+ /** Index of the slice in the data array */+ index: number;+ /** Optional color override - falls back to data color or palette */+ color?: string;+ /** Optional fill override for patterns/gradients (e.g., "url(#patternId)") */+ fill?: string;+ /** Animate the slice on mount. Default: true */+ animate?: boolean;+ /** Show glow effect on hover. Default: true */+ showGlow?: boolean;+ /**+ * Hover effect type. Default: "translate"+ * - "translate": Slice moves outward along its radial axis+ * - "grow": Slice extends its outer radius (gets longer)+ * - "none": No hover animation+ */+ hoverEffect?: PieSliceHoverEffect;+ /** Distance in pixels for hover effect (translate distance or grow amount). Defaults to PieChart's hoverOffset */+ hoverOffset?: number;+ /** Additional CSS class */+ className?: string;+}++interface AnimatedSliceTranslateProps {+ index: number;+ innerRadius: number;+ outerRadius: number;+ startAngle: number;+ endAngle: number;+ cornerRadius: number;+ padAngle: number;+ fill: string;+ color: string;+ isHovered: boolean;+ isFaded: boolean;+ animationKey: number;+ showGlow: boolean;+ hoverOffset: number;+}++function AnimatedSliceTranslate({+ index,+ innerRadius,+ outerRadius,+ startAngle,+ endAngle,+ cornerRadius,+ padAngle,+ fill,+ color,+ isHovered,+ isFaded,+ animationKey,+ showGlow,+ hoverOffset,+}: AnimatedSliceTranslateProps) {+ const {+ enterTransition,+ enterStaggerScale,+ animationKey: pieAnimationKey,+ } = usePieStable();+ const animationDelay = (0.1 + index * 0.08) * enterStaggerScale;+ const mountProgress = useMountProgress(+ enterTransition,+ animationDelay,+ pieAnimationKey+ );+ const enterComplete = useEnterComplete(mountProgress);++ const animatedPath = useTransform(mountProgress, (mount) => {+ const currentEndAngle = startAngle + (endAngle - startAngle) * mount;+ if (currentEndAngle <= startAngle + 0.01) {+ return '';+ }+ return generateArcPath(+ innerRadius,+ outerRadius,+ startAngle,+ currentEndAngle,+ cornerRadius,+ padAngle+ );+ });++ const offset = getSliceOffset(startAngle, endAngle, hoverOffset);+ const glowColor = color;+ const hitboxPath = generateArcPath(+ innerRadius,+ outerRadius,+ startAngle,+ endAngle,+ cornerRadius,+ padAngle+ );++ if (enterComplete) {+ const shouldTranslate = isHovered;+ return (+ <motion.path+ animate={{+ opacity: isFaded ? 0.4 : 1,+ x: shouldTranslate ? offset.x : 0,+ y: shouldTranslate ? offset.y : 0,+ }}+ d={hitboxPath}+ fill={fill}+ pointerEvents="none"+ style={{+ filter:+ showGlow && isHovered+ ? `drop-shadow(0 0 12px ${glowColor})`+ : 'none',+ }}+ transition={{+ opacity: { duration: 0.15 },+ x: { type: 'spring', stiffness: 400, damping: 25 },+ y: { type: 'spring', stiffness: 400, damping: 25 },+ }}+ />+ );+ }++ return (+ <motion.path+ animate={{+ opacity: isFaded ? 0.4 : 1,+ x: isHovered ? offset.x : 0,+ y: isHovered ? offset.y : 0,+ }}+ d={animatedPath}+ fill={fill}+ key={`slice-${animationKey}-${index}`}+ pointerEvents="none"+ style={{+ filter:+ showGlow && isHovered ? `drop-shadow(0 0 12px ${glowColor})` : 'none',+ }}+ transition={{+ opacity: { duration: 0.15 },+ x: { type: 'spring', stiffness: 400, damping: 25 },+ y: { type: 'spring', stiffness: 400, damping: 25 },+ }}+ />+ );+}++interface AnimatedSliceGrowProps {+ index: number;+ innerRadius: number;+ outerRadius: number;+ startAngle: number;+ endAngle: number;+ cornerRadius: number;+ padAngle: number;+ fill: string;+ color: string;+ isHovered: boolean;+ isFaded: boolean;+ animationKey: number;+ showGlow: boolean;+ hoverOffset: number;+}++function AnimatedSliceGrow({+ index,+ innerRadius,+ outerRadius,+ startAngle,+ endAngle,+ cornerRadius,+ padAngle,+ fill,+ color,+ isHovered,+ isFaded,+ animationKey,+ showGlow,+ hoverOffset,+}: AnimatedSliceGrowProps) {+ const {+ enterTransition,+ enterStaggerScale,+ animationKey: pieAnimationKey,+ } = usePieStable();+ const animationDelay = (0.1 + index * 0.08) * enterStaggerScale;+ const mountProgress = useMountProgress(+ enterTransition,+ animationDelay,+ pieAnimationKey+ );+ const enterComplete = useEnterComplete(mountProgress);++ const growSpring = useSpring(outerRadius, {+ stiffness: 400,+ damping: 25,+ });++ useEffect(() => {+ growSpring.set(isHovered ? outerRadius + hoverOffset : outerRadius);+ }, [isHovered, hoverOffset, outerRadius, growSpring]);++ const animatedPath = useTransform(+ [mountProgress, growSpring],+ ([mount, currentOuterRadius]) => {+ const currentEndAngle =+ startAngle + (endAngle - startAngle) * (mount as number);+ if (currentEndAngle <= startAngle + 0.01) {+ return '';+ }+ return generateArcPath(+ innerRadius,+ currentOuterRadius as number,+ startAngle,+ currentEndAngle,+ cornerRadius,+ padAngle+ );+ }+ );++ const glowColor = color;+ const grownOuterRadius = isHovered ? outerRadius + hoverOffset : outerRadius;+ const grownPath = generateArcPath(+ innerRadius,+ grownOuterRadius,+ startAngle,+ endAngle,+ cornerRadius,+ padAngle+ );++ if (enterComplete) {+ return (+ <motion.path+ animate={{+ opacity: isFaded ? 0.4 : 1,+ d: grownPath,+ }}+ d={grownPath}+ fill={fill}+ pointerEvents="none"+ style={{+ filter:+ showGlow && isHovered+ ? `drop-shadow(0 0 12px ${glowColor})`+ : 'none',+ }}+ transition={{+ opacity: { duration: 0.15 },+ d: { type: 'spring', stiffness: 400, damping: 25 },+ }}+ />+ );+ }++ return (+ <motion.path+ animate={{+ opacity: isFaded ? 0.4 : 1,+ }}+ d={animatedPath}+ fill={fill}+ key={`slice-${animationKey}-${index}`}+ pointerEvents="none"+ style={{+ filter:+ showGlow && isHovered ? `drop-shadow(0 0 12px ${glowColor})` : 'none',+ }}+ transition={{+ opacity: { duration: 0.15 },+ }}+ />+ );+}++export const PieSlice = memo(function PieSlice({+ index,+ color: colorProp,+ fill: fillProp,+ animate = true,+ showGlow = true,+ hoverEffect = 'translate',+ hoverOffset: hoverOffsetProp,+}: PieSliceProps) {+ const {+ arcs,+ innerRadius,+ outerRadius,+ cornerRadius,+ hoverOffset: contextHoverOffset,+ animationKey,+ geometryScrubbing,+ scrubSlicePaths,+ getColor,+ getFill,+ } = usePieStable();+ const { hoveredIndex, setHoveredIndex } = usePieHover();++ // Use prop if provided, otherwise use context value+ const hoverOffset = hoverOffsetProp ?? contextHoverOffset;++ const arcData = arcs[index];+ if (!arcData) {+ return null;+ }++ const color = colorProp || getColor(index);+ const fill = fillProp || getFill(index);++ if (geometryScrubbing) {+ const scrubPath = scrubSlicePaths?.[index];+ if (!scrubPath) {+ return null;+ }+ return <path d={scrubPath} fill={fill} pointerEvents="none" />;+ }++ const isHovered = hoveredIndex === index;+ const isFaded = hoveredIndex !== null && hoveredIndex !== index;++ // Calculate values for non-animated/static paths+ const offset = getSliceOffset(+ arcData.startAngle,+ arcData.endAngle,+ hoverOffset+ );++ // Generate the static hitbox path (always uses base outer radius)+ const hitboxPath = generateArcPath(+ innerRadius,+ outerRadius,+ arcData.startAngle,+ arcData.endAngle,+ cornerRadius,+ arcData.padAngle+ );++ // Generate the visible path for grow effect+ const grownOuterRadius = isHovered ? outerRadius + hoverOffset : outerRadius;+ const grownPath = generateArcPath(+ innerRadius,+ grownOuterRadius,+ arcData.startAngle,+ arcData.endAngle,+ cornerRadius,+ arcData.padAngle+ );++ // Render animated slice based on effect type+ const renderAnimatedSlice = () => {+ if (hoverEffect === 'grow') {+ return (+ <AnimatedSliceGrow+ animationKey={animationKey}+ color={color}+ cornerRadius={cornerRadius}+ endAngle={arcData.endAngle}+ fill={fill}+ hoverOffset={hoverOffset}+ index={index}+ innerRadius={innerRadius}+ isFaded={isFaded}+ isHovered={isHovered}+ outerRadius={outerRadius}+ padAngle={arcData.padAngle}+ showGlow={showGlow}+ startAngle={arcData.startAngle}+ />+ );+ }++ // Default: translate effect (also covers "none" with hoverOffset=0)+ return (+ <AnimatedSliceTranslate+ animationKey={animationKey}+ color={color}+ cornerRadius={cornerRadius}+ endAngle={arcData.endAngle}+ fill={fill}+ hoverOffset={hoverEffect === 'none' ? 0 : hoverOffset}+ index={index}+ innerRadius={innerRadius}+ isFaded={isFaded}+ isHovered={isHovered}+ outerRadius={outerRadius}+ padAngle={arcData.padAngle}+ showGlow={showGlow}+ startAngle={arcData.startAngle}+ />+ );+ };++ // Render static (non-animated) slice+ const renderStaticSlice = () => {+ if (hoverEffect === 'grow') {+ return (+ <motion.path+ animate={{+ opacity: isFaded ? 0.4 : 1,+ d: grownPath,+ }}+ d={hitboxPath}+ fill={fill}+ pointerEvents="none"+ style={{+ filter:+ showGlow && isHovered ? `drop-shadow(0 0 12px ${color})` : 'none',+ }}+ transition={{+ opacity: { duration: 0.15 },+ d: { type: 'spring', stiffness: 400, damping: 25 },+ }}+ />+ );+ }++ // Default: translate effect+ const shouldTranslate = hoverEffect !== 'none' && isHovered;+ const translateX = shouldTranslate ? offset.x : 0;+ const translateY = shouldTranslate ? offset.y : 0;++ return (+ <motion.path+ animate={{+ opacity: isFaded ? 0.4 : 1,+ x: translateX,+ y: translateY,+ }}+ d={hitboxPath}+ fill={fill}+ pointerEvents="none"+ style={{+ filter:+ showGlow && isHovered ? `drop-shadow(0 0 12px ${color})` : 'none',+ }}+ transition={{+ opacity: { duration: 0.15 },+ x: { type: 'spring', stiffness: 400, damping: 25 },+ y: { type: 'spring', stiffness: 400, damping: 25 },+ }}+ />+ );+ };++ return (+ <g style={{ cursor: 'pointer' }}>+ {/* Invisible hitbox - stays in place, handles hover events */}+ {/* biome-ignore lint/a11y/noStaticElementInteractions: SVG path used as hover hitbox for visualization */}+ <path+ d={hitboxPath}+ fill="transparent"+ onMouseEnter={() => setHoveredIndex(index)}+ onMouseLeave={() => setHoveredIndex(null)}+ />++ {/* Visible slice - animates based on hover effect, no pointer events */}+ {animate ? renderAnimatedSlice() : renderStaticSlice()}+ </g>+ );+});++PieSlice.displayName = 'PieSlice';++export default PieSlice;diff --git a/apps/start/src/components/charts/projection-config.ts b/apps/start/src/components/charts/projection-config.tsnew file mode 100644index 000000000..e4c83db98--- /dev/null+++ b/apps/start/src/components/charts/projection-config.ts@@ -0,0 +1,129 @@+import {+ Children,+ Fragment,+ isValidElement,+ type ReactElement,+ type ReactNode,+} from 'react';+import { isChartClipPassthrough } from './chart-child-passthrough';+import type { ProjectionPoint } from './projection-utils';+import {+ projectionDateExtents,+ projectionValueExtents,+} from './projection-utils';+import { normalizeYAxisId } from './y-axis-scales';++export interface ProjectionLineConfig {+ yAxisId: string;+ data: ProjectionPoint[];+}++interface ProjectionLineConfigProps {+ data?: ProjectionPoint[];+ yAxisId?: string | number;+}++function getChildComponentName(child: ReactElement) {+ const childType = child.type as { displayName?: string; name?: string };+ return typeof child.type === 'function'+ ? childType.displayName || childType.name || ''+ : '';+}++function isProjectionLineElement(child: ReactElement): boolean {+ return getChildComponentName(child) === 'ProjectionLine';+}++function normalizeProjectionData(+ data: ProjectionPoint[] | undefined+): ProjectionPoint[] {+ if (!data?.length) {+ return [];+ }+ return data.map((point) => ({+ date: point.date instanceof Date ? point.date : new Date(point.date),+ value: point.value,+ }));+}++/** Collect {@link ProjectionLine} props from chart children for domain extension. */+export function extractProjectionLineConfigs(+ children: ReactNode+): ProjectionLineConfig[] {+ const configs: ProjectionLineConfig[] = [];++ const visit = (node: ReactNode) => {+ Children.forEach(node, (child) => {+ if (!isValidElement(child)) {+ return;+ }++ if (child.type === Fragment) {+ visit((child.props as { children?: ReactNode }).children);+ return;+ }++ if (isProjectionLineElement(child)) {+ const props = child.props as ProjectionLineConfigProps | undefined;+ const data = normalizeProjectionData(props?.data);+ if (data.length >= 2) {+ configs.push({+ yAxisId: normalizeYAxisId(props?.yAxisId),+ data,+ });+ }+ return;+ }++ if (isChartClipPassthrough(child.type)) {+ visit((child.props as { children?: ReactNode }).children);+ return;+ }++ const childProps = child.props as { children?: ReactNode } | undefined;+ if (childProps?.children) {+ visit(childProps.children);+ }+ });+ };++ visit(children);+ return configs;+}++export function mergeProjectionYDomain(+ domain: [number, number],+ configs: ProjectionLineConfig[],+ yAxisId: string+): [number, number] {+ const paths = configs+ .filter((config) => config.yAxisId === yAxisId)+ .map((config) => config.data);+ const extents = projectionValueExtents(paths);+ if (!extents) {+ return domain;+ }++ const [min, max] = domain;+ const nextMin = Math.min(min, extents.minValue);+ const nextMax = Math.max(max, extents.maxValue);++ if (nextMin >= 0 && min >= 0) {+ return [0, nextMax <= 0 ? 100 : nextMax * 1.1];+ }++ const padding = (nextMax - nextMin) * 0.05 || 1;+ return [nextMin - padding, nextMax + padding];+}++export function mergeProjectionXDomainMax(+ maxTime: number,+ configs: ProjectionLineConfig[]+): number {+ const paths = configs.map((config) => config.data);+ const extents = projectionDateExtents(paths);+ if (!extents) {+ return maxTime;+ }+ return Math.max(maxTime, extents.maxTime);+}diff --git a/apps/start/src/components/charts/projection-line-end-marker.tsx b/apps/start/src/components/charts/projection-line-end-marker.tsxnew file mode 100644index 000000000..55cee78a4--- /dev/null+++ b/apps/start/src/components/charts/projection-line-end-marker.tsx@@ -0,0 +1,69 @@+'use client';++import { useCallback } from 'react';+import { useChartStable, useYScale } from './chart-context';+import type { ProjectionPoint } from './projection-utils';++export interface ProjectionLineEndMarkerProps {+ data: ProjectionPoint[];+ yAxisId?: string | number;+ stroke?: string;+ strokeOpacity?: number;+ radius?: number;+}++/** Renders the projection horizon dot outside the series reveal clip. */+export function ProjectionLineEndMarker({+ data,+ yAxisId,+ stroke = 'var(--chart-3)',+ strokeOpacity = 1,+ radius = 5,+}: ProjectionLineEndMarkerProps) {+ const { xScale, chartPhase, innerWidth } = useChartStable();+ const yScale = useYScale(yAxisId);++ const getX = useCallback(+ (point: ProjectionPoint) => xScale(point.date) ?? 0,+ [xScale]+ );+ const getY = useCallback(+ (point: ProjectionPoint) => yScale(point.value) ?? 0,+ [yScale]+ );++ const showStroke =+ chartPhase === 'revealing' ||+ chartPhase === 'ready' ||+ chartPhase === 'exitingReady';++ if (!showStroke || data.length < 2) {+ return null;+ }++ const endPoint = data.at(-1);+ if (!endPoint) {+ return null;+ }+ const edgePadding = radius + 1;+ const endX = Math.min(getX(endPoint), Math.max(0, innerWidth - edgePadding));+ const endY = getY(endPoint);++ return (+ <circle+ cx={endX}+ cy={endY}+ fill={stroke}+ fillOpacity={strokeOpacity}+ r={radius * 0.85}+ />+ );+}++ProjectionLineEndMarker.displayName = 'ProjectionLineEndMarker';++(+ ProjectionLineEndMarker as unknown as Record<string, boolean>+).__isPostOverlay = true;++export default ProjectionLineEndMarker;diff --git a/apps/start/src/components/charts/projection-line.tsx b/apps/start/src/components/charts/projection-line.tsxnew file mode 100644index 000000000..f01ecfc04--- /dev/null+++ b/apps/start/src/components/charts/projection-line.tsx@@ -0,0 +1,234 @@+'use client';++import { curveLinear } from '@visx/curve';+import { LinePath } from '@visx/shape';+import { useCallback, useId, useMemo } from 'react';+import { useChartStable, useYScale } from './chart-context';+import {+ buildHorizontalTangentBezierPath,+ type ProjectionCurveKind,+ type ProjectionPoint,+} from './projection-utils';++// biome-ignore lint/suspicious/noExplicitAny: d3 curve factory type+type CurveFactory = any;++export type ProjectionStrokeStyle = 'solid' | 'gradient';++export interface ProjectionLineProps {+ /** Projection path points — anchor (last data row) + horizon end. */+ data: ProjectionPoint[];+ /** Y-scale group id. Default: `"left"`. */+ yAxisId?: string | number;+ /** Solid stroke color. Default: var(--chart-3) */+ stroke?: string;+ /** Solid or path-aligned gradient stroke. Default: solid */+ strokeStyle?: ProjectionStrokeStyle;+ /** Gradient start color when `strokeStyle` is gradient. Default: `stroke` */+ gradientStart?: string;+ /** Gradient end color when `strokeStyle` is gradient. Default: var(--chart-5) */+ gradientEnd?: string;+ /** Stroke width. Default: 2 */+ strokeWidth?: number;+ /** Straight segment or horizontal-tangent S-curve. Default: linear */+ curveKind?: ProjectionCurveKind;+ /** Advanced curve override (used when `curveKind` is omitted). */+ curve?: CurveFactory;+ /** Dash pattern. Default: "6,4" */+ strokeDasharray?: string;+ /** Stroke opacity. Default: 1 */+ strokeOpacity?: number;+ /** Show horizon endpoint marker. Default: true */+ showEndMarker?: boolean;+ /** @deprecated Use `showEndMarker`. */+ showEndpoints?: boolean;+ /** Endpoint marker radius. Default: 5 */+ endpointRadius?: number;+ className?: string;+}++function resolveVisibleEndX(+ endX: number,+ innerWidth: number,+ endpointRadius: number,+ strokeWidth: number+): number {+ const edgePadding = endpointRadius + strokeWidth * 0.5 + 1;+ return Math.min(endX, Math.max(0, innerWidth - edgePadding));+}++function renderProjectionStroke({+ bezierPath,+ curve,+ curveKind,+ data,+ getX,+ getY,+ linearPath,+ strokeProps,+}: {+ bezierPath: string | null;+ curve: CurveFactory | undefined;+ curveKind: ProjectionCurveKind;+ data: ProjectionPoint[];+ getX: (point: ProjectionPoint) => number;+ getY: (point: ProjectionPoint) => number;+ linearPath: string | null;+ strokeProps: {+ stroke: string;+ strokeDasharray: string;+ strokeLinecap: 'round';+ strokeOpacity: number;+ strokeWidth: number;+ };+}) {+ if (curveKind === 'bezier' && bezierPath) {+ return <path d={bezierPath} fill="none" {...strokeProps} />;+ }+ if (curveKind === 'linear' && linearPath) {+ return <path d={linearPath} fill="none" {...strokeProps} />;+ }+ return (+ <LinePath+ curve={curve ?? curveLinear}+ data={data}+ {...strokeProps}+ x={getX}+ y={getY}+ />+ );+}++export function ProjectionLine({+ data,+ yAxisId,+ stroke = 'var(--chart-3)',+ strokeStyle = 'solid',+ gradientStart,+ gradientEnd = 'var(--chart-5)',+ strokeWidth = 2,+ curveKind = 'linear',+ curve,+ strokeDasharray = '6,4',+ strokeOpacity = 1,+ showEndMarker,+ showEndpoints,+ endpointRadius = 5,+ className,+}: ProjectionLineProps) {+ const { xScale, chartPhase, innerWidth } = useChartStable();+ const yScale = useYScale(yAxisId);+ const gradientId = useId().replace(/:/g, '');+ const showMarker = showEndMarker ?? showEndpoints ?? true;+ const resolvedGradientStart = gradientStart ?? stroke;++ const getX = useCallback(+ (point: ProjectionPoint) => xScale(point.date) ?? 0,+ [xScale]+ );+ const getY = useCallback(+ (point: ProjectionPoint) => yScale(point.value) ?? 0,+ [yScale]+ );++ const startPoint = data[0];+ const endPoint = data.at(-1);++ const geometry = useMemo(() => {+ if (!(startPoint && endPoint)) {+ return null;+ }+ const startX = getX(startPoint);+ const startY = getY(startPoint);+ const endX = getX(endPoint);+ const endY = getY(endPoint);+ const visibleEndX = resolveVisibleEndX(+ endX,+ innerWidth,+ showMarker ? endpointRadius : 0,+ strokeWidth+ );+ return { startX, startY, visibleEndX, endY };+ }, [+ endPoint,+ endpointRadius,+ getX,+ getY,+ innerWidth,+ showMarker,+ startPoint,+ strokeWidth,+ ]);++ const bezierPath = useMemo(() => {+ if (curveKind !== 'bezier' || !geometry) {+ return null;+ }+ return buildHorizontalTangentBezierPath(+ geometry.startX,+ geometry.startY,+ geometry.visibleEndX,+ geometry.endY+ );+ }, [curveKind, geometry]);++ const linearPath = useMemo(() => {+ if (curveKind !== 'linear' || !geometry) {+ return null;+ }+ return `M ${geometry.startX},${geometry.startY} L ${geometry.visibleEndX},${geometry.endY}`;+ }, [curveKind, geometry]);++ const showStroke =+ chartPhase === 'revealing' ||+ chartPhase === 'ready' ||+ chartPhase === 'exitingReady';++ if (data.length < 2 || !geometry) {+ return null;+ }++ const resolvedStroke =+ strokeStyle === 'gradient' && geometry ? `url(#${gradientId})` : stroke;+ const strokeProps = {+ stroke: showStroke ? resolvedStroke : 'transparent',+ strokeDasharray,+ strokeLinecap: 'round' as const,+ strokeOpacity,+ strokeWidth,+ };++ return (+ <g className={className ?? 'chart-projection-line'}>+ {strokeStyle === 'gradient' && geometry ? (+ <defs>+ <linearGradient+ gradientUnits="userSpaceOnUse"+ id={gradientId}+ x1={geometry.startX}+ x2={geometry.visibleEndX}+ y1={geometry.startY}+ y2={geometry.endY}+ >+ <stop offset="0%" stopColor={resolvedGradientStart} />+ <stop offset="100%" stopColor={gradientEnd} />+ </linearGradient>+ </defs>+ ) : null}+ {renderProjectionStroke({+ bezierPath,+ curve,+ curveKind,+ data,+ getX,+ getY,+ linearPath,+ strokeProps,+ })}+ </g>+ );+}++ProjectionLine.displayName = 'ProjectionLine';++export default ProjectionLine;diff --git a/apps/start/src/components/charts/projection-utils.ts b/apps/start/src/components/charts/projection-utils.tsnew file mode 100644index 000000000..a565b05b1--- /dev/null+++ b/apps/start/src/components/charts/projection-utils.ts@@ -0,0 +1,386 @@+export type ProjectionMode = 'auto' | 'target' | 'manual';+export type ProjectionAutoMethod = 'linearRegression' | 'lastSegment';+/** How the projection segment is drawn between anchor and horizon. */+export type ProjectionCurveKind = 'linear' | 'bezier';+/** @deprecated Stepped density removed — projections always anchor → horizon. */+export type ProjectionPathDensity = 'stepped' | 'endpoints';++export interface ProjectionPoint {+ date: Date;+ value: number;+}++export interface BuildProjectionPathOptions {+ sourceData: Record<string, unknown>[];+ seriesKey: string;+ xDataKey?: string;+ mode: ProjectionMode;+ autoMethod?: ProjectionAutoMethod;+ /** Auto mode: stepped points per interval, or anchor + end only. Default: stepped */+ pathDensity?: ProjectionPathDensity;+ /** Index in sourceData where projection anchors (default: last point). */+ startIndex?: number;+ /** How many future points to generate (matches source cadence). */+ horizonPoints?: number;+ /** Target Y at the final projected date (target mode). */+ endValue?: number;+ /** Full manual path — anchor + future points (manual mode). */+ points?: ProjectionPoint[];+}++function readDate(row: Record<string, unknown>, xDataKey: string): Date | null {+ const raw = row[xDataKey];+ if (raw instanceof Date && !Number.isNaN(raw.getTime())) {+ return raw;+ }+ if (typeof raw === 'number' && Number.isFinite(raw)) {+ const date = new Date(raw);+ return Number.isNaN(date.getTime()) ? null : date;+ }+ if (typeof raw === 'string') {+ const date = new Date(raw);+ return Number.isNaN(date.getTime()) ? null : date;+ }+ return null;+}++function readValue(+ row: Record<string, unknown>,+ seriesKey: string+): number | null {+ const raw = row[seriesKey];+ return typeof raw === 'number' && Number.isFinite(raw) ? raw : null;+}++function resolveStartIndex(+ sourceData: Record<string, unknown>[],+ startIndex: number | undefined+): number {+ if (startIndex == null || !Number.isFinite(startIndex)) {+ return Math.max(0, sourceData.length - 1);+ }+ return Math.min(Math.max(0, Math.floor(startIndex)), sourceData.length - 1);+}++function intervalFromAdjacentRows(+ sourceData: Record<string, unknown>[],+ xDataKey: string,+ startIndex: number+): number | null {+ if (startIndex < 1) {+ return null;+ }+ const prevRow = sourceData[startIndex - 1];+ const currentRow = sourceData[startIndex];+ const prev = prevRow ? readDate(prevRow, xDataKey) : null;+ const current = currentRow ? readDate(currentRow, xDataKey) : null;+ if (!(prev && current)) {+ return null;+ }+ const delta = current.getTime() - prev.getTime();+ return delta > 0 ? delta : null;+}++function intervalFromSeriesSpan(+ sourceData: Record<string, unknown>[],+ xDataKey: string+): number | null {+ if (sourceData.length < 2) {+ return null;+ }+ const firstRow = sourceData[0];+ const lastRow = sourceData.at(-1);+ const first = firstRow ? readDate(firstRow, xDataKey) : null;+ const last = lastRow ? readDate(lastRow, xDataKey) : null;+ if (!(first && last)) {+ return null;+ }+ const span = last.getTime() - first.getTime();+ return span > 0 ? span / (sourceData.length - 1) : null;+}++function resolveIntervalMs(+ sourceData: Record<string, unknown>[],+ xDataKey: string,+ startIndex: number+): number {+ return (+ intervalFromAdjacentRows(sourceData, xDataKey, startIndex) ??+ intervalFromSeriesSpan(sourceData, xDataKey) ??+ 86_400_000+ );+}++function linearRegressionSlope(points: { t: number; y: number }[]): number {+ if (points.length < 2) {+ return 0;+ }+ const n = points.length;+ let sumT = 0;+ let sumY = 0;+ let sumTY = 0;+ let sumTT = 0;+ for (const { t, y } of points) {+ sumT += t;+ sumY += y;+ sumTY += t * y;+ sumTT += t * t;+ }+ const denom = n * sumTT - sumT * sumT;+ if (Math.abs(denom) < 1e-12) {+ return 0;+ }+ return (n * sumTY - sumT * sumY) / denom;+}++function buildAutoFutureValues(options: {+ anchorTime: number;+ anchorValue: number;+ autoMethod: ProjectionAutoMethod;+ historyPoints: { t: number; y: number }[];+ horizonPoints: number;+ intervalMs: number;+ pathDensity: ProjectionPathDensity;+}): ProjectionPoint[] {+ const {+ anchorTime,+ anchorValue,+ autoMethod,+ historyPoints,+ horizonPoints,+ intervalMs,+ pathDensity,+ } = options;++ const slope =+ autoMethod === 'lastSegment' && historyPoints.length >= 2+ ? (() => {+ const prev = historyPoints.at(-2);+ const last = historyPoints.at(-1);+ if (!(prev && last)) {+ return 0;+ }+ const dt = last.t - prev.t;+ return dt === 0 ? 0 : (last.y - prev.y) / dt;+ })()+ : linearRegressionSlope(historyPoints);++ if (pathDensity === 'endpoints') {+ const endTime = anchorTime + intervalMs * horizonPoints;+ const endValue = anchorValue + slope * intervalMs * horizonPoints;+ return [+ { date: new Date(anchorTime), value: anchorValue },+ { date: new Date(endTime), value: endValue },+ ];+ }++ const result: ProjectionPoint[] = [+ { date: new Date(anchorTime), value: anchorValue },+ ];++ for (let i = 1; i <= horizonPoints; i++) {+ const t = anchorTime + intervalMs * i;+ const value = anchorValue + slope * intervalMs * i;+ result.push({ date: new Date(t), value });+ }++ return result;+}++/** Slope (value change per ms) at the projection anchor from the last data segment. */+export function computeProjectionAnchorTangentSlope(+ sourceData: Record<string, unknown>[],+ seriesKey: string,+ xDataKey = 'date',+ startIndexProp?: number+): number {+ if (sourceData.length < 2) {+ return 0;+ }+ const startIndex = resolveStartIndex(sourceData, startIndexProp);+ const historyPoints: { t: number; y: number }[] = [];+ for (let i = 0; i <= startIndex; i++) {+ const row = sourceData[i];+ if (!row) {+ continue;+ }+ const date = readDate(row, xDataKey);+ const value = readValue(row, seriesKey);+ if (date && value != null) {+ historyPoints.push({ t: date.getTime(), y: value });+ }+ }+ if (historyPoints.length < 2) {+ return 0;+ }+ const prev = historyPoints.at(-2);+ const last = historyPoints.at(-1);+ if (!(prev && last)) {+ return 0;+ }+ const dt = last.t - prev.t;+ return dt === 0 ? 0 : (last.y - prev.y) / dt;+}++/** Cubic bezier with horizontal tangents at start and end (price-target S-curve). */+export function buildHorizontalTangentBezierPath(+ x0: number,+ y0: number,+ x1: number,+ y1: number,+ /** How far control points sit along the x span (0–0.5). Default: 0.45 */+ tension = 0.45+): string {+ const dx = x1 - x0;+ if (Math.abs(dx) < 1e-6) {+ return `M ${x0},${y0} L ${x1},${y1}`;+ }+ const t = Math.min(0.5, Math.max(0.05, tension));+ const c1x = x0 + dx * t;+ const c2x = x1 - dx * t;+ return `M ${x0},${y0} C ${c1x},${y0} ${c2x},${y1} ${x1},${y1}`;+}++function buildTargetPath(options: {+ anchorTime: number;+ anchorValue: number;+ endValue: number;+ horizonPoints: number;+ intervalMs: number;+}): ProjectionPoint[] {+ const { anchorTime, anchorValue, endValue, horizonPoints, intervalMs } =+ options;+ const endTime = anchorTime + intervalMs * horizonPoints;+ return [+ { date: new Date(anchorTime), value: anchorValue },+ { date: new Date(endTime), value: endValue },+ ];+}++/** Build a projection path from historical chart data or explicit points. */+export function buildProjectionPath(+ options: BuildProjectionPathOptions+): ProjectionPoint[] {+ const {+ sourceData,+ seriesKey,+ xDataKey = 'date',+ mode,+ autoMethod = 'linearRegression',+ pathDensity = 'endpoints',+ startIndex: startIndexProp,+ horizonPoints = 6,+ endValue,+ points,+ } = options;++ if (mode === 'manual' && points && points.length >= 2) {+ return points.map((point) => ({+ date: new Date(point.date),+ value: point.value,+ }));+ }++ if (sourceData.length === 0) {+ return [];+ }++ const startIndex = resolveStartIndex(sourceData, startIndexProp);+ const anchorRow = sourceData[startIndex];+ if (!anchorRow) {+ return [];+ }++ const anchorDate = readDate(anchorRow, xDataKey);+ const anchorValue = readValue(anchorRow, seriesKey);+ if (!anchorDate || anchorValue == null) {+ return [];+ }++ const intervalMs = resolveIntervalMs(sourceData, xDataKey, startIndex);+ const anchorTime = anchorDate.getTime();++ const historyPoints: { t: number; y: number }[] = [];+ for (let i = 0; i <= startIndex; i++) {+ const row = sourceData[i];+ if (!row) {+ continue;+ }+ const date = readDate(row, xDataKey);+ const value = readValue(row, seriesKey);+ if (date && value != null) {+ historyPoints.push({ t: date.getTime(), y: value });+ }+ }++ if (mode === 'target' && endValue != null && Number.isFinite(endValue)) {+ return buildTargetPath({+ anchorTime,+ anchorValue,+ endValue,+ horizonPoints,+ intervalMs,+ });+ }++ return buildAutoFutureValues({+ anchorTime,+ anchorValue,+ autoMethod,+ historyPoints,+ horizonPoints,+ intervalMs,+ pathDensity,+ });+}++/** Collect numeric Y extents from projection point arrays. */+export function projectionValueExtents(+ paths: ProjectionPoint[][]+): { minValue: number; maxValue: number } | null {+ let minValue = Number.POSITIVE_INFINITY;+ let maxValue = Number.NEGATIVE_INFINITY;++ for (const path of paths) {+ for (const point of path) {+ if (point.value < minValue) {+ minValue = point.value;+ }+ if (point.value > maxValue) {+ maxValue = point.value;+ }+ }+ }++ if (minValue === Number.POSITIVE_INFINITY) {+ return null;+ }++ return { minValue, maxValue };+}++/** Collect date extents from projection point arrays. */+export function projectionDateExtents(+ paths: ProjectionPoint[][]+): { minTime: number; maxTime: number } | null {+ let minTime = Number.POSITIVE_INFINITY;+ let maxTime = Number.NEGATIVE_INFINITY;++ for (const path of paths) {+ for (const point of path) {+ const time = point.date.getTime();+ if (time < minTime) {+ minTime = time;+ }+ if (time > maxTime) {+ maxTime = time;+ }+ }+ }++ if (minTime === Number.POSITIVE_INFINITY) {+ return null;+ }++ return { minTime, maxTime };+}diff --git a/apps/start/src/components/charts/reference-area-config.ts b/apps/start/src/components/charts/reference-area-config.tsnew file mode 100644index 000000000..201caf22c--- /dev/null+++ b/apps/start/src/components/charts/reference-area-config.ts@@ -0,0 +1,68 @@+import {+ Children,+ isValidElement,+ type ReactElement,+ type ReactNode,+} from 'react';+import { normalizeYAxisId } from './y-axis-scales';++export interface ReferenceAreaConfig {+ yAxisId: string;+ y1?: number;+ y2?: number;+ axisLabelColor?: string;+}++interface ReferenceAreaConfigProps {+ yAxisId?: string | number;+ y1?: number;+ y2?: number;+ axisLabelColor?: string;+}++function getChildComponentName(child: ReactElement) {+ const childType = child.type as { displayName?: string; name?: string };+ return typeof child.type === 'function'+ ? childType.displayName || childType.name || ''+ : '';+}++function isReferenceAreaElement(child: ReactElement): boolean {+ return getChildComponentName(child) === 'ReferenceArea';+}++/** Collect {@link ReferenceArea} props from chart children for axis label styling. */+export function extractReferenceAreaConfigs(+ children: ReactNode+): ReferenceAreaConfig[] {+ const configs: ReferenceAreaConfig[] = [];++ const visit = (node: ReactNode) => {+ Children.forEach(node, (child) => {+ if (!isValidElement(child)) {+ return;+ }++ if (isReferenceAreaElement(child)) {+ const props = child.props as ReferenceAreaConfigProps | undefined;+ if (props) {+ configs.push({+ yAxisId: normalizeYAxisId(props.yAxisId),+ y1: props.y1,+ y2: props.y2,+ axisLabelColor: props.axisLabelColor,+ });+ }+ return;+ }++ const childProps = child.props as { children?: ReactNode } | undefined;+ if (childProps?.children) {+ visit(childProps.children);+ }+ });+ };++ visit(children);+ return configs;+}diff --git a/apps/start/src/components/charts/reference-area-geometry.ts b/apps/start/src/components/charts/reference-area-geometry.tsnew file mode 100644index 000000000..b2f3de4b1--- /dev/null+++ b/apps/start/src/components/charts/reference-area-geometry.ts@@ -0,0 +1,136 @@+export type ReferenceAreaIfOverflow = 'hidden' | 'visible' | 'discard';++export interface ReferenceAreaRect {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface ComputeReferenceAreaRectOptions {+ innerWidth: number;+ innerHeight: number;+ x1?: Date | number;+ x2?: Date | number;+ y1?: number;+ y2?: number;+ ifOverflow?: ReferenceAreaIfOverflow;+ xScale: (value: Date) => number;+ yScale: (value: number) => number;+}++function toDate(value: Date | number): Date {+ return value instanceof Date ? value : new Date(value);+}++function resolveXPixel(+ xScale: (value: Date) => number,+ value: Date | number | undefined,+ fallback: number+): number {+ if (value == null) {+ return fallback;+ }+ return xScale(toDate(value));+}++function resolveYPixel(+ yScale: (value: number) => number,+ value: number | undefined,+ fallback: number+): number {+ if (value == null) {+ return fallback;+ }+ return yScale(value);+}++function clampRectToPlot(+ rect: ReferenceAreaRect,+ innerWidth: number,+ innerHeight: number+): ReferenceAreaRect | null {+ const x1 = Math.max(0, rect.x);+ const y1 = Math.max(0, rect.y);+ const x2 = Math.min(innerWidth, rect.x + rect.width);+ const y2 = Math.min(innerHeight, rect.y + rect.height);+ const width = x2 - x1;+ const height = y2 - y1;+ if (width <= 0 || height <= 0) {+ return null;+ }+ return { x: x1, y: y1, width, height };+}++function isFullyInsidePlot(+ rect: ReferenceAreaRect,+ innerWidth: number,+ innerHeight: number+): boolean {+ return (+ rect.x >= 0 &&+ rect.y >= 0 &&+ rect.x + rect.width <= innerWidth &&+ rect.y + rect.height <= innerHeight+ );+}++/** Map data bounds to plot pixels for a reference rectangle. */+export function computeReferenceAreaRect(+ options: ComputeReferenceAreaRectOptions+): ReferenceAreaRect | null {+ const {+ innerWidth,+ innerHeight,+ x1,+ x2,+ y1,+ y2,+ ifOverflow = 'hidden',+ xScale,+ yScale,+ } = options;++ if (innerWidth <= 0 || innerHeight <= 0) {+ return null;+ }++ const left = resolveXPixel(xScale, x1, 0);+ const right = resolveXPixel(xScale, x2, innerWidth);+ const top = resolveYPixel(yScale, y1, 0);+ const bottom = resolveYPixel(yScale, y2, innerHeight);++ const x = Math.min(left, right);+ const y = Math.min(top, bottom);+ const width = Math.abs(right - left);+ const height = Math.abs(bottom - top);++ if (width <= 0 || height <= 0) {+ return null;+ }++ const rect: ReferenceAreaRect = { x, y, width, height };++ if (ifOverflow === 'visible') {+ return rect;+ }++ if (ifOverflow === 'discard') {+ return isFullyInsidePlot(rect, innerWidth, innerHeight) ? rect : null;+ }++ return clampRectToPlot(rect, innerWidth, innerHeight);+}++/** Inclusive data range for axis label highlighting. */+export function resolveReferenceDataRange(+ y1: number | undefined,+ y2: number | undefined,+ domain: [number, number]+): [number, number] {+ const dMin = Math.min(domain[0], domain[1]);+ const dMax = Math.max(domain[0], domain[1]);+ const low = y1 ?? dMin;+ const high = y2 ?? dMax;+ return [Math.min(low, high), Math.max(low, high)];+}diff --git a/apps/start/src/components/charts/reference-area-registration-context.tsx b/apps/start/src/components/charts/reference-area-registration-context.tsxnew file mode 100644index 000000000..63130c088--- /dev/null+++ b/apps/start/src/components/charts/reference-area-registration-context.tsx@@ -0,0 +1,16 @@+'use client';++import { createContext, useContext } from 'react';+import type { ReferenceAreaConfig } from './reference-area-config';++export interface ReferenceAreaRegistrationContextValue {+ registerReferenceArea: (id: string, config: ReferenceAreaConfig) => void;+ unregisterReferenceArea: (id: string) => void;+}++export const ReferenceAreaRegistrationContext =+ createContext<ReferenceAreaRegistrationContextValue | null>(null);++export function useReferenceAreaRegistration(): ReferenceAreaRegistrationContextValue | null {+ return useContext(ReferenceAreaRegistrationContext);+}diff --git a/apps/start/src/components/charts/reference-area.tsx b/apps/start/src/components/charts/reference-area.tsxnew file mode 100644index 000000000..582e79dd1--- /dev/null+++ b/apps/start/src/components/charts/reference-area.tsx@@ -0,0 +1,285 @@+'use client';++import { motion } from 'motion/react';+import { useId, useLayoutEffect, useMemo } from 'react';+import { chartCssVars, useChartStable, useYScale } from './chart-context';+import { type PatternPresetId, renderPatternPreset } from './pattern-preset';+import {+ computeReferenceAreaRect,+ type ReferenceAreaIfOverflow,+} from './reference-area-geometry';+import { useReferenceAreaRegistration } from './reference-area-registration-context';+import { normalizeYAxisId } from './y-axis-scales';+import { isReferenceAreaVisiblePhase } from './y-domain-utils';++const DEFAULT_FILL =+ 'color-mix(in oklch, var(--chart-foreground-muted) 12%, transparent)';++export type ReferenceAreaStrokeStyle = 'solid' | 'dashed';++export interface ReferenceAreaProps {+ /** Lower Y data bound (extends to plot top when omitted). */+ y1?: number;+ /** Upper Y data bound (extends to plot bottom when omitted). */+ y2?: number;+ /** Starting X data coordinate (extends to plot left when omitted). */+ x1?: Date | number;+ /** Ending X data coordinate (extends to plot right when omitted). */+ x2?: Date | number;+ /** Y-scale group id. Default: `"left"`. */+ yAxisId?: string | number;+ /** Solid fill when `pattern` is `"none"`. */+ fill?: string;+ fillOpacity?: number;+ /** Pattern preset. `"none"` uses solid `fill`. */+ pattern?: PatternPresetId;+ /** Pattern stroke / tile color. */+ patternColor?: string;+ patternScale?: number;+ patternStrokeWidth?: number;+ patternRadius?: number;+ patternComplement?: boolean;+ patternFill?: string;+ patternDotFill?: boolean;+ patternTileBackground?: string;+ stroke?: string;+ strokeWidth?: number;+ strokeStyle?: ReferenceAreaStrokeStyle;+ /** Dash array when `strokeStyle` is `"dashed"`. Default: `"4,4"`. */+ strokeDasharray?: string;+ /** Fade fill and edge lines at left/right. Default: true */+ fadeEdges?: boolean;+ /** Horizontal fade zone as % of plot width per edge. Default: 10 */+ fadeEdgesLength?: number;+ /** Y-axis tick label color for values inside this band. */+ axisLabelColor?: string;+ /** Inward bracket markers at the horizontal center of the band. */+ showMarkers?: boolean;+ markerColor?: string;+ markerSize?: number;+ ifOverflow?: ReferenceAreaIfOverflow;+ className?: string;+}++const ENTER_FADE_MS = 420;++function clampFadeLength(length: number): number {+ return Math.min(45, Math.max(0, length));+}++function bracketMarkerPath(+ centerX: number,+ edgeY: number,+ size: number,+ direction: 'down' | 'up'+): string {+ const half = size / 2;+ if (direction === 'down') {+ return `M ${centerX - half} ${edgeY} L ${centerX + half} ${edgeY} L ${centerX} ${edgeY + size} Z`;+ }+ return `M ${centerX - half} ${edgeY} L ${centerX + half} ${edgeY} L ${centerX} ${edgeY - size} Z`;+}++export function ReferenceArea({+ y1,+ y2,+ x1,+ x2,+ yAxisId,+ fill = DEFAULT_FILL,+ fillOpacity = 1,+ pattern = 'none',+ patternColor = chartCssVars.foregroundMuted,+ patternScale = 1,+ patternStrokeWidth,+ patternRadius,+ patternComplement,+ patternFill,+ patternDotFill,+ patternTileBackground,+ stroke = chartCssVars.foregroundMuted,+ strokeWidth = 1,+ strokeStyle = 'dashed',+ strokeDasharray = '4,4',+ fadeEdges = true,+ fadeEdgesLength = 10,+ axisLabelColor,+ showMarkers = false,+ markerColor = 'var(--chart-1)',+ markerSize = 6,+ ifOverflow = 'hidden',+ className,+}: ReferenceAreaProps) {+ const { innerWidth, innerHeight, xScale, chartPhase, enterTransition } =+ useChartStable();+ const yScale = useYScale(yAxisId);+ const uniqueId = useId().replace(/:/g, '');+ const registration = useReferenceAreaRegistration();++ useLayoutEffect(() => {+ if (!registration) {+ return;+ }+ registration.registerReferenceArea(uniqueId, {+ yAxisId: normalizeYAxisId(yAxisId),+ y1,+ y2,+ axisLabelColor,+ });+ return () => registration.unregisterReferenceArea(uniqueId);+ }, [registration, uniqueId, yAxisId, y1, y2, axisLabelColor]);++ const patternId = `chart-reference-area-pattern-${uniqueId}`;+ const hMaskId = `chart-reference-area-fade-${uniqueId}`;+ const hGradientId = `${hMaskId}-gradient`;++ const rect = useMemo(+ () =>+ computeReferenceAreaRect({+ innerWidth,+ innerHeight,+ x1,+ x2,+ y1,+ y2,+ ifOverflow,+ xScale,+ yScale,+ }),+ [innerWidth, innerHeight, x1, x2, y1, y2, ifOverflow, xScale, yScale]+ );++ const usesPattern = pattern !== 'none';+ const patternNode = useMemo(() => {+ if (!usesPattern) {+ return null;+ }+ return renderPatternPreset(pattern, patternId, {+ color: patternColor,+ scale: patternScale,+ strokeWidth: patternStrokeWidth,+ radius: patternRadius,+ complement: patternComplement,+ fill: patternFill,+ dotFill: patternDotFill,+ tileBackground: patternTileBackground,+ });+ }, [+ usesPattern,+ pattern,+ patternId,+ patternColor,+ patternScale,+ patternStrokeWidth,+ patternRadius,+ patternComplement,+ patternFill,+ patternDotFill,+ patternTileBackground,+ ]);++ const fadeEdge = clampFadeLength(fadeEdgesLength);+ const edgeMask = fadeEdges ? `url(#${hMaskId})` : undefined;+ const lineDash = strokeStyle === 'dashed' ? strokeDasharray : undefined;++ if (!rect) {+ return null;+ }++ const { x, y, width, height } = rect;+ const topEdgeY = y;+ const bottomEdgeY = y + height;+ const centerX = x + width / 2;+ const visible = isReferenceAreaVisiblePhase(chartPhase);+ const fadeTransition =+ enterTransition && typeof enterTransition === 'object'+ ? enterTransition+ : { duration: ENTER_FADE_MS / 1000, ease: 'easeOut' as const };+ const areaFill = usesPattern && patternNode ? `url(#${patternId})` : fill;++ return (+ // biome-ignore lint/a11y/noAriaHiddenOnFocusable: decorative reference band+ <motion.g+ animate={{ opacity: visible ? 1 : 0 }}+ aria-hidden="true"+ className={className ?? 'chart-reference-area'}+ initial={{ opacity: 0 }}+ transition={fadeTransition}+ >+ {edgeMask ? (+ <defs>+ <linearGradient id={hGradientId} x1="0%" x2="100%" y1="0%" y2="0%">+ <stop offset="0%" style={{ stopColor: 'white', stopOpacity: 0 }} />+ <stop+ offset={`${fadeEdge}%`}+ style={{ stopColor: 'white', stopOpacity: 1 }}+ />+ <stop+ offset={`${100 - fadeEdge}%`}+ 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>+ ) : null}+ {patternNode ? <defs>{patternNode}</defs> : null}+ <rect+ fill={areaFill}+ fillOpacity={fillOpacity}+ height={height}+ mask={edgeMask}+ width={width}+ x={x}+ y={y}+ />+ <g mask={edgeMask}>+ <line+ stroke={stroke}+ strokeDasharray={lineDash}+ strokeWidth={strokeWidth}+ x1={x}+ x2={x + width}+ y1={topEdgeY}+ y2={topEdgeY}+ />+ <line+ stroke={stroke}+ strokeDasharray={lineDash}+ strokeWidth={strokeWidth}+ x1={x}+ x2={x + width}+ y1={bottomEdgeY}+ y2={bottomEdgeY}+ />+ </g>+ {showMarkers ? (+ <>+ <path+ d={bracketMarkerPath(centerX, topEdgeY, markerSize, 'down')}+ fill={markerColor}+ />+ <path+ d={bracketMarkerPath(centerX, bottomEdgeY, markerSize, 'up')}+ fill={markerColor}+ />+ </>+ ) : null}+ </motion.g>+ );+}++ReferenceArea.displayName = 'ReferenceArea';++export default ReferenceArea;diff --git a/apps/start/src/components/charts/sankey/index.ts b/apps/start/src/components/charts/sankey/index.tsnew file mode 100644index 000000000..cce787b37--- /dev/null+++ b/apps/start/src/components/charts/sankey/index.ts@@ -0,0 +1,22 @@+export {+ SankeyChart,+ type SankeyChartProps,+ type SankeyData,+} from './sankey-chart';+export {+ type Margin,+ type SankeyContextValue,+ type SankeyLinkDatum,+ type SankeyNodeDatum,+ SankeyProvider,+ type SankeyTooltipData,+ sankeyCssVars,+ useSankey,+} from './sankey-context';+export { SankeyLink, type SankeyLinkProps } from './sankey-link';+export {+ type SankeyLabelOrientation,+ SankeyNode,+ type SankeyNodeProps,+} from './sankey-node';+export { SankeyTooltip, type SankeyTooltipProps } from './sankey-tooltip';diff --git a/apps/start/src/components/charts/sankey/sankey-chart.tsx b/apps/start/src/components/charts/sankey/sankey-chart.tsxnew file mode 100644index 000000000..8284f265c--- /dev/null+++ b/apps/start/src/components/charts/sankey/sankey-chart.tsx@@ -0,0 +1,272 @@+'use client';++import { localPoint } from '@visx/event';+import { sankey, sankeyCenter, sankeyLinkHorizontal } from '@visx/sankey';+import type { Transition } from 'motion/react';+import {+ memo,+ type ReactNode,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import { ParentSize } from '../chart-parent-size';+import {+ type Margin,+ type SankeyLinkDatum,+ type SankeyNodeDatum,+ SankeyProvider,+ type SankeyTooltipData,+} from './sankey-context';+import { cn } from '@/lib/utils';++export interface SankeyData {+ nodes: SankeyNodeDatum[];+ links: SankeyLinkDatum[];+}++export interface SankeyChartProps {+ /** Sankey data with nodes and links */+ data: SankeyData;+ /** Chart margins */+ margin?: Partial<Margin>;+ /** Animation duration in milliseconds. Default: 1100 */+ animationDuration?: number;+ /** 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;+ /** Node width in pixels. Default: 16 */+ nodeWidth?: number;+ /** Node padding in pixels. Default: 24 */+ nodePadding?: number;+ /** Additional class name for the container */+ className?: string;+ /** Child components (SankeyNode, SankeyLink, SankeyTooltip) */+ children: ReactNode;+ /** Controlled hovered node index (e.g. from ChartLegend). */+ hoveredNodeIndex?: number | null;+ /** Called when node hover changes from the chart surface. */+ onNodeHoverChange?: (index: number | null) => void;+}++const DEFAULT_MARGIN: Margin = { top: 40, right: 180, bottom: 40, left: 180 };++interface SankeyChartInnerProps {+ data: SankeyData;+ width: number;+ height: number;+ margin: Margin;+ animationDuration: number;+ enterTransition?: Transition;+ revealSignature?: string;+ nodeWidth: number;+ nodePadding: number;+ children: ReactNode;+ hoveredNodeIndexProp?: number | null;+ onNodeHoverChange?: (index: number | null) => void;+}++function SankeyChartInner(props: SankeyChartInnerProps) {+ const { width, height } = props;++ if (width < 10 || height < 10) {+ return null;+ }++ return <SankeyChartCore {...props} />;+}++const SankeyChartCore = memo(function SankeyChartCore({+ data,+ width,+ height,+ margin,+ animationDuration,+ enterTransition,+ revealSignature = '',+ nodeWidth,+ nodePadding,+ children,+ hoveredNodeIndexProp,+ onNodeHoverChange,+}: SankeyChartInnerProps) {+ const containerRef = useRef<HTMLDivElement>(null);+ const [isLoaded, setIsLoaded] = useState(false);+ const [revealEpoch, setRevealEpoch] = useState(0);+ const [internalHoveredNodeIndex, setInternalHoveredNodeIndex] = useState<+ number | null+ >(null);+ const isNodeHoverControlled = hoveredNodeIndexProp !== undefined;+ const hoveredNodeIndex = isNodeHoverControlled+ ? hoveredNodeIndexProp+ : internalHoveredNodeIndex;+ const setHoveredNodeIndex = useCallback(+ (index: number | null) => {+ if (isNodeHoverControlled) {+ onNodeHoverChange?.(index);+ } else {+ setInternalHoveredNodeIndex(index);+ }+ },+ [isNodeHoverControlled, onNodeHoverChange]+ );+ const [hoveredLinkIndex, setHoveredLinkIndex] = useState<number | null>(null);+ const [tooltipData, setTooltipData] = useState<SankeyTooltipData | null>(+ null+ );+ const [mousePos, setMousePos] = useState<{ x: number; y: number } | null>(+ null+ );++ const innerWidth = width - margin.left - margin.right;+ const innerHeight = height - margin.top - margin.bottom;++ // biome-ignore lint/correctness/useExhaustiveDependencies: revealSignature+ useEffect(() => {+ setRevealEpoch((n) => n + 1);+ setIsLoaded(false);+ const timeout = setTimeout(() => {+ setIsLoaded(true);+ }, animationDuration);+ return () => clearTimeout(timeout);+ }, [animationDuration, revealSignature]);++ const sankeyGenerator = useMemo(() => {+ return sankey<SankeyNodeDatum, SankeyLinkDatum>()+ .nodeWidth(nodeWidth)+ .nodePadding(nodePadding)+ .nodeAlign(sankeyCenter)+ .extent([+ [0, 0],+ [innerWidth, innerHeight],+ ]);+ }, [innerWidth, innerHeight, nodeWidth, nodePadding]);++ const graph = useMemo(() => {+ const clonedData = {+ nodes: data.nodes.map((node) => ({ ...node })),+ links: data.links.map((link) => ({ ...link })),+ };+ return sankeyGenerator(clonedData);+ }, [data, sankeyGenerator]);++ const createPath = useCallback(+ // biome-ignore lint/suspicious/noExplicitAny: d3-sankey types are complex+ (link: any) => {+ try {+ const pathGenerator = sankeyLinkHorizontal();+ return pathGenerator(link) || '';+ } catch {+ return '';+ }+ },+ []+ );++ const handleMouseMove = useCallback((event: React.MouseEvent) => {+ const point = localPoint(event);+ if (point) {+ setMousePos({ x: point.x, y: point.y });+ }+ }, []);++ const handleMouseLeave = useCallback(() => {+ setHoveredNodeIndex(null);+ setHoveredLinkIndex(null);+ setTooltipData(null);+ setMousePos(null);+ }, [setHoveredNodeIndex]);++ const contextValue = {+ graph,+ nodes: graph.nodes,+ links: graph.links,+ width,+ height,+ innerWidth,+ innerHeight,+ margin,+ hoveredNodeIndex,+ hoveredLinkIndex,+ setHoveredNodeIndex,+ setHoveredLinkIndex,+ tooltipData,+ setTooltipData,+ containerRef,+ isLoaded,+ animationDuration,+ enterTransition,+ revealEpoch,+ mousePos,+ createPath,+ };++ return (+ <SankeyProvider value={contextValue}>+ <div className="relative h-full w-full" ref={containerRef}>+ <svg+ aria-hidden="true"+ className="overflow-visible"+ height={height}+ onMouseLeave={handleMouseLeave}+ onMouseMove={handleMouseMove}+ width={width}+ >+ <g transform={`translate(${margin.left},${margin.top})`}>+ {children}+ </g>+ </svg>+ </div>+ </SankeyProvider>+ );+});++export function SankeyChart({+ data,+ margin: marginProp,+ animationDuration = 1100,+ enterTransition,+ revealSignature,+ aspectRatio = '2 / 1',+ nodeWidth = 16,+ nodePadding = 24,+ className = '',+ children,+ hoveredNodeIndex,+ onNodeHoverChange,+}: SankeyChartProps) {+ const margin = { ...DEFAULT_MARGIN, ...marginProp };++ return (+ <div className={cn('relative w-full', className)} style={{ aspectRatio }}>+ <ParentSize>+ {({ width, height }) => (+ <SankeyChartInner+ animationDuration={animationDuration}+ data={data}+ enterTransition={enterTransition}+ height={height}+ hoveredNodeIndexProp={hoveredNodeIndex}+ margin={margin}+ nodePadding={nodePadding}+ nodeWidth={nodeWidth}+ onNodeHoverChange={onNodeHoverChange}+ revealSignature={revealSignature}+ width={width}+ >+ {children}+ </SankeyChartInner>+ )}+ </ParentSize>+ </div>+ );+}++SankeyChart.displayName = 'SankeyChart';++export default SankeyChart;diff --git a/apps/start/src/components/charts/sankey/sankey-context.tsx b/apps/start/src/components/charts/sankey/sankey-context.tsxnew file mode 100644index 000000000..d3dc8757e--- /dev/null+++ b/apps/start/src/components/charts/sankey/sankey-context.tsx@@ -0,0 +1,110 @@+'use client';++import type { SankeyGraph, SankeyLink, SankeyNode } from 'd3-sankey';+import type { Transition } from 'motion/react';+import {+ createContext,+ type Dispatch,+ type RefObject,+ type SetStateAction,+ useContext,+} from 'react';++export interface Margin {+ top: number;+ right: number;+ bottom: number;+ left: number;+}++export interface SankeyNodeDatum {+ name: string;+ category?: 'source' | 'landing' | 'outcome';+ [key: string]: unknown;+}++export interface SankeyLinkDatum {+ source: number;+ target: number;+ value: number;+ [key: string]: unknown;+}++export interface SankeyTooltipData {+ type: 'node' | 'link';+ nodeIndex?: number;+ linkIndex?: number;+ x: number;+ y: number;+ data: SankeyNodeDatum | SankeyLinkDatum;+}++export interface SankeyContextValue {+ // Layout data+ graph: SankeyGraph<SankeyNodeDatum, SankeyLinkDatum>;+ nodes: SankeyNode<SankeyNodeDatum, SankeyLinkDatum>[];+ links: SankeyLink<SankeyNodeDatum, SankeyLinkDatum>[];++ // Dimensions+ width: number;+ height: number;+ innerWidth: number;+ innerHeight: number;+ margin: Margin;++ // Hover state+ hoveredNodeIndex: number | null;+ hoveredLinkIndex: number | null;+ setHoveredNodeIndex: (index: number | null) => void;+ setHoveredLinkIndex: (index: number | null) => void;++ // Tooltip+ tooltipData: SankeyTooltipData | null;+ setTooltipData: Dispatch<SetStateAction<SankeyTooltipData | null>>;+ containerRef: RefObject<HTMLDivElement | null>;++ // Animation+ isLoaded: boolean;+ animationDuration: number;+ /** Motion enter transition (spring or cubic-bezier tween). */+ enterTransition?: Transition;+ /** Increments when enter animation should replay. */+ revealEpoch: number;++ // Mouse position for dynamic tooltips+ mousePos: { x: number; y: number } | null;++ // Link path generator+ createPath: (link: SankeyLink<SankeyNodeDatum, SankeyLinkDatum>) => string;+}++const SankeyContext = createContext<SankeyContextValue | null>(null);++export function SankeyProvider({+ children,+ value,+}: {+ children: React.ReactNode;+ value: SankeyContextValue;+}) {+ return (+ <SankeyContext.Provider value={value}>{children}</SankeyContext.Provider>+ );+}++export function useSankey(): SankeyContextValue {+ const context = useContext(SankeyContext);+ if (!context) {+ throw new Error('useSankey must be used within a SankeyProvider');+ }+ return context;+}++// CSS variables for sankey theming+export const sankeyCssVars = {+ background: 'var(--chart-background)',+ foreground: 'var(--chart-foreground)',+ nodePrimary: 'var(--chart-line-primary)',+ nodeSecondary: 'var(--chart-line-secondary)',+ linkColor: 'var(--chart-foreground-muted, hsl(0, 0%, 50%))',+};diff --git a/apps/start/src/components/charts/sankey/sankey-link.tsx b/apps/start/src/components/charts/sankey/sankey-link.tsxnew file mode 100644index 000000000..40de4be8c--- /dev/null+++ b/apps/start/src/components/charts/sankey/sankey-link.tsx@@ -0,0 +1,348 @@+'use client';++import type {+ SankeyLink as SankeyLinkType,+ SankeyNode as SankeyNodeType,+} from 'd3-sankey';+import { motion, useTransform } from 'motion/react';+import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { useMountProgress } from '../use-mount-progress';+import {+ type SankeyLinkDatum,+ type SankeyNodeDatum,+ useSankey,+} from './sankey-context';++// Helper to get node index from link source/target+type NodeOrIndex = SankeyNodeType<SankeyNodeDatum, SankeyLinkDatum> | number;++function getNodeIndex(nodeOrIndex: NodeOrIndex): number | undefined {+ if (typeof nodeOrIndex === 'number') {+ return nodeOrIndex;+ }+ return nodeOrIndex.index;+}++function getNodeObject(+ nodeOrIndex: NodeOrIndex+): SankeyNodeType<SankeyNodeDatum, SankeyLinkDatum> | null {+ if (typeof nodeOrIndex === 'number') {+ return null;+ }+ return nodeOrIndex;+}++// Default node color palette using CSS variables+const defaultColors = [+ 'var(--chart-1)',+ 'var(--chart-2)',+ 'var(--chart-3)',+ 'var(--chart-4)',+ 'var(--chart-5)',+];++function getDefaultNodeColor(+ node: SankeyNodeType<SankeyNodeDatum, SankeyLinkDatum>+): string {+ const index = node.index ?? 0;+ return defaultColors[index % defaultColors.length] ?? 'var(--chart-1)';+}++export interface SankeyLinkProps {+ /** Stroke color for links (overrides gradient). Default: uses gradient */+ stroke?: string;+ /** Stroke opacity. Default: 0.5 */+ strokeOpacity?: number;+ /** Opacity when another link/node is hovered. Default: 0.1 */+ fadedOpacity?: number;+ /** Pixels taken off each link's width, so adjacent links read as separate bands. Default: 0 */+ linkGap?: number;+ /** Use gradient from source to target color. Default: true */+ useGradient?: boolean;+ /** Custom function to get node color (for gradient) */+ getNodeColor?: (+ node: SankeyNodeType<SankeyNodeDatum, SankeyLinkDatum>,+ index: number+ ) => string;+ /** Custom link color function (overrides gradient) */+ getLinkColor?: (+ link: SankeyLinkType<SankeyNodeDatum, SankeyLinkDatum>,+ index: number+ ) => string;+ /** Pattern definitions to render in defs. Use @visx/pattern components (PatternLines, PatternCircles, etc.) */+ patterns?: React.ReactNode;+ /** Return pattern ID for a link, or null/undefined to use gradient/solid color */+ getLinkPattern?: (+ link: SankeyLinkType<SankeyNodeDatum, SankeyLinkDatum>,+ index: number+ ) => string | null | undefined;+}++interface AnimatedLinkProps {+ path: string;+ width: number;+ stroke: string;+ strokeOpacity: number;+ index: number;+ totalLinks: number;+ isFaded: boolean;+ isHighlighted: boolean;+ fadedOpacity: number;+ animationDuration: number;+ onMouseEnter: () => void;+ onMouseLeave: () => void;+}++function AnimatedLink({+ path,+ width,+ stroke,+ strokeOpacity,+ index,+ totalLinks,+ isFaded,+ isHighlighted,+ fadedOpacity,+ animationDuration,+ onMouseEnter,+ onMouseLeave,+}: AnimatedLinkProps) {+ const { enterTransition, revealEpoch } = useSankey();+ const pathRef = useRef<SVGPathElement>(null);+ const [pathLength, setPathLength] = useState(0);++ // Links animate during the last 80% of total duration, starting at 20%+ const linkStartDelay = animationDuration * 0.2;+ const linkAnimDuration = animationDuration * 0.8;+ const staggerDelaySeconds =+ (linkStartDelay + (index / totalLinks) * linkAnimDuration * 0.4) / 1000;++ useLayoutEffect(() => {+ if (pathRef.current) {+ const length = pathRef.current.getTotalLength();+ setPathLength(length);+ }+ });++ const progress = useMountProgress(+ enterTransition,+ staggerDelaySeconds,+ `${revealEpoch}-${index}`+ );+ const strokeDashoffset = useTransform(progress, [0, 1], [pathLength, 0]);++ // Calculate target opacity+ const getTargetOpacity = () => {+ if (isFaded) {+ return fadedOpacity;+ }+ if (isHighlighted) {+ return Math.min(1, strokeOpacity * 1.3);+ }+ return strokeOpacity;+ };+ const targetOpacity = getTargetOpacity();++ // Dasharray for path reveal+ const dashArray = pathLength > 0 ? `${pathLength} ${pathLength}` : 'none';++ // Ensure opacity values are always numbers+ const initialOpacity = strokeOpacity ?? 0.5;+ const animatedOpacity = targetOpacity ?? initialOpacity;++ return (+ <motion.path+ animate={{ opacity: animatedOpacity }}+ d={path}+ fill="none"+ initial={{ opacity: initialOpacity }}+ onMouseEnter={onMouseEnter}+ onMouseLeave={onMouseLeave}+ ref={pathRef}+ stroke={stroke}+ strokeDasharray={dashArray}+ strokeWidth={Math.max(1, width)}+ style={{+ cursor: 'pointer',+ strokeDashoffset,+ }}+ transition={{ duration: 0.18, ease: 'easeOut' }}+ />+ );+}++export function SankeyLink({+ stroke,+ strokeOpacity = 0.5,+ fadedOpacity = 0.1,+ linkGap = 0,+ useGradient = true,+ getNodeColor,+ getLinkColor,+ patterns,+ getLinkPattern,+}: SankeyLinkProps) {+ const {+ links,+ hoveredNodeIndex,+ hoveredLinkIndex,+ setHoveredLinkIndex,+ setTooltipData,+ animationDuration,+ createPath,+ } = useSankey();++ // Get color for a node (for gradients)+ const getNodeColorFn = useCallback(+ (node: SankeyNodeType<SankeyNodeDatum, SankeyLinkDatum>): string => {+ if (getNodeColor) {+ return getNodeColor(node, node.index ?? 0);+ }+ return getDefaultNodeColor(node);+ },+ [getNodeColor]+ );++ // Get color for a link (solid color, when not using gradient)+ const getLinkColorFn = useCallback(+ (link: SankeyLinkType<SankeyNodeDatum, SankeyLinkDatum>, index: number) => {+ if (getLinkColor) {+ return getLinkColor(link, index);+ }+ return stroke || 'var(--chart-line-primary)';+ },+ [getLinkColor, stroke]+ );++ // Check if any element is hovered+ const isAnyHovered = hoveredNodeIndex !== null || hoveredLinkIndex !== null;++ // Build gradient definitions for all links+ const gradientDefs = useMemo(() => {+ if (!useGradient || stroke || getLinkColor) {+ return null;+ }++ return links.map((link, index) => {+ const sourceNode = getNodeObject(link.source as NodeOrIndex);+ const targetNode = getNodeObject(link.target as NodeOrIndex);++ // Always define a gradient so `url(#...)` never points to a missing id.+ // Use fallback colors if nodes can't be resolved+ const sourceColor = sourceNode+ ? getNodeColorFn(sourceNode)+ : 'var(--chart-1)';+ const targetColor = targetNode+ ? getNodeColorFn(targetNode)+ : 'var(--chart-1)';+ const gradientId = `link-gradient-${index}`;++ // Get absolute x positions for gradient+ // Use userSpaceOnUse to avoid issues with horizontal links (where bounding box has zero height)+ const x1 = sourceNode?.x1 ?? 0;+ const x2 = targetNode?.x0 ?? 100;++ return (+ <linearGradient+ gradientUnits="userSpaceOnUse"+ id={gradientId}+ key={gradientId}+ x1={x1}+ x2={x2}+ y1="0"+ y2="0"+ >+ <stop offset="0%" stopColor={sourceColor} stopOpacity={1} />+ <stop offset="100%" stopColor={targetColor} stopOpacity={1} />+ </linearGradient>+ );+ });+ }, [links, useGradient, stroke, getLinkColor, getNodeColorFn]);++ return (+ <g className="sankey-links">+ {/* Pattern and gradient definitions */}+ <defs>+ {patterns}+ {gradientDefs}+ </defs>++ {/* Links */}+ {links.map((link, index) => {+ const path = createPath(link);+ const linkWidth = Math.max(1, (link.width ?? 1) - linkGap);++ // Skip if path is empty+ if (!path || path.trim() === '') {+ return null;+ }++ const sIdx = getNodeIndex(link.source as NodeOrIndex);+ const tIdx = getNodeIndex(link.target as NodeOrIndex);++ // Use fallback indices if we can't resolve+ const sourceIdx =+ sIdx ?? (typeof link.source === 'number' ? link.source : -1);+ const targetIdx =+ tIdx ?? (typeof link.target === 'number' ? link.target : -1);++ const isHighlighted =+ hoveredLinkIndex === index ||+ hoveredNodeIndex === sourceIdx ||+ hoveredNodeIndex === targetIdx;+ const isFaded = isAnyHovered && !isHighlighted;++ const handleMouseEnter = () => {+ setHoveredLinkIndex(index);+ setTooltipData({+ type: 'link',+ linkIndex: index,+ x: 0,+ y: 0,+ data: link,+ });+ };++ const handleMouseLeave = () => {+ setHoveredLinkIndex(null);+ setTooltipData(null);+ };++ // Determine stroke color (pattern URL, gradient URL, or solid color)+ let linkStroke: string;+ const patternId = getLinkPattern?.(link, index);+ if (patternId) {+ // Use pattern fill+ linkStroke = `url(#${patternId})`;+ } else if (useGradient && !stroke && !getLinkColor) {+ // Use gradient+ linkStroke = `url(#link-gradient-${index})`;+ } else {+ linkStroke = getLinkColorFn(link, index);+ }++ return (+ <AnimatedLink+ animationDuration={animationDuration}+ fadedOpacity={fadedOpacity}+ index={index}+ isFaded={isFaded}+ isHighlighted={isHighlighted}+ key={`link-${sourceIdx}-${targetIdx}-${link.width ?? link.value ?? ''}`}+ onMouseEnter={handleMouseEnter}+ onMouseLeave={handleMouseLeave}+ path={path}+ stroke={linkStroke}+ strokeOpacity={strokeOpacity}+ totalLinks={links.length}+ width={linkWidth}+ />+ );+ })}+ </g>+ );+}++SankeyLink.displayName = 'SankeyLink';++export default SankeyLink;diff --git a/apps/start/src/components/charts/sankey/sankey-node.tsx b/apps/start/src/components/charts/sankey/sankey-node.tsxnew file mode 100644index 000000000..e3a976959--- /dev/null+++ b/apps/start/src/components/charts/sankey/sankey-node.tsx@@ -0,0 +1,462 @@+'use client';++import type { SankeyNode as SankeyNodeType } from 'd3-sankey';+import { motion, type Transition } from 'motion/react';+import { type ReactNode, useCallback, useMemo } from 'react';+import { intFmt } from '../chart-formatters';+import { transitionWithDelay } from '../motion-utils';+import {+ type SankeyLinkDatum,+ type SankeyNodeDatum,+ useSankey,+} from './sankey-context';++// Helper to get node index from link source/target+type NodeOrIndex = SankeyNodeType<SankeyNodeDatum, SankeyLinkDatum> | number;++export type SankeyLabelOrientation = 'horizontal' | 'vertical';++function getNodeIndex(nodeOrIndex: NodeOrIndex): number | undefined {+ if (typeof nodeOrIndex === 'number') {+ return nodeOrIndex;+ }+ return nodeOrIndex.index;+}++export interface SankeyNodeProps {+ /** Fill color for nodes. Default: uses theme colors */+ fill?: string;+ /** Corner radius for nodes. Default: 4 */+ lineCap?: number;+ /** Opacity when another node/link is hovered. Default: 0.4 */+ fadedOpacity?: number;+ /** Show node labels. Default: true */+ showLabels?: boolean;+ /** Show value labels under node names. Default: true */+ showValueLabels?: boolean;+ /**+ * Label reading direction for outside node labels.+ * - "horizontal": labels sit left/right of nodes (default).+ * - "vertical": labels rotate 90° and read along the node edge.+ */+ labelOrientation?: SankeyLabelOrientation;+ /** Custom node color function */+ getNodeColor?: (+ node: SankeyNodeType<SankeyNodeDatum, SankeyLinkDatum>,+ index: number+ ) => string;+}++type TextAnchor = 'start' | 'middle' | 'end';++interface NodeLabelLayout {+ x: number;+ y: number;+ textAnchor: TextAnchor;+ dy: string;+ textLocalX: number;+ rotate: number;+ initialX: number;+ initialY: number;+}++const LABEL_OFFSET = 12;+const VALUE_LABEL_GAP = 16;++function getNodeLabelLayouts({+ labelOrientation,+ isLeftSide,+ x,+ y,+ width,+ height,+ showValueLabels,+}: {+ labelOrientation: SankeyLabelOrientation;+ isLeftSide: boolean;+ x: number;+ y: number;+ width: number;+ height: number;+ showValueLabels: boolean;+}): { name: NodeLabelLayout; value: NodeLabelLayout | null } {+ const centerY = y + height / 2;+ const initialX = isLeftSide ? x + 8 : x + width - 8;++ if (labelOrientation === 'horizontal') {+ const labelX = isLeftSide ? x - LABEL_OFFSET : x + width + LABEL_OFFSET;+ const textAnchor: TextAnchor = isLeftSide ? 'end' : 'start';++ return {+ name: {+ x: labelX,+ y: centerY,+ textAnchor,+ dy: '0.35em',+ textLocalX: 0,+ rotate: 0,+ initialX,+ initialY: centerY,+ },+ value: showValueLabels+ ? {+ x: labelX,+ y: centerY + VALUE_LABEL_GAP,+ textAnchor,+ dy: '0.35em',+ textLocalX: 0,+ rotate: 0,+ initialX,+ initialY: centerY + VALUE_LABEL_GAP,+ }+ : null,+ };+ }++ const labelX = isLeftSide ? x - LABEL_OFFSET : x + width + LABEL_OFFSET;+ const rotate = isLeftSide ? -90 : 90;+ const halfGap = VALUE_LABEL_GAP / 2;+ let nameLocalX = 0;+ if (showValueLabels) {+ nameLocalX = isLeftSide ? halfGap : -halfGap;+ }+ const valueLocalX = isLeftSide ? -halfGap : halfGap;++ return {+ name: {+ x: labelX,+ y: centerY,+ textAnchor: 'middle',+ dy: '0.35em',+ textLocalX: nameLocalX,+ rotate,+ initialX,+ initialY: centerY,+ },+ value: showValueLabels+ ? {+ x: labelX,+ y: centerY,+ textAnchor: 'middle',+ dy: '0.35em',+ textLocalX: valueLocalX,+ rotate,+ initialX,+ initialY: centerY,+ }+ : null,+ };+}++interface AnimatedNodeProps {+ x: number;+ y: number;+ width: number;+ height: number;+ fill: string;+ rx: number;+ index: number;+ totalNodes: number;+ isFaded: boolean;+ fadedOpacity: number;+ animationDuration: number;+ onMouseEnter: () => void;+ onMouseLeave: () => void;+ name: string;+ value: number;+ isLeftSide: boolean;+ showLabels: boolean;+ showValueLabels: boolean;+ labelOrientation: SankeyLabelOrientation;+}++function NodeLabel({+ layout,+ opacity,+ transition,+ className,+ children,+}: {+ layout: NodeLabelLayout;+ opacity: number;+ transition: Transition;+ className: string;+ children: ReactNode;+}) {+ return (+ <motion.g+ animate={{+ opacity,+ x: layout.x,+ y: layout.y,+ rotate: layout.rotate,+ }}+ initial={{+ opacity: 0,+ x: layout.initialX,+ y: layout.initialY,+ rotate: layout.rotate,+ }}+ transition={transition}+ >+ <text+ className={className}+ dy={layout.dy}+ textAnchor={layout.textAnchor}+ x={layout.textLocalX}+ >+ {children}+ </text>+ </motion.g>+ );+}++function AnimatedNode({+ x,+ y,+ width,+ height,+ fill,+ rx,+ index,+ totalNodes,+ isFaded,+ fadedOpacity,+ animationDuration,+ onMouseEnter,+ onMouseLeave,+ name,+ value,+ isLeftSide,+ showLabels,+ showValueLabels,+ labelOrientation,+}: AnimatedNodeProps) {+ const { enterTransition, revealEpoch } = useSankey();++ const nodeAnimDuration = animationDuration * 0.6;+ const staggerDelaySec =+ ((index / totalNodes) * nodeAnimDuration * 0.4) / 1000;+ const nameLabelDelaySec =+ staggerDelaySec + (nodeAnimDuration * 0.6 * 0.3) / 1000;+ const valueLabelDelaySec = nameLabelDelaySec + 0.06;++ const nodeEnter = transitionWithDelay(enterTransition, staggerDelaySec);+ const nameEnter = transitionWithDelay(enterTransition, nameLabelDelaySec);+ const valueEnter = transitionWithDelay(enterTransition, valueLabelDelaySec);+ const nodeOpacity = isFaded ? fadedOpacity : 1;+ const nameOpacity = isFaded ? fadedOpacity : 1;+ const valueOpacity = isFaded ? fadedOpacity * 0.8 : 0.6;+ const labelLayouts = getNodeLabelLayouts({+ labelOrientation,+ isLeftSide,+ x,+ y,+ width,+ height,+ showValueLabels,+ });++ return (+ <motion.g+ onMouseEnter={onMouseEnter}+ onMouseLeave={onMouseLeave}+ style={{ cursor: 'pointer' }}+ >+ <motion.rect+ animate={{ opacity: nodeOpacity, scaleY: 1 }}+ fill={fill}+ height={height}+ initial={{ opacity: 0, scaleY: 0 }}+ key={`node-${index}-${revealEpoch}`}+ rx={rx}+ ry={rx}+ style={{ originY: 0.5 }}+ transition={nodeEnter}+ width={width}+ x={x}+ y={y}+ />+ {showLabels ? (+ <>+ <NodeLabel+ className="fill-foreground font-medium text-[13px]"+ key={`name-${index}-${revealEpoch}`}+ layout={labelLayouts.name}+ opacity={nameOpacity}+ transition={nameEnter}+ >+ {name}+ </NodeLabel>+ {labelLayouts.value ? (+ <NodeLabel+ className="fill-foreground text-[11px]"+ key={`value-${index}-${revealEpoch}`}+ layout={labelLayouts.value}+ opacity={valueOpacity}+ transition={valueEnter}+ >+ {intFmt(value)} sessions+ </NodeLabel>+ ) : null}+ </>+ ) : null}+ </motion.g>+ );+}++export function SankeyNode({+ fill,+ lineCap = 4,+ fadedOpacity = 0.4,+ showLabels = true,+ showValueLabels = true,+ labelOrientation = 'horizontal',+ getNodeColor: getNodeColorProp,+}: SankeyNodeProps) {+ const {+ nodes,+ links,+ width,+ margin,+ hoveredNodeIndex,+ hoveredLinkIndex,+ setHoveredNodeIndex,+ setTooltipData,+ animationDuration,+ } = useSankey();++ // Default colors using CSS variables+ const defaultColors = useMemo(+ () => [+ 'var(--chart-1)',+ 'var(--chart-2)',+ 'var(--chart-3)',+ 'var(--chart-4)',+ 'var(--chart-5)',+ ],+ []+ );++ // Get color for a node+ const getColor = useCallback(+ (+ node: SankeyNodeType<SankeyNodeDatum, SankeyLinkDatum>,+ index: number+ ): string => {+ if (fill) {+ return fill;+ }+ if (getNodeColorProp) {+ return getNodeColorProp(node, index);+ }++ return defaultColors[index % defaultColors.length] ?? 'var(--chart-1)';+ },+ [fill, getNodeColorProp, defaultColors]+ );++ // Check if a node is connected to the hovered element+ const isNodeConnected = useCallback(+ (nodeIndex: number) => {+ if (hoveredNodeIndex !== null) {+ if (hoveredNodeIndex === nodeIndex) {+ return true;+ }+ return links.some((link) => {+ const sIdx = getNodeIndex(link.source as NodeOrIndex);+ const tIdx = getNodeIndex(link.target as NodeOrIndex);+ return (+ (sIdx === hoveredNodeIndex && tIdx === nodeIndex) ||+ (tIdx === hoveredNodeIndex && sIdx === nodeIndex)+ );+ });+ }+ if (hoveredLinkIndex !== null) {+ const link = links[hoveredLinkIndex];+ if (!link) {+ return false;+ }+ const sIdx = getNodeIndex(link.source as NodeOrIndex);+ const tIdx = getNodeIndex(link.target as NodeOrIndex);+ return sIdx === nodeIndex || tIdx === nodeIndex;+ }+ return false;+ },+ [hoveredNodeIndex, hoveredLinkIndex, links]+ );++ const isAnyHovered = hoveredNodeIndex !== null || hoveredLinkIndex !== null;+ const innerWidth = width - margin.left - margin.right;++ return (+ <g className="sankey-nodes">+ {nodes.map((node, index) => {+ const nodeX = node.x0 ?? 0;+ const nodeY = node.y0 ?? 0;+ const nodeWidth = (node.x1 ?? 0) - nodeX;+ const nodeHeight = (node.y1 ?? 0) - nodeY;++ const isConnected = isNodeConnected(index);+ const isFaded = isAnyHovered && !isConnected;+ const isLeftSide = nodeX < innerWidth / 2;++ let displayValue = 0;+ for (const l of links) {+ const sIdx = getNodeIndex(l.source as NodeOrIndex);+ const tIdx = getNodeIndex(l.target as NodeOrIndex);+ if (node.category === 'source' && sIdx === index) {+ displayValue += l.value;+ } else if (node.category !== 'source' && tIdx === index) {+ displayValue += l.value;+ }+ }++ const handleMouseEnter = () => {+ setHoveredNodeIndex(index);+ setTooltipData({+ type: 'node',+ nodeIndex: index,+ x: 0,+ y: 0,+ data: node,+ });+ };++ const handleMouseLeave = () => {+ setHoveredNodeIndex(null);+ setTooltipData(null);+ };++ return (+ <AnimatedNode+ animationDuration={animationDuration}+ fadedOpacity={fadedOpacity}+ fill={getColor(node, index)}+ height={nodeHeight}+ index={index}+ isFaded={isFaded}+ isLeftSide={isLeftSide}+ key={`node-${node.name}`}+ labelOrientation={labelOrientation}+ name={node.name}+ onMouseEnter={handleMouseEnter}+ onMouseLeave={handleMouseLeave}+ rx={lineCap}+ showLabels={showLabels}+ showValueLabels={showValueLabels}+ totalNodes={nodes.length}+ value={displayValue}+ width={nodeWidth}+ x={nodeX}+ y={nodeY}+ />+ );+ })}+ </g>+ );+}++SankeyNode.displayName = 'SankeyNode';++export default SankeyNode;diff --git a/apps/start/src/components/charts/sankey/sankey-tooltip.tsx b/apps/start/src/components/charts/sankey/sankey-tooltip.tsxnew file mode 100644index 000000000..d696f8d99--- /dev/null+++ b/apps/start/src/components/charts/sankey/sankey-tooltip.tsx@@ -0,0 +1,179 @@+'use client';++import type { SankeyLink, SankeyNode } from 'd3-sankey';+import { intFmt } from '../chart-formatters';+import { TooltipBox } from '../tooltip/tooltip-box';+import { TooltipContent, type TooltipRow } from '../tooltip/tooltip-content';+import {+ type SankeyLinkDatum,+ type SankeyNodeDatum,+ useSankey,+} from './sankey-context';++// Helper to get node name from link source/target+type NodeOrIndex = SankeyNode<SankeyNodeDatum, SankeyLinkDatum> | number;++function getNodeName(nodeOrIndex: NodeOrIndex, fallbackIndex: number): string {+ if (typeof nodeOrIndex === 'number') {+ return `Node ${nodeOrIndex}`;+ }+ return nodeOrIndex.name ?? `Node ${fallbackIndex}`;+}++export interface SankeyTooltipProps {+ /** Custom content renderer for node tooltips */+ nodeContent?: (props: {+ node: SankeyNode<SankeyNodeDatum, SankeyLinkDatum>;+ index: number;+ }) => React.ReactNode;+ /** Custom content renderer for link tooltips */+ linkContent?: (props: {+ link: SankeyLink<SankeyNodeDatum, SankeyLinkDatum>;+ index: number;+ }) => React.ReactNode;+ /** Value formatter function */+ formatValue?: (value: number) => string;+ /** Custom class name */+ className?: string;+}++export function SankeyTooltip({+ nodeContent,+ linkContent,+ formatValue = intFmt,+ className = '',+}: SankeyTooltipProps) {+ const {+ tooltipData,+ containerRef,+ width,+ height,+ margin,+ nodes,+ links,+ mousePos,+ } = useSankey();++ if (!tooltipData) {+ return null;+ }++ // Use mouse position if available, otherwise fallback to anchor point+ const x = mousePos ? mousePos.x : tooltipData.x + margin.left;+ const y = mousePos ? mousePos.y : tooltipData.y + margin.top;++ // Render node tooltip+ if (tooltipData.type === 'node' && tooltipData.nodeIndex !== undefined) {+ const node = nodes[tooltipData.nodeIndex];+ if (!node) {+ return null;+ }++ // Calculate total value flowing through this node+ const totalValue = node.value ?? 0;++ // Custom content+ if (nodeContent) {+ return (+ <TooltipBox+ className={className}+ containerHeight={height}+ containerRef={containerRef}+ containerWidth={width}+ visible+ x={x}+ y={y}+ >+ {nodeContent({ node, index: tooltipData.nodeIndex })}+ </TooltipBox>+ );+ }++ // Default node tooltip+ const rows: TooltipRow[] = [+ {+ color: 'var(--chart-line-primary)',+ label: 'Sessions',+ value: formatValue(totalValue),+ },+ ];++ return (+ <TooltipBox+ className={className}+ containerHeight={height}+ containerRef={containerRef}+ containerWidth={width}+ visible+ x={x}+ y={y}+ >+ <TooltipContent rows={rows} title={node.name} />+ </TooltipBox>+ );+ }++ // Render link tooltip+ if (tooltipData.type === 'link' && tooltipData.linkIndex !== undefined) {+ const link = links[tooltipData.linkIndex];+ if (!link) {+ return null;+ }++ // Get source and target names+ const sourceName = getNodeName(+ link.source as NodeOrIndex,+ tooltipData.linkIndex+ );+ const targetName = getNodeName(+ link.target as NodeOrIndex,+ tooltipData.linkIndex+ );++ // Custom content+ if (linkContent) {+ return (+ <TooltipBox+ className={className}+ containerHeight={height}+ containerRef={containerRef}+ containerWidth={width}+ visible+ x={x}+ y={y}+ >+ {linkContent({ link, index: tooltipData.linkIndex })}+ </TooltipBox>+ );+ }++ // Default link tooltip+ const rows: TooltipRow[] = [+ {+ color: 'var(--chart-foreground-muted)',+ label: 'Flow',+ value: formatValue(link.value),+ },+ ];++ return (+ <TooltipBox+ className={className}+ containerHeight={height}+ containerRef={containerRef}+ containerWidth={width}+ visible+ x={x}+ y={y}+ >+ <TooltipContent rows={rows} title={`${sourceName} → ${targetName}`} />+ </TooltipBox>+ );+ }++ return null;+}++SankeyTooltip.displayName = 'SankeyTooltip';++export default SankeyTooltip;diff --git a/apps/start/src/components/charts/series-bar.tsx b/apps/start/src/components/charts/series-bar.tsxindex d9ded91ff..076cff7c2 100644--- a/apps/start/src/components/charts/series-bar.tsx+++ b/apps/start/src/components/charts/series-bar.tsx@@ -3,7 +3,7 @@import type { Transition } from 'motion/react';import { motion } from 'motion/react';import { useMemo } from 'react';-import { chartCssVars, useChart } from './chart-context';+import { chartCssVars, useChart, useYScale } from './chart-context';import { transitionWithDelay } from './motion-utils';import { computeSeriesBarWidth } from './series-bar-layout';@@ -81,6 +81,8 @@ function computeSeriesBarLayout(input: {export interface SeriesBarProps {/** Key in data for bar height (y value) */dataKey: string;+ /** Y-scale group id (Recharts `yAxisId`). Default: `"left"`. */+ yAxisId?: string | number;/** Fill color. Default: var(--chart-line-primary) */fill?: string;/** Tooltip dot color when fill is gradient/pattern. Default: fill */@@ -95,6 +97,7 @@ export interface SeriesBarProps {export function SeriesBar({dataKey,+ yAxisId,fill = chartCssVars.linePrimary,radius = 0,animate = true,@@ -103,7 +106,6 @@ export function SeriesBar({const {data,xScale,- yScale,xAccessor,innerHeight,innerWidth,@@ -122,6 +124,7 @@ export function SeriesBar({composedStackGap,tooltipData,} = useChart();+ const yScale = useYScale(yAxisId);const barKeys = useMemo(() => {if (composedBarDataKeys && composedBarDataKeys.length > 0) {diff --git a/apps/start/src/components/charts/series-dash-tail-overlay.tsx b/apps/start/src/components/charts/series-dash-tail-overlay.tsxindex 2580a45bf..230e0ad41 100644--- a/apps/start/src/components/charts/series-dash-tail-overlay.tsx+++ b/apps/start/src/components/charts/series-dash-tail-overlay.tsx@@ -40,23 +40,6 @@ function SeriesDashTailOverlayImpl({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;}@@ -64,12 +47,10 @@ function SeriesDashTailOverlayImpl({return (<DashTailStrokedashArray={dashArray}- dashStartLength={dashStartLength}dashStartX={dashStartX}innerHeight={innerHeight}innerWidth={innerWidth}pathD={pathD}- pathLength={pathLength}stroke={stroke}strokeWidth={strokeWidth}/>diff --git a/apps/start/src/components/charts/series-hover-dim.tsx b/apps/start/src/components/charts/series-hover-dim.tsxindex bb3e802e4..43070ba98 100644--- a/apps/start/src/components/charts/series-hover-dim.tsx+++ b/apps/start/src/components/charts/series-hover-dim.tsx@@ -3,6 +3,7 @@import { motion } from 'motion/react';import type { ReactNode } from 'react';import { useChartHover } from './chart-context';+import { useChartLegendHover } from './chart-legend-hover';interface SeriesHoverDimProps {/** Skip the dim entirely. */@@ -11,6 +12,8 @@ interface SeriesHoverDimProps {dimOpacity?: number;/** Tween duration in seconds. */durationSec?: number;+ /** Series index for multi-series legend hover dimming. */+ seriesIndex?: number;/** Stable chart visuals — area fill, stroke line, dashed tail, etc. */children: ReactNode;}@@ -29,11 +32,18 @@ export function SeriesHoverDim({enabled = true,dimOpacity = 0.5,durationSec = 0.4,+ seriesIndex,children,}: SeriesHoverDimProps) {const { tooltipData, selection } = useChartHover();- const isHovering = tooltipData !== null || selection?.active === true;- const opacity = enabled && isHovering ? dimOpacity : 1;+ const { hoveredIndex: legendHoveredIndex } = useChartLegendHover();+ const isChartHovering = tooltipData !== null || selection?.active === true;+ const isLegendDimmed =+ legendHoveredIndex !== null &&+ seriesIndex !== undefined &&+ legendHoveredIndex !== seriesIndex;+ const opacity =+ enabled && (isChartHovering || isLegendDimmed) ? dimOpacity : 1;return (<motion.ganimate={{ opacity }}diff --git a/apps/start/src/components/charts/series-markers.tsx b/apps/start/src/components/charts/series-markers.tsxindex 361f5ece6..9148b3c6e 100644--- a/apps/start/src/components/charts/series-markers.tsx+++ b/apps/start/src/components/charts/series-markers.tsx@@ -6,7 +6,9 @@ import {defaultScatterColors,useChartHover,useChartStable,+ useYScale,} from './chart-context';+import { useChartLegendHover } from './chart-legend-hover';import {getSeriesMarkerVisualExtent,SeriesPointMarker,@@ -61,7 +63,6 @@ export function SeriesMarkers({const {data,xScale,- yScale,innerWidth,enterTransition,animationDuration,@@ -77,6 +78,7 @@ export function SeriesMarkers({}, [lines, dataKey]);const seriesConfig = lines[seriesIndex];+ const yScale = useYScale(seriesConfig?.yAxisId);const seriesColor =defaultScatterColors[seriesIndex % defaultScatterColors.length] ??defaultScatterColors[0];@@ -199,6 +201,7 @@ export function SeriesMarkers({enabled={fadeOnHover}inactiveBlur={inactiveBlur}inactiveOpacity={inactiveOpacity}+ seriesIndex={seriesIndex}>{baseMarkers}</SeriesMarkersDimWrapper>@@ -218,6 +221,7 @@ interface SeriesMarkersDimWrapperProps {enabled: boolean;inactiveOpacity: number;inactiveBlur: number;+ seriesIndex: number;children: ReactNode;}@@ -230,10 +234,14 @@ function SeriesMarkersDimWrapper({enabled,inactiveOpacity,inactiveBlur,+ seriesIndex,children,}: SeriesMarkersDimWrapperProps) {const { tooltipData } = useChartHover();- const dimBase = enabled && tooltipData !== null;+ const { hoveredIndex: legendHoveredIndex } = useChartLegendHover();+ const isLegendDimmed =+ legendHoveredIndex !== null && legendHoveredIndex !== seriesIndex;+ const dimBase = enabled && (tooltipData !== null || isLegendDimmed);return (<gopacity={dimBase ? inactiveOpacity : 1}diff --git a/apps/start/src/components/charts/series-path-utils.ts b/apps/start/src/components/charts/series-path-utils.tsnew file mode 100644index 000000000..76d7af2f3--- /dev/null+++ b/apps/start/src/components/charts/series-path-utils.ts@@ -0,0 +1,108 @@+import { line as d3Line } from 'd3-shape';++// biome-ignore lint/suspicious/noExplicitAny: d3 curve factory type+type CurveFactory = any;++export interface SeriesPathPoint {+ x: number;+ y: number;+ key: string;+}++export function computeSeriesPathPoints(+ data: Record<string, unknown>[],+ xAccessor: (datum: Record<string, unknown>) => Date,+ xScale: (value: Date) => number | undefined,+ yScale: (value: number) => number | undefined,+ dataKey: string+): SeriesPathPoint[] {+ return data.map((datum, index) => {+ const xValue = xAccessor(datum);+ const yValue = datum[dataKey];+ return {+ x: xScale(xValue) ?? 0,+ y: typeof yValue === 'number' ? (yScale(yValue) ?? 0) : 0,+ key: String(xValue.getTime?.() ?? index),+ };+ });+}++export function interpolateSeriesPathPoints(+ from: SeriesPathPoint[],+ to: SeriesPathPoint[],+ progress: number+): SeriesPathPoint[] {+ if (progress >= 1) {+ return to;+ }+ if (progress <= 0) {+ return from.length > 0 ? from : to;+ }++ const fromByKey = new Map(from.map((point) => [point.key, point]));++ return to.map((target, index) => {+ const source = fromByKey.get(target.key);+ if (source) {+ return {+ key: target.key,+ x: source.x + (target.x - source.x) * progress,+ y: source.y + (target.y - source.y) * progress,+ };+ }++ const previousTarget = index > 0 ? to[index - 1] : undefined;+ const previousSource = previousTarget+ ? fromByKey.get(previousTarget.key)+ : undefined;+ const nextTarget = index < to.length - 1 ? to[index + 1] : undefined;+ const nextSource = nextTarget ? fromByKey.get(nextTarget.key) : undefined;+ const anchor = previousSource ?? nextSource ?? from[0] ?? target;++ return {+ key: target.key,+ x: anchor.x + (target.x - anchor.x) * progress,+ y: anchor.y + (target.y - anchor.y) * progress,+ };+ });+}++export function seriesPathFromPoints(+ points: SeriesPathPoint[],+ curve: CurveFactory+): string {+ if (points.length === 0) {+ return '';+ }++ const generator = d3Line<SeriesPathPoint>()+ .x((point) => point.x)+ .y((point) => point.y)+ .curve(curve);++ return generator(points) ?? '';+}++export function seriesPathTransitionSignature({+ renderData,+ xAccessor,+ dataKey,+ innerWidth,+ xDomainMin,+ xDomainMax,+}: {+ renderData: Record<string, unknown>[];+ xAccessor: (datum: Record<string, unknown>) => Date;+ dataKey: string;+ innerWidth: number;+ xDomainMin: number;+ xDomainMax: number;+}): string {+ const values = renderData.map((datum) => {+ const xValue = xAccessor(datum);+ const yValue = datum[dataKey];+ return `${xValue.getTime()}:${typeof yValue === 'number' ? yValue : ''}`;+ });++ return `${innerWidth}|${xDomainMin}|${xDomainMax}|${values.join(',')}`;+}diff --git a/apps/start/src/components/charts/static-chart-preview-context.tsx b/apps/start/src/components/charts/static-chart-preview-context.tsxnew file mode 100644index 000000000..0ecc42c14--- /dev/null+++ b/apps/start/src/components/charts/static-chart-preview-context.tsx@@ -0,0 +1,22 @@+'use client';++import { createContext, type ReactNode, useContext } from 'react';++const StaticChartPreviewContext = createContext(false);++/** Disables cartesian reveal clip-path for static docs previews. */+export function StaticChartPreviewProvider({+ children,+}: {+ children: ReactNode;+}) {+ return (+ <StaticChartPreviewContext.Provider value={true}>+ {children}+ </StaticChartPreviewContext.Provider>+ );+}++export function useStaticChartPreview() {+ return useContext(StaticChartPreviewContext);+}diff --git a/apps/start/src/components/charts/time-series-chart-shell.tsx b/apps/start/src/components/charts/time-series-chart-shell.tsxindex 6b757afbb..aa3a26896 100644--- a/apps/start/src/components/charts/time-series-chart-shell.tsx+++ b/apps/start/src/components/charts/time-series-chart-shell.tsx@@ -12,23 +12,74 @@ import {type ReactNode,useCallback,useEffect,+ useId,useMemo,useState,} from 'react';-import { DEFAULT_ANIMATION_EASING } from './animation';+import {+ DEFAULT_ANIMATION_EASING,+ DEFAULT_CHART_ENTER_TRANSITION,+} from './animation';+import {+ isClipExcludedComponent,+ isPostOverlayComponent,+ isUnderlayComponent,+ resolveChartChildElement,+} from './chart-child-passthrough';import { ChartProvider, type LineConfig, type Margin } from './chart-context';import { isGradientDefComponent, isPatternDefComponent } from './chart-defs';import { shortDateFmt } from './chart-formatters';+import {+ type ChartPhase,+ type ChartStatus,+ DEFAULT_CHART_STATUS,+ DEFAULT_Y_DOMAIN_TWEEN_MS,+ isChartInteractionPhase,+} from './chart-phase';import { ChartRevealClip } from './chart-reveal-clip';import {decimateTimeSeries,maxRenderPointsForWidth,} from './decimate-time-series';+import { filterDataByXDomain } from './filter-data-by-x-domain';+import {+ generateChartSkeletonData,+ generateChartSkeletonFromTarget,+} from './generate-chart-skeleton-data';+import {+ extractProjectionLineConfigs,+ mergeProjectionXDomainMax,+ mergeProjectionYDomain,+} from './projection-config';+import {+ extractReferenceAreaConfigs,+ type ReferenceAreaConfig,+} from './reference-area-config';+import { ReferenceAreaRegistrationContext } from './reference-area-registration-context';import {computeSeriesBarRevealClipPadding,computeSeriesBarWidth,} from './series-bar-layout';+import { useStaticChartPreview } from './static-chart-preview-context';+import { useAnimatedYDomains } from './use-animated-y-domains';import { useChartInteraction } from './use-chart-interaction';+import { useChartPhaseOrchestrator } from './use-chart-phase-orchestrator';+import {+ buildYScalesFromDomains,+ DEFAULT_Y_AXIS_ID,+ getPrimaryYScale,+ groupLinesByYAxisId,+} from './y-axis-scales';+import { computeYDomainsByAxis } from './y-domain-utils';++/**+ * Bleed around the series reveal clip so glyphs centred on the plot edge+ * (point markers, active rings, round stroke caps at min/max values) are not+ * cut in half once the reveal settles. The reveal only animates x, so the+ * vertical bleed is always applied; horizontal bleed is skipped while an+ * `xDomain` viewport is set because series then extend past the plot edges.+ */+const SERIES_CLIP_EDGE_BLEED = 24;function collectNumericExtents(data: Record<string, unknown>[],@@ -78,26 +129,6 @@ function resolveTimeSeriesYDomain(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;@@ -120,7 +151,10 @@ export interface TimeSeriesChartInnerProps {containerRef: React.RefObject<HTMLDivElement | null>;/** Series keys driving y-domain and tooltip (Line / Area / SeriesBar configs). */lines: LineConfig[];- /** SVG clipPath id for grow animation. */+ /**+ * Base SVG clipPath id for grow animation. Uniquified per chart instance so+ * multiple charts on one page do not share a clipPath (#226).+ */clipPathId: string;/** Optional ComposedChart bar layout (forwarded into context). */composedBarDataKeys?: string[];@@ -132,6 +166,27 @@ export interface TimeSeriesChartInnerProps {composedStackGap?: number;/** When set, drives the y-axis max instead of scanning `lines` (e.g. stacked bar totals). */yScaleDomainMax?: number;+ /** Loading vs ready — drives chart phase until transition orchestration lands. */+ chartStatus?: ChartStatus;+ loadingLabel?: string;+ /** Animate y-domain on status / data transitions. Default: true */+ yDomainTween?: boolean;+ yDomainTweenDuration?: number;+ /** Visible x-domain for brush zoom. When set, y-domain and series use data in this range. */+ xDomain?: [Date, Date];+ /** Full dataset length for x-scale padding when `xDomain` is set. */+ xDomainSlotCount?: number;+ /** Tween y-domain when the visible x-range changes during the ready phase. */+ tweenYDomainOnXDomainChange?: boolean;+ onPhaseChange?: (phase: ChartPhase) => void;+ /** Formats the x-axis and crosshair date labels. Default: `shortDateFmt`. */+ formatDateLabel?: (date: Date) => string;+ /** Fixed y domain, used as is: no headroom and no rounding. */+ yDomain?: [number, number];+ /** Fixed y domain per `yAxisId`; wins over `yDomain` for that axis. */+ yDomains?: Record<string, [number, number]>;+ /** Smallest value at the top, for "lower is better" metrics. */+ yReversed?: boolean;}export function TimeSeriesChartInner(props: TimeSeriesChartInnerProps) {@@ -164,13 +219,78 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({composedStackOffsets,composedStackGap,yScaleDomainMax,+ chartStatus = DEFAULT_CHART_STATUS,+ loadingLabel,+ yDomainTween = true,+ yDomainTweenDuration = DEFAULT_Y_DOMAIN_TWEEN_MS,+ xDomain,+ xDomainSlotCount,+ tweenYDomainOnXDomainChange = false,+ onPhaseChange,+ formatDateLabel = shortDateFmt.format,+ yDomain,+ yDomains,+ yReversed = false,}: TimeSeriesChartInnerProps) {- const [isLoaded, setIsLoaded] = useState(false);- const [revealEpoch, setRevealEpoch] = useState(0);-+ // Unique per instance — shared clipPath ids crop later charts (#226).+ const uniqueClipPathId = `${clipPathId}-${useId().replace(/:/g, '')}`;+ const staticPreview = useStaticChartPreview();const innerWidth = width - margin.left - margin.right;const innerHeight = height - margin.top - margin.bottom;+ const resolveYDomain = useCallback(+ (+ sourceData: Record<string, unknown>[],+ dataKeys: string[],+ axisId: string+ ) => {+ const fixedDomain = yDomains?.[axisId] ?? yDomain;+ if (fixedDomain) {+ return fixedDomain;+ }+ const axisGroups = groupLinesByYAxisId(lines);+ const usesDefaultOnly =+ axisGroups.size === 1 && axisGroups.has(DEFAULT_Y_AXIS_ID);+ const domainMax =+ usesDefaultOnly && yScaleDomainMax != null+ ? yScaleDomainMax+ : undefined;+ return resolveTimeSeriesYDomain(sourceData, dataKeys, domainMax);+ },+ [lines, yScaleDomainMax, yDomain, yDomains]+ );++ const skeletonData = useMemo(() => {+ const primaryKey = lines[0]?.dataKey ?? 'value';+ if (data.length === 0) {+ return generateChartSkeletonData({ dataKey: primaryKey });+ }+ return generateChartSkeletonFromTarget(data, primaryKey);+ }, [data, lines]);++ const {+ chartPhase,+ plotData,+ revealEpoch,+ concealEpoch,+ isLoaded,+ notifyLoadingPulseComplete,+ notifyRevealConcealComplete,+ notifyYDomainTweenComplete,+ } = useChartPhaseOrchestrator({+ animationDuration,+ chartStatus,+ revealSignature,+ skeletonData,+ skipEnterReveal: staticPreview,+ targetData: data,+ yDomainTweenDuration,+ });++ useEffect(() => {+ onPhaseChange?.(chartPhase);+ }, [chartPhase, onPhaseChange]);+const xAccessor = useCallback((d: Record<string, unknown>): Date => {const value = d[xDataKey];@@ -184,60 +304,147 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({[xAccessor]);+ const visiblePlotData = useMemo(() => {+ if (!xDomain) {+ return plotData;+ }+ return filterDataByXDomain(plotData, xDomain, xAccessor);+ }, [plotData, xDomain, xAccessor]);++ const projectionConfigs = useMemo(+ () => extractProjectionLineConfigs(children),+ [children]+ );+const xScale = useMemo(() => {- const timeExtent = extent(data, (d) => xAccessor(d).getTime());- const minTime = timeExtent[0] ?? 0;- const maxTime = timeExtent[1] ?? minTime;+ const minTime = xDomain+ ? xDomain[0].getTime()+ : (extent(plotData, (d) => xAccessor(d).getTime())[0] ?? 0);+ let maxTime = xDomain+ ? xDomain[1].getTime()+ : (extent(plotData, (d) => xAccessor(d).getTime())[1] ?? minTime);+ // Brush defines the viewport — projection horizon is included via brush+ // track extent, not by extending past the selection on the main chart.+ if (!xDomain) {+ maxTime = mergeProjectionXDomainMax(maxTime, projectionConfigs);+ }return scaleTime({range: [0, innerWidth],domain: [minTime, maxTime],});- }, [innerWidth, data, xAccessor]);+ }, [innerWidth, plotData, projectionConfigs, xAccessor, xDomain]);++ // When brushing, keep the full series for path rendering so edge fades stay+ // anchored to the viewport while the line pans through them. Y-domain and+ // interaction still use the filtered visible slice.+ const seriesSourceData = xDomain ? plotData : visiblePlotData;const renderData = useMemo(() => {const valueKeys = lines.map((line) => line.dataKey);return decimateTimeSeries(- data,+ seriesSourceData,maxRenderPointsForWidth(innerWidth),valueKeys);- }, [data, innerWidth, lines]);+ }, [seriesSourceData, innerWidth, lines]);const columnWidth = useMemo(() => {- if (data.length < 2) {+ const slotCount =+ xDomain && xDomainSlotCount != null+ ? xDomainSlotCount+ : visiblePlotData.length;+ if (slotCount < 2) {return 0;}- return innerWidth / (data.length - 1);- }, [innerWidth, data.length]);+ return innerWidth / (slotCount - 1);+ }, [innerWidth, visiblePlotData.length, xDomain, xDomainSlotCount]);++ const yDomainSkeletonByAxis = useMemo(+ () =>+ computeYDomainsByAxis({+ lines,+ resolveDomain: (dataKeys, axisId) =>+ resolveYDomain(skeletonData, dataKeys, axisId),+ }),+ [lines, resolveYDomain, skeletonData]+ );++ const yDomainTargetByAxis = useMemo(() => {+ const base = computeYDomainsByAxis({+ lines,+ resolveDomain: (dataKeys, axisId) =>+ resolveYDomain(xDomain ? visiblePlotData : data, dataKeys, axisId),+ });+ if (projectionConfigs.length === 0) {+ return base;+ }+ const merged: Record<string, [number, number]> = { ...base };+ for (const axisId of Object.keys(base)) {+ merged[axisId] = mergeProjectionYDomain(+ base[axisId] ?? [0, 100],+ projectionConfigs,+ axisId+ );+ }+ for (const config of projectionConfigs) {+ if (!merged[config.yAxisId]) {+ merged[config.yAxisId] = mergeProjectionYDomain(+ [0, 100],+ projectionConfigs,+ config.yAxisId+ );+ }+ }+ return merged;+ }, [+ data,+ lines,+ projectionConfigs,+ resolveYDomain,+ visiblePlotData,+ xDomain,+ ]);- const yScale = useMemo(() => {- const dataKeys = lines.map((line) => line.dataKey);- const domain = resolveTimeSeriesYDomain(data, dataKeys, yScaleDomainMax);+ const animatedYDomainsByAxis = useAnimatedYDomains({+ chartPhase,+ durationMs: yDomainTweenDuration,+ enabled: yDomainTween,+ onSettled: notifyYDomainTweenComplete,+ skeletonByAxis: yDomainSkeletonByAxis,+ targetByAxis: yDomainTargetByAxis,+ tweenOnTargetChange:+ yDomainTween || (tweenYDomainOnXDomainChange && xDomain != null),+ });- return scaleLinear({- range: [innerHeight, 0],- domain,+ const yDomainsForScales = animatedYDomainsByAxis;++ const yScales = useMemo(+ () =>+ buildYScalesFromDomains({+ domainsByAxis: yDomainsForScales,+ innerHeight,+ lines,+ reversed: yReversed,+ }),+ [yDomainsForScales, innerHeight, lines, yReversed]+ );++ const yScale = getPrimaryYScale(+ yScales,+ scaleLinear({+ range: yReversed ? [0, innerHeight] : [innerHeight, 0],+ domain: [0, 100],nice: true,- });- }, [innerHeight, data, lines, yScaleDomainMax]);+ })+ );const dateLabels = useMemo(- () => data.map((d) => shortDateFmt.format(xAccessor(d))),- [data, xAccessor]+ () => visiblePlotData.map((d) => formatDateLabel(xAccessor(d))),+ [visiblePlotData, xAccessor, formatDateLabel]);- // 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 canInteract = isLoaded && isChartInteractionPhase(chartPhase);const {tooltipData,@@ -247,17 +454,20 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({interactionHandlers,interactionStyle,} = useChartInteraction({- xScale,- yScale,- data,+ bisectDate,+ canInteract,+ data: visiblePlotData,lines,margin,xAccessor,- bisectDate,- canInteract,+ xScale,+ yScale,+ yScales,});const defsChildren: ReactElement[] = [];+ const clipExcludedChildren: ReactElement[] = [];+ const underlayChildren: ReactElement[] = [];const preOverlayChildren: ReactElement[] = [];const postOverlayChildren: ReactElement[] = [];@@ -267,25 +477,83 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({}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);+ const resolvedChild = resolveChartChildElement(keyedChild);++ if (isGradientDefComponent(resolvedChild)) {+ defsChildren.push(resolvedChild);+ } else if (isPatternDefComponent(resolvedChild)) {+ preOverlayChildren.push(resolvedChild);+ } else if (isPostOverlayComponent(resolvedChild)) {+ postOverlayChildren.push(resolvedChild);+ } else if (isClipExcludedComponent(resolvedChild)) {+ clipExcludedChildren.push(resolvedChild);+ } else if (isUnderlayComponent(resolvedChild)) {+ underlayChildren.push(resolvedChild);} else {- preOverlayChildren.push(keyedChild);+ preOverlayChildren.push(resolvedChild);}});+ const [registeredReferenceAreas, setRegisteredReferenceAreas] = useState(+ () => new Map<string, ReferenceAreaConfig>()+ );++ const registerReferenceArea = useCallback(+ (id: string, config: ReferenceAreaConfig) => {+ setRegisteredReferenceAreas((prev) => {+ const existing = prev.get(id);+ if (+ existing &&+ existing.yAxisId === config.yAxisId &&+ existing.y1 === config.y1 &&+ existing.y2 === config.y2 &&+ existing.axisLabelColor === config.axisLabelColor+ ) {+ return prev;+ }+ const next = new Map(prev);+ next.set(id, config);+ return next;+ });+ },+ []+ );++ const unregisterReferenceArea = useCallback((id: string) => {+ setRegisteredReferenceAreas((prev) => {+ if (!prev.has(id)) {+ return prev;+ }+ const next = new Map(prev);+ next.delete(id);+ return next;+ });+ }, []);++ const referenceAreaRegistration = useMemo(+ () => ({ registerReferenceArea, unregisterReferenceArea }),+ [registerReferenceArea, unregisterReferenceArea]+ );++ const referenceAreas = useMemo(() => {+ const extracted = extractReferenceAreaConfigs(children);+ const registered = [...registeredReferenceAreas.values()];+ if (registered.length === 0) {+ return extracted;+ }+ if (extracted.length === 0) {+ return registered;+ }+ return [...extracted, ...registered];+ }, [children, registeredReferenceAreas]);+const contextValue = useMemo(() => ({- data,+ data: visiblePlotData,renderData,xScale,yScale,+ yScales,width,height,innerWidth,@@ -296,13 +564,23 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({setTooltipData,containerRef,lines,+ referenceAreas,+ chartPhase,+ chartStatus,+ loadingLabel,+ yDomainTweenDuration,+ yDomainSkeletonByAxis,+ yDomainTargetByAxis,isLoaded,animationDuration,animationEasing,enterTransition,revealEpoch,+ notifyLoadingPulseComplete,xAccessor,dateLabels,+ xDomain,+ xDomainSlotCount,selection,clearSelection,composedBarDataKeys,@@ -314,10 +592,11 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({composedStackGap,}),[- data,+ visiblePlotData,renderData,xScale,yScale,+ yScales,width,height,innerWidth,@@ -328,13 +607,23 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({setTooltipData,containerRef,lines,+ referenceAreas,+ chartPhase,+ chartStatus,+ loadingLabel,+ yDomainTweenDuration,+ yDomainSkeletonByAxis,+ yDomainTargetByAxis,isLoaded,animationDuration,animationEasing,enterTransition,revealEpoch,+ notifyLoadingPulseComplete,xAccessor,dateLabels,+ xDomain,+ xDomainSlotCount,selection,clearSelection,composedBarDataKeys,@@ -347,40 +636,40 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({]);- // Single shared reveal clip for every series: one motion-driven attribute- // animation instead of one per line/area, with all series referencing the- // same `<clipPath>`. The wipe is a left-to-right unveil of static path- // geometry.- // 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(() => {+ const useClipReveal =+ !staticPreview &&+ renderData.length > 1 &&+ innerWidth > 0 &&+ animationDuration > 0;+ const isRevealAnimating = chartPhase === 'revealing';+ const isRevealConcealing =+ chartPhase === 'exitingReady' && animationDuration > 0;++ const effectiveEnterTransition: Transition =+ enterTransition ??+ ({+ ...DEFAULT_CHART_ENTER_TRANSITION,+ duration: animationDuration / 1000,+ } satisfies Transition);++ const barRevealClipPadding = useMemo(() => {if (!composedBarDataKeys?.length) {return 0;}const barWidth = computeSeriesBarWidth({- innerWidth,- dataLength: data.length,columnWidth,- seriesCount: composedBarDataKeys.length,+ composedBarGap,composedBarSize,composedMaxBarSize,- composedBarGap,+ dataLength: plotData.length,+ innerWidth,+ seriesCount: composedBarDataKeys.length,stacked: composedStacked,});return computeSeriesBarRevealClipPadding({barWidth,- seriesCount: composedBarDataKeys.length,gap: composedBarGap,+ seriesCount: composedBarDataKeys.length,stacked: composedStacked,});}, [@@ -390,50 +679,75 @@ const TimeSeriesChartCore = memo(function TimeSeriesChartCore({composedBarSize,composedMaxBarSize,composedStacked,- data.length,innerWidth,+ plotData.length,]);+ const revealClipPadding = xDomain+ ? barRevealClipPadding+ : Math.max(barRevealClipPadding, SERIES_CLIP_EDGE_BLEED);+ const revealClipPaddingY = Math.max(+ barRevealClipPadding,+ SERIES_CLIP_EDGE_BLEED+ );+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}+ <ReferenceAreaRegistrationContext.Provider+ value={referenceAreaRegistration}+ >+ <ChartProvider value={contextValue}>+ <svg+ aria-hidden="true"+ className="overflow-visible"+ height={height}+ width={width}+ >+ <defs>+ {defsChildren}+ {useClipReveal ? (+ <ChartRevealClip+ animating={isRevealAnimating || isRevealConcealing}+ clipPathId={uniqueClipPathId}+ enterTransition={effectiveEnterTransition}+ height={innerHeight}+ mode={isRevealConcealing ? 'conceal' : 'reveal'}+ onComplete={+ isRevealConcealing ? notifyRevealConcealComplete : undefined+ }+ padding={revealClipPadding}+ paddingY={revealClipPaddingY}+ revealEpoch={isRevealConcealing ? concealEpoch : 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}/>- ) : 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>+ {clipExcludedChildren}+ {underlayChildren}+ {useClipReveal ? (+ <g clipPath={`url(#${uniqueClipPathId})`}>{preOverlayChildren}</g>+ ) : (+ preOverlayChildren+ )}+ {postOverlayChildren}+ </g>+ </svg>+ </ChartProvider>+ </ReferenceAreaRegistrationContext.Provider>);});diff --git a/apps/start/src/components/charts/tooltip/chart-tooltip.tsx b/apps/start/src/components/charts/tooltip/chart-tooltip.tsxindex 2d921fd87..c08f4a807 100644--- a/apps/start/src/components/charts/tooltip/chart-tooltip.tsx+++ b/apps/start/src/components/charts/tooltip/chart-tooltip.tsx@@ -3,7 +3,11 @@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 {+ resolveTooltipBoxMotion,+ type SpringConfig,+ useChartConfig,+} from '../chart-config-context';import {chartCssVars,type LineConfig,@@ -11,6 +15,7 @@ import {useChartStable,} from '../chart-context';import { weekdayDateFmt } from '../chart-formatters';+import type { IndicatorFadeEdges } from '../indicator-fade';import { DateTicker } from './date-ticker';import { TooltipBox } from './tooltip-box';import { TooltipContent, type TooltipRow } from './tooltip-content';@@ -24,6 +29,29 @@ export interface ChartTooltipProps {showCrosshair?: boolean;/** Whether to show dots on the lines. Default: true */showDots?: boolean;+ /**+ * Dot style: filled circle with a soft same-color halo, or transparent ring.+ * Default: "dot"+ */+ dotVariant?: 'dot' | 'ring';+ /** Dot core / ring radius in pixels. Default: 5 */+ dotSize?: number;+ /**+ * `dot` variant: halo radius as a multiple of the core radius. `0` hides the halo.+ * Default: `2.6`+ */+ dotHaloScale?: number;+ /** `dot` variant: halo opacity (0–1). Default: `0.3` */+ dotHaloOpacity?: number;+ /** Ring corner radius as a fraction of side length (0 = square, 0.5 = circle). */+ dotRadiusFraction?: number;+ /** Multiplier applied to the computed dot / ring pixel radius. Default: 1 */+ dotScale?: number;+ /**+ * Ring stroke width in pixels (default `1.5`). For the `dot` variant, draws a+ * background-colored outline around the core (default `0`, none).+ */+ dotStrokeWidth?: number;/*** 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.@@ -49,8 +77,31 @@ export interface ChartTooltipProps {className?: string;/** Per-chart override for the crosshair / dot / date-pill spring. */springConfig?: SpringConfig;+ /**+ * When `true`, the floating panel uses the crosshair spring and stays in sync.+ * Default `false` — panel follow uses `damping` (`20`).+ */+ matchCrosshair?: boolean;+ /**+ * Spring damping for the floating tooltip panel when `matchCrosshair` is `false`.+ * `0` disables spring motion (instant). Default: `20`.+ */+ damping?: number;+ /** SVG stroke dash pattern for the crosshair. Omit for solid. */+ indicatorDasharray?: string;+ /** Vertical crosshair fade: `both`, `top`, `bottom`, or `none` (solid). Default: `both`. */+ indicatorFadeEdges?: IndicatorFadeEdges;+ /** Crosshair fade zone size (% of height). Default: `10`. */+ indicatorFadeLength?: number;/** Per-chart override for the floating-panel spring. */boxSpringConfig?: SpringConfig;+ /** Inline styles for the tooltip panel (background, blur, etc.). */+ panelStyle?: React.CSSProperties;+ /**+ * Tooltip panel background color (CSS variable or color value).+ * Default: `var(--chart-tooltip-background)`.+ */+ backgroundColor?: string;}interface ChartTooltipInnerProps extends ChartTooltipProps {@@ -61,6 +112,13 @@ const ChartTooltipInner = memo(function ChartTooltipInner({showDatePill = true,showCrosshair = true,showDots = true,+ dotVariant = 'dot',+ dotSize = 5,+ dotHaloScale,+ dotHaloOpacity,+ dotRadiusFraction,+ dotScale = 1,+ dotStrokeWidth,indicatorColor: indicatorColorProp,content,rows: rowsRenderer,@@ -69,7 +127,14 @@ const ChartTooltipInner = memo(function ChartTooltipInner({className = '',container,springConfig,+ matchCrosshair = false,+ damping,+ indicatorDasharray,+ indicatorFadeEdges,+ indicatorFadeLength,boxSpringConfig,+ panelStyle,+ backgroundColor,}: ChartTooltipInnerProps) {const {tooltipData,@@ -84,11 +149,53 @@ const ChartTooltipInner = memo(function ChartTooltipInner({containerRef,orientation,barXAccessor,+ bandWidth,+ squareSnap,} = useChart();+ const { tooltipSpring } = useChartConfig();const isHorizontal = orientation === 'horizontal';const discreteInteraction = dateLabels.length > 60;+ const resolvedDotSize = useMemo(() => {+ if (dotVariant !== 'ring' || !bandWidth || lines.length === 0) {+ return dotSize * dotScale;+ }+ const seriesCount = lines.length;+ const gap = squareSnap?.groupGap ?? (seriesCount > 1 ? 4 : 0);+ const squareSize = (bandWidth - gap * (seriesCount - 1)) / seriesCount;+ return (squareSize / 2) * dotScale;+ }, [+ bandWidth,+ dotScale,+ dotSize,+ dotVariant,+ lines.length,+ squareSnap?.groupGap,+ ]);+ const boxMotion = useMemo(() => {+ if (boxSpringConfig) {+ return {+ animate: !discreteInteraction,+ springConfig: boxSpringConfig,+ };+ }+ if (matchCrosshair) {+ return {+ animate: !discreteInteraction,+ springConfig: springConfig ?? tooltipSpring,+ };+ }+ return resolveTooltipBoxMotion(damping);+ }, [+ boxSpringConfig,+ damping,+ discreteInteraction,+ matchCrosshair,+ springConfig,+ tooltipSpring,+ ]);+const visible = tooltipData !== null;const x = tooltipData?.x ?? 0;const xWithMargin = x + margin.left;@@ -134,6 +241,7 @@ const ChartTooltipInner = memo(function ChartTooltipInner({};}, [dotColorProp, rowsRenderer, tooltipData, tooltipRows]);+ // Resolve indicator color (static or from hovered point)const indicatorColor = useMemo(() => {if (indicatorColorProp == null) {return chartCssVars.crosshair;@@ -146,13 +254,16 @@ const ChartTooltipInner = memo(function ChartTooltipInner({return indicatorColorProp;}, [indicatorColorProp, tooltipData]);+ // Title from date or categoryconst title = useMemo(() => {if (!tooltipData) {return undefined;}+ // For bar charts (horizontal or vertical), use the category nameif (barXAccessor) {return barXAccessor(tooltipData.point);}+ // For line/area charts, use the datereturn weekdayDateFmt.format(xAccessor(tooltipData.point));}, [tooltipData, barXAccessor, xAccessor]);@@ -162,7 +273,7 @@ const ChartTooltipInner = memo(function ChartTooltipInner({{showCrosshair && (<svgaria-hidden="true"- className="pointer-events-none absolute inset-0"+ className="pointer-events-none absolute inset-0 overflow-visible"height="100%"width="100%">@@ -172,9 +283,13 @@ const ChartTooltipInner = memo(function ChartTooltipInner({colorEdge={indicatorColor}colorMid={indicatorColor}columnWidth={columnWidth}- fadeEdges+ fadeEdges={+ indicatorDasharray ? 'none' : (indicatorFadeEdges ?? 'both')+ }+ fadeLength={indicatorFadeLength}height={innerHeight}springConfig={springConfig}+ strokeDasharray={indicatorDasharray}visible={visible}width="line"x={x}@@ -187,7 +302,7 @@ const ChartTooltipInner = memo(function ChartTooltipInner({{showDots && visible && !isHorizontal && (<svgaria-hidden="true"- className="pointer-events-none absolute inset-0"+ className="pointer-events-none absolute inset-0 overflow-visible"height="100%"width="100%">@@ -195,10 +310,20 @@ const ChartTooltipInner = memo(function ChartTooltipInner({{lines.map((line, index) => (<TooltipDotcolor={resolveDotColor(line, index)}+ cornerRadiusFraction={+ dotVariant === 'ring' ? dotRadiusFraction : undefined+ }+ haloOpacity={dotHaloOpacity}+ haloScale={dotHaloScale}key={line.dataKey}+ size={resolvedDotSize}springConfig={springConfig}strokeColor={chartCssVars.background}- visible={visible}+ strokeWidth={dotStrokeWidth}+ variant={dotVariant}+ visible={+ visible && tooltipData?.yPositions[line.dataKey] !== undefined+ }x={tooltipData?.xPositions?.[line.dataKey] ?? x}y={tooltipData?.yPositions[line.dataKey] ?? 0}/>@@ -207,12 +332,16 @@ const ChartTooltipInner = memo(function ChartTooltipInner({</svg>)}+ {/* Tooltip Box */}<TooltipBox+ animate={boxMotion.animate}+ backgroundColor={backgroundColor}className={className}containerHeight={height}containerRef={containerRef}containerWidth={width}- springConfig={boxSpringConfig}+ panelStyle={panelStyle}+ springConfig={boxMotion.springConfig}top={isHorizontal ? undefined : margin.top}visible={visible}x={xWithMargin}@@ -300,6 +429,11 @@ function DatePillTrackerInner({animatedX.set(xWithMargin);}+ // biome-ignore lint/correctness/useExhaustiveDependencies: we need to jump the animatedX when the visible prop changes+ useEffect(() => {+ animatedX.set(xWithMargin);+ }, [animatedX, visible]);+return (<motion.divclassName="pointer-events-none absolute z-50"diff --git a/apps/start/src/components/charts/tooltip/date-ticker.tsx b/apps/start/src/components/charts/tooltip/date-ticker.tsxindex fa9fdda61..896c3c4fb 100644--- a/apps/start/src/components/charts/tooltip/date-ticker.tsx+++ b/apps/start/src/components/charts/tooltip/date-ticker.tsx@@ -1,12 +1,64 @@'use client';-import { motion, useSpring } from 'motion/react';-import { memo, useMemo, useRef } from 'react';+import { type MotionValue, motion, useSpring } from 'motion/react';+import { memo, type RefObject, useLayoutEffect, useMemo, useRef } from 'react';const TICKER_ITEM_HEIGHT = 24;+const TICKER_SPRING = { stiffness: 400, damping: 35 };/** Full scroll stacks are skipped above this count — single label + instant updates. */const COMPACT_TICKER_THRESHOLD = 60;+/**+ * Widths of a stack's `[data-ticker-item]` children, re-measured when the+ * items or loaded fonts change. Drives `width` toward the active item so the+ * pill hugs the current label instead of the longest one.+ */+function useActiveItemWidth(+ stackRef: RefObject<HTMLElement | null>,+ items: readonly unknown[],+ activeIndex: number,+ width: MotionValue<number>+) {+ const widthsRef = useRef<number[]>([]);+ const activeIndexRef = useRef(activeIndex);+ activeIndexRef.current = activeIndex;++ // biome-ignore lint/correctness/useExhaustiveDependencies: items change the rendered stack, so re-measure+ useLayoutEffect(() => {+ let cancelled = false;+ const measure = (snap: boolean) => {+ const stack = stackRef.current;+ if (cancelled || !stack) {+ return;+ }+ widthsRef.current = Array.from(+ stack.querySelectorAll<HTMLElement>('[data-ticker-item]'),+ (node) => node.getBoundingClientRect().width+ );+ const next = widthsRef.current[activeIndexRef.current];+ if (next === undefined) {+ return;+ }+ // First measure snaps so the pill never grows in from zero.+ if (snap) {+ width.jump(next);+ } else {+ width.set(next);+ }+ };+ measure(widthsRef.current.length === 0);+ document.fonts?.ready.then(() => measure(false));+ return () => {+ cancelled = true;+ };+ }, [stackRef, items, width]);++ const target = widthsRef.current[activeIndex];+ if (target !== undefined) {+ width.set(target);+ }+}+export interface DateTickerProps {currentIndex: number;labels: string[];@@ -18,12 +70,27 @@ const DateTickerCompact = memo(function DateTickerCompact({labels,}: Omit<DateTickerProps, 'visible'>) {const label = labels[currentIndex] ?? labels[0] ?? '';+ const labelItems = useMemo(() => [label], [label]);+ const stackRef = useRef<HTMLDivElement>(null);+ const width = useSpring(0, TICKER_SPRING);+ useActiveItemWidth(stackRef, labelItems, 0, width);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>+ <motion.div className="relative h-6" style={{ width }}>+ <motion.div+ className="absolute top-0 left-1/2 flex h-6 items-center"+ ref={stackRef}+ style={{ x: '-50%' }}+ >+ <span+ className="whitespace-nowrap font-medium text-sm"+ data-ticker-item+ >+ {label}+ </span>+ </motion.div>+ </motion.div></div>);});@@ -78,8 +145,21 @@ const DateTickerInner = memo(function DateTickerInner({const prevMonthIndexRef = useRef(-1);// Animated Y offsets- const dayY = useSpring(0, { stiffness: 400, damping: 35 });- const monthY = useSpring(0, { stiffness: 400, damping: 35 });+ const dayY = useSpring(0, TICKER_SPRING);+ const monthY = useSpring(0, TICKER_SPRING);++ // Each stack's width follows its active item, so the pill resizes per label.+ const monthStackRef = useRef<HTMLDivElement>(null);+ const dayStackRef = useRef<HTMLDivElement>(null);+ const monthWidth = useSpring(0, TICKER_SPRING);+ const dayWidth = useSpring(0, TICKER_SPRING);+ useActiveItemWidth(+ monthStackRef,+ monthSegments,+ currentMonthIndex,+ monthWidth+ );+ useActiveItemWidth(dayStackRef, parsedLabels, currentIndex, dayWidth);dayY.set(-currentIndex * TICKER_ITEM_HEIGHT);@@ -96,11 +176,20 @@ const DateTickerInner = memo(function DateTickerInner({<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">- <div className="relative h-6 overflow-hidden">- <motion.div className="flex flex-col" style={{ y: monthY }}>+ {/* Month stack */}+ <motion.div+ className="relative h-6 overflow-hidden"+ style={{ width: monthWidth }}+ >+ <motion.div+ className="absolute top-0 left-1/2 flex flex-col items-center"+ ref={monthStackRef}+ style={{ x: '-50%', y: monthY }}+ >{monthSegments.map((segment) => (<divclassName="flex h-6 shrink-0 items-center justify-center"+ data-ticker-itemkey={segment.key}><span className="whitespace-nowrap font-medium text-sm">@@ -109,13 +198,22 @@ const DateTickerInner = memo(function DateTickerInner({</div>))}</motion.div>- </div>-- <div className="relative h-6 overflow-hidden">- <motion.div className="flex flex-col" style={{ y: dayY }}>+ </motion.div>++ {/* Day stack */}+ <motion.div+ className="relative h-6 overflow-hidden"+ style={{ width: dayWidth }}+ >+ <motion.div+ className="absolute top-0 left-1/2 flex flex-col items-center"+ ref={dayStackRef}+ style={{ x: '-50%', y: dayY }}+ >{parsedLabels.map((label) => (<divclassName="flex h-6 shrink-0 items-center justify-center"+ data-ticker-itemkey={label.key}><span className="whitespace-nowrap font-medium text-sm">@@ -124,7 +222,7 @@ const DateTickerInner = memo(function DateTickerInner({</div>))}</motion.div>- </div>+ </motion.div></div></div></div>diff --git a/apps/start/src/components/charts/tooltip/index.ts b/apps/start/src/components/charts/tooltip/index.tsindex 87b50bc70..e611e34dc 100644--- a/apps/start/src/components/charts/tooltip/index.ts+++ b/apps/start/src/components/charts/tooltip/index.ts@@ -4,6 +4,8 @@ export { TooltipBox, type TooltipBoxProps } from './tooltip-box';export {TooltipContent,type TooltipContentProps,+ TooltipHeader,+ type TooltipHeaderProps,type TooltipRow,} from './tooltip-content';export { TooltipDot, type TooltipDotProps } from './tooltip-dot';diff --git a/apps/start/src/components/charts/tooltip/tooltip-box.tsx b/apps/start/src/components/charts/tooltip/tooltip-box.tsxindex 182631f89..645e12af9 100644--- a/apps/start/src/components/charts/tooltip/tooltip-box.tsx+++ b/apps/start/src/components/charts/tooltip/tooltip-box.tsx@@ -5,6 +5,7 @@ import type { RefObject } from 'react';import { useEffect, useLayoutEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { type SpringConfig, useChartConfig } from '../chart-config-context';+import { chartCssVars } from '../chart-context';import { cn } from '@/lib/utils';export interface TooltipBoxProps {@@ -34,8 +35,31 @@ export interface TooltipBoxProps {flipped?: boolean;/** Per-chart override; falls back to `ChartConfigProvider.tooltipBoxSpring`. */springConfig?: SpringConfig;+ /** Animate panel position with a spring. Default: true */+ animate?: boolean;+ /** Fade/scale the panel on show. Default: true */+ entrance?: boolean;+ /** Inline styles for the inner tooltip panel. */+ panelStyle?: React.CSSProperties;+ /**+ * Tooltip panel background color (CSS variable or color value).+ * Default: `var(--chart-tooltip-background)`.+ */+ backgroundColor?: string;}+/**+ * Popover-style panel: rounded, 1px border, soft layered shadow and a 1px+ * edge highlight (`before:`) — matches shadcn / coss popovers using only theme+ * tokens (`border`, `--radius`) and Tailwind utilities.+ */+const TOOLTIP_PANEL_CLASS_NAME =+ 'relative min-w-[160px] rounded-xl border not-dark:bg-clip-padding text-chart-tooltip-foreground shadow-lg/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-xl)-1px)] before:shadow-[0_1px_rgb(0_0_0/0.04)] dark:before:shadow-[0_-1px_rgb(255_255_255/0.06)]';++/** Clips content to the panel's inner radius without clipping the edge highlight. */+const TOOLTIP_PANEL_INNER_CLASS_NAME =+ 'overflow-hidden rounded-[calc(var(--radius-xl)-1px)]';+// 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) {@@ -67,6 +91,10 @@ function TooltipBoxInner({top: topOverride,flipped: flippedOverride,springConfig,+ animate = true,+ entrance = true,+ panelStyle,+ backgroundColor = chartCssVars.tooltipBackground,container,}: Omit<TooltipBoxProps, 'visible' | 'containerRef'> & {container: HTMLElement;@@ -77,6 +105,7 @@ function TooltipBoxInner({const tooltipRef = useRef<HTMLDivElement>(null);const tooltipWidthRef = useRef(180);const tooltipHeightRef = useRef(80);+ const [staticPosition, setStaticPosition] = useState({ left: x, top: y });const tw = tooltipWidthRef.current;const th = tooltipHeightRef.current;@@ -90,10 +119,10 @@ function TooltipBoxInner({const animatedLeft = useSpring(targetX, effectiveSpring);const animatedTop = useSpring(targetY, effectiveSpring);- if (leftOverride === undefined) {+ if (animate && leftOverride === undefined) {animatedLeft.set(targetX);}- if (topOverride === undefined) {+ if (animate && topOverride === undefined) {animatedTop.set(targetY);}@@ -118,6 +147,10 @@ function TooltipBoxInner({offset,Math.min(y - h2 / 2, containerHeight - h2 - offset));+ if (!animate) {+ setStaticPosition({ left: tx, top: ty });+ return;+ }if (leftOverride === undefined) {animatedLeft.set(tx);}@@ -132,6 +165,7 @@ function TooltipBoxInner({offset,leftOverride,topOverride,+ animate,animatedLeft,animatedTop,]);@@ -146,11 +180,43 @@ function TooltipBoxInner({}}, [shouldFlipX]);- const finalLeft = leftOverride ?? animatedLeft;- const finalTop = topOverride ?? animatedTop;+ const finalLeft = animate+ ? (leftOverride ?? animatedLeft)+ : staticPosition.left;+ const finalTop = animate ? (topOverride ?? animatedTop) : staticPosition.top;const isFlipped = flippedOverride ?? shouldFlipX;const transformOrigin = isFlipped ? 'right top' : 'left top';+ const panelClassName = cn(+ TOOLTIP_PANEL_CLASS_NAME,+ panelStyle?.backgroundColor === undefined &&+ backgroundColor === chartCssVars.tooltipBackground &&+ 'bg-chart-tooltip-background',+ panelStyle?.backdropFilter === undefined && 'backdrop-blur-md'+ );+ const panelStyleResolved = {+ transformOrigin,+ ...(panelStyle?.backgroundColor === undefined && {+ backgroundColor,+ }),+ ...panelStyle,+ };++ if (!entrance) {+ return createPortal(+ <div+ className={cn('pointer-events-none absolute z-50', className)}+ ref={tooltipRef}+ style={{ left: staticPosition.left, top: staticPosition.top }}+ >+ <div className={panelClassName} style={panelStyleResolved}>+ <div className={TOOLTIP_PANEL_INNER_CLASS_NAME}>{children}</div>+ </div>+ </div>,+ container+ );+ }+return createPortal(<motion.divanimate={{ opacity: 1 }}@@ -163,13 +229,13 @@ function TooltipBoxInner({><motion.divanimate={{ 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"+ className={panelClassName}initial={{ scale: 0.85, opacity: 0, x: isFlipped ? 20 : -20 }}key={flipKey}- style={{ transformOrigin }}+ style={panelStyleResolved}transition={{ type: 'spring', stiffness: 300, damping: 25 }}>- {children}+ <div className={TOOLTIP_PANEL_INNER_CLASS_NAME}>{children}</div></motion.div></motion.div>,containerdiff --git a/apps/start/src/components/charts/tooltip/tooltip-content.tsx b/apps/start/src/components/charts/tooltip/tooltip-content.tsxindex 596d4bca5..fc4122b9f 100644--- a/apps/start/src/components/charts/tooltip/tooltip-content.tsx+++ b/apps/start/src/components/charts/tooltip/tooltip-content.tsx@@ -2,6 +2,7 @@import type { ReactNode } from 'react';import { intFmt } from '../chart-formatters';+import { cn } from '@/lib/utils';export interface TooltipRow {color: string;@@ -16,43 +17,75 @@ export interface TooltipContentProps {children?: ReactNode;}+export interface TooltipHeaderProps {+ children: ReactNode;+ className?: string;+}++/**+ * Popover-style header row: medium-weight label separated from the body by a+ * full-width border. Use it at the top of custom `ChartTooltip` `content`.+ */+export function TooltipHeader({ children, className }: TooltipHeaderProps) {+ return (+ <div+ className={cn(+ 'border-b px-3.5 py-2.5 text-left font-medium text-chart-tooltip-foreground text-sm',+ className+ )}+ >+ {children}+ </div>+ );+}++TooltipHeader.displayName = 'TooltipHeader';+export function TooltipContent({ title, rows, children }: TooltipContentProps) {+ const hasBody = rows.length > 0 || Boolean(children);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>+ {title && <TooltipHeader>{title}</TooltipHeader>}+ {hasBody && (+ <div className="px-3.5 py-3">+ {rows.length > 0 && (+ <div className="space-y-2">+ {rows.map((row) => (+ <div+ className="flex items-center justify-between gap-6"+ key={`${row.label}-${row.color}`}+ >+ <div className="flex min-w-0 items-center gap-2">+ <span+ className="size-2 shrink-0 rounded-full"+ style={{ backgroundColor: row.color }}+ />+ <span className="truncate text-chart-tooltip-muted text-sm">+ {row.label}+ </span>+ </div>+ <span className="text-right 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="flex items-center justify-between gap-4"- key={`${row.label}-${row.color}`}+ className={cn(+ 'transition-opacity duration-200 ease-out',+ rows.length > 0 && 'mt-2'+ )}>- <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>+ {children}</div>- ))}+ )}</div>-- {children && (- <div className="mt-2 transition-opacity duration-200 ease-out">- {children}- </div>- )}- </div>+ )}</div>);}diff --git a/apps/start/src/components/charts/tooltip/tooltip-dot.tsx b/apps/start/src/components/charts/tooltip/tooltip-dot.tsxindex cb1cb3278..cb85930ab 100644--- a/apps/start/src/components/charts/tooltip/tooltip-dot.tsx+++ b/apps/start/src/components/charts/tooltip/tooltip-dot.tsx@@ -1,6 +1,6 @@'use client';-import { motion, useSpring } from 'motion/react';+import { motion, useSpring, useTransform } from 'motion/react';import { type SpringConfig, useChartConfig } from '../chart-config-context';import { chartCssVars } from '../chart-context';@@ -9,11 +9,92 @@ export interface TooltipDotProps {y: number;visible: boolean;color: string;+ /** Core dot radius; half-extent for ring squares. Default: 5 */size?: number;+ /** Outline color for the `dot` variant. Default: `var(--chart-background)` */strokeColor?: string;+ /**+ * `dot`: outline width around the core (default `0`, no outline).+ * `ring`: ring stroke width (default `1.5`).+ */strokeWidth?: number;+ /**+ * `dot` variant: halo radius as a multiple of `size`. The halo is a soft disc+ * in the series color behind the core. `0` hides it. Default: `2.6`+ */+ haloScale?: number;+ /** `dot` variant: halo opacity (0–1). Default: `0.3` */+ haloOpacity?: number;+ /** Dot fill or transparent ring around the hovered mark. Default: "dot" */+ variant?: 'dot' | 'ring';+ /**+ * Ring corner radius as a fraction of side length (0 = square, 0.5 = circle).+ * Same semantics as bar square radius.+ */+ cornerRadiusFraction?: number;/** Per-chart override; falls back to `ChartConfigProvider.tooltipSpring`. */springConfig?: SpringConfig;+ /** Animate position with a spring. Default: true */+ animate?: boolean;+}++const DEFAULT_HALO_SCALE = 2.6;+const DEFAULT_HALO_OPACITY = 0.3;+/** Entrance spring for the core + halo radius (position uses the tooltip spring). */+const HALO_SPRING = { type: 'spring', stiffness: 420, damping: 28 } as const;++function ringCornerRadius(+ halfExtent: number,+ cornerRadiusFraction: number+): number {+ const side = halfExtent * 2;+ return side * Math.max(0, Math.min(0.5, cornerRadiusFraction));+}++function AnimatedRingDot({+ x,+ y,+ halfExtent,+ cornerRadiusFraction,+ fill,+ stroke,+ strokeWidth,+ springConfig,+}: {+ x: number;+ y: number;+ halfExtent: number;+ cornerRadiusFraction: number;+ fill: string;+ stroke: string;+ strokeWidth: number;+ springConfig?: SpringConfig;+}) {+ const { tooltipSpring } = useChartConfig();+ const effectiveSpring = springConfig ?? tooltipSpring;+ const animatedX = useSpring(x, effectiveSpring);+ const animatedY = useSpring(y, effectiveSpring);+ const side = halfExtent * 2;+ const rx = ringCornerRadius(halfExtent, cornerRadiusFraction);+ const rectX = useTransform(animatedX, (value) => value - halfExtent);+ const rectY = useTransform(animatedY, (value) => value - halfExtent);++ animatedX.set(x);+ animatedY.set(y);++ return (+ <motion.rect+ fill={fill}+ height={side}+ rx={rx}+ ry={rx}+ stroke={stroke}+ strokeWidth={strokeWidth}+ width={side}+ x={rectX}+ y={rectY}+ />+ );}export function TooltipDot({@@ -23,30 +104,113 @@ export function TooltipDot({color,size = 5,strokeColor = chartCssVars.background,- strokeWidth = 2,+ strokeWidth,+ haloScale = DEFAULT_HALO_SCALE,+ haloOpacity = DEFAULT_HALO_OPACITY,+ variant = 'dot',+ cornerRadiusFraction = 0.25,springConfig,+ animate = true,}: TooltipDotProps) {const { tooltipSpring } = useChartConfig();const effectiveSpring = springConfig ?? tooltipSpring;const animatedX = useSpring(x, effectiveSpring);const animatedY = useSpring(y, effectiveSpring);- animatedX.set(x);- animatedY.set(y);+ const isRing = variant === 'ring';++ if (animate && !isRing) {+ animatedX.set(x);+ animatedY.set(y);+ }if (!visible) {return null;}+ if (isRing) {+ const ringStrokeWidth = strokeWidth ?? 1.5;+ if (animate) {+ return (+ <AnimatedRingDot+ cornerRadiusFraction={cornerRadiusFraction}+ fill="transparent"+ halfExtent={size}+ springConfig={springConfig}+ stroke={color}+ strokeWidth={ringStrokeWidth}+ x={x}+ y={y}+ />+ );+ }++ const side = size * 2;+ const rx = ringCornerRadius(size, cornerRadiusFraction);++ return (+ <rect+ fill="transparent"+ height={side}+ rx={rx}+ ry={rx}+ stroke={color}+ strokeWidth={ringStrokeWidth}+ width={side}+ x={x - size}+ y={y - size}+ />+ );+ }++ const outlineWidth = strokeWidth ?? 0;+ const outline =+ outlineWidth > 0+ ? { stroke: strokeColor, strokeWidth: outlineWidth }+ : undefined;+ const haloRadius = Math.max(0, size * haloScale);+ const showHalo = haloRadius > size && haloOpacity > 0;++ if (!animate) {+ return (+ <g>+ {showHalo && (+ <circle+ cx={x}+ cy={y}+ fill={color}+ fillOpacity={haloOpacity}+ r={haloRadius}+ />+ )}+ <circle cx={x} cy={y} fill={color} r={size} {...outline} />+ </g>+ );+ }+return (- <motion.circle- cx={animatedX}- cy={animatedY}- fill={color}- r={size}- stroke={strokeColor}- strokeWidth={strokeWidth}- />+ <g>+ {showHalo && (+ <motion.circle+ animate={{ r: haloRadius }}+ cx={animatedX}+ cy={animatedY}+ fill={color}+ fillOpacity={haloOpacity}+ initial={{ r: size }}+ transition={HALO_SPRING}+ />+ )}+ <motion.circle+ animate={{ r: size }}+ cx={animatedX}+ cy={animatedY}+ fill={color}+ initial={{ r: size * 0.5 }}+ transition={HALO_SPRING}+ {...outline}+ />+ </g>);}diff --git a/apps/start/src/components/charts/tooltip/tooltip-indicator.tsx b/apps/start/src/components/charts/tooltip/tooltip-indicator.tsxindex f6a93cfab..1575f2aaa 100644--- a/apps/start/src/components/charts/tooltip/tooltip-indicator.tsx+++ b/apps/start/src/components/charts/tooltip/tooltip-indicator.tsx@@ -1,8 +1,14 @@'use client';import { motion, useSpring } from 'motion/react';+import { useEffect } from 'react';import { type SpringConfig, useChartConfig } from '../chart-config-context';import { chartCssVars } from '../chart-context';+import {+ type IndicatorFadeEdges,+ indicatorFadeGradientStops,+ resolveVerticalFadeSides,+} from '../indicator-fade';export type IndicatorWidth =| number // Pixel width@@ -34,14 +40,18 @@ export interface TooltipIndicatorProps {colorEdge?: string;/** Secondary color at center (50%) */colorMid?: string;- /** Whether to fade to transparent at 0% and 100% */- fadeEdges?: boolean;+ /** Vertical fade: both ends, top, bottom, or none (solid). */+ fadeEdges?: IndicatorFadeEdges | boolean;+ /** Fade zone size as a percentage of indicator height. Default: 10 */+ fadeLength?: number;/** 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;+ /** SVG stroke dash pattern. When set, renders a dashed stroke instead of a solid fill. */+ strokeDasharray?: string;}function resolveWidth(width: IndicatorWidth): number {@@ -73,17 +83,20 @@ export function TooltipIndicator(props: TooltipIndicatorProps) {function TooltipIndicatorInner({x,+ visible,height,width = 'line',span,columnWidth,colorEdge = chartCssVars.crosshair,colorMid = chartCssVars.crosshair,- fadeEdges = true,+ fadeEdges = 'both',+ fadeLength = 10,animate = true,gradientId = 'tooltip-indicator-gradient',springConfig,-}: Omit<TooltipIndicatorProps, 'visible'>) {+ strokeDasharray,+}: TooltipIndicatorProps) {const { tooltipSpring } = useChartConfig();const effectiveSpring = springConfig ?? tooltipSpring;@@ -93,29 +106,83 @@ function TooltipIndicatorInner({: resolveWidth(width);const rectX = x - pixelWidth / 2;+ const lineX = x;const animatedX = useSpring(rectX, effectiveSpring);+ const animatedLineX = useSpring(lineX, effectiveSpring);if (animate) {animatedX.set(rectX);+ animatedLineX.set(lineX);}- const edgeOpacity = fadeEdges ? 0 : 1;+ // biome-ignore lint/correctness/useExhaustiveDependencies: we need to jump the animatedX when the visible prop changes+ useEffect(() => {+ animatedX.set(rectX);+ animatedLineX.set(lineX);+ }, [animatedLineX, animatedX, lineX, rectX, visible]);++ const indicatorFill = colorMid || colorEdge;+ const fadeSides = resolveVerticalFadeSides(fadeEdges);+ const dashed = Boolean(strokeDasharray);++ if (dashed) {+ const strokeWidth = Math.max(1, pixelWidth);+ return animate ? (+ <motion.line+ stroke={indicatorFill}+ strokeDasharray={strokeDasharray}+ strokeWidth={strokeWidth}+ x1={animatedLineX}+ x2={animatedLineX}+ y1={0}+ y2={height}+ />+ ) : (+ <line+ stroke={indicatorFill}+ strokeDasharray={strokeDasharray}+ strokeWidth={strokeWidth}+ x1={lineX}+ x2={lineX}+ y1={0}+ y2={height}+ />+ );+ }++ if (!fadeSides.any) {+ return animate ? (+ <motion.rect+ fill={indicatorFill}+ height={height}+ width={pixelWidth}+ x={animatedX}+ y={0}+ />+ ) : (+ <rect+ fill={indicatorFill}+ height={height}+ width={pixelWidth}+ x={rectX}+ y={0}+ />+ );+ }++ const fadeStops = indicatorFadeGradientStops(fadeSides, fadeLength);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 }}- />+ {fadeStops.map((stop) => (+ <stop+ key={stop.offset}+ offset={stop.offset}+ style={{ stopColor: indicatorFill, stopOpacity: stop.opacity }}+ />+ ))}</linearGradient></defs>{animate ? (diff --git a/apps/start/src/components/charts/use-animated-series-path.ts b/apps/start/src/components/charts/use-animated-series-path.tsnew file mode 100644index 000000000..1aca2dd14--- /dev/null+++ b/apps/start/src/components/charts/use-animated-series-path.ts@@ -0,0 +1,165 @@+'use client';++import { animate, useReducedMotion } from 'motion/react';+import { useEffect, useMemo, useRef, useState } from 'react';+import { LINE_LOADING_PULSE_EASE } from './line-loading-timing';+import {+ computeSeriesPathPoints,+ interpolateSeriesPathPoints,+ type SeriesPathPoint,+ seriesPathFromPoints,+ seriesPathTransitionSignature,+} from './series-path-utils';++// biome-ignore lint/suspicious/noExplicitAny: d3 curve factory type+type CurveFactory = any;++export interface UseAnimatedSeriesPathOptions {+ renderData: Record<string, unknown>[];+ xAccessor: (datum: Record<string, unknown>) => Date;+ xScale: (value: Date) => number | undefined;+ yScale: (value: number) => number | undefined;+ dataKey: string;+ curve: CurveFactory;+ chartPhase: string;+ durationMs: number;+ innerWidth: number;+ enabled: boolean;+}++export function useAnimatedSeriesPath({+ renderData,+ xAccessor,+ xScale,+ yScale,+ dataKey,+ curve,+ chartPhase,+ durationMs,+ innerWidth,+ enabled,+}: UseAnimatedSeriesPathOptions) {+ const reducedMotion = useReducedMotion();+ const [animatedPoints, setAnimatedPoints] = useState<+ SeriesPathPoint[] | null+ >(null);+ const displayedPointsRef = useRef<SeriesPathPoint[] | null>(null);+ const animatingRef = useRef(false);++ const xScaleDomain = useMemo(() => {+ const scaleWithDomain = xScale as { domain?: () => [Date, Date] };+ return scaleWithDomain.domain?.() ?? [new Date(0), new Date(0)];+ }, [xScale]);++ const transitionSignature = useMemo(+ () =>+ seriesPathTransitionSignature({+ renderData,+ xAccessor,+ dataKey,+ innerWidth,+ xDomainMin: xScaleDomain[0]?.getTime?.() ?? 0,+ xDomainMax: xScaleDomain[1]?.getTime?.() ?? 0,+ }),+ [renderData, xAccessor, dataKey, innerWidth, xScaleDomain]+ );++ const targetPoints = useMemo(+ () =>+ computeSeriesPathPoints(renderData, xAccessor, xScale, yScale, dataKey),+ [renderData, xAccessor, xScale, yScale, dataKey]+ );++ const prevTransitionSignatureRef = useRef(transitionSignature);++ useEffect(() => {+ if (!animatingRef.current) {+ displayedPointsRef.current = targetPoints;+ }+ }, [targetPoints]);++ useEffect(() => {+ const shouldAnimate =+ enabled &&+ !reducedMotion &&+ chartPhase === 'ready' &&+ durationMs > 0 &&+ renderData.length > 0;++ if (!shouldAnimate) {+ animatingRef.current = false;+ setAnimatedPoints(null);+ displayedPointsRef.current = targetPoints;+ prevTransitionSignatureRef.current = transitionSignature;+ return;+ }++ if (prevTransitionSignatureRef.current === transitionSignature) {+ return;+ }+ prevTransitionSignatureRef.current = transitionSignature;++ const fromPoints = displayedPointsRef.current ?? targetPoints;+ if (fromPoints.length === 0) {+ displayedPointsRef.current = targetPoints;+ return;+ }++ animatingRef.current = true;+ const fromSnapshot = fromPoints;++ const control = animate(0, 1, {+ duration: durationMs / 1000,+ ease: [...LINE_LOADING_PULSE_EASE],+ onUpdate: (progress) => {+ const currentTarget = computeSeriesPathPoints(+ renderData,+ xAccessor,+ xScale,+ yScale,+ dataKey+ );+ const next = interpolateSeriesPathPoints(+ fromSnapshot,+ currentTarget,+ progress+ );+ displayedPointsRef.current = next;+ setAnimatedPoints(next);+ },+ onComplete: () => {+ animatingRef.current = false;+ displayedPointsRef.current = targetPoints;+ setAnimatedPoints(null);+ },+ });++ return () => {+ control.stop();+ animatingRef.current = false;+ };+ }, [+ transitionSignature,+ chartPhase,+ durationMs,+ enabled,+ reducedMotion,+ renderData,+ xAccessor,+ xScale,+ yScale,+ dataKey,+ targetPoints,+ ]);++ const activePoints = animatedPoints ?? targetPoints;+ const pathD = useMemo(+ () => seriesPathFromPoints(activePoints, curve),+ [activePoints, curve]+ );++ return {+ pathD,+ isPathAnimating: animatedPoints != null,+ };+}diff --git a/apps/start/src/components/charts/use-animated-y-domains.ts b/apps/start/src/components/charts/use-animated-y-domains.tsnew file mode 100644index 000000000..cf0a53253--- /dev/null+++ b/apps/start/src/components/charts/use-animated-y-domains.ts@@ -0,0 +1,242 @@+'use client';++import { animate, useReducedMotion } from 'motion/react';+import { useEffect, useRef, useState } from 'react';+import type { ChartPhase } from './chart-phase';+import { LINE_LOADING_PULSE_EASE } from './line-loading-timing';+import {+ domainsEqual,+ isYDomainTweenPhase,+ resolveAnimatedYDestinationDomains,+ shouldTweenYDomain,+ type YDomain,+} from './y-domain-utils';++function lerpDomain(from: YDomain, to: YDomain, progress: number): YDomain {+ return [+ from[0] + (to[0] - from[0]) * progress,+ from[1] + (to[1] - from[1]) * progress,+ ];+}++function snapDomains(+ domains: Record<string, YDomain>,+ setAnimatedByAxis: (domains: Record<string, YDomain>) => void,+ animatedRef: { current: Record<string, YDomain> }+) {+ if (domainsEqual(animatedRef.current, domains)) {+ return;+ }+ setAnimatedByAxis(domains);+ animatedRef.current = domains;+}++function tweenDomains({+ destination,+ durationMs,+ enabled,+ reducedMotion,+ animatedRef,+ setAnimatedByAxis,+ onSettled,+}: {+ destination: Record<string, YDomain>;+ durationMs: number;+ enabled: boolean;+ reducedMotion: boolean | null;+ animatedRef: { current: Record<string, YDomain> };+ setAnimatedByAxis: (domains: Record<string, YDomain>) => void;+ onSettled?: () => void;+}) {+ if (domainsEqual(animatedRef.current, destination)) {+ onSettled?.();+ return;+ }++ if (!enabled || reducedMotion) {+ snapDomains(destination, setAnimatedByAxis, animatedRef);+ onSettled?.();+ return;+ }++ const axisIds = Object.keys(destination);+ const fromSnapshot = animatedRef.current;++ let needsTween = false;+ for (const axisId of axisIds) {+ const from =+ fromSnapshot[axisId] ?? destination[axisId] ?? ([0, 100] as YDomain);+ const to = destination[axisId] ?? from;+ if (shouldTweenYDomain(from, to)) {+ needsTween = true;+ break;+ }+ }++ if (!needsTween) {+ snapDomains(destination, setAnimatedByAxis, animatedRef);+ onSettled?.();+ return;+ }++ const fromByAxis: Record<string, YDomain> = {};+ for (const axisId of axisIds) {+ fromByAxis[axisId] = fromSnapshot[axisId] ??+ destination[axisId] ?? [0, 100];+ }++ const control = animate(0, 1, {+ duration: durationMs / 1000,+ ease: [...LINE_LOADING_PULSE_EASE],+ onUpdate: (progress) => {+ const next: Record<string, YDomain> = {};+ for (const axisId of axisIds) {+ const from =+ fromByAxis[axisId] ?? destination[axisId] ?? ([0, 100] as YDomain);+ const to = destination[axisId] ?? from;+ next[axisId] = shouldTweenYDomain(from, to)+ ? lerpDomain(from, to, progress)+ : to;+ }+ animatedRef.current = next;+ setAnimatedByAxis(next);+ },+ onComplete: () => {+ snapDomains(destination, setAnimatedByAxis, animatedRef);+ onSettled?.();+ },+ });++ return control;+}++export interface UseAnimatedYDomainsOptions {+ enabled: boolean;+ durationMs: number;+ chartPhase: ChartPhase;+ skeletonByAxis: Record<string, YDomain>;+ targetByAxis: Record<string, YDomain>;+ onSettled?: () => void;+ /** When true, tweens y-domains on target changes while the chart is in the ready phase (e.g. brush zoom). */+ tweenOnTargetChange?: boolean;+}++export function useAnimatedYDomains({+ enabled,+ durationMs,+ chartPhase,+ skeletonByAxis,+ targetByAxis,+ onSettled,+ tweenOnTargetChange = false,+}: UseAnimatedYDomainsOptions): Record<string, YDomain> {+ const reducedMotion = useReducedMotion();+ const destinationByAxis = resolveAnimatedYDestinationDomains(+ chartPhase,+ skeletonByAxis,+ targetByAxis+ );+ const destinationRef = useRef(destinationByAxis);+ destinationRef.current = destinationByAxis;+ const skeletonRef = useRef(skeletonByAxis);+ skeletonRef.current = skeletonByAxis;+ const targetRef = useRef(targetByAxis);+ targetRef.current = targetByAxis;++ const [animatedByAxis, setAnimatedByAxis] = useState(destinationByAxis);+ const animatedRef = useRef(animatedByAxis);+ const prevPhaseRef = useRef(chartPhase);+ const onSettledRef = useRef(onSettled);+ onSettledRef.current = onSettled;++ useEffect(() => {+ animatedRef.current = animatedByAxis;+ }, [animatedByAxis]);++ useEffect(() => {+ if (prevPhaseRef.current === chartPhase) {+ return;+ }+ prevPhaseRef.current = chartPhase;++ const settle = () => {+ onSettledRef.current?.();+ };++ // Keep grid spacing frozen while the series exits the viewport.+ if (chartPhase === 'exiting') {+ snapDomains(skeletonRef.current, setAnimatedByAxis, animatedRef);+ return;+ }+ if (chartPhase === 'exitingReady') {+ snapDomains(targetRef.current, setAnimatedByAxis, animatedRef);+ return;+ }+ if (chartPhase === 'loading') {+ snapDomains(skeletonRef.current, setAnimatedByAxis, animatedRef);+ return;+ }+ if (chartPhase === 'revealing' || chartPhase === 'ready') {+ snapDomains(targetRef.current, setAnimatedByAxis, animatedRef);+ return;+ }++ if (!isYDomainTweenPhase(chartPhase)) {+ return;+ }++ const control = tweenDomains({+ destination: destinationRef.current,+ durationMs,+ enabled,+ reducedMotion,+ animatedRef,+ setAnimatedByAxis,+ onSettled: settle,+ });++ return () => control?.stop();+ }, [chartPhase, durationMs, enabled, reducedMotion]);++ const targetSignature = JSON.stringify(targetByAxis);+ const prevTargetSignatureRef = useRef(targetSignature);++ useEffect(() => {+ const inLivePhase = chartPhase === 'ready' || chartPhase === 'revealing';++ if (!inLivePhase) {+ prevTargetSignatureRef.current = targetSignature;+ return;+ }++ if (prevTargetSignatureRef.current === targetSignature) {+ return;+ }+ prevTargetSignatureRef.current = targetSignature;++ if (tweenOnTargetChange && chartPhase === 'ready') {+ const control = tweenDomains({+ destination: targetRef.current,+ durationMs,+ enabled,+ reducedMotion,+ animatedRef,+ setAnimatedByAxis,+ onSettled: () => onSettledRef.current?.(),+ });++ return () => control?.stop();+ }++ snapDomains(targetRef.current, setAnimatedByAxis, animatedRef);+ }, [+ chartPhase,+ durationMs,+ enabled,+ reducedMotion,+ targetSignature,+ tweenOnTargetChange,+ ]);++ return animatedByAxis;+}diff --git a/apps/start/src/components/charts/use-area-segment-highlight.ts b/apps/start/src/components/charts/use-area-segment-highlight.tsdeleted file mode 100644index 91d2c0480..000000000--- a/apps/start/src/components/charts/use-area-segment-highlight.ts+++ /dev/null@@ -1,163 +0,0 @@-'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.tsindex d12875b8f..02e5a686f 100644--- a/apps/start/src/components/charts/use-chart-interaction.ts+++ b/apps/start/src/components/charts/use-chart-interaction.ts@@ -2,9 +2,10 @@import { localPoint } from '@visx/event';import type { scaleLinear, scaleTime } from '@visx/scale';-import { useCallback, useRef, useState } from 'react';+import { useCallback, useEffect, useRef, useState } from 'react';import type { LineConfig, Margin, TooltipData } from './chart-context';import { useScheduledTooltip } from './use-scheduled-tooltip';+import { normalizeYAxisId } from './y-axis-scales';type ScaleTime = ReturnType<typeof scaleTime<number>>;type ScaleLinear = ReturnType<typeof scaleLinear<number>>;@@ -20,6 +21,7 @@ export interface ChartSelection {interface UseChartInteractionParams {xScale: ScaleTime;yScale: ScaleLinear;+ yScales: Record<string, ScaleLinear>;data: Record<string, unknown>[];lines: LineConfig[];margin: Margin;@@ -52,6 +54,7 @@ interface ChartInteractionResult {export function useChartInteraction({xScale,yScale,+ yScales,data,lines,margin,@@ -70,6 +73,7 @@ export function useChartInteraction({const isDraggingRef = useRef(false);const dragStartXRef = useRef<number>(0);+ const lastHoveredXRef = useRef<number | null>(null);const resolveTooltipFromX = useCallback((pixelX: number): TooltipData | null => {@@ -97,7 +101,8 @@ export function useChartInteraction({for (const line of lines) {const value = d[line.dataKey];if (typeof value === 'number') {- yPositions[line.dataKey] = yScale(value) ?? 0;+ const axisScale = yScales[normalizeYAxisId(line.yAxisId)] ?? yScale;+ yPositions[line.dataKey] = axisScale(value) ?? 0;}}@@ -108,7 +113,7 @@ export function useChartInteraction({yPositions,};},- [xScale, yScale, data, lines, xAccessor, bisectDate]+ [xScale, yScale, yScales, data, lines, xAccessor, bisectDate]);const resolveIndexFromX = useCallback(@@ -181,6 +186,7 @@ export function useChartInteraction({return;}+ lastHoveredXRef.current = chartX;const tooltip = resolveTooltipFromX(chartX);if (tooltip) {scheduleTooltip(tooltip);@@ -190,6 +196,7 @@ export function useChartInteraction({);const handleMouseLeave = useCallback(() => {+ lastHoveredXRef.current = null;clearTooltip();if (isDraggingRef.current) {isDraggingRef.current = false;@@ -226,6 +233,7 @@ export function useChartInteraction({if (chartX === null) {return;}+ lastHoveredXRef.current = chartX;const tooltip = resolveTooltipFromX(chartX);if (tooltip) {scheduleTooltip(tooltip);@@ -268,6 +276,7 @@ export function useChartInteraction({if (chartX === null) {return;}+ lastHoveredXRef.current = chartX;const tooltip = resolveTooltipFromX(chartX);if (tooltip) {scheduleTooltip(tooltip);@@ -302,6 +311,19 @@ export function useChartInteraction({setSelection(null);}, []);+ // Re-anchor tooltip/crosshair when x-scale or visible data changes (e.g. brush zoom commit).+ useEffect(() => {+ if (!canInteract || lastHoveredXRef.current === null) {+ return;+ }+ const tooltip = resolveTooltipFromX(lastHoveredXRef.current);+ if (tooltip) {+ scheduleTooltip(tooltip, `${tooltip.index}:${Math.round(tooltip.x)}`);+ return;+ }+ clearTooltip();+ }, [canInteract, clearTooltip, resolveTooltipFromX, scheduleTooltip]);+const interactionHandlers = canInteract? {onMouseMove: handleMouseMove,diff --git a/apps/start/src/components/charts/use-chart-phase-orchestrator.ts b/apps/start/src/components/charts/use-chart-phase-orchestrator.tsnew file mode 100644index 000000000..d77c4bebc--- /dev/null+++ b/apps/start/src/components/charts/use-chart-phase-orchestrator.ts@@ -0,0 +1,183 @@+'use client';++import { useCallback, useEffect, useRef, useState } from 'react';+import {+ type ChartPhase,+ type ChartStatus,+ resolveRestingChartPhase,+} from './chart-phase';++export interface UseChartPhaseOrchestratorOptions {+ chartStatus: ChartStatus;+ targetData: Record<string, unknown>[];+ skeletonData: Record<string, unknown>[];+ animationDuration: number;+ yDomainTweenDuration: number;+ /** Signature of motion URL state — replays clip reveal in Studio. */+ revealSignature?: string;+ /** Skip mount/signature enter reveal (static docs previews). */+ skipEnterReveal?: boolean;+}++export function useChartPhaseOrchestrator({+ chartStatus,+ targetData,+ skeletonData,+ animationDuration,+ yDomainTweenDuration,+ revealSignature = '',+ skipEnterReveal = false,+}: UseChartPhaseOrchestratorOptions) {+ const [chartPhase, setChartPhase] = useState<ChartPhase>(() =>+ resolveRestingChartPhase(chartStatus)+ );+ const [plotData, setPlotData] = useState<Record<string, unknown>[]>(() =>+ chartStatus === 'loading' ? skeletonData : targetData+ );+ const [revealEpoch, setRevealEpoch] = useState(0);+ const [concealEpoch, setConcealEpoch] = useState(0);+ const [isLoaded, setIsLoaded] = useState(() => chartStatus === 'ready');+ const prevStatusRef = useRef(chartStatus);+ const phaseRef = useRef(chartPhase);+ phaseRef.current = chartPhase;++ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: status transition branches for animation durations+ useEffect(() => {+ const prevStatus = prevStatusRef.current;+ if (prevStatus === chartStatus) {+ return;+ }+ prevStatusRef.current = chartStatus;++ if (chartStatus === 'ready' && prevStatus === 'loading') {+ setIsLoaded(false);+ if (animationDuration <= 0) {+ if (yDomainTweenDuration <= 0) {+ setPlotData(targetData);+ setChartPhase('revealing');+ } else {+ setChartPhase('gridTweenReady');+ }+ } else {+ setChartPhase('exiting');+ }+ return;+ }++ if (chartStatus === 'loading' && prevStatus === 'ready') {+ setIsLoaded(false);+ if (animationDuration <= 0) {+ if (yDomainTweenDuration <= 0) {+ setPlotData(skeletonData);+ setChartPhase('loading');+ } else {+ setChartPhase('gridTweenLoading');+ }+ } else {+ setConcealEpoch((epoch) => epoch + 1);+ setChartPhase('exitingReady');+ }+ }+ }, [+ animationDuration,+ chartStatus,+ skeletonData,+ targetData,+ yDomainTweenDuration,+ ]);++ // biome-ignore lint/correctness/useExhaustiveDependencies: revealSignature replays enter+ useEffect(() => {+ if (skipEnterReveal) {+ return;+ }+ if (chartStatus !== 'ready') {+ return;+ }+ if (phaseRef.current !== 'ready') {+ return;+ }++ setChartPhase('revealing');+ setIsLoaded(false);+ }, [animationDuration, chartStatus, revealSignature, skipEnterReveal]);++ useEffect(() => {+ switch (chartPhase) {+ case 'loading':+ if (chartStatus === 'loading') {+ setPlotData(skeletonData);+ }+ break;+ case 'exiting':+ setPlotData(skeletonData);+ break;+ case 'exitingReady':+ case 'gridTweenLoading':+ case 'gridTweenReady':+ case 'revealing':+ case 'ready':+ setPlotData(targetData);+ break;+ default:+ break;+ }+ }, [chartPhase, chartStatus, skeletonData, targetData]);++ /** Loading pulse exit finished — tween grid to ready spacing next. */+ const notifyLoadingPulseComplete = useCallback(() => {+ if (phaseRef.current !== 'exiting') {+ return;+ }+ setChartPhase('gridTweenReady');+ }, []);++ /** Ready series conceal finished — tween grid to loading spacing next. */+ const notifyRevealConcealComplete = useCallback(() => {+ if (phaseRef.current !== 'exitingReady') {+ return;+ }+ setChartPhase('gridTweenLoading');+ }, []);++ /** Grid tween finished — enter the next resting phase. */+ const notifyYDomainTweenComplete = useCallback(() => {+ if (phaseRef.current === 'gridTweenLoading') {+ setChartPhase('loading');+ return;+ }+ if (phaseRef.current === 'gridTweenReady') {+ setChartPhase('revealing');+ }+ }, []);++ useEffect(() => {+ if (chartPhase !== 'revealing') {+ return;+ }++ setRevealEpoch((epoch) => epoch + 1);+ if (animationDuration <= 0) {+ setChartPhase('ready');+ setIsLoaded(true);+ return;+ }++ const timer = window.setTimeout(() => {+ setChartPhase('ready');+ setIsLoaded(true);+ }, animationDuration);+ return () => window.clearTimeout(timer);+ }, [animationDuration, chartPhase]);++ return {+ chartPhase,+ plotData,+ revealEpoch,+ concealEpoch,+ isLoaded,+ notifyLoadingPulseComplete,+ notifyRevealConcealComplete,+ notifyYDomainTweenComplete,+ };+}diff --git a/apps/start/src/components/charts/use-enter-complete.ts b/apps/start/src/components/charts/use-enter-complete.tsnew file mode 100644index 000000000..38860f86b--- /dev/null+++ b/apps/start/src/components/charts/use-enter-complete.ts@@ -0,0 +1,28 @@+'use client';++import type { MotionValue } from 'motion/react';+import { useEffect, useState } from 'react';++/**+ * Returns true once a mount-progress MotionValue reaches 1.+ * Use to swap animated MotionValue-driven props for static values after+ * enter completes — drops per-frame subscriptions during pan/hover.+ */+export function useEnterComplete(mountProgress: MotionValue<number>): boolean {+ const [complete, setComplete] = useState(() => mountProgress.get() >= 1);++ useEffect(() => {+ if (mountProgress.get() >= 1) {+ setComplete(true);+ return;+ }++ return mountProgress.on('change', (value) => {+ if (value >= 1) {+ setComplete(true);+ }+ });+ }, [mountProgress]);++ return complete;+}diff --git a/apps/start/src/components/charts/use-grid-shimmer.ts b/apps/start/src/components/charts/use-grid-shimmer.tsnew file mode 100644index 000000000..01d53d637--- /dev/null+++ b/apps/start/src/components/charts/use-grid-shimmer.ts@@ -0,0 +1,111 @@+'use client';++import {+ animate,+ useMotionValue,+ useReducedMotion,+ useTransform,+} from 'motion/react';+import { useEffect } from 'react';+import {+ LINE_LOADING_LOOP_PAUSE_MS,+ LINE_LOADING_PULSE_CYCLE_S,+ LINE_LOADING_PULSE_EASE,+} from './line-loading-timing';++export interface UseGridShimmerOptions {+ innerWidth: number;+ shimmer: boolean;+ shimmerLength: number;+ shimmerSpeed: number;+ shimmerSync: boolean;+ /** When false, shimmer animation is paused (e.g. during exit transition). */+ active: boolean;+ /** Run a single synced sweep (loading → ready handoff). */+ oneShot?: boolean;+}++export function useGridShimmer({+ innerWidth,+ shimmer,+ shimmerLength,+ shimmerSpeed,+ shimmerSync,+ active,+ oneShot = false,+}: UseGridShimmerOptions) {+ const progress = useMotionValue(0);+ const reducedMotion = useReducedMotion();+ const shimmerCycleS =+ LINE_LOADING_PULSE_CYCLE_S / Math.max(shimmerSpeed, 0.1);+ const shimmerEnabled =+ active && shimmer && reducedMotion !== true && innerWidth > 0;++ useEffect(() => {+ if (!shimmerEnabled) {+ return;+ }++ let cancelled = false;+ let timeoutId: number | undefined;+ let controls: ReturnType<typeof animate> | undefined;++ const runSyncedCycle = () => {+ if (cancelled) {+ return;+ }++ progress.set(0);+ controls = animate(progress, 1, {+ duration: shimmerCycleS,+ ease: [...LINE_LOADING_PULSE_EASE],+ onComplete: () => {+ if (cancelled) {+ return;+ }+ timeoutId = window.setTimeout(+ runSyncedCycle,+ LINE_LOADING_LOOP_PAUSE_MS+ );+ },+ });+ };++ if (shimmerSync && oneShot) {+ progress.set(0);+ controls = animate(progress, 1, {+ duration: shimmerCycleS / 2,+ ease: [...LINE_LOADING_PULSE_EASE],+ });+ return () => controls?.stop();+ }++ if (shimmerSync) {+ runSyncedCycle();+ return () => {+ cancelled = true;+ controls?.stop();+ if (timeoutId !== undefined) {+ window.clearTimeout(timeoutId);+ }+ };+ }++ progress.set(0);+ controls = animate(progress, 1, {+ duration: shimmerCycleS,+ repeat: Number.POSITIVE_INFINITY,+ ease: [...LINE_LOADING_PULSE_EASE],+ });++ return () => controls?.stop();+ }, [oneShot, progress, shimmerCycleS, shimmerEnabled, shimmerSync]);++ const shimmerX = useTransform(+ progress,+ (value) => -shimmerLength + value * (innerWidth + shimmerLength * 2)+ );+ const shimmerTransform = useTransform(shimmerX, (x) => `translate(${x}, 0)`);++ return { shimmerEnabled, shimmerTransform };+}diff --git a/apps/start/src/components/charts/use-highlight-segment.ts b/apps/start/src/components/charts/use-highlight-segment.tsindex fe184e15b..2e665be03 100644--- a/apps/start/src/components/charts/use-highlight-segment.ts+++ b/apps/start/src/components/charts/use-highlight-segment.ts@@ -9,7 +9,11 @@ import {INACTIVE_SEGMENT,} from './highlight-segment-bounds';-// Anything calling this hook re-renders on hover.+// 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>;diff --git a/apps/start/src/components/charts/use-line-segment-highlight.ts b/apps/start/src/components/charts/use-line-segment-highlight.tsdeleted file mode 100644index ed39832d8..000000000--- a/apps/start/src/components/charts/use-line-segment-highlight.ts+++ /dev/null@@ -1,119 +0,0 @@-'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-scheduled-tooltip.ts b/apps/start/src/components/charts/use-scheduled-tooltip.tsindex 4a4eeccdf..b72d8a204 100644--- a/apps/start/src/components/charts/use-scheduled-tooltip.ts+++ b/apps/start/src/components/charts/use-scheduled-tooltip.ts@@ -17,7 +17,11 @@ function defaultDedupeKey<T>(tooltip: T): string {'index' in tooltip &&typeof (tooltip as { index: unknown }).index === 'number') {- return String((tooltip as { index: number }).index);+ const { index, x } = tooltip as { index: number; x?: number };+ if (typeof x === 'number') {+ return `${index}:${Math.round(x)}`;+ }+ return String(index);}return JSON.stringify(tooltip);}diff --git a/apps/start/src/components/charts/visx-pattern.tsx b/apps/start/src/components/charts/visx-pattern.tsxnew file mode 100644index 000000000..7cc7c0787--- /dev/null+++ b/apps/start/src/components/charts/visx-pattern.tsx@@ -0,0 +1,33 @@+'use client';++import type { ComponentProps } from 'react';+import {+ PatternCircles as VisxPatternCircles,+ PatternHexagons as VisxPatternHexagons,+ PatternLines as VisxPatternLines,+ PatternWaves as VisxPatternWaves,+} from './patterns/index';++export function PatternLines(props: ComponentProps<typeof VisxPatternLines>) {+ return <VisxPatternLines {...props} />;+}+PatternLines.displayName = 'PatternLines';++export function PatternCircles(+ props: ComponentProps<typeof VisxPatternCircles>+) {+ return <VisxPatternCircles {...props} />;+}+PatternCircles.displayName = 'PatternCircles';++export function PatternWaves(props: ComponentProps<typeof VisxPatternWaves>) {+ return <VisxPatternWaves {...props} />;+}+PatternWaves.displayName = 'PatternWaves';++export function PatternHexagons(+ props: ComponentProps<typeof VisxPatternHexagons>+) {+ return <VisxPatternHexagons {...props} />;+}+PatternHexagons.displayName = 'PatternHexagons';diff --git a/apps/start/src/components/charts/x-axis.tsx b/apps/start/src/components/charts/x-axis.tsxindex bb4f3b762..bc4e0bd90 100644--- a/apps/start/src/components/charts/x-axis.tsx+++ b/apps/start/src/components/charts/x-axis.tsx@@ -4,34 +4,48 @@ import { memo, useEffect, useMemo, useState } from 'react';import { createPortal } from 'react-dom';import { useChart, useChartStable } from './chart-context';import { shortDateFmt } from './chart-formatters';+import { DEFAULT_Y_DOMAIN_TWEEN_MS } from './chart-phase';+import { LINE_LOADING_PULSE_EASE } from './line-loading-timing';import { cn } from '@/lib/utils';+const X_AXIS_POSITION_TWEEN_MS = DEFAULT_Y_DOMAIN_TWEEN_MS;+export interface XAxisProps {- /** Number of ticks to show (including first and last). Default: 5. Used when `tickMode` is `"domain"`. */+ /** Number of ticks to show (including first and last). Default: 5. */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).+ * `"data"` — tick labels snap to data rows so crosshair and tooltip stay aligned (default).+ * `"domain"` — evenly spaced ticks across the time domain (may not align with hover).*/tickMode?: 'domain' | 'data';}+interface AxisTick {+ date: Date;+ x: number;+ label: string;+}+interface XAxisLabelProps {label: string;x: number;crosshairX: number | null;+ hoveredLabel: string | null;isHovering: boolean;tickerHalfWidth: number;+ animatePosition: boolean;}function XAxisLabel({label,x,crosshairX,+ hoveredLabel,isHovering,tickerHalfWidth,+ animatePosition,}: XAxisLabelProps) {const fadeBuffer = 20;const fadeRadius = tickerHalfWidth + fadeBuffer;@@ -41,14 +55,13 @@ function XAxisLabel({const distance = Math.abs(x - crosshairX);if (distance < tickerHalfWidth) {opacity = 0;+ } else if (hoveredLabel && label === hoveredLabel) {+ 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-alignreturn (<divclassName="absolute"@@ -58,6 +71,9 @@ function XAxisLabel({width: 0,display: 'flex',justifyContent: 'center',+ transition: animatePosition+ ? `left ${X_AXIS_POSITION_TWEEN_MS}ms cubic-bezier(${LINE_LOADING_PULSE_EASE.join(', ')})`+ : undefined,}}><span@@ -73,6 +89,473 @@ function XAxisLabel({);}+const MAX_GAP_LAYOUTS = 400;++function binomial(n: number, k: number): number {+ if (k < 0 || k > n) {+ return 0;+ }+ let result = 1;+ for (let i = 0; i < k; i++) {+ result = (result * (n - i)) / (i + 1);+ }+ return result;+}++/** All ways to split `span` into `parts` positive integer gaps. */+function composePositiveSum(sum: number, parts: number): number[][] {+ if (parts === 1) {+ return sum >= 1 ? [[sum]] : [];+ }++ const layouts: number[][] = [];+ for (let gap = 1; gap <= sum - (parts - 1); gap++) {+ for (const tail of composePositiveSum(sum - gap, parts - 1)) {+ layouts.push([gap, ...tail]);+ }+ }+ return layouts;+}++function gapsToIndices(gaps: number[]): number[] {+ const indices = [0];+ let position = 0;+ for (const gap of gaps) {+ position += gap;+ indices.push(position);+ }+ return indices;+}++function indicesForTickCount(length: number, tickCount: number): number[] {+ const span = length - 1;+ if (span <= 0) {+ return [0];+ }++ const rawIndices = Array.from({ length: tickCount }, (_, index) =>+ Math.round((index / (tickCount - 1)) * span)+ );++ const indices = [...new Set(rawIndices)].sort((a, b) => a - b);+ if (indices[0] !== 0) {+ indices.unshift(0);+ }+ if (indices.at(-1) !== span) {+ indices.push(span);+ }++ return [...new Set(indices)].sort((a, b) => a - b);+}++function allIndexLayouts(length: number, tickCount: number): number[][] {+ const span = length - 1;+ if (span <= 0) {+ return [[0]];+ }++ const gapCount = tickCount - 1;+ if (gapCount <= 0) {+ return [[0]];+ }++ const layoutCount = binomial(span - 1, gapCount - 1);+ if (layoutCount > MAX_GAP_LAYOUTS) {+ return [indicesForTickCount(length, tickCount)];+ }++ return composePositiveSum(span, gapCount).map(gapsToIndices);+}++function dedupeIndicesByLabel(+ indices: number[],+ data: Record<string, unknown>[],+ dateLabels: string[],+ xAccessor: (d: Record<string, unknown>) => Date+): number[] {+ const seenLabels = new Set<string>();+ const deduped: number[] = [];++ for (const index of indices) {+ const point = data[index];+ if (!point) {+ continue;+ }+ const label = dateLabels[index] ?? shortDateFmt.format(xAccessor(point));+ if (seenLabels.has(label)) {+ continue;+ }+ seenLabels.add(label);+ deduped.push(index);+ }++ return deduped;+}++interface TickLayoutScore {+ score: number;+ symmetryPenalty: number;+ countDistance: number;+ /** 0 = smallest gap at end, 1 = at start, 2 = in the middle */+ edgePreference: number;+}++function indexGaps(indices: number[]): number[] {+ const gaps: number[] = [];+ for (let i = 1; i < indices.length; i++) {+ const current = indices[i];+ const previous = indices[i - 1];+ if (current == null || previous == null) {+ continue;+ }+ gaps.push(current - previous);+ }+ return gaps;+}++function smallestGapEdgePreference(indices: number[]): number {+ const gaps = indexGaps(indices);+ const smallestGap = Math.min(...gaps);+ const smallestGapIndex = gaps.indexOf(smallestGap);+ if (smallestGapIndex === gaps.length - 1) {+ return 0;+ }+ if (smallestGapIndex === 0) {+ return 1;+ }+ return 2;+}++function scoreTickLayout(+ indices: number[],+ resolveXPx: (index: number) => number,+ targetCount: number+): TickLayoutScore {+ if (indices.length < 2) {+ return {+ score: Number.POSITIVE_INFINITY,+ symmetryPenalty: Number.POSITIVE_INFINITY,+ countDistance: Number.POSITIVE_INFINITY,+ edgePreference: Number.POSITIVE_INFINITY,+ };+ }++ const pixelGaps: number[] = [];+ for (let i = 1; i < indices.length; i++) {+ const current = indices[i];+ const previous = indices[i - 1];+ if (current == null || previous == null) {+ continue;+ }+ pixelGaps.push(resolveXPx(current) - resolveXPx(previous));+ }++ const minGap = Math.min(...pixelGaps);+ const maxGap = Math.max(...pixelGaps);+ const meanGap =+ pixelGaps.reduce((sum, gap) => sum + gap, 0) / pixelGaps.length;+ const spreadRatio =+ meanGap > 0 ? (maxGap - minGap) / meanGap : maxGap - minGap;+ const countDistance = Math.abs(indices.length - targetCount);++ const gaps = indexGaps(indices);+ const smallestGap = Math.min(...gaps);+ const smallestGapIndex = gaps.indexOf(smallestGap);+ const interiorPenalty =+ smallestGapIndex > 0 && smallestGapIndex < gaps.length - 1 ? 0.08 : 0;++ const symmetryPenalty =+ gaps.reduce((penalty, gap, index) => {+ return penalty + Math.abs(gap - (gaps.at(-1 - index) ?? gap));+ }, 0) / gaps.length;++ return {+ score:+ spreadRatio ++ 0.1 * countDistance ++ interiorPenalty ++ symmetryPenalty * 0.02,+ symmetryPenalty,+ countDistance,+ edgePreference: smallestGapEdgePreference(indices),+ };+}++function isBetterTickLayout(+ next: TickLayoutScore,+ best: TickLayoutScore,+ nextCountDistance: number,+ bestCountDistance: number+): boolean {+ if (next.score < best.score - 1e-6) {+ return true;+ }+ if (Math.abs(next.score - best.score) > 1e-6) {+ return false;+ }+ if (nextCountDistance < bestCountDistance) {+ return true;+ }+ if (nextCountDistance > bestCountDistance) {+ return false;+ }+ if (next.symmetryPenalty < best.symmetryPenalty - 1e-6) {+ return true;+ }+ if (next.symmetryPenalty > best.symmetryPenalty + 1e-6) {+ return false;+ }+ return next.edgePreference < best.edgePreference;+}++/**+ * Picks tick indices with the most even on-screen spacing. Tries+ * `targetCount ± 1` and evaluates every gap layout when feasible.+ */+export function selectEvenlySpacedIndices(+ length: number,+ targetCount: number,+ options?: {+ data?: Record<string, unknown>[];+ dateLabels?: string[];+ xAccessor?: (d: Record<string, unknown>) => Date;+ resolveXPx?: (index: number) => number;+ }+): number[] {+ if (length <= 0) {+ return [];+ }+ if (length === 1) {+ return [0];+ }+ if (length <= targetCount) {+ return Array.from({ length }, (_, index) => index);+ }++ const resolveXPx = options?.resolveXPx ?? ((index: number) => index);++ const minCount = Math.max(2, targetCount - 1);+ const maxCount = Math.min(length, targetCount + 1);++ let bestIndices = indicesForTickCount(length, targetCount);+ let bestScore = scoreTickLayout(bestIndices, resolveXPx, targetCount);+ let bestCountDistance = bestScore.countDistance;++ for (let tickCount = minCount; tickCount <= maxCount; tickCount++) {+ for (const rawIndices of allIndexLayouts(length, tickCount)) {+ const indices =+ options?.data && options.dateLabels && options.xAccessor+ ? dedupeIndicesByLabel(+ rawIndices,+ options.data,+ options.dateLabels,+ options.xAccessor+ )+ : rawIndices;++ if (indices.length < 2) {+ continue;+ }++ const layoutScore = scoreTickLayout(indices, resolveXPx, targetCount);+ const countDistance = Math.abs(indices.length - targetCount);++ if (+ isBetterTickLayout(+ layoutScore,+ bestScore,+ countDistance,+ bestCountDistance+ )+ ) {+ bestIndices = indices;+ bestScore = layoutScore;+ bestCountDistance = countDistance;+ }+ }+ }++ return bestIndices;+}++function buildDataAlignedTicks({+ data,+ dateLabels,+ marginLeft,+ targetTickCount,+ xAccessor,+ xScale,+}: {+ data: Record<string, unknown>[];+ dateLabels: string[];+ marginLeft: number;+ targetTickCount: number;+ xAccessor: (d: Record<string, unknown>) => Date;+ xScale: (date: Date) => number | undefined;+}): AxisTick[] {+ const seenLabels = new Set<string>();+ const ticks: AxisTick[] = [];++ const resolveXPx = (index: number) => {+ const point = data[index];+ if (!point) {+ return index;+ }+ return xScale(xAccessor(point)) ?? 0;+ };++ for (const index of selectEvenlySpacedIndices(data.length, targetTickCount, {+ data,+ dateLabels,+ resolveXPx,+ xAccessor,+ })) {+ const point = data[index];+ if (!point) {+ continue;+ }+ const date = xAccessor(point);+ const label = dateLabels[index] ?? shortDateFmt.format(date);+ if (seenLabels.has(label)) {+ continue;+ }+ seenLabels.add(label);+ ticks.push({+ date,+ label,+ x: (xScale(date) ?? 0) + marginLeft,+ });+ }++ return ticks;+}++function buildDomainTicks({+ marginLeft,+ numTicks,+ xScale,+}: {+ marginLeft: number;+ numTicks: number;+ xScale: {+ domain: () => Date[];+ (date: Date): number | undefined;+ };+}): AxisTick[] {+ 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;+ const tickCount = Math.max(2, numTicks);+ const seenLabels = new Set<string>();+ const ticks: AxisTick[] = [];++ for (let i = 0; i < tickCount; i++) {+ const t = i / (tickCount - 1);+ const date = new Date(startTime + t * timeRange);+ const label = shortDateFmt.format(date);+ if (seenLabels.has(label)) {+ continue;+ }+ seenLabels.add(label);+ ticks.push({+ date,+ label,+ x: (xScale(date) ?? 0) + marginLeft,+ });+ }++ return ticks;+}++function domainExtendsPastData(+ data: Record<string, unknown>[],+ xAccessor: (d: Record<string, unknown>) => Date,+ xScale: { domain: () => Date[] }+): boolean {+ if (data.length === 0) {+ return false;+ }+ const domainEnd = xScale.domain()[1];+ const lastPoint = data.at(-1);+ if (!(domainEnd && lastPoint)) {+ return false;+ }+ return domainEnd.getTime() > xAccessor(lastPoint).getTime();+}++/** Domain ticks for the projection tail when brush keeps data-aligned labels. */+function appendProjectionTailTicks(+ ticks: AxisTick[],+ data: Record<string, unknown>[],+ xAccessor: (d: Record<string, unknown>) => Date,+ xScale: {+ domain: () => Date[];+ (date: Date): number | undefined;+ },+ marginLeft: number,+ maxExtraTicks: number+): AxisTick[] {+ if (data.length === 0 || maxExtraTicks <= 0) {+ return ticks;+ }++ const lastPoint = data.at(-1);+ const domainEnd = xScale.domain()[1];+ if (!(lastPoint && domainEnd)) {+ return ticks;+ }++ const lastDate = xAccessor(lastPoint);+ const startTime = lastDate.getTime();+ const endTime = domainEnd.getTime();+ if (endTime <= startTime) {+ return ticks;+ }++ const seenLabels = new Set(ticks.map((tick) => tick.label));+ const extras: AxisTick[] = [];+ const extraCount = Math.min(maxExtraTicks, 3);++ for (let i = 1; i <= extraCount; i++) {+ const date = new Date(+ startTime + (i / (extraCount + 1)) * (endTime - startTime)+ );+ const label = shortDateFmt.format(date);+ if (seenLabels.has(label)) {+ continue;+ }+ seenLabels.add(label);+ extras.push({+ date,+ label,+ x: (xScale(date) ?? 0) + marginLeft,+ });+ }++ const endLabel = shortDateFmt.format(domainEnd);+ if (!seenLabels.has(endLabel)) {+ extras.push({+ date: domainEnd,+ label: endLabel,+ x: (xScale(domainEnd) ?? 0) + marginLeft,+ });+ }++ if (extras.length === 0) {+ return ticks;+ }++ return [...ticks, ...extras].sort((a, b) => a.x - b.x);+}+export function XAxis(props: XAxisProps) {const { containerRef } = useChartStable();const [mounted, setMounted] = useState(false);@@ -92,59 +575,81 @@ export function XAxis(props: XAxisProps) {const XAxisInner = memo(function XAxisInner({numTicks = 5,tickerHalfWidth = 50,- tickMode = 'domain',+ tickMode = 'data',container,}: XAxisProps & { container: HTMLDivElement }) {- const { xScale, margin, tooltipData, data, xAccessor, dateLabels } =+ const { xScale, margin, tooltipData, data, xAccessor, dateLabels, xDomain } =useChart();- // Generate tick labels: evenly spaced along the domain, or one per data rowconst 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];+ const projectionExtendsScale =+ tickMode === 'data' && domainExtendsPastData(data, xAccessor, xScale);- if (!(startDate && endDate)) {- return [];+ if (tickMode === 'domain') {+ return buildDomainTicks({+ marginLeft: margin.left,+ numTicks,+ xScale,+ });}- const startTime = startDate.getTime();- const endTime = endDate.getTime();- const timeRange = endTime - startTime;+ // No brush: evenly spaced ticks across the full domain (data + projection).+ if (projectionExtendsScale && xDomain == null) {+ return buildDomainTicks({+ marginLeft: margin.left,+ numTicks,+ xScale,+ });+ }- // Create evenly spaced dates from start to end- const tickCount = Math.max(2, numTicks); // At least first and last- const dates: Date[] = [];+ const dataTicks = buildDataAlignedTicks({+ data,+ dateLabels,+ marginLeft: margin.left,+ targetTickCount: numTicks,+ xAccessor,+ xScale,+ });- 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));+ // Brush: keep data-aligned ticks, add labels only in the projection tail.+ if (projectionExtendsScale && xDomain != null) {+ return appendProjectionTailTicks(+ dataTicks,+ data,+ xAccessor,+ xScale,+ margin.left,+ Math.max(1, numTicks - dataTicks.length + 1)+ );}- return dates.map((date) => ({- date,- x: (xScale(date) ?? 0) + margin.left,- label: shortDateFmt.format(date),- }));- }, [tickMode, data, xAccessor, xScale, margin.left, dateLabels, numTicks]);+ return dataTicks;+ }, [+ tickMode,+ xDomain,+ data,+ dateLabels,+ xAccessor,+ xScale,+ margin.left,+ numTicks,+ ]);const isHovering = tooltipData !== null;const crosshairX = tooltipData ? tooltipData.x + margin.left : null;+ const hoveredLabel =+ isHovering && tooltipData+ ? (dateLabels[tooltipData.index] ??+ shortDateFmt.format(xAccessor(tooltipData.point)))+ : null;return createPortal(<div className="pointer-events-none absolute inset-0">{labelsToShow.map((item) => (<XAxisLabel+ animatePosition={xDomain == null}crosshairX={crosshairX}+ hoveredLabel={hoveredLabel}isHovering={isHovering}key={`${item.date.getTime()}-${item.x}`}label={item.label}diff --git a/apps/start/src/components/charts/y-axis-scales.ts b/apps/start/src/components/charts/y-axis-scales.tsnew file mode 100644index 000000000..9bb255451--- /dev/null+++ b/apps/start/src/components/charts/y-axis-scales.ts@@ -0,0 +1,118 @@+import { scaleLinear } from '@visx/scale';+import type { LineConfig } from './chart-context';++/** Default axis id when `yAxisId` is omitted (Recharts-style `0` / primary left axis). */+export const DEFAULT_Y_AXIS_ID = 'left';++export type YAxisOrientation = 'left' | 'right';++export function normalizeYAxisId(id?: string | number): string {+ if (id == null || id === '') {+ return DEFAULT_Y_AXIS_ID;+ }+ return String(id);+}++export function groupLinesByYAxisId(+ lines: LineConfig[]+): Map<string, LineConfig[]> {+ const groups = new Map<string, LineConfig[]>();+ for (const line of lines) {+ const axisId = normalizeYAxisId(line.yAxisId);+ const bucket = groups.get(axisId) ?? [];+ bucket.push(line);+ groups.set(axisId, bucket);+ }+ return groups;+}++type YScale = ReturnType<typeof scaleLinear<number>>;++export function getPrimaryYScale(+ yScales: Record<string, YScale>,+ fallback: YScale+): YScale {+ const primary = yScales[DEFAULT_Y_AXIS_ID];+ if (primary) {+ return primary;+ }+ const first = Object.values(yScales)[0];+ return first ?? fallback;+}++export function buildYScalesForLines({+ lines,+ innerHeight,+ resolveDomain,+}: {+ lines: LineConfig[];+ /** Passed by callers; domain is resolved via `resolveDomain`. */+ data?: Record<string, unknown>[];+ innerHeight: number;+ resolveDomain: (dataKeys: string[]) => [number, number];+}): Record<string, YScale> {+ const groups = groupLinesByYAxisId(lines);+ const scales: Record<string, YScale> = {};++ for (const [axisId, axisLines] of groups) {+ const dataKeys = axisLines.map((line) => line.dataKey);+ const domain = resolveDomain(dataKeys);+ scales[axisId] = scaleLinear({+ range: [innerHeight, 0],+ domain,+ nice: true,+ });+ }++ if (!scales[DEFAULT_Y_AXIS_ID]) {+ scales[DEFAULT_Y_AXIS_ID] = scaleLinear({+ range: [innerHeight, 0],+ domain: [0, 100],+ nice: true,+ });+ }++ return scales;+}++/** Build y-scales from pre-computed (already nice'd) domain endpoints. */+export function buildYScalesFromDomains({+ lines,+ innerHeight,+ domainsByAxis,+ reversed = false,+}: {+ lines: LineConfig[];+ innerHeight: number;+ domainsByAxis: Record<string, [number, number]>;+ /** Smallest value at the top, for "lower is better" metrics. */+ reversed?: boolean;+}): Record<string, YScale> {+ const groups = groupLinesByYAxisId(lines);+ const scales: Record<string, YScale> = {};+ const range: [number, number] = reversed+ ? [0, innerHeight]+ : [innerHeight, 0];++ for (const [axisId] of groups) {+ const domain =+ domainsByAxis[axisId] ??+ domainsByAxis[DEFAULT_Y_AXIS_ID] ??+ ([0, 100] as [number, number]);+ scales[axisId] = scaleLinear({ range, domain });+ }++ if (!scales[DEFAULT_Y_AXIS_ID]) {+ scales[DEFAULT_Y_AXIS_ID] = scaleLinear({+ range,+ domain: domainsByAxis[DEFAULT_Y_AXIS_ID] ?? [0, 100],+ });+ }++ return scales;+}++/** Single-axis charts (bar, scatter, candlestick, live line). */+export function wrapSingleYScale(yScale: YScale): Record<string, YScale> {+ return { [DEFAULT_Y_AXIS_ID]: yScale };+}diff --git a/apps/start/src/components/charts/y-axis-ticks.ts b/apps/start/src/components/charts/y-axis-ticks.tsnew file mode 100644index 000000000..26110d88c--- /dev/null+++ b/apps/start/src/components/charts/y-axis-ticks.ts@@ -0,0 +1,26 @@+/** Default hint passed to `scale.ticks()` (d3 — approximate tick count). */+export const Y_AXIS_DEFAULT_TICK_COUNT = 5;++/** Minimum valid `numTicks` for `scale.ticks()` — values ≤ 0 yield no ticks. */+export const Y_AXIS_MIN_TICK_COUNT = 1;++/**+ * Upper bound for the tick count hint. D3 may return more "nice" ticks above ~10;+ * keeping the hint in a modest range avoids overcrowded axes.+ */+export const Y_AXIS_MAX_TICK_COUNT = 10;++/** Clamps a user `numTicks` value to a valid d3 tick-count hint. */+export function resolveYAxisTickCount(numTicks?: number): number {+ if (numTicks == null || !Number.isFinite(numTicks)) {+ return Y_AXIS_DEFAULT_TICK_COUNT;+ }+ const rounded = Math.round(numTicks);+ if (rounded < Y_AXIS_MIN_TICK_COUNT) {+ return Y_AXIS_MIN_TICK_COUNT;+ }+ if (rounded > Y_AXIS_MAX_TICK_COUNT) {+ return Y_AXIS_MAX_TICK_COUNT;+ }+ return rounded;+}diff --git a/apps/start/src/components/charts/y-domain-utils.ts b/apps/start/src/components/charts/y-domain-utils.tsnew file mode 100644index 000000000..a32640678--- /dev/null+++ b/apps/start/src/components/charts/y-domain-utils.ts@@ -0,0 +1,134 @@+import { scaleLinear } from '@visx/scale';+import type { LineConfig } from './chart-context';+import { type ChartPhase, Y_DOMAIN_TWEEN_SKIP_THRESHOLD } from './chart-phase';+import { groupLinesByYAxisId, normalizeYAxisId } from './y-axis-scales';++export type YDomain = [number, number];++/** Apply visx `nice()` to raw domain endpoints for stable grid ticks. */+export function niceYDomain(domain: YDomain): YDomain {+ const scale = scaleLinear({ domain, range: [0, 1], nice: true });+ const niceDomain = scale.domain();+ return [niceDomain[0] ?? domain[0], niceDomain[1] ?? domain[1]];+}++/**+ * Skip Y tween when both endpoints move less than the threshold relative to span.+ * When in doubt callers should tween — beauty wins over micro-optimization.+ */+export function shouldTweenYDomain(from: YDomain, to: YDomain): boolean {+ const span = Math.max(+ Math.abs(to[1] - to[0]),+ Math.abs(from[1] - from[0]),+ 1+ );+ const deltaMin = Math.abs(to[0] - from[0]) / span;+ const deltaMax = Math.abs(to[1] - from[1]) / span;+ return (+ deltaMin >= Y_DOMAIN_TWEEN_SKIP_THRESHOLD ||+ deltaMax >= Y_DOMAIN_TWEEN_SKIP_THRESHOLD+ );+}++/** Phases where the chart shows loading chrome (shimmer, pulse, label). */+export function isLoadingChromePhase(phase: ChartPhase): boolean {+ return phase === 'loading' || phase === 'revealingLoading';+}++/** Phases where grid lines use loading stroke styling (muted / dashed chrome). */+export function isLoadingGridChromePhase(phase: ChartPhase): boolean {+ return (+ phase === 'loading' || phase === 'exiting' || phase === 'gridTweenLoading'+ );+}++/** Phases where Y-domain tween runs after the series has exited. */+export function isYDomainTweenPhase(phase: ChartPhase): boolean {+ return phase === 'gridTweenLoading' || phase === 'gridTweenReady';+}++/** Phases where {@link ReferenceArea} bands are shown (fade in/out on transitions). */+export function isReferenceAreaVisiblePhase(phase: ChartPhase): boolean {+ return (+ phase === 'ready' || phase === 'revealing' || phase === 'gridTweenReady'+ );+}++export function resolveAnimatedYDestinationDomains(+ chartPhase: ChartPhase,+ skeletonByAxis: Record<string, YDomain>,+ targetByAxis: Record<string, YDomain>+): Record<string, YDomain> {+ switch (chartPhase) {+ case 'loading':+ case 'exiting':+ case 'gridTweenLoading':+ return skeletonByAxis;+ case 'exitingReady':+ case 'gridTweenReady':+ case 'revealing':+ case 'ready':+ return targetByAxis;+ default:+ return targetByAxis;+ }+}++export function computeYDomainsByAxis({+ lines,+ resolveDomain,+}: {+ lines: LineConfig[];+ resolveDomain: (dataKeys: string[], axisId: string) => YDomain;+}): Record<string, YDomain> {+ const groups = groupLinesByYAxisId(lines);+ const domains: Record<string, YDomain> = {};++ for (const [axisId, axisLines] of groups) {+ const dataKeys = axisLines.map((line) => line.dataKey);+ const normalizedAxisId = normalizeYAxisId(axisId);+ domains[normalizedAxisId] = niceYDomain(+ resolveDomain(dataKeys, normalizedAxisId)+ );+ }++ if (!domains.left) {+ domains.left = niceYDomain([0, 100]);+ }++ return domains;+}++/** Merge domain maps, normalizing axis ids to strings. */+export function mergeYDomainRecords(+ ...records: Record<string, YDomain>[]+): Record<string, YDomain> {+ const merged: Record<string, YDomain> = {};+ for (const record of records) {+ for (const [axisId, domain] of Object.entries(record)) {+ merged[normalizeYAxisId(axisId)] = domain;+ }+ }+ return merged;+}++export function domainsEqual(+ left: Record<string, YDomain>,+ right: Record<string, YDomain>+): boolean {+ const leftKeys = Object.keys(left);+ const rightKeys = Object.keys(right);+ if (leftKeys.length !== rightKeys.length) {+ return false;+ }++ for (const axisId of leftKeys) {+ const from = left[axisId];+ const to = right[axisId];+ if (!(from && to) || from[0] !== to[0] || from[1] !== to[1]) {+ return false;+ }+ }++ return true;+}diff --git a/apps/start/src/components/cohort/cohort-events-chart.tsx b/apps/start/src/components/cohort/cohort-events-chart.tsxindex 9cd56557e..abfb4ab0f 100644--- a/apps/start/src/components/cohort/cohort-events-chart.tsx+++ b/apps/start/src/components/cohort/cohort-events-chart.tsx@@ -1,73 +1,36 @@+import { curveMonotoneX } from 'd3-shape';import { ActivityIcon } from 'lucide-react';-import {- Area,- AreaChart,- CartesianGrid,- Tooltip as RechartTooltip,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';import { WidgetHead, WidgetTitle } from '../overview/overview-widget';-import {- useXAxisProps,- useYAxisProps,-} from '@/components/report-chart/common/axis';+import { Area, AreaChart } from '@/components/charts/area-chart';+import { Grid } from '@/components/charts/grid';+import { OPChartTooltip } from '@/components/charts/op-tooltip';+import { XAxis } from '@/components/charts/x-axis';+import { YAxis } from '@/components/charts/y-axis';import { Widget, WidgetBody } from '@/components/widget';-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';+import { formatDateInterval } from '@/hooks/use-format-date-interval';import { useNumber } from '@/hooks/use-numer-formatter';import { getChartColor } from '@/utils/theme';-type Props = {- data: { date: string; count: number }[];-};+const MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };+const FILL_OPACITY = 0.3;+const COLOR = getChartColor(0);-function Tooltip(props: any) {- const number = useNumber();- const formatDate = useFormatDateInterval({ interval: 'day', short: false });- const payload = props.payload?.[0]?.payload;-- if (!payload) {- return null;- }-- return (- <div className="flex min-w-[160px] flex-col gap-2 rounded-xl border bg-card p-3 shadow-xl">- <div className="text-muted-foreground text-sm">- {formatDate(new Date(payload.timestamp))}- </div>- <div className="flex items-center gap-2">- <div- className="h-10 w-1 rounded-full"- style={{ background: getChartColor(0) }}- />- <div className="col gap-1">- <div className="text-muted-foreground text-sm">Events</div>- <div- className="font-semibold text-lg"- style={{ color: getChartColor(0) }}- >- {number.format(payload.count)}- </div>- </div>- </div>- </div>- );+interface Point {+ [key: string]: unknown;+ date: string;+ count: number;}-export function CohortEventsChart({ data }: Props) {- const xAxisProps = useXAxisProps({ interval: 'day' });- const yAxisProps = useYAxisProps({});- const color = getChartColor(0);+interface Props {+ data: Point[];+}- const chartData = data.map((item) => ({- date: item.date,- timestamp: new Date(item.date).getTime(),- count: item.count,- }));+const formatDateLabel = (date: Date) =>+ formatDateInterval({ interval: 'day', date, short: true });- const gradientId = 'cohortEventsGradient';- const total = data.reduce((acc, d) => acc + d.count, 0);+export function CohortEventsChart({ data }: Props) {+ const number = useNumber();+ const total = data.reduce((acc, point) => acc + point.count, 0);return (<Widget className="w-full">@@ -82,40 +45,40 @@ export function CohortEventsChart({ data }: Props) {No events yet</p>) : (- <div className="h-[200px] w-full">- <ResponsiveContainer>- <AreaChart data={chartData}>- <defs>- <linearGradient id={gradientId} x1="0" x2="0" y1="0" y2="1">- <stop offset="5%" stopColor={color} stopOpacity={0.3} />- <stop offset="95%" stopColor={color} stopOpacity={0.02} />- </linearGradient>- </defs>- <RechartTooltip- content={<Tooltip />}- cursor={{ stroke: color, strokeOpacity: 0.3 }}- />- <Area- dataKey="count"- dot={false}- fill={`url(#${gradientId})`}- isAnimationActive={false}- stroke={color}- strokeWidth={2}- type="monotone"- />- <XAxis {...xAxisProps} />- <YAxis {...yAxisProps} />- <CartesianGrid- className="stroke-border"- horizontal={true}- strokeDasharray="3 3"- strokeOpacity={0.5}- vertical={false}- />- </AreaChart>- </ResponsiveContainer>- </div>+ <AreaChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-[200px]"+ data={data}+ formatDateLabel={formatDateLabel}+ margin={MARGIN}+ xDataKey="date"+ >+ <Grid horizontal />+ <YAxis formatValue={number.short} />+ <XAxis />+ <Area+ animate={false}+ curve={curveMonotoneX}+ dataKey="count"+ fill={COLOR}+ fillOpacity={FILL_OPACITY}+ stroke={COLOR}+ />+ <OPChartTooltip<Point>+ interval="day"+ rows={(point) => [+ {+ color: COLOR,+ label: 'Events',+ value: point.count,+ format: number.format,+ },+ ]}+ showCrosshair+ showDots+ />+ </AreaChart>)}</WidgetBody></Widget>diff --git a/apps/start/src/components/dashboard-grid.tsx b/apps/start/src/components/dashboard-grid.tsxnew file mode 100644index 000000000..41087e921--- /dev/null+++ b/apps/start/src/components/dashboard-grid.tsx@@ -0,0 +1,114 @@+import type { IServiceReport } from '@openpanel/core';+import { type ReactNode, useEffect, useMemo, useState } from 'react';+import {+ GridLayout,+ type GridLayoutProps,+ type Layout,+ type LayoutItem,+ type ResizeHandleAxis,+ useContainerWidth,+ verticalCompactor,+} from 'react-grid-layout';++export type { Layout, LayoutItem } from 'react-grid-layout';++export const GRID_COLUMNS = 12;+export const GRID_ROW_HEIGHT = 100;+export const GRID_GAP = 16;+export const TILE_MIN_SIZE = { minW: 3, minH: 3 } as const;+const RESIZE_HANDLES: readonly ResizeHandleAxis[] = ['se', 'sw', 'ne', 'nw'];+const TILE_DEFAULT_SIZE = { w: 6, h: 4 } as const;+// Narrower than this and tiles stack in one column with no drag, since a+// drag would hijack scrolling on a phone.+const SINGLE_COLUMN_MAX_WIDTH = 640;++export type DashboardReport = NonNullable<IServiceReport>;+/** What placing a report on the grid needs; the dashboards list has reports in a lighter shape than the editor. */+export interface LayoutSource {+ id: string;+ layout?: Pick<LayoutItem, 'x' | 'y' | 'w' | 'h'> | null;+}++export function toLayout(reports: LayoutSource[]): Layout {+ return reports.map((report, index) => ({+ i: report.id,+ x: report.layout?.x ?? (index % 2) * TILE_DEFAULT_SIZE.w,+ y: report.layout?.y ?? Math.floor(index / 2) * TILE_DEFAULT_SIZE.h,+ w: report.layout?.w ?? TILE_DEFAULT_SIZE.w,+ h: report.layout?.h ?? TILE_DEFAULT_SIZE.h,+ ...TILE_MIN_SIZE,+ }));+}++function toSingleColumn(layout: Layout): Layout {+ const ordered = [...layout].sort((a, b) => a.y - b.y || a.x - b.x);+ let nextY = 0;+ return ordered.map((item) => {+ const stacked = { ...item, x: 0, y: nextY, w: GRID_COLUMNS };+ nextY += item.h;+ return stacked;+ });+}++type TilePosition = Pick<LayoutItem, 'x' | 'y' | 'w' | 'h'>;++export function isSameTilePosition(a: TilePosition, b: TilePosition) {+ return a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;+}++// The grid owns the layout while the user drags; saved positions only seed it.+export function useDashboardLayout(reports: DashboardReport[]) {+ const savedLayout = useMemo(() => toLayout(reports), [reports]);+ const [layout, setLayout] = useState(savedLayout);++ useEffect(() => {+ setLayout(savedLayout);+ }, [savedLayout]);++ return [layout, setLayout] as const;+}++export function DashboardGrid({+ layout,+ isEditable = false,+ onLayoutChange,+ onDragStop,+ onResizeStop,+ children,+}: {+ layout: Layout;+ isEditable?: boolean;+ children: ReactNode;+} & Pick<GridLayoutProps, 'onLayoutChange' | 'onDragStop' | 'onResizeStop'>) {+ const { width, containerRef, mounted } = useContainerWidth();+ const isSingleColumn = width < SINGLE_COLUMN_MAX_WIDTH;+ const canEdit = isEditable && !isSingleColumn;+ const gridLayout = useMemo(+ () => (isSingleColumn ? toSingleColumn(layout) : layout),+ [isSingleColumn, layout]+ );++ return (+ <div className="-m-4" ref={containerRef}>+ {mounted && (+ <GridLayout+ compactor={verticalCompactor}+ dragConfig={{ enabled: canEdit, handle: '.drag-handle' }}+ gridConfig={{+ cols: GRID_COLUMNS,+ rowHeight: GRID_ROW_HEIGHT,+ margin: [GRID_GAP, GRID_GAP],+ }}+ layout={gridLayout}+ onDragStop={onDragStop}+ onLayoutChange={canEdit ? onLayoutChange : undefined}+ onResizeStop={onResizeStop}+ resizeConfig={{ enabled: canEdit, handles: RESIZE_HANDLES }}+ width={width}+ >+ {children}+ </GridLayout>+ )}+ </div>+ );+}diff --git a/apps/start/src/components/dashboard-preview.tsx b/apps/start/src/components/dashboard-preview.tsxnew file mode 100644index 000000000..192153aef--- /dev/null+++ b/apps/start/src/components/dashboard-preview.tsx@@ -0,0 +1,96 @@+import type { IChartType } from '@openpanel/core/modules/report/report.constants';+import {+ AreaChartIcon,+ BarChart3Icon,+ BarChartHorizontalIcon,+ ChartScatterIcon,+ ConeIcon,+ GitBranchIcon,+ Globe2Icon,+ HashIcon,+ LineChartIcon,+ type LucideIcon,+ PieChartIcon,+ TrendingUpIcon,+} from 'lucide-react';+import { useMemo } from 'react';+import { GRID_COLUMNS, type LayoutSource, toLayout } from './dashboard-grid';+import { cn } from '@/utils/cn';++export const CHART_TYPE_ICONS: Record<IChartType, LucideIcon> = {+ bar: BarChartHorizontalIcon,+ linear: LineChartIcon,+ pie: PieChartIcon,+ metric: HashIcon,+ map: Globe2Icon,+ histogram: BarChart3Icon,+ funnel: ConeIcon,+ area: AreaChartIcon,+ retention: ChartScatterIcon,+ conversion: TrendingUpIcon,+ sankey: GitBranchIcon,+};++// Shown rows: a short dashboard still looks like a dashboard, a long one is cut+// rather than shrunk to specks.+const MIN_ROWS = 6;+const MAX_ROWS = 14;+// A tile shows its chart icon only when it is big enough to hold one.+const ICON_MIN_WIDTH_COLUMNS = 3;+const ICON_MIN_HEIGHT_ROWS = 2;+const ICON_SIZE = 14;++function iconFor(chartType: IChartType | undefined) {+ return chartType ? CHART_TYPE_ICONS[chartType] : undefined;+}++/** A dashboard's saved layout in miniature: one block per report, with its chart's icon. */+export function DashboardPreview({+ reports,+ className,+}: {+ reports: (LayoutSource & { chartType: IChartType })[];+ className?: string;+}) {+ const tiles = useMemo(() => {+ const layout = toLayout(reports);+ const byId = new Map(reports.map((report) => [report.id, report]));+ const rows = Math.min(+ MAX_ROWS,+ Math.max(MIN_ROWS, ...layout.map((item) => item.y + item.h))+ );+ return layout+ .filter((item) => item.y < rows)+ .map((item) => ({+ id: item.i,+ icon: iconFor(byId.get(item.i)?.chartType),+ showIcon:+ item.w >= ICON_MIN_WIDTH_COLUMNS && item.h >= ICON_MIN_HEIGHT_ROWS,+ style: {+ left: `${(item.x / GRID_COLUMNS) * 100}%`,+ top: `${(item.y / rows) * 100}%`,+ width: `${(item.w / GRID_COLUMNS) * 100}%`,+ height: `${(Math.min(item.h, rows - item.y) / rows) * 100}%`,+ },+ }));+ }, [reports]);++ return (+ <div+ className={cn(+ 'relative aspect-[2/1] w-full overflow-hidden rounded-md bg-def-100 p-1.5',+ className+ )}+ >+ <div className="relative h-full w-full">+ {tiles.map((tile) => (+ <div className="absolute p-0.5" key={tile.id} style={tile.style}>+ <div className="flex h-full w-full items-center justify-center rounded-[3px] bg-def-300/70 text-muted-foreground transition-colors group-hover:bg-chart-0/20 group-hover:text-chart-0 dark:bg-def-700/70">+ {tile.icon && tile.showIcon && <tile.icon size={ICON_SIZE} />}+ </div>+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/apps/start/src/components/grafana-grid.tsx b/apps/start/src/components/grafana-grid.tsxdeleted file mode 100644index 03cb10bbf..000000000--- a/apps/start/src/components/grafana-grid.tsx+++ /dev/null@@ -1,95 +0,0 @@-import type { IServiceReport } from '@openpanel/core';-import { useMemo } from 'react';-import { Responsive, WidthProvider } from 'react-grid-layout';--const ResponsiveGridLayout = WidthProvider(Responsive);--export type Layout = ReactGridLayout.Layout;--export const useReportLayouts = (- reports: NonNullable<IServiceReport>[]-): ReactGridLayout.Layouts => {- return useMemo(() => {- const baseLayout = reports.map((report, index) => ({- i: report.id,- x: report.layout?.x ?? (index % 2) * 6,- y: report.layout?.y ?? Math.floor(index / 2) * 4,- w: report.layout?.w ?? 6,- h: report.layout?.h ?? 4,- minW: 3,- minH: 3,- }));-- return {- lg: baseLayout,- md: baseLayout,- sm: baseLayout.map((item) => ({ ...item, w: Math.min(item.w, 6) })),- xs: baseLayout.map((item) => ({ ...item, w: 4, x: 0 })),- xxs: baseLayout.map((item) => ({ ...item, w: 2, x: 0 })),- };- }, [reports]);-};--export function GrafanaGrid({- layouts,- children,- transitions,- onLayoutChange,- onDragStop,- onResizeStop,- isDraggable,- isResizable,-}: {- children: React.ReactNode;- transitions?: boolean;-} & Pick<- ReactGridLayout.ResponsiveProps,- | 'layouts'- | 'onLayoutChange'- | 'onDragStop'- | 'onResizeStop'- | 'isDraggable'- | 'isResizable'->) {- return (- <>- <style>{`- .react-grid-item {- transition: ${transitions ? 'transform 200ms ease, width 200ms ease, height 200ms ease' : 'none'} !important;- }- .react-grid-item.react-grid-placeholder {- background: none !important;- opacity: 0.5;- transition-duration: 100ms;- border-radius: 0.5rem;- border: 1px dashed var(--primary);- }- .react-grid-item.resizing {- transition: none !important;- }- `}</style>- <div className="-m-4">- <ResponsiveGridLayout- breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}- className="layout"- cols={{ lg: 12, md: 12, sm: 6, xs: 4, xxs: 2 }}- compactType="vertical"- draggableHandle=".drag-handle"- isDraggable={isDraggable}- isResizable={isResizable}- layouts={layouts}- margin={[16, 16]}- onDragStop={onDragStop}- onLayoutChange={onLayoutChange}- onResizeStop={onResizeStop}- preventCollision={false}- rowHeight={100}- transformScale={1}- useCSSTransforms={true}- >- {children}- </ResponsiveGridLayout>- </div>- </>- );-}diff --git a/apps/start/src/components/groups/group-member-growth.tsx b/apps/start/src/components/groups/group-member-growth.tsxindex 1aab0f229..5a9c35d90 100644--- a/apps/start/src/components/groups/group-member-growth.tsx+++ b/apps/start/src/components/groups/group-member-growth.tsx@@ -1,83 +1,43 @@+import { curveMonotoneX } from 'd3-shape';import { TrendingUpIcon } from 'lucide-react';-import {- Area,- AreaChart,- CartesianGrid,- Tooltip as RechartTooltip,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';import { WidgetHead, WidgetTitle } from '../overview/overview-widget';-import {- useXAxisProps,- useYAxisProps,-} from '@/components/report-chart/common/axis';+import { Area, AreaChart } from '@/components/charts/area-chart';+import { Grid } from '@/components/charts/grid';+import { OPChartTooltip } from '@/components/charts/op-tooltip';+import { XAxis } from '@/components/charts/x-axis';+import { YAxis } from '@/components/charts/y-axis';import { Widget, WidgetBody } from '@/components/widget';-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';+import { formatDateInterval } from '@/hooks/use-format-date-interval';import { useNumber } from '@/hooks/use-numer-formatter';import { getChartColor } from '@/utils/theme';-type Props = {- data: { date: string; count: number }[];-};--function Tooltip(props: any) {- const number = useNumber();- const formatDate = useFormatDateInterval({ interval: 'day', short: false });- const payload = props.payload?.[0]?.payload;+const MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };+const FILL_OPACITY = 0.3;+const COLOR = getChartColor(0);- if (!payload) {- return null;- }+interface Point {+ [key: string]: unknown;+ date: string;+ count: number;+ cumulative: number;+}- return (- <div className="flex min-w-[160px] flex-col gap-2 rounded-xl border bg-card p-3 shadow-xl">- <div className="text-muted-foreground text-sm">- {formatDate(new Date(payload.timestamp))}- </div>- <div className="flex items-center gap-2">- <div- className="h-10 w-1 rounded-full"- style={{ background: getChartColor(0) }}- />- <div className="col gap-1">- <div className="text-muted-foreground text-sm">Total members</div>- <div- className="font-semibold text-lg"- style={{ color: getChartColor(0) }}- >- {number.format(payload.cumulative)}- </div>- </div>- </div>- {payload.count > 0 && (- <div className="text-muted-foreground text-xs">- +{number.format(payload.count)} new- </div>- )}- </div>- );+interface Props {+ data: { date: string; count: number }[];}+const formatDateLabel = (date: Date) =>+ formatDateInterval({ interval: 'day', date, short: true });+export function GroupMemberGrowth({ data }: Props) {- const xAxisProps = useXAxisProps({ interval: 'day' });- const yAxisProps = useYAxisProps({});- const color = getChartColor(0);+ const number = useNumber();let cumulative = 0;- const chartData = data.map((item) => {+ const points: Point[] = data.map((item) => {cumulative += item.count;- return {- date: item.date,- timestamp: new Date(item.date).getTime(),- count: item.count,- cumulative,- };+ return { date: item.date, count: item.count, cumulative };});- const gradientId = 'memberGrowthGradient';-return (<Widget className="w-full"><WidgetHead>@@ -91,40 +51,49 @@ export function GroupMemberGrowth({ data }: Props) {No data yet</p>) : (- <div className="h-[200px] w-full">- <ResponsiveContainer>- <AreaChart data={chartData}>- <defs>- <linearGradient id={gradientId} x1="0" x2="0" y1="0" y2="1">- <stop offset="5%" stopColor={color} stopOpacity={0.3} />- <stop offset="95%" stopColor={color} stopOpacity={0.02} />- </linearGradient>- </defs>- <RechartTooltip- content={<Tooltip />}- cursor={{ stroke: color, strokeOpacity: 0.3 }}- />- <Area- dataKey="cumulative"- dot={false}- fill={`url(#${gradientId})`}- isAnimationActive={false}- stroke={color}- strokeWidth={2}- type="monotone"- />- <XAxis {...xAxisProps} />- <YAxis {...yAxisProps} />- <CartesianGrid- className="stroke-border"- horizontal={true}- strokeDasharray="3 3"- strokeOpacity={0.5}- vertical={false}- />- </AreaChart>- </ResponsiveContainer>- </div>+ <AreaChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-[200px]"+ data={points}+ formatDateLabel={formatDateLabel}+ margin={MARGIN}+ xDataKey="date"+ >+ <Grid horizontal />+ <YAxis formatValue={number.short} />+ <XAxis />+ <Area+ animate={false}+ curve={curveMonotoneX}+ dataKey="cumulative"+ fill={COLOR}+ fillOpacity={FILL_OPACITY}+ stroke={COLOR}+ />+ <OPChartTooltip<Point>+ interval="day"+ rows={(point) => [+ {+ color: COLOR,+ label: 'Total members',+ value: point.cumulative,+ format: number.format,+ sub:+ point.count > 0+ ? [+ {+ label: 'New',+ value: `+${number.format(point.count)}`,+ },+ ]+ : undefined,+ },+ ]}+ showCrosshair+ showDots+ />+ </AreaChart>)}</WidgetBody></Widget>diff --git a/apps/start/src/components/organization/billing-usage.tsx b/apps/start/src/components/organization/billing-usage.tsxindex 0f47ccb7e..3a076c44d 100644--- a/apps/start/src/components/organization/billing-usage.tsx+++ b/apps/start/src/components/organization/billing-usage.tsx@@ -2,29 +2,39 @@ import type { IServiceOrganization } from '@openpanel/core';import { sum } from '@openpanel/shared';import { useQuery } from '@tanstack/react-query';import { Loader2Icon } from 'lucide-react';-import {- Bar,- BarChart,- CartesianGrid,- Tooltip as RechartTooltip,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';-import { BarShapeBlue } from '../charts/common-bar';-import {- useXAxisProps,- useYAxisProps,-} from '@/components/report-chart/common/axis';+import { useCallback } from 'react';+import { ComposedChart } from '@/components/charts/composed-chart';+import { Grid } from '@/components/charts/grid';+import { OPChartTooltip } from '@/components/charts/op-tooltip';+import { SeriesBar } from '@/components/charts/series-bar';+import { XAxis } from '@/components/charts/x-axis';+import { YAxis } from '@/components/charts/y-axis';import { Widget, WidgetBody, WidgetHead } from '@/components/widget';+import { formatDateInterval } from '@/hooks/use-format-date-interval';import { useNumber } from '@/hooks/use-numer-formatter';import { useTRPC } from '@/integrations/trpc/react';import { formatDate } from '@/utils/date';+import { getChartColor } from '@/utils/theme';++const MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };+const BAR_RADIUS = 4;+const DAILY_BAR_SIZE = 8;+const WEEKLY_BAR_SIZE = 20;+// Past this many days daily bars get too thin to read, so usage is summed per week.+const WEEKLY_THRESHOLD_DAYS = 30;+const BAR_COLOR = getChartColor(0);interface Props {organization: IServiceOrganization;}+interface UsagePoint {+ [key: string]: unknown;+ date: number;+ count: number;+ weekRange?: string;+}+function Card({ title, value }: { title: string; value: string }) {return (<div className="col min-w-0 flex-1 gap-2 p-4" title={`${title}: ${value}`}>@@ -43,7 +53,6 @@ export default function BillingUsage({ organization }: Props) {}));- // Determine interval based on data range - use weekly if more than 30 daysconst getDataInterval = () => {if (!usageQuery.data || usageQuery.data.length === 0) {return 'day';@@ -56,13 +65,15 @@ export default function BillingUsage({ organization }: Props) {(maxDate.getTime() - minDate.getTime()) / (1000 * 60 * 60 * 24));- return daysDiff > 30 ? 'week' : 'day';+ return daysDiff > WEEKLY_THRESHOLD_DAYS ? 'week' : 'day';};const interval = getDataInterval();const useWeeklyIntervals = interval === 'week';- const xAxisProps = useXAxisProps({ interval });- const yAxisProps = useYAxisProps({});+ const formatDateLabel = useCallback(+ (date: Date) => formatDateInterval({ interval, date, short: true }),+ [interval]+ );const wrapper = (node: React.ReactNode) => (<Widget className="w-full">@@ -105,24 +116,22 @@ export default function BillingUsage({ organization }: Props) {? organization.subscriptionPeriodEventsCount: 0;- // Group daily data into weekly intervals if data spans more than 30 days- const processChartData = () => {+ const processChartData = (): UsagePoint[] => {if (!usageQuery.data) {return [];}if (useWeeklyIntervals) {- // Group daily data into weekly intervalsconst weeklyData: {[key: string]: { count: number; startDate: Date; endDate: Date };} = {};- usageQuery.data.forEach((item) => {+ for (const item of usageQuery.data) {const date = new Date(item.day);- // Get the start of the week (Monday)const startOfWeek = new Date(date);const dayOfWeek = date.getDay();- const diff = date.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1); // Adjust when day is Sunday+ // Weeks start on Monday; getDay() puts Sunday first.+ const diff = date.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1);startOfWeek.setDate(diff);startOfWeek.setHours(0, 0, 0, 0);@@ -138,7 +147,7 @@ export default function BillingUsage({ organization }: Props) {weeklyData[weekKey].count += item.count;weeklyData[weekKey].endDate = new Date(date);- });+ }return Object.values(weeklyData).map((week) => ({date: week.startDate.getTime(),@@ -147,7 +156,6 @@ export default function BillingUsage({ organization }: Props) {}));}- // Use daily data for monthly subscriptionsreturn usageQuery.data.map((item) => ({date: new Date(item.day).getTime(),count: item.count,@@ -155,17 +163,9 @@ export default function BillingUsage({ organization }: Props) {};const chartData = processChartData();-- const domain = [- 0,- Math.max(- subscriptionPeriodEventsLimit,- subscriptionPeriodEventsCount,- ...chartData.map((item) => item.count)- ),- ] as [number, number];-- domain[1] += domain[1] * 0.05;+ const eventsLabel = useWeeklyIntervals+ ? 'Events this week'+ : 'Events this day';return wrapper(<>@@ -223,101 +223,43 @@ export default function BillingUsage({ organization }: Props) {<h3 className="font-medium text-muted-foreground text-sm">{useWeeklyIntervals ? 'Weekly Events' : 'Daily Events'}</h3>- <div className="h-[250px] max-h-[300px] w-full p-4">- <ResponsiveContainer>- <BarChart barSize={useWeeklyIntervals ? 20 : 8} data={chartData}>- <RechartTooltip- content={<EventsTooltip useWeekly={useWeeklyIntervals} />}- cursor={{- fill: 'var(--def-200)',- stroke: 'var(--def-200)',- }}- />- <Bar- dataKey="count"- isAnimationActive={false}- shape={BarShapeBlue}- />- <XAxis {...xAxisProps} dataKey="date" />- <YAxis {...yAxisProps} domain={[0, 'dataMax']} />- <CartesianGrid- className="stroke-border"- horizontal={true}- strokeDasharray="3 3"- strokeOpacity={0.5}- vertical={false}- />- </BarChart>- </ResponsiveContainer>- </div>+ <ComposedChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-[250px]"+ data={chartData}+ formatDateLabel={formatDateLabel}+ margin={MARGIN}+ maxBarSize={useWeeklyIntervals ? WEEKLY_BAR_SIZE : DAILY_BAR_SIZE}+ xDataKey="date"+ >+ <Grid horizontal />+ <YAxis formatValue={number.short} />+ <XAxis />+ <SeriesBar+ animate={false}+ dataKey="count"+ fill={BAR_COLOR}+ radius={BAR_RADIUS}+ />+ <OPChartTooltip<UsagePoint>+ interval={interval}+ rows={(point) => [+ {+ color: BAR_COLOR,+ label: eventsLabel,+ value: point.count,+ format: number.format,+ },+ ]}+ showCrosshair={false}+ showDots={false}+ title={(point) =>+ point.weekRange ?? formatDate(new Date(point.date))+ }+ />+ </ComposedChart></div></>);}--function EventsTooltip({ useWeekly, ...props }: { useWeekly: boolean } & any) {- const number = useNumber();- const payload = props.payload?.[0]?.payload;-- if (!payload) {- return null;- }-- return (- <div className="flex min-w-[180px] flex-col gap-2 rounded-xl border bg-card p-3 shadow-xl">- <div className="text-muted-foreground text-sm">- {useWeekly && payload.weekRange- ? payload.weekRange- : payload?.date- ? formatDate(new Date(payload.date))- : 'Unknown date'}- </div>- <div className="flex items-center gap-2">- <div className="h-10 w-1 rounded-full bg-chart-0" />- <div className="col gap-1">- <div className="text-muted-foreground text-sm">- Events {useWeekly ? 'this week' : 'this day'}- </div>- <div className="font-semibold text-chart-0 text-lg">- {number.format(payload.count)}- </div>- </div>- </div>- </div>- );-}--function TotalTooltip(props: any) {- const number = useNumber();- const payload = props.payload?.[0]?.payload;-- if (!payload) {- return null;- }-- return (- <div className="flex min-w-[180px] flex-col gap-2 rounded-xl border bg-card p-3 shadow-xl">- <div className="text-muted-foreground text-sm">Total Events</div>- <div className="flex items-center gap-2">- <div className="h-10 w-1 rounded-full bg-chart-2" />- <div className="col gap-1">- <div className="text-muted-foreground text-sm">Your events count</div>- <div className="font-semibold text-chart-2 text-lg">- {number.format(payload.count)}- </div>- </div>- </div>- {payload.limit > 0 && (- <div className="flex items-center gap-2">- <div className="h-10 w-1 rounded-full border-2 border-chart-1 border-dashed" />- <div className="col gap-1">- <div className="text-muted-foreground text-sm">Your tier limit</div>- <div className="font-semibold text-chart-1 text-lg">- {number.format(payload.limit)}- </div>- </div>- </div>- )}- </div>- );-}diff --git a/apps/start/src/components/overview/overview-line-chart.tsx b/apps/start/src/components/overview/overview-line-chart.tsxindex 3775d6832..9116512bc 100644--- a/apps/start/src/components/overview/overview-line-chart.tsx+++ b/apps/start/src/components/overview/overview-line-chart.tsx@@ -8,7 +8,6 @@ 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';@@ -52,9 +51,11 @@ function transformData(visibleSeries: SeriesMeta[]): ChartPoint[] {const allDates = new Set<string>();- items.forEach((item) => {- item.data.forEach((d) => allDates.add(d.date));- });+ for (const item of items) {+ for (const point of item.data) {+ allDates.add(point.date);+ }+ }return Array.from(allDates).sort()@@ -146,7 +147,6 @@ export function OverviewLineChart({strokeWidth={1.5}/>))}- <OPDatePill interval={interval} /><OPChartTooltip<ChartPoint>extra={() => {const total = visibleSeries.length;@@ -212,7 +212,6 @@ export function OverviewLineChart({}));}}showCrosshair- showDatePill={false}showDots/></LineChart>diff --git a/apps/start/src/components/overview/overview-metric-card.tsx b/apps/start/src/components/overview/overview-metric-card.tsxindex 877d2069b..9f6693eb7 100644--- a/apps/start/src/components/overview/overview-metric-card.tsx+++ b/apps/start/src/components/overview/overview-metric-card.tsx@@ -17,6 +17,9 @@ import { formatDate as formatAbsoluteDate, timeAgo } from '@/utils/date';const PRIMARY_COLOR = 'var(--chart-0)';const METRIC_ERROR_LABEL = 'Could not load';+// A tall card's bars get the report bars' rounding; the 40px sparkline's thin bars only a hint of it.+const BAR_RADIUS = 4;+const SPARKLINE_BAR_RADIUS = 1;export type MetricUnit = '' | 'date' | 'timeAgo' | 'min' | '%' | 'currency';@@ -43,6 +46,8 @@ interface MetricCardProps {interval?: IInterval;/** Range drives the default label ("Last 30 days") and dashed-tail logic. */range?: keyof typeof timeWindows;+ /** Stretch to the parent's height; the sparkline takes the extra room. */+ fill?: boolean;}export function OverviewMetricCard({@@ -57,6 +62,7 @@ export function OverviewMetricCard({isError = false,interval = 'day',range,+ fill = false,}: MetricCardProps) {const formatDate = useFormatDateInterval({ interval, short: false });const [hover, setHover] = useState<@@ -76,7 +82,11 @@ export function OverviewMetricCard({const hasValue = !(isLoading || isError);return (- <MetricCardShell active={active} onClick={onClick}>+ <MetricCardShell+ active={active}+ className={cn(fill && 'h-full')}+ onClick={onClick}+ ><div className="px-3 pt-2.5"><div className="flex items-start justify-between gap-2"><span className="truncate font-medium text-[10px] text-muted-foreground uppercase tracking-wider">@@ -100,7 +110,7 @@ export function OverviewMetricCard({</div></div>- <div className="mt-1.5 h-[40px]">+ <div className={cn('mt-1.5', fill ? 'min-h-[40px] flex-1' : 'h-[40px]')}>{data.length > 0 && (<BarChartanimationDuration={0}@@ -117,7 +127,7 @@ export function OverviewMetricCard({dataKey="current"fadedOpacity={0.35}fill={PRIMARY_COLOR}- lineCap={1}+ lineCap={fill ? BAR_RADIUS : SPARKLINE_BAR_RADIUS}/></BarChart>)}diff --git a/apps/start/src/components/overview/overview-metrics.tsx b/apps/start/src/components/overview/overview-metrics.tsxindex 5503728f2..5ba2ed5d3 100644--- a/apps/start/src/components/overview/overview-metrics.tsx+++ b/apps/start/src/components/overview/overview-metrics.tsx@@ -8,7 +8,6 @@ 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';@@ -385,8 +384,6 @@ function Chart({strokeWidth={1.5}/>)}-- <OPDatePill interval={interval} /><OPSeriesDotsdots={[{ dataKey: activeMetric.key, color: primaryColor },@@ -442,7 +439,6 @@ function Chart({return rows;}}- showDatePill={false}showDots={false}spikes={flatSpikes}/>diff --git a/apps/start/src/components/overview/overview-top-devices.tsx b/apps/start/src/components/overview/overview-top-devices.tsxindex eeb09c01f..cbf633e70 100644--- a/apps/start/src/components/overview/overview-top-devices.tsx+++ b/apps/start/src/components/overview/overview-top-devices.tsx@@ -118,7 +118,7 @@ export default function OverviewTopDevices({options: {columns: ['Version', isPageFilter ? 'Views' : 'Sessions'],renderSerieName(name) {- return name[1] || NOT_SET_VALUE;+ return name.at(-1) || NOT_SET_VALUE;},},report: {@@ -199,7 +199,7 @@ export default function OverviewTopDevices({options: {columns: ['Version', isPageFilter ? 'Views' : 'Sessions'],renderSerieName(name) {- return name[1] || NOT_SET_VALUE;+ return name.at(-1) || NOT_SET_VALUE;},},report: {@@ -280,7 +280,7 @@ export default function OverviewTopDevices({options: {columns: ['Model', isPageFilter ? 'Views' : 'Sessions'],renderSerieName(name) {- return name[1] || NOT_SET_VALUE;+ return name.at(-1) || NOT_SET_VALUE;},},report: {diff --git a/apps/start/src/components/page/gsc-clicks-chart.tsx b/apps/start/src/components/page/gsc-clicks-chart.tsxindex 6eb885d0c..7fa09aa30 100644--- a/apps/start/src/components/page/gsc-clicks-chart.tsx+++ b/apps/start/src/components/page/gsc-clicks-chart.tsx@@ -1,61 +1,25 @@import { useQuery } from '@tanstack/react-query';import {- CartesianGrid,- ComposedChart,- Line,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';-import {- ChartTooltipHeader,- ChartTooltipItem,- createChartTooltip,-} from '@/components/charts/chart-tooltip';+ OPLineChart,+ OPLineChartLegend,+ type OPLineChartSeries,+} from '@/components/charts/op-line-chart';import { useOverviewOptions } from '@/components/overview/useOverviewOptions';-import {- useYAxisProps,- X_AXIS_STYLE_PROPS,-} from '@/components/report-chart/common/axis';import { Skeleton } from '@/components/skeleton';-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';import { useTRPC } from '@/integrations/trpc/react';import { getChartColor } from '@/utils/theme';-interface ChartData {- date: string;- clicks: number;- impressions: number;-}+const CHART_HEIGHT = 160;-const { TooltipProvider, Tooltip } = createChartTooltip<- ChartData,- { formatDate: (date: Date | string) => string }->(({ data, context }) => {- const item = data[0];- if (!item) {- return null;- }- return (- <>- <ChartTooltipHeader>- <div>{context.formatDate(item.date)}</div>- </ChartTooltipHeader>- <ChartTooltipItem color={getChartColor(0)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Clicks</span>- <span>{item.clicks.toLocaleString()}</span>- </div>- </ChartTooltipItem>- <ChartTooltipItem color={getChartColor(1)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Impressions</span>- <span>{item.impressions.toLocaleString()}</span>- </div>- </ChartTooltipItem>- </>- );-});+export const GSC_CLICKS_SERIES: OPLineChartSeries[] = [+ { dataKey: 'clicks', label: 'Clicks', color: getChartColor(0) },+ {+ dataKey: 'impressions',+ label: 'Impressions',+ color: getChartColor(1),+ yAxisId: 'right',+ },+];interface GscClicksChartProps {projectId: string;@@ -70,9 +34,6 @@ export function GscClicksChart({}: GscClicksChartProps) {const { range, startDate, endDate, interval } = useOverviewOptions();const trpc = useTRPC();- const yAxisProps = useYAxisProps();- const formatDateShort = useFormatDateInterval({ interval, short: true });- const formatDateLong = useFormatDateInterval({ interval, short: false });const dateInput = {range,@@ -101,96 +62,27 @@ export function GscClicksChart({? pageQuery.data?.timeseries: queryQuery.data?.timeseries) ?? [];- const data: ChartData[] = timeseries.map((r) => ({- date: r.date,- clicks: r.clicks,- impressions: r.impressions,+ const data = timeseries.map((row) => ({+ date: row.date,+ clicks: row.clicks,+ impressions: row.impressions,}));return (<div className="card p-4"><div className="mb-4 flex items-center justify-between"><h3 className="font-medium text-sm">Clicks & Impressions</h3>- <div className="flex items-center gap-4 text-muted-foreground text-xs">- <span className="flex items-center gap-1.5">- <span- className="h-0.5 w-3 rounded-full"- style={{ backgroundColor: getChartColor(0) }}- />- Clicks- </span>- <span className="flex items-center gap-1.5">- <span- className="h-0.5 w-3 rounded-full"- style={{ backgroundColor: getChartColor(1) }}- />- Impressions- </span>- </div>+ <OPLineChartLegend series={GSC_CLICKS_SERIES} /></div>{isLoading ? (<Skeleton className="h-40 w-full" />) : (- <TooltipProvider formatDate={formatDateLong}>- <ResponsiveContainer height={160} width="100%">- <ComposedChart data={data}>- <defs>- <filter- height="140%"- id="gsc-clicks-glow"- width="140%"- x="-20%"- y="-20%"- >- <feGaussianBlur result="blur" stdDeviation="5" />- <feComponentTransfer in="blur" result="dimmedBlur">- <feFuncA slope="0.5" type="linear" />- </feComponentTransfer>- <feComposite- in="SourceGraphic"- in2="dimmedBlur"- operator="over"- />- </filter>- </defs>- <CartesianGrid- className="stroke-border"- horizontal- strokeDasharray="3 3"- vertical={false}- />- <XAxis- {...X_AXIS_STYLE_PROPS}- dataKey="date"- tickFormatter={(v: string) => formatDateShort(v)}- type="category"- />- <YAxis {...yAxisProps} yAxisId="left" />- <YAxis {...yAxisProps} orientation="right" yAxisId="right" />- <Tooltip />- <Line- dataKey="clicks"- dot={false}- filter="url(#gsc-clicks-glow)"- isAnimationActive={false}- stroke={getChartColor(0)}- strokeWidth={2}- type="monotone"- yAxisId="left"- />- <Line- dataKey="impressions"- dot={false}- filter="url(#gsc-clicks-glow)"- isAnimationActive={false}- stroke={getChartColor(1)}- strokeWidth={2}- type="monotone"- yAxisId="right"- />- </ComposedChart>- </ResponsiveContainer>- </TooltipProvider>+ <OPLineChart+ data={data}+ height={CHART_HEIGHT}+ interval={interval}+ series={GSC_CLICKS_SERIES}+ />)}</div>);diff --git a/apps/start/src/components/page/gsc-ctr-benchmark.tsx b/apps/start/src/components/page/gsc-ctr-benchmark.tsxindex 10847d847..350f99f57 100644--- a/apps/start/src/components/page/gsc-ctr-benchmark.tsx+++ b/apps/start/src/components/page/gsc-ctr-benchmark.tsx@@ -1,20 +1,16 @@+import { Bar } from '@/components/charts/bar';+import { BarChart } from '@/components/charts/bar-chart';+import { BarXAxis } from '@/components/charts/bar-x-axis';+import { Grid } from '@/components/charts/grid';import {- CartesianGrid,- ComposedChart,- Line,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';+ OPLineChartLegend,+ type OPLineChartSeries,+} from '@/components/charts/op-line-chart';import {- ChartTooltipHeader,- ChartTooltipItem,- createChartTooltip,-} from '@/components/charts/chart-tooltip';-import {- useYAxisProps,- X_AXIS_STYLE_PROPS,-} from '@/components/report-chart/common/axis';+ OPChartTooltip,+ type OPTooltipRow,+} from '@/components/charts/op-tooltip';+import { YAxis } from '@/components/charts/y-axis';import { Skeleton } from '@/components/skeleton';import { getChartColor } from '@/utils/theme';@@ -42,66 +38,42 @@ const BENCHMARK: Record<number, number> = {20: 0.7,};+const POSITION_COUNT = 20;+// Pages with fewer impressions than this have too noisy a CTR to average.+const MIN_IMPRESSIONS = 10;+const PAGES_PER_POSITION = 5;+const MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };+const BAR_GAP = 0.3;+const BAR_RADIUS = 2;+const AXIS_LABEL_COUNT = 5;++const YOUR_CTR_SERIES: OPLineChartSeries = {+ dataKey: 'yourCtr',+ label: 'Your CTR',+ color: getChartColor(0),+};+const BENCHMARK_SERIES: OPLineChartSeries = {+ dataKey: 'benchmark',+ label: 'Benchmark',+ color: `color-mix(in oklch, ${getChartColor(3)} 60%, transparent)`,+};+interface PageEntry {path: string;ctr: number;impressions: number;}-interface ChartData {+interface ChartRow {+ [key: string]: unknown;position: number;+ label: string;yourCtr: number | null;benchmark: number;pages: PageEntry[];}-const { TooltipProvider, Tooltip } = createChartTooltip<- ChartData,- Record<string, unknown>->(({ data }) => {- const item = data[0];- if (!item) {- return null;- }- return (- <>- <ChartTooltipHeader>- <div>Position #{item.position}</div>- </ChartTooltipHeader>- {item.yourCtr != null && (- <ChartTooltipItem color={getChartColor(0)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Your avg CTR</span>- <span>{item.yourCtr.toFixed(1)}%</span>- </div>- </ChartTooltipItem>- )}- <ChartTooltipItem color={getChartColor(3)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Benchmark</span>- <span>{item.benchmark.toFixed(1)}%</span>- </div>- </ChartTooltipItem>- {item.pages.length > 0 && (- <div className="mt-1.5 border-t pt-1.5">- {item.pages.map((p) => (- <div- className="flex items-center justify-between gap-4 py-0.5"- key={p.path}- >- <span className="max-w-40 truncate font-mono text-muted-foreground text-xs">- {p.path}- </span>- <span className="shrink-0 font-mono text-xs tabular-nums">- {(p.ctr * 100).toFixed(1)}%- </span>- </div>- ))}- </div>- )}- </>- );-});+const formatPercent = (value: number) => `${value.toFixed(1)}%`;interface GscCtrBenchmarkProps {data: Array<{@@ -114,115 +86,131 @@ interface GscCtrBenchmarkProps {}export function GscCtrBenchmark({ data, isLoading }: GscCtrBenchmarkProps) {- const yAxisProps = useYAxisProps();-const grouped = new Map<number, { ctrSum: number; pages: PageEntry[] }>();- for (const d of data) {- const pos = Math.round(d.position);- if (pos < 1 || pos > 20 || d.impressions < 10) {+ for (const row of data) {+ const position = Math.round(row.position);+ const outOfRange = position < 1 || position > POSITION_COUNT;+ if (outOfRange || row.impressions < MIN_IMPRESSIONS) {continue;}- let path = d.page;+ let path = row.page;try {- path = new URL(d.page).pathname;+ path = new URL(row.page).pathname;} catch {// keep as-is}- const entry = grouped.get(pos) ?? { ctrSum: 0, pages: [] };- entry.ctrSum += d.ctr * 100;- entry.pages.push({ path, ctr: d.ctr, impressions: d.impressions });- grouped.set(pos, entry);+ const entry = grouped.get(position) ?? { ctrSum: 0, pages: [] };+ entry.ctrSum += row.ctr * 100;+ entry.pages.push({ path, ctr: row.ctr, impressions: row.impressions });+ grouped.set(position, entry);}- const chartData: ChartData[] = Array.from({ length: 20 }, (_, i) => {- const pos = i + 1;- const entry = grouped.get(pos);+ const rows: ChartRow[] = Array.from({ length: POSITION_COUNT }, (_, i) => {+ const position = i + 1;+ const entry = grouped.get(position);const pages = entry- ? [...entry.pages].sort((a, b) => b.ctr - a.ctr).slice(0, 5)+ ? [...entry.pages]+ .sort((a, b) => b.ctr - a.ctr)+ .slice(0, PAGES_PER_POSITION): [];return {- position: pos,+ position,+ label: `#${position}`,yourCtr: entry ? entry.ctrSum / entry.pages.length : null,- benchmark: BENCHMARK[pos] ?? 0,+ benchmark: BENCHMARK[position] ?? 0,pages,};});- const hasAnyData = chartData.some((d) => d.yourCtr != null);+ const hasAnyData = rows.some((row) => row.yourCtr != null);+ const legend = hasAnyData+ ? [YOUR_CTR_SERIES, BENCHMARK_SERIES]+ : [BENCHMARK_SERIES];return (<div className="card p-4"><div className="mb-4 flex items-center justify-between"><h3 className="font-medium text-sm">CTR vs Position</h3>- <div className="flex items-center gap-4 text-muted-foreground text-xs">- {hasAnyData && (- <span className="flex items-center gap-1.5">- <span- className="h-0.5 w-3 rounded-full"- style={{ backgroundColor: getChartColor(0) }}- />- Your CTR- </span>- )}- <span className="flex items-center gap-1.5">- <span- className="h-0.5 w-3 rounded-full opacity-60"- style={{ backgroundColor: getChartColor(3) }}- />- Benchmark- </span>- </div>+ <OPLineChartLegend series={legend} /></div>{isLoading ? (<Skeleton className="h-40 w-full" />) : (- <TooltipProvider>- <ResponsiveContainer height={160} width="100%">- <ComposedChart data={chartData}>- <CartesianGrid- className="stroke-border"- horizontal- strokeDasharray="3 3"- vertical={false}- />- <XAxis- {...X_AXIS_STYLE_PROPS}- dataKey="position"- domain={[1, 20]}- tickFormatter={(v: number) => `#${v}`}- ticks={[1, 5, 10, 15, 20]}- type="number"- />- <YAxis- {...yAxisProps}- domain={[0, 'auto']}- tickFormatter={(v: number) => `${v}%`}- />- <Tooltip />- <Line- activeDot={{ r: 4 }}- connectNulls={false}- dataKey="yourCtr"- dot={{ r: 3, fill: getChartColor(0) }}- isAnimationActive={false}- stroke={getChartColor(0)}- strokeWidth={2}- type="monotone"- />- <Line- dataKey="benchmark"- dot={false}- isAnimationActive={false}- stroke={getChartColor(3)}- strokeDasharray="4 3"- strokeOpacity={0.6}- strokeWidth={1.5}- type="monotone"- />- </ComposedChart>- </ResponsiveContainer>- </TooltipProvider>+ <BarChart+ animationDuration={0}+ aspectRatio="auto"+ barGap={BAR_GAP}+ className="h-40"+ data={rows}+ margin={MARGIN}+ xDataKey="label"+ >+ <Grid horizontal />+ <YAxis formatValue={(value) => `${value}%`} />+ <BarXAxis maxLabels={AXIS_LABEL_COUNT} />+ <Bar+ animate={false}+ dataKey={YOUR_CTR_SERIES.dataKey}+ fill={YOUR_CTR_SERIES.color}+ lineCap={BAR_RADIUS}+ />+ <Bar+ animate={false}+ dataKey={BENCHMARK_SERIES.dataKey}+ fill={BENCHMARK_SERIES.color}+ lineCap={BAR_RADIUS}+ />+ <OPChartTooltip<ChartRow>+ datePill={false}+ extra={renderPages}+ rows={tooltipRows}+ showDots={false}+ title={(row) => `Position ${row.label}`}+ />+ </BarChart>)}</div>);}++function tooltipRows(row: ChartRow): OPTooltipRow[] {+ const rows: OPTooltipRow[] = [];+ if (row.yourCtr != null) {+ rows.push({+ color: YOUR_CTR_SERIES.color,+ label: YOUR_CTR_SERIES.label,+ value: row.yourCtr,+ format: formatPercent,+ });+ }+ rows.push({+ color: getChartColor(3),+ label: BENCHMARK_SERIES.label,+ value: row.benchmark,+ format: formatPercent,+ });+ return rows;+}++function renderPages(row: ChartRow) {+ if (row.pages.length === 0) {+ return null;+ }+ return (+ <div className="mt-1 border-t pt-1.5">+ {row.pages.map((page) => (+ <div+ className="flex items-center justify-between gap-4 py-0.5"+ key={page.path}+ >+ <span className="max-w-40 truncate font-mono text-muted-foreground text-xs">+ {page.path}+ </span>+ <span className="shrink-0 font-mono text-xs tabular-nums">+ {formatPercent(page.ctr * 100)}+ </span>+ </div>+ ))}+ </div>+ );+}diff --git a/apps/start/src/components/page/gsc-position-chart.tsx b/apps/start/src/components/page/gsc-position-chart.tsxindex c98c32706..53d2c3a33 100644--- a/apps/start/src/components/page/gsc-position-chart.tsx+++ b/apps/start/src/components/page/gsc-position-chart.tsx@@ -1,69 +1,43 @@+import type { IInterval } from '@openpanel/core/modules/report/report.constants';import {- CartesianGrid,- ComposedChart,- Line,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';-import {- ChartTooltipHeader,- ChartTooltipItem,- createChartTooltip,-} from '@/components/charts/chart-tooltip';-import {- useYAxisProps,- X_AXIS_STYLE_PROPS,-} from '@/components/report-chart/common/axis';+ OPLineChart,+ type OPLineChartSeries,+} from '@/components/charts/op-line-chart';import { Skeleton } from '@/components/skeleton';import { getChartColor } from '@/utils/theme';-interface ChartData {- date: string;- position: number;-}+const CHART_HEIGHT = 160;+// Room above and below the plotted positions so the line does not hug the edges.+const POSITION_PADDING = 2;+const DEFAULT_MAX_POSITION = 20;-const { TooltipProvider, Tooltip } = createChartTooltip<- ChartData,- Record<string, unknown>->(({ data }) => {- const item = data[0];- if (!item) {- return null;- }- return (- <>- <ChartTooltipHeader>- <div>{item.date}</div>- </ChartTooltipHeader>- <ChartTooltipItem color={getChartColor(2)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Avg Position</span>- <span>{item.position.toFixed(1)}</span>- </div>- </ChartTooltipItem>- </>- );-});+const SERIES: OPLineChartSeries[] = [+ {+ dataKey: 'position',+ label: 'Avg Position',+ color: getChartColor(2),+ format: (value) => value.toFixed(1),+ },+];interface GscPositionChartProps {data: Array<{ date: string; position: number }>;+ interval: IInterval;isLoading: boolean;}-export function GscPositionChart({ data, isLoading }: GscPositionChartProps) {- const yAxisProps = useYAxisProps();-- const chartData: ChartData[] = data.map((r) => ({- date: r.date,- position: r.position,- }));-- const positions = chartData.map((d) => d.position).filter((p) => p > 0);- const minPos = positions.length- ? Math.max(1, Math.floor(Math.min(...positions)) - 2)+export function GscPositionChart({+ data,+ interval,+ isLoading,+}: GscPositionChartProps) {+ const positions = data.map((row) => row.position).filter((p) => p > 0);+ const minPosition = positions.length+ ? Math.max(1, Math.floor(Math.min(...positions)) - POSITION_PADDING): 1;- const maxPos = positions.length ? Math.ceil(Math.max(...positions)) + 2 : 20;+ const maxPosition = positions.length+ ? Math.ceil(Math.max(...positions)) + POSITION_PADDING+ : DEFAULT_MAX_POSITION;return (<div className="card p-4">@@ -74,59 +48,15 @@ export function GscPositionChart({ data, isLoading }: GscPositionChartProps) {{isLoading ? (<Skeleton className="h-40 w-full" />) : (- <TooltipProvider>- <ResponsiveContainer height={160} width="100%">- <ComposedChart data={chartData}>- <defs>- <filter- height="140%"- id="gsc-pos-glow"- width="140%"- x="-20%"- y="-20%"- >- <feGaussianBlur result="blur" stdDeviation="5" />- <feComponentTransfer in="blur" result="dimmedBlur">- <feFuncA slope="0.5" type="linear" />- </feComponentTransfer>- <feComposite- in="SourceGraphic"- in2="dimmedBlur"- operator="over"- />- </filter>- </defs>- <CartesianGrid- className="stroke-border"- horizontal- strokeDasharray="3 3"- vertical={false}- />- <XAxis- {...X_AXIS_STYLE_PROPS}- dataKey="date"- tickFormatter={(v: string) => v.slice(5)}- type="category"- />- <YAxis- {...yAxisProps}- domain={[minPos, maxPos]}- reversed- tickFormatter={(v: number) => `#${v}`}- />- <Tooltip />- <Line- dataKey="position"- dot={false}- filter="url(#gsc-pos-glow)"- isAnimationActive={false}- stroke={getChartColor(2)}- strokeWidth={2}- type="monotone"- />- </ComposedChart>- </ResponsiveContainer>- </TooltipProvider>+ <OPLineChart+ data={data}+ formatAxisValue={(value) => `#${value}`}+ height={CHART_HEIGHT}+ interval={interval}+ series={SERIES}+ yDomain={[minPosition, maxPosition]}+ yReversed+ />)}</div>);diff --git a/apps/start/src/components/page/page-views-chart.tsx b/apps/start/src/components/page/page-views-chart.tsxindex 4f66241de..d882ca725 100644--- a/apps/start/src/components/page/page-views-chart.tsx+++ b/apps/start/src/components/page/page-views-chart.tsx@@ -1,61 +1,25 @@import { useQuery } from '@tanstack/react-query';import {- CartesianGrid,- ComposedChart,- Line,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';-import {- ChartTooltipHeader,- ChartTooltipItem,- createChartTooltip,-} from '@/components/charts/chart-tooltip';+ OPLineChart,+ OPLineChartLegend,+ type OPLineChartSeries,+} from '@/components/charts/op-line-chart';import { useOverviewOptions } from '@/components/overview/useOverviewOptions';-import {- useYAxisProps,- X_AXIS_STYLE_PROPS,-} from '@/components/report-chart/common/axis';import { Skeleton } from '@/components/skeleton';-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';import { useTRPC } from '@/integrations/trpc/react';import { getChartColor } from '@/utils/theme';-interface ChartData {- date: string;- pageviews: number;- sessions: number;-}+const CHART_HEIGHT = 160;-const { TooltipProvider, Tooltip } = createChartTooltip<- ChartData,- { formatDate: (date: Date | string) => string }->(({ data, context }) => {- const item = data[0];- if (!item) {- return null;- }- return (- <>- <ChartTooltipHeader>- <div>{context.formatDate(item.date)}</div>- </ChartTooltipHeader>- <ChartTooltipItem color={getChartColor(0)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Views</span>- <span>{item.pageviews.toLocaleString()}</span>- </div>- </ChartTooltipItem>- <ChartTooltipItem color={getChartColor(1)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Sessions</span>- <span>{item.sessions.toLocaleString()}</span>- </div>- </ChartTooltipItem>- </>- );-});+const SERIES: OPLineChartSeries[] = [+ { dataKey: 'pageviews', label: 'Views', color: getChartColor(0) },+ {+ dataKey: 'sessions',+ label: 'Sessions',+ color: getChartColor(1),+ yAxisId: 'right',+ },+];interface PageViewsChartProps {projectId: string;@@ -70,9 +34,6 @@ export function PageViewsChart({}: PageViewsChartProps) {const { range, interval } = useOverviewOptions();const trpc = useTRPC();- const yAxisProps = useYAxisProps();- const formatDateShort = useFormatDateInterval({ interval, short: true });- const formatDateLong = useFormatDateInterval({ interval, short: false });const query = useQuery(trpc.event.pageTimeseries.queryOptions({@@ -84,96 +45,27 @@ export function PageViewsChart({}));- const data: ChartData[] = (query.data ?? []).map((r) => ({- date: r.date,- pageviews: r.pageviews,- sessions: r.sessions,+ const data = (query.data ?? []).map((row) => ({+ date: row.date,+ pageviews: row.pageviews,+ sessions: row.sessions,}));return (<div className="card p-4"><div className="mb-4 flex items-center justify-between"><h3 className="font-medium text-sm">Views & Sessions</h3>- <div className="flex items-center gap-4 text-muted-foreground text-xs">- <span className="flex items-center gap-1.5">- <span- className="h-0.5 w-3 rounded-full"- style={{ backgroundColor: getChartColor(0) }}- />- Views- </span>- <span className="flex items-center gap-1.5">- <span- className="h-0.5 w-3 rounded-full"- style={{ backgroundColor: getChartColor(1) }}- />- Sessions- </span>- </div>+ <OPLineChartLegend series={SERIES} /></div>{query.isLoading ? (<Skeleton className="h-40 w-full" />) : (- <TooltipProvider formatDate={formatDateLong}>- <ResponsiveContainer height={160} width="100%">- <ComposedChart data={data}>- <defs>- <filter- height="140%"- id="page-views-glow"- width="140%"- x="-20%"- y="-20%"- >- <feGaussianBlur result="blur" stdDeviation="5" />- <feComponentTransfer in="blur" result="dimmedBlur">- <feFuncA slope="0.5" type="linear" />- </feComponentTransfer>- <feComposite- in="SourceGraphic"- in2="dimmedBlur"- operator="over"- />- </filter>- </defs>- <CartesianGrid- className="stroke-border"- horizontal- strokeDasharray="3 3"- vertical={false}- />- <XAxis- {...X_AXIS_STYLE_PROPS}- dataKey="date"- tickFormatter={(v: string) => formatDateShort(v)}- type="category"- />- <YAxis {...yAxisProps} yAxisId="left" />- <YAxis {...yAxisProps} orientation="right" yAxisId="right" />- <Tooltip />- <Line- dataKey="pageviews"- dot={false}- filter="url(#page-views-glow)"- isAnimationActive={false}- stroke={getChartColor(0)}- strokeWidth={2}- type="monotone"- yAxisId="left"- />- <Line- dataKey="sessions"- dot={false}- filter="url(#page-views-glow)"- isAnimationActive={false}- stroke={getChartColor(1)}- strokeWidth={2}- type="monotone"- yAxisId="right"- />- </ComposedChart>- </ResponsiveContainer>- </TooltipProvider>+ <OPLineChart+ data={data}+ height={CHART_HEIGHT}+ interval={interval}+ series={SERIES}+ />)}</div>);diff --git a/apps/start/src/components/projects/project-card.tsx b/apps/start/src/components/projects/project-card.tsxindex bbf362b07..da94fc865 100644--- a/apps/start/src/components/projects/project-card.tsx+++ b/apps/start/src/components/projects/project-card.tsx@@ -21,7 +21,7 @@ export function ProjectCardRoot({return (<divclassName={cn(- 'card relative hover:-translate-y-px hover:shadow-sm',+ 'card relative hover:z-10 hover:-translate-y-px hover:shadow-sm',className)}>@@ -88,7 +88,7 @@ function ProjectChartOuter({ id }: { id: string }) {return (<FadeIn className="h-full w-full">- <ProjectChart color={'blue'} data={data?.chart || []} />+ <ProjectChart data={data?.chart || []} /></FadeIn>);}diff --git a/apps/start/src/components/projects/project-chart.tsx b/apps/start/src/components/projects/project-chart.tsxindex 3bd5750f0..815c0fee5 100644--- a/apps/start/src/components/projects/project-chart.tsx+++ b/apps/start/src/components/projects/project-chart.tsx@@ -1,261 +1,143 @@-import { useState } from 'react';-import {- Bar,- Cell,- ComposedChart,- Line,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';-import { useYAxisProps } from '../report-chart/common/axis';-import {- ChartTooltipHeader,- ChartTooltipItem,- createChartTooltip,-} from '@/components/charts/chart-tooltip';+import { curveMonotoneX } from 'd3-shape';+import { ComposedChart } from '@/components/charts/composed-chart';+import { Line } from '@/components/charts/line';+import { OPChartTooltip } from '@/components/charts/op-tooltip';+import { SeriesBar } from '@/components/charts/series-bar';+import { YAxis } from '@/components/charts/y-axis';import { useNumber } from '@/hooks/use-numer-formatter';-import { cn } from '@/utils/cn';import { getChartColor } from '@/utils/theme';-type ChartDataItem = {+const MARGIN = { top: 10, right: 10, bottom: 10, left: 32 };+const SESSIONS_COLOR = getChartColor(0);+const REVENUE_COLOR = '#3ba974';+const REVENUE_AXIS_ID = 'right';+// Revenue bars sit in the lower half so the sessions line stays readable above them.+const REVENUE_HEADROOM = 2;+const REVENUE_MAX_BAR_SIZE = 20;+// Thin bars: a larger radius rounds every corner into a pill.+const REVENUE_BAR_RADIUS = 2;+const HOVER_DOT_SIZE = 3;+const HOVER_DOT_HALO_SCALE = 1.8;+const LINE_WIDTH = 2;+const AXIS_TICKS = 2;++const EMPTY_STATE_BARS = [+ 28, 42, 35, 50, 40, 56, 45, 60, 49, 32, 98, 29, 49, 69, 49, 20, 28, 42, 35,+ 50, 40, 56, 45, 60, 49, 32, 98, 29, 49, 69, 49, 20,+];++interface ChartPoint {+ [key: string]: unknown;value: number;date: Date;revenue: number;- timestamp: number;-};--const { Tooltip, TooltipProvider } = createChartTooltip<- ChartDataItem,- {- color: 'blue' | 'green' | 'red';- }->(- ({- context,- data: dataArray,- }: {- context: { color: 'blue' | 'green' | 'red' };- data: ChartDataItem[];- }) => {- const { color } = context;- const data = dataArray[0];- const number = useNumber();-- if (!data) {- return null;- }-- const getColorValue = () => {- if (color === 'green') {- return '#16a34a';- }- if (color === 'red') {- return '#dc2626';- }- return getChartColor(0);- };-- const formatDate = (date: Date) => {- return new Intl.DateTimeFormat('en-GB', {- weekday: 'short',- day: '2-digit',- month: 'short',- }).format(date);- };-- return (- <>- <ChartTooltipHeader>- <div className="text-muted-foreground">{formatDate(data.date)}</div>- </ChartTooltipHeader>- <ChartTooltipItem- color={getColorValue()}- innerClassName="row justify-between"- >- <div className="flex items-center gap-1">Sessions</div>- <div className="font-bold font-mono">{number.format(data.value)}</div>- </ChartTooltipItem>- {data.revenue > 0 && (- <ChartTooltipItem color="#3ba974">- <div className="flex items-center gap-1">Revenue</div>- <div className="font-medium font-mono">- {number.currency(data.revenue / 100)}- </div>- </ChartTooltipItem>- )}- </>- );- }-);+}export function ProjectChart({data,- dots = false,- color = 'blue',}: {- dots?: boolean;- color?: 'blue' | 'green' | 'red';data: { value: number; date: Date; revenue: number }[];}) {- const [activeBar, setActiveBar] = useState(-1);-- const yAxisProps = useYAxisProps({- width: 30,- });+ const number = useNumber();if (data.length === 0) {return null;}+ const points: ChartPoint[] = data.map((point) => ({ ...point }));- // Transform data for Recharts (needs timestamp for time-based x-axis)- const chartData = data.map((item) => ({- ...item,- timestamp: item.date.getTime(),- }));-- const maxValue = Math.max(...data.map((d) => d.value), 0);- const maxRevenue = Math.max(...data.map((d) => d.revenue), 0);-- const getColorValue = () => {- if (color === 'green') {- return '#16a34a';- }- if (color === 'red') {- return '#dc2626';- }- return getChartColor(0);- };+ const maxValue = Math.max(...data.map((point) => point.value), 0);+ const maxRevenue = Math.max(...data.map((point) => point.revenue), 0);+ const hasRevenue = maxRevenue > 0;if (maxValue === 0) {- return (- <div className="relative h-full w-full pl-3">- <div className="pointer-events-none absolute inset-x-3 bottom-2 h-12">- <div className="flex h-full items-end gap-1.5 opacity-35">- {[- 28, 42, 35, 50, 40, 56, 45, 60, 49, 32, 98, 29, 49, 69, 49, 20,- 28, 42, 35, 50, 40, 56, 45, 60, 49, 32, 98, 29, 49, 69, 49, 20,- ].map((height, index) => (- <div- className="flex-1 rounded-full bg-foreground/20"- key={index}- style={{ height: `${height}%` }}- />- ))}- </div>- </div>-- <div className="absolute inset-0 flex flex-col items-center justify-center gap-1 px-4 text-center">- <p className="font-medium text-foreground/85 text-sm">- No activity yet- </p>- <p className="text-muted-foreground text-xs">- Sessions will show up here once tracking starts.- </p>- </div>- </div>- );+ return <EmptyState />;}return (<div className="relative h-full w-full pl-3">- <TooltipProvider color={color}>- <ResponsiveContainer height="100%" width="100%">- <ComposedChart- data={chartData}- margin={{ top: 10, right: 10, bottom: 10, left: 0 }}- onMouseMove={(e) => {- setActiveBar(e.activeTooltipIndex ?? -1);- }}- >- <XAxis- dataKey="timestamp"- domain={['dataMin', 'dataMax']}- hide- scale="time"- type="number"- />- <YAxis- {...yAxisProps}- allowDecimals={false}- domain={[0, maxValue || 'dataMax']}- />- <YAxis- domain={[0, maxRevenue * 2 || 'dataMax']}- hide- orientation="right"- width={0}- yAxisId="right"- />-- <Tooltip />-- <defs>- <filter- height="140%"- id="rainbow-line-glow"- width="140%"- x="-20%"- y="-20%"- >- <feGaussianBlur result="blur" stdDeviation="5" />- <feComponentTransfer in="blur" result="dimmedBlur">- <feFuncA slope="0.5" type="linear" />- </feComponentTransfer>- <feComposite- in="SourceGraphic"- in2="dimmedBlur"- operator="over"- />- </filter>- </defs>+ <ComposedChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-full"+ data={points}+ margin={MARGIN}+ maxBarSize={REVENUE_MAX_BAR_SIZE}+ xDataKey="date"+ yDomains={+ hasRevenue+ ? { [REVENUE_AXIS_ID]: [0, maxRevenue * REVENUE_HEADROOM] }+ : undefined+ }+ >+ <YAxis formatValue={number.short} numTicks={AXIS_TICKS} />+ {hasRevenue && (+ <SeriesBar+ animate={false}+ dataKey="revenue"+ fill={REVENUE_COLOR}+ radius={REVENUE_BAR_RADIUS}+ yAxisId={REVENUE_AXIS_ID}+ />+ )}+ <Line+ animate={false}+ curve={curveMonotoneX}+ dataKey="value"+ stroke={SESSIONS_COLOR}+ strokeWidth={LINE_WIDTH}+ />+ <OPChartTooltip<ChartPoint>+ datePill={false}+ dotHaloScale={HOVER_DOT_HALO_SCALE}+ dotSize={HOVER_DOT_SIZE}+ rows={(point) => [+ {+ color: SESSIONS_COLOR,+ label: 'Sessions',+ value: point.value,+ format: number.format,+ },+ ...(point.revenue > 0+ ? [+ {+ color: REVENUE_COLOR,+ label: 'Revenue',+ value: point.revenue,+ unit: 'currency',+ },+ ]+ : []),+ ]}+ showCrosshair+ showDots+ />+ </ComposedChart>+ </div>+ );+}- <Line- activeDot={{- stroke: getColorValue(),- fill: 'var(--def-100)',- strokeWidth: 2,- r: 4,- }}- dataKey="value"- dot={- dots && data.length <= 90- ? {- stroke: getColorValue(),- fill: 'transparent',- strokeWidth: 1.5,- r: 3,- }- : false- }- filter="url(#rainbow-line-glow)"- isAnimationActive={false}- stroke={getColorValue()}- strokeWidth={2}- type="monotone"+function EmptyState() {+ return (+ <div className="relative h-full w-full pl-3">+ <div className="pointer-events-none absolute inset-x-3 bottom-2 h-12">+ <div className="flex h-full items-end gap-1.5 opacity-35">+ {EMPTY_STATE_BARS.map((height, index) => (+ <div+ className="flex-1 rounded-full bg-foreground/20"+ key={`${index}-${height}`}+ style={{ height: `${height}%` }}/>+ ))}+ </div>+ </div>- <Bar- dataKey="revenue"- isAnimationActive={false}- maxBarSize={20}- radius={5}- stackId="revenue"- yAxisId="right"- >- {chartData.map((item, index) => (- <Cell- className={cn(- index === activeBar- ? 'fill-emerald-700/100'- : 'fill-emerald-700/80'- )}- key={item.timestamp}- />- ))}- </Bar>- </ComposedChart>- </ResponsiveContainer>- </TooltipProvider>+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-1 px-4 text-center">+ <p className="font-medium text-foreground/85 text-sm">+ No activity yet+ </p>+ <p className="text-muted-foreground text-xs">+ Sessions will show up here once tracking starts.+ </p>+ </div></div>);}diff --git a/apps/start/src/components/providers.tsx b/apps/start/src/components/providers.tsxindex ca7fe4a7a..3c61440bd 100644--- a/apps/start/src/components/providers.tsx+++ b/apps/start/src/components/providers.tsx@@ -3,6 +3,10 @@ import { useRef } from 'react';import { Provider as ReduxProvider } from 'react-redux';import { Toaster } from 'sonner';import { ThemeProvider } from './theme-provider';+import {+ ChartConfigProvider,+ type ChartConfigValue,+} from '@/components/charts/chart-config-context';import { ChatStateProvider } from '@/components/chat/chat-context';import { NotificationProvider } from '@/components/notifications/notification-provider';import { TooltipProvider } from '@/components/ui/tooltip';@@ -11,6 +15,15 @@ import { ModalProvider } from '@/modals';import type { AppStore } from '@/redux';import makeStore from '@/redux';+// Dense time series are hovered bucket to bucket; bklit's default springs+// read as lag there.+const SNAPPY_SPRING = { stiffness: 1000, damping: 60 };+const CHART_CONFIG: ChartConfigValue = {+ tooltipSpring: SNAPPY_SPRING,+ tooltipBoxSpring: SNAPPY_SPRING,+ highlightSpring: SNAPPY_SPRING,+};+export function Providers({ children }: { children: React.ReactNode }) {const storeRef = useRef<AppStore>(undefined);if (!storeRef.current) {@@ -22,14 +35,16 @@ export function Providers({ children }: { children: React.ReactNode }) {<ThemeProvider><ReduxProvider store={storeRef.current}><TooltipProvider delayDuration={200}>- <PageContextProvider>- <ChatStateProvider>- {children}- <NotificationProvider />- <Toaster />- <ModalProvider />- </ChatStateProvider>- </PageContextProvider>+ <ChartConfigProvider value={CHART_CONFIG}>+ <PageContextProvider>+ <ChatStateProvider>+ {children}+ <NotificationProvider />+ <Toaster />+ <ModalProvider />+ </ChatStateProvider>+ </PageContextProvider>+ </ChartConfigProvider></TooltipProvider></ReduxProvider></ThemeProvider>diff --git a/apps/start/src/components/realtime/realtime-live-histogram.tsx b/apps/start/src/components/realtime/realtime-live-histogram.tsxindex 2a88b550a..86ab50dee 100644--- a/apps/start/src/components/realtime/realtime-live-histogram.tsx+++ b/apps/start/src/components/realtime/realtime-live-histogram.tsx@@ -1,22 +1,26 @@-import * as Portal from '@radix-ui/react-portal';import { useQuery } from '@tanstack/react-query';-import { bind } from 'bind-event-listener';-import throttle from 'lodash.throttle';-import React, { useEffect, useState } from 'react';-import {- Bar,- BarChart,- ResponsiveContainer,- Tooltip,- XAxis,- YAxis,-} from 'recharts';+import type React from 'react';import { AnimatedNumber } from '../animated-number';import { SerieIcon } from '../report-chart/common/serie-icon';+import { Bar } from '@/components/charts/bar';+import { BarChart } from '@/components/charts/bar-chart';+import { OPChartTooltip } from '@/components/charts/op-tooltip';import { useNumber } from '@/hooks/use-numer-formatter';import { useTRPC } from '@/integrations/trpc/react';+import type { RouterOutputs } from '@/trpc/client';import { getChartColor } from '@/utils/theme';+const BAR_COLOR = getChartColor(0);+const BAR_RADIUS = 1;+const BAR_GAP = 0.25;+const NO_MARGIN = { top: 0, right: 0, bottom: 0, left: 0 };+const TOOLTIP_REFERRERS = 3;++type MinutePoint =+ RouterOutputs['overview']['liveData']['minuteCounts'][number] & {+ [key: string]: unknown;+ };+interface RealtimeLiveHistogramProps {projectId: string;}@@ -32,7 +36,9 @@ export function RealtimeLiveHistogram({trpc.overview.liveData.queryOptions({ projectId }));- const chartData = liveData?.minuteCounts ?? [];+ const chartData: MinutePoint[] = (liveData?.minuteCounts ?? []).map(+ (point) => ({ ...point })+ );// Approximation: totalSessions, not unique visitors across the window.const totalVisitors = liveData?.totalSessions ?? 0;@@ -48,35 +54,73 @@ export function RealtimeLiveHistogram({return null;}- const maxDomain =- Math.max(...chartData.map((item) => item.visitorCount), 0) * 1.2 || 1;-return (<Wrapper count={totalVisitors}>- <ResponsiveContainer height="100%" width="100%">- <BarChart- data={chartData}- margin={{ top: 0, right: 0, left: 0, bottom: 0 }}- >- <Tooltip- content={CustomTooltip}- cursor={{- fill: 'var(--def-200)',- }}- />- <XAxis axisLine={false} dataKey="time" hide tickLine={false} />- <YAxis domain={[0, maxDomain]} hide />- <Bar- className="fill-chart-0"- dataKey="visitorCount"- isAnimationActive={false}- />- </BarChart>- </ResponsiveContainer>+ <BarChart+ animationDuration={0}+ aspectRatio="auto"+ barGap={BAR_GAP}+ className="h-full"+ data={chartData}+ margin={NO_MARGIN}+ xDataKey="time"+ >+ <Bar+ animate={false}+ dataKey="visitorCount"+ fill={BAR_COLOR}+ lineCap={BAR_RADIUS}+ />+ <OPChartTooltip<MinutePoint>+ datePill={false}+ extra={renderReferrers}+ rows={(point) => [+ {+ color: BAR_COLOR,+ label: 'Active users',+ value: point.visitorCount,+ format: number.format,+ },+ ]}+ showDots={false}+ title={(point) => point.time}+ />+ </BarChart></Wrapper>);}+function renderReferrers(point: MinutePoint) {+ if (point.referrers.length === 0) {+ return null;+ }+ const hidden = point.referrers.length - TOOLTIP_REFERRERS;+ return (+ <div className="mt-1 border-border border-t pt-2">+ <div className="mb-2 text-muted-foreground text-xs">Referrers:</div>+ <div className="space-y-1">+ {point.referrers.slice(0, TOOLTIP_REFERRERS).map((ref) => (+ <div+ className="row items-center justify-between text-xs"+ key={ref.referrer}+ >+ <div className="row items-center gap-1">+ <SerieIcon name={ref.referrer} />+ <span className="max-w-[120px] truncate" title={ref.referrer}>+ {ref.referrer}+ </span>+ </div>+ <span className="font-mono">{ref.count}</span>+ </div>+ ))}+ {hidden > 0 && (+ <div className="text-muted-foreground text-xs">+{hidden} more</div>+ )}+ </div>+ </div>+ );+}+interface WrapperProps {children: React.ReactNode;count: number;@@ -101,122 +145,3 @@ function Wrapper({ children, count, icons }: WrapperProps) {</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- className="rounded-md border bg-background/80 p-3 shadow-xl backdrop-blur-sm"- style={{- position: 'fixed',- top: position?.y,- left: correctXPosition(position?.x),- zIndex: 1000,- width: tooltipWidth,- }}- >- <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">Active users</div>- <div className="flex justify-between gap-8 font-medium font-mono">- <div className="row gap-1">- {number.formatWithUnit(data.visitorCount)}- </div>- </div>- </div>- </div>- {data.referrers && data.referrers.length > 0 && (- <div className="mt-2 border-border border-t pt-2">- <div className="mb-2 text-muted-foreground text-xs">Referrers:</div>- <div className="space-y-1">- {data.referrers.slice(0, 3).map((ref: any, index: number) => (- <div- className="row items-center justify-between text-xs"- key={`${ref.referrer}-${ref.count}-${index}`}- >- <div className="row items-center gap-1">- <SerieIcon name={ref.referrer} />- <span- className="max-w-[120px] truncate"- title={ref.referrer}- >- {ref.referrer}- </span>- </div>- <span className="font-mono">{ref.count}</span>- </div>- ))}- {data.referrers.length > 3 && (- <div className="text-muted-foreground text-xs">- +{data.referrers.length - 3} more- </div>- )}- </div>- </div>- )}- </React.Fragment>- </Portal.Portal>- );-};diff --git a/apps/start/src/components/report-chart/area/chart.tsx b/apps/start/src/components/report-chart/area/chart.tsxindex 61a61ce91..f06694627 100644--- a/apps/start/src/components/report-chart/area/chart.tsx+++ b/apps/start/src/components/report-chart/area/chart.tsx@@ -1,320 +1,123 @@-import { useQuery } from '@tanstack/react-query';-import { isSameDay, isSameHour, isSameMonth, isSameWeek } from 'date-fns';-import { BookmarkIcon, UsersIcon } from 'lucide-react';-import { last } from 'ramda';-import { useCallback } from 'react';+import { useMemo } from 'react';+import { PointClick } from '../common/point-click';import {- Area,- CartesianGrid,- ComposedChart,- Customized,- Legend,- Line,- ReferenceLine,- ResponsiveContainer,- Tooltip,- XAxis,- YAxis,-} from 'recharts';-import { useXAxisProps, useYAxisProps } from '../common/axis';-import {- ChartClickMenu,- type ChartClickMenuItem,-} from '../common/chart-click-menu';-import { ReportChartTooltip } from '../common/report-chart-tooltip';-import { ReportTable } from '../common/report-table';-import { SerieIcon } from '../common/serie-icon';-import { SerieName } from '../common/serie-name';-import { useReportChartContext } from '../context';-import { changeVisibleSeries } from '@/components/report/reportSlice';-import { useDashedStroke } from '@/hooks/use-dashed-stroke';-import { useRechartDataModel } from '@/hooks/use-rechart-data-model';-import { useVisibleSeries } from '@/hooks/use-visible-series';-import { useTRPC } from '@/integrations/trpc/react';-import { pushModal } from '@/modals';-import { useDispatch } from '@/redux';+ POINT_MARKER,+ previousPeriodColor,+ TimeSeriesFrame,+ type TimeSeriesPoint,+ useTimeSeriesChart,+} from '../common/time-series';+import { Area, AreaChart } from '@/components/charts/area-chart';+import { Grid } from '@/components/charts/grid';+import { OPReferences } from '@/components/charts/op-references';+import { OPChartTooltip } from '@/components/charts/op-tooltip';+import { XAxis } from '@/components/charts/x-axis';+import { YAxis } from '@/components/charts/y-axis';+import type { IVisibleSeries } from '@/hooks/use-visible-series';import type { IChartData } from '@/trpc/client';-import { cn } from '@/utils/cn';import { getChartColor } from '@/utils/theme';+const AREA_FILL_OPACITY = 0.5;+const PREVIOUS_FILL_OPACITY = 0.15;+interface Props {data: IChartData;+ series: IVisibleSeries;}-export function Chart({ data }: Props) {- const {- report: {- previous,- interval,- projectId,- startDate,- endDate,- range,- lineType,- series: reportSeries,- breakdowns,- visibleSeries: savedVisibleSeries,- },- isEditMode,- shareId,- options: { hideXAxis, hideYAxis },- } = useReportChartContext();- const dispatch = useDispatch();- const trpc = useTRPC();- const references = useQuery(- trpc.reference.getChartReferences.queryOptions({- projectId,- startDate,- endDate,- range,- })+export function Chart({ data, series }: Props) {+ const chart = useTimeSeriesChart({ data, series, chartType: 'area' });+ const stackedData = useMemo(+ () => stackSeries(chart.chartData, series),+ [chart.chartData, series]);- const { series, setVisibleSeries } = useVisibleSeries(data, {- savedVisibleSeries,- onVisibleSeriesChange: isEditMode- ? (ids) => dispatch(changeVisibleSeries(ids))- : undefined,- });- const rechartData = useRechartDataModel(series);-- let dotIndex;- if (range === 'today') {- // Find closest index based on times- dotIndex = rechartData.findIndex((item) => {- return isSameHour(item.date, new Date());- });- }-- const lastSerieDataItem = last(series[0]?.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());- }-- if (interval === 'month') {- return isSameMonth(lastSerieDataItem, new Date());- }-- if (interval === 'week') {- return isSameWeek(lastSerieDataItem, new Date());- }- return false;- })();-- const CustomLegend = useCallback(() => {- return (- <div className="mt-4 -mb-2 flex flex-wrap justify-center gap-x-4 gap-y-1 text-xs">+ return (+ <TimeSeriesFrame chartType="area" menu={chart.menu} series={series}>+ <AreaChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-full"+ data={stackedData}+ formatDateLabel={chart.formatDateLabel}+ margin={chart.margin}+ style={{ touchAction: 'pan-y' }}+ xDataKey="date"+ >+ <Grid horizontal />+ {!chart.hideYAxis && <YAxis formatValue={chart.formatAxisValue} />}+ {!chart.hideXAxis && <XAxis />}+ {chart.previous &&+ series.map((serie) => (+ <Area+ animate={false}+ baselineKey={stackKeys(serie.id, 'prev').base}+ curve={chart.curve}+ dataKey={stackKeys(serie.id, 'prev').top}+ fill={previousPeriodColor(serie.index)}+ fillOpacity={PREVIOUS_FILL_OPACITY}+ key={`${serie.id}:prev`}+ showHighlight={false}+ showLine={false}+ />+ ))}{series.map((serie) => (- <div- className="flex items-center gap-1"+ <Area+ animate={false}+ baselineKey={stackKeys(serie.id).base}+ curve={chart.curve}+ dashArray="4,4"+ dashFromIndex={chart.dashFromIndex}+ dataKey={stackKeys(serie.id).top}+ fill={getChartColor(serie.index)}+ fillOpacity={AREA_FILL_OPACITY}key={serie.id}- style={{- color: getChartColor(serie.index),- }}- >- <SerieIcon name={serie.names} />- <SerieName name={serie.names} />- </div>+ markers={POINT_MARKER}+ showMarkers={chart.showMarkers}+ stroke={getChartColor(serie.index)}+ />))}- </div>- );- }, [series]);-- const yAxisProps = useYAxisProps({- hide: hideYAxis,- });- const xAxisProps = useXAxisProps({- hide: hideXAxis,- interval,- });-- const getMenuItems = useCallback(- (e: any, clickedData: any): ChartClickMenuItem[] => {- const items: ChartClickMenuItem[] = [];-- // Both actions need a signed-in member, which a share visitor is not.- if (shareId || !clickedData?.date) {- return items;- }-- // View Users - only show if we have projectId- if (projectId) {- items.push({- label: 'View Users',- icon: <UsersIcon size={16} />,- onClick: () => {- pushModal('ViewChartUsers', {- type: 'chart',- chartData: data,- report: {- projectId,- series: reportSeries,- breakdowns: breakdowns || [],- interval,- startDate,- endDate,- range,- previous,- chartType: 'area',- metric: 'sum',- },- date: clickedData.date,- });- },- });- }-- // Add Reference - always show- items.push({- label: 'Add Reference',- icon: <BookmarkIcon size={16} />,- onClick: () => {- pushModal('AddReference', {- datetime: new Date(clickedData.date).toISOString(),- });- },- });-- return items;- },- [- shareId,- projectId,- data,- reportSeries,- breakdowns,- interval,- startDate,- endDate,- range,- previous,- ]+ <OPReferences items={chart.references} />+ <OPChartTooltip<TimeSeriesPoint>+ extra={chart.tooltipExtra}+ interval={chart.interval}+ references={chart.references}+ rows={chart.tooltipRows}+ showCrosshair+ showDots+ />+ <PointClick<TimeSeriesPoint> onClick={chart.menu.openMenu} />+ </AreaChart>+ </TimeSeriesFrame>);+}- const { getStrokeDasharray, calcStrokeDasharray, handleAnimationEnd } =- useDashedStroke({- dotIndex,- });+function stackKeys(serieId: string, period?: 'prev') {+ const prefix = period ? `${serieId}:${period}` : serieId;+ return {+ value: `${prefix}:count`,+ top: `${prefix}:stack`,+ base: `${prefix}:stack-base`,+ };+}- return (- <ReportChartTooltip.TooltipProvider references={references.data}>- <ChartClickMenu getMenuItems={getMenuItems}>- <div className={cn('h-full w-full', isEditMode && 'card p-4')}>- <ResponsiveContainer>- <ComposedChart data={rechartData}>- <Customized component={calcStrokeDasharray} />- <Line- animationDuration={0}- dataKey="calcStrokeDasharray"- legendType="none"- onAnimationEnd={handleAnimationEnd}- />- <CartesianGrid- className="stroke-border"- horizontal={true}- strokeDasharray="3 3"- vertical={false}- />- {references.data?.map((ref) => (- <ReferenceLine- fontSize={10}- key={ref.id}- label={{- value: ref.title,- position: 'centerTop',- fill: '#334155',- fontSize: 12,- }}- stroke={'oklch(from var(--foreground) l c h / 0.1)'}- strokeDasharray={'3 3'}- x={ref.date.getTime()}- />- ))}- <YAxis {...yAxisProps} />- <XAxis {...xAxisProps} />- <Legend content={<CustomLegend />} />- <Tooltip content={<ReportChartTooltip.Tooltip />} />- {series.map((serie) => {- const color = getChartColor(serie.index);- return (- <defs key={`defs-${serie.id}`}>- <linearGradient- id={`color${color}`}- x1="0"- x2="0"- y1="0"- y2="1"- >- <stop offset="0%" stopColor={color} stopOpacity={0.8} />- <stop- offset={'100%'}- stopColor={color}- stopOpacity={0.1}- />- </linearGradient>- </defs>- );- })}- {series.map((serie) => {- const color = getChartColor(serie.index);- return (- <Area- dataKey={`${serie.id}:count`}- fill={`url(#color${color})`}- fillOpacity={0.7}- isAnimationActive={false}- key={serie.id}- name={serie.id}- stackId="1"- stroke={color}- strokeDasharray={- useDashedLastLine- ? getStrokeDasharray(`${serie.id}:count`)- : undefined- }- strokeWidth={2}- type={lineType}- />- );- })}- {previous &&- series.map((serie) => {- const color = getChartColor(serie.index);- return (- <Area- dataKey={`${serie.id}:prev:count`}- fill={color}- fillOpacity={0.3}- isAnimationActive={false}- key={`${serie.id}:prev`}- name={`${serie.id}:prev`}- stackId="2"- stroke={color}- strokeOpacity={0.3}- type={lineType}- />- );- })}- </ComposedChart>- </ResponsiveContainer>- </div>- {isEditMode && (- <ReportTable- data={data}- setVisibleSeries={setVisibleSeries}- visibleSeries={series}- />- )}- </ChartClickMenu>- </ReportChartTooltip.TooltipProvider>- );+/** Adds a top and a base per series so each area sits on the ones before it. */+function stackSeries(points: TimeSeriesPoint[], series: IVisibleSeries) {+ return points.map((point) => {+ const stacked: TimeSeriesPoint = { ...point };+ for (const period of [undefined, 'prev'] as const) {+ let total = 0;+ for (const serie of series) {+ const keys = stackKeys(serie.id, period);+ const value = point[keys.value];+ if (typeof value !== 'number') {+ continue;+ }+ stacked[keys.base] = total;+ total += value;+ stacked[keys.top] = total;+ }+ }+ return stacked;+ });}diff --git a/apps/start/src/components/report-chart/area/index.tsx b/apps/start/src/components/report-chart/area/index.tsxindex fac448240..cae2ca611 100644--- a/apps/start/src/components/report-chart/area/index.tsx+++ b/apps/start/src/components/report-chart/area/index.tsx@@ -3,6 +3,7 @@ import { AspectContainer } from '../aspect-container';import { ReportChartEmpty } from '../common/empty';import { ReportChartError } from '../common/error';import { ReportChartLoading } from '../common/loading';+import { SeriesWithTable } from '../common/series-with-table';import { useChartInput, useReportChartContext } from '../context';import { Chart } from './chart';import { useTRPC } from '@/integrations/trpc/react';@@ -42,9 +43,10 @@ export function ReportAreaChart() {}return (- <AspectContainer>- <Chart data={res.data} />- </AspectContainer>+ <SeriesWithTable+ chart={(series) => <Chart data={res.data} series={series} />}+ data={res.data}+ />);}diff --git a/apps/start/src/components/report-chart/aspect-container.tsx b/apps/start/src/components/report-chart/aspect-container.tsxindex 3cac791e0..d9b73c3a1 100644--- a/apps/start/src/components/report-chart/aspect-container.tsx+++ b/apps/start/src/components/report-chart/aspect-container.tsx@@ -8,21 +8,29 @@ interface AspectContainerProps {}export function AspectContainer({ children, className }: AspectContainerProps) {- const { options } = useReportChartContext();+ const { options, layout } = useReportChartContext();+ if (layout === 'fill') {+ return (+ <div className={cn('h-full min-h-0 w-full', className)}>{children}</div>+ );+ }const minHeight = options?.minHeight ?? 100;const maxHeight = options?.maxHeight ?? 300;const aspectRatio = options?.aspectRatio ?? DEFAULT_ASPECT_RATIO;+ // Safari does not resolve a child's `height: 100%` against a height that+ // comes from `aspect-ratio`, so the chart grew past the box and over the+ // table below. An absolute layer gives children a definite height.return (<div- className={cn('w-full', className)}+ className={cn('relative w-full', className)}style={{aspectRatio: 1 / aspectRatio,maxHeight,minHeight,}}>- {children}+ <div className="absolute inset-0">{children}</div></div>);}diff --git a/apps/start/src/components/report-chart/bar/bar-labels.tsx b/apps/start/src/components/report-chart/bar/bar-labels.tsxnew file mode 100644index 000000000..7036d8faf--- /dev/null+++ b/apps/start/src/components/report-chart/bar/bar-labels.tsx@@ -0,0 +1,102 @@+import { NOT_SET_VALUE } from '@openpanel/core/modules/report/report.constants';+import { useEffect, useState } from 'react';+import { createPortal } from 'react-dom';+import { SerieIcon } from '../common/serie-icon';+import { useReportChartContext } from '../context';+import type { BarRow } from './chart';+import { useChart } from '@/components/charts/chart-context';+import { DeltaChip } from '@/components/delta-chip';+import { useNumber } from '@/hooks/use-numer-formatter';+import { cn } from '@/utils/cn';++/**+ * Names (with icons) left of each bar and the value right of it. Drawn in+ * HTML over the chart, like bklit's own axes, because the bar y-axis only+ * renders short plain-text labels.+ */+export function BarLabels({+ rowsById,+ comparesPrevious,+}: {+ rowsById: Map<string, BarRow>;+ comparesPrevious: boolean;+}) {+ const { containerRef, barScale, margin, data, hoveredBarIndex } = useChart();+ const number = useNumber();+ const {+ options: { renderSerieName },+ } = useReportChartContext();+ const [mounted, setMounted] = useState(false);+ useEffect(() => {+ setMounted(true);+ }, []);++ const container = containerRef.current;+ if (!(mounted && container && barScale)) {+ return null;+ }+ const bandHeight = barScale.step();+ const bandOffset = (barScale.step() - barScale.bandwidth()) / 2;++ return createPortal(+ <div className="pointer-events-none absolute inset-0">+ {data.map((datum, index) => {+ const row = rowsById.get(String(datum.id));+ if (!row) {+ return null;+ }+ const top = (barScale(row.id) ?? 0) - bandOffset + margin.top;+ const isDimmed = hoveredBarIndex != null && hoveredBarIndex !== index;+ return (+ <div+ className={cn(+ 'absolute inset-x-0 flex items-center transition-opacity',+ isDimmed && 'opacity-50'+ )}+ key={row.id}+ style={{ top, height: bandHeight }}+ >+ <div+ className="flex min-w-0 items-center gap-2 pr-3"+ style={{ width: margin.left }}+ >+ <SerieIcon name={row.labelNames} />+ <span+ className="min-w-0 truncate font-medium text-sm"+ title={row.names.join(' › ')}+ >+ {renderSerieName+ ? renderSerieName(row.labelNames)+ : row.labelNames+ .map((name) => name || NOT_SET_VALUE)+ .join(' › ')}+ </span>+ </div>+ <div+ className="ml-auto flex items-center justify-end gap-1.5 pl-2"+ style={{ width: margin.right }}+ >+ <span className="font-mono font-semibold text-sm">+ {number.short(row.count)}+ </span>+ {comparesPrevious && !row.previous && row.count > 0 && (+ <DeltaChip size="sm">New</DeltaChip>+ )}+ {row.previousDiff?.diff != null && (+ <DeltaChip+ size="sm"+ variant={+ row.previousDiff.state === 'positive' ? 'inc' : 'dec'+ }+ >+ {row.previousDiff.diff.toFixed(0)}%+ </DeltaChip>+ )}+ </div>+ </div>+ );+ })}+ </div>,+ container+ );+}diff --git a/apps/start/src/components/report-chart/bar/chart.tsx b/apps/start/src/components/report-chart/bar/chart.tsxindex e49429ec5..220340718 100644--- a/apps/start/src/components/report-chart/bar/chart.tsx+++ b/apps/start/src/components/report-chart/bar/chart.tsx@@ -1,322 +1,173 @@-import { NOT_SET_VALUE } from '@openpanel/core/modules/report/report.constants';import { round } from '@openpanel/shared';-import { DropdownMenuPortal } from '@radix-ui/react-dropdown-menu';-import { SearchIcon } from 'lucide-react';-import { useMemo, useState } from 'react';+import { useMemo } from 'react';+import { getLabelNames } from '../common/label-names';import { SerieIcon } from '../common/serie-icon';import { SerieName } from '../common/serie-name';import { useReportChartContext } from '../context';-import { DeltaChip } from '@/components/delta-chip';-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu';-import { Input } from '@/components/ui/input';-import {- Select,- SelectContent,- SelectItem,- SelectTrigger,- SelectValue,-} from '@/components/ui/select';-import { useNumber } from '@/hooks/use-numer-formatter';+import { BarLabels } from './bar-labels';+import { Bar } from '@/components/charts/bar';+import { BarChart } from '@/components/charts/bar-chart';+import { OPChartTooltip } from '@/components/charts/op-tooltip';+import { useElementSize } from '@/hooks/use-element-size';import { useVisibleSeries } from '@/hooks/use-visible-series';import type { IChartData } from '@/trpc/client';import { cn } from '@/utils/cn';import { getChartColor } from '@/utils/theme';-type SortOption =- | 'count-desc'- | 'count-asc'- | 'name-asc'- | 'name-desc'- | 'percent-desc'- | 'percent-asc';+const DEFAULT_ROWS = 10;+const ALL_SERIES_LIMIT = 500;+export const ROW_HEIGHT = 36;+const MORE_ROW_HEIGHT = 28;+const BAR_GAP = 0.35;+const LABEL_SHARE = 0.4;+const LABEL_MAX_WIDTH = 260;+const VALUE_WIDTH = 96;+const BAR_COLOR = getChartColor(0);+const PREVIOUS_BAR_COLOR = `color-mix(in oklch, ${BAR_COLOR} 30%, transparent)`;++// The index signature lets rows go straight into bklit's chart data.+export interface BarRow {+ [key: string]: unknown;+ id: string;+ names: string[];+ /** `names` without the event name when every row shares it. */+ labelNames: string[];+ count: number;+ previous?: number;+ previousDiff?: { diff: number | null; state: string };+ share: number;+}interface Props {data: IChartData;}export function Chart({ data }: Props) {- const [isOpen, setOpen] = useState<string | null>(null);- const [searchQuery, setSearchQuery] = useState('');- const [sortBy, setSortBy] = useState<SortOption>('count-desc');const {isEditMode,+ layout,report: { metric, limit, previous },- options: { onClick, dropdownMenuContent },} = useReportChartContext();- const number = useNumber();-- // Use useVisibleSeries to add index property for colors- const { series: allSeriesWithIndex } = useVisibleSeries(data, { limit: 500 });-- const totalSum = data.metrics.sum || 1;-- // Calculate original ranks (based on count descending - default sort)- const seriesWithOriginalRank = useMemo(() => {- const sortedByCount = [...allSeriesWithIndex].sort(- (a, b) => b.metrics.sum - a.metrics.sum- );- const rankMap = new Map<string, number>();- sortedByCount.forEach((serie, idx) => {- rankMap.set(serie.id, idx + 1);- });- return allSeriesWithIndex.map((serie) => ({- ...serie,- originalRank: rankMap.get(serie.id) ?? 0,- }));- }, [allSeriesWithIndex]);-- // Filter and sort series- const series = useMemo(() => {- let filtered = seriesWithOriginalRank;-- // Filter by search query- if (searchQuery.trim()) {- const query = searchQuery.toLowerCase();- filtered = filtered.filter((serie) =>- serie.names.some((name) => name.toLowerCase().includes(query))+ const isTile = layout === 'fill';+ const [sizeRef, { width, height }] = useElementSize();+ const { series } = useVisibleSeries(data, { limit: ALL_SERIES_LIMIT });+ const total = data.metrics.sum || 1;++ const rows = useMemo(() => {+ const labelNames = getLabelNames(series);+ return [...series]+ .sort((a, b) => b.metrics.sum - a.metrics.sum)+ .map(+ (serie): BarRow => ({+ id: serie.id,+ names: serie.names,+ labelNames: labelNames(serie.names),+ count: serie.metrics.sum,+ previous: previous+ ? serie.metrics.previous?.[metric]?.value+ : undefined,+ previousDiff: previous ? serie.metrics.previous?.[metric] : undefined,+ share: round((serie.metrics.sum / total) * 100, 1),+ }));+ }, [series, previous, metric, total]);++ const rowLimit = (() => {+ // A tile shows the whole rows that fit its height; a saved limit still caps it.+ if (isTile) {+ const fitting = Math.floor(height / ROW_HEIGHT);+ const fittingWithMore = Math.floor(+ (height - MORE_ROW_HEIGHT) / ROW_HEIGHT+ );+ const fits = Math.min(rows.length, limit ?? Number.POSITIVE_INFINITY);+ return fits <= fitting ? fits : Math.max(1, fittingWithMore);}-- // Sort- const sorted = [...filtered].sort((a, b) => {- switch (sortBy) {- case 'count-desc':- return b.metrics.sum - a.metrics.sum;- case 'count-asc':- return a.metrics.sum - b.metrics.sum;- case 'name-asc':- return a.names.join(' > ').localeCompare(b.names.join(' > '));- case 'name-desc':- return b.names.join(' > ').localeCompare(a.names.join(' > '));- case 'percent-desc':- return b.metrics.sum / totalSum - a.metrics.sum / totalSum;- case 'percent-asc':- return a.metrics.sum / totalSum - b.metrics.sum / totalSum;- default:- return 0;- }- });-- // Apply limit if not in edit mode- return isEditMode ? sorted : sorted.slice(0, limit || 10);- }, [- seriesWithOriginalRank,- searchQuery,- sortBy,- totalSum,- isEditMode,- limit,- ]);+ return limit || DEFAULT_ROWS;+ })();+ const visibleRows = rows.slice(0, rowLimit);+ const hiddenCount = rows.length - visibleRows.length;return (- <div className={cn('w-full', isEditMode && 'card')}>- {isEditMode && (- <div className="flex items-center gap-3 border-def-200 border-b p-4 dark:border-def-800">- <div className="relative flex-1">- <SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />- <Input- className="pl-9"- onChange={(e) => setSearchQuery(e.target.value)}- placeholder="Filter by name"- size="sm"- type="text"- value={searchQuery}- />- </div>- <Select- onValueChange={(value) => setSortBy(value as SortOption)}- value={sortBy}+ <div className={cn('col w-full', isEditMode && 'card', isTile && 'h-full')}>+ <div+ className={cn(+ 'w-full',+ isTile && 'min-h-0 flex-1',+ isEditMode && 'p-4'+ )}+ data-report-chart="bar"+ ref={sizeRef}+ >+ {width > 0 && visibleRows.length > 0 && (+ <BarRows previous={previous} rows={visibleRows} width={width} />+ )}+ {hiddenCount > 0 && (+ <div+ className="flex items-center px-1 text-muted-foreground text-sm"+ style={{ height: MORE_ROW_HEIGHT }}>- <SelectTrigger className="w-[180px]" size="sm">- <SelectValue />- </SelectTrigger>- <SelectContent>- <SelectItem value="count-desc">Count (High → Low)</SelectItem>- <SelectItem value="count-asc">Count (Low → High)</SelectItem>- <SelectItem value="name-asc">Name (A → Z)</SelectItem>- <SelectItem value="name-desc">Name (Z → A)</SelectItem>- <SelectItem value="percent-desc">- Percentage (High → Low)- </SelectItem>- <SelectItem value="percent-asc">- Percentage (Low → High)- </SelectItem>- </SelectContent>- </Select>- </div>- )}- <div className="overflow-hidden">- <div className="divide-y divide-def-200 dark:divide-def-800">- {series.map((serie, idx) => {- const isClickable =- !serie.names.includes(NOT_SET_VALUE) && !!onClick;- const isDropDownEnabled =- !serie.names.includes(NOT_SET_VALUE) &&- (dropdownMenuContent?.(serie) || []).length > 0;-- const color = getChartColor(serie.index);- const percentOfTotal = round(- (serie.metrics.sum / totalSum) * 100,- 1- );-- return (- <div- className={cn(- 'group relative overflow-hidden px-4 py-3 transition-colors',- isClickable && 'cursor-pointer'- )}- key={serie.id}- onClick={() => {- if (isClickable && !isDropDownEnabled) {- onClick?.(serie);- }- }}- onKeyDown={(e) => {- if (!isClickable || isDropDownEnabled) {- return;- }- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- onClick?.(serie);- }- }}- role={isClickable ? 'button' : undefined}- tabIndex={isClickable ? 0 : undefined}- >- <div- className="pointer-events-none absolute -top-10 -left-10 h-40 w-96 rounded-full opacity-0 blur-3xl transition-opacity duration-500 group-hover:opacity-10"- style={{- background: `radial-gradient(circle, ${color} 0%, transparent 70%)`,- }}- />-- <div className="relative z-10 flex flex-col gap-2">- <div className="flex items-center justify-between gap-4">- <div className="flex min-w-0 items-center gap-3">- <div- className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border bg-def-50 dark:border-def-800 dark:bg-def-900"- style={{ borderColor: `${color}22` }}- >- <SerieIcon name={serie.names[0]} />- </div>-- <div className="min-w-0">- <div className="mb-1 flex items-center gap-2">- <div- className="h-2 w-2 rounded-full"- style={{ backgroundColor: color }}- />- <span className="font-semibold text-[10px] text-muted-foreground uppercase tracking-widest">- Rank {serie.originalRank}- </span>- </div>-- <DropdownMenu- onOpenChange={() =>- setOpen((p) => (p === serie.id ? null : serie.id))- }- open={isOpen === serie.id}- >- <DropdownMenuTrigger- asChild- disabled={!isDropDownEnabled}- {...(isDropDownEnabled- ? {- onPointerDown: (e) => e.preventDefault(),- onClick: (e) => {- e.stopPropagation();- setOpen(serie.id);- },- }- : {})}- >- <div- className={cn(- 'min-w-0',- isDropDownEnabled && 'cursor-pointer'- )}- {...(isClickable && !isDropDownEnabled- ? {- onClick: (e) => {- e.stopPropagation();- onClick?.(serie);- },- }- : {})}- >- <SerieName- className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap font-semibold text-sm tracking-tight"- name={serie.names}- />- </div>- </DropdownMenuTrigger>- <DropdownMenuPortal>- <DropdownMenuContent>- {dropdownMenuContent?.(serie).map((item) => (- <DropdownMenuItem- key={item.title}- onClick={(e) => {- e.stopPropagation();- item.onClick();- }}- >- {item.icon && (- <item.icon className="mr-2" size={16} />- )}- {item.title}- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenuPortal>- </DropdownMenu>- </div>- </div>+ +{hiddenCount} more+ </div>+ )}+ </div>+ </div>+ );+}- <div className="flex shrink-0 flex-col items-end gap-1">- <div className="flex items-center gap-2">- <div className="font-mono font-semibold text-base tracking-tight">- {number.format(serie.metrics.sum)}- </div>- {previous && serie.metrics.previous?.[metric] && (- <DeltaChip- size="sm"- variant={- serie.metrics.previous[metric].state ===- 'positive'- ? 'inc'- : 'dec'- }- >- {serie.metrics.previous[metric].diff?.toFixed(1)}%- </DeltaChip>- )}- </div>- </div>- </div>+function BarRows({+ rows,+ width,+ previous,+}: {+ rows: BarRow[];+ width: number;+ previous: boolean | undefined;+}) {+ const labelWidth = Math.min(width * LABEL_SHARE, LABEL_MAX_WIDTH);+ // An empty previous bar would still take half of every row.+ const hasPrevious = previous && rows.some((row) => (row.previous ?? 0) > 0);+ const rowsById = useMemo(+ () => new Map(rows.map((row) => [row.id, row])),+ [rows]+ );- <div className="flex items-center">- <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-def-100 dark:bg-def-900">- <div- className="h-full rounded-full transition-[width] duration-700 ease-out"- style={{- width: `${percentOfTotal}%`,- background: `linear-gradient(90deg, ${color}aa, ${color})`,- }}- />- </div>- </div>- </div>- </div>- );- })}- </div>- </div>+ return (+ <div style={{ height: rows.length * ROW_HEIGHT }}>+ <BarChart+ animationDuration={0}+ aspectRatio="auto"+ barGap={BAR_GAP}+ className="h-full"+ data={rows}+ margin={{ top: 0, right: VALUE_WIDTH, bottom: 0, left: labelWidth }}+ orientation="horizontal"+ xDataKey="id"+ >+ <Bar animate={false} dataKey="count" fill={BAR_COLOR} lineCap={4} />+ {hasPrevious && (+ <Bar+ animate={false}+ dataKey="previous"+ fill={PREVIOUS_BAR_COLOR}+ lineCap={4}+ />+ )}+ <BarLabels comparesPrevious={Boolean(previous)} rowsById={rowsById} />+ <OPChartTooltip<BarRow>+ datePill={false}+ rows={(row) => [+ {+ color: BAR_COLOR,+ icon: <SerieIcon name={row.labelNames} />,+ label: <SerieName name={row.labelNames} />,+ value: row.count,+ previous: row.previous,+ percentage: row.share,+ },+ ]}+ title={() => null}+ />+ </BarChart></div>);}diff --git a/apps/start/src/components/report-chart/bar/index.tsx b/apps/start/src/components/report-chart/bar/index.tsxindex 345f3a3fa..5aabf3558 100644--- a/apps/start/src/components/report-chart/bar/index.tsx+++ b/apps/start/src/components/report-chart/bar/index.tsx@@ -1,18 +1,19 @@import { keepPreviousData, useQuery } from '@tanstack/react-query';import { AspectContainer } from '../aspect-container';+import { ChartWithTable, TableCard } from '../common/chart-with-table';import { ReportChartEmpty } from '../common/empty';import { ReportChartError } from '../common/error';+import { RankedTable } from '../common/ranked-table';import { useChartInput, useReportChartContext } from '../context';-import { Chart } from './chart';+import { Chart, ROW_HEIGHT } from './chart';import { useTRPC } from '@/integrations/trpc/react';+import type { IChartData } from '@/trpc/client';import { cn } from '@/utils/cn';-// Fixed, not random. The server and the browser each rendered their own-// widths, so every skeleton row was an attribute mismatch and React threw the-// SSR tree away. The exact values do not matter; only that-// both renders agree.-const SKELETON_NAME_WIDTHS = [186, 134, 158, 112, 170, 126, 194, 148, 120, 176];+// Fixed, not random: the server and the browser must render the same widths.+const SKELETON_NAME_WIDTHS = [62, 48, 56, 40, 60, 44, 66, 52, 38, 58];const SKELETON_BAR_WIDTHS = [72, 48, 63, 35, 57, 41, 78, 52, 29, 66];+const SKELETON_ROWS = 10;export function ReportBarChart() {const { isLazyLoading, shareId } = useReportChartContext();@@ -47,60 +48,54 @@ export function ReportBarChart() {return <Empty />;}- return <Chart data={res.data} />;+ return <BarWithTable data={res.data} />;+}++function BarWithTable({ data }: { data: IChartData }) {+ return (+ <ChartWithTable+ chart={<Chart data={data} />}+ sizesItself+ tables={+ <TableCard>+ <RankedTable data={data} />+ </TableCard>+ }+ />+ );}function Loading() {- const { isEditMode } = useReportChartContext();+ const { isEditMode, layout } = useReportChartContext();return (- <div className={cn('w-full', isEditMode && 'card')}>- <div className="overflow-hidden">- <div className="divide-y divide-def-200 dark:divide-def-800">- {Array.from({ length: 10 }).map((_, index) => (+ <div+ className={cn(+ 'col w-full overflow-hidden',+ isEditMode && 'card p-4',+ layout === 'fill' && 'h-full'+ )}+ >+ {Array.from({ length: SKELETON_ROWS }, (_, index) => (+ <div+ className="flex shrink-0 animate-pulse items-center gap-3"+ key={SKELETON_BAR_WIDTHS[index]}+ style={{ height: ROW_HEIGHT }}+ >+ <div className="flex w-2/5 items-center gap-2">+ <div className="size-4 rounded-full bg-def-200 dark:bg-def-700" /><div- className="relative animate-pulse px-4 py-3"- key={index as number}- >- <div className="relative z-10 flex flex-col gap-2">- <div className="flex items-center justify-between gap-4">- <div className="flex min-w-0 items-center gap-3">- <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border bg-def-100 dark:border-def-800 dark:bg-def-900" />-- <div className="min-w-0">- <div className="mb-1 flex items-center gap-2">- <div className="h-2 w-2 rounded-full bg-def-200 dark:bg-def-700" />- <div className="h-2 w-12 rounded bg-def-200 dark:bg-def-700" />- </div>-- <div- className="h-4 rounded bg-def-200 dark:bg-def-700"- style={{- width: `${SKELETON_NAME_WIDTHS[index % SKELETON_NAME_WIDTHS.length]}px`,- }}- />- </div>- </div>-- <div className="flex shrink-0 flex-col items-end gap-1">- <div className="h-5 w-16 rounded bg-def-200 dark:bg-def-700" />- </div>- </div>-- <div className="flex items-center">- <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-def-100 dark:bg-def-900">- <div- className="h-full rounded-full bg-def-200 dark:bg-def-700"- style={{- width: `${SKELETON_BAR_WIDTHS[index % SKELETON_BAR_WIDTHS.length]}%`,- }}- />- </div>- </div>- </div>- </div>- ))}+ className="h-3 rounded bg-def-200 dark:bg-def-700"+ style={{ width: `${SKELETON_NAME_WIDTHS[index]}%` }}+ />+ </div>+ <div className="flex-1">+ <div+ className="h-4 rounded bg-def-100 dark:bg-def-800"+ style={{ width: `${SKELETON_BAR_WIDTHS[index]}%` }}+ />+ </div></div>- </div>+ ))}</div>);}diff --git a/apps/start/src/components/report-chart/common/axis.tsx b/apps/start/src/components/report-chart/common/axis.tsxdeleted file mode 100644index eca3763c0..000000000--- a/apps/start/src/components/report-chart/common/axis.tsx+++ /dev/null@@ -1,96 +0,0 @@-import type { IInterval } from '@openpanel/core/modules/report/report.constants';-import { isNil } from 'ramda';-import { useRef, useState } from 'react';-import type { AxisDomain } from 'recharts/types/util/types';-import { useDebounceFn } from '@/hooks/use-debounce-fn';-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';-import { useNumber } from '@/hooks/use-numer-formatter';-export const AXIS_FONT_PROPS = {- fontSize: 8,- className: 'font-mono',-};--export function getYAxisWidth(value: string | undefined | null) {- const charLength = AXIS_FONT_PROPS.fontSize * 0.6;-- if (isNil(value) || value.length === 0) {- return charLength * 2;- }-- return charLength * value.length + charLength;-}--export const useYAxisProps = (options?: {- hide?: boolean;- tickFormatter?: (value: number) => string;- width?: number;-}) => {- const [width, setWidth] = useState(options?.width || 24);- const setWidthDebounced = useDebounceFn(setWidth, 100);- const number = useNumber();- const ref = useRef<number[]>([]);-- return {- ...AXIS_FONT_PROPS,- width: options?.hide ? 0 : width,- axisLine: false,- tickLine: false,- allowDecimals: false,- tickFormatter: (value: number) => {- const tick = options?.tickFormatter- ? options.tickFormatter(value)- : number.short(value);- if (!options?.width) {- const newWidth = getYAxisWidth(tick);- ref.current.push(newWidth);- setWidthDebounced(Math.max(...ref.current));- }- return tick;- },- };-};--export const X_AXIS_STYLE_PROPS = {- height: 14,- tickSize: 10,- axisLine: false,- tickLine: false,- ...AXIS_FONT_PROPS,-};--export const useXAxisProps = (- {- interval = 'auto',- hide,- }: {- interval?: IInterval | 'auto';- hide?: boolean;- } = {- hide: false,- interval: 'auto',- }-) => {- const formatDate = useFormatDateInterval({- interval: interval === 'auto' ? 'day' : interval,- short: true,- });-- return {- ...X_AXIS_STYLE_PROPS,- height: hide ? 0 : X_AXIS_STYLE_PROPS.height,- dataKey: 'timestamp',- scale: 'utc',- domain: ['dataMin', 'dataMax'] as AxisDomain,- tickFormatter:- interval === 'auto'- ? undefined- : (m: string) => {- if (['dataMin', 'dataMax'].includes(m)) {- return m;- }-- return formatDate(new Date(m));- },- type: 'number' as const,- } as const;-};diff --git a/apps/start/src/components/report-chart/common/chart-click-menu.tsx b/apps/start/src/components/report-chart/common/chart-click-menu.tsxindex 6ee59b58c..5efea1aee 100644--- a/apps/start/src/components/report-chart/common/chart-click-menu.tsx+++ b/apps/start/src/components/report-chart/common/chart-click-menu.tsx@@ -28,6 +28,8 @@ interface ChartClickMenuProps {export interface ChartClickMenuHandle {setPosition: (position: { x: number; y: number } | null) => void;+ /** Opens the menu for `data` at a viewport point, for charts that are not Recharts. */+ openAt: (data: unknown, clientX: number, clientY: number) => void;getContainerElement: () => HTMLDivElement | null;}@@ -124,6 +126,16 @@ export const ChartClickMenu = forwardRef<setPosition: (position: { x: number; y: number } | null) => {setClickPosition(position);},+ openAt: (data, clientX, clientY) => {+ const container = containerRef.current;+ if (!(data && container)) {+ return;+ }+ const rect = container.getBoundingClientRect();+ setClickedData(data);+ setClickEvent({});+ setClickPosition({ x: clientX - rect.left, y: clientY - rect.top });+ },getContainerElement: () => containerRef.current,}),[]diff --git a/apps/start/src/components/report-chart/common/chart-with-table.tsx b/apps/start/src/components/report-chart/common/chart-with-table.tsxnew file mode 100644index 000000000..87ef0f4b6--- /dev/null+++ b/apps/start/src/components/report-chart/common/chart-with-table.tsx@@ -0,0 +1,59 @@+import type { ReactNode } from 'react';+import { AspectContainer } from '../aspect-container';+import { useReportChartContext } from '../context';++/**+ * Where a report's pieces go: a dashboard tile, or any embed with `hideTable`,+ * is the chart alone; the editor and the share page get the summary, the+ * chart, and the tables under it.+ */+export function ChartWithTable({+ summary,+ chart,+ tables,+ sizesItself = false,+}: {+ summary?: ReactNode;+ chart: ReactNode;+ tables: ReactNode;+ /** The chart measures its own height (bar, sankey) instead of the aspect box. */+ sizesItself?: boolean;+}) {+ const {+ layout,+ options: { hideTable },+ } = useReportChartContext();+ const sizedChart = sizesItself ? (+ chart+ ) : (+ <AspectContainer>{chart}</AspectContainer>+ );++ if (layout === 'fill' || hideTable) {+ return sizedChart;+ }++ return (+ <div className="col gap-4">+ {summary}+ {sizedChart}+ {tables}+ </div>+ );+}++/** A table's frame under the chart. */+export function TableCard({+ title,+ children,+}: {+ title?: ReactNode;+ children: ReactNode;+}) {+ return (+ <div className="card overflow-hidden">+ {title && <div className="border-b px-4 py-3 font-medium">{title}</div>}+ {children}+ </div>+ );+}diff --git a/apps/start/src/components/report-chart/common/curve.ts b/apps/start/src/components/report-chart/common/curve.tsnew file mode 100644index 000000000..2d29a08dd--- /dev/null+++ b/apps/start/src/components/report-chart/common/curve.ts@@ -0,0 +1,40 @@+import type { lineTypes } from '@openpanel/core/modules/report/report.constants';+import {+ type CurveFactory,+ curveBasis,+ curveBasisClosed,+ curveBasisOpen,+ curveBumpX,+ curveBumpY,+ curveLinear,+ curveLinearClosed,+ curveMonotoneX,+ curveMonotoneY,+ curveNatural,+ curveStep,+ curveStepAfter,+ curveStepBefore,+} from 'd3-shape';++// Recharts' names, which saved reports store: `monotone` and `bump` are the X variants.+const CURVES = {+ monotone: curveMonotoneX,+ monotoneX: curveMonotoneX,+ monotoneY: curveMonotoneY,+ linear: curveLinear,+ natural: curveNatural,+ basis: curveBasis,+ step: curveStep,+ stepBefore: curveStepBefore,+ stepAfter: curveStepAfter,+ basisClosed: curveBasisClosed,+ basisOpen: curveBasisOpen,+ bumpX: curveBumpX,+ bumpY: curveBumpY,+ bump: curveBumpX,+ linearClosed: curveLinearClosed,+} satisfies Record<keyof typeof lineTypes, CurveFactory>;++export function getCurve(lineType: keyof typeof lineTypes | undefined) {+ return CURVES[lineType ?? 'monotone'];+}diff --git a/apps/start/src/components/report-chart/common/label-names.ts b/apps/start/src/components/report-chart/common/label-names.tsnew file mode 100644index 000000000..47ed1fd3d--- /dev/null+++ b/apps/start/src/components/report-chart/common/label-names.ts@@ -0,0 +1,10 @@+/**+ * The names to show for a series: without the event name when every series+ * shares it, so a breakdown of one event lists only the breakdown values.+ */+export function getLabelNames(allSeries: { names: string[] }[]) {+ const isSharedEvent =+ new Set(allSeries.map((serie) => serie.names[0])).size === 1;+ return (names: string[]) =>+ isSharedEvent && names.length > 1 ? names.slice(1) : names;+}diff --git a/apps/start/src/components/report-chart/common/linear-gradient.tsx b/apps/start/src/components/report-chart/common/linear-gradient.tsxdeleted file mode 100644index e8bb74aec..000000000--- a/apps/start/src/components/report-chart/common/linear-gradient.tsx+++ /dev/null@@ -1,69 +0,0 @@-interface GradientProps {- percentage: number;- baseColor: string;- id: string;-}--export const SolidToDashedGradient: React.FC<GradientProps> = ({- percentage,- baseColor,- id,-}) => {- const stops = generateSolidToDashedLinearGradient(percentage, baseColor);-- return (- <linearGradient id={id} x1="0" x2="1" y1="0" y2="0">- {stops.map((stop, index) => (- <stop- key={index as any}- offset={stop.offset}- stopColor={stop.color}- stopOpacity={stop.opacity}- />- ))}- </linearGradient>- );-};--// Helper function moved to the same file-const generateSolidToDashedLinearGradient = (- percentage: number,- baseColor: string-) => {- // Start with solid baseColor up to percentage- const stops = [- { offset: '0%', color: baseColor, opacity: 1 },- { offset: `${percentage}%`, color: baseColor, opacity: 1 },- ];-- // Calculate the remaining space for dashes- const remainingSpace = 100 - percentage;- const dashWidth = remainingSpace / 20; // 10 dashes = 20 segments (dash + gap)-- // Generate 10 dashes- for (let i = 0; i < 10; i++) {- const startOffset = percentage + i * 2 * dashWidth;-- // Add dash and gap with sharp transitions- stops.push(- // Start of dash- { offset: `${startOffset}%`, color: baseColor, opacity: 1 },- // End of dash- { offset: `${startOffset + dashWidth}%`, color: baseColor, opacity: 1 },- // Start of gap (immediate transition)- {- offset: `${startOffset + dashWidth}%`,- color: 'transparent',- opacity: 0,- },- // End of gap- {- offset: `${startOffset + 2 * dashWidth}%`,- color: 'transparent',- opacity: 0,- }- );- }-- return stops;-};diff --git a/apps/start/src/components/report-chart/common/point-click.tsx b/apps/start/src/components/report-chart/common/point-click.tsxnew file mode 100644index 000000000..56edcc2f0--- /dev/null+++ b/apps/start/src/components/report-chart/common/point-click.tsx@@ -0,0 +1,44 @@+import { useEffect, useRef } from 'react';+import {+ useChartHover,+ useChartStable,+} from '@/components/charts/chart-context';++/**+ * Calls `onClick` with the data point under the pointer when a bklit chart is+ * clicked. Remembers the last hovered point because the chart clears its+ * tooltip on mousedown, before the click lands.+ */+export function PointClick<T extends Record<string, unknown>>({+ onClick,+}: {+ onClick: (point: T, event: MouseEvent) => void;+}) {+ const { containerRef } = useChartStable();+ const { tooltipData } = useChartHover();+ const pointRef = useRef<T | null>(null);+ const onClickRef = useRef(onClick);+ onClickRef.current = onClick;++ useEffect(() => {+ if (tooltipData) {+ pointRef.current = tooltipData.point as T;+ }+ }, [tooltipData]);++ useEffect(() => {+ const container = containerRef.current;+ if (!container) {+ return;+ }+ const handleClick = (event: MouseEvent) => {+ if (pointRef.current) {+ onClickRef.current(pointRef.current, event);+ }+ };+ container.addEventListener('click', handleClick);+ return () => container.removeEventListener('click', handleClick);+ }, [containerRef]);++ return null;+}diff --git a/apps/start/src/components/report-chart/common/ranked-table.tsx b/apps/start/src/components/report-chart/common/ranked-table.tsxnew file mode 100644index 000000000..cc21df978--- /dev/null+++ b/apps/start/src/components/report-chart/common/ranked-table.tsx@@ -0,0 +1,146 @@+import { round } from '@openpanel/shared';+import { useCallback, useMemo } from 'react';+import { useReportChartContext } from '../context';+import { getLabelNames } from './label-names';+import { PreviousDiffIndicatorPure } from './previous-diff-indicator';+import { SerieIcon } from './serie-icon';+import { SerieName } from './serie-name';+import {+ type ReportColumn,+ ReportDataTable,+ type ReportRowIdentity,+} from '@/components/report-table/report-data-table';+import { useNumber } from '@/hooks/use-numer-formatter';+import type { IChartData } from '@/trpc/client';+import { getChartColor } from '@/utils/theme';++interface RankedRow {+ id: string;+ names: string[];+ labelNames: string[];+ color: string;+ value: number;+ share: number;+ previous: number | undefined;+ change: { diff: number | null; state: string } | undefined;+}++interface Props {+ data: IChartData;+ visibleIds?: ReadonlySet<string>;+ /** Absent on read-only pages, which hides the checkboxes. */+ onToggle?: (id: string) => void;+ onUnselectAll?: () => void;+ onReset?: () => void;+}++/** One row per series ranked by its value: the table behind bar and pie reports. */+export function RankedTable({+ data,+ visibleIds,+ onToggle,+ onUnselectAll,+ onReset,+}: Props) {+ const {+ report: { metric, unit, previous: comparesPrevious, name },+ } = useReportChartContext();+ const number = useNumber();+ const formatValue = useCallback(+ (value: number) => number.formatWithUnit(value, unit),+ [number, unit]+ );++ const rows = useMemo(() => {+ const total =+ data.series.reduce(+ (sum, serie) => sum + (serie.metrics[metric] ?? 0),+ 0+ ) || 1;+ const labelNames = getLabelNames(data.series);+ return data.series.map((serie, index): RankedRow => {+ const value = serie.metrics[metric] ?? 0;+ const previous = comparesPrevious+ ? serie.metrics.previous?.[metric]+ : undefined;+ return {+ id: serie.id,+ names: serie.names,+ labelNames: labelNames(serie.names),+ color: getChartColor(index),+ value,+ share: round((value / total) * 100, 1),+ previous: comparesPrevious ? (previous?.value ?? 0) : undefined,+ change: previous,+ };+ });+ }, [data.series, metric, comparesPrevious]);++ const identity = useMemo<ReportRowIdentity<RankedRow>>(+ () => ({+ header: 'Series',+ render: (row) => (+ <span className="flex items-center gap-1.5">+ <SerieIcon name={row.labelNames} />+ <SerieName name={row.labelNames} />+ </span>+ ),+ searchText: (row) => row.names.join(' › '),+ color: (row) => row.color,+ }),+ []+ );++ const columns = useMemo<ReportColumn<RankedRow>[]>(+ () => [+ {+ id: 'value',+ header: metric === 'sum' ? 'Value' : metric,+ value: (row) => row.value,+ render: (row) => formatValue(row.value),+ decorate: 'bar',+ width: 160,+ },+ {+ id: 'share',+ header: 'Share',+ value: (row) => row.share,+ format: 'percent',+ },+ ...(comparesPrevious+ ? [+ {+ id: 'previous',+ header: 'Previous',+ value: (row: RankedRow) => row.previous,+ render: (row: RankedRow) => formatValue(row.previous ?? 0),+ },+ {+ id: 'change',+ header: 'Change',+ value: (row: RankedRow) => row.change?.diff ?? null,+ render: (row: RankedRow) =>+ row.change ? (+ <PreviousDiffIndicatorPure {...row.change} size="xs" />+ ) : null,+ },+ ]+ : []),+ ],+ [metric, comparesPrevious, formatValue]+ );++ return (+ <ReportDataTable+ columns={columns}+ csvFilename={name || 'report'}+ getRowId={(row) => row.id}+ identity={identity}+ onReset={onReset}+ onToggleRow={onToggle}+ onUnselectAll={onUnselectAll}+ rows={rows}+ selectedIds={visibleIds}+ />+ );+}diff --git a/apps/start/src/components/report-chart/common/report-chart-tooltip.tsx b/apps/start/src/components/report-chart/common/report-chart-tooltip.tsxdeleted file mode 100644index ed1b21a4c..000000000--- a/apps/start/src/components/report-chart/common/report-chart-tooltip.tsx+++ /dev/null@@ -1,147 +0,0 @@-import type { IInterval } from '@openpanel/core/modules/report/report.constants';-import {- format,- isSameDay,- isSameHour,- isSameMinute,- isSameMonth,- isSameWeek,-} from 'date-fns';-import React from 'react';-import { useReportChartContext } from '../context';-import { PreviousDiffIndicator } from './previous-diff-indicator';-import { SerieIcon } from './serie-icon';-import { SerieName } from './serie-name';-import {- ChartTooltipHeader,- ChartTooltipItem,- createChartTooltip,-} from '@/components/charts/chart-tooltip';-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';-import { useNumber } from '@/hooks/use-numer-formatter';-import type { IRechartPayloadItem } from '@/hooks/use-rechart-data-model';-import type { RouterOutputs } from '@/trpc/client';--const getMatchingReferences = (- interval: IInterval,- references: RouterOutputs['reference']['getChartReferences'],- date: Date-) => {- return references.filter((reference) => {- if (interval === 'minute') {- return isSameMinute(reference.date, date);- }- if (interval === 'hour') {- return isSameHour(reference.date, date);- }- if (interval === 'day') {- return isSameDay(reference.date, date);- }- if (interval === 'week') {- return isSameWeek(reference.date, date);- }- if (interval === 'month') {- return isSameMonth(reference.date, date);- }- return false;- });-};--type Context = {- references?: RouterOutputs['reference']['getChartReferences'];-};-type Data = {- date: string;- timestamp: number;- [key: `${string}:count`]: number;- [key: `${string}:payload`]: IRechartPayloadItem;-};-export const ReportChartTooltip = createChartTooltip<Data, Context>(- ({ context: { references }, data }) => {- const {- report: { interval, unit },- } = useReportChartContext();- const formatDate = useFormatDateInterval({- interval,- short: false,- });- const number = useNumber();-- if (!data || data.length === 0) {- return null;- }-- const firstItem = data[0];- const matchingReferences = getMatchingReferences(- interval,- references ?? [],- new Date(firstItem.date)- );-- // Get all payload items from the first data point- const payloadItems = Object.keys(firstItem)- .filter((key) => key.endsWith(':payload'))- .map(- (key) => firstItem[key as keyof typeof firstItem] as IRechartPayloadItem- )- .filter((item) => item && typeof item === 'object' && 'id' in item);-- // Sort by count- const sorted = payloadItems.sort((a, b) => (b.count || 0) - (a.count || 0));- const limit = 3;- const visible = sorted.slice(0, limit);- const hidden = sorted.slice(limit);-- return (- <>- {visible.map((item, index) => (- <React.Fragment key={item.id}>- {index === 0 && item.date && (- <ChartTooltipHeader>- <div>{formatDate(new Date(item.date))}</div>- </ChartTooltipHeader>- )}- <ChartTooltipItem color={item.color}>- <div className="flex items-center gap-1">- <SerieIcon name={item.names} />- <SerieName name={item.names} />- </div>- <div className="flex justify-between gap-8 font-medium font-mono">- <div className="row gap-1">- {number.formatWithUnit(item.count, unit)}- {!!item.previous && (- <span className="text-muted-foreground">- ({number.formatWithUnit(item.previous.value, unit)})- </span>- )}- </div>- <PreviousDiffIndicator {...item.previous} />- </div>- </ChartTooltipItem>- </React.Fragment>- ))}- {hidden.length > 0 && (- <div className="text-muted-foreground">- and {hidden.length} more...- </div>- )}- {matchingReferences.length > 0 && (- <>- <hr className="border-border" />- {matchingReferences.map((reference) => (- <div- className="row items-center justify-between"- key={reference.id}- >- <div className="font-medium text-sm">{reference.title}</div>- <div className="shrink-0 font-medium text-muted-foreground text-sm">- {format(reference.date, 'HH:mm')}- </div>- </div>- ))}- </>- )}- </>- );- }-);diff --git a/apps/start/src/components/report-chart/common/report-table-toolbar.tsx b/apps/start/src/components/report-chart/common/report-table-toolbar.tsxdeleted file mode 100644index 311ccedd9..000000000--- a/apps/start/src/components/report-chart/common/report-table-toolbar.tsx+++ /dev/null@@ -1,52 +0,0 @@-import { List, Rows3, Search, X } from 'lucide-react';-import { Button } from '@/components/ui/button';-import { Input } from '@/components/ui/input';--interface ReportTableToolbarProps {- grouped?: boolean;- onToggleGrouped?: () => void;- search: string;- onSearchChange?: (value: string) => void;- onUnselectAll?: () => void;-}--export function ReportTableToolbar({- grouped,- onToggleGrouped,- search,- onSearchChange,- onUnselectAll,-}: ReportTableToolbarProps) {- return (- <div className="col md:row gap-2 border-b p-2 md:items-center md:justify-between">- {onSearchChange && (- <div className="relative w-full flex-1 md:max-w-sm">- <Search className="absolute top-1/2 left-2 size-4 -translate-y-1/2 text-muted-foreground" />- <Input- className="pl-8"- onChange={(e) => onSearchChange(e.target.value)}- placeholder="Search..."- value={search}- />- </div>- )}- <div className="flex items-center gap-2">- {onToggleGrouped && (- <Button- icon={grouped ? Rows3 : List}- onClick={onToggleGrouped}- size="sm"- variant={'outline'}- >- {grouped ? 'Grouped' : 'Flat'}- </Button>- )}- {onUnselectAll && (- <Button icon={X} onClick={onUnselectAll} size="sm" variant="outline">- Unselect All- </Button>- )}- </div>- </div>- );-}diff --git a/apps/start/src/components/report-chart/common/report-table-utils.ts b/apps/start/src/components/report-chart/common/report-table-utils.tsdeleted file mode 100644index bc1c2ab0e..000000000--- a/apps/start/src/components/report-chart/common/report-table-utils.ts+++ /dev/null@@ -1,658 +0,0 @@-import { getPropertyLabel } from '@/translations/properties';-import type { IChartData } from '@/trpc/client';--export type TableRow = {- id: string;- serieId: string; // Serie ID for visibility/color lookup- serieName: string;- breakdownValues: string[];- count: number;- sum: number;- average: number;- min: number;- max: number;- dateValues: Record<string, number>; // date -> count- groupKey?: string;- parentGroupKey?: string;- isSummaryRow?: boolean;-};--export type GroupedTableRow = TableRow & {- // For grouped mode, indicates which breakdown levels should show empty cells- breakdownDisplay: (string | null)[]; // null means show empty cell-};--/** Row type that supports TanStack Table's expanding feature. */-export type ExpandableTableRow = TableRow & {- subRows?: ExpandableTableRow[];- isGroupHeader?: boolean;- groupValue?: string;- groupLevel?: number; // 0-based- breakdownDisplay?: (string | null)[];-};--/** Hierarchical group structure for collapse/expand. */-export type GroupedItem<T> = {- group: string;- items: Array<GroupedItem<T> | T>;- level: number;- groupKey: string; // path-based- parentGroupKey?: string;-};--/** Transform a flat array with hierarchical names into a nested group tree. */-export function groupByNames<T extends { names: string[] }>(- items: T[]-): Array<GroupedItem<T>> {- const rootGroups = new Map<string, GroupedItem<T>>();-- for (const item of items) {- const names = item.names;- if (names.length === 0) {- continue;- }-- // Start with the first level (serie name, level -1)- const firstLevel = names[0]!;- const rootGroupKey = firstLevel;-- if (!rootGroups.has(firstLevel)) {- rootGroups.set(firstLevel, {- group: firstLevel,- items: [],- level: -1, // Serie level- groupKey: rootGroupKey,- });- }-- const rootGroup = rootGroups.get(firstLevel)!;-- // Navigate/create nested groups for remaining levels (breakdowns, level 0+)- let currentGroup = rootGroup;- let parentGroupKey = rootGroupKey;-- for (let i = 1; i < names.length; i++) {- const levelName = names[i]!;- const groupKey = `${parentGroupKey}:${levelName}`;- const level = i - 1; // Breakdown levels start at 0-- const existingGroup = currentGroup.items.find(- (child): child is GroupedItem<T> =>- typeof child === 'object' &&- 'group' in child &&- child.group === levelName &&- 'level' in child &&- child.level === level- );-- if (existingGroup) {- currentGroup = existingGroup;- parentGroupKey = groupKey;- } else {- const newGroup: GroupedItem<T> = {- group: levelName,- items: [],- level,- groupKey,- parentGroupKey,- };- currentGroup.items.push(newGroup);- currentGroup = newGroup;- parentGroupKey = groupKey;- }- }-- currentGroup.items.push(item);- }-- return Array.from(rootGroups.values());-}--/** Flatten a grouped structure back into a flat array of items. */-export function flattenGroupedItems<T>(- groupedItems: Array<GroupedItem<T> | T>-): T[] {- const result: T[] = [];-- for (const item of groupedItems) {- if (item && typeof item === 'object' && 'items' in item) {- result.push(...flattenGroupedItems(item.items));- } else if (item) {- result.push(item);- }- }-- return result;-}--/**- * Find a group by its groupKey in a nested structure- */-export function findGroup<T>(- groups: Array<GroupedItem<T>>,- groupKey: string-): GroupedItem<T> | null {- for (const group of groups) {- if (group.groupKey === groupKey) {- return group;- }-- for (const item of group.items) {- if (item && typeof item === 'object' && 'items' in item) {- const found = findGroup([item], groupKey);- if (found) {- return found;- }- }- }- }-- return null;-}--/**- * Convert hierarchical groups into TanStack Table's flat expandable-row- * format. The serie level and every breakdown level except the last create- * group header rows; the last breakdown level is always individual rows.- */-export function groupsToExpandableRows(- groups: Array<GroupedItem<TableRow>>,- breakdownCount: number-): ExpandableTableRow[] {- const result: ExpandableTableRow[] = [];-- function processGroup(- group: GroupedItem<TableRow>,- parentPath: string[] = []- ): ExpandableTableRow[] {- const currentPath = [...parentPath, group.group];- const subRows: ExpandableTableRow[] = [];-- const nestedGroups: GroupedItem<TableRow>[] = [];- const individualItems: TableRow[] = [];-- for (const item of group.items) {- if (item && typeof item === 'object' && 'items' in item) {- nestedGroups.push(item);- } else if (item) {- individualItems.push(item);- }- }-- for (const nestedGroup of nestedGroups) {- subRows.push(...processGroup(nestedGroup, currentPath));- }-- // Build breakdownDisplay: the first row shows all breakdown values;- // subsequent rows show the parent path's values, then the item's own.- individualItems.forEach((item, index) => {- const breakdownDisplay: (string | null)[] = [];- const breakdownValues = item.breakdownValues;-- for (let i = 0; i < breakdownCount; i++) {- if (index === 0) {- breakdownDisplay.push(breakdownValues[i] ?? null);- } else if (i < currentPath.length) {- breakdownDisplay.push(currentPath[i] ?? null);- } else if (i < breakdownValues.length) {- breakdownDisplay.push(breakdownValues[i] ?? null);- } else {- breakdownDisplay.push(null);- }- }-- subRows.push({- ...item,- breakdownDisplay,- groupKey: group.groupKey,- parentGroupKey: group.parentGroupKey,- isGroupHeader: false,- isSummaryRow: false,- });- });-- // Every level groups into a header row except the last breakdown level- // (level === breakdownCount - 1), which always stays individual rows.- const shouldCreateGroupHeader =- subRows.length > 0 &&- (group.level === -1 || group.level < breakdownCount - 1);-- if (shouldCreateGroupHeader) {- const groupItems = flattenGroupedItems(group.items);- const summaryRow = createSummaryRow(- groupItems,- group.groupKey,- breakdownCount- );-- return [- {- ...summaryRow,- isGroupHeader: true,- groupValue: group.group,- groupLevel: group.level,- subRows,- },- ];- }-- return subRows;- }-- for (const group of groups) {- result.push(...processGroup(group));- }-- return result;-}--/**- * Convert hierarchical groups to flat table rows, respecting collapsed groups- * This creates GroupedTableRow entries with proper breakdownDisplay values- * @deprecated Use groupsToExpandableRows with TanStack Table's expanding feature instead- */-export function groupsToTableRows<T extends TableRow>(- groups: Array<GroupedItem<T>>,- collapsedGroups: Set<string>,- breakdownCount: number-): GroupedTableRow[] {- const rows: GroupedTableRow[] = [];-- function processGroup(- group: GroupedItem<T>,- parentPath: string[] = [],- parentGroupKey?: string- ): void {- const isGroupCollapsed = collapsedGroups.has(group.groupKey);- const currentPath = [...parentPath, group.group];-- if (isGroupCollapsed) {- const groupItems = flattenGroupedItems(group.items);- if (groupItems.length > 0) {- const summaryRow = createSummaryRow(- groupItems,- group.groupKey,- breakdownCount- );- rows.push(summaryRow);- }- return;- }-- const nestedGroups: GroupedItem<T>[] = [];- const actualItems: T[] = [];-- for (const item of group.items) {- if (item && typeof item === 'object' && 'items' in item) {- nestedGroups.push(item);- } else if (item) {- actualItems.push(item);- }- }-- actualItems.forEach((item, index) => {- const breakdownDisplay: (string | null)[] = [];- const breakdownValues = item.breakdownValues;-- if (index === 0) {- for (let i = 0; i < breakdownCount; i++) {- breakdownDisplay.push(breakdownValues[i] ?? null);- }- } else {- for (let i = 0; i < breakdownCount; i++) {- if (i < currentPath.length) {- breakdownDisplay.push(currentPath[i] ?? null);- } else if (i < breakdownValues.length) {- breakdownDisplay.push(breakdownValues[i] ?? null);- } else {- breakdownDisplay.push(null);- }- }- }-- rows.push({- ...item,- breakdownDisplay,- groupKey: group.groupKey,- parentGroupKey: group.parentGroupKey,- });- });-- for (const nestedGroup of nestedGroups) {- processGroup(nestedGroup, currentPath, group.groupKey);- }- }-- for (const group of groups) {- processGroup(group);- }-- return rows;-}--/** Extract unique dates from all series. */-function getUniqueDates(series: IChartData['series']): string[] {- const dateSet = new Set<string>();- series.forEach((serie) => {- serie.data.forEach((d) => {- dateSet.add(d.date);- });- });- return Array.from(dateSet).sort();-}--/**- * Get breakdown property names from series. Breakdown values live in- * names.slice(1), so the property names have to be inferred from the- * breakdowns array or from the series structure.- */-function getBreakdownPropertyNames(- series: IChartData['series'],- breakdowns: Array<{ name: string }>-): string[] {- if (breakdowns.length > 0) {- return breakdowns.map((b) => getPropertyLabel(b.name));- }-- // All series should have the same number of breakdown values- if (series.length === 0) {- return [];- }- const firstSerie = series[0];- const breakdownCount = firstSerie.names.length - 1;- return Array.from({ length: breakdownCount }, (_, i) => `Breakdown ${i + 1}`);-}--/**- * Transform series into flat table rows- */-export function createFlatRows(- series: IChartData['series'],- dates: string[]-): TableRow[] {- return series.map((serie) => {- const dateValues: Record<string, number> = {};- dates.forEach((date) => {- const dataPoint = serie.data.find((d) => d.date === date);- dateValues[date] = dataPoint?.count ?? 0;- });-- return {- id: serie.id,- serieId: serie.id,- serieName: serie.names[0] ?? '',- breakdownValues: serie.names.slice(1),- count: serie.metrics.count ?? 0,- sum: serie.metrics.sum,- average: serie.metrics.average,- min: serie.metrics.min,- max: serie.metrics.max,- dateValues,- };- });-}--/** Transform series into hierarchical groups: serie name, then breakdown values. */-export function createGroupedRowsHierarchical(- series: IChartData['series'],- dates: string[]-): Array<GroupedItem<TableRow>> {- const flatRows = createFlatRows(series, dates);-- // Sort by sum descending before grouping- flatRows.sort((a, b) => b.sum - a.sum);-- const breakdownCount = flatRows[0]?.breakdownValues.length ?? 0;-- if (breakdownCount === 0) {- // No breakdowns - return empty array (will be handled as flat rows)- return [];- }-- // groupByNames expects items with a `names` array; building a temporary- // one here is a minor inefficiency that keeps groupByNames generic.- const itemsWithNames = flatRows.map((row) => ({- ...row,- names: [row.serieName, ...row.breakdownValues],- }));-- return groupByNames(itemsWithNames);-}--/**- * Transform series into grouped table rows (legacy flat format)- * @deprecated Use createGroupedRowsHierarchical + groupsToTableRows instead- */-export function createGroupedRows(- series: IChartData['series'],- dates: string[]-): GroupedTableRow[] {- const flatRows = createFlatRows(series, dates);-- flatRows.sort((a, b) => b.sum - a.sum);-- const grouped: GroupedTableRow[] = [];- const breakdownCount = flatRows[0]?.breakdownValues.length ?? 0;-- if (breakdownCount === 0) {- return flatRows.map((row) => ({- ...row,- breakdownDisplay: [],- }));- }-- const groupsByFirstBreakdown = new Map<string, TableRow[]>();- flatRows.forEach((row) => {- const firstBreakdown = row.breakdownValues[0] ?? '';- if (!groupsByFirstBreakdown.has(firstBreakdown)) {- groupsByFirstBreakdown.set(firstBreakdown, []);- }- groupsByFirstBreakdown.get(firstBreakdown)!.push(row);- });-- const sortedGroups = Array.from(groupsByFirstBreakdown.entries()).sort(- (a, b) => {- const aMax = Math.max(...a[1].map((r) => r.sum));- const bMax = Math.max(...b[1].map((r) => r.sum));- return bMax - aMax;- }- );-- sortedGroups.forEach(([firstBreakdownValue, groupRows]) => {- groupRows.sort((a, b) => b.sum - a.sum);-- const groupKey = firstBreakdownValue;-- groupRows.forEach((row, index) => {- const breakdownDisplay: (string | null)[] = [];- const firstRow = groupRows[0]!;-- if (index === 0) {- breakdownDisplay.push(...row.breakdownValues);- } else {- // Always show the value, even if it matches the first row.- for (let i = 0; i < row.breakdownValues.length; i++) {- breakdownDisplay.push(row.breakdownValues[i] ?? null);- }- }-- grouped.push({- ...row,- breakdownDisplay,- groupKey,- });- });- });-- return grouped;-}--/** Create a summary row for a collapsed group. */-export function createSummaryRow(- groupRows: TableRow[],- groupKey: string,- breakdownCount: number-): GroupedTableRow {- const firstRow = groupRows[0]!;-- const totalSum = groupRows.reduce((sum, row) => sum + row.sum, 0);- const totalCount = groupRows.reduce((sum, row) => sum + row.count, 0);- const totalAverage =- groupRows.reduce((sum, row) => sum + row.average, 0) / groupRows.length;- const totalMin = Math.min(...groupRows.map((row) => row.min));- const totalMax = Math.max(...groupRows.map((row) => row.max));-- const dateValues: Record<string, number> = {};- groupRows.forEach((row) => {- Object.keys(row.dateValues).forEach((date) => {- dateValues[date] = (dateValues[date] ?? 0) + row.dateValues[date];- });- });-- // Build breakdownDisplay: show first breakdown value, rest are null- const breakdownDisplay: (string | null)[] = [- firstRow.breakdownValues[0] ?? null,- ...Array(breakdownCount - 1).fill(null),- ];-- return {- id: `summary-${groupKey}`,- serieId: firstRow.serieId,- serieName: firstRow.serieName,- breakdownValues: firstRow.breakdownValues,- count: totalCount,- sum: totalSum,- average: totalAverage,- min: totalMin,- max: totalMax,- dateValues,- groupKey,- isSummaryRow: true,- breakdownDisplay,- };-}--/** Reorder breakdowns by number of unique values (fewest first). */-function reorderBreakdownsByUniqueCount(- series: IChartData['series'],- breakdownPropertyNames: string[]-): {- reorderedNames: string[];- reorderMap: number[]; // Maps new index -> old index- reverseMap: number[]; // Maps old index -> new index-} {- if (breakdownPropertyNames.length === 0 || series.length === 0) {- return {- reorderedNames: breakdownPropertyNames,- reorderMap: [],- reverseMap: [],- };- }-- const uniqueCounts = breakdownPropertyNames.map((_, index) => {- const uniqueValues = new Set<string>();- series.forEach((serie) => {- const value = serie.names[index + 1]; // +1 because names[0] is serie name- if (value) {- uniqueValues.add(value);- }- });- return { index, count: uniqueValues.size };- });-- uniqueCounts.sort((a, b) => a.count - b.count);-- const reorderedNames = uniqueCounts.map(- (item) => breakdownPropertyNames[item.index]!- );- const reorderMap = uniqueCounts.map((item) => item.index); // new index -> old index- const reverseMap = new Array(breakdownPropertyNames.length);- reorderMap.forEach((oldIndex, newIndex) => {- reverseMap[oldIndex] = newIndex;- });-- return { reorderedNames, reorderMap, reverseMap };-}--/** Transform chart data into table-ready format. */-export function transformToTableData(- data: IChartData,- breakdowns: Array<{ name: string }>,- grouped: boolean-): {- rows: TableRow[] | GroupedTableRow[];- dates: string[];- breakdownPropertyNames: string[];-} {- const dates = getUniqueDates(data.series);- const originalBreakdownPropertyNames = getBreakdownPropertyNames(- data.series,- breakdowns- );-- const { reorderedNames: breakdownPropertyNames, reorderMap } =- reorderBreakdownsByUniqueCount(data.series, originalBreakdownPropertyNames);-- const reorderedSeries = data.series.map((serie) => {- const reorderedNames = [- serie.names[0],- ...reorderMap.map((oldIndex) => serie.names[oldIndex + 1] ?? ''),- ];- return {- ...serie,- names: reorderedNames,- };- });-- const rows = grouped- ? createGroupedRows(reorderedSeries, dates)- : createFlatRows(reorderedSeries, dates);-- if (!grouped) {- (rows as TableRow[]).sort((a, b) => b.sum - a.sum);- }-- return {- rows,- dates,- breakdownPropertyNames,- };-}--/** Transform chart data into hierarchical groups. */-export function transformToHierarchicalGroups(- data: IChartData,- breakdowns: Array<{ name: string }>-): {- groups: Array<GroupedItem<TableRow>>;- dates: string[];- breakdownPropertyNames: string[];-} {- const dates = getUniqueDates(data.series);- const originalBreakdownPropertyNames = getBreakdownPropertyNames(- data.series,- breakdowns- );-- const { reorderedNames: breakdownPropertyNames, reorderMap } =- reorderBreakdownsByUniqueCount(data.series, originalBreakdownPropertyNames);-- const reorderedSeries = data.series.map((serie) => {- const reorderedNames = [- serie.names[0],- ...reorderMap.map((oldIndex) => serie.names[oldIndex + 1] ?? ''),- ];- return {- ...serie,- names: reorderedNames,- };- });-- const groups = createGroupedRowsHierarchical(reorderedSeries, dates);-- return {- groups,- dates,- breakdownPropertyNames,- };-}diff --git a/apps/start/src/components/report-chart/common/report-table.tsx b/apps/start/src/components/report-chart/common/report-table.tsxdeleted file mode 100644index 30ebdc81c..000000000--- a/apps/start/src/components/report-chart/common/report-table.tsx+++ /dev/null@@ -1,1629 +0,0 @@-import type { ColumnDef, Header, Row } from '@tanstack/react-table';-import {- type ExpandedState,- flexRender,- getCoreRowModel,- getExpandedRowModel,- getFilteredRowModel,- type SortingState,- useReactTable,-} from '@tanstack/react-table';-import {- useVirtualizer,- useWindowVirtualizer,- type VirtualItem,-} from '@tanstack/react-virtual';-import throttle from 'lodash.throttle';-import { ChevronDown, ChevronRight } from 'lucide-react';-import type * as React from 'react';-import { useEffect, useMemo, useRef, useState } from 'react';-import { ReportTableToolbar } from './report-table-toolbar';-import {- type ExpandableTableRow,- type GroupedTableRow,- groupsToExpandableRows,- type TableRow,- transformToHierarchicalGroups,- transformToTableData,-} from './report-table-utils';-import { SerieName } from './serie-name';-import { Checkbox } from '@/components/ui/checkbox';-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';-import { useNumber } from '@/hooks/use-numer-formatter';-import { useSelector } from '@/redux';-import type { IChartData } from '@/trpc/client';-import { cn } from '@/utils/cn';-import { getChartColor } from '@/utils/theme';--declare module '@tanstack/react-table' {- interface ColumnMeta<TData, TValue> {- pinned?: 'left' | 'right';- isBreakdown?: boolean;- breakdownIndex?: number;- }-}--interface ReportTableProps {- data: IChartData;- visibleSeries: IChartData['series'] | string[];- setVisibleSeries: React.Dispatch<React.SetStateAction<string[]>>;-}--const DEFAULT_COLUMN_WIDTH = 150;-const ROW_HEIGHT = 48; // h-12--interface VirtualRowProps {- row: Row<TableRow | GroupedTableRow>;- virtualRow: VirtualItem;- pinningStylesMap: Map<string, React.CSSProperties>;- headers: Header<TableRow | GroupedTableRow, unknown>[];- isResizingRef: React.MutableRefObject<boolean>;- resizingColumnId: string | null;- setResizingColumnId: (id: string | null) => void;- leftPinnedColumns: Header<TableRow | GroupedTableRow, unknown>['column'][];- scrollableColumns: Header<TableRow | GroupedTableRow, unknown>['column'][];- rightPinnedColumns: Header<TableRow | GroupedTableRow, unknown>['column'][];- virtualColumns: VirtualItem[];- leftPinnedWidth: number;- scrollableColumnsTotalWidth: number;- rightPinnedWidth: number;-}--const VirtualRow = function VirtualRow({- row,- virtualRow,- pinningStylesMap,- headers,- isResizingRef,- resizingColumnId,- setResizingColumnId,- leftPinnedColumns,- scrollableColumns,- rightPinnedColumns,- virtualColumns,- leftPinnedWidth,- scrollableColumnsTotalWidth,- rightPinnedWidth,-}: VirtualRowProps) {- const cells = row.getVisibleCells();-- const renderCell = (- column: Header<TableRow | GroupedTableRow, unknown>['column'],- header: Header<TableRow | GroupedTableRow, unknown> | undefined- ) => {- const cell = cells.find((c) => c.column.id === column.id);- if (!(cell && header)) {- return null;- }-- const isBreakdown = column.columnDef.meta?.isBreakdown ?? false;- const pinningStyles = pinningStylesMap.get(column.id) ?? {};- const canResize = column.getCanResize();- const isPinned = column.columnDef.meta?.pinned === 'left';- const isResizing = resizingColumnId === column.id;-- return (- <div- className={cn('relative overflow-hidden border-r')}- key={cell.id}- style={{- width: `${header.getSize()}px`,- minWidth: column.columnDef.minSize,- maxWidth: column.columnDef.maxSize,- ...pinningStyles,- }}- >- {flexRender(cell.column.columnDef.cell, cell.getContext())}- {canResize && isPinned && (- <div- className={cn(- 'absolute top-0 right-0 h-full w-1 cursor-col-resize touch-none select-none bg-transparent transition-colors hover:bg-primary/50',- isResizing && 'bg-primary'- )}- data-resize-handle- onMouseDown={(e) => {- e.stopPropagation();- isResizingRef.current = true;- setResizingColumnId(column.id);- header.getResizeHandler()(e);- }}- onMouseUp={() => {- setTimeout(() => {- isResizingRef.current = false;- setResizingColumnId(null);- }, 0);- }}- onTouchEnd={() => {- setTimeout(() => {- isResizingRef.current = false;- setResizingColumnId(null);- }, 0);- }}- onTouchStart={(e) => {- e.stopPropagation();- isResizingRef.current = true;- setResizingColumnId(column.id);- header.getResizeHandler()(e);- }}- />- )}- </div>- );- };-- return (- <div- className="border-b transition-colors hover:bg-muted/30"- key={virtualRow.key}- style={{- position: 'absolute',- top: 0,- left: 0,- width: leftPinnedWidth + scrollableColumnsTotalWidth + rightPinnedWidth,- height: `${virtualRow.size}px`,- transform: `translateY(${virtualRow.start}px)`,- display: 'flex',- minWidth: 'fit-content',- }}- >- {leftPinnedColumns.map((column) => {- const header = headers.find((h) => h.column.id === column.id);- return renderCell(column, header);- })}-- <div- style={{- position: 'relative',- width: scrollableColumnsTotalWidth,- height: `${virtualRow.size}px`,- }}- >- {virtualColumns.map((virtualCol) => {- const column = scrollableColumns[virtualCol.index];- if (!column) {- return null;- }- const header = headers.find((h) => h.column.id === column.id);- const cell = cells.find((c) => c.column.id === column.id);- if (!(cell && header)) {- return null;- }-- return (- <div- className={cn('relative overflow-hidden')}- key={cell.id}- style={{- position: 'absolute',- left: `${virtualCol.start}px`,- width: `${virtualCol.size}px`,- height: `${virtualRow.size}px`,- }}- >- {flexRender(cell.column.columnDef.cell, cell.getContext())}- </div>- );- })}- </div>-- {rightPinnedColumns.map((column) => {- const header = headers.find((h) => h.column.id === column.id);- return renderCell(column, header);- })}- </div>- );-};--export function ReportTable({- data,- visibleSeries,- setVisibleSeries,-}: ReportTableProps) {- const [grouped, setGrouped] = useState(false);- const [expanded, setExpanded] = useState<ExpandedState>({});- const [sorting, setSorting] = useState<SortingState>([]);- const [globalFilter, setGlobalFilter] = useState('');- const [columnSizing, setColumnSizing] = useState<Record<string, number>>({});- const [resizingColumnId, setResizingColumnId] = useState<string | null>(null);- const isResizingRef = useRef(false);- const parentRef = useRef<HTMLDivElement>(null);- const [scrollMargin, setScrollMargin] = useState(0);- const number = useNumber();- const interval = useSelector((state) => state.report.interval);- const breakdowns = useSelector((state) => state.report.breakdowns);-- const formatDate = useFormatDateInterval({- interval,- short: true,- });-- const {- groups: hierarchicalGroups,- rows: flatRows,- dates,- breakdownPropertyNames,- } = useMemo(() => {- if (grouped) {- const result = transformToHierarchicalGroups(data, breakdowns);- return {- groups: result.groups,- rows: null,- dates: result.dates,- breakdownPropertyNames: result.breakdownPropertyNames,- };- }- const result = transformToTableData(data, breakdowns, false);- return {- groups: null,- rows: result.rows as TableRow[],- dates: result.dates,- breakdownPropertyNames: result.breakdownPropertyNames,- };- }, [data, breakdowns, grouped]);-- const expandableRows = useMemo(() => {- if (!(grouped && hierarchicalGroups) || hierarchicalGroups.length === 0) {- return null;- }-- return groupsToExpandableRows(- hierarchicalGroups,- breakdownPropertyNames.length- );- }, [grouped, hierarchicalGroups, breakdownPropertyNames.length]);-- const rows = expandableRows ?? flatRows ?? [];-- const filteredRows = useMemo(() => {- let result = rows;-- if (globalFilter.trim()) {- const searchLower = globalFilter.toLowerCase();- result = rows.filter((row) => {- if (row.serieName.toLowerCase().includes(searchLower)) {- return true;- }-- if (- row.breakdownValues.some((val) =>- val?.toLowerCase().includes(searchLower)- )- ) {- return true;- }-- const metrics = ['count', 'sum', 'average', 'min', 'max'] as const;- if (- metrics.some((metric) =>- String(row[metric]).toLowerCase().includes(searchLower)- )- ) {- return true;- }-- if (- Object.values(row.dateValues).some((val) =>- String(val).toLowerCase().includes(searchLower)- )- ) {- return true;- }-- return false;- });- }-- if (grouped && result.length > 0) {- const groupedRows = result as ExpandableTableRow[] | GroupedTableRow[];-- const sortFn = (- a: ExpandableTableRow | GroupedTableRow | TableRow,- b: ExpandableTableRow | GroupedTableRow | TableRow- ) => {- if (sorting.length === 0) {- return 0;- }-- for (const sort of sorting) {- const { id, desc } = sort;- let aValue: any;- let bValue: any;-- if (id === 'serie-name') {- aValue = a.serieName ?? '';- bValue = b.serieName ?? '';- } else if (id.startsWith('breakdown-')) {- const index = Number.parseInt(id.replace('breakdown-', ''), 10);- if ('breakdownDisplay' in a && a.breakdownDisplay) {- aValue = a.breakdownDisplay[index] ?? '';- } else {- aValue = a.breakdownValues[index] ?? '';- }- if ('breakdownDisplay' in b && b.breakdownDisplay) {- bValue = b.breakdownDisplay[index] ?? '';- } else {- bValue = b.breakdownValues[index] ?? '';- }- } else if (id.startsWith('metric-')) {- const metric = id.replace('metric-', '') as keyof TableRow;- aValue = a[metric] ?? 0;- bValue = b[metric] ?? 0;- } else if (id.startsWith('date-')) {- const date = id.replace('date-', '');- aValue = a.dateValues[date] ?? 0;- bValue = b.dateValues[date] ?? 0;- } else {- continue;- }-- if (aValue == null && bValue == null) {- continue;- }- if (aValue == null) {- return 1;- }- if (bValue == null) {- return -1;- }-- if (typeof aValue === 'string' && typeof bValue === 'string') {- const comparison = aValue.localeCompare(bValue);- if (comparison !== 0) {- return desc ? -comparison : comparison;- }- } else {- if (aValue < bValue) {- return desc ? 1 : -1;- }- if (aValue > bValue) {- return desc ? -1 : 1;- }- }- }- return 0;- };-- function sortExpandableRows(- rows: ExpandableTableRow[],- isTopLevel = true- ): ExpandableTableRow[] {- const sorted = [...rows].sort((a, b) => {- if (isTopLevel) {- const aIsGroupHeader = 'isGroupHeader' in a && a.isGroupHeader;- const bIsGroupHeader = 'isGroupHeader' in b && b.isGroupHeader;-- if (aIsGroupHeader && bIsGroupHeader) {- const aLevel = 'groupLevel' in a ? (a.groupLevel ?? -1) : -1;- const bLevel = 'groupLevel' in b ? (b.groupLevel ?? -1) : -1;-- // Same level groups: sort by count first (always, regardless of user sort)- if (aLevel === bLevel) {- const aCount = a.count ?? 0;- const bCount = b.count ?? 0;- if (aCount !== bCount) {- return bCount - aCount;- }- // If counts are equal, fall through to user sort- }- }- }-- return sortFn(a, b);- });-- return sorted.map((row) => {- if ('subRows' in row && row.subRows) {- return {- ...row,- subRows: sortExpandableRows(row.subRows, false),- };- }- return row;- });- }-- return sortExpandableRows(groupedRows as ExpandableTableRow[]);- }-- if (!grouped && result.length > 0 && sorting.length > 0) {- return [...result].sort((a, b) => {- for (const sort of sorting) {- const { id, desc } = sort;- let aValue: any;- let bValue: any;-- if (id === 'serie-name') {- aValue = a.serieName ?? '';- bValue = b.serieName ?? '';- } else if (id.startsWith('breakdown-')) {- const index = Number.parseInt(id.replace('breakdown-', ''), 10);- aValue = a.breakdownValues[index] ?? '';- bValue = b.breakdownValues[index] ?? '';- } else if (id.startsWith('metric-')) {- const metric = id.replace('metric-', '') as keyof TableRow;- aValue = a[metric] ?? 0;- bValue = b[metric] ?? 0;- } else if (id.startsWith('date-')) {- const date = id.replace('date-', '');- aValue = a.dateValues[date] ?? 0;- bValue = b.dateValues[date] ?? 0;- } else {- continue;- }-- if (aValue == null && bValue == null) {- continue;- }- if (aValue == null) {- return 1;- }- if (bValue == null) {- return -1;- }-- if (typeof aValue === 'string' && typeof bValue === 'string') {- const comparison = aValue.localeCompare(bValue);- if (comparison !== 0) {- return desc ? -comparison : comparison;- }- } else {- if (aValue < bValue) {- return desc ? 1 : -1;- }- if (aValue > bValue) {- return desc ? -1 : 1;- }- }- }- return 0;- });- }-- return result;- }, [rows, globalFilter, grouped, sorting]);-- const { metricRanges, dateRanges } = useMemo(() => {- const metricRanges: Record<string, { min: number; max: number }> = {- count: {- min: Number.POSITIVE_INFINITY,- max: Number.NEGATIVE_INFINITY,- },- sum: { min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY },- average: {- min: Number.POSITIVE_INFINITY,- max: Number.NEGATIVE_INFINITY,- },- min: { min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY },- max: { min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY },- };-- const dateRanges: Record<string, { min: number; max: number }> = {};- dates.forEach((date) => {- dateRanges[date] = {- min: Number.POSITIVE_INFINITY,- max: Number.NEGATIVE_INFINITY,- };- });-- function getIndividualRows(- rows: (ExpandableTableRow | TableRow)[]- ): TableRow[] {- const individualRows: TableRow[] = [];- for (const row of rows) {- const isGroupHeader =- 'isGroupHeader' in row && row.isGroupHeader === true;- const isSummary = 'isSummaryRow' in row && row.isSummaryRow === true;-- if (!(isGroupHeader || isSummary)) {- individualRows.push(row as TableRow);- }-- if ('subRows' in row && row.subRows && Array.isArray(row.subRows)) {- individualRows.push(...getIndividualRows(row.subRows));- }- }- return individualRows;- }-- const individualRows = getIndividualRows(rows);- const isSingleSeries = individualRows.length === 1;-- if (isSingleSeries) {- const singleRow = individualRows[0]!;- const allDateValues = dates.map(- (date) => singleRow.dateValues[date] ?? 0- );- const dateMin = Math.min(...allDateValues);- const dateMax = Math.max(...allDateValues);-- dates.forEach((date) => {- dateRanges[date] = {- min: dateMin,- max: dateMax,- };- });-- metricRanges.count = { min: dateMin, max: dateMax };- metricRanges.sum = { min: dateMin, max: dateMax };- metricRanges.average = { min: dateMin, max: dateMax };- metricRanges.min = { min: dateMin, max: dateMax };- metricRanges.max = { min: dateMin, max: dateMax };- } else if (individualRows.length === 0) {- } else {- individualRows.forEach((row) => {- Object.keys(metricRanges).forEach((key) => {- const value = row[key as keyof typeof row] as number;- if (typeof value === 'number' && !Number.isNaN(value)) {- metricRanges[key]!.min = Math.min(metricRanges[key]!.min, value);- metricRanges[key]!.max = Math.max(metricRanges[key]!.max, value);- }- });-- dates.forEach((date) => {- const value = row.dateValues[date] ?? 0;- if (!dateRanges[date]) {- dateRanges[date] = {- min: Number.POSITIVE_INFINITY,- max: Number.NEGATIVE_INFINITY,- };- }- if (typeof value === 'number' && !Number.isNaN(value)) {- dateRanges[date]!.min = Math.min(dateRanges[date]!.min, value);- dateRanges[date]!.max = Math.max(dateRanges[date]!.max, value);- }- });- });- }-- return { metricRanges, dateRanges };- }, [rows, dates]);-- // Returns both style and opacity (for text color calculation) to avoid parsing- const getCellBackgroundStyle = (- value: number,- min: number,- max: number,- colorClass: 'purple' | 'emerald' = 'emerald'- ): { style: React.CSSProperties; opacity: number } => {- if (value === 0) {- return { style: {}, opacity: 0 };- }-- let opacity: number;- if (max === min) {- opacity = 0.5;- } else {- const percentage = (value - min) / (max - min);- opacity = Math.max(0.05, Math.min(1, percentage));- }-- // Use rgba colors directly instead of opacity + background class- const backgroundColor =- colorClass === 'purple'- ? `rgba(168, 85, 247, ${opacity})` // purple-500- : `rgba(16, 185, 129, ${opacity})`; // emerald-500-- return {- style: { backgroundColor },- opacity,- };- };-- const visibleSeriesIds = useMemo(() => {- if (visibleSeries.length === 0) {- return [];- }- if (typeof visibleSeries[0] === 'string') {- return visibleSeries as string[];- }- return (visibleSeries as IChartData['series']).map((s) => s.id);- }, [visibleSeries]);-- const visibleSeriesIdsHash = useMemo(() => {- return visibleSeriesIds.sort().join(',');- }, [visibleSeriesIds]);-- const getSerieIndex = (serieId: string): number => {- return data.series.findIndex((s) => s.id === serieId);- };-- const toggleSerieVisibility = (serieId: string) => {- setVisibleSeries((prev) => {- if (prev.includes(serieId)) {- return prev.filter((id) => id !== serieId);- }- return [...prev, serieId];- });- };-- const toggleGroupCollapse = (groupKey: string) => {- // For now, this is a no-op as TanStack Table handles it- };-- const columns = useMemo<ColumnDef<TableRow | GroupedTableRow>[]>(() => {- const cols: ColumnDef<TableRow | GroupedTableRow>[] = [];-- cols.push({- id: 'serie-name',- header: 'Serie',- accessorKey: 'serieName',- enableSorting: true,- size: DEFAULT_COLUMN_WIDTH,- meta: {- pinned: 'left',- },- cell: ({ row }) => {- const original = row.original;- const serieId = original.serieId;- // Look up serie name directly from data to ensure we always have the latest value- const serie = data.series.find((s) => s.id === serieId);- const serieName = serie?.names[0] ?? original.serieName ?? '';- const isVisible = visibleSeriesIds.includes(serieId);- const serieIndex = getSerieIndex(serieId);- const color = getChartColor(serieIndex);-- // Check if this serie name matches the first row in the group (for muted styling)- let isMuted = false;- let isFirstRowInGroup = false;- if (- grouped &&- 'groupKey' in original &&- original.groupKey &&- !original.isSummaryRow- ) {- const groupRows = rows.filter(- (r): r is GroupedTableRow =>- 'groupKey' in r &&- r.groupKey === original.groupKey &&- !r.isSummaryRow- );-- if (groupRows.length > 0) {- const firstRowInGroup = groupRows[0]!;-- if (firstRowInGroup.id === original.id) {- isFirstRowInGroup = true;- } else {- isMuted = true;- }- }- }-- const originalRow = row.original as ExpandableTableRow | TableRow;- const isGroupHeader =- 'isGroupHeader' in originalRow && originalRow.isGroupHeader === true;- const isExpanded = grouped ? (row.getIsExpanded?.() ?? false) : false;- const isSerieGroupHeader =- isGroupHeader &&- 'groupLevel' in originalRow &&- originalRow.groupLevel === -1;- const hasSubRows =- 'subRows' in originalRow && (originalRow.subRows?.length ?? 0) > 0;- const isExpandable = grouped && isSerieGroupHeader && hasSubRows;-- return (- <div className="flex h-12 items-center gap-2 px-4">- <Checkbox- checked={isVisible}- className="h-4 w-4 shrink-0"- onCheckedChange={() => toggleSerieVisibility(serieId)}- style={{- borderColor: color,- backgroundColor: isVisible ? color : 'transparent',- }}- />- <SerieName- className={cn(- 'truncate',- !isExpandable && grouped && 'text-muted-foreground/40',- isExpandable && 'font-semibold'- )}- name={serieName}- />- {isExpandable && (- <button- className="cursor-pointer hover:opacity-70"- onClick={(e) => {- e.stopPropagation();- e.preventDefault();- setExpanded((prev) => {- const newExpanded: ExpandedState =- typeof prev === 'object' ? { ...prev } : {};- const rowId = row.id;- newExpanded[rowId] = !newExpanded[rowId];- return newExpanded;- });- }}- type="button"- >- {isExpanded ? (- <ChevronDown className="h-4 w-4" />- ) : (- <ChevronRight className="h-4 w-4" />- )}- </button>- )}- </div>- );- },- });-- breakdownPropertyNames.forEach((propertyName, index) => {- const isLastBreakdown = index === breakdownPropertyNames.length - 1;- const isCollapsible = grouped && !isLastBreakdown;-- cols.push({- id: `breakdown-${index}`,- enableSorting: true,- enableResizing: true,- size: columnSizing[`breakdown-${index}`] ?? DEFAULT_COLUMN_WIDTH,- minSize: 100,- maxSize: 500,- accessorFn: (row) => {- if ('breakdownDisplay' in row && grouped) {- return row.breakdownDisplay[index] ?? '';- }- return row.breakdownValues[index] ?? '';- },- header: ({ column }) => {- if (!isCollapsible) {- return propertyName;- }-- const rowsAtLevel: string[] = [];- if (grouped && expandableRows) {- function collectRowIdsAtLevel(- rows: ExpandableTableRow[],- targetLevel: number,- currentLevel = 0- ): void {- for (const row of rows) {- if (- row.isGroupHeader &&- row.groupLevel === targetLevel &&- (row.subRows?.length ?? 0) > 0- ) {- rowsAtLevel.push(row.id);- }- if (currentLevel < targetLevel && row.subRows) {- collectRowIdsAtLevel(- row.subRows,- targetLevel,- currentLevel + 1- );- }- }- }- collectRowIdsAtLevel(expandableRows, index);- }-- const allExpanded =- rowsAtLevel.length > 0 &&- rowsAtLevel.every(- (id) => typeof expanded === 'object' && expanded[id] === true- );-- return (- <div- className="flex cursor-pointer items-center gap-2 hover:opacity-70"- onClick={() => {- if (!grouped) {- return;- }- setExpanded((prev) => {- const newExpanded: ExpandedState =- typeof prev === 'object' ? { ...prev } : {};- const shouldExpand = !allExpanded;- rowsAtLevel.forEach((id) => {- newExpanded[id] = shouldExpand;- });- return newExpanded;- });- }}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- if (!grouped) {- return;- }- setExpanded((prev) => {- const newExpanded: ExpandedState =- typeof prev === 'object' ? { ...prev } : {};- const shouldExpand = !allExpanded;- rowsAtLevel.forEach((id) => {- newExpanded[id] = shouldExpand;- });- return newExpanded;- });- }- }}- role="button"- tabIndex={0}- >- <span>{propertyName}</span>- </div>- );- },- meta: {- pinned: 'left',- isBreakdown: true,- },- cell: ({ row }) => {- const original = row.original as ExpandableTableRow | TableRow;- const isGroupHeader =- 'isGroupHeader' in original && original.isGroupHeader === true;- const canExpand = row.getCanExpand?.() ?? false;- const isExpanded = row.getIsExpanded?.() ?? false;-- const value: string | number | null =- original.breakdownValues[index] ?? null;- const isLastBreakdown = index === breakdownPropertyNames.length - 1;- const isMuted =- (!(isLastBreakdown || canExpand) && grouped) || !value;-- // For group headers, only show value at the group level, hide deeper breakdowns- if (isGroupHeader && 'groupLevel' in original) {- const groupLevel = original.groupLevel ?? 0;- if (index !== groupLevel) {- return <div className="flex h-12 items-center gap-2 px-4" />;- }- }-- return (- <div className="flex h-12 items-center gap-2 px-4">- <span- className={cn(- 'block truncate leading-[48px]',- isMuted && 'text-muted-foreground/50',- isGroupHeader && 'font-semibold'- )}- >- {value || '(Not set)'}- </span>- {canExpand &&- index ===- ('groupLevel' in original ? (original.groupLevel ?? 0) : 0) &&- index < breakdownPropertyNames.length - 1 && (- <button- className="cursor-pointer hover:opacity-70"- onClick={(e) => {- e.stopPropagation();- const handler = row.getToggleExpandedHandler();- if (handler) {- handler();- }- }}- type="button"- >- {isExpanded ? (- <ChevronDown className="h-4 w-4" />- ) : (- <ChevronRight className="h-4 w-4" />- )}- </button>- )}- </div>- );- },- });- });-- const metrics = [- { key: 'count', label: 'Unique' },- { key: 'sum', label: 'Sum' },- { key: 'average', label: 'Average' },- { key: 'min', label: 'Min' },- { key: 'max', label: 'Max' },- ] as const;-- metrics.forEach((metric) => {- cols.push({- id: `metric-${metric.key}`,- header: metric.label,- accessorKey: metric.key,- enableSorting: true,- size: 100,- cell: ({ row }) => {- const value = row.original[metric.key];- const original = row.original as ExpandableTableRow | TableRow;- const hasIsSummaryRow = 'isSummaryRow' in original;- const hasIsGroupHeader = 'isGroupHeader' in original;- const isSummary = hasIsSummaryRow && original.isSummaryRow === true;- const isGroupHeader =- hasIsGroupHeader && original.isGroupHeader === true;- const isIndividualRow = !(isSummary || isGroupHeader);- const range = metricRanges[metric.key];-- // Also check that range is valid (not still at initial values)- const hasValidRange =- range &&- range.min !== Number.POSITIVE_INFINITY &&- range.max !== Number.NEGATIVE_INFINITY;-- const { style: backgroundStyle, opacity: bgOpacity } =- isIndividualRow && hasValidRange- ? getCellBackgroundStyle(value, range.min, range.max, 'purple')- : { style: {}, opacity: 0 };-- return (- <div- className={cn(- 'flex h-12 w-full items-center justify-end px-4 text-right font-mono text-sm',- 'shadow-[inset_-1px_-1px_0_var(--border)] [text-shadow:_0_0_3px_rgb(0_0_0_/_20%)]',- (isSummary || isGroupHeader) && 'font-semibold'- )}- style={backgroundStyle}- >- {number.format(value)}- </div>- );- },- });- });-- dates.forEach((date) => {- cols.push({- id: `date-${date}`,- header: formatDate(date),- accessorFn: (row) => row.dateValues[date] ?? 0,- enableSorting: true,- size: 100,- cell: ({ row }) => {- const value = row.original.dateValues[date] ?? 0;- const isSummary = row.original.isSummaryRow ?? false;- const isGroupHeader =- 'isGroupHeader' in row.original &&- row.original.isGroupHeader === true;- const isIndividualRow = !(isSummary || isGroupHeader);- const range = dateRanges[date];- // Also check that range is valid (not still at initial values)- const hasValidRange =- range &&- range.min !== Number.POSITIVE_INFINITY &&- range.max !== Number.NEGATIVE_INFINITY;- const { style: backgroundStyle, opacity: bgOpacity } =- isIndividualRow && hasValidRange- ? getCellBackgroundStyle(value, range.min, range.max, 'emerald')- : { style: {}, opacity: 0 };-- const needsLightText = bgOpacity > 0.7;-- return (- <div- className={cn(- 'flex h-12 w-full items-center justify-end px-4 text-right font-mono text-sm',- 'shadow-[inset_-1px_-1px_0_var(--border)] [text-shadow:_0_0_3px_rgb(0_0_0_/_20%)]',- (isSummary || isGroupHeader) && 'font-semibold'- )}- style={backgroundStyle}- >- {number.format(value)}- </div>- );- },- });- });-- return cols;- }, [- breakdownPropertyNames,- dates,- formatDate,- number,- grouped,- visibleSeriesIds,- expandableRows,- rows,- metricRanges,- dateRanges,- columnSizing,- expanded,- data,- ]);-- const columnsHash = useMemo(() => {- return columns.map((col) => col.id).join(',');- }, [columns]);-- const tableOptions = useMemo(- () => ({- data: filteredRows,- columns,- getCoreRowModel: getCoreRowModel(),- getExpandedRowModel: grouped ? getExpandedRowModel() : undefined,- getSubRows: grouped- ? (row: ExpandableTableRow | TableRow) =>- 'subRows' in row ? row.subRows : undefined- : undefined,- // Sorting is handled manually in filteredRows, so we don't use getSortedRowModel- getFilteredRowModel: getFilteredRowModel(),- filterFns: {- isWithinRange: () => true,- },- enableColumnResizing: true,- columnResizeMode: 'onChange' as const,- getRowCanExpand: grouped- ? (row: any) => {- const r = row.original as ExpandableTableRow;- if (!('isGroupHeader' in r && r.isGroupHeader)) {- return false;- }- // Don't allow expansion for the last breakdown level- const groupLevel = r.groupLevel ?? -1;- const isLastBreakdown =- groupLevel === breakdownPropertyNames.length - 1;- const hasSubRows = (r.subRows?.length ?? 0) > 0;- return !isLastBreakdown && hasSubRows;- }- : undefined,- state: {- sorting, // Keep sorting state for UI indicators- columnSizing,- expanded: grouped ? expanded : undefined,- },- onSortingChange: setSorting,- onColumnSizingChange: setColumnSizing,- onExpandedChange: grouped ? setExpanded : undefined,- globalFilterFn: () => true,- manualSorting: true,- manualFiltering: true,- }),- [- filteredRows,- columns,- grouped,- breakdownPropertyNames.length,- sorting,- columnSizing,- expanded,- setSorting,- setColumnSizing,- setExpanded,- ]- );-- const table = useReactTable(tableOptions);-- useEffect(() => {- const updateScrollMargin = throttle(() => {- if (parentRef.current) {- setScrollMargin(- parentRef.current.getBoundingClientRect().top + window.scrollY- );- }- }, 500);-- updateScrollMargin();- window.addEventListener('resize', updateScrollMargin);-- return () => {- window.removeEventListener('resize', updateScrollMargin);- };- }, []);-- useEffect(() => {- const handleMouseUp = () => {- if (isResizingRef.current) {- // Small delay to ensure resize handlers complete- setTimeout(() => {- isResizingRef.current = false;- setResizingColumnId(null);- }, 100);- }- };-- window.addEventListener('mouseup', handleMouseUp);- window.addEventListener('touchend', handleMouseUp);-- return () => {- window.removeEventListener('mouseup', handleMouseUp);- window.removeEventListener('touchend', handleMouseUp);- };- }, []);-- // Always call the table helpers so React Table can manage its own memoization- const rowModelToUse = grouped- ? table.getExpandedRowModel()- : table.getRowModel();-- const virtualizer = useWindowVirtualizer({- count: rowModelToUse.rows.length,- estimateSize: () => ROW_HEIGHT,- overscan: 10,- scrollMargin,- });-- const virtualRows = virtualizer.getVirtualItems();-- const headerColumns = table- .getAllLeafColumns()- .filter((col) => table.getState().columnVisibility[col.id] !== false);-- const leftPinnedColumns = headerColumns.filter(- (col) => col.columnDef.meta?.pinned === 'left'- );- const rightPinnedColumns = headerColumns.filter(- (col) => col.columnDef.meta?.pinned === 'right'- );- const scrollableColumns = headerColumns.filter(- (col) => !col.columnDef.meta?.pinned- );-- const leftPinnedWidth = useMemo(- () => leftPinnedColumns.reduce((sum, col) => sum + col.getSize(), 0),- [leftPinnedColumns, columnSizing]- );- const rightPinnedWidth = useMemo(- () => rightPinnedColumns.reduce((sum, col) => sum + col.getSize(), 0),- [rightPinnedColumns, columnSizing]- );- const scrollableColumnsTotalWidth = useMemo(- () => scrollableColumns.reduce((sum, col) => sum + col.getSize(), 0),- [scrollableColumns, columnSizing]- );-- // Only virtualize if we have enough columns to benefit from it- const shouldVirtualizeHorizontal = scrollableColumns.length > 10;-- const horizontalVirtualizer = useVirtualizer({- count: scrollableColumns.length,- getScrollElement: () => parentRef.current,- estimateSize: (index) =>- scrollableColumns[index]?.getSize() ?? DEFAULT_COLUMN_WIDTH,- horizontal: true,- overscan: shouldVirtualizeHorizontal ? 5 : scrollableColumns.length,- });-- const virtualColumns = shouldVirtualizeHorizontal- ? horizontalVirtualizer.getVirtualItems()- : scrollableColumns.map((col, index) => ({- index,- start: scrollableColumns- .slice(0, index)- .reduce((sum, c) => sum + c.getSize(), 0),- size: col.getSize(),- key: col.id,- end: 0,- lane: 0,- }));-- const { gridTemplateColumns, headers } = useMemo(() => {- const headerGroups = table.getHeaderGroups();- const firstGroupHeaders = headerGroups[0]?.headers ?? [];- return {- gridTemplateColumns:- firstGroupHeaders.map((h) => `${h.getSize()}px`).join(' ') ?? '',- headers: firstGroupHeaders,- };- }, [table, columnSizing, columnsHash]);-- const pinningStylesMap = useMemo(() => {- const stylesMap = new Map<string, React.CSSProperties>();- const headerGroups = table.getHeaderGroups();-- headerGroups.forEach((group) => {- group.headers.forEach((header) => {- const column = header.column;- const isPinned = column.columnDef.meta?.pinned;- if (!isPinned) {- stylesMap.set(column.id, {});- return;- }-- const pinnedColumns =- isPinned === 'left' ? leftPinnedColumns : rightPinnedColumns;- const columnIndex = pinnedColumns.findIndex((c) => c.id === column.id);- const isLastPinned =- columnIndex === pinnedColumns.length - 1 && isPinned === 'left';- const isFirstRightPinned = columnIndex === 0 && isPinned === 'right';-- let left = 0;- if (isPinned === 'left') {- for (let i = 0; i < columnIndex; i++) {- left += pinnedColumns[i]!.getSize();- }- }-- stylesMap.set(column.id, {- position: 'sticky' as const,- left: isPinned === 'left' ? `${left}px` : undefined,- right: isPinned === 'right' ? '0px' : undefined,- zIndex: 10,- backgroundColor: 'var(--card)',- boxShadow: isLastPinned- ? '-4px 0 4px -4px var(--border) inset'- : isFirstRightPinned- ? '4px 0 4px -4px var(--border) inset'- : undefined,- });- });- });-- return stylesMap;- }, [table, leftPinnedColumns, rightPinnedColumns, columnSizing, columnsHash]);-- const getPinningStyles = (- column: ReturnType<typeof table.getColumn> | undefined- ) => {- if (!column) {- return {};- }- return pinningStylesMap.get(column.id) ?? {};- };-- if (rows.length === 0) {- return null;- }-- return (- <div className="mt-8 flex flex-col overflow-hidden rounded-lg border bg-card">- <ReportTableToolbar- grouped={grouped}- onSearchChange={setGlobalFilter}- onToggleGrouped={- !breakdowns || breakdowns.length === 0- ? undefined- : () => setGrouped(!grouped)- }- onUnselectAll={() => setVisibleSeries([])}- search={globalFilter}- />- <div- className="overflow-x-auto"- ref={parentRef}- style={{- width: '100%',- }}- >- <div- className="relative"- style={{- width:- leftPinnedWidth + scrollableColumnsTotalWidth + rightPinnedWidth,- minWidth: 'fit-content',- }}- >- <div- className="sticky top-0 z-20 border-b bg-card"- style={{- display: 'flex',- width:- leftPinnedWidth +- scrollableColumnsTotalWidth +- rightPinnedWidth,- minWidth: 'fit-content',- }}- >- {leftPinnedColumns.map((column) => {- const header = headers.find((h) => h.column.id === column.id);- if (!header) {- return null;- }- const headerContent = column.columnDef.header;- const isBreakdown = column.columnDef.meta?.isBreakdown ?? false;- const pinningStyles = getPinningStyles(column);- const isMetricOrDate =- column.id.startsWith('metric-') ||- column.id.startsWith('date-');-- const canSort = column.getCanSort();- const isSorted = column.getIsSorted();- const canResize = column.getCanResize();- const isPinned = column.columnDef.meta?.pinned === 'left';-- return (- <div- className={cn(- 'relative flex h-10 items-center whitespace-nowrap border-border border-r bg-muted/30 px-4 font-semibold text-[10px] uppercase',- isMetricOrDate && 'text-right',- canSort && 'cursor-pointer select-none hover:bg-muted/50'- )}- key={header.id}- onClick={- canSort- ? (e) => {- // Don't trigger sort if clicking on resize handle or if we just finished resizing- if (- isResizingRef.current ||- column.getIsResizing() ||- (e.target as HTMLElement).closest(- '[data-resize-handle]'- )- ) {- return;- }- column.toggleSorting();- }- : undefined- }- onKeyDown={- canSort- ? (e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- column.toggleSorting();- }- }- : undefined- }- role={canSort ? 'button' : undefined}- style={{- width: `${header.getSize()}px`,- minWidth: column.columnDef.minSize,- maxWidth: column.columnDef.maxSize,- ...pinningStyles,- }}- tabIndex={canSort ? 0 : undefined}- >- <div className="flex flex-1 items-center gap-1.5">- {header.isPlaceholder- ? null- : typeof headerContent === 'function'- ? flexRender(headerContent, header.getContext())- : headerContent}- {canSort && (- <span className="text-muted-foreground">- {isSorted === 'asc'- ? '↑'- : isSorted === 'desc'- ? '↓'- : '⇅'}- </span>- )}- </div>- {canResize && isPinned && (- <div- className={cn(- 'absolute top-0 right-0 h-full w-1 cursor-col-resize touch-none select-none bg-transparent transition-colors hover:bg-primary/50',- header.column.getIsResizing() && 'bg-primary'- )}- data-resize-handle- onMouseDown={(e) => {- e.stopPropagation();- isResizingRef.current = true;- setResizingColumnId(column.id);- header.getResizeHandler()(e);- }}- onMouseUp={() => {- // Use setTimeout to allow the resize to complete before resetting- setTimeout(() => {- isResizingRef.current = false;- setResizingColumnId(null);- }, 0);- }}- onTouchEnd={() => {- setTimeout(() => {- isResizingRef.current = false;- setResizingColumnId(null);- }, 0);- }}- onTouchStart={(e) => {- e.stopPropagation();- isResizingRef.current = true;- setResizingColumnId(column.id);- header.getResizeHandler()(e);- }}- />- )}- </div>- );- })}-- <div- style={{- position: 'relative',- width: scrollableColumnsTotalWidth,- height: '40px',- }}- >- {virtualColumns.map((virtualCol) => {- const column = scrollableColumns[virtualCol.index];- if (!column) {- return null;- }- const header = headers.find((h) => h.column.id === column.id);- if (!header) {- return null;- }-- const headerContent = header.column.columnDef.header;- const isBreakdown =- header.column.columnDef.meta?.isBreakdown ?? false;- const isMetricOrDate =- header.column.id.startsWith('metric-') ||- header.column.id.startsWith('date-');- const canSort = header.column.getCanSort();- const isSorted = header.column.getIsSorted();-- return (- <div- className={cn(- 'flex items-center whitespace-nowrap border-border border-r bg-muted/30 px-4 font-semibold text-[10px] uppercase',- isMetricOrDate && 'text-right',- canSort && 'cursor-pointer select-none hover:bg-muted/50'- )}- key={header.id}- onClick={- canSort- ? (e) => {- if (- isResizingRef.current ||- header.column.getIsResizing() ||- (e.target as HTMLElement).closest(- '[data-resize-handle]'- )- ) {- return;- }- header.column.toggleSorting();- }- : undefined- }- onKeyDown={- canSort- ? (e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- header.column.toggleSorting();- }- }- : undefined- }- role={canSort ? 'button' : undefined}- style={{- position: 'absolute',- left: `${virtualCol.start}px`,- width: `${virtualCol.size}px`,- height: '40px',- }}- tabIndex={canSort ? 0 : undefined}- >- <div className="flex flex-1 items-center gap-1.5">- {header.isPlaceholder- ? null- : typeof headerContent === 'function'- ? flexRender(headerContent, header.getContext())- : headerContent}- {canSort && (- <span className="text-muted-foreground">- {isSorted === 'asc'- ? '↑'- : isSorted === 'desc'- ? '↓'- : '⇅'}- </span>- )}- </div>- </div>- );- })}- </div>-- {rightPinnedColumns.map((column) => {- const header = headers.find((h) => h.column.id === column.id);- if (!header) {- return null;- }-- const headerContent = header.column.columnDef.header;- const isBreakdown =- header.column.columnDef.meta?.isBreakdown ?? false;- const pinningStyles = getPinningStyles(header.column);- const isMetricOrDate =- header.column.id.startsWith('metric-') ||- header.column.id.startsWith('date-');- const canSort = header.column.getCanSort();- const isSorted = header.column.getIsSorted();- const canResize = header.column.getCanResize();-- return (- <div- className={cn(- 'relative flex h-10 items-center whitespace-nowrap border-border border-r bg-muted/30 px-4 font-semibold text-[10px] uppercase',- isMetricOrDate && 'text-right',- canSort && 'cursor-pointer select-none hover:bg-muted/50'- )}- key={header.id}- onClick={- canSort- ? (e) => {- if (- isResizingRef.current ||- header.column.getIsResizing() ||- (e.target as HTMLElement).closest(- '[data-resize-handle]'- )- ) {- return;- }- header.column.toggleSorting();- }- : undefined- }- onKeyDown={- canSort- ? (e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- header.column.toggleSorting();- }- }- : undefined- }- role={canSort ? 'button' : undefined}- style={{- width: `${header.getSize()}px`,- minWidth: header.column.columnDef.minSize,- maxWidth: header.column.columnDef.maxSize,- ...pinningStyles,- }}- tabIndex={canSort ? 0 : undefined}- >- <div className="flex flex-1 items-center gap-1.5">- {header.isPlaceholder- ? null- : typeof headerContent === 'function'- ? flexRender(headerContent, header.getContext())- : headerContent}- {canSort && (- <span className="text-muted-foreground">- {isSorted === 'asc'- ? '↑'- : isSorted === 'desc'- ? '↓'- : '⇅'}- </span>- )}- </div>- </div>- );- })}- </div>-- <div- style={{- height: `${virtualizer.getTotalSize()}px`,- position: 'relative',- }}- >- {virtualRows.map((virtualRow) => {- const tableRow = rowModelToUse.rows[virtualRow.index];- if (!tableRow) {- return null;- }-- // Include serie name in key to force re-render when name changes- const serieId = tableRow.original.serieId;- const serie = data.series.find((s) => s.id === serieId);- const serieName =- serie?.names[0] ?? tableRow.original.serieName ?? '';-- return (- <VirtualRow- headers={headers}- isResizingRef={isResizingRef}- key={`${virtualRow.key}-${serieName}-${gridTemplateColumns}`}- leftPinnedColumns={leftPinnedColumns}- leftPinnedWidth={leftPinnedWidth}- pinningStylesMap={pinningStylesMap}- resizingColumnId={resizingColumnId}- rightPinnedColumns={rightPinnedColumns}- rightPinnedWidth={rightPinnedWidth}- row={tableRow}- scrollableColumns={scrollableColumns}- scrollableColumnsTotalWidth={scrollableColumnsTotalWidth}- setResizingColumnId={setResizingColumnId}- virtualColumns={virtualColumns}- virtualRow={{- ...virtualRow,- start: virtualRow.start - virtualizer.options.scrollMargin,- }}- />- );- })}- </div>- </div>- </div>- </div>- );-}diff --git a/apps/start/src/components/report-chart/common/series-table.tsx b/apps/start/src/components/report-chart/common/series-table.tsxnew file mode 100644index 000000000..4dcce2c2a--- /dev/null+++ b/apps/start/src/components/report-chart/common/series-table.tsx@@ -0,0 +1,149 @@+import { useCallback, useMemo } from 'react';+import { useReportChartContext } from '../context';+import { PreviousDiffIndicatorPure } from './previous-diff-indicator';+import { SerieIcon } from './serie-icon';+import {+ type ReportColumn,+ ReportDataTable,+ type ReportRowIdentity,+} from '@/components/report-table/report-data-table';+import { useFormatDateInterval } from '@/hooks/use-format-date-interval';+import { useNumber } from '@/hooks/use-numer-formatter';+import type { IChartData } from '@/trpc/client';+import { getChartColor } from '@/utils/theme';++type Serie = IChartData['series'][number];++interface SeriesRow {+ id: string;+ serie: Serie;+ color: string;+ countByDate: Record<string, number>;+}++interface Props {+ data: IChartData;+ visibleIds: ReadonlySet<string>;+ /** Absent on read-only pages, which hides the checkboxes. */+ onToggle?: (id: string) => void;+ onUnselectAll?: () => void;+ onReset?: () => void;+}++const METRIC_COLUMNS = [+ { key: 'count', header: 'Unique' },+ { key: 'sum', header: 'Sum' },+ { key: 'average', header: 'Average' },+ { key: 'min', header: 'Min' },+ { key: 'max', header: 'Max' },+] as const;+const BREAKDOWN_COLUMN_WIDTH = 140;++/** One row per series: its breakdown values, the summary metrics and a heat-shaded cell per period. */+export function SeriesTable({+ data,+ visibleIds,+ onToggle,+ onUnselectAll,+ onReset,+}: Props) {+ const {+ report: { interval, unit, breakdowns, name },+ } = useReportChartContext();+ const number = useNumber();+ const formatDate = useFormatDateInterval({ interval, short: true });+ const formatValue = useCallback(+ (value: number) => number.formatWithUnit(value, unit),+ [number, unit]+ );++ const dates = useMemo(+ () => data.series[0]?.data.map((item) => item.date) ?? [],+ [data.series]+ );+ const rows = useMemo(+ () =>+ data.series.map(+ (serie, index): SeriesRow => ({+ id: serie.id,+ serie,+ color: getChartColor(index),+ countByDate: Object.fromEntries(+ serie.data.map((item) => [item.date, item.count])+ ),+ })+ ),+ [data.series]+ );++ const identity = useMemo<ReportRowIdentity<SeriesRow>>(+ () => ({+ header: 'Series',+ render: (row) => (+ <span className="flex items-center gap-1.5">+ <SerieIcon name={row.serie.names[0] ?? ''} />+ <span className="truncate">{row.serie.names[0]}</span>+ </span>+ ),+ searchText: (row) => row.serie.names.join(' › '),+ color: (row) => row.color,+ }),+ []+ );++ const columns = useMemo<ReportColumn<SeriesRow>[]>(+ () => [+ ...(breakdowns ?? []).map(+ (breakdown, index): ReportColumn<SeriesRow> => ({+ id: `breakdown:${breakdown.name}`,+ header: breakdown.name,+ value: (row) => row.serie.names[index + 1] ?? '',+ format: 'text',+ width: BREAKDOWN_COLUMN_WIDTH,+ })+ ),+ ...METRIC_COLUMNS.map(+ ({ key, header }): ReportColumn<SeriesRow> => ({+ id: key,+ header,+ value: (row) => row.serie.metrics[key],+ render: (row) => {+ const previous = row.serie.metrics.previous?.[key];+ return (+ <span className="flex items-center justify-end gap-2">+ {formatValue(row.serie.metrics[key] ?? 0)}+ {previous && key === 'sum' && (+ <PreviousDiffIndicatorPure {...previous} size="xs" />+ )}+ </span>+ );+ },+ })+ ),+ ...dates.map(+ (date): ReportColumn<SeriesRow> => ({+ id: date,+ header: formatDate(date),+ value: (row) => row.countByDate[date] ?? 0,+ render: (row) => formatValue(row.countByDate[date] ?? 0),+ decorate: 'heat',+ })+ ),+ ],+ [breakdowns, dates, formatDate, formatValue]+ );++ return (+ <ReportDataTable+ columns={columns}+ csvFilename={name || 'report'}+ getRowId={(row) => row.id}+ identity={identity}+ onReset={onReset}+ onToggleRow={onToggle}+ onUnselectAll={onUnselectAll}+ rows={rows}+ selectedIds={visibleIds}+ />+ );+}diff --git a/apps/start/src/components/report-chart/common/series-with-table.tsx b/apps/start/src/components/report-chart/common/series-with-table.tsxnew file mode 100644index 000000000..2eae42956--- /dev/null+++ b/apps/start/src/components/report-chart/common/series-with-table.tsx@@ -0,0 +1,74 @@+import { type ReactNode, useCallback, useMemo } from 'react';+import { useReportChartContext } from '../context';+import { ChartWithTable, TableCard } from './chart-with-table';+import { RankedTable } from './ranked-table';+import { SeriesTable } from './series-table';+import { changeVisibleSeries } from '@/components/report/reportSlice';+import {+ type IVisibleSeries,+ useVisibleSeries,+} from '@/hooks/use-visible-series';+import { useDispatch } from '@/redux';+import type { IChartData } from '@/trpc/client';++/**+ * The chart for the visible series with the series table under it. A+ * dashboard tile shows the chart alone; the editor's table toggles series,+ * the share page's is read-only.+ */+export function SeriesWithTable({+ data,+ chart,+ table = 'series',+}: {+ data: IChartData;+ chart: (series: IVisibleSeries) => ReactNode;+ /** `series` is one row per series with its periods; `ranked` sorts them by value. */+ table?: 'series' | 'ranked';+}) {+ const Table = table === 'ranked' ? RankedTable : SeriesTable;+ const {+ report: { visibleSeries: savedVisibleSeries },+ isEditMode,+ } = useReportChartContext();+ const dispatch = useDispatch();+ const { series, setVisibleSeries, reset, isDefaultSelection } =+ useVisibleSeries(data, {+ savedVisibleSeries,+ onVisibleSeriesChange: isEditMode+ ? (ids) => dispatch(changeVisibleSeries(ids))+ : undefined,+ });+ const visibleIds = useMemo(+ () => new Set(series.map((serie) => serie.id)),+ [series]+ );+ const toggleSeries = useCallback(+ (id: string) =>+ setVisibleSeries((ids) =>+ ids.includes(id) ? ids.filter((item) => item !== id) : [...ids, id]+ ),+ [setVisibleSeries]+ );++ return (+ <ChartWithTable+ chart={chart(series)}+ tables={+ <TableCard>+ <Table+ data={data}+ onReset={isEditMode && !isDefaultSelection ? reset : undefined}+ onToggle={isEditMode ? toggleSeries : undefined}+ onUnselectAll={+ isEditMode && series.length > 0+ ? () => setVisibleSeries([])+ : undefined+ }+ visibleIds={visibleIds}+ />+ </TableCard>+ }+ />+ );+}diff --git a/apps/start/src/components/report-chart/common/stat-strip.tsx b/apps/start/src/components/report-chart/common/stat-strip.tsxnew file mode 100644index 000000000..36e4133c1--- /dev/null+++ b/apps/start/src/components/report-chart/common/stat-strip.tsx@@ -0,0 +1,57 @@+import type { ReactNode } from 'react';+import { cn } from '@/utils/cn';++/** A row of headline numbers in the overview's metric-card style. */+export function StatStrip({+ children,+ className,+ framed = true,+}: {+ children: ReactNode;+ className?: string;+ /** Draw as its own card. Off when the strip sits inside another card. */+ framed?: boolean;+}) {+ return (+ <div+ className={cn(+ 'grid grid-cols-2 overflow-hidden',+ framed && 'card',+ className+ )}+ >+ {children}+ </div>+ );+}++export function Stat({+ label,+ value,+ change,+ detail,+}: {+ label: string;+ value: string;+ change?: ReactNode;+ detail?: ReactNode;+}) {+ return (+ <div className="col min-w-0 gap-1 px-4 py-3 shadow-[0_0_0_0.5px] shadow-border">+ <span className="truncate font-medium text-[10px] text-muted-foreground uppercase tracking-wider">+ {label}+ </span>+ <span className="flex items-baseline gap-2">+ <span className="truncate font-mono font-semibold text-xl tabular-nums tracking-tight">+ {value}+ </span>+ {change}+ </span>+ {detail && (+ <span className="flex min-w-0 items-center gap-1.5 truncate text-[11px] text-muted-foreground">+ {detail}+ </span>+ )}+ </div>+ );+}diff --git a/apps/start/src/components/report-chart/common/time-series.tsx b/apps/start/src/components/report-chart/common/time-series.tsxnew file mode 100644index 000000000..6c34be7c2--- /dev/null+++ b/apps/start/src/components/report-chart/common/time-series.tsx@@ -0,0 +1,260 @@+import type { IChartType } from '@openpanel/core/modules/report/report.constants';+import { useQuery } from '@tanstack/react-query';+import { BookmarkIcon, UsersIcon } from 'lucide-react';+import { type ReactNode, useCallback, useRef } from 'react';+import { useReportChartContext } from '../context';+import {+ ChartClickMenu,+ type ChartClickMenuHandle,+ type ChartClickMenuItem,+} from './chart-click-menu';+import { getCurve } from './curve';+import { SerieIcon } from './serie-icon';+import { SerieName } from './serie-name';+import { useDashedTail } from '@/components/charts/op-dashed-tail';+import type { OPTooltipRow } from '@/components/charts/op-tooltip';+import { formatDateInterval } from '@/hooks/use-format-date-interval';+import { useNumber } from '@/hooks/use-numer-formatter';+import {+ type IRechartPayloadItem,+ useRechartDataModel,+} from '@/hooks/use-rechart-data-model';+import type { IVisibleSeries } from '@/hooks/use-visible-series';+import { useTRPC } from '@/integrations/trpc/react';+import { pushModal } from '@/modals';+import type { IChartData } from '@/trpc/client';+import { cn } from '@/utils/cn';+import { getChartColor } from '@/utils/theme';++const TOOLTIP_SERIES_LIMIT = 3;+const MARKERS_MAX_POINTS = 8;+const PREVIOUS_PERIOD_OPACITY = '30%';+const AXIS_MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };+const BARE_MARGIN = { top: 12, right: 12, bottom: 12, left: 12 };++/** Small point markers for sparse series; bklit's default ring is sized for hero charts. */+export const POINT_MARKER = { radius: 3, strokeWidth: 0, ringGap: 0 };++export type TimeSeriesPoint = Record<string, unknown> & { date: string };++/** What the line, area and histogram report charts share around their bklit chart. */+export function useTimeSeriesChart({+ data,+ series,+ chartType,+}: {+ data: IChartData;+ series: IVisibleSeries;+ chartType: IChartType;+}) {+ const {+ report: {+ previous,+ interval,+ projectId,+ startDate,+ endDate,+ range,+ lineType,+ unit,+ series: reportSeries,+ breakdowns,+ },+ shareId,+ options: { hideXAxis, hideYAxis },+ } = useReportChartContext();+ const trpc = useTRPC();+ const number = useNumber();+ const references = useQuery(+ trpc.reference.getChartReferences.queryOptions({+ projectId,+ startDate,+ endDate,+ range,+ })+ );+ const chartData = useRechartDataModel(series) as TimeSeriesPoint[];+ const dashFromIndex = useDashedTail({ data: chartData, range, interval });++ const formatDateLabel = useCallback(+ (date: Date) => formatDateInterval({ interval, date, short: true }),+ [interval]+ );+ const formatValue = useCallback(+ (value: number) => number.formatWithUnit(value, unit),+ [number, unit]+ );++ const tooltipRows = useCallback(+ (point: TimeSeriesPoint): OPTooltipRow[] =>+ seriesPayloads(point, series)+ .slice(0, TOOLTIP_SERIES_LIMIT)+ .map(({ payload, color }) => ({+ color,+ icon: <SerieIcon name={payload.names} />,+ label: <SerieName name={payload.names} />,+ value: payload.count,+ // An empty previous period comes back without a value; it is 0, not unknown.+ previous: previous ? (payload.previous?.value ?? 0) : undefined,+ format: formatValue,+ })),+ [series, formatValue, previous]+ );+ const tooltipExtra = useCallback(+ (point: TimeSeriesPoint) => {+ const hidden =+ seriesPayloads(point, series).length - TOOLTIP_SERIES_LIMIT;+ if (hidden <= 0) {+ return null;+ }+ return (+ <div className="text-muted-foreground text-sm">+ and {hidden} more...+ </div>+ );+ },+ [series]+ );++ const menuRef = useRef<ChartClickMenuHandle>(null);+ const getMenuItems = useCallback(+ (+ _event: unknown,+ clickedData: TimeSeriesPoint | null+ ): ChartClickMenuItem[] => {+ // Both actions need a signed-in member, which a share visitor is not.+ if (shareId || !clickedData?.date) {+ return [];+ }+ return [+ {+ label: 'View Users',+ icon: <UsersIcon size={16} />,+ onClick: () => {+ pushModal('ViewChartUsers', {+ type: 'chart',+ chartData: data,+ report: {+ projectId,+ series: reportSeries,+ breakdowns: breakdowns || [],+ interval,+ startDate,+ endDate,+ range,+ previous,+ chartType,+ metric: 'sum',+ },+ date: clickedData.date,+ });+ },+ },+ {+ label: 'Add Reference',+ icon: <BookmarkIcon size={16} />,+ onClick: () => {+ pushModal('AddReference', {+ datetime: new Date(clickedData.date).toISOString(),+ });+ },+ },+ ];+ },+ [+ shareId,+ projectId,+ data,+ reportSeries,+ breakdowns,+ interval,+ startDate,+ endDate,+ range,+ previous,+ chartType,+ ]+ );+ const openMenu = useCallback((point: TimeSeriesPoint, event: MouseEvent) => {+ menuRef.current?.openAt(point, event.clientX, event.clientY);+ }, []);++ return {+ chartData,+ references: references.data,+ previous,+ interval,+ hideXAxis,+ hideYAxis,+ dashFromIndex,+ curve: getCurve(lineType),+ showMarkers: chartData.length <= MARKERS_MAX_POINTS,+ margin: hideXAxis && hideYAxis ? BARE_MARGIN : AXIS_MARGIN,+ formatDateLabel,+ formatAxisValue: number.short,+ tooltipRows,+ tooltipExtra,+ menu: { ref: menuRef, getMenuItems, openMenu },+ };+}++export function previousPeriodColor(index: number) {+ return `color-mix(in oklch, ${getChartColor(index)} ${PREVIOUS_PERIOD_OPACITY}, transparent)`;+}++/** The click menu, the card in the editor, and a legend under the chart when there is more than one series. */+export function TimeSeriesFrame({+ chartType,+ series,+ menu,+ children,+}: {+ chartType: IChartType;+ series: IVisibleSeries;+ menu: ReturnType<typeof useTimeSeriesChart>['menu'];+ children: ReactNode;+}) {+ const { isEditMode } = useReportChartContext();+ return (+ <ChartClickMenu getMenuItems={menu.getMenuItems} ref={menu.ref}>+ <div className={cn('col h-full w-full', isEditMode && 'card p-4')}>+ <div+ className="min-h-0 flex-1"+ data-report-chart={chartType}+ data-visible-series={series.length}+ >+ {children}+ </div>+ {series.length > 1 && <SeriesLegend series={series} />}+ </div>+ </ChartClickMenu>+ );+}++function SeriesLegend({ series }: { series: IVisibleSeries }) {+ return (+ <div className="flex shrink-0 flex-wrap justify-center gap-x-4 gap-y-1 pt-2 text-xs">+ {series.map((serie) => (+ <div+ className="flex items-center gap-1"+ key={serie.id}+ style={{ color: getChartColor(serie.index) }}+ >+ <SerieIcon name={serie.names} />+ <SerieName className="font-semibold" name={serie.names} />+ </div>+ ))}+ </div>+ );+}++function seriesPayloads(point: TimeSeriesPoint, series: IVisibleSeries) {+ return series+ .flatMap((serie) => {+ const payload = point[`${serie.id}:payload`] as+ | IRechartPayloadItem+ | undefined;+ return payload ? [{ payload, color: getChartColor(serie.index) }] : [];+ })+ .sort((a, b) => (b.payload.count || 0) - (a.payload.count || 0));+}diff --git a/apps/start/src/components/report-chart/context.tsx b/apps/start/src/components/report-chart/context.tsxindex 9a35edba7..ac3f7672f 100644--- a/apps/start/src/components/report-chart/context.tsx+++ b/apps/start/src/components/report-chart/context.tsx@@ -3,34 +3,31 @@ import type {IReportInput,} from '@openpanel/core/modules/report/report.constants';import isEqual from 'lodash.isequal';-import type { LucideIcon } from 'lucide-react';import { createContext, useContext, useEffect, useMemo, useState } from 'react';-export type ReportChartContextType = {+export interface ReportChartContextType {options: Partial<{columns: React.ReactNode[];hideLegend: boolean;+ /** Show the chart alone, without the series tables an editor shows under it. */+ hideTable: boolean;hideXAxis: boolean;hideYAxis: boolean;aspectRatio: number;maxHeight: number;minHeight: number;- maxDomain: number;- onClick: (serie: IChartSerie) => void;renderSerieName: (names: string[]) => React.ReactNode;renderSerieIcon: (serie: IChartSerie) => React.ReactNode;- dropdownMenuContent: (serie: IChartSerie) => {- icon: LucideIcon;- title: string;- onClick: () => void;- }[];}>;report: IReportInput & { id?: string };isLazyLoading: boolean;isEditMode: boolean;+ // `fill` takes the parent's height (a dashboard tile); `aspect` sizes the+ // chart from its width (the editor, chat, modals, share pages).+ layout: 'fill' | 'aspect';shareId?: string;reportId?: string;-};+}type ReportChartContextProviderProps = ReportChartContextType & {children: React.ReactNode;diff --git a/apps/start/src/components/report-chart/conversion/chart.tsx b/apps/start/src/components/report-chart/conversion/chart.tsxindex 0562c64be..2b6bd7b3a 100644--- a/apps/start/src/components/report-chart/conversion/chart.tsx+++ b/apps/start/src/components/report-chart/conversion/chart.tsx@@ -1,69 +1,53 @@-import type { IInterval } from '@openpanel/core/modules/report/report.constants';import { average, round } from '@openpanel/shared';import { useQuery } from '@tanstack/react-query';-import React, { useCallback, useMemo } from 'react';-import {- CartesianGrid,- Legend,- Line,- LineChart,- ReferenceLine,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';-import { getPreviousMetric } from '../../../utils/previous-metric';-import { useXAxisProps, useYAxisProps } from '../common/axis';-import { PreviousDiffIndicator } from '../common/previous-diff-indicator';+import { useCallback, useMemo } from 'react';+import { getCurve } from '../common/curve';+import { PointClick } from '../common/point-click';import { SerieIcon } from '../common/serie-icon';import { SerieName } from '../common/serie-name';+import { POINT_MARKER, previousPeriodColor } from '../common/time-series';import { useReportChartContext } from '../context';-import { ConversionTable } from './conversion-table';+import { Grid } from '@/components/charts/grid';+import { Line, LineChart } from '@/components/charts/line-chart';+import { OPReferences } from '@/components/charts/op-references';import {- ChartTooltipHeader,- ChartTooltipItem,- createChartTooltip,-} from '@/components/charts/chart-tooltip';-import { changeVisibleSeries } from '@/components/report/reportSlice';+ OPChartTooltip,+ type OPTooltipRow,+} from '@/components/charts/op-tooltip';+import { XAxis } from '@/components/charts/x-axis';+import { YAxis } from '@/components/charts/y-axis';import { useConversionRechartDataModel } from '@/hooks/use-conversion-rechart-data-model';-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';+import { formatDateInterval } from '@/hooks/use-format-date-interval';import { useNumber } from '@/hooks/use-numer-formatter';-import { useVisibleConversionSeries } from '@/hooks/use-visible-conversion-series';import { useTRPC } from '@/integrations/trpc/react';import { pushModal } from '@/modals';-import { useDispatch } from '@/redux';import type { RouterOutputs } from '@/trpc/client';import { cn } from '@/utils/cn';import { getChartColor } from '@/utils/theme';-interface Props {- data: RouterOutputs['chart']['conversion'];-}+const AXIS_MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };+const BARE_MARGIN = { top: 12, right: 12, bottom: 12, left: 12 };+const MARKERS_MAX_POINTS = 30;+const PERCENT_DOMAIN: [number, number] = [0, 100];++type ConversionSeries = RouterOutputs['chart']['conversion']['current'];+type ConversionPoint = Record<string, unknown> & { date: string };-export function Chart({ data }: Props) {+const seriesNames = (serie: ConversionSeries[number]) =>+ serie.breakdowns.length > 0 ? serie.breakdowns : ['Conversion'];++export function Chart({+ series,+}: {+ series: (ConversionSeries[number] & { index: number })[];+}) {const {- report: {- interval,- projectId,- startDate,- endDate,- range,- lineType,- visibleSeries: savedVisibleSeries,- },+ report: { interval, projectId, startDate, endDate, range, lineType },isEditMode,shareId,- options: { hideXAxis, hideYAxis, maxDomain },+ options: { hideXAxis, hideYAxis },} = useReportChartContext();- const dispatch = useDispatch();- const { series, setVisibleSeries } = useVisibleConversionSeries(data, {- limit: 5,- savedVisibleSeries,- onVisibleSeriesChange: isEditMode- ? (ids) => dispatch(changeVisibleSeries(ids))- : undefined,- });- const rechartData = useConversionRechartDataModel(series);+ const number = useNumber();const trpc = useTRPC();const references = useQuery(trpc.reference.getChartReferences.queryOptions({@@ -73,261 +57,154 @@ export function Chart({ data }: Props) {range,}));-- const xAxisProps = useXAxisProps({ interval, hide: hideXAxis });- const number = useNumber();-- // Calculate dynamic Y-axis domain based on max rate- const yAxisDomain = useMemo(() => {- if (!series.length) {- return [0, 100];- }-- const maxRate = Math.max(- ...series.flatMap((serie) => serie.data.map((item) => item.rate))- );-- if (maxRate <= 5) {- return [0, 10];- }- if (maxRate <= 20) {- return [0, 30];- }- if (maxRate <= 50) {- return [0, 60];- }- return [0, 100];- }, [series]);-- const yAxisProps = useYAxisProps({- hide: hideYAxis,- tickFormatter: (value: number) => {- return `${number.short(value)}%`;- },- });-- const averageConversionRate = average(- series.map((serie) => {- return average(serie.data.map((item) => item.rate));- }, 0)+ const averageRate = average(+ series.map((serie) =>+ average(+ serie.data.map((item) => item.rate),+ true+ )+ ),+ true);+ const averageColor = getChartColor(series.length);+ const rechartData = useConversionRechartDataModel(series);+ const chartData = useMemo(+ () =>+ rechartData.map(+ (point): ConversionPoint => ({+ ...point,+ date: String(point.date),+ average: averageRate,+ })+ ),+ [rechartData, averageRate]+ );+ const curve = getCurve(lineType);- // Show dots when we have 30 or fewer data points- const showDots = rechartData.length <= 30;-- const handleChartClick = useCallback((e: any) => {- if (e?.activePayload?.[0]) {- const clickedData = e.activePayload[0].payload;- if (clickedData.date) {- pushModal('AddReference', {- datetime: new Date(clickedData.date).toISOString(),- });- }- }+ const formatDateLabel = useCallback(+ (date: Date) => formatDateInterval({ interval, date, short: true }),+ [interval]+ );+ const formatRate = useCallback(+ (rate: number) => number.formatWithUnit(rate / 100, '%'),+ [number]+ );+ const tooltipRows = useCallback(+ (point: ConversionPoint): OPTooltipRow[] =>+ series.flatMap((serie) => {+ const rate = point[`${serie.id}:rate`];+ if (typeof rate !== 'number') {+ return [];+ }+ const previous = point[`${serie.id}:previousRate`];+ return [+ {+ color: getChartColor(serie.index),+ icon: <SerieIcon name={seriesNames(serie)} />,+ label: <SerieName name={seriesNames(serie)} />,+ value: rate,+ previous: typeof previous === 'number' ? previous : undefined,+ format: formatRate,+ sub: [+ { label: 'Total', value: Number(point[`${serie.id}:total`]) },+ ],+ },+ ];+ }),+ [series, formatRate]+ );+ const addReference = useCallback((point: ConversionPoint) => {+ pushModal('AddReference', {+ datetime: new Date(point.date).toISOString(),+ });}, []);- const CustomLegend = useCallback(() => {- return (- <div className="mt-4 -mb-2 flex flex-wrap justify-center gap-x-4 gap-y-1 text-xs">- {series.map((serie) => (- <div- className="flex items-center gap-1"- key={serie.id}- style={{- color: getChartColor(serie.index),- }}- >- <SerieIcon name={serie.breakdowns} />- <SerieName- className="font-semibold"- name={- serie.breakdowns.length > 0 ? serie.breakdowns : ['Conversion']- }- />- </div>- ))}- </div>- );- }, [series]);-return (- <TooltipProvider- conversion={data}- interval={interval}- visibleSeries={series}- >- <div className={cn('h-full w-full', isEditMode && 'card p-4')}>- <ResponsiveContainer>- <LineChart- data={rechartData}- onClick={shareId ? undefined : handleChartClick}- >- <CartesianGrid- className="stroke-border"- horizontal={true}- strokeDasharray="3 3"- vertical={false}+ <div className={cn('col h-full w-full', isEditMode && 'card p-4')}>+ <div+ className="relative min-h-0 flex-1"+ data-report-chart="conversion"+ data-visible-series={series.length}+ >+ <LineChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-full"+ data={chartData}+ formatDateLabel={formatDateLabel}+ margin={hideXAxis && hideYAxis ? BARE_MARGIN : AXIS_MARGIN}+ style={{ touchAction: 'pan-y' }}+ xDataKey="date"+ yDomain={PERCENT_DOMAIN}+ >+ <Grid horizontal />+ {!hideYAxis && (+ <YAxis formatValue={(value) => `${number.short(value)}%`} />+ )}+ {!hideXAxis && <XAxis />}+ {series.map((serie) => (+ <Line+ animate={false}+ curve={curve}+ dataKey={`${serie.id}:previousRate`}+ key={`${serie.id}:previousRate`}+ showHighlight={false}+ stroke={previousPeriodColor(serie.index)}+ strokeWidth={1}/>- {references.data?.map((ref) => (- <ReferenceLine- fontSize={10}- key={ref.id}- label={{- value: ref.title,- position: 'centerTop',- fill: '#334155',- fontSize: 12,- }}- stroke={'oklch(from var(--foreground) l c h / 0.1)'}- strokeDasharray={'3 3'}- x={ref.date.getTime()}- />- ))}- <YAxis {...yAxisProps} domain={yAxisDomain} />- <XAxis {...xAxisProps} allowDuplicatedCategory={false} />- {series.length > 1 && <Legend content={<CustomLegend />} />}- <Tooltip />- {series.map((serie) => {- const color = getChartColor(serie.index);- return (- <Line- dataKey={`${serie.id}:previousRate`}- dot={false}- isAnimationActive={false}- key={`${serie.id}:previousRate`}- stroke={color}- strokeOpacity={0.3}- strokeWidth={1}- type={lineType}- />- );- })}- {series.map((serie) => {- const color = getChartColor(serie.index);- return (- <Line- activeDot={showDots ? { r: 5, strokeWidth: 2 } : { r: 4 }}- dataKey={`${serie.id}:rate`}- dot={- showDots ? { r: 3, strokeWidth: 2, fill: 'white' } : false- }- isAnimationActive={false}- key={`${serie.id}:rate`}- stroke={color}- strokeWidth={2}- type={lineType}- />- );- })}- {typeof averageConversionRate === 'number' &&- averageConversionRate && (- <ReferenceLine- label={{- value: `Average (${round(averageConversionRate, 2)}%)`,- fill: getChartColor(series.length),- position: 'insideBottomRight',- fontSize: 13,- fontWeight: 500,- }}- stroke={getChartColor(series.length)}- strokeDasharray="3 3"- strokeLinecap="round"- strokeOpacity={0.6}- strokeWidth={2}- y={averageConversionRate}- />- )}- </LineChart>- </ResponsiveContainer>+ ))}+ {series.map((serie) => (+ <Line+ animate={false}+ curve={curve}+ dataKey={`${serie.id}:rate`}+ key={`${serie.id}:rate`}+ markers={POINT_MARKER}+ showMarkers={chartData.length <= MARKERS_MAX_POINTS}+ stroke={getChartColor(serie.index)}+ strokeWidth={2}+ />+ ))}+ <Line+ animate={false}+ dashArray="4,4"+ dashFromIndex={0}+ dataKey="average"+ showHighlight={false}+ stroke={averageColor}+ strokeWidth={1.5}+ />+ <OPReferences items={references.data} />+ <OPChartTooltip<ConversionPoint>+ interval={interval}+ references={references.data}+ rows={tooltipRows}+ showCrosshair+ showDots+ />+ {!shareId && <PointClick<ConversionPoint> onClick={addReference} />}+ </LineChart>+ <div+ className="pointer-events-none absolute top-0 right-3 font-medium text-xs"+ style={{ color: averageColor }}+ >+ Average ({round(averageRate, 2)}%)+ </div></div>- <ConversionTable- data={data}- setVisibleSeries={setVisibleSeries}- visibleSeries={series}- />- </TooltipProvider>+ {series.length > 1 && (+ <div className="flex shrink-0 flex-wrap justify-center gap-x-4 gap-y-1 pt-2 text-xs">+ {series.map((serie) => (+ <div+ className="flex items-center gap-1"+ key={serie.id}+ style={{ color: getChartColor(serie.index) }}+ >+ <SerieIcon name={seriesNames(serie)} />+ <SerieName className="font-semibold" name={seriesNames(serie)} />+ </div>+ ))}+ </div>+ )}+ </div>);}--const { Tooltip, TooltipProvider } = createChartTooltip<- Record<string, any>,- {- conversion: RouterOutputs['chart']['conversion'];- interval: IInterval;- visibleSeries: RouterOutputs['chart']['conversion']['current'];- }->(({ data, context }) => {- if (!(data && data[0])) {- return null;- }-- const payload = data[0];- const { date } = payload;- const formatDate = useFormatDateInterval({- interval: context.interval,- short: false,- });- const number = useNumber();-- return (- <>- {context.visibleSeries.map((serie, index) => {- const rate = payload[`${serie.id}:rate`];- const total = payload[`${serie.id}:total`];- const previousRate = payload[`${serie.id}:previousRate`];-- if (rate === undefined) {- return null;- }-- const prevSerie = context.conversion?.previous?.find(- (p) => p.id === serie.id- );- const prevItem = prevSerie?.data.find((d) => d.date === date);- const previousMetric = getPreviousMetric(rate, previousRate);-- return (- <React.Fragment key={serie.id}>- {index === 0 && (- <ChartTooltipHeader>- <div>{formatDate(date)}</div>- </ChartTooltipHeader>- )}- <ChartTooltipItem color={getChartColor(index)}>- <div className="flex items-center gap-1">- <SerieIcon- name={- serie.breakdowns.length > 0- ? serie.breakdowns- : ['Conversion']- }- />- <SerieName- name={- serie.breakdowns.length > 0- ? serie.breakdowns- : ['Conversion']- }- />- </div>- <div className="flex justify-between gap-8 font-medium font-mono">- <div className="row gap-1">- <span>{number.formatWithUnit(rate / 100, '%')}</span>- <span className="text-muted-foreground">({total})</span>- {prevItem && previousRate !== undefined && (- <span className="text-muted-foreground">- ({number.formatWithUnit(previousRate / 100, '%')})- </span>- )}- </div>- {previousRate !== undefined && (- <PreviousDiffIndicator {...previousMetric} />- )}- </div>- </ChartTooltipItem>- </React.Fragment>- );- })}- </>- );-});diff --git a/apps/start/src/components/report-chart/conversion/conversion-table.tsx b/apps/start/src/components/report-chart/conversion/conversion-table.tsxdeleted file mode 100644index 1d3ab982f..000000000--- a/apps/start/src/components/report-chart/conversion/conversion-table.tsx+++ /dev/null@@ -1,518 +0,0 @@-import type { SortingState } from '@tanstack/react-table';-import { useMemo, useState } from 'react';-import { getPreviousMetric } from '../../../utils/previous-metric';-import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';-import { ReportTableToolbar } from '../common/report-table-toolbar';-import { SerieIcon } from '../common/serie-icon';-import { SerieName } from '../common/serie-name';-import { Checkbox } from '@/components/ui/checkbox';-import { useFormatDateInterval } from '@/hooks/use-format-date-interval';-import { useNumber } from '@/hooks/use-numer-formatter';-import { useSelector } from '@/redux';-import type { RouterOutputs } from '@/trpc/client';-import { cn } from '@/utils/cn';-import { getChartColor } from '@/utils/theme';--interface ConversionTableProps {- data: RouterOutputs['chart']['conversion'];- visibleSeries: RouterOutputs['chart']['conversion']['current'];- setVisibleSeries: React.Dispatch<React.SetStateAction<string[]>>;-}--export function ConversionTable({- data,- visibleSeries,- setVisibleSeries,-}: ConversionTableProps) {- const [sorting, setSorting] = useState<SortingState>([]);- const [globalFilter, setGlobalFilter] = useState('');- const number = useNumber();- const interval = useSelector((state) => state.report.interval);- const formatDate = useFormatDateInterval({- interval,- short: true,- });-- const dates = useMemo(- () => data.current[0]?.data.map((item) => item.date) ?? [],- [data.current]- );-- // Get all series (including non-visible ones for toggle functionality)- const allSeries = data.current;-- const rows = useMemo(() => {- return allSeries.map((serie) => {- const dateValues: Record<string, number> = {};- dates.forEach((date) => {- const item = serie.data.find((d) => d.date === date);- dateValues[date] = item?.rate ?? 0;- });-- const total = serie.data.reduce((sum, item) => sum + item.total, 0);- const conversions = serie.data.reduce(- (sum, item) => sum + item.conversions,- 0- );- const avgRate =- serie.data.length > 0- ? serie.data.reduce((sum, item) => sum + item.rate, 0) /- serie.data.length- : 0;-- const prevSerie = data.previous?.find((p) => p.id === serie.id);- const prevAvgRate =- prevSerie && prevSerie.data.length > 0- ? prevSerie.data.reduce((sum, item) => sum + item.rate, 0) /- prevSerie.data.length- : undefined;-- return {- id: serie.id,- serieId: serie.id,- serieName:- serie.breakdowns.length > 0 ? serie.breakdowns : ['Conversion'],- breakdownValues: serie.breakdowns,- avgRate,- prevAvgRate,- total,- conversions,- dateValues,- };- });- }, [allSeries, dates, data.previous]);-- const { metricRanges, dateRanges } = useMemo(() => {- const metricRanges: Record<string, { min: number; max: number }> = {- avgRate: {- min: Number.POSITIVE_INFINITY,- max: Number.NEGATIVE_INFINITY,- },- total: {- min: Number.POSITIVE_INFINITY,- max: Number.NEGATIVE_INFINITY,- },- conversions: {- min: Number.POSITIVE_INFINITY,- max: Number.NEGATIVE_INFINITY,- },- };-- const dateRanges: Record<string, { min: number; max: number }> = {};- dates.forEach((date) => {- dateRanges[date] = {- min: Number.POSITIVE_INFINITY,- max: Number.NEGATIVE_INFINITY,- };- });-- rows.forEach((row) => {- metricRanges.avgRate.min = Math.min(- metricRanges.avgRate.min,- row.avgRate- );- metricRanges.avgRate.max = Math.max(- metricRanges.avgRate.max,- row.avgRate- );- metricRanges.total.min = Math.min(metricRanges.total.min, row.total);- metricRanges.total.max = Math.max(metricRanges.total.max, row.total);- metricRanges.conversions.min = Math.min(- metricRanges.conversions.min,- row.conversions- );- metricRanges.conversions.max = Math.max(- metricRanges.conversions.max,- row.conversions- );-- dates.forEach((date) => {- const value = row.dateValues[date] ?? 0;- dateRanges[date]!.min = Math.min(dateRanges[date]!.min, value);- dateRanges[date]!.max = Math.max(dateRanges[date]!.max, value);- });- });-- return { metricRanges, dateRanges };- }, [rows, dates]);-- const getCellBackgroundStyle = (- value: number,- min: number,- max: number,- colorClass: 'purple' | 'emerald' = 'emerald'- ): React.CSSProperties => {- if (value === 0 || max === min) {- return {};- }-- const percentage = (value - min) / (max - min);- const opacity = Math.max(0.05, Math.min(1, percentage));-- const backgroundColor =- colorClass === 'purple'- ? `rgba(168, 85, 247, ${opacity})`- : `rgba(16, 185, 129, ${opacity})`;-- return { backgroundColor };- };-- const visibleSeriesIds = useMemo(- () => visibleSeries.map((s) => s.id),- [visibleSeries]- );-- const getSerieIndex = (serieId: string): number => {- return allSeries.findIndex((s) => s.id === serieId);- };-- const toggleSerieVisibility = (serieId: string) => {- setVisibleSeries((prev) => {- if (prev.includes(serieId)) {- return prev.filter((id) => id !== serieId);- }- return [...prev, serieId];- });- };-- // Filter and sort rows- const filteredAndSortedRows = useMemo(() => {- let result = rows;-- // Apply search filter- if (globalFilter.trim()) {- const searchLower = globalFilter.toLowerCase();- result = rows.filter((row) => {- if (- row.serieName.some((name) =>- name?.toLowerCase().includes(searchLower)- )- ) {- return true;- }-- if (- row.breakdownValues.some((val) =>- val?.toLowerCase().includes(searchLower)- )- ) {- return true;- }-- if (- String(row.avgRate).toLowerCase().includes(searchLower) ||- String(row.total).toLowerCase().includes(searchLower) ||- String(row.conversions).toLowerCase().includes(searchLower)- ) {- return true;- }-- if (- Object.values(row.dateValues).some((val) =>- String(val).toLowerCase().includes(searchLower)- )- ) {- return true;- }-- return false;- });- }-- // Apply sorting- if (sorting.length > 0) {- result = [...result].sort((a, b) => {- for (const sort of sorting) {- const { id, desc } = sort;- let aValue: any;- let bValue: any;-- if (id === 'serie-name') {- aValue = a.serieName.join(' > ') ?? '';- bValue = b.serieName.join(' > ') ?? '';- } else if (id === 'metric-avgRate') {- aValue = a.avgRate ?? 0;- bValue = b.avgRate ?? 0;- } else if (id === 'metric-total') {- aValue = a.total ?? 0;- bValue = b.total ?? 0;- } else if (id === 'metric-conversions') {- aValue = a.conversions ?? 0;- bValue = b.conversions ?? 0;- } else if (id.startsWith('date-')) {- const date = id.replace('date-', '');- aValue = a.dateValues[date] ?? 0;- bValue = b.dateValues[date] ?? 0;- } else {- continue;- }-- // Handle null/undefined values- if (aValue == null && bValue == null) {- continue;- }- if (aValue == null) {- return 1;- }- if (bValue == null) {- return -1;- }-- if (typeof aValue === 'string' && typeof bValue === 'string') {- const comparison = aValue.localeCompare(bValue);- if (comparison !== 0) {- return desc ? -comparison : comparison;- }- } else {- if (aValue < bValue) {- return desc ? 1 : -1;- }- if (aValue > bValue) {- return desc ? -1 : 1;- }- }- }- return 0;- });- }-- return result;- }, [rows, globalFilter, sorting]);-- const handleSort = (columnId: string) => {- setSorting((prev) => {- const existingSort = prev.find((s) => s.id === columnId);- if (existingSort) {- if (existingSort.desc) {- // Toggle to ascending if already descending- return [{ id: columnId, desc: false }];- }- // Remove sort if already ascending- return [];- }- // Start with descending (highest first)- return [{ id: columnId, desc: true }];- });- };-- const getSortIcon = (columnId: string) => {- const sort = sorting.find((s) => s.id === columnId);- if (!sort) {- return '⇅';- }- return sort.desc ? '↓' : '↑';- };-- if (allSeries.length === 0) {- return null;- }-- return (- <div className="mt-8 flex flex-col overflow-hidden rounded-lg border bg-card">- <ReportTableToolbar- onSearchChange={setGlobalFilter}- onUnselectAll={() => setVisibleSeries([])}- search={globalFilter}- />- <div- className="overflow-x-auto overflow-y-auto"- style={{- width: '100%',- maxHeight: '600px',- }}- >- <table className="w-full" style={{ minWidth: 'fit-content' }}>- <thead className="sticky top-0 z-10 border-b bg-muted/30">- <tr>- <th- className="sticky left-0 z-20 h-10 min-w-[200px] whitespace-nowrap border-border border-r bg-card px-4 text-left font-semibold text-[10px] uppercase"- style={{- boxShadow: '2px 0 4px -2px var(--border)',- }}- >- <div className="flex items-center">Serie</div>- </th>- <th- className="h-10 min-w-[100px] cursor-pointer select-none whitespace-nowrap border-border border-r px-4 text-right font-semibold text-[10px] uppercase hover:bg-muted/50"- onClick={() => handleSort('metric-avgRate')}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- handleSort('metric-avgRate');- }- }}- >- <div className="flex items-center justify-end gap-1.5">- Avg Rate- <span className="text-muted-foreground">- {getSortIcon('metric-avgRate')}- </span>- </div>- </th>- <th- className="h-10 min-w-[100px] cursor-pointer select-none whitespace-nowrap border-border border-r px-4 text-right font-semibold text-[10px] uppercase hover:bg-muted/50"- onClick={() => handleSort('metric-total')}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- handleSort('metric-total');- }- }}- >- <div className="flex items-center justify-end gap-1.5">- Total- <span className="text-muted-foreground">- {getSortIcon('metric-total')}- </span>- </div>- </th>- <th- className="h-10 min-w-[100px] cursor-pointer select-none whitespace-nowrap border-border border-r px-4 text-right font-semibold text-[10px] uppercase hover:bg-muted/50"- onClick={() => handleSort('metric-conversions')}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- handleSort('metric-conversions');- }- }}- >- <div className="flex items-center justify-end gap-1.5">- Conversions- <span className="text-muted-foreground">- {getSortIcon('metric-conversions')}- </span>- </div>- </th>- {dates.map((date) => (- <th- className="h-10 min-w-[100px] cursor-pointer select-none whitespace-nowrap border-border border-r px-4 text-right font-semibold text-[10px] uppercase hover:bg-muted/50"- key={date}- onClick={() => handleSort(`date-${date}`)}- onKeyDown={(e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- handleSort(`date-${date}`);- }- }}- >- <div className="flex items-center justify-end gap-1.5">- {formatDate(date)}- <span className="text-muted-foreground">- {getSortIcon(`date-${date}`)}- </span>- </div>- </th>- ))}- </tr>- </thead>- <tbody>- {filteredAndSortedRows.map((row) => {- const isVisible = visibleSeriesIds.includes(row.serieId);- const serieIndex = getSerieIndex(row.serieId);- const color = getChartColor(serieIndex);- const previousMetric =- row.prevAvgRate !== undefined- ? getPreviousMetric(row.avgRate, row.prevAvgRate)- : null;-- return (- <tr- className={cn(- 'border-b transition-colors hover:bg-muted/30',- !isVisible && 'opacity-50'- )}- key={row.id}- >- <td- className="sticky left-0 z-10 border-border border-r px-4 py-3"- style={{- backgroundColor: 'var(--card)',- boxShadow: '2px 0 4px -2px var(--border)',- }}- >- <div className="flex items-center gap-2">- <Checkbox- checked={isVisible}- className="h-4 w-4 shrink-0"- onCheckedChange={() =>- toggleSerieVisibility(row.serieId)- }- style={{- borderColor: color,- backgroundColor: isVisible ? color : 'transparent',- }}- />- <div- className="w-[3px] shrink-0 rounded-full"- style={{ background: color }}- />- <SerieIcon name={row.serieName} />- <SerieName className="truncate" name={row.serieName} />- </div>- </td>- <td- className="px-4 py-3 text-right font-mono text-sm"- style={getCellBackgroundStyle(- row.avgRate,- metricRanges.avgRate.min,- metricRanges.avgRate.max,- 'purple'- )}- >- <div className="flex items-center justify-end gap-2">- <span>- {number.formatWithUnit(row.avgRate / 100, '%')}- </span>- {previousMetric && (- <PreviousDiffIndicatorPure {...previousMetric} />- )}- </div>- </td>- <td- className="px-4 py-3 text-right font-mono text-sm"- style={getCellBackgroundStyle(- row.total,- metricRanges.total.min,- metricRanges.total.max,- 'purple'- )}- >- {number.format(row.total)}- </td>- <td- className="px-4 py-3 text-right font-mono text-sm"- style={getCellBackgroundStyle(- row.conversions,- metricRanges.conversions.min,- metricRanges.conversions.max,- 'purple'- )}- >- {number.format(row.conversions)}- </td>- {dates.map((date) => {- const value = row.dateValues[date] ?? 0;- return (- <td- className="px-4 py-3 text-right font-mono text-sm"- key={date}- style={getCellBackgroundStyle(- value,- dateRanges[date]!.min,- dateRanges[date]!.max,- 'emerald'- )}- >- {number.formatWithUnit(value / 100, '%')}- </td>- );- })}- </tr>- );- })}- </tbody>- </table>- </div>- </div>- );-}diff --git a/apps/start/src/components/report-chart/conversion/index.tsx b/apps/start/src/components/report-chart/conversion/index.tsxindex 0b236844f..4d11a4cc1 100644--- a/apps/start/src/components/report-chart/conversion/index.tsx+++ b/apps/start/src/components/report-chart/conversion/index.tsx@@ -1,12 +1,21 @@import { keepPreviousData, useQuery } from '@tanstack/react-query';+import { useCallback, useMemo } from 'react';import { AspectContainer } from '../aspect-container';+import { ChartWithTable, TableCard } from '../common/chart-with-table';import { ReportChartEmpty } from '../common/empty';import { ReportChartError } from '../common/error';import { ReportChartLoading } from '../common/loading';import { useChartInput, useReportChartContext } from '../context';import { Chart } from './chart';import { Summary } from './summary';+import { ConversionTable } from './table';+import { changeVisibleSeries } from '@/components/report/reportSlice';+import { useVisibleConversionSeries } from '@/hooks/use-visible-conversion-series';import { useTRPC } from '@/integrations/trpc/react';+import { useDispatch } from '@/redux';+import type { RouterOutputs } from '@/trpc/client';++const VISIBLE_SERIES_LIMIT = 5;export function ReportConversionChart() {const { isLazyLoading, shareId } = useReportChartContext();@@ -41,13 +50,60 @@ export function ReportConversionChart() {return <Empty />;}+ return <ConversionWithTable data={res.data} />;+}++function ConversionWithTable({+ data,+}: {+ data: RouterOutputs['chart']['conversion'];+}) {+ const {+ report: { visibleSeries: savedVisibleSeries },+ isEditMode,+ } = useReportChartContext();+ const dispatch = useDispatch();+ const { series, setVisibleSeries, reset, isDefaultSelection } =+ useVisibleConversionSeries(data, {+ limit: VISIBLE_SERIES_LIMIT,+ savedVisibleSeries,+ onVisibleSeriesChange: isEditMode+ ? (ids) => dispatch(changeVisibleSeries(ids))+ : undefined,+ });++ const visibleIds = useMemo(+ () => new Set(series.map((serie) => serie.id)),+ [series]+ );+ const toggleSeries = useCallback(+ (id: string) =>+ setVisibleSeries((ids) =>+ ids.includes(id) ? ids.filter((item) => item !== id) : [...ids, id]+ ),+ [setVisibleSeries]+ );+return (- <div>- <Summary data={res.data} />- <AspectContainer>- <Chart data={res.data} />- </AspectContainer>- </div>+ <ChartWithTable+ chart={<Chart series={series} />}+ summary={<Summary data={data} />}+ tables={+ <TableCard>+ <ConversionTable+ data={data}+ onReset={isEditMode && !isDefaultSelection ? reset : undefined}+ onToggle={isEditMode ? toggleSeries : undefined}+ onUnselectAll={+ isEditMode && series.length > 0+ ? () => setVisibleSeries([])+ : undefined+ }+ visibleIds={visibleIds}+ />+ </TableCard>+ }+ />);}diff --git a/apps/start/src/components/report-chart/conversion/summary.tsx b/apps/start/src/components/report-chart/conversion/summary.tsxindex 431239b07..f0874216e 100644--- a/apps/start/src/components/report-chart/conversion/summary.tsx+++ b/apps/start/src/components/report-chart/conversion/summary.tsx@@ -1,227 +1,191 @@import { average, sum } from '@openpanel/shared';-import {- ArrowDownRight,- ArrowUpRight,- GitBranch,- Hash,- Percent,- Target,- Trophy,-} from 'lucide-react';-import type React from 'react';import { useMemo } from 'react';+import { getPreviousMetric } from '../../../utils/previous-metric';+import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';+import { SerieIcon } from '../common/serie-icon';+import { Stat, StatStrip } from '../common/stat-strip';import { useReportChartContext } from '../context';import { useNumber } from '@/hooks/use-numer-formatter';import type { RouterOutputs } from '@/trpc/client';+import { cn } from '@/utils/cn';import { formatDate } from '@/utils/date';-const SUMMARY_ICONS: Record<- string,- React.ComponentType<{ className?: string }>-> = {- Flow: GitBranch,- 'Average conversion rate': Percent,- 'Total conversions': Target,- 'Previous period average conversion rate': Percent,- 'Previous period total conversions': Hash,- 'Best breakdown (avg)': Trophy,- 'Worst breakdown (avg)': ArrowDownRight,- 'Best conversion rate': ArrowUpRight,- 'Worst conversion rate': ArrowDownRight,-};+type ConversionData = RouterOutputs['chart']['conversion'];+type Serie = ConversionData['current'][number];+type Point = Serie['data'][number];interface Props {- data: RouterOutputs['chart']['conversion'];+ data: ConversionData;}+interface DayMatch {+ serie: Serie;+ point: Point;+}++const averageRate = (serie: { data: { rate: number }[] }) =>+ average(+ serie.data.map((item) => item.rate),+ true+ );++/** The report's headline numbers: overall conversion, how many converted, and the best and worst day and breakdown. */export function Summary({ data }: Props) {const number = useNumber();const { report } = useReportChartContext();+ const hasBreakdowns = data.current.length > 1;+ const flow = report.series+ .filter((item) => item.type === 'event')+ .map((item) => item.displayName || item.name)+ .join(' → ');- const bestConversionRateMatch = useMemo(() => {- return data.current.reduce(- (acc, serie, serieIndex) => {- const serieMax = serie.data.reduce(- (maxInSerie, item, dataIndex) => {- if (item.rate > maxInSerie.rate) {- return { rate: item.rate, serieIndex, dataIndex };- }- return maxInSerie;- },- { rate: 0, serieIndex, dataIndex: 0 }- );-- return serieMax.rate > acc.rate ? serieMax : acc;- },- {- rate: 0,- serieIndex: 0,- dataIndex: 0,- }+ const stats = useMemo(() => {+ const conversions = sumOf(data.current, 'conversions');+ const opportunities = sumOf(data.current, 'total');+ const previousConversions = data.previous?.length+ ? sumOf(data.previous, 'conversions')+ : null;+ const previousOpportunities = data.previous?.length+ ? sumOf(data.previous, 'total')+ : null;+ // Conversions over opportunities, not a mean of daily rates: a day with+ // one visitor should not weigh as much as a day with a hundred.+ const rate = overallRate(conversions, opportunities);+ const previousRate =+ previousConversions === null || previousOpportunities === null+ ? null+ : overallRate(previousConversions, previousOpportunities);+ const days = data.current.flatMap((serie) =>+ serie.data+ .filter((point) => point.total > 0)+ .map((point): DayMatch => ({ serie, point })));- }, [data.current]);-- const worstConversionRateMatch = useMemo(() => {- return data.current.reduce(- (acc, serie, serieIndex) => {- const serieMin = serie.data.reduce(- (minInSerie, item, dataIndex) => {- if (item.rate < minInSerie.rate) {- return { rate: item.rate, serieIndex, dataIndex };- }- return minInSerie;- },- { rate: 100, serieIndex, dataIndex: 0 }- );-- return serieMin.rate < acc.rate ? serieMin : acc;- },- {- rate: 100,- serieIndex: 0,- dataIndex: 0,- }+ const bySerie = [...data.current].sort(+ (a, b) => averageRate(b) - averageRate(a));- }, [data.current]);- const bestConversionRate =- data.current[bestConversionRateMatch.serieIndex]?.data[- bestConversionRateMatch.dataIndex- ];- const worstConversionRate =- data.current[worstConversionRateMatch.serieIndex]?.data[- worstConversionRateMatch.dataIndex- ];+ return {+ rate,+ previousRate,+ conversions,+ previousConversions,+ opportunities,+ bestDay: maxBy(days, (day) => day.point.rate),+ worstDay: minBy(days, (day) => day.point.rate),+ bestSerie: bySerie[0],+ worstSerie: bySerie.at(-1),+ };+ }, [data]);- const bestAverageConversionRateMatch = data.current.reduce(- (acc, serie) => {- const averageRate = average(serie.data.map((item) => item.rate));- return averageRate > acc.averageRate ? { serie, averageRate } : acc;- },- { serie: data.current[0], averageRate: 0 }- );- const worstAverageConversionRateMatch = data.current.reduce(- (acc, serie) => {- const averageRate = average(serie.data.map((item) => item.rate));- return averageRate < acc.averageRate ? { serie, averageRate } : acc;- },- { serie: data.current[0], averageRate: 100 }+ const formatRate = (value: number) => number.formatWithUnit(value / 100, '%');++ return (+ <StatStrip+ className={cn('md:grid-cols-4', hasBreakdowns && 'lg:grid-cols-6')}+ >+ <Stat+ change={+ stats.previousRate !== null && (+ <PreviousDiffIndicatorPure+ {...getPreviousMetric(stats.rate, stats.previousRate)}+ size="xs"+ />+ )+ }+ detail={flow}+ label="Conversion"+ value={formatRate(stats.rate)}+ />+ <Stat+ change={+ stats.previousConversions !== null && (+ <PreviousDiffIndicatorPure+ {...getPreviousMetric(+ stats.conversions,+ stats.previousConversions+ )}+ size="xs"+ />+ )+ }+ detail={`of ${number.format(stats.opportunities)} opportunities`}+ label="Conversions"+ value={number.format(stats.conversions)}+ />+ <Stat+ detail={stats.bestDay && <DayDetail match={stats.bestDay} />}+ label="Best day"+ value={stats.bestDay ? formatRate(stats.bestDay.point.rate) : '–'}+ />+ <Stat+ detail={stats.worstDay && <DayDetail match={stats.worstDay} />}+ label="Worst day"+ value={stats.worstDay ? formatRate(stats.worstDay.point.rate) : '–'}+ />+ {hasBreakdowns && stats.bestSerie && (+ <Stat+ detail={<Breakdown serie={stats.bestSerie} />}+ label="Best breakdown"+ value={formatRate(averageRate(stats.bestSerie))}+ />+ )}+ {hasBreakdowns && stats.worstSerie && (+ <Stat+ detail={<Breakdown serie={stats.worstSerie} />}+ label="Worst breakdown"+ value={formatRate(averageRate(stats.worstSerie))}+ />+ )}+ </StatStrip>);+}- const averageConversionRate = average(- data.current.map((serie) => {- return average(serie.data.map((item) => item.rate));- }, 0)+function DayDetail({ match }: { match: DayMatch }) {+ const hasBreakdown = match.serie.breakdowns.length > 0;+ return (+ <>+ {formatDate(new Date(match.point.date))}+ {hasBreakdown && (+ <>+ <span>·</span>+ <Breakdown serie={match.serie} />+ </>+ )}+ </>);+}- const averageConversionRatePrevious =- average(- data.previous?.map((serie) => {- return average(serie.data.map((item) => item.rate));- }) ?? []- ) ?? 0;+function Breakdown({ serie }: { serie: Serie }) {+ return (+ <>+ <SerieIcon name={serie.breakdowns} />+ <span className="truncate">{serie.breakdowns.join(' › ')}</span>+ </>+ );+}- const sumConversions = data.current.reduce((acc, serie) => {- return acc + sum(serie.data.map((item) => item.conversions));- }, 0);- const sumConversionsPrevious = data.previous?.reduce((acc, serie) => {- return acc + sum(serie.data.map((item) => item.conversions));- }, 0);+function sumOf(+ series: { data: { conversions: number; total: number }[] }[],+ key: 'conversions' | 'total'+) {+ return sum(series.flatMap((serie) => serie.data.map((item) => item[key])));+}- const hasManySeries = data.current.length > 1;+function overallRate(conversions: number, opportunities: number) {+ return opportunities > 0 ? (conversions / opportunities) * 100 : 0;+}- const keyValueData = useMemo(() => {- const flowLabel = report.series- .filter((item) => item.type === 'event')- .map((e) => e.displayName || e.name)- .join(' → ');- const items: { name: string; value: React.ReactNode }[] = [- { name: 'Flow', value: flowLabel },- {- name: 'Average conversion rate',- value: number.formatWithUnit(averageConversionRate / 100, '%'),- },- { name: 'Total conversions', value: sumConversions },- ];- if (data.previous != null) {- items.push(- {- name: 'Previous period average conversion rate',- value: number.formatWithUnit(- averageConversionRatePrevious / 100,- '%'- ),- },- {- name: 'Previous period total conversions',- value: sumConversionsPrevious ?? 0,- }- );- }- if (hasManySeries && bestAverageConversionRateMatch) {- items.push({- name: 'Best breakdown (avg)',- value: `${bestAverageConversionRateMatch.serie?.breakdowns.join(', ')} with ${number.formatWithUnit(bestAverageConversionRateMatch.averageRate / 100, '%')}`,- });- }- if (hasManySeries && worstAverageConversionRateMatch) {- items.push({- name: 'Worst breakdown (avg)',- value: `${worstAverageConversionRateMatch.serie?.breakdowns.join(', ')} with ${number.formatWithUnit(worstAverageConversionRateMatch.averageRate / 100, '%')}`,- });- }- if (bestConversionRate) {- const breakdowns = bestConversionRate.serie.breakdowns.join(', ');- items.push({- name: 'Best conversion rate',- value: breakdowns- ? `${number.formatWithUnit(bestConversionRate.rate / 100, '%')} on ${breakdowns} at ${formatDate(new Date(bestConversionRate.date))}`- : `${number.formatWithUnit(bestConversionRate.rate / 100, '%')} at ${formatDate(new Date(bestConversionRate.date))}`,- });- }- if (worstConversionRate) {- const breakdowns = worstConversionRate.serie.breakdowns.join(', ');- items.push({- name: 'Worst conversion rate',- value: breakdowns- ? `${number.formatWithUnit(worstConversionRate.rate / 100, '%')} on ${breakdowns} at ${formatDate(new Date(worstConversionRate.date))}`- : `${number.formatWithUnit(worstConversionRate.rate / 100, '%')} at ${formatDate(new Date(worstConversionRate.date))}`,- });- }- return items;- }, [- report.series,- averageConversionRate,- sumConversions,- data.previous,- averageConversionRatePrevious,- sumConversionsPrevious,- hasManySeries,- bestAverageConversionRateMatch,- worstAverageConversionRateMatch,- bestConversionRate,- worstConversionRate,- number,- ]);+function maxBy<T>(items: T[], score: (item: T) => number) {+ return items.reduce<T | undefined>(+ (best, item) =>+ best === undefined || score(item) > score(best) ? item : best,+ undefined+ );+}- return (- <div className="my-4 space-y-3">- <div className="row flex-wrap gap-2">- {keyValueData.map((item) => {- const Icon = SUMMARY_ICONS[item.name];- return (- <div- className="card row items-center justify-between gap-4 p-4 py-3 font-medium"- key={item.name}- >- <span className="row items-center gap-2 text-muted-foreground">- {Icon != null && <Icon className="size-4 shrink-0" />}- {item.name}- </span>- <span>{item.value}</span>- </div>- );- })}- </div>- </div>+function minBy<T>(items: T[], score: (item: T) => number) {+ return items.reduce<T | undefined>(+ (worst, item) =>+ worst === undefined || score(item) < score(worst) ? item : worst,+ undefined);}diff --git a/apps/start/src/components/report-chart/conversion/table.tsx b/apps/start/src/components/report-chart/conversion/table.tsxnew file mode 100644index 000000000..767393f13--- /dev/null+++ b/apps/start/src/components/report-chart/conversion/table.tsx@@ -0,0 +1,161 @@+import { average } from '@openpanel/shared';+import { useMemo } from 'react';+import { getPreviousMetric } from '../../../utils/previous-metric';+import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';+import { SerieIcon } from '../common/serie-icon';+import { SerieName } from '../common/serie-name';+import { useReportChartContext } from '../context';+import {+ type ReportColumn,+ ReportDataTable,+ type ReportRowIdentity,+} from '@/components/report-table/report-data-table';+import { useFormatDateInterval } from '@/hooks/use-format-date-interval';+import type { RouterOutputs } from '@/trpc/client';+import { getChartColor } from '@/utils/theme';++type ConversionData = RouterOutputs['chart']['conversion'];++interface ConversionRow {+ id: string;+ names: string[];+ color: string;+ averageRate: number;+ previousAverageRate: number | undefined;+ total: number;+ conversions: number;+ rateByDate: Record<string, number>;+}++interface Props {+ data: ConversionData;+ visibleIds: ReadonlySet<string>;+ /** Absent on read-only pages, which hides the checkboxes. */+ onToggle?: (id: string) => void;+ onUnselectAll?: () => void;+ onReset?: () => void;+}++const SUMMARY_COLUMNS: ReportColumn<ConversionRow>[] = [+ {+ id: 'averageRate',+ header: 'Avg rate',+ value: (row) => row.averageRate,+ format: 'percent',+ width: 150,+ render: (row, formatted) => (+ <AverageRateCell formatted={formatted} row={row} />+ ),+ },+ { id: 'total', header: 'Total', value: (row) => row.total },+ { id: 'conversions', header: 'Conversions', value: (row) => row.conversions },+];++const IDENTITY: ReportRowIdentity<ConversionRow> = {+ header: 'Series',+ render: (row) => (+ <span className="flex items-center gap-1.5">+ <SerieIcon name={row.names} />+ <SerieName name={row.names} />+ </span>+ ),+ searchText: (row) => row.names.join(' › '),+ color: (row) => row.color,+};++export function ConversionTable({+ data,+ visibleIds,+ onToggle,+ onUnselectAll,+ onReset,+}: Props) {+ const {+ report: { interval, name },+ } = useReportChartContext();+ const formatDate = useFormatDateInterval({ interval, short: true });++ const dates = useMemo(+ () => data.current[0]?.data.map((item) => item.date) ?? [],+ [data.current]+ );+ const rows = useMemo(+ () =>+ data.current.map((serie, index): ConversionRow => {+ const previous = data.previous?.find((item) => item.id === serie.id);+ return {+ id: serie.id,+ names:+ serie.breakdowns.length > 0 ? serie.breakdowns : ['Conversion'],+ color: getChartColor(index),+ averageRate: average(+ serie.data.map((item) => item.rate),+ true+ ),+ previousAverageRate: previous?.data.length+ ? average(+ previous.data.map((item) => item.rate),+ true+ )+ : undefined,+ total: serie.data.reduce((sum, item) => sum + item.total, 0),+ conversions: serie.data.reduce(+ (sum, item) => sum + item.conversions,+ 0+ ),+ rateByDate: Object.fromEntries(+ serie.data.map((item) => [item.date, item.rate])+ ),+ };+ }),+ [data]+ );+ const columns = useMemo<ReportColumn<ConversionRow>[]>(+ () => [+ ...SUMMARY_COLUMNS,+ ...dates.map(+ (date): ReportColumn<ConversionRow> => ({+ id: date,+ header: formatDate(date),+ value: (row) => row.rateByDate[date] ?? 0,+ format: 'percent',+ decorate: 'heat',+ })+ ),+ ],+ [dates, formatDate]+ );++ return (+ <ReportDataTable+ columns={columns}+ csvFilename={name || 'conversion'}+ getRowId={(row) => row.id}+ identity={IDENTITY}+ onReset={onReset}+ onToggleRow={onToggle}+ onUnselectAll={onUnselectAll}+ rows={rows}+ selectedIds={visibleIds}+ />+ );+}++function AverageRateCell({+ row,+ formatted,+}: {+ row: ConversionRow;+ formatted: string;+}) {+ const diff =+ row.previousAverageRate === undefined+ ? null+ : getPreviousMetric(row.averageRate, row.previousAverageRate);+ return (+ <span className="flex items-center justify-end gap-2">+ {formatted}+ {diff && <PreviousDiffIndicatorPure {...diff} size="xs" />}+ </span>+ );+}diff --git a/apps/start/src/components/report-chart/funnel/breakdown-list.tsx b/apps/start/src/components/report-chart/funnel/breakdown-list.tsxdeleted file mode 100644index b3ba931fc..000000000--- a/apps/start/src/components/report-chart/funnel/breakdown-list.tsx+++ /dev/null@@ -1,174 +0,0 @@-import { ChevronDown, ChevronRight } from 'lucide-react';-import { useState } from 'react';-import { getPreviousMetric } from '../../../utils/previous-metric';-import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';-import { Tables } from './chart';-import { Checkbox } from '@/components/ui/checkbox';-import { useNumber } from '@/hooks/use-numer-formatter';-import type { RouterOutputs } from '@/trpc/client';-import { cn } from '@/utils/cn';-import { getChartColor } from '@/utils/theme';--interface BreakdownListProps {- data: RouterOutputs['chart']['funnel'];- visibleSeriesIds: string[];- setVisibleSeries: React.Dispatch<React.SetStateAction<string[]>>;-}--const COMPACT_THRESHOLD = 4;--export function BreakdownList({- data,- visibleSeriesIds,- setVisibleSeries,-}: BreakdownListProps) {- const allBreakdowns = data.current;- const previousData = data.previous || [];- const isCompact = allBreakdowns.length > COMPACT_THRESHOLD;- const hasBreakdowns = allBreakdowns.length > 1;- const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());- const number = useNumber();-- const toggleExpanded = (id: string) => {- setExpandedIds((prev) => {- const next = new Set(prev);- if (next.has(id)) {- next.delete(id);- } else {- next.add(id);- }- return next;- });- };-- const toggleVisibility = (id: string) => {- setVisibleSeries((prev) => {- if (prev.includes(id)) {- return prev.filter((s) => s !== id);- }- return [...prev, id];- });- };-- // Get the stable color index for a breakdown (position in full list, matches chart)- const getStableColorIndex = (id: string) => {- return allBreakdowns.findIndex((b) => b.id === id);- };-- if (allBreakdowns.length === 0) {- return null;- }-- // Detailed mode: <= COMPACT_THRESHOLD breakdowns, show full Tables for each- if (!isCompact) {- return (- <div className="col gap-4">- {allBreakdowns.map((item, index) => (- <Tables- data={{- current: item,- previous: previousData[index] ?? null,- }}- key={item.id}- />- ))}- </div>- );- }-- // Compact mode: > COMPACT_THRESHOLD breakdowns, show compact rows with expand- return (- <div className="col gap-2">- {allBreakdowns.map((item, index) => {- const isExpanded = expandedIds.has(item.id);- const isVisible = visibleSeriesIds.includes(item.id);- const stableColorIndex = getStableColorIndex(item.id);- const previousItem = previousData[index] ?? null;- const hasBreakdownName = item.breakdowns && item.breakdowns.length > 0;- const color =- stableColorIndex >= 0 ? getChartColor(stableColorIndex) : undefined;-- return (- <div className="col" key={item.id}>- <div- className={cn(- 'card row w-full items-center gap-3 px-4 py-3 text-left',- isExpanded && 'rounded-b-none'- )}- >- {hasBreakdowns && (- <Checkbox- checked={isVisible}- className="shrink-0"- onCheckedChange={() => toggleVisibility(item.id)}- style={{- borderColor: color,- backgroundColor: isVisible && color ? color : 'transparent',- }}- />- )}-- <button- className="flex min-w-0 flex-1 items-center gap-3 transition-opacity hover:opacity-80"- onClick={() => toggleExpanded(item.id)}- type="button"- >- {isExpanded ? (- <ChevronDown className="size-4 shrink-0 text-muted-foreground" />- ) : (- <ChevronRight className="size-4 shrink-0 text-muted-foreground" />- )}- <span className="truncate font-medium">- {hasBreakdownName ? item.breakdowns.join(' > ') : 'Funnel'}- </span>- </button>-- <div className="flex shrink-0 items-center gap-6">- <div className="row items-center gap-2 text-right">- <div className="text-muted-foreground text-sm">- Conversion- </div>- <div className="font-mono font-semibold text-sm">- {number.formatWithUnit(item.lastStep.percent / 100, '%')}- </div>- {previousItem && (- <PreviousDiffIndicatorPure- {...getPreviousMetric(- item.lastStep.percent,- previousItem.lastStep.percent- )}- />- )}- </div>- <div className="row items-center gap-2 text-right">- <div className="text-muted-foreground text-sm">Completed</div>- <div className="font-mono font-semibold text-sm">- {number.format(item.lastStep.count)}- </div>- {previousItem && (- <PreviousDiffIndicatorPure- {...getPreviousMetric(- item.lastStep.count,- previousItem.lastStep.count- )}- />- )}- </div>- </div>- </div>-- {isExpanded && (- <Tables- data={{- current: item,- previous: previousItem,- }}- noTopBorderRadius- />- )}- </div>- );- })}- </div>- );-}diff --git a/apps/start/src/components/report-chart/funnel/breakdown-table.tsx b/apps/start/src/components/report-chart/funnel/breakdown-table.tsxnew file mode 100644index 000000000..c87a3c556--- /dev/null+++ b/apps/start/src/components/report-chart/funnel/breakdown-table.tsx@@ -0,0 +1,140 @@+import { useMemo } from 'react';+import { getPreviousMetric } from '../../../utils/previous-metric';+import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';+import { SerieIcon } from '../common/serie-icon';+import { SerieName } from '../common/serie-name';+import { useReportChartContext } from '../context';+import {+ type ReportColumn,+ ReportDataTable,+ type ReportRowIdentity,+} from '@/components/report-table/report-data-table';+import type { RouterOutputs } from '@/trpc/client';+import { getChartColor } from '@/utils/theme';++type FunnelData = RouterOutputs['chart']['funnel'];+type Funnel = FunnelData['current'][number];++interface BreakdownRow {+ id: string;+ funnel: Funnel;+ previous: Funnel | null;+ color: string;+}++interface Props {+ data: FunnelData;+ visibleIds: ReadonlySet<string>;+ onToggle?: (id: string) => void;+ onUnselectAll?: () => void;+ onReset?: () => void;+ /** The breakdown whose steps are shown under the table. */+ activeId?: string;+ onSelect: (id: string) => void;+}++const IDENTITY: ReportRowIdentity<BreakdownRow> = {+ header: 'Breakdown',+ render: (row) => (+ <span className="flex items-center gap-1.5">+ <SerieIcon name={row.funnel.breakdowns} />+ <SerieName name={row.funnel.breakdowns} />+ </span>+ ),+ searchText: (row) => row.funnel.breakdowns.join(' › '),+ color: (row) => row.color,+};++/** One row per breakdown: its conversion, how many completed, and how far along each step got. */+export function BreakdownTable({+ data,+ visibleIds,+ onToggle,+ onUnselectAll,+ onReset,+ activeId,+ onSelect,+}: Props) {+ const {+ report: { name },+ } = useReportChartContext();+ const rows = useMemo(+ () =>+ data.current.map(+ (funnel, index): BreakdownRow => ({+ id: funnel.id,+ funnel,+ previous: data.previous?.[index] ?? null,+ color: getChartColor(index),+ })+ ),+ [data]+ );+ const steps = data.current[0]?.steps ?? [];++ const columns = useMemo<ReportColumn<BreakdownRow>[]>(+ () => [+ {+ id: 'conversion',+ header: 'Conversion',+ value: (row) => row.funnel.lastStep.percent,+ format: 'percent',+ decorate: 'bar',+ width: 150,+ render: (row, formatted) => (+ <span className="flex items-center justify-end gap-2">+ {formatted}+ {row.previous && (+ <PreviousDiffIndicatorPure+ {...getPreviousMetric(+ row.funnel.lastStep.percent,+ row.previous.lastStep.percent+ )}+ size="xs"+ />+ )}+ </span>+ ),+ },+ {+ id: 'completed',+ header: 'Completed',+ value: (row) => row.funnel.lastStep.count,+ },+ {+ id: 'dropoff',+ header: 'Most drop-off after',+ value: (row) => row.funnel.mostDropoffsStep?.event.displayName ?? '',+ format: 'text',+ width: 180,+ },+ ...steps.map(+ (step, index): ReportColumn<BreakdownRow> => ({+ id: `step:${index}`,+ header: step.event.displayName,+ value: (row) => row.funnel.steps[index]?.percent ?? 0,+ format: 'percent',+ decorate: 'heat',+ width: 150,+ })+ ),+ ],+ [steps]+ );++ return (+ <ReportDataTable+ activeId={activeId}+ columns={columns}+ csvFilename={name || 'funnel'}+ getRowId={(row) => row.id}+ identity={IDENTITY}+ onReset={onReset}+ onRowClick={onSelect}+ onToggleRow={onToggle}+ onUnselectAll={onUnselectAll}+ rows={rows}+ selectedIds={visibleIds}+ />+ );+}diff --git a/apps/start/src/components/report-chart/funnel/chart.tsx b/apps/start/src/components/report-chart/funnel/chart.tsxdeleted file mode 100644index 1dec1d9c4..000000000--- a/apps/start/src/components/report-chart/funnel/chart.tsx+++ /dev/null@@ -1,767 +0,0 @@-import { alphabetIds } from '@openpanel/core/modules/report/report.constants';-import { ChevronRightIcon, InfoIcon, UsersIcon } from 'lucide-react';-import { useCallback } from 'react';-import {- Bar,- BarChart,- CartesianGrid,- Cell,- Legend,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';-import { getPreviousMetric } from '../../../utils/previous-metric';-import { useXAxisProps, useYAxisProps } from '../common/axis';-import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';-import { SerieIcon } from '../common/serie-icon';-import { SerieName } from '../common/serie-name';-import { useReportChartContext } from '../context';-import { createChartTooltip } from '@/components/charts/chart-tooltip';-import { BarShapeProps } from '@/components/charts/common-bar';-import { ColorSquare } from '@/components/color-square';-import { Button } from '@/components/ui/button';-import { Tooltiper } from '@/components/ui/tooltip';-import { WidgetTable } from '@/components/widget-table';-import { useNumber } from '@/hooks/use-numer-formatter';-import { pushModal } from '@/modals';-import type { RouterOutputs } from '@/trpc/client';-import { cn } from '@/utils/cn';-import { getChartColor, getChartTranslucentColor } from '@/utils/theme';--type Props = {- data: {- current: RouterOutputs['chart']['funnel']['current'][number];- previous: RouterOutputs['chart']['funnel']['current'][number] | null;- };- noTopBorderRadius?: boolean;-};--export const Metric = ({- label,- value,- enhancer,- className,-}: {- label: string;- value: React.ReactNode;- enhancer?: React.ReactNode;- className?: string;-}) => (- <div className={cn('col flex-1 justify-between gap-1', className)}>- <div className="text-muted-foreground text-sm">{label}</div>- <div className="row items-center justify-between gap-2">- <div className="font-mono font-semibold">{value}</div>- {enhancer && <div>{enhancer}</div>}- </div>- </div>-);--export function Summary({ data }: { data: RouterOutputs['chart']['funnel'] }) {- const number = useNumber();- const highestConversion = data.current- .slice(0)- .sort((a, b) => b.lastStep.percent - a.lastStep.percent)[0];- const highestCount = data.current- .slice(0)- .sort((a, b) => b.lastStep.count - a.lastStep.count)[0];- return (- <div className="grid grid-cols-2 gap-4">- {highestConversion && (- <div className="card row items-center p-4 py-3">- <Metric- label="Highest conversion rate"- value={- <ChartName breakdowns={highestConversion.breakdowns ?? []} />- }- />- <span className="font-mono font-semibold text-xl">- {number.formatWithUnit(- highestConversion.lastStep.percent / 100,- '%'- )}- </span>- </div>- )}- {highestCount && (- <div className="card row items-center p-4 py-3">- <Metric- label="Most conversions"- value={<ChartName breakdowns={highestCount.breakdowns ?? []} />}- />- <span className="font-mono font-semibold text-xl">- {number.format(highestCount.lastStep.count)}- </span>- </div>- )}- </div>- );-}--function ChartName({- breakdowns,- className,-}: {- breakdowns: string[];- className?: string;-}) {- return (- <div className={cn('flex items-center gap-2 font-medium', className)}>- {breakdowns.map((name, index) => {- return (- <>- {index !== 0 && <ChevronRightIcon className="size-3" />}- <span key={name}>{name}</span>- </>- );- })}- </div>- );-}--export function Tables({- data: {- current: { steps, mostDropoffsStep, lastStep, breakdowns },- previous: previousData,- },- noTopBorderRadius,-}: Props) {- const number = useNumber();- const hasHeader = breakdowns.length > 0;- const {- report: {- projectId,- startDate,- endDate,- range,- interval,- series: reportSeries,- breakdowns: reportBreakdowns,- previous,- options,- },- shareId,- } = useReportChartContext();-- const funnelOptions = options?.type === 'funnel' ? options : undefined;-- const handleInspectStep = (step: (typeof steps)[0], stepIndex: number) => {- if (!(projectId && step.event.id)) {- return;- }-- // For funnels, we need to pass the step index so the modal can query- // users who completed at least that step in the funnel sequence- pushModal('ViewChartUsers', {- type: 'funnel',- report: {- projectId,- series: reportSeries,- breakdowns: reportBreakdowns || [],- interval: interval || 'day',- startDate,- endDate,- range,- previous,- chartType: 'funnel',- metric: 'sum',- options: funnelOptions,- },- stepIndex,- breakdownValues: breakdowns,- });- };- return (- <div- className={cn(- 'col @container card divide-y divide-border',- noTopBorderRadius && 'rounded-t-none'- )}- >- {hasHeader && <ChartName breakdowns={breakdowns} className="p-4 py-3" />}- <div- className={cn(- 'bg-def-100',- !hasHeader && 'rounded-t-md',- noTopBorderRadius && 'rounded-t-none'- )}- >- <div className="col md:row divide-border max-md:divide-y md:items-center md:divide-x">- <Metric- className="p-4 py-3"- enhancer={- previousData && (- <PreviousDiffIndicatorPure- {...getPreviousMetric(- lastStep?.percent,- previousData.lastStep?.percent- )}- />- )- }- label="Conversion"- value={number.formatWithUnit(lastStep?.percent / 100, '%')}- />- <Metric- className="p-4 py-3"- enhancer={- previousData && (- <PreviousDiffIndicatorPure- {...getPreviousMetric(- lastStep?.count,- previousData.lastStep?.count- )}- />- )- }- label="Completed"- value={number.format(lastStep?.count)}- />- {!!mostDropoffsStep && (- <Metric- className="p-4 py-3"- enhancer={- <Tooltiper- content={- <span>- <span className="font-semibold">- {mostDropoffsStep?.dropoffCount}- </span>{' '}- dropped after this event. Improve this step and your- conversion rate will likely increase.- </span>- }- tooltipClassName="max-w-xs"- >- <InfoIcon className="size-3" />- </Tooltiper>- }- label="Most dropoffs after"- value={mostDropoffsStep?.event?.displayName}- />- )}- </div>- </div>- <div className="col divide-y divide-def-200">- <WidgetTable- className={'@container text-sm'}- columnClassName="px-2 group/row items-center"- columns={[- {- name: 'Event',- render: (item, index) => (- <div className="row relative min-w-0 items-center gap-2">- <ColorSquare color={getChartColor(index)}>- {alphabetIds[index]}- </ColorSquare>- <span className="truncate">{item.event.displayName}</span>- </div>- ),- width: 'w-full',- className: 'text-left font-mono font-semibold',- },- {- name: 'Completed',- render: (item) => number.format(item.count),- className: 'text-right font-mono hidden @xl:block',- width: '82px',- },- {- name: 'Dropped after',- render: (item) =>- item.dropoffCount !== null && item.dropoffPercent !== null- ? number.format(item.dropoffCount)- : null,- className: 'text-right font-mono hidden @xl:block',- width: '110px',- },- {- name: 'Conversion',- render: (item) => number.formatWithUnit(item.percent / 100, '%'),- className: 'text-right font-mono font-semibold',- width: '90px',- },- {- name: '',- render: (item) =>- shareId ? null : (- <Button- className="h-8 w-8 p-0"- onClick={(e) => {- e.stopPropagation();- const stepIndex = steps.findIndex(- (s) => s.event.id === item.event.id- );- handleInspectStep(item, stepIndex);- }}- size="sm"- title="View users who completed this step"- variant="ghost"- >- <UsersIcon size={16} />- </Button>- ),- className: 'text-right',- width: '48px',- },- ]}- data={steps}- eachRow={(item, index) => {- return (- <div className="!p-0 absolute inset-px">- <div- className={cn(- 'relative h-full bg-def-300 transition-colors group-hover/row:bg-blue-200 dark:group-hover/row:bg-blue-900',- item.isHighestDropoff && [- 'bg-red-500/20',- 'group-hover/row:bg-red-500/70',- ],- index === steps.length - 1 && 'rounded-bl-sm'- )}- style={{- width: `${item.percent}%`,- }}- />- </div>- );- }}- keyExtractor={(item) => item.event.id!}- />- </div>- </div>- );-}--type RechartData = {- name: string;- [key: `step:percent:${number}`]: number | null;- [key: `step:data:${number}`]:- | (RouterOutputs['chart']['funnel']['current'][number] & {- step: RouterOutputs['chart']['funnel']['current'][number]['steps'][number];- })- | null;- [key: `prev_step:percent:${number}`]: number | null;- [key: `prev_step:data:${number}`]:- | (RouterOutputs['chart']['funnel']['current'][number] & {- step: RouterOutputs['chart']['funnel']['current'][number]['steps'][number];- })- | null;-};--const useRechartData = ({- current,- previous,- visibleBreakdowns,-}: RouterOutputs['chart']['funnel'] & {- visibleBreakdowns: RouterOutputs['chart']['funnel']['current'];-}): RechartData[] => {- const firstFunnel = current[0];- // Create a map of original index to visible index- const visibleBreakdownIds = new Set(visibleBreakdowns.map((b) => b.id));- const originalToVisibleIndex = new Map<number, number>();- let visibleIndex = 0;- current.forEach((item, originalIndex) => {- if (visibleBreakdownIds.has(item.id)) {- originalToVisibleIndex.set(originalIndex, visibleIndex);- visibleIndex++;- }- });-- return (- firstFunnel?.steps.map((step, stepIndex) => {- return {- id: step?.event.id ?? '',- name: step?.event.displayName ?? '',- ...visibleBreakdowns.reduce((acc, visibleItem, visibleIdx) => {- // Find the original index for this visible breakdown- const originalIndex = current.findIndex(- (item) => item.id === visibleItem.id- );- if (originalIndex === -1) {- return acc;- }-- const diff = previous?.[originalIndex];- return {- ...acc,- [`step:percent:${visibleIdx}`]:- visibleItem.steps[stepIndex]?.percent ?? null,- [`step:data:${visibleIdx}`]: {- ...visibleItem,- step: visibleItem.steps[stepIndex],- },- [`prev_step:percent:${visibleIdx}`]:- diff?.steps[stepIndex]?.percent ?? null,- [`prev_step:data:${visibleIdx}`]: diff- ? {- ...diff,- step: diff?.steps?.[stepIndex],- }- : null,- };- }, {}),- };- }) ?? []- );-};--const StripedBarShape = (props: any) => {- const { x, y, width, height, fill, stroke, value } = props;- const patternId = `prev-stripes-${(fill || '').replace(/[^a-z0-9]/gi, '')}`;- return (- <g>- <defs>- <pattern- height="6"- id={patternId}- patternTransform="rotate(-45)"- patternUnits="userSpaceOnUse"- width="6"- >- <rect fill="transparent" height="6" width="6" />- <rect fill={fill} height="6" width="3" />- </pattern>- </defs>- <rect- fill={`url(#${patternId})`}- height={height}- rx={3}- width={width}- x={x}- y={y}- />- {value > 0 && (- <rect- fill={stroke}- height={2}- opacity={0.6}- rx={2}- stroke="none"- width={width}- x={x}- y={y - 3}- />- )}- </g>- );-};--export function Chart({- data,- visibleBreakdowns,-}: {- data: RouterOutputs['chart']['funnel'];- visibleBreakdowns: RouterOutputs['chart']['funnel']['current'];-}) {- const rechartData = useRechartData({ ...data, visibleBreakdowns });- const xAxisProps = useXAxisProps();- const yAxisProps = useYAxisProps();- const hasBreakdowns = data.current.length > 1;- const hasVisibleBreakdowns = visibleBreakdowns.length > 1;- const hasPrevious =- data.previous !== null &&- data.previous !== undefined &&- data.previous.length > 0;- const showPreviousBars = hasPrevious && !hasBreakdowns;-- const CustomLegend = useCallback(() => {- if (!hasVisibleBreakdowns) {- return null;- }- return (- <div className="mt-4 -mb-2 flex flex-wrap justify-center gap-x-4 gap-y-1 text-xs">- {visibleBreakdowns.map((breakdown, idx) => {- const stableIndex = data.current.findIndex(- (b) => b.id === breakdown.id- );- const colorIndex = stableIndex >= 0 ? stableIndex : idx;- return (- <div- className="flex items-center gap-1.5 rounded px-2 py-1"- key={breakdown.id}- style={{- color: getChartColor(colorIndex),- }}- >- <SerieIcon name={breakdown.breakdowns ?? []} />- <SerieName- className="font-semibold"- name={- breakdown.breakdowns && breakdown.breakdowns.length > 0- ? breakdown.breakdowns- : ['Funnel']- }- />- </div>- );- })}- </div>- );- }, [visibleBreakdowns, hasVisibleBreakdowns]);-- const PreviousLegend = useCallback(() => {- if (!showPreviousBars) {- return null;- }- return (- <div className="mt-4 -mb-2 flex flex-wrap justify-center gap-x-4 gap-y-1.5 text-xs">- <div className="flex items-center gap-1.5 rounded px-2 py-1">- <div- className="h-3 w-3 rounded-[2px]"- style={{- background: 'rgba(59, 121, 255, 0.3)',- borderTop: '2px solid rgba(59, 121, 255, 1)',- }}- />- <span className="font-medium text-muted-foreground">Current</span>- </div>- <div className="flex items-center gap-1.5 rounded px-2 py-1">- <svg height="12" viewBox="0 0 12 12" width="12">- <defs>- <pattern- height="4"- id="legend-stripes"- patternTransform="rotate(-45)"- patternUnits="userSpaceOnUse"- width="4"- >- <rect fill="transparent" height="4" width="4" />- <rect fill="rgba(59, 121, 255, 0.3)" height="4" width="2" />- </pattern>- </defs>- <rect fill="url(#legend-stripes)" height="12" rx="2" width="12" />- </svg>- <span className="font-medium text-muted-foreground">Previous</span>- </div>- </div>- );- }, [showPreviousBars]);-- return (- <TooltipProvider- data={data.current}- hasBreakdowns={hasBreakdowns}- hasPrevious={hasPrevious}- visibleBreakdownIds={new Set(visibleBreakdowns.map((b) => b.id))}- >- <div className="card aspect-video max-h-[250px] w-full p-4 pb-1">- <ResponsiveContainer>- <BarChart data={rechartData}>- <CartesianGrid- className="stroke-border"- horizontal={true}- strokeDasharray="3 3"- vertical={true}- />- <XAxis- {...xAxisProps}- allowDuplicatedCategory={false}- dataKey="id"- domain={undefined}- interval="preserveStartEnd"- scale="auto"- tickFormatter={(id) =>- data.current[0].steps.find((step) => step.event.id === id)- ?.event.displayName ?? ''- }- tickMargin={4}- tickSize={0}- type={'category'}- />- <YAxis {...yAxisProps} />- {hasBreakdowns &&- visibleBreakdowns.map((item, breakdownIndex) => {- const stableIndex = data.current.findIndex(- (b) => b.id === item.id- );- const colorIndex =- stableIndex >= 0 ? stableIndex : breakdownIndex;- return (- <Bar- dataKey={`step:percent:${breakdownIndex}`}- key={`step:percent:${item.id}`}- shape={<BarShapeProps />}- >- {rechartData.map((row, stepIndex) => (- <Cell- fill={getChartTranslucentColor(colorIndex)}- key={`${row.name}-${breakdownIndex}`}- stroke={getChartColor(colorIndex)}- />- ))}- </Bar>- );- })}- {!hasBreakdowns && (- <Bar dataKey="step:percent:0" shape={<BarShapeProps />}>- {rechartData.map((item, index) => (- <Cell- fill={getChartTranslucentColor(index)}- key={item.name}- stroke={getChartColor(index)}- />- ))}- </Bar>- )}- {showPreviousBars && (- <Bar dataKey="prev_step:percent:0" shape={<StripedBarShape />}>- {rechartData.map((item, index) => (- <Cell- fill={getChartTranslucentColor(index)}- key={`prev-${item.name}`}- stroke={getChartColor(index)}- />- ))}- </Bar>- )}- {hasVisibleBreakdowns && <Legend content={<CustomLegend />} />}- {showPreviousBars && <Legend content={<PreviousLegend />} />}- <Tooltip />- </BarChart>- </ResponsiveContainer>- </div>- </TooltipProvider>- );-}--const { Tooltip, TooltipProvider } = createChartTooltip<- RechartData,- {- data: RouterOutputs['chart']['funnel']['current'];- visibleBreakdownIds: Set<string>;- hasPrevious: boolean;- hasBreakdowns: boolean;- }->(({ data: dataArray, context, ...props }) => {- const data = dataArray[0];- const number = useNumber();- if (!data) {- return null;- }- const variants = Object.keys(data).filter((key) =>- key.startsWith('step:data:')- ) as `step:data:${number}`[];-- const index = context.data[0].steps.findIndex(- (step) => step.event.id === (data as any).id- );-- // Filter variants to only show visible breakdowns- // The variant object contains the full breakdown item, so we can check its ID directly- const visibleVariants = variants.filter((key) => {- const variant = data[key];- if (!variant) {- return false;- }- // The variant is the breakdown item itself (with step added), so it has an id property- return context.visibleBreakdownIds.has(variant.id);- });-- if (!context.hasBreakdowns && context.hasPrevious) {- const currentVariant = data['step:data:0'];- const previousVariant = data['prev_step:data:0'];-- if (!currentVariant?.step) {- return null;- }-- const metric = getPreviousMetric(- currentVariant.step.percent,- previousVariant?.step.percent- );-- return (- <>- <div className="text-muted-foreground">{data.name}</div>- <div className="col gap-1.5">- <div className="flex justify-between gap-8 font-medium font-mono">- <span className="text-muted-foreground">Current</span>- <span>- {number.format(currentVariant.step.count)} (- {number.formatWithUnit(currentVariant.step.percent / 100, '%')})- </span>- </div>- {previousVariant?.step && (- <div className="flex justify-between gap-8 font-medium font-mono text-muted-foreground">- <span>Previous</span>- <span>- {number.format(previousVariant.step.count)} (- {number.formatWithUnit(previousVariant.step.percent / 100, '%')}- )- </span>- </div>- )}- {metric && metric.diff != null && (- <div className="mt-0.5 flex items-center justify-between gap-8 border-border border-t pt-1.5">- <span className="font-medium text-sm">- {metric.state === 'positive'- ? 'Improvement'- : metric.state === 'negative'- ? 'Decline'- : 'No change'}- </span>- <PreviousDiffIndicatorPure {...metric} size="xs" />- </div>- )}- </div>- </>- );- }-- return (- <>- <div className="flex justify-between gap-8 text-muted-foreground">- <div>{data.name}</div>- </div>- {visibleVariants.map((key, visibleIndex) => {- const variant = data[key];- const prevVariant = data[`prev_${key}`];- if (!variant?.step) {- return null;- }- // Find the original breakdown index for color (matches chart bar order)- const originalBreakdownIndex = context.data.findIndex(- (b) => b.id === variant.id- );- let colorIndex = index;- if (visibleVariants.length > 1) {- colorIndex =- originalBreakdownIndex >= 0 ? originalBreakdownIndex : visibleIndex;- }- return (- <div className="row gap-2" key={key}>- <div- className="w-[3px] shrink-0 rounded-full"- style={{- background: getChartColor(colorIndex),- }}- />- <div className="col min-w-0 flex-1 gap-1">- <div className="flex items-center gap-1">- <ChartName breakdowns={variant.breakdowns ?? []} />- </div>- <div className="flex items-center justify-between gap-4 font-medium font-mono">- <div className="col gap-0.5">- <span>- {number.formatWithUnit(variant.step.percent / 100, '%')}- </span>- <span className="text-muted-foreground text-xs">- ({number.format(variant.step.count)})- </span>- </div>-- <PreviousDiffIndicatorPure- {...getPreviousMetric(- variant.step.percent,- prevVariant?.step.percent- )}- size="xs"- />- </div>- </div>- </div>- );- })}- </>- );-});diff --git a/apps/start/src/components/report-chart/funnel/index.tsx b/apps/start/src/components/report-chart/funnel/index.tsxindex fac2b3c2e..f7e60d646 100644--- a/apps/start/src/components/report-chart/funnel/index.tsx+++ b/apps/start/src/components/report-chart/funnel/index.tsx@@ -1,15 +1,20 @@import { useQuery } from '@tanstack/react-query';+import { useCallback, useMemo, useState } from 'react';import { AspectContainer } from '../aspect-container';+import { ChartWithTable, TableCard } from '../common/chart-with-table';import { ReportChartEmpty } from '../common/empty';import { ReportChartError } from '../common/error';import { ReportChartLoading } from '../common/loading';import { useChartInput, useReportChartContext } from '../context';-import { BreakdownList } from './breakdown-list';-import { Chart, Summary } from './chart';+import { BreakdownTable } from './breakdown-table';+import { Chart } from './steps-chart';+import { StepsTable } from './steps-table';+import { Summary } from './summary';import { changeVisibleSeries } from '@/components/report/reportSlice';import { useVisibleFunnelBreakdowns } from '@/hooks/use-visible-funnel-breakdowns';import { useTRPC } from '@/integrations/trpc/react';import { useDispatch } from '@/redux';+import type { RouterOutputs } from '@/trpc/client';export function ReportFunnelChart() {const { isLazyLoading, report, shareId, isEditMode } =@@ -30,14 +35,18 @@ export function ReportFunnelChart() {);// Hook for limiting which breakdowns are shown in the chart only- const { breakdowns: visibleBreakdowns, setVisibleSeries } =- useVisibleFunnelBreakdowns(res.data?.current ?? [], {- limit: 10,- savedVisibleSeries: report.visibleSeries,- onVisibleSeriesChange: isEditMode- ? (ids) => dispatch(changeVisibleSeries(ids))- : undefined,- });+ const {+ breakdowns: visibleBreakdowns,+ setVisibleSeries,+ reset,+ isDefaultSelection,+ } = useVisibleFunnelBreakdowns(res.data?.current ?? [], {+ limit: 10,+ savedVisibleSeries: report.visibleSeries,+ onVisibleSeriesChange: isEditMode+ ? (ids) => dispatch(changeVisibleSeries(ids))+ : undefined,+ });if (isLazyLoading || res.isLoading) {return <Loading />;@@ -51,18 +60,91 @@ export function ReportFunnelChart() {return <Empty />;}- const hasBreakdowns = res.data.current.length > 1;+ return (+ <FunnelWithTables+ data={res.data}+ isDefaultSelection={isDefaultSelection}+ isEditMode={isEditMode}+ reset={reset}+ setVisibleSeries={setVisibleSeries}+ visibleBreakdowns={visibleBreakdowns}+ />+ );+}++function FunnelWithTables({+ data,+ isEditMode,+ visibleBreakdowns,+ setVisibleSeries,+ reset,+ isDefaultSelection,+}: {+ data: RouterOutputs['chart']['funnel'];+ isEditMode: boolean;+ visibleBreakdowns: RouterOutputs['chart']['funnel']['current'];+ setVisibleSeries: React.Dispatch<React.SetStateAction<string[]>>;+ reset: () => void;+ isDefaultSelection: boolean;+}) {+ const hasBreakdowns = data.current.length > 1;+ const [selectedId, setSelectedId] = useState<string>();+ const visibleIds = useMemo(+ () => new Set(visibleBreakdowns.map((item) => item.id)),+ [visibleBreakdowns]+ );+ const toggle = useCallback(+ (id: string) =>+ setVisibleSeries((ids) =>+ ids.includes(id) ? ids.filter((item) => item !== id) : [...ids, id]+ ),+ [setVisibleSeries]+ );+ const activeIndex = Math.max(+ 0,+ data.current.findIndex((item) => item.id === selectedId)+ );+ const active = data.current[activeIndex];return (- <div className="col gap-4">- {hasBreakdowns && <Summary data={res.data} />}- <Chart data={res.data} visibleBreakdowns={visibleBreakdowns} />- <BreakdownList- data={res.data}- setVisibleSeries={setVisibleSeries}- visibleSeriesIds={visibleBreakdowns.map((b) => b.id)}- />- </div>+ <ChartWithTable+ chart={<Chart data={data} visibleBreakdowns={visibleBreakdowns} />}+ sizesItself+ summary={hasBreakdowns && <Summary data={data} />}+ tables={+ <>+ {hasBreakdowns && (+ <TableCard>+ <BreakdownTable+ activeId={active?.id}+ data={data}+ onReset={isEditMode && !isDefaultSelection ? reset : undefined}+ onSelect={setSelectedId}+ onToggle={isEditMode ? toggle : undefined}+ onUnselectAll={+ isEditMode && visibleBreakdowns.length > 0+ ? () => setVisibleSeries([])+ : undefined+ }+ visibleIds={visibleIds}+ />+ </TableCard>+ )}+ {active && (+ <TableCard+ title={+ hasBreakdowns && `Steps for ${active.breakdowns.join(' › ')}`+ }+ >+ <StepsTable+ funnel={active}+ previous={data.previous?.[activeIndex] ?? null}+ />+ </TableCard>+ )}+ </>+ }+ />);}diff --git a/apps/start/src/components/report-chart/funnel/steps-chart.tsx b/apps/start/src/components/report-chart/funnel/steps-chart.tsxnew file mode 100644index 000000000..514801c85--- /dev/null+++ b/apps/start/src/components/report-chart/funnel/steps-chart.tsx@@ -0,0 +1,217 @@+import { useMemo } from 'react';+import { getPreviousMetric } from '../../../utils/previous-metric';+import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';+import { SerieIcon } from '../common/serie-icon';+import { SerieName } from '../common/serie-name';+import { useReportChartContext } from '../context';+import { Bar } from '@/components/charts/bar';+import { BarChart } from '@/components/charts/bar-chart';+import { BarXAxis } from '@/components/charts/bar-x-axis';+import { FunnelChart } from '@/components/charts/funnel-chart';+import { Grid } from '@/components/charts/grid';+import {+ OPChartTooltip,+ type OPTooltipRow,+} from '@/components/charts/op-tooltip';+import { YAxis } from '@/components/charts/y-axis';+import { useNumber } from '@/hooks/use-numer-formatter';+import type { RouterOutputs } from '@/trpc/client';+import { getChartColor } from '@/utils/theme';++type FunnelData = RouterOutputs['chart']['funnel'];+type Funnel = FunnelData['current'][number];++const BREAKDOWN_MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };+const BREAKDOWN_BAR_GAP = 0.25;++export function Chart({+ data,+ visibleBreakdowns,+}: {+ data: FunnelData;+ visibleBreakdowns: Funnel[];+}) {+ const { layout } = useReportChartContext();+ const hasBreakdowns = data.current.length > 1;+ const funnel = data.current[0];+ const content = (+ <>+ {hasBreakdowns && (+ <BreakdownBars data={data} visibleBreakdowns={visibleBreakdowns} />+ )}+ {!hasBreakdowns && funnel && (+ <SingleFunnel funnel={funnel} previous={data.previous?.[0] ?? null} />+ )}+ </>+ );++ if (layout === 'fill') {+ return (+ <div className="h-full w-full" data-report-chart="funnel">+ {content}+ </div>+ );+ }++ // Safari does not resolve `h-full` against an `aspect-video` height, so the+ // funnel needs an absolute layer to get a definite height to fill.+ return (+ <div+ className="card relative aspect-video max-h-[250px] w-full"+ data-report-chart="funnel"+ >+ <div className="absolute inset-4">{content}</div>+ </div>+ );+}++function SingleFunnel({+ funnel,+ previous,+}: {+ funnel: Funnel;+ previous: Funnel | null;+}) {+ const number = useNumber();+ const stages = funnel.steps.map((step) => ({+ label: step.event.displayName,+ value: step.count,+ }));+ const conversion = funnel.lastStep.percent;+ const previousConversion = previous?.lastStep.percent;+ const comparison =+ previousConversion == null+ ? null+ : getPreviousMetric(conversion, previousConversion);++ return (+ <div className="col h-full gap-2">+ <div className="min-h-0 flex-1">+ <FunnelChart+ className="h-full"+ color={getChartColor(0)}+ data={stages}+ formatValue={number.short}+ grid={{ bands: true, lines: false }}+ />+ </div>+ {comparison && previousConversion != null && (+ <div className="flex shrink-0 items-center justify-center gap-2 text-muted-foreground text-sm">+ <span>+ Conversion{' '}+ <span className="font-mono font-semibold text-foreground">+ {number.formatWithUnit(conversion / 100, '%')}+ </span>+ </span>+ <span>+ previous{' '}+ <span className="font-mono">+ {number.formatWithUnit(previousConversion / 100, '%')}+ </span>+ </span>+ <PreviousDiffIndicatorPure {...comparison} size="xs" />+ </div>+ )}+ </div>+ );+}++function BreakdownBars({+ data,+ visibleBreakdowns,+}: {+ data: FunnelData;+ visibleBreakdowns: Funnel[];+}) {+ const number = useNumber();+ const breakdowns = useMemo(+ () =>+ visibleBreakdowns.map((breakdown, visibleIndex) => {+ const index = data.current.findIndex(+ (item) => item.id === breakdown.id+ );+ return {+ funnel: breakdown,+ key: `breakdown:${visibleIndex}`,+ color: getChartColor(index >= 0 ? index : visibleIndex),+ names: breakdown.breakdowns?.length+ ? breakdown.breakdowns+ : ['Funnel'],+ };+ }),+ [data.current, visibleBreakdowns]+ );++ const rows = useMemo(+ () =>+ (data.current[0]?.steps ?? []).map((step, stepIndex) => {+ const row: Record<string, unknown> = { name: step.event.displayName };+ for (const breakdown of breakdowns) {+ row[breakdown.key] = breakdown.funnel.steps[stepIndex]?.percent ?? 0;+ }+ row.stepIndex = stepIndex;+ return row;+ }),+ [data.current, breakdowns]+ );++ const tooltipRows = (row: Record<string, unknown>): OPTooltipRow[] =>+ breakdowns.map((breakdown) => {+ const step = breakdown.funnel.steps[row.stepIndex as number];+ return {+ color: breakdown.color,+ icon: <SerieIcon name={breakdown.names} />,+ label: <SerieName name={breakdown.names} />,+ value: step?.percent ?? 0,+ format: (value) => number.formatWithUnit(value / 100, '%'),+ sub: [{ label: 'Count', value: step?.count ?? 0 }],+ };+ });++ return (+ <div className="col h-full">+ <div className="min-h-0 flex-1">+ <BarChart+ animationDuration={0}+ aspectRatio="auto"+ barGap={BREAKDOWN_BAR_GAP}+ className="h-full"+ data={rows}+ margin={BREAKDOWN_MARGIN}+ xDataKey="name"+ >+ <Grid horizontal />+ <YAxis formatValue={(value) => `${value}%`} />+ <BarXAxis />+ {breakdowns.map((breakdown) => (+ <Bar+ animate={false}+ dataKey={breakdown.key}+ fill={breakdown.color}+ key={breakdown.key}+ lineCap={4}+ />+ ))}+ <OPChartTooltip+ rows={tooltipRows}+ title={(row) => String(row.name)}+ />+ </BarChart>+ </div>+ {breakdowns.length > 1 && (+ <div className="flex shrink-0 flex-wrap justify-center gap-x-4 gap-y-1 pt-2 text-xs">+ {breakdowns.map((breakdown) => (+ <div+ className="flex items-center gap-1"+ key={breakdown.key}+ style={{ color: breakdown.color }}+ >+ <SerieIcon name={breakdown.names} />+ <SerieName className="font-semibold" name={breakdown.names} />+ </div>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/apps/start/src/components/report-chart/funnel/steps-table.tsx b/apps/start/src/components/report-chart/funnel/steps-table.tsxnew file mode 100644index 000000000..a2622d210--- /dev/null+++ b/apps/start/src/components/report-chart/funnel/steps-table.tsx@@ -0,0 +1,197 @@+import { alphabetIds } from '@openpanel/core/modules/report/report.constants';+import { UsersIcon } from 'lucide-react';+import { useCallback, useMemo } from 'react';+import { getPreviousMetric } from '../../../utils/previous-metric';+import { PreviousDiffIndicatorPure } from '../common/previous-diff-indicator';+import { Stat, StatStrip } from '../common/stat-strip';+import { useReportChartContext } from '../context';+import { ColorSquare } from '@/components/color-square';+import {+ type ReportColumn,+ ReportDataTable,+ type ReportRowIdentity,+} from '@/components/report-table/report-data-table';+import { Button } from '@/components/ui/button';+import { useNumber } from '@/hooks/use-numer-formatter';+import { pushModal } from '@/modals';+import type { RouterOutputs } from '@/trpc/client';+import { getChartColor } from '@/utils/theme';++type Funnel = RouterOutputs['chart']['funnel']['current'][number];+type Step = Funnel['steps'][number];++interface StepRow {+ id: string;+ index: number;+ step: Step;+}++const ACTION_WIDTH = 56;++/** One row per funnel step: how many got there, how many left after it, and the conversion so far. */+export function StepsTable({+ funnel,+ previous,+}: {+ funnel: Funnel;+ previous: Funnel | null;+}) {+ const { report, shareId } = useReportChartContext();+ const rows = useMemo(+ () =>+ funnel.steps.map(+ (step, index): StepRow => ({+ id: step.event.id ?? `${index}`,+ index,+ step,+ })+ ),+ [funnel.steps]+ );++ const identity = useMemo<ReportRowIdentity<StepRow>>(+ () => ({+ header: 'Step',+ render: (row) => (+ <span className="flex items-center gap-2">+ <ColorSquare color={getChartColor(row.index)}>+ {alphabetIds[row.index]}+ </ColorSquare>+ <span className="truncate">{row.step.event.displayName}</span>+ </span>+ ),+ searchText: (row) => row.step.event.displayName,+ }),+ []+ );++ const inspectStep = useCallback(+ (row: StepRow) => {+ if (!(report.projectId && row.step.event.id)) {+ return;+ }+ // The modal lists the users who reached at least this step of the sequence.+ pushModal('ViewChartUsers', {+ type: 'funnel',+ report: {+ projectId: report.projectId,+ series: report.series,+ breakdowns: report.breakdowns || [],+ interval: report.interval || 'day',+ startDate: report.startDate,+ endDate: report.endDate,+ range: report.range,+ previous: report.previous,+ chartType: 'funnel',+ metric: 'sum',+ options:+ report.options?.type === 'funnel' ? report.options : undefined,+ },+ stepIndex: row.index,+ breakdownValues: funnel.breakdowns,+ });+ },+ [report, funnel.breakdowns]+ );++ const columns = useMemo<ReportColumn<StepRow>[]>(+ () => [+ { id: 'count', header: 'Completed', value: (row) => row.step.count },+ {+ id: 'dropoff',+ header: 'Dropped after',+ value: (row) => row.step.dropoffCount,+ width: 130,+ render: (row, formatted) => (+ <span className={row.step.isHighestDropoff ? 'text-red-500' : ''}>+ {formatted}+ </span>+ ),+ },+ {+ id: 'percent',+ header: 'Conversion',+ value: (row) => row.step.percent,+ format: 'percent',+ decorate: 'bar',+ width: 150,+ },+ ...(shareId+ ? []+ : [+ {+ id: 'users',+ header: '',+ value: () => '',+ format: 'text' as const,+ sortable: false,+ width: ACTION_WIDTH,+ render: (row: StepRow) => (+ <Button+ className="h-7 w-7 p-0"+ onClick={() => inspectStep(row)}+ size="sm"+ title="View users who completed this step"+ variant="ghost"+ >+ <UsersIcon size={14} />+ </Button>+ ),+ },+ ]),+ ],+ [shareId, inspectStep]+ );++ return (+ <div className="col">+ <FunnelMetrics funnel={funnel} previous={previous} />+ <ReportDataTable+ columns={columns}+ csvFilename={`${report.name || 'funnel'}${funnel.breakdowns.length ? ` ${funnel.breakdowns.join(' ')}` : ''}`}+ getRowId={(row) => row.id}+ identity={identity}+ rows={rows}+ searchable={false}+ />+ </div>+ );+}++function FunnelMetrics({+ funnel,+ previous,+}: {+ funnel: Funnel;+ previous: Funnel | null;+}) {+ const number = useNumber();+ const change = (current: number, before: number | undefined) =>+ before === undefined ? undefined : (+ <PreviousDiffIndicatorPure+ {...getPreviousMetric(current, before)}+ size="xs"+ />+ );+ return (+ <StatStrip className="border-b md:grid-cols-3" framed={false}>+ <Stat+ change={change(funnel.lastStep.percent, previous?.lastStep.percent)}+ label="Conversion"+ value={number.formatWithUnit(funnel.lastStep.percent / 100, '%')}+ />+ <Stat+ change={change(funnel.lastStep.count, previous?.lastStep.count)}+ label="Completed"+ value={number.format(funnel.lastStep.count)}+ />+ {funnel.mostDropoffsStep && (+ <Stat+ detail={`${number.format(funnel.mostDropoffsStep.dropoffCount ?? 0)} dropped after this step`}+ label="Most drop-offs after"+ value={funnel.mostDropoffsStep.event.displayName}+ />+ )}+ </StatStrip>+ );+}diff --git a/apps/start/src/components/report-chart/funnel/summary.tsx b/apps/start/src/components/report-chart/funnel/summary.tsxnew file mode 100644index 000000000..111a12ae7--- /dev/null+++ b/apps/start/src/components/report-chart/funnel/summary.tsx@@ -0,0 +1,45 @@+import { SerieIcon } from '../common/serie-icon';+import { Stat, StatStrip } from '../common/stat-strip';+import { useNumber } from '@/hooks/use-numer-formatter';+import type { RouterOutputs } from '@/trpc/client';++type Funnel = RouterOutputs['chart']['funnel']['current'][number];++/** Which breakdown converts best and which converts most, for a funnel with breakdowns. */+export function Summary({ data }: { data: RouterOutputs['chart']['funnel'] }) {+ const number = useNumber();+ const byRate = [...data.current].sort(+ (a, b) => b.lastStep.percent - a.lastStep.percent+ );+ const byCount = [...data.current].sort(+ (a, b) => b.lastStep.count - a.lastStep.count+ );+ const bestRate = byRate[0];+ const mostConversions = byCount[0];+ if (!(bestRate && mostConversions)) {+ return null;+ }+ return (+ <StatStrip>+ <Stat+ detail={<Breakdown funnel={bestRate} />}+ label="Highest conversion rate"+ value={number.formatWithUnit(bestRate.lastStep.percent / 100, '%')}+ />+ <Stat+ detail={<Breakdown funnel={mostConversions} />}+ label="Most conversions"+ value={number.format(mostConversions.lastStep.count)}+ />+ </StatStrip>+ );+}++function Breakdown({ funnel }: { funnel: Funnel }) {+ return (+ <>+ <SerieIcon name={funnel.breakdowns} />+ <span className="truncate">{funnel.breakdowns.join(' › ')}</span>+ </>+ );+}diff --git a/apps/start/src/components/report-chart/histogram/chart.tsx b/apps/start/src/components/report-chart/histogram/chart.tsxindex 7582cbc13..62a263449 100644--- a/apps/start/src/components/report-chart/histogram/chart.tsx+++ b/apps/start/src/components/report-chart/histogram/chart.tsx@@ -1,236 +1,89 @@-import { useQuery } from '@tanstack/react-query';-import { BookmarkIcon, UsersIcon } from 'lucide-react';-import { useCallback } from 'react';+import { PointClick } from '../common/point-click';import {- Bar,- BarChart,- CartesianGrid,- ReferenceLine,- ResponsiveContainer,- Tooltip,- XAxis,- YAxis,-} from 'recharts';-import { useXAxisProps, useYAxisProps } from '../common/axis';-import {- ChartClickMenu,- type ChartClickMenuItem,-} from '../common/chart-click-menu';-import { ReportChartTooltip } from '../common/report-chart-tooltip';-import { ReportTable } from '../common/report-table';+ previousPeriodColor,+ TimeSeriesFrame,+ type TimeSeriesPoint,+ useTimeSeriesChart,+} from '../common/time-series';import { useReportChartContext } from '../context';-import { changeVisibleSeries } from '@/components/report/reportSlice';-import { useRechartDataModel } from '@/hooks/use-rechart-data-model';-import { useTheme } from '@/hooks/use-theme';-import { useVisibleSeries } from '@/hooks/use-visible-series';-import { useTRPC } from '@/integrations/trpc/react';-import { pushModal } from '@/modals';-import { useDispatch } from '@/redux';+import { ComposedChart } from '@/components/charts/composed-chart';+import { Grid } from '@/components/charts/grid';+import { OPReferences } from '@/components/charts/op-references';+import { OPChartTooltip } from '@/components/charts/op-tooltip';+import { SeriesBar } from '@/components/charts/series-bar';+import { XAxis } from '@/components/charts/x-axis';+import { YAxis } from '@/components/charts/y-axis';+import type { IVisibleSeries } from '@/hooks/use-visible-series';import type { IChartData } from '@/trpc/client';-import { cn } from '@/utils/cn';import { getChartColor } from '@/utils/theme';+const BAR_RADIUS = 4;+// Room between stacked segments so each reads as its own rounded block, like the bar chart's rows.+const STACK_GAP = 2;+const MAX_BAR_WIDTH = 48;+interface Props {data: IChartData;+ series: IVisibleSeries;}-function BarHover({ x, y, width, height, top, left, right, bottom }: any) {- const themeMode = useTheme();- const styles = getComputedStyle(document.documentElement);- const def100 = styles.getPropertyValue('--def-100');- const def300 = styles.getPropertyValue('--def-300');- const bg = themeMode?.theme === 'dark' ? def100 : def300;- return (- <rect- {...{ x, y, width, height, top, left, right, bottom }}- fill={bg}- fillOpacity={0.5}- rx="3"- />- );-}--export function Chart({ data }: Props) {+export function Chart({ data, series }: Props) {const {- isEditMode,- shareId,- report: {- previous,- interval,- projectId,- startDate,- endDate,- range,- series: reportSeries,- breakdowns,- options: reportOptions,- visibleSeries: savedVisibleSeries,- },- options: { hideXAxis, hideYAxis },+ report: { options },} = useReportChartContext();- const dispatch = useDispatch();-- const histogramOptions =- reportOptions?.type === 'histogram' ? reportOptions : undefined;- const isStacked = histogramOptions?.stacked ?? false;- const trpc = useTRPC();- const references = useQuery(- trpc.reference.getChartReferences.queryOptions({- projectId,- startDate,- endDate,- range,- })- );- const { series, setVisibleSeries } = useVisibleSeries(data, {- savedVisibleSeries,- onVisibleSeriesChange: isEditMode- ? (ids) => dispatch(changeVisibleSeries(ids))- : undefined,- });- const rechartData = useRechartDataModel(series);- const yAxisProps = useYAxisProps({- hide: hideYAxis,- });- const xAxisProps = useXAxisProps({- hide: hideXAxis,- interval,- });-- const getMenuItems = useCallback(- (e: any, clickedData: any): ChartClickMenuItem[] => {- const items: ChartClickMenuItem[] = [];-- // Both actions need a signed-in member, which a share visitor is not.- if (shareId || !clickedData?.date) {- return items;- }-- // View Users - only show if we have projectId- if (projectId) {- items.push({- label: 'View Users',- icon: <UsersIcon size={16} />,- onClick: () => {- pushModal('ViewChartUsers', {- type: 'chart',- chartData: data,- report: {- projectId,- series: reportSeries,- breakdowns: breakdowns || [],- interval,- startDate,- endDate,- range,- previous,- chartType: 'histogram',- metric: 'sum',- },- date: clickedData.date,- });- },- });- }-- // Add Reference - always show- items.push({- label: 'Add Reference',- icon: <BookmarkIcon size={16} />,- onClick: () => {- pushModal('AddReference', {- datetime: new Date(clickedData.date).toISOString(),- });- },- });-- return items;- },- [- shareId,- projectId,- data,- reportSeries,- breakdowns,- interval,- startDate,- endDate,- range,- previous,- ]- );+ const chart = useTimeSeriesChart({ data, series, chartType: 'histogram' });+ const isStacked = options?.type === 'histogram' && options.stacked === true;+ // Stacking applies to every bar series, so stacked histograms show the+ // previous period in the tooltip only.+ const showPreviousBars = chart.previous && !isStacked;return (- <ReportChartTooltip.TooltipProvider references={references.data}>- <ChartClickMenu getMenuItems={getMenuItems}>- <div className={cn('h-full w-full', isEditMode && 'card p-4')}>- <ResponsiveContainer>- <BarChart data={rechartData}>- <CartesianGrid- className="stroke-def-200"- strokeDasharray="3 3"- vertical={false}- />- <Tooltip- content={<ReportChartTooltip.Tooltip />}- cursor={<BarHover />}- />- <YAxis {...yAxisProps} />- <XAxis {...xAxisProps} scale={'auto'} type="category" />- {previous- ? series.map((serie) => {- return (- <Bar- dataKey={`${serie.id}:prev:count`}- fill={getChartColor(serie.index)}- fillOpacity={0.3}- key={`${serie.id}:prev`}- name={`${serie.id}:prev`}- radius={5}- stackId={isStacked ? 'prev' : undefined}- />- );- })- : null}- {series.map((serie) => {- return (- <Bar- dataKey={`${serie.id}:count`}- fill={getChartColor(serie.index)}- fillOpacity={1}- key={serie.id}- name={serie.id}- radius={isStacked ? 0 : 4}- stackId={isStacked ? 'current' : undefined}- />- );- })}- {references.data?.map((ref) => (- <ReferenceLine- fontSize={10}- key={ref.id}- label={{- value: ref.title,- position: 'centerTop',- fill: '#334155',- fontSize: 12,- }}- stroke={'oklch(from var(--foreground) l c h / 0.1)'}- strokeDasharray={'3 3'}- x={ref.date.getTime()}- />- ))}- </BarChart>- </ResponsiveContainer>- </div>- {isEditMode && (- <ReportTable- data={data}- setVisibleSeries={setVisibleSeries}- visibleSeries={series}+ <TimeSeriesFrame chartType="histogram" menu={chart.menu} series={series}>+ <ComposedChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-full"+ data={chart.chartData}+ formatDateLabel={chart.formatDateLabel}+ margin={chart.margin}+ maxBarSize={MAX_BAR_WIDTH}+ stacked={isStacked}+ stackGap={isStacked ? STACK_GAP : 0}+ xDataKey="date"+ >+ <Grid horizontal />+ {!chart.hideYAxis && <YAxis formatValue={chart.formatAxisValue} />}+ {!chart.hideXAxis && <XAxis />}+ {showPreviousBars &&+ series.map((serie) => (+ <SeriesBar+ animate={false}+ dataKey={`${serie.id}:prev:count`}+ fill={previousPeriodColor(serie.index)}+ key={`${serie.id}:prev`}+ radius={BAR_RADIUS}+ />+ ))}+ {series.map((serie) => (+ <SeriesBar+ animate={false}+ dataKey={`${serie.id}:count`}+ fill={getChartColor(serie.index)}+ key={serie.id}+ radius={BAR_RADIUS}/>- )}- </ChartClickMenu>- </ReportChartTooltip.TooltipProvider>+ ))}+ <OPReferences items={chart.references} />+ <OPChartTooltip<TimeSeriesPoint>+ extra={chart.tooltipExtra}+ interval={chart.interval}+ references={chart.references}+ rows={chart.tooltipRows}+ showCrosshair={false}+ showDots={false}+ />+ <PointClick<TimeSeriesPoint> onClick={chart.menu.openMenu} />+ </ComposedChart>+ </TimeSeriesFrame>);}diff --git a/apps/start/src/components/report-chart/histogram/index.tsx b/apps/start/src/components/report-chart/histogram/index.tsxindex 01186f128..ed5c09cf1 100644--- a/apps/start/src/components/report-chart/histogram/index.tsx+++ b/apps/start/src/components/report-chart/histogram/index.tsx@@ -3,6 +3,7 @@ import { AspectContainer } from '../aspect-container';import { ReportChartEmpty } from '../common/empty';import { ReportChartError } from '../common/error';import { ReportChartLoading } from '../common/loading';+import { SeriesWithTable } from '../common/series-with-table';import { useChartInput, useReportChartContext } from '../context';import { Chart } from './chart';import { useTRPC } from '@/integrations/trpc/react';@@ -42,9 +43,10 @@ export function ReportHistogramChart() {}return (- <AspectContainer>- <Chart data={res.data} />- </AspectContainer>+ <SeriesWithTable+ chart={(series) => <Chart data={res.data} series={series} />}+ data={res.data}+ />);}diff --git a/apps/start/src/components/report-chart/index.tsx b/apps/start/src/components/report-chart/index.tsxindex f5f7090a3..92e7fbfa2 100644--- a/apps/start/src/components/report-chart/index.tsx+++ b/apps/start/src/components/report-chart/index.tsx@@ -14,6 +14,7 @@ import { ReportMetricChart } from './metric';import { ReportPieChart } from './pie';import { ReportRetentionChart } from './retention';import { ReportSankeyChart } from './sankey';+import { cn } from '@/utils/cn';export const ReportChart = ({ lazy = true, ...props }: ReportChartProps) => {const ref = useRef<HTMLDivElement>(null);@@ -64,9 +65,15 @@ export const ReportChart = ({ lazy = true, ...props }: ReportChartProps) => {};return (- <div ref={ref}>+ <div+ className={cn('w-full', props.layout === 'fill' && 'h-full min-h-0')}+ ref={ref}+ ><ReportChartProvider- {...mergeDeepRight({ options: {}, isEditMode: false }, props)}+ {...mergeDeepRight(+ { options: {}, isEditMode: false, layout: 'aspect' as const },+ props+ )}isLazyLoading={!loaded}>{renderReportChart()}diff --git a/apps/start/src/components/report-chart/line/chart.tsx b/apps/start/src/components/report-chart/line/chart.tsxindex de6c1ad8b..3d8562378 100644--- a/apps/start/src/components/report-chart/line/chart.tsx+++ b/apps/start/src/components/report-chart/line/chart.tsx@@ -1,338 +1,81 @@-import { useQuery } from '@tanstack/react-query';-import { isSameDay, isSameHour, isSameMonth, isSameWeek } from 'date-fns';-import { BookmarkIcon, UsersIcon } from 'lucide-react';-import { last } from 'ramda';-import { useCallback } from 'react';+import { PointClick } from '../common/point-click';import {- CartesianGrid,- ComposedChart,- Customized,- Legend,- Line,- ReferenceLine,- ResponsiveContainer,- Tooltip,- XAxis,- YAxis,-} from 'recharts';-import { useXAxisProps, useYAxisProps } from '../common/axis';-import {- ChartClickMenu,- type ChartClickMenuItem,-} from '../common/chart-click-menu';-import { ReportChartTooltip } from '../common/report-chart-tooltip';-import { ReportTable } from '../common/report-table';-import { SerieIcon } from '../common/serie-icon';-import { SerieName } from '../common/serie-name';-import { useReportChartContext } from '../context';-import { changeVisibleSeries } from '@/components/report/reportSlice';-import { useDashedStroke } from '@/hooks/use-dashed-stroke';-import { useRechartDataModel } from '@/hooks/use-rechart-data-model';-import { useVisibleSeries } from '@/hooks/use-visible-series';-import { useTRPC } from '@/integrations/trpc/react';-import { pushModal } from '@/modals';-import { useDispatch } from '@/redux';+ POINT_MARKER,+ previousPeriodColor,+ TimeSeriesFrame,+ type TimeSeriesPoint,+ useTimeSeriesChart,+} from '../common/time-series';+import { Grid } from '@/components/charts/grid';+import { Line, LineChart } from '@/components/charts/line-chart';+import { OPReferences } from '@/components/charts/op-references';+import { OPChartTooltip } from '@/components/charts/op-tooltip';+import { XAxis } from '@/components/charts/x-axis';+import { YAxis } from '@/components/charts/y-axis';+import type { IVisibleSeries } from '@/hooks/use-visible-series';import type { IChartData } from '@/trpc/client';-import { cn } from '@/utils/cn';import { getChartColor } from '@/utils/theme';interface Props {data: IChartData;+ series: IVisibleSeries;}-export function Chart({ data }: Props) {- const {- report: {- previous,- interval,- projectId,- startDate,- endDate,- range,- lineType,- series: reportSeries,- breakdowns,- visibleSeries: savedVisibleSeries,- },- isEditMode,- shareId,- options: { hideXAxis, hideYAxis, maxDomain },- } = useReportChartContext();- const dispatch = useDispatch();- const dataLength = data.series[0]?.data?.length || 0;- const trpc = useTRPC();- const references = useQuery(- trpc.reference.getChartReferences.queryOptions({- projectId,- startDate,- endDate,- range,- })- );- const { series, setVisibleSeries } = useVisibleSeries(data, {- savedVisibleSeries,- onVisibleSeriesChange: isEditMode- ? (ids) => dispatch(changeVisibleSeries(ids))- : undefined,- });- const rechartData = useRechartDataModel(series);-- let dotIndex;- if (range === 'today') {- // Find closest index based on times- dotIndex = rechartData.findIndex((item) => {- return isSameHour(item.date, new Date());- });- }-- const lastSerieDataItem = last(series[0]?.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());- }-- if (interval === 'month') {- return isSameMonth(lastSerieDataItem, new Date());- }+export function Chart({ data, series }: Props) {+ const chart = useTimeSeriesChart({ data, series, chartType: 'linear' });- if (interval === 'week') {- return isSameWeek(lastSerieDataItem, new Date());- }-- return false;- })();-- const { getStrokeDasharray, calcStrokeDasharray, handleAnimationEnd } =- useDashedStroke({- dotIndex,- });-- const CustomLegend = useCallback(() => {- return (- <div className="mt-4 -mb-2 flex flex-wrap justify-center gap-x-4 gap-y-1 text-xs">+ return (+ <TimeSeriesFrame chartType="linear" menu={chart.menu} series={series}>+ <LineChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-full"+ data={chart.chartData}+ formatDateLabel={chart.formatDateLabel}+ margin={chart.margin}+ style={{ touchAction: 'pan-y' }}+ xDataKey="date"+ >+ <Grid horizontal />+ {!chart.hideYAxis && <YAxis formatValue={chart.formatAxisValue} />}+ {!chart.hideXAxis && <XAxis />}+ {chart.previous &&+ series.map((serie) => (+ <Line+ animate={false}+ curve={chart.curve}+ dataKey={`${serie.id}:prev:count`}+ key={`${serie.id}:prev`}+ showHighlight={false}+ stroke={previousPeriodColor(serie.index)}+ strokeWidth={1.5}+ />+ ))}{series.map((serie) => (- <div- className="flex items-center gap-1"+ <Line+ animate={false}+ curve={chart.curve}+ dashArray="4,4"+ dashFromIndex={chart.dashFromIndex}+ dataKey={`${serie.id}:count`}key={serie.id}- style={{- color: getChartColor(serie.index),- }}- >- <SerieIcon name={serie.names} />- <SerieName className="font-semibold" name={serie.names} />- </div>- ))}- </div>- );- }, [series]);-- const xAxisProps = useXAxisProps({ interval, hide: hideXAxis });- const yAxisProps = useYAxisProps({- hide: hideYAxis,- });-- const getMenuItems = useCallback(- (e: any, clickedData: any): ChartClickMenuItem[] => {- const items: ChartClickMenuItem[] = [];-- // Both actions need a signed-in member, which a share visitor is not.- if (shareId || !clickedData?.date) {- return items;- }-- // Extract serie ID from the click event if needed- // activePayload is an array of payload objects- const validPayload = e.activePayload?.find(- (p: any) =>- p.dataKey &&- p.dataKey !== 'calcStrokeDasharray' &&- typeof p.dataKey === 'string' &&- p.dataKey.includes(':count')- );- const serieId = validPayload?.dataKey?.toString().replace(':count', '');-- // View Users - only show if we have projectId- if (projectId) {- items.push({- label: 'View Users',- icon: <UsersIcon size={16} />,- onClick: () => {- pushModal('ViewChartUsers', {- type: 'chart',- chartData: data,- report: {- projectId,- series: reportSeries,- breakdowns: breakdowns || [],- interval,- startDate,- endDate,- range,- previous,- chartType: 'linear',- metric: 'sum',- },- date: clickedData.date,- });- },- });- }-- // Add Reference - always show- items.push({- label: 'Add Reference',- icon: <BookmarkIcon size={16} />,- onClick: () => {- pushModal('AddReference', {- datetime: new Date(clickedData.date).toISOString(),- });- },- });-- return items;- },- [- shareId,- projectId,- data,- reportSeries,- breakdowns,- interval,- startDate,- endDate,- range,- previous,- ]- );-- return (- <ReportChartTooltip.TooltipProvider references={references.data}>- <ChartClickMenu getMenuItems={getMenuItems}>- <div className={cn('h-full w-full', isEditMode && 'card p-4')}>- <ResponsiveContainer>- <ComposedChart data={rechartData}>- <Customized component={calcStrokeDasharray} />- <Line- animationDuration={0}- dataKey="calcStrokeDasharray"- legendType="none"- onAnimationEnd={handleAnimationEnd}- />- <CartesianGrid- className="stroke-border"- horizontal={true}- strokeDasharray="3 3"- vertical={false}- />- {references.data?.map((ref) => (- <ReferenceLine- fontSize={10}- key={ref.id}- label={{- value: ref.title,- position: 'centerTop',- fill: '#334155',- fontSize: 12,- }}- stroke={'oklch(from var(--foreground) l c h / 0.1)'}- strokeDasharray={'3 3'}- x={ref.date.getTime()}- />- ))}- <YAxis- {...yAxisProps}- domain={maxDomain ? [0, maxDomain] : undefined}- />- <XAxis {...xAxisProps} />- {series.length > 1 && <Legend content={<CustomLegend />} />}- <Tooltip content={<ReportChartTooltip.Tooltip />} />-- <defs>- <filter- height="140%"- id="rainbow-line-glow"- width="140%"- x="-20%"- y="-20%"- >- <feGaussianBlur result="blur" stdDeviation="5" />- <feComponentTransfer in="blur" result="dimmedBlur">- <feFuncA slope="0.5" type="linear" />- </feComponentTransfer>- <feComposite- in="SourceGraphic"- in2="dimmedBlur"- operator="over"- />- </filter>- </defs>-- {series.map((serie) => {- const color = getChartColor(serie.index);- return (- <Line- dataKey={`${serie.id}:count`}- dot={dataLength <= 8}- fill={color}- filter={- series.length === 1- ? 'url(#rainbow-line-glow)'- : undefined- }- isAnimationActive={false}- key={serie.id}- name={serie.id}- stroke={color}- strokeDasharray={- useDashedLastLine- ? getStrokeDasharray(`${serie.id}:count`)- : undefined- }- // Use for legend- strokeWidth={2}- type={lineType}- />- );- })}-- {previous- ? series.map((serie) => {- const color = getChartColor(serie.index);- return (- <Line- dataKey={`${serie.id}:prev:count`}- dot={false}- fill={color}- isAnimationActive- key={`${serie.id}:prev`}- name={`${serie.id}:prev`}- stroke={color}- strokeOpacity={0.3}- // Use for legend- type={lineType}- />- );- })- : null}- </ComposedChart>- </ResponsiveContainer>- </div>- {isEditMode && (- <ReportTable- data={data}- setVisibleSeries={setVisibleSeries}- visibleSeries={series}+ markers={POINT_MARKER}+ showMarkers={chart.showMarkers}+ stroke={getChartColor(serie.index)}+ strokeWidth={2}/>- )}- </ChartClickMenu>- </ReportChartTooltip.TooltipProvider>+ ))}+ <OPReferences items={chart.references} />+ <OPChartTooltip<TimeSeriesPoint>+ extra={chart.tooltipExtra}+ interval={chart.interval}+ references={chart.references}+ rows={chart.tooltipRows}+ showCrosshair+ showDots+ />+ <PointClick<TimeSeriesPoint> onClick={chart.menu.openMenu} />+ </LineChart>+ </TimeSeriesFrame>);}diff --git a/apps/start/src/components/report-chart/line/index.tsx b/apps/start/src/components/report-chart/line/index.tsxindex 52a027e87..e055aa4ba 100644--- a/apps/start/src/components/report-chart/line/index.tsx+++ b/apps/start/src/components/report-chart/line/index.tsx@@ -3,6 +3,7 @@ import { AspectContainer } from '../aspect-container';import { ReportChartEmpty } from '../common/empty';import { ReportChartError } from '../common/error';import { ReportChartLoading } from '../common/loading';+import { SeriesWithTable } from '../common/series-with-table';import { useChartInput, useReportChartContext } from '../context';import { Chart } from './chart';import { useTRPC } from '@/integrations/trpc/react';@@ -41,9 +42,10 @@ export function ReportLineChart() {}return (- <AspectContainer>- <Chart data={res.data} />- </AspectContainer>+ <SeriesWithTable+ chart={(series) => <Chart data={res.data} series={series} />}+ data={res.data}+ />);}diff --git a/apps/start/src/components/report-chart/map/chart.tsx b/apps/start/src/components/report-chart/map/chart.tsxindex f7ed67424..44de3aef9 100644--- a/apps/start/src/components/report-chart/map/chart.tsx+++ b/apps/start/src/components/report-chart/map/chart.tsx@@ -1,10 +1,29 @@-import { useMemo } from 'react';-import WorldMap from 'react-svg-worldmap';-import AutoSizer from 'react-virtualized-auto-sizer';+import { useEffect, useMemo, useRef } from 'react';import { useReportChartContext } from '../context';+import { WORLD_COUNTRIES } from './world-geo';+import {+ ChoroplethChart,+ type ChoroplethFeature,+ ChoroplethFeatureComponent,+ ChoroplethTooltip,+ useChoropleth,+} from '@/components/charts/choropleth';+import { useElementSize } from '@/hooks/use-element-size';import { useEventQueryFilters } from '@/hooks/use-event-query-filters';+import { useNumber } from '@/hooks/use-numer-formatter';import { useVisibleSeries } from '@/hooks/use-visible-series';import type { IChartData } from '@/trpc/client';+import { cn } from '@/utils/cn';++const ALL_COUNTRIES = 99_999;+// Mercator world width and visible height per unit of projection scale.+const WORLD_WIDTH_PER_SCALE = 6.3;+const WORLD_HEIGHT_PER_SCALE = 3.6;+// The projection centres on the equator; the map has more land north of it.+const NORTH_SHIFT_PER_SCALE = 0.5;+// The faintest share of the brand colour, so countries with few visitors still read as "some".+const MIN_FILL_SHARE = 15;+const NO_DATA_FILL = 'var(--def-200)';interface Props {data: IChartData;@@ -13,34 +32,111 @@ interface Props {export function Chart({ data }: Props) {const {report: { metric, unit },+ layout,} = useReportChartContext();- const { series } = useVisibleSeries(data, { limit: 99_999 });- const [_, setFilter] = useEventQueryFilters();- const mapData = useMemo(+ const number = useNumber();+ const { series } = useVisibleSeries(data, { limit: ALL_COUNTRIES });+ const [, setFilter] = useEventQueryFilters();+ const [sizeRef, size] = useElementSize();++ const valueByCountry = useMemo(() =>- series.map((s) => ({- country: s.names[1]?.toLowerCase() ?? '',- value: s.metrics[metric] ?? 0,- })),+ new Map(+ series.map((serie) => [+ serie.names[1]?.toUpperCase() ?? '',+ serie.metrics[metric] ?? 0,+ ])+ ),[series, metric]);+ const maxValue = Math.max(1, ...valueByCountry.values());++ const scale = Math.min(+ size.width / WORLD_WIDTH_PER_SCALE,+ size.height / WORLD_HEIGHT_PER_SCALE+ );+ const countryValue = (feature: ChoroplethFeature) =>+ valueByCountry.get(String(feature.properties?.id ?? '')) ?? 0;+ const countryColor = (feature: ChoroplethFeature) => {+ const value = countryValue(feature);+ if (!value) {+ return NO_DATA_FILL;+ }+ // Square root so a handful of big countries do not wash out the rest.+ const share =+ MIN_FILL_SHARE + (100 - MIN_FILL_SHARE) * Math.sqrt(value / maxValue);+ return `color-mix(in oklab, var(--chart-0) ${Math.round(share)}%, var(--def-100))`;+ };return (- <AutoSizer disableHeight>- {({ width }) => (- <WorldMap- borderColor={'var(--foreground)'}- color={'var(--chart-0)'}- data={mapData}- onClickFunction={(event) => {- if (event.countryCode) {- setFilter('country', event.countryCode);- }- }}- size={width}- value-suffix={unit}- />+ <div+ className={cn('w-full', layout === 'fill' ? 'h-full' : 'aspect-[2]')}+ data-report-chart="map"+ ref={sizeRef}+ >+ {scale > 0 && (+ <ChoroplethChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-full"+ data={WORLD_COUNTRIES}+ margin={{ top: 0, right: 0, bottom: 0, left: 0 }}+ scale={scale}+ translate={[+ size.width / 2,+ size.height / 2 + scale * NORTH_SHIFT_PER_SCALE,+ ]}+ zoomEnabled={false}+ >+ <ChoroplethFeatureComponent+ getFeatureColor={countryColor}+ stroke="var(--background)"+ strokeWidth={0.5}+ />+ <ChoroplethTooltip+ formatValue={(value) => number.formatWithUnit(value, unit)}+ getFeatureValue={countryValue}+ valueLabel={series[0]?.names[0]}+ />+ <CountryClick+ onClick={(code) => setFilter('country', code)}+ valueOf={countryValue}+ />+ </ChoroplethChart>)}- </AutoSizer>+ </div>);}++/** Clicking a country with data filters the page by it. */+function CountryClick({+ onClick,+ valueOf,+}: {+ onClick: (countryCode: string) => void;+ valueOf: (feature: ChoroplethFeature) => number;+}) {+ const { containerRef, features, hoveredFeatureIndex } = useChoropleth();+ const latest = useRef({ onClick, valueOf, features, hoveredFeatureIndex });+ latest.current = { onClick, valueOf, features, hoveredFeatureIndex };++ useEffect(() => {+ const container = containerRef.current;+ if (!container) {+ return;+ }+ const handleClick = () => {+ const { features, hoveredFeatureIndex, valueOf, onClick } =+ latest.current;+ const feature =+ hoveredFeatureIndex === null ? null : features[hoveredFeatureIndex];+ if (feature && valueOf(feature) > 0) {+ onClick(String(feature.properties?.id));+ }+ };+ container.addEventListener('click', handleClick);+ return () => container.removeEventListener('click', handleClick);+ }, [containerRef]);++ return null;+}diff --git a/apps/start/src/components/report-chart/map/world-geo.ts b/apps/start/src/components/report-chart/map/world-geo.tsnew file mode 100644index 000000000..02f674b8f--- /dev/null+++ b/apps/start/src/components/report-chart/map/world-geo.ts@@ -0,0 +1,21 @@+import type { FeatureCollection, MultiPolygon } from 'geojson';+import countries from 'react-svg-worldmap/dist/countries.geo';+import type { ChoroplethFeatureProperties } from '@/components/charts/choropleth';++/**+ * Country outlines keyed by ISO 3166 alpha-2 code, the code our country+ * breakdowns use. They come with react-svg-worldmap, already a dependency,+ * in its own compact shape (`N` name, `I` code, `C` MultiPolygon coordinates).+ */+export const WORLD_COUNTRIES: FeatureCollection<+ MultiPolygon,+ ChoroplethFeatureProperties+> = {+ type: 'FeatureCollection',+ features: countries.features.map((country) => ({+ type: 'Feature',+ id: country.I,+ properties: { name: country.N, id: country.I },+ geometry: { type: 'MultiPolygon', coordinates: country.C },+ })),+};diff --git a/apps/start/src/components/report-chart/metric/chart.tsx b/apps/start/src/components/report-chart/metric/chart.tsxindex 557304218..e4004a1cb 100644--- a/apps/start/src/components/report-chart/metric/chart.tsx+++ b/apps/start/src/components/report-chart/metric/chart.tsx@@ -1,5 +1,6 @@import { useReportChartContext } from '../context';import { MetricCard } from './metric-card';+import { MetricPager } from './metric-pager';import { useVisibleSeries } from '@/hooks/use-visible-series';import type { IChartData } from '@/trpc/client';import { cn } from '@/utils/cn';@@ -11,26 +12,28 @@ interface Props {export function Chart({ data }: Props) {const {isEditMode,+ layout,report: { metric, unit },} = useReportChartContext();- const { series } = useVisibleSeries(data, { limit: isEditMode ? 20 : 4 });+ const isTile = layout === 'fill';+ const { series } = useVisibleSeries(data, {+ limit: isTile || isEditMode ? 20 : 4,+ });++ if (isTile) {+ return <MetricPager metric={metric} series={series} unit={unit} />;+ }+return (<divclassName={cn(- 'grid grid-cols-1 gap-4',- isEditMode && 'md:grid-cols-2 lg:grid-cols-3'+ 'card grid grid-cols-2 overflow-hidden rounded-md',+ isEditMode && 'md:grid-cols-4')}>- {series.map((serie) => {- return (- <MetricCard- key={serie.id}- metric={metric}- serie={serie}- unit={unit}- />- );- })}+ {series.map((serie) => (+ <MetricCard key={serie.id} metric={metric} serie={serie} unit={unit} />+ ))}</div>);}diff --git a/apps/start/src/components/report-chart/metric/metric-card.tsx b/apps/start/src/components/report-chart/metric/metric-card.tsxindex 2cafe47ee..27edbf48f 100644--- a/apps/start/src/components/report-chart/metric/metric-card.tsx+++ b/apps/start/src/components/report-chart/metric/metric-card.tsx@@ -1,178 +1,50 @@import type { IChartMetric } from '@openpanel/core/modules/report/report.constants';-import AutoSizer from 'react-virtualized-auto-sizer';-import { Area, AreaChart, Tooltip } from 'recharts';-import {- getDiffIndicator,- PreviousDiffIndicator,-} from '../common/previous-diff-indicator';-import { SerieName } from '../common/serie-name';+import { useMemo } from 'react';import { useReportChartContext } from '../context';import {- ChartTooltipContainer,- ChartTooltipHeader,- ChartTooltipItem,-} from '@/components/charts/chart-tooltip';-import { fancyMinutes, useNumber } from '@/hooks/use-numer-formatter';+ type MetricUnit,+ OverviewMetricCard,+} from '@/components/overview/overview-metric-card';import type { IChartData } from '@/trpc/client';-import { cn } from '@/utils/cn';-import { formatDate } from '@/utils/date';-import { getChartColor } from '@/utils/theme';++// Report units the card formats itself; any other unit shows the plain number.+const CARD_UNITS: Record<string, MetricUnit> = { min: 'min', '%': '%' };interface MetricCardProps {serie: IChartData['series'][number];- color?: string;metric: IChartMetric;unit?: string;+ fill?: boolean;}-const TooltipContent = (props: { payload?: any[] }) => {- const number = useNumber();- return (- <ChartTooltipContainer>- {props.payload?.map((item) => {- const { date, count } = item.payload;- return (- <div className="col gap-2" key={item.id}>- <ChartTooltipHeader>- <div>{formatDate(new Date(date))}</div>- </ChartTooltipHeader>- <ChartTooltipItem color={getChartColor(0)}>- <div>{number.format(count)}</div>- </ChartTooltipItem>- </div>- );- })}- </ChartTooltipContainer>- );-};--export function MetricCard({- serie,- color: _color,- metric,- unit,-}: MetricCardProps) {- const { isEditMode } = useReportChartContext();- const number = useNumber();-- const renderValue = (value: number | undefined, unitClassName?: string) => {- // A genuine 0 is a real value, not a missing one — `min` is 0 whenever the- // range contains an empty bucket. Only absent metrics render as N/A, which- // still matters: getAggregateChartSql never selects total_count, so `count`- // really is undefined for bar/pie series.- if (value === undefined || value === null) {- return <div className="text-muted-foreground">N/A</div>;- }-- if (unit === 'min') {- return <>{fancyMinutes(value)}</>;- }-- return (- <>- {number.short(value)}- {unit && <span className={unitClassName}>{unit}</span>}- </>- );- };-- const previous = serie.metrics.previous?.[metric];-- const graphColors = getDiffIndicator(- false,- previous?.state,- '#6ee7b7', // green- '#fda4af', // red- '#93c5fd' // blue+/** One series of a metric report, drawn as the overview's metric card. */+export function MetricCard({ serie, metric, unit, fill }: MetricCardProps) {+ const {+ report: { interval, range },+ } = useReportChartContext();+ const buckets = useMemo(+ () =>+ serie.data.map((item) => ({+ date: item.date,+ current: item.count,+ previous: item.previous?.value,+ })),+ [serie.data]);return (- <div- className={cn(- 'group relative p-4 hover:z-10',- isEditMode && 'card h-auto'- )}- key={serie.id}- >- <div- className={cn(- 'absolute top-0 -right-1 bottom-0 -left-1 z-0 opacity-100 transition-opacity duration-300 group-hover:opacity-100'- )}- >- <AutoSizer>- {({ width, height }) => (- <AreaChart- data={serie.data}- height={height / 4}- style={{ marginTop: (height / 4) * 3 }}- width={width}- >- <defs>- <linearGradient- id={`colorUv${serie.id}`}- x1="0"- x2="0"- y1="0"- y2="1"- >- <stop offset="0%" stopColor={graphColors} stopOpacity={0.2} />- <stop- offset="100%"- stopColor={graphColors}- stopOpacity={0.05}- />- </linearGradient>- </defs>- <Tooltip content={TooltipContent} />- <Area- dataKey="count"- fill={`url(#colorUv${serie.id})`}- fillOpacity={1}- isAnimationActive={false}- stroke={graphColors}- strokeWidth={1}- type="step"- />- </AreaChart>- )}- </AutoSizer>- </div>- <MetricCardNumber- enhancer={- <PreviousDiffIndicator- {...previous}- className="text-muted-foreground text-sm"- />- }- label={<SerieName name={serie.names} />}- value={renderValue(serie.metrics[metric], 'ml-1 font-light text-xl')}- />- </div>- );-}--export function MetricCardNumber({- label,- value,- enhancer,- className,-}: {- label: React.ReactNode;- value: React.ReactNode;- enhancer?: React.ReactNode;- className?: string;-}) {- return (- <div className={cn('flex min-w-0 flex-col gap-2', className)}>- <div className="flex items-center justify-between gap-2">- <div className="flex min-w-0 items-center gap-2 text-left">- <span className="truncate text-muted-foreground">{label}</span>- </div>- </div>- <div className="flex items-end justify-between gap-4">- <div className="truncate font-bold font-mono text-3xl">{value}</div>- {enhancer}- </div>- </div>+ <OverviewMetricCard+ data={buckets}+ fill={fill}+ id={serie.id}+ interval={interval}+ label={serie.names.join(' › ')}+ metric={{+ current: serie.metrics[metric] ?? 0,+ previous: serie.metrics.previous?.[metric]?.value,+ }}+ range={range}+ unit={unit ? (CARD_UNITS[unit] ?? '') : ''}+ />);}diff --git a/apps/start/src/components/report-chart/metric/metric-pager.tsx b/apps/start/src/components/report-chart/metric/metric-pager.tsxnew file mode 100644index 000000000..3b20d9833--- /dev/null+++ b/apps/start/src/components/report-chart/metric/metric-pager.tsx@@ -0,0 +1,118 @@+import type { IChartMetric } from '@openpanel/core/modules/report/report.constants';+import { useEffect, useState } from 'react';+import AutoSizer from 'react-virtualized-auto-sizer';+import { MetricCard } from './metric-card';+import {+ Carousel,+ type CarouselApi,+ CarouselContent,+ CarouselItem,+} from '@/components/ui/carousel';+import type { IVisibleSeries } from '@/hooks/use-visible-series';+import { cn } from '@/utils/cn';++const MIN_CARD_WIDTH = 200;+const MAX_CARDS_PER_PAGE = 3;+const CARD_BASIS = {+ 1: 'basis-full',+ 2: 'basis-1/2',+ 3: 'basis-1/3',+} as const;++interface MetricPagerProps {+ series: IVisibleSeries;+ metric: IChartMetric;+ unit?: string;+}++// A tile shows as many whole metric cards as fit side by side; the rest are+// a swipe away, one page per set.+export function MetricPager({ series, metric, unit }: MetricPagerProps) {+ return (+ <AutoSizer>+ {({ width, height }) => {+ const perPage = Math.max(+ 1,+ Math.min(MAX_CARDS_PER_PAGE, Math.floor(width / MIN_CARD_WIDTH))+ ) as keyof typeof CARD_BASIS;+ return (+ <Pages+ height={height}+ key={perPage}+ metric={metric}+ perPage={perPage}+ series={series}+ unit={unit}+ width={width}+ />+ );+ }}+ </AutoSizer>+ );+}++function Pages({+ series,+ metric,+ unit,+ perPage,+ width,+ height,+}: MetricPagerProps & {+ perPage: keyof typeof CARD_BASIS;+ width: number;+ height: number;+}) {+ const [api, setApi] = useState<CarouselApi>();+ const [page, setPage] = useState(0);+ const pageCount = Math.ceil(series.length / perPage);++ useEffect(() => {+ if (!api) {+ return;+ }+ const onSelect = () => setPage(api.selectedScrollSnap());+ onSelect();+ api.on('select', onSelect);+ return () => {+ api.off('select', onSelect);+ };+ }, [api]);++ return (+ <div className="relative" style={{ width, height }}>+ <Carousel+ className="h-full [&>div]:h-full"+ opts={{ align: 'start', slidesToScroll: perPage }}+ setApi={setApi}+ >+ <CarouselContent className="h-full">+ {series.map((serie) => (+ <CarouselItem+ className={cn('h-full pl-0', CARD_BASIS[perPage])}+ key={serie.id}+ >+ <MetricCard fill metric={metric} serie={serie} unit={unit} />+ </CarouselItem>+ ))}+ </CarouselContent>+ </Carousel>+ {pageCount > 1 && (+ <div className="absolute inset-x-0 bottom-1.5 flex justify-center gap-1.5">+ {Array.from({ length: pageCount }, (_, index) => (+ <button+ aria-label={`Page ${index + 1} of ${pageCount}`}+ className={cn(+ 'size-1.5 rounded-full transition-colors',+ index === page ? 'bg-foreground' : 'bg-foreground/20'+ )}+ key={series[index * perPage]?.id ?? index}+ onClick={() => api?.scrollTo(index)}+ type="button"+ />+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/apps/start/src/components/report-chart/pie/chart.tsx b/apps/start/src/components/report-chart/pie/chart.tsxindex bc1a99873..15fc2868e 100644--- a/apps/start/src/components/report-chart/pie/chart.tsx+++ b/apps/start/src/components/report-chart/pie/chart.tsx@@ -1,188 +1,143 @@import { round } from '@openpanel/shared';-import { Fragment } from 'react';-import { Cell, Pie, PieChart, ResponsiveContainer, Tooltip } from 'recharts';-import { AXIS_FONT_PROPS } from '../common/axis';-import { PreviousDiffIndicator } from '../common/previous-diff-indicator';-import { ReportTable } from '../common/report-table';+import { useMemo, useState } from 'react';+import { getLabelNames } from '../common/label-names';import { SerieIcon } from '../common/serie-icon';import { SerieName } from '../common/serie-name';import { useReportChartContext } from '../context';-import {- ChartTooltipContainer,- ChartTooltipHeader,- ChartTooltipItem,-} from '@/components/charts/chart-tooltip';-import { changeVisibleSeries } from '@/components/report/reportSlice';+import { PieCenter } from '@/components/charts/pie-center';+import { DEFAULT_HOVER_OFFSET, PieChart } from '@/components/charts/pie-chart';+import { PieSlice } from '@/components/charts/pie-slice';+import { useElementSize } from '@/hooks/use-element-size';import { useNumber } from '@/hooks/use-numer-formatter';-import { useVisibleSeries } from '@/hooks/use-visible-series';-import { useDispatch } from '@/redux';-import type { IChartData } from '@/trpc/client';+import type { IVisibleSeries } from '@/hooks/use-visible-series';import { cn } from '@/utils/cn';-import { formatDate } from '@/utils/date';import { getChartColor } from '@/utils/theme';-import { truncate } from '@/utils/truncate';++const DONUT_HOLE = 0.6;+const PAD_ANGLE = 0.02;+const CORNER_RADIUS = 4;+// Wider than this (width / height) and the legend goes beside the donut.+const SIDE_LEGEND_RATIO = 1.3;interface Props {- data: IChartData;+ series: IVisibleSeries;}-const PieTooltip = (props: { payload?: any[] }) => {+export function Chart({ series }: Props) {+ const { isEditMode } = useReportChartContext();const number = useNumber();- return (- <ChartTooltipContainer>- {props.payload?.map((serie, index) => {- const item = serie.payload;- return (- <Fragment key={item.id}>- {index === 0 && item.date && (- <ChartTooltipHeader>- <div>{formatDate(new Date(item.date))}</div>- </ChartTooltipHeader>- )}- <ChartTooltipItem color={item.color}>- <div className="flex items-center gap-1">- <SerieIcon name={item.name} />- <SerieName className="font-medium" name={item.names} />- </div>- <div className="flex justify-between gap-8 font-medium font-mono">- <div className="row gap-1">- {number.formatWithUnit(item.count)}- {!!item.previous && (- <span className="text-muted-foreground">- ({number.formatWithUnit(item.previous.sum.value)})- </span>- )}- </div>- <PreviousDiffIndicator {...item.previous?.sum} />- </div>- </ChartTooltipItem>- </Fragment>- );- })}- </ChartTooltipContainer>- );-};+ const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);+ const [frameRef, frame] = useElementSize();+ const [pieRef, pieBox] = useElementSize();-export function Chart({ data }: Props) {- const {- isEditMode,- report: { visibleSeries: savedVisibleSeries },- } = useReportChartContext();- const dispatch = useDispatch();- const { series, setVisibleSeries } = useVisibleSeries(data, {- savedVisibleSeries,- onVisibleSeriesChange: isEditMode- ? (ids) => dispatch(changeVisibleSeries(ids))- : undefined,- });+ const slices = useMemo(() => {+ const total = series.reduce((sum, serie) => sum + serie.metrics.sum, 0);+ const labelNames = getLabelNames(series);+ return series.map((serie) => ({+ id: serie.id,+ names: labelNames(serie.names),+ label: serie.names.join(' › '),+ value: serie.metrics.sum,+ share: total ? round((serie.metrics.sum / total) * 100, 1) : 0,+ color: getChartColor(serie.index),+ }));+ }, [series]);- const sum = series.reduce((acc, serie) => acc + serie.metrics.sum, 0);- const pieData = series.map((serie) => ({- id: serie.id,- color: getChartColor(serie.index),- index: serie.index,- name: serie.names.join(' > '),- names: serie.names,- count: serie.metrics.sum,- percent: serie.metrics.sum / sum,- previous: serie.metrics.previous ? serie.metrics.previous : undefined,- }));+ const isSideLegend = frame.width > frame.height * SIDE_LEGEND_RATIO;+ const pieSize = Math.min(pieBox.width, pieBox.height);+ const innerRadius = Math.max(+ 0,+ (pieSize / 2 - DEFAULT_HOVER_OFFSET) * DONUT_HOLE+ );return (- <>+ <div className={cn('h-full w-full', isEditMode && 'card p-4')}><div- className={cn('h-full w-full max-sm:-mx-3', isEditMode && 'card p-4')}+ className={cn(+ 'flex h-full w-full gap-4',+ isSideLegend ? 'flex-row items-center' : 'col'+ )}+ data-report-chart="pie"+ ref={frameRef}>- <ResponsiveContainer>- <PieChart>- <Tooltip content={<PieTooltip />} />- <Pie- data={pieData}- dataKey={'count'}- innerRadius={'30%'}- isAnimationActive={false}- label={renderLabel}- outerRadius={'80%'}- >- {pieData.map((item) => {- return (- <Cell- className="stroke-background"- fill={item.color}- key={item.id}- strokeWidth={4}- />- );- })}- </Pie>- </PieChart>- </ResponsiveContainer>+ <div+ className="relative min-h-0 min-w-0 flex-1 self-stretch"+ ref={pieRef}+ >+ {pieSize > 0 && (+ <div className="absolute inset-0 flex items-center justify-center">+ <PieChart+ cornerRadius={CORNER_RADIUS}+ data={slices}+ hoveredIndex={hoveredIndex}+ innerRadius={innerRadius}+ onHoverChange={setHoveredIndex}+ padAngle={PAD_ANGLE}+ size={pieSize}+ >+ {slices.map((slice, index) => (+ <PieSlice animate={false} index={index} key={slice.id} />+ ))}+ <PieCenter>+ {({ value, isHovered }) => {+ const slice =+ hoveredIndex === null ? null : slices[hoveredIndex];+ return (+ <div className="col max-w-[80%] items-center text-center">+ <div className="font-mono font-semibold text-lg">+ {number.short(value)}+ </div>+ <div className="w-full truncate text-muted-foreground text-xs">+ {isHovered && slice ? `${slice.share}%` : 'Total'}+ </div>+ </div>+ );+ }}+ </PieCenter>+ </PieChart>+ </div>+ )}+ </div>+ <ul+ className={cn(+ 'col min-h-0 shrink-0 gap-0.5 overflow-y-auto text-sm',+ isSideLegend ? 'w-1/2 max-w-72' : 'max-h-[40%] w-full'+ )}+ >+ {slices.map((slice, index) => (+ <li key={slice.id}>+ <button+ className={cn(+ 'flex w-full items-center gap-2 rounded px-1.5 py-1 text-left transition-opacity',+ hoveredIndex !== null &&+ hoveredIndex !== index &&+ 'opacity-50'+ )}+ onBlur={() => setHoveredIndex(null)}+ onFocus={() => setHoveredIndex(index)}+ onMouseEnter={() => setHoveredIndex(index)}+ onMouseLeave={() => setHoveredIndex(null)}+ type="button"+ >+ <span+ className="size-2.5 shrink-0 rounded-full"+ style={{ background: slice.color }}+ />+ <SerieIcon name={slice.names} />+ <div className="min-w-0 flex-1 overflow-hidden whitespace-nowrap">+ <SerieName name={slice.names} />+ </div>+ <span className="font-mono font-semibold">+ {number.short(slice.value)}+ </span>+ <span className="w-12 text-right font-mono text-muted-foreground">+ {slice.share}%+ </span>+ </button>+ </li>+ ))}+ </ul></div>- {isEditMode && (- <ReportTable- data={data}- setVisibleSeries={setVisibleSeries}- visibleSeries={series}- />- )}- </>+ </div>);}--const renderLabel = ({- cx,- cy,- midAngle,- innerRadius,- outerRadius,- fill,- payload,-}: {- cx: number;- cy: number;- midAngle: number;- innerRadius: number;- outerRadius: number;- fill: string;- payload: { name: string; percent: number };-}) => {- const RADIAN = Math.PI / 180;- const radius = 25 + innerRadius + (outerRadius - innerRadius);- const radiusProcent = innerRadius + (outerRadius - innerRadius) * 0.5;- const xProcent = cx + radiusProcent * Math.cos(-midAngle * RADIAN);- const yProcent = cy + radiusProcent * Math.sin(-midAngle * RADIAN);- const x = cx + radius * Math.cos(-midAngle * RADIAN);- const y = cy + radius * Math.sin(-midAngle * RADIAN);- const name = payload.name;- const percent = round(payload.percent * 100, 1);-- return (- <>- <text- dominantBaseline="central"- fill="white"- pointerEvents={'none'}- textAnchor="middle"- x={xProcent}- y={yProcent}- {...AXIS_FONT_PROPS}- fontSize={12}- fontWeight={700}- >- {percent}%- </text>- <text- dominantBaseline="central"- fill={fill}- textAnchor={x > cx ? 'start' : 'end'}- x={x}- y={y}- {...AXIS_FONT_PROPS}- fontSize={10}- fontWeight={700}- >- {truncate(name, 20)}- </text>- </>- );-};diff --git a/apps/start/src/components/report-chart/pie/index.tsx b/apps/start/src/components/report-chart/pie/index.tsxindex 97a426c34..31ff01eeb 100644--- a/apps/start/src/components/report-chart/pie/index.tsx+++ b/apps/start/src/components/report-chart/pie/index.tsx@@ -3,6 +3,7 @@ import { AspectContainer } from '../aspect-container';import { ReportChartEmpty } from '../common/empty';import { ReportChartError } from '../common/error';import { ReportChartLoading } from '../common/loading';+import { SeriesWithTable } from '../common/series-with-table';import { useChartInput, useReportChartContext } from '../context';import { Chart } from './chart';import { useTRPC } from '@/integrations/trpc/react';@@ -42,9 +43,11 @@ export function ReportPieChart() {}return (- <AspectContainer>- <Chart data={res.data} />- </AspectContainer>+ <SeriesWithTable+ chart={(series) => <Chart series={series} />}+ data={res.data}+ table="ranked"+ />);}diff --git a/apps/start/src/components/report-chart/retention/chart.tsx b/apps/start/src/components/report-chart/retention/chart.tsxindex 5ef311b5d..1040ed94a 100644--- a/apps/start/src/components/report-chart/retention/chart.tsx+++ b/apps/start/src/components/report-chart/retention/chart.tsx@@ -1,109 +1,132 @@import { average, round } from '@openpanel/shared';-import {- Area,- CartesianGrid,- ComposedChart,- ReferenceLine,- ResponsiveContainer,- Tooltip,- XAxis,- YAxis,-} from 'recharts';-import { useXAxisProps, useYAxisProps } from '../common/axis';+import { curveMonotoneX } from 'd3-shape';+import { useCallback, useMemo } from 'react';import { useReportChartContext } from '../context';-import { RetentionTooltip } from './tooltip';+import { Area, AreaChart } from '@/components/charts/area-chart';+import { Grid } from '@/components/charts/grid';+import { Line } from '@/components/charts/line';+import { OPChartTooltip } from '@/components/charts/op-tooltip';+import { XAxis } from '@/components/charts/x-axis';+import { YAxis } from '@/components/charts/y-axis';+import { useNumber } from '@/hooks/use-numer-formatter';import type { RouterOutputs } from '@/trpc/client';import { cn } from '@/utils/cn';import { getChartColor } from '@/utils/theme';+// bklit's x axis is a time axis; periods since the cohort start are laid out+// as consecutive days from the epoch and read back by the axis formatter.+const PERIOD_MS = 86_400_000;+const AXIS_MARGIN = { top: 12, right: 12, bottom: 28, left: 40 };+const BARE_MARGIN = { top: 12, right: 12, bottom: 12, left: 12 };+const RETENTION_COLOR = getChartColor(0);+const AVERAGE_COLOR = getChartColor(1);+interface Props {data: RouterOutputs['chart']['cohort'];}+interface RetentionPoint {+ [key: string]: unknown;+ date: Date;+ period: number;+ percentage: number;+ average: number;+ retained: number;+ total: number;+}++const periodOf = (date: Date) => Math.round(date.getTime() / PERIOD_MS);+export function Chart({ data }: Props) {const {report: { interval },isEditMode,options: { hideXAxis, hideYAxis },} = useReportChartContext();-- const xAxisProps = useXAxisProps({ interval, hide: hideXAxis });- const yAxisProps = useYAxisProps({- hide: hideYAxis,- tickFormatter: (value) => `${value}%`,- });+ const number = useNumber();const averageRow = data[0];- const averageRetentionRate =- average(averageRow?.percentages || [], true) * 100;- const rechartData = averageRow?.percentages.map((item, index) => ({- days: index,- percentage: item * 100,- value: averageRow.values?.[index],- sum: averageRow.sum,- }));+ const averageRate = average(averageRow?.percentages ?? [], true) * 100;++ const points = useMemo(+ () =>+ (averageRow?.percentages ?? []).map(+ (rate, period): RetentionPoint => ({+ date: new Date(period * PERIOD_MS),+ period,+ percentage: rate * 100,+ average: averageRate,+ retained: averageRow?.values?.[period] ?? 0,+ total: averageRow?.sum ?? 0,+ })+ ),+ [averageRow, averageRate]+ );++ const formatPeriod = useCallback((date: Date) => String(periodOf(date)), []);return (- <>- <div className={cn('h-full w-full', isEditMode && 'card p-4')}>- <ResponsiveContainer>- <ComposedChart data={rechartData}>- <CartesianGrid- className="stroke-border"- horizontal={true}- strokeDasharray="3 3"- vertical={true}- />- <YAxis {...yAxisProps} dataKey="retentionRate" domain={[0, 100]} />- <XAxis- {...xAxisProps}- allowDuplicatedCategory- dataKey="days"- interval={0}- scale="linear"- tickCount={31}- tickFormatter={(value) => value.toString()}- />- <Tooltip content={<RetentionTooltip />} />- <defs>- <linearGradient id={'color'} x1="0" x2="0" y1="0" y2="1">- <stop- offset="0%"- stopColor={getChartColor(0)}- stopOpacity={0.8}- />- <stop- offset="100%"- stopColor={getChartColor(0)}- stopOpacity={0.1}- />- </linearGradient>- </defs>- <ReferenceLine- label={{- value: `Average (${round(averageRetentionRate, 2)} %)`,- fill: getChartColor(1),- position: 'insideBottomRight',- fontSize: 12,- }}- stroke={getChartColor(1)}- strokeDasharray="3 3"- strokeLinecap="round"- strokeOpacity={0.5}- strokeWidth={2}- y={averageRetentionRate}- />- <Area- dataKey="percentage"- fill={'url(#color)'}- fillOpacity={0.1}- isAnimationActive={false}- stroke={getChartColor(0)}- strokeWidth={2}- type={'monotone'}- />- </ComposedChart>- </ResponsiveContainer>+ <div+ className={cn('relative h-full w-full', isEditMode && 'card p-4')}+ data-report-chart="retention"+ >+ <AreaChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-full"+ data={points}+ formatDateLabel={formatPeriod}+ margin={hideXAxis && hideYAxis ? BARE_MARGIN : AXIS_MARGIN}+ style={{ touchAction: 'pan-y' }}+ xDataKey="date"+ >+ <Grid horizontal />+ {!hideYAxis && <YAxis formatValue={(value) => `${value}%`} />}+ {!hideXAxis && <XAxis />}+ <Area+ animate={false}+ curve={curveMonotoneX}+ dataKey="percentage"+ fill={RETENTION_COLOR}+ stroke={RETENTION_COLOR}+ />+ <Line+ animate={false}+ dashArray="4,4"+ dashFromIndex={0}+ dataKey="average"+ showHighlight={false}+ stroke={AVERAGE_COLOR}+ strokeWidth={1.5}+ />+ <OPChartTooltip<RetentionPoint>+ datePill={false}+ rows={(point) => [+ {+ color: RETENTION_COLOR,+ label: 'Retention rate',+ value: point.percentage,+ format: (value) => number.formatWithUnit(value / 100, '%'),+ sub: [+ { label: 'Retained users', value: point.retained },+ { label: 'Total users', value: point.total },+ ],+ },+ ]}+ showCrosshair+ showDots+ title={(point) => (+ <span className="capitalize">+ {interval} {point.period}+ </span>+ )}+ />+ </AreaChart>+ <div+ className="pointer-events-none absolute top-2 right-3 font-medium text-xs"+ style={{ color: AVERAGE_COLOR }}+ >+ Average ({round(averageRate, 2)} %)</div>- </>+ </div>);}diff --git a/apps/start/src/components/report-chart/retention/index.tsx b/apps/start/src/components/report-chart/retention/index.tsxindex ba28f58b6..73e26a002 100644--- a/apps/start/src/components/report-chart/retention/index.tsx+++ b/apps/start/src/components/report-chart/retention/index.tsx@@ -1,11 +1,12 @@import { keepPreviousData, useQuery } from '@tanstack/react-query';import { AspectContainer } from '../aspect-container';+import { ChartWithTable, TableCard } from '../common/chart-with-table';import { ReportChartEmpty } from '../common/empty';import { ReportChartError } from '../common/error';import { ReportChartLoading } from '../common/loading';import { useReportChartContext } from '../context';import { Chart } from './chart';-import CohortTable from './table';+import { CohortTable } from './table';import { useTRPC } from '@/integrations/trpc/react';export function ReportRetentionChart() {@@ -22,8 +23,7 @@ export function ReportRetentionChart() {(item.filters ?? []).filter((filter) => filter.name !== 'name')),];- const isEnabled =- firstEvent.length > 0 && secondEvent.length > 0 && !isLazyLoading;+ const hasEvents = firstEvent.length > 0 && secondEvent.length > 0;const retentionOptions =report.options?.type === 'retention' ? report.options : undefined;@@ -47,12 +47,12 @@ export function ReportRetentionChart() {},{placeholderData: keepPreviousData,- enabled: isEnabled,+ enabled: hasEvents && !isLazyLoading,}));- if (!isEnabled) {+ if (!hasEvents) {return <Disabled />;}@@ -69,12 +69,14 @@ export function ReportRetentionChart() {}return (- <div className="col gap-4">- <AspectContainer>- <Chart data={res.data} />- </AspectContainer>- <CohortTable data={res.data} />- </div>+ <ChartWithTable+ chart={<Chart data={res.data} />}+ tables={+ <TableCard>+ <CohortTable data={res.data} />+ </TableCard>+ }+ />);}diff --git a/apps/start/src/components/report-chart/retention/table.tsx b/apps/start/src/components/report-chart/retention/table.tsxindex 467a29a76..1118083e0 100644--- a/apps/start/src/components/report-chart/retention/table.tsx+++ b/apps/start/src/components/report-chart/retention/table.tsx@@ -1,133 +1,65 @@-import { max, min } from '@openpanel/shared';+import { useMemo } from 'react';import { useReportChartContext } from '../context';+import {+ type ReportColumn,+ ReportDataTable,+ type ReportRowIdentity,+} from '@/components/report-table/report-data-table';import { useNumber } from '@/hooks/use-numer-formatter';import type { RouterOutputs } from '@/trpc/client';-import { cn } from '@/utils/cn';-type CohortData = RouterOutputs['chart']['cohort'];+type CohortRow = RouterOutputs['chart']['cohort'][number];-type CohortTableProps = {- data: CohortData;+const COHORT_WIDTH = 170;++const IDENTITY: ReportRowIdentity<CohortRow> = {+ header: 'Cohort',+ render: (row) => row.cohort_interval,+ searchText: (row) => row.cohort_interval,+ width: COHORT_WIDTH,};-const CohortTable: React.FC<CohortTableProps> = ({ data }) => {+/** One row per cohort: how many profiles it started with and how many came back each period. */+export function CohortTable({ data }: { data: CohortRow[] }) {const {- report: { unit, interval },+ report: { unit, interval, name },} = useReportChartContext();- const isPercentage = unit === '%';const number = useNumber();- const highestValue = max(data.map((row) => max(row.values)));- const lowestValue = min(data.map((row) => min(row.values)));- const rowWithHigestSum = data.find(- (row) => row.sum === max(data.map((row) => row.sum))- );-- const getBackground = (value: number | undefined) => {- if (!value) {- return {- backgroundClassName: '',- opacity: 0,- };- }-- const percentage = isPercentage- ? value / 100- : (value - lowestValue) / (highestValue - lowestValue);- const opacity = Math.max(0.05, percentage);-- return {- backgroundClassName: 'bg-highlight dark:bg-emerald-700',- opacity,- };- };+ const isPercentage = unit === '%';+ const periodCount = data[0]?.values.length ?? 0;- const thClassName =- 'h-10 align-top pt-3 whitespace-nowrap font-semibold text-muted-foreground';+ const columns = useMemo<ReportColumn<CohortRow>[]>(+ () => [+ {+ id: 'sum',+ header: 'Total profiles',+ value: (row) => row.sum,+ decorate: 'bar',+ width: 130,+ },+ ...Array.from({ length: periodCount }, (_, period) => ({+ id: `period:${period}`,+ header: period === 0 ? `< ${interval} 1` : `${interval} ${period}`,+ value: (row: CohortRow) =>+ (isPercentage ? row.percentages : row.values)[period],+ render: (row: CohortRow, formatted: string) =>+ isPercentage && row.percentages[period] !== undefined+ ? number.formatWithUnit(row.percentages[period], '%')+ : formatted,+ decorate: 'heat' as const,+ })),+ ],+ [periodCount, interval, isPercentage, number]+ );return (- <div className="card relative overflow-hidden">- <div- className={'absolute top-px right-0 left-0 h-10 border-b bg-def-100'}- />- <div className="hide-scrollbar w-full overflow-x-auto">- <div className="relative min-w-full">- <table className="w-full table-auto whitespace-nowrap">- <thead>- <tr>- <th className={cn(thClassName, 'sticky left-0 z-10')}>- <div className="bg-def-100">- <div className="center-center -mt-3 h-10">Date</div>- </div>- </th>- <th className={cn(thClassName, 'pr-1')}>Total profiles</th>- {data[0]?.values.map((column, index) => (- <th- className={cn(thClassName, 'capitalize')}- key={index.toString()}- >- {index === 0 ? `< ${interval} 1` : `${interval} ${index}`}- </th>- ))}- </tr>- </thead>- <tbody>- {data.map((row) => {- const values = isPercentage ? row.percentages : row.values;- return (- <tr key={row.cohort_interval}>- <td className="sticky left-0 z-10 w-36 bg-card p-0">- <div className="center-center h-10 px-4 font-medium text-muted-foreground">- {row.cohort_interval}- </div>- </td>- <td className="min-w-12 p-0">- <div className={cn('rounded px-3 font-medium font-mono')}>- {number.format(row?.sum)}- {row.cohort_interval ===- rowWithHigestSum?.cohort_interval && ' 🚀'}- </div>- </td>- {values.map((value, index) => {- const { opacity, backgroundClassName } =- getBackground(value);- return (- <td- className="min-w-24 p-0"- key={row.cohort_interval + index.toString()}- >- <div- className={cn(- 'center-center relative h-10 font-mono hover:shadow-[inset_0_0_0_2px_rgb(255,255,255)]',- opacity > 0.7 &&- 'text-white [text-shadow:_0_0_3px_rgb(0_0_0_/_20%)]'- )}- >- <div- className={cn(- backgroundClassName,- 'absolute inset-0 h-full w-full'- )}- style={{- opacity,- }}- />- <div className="relative">- {number.formatWithUnit(value, unit)}- {value === highestValue && ' 🚀'}- </div>- </div>- </td>- );- })}- </tr>- );- })}- </tbody>- </table>- </div>- </div>- </div>+ <ReportDataTable+ columns={columns}+ csvFilename={name || 'retention'}+ getRowId={(row) => row.cohort_interval}+ identity={IDENTITY}+ rows={data}+ searchable={false}+ />);-};--export default CohortTable;+}diff --git a/apps/start/src/components/report-chart/retention/tooltip.tsx b/apps/start/src/components/report-chart/retention/tooltip.tsxdeleted file mode 100644index bf162923a..000000000--- a/apps/start/src/components/report-chart/retention/tooltip.tsx+++ /dev/null@@ -1,46 +0,0 @@-import { useReportChartContext } from '../context';-import { useNumber } from '@/hooks/use-numer-formatter';--type Props = {- active?: boolean;- payload?: Array<{- payload: any;- }>;-};-export function RetentionTooltip({ active, payload }: Props) {- const {- report: { interval },- } = useReportChartContext();- const number = useNumber();- if (!active) {- return null;- }-- if (!payload?.[0]) {- return null;- }-- const { days, percentage, value, sum } = payload[0].payload;-- return (- <div className="flex min-w-[200px] flex-col gap-2 rounded-xl border bg-card p-3 shadow-xl">- <h3 className="font-semibold capitalize">- {interval} {days}- </h3>- <div className="flex justify-between">- <span className="text-muted-foreground">Retention Rate:</span>- <span className="font-medium">- {number.formatWithUnit(percentage / 100, '%')}- </span>- </div>- <div className="flex justify-between">- <span className="text-muted-foreground">Retained Users:</span>- <span className="font-medium">{number.format(value)}</span>- </div>- <div className="flex justify-between">- <span className="text-muted-foreground">Total Users:</span>- <span className="font-medium">{number.format(sum)}</span>- </div>- </div>- );-}diff --git a/apps/start/src/components/report-chart/sankey/chart.tsx b/apps/start/src/components/report-chart/sankey/chart.tsxindex 4792313b0..6af500bb9 100644--- a/apps/start/src/components/report-chart/sankey/chart.tsx+++ b/apps/start/src/components/report-chart/sankey/chart.tsx@@ -1,137 +1,35 @@-import { ResponsiveSankey } from '@nivo/sankey';import { round } from '@openpanel/shared';import { ArrowRightIcon } from 'lucide-react';-import {- type ReactNode,- useLayoutEffect,- useMemo,- useRef,- useState,-} from 'react';-import { createPortal } from 'react-dom';+import { useMemo } from 'react';import { AspectContainer } from '../aspect-container';+import { OPTooltipCard } from '@/components/charts/op-tooltip';import {- ChartTooltipContainer,- ChartTooltipHeader,- ChartTooltipItem,-} from '@/components/charts/chart-tooltip';-import { useTheme } from '@/components/theme-provider';+ SankeyChart,+ SankeyLink,+ SankeyNode,+ SankeyTooltip,+} from '@/components/charts/sankey';+import { useElementSize } from '@/hooks/use-element-size';import { useNumber } from '@/hooks/use-numer-formatter';+import { getChartColor } from '@/utils/theme';import { truncate } from '@/utils/truncate';-type PortalTooltipPosition = { left: number; top: number; ready: boolean };--function SankeyPortalTooltip({- children,- offset = 12,- padding = 8,-}: {- children: ReactNode;- offset?: number;- padding?: number;-}) {- const anchorRef = useRef<HTMLSpanElement | null>(null);- const tooltipRef = useRef<HTMLDivElement | null>(null);- const [anchorRect, setAnchorRect] = useState<DOMRect | null>(null);- const [pos, setPos] = useState<PortalTooltipPosition>({- left: 0,- top: 0,- ready: false,- });- const [mounted, setMounted] = useState(false);-- useLayoutEffect(() => {- setMounted(true);- }, []);-- useLayoutEffect(() => {- const el = anchorRef.current;- if (!el) {- return;- }-- const wrapper = el.parentElement;- if (!wrapper) {- return;- }-- const update = () => {- setAnchorRect(wrapper.getBoundingClientRect());- };-- update();-- const ro = new ResizeObserver(update);- ro.observe(wrapper);-- window.addEventListener('scroll', update, true);- window.addEventListener('resize', update);-- return () => {- ro.disconnect();- window.removeEventListener('scroll', update, true);- window.removeEventListener('resize', update);- };- }, []);-- useLayoutEffect(() => {- if (!mounted) {- return;- }- if (!anchorRect) {- return;- }- const tooltipEl = tooltipRef.current;- if (!tooltipEl) {- return;- }-- const rect = tooltipEl.getBoundingClientRect();- const vw = window.innerWidth;- const vh = window.innerHeight;-- let left = anchorRect.left + offset;- let top = anchorRect.top + offset;-- left = Math.min(- Math.max(padding, left),- Math.max(padding, vw - rect.width - padding)- );- top = Math.min(- Math.max(padding, top),- Math.max(padding, vh - rect.height - padding)- );-- setPos({ left, top, ready: true });- }, [mounted, anchorRect, children, offset, padding]);-- if (typeof document === 'undefined') {- return <>{children}</>;- }-- return (- <>- <span className="sr-only" ref={anchorRef} />- {mounted &&- createPortal(- <div- className="pointer-events-none fixed z-[9999]"- ref={tooltipRef}- style={{- left: pos.left,- top: pos.top,- visibility: pos.ready ? 'visible' : 'hidden',- }}- >- {children}- </div>,- document.body- )}- </>- );-}--type SankeyData = {+// Roughly one character of the 12px label font, to fit labels in their margin.+const LABEL_CHAR_WIDTH = 7;+const LABEL_SHARE = 0.2;+const LABEL_MAX_WIDTH = 170;+const VERTICAL_MARGIN = 24;+const NODE_WIDTH = 12;+const NODE_PADDING = 28;+const NODE_RADIUS = 4;+const LINK_GAP = 2;+const LINK_OPACITY = 0.45;+// Where a session starts or ends is context, not a step: drawn muted so the+// flow between real events stands out.+const SESSION_BOUNDARIES = new Set(['session_start', 'session_end']);+const BOUNDARY_COLOR = 'var(--def-300)';++interface ReportSankeyData {nodes: Array<{id: string;label: string;@@ -141,175 +39,177 @@ type SankeyData = {step?: number;}>;links: Array<{ source: string; target: string; value: number }>;-};+}-export function Chart({ data }: { data: SankeyData }) {+interface SankeyNodeInfo {+ [key: string]: unknown;+ name: string;+ category?: 'source';+ label: string;+ color: string;+ step?: number;+}++export function Chart({ data }: { data: ReportSankeyData }) {const number = useNumber();- const containerRef = useRef<HTMLDivElement>(null);- const { appTheme } = useTheme();+ const [sizeRef, size] = useElementSize();++ const labelWidth = Math.min(size.width * LABEL_SHARE, LABEL_MAX_WIDTH);+ const labelLength = Math.floor(labelWidth / LABEL_CHAR_WIDTH);- // Process data for Sankeyconst sankeyData = useMemo(() => {- if (!data) {- return { nodes: [], links: [] };+ const indexById = new Map(+ data.nodes.map((node, index) => [node.id, index])+ );+ const targets = new Set(data.links.map((link) => link.target));+ const colorByLabel = new Map<string, string>();+ for (const node of data.nodes) {+ const label = node.label || node.id;+ if (!(SESSION_BOUNDARIES.has(label) || colorByLabel.has(label))) {+ colorByLabel.set(label, getChartColor(colorByLabel.size));+ }}-return {- nodes: data.nodes.map((node) => ({- ...node,- label: node.label || node.id,- data: {- percentage: node.percentage,- value: node.value,- step: node.step,+ nodes: data.nodes.map(+ (node): SankeyNodeInfo => ({+ name: truncate(node.label || node.id, labelLength, 'middle'),+ // bklit counts a source by its outgoing flow, every other node by its incoming flow.+ category: targets.has(node.id) ? undefined : 'source',label: node.label || node.id,- },- })),- links: data.links,+ color: colorByLabel.get(node.label || node.id) ?? BOUNDARY_COLOR,+ step: node.step,+ })+ ),+ links: data.links.flatMap((link) => {+ const source = indexById.get(link.source);+ const target = indexById.get(link.target);+ if (source === undefined || target === undefined) {+ return [];+ }+ return [{ source, target, value: link.value }];+ }),};- }, [data]);+ }, [data, labelLength]);+ // Share of the sessions that start the flow, so link and node shares add up per step.const totalSessions = useMemo(() => {- if (!sankeyData.nodes || sankeyData.nodes.length === 0) {- return 0;- }- const step1 = sankeyData.nodes.filter((n: any) => n.data?.step === 1);- const base = step1.length > 0 ? step1 : sankeyData.nodes;- return base.reduce((sum: number, n: any) => sum + (n.data?.value ?? 0), 0);- }, [sankeyData.nodes]);+ const firstStep = data.nodes.filter((node) => node.step === 1);+ const base = firstStep.length > 0 ? firstStep : data.nodes;+ return base.reduce((sum, node) => sum + (node.value ?? 0), 0);+ }, [data.nodes]);+ const shareOfTotal = (value: number) =>+ totalSessions > 0 ? round((value / totalSessions) * 100, 1) : 0;++ const nodeColor = (node: { name?: string; color?: unknown }) =>+ typeof node.color === 'string' ? node.color : 'var(--chart-0)';return (<AspectContainer><div- className="relative aspect-square w-full md:aspect-[2]"- ref={containerRef}+ className="relative h-full w-full"+ data-report-chart="sankey"+ ref={sizeRef}>- <ResponsiveSankey- animate={false}- colors={(node: any) => node.nodeColor}- data={sankeyData}- label={(node: any) => {- const label = node.data?.label || node.label || node.id;- return truncate(label, 30, 'middle');- }}- labelTextColor={appTheme === 'dark' ? '#e2e8f0' : '#0f172a'}- linkBlendMode={'normal'}- linkContract={1}- linkOpacity={0.3}- linkTooltip={({ link }: any) => {- const sourceLabel =- link?.source?.data?.label ??- link?.source?.label ??- link?.source?.id;- const targetLabel =- link?.target?.data?.label ??- link?.target?.label ??- link?.target?.id;-- const value = link?.value ?? 0;- const sourceValue =- link?.source?.data?.value ?? link?.source?.value ?? 0;-- const pctOfTotal =- totalSessions > 0 ? (value / totalSessions) * 100 : 0;- const pctOfSource =- sourceValue > 0 ? (value / sourceValue) * 100 : 0;-- const sourceStep = link?.source?.data?.step;- const targetStep = link?.target?.data?.step;-- const color =- link?.color ??- link?.source?.color ??- link?.source?.data?.nodeColor ??- '#64748b';-- return (- <SankeyPortalTooltip>- <ChartTooltipContainer>- <ChartTooltipHeader>- <div className="min-w-0 flex-1 break-words font-medium">- {sourceLabel}- <ArrowRightIcon className="mx-3 inline-block size-2" />- {targetLabel}+ {size.width > 0 && (+ <SankeyChart+ animationDuration={0}+ aspectRatio="auto"+ className="h-full"+ data={sankeyData}+ margin={{+ top: VERTICAL_MARGIN,+ bottom: VERTICAL_MARGIN,+ left: labelWidth,+ right: labelWidth,+ }}+ nodePadding={NODE_PADDING}+ nodeWidth={NODE_WIDTH}+ >+ <SankeyLink+ getNodeColor={nodeColor}+ linkGap={LINK_GAP}+ strokeOpacity={LINK_OPACITY}+ />+ <SankeyNode getNodeColor={nodeColor} lineCap={NODE_RADIUS} />+ <SankeyTooltip+ linkContent={({ link }) => {+ const source = link.source as unknown as SankeyNodeInfo & {+ value?: number;+ };+ const target = link.target as unknown as SankeyNodeInfo;+ const sourceValue = source.value ?? 0;+ return (+ <OPTooltipCard className="min-w-[220px]">+ <div className="font-medium">+ {source.label}+ <ArrowRightIcon className="mx-2 inline-block size-3" />+ {target.label}</div>- {typeof sourceStep === 'number' &&- typeof targetStep === 'number' && (- <div className="shrink-0 text-muted-foreground">- {sourceStep} → {targetStep}- </div>+ <TooltipStats+ color={nodeColor(source)}+ rows={[+ ['Sessions', number.format(link.value)],+ ['% of total', `${shareOfTotal(link.value)} %`],+ [+ '% of source',+ `${sourceValue > 0 ? round((link.value / sourceValue) * 100, 1) : 0} %`,+ ],+ ]}+ />+ </OPTooltipCard>+ );+ }}+ nodeContent={({ node }) => {+ const info = node as unknown as SankeyNodeInfo & {+ value?: number;+ };+ const value = info.value ?? 0;+ return (+ <OPTooltipCard className="min-w-[220px]">+ <div className="flex justify-between gap-4">+ <span className="font-medium">{info.label}</span>+ {info.step !== undefined && (+ <span className="shrink-0 text-muted-foreground">+ Step {info.step}+ </span>)}- </ChartTooltipHeader>-- <ChartTooltipItem color={color} innerClassName="gap-2">- <div className="flex items-center justify-between gap-8 font-medium font-mono">- <div className="text-muted-foreground">Sessions</div>- <div>{number.format(value)}</div>- </div>- <div className="flex items-center justify-between gap-8 font-mono text-sm">- <div className="text-muted-foreground">% of total</div>- <div>{number.format(round(pctOfTotal, 1))} %</div>- </div>- <div className="flex items-center justify-between gap-8 font-mono text-sm">- <div className="text-muted-foreground">% of source</div>- <div>{number.format(round(pctOfSource, 1))} %</div>- </div>- </ChartTooltipItem>- </ChartTooltipContainer>- </SankeyPortalTooltip>- );- }}- margin={{ top: 20, right: 20, bottom: 20, left: 20 }}- nodeBorderRadius={2}- nodeBorderWidth={0}- nodeOpacity={0.8}- nodeSpacing={10}- nodeTooltip={({ node }: any) => {- const label = node?.data?.label ?? node?.label ?? node?.id;- const value = node?.data?.value ?? node?.value ?? 0;- const step = node?.data?.step;- const pct =- typeof node?.data?.percentage === 'number'- ? node.data.percentage- : totalSessions > 0- ? (value / totalSessions) * 100- : 0;- const color =- node?.color ??- node?.data?.nodeColor ??- node?.data?.color ??- node?.nodeColor ??- '#64748b';-- return (- <SankeyPortalTooltip>- <ChartTooltipContainer className="min-w-[250px]">- <ChartTooltipHeader>- <div className="min-w-0 flex-1 break-words font-medium">- {label}- </div>- {typeof step === 'number' && (- <div className="shrink-0 text-muted-foreground">- Step {step}- </div>- )}- </ChartTooltipHeader>- <ChartTooltipItem color={color} innerClassName="gap-2">- <div className="flex items-center justify-between gap-8 font-medium font-mono">- <div className="text-muted-foreground">Sessions</div>- <div>{number.format(value)}</div>- </div>- <div className="flex items-center justify-between gap-8 font-medium font-mono">- <div className="text-muted-foreground">Share</div>- <div>{number.format(round(pct, 1))} %</div></div>- </ChartTooltipItem>- </ChartTooltipContainer>- </SankeyPortalTooltip>- );- }}- />+ <TooltipStats+ color={nodeColor(info)}+ rows={[+ ['Sessions', number.format(value)],+ ['Share', `${shareOfTotal(value)} %`],+ ]}+ />+ </OPTooltipCard>+ );+ }}+ />+ </SankeyChart>+ )}</div></AspectContainer>);}++function TooltipStats({+ color,+ rows,+}: {+ color: string;+ rows: [label: string, value: string][];+}) {+ return (+ <div className="flex gap-2">+ <div className="w-[3px] rounded-full" style={{ background: color }} />+ <div className="col flex-1 gap-1 font-mono text-sm">+ {rows.map(([label, value]) => (+ <div className="flex justify-between gap-8" key={label}>+ <span className="text-muted-foreground">{label}</span>+ <span>{value}</span>+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/apps/start/src/components/report-chart/sankey/index.tsx b/apps/start/src/components/report-chart/sankey/index.tsxindex 308eff865..430ca1576 100644--- a/apps/start/src/components/report-chart/sankey/index.tsx+++ b/apps/start/src/components/report-chart/sankey/index.tsx@@ -1,11 +1,13 @@import type { IReportInput } from '@openpanel/core/modules/report/report.constants';import { useQuery } from '@tanstack/react-query';import { AspectContainer } from '../aspect-container';+import { ChartWithTable, TableCard } from '../common/chart-with-table';import { ReportChartEmpty } from '../common/empty';import { ReportChartError } from '../common/error';import { ReportChartLoading } from '../common/loading';import { useReportChartContext } from '../context';import { Chart } from './chart';+import { PathsTable } from './table';import { useTRPC } from '@/integrations/trpc/react';export function ReportSankeyChart() {@@ -67,9 +69,15 @@ export function ReportSankeyChart() {}return (- <div className="col gap-4">- <Chart data={res.data} />- </div>+ <ChartWithTable+ chart={<Chart data={res.data} />}+ sizesItself+ tables={+ <TableCard>+ <PathsTable data={res.data} />+ </TableCard>+ }+ />);}diff --git a/apps/start/src/components/report-chart/sankey/table.tsx b/apps/start/src/components/report-chart/sankey/table.tsxnew file mode 100644index 000000000..005a8cbf0--- /dev/null+++ b/apps/start/src/components/report-chart/sankey/table.tsx@@ -0,0 +1,109 @@+import { round } from '@openpanel/shared';+import { ArrowRightIcon } from 'lucide-react';+import { useMemo } from 'react';+import { useReportChartContext } from '../context';+import {+ type ReportColumn,+ ReportDataTable,+ type ReportRowIdentity,+} from '@/components/report-table/report-data-table';++interface SankeyData {+ nodes: Array<{+ id: string;+ label: string;+ nodeColor: string;+ value?: number;+ step?: number;+ }>;+ links: Array<{ source: string; target: string; value: number }>;+}++interface PathRow {+ id: string;+ from: string;+ to: string;+ color: string;+ sessions: number;+ shareOfTotal: number;+ shareOfSource: number;+}++const IDENTITY: ReportRowIdentity<PathRow> = {+ header: 'Path',+ render: (row) => (+ <span className="flex items-center gap-1.5">+ <span className="truncate">{row.from}</span>+ <ArrowRightIcon className="size-3 shrink-0 text-muted-foreground" />+ <span className="truncate">{row.to}</span>+ </span>+ ),+ searchText: (row) => `${row.from} → ${row.to}`,+ color: (row) => row.color,+ width: 320,+};++const COLUMNS: ReportColumn<PathRow>[] = [+ {+ id: 'sessions',+ header: 'Sessions',+ value: (row) => row.sessions,+ decorate: 'bar',+ width: 150,+ },+ {+ id: 'shareOfTotal',+ header: '% of total',+ value: (row) => row.shareOfTotal,+ format: 'percent',+ },+ {+ id: 'shareOfSource',+ header: '% of source',+ value: (row) => row.shareOfSource,+ format: 'percent',+ },+];++/** Every link of the flow, ranked by sessions, with its share of all sessions and of its source node. */+export function PathsTable({ data }: { data: SankeyData }) {+ const {+ report: { name },+ } = useReportChartContext();++ const rows = useMemo(() => {+ const nodeById = new Map(data.nodes.map((node) => [node.id, node]));+ const firstStep = data.nodes.filter((node) => node.step === 1);+ const total = (firstStep.length > 0 ? firstStep : data.nodes).reduce(+ (sum, node) => sum + (node.value ?? 0),+ 0+ );+ return data.links+ .map((link): PathRow => {+ const source = nodeById.get(link.source);+ const target = nodeById.get(link.target);+ const sourceValue = source?.value ?? 0;+ return {+ id: `${link.source}→${link.target}`,+ from: source?.label ?? link.source,+ to: target?.label ?? link.target,+ color: source?.nodeColor ?? 'var(--chart-0)',+ sessions: link.value,+ shareOfTotal: total > 0 ? round((link.value / total) * 100, 1) : 0,+ shareOfSource:+ sourceValue > 0 ? round((link.value / sourceValue) * 100, 1) : 0,+ };+ })+ .sort((a, b) => b.sessions - a.sessions);+ }, [data]);++ return (+ <ReportDataTable+ columns={COLUMNS}+ csvFilename={name || 'paths'}+ getRowId={(row) => row.id}+ identity={IDENTITY}+ rows={rows}+ />+ );+}diff --git a/apps/start/src/components/report-table/columns.ts b/apps/start/src/components/report-table/columns.tsnew file mode 100644index 000000000..b30ea33d6--- /dev/null+++ b/apps/start/src/components/report-table/columns.ts@@ -0,0 +1,38 @@+import type { ReactNode } from 'react';++export type ReportCellFormat =+ | 'number'+ | 'percent'+ | 'currency'+ | 'minutes'+ | 'text';++/** How a numeric cell is shaded against the other values in its column. */+export type ReportCellDecoration = 'bar' | 'heat';++export interface ReportColumn<Row> {+ id: string;+ header: string;+ value: (row: Row) => number | string | null | undefined;+ /** Formats `value` for display and decides alignment. Default: `number`. */+ format?: ReportCellFormat;+ /** Replaces the cell's content; `formatted` is `value` run through the formatter. CSV still uses `value`. */+ render?: (row: Row, formatted: string) => ReactNode;+ width?: number;+ decorate?: ReportCellDecoration;+ /** Default: true. */+ sortable?: boolean;+}++/** The pinned first column: what a row is. */+export interface ReportRowIdentity<Row> {+ header: string;+ render: (row: Row) => ReactNode;+ /** Text the search box matches against. */+ searchText: (row: Row) => string;+ color?: (row: Row) => string;+ width?: number;+}++export const DEFAULT_COLUMN_WIDTH = 112;+export const DEFAULT_IDENTITY_WIDTH = 260;diff --git a/apps/start/src/components/report-table/csv.ts b/apps/start/src/components/report-table/csv.tsnew file mode 100644index 000000000..a035550da--- /dev/null+++ b/apps/start/src/components/report-table/csv.ts@@ -0,0 +1,36 @@+import type { ReportColumn, ReportRowIdentity } from './columns';++function escapeCell(cell: string) {+ return /[",\n]/.test(cell) ? `"${cell.replace(/"/g, '""')}"` : cell;+}++/** Raw values, not the formatted ones, so the file can be summed in a spreadsheet. */+export function buildCsv<Row>(+ rows: Row[],+ identity: ReportRowIdentity<Row>,+ columns: ReportColumn<Row>[]+) {+ // A column without a header holds row actions, not data.+ const dataColumns = columns.filter((column) => column.header !== '');+ const header = [+ identity.header,+ ...dataColumns.map((column) => column.header),+ ];+ const lines = rows.map((row) => [+ identity.searchText(row),+ ...dataColumns.map((column) => String(column.value(row) ?? '')),+ ]);+ return [header, ...lines]+ .map((line) => line.map(escapeCell).join(','))+ .join('\n');+}++export function downloadCsv(filename: string, csv: string) {+ const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement('a');+ anchor.href = url;+ anchor.download = filename.endsWith('.csv') ? filename : `${filename}.csv`;+ anchor.click();+ URL.revokeObjectURL(url);+}diff --git a/apps/start/src/components/report-table/format.ts b/apps/start/src/components/report-table/format.tsnew file mode 100644index 000000000..7a3a2ca8d--- /dev/null+++ b/apps/start/src/components/report-table/format.ts@@ -0,0 +1,40 @@+import { useCallback } from 'react';+import type { ReportCellFormat } from './columns';+import { fancyMinutes, useNumber } from '@/hooks/use-numer-formatter';++const EMPTY_CELL = '–';++/** One formatter for every table cell, so numbers read the same as in tooltips and metric cards. */+export function useCellFormatter() {+ const number = useNumber();+ return useCallback(+ (+ value: number | string | null | undefined,+ format: ReportCellFormat = 'number'+ ): string => {+ if (value === null || value === undefined || value === '') {+ return EMPTY_CELL;+ }+ if (typeof value === 'string') {+ return value;+ }+ switch (format) {+ case 'percent':+ return number.formatWithUnit(value / 100, '%');+ case 'currency':+ return number.currency(value / 100);+ case 'minutes':+ return fancyMinutes(value);+ case 'text':+ return String(value);+ default:+ return number.format(value);+ }+ },+ [number]+ );+}++export function isNumericFormat(format: ReportCellFormat | undefined) {+ return format !== 'text';+}diff --git a/apps/start/src/components/report-table/report-data-table.tsx b/apps/start/src/components/report-table/report-data-table.tsxnew file mode 100644index 000000000..25bc9e6ad--- /dev/null+++ b/apps/start/src/components/report-table/report-data-table.tsx@@ -0,0 +1,474 @@+import {+ type ColumnDef,+ getCoreRowModel,+ getSortedRowModel,+ type SortingState,+ type Row as TableRow,+ useReactTable,+} from '@tanstack/react-table';+import { useVirtualizer } from '@tanstack/react-virtual';+import {+ ChevronDownIcon,+ ChevronUpIcon,+ DownloadIcon,+ RotateCcwIcon,+ SearchIcon,+ XIcon,+} from 'lucide-react';+import { useMemo, useRef, useState } from 'react';+import {+ DEFAULT_COLUMN_WIDTH,+ DEFAULT_IDENTITY_WIDTH,+ type ReportColumn,+ type ReportRowIdentity,+} from './columns';+import { buildCsv, downloadCsv } from './csv';+import { isNumericFormat, useCellFormatter } from './format';+import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';+import { Input } from '@/components/ui/input';+import { cn } from '@/utils/cn';++export const ROW_HEIGHT = 40;+const HEADER_HEIGHT = 32;+const MAX_TABLE_HEIGHT = 600;+// Below this many rows the DOM is small enough to render whole.+const VIRTUALIZE_FROM = 40;+const VIRTUAL_OVERSCAN = 8;+const HEAT_MIN_OPACITY = 0.06;+// Strong enough to read as a scale, light enough that the number on top stays legible.+const HEAT_MAX_OPACITY = 0.4;++interface ReportDataTableProps<Row> {+ rows: Row[];+ columns: ReportColumn<Row>[];+ identity: ReportRowIdentity<Row>;+ getRowId: (row: Row) => string;+ /** Rows the chart currently draws; with `onToggleRow` each row gets a checkbox. */+ selectedIds?: ReadonlySet<string>;+ onToggleRow?: (id: string) => void;+ onUnselectAll?: () => void;+ /** Puts the chart's default selection back. */+ onReset?: () => void;+ /** Enables the "Download CSV" button, named after this. */+ csvFilename?: string;+ searchable?: boolean;+ /** Clicking a row reports its id; `activeId` highlights the chosen one. */+ onRowClick?: (id: string) => void;+ activeId?: string;+ className?: string;+}++interface ColumnRange {+ min: number;+ max: number;+}++export function ReportDataTable<Row>({+ rows,+ columns,+ identity,+ getRowId,+ selectedIds,+ onToggleRow,+ onUnselectAll,+ onReset,+ csvFilename,+ searchable = true,+ onRowClick,+ activeId,+ className,+}: ReportDataTableProps<Row>) {+ const formatCell = useCellFormatter();+ const [sorting, setSorting] = useState<SortingState>([]);+ const [search, setSearch] = useState('');+ const scrollRef = useRef<HTMLDivElement>(null);++ const ranges = useMemo(() => columnRanges(rows, columns), [rows, columns]);+ const searchedRows = useMemo(() => {+ const needle = search.trim().toLowerCase();+ if (!needle) {+ return rows;+ }+ return rows.filter((row) =>+ identity.searchText(row).toLowerCase().includes(needle)+ );+ }, [rows, search, identity]);++ const columnDefs = useMemo<ColumnDef<Row>[]>(+ () => [+ {+ id: 'identity',+ accessorFn: (row) => identity.searchText(row),+ enableSorting: true,+ sortingFn: 'alphanumeric',+ },+ ...columns.map(+ (column): ColumnDef<Row> => ({+ id: column.id,+ accessorFn: (row) => column.value(row) ?? null,+ enableSorting: column.sortable !== false,+ sortUndefined: 'last',+ sortingFn: isNumericFormat(column.format) ? 'basic' : 'alphanumeric',+ })+ ),+ ],+ [columns, identity]+ );++ const table = useReactTable({+ data: searchedRows,+ columns: columnDefs,+ state: { sorting },+ // `src/types/data-table.ts` makes this filter mandatory on every table; rows are searched before they get here.+ filterFns: { isWithinRange: () => true },+ onSortingChange: setSorting,+ getRowId: (row) => getRowId(row),+ getCoreRowModel: getCoreRowModel(),+ getSortedRowModel: getSortedRowModel(),+ });+ const tableRows = table.getRowModel().rows;++ const virtualizer = useVirtualizer({+ count: tableRows.length,+ getScrollElement: () => scrollRef.current,+ estimateSize: () => ROW_HEIGHT,+ overscan: VIRTUAL_OVERSCAN,+ enabled: tableRows.length > VIRTUALIZE_FROM,+ });+ const isVirtual = tableRows.length > VIRTUALIZE_FROM;+ const virtualRows = isVirtual ? virtualizer.getVirtualItems() : null;++ const identityWidth = identity.width ?? DEFAULT_IDENTITY_WIDTH;+ // The name column takes whatever width the value columns leave, so a short+ // table still fills its card; it only shrinks to its base width when the+ // columns need the horizontal scroll.+ const identityStyle = { flex: `1 0 ${identityWidth}px` };+ const totalWidth =+ identityWidth ++ columns.reduce(+ (sum, column) => sum + (column.width ?? DEFAULT_COLUMN_WIDTH),+ 0+ );++ const renderRow = (row: TableRow<Row>, style?: React.CSSProperties) => {+ const id = row.id;+ const isSelected = selectedIds?.has(id) ?? true;+ const color = identity.color?.(row.original);+ const RowTag = onRowClick ? 'button' : 'div';+ return (+ <RowTag+ className={cn(+ 'group/row flex w-full min-w-full border-border border-b text-left transition-colors hover:bg-def-100',+ !isSelected && 'opacity-50',+ activeId === id && 'bg-def-100'+ )}+ data-report-table-row={id}+ key={id}+ onClick={onRowClick ? () => onRowClick(id) : undefined}+ style={{ height: ROW_HEIGHT, minWidth: totalWidth, ...style }}+ type={onRowClick ? 'button' : undefined}+ >+ <div+ className={cn(+ 'sticky left-0 z-10 flex items-center gap-2 bg-card px-3 group-hover/row:bg-def-100',+ activeId === id && 'bg-def-100'+ )}+ style={identityStyle}+ >+ {onToggleRow && (+ <Checkbox+ aria-label={`Show ${identity.searchText(row.original)}`}+ checked={isSelected}+ onCheckedChange={() => onToggleRow(id)}+ onClick={(event) => event.stopPropagation()}+ />+ )}+ {color && (+ <span+ className="h-5 w-[3px] shrink-0 rounded-full"+ style={{ background: color }}+ />+ )}+ <div className="min-w-0 flex-1 truncate">+ {identity.render(row.original)}+ </div>+ </div>+ {columns.map((column) => (+ <Cell+ column={column}+ formatted={formatCell(column.value(row.original), column.format)}+ key={column.id}+ range={ranges.get(rangeKey(column))}+ row={row.original}+ />+ ))}+ </RowTag>+ );+ };++ return (+ <div className={cn('col', className)} data-report-table>+ <Toolbar+ onDownload={+ csvFilename+ ? () =>+ downloadCsv(+ csvFilename,+ buildCsv(+ tableRows.map((row) => row.original),+ identity,+ columns+ )+ )+ : undefined+ }+ onReset={onReset}+ onSearch={searchable ? setSearch : undefined}+ onUnselectAll={onUnselectAll}+ search={search}+ />+ <div+ className="scrollbar-thin relative overflow-auto"+ ref={scrollRef}+ style={{ maxHeight: MAX_TABLE_HEIGHT }}+ >+ <div+ className="sticky top-0 z-20 flex min-w-full border-border border-b bg-card"+ style={{ height: HEADER_HEIGHT, minWidth: totalWidth }}+ >+ {table.getFlatHeaders().map((header) => {+ const column = columns.find((item) => item.id === header.id);+ const isIdentity = header.id === 'identity';+ const sorted = header.column.getIsSorted();+ const numeric = !isIdentity && isNumericFormat(column?.format);+ return (+ <button+ className={cn(+ 'flex shrink-0 items-center gap-1 px-3 font-medium text-muted-foreground text-sm hover:text-foreground',+ numeric ? 'justify-end' : 'justify-start',+ isIdentity && 'sticky left-0 z-10 bg-card'+ )}+ disabled={!header.column.getCanSort()}+ key={header.id}+ onClick={header.column.getToggleSortingHandler()}+ style={+ isIdentity+ ? identityStyle+ : { width: column?.width ?? DEFAULT_COLUMN_WIDTH }+ }+ type="button"+ >+ <span className="truncate">+ {isIdentity ? identity.header : column?.header}+ </span>+ <SortChevron direction={sorted || null} />+ </button>+ );+ })}+ </div>+ {tableRows.length === 0 && (+ <div className="flex h-20 items-center justify-center text-muted-foreground text-sm">+ No rows match+ </div>+ )}+ {virtualRows ? (+ <div+ className="relative"+ style={{ height: virtualizer.getTotalSize() }}+ >+ {virtualRows.map((virtualRow) =>+ renderRow(tableRows[virtualRow.index]!, {+ position: 'absolute',+ top: 0,+ left: 0,+ right: 0,+ transform: `translateY(${virtualRow.start}px)`,+ })+ )}+ </div>+ ) : (+ tableRows.map((row) => renderRow(row))+ )}+ </div>+ </div>+ );+}++function Cell<Row>({+ column,+ row,+ formatted,+ range,+}: {+ column: ReportColumn<Row>;+ row: Row;+ formatted: string;+ range: ColumnRange | undefined;+}) {+ const numeric = isNumericFormat(column.format);+ const raw = column.value(row);+ const share =+ column.decorate && range && typeof raw === 'number'+ ? decorationShare(raw, range, column.decorate)+ : null;+ return (+ <div+ className={cn(+ 'relative flex shrink-0 items-center px-3',+ numeric && 'justify-end font-mono tabular-nums'+ )}+ style={{ width: column.width ?? DEFAULT_COLUMN_WIDTH }}+ >+ {share !== null && column.decorate === 'bar' && (+ <span+ aria-hidden+ className="absolute inset-y-2 left-0 rounded-r bg-def-200 group-hover/row:bg-blue-200 dark:group-hover/row:bg-blue-900"+ style={{ width: `${share * 100}%` }}+ />+ )}+ {share !== null && column.decorate === 'heat' && (+ <span+ aria-hidden+ className="absolute inset-0 bg-chart-0"+ style={{+ opacity:+ HEAT_MIN_OPACITY + share * (HEAT_MAX_OPACITY - HEAT_MIN_OPACITY),+ }}+ />+ )}+ <span className="relative truncate">+ {column.render ? column.render(row, formatted) : formatted}+ </span>+ </div>+ );+}++function Toolbar({+ search,+ onSearch,+ onUnselectAll,+ onReset,+ onDownload,+}: {+ search: string;+ onSearch?: (value: string) => void;+ onUnselectAll?: () => void;+ onReset?: () => void;+ onDownload?: () => void;+}) {+ if (!(onSearch || onUnselectAll || onReset || onDownload)) {+ return null;+ }+ return (+ <div className="flex items-center gap-2 border-border border-b p-2">+ {onSearch && (+ <div className="relative flex-1 md:max-w-xs">+ <SearchIcon className="absolute top-1/2 left-2 size-4 -translate-y-1/2 text-muted-foreground" />+ <Input+ className="pl-8"+ onChange={(event) => onSearch(event.target.value)}+ placeholder="Search…"+ size="sm"+ value={search}+ />+ </div>+ )}+ <div className="ml-auto flex items-center gap-2">+ {onReset && (+ <Button+ icon={RotateCcwIcon}+ onClick={onReset}+ size="sm"+ variant="outline"+ >+ Reset+ </Button>+ )}+ {onUnselectAll && (+ <Button+ icon={XIcon}+ onClick={onUnselectAll}+ size="sm"+ variant="outline"+ >+ Unselect all+ </Button>+ )}+ {onDownload && (+ <Button+ icon={DownloadIcon}+ onClick={onDownload}+ size="sm"+ variant="outline"+ >+ CSV+ </Button>+ )}+ </div>+ </div>+ );+}++function SortChevron({ direction }: { direction: 'asc' | 'desc' | null }) {+ if (direction === 'desc') {+ return <ChevronDownIcon className="size-3 shrink-0" />;+ }+ if (direction === 'asc') {+ return <ChevronUpIcon className="size-3 shrink-0" />;+ }+ return <ChevronDownIcon className="size-3 shrink-0 opacity-0" />;+}++const HEAT_RANGE_KEY = 'heat';++/** Bars are relative to their own column; heat is one scale across every heat column, so cells compare across the matrix. */+function rangeKey<Row>(column: ReportColumn<Row>) {+ return column.decorate === 'heat' ? HEAT_RANGE_KEY : column.id;+}++function columnRanges<Row>(rows: Row[], columns: ReportColumn<Row>[]) {+ const ranges = new Map<string, ColumnRange>();+ for (const column of columns) {+ if (!column.decorate) {+ continue;+ }+ const key = rangeKey(column);+ const range = ranges.get(key) ?? {+ min: Number.POSITIVE_INFINITY,+ max: Number.NEGATIVE_INFINITY,+ };+ for (const row of rows) {+ const value = column.value(row);+ if (typeof value === 'number') {+ range.min = Math.min(range.min, value);+ range.max = Math.max(range.max, value);+ }+ }+ ranges.set(key, range);+ }+ for (const [key, range] of ranges) {+ if (!(range.max > range.min || range.max > 0)) {+ ranges.delete(key);+ }+ }+ return ranges;+}++/** A bar shows the share of the column's largest value; heat shows where the value sits between min and max. */+function decorationShare(+ value: number,+ range: ColumnRange,+ decoration: 'bar' | 'heat'+) {+ if (decoration === 'bar') {+ return range.max > 0 ? Math.max(0, value / range.max) : 0;+ }+ if (value <= 0) {+ return null;+ }+ const span = range.max - range.min;+ return span > 0 ? (value - range.min) / span : 1;+}++export type { ReportColumn, ReportRowIdentity } from './columns';diff --git a/apps/start/src/components/report/report-item.tsx b/apps/start/src/components/report/report-item.tsxindex eb904cf99..29de23ea4 100644--- a/apps/start/src/components/report/report-item.tsx+++ b/apps/start/src/components/report/report-item.tsx@@ -183,11 +183,12 @@ export function ReportItem({</div><divclassName={cn(- 'flex-1 overflow-auto p-4',+ 'min-h-0 flex-1 overflow-hidden p-4',report.chartType === 'metric' && 'p-0')}><ReportChart+ layout="fill"report={{...report,range: range ?? report.range,@@ -251,11 +252,12 @@ export function ReportItemReadOnly({</div><divclassName={cn(- 'flex-1 overflow-auto p-4',+ 'min-h-0 flex-1 overflow-hidden p-4',report.chartType === 'metric' && 'p-0')}><ReportChart+ layout="fill"report={{...report,range: range ?? report.range,diff --git a/apps/start/src/components/shimmering-text.tsx b/apps/start/src/components/shimmering-text.tsxnew file mode 100644index 000000000..03bd275b8--- /dev/null+++ b/apps/start/src/components/shimmering-text.tsx@@ -0,0 +1,90 @@+'use client';++import { motion, useReducedMotion, type Variants } from 'motion/react';+import { type ComponentProps, useCallback } from 'react';+import { cn } from '@/lib/utils';++export type ShimmeringTextProps = Omit<+ ComponentProps<typeof motion.span>,+ 'children'+> & {+ /** The text to render with the shimmering effect. */+ text: string;+ /**+ * Duration in seconds for one shimmer cycle.+ * @defaultValue 1+ */+ duration?: number;+ /**+ * Pause the shimmer (e.g. when the hero leaves the viewport).+ * @defaultValue false+ */+ paused?: boolean;+ /**+ * Legacy alias for `paused`.+ * @defaultValue false+ */+ isStopped?: boolean;+};++export function ShimmeringText({+ text,+ duration = 1,+ isStopped = false,+ paused = false,+ className,+ ...props+}: ShimmeringTextProps) {+ const reducedMotion = useReducedMotion();+ const stopped = isStopped || paused || reducedMotion === true;++ const createCharVariants = useCallback(+ (charIndex: number): Variants => ({+ running: {+ color: ['var(--color)', 'var(--shimmering-color)', 'var(--color)'],+ transition: {+ duration,+ repeat: Number.POSITIVE_INFINITY,+ repeatType: 'loop',+ repeatDelay: text.length * 0.05,+ delay: (charIndex * duration) / text.length,+ ease: 'easeInOut',+ },+ },+ stopped: {+ color: 'var(--color)',+ transition: {+ duration: duration * 0.5,+ ease: 'easeOut',+ },+ },+ }),+ [duration, text.length]+ );++ return (+ <motion.span+ className={cn(+ 'inline-flex select-none items-center leading-none',+ '[--color:var(--muted-foreground)] [--shimmering-color:var(--foreground)]',+ className+ )}+ {...props}+ >+ {text.split('').map((char, index) => (+ <motion.span+ animate={stopped ? 'stopped' : 'running'}+ aria-hidden+ className="inline-block whitespace-pre leading-none"+ initial="stopped"+ // biome-ignore lint/suspicious/noArrayIndexKey: static label text, order never changes+ key={index}+ variants={createCharVariants(index)}+ >+ {char}+ </motion.span>+ ))}+ <span className="sr-only">{text}</span>+ </motion.span>+ );+}diff --git a/apps/start/src/hooks/use-dashed-stroke.tsx b/apps/start/src/hooks/use-dashed-stroke.tsxdeleted file mode 100644index f2ce1aa8a..000000000--- a/apps/start/src/hooks/use-dashed-stroke.tsx+++ /dev/null@@ -1,202 +0,0 @@-import { useCallback, useRef, useState } from 'react';-export type GraphicalItemPoint = {- /**- * x point coordinate.- */- x?: number;- /**- * y point coordinate.- */- y?: number;-};--export type GraphicalItemProps = {- /**- * graphical item points.- */- points?: GraphicalItemPoint[];-};--export type ItemProps = {- /**- * item data key.- */- dataKey?: string;-};--export type ItemType = {- /**- * recharts item display name.- */- displayName?: string;-};--export type Item = {- /**- * item props.- */- props?: ItemProps;- /**- * recharts item class.- */- type?: ItemType;-};--export type GraphicalItem = {- /**- * from recharts internal state and props of chart.- */- props?: GraphicalItemProps;- /**- * from recharts internal state and props of chart.- */- item?: Item;-};--export type RechartsChartProps = {- /**- * from recharts internal state and props of chart.- */- formattedGraphicalItems?: GraphicalItem[];-};--export type CalculateStrokeDasharray = (props?: any) => any;--export type LineStrokeDasharray = {- /**- * line name.- */- name?: string;- /**- * line strokeDasharray.- */- strokeDasharray?: string;-};--export type LinesStrokeDasharray = LineStrokeDasharray[];--export type LineProps = {- /**- * line name.- */- name?: string;- /**- * specifies the starting index of the first dot in the dash pattern.- */- dotIndex?: number;- /**- * defines the pattern of dashes and gaps. an array of [gap length, dash length].- */- strokeDasharray?: [number, number];- /**- * adjusts the percentage correction of the first line segment for better alignment in curved lines.- */- curveCorrection?: number;-};--export type UseStrokeDasharrayProps = {- /**- * an array of properties to target specific line(s) and override default settings.- */- linesProps?: LineProps[];-} & LineProps;--export function useStrokeDasharray({- linesProps = [],- dotIndex = -2,- strokeDasharray: restStroke = [5, 3],- curveCorrection = 1,-}: UseStrokeDasharrayProps): [CalculateStrokeDasharray, LinesStrokeDasharray] {- const linesStrokeDasharray = useRef<LinesStrokeDasharray>([]);-- const calculateStrokeDasharray = useCallback(- (props: RechartsChartProps): null => {- const items = props?.formattedGraphicalItems;-- const getLineWidth = (points: GraphicalItemPoint[]) => {- const width = points?.reduce((acc, point, index) => {- if (!index) {- return acc;- }-- const prevPoint = points?.[index - 1];-- const xAxis = point?.x || 0;- const prevXAxis = prevPoint?.x || 0;- const xWidth = xAxis - prevXAxis;-- const yAxis = point?.y || 0;- const prevYAxis = prevPoint?.y || 0;- const yWidth = Math.abs(yAxis - prevYAxis);-- const hypotenuse = Math.sqrt(xWidth * xWidth + yWidth * yWidth);- acc += hypotenuse;- return acc;- }, 0);-- return width || 0;- };-- items?.forEach((line) => {- const linePoints = line?.props?.points;- const lineWidth = getLineWidth(linePoints || []);-- const name = line?.item?.props?.dataKey;- const targetLine = linesProps?.find((target) => target?.name === name);- const targetIndex = targetLine?.dotIndex ?? dotIndex;- const dashedPoints = linePoints?.slice(targetIndex);- const dashedWidth = getLineWidth(dashedPoints || []);-- if (!(lineWidth && dashedWidth)) {- return;- }-- const firstWidth = lineWidth - dashedWidth;- const targetCurve = targetLine?.curveCorrection ?? curveCorrection;- const correctionWidth = (firstWidth * targetCurve) / 100;- const firstDasharray = firstWidth + correctionWidth;-- const targetRestStroke = targetLine?.strokeDasharray || restStroke;- const gapDashWidth = targetRestStroke?.[0] + targetRestStroke?.[1] || 1;- const restDasharrayLength = dashedWidth / gapDashWidth;- const restDasharray = new Array(Math.ceil(restDasharrayLength)).fill(- targetRestStroke.join(' ')- );-- const strokeDasharray = `${firstDasharray} ${restDasharray.join(' ')}`;- const lineStrokeDasharray = { name, strokeDasharray };-- const dasharrayIndex = linesStrokeDasharray.current.findIndex((d) => {- return d.name === line?.item?.props?.dataKey;- });-- if (dasharrayIndex === -1) {- linesStrokeDasharray.current.push(lineStrokeDasharray);- return;- }-- linesStrokeDasharray.current[dasharrayIndex] = lineStrokeDasharray;- });-- return null;- },- [dotIndex]- );-- return [calculateStrokeDasharray, linesStrokeDasharray.current];-}--export function useDashedStroke(options: UseStrokeDasharrayProps = {}) {- const [calcStrokeDasharray, strokes] = useStrokeDasharray(options);- const [strokeDasharray, setStrokeDasharray] = useState([...strokes]);- const handleAnimationEnd = () => setStrokeDasharray([...strokes]);- const getStrokeDasharray = (name: string) => {- return strokeDasharray.find((s) => s?.name === name)?.strokeDasharray;- };-- return {- calcStrokeDasharray,- getStrokeDasharray,- handleAnimationEnd,- };-}diff --git a/apps/start/src/hooks/use-element-size.ts b/apps/start/src/hooks/use-element-size.tsnew file mode 100644index 000000000..55ae301b2--- /dev/null+++ b/apps/start/src/hooks/use-element-size.ts@@ -0,0 +1,32 @@+import { useCallback, useState } from 'react';++export interface ElementSize {+ width: number;+ height: number;+}++/** The element's content-box size, kept current by a ResizeObserver. */+export function useElementSize<T extends HTMLElement = HTMLDivElement>() {+ const [size, setSize] = useState<ElementSize>({ width: 0, height: 0 });++ const ref = useCallback((element: T | null) => {+ if (!element) {+ return;+ }+ const observer = new ResizeObserver(([entry]) => {+ if (!entry) {+ return;+ }+ const { width, height } = entry.contentRect;+ setSize((previous) =>+ previous.width === width && previous.height === height+ ? previous+ : { width, height }+ );+ });+ observer.observe(element);+ return () => observer.disconnect();+ }, []);++ return [ref, size] as const;+}diff --git a/apps/start/src/hooks/use-visible-conversion-series.ts b/apps/start/src/hooks/use-visible-conversion-series.tsindex dfa6126ff..75c909802 100644--- a/apps/start/src/hooks/use-visible-conversion-series.ts+++ b/apps/start/src/hooks/use-visible-conversion-series.ts@@ -38,11 +38,14 @@ export function useVisibleConversionSeries(const [visibleSeries, setVisibleSeries] = useState<string[]>(() =>resolveIds(data?.current ?? []));+ // What the chart first showed for this set of series; "Reset" goes back to it.+ const defaultIdsRef = useRef(visibleSeries);const prevKeyRef = useRef(seriesKey);if (prevKeyRef.current !== seriesKey) {prevKeyRef.current = seriesKey;- setVisibleSeries(resolveIds(data?.current ?? []));+ defaultIdsRef.current = resolveIds(data?.current ?? []);+ setVisibleSeries(defaultIdsRef.current);}const handleSet = useCallback<React.Dispatch<React.SetStateAction<string[]>>>(@@ -56,13 +59,23 @@ export function useVisibleConversionSeries([]);+ const defaultIds = defaultIdsRef.current;+ const isDefaultSelection =+ defaultIds.length === visibleSeries.length &&+ defaultIds.every((id) => visibleSeries.includes(id));+ const resetRef = useRef<() => void>(() => undefined);+ resetRef.current = () => handleSet(defaultIds);+ const reset = useCallback(() => resetRef.current(), []);+return useMemo(() => ({+ isDefaultSelection,+ reset,series: data.current.map((serie, index) => ({ ...serie, index })).filter((serie) => visibleSeries.includes(serie.id)),setVisibleSeries: handleSet,}),- [visibleSeries, data.current, handleSet]+ [visibleSeries, data.current, handleSet, isDefaultSelection, reset]);}diff --git a/apps/start/src/hooks/use-visible-funnel-breakdowns.ts b/apps/start/src/hooks/use-visible-funnel-breakdowns.tsindex 65f2e81e2..b3a6144c3 100644--- a/apps/start/src/hooks/use-visible-funnel-breakdowns.ts+++ b/apps/start/src/hooks/use-visible-funnel-breakdowns.ts@@ -38,11 +38,14 @@ export function useVisibleFunnelBreakdowns(const [visibleSeries, setVisibleSeries] = useState<string[]>(() =>resolveIds(data ?? []));+ // What the chart first showed for this set of series; "Reset" goes back to it.+ const defaultIdsRef = useRef(visibleSeries);const prevKeyRef = useRef(seriesKey);if (prevKeyRef.current !== seriesKey) {prevKeyRef.current = seriesKey;- setVisibleSeries(resolveIds(data ?? []));+ defaultIdsRef.current = resolveIds(data ?? []);+ setVisibleSeries(defaultIdsRef.current);}const handleSet = useCallback<React.Dispatch<React.SetStateAction<string[]>>>(@@ -56,13 +59,23 @@ export function useVisibleFunnelBreakdowns([]);+ const defaultIds = defaultIdsRef.current;+ const isDefaultSelection =+ defaultIds.length === visibleSeries.length &&+ defaultIds.every((id) => visibleSeries.includes(id));+ const resetRef = useRef<() => void>(() => undefined);+ resetRef.current = () => handleSet(defaultIds);+ const reset = useCallback(() => resetRef.current(), []);+return useMemo(() => ({+ isDefaultSelection,+ reset,breakdowns: data.map((item, index) => ({ ...item, index })).filter((item) => visibleSeries.includes(item.id)),setVisibleSeries: handleSet,}),- [visibleSeries, data, handleSet]+ [visibleSeries, data, handleSet, isDefaultSelection, reset]);}diff --git a/apps/start/src/hooks/use-visible-series.ts b/apps/start/src/hooks/use-visible-series.tsindex d6cf24b1c..29fbde174 100644--- a/apps/start/src/hooks/use-visible-series.ts+++ b/apps/start/src/hooks/use-visible-series.ts@@ -36,6 +36,8 @@ export function useVisibleSeries(const [visibleSeries, setVisibleSeries] = useState<string[]>(() =>resolveIds(data?.series ?? []));+ // What the chart first showed for this set of series; "Reset" goes back to it.+ const defaultIdsRef = useRef(visibleSeries);// Reset only when the actual series IDs change (breakdowns/events changed),// not when the data object reference changes. This is React's recommended@@ -43,7 +45,8 @@ export function useVisibleSeries(const prevKeyRef = useRef(seriesKey);if (prevKeyRef.current !== seriesKey) {prevKeyRef.current = seriesKey;- setVisibleSeries(resolveIds(data?.series ?? []));+ defaultIdsRef.current = resolveIds(data?.series ?? []);+ setVisibleSeries(defaultIdsRef.current);}// Stable setter that notifies parent without recreating on every render@@ -58,13 +61,23 @@ export function useVisibleSeries([]);+ const defaultIds = defaultIdsRef.current;+ const isDefaultSelection =+ defaultIds.length === visibleSeries.length &&+ defaultIds.every((id) => visibleSeries.includes(id));+ const resetRef = useRef<() => void>(() => undefined);+ resetRef.current = () => handleSet(defaultIds);+ const reset = useCallback(() => resetRef.current(), []);+return useMemo(() => ({+ isDefaultSelection,+ reset,series: data.series.map((serie, index) => ({ ...serie, index })).filter((serie) => visibleSeries.includes(serie.id)),setVisibleSeries: handleSet,}),- [visibleSeries, data.series, handleSet]+ [visibleSeries, data.series, handleSet, isDefaultSelection, reset]);}diff --git a/apps/start/src/modals/event-details.tsx b/apps/start/src/modals/event-details.tsxindex 255848612..1ab6d3f87 100644--- a/apps/start/src/modals/event-details.tsx+++ b/apps/start/src/modals/event-details.tsx@@ -340,6 +340,7 @@ function EventDetailsContent({ id, createdAt, projectId }: Props) {<div className="card p-4"><ReportChartShortcutchartType="linear"+ options={{ hideTable: true }}projectId={event.projectId}series={[{diff --git a/apps/start/src/modals/gsc-details.tsx b/apps/start/src/modals/gsc-details.tsxindex 848f8a56f..17d47ce7d 100644--- a/apps/start/src/modals/gsc-details.tsx+++ b/apps/start/src/modals/gsc-details.tsx@@ -4,90 +4,21 @@ import type {} from '@openpanel/core/modules/report/report.constants';import { useQuery } from '@tanstack/react-query';import {- CartesianGrid,- ComposedChart,- Line,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';-import {- ChartTooltipHeader,- ChartTooltipItem,- createChartTooltip,-} from '@/components/charts/chart-tooltip';+ OPLineChart,+ type OPLineChartSeries,+} from '@/components/charts/op-line-chart';import { OverviewWidgetTable } from '@/components/overview/overview-widget-table';-import {- useYAxisProps,- X_AXIS_STYLE_PROPS,-} from '@/components/report-chart/common/axis';+import { GSC_CLICKS_SERIES } from '@/components/page/gsc-clicks-chart';import { Skeleton } from '@/components/skeleton';import { SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';import { useTRPC } from '@/integrations/trpc/react';import { getChartColor } from '@/utils/theme';-interface GscChartData {- date: string;- clicks: number;- impressions: number;-}-interface GscViewsChartData {- date: string;- views: number;-}+const CHART_HEIGHT = 160;-const { TooltipProvider, Tooltip: GscTooltip } = createChartTooltip<- GscChartData | GscViewsChartData,- Record<string, unknown>->(({ data }) => {- const item = data[0];- if (!item) {- return null;- }- if (!('date' in item)) {- return null;- }- if ('views' in item && item.views != null) {- return (- <>- <ChartTooltipHeader>- <div>{item.date}</div>- </ChartTooltipHeader>- <ChartTooltipItem color={getChartColor(0)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Views</span>- <span>{item.views.toLocaleString()}</span>- </div>- </ChartTooltipItem>- </>- );- }- const clicks = 'clicks' in item ? item.clicks : undefined;- const impressions = 'impressions' in item ? item.impressions : undefined;- return (- <>- <ChartTooltipHeader>- <div>{item.date}</div>- </ChartTooltipHeader>- {clicks != null && (- <ChartTooltipItem color={getChartColor(0)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Clicks</span>- <span>{clicks.toLocaleString()}</span>- </div>- </ChartTooltipItem>- )}- {impressions != null && (- <ChartTooltipItem color={getChartColor(1)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Impressions</span>- <span>{impressions.toLocaleString()}</span>- </div>- </ChartTooltipItem>- )}- </>- );-});+const VIEWS_SERIES: OPLineChartSeries[] = [+ { dataKey: 'views', label: 'Views', color: getChartColor(0) },+];type Props =| {@@ -185,11 +116,14 @@ export default function GscDetails(props: Props) {{isLoading || pageTimeseriesQuery.isLoading ? (<Skeleton className="h-40 w-full" />) : (- <GscViewsChart- data={pageTimeseries.map((r) => ({- date: r.date,- views: r.pageviews,+ <OPLineChart+ data={pageTimeseries.map((row) => ({+ date: row.date,+ views: row.pageviews,}))}+ height={CHART_HEIGHT}+ interval={interval}+ series={VIEWS_SERIES}/>)}</div>@@ -200,7 +134,16 @@ export default function GscDetails(props: Props) {{isLoading ? (<Skeleton className="h-40 w-full" />) : (- <GscTimeseriesChart data={timeseries} />+ <OPLineChart+ data={timeseries.map((row) => ({+ date: row.date,+ clicks: row.clicks,+ impressions: row.impressions,+ }))}+ height={CHART_HEIGHT}+ interval={interval}+ series={GSC_CLICKS_SERIES}+ />)}</div>@@ -310,135 +253,3 @@ export default function GscDetails(props: Props) {</SheetContent>);}--function GscViewsChart({- data,-}: {- data: Array<{ date: string; views: number }>;-}) {- const yAxisProps = useYAxisProps();-- return (- <TooltipProvider>- <ResponsiveContainer height={160} width="100%">- <ComposedChart data={data}>- <defs>- <filter- height="140%"- id="gsc-detail-glow"- width="140%"- x="-20%"- y="-20%"- >- <feGaussianBlur result="blur" stdDeviation="5" />- <feComponentTransfer in="blur" result="dimmedBlur">- <feFuncA slope="0.5" type="linear" />- </feComponentTransfer>- <feComposite- in="SourceGraphic"- in2="dimmedBlur"- operator="over"- />- </filter>- </defs>- <CartesianGrid- className="stroke-border"- horizontal- strokeDasharray="3 3"- vertical={false}- />- <XAxis- {...X_AXIS_STYLE_PROPS}- dataKey="date"- tickFormatter={(v: string) => v.slice(5)}- type="category"- />- <YAxis {...yAxisProps} yAxisId="left" />- <YAxis {...yAxisProps} orientation="right" yAxisId="right" />- <GscTooltip />- <Line- dataKey="views"- dot={false}- filter="url(#gsc-detail-glow)"- isAnimationActive={false}- stroke={getChartColor(0)}- strokeWidth={2}- type="monotone"- yAxisId="left"- />- </ComposedChart>- </ResponsiveContainer>- </TooltipProvider>- );-}--function GscTimeseriesChart({- data,-}: {- data: Array<{ date: string; clicks: number; impressions: number }>;-}) {- const yAxisProps = useYAxisProps();-- return (- <TooltipProvider>- <ResponsiveContainer height={160} width="100%">- <ComposedChart data={data}>- <defs>- <filter- height="140%"- id="gsc-detail-glow"- width="140%"- x="-20%"- y="-20%"- >- <feGaussianBlur result="blur" stdDeviation="5" />- <feComponentTransfer in="blur" result="dimmedBlur">- <feFuncA slope="0.5" type="linear" />- </feComponentTransfer>- <feComposite- in="SourceGraphic"- in2="dimmedBlur"- operator="over"- />- </filter>- </defs>- <CartesianGrid- className="stroke-border"- horizontal- strokeDasharray="3 3"- vertical={false}- />- <XAxis- {...X_AXIS_STYLE_PROPS}- dataKey="date"- tickFormatter={(v: string) => v.slice(5)}- type="category"- />- <YAxis {...yAxisProps} yAxisId="left" />- <YAxis {...yAxisProps} orientation="right" yAxisId="right" />- <GscTooltip />- <Line- dataKey="clicks"- dot={false}- filter="url(#gsc-detail-glow)"- isAnimationActive={false}- stroke={getChartColor(0)}- strokeWidth={2}- type="monotone"- yAxisId="left"- />- <Line- dataKey="impressions"- dot={false}- filter="url(#gsc-detail-glow)"- isAnimationActive={false}- stroke={getChartColor(1)}- strokeWidth={2}- type="monotone"- yAxisId="right"- />- </ComposedChart>- </ResponsiveContainer>- </TooltipProvider>- );-}diff --git a/apps/start/src/routes/__root.tsx b/apps/start/src/routes/__root.tsxindex d02ab5079..48f9bb672 100644--- a/apps/start/src/routes/__root.tsx+++ b/apps/start/src/routes/__root.tsx@@ -8,8 +8,6 @@ import { useEffect } from 'react';import 'flag-icons/css/flag-icons.min.css';import 'katex/dist/katex.min.css';-import 'react-grid-layout/css/styles.css';-import 'react-resizable/css/styles.css';import type { AppRouter } from '@openpanel/core';import type { QueryClient } from '@tanstack/react-query';import { TRPCClientError } from '@trpc/client';diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.dashboards.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.dashboards.tsxindex 7a158a3ca..fcbfd82f1 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.dashboards.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.dashboards.tsx@@ -1,25 +1,10 @@import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { createFileRoute, Link } from '@tanstack/react-router';import { format } from 'date-fns';-import {- AreaChartIcon,- BarChart3Icon,- BarChartHorizontalIcon,- ChartScatterIcon,- ConeIcon,- GitBranchIcon,- Globe2Icon,- HashIcon,- LayoutPanelTopIcon,- LineChartIcon,- Pencil,- PieChartIcon,- PlusIcon,- Trash,- TrendingUpIcon,-} from 'lucide-react';+import { LayoutPanelTopIcon, Pencil, PlusIcon, Trash } from 'lucide-react';import { toast } from 'sonner';import { Card, CardActions, CardActionsItem } from '@/components/card';+import { DashboardPreview } from '@/components/dashboard-preview';import { FullPageEmptyState } from '@/components/full-page-empty-state';import FullPageLoadingState from '@/components/full-page-loading-state';import { PageContainer } from '@/components/page-container';@@ -27,7 +12,6 @@ import { PageHeader } from '@/components/page-header';import { Button } from '@/components/ui/button';import { handleErrorToastOptions, useTRPC } from '@/integrations/trpc/react';import { pushModal, showConfirm } from '@/modals';-import { cn } from '@/utils/cn';import { createProjectTitle } from '@/utils/title';export const Route = createFileRoute(@@ -117,107 +101,54 @@ function Component() {title="Dashboards"/><div className="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3">- {dashboards.map((item) => {- const visibleReports = item.reports.slice(- 0,- item.reports.length > 6 ? 5 : 6- );- return (- <Card hover key={item.id}>- <div>- <Link- className="@container flex flex-col p-4"- from={Route.fullPath}- to={`${item.id}`}- >- <div className="col gap-2">- <div className="font-medium">{item.name}</div>- <div className="text-muted-foreground text-sm">- {format(item.updatedAt, 'HH:mm · MMM d')}- </div>- </div>- <div- className={cn(- 'mt-4 grid gap-2',- '@sm:grid-cols-2 grid-cols-1'- )}- >- {visibleReports.map((report) => {- const Icon = {- bar: BarChartHorizontalIcon,- linear: LineChartIcon,- pie: PieChartIcon,- metric: HashIcon,- map: Globe2Icon,- histogram: BarChart3Icon,- funnel: ConeIcon,- area: AreaChartIcon,- retention: ChartScatterIcon,- conversion: TrendingUpIcon,- sankey: GitBranchIcon,- }[report.chartType];-- return (- <div- className="row items-center gap-2 rounded-md bg-def-200 p-4 py-2"- key={report.id}- >- <Icon size={24} />- <div className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm">- {report.name}- </div>- </div>- );- })}- {item.reports.length > 6 && (- <div className="row items-center gap-2 rounded-md bg-def-100 p-4 py-2">- <PlusIcon size={24} />- <div className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm">- {item.reports.length - 5} more- </div>- </div>- )}- </div>- {/* <span className="overflow-hidden text-ellipsis whitespace-nowrap text-muted-foreground">- <span className="mr-2 font-medium">- {item.reports.length} reports- </span>- {item.reports.map((item) => item.name).join(', ')}- </span> */}- </Link>+ {dashboards.map((item) => (+ <Card className="group" hover key={item.id}>+ <Link+ className="col gap-3 p-3"+ from={Route.fullPath}+ to={`${item.id}`}+ >+ <DashboardPreview reports={item.reports} />+ <div className="col gap-0.5 px-1">+ <div className="truncate font-medium">{item.name}</div>+ <div className="truncate text-muted-foreground text-sm">+ {item.reports.length}{' '}+ {item.reports.length === 1 ? 'report' : 'reports'} · Updated{' '}+ {format(item.updatedAt, 'MMM d, HH:mm')}+ </div></div>+ </Link>- <CardActions>- <CardActionsItem asChild className="w-full">- <button- onClick={() => {- pushModal('EditDashboard', item);- }}- type="button"- >- <Pencil size={16} />- Edit- </button>- </CardActionsItem>- <CardActionsItem asChild className="w-full text-destructive">- <button- onClick={() => {- showConfirm({- title: 'Delete dashboard',- text: 'Are you sure you want to delete this dashboard? All your reports will be deleted!',- onConfirm: () => deletion.mutate({ id: item.id }),- });- }}- type="button"- >- <Trash size={16} />- Delete- </button>- </CardActionsItem>- </CardActions>- </Card>- );- })}+ <CardActions>+ <CardActionsItem asChild className="w-full">+ <button+ onClick={() => {+ pushModal('EditDashboard', item);+ }}+ type="button"+ >+ <Pencil size={16} />+ Edit+ </button>+ </CardActionsItem>+ <CardActionsItem asChild className="w-full text-destructive">+ <button+ onClick={() => {+ showConfirm({+ title: 'Delete dashboard',+ text: 'Are you sure you want to delete this dashboard? All your reports will be deleted!',+ onConfirm: () => deletion.mutate({ id: item.id }),+ });+ }}+ type="button"+ >+ <Trash size={16} />+ Delete+ </button>+ </CardActionsItem>+ </CardActions>+ </Card>+ ))}</div></PageContainer>);diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsxindex 5bdb71231..783acaffe 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.dashboards_.$dashboardId.tsx@@ -9,15 +9,17 @@ import {ShareIcon,TrashIcon,} from 'lucide-react';-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useMemo, useState } from 'react';import { toast } from 'sonner';-import { FullPageEmptyState } from '@/components/full-page-empty-state';-import FullPageLoadingState from '@/components/full-page-loading-state';import {- GrafanaGrid,+ DashboardGrid,+ isSameTilePosition,type Layout,- useReportLayouts,-} from '@/components/grafana-grid';+ TILE_MIN_SIZE,+ useDashboardLayout,+} from '@/components/dashboard-grid';+import { FullPageEmptyState } from '@/components/full-page-empty-state';+import FullPageLoadingState from '@/components/full-page-loading-state';import { OverviewInterval } from '@/components/overview/overview-interval';import { OverviewRange } from '@/components/overview/overview-range';import { useOverviewOptions } from '@/components/overview/useOverviewOptions';@@ -121,10 +123,8 @@ function Component() {}));- const reports = reportsQuery.data ?? [];+ const reports = useMemo(() => reportsQuery.data ?? [], [reportsQuery.data]);const dashboard = dashboardQuery.data;- const [isGridReady, setIsGridReady] = useState(false);- const [enableTransitions, setEnableTransitions] = useState(false);const [search, setSearch] = useState('');const filteredReports = useMemo(() => {@@ -135,19 +135,6 @@ function Component() {return reports.filter((r) => r.name?.toLowerCase().includes(q));}, [reports, search]);- // Wait for initial render to ensure grid has proper dimensions- useEffect(() => {- if (reports.length > 0 && !isGridReady) {- // Small delay to ensure container has rendered with proper width- const timer = setTimeout(() => {- setIsGridReady(true);- // Enable transitions after initial render- setTimeout(() => setEnableTransitions(true), 100);- }, 0);- return () => clearTimeout(timer);- }- }, [reports.length, isGridReady]);-const reportDeletion = useMutation(trpc.report.delete.mutationOptions({onError: handleErrorToastOptions({}),@@ -170,12 +157,23 @@ function Component() {}));- const updateLayout = useMutation(- trpc.report.updateLayout.mutationOptions({- onError: handleErrorToastOptions({}),- onSuccess() {- // Silently refetch reports (which includes layouts)- reportsQuery.refetch();+ const reportsQueryKey = trpc.report.list.queryKey({ dashboardId, projectId });+ const { mutate: saveLayouts } = useMutation(+ trpc.report.updateLayouts.mutationOptions({+ onSuccess(savedLayouts) {+ queryClient.setQueryData(reportsQueryKey, (current) =>+ current?.map((report) => ({+ ...report,+ layout:+ savedLayouts.find((saved) => saved.reportId === report.id) ??+ report.layout,+ }))+ );+ },+ onError(error) {+ handleErrorToastOptions({})(error);+ // The grid already shows the rejected layout; the saved one is the rollback.+ queryClient.invalidateQueries({ queryKey: reportsQueryKey });},}));@@ -190,8 +188,7 @@ function Component() {}));- // Convert reports to grid layout format for all breakpoints- const layouts = useReportLayouts(filteredReports);+ const [layout, setLayout] = useDashboardLayout(filteredReports);const dashboardPrimer = useMemo(() => ({@@ -208,74 +205,70 @@ function Component() {useDashboardPageContext(dashboardId, dashboardPrimer);- const handleLayoutChange = useCallback((newLayout: Layout[]) => {- // This is called during dragging/resizing, we'll save on drag/resize stop- }, []);-- const handleDragStop = useCallback(- (newLayout: Layout[]) => {- // Save each changed layout after drag stops- newLayout.forEach((item) => {- const report = reports.find((r) => r.id === item.i);- if (report) {- const oldLayout = report.layout;- // Only update if layout actually changed- if (- !oldLayout ||- oldLayout.x !== item.x ||- oldLayout.y !== item.y ||- oldLayout.w !== item.w ||- oldLayout.h !== item.h- ) {- updateLayout.mutate({- reportId: item.i,- layout: {- x: item.x,- y: item.y,- w: item.w,- h: item.h,- minW: item.minW ?? 3,- minH: item.minH ?? 3,- },- });- }- }- });+ const saveLayout = useCallback(+ (newLayout: Layout) => {+ const items = newLayout+ .filter((item) => {+ const saved = reports.find((report) => report.id === item.i)?.layout;+ return !(saved && isSameTilePosition(item, saved));+ })+ .map((item) => ({+ reportId: item.i,+ layout: {+ x: item.x,+ y: item.y,+ w: item.w,+ h: item.h,+ minW: item.minW ?? TILE_MIN_SIZE.minW,+ minH: item.minH ?? TILE_MIN_SIZE.minH,+ },+ }));+ if (items.length === 0) {+ return;+ }+ saveLayouts({ dashboardId, projectId, items });},- [reports, updateLayout]+ [reports, saveLayouts, dashboardId, projectId]);- const handleResizeStop = useCallback(- (newLayout: Layout[]) => {- // Save each changed layout after resize stops- newLayout.forEach((item) => {- const report = reports.find((r) => r.id === item.i);- if (report) {- const oldLayout = report.layout;- // Only update if layout actually changed- if (- !oldLayout ||- oldLayout.x !== item.x ||- oldLayout.y !== item.y ||- oldLayout.w !== item.w ||- oldLayout.h !== item.h- ) {- updateLayout.mutate({- reportId: item.i,- layout: {- x: item.x,- y: item.y,- w: item.w,- h: item.h,- minW: item.minW ?? 3,- minH: item.minH ?? 3,- },- });- }- }- });- },- [reports, updateLayout]+ // The grid re-renders on every drag frame; tiles that keep their element+ // identity are skipped by the grid's memo, so no chart renders mid-drag.+ const deleteReport = reportDeletion.mutate;+ const duplicateReport = reportDuplicate.mutate;+ const moveReport = useCallback(+ (reportId: string) => pushModal('MoveReport', { reportId, dashboardId }),+ [dashboardId]+ );+ const tiles = useMemo(+ () =>+ filteredReports.map((report) => (+ <div key={report.id}>+ <ReportItem+ endDate={endDate}+ interval={interval}+ onDelete={(reportId) => deleteReport({ reportId })}+ onDuplicate={(reportId) => duplicateReport({ reportId })}+ onMove={moveReport}+ organizationId={organizationId}+ projectId={projectId}+ range={range}+ report={report}+ startDate={startDate}+ />+ </div>+ )),+ [+ filteredReports,+ endDate,+ interval,+ range,+ startDate,+ organizationId,+ projectId,+ deleteReport,+ duplicateReport,+ moveReport,+ ]);if (!dashboard) {@@ -376,7 +369,7 @@ function Component() {Create report</LinkButton></FullPageEmptyState>- ) : !isGridReady || reportsQuery.isLoading ? (+ ) : reportsQuery.isLoading ? (<div className="grid grid-cols-1 gap-4 md:grid-cols-2"><ReportItemSkeleton /><ReportItemSkeleton />@@ -390,38 +383,15 @@ function Component() {<p>No reports match "{search}". Try a different search.</p></FullPageEmptyState>) : (- <GrafanaGrid- isDraggable={!search}- isResizable={!search}- layouts={layouts}- onDragStop={handleDragStop}- onLayoutChange={handleLayoutChange}- onResizeStop={handleResizeStop}- transitions={enableTransitions}+ <DashboardGrid+ isEditable={!search}+ layout={layout}+ onDragStop={saveLayout}+ onLayoutChange={setLayout}+ onResizeStop={saveLayout}>- {filteredReports.map((report) => (- <div key={report.id}>- <ReportItem- endDate={endDate}- interval={interval}- onDelete={(reportId) => {- reportDeletion.mutate({ reportId });- }}- onDuplicate={(reportId) => {- reportDuplicate.mutate({ reportId });- }}- onMove={(reportId) => {- pushModal('MoveReport', { reportId, dashboardId });- }}- organizationId={organizationId}- projectId={projectId}- range={range}- report={report}- startDate={startDate}- />- </div>- ))}- </GrafanaGrid>+ {tiles}+ </DashboardGrid>)}</PageContainer>);diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsxindex e9d47f7a7..621760c86 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx@@ -49,6 +49,7 @@ function Component() {<WidgetBody><ReportChartShortcutchartType="histogram"+ options={{ hideTable: true }}projectId={projectId}range="30d"series={@@ -80,8 +81,9 @@ function Component() {]}chartType="pie"options={{+ hideTable: true,renderSerieName(names) {- return names[1];+ return names.at(-1);},}}projectId={projectId}@@ -124,8 +126,9 @@ function Component() {]}chartType="bar"options={{+ hideTable: true,renderSerieName(names) {- return names[1];+ return names.at(-1);},}}projectId={projectId}@@ -168,8 +171,9 @@ function Component() {]}chartType="linear"options={{+ hideTable: true,renderSerieName(names) {- return names[1];+ return names.at(-1);},}}projectId={projectId}diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsxindex 73e52e4dc..aee41abfe 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.seo.tsx@@ -1,20 +1,9 @@+import type { IInterval } from '@openpanel/core/modules/report/report.constants';import { useQuery } from '@tanstack/react-query';import { createFileRoute, useNavigate } from '@tanstack/react-router';import { SearchIcon } from 'lucide-react';import { useMemo, useState } from 'react';-import {- CartesianGrid,- ComposedChart,- Line,- ResponsiveContainer,- XAxis,- YAxis,-} from 'recharts';-import {- ChartTooltipHeader,- ChartTooltipItem,- createChartTooltip,-} from '@/components/charts/chart-tooltip';+import { OPLineChart } from '@/components/charts/op-line-chart';import { FullPageEmptyState } from '@/components/full-page-empty-state';import { OverviewInterval } from '@/components/overview/overview-interval';import { OverviewMetricCard } from '@/components/overview/overview-metric-card';@@ -22,16 +11,13 @@ import { OverviewRange } from '@/components/overview/overview-range';import { OverviewWidgetTable } from '@/components/overview/overview-widget-table';import { useOverviewOptions } from '@/components/overview/useOverviewOptions';import { GscCannibalization } from '@/components/page/gsc-cannibalization';+import { GSC_CLICKS_SERIES } from '@/components/page/gsc-clicks-chart';import { GscCtrBenchmark } from '@/components/page/gsc-ctr-benchmark';import { GscPositionChart } from '@/components/page/gsc-position-chart';import { PagesInsights } from '@/components/page/pages-insights';import { PageContainer } from '@/components/page-container';import { PageHeader } from '@/components/page-header';import { Pagination } from '@/components/pagination';-import {- useYAxisProps,- X_AXIS_STYLE_PROPS,-} from '@/components/report-chart/common/axis';import { SerieIcon } from '@/components/report-chart/common/serie-icon';import { Skeleton } from '@/components/skeleton';import { Button } from '@/components/ui/button';@@ -40,7 +26,6 @@ import { useAppParams } from '@/hooks/use-app-params';import { useRangePageContext } from '@/hooks/use-page-context-helpers';import { useTRPC } from '@/integrations/trpc/react';import { pushModal } from '@/modals';-import { getChartColor } from '@/utils/theme';import { createProjectTitle } from '@/utils/title';export const Route = createFileRoute('/_app/$organizationId/$projectId/seo')({@@ -50,40 +35,7 @@ export const Route = createFileRoute('/_app/$organizationId/$projectId/seo')({}),});-interface GscChartData {- date: string;- clicks: number;- impressions: number;-}--const { TooltipProvider, Tooltip: GscTooltip } = createChartTooltip<- GscChartData,- Record<string, unknown>->(({ data }) => {- const item = data[0];- if (!item) {- return null;- }- return (- <>- <ChartTooltipHeader>- <div>{item.date}</div>- </ChartTooltipHeader>- <ChartTooltipItem color={getChartColor(0)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Clicks</span>- <span>{item.clicks.toLocaleString()}</span>- </div>- </ChartTooltipItem>- <ChartTooltipItem color={getChartColor(1)}>- <div className="flex justify-between gap-8 font-medium font-mono">- <span>Impressions</span>- <span>{item.impressions.toLocaleString()}</span>- </div>- </ChartTooltipItem>- </>- );-});+const CHART_HEIGHT = 200;function SeoPage() {const { projectId, organizationId } = useAppParams();@@ -321,11 +273,16 @@ function SeoPage() {/></div>- <GscChart data={overview} isLoading={overviewQuery.isLoading} />+ <GscChart+ data={overview}+ interval={interval ?? 'day'}+ isLoading={overviewQuery.isLoading}+ /><div className="grid grid-cols-1 gap-4 lg:grid-cols-2"><GscPositionChartdata={overview}+ interval={interval ?? 'day'}isLoading={overviewQuery.isLoading}/><GscCtrBenchmark@@ -533,80 +490,29 @@ function AiEngines(props: {function GscChart({data,+ interval,isLoading,}: {data: Array<{ date: string; clicks: number; impressions: number }>;+ interval: IInterval;isLoading: boolean;}) {- const color = getChartColor(0);- const yAxisProps = useYAxisProps();-return (<div className="card p-4"><h3 className="mb-4 font-medium text-sm">Clicks & Impressions</h3>{isLoading ? (<Skeleton className="h-48 w-full" />) : (- <TooltipProvider>- <ResponsiveContainer height={200} width="100%">- <ComposedChart data={data}>- <defs>- <filter- height="140%"- id="gsc-line-glow"- width="140%"- x="-20%"- y="-20%"- >- <feGaussianBlur result="blur" stdDeviation="5" />- <feComponentTransfer in="blur" result="dimmedBlur">- <feFuncA slope="0.5" type="linear" />- </feComponentTransfer>- <feComposite- in="SourceGraphic"- in2="dimmedBlur"- operator="over"- />- </filter>- </defs>- <CartesianGrid- className="stroke-border"- horizontal- strokeDasharray="3 3"- vertical={false}- />- <XAxis- {...X_AXIS_STYLE_PROPS}- dataKey="date"- tickFormatter={(v: string) => v.slice(5)}- type="category"- />- <YAxis {...yAxisProps} yAxisId="left" />- <YAxis {...yAxisProps} orientation="right" yAxisId="right" />- <GscTooltip />- <Line- dataKey="clicks"- dot={false}- filter="url(#gsc-line-glow)"- isAnimationActive={false}- stroke={color}- strokeWidth={2}- type="monotone"- yAxisId="left"- />- <Line- dataKey="impressions"- dot={false}- filter="url(#gsc-line-glow)"- isAnimationActive={false}- stroke={getChartColor(1)}- strokeWidth={2}- type="monotone"- yAxisId="right"- />- </ComposedChart>- </ResponsiveContainer>- </TooltipProvider>+ <OPLineChart+ data={data.map((row) => ({+ date: row.date,+ clicks: row.clicks,+ impressions: row.impressions,+ }))}+ height={CHART_HEIGHT}+ interval={interval}+ series={GSC_CLICKS_SERIES}+ />)}</div>);diff --git a/apps/start/src/routes/share.dashboard.$shareId.tsx b/apps/start/src/routes/share.dashboard.$shareId.tsxindex ba9b21a49..0dc81beb3 100644--- a/apps/start/src/routes/share.dashboard.$shareId.tsx+++ b/apps/start/src/routes/share.dashboard.$shareId.tsx@@ -1,10 +1,11 @@import { useQuery, useSuspenseQuery } from '@tanstack/react-query';import { createFileRoute, notFound, useSearch } from '@tanstack/react-router';+import { useMemo } from 'react';import { z } from 'zod';import { ShareEnterPassword } from '@/components/auth/share-enter-password';+import { DashboardGrid, useDashboardLayout } from '@/components/dashboard-grid';import { FullPageEmptyState } from '@/components/full-page-empty-state';import FullPageLoadingState from '@/components/full-page-loading-state';-import { GrafanaGrid, useReportLayouts } from '@/components/grafana-grid';import { LoginNavbar } from '@/components/login-navbar';import { OverviewInterval } from '@/components/overview/overview-interval';import { OverviewRange } from '@/components/overview/overview-range';@@ -95,6 +96,8 @@ function RouteComponent() {});const share = shareQuery.data;+ const reports = useMemo(() => reportsQuery.data ?? [], [reportsQuery.data]);+ const [layout] = useDashboardLayout(reports);if (!share) {throw notFound();@@ -109,11 +112,6 @@ function RouteComponent() {const isHeaderVisible =header !== '0' && header !== 0 && header !== 'false' && header !== false;- const reports = reportsQuery.data ?? [];-- // Convert reports to grid layout format for all breakpoints- const layouts = useReportLayouts(reports);-return (<div>{isHeaderVisible && (@@ -144,7 +142,7 @@ function RouteComponent() {) : reports.length === 0 ? (<FullPageEmptyState title="No reports" />) : (- <GrafanaGrid layouts={layouts}>+ <DashboardGrid layout={layout}>{reports.map((report) => (<div key={report.id}><ReportItemReadOnly@@ -157,7 +155,7 @@ function RouteComponent() {/></div>))}- </GrafanaGrid>+ </DashboardGrid>)}</div></div>diff --git a/apps/start/src/routes/widget/realtime.tsx b/apps/start/src/routes/widget/realtime.tsxindex e101db965..6dd375311 100644--- a/apps/start/src/routes/widget/realtime.tsx+++ b/apps/start/src/routes/widget/realtime.tsx@@ -1,21 +1,11 @@import { useQuery, useQueryClient } from '@tanstack/react-query';import { createFileRoute } from '@tanstack/react-router';import type React from 'react';-import {- Bar,- BarChart,- ResponsiveContainer,- Tooltip,- XAxis,- YAxis,-} from 'recharts';import { z } from 'zod';import { AnimatedNumber } from '@/components/animated-number';-import {- ChartTooltipContainer,- ChartTooltipHeader,- ChartTooltipItem,-} from '@/components/charts/chart-tooltip';+import { Bar } from '@/components/charts/bar';+import { BarChart } from '@/components/charts/bar-chart';+import { OPChartTooltip } from '@/components/charts/op-tooltip';import { LogoSquare } from '@/components/logo';import { Ping } from '@/components/ping';import { SerieIcon } from '@/components/report-chart/common/serie-icon';@@ -27,6 +17,17 @@ import type { RouterOutputs } from '@/trpc/client';import { cn } from '@/utils/cn';import { getChartColor } from '@/utils/theme';+const DEFAULT_BAR_COLOR = getChartColor(0);+const BAR_RADIUS = 4;+const BAR_GAP = 0.25;+const NO_MARGIN = { top: 0, right: 0, bottom: 0, left: 0 };+const TOOLTIP_MIN_WIDTH = 120;++type HistogramPoint =+ RouterOutputs['widget']['realtimeData']['histogram'][number] & {+ [key: string]: unknown;+ };+const widgetSearchSchema = z.object({shareId: z.string(),limit: z.number().default(10),@@ -110,8 +111,9 @@ function RealtimeWidget({ shareId, data, limit, color }: RealtimeWidgetProps) {});- const maxDomain =- Math.max(...data.histogram.map((item) => item.sessionCount), 1) * 1.2;+ const barColor = color || DEFAULT_BAR_COLOR;+ const firstMinute = data.histogram[0]?.time;+ const lastMinute = data.histogram.at(-1)?.time;const grids = (() => {const countries = data.countries.length > 0 ? 1 : 0;@@ -147,36 +149,40 @@ function RealtimeWidget({ shareId, data, limit, color }: RealtimeWidgetProps) {</div><div className="-mt-4 flex h-20 w-full flex-col">- <div className="flex-1">- <ResponsiveContainer height="100%" width="100%">- <BarChart- data={data.histogram}- margin={{ top: 0, right: 0, left: 0, bottom: 0 }}- >- <Tooltip- content={CustomTooltip}- cursor={{ fill: 'var(--def-100)', radius: 4 }}- />- <XAxis- axisLine={false}- dataKey="time"- interval="preserveStartEnd"- tick={{ fill: 'var(--muted-foreground)', fontSize: 10 }}- tickLine={false}- ticks={[- data.histogram[0].time,- data.histogram[data.histogram.length - 1].time,- ]}- />- <YAxis domain={[0, maxDomain]} hide />- <Bar- dataKey="sessionCount"- fill={color || 'var(--chart-0)'}- isAnimationActive={false}- radius={[4, 4, 4, 4]}- />- </BarChart>- </ResponsiveContainer>+ <div className="min-h-0 flex-1">+ <BarChart+ animationDuration={0}+ aspectRatio="auto"+ barGap={BAR_GAP}+ className="h-full"+ data={data.histogram}+ margin={NO_MARGIN}+ xDataKey="time"+ >+ <Bar+ animate={false}+ dataKey="sessionCount"+ fill={barColor}+ lineCap={BAR_RADIUS}+ />+ <OPChartTooltip<HistogramPoint>+ datePill={false}+ minWidth={TOOLTIP_MIN_WIDTH}+ rows={(point) => [+ {+ color: barColor,+ label: 'Visitors',+ value: point.sessionCount,+ },+ ]}+ showDots={false}+ title={(point) => point.time}+ />+ </BarChart>+ </div>+ <div className="row justify-between pt-1 text-[10px] text-muted-foreground">+ <span>{firstMinute}</span>+ <span>{lastMinute}</span></div></div></div>@@ -309,29 +315,6 @@ function RealtimeWidget({ shareId, data, limit, color }: RealtimeWidgetProps) {);}-// Custom tooltip component that uses portals to escape overflow hidden-const CustomTooltip = ({ active, payload }: any) => {- const number = useNumber();-- if (!(active && payload && payload.length)) {- return null;- }-- const data = payload[0].payload;-- return (- <ChartTooltipContainer className="max-w-[100px]">- <ChartTooltipHeader>- <div>{data.time}</div>- </ChartTooltipHeader>- <ChartTooltipItem color={getChartColor(0)} innerClassName="row gap-1">- <div className="flex-1">Visitors</div>- <div>{number.short(data.sessionCount)}</div>- </ChartTooltipItem>- </ChartTooltipContainer>- );-};-function RowItem({children,count,diff --git a/apps/start/src/styles.css b/apps/start/src/styles.cssindex 40b6e8b90..7cc6ebd2a 100644--- a/apps/start/src/styles.css+++ b/apps/start/src/styles.css@@ -1,4 +1,5 @@@import "tailwindcss";+@import "react-grid-layout/css/styles.css";@import "tw-animate-css";@@ -98,10 +99,10 @@ code {--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);+ /* Slightly see-through so the chart's blur shows, opaque enough to read over bright series. */+ --chart-tooltip-background: oklch(from var(--card) l c h / 0.9);+ --chart-tooltip-foreground: var(--foreground);+ --chart-tooltip-muted: var(--muted-foreground);--chart-marker-background: var(--def-100);--chart-marker-border: var(--border);--chart-marker-foreground: var(--foreground);@@ -113,6 +114,17 @@ code {--chart-marker-badge-foreground: var(--background);--chart-ring-background: oklch(from var(--foreground) l c h / 0.12);--chart-label: var(--muted-foreground);+ --chart-scale-01: color-mix(in oklab, var(--chart-0) 8%, var(--card));+ --chart-scale-02: color-mix(in oklab, var(--chart-0) 28%, var(--card));+ --chart-scale-03: color-mix(in oklab, var(--chart-0) 50%, var(--card));+ --chart-scale-04: color-mix(in oklab, var(--chart-0) 75%, var(--card));+ --chart-scale-05: var(--chart-0);+ --chart-scale-pattern-color: var(--def-100);+ --legend: var(--card);+ --legend-foreground: var(--foreground);+ --legend-muted: var(--def-100);+ --legend-muted-foreground: var(--muted-foreground);+ --legend-track: var(--def-200);}.dark {@@ -148,27 +160,6 @@ 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 {@@ -331,12 +322,6 @@ code {}}-/* Rechart styles from globals.css */-.recharts-wrapper .recharts-cartesian-grid-horizontal line:first-child,-.recharts-wrapper .recharts-cartesian-grid-horizontal line:last-child {- stroke-opacity: 0;-}-button {@apply cursor-pointer;}@@ -355,6 +340,7 @@ button {}.scrollbar-thin::-webkit-scrollbar {width: 6px;+ height: 6px;}.scrollbar-thin::-webkit-scrollbar-track {background: transparent;@@ -539,12 +525,48 @@ button {--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-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);}++/* Dashboard grid: only tiles making room animate; the one under the pointer+ follows it 1:1. */+.react-grid-item.cssTransforms {+ transition: transform 180ms cubic-bezier(0.2, 0, 0, 1);+}+.react-grid-item.react-draggable-dragging,+.react-grid-item.resizing {+ transition: none;+}+.react-grid-item.react-grid-placeholder {+ background: color-mix(in oklch, var(--primary) 8%, transparent);+ opacity: 1;+ border: 1px solid var(--primary);+ border-radius: var(--radius);+ transition: transform 100ms cubic-bezier(0.2, 0, 0, 1);+}+@media (prefers-reduced-motion: reduce) {+ .react-grid-item.cssTransforms,+ .react-grid-item.react-grid-placeholder {+ transition: none;+ }+}++/* While a tile moves, nothing under the pointer reacts: no chart tooltips,+ no hover states, no text selection. The gesture itself runs on document+ listeners, so the tiles need no pointer events until it ends. */+.react-grid-layout:has(.react-draggable-dragging, .resizing) .react-grid-item+ > * {+ pointer-events: none;+ user-select: none;+}+html:has(.react-grid-item.react-draggable-dragging),+.react-grid-item.react-draggable-dragging {+ cursor: grabbing;+}diff --git a/apps/start/src/types/index.ts b/apps/start/src/types/index.tsindex 013c4beab..703f7db96 100644--- a/apps/start/src/types/index.ts+++ b/apps/start/src/types/index.ts@@ -1,11 +1,6 @@-import type { TooltipProps } from 'recharts';-export type HtmlProps<T> = Omit<React.DetailedHTMLProps<React.HTMLAttributes<T>, T>,'ref'>;-export type IToolTipProps<T> = Omit<TooltipProps<number, string>, 'payload'> & {- payload?: T[];-};export type OAuthStrategy = 'oauth_google' | 'oauth_github';diff --git a/apps/start/vite.config.ts b/apps/start/vite.config.tsindex 3f0d052a8..c875cdafd 100644--- a/apps/start/vite.config.ts+++ b/apps/start/vite.config.ts@@ -38,7 +38,18 @@ const config = defineConfig({...(behindProxy ? { hmr: { protocol: 'wss', clientPort: 443 } } : {}),},ssr: {- noExternal: ['react-syntax-highlighter', 'lowlight', 'highlight.js'],+ noExternal: [+ 'react-syntax-highlighter',+ 'lowlight',+ 'highlight.js',+ // CommonJS that Node's ESM loader gets wrong in the built server:+ // @visx/responsive imports `lodash/debounce` without an extension, and+ // react-svg-worldmap's default export arrives as `{ default }`. Bundled,+ // both resolve.+ '@visx/responsive',+ 'lodash',+ 'react-svg-worldmap',+ ],},});diff --git a/bklit-issues.md b/bklit-issues.mdindex 2d94e085a..664f1769b 100644--- a/bklit-issues.md+++ b/bklit-issues.md@@ -2,6 +2,32 @@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.+## Re-vendoring++Last synced from the registry on 2026-10-15. Fetch every item (and its `registryDependencies`) into a scratch directory, diff against `apps/start/src/components/charts/`, copy over, then `bunx biome format --write` the folder and re-apply the patches marked **open** below.++| # | Patch | Status |+|---|---|---|+| 1 | `require("react-dom")` | fixed upstream |+| 2 | registry lags local source | obsolete, registry is current |+| 3 | dark `--chart-*` overrides | **open**: re-apply in `styles.css` after `shadcn add` |+| 4 | no dual Y axis | **open**: workaround in `overview-metrics.tsx` |+| 5 | `tickMode="data"` | **open**: pass it per chart |+| 6 | svg clips markers | fixed upstream (`overflow-visible`) |+| 7 | tooltip ignores markers | **open**: ours, `op-tooltip.tsx` |+| 8 | missing values | **open**: re-apply in `line.tsx` / `area.tsx` |+| 9 | slow hover springs | **open**: configured, not patched (`ChartConfigProvider` in `providers.tsx`) |+| 10–16, 18 | hover performance, `useId`, memo splits, stable context, `console.log` | fixed upstream |+| 17 | `series-point-marker` variants per render | obsolete: the marker is `memo`ed and its variants only drive the mount animation |+| 19 | marker badge props | **open**: re-apply in `markers/marker-group.tsx` |+| 20 | x-axis date labels are always `Sep 25` | **open**: re-apply `formatDateLabel` in `time-series-chart-shell.tsx` / `line-chart.tsx` |+| 21 | tooltip dot for a missing value sits at the top | **open**: re-apply in `tooltip/chart-tooltip.tsx` |+| 22 | no stacked areas | **open**: re-apply `baselineKey` in `area.tsx` |+| 23 | sankey links have no gap | **open**: re-apply `linkGap` in `sankey/sankey-link.tsx` |+| 24 | no fixed y domain (percent axes reach 120%) | **open**: re-apply `yDomain` in `time-series-chart-shell.tsx` / `line-chart.tsx` |++`chart-loading-label.tsx` imports `../components/shimmering-text`, which does not resolve with the registry's own targets; it is patched to `../shimmering-text`.+---## 1. `require("react-dom")` breaks under Vite / ESM bundlers@@ -77,13 +103,7 @@ The injection also collapses onto a single line, mangling the `.dark` block form**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);-```+After re-installing, remove everything the injection appended to `.dark`. The `:root` tokens (including `--chart-tooltip-*`, which follow `--card` / `--foreground`) already adapt to the theme.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`.@@ -191,17 +211,7 @@ The fallback `0` is a raw SVG y coordinate, not a data-domain zero. In SVG y=0 i**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]);-```+**Fix (applied locally)** in `apps/start/src/components/charts/line.tsx` and `area.tsx`: a `hasValue` callback passed as `defined` to the `LinePath` / `AreaClosed`, so a missing value leaves a gap instead of a point at y=0 or the ceiling. The animated transition path (`use-animated-series-path.ts`) still interpolates through gaps; it only shows during a data change.`shadcn add` will revert these — re-patch from this file.@@ -221,7 +231,7 @@ Bklit ships hover-related springs that feel sluggish compared to recharts' no-anPlus 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.+Upstream now reads these from `ChartConfigProvider` (`chart-config-context.tsx`), so we no longer patch the files: `providers.tsx` wraps the app in a provider with `{ stiffness: 1000, damping: 60 }` for the tooltip, tooltip box and highlight springs.---@@ -563,3 +573,85 @@ Backward compat preserved (defaults off). Used by `op-marker-layer.tsx` to giveAlso 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.++---++## 20. X-axis labels ignore the interval++**Symptom**++An hourly or minute report shows the same day label (`Sep 25`) on every tick and in the crosshair pill.++**Cause**++`time-series-chart-shell.tsx` builds `dateLabels` with `shortDateFmt` unconditionally; there is no prop to format them.++**Fix (applied locally)**++`TimeSeriesChartInner` and `LineChart` take `formatDateLabel?: (date: Date) => string` (default `shortDateFmt.format`), used for `dateLabels`. `AreaChart` forwards it too. The report charts pass `formatDateInterval({ interval, short: true })`.++`shadcn add` reverts.++---++## 21. Tooltip dot for a series without a value is drawn at the top++**Symptom**++Hovering a point where one series has no value (e.g. the previous period of a range that has no earlier data) shows that series' dot at the very top of the chart.++**Cause**++`use-chart-interaction.ts` only writes `yPositions[dataKey]` for numeric values, but `chart-tooltip.tsx` renders every line's `TooltipDot` with `y={yPositions[dataKey] ?? 0}`.++**Fix (applied locally)**++The dot's `visible` is false when `yPositions[line.dataKey]` is undefined.++`shadcn add` reverts.++---++## 22. `<Area>` cannot stack++**Symptom**++Report area charts are stacked (each series on top of the ones before it); bklit's `<Area>` always fills down to zero.++**Fix (applied locally)**++`<Area baselineKey="…">` reads each point's baseline from that key and passes it to visx's `AreaClosed` as `y0`. The report area chart pre-computes a `:stack` top and `:stack-base` per series (`report-chart/area/chart.tsx`, `stackSeries`) and plots the tops, so the y-domain and the tooltip dots follow the stacked values while the tooltip rows show the raw counts.++`shadcn add` reverts.++---++## 23. Sankey links touch, so neighbouring flows merge++**Symptom**++Links that leave or enter a node side by side read as one block, most of all when the nodes share a colour.++**Fix (applied locally)**++`<SankeyLink linkGap={n}>` takes `n` pixels off every link's stroke width, leaving a hairline between neighbouring bands. The report sankey passes 2.++`shadcn add` reverts.++---++## 24. The y domain always gets 10% headroom++**Symptom**++A chart of percentages tops out at 120%, which reads as if conversion could exceed 100%.++**Cause**++`resolveTimeSeriesYDomain` in `time-series-chart-shell.tsx` returns `[0, max * 1.1]` and `niceYDomain` rounds it; there is no way to pin the domain.++**Fix (applied locally)**++`TimeSeriesChartInner` and `LineChart` take `yDomain?: [number, number]`, used as is when set. The conversion report passes `[0, 100]`.++`shadcn add` reverts.diff --git a/bun.lock b/bun.lockindex 23abbffd7..ad407a288 100644--- a/bun.lock+++ b/bun.lock@@ -94,6 +94,7 @@"apps/start": {"name": "start","dependencies": {+ "@base-ui/react": "1.9.0","@better-agent/client": "0.1.0-beta.3","@codemirror/commands": "6.10.1","@codemirror/lang-javascript": "6.2.4",@@ -161,12 +162,17 @@"@trpc/tanstack-react-query": "11.6.0","@visx/curve": "4.0.1-alpha.0","@visx/event": "4.0.1-alpha.0",+ "@visx/geo": "4.0.1-alpha.0","@visx/gradient": "4.0.1-alpha.0","@visx/grid": "4.0.1-alpha.0",+ "@visx/group": "4.0.1-alpha.0",+ "@visx/heatmap": "4.0.1-alpha.0","@visx/pattern": "4.0.1-alpha.0","@visx/responsive": "4.0.1-alpha.0",+ "@visx/sankey": "4.0.1-alpha.0","@visx/scale": "4.0.1-alpha.0","@visx/shape": "4.0.1-alpha.0",+ "@visx/zoom": "4.0.1-alpha.0","bind-event-listener": "3.0.0","class-variance-authority": "0.7.1","clsx": "2.1.1",@@ -174,6 +180,9 @@"codemirror": "6.0.2","d3": "7.8.5","d3-array": "3.2.4",+ "d3-geo": "3.1.1",+ "d3-sankey": "0.12.3",+ "d3-shape": "3.2.0","date-fns": "3.3.1","debounce": "2.2.0","embla-carousel-autoplay": "8.6.0",@@ -202,19 +211,17 @@"react-animated-numbers": "1.1.1","react-day-picker": "9.9.0","react-dom": "catalog:",- "react-grid-layout": "1.5.2",+ "react-grid-layout": "2.3.0","react-hook-form": "7.50.1","react-in-viewport": "1.0.0-beta.8","react-markdown": "10.1.0","react-redux": "8.1.3",- "react-resizable": "3.0.5","react-responsive": "9.0.2","react-simple-maps": "3.0.0","react-svg-worldmap": "2.0.0-alpha.16","react-syntax-highlighter": "15.5.0","react-use-websocket": "4.7.0","react-virtualized-auto-sizer": "1.0.22",- "recharts": "2.15.4","rehype-katex": "7.0.1","remark-gfm": "4.0.1","remark-highlight": "0.1.1",@@ -244,13 +251,16 @@"@testing-library/react": "16.3.0","@types/d3": "7.4.3","@types/d3-array": "3.2.2",+ "@types/d3-geo": "3.1.1",+ "@types/d3-sankey": "0.12.5",+ "@types/d3-shape": "3.2.0",+ "@types/geojson": "7946.0.16","@types/lodash.debounce": "4.0.9","@types/lodash.isequal": "4.5.8","@types/lodash.throttle": "4.1.9","@types/ramda": "0.31.0","@types/react": "catalog:","@types/react-dom": "catalog:",- "@types/react-grid-layout": "1.3.5","@types/react-simple-maps": "3.0.4","@types/react-syntax-highlighter": "15.5.11","@vitejs/plugin-react": "5.2.0",@@ -630,6 +640,7 @@},},"patchedDependencies": {+ "[email protected]": "patches/[email protected]","@polar-sh/[email protected]": "patches/@polar-sh__sdk.patch",},"overrides": {@@ -1047,6 +1058,10 @@"@babel/types": ["@babel/[email protected]", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="],+ "@base-ui/react": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.29.7 || ^8.0.0", "@base-ui/utils": "0.5.0", "@floating-ui/react-dom": "^2.1.9", "@floating-ui/utils": "^0.2.12", "use-sync-external-store": "^1.7.0" }, "peerDependencies": { "@date-fns/tz": "^1.2.0", "@types/react": "^17 || ^18 || ^19", "date-fns": "^4.0.0", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@date-fns/tz", "@types/react", "date-fns"] }, "sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ=="],++ "@base-ui/utils": ["@base-ui/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.29.7 || ^8.0.0", "@floating-ui/utils": "^0.2.12", "reselect": "^5.3.0", "use-sync-external-store": "^1.7.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A=="],+"@better-agent/client": ["@better-agent/[email protected]", "", { "dependencies": { "@better-agent/core": "0.1.0-beta.3", "@better-agent/shared": "0.1.0-beta.3" }, "peerDependencies": { "preact": "^10.0.0", "react": "^18.0.0 || ^19.0.0", "solid-js": "^1.9.0", "svelte": "^4.0.0 || ^5.0.0", "vue": "^3.3.0" }, "optionalPeers": ["preact", "react", "solid-js", "svelte", "vue"] }, "sha512-+fqFcmxHQRBE5D69Cq8EZJpU0xjNi4UfQSSSgxwz2CWmdaGAep6Xhh5CRFaJBvqXv6+WHdM3d8g2sXQKCyZqHw=="],"@better-agent/core": ["@better-agent/[email protected]", "", { "dependencies": { "@better-agent/shared": "0.1.0-beta.3", "@standard-schema/spec": "1.1.0", "ajv": "^8.17.1", "json-schema-to-ts": "^3.1.1" } }, "sha512-Mic8iDyHz/2ESTgZvgslPD+zf3iYFiSBda2l0f2T3UD/wMXux9rkSVXCpD8jSgMYWUxx1gt8Fns+7IVQfbnDJw=="],@@ -2673,7 +2688,7 @@"@types/d3-random": ["@types/[email protected]", "", {}, "sha512-UHYId5WTCx4L4YNel7NU00XUXXgvgpgZOvp10PuvsQENjMDXhh2RyFc0KBjO7B45ne4Ha1yVH7ii0vnzKkuzWA=="],- "@types/d3-sankey": ["@types/[email protected]", "", { "dependencies": { "@types/d3-shape": "^1" } }, "sha512-U6SrTWUERSlOhnpSrgvMX64WblX1AxX6nEjI2t3mLK2USpQrnbwYYK+AS9SwiE7wgYmOsSSKoSdr8aoKBH0HgQ=="],+ "@types/d3-sankey": ["@types/[email protected]", "", { "dependencies": { "@types/d3-shape": "^1" } }, "sha512-/3RZSew0cLAtzGQ+C89hq/Rp3H20QJuVRSqFy6RKLe7E0B8kd2iOS1oBsodrgds4PcNVpqWhdUEng/SHvBcJ6Q=="],"@types/d3-scale": ["@types/[email protected]", "", { "dependencies": { "@types/d3-time": "*" } }, "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw=="],@@ -2793,8 +2808,6 @@"@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="],- "@types/react-grid-layout": ["@types/[email protected]", "", { "dependencies": { "@types/react": "*" } }, "sha512-WH/po1gcEcoR6y857yAnPGug+ZhkF4PaTUxgAbwfeSH/QOgVSakKHBXoPGad/sEznmkiaK3pqHk+etdWisoeBQ=="],-"@types/react-simple-maps": ["@types/[email protected]", "", { "dependencies": { "@types/d3-geo": "^2", "@types/d3-zoom": "^2", "@types/geojson": "*", "@types/react": "*" } }, "sha512-U9qnX0wVhxldrTpsase44fIoLpyO1OT/hgNMRoJTixj1qjpMRdSRIfih93mR3D/Tss/8CmM7dPwKMjtaGkDpmw=="],"@types/react-syntax-highlighter": ["@types/[email protected]", "", { "dependencies": { "@types/react": "*" } }, "sha512-ZqIJl+Pg8kD+47kxUjvrlElrraSUrYa4h0dauY/U/FTUuprSCqvUj+9PNQNQzVc6AJgIWUUxn87/gqsMHNbRjw=="],@@ -2861,30 +2874,42 @@"@unhead/vue": ["@unhead/[email protected]", "", { "dependencies": { "hookable": "^6.0.1", "unhead": "2.1.17" }, "peerDependencies": { "vue": ">=3.5.18" } }, "sha512-pnC8x9HLV3qQXdvWfylUEU25uhfCAy3ly9nmpQz84j9py818DRfU8jOsQ5wjdWtxyU1vX/fW2udfm4jtxUK8Bg=="],+ "@use-gesture/core": ["@use-gesture/[email protected]", "", {}, "sha512-WcINiDt8WjqBdUXye25anHiNxPc0VOrlT8F6LLkU6cycrOGUDyY/yyFmsg3k8i5OLvv25llc0QC45GhR/C8llw=="],++ "@use-gesture/react": ["@use-gesture/[email protected]", "", { "dependencies": { "@use-gesture/core": "10.3.1" }, "peerDependencies": { "react": ">= 16.8.0" } }, "sha512-Yy19y6O2GJq8f7CHf7L0nxL8bf4PZCPaVOCgJrusOeFHY1LvHgYXnmnXg6N5iwAnbgbZCDjo60SiM6IPJi9C5g=="],+"@vercel/nft": ["@vercel/[email protected]", "", { "dependencies": { "@mapbox/node-pre-gyp": "^2.0.0", "@rollup/pluginutils": "^5.1.3", "acorn": "^8.6.0", "acorn-import-attributes": "^1.9.5", "async-sema": "^3.1.1", "bindings": "^1.4.0", "estree-walker": "2.0.2", "glob": "^13.0.0", "graceful-fs": "^4.2.9", "node-gyp-build": "^4.2.2", "picomatch": "^4.0.4", "resolve-from": "^5.0.0" }, "bin": { "nft": "out/cli.js" } }, "sha512-m1QFg+U+3yPOnP1xSYJ73UIRxLOXdts1JOhiOiyPYqEsALgrXFFINvgUaD6R6iNvaBFAjHllBCbkfx4FuOdpaA=="],"@visx/curve": ["@visx/[email protected]", "", { "dependencies": { "@visx/vendor": "4.0.0-alpha.0" } }, "sha512-jRu61Uz274pV1zyioXmboyrLutYbnKsgjj4njSGCnhdXj5GkZvZbg+ThDb6oOzoAnJOBRLz4rzPlWvNJOzuVMg=="],"@visx/event": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "@visx/point": "4.0.1-alpha.0" } }, "sha512-EQqCMSv/s8NbFjo+hz3FKsvvYfP+2QslsFJ/24/O5l/W+7UC6J6aAvO0ujVwrTwdYbuQ+vhxKi1xdPdKR/qj1g=="],+ "@visx/geo": ["@visx/[email protected]", "", { "dependencies": { "@types/geojson": "*", "@types/react": "*", "@visx/group": "4.0.1-alpha.0", "@visx/vendor": "4.0.0-alpha.0", "classnames": "^2.3.1" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-ZzeXrMgT1JjUZl1GaW3KecN2PkCCTDfYDeTD8+kvugC6umLKTsJ4+ii1GpjrgnPTtOBzZnJHCAknJ3mzaz/DRg=="],+"@visx/gradient": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-HxkxLdThV/gPaulw+t7/ESo7AtqIBq9IlHIkHi7lQqXe0Yl+x8rpM3KYlYqEZjtihD9CeEaVJjBbdY7fQb54IA=="],"@visx/grid": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "@visx/curve": "4.0.1-alpha.0", "@visx/group": "4.0.1-alpha.0", "@visx/point": "4.0.1-alpha.0", "@visx/scale": "4.0.1-alpha.0", "@visx/shape": "4.0.1-alpha.0", "classnames": "^2.3.1" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-rycutGmTHO+znNdPumheWMglm7YfpffvRwUkVy5zy4WoORIuKTMkDxwnOzHG2xMxU3EE/YCd37xFV5AxA30yeg=="],"@visx/group": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "classnames": "^2.3.1" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-V19l7iQ7jccBv8kao/EByuI6o4xtxzzLV9nqVI1hRvmdzTVsuLpqlwzYCZUXJaTVvUWf8s4D2SQFjGkj/Nw+0w=="],+ "@visx/heatmap": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "@visx/group": "4.0.1-alpha.0", "classnames": "^2.3.1" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-fxghd5MCLSDeLxlT8f0x6ulEcBPgJZg9VyLQvCwVNHwopm3DUkk6evPJOMlcpXJiESDXsHkhSNit42O2fIZBRA=="],+"@visx/pattern": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "classnames": "^2.3.1" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-KCqHpjtHdu95uqamc5PIYG55Xp0w+7/Zz63k4eeZErwK1o0PN2rZiBiuodNtENL8NqIU2b5AP+XI/xXaUH0M4Q=="],"@visx/point": ["@visx/[email protected]", "", {}, "sha512-ijTfr/Nx09f03vIj9nyTr3z4Xth4Y75427UaogJh6dnIRLMEFHQOwNu791sbfiNj0a+ZXuaE32h0vKrFe4/8Qg=="],"@visx/responsive": ["@visx/[email protected]", "", { "dependencies": { "@types/lodash": "^4.17.13", "@types/react": "*", "lodash": "^4.17.21" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-o+1zGywQZY0+yOx3Iw87wc4bbPJRr/HnIukTwfOz4UVyj9pB1OQNVHB7OORO1+LBHJceWpB31co/ZV9KHncKrA=="],+ "@visx/sankey": ["@visx/[email protected]", "", { "dependencies": { "@types/d3-sankey": "^0.12.4", "@types/react": "*", "@visx/group": "4.0.1-alpha.0", "@visx/vendor": "4.0.0-alpha.0", "classnames": "^2.3.1", "d3-sankey": "^0.12.3" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-bzF3MHdJ9A/KdWiGK7vy64A9MK8HhNldAxeUTiQd5wELdvx8YMHOkU8AxtKACWHveaoakthnesgQjbrEGt4oeg=="],+"@visx/scale": ["@visx/[email protected]", "", { "dependencies": { "@visx/vendor": "4.0.0-alpha.0" } }, "sha512-nzjeE87vFSAXGWFiiNfBpNLAf0Q8Qmf6syvKLjqNi4kGZkdhbUll3E/59YsgWXmjM8+llPLWzGsP+JPvo5eq1A=="],"@visx/shape": ["@visx/[email protected]", "", { "dependencies": { "@types/lodash": "^4.17.13", "@types/react": "*", "@visx/curve": "4.0.1-alpha.0", "@visx/group": "4.0.1-alpha.0", "@visx/scale": "4.0.1-alpha.0", "@visx/vendor": "4.0.0-alpha.0", "classnames": "^2.3.1", "lodash": "^4.17.21" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-62QeiVNmPlterQGwhkEDcbq7M0MqY0lBsK5QKXtM9ZoPZWkuGV3aykA3+Xu20B2FAvyJq4LqJzBc7Sxr+EAdbA=="],"@visx/vendor": ["@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" } }, "sha512-6I+MuqXBcv9jnlcVowHoHKSdk9gXTWkHLKyqBwRWg7LY6A3Ei8SHfubpqGV5rBUSppxMq2RszPJUS6w+H0YgmQ=="],+ "@visx/zoom": ["@visx/[email protected]", "", { "dependencies": { "@types/react": "*", "@use-gesture/react": "^10.3.1", "@visx/event": "4.0.1-alpha.0" }, "peerDependencies": { "react": "^16.14.0 || ^17.0.0-0 || ^18.0.0-0 || ^19.0.0-0" } }, "sha512-f+Y3rI3Lhpn4wbkSQw3IPsqtcRbh/TcF4M4N5ETrciMXtkJVQNrYzzC6mgxN1fZcw2228oKZzNaMI7hpOLoPkw=="],+"@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw=="],"@vitejs/plugin-vue": ["@vitejs/[email protected]", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", "vue": "^3.2.25" } }, "sha512-0ZjgOg7oO6farnNGup7yvoM/YXZV84OZxHAwtflItNa/6zzQyVb5LNxyea3FEKEX2XlagIKzrlH7wwxkKgtiew=="],@@ -5081,7 +5106,7 @@"react-email": ["[email protected]", "", { "dependencies": { "@babel/core": "7.24.5", "@babel/parser": "7.24.5", "chalk": "4.1.2", "chokidar": "^4.0.1", "commander": "11.1.0", "debounce": "2.0.0", "esbuild": "0.19.11", "glob": "10.3.4", "log-symbols": "4.1.0", "mime-types": "2.1.35", "next": "15.0.4", "normalize-path": "3.0.0", "ora": "5.4.1", "socket.io": "4.8.0" }, "bin": { "email": "dist/cli/index.js" } }, "sha512-nXdo9P3V+qYSW6m5yN3XpFGhHb/bflX86m0EDQEqDIgayprj6InmBJoBnMSIyC5EP4tPtoAljlclJns4lJG/MQ=="],- "react-grid-layout": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1", "fast-equals": "^4.0.3", "prop-types": "^15.8.1", "react-draggable": "^4.4.6", "react-resizable": "^3.0.5", "resize-observer-polyfill": "^1.5.1" }, "peerDependencies": { "react": ">= 16.3.0", "react-dom": ">= 16.3.0" } }, "sha512-vT7xmQqszTT+sQw/LfisrEO4le1EPNnSEMVHy6sBZyzS3yGkMywdOd+5iEFFwQwt0NSaGkxuRmYwa1JsP6OJdw=="],+ "react-grid-layout": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1", "fast-equals": "^4.0.3", "prop-types": "^15.8.1", "react-draggable": "^4.4.6", "react-resizable": "^3.2.0", "resize-observer-polyfill": "^1.5.1" }, "peerDependencies": { "react": ">= 16.3.0", "react-dom": ">= 16.3.0" } }, "sha512-4ofzuR/MlYchp+ixDUVBxH6ybaw+JH51M+rpf675ik/++4Dn0Kax/Vf2Gv/7Z++mV1ZC7mY9UV2sRRycjGjKXQ=="],"react-hook-form": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17 || ^18" } }, "sha512-3PCY82oE0WgeOgUtIr3nYNNtNvqtJ7BZjsbxh6TnYNbXButaD5WpjOmTjdxZfheuHKR68qfeFnEDVYoSSFPMTQ=="],@@ -5107,7 +5132,7 @@"react-remove-scroll-bar": ["[email protected]", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="],- "react-resizable": ["[email protected]", "", { "dependencies": { "prop-types": "15.x", "react-draggable": "^4.0.3" }, "peerDependencies": { "react": ">= 16.3" } }, "sha512-vKpeHhI5OZvYn82kXOs1bC8aOXktGU5AmKAgaZS4F5JPburCtbmDPqE7Pzp+1kN4+Wb81LlF33VpGwWwtXem+w=="],+ "react-resizable": ["[email protected]", "", { "dependencies": { "prop-types": "15.x", "react-draggable": "^4.5.0" }, "peerDependencies": { "react": ">= 16.3", "react-dom": ">= 16.3" } }, "sha512-3NKQ0SLZV7rs3LQHeXlOzDSRQfFrkX6TVet77/Qk03zqiZyee37b7N8/gwDJAA8UUjRz7PdWCCy49hcso45SMQ=="],"react-responsive": ["[email protected]", "", { "dependencies": { "hyphenate-style-name": "^1.0.0", "matchmediaquery": "^0.3.0", "prop-types": "^15.6.1", "shallow-equal": "^1.2.1" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+4CCab7z8G8glgJoRjAwocsgsv6VA2w7JPxFWHRc7kvz8mec1/K5LutNC2MG28Mn8mu6+bu04XZxHv5gyfT7xQ=="],@@ -5781,7 +5806,7 @@"use-stick-to-bottom": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-GgRLdeGhxBxpcbrBbEIEoOKUQ9d46/eaSII+wyv1r9Du+NbCn1W/OE+VddefvRP4+5w/1kATN/6g2/BAC/yowQ=="],- "use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],+ "use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="],"usehooks-ts": ["[email protected]", "", { "dependencies": { "lodash.debounce": "^4.0.8" }, "peerDependencies": { "react": "^16.8.0 || ^17 || ^18" } }, "sha512-jnhrjTRJoJS7cFxz63tRYc5mzTKf/h+Ii8P0PDHymT9qDe4ZA2/gzDRmDR4WGausg5X8wMIdghwi3BBCN9JKow=="],@@ -6167,6 +6192,8 @@"@nivo/core/react-virtualized-auto-sizer": ["[email protected]", "", { "peerDependencies": { "react": "^15.3.0 || ^16.0.0-alpha || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^15.3.0 || ^16.0.0-alpha || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-CblNyiNVw2o+hsa5/49NH2ogGxZ+t+3aweRvNSq7TVjDIlwk7ir4lencEg5HxHeSzwNarSkNkiu0qJSOXtxm5A=="],+ "@nivo/sankey/@types/d3-sankey": ["@types/[email protected]", "", { "dependencies": { "@types/d3-shape": "^1" } }, "sha512-U6SrTWUERSlOhnpSrgvMX64WblX1AxX6nEjI2t3mLK2USpQrnbwYYK+AS9SwiE7wgYmOsSSKoSdr8aoKBH0HgQ=="],+"@node-minify/core/glob": ["[email protected]", "", { "dependencies": { "fs.realpath": "^1.0.0", "minimatch": "^8.0.2", "minipass": "^4.2.4", "path-scurry": "^1.6.1" } }, "sha512-e1LleDykUz2Iu+MTYdkSsuWX8lvAjAcs0Xef0lNIu0S2wOAzuTxCJtcd9S3cijlwYF18EsU3rzb8jPVobxDh9Q=="],"@node-minify/core/mkdirp": ["[email protected]", "", { "bin": { "mkdirp": "bin/cmd.js" } }, "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw=="],@@ -6393,6 +6420,8 @@"@radix-ui/react-use-effect-event/@radix-ui/react-use-layout-effect": ["@radix-ui/[email protected]", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="],+ "@radix-ui/react-use-is-hydrated/use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],+"@react-email/components/@react-email/render": ["@react-email/[email protected]", "", { "dependencies": { "html-to-text": "^9.0.5", "prettier": "^3.5.3", "react-promise-suspense": "^0.3.4" }, "peerDependencies": { "react": "^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^18.0 || ^19.0 || ^19.0.0-rc" } }, "sha512-oq8/BD/I/YspeuBjjdLJG6xaf9tsPYk+VWu8/mX9xWbRN0t0ExKSVm9sEBL6RsCpndQA2jbY2VgPEreIrzUgqw=="],"@react-native-community/cli/commander": ["[email protected]", "", {}, "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ=="],@@ -6539,6 +6568,8 @@"@tanstack/react-router-devtools/vite": ["[email protected]", "", { "dependencies": { "esbuild": "^0.27.0 || ^0.28.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", "rollup": "^4.43.0", "tinyglobby": "^0.2.15" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "jiti": ">=1.21.0", "less": "^4.0.0", "lightningcss": "^1.21.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg=="],+ "@tanstack/react-store/use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],+"@tanstack/router-core/@tanstack/store": ["@tanstack/[email protected]", "", {}, "sha512-xa6pTan1bcaqYDS9BDpSiS63qa6EoDkPN9RsRaxHuDdVDNntzq3xNwR5YKTU/V3SkSyC9T4YVOPh2zRQN0nhIQ=="],"@tanstack/router-core/cookie-es": ["[email protected]", "", {}, "sha512-aVf4A4hI2w70LnF7GG+7xDQUkliwiXWXFvTjkip4+b64ygDQ2sJPRSKFDHbxn8o0xu9QzPkMuuiWIXyFSE2slA=="],@@ -7305,6 +7336,8 @@"react-promise-suspense/fast-deep-equal": ["[email protected]", "", {}, "sha512-bCK/2Z4zLidyB4ReuIsvALH6w31YfAQDmXMqMx6FyfHqvBxtjC0eRumeSu4Bs3XtXwpyIywtSTrVT99BxY1f9w=="],+ "react-redux/use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],+"react-simple-maps/d3-geo": ["[email protected]", "", { "dependencies": { "d3-array": "^2.5.0" } }, "sha512-8pM1WGMLGFuhq9S+FpPURxic+gKzjluCD/CHTuUF3mXMeiCo0i6R0tO1s4+GArRFde96SLcW/kOFRjoAosPsFA=="],"react-simple-maps/d3-selection": ["[email protected]", "", {}, "sha512-XoGGqhLUN/W14NmaqcO/bb1nqjDAw5WtSYb2X8wiuQWvSZUsUVYsOSkOybUrNvcBjaywBdYPy03eXHMXjk9nZA=="],@@ -7663,6 +7696,8 @@"@nivo/core/d3-time-format/d3-time": ["[email protected]", "", { "dependencies": { "d3-array": "2" } }, "sha512-/eIQe/eR4kCQwq7yxi7z4c6qEXf2IYGcjoWB5OOQy4Tq9Uv39/947qlDcN2TLkiTzQWzvnsuYPB9TrWaNfipKQ=="],+ "@nivo/sankey/@types/d3-sankey/@types/d3-shape": ["@types/[email protected]", "", { "dependencies": { "@types/d3-path": "^1" } }, "sha512-8oMzcd4+poSLGgV0R1Q1rOlx/xdmozS4Xab7np0eamFFUYq71AU9pOCJEFnkXW2aI/oXdVYJzw6pssbSut7Z9Q=="],+"@node-minify/core/glob/minimatch": ["[email protected]", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-V+1uQNdzybxa14e/p00HZnQNNcTjnRJjDxg2V8wtkjFctq4M7hXFws4oekyTP0Jebeq7QYtpFyOeBAjc88zvYg=="],"@node-minify/core/glob/minipass": ["[email protected]", "", {}, "sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ=="],@@ -8021,6 +8056,8 @@"@tanstack/react-router/@tanstack/react-store/@tanstack/store": ["@tanstack/[email protected]", "", {}, "sha512-xa6pTan1bcaqYDS9BDpSiS63qa6EoDkPN9RsRaxHuDdVDNntzq3xNwR5YKTU/V3SkSyC9T4YVOPh2zRQN0nhIQ=="],+ "@tanstack/react-router/@tanstack/react-store/use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],+"@tanstack/router-devtools-core/vite/picomatch": ["[email protected]", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],"@tanstack/router-devtools-core/vite/tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],@@ -9147,6 +9184,8 @@"@nivo/core/d3-time-format/d3-time/d3-array": ["[email protected]", "", { "dependencies": { "internmap": "^1.0.0" } }, "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ=="],+ "@nivo/sankey/@types/d3-sankey/@types/d3-shape/@types/d3-path": ["@types/[email protected]", "", {}, "sha512-4pQMp8ldf7UaB/gR8Fvvy69psNHkTpD/pVw3vmEi8iZAB9EPMBruB1JvHO4BIq9QkUUd2lV1F5YXpMNj7JPBpw=="],+"@node-minify/core/glob/path-scurry/lru-cache": ["[email protected]", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],"@node-minify/core/glob/path-scurry/minipass": ["[email protected]", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="],diff --git a/package.json b/package.jsonindex 248c63df0..733d8aea6 100644--- a/package.json+++ b/package.json@@ -36,7 +36,8 @@}},"patchedDependencies": {- "@polar-sh/[email protected]": "patches/@polar-sh__sdk.patch"+ "@polar-sh/[email protected]": "patches/@polar-sh__sdk.patch",+ "[email protected]": "patches/[email protected]"},"overrides": {"esm-env": "npm:esm-env-runtime@^0.1.0",diff --git a/packages/core/src/http/session.test.ts b/packages/core/src/http/session.test.tsindex 493f16303..82c33ed64 100644--- a/packages/core/src/http/session.test.ts+++ b/packages/core/src/http/session.test.ts@@ -1,6 +1,7 @@import { expect, test } from 'bun:test';import { stubAppDeps } from '../../test/http-fixtures';import { type AppDeps, createCtx } from '../context';+import { hashSessionToken } from '../modules/auth/src/token';import { resolveSession } from './session';const NO_HEADERS = new Headers();@@ -42,3 +43,24 @@ test('a failing session lookup propagates instead of signing the user out', asynresolveSession(ctx, cookieJar('some-token'), NO_HEADERS)).rejects.toThrow("Can't reach database server");});++test('with several session cookies the first that is signed in wins', async () => {+ const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);+ const user = { id: 'user_1', email: '[email protected]' };+ const liveId = hashSessionToken('live-token');+ const lookedUp: string[] = [];+ const ctx = ctxWithSessionLookup(((args: { where: { id: string } }) => {+ lookedUp.push(args.where.id);+ return Promise.resolve(+ args.where.id === liveId ? { id: liveId, expiresAt, user } : null+ );+ }) as () => Promise<unknown>);+ const headers = new Headers({+ cookie: `session=${encodeURIComponent('stale-token')}; other=1; session=${encodeURIComponent('live-token')}`,+ });++ const resolved = await resolveSession(ctx, cookieJar('stale-token'), headers);++ expect(resolved?.userId).toBe('user_1');+ expect(lookedUp).toEqual([hashSessionToken('stale-token'), liveId]);+});diff --git a/packages/core/src/http/session.ts b/packages/core/src/http/session.tsindex fefb869dd..3448f026f 100644--- a/packages/core/src/http/session.ts+++ b/packages/core/src/http/session.ts@@ -15,20 +15,58 @@ export const SESSION_COOKIE_NAME = 'session';/** ALS scope for the demo branch. */const DEMO_ALS_SESSION_ID = '1';+// A browser sends every `session` cookie whose domain covers the API host, and+// the parser keeps only the first. A stale one on a parent domain (another+// local setup, an old deploy) would then sign the user out, so each candidate+// gets a turn. One cookie, the common case, costs exactly what it did before.+function sessionTokens(cookies: CookieJar, headers: Headers): string[] {+ const header = headers.get('cookie');+ if (!header) {+ const token = cookies.get(SESSION_COOKIE_NAME);+ return token ? [token] : [];+ }+ const tokens = new Set<string>();+ for (const pair of header.split(';')) {+ const separator = pair.indexOf('=');+ if (separator === -1) {+ continue;+ }+ if (pair.slice(0, separator).trim() !== SESSION_COOKIE_NAME) {+ continue;+ }+ const value = pair.slice(separator + 1).trim();+ if (value) {+ tokens.add(decodeURIComponent(value));+ }+ }+ return [...tokens];+}+export async function resolveSession(ctx: Ctx,cookies: CookieJar,- _headers: Headers+ headers: Headers): Promise<Session | null> {- const token = cookies.get(SESSION_COOKIE_NAME);const auth = ctx.services.auth;+ const tokens = sessionTokens(cookies, headers);// No catch: decoding is a hash and cannot fail, so only the database throws.// Answering `null` would be a 401 and sign every user out during a blip; a// 500 makes the client retry.- const result = await runWithAlsSession(- token ? auth.decodeSessionToken(token) : DEMO_ALS_SESSION_ID,- () => auth.validateSessionToken(token ?? null)- );- return result.userId === null ? null : result;+ if (tokens.length === 0) {+ const result = await runWithAlsSession(DEMO_ALS_SESSION_ID, () =>+ auth.validateSessionToken(null)+ );+ return result.userId === null ? null : result;+ }++ for (const token of tokens) {+ const result = await runWithAlsSession(auth.decodeSessionToken(token), () =>+ auth.validateSessionToken(token)+ );+ if (result.userId !== null) {+ return result;+ }+ }+ return null;}diff --git a/packages/core/src/modules/report/report.rpc.ts b/packages/core/src/modules/report/report.rpc.tsindex dbfb2dfd4..fd5051d5d 100644--- a/packages/core/src/modules/report/report.rpc.ts+++ b/packages/core/src/modules/report/report.rpc.ts@@ -4,7 +4,11 @@// through `ctx.services.auth` is the only check that fires.import { z } from 'zod';-import { createTRPCRouter, protectedProcedure } from '../../rpc/base';+import {+ createTRPCRouter,+ protectedProcedure,+ type TrpcContext,+} from '../../rpc/base';import { TRPCNotFoundError } from '../../rpc/errors';import { zReport } from './report.constants';@@ -24,6 +28,27 @@ const zReportLayout = z.object({maxH: z.number().int().min(1).max(GRID_MAX_ROWS).optional(),});+// Project access only proves the caller owns `projectId`. Binding the+// caller-supplied `dashboardId` to that project as well is what stops a+// dashboard from another organization being rewritten through these handlers.+async function requireDashboardWrite(+ ctx: Pick<TrpcContext, 'services'> & { session: { userId: string } },+ { dashboardId, projectId }: { dashboardId: string; projectId: string }+) {+ await ctx.services.auth.requireProjectAccess({+ userId: ctx.session.userId,+ projectId,+ level: 'write',+ });+ const dashboard = await ctx.services.dashboard.getDashboardById(+ dashboardId,+ projectId+ );+ if (!dashboard) {+ throw new TRPCNotFoundError('Dashboard not found');+ }+}+export const reportRouter = createTRPCRouter({list: protectedProcedure.input(@@ -150,21 +175,19 @@ export const reportRouter = createTRPCRouter({return report;}),- updateLayout: protectedProcedure+ updateLayouts: protectedProcedure.input(z.object({- reportId: z.string(),- layout: zReportLayout,+ dashboardId: z.string(),+ projectId: z.string(),+ items: z+ .array(z.object({ reportId: z.string(), layout: zReportLayout }))+ .min(1),}))- .mutation(async ({ input: { reportId, layout }, ctx }) => {- const dbReport = await ctx.services.report.getReportByIdOrThrow(reportId);- await ctx.services.auth.requireProjectAccess({- userId: ctx.session.userId,- projectId: dbReport.projectId,- level: 'write',- });- return ctx.services.report.updateReportLayout({ reportId, layout });+ .mutation(async ({ input: { dashboardId, projectId, items }, ctx }) => {+ await requireDashboardWrite(ctx, { dashboardId, projectId });+ return ctx.services.report.updateReportLayouts({ dashboardId, items });}),resetLayout: protectedProcedure@@ -175,24 +198,7 @@ export const reportRouter = createTRPCRouter({})).mutation(async ({ input: { dashboardId, projectId }, ctx }) => {- await ctx.services.auth.requireProjectAccess({- userId: ctx.session.userId,- projectId,- level: 'write',- });-- // The access check above only proves the caller owns `projectId`. Bind- // the caller-supplied `dashboardId` to that project as well before- // deleting anything, otherwise a dashboard from another organization- // can be wiped through this handler.- const dashboard = await ctx.services.dashboard.getDashboardById(- dashboardId,- projectId- );- if (!dashboard) {- throw new TRPCNotFoundError('Dashboard not found');- }-+ await requireDashboardWrite(ctx, { dashboardId, projectId });return ctx.services.report.resetReportLayouts({dashboardId,projectId,diff --git a/packages/core/src/modules/report/report.service.test.ts b/packages/core/src/modules/report/report.service.test.tsindex 0cc1fe0ce..7c223311a 100644--- a/packages/core/src/modules/report/report.service.test.ts+++ b/packages/core/src/modules/report/report.service.test.ts@@ -1,11 +1,7 @@-/**- * Unit tests for the pure report helpers: mergeGlobalFilters, which combines- * report-level global filters with each event series' own filters (AND- * semantics), and transformFilter, which normalizes a saved filter.- */-import { describe, expect, it } from 'bun:test';+import { describe, expect, it, mock } from 'bun:test';+import type { ServiceDeps } from '../../services';import type { IChartEventFilter, IChartEventItem } from './report.constants';-import { transformFilter } from './report.service';+import { transformFilter, updateReportLayouts } from './report.service';import { mergeGlobalFilters } from './src/series';const globalFilter: IChartEventFilter = {@@ -110,3 +106,60 @@ describe('transformFilter', () => {});});});++describe('updateReportLayouts', () => {+ const layout = { x: 0, y: 0, w: 6, h: 4 };++ function stubDeps(reportIdsOnDashboard: string[]) {+ const upsert = mock((args: unknown) => args);+ const transaction = mock(async (writes: unknown[]) => writes);+ const findMany = mock(async () =>+ reportIdsOnDashboard.map((id) => ({ id }))+ );+ const deps = {+ db: {+ report: { findMany },+ reportLayout: { upsert },+ $transaction: transaction,+ },+ } as unknown as ServiceDeps;+ return { deps, upsert, transaction, findMany };+ }++ it('writes every tile in one transaction', async () => {+ const { deps, upsert, transaction } = stubDeps(['r1', 'r2']);+ await updateReportLayouts(deps, {+ dashboardId: 'd1',+ items: [+ { reportId: 'r1', layout },+ { reportId: 'r2', layout: { ...layout, x: 6 } },+ ],+ });+ expect(transaction).toHaveBeenCalledTimes(1);+ expect(upsert).toHaveBeenCalledTimes(2);+ expect(upsert).toHaveBeenCalledWith({+ where: { reportId: 'r2' },+ create: { reportId: 'r2', ...layout, x: 6 },+ update: { ...layout, x: 6 },+ });+ });++ it('refuses the whole batch when a report is on another dashboard', async () => {+ const { deps, upsert, transaction, findMany } = stubDeps(['r1']);+ await expect(+ updateReportLayouts(deps, {+ dashboardId: 'd1',+ items: [+ { reportId: 'r1', layout },+ { reportId: 'r_other', layout },+ ],+ })+ ).rejects.toThrow('r_other');+ expect(findMany).toHaveBeenCalledWith({+ where: { id: { in: ['r1', 'r_other'] }, dashboardId: 'd1' },+ select: { id: true },+ });+ expect(transaction).not.toHaveBeenCalled();+ expect(upsert).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/modules/report/report.service.ts b/packages/core/src/modules/report/report.service.tsindex 22ef73b14..533ae89e0 100644--- a/packages/core/src/modules/report/report.service.ts+++ b/packages/core/src/modules/report/report.service.ts@@ -389,26 +389,36 @@ interface ReportLayoutInput {maxH?: number;}-export async function updateReportLayout(+export async function updateReportLayouts(deps: ServiceDeps,input: {- reportId: string;- layout: ReportLayoutInput;+ dashboardId: string;+ items: { reportId: string; layout: ReportLayoutInput }[];}) {const db = deps.db;- const { reportId, layout } = input;-- return db.reportLayout.upsert({- where: {- reportId,- },- create: {- reportId,- ...layout,- },- update: layout,+ const reportIds = input.items.map((item) => item.reportId);+ const reportsOnDashboard = await db.report.findMany({+ where: { id: { in: reportIds }, dashboardId: input.dashboardId },+ select: { id: true },});+ const knownIds = new Set(reportsOnDashboard.map((report) => report.id));+ const foreignIds = reportIds.filter((id) => !knownIds.has(id));+ if (foreignIds.length > 0) {+ throw new TRPCBadRequestError(+ `Reports do not belong to this dashboard: ${foreignIds.join(', ')}`+ );+ }++ return db.$transaction(+ input.items.map(({ reportId, layout }) =>+ db.reportLayout.upsert({+ where: { reportId },+ create: { reportId, ...layout },+ update: layout,+ })+ )+ );}export async function getReportLayouts(@@ -489,9 +499,10 @@ export function createReportService(deleteReport(deps, reportId),duplicateReport: (report: DbReport): ReturnType<typeof duplicateReport> =>duplicateReport(deps, report),- updateReportLayout: (- input: Parameters<typeof updateReportLayout>[1]- ): ReturnType<typeof updateReportLayout> => updateReportLayout(deps, input),+ updateReportLayouts: (+ input: Parameters<typeof updateReportLayouts>[1]+ ): ReturnType<typeof updateReportLayouts> =>+ updateReportLayouts(deps, input),getReportLayouts: (input: Parameters<typeof getReportLayouts>[1]): ReturnType<typeof getReportLayouts> => getReportLayouts(deps, input),diff --git a/patches/[email protected] b/patches/[email protected]new file mode 100644index 000000000..ca01a2a39--- /dev/null+++ b/patches/[email protected]@@ -0,0 +1,59 @@+diff --git a/node_modules/react-grid-layout/.bun-tag-b2fa34526007af71 b/.bun-tag-b2fa34526007af71+new file mode 100644+index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391+diff --git a/dist/chunk-CUP5Y2ZG.js b/dist/chunk-CUP5Y2ZG.js+index 23399caefebeefb2038279331382aa20e5932bc1..753d04df620086ae0462080d48ca1f8af906c7d8 100644+--- a/dist/chunk-CUP5Y2ZG.js++++ b/dist/chunk-CUP5Y2ZG.js+@@ -124,6 +124,7 @@ function GridItemInner(props) {+ onResizeStop: onResizeStopProp+ } = props;+ const [dragging, setDragging] = React2.useState(false);++ const [, bumpFrame] = React2.useState(0);+ const [resizing, setResizing] = React2.useState(false);+ const elementRef = React2.useRef(null);+ const dragPositionRef = React2.useRef({ left: 0, top: 0 });+@@ -334,6 +335,7 @@ function GridItemInner(props) {+ }+ const newPosition = { top, left };+ dragPositionRef.current = newPosition;++ bumpFrame((frame) => frame + 1);+ const rawPos = chunkVJJIA3HC_js.calcXYRaw(positionParams, top, left);+ const { x: newX, y: newY } = chunkQAIA5KAO_js.applyPositionConstraints(+ constraints,+@@ -430,6 +432,7 @@ function GridItemInner(props) {+ };+ }+ resizePositionRef.current = updatedSize;++ bumpFrame((frame) => frame + 1);+ const containerHeight = node?.offsetParent?.clientHeight ?? 0;+ const rawSize = chunkVJJIA3HC_js.calcWHRaw(+ positionParams,+diff --git a/dist/chunk-Z6CWRR74.mjs b/dist/chunk-Z6CWRR74.mjs+index 5d3ee00ad7b14cfe15445fcf7bfdbee04408236e..5659a9713ad4b8d5ab096fa7359d55aae4fa8d46 100644+--- a/dist/chunk-Z6CWRR74.mjs++++ b/dist/chunk-Z6CWRR74.mjs+@@ -117,6 +117,7 @@ function GridItemInner(props) {+ onResizeStop: onResizeStopProp+ } = props;+ const [dragging, setDragging] = useState(false);++ const [, bumpFrame] = useState(0);+ const [resizing, setResizing] = useState(false);+ const elementRef = useRef(null);+ const dragPositionRef = useRef({ left: 0, top: 0 });+@@ -327,6 +328,7 @@ function GridItemInner(props) {+ }+ const newPosition = { top, left };+ dragPositionRef.current = newPosition;++ bumpFrame((frame) => frame + 1);+ const rawPos = calcXYRaw(positionParams, top, left);+ const { x: newX, y: newY } = applyPositionConstraints(+ constraints,+@@ -423,6 +425,7 @@ function GridItemInner(props) {+ };+ }+ resizePositionRef.current = updatedSize;++ bumpFrame((frame) => frame + 1);+ const containerHeight = node?.offsetParent?.clientHeight ?? 0;+ const rawSize = calcWHRaw(+ positionParams,diff --git a/tooling/release/src/decide.test.ts b/tooling/release/src/decide.test.tsindex a7cdf1c9e..c82c9c666 100644--- a/tooling/release/src/decide.test.ts+++ b/tooling/release/src/decide.test.ts@@ -5,7 +5,25 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { decide } from './next-version';+// A git hook (pre-push runs this suite) exports GIT_DIR and friends, which win+// over `cwd`: this suite once committed, tagged and set user/core.bare on the+// real repository. Every git call here, and in the code under test, is pinned+// to the scratch repository instead.+for (const key of Object.keys(process.env)) {+ if (key.startsWith('GIT_')) {+ delete process.env[key];+ }+}+const repo = mkdtempSync(join(tmpdir(), 'op-release-'));+if (!repo.startsWith(tmpdir())) {+ throw new Error(`refusing to run git outside the temp dir: ${repo}`);+}+process.env.GIT_DIR = join(repo, '.git');+process.env.GIT_WORK_TREE = repo;+process.env.GIT_CONFIG_NOSYSTEM = '1';+process.env.GIT_CONFIG_GLOBAL = '/dev/null';+const run = (...args: string[]) =>execFileSync('git', args, { cwd: repo, encoding: 'utf8' }).trim();const commit = (message: string) => {