Skip to content

A local-first personal finance app

[Mobile] Drag and drop on accounts to re-order (#4476)

Joel Jeremy Marquezb3e82c55f605
diff --git a/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx b/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx
index 8c72ef1ffa..5a55f7226b 100644
--- a/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx
+++ b/packages/desktop-client/src/components/mobile/accounts/Accounts.tsx
@@ -1,4 +1,15 @@
-import React, { type CSSProperties, useCallback } from 'react';
+import React, {
+ type ComponentPropsWithoutRef,
+ type CSSProperties,
+ useCallback,
+} from 'react';
+import { type DragItem } from 'react-aria';
+import {
+ DropIndicator,
+ ListBox,
+ ListBoxItem,
+ useDragAndDrop,
+} from 'react-aria-components';
import { useTranslation, Trans } from 'react-i18next';
import { Button } from '@actual-app/components/button';
@@ -8,6 +19,7 @@ import { TextOneLine } from '@actual-app/components/text-one-line';
import { View } from '@actual-app/components/view';
import { css } from '@emotion/css';
+import { moveAccount } from 'loot-core/client/accounts/accountsSlice';
import { syncAndDownload } from 'loot-core/client/app/appSlice';
import { replaceModal } from 'loot-core/client/modals/modalsSlice';
import * as queries from 'loot-core/client/queries';
@@ -101,95 +113,108 @@ function AccountHeader<SheetFieldName extends SheetFields<'account'>>({
);
}
-type AccountCardProps = {
- account: AccountEntity;
- updated: boolean;
- connected: boolean;
- pending: boolean;
- failed: boolean;
+type AccountListItemProps = ComponentPropsWithoutRef<
+ typeof ListBoxItem<AccountEntity>
+> & {
+ isUpdated: boolean;
+ isConnected: boolean;
+ isPending: boolean;
+ isFailed: boolean;
getBalanceQuery: (account: AccountEntity) => Binding<'account', 'balance'>;
- onSelect: (id: string) => void;
+ onSelect: (account: AccountEntity) => void;
};
-function AccountCard({
- account,
- updated,
- connected,
- pending,
- failed,
+function AccountListItem({
+ isUpdated,
+ isConnected,
+ isPending,
+ isFailed,
getBalanceQuery,
onSelect,
-}: AccountCardProps) {
+ ...props
+}: AccountListItemProps) {
+ const { value: account } = props;
+
+ if (!account) {
+ return null;
+ }
+
return (
- <Button
- onPress={() => onSelect(account.id)}
- style={{
- border: `1px solid ${theme.pillBorder}`,
- borderRadius: 6,
- boxShadow: `0 1px 1px ${theme.mobileAccountShadow}`,
- marginTop: 10,
- }}
- data-testid="account-list-item"
- >
- <View
- style={{
- flex: 1,
- margin: '10px 0',
- }}
- >
- <View
+ <ListBoxItem textValue={account.name} {...props}>
+ {itemProps => (
+ <Button
+ {...itemProps}
style={{
- flexDirection: 'row',
- alignItems: 'center',
+ width: '100%',
+ border: `1px solid ${theme.pillBorder}`,
+ borderRadius: 6,
+ boxShadow: `0 1px 1px ${theme.mobileAccountShadow}`,
+ marginTop: 10,
}}
+ data-testid="account-list-item"
+ onPress={() => onSelect(account)}
>
- {
- /* TODO: Should bankId be part of the AccountEntity type? */
- 'bankId' in account && account.bankId ? (
- <View
- style={{
- backgroundColor: pending
- ? theme.sidebarItemBackgroundPending
- : failed
- ? theme.sidebarItemBackgroundFailed
- : theme.sidebarItemBackgroundPositive,
- marginRight: '8px',
- width: 8,
- flexShrink: 0,
- height: 8,
- borderRadius: 8,
- opacity: connected ? 1 : 0,
- }}
- />
- ) : null
- }
- <TextOneLine
+ <View
style={{
- ...styles.text,
- fontSize: 17,
- fontWeight: 600,
- color: updated ? theme.mobileAccountText : theme.pillText,
- paddingRight: 30,
+ flex: 1,
+ margin: '10px 0',
}}
- data-testid="account-name"
>
- {account.name}
- </TextOneLine>
- </View>
- </View>
- <CellValue binding={getBalanceQuery(account)} type="financial">
- {props => (
- <CellValueText<'account', 'balance'>
- {...props}
- style={{
- fontSize: 16,
- ...makeAmountFullStyle(props.value),
- }}
- data-testid="account-balance"
- />
- )}
- </CellValue>
- </Button>
+ <View
+ style={{
+ flexDirection: 'row',
+ alignItems: 'center',
+ }}
+ >
+ {
+ /* TODO: Should bankId be part of the AccountEntity type? */
+ 'bankId' in account && account.bankId ? (
+ <View
+ style={{
+ backgroundColor: isPending
+ ? theme.sidebarItemBackgroundPending
+ : isFailed
+ ? theme.sidebarItemBackgroundFailed
+ : theme.sidebarItemBackgroundPositive,
+ marginRight: '8px',
+ width: 8,
+ flexShrink: 0,
+ height: 8,
+ borderRadius: 8,
+ opacity: isConnected ? 1 : 0,
+ }}
+ />
+ ) : null
+ }
+ <TextOneLine
+ style={{
+ ...styles.text,
+ fontSize: 17,
+ fontWeight: 600,
+ color: isUpdated ? theme.mobileAccountText : theme.pillText,
+ paddingRight: 30,
+ }}
+ data-testid="account-name"
+ >
+ {account.name}
+ </TextOneLine>
+ </View>
+ </View>
+ <CellValue binding={getBalanceQuery(account)} type="financial">
+ {props => (
+ <CellValueText<'account', 'balance'>
+ {...props}
+ style={{
+ fontSize: 16,
+ ...makeAmountFullStyle(props.value),
+ }}
+ data-testid="account-balance"
+ />
+ )}
+ </CellValue>
+ </Button>
+ )}
+ </ListBoxItem>
);
}
@@ -207,30 +232,26 @@ function EmptyMessage() {
);
}
-type AccountListProps = {
+type AllAccountListProps = {
accounts: AccountEntity[];
- updatedAccounts: Array<AccountEntity['id']>;
- getBalanceQuery: (account: AccountEntity) => Binding<'account', 'balance'>;
+ getAccountBalance: (account: AccountEntity) => Binding<'account', 'balance'>;
getOnBudgetBalance: () => Binding<'account', 'onbudget-accounts-balance'>;
getOffBudgetBalance: () => Binding<'account', 'offbudget-accounts-balance'>;
onAddAccount: () => void;
- onSelectAccount: (id: string) => void;
+ onOpenAccount: (account: AccountEntity) => void;
onSync: () => Promise<void>;
};
-function AccountList({
+function AllAccountList({
accounts,
- updatedAccounts,
- getBalanceQuery,
+ getAccountBalance,
getOnBudgetBalance,
getOffBudgetBalance,
onAddAccount,
- onSelectAccount,
+ onOpenAccount,
onSync,
-}: AccountListProps) {
+}: AllAccountListProps) {
const { t } = useTranslation();
- const failedAccounts = useFailedAccounts();
- const syncingAccountIds = useSelector(state => state.account.accountsSyncing);
const onBudgetAccounts = accounts.filter(account => account.offbudget === 0);
const offBudgetAccounts = accounts.filter(account => account.offbudget === 1);
@@ -266,19 +287,12 @@ function AccountList({
amount={getOnBudgetBalance()}
/>
)}
- {onBudgetAccounts.map(acct => (
- <AccountCard
- account={acct}
- key={acct.id}
- updated={updatedAccounts && updatedAccounts.includes(acct.id)}
- connected={!!acct.bank}
- pending={syncingAccountIds.includes(acct.id)}
- failed={failedAccounts && failedAccounts.has(acct.id)}
- getBalanceQuery={getBalanceQuery}
- onSelect={onSelectAccount}
- />
- ))}
-
+ <AccountList
+ aria-label={t('On budget accounts')}
+ accounts={onBudgetAccounts}
+ getAccountBalance={getAccountBalance}
+ onOpenAccount={onOpenAccount}
+ />
{offBudgetAccounts.length > 0 && (
<AccountHeader
id="offbudget"
@@ -287,37 +301,132 @@ function AccountList({
style={{ marginTop: 30 }}
/>
)}
- {offBudgetAccounts.map(acct => (
- <AccountCard
- account={acct}
- key={acct.id}
- updated={updatedAccounts && updatedAccounts.includes(acct.id)}
- connected={!!acct.bank}
- pending={syncingAccountIds.includes(acct.id)}
- failed={failedAccounts && failedAccounts.has(acct.id)}
- getBalanceQuery={getBalanceQuery}
- onSelect={onSelectAccount}
- />
- ))}
+ <AccountList
+ aria-label={t('Off budget accounts')}
+ accounts={offBudgetAccounts}
+ getAccountBalance={getAccountBalance}
+ onOpenAccount={onOpenAccount}
+ />
</View>
</PullToRefresh>
</Page>
);
}
+type AccountListProps = {
+ 'aria-label': string;
+ accounts: AccountEntity[];
+ getAccountBalance: (account: AccountEntity) => Binding<'account', 'balance'>;
+ onOpenAccount: (account: AccountEntity) => void;
+};
+
+function AccountList({
+ 'aria-label': ariaLabel,
+ accounts,
+ getAccountBalance: getBalanceBinding,
+ onOpenAccount,
+}: AccountListProps) {
+ const failedAccounts = useFailedAccounts();
+ const syncingAccountIds = useSelector(state => state.account.accountsSyncing);
+ const updatedAccounts = useSelector(state => state.queries.updatedAccounts);
+ const dispatch = useDispatch();
+
+ const { dragAndDropHooks } = useDragAndDrop({
+ getItems: keys =>
+ [...keys].map(
+ key =>
+ ({
+ 'text/plain': key as AccountEntity['id'],
+ }) as DragItem,
+ ),
+ renderDropIndicator: target => {
+ return (
+ <DropIndicator
+ target={target}
+ style={{
+ backgroundColor: theme.tableBorderSeparator,
+ position: 'absolute',
+ left: 2,
+ right: 2,
+ borderRadius: 3,
+ height: 3,
+ }}
+ />
+ );
+ },
+ onReorder: e => {
+ const [key] = e.keys;
+ const accountIdToMove = key as AccountEntity['id'];
+ const targetAccountId = e.target.key as AccountEntity['id'];
+
+ if (e.target.dropPosition === 'before') {
+ dispatch(
+ moveAccount({
+ id: accountIdToMove,
+ targetId: targetAccountId,
+ }),
+ );
+ } else if (e.target.dropPosition === 'after') {
+ const targetAccountIndex = accounts.findIndex(
+ account => account.id === e.target.key,
+ );
+ if (targetAccountIndex === -1) {
+ throw new Error(
+ `Internal error: account with ID ${targetAccountId} not found.`,
+ );
+ }
+
+ const nextToTargetAccount = accounts[targetAccountIndex + 1];
+
+ dispatch(
+ moveAccount({
+ id: accountIdToMove,
+ // Due to the way `moveAccount` works, we use the account next to the
+ // actual target account here because `moveAccount` always shoves the
+ // account *before* the target account.
+ // On the other hand, using `null` as `targetId`moves the account
+ // to the end of the list.
+ targetId: nextToTargetAccount?.id || null,
+ }),
+ );
+ }
+ },
+ });
+ return (
+ <ListBox
+ aria-label={ariaLabel}
+ items={accounts}
+ dragAndDropHooks={dragAndDropHooks}
+ >
+ {account => (
+ <AccountListItem
+ key={account.id}
+ id={account.id}
+ value={account}
+ isUpdated={updatedAccounts && updatedAccounts.includes(account.id)}
+ isConnected={!!account.bank}
+ isPending={syncingAccountIds.includes(account.id)}
+ isFailed={failedAccounts && failedAccounts.has(account.id)}
+ getBalanceQuery={getBalanceBinding}
+ onSelect={onOpenAccount}
+ />
+ )}
+ </ListBox>
+ );
+}
+
export function Accounts() {
const dispatch = useDispatch();
const accounts = useAccounts();
- const updatedAccounts = useSelector(state => state.queries.updatedAccounts);
const [_numberFormat] = useSyncedPref('numberFormat');
const numberFormat = _numberFormat || 'comma-dot';
const [hideFraction] = useSyncedPref('hideFraction');
const navigate = useNavigate();
- const onSelectAccount = useCallback(
- (id: AccountEntity['id']) => {
- navigate(`/accounts/${id}`);
+ const onOpenAccount = useCallback(
+ (account: AccountEntity) => {
+ navigate(`/accounts/${account.id}`);
},
[navigate],
);
@@ -332,17 +441,16 @@ export function Accounts() {
return (
<View style={{ flex: 1 }}>
- <AccountList
+ <AllAccountList
// This key forces the whole table rerender when the number
// format changes
key={numberFormat + hideFraction}
accounts={accounts.filter(account => !account.closed)}
- updatedAccounts={updatedAccounts}
- getBalanceQuery={queries.accountBalance}
+ getAccountBalance={queries.accountBalance}
getOnBudgetBalance={queries.onBudgetAccountBalance}
getOffBudgetBalance={queries.offBudgetAccountBalance}
onAddAccount={onAddAccount}
- onSelectAccount={onSelectAccount}
+ onOpenAccount={onOpenAccount}
onSync={onSync}
/>
</View>
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
index fb29dac6c4..f0dfbf2105 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionListItem.tsx
@@ -142,15 +142,16 @@ export function TransactionListItem({
return (
<ListBoxItem textValue={id} {...props}>
- {({ isSelected }) => (
+ {itemProps => (
<PressResponder {...mergeProps(pressProps, longPressProps)}>
<Button
+ {...itemProps}
style={{
userSelect: 'none',
height: ROW_HEIGHT,
width: '100%',
borderRadius: 0,
- ...(isSelected
+ ...(itemProps.isSelected
? {
borderWidth: '0 0 0 4px',
borderColor: theme.mobileTransactionSelected,
diff --git a/packages/loot-core/src/client/accounts/accountsSlice.ts b/packages/loot-core/src/client/accounts/accountsSlice.ts
index 71b6ea78d8..0b713d1b13 100644
--- a/packages/loot-core/src/client/accounts/accountsSlice.ts
+++ b/packages/loot-core/src/client/accounts/accountsSlice.ts
@@ -325,7 +325,7 @@ export const syncAccounts = createAppAsyncThunk(
type MoveAccountPayload = {
id: AccountEntity['id'];
- targetId: AccountEntity['id'];
+ targetId: AccountEntity['id'] | null;
};
export const moveAccount = createAppAsyncThunk(
diff --git a/packages/loot-core/src/server/accounts/app.ts b/packages/loot-core/src/server/accounts/app.ts
index adbc808ebb..9e522f74a7 100644
--- a/packages/loot-core/src/server/accounts/app.ts
+++ b/packages/loot-core/src/server/accounts/app.ts
@@ -473,7 +473,7 @@ async function moveAccount({
targetId,
}: {
id: AccountEntity['id'];
- targetId: AccountEntity['id'];
+ targetId: AccountEntity['id'] | null;
}) {
await db.moveAccount(id, targetId);
}
diff --git a/packages/loot-core/src/server/db/index.ts b/packages/loot-core/src/server/db/index.ts
index 3bdcdd5371..d9625345d1 100644
--- a/packages/loot-core/src/server/db/index.ts
+++ b/packages/loot-core/src/server/db/index.ts
@@ -694,7 +694,7 @@ export function deleteAccount(account) {
export async function moveAccount(
id: DbAccount['id'],
- targetId: DbAccount['id'],
+ targetId: DbAccount['id'] | null,
) {
const account = await first<DbAccount>(
'SELECT * FROM accounts WHERE id = ?',
diff --git a/packages/loot-core/src/server/db/sort.ts b/packages/loot-core/src/server/db/sort.ts
index eb59865317..28fa615d52 100644
--- a/packages/loot-core/src/server/db/sort.ts
+++ b/packages/loot-core/src/server/db/sort.ts
@@ -15,7 +15,7 @@ function midpoint<T extends { sort_order: number }>(items: T[], to: number) {
export function shoveSortOrders<T extends { id: string; sort_order: number }>(
items: T[],
- targetId?: string,
+ targetId: string | null = null,
) {
const to = items.findIndex(item => item.id === targetId);
const target = items[to];
diff --git a/upcoming-release-notes/4476.md b/upcoming-release-notes/4476.md
new file mode 100644
index 0000000000..021a334ce9
--- /dev/null
+++ b/upcoming-release-notes/4476.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [joel-jeremy]
+---
+
+[Mobile] Drag and drop to reorder accounts (only supports for Chromium-based browsers for now)