: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(insights): add a chart gallery with live previews (#99929)
Sam Pennington584fae4f25a8
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 69b01447f95c..8df77a63c757 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -442,6 +442,7 @@ export const FEATURE_FLAGS = {POSTHOG_CODE_BILLING: 'posthog-code-billing', // owner: #team-desktopPOSTHOG_CONNECT: 'posthog-connect', // owner: @Gilbert09, gates the "connect another PostHog project" personal integrationPOSTHOG_DESKTOP_CLOUD_COMPUTE_BILLING: 'posthog-desktop-cloud-compute-billing', // owner: #team-desktop+ PRODUCT_ANALYTICS_CHART_ALTERNATIVES: 'product-analytics-chart-alternatives', // owner: #team-product-analyticsPRODUCT_ANALYTICS_DASHBOARD_COLORS: 'dashboard-colors', // owner: @thmsobrmlr #team-product-analyticsPRODUCT_ANALYTICS_DASHBOARD_MODAL_SMART_DEFAULTS: 'product-analytics-dashboard-modal-smart-defaults', // owner: @sam #team-product-analyticsPRODUCT_ANALYTICS_INSIGHT_HORIZONTAL_CONTROLS: 'insight-horizontal-controls', // owner: #team-product-analyticsdiff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsxindex ffc65ad591c2..405ad90c5530 100644--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx@@ -28,7 +28,7 @@ import { RetentionDatePicker } from 'products/product_analytics/frontend/insightimport { useInsightDisplayOptions } from './insightDisplayOptions'import { InsightDisplayOptionsPanel } from './InsightDisplayOptionsPanel'-export function InsightDisplayConfig(): JSX.Element {+export function InsightDisplayConfig({ chartTypeControl }: { chartTypeControl?: ReactNode }): JSX.Element {const { insightProps, canEditInsight, editingDisabledReason } = useValues(insightLogic)const {@@ -156,11 +156,7 @@ export function InsightDisplayConfig(): JSX.Element {</LemonDropdown></>)}- {supportsDisplay && (- <ConfigFilter>- <ChartFilter />- </ConfigFilter>- )}+ {supportsDisplay && <ConfigFilter>{chartTypeControl ?? <ChartFilter />}</ConfigFilter>}{!!isRetention && (<ConfigFilter><RetentionChartPicker />diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsxindex fdd2882d12a3..39e992af9586 100644--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx@@ -45,6 +45,7 @@ import {PropertyMathType,} from '~/types'+import { ChartAlternatives } from 'products/product_analytics/frontend/insights/chartAlternatives/ChartAlternatives'import { Funnel } from 'products/product_analytics/frontend/insights/funnels/Funnel'import { FunnelCanvasLabel } from 'products/product_analytics/frontend/insights/funnels/FunnelCanvasLabel'import { FunnelCorrelation } from 'products/product_analytics/frontend/insights/funnels/FunnelCorrelation/FunnelCorrelation'@@ -554,7 +555,18 @@ export function InsightVizDisplay({)}data-attr={INSIGHT_GRAPH_DATA_ATTR}>- {disableHeader ? null : <InsightDisplayConfig />}+ {disableHeader ? null : (+ <InsightDisplayConfig+ chartTypeControl={+ <ChartAlternatives+ insightProps={insightProps}+ editMode={editMode}+ embedded={embedded}+ inSharedMode={inSharedMode}+ />+ }+ />+ )}{showingResults && (<>{!embedded &&diff --git a/products/product_analytics/frontend/insights/chartAlternatives/ChartAlternatives.test.tsx b/products/product_analytics/frontend/insights/chartAlternatives/ChartAlternatives.test.tsxnew file mode 100644index 000000000000..bf94e9c5c062--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/ChartAlternatives.test.tsx@@ -0,0 +1,143 @@+import '@testing-library/jest-dom'++import { cleanup, render, waitFor } from '@testing-library/react'+import { BindLogic, Provider } from 'kea'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { insightLogic } from 'scenes/insights/insightLogic'+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'++import { useMocks } from '~/mocks/jest'+import { NodeKind } from '~/queries/schema/schema-general'+import type { InsightVizNode, TrendsQuery } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { BaseMathType, ChartDisplayType, InsightShortId } from '~/types'++import { ChartAlternatives } from './ChartAlternatives'+import { chartAlternativesLogic } from './chartAlternativesLogic'+import { chartPreviewsLogic } from './chartPreviewsLogic'++const insightProps = { dashboardItemId: 'chart-alternatives' as InsightShortId }++function makeTrendsQuery(overrides: Partial<TrendsQuery> = {}): TrendsQuery {+ return {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ name: '$pageview',+ event: '$pageview',+ math: BaseMathType.TotalCount,+ math_property: 'duration',+ },+ ],+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph },+ ...overrides,+ }+}++describe('ChartAlternatives', () => {+ let builtInsightDataLogic: ReturnType<typeof insightDataLogic.build>+ let builtInsightVizDataLogic: ReturnType<typeof insightVizDataLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/insights/trend': [],+ '/api/environments/:team_id/insights/': { results: [{}] },+ },+ post: {+ '/api/projects/:team_id/query/:kind/': () => new Promise(() => {}),+ },+ })+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.PRODUCT_ANALYTICS_CHART_ALTERNATIVES], {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_CHART_ALTERNATIVES]: true,+ })++ insightLogic(insightProps).mount()+ builtInsightDataLogic = insightDataLogic(insightProps)+ builtInsightVizDataLogic = insightVizDataLogic(insightProps)+ builtInsightDataLogic.mount()+ builtInsightVizDataLogic.mount()+ })++ afterEach(() => {+ cleanup()+ chartAlternativesLogic.findMounted({ editMode: true, embedded: false, ...insightProps })?.unmount()+ })++ function setQuery(query: TrendsQuery): void {+ builtInsightVizDataLogic.actions.updateQuerySource(query)+ }++ function alternativesLogic(): ReturnType<typeof chartAlternativesLogic.build> {+ render(+ <Provider>+ <BindLogic logic={insightLogic} props={insightProps}>+ <ChartAlternatives insightProps={insightProps} editMode embedded={false} />+ </BindLogic>+ </Provider>+ )+ return chartAlternativesLogic.findMounted({ editMode: true, embedded: false, ...insightProps })!+ }++ function currentTrendsQuery(): TrendsQuery {+ return (builtInsightDataLogic.values.query as InsightVizNode).source as TrendsQuery+ }++ it('applies the display rewrite when a chart is selected and closes the gallery', () => {+ setQuery(+ makeTrendsQuery({+ breakdownFilter: { breakdown: 'browser', breakdown_type: 'event' },+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph, formula: 'A / B' },+ })+ )+ const logic = alternativesLogic()+ logic.actions.openGallery()+ expect(logic.values.galleryOpen).toBe(true)++ logic.actions.selectChart(ChartDisplayType.BoxPlot, 'gallery')++ expect(currentTrendsQuery().trendsFilter).toMatchObject({+ display: ChartDisplayType.BoxPlot,+ formula: undefined,+ formulaNodes: [],+ })+ expect(currentTrendsQuery().breakdownFilter).toBeUndefined()+ expect(logic.values.galleryOpen).toBe(false)+ })++ it('mounts preview state with the chart control', () => {+ setQuery(makeTrendsQuery())+ alternativesLogic()++ expect(chartPreviewsLogic.findMounted({ editMode: true, embedded: false, ...insightProps })).not.toBeUndefined()+ })++ it('opens the gallery in a popover anchored to the chart type button', async () => {+ setQuery(makeTrendsQuery())+ const logic = alternativesLogic()+ expect(document.querySelector('[data-attr="chart-alternatives-gallery"]')).not.toBeInTheDocument()++ logic.actions.openGallery()++ await waitFor(() =>+ expect(document.querySelector('.Popover [data-attr="chart-alternatives-gallery"]')).toBeInTheDocument()+ )+ })++ it('renders the chart switch control only while the flag is on', async () => {+ setQuery(makeTrendsQuery())+ alternativesLogic()+ await waitFor(() => expect(document.querySelector('[data-attr="chart-alternatives-all"]')).toBeInTheDocument())++ featureFlagLogic.actions.setFeatureFlags([], {})+ await waitFor(() =>+ expect(document.querySelector('[data-attr="chart-alternatives-all"]')).not.toBeInTheDocument()+ )+ })+})diff --git a/products/product_analytics/frontend/insights/chartAlternatives/ChartAlternatives.tsx b/products/product_analytics/frontend/insights/chartAlternatives/ChartAlternatives.tsxnew file mode 100644index 000000000000..9a6e45565788--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/ChartAlternatives.tsx@@ -0,0 +1,75 @@+import { useActions, useMountedLogic, useValues } from 'kea'+import { useRef } from 'react'++import { LemonButton, Popover } from '@posthog/lemon-ui'++import { ChartFilter } from 'lib/components/ChartFilter'++import type { InsightLogicProps } from '~/types'++import { chartAlternativesLogic } from './chartAlternativesLogic'+import { ChartDisplayIcon } from './ChartDisplayIcon'+import { ChartGallery } from './ChartGallery'+import { chartPreviewsLogic } from './chartPreviewsLogic'++// Leaves the gallery 33rem of content box, just over the @lg breakpoint that puts three tiles in a row.+const GALLERY_WIDTH = 'w-[34rem] max-w-[calc(100vw-2rem)]'++export function ChartAlternatives({+ editMode,+ embedded,+ inSharedMode,+ insightProps,+}: {+ editMode?: boolean+ embedded: boolean+ inSharedMode?: boolean+ insightProps: InsightLogicProps+}): JSX.Element {+ const logicProps = { editMode, embedded, inSharedMode, ...insightProps }+ const logic = useMountedLogic(chartAlternativesLogic(logicProps))+ useMountedLogic(chartPreviewsLogic(logicProps))+ const { canShowAlternatives, currentOption, galleryOpen, selectionDisabledReason } = useValues(logic)+ const { closeGallery, toggleGallery } = useActions(logic)+ const triggerRef = useRef<HTMLButtonElement>(null)++ if (!canShowAlternatives) {+ return <ChartFilter />+ }++ return (+ <Popover+ visible={galleryOpen}+ onClickOutside={(event) => {+ // A press on the trigger counts as outside, and would close then reopen on the click.+ if (!(event.target instanceof Node && triggerRef.current?.contains(event.target))) {+ closeGallery()+ }+ }}+ placement="bottom-end"+ padded={false}+ overlay={+ <ChartGallery+ className={GALLERY_WIDTH}+ insightProps={insightProps}+ editMode={editMode}+ embedded={embedded}+ inSharedMode={inSharedMode}+ />+ }+ >+ <LemonButton+ ref={triggerRef}+ size="small"+ type="secondary"+ active={galleryOpen}+ icon={currentOption ? <ChartDisplayIcon icon={currentOption.icon} /> : undefined}+ data-attr="chart-alternatives-all"+ disabledReason={selectionDisabledReason}+ onClick={toggleGallery}+ >+ {currentOption?.label ?? 'Chart type'}+ </LemonButton>+ </Popover>+ )+}diff --git a/products/product_analytics/frontend/insights/chartAlternatives/ChartGallery.tsx b/products/product_analytics/frontend/insights/chartAlternatives/ChartGallery.tsxnew file mode 100644index 000000000000..40c8c69d6ba2--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/ChartGallery.tsx@@ -0,0 +1,51 @@+import clsx from 'clsx'+import { useActions, useMountedLogic, useValues } from 'kea'++import type { InsightLogicProps } from '~/types'++import { chartAlternativesLogic } from './chartAlternativesLogic'+import type { ChartPreview } from './chartPreviewsLogic'+import { chartPreviewsLogic } from './chartPreviewsLogic'+import { ChartPreviewTile } from './ChartPreviewTile'++const GRID = 'grid grid-cols-1 gap-2 @sm:grid-cols-2 @lg:grid-cols-3'++export function ChartGallery({+ className,+ editMode,+ embedded,+ inSharedMode,+ insightProps,+}: {+ className?: string+ editMode?: boolean+ embedded: boolean+ inSharedMode?: boolean+ insightProps: InsightLogicProps+}): JSX.Element {+ const logicProps = { editMode, embedded, inSharedMode, ...insightProps }+ const alternativesLogic = useMountedLogic(chartAlternativesLogic(logicProps))+ const { selectionDisabledReason } = useValues(alternativesLogic)+ const { selectChart } = useActions(alternativesLogic)+ const { previews } = useValues(chartPreviewsLogic(logicProps))+ const suggested = previews.filter((preview) => preview.suggested)+ const remaining = previews.filter((preview) => !preview.suggested)++ const renderTile = (preview: ChartPreview): JSX.Element => (+ <ChartPreviewTile+ key={preview.option.display}+ preview={preview}+ disabledReason={selectionDisabledReason}+ onSelect={() => selectChart(preview.option.display, preview.suggested ? 'recommended' : 'gallery')}+ />+ )++ 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>+ </div>+ </div>+ )+}diff --git a/products/product_analytics/frontend/insights/chartAlternatives/ChartPreviewCanvas.tsx b/products/product_analytics/frontend/insights/chartAlternatives/ChartPreviewCanvas.tsxnew file mode 100644index 000000000000..3ceb4e30c942--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/ChartPreviewCanvas.tsx@@ -0,0 +1,74 @@+import { BindLogic, useMountedLogic } from 'kea'+import { useMemo } from 'react'++import 'lib/components/Cards/InsightCard/InsightCard.scss'+import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { insightLogic } from 'scenes/insights/insightLogic'+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'++import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { insightVizDataCollectionId, insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'+import type { AnyResponseType, InsightVizNode } from '~/queries/schema/schema-general'+import type { QueryContext } from '~/queries/types'+import { InsightLogicProps, InsightType } from '~/types'++import { TrendInsight } from 'products/product_analytics/frontend/insights/trends/Trends'++const PREVIEW_CONTEXT: QueryContext<InsightVizNode> = { hideAxes: true }++// A chart-only render of a query with a known result: the same logics the insight editor mounts, minus the+// display chrome, and with loading disabled so a tile never issues a request of its own.+export function ChartPreviewCanvas({+ embedded = true,+ query,+ response,+ uniqueKey,+}: {+ embedded?: boolean+ query: InsightVizNode+ response: AnyResponseType+ uniqueKey: string+}): JSX.Element {+ const insightProps = useMemo(+ (): InsightLogicProps<InsightVizNode> => ({+ // The `new-AdHoc.` prefix is what makes insightDataLogic take the query from props.+ dashboardItemId: `new-AdHoc.${uniqueKey}`,+ query,+ doNotLoad: true,+ dataNodeCollectionId: uniqueKey,+ }),+ [query, uniqueKey]+ )+ const dataNodeLogicProps = useMemo((): DataNodeLogicProps => {+ const vizKey = insightVizDataNodeKey(insightProps)+ return {+ query: query.source,+ key: vizKey,+ cachedResults: response,+ doNotLoad: true,+ dataNodeCollectionId: insightVizDataCollectionId(insightProps, vizKey),+ }+ }, [insightProps, query.source, response])++ useMountedLogic(dataNodeLogic(dataNodeLogicProps))+ useMountedLogic(insightLogic(insightProps as InsightLogicProps))+ useMountedLogic(insightDataLogic(insightProps as InsightLogicProps))+ useMountedLogic(insightVizDataLogic(insightProps as InsightLogicProps))++ return (+ <BindLogic logic={insightLogic} props={insightProps}>+ <BindLogic logic={insightDataLogic} props={insightProps}>+ <BindLogic logic={dataNodeLogic} props={dataNodeLogicProps}>+ <BindLogic logic={insightVizDataLogic} props={insightProps}>+ <TrendInsight+ view={InsightType.TRENDS}+ embedded={embedded}+ inSharedMode+ context={PREVIEW_CONTEXT}+ />+ </BindLogic>+ </BindLogic>+ </BindLogic>+ </BindLogic>+ )+}diff --git a/products/product_analytics/frontend/insights/chartAlternatives/ChartPreviewTile.tsx b/products/product_analytics/frontend/insights/chartAlternatives/ChartPreviewTile.tsxnew file mode 100644index 000000000000..5adcb74d9275--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/ChartPreviewTile.tsx@@ -0,0 +1,87 @@+import clsx from 'clsx'++import { IconInfo } from '@posthog/icons'++import { Tooltip } from 'lib/lemon-ui/Tooltip'++import { ChartDisplayType } from '~/types'++import { ChartDisplayIcon } from './ChartDisplayIcon'+import { ChartPreviewCanvas } from './ChartPreviewCanvas'+import type { ChartPreview } from './chartPreviewsLogic'++export function ChartPreviewTile({+ disabledReason,+ onSelect,+ preview,+}: {+ disabledReason?: string+ onSelect: () => void+ preview: ChartPreview+}): JSX.Element {+ const { option, query, response, sample, uniqueKey } = preview+ const reason = disabledReason ?? option.disabledReason+ const disabled = !!reason++ let body: JSX.Element+ if (response) {+ body = <ChartPreviewCanvas uniqueKey={uniqueKey} query={query} response={response} />+ } else {+ body = (+ <div className="flex flex-1 flex-col items-center justify-center gap-2 px-4 text-center text-secondary">+ <span className="text-4xl opacity-40">+ <ChartDisplayIcon icon={option.icon} />+ </span>+ {reason ? <span className="text-xs">{reason}</span> : null}+ </div>+ )+ }++ const tile = (+ <button+ type="button"+ className={clsx(+ 'flex w-full flex-col overflow-hidden rounded border bg-surface-primary text-left transition-colors',+ disabled ? 'cursor-default' : 'cursor-pointer hover:border-accent hover:bg-surface-secondary',+ reason && 'opacity-60'+ )}+ data-attr={`chart-preview-${option.display}`}+ disabled={disabled}+ onClick={onSelect}+ >+ <span className="flex items-center gap-1 border-b px-2 py-1 text-xs">+ <ChartDisplayIcon icon={option.icon} />+ <span className="truncate font-medium">{option.label}</span>+ <Tooltip title={option.description}>+ <IconInfo className="ml-auto shrink-0 text-base text-secondary" />+ </Tooltip>+ </span>+ <span className="pointer-events-none relative flex h-32 flex-col overflow-hidden" aria-hidden>+ <span+ className={clsx(+ 'flex h-full flex-col [&_.text-7xl]:text-lg [&_.text-7xl]:leading-tight',+ option.display === ChartDisplayType.CalendarHeatmap &&+ '[zoom:0.3] [&_.CalendarHeatMapContainer+div]:hidden',+ // MetricCard hardcodes its headline at text-4xl, which truncates at tile width.+ option.display === ChartDisplayType.Metric &&+ '[&_.text-4xl]:text-lg [&_.text-4xl]:leading-tight',+ 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!'+ )}+ >+ {body}+ </span>+ </span>+ {sample && !reason ? (+ <Tooltip title="Shows how this chart type looks. Select it to run the query on your data.">+ <span className="flex items-center gap-1 border-t px-2 py-1 text-xs text-secondary">+ Sample data+ <IconInfo className="ml-auto shrink-0 text-base" />+ </span>+ </Tooltip>+ ) : null}+ </button>+ )++ return reason ? <Tooltip title={reason}>{tile}</Tooltip> : tile+}diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartAlternativesLogic.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartAlternativesLogic.tsnew file mode 100644index 000000000000..1a5c64cab6e3--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartAlternativesLogic.ts@@ -0,0 +1,361 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { insightLogic } from 'scenes/insights/insightLogic'+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'+import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'+import { isBoxPlotMissingProperty } from 'scenes/insights/utils/queryUtils'++import type { FeatureFlagsSet } from '~/lib/logic/featureFlagLogic'+import type { Node, TrendsQuery } from '~/queries/schema/schema-general'+import { isTrendsQuery } from '~/queries/utils'+import type { InsightLogicProps } from '~/types'+import { ChartDisplayType } from '~/types'++import type {+ AnyDataWarehouseNode,+ AnyEntityNode,+ DataWarehouseNode,+ FunnelsQuery,+ GroupNode,+ LifecycleQuery,+ PathsQuery,+ PathsV2Query,+ RetentionQuery,+ StickinessQuery,+ WebOverviewQuery,+ WebStatsTableQuery,+} from '../../../../../frontend/src/queries/schema/schema-general'+import { applyChartDisplay, getChartDisplayOptions, hasTrendsFormula } from './chartDisplayOptions'+import type { ChartDisplayOption, ChartDisplayOptionGroup } from './chartDisplayOptions'+import { getChartAlternatives } from './chartRecommendations'++export type ChartAlternativeSource = 'gallery' | 'preview' | 'recommended'++export interface ChartAlternativesLogicProps extends InsightLogicProps {+ editMode?: boolean+ embedded: boolean+ inSharedMode?: boolean+}++const optionForDisplay = (+ options: ChartDisplayOptionGroup[],+ display: ChartDisplayType+): ChartDisplayOption | undefined =>+ options.flatMap((group) => group.options).find((option) => option.display === display)++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface chartAlternativesLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ canEditInsight: boolean // insightLogic+ editingDisabledReason: null // insightLogic+ isInDashboardContext: boolean // insightLogic+ display: ChartDisplayType | null | undefined // insightVizDataLogic+ insightDataLoading: boolean // insightVizDataLogic+ isSingleSeriesOutput: boolean // insightVizDataLogic+ isTrends: boolean // insightVizDataLogic+ query: Node | null // insightVizDataLogic+ querySource:+ | FunnelsQuery+ | LifecycleQuery+ | PathsQuery+ | PathsV2Query+ | RetentionQuery+ | StickinessQuery+ | TrendsQuery+ | WebOverviewQuery+ | WebStatsTableQuery+ | null // insightVizDataLogic+ series: (AnyEntityNode<AnyDataWarehouseNode> | GroupNode<DataWarehouseNode>)[] | null | undefined // insightVizDataLogic+ alternatives: ChartDisplayOption[]+ canSelectCharts: boolean+ canShowAlternatives: boolean+ currentDisplay: ChartDisplayType+ currentOption: ChartDisplayOption | undefined+ editMode: boolean | undefined+ embedded: boolean+ galleryOpen: boolean+ inSharedMode: boolean | undefined+ isEditableSurface: boolean+ options: ChartDisplayOptionGroup[]+ selectionDisabledReason: string | undefined+ trendsSource: TrendsQuery | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface chartAlternativesLogicActions {+ setQuery: (+ query: Node<Record<string, any>> | null,+ fromUrl?: boolean | undefined+ ) => {+ fromUrl: boolean+ query: Node<Record<string, any>> | null+ } // insightDataLogic+ updateQuerySource: (querySource: import('scenes/insights/insightVizDataLogic').QuerySourceUpdate) => {+ querySource: import('scenes/insights/insightVizDataLogic').QuerySourceUpdate+ } // insightVizDataLogic+ closeGallery: () => {+ value: true+ }+ openGallery: () => {+ value: true+ }+ selectChart: (+ display: ChartDisplayType,+ source: ChartAlternativeSource+ ) => {+ display: ChartDisplayType+ source: ChartAlternativeSource+ }+ toggleGallery: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface chartAlternativesLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ editMode: (arg: any) => boolean | undefined+ embedded: (arg: any) => boolean+ inSharedMode: (arg: any) => boolean | undefined+ currentDisplay: (display: ChartDisplayType | null | undefined) => ChartDisplayType+ trendsSource: (+ querySource:+ | FunnelsQuery+ | LifecycleQuery+ | PathsQuery+ | PathsV2Query+ | RetentionQuery+ | StickinessQuery+ | TrendsQuery+ | WebOverviewQuery+ | WebStatsTableQuery+ | null+ ) => TrendsQuery | null+ options: (+ isTrends: boolean,+ isSingleSeriesOutput: boolean,+ trendsSource: TrendsQuery | null,+ series: (AnyEntityNode<AnyDataWarehouseNode> | GroupNode<DataWarehouseNode>)[] | null | undefined,+ featureFlags: FeatureFlagsSet+ ) => ChartDisplayOptionGroup[]+ alternatives: (options: ChartDisplayOptionGroup[], trendsSource: TrendsQuery | null) => ChartDisplayOption[]+ currentOption: (+ options: ChartDisplayOptionGroup[],+ currentDisplay: ChartDisplayType+ ) => ChartDisplayOption | undefined+ isEditableSurface: (+ editMode: boolean | undefined,+ embedded: boolean,+ inSharedMode: boolean | undefined,+ isInDashboardContext: boolean,+ canEditInsight: boolean,+ editingDisabledReason: null+ ) => boolean+ canShowAlternatives: (+ featureFlags: FeatureFlagsSet,+ isEditableSurface: boolean,+ isTrends: boolean,+ query: Node<Record<string, any>> | null,+ trendsSource: TrendsQuery | null+ ) => boolean+ canSelectCharts: (canShowAlternatives: boolean, insightDataLoading: boolean) => boolean+ selectionDisabledReason: (+ canShowAlternatives: boolean,+ insightDataLoading: boolean,+ editingDisabledReason: null+ ) => string | undefined+ }+}++export type chartAlternativesLogicType = MakeLogicType<+ chartAlternativesLogicValues,+ chartAlternativesLogicActions,+ ChartAlternativesLogicProps,+ chartAlternativesLogicMeta+>++export const chartAlternativesLogic = kea<chartAlternativesLogicType>([+ props({} as ChartAlternativesLogicProps),+ key(keyForInsightLogicProps('new')),+ path((key) => ['products', 'product_analytics', 'insights', 'chartAlternatives', 'chartAlternativesLogic', key]),+ connect((props: ChartAlternativesLogicProps) => ({+ values: [+ featureFlagLogic,+ ['featureFlags'],+ insightLogic(props),+ ['canEditInsight', 'editingDisabledReason', 'isInDashboardContext'],+ insightVizDataLogic(props),+ ['display', 'insightDataLoading', 'isSingleSeriesOutput', 'isTrends', 'query', 'querySource', 'series'],+ ],+ actions: [insightDataLogic(props), ['setQuery'], insightVizDataLogic(props), ['updateQuerySource']],+ })),+ actions({+ openGallery: true,+ closeGallery: true,+ toggleGallery: true,+ selectChart: (display: ChartDisplayType, source: ChartAlternativeSource) => ({ display, source }),+ }),+ reducers({+ galleryOpen: [+ false,+ {+ openGallery: () => true,+ closeGallery: () => false,+ toggleGallery: (state) => !state,+ selectChart: () => false,+ },+ ],+ }),+ selectors({+ editMode: [() => [(_, props) => props.editMode], (editMode: boolean | undefined) => editMode],+ embedded: [() => [(_, props) => props.embedded], (embedded: boolean) => embedded],+ inSharedMode: [() => [(_, props) => props.inSharedMode], (inSharedMode: boolean | undefined) => inSharedMode],+ currentDisplay: [+ (s) => [s.display],+ (display: ChartDisplayType | null | undefined): ChartDisplayType =>+ display ?? ChartDisplayType.ActionsLineGraph,+ ],+ trendsSource: [+ (s) => [s.querySource],+ (+ querySource:+ | FunnelsQuery+ | LifecycleQuery+ | PathsQuery+ | PathsV2Query+ | RetentionQuery+ | StickinessQuery+ | TrendsQuery+ | WebOverviewQuery+ | WebStatsTableQuery+ | null+ ): TrendsQuery | null => (querySource && isTrendsQuery(querySource) ? querySource : null),+ ],+ options: [+ (s) => [s.isTrends, s.isSingleSeriesOutput, s.trendsSource, s.series, s.featureFlags],+ (+ isTrends: boolean,+ isSingleSeriesOutput: boolean,+ trendsSource: TrendsQuery | null,+ series: (AnyEntityNode<AnyDataWarehouseNode> | GroupNode<DataWarehouseNode>)[] | null | undefined,+ featureFlags: FeatureFlagsSet+ ): ChartDisplayOptionGroup[] =>+ getChartDisplayOptions({+ isTrends,+ hasSingleSeriesOutput: isSingleSeriesOutput,+ hasTrendsFormula: hasTrendsFormula(trendsSource?.trendsFilter),+ breakdown: trendsSource?.breakdownFilter?.breakdown,+ breakdowns: trendsSource?.breakdownFilter?.breakdowns,+ boxPlotMissingProperty: isBoxPlotMissingProperty(series as TrendsQuery['series']),+ hasMetricInsight: !!featureFlags[FEATURE_FLAGS.METRIC_INSIGHT],+ }),+ ],+ alternatives: [+ (s) => [s.options, s.trendsSource],+ (options: ChartDisplayOptionGroup[], trendsSource: TrendsQuery | null): ChartDisplayOption[] =>+ getChartAlternatives(options, trendsSource),+ ],+ currentOption: [+ (s) => [s.options, s.currentDisplay],+ (options: ChartDisplayOptionGroup[], currentDisplay: ChartDisplayType): ChartDisplayOption | undefined =>+ optionForDisplay(options, currentDisplay),+ ],+ isEditableSurface: [+ (s) => [+ s.editMode,+ s.embedded,+ s.inSharedMode,+ s.isInDashboardContext,+ s.canEditInsight,+ s.editingDisabledReason,+ ],+ (+ editMode: boolean | undefined,+ embedded: boolean,+ inSharedMode: boolean | undefined,+ isInDashboardContext: boolean,+ canEditInsight: boolean,+ editingDisabledReason: null+ ): boolean =>+ !!editMode &&+ !embedded &&+ !inSharedMode &&+ !isInDashboardContext &&+ canEditInsight &&+ !editingDisabledReason,+ ],+ canShowAlternatives: [+ (s) => [s.featureFlags, s.isEditableSurface, s.isTrends, s.query, s.trendsSource],+ (+ featureFlags: FeatureFlagsSet,+ isEditableSurface: boolean,+ isTrends: boolean,+ query: Node | null,+ trendsSource: TrendsQuery | null+ ): boolean =>+ !!featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_CHART_ALTERNATIVES] &&+ isEditableSurface &&+ isTrends &&+ !!query &&+ !!trendsSource,+ ],+ canSelectCharts: [+ (s) => [s.canShowAlternatives, s.insightDataLoading],+ (canShowAlternatives: boolean, insightDataLoading: boolean): boolean =>+ canShowAlternatives && !insightDataLoading,+ ],+ selectionDisabledReason: [+ (s) => [s.canShowAlternatives, s.insightDataLoading, s.editingDisabledReason],+ (+ canShowAlternatives: boolean,+ insightDataLoading: boolean,+ editingDisabledReason: null+ ): string | undefined => {+ if (editingDisabledReason) {+ return editingDisabledReason+ }+ if (insightDataLoading) {+ return 'Chart is loading.'+ }+ return canShowAlternatives ? undefined : 'Chart types are unavailable.'+ },+ ],+ }),+ listeners(({ actions, values }) => ({+ openGallery: () => {+ if (!values.canSelectCharts) {+ actions.closeGallery()+ }+ },+ selectChart: ({ display, source }) => {+ const option = optionForDisplay(values.options, display)+ if (+ !values.canSelectCharts ||+ !values.trendsSource ||+ !option ||+ option.disabledReason ||+ display === values.currentDisplay+ ) {+ return+ }+ const previousDisplay = values.currentDisplay+ const next = applyChartDisplay(values.trendsSource, display)+ actions.updateQuerySource({ trendsFilter: next.trendsFilter, breakdownFilter: next.breakdownFilter })+ posthog.capture('insight chart alternative selected', {+ previous_display: previousDisplay,+ display,+ source,+ })+ },+ setQuery: () => {+ if (values.galleryOpen) {+ actions.closeGallery()+ }+ },+ })),+])diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.tsindex 71870443d2fc..2ef73e1de449 100644--- a/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.ts+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartDisplayOptions.ts@@ -1,4 +1,6 @@-import type { BreakdownFilter, TrendsFilter } from '~/queries/schema/schema-general'+import { NON_BREAKDOWN_DISPLAY_TYPES } from 'lib/constants'++import type { BreakdownFilter, TrendsFilter, TrendsQuery } from '~/queries/schema/schema-general'import { ChartDisplayType } from '~/types'export type ChartDisplayIcon =@@ -41,7 +43,7 @@ export interface ChartDisplayOptionEligibility {const COUNTRY_PROPERTIES = new Set(['$geoip_country_code', '$geoip_country_name'])-function isCountryProperty(value: unknown): boolean {+export function isCountryProperty(value: unknown): boolean {return typeof value === 'string' && COUNTRY_PROPERTIES.has(value)}@@ -61,6 +63,28 @@ export function hasTrendsFormula(trendsFilter?: TrendsFilter | null): boolean {return !!trendsFilter?.formula || !!trendsFilter?.formulas?.length || !!trendsFilter?.formulaNodes?.length}+function worldMapBreakdownFilter(query: TrendsQuery): BreakdownFilter {+ const math = query.series?.[0]?.math ?? ''+ return {+ breakdown: '$geoip_country_code',+ breakdown_type: ['dau', 'weekly_active', 'monthly_active'].includes(math) ? 'person' : 'event',+ }+}++export function applyChartDisplay(query: TrendsQuery, display: ChartDisplayType): TrendsQuery {+ const next: TrendsQuery = { ...query, trendsFilter: { ...query.trendsFilter, display } }+ if (NON_BREAKDOWN_DISPLAY_TYPES.includes(display)) {+ next.breakdownFilter = undefined+ }+ if (display === ChartDisplayType.BoxPlot) {+ next.trendsFilter = { ...next.trendsFilter, formula: undefined, formulas: undefined, formulaNodes: [] }+ }+ if (display === ChartDisplayType.WorldMap) {+ next.breakdownFilter = worldMapBreakdownFilter(query)+ }+ return next+}+export function getChartDisplayOptions({boxPlotMissingProperty,hasMetricInsight,diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.test.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.test.tsnew file mode 100644index 000000000000..b60fea6be604--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.test.ts@@ -0,0 +1,116 @@+import { waitFor } from '@testing-library/react'+import { expectLogic } from 'kea-test-utils'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { insightLogic } from 'scenes/insights/insightLogic'+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'++import { useMocks } from '~/mocks/jest'+import { NodeKind } from '~/queries/schema/schema-general'+import type { TrendsQuery } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { BaseMathType, ChartDisplayType, InsightShortId } from '~/types'++import { chartAlternativesLogic } from './chartAlternativesLogic'+import { chartPreviewsLogic } from './chartPreviewsLogic'+import type { ChartPreview } from './chartPreviewsLogic'++const insightProps = { dashboardItemId: 'chart-previews' as InsightShortId }+const logicProps = { editMode: true, embedded: false, ...insightProps }+const FIRST_REFRESH = '2026-01-01T00:00:00.000Z'+const SECOND_REFRESH = '2026-01-01T00:01:00.000Z'++const timeSeriesRow = {+ action: { id: '$pageview', type: 'events', order: 0, math: 'total' },+ label: '$pageview',+ data: [1, 2, 3],+ days: ['2026-01-01', '2026-01-02', '2026-01-03'],+ labels: ['1-Jan', '2-Jan', '3-Jan'],+ count: 6,+}+const totalValueRow = { ...timeSeriesRow, data: [], count: 0, aggregated_value: 6 }++function trendsQuery(display: ChartDisplayType): TrendsQuery {+ return {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview', math: BaseMathType.TotalCount }],+ trendsFilter: { display },+ }+}++describe('chartPreviewsLogic', () => {+ let refreshModes: string[]++ beforeEach(() => {+ refreshModes = []+ const queryMock = async ({ request }: { request: Request }): Promise<Record<string, unknown>> => {+ const body = (await request.json()) as { refresh?: string }+ refreshModes.push(body.refresh ?? '')+ return { results: [timeSeriesRow], last_refresh: FIRST_REFRESH }+ }+ useMocks({+ get: { '/api/environments/:team_id/insights/': { results: [{}] } },+ post: {+ '/api/environments/:team_id/query/': queryMock,+ '/api/environments/:team_id/query/:kind/': queryMock,+ },+ })+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.PRODUCT_ANALYTICS_CHART_ALTERNATIVES], {+ [FEATURE_FLAGS.PRODUCT_ANALYTICS_CHART_ALTERNATIVES]: true,+ })+ insightLogic(insightProps).mount()+ insightDataLogic(insightProps).mount()+ insightVizDataLogic(insightProps).mount()+ chartAlternativesLogic(logicProps).mount()+ chartPreviewsLogic(logicProps).mount()+ })++ afterEach(() => {+ chartPreviewsLogic(logicProps).unmount()+ chartAlternativesLogic(logicProps).unmount()+ })++ function load(query: TrendsQuery, row: Record<string, unknown>, lastRefresh = FIRST_REFRESH): void {+ insightVizDataLogic(insightProps).actions.updateQuerySource(query)+ insightDataLogic(insightProps).actions.setInsightData({ results: [row], last_refresh: lastRefresh })+ }++ function lineTile(): ChartPreview | undefined {+ return chartPreviewsLogic(logicProps).values.previews.find(+ (preview) => preview.option.display === ChartDisplayType.ActionsLineGraph+ )+ }++ it('reuses the time series it saw before the chart became a total value, even when the total loaded later', async () => {+ load(trendsQuery(ChartDisplayType.ActionsLineGraph), timeSeriesRow)+ load(trendsQuery(ChartDisplayType.ActionsPie), totalValueRow, SECOND_REFRESH)+ chartAlternativesLogic(logicProps).actions.openGallery()++ await waitFor(() =>+ expect(lineTile()?.response).toMatchObject({ results: [expect.objectContaining({ data: [1, 2, 3] })] })+ )+ })++ it('does not reuse a time series remembered for a different query', async () => {+ load(trendsQuery(ChartDisplayType.ActionsLineGraph), timeSeriesRow)+ load({ ...trendsQuery(ChartDisplayType.ActionsPie), filterTestAccounts: true }, totalValueRow)+ chartAlternativesLogic(logicProps).actions.openGallery()++ await expectLogic(chartPreviewsLogic(logicProps)).toFinishAllListeners()+ expect(lineTile()).toMatchObject({ response: null })+ })++ it('shows no time series preview, and queries nothing, when a total value chart has none remembered', async () => {+ load(trendsQuery(ChartDisplayType.ActionsPie), totalValueRow)+ const queriesBeforeOpen = refreshModes.length+ chartAlternativesLogic(logicProps).actions.openGallery()++ await expectLogic(chartPreviewsLogic(logicProps)).toFinishAllListeners()+ expect(lineTile()).toMatchObject({ response: null })+ expect(refreshModes).toHaveLength(queriesBeforeOpen)+ })+})diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.tsnew file mode 100644index 000000000000..5651dd8a5344--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartPreviewsLogic.ts@@ -0,0 +1,312 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'++import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'+import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'++import type { AnyResponseType, InsightVizNode, TrendsQuery } from '~/queries/schema/schema-general'+import { NodeKind } from '~/queries/schema/schema-general'+import { ChartDisplayType } from '~/types'++import type { ChartAlternativesLogicProps } from './chartAlternativesLogic'+import { chartAlternativesLogic } from './chartAlternativesLogic'+import { applyChartDisplay } from './chartDisplayOptions'+import type { ChartDisplayOption, ChartDisplayOptionGroup } from './chartDisplayOptions'+import { RAW_TIME_SERIES_DISPLAYS, deriveChartPreview } from './chartPreviewData'++export interface ChartPreview {+ option: ChartDisplayOption+ suggested: boolean+ query: InsightVizNode+ response: AnyResponseType | null+ sample: boolean+ uniqueKey: string+}++export interface TimeSeriesEntry {+ key: string+ response: AnyResponseType+}++export function previewVizNode(querySource: TrendsQuery, display: ChartDisplayType): InsightVizNode {+ return {+ kind: NodeKind.InsightVizNode,+ source: applyChartDisplay(querySource, display),+ embedded: true,+ hidePersonsModal: true,+ showHeader: false,+ showTable: false,+ showLastComputation: false,+ showLastComputationRefresh: false,+ }+}++function hasResults(response: AnyResponseType | null | undefined): boolean {+ const queryResponse = response as { result?: unknown; results?: unknown } | null | undefined+ const raw = queryResponse?.results ?? queryResponse?.result+ return Array.isArray(raw) && raw.length > 0+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface chartPreviewsLogicValues {+ alternatives: ChartDisplayOption[] // chartAlternativesLogic+ currentDisplay: ChartDisplayType // chartAlternativesLogic+ options: ChartDisplayOptionGroup[] // chartAlternativesLogic+ trendsSource: TrendsQuery | null // chartAlternativesLogic+ insightData: Record<string, any> // insightVizDataLogic+ insightDataLoading: boolean // insightVizDataLogic+ freeResponse: AnyResponseType | null+ loadedTimeSeries: TimeSeriesEntry | null+ previews: ChartPreview[]+ rememberedTimeSeries: TimeSeriesEntry | null+ timeSeriesKey: string | null+ timeSeriesResponse: AnyResponseType | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface chartPreviewsLogicActions {+ loadDataSuccess: (+ response:+ | Record<string, any>+ | null+ | import('~/queries/schema').ErrorTrackingQueryResponse+ | import('~/queries/schema').HogQLAutocompleteResponse+ | import('~/queries/schema').HogQLMetadataResponse+ | import('~/queries/schema').HogQLQueryResponse<any[]>+ | import('~/queries/schema').HogQueryResponse+ | import('~/queries/schema').LogAttributesQueryResponse+ | import('~/queries/schema').LogValuesQueryResponse+ | import('~/queries/schema').MetricsQueryResponse+ | import('~/queries/schema').SessionsQueryResponse+ | import('~/queries/schema').TraceSpansAggregationQueryResponse+ | import('~/queries/schema').TraceSpansAttributeBreakdownQueryResponse+ | import('~/queries/schema').TraceSpansQueryResponse+ | undefined,+ payload?:+ | {+ overrideQuery: import('~/queries/schema').DataNode<Record<string, any>> | undefined+ pollOnly: boolean+ queryId: string+ refresh: import('~/queries/schema').RefreshType | undefined+ }+ | undefined+ ) => {+ payload?: {+ overrideQuery: import('~/queries/schema').DataNode<Record<string, any>> | undefined+ pollOnly: boolean+ queryId: string+ refresh: import('~/queries/schema').RefreshType | undefined+ }+ response:+ | Record<string, any>+ | null+ | import('~/queries/schema').ErrorTrackingQueryResponse+ | import('~/queries/schema').HogQLAutocompleteResponse+ | import('~/queries/schema').HogQLMetadataResponse+ | import('~/queries/schema').HogQLQueryResponse<any[]>+ | import('~/queries/schema').HogQueryResponse+ | import('~/queries/schema').LogAttributesQueryResponse+ | import('~/queries/schema').LogValuesQueryResponse+ | import('~/queries/schema').MetricsQueryResponse+ | import('~/queries/schema').SessionsQueryResponse+ | import('~/queries/schema').TraceSpansAggregationQueryResponse+ | import('~/queries/schema').TraceSpansAttributeBreakdownQueryResponse+ | import('~/queries/schema').TraceSpansQueryResponse+ | undefined+ } // insightVizDataLogic+ setInsightData: (+ response:+ | Record<string, any>+ | import('~/queries/schema').ErrorTrackingQueryResponse+ | import('~/queries/schema').EventsQueryResponse+ | import('~/queries/schema').HogQLAutocompleteResponse+ | import('~/queries/schema').HogQLMetadataResponse+ | import('~/queries/schema').HogQLQueryResponse<any[]>+ | import('~/queries/schema').HogQueryResponse+ | import('~/queries/schema').LogAttributesQueryResponse+ | import('~/queries/schema').LogsQueryResponse+ | import('~/queries/schema').LogValuesQueryResponse+ | import('~/queries/schema').MetricsQueryResponse+ | import('~/queries/schema').SessionsQueryResponse+ | import('~/queries/schema').TraceSpansAggregationQueryResponse+ | import('~/queries/schema').TraceSpansAttributeBreakdownQueryResponse+ | import('~/queries/schema').TraceSpansQueryResponse+ | import('~/queries/schema').TraceSpansTreeQueryResponse+ ) =>+ | Record<string, any>+ | import('~/queries/schema').ErrorTrackingQueryResponse+ | import('~/queries/schema').EventsQueryResponse+ | import('~/queries/schema').HogQLAutocompleteResponse+ | import('~/queries/schema').HogQLMetadataResponse+ | import('~/queries/schema').HogQLQueryResponse<any[]>+ | import('~/queries/schema').HogQueryResponse+ | import('~/queries/schema').LogAttributesQueryResponse+ | import('~/queries/schema').LogsQueryResponse+ | import('~/queries/schema').LogValuesQueryResponse+ | import('~/queries/schema').MetricsQueryResponse+ | import('~/queries/schema').SessionsQueryResponse+ | import('~/queries/schema').TraceSpansAggregationQueryResponse+ | import('~/queries/schema').TraceSpansAttributeBreakdownQueryResponse+ | import('~/queries/schema').TraceSpansQueryResponse+ | import('~/queries/schema').TraceSpansTreeQueryResponse // insightVizDataLogic+ rememberTimeSeries: (entry: TimeSeriesEntry) => {+ entry: TimeSeriesEntry+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface chartPreviewsLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ freeResponse: (insightData: Record<string, any>) => AnyResponseType | null+ timeSeriesKey: (trendsSource: TrendsQuery | null) => string | null+ loadedTimeSeries: (+ timeSeriesKey: string | null,+ currentDisplay: ChartDisplayType,+ freeResponse: AnyResponseType | null+ ) => TimeSeriesEntry | null+ timeSeriesResponse: (+ timeSeriesKey: string | null,+ rememberedTimeSeries: TimeSeriesEntry | null+ ) => AnyResponseType | null+ previews: (+ trendsSource: TrendsQuery | null,+ options: ChartDisplayOptionGroup[],+ alternatives: ChartDisplayOption[],+ freeResponse: AnyResponseType | null,+ timeSeriesResponse: AnyResponseType | null,+ insightDataLoading: boolean,+ arg: string+ ) => ChartPreview[]+ }+}++export type chartPreviewsLogicType = MakeLogicType<+ chartPreviewsLogicValues,+ chartPreviewsLogicActions,+ ChartAlternativesLogicProps,+ chartPreviewsLogicMeta+>++export const chartPreviewsLogic = kea<chartPreviewsLogicType>([+ props({} as ChartAlternativesLogicProps),+ key(keyForInsightLogicProps('new')),+ path((key) => ['products', 'product_analytics', 'insights', 'chartAlternatives', 'chartPreviewsLogic', key]),+ connect((props: ChartAlternativesLogicProps) => ({+ values: [+ chartAlternativesLogic(props),+ ['alternatives', 'currentDisplay', 'options', 'trendsSource'],+ insightVizDataLogic(props),+ ['insightData', 'insightDataLoading'],+ ],+ actions: [insightVizDataLogic(props), ['loadDataSuccess', 'setInsightData']],+ })),+ actions({+ rememberTimeSeries: (entry: TimeSeriesEntry) => ({ entry }),+ }),+ reducers({+ rememberedTimeSeries: [+ null as TimeSeriesEntry | null,+ {+ rememberTimeSeries: (_, { entry }) => entry,+ },+ ],+ }),+ selectors({+ freeResponse: [+ (s) => [s.insightData],+ (insightData: Record<string, any> | null): AnyResponseType | null =>+ insightData?.result != null || insightData?.results != null ? (insightData as AnyResponseType) : null,+ ],+ timeSeriesKey: [+ (s) => [s.trendsSource],+ (trendsSource: TrendsQuery | null): string | null =>+ trendsSource+ ? JSON.stringify(applyChartDisplay(trendsSource, ChartDisplayType.ActionsLineGraph))+ : null,+ ],+ loadedTimeSeries: [+ (s) => [s.timeSeriesKey, s.currentDisplay, s.freeResponse],+ (+ timeSeriesKey: string | null,+ currentDisplay: ChartDisplayType,+ freeResponse: AnyResponseType | null+ ): TimeSeriesEntry | null =>+ timeSeriesKey &&+ freeResponse &&+ RAW_TIME_SERIES_DISPLAYS.has(currentDisplay) &&+ hasResults(freeResponse)+ ? { key: timeSeriesKey, response: freeResponse }+ : null,+ ],+ // A total value result has no buckets, so time series tiles reuse the last time series loaded for this query.+ timeSeriesResponse: [+ (s) => [s.timeSeriesKey, s.rememberedTimeSeries],+ (timeSeriesKey: string | null, rememberedTimeSeries: TimeSeriesEntry | null): AnyResponseType | null =>+ timeSeriesKey && rememberedTimeSeries?.key === timeSeriesKey ? rememberedTimeSeries.response : null,+ ],+ previews: [+ (s) => [+ s.trendsSource,+ s.options,+ s.alternatives,+ s.freeResponse,+ s.timeSeriesResponse,+ s.insightDataLoading,+ (_, props) => keyForInsightLogicProps('new')(props),+ ],+ (+ trendsSource: TrendsQuery | null,+ options: ChartDisplayOptionGroup[],+ alternatives: ChartDisplayOption[],+ freeResponse: AnyResponseType | null,+ timeSeriesResponse: AnyResponseType | null,+ insightDataLoading: boolean,+ logicKey: string+ ): ChartPreview[] => {+ if (!trendsSource) {+ return []+ }+ const suggestedDisplays = new Set(alternatives.map((option) => option.display))+ const remaining = options.flatMap((group) =>+ group.options.filter((option) => !suggestedDisplays.has(option.display))+ )+ const ordered = [+ ...alternatives,+ ...remaining.filter((option) => !option.disabledReason),+ ...remaining.filter((option) => !!option.disabledReason),+ ]+ return ordered.map((option) => {+ const derived =+ option.disabledReason || !freeResponse || insightDataLoading+ ? null+ : deriveChartPreview(option.display, trendsSource, freeResponse, timeSeriesResponse)+ return {+ option,+ suggested: suggestedDisplays.has(option.display),+ query: previewVizNode(trendsSource, option.display),+ response: derived?.response ?? null,+ sample: derived?.sample ?? false,+ uniqueKey: `chart-preview-${logicKey}-${option.display}`,+ }+ })+ },+ ],+ }),+ listeners(({ actions, values }) => {+ const rememberLoadedTimeSeries = (): void => {+ if (values.loadedTimeSeries) {+ actions.rememberTimeSeries(values.loadedTimeSeries)+ }+ }+ return {+ loadDataSuccess: rememberLoadedTimeSeries,+ setInsightData: rememberLoadedTimeSeries,+ }+ }),+ // The insight can finish loading before this logic mounts.+ afterMount(({ actions, values }) => {+ if (values.loadedTimeSeries) {+ actions.rememberTimeSeries(values.loadedTimeSeries)+ }+ }),+])diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.test.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.test.tsnew file mode 100644index 000000000000..fa65c13bbb20--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.test.ts@@ -0,0 +1,94 @@+import { NodeKind } from '~/queries/schema/schema-general'+import type { TrendsQuery } from '~/queries/schema/schema-general'+import { BaseMathType, ChartDisplayType, PropertyFilterType, PropertyMathType, PropertyOperator } from '~/types'++import { getChartDisplayOptions } from './chartDisplayOptions'+import { getChartAlternatives } from './chartRecommendations'++function makeTrendsQuery(overrides: Partial<TrendsQuery> = {}): TrendsQuery {+ return {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ name: '$pageview',+ event: '$pageview',+ math: BaseMathType.TotalCount,+ math_property: 'duration',+ },+ ],+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph },+ ...overrides,+ }+}++const compatibleOptions = getChartDisplayOptions({+ isTrends: true,+ hasSingleSeriesOutput: true,+ hasTrendsFormula: false,+ boxPlotMissingProperty: false,+ hasMetricInsight: true,+})++describe('getChartAlternatives', () => {+ it.each([+ {+ name: 'prefers time series siblings and Metric for a plain line chart',+ query: makeTrendsQuery(),+ expected: [+ ChartDisplayType.Metric,+ ChartDisplayType.ActionsUnstackedBar,+ ChartDisplayType.ActionsAreaGraph,+ ],+ },+ {+ name: 'puts the world map first for a country breakdown, skips breakdown-dropping types and demotes vertical bars',+ query: makeTrendsQuery({+ breakdownFilter: { breakdowns: [{ property: '$geoip_country_code', type: 'event' }] },+ }),+ expected: [ChartDisplayType.WorldMap, ChartDisplayType.ActionsAreaGraph, ChartDisplayType.ActionsBarValue],+ },+ {+ name: 'puts the world map first for a country filter',+ query: makeTrendsQuery({+ properties: [+ {+ key: '$geoip_country_name',+ value: 'Germany',+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ },+ ],+ }),+ expected: [ChartDisplayType.WorldMap, ChartDisplayType.Metric, ChartDisplayType.ActionsUnstackedBar],+ },+ {+ name: 'puts the box plot first for a percentile series',+ query: makeTrendsQuery({+ series: [+ {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ math: PropertyMathType.P90,+ math_property: 'duration',+ },+ ],+ }),+ expected: [ChartDisplayType.BoxPlot, ChartDisplayType.Metric, ChartDisplayType.ActionsUnstackedBar],+ },+ {+ name: 'puts the box plot first for a moving average',+ query: makeTrendsQuery({+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph, smoothingIntervals: 7 },+ }),+ expected: [ChartDisplayType.BoxPlot, ChartDisplayType.Metric, ChartDisplayType.ActionsUnstackedBar],+ },+ {+ name: 'prefers other total value charts when viewing a pie chart',+ query: makeTrendsQuery({ trendsFilter: { display: ChartDisplayType.ActionsPie } }),+ expected: [ChartDisplayType.ActionsDonut, ChartDisplayType.ActionsBarValue, ChartDisplayType.Metric],+ },+ ])('$name', ({ query, expected }) => {+ expect(getChartAlternatives(compatibleOptions, query).map((option) => option.display)).toEqual(expected)+ })+})diff --git a/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.ts b/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.tsnew file mode 100644index 000000000000..be402c8bc9f8--- /dev/null+++ b/products/product_analytics/frontend/insights/chartAlternatives/chartRecommendations.ts@@ -0,0 +1,89 @@+import { convertPropertyGroupToProperties } from 'lib/components/PropertyFilters/utils'+import { DISPLAY_TYPES_TO_CATEGORIES, NON_BREAKDOWN_DISPLAY_TYPES, PIE_DISPLAY_TYPES } from 'lib/constants'+import { isPropertyValueMath } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/mathUtils'++import type { BreakdownFilter, TrendsQuery } from '~/queries/schema/schema-general'+import { hasBreakdownFilter } from '~/queries/utils'+import { ChartDisplayCategory, ChartDisplayType, PropertyMathType } from '~/types'+import type { AnyPropertyFilter } from '~/types'++import { breakdownProperties, isCountryProperty } from './chartDisplayOptions'+import type { ChartDisplayOption, ChartDisplayOptionGroup } from './chartDisplayOptions'++const DEFAULT_RECOMMENDATION_ORDER = [+ ChartDisplayType.Metric,+ ChartDisplayType.ActionsUnstackedBar,+ ChartDisplayType.ActionsLineGraph,+ ChartDisplayType.ActionsAreaGraph,+ ChartDisplayType.ActionsBarValue,+ ChartDisplayType.ActionsBar,+ ChartDisplayType.ActionsLineGraphCumulative,+ ChartDisplayType.ActionsPie,+ ChartDisplayType.ActionsDonut,+ ChartDisplayType.BoldNumber,+ ChartDisplayType.BoxPlot,+ ChartDisplayType.WorldMap,+]++// Vertical bars get crowded once every bucket holds one bar per breakdown value.+const BREAKDOWN_DEMOTED_DISPLAYS = [ChartDisplayType.ActionsUnstackedBar, ChartDisplayType.ActionsBar]++function isSingleCountryBreakdown(breakdownFilter?: BreakdownFilter | null): boolean {+ const properties = breakdownProperties(breakdownFilter)+ return properties.length === 1 && isCountryProperty(properties[0])+}++function hasCountryContext(query: TrendsQuery): boolean {+ if (isSingleCountryBreakdown(query.breakdownFilter)) {+ return true+ }+ const filters: AnyPropertyFilter[] = [+ ...(convertPropertyGroupToProperties(query.properties) ?? []),+ ...(query.series ?? []).flatMap((node) => node.properties ?? []),+ ]+ return filters.some((filter) => isCountryProperty(filter.key))+}++function isStatistical(query: TrendsQuery): boolean {+ return (+ (query.series ?? []).some((node) => isPropertyValueMath(node.math) && node.math !== PropertyMathType.Sum) ||+ (query.trendsFilter?.smoothingIntervals ?? 1) > 1+ )+}++function rankRecommendations(query: TrendsQuery | null, currentDisplay: ChartDisplayType): ChartDisplayType[] {+ const boosted: ChartDisplayType[] = []+ const demoted = query && hasBreakdownFilter(query.breakdownFilter) ? BREAKDOWN_DEMOTED_DISPLAYS : []+ if (query) {+ if (hasCountryContext(query)) {+ boosted.push(ChartDisplayType.WorldMap)+ }+ if (isStatistical(query)) {+ boosted.push(ChartDisplayType.BoxPlot)+ }+ }+ if (DISPLAY_TYPES_TO_CATEGORIES[currentDisplay] === ChartDisplayCategory.TotalValue) {+ boosted.push(...PIE_DISPLAY_TYPES, ChartDisplayType.ActionsBarValue)+ }+ const ranked = [...new Set([...boosted, ...DEFAULT_RECOMMENDATION_ORDER])]+ return [...ranked.filter((display) => !demoted.includes(display)), ...demoted]+}++export function getChartAlternatives(+ options: ChartDisplayOptionGroup[] | null | undefined,+ query: TrendsQuery | null+): ChartDisplayOption[] {+ const optionsByDisplay = new Map(+ (options ?? []).flatMap((group) => group.options).map((option) => [option.display, option])+ )+ const currentDisplay = query?.trendsFilter?.display ?? ChartDisplayType.ActionsLineGraph+ const hasBreakdown = hasBreakdownFilter(query?.breakdownFilter)+ return rankRecommendations(query, currentDisplay)+ .filter((recommended) => !hasBreakdown || !NON_BREAKDOWN_DISPLAY_TYPES.includes(recommended))+ .map((recommended) => optionsByDisplay.get(recommended))+ .filter(+ (option): option is ChartDisplayOption =>+ !!option && option.display !== currentDisplay && !option.disabledReason+ )+ .slice(0, 3)+}