: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(sparkline): render simple sparklines via quill charts behind a flag (#70231)
Sam Pennington3da362f306a7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2e22f9055474..d650af3b4b36 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1720,6 +1720,18 @@ snapshots:hash: v1.k794b7964.cb1d1d3239f78521823c1278cadb102e136422579a910c3a691c2b6b17ebb962.aj9xFX3wR7NQKuqnk4Tgypbsd2Ase4rHeCGuKjORB3wcomponents-sparkline--bar-chart--light:hash: v1.k794b7964.31239811ce1a1008b0f7ce278672dea78cc73785762735c6dc75437b165e6546.6_LSwYHJwrSsIBtnEhFwPCl3X6531Z_0iJaYpOj5sIU+ components-sparkline--bar-chart-quill--dark:+ hash: v1.k794b7964.65da75bd15e9d0d9f2e575e4eb04e0aaafdb39e02dbc19ba5006cf3651cb792d.4h71v2aMuCoUCk73AbsUPFhaiOPh4OZNrsDfJF_hB8g+ components-sparkline--bar-chart-quill--light:+ hash: v1.k794b7964.6eb3adde804dad4d1679afdac8ba0885d492ce67b8b9e6165a8c249f44ecdd15.ch68xtIx6_gqRUW9iJtAYsQgLI9yWafMHdNiABRmSOM+ components-sparkline--line-chart-quill--dark:+ hash: v1.k794b7964.3f80f2e2ad5ecb11b49b40e0c8293cbbbb1b8ff2309dac2352e61106a558ad31.FIhBn_k2DHJBVrbBtjcsJ98lzMyE3WX314pjRXPaL3o+ components-sparkline--line-chart-quill--light:+ hash: v1.k794b7964.8a485c8268bf80fc31f15248a14e8313792aab3dcbd19cec7f9b2d949f77cd40.pK48prQY4E_mKVhX9AieWtWjecgVHYLG7_JlTdBx_Gg+ components-sparkline--stacked-bar-chart-quill--dark:+ hash: v1.k794b7964.8b8cfdf1368aca38505c7d33c1325cfabe1182bd63ee2c24f26c2c81d2169d6e.jqQyZDit67S6ex-m780qpZoPElLpC3ta6xDR8H6iCfA+ components-sparkline--stacked-bar-chart-quill--light:+ hash: v1.k794b7964.2acecce6124d42c05297ea6becbc68fe4c2e5683d963123df0be9c159746e838.MvDZ47SSb1LeD59U3glRLe8gM_bDBfLCPzaxRdnaI40components-sparkline--timeseries-chart--dark:hash: v1.k794b7964.69943832ea0d231f0a5600318dea944b617e1109f8075b233905915790d08b8d.qzAP9q8SkcIOogn967c1ONIEcKJxILqd1oDgYk9jYCEcomponents-sparkline--timeseries-chart--light:diff --git a/frontend/src/lib/components/Sparkline.stories.tsx b/frontend/src/lib/components/Sparkline.stories.tsxindex 0bd8ab9f07ec..27cf4ccb326c 100644--- a/frontend/src/lib/components/Sparkline.stories.tsx+++ b/frontend/src/lib/components/Sparkline.stories.tsx@@ -2,7 +2,7 @@ import type { Meta, StoryObj } from '@storybook/react'import { dayjs } from 'lib/dayjs'-import { AnyScaleOptions, Sparkline, SparklineProps } from './Sparkline'+import { AnyScaleOptions, QuillSparkline, Sparkline, SparklineProps } from './Sparkline'type Story = StoryObj<SparklineProps>const meta: Meta<SparklineProps> = {@@ -55,3 +55,39 @@ export const TimeseriesChart: Story = {},},}++// Quill-rendered variants (see docs/internal/quill-migration-sparkline.md), for side-by-side+// comparison with the legacy stories above. These render `QuillSparkline` directly rather than+// flipping the `quill-sparkline` flag: the flag dispatch is unusable under Storybook, whose+// implicit-action args inject an `onSelectionChange` spy that the dispatch reads as a+// legacy-only feature. The quill chart paints onto an absolutely-positioned canvas that adds no+// intrinsic size, so the wrapper needs an explicit width and height — a `w-full` here would+// collapse to a zero-width, unsnapshottable root under the test runner.+export const BarChartQuill: Story = {+ args: {+ data: [10, 5, 3, 30, 22, 10, 2],+ labels: ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],+ },+ render: (args) => <QuillSparkline {...args} className="w-64 h-16" />,+}++export const StackedBarChartQuill: Story = {+ args: {+ data: [+ { name: 'success', values: [10, 5, 3, 30, 22, 10, 2], color: 'success' },+ { name: 'failure', values: [1, 0, 2, 4, 0, 1, 0], color: 'danger' },+ ],+ labels: ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],+ },+ render: (args) => <QuillSparkline {...args} className="w-64 h-16" />,+}++export const LineChartQuill: Story = {+ args: {+ data: [10, 5, 3, 30, 22, 10, 2],+ labels: ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],+ type: 'line',+ color: 'success',+ },+ render: (args) => <QuillSparkline {...args} className="w-64 h-16" />,+}diff --git a/frontend/src/lib/components/Sparkline.test.tsx b/frontend/src/lib/components/Sparkline.test.tsxnew file mode 100644index 000000000000..f98814de3468--- /dev/null+++ b/frontend/src/lib/components/Sparkline.test.tsx@@ -0,0 +1,121 @@+import '@testing-library/jest-dom'++import { cleanup, render, waitFor } from '@testing-library/react'++import {+ createDefaultTooltipAccessor,+ getHogChart,+ hoverUntilTooltip,+ setupJsdom,+ setupSyncRaf,+} from '@posthog/quill-charts/testing'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'++import { Sparkline, SparklineProps } from './Sparkline'++let cleanupJsdom: () => void+let cleanupRaf: () => void++beforeEach(() => {+ cleanupJsdom = setupJsdom()+ cleanupRaf = setupSyncRaf()+})++afterEach(() => {+ cleanupRaf()+ cleanupJsdom()+ cleanup()+})++function renderSparkline(props: SparklineProps, { quillFlag = true }: { quillFlag?: boolean } = {}): void {+ initKeaTests()+ const ffLogic = featureFlagLogic()+ ffLogic.mount()+ // Always set the flag explicitly — the featureFlags reducer is kea-persisted to localStorage,+ // which survives across tests in this file, so an unset flag would leak the previous test's value.+ ffLogic.actions.setFeatureFlags([FEATURE_FLAGS.QUILL_SPARKLINE], { [FEATURE_FLAGS.QUILL_SPARKLINE]: quillFlag })+ render(<Sparkline {...props} />)+}++// Quill charts label their main canvas for a11y and add an aria-hidden hover-overlay canvas;+// the legacy Chart.js canvas carries neither attribute.+const quillCanvas = (): Element | null => document.querySelector('canvas[aria-label]')+const legacyCanvas = (): Element | null => document.querySelector('canvas:not([aria-label]):not([aria-hidden])')++const DATA = [10, 5, 3, 30]+const LABELS = ['Mon', 'Tue', 'Wed', 'Thu']++describe('Sparkline', () => {+ it('renders via quill when the flag is on and only simple props are used', () => {+ renderSparkline({ data: DATA, labels: LABELS })+ expect(quillCanvas()).toBeTruthy()+ expect(legacyCanvas()).toBeNull()+ })++ it('renders via Chart.js when the flag is off', () => {+ renderSparkline({ data: DATA, labels: LABELS }, { quillFlag: false })+ expect(legacyCanvas()).toBeTruthy()+ expect(quillCanvas()).toBeNull()+ })++ it.each<{ feature: string; props: Partial<SparklineProps> }>([+ { feature: 'onSelectionChange', props: { onSelectionChange: () => {} } },+ { feature: 'highlightedRange', props: { highlightedRange: { xMin: 'Mon', xMax: 'Tue' } } },+ { feature: 'incompleteBars', props: { incompleteBars: { indices: [3] } } },+ { feature: 'referenceLines', props: { referenceLines: [{ value: 20 }] } },+ { feature: 'withXScale', props: { withXScale: (x) => x } },+ { feature: 'withYScale', props: { withYScale: (y) => y } },+ ])('keeps Chart.js when $feature is passed, even with the flag on', ({ props }) => {+ renderSparkline({ data: DATA, labels: LABELS, ...props })+ expect(legacyCanvas()).toBeTruthy()+ expect(quillCanvas()).toBeNull()+ })++ it.each<{ shape: string; data: SparklineProps['data']; seriesCount: number }>([+ { shape: 'a flat number array', data: DATA, seriesCount: 1 },+ {+ shape: 'multiple time series',+ data: [+ { name: 'success', values: [1, 2, 3, 4], color: 'success' },+ { name: 'failure', values: [4, 3, 2, 1], color: 'danger' },+ ],+ seriesCount: 2,+ },+ ])('normalizes $shape into $seriesCount quill series', ({ data, seriesCount }) => {+ renderSparkline({ data, labels: LABELS })+ expect(getHogChart().seriesCount).toBe(seriesCount)+ })++ it('wires tooltip formatting and zero-row filtering through to the quill tooltip', async () => {+ // Line type: bar charts hit-test the cursor against filled segments before showing a+ // tooltip, while lines surface all series — and the tooltip wiring under test is shared.+ renderSparkline({+ data: [+ { name: 'volume', values: [10, 0, 3, 30] },+ { name: 'errors', values: [2, 0, 0, 1] },+ ],+ labels: LABELS,+ type: 'line',+ hideZerosInTooltip: true,+ renderLabel: (label) => `Day: ${label}`,+ renderTooltipValue: (value) => `$${value.toFixed(2)}`,+ })+ const chart = getHogChart()++ const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 2, LABELS.length))+ // The portal mounts before its content commits, so poll until the header lands.+ await waitFor(() => expect(tooltip.label()).toBe('Day: Wed'))+ expect(tooltip.value('volume')).toBe('$3.00')+ expect(tooltip.rows()).toEqual(['volume']) // the zero 'errors' row is hidden+ })++ it('shows a skeleton instead of a chart while loading', () => {+ renderSparkline({ data: DATA, labels: LABELS, loading: true })+ expect(document.querySelector('canvas')).toBeNull()+ expect(document.querySelector('.LemonSkeleton')).toBeTruthy()+ })+})diff --git a/frontend/src/lib/components/Sparkline.tsx b/frontend/src/lib/components/Sparkline.tsxindex f26985d37857..dd3131b502c9 100644--- a/frontend/src/lib/components/Sparkline.tsx+++ b/frontend/src/lib/components/Sparkline.tsx@@ -1,14 +1,17 @@import annotationPlugin from 'chartjs-plugin-annotation'import clsx from 'clsx'-import { useMemo, useRef, useState } from 'react'+import { useCallback, useMemo, useRef, useState } from 'react'import { IconWarning } from '@posthog/icons'import { Popover } from '@posthog/lemon-ui'+import { DefaultTooltip, Sparkline as QuillSparklineChart, useChartTheme } from '@posthog/quill-charts'+import type { Series, TooltipContext } from '@posthog/quill-charts'import { Chart, ScaleOptions, TooltipModel } from 'lib/Chart'import { getColorVar } from 'lib/colors'import { useChart } from 'lib/hooks/useChart'import { useEventListener } from 'lib/hooks/useEventListener'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'import { hexToRGBA } from 'lib/utils/colors'import { humanFriendlyNumber } from 'lib/utils/numbers'@@ -95,6 +98,146 @@ export interface SparklineProps {incompleteBars?: { indices: number[]; tooltip?: string } | null}+/** Normalize the permissive `data` prop into one `SparklineTimeSeries` per series. */+function normalizeSparklineData(+ data: SparklineProps['data'],+ name?: string,+ names?: string[],+ color?: string,+ colors?: string[]+): SparklineTimeSeries[] {+ const arrayData = Array.isArray(data)+ ? data.length > 0 && typeof data[0] === 'object'+ ? data // array of objects, one per series+ : [data] // array of numbers, turn it into the first series+ : typeof data === 'object'+ ? [data] // first series as an object+ : [[data]] // just a random number... huh+ return arrayData.map((timeseries, index): SparklineTimeSeries => {+ const defaultName =+ names?.[index] || (arrayData.length === 1 ? name || 'Count' : `${name || 'Series'} ${index + 1}`)+ const defaultColor = colors?.[index] || color || 'muted'+ if (typeof timeseries === 'object') {+ if (!Array.isArray(timeseries)) {+ return {+ name: timeseries.name || defaultName,+ color: timeseries.color || defaultColor,+ values: timeseries.values || [],+ }+ }+ return {+ name: defaultName,+ color: defaultColor,+ values: timeseries as number[],+ }+ }+ return {+ name: defaultName,+ color: defaultColor,+ values: timeseries ? [timeseries] : [],+ }+ })+}++/** Width scales with the number of buckets so short sparklines don't stretch their bars. */+function sparklineClassName(dataPointCount: number, className?: string): string {+ return clsx(+ 'relative',+ dataPointCount > 16 ? 'w-64' : dataPointCount > 8 ? 'w-48' : dataPointCount > 4 ? 'w-32' : 'w-24',+ className+ )+}++export function Sparkline(props: SparklineProps): JSX.Element {+ const quillEnabled = useFeatureFlag('QUILL_SPARKLINE')+ // Features the quill path doesn't cover yet. Consumers passing them stay on Chart.js until+ // their migration wave lands — see docs/internal/quill-migration-sparkline.md.+ const needsLegacyFeatures = !!(+ props.onSelectionChange ||+ props.highlightedRange ||+ props.incompleteBars?.indices?.length ||+ props.referenceLines?.length ||+ props.withXScale ||+ props.withYScale+ )+ return quillEnabled && !needsLegacyFeatures ? <QuillSparkline {...props} /> : <LegacySparkline {...props} />+}++/** Legacy consumers pass vars.scss color names ('success', 'danger', 'muted'); quill takes CSS colors. */+function resolveSparklineColor(color: string | undefined): string {+ const value = color || 'muted'+ return /^(#|rgb|hsl|var\()/.test(value) ? value : getColorVar(value)+}++/** The quill rendering path. Exported for Storybook only — the flag dispatch in `Sparkline` is+ * unusable there (Storybook's implicit-action args inject an `onSelectionChange` spy, which the+ * dispatch reads as a legacy-only feature). Consumers always use `Sparkline`. */+export function QuillSparkline({+ data,+ color,+ colors,+ name,+ names,+ labels,+ type = 'bar',+ loading = false,+ renderLabel,+ className,+ hideZerosInTooltip = false,+ sortTooltipByCount = false,+ renderTooltipValue,+}: SparklineProps): JSX.Element {+ const theme = useChartTheme()++ const series: Series[] = useMemo(+ () =>+ normalizeSparklineData(data, name, names, color, colors).map((timeseries, index) => ({+ key: `${index}`,+ label: timeseries.name,+ data: timeseries.values,+ color: resolveSparklineColor(timeseries.color),+ })),+ [data, name, names, color, colors]+ )+ const chartLabels = useMemo(() => labels ?? (series[0]?.data ?? []).map((_, i) => `Entry ${i}`), [labels, series])++ const renderTooltip = useCallback(+ (ctx: TooltipContext): JSX.Element => (+ <DefaultTooltip+ {...ctx}+ showHeader={!!labels}+ hideZeroRows={hideZerosInTooltip}+ sortedByValue={sortTooltipByCount}+ valueFormatter={(value) => (renderTooltipValue ?? humanFriendlyNumber)(value)}+ labelFormatter={renderLabel}+ />+ ),+ [labels, hideZerosInTooltip, sortTooltipByCount, renderTooltipValue, renderLabel]+ )++ const finalClassName = sparklineClassName(series[0]?.data.length || 0, className)++ if (loading) {+ return <LemonSkeleton className={finalClassName} />+ }+ if (data === undefined || data.length === 0) {+ return <div className={finalClassName} />+ }+ return (+ <div className={finalClassName}>+ <QuillSparklineChart+ series={series}+ labels={chartLabels}+ theme={theme}+ type={type}+ fill+ className="h-full"+ tooltip={renderTooltip}+ />+ </div>+ )+}+/*** Build a faded diagonal-hatch CanvasPattern for an incomplete bar: a translucent fill of the series* colour overlaid with hatch lines, so the bar reads as "still loading" while keeping its colour.@@ -124,7 +267,7 @@ function createHashedPattern(color: string): CanvasPattern | string {return ctx.createPattern(canvas, 'repeat') ?? color}-export function Sparkline({+function LegacySparkline({data,color,colors,@@ -155,39 +298,10 @@ export function Sparkline({const incompleteBarSet = useMemo(() => new Set(incompleteBars?.indices ?? []), [incompleteBars])- const adjustedData: SparklineTimeSeries[] = useMemo(() => {- const arrayData = Array.isArray(data)- ? data.length > 0 && typeof data[0] === 'object'- ? data // array of objects, one per series- : [data] // array of numbers, turn it into the first series- : typeof data === 'object'- ? [data] // first series as an object- : [[data]] // just a random number... huh- return arrayData.map((timeseries, index): SparklineTimeSeries => {- const defaultName =- names?.[index] || (arrayData.length === 1 ? name || 'Count' : `${name || 'Series'} ${index + 1}`)- const defaultColor = colors?.[index] || color || 'muted'- if (typeof timeseries === 'object') {- if (!Array.isArray(timeseries)) {- return {- name: timeseries.name || defaultName,- color: timeseries.color || defaultColor,- values: timeseries.values || [],- }- }- return {- name: defaultName,- color: defaultColor,- values: timeseries as number[],- }- }- return {- name: defaultName,- color: defaultColor,- values: timeseries ? [timeseries] : [],- }- })- }, [data]) // oxlint-disable-line react-hooks/exhaustive-deps+ const adjustedData: SparklineTimeSeries[] = useMemo(+ () => normalizeSparklineData(data, name, names, color, colors),+ [data] // oxlint-disable-line react-hooks/exhaustive-deps+ )const { canvasRef } = useChart({getConfig: () => {@@ -376,12 +490,7 @@ export function Sparkline({],})- const dataPointCount = adjustedData[0]?.values?.length || 0- const finalClassName = clsx(- 'relative',- dataPointCount > 16 ? 'w-64' : dataPointCount > 8 ? 'w-48' : dataPointCount > 4 ? 'w-32' : 'w-24',- className- )+ const finalClassName = sparklineClassName(adjustedData[0]?.values?.length || 0, className)const tooltipVisible = !!(tooltip && tooltip.opacity > 0)const toolTipDataPoints = tooltip && tooltip.dataPoints ? tooltip.dataPoints : []diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 7cc96a78005b..d1f97c538b28 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -448,6 +448,7 @@ export const FEATURE_FLAGS = {QUICK_START_PULSE_INDICATOR: 'quick-start-pulse-indicator', // owner: @fercgomes #team-growth multivariate=control,testQUILL_CHART_STYLE_REFRESH: 'quill-chart-style-refresh', // owner: #team-product-analytics, gates refreshed quill chart styling (monotone curves, axis lines + tick marks, faint dashed grid, crosshair)QUILL_DATE_PICKER: 'quill-date-picker', // owner: @pauldambra, flips the lib/components/DatePicker seam from LemonUI to Quill+ QUILL_SPARKLINE: 'quill-sparkline', // owner: @sampennington #team-product-analytics, gates rendering the shared lib Sparkline via @posthog/quill-charts (docs/internal/quill-migration-sparkline.md)RBAC_UI_REDESIGN: 'rbac-ui-redesign', // owner: @reece #team-platform-featuresREAD_ONLY_MODE: 'read-only-mode', // owner: @pauldambra, experiment: force users into read-only and steer mutations through Max/MCPREAL_TIME_NOTIFICATIONS: 'real-time-notifications', // owner: #team-platform-features