A local-first personal finance app
[AI] Smooth report card number resizing with CSS (#9123)
Alexis Vielmaa5a3c26397a7
diff --git a/packages/desktop-client/e2e/reports.test.ts b/packages/desktop-client/e2e/reports.test.tsindex 6ac5d3ec76..15f3d2a192 100644--- a/packages/desktop-client/e2e/reports.test.ts+++ b/packages/desktop-client/e2e/reports.test.ts@@ -47,6 +47,27 @@ test.describe('Reports', () => {await expect(page).toMatchThemeScreenshots();});+ test('resizes number cards with the viewport', async () => {+ await page.setViewportSize({ width: 1440, height: 900 });++ const number = page.locator('[aria-label*="amount:"]').first();+ await expect(number).toBeVisible();+ const numberText = number.locator('span').first();+ const initialFontSize = await numberText.evaluate(+ element => getComputedStyle(element).fontSize,+ );+ await expect(number).toMatchThemeScreenshots();++ await page.setViewportSize({ width: 900, height: 900 });+ await expect(number).toMatchThemeScreenshots();++ await expect+ .poll(() =>+ numberText.evaluate(element => getComputedStyle(element).fontSize),+ )+ .not.toBe(initialFontSize);+ });+test('right clicking a report card opens context menu', async () => {await reportsPage.rightClickReportCard('Net Worth');const menu = page.getByRole('menu');diff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-1-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-1-chromium-linux.pngnew file mode 100644index 0000000000..563d76f9c1Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-2-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-2-chromium-linux.pngnew file mode 100644index 0000000000..e80e4847e7Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-3-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-3-chromium-linux.pngnew file mode 100644index 0000000000..49b3659b04Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-4-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-4-chromium-linux.pngnew file mode 100644index 0000000000..ca209bdf94Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-4-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-5-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-5-chromium-linux.pngnew file mode 100644index 0000000000..f7621ab186Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-5-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-6-chromium-linux.png b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-6-chromium-linux.pngnew file mode 100644index 0000000000..0836f39c93Binary files /dev/null and b/packages/desktop-client/e2e/reports.test.ts-snapshots/Reports-resizes-number-cards-with-the-viewport-6-chromium-linux.png differdiff --git a/packages/desktop-client/src/components/reports/FormulaResult.tsx b/packages/desktop-client/src/components/reports/FormulaResult.tsxindex ece351ce0d..4912506d0e 100644--- a/packages/desktop-client/src/components/reports/FormulaResult.tsx+++ b/packages/desktop-client/src/components/reports/FormulaResult.tsx@@ -1,21 +1,11 @@-import React, {- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from 'react';-import type { Ref, RefObject } from 'react';+import React, { useMemo } from 'react';import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';import { amountToInteger } from '@actual-app/core/shared/util';-import { debounce } from 'es-toolkit/compat';import { PrivacyFilter } from '#components/PrivacyFilter';import { useFormat } from '#hooks/useFormat';-import { useMergedRefs } from '#hooks/useMergedRefs';-import { useResizeObserver } from '#hooks/useResizeObserver';import { ReportCardValueSkeleton } from './ReportCardValueSkeleton';@@ -24,33 +14,21 @@ const CONTAINER_MARGIN = 8;type FormulaResultProps = {value: number | string | null;- animate?: boolean;loading?: boolean;error?: string | null;- initialFontSize?: number;- fontSizeChanged?: (fontSize: number) => void;fontSizeMode?: 'dynamic' | 'static';staticFontSize?: number;customColor?: string | null;- containerRef?: RefObject<HTMLDivElement | null>;};export function FormulaResult({value,- animate = false,loading = true,error = null,- initialFontSize = 14,- fontSizeChanged,fontSizeMode = 'dynamic',staticFontSize = 32,customColor = null,- containerRef,}: FormulaResultProps) {- const [fontSize, setFontSize] = useState<number>(initialFontSize);- const [hasSized, setHasSized] = useState(false);- const refDiv = useRef<HTMLDivElement>(null);- const previousFontSizeRef = useRef<number>(initialFontSize);const format = useFormat();// Format the display value - just show what we got@@ -69,89 +47,13 @@ export function FormulaResult({}}, [error, value, format]);- const calculateFontSize = useCallback(() => {- if (!refDiv.current) return;-- const elementToMeasure =- containerRef?.current || refDiv.current.parentElement || refDiv.current;- const { clientWidth, clientHeight } = elementToMeasure;-- const width = clientWidth;- const height = clientHeight - CONTAINER_MARGIN * 2;-- if (width <= 0 || height <= 0) return;-- // Check if the display value contains line breaks and calculate font size accordingly.- const lines = displayValue.split(/\r?\n/);- const lineCount = lines.length;- const longestLineLength = Math.max(...lines.map(line => line.length), 1);-- // Calculate font size based on the longest line and number of lines- const calculatedFontSize = Math.min(- (width * FONT_SIZE_SCALE_FACTOR) / longestLineLength,- height / lineCount, // Divide height by number of lines to fit all lines- );-- if (calculatedFontSize > 0) {- setFontSize(calculatedFontSize);- setHasSized(true);- }-- // Only call fontSizeChanged if the font size actually changed- if (- fontSizeChanged &&- Math.abs(calculatedFontSize - previousFontSizeRef.current) > 0.5- ) {- previousFontSizeRef.current = calculatedFontSize;- fontSizeChanged(calculatedFontSize);- }- }, [displayValue, fontSizeChanged, containerRef]);-- // Debounce the calculation to avoid too many recalculations- const debouncedCalculateFontSize = useRef(- debounce(() => {- if (fontSizeMode === 'dynamic') {- calculateFontSize();- }- }, 100),- );-- // Update the debounced function when calculateFontSize changes- useEffect(() => {- debouncedCalculateFontSize.current.cancel?.();- debouncedCalculateFontSize.current = debounce(() => {- if (fontSizeMode === 'dynamic') {- calculateFontSize();- }- }, 100);-- return () => {- debouncedCalculateFontSize.current.cancel?.();- };- }, [calculateFontSize, fontSizeMode]);-- const ref = useResizeObserver(() => {- if (fontSizeMode === 'dynamic') {- debouncedCalculateFontSize.current();- }- });- const mergedRef = useMergedRefs(ref, refDiv);-- // Recalculate font size when displayValue changes (non-debounced for immediate update)- // Only for dynamic mode- useEffect(() => {- if (fontSizeMode === 'dynamic') {- calculateFontSize();- }- }, [displayValue, calculateFontSize, fontSizeMode]);-- // Use static font size when in static mode- useEffect(() => {- if (fontSizeMode === 'static') {- setFontSize(staticFontSize);- setHasSized(true);- }- }, [fontSizeMode, staticFontSize]);+ const lines = displayValue.split(/\r?\n/);+ const lineCount = lines.length;+ const longestLineLength = Math.max(...lines.map(line => line.length), 1);+ const fontSize =+ fontSizeMode === 'static'+ ? `${staticFontSize}px`+ : `min(${(FONT_SIZE_SCALE_FACTOR * 100) / longestLineLength}cqi, calc((100cqb - ${CONTAINER_MARGIN * 2}px) / ${lineCount}))`;// Determine colorconst color = customColor@@ -160,14 +62,11 @@ export function FormulaResult({? theme.errorText: theme.pageText;- const showContent = hasSized || fontSizeMode === 'static';-return (- <View style={{ flex: 1 }}>+ <View style={{ flex: 1, width: '100%', containerType: 'size' }}>{loading && <ReportCardValueSkeleton />}{!loading && (<View- ref={mergedRef as Ref<HTMLDivElement>}aria-label={displayValue}style={{alignItems: 'center',@@ -180,24 +79,19 @@ export function FormulaResult({lineHeight: 1,margin: `${CONTAINER_MARGIN}px 0`,justifyContent: 'center',- transition: animate ? 'font-size 0.3s ease' : '',color,}}>- {!showContent ? (- <ReportCardValueSkeleton />- ) : (- <span- aria-hidden="true"- style={{- whiteSpace: 'pre-wrap',- textAlign: 'center',- wordBreak: 'break-word',- }}- >- <PrivacyFilter>{displayValue}</PrivacyFilter>- </span>- )}+ <span+ aria-hidden="true"+ style={{+ whiteSpace: 'pre-wrap',+ textAlign: 'center',+ wordBreak: 'break-word',+ }}+ >+ <PrivacyFilter>{displayValue}</PrivacyFilter>+ </span></View>)}</View>diff --git a/packages/desktop-client/src/components/reports/SummaryNumber.tsx b/packages/desktop-client/src/components/reports/SummaryNumber.tsxindex 5b859b58ac..bd0aaff2aa 100644--- a/packages/desktop-client/src/components/reports/SummaryNumber.tsx+++ b/packages/desktop-client/src/components/reports/SummaryNumber.tsx@@ -1,16 +1,12 @@-import React, { useRef, useState } from 'react';-import type { Ref } from 'react';+import React from 'react';import { useTranslation } from 'react-i18next';import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';-import { debounce } from 'es-toolkit/compat';import { FinancialText } from '#components/FinancialText';import { PrivacyFilter } from '#components/PrivacyFilter';import { useFormat } from '#hooks/useFormat';-import { useMergedRefs } from '#hooks/useMergedRefs';-import { useResizeObserver } from '#hooks/useResizeObserver';import { ReportCardValueSkeleton } from './ReportCardValueSkeleton';@@ -20,26 +16,17 @@ const CONTAINER_MARGIN = 8;type SummaryNumberProps = {value: number;contentType: string;- animate?: boolean;suffix?: string;loading?: boolean;- initialFontSize?: number;- fontSizeChanged?: (fontSize: number) => void;};export function SummaryNumber({value,contentType,- animate = false,suffix = '',loading = true,- initialFontSize = 14,- fontSizeChanged,}: SummaryNumberProps) {const { t } = useTranslation();- const [fontSize, setFontSize] = useState<number>(initialFontSize);- const [hasSized, setHasSized] = useState(false);- const refDiv = useRef<HTMLDivElement>(null);const format = useFormat();const isNumericValue = Number.isFinite(value);@@ -50,37 +37,13 @@ export function SummaryNumber({displayAmount += suffix;- const handleResize = debounce(() => {- if (!refDiv.current) return;-- const { clientWidth, clientHeight } = refDiv.current;- const width = clientWidth; // no margin required on left and right- const height = clientHeight - CONTAINER_MARGIN * 2; // account for margin top and bottom-- const calculatedFontSize = Math.min(- (width * FONT_SIZE_SCALE_FACTOR) / displayAmount.toString().length,- height, // Ensure the text fits vertically by using the height as the limiting factor- );-- if (calculatedFontSize > 0) {- setFontSize(calculatedFontSize);- setHasSized(true);- }-- if (calculatedFontSize !== initialFontSize && fontSizeChanged) {- fontSizeChanged(calculatedFontSize);- }- }, 100);-- const ref = useResizeObserver(handleResize);- const mergedRef = useMergedRefs(ref, refDiv);+ const fontSize = `min(${(FONT_SIZE_SCALE_FACTOR * 100) / displayAmount.length}cqi, calc(100cqb - ${CONTAINER_MARGIN * 2}px))`;return (<>{loading && <ReportCardValueSkeleton />}{!loading && (<View- ref={mergedRef as Ref<HTMLDivElement>}aria-label={!isNumericValue? t('Unknown amount')@@ -97,11 +60,9 @@ export function SummaryNumber({width: '100%',height: '100%',maxWidth: '100%',- fontSize,- lineHeight: 1,+ containerType: 'size',margin: `${CONTAINER_MARGIN}px 0`,justifyContent: 'center',- transition: animate ? 'font-size 0.3s ease' : '',color: !isNumericValue? theme.reportsNumberNeutral: value === 0@@ -111,13 +72,9 @@ export function SummaryNumber({: theme.reportsNumberPositive,}}>- {!hasSized ? (- <ReportCardValueSkeleton />- ) : (- <FinancialText aria-hidden="true">- <PrivacyFilter>{displayAmount}</PrivacyFilter>- </FinancialText>- )}+ <FinancialText aria-hidden="true" style={{ fontSize, lineHeight: 1 }}>+ <PrivacyFilter>{displayAmount}</PrivacyFilter>+ </FinancialText></View>)}</>diff --git a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsxindex 67a3962199..4ee7af9575 100644--- a/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/FormulaCard.tsx@@ -1,4 +1,4 @@-import { useMemo, useRef, useState } from 'react';+import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { View } from '@actual-app/components/view';@@ -36,14 +36,12 @@ export function FormulaCard({const { t } = useTranslation();const [nameMenuOpen, setNameMenuOpen] = useState(false);const themeColors = useThemeColors();- const containerRef = useRef<HTMLDivElement>(null);// 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;const fontSizeMode = meta?.fontSizeMode || 'dynamic';const staticFontSize = meta?.staticFontSize || 32;const showTitle = meta?.showTitle ?? true;@@ -116,7 +114,6 @@ export function FormulaCard({</View>)}<View- ref={containerRef}style={{justifyContent: 'center',alignItems: 'center',@@ -131,18 +128,9 @@ export function FormulaCard({// 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 ?? {}),- fontSize: newSize,- });- }}fontSizeMode={fontSizeMode}staticFontSize={staticFontSize}customColor={customColor}- animate={isEditing ?? false}- containerRef={containerRef}/></View></View>diff --git a/packages/desktop-client/src/components/reports/reports/SummaryCard.tsx b/packages/desktop-client/src/components/reports/reports/SummaryCard.tsxindex e2dea62e14..71d6db91cc 100644--- a/packages/desktop-client/src/components/reports/reports/SummaryCard.tsx+++ b/packages/desktop-client/src/components/reports/reports/SummaryCard.tsx@@ -126,8 +126,6 @@ export function SummaryCard({contentType={content.type}suffix={content.type === 'percentage' ? '%' : ''}loading={!data}- initialFontSize={content.fontSize}- animate={isEditing ?? false}/>) : (<ReportCardValueSkeleton />diff --git a/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-checks-the-page-visuals-1-linux.png b/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-checks-the-page-visuals-1-linux.pngindex 5ed44a50cb..f6b310e595 100644Binary files a/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-checks-the-page-visuals-1-linux.png and b/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-checks-the-page-visuals-1-linux.png differdiff --git a/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-checks-the-page-visuals-2-linux.png b/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-checks-the-page-visuals-2-linux.pngindex c1a75fd583..a2d5c1708e 100644Binary files a/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-checks-the-page-visuals-2-linux.png and b/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-checks-the-page-visuals-2-linux.png differdiff --git a/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-starts-the-sync-server-and-navigates-to-bootstrap-page-1-linux.png b/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-starts-the-sync-server-and-navigates-to-bootstrap-page-1-linux.pngindex 513c94c70c..1db1ec7509 100644Binary files a/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-starts-the-sync-server-and-navigates-to-bootstrap-page-1-linux.png and b/packages/desktop-electron/e2e/__screenshots__/onboarding.test.ts/Onboarding-starts-the-sync-server-and-navigates-to-bootstrap-page-1-linux.png differdiff --git a/upcoming-release-notes/smooth-report-card-resizing.md b/upcoming-release-notes/smooth-report-card-resizing.mdnew file mode 100644index 0000000000..f39e8cabd9--- /dev/null+++ b/upcoming-release-notes/smooth-report-card-resizing.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [aelxxs]+---++Make number cards adapt more smoothly when resizing the screen.