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(hog-charts): add Legend primitive and ChartLegendLayout (#60393)

Sam Pennington922296c60a20
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f50c5e60b9d4..8c5d941c15fd 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -528,6 +528,38 @@ snapshots:
hash: v1.k794b7964.c154af270a078cbbb060543de422c6f2f2a2ae2134ffb797be0fb07f4e9c77bf.0gi1GO81ELv-U16NxXdiJF3VbtVBZaYK81G92hf8g_k
components-hogcharts-boxplot--with-gaps--light:
hash: v1.k794b7964.17739e468a4911b2bdfe16f13059a9b832e87386e3339ffb3a51c1c38ecfe821.9zttDtobDMs7E45HWOOxGwbEKOCRWDa2BqtMW8GSXcQ
+ components-hogcharts-legend--horizontal--dark:
+ hash: v1.k794b7964.5d39636c62e9f666902a6eba9478531a5326385494ae1a754ab1c133f546b3e1.knlLoncURwS3ntN36nlVwLODHi5eZonBGOOwIvLx5I8
+ components-hogcharts-legend--horizontal--light:
+ hash: v1.k794b7964.82d79f7e0a07c188f597a89fbc0a479e1b9605d007ba6f5fb71087a312fc0764.ENVTf91ekYBrR2zzMYiFkilFzL5adW_itJFXc3eZo-w
+ components-hogcharts-legend--interactive--dark:
+ hash: v1.k794b7964.5d39636c62e9f666902a6eba9478531a5326385494ae1a754ab1c133f546b3e1.yN8df5f_O9LA7ppecXLLDnoTO9CbnJT8QhazW0m0xkU
+ components-hogcharts-legend--interactive--light:
+ hash: v1.k794b7964.82d79f7e0a07c188f597a89fbc0a479e1b9605d007ba6f5fb71087a312fc0764.kFDhmb2BkonZoo3bR5snWR-aN_yY6R2-utLZ5ify3_E
+ components-hogcharts-legend--layout-bottom--dark:
+ hash: v1.k794b7964.6f34c5c79807ea26a631024458558c84093ab248138fbb7cba4d24deccda210d.xJ098X5I0o1k6yvWtmYXYJGlgsrbw5TpIN8C-osCojY
+ components-hogcharts-legend--layout-bottom--light:
+ hash: v1.k794b7964.ebb34148784fd49f208e59207fcfc3aa1476aeddd0af0cc3987543af514e6f0c.ygBJg6yMPl8-arZKotkxgO5XzM4AkWb_HsYkcTOkqes
+ components-hogcharts-legend--layout-left--dark:
+ hash: v1.k794b7964.e5ffa84c0c4612544185166fd7127e091f743d0a4e80e610021e9898cf68c16c.RWP2gB5lEXOaZJk2wYPvfCzAeDRDCBd59flzROZBj_E
+ components-hogcharts-legend--layout-left--light:
+ hash: v1.k794b7964.88db7c4f4fab4b0fee6b0be8b1508c91798270e69c17b507e046fc530dd2fafd.Yn1GAbiBehr5i16TVhPR01gSC2GpOfBnmo5LHnmCWqs
+ components-hogcharts-legend--layout-right--dark:
+ hash: v1.k794b7964.501db0b97c4d897a816cf08afba0f837a54be6f3533dd253b8410f34c57528d5.iT0_3sNr9zqZPacv3XSvc7iFxAhpejg9l26-8ek1wCA
+ components-hogcharts-legend--layout-right--light:
+ hash: v1.k794b7964.81902d1fc7bc428f1455585a08aa7667b409fe0edbf56f269ad38b56e21c53e0.nXCrZLvGoncvjvDYQ0Iq7VmbmorY7jNA6e1qCirbzbQ
+ components-hogcharts-legend--layout-top--dark:
+ hash: v1.k794b7964.07957a22916e5a09eedba69d385c07646d97d3d9483b3fc8d56ae0fae6eea448.4uZJgPeHOc567hzQaIzohLOCyS3dXMJOKB-boXjbYVA
+ components-hogcharts-legend--layout-top--light:
+ hash: v1.k794b7964.efd2345115e956ad9a0c4267248d90c40aade934d5dd896e10fad79f2afb425d.1JqrR7X4fPy38s0mKd20fHKfgLjrdwSNa05lG5GPcHA
+ components-hogcharts-legend--many-items-wraps--dark:
+ hash: v1.k794b7964.f6c2b82b8d93c25d9c21b9afc1d914d041138d25836485cf2d76a577d55a37c5.Ut_YYVfVrtgFs0gV16xnW-pxSADhDhx9tsfA_XEPirQ
+ components-hogcharts-legend--many-items-wraps--light:
+ hash: v1.k794b7964.376cc3f2d00b32edd65a5bc74b43ad4a22bb5d5befc0d7be5e10767717bf792f.cBQPCb5144l7YdeI5UPYc8saSV_mQiXEvGnOmA0xGuw
+ components-hogcharts-legend--vertical--dark:
+ hash: v1.k794b7964.8f9cdc0ce4c1529c1f95cf226b16fb3d28ebdf2a2eed7f57bb8b1e086fa54edf.iKnCYMI4351HMtNeZht7XjoxmFkbF8N0eIX9b8rIOQc
+ components-hogcharts-legend--vertical--light:
+ hash: v1.k794b7964.613d93ab14bd635185a8f3f5eabfaa884a3a8f7b418cdbdec94478b2bc3da2d2.poxwlxr4MP5HbhAC8JKzXCBFxGSJwc8uUXs26xUUcHU
components-hogcharts-linechart--combined-overlays--dark:
hash: v1.k794b7964.38753d5c6bab2f9d1be492d0e191aca21265953e220c0f37714913c89d7caf42.0wzgqeeUqe_bxIfIbS861HknzpuGVzxC664U1GTe9S8
components-hogcharts-linechart--combined-overlays--light:
diff --git a/frontend/src/lib/hog-charts/components/Legend/ChartLegendLayout.test.tsx b/frontend/src/lib/hog-charts/components/Legend/ChartLegendLayout.test.tsx
new file mode 100644
index 000000000000..cb5c12e4f6bd
--- /dev/null
+++ b/frontend/src/lib/hog-charts/components/Legend/ChartLegendLayout.test.tsx
@@ -0,0 +1,35 @@
+import { render } from '@testing-library/react'
+
+import { ChartLegendLayout } from './ChartLegendLayout'
+
+const LEGEND = <div data-attr="legend">L</div>
+const CHART = <div data-attr="chart">C</div>
+
+function root(props: Parameters<typeof ChartLegendLayout>[0]): HTMLElement {
+ return render(<ChartLegendLayout {...props} />).container.firstChild as HTMLElement
+}
+
+describe('ChartLegendLayout', () => {
+ it.each([
+ ['top', 'flex-col', 0],
+ ['bottom', 'flex-col', 1],
+ ['left', 'flex-row', 0],
+ ['right', 'flex-row', 1],
+ ] as const)('position=%s uses %s with legend at child index %s', (position, flex, legendIndex) => {
+ const r = root({ legend: LEGEND, position, children: CHART })
+ expect(r.className).toContain(flex)
+ expect(r.children[legendIndex].querySelector('[data-attr="legend"]')).not.toBeNull()
+ expect(r.children[1 - legendIndex].querySelector('[data-attr="chart"]')).not.toBeNull()
+ })
+
+ it('passes gap through as an inline style (default 8px)', () => {
+ expect(root({ legend: LEGEND, children: CHART }).style.gap).toBe('8px')
+ expect(root({ legend: LEGEND, gap: 24, children: CHART }).style.gap).toBe('24px')
+ })
+
+ it.each([null, undefined, false] as const)('omits the legend slot when legend is %p', (legend) => {
+ const r = root({ legend, children: CHART })
+ expect(r.children).toHaveLength(1)
+ expect(r.querySelector('[data-attr="chart"]')).not.toBeNull()
+ })
+})
diff --git a/frontend/src/lib/hog-charts/components/Legend/ChartLegendLayout.tsx b/frontend/src/lib/hog-charts/components/Legend/ChartLegendLayout.tsx
new file mode 100644
index 000000000000..feca7b584fb1
--- /dev/null
+++ b/frontend/src/lib/hog-charts/components/Legend/ChartLegendLayout.tsx
@@ -0,0 +1,43 @@
+/* eslint-disable react/forbid-dom-props -- dynamic pixel gap from prop */
+import React from 'react'
+
+export interface ChartLegendLayoutProps {
+ legend: React.ReactNode
+ position?: 'top' | 'bottom' | 'left' | 'right'
+ align?: 'start' | 'center' | 'end'
+ gap?: number
+ className?: string
+ dataAttr?: string
+ children: React.ReactNode
+}
+
+const ALIGN_CLASS = {
+ start: 'items-start',
+ center: 'items-center',
+ end: 'items-end',
+} as const
+
+export function ChartLegendLayout({
+ legend,
+ position = 'top',
+ align = 'center',
+ gap = 8,
+ className,
+ dataAttr,
+ children,
+}: ChartLegendLayoutProps): React.ReactElement {
+ const isRow = position === 'left' || position === 'right'
+ const legendFirst = position === 'top' || position === 'left'
+ const legendSlot = legend ? <div className="flex-none shrink-0">{legend}</div> : null
+ const chartSlot = <div className="flex-1 min-w-0 min-h-0">{children}</div>
+ return (
+ <div
+ className={`flex min-w-0 min-h-0 ${isRow ? 'flex-row' : 'flex-col'} ${ALIGN_CLASS[align]} ${className ?? ''}`}
+ style={{ gap }}
+ data-attr={dataAttr}
+ >
+ {legendFirst ? legendSlot : chartSlot}
+ {legendFirst ? chartSlot : legendSlot}
+ </div>
+ )
+}
diff --git a/frontend/src/lib/hog-charts/components/Legend/Legend.stories.tsx b/frontend/src/lib/hog-charts/components/Legend/Legend.stories.tsx
new file mode 100644
index 000000000000..9fb192a3d859
--- /dev/null
+++ b/frontend/src/lib/hog-charts/components/Legend/Legend.stories.tsx
@@ -0,0 +1,93 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { useMemo, useState } from 'react'
+
+import { DAYS, SERIES } from '../../charts/time-series-fixtures'
+import { TimeSeriesBarChart } from '../../charts/TimeSeriesBarChart/TimeSeriesBarChart'
+import { Stage, useReactiveTheme } from '../../story-helpers'
+import { ChartLegendLayout } from './ChartLegendLayout'
+import { Legend, type LegendItem } from './Legend'
+import { legendItemsFromSeries } from './legendItemsFromSeries'
+
+const LIFECYCLE: LegendItem[] = [
+ { key: 'new', label: 'New', color: '#22c55e' },
+ { key: 'returning', label: 'Returning', color: '#3b82f6' },
+ { key: 'resurrecting', label: 'Resurrecting', color: '#a855f7' },
+ { key: 'dormant', label: 'Dormant', color: '#f97316' },
+]
+
+const MANY: LegendItem[] = Array.from({ length: 12 }, (_, i) => ({
+ key: `series-${i}`,
+ label: `Breakdown value ${i + 1} with a fairly long name`,
+ color: `hsl(${(i * 36) % 360} 70% 55%)`,
+}))
+
+const meta: Meta = { title: 'Components/HogCharts/Legend', parameters: { layout: 'centered' } }
+export default meta
+
+type Story = StoryObj
+
+export const Horizontal: Story = {
+ render: () => (
+ <div className="w-[480px]">
+ <Legend items={LIFECYCLE} />
+ </div>
+ ),
+}
+
+export const Vertical: Story = {
+ render: () => (
+ <div className="w-[200px]">
+ <Legend items={LIFECYCLE} orientation="vertical" align="start" />
+ </div>
+ ),
+}
+
+export const Interactive: Story = {
+ render: () => {
+ function InteractiveLegend(): JSX.Element {
+ const [hidden, setHidden] = useState<string[]>([])
+ const toggle = (key: string): void =>
+ setHidden((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]))
+ return (
+ <div className="w-[480px]">
+ <Legend items={LIFECYCLE} hiddenKeys={hidden} onItemClick={toggle} />
+ </div>
+ )
+ }
+ return <InteractiveLegend />
+ },
+}
+
+export const ManyItemsWraps: Story = {
+ render: () => (
+ <div className="w-[480px] border border-border rounded p-2">
+ <Legend items={MANY} />
+ </div>
+ ),
+}
+
+function ChartWithLegend({ position }: { position: 'top' | 'bottom' | 'left' | 'right' }): JSX.Element {
+ const theme = useReactiveTheme()
+ const isRow = position === 'left' || position === 'right'
+ const items = useMemo(() => legendItemsFromSeries(SERIES, theme), [theme])
+ return (
+ <Stage width={520} height={320}>
+ <ChartLegendLayout
+ legend={<Legend items={items} orientation={isRow ? 'vertical' : 'horizontal'} />}
+ position={position}
+ >
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={DAYS}
+ theme={theme}
+ config={{ yAxis: { showGrid: true } }}
+ />
+ </ChartLegendLayout>
+ </Stage>
+ )
+}
+
+export const LayoutTop: Story = { render: () => <ChartWithLegend position="top" /> }
+export const LayoutBottom: Story = { render: () => <ChartWithLegend position="bottom" /> }
+export const LayoutLeft: Story = { render: () => <ChartWithLegend position="left" /> }
+export const LayoutRight: Story = { render: () => <ChartWithLegend position="right" /> }
diff --git a/frontend/src/lib/hog-charts/components/Legend/Legend.test.tsx b/frontend/src/lib/hog-charts/components/Legend/Legend.test.tsx
new file mode 100644
index 000000000000..be005d640aaa
--- /dev/null
+++ b/frontend/src/lib/hog-charts/components/Legend/Legend.test.tsx
@@ -0,0 +1,59 @@
+import { fireEvent, render } from '@testing-library/react'
+
+import { Legend, type LegendItem } from './Legend'
+
+const ITEMS: LegendItem[] = [
+ { key: 'new', label: 'New', color: '#22c55e' },
+ { key: 'returning', label: 'Returning', color: '#3b82f6' },
+ { key: 'dormant', label: 'Dormant', color: '#f97316' },
+]
+
+function rowsOf(container: HTMLElement): HTMLElement[] {
+ return Array.from(container.firstChild!.childNodes) as HTMLElement[]
+}
+
+describe('Legend', () => {
+ it('renders one row per item with the right label and swatch color', () => {
+ const { container } = render(<Legend items={ITEMS} />)
+ const swatches = Array.from(container.querySelectorAll<HTMLElement>('[aria-hidden="true"]'))
+ expect(swatches.map((s) => s.style.backgroundColor).every(Boolean)).toBe(true)
+ expect(swatches).toHaveLength(ITEMS.length)
+ expect(rowsOf(container).map((r) => r.textContent)).toEqual(ITEMS.map((i) => i.label))
+ })
+
+ it('renders nothing when items is empty', () => {
+ const { container } = render(<Legend items={[]} />)
+ expect(container.firstChild).toBeNull()
+ })
+
+ it('uses flex-row + flex-wrap for horizontal and flex-col for vertical', () => {
+ const h = render(<Legend items={ITEMS} dataAttr="h" />).container.querySelector('[data-attr="h"]')!
+ const v = render(<Legend items={ITEMS} orientation="vertical" dataAttr="v" />).container.querySelector(
+ '[data-attr="v"]'
+ )!
+ expect(h.className).toContain('flex-row')
+ expect(h.className).toContain('flex-wrap')
+ expect(v.className).toContain('flex-col')
+ expect(v.className).not.toContain('flex-wrap')
+ })
+
+ it('renders items as spans by default and as buttons that fire onItemClick when set', () => {
+ const onClick = jest.fn()
+ const plain = render(<Legend items={ITEMS} />).container
+ expect(plain.querySelectorAll('button')).toHaveLength(0)
+
+ const clickable = render(<Legend items={ITEMS} onItemClick={onClick} />).container
+ const buttons = clickable.querySelectorAll('button')
+ expect(buttons).toHaveLength(ITEMS.length)
+ fireEvent.click(buttons[1])
+ expect(onClick).toHaveBeenCalledWith('returning')
+ })
+
+ it('dims only rows whose key is in hiddenKeys', () => {
+ const { container } = render(<Legend items={ITEMS} hiddenKeys={['returning']} />)
+ const dimmedLabels = rowsOf(container)
+ .filter((row) => row.className.includes('opacity-40'))
+ .map((row) => row.textContent)
+ expect(dimmedLabels).toEqual(['Returning'])
+ })
+})
diff --git a/frontend/src/lib/hog-charts/components/Legend/Legend.tsx b/frontend/src/lib/hog-charts/components/Legend/Legend.tsx
new file mode 100644
index 000000000000..a42e451493d0
--- /dev/null
+++ b/frontend/src/lib/hog-charts/components/Legend/Legend.tsx
@@ -0,0 +1,72 @@
+/* eslint-disable react/forbid-dom-props -- swatch background-color is dynamic per item */
+import React from 'react'
+
+export interface LegendItem {
+ key: string
+ label: string
+ color: string
+}
+
+export interface LegendProps {
+ items: LegendItem[]
+ orientation?: 'horizontal' | 'vertical'
+ align?: 'start' | 'center' | 'end'
+ onItemClick?: (key: string) => void
+ hiddenKeys?: string[]
+ className?: string
+ dataAttr?: string
+}
+
+const ALIGN_CLASS = {
+ start: 'justify-start',
+ center: 'justify-center',
+ end: 'justify-end',
+} as const
+
+export function Legend({
+ items,
+ orientation = 'horizontal',
+ align = 'center',
+ onItemClick,
+ hiddenKeys,
+ className,
+ dataAttr,
+}: LegendProps): React.ReactElement | null {
+ if (items.length === 0) {
+ return null
+ }
+ const hidden = hiddenKeys?.length ? new Set(hiddenKeys) : null
+ const layout = orientation === 'horizontal' ? 'flex-row flex-wrap gap-x-3 gap-y-1' : 'flex-col gap-1'
+ return (
+ <div className={`flex ${layout} ${ALIGN_CLASS[align]} ${className ?? ''}`} data-attr={dataAttr}>
+ {items.map((item) => {
+ const dimmed = hidden?.has(item.key) ? ' opacity-40' : ''
+ const rowClass = `inline-flex items-center gap-1.5 text-xs leading-none${dimmed}`
+ const inner = (
+ <>
+ <span
+ aria-hidden="true"
+ className="inline-block w-2.5 h-2.5 rounded-sm shrink-0"
+ style={{ backgroundColor: item.color }}
+ />
+ <span className="truncate">{item.label}</span>
+ </>
+ )
+ return onItemClick ? (
+ <button
+ key={item.key}
+ type="button"
+ className={`${rowClass} cursor-pointer bg-transparent border-0 p-0 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent`}
+ onClick={() => onItemClick(item.key)}
+ >
+ {inner}
+ </button>
+ ) : (
+ <span key={item.key} className={rowClass}>
+ {inner}
+ </span>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/frontend/src/lib/hog-charts/components/Legend/legendItemsFromSeries.test.ts b/frontend/src/lib/hog-charts/components/Legend/legendItemsFromSeries.test.ts
new file mode 100644
index 000000000000..a1a537e986e6
--- /dev/null
+++ b/frontend/src/lib/hog-charts/components/Legend/legendItemsFromSeries.test.ts
@@ -0,0 +1,27 @@
+import type { ChartTheme, Series } from '../../core/types'
+import { legendItemsFromSeries } from './legendItemsFromSeries'
+
+const THEME: ChartTheme = { colors: ['#aaa', '#bbb', '#ccc'], backgroundColor: '#fff' }
+
+describe('legendItemsFromSeries', () => {
+ it('uses series.color when set and falls back to theme.colors[i % len] otherwise', () => {
+ const series: Series[] = [
+ { key: 'a', label: 'A', data: [], color: '#123' },
+ { key: 'b', label: 'B', data: [] },
+ { key: 'c', label: 'C', data: [] },
+ { key: 'd', label: 'D', data: [] },
+ ]
+ expect(legendItemsFromSeries(series, THEME).map((i) => i.color)).toEqual(['#123', '#bbb', '#ccc', '#aaa'])
+ })
+
+ it('drops excluded series and keeps the pre-filter color index of the rest', () => {
+ const series: Series[] = [
+ { key: 'a', label: 'A', data: [] },
+ { key: 'b', label: 'B', data: [], visibility: { excluded: true } },
+ { key: 'c', label: 'C', data: [] },
+ ]
+ const items = legendItemsFromSeries(series, THEME)
+ expect(items.map((i) => i.key)).toEqual(['a', 'c'])
+ expect(items.find((i) => i.key === 'c')!.color).toBe('#ccc')
+ })
+})
diff --git a/frontend/src/lib/hog-charts/components/Legend/legendItemsFromSeries.ts b/frontend/src/lib/hog-charts/components/Legend/legendItemsFromSeries.ts
new file mode 100644
index 000000000000..562049f6c06e
--- /dev/null
+++ b/frontend/src/lib/hog-charts/components/Legend/legendItemsFromSeries.ts
@@ -0,0 +1,16 @@
+import type { ChartTheme, ResolvedSeries, Series } from '../../core/types'
+import type { LegendItem } from './Legend'
+
+export function legendItemsFromSeries(series: ReadonlyArray<Series | ResolvedSeries>, theme: ChartTheme): LegendItem[] {
+ const palette = theme.colors
+ const items: LegendItem[] = []
+ for (let i = 0; i < series.length; i++) {
+ const s = series[i]
+ if (s.visibility?.excluded) {
+ continue
+ }
+ const fallback = palette.length > 0 ? palette[i % palette.length] : '#000'
+ items.push({ key: s.key, label: s.label, color: s.color ?? fallback })
+ }
+ return items
+}
diff --git a/frontend/src/lib/hog-charts/index.ts b/frontend/src/lib/hog-charts/index.ts
index cf6b81d66c2d..8b715aebe9b8 100644
--- a/frontend/src/lib/hog-charts/index.ts
+++ b/frontend/src/lib/hog-charts/index.ts
@@ -113,3 +113,10 @@ export type { GoalLineConfig } from './utils/goal-lines'
// Statistics helpers (used by trend-line / moving-average / confidence-interval features)
export { ciRanges, linearRegression, movingAverage, trendLine } from './utils/statistics'
+
+// Generic UI primitives (no canvas) — composed alongside charts by adapters
+export { Legend } from './components/Legend/Legend'
+export type { LegendItem, LegendProps } from './components/Legend/Legend'
+export { ChartLegendLayout } from './components/Legend/ChartLegendLayout'
+export type { ChartLegendLayoutProps } from './components/Legend/ChartLegendLayout'
+export { legendItemsFromSeries } from './components/Legend/legendItemsFromSeries'