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): render bar charts via quill-charts (#64625)

Sam Pennington888776c6629e
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.test.ts
new file mode 100644
index 000000000000..27bd83da620e
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.test.ts
@@ -0,0 +1,21 @@
+import { ChartDisplayType } from '~/types'
+
+import { LineGraphProps, sqlChartComponentFor } from './LineGraph'
+
+const baseProps = (visualizationType: ChartDisplayType): LineGraphProps => ({
+ xData: null,
+ yData: [],
+ visualizationType,
+ chartSettings: {},
+})
+
+describe('sqlChartComponentFor', () => {
+ it.each([
+ ['line', ChartDisplayType.ActionsLineGraph, true, 'SqlLineGraph'],
+ ['bar', ChartDisplayType.ActionsBar, true, 'SqlBarGraph'],
+ ['line with the flag off', ChartDisplayType.ActionsLineGraph, false, 'LegacyLineGraph'],
+ ['an unsupported visualization', ChartDisplayType.ActionsPie, true, 'LegacyLineGraph'],
+ ])('routes %s to the right component', (_name, visualizationType, newChartsEnabled, expected) => {
+ expect(sqlChartComponentFor(baseProps(visualizationType), newChartsEnabled).name).toBe(expected)
+ })
+})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx
index c0e890b72753..04cef3747379 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/LineGraph.tsx
@@ -45,9 +45,11 @@ import { ChartDisplayType, GraphType } from '~/types'
import { AxisSeries, AxisSeriesSettings, formatDataWithSettings } from '../../dataVisualizationLogic'
import { AxisBreakdownSeries } from '../seriesBreakdownLogic'
import { lineGraphLogic } from './lineGraphLogic'
+import { SqlBarGraph } from './SqlBarGraph'
import { SqlLineGraph } from './SqlLineGraph'
import {
AREA_FILL_OPACITY,
+ canRenderSqlBarGraph,
canRenderSqlLineGraph,
capYSeriesData,
exceedsMaxSeries,
@@ -728,13 +730,23 @@ const LegacyLineGraph = ({
)
}
+export function sqlChartComponentFor(
+ props: LineGraphProps,
+ newChartsEnabled: boolean
+): (props: LineGraphProps) => JSX.Element {
+ if (newChartsEnabled && canRenderSqlLineGraph(props)) {
+ return SqlLineGraph
+ }
+ if (newChartsEnabled && canRenderSqlBarGraph(props)) {
+ return SqlBarGraph
+ }
+ return LegacyLineGraph
+}
+
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} />
+ const Component = sqlChartComponentFor(props, newChartsEnabled)
+ return <Component {...props} />
}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx
new file mode 100644
index 000000000000..c969a5d13856
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx
@@ -0,0 +1,35 @@
+import clsx from 'clsx'
+
+import { TimeSeriesBarChart } from '@posthog/quill-charts'
+
+import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
+
+import { LineGraphProps } from './LineGraph'
+import { buildBarChartConfig } from './sqlLineGraphAdapter'
+import { useSqlChartModel } from './useSqlChartModel'
+
+const handleChartError = makeChartErrorHandler('sql-bar-chart')
+
+export const SqlBarGraph = (props: LineGraphProps): JSX.Element => {
+ const model = useSqlChartModel(props, buildBarChartConfig)
+
+ 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 && (
+ <TimeSeriesBarChart
+ series={model.series}
+ labels={model.labels}
+ theme={model.theme}
+ config={model.config}
+ onError={handleChartError}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
index d258652edab0..dd2812572dee 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
@@ -1,13 +1,13 @@
import clsx from 'clsx'
import { useCallback } from 'react'
-import { ChartLegend, DefaultTooltip, TimeSeriesLineChart, type TooltipContext } from '@posthog/quill-charts'
+import { DefaultTooltip, TimeSeriesLineChart, type TooltipContext } from '@posthog/quill-charts'
import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
import { LineGraphProps } from './LineGraph'
-import { SqlLineSeriesMeta, formatSqlSeriesValue } from './sqlLineGraphAdapter'
-import { useSqlLineGraph } from './useSqlLineGraph'
+import { SqlLineSeriesMeta, buildLineChartConfig, formatSqlSeriesValue } from './sqlLineGraphAdapter'
+import { useSqlChartModel } from './useSqlChartModel'
const handleChartError = makeChartErrorHandler('sql-line-chart')
@@ -18,7 +18,7 @@ const handleChartError = makeChartErrorHandler('sql-line-chart')
* DefaultTooltip extended to format each row with its column's own settings and to show a total row.
*/
export const SqlLineGraph = (props: LineGraphProps): JSX.Element => {
- const model = useSqlLineGraph(props)
+ const model = useSqlChartModel(props, buildLineChartConfig)
const { chartSettings } = props
const totalSettings = model?.totalFormatterSettings
@@ -36,7 +36,6 @@ export const SqlLineGraph = (props: LineGraphProps): JSX.Element => {
[showTotalRow, totalSettings]
)
- // Keep the styled container even with no data, matching the legacy path's background shell.
return (
<div
className={clsx(
@@ -46,22 +45,14 @@ export const SqlLineGraph = (props: LineGraphProps): JSX.Element => {
)}
>
{model && (
- <ChartLegend
- show={model.legendItems.length > 0}
- items={model.legendItems}
- hiddenKeys={model.hiddenKeys}
- onItemClick={model.toggleSeries}
- position="top"
- >
- <TimeSeriesLineChart<SqlLineSeriesMeta>
- series={model.series}
- labels={model.labels}
- theme={model.theme}
- config={model.config}
- tooltip={renderTooltip}
- onError={handleChartError}
- />
- </ChartLegend>
+ <TimeSeriesLineChart<SqlLineSeriesMeta>
+ series={model.series}
+ labels={model.labels}
+ theme={model.theme}
+ config={model.config}
+ tooltip={renderTooltip}
+ onError={handleChartError}
+ />
)}
</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
index b42de43aacc2..81ec8f610bb6 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
@@ -1,4 +1,4 @@
-import { ChartSettings } from '~/queries/schema/schema-general'
+import { ChartSettings, GoalLine } from '~/queries/schema/schema-general'
import { ChartDisplayType } from '~/types'
import { AxisSeries } from '../../dataVisualizationLogic'
@@ -7,8 +7,11 @@ import { LineGraphProps } from './LineGraph'
import {
AREA_FILL_OPACITY,
MAX_SERIES,
+ barLayoutForDisplay,
+ buildBarChartConfig,
buildLineChartConfig,
buildSeries,
+ canRenderSqlBarGraph,
canRenderSqlLineGraph,
capYSeriesData,
exceedsMaxSeries,
@@ -69,6 +72,56 @@ describe('sqlLineGraphAdapter', () => {
})
})
+ describe('canRenderSqlBarGraph', () => {
+ it.each([
+ ['line graph', ChartDisplayType.ActionsLineGraph, false],
+ ['area graph', ChartDisplayType.ActionsAreaGraph, false],
+ ['bar graph', ChartDisplayType.ActionsBar, true],
+ ['stacked bar graph', ChartDisplayType.ActionsStackedBar, true],
+ ])('returns %s support correctly for %s', (_name, visualizationType, expected) => {
+ expect(canRenderSqlBarGraph(baseProps({ visualizationType }))).toBe(expected)
+ })
+
+ it.each([
+ ['line', 'line' as const],
+ ['area', 'area' as const],
+ ])('falls back when any series overrides display to %s (mixed combo chart)', (_name, displayType) => {
+ const yData = [ySeries('a', [1]), ySeries('b', [2], { display: { displayType } })]
+ expect(canRenderSqlBarGraph(baseProps({ visualizationType: ChartDisplayType.ActionsBar, yData }))).toBe(
+ false
+ )
+ })
+
+ it('falls back when any series has a trend line', () => {
+ const yData = [ySeries('a', [1], { display: { trendLine: true } })]
+ expect(canRenderSqlBarGraph(baseProps({ visualizationType: ChartDisplayType.ActionsBar, yData }))).toBe(
+ false
+ )
+ })
+
+ it('falls back when any series targets the right y-axis', () => {
+ const yData = [ySeries('a', [1], { display: { yAxisPosition: 'right' } })]
+ expect(canRenderSqlBarGraph(baseProps({ visualizationType: ChartDisplayType.ActionsBar, yData }))).toBe(
+ false
+ )
+ })
+ })
+
+ describe('barLayoutForDisplay', () => {
+ it.each([
+ ['grouped bars for a bar graph', ChartDisplayType.ActionsBar, {}, 'grouped'],
+ ['stacked bars for a stacked bar graph', ChartDisplayType.ActionsStackedBar, {}, 'stacked'],
+ [
+ 'percent bars when stackBars100 is on for a stacked bar graph',
+ ChartDisplayType.ActionsStackedBar,
+ { stackBars100: true },
+ 'percent',
+ ],
+ ])('returns %s', (_name, visualizationType, chartSettings, expected) => {
+ expect(barLayoutForDisplay(visualizationType, chartSettings as ChartSettings)).toBe(expected)
+ })
+ })
+
describe('exceedsMaxSeries', () => {
const tooMany = Array.from({ length: MAX_SERIES + 1 }, (_, i) => ySeries(`s${i}`, [i]))
@@ -151,13 +204,8 @@ describe('sqlLineGraphAdapter', () => {
})
describe('formatSqlSeriesValue', () => {
- it.each([
- ['currency prefix', { formatting: { prefix: '$' } }, 1200, '$1200'],
- ['percent suffix', { formatting: { style: 'percent' as const } }, 42, '42%'],
- ['unit suffix', { formatting: { suffix: 'ms' } }, 350, '350ms'],
- ['no settings', undefined, 7, '7'],
- ])('formats with %s', (_name, settings, value, expected) => {
- expect(formatSqlSeriesValue(value, settings)).toBe(expected)
+ it('applies the column settings and stringifies the result', () => {
+ expect(formatSqlSeriesValue(1200, { formatting: { prefix: '$' } })).toBe('$1200')
})
it('falls back to the raw value when formatting yields null', () => {
@@ -197,5 +245,42 @@ describe('sqlLineGraphAdapter', () => {
const config = buildLineChartConfig({ xData: dateXData, chartSettings: {}, timezone: 'UTC' })
expect(config.yAxis).toMatchObject({ scale: 'linear', showGrid: true })
})
+
+ it.each([
+ ['shows', true, true],
+ ['hides', false, false],
+ ['hides by default', undefined, false],
+ ])('%s the built-in legend from showLegend', (_name, showLegend, expected) => {
+ const config = buildLineChartConfig({ xData: dateXData, chartSettings: { showLegend }, timezone: 'UTC' })
+ expect(config.legend).toEqual({ show: expected, position: 'top', interactive: true })
+ })
+
+ it('wires goalLines through schemaGoalLinesToConfigs', () => {
+ const goalLines: GoalLine[] = [{ label: 'Target', value: 100 }]
+ const config = buildLineChartConfig({ xData: dateXData, chartSettings: {}, timezone: 'UTC', goalLines })
+ expect(config.goalLines).toHaveLength(1)
+ expect(config.goalLines?.[0]).toMatchObject({ value: 100, label: 'Target' })
+ })
+ })
+
+ describe('buildBarChartConfig', () => {
+ const dateXData: AxisSeries<string> = {
+ column: { name: 'day', type: { name: 'DATE', isNumerical: false }, label: 'day', dataIndex: 0 },
+ data: ['2024-01-01', '2024-01-02'],
+ }
+
+ it('forces a linear y-axis scale for percent-stacked bars', () => {
+ const chartSettings: ChartSettings = {
+ stackBars100: true,
+ leftYAxisSettings: { scale: 'logarithmic' },
+ }
+ const config = buildBarChartConfig({
+ xData: dateXData,
+ chartSettings,
+ timezone: 'UTC',
+ visualizationType: ChartDisplayType.ActionsStackedBar,
+ })
+ expect(config.yAxis?.scale).toBe('linear')
+ })
})
})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
index bade4f1129c1..b1a55f44fa0a 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
@@ -1,5 +1,13 @@
import { lemonToast } from '@posthog/lemon-ui'
-import { type Series, type TimeSeriesLineChartConfig, createXAxisTickCallback } from '@posthog/quill-charts'
+import {
+ type ChartLegendConfig,
+ type Series,
+ type TimeSeriesBarChartConfig,
+ type TimeSeriesLineChartConfig,
+ type XAxisConfig,
+ type YAxisConfig,
+ createXAxisTickCallback,
+} from '@posthog/quill-charts'
import { ChartSettings, GoalLine } from '~/queries/schema/schema-general'
import { ChartDisplayType } from '~/types'
@@ -52,6 +60,39 @@ export function canRenderSqlLineGraph(props: LineGraphProps): boolean {
return true
}
+export function canRenderSqlBarGraph(props: LineGraphProps): boolean {
+ const { visualizationType, yData } = props
+
+ if (visualizationType !== ChartDisplayType.ActionsBar && visualizationType !== ChartDisplayType.ActionsStackedBar) {
+ return false
+ }
+ if (
+ yData?.some((series) => {
+ const displayType = series.settings?.display?.displayType
+ return displayType === 'line' || displayType === 'area'
+ })
+ ) {
+ return false
+ }
+ if (yData?.some((series) => series.settings?.display?.trendLine)) {
+ return false
+ }
+ if (yData?.some((series) => series.settings?.display?.yAxisPosition === 'right')) {
+ return false
+ }
+ return true
+}
+
+export function barLayoutForDisplay(
+ visualizationType: ChartDisplayType,
+ chartSettings: ChartSettings
+): NonNullable<TimeSeriesBarChartConfig['barLayout']> {
+ if (visualizationType === ChartDisplayType.ActionsStackedBar) {
+ return chartSettings.stackBars100 ? 'percent' : 'stacked'
+ }
+ return 'grouped'
+}
+
/** 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
@@ -107,28 +148,68 @@ interface BuildConfigArgs {
goalLines?: GoalLine[]
}
+export interface BuildBarConfigArgs extends BuildConfigArgs {
+ visualizationType: ChartDisplayType
+}
+
+function buildXAxisConfig(xData: AxisSeries<string>, chartSettings: ChartSettings, timezone: string): XAxisConfig {
+ const isDateAxis = xData.column.type.name === 'DATE' || xData.column.type.name === 'DATETIME'
+
+ return {
+ label: chartSettings.xAxisLabel,
+ tickFormatter: isDateAxis ? createXAxisTickCallback({ allDays: xData.data, timezone }) : undefined,
+ hide: chartSettings.showXAxisTicks === false,
+ }
+}
+
+function buildYAxisConfig(
+ chartSettings: ChartSettings,
+ { forceLinear = false }: { forceLinear?: boolean } = {}
+): YAxisConfig {
+ const yAxis = chartSettings.leftYAxisSettings
+
+ return {
+ label: yAxis?.label,
+ scale: !forceLinear && yAxis?.scale === 'logarithmic' ? 'log' : 'linear',
+ showGrid: yAxis?.showGridLines ?? true,
+ hide: yAxis?.showTicks === false,
+ }
+}
+
+function buildLegendConfig(chartSettings: ChartSettings): ChartLegendConfig {
+ return { show: chartSettings.showLegend ?? false, position: 'top', interactive: true }
+}
+
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: buildXAxisConfig(xData, chartSettings, timezone),
+ yAxis: buildYAxisConfig(chartSettings),
+ goalLines: schemaGoalLinesToConfigs(goalLines),
+ legend: buildLegendConfig(chartSettings),
+ tooltip: { enabled: true, pinnable: true },
+ }
+}
+
+export function buildBarChartConfig({
+ xData,
+ chartSettings,
+ timezone,
+ goalLines,
+ visualizationType,
+}: BuildBarConfigArgs): TimeSeriesBarChartConfig {
+ const barLayout = barLayoutForDisplay(visualizationType, chartSettings)
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,
- },
+ xAxis: buildXAxisConfig(xData, chartSettings, timezone),
+ yAxis: buildYAxisConfig(chartSettings, { forceLinear: barLayout === 'percent' }),
goalLines: schemaGoalLinesToConfigs(goalLines),
+ barLayout,
+ legend: buildLegendConfig(chartSettings),
tooltip: { enabled: true, pinnable: true },
}
}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel.ts
new file mode 100644
index 000000000000..7c5d1e85d42b
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel.ts
@@ -0,0 +1,63 @@
+import { useValues } from 'kea'
+import { useEffect, useMemo } from 'react'
+
+import { type ChartTheme, type Series } from '@posthog/quill-charts'
+
+import { buildTheme } from 'lib/charts/utils/theme'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+
+import { AxisSeriesSettings } from '../../dataVisualizationLogic'
+import { LineGraphProps } from './LineGraph'
+import {
+ type BuildBarConfigArgs,
+ type SqlLineSeriesMeta,
+ buildSeries,
+ capYSeriesData,
+ exceedsMaxSeries,
+ warnTooManySeries,
+} from './sqlLineGraphAdapter'
+
+export interface SqlChartModel<TConfig> {
+ series: Series<SqlLineSeriesMeta>[]
+ labels: string[]
+ theme: ChartTheme
+ config: TConfig
+ totalFormatterSettings?: AxisSeriesSettings
+}
+
+export function useSqlChartModel<TConfig>(
+ { xData, yData, visualizationType, chartSettings, dashboardId, goalLines }: LineGraphProps,
+ buildConfig: (args: BuildBarConfigArgs) => TConfig
+): SqlChartModel<TConfig> | null {
+ const { timezone } = useValues(teamLogic)
+ const { isDarkModeOn } = useValues(themeLogic)
+
+ useEffect(() => {
+ if (exceedsMaxSeries(yData, dashboardId)) {
+ warnTooManySeries(yData!.length)
+ }
+ }, [yData, dashboardId])
+
+ const ySeriesData = useMemo(() => capYSeriesData(yData), [yData])
+
+ const series = useMemo(
+ () => (ySeriesData ? buildSeries(ySeriesData, visualizationType) : []),
+ [ySeriesData, visualizationType]
+ )
+
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])
+
+ const config = useMemo(
+ () => (xData ? buildConfig({ xData, chartSettings, timezone, goalLines, visualizationType }) : undefined),
+ [xData, chartSettings, timezone, goalLines, visualizationType, buildConfig]
+ )
+
+ if (!xData || !ySeriesData || series.length === 0 || !config) {
+ return null
+ }
+
+ return { series, labels: xData.data, theme, config, totalFormatterSettings: ySeriesData[0]?.settings }
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlLineGraph.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlLineGraph.ts
deleted file mode 100644
index 6b4c5d0a467d..000000000000
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlLineGraph.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-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 { AxisSeriesSettings } from '../../dataVisualizationLogic'
-import { LineGraphProps } from './LineGraph'
-import {
- SqlLineSeriesMeta,
- buildLineChartConfig,
- buildSeries,
- capYSeriesData,
- exceedsMaxSeries,
- warnTooManySeries,
-} from './sqlLineGraphAdapter'
-
-export interface SqlLineGraphModel {
- series: Series<SqlLineSeriesMeta>[]
- labels: string[]
- theme: ChartTheme
- config: TimeSeriesLineChartConfig
- legendItems: LegendItem[]
- hiddenKeys: string[]
- toggleSeries: (key: string) => void
- /** Settings of the first (left-axis) series — used to format the tooltip's total row. */
- totalFormatterSettings?: AxisSeriesSettings
-}
-
-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,
- totalFormatterSettings: ySeriesData[0]?.settings,
- }
-}