:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hog-charts): add ComboChart for mixed bar/line/area series (#63894)
Sam Pennington533f8cb63cc4
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 5a3f6c319deb..82700d2e4b34 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -8,6 +8,7 @@ Quick-reference for AI agents using `@posthog/quill-charts`. Canvas-rendered cha| ------------------- | ------------------------------------------------------------------------------------------------------------------------------- || LineChart | Categorical x-axis trends; area fills, fill-between (confidence ribbons) || BarChart | Categorical comparisons — `barLayout: 'stacked' \| 'grouped' \| 'percent'`, `axisOrientation: 'horizontal'` for horizontal bars |+| ComboChart | Mixed bar/line/area series on one band x-axis — set `Series.type`; vertical-only, `barLayout: 'stacked' \| 'grouped'` || TimeSeriesLineChart | Time-indexed labels (ISO strings) with timezone/interval-aware x-axis || TimeSeriesBarChart | Same x-axis handling, bar rendering; supports per-series `yAxisId` axes || PieChart | Part-of-whole, one value per series; `innerRadiusRatio` for donut + `centerLabel` |diff --git a/packages/quill/packages/charts/src/charts/BarChart/utils/draw-bar-chart.ts b/packages/quill/packages/charts/src/charts/BarChart/utils/draw-bar-chart.tsindex 0605a4edc0b2..1276fb297084 100644--- a/packages/quill/packages/charts/src/charts/BarChart/utils/draw-bar-chart.ts+++ b/packages/quill/packages/charts/src/charts/BarChart/utils/draw-bar-chart.ts@@ -1,10 +1,9 @@import { color as d3Color } from 'd3-color'-import { bandCenter, type BarChartPrivate, computeBarTrackRect, computeSeriesBars } from '../../../core/bar-layout'+import { bandCenter, type BarChartPrivate, buildBarLayers, computeBarTrackRect } from '../../../core/bar-layout'import {BAR_HIGHLIGHT_DARKEN,BAR_TRACK_HOVER_ALPHA,- type BarRect,type BarShadow,clipToRoundedRects,drawAxes,@@ -17,7 +16,6 @@ import {import { barColorAt } from '../../../core/color-utils'import type { BarScaleSet, StackedBand } from '../../../core/scales'import type { BarChartConfig, BarFillStyle, BarsConfig, ChartDimensions, ChartDrawArgs } from '../../../core/types'-import { DEFAULT_Y_AXIS_ID } from '../../../core/types'import { computeVisibleXLabels } from '../../../overlays/AxisLabels'import { resolveBarShadow } from './bar-config'import { type BarLayout } from './bars-under-cursor'@@ -130,21 +128,15 @@ export function drawBarChartStatic(drawAxes(baseDrawCtx, { axisColor: theme.gridColor })}- const seriesBars = coloredSeries- .filter((s) => !s.visibility?.excluded)- .map((s) => {- const axisId = s.yAxisId ?? DEFAULT_Y_AXIS_ID- const bars = computeSeriesBars({- series: s,- labels: drawLabels,- scales: d3Scales,- layout: barLayout,- isHorizontal,- stackedBand: stackedData?.get(s.key),- isTopOfStack: topStackedKeyByAxis.get(axisId) === s.key,- }).filter((b): b is BarRect => b !== null)- return { series: s, bars }- })+ const seriesBars = buildBarLayers({+ series: coloredSeries,+ labels: drawLabels,+ scales: d3Scales,+ layout: barLayout,+ isHorizontal,+ stackedData,+ topStackedKeyByAxis,+ })// `roundStackEnds`: round both outer ends of the whole stack into a pill by clipping// the bar layer to a rounded rect spanning each band's full extent, then drawing thediff --git a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.stories.tsx b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.stories.tsxnew file mode 100644index 000000000000..0b8dec83929e--- /dev/null+++ b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.stories.tsx@@ -0,0 +1,137 @@+import { Meta, StoryObj } from '@storybook/react'++import type { ComboChartConfig, Series } from '../../core/types'+import { Stage, useReactiveTheme } from '../../story-helpers'+import { ComboChart } from './ComboChart'++const DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']++const meta: Meta = { title: 'Components/HogCharts/ComboChart', parameters: { layout: 'centered' } }+export default meta++type Story = StoryObj<{}>++export const BarAndLine: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series[] = [+ { key: 'visits', label: 'Visits', color: '', data: [40, 42, 44, 43, 45, 47, 46], type: 'bar' },+ { key: 'rolling', label: 'Rolling avg', color: '', data: [38, 40, 42, 43, 44, 45, 46], type: 'line' },+ ]+ const config: ComboChartConfig = { showGrid: true }+ return (+ <Stage>+ <ComboChart series={series} labels={DAYS} config={config} theme={theme} />+ </Stage>+ )+ },+}++export const AreaAndLine: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series[] = [+ { key: 'visits', label: 'Visits', color: '', data: [40, 42, 44, 43, 45, 47, 46], type: 'area' },+ { key: 'rolling', label: 'Rolling avg', color: '', data: [38, 40, 42, 43, 44, 45, 46], type: 'line' },+ ]+ const config: ComboChartConfig = { showGrid: true }+ return (+ <Stage>+ <ComboChart series={series} labels={DAYS} config={config} theme={theme} />+ </Stage>+ )+ },+}++export const StackedBarsAndLine: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series[] = [+ { key: 'desktop', label: 'Desktop', color: '', data: [22, 24, 28, 26, 30, 32, 31], type: 'bar' },+ { key: 'mobile', label: 'Mobile', color: '', data: [18, 18, 16, 17, 15, 15, 15], type: 'bar' },+ { key: 'total', label: 'Total (rolling)', color: '', data: [38, 40, 42, 43, 45, 47, 46], type: 'line' },+ ]+ const config: ComboChartConfig = { showGrid: true, barLayout: 'stacked' }+ return (+ <Stage>+ <ComboChart series={series} labels={DAYS} config={config} theme={theme} />+ </Stage>+ )+ },+}++export const GroupedBarsAndLine: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series[] = [+ { key: 'a', label: 'A', color: '', data: [22, 24, 28, 26, 30, 32, 31], type: 'bar' },+ { key: 'b', label: 'B', color: '', data: [18, 18, 16, 17, 15, 15, 15], type: 'bar' },+ { key: 'avg', label: 'Avg', color: '', data: [20, 21, 22, 21, 22, 23, 23], type: 'line' },+ ]+ const config: ComboChartConfig = { showGrid: true, barLayout: 'grouped' }+ return (+ <Stage>+ <ComboChart series={series} labels={DAYS} config={config} theme={theme} />+ </Stage>+ )+ },+}++/** Bar on the left axis, line on the right — independent y-axes. */+export const DualYAxisBarAndLine: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series[] = [+ {+ key: 'revenue',+ label: 'Revenue',+ color: '',+ data: [1100, 1300, 1250, 1700, 1500, 1900, 1800],+ type: 'bar',+ },+ {+ key: 'conversion',+ label: 'Conversion',+ color: '',+ data: [0.022, 0.028, 0.025, 0.034, 0.031, 0.038, 0.036],+ type: 'line',+ yAxisId: 'right',+ },+ ]+ const config: ComboChartConfig = { showGrid: true }+ return (+ <Stage>+ <ComboChart series={series} labels={DAYS} config={config} theme={theme} />+ </Stage>+ )+ },+}++/** Line series declared before an area series in the input — covers the two-pass z-order: the+ * area fill must paint behind the line regardless of series order. */+export const LineBeforeArea: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series[] = [+ { key: 'line', label: 'Trend', color: '', data: [10, 14, 12, 22, 18, 26, 20], type: 'line' },+ { key: 'area', label: 'Range', color: '', data: [16, 20, 18, 28, 24, 32, 26], type: 'area' },+ ]+ const config: ComboChartConfig = { showGrid: true }+ return (+ <Stage>+ <ComboChart series={series} labels={DAYS} config={config} theme={theme} />+ </Stage>+ )+ },+}++export const Empty: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage>+ <ComboChart series={[]} labels={[]} theme={theme} />+ </Stage>+ )+ },+}diff --git a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.test.tsx b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.test.tsxnew file mode 100644index 000000000000..2967324e0543--- /dev/null+++ b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.test.tsx@@ -0,0 +1,174 @@+import type { ChartTheme, Series } from '../../core/types'+import { ReferenceLine } from '../../overlays/ReferenceLine'+import { renderHogChart } from '../../testing'+import { ComboChart } from './ComboChart'++const THEME: ChartTheme = {+ colors: ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'],+ backgroundColor: '#ffffff',+ gridColor: '#eeeeee',+ crosshairColor: '#888888',+}++const LABELS = ['Mon', 'Tue', 'Wed']++const BAR_AND_LINE: Series[] = [+ { key: 'visits', label: 'Visits', data: [40, 60, 50], type: 'bar' },+ { key: 'avg', label: 'Avg', data: [42, 55, 53], type: 'line' },+]++describe('ComboChart', () => {+ it('renders a bar + line combo without crashing', () => {+ const { chart } = renderHogChart(<ComboChart series={BAR_AND_LINE} labels={LABELS} theme={THEME} />)+ expect(chart.seriesCount).toBe(2)+ expect(chart.yTicks().length).toBeGreaterThan(0)+ })++ it('renders an area + line combo without crashing', () => {+ const series: Series[] = [+ { key: 'area', label: 'Area', data: [10, 30, 20], type: 'area' },+ { key: 'avg', label: 'Avg', data: [15, 25, 20], type: 'line' },+ ]+ const { chart } = renderHogChart(<ComboChart series={series} labels={LABELS} theme={THEME} />)+ expect(chart.seriesCount).toBe(2)+ })++ it('renders empty state without crashing', () => {+ const { chart } = renderHogChart(<ComboChart series={[]} labels={[]} theme={THEME} />)+ expect(chart.seriesCount).toBe(0)+ })++ it('forwards `dataAttr` to the chart wrapper', () => {+ const { chart } = renderHogChart(+ <ComboChart series={BAR_AND_LINE} labels={LABELS} theme={THEME} dataAttr="combo-instance" />+ )+ expect(chart.element.getAttribute('data-attr')).toBe('combo-instance')+ })++ it('applies xTickFormatter to x-axis ticks', () => {+ const { chart } = renderHogChart(+ <ComboChart+ series={BAR_AND_LINE}+ labels={LABELS}+ theme={THEME}+ config={{ xTickFormatter: (_l, i) => `tick-${i}` }}+ />+ )+ expect(chart.xTicks()).toEqual(['tick-0', 'tick-1', 'tick-2'])+ })++ it('renders a right axis when a series sets yAxisId: right', () => {+ const series: Series[] = [+ { key: 'b', label: 'B', data: [40, 60, 50], type: 'bar' },+ { key: 'l', label: 'L', data: [1000, 2000, 3000], type: 'line', yAxisId: 'right' },+ ]+ const { chart } = renderHogChart(<ComboChart series={series} labels={LABELS} theme={THEME} />)+ expect(chart.hasRightAxis).toBe(true)+ expect(chart.yRightTicks().length).toBeGreaterThan(0)+ })++ describe('hover & tooltip', () => {+ it('lists every visible series at the hovered x', async () => {+ const { chart } = renderHogChart(<ComboChart series={BAR_AND_LINE} labels={LABELS} theme={THEME} />)+ chart.hoverAtIndex(1)+ const tooltip = await chart.waitForTooltip()+ const keys = tooltip.seriesData.map((s) => s.series.key).sort()+ expect(keys).toEqual(['avg', 'visits'])+ })++ it('keeps line series in tooltip even when the cursor is in a band gap', async () => {+ const onlyLine: Series[] = [+ { key: 'b', label: 'B', data: [10, 20, 30], type: 'bar' },+ { key: 'l', label: 'L', data: [5, 15, 25], type: 'line' },+ ]+ const { chart } = renderHogChart(<ComboChart series={onlyLine} labels={LABELS} theme={THEME} />)+ chart.hoverAtIndex(1)+ const tooltip = await chart.waitForTooltip()+ const keys = tooltip.seriesData.map((s) => s.series.key)+ expect(keys).toContain('l')+ })++ it('renders bar+line on dual axes and shows both in the tooltip', async () => {+ const series: Series[] = [+ { key: 'b', label: 'Revenue', data: [1000, 2000, 1500], type: 'bar' },+ { key: 'l', label: 'Conv', data: [0.02, 0.03, 0.025], type: 'line', yAxisId: 'right' },+ ]+ const { chart } = renderHogChart(<ComboChart series={series} labels={LABELS} theme={THEME} />)+ chart.hoverAtIndex(1)+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.seriesData.map((s) => s.series.key).sort()).toEqual(['b', 'l'])+ expect(chart.hasRightAxis).toBe(true)+ })++ it('pins the tooltip on click when tooltip.pinnable is true', async () => {+ const { chart } = renderHogChart(+ <ComboChart+ series={BAR_AND_LINE}+ labels={LABELS}+ theme={THEME}+ config={{ tooltip: { pinnable: true } }}+ />+ )+ await chart.clickAtIndex(1)+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.isPinned).toBe(true)+ })++ it('stacked bar tooltip shows each bar segment own value, not the cumulative total', async () => {+ // Two bar series stacked: a=20 + b=15 at index 1. b's stacked top is 35, but the+ // tooltip must report b's own 15.+ const series: Series[] = [+ { key: 'a', label: 'A', data: [10, 20, 30], type: 'bar' },+ { key: 'b', label: 'B', data: [5, 15, 25], type: 'bar' },+ { key: 'l', label: 'L', data: [50, 60, 70], type: 'line' },+ ]+ const { chart } = renderHogChart(+ <ComboChart series={series} labels={LABELS} theme={THEME} config={{ barLayout: 'stacked' }} />+ )+ chart.hoverAtIndex(1)+ const tooltip = await chart.waitForTooltip()+ expect(tooltip.series.a.value).toBe(20)+ expect(tooltip.series.b.value).toBe(15)+ expect(tooltip.series.l.value).toBe(60)+ })+ })++ describe('children & error boundary', () => {+ it('renders a ReferenceLine child via the accessor', () => {+ const { chart } = renderHogChart(+ <ComboChart series={BAR_AND_LINE} labels={LABELS} theme={THEME}>+ <ReferenceLine value={45} label="Target" />+ </ComboChart>+ )+ const lines = chart.referenceLines()+ expect(lines).toHaveLength(1)+ expect(lines[0].label).toBe('Target')+ })++ it('reports render errors through onError', () => {+ const onError = jest.fn()+ const tooltip = (): never => {+ throw new Error('boom')+ }+ // ChartErrorBoundary surfaces the error to onError; React still logs it. Restore+ // explicitly rather than via afterEach — setupJsdom installs a persistent+ // getBoundingClientRect spy that restoreAllMocks would also tear down.+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})+ try {+ const { chart } = renderHogChart(+ <ComboChart+ series={BAR_AND_LINE}+ labels={LABELS}+ theme={THEME}+ tooltip={tooltip}+ onError={onError}+ />+ )+ chart.hoverAtIndex(1)+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'boom' }), expect.anything())+ } finally {+ consoleErrorSpy.mockRestore()+ }+ })+ })+})diff --git a/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsxnew file mode 100644index 000000000000..f89f8d4e9cd4--- /dev/null+++ b/packages/quill/packages/charts/src/charts/ComboChart/ComboChart.tsx@@ -0,0 +1,323 @@+import { color as d3Color } from 'd3-color'+import React, { useCallback, useMemo } from 'react'++import { bandCenter, buildBarLayers, computeBarAtIndex, groupedBarCenter } from '../../core/bar-layout'+import {+ BAR_HIGHLIGHT_DARKEN,+ DEFAULT_BAR_CORNER_RADIUS,+ drawBarHighlight,+ drawBars,+ drawGrid,+ drawLineHoverPoints,+ drawLineSeriesLayer,+ type DrawContext,+} from '../../core/canvas-renderer'+import { Chart } from '../../core/Chart'+import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'+import { barColorAt } from '../../core/color-utils'+import { type ComboChartPrivate, createComboScales, partitionByType, resolveSeriesType } from '../../core/combo-scales'+import {+ buildSegmentResolveValue,+ buildStackedPositionValue,+ computeStackData,+ computeTopStackedKeyByAxis,+ resolveYScaleForSeries,+ type StackedBand,+ toYAxisScales,+ yTickCountForHeight,+} from '../../core/scales'+import type {+ ChartDimensions,+ ChartDrawArgs,+ ChartScales,+ ChartTheme,+ ComboChartConfig,+ CreateScalesFn,+ DrawHoverResult,+ PointClickData,+ ResolvedSeries,+ Series,+ SeriesType,+ TooltipContext,+} from '../../core/types'+import { DEFAULT_SERIES_TYPE, DEFAULT_Y_AXIS_ID } from '../../core/types'+import { computeVisibleXLabels } from '../../overlays/AxisLabels'+import { resolveBarsAtCursor } from '../BarChart/utils/bars-under-cursor'++export interface ComboChartProps<Meta = unknown> {+ series: Series<Meta>[]+ labels: string[]+ config?: ComboChartConfig+ theme: ChartTheme+ tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode+ onPointClick?: (data: PointClickData<Meta>) => void+ className?: string+ /** `data-attr` applied to the chart wrapper. See `ChartProps.dataAttr`. */+ dataAttr?: string+ children?: React.ReactNode+ onError?: (error: Error, info: React.ErrorInfo) => void+}++export function ComboChart<Meta = unknown>({ onError, ...rest }: ComboChartProps<Meta>): React.ReactElement {+ return (+ <ChartErrorBoundary onError={onError}>+ <ComboChartInner {...rest} />+ </ChartErrorBoundary>+ )+}++function ComboChartInner<Meta = unknown>({+ series,+ labels,+ config,+ theme,+ tooltip,+ onPointClick,+ className,+ dataAttr,+ children,+}: Omit<ComboChartProps<Meta>, 'onError'>): React.ReactElement {+ const {+ yScaleType = 'linear',+ showGrid = false,+ barLayout = 'stacked',+ barCornerRadius = DEFAULT_BAR_CORNER_RADIUS,+ defaultSeriesType = DEFAULT_SERIES_TYPE,+ xTickFormatter,+ } = config ?? {}++ const seriesTypeOf = useCallback(+ (s: Pick<Series, 'type'>): SeriesType => resolveSeriesType(s, defaultSeriesType),+ [defaultSeriesType]+ )++ // Stack only bar series together. Lines/areas are explicitly excluded so a line doesn't get a+ // bottom-of-stack offset and bars don't widen the line's drawn baseline.+ const barStackedData = useMemo<Map<string, StackedBand> | undefined>(() => {+ if (barLayout !== 'stacked') {+ return undefined+ }+ const barSeries = series.filter((s) => seriesTypeOf(s) === 'bar')+ if (barSeries.length === 0) {+ return undefined+ }+ return computeStackData(barSeries, labels)+ }, [barLayout, series, labels, seriesTypeOf])++ // Per-axis topmost bar — only bar layers below the cap forgo corner rounding. Non-bar series are+ // skipped so lines/areas don't take part in bar stacking. Shares BarChart's helper.+ const topStackedKeyByAxis = useMemo<Map<string, string>>(+ () =>+ barLayout !== 'stacked'+ ? new Map()+ : computeTopStackedKeyByAxis(series, { skip: (s) => seriesTypeOf(s) !== 'bar' }),+ [barLayout, series, seriesTypeOf]+ )++ const createScales: CreateScalesFn = useCallback(+ (coloredSeries: ResolvedSeries[], scaleLabels: string[], dimensions: ChartDimensions): ChartScales => {+ const comboScales = createComboScales(coloredSeries, scaleLabels, dimensions, {+ scaleType: yScaleType,+ barLayout,+ seriesTypeOf,+ barStackedData,+ })++ const yTickCount = yTickCountForHeight(dimensions.plotHeight)++ // Pre-index series by key so the grouped `x` closure resolves seriesKey → type in O(1)+ // instead of scanning the array on every overlay/value-label call.+ const seriesByKey = new Map<string, ResolvedSeries>()+ for (const s of coloredSeries) {+ seriesByKey.set(s.key, s)+ }++ const comboPrivate: ComboChartPrivate = { __comboChart: comboScales }++ return {+ x: (label: string, seriesKey?: string) => {+ // Only grouped bars get a per-series sub-band offset; everything else (lines,+ // areas, the unkeyed call) anchors at the band center.+ if (seriesKey == null || barLayout !== 'grouped') {+ return bandCenter(comboScales, label)+ }+ const s = seriesByKey.get(seriesKey)+ if (s && seriesTypeOf(s) === 'bar') {+ return groupedBarCenter(comboScales, label, seriesKey) ?? bandCenter(comboScales, label)+ }+ return bandCenter(comboScales, label)+ },+ y: (v: number) => comboScales.y(v),+ yTicks: () => comboScales.y.ticks?.(yTickCount) ?? [],+ yAxes: toYAxisScales(comboScales.yAxes, yTickCount),+ _private: comboPrivate,+ }+ },+ [yScaleType, barLayout, seriesTypeOf, barStackedData]+ )++ const drawStatic = useCallback(+ ({ ctx, dimensions, scales, series: coloredSeries, labels: drawLabels, theme }: ChartDrawArgs) => {+ const comboScales = (scales._private as ComboChartPrivate | undefined)?.__comboChart+ if (!comboScales) {+ return+ }++ const { bars: barSeries, lines: lineSeries } = partitionByType(coloredSeries, seriesTypeOf)++ const baseDrawCtx: DrawContext = {+ ctx,+ dimensions,+ xScale: (label) => bandCenter(comboScales, label),+ yScale: comboScales.y,+ labels: drawLabels,+ }++ if (showGrid) {+ const categoryTicks = computeVisibleXLabels(+ drawLabels,+ (label) => bandCenter(comboScales, label),+ xTickFormatter+ ).map((entry) => entry.x)+ drawGrid(baseDrawCtx, { gridColor: theme.gridColor, categoryTicks })+ }++ // ── 1. Bars ──────────────────────────────────────────────────────────────────────+ // `comboScales` is structurally a `BarScaleSet`; `buildBarLayers` (shared with BarChart)+ // resolves each series' own axis (`yAxes[id] ?? value`), so dual-axis bars draw correctly.+ const barLayers = buildBarLayers({+ series: barSeries,+ labels: drawLabels,+ scales: comboScales,+ layout: barLayout,+ isHorizontal: false,+ stackedData: barStackedData,+ topStackedKeyByAxis,+ })+ for (const { series: s, bars } of barLayers) {+ drawBars(baseDrawCtx, s, bars, barCornerRadius)+ }++ // ── 2. Lines + areas (shared with LineChart). `areas-first` so every area sits below+ // every line regardless of input order; combo lines aren't stacked, so the raw data+ // is used and a series counts as filled when its type is 'area' or it sets `fill`.+ drawLineSeriesLayer({+ ctx,+ dimensions,+ labels: drawLabels,+ series: lineSeries,+ xScale: (label) => bandCenter(comboScales, label),+ resolveYScale: (s) => resolveYScaleForSeries(comboScales, s),+ shouldFill: (s) => seriesTypeOf(s) === 'area' || !!s.fill,+ bottomFor: (s) => s.fill?.lowerData,+ zOrder: 'areas-first',+ })+ },+ [seriesTypeOf, showGrid, xTickFormatter, barLayout, barStackedData, topStackedKeyByAxis, barCornerRadius]+ )++ const drawHover = useCallback(+ ({+ ctx,+ scales,+ series: coloredSeries,+ labels: drawLabels,+ hoverIndex,+ hoverPosition,+ theme,+ }: ChartDrawArgs): DrawHoverResult => {+ if (hoverIndex < 0) {+ return false+ }+ const comboScales = (scales._private as ComboChartPrivate | undefined)?.__comboChart+ if (!comboScales) {+ return false+ }++ const hoveredLabel = drawLabels[hoverIndex]+ const { bars: barSeries, lines: lineSeries } = partitionByType(coloredSeries, seriesTypeOf)+ let drewAny = false++ // Bars: only highlight those whose band-axis extent contains the cursor. The shared bar+ // resolver works directly on the combo scales (per-axis resolution inside computeBarAtIndex).+ const barHits = hoverPosition+ ? resolveBarsAtCursor({+ series: barSeries,+ label: hoveredLabel,+ dataIndex: hoverIndex,+ cursor: hoverPosition,+ scales: comboScales,+ layout: barLayout,+ isHorizontal: false,+ stackedData: barStackedData,+ topStackedKeyByAxis,+ }).hits+ : null++ for (const s of barSeries) {+ if (barHits && !barHits.has(s.key)) {+ continue+ }+ const axisId = s.yAxisId ?? DEFAULT_Y_AXIS_ID+ const bar = computeBarAtIndex({+ series: s,+ label: hoveredLabel,+ dataIndex: hoverIndex,+ scales: comboScales,+ layout: barLayout,+ isHorizontal: false,+ stackedBand: barStackedData?.get(s.key),+ isTopOfStack: topStackedKeyByAxis.get(axisId) === s.key,+ })+ if (!bar) {+ continue+ }+ const barColor = barColorAt(s, bar.dataIndex)+ const highlightColor = d3Color(barColor)?.darker(BAR_HIGHLIGHT_DARKEN).toString() ?? barColor+ drawBarHighlight(ctx, bar, highlightColor, barCornerRadius)+ drewAny = true+ }++ // Lines/areas — highlight ring at the band center for this index (shared with LineChart).+ const x = bandCenter(comboScales, hoveredLabel)+ if (x != null) {+ const drewLine = drawLineHoverPoints(ctx, lineSeries, theme.backgroundColor ?? '#ffffff', (s) => {+ const raw = s.data[hoverIndex]+ if (raw == null || !isFinite(raw)) {+ return null+ }+ return { x, y: resolveYScaleForSeries(comboScales, s)(raw) }+ })+ drewAny = drewAny || drewLine+ }+ return drewAny+ },+ [seriesTypeOf, barLayout, barStackedData, topStackedKeyByAxis, barCornerRadius]+ )++ // Bar segments report their own value; lines report raw. buildSegmentResolveValue's fallback+ // handles non-bar series automatically (they aren't in barStackedData), so the bar-only stack+ // still yields correct line values.+ const resolveValue = useMemo(() => buildSegmentResolveValue(barStackedData), [barStackedData])+ const resolvePositionValue = useMemo(() => buildStackedPositionValue(barStackedData), [barStackedData])++ return (+ <Chart+ series={series}+ labels={labels}+ config={config}+ theme={theme}+ createScales={createScales}+ drawStatic={drawStatic}+ drawHover={drawHover}+ tooltip={tooltip}+ onPointClick={onPointClick}+ className={className}+ dataAttr={dataAttr}+ resolveValue={resolveValue}+ resolvePositionValue={resolvePositionValue}+ >+ {children}+ </Chart>+ )+}diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsxindex 378d8b17609b..7b485a6c45fe 100644--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx@@ -2,9 +2,8 @@ import React, { useCallback, useMemo } from 'react'import { ChartLegend } from '../../components/Legend/ChartLegend'import { useChartLegend } from '../../components/Legend/useChartLegend'-import { drawArea, drawAxes, drawGrid, drawLine, drawLineHoverPoints, drawPoints } from '../../core/canvas-renderer'+import { drawAxes, drawGrid, drawLineHoverPoints, drawLineSeriesLayer } from '../../core/canvas-renderer'import type { DrawContext } from '../../core/canvas-renderer'-import { withVerticalClip } from '../../core/canvas-renderer'import { Chart } from '../../core/Chart'import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'import {@@ -179,29 +178,19 @@ function LineChartInner<Meta = unknown>({drawAxes(baseDrawCtx, { axisColor: theme.gridColor })}- // Clip vertically only: keep out-of-domain values (e.g. a trendline below 0) out of the- // axis-label gutters, but span the full width so edge point markers/line caps render whole.- withVerticalClip(ctx, dimensions, () => {- for (const s of coloredSeries) {- if (s.visibility?.excluded) {- continue- }-- const drawCtx: DrawContext = {- ...baseDrawCtx,- yScale: resolveYScale(s),- }- const band = stackedData?.get(s.key)- const yValues = band?.top-- if (s.fill) {- drawArea(drawCtx, s, yValues, s.fill.lowerData ?? band?.bottom)- }- if (!s.fill?.lowerData) {- drawLine(drawCtx, s, yValues)- drawPoints(drawCtx, s, yValues)- }- }+ // Area then line+points per series, clipped vertically (shared with ComboChart). Areas use+ // the stacked top as the line value and the stacked bottom (or `fill.lowerData`) as the floor.+ drawLineSeriesLayer({+ ctx,+ dimensions,+ labels: drawLabels,+ series: coloredSeries,+ xScale: d3Scales.x,+ resolveYScale,+ yValuesFor: (s) => stackedData?.get(s.key)?.top,+ bottomFor: (s) => s.fill?.lowerData ?? stackedData?.get(s.key)?.bottom,+ shouldFill: (s) => !!s.fill,+ zOrder: 'per-series',})},[showGrid, showAxisLines, stackedData]diff --git a/packages/quill/packages/charts/src/core/bar-layout.ts b/packages/quill/packages/charts/src/core/bar-layout.tsindex f5941cc2db87..4970bf57abbe 100644--- a/packages/quill/packages/charts/src/core/bar-layout.ts+++ b/packages/quill/packages/charts/src/core/bar-layout.ts@@ -1,6 +1,6 @@import type { BarRect, BarRoundedCorners } from './canvas-renderer'import { type BarScaleSet, groupedBandSlot, type StackedBand } from './scales'-import type { Series } from './types'+import type { ResolvedSeries, Series } from './types'import { DEFAULT_Y_AXIS_ID } from './types'/** Brand for the BarChart `ChartScales._private` slot — populated by BarChart and@@ -116,6 +116,54 @@ export function computeSeriesBars({return result}+/** One drawn series and its computed rects — the unit both BarChart and ComboChart iterate. */+export interface BarLayer {+ series: ResolvedSeries+ bars: BarRect[]+}++export interface BuildBarLayersOptions {+ series: readonly ResolvedSeries[]+ labels: string[]+ scales: BarScaleSet+ layout: 'stacked' | 'grouped' | 'percent'+ isHorizontal: boolean+ stackedData?: Map<string, StackedBand>+ topStackedKeyByAxis: Map<string, string>+}++/** Compute the bar rects for every visible series — the per-series `computeSeriesBars` loop shared by+ * `drawBarChartStatic` and ComboChart so the band/axis/stack wiring lives in one place. Excluded+ * series are dropped; nulls (overlay/CI-band series with no stacked entry) are filtered out. */+export function buildBarLayers({+ series,+ labels,+ scales,+ layout,+ isHorizontal,+ stackedData,+ topStackedKeyByAxis,+}: BuildBarLayersOptions): BarLayer[] {+ const layers: BarLayer[] = []+ for (const s of series) {+ if (s.visibility?.excluded) {+ continue+ }+ const axisId = s.yAxisId ?? DEFAULT_Y_AXIS_ID+ const bars = computeSeriesBars({+ series: s,+ labels,+ scales,+ layout,+ isHorizontal,+ stackedBand: stackedData?.get(s.key),+ isTopOfStack: topStackedKeyByAxis.get(axisId) === s.key,+ }).filter((b): b is BarRect => b !== null)+ layers.push({ series: s, bars })+ }+ return layers+}+export interface ComputeBarAtIndexOptions {series: Serieslabel: stringdiff --git a/packages/quill/packages/charts/src/core/canvas-renderer.ts b/packages/quill/packages/charts/src/core/canvas-renderer.tsindex 78ece4c1642b..ee4a4fd50a1e 100644--- a/packages/quill/packages/charts/src/core/canvas-renderer.ts+++ b/packages/quill/packages/charts/src/core/canvas-renderer.ts@@ -574,6 +574,68 @@ export function withVerticalClip(}}+export interface LineSeriesLayerOptions {+ ctx: CanvasRenderingContext2D+ dimensions: ChartDimensions+ labels: string[]+ /** Series to draw, in paint order. Excluded series are skipped. */+ series: readonly ResolvedSeries[]+ xScale: (label: string) => number | undefined+ resolveYScale: (s: ResolvedSeries) => ScaleLinear<number, number> | ScaleLogarithmic<number, number>+ /** y-values to plot for a series (e.g. stacked tops). Defaults to `series.data`. */+ yValuesFor?: (s: ResolvedSeries) => number[] | undefined+ /** Bottom edge for the area fill (stacked bottom or `fill.lowerData`). */+ bottomFor?: (s: ResolvedSeries) => number[] | undefined+ /** Whether to fill the area under a series. Defaults to `!!s.fill`. */+ shouldFill?: (s: ResolvedSeries) => boolean+ /** `per-series`: area then line+points per series (LineChart). `areas-first`: every area, then+ * every line+points (ComboChart) so a later area can't paint over an earlier line. */+ zOrder?: 'per-series' | 'areas-first'+}++/** Draw a line/area layer (clipped vertically) — the per-series area/line/points orchestration shared+ * by LineChart and ComboChart. Callers supply the y-value source (raw vs stacked tops), the fill+ * predicate, and the z-order; the loop, clip, and primitive calls live here. */+export function drawLineSeriesLayer(options: LineSeriesLayerOptions): void {+ const { ctx, dimensions, labels, series, xScale, resolveYScale } = options+ const yValuesFor = options.yValuesFor ?? (() => undefined)+ const bottomFor = options.bottomFor ?? ((s: ResolvedSeries) => s.fill?.lowerData)+ const shouldFill = options.shouldFill ?? ((s: ResolvedSeries) => !!s.fill)+ const zOrder = options.zOrder ?? 'per-series'+ const visible = series.filter((s) => !s.visibility?.excluded)++ const paintArea = (s: ResolvedSeries): void => {+ if (!shouldFill(s)) {+ return+ }+ drawArea({ ctx, dimensions, labels, xScale, yScale: resolveYScale(s) }, s, yValuesFor(s), bottomFor(s))+ }+ const paintLine = (s: ResolvedSeries): void => {+ if (s.fill?.lowerData) {+ return+ }+ const drawCtx: DrawContext = { ctx, dimensions, labels, xScale, yScale: resolveYScale(s) }+ drawLine(drawCtx, s, yValuesFor(s))+ drawPoints(drawCtx, s, yValuesFor(s))+ }++ withVerticalClip(ctx, dimensions, () => {+ if (zOrder === 'areas-first') {+ for (const s of visible) {+ paintArea(s)+ }+ for (const s of visible) {+ paintLine(s)+ }+ return+ }+ for (const s of visible) {+ paintArea(s)+ paintLine(s)+ }+ })+}+/** Draw hover highlight rings for line/area series at the hovered index. Skips excluded,* fill-between (`fill.lowerData`), and overlay series (trendlines/moving averages opt out of hover* points). `pointFor` lets each chart supply its own anchor — LineChart resolves the point x anddiff --git a/packages/quill/packages/charts/src/core/combo-scales.test.ts b/packages/quill/packages/charts/src/core/combo-scales.test.tsnew file mode 100644index 000000000000..8a4c0c74f2a9--- /dev/null+++ b/packages/quill/packages/charts/src/core/combo-scales.test.ts@@ -0,0 +1,259 @@+import { dimensions, makeSeries } from '../testing'+import { computeBarAtIndex } from './bar-layout'+import { createComboScales, isLineLike, partitionByType, resolveSeriesType } from './combo-scales'+import { computeStackData } from './scales'+import type { Series, SeriesType } from './types'+import { DEFAULT_Y_AXIS_ID } from './types'++function typeOfWithDefault(defaultType: SeriesType): (s: Pick<Series, 'type'>) => SeriesType {+ return (s) => resolveSeriesType(s, defaultType)+}++describe('combo-scales', () => {+ describe('resolveSeriesType', () => {+ it.each<[Pick<Series, 'type'>, SeriesType, SeriesType]>([+ [{ type: 'bar' }, 'line', 'bar'],+ [{ type: 'area' }, 'line', 'area'],+ [{}, 'line', 'line'],+ [{}, 'bar', 'bar'],+ ])('resolveSeriesType(%o, %s) === %s', (series, defaultType, expected) => {+ expect(resolveSeriesType(series, defaultType)).toBe(expected)+ })+ })++ describe('isLineLike', () => {+ it.each<[SeriesType, boolean]>([+ ['line', true],+ ['area', true],+ ['bar', false],+ ])('isLineLike(%s) === %s', (t, expected) => {+ expect(isLineLike(t)).toBe(expected)+ })+ })++ describe('partitionByType', () => {+ it('splits visible series by resolved type, preserving order', () => {+ const a = makeSeries({ key: 'a', data: [1], type: 'bar' })+ const b = makeSeries({ key: 'b', data: [1] }) // default line+ const c = makeSeries({ key: 'c', data: [1], type: 'area' })+ const d = makeSeries({ key: 'd', data: [1], type: 'bar' })+ const { bars, lines } = partitionByType([a, b, c, d], typeOfWithDefault('line'))+ expect(bars.map((s) => s.key)).toEqual(['a', 'd'])+ expect(lines.map((s) => s.key)).toEqual(['b', 'c'])+ })++ it('drops excluded series from both buckets', () => {+ const a = makeSeries({ key: 'a', data: [1], type: 'bar', visibility: { excluded: true } })+ const b = makeSeries({ key: 'b', data: [1], type: 'line', visibility: { excluded: true } })+ const c = makeSeries({ key: 'c', data: [1], type: 'bar' })+ const { bars, lines } = partitionByType([a, b, c], typeOfWithDefault('line'))+ expect(bars.map((s) => s.key)).toEqual(['c'])+ expect(lines).toHaveLength(0)+ })++ it('respects the per-series type even when default is bar', () => {+ const a = makeSeries({ key: 'a', data: [1] }) // default → bar+ const b = makeSeries({ key: 'b', data: [1], type: 'line' })+ const { bars, lines } = partitionByType([a, b], typeOfWithDefault('bar'))+ expect(bars.map((s) => s.key)).toEqual(['a'])+ expect(lines.map((s) => s.key)).toEqual(['b'])+ })+ })++ describe('createComboScales — band x', () => {+ it('places a line series at band centers (matches band scale center)', () => {+ const series: Series[] = [+ makeSeries({ key: 'b1', data: [10, 20, 30], type: 'bar' }),+ makeSeries({ key: 'l1', data: [5, 15, 25], type: 'line' }),+ ]+ const scales = createComboScales(series, ['a', 'b', 'c'], dimensions, {+ seriesTypeOf: typeOfWithDefault('line'),+ barStackedData: computeStackData(+ series.filter((s) => s.type === 'bar'),+ ['a', 'b', 'c']+ ),+ })+ const bw = scales.band.bandwidth()+ for (const label of ['a', 'b', 'c']) {+ const start = scales.band(label)!+ expect(start).toBeGreaterThanOrEqual(dimensions.plotLeft)+ expect(start + bw).toBeLessThanOrEqual(dimensions.plotLeft + dimensions.plotWidth)+ }+ })++ it('builds a group sub-band from bar series only when barLayout is grouped', () => {+ const series: Series[] = [+ makeSeries({ key: 'b1', data: [10], type: 'bar' }),+ makeSeries({ key: 'l1', data: [5], type: 'line' }),+ makeSeries({ key: 'b2', data: [3], type: 'bar' }),+ ]+ const scales = createComboScales(series, ['a'], dimensions, {+ barLayout: 'grouped',+ seriesTypeOf: typeOfWithDefault('line'),+ })+ expect(scales.group).not.toBeUndefined()+ expect(scales.group!.domain()).toEqual(['b1', 'b2'])+ })++ it('omits the group sub-band for stacked layout', () => {+ const series: Series[] = [makeSeries({ key: 'b1', data: [10], type: 'bar' })]+ const scales = createComboScales(series, ['a'], dimensions, {+ barLayout: 'stacked',+ seriesTypeOf: typeOfWithDefault('line'),+ barStackedData: computeStackData(series, ['a']),+ })+ expect(scales.group).toBeUndefined()+ })+ })++ describe('createComboScales — value domain spans all types per axis', () => {+ it('lets a line series extend the axis max above the highest bar', () => {+ const bar = makeSeries({ key: 'b', data: [10, 20, 30], type: 'bar' })+ const line = makeSeries({ key: 'l', data: [5, 60, 90], type: 'line' })+ const scales = createComboScales([bar, line], ['a', 'b', 'c'], dimensions, {+ seriesTypeOf: typeOfWithDefault('line'),+ barStackedData: computeStackData([bar], ['a', 'b', 'c']),+ })+ const [, domainMax] = scales.y.domain()+ expect(domainMax).toBeGreaterThanOrEqual(90)+ })++ it('uses bar stacked tops (not raw) when bars are stacked', () => {+ const b1 = makeSeries({ key: 'b1', data: [10, 20, 30], type: 'bar' })+ const b2 = makeSeries({ key: 'b2', data: [10, 20, 30], type: 'bar' })+ const scales = createComboScales([b1, b2], ['a', 'b', 'c'], dimensions, {+ barLayout: 'stacked',+ seriesTypeOf: typeOfWithDefault('line'),+ barStackedData: computeStackData([b1, b2], ['a', 'b', 'c']),+ })+ const [, domainMax] = scales.y.domain()+ expect(domainMax).toBeGreaterThanOrEqual(60)+ })++ it('keeps bar and line on the same axis under one value scale', () => {+ const bar = makeSeries({ key: 'b', data: [100], type: 'bar' })+ const line = makeSeries({ key: 'l', data: [200], type: 'line' })+ const scales = createComboScales([bar, line], ['a'], dimensions, {+ seriesTypeOf: typeOfWithDefault('line'),+ })+ expect(Object.keys(scales.yAxes)).toEqual([DEFAULT_Y_AXIS_ID])+ })++ it('builds independent scales per yAxisId, each spanning that axis own series only', () => {+ const leftBar = makeSeries({ key: 'lb', data: [10], type: 'bar' })+ const leftLine = makeSeries({ key: 'll', data: [15], type: 'line' })+ const rightLine = makeSeries({ key: 'rl', data: [1000], type: 'line', yAxisId: 'y1' })+ const scales = createComboScales([leftBar, leftLine, rightLine], ['a'], dimensions, {+ seriesTypeOf: typeOfWithDefault('line'),+ })+ expect(scales.yAxes[DEFAULT_Y_AXIS_ID]).not.toBeUndefined()+ expect(scales.yAxes.y1).not.toBeUndefined()+ expect(scales.yAxes.y1.position).toBe('right')+ const [, leftMax] = scales.yAxes[DEFAULT_Y_AXIS_ID].scale.domain()+ expect(leftMax).toBeLessThan(500)+ })++ it('points combo.y at the default axis when present', () => {+ const leftLine = makeSeries({ key: 'l', data: [10] })+ const rightBar = makeSeries({ key: 'r', data: [1000], type: 'bar', yAxisId: 'y1' })+ const scales = createComboScales([leftLine, rightBar], ['a'], dimensions, {+ seriesTypeOf: typeOfWithDefault('line'),+ })+ expect(scales.y(10)).toBe(scales.yAxes[DEFAULT_Y_AXIS_ID].scale(10))+ })++ it('excludes excluded series from the axis domain', () => {+ const visible = makeSeries({ key: 'v', data: [10], type: 'bar' })+ const hidden = makeSeries({+ key: 'h',+ data: [9999],+ type: 'line',+ visibility: { excluded: true },+ })+ const scales = createComboScales([visible, hidden], ['a'], dimensions, {+ seriesTypeOf: typeOfWithDefault('line'),+ barStackedData: computeStackData([visible], ['a']),+ })+ const [, domainMax] = scales.y.domain()+ expect(domainMax).toBeLessThan(100)+ })++ it('returns a fallback [0,1] domain when all axis series are non-finite', () => {+ const s = makeSeries({ key: 's', data: [NaN, NaN], type: 'line' })+ const scales = createComboScales([s], ['a', 'b'], dimensions, {+ seriesTypeOf: typeOfWithDefault('line'),+ })+ expect(scales.y.domain()).toEqual([0, 1])+ })++ it('brackets a degenerate domain when every value is identical', () => {+ // All-equal-to-zero collapses min === max; the shared guard must keep the axis well-formed+ // rather than mapping everything to NaN.+ const s = makeSeries({ key: 's', data: [0, 0, 0], type: 'line' })+ const scales = createComboScales([s], ['a', 'b', 'c'], dimensions, {+ seriesTypeOf: typeOfWithDefault('line'),+ })+ const [min, max] = scales.y.domain()+ expect(max).toBeGreaterThan(min)+ expect(isFinite(scales.y(0))).toBe(true)+ })++ it('builds a log value scale when scaleType is log', () => {+ const s = makeSeries({ key: 's', data: [10, 100, 1000], type: 'line' })+ const scales = createComboScales([s], ['a', 'b', 'c'], dimensions, {+ scaleType: 'log',+ seriesTypeOf: typeOfWithDefault('line'),+ })+ // Larger values map to smaller y-pixels (axis inverted); a log scale stays monotonic.+ expect(scales.y(1000)).toBeLessThan(scales.y(100))+ expect(scales.y(100)).toBeLessThan(scales.y(10))+ })+ })++ describe('createComboScales — stacked bars on a secondary axis', () => {+ it('resolves a stacked bar against its own axis scale, not the primary', () => {+ // Bars stacked on the right axis (values ~thousands) must be positioned against the right+ // scale, not the left one (~tens). Regression guard: `computeBarAtIndex`'s stacked branch+ // is axis-aware so combo can pass the whole scale set for both draw and hit-test.+ const leftBar = makeSeries({ key: 'l', data: [10], type: 'bar' })+ const r1 = makeSeries({ key: 'r1', data: [1000], type: 'bar', yAxisId: 'right' })+ const r2 = makeSeries({ key: 'r2', data: [2000], type: 'bar', yAxisId: 'right' })+ const series = [leftBar, r1, r2]+ const barStackedData = computeStackData(series, ['a'])+ const scales = createComboScales(series, ['a'], dimensions, {+ barLayout: 'stacked',+ seriesTypeOf: typeOfWithDefault('line'),+ barStackedData,+ })+ // r2 is the top of the right-axis stack — its cumulative top is 1000 + 2000 = 3000.+ const bar = computeBarAtIndex({+ series: r2,+ label: 'a',+ dataIndex: 0,+ scales,+ layout: 'stacked',+ isHorizontal: false,+ stackedBand: barStackedData.get('r2'),+ isTopOfStack: true,+ })+ expect(bar).not.toBeNull()+ const rightScale = scales.yAxes.right.scale+ expect(bar!.y).toBeCloseTo(rightScale(3000), 0)+ // The left/primary scale (domain ~[0,10]) would place 3000 far off-plot — confirm it differs.+ expect(Math.abs(bar!.y - scales.y(3000))).toBeGreaterThan(1)+ })+ })++ describe('createComboScales — per-series type defaulting from config', () => {+ it('treats series without explicit type as the configured default', () => {+ const untyped = makeSeries({ key: 'u', data: [50] })+ const scales = createComboScales([untyped], ['a'], dimensions, {+ seriesTypeOf: typeOfWithDefault('bar'),+ barLayout: 'grouped',+ })+ expect(scales.y(50)).toBeLessThan(scales.y(0))+ const [, domainMax] = scales.y.domain()+ expect(domainMax).toBeGreaterThanOrEqual(50)+ })+ })+})diff --git a/packages/quill/packages/charts/src/core/combo-scales.ts b/packages/quill/packages/charts/src/core/combo-scales.tsnew file mode 100644index 000000000000..79916715dee6--- /dev/null+++ b/packages/quill/packages/charts/src/core/combo-scales.ts@@ -0,0 +1,150 @@+import { scaleBand, type ScaleBand } from 'd3-scale'++import {+ buildValueScale,+ type D3YScale,+ groupVisibleSeriesByAxis,+ orderedAxisPositions,+ seriesValueRange,+ type StackedBand,+ yTickCountForHeight,+} from './scales'+import type { ChartDimensions, Series, SeriesType } from './types'+import { DEFAULT_Y_AXIS_ID } from './types'++/** Combo chart scale set — a band x-axis plus per-axis value scales spanning every series on+ * that axis. `yAxes` is always populated (even for single-axis charts) so combo draw code has+ * one lookup path. `group` is the sub-band for grouped bar layout, built from bar-series keys+ * only — lines/areas don't participate.+ *+ * `value` aliases the primary axis scale so the set is structurally a `BarScaleSet` and can be+ * passed straight into the shared bar helpers (`computeBarAtIndex`, `bandCenter`, `resolveBarsAtCursor`);+ * `y`/`yAxes` let `resolveYScaleForSeries` resolve a series' own axis scale. */+export interface ComboScaleSet {+ band: ScaleBand<string>+ yAxes: Record<string, { scale: D3YScale; position: 'left' | 'right' }>+ /** Primary (default/left) axis value scale. */+ y: D3YScale+ /** Alias of `y` — present so this set satisfies `BarScaleSet` for the shared bar helpers. */+ value: D3YScale+ group?: ScaleBand<string>+}++/** Brand for the ComboChart `ChartScales._private` slot. Single source of truth so a shape+ * change in `ComboScaleSet` doesn't drift between consumers. */+export interface ComboChartPrivate {+ __comboChart: ComboScaleSet+}++export interface CreateComboScalesOptions {+ scaleType?: 'linear' | 'log'+ barLayout?: 'stacked' | 'grouped'+ bandPadding?: number+ groupPadding?: number+ seriesTypeOf: (series: Series) => SeriesType+ /** Stacked-band data for bar series. Required when `barLayout` is `'stacked'`. */+ barStackedData?: Map<string, StackedBand>+}++export function resolveSeriesType(series: Pick<Series, 'type'>, defaultType: SeriesType): SeriesType {+ return series.type ?? defaultType+}++export function isLineLike(type: SeriesType): boolean {+ return type === 'line' || type === 'area'+}++export function createComboScales(+ series: Series[],+ labels: string[],+ dimensions: ChartDimensions,+ options: CreateComboScalesOptions+): ComboScaleSet {+ const {+ scaleType = 'linear',+ barLayout = 'stacked',+ bandPadding = 0.2,+ groupPadding = 0.1,+ seriesTypeOf,+ barStackedData,+ } = options++ const band = scaleBand<string>()+ .domain(labels)+ .range([dimensions.plotLeft, dimensions.plotLeft + dimensions.plotWidth])+ .paddingInner(bandPadding)+ .paddingOuter(bandPadding / 2)++ // Sub-band restricted to bar series — lines/areas plot at band centers regardless of+ // grouped-bar offsets, so they do not contribute keys here.+ let group: ScaleBand<string> | undefined+ if (barLayout === 'grouped') {+ const barKeys = series.filter((s) => !s.visibility?.excluded && seriesTypeOf(s) === 'bar').map((s) => s.key)+ group = scaleBand<string>().domain(barKeys).range([0, band.bandwidth()]).padding(groupPadding)+ }++ const tickCount = yTickCountForHeight(dimensions.plotHeight)+ const valueRange: [number, number] = [dimensions.plotTop + dimensions.plotHeight, dimensions.plotTop]++ // Empty chart still needs an axis to draw against.+ const axisPositions = orderedAxisPositions(series)+ if (axisPositions.length === 0) {+ axisPositions.push({ axisId: DEFAULT_Y_AXIS_ID, position: 'left' })+ }+ const seriesByAxis = groupVisibleSeriesByAxis(series)+ const yAxes: ComboScaleSet['yAxes'] = {}+ for (const { axisId, position } of axisPositions) {+ const axisSeries = seriesByAxis.get(axisId) ?? []+ // Per-axis contributions: bars contribute their stacked-top values when stacked, raw+ // otherwise; lines/areas always contribute raw. The value scale spans the union.+ const axisValueSeries: Series[] = axisSeries.map((s) => {+ const stacked = barStackedData?.get(s.key)+ if (seriesTypeOf(s) === 'bar' && barLayout === 'stacked' && stacked) {+ return { ...s, data: stacked.top }+ }+ return s+ })+ yAxes[axisId] = { scale: buildComboValueScale(axisValueSeries, valueRange, tickCount, scaleType), position }+ }++ const primaryAxisId = axisPositions.some((a) => a.axisId === DEFAULT_Y_AXIS_ID)+ ? DEFAULT_Y_AXIS_ID+ : axisPositions[0].axisId+ const primary = yAxes[primaryAxisId].scale++ return { band, group, yAxes, y: primary, value: primary }+}++function buildComboValueScale(+ series: Series[],+ valueRange: [number, number],+ tickCount: number,+ scaleType: 'linear' | 'log'+): D3YScale {+ const range = seriesValueRange(series)+ const primaryRange = series.some((s) => s.overlay) ? seriesValueRange(series.filter((s) => !s.overlay)) : range+ // Shares `createYScale`'s overlay baseline clamp, degenerate `min === max` guard, and log+ // fallback — see `buildValueScale`.+ return buildValueScale({ range, primaryRange, valueRange, tickCount, scaleType })+}++/** Partition visible series into bar vs line/area buckets, preserving input order within each+ * bucket. Excluded series are dropped. */+export function partitionByType<S extends Pick<Series, 'visibility'>>(+ series: readonly S[],+ typeOf: (s: S) => SeriesType+): { bars: S[]; lines: S[] } {+ const bars: S[] = []+ const lines: S[] = []+ for (const s of series) {+ if (s.visibility?.excluded) {+ continue+ }+ if (typeOf(s) === 'bar') {+ bars.push(s)+ } else {+ lines.push(s)+ }+ }+ return { bars, lines }+}diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex cc3454b8cfa8..5229d90a2c73 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -21,6 +21,12 @@ export const DEFAULT_Y_AXIS_ID = 'left'* with color either supplied or omitted (chart picks one) and let the chart resolve it. */export type ResolvedSeries<Meta = unknown> = Series<Meta> & { color: string }+/** How a series is rendered in a mixed-type chart. */+export type SeriesType = 'line' | 'bar' | 'area'++/** Series type assumed when a `Series` sets no explicit `type`. */+export const DEFAULT_SERIES_TYPE: SeriesType = 'line'+export interface Series<Meta = unknown> {/** Unique identifier used to key React elements and look up stacked data. */key: string@@ -38,6 +44,10 @@ export interface Series<Meta = unknown> {bars?: { color?: string; label?: string; meta?: Meta }[]/** Which y-axis this series is scaled against. Defaults to {@link DEFAULT_Y_AXIS_ID}. */yAxisId?: string+ /** Mixed-type charts ({@link ComboChart}) read this to draw the series as a bar, line, or+ * area. Falls back to the chart's `defaultSeriesType` when omitted. Ignored by single-type+ * charts. */+ type?: SeriesType/** Arbitrary consumer data attached to this series. Flows through to TooltipContext* so custom tooltip components can access domain-specific information (e.g. breakdown* values, comparison labels, anomaly scores) without the library needing to know about them.@@ -344,6 +354,20 @@ export interface LineChartConfig extends ChartConfig {legend?: ChartLegendConfig}+/** Config for {@link ComboChart}, which draws bar, line, and area series together. `axisOrientation`+ * is omitted on purpose — bars require a band x-axis, so combo charts are vertical-only. Percent+ * layout is also unsupported: stack-as-percent is only meaningful when every series participates,+ * but lines/areas draw unstacked. */+export interface ComboChartConfig extends Omit<ChartConfig, 'axisOrientation'> {+ /** Type used for series that don't set {@link Series.type}. Defaults to `'line'`. */+ defaultSeriesType?: SeriesType+ /** Layout applied to *bar* series only — lines and areas never stack or group. Defaults to+ * `'stacked'`. */+ barLayout?: 'stacked' | 'grouped'+ /** Corner radius for the cap of bar segments. Stacked bars only round the topmost segment. */+ barCornerRadius?: number+}+/** Arguments passed to a chart type's canvas draw function. */export interface ChartDrawArgs {/** 2D canvas rendering context (DPR already applied, save/restore handled by Chart). */diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.tsindex c4c0fe3005b0..8d708792f13a 100644--- a/packages/quill/packages/charts/src/index.ts+++ b/packages/quill/packages/charts/src/index.ts@@ -3,6 +3,8 @@ export { BarChart } from './charts/BarChart/BarChart'export type { BarChartProps } from './charts/BarChart/BarChart'export { LineChart } from './charts/LineChart/LineChart'export type { LineChartProps } from './charts/LineChart/LineChart'+export { ComboChart } from './charts/ComboChart/ComboChart'+export type { ComboChartProps } from './charts/ComboChart/ComboChart'export { TimeSeriesLineChart } from './charts/TimeSeriesLineChart/TimeSeriesLineChart'export type {ConfidenceIntervalConfig,@@ -83,6 +85,7 @@ export type {ChartMargins,ChartScales,ChartTheme,+ ComboChartConfig,CreateScalesFn,DateRangeZoomData,DragRect,@@ -91,6 +94,7 @@ export type {ResolvedSeries,ResolveValueFn,Series,+ SeriesType,TooltipConfig,TooltipContext,ValueDomain,