Skip to content

A local-first personal finance app

[AI] Scroll to and highlight the other side of a transfer (#9326)

Andres Pastranad9d15c12fa41
diff --git a/packages/desktop-client/e2e/accounts.test.ts b/packages/desktop-client/e2e/accounts.test.ts
index 3034eef10e..784d12a814 100644
--- a/packages/desktop-client/e2e/accounts.test.ts
+++ b/packages/desktop-client/e2e/accounts.test.ts
@@ -233,6 +233,86 @@ test.describe('Accounts', () => {
await expect(accountPage.selectButton).toHaveText('2 transactions');
});
+ test('opens the other side of a transfer from its arrow', async () => {
+ accountPage = await navigation.goToAccountPage('Bank of America');
+ await accountPage.createSingleTransaction({
+ payee: 'Ally Savings',
+ notes: 'Transfer to point out',
+ debit: '12.34',
+ });
+
+ await accountPage.transactionTableRow
+ .filter({ hasText: 'Transfer to point out' })
+ .getByTestId('transfer-icon')
+ .click();
+
+ await expect(accountPage.accountName).toHaveText('Ally Savings');
+ const otherSide = accountPage.transactionTableRow.filter({
+ hasText: 'Transfer to point out',
+ });
+ await expect(otherSide).toHaveAttribute('data-pulse', 'true');
+ await expect(otherSide).toBeInViewport();
+ // The row is pointed out for a while only
+ await expect(otherSide).not.toHaveAttribute('data-pulse');
+ });
+
+ test('opens the other side of a transfer older than the first loaded page', async () => {
+ await page.evaluate(async () => {
+ const $send = (
+ window as unknown as {
+ $send: <T>(type: string, args?: unknown) => Promise<T>;
+ }
+ ).$send;
+ const accounts =
+ await $send<{ id: string; name: string }[]>('accounts-get');
+ const payees =
+ await $send<{ id: string; transfer_acct: string | null }[]>(
+ 'payees-get',
+ );
+ const bankOfAmerica = accounts.find(a => a.name === 'Bank of America');
+ const allySavings = accounts.find(a => a.name === 'Ally Savings');
+ const allySavingsPayee = payees.find(
+ p => p.transfer_acct === allySavings?.id,
+ );
+ if (!bankOfAmerica || !allySavings || !allySavingsPayee) {
+ throw new Error('Missing test accounts');
+ }
+
+ // More newer transactions in Ally Savings than an account loads at
+ // first, so the other side of the transfer is only on a later page
+ await $send('transactions-batch-update', {
+ added: Array.from({ length: 200 }, () => ({
+ id: crypto.randomUUID(),
+ account: allySavings.id,
+ date: '2001-01-01',
+ amount: -100,
+ })),
+ });
+ await $send('transaction-add', {
+ id: crypto.randomUUID(),
+ account: bankOfAmerica.id,
+ date: '2000-01-01',
+ amount: -1234,
+ payee: allySavingsPayee.id,
+ notes: 'Old transfer to point out',
+ });
+ });
+
+ accountPage = await navigation.goToAccountPage('Bank of America');
+ await page.getByPlaceholder('Search').fill('Old transfer to point out');
+ await accountPage.transactionTableRow
+ .filter({ hasText: 'Old transfer to point out' })
+ .getByTestId('transfer-icon')
+ .click();
+
+ await expect(accountPage.accountName).toHaveText('Ally Savings');
+ const otherSide = accountPage.transactionTableRow.filter({
+ hasText: 'Old transfer to point out',
+ });
+ await expect(otherSide).toHaveAttribute('data-pulse', 'true');
+ await expect(otherSide).toBeInViewport();
+ });
+
test.describe('On Budget Accounts', () => {
// Reset filters
test.afterEach(async () => {
diff --git a/packages/desktop-client/src/components/FixedSizeList.test.ts b/packages/desktop-client/src/components/FixedSizeList.test.ts
new file mode 100644
index 0000000000..57663bb497
--- /dev/null
+++ b/packages/desktop-client/src/components/FixedSizeList.test.ts
@@ -0,0 +1,23 @@
+import { FixedSizeList } from './FixedSizeList';
+
+function centeredOffset(itemCount: number, height: number, index: number) {
+ const list = new FixedSizeList({
+ renderRow: () => null,
+ itemCount,
+ itemSize: 30,
+ height,
+ width: 500,
+ });
+ return list.getOffsetForIndexAndAlignment(index, 'center');
+}
+
+describe('FixedSizeList', () => {
+ it('centers an item in the middle of a list', () => {
+ expect(centeredOffset(100, 600, 50)).toBe(50 * 30 - (600 - 30) / 2);
+ });
+
+ it('scrolls to the last item of a list barely taller than the view', () => {
+ // 27 items of 30px in a 718px view can scroll 92px
+ expect(centeredOffset(27, 718, 26)).toBe(92);
+ });
+});
diff --git a/packages/desktop-client/src/components/FixedSizeList.tsx b/packages/desktop-client/src/components/FixedSizeList.tsx
index 07347b9ef2..a4d6db6dc9 100644
--- a/packages/desktop-client/src/components/FixedSizeList.tsx
+++ b/packages/desktop-client/src/components/FixedSizeList.tsx
@@ -338,18 +338,11 @@ export class FixedSizeList extends PureComponent<
case 'end':
return minOffset;
case 'center': {
- // "Centered" offset is usually the average of the min and max.
- // But near the edges of the list, this doesn't hold true.
- const middleOffset = Math.round(
- minOffset + (maxOffset - minOffset) / 2,
+ // Items near either end can't be centered, so clamp to the list
+ const centeredOffset = Math.round(
+ index * this.props.itemSize - (size - this.props.itemSize) / 2,
);
- if (middleOffset < Math.ceil(size / 2)) {
- return 0; // near the beginning
- } else if (middleOffset > lastItemOffset + Math.floor(size / 2)) {
- return lastItemOffset; // near the end
- } else {
- return middleOffset;
- }
+ return Math.min(lastItemOffset, Math.max(0, centeredOffset));
}
case 'auto':
default:
diff --git a/packages/desktop-client/src/components/accounts/Account.tsx b/packages/desktop-client/src/components/accounts/Account.tsx
index 077bbe5ee6..51e4879b48 100644
--- a/packages/desktop-client/src/components/accounts/Account.tsx
+++ b/packages/desktop-client/src/components/accounts/Account.tsx
@@ -211,6 +211,15 @@ function getField(field?: string) {
}
}
+// The transaction a link to the account asks to bring into view, e.g. the
+// other side of a transfer
+function getFocusTransactionId(
+ location: ReturnType<typeof useLocation>,
+): TransactionEntity['id'] | null {
+ const id: unknown = location.state?.focusTransactionId;
+ return typeof id === 'string' ? id : null;
+}
+
type AccountInternalProps = {
accountId?:
| AccountEntity['id']
@@ -290,6 +299,7 @@ type AccountInternalState = {
prevAscDesc?: 'asc' | 'desc' | undefined;
} | null;
filteredAmount: null | number;
+ focusedTransactionId: TransactionEntity['id'] | null;
};
export type TableRef = RefObject<{
@@ -311,6 +321,8 @@ class AccountInternal extends PureComponent<
unlisten?: () => void;
dispatchSelected?: (action: Actions) => void;
_isOptimisticUpdate: boolean = false;
+ // A transaction to bring into view once the account is loaded
+ pendingFocusId: TransactionEntity['id'] | null = null;
constructor(props: AccountInternalProps) {
super(props);
@@ -334,6 +346,7 @@ class AccountInternal extends PureComponent<
isAdding: false,
sort: null,
filteredAmount: null,
+ focusedTransactionId: null,
};
}
@@ -394,6 +407,7 @@ class AccountInternal extends PureComponent<
// Important that any async work happens last so that the
// listeners are set up synchronously
+ this.pendingFocusId = getFocusTransactionId(this.props.location);
this.fetchTransactions(this.state.filterConditions);
// If there is a pending undo, apply it immediately (this happens
@@ -487,7 +501,7 @@ class AccountInternal extends PureComponent<
query = query.filter({ reconciled: { $eq: false } });
}
- this.paged = pagedQuery(query.select('*'), {
+ const paged = pagedQuery<TransactionEntity>(query.select('*'), {
onData: async (groupedData, prevData) => {
const data = ungroupTransactions([...groupedData]);
const firstLoad = prevData == null;
@@ -550,6 +564,9 @@ class AccountInternal extends PureComponent<
() => {
if (firstLoad) {
this.table.current?.scrollToTop();
+ if (paged === this.paged) {
+ void this.showPendingFocus(paged);
+ }
}
setTimeout(() => {
@@ -563,14 +580,17 @@ class AccountInternal extends PureComponent<
onlySync: true,
},
});
+ this.paged = paged;
}
// oxlint-disable-next-line react/no-unsafe
UNSAFE_componentWillReceiveProps(nextProps: AccountInternalProps) {
if (this.props.accountId !== nextProps.accountId) {
+ this.pendingFocusId = getFocusTransactionId(nextProps.location);
this.setState(
{
loading: true,
+ focusedTransactionId: null,
search: '',
showBalances: nextProps.showBalances,
balances: null,
@@ -585,6 +605,42 @@ class AccountInternal extends PureComponent<
}
}
+ // Brings the pending transaction into view, loading the account up to it
+ // if needed. Leaves the account at the top when the query doesn't have it,
+ // e.g. while reconciled transactions are hidden.
+ showPendingFocus = async (paged: PagedQuery<TransactionEntity>) => {
+ const id = this.pendingFocusId;
+ this.pendingFocusId = null;
+ // Only in the default date order; the lookup relies on it
+ if (id == null || this.state.sort != null) {
+ return;
+ }
+ if (!this.state.transactions.some(t => t.id === id)) {
+ await paged.refetchUpToRow(id, { field: 'date', order: 'desc' });
+ }
+
+ const transaction = ungroupTransactions(paged.data).find(t => t.id === id);
+ if (
+ transaction == null ||
+ (transaction.reconciled && !this.state.showReconciled) ||
+ // The query was replaced meanwhile, e.g. by a sort or another account
+ !paged.isRunning
+ ) {
+ return;
+ }
+ if (transaction.parent_id) {
+ this.props.splitsExpandedDispatch({
+ type: 'open-split',
+ id: transaction.parent_id,
+ });
+ }
+ this.setState({ focusedTransactionId: id });
+ };
+
+ onFocusedTransactionShown = () => {
+ this.setState({ focusedTransactionId: null });
+ };
+
onSearch = (value: string) => {
this.paged?.unsubscribe();
this.setState({ search: value }, this.onSearchDone);
@@ -1995,6 +2051,8 @@ class AccountInternal extends PureComponent<
this.onMakeAsNonSplitTransactions
}
onRefetch={this.refetchTransactions}
+ focusedTransactionId={this.state.focusedTransactionId}
+ onFocusedTransactionShown={this.onFocusedTransactionShown}
onCloseAddTransaction={() =>
this.setState({ isAdding: false })
}
diff --git a/packages/desktop-client/src/components/transactions/TransactionList.tsx b/packages/desktop-client/src/components/transactions/TransactionList.tsx
index 555475e1cc..315f0bc5a9 100644
--- a/packages/desktop-client/src/components/transactions/TransactionList.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionList.tsx
@@ -91,6 +91,7 @@ type TransactionListProps = Pick<
| 'balances'
| 'categoryGroups'
| 'dateFormat'
+ | 'focusedTransactionId'
| 'hideFraction'
| 'isAdding'
| 'isMatched'
@@ -103,6 +104,7 @@ type TransactionListProps = Pick<
| 'onCloseAddTransaction'
| 'onCreatePayee'
| 'onCreateRule'
+ | 'onFocusedTransactionShown'
| 'onMakeAsNonSplitTransactions'
| 'onSort'
| 'onScheduleAction'
@@ -159,6 +161,8 @@ export function TransactionList({
dateFormat,
hideFraction,
renderEmpty,
+ focusedTransactionId,
+ onFocusedTransactionShown,
onSort,
sortField,
ascDesc,
@@ -304,8 +308,16 @@ export function TransactionList({
);
const onNavigateToTransferAccount = useCallback(
- (accountId: AccountEntity['id']) => {
- void navigate(`/accounts/${accountId}`);
+ (
+ accountId: AccountEntity['id'],
+ transactionId?: TransactionEntity['id'],
+ ) => {
+ void navigate(
+ `/accounts/${accountId}`,
+ transactionId
+ ? { state: { focusTransactionId: transactionId } }
+ : undefined,
+ );
},
[navigate],
);
@@ -495,6 +507,8 @@ export function TransactionList({
<TransactionTable
ref={tableRef}
transactions={allTransactions}
+ focusedTransactionId={focusedTransactionId}
+ onFocusedTransactionShown={onFocusedTransactionShown}
loadMoreTransactions={loadMoreTransactions}
accounts={accounts}
categoryGroups={categoryGroups}
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
index 448ebf26b2..f244138fcc 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.test.tsx
@@ -174,6 +174,8 @@ type LiveTransactionTableProps = {
transaction: TransactionEntity,
updatedFieldName?: string | null,
) => Promise<TransactionEntity>;
+ focusedTransactionId?: TransactionEntity['id'] | null;
+ onFocusedTransactionShown?: () => void;
};
function LiveTransactionTable(props: LiveTransactionTableProps) {
@@ -594,6 +596,29 @@ describe('Transactions', () => {
});
});
+ test('points out the focused transaction for a while', () => {
+ vi.useFakeTimers();
+ try {
+ const onFocusedTransactionShown = vi.fn();
+ const { container, getTransactions, updateProps } = renderTransactions({
+ onFocusedTransactionShown,
+ });
+ updateProps({ focusedTransactionId: getTransactions()[2].id });
+
+ const pulsing = container.querySelectorAll('[data-pulse]');
+ expect(pulsing).toHaveLength(1);
+ expect(pulsing[0]).toBe(
+ queryField(container, 'payee', 'div', 2).closest('[data-testid="row"]'),
+ );
+ expect(onFocusedTransactionShown).not.toHaveBeenCalled();
+
+ vi.runOnlyPendingTimers();
+ expect(onFocusedTransactionShown).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
test('transactions table shows the correct data', () => {
const { container, getTransactions } = renderTransactions();
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
index fa8d81a1dd..aebdd50ce5 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
@@ -79,6 +79,7 @@ import type {
ScheduleEntity,
TransactionEntity,
} from '@actual-app/core/types/models';
+import { keyframes } from '@emotion/css';
import { format as formatDate, parseISO } from 'date-fns';
import { getAccountsById } from '#accounts/accountsSlice';
@@ -622,6 +623,12 @@ function HeaderCell({
);
}
+// Opens the account, bringing the transaction into view if given
+type NavigateToTransferAccount = (
+ accountId: AccountEntity['id'],
+ transactionId?: TransactionEntity['id'],
+) => void;
+
type PayeeCellProps = {
id: TransactionEntity['id'];
payee?: PayeeEntity;
@@ -639,7 +646,7 @@ type PayeeCellProps = {
onUpdate: TransactionUpdateFunction;
onCreatePayee: (name: string) => Promise<null | PayeeEntity['id']>;
onManagePayees: (id: PayeeEntity['id'] | undefined) => void;
- onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNavigateToTransferAccount: NavigateToTransferAccount;
onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
};
@@ -886,6 +893,12 @@ function PayeeCell({
);
}
+const ROW_PULSE_DURATION_MS = 2000;
+
+const rowPulse = keyframes({
+ '50%': { backgroundColor: theme.tableRowBackgroundHighlight },
+});
+
const payeeIconButtonStyle = {
marginLeft: -5,
marginRight: 2,
@@ -899,7 +912,7 @@ const transferIconStyle = { width: 10, height: 10 };
type PayeeIconsProps = {
transaction: SerializedTransaction;
transferAccount: AccountEntity | null;
- onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNavigateToTransferAccount: NavigateToTransferAccount;
onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
};
@@ -961,7 +974,10 @@ function PayeeIcons({
style={payeeIconButtonStyle}
onPress={() => {
if (!isTemporaryId(transaction.id)) {
- onNavigateToTransferAccount(transferAccount.id);
+ onNavigateToTransferAccount(
+ transferAccount.id,
+ transaction.transfer_id ?? undefined,
+ );
}
}}
>
@@ -990,6 +1006,8 @@ type TransactionProps = {
highlighted?: boolean;
added?: boolean;
matched?: boolean;
+ // Highlights the row briefly to point it out
+ pulse?: boolean;
expanded?: boolean;
focusedField?: string;
categoryGroups: CategoryGroupEntity[];
@@ -1019,7 +1037,7 @@ type TransactionProps = {
onToggleSplit: (id: TransactionEntity['id']) => void;
onCreatePayee: (name: string) => Promise<null | PayeeEntity['id']>;
onManagePayees: (id: PayeeEntity['id'] | undefined) => void;
- onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNavigateToTransferAccount: NavigateToTransferAccount;
onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
onNotesTagClick: (tag: string) => void;
splitError?: ReactNode;
@@ -1057,6 +1075,7 @@ const Transaction = memo(function Transaction({
highlighted,
added,
matched,
+ pulse,
expanded,
focusedField,
categoryGroups,
@@ -2117,6 +2136,7 @@ const Transaction = memo(function Transaction({
<Row
ref={rowRef}
{...dragProps}
+ {...(pulse && { 'data-pulse': true })}
style={{
backgroundColor: selected
? theme.tableRowBackgroundHighlight
@@ -2137,6 +2157,13 @@ const Transaction = memo(function Transaction({
...(highlighted || selected
? { color: theme.tableRowBackgroundHighlightText }
: { color: theme.tableText }),
+ ...(pulse && {
+ animation: `${rowPulse} ${ROW_PULSE_DURATION_MS / 2}ms ease-in-out 2`,
+ '@media (prefers-reduced-motion: reduce)': {
+ animation: 'none',
+ backgroundColor: theme.tableRowBackgroundHighlight,
+ },
+ }),
...style,
...(isPreview && {
color: theme.tableTextInactive,
@@ -2423,7 +2450,7 @@ type NewTransactionProps = {
onEdit: (id: TransactionEntity['id'], field: string) => void;
onManagePayees: (id: PayeeEntity['id'] | undefined) => void;
onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
- onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNavigateToTransferAccount: NavigateToTransferAccount;
onNotesTagClick: (tag: string) => void;
onSave: (
tx: TransactionEntity,
@@ -2622,6 +2649,8 @@ type TransactionTableInnerProps = {
balances: Record<TransactionEntity['id'], IntegerAmount> | null;
columns: TransactionTableColumnId[];
showReconciled: boolean;
+ focusedTransactionId?: TransactionEntity['id'] | null;
+ onFocusedTransactionShown?: () => void;
currentAccountId: AccountEntity['id'];
currentCategoryId: CategoryEntity['id'];
isAdding: boolean;
@@ -2642,7 +2671,7 @@ type TransactionTableInnerProps = {
onAdd: (transactions: TransactionEntity[]) => void;
onCreatePayee: (name: string) => Promise<null | PayeeEntity['id']>;
style?: CSSProperties;
- onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNavigateToTransferAccount: NavigateToTransferAccount;
onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
onNotesTagClick: (tag: string) => void;
sortField: string;
@@ -2709,9 +2738,12 @@ function TransactionTableInner({
} = props;
const onNavigateToTransferAccount = useCallback(
- (accountId: AccountEntity['id']) => {
+ (
+ accountId: AccountEntity['id'],
+ transactionId?: TransactionEntity['id'],
+ ) => {
onCloseAddTransactionProp();
- onNavigateToTransferAccountProp(accountId);
+ onNavigateToTransferAccountProp(accountId, transactionId);
},
[onCloseAddTransactionProp, onNavigateToTransferAccountProp],
);
@@ -2847,6 +2879,7 @@ function TransactionTableInner({
added={isNew?.(trans.id)}
expanded={isExpanded?.(trans.id)}
matched={isMatched?.(trans.id)}
+ pulse={trans.id === props.focusedTransactionId}
showZeroInDeposit={isChildDeposit}
balance={balances?.[trans.id] ?? 0}
amountColumnWidths={amountColumnWidths}
@@ -3053,7 +3086,7 @@ export type TransactionTableProps = {
onAdd: (transactions: TransactionEntity[]) => void;
onCreatePayee: (name: string) => Promise<null | PayeeEntity['id']>;
style?: CSSProperties;
- onNavigateToTransferAccount: (id: AccountEntity['id']) => void;
+ onNavigateToTransferAccount: NavigateToTransferAccount;
onNavigateToSchedule: (id: ScheduleEntity['id']) => void;
onNotesTagClick: (tag: string) => void;
onSort: (field: string, ascDesc: 'asc' | 'desc') => void;
@@ -3077,6 +3110,9 @@ export type TransactionTableProps = {
showSelection: boolean;
allowSplitTransaction?: boolean;
onManagePayees: (id?: PayeeEntity['id']) => void;
+ // The transaction to bring into view and point out, until it's shown
+ focusedTransactionId?: TransactionEntity['id'] | null;
+ onFocusedTransactionShown?: () => void;
};
export const TransactionTable = forwardRef(
@@ -3240,6 +3276,38 @@ export const TransactionTable = forwardRef(
);
}, [transactionsWithExpandedSplits]);
+ // Scrolls to the focused transaction once it's listed, and again when
+ // rows are added above it, e.g. upcoming scheduled transactions
+ const { focusedTransactionId, onFocusedTransactionShown } = props;
+ const focusedTransactionIndex =
+ focusedTransactionId == null
+ ? -1
+ : transactionsWithExpandedSplits.findIndex(
+ t => t.id === focusedTransactionId,
+ );
+ const isFocusedTransactionListed = focusedTransactionIndex !== -1;
+ useEffect(() => {
+ if (focusedTransactionId != null && focusedTransactionIndex !== -1) {
+ tableRef.current?.scrollTo(focusedTransactionId, 'center');
+ }
+ }, [focusedTransactionId, focusedTransactionIndex]);
+
+ // Timed here rather than on the row, which unmounts when scrolled away
+ useEffect(() => {
+ if (!isFocusedTransactionListed) {
+ return;
+ }
+ const timeout = setTimeout(
+ () => onFocusedTransactionShown?.(),
+ ROW_PULSE_DURATION_MS,
+ );
+ return () => clearTimeout(timeout);
+ }, [
+ focusedTransactionId,
+ isFocusedTransactionListed,
+ onFocusedTransactionShown,
+ ]);
+
const transactionsByParent = useMemo(() => {
return props.transactions.reduce(
(acc, trans) => {
diff --git a/packages/desktop-client/src/queries/pagedQuery.test.ts b/packages/desktop-client/src/queries/pagedQuery.test.ts
index d57bb58808..9d50e97614 100644
--- a/packages/desktop-client/src/queries/pagedQuery.test.ts
+++ b/packages/desktop-client/src/queries/pagedQuery.test.ts
@@ -43,7 +43,7 @@ function runPagedQuery(query, data) {
if (query.filterExpressions.length > 0) {
const filter = query.filterExpressions[0];
if (filter.id != null) {
- return [data.find(row => row.id === filter.id)];
+ return data.filter(row => row.id === filter.id);
}
if (filter.date != null) {
@@ -619,6 +619,67 @@ describe('pagedQuery', () => {
await wait(1000);
});
+ // Each query takes 50ms and fetching up to a row takes three, so a plain
+ // refresh from an early sync would finish before it, and from a late one
+ // after it
+ it.each([
+ ['early', 5],
+ ['late', 120],
+ ])(
+ 'pagedQuery fetches up to a row through a sync arriving %s',
+ async (_, syncDelay) => {
+ mockPagingServer(500, { delay: 50 });
+ const query = q('transactions').select(['id', 'date']);
+ const paged = pagedQuery<{ id: number }>(query, {
+ options: { pageCount: 20 },
+ });
+ await paged.run();
+
+ const refetch = paged.refetchUpToRow(300, {
+ field: 'date',
+ order: 'desc',
+ });
+ await wait(syncDelay);
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
+ await refetch;
+
+ expect(paged.data.some(row => row.id === 300)).toBe(true);
+ },
+ );
+
+ it('pagedQuery drops a row deleted while fetching up to it', async () => {
+ const data = [];
+ for (let i = 0; i < 500; i++) {
+ data.push({ id: i, date: subDays('2020-05-01', Math.floor(i / 5)) });
+ }
+ mockServer({
+ send: async (name, query) => {
+ const result = runPagedQuery(query, data);
+ // A sync deletes it while the extra page after it loads
+ if (query.filterExpressions[0]?.date?.$lt && data[300].id === 300) {
+ data.splice(300, 1);
+ mockPublishEvent('sync-event', {
+ type: 'success',
+ tables: ['transactions'],
+ });
+ }
+ return { data: result, dependencies: ['transactions'] };
+ },
+ });
+ const query = q('transactions').select(['id', 'date']);
+ const paged = pagedQuery<{ id: number }>(query, {
+ options: { pageCount: 20 },
+ });
+ await paged.run();
+
+ await paged.refetchUpToRow(300, { field: 'date', order: 'desc' });
+
+ expect(paged.data.some(row => row.id === 300)).toBe(false);
+ });
+
it('does not spin forever when unsubscribed during a refetch', async () => {
// Regression test: unsubscribing while a refetch was in flight (e.g.
// switching accounts while a scroll-triggered `fetchNext` was pending)
diff --git a/packages/desktop-client/src/queries/pagedQuery.ts b/packages/desktop-client/src/queries/pagedQuery.ts
index 0f1c15ba38..1442c19d98 100644
--- a/packages/desktop-client/src/queries/pagedQuery.ts
+++ b/packages/desktop-client/src/queries/pagedQuery.ts
@@ -48,6 +48,9 @@ export class PagedQuery<TResponse = unknown> extends LiveQuery<TResponse> {
private _pageCount: number;
private _fetchDataPromise: Promise<void> | null;
private _totalCount: number;
+ // The fetch up to a row in progress. A refresh meanwhile, e.g. from a
+ // sync, makes it fetch again instead of replacing its rows with fewer.
+ private _upToRow: { isStale: boolean } | null = null;
get hasNext() {
return !this._hasReachedEnd;
@@ -79,6 +82,10 @@ export class PagedQuery<TResponse = unknown> extends LiveQuery<TResponse> {
};
run = () => {
+ if (this._upToRow) {
+ this._upToRow.isStale = true;
+ return this._fetchDataPromise;
+ }
this.subscribe();
this._fetchDataPromise = this.fetchData(async () => {
@@ -87,20 +94,25 @@ export class PagedQuery<TResponse = unknown> extends LiveQuery<TResponse> {
// Also fetch the total count
void this.fetchCount();
- // If data is null, we haven't fetched anything yet so just
- // fetch the first page
- return aqlQuery(
- this.query.limit(
- this.data == null
- ? this._pageCount
- : Math.max(this.data.length, this._pageCount),
- ),
- );
+ return this.fetchLoaded();
});
return this._fetchDataPromise;
};
+ // Refetches the rows loaded so far
+ private fetchLoaded = () => {
+ // If data is null, we haven't fetched anything yet so just
+ // fetch the first page
+ return aqlQuery(
+ this.query.limit(
+ this.data == null
+ ? this._pageCount
+ : Math.max(this.data.length, this._pageCount),
+ ),
+ );
+ };
+
static runPagedQuery = <TResponse>(
query: Query,
onData?: Listener<TResponse>,
@@ -119,8 +131,22 @@ export class PagedQuery<TResponse = unknown> extends LiveQuery<TResponse> {
return pagedQuery;
};
+ // Resolves once the rows up to it, as of the latest refresh, are loaded
refetchUpToRow = async (id, defaultOrderBy) => {
- this._fetchDataPromise = this.fetchData(async () => {
+ const upToRow = { isStale: false };
+ this._upToRow = upToRow;
+ do {
+ upToRow.isStale = false;
+ this._fetchDataPromise = this.fetchUpToRow(id, defaultOrderBy);
+ await this._fetchDataPromise;
+ } while (upToRow.isStale && this._upToRow === upToRow);
+ if (this._upToRow === upToRow) {
+ this._upToRow = null;
+ }
+ };
+
+ private fetchUpToRow = (id, defaultOrderBy) => {
+ return this.fetchData(async () => {
this._hasReachedEnd = false;
// Also fetch the total count
@@ -137,8 +163,8 @@ export class PagedQuery<TResponse = unknown> extends LiveQuery<TResponse> {
if (result.data.length === 0) {
// This row is not part of this set anymore, we can't do
// this. We stop early to avoid possibly pulling in a ton of
- // data that we don't need
- return;
+ // data that we don't need, and refetch what's loaded instead
+ return this.fetchLoaded();
}
const fullRow = result.data[0];
@@ -168,8 +194,6 @@ export class PagedQuery<TResponse = unknown> extends LiveQuery<TResponse> {
dependencies: result.dependencies,
};
});
-
- return this._fetchDataPromise;
};
private onPageData = (data: Data<TResponse>) => {
diff --git a/packages/docs/docs/transactions/transfers.md b/packages/docs/docs/transactions/transfers.md
index 1a5155a8f1..419c5641bc 100644
--- a/packages/docs/docs/transactions/transfers.md
+++ b/packages/docs/docs/transactions/transfers.md
@@ -37,6 +37,10 @@ Make a transfer of existing transactions in the same way you [bulk-edit transact
3. Go to the drop down top right (the arrow next to "2 transactions")
4. If the transactions are valid to be converted to a transfer, you can click **Make transfer**.
+## Finding the Other Side of a Transfer
+
+Next to the payee of a transfer, an arrow points to the other account. Click it to open that account with the other side of the transfer scrolled into view and briefly highlighted.
+
## Modifying a Transfer
Some fields are tied together across the two halves of a transfer, and some are not.
diff --git a/upcoming-release-notes/scroll-to-linked-transfer.md b/upcoming-release-notes/scroll-to-linked-transfer.md
new file mode 100644
index 0000000000..56a5a94b84
--- /dev/null
+++ b/upcoming-release-notes/scroll-to-linked-transfer.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [rapastranac]
+---
+
+Scroll to and highlight the other side of a transfer when opening it from the transfer arrow