: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
fix(insights): turn formula mode off when the last formula goes (#103999)
Thomas Obermüllerd27b586f38d6
diff --git a/frontend/src/queries/nodes/InsightViz/TrendsFormula.test.tsx b/frontend/src/queries/nodes/InsightViz/TrendsFormula.test.tsxindex 74c2bf9c84cc..057a17abced7 100644--- a/frontend/src/queries/nodes/InsightViz/TrendsFormula.test.tsx+++ b/frontend/src/queries/nodes/InsightViz/TrendsFormula.test.tsx@@ -32,31 +32,94 @@ function rewriteFormulasOutsideTheEditor(formulaNodes: TrendsFormulaNode[]): voidescribe('TrendsFormula', () => {afterEach(cleanup)- it('drops the formula from the query when its only input is emptied', async () => {+ const removals: [string, () => Promise<void>][] = [+ [+ 'emptying its only input',+ async () => {+ await userEvent.clear(await screen.findByPlaceholderText(FORMULA_PLACEHOLDER))+ await userEvent.tab()+ },+ ],+ [+ 'removing its only input',+ async () => {+ await userEvent.click(await screen.findByTitle('Remove formula and disable formula mode'))+ },+ ],+ [+ 'switching formula mode off',+ async () => {+ await screen.findByPlaceholderText(FORMULA_PLACEHOLDER)+ await userEvent.click(screen.getByTestId('trends-formula-switch'))+ },+ ],+ ]++ it.each(removals)('drops the formula from the query and closes the editor when %s', async (_, remove) => {renderInsightPage({ query: buildTrendsQuery({ trendsFilter: { formulaNodes: nodes('A') } }) })- const input = await screen.findByPlaceholderText(FORMULA_PLACEHOLDER)- await userEvent.clear(input)- await userEvent.tab()+ await remove()- await waitFor(() => expect(getQuerySource().trendsFilter?.formulaNodes).toEqual([]))+ await waitFor(() => {+ expect(getQuerySource().trendsFilter?.formulaNodes).toEqual([])+ expect(screen.queryByText('Add formula')).not.toBeInTheDocument()+ })})- it('clears a field whose formula the query lost, so a blur cannot restore it', async () => {- renderInsightPage({ query: buildTrendsQuery() })+ /** Each route leaves the editor open on one filled formula, so the removal behind it must not+ * change what emptying that formula does. */+ const routesToOneFormula: [string, TrendsFormulaNode[], () => Promise<void>][] = [+ [+ 'another was removed',+ nodes('A', 'B'),+ async () => {+ await waitFor(() => expect(formulaInputs()).toHaveLength(2))+ await userEvent.click(screen.getAllByTitle('Remove formula')[1])+ await waitFor(() => expect(getQuerySource().trendsFilter?.formulaNodes).toEqual(nodes('A')))+ },+ ],+ [+ 'the only filled one was removed and a new one typed',+ nodes('A'),+ async () => {+ await screen.findByPlaceholderText(FORMULA_PLACEHOLDER)+ await userEvent.click(screen.getByText('Add formula'))+ await userEvent.click(screen.getAllByTitle('Remove formula')[0])+ await waitFor(() => expect(getQuerySource().trendsFilter?.formulaNodes).toEqual([]))++ await userEvent.type(formulaInputs()[0], 'B')+ await userEvent.tab()+ await waitFor(() => expect(getQuerySource().trendsFilter?.formulaNodes).toEqual(nodes('B')))+ },+ ],+ ]++ it.each(routesToOneFormula)(+ 'closes the editor when the last formula is emptied after %s',+ async (_, initialNodes, reachOneFormula) => {+ renderInsightPage({ query: buildTrendsQuery({ trendsFilter: { formulaNodes: initialNodes } }) })++ await reachOneFormula()++ await userEvent.clear(formulaInputs()[0])+ await userEvent.tab()- await userEvent.click(await screen.findByTestId('trends-formula-switch'))- await userEvent.type(await screen.findByPlaceholderText(FORMULA_PLACEHOLDER), 'A')- await userEvent.tab()- await waitFor(() => expect(getQuerySource().trendsFilter?.formulaNodes).toEqual(nodes('A')))+ await waitFor(() => {+ expect(getQuerySource().trendsFilter?.formulaNodes).toEqual([])+ expect(screen.queryByText('Add formula')).not.toBeInTheDocument()+ })+ }+ )- rewriteFormulasOutsideTheEditor([])+ it('keeps the editor open on a blank input when the only filled formula is removed', async () => {+ renderInsightPage({ query: buildTrendsQuery({ trendsFilter: { formulaNodes: nodes('A') } }) })- await waitFor(() => expect(formulaInputs().map((input) => input.value)).toEqual(['']))+ await screen.findByPlaceholderText(FORMULA_PLACEHOLDER)+ await userEvent.click(screen.getByText('Add formula'))+ await userEvent.click(screen.getAllByTitle('Remove formula')[0])- await userEvent.click(formulaInputs()[0])- await userEvent.tab()- expect(getQuerySource().trendsFilter?.formulaNodes).toEqual([])+ await waitFor(() => expect(getQuerySource().trendsFilter?.formulaNodes).toEqual([]))+ expect(formulaInputs().map((input) => input.value)).toEqual([''])})const rewrites: [string, TrendsFormulaNode[], TrendsFormulaNode[], string[]][] = [diff --git a/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx b/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsxindex d57fa370aa69..917bba0887a2 100644--- a/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx+++ b/frontend/src/queries/nodes/InsightViz/TrendsSeries.tsx@@ -35,7 +35,7 @@ export function TrendsSeries(): JSX.Element | null {const { querySource, isTrends, isLifecycle, isStickiness, display, hasFormula, series } = useValues(insightVizDataLogic(insightProps))- const { updateQuerySource, toggleFormulaMode } = useActions(insightVizDataLogic(insightProps))+ const { updateQuerySource, setFormulaMode } = useActions(insightVizDataLogic(insightProps))const { groupsTaxonomicTypes } = useValues(groupsModel)@@ -75,7 +75,7 @@ export function TrendsSeries(): JSX.Element | null {<LemonSwitchclassName="mt-2"checked={hasFormula}- onChange={() => toggleFormulaMode()}+ onChange={setFormulaMode}disabled={hasFormula && !canDisableFormula}label="Formula mode"bordereddiff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.tsindex 09525bacd780..706e15d7bdc6 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts@@ -421,15 +421,15 @@ export interface insightVizDataLogicActions {setDetailedResultsAggregationType: (detailedResultsAggregationType: AggregationType) => {detailedResultsAggregationType: AggregationType}+ setFormulaMode: (enabled: boolean) => {+ enabled: boolean+ }setIsIntervalManuallySet: (isIntervalManuallySet: boolean) => {isIntervalManuallySet: boolean}setTimedOutQueryId: (id: string | null) => {id: string | null}- toggleFormulaMode: () => {- value: true- }updateBreakdownFilter: (breakdownFilter: BreakdownFilter) => {breakdownFilter: BreakdownFilter}@@ -1371,7 +1371,7 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([updateDisplay: (display: ChartDisplayType | undefined) => ({ display }),setTimedOutQueryId: (id: string | null) => ({ id }),setIsIntervalManuallySet: (isIntervalManuallySet: boolean) => ({ isIntervalManuallySet }),- toggleFormulaMode: true,+ setFormulaMode: (enabled: boolean) => ({ enabled }),removeFormulaNode: (formulas: TrendsFormulaNode[]) => ({ formulas }),setDetailedResultsAggregationType: (detailedResultsAggregationType: AggregationType) => ({detailedResultsAggregationType,@@ -1399,7 +1399,18 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([isFormulaModeOpenedExplicitly: [false,{- toggleFormulaMode: (state) => !state,+ setFormulaMode: (_, { enabled }) => enabled,+ // A blank row left behind still empties the query's formula list, so hold the+ // mode open or hasFormula closes the editor mid-edit. A filled row needs no flag.+ removeFormulaNode: (state, { formulas }) =>+ formulas.length > 0 && formulas.every((node) => node.formula.trim() === '') ? true : state,+ // A query that holds a formula keeps the mode open on its own, so drop the flag+ // there. It would otherwise outlive the removal that set it and hold the editor+ // open over the next empty field. The reset keys on setQuery, which is what writes+ // the formula into the query: reset it one action earlier and hasFormula is false+ // for a render, which closes the editor the user is typing in.+ setQuery: (state, { query }) =>+ isInsightVizNode(query) && (getFormulaNodes(query.source)?.length ?? 0) > 0 ? false : state,},],}),@@ -2820,26 +2831,24 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([loadDataFailure: () => {actions.setTimedOutQueryId(null)},- toggleFormulaMode: () => {- // Only if formula mode is already open should we trigger a query.- if (values.hasFormula) {+ setFormulaMode: ({ enabled }) => {+ // Turning the mode off has to clear the query's formulas too, because hasFormula reads+ // them back and would turn the mode straight on again.+ if (!enabled && values.formulaNodes.length > 0) {actions.updateInsightFilter({ formula: undefined, formulas: undefined, formulaNodes: [] })}},removeFormulaNode: ({ formulas }) => {if (formulas.length === 0) {- actions.toggleFormulaMode()+ actions.setFormulaMode(false)return}- const filledFormulas = formulas.filter((v) => v.formula.trim() !== '')- if (filledFormulas.length > 0) {- actions.updateInsightFilter({- formula: undefined,- formulas: undefined,- formulaNodes: filledFormulas,- })- }+ actions.updateInsightFilter({+ formula: undefined,+ formulas: undefined,+ formulaNodes: formulas.filter((v) => v.formula.trim() !== ''),+ })},})),afterMount(({ actions, values }) => {