: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): keep the trends formula editor in step with the query (#103989)
Thomas Obermüller207411d41807
diff --git a/frontend/src/queries/nodes/InsightViz/TrendsFormula.test.tsx b/frontend/src/queries/nodes/InsightViz/TrendsFormula.test.tsxnew file mode 100644index 000000000000..74c2bf9c84cc--- /dev/null+++ b/frontend/src/queries/nodes/InsightViz/TrendsFormula.test.tsx@@ -0,0 +1,78 @@+import '@testing-library/jest-dom'++import { act, cleanup, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'++import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'++import { TrendsFormulaNode } from '~/queries/schema/schema-general'+import { buildTrendsQuery, getQuerySource, INSIGHT_TEST_ID, renderInsightPage } from '~/test/insight-testing'++// Mounting the whole filter editor can outrun Jest's 5s default on a contended shard.+jest.setTimeout(15000)++const FORMULA_PLACEHOLDER = 'Example: (A + B) / 100'++function formulaInputs(): HTMLInputElement[] {+ return screen.queryAllByPlaceholderText(FORMULA_PLACEHOLDER) as HTMLInputElement[]+}++function nodes(...formulas: string[]): TrendsFormulaNode[] {+ return formulas.map((formula) => ({ formula }))+}++/** Rewrite the query's formulas the way the source query editor does. Formula mode stays on,+ * so TrendsSeries never remounts the editor and its local state has to catch up. */+function rewriteFormulasOutsideTheEditor(formulaNodes: TrendsFormulaNode[]): void {+ act(() => {+ insightVizDataLogic({ dashboardItemId: INSIGHT_TEST_ID }).actions.updateInsightFilter({ formulaNodes })+ })+}++describe('TrendsFormula', () => {+ afterEach(cleanup)++ it('drops the formula from the query when its only input is emptied', async () => {+ renderInsightPage({ query: buildTrendsQuery({ trendsFilter: { formulaNodes: nodes('A') } }) })++ const input = await screen.findByPlaceholderText(FORMULA_PLACEHOLDER)+ await userEvent.clear(input)+ await userEvent.tab()++ await waitFor(() => expect(getQuerySource().trendsFilter?.formulaNodes).toEqual([]))+ })++ it('clears a field whose formula the query lost, so a blur cannot restore it', async () => {+ renderInsightPage({ query: buildTrendsQuery() })++ 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')))++ rewriteFormulasOutsideTheEditor([])++ await waitFor(() => expect(formulaInputs().map((input) => input.value)).toEqual(['']))++ await userEvent.click(formulaInputs()[0])+ await userEvent.tab()+ expect(getQuerySource().trendsFilter?.formulaNodes).toEqual([])+ })++ const rewrites: [string, TrendsFormulaNode[], TrendsFormulaNode[], string[]][] = [+ ['grown', nodes('A'), nodes('A', 'B', 'C'), ['A', 'B', 'C']],+ ['shrunk', nodes('A', 'B', 'C'), nodes('B'), ['B']],+ ]++ it.each(rewrites)(+ 'shows one input per formula after the query has %s elsewhere',+ async (_, initialNodes, rewrittenNodes, expectedInputValues) => {+ renderInsightPage({ query: buildTrendsQuery({ trendsFilter: { formulaNodes: initialNodes } }) })+ await waitFor(() => expect(formulaInputs()).toHaveLength(initialNodes.length))++ rewriteFormulasOutsideTheEditor(rewrittenNodes)++ await waitFor(() => expect(formulaInputs().map((input) => input.value)).toEqual(expectedInputValues))+ }+ )+})diff --git a/frontend/src/test/insight-testing/index.ts b/frontend/src/test/insight-testing/index.tsindex 0f28fe3c1c9f..4efe0ba4e4dc 100644--- a/frontend/src/test/insight-testing/index.ts+++ b/frontend/src/test/insight-testing/index.ts@@ -8,6 +8,7 @@ export {buildFunnelsQuery,buildStickinessQuery,buildTrendsQuery,+ INSIGHT_TEST_ID,renderInsight,renderInsightPage,renderWithInsights,diff --git a/products/product_analytics/frontend/insights/trends/filters/TrendsFormula.tsx b/products/product_analytics/frontend/insights/trends/filters/TrendsFormula.tsxindex f2112f23969d..46a99dd08658 100644--- a/products/product_analytics/frontend/insights/trends/filters/TrendsFormula.tsx+++ b/products/product_analytics/frontend/insights/trends/filters/TrendsFormula.tsx@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react'import { IconPlusSmall, IconTrash } from '@posthog/icons'import { LemonButton, LemonInput } from '@posthog/lemon-ui'+import { objectsEqual } from 'lib/utils/objects'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'import { TrendsFormulaNode } from '~/queries/schema/schema-general'@@ -16,43 +17,53 @@ export function TrendsFormula({ insightProps }: EditorFilterProps): JSX.Elementconst { formulaNodes, hasFormula } = useValues(insightVizDataLogic(insightProps))const { updateInsightFilter, removeFormulaNode } = useActions(insightVizDataLogic(insightProps))- // Initialize with at least one empty value- const [values, setValues] = useState<TrendsFormulaNode[]>(formulaNodes)- const [localValues, setLocalValues] = useState<TrendsFormulaNode[]>(values)+ const [localValues, setLocalValues] = useState<TrendsFormulaNode[]>(formulaNodes)useEffect(() => {// Don't clear the formulas so that the values are still there after toggling the formula switch.// formulaNodes is [] (truthy) when no formula is set, so check length to fall through to the// hasFormula branch that seeds one empty input when formula mode is toggled on.if (formulaNodes && formulaNodes.length > 0) {- setValues(formulaNodes)- // Merge incoming formulas with existing local fields, maintaining order+ // Merge incoming formulas with existing local fields, maintaining order. The source+ // query editor can change the query while this editor stays mounted, so the counts+ // can differ.setLocalValues((prev) => {- const newValues = [...prev]- // Update existing non-empty fields with backend values+ const merged: TrendsFormulaNode[] = []let backendIndex = 0- for (let i = 0; i < newValues.length && backendIndex < formulaNodes.length; i++) {- if (newValues[i].formula.trim() !== '') {- newValues[i] = formulaNodes[backendIndex]+ for (const localValue of prev) {+ if (localValue.formula.trim() === '') {+ merged.push(localValue)+ } else if (backendIndex < formulaNodes.length) {+ merged.push(formulaNodes[backendIndex])backendIndex++}}- return newValues+ while (backendIndex < formulaNodes.length) {+ merged.push(formulaNodes[backendIndex])+ backendIndex+++ }+ return merged})} else if (hasFormula) {- // Always ensure at least one empty value when formula mode is enabled- if (values.length === 0) {- const emptyNode = { formula: '' }- setValues([emptyNode])- setLocalValues([emptyNode])- }+ // The query can lose every formula from outside this editor. Drop the fields that+ // held them, so a later blur cannot write a formula back that the query no longer+ // has, and keep one blank field for the user to type in.+ setLocalValues((prev) => {+ const blanks = prev.filter((node) => node.formula.trim() === '')+ if (blanks.length === 0) {+ return [{ formula: '' }]+ }+ return blanks.length === prev.length ? prev : blanks+ })}}, [formulaNodes, hasFormula]) // oxlint-disable-line react-hooks/exhaustive-depsconst updateFormulas = (newValues: TrendsFormulaNode[]): void => {// Filter out empty values when updating the query but keep them in local stateconst filledValues = newValues.filter((v) => v.formula.trim() !== '')- if (filledValues.length === 0) {+ // Blurring a field the user did not change is the common case, so skip the query update+ // and the refetch it triggers.+ if (objectsEqual(filledValues, formulaNodes)) {return}@@ -82,21 +93,15 @@ export function TrendsFormula({ insightProps }: EditorFilterProps): JSX.ElementsetLocalValues(newValues)}- const handleFormulaBlur = (index: number, e: React.FocusEvent<HTMLInputElement>): void => {+ const handleFormulaBlur = (e: React.FocusEvent<HTMLInputElement>): void => {// Ignore TrendsFormulaLabel switch click to prevent conflicting updateInsightFilter callsif ((e.relatedTarget as HTMLElement | undefined)?.id !== 'trends-formula-switch') {- // Only update if the current field has content- if (localValues[index].formula.trim() !== '') {- updateFormulas(localValues)- }+ updateFormulas(localValues)}}- const handleCustomNameBlur = (index: number): void => {- // Only update if the current field has a formula with content- if (localValues[index].formula.trim() !== '') {- updateFormulas(localValues)- }+ const handleCustomNameBlur = (): void => {+ updateFormulas(localValues)}const handleFormulaEnter = (): void => {@@ -125,7 +130,7 @@ export function TrendsFormula({ insightProps }: EditorFilterProps): JSX.ElementautoFocus={index === localValues.length - 1}value={value.formula}onChange={(value) => handleFormulaChange(index, value)}- onBlur={(e) => handleFormulaBlur(index, e)}+ onBlur={handleFormulaBlur}onPressEnter={handleFormulaEnter}/><LemonInput@@ -134,7 +139,7 @@ export function TrendsFormula({ insightProps }: EditorFilterProps): JSX.Elementsize="small"value={value.custom_name || ''}onChange={(value) => handleCustomNameChange(index, value)}- onBlur={() => handleCustomNameBlur(index)}+ onBlur={handleCustomNameBlur}onPressEnter={handleFormulaEnter}/><LemonButton