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.

perf(dashboards): mount the result menu logic only while the menu is open (#125684)

Matt Pua4aa6489e8c61
diff --git a/products/dashboards/frontend/components/DashboardInsightResultMenu.test.tsx b/products/dashboards/frontend/components/DashboardInsightResultMenu.test.tsx
index c95e1d41c230..058b18570cb3 100644
--- a/products/dashboards/frontend/components/DashboardInsightResultMenu.test.tsx
+++ b/products/dashboards/frontend/components/DashboardInsightResultMenu.test.tsx
@@ -1,6 +1,7 @@
import '@testing-library/jest-dom'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { getContext } from 'kea'
import api from 'lib/api'
import { consumePersonsModalClick } from 'lib/components/ResultMenu/personsModalCapture'
@@ -8,7 +9,7 @@ import { openPersonsModal, OpenPersonsModalProps } from 'scenes/trends/persons-m
import * as queryRunner from '~/queries/query'
import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
-import { NodeKind, ActorsQueryResponse, HogQLQuery } from '~/queries/schema/schema-general'
+import { NodeKind, ActorsQueryResponse, DataVisualizationNode, HogQLQuery } from '~/queries/schema/schema-general'
import { insightOnDashboard } from '~/scenes/dashboard/dashboardLogic.testHelpers'
import { initKeaTests } from '~/test/init'
import { BaseMathType, ChartDisplayType, GroupMathType } from '~/types'
@@ -24,6 +25,10 @@ jest.mock('scenes/trends/persons-modal/PersonsModal', () => ({
},
}))
+// Every dashboard tile renders the menu trigger, so a closed menu must not mount its result logic.
+const resultLogicMounted = (): boolean =>
+ Object.keys(getContext().mount.mounted).some((path) => path.includes('dashboardInsightResultMenuLogic'))
+
afterEach(() => {
cleanup()
jest.restoreAllMocks()
@@ -59,8 +64,10 @@ describe('dashboard result menu', () => {
<button onClick={() => openPersonsModal(request)}>Lifecycle point</button>
</DashboardInsightResultMenu>
)
+ expect(resultLogicMounted()).toBe(false)
fireEvent.contextMenu(screen.getByText('Lifecycle point'))
await waitFor(() => expect(screen.getByText('Open in SQL editor').closest('a')).not.toBeNull())
+ expect(resultLogicMounted()).toBe(true)
expect(screen.queryByText('View recordings')).not.toBeInTheDocument()
expect(queryRunner.performQuery).toHaveBeenCalledWith(
expect.objectContaining({ source: request.query, select: ['actor'] }),
@@ -109,6 +116,24 @@ describe('dashboard result menu', () => {
expect(queryRunner.performQuery).not.toHaveBeenCalled()
})
+ it('opens a SQL chart in the SQL editor with its chart display and its rows as a table', () => {
+ const query: DataVisualizationNode = {
+ kind: NodeKind.DataVisualizationNode,
+ source: { kind: NodeKind.HogQLQuery, query: 'SELECT day, count() FROM events GROUP BY day' },
+ display: ChartDisplayType.ActionsLineGraph,
+ }
+ render(
+ <DashboardInsightResultMenu insight={{ ...insightOnDashboard(1, [1]), query }}>
+ <div>SQL chart</div>
+ </DashboardInsightResultMenu>
+ )
+ fireEvent.contextMenu(screen.getByText('SQL chart'))
+ const openQuery = (label: string): unknown =>
+ JSON.parse(new URL(screen.getByText(label).closest('a')!.href).searchParams.get('open_query')!)
+ expect(openQuery('Open in SQL editor')).toEqual(query)
+ expect(openQuery('View underlying rows')).toEqual({ ...query, display: ChartDisplayType.ActionsTable })
+ })
+
it.each([undefined, 0] as const)(
'defers the original datapoint drilldown with all user/group filters intact (group=%s)',
async (groupIndex) => {
diff --git a/products/dashboards/frontend/components/DashboardInsightResultMenu.tsx b/products/dashboards/frontend/components/DashboardInsightResultMenu.tsx
index c9349ee56ef7..32e9f3c645c8 100644
--- a/products/dashboards/frontend/components/DashboardInsightResultMenu.tsx
+++ b/products/dashboards/frontend/components/DashboardInsightResultMenu.tsx
@@ -1,29 +1,19 @@
-import { useValues } from 'kea'
import { ReactNode, useId, useRef, useState } from 'react'
import { capturePersonsModalForClick, CapturedPersonsModal } from 'lib/components/ResultMenu/personsModalCapture'
-import { ResultMenu } from 'lib/components/ResultMenu/ResultMenu'
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'
import { DataTableNode, DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'
-import {
- isActorsQuery,
- isBIVisualizationNode,
- isDataTableNode,
- isDataVisualizationNode,
- isHogQLQuery,
-} from '~/queries/utils'
-import { ChartDisplayType, InsightModel, ReplayTabs } from '~/types'
+import { isBIVisualizationNode, isDataTableNode, isDataVisualizationNode, isHogQLQuery } from '~/queries/utils'
+import { ChartDisplayType, InsightModel } from '~/types'
-import { dashboardInsightResultMenuLogic } from './dashboardInsightResultMenuLogic'
+import { DashboardInsightResultMenuPopover } from './DashboardInsightResultMenuPopover'
export function DashboardInsightResultMenu({
insight,
@@ -91,20 +81,6 @@ export function DashboardInsightResultMenu({
query: isDataTableNode(sqlQuery) ? sqlQuery : { ...sqlQuery, display: ChartDisplayType.ActionsTable },
})
: undefined
- const { selectedResult: resolvedResult, resultLoading } = useValues(
- dashboardInsightResultMenuLogic({
- key: `${menuId}-${selection}`,
- query: position && rowsQuery && isActorsQuery(rowsQuery.source) ? rowsQuery.source : null,
- })
- )
- const sqlUrl = resolvedResult?.sql
- ? urls.sqlEditor({ query: resolvedResult.sql })
- : sqlQuery
- ? urls.sqlEditor({ query: sqlQuery })
- : undefined
- const resultUnavailableReason = resultLoading
- ? 'Loading the selected result…'
- : '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')
@@ -151,65 +127,18 @@ export function DashboardInsightResultMenu({
>
{children}
{position && (
- <ResultMenu
+ <DashboardInsightResultMenuPopover
+ logicKey={`${menuId}-${selection}`}
triggerRef={triggerRef}
+ position={position}
selectedResult={selectedResult}
caption={actors ? insight.name || 'Insight result' : 'Dashboard insight'}
- interaction={position}
+ actors={actors}
+ canViewRecordings={canViewRecordings}
+ sqlQuery={sqlQuery}
+ rowsQuery={rowsQuery}
+ rowsUrl={rowsUrl}
close={close}
- actions={[
- {
- name: sqlQuery ? 'View underlying rows' : 'View people',
- className: 'ResultMenu__rows',
- to: rowsUrl,
- inPlace: !!actors,
- disabledReason:
- !actors && !sqlQuery
- ? 'Right-click a data point to view the users or groups behind it.'
- : undefined,
- onClick: () => {
- const request = actors
- close()
- if (request) {
- request.open ? request.open() : openPersonsModal(request)
- }
- },
- },
- ...(canViewRecordings && recordingQuery
- ? [
- {
- name: 'View recordings',
- className: 'ResultMenu__recordings',
- to: resolvedResult?.sessionIds.length
- ? urls.replay(
- ReplayTabs.Home,
- getPersonsRecordingFilters(
- { kind: NodeKind.ActorsQuery, source: recordingQuery },
- resolvedResult.sessionIds
- )
- )
- : undefined,
- disabledReason: resolvedResult?.sessionIds.length
- ? undefined
- : resolvedResult
- ? 'No recordings found for this result.'
- : resultUnavailableReason,
- onClick: close,
- },
- ]
- : []),
- {
- name: 'Open in SQL editor',
- className: 'ResultMenu__sql',
- to: sqlUrl,
- disabledReason: sqlUrl
- ? undefined
- : actors
- ? resultUnavailableReason
- : 'Right-click a data point to edit its underlying query.',
- onClick: close,
- },
- ]}
/>
)}
</div>
diff --git a/products/dashboards/frontend/components/DashboardInsightResultMenuPopover.tsx b/products/dashboards/frontend/components/DashboardInsightResultMenuPopover.tsx
new file mode 100644
index 000000000000..7397269b79a6
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardInsightResultMenuPopover.tsx
@@ -0,0 +1,122 @@
+import { useValues } from 'kea'
+import { ReactNode, RefObject } from 'react'
+
+import { CapturedPersonsModal } from 'lib/components/ResultMenu/personsModalCapture'
+import { ResultMenu } from 'lib/components/ResultMenu/ResultMenu'
+import { 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'
+
+import { DataTableNode, DataVisualizationNode, NodeKind } from '~/queries/schema/schema-general'
+import { isActorsQuery } from '~/queries/utils'
+import { ReplayTabs } from '~/types'
+
+import { dashboardInsightResultMenuLogic } from './dashboardInsightResultMenuLogic'
+
+/** The open result menu. It mounts the result logic only while the menu is open, because every
+ * dashboard tile renders the menu trigger and each mounted logic slows every later dispatch. */
+export function DashboardInsightResultMenuPopover({
+ logicKey,
+ triggerRef,
+ position,
+ selectedResult,
+ caption,
+ actors,
+ canViewRecordings,
+ sqlQuery,
+ rowsQuery,
+ rowsUrl,
+ close,
+}: {
+ logicKey: string
+ triggerRef: RefObject<HTMLDivElement>
+ position: ResultMenuPoint
+ selectedResult: ReactNode
+ caption: string
+ actors: CapturedPersonsModal | null
+ canViewRecordings: boolean
+ sqlQuery: DataVisualizationNode | DataTableNode | undefined
+ rowsQuery: DataTableNode | undefined
+ rowsUrl: string | undefined
+ close: () => void
+}): JSX.Element {
+ const recordingQuery = actors?.query
+ const { selectedResult: resolvedResult, resultLoading } = useValues(
+ dashboardInsightResultMenuLogic({
+ key: logicKey,
+ query: rowsQuery && isActorsQuery(rowsQuery.source) ? rowsQuery.source : null,
+ })
+ )
+ const sqlUrl = resolvedResult?.sql
+ ? urls.sqlEditor({ query: resolvedResult.sql })
+ : sqlQuery
+ ? urls.sqlEditor({ query: sqlQuery })
+ : undefined
+ const resultUnavailableReason = resultLoading
+ ? 'Loading the selected result…'
+ : 'Could not load the selected result. Right-click the data point again to retry.'
+
+ return (
+ <ResultMenu
+ triggerRef={triggerRef}
+ selectedResult={selectedResult}
+ caption={caption}
+ interaction={position}
+ close={close}
+ actions={[
+ {
+ name: sqlQuery ? 'View underlying rows' : 'View people',
+ className: 'ResultMenu__rows',
+ to: rowsUrl,
+ inPlace: !!actors,
+ disabledReason:
+ !actors && !sqlQuery
+ ? 'Right-click a data point to view the users or groups behind it.'
+ : undefined,
+ onClick: () => {
+ const request = actors
+ close()
+ if (request) {
+ request.open ? request.open() : openPersonsModal(request)
+ }
+ },
+ },
+ ...(canViewRecordings && recordingQuery
+ ? [
+ {
+ name: 'View recordings',
+ className: 'ResultMenu__recordings',
+ to: resolvedResult?.sessionIds.length
+ ? urls.replay(
+ ReplayTabs.Home,
+ getPersonsRecordingFilters(
+ { kind: NodeKind.ActorsQuery, source: recordingQuery },
+ resolvedResult.sessionIds
+ )
+ )
+ : undefined,
+ disabledReason: resolvedResult?.sessionIds.length
+ ? undefined
+ : resolvedResult
+ ? 'No recordings found for this result.'
+ : resultUnavailableReason,
+ onClick: close,
+ },
+ ]
+ : []),
+ {
+ name: 'Open in SQL editor',
+ className: 'ResultMenu__sql',
+ to: sqlUrl,
+ disabledReason: sqlUrl
+ ? undefined
+ : actors
+ ? resultUnavailableReason
+ : 'Right-click a data point to edit its underlying query.',
+ onClick: close,
+ },
+ ]}
+ />
+ )
+}