@acronis-platform/ui-react 5.5.1 → 5.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/ui/area-chart/area-chart.js +117 -113
- package/dist/components/ui/area-chart/area-chart.js.map +1 -1
- package/dist/components/ui/bar-chart/bar-chart.js +133 -131
- package/dist/components/ui/bar-chart/bar-chart.js.map +1 -1
- package/dist/components/ui/chart/chart.js +91 -48
- package/dist/components/ui/chart/chart.js.map +1 -1
- package/dist/components/ui/composed-chart/composed-chart.js +138 -136
- package/dist/components/ui/composed-chart/composed-chart.js.map +1 -1
- package/dist/components/ui/confidence-cone/confidence-cone.js +55 -54
- package/dist/components/ui/confidence-cone/confidence-cone.js.map +1 -1
- package/dist/components/ui/funnel-chart/funnel-chart.js +24 -23
- package/dist/components/ui/funnel-chart/funnel-chart.js.map +1 -1
- package/dist/components/ui/line-chart/line-chart.js +57 -53
- package/dist/components/ui/line-chart/line-chart.js.map +1 -1
- package/dist/components/ui/pie-chart/pie-chart.js +29 -28
- package/dist/components/ui/pie-chart/pie-chart.js.map +1 -1
- package/dist/components/ui/radar-chart/radar-chart.js +74 -73
- package/dist/components/ui/radar-chart/radar-chart.js.map +1 -1
- package/dist/components/ui/radial-bar-chart/radial-bar-chart.js +46 -45
- package/dist/components/ui/radial-bar-chart/radial-bar-chart.js.map +1 -1
- package/dist/components/ui/scatter-chart/scatter-chart.js +29 -26
- package/dist/components/ui/scatter-chart/scatter-chart.js.map +1 -1
- package/dist/components/ui/treemap/treemap.js +22 -21
- package/dist/components/ui/treemap/treemap.js.map +1 -1
- package/dist/llms/area-chart.md +1 -0
- package/dist/llms/bar-chart.md +1 -0
- package/dist/llms/chart.md +21 -0
- package/dist/llms/composed-chart.md +1 -0
- package/dist/llms/confidence-cone.md +1 -0
- package/dist/llms/funnel-chart.md +1 -0
- package/dist/llms/line-chart.md +1 -0
- package/dist/llms/pie-chart.md +1 -0
- package/dist/llms/radar-chart.md +1 -0
- package/dist/llms/radial-bar-chart.md +1 -0
- package/dist/llms/scatter-chart.md +1 -0
- package/dist/llms/treemap.md +1 -0
- package/dist/llms.txt +1 -1
- package/dist/src/components/ui/area-chart/area-chart.d.ts +2 -2
- package/dist/src/components/ui/bar-chart/bar-chart.d.ts +4 -3
- package/dist/src/components/ui/chart/chart.d.ts +15 -5
- package/dist/src/components/ui/chart/index.d.ts +1 -1
- package/dist/src/components/ui/composed-chart/composed-chart.d.ts +2 -2
- package/dist/src/components/ui/confidence-cone/confidence-cone.d.ts +2 -2
- package/dist/src/components/ui/funnel-chart/funnel-chart.d.ts +2 -2
- package/dist/src/components/ui/line-chart/line-chart.d.ts +2 -2
- package/dist/src/components/ui/pie-chart/pie-chart.d.ts +2 -2
- package/dist/src/components/ui/radar-chart/radar-chart.d.ts +2 -2
- package/dist/src/components/ui/radial-bar-chart/radial-bar-chart.d.ts +2 -2
- package/dist/src/components/ui/scatter-chart/scatter-chart.d.ts +2 -2
- package/dist/src/components/ui/treemap/treemap.d.ts +2 -2
- package/dist/ui-react.css +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"confidence-cone.js","names":[],"sources":["../../../../src/components/ui/confidence-cone/confidence-cone.tsx"],"sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport {\n Area,\n CartesianGrid,\n ComposedChart,\n Line,\n ReferenceArea,\n ReferenceLine,\n Text,\n XAxis,\n YAxis,\n} from 'recharts';\n\nimport { cn } from '@/lib/utils';\nimport {\n ChartContainer,\n ChartLegend,\n ChartLegendContent,\n ChartTooltip,\n ChartTooltipContent,\n resolveAxisDomain,\n resolveAnimation,\n resolveRotatedTickAnchor,\n resolveXAxisTitle,\n resolveYAxisTitle,\n CHART_LABEL_FONT_SIZE,\n type ChartConfig,\n type ChartLegendFontSize,\n type ChartPalette,\n type ChartLegendContentProps,\n type ChartTooltipContentProps,\n toCssKey,\n type CartesianChartProps,\n type ChartAnimationProps,\n} from '../chart';\nimport {\n mergeXAxisLayoutMargin,\n useXAxisLayout,\n} from '../chart/use-x-axis-layout';\nimport { resolveXAxisTickLabels } from '../chart/chart-format';\n\n// A forecast confidence-cone: a solid line over the known/actual period, a\n// dashed line over the forecast period, and a shaded band (the \"cone\") between\n// a lower and upper bound that typically widens with the horizon — visualizing\n// growing uncertainty. Built on the shared Chart primitives; no new tokens\n// (series colors are caller-supplied via `config`). The whole metric renders in\n// one hue — actual and forecast differ by line style, not color — so the cone\n// band and the forecast line both reuse the actual series' color.\n\n// Each series' band is a synthetic `[lower, upper]` range field per row that a\n// recharts <Area> shades; kept out of the tooltip/legend (see the filters\n// below). One band per series, so the key carries the series' actual key — the\n// whole `__cone` prefix is reserved.\nconst BAND_PREFIX = '__cone';\nconst bandKeyFor = (actualKey: string) => `${BAND_PREFIX}:${actualKey}`;\n\n/**\n * Drop every synthetic cone-band range series from a recharts tooltip/legend\n * payload, keeping the real actual/forecast series (and their order). Applied to\n * both the default tooltip and any caller-supplied `tooltipContent`, so no band\n * surfaces regardless of which path renders or how many series are plotted.\n */\nexport function dropConeBand<T extends { dataKey?: unknown }>(\n payload: readonly T[] | undefined\n): T[] | undefined {\n return payload?.filter(\n (item) =>\n !(\n typeof item.dataKey === 'string' && item.dataKey.startsWith(BAND_PREFIX)\n )\n );\n}\n\n/**\n * Reduce a legend payload to the metrics the chart plots — one entry per series.\n * A series' actual, forecast and cone are three recharts series painting a\n * single metric in a single hue, so the legend names each metric once, with its\n * actual series' swatch, instead of listing line styles as separate series.\n */\nexport function keepMetricSeries<T extends { dataKey?: unknown }>(\n payload: readonly T[] | undefined,\n actualKeys: readonly string[]\n): T[] | undefined {\n return payload?.filter(\n (item) =>\n typeof item.dataKey === 'string' && actualKeys.includes(item.dataKey)\n );\n}\n\n/**\n * Wrap a caller-supplied `tooltipContent` so the synthetic cone band is stripped\n * from the payload before it renders, while preserving recharts' own mount\n * semantics — a function is mounted via `createElement` (its own component\n * identity + hook state), an element via `cloneElement`. This mirrors what the\n * pass-through charts get by handing `content` straight to recharts, so a\n * function-form tooltip keeps its state across re-renders here too. The returned\n * component is a stable content type (memoize it on `tooltipContent`).\n */\ntype TooltipContentType = NonNullable<\n React.ComponentProps<typeof ChartTooltip>['content']\n>;\ntype TooltipContentFn = Extract<\n TooltipContentType,\n (...args: never[]) => unknown\n>;\ntype TooltipRenderProps = Parameters<TooltipContentFn>[0];\n\nexport function createConeTooltip(tooltipContent: TooltipContentType) {\n return function ConeTooltip(props: TooltipRenderProps) {\n const merged = {\n ...props,\n payload: dropConeBand(props.payload),\n } as TooltipRenderProps;\n return typeof tooltipContent === 'function'\n ? React.createElement(\n tooltipContent as React.FunctionComponent<TooltipRenderProps>,\n merged\n )\n : React.cloneElement(tooltipContent, merged);\n };\n}\n\n/**\n * One plotted metric: its actual / forecast columns and, optionally, the two\n * bound columns that shade its cone. Omit `lowerKey`/`upperKey` for a band-less\n * metric — a solid line handing off to a bare dashed projection.\n */\nexport interface ConfidenceConeSeries {\n /** Field for the known/actual values — drawn as a solid line with a filled area. */\n actualKey: string;\n /** Field for the projected values — drawn as a dashed line. */\n forecastKey: string;\n /** Field for the cone's lower bound. Omit (with `upperKey`) for no cone. */\n lowerKey?: string;\n /** Field for the cone's upper bound. Omit (with `lowerKey`) for no cone. */\n upperKey?: string;\n}\n\n/**\n * The x values of the projected period — every row carrying a forecast value for\n * at least one series, in data order. The first is the hand-off point (where the\n * shaded region and divider start); the whole set drives the forecast tick\n * styling, matched by value so tick `interval` can't skew it the way a tick\n * index would. Exported for unit tests; not part of the package's public API.\n */\nexport function forecastPeriodX(\n data: ReadonlyArray<Record<string, string | number | null | undefined>>,\n series: readonly ConfidenceConeSeries[],\n xKey: string\n): Array<string | number | null | undefined> {\n return data\n .filter((row) =>\n series.some(({ forecastKey }) => typeof row[forecastKey] === 'number')\n )\n .map((row) => row[xKey]);\n}\n\n/**\n * Build the X-axis tick renderer that sets the projected columns apart: italic,\n * in the metric's hue. Styled inline rather than through the `fill` attribute\n * recharts hands every tick, so the accent survives the class-based tick color\n * a chart theme may apply. A custom tick owns its own text, so the caller's\n * `xTickFormatter` is applied here — recharts only applies it to default ticks.\n * Exported for unit tests; not part of the package's public API.\n */\nexport function createForecastTick(\n forecastX: ReadonlySet<string | number | null | undefined>,\n color: string,\n tickFormatter?: CartesianChartProps['xTickFormatter']\n) {\n return function ForecastTick({\n payload,\n index,\n ...tickProps\n }: {\n payload?: { value?: string | number };\n index?: number;\n }) {\n const value = payload?.value;\n return (\n <Text\n {...tickProps}\n style={\n value != null && forecastX.has(value)\n ? { fontStyle: 'italic', fill: color }\n : undefined\n }\n >\n {tickFormatter && value != null ? tickFormatter(value, index) : value}\n </Text>\n );\n };\n}\n\n/** A dashed horizontal threshold on the value axis. */\nexport interface ConfidenceConeReferenceLine {\n /** Position on the value (Y) axis. */\n value: number;\n /** Optional caption rendered at the line's right end. */\n label?: string;\n}\n\n/**\n * Every prop except the one-form-or-the-other requirement `ConfidenceConeProps`\n * layers on below. Exported so the stories can type their `Meta` on a single\n * object shape — Storybook can't split a union's required args between `meta.args`\n * and a story's. Not re-exported from `index.ts`; not part of the public API.\n */\nexport interface ConfidenceConeBaseProps\n extends\n Omit<React.ComponentProps<'div'>, 'children'>,\n CartesianChartProps,\n ChartAnimationProps {\n /**\n * The dataviz palette this chart's series are painted from. Series that\n * state no `color` of their own take a stop of it. See `ChartPalette`.\n */\n palette?: ChartPalette;\n /**\n * Row-per-point data — the shared x dimension plus each series' actual /\n * forecast / bound fields. Rows are naturally sparse (a point has either an\n * actual or a forecast + bounds), so missing fields are allowed. Avoid fields\n * starting with `__cone` — that prefix is reserved for the internal\n * prediction-band series.\n */\n data: ReadonlyArray<Record<string, string | number | null | undefined>>;\n /**\n * Per-series map of `label` / `icon` / `tone` for the actual + forecast lines\n * (imported from the shared `Chart` primitives). Series take their colour from\n * the container's `palette`; each entry maps a key to a `label` and an optional\n * `tone`. Each metric renders in one hue: its cone band and forecast line both\n * reuse its actual series' color — actual and forecast differ by line style,\n * not hue.\n */\n config: ChartConfig;\n /** Category / time axis key (the shared dimension across rows). */\n xKey: string;\n /**\n * Plot several metrics against one shared axis — each with its own actual /\n * forecast / bound fields and its own hue (from `config[actualKey]`). Takes\n * precedence over the single-series `actualKey`/`forecastKey`/`lowerKey`/\n * `upperKey` shorthand below; pass one form or the other, not both. One of the\n * two forms is required.\n */\n series?: readonly ConfidenceConeSeries[];\n /**\n * Single-series shorthand — field for the known/actual values, drawn as a\n * solid line with a filled area. Required (with `forecastKey`) unless `series`\n * is set, which supersedes it.\n */\n actualKey?: string;\n /**\n * Single-series shorthand — field for the projected values, drawn as a dashed\n * line. Required (with `actualKey`) unless `series` is set, which supersedes\n * it.\n */\n forecastKey?: string;\n /** Field for the cone's lower bound. Omit (with `upperKey`) for no cone. */\n lowerKey?: string;\n /** Field for the cone's upper bound. Omit (with `lowerKey`) for no cone. */\n upperKey?: string;\n /**\n * How the known/actual period is drawn: a filled `area` under the line (the\n * default), or a bare `line` — for a chart where the cone is the only shaded\n * region, or where several metrics' fills would muddy each other.\n */\n actualType?: 'area' | 'line';\n /** Stroke width of the actual + forecast lines. */\n strokeWidth?: number;\n /**\n * Mark each data point: a filled dot on the observed values, a hollow one on\n * the projection — so a point reads as measured or predicted at a glance.\n */\n showDots?: boolean;\n /**\n * Italicize the X-axis ticks over the forecast period and paint them in the\n * first series' hue, so the projected columns read as projected even when the\n * shaded region is off.\n */\n styleForecastTicks?: boolean;\n /**\n * One or more dashed horizontal thresholds on the value axis — e.g. a target\n * or a capacity limit. Pass a single object or an array to draw several.\n */\n referenceLine?: ConfidenceConeReferenceLine | ConfidenceConeReferenceLine[];\n /**\n * Set off the forecast period from the actuals with a dashed divider at the\n * hand-off point (the first row with a forecast value) and a subtle shaded\n * band over the forecast region.\n */\n showForecastRegion?: boolean;\n showLegend?: boolean;\n /**\n * Font size of the legend text. Defaults to `'xs'` — the size the legend has\n * always rendered at. See `ChartLegendFontSize`.\n */\n legendFontSize?: ChartLegendFontSize;\n}\n\n/**\n * Which columns to plot has to be spelled out one way or the other: the `series`\n * array, or the flat `actualKey` + `forecastKey` shorthand. Expressed as a union\n * so a chart with neither is a compile error rather than a silent plot of axes\n * and nothing else. Both forms together stay legal — `series` wins (see\n * `plotted`), which is what the multi-series stories rely on to clear the args\n * table.\n */\nexport type ConfidenceConeProps = ConfidenceConeBaseProps &\n (\n | { series: readonly ConfidenceConeSeries[] }\n | { actualKey: string; forecastKey: string }\n );\n\nconst ConfidenceCone = React.forwardRef<HTMLDivElement, ConfidenceConeProps>(\n (\n {\n className,\n config,\n palette,\n data,\n xKey,\n series,\n actualKey,\n forecastKey,\n lowerKey,\n upperKey,\n xAxisLabel,\n yAxisLabel,\n yUnit,\n actualType = 'area',\n strokeWidth = 2,\n showDots = false,\n styleForecastTicks = false,\n referenceLine,\n showForecastRegion = true,\n showGrid = true,\n showTooltip = true,\n showLegend = true,\n legendFontSize,\n showXAxis = true,\n showYAxis = true,\n xTickFormatter,\n yTickFormatter,\n xAxisAngle,\n xAxisInterval,\n yAxisTickCount,\n yAxisDomain,\n gridDashed,\n gridHorizontal,\n gridVertical,\n tooltipContent,\n animate,\n animationDuration,\n animationBegin,\n animationEasing,\n ...props\n },\n ref\n ) => {\n // The flat *Key props are the single-series shorthand for `series`.\n const plotted = React.useMemo<readonly ConfidenceConeSeries[]>(() => {\n if (series?.length) return series;\n if (!actualKey || !forecastKey) return [];\n return [{ actualKey, forecastKey, lowerKey, upperKey }];\n }, [series, actualKey, forecastKey, lowerKey, upperKey]);\n\n const animation = resolveAnimation({\n animate,\n animationDuration,\n animationBegin,\n animationEasing,\n });\n // Memoized so recharts sees a stable content type across renders — a fresh\n // wrapper each render would remount the caller's tooltip and reset its state.\n const customTooltip = React.useMemo(\n () => (tooltipContent ? createConeTooltip(tooltipContent) : undefined),\n [tooltipContent]\n );\n\n const xAxisTitle = resolveXAxisTitle(xAxisLabel);\n const yAxisTitle = resolveYAxisTitle(yAxisLabel);\n\n const yDomain = resolveAxisDomain(yAxisDomain);\n\n // One hue per metric. Each cone and forecast line already paints with its own\n // series' actual color; re-pointing that series' forecast key's `--color-*`\n // at it too means nothing downstream — a custom tooltip, a caller's\n // `var(--color-<forecastKey>)` — can reintroduce a second color.\n const seriesConfig = React.useMemo(() => {\n let next: ChartConfig | undefined;\n for (const { actualKey: aKey, forecastKey: fKey } of plotted) {\n const actual = config[aKey];\n const forecast = config[fKey];\n if (!actual || !forecast) continue;\n next ??= { ...config };\n next[fKey] = {\n label: forecast.label,\n icon: forecast.icon,\n tone: { sameAs: aKey },\n };\n }\n return next ?? config;\n }, [config, plotted]);\n\n const xAxisTickLabels = resolveXAxisTickLabels(\n data.map((row) => row[xKey]),\n xTickFormatter\n );\n const chartContainerRef = React.useRef<HTMLDivElement>(null);\n const xAxisLayout = useXAxisLayout(\n chartContainerRef,\n xAxisAngle,\n xAxisLabel,\n xAxisTickLabels.join('\\u0000')\n );\n\n // Augment each row with one `[lower, upper]` band tuple per coned series for\n // its Area to shade. Rows missing a numeric bound are left un-coned (the\n // band breaks there); a series without bounds gets no band at all.\n const chartData = data.map((row) => {\n const next: Record<string, unknown> = { ...row };\n for (const {\n actualKey: aKey,\n lowerKey: lKey,\n upperKey: uKey,\n } of plotted) {\n if (!lKey || !uKey) continue;\n const lower = row[lKey];\n const upper = row[uKey];\n next[bandKeyFor(aKey)] =\n typeof lower === 'number' && typeof upper === 'number'\n ? [lower, upper]\n : undefined;\n }\n return next;\n });\n\n const forecastX = forecastPeriodX(data, plotted, xKey);\n // Set the projected period off from the actuals with a shaded band + a\n // divider at the hand-off.\n const forecastStart = showForecastRegion ? forecastX[0] : undefined;\n const lastX = data[data.length - 1]?.[xKey];\n\n const renderForecastTick = createForecastTick(\n new Set(forecastX),\n `var(--color-${toCssKey(plotted[0]?.actualKey ?? '')})`,\n xTickFormatter\n );\n\n const referenceLines = referenceLine\n ? Array.isArray(referenceLine)\n ? referenceLine\n : [referenceLine]\n : [];\n\n // Everything from here to the `return` is lifted out of the returned tree\n // only to keep it readable as a flat list of chart children. Nothing in\n // recharts forces the `render*` helpers to be plain functions: axes and\n // series register themselves with the chart's store, and `<Cell>` is the\n // only child still looked up by element type — a component wrapper renders\n // fine (see AreaChart's `AreaFillGradients`). They stay functions because\n // they are declared inside the render body, where a component would get a\n // fresh element type on every render and remount its subtree.\n\n const renderAxes = () => (\n <>\n <XAxis\n dataKey={xKey}\n type=\"category\"\n hide={!showXAxis}\n tickLine={false}\n axisLine={false}\n tickMargin={8}\n tickFormatter={xTickFormatter}\n tick={styleForecastTicks ? renderForecastTick : undefined}\n angle={xAxisAngle}\n interval={xAxisInterval}\n textAnchor={resolveRotatedTickAnchor(xAxisAngle)}\n height={xAxisLayout.height}\n label={xAxisTitle}\n />\n <YAxis\n type=\"number\"\n hide={!showYAxis}\n tickLine={false}\n axisLine={false}\n unit={yUnit}\n tickFormatter={yTickFormatter}\n tickCount={yAxisTickCount}\n domain={yDomain}\n width={yAxisLabel ? 72 : undefined}\n label={yAxisTitle}\n />\n </>\n );\n\n // Set the forecast region off from the actuals (behind everything).\n const renderForecastRegion = () => (\n <>\n {forecastStart != null && lastX != null && (\n <ReferenceArea\n x1={forecastStart}\n x2={lastX}\n fill=\"var(--ui-background-surface-secondary)\"\n fillOpacity={0.5}\n ifOverflow=\"extendDomain\"\n />\n )}\n {forecastStart != null && (\n <ReferenceLine\n x={forecastStart}\n stroke=\"var(--ui-border-on-surface-border)\"\n strokeDasharray=\"4 4\"\n />\n )}\n </>\n );\n\n const renderThreshold = (\n threshold: ConfidenceConeReferenceLine,\n index: number\n ) => (\n <ReferenceLine\n key={`${threshold.label ?? 'threshold'}-${index}`}\n y={threshold.value}\n stroke=\"var(--ui-text-on-surface-secondary)\"\n strokeDasharray=\"4 4\"\n // extendDomain so a threshold beyond the data max stays visible.\n ifOverflow=\"extendDomain\"\n label={\n threshold.label\n ? {\n value: threshold.label,\n position: 'insideTopRight',\n fill: 'var(--ui-text-on-surface-secondary)',\n fontSize: CHART_LABEL_FONT_SIZE,\n }\n : undefined\n }\n />\n );\n\n const renderTooltip = () =>\n customTooltip ? (\n // Strips the synthetic band before the caller's tooltip sees it — the\n // `__cone` series feeds the Area, not the tooltip.\n <ChartTooltip content={customTooltip} />\n ) : (\n <ChartTooltip\n content={(tp) => (\n <ChartTooltipContent\n active={tp.active}\n label={tp.label}\n // The synthetic band feeds the Area, not the tooltip.\n payload={\n dropConeBand(tp.payload) as ChartTooltipContentProps['payload']\n }\n />\n )}\n />\n );\n\n const renderLegend = () => (\n <ChartLegend\n content={(lp) => (\n <ChartLegendContent\n verticalAlign={lp.verticalAlign}\n fontSize={legendFontSize}\n payload={\n keepMetricSeries(\n lp.payload,\n plotted.map((s) => s.actualKey)\n ) as ChartLegendContentProps['payload']\n }\n />\n )}\n />\n );\n\n // One color per metric — actual and forecast differ by line style, not hue\n // — so a cone reuses its series' actual color.\n const renderConeBand = ({\n actualKey: aKey,\n lowerKey: lKey,\n upperKey: uKey,\n }: ConfidenceConeSeries) =>\n lKey && uKey ? (\n <Area\n key={bandKeyFor(aKey)}\n // The band paints in the same hue, at the same opacity, as the\n // actual series' own area, so nothing on the rendered path tells\n // the two apart. recharts forwards `data-*` onto the path it\n // draws; the tests select the band through this.\n data-slot=\"confidence-cone-band\"\n dataKey={bandKeyFor(aKey)}\n type=\"monotone\"\n stroke=\"none\"\n fill={`var(--color-${toCssKey(aKey)})`}\n fillOpacity={0.15}\n connectNulls={false}\n dot={false}\n activeDot={false}\n {...animation}\n legendType=\"none\"\n tooltipType=\"none\"\n />\n ) : null;\n\n const renderActualMark = ({ actualKey: aKey }: ConfidenceConeSeries) => {\n // An area and a line take the same props here; only the region under the\n // curve (and the mark recharts draws) differ. A `Line` gets no fill at\n // all — `fillOpacity: 0` would also erase its dots.\n const ActualMark = actualType === 'line' ? Line : Area;\n const areaFill =\n actualType === 'line'\n ? undefined\n : { fill: `var(--color-${toCssKey(aKey)})`, fillOpacity: 0.15 };\n // Observed points read as measured: LineChart's dot geometry (r 3, 2px\n // ring) filled with the metric hue. The ring is that same hue, so the\n // mark is solid — and wide enough against the 2px line not to read as a\n // mere thickening of it. `fillOpacity: 1` is load-bearing: recharts\n // merges the parent mark's own presentation props into every dot it\n // draws, so an `<Area>`'s 0.15 would otherwise wash the dot out to a halo.\n const dot = showDots\n ? {\n r: 3,\n fill: `var(--color-${toCssKey(aKey)})`,\n fillOpacity: 1,\n stroke: `var(--color-${toCssKey(aKey)})`,\n strokeWidth: 2,\n }\n : false;\n return (\n <ActualMark\n key={aKey}\n dataKey={aKey}\n type=\"monotone\"\n stroke={`var(--color-${toCssKey(aKey)})`}\n strokeWidth={strokeWidth}\n {...areaFill}\n dot={dot}\n activeDot={showDots ? { r: 5 } : false}\n connectNulls\n {...animation}\n // The legend names the metric once, so it carries the swatch that\n // stands for the whole series rather than the actual line's style.\n legendType=\"rect\"\n />\n );\n };\n\n const renderForecastLine = ({\n actualKey: aKey,\n forecastKey: fKey,\n }: ConfidenceConeSeries) => {\n // Projected points read as predicted: the same LineChart dot, inverted —\n // the metric's hue as the ring, the surface color as the fill, so the\n // dashed line doesn't show through the middle. (LineChart leaves the fill\n // to recharts, whose `Line` defaults it to `#fff`; the token is that same\n // white in the light theme and also holds up in the dark one.)\n // `strokeDasharray: 'none'` is load-bearing: recharts merges the parent\n // mark's presentation props into every dot, so this line's `5 5` would\n // otherwise break each dot's ring into two arcs.\n const dot = showDots\n ? {\n r: 3,\n fill: 'var(--ui-background-surface-primary)',\n stroke: `var(--color-${toCssKey(aKey)})`,\n strokeWidth: 2,\n strokeDasharray: 'none',\n }\n : false;\n return (\n <Line\n key={fKey}\n dataKey={fKey}\n type=\"monotone\"\n stroke={`var(--color-${toCssKey(aKey)})`}\n strokeWidth={strokeWidth}\n strokeDasharray=\"5 5\"\n dot={dot}\n // Paired with `dot` the way every other chart does it — left unset,\n // the projection would keep recharts' default active dot while the\n // actuals had none (and a different radius when on).\n activeDot={showDots ? { r: 5 } : false}\n connectNulls\n {...animation}\n />\n );\n };\n\n return (\n <div ref={ref} className={cn(className)} {...props}>\n <ChartContainer\n ref={chartContainerRef}\n config={seriesConfig}\n palette={palette}\n className=\"size-full [&_.recharts-label]:fill-foreground\"\n >\n <ComposedChart\n data={chartData as readonly unknown[]}\n margin={mergeXAxisLayoutMargin(undefined, xAxisLayout.margin)}\n >\n {showGrid && (\n <CartesianGrid\n horizontal={gridHorizontal ?? true}\n vertical={gridVertical ?? false}\n strokeDasharray={gridDashed ? '3 3' : undefined}\n />\n )}\n {renderAxes()}\n {renderForecastRegion()}\n {referenceLines.map(renderThreshold)}\n {showTooltip && renderTooltip()}\n {showLegend && renderLegend()}\n {/* Every cone renders before any line, so the lines draw on top of\n all of them. */}\n {plotted.map(renderConeBand)}\n {plotted.map(renderActualMark)}\n {plotted.map(renderForecastLine)}\n </ComposedChart>\n </ChartContainer>\n </div>\n );\n }\n);\nConfidenceCone.displayName = 'ConfidenceCone';\n\nexport { ConfidenceCone };\n"],"mappings":";;;;;;;;;AAuDA,IAAM,IAAc,UACd,KAAc,MAAsB,GAAG,EAAY,GAAG;AAQ5D,SAAgB,EACd,GACiB;CACjB,OAAO,GAAS,QACb,MACC,EACE,OAAO,EAAK,WAAY,YAAY,EAAK,QAAQ,WAAW,CAAW,EAE7E;AACF;AAQA,SAAgB,EACd,GACA,GACiB;CACjB,OAAO,GAAS,QACb,MACC,OAAO,EAAK,WAAY,YAAY,EAAW,SAAS,EAAK,OAAO,CACxE;AACF;AAoBA,SAAgB,EAAkB,GAAoC;CACpE,OAAO,SAAqB,GAA2B;EACrD,IAAM,IAAS;GACb,GAAG;GACH,SAAS,EAAa,EAAM,OAAO;EACrC;EACA,OAAO,OAAO,KAAmB,aAC7B,EAAM,cACJ,GACA,CACF,IACA,EAAM,aAAa,GAAgB,CAAM;CAC/C;AACF;AAyBA,SAAgB,EACd,GACA,GACA,GAC2C;CAC3C,OAAO,EACJ,QAAQ,MACP,EAAO,MAAM,EAAE,qBAAkB,OAAO,EAAI,MAAiB,QAAQ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1B,iBAAiB,KAAa,QAAQ,KAAA;KACvC,CAAA;KAEF,GAAW;KACX,GAAqB;KACrB,GAAe,IAAI,EAAe;KAClC,KAAe,GAAc;KAC7B,KAAc,GAAa;KAG3B,EAAQ,IAAI,EAAc;KAC1B,EAAQ,IAAI,EAAgB;KAC5B,EAAQ,IAAI,EAAkB;IAClB;;EACD,CAAA;CACb,CAAA;AAET,CACF;AACA,EAAe,cAAc"}
|
|
1
|
+
{"version":3,"file":"confidence-cone.js","names":[],"sources":["../../../../src/components/ui/confidence-cone/confidence-cone.tsx"],"sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport {\n Area,\n CartesianGrid,\n ComposedChart,\n Line,\n ReferenceArea,\n ReferenceLine,\n Text,\n XAxis,\n YAxis,\n} from 'recharts';\n\nimport { cn } from '@/lib/utils';\nimport {\n ChartContainer,\n ChartLegend,\n ChartLegendContent,\n ChartTooltip,\n ChartTooltipContent,\n resolveAxisDomain,\n resolveAnimation,\n resolveRotatedTickAnchor,\n resolveXAxisTitle,\n resolveYAxisTitle,\n CHART_LABEL_FONT_SIZE,\n type ChartConfig,\n type ChartLegendFontSize,\n type ChartLegendAriaLabelProps,\n type ChartPalette,\n type ChartLegendContentProps,\n type ChartTooltipContentProps,\n toCssKey,\n type CartesianChartProps,\n type ChartAnimationProps,\n} from '../chart';\nimport {\n mergeXAxisLayoutMargin,\n useXAxisLayout,\n} from '../chart/use-x-axis-layout';\nimport { resolveXAxisTickLabels } from '../chart/chart-format';\n\n// A forecast confidence-cone: a solid line over the known/actual period, a\n// dashed line over the forecast period, and a shaded band (the \"cone\") between\n// a lower and upper bound that typically widens with the horizon — visualizing\n// growing uncertainty. Built on the shared Chart primitives; no new tokens\n// (series colors are caller-supplied via `config`). The whole metric renders in\n// one hue — actual and forecast differ by line style, not color — so the cone\n// band and the forecast line both reuse the actual series' color.\n\n// Each series' band is a synthetic `[lower, upper]` range field per row that a\n// recharts <Area> shades; kept out of the tooltip/legend (see the filters\n// below). One band per series, so the key carries the series' actual key — the\n// whole `__cone` prefix is reserved.\nconst BAND_PREFIX = '__cone';\nconst bandKeyFor = (actualKey: string) => `${BAND_PREFIX}:${actualKey}`;\n\n/**\n * Drop every synthetic cone-band range series from a recharts tooltip/legend\n * payload, keeping the real actual/forecast series (and their order). Applied to\n * both the default tooltip and any caller-supplied `tooltipContent`, so no band\n * surfaces regardless of which path renders or how many series are plotted.\n */\nexport function dropConeBand<T extends { dataKey?: unknown }>(\n payload: readonly T[] | undefined\n): T[] | undefined {\n return payload?.filter(\n (item) =>\n !(\n typeof item.dataKey === 'string' && item.dataKey.startsWith(BAND_PREFIX)\n )\n );\n}\n\n/**\n * Reduce a legend payload to the metrics the chart plots — one entry per series.\n * A series' actual, forecast and cone are three recharts series painting a\n * single metric in a single hue, so the legend names each metric once, with its\n * actual series' swatch, instead of listing line styles as separate series.\n */\nexport function keepMetricSeries<T extends { dataKey?: unknown }>(\n payload: readonly T[] | undefined,\n actualKeys: readonly string[]\n): T[] | undefined {\n return payload?.filter(\n (item) =>\n typeof item.dataKey === 'string' && actualKeys.includes(item.dataKey)\n );\n}\n\n/**\n * Wrap a caller-supplied `tooltipContent` so the synthetic cone band is stripped\n * from the payload before it renders, while preserving recharts' own mount\n * semantics — a function is mounted via `createElement` (its own component\n * identity + hook state), an element via `cloneElement`. This mirrors what the\n * pass-through charts get by handing `content` straight to recharts, so a\n * function-form tooltip keeps its state across re-renders here too. The returned\n * component is a stable content type (memoize it on `tooltipContent`).\n */\ntype TooltipContentType = NonNullable<\n React.ComponentProps<typeof ChartTooltip>['content']\n>;\ntype TooltipContentFn = Extract<\n TooltipContentType,\n (...args: never[]) => unknown\n>;\ntype TooltipRenderProps = Parameters<TooltipContentFn>[0];\n\nexport function createConeTooltip(tooltipContent: TooltipContentType) {\n return function ConeTooltip(props: TooltipRenderProps) {\n const merged = {\n ...props,\n payload: dropConeBand(props.payload),\n } as TooltipRenderProps;\n return typeof tooltipContent === 'function'\n ? React.createElement(\n tooltipContent as React.FunctionComponent<TooltipRenderProps>,\n merged\n )\n : React.cloneElement(tooltipContent, merged);\n };\n}\n\n/**\n * One plotted metric: its actual / forecast columns and, optionally, the two\n * bound columns that shade its cone. Omit `lowerKey`/`upperKey` for a band-less\n * metric — a solid line handing off to a bare dashed projection.\n */\nexport interface ConfidenceConeSeries {\n /** Field for the known/actual values — drawn as a solid line with a filled area. */\n actualKey: string;\n /** Field for the projected values — drawn as a dashed line. */\n forecastKey: string;\n /** Field for the cone's lower bound. Omit (with `upperKey`) for no cone. */\n lowerKey?: string;\n /** Field for the cone's upper bound. Omit (with `lowerKey`) for no cone. */\n upperKey?: string;\n}\n\n/**\n * The x values of the projected period — every row carrying a forecast value for\n * at least one series, in data order. The first is the hand-off point (where the\n * shaded region and divider start); the whole set drives the forecast tick\n * styling, matched by value so tick `interval` can't skew it the way a tick\n * index would. Exported for unit tests; not part of the package's public API.\n */\nexport function forecastPeriodX(\n data: ReadonlyArray<Record<string, string | number | null | undefined>>,\n series: readonly ConfidenceConeSeries[],\n xKey: string\n): Array<string | number | null | undefined> {\n return data\n .filter((row) =>\n series.some(({ forecastKey }) => typeof row[forecastKey] === 'number')\n )\n .map((row) => row[xKey]);\n}\n\n/**\n * Build the X-axis tick renderer that sets the projected columns apart: italic,\n * in the metric's hue. Styled inline rather than through the `fill` attribute\n * recharts hands every tick, so the accent survives the class-based tick color\n * a chart theme may apply. A custom tick owns its own text, so the caller's\n * `xTickFormatter` is applied here — recharts only applies it to default ticks.\n * Exported for unit tests; not part of the package's public API.\n */\nexport function createForecastTick(\n forecastX: ReadonlySet<string | number | null | undefined>,\n color: string,\n tickFormatter?: CartesianChartProps['xTickFormatter']\n) {\n return function ForecastTick({\n payload,\n index,\n ...tickProps\n }: {\n payload?: { value?: string | number };\n index?: number;\n }) {\n const value = payload?.value;\n return (\n <Text\n {...tickProps}\n style={\n value != null && forecastX.has(value)\n ? { fontStyle: 'italic', fill: color }\n : undefined\n }\n >\n {tickFormatter && value != null ? tickFormatter(value, index) : value}\n </Text>\n );\n };\n}\n\n/** A dashed horizontal threshold on the value axis. */\nexport interface ConfidenceConeReferenceLine {\n /** Position on the value (Y) axis. */\n value: number;\n /** Optional caption rendered at the line's right end. */\n label?: string;\n}\n\n/**\n * Every prop except the one-form-or-the-other requirement `ConfidenceConeProps`\n * layers on below. Exported so the stories can type their `Meta` on a single\n * object shape — Storybook can't split a union's required args between `meta.args`\n * and a story's. Not re-exported from `index.ts`; not part of the public API.\n */\nexport interface ConfidenceConeBaseProps\n extends\n Omit<React.ComponentProps<'div'>, 'children'>,\n CartesianChartProps,\n ChartAnimationProps,\n ChartLegendAriaLabelProps {\n /**\n * The dataviz palette this chart's series are painted from. Series that\n * state no `color` of their own take a stop of it. See `ChartPalette`.\n */\n palette?: ChartPalette;\n /**\n * Row-per-point data — the shared x dimension plus each series' actual /\n * forecast / bound fields. Rows are naturally sparse (a point has either an\n * actual or a forecast + bounds), so missing fields are allowed. Avoid fields\n * starting with `__cone` — that prefix is reserved for the internal\n * prediction-band series.\n */\n data: ReadonlyArray<Record<string, string | number | null | undefined>>;\n /**\n * Per-series map of `label` / `icon` / `tone` for the actual + forecast lines\n * (imported from the shared `Chart` primitives). Series take their colour from\n * the container's `palette`; each entry maps a key to a `label` and an optional\n * `tone`. Each metric renders in one hue: its cone band and forecast line both\n * reuse its actual series' color — actual and forecast differ by line style,\n * not hue.\n */\n config: ChartConfig;\n /** Category / time axis key (the shared dimension across rows). */\n xKey: string;\n /**\n * Plot several metrics against one shared axis — each with its own actual /\n * forecast / bound fields and its own hue (from `config[actualKey]`). Takes\n * precedence over the single-series `actualKey`/`forecastKey`/`lowerKey`/\n * `upperKey` shorthand below; pass one form or the other, not both. One of the\n * two forms is required.\n */\n series?: readonly ConfidenceConeSeries[];\n /**\n * Single-series shorthand — field for the known/actual values, drawn as a\n * solid line with a filled area. Required (with `forecastKey`) unless `series`\n * is set, which supersedes it.\n */\n actualKey?: string;\n /**\n * Single-series shorthand — field for the projected values, drawn as a dashed\n * line. Required (with `actualKey`) unless `series` is set, which supersedes\n * it.\n */\n forecastKey?: string;\n /** Field for the cone's lower bound. Omit (with `upperKey`) for no cone. */\n lowerKey?: string;\n /** Field for the cone's upper bound. Omit (with `lowerKey`) for no cone. */\n upperKey?: string;\n /**\n * How the known/actual period is drawn: a filled `area` under the line (the\n * default), or a bare `line` — for a chart where the cone is the only shaded\n * region, or where several metrics' fills would muddy each other.\n */\n actualType?: 'area' | 'line';\n /** Stroke width of the actual + forecast lines. */\n strokeWidth?: number;\n /**\n * Mark each data point: a filled dot on the observed values, a hollow one on\n * the projection — so a point reads as measured or predicted at a glance.\n */\n showDots?: boolean;\n /**\n * Italicize the X-axis ticks over the forecast period and paint them in the\n * first series' hue, so the projected columns read as projected even when the\n * shaded region is off.\n */\n styleForecastTicks?: boolean;\n /**\n * One or more dashed horizontal thresholds on the value axis — e.g. a target\n * or a capacity limit. Pass a single object or an array to draw several.\n */\n referenceLine?: ConfidenceConeReferenceLine | ConfidenceConeReferenceLine[];\n /**\n * Set off the forecast period from the actuals with a dashed divider at the\n * hand-off point (the first row with a forecast value) and a subtle shaded\n * band over the forecast region.\n */\n showForecastRegion?: boolean;\n showLegend?: boolean;\n /**\n * Font size of the legend text. Defaults to `'xs'` — the size the legend has\n * always rendered at. See `ChartLegendFontSize`.\n */\n legendFontSize?: ChartLegendFontSize;\n}\n\n/**\n * Which columns to plot has to be spelled out one way or the other: the `series`\n * array, or the flat `actualKey` + `forecastKey` shorthand. Expressed as a union\n * so a chart with neither is a compile error rather than a silent plot of axes\n * and nothing else. Both forms together stay legal — `series` wins (see\n * `plotted`), which is what the multi-series stories rely on to clear the args\n * table.\n */\nexport type ConfidenceConeProps = ConfidenceConeBaseProps &\n (\n | { series: readonly ConfidenceConeSeries[] }\n | { actualKey: string; forecastKey: string }\n );\n\nconst ConfidenceCone = React.forwardRef<HTMLDivElement, ConfidenceConeProps>(\n (\n {\n className,\n config,\n palette,\n data,\n xKey,\n series,\n actualKey,\n forecastKey,\n lowerKey,\n upperKey,\n xAxisLabel,\n yAxisLabel,\n yUnit,\n actualType = 'area',\n strokeWidth = 2,\n showDots = false,\n styleForecastTicks = false,\n referenceLine,\n showForecastRegion = true,\n showGrid = true,\n showTooltip = true,\n showLegend = true,\n legendFontSize,\n legendAriaLabel,\n showXAxis = true,\n showYAxis = true,\n xTickFormatter,\n yTickFormatter,\n xAxisAngle,\n xAxisInterval,\n yAxisTickCount,\n yAxisDomain,\n gridDashed,\n gridHorizontal,\n gridVertical,\n tooltipContent,\n animate,\n animationDuration,\n animationBegin,\n animationEasing,\n ...props\n },\n ref\n ) => {\n // The flat *Key props are the single-series shorthand for `series`.\n const plotted = React.useMemo<readonly ConfidenceConeSeries[]>(() => {\n if (series?.length) return series;\n if (!actualKey || !forecastKey) return [];\n return [{ actualKey, forecastKey, lowerKey, upperKey }];\n }, [series, actualKey, forecastKey, lowerKey, upperKey]);\n\n const animation = resolveAnimation({\n animate,\n animationDuration,\n animationBegin,\n animationEasing,\n });\n // Memoized so recharts sees a stable content type across renders — a fresh\n // wrapper each render would remount the caller's tooltip and reset its state.\n const customTooltip = React.useMemo(\n () => (tooltipContent ? createConeTooltip(tooltipContent) : undefined),\n [tooltipContent]\n );\n\n const xAxisTitle = resolveXAxisTitle(xAxisLabel);\n const yAxisTitle = resolveYAxisTitle(yAxisLabel);\n\n const yDomain = resolveAxisDomain(yAxisDomain);\n\n // One hue per metric. Each cone and forecast line already paints with its own\n // series' actual color; re-pointing that series' forecast key's `--color-*`\n // at it too means nothing downstream — a custom tooltip, a caller's\n // `var(--color-<forecastKey>)` — can reintroduce a second color.\n const seriesConfig = React.useMemo(() => {\n let next: ChartConfig | undefined;\n for (const { actualKey: aKey, forecastKey: fKey } of plotted) {\n const actual = config[aKey];\n const forecast = config[fKey];\n if (!actual || !forecast) continue;\n next ??= { ...config };\n next[fKey] = {\n label: forecast.label,\n icon: forecast.icon,\n tone: { sameAs: aKey },\n };\n }\n return next ?? config;\n }, [config, plotted]);\n\n const xAxisTickLabels = resolveXAxisTickLabels(\n data.map((row) => row[xKey]),\n xTickFormatter\n );\n const chartContainerRef = React.useRef<HTMLDivElement>(null);\n const xAxisLayout = useXAxisLayout(\n chartContainerRef,\n xAxisAngle,\n xAxisLabel,\n xAxisTickLabels.join('\\u0000')\n );\n\n // Augment each row with one `[lower, upper]` band tuple per coned series for\n // its Area to shade. Rows missing a numeric bound are left un-coned (the\n // band breaks there); a series without bounds gets no band at all.\n const chartData = data.map((row) => {\n const next: Record<string, unknown> = { ...row };\n for (const {\n actualKey: aKey,\n lowerKey: lKey,\n upperKey: uKey,\n } of plotted) {\n if (!lKey || !uKey) continue;\n const lower = row[lKey];\n const upper = row[uKey];\n next[bandKeyFor(aKey)] =\n typeof lower === 'number' && typeof upper === 'number'\n ? [lower, upper]\n : undefined;\n }\n return next;\n });\n\n const forecastX = forecastPeriodX(data, plotted, xKey);\n // Set the projected period off from the actuals with a shaded band + a\n // divider at the hand-off.\n const forecastStart = showForecastRegion ? forecastX[0] : undefined;\n const lastX = data[data.length - 1]?.[xKey];\n\n const renderForecastTick = createForecastTick(\n new Set(forecastX),\n `var(--color-${toCssKey(plotted[0]?.actualKey ?? '')})`,\n xTickFormatter\n );\n\n const referenceLines = referenceLine\n ? Array.isArray(referenceLine)\n ? referenceLine\n : [referenceLine]\n : [];\n\n // Everything from here to the `return` is lifted out of the returned tree\n // only to keep it readable as a flat list of chart children. Nothing in\n // recharts forces the `render*` helpers to be plain functions: axes and\n // series register themselves with the chart's store, and `<Cell>` is the\n // only child still looked up by element type — a component wrapper renders\n // fine (see AreaChart's `AreaFillGradients`). They stay functions because\n // they are declared inside the render body, where a component would get a\n // fresh element type on every render and remount its subtree.\n\n const renderAxes = () => (\n <>\n <XAxis\n dataKey={xKey}\n type=\"category\"\n hide={!showXAxis}\n tickLine={false}\n axisLine={false}\n tickMargin={8}\n tickFormatter={xTickFormatter}\n tick={styleForecastTicks ? renderForecastTick : undefined}\n angle={xAxisAngle}\n interval={xAxisInterval}\n textAnchor={resolveRotatedTickAnchor(xAxisAngle)}\n height={xAxisLayout.height}\n label={xAxisTitle}\n />\n <YAxis\n type=\"number\"\n hide={!showYAxis}\n tickLine={false}\n axisLine={false}\n unit={yUnit}\n tickFormatter={yTickFormatter}\n tickCount={yAxisTickCount}\n domain={yDomain}\n width={yAxisLabel ? 72 : undefined}\n label={yAxisTitle}\n />\n </>\n );\n\n // Set the forecast region off from the actuals (behind everything).\n const renderForecastRegion = () => (\n <>\n {forecastStart != null && lastX != null && (\n <ReferenceArea\n x1={forecastStart}\n x2={lastX}\n fill=\"var(--ui-background-surface-secondary)\"\n fillOpacity={0.5}\n ifOverflow=\"extendDomain\"\n />\n )}\n {forecastStart != null && (\n <ReferenceLine\n x={forecastStart}\n stroke=\"var(--ui-border-on-surface-border)\"\n strokeDasharray=\"4 4\"\n />\n )}\n </>\n );\n\n const renderThreshold = (\n threshold: ConfidenceConeReferenceLine,\n index: number\n ) => (\n <ReferenceLine\n key={`${threshold.label ?? 'threshold'}-${index}`}\n y={threshold.value}\n stroke=\"var(--ui-text-on-surface-secondary)\"\n strokeDasharray=\"4 4\"\n // extendDomain so a threshold beyond the data max stays visible.\n ifOverflow=\"extendDomain\"\n label={\n threshold.label\n ? {\n value: threshold.label,\n position: 'insideTopRight',\n fill: 'var(--ui-text-on-surface-secondary)',\n fontSize: CHART_LABEL_FONT_SIZE,\n }\n : undefined\n }\n />\n );\n\n const renderTooltip = () =>\n customTooltip ? (\n // Strips the synthetic band before the caller's tooltip sees it — the\n // `__cone` series feeds the Area, not the tooltip.\n <ChartTooltip content={customTooltip} />\n ) : (\n <ChartTooltip\n content={(tp) => (\n <ChartTooltipContent\n active={tp.active}\n label={tp.label}\n // The synthetic band feeds the Area, not the tooltip.\n payload={\n dropConeBand(tp.payload) as ChartTooltipContentProps['payload']\n }\n />\n )}\n />\n );\n\n const renderLegend = () => (\n <ChartLegend\n content={(lp) => (\n <ChartLegendContent\n verticalAlign={lp.verticalAlign}\n fontSize={legendFontSize}\n ariaLabel={legendAriaLabel}\n payload={\n keepMetricSeries(\n lp.payload,\n plotted.map((s) => s.actualKey)\n ) as ChartLegendContentProps['payload']\n }\n />\n )}\n />\n );\n\n // One color per metric — actual and forecast differ by line style, not hue\n // — so a cone reuses its series' actual color.\n const renderConeBand = ({\n actualKey: aKey,\n lowerKey: lKey,\n upperKey: uKey,\n }: ConfidenceConeSeries) =>\n lKey && uKey ? (\n <Area\n key={bandKeyFor(aKey)}\n // The band paints in the same hue, at the same opacity, as the\n // actual series' own area, so nothing on the rendered path tells\n // the two apart. recharts forwards `data-*` onto the path it\n // draws; the tests select the band through this.\n data-slot=\"confidence-cone-band\"\n dataKey={bandKeyFor(aKey)}\n type=\"monotone\"\n stroke=\"none\"\n fill={`var(--color-${toCssKey(aKey)})`}\n fillOpacity={0.15}\n connectNulls={false}\n dot={false}\n activeDot={false}\n {...animation}\n legendType=\"none\"\n tooltipType=\"none\"\n />\n ) : null;\n\n const renderActualMark = ({ actualKey: aKey }: ConfidenceConeSeries) => {\n // An area and a line take the same props here; only the region under the\n // curve (and the mark recharts draws) differ. A `Line` gets no fill at\n // all — `fillOpacity: 0` would also erase its dots.\n const ActualMark = actualType === 'line' ? Line : Area;\n const areaFill =\n actualType === 'line'\n ? undefined\n : { fill: `var(--color-${toCssKey(aKey)})`, fillOpacity: 0.15 };\n // Observed points read as measured: LineChart's dot geometry (r 3, 2px\n // ring) filled with the metric hue. The ring is that same hue, so the\n // mark is solid — and wide enough against the 2px line not to read as a\n // mere thickening of it. `fillOpacity: 1` is load-bearing: recharts\n // merges the parent mark's own presentation props into every dot it\n // draws, so an `<Area>`'s 0.15 would otherwise wash the dot out to a halo.\n const dot = showDots\n ? {\n r: 3,\n fill: `var(--color-${toCssKey(aKey)})`,\n fillOpacity: 1,\n stroke: `var(--color-${toCssKey(aKey)})`,\n strokeWidth: 2,\n }\n : false;\n return (\n <ActualMark\n key={aKey}\n dataKey={aKey}\n type=\"monotone\"\n stroke={`var(--color-${toCssKey(aKey)})`}\n strokeWidth={strokeWidth}\n {...areaFill}\n dot={dot}\n activeDot={showDots ? { r: 5 } : false}\n connectNulls\n {...animation}\n // The legend names the metric once, so it carries the swatch that\n // stands for the whole series rather than the actual line's style.\n legendType=\"rect\"\n />\n );\n };\n\n const renderForecastLine = ({\n actualKey: aKey,\n forecastKey: fKey,\n }: ConfidenceConeSeries) => {\n // Projected points read as predicted: the same LineChart dot, inverted —\n // the metric's hue as the ring, the surface color as the fill, so the\n // dashed line doesn't show through the middle. (LineChart leaves the fill\n // to recharts, whose `Line` defaults it to `#fff`; the token is that same\n // white in the light theme and also holds up in the dark one.)\n // `strokeDasharray: 'none'` is load-bearing: recharts merges the parent\n // mark's presentation props into every dot, so this line's `5 5` would\n // otherwise break each dot's ring into two arcs.\n const dot = showDots\n ? {\n r: 3,\n fill: 'var(--ui-background-surface-primary)',\n stroke: `var(--color-${toCssKey(aKey)})`,\n strokeWidth: 2,\n strokeDasharray: 'none',\n }\n : false;\n return (\n <Line\n key={fKey}\n dataKey={fKey}\n type=\"monotone\"\n stroke={`var(--color-${toCssKey(aKey)})`}\n strokeWidth={strokeWidth}\n strokeDasharray=\"5 5\"\n dot={dot}\n // Paired with `dot` the way every other chart does it — left unset,\n // the projection would keep recharts' default active dot while the\n // actuals had none (and a different radius when on).\n activeDot={showDots ? { r: 5 } : false}\n connectNulls\n {...animation}\n />\n );\n };\n\n return (\n <div ref={ref} className={cn(className)} {...props}>\n <ChartContainer\n ref={chartContainerRef}\n config={seriesConfig}\n palette={palette}\n className=\"size-full [&_.recharts-label]:fill-foreground\"\n >\n <ComposedChart\n data={chartData as readonly unknown[]}\n margin={mergeXAxisLayoutMargin(undefined, xAxisLayout.margin)}\n >\n {showGrid && (\n <CartesianGrid\n horizontal={gridHorizontal ?? true}\n vertical={gridVertical ?? false}\n strokeDasharray={gridDashed ? '3 3' : undefined}\n />\n )}\n {renderAxes()}\n {renderForecastRegion()}\n {referenceLines.map(renderThreshold)}\n {showTooltip && renderTooltip()}\n {showLegend && renderLegend()}\n {/* Every cone renders before any line, so the lines draw on top of\n all of them. */}\n {plotted.map(renderConeBand)}\n {plotted.map(renderActualMark)}\n {plotted.map(renderForecastLine)}\n </ComposedChart>\n </ChartContainer>\n </div>\n );\n }\n);\nConfidenceCone.displayName = 'ConfidenceCone';\n\nexport { ConfidenceCone };\n"],"mappings":";;;;;;;;;AAwDA,IAAM,IAAc,UACd,KAAc,MAAsB,GAAG,EAAY,GAAG;AAQ5D,SAAgB,EACd,GACiB;CACjB,OAAO,GAAS,QACb,MACC,EACE,OAAO,EAAK,WAAY,YAAY,EAAK,QAAQ,WAAW,CAAW,EAE7E;AACF;AAQA,SAAgB,EACd,GACA,GACiB;CACjB,OAAO,GAAS,QACb,MACC,OAAO,EAAK,WAAY,YAAY,EAAW,SAAS,EAAK,OAAO,CACxE;AACF;AAoBA,SAAgB,EAAkB,GAAoC;CACpE,OAAO,SAAqB,GAA2B;EACrD,IAAM,IAAS;GACb,GAAG;GACH,SAAS,EAAa,EAAM,OAAO;EACrC;EACA,OAAO,OAAO,KAAmB,aAC7B,EAAM,cACJ,GACA,CACF,IACA,EAAM,aAAa,GAAgB,CAAM;CAC/C;AACF;AAyBA,SAAgB,EACd,GACA,GACA,GAC2C;CAC3C,OAAO,EACJ,QAAQ,MACP,EAAO,MAAM,EAAE,qBAAkB,OAAO,EAAI,MAAiB,QAAQ,CACvE,CAAC,CACA,KAAK,MAAQ,EAAI,EAAK;AAC3B;AAUA,SAAgB,EACd,GACA,GACA,GACA;CACA,OAAO,SAAsB,EAC3B,YACA,UACA,GAAG,KAIF;EACD,IAAM,IAAQ,GAAS;EACvB,OACE,kBAAC,GAAD;GACE,GAAI;GACJ,OACE,KAAS,QAAQ,EAAU,IAAI,CAAK,IAChC;IAAE,WAAW;IAAU,MAAM;GAAM,IACnC,KAAA;GAGL,UAAA,KAAiB,KAAS,OAAO,EAAc,GAAO,CAAK,IAAI;EAC5D,CAAA;CAEV;AAC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, height:
|
|
|
127
127
|
strokeWidth: g ? w : c
|
|
128
128
|
});
|
|
129
129
|
}
|
|
130
|
-
var W = u.forwardRef(({ className: t, config: C, palette: w, data: T, dataKey: E, nameKey: D, lastShape: O = "triangle", reversed: A = !1, showLabels: j = !1, labelFormat: M = "name", labelPosition: N = "right", showValueLabels: P = !1, valuePosition: F, labelFill: I, labelFormatter: L, percentFormatter: R, showLegend: z = !0, legendFontSize: H,
|
|
130
|
+
var W = u.forwardRef(({ className: t, config: C, palette: w, data: T, dataKey: E, nameKey: D, lastShape: O = "triangle", reversed: A = !1, showLabels: j = !1, labelFormat: M = "name", labelPosition: N = "right", showValueLabels: P = !1, valuePosition: F, labelFill: I, labelFormatter: L, percentFormatter: R, showLegend: z = !0, legendFontSize: H, legendAriaLabel: W, legendValueFormatter: ne, stageSettings: G, showActiveShape: re = !1, stroke: ie, strokeWidth: K, funnelWidth: ae, margin: q, showTooltip: oe = !0, tooltipContent: se, animate: ce, animationDuration: le, animationBegin: ue, animationEasing: de, ...fe }, pe) => {
|
|
131
131
|
let me = c({
|
|
132
132
|
animate: ce,
|
|
133
133
|
animationDuration: le,
|
|
134
134
|
animationBegin: ue,
|
|
135
135
|
animationEasing: de
|
|
136
|
-
}),
|
|
136
|
+
}), J = u.useMemo(() => {
|
|
137
137
|
let e = T.filter((e) => !G?.[String(e[D])]?.hidden), t = e.reduce((e, t) => {
|
|
138
138
|
let n = Number(t[E]);
|
|
139
139
|
return Number.isFinite(n) && n > e ? n : e;
|
|
@@ -168,44 +168,44 @@ var W = u.forwardRef(({ className: t, config: C, palette: w, data: T, dataKey: E
|
|
|
168
168
|
D,
|
|
169
169
|
R,
|
|
170
170
|
G
|
|
171
|
-
]),
|
|
171
|
+
]), Y = u.useMemo(() => z ? o(C, w ?? k) : null, [
|
|
172
172
|
z,
|
|
173
173
|
C,
|
|
174
174
|
w
|
|
175
175
|
]), he = u.useMemo(() => {
|
|
176
|
-
if (!
|
|
176
|
+
if (!Y) return [];
|
|
177
177
|
let e = /* @__PURE__ */ new Set();
|
|
178
|
-
return
|
|
178
|
+
return J.flatMap((t) => {
|
|
179
179
|
let n = String(t[D]);
|
|
180
180
|
return e.has(n) ? [] : (e.add(n), [{
|
|
181
181
|
value: n,
|
|
182
182
|
dataKey: D,
|
|
183
183
|
type: "rect",
|
|
184
|
-
color: G?.[n]?.color ??
|
|
184
|
+
color: G?.[n]?.color ?? Y[n]?.color ?? String(t.fill),
|
|
185
185
|
payload: t
|
|
186
186
|
}]);
|
|
187
187
|
});
|
|
188
188
|
}, [
|
|
189
189
|
D,
|
|
190
|
-
q,
|
|
191
190
|
J,
|
|
191
|
+
Y,
|
|
192
192
|
G
|
|
193
|
-
]),
|
|
193
|
+
]), X = F ?? y(N), ge = j && N !== "inside" || P && X !== "inside", Z = v[N], Q = v[X], _e = {
|
|
194
194
|
...V({
|
|
195
195
|
showLabels: j,
|
|
196
196
|
labelPosition: N,
|
|
197
197
|
showValueLabels: P,
|
|
198
|
-
valuePosition:
|
|
198
|
+
valuePosition: X
|
|
199
199
|
}),
|
|
200
|
-
...
|
|
201
|
-
},
|
|
200
|
+
...q
|
|
201
|
+
}, ve = ae ?? B({
|
|
202
202
|
showLabels: j,
|
|
203
203
|
labelPosition: N,
|
|
204
204
|
labelFormat: M
|
|
205
|
-
}),
|
|
205
|
+
}), ye = ie ?? (K == null ? "none" : "var(--ui-border-on-surface-border)"), $ = (e) => /* @__PURE__ */ d(te, {
|
|
206
206
|
...e,
|
|
207
|
-
showActiveShape:
|
|
208
|
-
topStageIndex: A ?
|
|
207
|
+
showActiveShape: re,
|
|
208
|
+
topStageIndex: A ? J.length - 1 : 0
|
|
209
209
|
});
|
|
210
210
|
return /* @__PURE__ */ f("div", {
|
|
211
211
|
ref: pe,
|
|
@@ -213,30 +213,30 @@ var W = u.forwardRef(({ className: t, config: C, palette: w, data: T, dataKey: E
|
|
|
213
213
|
className: e("flex flex-row items-center gap-4", !z && "justify-center", _({ lastShape: O }), t),
|
|
214
214
|
...fe,
|
|
215
215
|
children: [/* @__PURE__ */ d("div", {
|
|
216
|
-
className:
|
|
216
|
+
className: ge ? "h-[120px] flex-1" : e(ee, "shrink-0"),
|
|
217
217
|
children: /* @__PURE__ */ d(n, {
|
|
218
218
|
config: C,
|
|
219
219
|
palette: w ?? k,
|
|
220
220
|
className: "size-full",
|
|
221
221
|
children: /* @__PURE__ */ f(h, {
|
|
222
|
-
margin:
|
|
222
|
+
margin: _e,
|
|
223
223
|
children: [oe && /* @__PURE__ */ d(i, { content: se ?? /* @__PURE__ */ d(a, {
|
|
224
224
|
nameKey: D,
|
|
225
225
|
hideLabel: !0
|
|
226
226
|
}) }), /* @__PURE__ */ f(m, {
|
|
227
227
|
dataKey: E,
|
|
228
228
|
nameKey: D,
|
|
229
|
-
data:
|
|
229
|
+
data: J,
|
|
230
230
|
lastShapeType: O ?? "triangle",
|
|
231
231
|
reversed: A,
|
|
232
|
-
width:
|
|
233
|
-
stroke:
|
|
232
|
+
width: ve,
|
|
233
|
+
stroke: ye,
|
|
234
234
|
strokeWidth: K,
|
|
235
235
|
shape: $,
|
|
236
236
|
activeShape: $,
|
|
237
237
|
...me,
|
|
238
238
|
children: [
|
|
239
|
-
|
|
239
|
+
J.map((e, t) => /* @__PURE__ */ d(p, { fill: String(e.fill) }, t)),
|
|
240
240
|
j && /* @__PURE__ */ d(g, {
|
|
241
241
|
position: Z,
|
|
242
242
|
dataKey: b,
|
|
@@ -255,14 +255,15 @@ var W = u.forwardRef(({ className: t, config: C, palette: w, data: T, dataKey: E
|
|
|
255
255
|
})]
|
|
256
256
|
})
|
|
257
257
|
})
|
|
258
|
-
}), z &&
|
|
258
|
+
}), z && Y && /* @__PURE__ */ d(r, {
|
|
259
259
|
variant: "list",
|
|
260
260
|
payload: he,
|
|
261
|
-
config:
|
|
261
|
+
config: Y,
|
|
262
262
|
nameKey: D,
|
|
263
263
|
fontSize: H,
|
|
264
|
+
ariaLabel: W,
|
|
264
265
|
valueKey: E,
|
|
265
|
-
valueFormatter:
|
|
266
|
+
valueFormatter: ne,
|
|
266
267
|
valueClassName: "text-[var(--ui-text-on-surface-primary)]",
|
|
267
268
|
className: "min-w-0 flex-1"
|
|
268
269
|
})]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"funnel-chart.js","names":[],"sources":["../../../../src/components/ui/funnel-chart/funnel-chart.tsx"],"sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport { cva, type VariantProps } from 'class-variance-authority';\nimport {\n Cell,\n Funnel,\n FunnelChart as RechartsFunnelChart,\n LabelList,\n} from 'recharts';\nimport type { LegendPayload } from 'recharts/types/component/DefaultLegendContent';\n\nimport { cn } from '@/lib/utils';\nimport {\n ChartContainer,\n ChartLegendContent,\n ChartTooltip,\n ChartTooltipContent,\n resolveAnimation,\n resolveChartColors,\n resolveLabelFillClass,\n toCssKey,\n type ChartAnimationProps,\n type ChartConfig,\n type ChartLegendFontSize,\n type ChartPalette,\n type TickFormatter,\n} from '../chart';\n\n// A typed recharts composition over the shared `Chart` primitives. The single\n// CVA axis is the design's Funnel-chart variant set: `lastShape` (does the\n// funnel narrow to a point — `triangle` — or end flat — `rectangle`). The class\n// stays empty because recharts' SVG — not CSS — draws the funnel: `lastShape`\n// drives the `<Funnel>`'s `lastShapeType`. CVA is kept so the variant set is a\n// first-class, spec-conformant part of the API (matched against ui-spec's\n// api.yaml enums) and exposed via `VariantProps`; the resolved value is also\n// mirrored onto `data-last-shape`.\nconst funnelChartVariants = cva('', {\n variants: {\n lastShape: {\n triangle: '',\n rectangle: '',\n },\n },\n defaultVariants: {\n lastShape: 'triangle',\n },\n});\n\n/** Where a stage's label sits relative to its segment. */\nexport type FunnelChartLabelPosition = 'right' | 'left' | 'inside';\n\n/** What a stage's label says. */\nexport type FunnelChartLabelFormat =\n | 'name'\n | 'value'\n | 'percent'\n | 'name-value'\n | 'name-percent'\n | 'value-percent';\n\n/** Override for a single stage, keyed by its `nameKey` value. */\nexport interface FunnelChartStageSettings {\n /**\n * Paint this stage with a colour of its own instead of its `palette` stop —\n * the same per-item escape hatch `PieChart`'s `sliceSettings` offers.\n * Reference an existing semantic `--ui-*` token.\n */\n color?: string;\n /**\n * Drop the stage from the funnel — and from the legend, labels and the\n * conversion percentages, which are computed over the visible stages only.\n */\n hidden?: boolean;\n}\n\n// recharts' `LabelList` positions that a funnel trapezoid understands. `inside`\n// is recharts' `center`: a trapezoid has no `insideLeft`/`insideTop` anchor, so\n// centring is the only on-segment placement. `outside` is not offered — for a\n// funnel it would mean \"beside the segment\", which is what `right`/`left`\n// already are, and recharts' polar `outside` doesn't apply to a trapezoid.\nconst LABEL_POSITION: Record<\n FunnelChartLabelPosition,\n 'right' | 'left' | 'center'\n> = {\n right: 'right',\n left: 'left',\n inside: 'center',\n};\n\n/**\n * Where the value labels sit when the caller doesn't say: opposite the names, so\n * the two lists never stack on the same edge. `inside` names sit on the segments\n * and leave both edges free, so the values take the default `right`.\n *\n * A static default can't do this — `valuePosition=\"left\"` beside\n * `labelPosition=\"left\"` draws both lists at the same anchor, overprinting the\n * name with its own value.\n */\nexport function funnelChartOppositeSide(\n labelPosition: FunnelChartLabelPosition\n): FunnelChartLabelPosition {\n switch (labelPosition) {\n case 'right':\n return 'left';\n case 'left':\n return 'right';\n case 'inside':\n return 'right';\n }\n}\n\n// Synthetic row fields the two label lists read. A `LabelList` resolves its text\n// from a `dataKey`, and its `formatter` only ever sees that one field's value —\n// so a composite label (\"Signups: 52.0%\") has to be composed onto the row before\n// recharts sees it, the same way `fill` already is.\nconst STAGE_LABEL_KEY = '__stageLabel';\nconst STAGE_VALUE_LABEL_KEY = '__stageValueLabel';\n\n// Which stage this row is. recharts hands a custom `shape` the data row as\n// `payload` but no index, and the first stage is the one that must *not* be\n// pushed down — its top edge is the top of the funnel.\nconst STAGE_INDEX_KEY = '__stageIndex';\n\n// Hover highlight for `showActiveShape` — an outline rather than a fill change,\n// so the segment keeps the colour that ties it to its legend entry and label.\nconst ACTIVE_STROKE = 'var(--ui-border-on-surface-border-active)';\nconst ACTIVE_STROKE_WIDTH = 2;\n\n/**\n * The design's funnel plot: a 120×120 square beside its legend — the same\n * geometry `ChartDonut` uses in Figma, which is why `PieChart` and\n * `RadialBarChart` size their plot exactly this way too.\n *\n * The *component* is still parent-responsive: the root is a flex row whose\n * legend column takes every pixel the plot doesn't, so a funnel widens with its\n * widget instead of the plot growing into a tall, narrow wedge.\n *\n * Figma: `8811:175245` → `Chart` is `size-[120px]`, `gap-[16px]`, legend\n * `flex-[1_0_0]`.\n */\nconst PLOT_SIZE_CLASS = 'size-[120px]';\n\n/**\n * Surface showing between two stages, in px. recharts draws the stages flush —\n * `Funnel` has no gap prop and `Trapezoid` no radius — so both come from the\n * custom `shape` below.\n *\n * Figma `8811:175245` stacks the stages at y = 4 / 34 / 64 / 94 with shapes 28\n * tall: a 2px gap, three times over for four stages.\n */\nconst STAGE_GAP = 2;\n\n/** Corner rounding on the two upper edges of each stage (Figma: ~2px clip along the top edge). */\nconst STAGE_RADIUS = 2;\n\n/**\n * Corner rounding on the two lower edges of each stage.\n *\n * Figma's bottom corners clip ~0.85px — significantly less than the upper\n * corners. The asymmetry is intentional: the diagonal-meets-flat-bottom\n * transition is shallow, so a smaller radius keeps it from looking over-rounded\n * at the narrow tail of the funnel. 1px is the nearest integer match.\n */\nconst STAGE_BOTTOM_RADIUS = 1;\n\n/**\n * The plot-area inset when nothing sits beside the funnel. Figma's widest stage\n * spans 102.67 of the 120px box and the stack runs y=4 → ~115.7, i.e. ~8px of\n * horizontal and 4px of vertical breathing room.\n */\nconst PLOT_MARGIN = { top: 4, right: 8, bottom: 4, left: 8 };\n\n/**\n * The palette Figma paints the funnel from: the sequential blue ramp, whose\n * stops read as one quantity falling down the funnel. Every other chart keeps\n * the shared categorical default — a funnel's stages are an *ordered* series,\n * which is what a sequential ramp is for.\n *\n * Figma `8811:175245` uses `dataviz/sequential/blue/{2,4,6,8}`.\n */\nexport const FUNNEL_CHART_DEFAULT_PALETTE: ChartPalette = Object.freeze({\n type: 'sequential',\n ramp: 'blue',\n});\n\ntype StagePoint = readonly [number, number];\n\nconst distance = (a: StagePoint, b: StagePoint) =>\n Math.hypot(b[0] - a[0], b[1] - a[1]);\n\n/** A point `d` px from `from` along the segment toward `to`. */\nfunction along(from: StagePoint, to: StagePoint, d: number): StagePoint {\n const length = distance(from, to);\n if (length === 0) return from;\n return [\n from[0] + ((to[0] - from[0]) * d) / length,\n from[1] + ((to[1] - from[1]) * d) / length,\n ];\n}\n\n// Trimmed to 3dp so the emitted `d` is stable across platforms — a raw float\n// makes every visual-regression baseline and DOM assertion renderer-dependent.\nconst coord = ([x, y]: StagePoint) =>\n `${Number(x.toFixed(3))},${Number(y.toFixed(3))}`;\n\n/**\n * A closed polygon with rounded corners, as an SVG path.\n *\n * Each corner is trimmed back along both of its edges and bridged with a\n * quadratic curve through the original vertex. The radius is clamped to half of\n * either adjacent edge, so two corners can never overrun each other on a short\n * edge — which is the normal case at the bottom of a funnel, where the last\n * stages are only a few px wide.\n */\nfunction roundedPolygonPath(\n points: readonly StagePoint[],\n radius: number | readonly number[]\n): string {\n const count = points.length;\n if (count < 3) return '';\n\n let path = '';\n for (let i = 0; i < count; i++) {\n const r = typeof radius === 'number' ? radius : radius[i];\n const previous = points[(i - 1 + count) % count];\n const current = points[i];\n const next = points[(i + 1) % count];\n const corner = Math.max(\n 0,\n Math.min(\n r,\n distance(previous, current) / 2,\n distance(current, next) / 2\n )\n );\n const entry = along(current, previous, corner);\n const exit = along(current, next, corner);\n path += `${i === 0 ? 'M' : ' L'} ${coord(entry)}`;\n path += ` Q ${coord(current)} ${coord(exit)}`;\n }\n return `${path} Z`;\n}\n\n/**\n * The `d` for one funnel stage — recharts' trapezoid geometry with the design's\n * rounded corners.\n *\n * `x`/`y` is the top-left of the *upper* edge and the shape is centred on\n * `x + upperWidth / 2`, matching recharts' own `getTrapezoidPath`.\n *\n * Either edge can collapse to a single rounded apex rather than a zero-length\n * one — the `triangle` last shape narrows to a point at the bottom, and a\n * `reversed` funnel stands that same triangle on its head at the top.\n */\nexport function funnelChartStagePath(options: {\n x: number;\n y: number;\n upperWidth: number;\n lowerWidth: number;\n height: number;\n /**\n * Uniform corner radius — applies to all four corners. Overridden per-side\n * by `topRadius` / `bottomRadius`. When absent, defaults to\n * `STAGE_RADIUS` (top) and `STAGE_BOTTOM_RADIUS` (bottom).\n */\n radius?: number;\n /** Radius for the two upper corners (default: `STAGE_RADIUS = 2`). */\n topRadius?: number;\n /**\n * Radius for the two lower corners (default: `STAGE_BOTTOM_RADIUS = 1`).\n *\n * Figma's bottom corners clip ~0.85px — much smaller than the upper ones —\n * so the default is intentionally lower than `topRadius`.\n */\n bottomRadius?: number;\n}): string {\n const { x, y, upperWidth, lowerWidth, height } = options;\n // `radius` is a backward-compat shorthand for all corners.\n // Per-side props win; if only `radius` is given it applies to both sides.\n // If nothing is given, use the asymmetric Figma defaults.\n const uniformRadius = options.radius;\n const topRadius = options.topRadius ?? uniformRadius ?? STAGE_RADIUS;\n const bottomRadius =\n options.bottomRadius ?? uniformRadius ?? STAGE_BOTTOM_RADIUS;\n\n if (height <= 0 || (upperWidth <= 0 && lowerWidth <= 0)) return '';\n\n const centre = x + upperWidth / 2;\n const upper: StagePoint[] =\n upperWidth <= 0\n ? [[centre, y]]\n : [\n [x, y],\n [x + upperWidth, y],\n ];\n const lower: StagePoint[] =\n lowerWidth <= 0\n ? [[centre, y + height]]\n : [\n [centre + lowerWidth / 2, y + height],\n [centre - lowerWidth / 2, y + height],\n ];\n\n // Upper points get topRadius, lower points get bottomRadius — matching\n // Figma's intentional asymmetry (the diagonal-meets-bottom transition\n // uses a much smaller clip than the diagonal-meets-top one).\n const radii: number[] = [\n ...upper.map(() => topRadius),\n ...lower.map(() => bottomRadius),\n ];\n return roundedPolygonPath([...upper, ...lower], radii);\n}\n\n/**\n * Pull a stage's **top** edge down by `gap`, so surface shows between it and the\n * stage above.\n *\n * The top rather than the bottom on purpose: the bottom edge is what\n * `lastShapeType` defines — the triangle's apex — so leaving it exactly where\n * recharts put it keeps a `triangle` funnel ending in a real point instead of a\n * blunt 2px edge. The upper edge slides down the funnel's own slope, so the\n * taper is unchanged rather than steepened.\n *\n * A stage with no room for the gap is returned untouched: better a missing gap\n * than an inverted shape.\n */\nexport function funnelChartStageInset(options: {\n x: number;\n y: number;\n upperWidth: number;\n lowerWidth: number;\n height: number;\n gap: number;\n}) {\n const { x, y, upperWidth, lowerWidth, height, gap } = options;\n if (gap <= 0 || height <= gap) {\n return { x, y, upperWidth, lowerWidth, height };\n }\n\n const insetUpperWidth =\n upperWidth + ((lowerWidth - upperWidth) * gap) / height;\n return {\n x: x + upperWidth / 2 - insetUpperWidth / 2,\n y: y + gap,\n upperWidth: insetUpperWidth,\n lowerWidth,\n height: height - gap,\n };\n}\n\n// The inset reserved on whichever side a label list sits. It is *not* label\n// room — see `funnelChartLabelReserve` for why — but a label whose text can't\n// wrap (one long word) does overflow past the plot edge, and this is what keeps\n// that overflow inside the SVG.\nconst LABEL_SIDE_INSET = 96;\n\n// The plot-area margin a funnel has always been drawn with: the right side\n// reserved, the left not.\nconst BASE_MARGIN = {\n top: 8,\n right: LABEL_SIDE_INSET,\n bottom: 8,\n left: 24,\n};\n\n/**\n * Share of the plot area handed to the funnel when a composite label sits to its\n * right. The rest becomes real label room — see `funnelChartLabelReserve`.\n *\n * A percentage, not a pixel count: the plot area is responsive, and recharts\n * resolves `Funnel`'s `width` against it, so a ratio keeps the reserve\n * proportional at every chart size.\n */\nconst COMPOSITE_FUNNEL_WIDTH = '75%';\n\n/** A label format that pairs two fields, so its text is roughly twice as wide. */\nfunction isCompositeFormat(format: FunnelChartLabelFormat): boolean {\n return format.includes('-');\n}\n\n/**\n * Reserve room for a composite label beside the funnel, by narrowing the\n * **funnel** rather than the plot area.\n *\n * recharts word-wraps a label against the space between its trapezoid's\n * mid-height edge and the *plot area* edge (`getCartesianPosition` clamps\n * `width` to `parentViewBox`, which `Funnel` sets to the plot box). A margin\n * shrinks the plot area and the funnel inside it in lockstep, so widening\n * `margin.right` moves the clamp edge *inward* and leaves a composite label\n * with less room, not more — the reserved strip sits outside `parentViewBox`\n * where the text can never reach it.\n *\n * `Funnel`'s `width` is the lever that works: it scales the funnel within the\n * plot area while `parentViewBox` stays put, and because recharts anchors the\n * funnel at the plot area's left edge (`offsetX = offset.left`), everything it\n * frees lands on the right. Narrowing the funnel to\n * `COMPOSITE_FUNNEL_WIDTH` turns ~35px of wrap width into ~140px on a 460px\n * chart.\n *\n * Returns `undefined` — i.e. leave the funnel at its full width — for every\n * other case, so a funnel with plain labels, no labels, or `inside` labels keeps\n * exactly the geometry it has always had.\n *\n * There is no equivalent lever for `labelPosition=\"left\"`: the widest trapezoid\n * always starts flush at the plot area's left edge, so a left-hand label is\n * bounded by how sharply the funnel narrows and narrowing it further only makes\n * that worse. Composite left-hand labels wrap; that's a recharts limitation, not\n * a tuning choice.\n *\n * A caller-supplied `funnelWidth` always wins — this is only the default.\n */\nexport function funnelChartLabelReserve(options: {\n showLabels: boolean;\n labelPosition: FunnelChartLabelPosition;\n labelFormat: FunnelChartLabelFormat;\n}): string | undefined {\n const { showLabels, labelPosition, labelFormat } = options;\n return showLabels &&\n labelPosition === 'right' &&\n isCompositeFormat(labelFormat)\n ? COMPOSITE_FUNNEL_WIDTH\n : undefined;\n}\n\n/**\n * The plot-area margin.\n *\n * With nothing beside the funnel — the default, and what Figma draws — the plot\n * is the design's own inset (`PLOT_MARGIN`): just the few px the rounded corners\n * and the apex need, so the funnel fills its 120px square instead of being\n * squeezed into the middle by label room it isn't using.\n *\n * As soon as a label list *does* sit beside the funnel, the side insets come\n * back: this is overflow protection, not label room — the wrap width comes from\n * `funnelChartLabelReserve`. A caller-supplied `margin` is merged over these\n * defaults per side, so `margin={{ right: 160 }}` keeps the default top, bottom\n * and left rather than collapsing them to zero.\n */\nexport function funnelChartLabelMargin(options: {\n showLabels: boolean;\n labelPosition: FunnelChartLabelPosition;\n showValueLabels: boolean;\n valuePosition: FunnelChartLabelPosition;\n}) {\n const { showLabels, labelPosition, showValueLabels, valuePosition } = options;\n const stageLabelAt = showLabels ? labelPosition : undefined;\n const valueLabelAt = showValueLabels ? valuePosition : undefined;\n const besideOnLeft = stageLabelAt === 'left' || valueLabelAt === 'left';\n const besideOnRight = stageLabelAt === 'right' || valueLabelAt === 'right';\n\n // `inside` labels sit on the segments, so they count as \"nothing beside the\n // funnel\" and keep the tight design margin too.\n if (!besideOnLeft && !besideOnRight) {\n return { ...PLOT_MARGIN };\n }\n\n return {\n ...BASE_MARGIN,\n left: besideOnLeft ? LABEL_SIDE_INSET : BASE_MARGIN.left,\n };\n}\n\n/**\n * Format a conversion share the way the default `percent` label reads it:\n * `0.52 → \"52.0%\"`. Exported so a `percentFormatter` can wrap or replace it.\n */\nexport const funnelChartPercent: TickFormatter = (value) => {\n const n = typeof value === 'number' ? value : Number(value);\n return Number.isFinite(n) ? `${(n * 100).toFixed(1)}%` : String(value);\n};\n\n/**\n * Compose one stage's label text.\n *\n * `base` is the value the percentage is measured against — the funnel's widest\n * stage, not the sum of every stage. A funnel's stages are nested subsets of\n * each other rather than parts of a whole, so their values don't add up to\n * anything meaningful; the share that reads as information is the conversion\n * from the top of the funnel. (A pie's `percent` is the other way round — there\n * a slice really is a share of the total.)\n *\n * Only the numeric part goes through `formatter`, so a label and its tooltip can\n * share one formatter; the share goes through `percentFormatter`, so a locale\n * that doesn't write a bare `%` can replace it. The percent formats degrade to\n * the name (or to the value) rather than printing `NaN%` when there is nothing\n * to divide by.\n */\nexport function funnelChartLabelText(options: {\n name: string;\n value: number | string;\n base: number;\n format: FunnelChartLabelFormat;\n formatter?: TickFormatter;\n percentFormatter?: TickFormatter;\n}): string {\n const {\n name,\n value,\n base,\n format,\n formatter,\n percentFormatter = funnelChartPercent,\n } = options;\n const text = formatter ? formatter(value) : String(value);\n const numeric = typeof value === 'number' ? value : Number(value);\n const share =\n base > 0 && Number.isFinite(numeric)\n ? percentFormatter(numeric / base)\n : '';\n\n switch (format) {\n case 'name':\n return name;\n case 'value':\n return text;\n case 'percent':\n return share;\n case 'name-value':\n return `${name}: ${text}`;\n case 'name-percent':\n return share ? `${name}: ${share}` : name;\n case 'value-percent':\n return share ? `${text} (${share})` : text;\n }\n}\n\n// What recharts hands a custom `Funnel` `shape`: the trapezoid box it measured,\n// the presentation props it resolved (`fill` from the `Cell`, `stroke`), the\n// data row, and whether this stage is the hovered one.\ntype FunnelStageShapeProps = {\n x?: number;\n y?: number;\n upperWidth?: number;\n lowerWidth?: number;\n height?: number;\n fill?: string;\n stroke?: string;\n strokeWidth?: string | number;\n className?: string;\n isActive?: boolean;\n payload?: Record<string, unknown>;\n showActiveShape?: boolean;\n /**\n * Which stage sits at the top of the plot area, and so takes no gap above it.\n * Not always the first row: `reversed` flips the stack, which puts the *last*\n * stage at the top.\n */\n topStageIndex?: number;\n};\n\n/**\n * One funnel stage. Replaces recharts' `Trapezoid` because the design's stage\n * has two things it can't express: a 2px gap to the stage above and 2px rounded\n * corners.\n *\n * Safe to substitute — recharts puts the tooltip/click handlers on the `<g\n * className=\"recharts-funnel-trapezoid\">` that wraps this, not on the shape, so\n * hover and the tooltip keep working without any event plumbing here.\n */\nfunction FunnelStageShape({\n x = 0,\n y = 0,\n upperWidth = 0,\n lowerWidth = 0,\n height = 0,\n fill,\n stroke,\n strokeWidth,\n className,\n isActive,\n payload,\n showActiveShape,\n topStageIndex = 0,\n}: FunnelStageShapeProps) {\n const isTopStage = payload?.[STAGE_INDEX_KEY] === topStageIndex;\n const inset = funnelChartStageInset({\n x,\n y,\n upperWidth,\n lowerWidth,\n height,\n // The funnel's own top edge is not a seam, so only the stages below the\n // topmost one are pushed down: n stages give exactly n-1 gaps.\n gap: isTopStage ? 0 : STAGE_GAP,\n });\n const d = funnelChartStagePath(inset);\n if (!d) return null;\n\n const outlined = Boolean(isActive && showActiveShape);\n return (\n <path\n className={cn('recharts-funnel-stage', className)}\n d={d}\n fill={fill}\n stroke={outlined ? ACTIVE_STROKE : stroke}\n strokeWidth={outlined ? ACTIVE_STROKE_WIDTH : strokeWidth}\n />\n );\n}\n\nexport interface FunnelChartProps\n extends\n Omit<React.ComponentProps<'div'>, 'children'>,\n VariantProps<typeof funnelChartVariants>,\n ChartAnimationProps {\n /**\n * The dataviz palette the stages are painted from — the only source of a\n * stage's colour, bar a per-stage `stageSettings.color`. Defaults to\n * `FUNNEL_CHART_DEFAULT_PALETTE` (the sequential blue ramp), which is what\n * Figma paints the funnel with; a funnel's stages are an ordered series, so a\n * ramp reads them better than the shared categorical default.\n * See `ChartPalette`.\n */\n palette?: ChartPalette;\n /** Row-per-stage data. Each object holds the stage's `nameKey` label + its `dataKey` numeric value. */\n data: ReadonlyArray<Record<string, string | number>>;\n /**\n * Per-stage map of `label` / `icon` / `tone`, keyed by the stage's `nameKey`\n * value (imported from the shared `Chart` primitives). Turned into\n * `--color-<name>` custom properties. Series take their colour from the\n * container's `palette`; each entry maps a key to a `label` and an optional\n * `tone`.\n */\n config: ChartConfig;\n /** Numeric field that sizes each stage (the funnel narrows as it drops). */\n dataKey: string;\n /**\n * Label field that names each stage (drives the legend, tooltip, on-chart\n * labels, and the `--color-<name>` lookup). Values should be unique per chart —\n * stages sharing a name share one `config`/color entry.\n */\n nameKey: string;\n /** Flip the funnel so it widens toward the bottom instead of narrowing. */\n reversed?: boolean;\n /** Render a label for each stage — see `labelFormat` and `labelPosition`. */\n showLabels?: boolean;\n /**\n * What each stage's label says. `percent` is the stage's share of the widest\n * stage — its conversion from the top of the funnel.\n */\n labelFormat?: FunnelChartLabelFormat;\n /**\n * Where each stage's label sits. Defaults to `right`, beside the segment.\n * `inside` centres it on the segment, which only works while every stage is\n * wide enough to hold the text — a funnel narrows, so its last stages often\n * are not. Keep the text short there (`percent`) or leave the labels beside\n * the funnel.\n */\n labelPosition?: FunnelChartLabelPosition;\n /**\n * Render a second label carrying the stage's value, so the name and the number\n * can sit on opposite sides of the funnel.\n */\n showValueLabels?: boolean;\n /**\n * Where the value label sits. Defaults to the side opposite `labelPosition`,\n * where every stage has room — so it follows the names rather than pinning\n * itself to one edge. See `labelPosition` before choosing `inside`.\n */\n valuePosition?: FunnelChartLabelPosition;\n /**\n * Colour for both label lists, overriding the contrast-matched default (the\n * on-surface token beside the funnel, the on-fill token on a segment). Pass a\n * `--ui-*` token; only use it when the default doesn't work on your surface.\n */\n labelFill?: string;\n /** Format the numeric part of a label — pass the same formatter used elsewhere. */\n labelFormatter?: TickFormatter;\n /**\n * Format the conversion share behind the `percent` formats. Receives the share\n * as a fraction (`0.52`); defaults to `funnelChartPercent` (`\"52.0%\"`). Pass\n * `createTickFormatter({ style: 'percent', minimumFractionDigits: 1 }, locale)`\n * for a locale that doesn't write a bare `%`.\n */\n percentFormatter?: TickFormatter;\n /**\n * Render the stage list beside the funnel. On by default: the design's funnel\n * carries no on-plot labels, so the legend is where the stages are named.\n */\n showLegend?: boolean;\n /**\n * Font size of the legend text (stage names and values). Defaults to `'xs'` —\n * the size the legend has always rendered at. See `ChartLegendFontSize`.\n */\n legendFontSize?: ChartLegendFontSize;\n /** Format the value in each legend row — the stage's `dataKey` number. */\n legendValueFormatter?: (value: string | number) => string;\n /** Per-stage `color` / `hidden` overrides, keyed by the stage's `nameKey` value. */\n stageSettings?: Record<string, FunnelChartStageSettings>;\n /** Outline the hovered segment. */\n showActiveShape?: boolean;\n /**\n * Segment border colour. Reference an existing semantic `--ui-*` token.\n * Defaults to the border token when `strokeWidth` is set on its own.\n */\n stroke?: string;\n /** Segment border width, in px. Implies a default `stroke` when given alone. */\n strokeWidth?: number;\n /**\n * Funnel width — a number in px or a percentage of the plot area (`'70%'`).\n * Defaults to the full plot area, except that a composite `labelFormat` beside\n * the funnel narrows it to leave the label real room to wrap into.\n */\n funnelWidth?: number | string;\n /**\n * Plot-area margin, in px. Merged over the defaults per side, so passing one\n * side keeps the others.\n */\n margin?: { top?: number; right?: number; bottom?: number; left?: number };\n showTooltip?: boolean;\n /**\n * Replace the default tooltip. Pass a configured `ChartTooltipContent`\n * (imported from this library) — e.g. with a `formatter` / `labelFormatter` —\n * to customize formatting, per-series rows, or extra fields without composing\n * recharts yourself. Ignored when `showTooltip` is false.\n */\n tooltipContent?: React.ComponentProps<typeof ChartTooltip>['content'];\n}\n\nconst FunnelChart = React.forwardRef<HTMLDivElement, FunnelChartProps>(\n (\n {\n className,\n config,\n palette,\n data,\n dataKey,\n nameKey,\n lastShape = 'triangle',\n reversed = false,\n showLabels = false,\n labelFormat = 'name',\n labelPosition = 'right',\n showValueLabels = false,\n valuePosition,\n labelFill,\n labelFormatter,\n percentFormatter,\n showLegend = true,\n legendFontSize,\n legendValueFormatter,\n stageSettings,\n showActiveShape = false,\n stroke,\n strokeWidth,\n funnelWidth,\n margin,\n showTooltip = true,\n tooltipContent,\n animate,\n animationDuration,\n animationBegin,\n animationEasing,\n ...props\n },\n ref\n ) => {\n const animation = resolveAnimation({\n animate,\n animationDuration,\n animationBegin,\n animationEasing,\n });\n\n // Stamp each row with its `fill` and its label texts (the shadcn data-driven\n // pattern). A Funnel's default fill is grey (#808080) and recharts doesn't\n // carry a per-segment color on the tooltip/legend payload item, so putting the\n // color on the data row is what lets a real hover resolve each segment's\n // color. (The forced-open `defaultIndex` VR snapshot can still show a neutral\n // indicator — it synthesizes the open state without a pointer hover.)\n const seriesData = React.useMemo(() => {\n const visible = data.filter(\n (row) => !stageSettings?.[String(row[nameKey])]?.hidden\n );\n // The percentages are conversions from the funnel's widest stage, and\n // recharts sizes the trapezoids off `Math.max` of the values — so the base\n // is the largest visible value, not the first row. Taking the first row\n // would read as a conversion above 100% whenever the data isn't sorted\n // descending.\n const conversionBase = visible.reduce((widest, row) => {\n const value = Number(row[dataKey]);\n return Number.isFinite(value) && value > widest ? value : widest;\n }, 0);\n\n return visible.map((row, index) => {\n const name = String(row[nameKey]);\n const fill =\n stageSettings?.[name]?.color ?? `var(--color-${toCssKey(name)})`;\n const labelArgs = {\n name,\n value: row[dataKey],\n base: conversionBase,\n formatter: labelFormatter,\n percentFormatter,\n };\n\n return {\n ...row,\n fill,\n [STAGE_INDEX_KEY]: index,\n [STAGE_LABEL_KEY]: funnelChartLabelText({\n ...labelArgs,\n format: labelFormat,\n }),\n [STAGE_VALUE_LABEL_KEY]: funnelChartLabelText({\n ...labelArgs,\n format: 'value',\n }),\n } as Record<string, string | number>;\n });\n }, [\n data,\n dataKey,\n labelFormat,\n labelFormatter,\n nameKey,\n percentFormatter,\n stageSettings,\n ]);\n\n // The legend sits *outside* `ChartContainer`, beside the plot — so it can't\n // read the `--color-<name>` custom properties `ChartStyle` scopes to\n // `[data-chart=…]`. Resolving the palette here is what gives its markers the\n // same colours the stages paint with, the way `PieChart` and\n // `RadialBarChart` already do for their side legends.\n const resolvedConfigForLegend = React.useMemo(\n () =>\n showLegend\n ? resolveChartColors(config, palette ?? FUNNEL_CHART_DEFAULT_PALETTE)\n : null,\n [showLegend, config, palette]\n );\n\n // recharts 3 builds the legend payload from the graphical item, and `Funnel`\n // — unlike Bar/Line/Area/Pie/Radar/RadialBar/Scatter — never registers one,\n // so a `<Legend>` inside a `FunnelChart` renders empty. The payload is\n // synthesized from the visible stages instead and handed to the shared\n // `ChartLegendContent`, which keeps the funnel on the same legend markers,\n // labels and `config` lookup as every other chart. `payload` carries the row\n // so each entry resolves its own `config` entry via `nameKey`.\n //\n // One entry per *distinct* stage name: same-named stages deliberately share a\n // `config` entry, so a second entry would repeat the first verbatim — and\n // `ChartLegendContent` keys its entries on `value`, so it would also be a\n // duplicate React key.\n const legendPayload = React.useMemo<LegendPayload[]>(() => {\n if (!resolvedConfigForLegend) return [];\n const seen = new Set<string>();\n return seriesData.flatMap((row) => {\n const value = String(row[nameKey]);\n if (seen.has(value)) return [];\n seen.add(value);\n return [\n {\n value,\n dataKey: nameKey,\n type: 'rect' as const,\n // A `stageSettings` colour is a real colour and paints as-is; every\n // other stage takes its resolved palette stop.\n color:\n stageSettings?.[value]?.color ??\n resolvedConfigForLegend[value]?.color ??\n String(row.fill),\n payload: row,\n },\n ];\n });\n }, [nameKey, seriesData, resolvedConfigForLegend, stageSettings]);\n\n const resolvedValuePosition =\n valuePosition ?? funnelChartOppositeSide(labelPosition);\n\n // When labels sit beside the funnel (not on the segments), the 120px plot\n // is too narrow: the label margins eat the whole width and leave 0px for the\n // funnel. Make the plot grow to fill available width in that case; the fixed\n // 120px square is only for the default \"no outside labels\" layout.\n const hasOutsideLabels =\n (showLabels && labelPosition !== 'inside') ||\n (showValueLabels && resolvedValuePosition !== 'inside');\n\n const stagePosition = LABEL_POSITION[labelPosition];\n const valueLabelPosition = LABEL_POSITION[resolvedValuePosition];\n const plotMargin = {\n ...funnelChartLabelMargin({\n showLabels,\n labelPosition,\n showValueLabels,\n valuePosition: resolvedValuePosition,\n }),\n ...margin,\n };\n // A caller-supplied `funnelWidth` wins; otherwise a composite label beside the\n // funnel narrows it to leave itself room to wrap into.\n const resolvedFunnelWidth =\n funnelWidth ??\n funnelChartLabelReserve({ showLabels, labelPosition, labelFormat });\n // recharts defaults a Funnel's stroke to a hardcoded `#fff`.\n // ChartContainer's CSS neutralizer targets `.recharts-trapezoid`, but our\n // custom shape renders as `.recharts-funnel-stage`, so the neutralizer\n // never matches. Explicitly default to `'none'` to suppress the white\n // outline — and pair a bare `strokeWidth` with the border token so it\n // doesn't widen an invisible border.\n const resolvedStroke =\n stroke ??\n (strokeWidth != null ? 'var(--ui-border-on-surface-border)' : 'none');\n // One renderer for both slots: recharts swaps in `activeShape` for the\n // hovered stage, so leaving it unset would drop back to its own square-\n // cornered, gapless `Trapezoid` on hover.\n const renderStage = (stageProps: FunnelStageShapeProps) => (\n <FunnelStageShape\n {...stageProps}\n showActiveShape={showActiveShape}\n // `reversed` stacks the funnel the other way up, so the stage with no\n // gap above it is the last row rather than the first.\n topStageIndex={reversed ? seriesData.length - 1 : 0}\n />\n );\n\n return (\n <div\n ref={ref}\n data-last-shape={lastShape}\n className={cn(\n // The design's funnel is a row: a square plot, a 16px gutter, then the\n // legend taking whatever is left — so the component fills its parent's\n // width without the plot stretching into a tall, narrow wedge.\n 'flex flex-row items-center gap-4',\n !showLegend && 'justify-center',\n funnelChartVariants({ lastShape }),\n className\n )}\n {...props}\n >\n <div\n className={\n hasOutsideLabels\n ? 'h-[120px] flex-1'\n : cn(PLOT_SIZE_CLASS, 'shrink-0')\n }\n >\n <ChartContainer\n config={config}\n palette={palette ?? FUNNEL_CHART_DEFAULT_PALETTE}\n className=\"size-full\"\n >\n <RechartsFunnelChart margin={plotMargin}>\n {showTooltip && (\n <ChartTooltip\n content={\n tooltipContent ?? (\n <ChartTooltipContent nameKey={nameKey} hideLabel />\n )\n }\n />\n )}\n <Funnel\n dataKey={dataKey}\n nameKey={nameKey}\n data={seriesData}\n lastShapeType={lastShape ?? 'triangle'}\n reversed={reversed}\n width={resolvedFunnelWidth}\n stroke={resolvedStroke}\n strokeWidth={strokeWidth}\n shape={renderStage}\n activeShape={renderStage}\n {...animation}\n >\n {seriesData.map((entry, index) => (\n // Keyed by index, not the name: two stages could share a nameKey\n // value, which would collide as a React key. Same-named stages\n // intentionally share a color/config entry via `--color-<name>`.\n <Cell key={index} fill={String(entry.fill)} />\n ))}\n {showLabels && (\n <LabelList\n position={stagePosition}\n dataKey={STAGE_LABEL_KEY}\n className={\n labelFill\n ? undefined\n : resolveLabelFillClass(stagePosition)\n }\n fill={labelFill}\n stroke=\"none\"\n />\n )}\n {showValueLabels && (\n <LabelList\n position={valueLabelPosition}\n dataKey={STAGE_VALUE_LABEL_KEY}\n className={\n labelFill\n ? undefined\n : resolveLabelFillClass(valueLabelPosition)\n }\n fill={labelFill}\n stroke=\"none\"\n />\n )}\n </Funnel>\n </RechartsFunnelChart>\n </ChartContainer>\n </div>\n {showLegend && resolvedConfigForLegend && (\n <ChartLegendContent\n variant=\"list\"\n payload={legendPayload}\n config={resolvedConfigForLegend}\n nameKey={nameKey}\n fontSize={legendFontSize}\n valueKey={dataKey}\n valueFormatter={legendValueFormatter}\n // Figma paints the funnel legend's value in the primary text token,\n // not the link token the donut/radial legends use for theirs.\n valueClassName=\"text-[var(--ui-text-on-surface-primary)]\"\n className=\"min-w-0 flex-1\"\n />\n )}\n </div>\n );\n }\n);\nFunnelChart.displayName = 'FunnelChart';\n\nexport { FunnelChart, funnelChartVariants };\n"],"mappings":";;;;;;;;;AAqCA,IAAM,IAAsB,EAAI,IAAI;CAClC,UAAU,EACR,WAAW;EACT,UAAU;EACV,WAAW;CACb,EACF;CACA,iBAAiB,EACf,WAAW,WACb;AACF,CAAC,GAkCK,IAGF;CACF,OAAO;CACP,MAAM;CACN,QAAQ;AACV;AAWA,SAAgB,EACd,GAC0B;CAC1B,QAAQ,GAAR;EACE,KAAK,SACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,UACH,OAAO;CACX;AACF;AAMA,IAAM,IAAkB,gBAClB,IAAwB,qBAKxB,IAAkB,gBAIlB,IAAgB,6CAChB,IAAsB,GActB,KAAkB,gBAUlB,IAAY,GAGZ,IAAe,GAUf,IAAsB,GAOtB,IAAc;CAAE,KAAK;CAAG,OAAO;CAAG,QAAQ;CAAG,MAAM;AAAE,GAU9C,IAA6C,OAAO,OAAO;CACtE,MAAM;CACN,MAAM;AACR,CAAC,GAIK,KAAY,GAAe,MAC/B,KAAK,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE;AAGrC,SAAS,EAAM,GAAkB,GAAgB,GAAuB;CACtE,IAAM,IAAS,EAAS,GAAM,CAAE;CAEhC,OADI,MAAW,IAAU,IAClB,CACL,EAAK,MAAO,EAAG,KAAK,EAAK,MAAM,IAAK,GACpC,EAAK,MAAO,EAAG,KAAK,EAAK,MAAM,IAAK,CACtC;AACF;AAIA,IAAM,KAAS,CAAC,GAAG,OACjB,GAAG,OAAO,EAAE,QAAQ,CAAC,CAAC,EAAE,GAAG,OAAO,EAAE,QAAQ,CAAC,CAAC;AAWhD,SAAS,EACP,GACA,GACQ;CACR,IAAM,IAAQ,EAAO;CACrB,IAAI,IAAQ,GAAG,OAAO;CAE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A;EACb,CAAA,GACJ,KAAc,KACb,kBAAC,GAAD;GACE,SAAQ;GACR,SAAS;GACT,QAAQ;GACC;GACT,UAAU;GACV,UAAU;GACV,gBAAgB;GAGhB,gBAAe;GACf,WAAU;EACX,CAAA,CAEA;;AAET,CACF;AACA,EAAY,cAAc"}
|
|
1
|
+
{"version":3,"file":"funnel-chart.js","names":[],"sources":["../../../../src/components/ui/funnel-chart/funnel-chart.tsx"],"sourcesContent":["'use client';\n\nimport * as React from 'react';\nimport { cva, type VariantProps } from 'class-variance-authority';\nimport {\n Cell,\n Funnel,\n FunnelChart as RechartsFunnelChart,\n LabelList,\n} from 'recharts';\nimport type { LegendPayload } from 'recharts/types/component/DefaultLegendContent';\n\nimport { cn } from '@/lib/utils';\nimport {\n ChartContainer,\n ChartLegendContent,\n ChartTooltip,\n ChartTooltipContent,\n resolveAnimation,\n resolveChartColors,\n resolveLabelFillClass,\n toCssKey,\n type ChartAnimationProps,\n type ChartConfig,\n type ChartLegendFontSize,\n type ChartLegendAriaLabelProps,\n type ChartPalette,\n type TickFormatter,\n} from '../chart';\n\n// A typed recharts composition over the shared `Chart` primitives. The single\n// CVA axis is the design's Funnel-chart variant set: `lastShape` (does the\n// funnel narrow to a point — `triangle` — or end flat — `rectangle`). The class\n// stays empty because recharts' SVG — not CSS — draws the funnel: `lastShape`\n// drives the `<Funnel>`'s `lastShapeType`. CVA is kept so the variant set is a\n// first-class, spec-conformant part of the API (matched against ui-spec's\n// api.yaml enums) and exposed via `VariantProps`; the resolved value is also\n// mirrored onto `data-last-shape`.\nconst funnelChartVariants = cva('', {\n variants: {\n lastShape: {\n triangle: '',\n rectangle: '',\n },\n },\n defaultVariants: {\n lastShape: 'triangle',\n },\n});\n\n/** Where a stage's label sits relative to its segment. */\nexport type FunnelChartLabelPosition = 'right' | 'left' | 'inside';\n\n/** What a stage's label says. */\nexport type FunnelChartLabelFormat =\n | 'name'\n | 'value'\n | 'percent'\n | 'name-value'\n | 'name-percent'\n | 'value-percent';\n\n/** Override for a single stage, keyed by its `nameKey` value. */\nexport interface FunnelChartStageSettings {\n /**\n * Paint this stage with a colour of its own instead of its `palette` stop —\n * the same per-item escape hatch `PieChart`'s `sliceSettings` offers.\n * Reference an existing semantic `--ui-*` token.\n */\n color?: string;\n /**\n * Drop the stage from the funnel — and from the legend, labels and the\n * conversion percentages, which are computed over the visible stages only.\n */\n hidden?: boolean;\n}\n\n// recharts' `LabelList` positions that a funnel trapezoid understands. `inside`\n// is recharts' `center`: a trapezoid has no `insideLeft`/`insideTop` anchor, so\n// centring is the only on-segment placement. `outside` is not offered — for a\n// funnel it would mean \"beside the segment\", which is what `right`/`left`\n// already are, and recharts' polar `outside` doesn't apply to a trapezoid.\nconst LABEL_POSITION: Record<\n FunnelChartLabelPosition,\n 'right' | 'left' | 'center'\n> = {\n right: 'right',\n left: 'left',\n inside: 'center',\n};\n\n/**\n * Where the value labels sit when the caller doesn't say: opposite the names, so\n * the two lists never stack on the same edge. `inside` names sit on the segments\n * and leave both edges free, so the values take the default `right`.\n *\n * A static default can't do this — `valuePosition=\"left\"` beside\n * `labelPosition=\"left\"` draws both lists at the same anchor, overprinting the\n * name with its own value.\n */\nexport function funnelChartOppositeSide(\n labelPosition: FunnelChartLabelPosition\n): FunnelChartLabelPosition {\n switch (labelPosition) {\n case 'right':\n return 'left';\n case 'left':\n return 'right';\n case 'inside':\n return 'right';\n }\n}\n\n// Synthetic row fields the two label lists read. A `LabelList` resolves its text\n// from a `dataKey`, and its `formatter` only ever sees that one field's value —\n// so a composite label (\"Signups: 52.0%\") has to be composed onto the row before\n// recharts sees it, the same way `fill` already is.\nconst STAGE_LABEL_KEY = '__stageLabel';\nconst STAGE_VALUE_LABEL_KEY = '__stageValueLabel';\n\n// Which stage this row is. recharts hands a custom `shape` the data row as\n// `payload` but no index, and the first stage is the one that must *not* be\n// pushed down — its top edge is the top of the funnel.\nconst STAGE_INDEX_KEY = '__stageIndex';\n\n// Hover highlight for `showActiveShape` — an outline rather than a fill change,\n// so the segment keeps the colour that ties it to its legend entry and label.\nconst ACTIVE_STROKE = 'var(--ui-border-on-surface-border-active)';\nconst ACTIVE_STROKE_WIDTH = 2;\n\n/**\n * The design's funnel plot: a 120×120 square beside its legend — the same\n * geometry `ChartDonut` uses in Figma, which is why `PieChart` and\n * `RadialBarChart` size their plot exactly this way too.\n *\n * The *component* is still parent-responsive: the root is a flex row whose\n * legend column takes every pixel the plot doesn't, so a funnel widens with its\n * widget instead of the plot growing into a tall, narrow wedge.\n *\n * Figma: `8811:175245` → `Chart` is `size-[120px]`, `gap-[16px]`, legend\n * `flex-[1_0_0]`.\n */\nconst PLOT_SIZE_CLASS = 'size-[120px]';\n\n/**\n * Surface showing between two stages, in px. recharts draws the stages flush —\n * `Funnel` has no gap prop and `Trapezoid` no radius — so both come from the\n * custom `shape` below.\n *\n * Figma `8811:175245` stacks the stages at y = 4 / 34 / 64 / 94 with shapes 28\n * tall: a 2px gap, three times over for four stages.\n */\nconst STAGE_GAP = 2;\n\n/** Corner rounding on the two upper edges of each stage (Figma: ~2px clip along the top edge). */\nconst STAGE_RADIUS = 2;\n\n/**\n * Corner rounding on the two lower edges of each stage.\n *\n * Figma's bottom corners clip ~0.85px — significantly less than the upper\n * corners. The asymmetry is intentional: the diagonal-meets-flat-bottom\n * transition is shallow, so a smaller radius keeps it from looking over-rounded\n * at the narrow tail of the funnel. 1px is the nearest integer match.\n */\nconst STAGE_BOTTOM_RADIUS = 1;\n\n/**\n * The plot-area inset when nothing sits beside the funnel. Figma's widest stage\n * spans 102.67 of the 120px box and the stack runs y=4 → ~115.7, i.e. ~8px of\n * horizontal and 4px of vertical breathing room.\n */\nconst PLOT_MARGIN = { top: 4, right: 8, bottom: 4, left: 8 };\n\n/**\n * The palette Figma paints the funnel from: the sequential blue ramp, whose\n * stops read as one quantity falling down the funnel. Every other chart keeps\n * the shared categorical default — a funnel's stages are an *ordered* series,\n * which is what a sequential ramp is for.\n *\n * Figma `8811:175245` uses `dataviz/sequential/blue/{2,4,6,8}`.\n */\nexport const FUNNEL_CHART_DEFAULT_PALETTE: ChartPalette = Object.freeze({\n type: 'sequential',\n ramp: 'blue',\n});\n\ntype StagePoint = readonly [number, number];\n\nconst distance = (a: StagePoint, b: StagePoint) =>\n Math.hypot(b[0] - a[0], b[1] - a[1]);\n\n/** A point `d` px from `from` along the segment toward `to`. */\nfunction along(from: StagePoint, to: StagePoint, d: number): StagePoint {\n const length = distance(from, to);\n if (length === 0) return from;\n return [\n from[0] + ((to[0] - from[0]) * d) / length,\n from[1] + ((to[1] - from[1]) * d) / length,\n ];\n}\n\n// Trimmed to 3dp so the emitted `d` is stable across platforms — a raw float\n// makes every visual-regression baseline and DOM assertion renderer-dependent.\nconst coord = ([x, y]: StagePoint) =>\n `${Number(x.toFixed(3))},${Number(y.toFixed(3))}`;\n\n/**\n * A closed polygon with rounded corners, as an SVG path.\n *\n * Each corner is trimmed back along both of its edges and bridged with a\n * quadratic curve through the original vertex. The radius is clamped to half of\n * either adjacent edge, so two corners can never overrun each other on a short\n * edge — which is the normal case at the bottom of a funnel, where the last\n * stages are only a few px wide.\n */\nfunction roundedPolygonPath(\n points: readonly StagePoint[],\n radius: number | readonly number[]\n): string {\n const count = points.length;\n if (count < 3) return '';\n\n let path = '';\n for (let i = 0; i < count; i++) {\n const r = typeof radius === 'number' ? radius : radius[i];\n const previous = points[(i - 1 + count) % count];\n const current = points[i];\n const next = points[(i + 1) % count];\n const corner = Math.max(\n 0,\n Math.min(\n r,\n distance(previous, current) / 2,\n distance(current, next) / 2\n )\n );\n const entry = along(current, previous, corner);\n const exit = along(current, next, corner);\n path += `${i === 0 ? 'M' : ' L'} ${coord(entry)}`;\n path += ` Q ${coord(current)} ${coord(exit)}`;\n }\n return `${path} Z`;\n}\n\n/**\n * The `d` for one funnel stage — recharts' trapezoid geometry with the design's\n * rounded corners.\n *\n * `x`/`y` is the top-left of the *upper* edge and the shape is centred on\n * `x + upperWidth / 2`, matching recharts' own `getTrapezoidPath`.\n *\n * Either edge can collapse to a single rounded apex rather than a zero-length\n * one — the `triangle` last shape narrows to a point at the bottom, and a\n * `reversed` funnel stands that same triangle on its head at the top.\n */\nexport function funnelChartStagePath(options: {\n x: number;\n y: number;\n upperWidth: number;\n lowerWidth: number;\n height: number;\n /**\n * Uniform corner radius — applies to all four corners. Overridden per-side\n * by `topRadius` / `bottomRadius`. When absent, defaults to\n * `STAGE_RADIUS` (top) and `STAGE_BOTTOM_RADIUS` (bottom).\n */\n radius?: number;\n /** Radius for the two upper corners (default: `STAGE_RADIUS = 2`). */\n topRadius?: number;\n /**\n * Radius for the two lower corners (default: `STAGE_BOTTOM_RADIUS = 1`).\n *\n * Figma's bottom corners clip ~0.85px — much smaller than the upper ones —\n * so the default is intentionally lower than `topRadius`.\n */\n bottomRadius?: number;\n}): string {\n const { x, y, upperWidth, lowerWidth, height } = options;\n // `radius` is a backward-compat shorthand for all corners.\n // Per-side props win; if only `radius` is given it applies to both sides.\n // If nothing is given, use the asymmetric Figma defaults.\n const uniformRadius = options.radius;\n const topRadius = options.topRadius ?? uniformRadius ?? STAGE_RADIUS;\n const bottomRadius =\n options.bottomRadius ?? uniformRadius ?? STAGE_BOTTOM_RADIUS;\n\n if (height <= 0 || (upperWidth <= 0 && lowerWidth <= 0)) return '';\n\n const centre = x + upperWidth / 2;\n const upper: StagePoint[] =\n upperWidth <= 0\n ? [[centre, y]]\n : [\n [x, y],\n [x + upperWidth, y],\n ];\n const lower: StagePoint[] =\n lowerWidth <= 0\n ? [[centre, y + height]]\n : [\n [centre + lowerWidth / 2, y + height],\n [centre - lowerWidth / 2, y + height],\n ];\n\n // Upper points get topRadius, lower points get bottomRadius — matching\n // Figma's intentional asymmetry (the diagonal-meets-bottom transition\n // uses a much smaller clip than the diagonal-meets-top one).\n const radii: number[] = [\n ...upper.map(() => topRadius),\n ...lower.map(() => bottomRadius),\n ];\n return roundedPolygonPath([...upper, ...lower], radii);\n}\n\n/**\n * Pull a stage's **top** edge down by `gap`, so surface shows between it and the\n * stage above.\n *\n * The top rather than the bottom on purpose: the bottom edge is what\n * `lastShapeType` defines — the triangle's apex — so leaving it exactly where\n * recharts put it keeps a `triangle` funnel ending in a real point instead of a\n * blunt 2px edge. The upper edge slides down the funnel's own slope, so the\n * taper is unchanged rather than steepened.\n *\n * A stage with no room for the gap is returned untouched: better a missing gap\n * than an inverted shape.\n */\nexport function funnelChartStageInset(options: {\n x: number;\n y: number;\n upperWidth: number;\n lowerWidth: number;\n height: number;\n gap: number;\n}) {\n const { x, y, upperWidth, lowerWidth, height, gap } = options;\n if (gap <= 0 || height <= gap) {\n return { x, y, upperWidth, lowerWidth, height };\n }\n\n const insetUpperWidth =\n upperWidth + ((lowerWidth - upperWidth) * gap) / height;\n return {\n x: x + upperWidth / 2 - insetUpperWidth / 2,\n y: y + gap,\n upperWidth: insetUpperWidth,\n lowerWidth,\n height: height - gap,\n };\n}\n\n// The inset reserved on whichever side a label list sits. It is *not* label\n// room — see `funnelChartLabelReserve` for why — but a label whose text can't\n// wrap (one long word) does overflow past the plot edge, and this is what keeps\n// that overflow inside the SVG.\nconst LABEL_SIDE_INSET = 96;\n\n// The plot-area margin a funnel has always been drawn with: the right side\n// reserved, the left not.\nconst BASE_MARGIN = {\n top: 8,\n right: LABEL_SIDE_INSET,\n bottom: 8,\n left: 24,\n};\n\n/**\n * Share of the plot area handed to the funnel when a composite label sits to its\n * right. The rest becomes real label room — see `funnelChartLabelReserve`.\n *\n * A percentage, not a pixel count: the plot area is responsive, and recharts\n * resolves `Funnel`'s `width` against it, so a ratio keeps the reserve\n * proportional at every chart size.\n */\nconst COMPOSITE_FUNNEL_WIDTH = '75%';\n\n/** A label format that pairs two fields, so its text is roughly twice as wide. */\nfunction isCompositeFormat(format: FunnelChartLabelFormat): boolean {\n return format.includes('-');\n}\n\n/**\n * Reserve room for a composite label beside the funnel, by narrowing the\n * **funnel** rather than the plot area.\n *\n * recharts word-wraps a label against the space between its trapezoid's\n * mid-height edge and the *plot area* edge (`getCartesianPosition` clamps\n * `width` to `parentViewBox`, which `Funnel` sets to the plot box). A margin\n * shrinks the plot area and the funnel inside it in lockstep, so widening\n * `margin.right` moves the clamp edge *inward* and leaves a composite label\n * with less room, not more — the reserved strip sits outside `parentViewBox`\n * where the text can never reach it.\n *\n * `Funnel`'s `width` is the lever that works: it scales the funnel within the\n * plot area while `parentViewBox` stays put, and because recharts anchors the\n * funnel at the plot area's left edge (`offsetX = offset.left`), everything it\n * frees lands on the right. Narrowing the funnel to\n * `COMPOSITE_FUNNEL_WIDTH` turns ~35px of wrap width into ~140px on a 460px\n * chart.\n *\n * Returns `undefined` — i.e. leave the funnel at its full width — for every\n * other case, so a funnel with plain labels, no labels, or `inside` labels keeps\n * exactly the geometry it has always had.\n *\n * There is no equivalent lever for `labelPosition=\"left\"`: the widest trapezoid\n * always starts flush at the plot area's left edge, so a left-hand label is\n * bounded by how sharply the funnel narrows and narrowing it further only makes\n * that worse. Composite left-hand labels wrap; that's a recharts limitation, not\n * a tuning choice.\n *\n * A caller-supplied `funnelWidth` always wins — this is only the default.\n */\nexport function funnelChartLabelReserve(options: {\n showLabels: boolean;\n labelPosition: FunnelChartLabelPosition;\n labelFormat: FunnelChartLabelFormat;\n}): string | undefined {\n const { showLabels, labelPosition, labelFormat } = options;\n return showLabels &&\n labelPosition === 'right' &&\n isCompositeFormat(labelFormat)\n ? COMPOSITE_FUNNEL_WIDTH\n : undefined;\n}\n\n/**\n * The plot-area margin.\n *\n * With nothing beside the funnel — the default, and what Figma draws — the plot\n * is the design's own inset (`PLOT_MARGIN`): just the few px the rounded corners\n * and the apex need, so the funnel fills its 120px square instead of being\n * squeezed into the middle by label room it isn't using.\n *\n * As soon as a label list *does* sit beside the funnel, the side insets come\n * back: this is overflow protection, not label room — the wrap width comes from\n * `funnelChartLabelReserve`. A caller-supplied `margin` is merged over these\n * defaults per side, so `margin={{ right: 160 }}` keeps the default top, bottom\n * and left rather than collapsing them to zero.\n */\nexport function funnelChartLabelMargin(options: {\n showLabels: boolean;\n labelPosition: FunnelChartLabelPosition;\n showValueLabels: boolean;\n valuePosition: FunnelChartLabelPosition;\n}) {\n const { showLabels, labelPosition, showValueLabels, valuePosition } = options;\n const stageLabelAt = showLabels ? labelPosition : undefined;\n const valueLabelAt = showValueLabels ? valuePosition : undefined;\n const besideOnLeft = stageLabelAt === 'left' || valueLabelAt === 'left';\n const besideOnRight = stageLabelAt === 'right' || valueLabelAt === 'right';\n\n // `inside` labels sit on the segments, so they count as \"nothing beside the\n // funnel\" and keep the tight design margin too.\n if (!besideOnLeft && !besideOnRight) {\n return { ...PLOT_MARGIN };\n }\n\n return {\n ...BASE_MARGIN,\n left: besideOnLeft ? LABEL_SIDE_INSET : BASE_MARGIN.left,\n };\n}\n\n/**\n * Format a conversion share the way the default `percent` label reads it:\n * `0.52 → \"52.0%\"`. Exported so a `percentFormatter` can wrap or replace it.\n */\nexport const funnelChartPercent: TickFormatter = (value) => {\n const n = typeof value === 'number' ? value : Number(value);\n return Number.isFinite(n) ? `${(n * 100).toFixed(1)}%` : String(value);\n};\n\n/**\n * Compose one stage's label text.\n *\n * `base` is the value the percentage is measured against — the funnel's widest\n * stage, not the sum of every stage. A funnel's stages are nested subsets of\n * each other rather than parts of a whole, so their values don't add up to\n * anything meaningful; the share that reads as information is the conversion\n * from the top of the funnel. (A pie's `percent` is the other way round — there\n * a slice really is a share of the total.)\n *\n * Only the numeric part goes through `formatter`, so a label and its tooltip can\n * share one formatter; the share goes through `percentFormatter`, so a locale\n * that doesn't write a bare `%` can replace it. The percent formats degrade to\n * the name (or to the value) rather than printing `NaN%` when there is nothing\n * to divide by.\n */\nexport function funnelChartLabelText(options: {\n name: string;\n value: number | string;\n base: number;\n format: FunnelChartLabelFormat;\n formatter?: TickFormatter;\n percentFormatter?: TickFormatter;\n}): string {\n const {\n name,\n value,\n base,\n format,\n formatter,\n percentFormatter = funnelChartPercent,\n } = options;\n const text = formatter ? formatter(value) : String(value);\n const numeric = typeof value === 'number' ? value : Number(value);\n const share =\n base > 0 && Number.isFinite(numeric)\n ? percentFormatter(numeric / base)\n : '';\n\n switch (format) {\n case 'name':\n return name;\n case 'value':\n return text;\n case 'percent':\n return share;\n case 'name-value':\n return `${name}: ${text}`;\n case 'name-percent':\n return share ? `${name}: ${share}` : name;\n case 'value-percent':\n return share ? `${text} (${share})` : text;\n }\n}\n\n// What recharts hands a custom `Funnel` `shape`: the trapezoid box it measured,\n// the presentation props it resolved (`fill` from the `Cell`, `stroke`), the\n// data row, and whether this stage is the hovered one.\ntype FunnelStageShapeProps = {\n x?: number;\n y?: number;\n upperWidth?: number;\n lowerWidth?: number;\n height?: number;\n fill?: string;\n stroke?: string;\n strokeWidth?: string | number;\n className?: string;\n isActive?: boolean;\n payload?: Record<string, unknown>;\n showActiveShape?: boolean;\n /**\n * Which stage sits at the top of the plot area, and so takes no gap above it.\n * Not always the first row: `reversed` flips the stack, which puts the *last*\n * stage at the top.\n */\n topStageIndex?: number;\n};\n\n/**\n * One funnel stage. Replaces recharts' `Trapezoid` because the design's stage\n * has two things it can't express: a 2px gap to the stage above and 2px rounded\n * corners.\n *\n * Safe to substitute — recharts puts the tooltip/click handlers on the `<g\n * className=\"recharts-funnel-trapezoid\">` that wraps this, not on the shape, so\n * hover and the tooltip keep working without any event plumbing here.\n */\nfunction FunnelStageShape({\n x = 0,\n y = 0,\n upperWidth = 0,\n lowerWidth = 0,\n height = 0,\n fill,\n stroke,\n strokeWidth,\n className,\n isActive,\n payload,\n showActiveShape,\n topStageIndex = 0,\n}: FunnelStageShapeProps) {\n const isTopStage = payload?.[STAGE_INDEX_KEY] === topStageIndex;\n const inset = funnelChartStageInset({\n x,\n y,\n upperWidth,\n lowerWidth,\n height,\n // The funnel's own top edge is not a seam, so only the stages below the\n // topmost one are pushed down: n stages give exactly n-1 gaps.\n gap: isTopStage ? 0 : STAGE_GAP,\n });\n const d = funnelChartStagePath(inset);\n if (!d) return null;\n\n const outlined = Boolean(isActive && showActiveShape);\n return (\n <path\n className={cn('recharts-funnel-stage', className)}\n d={d}\n fill={fill}\n stroke={outlined ? ACTIVE_STROKE : stroke}\n strokeWidth={outlined ? ACTIVE_STROKE_WIDTH : strokeWidth}\n />\n );\n}\n\nexport interface FunnelChartProps\n extends\n Omit<React.ComponentProps<'div'>, 'children'>,\n VariantProps<typeof funnelChartVariants>,\n ChartAnimationProps,\n ChartLegendAriaLabelProps {\n /**\n * The dataviz palette the stages are painted from — the only source of a\n * stage's colour, bar a per-stage `stageSettings.color`. Defaults to\n * `FUNNEL_CHART_DEFAULT_PALETTE` (the sequential blue ramp), which is what\n * Figma paints the funnel with; a funnel's stages are an ordered series, so a\n * ramp reads them better than the shared categorical default.\n * See `ChartPalette`.\n */\n palette?: ChartPalette;\n /** Row-per-stage data. Each object holds the stage's `nameKey` label + its `dataKey` numeric value. */\n data: ReadonlyArray<Record<string, string | number>>;\n /**\n * Per-stage map of `label` / `icon` / `tone`, keyed by the stage's `nameKey`\n * value (imported from the shared `Chart` primitives). Turned into\n * `--color-<name>` custom properties. Series take their colour from the\n * container's `palette`; each entry maps a key to a `label` and an optional\n * `tone`.\n */\n config: ChartConfig;\n /** Numeric field that sizes each stage (the funnel narrows as it drops). */\n dataKey: string;\n /**\n * Label field that names each stage (drives the legend, tooltip, on-chart\n * labels, and the `--color-<name>` lookup). Values should be unique per chart —\n * stages sharing a name share one `config`/color entry.\n */\n nameKey: string;\n /** Flip the funnel so it widens toward the bottom instead of narrowing. */\n reversed?: boolean;\n /** Render a label for each stage — see `labelFormat` and `labelPosition`. */\n showLabels?: boolean;\n /**\n * What each stage's label says. `percent` is the stage's share of the widest\n * stage — its conversion from the top of the funnel.\n */\n labelFormat?: FunnelChartLabelFormat;\n /**\n * Where each stage's label sits. Defaults to `right`, beside the segment.\n * `inside` centres it on the segment, which only works while every stage is\n * wide enough to hold the text — a funnel narrows, so its last stages often\n * are not. Keep the text short there (`percent`) or leave the labels beside\n * the funnel.\n */\n labelPosition?: FunnelChartLabelPosition;\n /**\n * Render a second label carrying the stage's value, so the name and the number\n * can sit on opposite sides of the funnel.\n */\n showValueLabels?: boolean;\n /**\n * Where the value label sits. Defaults to the side opposite `labelPosition`,\n * where every stage has room — so it follows the names rather than pinning\n * itself to one edge. See `labelPosition` before choosing `inside`.\n */\n valuePosition?: FunnelChartLabelPosition;\n /**\n * Colour for both label lists, overriding the contrast-matched default (the\n * on-surface token beside the funnel, the on-fill token on a segment). Pass a\n * `--ui-*` token; only use it when the default doesn't work on your surface.\n */\n labelFill?: string;\n /** Format the numeric part of a label — pass the same formatter used elsewhere. */\n labelFormatter?: TickFormatter;\n /**\n * Format the conversion share behind the `percent` formats. Receives the share\n * as a fraction (`0.52`); defaults to `funnelChartPercent` (`\"52.0%\"`). Pass\n * `createTickFormatter({ style: 'percent', minimumFractionDigits: 1 }, locale)`\n * for a locale that doesn't write a bare `%`.\n */\n percentFormatter?: TickFormatter;\n /**\n * Render the stage list beside the funnel. On by default: the design's funnel\n * carries no on-plot labels, so the legend is where the stages are named.\n */\n showLegend?: boolean;\n /**\n * Font size of the legend text (stage names and values). Defaults to `'xs'` —\n * the size the legend has always rendered at. See `ChartLegendFontSize`.\n */\n legendFontSize?: ChartLegendFontSize;\n /** Format the value in each legend row — the stage's `dataKey` number. */\n legendValueFormatter?: (value: string | number) => string;\n /** Per-stage `color` / `hidden` overrides, keyed by the stage's `nameKey` value. */\n stageSettings?: Record<string, FunnelChartStageSettings>;\n /** Outline the hovered segment. */\n showActiveShape?: boolean;\n /**\n * Segment border colour. Reference an existing semantic `--ui-*` token.\n * Defaults to the border token when `strokeWidth` is set on its own.\n */\n stroke?: string;\n /** Segment border width, in px. Implies a default `stroke` when given alone. */\n strokeWidth?: number;\n /**\n * Funnel width — a number in px or a percentage of the plot area (`'70%'`).\n * Defaults to the full plot area, except that a composite `labelFormat` beside\n * the funnel narrows it to leave the label real room to wrap into.\n */\n funnelWidth?: number | string;\n /**\n * Plot-area margin, in px. Merged over the defaults per side, so passing one\n * side keeps the others.\n */\n margin?: { top?: number; right?: number; bottom?: number; left?: number };\n showTooltip?: boolean;\n /**\n * Replace the default tooltip. Pass a configured `ChartTooltipContent`\n * (imported from this library) — e.g. with a `formatter` / `labelFormatter` —\n * to customize formatting, per-series rows, or extra fields without composing\n * recharts yourself. Ignored when `showTooltip` is false.\n */\n tooltipContent?: React.ComponentProps<typeof ChartTooltip>['content'];\n}\n\nconst FunnelChart = React.forwardRef<HTMLDivElement, FunnelChartProps>(\n (\n {\n className,\n config,\n palette,\n data,\n dataKey,\n nameKey,\n lastShape = 'triangle',\n reversed = false,\n showLabels = false,\n labelFormat = 'name',\n labelPosition = 'right',\n showValueLabels = false,\n valuePosition,\n labelFill,\n labelFormatter,\n percentFormatter,\n showLegend = true,\n legendFontSize,\n legendAriaLabel,\n legendValueFormatter,\n stageSettings,\n showActiveShape = false,\n stroke,\n strokeWidth,\n funnelWidth,\n margin,\n showTooltip = true,\n tooltipContent,\n animate,\n animationDuration,\n animationBegin,\n animationEasing,\n ...props\n },\n ref\n ) => {\n const animation = resolveAnimation({\n animate,\n animationDuration,\n animationBegin,\n animationEasing,\n });\n\n // Stamp each row with its `fill` and its label texts (the shadcn data-driven\n // pattern). A Funnel's default fill is grey (#808080) and recharts doesn't\n // carry a per-segment color on the tooltip/legend payload item, so putting the\n // color on the data row is what lets a real hover resolve each segment's\n // color. (The forced-open `defaultIndex` VR snapshot can still show a neutral\n // indicator — it synthesizes the open state without a pointer hover.)\n const seriesData = React.useMemo(() => {\n const visible = data.filter(\n (row) => !stageSettings?.[String(row[nameKey])]?.hidden\n );\n // The percentages are conversions from the funnel's widest stage, and\n // recharts sizes the trapezoids off `Math.max` of the values — so the base\n // is the largest visible value, not the first row. Taking the first row\n // would read as a conversion above 100% whenever the data isn't sorted\n // descending.\n const conversionBase = visible.reduce((widest, row) => {\n const value = Number(row[dataKey]);\n return Number.isFinite(value) && value > widest ? value : widest;\n }, 0);\n\n return visible.map((row, index) => {\n const name = String(row[nameKey]);\n const fill =\n stageSettings?.[name]?.color ?? `var(--color-${toCssKey(name)})`;\n const labelArgs = {\n name,\n value: row[dataKey],\n base: conversionBase,\n formatter: labelFormatter,\n percentFormatter,\n };\n\n return {\n ...row,\n fill,\n [STAGE_INDEX_KEY]: index,\n [STAGE_LABEL_KEY]: funnelChartLabelText({\n ...labelArgs,\n format: labelFormat,\n }),\n [STAGE_VALUE_LABEL_KEY]: funnelChartLabelText({\n ...labelArgs,\n format: 'value',\n }),\n } as Record<string, string | number>;\n });\n }, [\n data,\n dataKey,\n labelFormat,\n labelFormatter,\n nameKey,\n percentFormatter,\n stageSettings,\n ]);\n\n // The legend sits *outside* `ChartContainer`, beside the plot — so it can't\n // read the `--color-<name>` custom properties `ChartStyle` scopes to\n // `[data-chart=…]`. Resolving the palette here is what gives its markers the\n // same colours the stages paint with, the way `PieChart` and\n // `RadialBarChart` already do for their side legends.\n const resolvedConfigForLegend = React.useMemo(\n () =>\n showLegend\n ? resolveChartColors(config, palette ?? FUNNEL_CHART_DEFAULT_PALETTE)\n : null,\n [showLegend, config, palette]\n );\n\n // recharts 3 builds the legend payload from the graphical item, and `Funnel`\n // — unlike Bar/Line/Area/Pie/Radar/RadialBar/Scatter — never registers one,\n // so a `<Legend>` inside a `FunnelChart` renders empty. The payload is\n // synthesized from the visible stages instead and handed to the shared\n // `ChartLegendContent`, which keeps the funnel on the same legend markers,\n // labels and `config` lookup as every other chart. `payload` carries the row\n // so each entry resolves its own `config` entry via `nameKey`.\n //\n // One entry per *distinct* stage name: same-named stages deliberately share a\n // `config` entry, so a second entry would repeat the first verbatim — and\n // `ChartLegendContent` keys its entries on `value`, so it would also be a\n // duplicate React key.\n const legendPayload = React.useMemo<LegendPayload[]>(() => {\n if (!resolvedConfigForLegend) return [];\n const seen = new Set<string>();\n return seriesData.flatMap((row) => {\n const value = String(row[nameKey]);\n if (seen.has(value)) return [];\n seen.add(value);\n return [\n {\n value,\n dataKey: nameKey,\n type: 'rect' as const,\n // A `stageSettings` colour is a real colour and paints as-is; every\n // other stage takes its resolved palette stop.\n color:\n stageSettings?.[value]?.color ??\n resolvedConfigForLegend[value]?.color ??\n String(row.fill),\n payload: row,\n },\n ];\n });\n }, [nameKey, seriesData, resolvedConfigForLegend, stageSettings]);\n\n const resolvedValuePosition =\n valuePosition ?? funnelChartOppositeSide(labelPosition);\n\n // When labels sit beside the funnel (not on the segments), the 120px plot\n // is too narrow: the label margins eat the whole width and leave 0px for the\n // funnel. Make the plot grow to fill available width in that case; the fixed\n // 120px square is only for the default \"no outside labels\" layout.\n const hasOutsideLabels =\n (showLabels && labelPosition !== 'inside') ||\n (showValueLabels && resolvedValuePosition !== 'inside');\n\n const stagePosition = LABEL_POSITION[labelPosition];\n const valueLabelPosition = LABEL_POSITION[resolvedValuePosition];\n const plotMargin = {\n ...funnelChartLabelMargin({\n showLabels,\n labelPosition,\n showValueLabels,\n valuePosition: resolvedValuePosition,\n }),\n ...margin,\n };\n // A caller-supplied `funnelWidth` wins; otherwise a composite label beside the\n // funnel narrows it to leave itself room to wrap into.\n const resolvedFunnelWidth =\n funnelWidth ??\n funnelChartLabelReserve({ showLabels, labelPosition, labelFormat });\n // recharts defaults a Funnel's stroke to a hardcoded `#fff`.\n // ChartContainer's CSS neutralizer targets `.recharts-trapezoid`, but our\n // custom shape renders as `.recharts-funnel-stage`, so the neutralizer\n // never matches. Explicitly default to `'none'` to suppress the white\n // outline — and pair a bare `strokeWidth` with the border token so it\n // doesn't widen an invisible border.\n const resolvedStroke =\n stroke ??\n (strokeWidth != null ? 'var(--ui-border-on-surface-border)' : 'none');\n // One renderer for both slots: recharts swaps in `activeShape` for the\n // hovered stage, so leaving it unset would drop back to its own square-\n // cornered, gapless `Trapezoid` on hover.\n const renderStage = (stageProps: FunnelStageShapeProps) => (\n <FunnelStageShape\n {...stageProps}\n showActiveShape={showActiveShape}\n // `reversed` stacks the funnel the other way up, so the stage with no\n // gap above it is the last row rather than the first.\n topStageIndex={reversed ? seriesData.length - 1 : 0}\n />\n );\n\n return (\n <div\n ref={ref}\n data-last-shape={lastShape}\n className={cn(\n // The design's funnel is a row: a square plot, a 16px gutter, then the\n // legend taking whatever is left — so the component fills its parent's\n // width without the plot stretching into a tall, narrow wedge.\n 'flex flex-row items-center gap-4',\n !showLegend && 'justify-center',\n funnelChartVariants({ lastShape }),\n className\n )}\n {...props}\n >\n <div\n className={\n hasOutsideLabels\n ? 'h-[120px] flex-1'\n : cn(PLOT_SIZE_CLASS, 'shrink-0')\n }\n >\n <ChartContainer\n config={config}\n palette={palette ?? FUNNEL_CHART_DEFAULT_PALETTE}\n className=\"size-full\"\n >\n <RechartsFunnelChart margin={plotMargin}>\n {showTooltip && (\n <ChartTooltip\n content={\n tooltipContent ?? (\n <ChartTooltipContent nameKey={nameKey} hideLabel />\n )\n }\n />\n )}\n <Funnel\n dataKey={dataKey}\n nameKey={nameKey}\n data={seriesData}\n lastShapeType={lastShape ?? 'triangle'}\n reversed={reversed}\n width={resolvedFunnelWidth}\n stroke={resolvedStroke}\n strokeWidth={strokeWidth}\n shape={renderStage}\n activeShape={renderStage}\n {...animation}\n >\n {seriesData.map((entry, index) => (\n // Keyed by index, not the name: two stages could share a nameKey\n // value, which would collide as a React key. Same-named stages\n // intentionally share a color/config entry via `--color-<name>`.\n <Cell key={index} fill={String(entry.fill)} />\n ))}\n {showLabels && (\n <LabelList\n position={stagePosition}\n dataKey={STAGE_LABEL_KEY}\n className={\n labelFill\n ? undefined\n : resolveLabelFillClass(stagePosition)\n }\n fill={labelFill}\n stroke=\"none\"\n />\n )}\n {showValueLabels && (\n <LabelList\n position={valueLabelPosition}\n dataKey={STAGE_VALUE_LABEL_KEY}\n className={\n labelFill\n ? undefined\n : resolveLabelFillClass(valueLabelPosition)\n }\n fill={labelFill}\n stroke=\"none\"\n />\n )}\n </Funnel>\n </RechartsFunnelChart>\n </ChartContainer>\n </div>\n {showLegend && resolvedConfigForLegend && (\n <ChartLegendContent\n variant=\"list\"\n payload={legendPayload}\n config={resolvedConfigForLegend}\n nameKey={nameKey}\n fontSize={legendFontSize}\n ariaLabel={legendAriaLabel}\n valueKey={dataKey}\n valueFormatter={legendValueFormatter}\n // Figma paints the funnel legend's value in the primary text token,\n // not the link token the donut/radial legends use for theirs.\n valueClassName=\"text-[var(--ui-text-on-surface-primary)]\"\n className=\"min-w-0 flex-1\"\n />\n )}\n </div>\n );\n }\n);\nFunnelChart.displayName = 'FunnelChart';\n\nexport { FunnelChart, funnelChartVariants };\n"],"mappings":";;;;;;;;;AAsCA,IAAM,IAAsB,EAAI,IAAI;CAClC,UAAU,EACR,WAAW;EACT,UAAU;EACV,WAAW;CACb,EACF;CACA,iBAAiB,EACf,WAAW,WACb;AACF,CAAC,GAkCK,IAGF;CACF,OAAO;CACP,MAAM;CACN,QAAQ;AACV;AAWA,SAAgB,EACd,GAC0B;CAC1B,QAAQ,GAAR;EACE,KAAK,SACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,KAAK,UACH,OAAO;CACX;AACF;AAMA,IAAM,IAAkB,gBAClB,IAAwB,qBAKxB,IAAkB,gBAIlB,IAAgB,6CAChB,IAAsB,GActB,KAAkB,gBAUlB,IAAY,GAGZ,IAAe,GAUf,IAAsB,GAOtB,IAAc;CAAE,KAAK;CAAG,OAAO;CAAG,QAAQ;CAAG,MAAM;AAAE,GAU9C,IAA6C,OAAO,OAAO;CACtE,MAAM;CACN,MAAM;AACR,CAAC,GAIK,KAAY,GAAe,MAC/B,KAAK,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE;AAGrC,SAAS,EAAM,GAAkB,GAAgB,GAAuB;CACtE,IAAM,IAAS,EAAS,GAAM,CAAE;CAEhC,OADI,MAAW,IAAU,IAClB,CACL,EAAK,MAAO,EAAG,KAAK,EAAK,MAAM,IAAK,GACpC,EAAK,MAAO,EAAG,KAAK,EAAK,MAAM,IAAK,CACtC;AACF;AAIA,IAAM,KAAS,CAAC,GAAG,OACjB,GAAG,OAAO,EAAE,QAAQ,CAAC,CAAC,EAAE,GAAG,OAA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