A local-first personal finance app
[AI] Keep mobile transaction search when going back from a transaction (#9172)
John Costaab0b5c40fa67
diff --git a/packages/desktop-client/e2e/accounts.mobile.test.ts b/packages/desktop-client/e2e/accounts.mobile.test.tsindex af9af1e3c5..4117e63e60 100644--- a/packages/desktop-client/e2e/accounts.mobile.test.ts+++ b/packages/desktop-client/e2e/accounts.mobile.test.ts@@ -3,6 +3,7 @@ import type { Page } from '@playwright/test';import { expect, test } from './fixtures';import { ConfigurationPage } from './page-models/configuration-page';import { MobileNavigation } from './page-models/mobile-navigation';+import { MobileTransactionEntryPage } from './page-models/mobile-transaction-entry-page';test.describe('Mobile Accounts', () => {let page: Page;@@ -63,6 +64,31 @@ test.describe('Mobile Accounts', () => {await expect(page).toMatchThemeScreenshots();});+ test('keeps the search after opening a transaction and going back', async () => {+ const accountsPage = await navigation.goToAccountsPage();+ await accountsPage.waitFor();++ const accountPage = await accountsPage.openNthAccount(0);+ await accountPage.waitFor();++ await accountPage.searchByText('Kroger');+ await expect(page).toHaveURL(/[?&]search=Kroger/);+ // Wait for the filtered list; unfiltered, the first rows are schedules.+ await expect(accountPage.transactions.first()).toContainText('Kroger');+ const searchedCount = await accountPage.transactions.count();++ await accountPage.transactions.first().click();+ const transactionPage = new MobileTransactionEntryPage(page);+ await transactionPage.waitFor();++ await page.getByRole('button', { name: 'Back', exact: true }).click();+ await accountPage.waitFor();++ await expect(accountPage.searchBox).toHaveValue('Kroger');+ await expect(page).toHaveURL(/[?&]search=Kroger/);+ await expect(accountPage.transactions).toHaveCount(searchedCount);+ });+test('reconciles an account', async () => {const accountsPage = await navigation.goToAccountsPage();await accountsPage.waitFor();diff --git a/packages/desktop-client/src/components/mobile/accounts/AllAccountTransactions.test.tsx b/packages/desktop-client/src/components/mobile/accounts/AllAccountTransactions.test.tsxnew file mode 100644index 0000000000..b6de0c72cf--- /dev/null+++ b/packages/desktop-client/src/components/mobile/accounts/AllAccountTransactions.test.tsx@@ -0,0 +1,140 @@+import React from 'react';+import { BrowserRouter } from 'react-router';++import { initServer } from '@actual-app/core/platform/client/connection';+import type { Query } from '@actual-app/core/shared/query';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++import { useTransactions } from '#hooks/useTransactions';+import { TestProviders } from '#mocks';++import { AllAccountTransactions } from './AllAccountTransactions';++vi.mock(+ '@actual-app/core/platform/client/connection',+ () => import('#mocks/connection'),+);+vi.mock('#components/spreadsheet/CellValue', () => ({+ CellValue: () => null,+ CellValueText: () => null,+}));+vi.mock('#components/mobile/transactions/TransactionList', () => ({+ TransactionList: () => null,+}));+vi.mock('#hooks/useTransactions', () => ({+ useTransactions: vi.fn(() => ({+ transactions: [],+ isPending: false,+ isFetchingNextPage: false,+ fetchNextPage: vi.fn(),+ })),+}));+vi.mock('#hooks/usePreviewTransactions', () => ({+ usePreviewTransactions: () => ({ previewTransactions: [], isLoading: false }),+}));+vi.mock('#hooks/useSchedules', () => ({+ getSchedulesQuery: vi.fn(),+ useSchedules: () => ({}),+}));++const drillDownFilter = { notes: { $eq: 'from-report' } };++// The query AllAccountTransactions currently hands to useTransactions+// (DisplayPayeeProvider also calls it, with a different query).+function currentQuery() {+ const queries = vi+ .mocked(useTransactions)+ .mock.calls.map(+ ([props]) =>+ (props.query as Query | undefined)?.serializeAsString() ?? '',+ )+ .filter(query => query.includes('"splits":"all"'));+ return queries[queries.length - 1] ?? '';+}++describe('AllAccountTransactions', () => {+ // Drill-downs from reports land here with filter conditions in the+ // navigation state. A real BrowserRouter is used because, like the app,+ // it rebuilds location.state from history.state on every URL update.+ const renderPage = (url: string, filterDelayMs = 0) => {+ const makeFilters = vi.fn(async () => {+ await new Promise(resolve => setTimeout(resolve, filterDelayMs));+ return { filters: [drillDownFilter] };+ });+ initServer({ 'make-filters-from-conditions': makeFilters });+ window.history.replaceState(+ {+ usr: { filterConditions: [{ field: 'notes', op: 'is', value: 'x' }] },+ key: 'drill',+ idx: 0,+ },+ '',+ url,+ );+ render(+ <TestProviders>+ <BrowserRouter>+ <AllAccountTransactions />+ </BrowserRouter>+ </TestProviders>,+ );+ return makeFilters;+ };++ beforeEach(() => {+ vi.mocked(useTransactions).mockClear();+ // Browsers structured-clone history state, so location.state gets a new+ // identity on every URL update; jsdom keeps the same object.+ const { pushState, replaceState } = window.history;+ vi.spyOn(window.history, 'pushState').mockImplementation((data, ...rest) =>+ pushState.call(window.history, structuredClone(data), ...rest),+ );+ vi.spyOn(window.history, 'replaceState').mockImplementation(+ (data, ...rest) =>+ replaceState.call(window.history, structuredClone(data), ...rest),+ );+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('applies drill-down filters once and keeps the search on top of them', async () => {+ const user = userEvent.setup();+ const makeFilters = renderPage('/accounts/all');+ await waitFor(() => expect(currentQuery()).toContain('from-report'));++ await user.type(screen.getByPlaceholderText('Search All Accounts'), 'Fuel');++ await waitFor(() => expect(currentQuery()).toContain('%Fuel%'));+ expect(currentQuery()).toContain('from-report');+ expect(window.location.search).toBe('?search=Fuel');+ expect(makeFilters).toHaveBeenCalledTimes(1);+ });++ it('re-applies a restored search once slow drill-down filters load', async () => {+ const makeFilters = renderPage('/accounts/all?search=Fuel', 300);++ expect(screen.getByPlaceholderText('Search All Accounts')).toHaveValue(+ 'Fuel',+ );+ await waitFor(+ () => {+ expect(currentQuery()).toContain('from-report');+ expect(currentQuery()).toContain('%Fuel%');+ },+ { timeout: 2000 },+ );+ expect(makeFilters).toHaveBeenCalledTimes(1);+ // The filtered query is never handed over without the search on top.+ const filteredQueries = vi+ .mocked(useTransactions)+ .mock.calls.map(+ ([props]) =>+ (props.query as Query | undefined)?.serializeAsString() ?? '',+ )+ .filter(query => query.includes('from-report'));+ expect(filteredQueries.every(query => query.includes('%Fuel%'))).toBe(true);+ });+});diff --git a/packages/desktop-client/src/components/mobile/accounts/AllAccountTransactions.tsx b/packages/desktop-client/src/components/mobile/accounts/AllAccountTransactions.tsxindex f64a28569f..d90140ac18 100644--- a/packages/desktop-client/src/components/mobile/accounts/AllAccountTransactions.tsx+++ b/packages/desktop-client/src/components/mobile/accounts/AllAccountTransactions.tsx@@ -1,4 +1,10 @@-import React, { useCallback, useEffect, useMemo, useState } from 'react';+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';import { useTranslation } from 'react-i18next';import { useLocation } from 'react-router';@@ -69,8 +75,12 @@ function TransactionListWithPreviews() {});const [searchText, setSearchText] = useState('');+ // The ref lets the filter effect below re-run the current search without+ // depending on (and re-running for) every keystroke.+ const searchTextRef = useRef('');const onSearch = useCallback((text: string) => {+ searchTextRef.current = text;setSearchText(text);search(text);},@@ -96,6 +106,10 @@ function TransactionListWithPreviews() {}}+ // Keyed on the serialized conditions, not location.state: updating the URL+ // (e.g. the search param) gives location.state a new identity each time.+ const filterConditionsKey = JSON.stringify(filterConditions);+useEffect(() => {let isStale = false;@@ -108,19 +122,43 @@ function TransactionListWithPreviews() {const query = rootQuery.filter({ $and: queryFilters });if (!isStale) {setCurrentQuery(query);- setTransactionsQuery(query);+ // A search typed or restored before the filters loaded had no query+ // to apply to; apply it now so rows that only match the filters+ // never show.+ const text = searchTextRef.current;+ setTransactionsQuery(+ text !== ''+ ? queries.transactionsSearch(+ query,+ text,+ dateFormat,+ currencySymbol,+ )+ : query,+ );+ // Restart any pending debounced search so it can't fire with the+ // query from before the filters loaded.+ if (text !== '') {+ search(text);+ }}};- const conditions = location?.state?.filterConditions;- if (conditions?.length) {+ const conditions: RuleConditionEntity[] = JSON.parse(filterConditionsKey);+ if (conditions.length) {void applyFilters(conditions);}return () => {isStale = true;};- }, [location.state, makeRootTransactionsQuery]);+ }, [+ filterConditionsKey,+ makeRootTransactionsQuery,+ search,+ dateFormat,+ currencySymbol,+ ]);const {transactions,diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionListWithBalances.test.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionListWithBalances.test.tsxnew file mode 100644index 0000000000..d79d8577d3--- /dev/null+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionListWithBalances.test.tsx@@ -0,0 +1,177 @@+import React, { useState } from 'react';+import { MemoryRouter, Route, Routes, useLocation } from 'react-router';++import type { TransactionEntity } from '@actual-app/core/types/models';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++import { useNavigate } from '#hooks/useNavigate';+import { TestProviders } from '#mocks';+import * as bindings from '#spreadsheet/bindings';++import { TransactionListWithBalances } from './TransactionListWithBalances';++vi.mock('#components/spreadsheet/CellValue', () => ({+ CellValue: () => null,+ CellValueText: () => null,+}));++vi.mock('./TransactionList', () => ({+ TransactionList: ({+ transactions,+ onOpenTransaction,+ }: {+ transactions: TransactionEntity[];+ onOpenTransaction: (transaction: TransactionEntity) => void;+ }) => (+ <ul>+ {transactions.map(transaction => (+ <li key={transaction.id}>+ <button onClick={() => onOpenTransaction(transaction)}>+ {transaction.notes}+ </button>+ </li>+ ))}+ </ul>+ ),+}));++const mockTransactions = [+ { id: 'trans-1', notes: 'Groceries #food' },+ { id: 'trans-2', notes: 'Fuel' },+] as TransactionEntity[];++// Stands in for the mobile account pages: the search narrows the list and+// tapping a transaction opens the edit page.+function AccountTransactionsPage() {+ const navigate = useNavigate();+ const [searchText, setSearchText] = useState('');++ return (+ <TransactionListWithBalances+ isLoading={false}+ transactions={mockTransactions.filter(t => t.notes?.includes(searchText))}+ balance={bindings.allAccountBalance()}+ searchPlaceholder="Search All Accounts"+ onSearch={setSearchText}+ isLoadingMore={false}+ onLoadMore={vi.fn()}+ onOpenTransaction={transaction =>+ void navigate(`/transactions/${transaction.id}`)+ }+ />+ );+}++function TransactionEditPage() {+ const navigate = useNavigate();+ return <button onClick={() => void navigate(-1)}>Save changes</button>;+}++// Navigates to a URL on the same page, like a link or the browser's+// back/forward between two searches would, without remounting the list.+function NavigateButton({ to }: { to: string }) {+ const navigate = useNavigate();+ return <button onClick={() => void navigate(to)}>Go to {to}</button>;+}++function LocationDisplay() {+ const location = useLocation();+ return (+ <div data-testid="location">+ {location.pathname}+ {location.search}+ <span data-testid="location-state">{JSON.stringify(location.state)}</span>+ </div>+ );+}++describe('TransactionListWithBalances', () => {+ const renderPage = (+ initialEntry: string | { pathname: string; state: unknown } = '/accounts',+ ) =>+ render(+ <TestProviders>+ <MemoryRouter initialEntries={[initialEntry]}>+ <Routes>+ <Route path="/accounts" element={<AccountTransactionsPage />} />+ <Route path="/transactions/:id" element={<TransactionEditPage />} />+ </Routes>+ <LocationDisplay />+ <NavigateButton to="/accounts?search=Fuel" />+ <NavigateButton to="/accounts" />+ </MemoryRouter>+ </TestProviders>,+ );++ it('keeps the search after editing a transaction and going back', async () => {+ const user = userEvent.setup();+ renderPage();++ await user.type(+ screen.getByPlaceholderText('Search All Accounts'),+ '#food',+ );+ expect(screen.queryByText('Fuel')).not.toBeInTheDocument();++ await user.click(screen.getByText('Groceries #food'));+ expect(screen.getByTestId('location')).toHaveTextContent(+ '/transactions/trans-1',+ );++ await user.click(screen.getByText('Save changes'));++ expect(screen.getByPlaceholderText('Search All Accounts')).toHaveValue(+ '#food',+ );+ expect(screen.getByText('Groceries #food')).toBeInTheDocument();+ expect(screen.queryByText('Fuel')).not.toBeInTheDocument();+ });++ it('keeps other URL params and drops the search param when cleared', async () => {+ const user = userEvent.setup();+ renderPage('/accounts?reconcile=100&search=Fuel');++ const searchBox = screen.getByPlaceholderText('Search All Accounts');+ expect(searchBox).toHaveValue('Fuel');+ expect(screen.queryByText('Groceries #food')).not.toBeInTheDocument();++ await user.clear(searchBox);++ const location = screen.getByTestId('location');+ expect(location).toHaveTextContent('/accounts?reconcile=100');+ expect(location).not.toHaveTextContent('search=');+ expect(screen.getByText('Groceries #food')).toBeInTheDocument();+ });++ it('follows the search param when the URL changes after the first render', async () => {+ const user = userEvent.setup();+ renderPage();++ const searchBox = screen.getByPlaceholderText('Search All Accounts');+ expect(searchBox).toHaveValue('');++ await user.click(screen.getByText('Go to /accounts?search=Fuel'));+ expect(searchBox).toHaveValue('Fuel');+ expect(screen.getByText('Fuel')).toBeInTheDocument();+ expect(screen.queryByText('Groceries #food')).not.toBeInTheDocument();++ await user.click(screen.getByText('Go to /accounts'));+ expect(searchBox).toHaveValue('');+ expect(screen.getByText('Groceries #food')).toBeInTheDocument();+ });++ it('keeps navigation state (e.g. drill-down filters) while searching', async () => {+ const user = userEvent.setup();+ renderPage({ pathname: '/accounts', state: { filterConditions: ['x'] } });++ await user.type(screen.getByPlaceholderText('Search All Accounts'), 'Fuel');++ expect(screen.getByTestId('location')).toHaveTextContent(+ '/accounts?search=Fuel',+ );+ expect(screen.getByTestId('location-state')).toHaveTextContent(+ '{"filterConditions":["x"]}',+ );+ });+});diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionListWithBalances.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionListWithBalances.tsxindex 5a560b3a9e..9b5397be58 100644--- a/packages/desktop-client/src/components/mobile/transactions/TransactionListWithBalances.tsx+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionListWithBalances.tsx@@ -1,17 +1,15 @@-import React, { useState } from 'react';+import React from 'react';import type { ComponentProps } from 'react';import { Trans, useTranslation } from 'react-i18next';import { SvgFilter } from '@actual-app/components/icons/v1';import { Label } from '@actual-app/components/label';-import { styles } from '@actual-app/components/styles';import { Text } from '@actual-app/components/text';import { theme } from '@actual-app/components/theme';import { View } from '@actual-app/components/view';import type { IntegerAmount } from '@actual-app/core/shared/util';import type { TransactionEntity } from '@actual-app/core/types/models';-import { Search } from '#components/common/Search';import { PullToRefresh } from '#components/mobile/PullToRefresh';import { CellValue, CellValueText } from '#components/spreadsheet/CellValue';import { DisplayPayeeProvider } from '#hooks/useDisplayPayee';@@ -20,45 +18,7 @@ import { useSheetValue } from '#hooks/useSheetValue';import type { Binding, SheetFields, SheetNames } from '#spreadsheet';import { TransactionList } from './TransactionList';--type TransactionSearchInputProps = {- placeholder: string;- onSearch: TransactionListWithBalancesProps['onSearch'];-};--function TransactionSearchInput({- placeholder,- onSearch,-}: TransactionSearchInputProps) {- const [text, setText] = useState('');-- return (- <View- style={{- flexDirection: 'row',- alignItems: 'center',- backgroundColor: theme.mobilePageBackground,- padding: 10,- width: '100%',- }}- >- <Search- value={text}- onChange={text => {- setText(text);- onSearch(text);- }}- placeholder={placeholder}- width="100%"- height={styles.mobileMinHeight}- style={{- backgroundColor: theme.tableBackground,- borderColor: theme.formInputBorder,- }}- />- </View>- );-}+import { TransactionSearchInput } from './TransactionSearchInput';type TransactionListWithBalancesProps = {isLoading: boolean;diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionSearchInput.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionSearchInput.tsxnew file mode 100644index 0000000000..b668394077--- /dev/null+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionSearchInput.tsx@@ -0,0 +1,72 @@+import React, { useEffect, useEffectEvent, useRef, useState } from 'react';+import { useLocation } from 'react-router';++import { styles } from '@actual-app/components/styles';+import { theme } from '@actual-app/components/theme';+import { View } from '@actual-app/components/view';++import { Search } from '#components/common/Search';+import { useUrlParam } from '#hooks/useUrlParam';++type TransactionSearchInputProps = {+ placeholder: string;+ onSearch: (searchText: string) => void;+};++export function TransactionSearchInput({+ placeholder,+ onSearch,+}: TransactionSearchInputProps) {+ const location = useLocation();+ // Keep the search in the URL so it survives opening a transaction and+ // navigating back. Local state drives the input so typing stays responsive.+ const [searchParam, setSearchParam] = useUrlParam('search');+ const urlText = searchParam ?? '';+ const [text, setText] = useState(urlText);+ // The last search sent to onSearch, so the URL update caused by typing+ // isn't applied a second time.+ const lastSearch = useRef('');++ const applySearch = useEffectEvent((value: string) => {+ if (value !== lastSearch.current) {+ lastSearch.current = value;+ setText(value);+ onSearch(value);+ }+ });+ // Follow the URL whenever it changes: on mount (restoring a search after+ // navigating back) and on any later navigation that changes `search`.+ useEffect(() => {+ applySearch(urlText);+ }, [urlText]);++ return (+ <View+ style={{+ flexDirection: 'row',+ alignItems: 'center',+ backgroundColor: theme.mobilePageBackground,+ padding: 10,+ width: '100%',+ }}+ >+ <Search+ value={text}+ onChange={text => {+ lastSearch.current = text;+ setText(text);+ onSearch(text);+ // Preserve navigation state (e.g. report drill-down filters).+ setSearchParam(text, { replace: true, state: location.state });+ }}+ placeholder={placeholder}+ width="100%"+ height={styles.mobileMinHeight}+ style={{+ backgroundColor: theme.tableBackground,+ borderColor: theme.formInputBorder,+ }}+ />+ </View>+ );+}diff --git a/upcoming-release-notes/keep-mobile-transaction-search.md b/upcoming-release-notes/keep-mobile-transaction-search.mdnew file mode 100644index 0000000000..54c9f6da44--- /dev/null+++ b/upcoming-release-notes/keep-mobile-transaction-search.md@@ -0,0 +1,6 @@+---+category: Bugfix+authors: [costajohnt]+---++Keep the search on mobile account transaction lists when opening a transaction and going back.