: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): add SlopeChart (slopegraph) to quill charts (#63442)
Paul D'Ambra4c572d85c269
diff --git a/.agents/skills/visualizing-change-over-time/SKILL.md b/.agents/skills/visualizing-change-over-time/SKILL.mdnew file mode 100644index 000000000000..41af5656b05d--- /dev/null+++ b/.agents/skills/visualizing-change-over-time/SKILL.md@@ -0,0 +1,89 @@+---+name: visualizing-change-over-time+description: >+ Helps PostHog engineers and agents pick the right chart when a request is about+ visualizing change over time, before/after comparisons, or period-over-period+ movement while building UI with @posthog/quill-charts (dashboards, reports, the+ mcp_analytics frontend, custom visualizations). Use when a user asks how something+ "changed", "moved", "grew", "dropped", "improved", or "regressed" between two+ points or periods, or mentions "before/after", "period over period", "week over+ week", "delta", "slope graph", "slopegraph", or comparing many series across two+ snapshots. Surfaces the SlopeChart as one of the options. Not for picking a native+ insight ChartDisplayType in the product analytics insight editor.+---++# Visualizing change over time++When a request is about **how something changed**, the default reach is a line/area+trend — and that is usually right for a continuous series with many x points. But for+some change-over-time shapes a different chart reads far better. This skill is the+menu to offer, including the **slope graph**, when building visualizations with+[`@posthog/quill-charts`](../../../packages/quill/packages/charts/AGENTS.md).++Present the fitting option(s) and let the user choose — none of these is mandatory.++## Pick by the shape of the change++| The change is… | Reach for | Why |+| ------------------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |+| A continuous series over many time points (a trend) | `TimeSeriesLineChart` / `LineChart` (area fill for emphasis) | The standard trend; the slope between every pair of points is visible. |+| **Two points only** (before → after) across **several series/categories** | **`SlopeChart`** | One line per entity from a left "before" to a right "after" — direction and magnitude of each entity's change, and rank flips, read at a glance. |+| Magnitude comparison at points in time (not the path between them) | `BarChart` / `TimeSeriesBarChart` | Bars compare discrete values; group/stack for sub-series. |+| A single headline number plus its change vs a prior period | `MetricCard` | Big number + sparkline + change pill. |++If the user is comparing exactly **two snapshots** (this week vs last, control vs+treatment, Q1 vs Q2) and especially when there are **many categories** whose+_relative_ movement matters, offer the slope graph as the cleaner alternative to a+grouped bar or a 2-point line chart.++## Using the SlopeChart++```tsx+import { SlopeChart } from '@posthog/quill-charts'+import type { Series } from '@posthog/quill-charts'+import type { SlopeSeriesMeta } from '@posthog/quill-charts'++// One series per entity; `data` is exactly [start, end].+const series: Series<SlopeSeriesMeta>[] = [+ { key: 'us', label: 'US', data: [120, 185] },+ { key: 'eu', label: 'EU', data: [200, 150] },+]++<SlopeChart+ series={series}+ labels={['Before', 'After']}+ theme={theme}+ config={{+ showSeriesLabels: true, // name beside each end point; steepest line always keeps its label+ legend: { show: true }, // each row shows the color, label, and the formatted change+ deltaFormatter: (d) => `${d >= 0 ? '+' : ''}${d}`,+ }}+/>+```++Key options (full list in the charts+[AGENTS.md](../../../packages/quill/packages/charts/AGENTS.md) "Composition" section):++- `showStartLabels` / `showEndLabels` — chart-level defaults for the value labels;+ override per series with `meta.showStartLabel` / `meta.showEndLabel`.+- `showSeriesLabels` — the name labels; on collision the series with the **largest+ change** (`|end − start|`) always keeps its label.+- `legend: { show, position }` — rows carry the per-series change (`deltaFormatter`).+- The value axis is hidden by default — the start/end labels are the readout.++The theme comes from `useChartTheme()`; give the wrapper a real height. See the+charts AGENTS.md for theme wiring and sizing.++## Scope note++`SlopeChart` is a charts-library component — use it for dashboards, reports, the+`mcp_analytics` frontend, and custom visualizations. It already backs the **Slope**+view toggle on Max's inline trends result card+(`services/mcp/src/ui-apps/components/TrendsVisualizer.tsx`). It is **not** yet a+native insight `ChartDisplayType`, so it does not appear in the product analytics+insight chart picker and cannot be created through the `posthog:insight-create` MCP+tool. If+a user wants the slope graph as a first-class, one-click insight display, that is a+larger change: add `ChartDisplayType.SlopeChart` in `frontend/src/types.ts`, a+picker entry in `ChartFilter.tsx` (gate behind a feature flag), and a rendering path+in the trends view — mirroring how `BoxPlot` was wired in.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 029f9d6d391d..d9c7cfe1c79e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -720,6 +720,34 @@ snapshots:hash: v1.k794b7964.4b506b7851221502ce2216904c24cd02eb0c0ba0246803cb03eba0b3aa7527f8.KgwI0xt24vENLyD4qQdys5oxf0eW8Its5x83gu7d2JQcomponents-hogcharts-referenceline--vertical-reference-lines--light:hash: v1.k794b7964.c87765d2d128e6ded9f0cc2d05c12bd629a5cece5ad3131e5a2be22854d7d0e2.zCVu9IzRzHylPMa2vBLFV3-OpsX8oj5Q1KsXXogMWHU+ components-hogcharts-slopechart--colliding-labels--dark:+ hash: v1.k794b7964.54eecd802dbf9af9410250822af66ef4638b8e6406b6f183990cead97100503a.cLTNaaQeA8MECQ7ny1SAnX1pF5SbA41jE814OjoBW-0+ components-hogcharts-slopechart--colliding-labels--light:+ hash: v1.k794b7964.23fecafce8865e1935e04e5c419969f0926b616fd0dae07858e3b36073420b52.6zoIHio6n0QTpUOqTJn0eR4jUCHpjm-wVZlz0gCu3zc+ components-hogcharts-slopechart--default--dark:+ hash: v1.k794b7964.f7a7ab10ea241c5fbe4b2eda64d68e8c3486b97c3c2377886eb774411b245458.7T0Vga1QklSHq4c6AVQjz7xaB7KaXnENYTgP6yczo_o+ components-hogcharts-slopechart--default--light:+ hash: v1.k794b7964.767c8b748b168ed3b5cc2f29304d021008daf84127b75cbd7c125f27a9a4ae1a.Uo_Ajb9L7xem1Kyi41a7splR7w_Jhtjdo2tRbNf5iHE+ components-hogcharts-slopechart--empty--dark:+ hash: v1.k794b7964.c5de55c471941eed34d689ba85f43a07017bf231e8bdc4ffca98521cdab3bcd0.l5q1XuFp9vcETkmULkBOR7oZw7Y-MbeQkyuOTkrMiyw+ components-hogcharts-slopechart--empty--light:+ hash: v1.k794b7964.8c60ac901acd4c646cd3d874b8de6bd6dffe3c0ba4e6a920e202198b2f467f4e.seAawuDJwtjwqqjlVkBrYMcqoTTUh3LzjO5-kf9JiJ8+ components-hogcharts-slopechart--legend-right--dark:+ hash: v1.k794b7964.5a3bd59b3c452187180052e9642e8f5b28fbee80eb37c147b326d9d886070cc4.ClqpcWz4o-XlMOOF9U5V6VHlURr6NnpmYhEhaAJ_HO8+ components-hogcharts-slopechart--legend-right--light:+ hash: v1.k794b7964.5a233a678501be3bf4f54fa44ef97196414210300837740680392c246d194d54.ht_NNhWf23OZP-zDPU3Y8Bja7XsKRxU-gHv_zaAJH50+ components-hogcharts-slopechart--per-series-value-labels--dark:+ hash: v1.k794b7964.4557a51b2830ba6075a6df79ec11666bbd4c18f3bae003837bb52217e28312b2.xsBWhDxGfGW38jCp84Vp7yXJsY0Cf0WYji0T6a_2boE+ components-hogcharts-slopechart--per-series-value-labels--light:+ hash: v1.k794b7964.91bdd8ac378a442e9bfb821dc7c846d63c7894153a7203870869d9e44190da98.HmocxpB-z7EEGbHJibGZHmMJ_MrPstSJzDYmNbcYuZg+ components-hogcharts-slopechart--with-legend--dark:+ hash: v1.k794b7964.61f2025b5f8e7c98e66281ee55d7b5438fe201303103300e1752e9fc580cd69d.fxOPAJFHGeuA_U51Aga833dTsaMUhIBrR-5FdooQdak+ components-hogcharts-slopechart--with-legend--light:+ hash: v1.k794b7964.2ac49159d1d695d5e03841ee4a21c7b0e85c9094f4550fffba63ba3cbfdcf2ef.vo_qrp156I2g-EvBd7-Ui1GftNtPsd_Z88sBV6P5jsA+ components-hogcharts-slopechart--without-series-labels--dark:+ hash: v1.k794b7964.497f0d0a8a9f172ed6c3c7f98cdf452406533753e18a2d3e8abdbc631fcc9d8b.bYusSAhxD_HP_WrOCd56aDLZtC7tGwWNf14maiRugFc+ components-hogcharts-slopechart--without-series-labels--light:+ hash: v1.k794b7964.5f4ed4bd2e8b76a9146d4cec772a9dec098f1d101bbfff9eb7c2de542807ee36.B4F1sc0cdH3SMp-rPFHfd4VnivUHhH2neom0RghB0Ngcomponents-hogcharts-sparkline--custom-color--dark:hash: v1.k794b7964.9a599ca7e855408c1bda17c3b9094b60c333249c9df7d14d0be865a4f9fb424d.EFS4alrXA5COnCpJYXUfVxFvJd4GWClskV2utoqKWtEcomponents-hogcharts-sparkline--custom-color--light:diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.mdindex 32cc29ca1c3d..175bbd1273b6 100644--- a/packages/quill/packages/charts/AGENTS.md+++ b/packages/quill/packages/charts/AGENTS.md@@ -14,6 +14,7 @@ Quick-reference for AI agents using `@posthog/quill-charts`. Canvas-rendered cha| BoxPlot | Distribution summaries — `{ min, p25, median, mean, p75, max }` per label || Sparkline | Tiny inline trend from a flat `number[]` — no axes, no series structure || 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]` |## Theme wiring@@ -65,7 +66,8 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei- Overlays (`ReferenceLine`/`ReferenceLines`, `ValueLabels`, `AxisTitles`) compose as children.- `ReferenceLine` variants: `goal` (dashed grey), `alert` (dashed red), `marker` (solid thin).- `ValueLabels` formatter gets `(value, seriesIndex, dataIndex, context)`; in percent layouts `value` is a 0–1 fraction — use `context.rawValue` for the original.-- `Legend` is presentational: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state.+- `Legend` is presentational: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change).+- `SlopeChart` config: `showSeriesLabels` (name beside each end point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout.- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.## Maintenancediff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsxindex 1f3531c8d3d0..28bf15b76f32 100644--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx@@ -179,20 +179,12 @@ function LineChartInner<Meta = unknown>({drawAxes(baseDrawCtx, { axisColor: theme.gridColor })}- // Clip data drawing to the plot area so an overlay series with values outside- // the y-domain (e.g. a trendline projecting below 0) doesn't bleed into the- // axis-label gutter beneath the chart. A small pad on top/bottom keeps strokes- // at the domain edge from rendering at half-thickness — line strokes and point- // markers extend past the value's pixel center.+ // Clip vertically only: keep out-of-domain values (e.g. a trendline below 0) out of the+ // axis-label gutters, but span the full width so edge point markers/line caps render whole.const CLIP_PAD = 8ctx.save()ctx.beginPath()- ctx.rect(- dimensions.plotLeft,- dimensions.plotTop - CLIP_PAD,- dimensions.plotWidth,- dimensions.plotHeight + CLIP_PAD * 2- )+ ctx.rect(0, dimensions.plotTop - CLIP_PAD, dimensions.width, dimensions.plotHeight + CLIP_PAD * 2)ctx.clip()for (const s of coloredSeries) {diff --git a/packages/quill/packages/charts/src/charts/PieChart/SliceLabels.tsx b/packages/quill/packages/charts/src/charts/PieChart/SliceLabels.tsxindex bd4cddf23e5b..537bb2a7cd7c 100644--- a/packages/quill/packages/charts/src/charts/PieChart/SliceLabels.tsx+++ b/packages/quill/packages/charts/src/charts/PieChart/SliceLabels.tsx@@ -1,8 +1,12 @@import React from 'react'+import { type LabelBox, nonCollidingKeys } from '../../core/label-collision'import { useRadialLayout } from '../../core/radial-context'import { FONT_FAMILY, measureLabelWidth } from '../../utils/text-measure'+export { nonCollidingKeys } from '../../core/label-collision'+export type { LabelBox } from '../../core/label-collision'+export interface SliceLabelsProps {valueFormatter?: (value: number) => string/** Show the slice's value above the slice. Default true. */@@ -43,35 +47,6 @@ function formatPercent(fraction: number): string {return `${Math.round(fraction * 1000) / 10}%`}-export interface LabelBox {- key: string- x: number- y: number- halfWidth: number- halfHeight: number- value: number- lines: string[]-}--function overlaps(a: LabelBox, b: LabelBox): boolean {- return Math.abs(a.x - b.x) < a.halfWidth + b.halfWidth && Math.abs(a.y - b.y) < a.halfHeight + b.halfHeight-}--/** Slices whose centered label box doesn't collide with an already-kept one. Larger slices win,- * so when adjacent thin slices crowd the same arc the most significant labels survive and the- * rest are dropped rather than overlapping. */-export function nonCollidingKeys(boxes: LabelBox[]): Set<string> {- const kept: LabelBox[] = []- const keptKeys = new Set<string>()- for (const box of [...boxes].sort((a, b) => b.value - a.value)) {- if (kept.every((other) => !overlaps(box, other))) {- kept.push(box)- keptKeys.add(box.key)- }- }- return keptKeys-}-export function SliceLabels({valueFormatter = defaultFormatter,showValueOnSlice = true,diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.stories.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.stories.tsxnew file mode 100644index 000000000000..54eb2784ca09--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.stories.tsx@@ -0,0 +1,115 @@+import { Meta, StoryObj } from '@storybook/react'++import type { Series } from '../../core/types'+import { Stage, useReactiveTheme } from '../../story-helpers'+import type { SlopeSeriesMeta } from './slope-data'+import { SlopeChart } from './SlopeChart'++const LABELS = ['Before', 'After']++const SERIES: Series<SlopeSeriesMeta>[] = [+ { key: 'us', label: 'US', color: '', data: [120, 185] },+ { key: 'eu', label: 'EU', color: '', data: [200, 150] },+ { key: 'apac', label: 'APAC', color: '', data: [80, 96] },+ { key: 'latam', label: 'LATAM', color: '', data: [60, 70] },+]++const meta: Meta = { title: 'Components/HogCharts/SlopeChart', parameters: { layout: 'centered' } }+export default meta++type Story = StoryObj<{}>++export const Default: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage width={420}>+ <SlopeChart series={SERIES} labels={LABELS} theme={theme} />+ </Stage>+ )+ },+}++export const WithoutSeriesLabels: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage width={420}>+ <SlopeChart series={SERIES} labels={LABELS} config={{ showSeriesLabels: false }} theme={theme} />+ </Stage>+ )+ },+}++/** Two near-flat series crowd the same vertical band as a steep one — the steepest line keeps its+ * name label and the low-change ones are dropped. */+export const CollidingLabels: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series<SlopeSeriesMeta>[] = [+ { key: 'rocket', label: 'Rocket', color: '', data: [40, 198] },+ { key: 'flat-a', label: 'Flat A', color: '', data: [196, 200] },+ { key: 'flat-b', label: 'Flat B', color: '', data: [200, 202] },+ ]+ return (+ <Stage width={420}>+ <SlopeChart series={series} labels={LABELS} theme={theme} />+ </Stage>+ )+ },+}++/** Per-series control of which value labels show via `meta`. */+export const PerSeriesValueLabels: Story = {+ render: () => {+ const theme = useReactiveTheme()+ const series: Series<SlopeSeriesMeta>[] = [+ { key: 'us', label: 'US', color: '', data: [120, 185], meta: { showStartLabel: false } },+ { key: 'eu', label: 'EU', color: '', data: [200, 150], meta: { showEndLabel: false } },+ { key: 'apac', label: 'APAC', color: '', data: [80, 96] },+ ]+ return (+ <Stage width={420}>+ <SlopeChart series={series} labels={LABELS} theme={theme} />+ </Stage>+ )+ },+}++export const WithLegend: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage width={420} height={320}>+ <SlopeChart series={SERIES} labels={LABELS} config={{ legend: { show: true } }} theme={theme} />+ </Stage>+ )+ },+}++export const LegendRight: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage width={560} height={280}>+ <SlopeChart+ series={SERIES}+ labels={LABELS}+ config={{ legend: { show: true, position: 'right' } }}+ theme={theme}+ />+ </Stage>+ )+ },+}++export const Empty: Story = {+ render: () => {+ const theme = useReactiveTheme()+ return (+ <Stage width={420}>+ <SlopeChart series={[]} labels={LABELS} theme={theme} />+ </Stage>+ )+ },+}diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsxnew file mode 100644index 000000000000..4de8c10e2cc2--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.test.tsx@@ -0,0 +1,162 @@+import type { ChartTheme, Series } from '../../core/types'+import { renderHogChart } from '../../testing'+import type { SlopeSeriesMeta } from './slope-data'+import { SlopeChart } from './SlopeChart'++const THEME: ChartTheme = {+ colors: ['#1f77b4', '#ff7f0e', '#2ca02c'],+ backgroundColor: '#ffffff',+ gridColor: '#eeeeee',+ crosshairColor: '#888888',+}++const LABELS = ['Before', 'After']++const SERIES: Series<SlopeSeriesMeta>[] = [+ { key: 'a', label: 'A', data: [10, 90] },+ { key: 'b', label: 'B', data: [80, 20] },+]++describe('SlopeChart', () => {+ it('renders the two columns and hides the value axis by default', () => {+ const { chart } = renderHogChart(<SlopeChart series={SERIES} labels={LABELS} theme={THEME} />)+ expect(chart.seriesCount).toBe(2)+ expect(chart.xTicks()).toEqual(['Before', 'After'])+ expect(chart.yTicks()).toHaveLength(0)+ })++ it('renders empty state without crashing', () => {+ const { chart } = renderHogChart(<SlopeChart series={[]} labels={LABELS} theme={THEME} />)+ expect(chart.seriesCount).toBe(0)+ expect(chart.slopeValueLabels()).toHaveLength(0)+ })++ it('skips excluded series everywhere', () => {+ const series: Series<SlopeSeriesMeta>[] = [+ ...SERIES,+ { key: 'c', label: 'C', data: [5, 9], visibility: { excluded: true } },+ ]+ const { chart } = renderHogChart(+ <SlopeChart series={series} labels={LABELS} config={{ legend: { show: true } }} theme={THEME} />+ )+ expect(chart.seriesCount).toBe(2)+ expect(chart.slopeSeriesLabels()).not.toContain('C')+ expect(chart.slopeLegendItems().map((i) => i.label)).not.toContain('C')+ })++ describe('value labels', () => {+ it('shows both start and end value labels for every series by default', () => {+ const { chart } = renderHogChart(<SlopeChart series={SERIES} labels={LABELS} theme={THEME} />)+ const labels = chart.slopeValueLabels()+ expect(+ labels+ .filter((l) => l.side === 'start')+ .map((l) => l.text)+ .sort()+ ).toEqual(['10', '80'])+ expect(+ labels+ .filter((l) => l.side === 'end')+ .map((l) => l.text)+ .sort()+ ).toEqual(['20', '90'])+ })++ it.each([+ ['showStartLabels: false', { showStartLabels: true } as const, { showStartLabel: false }, 'start'],+ ['showEndLabels: false', { showEndLabels: true } as const, { showEndLabel: false }, 'end'],+ ])('honors per-series %s via meta', (_label, config, metaOverride, side) => {+ const series: Series<SlopeSeriesMeta>[] = [+ { key: 'a', label: 'A', data: [10, 90], meta: metaOverride },+ { key: 'b', label: 'B', data: [80, 20] },+ ]+ const { chart } = renderHogChart(+ <SlopeChart series={series} labels={LABELS} theme={THEME} config={config} />+ )+ const sideTexts = chart.slopeValueLabels().filter((l) => l.side === side)+ // The toggled series (`a`) is missing from that column, the other (`b`) remains.+ const aValue = side === 'start' ? '10' : '90'+ expect(sideTexts.map((l) => l.text)).not.toContain(aValue)+ expect(sideTexts).toHaveLength(1)+ })++ it('drops all value labels for a series with visibility.valueLabel false', () => {+ const series: Series<SlopeSeriesMeta>[] = [+ { key: 'a', label: 'A', data: [10, 90], visibility: { valueLabel: false } },+ { key: 'b', label: 'B', data: [80, 20] },+ ]+ const { chart } = renderHogChart(<SlopeChart series={series} labels={LABELS} theme={THEME} />)+ const texts = chart.slopeValueLabels().map((l) => l.text)+ expect(texts).toEqual(expect.arrayContaining(['80', '20']))+ expect(texts).not.toContain('10')+ expect(texts).not.toContain('90')+ })++ it('formats values with a custom valueFormatter', () => {+ const { chart } = renderHogChart(+ <SlopeChart series={SERIES} labels={LABELS} config={{ valueFormatter: (v) => `${v}%` }} theme={THEME} />+ )+ expect(chart.slopeValueLabels().every((l) => l.text.endsWith('%'))).toBe(true)+ })+ })++ describe('series labels', () => {+ it('renders a name label per series by default', () => {+ const { chart } = renderHogChart(<SlopeChart series={SERIES} labels={LABELS} theme={THEME} />)+ expect(chart.slopeSeriesLabels().sort()).toEqual(['A', 'B'])+ })++ it('hides all name labels when showSeriesLabels is false', () => {+ const { chart } = renderHogChart(+ <SlopeChart series={SERIES} labels={LABELS} config={{ showSeriesLabels: false }} theme={THEME} />+ )+ expect(chart.slopeSeriesLabels()).toHaveLength(0)+ })++ it('keeps the highest-change name and drops a colliding low-change one', () => {+ // Both end at 100 (same y, same column); the steeper line must win the collision.+ const series: Series<SlopeSeriesMeta>[] = [+ { key: 'big', label: 'Big', data: [0, 100] },+ { key: 'sml', label: 'Small', data: [98, 100] },+ ]+ const { chart } = renderHogChart(<SlopeChart series={series} labels={LABELS} theme={THEME} />)+ expect(chart.slopeSeriesLabels()).toEqual(['Big'])+ })+ })++ describe('legend', () => {+ it('is hidden unless enabled', () => {+ const { chart } = renderHogChart(<SlopeChart series={SERIES} labels={LABELS} theme={THEME} />)+ expect(chart.slopeLegendItems()).toHaveLength(0)+ })++ it('shows the label and signed change for each series', () => {+ const { chart } = renderHogChart(+ <SlopeChart series={SERIES} labels={LABELS} config={{ legend: { show: true } }} theme={THEME} />+ )+ expect(chart.slopeLegendItems()).toEqual([+ { label: 'A', secondaryLabel: '+80' },+ { label: 'B', secondaryLabel: '-60' },+ ])+ })++ it('formats the change with a custom deltaFormatter', () => {+ const { chart } = renderHogChart(+ <SlopeChart+ series={SERIES}+ labels={LABELS}+ config={{ legend: { show: true }, deltaFormatter: (d) => `${d > 0 ? '↑' : '↓'}${Math.abs(d)}` }}+ theme={THEME}+ />+ )+ expect(chart.slopeLegendItems().map((i) => i.secondaryLabel)).toEqual(['↑80', '↓60'])+ })+ })++ it('forwards dataAttr to the chart wrapper', () => {+ const { chart } = renderHogChart(+ <SlopeChart series={SERIES} labels={LABELS} theme={THEME} dataAttr="slope-instance" />+ )+ expect(chart.element.getAttribute('data-attr')).toBe('slope-instance')+ })+})diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsxnew file mode 100644index 000000000000..208c3b5b9862--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeChart.tsx@@ -0,0 +1,192 @@+import React, { useCallback, useMemo } from 'react'++import { ChartLegend } from '../../components/Legend/ChartLegend'+import { ChartErrorBoundary } from '../../core/ChartErrorBoundary'+import type {+ ChartConfig,+ ChartMargins,+ ChartTheme,+ LineChartConfig,+ PointClickData,+ Series,+ TooltipContext,+ ValueDomain,+} from '../../core/types'+import { FONT_FAMILY, measureLabelWidth } from '../../utils/text-measure'+import { LineChart } from '../LineChart/LineChart'+import {+ defaultDeltaFormatter,+ defaultValueFormatter,+ slopeEnd,+ slopeLabelVisible,+ slopeStart,+ type SlopeSeriesMeta,+} from './slope-data'+import { slopeLegendItems } from './slope-legend'+import { SlopeSeriesLabels } from './SlopeSeriesLabels'+import { SlopeValueLabels } from './SlopeValueLabels'++export type { SlopeSeriesMeta } from './slope-data'++const LABEL_FONT = `600 12px ${FONT_FAMILY}`+const VALUE_GAP = 8+const NAME_GAP = 8+const EDGE_PAD = 8+const DEFAULT_ENDPOINT_RADIUS = 4++export interface SlopeChartLegendConfig {+ /** Show the legend. Default false. */+ show?: boolean+ position?: 'top' | 'bottom' | 'left' | 'right'+ align?: 'start' | 'center' | 'end'+ gap?: number+}++export interface SlopeChartConfig extends ChartConfig {+ /** Show the series name labels beside each end point. Default true. */+ showSeriesLabels?: boolean+ /** Default for the start (left) value labels; per-series `meta.showStartLabel` overrides. Default true. */+ showStartLabels?: boolean+ /** Default for the end (right) value labels; per-series `meta.showEndLabel` overrides. Default true. */+ showEndLabels?: boolean+ /** Legend visibility + placement. Hidden by default. */+ legend?: SlopeChartLegendConfig+ /** Formats the start/end value labels. Defaults to `toLocaleString`. */+ valueFormatter?: (value: number) => string+ /** Formats the per-series change shown in the legend. Defaults to a signed `toLocaleString`. */+ deltaFormatter?: (delta: number) => string+ /** Radius of the endpoint dots in px. Default 4. */+ endpointRadius?: number+ /** Value-axis domain control — omit for data-derived auto-scaling. */+ valueDomain?: ValueDomain+}++export interface SlopeChartProps<Meta = SlopeSeriesMeta> {+ series: Series<Meta>[]+ labels: string[]+ config?: SlopeChartConfig+ theme: ChartTheme+ tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode+ onPointClick?: (data: PointClickData<Meta>) => void+ className?: string+ /** `data-attr` applied to the chart wrapper. See `ChartProps.dataAttr`. */+ dataAttr?: string+ children?: React.ReactNode+ onError?: (error: Error, info: React.ErrorInfo) => void+}++export function SlopeChart<Meta = SlopeSeriesMeta>({ onError, ...rest }: SlopeChartProps<Meta>): React.ReactElement {+ return (+ <ChartErrorBoundary onError={onError}>+ <SlopeChartInner {...rest} />+ </ChartErrorBoundary>+ )+}++function maxLabelWidth(texts: string[]): number {+ return texts.reduce((max, t) => Math.max(max, measureLabelWidth(t, LABEL_FONT)), 0)+}++function SlopeChartInner<Meta = SlopeSeriesMeta>({+ series,+ labels,+ config,+ theme,+ tooltip,+ onPointClick,+ className,+ dataAttr,+ children,+}: SlopeChartProps<Meta>): React.ReactElement {+ const {+ showSeriesLabels = true,+ showStartLabels = true,+ showEndLabels = true,+ legend,+ valueFormatter = defaultValueFormatter,+ deltaFormatter = defaultDeltaFormatter,+ endpointRadius = DEFAULT_ENDPOINT_RADIUS,+ valueDomain,+ } = config ?? {}++ const showsStart = useCallback(+ (s: Series<Meta>): boolean => slopeLabelVisible(s, 'start', showStartLabels),+ [showStartLabels]+ )+ const showsEnd = useCallback(+ (s: Series<Meta>): boolean => slopeLabelVisible(s, 'end', showEndLabels),+ [showEndLabels]+ )++ // Reserve left/right gutters for the value/name labels, which sit in the margins beyond the plot.+ const { margins, nameOffsetX } = useMemo(() => {+ const startWidth = maxLabelWidth(series.filter(showsStart).map((s) => valueFormatter(slopeStart(s))))+ const endWidth = maxLabelWidth(series.filter(showsEnd).map((s) => valueFormatter(slopeEnd(s))))+ const nameWidth = showSeriesLabels+ ? maxLabelWidth(+ series+ .filter((s) => !s.visibility?.excluded && s.visibility?.valueLabel !== false)+ .map((s) => s.label)+ )+ : 0++ const left = startWidth > 0 ? startWidth + VALUE_GAP + EDGE_PAD : EDGE_PAD+ const endGutter = endWidth > 0 ? VALUE_GAP + endWidth : 0+ const nameGutter = nameWidth > 0 ? NAME_GAP + nameWidth : 0+ const right = endGutter || nameGutter ? endGutter + nameGutter + EDGE_PAD : EDGE_PAD++ // Names start just past the end value column.+ const offset = (endWidth > 0 ? VALUE_GAP + endWidth : 0) + NAME_GAP++ const base: Partial<ChartMargins> = { left, right }+ return { margins: { ...base, ...config?.margins }, nameOffsetX: offset }+ }, [series, showsStart, showsEnd, showSeriesLabels, valueFormatter, config?.margins])++ // A slope is a two-point line — collapse each series to its endpoints, with a dot at each.+ const slopeSeries = useMemo<Series<Meta>[]>(+ () =>+ series.map((s) => ({+ ...s,+ data: [slopeStart(s), slopeEnd(s)],+ points: { ...s.points, radius: endpointRadius },+ })),+ [series, endpointRadius]+ )++ const lineConfig = useMemo<LineChartConfig>(+ () => ({ ...config, hideYAxis: config?.hideYAxis ?? true, showGrid: false, margins, valueDomain }),+ [config, margins, valueDomain]+ )++ const legendItems = useMemo(() => slopeLegendItems(series, theme, deltaFormatter), [series, theme, deltaFormatter])++ return (+ <ChartLegend+ show={legend?.show ?? false}+ items={legendItems}+ position={legend?.position ?? 'bottom'}+ align={legend?.align}+ gap={legend?.gap}+ legendDataAttr="hog-chart-slope-legend"+ >+ <LineChart<Meta>+ series={slopeSeries}+ labels={labels}+ config={lineConfig}+ theme={theme}+ tooltip={tooltip}+ onPointClick={onPointClick}+ className={className}+ dataAttr={dataAttr}+ >+ <SlopeValueLabels+ valueFormatter={valueFormatter}+ showStartLabels={showStartLabels}+ showEndLabels={showEndLabels}+ />+ <SlopeSeriesLabels show={showSeriesLabels} offsetX={nameOffsetX} />+ {children}+ </LineChart>+ </ChartLegend>+ )+}diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeLabel.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeLabel.tsxnew file mode 100644index 000000000000..65b77a6e0745--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeLabel.tsx@@ -0,0 +1,45 @@+import React from 'react'++import { FONT_FAMILY } from '../../utils/text-measure'+import type { SlopeSide } from './slope-data'++export const SLOPE_LABEL_FONT_SIZE = 12+const SLOPE_LABEL_FONT_WEIGHT = 600+/** The font slope labels render and measure with — keeps rendering and width measurement in step. */+export const SLOPE_LABEL_FONT = `${SLOPE_LABEL_FONT_WEIGHT} ${SLOPE_LABEL_FONT_SIZE}px ${FONT_FAMILY}`++export interface SlopeLabelProps {+ x: number+ y: number+ /** CSS transform anchoring the label relative to its `(x, y)` point. */+ transform: string+ color: string+ text: string+ dataAttr: string+ side?: SlopeSide+}++/** A single non-interactive slope label: series-colored text positioned absolutely at `(x, y)` and+ * offset by `transform`. Shared by the value-label columns and the end-anchored series names. */+export function SlopeLabel({ x, y, transform, color, text, dataAttr, side }: SlopeLabelProps): React.ReactElement {+ return (+ <div+ data-attr={dataAttr}+ data-slope-side={side}+ style={{+ position: 'absolute',+ left: Math.round(x),+ top: Math.round(y),+ transform,+ color,+ fontSize: SLOPE_LABEL_FONT_SIZE,+ fontWeight: SLOPE_LABEL_FONT_WEIGHT,+ lineHeight: 1,+ whiteSpace: 'nowrap',+ pointerEvents: 'none',+ }}+ >+ {text}+ </div>+ )+}diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeSeriesLabels.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeSeriesLabels.tsxnew file mode 100644index 000000000000..eb4b6bb80570--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeSeriesLabels.tsx@@ -0,0 +1,90 @@+import React, { useMemo } from 'react'++import { useChartLayout } from '../../core/chart-context'+import { type LabelBox, nonCollidingKeys } from '../../core/label-collision'+import type { ResolvedSeries } from '../../core/types'+import { measureLabelWidth } from '../../utils/text-measure'+import { slopeDelta, slopeEnd } from './slope-data'+import { SLOPE_LABEL_FONT, SLOPE_LABEL_FONT_SIZE, SlopeLabel } from './SlopeLabel'++const LABEL_PADDING_X = 4+const LABEL_PADDING_Y = 3++export interface SlopeSeriesLabelsProps {+ /** Render the series name labels. Default true. */+ show?: boolean+ /** Px to the right of the right endpoint where the name labels begin. */+ offsetX?: number+}++interface NameEntry {+ box: LabelBox+ color: string+ label: string+}++/** Series name labels anchored beside each series' end point. When two names would overlap, the+ * series with the larger change (`|end − start|`) wins — it is always kept, and lower-change names+ * that collide with it are dropped (requirement: the steepest line never loses its label). */+export function SlopeSeriesLabels({ show = true, offsetX = 8 }: SlopeSeriesLabelsProps): React.ReactElement | null {+ const { series, scales, labels } = useChartLayout()++ const entries = useMemo<NameEntry[]>(() => {+ if (!show || labels.length < 2) {+ return []+ }+ const x1 = scales.x(labels[labels.length - 1])+ if (x1 == null) {+ return []+ }+ const out: NameEntry[] = []+ for (const s of series as ResolvedSeries[]) {+ if (s.visibility?.excluded || s.visibility?.valueLabel === false) {+ continue+ }+ const y = scales.y(slopeEnd(s))+ if (!isFinite(y)) {+ continue+ }+ const width = measureLabelWidth(s.label, SLOPE_LABEL_FONT)+ out.push({+ color: s.color,+ label: s.label,+ box: {+ key: s.key,+ x: x1 + offsetX + width / 2,+ y,+ halfWidth: width / 2 + LABEL_PADDING_X,+ halfHeight: SLOPE_LABEL_FONT_SIZE / 2 + LABEL_PADDING_Y,+ value: Math.abs(slopeDelta(s)),+ lines: [s.label],+ },+ })+ }+ return out+ }, [series, scales, labels, show, offsetX])++ const visibleKeys = useMemo(() => nonCollidingKeys(entries.map((e) => e.box)), [entries])++ if (entries.length === 0) {+ return null+ }++ return (+ <>+ {entries+ .filter((e) => visibleKeys.has(e.box.key))+ .map((e) => (+ <SlopeLabel+ key={e.box.key}+ x={e.box.x}+ y={e.box.y}+ transform="translate(-50%, -50%)"+ color={e.color}+ text={e.label}+ dataAttr="hog-chart-slope-series-label"+ />+ ))}+ </>+ )+}diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/SlopeValueLabels.tsx b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeValueLabels.tsxnew file mode 100644index 000000000000..948fb7d3ce6f--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SlopeChart/SlopeValueLabels.tsx@@ -0,0 +1,112 @@+import React, { useMemo } from 'react'++import { useChartLayout } from '../../core/chart-context'+import type { ResolvedSeries } from '../../core/types'+import { defaultValueFormatter, slopeEnd, slopeLabelVisible, type SlopeSide, slopeStart } from './slope-data'+import { SlopeLabel } from './SlopeLabel'++export interface SlopeValueLabelsProps {+ valueFormatter?: (value: number) => string+ /** Chart-level default for the start (left) value labels. Per-series `meta.showStartLabel` wins. */+ showStartLabels?: boolean+ /** Chart-level default for the end (right) value labels. Per-series `meta.showEndLabel` wins. */+ showEndLabels?: boolean+ /** Px gap between the endpoint dot and its value label. */+ gap?: number+ /** Min vertical px between two labels in the same column before the lower one is dropped. */+ minGap?: number+}++interface ValueCandidate {+ key: string+ side: SlopeSide+ text: string+ color: string+ x: number+ y: number+}++const LABEL_HEIGHT = 16++/** Keep labels in one column top-to-bottom, dropping any that would crowd the one above it. */+function columnSweep(candidates: ValueCandidate[], minGap: number): ValueCandidate[] {+ const sorted = [...candidates].sort((a, b) => a.y - b.y)+ const kept: ValueCandidate[] = []+ const halfH = LABEL_HEIGHT / 2+ let lastBottom = -Infinity+ for (const c of sorted) {+ if (c.y - halfH >= lastBottom + minGap) {+ kept.push(c)+ lastBottom = c.y + halfH+ }+ }+ return kept+}++/** Start (left) and end (right) value labels for a slope chart, one per series per side. Each side+ * is a vertical column anchored on the endpoint dots; within a column, lower-priority labels are+ * dropped on collision. Per-series visibility comes from `meta.showStartLabel`/`showEndLabel`. */+export function SlopeValueLabels({+ valueFormatter = defaultValueFormatter,+ showStartLabels = true,+ showEndLabels = true,+ gap = 8,+ minGap = 2,+}: SlopeValueLabelsProps): React.ReactElement | null {+ const { series, scales, labels } = useChartLayout()++ const visible = useMemo(() => {+ if (labels.length < 2) {+ return []+ }+ const x0 = scales.x(labels[0])+ const x1 = scales.x(labels[labels.length - 1])+ const start: ValueCandidate[] = []+ const end: ValueCandidate[] = []+ for (const s of series as ResolvedSeries[]) {+ if (slopeLabelVisible(s, 'start', showStartLabels) && x0 != null) {+ const y = scales.y(slopeStart(s))+ if (isFinite(y)) {+ start.push({+ key: s.key,+ side: 'start',+ text: valueFormatter(slopeStart(s)),+ color: s.color,+ x: x0,+ y,+ })+ }+ }+ if (slopeLabelVisible(s, 'end', showEndLabels) && x1 != null) {+ const y = scales.y(slopeEnd(s))+ if (isFinite(y)) {+ end.push({ key: s.key, side: 'end', text: valueFormatter(slopeEnd(s)), color: s.color, x: x1, y })+ }+ }+ }+ return [...columnSweep(start, minGap), ...columnSweep(end, minGap)]+ }, [series, scales, labels, valueFormatter, showStartLabels, showEndLabels, minGap])++ if (visible.length === 0) {+ return null+ }++ return (+ <>+ {visible.map((c) => (+ <SlopeLabel+ key={`${c.side}-${c.key}`}+ x={c.x}+ y={c.y}+ transform={+ c.side === 'start' ? `translate(calc(-100% - ${gap}px), -50%)` : `translate(${gap}px, -50%)`+ }+ color={c.color}+ text={c.text}+ dataAttr="hog-chart-slope-value-label"+ side={c.side}+ />+ ))}+ </>+ )+}diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/slope-data.ts b/packages/quill/packages/charts/src/charts/SlopeChart/slope-data.tsnew file mode 100644index 000000000000..4a1015d3e5a5--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SlopeChart/slope-data.ts@@ -0,0 +1,51 @@+import type { Series } from '../../core/types'++/** Per-series options read from `Series.meta` by the slope chart. Lets a consumer toggle the+ * start/end value labels for an individual series without touching the shared `Series` type. */+export interface SlopeSeriesMeta {+ /** Show this series' start (left) value label. Falls back to the chart-level default. */+ showStartLabel?: boolean+ /** Show this series' end (right) value label. Falls back to the chart-level default. */+ showEndLabel?: boolean+}++export type SlopeSide = 'start' | 'end'++/** Whether a series' value label for `side` should render. Excluded/hidden series never show one;+ * otherwise the per-series `meta` override wins over the chart-level default. Shared by the gutter+ * sizing and the label rendering so the reserved margin always matches what is drawn. */+export function slopeLabelVisible(+ series: Pick<Series, 'visibility' | 'meta'>,+ side: SlopeSide,+ chartDefault: boolean+): boolean {+ if (series.visibility?.excluded || series.visibility?.valueLabel === false) {+ return false+ }+ const meta = series.meta as SlopeSeriesMeta | undefined+ const override = side === 'start' ? meta?.showStartLabel : meta?.showEndLabel+ return override ?? chartDefault+}++/** A slope chart series carries exactly two values — `[start, end]`. These helpers read the first+ * and last entry, substituting 0 when an endpoint is absent. */+export function slopeStart(series: Pick<Series, 'data'>): number {+ return series.data[0] ?? 0+}++export function slopeEnd(series: Pick<Series, 'data'>): number {+ return series.data[series.data.length - 1] ?? 0+}++export function slopeDelta(series: Pick<Series, 'data'>): number {+ return slopeEnd(series) - slopeStart(series)+}++export function defaultValueFormatter(value: number): string {+ return value.toLocaleString()+}++export function defaultDeltaFormatter(delta: number): string {+ const sign = delta > 0 ? '+' : ''+ return `${sign}${delta.toLocaleString()}`+}diff --git a/packages/quill/packages/charts/src/charts/SlopeChart/slope-legend.ts b/packages/quill/packages/charts/src/charts/SlopeChart/slope-legend.tsnew file mode 100644index 000000000000..cd66c7071964--- /dev/null+++ b/packages/quill/packages/charts/src/charts/SlopeChart/slope-legend.ts@@ -0,0 +1,18 @@+import type { LegendItem } from '../../components/Legend/Legend'+import { legendItemsFromSeries } from '../../components/Legend/legendItemsFromSeries'+import type { ChartTheme, ResolvedSeries, Series } from '../../core/types'+import { slopeDelta } from './slope-data'++/** Legend items for a slope chart — `legendItemsFromSeries` plus a per-series change+ * (`end − start`, formatted) carried as each row's `secondaryLabel`. */+export function slopeLegendItems(+ series: ReadonlyArray<Series | ResolvedSeries>,+ theme: ChartTheme,+ deltaFormatter: (delta: number) => string+): LegendItem[] {+ const byKey = new Map(series.map((s) => [s.key, s]))+ return legendItemsFromSeries(series, theme).map((item) => ({+ ...item,+ secondaryLabel: deltaFormatter(slopeDelta(byKey.get(item.key)!)),+ }))+}diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.tsxindex a42e451493d0..037f1060d980 100644--- a/packages/quill/packages/charts/src/components/Legend/Legend.tsx+++ b/packages/quill/packages/charts/src/components/Legend/Legend.tsx@@ -5,6 +5,8 @@ export interface LegendItem {key: stringlabel: stringcolor: string+ /** Optional trailing text shown muted after the label — e.g. a slope chart's per-series change. */+ secondaryLabel?: string}export interface LegendProps {@@ -50,6 +52,11 @@ export function Legend({style={{ backgroundColor: item.color }}/><span className="truncate">{item.label}</span>+ {item.secondaryLabel != null && item.secondaryLabel !== '' && (+ <span className="shrink-0 text-muted" data-attr="hog-chart-legend-secondary">+ {item.secondaryLabel}+ </span>+ )}</>)return onItemClick ? (diff --git a/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.ts b/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.tsindex 562049f6c06e..30c376b6b50a 100644--- a/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.ts+++ b/packages/quill/packages/charts/src/components/Legend/legendItemsFromSeries.ts@@ -10,7 +10,7 @@ export function legendItemsFromSeries(series: ReadonlyArray<Series | ResolvedSercontinue}const fallback = palette.length > 0 ? palette[i % palette.length] : '#000'- items.push({ key: s.key, label: s.label, color: s.color ?? fallback })+ items.push({ key: s.key, label: s.label, color: s.color || fallback })}return items}diff --git a/packages/quill/packages/charts/src/core/label-collision.ts b/packages/quill/packages/charts/src/core/label-collision.tsnew file mode 100644index 000000000000..343f3af57992--- /dev/null+++ b/packages/quill/packages/charts/src/core/label-collision.ts@@ -0,0 +1,33 @@+// Priority-drop collision resolution for absolutely-positioned label boxes. Shared by chart+// types that crowd labels into a tight region (pie slice labels, slope-chart series labels) and+// want the most significant labels to survive rather than letting everything overlap.++export interface LabelBox {+ key: string+ x: number+ y: number+ halfWidth: number+ halfHeight: number+ /** Priority used to resolve collisions — larger values are kept first. */+ value: number+ lines: string[]+}++export function overlaps(a: LabelBox, b: LabelBox): boolean {+ return Math.abs(a.x - b.x) < a.halfWidth + b.halfWidth && Math.abs(a.y - b.y) < a.halfHeight + b.halfHeight+}++/** Keys of the boxes whose centered box doesn't collide with an already-kept one. Higher-`value`+ * boxes win, so when labels crowd the same region the most significant ones survive and the rest+ * are dropped rather than overlapping. */+export function nonCollidingKeys(boxes: LabelBox[]): Set<string> {+ const kept: LabelBox[] = []+ const keptKeys = new Set<string>()+ for (const box of [...boxes].sort((a, b) => b.value - a.value)) {+ if (kept.every((other) => !overlaps(box, other))) {+ kept.push(box)+ keptKeys.add(box.key)+ }+ }+ return keptKeys+}diff --git a/packages/quill/packages/charts/src/index.ts b/packages/quill/packages/charts/src/index.tsindex d9b8bed5c6e8..37c3e48f2738 100644--- a/packages/quill/packages/charts/src/index.ts+++ b/packages/quill/packages/charts/src/index.ts@@ -41,6 +41,20 @@ export type { BoxRect } from './core/types'export { BoxPlotTooltip } from './charts/BoxPlot/BoxPlotTooltip'export type { BoxPlotTooltipProps } from './charts/BoxPlot/BoxPlotTooltip'+// Slope chart+export { SlopeChart } from './charts/SlopeChart/SlopeChart'+export type {+ SlopeChartConfig,+ SlopeChartLegendConfig,+ SlopeChartProps,+ SlopeSeriesMeta,+} from './charts/SlopeChart/SlopeChart'+export { SlopeValueLabels } from './charts/SlopeChart/SlopeValueLabels'+export type { SlopeValueLabelsProps } from './charts/SlopeChart/SlopeValueLabels'+export { SlopeSeriesLabels } from './charts/SlopeChart/SlopeSeriesLabels'+export type { SlopeSeriesLabelsProps } from './charts/SlopeChart/SlopeSeriesLabels'+export { slopeLegendItems } from './charts/SlopeChart/slope-legend'+// Pie / donutexport { PieChart } from './charts/PieChart/PieChart'export type { PieChartConfig, PieChartProps } from './charts/PieChart/PieChart'diff --git a/packages/quill/packages/charts/src/testing/accessor.ts b/packages/quill/packages/charts/src/testing/accessor.tsindex f31b0c717875..969ca15db129 100644--- a/packages/quill/packages/charts/src/testing/accessor.ts+++ b/packages/quill/packages/charts/src/testing/accessor.ts@@ -45,6 +45,20 @@ interface AnomalyPointSummary {color: string}+interface SlopeValueLabelSummary {+ text: string+ /** Inline style color (matches the series color). */+ color: string+ /** Which end of the slope this label sits on. */+ side: 'start' | 'end'+}++interface SlopeLegendItemSummary {+ label: string+ /** The per-series change text, or null when absent. */+ secondaryLabel: string | null+}+export interface HogChart<Meta = unknown> {/** The wrapper div of this chart. */element: HTMLElement@@ -68,6 +82,12 @@ export interface HogChart<Meta = unknown> {valueLabels(): ValueLabelSummary[]/** All anomaly point markers currently rendered (TimeSeriesLineChart only). */anomalyPoints(): AnomalyPointSummary[]+ /** All slope-chart value labels currently rendered (start + end columns). */+ slopeValueLabels(): SlopeValueLabelSummary[]+ /** Series name labels currently rendered by a slope chart (post-collision-avoidance). */+ slopeSeriesLabels(): string[]+ /** Slope-chart legend rows — label plus the per-series change. Empty when the legend is hidden. */+ slopeLegendItems(): SlopeLegendItemSummary[]/** Annotation badges currently rendered. */annotationBadges(): HTMLElement[]/** Fire a `mouseMove` over the data point at `index`. Only available when the chart was@@ -197,6 +217,34 @@ export function getHogChart<Meta = unknown>(element: el,color: el.style.backgroundColor,})),+ slopeValueLabels: () =>+ Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-slope-value-label"]')).map(+ (el) => ({+ text: el.textContent ?? '',+ color: el.style.color,+ side: el.dataset.slopeSide === 'end' ? 'end' : 'start',+ })+ ),+ slopeSeriesLabels: () =>+ Array.from(wrapper.querySelectorAll<HTMLElement>('[data-attr="hog-chart-slope-series-label"]')).map(+ (el) => el.textContent ?? ''+ ),+ slopeLegendItems: () => {+ // The legend renders as a sibling of the chart wrapper (inside ChartLegendLayout), so it+ // lives in the broader render scope rather than under `wrapper`.+ const legend = scope.querySelector<HTMLElement>('[data-attr="hog-chart-slope-legend"]')+ if (!legend) {+ return []+ }+ return Array.from(legend.querySelectorAll<HTMLElement>('.truncate')).map((labelEl) => {+ const secondary = labelEl.nextElementSibling+ const isSecondary = secondary?.getAttribute('data-attr') === 'hog-chart-legend-secondary'+ return {+ label: labelEl.textContent ?? '',+ secondaryLabel: isSecondary ? (secondary as HTMLElement).textContent : null,+ }+ })+ },annotationBadges: () => Array.from(wrapper.querySelectorAll<HTMLElement>('.AnnotationsBadge')),hoverAtIndex(index: number): void {if (totalLabels === undefined) {diff --git a/products/product_analytics/skills/choosing-trend-or-slope-view/SKILL.md b/products/product_analytics/skills/choosing-trend-or-slope-view/SKILL.mdnew file mode 100644index 000000000000..25e8b5f218c7--- /dev/null+++ b/products/product_analytics/skills/choosing-trend-or-slope-view/SKILL.md@@ -0,0 +1,73 @@+---+name: choosing-trend-or-slope-view+description: >+ Clarify how to visualize change over a time range before building a trend.+ Use whenever the user asks how much something changed, grew, dropped,+ improved, or regressed between two points or periods — "how much did X change+ from A to B", "before vs after", "start vs end", "week over week", "compare+ this month to last", "change over time" — or mentions a "slope chart" /+ "slopegraph". Two readings of "change" need different charts: the whole trend+ (a line, every interval) versus just the two endpoints (a slope, start vs+ end). Ask which they want, then render it. Not for choosing a saved insight+ ChartDisplayType in the insight editor.+---++# Choosing a trend line vs a slope view++"How did X change between A and B?" is ambiguous. Two charts answer two different+questions, so **clarify before you build** unless the user already named one:++- **Change over time (line)** — the value at every interval across the range.+ Shows the _path_: dips, spikes, when it moved. This is the default trend.+- **Start vs end (slope)** — only the first and last point, one line per series+ connecting them. Shows the _net change_ and, across many series, which rose,+ which fell, and any rank flips — without the noise of the path between.++When the request could be either, ask a short either/or, e.g.:++> Do you want to see how it moved across the whole period (a line chart), or just+> the change from the start to the end (a slope chart)?++If the user clearly wants one — "just tell me how much it grew start to end" → slope;+"show me the trend / when did it spike" → line — skip the question and build it.++## How to render each++Both come from the **same** `TrendsQuery` over the same date range — the slope is+that series collapsed to its first and last point, not a different query.++### Change over time → line++Default trends behavior. Create or run a `TrendsQuery` and leave+`trendsFilter.display` as `ActionsLineGraph` (the default, "change over time"):++```json+{+ "kind": "TrendsQuery",+ "series": [{ "kind": "EventsNode", "event": "$pageview", "math": "total" }],+ "dateRange": { "date_from": "2025-01-01", "date_to": "2025-03-31" },+ "trendsFilter": { "display": "ActionsLineGraph" }+}+```++### Start vs end → slope++Run the trend with `posthog:query-trends`. The result card Max renders has a+**Line / Bar / Slope** view toggle — switch it to **Slope** to show each series as+a single line from its first to its last point, with the per-series change in the+legend. Tell the user they can flip to the Slope view on the result.++The slope view is best for a clean before→after comparison, especially with several+series/categories whose relative movement matters. Pick a date range whose two ends+are the points you want compared (the slope uses the first and last interval).++## Important limits++- **Slope is a view, not a saved insight type.** It lives on Max's inline trends+ result card (the `query-trends` visualizer). A _saved_ insight has no slope+ display — `SlopeChart` is not a `ChartDisplayType`, so `posthog:insight-create`+ with a slope display is not available. If the user wants a saved/dashboard chart,+ save the line and offer the slope as the inline view, or note the limitation.+- For period-over-period on a single series (this month vs last), a line with+ `compareFilter: { "compare": true }` overlays the two periods; a slope is the+ better fit when comparing the endpoints of **many** series at once.diff --git a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsxindex 51eba9d3ddbb..4f2834d449b2 100644--- a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx+++ b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx@@ -2,7 +2,7 @@ import { type ReactElement, useState } from 'react'import { emptyStateIllustration } from '@posthog/mcp-ui'import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'-import { BarChart as BarValueChart, TimeSeriesBarChart, TimeSeriesLineChart } from '@posthog/quill-charts'+import { BarChart as BarValueChart, SlopeChart, TimeSeriesBarChart, TimeSeriesLineChart } from '@posthog/quill-charts'import { buildTrendsBarChartModel } from 'products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms'import {@@ -19,13 +19,17 @@ import { CHART_THEME, colorAt } from './charts/theme'import type { TrendsResultItem, TrendsVisualizerProps } from './types'import { formatDate, getDisplayType, getSeriesLabel, isBarChart } from './utils'-type ChartMode = 'line' | 'bar'+type ChartMode = 'line' | 'bar' | 'slope'const CHART_MODE_OPTIONS = [{ value: 'line' as const, label: 'Line' },{ value: 'bar' as const, label: 'Bar' },]+// "Slope" collapses each series to its first and last point — the start-vs-end view a user wants+// when they ask "how much did X change between A and B?" rather than the path between them.+const SLOPE_MODE_OPTION = { value: 'slope' as const, label: 'Slope' }+const TOOLTIP_CONFIG = { pinnable: true, placement: 'top' as const }function calculateTotal(results: TrendsResultItem[]): number {@@ -94,9 +98,39 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Rea}))const yAxisLabel = results.length === 1 && results[0] ? getSeriesLabel(results[0], 0) : undefined+ // A slope needs a start and an end, so only offer it when there are at least two time points.+ const slopeAvailable = labels.length >= 2+ const chartModeOptions = slopeAvailable ? [...CHART_MODE_OPTIONS, SLOPE_MODE_OPTION] : CHART_MODE_OPTIONS+ // Results can shrink below two points after slope was selected; fall back rather than render blank.+ const effectiveMode = chartMode === 'slope' && !slopeAvailable ? 'line' : chartMode+// Build only the active mode's chart model — toggling shouldn't recompute the hidden one.const renderChart = (): ReactElement => {- if (chartMode === 'bar') {+ if (effectiveMode === 'slope') {+ const slopeSeries = trendResults+ .map((item, index) => {+ if (item.data.length < 2) {+ return null+ }+ return {+ key: String(item.id),+ label: item.label,+ color: colorAt(index),+ data: [item.data[0]!, item.data[item.data.length - 1]!],+ }+ })+ .filter((s): s is NonNullable<typeof s> => s !== null)+ const slopeLabels = [formatDate(labels[0]!), formatDate(labels[labels.length - 1]!)]+ return (+ <SlopeChart+ series={slopeSeries}+ labels={slopeLabels}+ theme={CHART_THEME}+ config={{ showSeriesLabels: false, legend: { show: true, position: 'bottom' } }}+ />+ )+ }+ if (effectiveMode === 'bar') {const { series, config } = buildTrendsBarChartModel(trendResults, {getColor: (_, index) => colorAt(index),labels,@@ -127,7 +161,7 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Rea<div><div className="mb-2 flex justify-end">{/* eslint-disable-next-line react/forbid-elements */}- <Select value={chartMode} onChange={setChartMode} options={CHART_MODE_OPTIONS} />+ <Select value={effectiveMode} onChange={setChartMode} options={chartModeOptions} /></div><div className="flex flex-col w-full h-[400px]">{renderChart()}</div></div>