Skip to content

: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.

feat(sql insights): add SQL line graph via quill-charts (#64282)

Sam Pennington7d9560ff596b
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index e8d8be65f0b3..60185023973e 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -422,6 +422,7 @@ export const FEATURE_FLAGS = {
PRODUCT_ANALYTICS_HIDE_WEEKENDS: 'product-analytics-hide-weekends', // owner: @kliment-slice #team-irl-events
PRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analytics
PRODUCT_ANALYTICS_PATHS_V2: 'paths-v2', // owner: @thmsobrmlr #team-product-analytics
+ PRODUCT_ANALYTICS_QUILL_SQL_CHARTS: 'product-analytics-quill-sql-charts', // owner: #team-data-tools, gates rendering DataVisualization line/area charts via @posthog/quill-charts
PRODUCT_ANALYTICS_RETENTION_AGGREGATION: 'retention-aggregation', // owner: @anirudhpillai #team-product-analytics
PRODUCT_ANALYTICS_RETENTION_DWH: 'retention-dwh', // owner: @thmsobrmlr #team-product-analytics
PRODUCT_AUTONOMY: 'product-autonomy', // owner: #team-signals
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx
index 9dc5cbaebeee..c0e890b72753 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx
@@ -10,7 +10,7 @@ import { useActions, useValues } from 'kea'
import { useEffect, useMemo } from 'react'
import { IconX } from '@posthog/icons'
-import { LemonTable, lemonToast } from '@posthog/lemon-ui'
+import { LemonTable } from '@posthog/lemon-ui'
import { createXAxisTickCallback } from '@posthog/quill-charts'
import {
@@ -30,8 +30,10 @@ import {
import { resolveVariableColor } from 'lib/charts/utils/color'
import { getGraphColors, getSeriesColor } from 'lib/colors'
import { InsightLabel } from 'lib/components/InsightLabel'
+import { FEATURE_FLAGS } from 'lib/constants'
import { useChart } from 'lib/hooks/useChart'
import { useKeyHeld } from 'lib/hooks/useKeyHeld'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { hexToRGBA } from 'lib/utils/colors'
import { uuid } from 'lib/utils/dom'
import { unpinTooltip, useInsightTooltip } from 'scenes/insights/useInsightTooltip'
@@ -43,6 +45,15 @@ import { ChartDisplayType, GraphType } from '~/types'
import { AxisSeries, AxisSeriesSettings, formatDataWithSettings } from '../../dataVisualizationLogic'
import { AxisBreakdownSeries } from '../seriesBreakdownLogic'
import { lineGraphLogic } from './lineGraphLogic'
+import { SqlLineGraph } from './SqlLineGraph'
+import {
+ AREA_FILL_OPACITY,
+ canRenderSqlLineGraph,
+ capYSeriesData,
+ exceedsMaxSeries,
+ isAreaSeries,
+ warnTooManySeries,
+} from './sqlLineGraphAdapter'
Chart.register(annotationPlugin)
Chart.register(ChartjsPluginStacked100)
@@ -62,10 +73,6 @@ const getGraphType = (chartType: ChartDisplayType, settings: AxisSeriesSettings
return GraphType.Line
}
-const isAreaSeries = (chartType: ChartDisplayType, settings: AxisSeriesSettings | undefined): boolean => {
- return chartType === ChartDisplayType.ActionsAreaGraph || settings?.display?.displayType === 'area'
-}
-
const axisLabelFont = {
family: '"Emoji Flags Polyfill", -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", "Roboto", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"',
size: 12,
@@ -134,8 +141,7 @@ export type LineGraphProps = {
className?: string
}
-// LineGraph displays a graph using either x and y data or series breakdown data
-export const LineGraph = ({
+const LegacyLineGraph = ({
xData,
yData,
presetChartHeight,
@@ -167,22 +173,14 @@ export const LineGraph = ({
const isAreaChart = visualizationType === ChartDisplayType.ActionsAreaGraph
const isHighlightBarMode = isBarChart && isStackedBarChart && isShiftPressed
- const MAX_SERIES = 200
- const ySeriesData = useMemo(() => {
- if (!yData) {
- return null
- }
- if (yData.length > MAX_SERIES) {
- if (!dashboardId) {
- lemonToast.warning(
- `This breakdown has too many series (${yData.length}). Only showing top ${MAX_SERIES} series in the chart. All series are still available in the table below.`
- )
- }
- return yData.slice(0, MAX_SERIES)
+ useEffect(() => {
+ if (exceedsMaxSeries(yData, dashboardId)) {
+ warnTooManySeries(yData!.length)
}
- return yData
}, [yData, dashboardId])
+ const ySeriesData = useMemo(() => capYSeriesData(yData), [yData])
+
const datasets = useMemo(() => {
if (!ySeriesData) {
return null
@@ -191,7 +189,7 @@ export const LineGraph = ({
return ySeriesData.map(({ data: seriesData, settings, ...rest }, index) => {
const seriesColor = settings?.display?.color ?? getSeriesColor(index)
const hasAreaFill = isAreaSeries(visualizationType, settings)
- let backgroundColor = hasAreaFill ? hexToRGBA(seriesColor, 0.5) : seriesColor
+ let backgroundColor = hasAreaFill ? hexToRGBA(seriesColor, AREA_FILL_OPACITY) : seriesColor
// Dim non-hovered bars in stacked bar charts when shift is pressed
if (isHighlightBarMode && hoveredDatasetIndex !== null && index !== hoveredDatasetIndex) {
@@ -729,3 +727,14 @@ export const LineGraph = ({
</div>
)
}
+
+export const LineGraph = (props: LineGraphProps): JSX.Element => {
+ const { featureFlags } = useValues(featureFlagLogic)
+ const newChartsEnabled = !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_QUILL_SQL_CHARTS]
+
+ if (newChartsEnabled && canRenderSqlLineGraph(props)) {
+ return <SqlLineGraph {...props} />
+ }
+
+ return <LegacyLineGraph {...props} />
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
new file mode 100644
index 000000000000..29e9b7d0b057
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
@@ -0,0 +1,49 @@
+import clsx from 'clsx'
+
+import { ChartLegend, TimeSeriesLineChart } from '@posthog/quill-charts'
+
+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
+
+import { LineGraphProps } from './LineGraph'
+import { useSqlLineGraph } from './useSqlLineGraph'
+
+const handleChartError = makeChartErrorHandler('sql-line-chart')
+
+/**
+ * SQL line/area graph rendered via @posthog/quill-charts, gated behind the
+ * `product-analytics-quill-sql-charts` flag (see {@link LineGraph}). Handles line, area, and goal
+ * lines; everything else falls back to the legacy chart.js path. Tooltip content is quill's
+ * DefaultTooltip — the rich InsightTooltip isn't bridged over yet.
+ */
+export const SqlLineGraph = (props: LineGraphProps): JSX.Element => {
+ const model = useSqlLineGraph(props)
+
+ // Keep the styled container even with no data, matching the legacy path's background shell.
+ return (
+ <div
+ className={clsx(
+ props.className,
+ 'rounded bg-surface-primary w-full grow relative overflow-hidden flex flex-col',
+ { 'h-[60vh]': props.presetChartHeight, 'h-full': !props.presetChartHeight }
+ )}
+ >
+ {model && (
+ <ChartLegend
+ show={model.legendItems.length > 0}
+ items={model.legendItems}
+ hiddenKeys={model.hiddenKeys}
+ onItemClick={model.toggleSeries}
+ position="top"
+ >
+ <TimeSeriesLineChart
+ series={model.series}
+ labels={model.labels}
+ theme={model.theme}
+ config={model.config}
+ onError={handleChartError}
+ />
+ </ChartLegend>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
new file mode 100644
index 000000000000..dc8d0e65ce13
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
@@ -0,0 +1,175 @@
+import { ChartSettings } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+import { AxisSeries } from '../../dataVisualizationLogic'
+import { AxisBreakdownSeries } from '../seriesBreakdownLogic'
+import { LineGraphProps } from './LineGraph'
+import {
+ AREA_FILL_OPACITY,
+ MAX_SERIES,
+ buildLineChartConfig,
+ buildSeries,
+ canRenderSqlLineGraph,
+ capYSeriesData,
+ exceedsMaxSeries,
+} from './sqlLineGraphAdapter'
+
+const numericColumn = (name: string, dataIndex: number): AxisSeries<number | null>['column'] => ({
+ name,
+ type: { name: 'INTEGER', isNumerical: true },
+ label: name,
+ dataIndex,
+})
+
+const ySeries = (
+ name: string,
+ data: (number | null)[],
+ settings: AxisSeries<number | null>['settings'] = {}
+): AxisSeries<number | null> => ({ column: numericColumn(name, 1), data, settings })
+
+const breakdownSeries = (
+ breakdownValue: string,
+ data: (number | null)[],
+ settings: AxisBreakdownSeries<number | null>['settings'] = {}
+): AxisBreakdownSeries<number | null> => ({ name: breakdownValue, breakdownValue, data, settings })
+
+const baseProps = (overrides: Partial<LineGraphProps>): LineGraphProps => ({
+ xData: null,
+ yData: [],
+ visualizationType: ChartDisplayType.ActionsLineGraph,
+ chartSettings: {},
+ ...overrides,
+})
+
+describe('sqlLineGraphAdapter', () => {
+ describe('canRenderSqlLineGraph', () => {
+ it.each([
+ ['line graph', ChartDisplayType.ActionsLineGraph, true],
+ ['area graph', ChartDisplayType.ActionsAreaGraph, true],
+ ['bar graph', ChartDisplayType.ActionsBar, false],
+ ['stacked bar graph', ChartDisplayType.ActionsStackedBar, false],
+ ])('returns %s support correctly for %s', (_name, visualizationType, expected) => {
+ expect(canRenderSqlLineGraph(baseProps({ visualizationType }))).toBe(expected)
+ })
+
+ it('falls back when any series renders as a bar', () => {
+ const yData = [ySeries('a', [1]), ySeries('b', [2], { display: { displayType: 'bar' } })]
+ expect(canRenderSqlLineGraph(baseProps({ yData }))).toBe(false)
+ })
+
+ it('falls back when any series has a trend line', () => {
+ const yData = [ySeries('a', [1], { display: { trendLine: true } })]
+ expect(canRenderSqlLineGraph(baseProps({ yData }))).toBe(false)
+ })
+
+ it('falls back when any series targets the right y-axis', () => {
+ const yData = [ySeries('a', [1], { display: { yAxisPosition: 'right' } })]
+ expect(canRenderSqlLineGraph(baseProps({ yData }))).toBe(false)
+ })
+ })
+
+ describe('exceedsMaxSeries', () => {
+ const tooMany = Array.from({ length: MAX_SERIES + 1 }, (_, i) => ySeries(`s${i}`, [i]))
+
+ it('is true above the cap outside a dashboard', () => {
+ expect(exceedsMaxSeries(tooMany, undefined)).toBe(true)
+ })
+
+ it('is false above the cap on a dashboard', () => {
+ expect(exceedsMaxSeries(tooMany, 'dash-1')).toBe(false)
+ })
+
+ it('is false at or below the cap', () => {
+ expect(exceedsMaxSeries([ySeries('a', [1])], undefined)).toBe(false)
+ })
+ })
+
+ describe('capYSeriesData', () => {
+ it('returns null for missing data', () => {
+ expect(capYSeriesData(undefined as unknown as LineGraphProps['yData'])).toBeNull()
+ })
+
+ it('returns the data unchanged at or below the cap', () => {
+ const yData = [ySeries('a', [1]), ySeries('b', [2])]
+ expect(capYSeriesData(yData)).toBe(yData)
+ })
+
+ it('slices to the cap when exceeded', () => {
+ const yData = Array.from({ length: MAX_SERIES + 5 }, (_, i) => ySeries(`s${i}`, [i]))
+ expect(capYSeriesData(yData)).toHaveLength(MAX_SERIES)
+ })
+ })
+
+ describe('buildSeries', () => {
+ it('maps nulls to NaN so quill draws gaps', () => {
+ const [series] = buildSeries([ySeries('a', [1, null, 3])], ChartDisplayType.ActionsLineGraph)
+ expect(series.data).toEqual([1, NaN, 3])
+ })
+
+ it('only pins an explicit color, leaving palette assignment to quill otherwise', () => {
+ const [withColor, withoutColor] = buildSeries(
+ [ySeries('a', [1], { display: { color: '#abcdef' } }), ySeries('b', [2])],
+ ChartDisplayType.ActionsLineGraph
+ )
+ expect(withColor.color).toBe('#abcdef')
+ expect(withoutColor.color).toBeUndefined()
+ })
+
+ it('adds an area fill for area graphs', () => {
+ const [series] = buildSeries([ySeries('a', [1])], ChartDisplayType.ActionsAreaGraph)
+ expect(series.fill).toEqual({ opacity: AREA_FILL_OPACITY })
+ })
+
+ it('adds an area fill when a series opts into area display', () => {
+ const [series] = buildSeries(
+ [ySeries('a', [1], { display: { displayType: 'area' } })],
+ ChartDisplayType.ActionsLineGraph
+ )
+ expect(series.fill).toEqual({ opacity: AREA_FILL_OPACITY })
+ })
+
+ it('omits the fill for plain line graphs', () => {
+ const [series] = buildSeries([ySeries('a', [1])], ChartDisplayType.ActionsLineGraph)
+ expect(series.fill).toBeUndefined()
+ })
+
+ it('keys breakdown series by breakdown value', () => {
+ const [series] = buildSeries([breakdownSeries('chrome', [1])], ChartDisplayType.ActionsLineGraph)
+ expect(series.key).toBe('chrome')
+ })
+ })
+
+ describe('buildLineChartConfig', () => {
+ const dateXData: AxisSeries<string> = {
+ column: { name: 'day', type: { name: 'DATE', isNumerical: false }, label: 'day', dataIndex: 0 },
+ data: ['2024-01-01', '2024-01-02'],
+ }
+ const stringXData: AxisSeries<string> = {
+ column: { name: 'name', type: { name: 'STRING', isNumerical: false }, label: 'name', dataIndex: 0 },
+ data: ['a', 'b'],
+ }
+
+ it('adds an x-axis tick formatter for date axes', () => {
+ const config = buildLineChartConfig({ xData: dateXData, chartSettings: {}, timezone: 'UTC' })
+ expect(config.xAxis?.tickFormatter).toBeInstanceOf(Function)
+ })
+
+ it('omits the tick formatter for non-date axes', () => {
+ const config = buildLineChartConfig({ xData: stringXData, chartSettings: {}, timezone: 'UTC' })
+ expect(config.xAxis?.tickFormatter).toBeUndefined()
+ })
+
+ it('maps logarithmic scale and y-axis settings', () => {
+ const chartSettings: ChartSettings = {
+ leftYAxisSettings: { label: 'Count', scale: 'logarithmic', showGridLines: false, showTicks: false },
+ }
+ const config = buildLineChartConfig({ xData: dateXData, chartSettings, timezone: 'UTC' })
+ expect(config.yAxis).toMatchObject({ label: 'Count', scale: 'log', showGrid: false, hide: true })
+ })
+
+ it('defaults to a linear scale with grid shown', () => {
+ const config = buildLineChartConfig({ xData: dateXData, chartSettings: {}, timezone: 'UTC' })
+ expect(config.yAxis).toMatchObject({ scale: 'linear', showGrid: true })
+ })
+ })
+})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
new file mode 100644
index 000000000000..0849301136bb
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
@@ -0,0 +1,122 @@
+import { lemonToast } from '@posthog/lemon-ui'
+import { type Series, type TimeSeriesLineChartConfig, createXAxisTickCallback } from '@posthog/quill-charts'
+
+import { ChartSettings, GoalLine } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+import { schemaGoalLinesToConfigs } from 'products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter'
+
+import { AxisSeries, AxisSeriesSettings } from '../../dataVisualizationLogic'
+import { AxisBreakdownSeries } from '../seriesBreakdownLogic'
+import { LineGraphProps } from './LineGraph'
+
+export const MAX_SERIES = 200
+
+/** Matches the legacy path's `hexToRGBA(seriesColor, 0.5)` area fill. */
+export const AREA_FILL_OPACITY = 0.5
+
+export type SqlLineYSeries = AxisSeries<number | null> | AxisBreakdownSeries<number | null>
+
+export const isAreaSeries = (visualizationType: ChartDisplayType, settings: AxisSeriesSettings | undefined): boolean =>
+ visualizationType === ChartDisplayType.ActionsAreaGraph || settings?.display?.displayType === 'area'
+
+const getSeriesLabel = (series: SqlLineYSeries): string => ('name' in series ? series.name : series.column.name)
+
+const getSeriesKey = (series: SqlLineYSeries, index: number): string =>
+ 'breakdownValue' in series ? series.breakdownValue : `${series.column.name}-${index}`
+
+/**
+ * Plain line/area charts — including goal lines — render here. Trend lines, mixed line/bar series,
+ * and right y-axis series aren't ported yet, so those fall back to the legacy chart.js path.
+ */
+export function canRenderSqlLineGraph(props: LineGraphProps): boolean {
+ const { visualizationType, yData } = props
+
+ if (
+ visualizationType !== ChartDisplayType.ActionsLineGraph &&
+ visualizationType !== ChartDisplayType.ActionsAreaGraph
+ ) {
+ return false
+ }
+ if (yData?.some((series) => series.settings?.display?.displayType === 'bar')) {
+ return false
+ }
+ if (yData?.some((series) => series.settings?.display?.trendLine)) {
+ return false
+ }
+ // quill applies a single tick formatter/scale to both gutters, so a right axis can't honor its
+ // own settings yet — fall back to legacy rather than silently dropping those prefs.
+ if (yData?.some((series) => series.settings?.display?.yAxisPosition === 'right')) {
+ return false
+ }
+ return true
+}
+
+/** Returns true when {@link MAX_SERIES} is exceeded and the user should be warned (not on dashboards). */
+export function exceedsMaxSeries(yData: LineGraphProps['yData'], dashboardId: LineGraphProps['dashboardId']): boolean {
+ return !!yData && yData.length > MAX_SERIES && !dashboardId
+}
+
+export function warnTooManySeries(count: number): void {
+ lemonToast.warning(
+ `This breakdown has too many series (${count}). Only showing top ${MAX_SERIES} series in the chart. All series are still available in the table below.`
+ )
+}
+
+/** Pure cap to {@link MAX_SERIES}; warn separately via {@link exceedsMaxSeries}/{@link warnTooManySeries}. */
+export function capYSeriesData(yData: LineGraphProps['yData']): SqlLineYSeries[] | null {
+ if (!yData) {
+ return null
+ }
+ return yData.length > MAX_SERIES ? yData.slice(0, MAX_SERIES) : yData
+}
+
+export function buildSeries(yData: SqlLineYSeries[], visualizationType: ChartDisplayType): Series[] {
+ return yData.map((series, index) => {
+ const settings = series.settings
+ const color = settings?.display?.color
+
+ return {
+ key: getSeriesKey(series, index),
+ label: getSeriesLabel(series),
+ // null -> NaN so quill draws a gap rather than a zero.
+ data: series.data.map((value) => (value == null ? NaN : value)),
+ // Only pin an explicit color; otherwise let quill assign palette colors by index.
+ ...(color ? { color } : {}),
+ ...(isAreaSeries(visualizationType, settings) ? { fill: { opacity: AREA_FILL_OPACITY } } : {}),
+ }
+ })
+}
+
+interface BuildConfigArgs {
+ xData: AxisSeries<string>
+ chartSettings: ChartSettings
+ timezone: string
+ goalLines?: GoalLine[]
+}
+
+export function buildLineChartConfig({
+ xData,
+ chartSettings,
+ timezone,
+ goalLines,
+}: BuildConfigArgs): TimeSeriesLineChartConfig {
+ const isDateAxis = xData.column.type.name === 'DATE' || xData.column.type.name === 'DATETIME'
+ const yAxis = chartSettings.leftYAxisSettings
+
+ return {
+ xAxis: {
+ label: chartSettings.xAxisLabel,
+ tickFormatter: isDateAxis ? createXAxisTickCallback({ allDays: xData.data, timezone }) : undefined,
+ hide: chartSettings.showXAxisTicks === false,
+ },
+ yAxis: {
+ label: yAxis?.label,
+ scale: yAxis?.scale === 'logarithmic' ? 'log' : 'linear',
+ showGrid: yAxis?.showGridLines ?? true,
+ hide: yAxis?.showTicks === false,
+ },
+ goalLines: schemaGoalLinesToConfigs(goalLines),
+ tooltip: { enabled: true, pinnable: true },
+ }
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlLineGraph.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlLineGraph.ts
new file mode 100644
index 000000000000..dc40b097513e
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlLineGraph.ts
@@ -0,0 +1,96 @@
+import { useValues } from 'kea'
+import { useCallback, useEffect, useMemo, useState } from 'react'
+
+import {
+ type ChartTheme,
+ type LegendItem,
+ type Series,
+ type TimeSeriesLineChartConfig,
+ legendItemsFromSeries,
+} from '@posthog/quill-charts'
+
+import { buildTheme } from 'lib/charts/utils/theme'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+
+import { LineGraphProps } from './LineGraph'
+import {
+ buildLineChartConfig,
+ buildSeries,
+ capYSeriesData,
+ exceedsMaxSeries,
+ warnTooManySeries,
+} from './sqlLineGraphAdapter'
+
+export interface SqlLineGraphModel {
+ series: Series[]
+ labels: string[]
+ theme: ChartTheme
+ config: TimeSeriesLineChartConfig
+ legendItems: LegendItem[]
+ hiddenKeys: string[]
+ toggleSeries: (key: string) => void
+}
+
+export function useSqlLineGraph({
+ xData,
+ yData,
+ visualizationType,
+ chartSettings,
+ dashboardId,
+ goalLines,
+}: LineGraphProps): SqlLineGraphModel | null {
+ const { timezone } = useValues(teamLogic)
+ const { isDarkModeOn } = useValues(themeLogic)
+ const [hiddenKeys, setHiddenKeys] = useState<string[]>([])
+
+ // Fire the cap warning as a side effect — capYSeriesData itself stays pure.
+ useEffect(() => {
+ if (exceedsMaxSeries(yData, dashboardId)) {
+ warnTooManySeries(yData!.length)
+ }
+ }, [yData, dashboardId])
+
+ const ySeriesData = useMemo(() => capYSeriesData(yData), [yData])
+
+ const allSeries = useMemo(
+ () => (ySeriesData ? buildSeries(ySeriesData, visualizationType) : []),
+ [ySeriesData, visualizationType]
+ )
+
+ // buildTheme reads CSS vars at call time; re-derive when the user toggles light/dark.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])
+
+ const config = useMemo(
+ () => (xData ? buildLineChartConfig({ xData, chartSettings, timezone, goalLines }) : undefined),
+ [xData, chartSettings, timezone, goalLines]
+ )
+
+ const showLegend = chartSettings.showLegend ?? false
+ const legendItems = useMemo(
+ () => (showLegend ? legendItemsFromSeries(allSeries, theme) : []),
+ [showLegend, allSeries, theme]
+ )
+
+ // Hidden series are excluded from rendering/scale/hit-testing; the legend still shows them dimmed.
+ const series = useMemo(() => {
+ if (hiddenKeys.length === 0) {
+ return allSeries
+ }
+ const hidden = new Set(hiddenKeys)
+ return allSeries.map((s) => (hidden.has(s.key) ? { ...s, visibility: { ...s.visibility, excluded: true } } : s))
+ }, [allSeries, hiddenKeys])
+
+ const toggleSeries = useCallback(
+ (key: string) => setHiddenKeys((keys) => (keys.includes(key) ? keys.filter((k) => k !== key) : [...keys, key])),
+ []
+ )
+
+ if (!xData || !ySeriesData || allSeries.length === 0 || !config) {
+ return null
+ }
+
+ return { series, labels: xData.data, theme, config, legendItems, hiddenKeys, toggleSeries }
+}