: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
chore(insights): hold query nodes in the ActionFilter series editor (#104067)
Thomas Obermüller343a258f9776
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e221ecc35422..b233e542ee71 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3168,6 +3168,10 @@ snapshots:hash: v1.k794b7964.8747f893c33a7965b9dca08aaee8b69da0057cc5e47d12766cd91d7c39b51b3a.anQcEhSmgooKf7awO46Qxfz9Ukw7x9jiso_P42Nq7IIfilters-action-filter--funnels-group-default-name--light:hash: v1.k794b7964.8e11329af3ee072662872001361b0e3d8bdaa396426bbc8af5f2e4c803fc0f47._Z9O_8LADc1XwJTtPVJRxuCcaMQxI2nJV9avyBQ2Slw+ filters-action-filter--legacy-filters--dark:+ hash: v1.k794b7964.8420820626238986e318165d50507951f50c8649d6ef1bb7911c277dcd0ec7f0.zjvEwdrJv6Ieyv5fbOKbZVgq1Lw6xJUnl1a_5OoFrY0+ filters-action-filter--legacy-filters--light:+ hash: v1.k794b7964.ebb564a39df01d9bb6509152d11c060895cb4e8898ac402b123692bea9c5d00f.HBgV8H3NfkJN4VG_xEdWCSYUYq9s-JiuFjm1MC3PzqQfilters-action-filter--property-filters-with-popover--dark:hash: v1.k794b7964.1194666b4cd343bab53f1c5dd7b8d1b8cf3fa4c90806d6c4281bce552e7d0b5e.qDNv_aIBmjN16RPEpOADICxO1r41Few01iN_njZ93lgfilters-action-filter--property-filters-with-popover--light:diff --git a/frontend/src/lib/components/EntityFilterInfo.tsx b/frontend/src/lib/components/EntityFilterInfo.tsxindex 7452f68c6937..5fedf8cb3632 100644--- a/frontend/src/lib/components/EntityFilterInfo.tsx+++ b/frontend/src/lib/components/EntityFilterInfo.tsx@@ -3,6 +3,13 @@ import clsx from 'clsx'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { ensureStringIsNotBlank } from 'lib/utils/strings'import { getEventDefinitionIcon } from 'scenes/data-management/events/DefinitionHeader'+import {+ SeriesNode,+ isActionsSeriesNode,+ isEventsSeriesNode,+ isGroupSeriesNode,+ isWarehouseSeriesNode,+} from 'scenes/insights/filters/ActionFilter/seriesNode'import { formatEventName, getDisplayNameFromEntityFilter, isAllEventsEntityFilter } from 'scenes/insights/utils'import { getCoreFilterDefinition } from '~/taxonomy/helpers'@@ -10,6 +17,33 @@ import { ActionFilter, EntityFilter, EntityTypes } from '~/types'import { TaxonomicFilterGroupType } from './TaxonomicFilter/types'+/** A series reaches this component either as a query node or as the legacy entity filter that+ * query responses and the legacy-persisted surfaces still carry. */+export type DisplayableEntity = EntityFilter | ActionFilter | SeriesNode++/** Reads a node into the legacy display fields, so one set of display rules serves both shapes. */+export type DisplayEntityFilter = (EntityFilter | ActionFilter) & { table_name?: string }++export function toDisplayEntityFilter(filter: DisplayableEntity): DisplayEntityFilter {+ if (!('kind' in filter)) {+ return filter+ }+ const shared = { name: filter.name, custom_name: filter.custom_name }+ if (isEventsSeriesNode(filter)) {+ return { ...shared, type: EntityTypes.EVENTS, id: filter.event ?? null }+ }+ if (isActionsSeriesNode(filter)) {+ return { ...shared, type: EntityTypes.ACTIONS, id: filter.id }+ }+ if (isWarehouseSeriesNode(filter)) {+ return { ...shared, type: EntityTypes.DATA_WAREHOUSE, id: filter.table_name, table_name: filter.table_name }+ }+ if (isGroupSeriesNode(filter)) {+ return { ...shared, type: EntityTypes.GROUPS, id: null }+ }+ return { ...shared, id: null }+}+interface UnderlyingEntity {/** The raw key the filter queries: event name as sent, action name, or table name. */raw: string@@ -23,7 +57,7 @@ interface UnderlyingEntity {* A series can be renamed via `custom_name` or by overriding `name` directly (e.g. via the* API), so neither of those fields reliably reveals what is actually being queried.*/-function getUnderlyingEntity(filter: EntityFilter | ActionFilter): UnderlyingEntity | null {+function getUnderlyingEntity(filter: DisplayEntityFilter): UnderlyingEntity | null {if (filter.type === EntityTypes.ACTIONS) {const raw = ensureStringIsNotBlank(filter.name) ?? (filter.id != null ? String(filter.id) : null)return raw ? { raw, display: raw, kind: 'action' } : null@@ -60,9 +94,10 @@ interface EntityFilterDisplayInfo {}function getEntityFilterDisplayInfo(- filter: EntityFilter | ActionFilter,+ entity: DisplayableEntity,filterGroupType?: TaxonomicFilterGroupType): EntityFilterDisplayInfo {+ const filter = toDisplayEntityFilter(entity)let name: string | undefinedif (isAllEventsEntityFilter(filter) && !filter?.custom_name) {name = 'All events'@@ -97,8 +132,12 @@ export interface SeriesRename {* use it to label the committed selection like the series the user clicked. Data* warehouse series keep their own committed-selection affordance, so they never report one.*/-export function getSeriesRename(filter: EntityFilter | ActionFilter | null | undefined): SeriesRename | null {- if (!filter || filter.type === EntityTypes.DATA_WAREHOUSE) {+export function getSeriesRename(entity: DisplayableEntity | null | undefined): SeriesRename | null {+ if (!entity) {+ return null+ }+ const filter = toDisplayEntityFilter(entity)+ if (filter.type === EntityTypes.DATA_WAREHOUSE) {return null}const { displayName, underlying, isRenamed } = getEntityFilterDisplayInfo(filter)@@ -134,7 +173,7 @@ function EntityFilterInfoTooltipTitle({}interface EntityFilterInfoProps {- filter?: EntityFilter | ActionFilter | null+ filter?: DisplayableEntity | nullallowWrap?: booleanshowSingleName?: booleanstyle?: React.CSSProperties@@ -145,7 +184,7 @@ interface EntityFilterInfoProps {}export function EntityFilterInfo({- filter,+ filter: entity,allowWrap = false,showSingleName = false,style,@@ -158,9 +197,10 @@ export function EntityFilterInfo({// `filter` is null for formula series (and can be absent for other callers); render nothing// rather than dereferencing it in getEntityFilterDisplayInfo.- if (!filter) {+ if (!entity) {return <></>}+ const filter = toDisplayEntityFilter(entity)const { displayName, baseName, underlying, isRenamed } = getEntityFilterDisplayInfo(filter, filterGroupType)diff --git a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsxindex 37bb512a558a..78afdb48f589 100644--- a/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx+++ b/frontend/src/lib/components/TaxonomicFilter/InfiniteList.tsx@@ -12,7 +12,12 @@ import { LemonButton, LemonDivider, LemonTag } from '@posthog/lemon-ui'import { AutoSizer } from 'lib/components/AutoSizer'import { ControlledDefinitionPopover } from 'lib/components/DefinitionPopover/DefinitionPopoverContents'import { definitionPopoverLogic } from 'lib/components/DefinitionPopover/definitionPopoverLogic'-import { EntityFilterInfo, getSeriesRename } from 'lib/components/EntityFilterInfo'+import {+ DisplayableEntity,+ EntityFilterInfo,+ getSeriesRename,+ toDisplayEntityFilter,+} from 'lib/components/EntityFilterInfo'import { formatPropertyLabel } from 'lib/components/PropertyFilters/utils'import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'import { AUTOCAPTURE_INTERACTIONS } from 'lib/components/TaxonomicFilter/eventTypeShortcuts'@@ -43,7 +48,7 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { pluralize } from 'lib/utils/strings'import { getCoreFilterDefinition } from '~/taxonomy/helpers'-import { EntityFilter, EventDefinition, PropertyDefinition } from '~/types'+import { EventDefinition, PropertyDefinition } from '~/types'import { NO_ITEM_SELECTED, infiniteListLogic } from './infiniteListLogic'import { TaxonomicEventMatchSuggestions } from './TaxonomicEventMatchSuggestions'@@ -168,15 +173,14 @@ const unusedIndicator = (eventNames: string[]): JSX.Element => {* the user clicked.*/const getSelectedItemRenameMeta = (- selectedItemMeta: EntityFilter | null | undefined,+ selectedItemMeta: DisplayableEntity | null | undefined,itemValue: string | number | null | undefined-): EntityFilter | null => {- if (- !selectedItemMeta ||- selectedItemMeta.id == null ||- itemValue == null ||- String(selectedItemMeta.id) !== String(itemValue)- ) {+): DisplayableEntity | null => {+ if (!selectedItemMeta || itemValue == null) {+ return null+ }+ const { id } = toDisplayEntityFilter(selectedItemMeta)+ if (id == null || String(id) !== String(itemValue)) {return null}return getSeriesRename(selectedItemMeta) ? selectedItemMeta : null@@ -208,7 +212,7 @@ const renderItemContents = ({itemGroup: TaxonomicFilterGroupeventNames: string[]isActive: boolean- selectedRenameMeta?: EntityFilter | null+ selectedRenameMeta?: DisplayableEntity | null}): JSX.Element | string => {if (isQuickFilterItem(item)) {const icon = itemGroup.getIcon ? (@@ -374,7 +378,7 @@ interface InfiniteListRowProps {groupType: TaxonomicFilterGroupType | undefinedvalue: string | number | null | undefinedselectedProperties: TaxonomicFilterGroupValueMap- selectedItemMeta: EntityFilter | null | undefined+ selectedItemMeta: DisplayableEntity | null | undefinedeventNames: string[]highlightedIndex: numberisActiveTab: booleandiff --git a/frontend/src/lib/components/TaxonomicFilter/types.ts b/frontend/src/lib/components/TaxonomicFilter/types.tsindex a600a4dfd11a..6eb16da7ed61 100644--- a/frontend/src/lib/components/TaxonomicFilter/types.ts+++ b/frontend/src/lib/components/TaxonomicFilter/types.ts@@ -2,6 +2,7 @@ import Fuse from 'fuse.js'import { LogicWrapper } from 'kea'import { ReactNode } from 'react'+import type { SeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'// eslint-disable-next-line import/no-cycleimport { MaxContextTaxonomicFilterOption } from 'scenes/max/maxTypes'@@ -126,7 +127,7 @@ export interface TaxonomicFilterProps {onClose?: () => void/** The series/entity filter the picker is editing — lets the list surface* the committed selection with its rename (`custom_name`) applied. */- filter?: EntityFilter | ActionFilter+ filter?: EntityFilter | ActionFilter | SeriesNodetaxonomicGroupTypes: TaxonomicFilterGroupType[]taxonomicFilterLogicKey?: stringoptionsFromProp?: Partial<Record<TaxonomicFilterGroupType, SimpleOption[]>>diff --git a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsx b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsxindex a743989ded3d..c7f61e92e6d8 100644--- a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsx+++ b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopover.tsx@@ -4,6 +4,7 @@ import { Ref, forwardRef, useEffect, useId, useState } from 'react'import { IconX } from '@posthog/icons'+import { DisplayableEntity } from 'lib/components/EntityFilterInfo'import { taxonomicTriggerWrapperClassName } from 'lib/components/TaxonomicFilter/menu/triggerLayout'import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'import {@@ -21,7 +22,6 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { MaxContextTaxonomicFilterOption } from 'scenes/max/maxTypes'import { AnyDataNode, DatabaseSchemaField } from '~/queries/schema/schema-general'-import { ActionFilter, EntityFilter } from '~/types'import { taxonomicMenuPreferenceLogic } from './taxonomicMenuPreferenceLogic'import { TaxonomicMenuToggle } from './TaxonomicMenuToggle'@@ -35,7 +35,7 @@ export interface TaxonomicPopoverProps<ValueType extends TaxonomicFilterValue =value?: ValueType | nullonChange: (value: ValueType, groupType: TaxonomicFilterGroupType, item: any) => void- filter?: EntityFilter | ActionFilter+ filter?: DisplayableEntitygroupTypes?: TaxonomicFilterGroupType[]renderValue?: (value: ValueType) => JSX.Element | nulleventNames?: string[]diff --git a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsxindex 16b59e716e07..9c88a7b1904a 100644--- a/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx+++ b/frontend/src/lib/components/TaxonomicPopover/TaxonomicPopoverMenu.tsx@@ -23,7 +23,7 @@ import { ReactElement, useEffect, useMemo, useState } from 'react'import { IconChevronDown, IconFilter } from '@posthog/icons'-import { SeriesRename, getSeriesRename } from 'lib/components/EntityFilterInfo'+import { DisplayableEntity, SeriesRename, getSeriesRename } from 'lib/components/EntityFilterInfo'import { TaxonomicFilterHeadless } from 'lib/components/TaxonomicFilter/headless'import { MenuFilterEntry, TaxonomicFilterMenu } from 'lib/components/TaxonomicFilter/menu'import { MenuInputTrigger } from 'lib/components/TaxonomicFilter/menu/InputTrigger'@@ -43,7 +43,6 @@ import { databaseTableListLogic } from 'scenes/data-management/database/databaseimport { MaxContextTaxonomicFilterOption } from 'scenes/max/maxTypes'import { AnyDataNode, DatabaseSchemaField } from '~/queries/schema/schema-general'-import { ActionFilter, EntityFilter } from '~/types'import { TaxonomicMenuToggle } from './TaxonomicMenuToggle'@@ -70,7 +69,7 @@ export interface TaxonomicPopoverMenuProps<ValueType extends TaxonomicFilterValugroupType: TaxonomicFilterGroupTypevalue?: ValueType | null/** The series/entity filter being edited — surfaces its rename on the committed selection. */- filter?: EntityFilter | ActionFilter+ filter?: DisplayableEntitygroupTypes?: TaxonomicFilterGroupType[]/** The 4th arg is the orchestrator's resolved group — consumers that* need the full `TaxonomicFilterGroup` (not just its type) can use it. */diff --git a/frontend/src/models/saveAsActionDialog.test.tsx b/frontend/src/models/saveAsActionDialog.test.tsxindex 34bcfdfe2ddc..bfa0d84e55cb 100644--- a/frontend/src/models/saveAsActionDialog.test.tsx+++ b/frontend/src/models/saveAsActionDialog.test.tsx@@ -2,12 +2,12 @@ import '@testing-library/jest-dom'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { LocalFilter } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'import { useMocks } from '~/mocks/jest'import { actionsModel } from '~/models/actionsModel'+import { EventsNode, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { EntityTypes, EventType, PropertyFilterType, PropertyOperator, RecordingEventType } from '~/types'+import { EventType, PropertyFilterType, PropertyOperator, RecordingEventType } from '~/types'import {buildActionNameValidator,@@ -16,7 +16,7 @@ import {isAutocaptureWithElements,openSaveAsActionDialog,saveActionFromEvent,- saveActionFromFilter,+ saveActionFromSeriesNode,} from './saveAsActionDialog'function makeAutocaptureEvent(overrides: Partial<EventType> = {}): EventType {@@ -31,13 +31,11 @@ function makeAutocaptureEvent(overrides: Partial<EventType> = {}): EventType {} as EventType}-function makeFilter(overrides: Partial<LocalFilter> = {}): LocalFilter {+function makeSeriesNode(overrides: Partial<EventsNode> = {}): EventsNode {return {- id: '$autocapture',+ kind: NodeKind.EventsNode,+ event: '$autocapture',name: '$autocapture',- type: EntityTypes.EVENTS,- order: 0,- uuid: 'test-uuid',properties: [],...overrides,}@@ -242,10 +240,10 @@ describe('saveAsActionDialog', () => {})})- describe('saveActionFromFilter', () => {+ describe('saveActionFromSeriesNode', () => {it('pre-fills name and step from a filter with $el_text', async () => {- saveActionFromFilter(- makeFilter({+ saveActionFromSeriesNode(+ makeSeriesNode({properties: [{key: '$el_text',@@ -269,8 +267,8 @@ describe('saveAsActionDialog', () => {})it('posts the full filter → action step mapping for text + selector', async () => {- saveActionFromFilter(- makeFilter({+ saveActionFromSeriesNode(+ makeSeriesNode({properties: [{key: '$el_text',diff --git a/frontend/src/models/saveAsActionDialog.tsx b/frontend/src/models/saveAsActionDialog.tsxindex 1bfadf0af8fe..afe7d3dc2f82 100644--- a/frontend/src/models/saveAsActionDialog.tsx+++ b/frontend/src/models/saveAsActionDialog.tsx@@ -13,10 +13,10 @@ import {elementsToAction,} from 'scenes/activity/explore/createActionFromEvent'import {- filterToActionStep,- generateActionNameFromFilter,+ generateActionNameFromSeriesNode,+ seriesNodeToActionStep,} from 'scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils'-import { LocalFilter } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'+import { SeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'import { urls } from 'scenes/urls'import { actionsModel } from '~/models/actionsModel'@@ -137,10 +137,10 @@ export function openSaveAsActionDialog({ suggestedName, step, createInFolder }:})}-export function saveActionFromFilter(filter: LocalFilter): void {+export function saveActionFromSeriesNode(node: SeriesNode): void {openSaveAsActionDialog({- suggestedName: generateActionNameFromFilter(filter),- step: filterToActionStep(filter),+ suggestedName: generateActionNameFromSeriesNode(node),+ step: seriesNodeToActionStep(node),})}diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.stories.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.stories.tsxindex c014789351e7..f19c968e5ed2 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.stories.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.stories.tsx@@ -6,22 +6,30 @@ import { useRef, useState } from 'react'import { taxonomicFilterMocksDecorator } from 'lib/components/TaxonomicFilter/__mocks__/taxonomicFilterMocksDecorator'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { SINGLE_SERIES_DISPLAY_TYPES } from 'lib/constants'+import { DISPLAY_TYPES_TO_CATEGORIES, SINGLE_SERIES_DISPLAY_TYPES } from 'lib/constants'import { uuid } from 'lib/utils/dom'import { alphabet } from 'lib/utils/strings'import { insightLogic } from 'scenes/insights/insightLogic'-import { isFilterWithDisplay, isLifecycleFilter } from 'scenes/insights/sharedUtils'import { cohortsModel } from '~/models/cohortsModel'import { groupsModel } from '~/models/groupsModel'-import { EntityTypes, FilterLogicalOperator, FilterType, InsightLogicProps, InsightType } from '~/types'+import { AnyEntityNode, NodeKind } from '~/queries/schema/schema-general'+import {+ ChartDisplayType,+ EntityTypes,+ FilterLogicalOperator,+ FilterType,+ InsightLogicProps,+ InsightType,+} from '~/types'import __trendsLineBreakdown from '../../../../mocks/fixtures/api/projects/team_id/insights/trendsLineBreakdown.json'-import { ActionFilter, ActionFilterProps } from './ActionFilter'+import { ActionFilter, ActionFilterProps, SeriesActionFilter, SeriesActionFilterProps } from './ActionFilter'import { MathAvailability } from './ActionFilterRow/types'+import { SeriesNode } from './seriesNode'-type Story = StoryObj<ActionFilterProps>-const meta: Meta<ActionFilterProps> = {+type Story = StoryObj<SeriesActionFilterProps>+const meta: Meta<SeriesActionFilterProps> = {title: 'Filters/Action Filter',decorators: [taxonomicFilterMocksDecorator],}@@ -29,59 +37,72 @@ export default metalet uniqueNode = 0-const renderActionFilter = ({ ...props }: Partial<ActionFilterProps>): JSX.Element => {- useMountedLogic(cohortsModel)- const { groupsTaxonomicTypes } = useValues(groupsModel)-- const id = useRef(uuid())+const eventNode = (event: string, extra: Record<string, any> = {}): AnyEntityNode =>+ ({ kind: NodeKind.EventsNode, event, name: event, ...extra }) as AnyEntityNode++const group = (nodes: AnyEntityNode[], opts: { custom_name?: string; math?: Record<string, any> } = {}): SeriesNode =>+ ({+ kind: NodeKind.GroupNode,+ name: nodes.map((node) => node.name).join(', '),+ operator: FilterLogicalOperator.Or,+ nodes,+ ...opts.math,+ ...(opts.custom_name && { custom_name: opts.custom_name }),+ }) as SeriesNode++/** insightLogic only needs something cached to sit in; the editor reads its series from props. */+function useStoryInsightProps(): InsightLogicProps {+ const [dashboardItemId] = useState(() => `ActionFilterStory.${uniqueNode++}`)+ const insight = __trendsLineBreakdown as any+ return {+ dashboardItemId,+ doNotLoad: true,+ cachedInsight: { ...insight, short_id: dashboardItemId },+ } as InsightLogicProps+}- const [filters, setFilters] = useState<FilterType>({- insight: InsightType.TRENDS,- events: [+const DEFAULT_SERIES: SeriesNode[] = [+ eventNode('$pageview', {+ properties: [{- id: '$pageview',- name: '$pageview',- order: 0,- type: 'events',- properties: [- {- key: '$browser',- value: ['Chrome'],- operator: 'exact',- type: 'person',- },- ],+ key: '$browser',+ value: ['Chrome'],+ operator: 'exact',+ type: 'person',},],- })+ }),+]- const [dashboardItemId] = useState(() => `ActionFilterStory.${uniqueNode++}`)+const renderActionFilter = ({ ...props }: Partial<SeriesActionFilterProps>): JSX.Element => {+ useMountedLogic(cohortsModel)+ const { groupsTaxonomicTypes } = useValues(groupsModel)- // eslint-disable-next-line @typescript-eslint/no-var-requires- const insight = __trendsLineBreakdown as any- const cachedInsight = { ...insight, short_id: dashboardItemId, filters }- const insightProps = { dashboardItemId, doNotLoad: true, cachedInsight } as InsightLogicProps+ const id = useRef(uuid())+ const [series, setSeries] = useState<SeriesNode[]>(DEFAULT_SERIES)+ const [insightType] = useState<InsightType>(InsightType.TRENDS)+ const [display] = useState<ChartDisplayType>(ChartDisplayType.ActionsLineGraph)+ const insightProps = useStoryInsightProps()return (<BindLogic logic={insightLogic} props={insightProps}>- <ActionFilter- filters={filters}- setFilters={(payload: Partial<FilterType>): void => setFilters(payload)}+ <SeriesActionFilter+ series={series}+ onChange={setSeries}typeKey={`trends_${id.current}`}+ insightType={insightType}+ trendsDisplayCategory={DISPLAY_TYPES_TO_CATEGORIES[display]}buttonCopy="Add graph series"showSeriesIndicatorentitiesLimit={- isLifecycleFilter(filters) ||- (isFilterWithDisplay(filters) &&- filters.display &&- SINGLE_SERIES_DISPLAY_TYPES.includes(filters.display))+ insightType === InsightType.LIFECYCLE || SINGLE_SERIES_DISPLAY_TYPES.includes(display)? 1: alphabet.length}mathAvailability={- filters.insight === InsightType.LIFECYCLE+ insightType === InsightType.LIFECYCLE? MathAvailability.None- : filters.insight === InsightType.STICKINESS+ : insightType === InsightType.STICKINESS? MathAvailability.ActorsOnly: MathAvailability.All}@@ -142,51 +163,39 @@ export const SingleFilter: Story = {},}-const renderAutocaptureFilter = ({ ...props }: Partial<ActionFilterProps>): JSX.Element => {+const renderAutocaptureFilter = ({ ...props }: Partial<SeriesActionFilterProps>): JSX.Element => {useMountedLogic(cohortsModel)const { groupsTaxonomicTypes } = useValues(groupsModel)const id = useRef(uuid())-- const [filters, setFilters] = useState<FilterType>({- insight: InsightType.TRENDS,- events: [- {- id: '$autocapture',- name: '$autocapture',- order: 0,- type: 'events',- properties: [- {- key: '$el_text',- value: 'Submit',- operator: 'exact',- type: 'event',- },- {- key: 'selector',- value: '.btn-primary',- operator: 'exact',- type: 'element',- },- ],- },- ],- })-- const [dashboardItemId] = useState(() => `ActionFilterStory.${uniqueNode++}`)-- // eslint-disable-next-line @typescript-eslint/no-var-requires- const insight = __trendsLineBreakdown as any- const cachedInsight = { ...insight, short_id: dashboardItemId, filters }- const insightProps = { dashboardItemId, doNotLoad: true, cachedInsight } as InsightLogicProps+ const [series, setSeries] = useState<SeriesNode[]>([+ eventNode('$autocapture', {+ properties: [+ {+ key: '$el_text',+ value: 'Submit',+ operator: 'exact',+ type: 'event',+ },+ {+ key: 'selector',+ value: '.btn-primary',+ operator: 'exact',+ type: 'element',+ },+ ],+ }),+ ])+ const insightProps = useStoryInsightProps()return (<BindLogic logic={insightLogic} props={insightProps}>- <ActionFilter- filters={filters}- setFilters={(payload: Partial<FilterType>): void => setFilters(payload)}+ <SeriesActionFilter+ series={series}+ onChange={setSeries}typeKey={`trends_${id.current}`}+ insightType={InsightType.TRENDS}+ trendsDisplayCategory={DISPLAY_TYPES_TO_CATEGORIES[ChartDisplayType.ActionsLineGraph]}buttonCopy="Add graph series"showSeriesIndicatormathAvailability={MathAvailability.All}@@ -226,50 +235,32 @@ export const AutocaptureWithSaveAsAction: Story = {},}-const groupEvent = (id: string, name: string, order: number, math?: Record<string, any>): Record<string, any> => ({- id,- type: EntityTypes.EVENTS,- name,- order,- ...math,-})--const group = (- order: number,- nestedFilters: any[],- opts: { custom_name?: string; math?: Record<string, any> } = {}-): Record<string, any> => ({- id: null,- type: EntityTypes.GROUPS,- name: nestedFilters.map((f: any) => f.name).join(', '),- order,- operator: FilterLogicalOperator.Or,- nestedFilters,- ...opts.math,- ...(opts.custom_name && { custom_name: opts.custom_name }),-})--const renderGroupStory = (initialFilters: FilterType, actionFilterProps: Partial<ActionFilterProps> = {}) => {- return ({ ...props }: Partial<ActionFilterProps>): JSX.Element => {+const renderGroupStory = (+ initialSeries: SeriesNode[],+ insightType: InsightType,+ actionFilterProps: Partial<SeriesActionFilterProps> = {}+) => {+ return ({ ...props }: Partial<SeriesActionFilterProps>): JSX.Element => {useMountedLogic(cohortsModel)const { groupsTaxonomicTypes } = useValues(groupsModel)const id = useRef(uuid())- const [filters, setFilters] = useState<FilterType>(initialFilters)- const [dashboardItemId] = useState(() => `ActionFilterStory.${uniqueNode++}`)-- // eslint-disable-next-line @typescript-eslint/no-var-requires- const insight = __trendsLineBreakdown as any- const cachedInsight = { ...insight, short_id: dashboardItemId, filters }- const insightProps = { dashboardItemId, doNotLoad: true, cachedInsight } as InsightLogicProps+ const [series, setSeries] = useState<SeriesNode[]>(initialSeries)+ const insightProps = useStoryInsightProps()return (<BindLogic logic={insightLogic} props={insightProps}>- <ActionFilter+ <SeriesActionFilter{...props}- filters={filters}- setFilters={(payload: Partial<FilterType>): void => setFilters(payload)}+ series={series}+ onChange={setSeries}typeKey={`group_story_${id.current}`}- buttonCopy={filters.insight === InsightType.FUNNELS ? 'Add funnel step' : 'Add graph series'}+ insightType={insightType}+ trendsDisplayCategory={+ insightType === InsightType.TRENDS+ ? DISPLAY_TYPES_TO_CATEGORIES[ChartDisplayType.ActionsLineGraph]+ : null+ }+ buttonCopy={insightType === InsightType.FUNNELS ? 'Add funnel step' : 'Add graph series'}showSeriesIndicatorentitiesLimit={alphabet.length}propertiesTaxonomicGroupTypes={[@@ -287,47 +278,37 @@ const renderGroupStory = (initialFilters: FilterType, actionFilterProps: Partial}export const TrendsGroupDefaultName: Story = {- render: renderGroupStory({- insight: InsightType.TRENDS,- groups: [group(0, [groupEvent('$pageview', '$pageview', 0), groupEvent('$exception', '$exception', 1)])],- }),+ render: renderGroupStory([group([eventNode('$pageview'), eventNode('$exception')])], InsightType.TRENDS),args: {},}export const TrendsGroupCustomName: Story = {- render: renderGroupStory({- insight: InsightType.TRENDS,- groups: [- group(0, [groupEvent('$pageview', '$pageview', 0), groupEvent('$exception', '$exception', 1)], {- custom_name: 'My custom name',- }),- ],- }),+ render: renderGroupStory(+ [group([eventNode('$pageview'), eventNode('$exception')], { custom_name: 'My custom name' })],+ InsightType.TRENDS+ ),args: {},}const hogqlMath = { math: 'hogql', math_hogql: 'sum(toInt(properties.$revenue))' }export const TrendsGroupCustomNameHogQL: Story = {- render: renderGroupStory({- insight: InsightType.TRENDS,- groups: [- group(0, [groupEvent('$pageview', '$pageview', 0, hogqlMath)], {+ render: renderGroupStory(+ [+ group([eventNode('$pageview', hogqlMath)], {custom_name: 'My custom name (HogQL)',math: hogqlMath,}),],- }),+ InsightType.TRENDS+ ),args: {},}export const FunnelsGroupDefaultName: Story = {render: renderGroupStory(- {- insight: InsightType.FUNNELS,- groups: [group(0, [groupEvent('$pageview', '$pageview', 0), groupEvent('$exception', '$exception', 1)])],- events: [groupEvent('$pageleave', '$pageleave', 1)],- },+ [group([eventNode('$pageview'), eventNode('$exception')]), eventNode('$pageleave') as SeriesNode],+ InsightType.FUNNELS,{seriesIndicatorType: 'numeric',sortable: true,@@ -339,15 +320,11 @@ export const FunnelsGroupDefaultName: Story = {export const FunnelsGroupCustomName: Story = {render: renderGroupStory(- {- insight: InsightType.FUNNELS,- groups: [- group(0, [groupEvent('$pageview', '$pageview', 0), groupEvent('$exception', '$exception', 1)], {- custom_name: 'My custom name',- }),- ],- events: [groupEvent('$pageleave', '$pageleave', 1)],- },+ [+ group([eventNode('$pageview'), eventNode('$exception')], { custom_name: 'My custom name' }),+ eventNode('$pageleave') as SeriesNode,+ ],+ InsightType.FUNNELS,{seriesIndicatorType: 'numeric',sortable: true,@@ -356,3 +333,44 @@ export const FunnelsGroupCustomName: Story = {),args: {},}++/**+ * The legacy-persisted surfaces (CDP, workflows, heatmaps, usage metrics, dashboard templates,+ * retention) keep the `filters`/`setFilters` props through the wrapper.+ */+const renderLegacyActionFilter = ({ ...props }: Partial<ActionFilterProps>): JSX.Element => {+ useMountedLogic(cohortsModel)+ const id = useRef(uuid())+ const [filters, setFilters] = useState<FilterType>({+ insight: InsightType.TRENDS,+ events: [+ {+ id: '$pageview',+ name: '$pageview',+ order: 0,+ type: EntityTypes.EVENTS,+ properties: [{ key: '$browser', value: ['Chrome'], operator: 'exact', type: 'person' }],+ },+ ],+ } as FilterType)+ const insightProps = useStoryInsightProps()++ return (+ <BindLogic logic={insightLogic} props={insightProps}>+ <ActionFilter+ filters={filters}+ setFilters={(payload: FilterType) => setFilters({ ...filters, ...payload })}+ typeKey={`legacy_${id.current}`}+ buttonCopy="Add graph series"+ showSeriesIndicator+ mathAvailability={MathAvailability.None}+ {...props}+ />+ </BindLogic>+ )+}++export const LegacyFilters: Story = {+ render: renderLegacyActionFilter as any,+ args: {},+}diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.test.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.test.tsxnew file mode 100644index 000000000000..421569b5ec2e--- /dev/null+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.test.tsx@@ -0,0 +1,102 @@+import { MOCK_GROUP_TYPES } from '~/lib/api.mock'++import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { Provider } from 'kea'++import { useMocks } from '~/mocks/jest'+import { actionsModel } from '~/models/actionsModel'+import { groupsModel } from '~/models/groupsModel'+import { initKeaTests } from '~/test/init'+import { setupInsightMocks } from '~/test/insight-testing'+import { EntityTypes, FilterType, PropertyFilterType, PropertyOperator } from '~/types'++import { ActionFilter } from './ActionFilter'+import { MathAvailability } from './ActionFilterRow/types'++// CDP compiles these filters to bytecode on the backend, so the wrapper has to hand them back+// with the same field names it was given.+const CDP_FILTERS = {+ events: [+ {+ id: '$pageview',+ type: EntityTypes.EVENTS,+ name: '$pageview',+ order: 0,+ properties: [+ {+ key: '$current_url',+ value: 'https://example.com',+ operator: PropertyOperator.IContains,+ type: PropertyFilterType.Event,+ },+ ],+ },+ ],+ actions: [{ id: '9', type: EntityTypes.ACTIONS, name: 'Users signed up', order: 1, properties: [] }],+ data_warehouse: [+ {+ id: 'payments',+ type: EntityTypes.DATA_WAREHOUSE,+ name: 'payments',+ order: 2,+ table_name: 'payments',+ timestamp_field: 'created_at',+ distinct_id_field: 'person_id',+ id_field: 'id',+ properties: [],+ },+ ],+} as unknown as FilterType++describe('ActionFilter', () => {+ afterEach(cleanup)++ beforeEach(() => {+ initKeaTests()+ setupInsightMocks()+ useMocks({+ get: {+ '/api/projects/:team/actions/': { results: CDP_FILTERS.actions },+ '/api/environments/:team/groups_types/': MOCK_GROUP_TYPES,+ '/api/projects/:team/warehouse_tables/': { results: [] },+ '/api/projects/:team/warehouse_saved_queries/': { results: [] },+ '/api/projects/:team/warehouse_view_links/': { results: [] },+ },+ })+ actionsModel.mount()+ groupsModel.mount()+ })++ it('hands a CDP-shaped filter object back unchanged after a UI edit', async () => {+ const setFilters = jest.fn()+ render(+ <Provider>+ <ActionFilter+ filters={CDP_FILTERS}+ setFilters={setFilters}+ typeKey="plugin-filters"+ mathAvailability={MathAvailability.None}+ buttonCopy="Add filter"+ />+ </Provider>+ )++ await userEvent.click(screen.getByTestId('add-action-event-button'))++ expect(setFilters).toHaveBeenCalledTimes(1)+ const emitted = setFilters.mock.calls[0][0]++ expect(emitted.events).toEqual([+ expect.objectContaining({ ...CDP_FILTERS.events![0], order: 0 }),+ // the row the edit added+ expect.objectContaining({ type: EntityTypes.EVENTS, order: 3 }),+ ])+ expect(emitted.actions).toEqual([expect.objectContaining({ ...CDP_FILTERS.actions![0], id: 9, order: 1 })])+ expect(emitted.data_warehouse).toEqual([+ expect.objectContaining({ ...CDP_FILTERS.data_warehouse![0], order: 2 }),+ ])+ })+})diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.tsxindex 2eaabb555a83..47662d067dab 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilter.tsx@@ -5,7 +5,7 @@ import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiimport { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable'import clsx from 'clsx'import { BindLogic, useActions, useValues } from 'kea'-import React, { useEffect } from 'react'+import React, { useEffect, useMemo } from 'react'import { IconPlusSmall } from '@posthog/icons'@@ -22,27 +22,29 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { RenameModal } from 'scenes/insights/filters/ActionFilter/RenameModal'import { isTrendsFilter } from 'scenes/insights/sharedUtils'-import {- ActionFilter as ActionFilterType,- ChartDisplayType,- EntityTypes,- FilterType,- FunnelExclusionLegacy,- InsightType,- PropertyOperator,-} from '~/types'+import { EventsNode } from '~/queries/schema/schema-general'+import { ChartDisplayCategory, ChartDisplayType, FilterType, InsightType, PropertyOperator } from '~/types'-import { teamLogic } from '../../../teamLogic'import { ActionFilterGroup } from './ActionFilterGroup/ActionFilterGroup'import { ActionFilterRow } from './ActionFilterRow/ActionFilterRow'import { MathAvailability } from './ActionFilterRow/types'-import { LocalFilter, entityFilterLogic, toFilters } from './entityFilterLogic'+import { LocalSeries, entityFilterLogic } from './entityFilterLogic'+import { legacyFiltersToSeries, seriesToLegacyFilters } from './legacyFilters'+import { SeriesNode, WarehouseSeriesNodeKind, isGroupSeriesNode } from './seriesNode'-export interface ActionFilterProps {- setFilters: (filters: FilterType) => void- filters: FilterType+export interface SeriesActionFilterProps {+ series: SeriesNode[]+ onChange: (series: SeriesNode[]) => voidtypeKey: string- addFilterDefaultOptions?: Record<string, any>+ dataWarehouseNodeKind?: WarehouseSeriesNodeKind+ /** Fields a new series starts with, on top of the project's default event. */+ newSeriesDefaults?: Partial<EventsNode>+ /** Drives combine availability, the rename modal title, the limit copy and the docs link. */+ insightType?: InsightType+ /** Whether the insight has a breakdown, which changes the series letter colours. */+ hasBreakdown?: boolean+ /** Display category of the trends chart, or null outside a trends context. */+ trendsDisplayCategory?: ChartDisplayCategory | nullmathAvailability?: MathAvailability/** Text copy for the action button to add more events/actions (graph series) */buttonCopy?: string@@ -75,11 +77,7 @@ export interface ActionFilterProps {customRowSuffix?:| string| JSX.Element- | ((props: {- filter: ActionFilterType | FunnelExclusionLegacy- index: number- onClose: () => void- }) => JSX.Element)+ | ((props: { node: SeriesNode; index: number; onClose: () => void }) => JSX.Element)/** Show nested arrows to the left of property filter buttons */showNestedArrow?: boolean/** Which tabs to show for actions selector */@@ -88,7 +86,7 @@ export interface ActionFilterProps {propertiesTaxonomicGroupTypes?: TaxonomicFilterGroupType[]/** Whether properties shown should be limited to just numerical types */showNumericalPropsOnly?: boolean- hideDeleteBtn?: boolean | ((filter: LocalFilter, index: number) => boolean)+ hideDeleteBtn?: boolean | ((node: SeriesNode, index: number) => boolean)readOnly?: booleanrenderRow?: ({seriesIndicator,@@ -119,12 +117,16 @@ export interface ActionFilterProps {customFooter?: React.ReactNode}-export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>(function ActionFilter(+export const SeriesActionFilter = React.forwardRef<HTMLDivElement, SeriesActionFilterProps>(function SeriesActionFilter({- setFilters,- filters,+ series,+ onChange,typeKey,- addFilterDefaultOptions = {},+ dataWarehouseNodeKind,+ newSeriesDefaults,+ insightType,+ hasBreakdown = false,+ trendsDisplayCategory = null,mathAvailability = MathAvailability.All,buttonCopy = '',buttonProps = {},@@ -162,40 +164,43 @@ export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>(},ref): JSX.Element {- const { currentTeamId } = useValues(teamLogic)- const logic = entityFilterLogic({- teamId: currentTeamId,- setFilters,- filters,+ const logicProps = {+ series,+ onChange,typeKey,- addFilterDefaultOptions,+ newSeriesDefaults,dataWarehousePopoverFields,- })+ dataWarehouseNodeKind,+ }+ const logic = entityFilterLogic(logicProps)const { reportFunnelStepReordered } = useActions(eventUsageLogic)- const { localFilters } = useValues(logic)- const { addFilter, setLocalFilters, showModal } = useActions(logic)+ const { localSeries } = useValues(logic)+ const { addSeries, setSeries } = useActions(logic)- // No way around this. Somehow the ordering of the logic calling each other causes stale "localFilters"- // to be shown on the /funnels page, even if we try to use a selector with props to hydrate it+ // No way around this. Somehow the ordering of the logic calling each other causes stale+ // series to be shown on the /funnels page, even if we try to use a selector with props+ // to hydrate ituseEffect(() => {- setLocalFilters(filters)- }, [filters]) // oxlint-disable-line react-hooks/exhaustive-deps+ setSeries(series)+ }, [series]) // oxlint-disable-line react-hooks/exhaustive-depsfunction onSortEnd({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }): void {- function move(arr: LocalFilter[], from: number, to: number): LocalFilter[] {+ function move(arr: LocalSeries[], from: number, to: number): LocalSeries[] {const clone = [...arr]Array.prototype.splice.call(clone, to, 0, Array.prototype.splice.call(clone, from, 1)[0])- return clone.map((child, order) => ({ ...child, order }))+ return clone}- setFilters(toFilters(move(localFilters, oldIndex, newIndex)))+ onChange(move(localSeries, oldIndex, newIndex).map(({ node }) => node))if (oldIndex !== newIndex) {reportFunnelStepReordered()}}const singleFilter = entitiesLimit === 1- const canAccessEventsCombination = filters.insight === InsightType.TRENDS || filters.insight === InsightType.FUNNELS+ const canAccessEventsCombination = insightType === InsightType.TRENDS || insightType === InsightType.FUNNELS+ // A filter object with no `insight` reads as trends, so an absent insight type does too.+ const isTrendsInsight = insightType === InsightType.TRENDS || insightType === undefinedconst commonProps = {logic,@@ -203,10 +208,8 @@ export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>(seriesIndicatorType,mathAvailability,customRowSuffix,- hasBreakdown: !!filters.breakdown,- trendsDisplayCategory: isTrendsFilter(filters)- ? DISPLAY_TYPES_TO_CATEGORY[filters.display || ChartDisplayType.ActionsLineGraph]- : null,+ hasBreakdown,+ trendsDisplayCategory,actionsTaxonomicGroupTypes,propertiesTaxonomicGroupTypes,propertyFiltersPopover,@@ -217,12 +220,13 @@ export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>(hideRename,hideDuplicate,showCombine: canAccessEventsCombination,- insightType: filters.insight,- onRenameClick: showModal,+ insightType,+ onRenameClick: logic.actions.showModal,sortable,showNumericalPropsOnly,allowedMathTypes,dataWarehousePopoverFields,+ dataWarehouseNodeKind,filtersLeftPadding,addFilterDocLink,excludedProperties,@@ -230,13 +234,13 @@ export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>(allowNonCapturedEvents,hogQLGlobals,operatorAllowlist,- inlineEventsDocLink: isTrendsFilter(filters)+ inlineEventsDocLink: isTrendsInsight? 'https://posthog.com/docs/product-analytics/trends/overview#combine-events-inline': 'https://posthog.com/docs/product-analytics/funnels#combine-events-inline',}- const reachedLimit: boolean = Boolean(entitiesLimit && localFilters.length >= entitiesLimit)- const sortedItemIds = localFilters.map((i) => i.uuid)+ const reachedLimit: boolean = Boolean(entitiesLimit && localSeries.length >= entitiesLimit)+ const sortedItemIds = localSeries.map((i) => i.uuid)return (<div@@ -246,11 +250,11 @@ export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>(ref={ref}>{!hideRename && !readOnly && (- <BindLogic logic={entityFilterLogic} props={{ setFilters, filters, typeKey, addFilterDefaultOptions }}>- <RenameModal view={filters.insight} typeKey={typeKey} />+ <BindLogic logic={entityFilterLogic} props={logicProps}>+ <RenameModal view={insightType} typeKey={typeKey} /></BindLogic>)}- {localFilters ? (+ {localSeries ? (<ul><DndContextonDragEnd={({ active, over }) => {@@ -269,14 +273,15 @@ export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>(items={sortedItemIds}strategy={verticalListSortingStrategy}>- {localFilters.map((filter, index) =>- canAccessEventsCombination && filter.type === EntityTypes.GROUPS ? (+ {localSeries.map(({ uuid, node }, index) =>+ canAccessEventsCombination && isGroupSeriesNode(node) ? (<ActionFilterGroup- key={filter.uuid}- filter={filter}+ key={uuid}+ node={node}+ uuid={uuid}index={index}typeKey={typeKey}- filterCount={localFilters.length}+ filterCount={localSeries.length}sortable={sortable}showSeriesIndicator={showSeriesIndicator}seriesIndicatorType={seriesIndicatorType}@@ -284,32 +289,33 @@ export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>(readOnly={readOnly}hideDeleteBtn={typeof hideDeleteBtn === 'function'- ? hideDeleteBtn(filter, index)+ ? hideDeleteBtn(node, index): hideDeleteBtn}- hasBreakdown={!!filters.breakdown}+ hasBreakdown={hasBreakdown}mathAvailability={mathAvailability}- groupTitle={filter.custom_name || 'Any of the events below'}+ groupTitle={node.custom_name || 'Any of the events below'}actionsTaxonomicGroupTypes={actionsTaxonomicGroupTypes}dataWarehousePopoverFields={dataWarehousePopoverFields}excludedProperties={excludedProperties}includeHiddenEvents={includeHiddenEvents}- insightType={filters.insight}+ insightType={insightType}definitionPopoverRenderer={definitionPopoverRenderer}/>) : (<ActionFilterRow- key={filter.uuid}+ key={uuid}typeKey={typeKey}- filter={filter}+ node={node}+ uuid={uuid}index={index}- filterCount={localFilters.length}+ filterCount={localSeries.length}showNestedArrow={showNestedArrow}singleFilter={singleFilter}hideFilter={hideFilter || readOnly}hideDeleteBtn={typeof hideDeleteBtn === 'function'- ? hideDeleteBtn(filter, index)+ ? hideDeleteBtn(node, index): hideDeleteBtn}definitionPopoverRenderer={definitionPopoverRenderer}@@ -325,7 +331,7 @@ export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>(<div className="ActionFilter-footer"><LemonButtontype={buttonType}- onClick={() => addFilter()}+ onClick={() => addSeries()}data-attr="add-action-event-button"icon={<IconPlusSmall />}size="small"@@ -335,7 +341,7 @@ export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>({!reachedLimit? buttonCopy || 'Action or event': `Reached limit of ${entitiesLimit} ${- filters.insight === InsightType.FUNNELS ? 'steps' : 'series'+ insightType === InsightType.FUNNELS ? 'steps' : 'series'}`}</LemonButton>{customFooter}@@ -344,3 +350,44 @@ export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>(</div>)})++export interface ActionFilterProps extends Omit<+ SeriesActionFilterProps,+ 'series' | 'onChange' | 'insightType' | 'hasBreakdown' | 'trendsDisplayCategory' | 'newSeriesDefaults'+> {+ setFilters: (filters: FilterType) => void+ filters: FilterType+ addFilterDefaultOptions?: Record<string, any>+}++/**+ * The legacy entity filter shape, for the surfaces that persist it on a backend or schema+ * contract. Everything else renders `SeriesActionFilter` and keeps its query nodes.+ */+export const ActionFilter = React.forwardRef<HTMLDivElement, ActionFilterProps>(function ActionFilter(+ { setFilters, filters, addFilterDefaultOptions, dataWarehouseNodeKind, ...rest },+ ref+): JSX.Element {+ const series = useMemo(+ () => legacyFiltersToSeries(filters, dataWarehouseNodeKind),+ [filters, dataWarehouseNodeKind]+ )++ return (+ <SeriesActionFilter+ {...rest}+ ref={ref}+ series={series}+ onChange={(nextSeries) => setFilters(seriesToLegacyFilters(nextSeries))}+ dataWarehouseNodeKind={dataWarehouseNodeKind}+ newSeriesDefaults={addFilterDefaultOptions}+ insightType={filters.insight}+ hasBreakdown={!!filters.breakdown}+ trendsDisplayCategory={+ isTrendsFilter(filters)+ ? DISPLAY_TYPES_TO_CATEGORY[filters.display || ChartDisplayType.ActionsLineGraph]+ : null+ }+ />+ )+})diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.test.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.test.tsindex 9947074452ea..657cb822d438 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.test.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.test.ts@@ -1,17 +1,39 @@import { expectLogic } from 'kea-test-utils'import * as libUtils from 'lib/utils/dom'-import {- entityFilterLogic,- singleFilterToGroupFilter,- splitGroupFilterToLocalFilters,- toLocalFilters,-} from 'scenes/insights/filters/ActionFilter/entityFilterLogic'+import { entityFilterLogic, seriesNodeToGroupNode } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'import { useMocks } from '~/mocks/jest'+import { AnyEntityNode, GroupNode, NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { EntityTypes, FilterLogicalOperator, FilterType } from '~/types'+import { legacyFiltersToSeries } from '../legacyFilters'+import { SeriesNode } from '../seriesNode'+import { actionFilterGroupLogic } from './actionFilterGroupLogic'++const eventNode = (event: string, extra: Record<string, any> = {}): AnyEntityNode =>+ ({ kind: NodeKind.EventsNode, event, name: event, ...extra }) as AnyEntityNode++const groupNode = (nodes: AnyEntityNode[], extra: Record<string, any> = {}): GroupNode =>+ ({+ kind: NodeKind.GroupNode,+ name: nodes.map((n) => n.name).join(', '),+ operator: FilterLogicalOperator.Or,+ nodes,+ ...extra,+ }) as GroupNode++/** Mounts the editor on a fixed series, with deterministic row uuids. */+const mountLogic = (series: SeriesNode[], typeKey: string): ReturnType<typeof entityFilterLogic.build> => {+ let uuidCounter = 0+ ;(libUtils as any).uuid = jest.fn(() => `uuid-${uuidCounter++}`)++ const logic = entityFilterLogic({ onChange: jest.fn(), series, typeKey })+ logic.mount()+ return logic+}+describe('ActionFilterGroup - Combining and Splitting Events', () => {beforeEach(() => {;(libUtils as any).uuid = jest.fn().mockReturnValue('test-uuid')@@ -28,528 +50,243 @@ describe('ActionFilterGroup - Combining and Splitting Events', () => {initKeaTests()})- describe('singleFilterToGroupFilter', () => {- it('converts a single event filter to a group filter', () => {- const eventFilter = {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- uuid: 'uuid-1',- }-- const groupFilter = singleFilterToGroupFilter(eventFilter)-- expect(groupFilter).toMatchObject({- id: null,- type: EntityTypes.GROUPS,+ describe('seriesNodeToGroupNode', () => {+ it('converts a single event node to a group node', () => {+ const node = eventNode('$pageview')++ const group = seriesNodeToGroupNode(node)++ expect(group).toMatchObject({+ kind: NodeKind.GroupNode,operator: FilterLogicalOperator.Or,- order: 0,- uuid: 'test-uuid',})- expect(groupFilter.nestedFilters).not.toBeUndefined()- expect(groupFilter.nestedFilters!).toHaveLength(1)- expect(groupFilter.nestedFilters![0]).toEqual(eventFilter)+ expect(group.nodes).toHaveLength(1)+ expect(group.nodes[0]).toEqual(node)})it('preserves math properties at group level', () => {- const eventFilter = {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- math: 'dau',- math_property: 'some_prop',- uuid: 'uuid-1',- }-- const groupFilter = singleFilterToGroupFilter(eventFilter)+ const group = seriesNodeToGroupNode(eventNode('$pageview', { math: 'dau', math_property: 'some_prop' }))- expect(groupFilter).toMatchObject({+ expect(group).toMatchObject({math: 'dau',math_property: 'some_prop',})})- it('handles action filters', () => {- const actionFilter = {- id: '123',- type: EntityTypes.ACTIONS,- name: 'User Signup',- order: 0,- uuid: 'uuid-1',- }+ it('handles action nodes', () => {+ const node = { kind: NodeKind.ActionsNode, id: 123, name: 'User Signup' } as AnyEntityNode- const groupFilter = singleFilterToGroupFilter(actionFilter)+ const group = seriesNodeToGroupNode(node)- expect(groupFilter.type).toBe(EntityTypes.GROUPS)- expect(groupFilter.nestedFilters).toContainEqual(actionFilter)+ expect(group.kind).toBe(NodeKind.GroupNode)+ expect(group.nodes).toContainEqual(node)})- })- describe('splitGroupFilterToLocalFilters', () => {- it('expands a group filter with two events back to individual filters', () => {- const pageviewFilter = {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- uuid: 'uuid-1',- }-- const exceptionFilter = {- id: '$exception',- type: EntityTypes.EVENTS,- name: '$exception',- order: 1,- uuid: 'uuid-2',- }-- const groupFilter = {- id: null,- type: EntityTypes.GROUPS,- name: 'group',- order: 0,- operator: FilterLogicalOperator.Or,- uuid: 'group-uuid',- nestedFilters: [pageviewFilter, exceptionFilter],- }+ it('defaults to OR operator when creating group', () => {+ expect(seriesNodeToGroupNode(eventNode('$pageview')).operator).toBe(FilterLogicalOperator.Or)+ })- const split = splitGroupFilterToLocalFilters(groupFilter, 0)+ it('does not carry custom_name from the child', () => {+ const group = seriesNodeToGroupNode(eventNode('$pageview', { custom_name: 'My renamed event' }))- expect(split).toHaveLength(2)- expect(split[0]).toEqual(- expect.objectContaining({- id: '$pageview',- order: 0,- })- )- expect(split[1]).toEqual(- expect.objectContaining({- id: '$exception',- order: 1,- })- )+ expect(group.custom_name).toBeUndefined()+ expect(group.kind).toBe(NodeKind.GroupNode)+ // the child retains its custom_name+ expect(group.nodes[0].custom_name).toBe('My renamed event')})+ })- it('maintains correct ordering when splitting', () => {- const filter1 = {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- uuid: 'uuid-1',- }-- const filter2 = {- id: '$exception',- type: EntityTypes.EVENTS,- name: '$exception',- order: 1,- uuid: 'uuid-2',- }-- const filter3 = {- id: '$pageleave',- type: EntityTypes.EVENTS,- name: '$pageleave',- order: 2,- uuid: 'uuid-3',- }-- const groupFilter = {- id: null,- type: EntityTypes.GROUPS,- name: 'group',- order: 0,- operator: FilterLogicalOperator.Or,- uuid: 'group-uuid',- nestedFilters: [filter1, filter2, filter3],- }+ describe('splitGroup', () => {+ it('expands a group with two events back to individual series', () => {+ const logic = mountLogic([groupNode([eventNode('$pageview'), eventNode('$exception')])], 'split_two')- const split = splitGroupFilterToLocalFilters(groupFilter, 5)+ logic.actions.splitGroup(0)- expect(split).toHaveLength(3)- expect(split[0].order).toBe(5)- expect(split[1].order).toBe(6)- expect(split[2].order).toBe(7)+ expect(logic.values.series).toEqual([eventNode('$pageview'), eventNode('$exception')])+ logic.unmount()})- it('handles groups with mix of events and actions', () => {- const eventFilter = {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- uuid: 'uuid-1',- }-- const actionFilter = {- id: '123',- type: EntityTypes.ACTIONS,- name: 'User Signup',- order: 1,- uuid: 'uuid-2',- }-- const groupFilter = {- id: null,- type: EntityTypes.GROUPS,- name: 'group',- order: 0,- operator: FilterLogicalOperator.Or,- uuid: 'group-uuid',- nestedFilters: [eventFilter, actionFilter],- }+ it('maintains correct ordering when splitting into the middle of the list', () => {+ const logic = mountLogic(+ [+ eventNode('$before'),+ groupNode([eventNode('$pageview'), eventNode('$exception'), eventNode('$pageleave')]),+ eventNode('$after'),+ ],+ 'split_ordering'+ )- const split = splitGroupFilterToLocalFilters(groupFilter, 0)+ logic.actions.splitGroup(1)- expect(split).toHaveLength(2)- expect(split[0].type).toBe(EntityTypes.EVENTS)- expect(split[1].type).toBe(EntityTypes.ACTIONS)+ expect(logic.values.series.map((node: any) => node.event)).toEqual([+ '$before',+ '$pageview',+ '$exception',+ '$pageleave',+ '$after',+ ])+ logic.unmount()})- it('preserves properties when splitting', () => {- const filter = {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- uuid: 'uuid-1',- properties: [- {- type: 'event',- key: 'page_location',- value: '/product',- operator: 'exact',- },+ it('handles groups with a mix of events and actions', () => {+ const logic = mountLogic(+ [+ groupNode([+ eventNode('$pageview'),+ { kind: NodeKind.ActionsNode, id: 123, name: 'User Signup' } as AnyEntityNode,+ ]),],- }-- const groupFilter = {- id: null,- type: EntityTypes.GROUPS,- name: 'group',- order: 0,- operator: FilterLogicalOperator.Or,- uuid: 'group-uuid',- nestedFilters: [filter],- }+ 'split_mixed'+ )- const split = splitGroupFilterToLocalFilters(groupFilter, 0)+ logic.actions.splitGroup(0)- expect(split[0].properties).toEqual(filter.properties)+ expect(logic.values.series.map((node) => node.kind)).toEqual([NodeKind.EventsNode, NodeKind.ActionsNode])+ logic.unmount()})- })- describe('single and group filters conversion', () => {- it('converts single filter to group and back to get same structure', () => {- const originalFilter = {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- uuid: 'uuid-1',- }+ it('preserves properties when splitting', () => {+ const properties = [{ type: 'event', key: 'page_location', value: '/product', operator: 'exact' }]+ const logic = mountLogic([groupNode([eventNode('$pageview', { properties })])], 'split_properties')- // Convert to group- const groupFilter = singleFilterToGroupFilter(originalFilter)+ logic.actions.splitGroup(0)- // Split back- const split = splitGroupFilterToLocalFilters(groupFilter, 0)+ expect(logic.values.series[0].properties).toEqual(properties)+ logic.unmount()+ })- expect(split).toHaveLength(1)- expect(split[0]).toEqual(- expect.objectContaining({- id: originalFilter.id,- type: originalFilter.type,- name: originalFilter.name,- })+ it('does not leak the group custom_name to its children', () => {+ const logic = mountLogic(+ [+ groupNode([eventNode('$pageview'), eventNode('$exception')], {+ custom_name: 'My conversion events',+ }),+ ],+ 'split_custom_name')++ logic.actions.splitGroup(0)++ expect(logic.values.series).toHaveLength(2)+ expect(logic.values.series[0].custom_name).toBeUndefined()+ expect(logic.values.series[1].custom_name).toBeUndefined()+ logic.unmount()})- it('handles multiple filters round-trip', () => {- const filters = [- {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- uuid: 'uuid-1',- },- {- id: 'signup-action',- type: EntityTypes.ACTIONS,- name: 'User Signup',- order: 1,- uuid: 'uuid-2',- },- ]+ it('combining and splitting round-trips to the same series', () => {+ const original = eventNode('$pageview')+ const logic = mountLogic([original], 'round_trip')- // Combine first filter to group- const groupFilter = singleFilterToGroupFilter(filters[0])+ logic.actions.convertToGroup(0)+ expect(logic.values.series[0].kind).toBe(NodeKind.GroupNode)- // Split back- const split = splitGroupFilterToLocalFilters(groupFilter, 0)+ logic.actions.splitGroup(0)- expect(split).toHaveLength(1)- expect(split[0].id).toBe('$pageview')+ expect(logic.values.series).toHaveLength(1)+ expect(logic.values.series[0]).toEqual(original)+ logic.unmount()})- })- describe('OR vs AND operators', () => {- it('defaults to OR operator when creating group', () => {- const filter = {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- uuid: 'uuid-1',- }+ it('handles an empty group', () => {+ const logic = mountLogic([groupNode([])], 'split_empty')- const groupFilter = singleFilterToGroupFilter(filter)+ logic.actions.splitGroup(0)- expect(groupFilter.operator).toBe(FilterLogicalOperator.Or)+ expect(logic.values.series).toHaveLength(0)+ logic.unmount()})- })- describe('edge cases', () => {- it('handles empty group filter', () => {- const groupFilter = {- id: null,- type: EntityTypes.GROUPS,- name: 'empty_group',- order: 0,- operator: FilterLogicalOperator.Or,- uuid: 'group-uuid',- nestedFilters: [],- }+ it('handles a single-item group', () => {+ const logic = mountLogic([groupNode([eventNode('$pageview')])], 'split_single')- const split = splitGroupFilterToLocalFilters(groupFilter, 0)+ logic.actions.splitGroup(0)- expect(split).toHaveLength(0)+ expect(logic.values.series).toEqual([eventNode('$pageview')])+ logic.unmount()})- it('handles single-item group filter', () => {- const filter = {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- uuid: 'uuid-1',- }-- const groupFilter = {- id: null,- type: EntityTypes.GROUPS,- name: 'single',- order: 0,- operator: FilterLogicalOperator.Or,- uuid: 'group-uuid',- nestedFilters: [filter],- }+ it('handles a large group with many events', () => {+ const nodes = Array.from({ length: 10 }, (_, i) => eventNode(`event-${i}`))+ const logic = mountLogic([groupNode(nodes)], 'split_large')- const split = splitGroupFilterToLocalFilters(groupFilter, 0)+ logic.actions.splitGroup(0)- expect(split).toHaveLength(1)- expect(split[0]).toEqual(- expect.objectContaining({- id: '$pageview',- })+ expect(logic.values.series).toHaveLength(10)+ expect(logic.values.series.map((node: any) => node.event)).toEqual(+ Array.from({ length: 10 }, (_, i) => `event-${i}`))+ logic.unmount()})- it('handles large group with many events', () => {- const filters = Array.from({ length: 10 }, (_, i) => ({- id: `event-${i}`,- type: EntityTypes.EVENTS,- name: `Event ${i}`,- order: i,- uuid: `uuid-${i}`,- }))-- const groupFilter = {- id: null,- type: EntityTypes.GROUPS,- name: 'large_group',- order: 0,- operator: FilterLogicalOperator.Or,- uuid: 'group-uuid',- nestedFilters: filters,- }+ it('leaves a non-group series alone', () => {+ const logic = mountLogic([eventNode('$pageview')], 'split_non_group')- const split = splitGroupFilterToLocalFilters(groupFilter, 0)+ logic.actions.splitGroup(0)- expect(split).toHaveLength(10)- expect(split.map((f) => f.id)).toEqual(Array.from({ length: 10 }, (_, i) => `event-${i}`))+ expect(logic.values.series).toEqual([eventNode('$pageview')])+ logic.unmount()})})- describe('duplicating a group filter', () => {- const groupFilter = {- id: null,- type: EntityTypes.GROUPS,- name: 'group',- order: 0,- operator: FilterLogicalOperator.Or,- nestedFilters: [- { id: '$pageview', type: EntityTypes.EVENTS, name: '$pageview', order: 0 },- { id: '$exception', type: EntityTypes.EVENTS, name: '$exception', order: 1 },- ],- }-- const mountLogic = (- filters: Partial<FilterType>,- typeKey: string- ): ReturnType<typeof entityFilterLogic.build> => {- let uuidCounter = 0- ;(libUtils as any).uuid = jest.fn(() => `uuid-${uuidCounter++}`)-- const logic = entityFilterLogic({- setFilters: jest.fn(),- filters: filters as FilterType,- typeKey,- })- logic.mount()- return logic- }+ describe('duplicating a group', () => {+ const group = (): GroupNode => groupNode([eventNode('$pageview'), eventNode('$exception')])it('duplicates a lone group into two identical groups', async () => {- const logic = mountLogic({ groups: [groupFilter] }, 'duplicate_single_group')- const original = logic.values.localFilters[0]+ const logic = mountLogic([group()], 'duplicate_single_group')+ const original = logic.values.localSeries[0]await expectLogic(logic, () => {- logic.actions.duplicateFilter(original)- }).toDispatchActions(['duplicateFilter', 'setFilters'])+ logic.actions.duplicateSeries(0)+ }).toDispatchActions(['duplicateSeries', 'setLocalSeries'])- const local = logic.values.localFilters+ const local = logic.values.localSeriesexpect(local).toHaveLength(2)- expect(local.map((f) => ({ type: f.type, order: f.order }))).toEqual([- { type: EntityTypes.GROUPS, order: 0 },- { type: EntityTypes.GROUPS, order: 1 },- ])+ expect(local.map((l) => l.node.kind)).toEqual([NodeKind.GroupNode, NodeKind.GroupNode])expect(local[1].uuid).not.toBe(original.uuid)- expect(local[1].nestedFilters).toEqual(original.nestedFilters)+ expect((local[1].node as GroupNode).nodes).toEqual((original.node as GroupNode).nodes)logic.unmount()})it('inserts the duplicate directly after the group and shifts trailing events', async () => {- const logic = mountLogic(- {- groups: [groupFilter],- events: [{ id: '$pageleave', type: EntityTypes.EVENTS, name: '$pageleave', order: 1 }],- },- 'duplicate_group_with_event'- )- const original = logic.values.localFilters[0]+ const logic = mountLogic([group(), eventNode('$pageleave')], 'duplicate_group_with_event')+ const original = logic.values.localSeries[0]await expectLogic(logic, () => {- logic.actions.duplicateFilter(original)- }).toDispatchActions(['duplicateFilter', 'setFilters'])+ logic.actions.duplicateSeries(0)+ }).toDispatchActions(['duplicateSeries', 'setLocalSeries'])- const local = logic.values.localFilters+ const local = logic.values.localSeriesexpect(local).toHaveLength(3)- expect(local.map((f) => ({ type: f.type, order: f.order }))).toEqual([- { type: EntityTypes.GROUPS, order: 0 },- { type: EntityTypes.GROUPS, order: 1 },- { type: EntityTypes.EVENTS, order: 2 },- ])+ expect(local.map((l) => l.node.kind)).toEqual([NodeKind.GroupNode, NodeKind.GroupNode, NodeKind.EventsNode])expect(local[1].uuid).not.toBe(original.uuid)- expect(local[1].nestedFilters).toEqual(original.nestedFilters)+ expect((local[1].node as GroupNode).nodes).toEqual((original.node as GroupNode).nodes)logic.unmount()})})describe('group custom_name handling', () => {- it('splitting a group with custom_name does not leak custom_name to children', () => {- const groupFilter = {- id: null,- type: EntityTypes.GROUPS,- name: '$pageview, $exception',- custom_name: 'My conversion events',- order: 0,- operator: FilterLogicalOperator.Or,- uuid: 'group-uuid',- nestedFilters: [- { id: '$pageview', type: EntityTypes.EVENTS, name: '$pageview', order: 0, uuid: 'uuid-1' },- { id: '$exception', type: EntityTypes.EVENTS, name: '$exception', order: 1, uuid: 'uuid-2' },- ],- }-- const split = splitGroupFilterToLocalFilters(groupFilter, 0)-- expect(split).toHaveLength(2)- expect(split[0].custom_name).toBeUndefined()- expect(split[1].custom_name).toBeUndefined()- })-- it('combining a filter into a group does not carry custom_name from the child', () => {- const eventFilter = {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- custom_name: 'My renamed event',- order: 0,- uuid: 'uuid-1',- }-- const groupFilter = singleFilterToGroupFilter(eventFilter)-- expect(groupFilter.custom_name).toBeUndefined()- expect(groupFilter.type).toBe(EntityTypes.GROUPS)- // the child retains its custom_name- expect(groupFilter.nestedFilters![0].custom_name).toBe('My renamed event')- })-it('preserves custom_name through rename via entityFilterLogic', async () => {- let uuidCounter = 0- ;(libUtils as any).uuid = jest.fn(() => `uuid-${uuidCounter++}`)-- const logic = entityFilterLogic({- setFilters: jest.fn(),- filters: {- groups: [- {- id: null,- type: EntityTypes.GROUPS,- name: '$pageview',- order: 0,- operator: FilterLogicalOperator.Or,- nestedFilters: [{ id: '$pageview', type: EntityTypes.EVENTS, name: '$pageview', order: 0 }],- },- ],- } as FilterType,- typeKey: 'rename_group_test',- })- logic.mount()+ const logic = mountLogic([groupNode([eventNode('$pageview')])], 'rename_group_test')- const groupFilter = logic.values.localFilters[0]- logic.actions.selectFilter(groupFilter)+ logic.actions.selectSeries(0, logic.values.series[0], logic.values.localSeries[0].uuid)await expectLogic(logic, () => {- logic.actions.renameFilter('Revenue events')- }).toDispatchActions(['renameFilter', 'updateFilter', 'setFilters'])+ logic.actions.renameSeries('Revenue events')+ }).toDispatchActions(['renameSeries', 'setLocalSeries'])- expect(logic.values.localFilters[0].custom_name).toBe('Revenue events')- expect(logic.values.localFilters[0].type).toBe(EntityTypes.GROUPS)+ expect(logic.values.series[0].custom_name).toBe('Revenue events')+ expect(logic.values.series[0].kind).toBe(NodeKind.GroupNode)logic.unmount()})})- describe('toLocalFilters with groups', () => {- it('includes group filters in local filters', () => {- const filterType = {- events: [- {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- },- ],+ describe('legacyFiltersToSeries with groups', () => {+ it('includes group filters in the series', () => {+ const series = legacyFiltersToSeries({+ events: [{ id: '$pageview', type: EntityTypes.EVENTS, name: '$pageview', order: 0 }],groups: [{id: null,@@ -557,48 +294,26 @@ describe('ActionFilterGroup - Combining and Splitting Events', () => {name: 'group',order: 1,operator: FilterLogicalOperator.Or,- nestedFilters: [- {- id: '$exception',- type: EntityTypes.EVENTS,- name: '$exception',- order: 0,- },- ],+ nestedFilters: [{ id: '$exception', type: EntityTypes.EVENTS, name: '$exception', order: 0 }],},],- }-- const localFilters = toLocalFilters(filterType)+ } as FilterType)- expect(localFilters).toHaveLength(2)- expect(localFilters[0]).toEqual(+ expect(series).toHaveLength(2)+ expect(series[0]).toEqual(expect.objectContaining({ kind: NodeKind.EventsNode, event: '$pageview' }))+ expect(series[1]).toEqual(expect.objectContaining({- id: '$pageview',- })- )- expect(localFilters[1]).toEqual(- expect.objectContaining({- type: EntityTypes.GROUPS,+ kind: NodeKind.GroupNode,+ nodes: [expect.objectContaining({ kind: NodeKind.EventsNode, event: '$exception' })],}))})it('maintains order across mixed filters and groups', () => {- const filterType = {+ const series = legacyFiltersToSeries({events: [- {- id: '$pageview',- type: EntityTypes.EVENTS,- name: '$pageview',- order: 0,- },- {- id: '$pageleave',- type: EntityTypes.EVENTS,- name: '$pageleave',- order: 2,- },+ { id: '$pageview', type: EntityTypes.EVENTS, name: '$pageview', order: 0 },+ { id: '$pageleave', type: EntityTypes.EVENTS, name: '$pageleave', order: 2 },],groups: [{@@ -607,21 +322,56 @@ describe('ActionFilterGroup - Combining and Splitting Events', () => {name: 'group',order: 1,operator: FilterLogicalOperator.Or,- nestedFilters: [- {- id: '$exception',- type: EntityTypes.EVENTS,- name: '$exception',- order: 0,- },- ],+ nestedFilters: [{ id: '$exception', type: EntityTypes.EVENTS, name: '$exception', order: 0 }],},],- }+ } as FilterType)++ expect(series.map((node) => node.kind)).toEqual([+ NodeKind.EventsNode,+ NodeKind.GroupNode,+ NodeKind.EventsNode,+ ])+ })+ })++ describe('nested row identity', () => {+ const mountGroupLogic = (+ nodes: AnyEntityNode[],+ typeKey: string+ ): ReturnType<typeof actionFilterGroupLogic.build> => {+ const parent = mountLogic([groupNode(nodes)], typeKey)+ const logic = actionFilterGroupLogic({+ filterUuid: parent.values.localSeries[0].uuid,+ typeKey,+ groupIndex: 0,+ })+ logic.mount()+ return logic+ }++ it('keeps each surviving nested row on its own uuid when one is removed', () => {+ const logic = mountGroupLogic(+ [eventNode('$pageview'), eventNode('$autocapture'), eventNode('$rageclick')],+ 'nested_removal'+ )+ const originalUuids = logic.values.nestedRows.map(({ uuid }) => uuid)+ expect(originalUuids).toHaveLength(3)++ logic.actions.removeNestedSeries(0)++ // Keying by index would move each surviving row's open property panel onto the next event.+ expect(logic.values.nestedRows.map(({ uuid }) => uuid)).toEqual(originalUuids.slice(1))+ })++ it('keeps every nested row on its uuid when one of them switches event', () => {+ const logic = mountGroupLogic([eventNode('$pageview'), eventNode('$autocapture')], 'nested_update')+ const originalUuids = logic.values.nestedRows.map(({ uuid }) => uuid)- const localFilters = toLocalFilters(filterType)+ logic.actions.updateNestedSeries(1, { event: '$rageclick', name: '$rageclick' } as Partial<AnyEntityNode>)- expect(localFilters.map((f) => f.order)).toEqual([0, 1, 2])+ expect(logic.values.nestedRows.map(({ uuid }) => uuid)).toEqual(originalUuids)+ expect(logic.values.nestedNodes[1]).toEqual(expect.objectContaining({ event: '$rageclick' }))})})})diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.tsxindex f8b18800968d..1e8ac711a47c 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/ActionFilterGroup.tsx@@ -25,19 +25,23 @@ import { SortableDragIcon } from 'lib/lemon-ui/icons'import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'import { teamLogic } from 'scenes/teamLogic'-import { BaseMathType, EntityTypes, InsightType } from '~/types'+import { GroupNode, NodeKind } from '~/queries/schema/schema-general'+import { BaseMathType, InsightType } from '~/types'import { MathCategory, mathsLogic } from 'products/product_analytics/frontend/insights/trends/mathsLogic'-import { ActionFilterRow, MathSelector, taxonomicFilterGroupTypeToEntityType } from '../ActionFilterRow/ActionFilterRow'+import { ActionFilterRow, MathSelector } from '../ActionFilterRow/ActionFilterRow'+import { taxonomicGroupTypeToSeriesNodeKind } from '../ActionFilterRow/actionFilterRowUtils'import { getDefaultMathHogQLExpression } from '../ActionFilterRow/mathUtils'import { MathAvailability } from '../ActionFilterRow/types'-import { LocalFilter, entityFilterLogic } from '../entityFilterLogic'+import { entityFilterLogic } from '../entityFilterLogic'import { actionFilterGroupLogic } from './actionFilterGroupLogic'import { nestedFilterLogic } from './nestedFilterLogic'interface ActionFilterGroupProps {- filter: LocalFilter+ node: GroupNode+ /** Sidecar row identity, for the drag key and the group's own logic key. */+ uuid: stringindex: numbertypeKey: stringfilterCount: number@@ -61,7 +65,8 @@ interface ActionFilterGroupProps {}export function ActionFilterGroup({- filter,+ node,+ uuid,index,typeKey,filterCount,@@ -88,17 +93,17 @@ export function ActionFilterGroup({].filter((groupType) => groupType !== TaxonomicFilterGroupType.DataWarehouse)const { currentTeamId } = useValues(teamLogic)- const { removeLocalFilter, splitLocalFilter, duplicateFilter, showModal, selectFilter } = useActions(+ const { removeSeries, splitGroup, duplicateSeries, showModal, selectSeries } = useActions(entityFilterLogic({ typeKey }))const { mathDefinitions } = useValues(mathsLogic)- const { setNodeRef, attributes, transform, transition, listeners, isDragging } = useSortable({ id: filter.uuid })+ const { setNodeRef, attributes, transform, transition, listeners, isDragging } = useSortable({ id: uuid })- const groupLogic = actionFilterGroupLogic({ filterUuid: filter.uuid, typeKey, groupIndex: index })- const { nestedFilters, operator, isHogQLDropdownVisible, groupFilter } = useValues(groupLogic)+ const groupLogic = actionFilterGroupLogic({ filterUuid: uuid, typeKey, groupIndex: index })+ const { nestedNodes, nestedRows, operator, isHogQLDropdownVisible, groupNode } = useValues(groupLogic)const {- addNestedFilter,- updateNestedFilterProperties,+ addNestedSeries,+ updateNestedSeriesProperties,setMath,setMathProperty,setMathHogQL,@@ -106,15 +111,15 @@ export function ActionFilterGroup({} = useActions(groupLogic)const defaultMathHogQLExpression = getDefaultMathHogQLExpression(insightType)- const mathCategory = mathDefinitions[filter.math || BaseMathType.TotalCount]?.category+ const mathCategory = mathDefinitions[node.math || BaseMathType.TotalCount]?.categoryconst hasSecondaryMathDropdown =mathCategory === MathCategory.PropertyValue || mathCategory === MathCategory.HogQLExpressionconst showMath = mathAvailability !== MathAvailability.None && mathAvailability !== MathAvailability.FunnelsOnlyconst mathSelectorProps = {size: 'small' as const,- math: filter.math,- mathGroupTypeIndex: filter.math_group_type_index,+ math: node.math,+ mathGroupTypeIndex: node.math_group_type_index,index,onMathSelect: (_: number, math: any) => setMath(math, defaultMathHogQLExpression),disabled: disabled || readOnly,@@ -181,7 +186,7 @@ export function ActionFilterGroup({size: 'medium',icon: <IconUndo />,onClick: () => {- splitLocalFilter(index)+ splitGroup(index)posthog.capture('split_events', {insight_type: insightType,team_id: currentTeamId,@@ -198,7 +203,7 @@ export function ActionFilterGroup({size: 'medium',icon: <IconPencil />,onClick: () => {- selectFilter(groupFilter ?? null)+ selectSeries(index, groupNode ?? null, uuid)showModal()},'data-attr': `group-filter-rename-${index}`,@@ -208,9 +213,7 @@ export function ActionFilterGroup({size: 'medium',icon: <IconCopy />,onClick: () => {- if (groupFilter) {- duplicateFilter(groupFilter)- }+ duplicateSeries(index)},'data-attr': `group-filter-duplicate-${index}`,},@@ -219,7 +222,7 @@ export function ActionFilterGroup({size: 'medium',status: 'danger',icon: <IconTrash />,- onClick: () => removeLocalFilter({ index }),+ onClick: () => removeSeries(index),'data-attr': `group-filter-delete-${index}`,},],@@ -251,7 +254,7 @@ export function ActionFilterGroup({truncatesize="small"groupType={- filter.math_property_type ||+ (node.math_property_type as TaxonomicFilterGroupType) ||TaxonomicFilterGroupType.NumericalEventProperties}groupTypes={[@@ -261,9 +264,9 @@ export function ActionFilterGroup({TaxonomicFilterGroupType.PersonProperties,TaxonomicFilterGroupType.DataWarehousePersonProperties,]}- value={filter.math_property}+ value={node.math_property}onChange={setMathProperty}- eventNames={nestedFilters.map((v) => v.name).filter(Boolean) as string[]}+ eventNames={nestedNodes.map((v) => v.name).filter(Boolean) as string[]}data-attr="math-property-select"showNumericalPropsOnly={showNumericalPropsOnly}renderValue={(currentValue) => (@@ -272,7 +275,7 @@ export function ActionFilterGroup({currentValue === '$session_duration' ? (<>Calculate{' '}- {mathDefinitions[filter.math ?? '']?.name.toLowerCase()} of+ {mathDefinitions[node.math ?? '']?.name.toLowerCase()} ofthe session duration. This is based on the{' '}<code>$session_id</code> property associated with events.The duration is derived from the time difference between the@@ -282,10 +285,10 @@ export function ActionFilterGroup({) : (<>Calculate{' '}- {mathDefinitions[filter.math ?? '']?.name.toLowerCase()}{' '}- from property <code>{currentValue}</code>. Note that only- event occurrences where <code>{currentValue}</code> is set- with a numeric value will be taken into account.+ {mathDefinitions[node.math ?? '']?.name.toLowerCase()} from+ property <code>{currentValue}</code>. Note that only event+ occurrences where <code>{currentValue}</code> is set with a+ numeric value will be taken into account.</>)}@@ -311,7 +314,7 @@ export function ActionFilterGroup({// eslint-disable-next-line react/forbid-dom-props<div className="w-120" style={{ maxWidth: 'max(60vw, 20rem)' }}><HogQLEditor- value={filter.math_hogql || defaultMathHogQLExpression}+ value={node.math_hogql || defaultMathHogQLExpression}onChange={(currentValue) => {setMathHogQL(currentValue)setHogQLDropdownVisible(false)@@ -329,7 +332,7 @@ export function ActionFilterGroup({onClick={() => setHogQLDropdownVisible(!isHogQLDropdownVisible)}><code className="truncate">- {filter.math_hogql || defaultMathHogQLExpression}+ {node.math_hogql || defaultMathHogQLExpression}</code></LemonButton></LemonDropdown>@@ -341,26 +344,28 @@ export function ActionFilterGroup({{/* Events list */}<ul className="ActionFilterGroup--events-list flex flex-col px-4 py-2.5 bg-primary [&_.ActionFilterRow]:!border-0 [&_.ActionFilterRow]:!rounded-none [&_.ActionFilterRow]:!p-0">- {nestedFilters.map((eventFilter, eventIndex) => {+ {nestedRows.map(({ uuid: nestedUuid, node: nestedNode }, eventIndex) => {const nestedLogicInstance = nestedFilterLogic({- groupFilterUuid: filter.uuid,+ groupFilterUuid: uuid,+ nestedUuid,nestedIndex: eventIndex,typeKey,groupIndex: index,})return (- <div key={eventFilter.uuid || eventIndex}>+ <div key={nestedUuid}><ActionFilterRowlogic={nestedLogicInstance as any}- filter={eventFilter}- index={eventFilter.order}+ node={nestedNode}+ uuid={nestedUuid}+ index={eventIndex}typeKey={`group-${index}-${eventIndex}`}mathAvailability={MathAvailability.None}hideRenamehideDuplicate- hideDeleteBtn={nestedFilters.length <= 1 || readOnly}- filterCount={nestedFilters.length}+ hideDeleteBtn={nestedNodes.length <= 1 || readOnly}+ filterCount={nestedNodes.length}sortable={false}hasBreakdown={hasBreakdown}disabled={disabled || readOnly}@@ -375,7 +380,7 @@ export function ActionFilterGroup({includeHiddenEvents={includeHiddenEvents}definitionPopoverRenderer={definitionPopoverRenderer}/>- {eventIndex < nestedFilters.length - 1 && (+ {eventIndex < nestedNodes.length - 1 && (<div className="flex items-center gap-3 mx-0.5 my-2.5"><div className="flex-1 h-px bg-border-primary" /><span className="text-[11px] font-semibold text-tertiary uppercase tracking-wide">@@ -390,7 +395,7 @@ export function ActionFilterGroup({</ul>{/* Add event button */}- {!readOnly && nestedFilters.length < 10 && (+ {!readOnly && nestedNodes.length < 10 && (<div className="ActionFilterGroup--footer px-4 py-2.5 bg-primary"><TaxonomicPopoverdata-attr={`add-group-event-${index}`}@@ -402,9 +407,9 @@ export function ActionFilterGroup({onChange={(value, groupType, item) => {if (isQuickFilterItem(item)) {if (item.eventName) {- const newIndex = nestedFilters.length- addNestedFilter(item.eventName, item.eventName, EntityTypes.EVENTS)- updateNestedFilterProperties(newIndex, quickFilterToPropertyFilters(item))+ const newIndex = nestedNodes.length+ addNestedSeries(item.eventName, item.eventName, NodeKind.EventsNode)+ updateNestedSeriesProperties(newIndex, quickFilterToPropertyFilters(item))posthog.capture('add_event_to_group', {insight_type: insightType,team_id: currentTeamId,@@ -412,9 +417,9 @@ export function ActionFilterGroup({}return}- const entityType = taxonomicFilterGroupTypeToEntityType(groupType)- if (entityType && value) {- addNestedFilter(String(value), item?.name || String(value), entityType)+ const kind = taxonomicGroupTypeToSeriesNodeKind(groupType)+ if (kind !== NodeKind.GroupNode && value) {+ addNestedSeries(String(value), item?.name || String(value), kind)posthog.capture('add_event_to_group', {insight_type: insightType,team_id: currentTeamId,diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.tsindex bdcf6c3b197b..42c040830242 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/actionFilterGroupLogic.ts@@ -1,9 +1,11 @@import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { subscriptions } from 'kea-subscriptions'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { uuid } from 'lib/utils/dom'-import { AnyPropertyFilter, EntityType, EntityTypes, FilterLogicalOperator } from '~/types'+import { AnyEntityNode, GroupNode, NodeKind } from '~/queries/schema/schema-general'+import { AnyPropertyFilter, FilterLogicalOperator } from '~/types'import {MathCategory,@@ -12,8 +14,8 @@ import {} from 'products/product_analytics/frontend/insights/trends/mathsLogic'import type { MathDefinition } from 'products/product_analytics/frontend/insights/trends/mathsLogic'-import type { ActionFilter, AnyDataWarehouseFilter, EntityFilter } from '../../../../../types'-import { LocalFilter, entityFilterLogic } from '../entityFilterLogic'+import { LocalSeries, SeriesEntityUpdate, entityFilterLogic } from '../entityFilterLogic'+import { SeriesNode, isGroupSeriesNode, withLatestVersion } from '../seriesNode'export interface ActionFilterGroupLogicProps {filterUuid: string@@ -21,152 +23,68 @@ export interface ActionFilterGroupLogicProps {groupIndex: number}-/** Extract math properties from a filter for spreading */-function getMathProps(filter: LocalFilter): Record<string, any> {+/** Extract math properties from a node for spreading */+function getMathProps(node: SeriesNode): Record<string, any> {return {- ...(filter.math && { math: filter.math }),- ...(filter.math_property && { math_property: filter.math_property }),- ...(filter.math_property_type && { math_property_type: filter.math_property_type }),- ...(filter.math_hogql && { math_hogql: filter.math_hogql }),- ...(filter.math_group_type_index !== undefined && {- math_group_type_index: filter.math_group_type_index,+ ...(node.math && { math: node.math }),+ ...(node.math_property && { math_property: node.math_property }),+ ...(node.math_property_type && { math_property_type: node.math_property_type }),+ ...(node.math_hogql && { math_hogql: node.math_hogql }),+ ...(node.math_group_type_index !== undefined && {+ math_group_type_index: node.math_group_type_index,}),}}+/**+ * Rows pair with nodes by position: an edit leaves the list the same length, and a removal has+ * already dropped the removed row's uuid by the time the shortened list reaches here.+ */+function alignNestedRows(current: LocalSeries[], nodes: AnyEntityNode[]): LocalSeries[] {+ const rows = nodes.map((node, index) => ({ uuid: current[index]?.uuid ?? uuid(), node }))+ const unchanged =+ rows.length === current.length &&+ rows.every((row, index) => row.uuid === current[index].uuid && row.node === current[index].node)+ return unchanged ? current : rows+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface actionFilterGroupLogicValues {- localFilters: LocalFilter[] // entityFilterLogic+ localSeries: LocalSeries[] // entityFilterLogicmathDefinitions: Partial<Record<string, MathDefinition>> // mathsLogic- groupFilter: LocalFilter | undefined+ groupNode: GroupNode | undefinedisHogQLDropdownVisible: boolean- nestedFilters: LocalFilter[]+ nestedNodes: AnyEntityNode[]+ nestedRows: LocalSeries[]operator: FilterLogicalOperator}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface actionFilterGroupLogicActions {- updateParentFilter: (- filter: (ActionFilter | AnyDataWarehouseFilter | EntityFilter) & {- index: number- table_name?: string- [key: string]: any- }- ) =>- | {- custom_name?: string | null | undefined- id: number | string | null- index: number- name?: string | null | undefined- optionalInFunnel?: boolean | undefined- order?: number | undefined- table_name?: string | undefined- type?: EntityType | undefined- [key: string]: any- }- | {- custom_name?: string | null | undefined- days?: string[] | undefined- id: number | string | null- index: number- math?: string | undefined- math_group_type_index?: number | null | undefined- math_hogql?: string | null | undefined- math_property?: string | null | undefined- math_property_type?: TaxonomicFilterGroupType | null | undefined- name?: string | null | undefined- negation?: boolean | undefined- nestedFilters?: EntityFilter[] | null | undefined- operator?: FilterLogicalOperator | null | undefined- optionalInFunnel?: boolean | undefined- order?: number | undefined- properties?: AnyPropertyFilter[] | undefined- table_name?: string | undefined- type: EntityType- [key: string]: any- }- | {- aggregation_target_field: string- created_at_field: string- custom_name?: string | null | undefined- days?: string[] | undefined- id: number | string | null- index: number- math?: string | undefined- math_group_type_index?: number | null | undefined- math_hogql?: string | null | undefined- math_property?: string | null | undefined- math_property_type?: TaxonomicFilterGroupType | null | undefined- name?: string | null | undefined- negation?: boolean | undefined- nestedFilters?: EntityFilter[] | null | undefined- operator?: FilterLogicalOperator | null | undefined- optionalInFunnel?: boolean | undefined- order?: number | undefined- properties?: AnyPropertyFilter[] | undefined- table_name: string- timestamp_field: string- type: EntityType- [key: string]: any- }- | {- aggregation_target_field: string- custom_name?: string | null | undefined- days?: string[] | undefined- id: number | string | null- id_field: string- index: number- math?: string | undefined- math_group_type_index?: number | null | undefined- math_hogql?: string | null | undefined- math_property?: string | null | undefined- math_property_type?: TaxonomicFilterGroupType | null | undefined- name?: string | null | undefined- negation?: boolean | undefined- nestedFilters?: EntityFilter[] | null | undefined- operator?: FilterLogicalOperator | null | undefined- optionalInFunnel?: boolean | undefined- order?: number | undefined- properties?: AnyPropertyFilter[] | undefined- table_name: string- timestamp_field: string- type: EntityType- [key: string]: any- }- | {- custom_name?: string | null | undefined- days?: string[] | undefined- distinct_id_field: string- id: number | string | null- id_field: string- index: number- math?: string | undefined- math_group_type_index?: number | null | undefined- math_hogql?: string | null | undefined- math_property?: string | null | undefined- math_property_type?: TaxonomicFilterGroupType | null | undefined- name?: string | null | undefined- negation?: boolean | undefined- nestedFilters?: EntityFilter[] | null | undefined- operator?: FilterLogicalOperator | null | undefined- optionalInFunnel?: boolean | undefined- order?: number | undefined- properties?: AnyPropertyFilter[] | undefined- table_name: string- timestamp_field: string- type: EntityType- [key: string]: any- } // entityFilterLogic- addNestedFilter: (- id: string,+ updateParentSeries: (+ index: number,+ update: SeriesEntityUpdate+ ) => {+ index: number+ update: SeriesEntityUpdate+ } // entityFilterLogic+ addNestedSeries: (+ key: string,name: string,- type: EntityType+ kind: SeriesNode['kind']) => {- id: string+ key: string+ kind:+ | NodeKind.EventsNode+ | NodeKind.GroupNode+ | NodeKind.ActionsNode+ | NodeKind.DataWarehouseNode+ | NodeKind.FunnelsDataWarehouseNode+ | NodeKind.LifecycleDataWarehouseNode+ | NodeKind.ExperimentDataWarehouseNodename: string- type: EntityType}- removeNestedFilter: (nestedIndex: number) => {+ removeNestedSeries: (nestedIndex: number) => {nestedIndex: number}setHogQLDropdownVisible: (visible: boolean) => {@@ -189,14 +107,17 @@ export interface actionFilterGroupLogicActions {property: stringpropertyType: TaxonomicFilterGroupType}- updateNestedFilter: (+ syncNestedRows: (nodes: AnyEntityNode[]) => {+ nodes: AnyEntityNode[]+ }+ updateNestedSeries: (nestedIndex: number,- updates: Partial<LocalFilter>+ updates: Partial<AnyEntityNode>) => {nestedIndex: number- updates: Partial<LocalFilter>+ updates: Partial<AnyEntityNode>}- updateNestedFilterProperties: (+ updateNestedSeriesProperties: (nestedIndex: number,properties: AnyPropertyFilter[]) => {@@ -209,9 +130,13 @@ export interface actionFilterGroupLogicActions {export interface actionFilterGroupLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {- groupFilter: (localFilters: LocalFilter[], groupIndex: number) => LocalFilter | undefined- nestedFilters: (groupFilter: LocalFilter | undefined) => LocalFilter[]- operator: (groupFilter: LocalFilter | undefined) => FilterLogicalOperator+ groupNode: (localSeries: LocalSeries[], groupIndex: number) => GroupNode | undefined+ nestedNodes: (+ groupNode: GroupNode<import('~/queries/schema/schema-general').DataWarehouseNode> | undefined+ ) => AnyEntityNode[]+ operator: (+ groupNode: GroupNode<import('~/queries/schema/schema-general').DataWarehouseNode> | undefined+ ) => FilterLogicalOperator}}@@ -227,18 +152,18 @@ export const actionFilterGroupLogic = kea<actionFilterGroupLogicType>([props({} as ActionFilterGroupLogicProps),key((props) => props.filterUuid),connect((props: ActionFilterGroupLogicProps) => ({- actions: [entityFilterLogic({ typeKey: props.typeKey }), ['updateFilter as updateParentFilter']],- values: [entityFilterLogic({ typeKey: props.typeKey }), ['localFilters'], mathsLogic, ['mathDefinitions']],+ actions: [entityFilterLogic({ typeKey: props.typeKey }), ['updateSeriesEntity as updateParentSeries']],+ values: [entityFilterLogic({ typeKey: props.typeKey }), ['localSeries'], mathsLogic, ['mathDefinitions']],})),actions({- addNestedFilter: (id: string, name: string, type: EntityType) => ({ id, name, type }),- updateNestedFilter: (nestedIndex: number, updates: Partial<LocalFilter>) => ({ nestedIndex, updates }),- updateNestedFilterProperties: (nestedIndex: number, properties: AnyPropertyFilter[]) => ({+ addNestedSeries: (key: string, name: string, kind: SeriesNode['kind']) => ({ key, name, kind }),+ updateNestedSeries: (nestedIndex: number, updates: Partial<AnyEntityNode>) => ({ nestedIndex, updates }),+ updateNestedSeriesProperties: (nestedIndex: number, properties: AnyPropertyFilter[]) => ({nestedIndex,properties,}),- removeNestedFilter: (nestedIndex: number) => ({ nestedIndex }),+ removeNestedSeries: (nestedIndex: number) => ({ nestedIndex }),setMath: (selectedMath: string | undefined, defaultMathHogQLExpression: string) => ({selectedMath,defaultMathHogQLExpression,@@ -246,6 +171,7 @@ export const actionFilterGroupLogic = kea<actionFilterGroupLogicType>([setMathProperty: (property: string, propertyType: TaxonomicFilterGroupType) => ({ property, propertyType }),setMathHogQL: (hogql: string) => ({ hogql }),setHogQLDropdownVisible: (visible: boolean) => ({ visible }),+ syncNestedRows: (nodes: AnyEntityNode[]) => ({ nodes }),}),reducers({@@ -255,82 +181,90 @@ export const actionFilterGroupLogic = kea<actionFilterGroupLogicType>([setHogQLDropdownVisible: (_, { visible }) => visible,},],+ nestedRows: [+ [] as LocalSeries[],+ {+ removeNestedSeries: (current, { nestedIndex }) => current.filter((_, i) => i !== nestedIndex),+ syncNestedRows: (current, { nodes }) => alignNestedRows(current, nodes),+ },+ ],}),selectors({- groupFilter: [- (s, p) => [s.localFilters, p.groupIndex],- (localFilters: LocalFilter[], groupIndex: number): LocalFilter | undefined => localFilters[groupIndex],+ groupNode: [+ (s, p) => [s.localSeries, p.groupIndex],+ (localSeries: LocalSeries[], groupIndex: number): GroupNode | undefined => {+ const node = localSeries[groupIndex]?.node+ return isGroupSeriesNode(node) ? node : undefined+ },],- nestedFilters: [- (s) => [s.groupFilter],- (groupFilter: LocalFilter | undefined): LocalFilter[] =>- ((groupFilter?.nestedFilters as LocalFilter[] | undefined) || []).map((val, i) => ({- ...val,- order: i,- })),+ nestedNodes: [+ (s) => [s.groupNode],+ (groupNode: GroupNode | undefined): AnyEntityNode[] => groupNode?.nodes ?? [],],operator: [- (s) => [s.groupFilter],- (groupFilter: LocalFilter | undefined): FilterLogicalOperator =>- groupFilter?.operator || FilterLogicalOperator.Or,+ (s) => [s.groupNode],+ (groupNode: GroupNode | undefined): FilterLogicalOperator =>+ groupNode?.operator || FilterLogicalOperator.Or,],}),+ subscriptions(({ actions }) => ({+ nestedNodes: (nodes: AnyEntityNode[]): void => {+ actions.syncNestedRows(nodes)+ },+ })),+listeners(({ actions, values, props }) => {- const updateGroup = (nestedFilters: LocalFilter[], extras: Record<string, any> = {}): void => {- const groupFilter = values.groupFilter- if (!groupFilter) {+ const updateGroup = (nestedNodes: AnyEntityNode[], extras: Record<string, any> = {}): void => {+ const groupNode = values.groupNode+ if (!groupNode) {return}- actions.updateParentFilter({- type: EntityTypes.GROUPS,+ actions.updateParentSeries(props.groupIndex, {+ kind: NodeKind.GroupNode,operator: values.operator,- nestedFilters,- name: nestedFilters.map((v) => v.name).join(', '),- index: props.groupIndex,- ...(groupFilter.custom_name !== undefined && { custom_name: groupFilter.custom_name }),- ...getMathProps(groupFilter),+ nodes: nestedNodes,+ name: nestedNodes.map((v) => v.name).join(', '),+ ...(groupNode.custom_name !== undefined && { custom_name: groupNode.custom_name }),+ ...getMathProps(groupNode),...extras,- } as any)+ })}return {- addNestedFilter: ({ id, name, type }) => {- const groupFilter = values.groupFilter- if (!groupFilter) {+ addNestedSeries: ({ key, name, kind }) => {+ const groupNode = values.groupNode+ if (!groupNode) {return}- const newFilter: LocalFilter = {- id,+ const newNode = withLatestVersion({+ kind,+ ...(kind === NodeKind.ActionsNode ? { id: parseInt(key) } : { event: key }),name,- type,- order: values.nestedFilters.length,- uuid: uuid(),- ...getMathProps(groupFilter),- }+ ...getMathProps(groupNode),+ } as SeriesNode) as AnyEntityNode- updateGroup([...values.nestedFilters, newFilter])+ updateGroup([...values.nestedNodes, newNode])},- updateNestedFilter: ({ nestedIndex, updates }) => {- const newFilters = [...values.nestedFilters]- newFilters[nestedIndex] = { ...newFilters[nestedIndex], ...updates }- updateGroup(newFilters)+ updateNestedSeries: ({ nestedIndex, updates }) => {+ const newNodes = [...values.nestedNodes]+ newNodes[nestedIndex] = { ...newNodes[nestedIndex], ...updates } as AnyEntityNode+ updateGroup(newNodes)},- updateNestedFilterProperties: ({ nestedIndex, properties }) => {- const newFilters = [...values.nestedFilters]- newFilters[nestedIndex] = { ...newFilters[nestedIndex], properties }- updateGroup(newFilters)+ updateNestedSeriesProperties: ({ nestedIndex, properties }) => {+ const newNodes = [...values.nestedNodes]+ newNodes[nestedIndex] = { ...newNodes[nestedIndex], properties } as AnyEntityNode+ updateGroup(newNodes)},- removeNestedFilter: ({ nestedIndex }) => {- const newFilters = values.nestedFilters.filter((_, i) => i !== nestedIndex)- updateGroup(newFilters)+ removeNestedSeries: ({ nestedIndex }) => {+ updateGroup(values.nestedNodes.filter((_, i) => i !== nestedIndex))},setMath: ({ selectedMath, defaultMathHogQLExpression }) => {- const groupFilter = values.groupFilter- if (!groupFilter) {+ const groupNode = values.groupNode+ if (!groupNode) {return}@@ -343,13 +277,13 @@ export const actionFilterGroupLogic = kea<actionFilterGroupLogicType>([...(apiValues.math_group_type_index === undefined && { math_group_type_index: undefined }),math_property:mathDef?.category === MathCategory.PropertyValue- ? (groupFilter.math_property ?? '$time')+ ? (groupNode.math_property ?? '$time'): undefined,math_hogql:mathDef?.category === MathCategory.HogQLExpression- ? (groupFilter.math_hogql ?? defaultMathHogQLExpression)+ ? (groupNode.math_hogql ?? defaultMathHogQLExpression): undefined,- math_property_type: groupFilter.math_property_type,+ math_property_type: groupNode.math_property_type,}} else {mathProps = {@@ -361,12 +295,12 @@ export const actionFilterGroupLogic = kea<actionFilterGroupLogicType>([}}- const newFilters = values.nestedFilters.map((f) => ({ ...f, ...mathProps }))- updateGroup(newFilters, mathProps)+ const newNodes = values.nestedNodes.map((f) => ({ ...f, ...mathProps }) as AnyEntityNode)+ updateGroup(newNodes, mathProps)},setMathProperty: ({ property, propertyType }) => {- const groupFilter = values.groupFilter- if (!groupFilter) {+ const groupNode = values.groupNode+ if (!groupNode) {return}@@ -375,12 +309,12 @@ export const actionFilterGroupLogic = kea<actionFilterGroupLogicType>([math_property_type: propertyType,math_hogql: undefined,}- const newFilters = values.nestedFilters.map((f) => ({ ...f, ...mathProps }))- updateGroup(newFilters, { math: groupFilter.math, ...mathProps })+ const newNodes = values.nestedNodes.map((f) => ({ ...f, ...mathProps }) as AnyEntityNode)+ updateGroup(newNodes, { math: groupNode.math, ...mathProps })},setMathHogQL: ({ hogql }) => {- const groupFilter = values.groupFilter- if (!groupFilter) {+ const groupNode = values.groupNode+ if (!groupNode) {return}@@ -389,8 +323,8 @@ export const actionFilterGroupLogic = kea<actionFilterGroupLogicType>([math_property_type: undefined,math_hogql: hogql,}- const newFilters = values.nestedFilters.map((f) => ({ ...f, ...mathProps }))- updateGroup(newFilters, { math: groupFilter.math, ...mathProps })+ const newNodes = values.nestedNodes.map((f) => ({ ...f, ...mathProps }) as AnyEntityNode)+ updateGroup(newNodes, { math: groupNode.math, ...mathProps })},}}),diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/nestedFilterLogic.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/nestedFilterLogic.tsindex 0a68c2b03bb8..2811b83bf01d 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/nestedFilterLogic.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterGroup/nestedFilterLogic.ts@@ -1,12 +1,15 @@import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { AnyEntityNode, NodeKind } from '~/queries/schema/schema-general'import { AnyPropertyFilter } from '~/types'-import { LocalFilter } from '../entityFilterLogic'+import { SeriesEntityUpdate } from '../entityFilterLogic'import { actionFilterGroupLogic } from './actionFilterGroupLogic'export interface NestedFilterLogicProps {groupFilterUuid: string+ /** Sidecar row identity, so a removal cannot move this row's state onto its neighbour. */+ nestedUuid: stringnestedIndex: numbertypeKey: stringgroupIndex: number@@ -20,31 +23,29 @@ export interface nestedFilterLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface nestedFilterLogicActions {- removeNestedFilter: (nestedIndex: number) => {+ removeNestedSeries: (nestedIndex: number) => {nestedIndex: number} // actionFilterGroupLogic- updateNestedFilter: (+ updateNestedSeries: (nestedIndex: number,- updates: Partial<LocalFilter>+ updates: Partial<AnyEntityNode>) => {nestedIndex: number- updates: Partial<LocalFilter>+ updates: Partial<AnyEntityNode>} // actionFilterGroupLogic- updateNestedFilterProperties: (+ updateNestedSeriesProperties: (nestedIndex: number,properties: AnyPropertyFilter[]) => {nestedIndex: numberproperties: AnyPropertyFilter[]} // actionFilterGroupLogic- convertFilterToGroup: () => {}- duplicateFilter: () => {}- removeLocalFilter: (filter: { index: number }) => {- filter: {- index: number- }+ convertToGroup: () => {}+ duplicateSeries: () => {}+ removeSeries: (index: number) => {+ index: number}- selectFilter: () => {}+ selectSeries: () => {}setEntityFilterVisibility: (index: number,value: boolean@@ -52,22 +53,21 @@ export interface nestedFilterLogicActions {index: numbervalue: boolean}- updateFilter: (- filter: Partial<LocalFilter> & {- index: number- }+ updateSeriesEntity: (+ index: number,+ update: SeriesEntityUpdate) => {- filter: Partial<LocalFilter> & {- index: number- }+ index: number+ update: SeriesEntityUpdate}- updateFilterMath: () => {}- updateFilterOptional: () => {}- updateFilterProperty: (filter: { index: number; properties: AnyPropertyFilter[] }) => {- filter: {- index: number- properties: AnyPropertyFilter[]- }+ updateSeriesMath: () => {}+ updateSeriesOptional: () => {}+ updateSeriesProperties: (+ index: number,+ properties: AnyPropertyFilter[]+ ) => {+ index: number+ properties: AnyPropertyFilter[]}}@@ -87,14 +87,14 @@ export type nestedFilterLogicType = MakeLogicType<>/**- * Minimal logic for nested filters within an ActionFilterGroup.+ * Minimal logic for nested series within an ActionFilterGroup.* Implements only the actions required by ActionFilterRow and delegates* all updates to the parent actionFilterGroupLogic.*/export const nestedFilterLogic = kea<nestedFilterLogicType>([path(['scenes', 'insights', 'filters', 'ActionFilter', 'ActionFilterGroup', 'nestedFilterLogic']),props({} as NestedFilterLogicProps),- key((props) => `${props.groupFilterUuid}-${props.nestedIndex}`),+ key((props) => `${props.groupFilterUuid}-${props.nestedUuid}`),connect((props: NestedFilterLogicProps) => ({actions: [@@ -103,21 +103,21 @@ export const nestedFilterLogic = kea<nestedFilterLogicType>([typeKey: props.typeKey,groupIndex: props.groupIndex,}),- ['updateNestedFilter', 'removeNestedFilter', 'updateNestedFilterProperties'],+ ['updateNestedSeries', 'removeNestedSeries', 'updateNestedSeriesProperties'],],})),actions({- updateFilter: (filter: Partial<LocalFilter> & { index: number }) => ({ filter }),- removeLocalFilter: (filter: { index: number }) => ({ filter }),- updateFilterProperty: (filter: { index: number; properties: AnyPropertyFilter[] }) => ({ filter }),+ updateSeriesEntity: (index: number, update: SeriesEntityUpdate) => ({ index, update }),+ removeSeries: (index: number) => ({ index }),+ updateSeriesProperties: (index: number, properties: AnyPropertyFilter[]) => ({ index, properties }),setEntityFilterVisibility: (index: number, value: boolean) => ({ index, value }),- // Stub actions that ActionFilterRow may call but we don't need for nested filters- selectFilter: () => ({}),- updateFilterOptional: () => ({}),- updateFilterMath: () => ({}),- duplicateFilter: () => ({}),- convertFilterToGroup: () => ({}),+ // Stub actions that ActionFilterRow may call but we don't need for nested series+ selectSeries: () => ({}),+ updateSeriesOptional: () => ({}),+ updateSeriesMath: () => ({}),+ duplicateSeries: () => ({}),+ convertToGroup: () => ({}),}),reducers({@@ -139,14 +139,25 @@ export const nestedFilterLogic = kea<nestedFilterLogicType>([}),listeners(({ actions, props }) => ({- updateFilter: ({ filter }) => {- actions.updateNestedFilter(props.nestedIndex, filter)+ updateSeriesEntity: ({ update }) => {+ const { kind, key, name, custom_name, ...extra } = update+ // The update merges onto the existing node, so the key the previous kind was+ // identified by has to be cleared or the node ends up carrying both.+ actions.updateNestedSeries(props.nestedIndex, {+ kind,+ ...(kind === NodeKind.ActionsNode+ ? { id: typeof key === 'string' ? parseInt(key) : key, event: undefined }+ : { event: key, id: undefined }),+ ...(typeof name !== 'undefined' && { name }),+ ...(typeof custom_name !== 'undefined' && { custom_name }),+ ...extra,+ } as Partial<AnyEntityNode>)},- removeLocalFilter: () => {- actions.removeNestedFilter(props.nestedIndex)+ removeSeries: () => {+ actions.removeNestedSeries(props.nestedIndex)},- updateFilterProperty: ({ filter }) => {- actions.updateNestedFilterProperties(props.nestedIndex, filter.properties)+ updateSeriesProperties: ({ properties }) => {+ actions.updateNestedSeriesProperties(props.nestedIndex, properties)},})),])diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsxindex 23ca398ded79..28ed8d78ea16 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.test.tsx@@ -17,6 +17,7 @@ import { useMocks } from '~/mocks/jest'import { actionsModel } from '~/models/actionsModel'import { groupsModel } from '~/models/groupsModel'import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'+import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { searchAndSelect, setupInsightMocks } from '~/test/insight-testing'import {@@ -31,6 +32,8 @@ import {} from '~/types'import filtersJson from '../__mocks__/filters.json'+import { legacyFiltersToSeries } from '../legacyFilters'+import { SeriesNode } from '../seriesNode'import { ActionFilterRow, taxonomicFilterGroupTypeToEntityType } from './ActionFilterRow'import { MathAvailability } from './types'@@ -57,12 +60,10 @@ jest.mock('@dnd-kit/sortable', () => ({}),}))-const DEFAULT_FILTER = {- id: '$pageview',+const DEFAULT_NODE: SeriesNode = {+ kind: NodeKind.EventsNode,+ event: '$pageview',name: '$pageview',- type: EntityTypes.EVENTS as const,- order: 0,- uuid: 'test-uuid-1',properties: [],}@@ -72,15 +73,15 @@ const INLINE_CONTEXT = {mathAvailability: MathAvailability.None,}-function setup(filtersOverride?: Partial<FilterType>): {+function setup(seriesOverride?: SeriesNode[]): {logic: ReturnType<typeof entityFilterLogic.build>- setFilters: jest.Mock+ onChange: jest.Mock} {- const filters = { ...filtersJson, ...filtersOverride } as FilterType- const setFilters = jest.fn()- const logic = entityFilterLogic({ setFilters, filters, typeKey: 'test-key' })+ const series = seriesOverride ?? legacyFiltersToSeries(filtersJson as FilterType)+ const onChange = jest.fn()+ const logic = entityFilterLogic({ onChange, series, typeKey: 'test-key' })logic.mount()- return { logic, setFilters }+ return { logic, onChange }}function renderRow(@@ -91,7 +92,8 @@ function renderRow(<Provider><ActionFilterRowlogic={logic}- filter={DEFAULT_FILTER}+ node={DEFAULT_NODE}+ uuid="test-uuid-1"index={0}typeKey="test-key"mathAvailability={MathAvailability.All}@@ -170,7 +172,7 @@ describe('ActionFilterRow', () => {it('shows the underlying event alongside a renamed series', () => {const { logic } = setup()renderRow(logic, {- filter: { ...DEFAULT_FILTER, id: 'user signed up', name: 'Signed up', custom_name: 'Signed up' },+ node: { ...DEFAULT_NODE, event: 'user signed up', name: 'Signed up', custom_name: 'Signed up' },})const row = document.querySelector('.ActionFilterRow')!expect(row.textContent).toContain('Signed up')@@ -181,7 +183,7 @@ describe('ActionFilterRow', () => {const { logic } = setup()renderRow(logic, {...INLINE_CONTEXT,- filter: { ...DEFAULT_FILTER, id: 'user signed up', name: 'Signed up', custom_name: 'Signed up' },+ node: { ...DEFAULT_NODE, event: 'user signed up', name: 'Signed up', custom_name: 'Signed up' },})await userEvent.click(screen.getByTestId('trend-element-subject-0'))@@ -261,7 +263,7 @@ describe('ActionFilterRow', () => {})it('shows ellipsis menu button in funnel context', () => {- const { logic } = setup({ insight: InsightType.FUNNELS })+ const { logic } = setup()renderRow(logic, { mathAvailability: MathAvailability.FunnelsOnly })expect(screen.getByLabelText('Show more actions')).toBeInTheDocument()})@@ -324,21 +326,16 @@ describe('ActionFilterRow', () => {joins: [],} as any)- const dataWarehouseFilter = {+ const dataWarehouseNode = {+ kind: NodeKind.DataWarehouseNode,id: 'events_table',name: 'events_table',- type: EntityTypes.DATA_WAREHOUSE,table_name: 'events_table',- order: 0,- }- const { logic, setFilters } = setup({- events: [],- actions: [],- data_warehouse: [dataWarehouseFilter],- } as Partial<FilterType>)+ } as SeriesNode+ const { logic, onChange } = setup([dataWarehouseNode])renderRow(logic, {mathAvailability: MathAvailability.BoxPlotOnly,- filter: { ...DEFAULT_FILTER, ...dataWarehouseFilter },+ node: dataWarehouseNode,})await userEvent.click(screen.getByTestId('box-plot-property-select'))@@ -349,16 +346,13 @@ describe('ActionFilterRow', () => {await userEvent.click(screen.getByText('duration'))await waitFor(() => {- expect(setFilters).toHaveBeenCalledWith(+ expect(onChange).toHaveBeenCalledWith([expect.objectContaining({- data_warehouse: [- expect.objectContaining({- math_property: 'duration',- math_property_type: TaxonomicFilterGroupType.DataWarehouseProperties,- }),- ],- })- )+ kind: NodeKind.DataWarehouseNode,+ math_property: 'duration',+ math_property_type: TaxonomicFilterGroupType.DataWarehouseProperties,+ }),+ ])})})})@@ -436,7 +430,7 @@ describe('ActionFilterRow', () => {...INLINE_CONTEXT,showCombine: true,singleFilter: false,- filter: { ...DEFAULT_FILTER, type: EntityTypes.DATA_WAREHOUSE },+ node: { ...DEFAULT_NODE, kind: NodeKind.DataWarehouseNode } as SeriesNode,})expect(screen.queryByTestId('show-prop-combine-0')).not.toBeInTheDocument()})@@ -468,14 +462,14 @@ describe('ActionFilterRow', () => {expect(screen.getByText('my-suffix')).toBeInTheDocument()})- it('calls function suffix with filter, index, onClose', () => {+ it('calls function suffix with node, index, onClose', () => {const { logic } = setup()- const suffixFn = jest.fn(({ filter }) => <span data-attr="fn-suffix">{filter.name}</span>)+ const suffixFn = jest.fn(({ node }) => <span data-attr="fn-suffix">{node.name}</span>)renderRow(logic, { customRowSuffix: suffixFn })expect(screen.getByTestId('fn-suffix')).toHaveTextContent('$pageview')expect(suffixFn).toHaveBeenCalledWith(expect.objectContaining({- filter: expect.objectContaining({ id: '$pageview' }),+ node: expect.objectContaining({ event: '$pageview' }),index: 0,onClose: expect.any(Function),})@@ -487,7 +481,7 @@ describe('ActionFilterRow', () => {it('renders with the action name', () => {const { logic } = setup()renderRow(logic, {- filter: { ...DEFAULT_FILTER, id: '9', name: 'Users signed up', type: EntityTypes.ACTIONS },+ node: { kind: NodeKind.ActionsNode, id: 9, name: 'Users signed up' } as SeriesNode,})expect(document.querySelector('.ActionFilterRow')!.textContent).toContain('Users signed up')})@@ -496,30 +490,26 @@ describe('ActionFilterRow', () => {describe('interactions', () => {it('dispatches removeLocalFilter on delete click', async () => {- const { logic, setFilters } = setup()+ const { logic, onChange } = setup()renderRow(logic, { ...INLINE_CONTEXT, hideDeleteBtn: false, singleFilter: false })await userEvent.click(screen.getByTitle('Delete graph series'))// Deleting the first event (order 0) leaves only 1 event + 1 action, re-ordered- expect(setFilters).toHaveBeenCalledWith(- expect.objectContaining({- events: [expect.objectContaining({ id: '$pageview' })],- actions: [expect.objectContaining({ id: '9' })],- })- )- // The remaining event list should have exactly 1 entry (down from 2)- const call = setFilters.mock.calls[0][0]- expect(call.events).toHaveLength(1)+ expect(onChange).toHaveBeenCalledWith([+ expect.objectContaining({ kind: NodeKind.EventsNode, event: '$pageview' }),+ expect.objectContaining({ kind: NodeKind.ActionsNode, id: 9 }),+ ])+ // Down from 3 series (2 events + 1 action) to 2+ expect(onChange.mock.calls[0][0]).toHaveLength(2)})it('dispatches duplicateFilter on duplicate click', async () => {- const { logic, setFilters } = setup()+ const { logic, onChange } = setup()renderRow(logic, { ...INLINE_CONTEXT, hideDuplicate: false, singleFilter: false })await userEvent.click(screen.getByTitle('Duplicate graph series'))- expect(setFilters).toHaveBeenCalledWith(- expect.objectContaining({- events: expect.arrayContaining([expect.objectContaining({ id: '$pageview', order: 0 })]),- })- )+ const duplicated = onChange.mock.calls[0][0]+ expect(duplicated).toHaveLength(4)+ expect(duplicated[0]).toEqual(expect.objectContaining({ kind: NodeKind.EventsNode, event: '$pageview' }))+ expect(duplicated[1]).toEqual(expect.objectContaining({ kind: NodeKind.EventsNode, event: '$pageview' }))})it('dispatches selectFilter and calls onRenameClick on rename', async () => {@@ -531,12 +521,14 @@ describe('ActionFilterRow', () => {})it('dispatches convertFilterToGroup on combine click', async () => {- const { logic, setFilters } = setup()+ const { logic, onChange } = setup()renderRow(logic, { ...INLINE_CONTEXT, showCombine: true, singleFilter: false })await userEvent.click(screen.getByTestId('show-prop-combine-0'))- expect(setFilters).toHaveBeenCalledWith(+ // The combined row becomes a group holding the event it was built from+ expect(onChange.mock.calls[0][0][0]).toEqual(expect.objectContaining({- events: expect.arrayContaining([expect.objectContaining({ id: '$pageview' })]),+ kind: NodeKind.GroupNode,+ nodes: [expect.objectContaining({ kind: NodeKind.EventsNode, event: '$pageview' })],}))})@@ -557,7 +549,7 @@ describe('ActionFilterRow', () => {describe('math selection', () => {it('changing math type calls setFilters with updated math', async () => {- const { logic, setFilters } = setup()+ const { logic, onChange } = setup()renderRow(logic, { mathAvailability: MathAvailability.All })await userEvent.click(screen.getByTestId('math-selector-0'))@@ -567,19 +559,15 @@ describe('ActionFilterRow', () => {})await userEvent.click(screen.getByText('Unique users'))- expect(setFilters).toHaveBeenCalledWith(- expect.objectContaining({- events: expect.arrayContaining([expect.objectContaining({ math: 'dau' })]),- })- )+ expect(onChange).toHaveBeenCalledWith(expect.arrayContaining([expect.objectContaining({ math: 'dau' })]))})it('shows property value selector when property math is active', () => {const { logic } = setup()renderRow(logic, {mathAvailability: MathAvailability.All,- filter: {- ...DEFAULT_FILTER,+ node: {+ ...DEFAULT_NODE,math: PropertyMathType.Average,math_property: '$time',},@@ -591,8 +579,8 @@ describe('ActionFilterRow', () => {const { logic } = setup()renderRow(logic, {mathAvailability: MathAvailability.All,- filter: {- ...DEFAULT_FILTER,+ node: {+ ...DEFAULT_NODE,math: HogQLMathType.HogQL,math_hogql: 'sum(price)',},@@ -602,7 +590,7 @@ describe('ActionFilterRow', () => {})it('defaults HogQL math expression to person_id for stickiness insights', async () => {- const { logic, setFilters } = setup({ insight: InsightType.STICKINESS })+ const { logic, onChange } = setup()renderRow(logic, {mathAvailability: MathAvailability.All,insightType: InsightType.STICKINESS,@@ -612,53 +600,49 @@ describe('ActionFilterRow', () => {await waitFor(() => expect(screen.getByText('SQL expression')).toBeInTheDocument())await userEvent.click(screen.getByText('SQL expression'))- expect(setFilters).toHaveBeenCalledWith(- expect.objectContaining({- events: expect.arrayContaining([expect.objectContaining({ math_hogql: 'person_id' })]),- })+ expect(onChange).toHaveBeenCalledWith(+ expect.arrayContaining([expect.objectContaining({ math_hogql: 'person_id' })]))})it('does not show math selector inline for FunnelsOnly (it goes in the popup menu)', () => {- const { logic } = setup({ insight: InsightType.FUNNELS })+ const { logic } = setup()renderRow(logic, { mathAvailability: MathAvailability.FunnelsOnly })// MathSelector should NOT be in the center section (it's in the popup menu instead)expect(screen.queryByTestId('math-selector-0')).not.toBeInTheDocument()})it('selecting property math sets math_property and clears math_hogql', async () => {- const { logic, setFilters } = setup()+ const { logic, onChange } = setup()renderRow(logic, {mathAvailability: MathAvailability.All,- filter: {- ...DEFAULT_FILTER,+ node: {+ ...DEFAULT_NODE,math: PropertyMathType.Average,math_property: '$time',math_hogql: 'count()',},})- // Simulate onMathPropertySelect which calls updateFilterMath- logic.actions.updateFilterMath({- ...DEFAULT_FILTER,+ // Simulate onMathPropertySelect+ logic.actions.updateSeriesMath(0, {math_hogql: undefined,math_property: '$session_duration',math_property_type: TaxonomicFilterGroupType.SessionProperties,- index: 0,})await waitFor(() => {- const call = setFilters.mock.calls[setFilters.mock.calls.length - 1][0]- expect(call.events).toEqual(+ const call = onChange.mock.calls[onChange.mock.calls.length - 1][0]+ expect(call).toEqual(expect.arrayContaining([expect.objectContaining({math_property: '$session_duration',}),]))- // math_hogql should not be present on the updated filter- const updatedEvent = call.events.find((e: any) => e.math_property === '$session_duration')- expect(updatedEvent.math_hogql).toBeUndefined()+ // math_hogql should not be present on the updated series+ const updated = call.find((node: any) => node.math_property === '$session_duration')+ expect(updated.math_hogql).toBeUndefined()})})@@ -680,7 +664,7 @@ describe('ActionFilterRow', () => {describe('funnel popup menu contents', () => {it('shows rename and delete inside popup menu when opened', async () => {- const { logic } = setup({ insight: InsightType.FUNNELS })+ const { logic } = setup()renderRow(logic, { mathAvailability: MathAvailability.FunnelsOnly })await userEvent.click(screen.getByLabelText('Show more actions'))@@ -692,7 +676,7 @@ describe('ActionFilterRow', () => {})it('shows duplicate in popup menu when not singleFilter', async () => {- const { logic } = setup({ insight: InsightType.FUNNELS })+ const { logic } = setup()renderRow(logic, {mathAvailability: MathAvailability.FunnelsOnly,singleFilter: false,@@ -706,7 +690,7 @@ describe('ActionFilterRow', () => {})it('hides duplicate in popup menu when singleFilter', async () => {- const { logic } = setup({ insight: InsightType.FUNNELS })+ const { logic } = setup()renderRow(logic, {mathAvailability: MathAvailability.FunnelsOnly,singleFilter: true,@@ -721,11 +705,10 @@ describe('ActionFilterRow', () => {})it('shows optional step checkbox for funnel steps after the first', async () => {- const { logic } = setup({ insight: InsightType.FUNNELS })+ const { logic } = setup()renderRow(logic, {mathAvailability: MathAvailability.FunnelsOnly,index: 1,- filter: { ...DEFAULT_FILTER, order: 1 },})await userEvent.click(screen.getByLabelText('Show more actions'))@@ -736,7 +719,7 @@ describe('ActionFilterRow', () => {})it('does not show optional step checkbox for the first funnel step', async () => {- const { logic } = setup({ insight: InsightType.FUNNELS })+ const { logic } = setup()renderRow(logic, {mathAvailability: MathAvailability.FunnelsOnly,index: 0,@@ -751,7 +734,7 @@ describe('ActionFilterRow', () => {})it('shows math selector inside funnel popup menu', async () => {- const { logic } = setup({ insight: InsightType.FUNNELS })+ const { logic } = setup()renderRow(logic, { mathAvailability: MathAvailability.FunnelsOnly })await userEvent.click(screen.getByLabelText('Show more actions'))@@ -763,7 +746,7 @@ describe('ActionFilterRow', () => {})it('shows property filter outside the popup menu', () => {- const { logic } = setup({ insight: InsightType.FUNNELS })+ const { logic } = setup()renderRow(logic, {mathAvailability: MathAvailability.FunnelsOnly,hideFilter: false,@@ -777,7 +760,7 @@ describe('ActionFilterRow', () => {describe('event selection onChange handler', () => {it('selecting an event updates the filter with the chosen event', async () => {- const { logic, setFilters } = setup()+ const { logic, onChange } = setup()renderRow(logic, INLINE_CONTEXT)await userEvent.click(screen.getByTestId('trend-element-subject-0'))@@ -789,15 +772,12 @@ describe('ActionFilterRow', () => {await userEvent.click(screen.getByTestId('prop-filter-events-1'))await waitFor(() => {- expect(setFilters).toHaveBeenCalledWith(- expect.objectContaining({- events: expect.arrayContaining([- expect.objectContaining({- type: EntityTypes.EVENTS,- order: 0,- }),- ]),- })+ expect(onChange).toHaveBeenCalledWith(+ expect.arrayContaining([+ expect.objectContaining({+ kind: NodeKind.EventsNode,+ }),+ ]))})})@@ -839,7 +819,7 @@ describe('ActionFilterRow', () => {},})- const { logic, setFilters } = setup()+ const { logic, onChange } = setup()renderRow(logic, {...INLINE_CONTEXT,actionsTaxonomicGroupTypes: [@@ -853,11 +833,11 @@ describe('ActionFilterRow', () => {await searchAndSelect('trend-element-subject-0', searchText, `prop-filter-${tab}-0`)await waitFor(() => {- const lastCall = setFilters.mock.calls[setFilters.mock.calls.length - 1][0]- expect(lastCall.events).toEqual(+ const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1][0]+ expect(lastCall).toEqual(expect.arrayContaining([expect.objectContaining({- id: expectedEventId,+ event: expectedEventId,properties: expect.arrayContaining([expect.objectContaining({key: expectedPropertyKey,@@ -878,8 +858,8 @@ describe('ActionFilterRow', () => {it('renders "All events" placeholder for null event id', () => {const { logic } = setup()renderRow(logic, {- filter: {- ...DEFAULT_FILTER,+ node: {+ ...DEFAULT_NODE,id: null,name: 'All events',},@@ -894,8 +874,8 @@ describe('ActionFilterRow', () => {renderRow(logic, {...INLINE_CONTEXT,hideFilter: false,- filter: {- ...DEFAULT_FILTER,+ node: {+ ...DEFAULT_NODE,properties: [{ key: '$browser', value: 'Chrome', operator: 'exact', type: 'event' },{ key: '$os', value: 'Mac', operator: 'exact', type: 'event' },@@ -911,7 +891,7 @@ describe('ActionFilterRow', () => {renderRow(logic, {...INLINE_CONTEXT,hideFilter: false,- filter: { ...DEFAULT_FILTER, id: 'empty' },+ node: { ...DEFAULT_NODE, event: 'empty' },})const filterButton = screen.getByTitle('Show filters')expect(filterButton).toHaveAttribute('aria-disabled', 'true')diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsxindex 2b1e949c4561..47152e6b48dc 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow.tsx@@ -30,7 +30,6 @@ import { getEventNamesForAction } from 'lib/utils/events'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { insightLogic } from 'scenes/insights/insightLogic'-import { isAllEventsEntityFilter } from 'scenes/insights/utils'import { teamLogic } from 'scenes/teamLogic'import { actionsModel } from '~/models/actionsModel'@@ -38,7 +37,6 @@ import { DatabaseSerializedFieldType, NodeKind } from '~/queries/schema/schema-gimport {AnyPropertyFilter,BaseMathType,- EntityTypes,InsightShortId,PropertyFilterType,PropertyFilterValue,@@ -52,8 +50,16 @@ import {mathsLogic,} from 'products/product_analytics/frontend/insights/trends/mathsLogic'+import {+ isActionsSeriesNode,+ isAllEventsSeriesNode,+ isEventsSeriesNode,+ isWarehouseSeriesNode,+ isWarehouseSeriesNodeKind,+ seriesNodeKey,+} from '../seriesNode'import { ActionFilterRowMenu } from './ActionFilterRowMenu'-import { getValue, taxonomicFilterGroupTypeToEntityType } from './actionFilterRowUtils'+import { getValue, taxonomicGroupTypeToSeriesNodeKind } from './actionFilterRowUtils'import { HogQLMathEditorDropdown } from './HogQLMathEditor'import { MathSelector } from './MathSelector'import { getDefaultMathHogQLExpression } from './mathUtils'@@ -89,7 +95,8 @@ const DATA_WAREHOUSE_GROUP_TYPE_BY_TYPE_KEY: Record<string, TaxonomicFilterGroupexport function ActionFilterRow({logic,- filter,+ node,+ uuid,index,typeKey,mathAvailability,@@ -119,6 +126,7 @@ export function ActionFilterRow({showNumericalPropsOnly,allowedMathTypes,dataWarehousePopoverFields = defaultDataWarehousePopoverFields,+ dataWarehouseNodeKind,filtersLeftPadding = false,addFilterDocLink,excludedProperties,@@ -138,25 +146,26 @@ export function ActionFilterRow({const { currentTeamId } = useValues(teamLogic)const { entityFilterVisible } = useValues(logic)const {- updateFilter,- selectFilter,- updateFilterOptional,- updateFilterMath,- removeLocalFilter,- updateFilterProperty,+ updateSeriesEntity,+ selectSeries,+ updateSeriesOptional,+ updateSeriesMath,+ removeSeries,+ updateSeriesProperties,setEntityFilterVisibility,- duplicateFilter,- convertFilterToGroup,+ duplicateSeries,+ convertToGroup,} = useActions(logic)- const { actions } = useValues(actionsModel({ shouldLoad: filter.type === EntityTypes.ACTIONS }))+ const { actions } = useValues(actionsModel({ shouldLoad: isActionsSeriesNode(node) }))const { mathDefinitions } = useValues(mathsLogic)const { dataWarehouseTablesMap } = useValues(databaseTableListLogic)const { ensureAllTableFields } = useActions(databaseTableListLogic)+ const isDataWarehouseFilter = isWarehouseSeriesNode(node)useEffect(() => {- if (filter.type === 'data_warehouse') {+ if (isDataWarehouseFilter) {ensureAllTableFields()}- }, [filter.type, ensureAllTableFields])+ }, [isDataWarehouseFilter, ensureAllTableFields])const { featureFlags } = useValues(featureFlagLogic)const mountedInsightDataLogic = insightDataLogic.findMounted({ dashboardItemId: typeKey })@@ -186,9 +195,9 @@ export function ActionFilterRow({transition,listeners,isDragging,- } = useSortable({ id: filter.uuid })+ } = useSortable({ id: uuid })- const propertyFiltersVisible = typeof filter.order === 'number' ? entityFilterVisible[filter.order] : false+ const propertyFiltersVisible = entityFilterVisible[index]let name: string | null | undefined, value: PropertyFilterValueconst {@@ -197,16 +206,16 @@ export function ActionFilterRow({math_property_type: mathPropertyType,math_hogql: mathHogQL,math_group_type_index: mathGroupTypeIndex,- } = filter+ } = nodeconst defaultMathHogQLExpression = getDefaultMathHogQLExpression(insightType)const onClose = (): void => {- removeLocalFilter({ ...filter, index })+ removeSeries(index)}const onPropertyChange = useCallback(- (properties: AnyPropertyFilter[]) => updateFilterProperty({ properties, index }),- [updateFilterProperty, index]+ (properties: AnyPropertyFilter[]) => updateSeriesProperties(index, properties),+ [updateSeriesProperties, index])/**@@ -225,77 +234,65 @@ export function ActionFilterRow({): void => {if (isQuickFilterItem(item)) {if (item.eventName) {- updateFilter({ type: EntityTypes.EVENTS, id: item.eventName, name: item.eventName, index })+ updateSeriesEntity(index, { kind: NodeKind.EventsNode, key: item.eventName, name: item.eventName })}- updateFilterProperty({ index, properties: quickFilterToPropertyFilters(item) })+ updateSeriesProperties(index, quickFilterToPropertyFilters(item))return}if (taxonomicGroupType === TaxonomicFilterGroupType.PageviewEvents) {- updateFilter({ type: EntityTypes.EVENTS, id: '$pageview', name: '$pageview', index })- updateFilterProperty({- index,- properties: [- {- key: '$current_url',- value: changedValue ? String(changedValue) : '',- operator: PropertyOperator.IContains,- type: PropertyFilterType.Event,- },- ],- })+ updateSeriesEntity(index, { kind: NodeKind.EventsNode, key: '$pageview', name: '$pageview' })+ updateSeriesProperties(index, [+ {+ key: '$current_url',+ value: changedValue ? String(changedValue) : '',+ operator: PropertyOperator.IContains,+ type: PropertyFilterType.Event,+ },+ ])return}if (taxonomicGroupType === TaxonomicFilterGroupType.ScreenEvents) {- updateFilter({ type: EntityTypes.EVENTS, id: '$screen', name: '$screen', index })- updateFilterProperty({- index,- properties: [- {- key: '$screen_name',- value: changedValue ? String(changedValue) : '',- operator: PropertyOperator.Exact,- type: PropertyFilterType.Event,- },- ],- })+ updateSeriesEntity(index, { kind: NodeKind.EventsNode, key: '$screen', name: '$screen' })+ updateSeriesProperties(index, [+ {+ key: '$screen_name',+ value: changedValue ? String(changedValue) : '',+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ },+ ])return}if (taxonomicGroupType === TaxonomicFilterGroupType.AutocaptureEvents) {- updateFilter({ type: EntityTypes.EVENTS, id: '$autocapture', name: '$autocapture', index })- updateFilterProperty({- index,- properties: [- {- key: '$el_text',- value: changedValue ? String(changedValue) : '',- operator: PropertyOperator.Exact,- type: PropertyFilterType.Event,- },- ],- })+ updateSeriesEntity(index, { kind: NodeKind.EventsNode, key: '$autocapture', name: '$autocapture' })+ updateSeriesProperties(index, [+ {+ key: '$el_text',+ value: changedValue ? String(changedValue) : '',+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.Event,+ },+ ])return}- const groupType = taxonomicFilterGroupTypeToEntityType(taxonomicGroupType)- if (groupType === EntityTypes.DATA_WAREHOUSE) {+ const kind = taxonomicGroupTypeToSeriesNodeKind(taxonomicGroupType, dataWarehouseNodeKind)+ if (isWarehouseSeriesNodeKind(kind)) {const extraValues = Object.fromEntries(dataWarehousePopoverFields.map(({ key }) => [key, item?.[key]]))- updateFilter({- type: groupType,- id: changedValue ? String(changedValue) : null,+ updateSeriesEntity(index, {+ kind,+ key: item?.name ?? (changedValue ? String(changedValue) : null),name: item?.name ?? '',- table_name: item?.name,- index,...extraValues,})} else {- updateFilter({- type: groupType || undefined,- id: changedValue ? String(changedValue) : null,+ updateSeriesEntity(index, {+ kind,+ key: changedValue ?? null,name: item?.name ?? '',- index,})}},- [updateFilter, updateFilterProperty, index, dataWarehousePopoverFields]+ [updateSeriesEntity, updateSeriesProperties, index, dataWarehousePopoverFields, dataWarehouseNodeKind])const onMathSelect = (_: unknown, selectedMath?: string): void => {@@ -325,42 +322,39 @@ export function ActionFilterRow({}}- updateFilterMath({- index,- type: filter.type,- ...mathProperties,- })+ updateSeriesMath(index, mathProperties)}const onMathPropertySelect = (_: unknown, property: string, groupType: TaxonomicFilterGroupType): void => {- updateFilterMath({- ...filter,+ updateSeriesMath(index, {+ math,math_hogql: undefined,math_property: property,math_property_type: groupType,- index,+ math_group_type_index: mathGroupTypeIndex,})}const onMathHogQLSelect = (_: unknown, hogql: string): void => {- updateFilterMath({- ...filter,+ updateSeriesMath(index, {+ math,math_property: undefined,math_property_type: undefined,math_hogql: hogql,- index,+ math_group_type_index: mathGroupTypeIndex,})}- if (filter.type === EntityTypes.ACTIONS) {- const action = actions.find((action) => action.id === filter.id)- name = action?.name || filter.name- value = action?.id || filter.id+ const nodeKey = seriesNodeKey(node)+ if (isActionsSeriesNode(node)) {+ const action = actions.find((action) => action.id === node.id)+ name = action?.name || node.name+ value = action?.id || node.id} else {- name = filter.name || String(filter.id)- // `id` is the event actually queried — `name` can be a rename (e.g. set via the API),- // and committing it as the taxonomic value would select a non-existent event.- value = filter.id != null && filter.id !== '' ? filter.id : (filter.name ?? null)+ name = node.name || String(nodeKey)+ // The node's own key is the event actually queried — `name` can be a rename (e.g. set via+ // the API), and committing it as the taxonomic value would select a non-existent event.+ value = nodeKey != null && nodeKey !== '' ? nodeKey : (node.name ?? null)}const seriesIndicator =@@ -370,7 +364,6 @@ export function ActionFilterRow({<SeriesLetter seriesIndex={index} hasBreakdown={hasBreakdown} />)- const isDataWarehouseFilter = filter.type === EntityTypes.DATA_WAREHOUSE// A behavioral filter compiles to a person_id subquery over the events table, which a warehouse series has no key forconst behavioralFiltersEnabled =allowBehavioralPropertyFilter &&@@ -386,12 +379,9 @@ export function ActionFilterRow({// and inline-group series have no single committed row to promote.const initialGroupType = isDataWarehouseFilter? dataWarehouseGroupType- : filter.type === EntityTypes.ACTIONS+ : isActionsSeriesNode(node)? TaxonomicFilterGroupType.Actions- : filter.type === EntityTypes.EVENTS &&- !isAllEventsEntityFilter(filter) &&- filter.id != null &&- filter.id !== ''+ : isEventsSeriesNode(node) && !isAllEventsSeriesNode(node) && nodeKey != null && nodeKey !== ''? TaxonomicFilterGroupType.Events: TaxonomicFilterGroupType.SuggestedFilters@@ -404,8 +394,8 @@ export function ActionFilterRow({fullWidthtruncategroupType={initialGroupType}- value={getValue(value, filter)}- filter={filter}+ value={getValue(value, node)}+ filter={node}suggestedFiltersLabel={suggestedFiltersLabel}enableKeywordShortcutspromoteSelectedItemToFirstPosition@@ -413,7 +403,7 @@ export function ActionFilterRow({onChange={(changedValue, taxonomicGroupType, item) =>applyTaxonomicSelection(taxonomicGroupType, changedValue, item)}- renderValue={() => <EntityFilterInfo filter={filter} showIcon />}+ renderValue={() => <EntityFilterInfo filter={node} showIcon />}groupTypes={effectiveActionsTaxonomicGroupTypes}placeholder="All events"placeholderClass=""@@ -429,10 +419,10 @@ export function ActionFilterRow({/>)- const suffix = typeof customRowSuffix === 'function' ? customRowSuffix({ filter, index, onClose }) : customRowSuffix+ const suffix = typeof customRowSuffix === 'function' ? customRowSuffix({ node, index, onClose }) : customRowSuffixconst propertyFiltersButton = (- <IconWithCount key="property-filter" count={filter.properties?.length || 0} showZero={false}>+ <IconWithCount key="property-filter" count={node.properties?.length || 0} showZero={false}><LemonButtonicon={<IconFilter />}title="Show filters"@@ -440,11 +430,9 @@ export function ActionFilterRow({noPaddingactive={propertyFiltersVisible}onClick={() => {- typeof filter.order === 'number'- ? setEntityFilterVisibility(filter.order, !propertyFiltersVisible)- : undefined+ setEntityFilterVisibility(index, !propertyFiltersVisible)}}- disabledReason={filter.id === 'empty' ? 'Please select an event first' : undefined}+ disabledReason={nodeKey === 'empty' ? 'Please select an event first' : undefined}tooltip="Show filters"tooltipDocLink={addFilterDocLink}/>@@ -462,7 +450,7 @@ export function ActionFilterRow({data-attr={`show-prop-rename-${index}`}noPadding={!enablePopup}onClick={() => {- selectFilter(filter)+ selectSeries(index, node, uuid)onRenameClick()}}fullWidth={enablePopup}@@ -479,7 +467,7 @@ export function ActionFilterRow({data-attr={`show-prop-duplicate-${index}`}noPadding={!enablePopup}onClick={() => {- duplicateFilter(filter)+ duplicateSeries(index)}}fullWidth={enablePopup}>@@ -494,7 +482,7 @@ export function ActionFilterRow({data-attr={`show-prop-combine-${index}`}noPadding={!enablePopup}onClick={() => {- convertFilterToGroup(index)+ convertToGroup(index)posthog.capture('combine_events', {insight_type: insightType,team_id: currentTeamId,@@ -621,7 +609,7 @@ export function ActionFilterRow({// event series can leave a stale non-warehouse group on the filter.isDataWarehouseFilter? TaxonomicFilterGroupType.DataWarehouseProperties- : mathPropertyType ||+ : (mathPropertyType as TaxonomicFilterGroupType) ||TaxonomicFilterGroupType.NumericalEventProperties}mathPropertyTypes={@@ -640,9 +628,9 @@ export function ActionFilterRow({onMathPropertySelect={onMathPropertySelect}showNumericalPropsOnly={isBoxPlotContext || showNumericalPropsOnly}schemaColumns={- isDataWarehouseFilter && filter.name+ isDataWarehouseFilter && node.name? Object.values(- dataWarehouseTablesMap[filter.name]?.fields ?? []+ dataWarehouseTablesMap[node.name]?.fields ?? []).filter((field) =>!(isBoxPlotContext || showNumericalPropsOnly) ||@@ -687,18 +675,14 @@ export function ActionFilterRow({trendsDisplayCategory={trendsDisplayCategory}readOnly={readOnly}query={query || {}}- filter={filter}+ filter={node}hideRename={!!hideRename}hideDuplicate={hideDuplicate}hideDeleteBtn={hideDeleteBtn}singleFilter={!!singleFilter}onMathSelect={onMathSelect}onUpdateOptional={(checked) => {- updateFilterOptional({- ...filter,- optionalInFunnel: checked,- index,- })+ updateSeriesOptional(index, checked)}}renameRowButton={renameRowButton}duplicateRowButton={duplicateRowButton}@@ -719,15 +703,17 @@ export function ActionFilterRow({<div className={`ActionFilterRow-filters${filtersLeftPadding ? ' pl-7' : ''}`}><PropertyFilterspageKey={`${index}-${value}-${typeKey}-filter`}- propertyFilters={filter.properties}+ propertyFilters={node.properties}onChange={onPropertyChange}showNestedArrow={showNestedArrow}disablePopover={!propertyFiltersPopover}metadataSource={- isDataWarehouseFilter+ isWarehouseSeriesNode(node)? {kind: NodeKind.HogQLQuery,- query: `select ${filter.aggregation_target_field} from ${filter.table_name}`,+ query: `select ${+ (node as { aggregation_target_field?: string }).aggregation_target_field+ } from ${node.table_name}`,}: undefined}@@ -740,18 +726,18 @@ export function ActionFilterRow({: propertiesTaxonomicGroupTypes}eventNames={- filter.type === TaxonomicFilterGroupType.Events && filter.id- ? [String(filter.id)]- : filter.type === TaxonomicFilterGroupType.Actions && filter.id- ? getEventNamesForAction(parseInt(String(filter.id)), actions)+ isEventsSeriesNode(node) && node.event+ ? [String(node.event)]+ : isActionsSeriesNode(node) && node.id+ ? getEventNamesForAction(node.id, actions): []}schemaColumns={- isDataWarehouseFilter && filter.name- ? Object.values(dataWarehouseTablesMap[filter.name]?.fields ?? [])+ isDataWarehouseFilter && node.name+ ? Object.values(dataWarehouseTablesMap[node.name]?.fields ?? []): []}- dataWarehouseTableName={isDataWarehouseFilter ? (filter.name ?? undefined) : undefined}+ dataWarehouseTableName={isDataWarehouseFilter ? (node.name ?? undefined) : undefined}addFilterDocLink={addFilterDocLink}excludedProperties={excludedProperties}hogQLGlobals={hogQLGlobals}@@ -770,7 +756,7 @@ export function ActionFilterRow({: null}/>- <SaveAsActionBanner filter={filter} />+ <SaveAsActionBanner node={node} /></div>)}</li>diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/SaveAsActionBanner.test.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/SaveAsActionBanner.test.tsxindex 172b854fe01f..8b44ec6068c6 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/SaveAsActionBanner.test.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/SaveAsActionBanner.test.tsx@@ -6,17 +6,18 @@ import { Provider } from 'kea'import { useMocks } from '~/mocks/jest'import { actionsModel } from '~/models/actionsModel'+import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { EntityTypes, PropertyFilterType, PropertyOperator } from '~/types'+import { PropertyFilterType, PropertyOperator } from '~/types'-import { LocalFilter } from '../entityFilterLogic'+import { SeriesNode } from '../seriesNode'import { SaveAsActionBanner } from './SaveAsActionBanner'-import { makeFilter } from './testHelpers'+import { makeSeriesNode } from './testHelpers'-function renderBanner(filter: LocalFilter): ReturnType<typeof render> {+function renderBanner(node: SeriesNode): ReturnType<typeof render> {return render(<Provider>- <SaveAsActionBanner filter={filter} />+ <SaveAsActionBanner node={node} /></Provider>)}@@ -45,7 +46,7 @@ describe('SaveAsActionBanner', () => {it.each([['autocapture with $el_text',- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',@@ -58,7 +59,7 @@ describe('SaveAsActionBanner', () => {],['autocapture with selector',- makeFilter({+ makeSeriesNode({properties: [{key: 'selector',@@ -71,7 +72,7 @@ describe('SaveAsActionBanner', () => {],['autocapture with text and selector',- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',@@ -94,10 +95,10 @@ describe('SaveAsActionBanner', () => {})it.each([- ['non-autocapture event', makeFilter({ id: '$pageview', name: '$pageview' })],+ ['non-autocapture event', makeSeriesNode({ event: '$pageview', name: '$pageview' })],['autocapture with no element properties',- makeFilter({+ makeSeriesNode({properties: [{key: '$browser',@@ -108,11 +109,11 @@ describe('SaveAsActionBanner', () => {],}),],- ['autocapture with empty properties', makeFilter({ properties: [] })],- ['action type', makeFilter({ id: '123', name: 'My Action', type: EntityTypes.ACTIONS })],+ ['autocapture with empty properties', makeSeriesNode({ properties: [] })],+ ['action type', makeSeriesNode({ kind: NodeKind.ActionsNode, id: 123, name: 'My Action' })],['autocapture with only negated operators',- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',@@ -132,7 +133,7 @@ describe('SaveAsActionBanner', () => {describe('Save as action button', () => {it('opens the shared save-as-action dialog when clicked', async () => {renderBanner(- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',@@ -155,7 +156,7 @@ describe('SaveAsActionBanner', () => {describe('dismissal', () => {it('hides the banner when close button is clicked', async () => {const { container } = renderBanner(- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/SaveAsActionBanner.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/SaveAsActionBanner.tsxindex e2ed7a4b08b3..64fead9e538f 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/SaveAsActionBanner.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/SaveAsActionBanner.tsx@@ -1,17 +1,17 @@import { LemonBanner } from '@posthog/lemon-ui'import { PostHogCaptureOnViewed } from '@posthog/react'-import { saveActionFromFilter } from '~/models/saveAsActionDialog'+import { saveActionFromSeriesNode } from '~/models/saveAsActionDialog'-import { LocalFilter } from '../entityFilterLogic'-import { isAutocaptureFilterWithElements } from './saveAsActionUtils'+import { SeriesNode } from '../seriesNode'+import { isAutocaptureSeriesWithElements } from './saveAsActionUtils'interface SaveAsActionBannerProps {- filter: LocalFilter+ node: SeriesNode}-export function SaveAsActionBanner({ filter }: SaveAsActionBannerProps): JSX.Element | null {- if (!isAutocaptureFilterWithElements(filter)) {+export function SaveAsActionBanner({ node }: SaveAsActionBannerProps): JSX.Element | null {+ if (!isAutocaptureSeriesWithElements(node)) {return null}@@ -23,7 +23,7 @@ export function SaveAsActionBanner({ filter }: SaveAsActionBannerProps): JSX.EledismissKey="autocapture-save-as-action-nudge"action={{children: 'Save as action',- onClick: () => saveActionFromFilter(filter),+ onClick: () => saveActionFromSeriesNode(node),'data-attr': 'autocapture-save-as-action',}}>diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/actionFilterRowUtils.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/actionFilterRowUtils.tsindex 53eb54dce8ef..657a07e72b86 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/actionFilterRowUtils.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/actionFilterRowUtils.ts@@ -1,20 +1,37 @@import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { isAllEventsEntityFilter } from 'scenes/insights/utils'-import { ActionFilter, EntityType, EntityTypes } from '~/types'+import { NodeKind } from '~/queries/schema/schema-general'+import { EntityType, EntityTypes } from '~/types'++import {+ SeriesNode,+ WarehouseSeriesNodeKind,+ isActionsSeriesNode,+ isAllEventsSeriesNode,+ seriesNodeKindForEntityType,+} from '../seriesNode'export const getValue = (value: string | number | null | undefined,- filter: ActionFilter+ node: SeriesNode): string | number | null | undefined => {- if (isAllEventsEntityFilter(filter)) {+ if (isAllEventsSeriesNode(node)) {return 'All events'- } else if (filter.type === 'actions') {+ } else if (isActionsSeriesNode(node)) {return typeof value === 'string' ? parseInt(value) : value || undefined}return value === null ? null : value || undefined}+/** The node kind a taxonomic group commits to, with the warehouse groups landing on the kind+ * the caller asked the editor to create. */+export function taxonomicGroupTypeToSeriesNodeKind(+ taxonomicFilterGroupType: TaxonomicFilterGroupType,+ warehouseKind: WarehouseSeriesNodeKind = NodeKind.DataWarehouseNode+): SeriesNode['kind'] {+ return seriesNodeKindForEntityType(taxonomicFilterGroupTypeToEntityType(taxonomicFilterGroupType), warehouseKind)+}+const taxonomicFilterGroupTypeToEntityTypeMapping: Partial<Record<TaxonomicFilterGroupType, EntityTypes>> = {[TaxonomicFilterGroupType.Events]: EntityTypes.EVENTS,[TaxonomicFilterGroupType.Actions]: EntityTypes.ACTIONS,diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.test.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.test.tsindex a4d898f825a8..141eb1a47d3b 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.test.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.test.ts@@ -1,19 +1,20 @@-import { AnyPropertyFilter, EntityTypes, PropertyFilterType, PropertyOperator } from '~/types'+import { NodeKind } from '~/queries/schema/schema-general'+import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'import {- filterToActionStep,- generateActionNameFromFilter,- isAutocaptureFilterWithElements,+ generateActionNameFromSeriesNode,+ isAutocaptureSeriesWithElements,operatorToStringMatching,+ seriesNodeToActionStep,} from './saveAsActionUtils'-import { makeFilter } from './testHelpers'+import { makeSeriesNode } from './testHelpers'describe('saveAsActionUtils', () => {- describe('isAutocaptureFilterWithElements', () => {+ describe('isAutocaptureSeriesWithElements', () => {it.each([['autocapture with $el_text property',- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',@@ -27,7 +28,7 @@ describe('saveAsActionUtils', () => {],['autocapture with element text property',- makeFilter({+ makeSeriesNode({properties: [{key: 'text',@@ -41,7 +42,7 @@ describe('saveAsActionUtils', () => {],['autocapture with selector property',- makeFilter({+ makeSeriesNode({properties: [{key: 'selector',@@ -55,7 +56,7 @@ describe('saveAsActionUtils', () => {],['autocapture with href property',- makeFilter({+ makeSeriesNode({properties: [{key: 'href',@@ -69,7 +70,7 @@ describe('saveAsActionUtils', () => {],['autocapture with no element properties',- makeFilter({+ makeSeriesNode({properties: [{key: '$browser',@@ -81,10 +82,10 @@ describe('saveAsActionUtils', () => {}),false,],- ['autocapture with empty properties', makeFilter({ properties: [] }), false],+ ['autocapture with empty properties', makeSeriesNode({ properties: [] }), false],['autocapture with only negated element operators',- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',@@ -98,7 +99,7 @@ describe('saveAsActionUtils', () => {],['selector with regex operator (no matching field to store it)',- makeFilter({+ makeSeriesNode({properties: [{key: 'selector',@@ -112,7 +113,7 @@ describe('saveAsActionUtils', () => {],['selector with icontains operator (no matching field to store it)',- makeFilter({+ makeSeriesNode({properties: [{key: 'selector',@@ -126,8 +127,8 @@ describe('saveAsActionUtils', () => {],['non-autocapture event with element-like properties',- makeFilter({- id: '$pageview',+ makeSeriesNode({+ event: '$pageview',name: '$pageview',properties: [{@@ -142,10 +143,10 @@ describe('saveAsActionUtils', () => {],['action type filter',- makeFilter({- id: '123',+ makeSeriesNode({+ kind: NodeKind.ActionsNode,+ id: 123,name: 'My Action',- type: EntityTypes.ACTIONS,properties: [{key: '$el_text',@@ -158,7 +159,7 @@ describe('saveAsActionUtils', () => {false,],])('%s → %s', (_description, filter, expected) => {- expect(isAutocaptureFilterWithElements(filter)).toBe(expected)+ expect(isAutocaptureSeriesWithElements(filter)).toBe(expected)})})@@ -178,9 +179,9 @@ describe('saveAsActionUtils', () => {})})- describe('filterToActionStep', () => {+ describe('seriesNodeToActionStep', () => {it('converts $el_text property to text field', () => {- const filter = makeFilter({+ const filter = makeSeriesNode({properties: [{key: '$el_text',@@ -190,7 +191,7 @@ describe('saveAsActionUtils', () => {},],})- expect(filterToActionStep(filter)).toEqual({+ expect(seriesNodeToActionStep(filter)).toEqual({event: '$autocapture',text: 'Submit',text_matching: 'exact',@@ -198,7 +199,7 @@ describe('saveAsActionUtils', () => {})it('converts element text property to text field', () => {- const filter = makeFilter({+ const filter = makeSeriesNode({properties: [{key: 'text',@@ -208,7 +209,7 @@ describe('saveAsActionUtils', () => {},],})- expect(filterToActionStep(filter)).toEqual({+ expect(seriesNodeToActionStep(filter)).toEqual({event: '$autocapture',text: 'Click me',text_matching: 'contains',@@ -216,7 +217,7 @@ describe('saveAsActionUtils', () => {})it('converts selector property', () => {- const filter = makeFilter({+ const filter = makeSeriesNode({properties: [{key: 'selector',@@ -226,14 +227,14 @@ describe('saveAsActionUtils', () => {},],})- expect(filterToActionStep(filter)).toEqual({+ expect(seriesNodeToActionStep(filter)).toEqual({event: '$autocapture',selector: '.btn-primary',})})it('converts href property', () => {- const filter = makeFilter({+ const filter = makeSeriesNode({properties: [{key: 'href',@@ -243,7 +244,7 @@ describe('saveAsActionUtils', () => {},],})- expect(filterToActionStep(filter)).toEqual({+ expect(seriesNodeToActionStep(filter)).toEqual({event: '$autocapture',href: '/signup',href_matching: 'regex',@@ -251,7 +252,7 @@ describe('saveAsActionUtils', () => {})it('combines multiple element properties', () => {- const filter = makeFilter({+ const filter = makeSeriesNode({properties: [{key: '$el_text',@@ -267,7 +268,7 @@ describe('saveAsActionUtils', () => {},],})- expect(filterToActionStep(filter)).toEqual({+ expect(seriesNodeToActionStep(filter)).toEqual({event: '$autocapture',text: 'Submit',text_matching: 'exact',@@ -282,7 +283,7 @@ describe('saveAsActionUtils', () => {operator: PropertyOperator.Exact,type: PropertyFilterType.Event,}- const filter = makeFilter({+ const filter = makeSeriesNode({properties: [{key: '$el_text',@@ -293,7 +294,7 @@ describe('saveAsActionUtils', () => {browserProp,],})- const result = filterToActionStep(filter)+ const result = seriesNodeToActionStep(filter)expect(result.text).toBe('Submit')expect(result.properties).toEqual([browserProp])})@@ -305,10 +306,10 @@ describe('saveAsActionUtils', () => {operator: PropertyOperator.NotIContains,type: PropertyFilterType.Event,}- const filter = makeFilter({+ const filter = makeSeriesNode({properties: [negatedProp],})- const result = filterToActionStep(filter)+ const result = seriesNodeToActionStep(filter)expect(result.text).toBeUndefined()expect(result.properties).toEqual([negatedProp])})@@ -320,10 +321,10 @@ describe('saveAsActionUtils', () => {operator: PropertyOperator.Exact,type: PropertyFilterType.Event,}- const filter = makeFilter({+ const filter = makeSeriesNode({properties: [arrayProp],})- const result = filterToActionStep(filter)+ const result = seriesNodeToActionStep(filter)expect(result.text).toBeUndefined()expect(result.properties).toEqual([arrayProp])})@@ -335,7 +336,7 @@ describe('saveAsActionUtils', () => {operator: PropertyOperator.Exact,type: PropertyFilterType.Event,}- const filter = makeFilter({+ const filter = makeSeriesNode({properties: [{key: '$el_text',@@ -346,17 +347,17 @@ describe('saveAsActionUtils', () => {secondTextProp,],})- const result = filterToActionStep(filter)+ const result = seriesNodeToActionStep(filter)expect(result.text).toBe('Submit')expect(result.properties).toEqual([secondTextProp])})})- describe('generateActionNameFromFilter', () => {+ describe('generateActionNameFromSeriesNode', () => {it.each([['text property',- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',@@ -370,7 +371,7 @@ describe('saveAsActionUtils', () => {],['selector property',- makeFilter({+ makeSeriesNode({properties: [{key: 'selector',@@ -384,7 +385,7 @@ describe('saveAsActionUtils', () => {],['href property',- makeFilter({+ makeSeriesNode({properties: [{key: 'href',@@ -398,7 +399,7 @@ describe('saveAsActionUtils', () => {],['text takes priority over selector',- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',@@ -418,7 +419,7 @@ describe('saveAsActionUtils', () => {],['array value uses first element',- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',@@ -432,7 +433,7 @@ describe('saveAsActionUtils', () => {],['skips negated props and uses next valid prop for name',- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',@@ -450,10 +451,10 @@ describe('saveAsActionUtils', () => {}),'Autocapture: .btn',],- ['empty properties', makeFilter({ properties: [] }), 'Autocapture action'],+ ['empty properties', makeSeriesNode({ properties: [] }), 'Autocapture action'],['properties with empty values',- makeFilter({+ makeSeriesNode({properties: [{key: '$el_text',@@ -466,12 +467,12 @@ describe('saveAsActionUtils', () => {'Autocapture action',],])('%s → %s', (_description, filter, expected) => {- expect(generateActionNameFromFilter(filter)).toBe(expected)+ expect(generateActionNameFromSeriesNode(filter)).toBe(expected)})it('truncates long values', () => {const longText = 'a'.repeat(100)- const filter = makeFilter({+ const filter = makeSeriesNode({properties: [{key: '$el_text',@@ -481,7 +482,7 @@ describe('saveAsActionUtils', () => {},],})- const name = generateActionNameFromFilter(filter)+ const name = generateActionNameFromSeriesNode(filter)expect(name.length).toBeLessThan(70)expect(name).toContain('...')})diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.tsindex 66051df02feb..09c7cbfb9dfb 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/saveAsActionUtils.ts@@ -4,12 +4,11 @@ import {ActionStepStringMatching,ActionStepType,AnyPropertyFilter,- EntityTypes,PropertyFilterType,PropertyOperator,} from '~/types'-import { LocalFilter } from '../entityFilterLogic'+import { SeriesNode, isEventsSeriesNode } from '../seriesNode'interface ElementKeyMapping {stepField: 'text' | 'selector' | 'href'@@ -71,11 +70,11 @@ function canMapToActionStep(prop: AnyPropertyFilter): boolean {return operator === undefined || operator === PropertyOperator.Exact}-export function isAutocaptureFilterWithElements(filter: LocalFilter): boolean {- if (filter.id !== '$autocapture' || filter.type !== EntityTypes.EVENTS) {+export function isAutocaptureSeriesWithElements(node: SeriesNode): boolean {+ if (!isEventsSeriesNode(node) || node.event !== '$autocapture') {return false}- return (filter.properties ?? []).some(canMapToActionStep)+ return (node.properties ?? []).some(canMapToActionStep)}export function operatorToStringMatching(operator: PropertyOperator | undefined): ActionStepStringMatching | null {@@ -103,11 +102,11 @@ function extractStringValue(prop: AnyPropertyFilter): string {return Array.isArray(raw) ? String(raw[0] ?? '') : String(raw)}-export function filterToActionStep(filter: LocalFilter): ActionStepType {+export function seriesNodeToActionStep(node: SeriesNode): ActionStepType {const step: ActionStepType = { event: '$autocapture' }const remainingProperties: AnyPropertyFilter[] = []- for (const prop of filter.properties ?? []) {+ for (const prop of node.properties ?? []) {const value = extractStringValue(prop)const operator = 'operator' in prop ? prop.operator : undefinedconst matching = operatorToStringMatching(operator)@@ -132,8 +131,8 @@ export function filterToActionStep(filter: LocalFilter): ActionStepType {const MAX_NAME_VALUE_LENGTH = 50-export function generateActionNameFromFilter(filter: LocalFilter): string {- for (const prop of filter.properties ?? []) {+export function generateActionNameFromSeriesNode(node: SeriesNode): string {+ for (const prop of node.properties ?? []) {if (!canMapToActionStep(prop)) {continue}diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/testHelpers.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/testHelpers.tsindex f5e7605e3392..a55864c0ccbe 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/testHelpers.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/testHelpers.ts@@ -1,15 +1,13 @@-import { EntityTypes } from '~/types'+import { EventsNode, NodeKind } from '~/queries/schema/schema-general'-import { LocalFilter } from '../entityFilterLogic'+import { SeriesNode } from '../seriesNode'-export function makeFilter(overrides: Partial<LocalFilter> = {}): LocalFilter {+export function makeSeriesNode(overrides: Partial<SeriesNode> = {}): SeriesNode {return {- id: '$autocapture',+ kind: NodeKind.EventsNode,+ event: '$autocapture',name: '$autocapture',- type: EntityTypes.EVENTS,- order: 0,- uuid: 'test-uuid',properties: [],...overrides,- }+ } as EventsNode}diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/types.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/types.tsindex 8bb273ae8051..cff9d5b4f5f9 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/types.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/types.ts@@ -7,16 +7,10 @@ import {} from 'lib/components/TaxonomicFilter/types'import { LemonButtonProps } from 'lib/lemon-ui/LemonButton'-import {- ActionFilter as ActionFilterType,- ChartDisplayCategory,- FunnelExclusionLegacy,- InsightType,- PropertyOperator,-} from '~/types'+import { ChartDisplayCategory, InsightType, PropertyOperator } from '~/types'-import { LocalFilter } from '../entityFilterLogic'import type { entityFilterLogicType } from '../entityFilterLogic'+import { SeriesNode, WarehouseSeriesNodeKind } from '../seriesNode'export enum MathAvailability {All,@@ -29,7 +23,9 @@ export enum MathAvailability {export interface ActionFilterRowProps {logic: BuiltLogic<entityFilterLogicType>- filter: LocalFilter+ node: SeriesNode+ /** Sidecar row identity, for the drag key. Nodes stay schema-pure so they carry none. */+ uuid: stringindex: numbertypeKey: stringmathAvailability: MathAvailability@@ -52,11 +48,7 @@ export interface ActionFilterRowProps {customRowSuffix?:| string| JSX.Element- | ((props: {- filter: ActionFilterType | FunnelExclusionLegacy- index: number- onClose: () => void- }) => JSX.Element) // Custom suffix element to show in each row+ | ((props: { node: SeriesNode; index: number; onClose: () => void }) => JSX.Element) // Custom suffix element to show in each rowhasBreakdown: boolean // Whether the current graph has a breakdown filter appliedshowNestedArrow?: boolean // Show nested arrows to the left of property filter buttonsactionsTaxonomicGroupTypes?: TaxonomicFilterGroupType[] // Which tabs to show for actions selector@@ -78,6 +70,8 @@ export interface ActionFilterRowProps {allowedMathTypes?: readonly string[]/** Fields to display in the data warehouse filter popover */dataWarehousePopoverFields?: DataWarehousePopoverField[]+ /** Node kind to create when a data warehouse table is picked */+ dataWarehouseNodeKind?: WarehouseSeriesNodeKind/** Whether to add left padding to the filters div to align with suffix content */filtersLeftPadding?: boolean/** Doc link to show in the tooltip of the New Filter button */diff --git a/frontend/src/scenes/insights/filters/ActionFilter/RenameModal.tsx b/frontend/src/scenes/insights/filters/ActionFilter/RenameModal.tsxindex d439fce01bb9..2501136519fb 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/RenameModal.tsx+++ b/frontend/src/scenes/insights/filters/ActionFilter/RenameModal.tsx@@ -4,7 +4,7 @@ import { LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'import { renameModalLogic } from 'scenes/insights/filters/ActionFilter/renameModalLogic'-import { getDisplayNameFromEntityFilter } from 'scenes/insights/utils'+import { getDisplayNameFromEntityNode } from 'scenes/insights/utils'import { InsightType } from '~/types'@@ -14,10 +14,11 @@ interface RenameModalProps {}export function RenameModal({ typeKey, view }: RenameModalProps): JSX.Element {- const { selectedFilter, modalVisible } = useValues(entityFilterLogic)- const { renameFilter, hideModal } = useActions(entityFilterLogic)+ const { selectedSeries, modalVisible } = useValues(entityFilterLogic)+ const { renameSeries, hideModal } = useActions(entityFilterLogic)- const logic = renameModalLogic({ typeKey, filter: selectedFilter })+ const selectedNode = selectedSeries?.node ?? null+ const logic = renameModalLogic({ typeKey, node: selectedNode })const { name } = useValues(logic)const { setName } = useActions(logic)@@ -35,7 +36,7 @@ export function RenameModal({ typeKey, view }: RenameModalProps): JSX.Element {<LemonButton type="secondary" onClick={hideModal}>Cancel</LemonButton>- <LemonButton type="primary" onClick={() => renameFilter(name)}>+ <LemonButton type="primary" onClick={() => renameSeries(name)}>{title}</LemonButton></>@@ -48,14 +49,14 @@ export function RenameModal({ typeKey, view }: RenameModalProps): JSX.Element {<div className="l4 mt-2 mb-2">Name</div><LemonInputvalue={name}- onPressEnter={() => renameFilter(name)}+ onPressEnter={() => renameSeries(name)}onChange={(value) => setName(value)}suffix={<spanclassName="text-secondary truncate max-w-[200px]"- title={getDisplayNameFromEntityFilter(selectedFilter, false) ?? ''}+ title={(selectedNode ? getDisplayNameFromEntityNode(selectedNode, false) : null) ?? ''}>- {getDisplayNameFromEntityFilter(selectedFilter, false) ?? ''}+ {(selectedNode ? getDisplayNameFromEntityNode(selectedNode, false) : null) ?? ''}</span>}autoFocusdiff --git a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.ts b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.tsindex 1d1e7ed3cd27..dc0e94ea0716 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.test.ts@@ -2,14 +2,19 @@ import { expectLogic } from 'kea-test-utils'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import * as libUtils from 'lib/utils/dom'-import { LocalFilter, entityFilterLogic, toLocalFilters } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'+import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'import { useMocks } from '~/mocks/jest'+import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'import { AnyPropertyFilter, FilterType, PropertyFilterType, PropertyOperator } from '~/types'import eventDefinitionsJson from './__mocks__/event_definitions.json'import filtersJson from './__mocks__/filters.json'+import { legacyFiltersToSeries } from './legacyFilters'+import { SeriesNode } from './seriesNode'++const baseSeries = (): SeriesNode[] => legacyFiltersToSeries(filtersJson as FilterType)describe('entityFilterLogic', () => {let logic: ReturnType<typeof entityFilterLogic.build>@@ -26,79 +31,66 @@ describe('entityFilterLogic', () => {})initKeaTests()logic = entityFilterLogic({- setFilters: jest.fn(),- filters: filtersJson,+ onChange: jest.fn(),+ series: baseSeries(),typeKey: 'logic_test',})logic.mount()})describe('core assumptions', () => {- it('localFilters', async () => {+ it('series', async () => {await expectLogic(logic).toMatchValues({- localFilters: toLocalFilters(filtersJson as FilterType),+ series: baseSeries(),})})})- describe('renaming filters', () => {+ describe('renaming series', () => {it('renames successfully', async () => {- // Select a filter to rename firstawait expectLogic(logic, () => {- logic.actions.selectFilter({- id: '$pageview',- name: '$pageview',- order: 0,- })+ logic.actions.selectSeries(0, logic.values.series[0], logic.values.localSeries[0].uuid)})await expectLogic(logic, () => {- logic.actions.renameFilter('Custom event name')- }).toDispatchActions(['renameFilter', 'updateFilter', 'setFilters'])-- expect(logic.props.setFilters).toHaveBeenCalledWith(- expect.objectContaining({- events: expect.arrayContaining([- expect.objectContaining({- custom_name: 'Custom event name',- }),- ]),- })+ logic.actions.renameSeries('Custom event name')+ }).toDispatchActions(['renameSeries', 'setLocalSeries'])++ expect(logic.props.onChange).toHaveBeenCalledWith(+ expect.arrayContaining([+ expect.objectContaining({+ custom_name: 'Custom event name',+ }),+ ]))})it('applies the rename and closes the modal without yielding', () => {- logic.actions.selectFilter(logic.values.localFilters[0])+ logic.actions.selectSeries(0, logic.values.series[0], logic.values.localSeries[0].uuid)logic.actions.showModal()- logic.actions.renameFilter('Custom event name')+ logic.actions.renameSeries('Custom event name')- expect(logic.values.localFilters[0].custom_name).toEqual('Custom event name')+ expect(logic.values.series[0].custom_name).toEqual('Custom event name')expect(logic.values.modalVisible).toBe(false)})it('closes the modal when no series is selected', () => {logic.actions.showModal()- logic.actions.renameFilter('Custom event name')+ logic.actions.renameSeries('Custom event name')expect(logic.values.modalVisible).toBe(false)})it('does not rename another series when the selected series is removed', () => {- const selectedFilter = logic.values.localFilters[0]- const replacementFilter = {- ...logic.values.localFilters[1],- order: selectedFilter.order,- uuid: 'replacement-uuid',- }- logic.actions.selectFilter(selectedFilter)+ logic.actions.selectSeries(0, logic.values.series[0], logic.values.localSeries[0].uuid)logic.actions.showModal()- logic.actions.setFilters([replacementFilter])+ logic.actions.setLocalSeries([{ uuid: 'replacement-uuid', node: logic.values.series[1] }])- logic.actions.renameFilter('Custom event name')+ logic.actions.renameSeries('Custom event name')- expect(logic.values.localFilters[0].custom_name).not.toEqual('Custom event name')+ expect(logic.values.series[0].custom_name).not.toEqual('Custom event name')expect(logic.values.modalVisible).toBe(false)})})@@ -121,7 +113,7 @@ describe('entityFilterLogic', () => {})})- describe('setLocalFilters preserves UUIDs', () => {+ describe('setSeries preserves UUIDs', () => {let uuidCounter: numberbeforeEach(() => {@@ -130,109 +122,107 @@ describe('entityFilterLogic', () => {logic.unmount()logic = entityFilterLogic({- setFilters: jest.fn(),- filters: filtersJson,+ onChange: jest.fn(),+ series: baseSeries(),typeKey: 'uuid_test',})logic.mount()})- it('preserves UUIDs when called with identical filters', () => {- const originalUuids = logic.values.localFilters.map((f) => f.uuid)+ it('preserves UUIDs when called with identical series', () => {+ const originalUuids = logic.values.localSeries.map((l) => l.uuid)++ logic.actions.setSeries(baseSeries())++ expect(logic.values.localSeries.map((l) => l.uuid)).toEqual(originalUuids)+ })++ it('preserves existing UUIDs when a series is added', () => {+ const originalUuids = logic.values.localSeries.map((l) => l.uuid)- logic.actions.setLocalFilters(filtersJson as FilterType)+ logic.actions.setSeries([+ ...baseSeries(),+ { kind: NodeKind.EventsNode, event: '$autocapture', name: '$autocapture' },+ ])- expect(logic.values.localFilters.map((f) => f.uuid)).toEqual(originalUuids)+ const newSeries = logic.values.localSeries+ expect(newSeries).toHaveLength(4)+ expect(newSeries[0].uuid).toBe(originalUuids[0])+ expect(newSeries[1].uuid).toBe(originalUuids[1])+ expect(newSeries[2].uuid).toBe(originalUuids[2])+ expect(originalUuids).not.toContain(newSeries[3].uuid)})- it('preserves existing UUIDs when a filter is added', () => {- const originalUuids = logic.values.localFilters.map((f) => f.uuid)+ it('keeps each surviving row on its own uuid when a series is removed', () => {+ const originalUuids = logic.values.localSeries.map((l) => l.uuid)- logic.actions.setLocalFilters({- ...filtersJson,- events: [...filtersJson.events, { id: '$autocapture', name: '$autocapture', type: 'events', order: 3 }],- } as FilterType)+ logic.actions.removeSeries(0)- const newFilters = logic.values.localFilters- expect(newFilters).toHaveLength(4)- expect(newFilters[0].uuid).toBe(originalUuids[0])- expect(newFilters[1].uuid).toBe(originalUuids[1])- expect(newFilters[2].uuid).toBe(originalUuids[2])- expect(originalUuids).not.toContain(newFilters[3].uuid)+ // Rebuilding the uuids by index would shift every row's identity up by one, which+ // moves open property panels and drag handles onto the wrong series.+ expect(logic.values.localSeries.map((l) => l.uuid)).toEqual(originalUuids.slice(1))})- it('preserves UUIDs for remaining filters when one is removed', () => {- const originalUuids = logic.values.localFilters.map((f) => f.uuid)+ it('preserves UUIDs for remaining series when one is removed', () => {+ const originalUuids = logic.values.localSeries.map((l) => l.uuid)+ const remaining = baseSeries().filter((_, index) => index !== 0)- logic.actions.setLocalFilters({- ...filtersJson,- events: [filtersJson.events[1]],- } as FilterType)+ logic.actions.setSeries(remaining)- const newFilters = logic.values.localFilters- expect(newFilters).toHaveLength(2)- expect(originalUuids).toContain(newFilters[0].uuid)- expect(originalUuids).toContain(newFilters[1].uuid)+ const newSeries = logic.values.localSeries+ expect(newSeries).toHaveLength(2)+ expect(originalUuids).toContain(newSeries[0].uuid)+ expect(originalUuids).toContain(newSeries[1].uuid)})})- describe('updateFilterMath preserves math_property_type', () => {+ describe('updateSeriesMath preserves math_property_type', () => {it('keeps math_property_type when updating math', async () => {await expectLogic(logic, () => {- logic.actions.updateFilterMath({- index: 0,- type: 'events',+ logic.actions.updateSeriesMath(0, {math: 'median',math_property: '$session_duration',math_property_type: TaxonomicFilterGroupType.SessionProperties,})- }).toDispatchActions(['updateFilterMath', 'setFilters'])-- expect(logic.props.setFilters).toHaveBeenCalledWith(- expect.objectContaining({- events: expect.arrayContaining([- expect.objectContaining({- math: 'median',- math_property: '$session_duration',- math_property_type: TaxonomicFilterGroupType.SessionProperties,- }),- ]),- })+ }).toDispatchActions(['updateSeriesMath', 'setLocalSeries'])++ expect(logic.props.onChange).toHaveBeenCalledWith(+ expect.arrayContaining([+ expect.objectContaining({+ math: 'median',+ math_property: '$session_duration',+ math_property_type: TaxonomicFilterGroupType.SessionProperties,+ }),+ ]))})it('clears math_property_type when math is cleared', async () => {- logic.actions.updateFilterMath({- index: 0,- type: 'events',+ logic.actions.updateSeriesMath(0, {math: 'median',math_property: '$session_duration',math_property_type: TaxonomicFilterGroupType.SessionProperties,})await expectLogic(logic, () => {- logic.actions.updateFilterMath({- index: 0,- type: 'events',+ logic.actions.updateSeriesMath(0, {math: undefined,math_property: undefined,math_property_type: undefined,})- }).toDispatchActions(['updateFilterMath', 'setFilters'])-- expect(logic.props.setFilters).toHaveBeenLastCalledWith(- expect.objectContaining({- events: expect.arrayContaining([- expect.objectContaining({- math_property_type: undefined,- }),- ]),- })+ }).toDispatchActions(['updateSeriesMath', 'setLocalSeries'])++ expect(logic.props.onChange).toHaveBeenLastCalledWith(+ expect.arrayContaining([+ expect.objectContaining({+ math_property_type: undefined,+ }),+ ]))})})- describe('updateFilter across entity types', () => {+ describe('updateSeriesEntity across node kinds', () => {const personProperty: AnyPropertyFilter = {key: 'email',value: '[email protected]',@@ -256,82 +246,75 @@ describe('entityFilterLogic', () => {type: PropertyFilterType.HogQL,}- const eventFilter: LocalFilter = {- id: '$pageview',+ const eventNode = {+ kind: NodeKind.EventsNode,+ event: '$pageview',name: '$pageview',- type: 'events',- order: 0,- uuid: 'uuid-0',properties: [personProperty, extendedPersonProperty, dwColumnProperty, hogqlProperty],- }- const dataWarehouseFilter: LocalFilter = {+ } as SeriesNode+ const dataWarehouseNode = {+ kind: NodeKind.DataWarehouseNode,id: 'payments',name: 'payments',- type: 'data_warehouse',table_name: 'payments',- order: 0,- uuid: 'uuid-0',properties: [dwColumnProperty, hogqlProperty],- }+ } as SeriesNodeconst switchToPayments = {- type: 'data_warehouse',- id: 'payments',+ kind: NodeKind.DataWarehouseNode,+ key: 'payments',name: 'payments',- table_name: 'payments',}it.each([['drops person-scoped filters when an event becomes a data warehouse series',- eventFilter,+ eventNode,switchToPayments,[hogqlProperty],],['drops column filters when a data warehouse series becomes an event',- dataWarehouseFilter,- { type: 'events', id: '$pageview', name: '$pageview' },+ dataWarehouseNode,+ { kind: NodeKind.EventsNode, key: '$pageview', name: '$pageview' },[hogqlProperty],],['drops column filters when the data warehouse table changes',- dataWarehouseFilter,- { type: 'data_warehouse', id: 'orders', name: 'orders', table_name: 'orders' },+ dataWarehouseNode,+ { kind: NodeKind.DataWarehouseNode, key: 'orders', name: 'orders' },[hogqlProperty],],['keeps column filters when the data warehouse table is unchanged',- dataWarehouseFilter,+ dataWarehouseNode,{ ...switchToPayments, timestamp_field: 'created_at' },[dwColumnProperty, hogqlProperty],],- ] as [string, LocalFilter, Record<string, any>, AnyPropertyFilter[]][])(+ ] as [string, SeriesNode, Record<string, any>, AnyPropertyFilter[]][])('%s',- async (_name, initialFilter, update, expectedProperties) => {- logic.actions.setFilters([initialFilter])+ async (_name, initialNode, update, expectedProperties) => {+ logic.actions.setLocalSeries([{ uuid: 'uuid-0', node: initialNode }])await expectLogic(logic, () => {- logic.actions.updateFilter({ ...update, index: 0 } as Parameters<- typeof logic.actions.updateFilter- >[0])- }).toDispatchActions(['updateFilter', 'setFilters'])+ logic.actions.updateSeriesEntity(0, update as any)+ }).toDispatchActions(['updateSeriesEntity', 'setLocalSeries'])- expect(logic.values.localFilters[0].properties).toEqual(expectedProperties)+ expect(logic.values.series[0].properties).toEqual(expectedProperties)})const eventPropertyMath = {- ...eventFilter,+ ...eventNode,math: 'sum',math_property: 'revenue',math_property_type: TaxonomicFilterGroupType.NumericalEventProperties,- }+ } as SeriesNodeconst dataWarehousePropertyMath = {- ...dataWarehouseFilter,+ ...dataWarehouseNode,math: 'sum',math_property: 'amount',math_property_type: TaxonomicFilterGroupType.DataWarehouseProperties,- }+ } as SeriesNodeit.each([[@@ -343,13 +326,13 @@ describe('entityFilterLogic', () => {['drops property math when a data warehouse series becomes an event',dataWarehousePropertyMath,- { type: 'events', id: '$pageview', name: '$pageview' },+ { kind: NodeKind.EventsNode, key: '$pageview', name: '$pageview' },{ math: undefined, math_property: undefined, math_property_type: undefined },],['drops property math when the data warehouse table changes',dataWarehousePropertyMath,- { type: 'data_warehouse', id: 'orders', name: 'orders', table_name: 'orders' },+ { kind: NodeKind.DataWarehouseNode, key: 'orders', name: 'orders' },{ math: undefined, math_property: undefined, math_property_type: undefined },],[@@ -364,49 +347,60 @@ describe('entityFilterLogic', () => {],['keeps math that does not depend on a property',- { ...eventFilter, math: 'dau' },+ { ...eventNode, math: 'dau' } as SeriesNode,switchToPayments,{ math: 'dau', math_property: undefined, math_property_type: undefined },],- ] as [string, LocalFilter, Record<string, any>, Record<string, any>][])(+ ] as [string, SeriesNode, Record<string, any>, Record<string, any>][])('%s',- async (_name, initialFilter, update, expectedMath) => {- logic.actions.setFilters([initialFilter])+ async (_name, initialNode, update, expectedMath) => {+ logic.actions.setLocalSeries([{ uuid: 'uuid-0', node: initialNode }])await expectLogic(logic, () => {- logic.actions.updateFilter({ ...update, index: 0 } as Parameters<- typeof logic.actions.updateFilter- >[0])- }).toDispatchActions(['updateFilter', 'setFilters'])+ logic.actions.updateSeriesEntity(0, update as any)+ }).toDispatchActions(['updateSeriesEntity', 'setLocalSeries'])- expect(logic.values.localFilters[0]).toMatchObject(expectedMath)+ expect(logic.values.series[0]).toMatchObject(expectedMath)})++ it('coerces a string action id to the integer the schema types', async () => {+ logic.actions.setLocalSeries([{ uuid: 'uuid-0', node: eventNode }])++ await expectLogic(logic, () => {+ logic.actions.updateSeriesEntity(0, {+ kind: NodeKind.ActionsNode,+ key: '9',+ name: 'Users signed up',+ })+ }).toDispatchActions(['updateSeriesEntity'])++ expect(logic.values.series[0]).toMatchObject({ kind: NodeKind.ActionsNode, id: 9 })+ })})- describe('duplicating filters', () => {+ describe('duplicating series', () => {it('preserves custom_name when duplicating', async () => {+ logic.actions.setLocalSeries([+ {+ uuid: 'uuid-0',+ node: {+ kind: NodeKind.EventsNode,+ event: '$pageview',+ name: '$pageview',+ custom_name: 'My custom label',+ },+ },+ ])+await expectLogic(logic, () => {- logic.actions.duplicateFilter({- id: '$pageview',- name: '$pageview',- custom_name: 'My custom label',- order: 0,- type: 'events',- })- }).toDispatchActions(['duplicateFilter', 'setFilters'])-- expect(logic.props.setFilters).toHaveBeenCalledWith(- expect.objectContaining({- events: expect.arrayContaining([- expect.objectContaining({- id: '$pageview',- custom_name: 'My custom label',- order: 1,- }),- ]),- })- )+ logic.actions.duplicateSeries(0)+ }).toDispatchActions(['duplicateSeries', 'setLocalSeries'])++ expect(logic.props.onChange).toHaveBeenLastCalledWith([+ expect.objectContaining({ event: '$pageview', custom_name: 'My custom label' }),+ expect.objectContaining({ event: '$pageview', custom_name: 'My custom label' }),+ ])})})})diff --git a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.tsindex a2784a46d2cc..d3eb016f0277 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/entityFilterLogic.ts@@ -2,57 +2,67 @@ import { deepEqual as equal } from 'fast-equals'import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'import posthog from 'posthog-js'-import { convertPropertyGroupToProperties } from 'lib/components/PropertyFilters/utils'import { defaultDataWarehousePopoverFields } from 'lib/components/TaxonomicFilter/taxonomicFilterLogic'import { DataWarehousePopoverField } from 'lib/components/TaxonomicFilter/types'import { uuid } from 'lib/utils/dom'import { GraphSeriesAddedSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'-import { getDefaultEventLabel, getDefaultEventName } from 'lib/utils/getAppContext'-import { assignField } from 'lib/utils/guards'+import { AnyEntityNode, EventsNode, GroupNode, NodeKind } from '~/queries/schema/schema-general'import {ActionFilter,AnyPropertyFilter,- AnyDataWarehouseFilter,- Entity,EntityFilter,EntityType,- EntityTypes,FilterLogicalOperator,- FilterType,PropertyFilterType,PropertyMathType,} from '~/types'-import type { TaxonomicFilterGroupType } from '../../../../lib/components/TaxonomicFilter/types'--export type LocalFilter = ActionFilter & {- order: number+import {+ SeriesNode,+ WarehouseSeriesNodeKind,+ createDefaultEventsNode,+ isGroupSeriesNode,+ isWarehouseSeriesNode,+ isWarehouseSeriesNodeKind,+ seriesNodeEntityType,+ seriesNodeKey,+ toActionId,+ withLatestVersion,+} from './seriesNode'++/** A series node plus the sidecar identity the editor needs for drag keys and row identity. */+export interface LocalSeries {uuid: string- table_name?: string- [key: string]: any+ node: SeriesNode+}++export interface SeriesMathUpdate {+ math?: string+ math_property?: string+ math_property_type?: string+ math_hogql?: string+ math_group_type_index?: number+}++/**+ * What the picker commits for a row: the node kind, the key that kind is identified by, and+ * whatever else that kind carries (warehouse popover fields, group operator and nodes).+ */+export interface SeriesEntityUpdate {+ kind: SeriesNode['kind']+ /** Event name, action id or table name, by kind. */+ key?: string | number | null+ name?: string | null+ custom_name?: string | null+ [field: string]: any}-export type BareEntity = Pick<Entity, 'id' | 'name'>--export function toLocalFilters(filters: Partial<FilterType>): LocalFilter[] {- const localFilters = [- ...(filters[EntityTypes.ACTIONS] || []),- ...(filters[EntityTypes.EVENTS] || []),- ...(filters[EntityTypes.DATA_WAREHOUSE] || []),- ...(filters[EntityTypes.GROUPS] || []),- ]- .sort((a, b) => a.order - b.order)- .map((filter, order) => ({ ...(filter as ActionFilter), order }))- return localFilters.map((filter) =>- filter.properties && Array.isArray(filter.properties)- ? {- ...filter,- uuid: uuid(),- properties: convertPropertyGroupToProperties(filter.properties),- }- : { ...filter, uuid: uuid() }- )+export interface SelectedSeries {+ index: number+ node: SeriesNode+ /** Row identity, so a rename cannot land on a different series that took this index. */+ uuid?: string}const PROPERTY_VALUE_MATHS = new Set<string>(Object.values(PropertyMathType))@@ -60,119 +70,96 @@ const PROPERTY_VALUE_MATHS = new Set<string>(Object.values(PropertyMathType))// math_property names a column or property on the entity the series aggregates, so it cannot// survive an entity switch. Property-value math (sum, avg, percentiles) is dropped with it —// the backend errors out on that math without a math_property.-function dropStaleMath(filter: LocalFilter): void {- if (filter.math && PROPERTY_VALUE_MATHS.has(filter.math)) {- filter.math = undefined+function dropStaleMath(node: Record<string, any>): void {+ if (node.math && PROPERTY_VALUE_MATHS.has(node.math)) {+ node.math = undefined}- filter.math_property = undefined- filter.math_property_type = undefined+ node.math_property = undefined+ node.math_property_type = undefined}-export function toFilters(localFilters: LocalFilter[]): FilterType {- const filters = localFilters.map((filter, index) => ({- ...filter,- order: index,- // The first step of a funnel cannot be optional- optionalInFunnel: index == 0 ? undefined : filter.optionalInFunnel,- }))-- return {- [EntityTypes.ACTIONS]: filters.filter((filter) => filter.type === EntityTypes.ACTIONS),- [EntityTypes.EVENTS]: filters.filter((filter) => filter.type === EntityTypes.EVENTS),- [EntityTypes.DATA_WAREHOUSE]: filters.filter((filter) => filter.type === EntityTypes.DATA_WAREHOUSE),- [EntityTypes.GROUPS]: filters.filter((filter) => filter.type === EntityTypes.GROUPS),- } as FilterType+function toLocalSeries(series: SeriesNode[]): LocalSeries[] {+ return series.map((node) => ({ uuid: uuid(), node }))}-/**- * Convert a single LocalFilter into a group filter- * Preserves the original filter in the values array for full reversibility- */-export function singleFilterToGroupFilter(filter: LocalFilter): LocalFilter {- return {- id: null,- name: filter.name, // for debugging- type: EntityTypes.GROUPS,- order: filter.order,- uuid: uuid(),- operator: FilterLogicalOperator.Or,- nestedFilters: [filter],- // Preserve math properties from the original filter at the group level- ...(filter.math && { math: filter.math }),- ...(filter.math_property && { math_property: filter.math_property }),- ...(filter.math_property_type && { math_property_type: filter.math_property_type }),- ...(filter.math_hogql && { math_hogql: filter.math_hogql }),- ...(filter.math_group_type_index !== undefined && { math_group_type_index: filter.math_group_type_index }),- } as LocalFilter+function applySeriesKey(node: Record<string, any>, kind: SeriesNode['kind'], key: string | number | null): void {+ if (kind === NodeKind.EventsNode) {+ node.event = key+ } else if (kind === NodeKind.ActionsNode) {+ node.id = toActionId(key)+ } else if (kind !== NodeKind.GroupNode) {+ node.table_name = key+ // Warehouse nodes mirror the table name onto `id`.+ node.id = key+ }}-/**- * Convert a group filter back into individual LocalFilters- * Each nested value in the group becomes a separate filter in the parent list- * Preserves order and all filter properties- */-export function splitGroupFilterToLocalFilters(groupFilter: LocalFilter, baseOrder: number): LocalFilter[] {- const nested = (groupFilter.nestedFilters as LocalFilter[] | null | undefined) || []- return nested.map((nestedFilter, index) => ({- ...nestedFilter,- order: baseOrder + index,- uuid: uuid(),- }))+/** Turns a row into a one-entity group, keeping the row inside it so the split is reversible. */+export function seriesNodeToGroupNode(node: SeriesNode): GroupNode {+ return withLatestVersion({+ kind: NodeKind.GroupNode,+ name: node.name,+ operator: FilterLogicalOperator.Or,+ nodes: [node as AnyEntityNode],+ ...(node.math && { math: node.math }),+ ...(node.math_property && { math_property: node.math_property }),+ ...(node.math_property_type && { math_property_type: node.math_property_type }),+ ...(node.math_hogql && { math_hogql: node.math_hogql }),+ ...(node.math_group_type_index !== undefined && { math_group_type_index: node.math_group_type_index }),+ } as GroupNode)}export interface EntityFilterProps {- setFilters?: (filters: FilterType) => void- filters?: Record<string, any>+ series?: SeriesNode[]+ onChange?: (series: SeriesNode[]) => voidtypeKey: stringsingleMode?: boolean- addFilterDefaultOptions?: Record<string, any>+ newSeriesDefaults?: Partial<EventsNode>dataWarehousePopoverFields?: DataWarehousePopoverField[]+ dataWarehouseNodeKind?: WarehouseSeriesNodeKind}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface entityFilterLogicValues {entityFilterVisible: boolean[]- filters: FilterType- localFilters: LocalFilter[]+ localSeries: LocalSeries[]modalVisible: boolean- selectedFilter: ActionFilter | EntityFilter | null+ selectedSeries: SelectedSeries | null+ series: SeriesNode[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface entityFilterLogicActions {- addFilter: () => {+ addSeries: () => {value: true}- convertFilterToGroup: (index: number) => {+ convertToGroup: (index: number) => {index: number}- duplicateFilter: (filter: ActionFilter | EntityFilter) => {- filter: ActionFilter | EntityFilter+ duplicateSeries: (index: number) => {+ index: number}hideModal: () => {value: true}- removeLocalFilter: (- filter: Partial<EntityFilter> & {- index: number- }- ) => {+ removeSeries: (index: number) => {index: number- type: EntityType | undefined}- renameFilter: (custom_name: string) => {- custom_name: string- }- renameLocalFilter: (- index: number,- custom_name: string- ) => {- custom_name: string- index: number+ renameSeries: (customName: string) => {+ customName: string}selectFilter: (filter: ActionFilter | EntityFilter | null) => {filter: ActionFilter | EntityFilter | null}+ selectSeries: (+ index: number | null,+ node?: SeriesNode | null,+ uuid?: string+ ) => {+ index: number | null+ node: SeriesNode | null | undefined+ uuid: string | undefined+ }setEntityFilterVisibility: (index: number,value: boolean@@ -180,158 +167,44 @@ export interface entityFilterLogicActions {index: numbervalue: boolean}- setFilters: (filters: LocalFilter[]) => {- filters: LocalFilter[]+ setLocalSeries: (localSeries: LocalSeries[]) => {+ localSeries: LocalSeries[]}- setLocalFilters: (filters: FilterType) => {- filters: FilterType+ setSeries: (series: SeriesNode[]) => {+ series: SeriesNode[]}showModal: () => {value: true}- splitLocalFilter: (index: number) => {+ splitGroup: (index: number) => {index: number}- updateFilter: (- filter: (ActionFilter | AnyDataWarehouseFilter | EntityFilter) & {- index: number- table_name?: string- [key: string]: any- }- ) =>- | {- custom_name?: string | null | undefined- id: number | string | null- index: number- name?: string | null | undefined- optionalInFunnel?: boolean | undefined- order?: number | undefined- table_name?: string | undefined- type?: EntityType | undefined- [key: string]: any- }- | {- custom_name?: string | null | undefined- days?: string[] | undefined- id: number | string | null- index: number- math?: string | undefined- math_group_type_index?: number | null | undefined- math_hogql?: string | null | undefined- math_property?: string | null | undefined- math_property_type?: TaxonomicFilterGroupType | null | undefined- name?: string | null | undefined- negation?: boolean | undefined- nestedFilters?: EntityFilter[] | null | undefined- operator?: FilterLogicalOperator | null | undefined- optionalInFunnel?: boolean | undefined- order?: number | undefined- properties?: AnyPropertyFilter[] | undefined- table_name?: string | undefined- type: EntityType- [key: string]: any- }- | {- aggregation_target_field: string- custom_name?: string | null | undefined- days?: string[] | undefined- id: number | string | null- id_field: string- index: number- math?: string | undefined- math_group_type_index?: number | null | undefined- math_hogql?: string | null | undefined- math_property?: string | null | undefined- math_property_type?: TaxonomicFilterGroupType | null | undefined- name?: string | null | undefined- negation?: boolean | undefined- nestedFilters?: EntityFilter[] | null | undefined- operator?: FilterLogicalOperator | null | undefined- optionalInFunnel?: boolean | undefined- order?: number | undefined- properties?: AnyPropertyFilter[] | undefined- table_name: string- timestamp_field: string- type: EntityType- [key: string]: any- }- | {- custom_name?: string | null | undefined- days?: string[] | undefined- distinct_id_field: string- id: number | string | null- id_field: string- index: number- math?: string | undefined- math_group_type_index?: number | null | undefined- math_hogql?: string | null | undefined- math_property?: string | null | undefined- math_property_type?: TaxonomicFilterGroupType | null | undefined- name?: string | null | undefined- negation?: boolean | undefined- nestedFilters?: EntityFilter[] | null | undefined- operator?: FilterLogicalOperator | null | undefined- optionalInFunnel?: boolean | undefined- order?: number | undefined- properties?: AnyPropertyFilter[] | undefined- table_name: string- timestamp_field: string- type: EntityType- [key: string]: any- }- | {- aggregation_target_field: string- created_at_field: string- custom_name?: string | null | undefined- days?: string[] | undefined- id: number | string | null- index: number- math?: string | undefined- math_group_type_index?: number | null | undefined- math_hogql?: string | null | undefined- math_property?: string | null | undefined- math_property_type?: TaxonomicFilterGroupType | null | undefined- name?: string | null | undefined- negation?: boolean | undefined- nestedFilters?: EntityFilter[] | null | undefined- operator?: FilterLogicalOperator | null | undefined- optionalInFunnel?: boolean | undefined- order?: number | undefined- properties?: AnyPropertyFilter[] | undefined- table_name: string- timestamp_field: string- type: EntityType- [key: string]: any- }- updateFilterMath: (- filter: Partial<ActionFilter> & {- index: number- }+ updateSeriesEntity: (+ index: number,+ update: SeriesEntityUpdate) => {index: number- math: string | undefined- math_group_type_index: number | null | undefined- math_hogql: string | null | undefined- math_property: string | null | undefined- math_property_type: TaxonomicFilterGroupType | null | undefined- type: EntityType+ update: SeriesEntityUpdate}- updateFilterOptional: (- filter: Partial<ActionFilter> & {- index: number- }+ updateSeriesMath: (+ index: number,+ math: SeriesMathUpdate+ ) => {+ index: number+ math: SeriesMathUpdate+ }+ updateSeriesOptional: (+ index: number,+ optionalInFunnel: boolean | undefined) => {index: numberoptionalInFunnel: boolean | undefined- type: EntityType}- updateFilterProperty: (- filter: Partial<EntityFilter> & {- index?: number- properties: AnyPropertyFilter[]- }+ updateSeriesProperties: (+ index: number,+ properties: AnyPropertyFilter[]) => {- index: number | undefined+ index: numberproperties: AnyPropertyFilter[]}}@@ -340,7 +213,7 @@ export interface entityFilterLogicActions {export interface entityFilterLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {- filters: (localFilters: LocalFilter[]) => FilterType+ series: (localSeries: LocalSeries[]) => SeriesNode[]}}@@ -359,96 +232,64 @@ export const entityFilterLogic = kea<entityFilterLogicType>([logic: [eventUsageLogic],})),actions({+ selectSeries: (index: number | null, node?: SeriesNode | null, uuid?: string) => ({ index, node, uuid }),+ // The results table hands over the legacy-shaped series object the trends runner emits.selectFilter: (filter: EntityFilter | ActionFilter | null) => ({ filter }),- updateFilterMath: (- filter: Partial<ActionFilter> & {- index: number- }- ) => ({- type: filter.type as EntityType,- math: filter.math,- math_property: filter.math_property,- math_property_type: filter.math_property_type,- math_hogql: filter.math_hogql,- index: filter.index,- math_group_type_index: filter.math_group_type_index,- }),- updateFilterOptional: (- filter: Partial<ActionFilter> & {- index: number- }- ) => ({- type: filter.type as EntityType,- index: filter.index,- optionalInFunnel: filter.optionalInFunnel,- }),- updateFilter: (- filter: (EntityFilter | ActionFilter | AnyDataWarehouseFilter) & {- index: number- table_name?: string- [key: string]: any- }- ) => ({- ...filter,- }),- renameFilter: (custom_name: string) => ({ custom_name }),- removeLocalFilter: (- filter: Partial<EntityFilter> & {- index: number- }- ) => ({- type: filter.type,- index: filter.index,- }),- splitLocalFilter: (index: number) => ({ index }),- addFilter: true,- duplicateFilter: (filter: EntityFilter | ActionFilter) => ({ filter }),- convertFilterToGroup: (index: number) => ({ index }),- updateFilterProperty: (- filter: Partial<EntityFilter> & {- index?: number- properties: AnyPropertyFilter[]- }- ) => ({- properties: filter.properties,- index: filter.index,- }),- setFilters: (filters: LocalFilter[]) => ({ filters }),- setLocalFilters: (filters: FilterType) => ({ filters }),+ updateSeriesEntity: (index: number, update: SeriesEntityUpdate) => ({ index, update }),+ updateSeriesMath: (index: number, math: SeriesMathUpdate) => ({ index, math }),+ updateSeriesProperties: (index: number, properties: AnyPropertyFilter[]) => ({ index, properties }),+ updateSeriesOptional: (index: number, optionalInFunnel: boolean | undefined) => ({ index, optionalInFunnel }),+ renameSeries: (customName: string) => ({ customName }),+ removeSeries: (index: number) => ({ index }),+ splitGroup: (index: number) => ({ index }),+ addSeries: true,+ duplicateSeries: (index: number) => ({ index }),+ convertToGroup: (index: number) => ({ index }),+ setLocalSeries: (localSeries: LocalSeries[]) => ({ localSeries }),+ setSeries: (series: SeriesNode[]) => ({ series }),setEntityFilterVisibility: (index: number, value: boolean) => ({ index, value }),- renameLocalFilter: (index: number, custom_name: string) => ({ index, custom_name }),showModal: true,hideModal: true,}),reducers(({ props }) => ({- selectedFilter: [- null as EntityFilter | ActionFilter | null,+ selectedSeries: [+ null as SelectedSeries | null,{- selectFilter: (_, { filter }) => filter,+ selectSeries: (_, { index, node, uuid }) => (index == null || !node ? null : { index, node, uuid }),},],- localFilters: [- toLocalFilters(props.filters ?? {}),+ localSeries: [+ toLocalSeries(props.series ?? []),{- setFilters: (_, { filters }) => filters,- setLocalFilters: (currentFilters, { filters }) => {- if (equal(toFilters(currentFilters), filters)) {- return currentFilters+ setLocalSeries: (_, { localSeries }) => localSeries,+ setSeries: (current, { series }) => {+ if (+ equal(+ current.map(({ node }) => node),+ series+ )+ ) {+ return current}- const newFilters = toLocalFilters(filters)+ // Row identity has to survive a parent re-render, or drag handles and open+ // property panels reset under the user. Match a row to the same kind and key,+ // preferring the one at the same index so two rows on the same event keep+ // their own uuid.const usedUuids = new Set<string>()- return newFilters.map((newFilter) => {- const isSameFilter = (f: LocalFilter): boolean =>- f.id === newFilter.id && f.type === newFilter.type && !usedUuids.has(f.uuid)+ return series.map((node, index) => {+ const isSameSeries = (candidate: LocalSeries): boolean =>+ candidate.node.kind === node.kind &&+ seriesNodeKey(candidate.node) === seriesNodeKey(node) &&+ !usedUuids.has(candidate.uuid)const existing =- currentFilters.find((f) => isSameFilter(f) && f.order === newFilter.order) ??- currentFilters.find(isSameFilter)+ (current[index] && isSameSeries(current[index]) ? current[index] : undefined) ??+ current.find(isSameSeries)if (existing) {usedUuids.add(existing.uuid)- return { ...newFilter, uuid: existing.uuid }+ return { uuid: existing.uuid, node }}- return newFilter+ return { uuid: uuid(), node }})},},@@ -472,243 +313,201 @@ export const entityFilterLogic = kea<entityFilterLogicType>([})),selectors({- filters: [(s) => [s.localFilters], (localFilters: LocalFilter[]): FilterType => toFilters(localFilters)],+ series: [(s) => [s.localSeries], (localSeries: LocalSeries[]): SeriesNode[] => localSeries.map((l) => l.node)],}),- listeners(({ actions, values, props }) => ({- renameFilter: ({ custom_name }) => {- const selectedFilter = values.selectedFilter as LocalFilter | null- if (selectedFilter) {- const index = selectedFilter.uuid- ? values.localFilters.findIndex((filter) => filter.uuid === selectedFilter.uuid)- : selectedFilter.order-- if (index !== -1) {- actions.updateFilter({- ...selectedFilter,- index,- custom_name,- } as EntityFilter & {- index: number- })+ listeners(({ actions, values, props }) => {+ const replaceAt = (index: number, update: (node: SeriesNode) => SeriesNode): void => {+ actions.setLocalSeries(+ values.localSeries.map((local, i) => (i === index ? { ...local, node: update(local.node) } : local))+ )+ }++ return {+ selectFilter: ({ filter }) => {+ if (!filter) {+ actions.selectSeries(null)+ return}- }- actions.hideModal()- },- hideModal: () => {- actions.selectFilter(null)- },- updateFilter: async ({ type, index, name, id, custom_name, table_name, ...fieldValues }) => {- actions.setFilters(- values.localFilters.map((filter, i) => {- if (i === index) {- const dataWarehousePopoverFields =- props.dataWarehousePopoverFields ?? defaultDataWarehousePopoverFields- if (type === EntityTypes.DATA_WAREHOUSE) {- const updatedFilter = {- ...filter,- id: typeof id === 'undefined' ? filter.id : id,- name: typeof name === 'undefined' ? filter.name : name,- type: typeof type === 'undefined' ? filter.type : type,- custom_name: typeof custom_name === 'undefined' ? filter.custom_name : custom_name,- table_name: typeof table_name === 'undefined' ? filter.table_name : table_name,- }-- // Dynamically handle fields from dataWarehousePopoverFields- dataWarehousePopoverFields.forEach(({ key }) => {- const fieldValue = fieldValues[key]- assignField(- updatedFilter,- key as keyof typeof updatedFilter,- typeof fieldValue === 'undefined' ? filter[key] : fieldValue- )- })-- // A data warehouse series resolves property filters against its own- // table: there is no person in scope, so person-scoped filters carried- // over from a previous event entity cannot resolve, and column filters- // from a different table cannot either. SQL expression filters are- // user-authored and stay visible in the UI, so they are kept.- if (Array.isArray(filter.properties)) {- updatedFilter.properties = filter.properties.filter(- (property: AnyPropertyFilter) =>- property.type === PropertyFilterType.HogQL ||- (property.type === PropertyFilterType.DataWarehouse &&- updatedFilter.table_name === filter.table_name)- )- }-- if (- filter.type !== EntityTypes.DATA_WAREHOUSE ||- updatedFilter.table_name !== filter.table_name- ) {- dropStaleMath(updatedFilter)- }-- return updatedFilter- }+ const index = filter.order ?? filter.index ?? -1+ const local = values.localSeries[index]+ actions.selectSeries(local ? index : null, local?.node, local?.uuid)+ },+ renameSeries: ({ customName }) => {+ const selected = values.selectedSeries+ if (selected) {+ // Resolve by row identity: the selected row may have moved or been removed+ // while the modal was open, and renaming by index alone would hit whichever+ // series took its place.+ const index = selected.uuid+ ? values.localSeries.findIndex(({ uuid: rowUuid }) => rowUuid === selected.uuid)+ : selected.index+ if (index !== -1) {+ replaceAt(index, (node) => ({ ...node, custom_name: customName }) as SeriesNode)+ }+ }+ actions.hideModal()+ },+ hideModal: () => {+ actions.selectSeries(null)+ },+ updateSeriesEntity: ({ index, update }) => {+ const { kind, key, name, custom_name, ...extra } = update+ const dataWarehousePopoverFields = props.dataWarehousePopoverFields ?? defaultDataWarehousePopoverFields- // Handle group filters: preserve all group-specific fields (values, operator)- if (type === EntityTypes.GROUPS) {- const newFilter = {- ...filter,- id: typeof id === 'undefined' ? filter.id : id,- name: typeof name === 'undefined' ? filter.name : name,- type: typeof type === 'undefined' ? filter.type : type,- custom_name: typeof custom_name === 'undefined' ? filter.custom_name : custom_name,- ...fieldValues,- } as LocalFilter-- return newFilter- }+ replaceAt(index, (current) => {+ const previousKind = current.kind+ const next: Record<string, any> = { ...current, kind }- // For non-DATA_WAREHOUSE types, remove any data warehouse specific fields- const cleanedFilter = { ...filter }- dataWarehousePopoverFields.forEach(({ key }) => {- delete cleanedFilter[key]+ if (typeof name !== 'undefined') {+ next.name = name+ }+ if (typeof custom_name !== 'undefined') {+ next.custom_name = custom_name+ }++ if (isWarehouseSeriesNodeKind(kind)) {+ applySeriesKey(next, kind, typeof key === 'undefined' ? seriesNodeKey(current) : key)+ dataWarehousePopoverFields.forEach(({ key: fieldKey }) => {+ const value = extra[fieldKey]+ next[fieldKey] = typeof value === 'undefined' ? (current as any)[fieldKey] : value})- // Data warehouse column filters reference the warehouse table, which an- // event or action series does not select from, so they cannot carry over.- if (Array.isArray(cleanedFilter.properties)) {- cleanedFilter.properties = cleanedFilter.properties.filter(- (property: AnyPropertyFilter) => property.type !== PropertyFilterType.DataWarehouse+ // A data warehouse series resolves property filters against its own+ // table: there is no person in scope, so person-scoped filters carried+ // over from a previous event entity cannot resolve, and column filters+ // from a different table cannot either. SQL expression filters are+ // user-authored and stay visible in the UI, so they are kept.+ if (Array.isArray(current.properties)) {+ next.properties = current.properties.filter(+ (property: AnyPropertyFilter) =>+ property.type === PropertyFilterType.HogQL ||+ (property.type === PropertyFilterType.DataWarehouse &&+ next.table_name === (current as any).table_name))}- if (filter.type === EntityTypes.DATA_WAREHOUSE) {- dropStaleMath(cleanedFilter)+ if (!isWarehouseSeriesNode(current) || next.table_name !== (current as any).table_name) {+ dropStaleMath(next)}- return {- ...cleanedFilter,- id: typeof id === 'undefined' ? filter.id : id,- name: typeof name === 'undefined' ? filter.name : name,- type: typeof type === 'undefined' ? filter.type : type,- custom_name: typeof custom_name === 'undefined' ? filter.custom_name : custom_name,- }+ return withLatestVersion(next as SeriesNode)}- return filter- })- )- !props.singleMode && actions.selectFilter(null)- },- updateFilterProperty: async ({ properties, index }) => {- actions.setFilters(- values.localFilters.map((filter, i) => (i === index ? { ...filter, properties } : filter))- )- },- updateFilterMath: async ({ index, ...mathProperties }) => {- actions.setFilters(- values.localFilters.map((filter, i) => (i === index ? { ...filter, ...mathProperties } : filter))- )- },- updateFilterOptional: async ({ index, optionalInFunnel }) => {- actions.setFilters(- values.localFilters.map((filter, i) => (i === index ? { ...filter, optionalInFunnel } : filter))- )- },- removeLocalFilter: async ({ index }) => {- const newFilters = values.localFilters.filter((_, i) => i !== index)- actions.setFilters(newFilters)- actions.setLocalFilters(toFilters(newFilters))- posthog.capture('local filter removed', { index: index })- },- splitLocalFilter: ({ index }) => {- const filter = values.localFilters[index]- if (!filter || filter.type !== EntityTypes.GROUPS) {- return- }+ if (kind === NodeKind.GroupNode) {+ return withLatestVersion({ ...next, ...extra } as SeriesNode)+ }- // Convert group filter into individual filters- const splitFilters = splitGroupFilterToLocalFilters(filter, filter.order)-- // Replace the group filter with individual filters- // and adjust orders for filters after it- const newFilters = values.localFilters.reduce<LocalFilter[]>((acc, f, i) => {- if (i === index) {- // Replace group filter with split filters- acc.push(...splitFilters)- } else if (i > index) {- // Adjust order for filters that come after- acc.push({- ...f,- order: f.order + splitFilters.length - 1,+ // Leaving the warehouse: its popover fields and column filters name a table+ // an event or action series does not select from, so neither can carry over.+ dataWarehousePopoverFields.forEach(({ key: fieldKey }) => {+ delete next[fieldKey]})- } else {- acc.push(f)- }- return acc- }, [])+ delete next.table_name+ if (Array.isArray(current.properties)) {+ next.properties = current.properties.filter(+ (property: AnyPropertyFilter) => property.type !== PropertyFilterType.DataWarehouse+ )+ }+ if (isWarehouseSeriesNode(current)) {+ dropStaleMath(next)+ }- actions.setFilters(newFilters)- },- addFilter: async () => {- const previousLength = values.localFilters.length- const newLength = previousLength + 1- const precedingEntity = values.localFilters[previousLength - 1] as LocalFilter | undefined- const order = precedingEntity ? precedingEntity.order + 1 : 0- const newFilter: LocalFilter = {- id: getDefaultEventName(),- name: getDefaultEventLabel(),- uuid: uuid(),- type: EntityTypes.EVENTS,- order: order,- ...props.addFilterDefaultOptions,- }- actions.setFilters([...values.localFilters, newFilter])- actions.selectFilter({ ...newFilter, index: order })- eventUsageLogic.actions.reportInsightFilterAdded(newLength, GraphSeriesAddedSource.Default)- },- duplicateFilter: async ({ filter }) => {- const previousLength = values.localFilters.length- const newLength = previousLength + 1- const order = filter.order ?? values.localFilters[previousLength - 1].order- const newFilters = [...values.localFilters]- for (const _filter of newFilters) {- // Because duplicate filters are inserted within the current filters we need to move over the remaining filers- if (_filter.order >= order + 1) {- _filter.order = _filter.order + 1+ if (kind === NodeKind.EventsNode) {+ delete next.id+ } else {+ delete next.event+ }+ if (previousKind === NodeKind.GroupNode) {+ delete next.nodes+ delete next.operator+ }+ applySeriesKey(next, kind, typeof key === 'undefined' ? seriesNodeKey(current) : key)++ return withLatestVersion(next as SeriesNode)+ })++ !props.singleMode && actions.selectSeries(null)+ },+ updateSeriesProperties: ({ index, properties }) => {+ replaceAt(index, (node) => ({ ...node, properties }) as SeriesNode)+ },+ updateSeriesMath: ({ index, math }) => {+ replaceAt(index, (node) => ({ ...node, ...math }) as SeriesNode)+ },+ updateSeriesOptional: ({ index, optionalInFunnel }) => {+ replaceAt(index, (node) => ({ ...node, optionalInFunnel }) as SeriesNode)+ },+ removeSeries: ({ index }) => {+ actions.setLocalSeries(values.localSeries.filter((_, i) => i !== index))+ posthog.capture('local filter removed', { index: index })+ },+ splitGroup: ({ index }) => {+ const node = values.localSeries[index]?.node+ if (!isGroupSeriesNode(node)) {+ return}- }- newFilters.splice(order + 1, 0, {- ...filter,- uuid: uuid(),- order: order + 1,- } as LocalFilter)- actions.setFilters(newFilters)- actions.setEntityFilterVisibility(order + 1, values.entityFilterVisible[order])- eventUsageLogic.actions.reportInsightFilterAdded(newLength, GraphSeriesAddedSource.Duplicate)- },- convertFilterToGroup: async ({ index }) => {- const filter = values.localFilters[index]- if (!filter) {- return- }- const groupFilter = singleFilterToGroupFilter(filter)- const newFilters = [...values.localFilters]- newFilters[index] = groupFilter- actions.setFilters(newFilters)- },- setFilters: async ({ filters }) => {- if (typeof props.setFilters === 'function') {- props.setFilters(toFilters(filters))- }- const sanitizedFilters = filters?.map(({ id, type }) => ({ id, type }))- posthog.capture('filters set', { filters: sanitizedFilters })- },- setEntityFilterVisibility: async ({ index, value }) => {- const entityName = values.localFilters[index]?.name || undefined- posthog.capture('entity filter visbility set', { index: index, visible: value, entityName: entityName })- },- })),- events(({ actions, props, values }) => ({+ const nested = node.nodes ?? []+ actions.setLocalSeries([+ ...values.localSeries.slice(0, index),+ ...nested.map((nestedNode) => ({ uuid: uuid(), node: nestedNode as SeriesNode })),+ ...values.localSeries.slice(index + 1),+ ])+ },+ addSeries: () => {+ const newLength = values.localSeries.length + 1+ const node = createDefaultEventsNode(props.newSeriesDefaults)+ const newUuid = uuid()+ actions.setLocalSeries([...values.localSeries, { uuid: newUuid, node }])+ actions.selectSeries(newLength - 1, node, newUuid)+ eventUsageLogic.actions.reportInsightFilterAdded(newLength, GraphSeriesAddedSource.Default)+ },+ duplicateSeries: ({ index }) => {+ const local = values.localSeries[index]+ if (!local) {+ return+ }+ const newLength = values.localSeries.length + 1+ const duplicated = { uuid: uuid(), node: withLatestVersion({ ...local.node }) }+ actions.setLocalSeries([+ ...values.localSeries.slice(0, index + 1),+ duplicated,+ ...values.localSeries.slice(index + 1),+ ])+ actions.setEntityFilterVisibility(index + 1, values.entityFilterVisible[index])+ eventUsageLogic.actions.reportInsightFilterAdded(newLength, GraphSeriesAddedSource.Duplicate)+ },+ convertToGroup: ({ index }) => {+ const node = values.localSeries[index]?.node+ if (!node) {+ return+ }+ replaceAt(index, () => seriesNodeToGroupNode(node))+ },+ setLocalSeries: ({ localSeries }) => {+ const series = localSeries.map(({ node }) => node)+ if (typeof props.onChange === 'function') {+ props.onChange(series)+ }+ posthog.capture('filters set', {+ filters: series.map((node) => ({+ id: seriesNodeKey(node),+ type: seriesNodeEntityType(node) as EntityType | undefined,+ })),+ })+ },+ setEntityFilterVisibility: ({ index, value }) => {+ const entityName = values.localSeries[index]?.node.name || undefined+ posthog.capture('entity filter visbility set', { index: index, visible: value, entityName: entityName })+ },+ }+ }),+ events(({ actions, props }) => ({afterMount: () => {if (props.singleMode) {- const filter = { id: null, type: EntityTypes.EVENTS, order: values.localFilters.length }- actions.setLocalFilters({ [`${EntityTypes.EVENTS}`]: [filter] })- actions.selectFilter({ ...filter, index: 0 })+ const node = withLatestVersion({ kind: NodeKind.EventsNode, event: null } as EventsNode)+ actions.setSeries([node])+ actions.selectSeries(0, node)}},})),diff --git a/frontend/src/scenes/insights/filters/ActionFilter/legacyFilters.ts b/frontend/src/scenes/insights/filters/ActionFilter/legacyFilters.tsnew file mode 100644index 000000000000..0ff26ffd8156--- /dev/null+++ b/frontend/src/scenes/insights/filters/ActionFilter/legacyFilters.ts@@ -0,0 +1,178 @@+import { convertPropertyGroupToProperties } from 'lib/components/PropertyFilters/utils'+import { uuid } from 'lib/utils/dom'++import { AnyEntityNode, GroupNode, NodeKind } from '~/queries/schema/schema-general'+import { ActionFilter, Entity, EntityTypes, FilterType } from '~/types'++import {+ SeriesNode,+ WarehouseSeriesNodeKind,+ isActionsSeriesNode,+ isEventsSeriesNode,+ isGroupSeriesNode,+ isWarehouseSeriesNode,+ seriesNodeEntityType,+ seriesNodeKindForEntityType,+ toActionId,+} from './seriesNode'++/**+ * Translation between the series editor's query nodes and the legacy entity filter shape that+ * CDP, workflows, heatmaps, usage metrics, dashboard templates and retention still persist.+ *+ * Only four things translate: `type` to `kind`, `id` to the node's own key, `order` to the array+ * index, and `nestedFilters` to `nodes`. Everything else, including warehouse popover fields a+ * caller declares itself, keeps its name and is copied through untouched.+ */++/** Keys that mean something different on each side, so neither side copies them blindly. */+const TRANSLATED_LEGACY_KEYS = ['type', 'id', 'order', 'index', 'nestedFilters', 'uuid'] as const+const TRANSLATED_NODE_KEYS = ['kind', 'version', 'event', 'id', 'nodes'] as const++function omit<T extends Record<string, any>>(source: T, keys: readonly string[]): Record<string, any> {+ const result: Record<string, any> = {}+ for (const [key, value] of Object.entries(source)) {+ if (!keys.includes(key)) {+ result[key] = value+ }+ }+ return result+}++function legacyFilterToSeriesNode(filter: ActionFilter, warehouseKind: WarehouseSeriesNodeKind): SeriesNode {+ const kind = seriesNodeKindForEntityType(filter.type, warehouseKind)+ const shared = omit(filter, TRANSLATED_LEGACY_KEYS)++ // A legacy filter may carry a property group where a node carries a flat list.+ if (Array.isArray(filter.properties)) {+ shared.properties = convertPropertyGroupToProperties(filter.properties)+ }++ if (kind === NodeKind.ActionsNode) {+ return { ...shared, kind, id: toActionId(filter.id) } as SeriesNode+ }+ if (kind === NodeKind.GroupNode) {+ return {+ ...shared,+ kind,+ nodes: (filter.nestedFilters ?? []).map(+ (nested) => legacyFilterToSeriesNode(nested as ActionFilter, warehouseKind) as AnyEntityNode+ ),+ } as GroupNode as SeriesNode+ }+ if (kind !== NodeKind.EventsNode) {+ // Warehouse: `table_name` is the key, and the legacy `id` mirrors it.+ const warehouseTableName = (filter as { table_name?: string }).table_name+ return {+ ...shared,+ kind,+ table_name: warehouseTableName ?? (typeof filter.id === 'string' ? filter.id : undefined),+ id: warehouseTableName ?? filter.id,+ } as SeriesNode+ }+ return { ...shared, kind, event: filter.id } as SeriesNode+}++/** Sorted by the `order` fields, which the editor then carries as the array index. */+export function legacyFiltersToSeries(+ filters: Partial<FilterType> | undefined,+ warehouseKind: WarehouseSeriesNodeKind = NodeKind.DataWarehouseNode+): SeriesNode[] {+ return [+ ...(filters?.[EntityTypes.ACTIONS] || []),+ ...(filters?.[EntityTypes.EVENTS] || []),+ ...(filters?.[EntityTypes.DATA_WAREHOUSE] || []),+ ...(filters?.[EntityTypes.GROUPS] || []),+ ]+ .sort((a, b) => (a.order ?? 0) - (b.order ?? 0))+ .map((filter) => legacyFilterToSeriesNode(filter as ActionFilter, warehouseKind))+}++function seriesNodeToLegacyFilter(node: SeriesNode, order: number): ActionFilter {+ const shared = omit(node, TRANSLATED_NODE_KEYS)+ const type = seriesNodeEntityType(node) ?? EntityTypes.EVENTS++ let id: ActionFilter['id'] = null+ if (isEventsSeriesNode(node)) {+ id = node.event ?? null+ } else if (isActionsSeriesNode(node)) {+ id = node.id+ } else if (isWarehouseSeriesNode(node)) {+ id = node.table_name+ }++ return {+ ...shared,+ ...(isGroupSeriesNode(node)+ ? { nestedFilters: node.nodes.map((nested, nestedOrder) => seriesNodeToLegacyFilter(nested, nestedOrder)) }+ : {}),+ id,+ type,+ order,+ } as ActionFilter+}++/** Reassigns `order` from the array index. */+export function seriesToLegacyFilters(series: SeriesNode[]): FilterType {+ const filters = series.map((node, index) => {+ const filter = seriesNodeToLegacyFilter(node, index)+ // The first step of a funnel cannot be optional.+ return index === 0 ? { ...filter, optionalInFunnel: undefined } : filter+ })++ return {+ [EntityTypes.ACTIONS]: filters.filter((filter) => filter.type === EntityTypes.ACTIONS),+ [EntityTypes.EVENTS]: filters.filter((filter) => filter.type === EntityTypes.EVENTS),+ [EntityTypes.DATA_WAREHOUSE]: filters.filter((filter) => filter.type === EntityTypes.DATA_WAREHOUSE),+ [EntityTypes.GROUPS]: filters.filter((filter) => filter.type === EntityTypes.GROUPS),+ } as FilterType+}++/**+ * The legacy row shape, still used by `cleanFilters` for the persons-modal URL path and by+ * replay's playlist summary. Both go in the PR that deletes the converter.+ */+export type LocalFilter = ActionFilter & {+ order: number+ uuid: string+ table_name?: string+ [key: string]: any+}++export type BareEntity = Pick<Entity, 'id' | 'name'>++export function toLocalFilters(filters: Partial<FilterType>): LocalFilter[] {+ const localFilters = [+ ...(filters[EntityTypes.ACTIONS] || []),+ ...(filters[EntityTypes.EVENTS] || []),+ ...(filters[EntityTypes.DATA_WAREHOUSE] || []),+ ...(filters[EntityTypes.GROUPS] || []),+ ]+ .sort((a, b) => a.order - b.order)+ .map((filter, order) => ({ ...(filter as ActionFilter), order }))+ return localFilters.map((filter) =>+ filter.properties && Array.isArray(filter.properties)+ ? {+ ...filter,+ uuid: uuid(),+ properties: convertPropertyGroupToProperties(filter.properties),+ }+ : { ...filter, uuid: uuid() }+ )+}++export function toFilters(localFilters: LocalFilter[]): FilterType {+ const filters = localFilters.map((filter, index) => ({+ ...filter,+ order: index,+ // The first step of a funnel cannot be optional+ optionalInFunnel: index == 0 ? undefined : filter.optionalInFunnel,+ }))++ return {+ [EntityTypes.ACTIONS]: filters.filter((filter) => filter.type === EntityTypes.ACTIONS),+ [EntityTypes.EVENTS]: filters.filter((filter) => filter.type === EntityTypes.EVENTS),+ [EntityTypes.DATA_WAREHOUSE]: filters.filter((filter) => filter.type === EntityTypes.DATA_WAREHOUSE),+ [EntityTypes.GROUPS]: filters.filter((filter) => filter.type === EntityTypes.GROUPS),+ } as FilterType+}diff --git a/frontend/src/scenes/insights/filters/ActionFilter/renameModalLogic.test.ts b/frontend/src/scenes/insights/filters/ActionFilter/renameModalLogic.test.tsindex d772f2c006fc..24067073ca1e 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/renameModalLogic.test.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/renameModalLogic.test.ts@@ -3,12 +3,15 @@ import { expectLogic } from 'kea-test-utils'import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'import { renameModalLogic } from 'scenes/insights/filters/ActionFilter/renameModalLogic'import { insightDataLogic } from 'scenes/insights/insightDataLogic'-import { getDisplayNameFromEntityFilter } from 'scenes/insights/utils'+import { getDisplayNameFromEntityNode } from 'scenes/insights/utils'import { initKeaTests } from '~/test/init'import { EntityFilter } from '~/types'import filtersJson from './__mocks__/filters.json'+import { legacyFiltersToSeries } from './legacyFilters'++const series = legacyFiltersToSeries(filtersJson as any)describe('renameModalLogic', () => {let logic: ReturnType<typeof renameModalLogic.build>@@ -20,13 +23,13 @@ describe('renameModalLogic', () => {someInsightDataLogic = insightDataLogic({ dashboardItemId: 'new' })someInsightDataLogic.mount()relevantEntityFilterLogic = entityFilterLogic({- setFilters: jest.fn(),- filters: filtersJson,+ onChange: jest.fn(),+ series,typeKey: 'new',})relevantEntityFilterLogic.mount()logic = renameModalLogic({- filter: filtersJson.events[0] as EntityFilter,+ node: series[0],typeKey: 'new',})logic.mount()@@ -39,7 +42,7 @@ describe('renameModalLogic', () => {it('name', async () => {await expectLogic(logic).toMatchValues({- name: getDisplayNameFromEntityFilter(filtersJson.events[0] as EntityFilter),+ name: getDisplayNameFromEntityNode(series[0]),})})})@@ -53,17 +56,33 @@ describe('renameModalLogic', () => {.toMatchValues({ name: 'veggie_straws' })})- it('set filter', async () => {+ it('follows the selected series', async () => {await expectLogic(relevantEntityFilterLogic, () => {- relevantEntityFilterLogic.actions.selectFilter({- ...filtersJson.events[0],+ relevantEntityFilterLogic.actions.selectSeries(0, {+ ...series[0],custom_name: 'zesty_veggie_straws',- } as EntityFilter)- }).toDispatchActions(['selectFilter'])+ })+ }).toDispatchActions(['selectSeries'])await expectLogic(logic).toMatchValues({name: 'zesty_veggie_straws',})})++ it('resolves the legacy series object the results table passes', async () => {+ await expectLogic(relevantEntityFilterLogic, () => {+ // The trends runner emits `order`, not an index.+ relevantEntityFilterLogic.actions.selectFilter({+ id: '9',+ name: 'Users signed up',+ type: 'actions',+ order: 2,+ } as EntityFilter)+ }).toDispatchActions(['selectFilter', 'selectSeries'])++ await expectLogic(logic).toMatchValues({+ name: 'Users signed up',+ })+ })})})diff --git a/frontend/src/scenes/insights/filters/ActionFilter/renameModalLogic.ts b/frontend/src/scenes/insights/filters/ActionFilter/renameModalLogic.tsindex 1166ecb5e0dd..a1eb69e602ba 100644--- a/frontend/src/scenes/insights/filters/ActionFilter/renameModalLogic.ts+++ b/frontend/src/scenes/insights/filters/ActionFilter/renameModalLogic.ts@@ -1,14 +1,12 @@import { MakeLogicType, actions, connect, kea, key, path, props, reducers } from 'kea'import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'-import { getDisplayNameFromEntityFilter } from 'scenes/insights/utils'+import { getDisplayNameFromEntityNode } from 'scenes/insights/utils'-import { EntityFilterTypes } from '~/types'--import type { ActionFilter, EntityFilter } from '../../../../types'+import { SeriesNode } from './seriesNode'export interface RenameModalProps {- filter: EntityFilterTypes+ node: SeriesNode | nulltypeKey: string}@@ -19,8 +17,14 @@ export interface renameModalLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface renameModalLogicActions {- selectFilter: (filter: ActionFilter | EntityFilter | null) => {- filter: ActionFilter | EntityFilter | null+ selectSeries: (+ index: number | null,+ node?: SeriesNode | null | undefined,+ uuid?: string | undefined+ ) => {+ index: number | null+ node: SeriesNode | null | undefined+ uuid: string | undefined} // entityFilterLogicsetName: (name: string) => {name: string@@ -44,17 +48,17 @@ export const renameModalLogic = kea<renameModalLogicType>([key((props) => props.typeKey),path((key) => ['scenes', 'insights', 'ActionFilter', 'renameModalLogic', key]),connect((props: RenameModalProps) => ({- actions: [entityFilterLogic({ typeKey: props.typeKey }), ['selectFilter']],+ actions: [entityFilterLogic({ typeKey: props.typeKey }), ['selectSeries']],})),actions(() => ({setName: (name: string) => ({ name }),})),reducers(({ props }) => ({name: [- getDisplayNameFromEntityFilter(props.filter) ?? '',+ (props.node ? getDisplayNameFromEntityNode(props.node) : null) ?? '',{setName: (_, { name }) => name,- selectFilter: (_, { filter }) => getDisplayNameFromEntityFilter(filter) ?? '',+ selectSeries: (_, { node }) => (node ? (getDisplayNameFromEntityNode(node) ?? '') : ''),},],})),diff --git a/frontend/src/scenes/insights/filters/ActionFilter/seriesNode.ts b/frontend/src/scenes/insights/filters/ActionFilter/seriesNode.tsnew file mode 100644index 000000000000..2ce67e011936--- /dev/null+++ b/frontend/src/scenes/insights/filters/ActionFilter/seriesNode.ts@@ -0,0 +1,137 @@+import { getDefaultEventLabel, getDefaultEventName } from 'lib/utils/getAppContext'++import {+ ActionsNode,+ AnyDataWarehouseNode,+ AnyEntityNode,+ EventsNode,+ ExperimentDataWarehouseNode,+ GroupNode,+ NodeKind,+} from '~/queries/schema/schema-general'+import { setLatestVersionsOnQuery } from '~/queries/utils'+import { EntityType, EntityTypes } from '~/types'++/**+ * A row in the series editor. The warehouse arm widens to `ExperimentDataWarehouseNode`,+ * which experiments pass in as their `dataWarehouseNodeKind` and which the schema does not+ * count as an `AnyEntityNode`.+ */+export type SeriesNode = AnyEntityNode<AnyDataWarehouseNode | ExperimentDataWarehouseNode> | GroupNode++/** The node kind the editor creates when a person picks a warehouse table. */+export type WarehouseSeriesNodeKind =+ | NodeKind.DataWarehouseNode+ | NodeKind.FunnelsDataWarehouseNode+ | NodeKind.LifecycleDataWarehouseNode+ | NodeKind.ExperimentDataWarehouseNode++const WAREHOUSE_SERIES_NODE_KINDS = new Set<string>([+ NodeKind.DataWarehouseNode,+ NodeKind.FunnelsDataWarehouseNode,+ NodeKind.LifecycleDataWarehouseNode,+ NodeKind.ExperimentDataWarehouseNode,+])++export function isWarehouseSeriesNodeKind(kind: SeriesNode['kind']): kind is WarehouseSeriesNodeKind {+ return WAREHOUSE_SERIES_NODE_KINDS.has(kind)+}++export function isWarehouseSeriesNode(+ node: SeriesNode | null | undefined+): node is AnyDataWarehouseNode | ExperimentDataWarehouseNode {+ return !!node && WAREHOUSE_SERIES_NODE_KINDS.has(node.kind)+}++export function isEventsSeriesNode(node: SeriesNode | null | undefined): node is EventsNode {+ return node?.kind === NodeKind.EventsNode+}++export function isActionsSeriesNode(node: SeriesNode | null | undefined): node is ActionsNode {+ return node?.kind === NodeKind.ActionsNode+}++export function isGroupSeriesNode(node: SeriesNode | null | undefined): node is GroupNode {+ return node?.kind === NodeKind.GroupNode+}++/**+ * An events node with no event queries every event. `getDisplayNameFromEntityNode` reads the+ * same spelling, so both stay on an explicit `null` rather than treating a missing event as+ * all-events.+ */+export function isAllEventsSeriesNode(node: SeriesNode | null | undefined): boolean {+ return isEventsSeriesNode(node) && node.event === null && (!node.name || node.name === 'All events')+}++/**+ * The key the row queries: the event, the action id, or the table. A group has none of its+ * own, so it reports `null` and the editor identifies it by index alone.+ */+export function seriesNodeKey(node: SeriesNode | null | undefined): string | number | null {+ if (!node) {+ return null+ }+ if (isEventsSeriesNode(node)) {+ return node.event ?? null+ }+ if (isActionsSeriesNode(node)) {+ return node.id+ }+ if (isWarehouseSeriesNode(node)) {+ return node.table_name+ }+ return null+}++const ENTITY_TYPE_BY_SERIES_NODE_KIND: Partial<Record<string, EntityType>> = {+ [NodeKind.EventsNode]: EntityTypes.EVENTS,+ [NodeKind.ActionsNode]: EntityTypes.ACTIONS,+ [NodeKind.DataWarehouseNode]: EntityTypes.DATA_WAREHOUSE,+ [NodeKind.FunnelsDataWarehouseNode]: EntityTypes.DATA_WAREHOUSE,+ [NodeKind.LifecycleDataWarehouseNode]: EntityTypes.DATA_WAREHOUSE,+ [NodeKind.ExperimentDataWarehouseNode]: EntityTypes.DATA_WAREHOUSE,+ [NodeKind.GroupNode]: EntityTypes.GROUPS,+}++/** For the parts of the UI still keyed by the legacy entity type. */+export function seriesNodeEntityType(node: SeriesNode | null | undefined): EntityType | undefined {+ return node ? ENTITY_TYPE_BY_SERIES_NODE_KIND[node.kind] : undefined+}++export function seriesNodeKindForEntityType(+ type: EntityType | null | undefined,+ warehouseKind: WarehouseSeriesNodeKind+): SeriesNode['kind'] {+ switch (type) {+ case EntityTypes.ACTIONS:+ return NodeKind.ActionsNode+ case EntityTypes.DATA_WAREHOUSE:+ return warehouseKind+ case EntityTypes.GROUPS:+ return NodeKind.GroupNode+ default:+ return NodeKind.EventsNode+ }+}++/**+ * An action id reaches the editor as a string from the taxonomic picker, while the schema types+ * `ActionsNode.id` as an integer. Coerce once, here, so no consumer has to repair it later.+ */+export function toActionId(id: string | number | null | undefined): number {+ return typeof id === 'string' ? parseInt(id) : (id ?? 0)+}++export function withLatestVersion<T extends SeriesNode>(node: T): T {+ return setLatestVersionsOnQuery(node)+}++export function createDefaultEventsNode(defaults?: Partial<EventsNode>): EventsNode {+ return withLatestVersion({+ kind: NodeKind.EventsNode,+ event: getDefaultEventName(),+ name: getDefaultEventLabel(),+ ...defaults,+ } as EventsNode)+}diff --git a/frontend/src/scenes/insights/utils.tsx b/frontend/src/scenes/insights/utils.tsxindex b7e5c3f19cfb..1b8bbc2dc7be 100644--- a/frontend/src/scenes/insights/utils.tsx+++ b/frontend/src/scenes/insights/utils.tsx@@ -13,6 +13,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'import { objectsEqual } from 'lib/utils/objects'import { removeUndefinedAndNull } from 'lib/utils/objects'import { ensureStringIsNotBlank } from 'lib/utils/strings'+import { isWarehouseSeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -22,6 +23,7 @@ import { examples } from '~/queries/examples'import {AnyDataWarehouseNode,AnyEntityNode,+ ExperimentDataWarehouseNode,BreakdownFilter,DashboardFilter,FileSystemIconType,@@ -41,9 +43,8 @@ import {} from '~/queries/schema/schema-general'import {containsHogQLQuery,- isDataTableNode,isBIVisualizationNode,- isAnyDataWarehouseNode,+ isDataTableNode,isEventsNode,isGroupNode,isInsightVizNode,@@ -120,7 +121,7 @@ export const getDisplayNameFromEntityFilter = (}export const getDisplayNameFromEntityNode = (- node: AnyEntityNode<AnyDataWarehouseNode> | GroupNode,+ node: AnyEntityNode<AnyDataWarehouseNode | ExperimentDataWarehouseNode> | GroupNode,isCustom = true): string | null => {// Make sure names aren't blank strings@@ -142,7 +143,7 @@ export const getDisplayNameFromEntityNode = (name = 'All events'}- const id = isAnyDataWarehouseNode(node)+ const id = isWarehouseSeriesNode(node)? node.table_name: isEventsNode(node)? node.eventdiff --git a/frontend/src/scenes/insights/utils/cleanFilters.ts b/frontend/src/scenes/insights/utils/cleanFilters.tsindex 79f31fd50089..e074e81f9919 100644--- a/frontend/src/scenes/insights/utils/cleanFilters.ts+++ b/frontend/src/scenes/insights/utils/cleanFilters.ts@@ -43,7 +43,7 @@ import {import { DEFAULT_STEP_LIMIT } from 'products/product_analytics/frontend/insights/paths/pathsDataLogic'-import { LocalFilter, toLocalFilters } from '../filters/ActionFilter/entityFilterLogic'+import { LocalFilter, toLocalFilters } from '../filters/ActionFilter/legacyFilters'export function getDefaultEvent(): Entity {const event = getDefaultEventName()diff --git a/frontend/src/scenes/session-recordings/playlist/playlistUtils.ts b/frontend/src/scenes/session-recordings/playlist/playlistUtils.tsindex 5166aa2e297f..da29f7e1ff62 100644--- a/frontend/src/scenes/session-recordings/playlist/playlistUtils.ts+++ b/frontend/src/scenes/session-recordings/playlist/playlistUtils.ts@@ -8,7 +8,7 @@ import { isActionFilter, isEventFilter } from 'lib/components/UniversalFilters/uimport { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { deleteWithUndo } from 'lib/utils/deleteWithUndo'import { genericOperatorMap } from 'lib/utils/operators'-import { toLocalFilters } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'+import { toLocalFilters } from 'scenes/insights/filters/ActionFilter/legacyFilters'import { getDisplayNameFromEntityFilter } from 'scenes/insights/utils'import { DEFAULT_RECORDING_FILTERS } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'import { teamLogic } from 'scenes/teamLogic'