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(insights): share the chart legend series menu across every chart (#82733)

Sam Penningtonf5fef32bb616
diff --git a/frontend/jest.polyfills.js b/frontend/jest.polyfills.js
index e0aab56781e1..396488789a00 100644
--- a/frontend/jest.polyfills.js
+++ b/frontend/jest.polyfills.js
@@ -81,3 +81,36 @@ if (typeof globalThis.performance?.markResourceTiming !== 'function') {
const { fetch, Request, Response, Headers, FormData } = require('undici')
define({ fetch, Request, Response, Headers, FormData })
+
+// jsdom ships no DOMRect, which Radix's ContextMenu constructs to anchor its content at the cursor.
+// Without it, right-clicking a trigger under jest throws before the menu ever mounts.
+if (typeof globalThis.DOMRect !== 'function') {
+ class DOMRect {
+ constructor(x = 0, y = 0, width = 0, height = 0) {
+ this.x = x
+ this.y = y
+ this.width = width
+ this.height = height
+ }
+ get top() {
+ return this.height < 0 ? this.y + this.height : this.y
+ }
+ get bottom() {
+ return this.height < 0 ? this.y : this.y + this.height
+ }
+ get left() {
+ return this.width < 0 ? this.x + this.width : this.x
+ }
+ get right() {
+ return this.width < 0 ? this.x : this.x + this.width
+ }
+ static fromRect(rect = {}) {
+ return new DOMRect(rect.x, rect.y, rect.width, rect.height)
+ }
+ toJSON() {
+ const { x, y, width, height, top, right, bottom, left } = this
+ return { x, y, width, height, top, right, bottom, left }
+ }
+ }
+ define({ DOMRect })
+}
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 2068d468beb8..dd2245c63fe4 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -336,6 +336,14 @@ snapshots:
hash: v1.k794b7964.0102b5932e02a20b3e9ebe64e598044973f2ea5e8311fbc60f2bc4d4ac71dd34.WWzoCG5jIHDxccStvfV99L1mEDBwUR-s5gv1Ra53etE
components-cards-text-card--word-art--light:
hash: v1.k794b7964.bbfbdf1c0cb4a9c5e2ebd29ea6d06eb292a761c70b1936ff7bea8a2e5294c9ef.cClgUmOs2MuzU2HfkFbT4TxQEVcQ3U2ipOGtvtqIHoo
+ components-chart-legend-series-menu--default--dark:
+ hash: v1.k794b7964.58a504304a7e9337e3eae5fb721ff54d83ff341332a71c8d385c691430a9cc45.RKtG6Jsas-E9f4HTlZCwlLYbPJo7cYWp3XRN_XKB8hU
+ components-chart-legend-series-menu--default--light:
+ hash: v1.k794b7964.3f5a2420c65b029ee7486f57ae9b8a0e2e85a11ea6ce3a1642477d21660ac4a3.GUBu6ybHDTS3O4jDJgNAE2jrSqC-V1kOrvF84bHRri8
+ components-chart-legend-series-menu--single-series--dark:
+ hash: v1.k794b7964.c5168eae4c3faf5aedbd64a29598f2d0a972f1864d5051dc8f7567a960777c7b.wtf7NrB3yC_1-AcfkjfR33aOe81OdBTQcI3GITUGcC0
+ components-chart-legend-series-menu--single-series--light:
+ hash: v1.k794b7964.45544c43c187fd1d1fc7b204e7c33c7e422c5c56838cac44e5d63318c7f5e283.phbzfcS5A5m2LHaspjABfv-I6FPQ1-LnsCFRwyX81uQ
components-compact-list--compact-list--dark:
hash: v1.k794b7964.59d9b22dc4c1fabb38cfa1c8072b3f6e3e4140bfddef6160e568f935c0ba7f29.aeZmv2PM9H27yaixZr0lFX-5hBEr1ET0-8F-DJP_QS4
components-compact-list--compact-list--light:
@@ -6577,7 +6585,7 @@ snapshots:
scenes-app-insights-error-empty-states--query-server-error--light:
hash: v1.k794b7964.2b569e38b9188a1b6651645db04fc1861a1fbca67c8a36c59a717d949b3e9cb6.6wC07yLeoObvqkr-b3JIDgOLa-iqmpa8aO-eLLzWoEw
scenes-app-insights-error-empty-states--server-error--dark:
- hash: v1.k794b7964.d4fc60a8e2dcacd414609ab296220b7d67381644f361e874c89790ad0166ac72.AvZwp_QBR6TzTD2jw9dj4M96gEsNdZ05GpMMfFp9RjQ
+ hash: v1.k794b7964.c78c9eaddad034d4747bccc025468e045b9e641e8f70daa75c428ac94def566c.WSvKXlMMIMORSx1W_7pTEH4AQMQUtr_4cSHSVfBGl_0
scenes-app-insights-error-empty-states--server-error--light:
hash: v1.k794b7964.79b5b63d2b650cc4f924ddf5a268fa8ef317b61002f878ba729b43114ff2458c.TeYRm6KIzF4y5I9oHWuR5KmccQgDWrUc9JHk9Hq0p4o
scenes-app-insights-error-empty-states--validation-error--dark:
diff --git a/frontend/src/lib/components/ChartLegendSeriesMenu/ChartLegendSeriesMenu.stories.tsx b/frontend/src/lib/components/ChartLegendSeriesMenu/ChartLegendSeriesMenu.stories.tsx
new file mode 100644
index 000000000000..9e93a9aa028d
--- /dev/null
+++ b/frontend/src/lib/components/ChartLegendSeriesMenu/ChartLegendSeriesMenu.stories.tsx
@@ -0,0 +1,86 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import { useState } from 'react'
+
+import { ChartLegendSeriesMenu } from './ChartLegendSeriesMenu'
+
+const SERIES = [
+ { key: 'pageviews', label: 'Pageviews', color: 'var(--data-color-1)' },
+ { key: 'signups', label: 'Signups', color: 'var(--data-color-2)' },
+ { key: 'purchases', label: 'Purchases', color: 'var(--data-color-3)' },
+]
+
+type Story = StoryObj<typeof ChartLegendSeriesMenu>
+const meta: Meta<typeof ChartLegendSeriesMenu> = {
+ title: 'Components/Chart legend series menu',
+ component: ChartLegendSeriesMenu,
+ tags: ['autodocs'],
+}
+export default meta
+
+/** A stand-in for the real quill chart legend: same click model (plain click isolates, ⌘/Ctrl-click
+ * adds), so the menu's labels can be exercised without mounting a chart. */
+function LegendHarness({ items }: { items: typeof SERIES }): JSX.Element {
+ const [hidden, setHidden] = useState<string[]>([])
+ const rowKeys = items.map((item) => item.key)
+ const visibleCount = rowKeys.filter((key) => !hidden.includes(key)).length
+
+ const toggle = (key: string): void =>
+ setHidden((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]))
+
+ const isolate = (key: string): void => {
+ const others = rowKeys.filter((k) => k !== key)
+ const isolated = !hidden.includes(key) && others.every((k) => hidden.includes(k))
+ setHidden(isolated ? [] : others)
+ }
+
+ return (
+ <div className="flex w-[420px] flex-row gap-3 rounded border border-primary bg-surface-primary p-3">
+ {items.map((item) => {
+ const isHidden = hidden.includes(item.key)
+ return (
+ <ChartLegendSeriesMenu
+ key={item.key}
+ seriesLabel={item.label}
+ seriesColor={item.color}
+ isHidden={isHidden}
+ isOnlyVisible={rowKeys.length > 1 && visibleCount === 1 && !isHidden}
+ areAllVisible={hidden.length === 0}
+ canIsolate={rowKeys.length > 1}
+ onToggle={() => toggle(item.key)}
+ onIsolate={() => isolate(item.key)}
+ onToggleAll={() => setHidden(hidden.length === 0 ? rowKeys : [])}
+ >
+ <button
+ type="button"
+ className={`inline-flex select-none items-center gap-1.5 border-0 bg-transparent p-0 text-xs ${
+ isHidden ? 'opacity-40' : ''
+ }`}
+ onClick={(event) =>
+ event.metaKey || event.ctrlKey || rowKeys.length === 1
+ ? toggle(item.key)
+ : isolate(item.key)
+ }
+ >
+ <span
+ aria-hidden="true"
+ // eslint-disable-next-line react/forbid-dom-props -- swatch takes the series color
+ style={{ backgroundColor: item.color }}
+ className="size-2.5 rounded-sm"
+ />
+ {item.label}
+ </button>
+ </ChartLegendSeriesMenu>
+ )
+ })}
+ </div>
+ )
+}
+
+export const Default: Story = {
+ render: () => <LegendHarness items={SERIES} />,
+}
+
+/** A single-series legend drops the isolate and hide-all rows — there is nothing to isolate from. */
+export const SingleSeries: Story = {
+ render: () => <LegendHarness items={SERIES.slice(0, 1)} />,
+}
diff --git a/frontend/src/lib/components/ChartLegendSeriesMenu/ChartLegendSeriesMenu.test.tsx b/frontend/src/lib/components/ChartLegendSeriesMenu/ChartLegendSeriesMenu.test.tsx
new file mode 100644
index 000000000000..6432eddb545b
--- /dev/null
+++ b/frontend/src/lib/components/ChartLegendSeriesMenu/ChartLegendSeriesMenu.test.tsx
@@ -0,0 +1,108 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { ChartLegendSeriesMenu, type ChartLegendSeriesMenuProps } from './ChartLegendSeriesMenu'
+
+const BASE: Omit<ChartLegendSeriesMenuProps, 'children'> = {
+ seriesLabel: 'Pageviews',
+ seriesColor: '#1d4aff',
+ isHidden: false,
+ isOnlyVisible: false,
+ areAllVisible: true,
+ canIsolate: true,
+ onToggle: jest.fn(),
+ onIsolate: jest.fn(),
+ onToggleAll: jest.fn(),
+}
+
+function openMenu(props: Partial<ChartLegendSeriesMenuProps> = {}): void {
+ const { container } = render(
+ <ChartLegendSeriesMenu {...BASE} {...props}>
+ <button type="button" data-attr="legend-row">
+ Pageviews
+ </button>
+ </ChartLegendSeriesMenu>
+ )
+ fireEvent.contextMenu(container.querySelector('[data-attr="legend-row"]')!)
+}
+
+function menuRowText(): (string | null)[] {
+ return screen.getAllByRole('menuitem').map((item) => item.textContent)
+}
+
+/** Text of every row carrying a gesture hint, so a hint that vanishes or lands on the wrong row shows up. */
+function gestureRowText(): (string | null)[] {
+ return Array.from(document.querySelectorAll('[data-attr="chart-legend-menu-gesture"]')).map(
+ (hint) => hint.closest('[role="menuitem"]')!.textContent
+ )
+}
+
+describe('ChartLegendSeriesMenu', () => {
+ // The menu content renders in a portal, so an unmounted case would otherwise leave its rows
+ // behind and the next one would match both.
+ afterEach(cleanup)
+
+ // Gesture hints are off by default here, so a row's text is exactly its label; the cases below
+ // that turn them on assert the appended hint.
+ it.each([
+ {
+ name: 'offers isolating and hiding when every series is visible',
+ props: {},
+ expected: ['Show only this series', 'Hide this series', 'Hide all series'],
+ },
+ {
+ name: 'offers restoring everything from the isolated series, without repeating show-all',
+ props: { isOnlyVisible: true, areAllVisible: false },
+ expected: ['Show all series', 'Hide this series'],
+ },
+ {
+ name: 'offers showing a hidden series back',
+ props: { isHidden: true, areAllVisible: false },
+ expected: ['Show only this series', 'Show this series', 'Show all series'],
+ },
+ {
+ name: 'drops the bulk actions on a single-series legend',
+ props: { canIsolate: false },
+ expected: ['Hide this series'],
+ },
+ ])('$name', ({ props, expected }) => {
+ openMenu(props)
+
+ expect(menuRowText()).toEqual(expected)
+ })
+
+ it('teaches the click gestures, on the rows those gestures reach', () => {
+ openMenu({ showGestureHints: true })
+
+ // KeyboardShortcut renders the platform modifier, which is `ctrl` under jsdom.
+ expect(gestureRowText()).toEqual(['Show only this seriesclick', 'Hide this seriesctrlclick'])
+ })
+
+ it('advertises no gesture on a legend whose rows only toggle', () => {
+ openMenu()
+
+ expect(gestureRowText()).toEqual([])
+ })
+
+ it('names the series the menu acts on, since rows sit close together', () => {
+ openMenu({ seriesLabel: 'Signups' })
+
+ expect(screen.getByTitle('Signups')).toBeInTheDocument()
+ })
+
+ it.each([
+ { label: 'Show only this series', handler: 'onIsolate' as const },
+ { label: 'Hide this series', handler: 'onToggle' as const },
+ { label: 'Hide all series', handler: 'onToggleAll' as const },
+ ])('runs $handler when "$label" is picked', ({ label, handler }) => {
+ const handlers = { onToggle: jest.fn(), onIsolate: jest.fn(), onToggleAll: jest.fn() }
+ openMenu(handlers)
+
+ const item = screen.getAllByRole('menuitem').find((el) => el.textContent?.startsWith(label))!
+ fireEvent.click(item)
+
+ expect(handlers[handler]).toHaveBeenCalledTimes(1)
+ expect(Object.values(handlers).filter((fn) => fn.mock.calls.length > 0)).toHaveLength(1)
+ })
+})
diff --git a/frontend/src/lib/components/ChartLegendSeriesMenu/ChartLegendSeriesMenu.tsx b/frontend/src/lib/components/ChartLegendSeriesMenu/ChartLegendSeriesMenu.tsx
new file mode 100644
index 000000000000..48512e2983c9
--- /dev/null
+++ b/frontend/src/lib/components/ChartLegendSeriesMenu/ChartLegendSeriesMenu.tsx
@@ -0,0 +1,169 @@
+import { ReactNode } from 'react'
+
+import { IconEye, IconHide, IconTarget } from '@posthog/icons'
+
+import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcut'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuGroup,
+ ContextMenuItem,
+ ContextMenuSeparator,
+ ContextMenuTrigger,
+} from 'lib/ui/ContextMenu/ContextMenu'
+
+export interface ChartLegendSeriesMenuProps {
+ /** The series the menu acts on. Shown in the menu header so the target is never ambiguous —
+ * legend rows sit close together and a right-click can easily land on the neighbor. */
+ seriesLabel: string
+ seriesColor: string
+ isHidden: boolean
+ /** This series is the only visible one, so isolating it again restores every series. */
+ isOnlyVisible: boolean
+ areAllVisible: boolean
+ /** False for a single-series legend, where isolating and hiding everything mean nothing. */
+ canIsolate: boolean
+ onToggle: () => void
+ onIsolate: () => void
+ onToggleAll: () => void
+ /** Advertise the click gestures that reach these actions without the menu. Only true for the
+ * in-chart quill legend — the legend table's rows are checkboxes with no isolate gesture. */
+ showGestureHints?: boolean
+ children: ReactNode
+}
+
+/** Right-click menu for one chart legend row: isolate this series, toggle it, or toggle all of
+ * them. Styled to match the charts' own floating panels (popover surface, 12px text, tight radius)
+ * rather than the app's larger menus, so it reads as part of the chart it hangs off.
+ *
+ * Purely presentational — the caller owns what each action does, and hands over the visibility
+ * state the labels switch on. */
+export function ChartLegendSeriesMenu({
+ seriesLabel,
+ seriesColor,
+ isHidden,
+ isOnlyVisible,
+ areAllVisible,
+ canIsolate,
+ onToggle,
+ onIsolate,
+ onToggleAll,
+ showGestureHints = false,
+ children,
+}: ChartLegendSeriesMenuProps): JSX.Element {
+ // Hiding all series is offered as its counterpart, "show all", once anything is hidden — but an
+ // isolated row already offers exactly that above, so the row would just repeat itself.
+ const showToggleAll = canIsolate && !isOnlyVisible
+
+ return (
+ <ContextMenu>
+ <Tooltip
+ title={<ChartLegendSeriesMenuHint canIsolate={canIsolate} showGestureHints={showGestureHints} />}
+ delayMs={500}
+ >
+ <ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
+ </Tooltip>
+ <ContextMenuContent className="click-outside-block w-fit max-w-[260px] min-w-[180px] rounded-sm bg-surface-popover text-xs">
+ <div className="flex items-center gap-1.5 px-2 pt-1.5 pb-1 text-xs">
+ <span
+ aria-hidden="true"
+ // eslint-disable-next-line react/forbid-dom-props -- the swatch takes the series' own color
+ style={{ backgroundColor: seriesColor }}
+ className="size-2.5 shrink-0 rounded-sm"
+ />
+ <span className="truncate font-semibold" title={seriesLabel}>
+ {seriesLabel}
+ </span>
+ </div>
+ {/* The separator's default -mx-1 assumes a padded menu; here it overflows instead,
+ which makes ScrollableShadows paint a scroll shadow down the right edge. */}
+ <ContextMenuSeparator className="mx-0" />
+ <ContextMenuGroup>
+ {canIsolate && (
+ <ContextMenuItem asChild>
+ <ButtonPrimitive
+ menuItem
+ size="xs"
+ className="text-xs"
+ onClick={onIsolate}
+ data-attr="insight-legend-hide-other-series"
+ >
+ <IconTarget />
+ {isOnlyVisible ? 'Show all series' : 'Show only this series'}
+ {showGestureHints && <MenuItemGesture>click</MenuItemGesture>}
+ </ButtonPrimitive>
+ </ContextMenuItem>
+ )}
+ <ContextMenuItem asChild>
+ <ButtonPrimitive
+ menuItem
+ size="xs"
+ className="text-xs"
+ onClick={onToggle}
+ data-attr="insight-legend-toggle-series"
+ >
+ {isHidden ? <IconEye /> : <IconHide />}
+ {isHidden ? 'Show this series' : 'Hide this series'}
+ {showGestureHints && canIsolate && (
+ <MenuItemGesture>
+ <KeyboardShortcut command minimal />
+ click
+ </MenuItemGesture>
+ )}
+ </ButtonPrimitive>
+ </ContextMenuItem>
+ {showToggleAll && (
+ <ContextMenuItem asChild>
+ <ButtonPrimitive
+ menuItem
+ size="xs"
+ className="text-xs"
+ onClick={onToggleAll}
+ data-attr="insight-legend-toggle-all-series"
+ >
+ {areAllVisible ? <IconHide /> : <IconEye />}
+ {areAllVisible ? 'Hide all series' : 'Show all series'}
+ </ButtonPrimitive>
+ </ContextMenuItem>
+ )}
+ </ContextMenuGroup>
+ </ContextMenuContent>
+ </ContextMenu>
+ )
+}
+
+/** Right-aligned muted note showing the gesture that runs a menu item, so the menu teaches the
+ * click shortcuts instead of being the only way to reach them. */
+function MenuItemGesture({ children }: { children: ReactNode }): JSX.Element {
+ return (
+ <span
+ className="ml-auto flex shrink-0 items-center gap-0.5 pl-2 text-secondary"
+ data-attr="chart-legend-menu-gesture"
+ >
+ {children}
+ </span>
+ )
+}
+
+function ChartLegendSeriesMenuHint({
+ canIsolate,
+ showGestureHints,
+}: {
+ canIsolate: boolean
+ showGestureHints: boolean
+}): JSX.Element {
+ if (!showGestureHints) {
+ return <>Right-click for options.</>
+ }
+ if (!canIsolate) {
+ return <>Click to hide this series. Right-click for options.</>
+ }
+ return (
+ <>
+ Click to show only this series, <KeyboardShortcut command minimal />
+ -click to add more. Right-click for options.
+ </>
+ )
+}
diff --git a/frontend/src/lib/components/ChartLegendSeriesMenu/captureLegendMenuAction.ts b/frontend/src/lib/components/ChartLegendSeriesMenu/captureLegendMenuAction.ts
new file mode 100644
index 000000000000..a7e748b099cf
--- /dev/null
+++ b/frontend/src/lib/components/ChartLegendSeriesMenu/captureLegendMenuAction.ts
@@ -0,0 +1,22 @@
+import posthog from 'posthog-js'
+
+interface LegendMenuAction {
+ action: string
+ /** Which row of the menu was used. */
+ source: string
+ /** Which chart the legend belongs to, e.g. 'trends' or 'sql'. */
+ surface: string
+ seriesCount: number
+}
+
+/** Reports a chart legend menu action. Shared by the quill legend menu and the legacy insight
+ * legend table so both surfaces land in one event. */
+export function captureLegendMenuAction({ action, source, surface, seriesCount }: LegendMenuAction): void {
+ // pinned: analytics event and property names — renaming breaks existing insights
+ posthog.capture('insight_legend_context_menu', {
+ action,
+ source,
+ surface,
+ series_count: seriesCount,
+ })
+}
diff --git a/frontend/src/lib/components/ChartLegendSeriesMenu/useChartLegendSeriesMenu.tsx b/frontend/src/lib/components/ChartLegendSeriesMenu/useChartLegendSeriesMenu.tsx
new file mode 100644
index 000000000000..9545ba4f0075
--- /dev/null
+++ b/frontend/src/lib/components/ChartLegendSeriesMenu/useChartLegendSeriesMenu.tsx
@@ -0,0 +1,65 @@
+import { useCallback } from 'react'
+
+import type { ChartLegendConfig } from '@posthog/quill-charts'
+
+import { captureLegendMenuAction } from './captureLegendMenuAction'
+import { ChartLegendSeriesMenu } from './ChartLegendSeriesMenu'
+
+interface UseChartLegendSeriesMenuOptions {
+ /** Which chart the legend belongs to, e.g. 'trends' or 'sql'. Reported with the menu's events. */
+ surface: string
+ seriesCount: number
+}
+
+/** Attaches {@link ChartLegendSeriesMenu} to every row of a quill chart's built-in legend. Pass the
+ * result as `config.legend.renderItem` — quill hands each row its own visibility state and actions,
+ * so this works the same on a controlled legend (trends, persisting into the query) and an
+ * uncontrolled one (SQL insights, in-chart state). */
+export function useChartLegendSeriesMenu({
+ surface,
+ seriesCount,
+}: UseChartLegendSeriesMenuOptions): NonNullable<ChartLegendConfig['renderItem']> {
+ return useCallback(
+ (node, item, controls) => (
+ <ChartLegendSeriesMenu
+ seriesLabel={item.label}
+ seriesColor={item.color}
+ isHidden={controls.isHidden}
+ isOnlyVisible={controls.isOnlyVisible}
+ areAllVisible={controls.areAllVisible}
+ canIsolate={controls.canIsolate}
+ showGestureHints
+ onToggle={() => {
+ captureLegendMenuAction({
+ action: controls.isHidden ? 'show_series' : 'hide_series',
+ source: 'toggle_row',
+ surface,
+ seriesCount,
+ })
+ controls.toggle()
+ }}
+ onIsolate={() => {
+ captureLegendMenuAction({
+ action: controls.isOnlyVisible ? 'show_all_series' : 'hide_other_series',
+ source: 'isolate_row',
+ surface,
+ seriesCount,
+ })
+ controls.isolate()
+ }}
+ onToggleAll={() => {
+ captureLegendMenuAction({
+ action: controls.areAllVisible ? 'hide_all_series' : 'show_all_series',
+ source: 'toggle_all_row',
+ surface,
+ seriesCount,
+ })
+ controls.toggleAll()
+ }}
+ >
+ {node}
+ </ChartLegendSeriesMenu>
+ ),
+ [surface, seriesCount]
+ )
+}
diff --git a/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx b/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx
index d27dfced99ce..974294541918 100644
--- a/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx
+++ b/frontend/src/lib/components/InsightLegend/InsightLegendRow.tsx
@@ -1,8 +1,9 @@
import { useActions, useValues } from 'kea'
-import posthog from 'posthog-js'
import { useEffect, useRef } from 'react'
import { getSeriesBackgroundColor } from 'lib/colors'
+import { captureLegendMenuAction } from 'lib/components/ChartLegendSeriesMenu/captureLegendMenuAction'
+import { ChartLegendSeriesMenu } from 'lib/components/ChartLegendSeriesMenu/ChartLegendSeriesMenu'
import { InsightLabel } from 'lib/components/InsightLabel'
import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
@@ -17,8 +18,6 @@ import { cohortsModel } from '~/models/cohortsModel'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
import { ChartDisplayType } from '~/types'
-import { InsightLegendRowContextMenu } from './InsightLegendRowContextMenu'
-
type InsightLegendRowProps = {
item: IndexedTrendResult
readOnly?: boolean
@@ -40,7 +39,6 @@ export function InsightLegendRow({ item, readOnly = false }: InsightLegendRowPro
resultCustomizationBy,
indexedResults,
areAllSeriesVisible,
- showLegendIsolateSeriesItem,
legendSeriesIsolationMenuEligible,
getIsOnlyVisibleSeriesInLegend,
} = useValues(trendsDataLogic(insightProps))
@@ -127,29 +125,43 @@ export function InsightLegendRow({ item, readOnly = false }: InsightLegendRowPro
}
return (
- <InsightLegendRowContextMenu
- areAllSeriesVisible={areAllSeriesVisible}
- showLegendIsolateSeriesItem={showLegendIsolateSeriesItem}
+ <ChartLegendSeriesMenu
+ seriesLabel={item.label}
+ seriesColor={mainColor}
isHidden={isHidden}
- isOnlyThisVisible={isOnlyThisVisible}
- onToggleOtherSeries={() => {
- posthog.capture('insight_legend_context_menu', {
+ isOnlyVisible={isOnlyThisVisible}
+ areAllVisible={areAllSeriesVisible}
+ canIsolate={legendSeriesIsolationMenuEligible}
+ showGestureHints={false}
+ onToggle={() => {
+ captureLegendMenuAction({
+ action: isHidden ? 'show_series' : 'hide_series',
+ source: 'toggle_row',
+ surface: 'insight_legend_table',
+ seriesCount: indexedResults.length,
+ })
+ toggleResultHidden(item)
+ }}
+ onIsolate={() => {
+ captureLegendMenuAction({
action: isOnlyThisVisible ? 'show_all_series' : 'hide_other_series',
source: 'isolate_row',
- series_count: indexedResults.length,
+ surface: 'insight_legend_table',
+ seriesCount: indexedResults.length,
})
toggleOtherSeriesHidden(item)
}}
- onToggleAllSeries={() => {
- posthog.capture('insight_legend_context_menu', {
+ onToggleAll={() => {
+ captureLegendMenuAction({
action: areAllSeriesVisible ? 'hide_all_series' : 'show_all_series',
source: 'toggle_all_row',
- series_count: indexedResults.length,
+ surface: 'insight_legend_table',
+ seriesCount: indexedResults.length,
})
toggleAllResultsHidden(indexedResults, areAllSeriesVisible)
}}
>
{row}
- </InsightLegendRowContextMenu>
+ </ChartLegendSeriesMenu>
)
}
diff --git a/frontend/src/lib/components/InsightLegend/InsightLegendRowContextMenu.tsx b/frontend/src/lib/components/InsightLegend/InsightLegendRowContextMenu.tsx
deleted file mode 100644
index e14c9cb83383..000000000000
--- a/frontend/src/lib/components/InsightLegend/InsightLegendRowContextMenu.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { ReactNode } from 'react'
-
-import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'
-import {
- ContextMenu,
- ContextMenuContent,
- ContextMenuGroup,
- ContextMenuItem,
- ContextMenuSeparator,
- ContextMenuTrigger,
-} from 'lib/ui/ContextMenu/ContextMenu'
-
-export type InsightLegendRowContextMenuProps = {
- children: ReactNode
- areAllSeriesVisible: boolean
- showLegendIsolateSeriesItem: boolean
- isHidden: boolean
- isOnlyThisVisible: boolean
- onToggleOtherSeries: () => void
- onToggleAllSeries: () => void
-}
-
-export function InsightLegendRowContextMenu({
- children,
- areAllSeriesVisible,
- showLegendIsolateSeriesItem,
- isHidden,
- isOnlyThisVisible,
- onToggleOtherSeries,
- onToggleAllSeries,
-}: InsightLegendRowContextMenuProps): JSX.Element {
- return (
- <ContextMenu>
- <Tooltip title="Right-click for options" delayMs={200}>
- <ContextMenuTrigger asChild>{children}</ContextMenuTrigger>
- </Tooltip>
- <ContextMenuContent className="max-w-[300px] click-outside-block">
- <ContextMenuGroup>
- {showLegendIsolateSeriesItem && !isHidden && (
- <ContextMenuItem asChild>
- <ButtonPrimitive
- menuItem
- onClick={onToggleOtherSeries}
- data-attr="insight-legend-hide-other-series"
- >
- {isOnlyThisVisible ? 'Show all series' : 'Hide other series'}
- </ButtonPrimitive>
- </ContextMenuItem>
- )}
- {showLegendIsolateSeriesItem && !isHidden && !isOnlyThisVisible && <ContextMenuSeparator />}
- {!isOnlyThisVisible && (
- <ContextMenuItem asChild>
- <ButtonPrimitive
- menuItem
- onClick={onToggleAllSeries}
- data-attr="insight-legend-toggle-all-series"
- >
- {areAllSeriesVisible ? 'Hide all series' : 'Show all series'}
- </ButtonPrimitive>
- </ContextMenuItem>
- )}
- </ContextMenuGroup>
- </ContextMenuContent>
- </ContextMenu>
- )
-}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx
index 4ba79d8a4d6b..94159bfffb1d 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx
@@ -306,7 +306,11 @@ describe('SqlLineGraph', () => {
it.each([
{ name: 'clicking a legend item isolates that series', additive: false, expectedRows: ['b'] },
- { name: 'meta-clicking a legend item hides just that series', additive: true, expectedRows: ['a'] },
+ {
+ name: 'meta-clicking a legend item hides just that series',
+ additive: true,
+ expectedRows: ['a'],
+ },
])('$name', async ({ additive, expectedRows }) => {
const { container } = renderLine(
{ yAxis: [{ column: 'a' }, { column: 'b' }], showLegend: true },
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
index 8680b5cf7a5d..e2c97f4937fb 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
@@ -718,6 +718,17 @@ describe('sqlLineGraphAdapter', () => {
expect(config.legend).toEqual({ show: expected, position: 'top', interactive: true })
})
+ it('forwards legendRenderItem, which carries the row right-click menu', () => {
+ const legendRenderItem = jest.fn()
+ const config = buildLineChartConfig({
+ xData: dateXData,
+ chartSettings: { showLegend: true },
+ timezone: 'UTC',
+ legendRenderItem,
+ })
+ expect(config.legend?.renderItem).toBe(legendRenderItem)
+ })
+
it('wires goalLines through schemaGoalLinesToConfigs', () => {
const goalLines: GoalLine[] = [{ label: 'Target', value: 100 }]
const config = buildLineChartConfig({ xData: dateXData, chartSettings: {}, timezone: 'UTC', goalLines })
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
index a70de12fd6f6..2ef12ac55b8e 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
@@ -311,6 +311,9 @@ interface BuildConfigArgs {
timezone: string
goalLines?: GoalLine[]
ySeriesData?: SqlLineYSeries[] | null
+ /** Wraps each legend row, e.g. with the series right-click menu. Passed straight through to
+ * quill so this module stays free of JSX. */
+ legendRenderItem?: ChartLegendConfig['renderItem']
}
export interface BuildBarConfigArgs extends BuildConfigArgs {
@@ -368,8 +371,13 @@ function buildYAxisConfig(
}
}
-function buildLegendConfig(chartSettings: ChartSettings): ChartLegendConfig {
- return { show: chartSettings.showLegend ?? false, position: 'top', interactive: true }
+function buildLegendConfig(
+ chartSettings: ChartSettings,
+ renderItem: ChartLegendConfig['renderItem']
+): ChartLegendConfig {
+ // No `hiddenKeys`, so the legend is uncontrolled: quill owns which series are toggled off, and
+ // isolating a series works without SQL charts having to persist anything.
+ return { show: chartSettings.showLegend ?? false, position: 'top', interactive: true, renderItem }
}
/** The X/Y axis-border toggles map onto quill's per-edge axis lines — undefined when both are on
@@ -406,6 +414,7 @@ export function buildLineChartConfig({
timezone,
goalLines,
ySeriesData,
+ legendRenderItem,
}: BuildConfigArgs): TimeSeriesLineChartConfig {
const leftSeries = seriesForAxis(ySeriesData, 'left')
const rightSeries = seriesForAxis(ySeriesData, 'right')
@@ -432,7 +441,7 @@ export function buildLineChartConfig({
goalLines: schemaGoalLinesToConfigs(goalLines),
showAxisLines: buildAxisLinesConfig(chartSettings),
trendLines: buildTrendLineConfigs(ySeriesData),
- legend: buildLegendConfig(chartSettings),
+ legend: buildLegendConfig(chartSettings, legendRenderItem),
valueLabels: buildValueLabelsConfig(chartSettings, ySeriesData),
curve: chartStyleCurve(chartSettings.chartStyle),
tooltip: {
@@ -449,6 +458,7 @@ export function buildBarChartConfig({
goalLines,
visualizationType,
ySeriesData,
+ legendRenderItem,
}: BuildBarConfigArgs): TimeSeriesBarChartConfig & { yAxis?: YAxisConfig } {
const barLayout = barLayoutForDisplay(visualizationType, chartSettings)
const labelFormatter = buildSqlDateLabelFormatter(xData, timezone)
@@ -483,7 +493,7 @@ export function buildBarChartConfig({
// Percent bars scale against a [0, 1] domain; trend lines plot raw series values, so they'd
// render off-scale and invisible.
trendLines: barLayout === 'percent' ? [] : buildTrendLineConfigs(ySeriesData),
- legend: buildLegendConfig(chartSettings),
+ legend: buildLegendConfig(chartSettings, legendRenderItem),
valueLabels: buildValueLabelsConfig(chartSettings, ySeriesData),
tooltip: {
...buildSqlTooltipConfig(chartSettings, ySeriesData),
@@ -499,6 +509,7 @@ export function buildComboChartConfig({
goalLines,
visualizationType,
ySeriesData,
+ legendRenderItem,
}: BuildBarConfigArgs): TimeSeriesComboChartConfig & { yAxis?: YAxisConfig } {
const labelFormatter = buildSqlDateLabelFormatter(xData, timezone)
@@ -536,7 +547,7 @@ export function buildComboChartConfig({
// render off-scale and invisible.
trendLines: isPercent ? [] : buildTrendLineConfigs(ySeriesData),
curve: chartStyleCurve(chartSettings.chartStyle),
- legend: buildLegendConfig(chartSettings),
+ legend: buildLegendConfig(chartSettings, legendRenderItem),
valueLabels: buildValueLabelsConfig(chartSettings, ySeriesData),
tooltip: {
...buildSqlTooltipConfig(chartSettings, ySeriesData),
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel.ts
index ef2e593f87f8..513ac931e2c2 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/useSqlChartModel.ts
@@ -4,6 +4,7 @@ import { useEffect, useMemo } from 'react'
import { type ChartTheme, type Series } from '@posthog/quill-charts'
import { useChartTheme, useChartConfig } from 'lib/charts/hooks'
+import { useChartLegendSeriesMenu } from 'lib/components/ChartLegendSeriesMenu/useChartLegendSeriesMenu'
import { teamLogic } from 'scenes/teamLogic'
import { SqlChartProps } from './SqlChart'
@@ -44,6 +45,8 @@ export function useSqlChartModel<TConfig extends object>(
const theme = useChartTheme()
+ const legendRenderItem = useChartLegendSeriesMenu({ surface: 'sql', seriesCount: series.length })
+
const config = useChartConfig(
() =>
xData
@@ -54,9 +57,10 @@ export function useSqlChartModel<TConfig extends object>(
goalLines,
visualizationType,
ySeriesData,
+ legendRenderItem,
})
: undefined,
- [xData, chartSettings, timezone, goalLines, visualizationType, buildConfig, ySeriesData]
+ [xData, chartSettings, timezone, goalLines, visualizationType, buildConfig, ySeriesData, legendRenderItem]
)
if (!xData || !ySeriesData || series.length === 0 || !config) {
diff --git a/frontend/src/scenes/trends/trendsDataLogic.test.ts b/frontend/src/scenes/trends/trendsDataLogic.test.ts
index 586bbbe7bc72..f4cd90c4b12d 100644
--- a/frontend/src/scenes/trends/trendsDataLogic.test.ts
+++ b/frontend/src/scenes/trends/trendsDataLogic.test.ts
@@ -258,7 +258,6 @@ describe('trendsDataLogic', () => {
trendPieResult.result,
{
areAllSeriesVisible: true,
- showLegendIsolateSeriesItem: true,
legendSeriesIsolationMenuEligible: true,
},
],
@@ -282,7 +281,7 @@ describe('trendsDataLogic', () => {
}
})
- it('hides isolate menu item when every series is hidden', async () => {
+ it('marks every series hidden when all are toggled off', async () => {
const query: TrendsQuery = {
kind: NodeKind.TrendsQuery,
series: [],
@@ -307,19 +306,22 @@ describe('trendsDataLogic', () => {
logic.actions.toggleAllResultsHidden(indexedResults, true)
}).toFinishAllListeners()
- await expectLogic(logic).toMatchValues({
- areAllSeriesVisible: false,
- showLegendIsolateSeriesItem: false,
- })
+ const { getTrendsHidden } = logic.values
+ expect(indexedResults.every((r) => getTrendsHidden(r))).toBe(true)
+ await expectLogic(logic).toMatchValues({ areAllSeriesVisible: false })
})
it('setResultsHidden hides exactly the given series in one update', async () => {
const query: TrendsQuery = {
kind: NodeKind.TrendsQuery,
series: [],
- trendsFilter: { display: ChartDisplayType.ActionsPie },
+ trendsFilter: {
+ display: ChartDisplayType.ActionsPie,
+ },
+ }
+ const insight: Partial<InsightModel> = {
+ result: trendPieResult.result,
}
- const insight: Partial<InsightModel> = { result: trendPieResult.result }
await expectLogic(logic, () => {
insightVizDataLogic.findMounted(insightProps)?.actions.updateQuerySource(query)
@@ -367,7 +369,8 @@ describe('trendsDataLogic', () => {
builtDataNodeLogic.actions.loadDataSuccess(insight)
}).toFinishAllListeners()
- const [currentRow, previousRow] = logic.values.indexedResults
+ const indexedResults = logic.values.indexedResults
+ const [currentRow, previousRow] = indexedResults
expect(getTrendResultCustomizationKey(ResultCustomizationBy.Value, currentRow)).toBe(
getTrendResultCustomizationKey(ResultCustomizationBy.Value, previousRow)
)
@@ -404,10 +407,7 @@ describe('trendsDataLogic', () => {
logic.actions.toggleOtherSeriesHidden(solo)
}).toFinishAllListeners()
- await expectLogic(logic).toMatchValues({
- areAllSeriesVisible: false,
- showLegendIsolateSeriesItem: true,
- })
+ await expectLogic(logic).toMatchValues({ areAllSeriesVisible: false })
const { getIsOnlyVisibleSeriesInLegend } = logic.values
expect(indexedResults.map((r) => getIsOnlyVisibleSeriesInLegend(r))).toEqual([
diff --git a/frontend/src/scenes/trends/trendsDataLogic.ts b/frontend/src/scenes/trends/trendsDataLogic.ts
index 361deefa8a48..9a8a1c089c61 100644
--- a/frontend/src/scenes/trends/trendsDataLogic.ts
+++ b/frontend/src/scenes/trends/trendsDataLogic.ts
@@ -197,7 +197,6 @@ export interface trendsDataLogicValues {
| undefined
results: TrendResult[]
showConfidenceIntervals: boolean
- showLegendIsolateSeriesItem: boolean
showMovingAverage: boolean
showTrendLines: boolean
}
@@ -390,7 +389,7 @@ export interface trendsDataLogicMeta {
| Record<string, ResultCustomizationByValue>
| Record<number, ResultCustomizationByPosition>
| undefined,
- getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null,
+ getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null, // insightVizDataLogic
breakdownFilter: BreakdownFilter | null | undefined,
querySource:
| FunnelsQuery
@@ -419,10 +418,6 @@ export interface trendsDataLogicMeta {
indexedResults: IndexedTrendResult[],
getTrendsHidden: (dataset: IndexedTrendResult) => boolean
) => boolean
- showLegendIsolateSeriesItem: (
- indexedResults: IndexedTrendResult[],
- getTrendsHidden: (dataset: IndexedTrendResult) => boolean
- ) => boolean
legendSeriesIsolationMenuEligible: (indexedResults: IndexedTrendResult[]) => boolean
getIsOnlyVisibleSeriesInLegend: (
indexedResults: IndexedTrendResult[],
@@ -1031,14 +1026,6 @@ export const trendsDataLogic = kea<trendsDataLogicType>([
): boolean => indexedResults.every((d) => !getTrendsHidden(d)),
],
- showLegendIsolateSeriesItem: [
- (s) => [s.indexedResults, s.getTrendsHidden],
- (
- indexedResults: IndexedTrendResult[],
- getTrendsHidden: (dataset: IndexedTrendResult) => boolean
- ): boolean => indexedResults.length > 0 && !indexedResults.every((d) => getTrendsHidden(d)),
- ],
-
legendSeriesIsolationMenuEligible: [
(s) => [s.indexedResults],
(indexedResults: IndexedTrendResult[]): boolean => indexedResults.length > 1,
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx
index d8420597ca37..79bc309a7562 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx
@@ -11,6 +11,7 @@ import type {
} from '@posthog/quill-charts'
import { useChartConfig, useChartTheme, useDateRangeZoom } from 'lib/charts/hooks'
+import { useChartLegendSeriesMenu } from 'lib/components/ChartLegendSeriesMenu/useChartLegendSeriesMenu'
import { funnelDataLogic } from 'scenes/funnels/funnelDataLogic'
import { funnelPersonsModalLogic } from 'scenes/funnels/funnelPersonsModalLogic'
import { hasBreakdown } from 'scenes/funnels/funnelUtils'
@@ -121,6 +122,7 @@ export function FunnelLineChart({
[seriesBase, breakdownFilter, allCohorts.results, formatPropertyValueForDisplay]
)
+ const legendRenderItem = useChartLegendSeriesMenu({ surface: 'funnel', seriesCount: series.length })
const legendConfig = useMemo<ChartLegendConfig>(
() =>
buildBaseLegendConfig({
@@ -128,8 +130,9 @@ export function FunnelLineChart({
legendPosition,
canEditInsight,
inSharedMode,
+ renderItem: legendRenderItem,
}),
- [showLegend, series.length, legendPosition, canEditInsight, inSharedMode]
+ [showLegend, series.length, legendPosition, canEditInsight, inSharedMode, legendRenderItem]
)
const chartConfig: TimeSeriesLineChartConfig = useChartConfig(
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
index 6cc233fb32ed..3f3bc4a609ca 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
@@ -6,6 +6,7 @@ import type { ChartLegendConfig, PointClickData, TooltipContext } from '@posthog
import { useChartConfig, useChartTheme, useDateRangeZoom } from 'lib/charts/hooks'
import { getBarColorFromStatus } from 'lib/colors'
+import { useChartLegendSeriesMenu } from 'lib/components/ChartLegendSeriesMenu/useChartLegendSeriesMenu'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { insightLogic } from 'scenes/insights/insightLogic'
@@ -74,9 +75,17 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi
// Lifecycle statuses all share the same resultCustomizationKey (same action.order), so
// useInsightsLegendConfig can't distinguish them — build the config inline and let the
// chart manage toggle state internally.
+ const legendRenderItem = useChartLegendSeriesMenu({ surface: 'lifecycle', seriesCount: indexedResults.length })
const legendConfig = useMemo<ChartLegendConfig>(
- () => buildBaseLegendConfig({ show: !!showLegend, legendPosition, canEditInsight, inSharedMode }),
- [showLegend, legendPosition, canEditInsight, inSharedMode]
+ () =>
+ buildBaseLegendConfig({
+ show: !!showLegend,
+ legendPosition,
+ canEditInsight,
+ inSharedMode,
+ renderItem: legendRenderItem,
+ }),
+ [showLegend, legendPosition, canEditInsight, inSharedMode, legendRenderItem]
)
const isStacked = lifecycleFilter?.stacked ?? true
diff --git a/products/product_analytics/frontend/insights/trends/shared/TrendsLegendItemContextMenu.tsx b/products/product_analytics/frontend/insights/trends/shared/TrendsLegendItemContextMenu.tsx
deleted file mode 100644
index 0d2aa0a3a3d1..000000000000
--- a/products/product_analytics/frontend/insights/trends/shared/TrendsLegendItemContextMenu.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { useActions, useValues } from 'kea'
-import posthog from 'posthog-js'
-import type { ReactNode } from 'react'
-
-import { InsightLegendRowContextMenu } from 'lib/components/InsightLegend/InsightLegendRowContextMenu'
-import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
-import type { IndexedTrendResult } from 'scenes/trends/types'
-
-import { InsightLogicProps } from '~/types'
-
-interface TrendsLegendItemContextMenuProps {
- insightProps: InsightLogicProps
- item: IndexedTrendResult
- children: ReactNode
-}
-
-/** Right-click isolate/show-all/hide-all menu for a quill legend row, mirroring the legacy
- * InsightLegendRow menu — shares trendsDataLogic's toggle actions so hidden state stays in
- * the query (resultCustomizations). */
-export function TrendsLegendItemContextMenu({
- insightProps,
- item,
- children,
-}: TrendsLegendItemContextMenuProps): JSX.Element {
- const {
- getTrendsHidden,
- indexedResults,
- areAllSeriesVisible,
- showLegendIsolateSeriesItem,
- getIsOnlyVisibleSeriesInLegend,
- } = useValues(trendsDataLogic(insightProps))
- const { toggleOtherSeriesHidden, toggleAllResultsHidden } = useActions(trendsDataLogic(insightProps))
-
- const isHidden = getTrendsHidden(item)
- const isOnlyThisVisible = getIsOnlyVisibleSeriesInLegend(item)
-
- return (
- <InsightLegendRowContextMenu
- areAllSeriesVisible={areAllSeriesVisible}
- showLegendIsolateSeriesItem={showLegendIsolateSeriesItem}
- isHidden={isHidden}
- isOnlyThisVisible={isOnlyThisVisible}
- onToggleOtherSeries={() => {
- posthog.capture('insight_legend_context_menu', {
- action: isOnlyThisVisible ? 'show_all_series' : 'hide_other_series',
- source: 'isolate_row',
- series_count: indexedResults.length,
- })
- toggleOtherSeriesHidden(item)
- }}
- onToggleAllSeries={() => {
- posthog.capture('insight_legend_context_menu', {
- action: areAllSeriesVisible ? 'hide_all_series' : 'show_all_series',
- source: 'toggle_all_row',
- series_count: indexedResults.length,
- })
- toggleAllResultsHidden(indexedResults, areAllSeriesVisible)
- }}
- >
- {children}
- </InsightLegendRowContextMenu>
- )
-}
diff --git a/products/product_analytics/frontend/insights/trends/shared/buildBaseLegendConfig.test.ts b/products/product_analytics/frontend/insights/trends/shared/buildBaseLegendConfig.test.ts
new file mode 100644
index 000000000000..074442538690
--- /dev/null
+++ b/products/product_analytics/frontend/insights/trends/shared/buildBaseLegendConfig.test.ts
@@ -0,0 +1,50 @@
+import { buildBaseLegendConfig } from './buildBaseLegendConfig'
+
+const renderItem = jest.fn()
+
+describe('buildBaseLegendConfig', () => {
+ it.each([
+ { name: 'right', legendPosition: 'right', expected: 'right' },
+ { name: 'left', legendPosition: 'left', expected: 'left' },
+ { name: 'unset (defaults to right)', legendPosition: undefined, expected: 'right' },
+ ])('positions the legend $name', ({ legendPosition, expected }) => {
+ const config = buildBaseLegendConfig({ show: true, legendPosition, canEditInsight: true })
+
+ expect(config.position).toBe(expected)
+ })
+
+ it.each([
+ {
+ name: 'an editable legend gets the row menu',
+ canEditInsight: true,
+ inSharedMode: false,
+ expectedInteractive: true,
+ expectedRenderItem: renderItem,
+ },
+ {
+ name: 'a read-only legend gets neither toggling nor the row menu',
+ canEditInsight: false,
+ inSharedMode: false,
+ expectedInteractive: false,
+ expectedRenderItem: undefined,
+ },
+ {
+ name: 'a shared-mode legend gets neither either',
+ canEditInsight: true,
+ inSharedMode: true,
+ expectedInteractive: false,
+ expectedRenderItem: undefined,
+ },
+ ])('$name', ({ canEditInsight, inSharedMode, expectedInteractive, expectedRenderItem }) => {
+ const config = buildBaseLegendConfig({
+ show: true,
+ legendPosition: 'right',
+ canEditInsight,
+ inSharedMode,
+ renderItem,
+ })
+
+ expect(config.interactive).toBe(expectedInteractive)
+ expect(config.renderItem).toBe(expectedRenderItem)
+ })
+})
diff --git a/products/product_analytics/frontend/insights/trends/shared/buildBaseLegendConfig.ts b/products/product_analytics/frontend/insights/trends/shared/buildBaseLegendConfig.ts
index c19a7c73ee02..980daa09cea7 100644
--- a/products/product_analytics/frontend/insights/trends/shared/buildBaseLegendConfig.ts
+++ b/products/product_analytics/frontend/insights/trends/shared/buildBaseLegendConfig.ts
@@ -2,21 +2,26 @@ import type { ChartLegendConfig } from '@posthog/quill-charts'
/** Returns the base `{ show, position, interactive }` legend shape shared by all chart types that
* build their config inline (lifecycle, funnel). Call sites own the `show` expression — e.g. funnel
- * gates it on `series.length > 1`. */
+ * gates it on `series.length > 1`. These legends are uncontrolled, so isolating a series and the
+ * row menu's bulk actions work off the chart's own state with nothing to persist. */
export function buildBaseLegendConfig({
show,
legendPosition,
canEditInsight,
inSharedMode,
+ renderItem,
}: {
show: boolean
legendPosition: string | null | undefined
canEditInsight: boolean
inSharedMode?: boolean
+ renderItem?: ChartLegendConfig['renderItem']
}): ChartLegendConfig {
+ const interactive = canEditInsight && !inSharedMode
return {
show,
position: (legendPosition ?? 'right') as ChartLegendConfig['position'],
- interactive: canEditInsight && !inSharedMode,
+ interactive,
+ renderItem: interactive ? renderItem : undefined,
}
}
diff --git a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx
index db726a2497a6..744b26585469 100644
--- a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.test.tsx
@@ -34,11 +34,7 @@ function setup({
trendsFilter,
compareFilter,
results,
-}: {
- trendsFilter?: TrendsFilter
- compareFilter?: CompareFilter
- results?: InsightModel['result']
-} = {}): void {
+}: { trendsFilter?: TrendsFilter; compareFilter?: CompareFilter; results?: InsightModel['result'] } = {}): void {
initKeaTests()
featureFlagLogic.mount()
diff --git a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx
index d8c8a33a3183..177efbb79ec2 100644
--- a/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx
+++ b/products/product_analytics/frontend/insights/trends/shared/useInsightsLegendConfig.tsx
@@ -1,8 +1,9 @@
import { useActions, useValues } from 'kea'
-import { useMemo, type ReactNode } from 'react'
+import { useMemo } from 'react'
-import type { ChartLegendConfig, LegendItem } from '@posthog/quill-charts'
+import type { ChartLegendConfig } from '@posthog/quill-charts'
+import { useChartLegendSeriesMenu } from 'lib/components/ChartLegendSeriesMenu/useChartLegendSeriesMenu'
import { insightLogic } from 'scenes/insights/insightLogic'
import { getTrendResultCustomizationKey } from 'scenes/insights/utils'
import { trendsDataLogic } from 'scenes/trends/trendsDataLogic'
@@ -10,29 +11,22 @@ import type { IndexedTrendResult } from 'scenes/trends/types'
import { InsightLogicProps } from '~/types'
-import { TrendsLegendItemContextMenu } from './TrendsLegendItemContextMenu'
-
interface UseInsightsLegendConfigOptions {
insightProps: InsightLogicProps
inSharedMode?: boolean
}
/** Builds the quill in-chart legend config for trends-family charts. Wires toggle persistence and the
- * isolate/show-all context menu through trendsDataLogic. Lifecycle and funnel charts build their
+ * isolate/show-all row menu through trendsDataLogic. Lifecycle and funnel charts build their
* legend config inline (they don't read from trendsDataLogic). */
export function useInsightsLegendConfig({
insightProps,
inSharedMode = false,
}: UseInsightsLegendConfigOptions): ChartLegendConfig {
const { canEditInsight } = useValues(insightLogic)
- const {
- indexedResults,
- getTrendsHidden,
- showLegend,
- legendPosition,
- legendSeriesIsolationMenuEligible,
- resultCustomizationBy,
- } = useValues(trendsDataLogic(insightProps))
+ const { indexedResults, getTrendsHidden, showLegend, legendPosition, resultCustomizationBy } = useValues(
+ trendsDataLogic(insightProps)
+ )
const { toggleResultHidden, setResultsHidden } = useActions(trendsDataLogic(insightProps))
const resultById = useMemo(() => {
@@ -42,10 +36,10 @@ export function useInsightsLegendConfig({
}, [indexedResults])
const legendInteractive = canEditInsight && !inSharedMode
+ const renderItem = useChartLegendSeriesMenu({ surface: 'trends', seriesCount: indexedResults?.length ?? 0 })
return useMemo<ChartLegendConfig>(() => {
const hiddenKeys = (indexedResults ?? []).filter((r) => getTrendsHidden(r)).map((r) => String(r.id))
- const showContextMenu = legendInteractive && legendSeriesIsolationMenuEligible
return {
show: !!showLegend,
position: (legendPosition as ChartLegendConfig['position']) ?? 'right',
@@ -57,8 +51,8 @@ export function useInsightsLegendConfig({
toggleResultHidden(result)
}
},
- // Isolating rewrites the whole hidden set, so it lands as one resultCustomizations
- // update rather than a toggle per series.
+ // Isolating and hide-all rewrite the whole hidden set, so they land as one
+ // resultCustomizations update rather than a toggle per series.
onSetHiddenSeries: setResultsHidden,
// Hidden state is stored per customization key, and comparing to the previous period puts
// a series' two rows on one key — so quill has to treat them as one series when it
@@ -67,19 +61,7 @@ export function useInsightsLegendConfig({
const result = resultById.get(key)
return result ? getTrendResultCustomizationKey(resultCustomizationBy, result) : key
},
- renderItem: showContextMenu
- ? (node: ReactNode, item: LegendItem) => {
- const result = resultById.get(item.key)
- if (!result) {
- return node
- }
- return (
- <TrendsLegendItemContextMenu insightProps={insightProps} item={result}>
- {node}
- </TrendsLegendItemContextMenu>
- )
- }
- : undefined,
+ renderItem: legendInteractive ? renderItem : undefined,
}
}, [
indexedResults,
@@ -87,11 +69,10 @@ export function useInsightsLegendConfig({
showLegend,
legendPosition,
legendInteractive,
- legendSeriesIsolationMenuEligible,
resultById,
toggleResultHidden,
setResultsHidden,
resultCustomizationBy,
- insightProps,
+ renderItem,
])
}