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): gate chart gallery on experiment, speed up its previews (#107502)

Sam Penningtona27ab2356434
diff --git a/frontend/src/scenes/insights/insightSceneLogic.test.ts b/frontend/src/scenes/insights/insightSceneLogic.test.ts
index 49d3b19f3a37..c7d784515e5e 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.test.ts
+++ b/frontend/src/scenes/insights/insightSceneLogic.test.ts
@@ -2,10 +2,13 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'
import { combineUrl, router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { addProjectIdIfMissing } from 'lib/utils/kea-router'
import { parseURLFilters, parseURLVariables } from 'scenes/dashboard/dashboardUtils'
+import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'
+import { insightUsageLogic } from 'scenes/insights/insightUsageLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -13,6 +16,8 @@ import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { cohortsModel } from '~/models/cohortsModel'
import { examples } from '~/queries/examples'
+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'
import { DashboardFilter, HogQLVariable, InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'
import { setLatestVersionsOnQuery } from '~/queries/utils'
import { initKeaTests } from '~/test/init'
@@ -78,6 +83,26 @@ describe('insightSceneLogic', () => {
expect(logic.values.breadcrumbs.at(-1)?.name).not.toContain('ID 987')
})
+ it('reports a view only for the scene insight when another unsaved insight mounts', async () => {
+ const capture = jest.spyOn(posthog, 'capture')
+ router.actions.push(urls.insightNew())
+ logic = insightSceneLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ const query: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery, series: [{ kind: NodeKind.EventsNode, event: '$pageview' }] },
+ }
+ const previewProps = { dashboardItemId: 'new-AdHoc.preview' as InsightShortId, query, doNotLoad: true }
+ dataNodeLogic({ key: insightVizDataNodeKey(previewProps), query: query.source, doNotLoad: true }).mount()
+ insightDataLogic(previewProps).mount()
+ await expectLogic(insightUsageLogic(previewProps)).toFinishAllListeners()
+ await expectLogic(insightUsageLogic(logic.values.insightLogicRef!.logic.props)).toFinishAllListeners()
+
+ expect(capture.mock.calls.filter(([event]) => event === 'insight viewed')).toHaveLength(1)
+ })
+
it('disables discussions for an unsaved insight so comments do not leak across the team', async () => {
// A new insight has no numeric id yet. The side panel context must still declare the Insight
// scope (so sidePanelContextLogic does not fall back to the URL guesser and drop item_id, which
diff --git a/frontend/src/scenes/insights/insightUsageLogic.ts b/frontend/src/scenes/insights/insightUsageLogic.ts
index a4901c674db2..b08f38253526 100644
--- a/frontend/src/scenes/insights/insightUsageLogic.ts
+++ b/frontend/src/scenes/insights/insightUsageLogic.ts
@@ -95,13 +95,14 @@ export const insightUsageLogic = kea<insightUsageLogicType>([
},
],
}),
- listeners(({ actions, values }) => ({
+ listeners(({ actions, props, values }) => ({
onQueryChange: async ({ query }, breakpoint) => {
// We only want to report direct views on the insights page.
const logic = insightSceneLogic.findMounted()
- const shortId = logic?.values.insight?.short_id
+ // Unsaved insights share an empty short_id, so it can't tell the scene's insight from a preview.
+ const sceneDashboardItemId = logic?.values.insightLogicRef?.logic.props.dashboardItemId
- if (!logic || shortId !== values.insight?.short_id) {
+ if (!logic || sceneDashboardItemId !== props.dashboardItemId) {
return
}
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/ChartGallery.tsx b/products/product_analytics/frontend/insights/chartAlternatives/ChartGallery.tsx
index 4c70143b1ae4..895b1d49ea3b 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/ChartGallery.tsx
+++ b/products/product_analytics/frontend/insights/chartAlternatives/ChartGallery.tsx
@@ -25,14 +25,15 @@ export function ChartGallery({
const alternativesLogic = useMountedLogic(chartAlternativesLogic(logicProps))
const { selectionDisabledReason } = useValues(alternativesLogic)
const { selectChart } = useActions(alternativesLogic)
- const { previews } = useValues(chartPreviewsLogic(logicProps))
+ const { chartsShown, previews } = useValues(chartPreviewsLogic(logicProps))
const suggested = previews.filter((preview) => preview.suggested)
const remaining = previews.filter((preview) => !preview.suggested)
- const renderTile = (preview: ChartPreview): JSX.Element => (
+ const renderTile = (preview: ChartPreview, index: number): JSX.Element => (
<ChartPreviewTile
key={preview.option.display}
preview={preview}
+ showChart={index < chartsShown}
disabledReason={selectionDisabledReason}
onSelect={() => selectChart(preview.option.display, preview.suggested ? 'recommended' : 'gallery')}
/>
@@ -41,8 +42,12 @@ export function ChartGallery({
return (
<div className={clsx('@container overflow-y-auto p-2', className)} data-attr="chart-alternatives-gallery">
<div className="flex flex-col gap-3">
- {suggested.length > 0 && <div className={GRID}>{suggested.map(renderTile)}</div>}
- <div className={GRID}>{remaining.map(renderTile)}</div>
+ {suggested.length > 0 && (
+ <div className={GRID}>{suggested.map((preview, index) => renderTile(preview, index))}</div>
+ )}
+ <div className={GRID}>
+ {remaining.map((preview, index) => renderTile(preview, suggested.length + index))}
+ </div>
</div>
</div>
)
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/ChartPreviewTile.tsx b/products/product_analytics/frontend/insights/chartAlternatives/ChartPreviewTile.tsx
index 8fedce6fc568..7de57276616c 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/ChartPreviewTile.tsx
+++ b/products/product_analytics/frontend/insights/chartAlternatives/ChartPreviewTile.tsx
@@ -14,17 +14,20 @@ export function ChartPreviewTile({
disabledReason,
onSelect,
preview,
+ showChart,
}: {
disabledReason?: string
onSelect: () => void
preview: ChartPreview
+ showChart: boolean
}): JSX.Element {
const { option, query, response, sample, uniqueKey } = preview
const reason = disabledReason ?? option.disabledReason
const disabled = !!reason
+ const chartShown = !!response && showChart
let body: JSX.Element
- if (response) {
+ if (response && chartShown) {
body = <ChartPreviewCanvas uniqueKey={uniqueKey} query={query} response={response} />
} else {
body = (
@@ -32,7 +35,7 @@ export function ChartPreviewTile({
<span className="text-4xl opacity-40">
<ChartDisplayIcon icon={option.icon} />
</span>
- {reason ? <span className="text-xs">{reason}</span> : null}
+ {reason && !response ? <span className="text-xs">{reason}</span> : null}
</div>
)
}
@@ -60,15 +63,15 @@ export function ChartPreviewTile({
<span
className={clsx(
'flex h-full flex-col [&_.text-7xl]:text-lg [&_.text-7xl]:leading-tight',
- response && option.display === ChartDisplayType.BoldNumber && '[&_.BoldNumber]:p-4',
- response &&
+ chartShown && option.display === ChartDisplayType.BoldNumber && '[&_.BoldNumber]:p-4',
+ chartShown &&
option.display === ChartDisplayType.CalendarHeatmap &&
'[zoom:0.3] [&_.CalendarHeatMapContainer+div]:hidden',
// MetricCard hardcodes its headline at text-4xl, which truncates at tile width.
- response &&
+ chartShown &&
option.display === ChartDisplayType.Metric &&
'[&_.text-4xl]:text-lg [&_.text-4xl]:leading-tight',
- response &&
+ chartShown &&
option.display === ChartDisplayType.ActionsTable &&
'[zoom:0.6] [&_.ScrollableShadows::before]:shadow-none! [&_.ScrollableShadows::after]:shadow-none! [&_.LemonTable__cell--sticky::before]:shadow-none! [&_.LemonTable__header--sticky::before]:shadow-none!'
)}
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.test.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.test.ts
index f6b49067e349..40ab89800efe 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.test.ts
+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.test.ts
@@ -3,7 +3,7 @@ import { NodeKind } from '~/queries/schema/schema-general'
import { ChartDisplayType, CompareLabelType } from '~/types'
import type { TrendResult } from '~/types'
-import { deriveChartPreview } from './chartPreviewData'
+import { PREVIEW_SERIES_LIMIT, deriveChartPreview } from './chartPreviewData'
import type { ChartPreviewData } from './chartPreviewData'
function series(overrides: Partial<TrendResult> & { math?: string }): TrendResult {
@@ -104,6 +104,60 @@ describe('deriveChartPreview', () => {
])
})
+ it.each([
+ ['caps', ChartDisplayType.ActionsLineGraph, PREVIEW_SERIES_LIMIT],
+ ['caps', ChartDisplayType.ActionsTable, PREVIEW_SERIES_LIMIT],
+ ['keeps every slice of', ChartDisplayType.ActionsPie, PREVIEW_SERIES_LIMIT + 5],
+ ])('%s the series of a large breakdown for %s', (_, display, expected) => {
+ const source = query(ChartDisplayType.ActionsLineGraph, {
+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },
+ })
+ const rows = Array.from({ length: PREVIEW_SERIES_LIMIT + 5 }, (_, index) =>
+ series({ breakdown_value: `browser ${index}` })
+ )
+
+ const shown = results(deriveChartPreview(display, source, response(rows)))
+ expect(shown.map((row) => row.breakdown_value)).toEqual(
+ rows.slice(0, expected).map((row) => row.breakdown_value)
+ )
+ })
+
+ it('keeps the previous-period row of every series a comparison preview shows', () => {
+ const source = query(ChartDisplayType.ActionsLineGraph, {
+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },
+ compareFilter: { compare: true },
+ })
+ const browsers = Array.from({ length: PREVIEW_SERIES_LIMIT + 5 }, (_, index) => `browser ${index}`)
+ const rows = [
+ ...browsers.map((browser) => series({ breakdown_value: browser, compare_label: CompareLabelType.Current })),
+ ...browsers.map((browser) =>
+ series({ breakdown_value: browser, compare_label: CompareLabelType.Previous })
+ ),
+ ]
+
+ const shown = results(deriveChartPreview(ChartDisplayType.ActionsLineGraph, source, response(rows)))
+ expect(shown.filter((row) => row.compare_label === CompareLabelType.Previous)).toHaveLength(
+ PREVIEW_SERIES_LIMIT
+ )
+ expect(new Set(shown.map((row) => row.breakdown_value))).toEqual(
+ new Set(browsers.slice(0, PREVIEW_SERIES_LIMIT))
+ )
+ })
+
+ it('caps formulas that share breakdown values as separate series', () => {
+ const source = query(ChartDisplayType.ActionsLineGraph, {
+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },
+ })
+ const browsers = Array.from({ length: PREVIEW_SERIES_LIMIT - 2 }, (_, index) => `browser ${index}`)
+ const rows = [0, 1].flatMap((order) =>
+ browsers.map((browser) => series({ action: null, order, breakdown_value: browser } as Partial<TrendResult>))
+ )
+
+ expect(results(deriveChartPreview(ChartDisplayType.ActionsLineGraph, source, response(rows)))).toHaveLength(
+ PREVIEW_SERIES_LIMIT
+ )
+ })
+
it.each([ChartDisplayType.WorldMap, ChartDisplayType.CalendarHeatmap, ChartDisplayType.BoxPlot])(
'shows sample data for %s instead of querying',
(display) => {
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts
index 18831be8967e..c572122fc02c 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts
+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewData.ts
@@ -22,6 +22,19 @@ export const RAW_TIME_SERIES_DISPLAYS = new Set<ChartDisplayType>([
ChartDisplayType.Metric,
])
+// A tile is too small to tell more series apart, and each extra series adds render time to every tile.
+export const PREVIEW_SERIES_LIMIT = 10
+
+// Pie and donut tiles show the total of every slice, and a map needs every country, so they keep all rows.
+const SERIES_CAPPED_DISPLAYS = new Set<ChartDisplayType>([
+ ...RAW_TIME_SERIES_DISPLAYS,
+ ChartDisplayType.ActionsLineGraphCumulative,
+ ChartDisplayType.SlopeGraph,
+ ChartDisplayType.ActionsBarValue,
+ ChartDisplayType.ActionsTable,
+ ChartDisplayType.BoxPlot,
+])
+
interface PreviewRows {
response: AnyResponseType
results: TrendResult[]
@@ -186,14 +199,32 @@ function candidateRows(
return candidates
}
-// Builds the result a chart type would render, without a query: from the insight's loaded result, or from
-// a raw time series for the same query when the loaded result is a total value. Returns null when neither
-// can produce the display.
-export function deriveChartPreview(
+function seriesKey(result: TrendResult): string {
+ return JSON.stringify([result.order ?? result.action?.order, result.breakdown_value])
+}
+
+// Keeps whole series, so a comparison keeps the previous-period row of each series it shows.
+function capSeries(display: ChartDisplayType, preview: ChartPreviewData): ChartPreviewData {
+ const results = resultsOf(preview.response)
+ const series = results.filter((result) => result.compare_label !== 'previous')
+ if (!SERIES_CAPPED_DISPLAYS.has(display) || series.length <= PREVIEW_SERIES_LIMIT) {
+ return preview
+ }
+ const kept = new Set(series.slice(0, PREVIEW_SERIES_LIMIT).map(seriesKey))
+ return {
+ ...preview,
+ response: withResults(
+ preview.response,
+ results.filter((result) => kept.has(seriesKey(result)))
+ ),
+ }
+}
+
+function deriveUncappedPreview(
display: ChartDisplayType,
source: TrendsQuery,
loadedResponse: AnyResponseType,
- timeSeriesResponse: AnyResponseType | null = null
+ timeSeriesResponse: AnyResponseType | null
): ChartPreviewData | null {
const keepComparison =
(display !== ChartDisplayType.SlopeGraph && !!source.compareFilter?.compare) ||
@@ -224,3 +255,16 @@ export function deriveChartPreview(
? { response: withResults(loaded.response, recipe.sampleRows(loaded.results)), sample: true }
: null
}
+
+// Builds the result a chart type would render, without a query: from the insight's loaded result, or from
+// a raw time series for the same query when the loaded result is a total value. Returns null when neither
+// can produce the display.
+export function deriveChartPreview(
+ display: ChartDisplayType,
+ source: TrendsQuery,
+ loadedResponse: AnyResponseType,
+ timeSeriesResponse: AnyResponseType | null = null
+): ChartPreviewData | null {
+ const preview = deriveUncappedPreview(display, source, loadedResponse, timeSeriesResponse)
+ return preview && capSeries(display, preview)
+}
diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.ts
index da966f66835b..790c24846ca3 100644
--- a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.ts
+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.ts
@@ -56,6 +56,7 @@ export interface chartPreviewsLogicValues {
trendsSource: TrendsQuery | null // chartAlternativesLogic
insightData: Record<string, any> // insightVizDataLogic
insightDataLoading: boolean // insightVizDataLogic
+ chartsShown: number
freeResponse: AnyResponseType | null
loadedTimeSeries: TimeSeriesEntry | null
previews: ChartPreview[]
@@ -66,6 +67,12 @@ export interface chartPreviewsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface chartPreviewsLogicActions {
+ closeGallery: () => {
+ value: true
+ } // chartAlternativesLogic
+ openGallery: () => {
+ value: true
+ } // chartAlternativesLogic
toggleGallery: () => {
value: true
} // chartAlternativesLogic
@@ -158,6 +165,9 @@ export interface chartPreviewsLogicActions {
rememberTimeSeries: (entry: TimeSeriesEntry) => {
entry: TimeSeriesEntry
}
+ showNextChart: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -207,13 +217,14 @@ export const chartPreviewsLogic = kea<chartPreviewsLogicType>([
],
actions: [
chartAlternativesLogic(props),
- ['toggleGallery'],
+ ['closeGallery', 'openGallery', 'toggleGallery'],
insightVizDataLogic(props),
['loadDataSuccess', 'setInsightData'],
],
})),
actions({
rememberTimeSeries: (entry: TimeSeriesEntry) => ({ entry }),
+ showNextChart: true,
}),
reducers({
rememberedTimeSeries: [
@@ -222,6 +233,16 @@ export const chartPreviewsLogic = kea<chartPreviewsLogicType>([
rememberTimeSeries: (_, { entry }) => entry,
},
],
+ // Each tile mounts a full chart, so the gallery mounts them one per frame to keep slower devices responsive.
+ chartsShown: [
+ 0,
+ {
+ showNextChart: (count) => count + 1,
+ openGallery: () => 0,
+ closeGallery: () => 0,
+ toggleGallery: () => 0,
+ },
+ ],
}),
selectors({
freeResponse: [
@@ -303,14 +324,36 @@ export const chartPreviewsLogic = kea<chartPreviewsLogicType>([
},
],
}),
- listeners(({ actions, values }) => {
+ listeners(({ actions, cache, values }) => {
+ const scheduleNextChart = (): void => {
+ if (!values.galleryOpen || values.chartsShown >= values.previews.length) {
+ cache.disposables.dispose('nextChart')
+ return
+ }
+ cache.disposables.add(() => {
+ let timeout: ReturnType<typeof setTimeout> | undefined
+ // A timeout after the frame lets the browser paint the previous tile before the next one mounts.
+ const frame = requestAnimationFrame(() => {
+ timeout = setTimeout(() => actions.showNextChart())
+ })
+ return () => {
+ cancelAnimationFrame(frame)
+ clearTimeout(timeout)
+ }
+ }, 'nextChart')
+ }
const rememberLoadedTimeSeries = (): void => {
if (values.loadedTimeSeries) {
actions.rememberTimeSeries(values.loadedTimeSeries)
}
+ scheduleNextChart()
}
return {
+ showNextChart: scheduleNextChart,
+ openGallery: scheduleNextChart,
+ closeGallery: scheduleNextChart,
toggleGallery: () => {
+ scheduleNextChart()
if (!values.galleryOpen || values.insightDataLoading) {
return
}