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.

fix(dashboards): open the result menu on right click (#123841)

Marius Andra92a7ea3b7236
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 4167065e0857..40d572128bc1 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -137,7 +137,7 @@ Each measure's **Format and display** dialog sets its label, currency, decimal p
In the worksheet editor, click a bar, line point, table cell, or pivot cell to explore its source rows. **Filter in new worksheet** preserves the original insight and adds the selected dimensions to a new worksheet. **View underlying rows** loads up to 1,000 matching source rows before aggregation; **Open in SQL editor** carries the same conditions, connection, and effective dashboard filters. When adding a drill-down condition would exceed the filter-group nesting limit, use **View underlying rows** or **Open in SQL editor**. Total cells omit rolled-up dimensions, and **Other** selects the categories outside the current Top N. Comparison-period points open rows from their original dates; their filtered-worksheet action is disabled to avoid combining current dates with prior-period conditions. These actions are unavailable on public shared insights.
-On authenticated dashboards in view mode, clicking a chart result opens a context menu beside the pointer. Chart tooltips stay hidden until the menu closes. BI worksheets offer **View underlying rows**, then **Open in SQL editor**. Product analytics datapoints offer **View people**, **View recordings** when the existing drilldown selects matched recordings, then **Open in SQL editor**. Lifecycle results offer people and SQL only: their actor query identifies bucket members without projecting matched events. The people and SQL actions preserve the selected date, breakdown, and aggregation. SQL and recording links become available after the selected actor rows load. Selecting another result or closing the menu cancels any pending query. Recordings use matched session IDs; when no sessions match, the recordings action stays disabled. Clicking the same result again, pressing Escape, or clicking outside closes the menu. Native links support opening actions in another tab. These actions do not change dashboard filters or create saved insights. Public shares, embeds, exports, and layout editing retain their existing behavior.
+On authenticated dashboards in view mode, right-clicking a chart result opens a context menu beside the pointer. A left click keeps its usual action, such as opening the people modal, pinning a multi-series tooltip, or opening the BI drill-down dialog. Right-clicking a link or an input keeps the browser menu. Chart tooltips stay hidden until the menu closes. BI worksheets offer **View underlying rows**, then **Open in SQL editor**. Product analytics datapoints offer **View people**, **View recordings** when the existing drilldown selects matched recordings, then **Open in SQL editor**. Lifecycle results offer people and SQL only: their actor query identifies bucket members without projecting matched events. The people and SQL actions preserve the selected date, breakdown, and aggregation. SQL and recording links become available after the selected actor rows load. Selecting another result or closing the menu cancels any pending query. Recordings use matched session IDs; when no sessions match, the recordings action stays disabled. A left click, Escape, or a click outside closes the menu. Right-clicking another result moves the menu to it. Native links support opening actions in another tab. These actions do not change dashboard filters or create saved insights. Public shares, embeds, exports, and layout editing retain their existing behavior.
**Compare previous period** turns date comparison on or off in one click. The adjacent comparison picker still supports custom offsets. Select a bounded date range before enabling comparison.
diff --git a/frontend/src/lib/components/ResultMenu/resultMenuTrigger.ts b/frontend/src/lib/components/ResultMenu/resultMenuTrigger.ts
new file mode 100644
index 000000000000..a98cfd526106
--- /dev/null
+++ b/frontend/src/lib/components/ResultMenu/resultMenuTrigger.ts
@@ -0,0 +1,53 @@
+import type { MouseEvent } from 'react'
+
+// A right click on these keeps the browser menu. Links and inputs have their own browser actions, and
+// legend rows are not results, so a replayed click on them hides or isolates a series.
+const NATIVE_CONTEXT_MENU_SELECTOR =
+ 'a[href], input, select, textarea, label, [data-hog-charts-legend], .InsightLegendMenu'
+
+// A replayed click must not reach these. A marked chart selects its result on right click already, and a click
+// on that chart or its tooltip can pin the tooltip or open the insight instead.
+const NO_REPLAY_SELECTOR = '[data-hog-charts-context-menu], [data-hog-charts-tooltip]'
+
+export interface ResultMenuPoint {
+ x: number
+ y: number
+ timestamp: number
+}
+
+// A context menu that a child already opened, such as the legend series menu, prevents the default action.
+export function isResultMenuContextMenu(event: MouseEvent<HTMLElement>): boolean {
+ const target = event.target as Element
+ return (
+ !event.defaultPrevented && event.currentTarget.contains(target) && !target.closest(NATIVE_CONTEXT_MENU_SELECTOR)
+ )
+}
+
+export function getResultMenuPoint(event: MouseEvent): ResultMenuPoint {
+ // A menu opened from the keyboard has no pointer position, so anchor it to the focused element.
+ if (!event.clientX && !event.clientY) {
+ const rect = (event.target as Element).getBoundingClientRect()
+ return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2, timestamp: event.timeStamp }
+ }
+ return { x: event.clientX, y: event.clientY, timestamp: event.timeStamp }
+}
+
+// Most visualizations select a result only in a click handler. Replaying the right click as a click runs
+// that handler, so the menu can capture the result that a left click acts on.
+export function replayAsClick(event: MouseEvent): void {
+ if ((event.target as Element).closest(NO_REPLAY_SELECTOR)) {
+ return
+ }
+ event.target.dispatchEvent(
+ new window.MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ view: window,
+ detail: 1,
+ clientX: event.clientX,
+ clientY: event.clientY,
+ screenX: event.screenX,
+ screenY: event.screenY,
+ })
+ )
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.test.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.test.tsx
index 8902b0d35850..3cb2a7d05580 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.test.tsx
@@ -97,6 +97,7 @@ describe('DataTableVisualization', () => {
memberAliases: alias ? [{ field: region, aliases: [{ value: 'west', label: 'West coast' }] }] : [],
}
renderDataVisualization({
+ embedded: true,
context: { dashboardResultMenu: true },
query: {
...buildBIQuery(config)!.node,
@@ -127,12 +128,15 @@ describe('DataTableVisualization', () => {
results: [['west', 2]],
},
})
- fireEvent.click(await screen.findByText('First slice'))
+ fireEvent.contextMenu(await screen.findByText('First slice'))
const menu = await screen.findByRole('menu')
const link = within(menu).getByText('Open in SQL editor').closest('a')!
const openedQuery = JSON.parse(new URL(link.href).searchParams.get('open_query')!)
expect(openedQuery.source.query).toContain("region = 'west'")
expect(openedQuery.source.query).not.toContain("region = 'West coast'")
+ fireEvent.click(screen.getByText('First slice'))
+ expect(screen.queryByRole('menu')).toBeNull()
+ await screen.findByText('Explore this result')
})
it.each([false, true])('opens and closes settings in the correct panel (hosted: %s)', async (hosted) => {
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index abb3dc1c1f93..31b09f0daf2f 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -9,6 +9,7 @@ import { LemonBanner, LemonButton, LemonDivider } from '@posthog/lemon-ui'
import { createXAxisTickCallback } from '@posthog/quill-charts'
import { ExportButton } from 'lib/components/ExportButton/ExportButton'
+import { getResultMenuPoint, isResultMenuContextMenu, replayAsClick } from 'lib/components/ResultMenu/resultMenuTrigger'
import { PART_OF_WHOLE_DISPLAY_TYPES } from 'lib/constants'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { InsightErrorState, StatelessInsightLoadingState } from 'scenes/insights/EmptyStates'
@@ -234,12 +235,12 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
query,
filtersOverride: props.filtersOverride,
variablesOverride: props.variablesOverride,
- dashboardMenu: !props.inSharedMode && props.context?.dashboardResultMenu,
}
const drilldownLogic = biDrilldownLogic(drilldownProps)
- const { inspect: inspectResult, setInteraction } = useActions(drilldownLogic)
+ const { inspect: inspectResult, setInteraction, close: closeResultMenu } = useActions(drilldownLogic)
const resultMenuTriggerRef = useRef<HTMLDivElement>(null)
const inspectedPoint = useRef(false)
+ const replayingClick = useRef(false)
const inspect = useCallback(
(record: Record<string, unknown>): void => {
inspectedPoint.current = true
@@ -249,6 +250,7 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
)
const isQuerySnapshot = query.kind === NodeKind.BIVisualizationNode && !!query.config.querySnapshot
const canDrill = query.kind === NodeKind.BIVisualizationNode && !isQuerySnapshot && !props.inSharedMode
+ const resultMenu = canDrill && !!props.context?.dashboardResultMenu
const { seriesBreakdownData, chartData } = useValues(seriesBreakdownLogic({ key: dataVisualizationProps.key }))
const { goalLines } = useValues(displayLogic)
@@ -641,7 +643,7 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
{component}
{canDrill ? (
<>
- {drilldownProps.dashboardMenu && (
+ {resultMenu && (
<BIDrilldownMenu logicProps={drilldownProps} triggerRef={resultMenuTriggerRef} />
)}
<BIDrilldownModal
@@ -665,32 +667,46 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
'DataVisualization InsightCard__viz',
effectiveVisualizationType === ChartDisplayType.Metric && 'InsightCard__viz--Metric'
)}
- onClick={
- canDrill && drilldownProps.dashboardMenu
+ onClickCapture={
+ resultMenu
? (event) => {
if (
- event.currentTarget.contains(event.target as Node) &&
- !!drilldownLogic.values.interaction &&
- !inspectedPoint.current &&
- !(event.target as Element).closest('a, button, input, select, [role="button"]')
+ !replayingClick.current &&
+ drilldownLogic.values.interaction &&
+ event.currentTarget.contains(event.target as Node)
) {
- inspect({})
+ closeResultMenu()
}
}
: undefined
}
- onClickCapture={
- canDrill && drilldownProps.dashboardMenu
+ onContextMenuCapture={
+ resultMenu
? (event) => {
- if (event.currentTarget.contains(event.target as Node)) {
+ if (isResultMenuContextMenu(event)) {
inspectedPoint.current = false
- const rect = (event.target as Element).getBoundingClientRect()
- setInteraction({
- x: event.detail ? event.clientX : rect.x + rect.width / 2,
- y: event.detail ? event.clientY : rect.y + rect.height / 2,
- clickCount: event.detail,
- timestamp: event.timeStamp,
- })
+ }
+ }
+ : undefined
+ }
+ onContextMenu={
+ resultMenu
+ ? (event) => {
+ if (!isResultMenuContextMenu(event)) {
+ return
+ }
+ event.preventDefault()
+ setInteraction(getResultMenuPoint(event))
+ if (!inspectedPoint.current) {
+ replayingClick.current = true
+ try {
+ replayAsClick(event)
+ } finally {
+ replayingClick.current = false
+ }
+ }
+ if (!inspectedPoint.current) {
+ inspect({})
}
}
: undefined
diff --git a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
index 26209c84d0b4..1a8a40040225 100644
--- a/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/BarChart/BarChart.tsx
@@ -49,6 +49,8 @@ export interface BarChartProps<Meta = unknown> {
theme: ChartTheme
tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
onPointClick?: (data: PointClickData<Meta>) => void
+ /** Right-click counterpart of `onPointClick`. See `ChartProps.onPointContextMenu`. */
+ onPointContextMenu?: (data: PointClickData<Meta>) => void
/** See `ChartProps.isPointClickable`. */
isPointClickable?: (dataIndex: number) => boolean
/** Enables x-axis drag-to-zoom. Vertical bars only — horizontal bars interact along y,
@@ -76,6 +78,7 @@ function BarChartInner<Meta = unknown>({
theme,
tooltip,
onPointClick,
+ onPointContextMenu,
isPointClickable,
onDateRangeZoom,
className,
@@ -451,9 +454,10 @@ function BarChartInner<Meta = unknown>({
/>
)}
onPointClick={onPointClick}
+ onPointContextMenu={onPointContextMenu}
isPointClickable={isPointClickable}
onDateRangeZoom={onDateRangeZoom}
- wrapClickData={onPointClick ? wrapClickData : undefined}
+ wrapClickData={onPointClick || onPointContextMenu ? wrapClickData : undefined}
resolveHoverIndex={seriesHasTrackCeiling ? resolveHoverIndex : undefined}
className={className}
dataAttr={dataAttr}
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
index 0d954f9313c4..ab6a8f4999ef 100644
--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
@@ -54,6 +54,8 @@ export interface LineChartProps<Meta = unknown> {
theme: ChartTheme
tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
onPointClick?: (data: PointClickData<Meta>) => void
+ /** Right-click counterpart of `onPointClick`. See `ChartProps.onPointContextMenu`. */
+ onPointContextMenu?: (data: PointClickData<Meta>) => void
onDateRangeZoom?: (data: DateRangeZoomData) => void
className?: string
/** `data-attr` applied to the chart wrapper. See `ChartProps.dataAttr`. */
@@ -77,6 +79,7 @@ function LineChartInner<Meta = unknown>({
theme,
tooltip,
onPointClick,
+ onPointContextMenu,
onDateRangeZoom,
className,
dataAttr,
@@ -297,6 +300,7 @@ function LineChartInner<Meta = unknown>({
drawHover={drawHover}
tooltip={tooltip}
onPointClick={onPointClick}
+ onPointContextMenu={onPointContextMenu}
onDateRangeZoom={onDateRangeZoom}
className={className}
dataAttr={dataAttr}
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index f5591479cdf5..f2c7f545a679 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -81,6 +81,8 @@ export interface TimeSeriesBarChartProps<Meta = unknown> {
config?: TimeSeriesBarChartConfig
tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
onPointClick?: (data: PointClickData<Meta>) => void
+ /** Right-click counterpart of `onPointClick`. See `ChartProps.onPointContextMenu`. */
+ onPointContextMenu?: (data: PointClickData<Meta>) => void
/** See `ChartProps.isPointClickable`. */
isPointClickable?: (dataIndex: number) => boolean
/** Enables x-axis drag-to-zoom. See `BarChartProps.onDateRangeZoom`. */
@@ -98,6 +100,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
config,
tooltip,
onPointClick,
+ onPointContextMenu,
isPointClickable,
onDateRangeZoom,
dataAttr,
@@ -191,6 +194,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
theme={theme}
tooltip={tooltip}
onPointClick={onPointClick}
+ onPointContextMenu={onPointContextMenu}
isPointClickable={isPointClickable}
onDateRangeZoom={onDateRangeZoom}
className={className}
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index fd29ac04d615..bb8b90a12e88 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -75,6 +75,8 @@ export interface TimeSeriesLineChartProps<Meta = unknown> {
config?: TimeSeriesLineChartConfig
tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
onPointClick?: (data: PointClickData<Meta>) => void
+ /** Right-click counterpart of `onPointClick`. See `ChartProps.onPointContextMenu`. */
+ onPointContextMenu?: (data: PointClickData<Meta>) => void
onDateRangeZoom?: (data: DateRangeZoomData) => void
dataAttr?: string
className?: string
@@ -89,6 +91,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
config,
tooltip,
onPointClick,
+ onPointContextMenu,
onDateRangeZoom,
dataAttr,
className,
@@ -178,6 +181,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
theme={theme}
tooltip={tooltip}
onPointClick={onPointClick}
+ onPointContextMenu={onPointContextMenu}
onDateRangeZoom={onDateRangeZoom}
className={className}
dataAttr={dataAttr}
diff --git a/packages/quill/packages/charts/src/components/Legend/Legend.tsx b/packages/quill/packages/charts/src/components/Legend/Legend.tsx
index 930eb8d4f2d3..abe33c6c9da9 100644
--- a/packages/quill/packages/charts/src/components/Legend/Legend.tsx
+++ b/packages/quill/packages/charts/src/components/Legend/Legend.tsx
@@ -72,6 +72,7 @@ export function Legend({
className={`flex ${layout} ${className ?? ''}`}
style={isVertical ? undefined : ({ '--legend-row-max': horizontalRowMax } as React.CSSProperties)}
data-attr={dataAttr}
+ data-hog-charts-legend=""
>
{items.map((item) => {
const dimmed = hidden?.has(item.key) ? ' opacity-40' : ''
diff --git a/packages/quill/packages/charts/src/core/Chart.tsx b/packages/quill/packages/charts/src/core/Chart.tsx
index 7679d7fc5c65..89067753059f 100644
--- a/packages/quill/packages/charts/src/core/Chart.tsx
+++ b/packages/quill/packages/charts/src/core/Chart.tsx
@@ -72,6 +72,10 @@ export interface ChartProps<Meta = unknown> {
drawHover: (args: ChartDrawArgs) => DrawHoverResult
tooltip?: (ctx: TooltipContext<Meta>) => React.ReactNode
onPointClick?: (data: PointClickData<Meta>) => void
+ /** Fires on a right click with the series nearest the cursor. It never pins or unpins the
+ * tooltip. The browser menu still opens unless the host calls `preventDefault()` on the
+ * `contextmenu` event. `isPointClickable` limits it like `onPointClick`. */
+ onPointContextMenu?: (data: PointClickData<Meta>) => void
/** Limits `onPointClick` and the pointer cursor to the points it returns true for. */
isPointClickable?: (dataIndex: number) => boolean
/** Enables x-axis drag-to-zoom. Fired with the label range the user dragged across.
@@ -130,6 +134,7 @@ export function Chart<Meta = unknown>({
drawHover,
tooltip: renderTooltipProp,
onPointClick,
+ onPointContextMenu,
isPointClickable,
onDateRangeZoom,
onAreaSelect,
@@ -349,6 +354,7 @@ export function Chart<Meta = unknown>({
pinnable: pinnableTooltip,
resolveClickToNearestSeries,
onPointClick,
+ onPointContextMenu,
isPointClickable,
onDateRangeZoom,
onAreaSelect,
@@ -457,6 +463,7 @@ export function Chart<Meta = unknown>({
(isPointClickable?.(hoverIndex) ?? true)
}
crosshair={!!onDateRangeZoom || !!onAreaSelect}
+ contextMenu={!!onPointContextMenu}
ariaLabel={ariaLabel}
labelCount={labels.length}
handlers={handlers}
diff --git a/packages/quill/packages/charts/src/core/chart-shell.tsx b/packages/quill/packages/charts/src/core/chart-shell.tsx
index 10192e89eca5..6c2f2586d43b 100644
--- a/packages/quill/packages/charts/src/core/chart-shell.tsx
+++ b/packages/quill/packages/charts/src/core/chart-shell.tsx
@@ -38,11 +38,13 @@ export interface ChartShellProps {
pointer: boolean
/** Show the crosshair cursor — a drag gesture (e.g. drag-to-zoom) is available. */
crosshair?: boolean
+ /** Mark the wrapper when a right click selects a point, so a host menu can tell that the chart handles it. */
+ contextMenu?: boolean
ariaLabel: string
/** Number of x labels. Tests read it to hover a label by index. */
labelCount?: number
handlers: Required<Pick<React.DOMAttributes<HTMLDivElement>, 'onMouseMove' | 'onMouseLeave' | 'onClick'>> &
- Pick<React.DOMAttributes<HTMLDivElement>, 'onMouseDown' | 'onPointerDown'>
+ Pick<React.DOMAttributes<HTMLDivElement>, 'onMouseDown' | 'onPointerDown' | 'onContextMenu'>
/** Render the overlay layer — bases gate this on layout readiness (dimensions + scales). */
showOverlay: boolean
children?: React.ReactNode
@@ -68,6 +70,7 @@ export function ChartShell({
dataAttr,
pointer,
crosshair = false,
+ contextMenu = false,
ariaLabel,
labelCount,
handlers,
@@ -79,11 +82,13 @@ export function ChartShell({
ref={wrapperRef}
className={[WRAPPER_CLASS, cursorClass(pointer, crosshair), className].filter(Boolean).join(' ')}
data-attr={dataAttr}
+ data-hog-charts-context-menu={contextMenu ? '' : undefined}
data-hog-charts-label-count={labelCount}
onMouseDown={handlers.onMouseDown}
onMouseMove={handlers.onMouseMove}
onMouseLeave={handlers.onMouseLeave}
onClick={handlers.onClick}
+ onContextMenu={handlers.onContextMenu}
onPointerDown={handlers.onPointerDown}
>
<canvas ref={canvasRef} role="img" aria-label={ariaLabel} className={STATIC_CANVAS_CLASS} />
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.test.ts b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.test.ts
index 7712db53a534..a95187268a24 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.test.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.test.ts
@@ -129,7 +129,8 @@ describe('useChartInteraction — tooltip pinning', () => {
function renderInteraction(
pinnable = true,
onPointClick?: (data: unknown) => void,
- resolveClickToNearestSeries = false
+ resolveClickToNearestSeries = false,
+ onPointContextMenu?: (data: unknown) => void
): RenderHookResult<ReturnType<typeof useChartInteraction>, unknown> {
return renderHook(() =>
useChartInteraction({
@@ -143,6 +144,7 @@ describe('useChartInteraction — tooltip pinning', () => {
pinnable,
resolveClickToNearestSeries,
onPointClick: onPointClick as never,
+ onPointContextMenu: onPointContextMenu as never,
resolveValue: (s, i) => s.data[i],
})
)
@@ -429,6 +431,38 @@ describe('useChartInteraction — tooltip pinning', () => {
}
)
+ it.each<[string, boolean, boolean, string | null]>([
+ ['fires onPointContextMenu for the nearest series', true, false, 'b'],
+ ['fires onPointContextMenu and keeps the pin on a pinned tooltip', true, true, 'b'],
+ ['does nothing without onPointContextMenu', false, false, null],
+ ])('a right click %s', (_, withContextMenu, pinned, expectedKey) => {
+ const onPointClick = jest.fn()
+ const onPointContextMenu = jest.fn()
+ const { result } = renderInteraction(
+ true,
+ onPointClick,
+ false,
+ withContextMenu ? onPointContextMenu : undefined
+ )
+ if (pinned) {
+ hoverAndPin(result)
+ }
+
+ mockWrapperRect(refs)
+ act(() => {
+ result.current.handlers.onContextMenu({
+ target: refs.wrapperRef.current!,
+ currentTarget: refs.wrapperRef.current!,
+ clientX: 200,
+ clientY: 185,
+ } as unknown as React.MouseEvent<HTMLDivElement>)
+ })
+
+ expect(onPointContextMenu.mock.calls.map(([data]) => data.series.key)).toEqual(expectedKey ? [expectedKey] : [])
+ expect(onPointClick).not.toHaveBeenCalled()
+ expect(result.current.tooltipCtx?.isPinned ?? false).toBe(pinned)
+ })
+
it('rebuilds the pinned tooltip when series data changes underneath the pin', () => {
const { rerender, result } = renderHook(
({ s }: { s: typeof series }) =>
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
index 477c81f8dd3c..9e3c6cfcf48e 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartInteraction.ts
@@ -45,6 +45,8 @@ interface UseChartInteractionOptions<Meta> {
/** See `TooltipConfig.resolveClickToNearestSeries`. */
resolveClickToNearestSeries?: boolean
onPointClick?: (data: PointClickData<Meta>) => void
+ /** See `ChartProps.onPointContextMenu`. */
+ onPointContextMenu?: (data: PointClickData<Meta>) => void
/** See `ChartProps.isPointClickable`. */
isPointClickable?: (dataIndex: number) => boolean
onDateRangeZoom?: (data: DateRangeZoomData) => void
@@ -112,6 +114,7 @@ interface UseChartInteractionResult<Meta> {
onMouseLeave: () => void
onClick: (e: React.MouseEvent<HTMLDivElement>) => void
onPointerDown: (e: React.PointerEvent<HTMLDivElement>) => void
+ onContextMenu: (e: React.MouseEvent<HTMLDivElement>) => void
}
}
@@ -126,6 +129,7 @@ export function useChartInteraction<Meta = unknown>({
pinnable,
resolveClickToNearestSeries = false,
onPointClick,
+ onPointContextMenu,
isPointClickable,
onDateRangeZoom,
onAreaSelect,
@@ -480,6 +484,42 @@ export function useChartInteraction<Meta = unknown>({
]
)
+ // Resolves the point from the event position, not the hover state, because a pinned tooltip
+ // freezes the hover state at the pinned point.
+ const onContextMenu = useCallback(
+ (e: React.MouseEvent<HTMLDivElement>) => {
+ if (!onPointContextMenu || originatesInTooltip(e)) {
+ return
+ }
+ const rect = e.currentTarget.getBoundingClientRect()
+ const position = { x: e.clientX - rect.left, y: e.clientY - rect.top }
+ const index = resolveIndexAt(position.x, position.y)
+ if (index < 0 || index >= labels.length || !(isPointClickable?.(index) ?? true)) {
+ return
+ }
+ const ctx = buildCtxAt(index, position)
+ const clickData =
+ ctx && ctx.seriesData.length > 1
+ ? resolveNearestSeriesClickData(index, series, labels, ctx, interactionAxis, position)
+ : buildPointClickData(index, series, labels, resolveValue, position)
+ if (clickData) {
+ onPointContextMenu(wrapClickData && scales ? wrapClickData(clickData, scales) : clickData)
+ }
+ },
+ [
+ onPointContextMenu,
+ isPointClickable,
+ series,
+ labels,
+ resolveValue,
+ interactionAxis,
+ wrapClickData,
+ scales,
+ resolveIndexAt,
+ buildCtxAt,
+ ]
+ )
+
const guardedMouseDown = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (originatesInTooltip(e) || originatesInInteractiveOverlay(e)) {
@@ -491,8 +531,8 @@ export function useChartInteraction<Meta = unknown>({
)
const handlers = useMemo(
- () => ({ onMouseDown: guardedMouseDown, onMouseMove, onMouseLeave, onClick, onPointerDown }),
- [guardedMouseDown, onMouseMove, onMouseLeave, onClick, onPointerDown]
+ () => ({ onMouseDown: guardedMouseDown, onMouseMove, onMouseLeave, onClick, onPointerDown, onContextMenu }),
+ [guardedMouseDown, onMouseMove, onMouseLeave, onClick, onPointerDown, onContextMenu]
)
return { hoverIndex, hoverPosition, tooltipCtx, dragRect, handlers }
diff --git a/packages/quill/packages/charts/src/docs/interactions.md b/packages/quill/packages/charts/src/docs/interactions.md
index 1e649e5e9444..60e0f7674cd7 100644
--- a/packages/quill/packages/charts/src/docs/interactions.md
+++ b/packages/quill/packages/charts/src/docs/interactions.md
@@ -13,6 +13,17 @@ Other points keep hover and tooltip, and show the drag crosshair if the chart ha
Chart-specific variants: `FunnelChart.onStepClick` reports `{ stepIndex, converted }`, where `converted: false` means the hatched drop-off track was clicked; `PieChart.onSliceClick`; `BoxPlot.onBoxClick`; `Heatmap.onCellClick` reports `{ xIndex, yIndex, value }`; `ScatterChart.onPointClick` receives the resolved `ScatterPointDatum`.
+## Right click: `onPointContextMenu`
+
+On `LineChart`, `TimeSeriesLineChart`, `BarChart`, `TimeSeriesBarChart`, and the base `Chart`.
+It fires on a right click with the same `PointClickData` as `onPointClick`, for the series nearest the cursor.
+
+- A right click never pins or unpins the tooltip, and it works while a tooltip is pinned.
+- `isPointClickable` limits it the same way it limits `onPointClick`. A right click outside the plot area, or on a point that is not clickable, fires nothing.
+- The chart does not suppress the browser menu. Call `preventDefault()` on the `contextmenu` event in the host, for example to show your own menu.
+- When the prop is set, the chart root carries `data-hog-charts-context-menu`, so a host can tell that the chart handles right clicks itself.
+- Other charts have no right-click callback yet.
+
## Drag-to-zoom: `onDateRangeZoom`
On `LineChart`, `TimeSeriesLineChart`, `BarChart`, `TimeSeriesBarChart`, and the base `Chart`.
diff --git a/products/business_intelligence/frontend/BIDrilldownMenu.test.tsx b/products/business_intelligence/frontend/BIDrilldownMenu.test.tsx
index 2fcc079afb07..10fb7536bdd8 100644
--- a/products/business_intelligence/frontend/BIDrilldownMenu.test.tsx
+++ b/products/business_intelligence/frontend/BIDrilldownMenu.test.tsx
@@ -41,11 +41,11 @@ describe('native result-menu links', () => {
const props = {
key: 'native-links',
query,
- dashboardMenu: true,
}
const logic = biDrilldownLogic(props)
const unmount = logic.mount()
try {
+ logic.actions.setInteraction({ x: 40, y: 40 })
logic.actions.inspect({ status: 'paid' })
render(<BIDrilldownMenu logicProps={props} />)
await screen.findByText('View underlying rows')
diff --git a/products/business_intelligence/frontend/BIDrilldownMenu.tsx b/products/business_intelligence/frontend/BIDrilldownMenu.tsx
index 09a4eca014f1..22d98a351fc7 100644
--- a/products/business_intelligence/frontend/BIDrilldownMenu.tsx
+++ b/products/business_intelligence/frontend/BIDrilldownMenu.tsx
@@ -15,7 +15,7 @@ export function BIDrilldownMenu({
}): JSX.Element | null {
const { selection, queries, interaction, showRows } = useValues(biDrilldownLogic(logicProps))
const { close, viewRows, openSqlEditor } = useActions(biDrilldownLogic(logicProps))
- if (!selection || showRows) {
+ if (!selection || !interaction || showRows) {
return null
}
const selectedResult =
diff --git a/products/business_intelligence/frontend/BIDrilldownModal.tsx b/products/business_intelligence/frontend/BIDrilldownModal.tsx
index d14b200f8a7f..c6115c52e8c8 100644
--- a/products/business_intelligence/frontend/BIDrilldownModal.tsx
+++ b/products/business_intelligence/frontend/BIDrilldownModal.tsx
@@ -20,12 +20,12 @@ export function BIDrilldownModal({
onNavigate?: (worksheet: BIVisualizationNode) => void
navigationDisabledReason?: string
}): JSX.Element {
- const { selection, queries, showRows, hierarchyDrills } = useValues(biDrilldownLogic(props))
+ const { selection, queries, showRows, hierarchyDrills, interaction } = useValues(biDrilldownLogic(props))
const { close, viewRows } = useActions(biDrilldownLogic(props))
return (
<LemonModal
title="Explore this result"
- isOpen={!!selection && (!props.dashboardMenu || showRows)}
+ isOpen={!!selection && (!interaction || showRows)}
onClose={close}
width={showRows ? '90vw' : 520}
>
@@ -45,7 +45,7 @@ export function BIDrilldownModal({
</ul>
) : null}
<div className="flex flex-wrap gap-2">
- {!props.dashboardMenu &&
+ {!interaction &&
hierarchyDrills.map(({ hierarchy, next, worksheet }) => (
<LemonButton
key={hierarchy.id}
@@ -66,7 +66,7 @@ export function BIDrilldownModal({
{onNavigate ? '' : ' in new worksheet'}
</LemonButton>
))}
- {!props.dashboardMenu && (
+ {!interaction && (
<LemonButton
type="primary"
onClick={() => {
diff --git a/products/business_intelligence/frontend/biDrilldownLogic.ts b/products/business_intelligence/frontend/biDrilldownLogic.ts
index ab1781fe25be..d036c9f06ec5 100644
--- a/products/business_intelligence/frontend/biDrilldownLogic.ts
+++ b/products/business_intelligence/frontend/biDrilldownLogic.ts
@@ -1,7 +1,5 @@
import { MakeLogicType, actions, kea, key, path, props, reducers, selectors, listeners } from 'kea'
-import { objectsEqual } from 'lib/utils/objects'
-
import { VisualizationNode, NodeKind, DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'
import { BIDrillSelection, getBIDrillQueries, getBIDrillSelection, getBIEffectiveQuery } from './biDrilldown'
@@ -13,13 +11,11 @@ export interface BIDrilldownProps {
query: VisualizationNode
filtersOverride?: DashboardFilter | null
variablesOverride?: Record<string, HogQLVariable> | null
- dashboardMenu?: boolean
}
export interface BIDrillInteraction {
x: number
y: number
- clickCount: number
timestamp?: number
}
@@ -82,7 +78,7 @@ export const biDrilldownLogic = kea<biDrilldownLogicType>([
close: true,
viewRows: true,
}),
- reducers(({ props }) => ({
+ reducers({
interaction: [
null as BIDrillInteraction | null,
{ setInteraction: (_, { interaction }) => interaction, close: () => null },
@@ -90,13 +86,12 @@ export const biDrilldownLogic = kea<biDrilldownLogicType>([
record: [
null as Record<string, unknown> | null,
{
- inspect: (previous, { record }) =>
- props.dashboardMenu ? (objectsEqual(previous, record) ? null : record) : record,
+ inspect: (_, { record }) => record,
close: () => null,
},
],
showRows: [false, { inspect: () => false, viewRows: () => true, close: () => false }],
- })),
+ }),
selectors({
hierarchyDrills: [
(s) => [s.selection, s.query],
@@ -126,10 +121,6 @@ export const biDrilldownLogic = kea<biDrilldownLogicType>([
}),
listeners(({ values, actions }) => ({
inspect: () => {
- if (!values.record) {
- actions.close()
- return
- }
if (values.query.kind === NodeKind.BIVisualizationNode && values.selection) {
captureBIWorksheetAction('drilldown_opened', values.query.config, {
previous_period: values.selection.previous,
diff --git a/products/dashboards/frontend/components/DashboardInsightResultMenu.test.tsx b/products/dashboards/frontend/components/DashboardInsightResultMenu.test.tsx
index a02a444e0331..c95e1d41c230 100644
--- a/products/dashboards/frontend/components/DashboardInsightResultMenu.test.tsx
+++ b/products/dashboards/frontend/components/DashboardInsightResultMenu.test.tsx
@@ -59,7 +59,7 @@ describe('dashboard result menu', () => {
<button onClick={() => openPersonsModal(request)}>Lifecycle point</button>
</DashboardInsightResultMenu>
)
- fireEvent.click(screen.getByText('Lifecycle point'))
+ fireEvent.contextMenu(screen.getByText('Lifecycle point'))
await waitFor(() => expect(screen.getByText('Open in SQL editor').closest('a')).not.toBeNull())
expect(screen.queryByText('View recordings')).not.toBeInTheDocument()
expect(queryRunner.performQuery).toHaveBeenCalledWith(
@@ -97,7 +97,7 @@ describe('dashboard result menu', () => {
<div>Snapshot chart</div>
</DashboardInsightResultMenu>
)
- fireEvent.click(screen.getByText('Snapshot chart'))
+ fireEvent.contextMenu(screen.getByText('Snapshot chart'))
for (const label of ['View underlying rows', 'Open in SQL editor']) {
const link = screen.getByText(label).closest('a')!
expect(JSON.parse(new URL(link.href).searchParams.get('open_query')!)).toEqual({
@@ -141,7 +141,7 @@ describe('dashboard result menu', () => {
<button onClick={() => openPersonsModal(request)}>Chart point</button>
</DashboardInsightResultMenu>
)
- fireEvent.click(screen.getByText('Chart point'))
+ expect(fireEvent.contextMenu(screen.getByText('Chart point'))).toBe(false)
expect(openedModal).not.toHaveBeenCalled()
expect(screen.getByText('Selected country')).toBeInTheDocument()
expect(screen.queryByText('Explore in new insight')).not.toBeInTheDocument()
@@ -153,7 +153,9 @@ describe('dashboard result menu', () => {
])
fireEvent.click(screen.getByText('Chart point'))
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
- fireEvent.click(screen.getByText('Chart point'))
+ expect(openedModal).toHaveBeenCalledWith(request)
+ openedModal.mockClear()
+ fireEvent.contextMenu(screen.getByText('Chart point'))
const rows = screen.getByText('View people')
const href = rows.closest('a')!.getAttribute('href')!
expect(decodeURIComponent(href)).toContain('"kind":"ActorsQuery"')
@@ -200,7 +202,7 @@ describe('dashboard result menu', () => {
<button onClick={() => openPersonsModal(request)}>Funnel point</button>
</DashboardInsightResultMenu>
)
- fireEvent.click(screen.getByText('Funnel point'))
+ fireEvent.contextMenu(screen.getByText('Funnel point'))
await waitFor(() => expect(screen.getByText('Open in SQL editor').closest('a')).not.toBeNull())
expect(queryRunner.performQuery).toHaveBeenCalledWith(
expect.objectContaining({ source: request.query }),
@@ -236,9 +238,9 @@ describe('dashboard result menu', () => {
<button onClick={() => openPersonsModal(point('2026-01-02'))}>Second point</button>
</DashboardInsightResultMenu>
)
- fireEvent.click(screen.getByText('First point'))
+ fireEvent.contextMenu(screen.getByText('First point'))
await waitFor(() => expect(queryRunner.performQuery).toHaveBeenCalledTimes(1))
- fireEvent.click(screen.getByText('Second point'))
+ fireEvent.contextMenu(screen.getByText('Second point'))
await waitFor(() => expect(queryRunner.performQuery).toHaveBeenCalledTimes(2))
const firstCall = jest.mocked(queryRunner.performQuery).mock.calls[0]
const secondCall = jest.mocked(queryRunner.performQuery).mock.calls[1]
@@ -248,8 +250,7 @@ describe('dashboard result menu', () => {
expect(secondCall[1]?.signal?.aborted).toBe(false)
await act(async () => resolveFirst({ hogql: 'SELECT 1', results: [] } as unknown as ActorsQueryResponse))
expect(screen.getByText('Open in SQL editor').closest('a')).toBeNull()
- fireEvent.click(screen.getByText('Second point'))
- fireEvent.click(screen.getByText('Second point'))
+ fireEvent.contextMenu(screen.getByText('Second point'))
await waitFor(() => expect(screen.getByText('Open in SQL editor').closest('a')).not.toBeNull())
const link = screen.getByText('Open in SQL editor').closest('a')!
expect(new URL(link.href).searchParams.get('open_query')).toBe('SELECT 2')
@@ -281,7 +282,7 @@ describe('dashboard result menu', () => {
</button>
</DashboardInsightResultMenu>
)
- fireEvent.click(screen.getByText('Chart point'))
+ fireEvent.contextMenu(screen.getByText('Chart point'))
await waitFor(() => expect(queryRunner.performQuery).toHaveBeenCalledTimes(1))
const call = jest.mocked(queryRunner.performQuery).mock.calls[0]
if (finish === 'complete') {
@@ -303,6 +304,35 @@ describe('dashboard result menu', () => {
}
})
+ it.each([
+ [
+ 'a context menu that a child handles',
+ (onClick: () => void) => (
+ <div onClick={onClick} onContextMenu={(event) => event.preventDefault()}>
+ Target
+ </div>
+ ),
+ ],
+ [
+ 'a legend row',
+ (onClick: () => void) => (
+ <div data-hog-charts-legend="">
+ <button onClick={onClick}>Target</button>
+ </div>
+ ),
+ ],
+ ])('leaves %s alone', (_, renderTarget) => {
+ const onClick = jest.fn()
+ render(
+ <DashboardInsightResultMenu insight={insightOnDashboard(1, [1])}>
+ {renderTarget(onClick)}
+ </DashboardInsightResultMenu>
+ )
+ fireEvent.contextMenu(screen.getByText('Target'))
+ expect(onClick).not.toHaveBeenCalled()
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ })
+
it('does not offer recordings for a drilldown without recording support', () => {
const request: OpenPersonsModalProps = {
title: 'Selected people',
@@ -316,7 +346,7 @@ describe('dashboard result menu', () => {
<button onClick={() => openPersonsModal(request)}>Chart point</button>
</DashboardInsightResultMenu>
)
- fireEvent.click(screen.getByText('Chart point'))
+ fireEvent.contextMenu(screen.getByText('Chart point'))
expect(screen.queryByText('View recordings')).not.toBeInTheDocument()
fireEvent.scroll(window)
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
diff --git a/products/dashboards/frontend/components/DashboardInsightResultMenu.tsx b/products/dashboards/frontend/components/DashboardInsightResultMenu.tsx
index cc48235e0fa1..c9349ee56ef7 100644
--- a/products/dashboards/frontend/components/DashboardInsightResultMenu.tsx
+++ b/products/dashboards/frontend/components/DashboardInsightResultMenu.tsx
@@ -3,7 +3,12 @@ import { ReactNode, useId, useRef, useState } from 'react'
import { capturePersonsModalForClick, CapturedPersonsModal } from 'lib/components/ResultMenu/personsModalCapture'
import { ResultMenu } from 'lib/components/ResultMenu/ResultMenu'
-import { objectsEqual } from 'lib/utils/objects'
+import {
+ getResultMenuPoint,
+ isResultMenuContextMenu,
+ replayAsClick,
+ ResultMenuPoint,
+} from 'lib/components/ResultMenu/resultMenuTrigger'
import { getPersonsRecordingFilters } from 'scenes/trends/persons-modal/getPersonsRecordingFilters'
import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'
import { urls } from 'scenes/urls'
@@ -27,10 +32,19 @@ export function DashboardInsightResultMenu({
insight: InsightModel
children: ReactNode
}): JSX.Element {
- const [position, setPosition] = useState<{ x: number; y: number; timestamp: number } | null>(null)
+ const [position, setPosition] = useState<ResultMenuPoint | null>(null)
const [actors, setActors] = useState<CapturedPersonsModal | null>(null)
+ // Each opened menu loads its result again, so selecting the same point again retries a failed load.
+ const [selection, setSelection] = useState(0)
+ const menuId = useId()
const triggerRef = useRef<HTMLDivElement>(null)
const captured = useRef(false)
+ const replaying = useRef(false)
+ const open = (point: ResultMenuPoint, request: CapturedPersonsModal | null): void => {
+ setActors(request)
+ setPosition(point)
+ setSelection((current) => current + 1)
+ }
const close = (): void => {
setPosition(null)
setActors(null)
@@ -79,7 +93,7 @@ export function DashboardInsightResultMenu({
: undefined
const { selectedResult: resolvedResult, resultLoading } = useValues(
dashboardInsightResultMenuLogic({
- key: useId(),
+ key: `${menuId}-${selection}`,
query: position && rowsQuery && isActorsQuery(rowsQuery.source) ? rowsQuery.source : null,
})
)
@@ -90,7 +104,7 @@ export function DashboardInsightResultMenu({
: undefined
const resultUnavailableReason = resultLoading
? 'Loading the selected result…'
- : 'Could not load the selected result. Select the data point again to retry.'
+ : 'Could not load the selected result. Right-click the data point again to retry.'
const selectedResult = actors?.title
? typeof actors.title === 'function'
? actors.title('Results')
@@ -101,59 +115,38 @@ export function DashboardInsightResultMenu({
ref={triggerRef}
className="flex flex-1 flex-col min-h-0 h-full"
onClickCapture={(event) => {
- if (
- !event.currentTarget.contains(event.target as Node) ||
- (event.target as Element).closest('a, input, select') ||
- event.metaKey ||
- event.ctrlKey ||
- event.altKey ||
- event.shiftKey
- ) {
+ if (position && !replaying.current && event.currentTarget.contains(event.target as Node)) {
+ close()
+ }
+ }}
+ onContextMenuCapture={(event) => {
+ if (!isResultMenuContextMenu(event)) {
return
}
captured.current = false
- const rect = (event.target as Element).getBoundingClientRect()
- const point = {
- x: event.detail ? event.clientX : rect.x + rect.width / 2,
- y: event.detail ? event.clientY : rect.y + rect.height / 2,
- timestamp: event.timeStamp,
- }
+ const point = getResultMenuPoint(event)
capturePersonsModalForClick((request) => {
captured.current = true
- if (
- position &&
- actors &&
- objectsEqual(actors.query, request.query) &&
- objectsEqual(actors.rowsQuery, request.rowsQuery) &&
- actors.url === request.url &&
- actors.urlsIndex === request.urlsIndex &&
- objectsEqual(actors.urls, request.urls)
- ) {
- close()
- return
- }
- setActors(request)
- setPosition(point)
+ open(point, request)
})
}}
- onClick={(event) => {
- if (
- !event.currentTarget.contains(event.target as Node) ||
- captured.current ||
- (event.target as Element).closest('a, button, input, select, [role="button"]') ||
- event.metaKey ||
- event.ctrlKey ||
- event.altKey ||
- event.shiftKey
- ) {
+ onContextMenu={(event) => {
+ if (!isResultMenuContextMenu(event)) {
return
}
- if (position) {
- close()
- return
+ event.preventDefault()
+ // A chart with `onPointContextMenu` captures its result before this handler runs.
+ if (!captured.current) {
+ replaying.current = true
+ try {
+ replayAsClick(event)
+ } finally {
+ replaying.current = false
+ }
+ }
+ if (!captured.current) {
+ open(getResultMenuPoint(event), null)
}
- setActors(null)
- setPosition({ x: event.clientX, y: event.clientY, timestamp: event.timeStamp })
}}
>
{children}
@@ -172,7 +165,7 @@ export function DashboardInsightResultMenu({
inPlace: !!actors,
disabledReason:
!actors && !sqlQuery
- ? 'Select a data point to view the users or groups behind it.'
+ ? 'Right-click a data point to view the users or groups behind it.'
: undefined,
onClick: () => {
const request = actors
@@ -213,7 +206,7 @@ export function DashboardInsightResultMenu({
? undefined
: actors
? resultUnavailableReason
- : 'Select a data point to edit its underlying query.',
+ : 'Right-click a data point to edit its underlying query.',
onClick: close,
},
]}
diff --git a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx
index a77e8f4a8e54..8cc40d5963e5 100644
--- a/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx
+++ b/products/product_analytics/frontend/insights/funnels/FunnelLineChart/FunnelLineChart.tsx
@@ -148,13 +148,12 @@ export function FunnelLineChart({
showTrendLines: funnelsFilter?.showTrendLines ?? false,
valueLabels: showValuesOnSeries ? { formatter: (value) => `${value}%` } : false,
showCrosshair: true,
- tooltip: { ...INSIGHT_TOOLTIP_CONFIG, resolveClickToNearestSeries: context?.dashboardResultMenu },
+ tooltip: INSIGHT_TOOLTIP_CONFIG,
}),
curve: chartStyleCurve(funnelsFilter?.chartStyle),
legend: legendConfig,
}),
[
- context?.dashboardResultMenu,
steps,
interval,
timezone,
@@ -264,6 +263,7 @@ export function FunnelLineChart({
config={chartConfig}
tooltip={renderTooltip}
onPointClick={showPersonsModal ? onPointClick : undefined}
+ onPointContextMenu={context?.dashboardResultMenu && showPersonsModal ? onPointClick : undefined}
onDateRangeZoom={onDateRangeZoom}
className="LineGraph"
dataAttr="trend-line-graph-funnel"
diff --git a/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsx b/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsx
index a3825f19460d..0a0c42d557fe 100644
--- a/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsx
+++ b/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsx
@@ -162,15 +162,12 @@ export function RetentionBarChart({
isPercentage,
goalLines,
series,
- tooltip: {
- ...INSIGHT_TOOLTIP_CONFIG,
- resolveClickToNearestSeries: resultMenuEnabled && !inSharedMode,
- },
+ tooltip: INSIGHT_TOOLTIP_CONFIG,
isIntervalView,
period,
timezone,
}),
- [resultMenuEnabled, inSharedMode, isPercentage, goalLines, series, isIntervalView, period, timezone]
+ [isPercentage, goalLines, series, isIntervalView, period, timezone]
)
if (filteredTrendSeries.length === 0 && hasValidBreakdown) {
@@ -189,6 +186,7 @@ export function RetentionBarChart({
config={barConfig}
tooltip={renderTooltip}
onPointClick={canClick ? onPointClick : undefined}
+ onPointContextMenu={resultMenuEnabled && !inSharedMode && canClick ? onPointClick : undefined}
className="LineGraph"
dataAttr="trend-line-graph"
onError={handleChartError}
diff --git a/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx b/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx
index d682c2e40ff4..f091bf4747c0 100644
--- a/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx
+++ b/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx
@@ -198,28 +198,14 @@ export function RetentionLineChart({
goalLines,
showTrendLines,
series,
- tooltip: {
- ...INSIGHT_TOOLTIP_CONFIG,
- resolveClickToNearestSeries: resultMenuEnabled && !inSharedMode,
- },
+ tooltip: INSIGHT_TOOLTIP_CONFIG,
isIntervalView,
period,
timezone,
}),
curve: chartStyleCurve(retentionFilter?.chartStyle),
}),
- [
- resultMenuEnabled,
- inSharedMode,
- isPercentage,
- goalLines,
- showTrendLines,
- series,
- isIntervalView,
- period,
- timezone,
- retentionFilter?.chartStyle,
- ]
+ [isPercentage, goalLines, showTrendLines, series, isIntervalView, period, timezone, retentionFilter?.chartStyle]
)
if (filteredTrendSeries.length === 0 && hasValidBreakdown) {
@@ -246,6 +232,7 @@ export function RetentionLineChart({
config={lineConfig}
tooltip={renderTooltip}
onPointClick={canClick ? onPointClick : undefined}
+ onPointContextMenu={resultMenuEnabled && !inSharedMode && canClick ? onPointClick : undefined}
className="LineGraph"
dataAttr="trend-line-graph"
onError={handleChartError}
diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx
index 85ab3e1c347a..dbf027d8cde5 100644
--- a/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx
+++ b/products/product_analytics/frontend/insights/stickiness/StickinessBarChart/StickinessBarChart.tsx
@@ -132,12 +132,12 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.El
yAxisScaleType,
isGrouped,
valueLabels: showValuesOnSeries ? { formatter: stickinessPercentFormatter } : false,
- tooltip: { ...tooltipConfig, resolveClickToNearestSeries: context?.dashboardResultMenu },
+ tooltip: tooltipConfig,
}),
// Interactive legend is a component concern, kept out of the pure transform.
legend: legendConfig,
}),
- [context?.dashboardResultMenu, yAxisScaleType, isGrouped, showValuesOnSeries, legendConfig, tooltipConfig]
+ [yAxisScaleType, isGrouped, showValuesOnSeries, legendConfig, tooltipConfig]
)
// Close over the primitives so the click memos don't invalidate when unrelated
@@ -223,6 +223,7 @@ export function StickinessBarChart({ context }: StickinessBarChartProps): JSX.El
config={chartConfig}
tooltip={renderTooltip}
onPointClick={hasClickHandler ? onPointClick : undefined}
+ onPointContextMenu={context?.dashboardResultMenu && hasClickHandler ? onPointClick : undefined}
className="BarGraph"
dataAttr="stickiness-bar-graph"
onError={handleChartError}
diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx
index 34a6575e5f32..c89be9ff25de 100644
--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx
+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.tsx
@@ -132,20 +132,13 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.
yAxisScaleType,
valueLabels: showValuesOnSeries ? { formatter: stickinessPercentFormatter } : false,
showCrosshair: true,
- tooltip: { ...tooltipConfig, resolveClickToNearestSeries: context?.dashboardResultMenu },
+ tooltip: tooltipConfig,
}),
curve: chartStyleCurve(stickinessFilter?.chartStyle),
// Interactive legend is a component concern, kept out of the pure transform.
legend: legendConfig,
}),
- [
- context?.dashboardResultMenu,
- yAxisScaleType,
- showValuesOnSeries,
- legendConfig,
- tooltipConfig,
- stickinessFilter?.chartStyle,
- ]
+ [yAxisScaleType, showValuesOnSeries, legendConfig, tooltipConfig, stickinessFilter?.chartStyle]
)
const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModal
@@ -227,6 +220,7 @@ export function StickinessLineChart({ context }: StickinessLineChartProps): JSX.
config={chartConfig}
tooltip={renderTooltip}
onPointClick={canHandleClick ? onPointClick : undefined}
+ onPointContextMenu={context?.dashboardResultMenu && canHandleClick ? onPointClick : undefined}
className="LineGraph"
dataAttr="trend-line-graph"
onError={handleChartError}
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
index 5342183d575c..519fe63f4cb2 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.test.tsx
@@ -121,8 +121,8 @@ describe('TrendsBarChart (ActionsBar)', () => {
)
})
- it.each([false, true])('opens the persons modal directly on a dashboard (compare=%s)', async (compare) => {
- renderInsight({ query: trendsBar({ compareFilter: { compare } }), context: { dashboardResultMenu: true } })
+ it('opens the persons modal on click for a single series', async () => {
+ renderInsight({ query: trendsBar() })
await screen.findByLabelText(/chart with/i, undefined, { timeout: 5000 })
await chart.clickAtIndex(2)
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
index fdcb54ffdfe4..bfbbf01a396b 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
@@ -265,7 +265,7 @@ export function TrendsBarChart({
yAxisLabel: trendsFilter?.yAxisLabel,
goalLines,
valueLabels: showValuesOnSeries ? { formatter: valueLabelFormatter } : false,
- tooltip: { ...INSIGHT_TOOLTIP_CONFIG, resolveClickToNearestSeries: context?.dashboardResultMenu },
+ tooltip: INSIGHT_TOOLTIP_CONFIG,
}),
// Interactive legend (toggle callbacks, context menu) is a component concern, kept out
// of the pure transform so the builder stays free of React state.
@@ -281,7 +281,6 @@ export function TrendsBarChart({
timezone,
currentPeriodResult?.days,
hideAxes,
- context?.dashboardResultMenu,
trendsFilter?.xAxisLabel,
trendsFilter?.yAxisLabel,
goalLines,
@@ -312,7 +311,7 @@ export function TrendsBarChart({
}
return {
showGrid: true,
- tooltip: { ...AGGREGATED_TOOLTIP_CONFIG, resolveClickToNearestSeries: context?.dashboardResultMenu },
+ tooltip: AGGREGATED_TOOLTIP_CONFIG,
yScaleType: yAxisScaleType === 'log10' ? 'log' : 'linear',
axisOrientation: 'horizontal',
barLayout: 'stacked',
@@ -333,7 +332,6 @@ export function TrendsBarChart({
bars: { fitToHeight: embedded, divergingStack: true },
}
}, [
- context?.dashboardResultMenu,
hideAxes,
yAxisScaleType,
aggregatedYTickFormatter,
@@ -469,6 +467,7 @@ export function TrendsBarChart({
theme={theme}
tooltip={renderTooltip}
onPointClick={canHandleClick ? onPointClick : undefined}
+ onPointContextMenu={context?.dashboardResultMenu && canHandleClick ? onPointClick : undefined}
className="BarGraph"
dataAttr="trend-bar-value-graph"
onError={handleChartError}
@@ -511,6 +510,7 @@ export function TrendsBarChart({
theme={theme}
tooltip={renderTooltip}
onPointClick={canHandleClick ? onPointClick : undefined}
+ onPointContextMenu={context?.dashboardResultMenu && canHandleClick ? onPointClick : undefined}
onDateRangeZoom={onDateRangeZoom}
className="BarGraph"
dataAttr="trend-bar-graph"
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
index 52324bb09cf6..b3690f6d94ab 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/TrendsLifecycleChart.tsx
@@ -140,11 +140,10 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi
timezone,
allDays: currentPeriodResult?.days ?? [],
valueLabels: showValuesOnSeries || showPercentagesOnSeries ? { formatter: valueLabelFormatter } : false,
- tooltip: { ...LIFECYCLE_TOOLTIP_CONFIG, resolveClickToNearestSeries: context?.dashboardResultMenu },
+ tooltip: LIFECYCLE_TOOLTIP_CONFIG,
legend: legendConfig,
}),
[
- context?.dashboardResultMenu,
indexedResults,
buildMeta,
currentPeriodResult?.labels,
@@ -261,6 +260,7 @@ export function TrendsLifecycleChart({ context, inSharedMode = false }: TrendsLi
theme={theme}
tooltip={renderTooltip}
onPointClick={canHandleClick ? onPointClick : undefined}
+ onPointContextMenu={context?.dashboardResultMenu && canHandleClick ? onPointClick : undefined}
onDateRangeZoom={onDateRangeZoom}
className="BarGraph"
dataAttr="trend-lifecycle-graph"
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
index c6256086a8af..db0d7f57308e 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx
@@ -233,6 +233,17 @@ export function TrendsLineChart({
[canHandleClick, canNavigateToInsight, clickDeps, navigateToInsight]
)
+ // Set even when only navigation is possible, so the dashboard menu does not replay the right
+ // click as a left click, which would open the insight.
+ const onPointContextMenu = useCallback(
+ (clickData: PointClickData) => {
+ if (canHandleClick) {
+ handleTrendsChartClick(clickData.series.key, clickData.dataIndex, clickDeps)
+ }
+ },
+ [canHandleClick, clickDeps]
+ )
+
const onDateRangeZoom = useDateRangeZoom(currentPeriodResult?.days, context?.onDateRangeZoom)
const renderTooltip = useCallback(
@@ -349,11 +360,10 @@ export function TrendsLineChart({
valueLabels: showValuesOnSeries && valueLabelFormatter ? { formatter: valueLabelFormatter } : false,
curve: chartStyleCurve(trendsFilter?.chartStyle),
showCrosshair: true,
- tooltip: { ...INSIGHT_TOOLTIP_CONFIG, resolveClickToNearestSeries: context?.dashboardResultMenu },
+ tooltip: INSIGHT_TOOLTIP_CONFIG,
legend: legendConfig,
}),
[
- context?.dashboardResultMenu,
indexedResults,
trendsFilter,
baseCurrency,
@@ -400,6 +410,9 @@ export function TrendsLineChart({
config={config}
tooltip={renderTooltip}
onPointClick={canHandlePointInteraction ? onPointClick : undefined}
+ onPointContextMenu={
+ context?.dashboardResultMenu && canHandlePointInteraction ? onPointContextMenu : undefined
+ }
onDateRangeZoom={onDateRangeZoom}
className="LineGraph"
dataAttr="trend-line-graph"