: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(charts): let the quill heatmap print a label in each cell (#102069)
Sam Penningtonedcd953a7960
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 7829a73f6ffb..f5326e68cb8c 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -192,6 +192,14 @@ snapshots:hash: v1.k794b7964.086485b762cfc1047f790eb9be1bf2d32411d88a9abb0aaa65eb9832d4460803.5sMKoH-Saf_fJOsoEBC62DjNoqB6-Pbp3yWlkrJe9wIai-observability-scorers--offline-disabled--light:hash: v1.k794b7964.2180bcbde737821240afcedee37c293417955b45ef6f03d990c8f5aa51933010.vALi9Nmw5uF4a15geZgWDSMnFrMnrx-01cJaq6zCuJ8+ charts-heatmap--cell-labels--dark:+ hash: v1.k794b7964.19b11a43aa9280e0b85498c1e87397d128cb1a1c9f1451419ab32de324783441.xEjoCIC6MhETYkz5iStffBD3Oc77sUugobUIKzq3EME+ charts-heatmap--cell-labels--light:+ hash: v1.k794b7964.2cc87c7069cfc6f370663f581b6866d795754e5a3604bf5c9827ca81a605f2d0.QBtjIUNJc3gvAOkojmyfhJUQwB1HB0zUkm3rdoUr3D0+ charts-heatmap--cell-labels-dropped-when-cells-are-small--dark:+ hash: v1.k794b7964.8f0bf7a9fc58c93f4dc73333e7debc16ac9e8beb1397753f8bf7876528c6be5e.l9lHu-Urnd94-CElJYYehON5QJ85IHWjuWrcd6QzZAg+ charts-heatmap--cell-labels-dropped-when-cells-are-small--light:+ hash: v1.k794b7964.3b470c279042363847a1ef329ab3726a284e8c0643ea9bab4801e087b7ada7d3.scHqOq42sVvvqNf8ClWcXX0dcA-06KfNxTbZv1oUmgccharts-heatmap--clickable-cells--dark:hash: v1.k794b7964.8f0bf7a9fc58c93f4dc73333e7debc16ac9e8beb1397753f8bf7876528c6be5e.vBhKsdEGwMCxSig2mqm7qome1H7ed0LuGFexudABJmocharts-heatmap--clickable-cells--light:diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.stories.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.stories.tsxindex 73c84bbdd766..f16172080fec 100644--- a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.stories.tsx+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.stories.tsx@@ -1,7 +1,7 @@import { Meta, StoryObj } from '@storybook/react'import { Stage, useReactiveTheme } from '../../story-helpers'-import { Heatmap } from './Heatmap'+import { Heatmap, type HeatmapCellDatum } 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)@@ -123,3 +123,45 @@ export const ClickableCells: Story = {)},}++// A retention grid: few, large cells whose numbers matter as much as their density.+const COHORT_LABELS = ['Week 4', 'Week 3', 'Week 2', 'Week 1']+const INTERVAL_LABELS = ['Day 0', 'Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5', 'Day 6']+const RETENTION_CELLS = COHORT_LABELS.map((_, row) =>+ INTERVAL_LABELS.map((_, col) => Math.round(100 * Math.exp(-col / (2.5 + row)) * 10) / 10)+)+const percentLabel = (cell: HeatmapCellDatum): string => `${cell.value.toFixed(1)}%`++export const CellLabels: Story = {+ render: function Render() {+ const theme = useReactiveTheme()+ return (+ <Stage width={720} height={280}>+ <Heatmap+ xLabels={INTERVAL_LABELS}+ yLabels={COHORT_LABELS}+ cells={RETENTION_CELLS}+ theme={theme}+ config={{ colorScale: 'linear', cellLabel: percentLabel }}+ />+ </Stage>+ )+ },+}++export const CellLabelsDroppedWhenCellsAreSmall: 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), cellLabel: percentLabel }}+ />+ </Stage>+ )+ },+}diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsxindex 8e6618170f71..c3a4db82ce45 100644--- a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.test.tsx@@ -2,11 +2,13 @@ import { waitFor } from '@testing-library/react'import type { ChartTheme } from '../../core/types'import { rawDrag, renderHogChart } from '../../testing'-import { Heatmap, type HeatmapBrushData } from './Heatmap'+import { Heatmap, type HeatmapBrushData, type HeatmapCellDatum } from './Heatmap'const THEME: ChartTheme = {colors: ['#1f77b4', '#ff7f0e'],backgroundColor: '#ffffff',+ // Light, as a dark theme sets it, so a label that borrows axis ink fails the contrast test.+ axisColor: '#cccccc',gridColor: '#eeeeee',crosshairColor: '#888888',}@@ -61,6 +63,56 @@ describe('Heatmap', () => {expect(chart.seriesCount).toBe(Y_LABELS.length)})+ describe('cellLabel', () => {+ function cellLabels(element: HTMLElement): HTMLElement[] {+ return Array.from(element.querySelectorAll('[data-attr="hog-chart-heatmap-cell-label"]'))+ }++ function renderLabelled(+ cellLabel: (cell: HeatmapCellDatum) => string | null,+ xLabels: string[] = X_LABELS,+ cells: number[][] = CELLS+ ): HTMLElement[] {+ const { chart } = renderHogChart(+ <Heatmap xLabels={xLabels} yLabels={Y_LABELS} cells={cells} theme={THEME} config={{ cellLabel }} />+ )+ return cellLabels(chart.element)+ }++ it('renders no labels without a formatter', () => {+ const { chart } = renderHogChart(+ <Heatmap xLabels={X_LABELS} yLabels={Y_LABELS} cells={CELLS} theme={THEME} />+ )+ expect(cellLabels(chart.element)).toHaveLength(0)+ })++ it('labels every cell, empty ones included', () => {+ const labels = renderLabelled((cell) => (cell.value > 0 ? String(cell.value) : '-'))+ expect(labels).toHaveLength(X_LABELS.length * Y_LABELS.length)+ expect(labels.filter((el) => el.textContent === '-')).toHaveLength(8)+ })++ it('leaves a cell unlabelled when the formatter returns null', () => {+ const labels = renderLabelled((cell) => (cell.value > 0 ? String(cell.value) : null))+ expect(labels).toHaveLength(8)+ })++ // Without the fit check a dense grid prints every number on top of its neighbour.+ it('drops labels too wide for their cell', () => {+ const manyColumns = Array.from({ length: 60 }, (_, i) => `col-${i}`)+ const wideCells = Y_LABELS.map(() => manyColumns.map(() => 5))+ expect(renderLabelled(() => '100.0%', manyColumns, wideCells)).toHaveLength(0)+ })++ // The densest cells are painted at the full accent, where dark text is unreadable.+ it('turns the label white over a saturated cell and keeps it dark over an empty one', () => {+ const labels = renderLabelled((cell) => String(cell.value))+ const byText = new Map(labels.map((el) => [el.textContent, el.style.color]))+ expect(byText.get('10')).toBe('rgb(255, 255, 255)')+ expect(byText.get('0')).toBe('rgb(17, 17, 17)')+ })+ })+// The jsdom chart mounts at 800x400; coordinates well inside the plot area are safe for drags.describe('onBrush', () => {async function brush(from: { x: number; y: number }, to: { x: number; y: number }): Promise<HeatmapBrushData> {diff --git a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsxindex a9e52ba1647c..d78ed07dac0d 100644--- a/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx+++ b/packages/quill/packages/charts/src/charts/Heatmap/Heatmap.tsx@@ -31,6 +31,7 @@ import {type HeatmapColorScale,type HeatmapLayout,} from './heatmap-layout'+import { HeatmapCellLabels, type HeatmapCellLabelFormatter } from './HeatmapCellLabels'/** 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. */@@ -68,6 +69,11 @@ export interface HeatmapConfig {yAxisLabel?: stringhideXAxis?: booleanhideYAxis?: boolean+ /** Draws a label in the middle of each cell, so the grid reads as values and not only as+ * density. Called for every cell, empty ones included; return null or an empty string to+ * leave a cell unlabelled. A label is dropped when its cell is too small for the text, so a+ * dense grid falls back to a plain density map. Should be referentially stable. */+ cellLabel?: HeatmapCellLabelFormatter/** Per-side margin overrides. Should be referentially stable. */margins?: Partial<ChartMargins>tooltip?: {@@ -444,6 +450,17 @@ function HeatmapInner({className={className}dataAttr={dataAttr}>+ {config?.cellLabel && (+ <HeatmapCellLabels+ xLabels={xLabels}+ yLabels={yLabels}+ cells={grid}+ accent={accent}+ maxValue={maxValue}+ colorScale={colorScale}+ formatter={config.cellLabel}+ />+ )}{children}</Chart>)diff --git a/packages/quill/packages/charts/src/charts/Heatmap/HeatmapCellLabels.tsx b/packages/quill/packages/charts/src/charts/Heatmap/HeatmapCellLabels.tsxnew file mode 100644index 000000000000..e3555021d3f5--- /dev/null+++ b/packages/quill/packages/charts/src/charts/Heatmap/HeatmapCellLabels.tsx@@ -0,0 +1,125 @@+import React, { useMemo } from 'react'++import { useChartLayout } from '../../core/chart-context'+import { mixColors, perceivedLuminance, toSrgbColor } from '../../core/color-utils'+import { FONT_FAMILY, measureLabelWidth } from '../../utils/text-measure'+import type { HeatmapCellDatum } from './Heatmap'+import { cellAlpha, cellRect, computeHeatmapLayout, normalizeCount, type HeatmapColorScale } from './heatmap-layout'++/** Returning null or an empty string leaves the cell unlabelled. */+export type HeatmapCellLabelFormatter = (cell: HeatmapCellDatum) => string | null++const LABEL_FONT_SIZE = 12+const LABEL_FONT = `500 ${LABEL_FONT_SIZE}px ${FONT_FAMILY}`+const LABEL_PADDING_X = 4+// Under this the text touches the cell edges and reads as one smear across rows.+const MIN_CELL_HEIGHT = LABEL_FONT_SIZE + 4+// Below this the fill is dark enough for white text; at or above it, dark text stays readable.+const DARK_FILL_LUMINANCE = 0.55+// Not `theme.axisColor`: a dark theme makes that light gray, which vanishes on a bright cell.+const DARK_TEXT = '#111111'++const LABEL_STYLE_BASE: React.CSSProperties = {+ position: 'absolute',+ transform: 'translate(-50%, -50%)',+ // Render in the font the fit check measures with, so a host font can't overflow a cell.+ fontFamily: FONT_FAMILY,+ fontSize: LABEL_FONT_SIZE,+ fontWeight: 500,+ lineHeight: 1,+ pointerEvents: 'none',+ whiteSpace: 'nowrap',+}++interface PlacedLabel {+ key: string+ text: string+ x: number+ y: number+ color: string+}++export interface HeatmapCellLabelsProps {+ xLabels: string[]+ yLabels: string[]+ /** Dense grid, `cells[rowIndex][colIndex]` — the same grid the canvas draws. */+ cells: number[][]+ accent: string+ maxValue: number+ colorScale: HeatmapColorScale+ formatter: HeatmapCellLabelFormatter+}++/** DOM labels centered in each heatmap cell. Text stays DOM rather than canvas for the same+ * reason the axis labels do: crisp type, and one place that owns font and color. */+export function HeatmapCellLabels({+ xLabels,+ yLabels,+ cells,+ accent,+ maxValue,+ colorScale,+ formatter,+}: HeatmapCellLabelsProps): React.ReactElement | null {+ const { dimensions, theme } = useChartLayout()++ const placed = useMemo<PlacedLabel[]>(() => {+ const layout = computeHeatmapLayout(dimensions, xLabels.length, yLabels.length)+ const maxTextWidth = layout.colWidth - LABEL_PADDING_X * 2+ if (layout.rowHeight < MIN_CELL_HEIGHT || maxTextWidth <= 0) {+ return []+ }+ const background = toSrgbColor(theme.backgroundColor ?? '#ffffff')+ const fillAccent = toSrgbColor(accent)+ const out: PlacedLabel[] = []+ for (let row = 0; row < layout.rows; row++) {+ for (let col = 0; col < layout.cols; col++) {+ const value = cells[row]?.[col] ?? 0+ const text = formatter({+ xIndex: col,+ yIndex: row,+ xLabel: xLabels[col] ?? '',+ yLabel: yLabels[row] ?? '',+ value,+ })+ if (!text || measureLabelWidth(text, LABEL_FONT) > maxTextWidth) {+ continue+ }+ // The canvas paints the accent at `cellAlpha` over the plot background, and a+ // linear mix by that alpha is exactly that composite, so the text contrasts+ // against the color the reader sees instead of the accent at full strength.+ const fill =+ value > 0+ ? mixColors(background, fillAccent, cellAlpha(normalizeCount(value, maxValue, colorScale)))+ : background+ const rect = cellRect(layout, col, row)+ out.push({+ key: `${row}:${col}`,+ text,+ x: rect.x + rect.width / 2,+ y: rect.y + rect.height / 2,+ color: perceivedLuminance(fill) < DARK_FILL_LUMINANCE ? '#ffffff' : DARK_TEXT,+ })+ }+ }+ return out+ }, [dimensions, theme, xLabels, yLabels, cells, accent, maxValue, colorScale, formatter])++ if (placed.length === 0) {+ return null+ }++ return (+ <>+ {placed.map((label) => (+ <div+ key={label.key}+ data-attr="hog-chart-heatmap-cell-label"+ style={{ ...LABEL_STYLE_BASE, left: label.x, top: label.y, color: label.color }}+ >+ {label.text}+ </div>+ ))}+ </>+ )+}diff --git a/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.ts b/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.tsindex c4d0c9ab6040..4a31121f3466 100644--- a/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.ts+++ b/packages/quill/packages/charts/src/charts/Heatmap/heatmap-layout.ts@@ -96,6 +96,12 @@ export function normalizeCount(count: number, max: number, scale: HeatmapColorSc// Alpha floor so a count-of-1 cell is still visible against the plot background.const MIN_CELL_ALPHA = 0.15+/** Opacity a cell of normalized intensity `t` is filled at. Label code recreates the+ * composited cell color from this to choose a readable text color. */+export function cellAlpha(t: number): number {+ return MIN_CELL_ALPHA + (1 - MIN_CELL_ALPHA) * Math.max(0, Math.min(1, t))+}+/** 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@@ -104,8 +110,7 @@ const MIN_CELL_ALPHA = 0.15export 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)+ const key = Math.round(cellAlpha(t) * 255)let color = cache.get(key)if (color === undefined) {color = dimColor(accent, key / 255)diff --git a/packages/quill/packages/charts/src/core/color-utils.ts b/packages/quill/packages/charts/src/core/color-utils.tsindex 973124bdf009..c561c0ba1c6b 100644--- a/packages/quill/packages/charts/src/core/color-utils.ts+++ b/packages/quill/packages/charts/src/core/color-utils.ts@@ -48,6 +48,43 @@ export function mixColors(from: string, to: string, t: number): string {return d3Rgb(lerp(a.r, b.r), lerp(a.g, b.g), lerp(a.b, b.b), lerp(a.opacity, b.opacity)).toString()}+let srgbProbe: CanvasRenderingContext2D | null | undefined++/** `color` in a form d3 can parse. Modern syntax such as `oklch()` survives a round trip through+ * `fillStyle` unchanged, so it is painted to one pixel and read back. Returns the input when+ * there is no DOM or the browser rejects the color. */+export function toSrgbColor(color: string): string {+ if (!Number.isNaN(d3Rgb(color).r)) {+ return color+ }+ if (srgbProbe === undefined) {+ srgbProbe =+ typeof document === 'undefined'+ ? null+ : document.createElement('canvas').getContext('2d', { willReadFrequently: true })+ }+ if (!srgbProbe) {+ return color+ }+ srgbProbe.clearRect(0, 0, 1, 1)+ srgbProbe.fillStyle = 'transparent'+ srgbProbe.fillStyle = color+ srgbProbe.fillRect(0, 0, 1, 1)+ const [r, g, b, a] = srgbProbe.getImageData(0, 0, 1, 1).data+ return a === 0 ? color : d3Rgb(r, g, b, a / 255).toString()+}++/** Perceived luminance of a color, 0 (black) to 1 (white), on the ITU-R BT.601 weighting.+ * Use it to pick light or dark text over a fill. Unparseable input returns 1, so a caller+ * falls back to dark text. */+export function perceivedLuminance(color: string): number {+ const c = d3Rgb(color)+ if (Number.isNaN(c.r)) {+ return 1+ }+ return (0.299 * c.r + 0.587 * c.g + 0.114 * c.b) / 255+}+/** Fill color for the bar at `index`: the per-bar override (`bars[index].color`) when set, else the* series color. The one resolver every bar color-read site (fill, hover highlight, tooltip swatch,* value labels) should use, so a per-bar series can't accidentally render bars in the series color. */diff --git a/packages/quill/packages/charts/src/docs/chart-types.md b/packages/quill/packages/charts/src/docs/chart-types.mdindex 5732c7dd52ca..930d90c6230e 100644--- a/packages/quill/packages/charts/src/docs/chart-types.md+++ b/packages/quill/packages/charts/src/docs/chart-types.md@@ -103,6 +103,9 @@ The tooltip receives a `BoxPlotTooltipContext`; `BoxPlotTooltip` is the default.A 2D density grid: `xLabels` by `yLabels` (row 0 at the bottom), `cells[row][col]` counts mapped to color intensity on one accent.Log ramp by default; `colorScale: 'linear'` to opt out.A single-cell tooltip resolves from the cursor, `onCellClick` reports `{ xIndex, yIndex, value }`, and `onBrush` reports row and column index ranges.+`config.cellLabel` prints a number in each cell, for a grid read as values rather than only as density (a retention table).+It runs for every cell, empty ones included; return null to leave one blank.+Each label takes light or dark text from the cell fill behind it, and is dropped when the cell is too small for the text, so a dense grid falls back to a plain density map.## SankeyChartdiff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.tsindex 422eeca3be3e..69b2ab298f7b 100644--- a/packages/quill/packages/charts/src/index.ts+++ b/packages/quill/packages/charts/src/index.ts@@ -85,6 +85,7 @@ export type {HeatmapTooltipContext,} from './charts/Heatmap/Heatmap'export type { HeatmapColorScale } from './charts/Heatmap/heatmap-layout'+export type { HeatmapCellLabelFormatter } from './charts/Heatmap/HeatmapCellLabels'// Slope chartexport { SlopeChart } from './charts/SlopeChart/SlopeChart'