A local-first personal finance app
[AI] Fix flickering text on the formula dashboard card (#8676)
youngcw93909fc80554
diff --git a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsxindex d194b78b6b..67a3962199 100644--- a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx@@ -2,7 +2,10 @@ import { useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { View } from '@actual-app/components/view';-import type { FormulaWidget } from '@actual-app/core/types/models';+import type {+ AccountEntity,+ FormulaWidget,+} from '@actual-app/core/types/models';import { FormulaResult } from '#components/reports/FormulaResult';import { ReportCard } from '#components/reports/ReportCard';@@ -18,17 +21,26 @@ type FormulaCardProps = {onMetaChange: (newMeta: FormulaWidget['meta']) => void;};+// Stable identities so a card without named queries, or one rendered before+// accounts have loaded, doesn't hand `useFormulaExecution` a fresh object on+// every render.+const EMPTY_QUERIES = {};+const EMPTY_ACCOUNTS: AccountEntity[] = [];+export function FormulaCard({widgetId,isEditing,- meta = {},+ meta,onMetaChange,}: FormulaCardProps) {const { t } = useTranslation();const [nameMenuOpen, setNameMenuOpen] = useState(false);const themeColors = useThemeColors();const containerRef = useRef<HTMLDivElement>(null);- const { data: accounts = [] } = useAccounts();+ // Not `const { data: accounts = [] }` — a default inside a destructuring+ // pattern makes React Compiler bail out of the whole component, which leaves+ // the objects handed to `useFormulaExecution` unmemoized.+ const accounts = useAccounts().data ?? EMPTY_ACCOUNTS;const formula = meta?.formula || '=SUM(1, 2, 3)';const fontSize = meta?.fontSize;@@ -47,7 +59,7 @@ export function FormulaCard({const { result, isLoading, error } = useFormulaExecution(formula,- meta?.queries || {},+ meta?.queries ?? EMPTY_QUERIES,meta?.queriesVersion,undefined,simpleAccounts,@@ -68,7 +80,7 @@ export function FormulaCard({);const { result: colorResult, error: colorError } = useFormulaExecution(colorFormula,- meta?.queries || {},+ meta?.queries ?? EMPTY_QUERIES,meta?.queriesVersion,colorVariables,simpleAccounts,@@ -94,7 +106,7 @@ export function FormulaCard({isEditing={nameMenuOpen}onChange={newName => {onMetaChange({- ...meta,+ ...(meta ?? {}),name: newName,});setNameMenuOpen(false);@@ -115,11 +127,14 @@ export function FormulaCard({<FormulaResultvalue={result}error={error}- loading={isLoading}+ // Only fall back to the skeleton when there is nothing to show yet;+ // a refresh should leave the previous value in place rather than+ // blanking the card.+ loading={isLoading && result === null && !error}initialFontSize={fontSize}fontSizeChanged={newSize => {onMetaChange({- ...meta,+ ...(meta ?? {}),fontSize: newSize,});}}diff --git a/packages/desktop-client/src/hooks/useFormulaExecution.test.ts b/packages/desktop-client/src/hooks/useFormulaExecution.test.tsindex 7084e8f687..26843c31bb 100644--- a/packages/desktop-client/src/hooks/useFormulaExecution.test.ts+++ b/packages/desktop-client/src/hooks/useFormulaExecution.test.ts@@ -302,3 +302,86 @@ describe('BALANCE_OF in query mode', () => {expect(queryPayloads).toHaveLength(0);});});++describe('formula execution stability', () => {+ let executionCount: number;++ beforeEach(() => {+ executionCount = 0;+ initServer({+ 'formula-load-user-preferences': async () => {+ executionCount += 1;+ return {+ currency: getCurrency('USD'),+ numberFormat: 'comma-dot',+ decimalPlaces: 2,+ thousandsSeparator: ',',+ decimalSeparator: '.',+ locale: 'en-US',+ currencySymbolPosition: 'before',+ currencySpaceBetweenAmountAndSymbol: false,+ };+ },+ });+ });++ afterEach(async () => {+ await clearServer();+ });++ it('does not re-execute when callers pass new objects each render', async () => {+ // Callers such as FormulaCard build `queries`/`accounts` inline, so those+ // objects have a fresh identity on every render. Keying the effect on+ // identity would re-execute forever, flickering the card between value and+ // skeleton.+ const { result, rerender } = renderHook(+ () =>+ useFormulaExecution('=SUM(1, 2, 3)', {}, undefined, { RESULT: 0 }, [+ { id: 'acc1', name: 'Checking' },+ ]),+ { wrapper: TestProviders },+ );++ await waitFor(() => expect(result.current.result).toBe(6));+ expect(executionCount).toBe(1);++ rerender();+ rerender();+ rerender();++ await waitFor(() => expect(result.current.isLoading).toBe(false));+ expect(executionCount).toBe(1);+ });++ it('re-executes when the queries contents actually change', async () => {+ const { result, rerender } = renderHook(+ ({ conditionValue }: { conditionValue: string }) =>+ useFormulaExecution('=SUM(1, 2, 3)', {+ Income: { conditions: [categoryCondition(conditionValue)] },+ }),+ {+ wrapper: TestProviders,+ initialProps: { conditionValue: 'income-cat' },+ },+ );++ await waitFor(() => expect(result.current.result).toBe(6));+ expect(executionCount).toBe(1);++ rerender({ conditionValue: 'other-cat' });++ await waitFor(() => expect(executionCount).toBe(2));+ });++ it('clears the loading state for a formula that does not start with =', async () => {+ const { result } = renderHook(+ () => useFormulaExecution('SUM(1, 2, 3)', {}),+ { wrapper: TestProviders },+ );++ await waitFor(() =>+ expect(result.current.error).toBe('Formula must start with ='),+ );+ expect(result.current.isLoading).toBe(false);+ });+});diff --git a/packages/desktop-client/src/hooks/useFormulaExecution.ts b/packages/desktop-client/src/hooks/useFormulaExecution.tsindex 03fe9de28e..c8673e6604 100644--- a/packages/desktop-client/src/hooks/useFormulaExecution.ts+++ b/packages/desktop-client/src/hooks/useFormulaExecution.ts@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { send } from '@actual-app/core/platform/client/connection';import {@@ -148,6 +148,23 @@ export function useFormulaExecution(const [isLoading, setIsLoading] = useState(false);const [error, setError] = useState<string | null>(null);+ // Callers pass `queries`/`namedExpressions`/`accounts` as plain objects, and+ // several of them build a fresh object on every render. Keying the effect on+ // the object identity would re-execute the formula on every render (and each+ // execution toggles `isLoading`, which renders again — an endless loop).+ // Depend on the serialized contents instead, and read the live objects+ // through refs.+ const queriesKey = JSON.stringify(queries ?? {});+ const namedExpressionsKey = JSON.stringify(namedExpressions ?? null);+ const accountsKey = JSON.stringify(accounts ?? null);++ const queriesRef = useRef(queries);+ queriesRef.current = queries;+ const namedExpressionsRef = useRef(namedExpressions);+ namedExpressionsRef.current = namedExpressions;+ const accountsRef = useRef(accounts);+ accountsRef.current = accounts;+useEffect(() => {let cancelled = false;@@ -155,9 +172,14 @@ export function useFormulaExecution(if (!formula || !formula.startsWith('=')) {setResult(null);setError('Formula must start with =');+ setIsLoading(false);return;}+ const currentQueries = queriesRef.current;+ const currentNamedExpressions = namedExpressionsRef.current;+ const currentAccounts = accountsRef.current;+setIsLoading(true);setError(null);@@ -183,19 +205,22 @@ export function useFormulaExecution(formula,formulaQueryContext,locale: formulaLocale,- namedExpressions,+ namedExpressions: currentNamedExpressions,throwOnCellError: false,});- await prefetchFormulaQueries(formulaQueryContext, queries);- await prefetchAccountBalances(formulaQueryContext, accounts ?? []);+ await prefetchFormulaQueries(formulaQueryContext, currentQueries);+ await prefetchAccountBalances(+ formulaQueryContext,+ currentAccounts ?? [],+ );formulaQueryContext.budgetQueryRequests.clear();evaluateFormulaWithContext({formula,formulaQueryContext,locale: formulaLocale,- namedExpressions,+ namedExpressions: currentNamedExpressions,throwOnCellError: false,});@@ -205,7 +230,7 @@ export function useFormulaExecution(formula,formulaQueryContext,locale: formulaLocale,- namedExpressions,+ namedExpressions: currentNamedExpressions,});if (cancelled) return;@@ -234,9 +259,9 @@ export function useFormulaExecution(queriesVersion,locale,language,- queries,- namedExpressions,- accounts,+ queriesKey,+ namedExpressionsKey,+ accountsKey,]);return { result, isLoading, error };diff --git a/upcoming-release-notes/fix-formula-card-flicker.md b/upcoming-release-notes/fix-formula-card-flicker.mdnew file mode 100644index 0000000000..3c4dabef30--- /dev/null+++ b/upcoming-release-notes/fix-formula-card-flicker.md@@ -0,0 +1,6 @@+---+category: Bugfix+authors: [youngcw]+---++Fix the formula card on the reports dashboard flickering between its value and a loading placeholder