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(charts): TrendLineOverlay — render regression lines on bar and combo charts (#67460)

Sam Penningtonb2e78789d370
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 39098ab12919..3c974c0ca304 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -984,6 +984,14 @@ snapshots:
hash: v1.k794b7964.f31f9a8bb858f1f542af4827a48b492fa0f62cd11daa993aabebdc9156fd528f._DmTPhCruyEl58wgr9pVArJRi2ds943ecjz-HcSwIdM
components-hogcharts-timeserieslinechart--y-axis-formats--light:
hash: v1.k794b7964.65d0d72c9327811583c55b46b021e1c34efa1c6d2fc2674d33dfdc8651dab943.-c90yY4PLBsCcqqmkYHYJDk_5sYGpYrLtEh_cEct5Ks
+ components-hogcharts-trendlineoverlay--single-series-with-trend--dark:
+ hash: v1.k794b7964.51179b990377cde12b4612baca64ac4b7525026c7f7902488e3d06e3fe047749.daCovoZzwrYU-QrbbqhFXiTV8ENdnC7keeJMvmoXPx8
+ components-hogcharts-trendlineoverlay--single-series-with-trend--light:
+ hash: v1.k794b7964.a7e2d9a9e1fd980cdd2ceaa8648aa6a6cbee2f0f497b9a5c4c47bb16324497de.qJ2lhi4r7IwXLVFgiPg1eKmp2g19SsftN0x3Lkny214
+ components-hogcharts-trendlineoverlay--stacked-with-trend-lines--dark:
+ hash: v1.k794b7964.d81ab93e253944ac58886226126ab4d953c264d897eddf4d94f5920d31128df8.zvxMqWymA6KenI3hWdco1Rt_RcSKjc1MEVHs12lIESI
+ components-hogcharts-trendlineoverlay--stacked-with-trend-lines--light:
+ hash: v1.k794b7964.6958e0487548b55d83678ebe52e01de21e632f28a19e4202db1202d3941784ad.1zzu33H6icWlT3QvLHlx7bN6BRdNZPW9WycRhVEyOP0
components-hogcharts-valuelabels--cross-series-overlap-removal--dark:
hash: v1.k794b7964.751cf324e4f021ebcfcea0c4c4785286fa8fc4968cb3c2affb4f5de5b3fc203e.hurpyvfhzw2rOGvsu6krXkc8C_gg4NjQMAHC9nmqHUE
components-hogcharts-valuelabels--cross-series-overlap-removal--light:
@@ -5615,7 +5623,7 @@ snapshots:
scenes-app-inbox-scene--inbox--dark:
hash: v1.k794b7964.eae93d2c506e66eb23f36e19f05bf6f07286d9a895dbad8f970c009fd98f1d53.AqLzv_So4UaxCTEYyb-ZB24M8Z4KF2Zq8PyO-8FDfos
scenes-app-inbox-scene--inbox--light:
- hash: v1.k794b7964.5c8f64d4038a66ddb48273508b811bdd76582bab51968ea8716c69c6b621a2dd.EBQKvx3RssFEMQceajW5B6iDk7y73GySolK6L5vrnlo
+ hash: v1.k794b7964.88e28c4041b75b5ec02df0ad87e73d6cd2b1274781a7f47181eed609a5f9d4c1.i7mKwerSXPALau25BeHD_X-Xo7-MsOSIzkx3a2FJfaA
scenes-app-inbox-scene--self-driving-onboarding--dark:
hash: v1.k794b7964.0730c341122d1d593f4e6acf7a176e05bdd79e9ca6bf5f785a909fd57ad274f1.qRvNaIt3BFQkYn9JRfSKCXUScoTY331T7aAtb5jHXsk
scenes-app-inbox-scene--self-driving-onboarding--light:
@@ -6793,25 +6801,25 @@ snapshots:
scenes-app-tasks--empty--light:
hash: v1.k794b7964.0f6cd8ff0b64d8ab73e1b52609e2d6f87831dad09bc8cef9e70cb1ad02721572.S-jlFvTMeb5xsf9f91lZsEXJikHQglCzmPq-dtm5U4g
scenes-app-tasks--list-load-error--dark:
- hash: v1.k794b7964.368745fe9fffe686e48055d5bcb845f1a237f9983c75075693c163ff7633d142.pstQDOZm19Cp-gF_HAIj_5i21EL3ZUNyjn0WexIcQbQ
+ hash: v1.k794b7964.9566449737abdd51fde7d6056dc2aba9dfbc52df4e7d9ec026971e82adab1bfa.9mb2jTWhyqCPIfIPMjs6zvJegIBX1y5G9ArWSVOQFo4
scenes-app-tasks--list-load-error--light:
- hash: v1.k794b7964.58b8418673007af44903c9848fb32f761bfdb496d53ff17c3730195aa46a7bf0.fZTJvXJYQgnGQ7BFZ8Dp-FoCR_TCPs8CawhyPcTnXmk
+ hash: v1.k794b7964.6206b9e3ba160ae9e49dd71ce75498ce51f900728b362140b02b15d4c75391fa.ApdMVwb1IsI_tfNk_a10Btf7Zm0LfVFFEFQtEGAkexg
scenes-app-tasks--list-with-composer--dark:
- hash: v1.k794b7964.bf8b6abf4b61c5a5a753a4a4b65a68a826083843c72ce5c84874a5f8b1a351f0.8_E1dRIEkR4aBflwi38DbZ24Bb-O8JlxNhV7r0ftFCM
+ hash: v1.k794b7964.ff98c916a8383d1a3db3d0b030e52b2bab714a41079e9d7d850d30f7232c03bf.2F3aP-7dlnPEOtrnABy8WmXw1V89hzYyWsru0kQox2c
scenes-app-tasks--list-with-composer--light:
- hash: v1.k794b7964.645d8fb5c766ad02d84cde4622a5bbe7234addd10bcc9ee7c228cd522fc44527.LY9de-ZX-ogFSxm5PbmeU4XHXNOlvoXQoxXCHUqszVM
+ hash: v1.k794b7964.60972cd63c5c83da427e4b0743611c5d177ad985e8a08545808b4742ea960fbd.qwyV74M2FYn04RKZc6vNzqYCchdX_0stBFjGdfvI8Lg
scenes-app-tasks--loading--dark:
- hash: v1.k794b7964.3341ca85b5e619070d96ca158c9ae1b7d9021e87bf54959861e8415d4abefc7a.h7Khw0d4gSHdl6BS0te0J8gJCRgB7f4Zm17DmEg3MC8
+ hash: v1.k794b7964.69ddc531a9bf89b2b8ce29129535d0620558ec64b185f8e9d7db92f9736382d3.vUeBrUbNn9khUb2I-gcmXW5XdrRPbdMFFJ5LHeEEjTQ
scenes-app-tasks--loading--light:
- hash: v1.k794b7964.368255ea27ffc7a362b0d6bbbefe85ea3f4fd4ed95b8092a90091087d62bd364.wbuwRgxSpLuh0CPLFt-KtqSXz7zLS1i4OeyR0MqY3xY
+ hash: v1.k794b7964.145588aca6bc14073df42b8b3789d46a195bc613e2363deef3f94082dd2f4979._C5LoopHdD4uoMtdsJntgYT_nzwvbKDjTnKqR1EOQtM
scenes-app-tasks--mobile-list--dark:
hash: v1.k794b7964.e65c5e289cbb347ed1cc035d3a381c56503b67ef643db47dd2e02f32fac047a8.aNQOxj2nwQyFuzC8E3a1YGPFtaxje7hw1Eb7HbBLyfQ
scenes-app-tasks--mobile-list--light:
hash: v1.k794b7964.a42e7297c99d46bf03e8ba9c7576b164e120a41c914d1d52824823140b8fae92.nCFkmftkVPQYI7UqGBF84D6YQ52LTeSiWkz6w_K_YWM
scenes-app-tasks--mobile-new-task--dark:
- hash: v1.k794b7964.de22e10e282dd787afc1fc4784d1aef6064b32b7c3bed6b3bced8ba776264cf2.UCqKfpWcRlmvwmvML2DjdyVQCwj3zUZpXlKA8wxMgVs
+ hash: v1.k794b7964.04a9d2be080fb6586920169a05f14d1ee3fecab3a7bff2b54991540eeda24903.i5EHYx6N-QK-ooccoLVdyP0zpRT4Y7amJnLbP-6kXNg
scenes-app-tasks--mobile-new-task--light:
- hash: v1.k794b7964.cf669044c3c0e2b6d870e588a22f58be3032bec6d90a2c1c3b1ee1412a491661.3mNJ_P0G8pSfhi3oEkjsTKKG7wVSFB9jdY7ujjDXj7k
+ hash: v1.k794b7964.365b32bd25aaa19ef2b7e35db06b67fe57d09ce1f39890b4201080345cbc4fb3.CuVZNBxkDEtv9uVsE3Q1hQslA4Tqdut3NuB3xzATMYM
scenes-app-tasks--mobile-task-selected--dark:
hash: v1.k794b7964.7a885468ce6eee10b0835ef0b76f5c5dd45d35d90273d972bcb8023d9c943b62.4O4SeGjvj3rHSH0F5LinWCoJv7oGd0UgG39TRxQQeEo
scenes-app-tasks--mobile-task-selected--light:
@@ -6821,9 +6829,9 @@ snapshots:
scenes-app-tasks--new-task--light:
hash: v1.k794b7964.25133a1f325d13995ce3308d3373d31db214be56bc0ba1a7165f1351cc57463f.rw15Q9WFmYC5WA1DkSKApJMz0Zf0VmfsPXZilsqqZuw
scenes-app-tasks--new-task-with-repository--dark:
- hash: v1.k794b7964.007045013ea7ca323a854ac898f357959215851601122652edd8b66f5522b748.FCfJRPZKDXGgNO5QthA84KFRTui_bwjO2sF69KQTeqQ
+ hash: v1.k794b7964.0b91a374f31195a572e4dc9ba06538fb24aa469715053646c59d6dcf55ce9d0a.mPiBMxgeYR2VFvWiyCVIqAffHpa1eWlmq1j6CelnInM
scenes-app-tasks--new-task-with-repository--light:
- hash: v1.k794b7964.85b8d80bed5a3f681769896383446146a143df4724ecf1e1feda295fd3e9a0ee.-nwx_seZR7tyvrewZFbxcgGWYpGxPSVR-xiSBkE0UaI
+ hash: v1.k794b7964.5e2f1107fe1ffce2d4c0189c839624e05c0c5df50011769bac86eb17e9476422.EUn4T_Fj1IbtANyMVPjdzJiKLWfZmI4Yoz2bnzPVdhU
scenes-app-tasks--task-detail-loading--dark:
hash: v1.k794b7964.a05d0af03f7eaeb33e1c22ccae2d417241ef3cb997cb4675ac5f8efe701a7c74.Fn6G0_Zzcycs9ikkn7R1jXhXk0czUQGbcdU0X58F8Jo
scenes-app-tasks--task-detail-loading--light:
@@ -6973,9 +6981,9 @@ snapshots:
scenes-other-billing--billing-purchase-credits-modal--light:
hash: v1.k794b7964.b5764f97504ff981a389efeec44dd4d86929f243fa3b99ab0516eb4bcddac2ad.k8EFOT3n4tKgKEC5-ciAKGmKQX4emuSKvVCOkG8TU7g
scenes-other-billing--billing-unsubscribe-modal--dark:
- hash: v1.k794b7964.4485466b38421f57e913dee9aa38bdec44e2a4545ab87c5e84e25116cc0024df.mEoCNNs0aT_srYooDJg4pKAUNjcSdbvYyvhkdpeh2uc
+ hash: v1.k794b7964.7ea59c3b121732aad1f8ad5ec5f33eed306dfcd0c992b515541d6daddc9d5661.hHqqTxmzBhip204qeGiGjJz_2goglvSA5UlYGkbE2BY
scenes-other-billing--billing-unsubscribe-modal--light:
- hash: v1.k794b7964.a2bfac76f992d3b0bac3fb6f08c8039f6011ad028c4f41e9001ccdec5e31636d.yq8TXP2L8KHkon4UwKHGYPPeCwbZzZhkYqJDc2N8xss
+ hash: v1.k794b7964.f428982e8db3a7c8211c24350c1961614de906b6c0792e126f5a36adb7657fe5.lrIEyvhewbhXyW2rGHoJ9wtQ7vLk79vezl8Gd9IUsBI
scenes-other-billing--billing-with-credit-cta--dark:
hash: v1.k794b7964.959bdf4d047f8c5f1af0453848d5632b2dfcaaab80fe6d9cb3aa58dcb08fe760.vLS-1KEmdcBoEcV4l87e7jlR2VMAMvykgIITrkvqLCM
scenes-other-billing--billing-with-credit-cta--light:
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 8e4fccdfd52f..a91afe797ef8 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -66,10 +66,11 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
</TimeSeriesLineChart>
```
-- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`) compose as children.
+- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`, `TrendLineOverlay`) compose as children.
- `DefaultTooltip` (the built-in tooltip, also usable from a custom `tooltip` render prop) takes optional `valueFormatter`, `labelFormatter`, `labelRenderer`, `showHeader`, `showTotal`, `totalLabel`, `totalFormatter`, `sortedByValue`, `hideZeroRows`, `onRowClick`, and `footer`. `valueFormatter` gets `(value, entry)` — the row's `seriesData` entry as a second arg — so each row can format with its own `series.meta` (e.g. per-column currency/duration); it may return a node, not just a string (e.g. a property-formatted value). `labelFormatter` transforms the raw x-axis label shown in the tooltip header (e.g. convert an ISO datetime string to "Jun 24, 10:00"). `labelRenderer` overrides how each row's label renders (defaults to the series label) — use for richer labels than a plain string, e.g. breakdown-value pills. `showHeader` (default true) toggles the header label row — pass false for charts without a meaningful header (pie slices, aggregated single-column bars). `showTotal` appends a footer row summing the visible series; it excludes `overlay` series (goal lines) from the sum and is suppressed when fewer than two summable series remain. `totalFormatter` formats the total (defaults to `valueFormatter` applied with the first summable row's entry); `totalLabel` defaults to `'Total'`. `sortedByValue` sorts rows by value descending so the highest value appears first. `hideZeroRows` drops rows whose value is exactly `0` (e.g. lifecycle statuses absent for a period), so the tooltip lists only series with data at the hovered point. `onRowClick` makes each series row clickable (firing with the row's `seriesData` entry) — the tooltip must be pinned for clicks to land, since an unpinned tooltip is `pointer-events: none`; use it to open a per-series drill-down (e.g. the persons modal). `footer` renders arbitrary content below all rows (with a divider) — useful for "click to inspect" hints. A formatter taking only `value` stays compatible — the extra arg is ignored.
- To tune the built-in tooltip **without writing a render prop**, put those same fields on `config.tooltip` (`{ enabled, pinnable, placement, valueFormatter, labelFormatter, showTotal, totalLabel, totalFormatter, sortedByValue }`). When no `tooltip` render prop is supplied, the chart renders `DefaultTooltip` with them applied; a render prop, if given, owns content entirely and these are ignored. Prefer config for "format each row / add a total" cases (e.g. SQL insights pass per-column formatters this way) and reach for the render prop only for genuinely custom tooltip markup (e.g. adding a `footer` hint).
- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).
+- `TrendLineOverlay` renders linear/exponential regression lines as SVG polylines on vertical bar and combo charts. Use via `trendLines?: TrendLineConfig[]` in `TimeSeriesBarChartConfig` or `TimeSeriesComboChartConfig` — the chart computes the derived series via `buildTrendLineSeries` and passes them to the overlay as a child. Only works for `axisOrientation: 'vertical'`; returns null on horizontal charts. Legend-toggled-off series are filtered automatically.
- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original. `context.bandValues` is the stack's values at this index and `context.previousBandValues` the same for the preceding index (empty at the first), so a formatter can compute a segment's share of the current or the previous band (e.g. period-over-period).
- Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `SlopeChart`) takes a `config.legend: ChartLegendConfig` (`{ show, position, align, gap, interactive, hiddenKeys, onToggleSeries, renderItem }`). With `show: true` the chart renders a built-in legend that, by default (`interactive`), is click-to-toggle: clicking a row hides that series (no draw, no scale contribution, no tooltip — the axes rescale into the freed space) while the row stays listed but dimmed so it can be restored. The chart owns the toggled-off state (uncontrolled); set `interactive: false` for a static legend, or pass `hiddenKeys` + `onToggleSeries` to control it yourself. Hidden by default. `config.legend.renderItem(defaultNode, item)` wraps each rendered row, so consumers can augment it (e.g. attach a right-click context menu) while keeping the default swatch/label/toggle rendering — return `defaultNode` to leave a row untouched. Toggling on time-series charts lists the user's series only (not derived trend lines / CI bands) — and hiding a series also hides everything derived from it (its CI band, moving average, and trend line), so no orphaned overlay floats over the gap.
- `Legend` (and `ChartLegend` for layout) is the lower-level presentational primitive: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. Use it directly when the built-in `config.legend` can't express what you need (custom item order/labels). `useChartLegend(series, theme, config, items?)` is the shared hook the charts use — returns `visibleSeries` (hidden applied as `visibility.excluded`) plus `legendProps` to spread onto `<ChartLegend>`; `applyHiddenSeries` is the underlying helper. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change). Long labels clip to a max width with an ellipsis and expose the full text via a native `title` tooltip on hover. The legend slot in `ChartLegendLayout` is bounded and scrolls (a top/bottom legend caps at ~40% of the chart height so the plot keeps the majority; a left/right legend stretches to full chart height and caps at ~45% width), so a many-series legend scrolls instead of squeezing or stretching the chart. A left/right legend uses `align-self: stretch` (resolves against the container's used height, so it works even when no ancestor sets an explicit `height`). The top/bottom `max-height: 40%` cap is a percentage, so it only resolves when the chart container has an **explicit** `height` — a flex-derived used size (e.g. `flex: 1` with only `min-height`/`max-height`) does **not** count and the cap silently no-ops; pin a real `height` on the container.
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index 70e37d4a3acf..e4e88037cf7b 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -13,6 +13,7 @@ import type {
TooltipContext,
} from '../../core/types'
import { ReferenceLines } from '../../overlays/ReferenceLine'
+import { TrendLineOverlay } from '../../overlays/TrendLineOverlay'
import { ValueLabels } from '../../overlays/ValueLabels'
import { buildGoalLineReferenceLines, goalLineValueDomain, type GoalLineConfig } from '../../utils/goal-lines'
import {
@@ -22,6 +23,7 @@ import {
type YAxisConfig,
} from '../../utils/use-axis-formatters'
import { BarChart } from '../BarChart/BarChart'
+import { buildTrendLineSeries, type TrendLineConfig } from '../TimeSeriesLineChart/utils/derived-series'
import {
resolveValueLabelsConfig,
useSeriesWithValueLabelAllowlist,
@@ -53,6 +55,8 @@ export interface TimeSeriesBarChartConfig {
animateHover?: boolean | number
/** Built-in legend with click-to-toggle series visibility. Hidden by default. */
legend?: ChartLegendConfig
+ /** Linear or exponential trend line overlays — rendered as SVG lines on top of the bars. */
+ trendLines?: TrendLineConfig[]
}
export interface TimeSeriesBarChartProps<Meta = unknown> {
@@ -95,6 +99,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
fillStyle,
animateHover,
legend,
+ trendLines,
} = config ?? {}
const xTickFormatter = useXTickFormatter(xAxis, labels)
const yTickFormatter = useYTickFormatter(yAxis)
@@ -118,6 +123,19 @@ export function TimeSeriesBarChart<Meta = unknown>({
// object stays referentially stable and doesn't re-trigger scale recomputation each render.
const valueDomain = useMemo(() => goalLineValueDomain(referenceLines), [referenceLines])
+ const trendSeries = useMemo(() => {
+ if (!trendLines?.length) {
+ return []
+ }
+ const byKey = new Map(visibleSeries.map((s) => [s.key, s]))
+ return trendLines.flatMap((tl) => {
+ const source = byKey.get(tl.seriesKey)
+ return source
+ ? [buildTrendLineSeries({ sourceSeries: source, kind: tl.kind, label: tl.label, fitUpTo: tl.fitUpTo, excluded: source.visibility?.excluded })]
+ : []
+ })
+ }, [trendLines, visibleSeries])
+
const barChartConfig: BarChartConfig = {
yScaleType: yAxis?.scale,
xTickFormatter,
@@ -155,6 +173,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
onError={onError}
>
{referenceLines.length > 0 && <ReferenceLines lines={referenceLines} />}
+ {trendSeries.length > 0 && <TrendLineOverlay trendSeries={trendSeries} />}
{valueLabelsConfig && <ValueLabels valueFormatter={valueLabelFormatter} />}
{children}
</BarChart>
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
index 50439edf8584..70d159f7fb95 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
@@ -13,6 +13,7 @@ import type {
TooltipContext,
} from '../../core/types'
import { ReferenceLines } from '../../overlays/ReferenceLine'
+import { TrendLineOverlay } from '../../overlays/TrendLineOverlay'
import { ValueLabels } from '../../overlays/ValueLabels'
import { buildGoalLineReferenceLines, goalLineValueDomain, type GoalLineConfig } from '../../utils/goal-lines'
import {
@@ -22,6 +23,7 @@ import {
type YAxisConfig,
} from '../../utils/use-axis-formatters'
import { ComboChart } from '../ComboChart/ComboChart'
+import { buildTrendLineSeries, type TrendLineConfig } from '../TimeSeriesLineChart/utils/derived-series'
import {
resolveValueLabelsConfig,
useSeriesWithValueLabelAllowlist,
@@ -48,6 +50,8 @@ export interface TimeSeriesComboChartConfig {
tooltip?: TooltipConfig
/** Built-in legend with click-to-toggle series visibility. Hidden by default. */
legend?: ChartLegendConfig
+ /** Trend line overlays rendered as SVG lines on top of the chart. */
+ trendLines?: TrendLineConfig[]
}
export interface TimeSeriesComboChartProps<Meta = unknown> {
@@ -90,6 +94,7 @@ export function TimeSeriesComboChart<Meta = unknown>({
showAxisLines,
tooltip: tooltipConfig,
legend,
+ trendLines,
} = config ?? {}
const xTickFormatter = useXTickFormatter(xAxis, labels)
const yTickFormatter = useYTickFormatter(yAxis)
@@ -111,6 +116,19 @@ export function TimeSeriesComboChart<Meta = unknown>({
// object stays referentially stable and doesn't re-trigger scale recomputation each render.
const valueDomain = useMemo(() => goalLineValueDomain(referenceLines), [referenceLines])
+ const trendSeries = useMemo(() => {
+ if (!trendLines?.length) {
+ return []
+ }
+ const byKey = new Map(visibleSeries.map((s) => [s.key, s]))
+ return trendLines.flatMap((tl) => {
+ const source = byKey.get(tl.seriesKey)
+ return source
+ ? [buildTrendLineSeries({ sourceSeries: source, kind: tl.kind, label: tl.label, fitUpTo: tl.fitUpTo, excluded: source.visibility?.excluded })]
+ : []
+ })
+ }, [trendLines, visibleSeries])
+
const comboChartConfig: ComboChartConfig = {
yScaleType: yAxis?.scale,
xTickFormatter,
@@ -143,6 +161,7 @@ export function TimeSeriesComboChart<Meta = unknown>({
onError={onError}
>
{referenceLines.length > 0 && <ReferenceLines lines={referenceLines} />}
+ {trendSeries.length > 0 && <TrendLineOverlay trendSeries={trendSeries} />}
{valueLabelsConfig && <ValueLabels valueFormatter={valueLabelFormatter} />}
{children}
</ComboChart>
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.ts b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.ts
index 8905279a8ac2..8e133dafd8a9 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.ts
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/utils/derived-series.ts
@@ -2,6 +2,8 @@ import type { Series } from '../../../core/types'
import { dimHex } from '../../../utils/comparison-dimming'
import { linearRegression, movingAverage, trendLine } from '../../../utils/statistics'
+export type { TrendLineConfig } from './use-derived-series'
+
const TREND_LINE_DIM_OPACITY = 0.5
const CI_FILL_OPACITY = 0.2
const MA_DASH_PATTERN = [10, 3]
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
index b0b7def8d576..eb82c2d8a38b 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
@@ -234,6 +234,7 @@ export function useChartInteraction<Meta = unknown>({
interactionAxis,
setHover,
setTooltipCtx,
+ resolveBottomValue,
]
)
diff --git a/packages/quill/packages/charts/src/overlays/TrendLineOverlay.stories.tsx b/packages/quill/packages/charts/src/overlays/TrendLineOverlay.stories.tsx
new file mode 100644
index 000000000000..977b4c392eda
--- /dev/null
+++ b/packages/quill/packages/charts/src/overlays/TrendLineOverlay.stories.tsx
@@ -0,0 +1,68 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { TimeSeriesBarChart } from '../charts/TimeSeriesBarChart/TimeSeriesBarChart'
+import type { Series } from '../core/types'
+import { Stage, useReactiveTheme } from '../story-helpers'
+
+const LABELS = ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06']
+
+const meta: Meta = {
+ title: 'Components/HogCharts/TrendLineOverlay',
+ parameters: { layout: 'centered' },
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+/** Single bar series with an upward linear trend line rendered as an SVG overlay. */
+export const SingleSeriesWithTrend: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const series: Series[] = [
+ { key: 'revenue', label: 'Revenue', color: '#7c3aed', data: [120, 180, 150, 220, 200, 260] },
+ ]
+ return (
+ <Stage>
+ <TimeSeriesBarChart
+ series={series}
+ labels={LABELS}
+ theme={theme}
+ config={{
+ barLayout: 'grouped',
+ yAxis: { showGrid: true },
+ trendLines: [{ seriesKey: 'revenue', kind: 'linear' }],
+ }}
+ />
+ </Stage>
+ )
+ },
+}
+
+/** Two stacked series each with their own trend line — trend lines respect series colour and are
+ * clipped to the plot area. */
+export const StackedWithTrendLines: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const series: Series[] = [
+ { key: 'a', label: 'Product A', color: '#059669', data: [80, 100, 90, 130, 110, 150] },
+ { key: 'b', label: 'Product B', color: '#db2777', data: [40, 60, 70, 90, 80, 110] },
+ ]
+ return (
+ <Stage>
+ <TimeSeriesBarChart
+ series={series}
+ labels={LABELS}
+ theme={theme}
+ config={{
+ barLayout: 'stacked',
+ yAxis: { showGrid: true },
+ trendLines: [
+ { seriesKey: 'a', kind: 'linear' },
+ { seriesKey: 'b', kind: 'linear' },
+ ],
+ }}
+ />
+ </Stage>
+ )
+ },
+}
diff --git a/packages/quill/packages/charts/src/overlays/TrendLineOverlay.test.tsx b/packages/quill/packages/charts/src/overlays/TrendLineOverlay.test.tsx
new file mode 100644
index 000000000000..9e06e268f7ca
--- /dev/null
+++ b/packages/quill/packages/charts/src/overlays/TrendLineOverlay.test.tsx
@@ -0,0 +1,85 @@
+import { cleanup } from '@testing-library/react'
+
+import type { Series } from '../core/types'
+import { makeOverlayContext, renderOverlayInChart } from '../testing'
+import { TrendLineOverlay } from './TrendLineOverlay'
+
+const DIMENSIONS = {
+ width: 600,
+ height: 300,
+ plotLeft: 40,
+ plotTop: 10,
+ plotWidth: 520,
+ plotHeight: 260,
+}
+
+// Linear y-scale: 0 -> 270 (bottom), 100 -> 10 (top)
+const yScale = (v: number): number => 270 - (v / 100) * 260
+// Linear x-scale: labels map to evenly spaced x positions
+const xScale = (label: string): number => {
+ const idx = ['A', 'B', 'C'].indexOf(label)
+ return 40 + idx * 200
+}
+
+const baseContext = makeOverlayContext(
+ { x: xScale, y: yScale, yTicks: () => [0, 50, 100] },
+ { dimensions: DIMENSIONS, labels: ['A', 'B', 'C'] }
+)
+
+const horizontalContext = makeOverlayContext(
+ { x: xScale, y: yScale, yTicks: () => [] },
+ { dimensions: DIMENSIONS, labels: ['A', 'B', 'C'], axisOrientation: 'horizontal' }
+)
+
+const makeSeries = (key: string, data: number[], excluded = false): Series => ({
+ key,
+ label: key,
+ data,
+ color: '#7c3aed',
+ stroke: { pattern: [6, 4] as [number, number] },
+ visibility: excluded ? ({ excluded: true } as const) : undefined,
+})
+
+afterEach(cleanup)
+
+describe('TrendLineOverlay', () => {
+ it('returns null when trendSeries is empty', () => {
+ const { container } = renderOverlayInChart(<TrendLineOverlay trendSeries={[]} />, baseContext)
+ expect(container.querySelector('svg')).toBeNull()
+ })
+
+ it('returns null for horizontal bar charts', () => {
+ const series = [makeSeries('a', [10, 50, 90])]
+ const { container } = renderOverlayInChart(<TrendLineOverlay trendSeries={series} />, horizontalContext)
+ expect(container.querySelector('svg')).toBeNull()
+ })
+
+ it('filters out excluded series', () => {
+ const series = [makeSeries('visible', [10, 50, 90]), makeSeries('hidden', [5, 25, 45], true)]
+ const { container } = renderOverlayInChart(<TrendLineOverlay trendSeries={series} />, baseContext)
+ const polylines = container.querySelectorAll('polyline')
+ expect(polylines).toHaveLength(1)
+ })
+
+ it('renders one SVG polyline per visible series', () => {
+ const series = [makeSeries('a', [10, 50, 90]), makeSeries('b', [90, 50, 10])]
+ const { container } = renderOverlayInChart(<TrendLineOverlay trendSeries={series} />, baseContext)
+ expect(container.querySelector('svg')).not.toBeNull()
+ expect(container.querySelectorAll('polyline')).toHaveLength(2)
+ })
+
+ it('uses the series stroke pattern as the SVG dash array', () => {
+ const series = [makeSeries('a', [10, 50, 90])]
+ const { container } = renderOverlayInChart(<TrendLineOverlay trendSeries={series} />, baseContext)
+ const polyline = container.querySelector('polyline')
+ expect(polyline?.getAttribute('stroke-dasharray')).toBe('6,4')
+ })
+
+ it('renders a non-interactive SVG overlay', () => {
+ const series = [makeSeries('a', [10, 50, 90])]
+ const { container } = renderOverlayInChart(<TrendLineOverlay trendSeries={series} />, baseContext)
+ const svg = container.querySelector('svg')
+ expect(svg).not.toBeNull()
+ expect(svg?.style.pointerEvents).toBe('none')
+ })
+})
diff --git a/packages/quill/packages/charts/src/overlays/TrendLineOverlay.tsx b/packages/quill/packages/charts/src/overlays/TrendLineOverlay.tsx
new file mode 100644
index 000000000000..ceec1778ba5a
--- /dev/null
+++ b/packages/quill/packages/charts/src/overlays/TrendLineOverlay.tsx
@@ -0,0 +1,83 @@
+/* eslint-disable react/forbid-dom-props -- dynamic pixel positions from d3 scales */
+import React, { useMemo } from 'react'
+
+import type { Series } from '../core/types'
+import { useChartLayout } from '../core/chart-context'
+import { resolveYScaleForSeries } from '../core/scales'
+
+interface TrendLineOverlayProps {
+ /** Pre-computed trend line series (from buildTrendLineSeries). One per source series. */
+ trendSeries: Series[]
+}
+
+/** Renders trend lines as SVG polylines over vertical bar and combo charts. */
+export function TrendLineOverlay({ trendSeries }: TrendLineOverlayProps): React.ReactElement | null {
+ const clipId = React.useId()
+ const { scales, dimensions, labels, axis } = useChartLayout()
+ const { plotLeft, plotTop, plotWidth, plotHeight, width, height } = dimensions
+
+ const lines = useMemo(() => {
+ if (axis.orientation === 'horizontal') {
+ return []
+ }
+ return trendSeries
+ .filter((s) => !s.visibility?.excluded)
+ .map((s) => {
+ const yScale = resolveYScaleForSeries(scales, s)
+ const points: string[] = []
+ for (let i = 0; i < labels.length; i++) {
+ const rawY = s.data[i]
+ if (rawY == null || !isFinite(rawY)) {
+ continue
+ }
+ const x = scales.x(labels[i])
+ const y = yScale(rawY as number)
+ if (x == null || !isFinite(x) || !isFinite(y)) {
+ continue
+ }
+ points.push(`${x},${y}`)
+ }
+ if (points.length < 2) {
+ return null
+ }
+ const dashArray = s.stroke?.pattern ? s.stroke.pattern.join(',') : '6,4'
+ return { key: s.key, points: points.join(' '), color: s.color ?? 'currentColor', dashArray }
+ })
+ .filter((l): l is NonNullable<typeof l> => l !== null)
+ }, [trendSeries, scales, labels, axis.orientation])
+
+ if (lines.length === 0) {
+ return null
+ }
+
+ return (
+ <svg
+ style={{
+ position: 'absolute',
+ left: 0,
+ top: 0,
+ width,
+ height,
+ pointerEvents: 'none',
+ overflow: 'visible',
+ }}
+ >
+ <clipPath id={clipId}>
+ <rect x={plotLeft} y={plotTop} width={plotWidth} height={plotHeight} />
+ </clipPath>
+ <g clipPath={`url(#${clipId})`}>
+ {lines.map(({ key, points, color, dashArray }) => (
+ <polyline
+ key={key}
+ points={points}
+ fill="none"
+ stroke={color}
+ strokeWidth={2}
+ strokeDasharray={dashArray}
+ strokeLinecap="round"
+ />
+ ))}
+ </g>
+ </svg>
+ )
+}