: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(quill-charts): position line chart labels by time (#127290)
Sam Pennington9a0825cde0df
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsxindex 929ad901c5a3..bf5b7129bc6b 100644--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.test.tsx@@ -1,6 +1,7 @@import { fireEvent } from '@testing-library/react'-import type { ChartTheme, Series } from '../../core/types'+import { useChartLayout } from '../../core/chart-context'+import type { ChartTheme, Series, TimeScale } from '../../core/types'import { ReferenceLine } from '../../overlays/ReferenceLine'import { dimensions as testDimensions, getChart, rawDrag, renderChart } from '../../testing'import { LineChart } from './LineChart'@@ -34,6 +35,45 @@ describe('LineChart', () => {expect(chart.seriesCount).toBeGreaterThan(0)})+ describe('timeScale', () => {+ const TIME_LABELS = ['2026-03-01T00:00:00Z', '2026-03-01T01:00:00Z', '2026-03-01T04:00:00Z']+ const timeScale = (from: string, to: string): TimeScale => ({+ parse: Date.parse,+ domain: [Date.parse(from), Date.parse(to)],+ })++ it.each([+ ['spaces labels evenly without one', undefined, [0, 0.5, 1]],+ ['places labels by time', timeScale(TIME_LABELS[0], TIME_LABELS[2]), [0, 0.25, 1]],+ [+ 'drops labels outside the domain',+ timeScale('2026-03-01T01:00:00Z', '2026-03-01T03:00:00Z'),+ [null, 0, null],+ ],+ ])('%s', (_, scale, expectedFractions) => {+ let fractions: (number | null)[] = []+ function Measure(): null {+ const { scales, dimensions } = useChartLayout()+ fractions = TIME_LABELS.map((label) => {+ const x = scales.x(label)+ return x == null ? null : (x - dimensions.plotLeft) / dimensions.plotWidth+ })+ return null+ }+ renderChart(+ <LineChart+ series={[{ key: 'a', label: 'A', data: [1, 2, 3] }]}+ labels={TIME_LABELS}+ theme={THEME}+ config={{ timeScale: scale }}+ >+ <Measure />+ </LineChart>+ )+ expect(fractions).toEqual(expectedFractions)+ })+ })+it('renders empty state without crashing', () => {const { chart } = renderChart(<LineChart series={[]} labels={[]} theme={THEME} />)expect(chart.seriesCount).toBe(0)diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsxindex 227f954acbf9..a2e64286d238 100644--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx@@ -20,6 +20,7 @@ import {computePercentStackData,computeStackData,createScales as createLineScales,+ createTimeXScale,resolveYScaleForSeries,toYAxisScales,yTickCountForHeight,@@ -98,6 +99,7 @@ function LineChartInner<Meta = unknown>({floatBaseline = false,yAxes,curve,+ timeScale,} = config ?? {}const smooth = curve === 'monotone'// Resolve to primitives so an inline `{ x, y }` config object can't churn the draw callbacks.@@ -167,14 +169,14 @@ function LineChartInner<Meta = unknown>({}return {- x: (label: string) => d3Scales.x(label),+ x: timeScale ? createTimeXScale(timeScale, dimensions) : (label: string) => d3Scales.x(label),y: (value: number) => d3Scales.y(value),yTicks: () => d3Scales.y.ticks?.(yTickCount) ?? [],yAxes: yAxisScales,_private: lineChartPrivate,}},- [yScaleType, percentStackView, stackedData, valueDomain, floatBaseline, yAxes]+ [yScaleType, percentStackView, stackedData, valueDomain, floatBaseline, yAxes, timeScale])const drawStatic = useCallback(@@ -192,7 +194,7 @@ function LineChartInner<Meta = unknown>({const baseDrawCtx: DrawContext = {ctx,dimensions,- xScale: d3Scales.x,+ xScale: scales.x,yScale: d3Scales.y,labels: drawLabels,}@@ -215,7 +217,7 @@ function LineChartInner<Meta = unknown>({dimensions,labels: drawLabels,series: coloredSeries,- xScale: d3Scales.x,+ xScale: scales.x,resolveYScale,yValuesFor: (s) => stackedData?.get(s.key)?.top,bottomFor: (s) => s.fill?.lowerData ?? stackedData?.get(s.key)?.bottom,diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.tsindex bccb9f1427b7..54bc1bfef3fc 100644--- a/packages/quill/packages/charts/src/core/scales.ts+++ b/packages/quill/packages/charts/src/core/scales.ts@@ -10,7 +10,7 @@ import {} from 'd3-scale'import { stack as stackGen, stackOffsetDiverging, stackOffsetExpand, stackOffsetNone } from 'd3-shape'-import type { BandSlot, ChartDimensions, ResolveValueFn, Series, ValueDomain, YAxisScale } from './types'+import type { BandSlot, ChartDimensions, ResolveValueFn, Series, TimeScale, ValueDomain, YAxisScale } from './types'import { DEFAULT_Y_AXIS_ID } from './types'/** Inner padding fraction applied to the band scale when `BarChartConfig.bars.bandPadding` is unset. */@@ -144,6 +144,19 @@ export function createXScale(labels: string[], dimensions: ChartDimensions): Sca.padding(0)}+export function createTimeXScale(+ { parse, domain }: TimeScale,+ dimensions: ChartDimensions+): (label: string) => number | undefined {+ const scale = scaleLinear()+ .domain(domain)+ .range([dimensions.plotLeft, dimensions.plotLeft + dimensions.plotWidth])+ return (label) => {+ const t = parse(label)+ return t >= domain[0] && t <= domain[1] ? scale(t) : undefined+ }+}+/** Min/max y-axis tick counts. `MIN_Y_TICKS` doubles as the floor for a non-finite/non-positive* plot height, where d3's `ticks()` would otherwise return an empty array. */const MIN_Y_TICKS = 2diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.tsindex 9b48a52b77e8..6fc632d3e31a 100644--- a/packages/quill/packages/charts/src/core/types.ts+++ b/packages/quill/packages/charts/src/core/types.ts@@ -513,8 +513,15 @@ export interface BarChartConfig extends ChartConfig {legend?: ChartLegendConfig}+export interface TimeScale {+ parse: (label: string) => number+ domain: readonly [number, number]+}+export interface LineChartConfig extends ChartConfig {percentStackView?: boolean+ /** Place each label at its time instead of evenly by index. Labels must be ascending. Memoize it. */+ timeScale?: TimeScale/** Value-axis domain control — omit for data-derived auto-scaling. See {@link ValueDomain}. */valueDomain?: ValueDomain/** Float the value axis to its data range instead of clamping the baseline to 0 (a y-axis "startdiff --git a/packages/quill/packages/charts/src/docs/axes.md b/packages/quill/packages/charts/src/docs/axes.mdindex f881746449be..3b8538ced5ae 100644--- a/packages/quill/packages/charts/src/docs/axes.md+++ b/packages/quill/packages/charts/src/docs/axes.md@@ -29,6 +29,7 @@ Theme-side restyle knobs, all optional: `theme.axisLineColor` strokes the baseli- Labels must be unique. The x-scale keys positions off the strings, so a duplicate collapses onto the first occurrence and draws the series backwards. On time-series charts pass ISO date strings, never formatted display labels that repeat across years. Set `xAxis.timezone` to format ticks and tooltip headers. The library infers the interval from `allDays` or chart labels; set `interval` only to override it. `tickFormatter` overrides automatic formatting.- `xAxis.tickLabelRotation` (`-45` tilts left) fixes the rotation, clamped to `-90..90`. Omit it to keep horizontal labels and the collision behavior.- `maxCategoryLabelWidth` truncates category labels with an ellipsis and reveals the full value on hover. It also clamps the axis margin, so a long label cannot push the plot off screen. On horizontal charts the cap grows to 30% of the chart width when that is wider, so a wider chart shows more of each label. `MAX_CATEGORY_LABEL_WIDTH` is the exported default.+- `LineChart` `timeScale: { parse, domain }` places each label at its time instead of evenly by index. `parse` returns epoch milliseconds, and labels outside `domain` are not drawn. Memoize the object.## Y-axis formatdiff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.tsindex 3e5eefc901d1..97881db1b090 100644--- a/packages/quill/packages/charts/src/index.ts+++ b/packages/quill/packages/charts/src/index.ts@@ -191,6 +191,7 @@ export type {ResolveValueFn,Series,SeriesType,+ TimeScale,TooltipConfig,TooltipContext,ValueDomain,