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(legends): consolidate legend position into unified legend options filter (#65208)

Sam Pennington8d6f2d8772df
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5f28c91caa81..b7ffad6eef5c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -656,10 +656,14 @@ snapshots:
hash: v1.k794b7964.6e64a543c991123d412574ef5242f84e11910441d54fff974bd96908be5455ae.nypUwrIVY9Dq2t4xRbMwl7gmqbSylWS4X1xzWkg4-aU
components-hogcharts-legend--legend-hidden--light:
hash: v1.k794b7964.c421a16355bae41c9fd5c1d1c6aa071f73152e460043018fc387b9b2a8a69435.YAeJXhL3L0kCKi5t7tzYOyNsfoE6H7iASEcvGIO7cXo
+ components-hogcharts-legend--long-labels-truncate--dark:
+ hash: v1.k794b7964.17a87c4fa402ff5f0871d0e40adbc47f90e065c0fdcf16b6b610adb487c9be7c.IvI7NT4lT_XmM9qSg-OHGFwijNSFXgJjQO3sZA87flM
+ components-hogcharts-legend--long-labels-truncate--light:
+ hash: v1.k794b7964.331a83b798c14594c31fbd0bb8ab30df6bfbb994460814ae66c1e2f25206c1ff.z5hnkMvwuTTNeqC4HkunO95MlM5pJd_lkGXJAkDtzis
components-hogcharts-legend--many-items-wraps--dark:
- hash: v1.k794b7964.3c9a0cea0cbbd5a8e060d3a02a02e32d2094f09a758be1a46b981bd3c69da239.eoCKPhPMZ-QobzeKmfGGvFrJzYeSW5-YxoXVVOczUaU
+ hash: v1.k794b7964.1b95335bf283551cdef86841be2fd53b6c652fa6f263b3da7203e1e6599d1c18.Lk6e0w_i4AQAMZulWHRcwh6J5PzTBlqcrIKEvFVFhas
components-hogcharts-legend--many-items-wraps--light:
- hash: v1.k794b7964.efe84fdfc119b7a3dcd8c8caa81f924f0a3a0d3aae9dcba7eea7cbe646d75f75.f-DbmqP9qC26Ba1vRzTG0LRulKSxBEAmIQdaO-GC8JQ
+ hash: v1.k794b7964.828b81c17c44ea01c54c37cbed719c119adba9b7ea7635aa12074b3d798ea25c.t0VXF8I2msfb7-4L1KpcZgD2WPODhEKK1sJlj9MwhCE
components-hogcharts-legend--vertical--dark:
hash: v1.k794b7964.ccfb11e836bb82f76eef037168a9475264909305f12b175514f32e79cde6570a.redbR1FEBZ4p8hDDGgFwqT9B4f8VHOZv3RLf9gTOOIg
components-hogcharts-legend--vertical--light:
@@ -6311,21 +6315,21 @@ snapshots:
scenes-app-replay-vision--scanners-list--light:
hash: v1.k794b7964.ac75c9575c6b504fa5217a62ec0f56511d669d3bceae8b10733a4d7da5afb960.yoiUiSh7RBOEyNeHUewLjo1LU3GGCNGZh2ZVbNMZlhA
scenes-app-revenue-analytics--revenue-analytics-dashboard--dark:
- hash: v1.k794b7964.3b4f6a185d0332a9ac4871791ad9cbd8c5153062e35b02463cf264ff78d929ae.yxixzefaqbohT5c-mkkDGFkQ5jFbxFZTJNQMfwOnapI
+ hash: v1.k794b7964.cdf9e00b28b52b4abf4d161b3593a7b9c7616df14c78ca1022f1b452ec98a628.oC6MqWeOLr6BAEuVc3MgKwPcv6ThL0vJfwRXWrfqH5g
scenes-app-revenue-analytics--revenue-analytics-dashboard--light:
- hash: v1.k794b7964.e377f74a29ac2e0276263d416ee1262c2b12400e927871c06be52e314ca2da09.V-mkg8TbXd_z-6ovJ9BoMzCV_sJ2GQ2o9WcSLdvlX8g
+ hash: v1.k794b7964.02253b1a5c3d9651da0b51eeb4ba44f04df027464523ed5c0c330fb0d3d88be9.RZ_elO1oYXLiLtFTXOcJJhAokQm4rk-pXnOwYgC_YIk
scenes-app-revenue-analytics--revenue-analytics-dashboard-area-mode--dark:
- hash: v1.k794b7964.e809b6057b3726a9a3bbfabe8b641164c53a113637d0371fdc75e57f59e9e6e1.t7Yi7gvwTUxhm_cxJoLCKJdAYKcvedk85pqf6Mkhm20
+ hash: v1.k794b7964.33951c6b1eeb3227239c24231067e6ae9fbd841d236e77e1e57b7e31ff9b41e9.G7cN52GuSbq17WTw4HZ0UxnrV9t5R9cBmETtLZoOM7A
scenes-app-revenue-analytics--revenue-analytics-dashboard-area-mode--light:
- hash: v1.k794b7964.ae4bd815a206bdbad9c1bd5e909fd51cb281f87e8eea7ad336135707984ca53a.Yj1cH-7VAUDQsMn-09ppYCfTyEjAuhIL17YZhh6X31Q
+ hash: v1.k794b7964.73363c9dc8d269b1bdca387dd6b982058982a8cb609a737b73e26b44b14f951c.2aoXnujRadIzXrpspIVsa2vcyZGsPUcEL0GYKoGc5Ss
scenes-app-revenue-analytics--revenue-analytics-dashboard-bar-mode--dark:
- hash: v1.k794b7964.127eeedd4aac02b5c07d856a6fb7726f284597153b4373fbabf1465d3d540373.rTYvcngE7KxbqbxYHSCsamc8HclEe8gmbMxRwSCIgy8
+ hash: v1.k794b7964.909b5eeaf1855ee758218ca35e344272822b29820ce5bf0051f90cae5cea4602.dq5wdDYjdSKyYsIQFTiahdQpmMEBbX2Fc2JWrAzSOEU
scenes-app-revenue-analytics--revenue-analytics-dashboard-bar-mode--light:
- hash: v1.k794b7964.a39ee336074c150d47b1b780c8dfa70cca4812b88b9a0a5b1aea6e320b027584.XLkzmwlIVkavbv1ZQNqV0zld9_fCnTYvBI3Nlqj_0_E
+ hash: v1.k794b7964.f794a5111b857c6bbcdef6a532ed700184a65e7d36fe7a7068582cf08a8eb0bc.xGrhk7yarlGtCqpI6CdfDyuvY7GXyT-5r8u2FO7BiRU
scenes-app-revenue-analytics--revenue-analytics-dashboard-sync-in-progress--dark:
- hash: v1.k794b7964.64238c158c8ad819ac47e780646c8beb7b36cc3e3d32e551340457426260f10d.xTB8G4yV7ZG6lbxWcmxkrS8zRGniCGHl5Jd_QDax8og
+ hash: v1.k794b7964.266208b782900d5e2e26a5220cb871fd48d89d91f52f4ff665640b71fc78fc28.6D1n65FigrpEjIhjnX58hCwrr__V0vle8k_7DCFKccY
scenes-app-revenue-analytics--revenue-analytics-dashboard-sync-in-progress--light:
- hash: v1.k794b7964.b5a85ba3d84b972ded4435b99744319a10ae1e8e991fbdb42dc8f73765ad011f.XRLpdbBkMVEhv75hgHMpSpQbw9YHH5L941DaqOYQsvI
+ hash: v1.k794b7964.fdda12c2a8bf8b84b93daaac139cbe6bbde8d8d4afe52cbadeaef7fb73b119f2.jbx3AQPO5xfAg9ekBEOYdYqXIljWj5EaRYIlLbEjfq0
scenes-app-revenue-analytics-mrr-breakdown-modal--mrr-breakdown-modal--dark:
hash: v1.k794b7964.938ab51f3ea5a625ceb998fec10ef2a20f0a83858d872d2f79d7d7ccb54cc708.1hsX-zh8Cg_rIt1a86SahGk6XjfkO60W_XEDOCYvl0s
scenes-app-revenue-analytics-mrr-breakdown-modal--mrr-breakdown-modal--light:
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
index efce303249ea..68323a37ec63 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
@@ -23,7 +23,7 @@ import { axisLabel } from 'scenes/insights/aggregationAxisFormat'
import { AxisLabelsFilter } from 'scenes/insights/EditorFilters/AxisLabelsFilter'
import { HideIncompleteConversionWindowPeriodsFilter } from 'scenes/insights/EditorFilters/HideIncompleteConversionWindowPeriodsFilter'
import { HideWeekendsFilter } from 'scenes/insights/EditorFilters/HideWeekendsFilter'
-import { LegendPositionFilter } from 'scenes/insights/EditorFilters/LegendPositionFilter'
+import { LegendOptionsFilter } from 'scenes/insights/EditorFilters/LegendOptionsFilter'
import { LifecyclePercentagesFilter } from 'scenes/insights/EditorFilters/LifecyclePercentagesFilter'
import { LifecycleStackingFilter } from 'scenes/insights/EditorFilters/LifecycleStackingFilter'
import {
@@ -161,6 +161,9 @@ export function InsightDisplayConfig(): JSX.Element {
const showFunnelLegendConfig = isTrendsFunnel && hasBreakdownFilter(breakdownFilter)
const isLineGraph = isLineDisplay && !isCumulativeLineDisplay
const isLinearScale = !yAxisScaleType || yAxisScaleType === 'linear'
+ // The in-chart quill legend supports placement, so it gets a single "Legend" select
+ // (Hide + position) instead of the legacy show/hide checkbox.
+ const useQuillLegendOptions = quillLegendEnabled && isTrends && isLineDisplay
const {
showValuesOnSeries,
@@ -268,14 +271,9 @@ export function InsightDisplayConfig(): JSX.Element {
]
: []),
...(supportsBarValueStacking ? [{ label: () => <StackBreakdownFilter /> }] : []),
- ...(hasLegend || showFunnelLegendConfig
+ ...((hasLegend || showFunnelLegendConfig) && !useQuillLegendOptions
? [{ label: () => <ShowLegendFilter /> }]
: []),
- // The in-chart quill legend supports placement; the legacy side
- // legend doesn't, so only offer it for trends line/area/cumulative.
- ...(quillLegendEnabled && isTrends && isLineDisplay && showLegend
- ? [{ label: () => <LegendPositionFilter /> }]
- : []),
...(display === ChartDisplayType.ActionsPie
? [{ label: () => <ShowPieTotalFilter /> }]
: []),
@@ -296,6 +294,7 @@ export function InsightDisplayConfig(): JSX.Element {
? [{ label: () => <HideWeekendsFilter /> }]
: []),
...(showAnnotationsConfig ? [{ label: () => <ShowAnnotationsFilter /> }] : []),
+ ...(useQuillLegendOptions ? [{ label: () => <LegendOptionsFilter /> }] : []),
],
},
]
diff --git a/frontend/src/queries/nodes/InsightViz/InsightViz.scss b/frontend/src/queries/nodes/InsightViz/InsightViz.scss
index 57de4417a9df..be3cbdaee61f 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightViz.scss
+++ b/frontend/src/queries/nodes/InsightViz/InsightViz.scss
@@ -202,21 +202,30 @@
display: flex;
flex: 1;
flex-direction: column;
+ height: var(--insight-viz-min-height);
+
+ // Explicit height (not just min/max) so a top/bottom in-chart legend's max-height: 40% cap resolves —
+ // a flex-derived used size does not count, and without it the legend stretches the chart taller.
min-height: var(--insight-viz-min-height);
+ max-height: var(--insight-viz-min-height);
margin: 0.5rem;
.NotebookNode &,
.InsightCard &,
.ExportedInsight &,
.WebAnalyticsDashboard & {
+ height: auto;
min-height: auto;
+ max-height: none;
}
&--ActionsTable,
&--WorldMap,
&--BoldNumber,
&--Metric {
+ height: auto;
min-height: auto;
+ max-height: none;
margin: 0;
}
diff --git a/frontend/src/scenes/insights/EditorFilters/LegendOptionsFilter.tsx b/frontend/src/scenes/insights/EditorFilters/LegendOptionsFilter.tsx
new file mode 100644
index 000000000000..f2c45bb4c282
--- /dev/null
+++ b/frontend/src/scenes/insights/EditorFilters/LegendOptionsFilter.tsx
@@ -0,0 +1,42 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonCheckbox, LemonSelect } from '@posthog/lemon-ui'
+
+import { insightLogic } from 'scenes/insights/insightLogic'
+
+import type { TrendsFilter } from '~/queries/schema/schema-general'
+
+import { insightVizDataLogic } from '../insightVizDataLogic'
+
+type LegendPosition = NonNullable<TrendsFilter['legendPosition']>
+
+const POSITION_OPTIONS: { value: LegendPosition; label: string }[] = [
+ { value: 'bottom', label: 'Bottom' },
+ { value: 'top', label: 'Top' },
+ { value: 'left', label: 'Left' },
+ { value: 'right', label: 'Right' },
+]
+
+export function LegendOptionsFilter(): JSX.Element {
+ const { insightProps } = useValues(insightLogic)
+ const { showLegend, legendPosition } = useValues(insightVizDataLogic(insightProps))
+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))
+
+ return (
+ <div className="flex items-center justify-between gap-2 p-1 px-2">
+ <LemonCheckbox
+ onChange={(checked) => updateInsightFilter({ showLegend: checked })}
+ checked={!!showLegend}
+ label={<span className="font-normal">Show legend</span>}
+ size="small"
+ />
+ <LemonSelect
+ size="small"
+ value={(legendPosition ?? 'bottom') as LegendPosition}
+ options={POSITION_OPTIONS}
+ disabledReason={!showLegend ? 'Enable the legend to set its position' : undefined}
+ onChange={(position) => updateInsightFilter({ legendPosition: position })}
+ />
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/insights/EditorFilters/LegendPositionFilter.tsx b/frontend/src/scenes/insights/EditorFilters/LegendPositionFilter.tsx
deleted file mode 100644
index 73023497cadd..000000000000
--- a/frontend/src/scenes/insights/EditorFilters/LegendPositionFilter.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { LemonSelect } from '@posthog/lemon-ui'
-
-import { insightLogic } from 'scenes/insights/insightLogic'
-
-import type { TrendsFilter } from '~/queries/schema/schema-general'
-
-import { insightVizDataLogic } from '../insightVizDataLogic'
-
-type LegendPosition = NonNullable<TrendsFilter['legendPosition']>
-
-const OPTIONS: { value: LegendPosition; label: string }[] = [
- { value: 'bottom', label: 'Bottom' },
- { value: 'top', label: 'Top' },
- { value: 'left', label: 'Left' },
- { value: 'right', label: 'Right' },
-]
-
-export function LegendPositionFilter(): JSX.Element {
- const { insightProps } = useValues(insightLogic)
- const { legendPosition } = useValues(insightVizDataLogic(insightProps))
- const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))
-
- return (
- <div className="flex items-center justify-between gap-2 p-1 px-2">
- <span className="font-normal">Legend position</span>
- <LemonSelect
- size="small"
- value={legendPosition ?? 'bottom'}
- options={OPTIONS}
- onChange={(value) => updateInsightFilter({ legendPosition: value as LegendPosition })}
- />
- </div>
- )
-}
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 9518398c9f8b..0dc77c36d2d6 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -72,7 +72,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- `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.
- 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).
+- `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.
- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order) and formats values with `valueFormatter` so they match the on-chart labels' units; pass your own `tooltip` to override. (`DefaultTooltip` itself takes an optional `valueFormatter` for the same reason — without it values fall back to `toLocaleString`.) Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`; `sparklineDashedFromIndex` dashes the sparkline from that index onward (e.g. an in-progress trailing period). `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point). `changeTooltip` shows a styled hover tooltip (floating-ui, using the host's tooltip surface tokens with chart-surface fallbacks) on the change pill (e.g. to spell out what the resting comparison is).
- `TimeSeriesComboChart` wraps `ComboChart` the way `TimeSeriesLineChart`/`TimeSeriesBarChart` wrap their base charts: `config.xAxis`/`config.yAxis` (date tick formatter, y-format, scale, grid), `config.goalLines` (off-scale targets stretch the value axis via `ComboChart`'s `valueDomain`), `config.legend` (click-to-toggle), and `config.valueLabels`. Per-series `type` (`'bar' | 'line' | 'area'`) drives rendering; `barLayout` (`'stacked' | 'grouped'`) and right-axis series (`yAxisId: 'right'`) carry over from `ComboChart`. `ComboChart` itself now also honors `valueDomain` (primary axis only) and `showAxisLines`.
diff --git a/packages/quill/packages/charts/src/components/Legend/ChartLegendLayout.tsx b/packages/quill/packages/charts/src/components/Legend/ChartLegendLayout.tsx
index d286b7fa1d04..b8747584e322 100644
--- a/packages/quill/packages/charts/src/components/Legend/ChartLegendLayout.tsx
+++ b/packages/quill/packages/charts/src/components/Legend/ChartLegendLayout.tsx
@@ -28,7 +28,16 @@ export function ChartLegendLayout({
}: ChartLegendLayoutProps): React.ReactElement {
const isRow = position === 'left' || position === 'right'
const legendFirst = position === 'top' || position === 'left'
- const legendSlot = legend ? <div className="flex-none shrink-0">{legend}</div> : null
+ // Side legends stretch to the chart height — a % max-height no-ops without an explicit ancestor height,
+ // which top/bottom's max-h-[40%] still needs. `justify-center-safe` keeps short side legends centered
+ // yet scrollable (plain center would push the top rows past the scroll origin).
+ const legendClass = isRow
+ ? 'flex flex-col self-stretch max-w-[45%] overflow-y-auto justify-center-safe'
+ : 'max-h-[40%] overflow-y-auto'
+
+ const legendSlot = legend ? (
+ <div className={`flex-none shrink-0 min-h-0 min-w-0 ${legendClass}`}>{legend}</div>
+ ) : null
// `flex flex-col` so the inner chart's `flex: 1` resolves; `self-stretch` so the chart fills the cross axis regardless of `align` (which then only affects the legend).
const chartSlot = <div className="flex flex-col flex-1 min-w-0 min-h-0 self-stretch">{children}</div>
return (
diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsx
index 7167c0751386..a40d52a67767 100644
--- a/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsx
+++ b/packages/quill/packages/charts/src/components/Legend/Legend.stories.tsx
@@ -69,6 +69,26 @@ export const ManyItemsWraps: Story = {
),
}
+const LONG_LABELS: LegendItem[] = [
+ { key: 'a', label: 'pageview · Chrome · United States · organic search', color: '#22c55e' },
+ { key: 'b', label: 'pageview · Safari · United Kingdom · paid social', color: '#3b82f6' },
+ { key: 'c', label: 'Short one', color: '#f97316' },
+]
+
+// Long labels clip to a max width with an ellipsis; the full text is on the row's `title` tooltip.
+export const LongLabelsTruncate: Story = {
+ render: () => (
+ <div className="flex flex-col gap-4">
+ <div className="w-[480px] border border-border rounded p-2">
+ <Legend items={LONG_LABELS} />
+ </div>
+ <div className="w-[200px] border border-border rounded p-2">
+ <Legend items={LONG_LABELS} orientation="vertical" align="start" />
+ </div>
+ </div>
+ ),
+}
+
function ChartLegendStory({
show = true,
position,
diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx
index 8901e64a6c37..38846138bf0e 100644
--- a/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx
+++ b/packages/quill/packages/charts/src/components/Legend/Legend.test.tsx
@@ -64,6 +64,15 @@ describe('Legend', () => {
expect(onClick).toHaveBeenCalledWith('returning')
})
+ it('truncates each label and exposes the full name via a native title tooltip', () => {
+ const long = 'Breakdown value with an extremely long name that would otherwise crush the plot'
+ const { container } = render(<Legend items={[{ key: 'a', label: long, color: '#000' }]} />)
+ const label = container.querySelector<HTMLElement>(`[title="${long}"]`)!
+ expect(label.textContent).toBe(long)
+ expect(label.className).toContain('truncate')
+ expect(label.style.maxWidth).toBe('180px')
+ })
+
it('dims only rows whose key is in hiddenKeys', () => {
const { container } = render(<Legend items={ITEMS} hiddenKeys={['returning']} />)
const dimmedLabels = rowsOf(container)
diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.tsx
index 9b3761815bb0..543cabf7c4ce 100644
--- a/packages/quill/packages/charts/src/components/Legend/Legend.tsx
+++ b/packages/quill/packages/charts/src/components/Legend/Legend.tsx
@@ -22,10 +22,12 @@ export interface LegendProps {
renderItem?: (defaultNode: React.ReactNode, item: LegendItem) => React.ReactNode
}
-const ALIGN_CLASS = {
- start: 'justify-start',
- center: 'justify-center',
- end: 'justify-end',
+// Position a horizontal legend via auto-margins on a fit-content box, not `justify-content`: rows keep a
+// shared left edge (so a wrapped legend is a clean grid, not ragged) while the block still honors `align`.
+const BLOCK_ALIGN_CLASS = {
+ start: 'mr-auto',
+ center: 'mx-auto',
+ end: 'ml-auto',
} as const
export function Legend({
@@ -42,9 +44,14 @@ export function Legend({
return null
}
const hidden = hiddenKeys?.length ? new Set(hiddenKeys) : null
- const layout = orientation === 'horizontal' ? 'flex-row flex-wrap gap-x-3 gap-y-1' : 'flex-col gap-1'
+ // Stack from the start edge (justify-start) so the legend scrolls cleanly when it overflows its slot;
+ // centering would push the leading rows past the scroll origin. Horizontal adds the fit-content box.
+ const layout =
+ orientation === 'horizontal'
+ ? `flex-row flex-wrap gap-x-3 gap-y-1 justify-start w-fit max-w-full ${BLOCK_ALIGN_CLASS[align]}`
+ : 'flex-col gap-1 justify-start'
return (
- <div className={`flex ${layout} ${ALIGN_CLASS[align]} ${className ?? ''}`} data-attr={dataAttr}>
+ <div className={`flex ${layout} ${className ?? ''}`} data-attr={dataAttr}>
{items.map((item) => {
const dimmed = hidden?.has(item.key) ? ' opacity-40' : ''
const rowClass = `inline-flex items-center gap-1.5 text-xs leading-none${dimmed}`
@@ -55,7 +62,9 @@ export function Legend({
className="inline-block w-2.5 h-2.5 rounded-sm shrink-0"
style={{ backgroundColor: item.color }}
/>
- <span className="truncate">{item.label}</span>
+ <span className="truncate" style={{ maxWidth: 180 }} title={item.label}>
+ {item.label}
+ </span>
{item.secondaryLabel != null && item.secondaryLabel !== '' && (
<span className="shrink-0 text-muted" data-attr="hog-chart-legend-secondary">
{item.secondaryLabel}
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.test.tsx b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.test.tsx
index 072dc0e74243..336a49360a03 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.test.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.test.tsx
@@ -260,9 +260,10 @@ describe('FunnelLineChart', () => {
await screen.findByRole('img', { name: /chart with/i })
const legend = await screen.findByTestId('funnel-line-legend')
- const swatchColors = Array.from(legend.querySelectorAll<HTMLElement>('span[style]')).map(
- (el) => el.style.backgroundColor
- )
+ // The label span also carries an inline style now (max-width), so keep only the colored swatches.
+ const swatchColors = Array.from(legend.querySelectorAll<HTMLElement>('span[style]'))
+ .map((el) => el.style.backgroundColor)
+ .filter(Boolean)
expect(swatchColors).toHaveLength(2)
expect(new Set(swatchColors).size).toBe(2)
})