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(quill): add Heatmap chart to quill-charts (#71567)

Jon McCallum8ea5eea9ad38
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 6874012b15b1..ad483dd5f18f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8,6 +8,18 @@ snapshots:
hash: v1.k794b7964.af0ce5703adcc074ea6c3afc8715d537a646698123a78625e6ec847123b26ae2.ypACU5Xagre6WeI4z7UlQ6w7oY0ieM1C-GnZs93KDkY
ai-observability-create-prompt-experiment-modal--default--light:
hash: v1.k794b7964.1f2df3488ddd83339f1b456d5754cc2914c96b636f3b42d2ec790d9d88cb4b7a.eEMgBC90LXIRJdk4qJWBJVarHjNmZb38tIjLxTV73_E
+ charts-heatmap--clickable-cells--dark:
+ hash: v1.k794b7964.8f0bf7a9fc58c93f4dc73333e7debc16ac9e8beb1397753f8bf7876528c6be5e.vBhKsdEGwMCxSig2mqm7qome1H7ed0LuGFexudABJmo
+ charts-heatmap--clickable-cells--light:
+ hash: v1.k794b7964.3b470c279042363847a1ef329ab3726a284e8c0643ea9bab4801e087b7ada7d3.XpYUiiUwx1_6tBbcV_4dwStXwCgHojuvn6On0TWXRD8
+ charts-heatmap--latency-over-time--dark:
+ hash: v1.k794b7964.bb9d9222ed53aa21ae844f8280d6075c0d0234d32a57b7969ac6bb182f92aa9f.THXyjjmWRQj2SEt-1o7b_fvBJMMENfGxsyqNFezQjXo
+ charts-heatmap--latency-over-time--light:
+ hash: v1.k794b7964.53bb0e1b5b39f7b4a7ce6fed5ffb11588832dccaf5992f3f3c2d1acd93498bbc.qCLFVHkb9X_zIGR3Ww_xPymSoNiiPpxPHgWpTx7s65A
+ charts-heatmap--linear-color-scale--dark:
+ hash: v1.k794b7964.8e7770037014d788ef5b7299b6b2f834c2afcad14dd6c6033ddd8ac885faa1c6.buSflXKIcQC5dcm7fbQWsczrZY8TleOkvO86ugYW8yw
+ charts-heatmap--linear-color-scale--light:
+ hash: v1.k794b7964.c94c02704b7f9b4972f811336d019e15b77cff047551902ca74d65c1571ea6ff.PA6k_wyPYr-SNYm1-Mv8sa0DFCLb2-8QxOVNlDn4hE8
components-account-project-switcher--no-pending-invite--dark:
hash: v1.k794b7964.ddbb5d27187cb1eb9341734e0b780c762cdfbc09aae81833c970369bd7ad4f32.3HNFMfb4Lflcg3uKD1-KNl09d3leMhmfuhR2WVLjLRE
components-account-project-switcher--no-pending-invite--light:
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 869d126c3e75..1315d85a2102 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -15,6 +15,7 @@ Quick-reference for AI agents using `@posthog/quill-charts`. Canvas-rendered cha
| TimeSeriesComboChart | Mixed bar + line/area on a time x-axis — `ComboChart` plus the time-series chrome (date x-axis, goal lines, legend, value labels) |
| PieChart | Part-of-whole, one value per series; `innerRadiusRatio` for donut + `centerLabel`; on-slice labels via `showLabelOnSlice`/`showValueOnSlice`, positioned with `labelRadiusRatio` (0=center, 1=rim) and gated by `minSlicePercentForLabel` |
| BoxPlot | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label |
+| Heatmap | 2D density grid (e.g. latency over time) — `xLabels` × `yLabels` (row 0 at the bottom), `cells[row][col]` counts → color intensity on one accent (log ramp by default, `colorScale: 'linear'` to opt out); single-cell tooltip resolved from the cursor, `onCellClick` reports `{ xIndex, yIndex, value }` |
| Sparkline | Tiny inline trend, no axes — a gradient-filled line (default) or stacked bars via `type: 'bar'`; a flat `number[]` + `color`, or full `series` for multi-series; tooltip off by default, opt in with a `tooltip` render prop |
| MetricCard | Headline number + sparkline + change pill (dashboard stat tiles) |
| SlopeChart | Change between two points (slopegraph) — one line per series, left "before" → right "after"; `data: [start, end]` |
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.stories.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.stories.tsx
new file mode 100644
index 000000000000..fecbbc611c65
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.stories.tsx
@@ -0,0 +1,100 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { Stage, useReactiveTheme } from '../../story-helpers'
+import { Heatmap } from './Heatmap'
+
+// A latency-over-time grid: x = 5-minute buckets, y = log 1-2-5 duration buckets. The data is
+// deterministic and bimodal — a fast band (cache hits) all day plus a slow band (cache misses)
+// that appears in the second half — the exact shape a latency heatmap exists to reveal.
+const X_LABELS = Array.from({ length: 48 }, (_, i) => {
+ const minutes = i * 5
+ const h = String(8 + Math.floor(minutes / 60)).padStart(2, '0')
+ const m = String(minutes % 60).padStart(2, '0')
+ return `${h}:${m}`
+})
+
+const Y_LABELS = ['1ms', '2ms', '5ms', '10ms', '20ms', '50ms', '100ms', '200ms', '500ms', '1s', '2s', '5s']
+
+function band(center: number, row: number, peak: number): number {
+ const d = Math.abs(row - center)
+ return Math.max(0, Math.round(peak / (1 + d * d * 2)))
+}
+
+const CELLS = Y_LABELS.map((_, row) =>
+ X_LABELS.map((_, col) => {
+ const wave = 1 + 0.5 * Math.sin(col / 5)
+ const fast = band(2.5, row, 140 * wave)
+ const slow = col > X_LABELS.length / 2 ? band(8.5, row, 30 * wave) : 0
+ const noise = (row * 7 + col * 13) % 11 === 0 ? 1 : 0
+ return fast + slow + noise
+ })
+)
+
+const meta: Meta<typeof Heatmap> = {
+ title: 'Charts/Heatmap',
+ component: Heatmap,
+ tags: ['autodocs'],
+}
+export default meta
+
+type Story = StoryObj<typeof Heatmap>
+
+export const LatencyOverTime: Story = {
+ render: function Render() {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={720} height={320}>
+ <Heatmap
+ xLabels={X_LABELS}
+ yLabels={Y_LABELS}
+ cells={CELLS}
+ theme={theme}
+ config={{
+ xTickFormatter: (label, i) => (i % 6 === 0 ? label : null),
+ xAxisLabel: 'Time',
+ yAxisLabel: 'Duration',
+ }}
+ />
+ </Stage>
+ )
+ },
+}
+
+export const LinearColorScale: Story = {
+ render: function Render() {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={720} height={320}>
+ <Heatmap
+ xLabels={X_LABELS}
+ yLabels={Y_LABELS}
+ cells={CELLS}
+ theme={theme}
+ config={{
+ colorScale: 'linear',
+ xTickFormatter: (label, i) => (i % 6 === 0 ? label : null),
+ }}
+ />
+ </Stage>
+ )
+ },
+}
+
+export const ClickableCells: Story = {
+ render: function Render() {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={720} height={320}>
+ <Heatmap
+ xLabels={X_LABELS}
+ yLabels={Y_LABELS}
+ cells={CELLS}
+ theme={theme}
+ config={{ xTickFormatter: (label, i) => (i % 6 === 0 ? label : null) }}
+ // eslint-disable-next-line no-console
+ onCellClick={(cell) => console.info('cell clicked', cell)}
+ />
+ </Stage>
+ )
+ },
+}
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx
new file mode 100644
index 000000000000..7478593aff94
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx
@@ -0,0 +1,61 @@
+import type { ChartTheme } from '../../core/types'
+import { renderHogChart } from '../../testing'
+import { Heatmap } from './Heatmap'
+
+const THEME: ChartTheme = {
+ colors: ['#1f77b4', '#ff7f0e'],
+ backgroundColor: '#ffffff',
+ gridColor: '#eeeeee',
+ crosshairColor: '#888888',
+}
+
+const X_LABELS = ['10:00', '10:02', '10:04', '10:06']
+const Y_LABELS = ['1ms', '2ms', '5ms', '10ms']
+const CELLS = [
+ [3, 0, 1, 0],
+ [10, 4, 0, 2],
+ [0, 1, 6, 0],
+ [0, 0, 0, 1],
+]
+
+describe('Heatmap', () => {
+ it('renders one adapter series per row', () => {
+ const { chart } = renderHogChart(<Heatmap xLabels={X_LABELS} yLabels={Y_LABELS} cells={CELLS} theme={THEME} />)
+ expect(chart.seriesCount).toBe(Y_LABELS.length)
+ })
+
+ // The categorical y-axis rides the numeric tick machinery (row-center values + a formatter
+ // mapping back to labels). If that adapter breaks, ticks render as raw numbers like "0.5".
+ it('renders row labels, not row-unit numbers, as y-axis ticks', () => {
+ const { chart } = renderHogChart(<Heatmap xLabels={X_LABELS} yLabels={Y_LABELS} cells={CELLS} theme={THEME} />)
+ const ticks = chart.yTicks()
+ expect(ticks.length).toBeGreaterThan(0)
+ for (const tick of ticks) {
+ expect(Y_LABELS).toContain(tick)
+ }
+ })
+
+ it('renders column labels as x-axis ticks', () => {
+ const { chart } = renderHogChart(<Heatmap xLabels={X_LABELS} yLabels={Y_LABELS} cells={CELLS} theme={THEME} />)
+ const ticks = chart.xTicks()
+ expect(ticks.length).toBeGreaterThan(0)
+ for (const tick of ticks) {
+ expect(X_LABELS).toContain(tick)
+ }
+ })
+
+ it('keeps columns with the same label distinct', () => {
+ // Columns are keyed by index, not label text; keying by label would collapse the two
+ // "10:00" columns onto one x position, dropping a tick and misrouting hover/click.
+ const dupLabels = ['10:00', '10:00', '10:02', '10:04']
+ const { chart } = renderHogChart(<Heatmap xLabels={dupLabels} yLabels={Y_LABELS} cells={CELLS} theme={THEME} />)
+ expect(chart.xTicks()).toEqual(dupLabels)
+ })
+
+ it('tolerates a ragged cells grid without crashing', () => {
+ const { chart } = renderHogChart(
+ <Heatmap xLabels={X_LABELS} yLabels={Y_LABELS} cells={[[1], [2, 3]]} theme={THEME} />
+ )
+ expect(chart.seriesCount).toBe(Y_LABELS.length)
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
new file mode 100644
index 000000000000..d03719ca8889
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx
@@ -0,0 +1,395 @@
+import React, { useCallback, useMemo } from 'react'
+
+import { Chart } from '../../core/Chart'
+import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'
+import { resolveCssColor } from '../../core/color-utils'
+import type {
+ ChartConfig,
+ ChartDimensions,
+ ChartDrawArgs,
+ ChartMargins,
+ ChartScales,
+ ChartTheme,
+ CreateScalesFn,
+ PointClickData,
+ ResolvedSeries,
+ ResolveValueFn,
+ Series,
+ TooltipContext,
+} from '../../core/types'
+import { DefaultTooltip } from '../../overlays/DefaultTooltip'
+import { findClosestSeriesKey } from '../../overlays/tooltipUtils'
+import {
+ cellRect,
+ computeHeatmapLayout,
+ createCellColorRamp,
+ maxCellValue,
+ normalizeCount,
+ rowAtY,
+ type HeatmapColorScale,
+ type HeatmapLayout,
+} from './heatmap-layout'
+
+/** Meta attached to the adapter series the Heatmap hands to the base `Chart` — one series
+ * per row, carrying its row index so tooltip/click code can map back to the grid. */
+export interface HeatmapRowMeta {
+ rowIndex: number
+}
+
+/** Tooltip context handed to consumer-supplied `tooltip` callbacks — `TooltipContext` with
+ * the row meta baked in. Each `seriesData` entry is one row at the hovered column; use
+ * `findClosestSeriesKey(ctx.seriesData, ctx.hoverPosition.y)` (as the built-in tooltip does)
+ * to narrow to the single hovered cell. */
+export type HeatmapTooltipContext = TooltipContext<HeatmapRowMeta>
+
+/** Stash slot — survives a render via `ChartScales._private` so drawStatic/drawHover/
+ * wrapClickData can read the grid layout without recomputing it. */
+interface HeatmapPrivate {
+ __heatmap: {
+ layout: HeatmapLayout
+ cells: number[][]
+ accent: string
+ maxValue: number
+ colorScale: HeatmapColorScale
+ }
+}
+
+export interface HeatmapConfig {
+ /** Custom x-axis tick label formatter. Return null to skip a tick. Called with (label, index). */
+ xTickFormatter?: (label: string, index: number) => string | null
+ /** How counts map to color intensity. Defaults to 'log' — right for long-tailed count grids. */
+ colorScale?: HeatmapColorScale
+ /** Accent color for the density ramp (hex, rgb, or var(--…)). Defaults to the first theme
+ * palette color. */
+ color?: string
+ xAxisLabel?: string
+ yAxisLabel?: string
+ hideXAxis?: boolean
+ hideYAxis?: boolean
+ /** Per-side margin overrides. Should be referentially stable. */
+ margins?: Partial<ChartMargins>
+ tooltip?: {
+ /** Show the single-cell tooltip on hover. Defaults to true. */
+ enabled?: boolean
+ /** Formats the column (x) label in the tooltip header. */
+ labelFormatter?: (label: string) => React.ReactNode
+ /** Formats the cell count. Defaults to `toLocaleString`. */
+ valueFormatter?: (value: number) => React.ReactNode
+ }
+}
+
+export interface HeatmapCellDatum {
+ /** Column index into `xLabels`. */
+ xIndex: number
+ /** Row index into `yLabels` (0 = bottom row). */
+ yIndex: number
+ xLabel: string
+ yLabel: string
+ /** The cell's count. */
+ value: number
+}
+
+export interface HeatmapProps {
+ /** Column labels, left to right. */
+ xLabels: string[]
+ /** Row labels, bottom to top — `yLabels[0]` is the bottom row (smallest bucket). */
+ yLabels: string[]
+ /** Dense grid of counts: `cells[rowIndex][colIndex]`, aligned with `yLabels`/`xLabels`.
+ * 0 (or a missing entry) means an empty cell — nothing is drawn there. */
+ cells: number[][]
+ theme: ChartTheme
+ config?: HeatmapConfig
+ /** Custom tooltip. Each `ctx.seriesData` entry is one row at the hovered column; narrow to
+ * the hovered cell via `findClosestSeriesKey(ctx.seriesData, ctx.hoverPosition.y)`. */
+ tooltip?: (ctx: HeatmapTooltipContext) => React.ReactNode
+ /** Fired when the user clicks a cell. */
+ onCellClick?: (cell: HeatmapCellDatum) => void
+ className?: string
+ dataAttr?: string
+ children?: React.ReactNode
+ onError?: (error: Error, info: React.ErrorInfo) => void
+}
+
+export function Heatmap({ onError, ...rest }: HeatmapProps): React.ReactElement {
+ return (
+ <ChartErrorBoundary onError={onError}>
+ <HeatmapInner {...rest} />
+ </ChartErrorBoundary>
+ )
+}
+
+function HeatmapInner({
+ xLabels,
+ yLabels,
+ cells,
+ theme,
+ config,
+ tooltip,
+ onCellClick,
+ className,
+ dataAttr,
+ children,
+}: Omit<HeatmapProps, 'onError'>): React.ReactElement {
+ const { colorScale = 'log' } = config ?? {}
+ // Resolve a `var(--…)` accent to a concrete color — canvas `fillStyle` (and `dimColor`'s
+ // d3 parse) can't handle CSS variables, so an unresolved var would blank out every cell.
+ // theme.colors are already resolved, so the memo re-runs (and re-resolves the accent against
+ // the current theme) on a light/dark flip too.
+ const accent = useMemo(
+ () => resolveCssColor(config?.color || theme.colors[0] || '#1d4aff'),
+ [config?.color, theme.colors]
+ )
+
+ // Dense row-major grid padded to the label counts, so a ragged `cells` input can't
+ // desync the draw loop from the axis.
+ const grid = useMemo<number[][]>(
+ () => yLabels.map((_, r) => xLabels.map((_, c) => cells[r]?.[c] ?? 0)),
+ [yLabels, xLabels, cells]
+ )
+
+ // Per-column keys so repeated `xLabels` don't collapse onto one slot in the base chart's
+ // label-keyed interaction and tick layer; formatters map them back to the display label.
+ const columnKeys = useMemo<string[]>(() => xLabels.map((_, i) => `${i}`), [xLabels])
+ const resolveColumnLabel = useCallback((key: string): string => xLabels[Number(key)] ?? key, [xLabels])
+ const maxValue = useMemo(() => maxCellValue(grid), [grid])
+
+ // One adapter series per row: `data` is that row's counts (tooltip values), `meta.rowIndex`
+ // maps back to the grid. All rows share the accent so tooltip swatches stay consistent.
+ const adaptedSeries = useMemo<Series<HeatmapRowMeta>[]>(
+ () =>
+ yLabels.map((yLabel, rowIndex) => ({
+ key: `row:${rowIndex}`,
+ label: yLabel,
+ data: grid[rowIndex],
+ color: accent,
+ meta: { rowIndex },
+ })),
+ [yLabels, grid, accent]
+ )
+
+ // The y "value" space is row units: rowIndex → bottom edge, rowIndex + 1 → top edge,
+ // rowIndex + 0.5 → center. Ticks sit at row centers and format to the row's label.
+ const yTickFormatter = useCallback(
+ (value: number): string => {
+ if (yLabels.length === 0) {
+ return ''
+ }
+ const index = Math.min(yLabels.length - 1, Math.max(0, Math.round(value - 0.5)))
+ return yLabels[index] ?? ''
+ },
+ [yLabels]
+ )
+
+ // Feeds `useChartMargins` tick sizing: row-center values run through `yTickFormatter`, so
+ // the y gutter is measured against the real row labels instead of the cell counts.
+ const valueRangeSeries = useMemo<Series[]>(
+ () => [{ key: '__heatmap-rows', label: '', data: yLabels.map((_, i) => i + 0.5) }],
+ [yLabels]
+ )
+
+ const createScales: CreateScalesFn = useCallback(
+ (_coloredSeries: ResolvedSeries[], scaleLabels: string[], dimensions: ChartDimensions): ChartScales => {
+ const layout = computeHeatmapLayout(dimensions, scaleLabels.length, yLabels.length)
+ const labelIndex = new Map(scaleLabels.map((label, i) => [label, i]))
+ const priv: HeatmapPrivate = {
+ __heatmap: { layout, cells: grid, accent, maxValue, colorScale },
+ }
+ return {
+ x: (label: string) => {
+ const index = labelIndex.get(label)
+ return index == null ? undefined : layout.plotLeft + (index + 0.5) * layout.colWidth
+ },
+ y: (value: number) => layout.plotTop + layout.plotHeight - value * layout.rowHeight,
+ yTicks: () => yLabels.map((_, i) => i + 0.5),
+ extent: () => layout.colWidth,
+ _private: priv,
+ }
+ },
+ [yLabels, grid, accent, maxValue, colorScale]
+ )
+
+ const drawStatic = useCallback(({ ctx, scales }: ChartDrawArgs) => {
+ const priv = (scales._private as HeatmapPrivate | undefined)?.__heatmap
+ if (!priv) {
+ return
+ }
+ const { layout, cells: drawCells, accent: drawAccent, maxValue: max, colorScale: scale } = priv
+ const cellColor = createCellColorRamp(drawAccent)
+ // A 1px gutter keeps cells readable as discrete buckets; collapse it when cells are so
+ // small the gap would dominate the fill.
+ const gap = layout.colWidth > 3 && layout.rowHeight > 3 ? 1 : 0
+ for (let r = 0; r < layout.rows; r++) {
+ const row = drawCells[r]
+ if (!row) {
+ continue
+ }
+ for (let c = 0; c < layout.cols; c++) {
+ const value = row[c]
+ if (!(value > 0)) {
+ continue
+ }
+ const rect = cellRect(layout, c, r)
+ ctx.fillStyle = cellColor(normalizeCount(value, max, scale))
+ ctx.fillRect(rect.x + gap / 2, rect.y + gap / 2, rect.width - gap, rect.height - gap)
+ }
+ }
+ }, [])
+
+ const drawHover = useCallback(
+ ({ ctx, scales, hoverIndex, hoverPosition, hoverProgress }: ChartDrawArgs): boolean => {
+ const priv = (scales._private as HeatmapPrivate | undefined)?.__heatmap
+ if (!priv || hoverIndex < 0 || !hoverPosition) {
+ return false
+ }
+ const row = rowAtY(priv.layout, hoverPosition.y)
+ if (row < 0) {
+ return false
+ }
+ const rect = cellRect(priv.layout, hoverIndex, row)
+ ctx.save()
+ ctx.globalAlpha = hoverProgress
+ ctx.strokeStyle = priv.accent
+ ctx.lineWidth = 1.5
+ ctx.strokeRect(rect.x + 0.75, rect.y + 0.75, rect.width - 1.5, rect.height - 1.5)
+ ctx.restore()
+ return true
+ },
+ []
+ )
+
+ // Each row's tooltip anchor spans its cell exactly (top edge → bottom edge), so
+ // `findClosestSeriesKey`'s containment pass resolves the hovered cell.
+ const resolvePositionValue: ResolveValueFn = useCallback(
+ (series) => ((series.meta as HeatmapRowMeta | undefined)?.rowIndex ?? 0) + 1,
+ []
+ )
+ const resolveBottomValue: ResolveValueFn = useCallback(
+ (series) => (series.meta as HeatmapRowMeta | undefined)?.rowIndex ?? 0,
+ []
+ )
+
+ // Rewrite clicks to the row under the cursor — the base chart's click payload carries the
+ // first series at the column, which is meaningless for a grid.
+ const wrapClickData = useCallback(
+ (data: PointClickData<HeatmapRowMeta>, scales: ChartScales): PointClickData<HeatmapRowMeta> => {
+ const priv = (scales._private as HeatmapPrivate | undefined)?.__heatmap
+ if (!priv || !data.cursor) {
+ return data
+ }
+ const row = rowAtY(priv.layout, data.cursor.y)
+ const match = data.crossSeriesData.find((entry) => entry.series.meta?.rowIndex === row)
+ if (row < 0 || !match) {
+ return data
+ }
+ return { ...data, series: match.series, seriesIndex: row, value: match.value }
+ },
+ []
+ )
+
+ const handlePointClick = useCallback(
+ (data: PointClickData<HeatmapRowMeta>): void => {
+ const rowIndex = data.series.meta?.rowIndex
+ if (rowIndex == null || !onCellClick) {
+ return
+ }
+ onCellClick({
+ xIndex: data.dataIndex,
+ yIndex: rowIndex,
+ // `data.label` is the per-column key, not the display label — map back by index.
+ xLabel: xLabels[data.dataIndex] ?? '',
+ yLabel: yLabels[rowIndex] ?? '',
+ value: data.value,
+ })
+ },
+ [onCellClick, xLabels, yLabels]
+ )
+
+ const userXTickFormatter = config?.xTickFormatter
+ const xTickFormatter = useCallback(
+ (key: string, index: number): string | null => {
+ const label = resolveColumnLabel(key)
+ return userXTickFormatter ? userXTickFormatter(label, index) : label
+ },
+ [resolveColumnLabel, userXTickFormatter]
+ )
+
+ const tooltipLabelFormatter = config?.tooltip?.labelFormatter
+ const tooltipValueFormatter = config?.tooltip?.valueFormatter
+ const renderTooltip = useMemo(
+ () =>
+ (ctx: HeatmapTooltipContext): React.ReactNode => {
+ // The base chart's `ctx.label` is the per-column key; restore the display label
+ // before it reaches either the custom or default tooltip.
+ const mapped = { ...ctx, label: resolveColumnLabel(ctx.label) }
+ if (tooltip) {
+ return tooltip(mapped)
+ }
+ // Narrow to the single hovered cell — rows carry their cell's exact pixel range
+ // (yPixel/yPixelBottom), so containment resolves it — and let DefaultTooltip
+ // render that one row rather than maintaining a bespoke tooltip surface.
+ const key = mapped.hoverPosition
+ ? findClosestSeriesKey(mapped.seriesData, mapped.hoverPosition.y)
+ : null
+ const entry = mapped.seriesData.find((s) => s.series.key === key)
+ if (!entry) {
+ return null
+ }
+ return (
+ <DefaultTooltip
+ {...mapped}
+ seriesData={[entry]}
+ labelFormatter={tooltipLabelFormatter}
+ valueFormatter={tooltipValueFormatter}
+ />
+ )
+ },
+ [tooltip, resolveColumnLabel, tooltipLabelFormatter, tooltipValueFormatter]
+ )
+
+ const baseConfig = useMemo<ChartConfig>(
+ () => ({
+ xTickFormatter,
+ yTickFormatter,
+ xAxisLabel: config?.xAxisLabel,
+ yAxisLabel: config?.yAxisLabel,
+ hideXAxis: config?.hideXAxis,
+ hideYAxis: config?.hideYAxis,
+ margins: config?.margins,
+ // 'cursor' placement: a follow-data anchor would pin the tooltip to the column top,
+ // far from the hovered cell in a tall grid.
+ tooltip: { enabled: config?.tooltip?.enabled, placement: 'cursor' },
+ }),
+ [
+ xTickFormatter,
+ yTickFormatter,
+ config?.xAxisLabel,
+ config?.yAxisLabel,
+ config?.hideXAxis,
+ config?.hideYAxis,
+ config?.margins,
+ config?.tooltip?.enabled,
+ ]
+ )
+
+ return (
+ <Chart<HeatmapRowMeta>
+ series={adaptedSeries}
+ labels={columnKeys}
+ config={baseConfig}
+ theme={theme}
+ createScales={createScales}
+ drawStatic={drawStatic}
+ drawHover={drawHover}
+ tooltip={renderTooltip}
+ onPointClick={onCellClick ? handlePointClick : undefined}
+ wrapClickData={wrapClickData}
+ resolvePositionValue={resolvePositionValue}
+ resolveBottomValue={resolveBottomValue}
+ valueRangeSeries={valueRangeSeries}
+ className={className}
+ dataAttr={dataAttr}
+ >
+ {children}
+ </Chart>
+ )
+}
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.test.ts b/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.test.ts
new file mode 100644
index 000000000000..ee78b632efd3
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.test.ts
@@ -0,0 +1,43 @@
+import type { ChartDimensions } from '../../core/types'
+import { cellRect, computeHeatmapLayout, maxCellValue, normalizeCount, rowAtY } from './heatmap-layout'
+
+const DIMENSIONS: ChartDimensions = {
+ width: 500,
+ height: 300,
+ plotLeft: 50,
+ plotTop: 20,
+ plotWidth: 400,
+ plotHeight: 200,
+}
+
+describe('heatmap-layout', () => {
+ // Row 0 must be the BOTTOM row (ascending value axis). Flipping this silently inverts
+ // every tooltip, hover highlight, and brush mapping downstream.
+ it('lays rows out bottom-to-top and maps pixels back to the same rows', () => {
+ const layout = computeHeatmapLayout(DIMENSIONS, 10, 4) // rowHeight 50
+ expect(cellRect(layout, 0, 0)).toEqual({ x: 50, y: 170, width: 40, height: 50 }) // bottom row
+ expect(cellRect(layout, 9, 3)).toEqual({ x: 410, y: 20, width: 40, height: 50 }) // top-right
+
+ expect(rowAtY(layout, 219)).toBe(0) // just above the plot bottom
+ expect(rowAtY(layout, 21)).toBe(3) // just below the plot top
+ expect(rowAtY(layout, 250)).toBe(-1) // below the plot
+ expect(rowAtY(layout, 10)).toBe(-1) // above the plot
+ })
+
+ it.each([
+ ['zero count maps to 0', 0, 100, 'log', 0],
+ ['zero max maps to 0 (all-empty grid)', 5, 0, 'log', 0],
+ ['max count maps to 1', 100, 100, 'log', 1],
+ ['linear is proportional', 50, 100, 'linear', 0.5],
+ ] as const)('normalizeCount: %s', (_name, count, max, scale, expected) => {
+ expect(normalizeCount(count, max, scale)).toBeCloseTo(expected)
+ })
+
+ it('log normalization lifts small counts above linear so the long tail stays visible', () => {
+ expect(normalizeCount(2, 1000, 'log')).toBeGreaterThan(normalizeCount(2, 1000, 'linear'))
+ })
+
+ it('maxCellValue ignores non-finite values', () => {
+ expect(maxCellValue([[1, Number.NaN], [Number.POSITIVE_INFINITY, 7]])).toBe(7)
+ })
+})
diff --git a/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.ts b/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.ts
new file mode 100644
index 000000000000..bdfd48cb6aa3
--- /dev/null
+++ b/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.ts
@@ -0,0 +1,102 @@
+import { dimColor } from '../../core/color-utils'
+import type { ChartDimensions } from '../../core/types'
+
+/** How cell counts map to color intensity. `log` (default) uses log1p normalization —
+ * latency/count grids are long-tailed, and a linear ramp washes out everything but the mode. */
+export type HeatmapColorScale = 'log' | 'linear'
+
+/** Uniform grid layout of the heatmap plot area. Rows index bottom-to-top: row 0 is the
+ * bottom row, matching an ascending value axis (smallest bucket at the bottom). */
+export interface HeatmapLayout {
+ cols: number
+ rows: number
+ colWidth: number
+ rowHeight: number
+ plotLeft: number
+ plotTop: number
+ plotWidth: number
+ plotHeight: number
+}
+
+export function computeHeatmapLayout(dimensions: ChartDimensions, cols: number, rows: number): HeatmapLayout {
+ return {
+ cols,
+ rows,
+ colWidth: cols > 0 ? dimensions.plotWidth / cols : 0,
+ rowHeight: rows > 0 ? dimensions.plotHeight / rows : 0,
+ plotLeft: dimensions.plotLeft,
+ plotTop: dimensions.plotTop,
+ plotWidth: dimensions.plotWidth,
+ plotHeight: dimensions.plotHeight,
+ }
+}
+
+export interface CellRect {
+ x: number
+ y: number
+ width: number
+ height: number
+}
+
+/** Pixel rect of the cell at (colIndex, rowIndex). Row 0 is the bottom row. */
+export function cellRect(layout: HeatmapLayout, colIndex: number, rowIndex: number): CellRect {
+ return {
+ x: layout.plotLeft + colIndex * layout.colWidth,
+ y: layout.plotTop + layout.plotHeight - (rowIndex + 1) * layout.rowHeight,
+ width: layout.colWidth,
+ height: layout.rowHeight,
+ }
+}
+
+/** Row index under a canvas y pixel, or -1 outside the plot. Row 0 is the bottom row. */
+export function rowAtY(layout: HeatmapLayout, y: number): number {
+ if (layout.rows === 0 || layout.rowHeight <= 0) {
+ return -1
+ }
+ const row = Math.floor((layout.plotTop + layout.plotHeight - y) / layout.rowHeight)
+ return row >= 0 && row < layout.rows ? row : -1
+}
+
+export function maxCellValue(cells: number[][]): number {
+ let max = 0
+ for (const row of cells) {
+ for (const value of row) {
+ if (Number.isFinite(value) && value > max) {
+ max = value
+ }
+ }
+ }
+ return max
+}
+
+/** Normalize a count to [0, 1] against the grid maximum. Zero/absent counts and an
+ * all-zero grid map to 0 — callers skip drawing those cells entirely. */
+export function normalizeCount(count: number, max: number, scale: HeatmapColorScale): number {
+ if (!(max > 0) || !(count > 0)) {
+ return 0
+ }
+ const t = scale === 'linear' ? count / max : Math.log1p(count) / Math.log1p(max)
+ return Math.max(0, Math.min(1, t))
+}
+
+// Alpha floor so a count-of-1 cell is still visible against the plot background.
+const MIN_CELL_ALPHA = 0.15
+
+/** A cell-fill ramp bound to one accent: maps a normalized intensity [0, 1] to a translucent
+ * fill (an alpha ramp over the accent), so density reads on light and dark without extra theme
+ * tokens. Memoizes by 8-bit alpha — canvas can't resolve finer, and the draw loop hits the same
+ * intensities across hundreds of cells, so the accent is parsed at most 256 times per draw
+ * instead of once per cell. */
+export function createCellColorRamp(accent: string): (t: number) => string {
+ const cache = new Map<number, string>()
+ return (t: number): string => {
+ const alpha = MIN_CELL_ALPHA + (1 - MIN_CELL_ALPHA) * Math.max(0, Math.min(1, t))
+ const key = Math.round(alpha * 255)
+ let color = cache.get(key)
+ if (color === undefined) {
+ color = dimColor(accent, key / 255)
+ cache.set(key, color)
+ }
+ return color
+ }
+}
diff --git a/packages/quill/packages/charts/src/core/color-utils.test.ts b/packages/quill/packages/charts/src/core/color-utils.test.ts
index 0a1d076f7bee..75094239abd5 100644
--- a/packages/quill/packages/charts/src/core/color-utils.test.ts
+++ b/packages/quill/packages/charts/src/core/color-utils.test.ts
@@ -1,13 +1,31 @@
-import { mixColors } from './color-utils'
+import { mixColors, resolveCssColor } from './color-utils'
describe('mixColors', () => {
it.each([
- { name: 'midpoint is halfway between the two colors', from: '#000000', to: '#ffffff', t: 0.5, expected: 'rgb(128, 128, 128)' },
+ {
+ name: 'midpoint is halfway between the two colors',
+ from: '#000000',
+ to: '#ffffff',
+ t: 0.5,
+ expected: 'rgb(128, 128, 128)',
+ },
{ name: 't=0 returns the from color', from: '#000000', to: '#ffffff', t: 0, expected: 'rgb(0, 0, 0)' },
{ name: 't=1 returns the to color', from: '#000000', to: '#ffffff', t: 1, expected: 'rgb(255, 255, 255)' },
{ name: 't below 0 clamps to the from color', from: '#000000', to: '#ffffff', t: -1, expected: 'rgb(0, 0, 0)' },
- { name: 't above 1 clamps to the to color', from: '#000000', to: '#ffffff', t: 2, expected: 'rgb(255, 255, 255)' },
- { name: 'interpolates opacity', from: 'rgba(255, 0, 0, 0.2)', to: 'rgba(255, 0, 0, 0.8)', t: 0.5, expected: 'rgba(255, 0, 0, 0.5)' },
+ {
+ name: 't above 1 clamps to the to color',
+ from: '#000000',
+ to: '#ffffff',
+ t: 2,
+ expected: 'rgb(255, 255, 255)',
+ },
+ {
+ name: 'interpolates opacity',
+ from: 'rgba(255, 0, 0, 0.2)',
+ to: 'rgba(255, 0, 0, 0.8)',
+ t: 0.5,
+ expected: 'rgba(255, 0, 0, 0.5)',
+ },
])('$name', ({ from, to, t, expected }) => {
expect(mixColors(from, to, t)).toBe(expected)
})
@@ -16,3 +34,40 @@ describe('mixColors', () => {
expect(mixColors('not-a-color', '#ffffff', 0.5)).toBe('not-a-color')
})
})
+
+describe('resolveCssColor', () => {
+ // Canvas can't resolve `var()`; if this stops resolving a variable accent, the Heatmap ramp
+ // (dimColor → d3 parse → fillStyle) gets an unparseable string and cells render blank.
+ function rootWithVars(vars: Record<string, string>): HTMLElement {
+ const el = document.createElement('div')
+ for (const [name, value] of Object.entries(vars)) {
+ el.style.setProperty(name, value)
+ }
+ document.body.appendChild(el)
+ return el
+ }
+
+ afterEach(() => {
+ document.body.replaceChildren()
+ })
+
+ it('passes a concrete color through unchanged', () => {
+ expect(resolveCssColor('#1d4aff')).toBe('#1d4aff')
+ expect(resolveCssColor('rgb(1, 2, 3)')).toBe('rgb(1, 2, 3)')
+ })
+
+ it('resolves a CSS variable to its computed value', () => {
+ const root = rootWithVars({ '--data-color-1': '#abcdef' })
+ expect(resolveCssColor('var(--data-color-1)', root)).toBe('#abcdef')
+ })
+
+ it('uses the fallback when the variable is undefined', () => {
+ const root = rootWithVars({})
+ expect(resolveCssColor('var(--missing, #123456)', root)).toBe('#123456')
+ })
+
+ it('returns the raw string when the variable is undefined and has no fallback', () => {
+ const root = rootWithVars({})
+ expect(resolveCssColor('var(--missing)', root)).toBe('var(--missing)')
+ })
+})
diff --git a/packages/quill/packages/charts/src/core/color-utils.ts b/packages/quill/packages/charts/src/core/color-utils.ts
index 554fc952fcbb..973124bdf009 100644
--- a/packages/quill/packages/charts/src/core/color-utils.ts
+++ b/packages/quill/packages/charts/src/core/color-utils.ts
@@ -8,6 +8,32 @@ export function dimColor(color: string, alpha: number): string {
return d3Color(color)?.copy({ opacity: alpha }).toString() ?? color
}
+/** Resolve a CSS custom-property reference (`var(--x)`, with an optional fallback) to its
+ * computed color value. A canvas 2D context can't resolve `var()`, so an accent handed to
+ * `fillStyle`/`strokeStyle` (or through `dimColor`, which relies on `d3.color` parsing it)
+ * must be a concrete color first. Non-`var()` inputs, and SSR/no-DOM contexts, return the
+ * input unchanged; `root` defaults to `document.body` to match {@link themeFromCssVars}. */
+export function resolveCssColor(color: string, root?: HTMLElement): string {
+ const trimmed = color.trim()
+ if (!trimmed.startsWith('var(')) {
+ return color
+ }
+ if (typeof document === 'undefined' || typeof getComputedStyle !== 'function') {
+ return color
+ }
+ const match = /^var\(\s*(--[^,)]+?)\s*(?:,\s*([\s\S]+))?\)$/.exec(trimmed)
+ if (!match) {
+ return color
+ }
+ const [, name, fallback] = match
+ const el = root ?? document.body
+ const value = getComputedStyle(el).getPropertyValue(name).trim()
+ if (value) {
+ return value
+ }
+ return fallback && fallback.trim() ? resolveCssColor(fallback.trim(), el) : color
+}
+
/** Linear RGB interpolation between two colors. `t` is clamped to [0, 1]; `t=0` returns `from`,
* `t=1` returns `to`. Falls back to `from` when either color can't be parsed. */
export function mixColors(from: string, to: string, t: number): string {
diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.ts
index b4294c8160a4..db83fa78c8e2 100644
--- a/packages/quill/packages/charts/src/index.ts
+++ b/packages/quill/packages/charts/src/index.ts
@@ -59,6 +59,17 @@ export type { BoxRect } from './core/types'
export { BoxPlotTooltip } from './charts/BoxPlot/BoxPlotTooltip'
export type { BoxPlotTooltipProps } from './charts/BoxPlot/BoxPlotTooltip'
+// Heatmap
+export { Heatmap } from './charts/Heatmap/Heatmap'
+export type {
+ HeatmapCellDatum,
+ HeatmapConfig,
+ HeatmapProps,
+ HeatmapRowMeta,
+ HeatmapTooltipContext,
+} from './charts/Heatmap/Heatmap'
+export type { HeatmapColorScale } from './charts/Heatmap/heatmap-layout'
+
// Slope chart
export { SlopeChart } from './charts/SlopeChart/SlopeChart'
export type {