A local-first personal finance app
automation UI: add mobile support 📱 (#8099)
Matt Fiddaman00cde6b6bee1
diff --git a/packages/desktop-client/e2e/budget-automations.mobile.test.ts b/packages/desktop-client/e2e/budget-automations.mobile.test.tsnew file mode 100644index 0000000000..41b9538521--- /dev/null+++ b/packages/desktop-client/e2e/budget-automations.mobile.test.ts@@ -0,0 +1,109 @@+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';++test.describe('Mobile budget automations', () => {+ let page: Page;+ let navigation: MobileNavigation;+ let configurationPage: ConfigurationPage;++ test.beforeEach(async ({ browser }) => {+ page = await browser.newPage();+ navigation = new MobileNavigation(page);+ configurationPage = new ConfigurationPage(page);++ await page.setViewportSize({ width: 350, height: 600 });+ await page.goto('/');+ await configurationPage.createTestFile();++ const settingsPage = await navigation.goToSettingsPage();+ await settingsPage.enableExperimentalFeature('Goal templates');+ const uiToggle = page.getByRole('checkbox', {+ name: 'Budget automations UI',+ });+ await uiToggle.waitFor({ state: 'visible' });+ if (!(await uiToggle.isChecked())) {+ await uiToggle.click();+ }+ });++ test.afterEach(async () => {+ await page.close();+ });++ test('opens automations from the category menu and drills into the editor', async () => {+ const budgetPage = await navigation.goToBudgetPage();+ const categoryName = await budgetPage.getCategoryNameForRow(1);++ const categoryMenuModal = await budgetPage.openCategoryMenu(categoryName);+ const automationsModal = await categoryMenuModal.editAutomations();++ await expect(automationsModal.getByText(categoryName)).toBeVisible();+ const addAutomation = automationsModal.getByRole('button', {+ name: 'Add an automation',+ });+ await expect(addAutomation).toBeVisible();++ await expect(+ automationsModal.getByRole('button', { name: 'Cancel' }),+ ).toBeInViewport({ ratio: 1 });+ await expect(+ automationsModal.getByRole('button', { name: 'Save', exact: true }),+ ).toBeInViewport({ ratio: 1 });++ await expect(page).toMatchThemeScreenshots();++ await addAutomation.click();+ const backButton = automationsModal.getByRole('button', {+ name: 'Back',+ exact: true,+ });+ await expect(backButton).toBeVisible();+ await expect(automationsModal.getByText('Automation type')).toBeVisible();++ const fieldHeight = (selector: string) =>+ automationsModal+ .locator(selector)+ .evaluate(el => Math.round(el.getBoundingClientRect().height));++ // on mobile every field is the touch-friendly height and consistent+ await automationsModal.getByRole('button', { name: /% of income/ }).click();+ const percentHeight = await fieldHeight('#percent-field');+ expect(percentHeight).toBeGreaterThanOrEqual(36);+ expect(+ Math.abs((await fieldHeight('#category-field')) - percentHeight),+ ).toBeLessThanOrEqual(3);++ await automationsModal+ .getByRole('button', { name: /Save by date/ })+ .click();+ const amountHeight = await fieldHeight('#by-amount-field');+ expect(amountHeight).toBeGreaterThanOrEqual(36);+ expect(+ Math.abs((await fieldHeight('#by-month-field')) - amountHeight),+ ).toBeLessThanOrEqual(3);++ const viewport = page.viewportSize();+ const editorBox = await automationsModal.boundingBox();+ if (!viewport || !editorBox) {+ throw new Error('expected a visible modal and viewport');+ }+ expect(editorBox.height).toBeLessThanOrEqual(viewport.height + 1);+ await expect(backButton).toBeInViewport({ ratio: 1 });+ await expect(+ automationsModal.getByRole('button', { name: 'Save', exact: true }),+ ).toHaveCount(0);+ await expect(page).toMatchThemeScreenshots();++ await backButton.click();+ await expect(addAutomation).toBeVisible();+ await expect(+ automationsModal.getByRole('button', { name: 'Save', exact: true }),+ ).toBeInViewport({ ratio: 1 });++ await automationsModal.getByRole('button', { name: 'Cancel' }).click();+ await expect(automationsModal).toBeHidden();+ });+});diff --git a/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-1-chromium-linux.png b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-1-chromium-linux.pngnew file mode 100644index 0000000000..4f1aeaab80Binary files /dev/null and b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-1-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-2-chromium-linux.png b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-2-chromium-linux.pngnew file mode 100644index 0000000000..e07ede6734Binary files /dev/null and b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-2-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-3-chromium-linux.png b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-3-chromium-linux.pngnew file mode 100644index 0000000000..644c12c67dBinary files /dev/null and b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-3-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-4-chromium-linux.png b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-4-chromium-linux.pngnew file mode 100644index 0000000000..9406d3d1d8Binary files /dev/null and b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-4-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-5-chromium-linux.png b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-5-chromium-linux.pngnew file mode 100644index 0000000000..82847302ceBinary files /dev/null and b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-5-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-6-chromium-linux.png b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-6-chromium-linux.pngnew file mode 100644index 0000000000..e70bd23d6eBinary files /dev/null and b/packages/desktop-client/e2e/budget-automations.mobile.test.ts-snapshots/Mobile-budget-automations-opens-automations-from-the-category-menu-and-drills-into-the-editor-6-chromium-linux.png differdiff --git a/packages/desktop-client/e2e/page-models/mobile-category-menu-modal.ts b/packages/desktop-client/e2e/page-models/mobile-category-menu-modal.tsindex 77d22b68be..79bc4c46d1 100644--- a/packages/desktop-client/e2e/page-models/mobile-category-menu-modal.ts+++ b/packages/desktop-client/e2e/page-models/mobile-category-menu-modal.ts@@ -8,6 +8,7 @@ export class CategoryMenuModal {readonly heading: Locator;readonly budgetAmountInput: Locator;readonly editNotesButton: Locator;+ readonly budgetAutomationsButton: Locator;constructor(locator: Locator) {this.locator = locator;@@ -16,6 +17,9 @@ export class CategoryMenuModal {this.heading = locator.getByRole('heading');this.budgetAmountInput = locator.getByTestId('amount-input');this.editNotesButton = locator.getByRole('button', { name: 'Edit notes' });+ this.budgetAutomationsButton = locator.getByRole('button', {+ name: 'Budget automations',+ });}async close() {@@ -31,4 +35,10 @@ export class CategoryMenuModal {}),);}++ async editAutomations() {+ await this.budgetAutomationsButton.click();++ return this.page.getByRole('dialog', { name: 'Modal dialog' });+ }}diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex 0fc3ba468e..809467f29f 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -45,6 +45,7 @@"#components/budget/goals/cleanupModel": "./src/components/budget/goals/cleanupModel.ts","#components/budget/goals/constants": "./src/components/budget/goals/constants.ts","#components/budget/goals/displayTemplateMeta": "./src/components/budget/goals/displayTemplateMeta.ts",+ "#components/budget/goals/editor/fieldLayout": "./src/components/budget/goals/editor/fieldLayout.ts","#components/budget/goals/formatMonthLabel": "./src/components/budget/goals/formatMonthLabel.ts","#components/budget/goals/reducer": "./src/components/budget/goals/reducer.ts","#components/budget/goals/useBudgetAutomationCategories": "./src/components/budget/goals/useBudgetAutomationCategories.ts",diff --git a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsxindex 6c6fb0f205..8f86d547a8 100644--- a/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/BySaveAutomation.tsx@@ -1,6 +1,7 @@import { useEffect, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';+import { useResponsive } from '@actual-app/components/hooks/useResponsive';import { SvgInformationCircle } from '@actual-app/components/icons/v2';import { Input } from '@actual-app/components/input';import { Select } from '@actual-app/components/select';@@ -16,12 +17,59 @@ import type {import { updateTemplate } from '#components/budget/goals/actions';import type { Action } from '#components/budget/goals/actions';+import { TWO_UP_FIELD_FLEX } from '#components/budget/goals/editor/fieldLayout';import { FormField, FormLabel } from '#components/forms';import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';+import {+ hideNativeDateIconClassName,+ InputField,+} from '#components/mobile/MobileForms';import { AmountInput } from '#components/util/AmountInput';import { GenericInput } from '#components/util/GenericInput';import { useFormat } from '#hooks/useFormat';+type MonthFieldProps = {+ id: string;+ value: string;+ onChange: (month: string) => void;+};++// we can use a month picker for mobile because we use the native datepicker+// no such luck on desktop (yet!)+function MonthField({ id, value, onChange }: MonthFieldProps) {+ const { isNarrowWidth } = useResponsive();+ if (isNarrowWidth) {+ return (+ <InputField+ id={id}+ type="month"+ value={value}+ onChange={event => onChange(event.target.value)}+ className={hideNativeDateIconClassName}+ style={{+ width: '100%',+ marginLeft: 0,+ marginRight: 0,+ boxSizing: 'border-box',+ WebkitAppearance: 'none',+ appearance: 'none',+ }}+ />+ );+ }+ return (+ <GenericInput+ // remount when the stored month changes so the picker re-syncs+ // to day 01 instead of lingering on whatever day the user picked+ key={value}+ type="date"+ field="date"+ value={value ? `${value}-01` : ''}+ onChange={(next: string) => onChange(next ? next.slice(0, 7) : '')}+ />+ );+}+type BySaveAutomationProps = {template: ByTemplate | SpendTemplate;dispatch: (action: Action) => void;@@ -59,7 +107,7 @@ export const BySaveAutomation = ({return (<><SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}><FormLabel title={t('Total amount')} htmlFor="by-amount-field" /><AmountInputid="by-amount-field"@@ -75,28 +123,19 @@ export const BySaveAutomation = ({}/></FormField>- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}><FormLabel title={t('Target month')} htmlFor="by-month-field" />- <GenericInput- // remount when the stored month changes so the picker re-syncs- // to day 01 instead of lingering on whatever day the user picked- key={template.month}- type="date"- field="date"- value={template.month ? `${template.month}-01` : ''}- onChange={(value: string) =>- dispatch(- updateTemplate({- type: template.type,- month: value ? value.slice(0, 7) : '',- }),- )+ <MonthField+ id="by-month-field"+ value={template.month ?? ''}+ onChange={month =>+ dispatch(updateTemplate({ type: template.type, month }))}/></FormField></SpaceBetween><SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}><LabeledCheckboxid="by-repeats-field"checked={repeats}@@ -123,47 +162,47 @@ export const BySaveAutomation = ({</span></LabeledCheckbox></FormField>- {repeats && (- <>- <FormField style={{ flex: 1 }}>- <FormLabel- title={t('Repeat every')}- htmlFor="by-repeat-amount-field"- />- <Input- id="by-repeat-amount-field"- type="number"- min={1}- step={1}- value={rawRepeat}- onChangeValue={setRawRepeat}- onBlur={commitRepeat}- />- </FormField>- <FormField style={{ flex: 1 }}>- <FormLabel title={t('Period')} htmlFor="by-period-field" />- <Select- id="by-period-field"- value={template.annual ? 'year' : 'month'}- onChange={value =>- dispatch(- updateTemplate({- type: template.type,- annual: value === 'year',- }),- )- }- options={[- ['month', t('Months')],- ['year', t('Years')],- ]}- />- </FormField>- </>- )}</SpaceBetween>+ {repeats && (+ <SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}>+ <FormLabel+ title={t('Repeat every')}+ htmlFor="by-repeat-amount-field"+ />+ <Input+ id="by-repeat-amount-field"+ type="number"+ min={1}+ step={1}+ value={rawRepeat}+ onChangeValue={setRawRepeat}+ onBlur={commitRepeat}+ />+ </FormField>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}>+ <FormLabel title={t('Period')} htmlFor="by-period-field" />+ <Select+ id="by-period-field"+ value={template.annual ? 'year' : 'month'}+ onChange={value =>+ dispatch(+ updateTemplate({+ type: template.type,+ annual: value === 'year',+ }),+ )+ }+ options={[+ ['month', t('Months')],+ ['year', t('Years')],+ ]}+ />+ </FormField>+ </SpaceBetween>+ )}<SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}><LabeledCheckboxid="by-spend-down-field"checked={spendDown}@@ -228,29 +267,24 @@ export const BySaveAutomation = ({</span></LabeledCheckbox></FormField>- {spendDown && (- <FormField style={{ flex: 1 }}>+ </SpaceBetween>+ {spendDown && (+ <SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}><FormLabeltitle={t('Start spending in')}htmlFor="by-spend-from-field"/>- <GenericInput- key={fromMonth}- type="date"- field="date"- value={fromMonth ? `${fromMonth}-01` : ''}- onChange={(value: string) =>- dispatch(- updateTemplate({- type: 'spend',- from: value ? value.slice(0, 7) : '',- }),- )+ <MonthField+ id="by-spend-from-field"+ value={fromMonth ?? ''}+ onChange={from =>+ dispatch(updateTemplate({ type: 'spend', from }))}/></FormField>- )}- </SpaceBetween>+ </SpaceBetween>+ )}</>);};diff --git a/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsxindex db0d90f41a..7be1164748 100644--- a/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/FixedAutomation.tsx@@ -9,6 +9,7 @@ import type { PeriodicTemplate } from '@actual-app/core/types/models/templates';import { updateTemplate } from '#components/budget/goals/actions';import type { Action } from '#components/budget/goals/actions';+import { TWO_UP_FIELD_FLEX } from '#components/budget/goals/editor/fieldLayout';import { FormField, FormLabel } from '#components/forms';import { AmountInput } from '#components/util/AmountInput';import { GenericInput } from '#components/util/GenericInput';@@ -61,7 +62,7 @@ export const FixedAutomation = ({return (<SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}><FormLabel title={t('Amount')} htmlFor="amount-field" /><AmountInputid="amount-field"@@ -77,7 +78,7 @@ export const FixedAutomation = ({}/></FormField>- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}><FormLabel title={t('Every')} htmlFor="period-amount-field" /><Inputid="period-amount-field"@@ -89,7 +90,7 @@ export const FixedAutomation = ({onBlur={commitPeriodAmount}/></FormField>- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}><FormLabel title={t('Period')} htmlFor="period-unit-field" /><Selectid="period-unit-field"@@ -108,7 +109,7 @@ export const FixedAutomation = ({options={periodUnitOptions}/></FormField>- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}><FormLabel title={t('Starting')} htmlFor="starting-field" /><GenericInputtype="date"diff --git a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsxindex d7739b3e61..34163ef155 100644--- a/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/HistoricalAutomation.tsx@@ -1,6 +1,7 @@import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useResponsive } from '@actual-app/components/hooks/useResponsive';import { Input } from '@actual-app/components/input';import { Select } from '@actual-app/components/select';import { SpaceBetween } from '@actual-app/components/space-between';@@ -12,6 +13,11 @@ import type {import { updateTemplate } from '#components/budget/goals/actions';import type { Action } from '#components/budget/goals/actions';import { AmountAdjustment } from '#components/budget/goals/editor/AmountAdjustment';+import {+ DESKTOP_FIELD_GAP,+ MOBILE_FIELD_GAP,+ STACKED_FIELD_FLEX,+} from '#components/budget/goals/editor/fieldLayout';import { FormField, FormLabel } from '#components/forms';type HistoricalAutomationProps = {@@ -24,6 +30,8 @@ export const HistoricalAutomation = ({dispatch,}: HistoricalAutomationProps) => {const { t } = useTranslation();+ const { isNarrowWidth } = useResponsive();+ const fieldFlex = isNarrowWidth ? STACKED_FIELD_FLEX : 1;const months =template.type === 'average' ? template.numMonths : template.lookBack;@@ -47,8 +55,11 @@ export const HistoricalAutomation = ({return (<>- <SpaceBetween gap={50} style={{ marginTop: 10 }}>- <FormField style={{ flex: 1 }}>+ <SpaceBetween+ gap={isNarrowWidth ? MOBILE_FIELD_GAP : DESKTOP_FIELD_GAP}+ style={{ marginTop: 10 }}+ >+ <FormField style={{ flex: fieldFlex }}><FormLabel title={t('Mode')} htmlFor="mode-field" /><Selectid="mode-field"@@ -61,7 +72,7 @@ export const HistoricalAutomation = ({onChange={type => dispatch(updateTemplate({ type }))}/></FormField>- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: fieldFlex }}><FormLabeltitle={t('Number of months back')}htmlFor="look-back-field"diff --git a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsxindex 642be2b32c..113d58ef16 100644--- a/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/LimitAutomation.tsx@@ -17,6 +17,7 @@ import { setDay } from 'date-fns/setDay';import { updateTemplate } from '#components/budget/goals/actions';import type { Action } from '#components/budget/goals/actions';+import { TWO_UP_FIELD_FLEX } from '#components/budget/goals/editor/fieldLayout';import { FormField, FormLabel } from '#components/forms';import { LabeledCheckbox } from '#components/forms/LabeledCheckbox';import { AmountInput } from '#components/util/AmountInput';@@ -52,7 +53,7 @@ export const LimitAutomation = ({});const weekdayField = (- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: TWO_UP_FIELD_FLEX }}><FormLabel title={t('Weekday')} htmlFor="weekday-field" /><Select@@ -73,7 +74,7 @@ export const LimitAutomation = ({);const amountField = (- <FormField key="amount-field" style={{ flex: 1 }}>+ <FormField key="amount-field" style={{ flex: TWO_UP_FIELD_FLEX }}><FormLabel title={t('Amount')} htmlFor="amount-field" /><AmountInputid="amount-field"@@ -92,7 +93,7 @@ export const LimitAutomation = ({);const cadenceField = (- <FormField key="cadence-field" style={{ flex: 1 }}>+ <FormField key="cadence-field" style={{ flex: TWO_UP_FIELD_FLEX }}><FormLabel title={t('Every')} htmlFor="cadence-field" /><Select@@ -156,7 +157,10 @@ export const LimitAutomation = ({<SpaceBetween align="center" gap={10} style={{ marginTop: 10 }}>{period === 'weekly' && weekdayField}- <FormField key="hold-overflow-field" style={{ flex: 1 }}>+ <FormField+ key="hold-overflow-field"+ style={{ flex: TWO_UP_FIELD_FLEX }}+ ><LabeledCheckboxid="hold-overflow-field"checked={!!hold}diff --git a/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomation.tsxindex 51efda0db2..26e139be7c 100644--- a/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/PercentageAutomation.tsx@@ -1,5 +1,6 @@import { useTranslation } from 'react-i18next';+import { useResponsive } from '@actual-app/components/hooks/useResponsive';import { Select } from '@actual-app/components/select';import { SpaceBetween } from '@actual-app/components/space-between';import { View } from '@actual-app/components/view';@@ -12,8 +13,16 @@ import type { PercentageTemplate } from '@actual-app/core/types/models/templatesimport { CategoryAutocomplete } from '#components/autocomplete/CategoryAutocomplete';import { updateTemplate } from '#components/budget/goals/actions';import type { Action } from '#components/budget/goals/actions';+import {+ DESKTOP_FIELD_GAP,+ MOBILE_FIELD_GAP,+ STACKED_FIELD_FLEX,+} from '#components/budget/goals/editor/fieldLayout';import { FormField, FormLabel } from '#components/forms';+import { TapField } from '#components/mobile/MobileForms';import { PercentInput } from '#components/util/PercentInput';+import { pushModal } from '#modals/modalsSlice';+import { useDispatch } from '#redux';type PercentageAutomationProps = {dispatch: (action: Action) => void;@@ -27,31 +36,77 @@ export const PercentageAutomation = ({categories,}: PercentageAutomationProps) => {const { t } = useTranslation();+ const reduxDispatch = useDispatch();+ const { isNarrowWidth } = useResponsive();+ const fieldFlex = isNarrowWidth ? STACKED_FIELD_FLEX : 1;++ const categoryGroups = template.previous+ ? categories.map(group => ({+ ...group,+ categories: group.categories?.filter(+ category => category.id !== 'available funds',+ ),+ }))+ : categories;++ const selectedCategoryName =+ categoryGroups+ .flatMap(group => group.categories ?? [])+ .find(category => category.id === template.category)?.name ??+ template.category ??+ '';return (<>- <SpaceBetween gap={50} style={{ marginTop: 10 }}>- <FormField style={{ flex: 1 }}>+ <SpaceBetween+ gap={isNarrowWidth ? MOBILE_FIELD_GAP : DESKTOP_FIELD_GAP}+ style={{ marginTop: 10 }}+ >+ <FormField style={{ flex: fieldFlex }}><FormLabel title={t('Category')} htmlFor="category-field" />- <CategoryAutocomplete- inputProps={{ id: 'category-field' }}- onSelect={(category: CategoryEntity['id']) =>- dispatch(updateTemplate({ type: 'percentage', category }))- }- value={template.category}- categoryGroups={- template.previous- ? categories.map(group => ({- ...group,- categories: group.categories?.filter(- category => category.id !== 'available funds',- ),- }))- : categories- }- />+ {isNarrowWidth ? (+ <TapField+ id="category-field"+ value={selectedCategoryName}+ placeholder={t('Select a category')}+ style={{+ marginLeft: 0,+ marginRight: 0,+ boxSizing: 'border-box',+ }}+ onPress={() =>+ reduxDispatch(+ pushModal({+ modal: {+ name: 'category-autocomplete',+ options: {+ categoryGroups,+ showHiddenCategories: false,+ onSelect: (id: string | null) =>+ dispatch(+ updateTemplate({+ type: 'percentage',+ category: id ?? '',+ }),+ ),+ },+ },+ }),+ )+ }+ />+ ) : (+ <CategoryAutocomplete+ inputProps={{ id: 'category-field' }}+ onSelect={(category: CategoryEntity['id']) =>+ dispatch(updateTemplate({ type: 'percentage', category }))+ }+ value={template.category}+ categoryGroups={categoryGroups}+ />+ )}</FormField>- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: fieldFlex }}><FormLabel title={t('Percentage')} htmlFor="percent-field" /><PercentInputid="percent-field"@@ -68,8 +123,11 @@ export const PercentageAutomation = ({/></FormField></SpaceBetween>- <SpaceBetween gap={50}>- <FormField style={{ flex: 1 }}>+ <SpaceBetween+ gap={isNarrowWidth ? MOBILE_FIELD_GAP : DESKTOP_FIELD_GAP}+ style={{ marginTop: 10 }}+ >+ <FormField style={{ flex: fieldFlex }}><FormLabel title={t('Percentage of')} htmlFor="previous-field" /><Selectid="previous-field"@@ -95,7 +153,7 @@ export const PercentageAutomation = ({}}/></FormField>- <View style={{ flex: 1 }} />+ {!isNarrowWidth && <View style={{ flex: 1 }} />}</SpaceBetween></>);diff --git a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsxindex 238119129a..53ec0e714a 100644--- a/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx+++ b/packages/desktop-client/src/components/budget/goals/editor/ScheduleAutomation.tsx@@ -1,5 +1,6 @@import { Trans, useTranslation } from 'react-i18next';+import { useResponsive } from '@actual-app/components/hooks/useResponsive';import { Select } from '@actual-app/components/select';import { SpaceBetween } from '@actual-app/components/space-between';import { Text } from '@actual-app/components/text';@@ -9,6 +10,11 @@ import type { ScheduleTemplate } from '@actual-app/core/types/models/templates';import { updateTemplate } from '#components/budget/goals/actions';import type { Action } from '#components/budget/goals/actions';import { AmountAdjustment } from '#components/budget/goals/editor/AmountAdjustment';+import {+ DESKTOP_FIELD_GAP,+ MOBILE_FIELD_GAP,+ STACKED_FIELD_FLEX,+} from '#components/budget/goals/editor/fieldLayout';import { Link } from '#components/common/Link';import { FormField, FormLabel } from '#components/forms';@@ -24,6 +30,8 @@ export const ScheduleAutomation = ({dispatch,}: ScheduleAutomationProps) => {const { t } = useTranslation();+ const { isNarrowWidth } = useResponsive();+ const fieldFlex = isNarrowWidth ? STACKED_FIELD_FLEX : 1;// Match the filter applied to the Select options below — completed and// tombstoned schedules aren't selectable, so a category whose only// schedules are completed should fall through to the "no schedules" state@@ -41,8 +49,11 @@ export const ScheduleAutomation = ({return selectableSchedules.length ? (<>- <SpaceBetween gap={50} style={{ marginTop: 10 }}>- <FormField style={{ flex: 1 }}>+ <SpaceBetween+ gap={isNarrowWidth ? MOBILE_FIELD_GAP : DESKTOP_FIELD_GAP}+ style={{ marginTop: 10 }}+ >+ <FormField style={{ flex: fieldFlex }}><FormLabel title={t('Schedule')} htmlFor="schedule-field" /><Selectid="schedule-field"@@ -60,7 +71,7 @@ export const ScheduleAutomation = ({options={selectableSchedules.map(s => [s.name, s.name] as const)}/></FormField>- <FormField style={{ flex: 1 }}>+ <FormField style={{ flex: fieldFlex }}><FormLabel title={t('Savings mode')} htmlFor="schedule-full-field" /><Selectid="schedule-full-field"diff --git a/packages/desktop-client/src/components/budget/goals/editor/fieldLayout.ts b/packages/desktop-client/src/components/budget/goals/editor/fieldLayout.tsnew file mode 100644index 0000000000..cb325605c0--- /dev/null+++ b/packages/desktop-client/src/components/budget/goals/editor/fieldLayout.ts@@ -0,0 +1,5 @@+// shared field-layout values for the automation editors+export const TWO_UP_FIELD_FLEX = '1 1 125px';+export const STACKED_FIELD_FLEX = '1 1 100%';+export const MOBILE_FIELD_GAP = 12;+export const DESKTOP_FIELD_GAP = 50;diff --git a/packages/desktop-client/src/components/mobile/MobileForms.tsx b/packages/desktop-client/src/components/mobile/MobileForms.tsxindex 426c21daf5..ef8915d1f5 100644--- a/packages/desktop-client/src/components/mobile/MobileForms.tsx+++ b/packages/desktop-client/src/components/mobile/MobileForms.tsx@@ -47,7 +47,7 @@ const valueStyle = {height: styles.mobileMinHeight,};-const hideNativeDateIconClassName = css({+export const hideNativeDateIconClassName = css({'&::-webkit-calendar-picker-indicator': {display: 'none',},diff --git a/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsx b/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsxindex a6dad3f704..8c376409f6 100644--- a/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsx+++ b/packages/desktop-client/src/components/mobile/budget/BudgetPage.tsx@@ -48,6 +48,7 @@ import { FinancialText } from '#components/FinancialText';import { MobilePageHeader, Page } from '#components/Page';import { SyncRefresh } from '#components/SyncRefresh';import { useCategories } from '#hooks/useCategories';+import { useFeatureFlag } from '#hooks/useFeatureFlag';import { useFormat } from '#hooks/useFormat';import { useLocale } from '#hooks/useLocale';import { useLocalPref } from '#hooks/useLocalPref';@@ -81,6 +82,8 @@ export function BudgetPage() {} = useCategories();const [budgetTypePref] = useSyncedPref('budgetType');const budgetType = isBudgetType(budgetTypePref) ? budgetTypePref : 'envelope';+ const goalTemplatesEnabled = useFeatureFlag('goalTemplatesEnabled');+ const goalTemplatesUIEnabled = useFeatureFlag('goalTemplatesUIEnabled');const spreadsheet = useSpreadsheet();const currMonth = monthUtils.currentMonth();@@ -431,6 +434,10 @@ export function BudgetPage() {const onOpenCategoryMenuModal = useCallback(id => {const category = categories.find(c => c.id === id);+ const canEditAutomations =+ goalTemplatesEnabled &&+ goalTemplatesUIEnabled &&+ !(category.is_income && budgetType !== 'tracking');dispatch(pushModal({modal: {@@ -441,18 +448,35 @@ export function BudgetPage() {onEditNotes: onOpenCategoryNotesModal,onDelete: onDeleteCategory,onToggleVisibility: onToggleCategoryVisibility,+ ...(canEditAutomations && {+ onEditAutomations: (categoryId: string) => {+ dispatch(collapseModals({ rootModalName: 'category-menu' }));+ dispatch(+ pushModal({+ modal: {+ name: 'category-automations-edit',+ options: { categoryId, month: startMonth },+ },+ }),+ );+ },+ }),},},}),);},[+ budgetType,categories,dispatch,+ goalTemplatesEnabled,+ goalTemplatesUIEnabled,onDeleteCategory,onOpenCategoryNotesModal,onSaveCategory,onToggleCategoryVisibility,+ startMonth,],);diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationEditorPane.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationEditorPane.tsxindex 8f15c15499..ae8f66c576 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationEditorPane.tsx+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/AutomationEditorPane.tsx@@ -4,8 +4,10 @@ import { Button } from '@actual-app/components/button';import { SvgDelete } from '@actual-app/components/icons/v0';import { SvgAlertTriangle } from '@actual-app/components/icons/v2';import { Input } from '@actual-app/components/input';+import { styles } from '@actual-app/components/styles';import { Text } from '@actual-app/components/text';import { theme } from '@actual-app/components/theme';+import { tokens } from '@actual-app/components/tokens';import { View } from '@actual-app/components/view';import type {CategoryGroupEntity,@@ -47,6 +49,20 @@ const CONFIG_PANEL_CLASS = css({},});+// on mobile, size fields to the touch-friendly standard, not the desktop height+const MOBILE_TOUCH_FIELDS_CLASS = css({+ [`@media (max-width: ${parseInt(tokens.breakpoint_small, 10) - 1}px)`]: {+ '& input:not([type="checkbox"]):not([type="radio"]), & button[type="button"]:not([aria-pressed])':+ {+ minHeight: styles.mobileMinHeight,+ boxSizing: 'border-box',+ },+ '& input[type="date"], & input[type="month"]': {+ width: '100%',+ },+ },+});+const SINGLETON_TYPES: ReadonlySet<DisplayTemplateType> = new Set(['limit','refill',@@ -164,7 +180,10 @@ export function AutomationEditorPane({scrollbarGutter: 'stable',}}>- <View style={{ padding: 20, gap: 14, flexShrink: 0 }}>+ <View+ className={MOBILE_TOUCH_FIELDS_CLASS}+ style={{ padding: 20, gap: 14, flexShrink: 0 }}+ >{activeError && (<Viewstyle={{diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBody.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBody.tsxindex 36fa19c853..6ab02285a5 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBody.tsx+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBody.tsx@@ -1,4 +1,3 @@-import { useEffect, useMemo, useState } from 'react';import type { CSSProperties, ReactNode } from 'react';import { Trans } from 'react-i18next';@@ -9,40 +8,20 @@ import { Text } from '@actual-app/components/text';import { theme } from '@actual-app/components/theme';import { Tooltip } from '@actual-app/components/tooltip';import { View } from '@actual-app/components/view';-import { send } from '@actual-app/core/platform/client/connection';import type {CategoryGroupEntity,ScheduleEntity,} from '@actual-app/core/types/models';import type { CleanupTemplate } from '@actual-app/core/types/models/cleanup-templates';import { css } from '@emotion/css';-import debounce from 'lodash/debounce';-import {- createAutomationEntry,- getAutomationExamples,-} from '#components/budget/goals/automationExamples';import type { AutomationEntry } from '#components/budget/goals/automationExamples';-import {- cleanupDefToEditor,- editorToCleanupDef,- emptyCleanupConfig,- isCleanupConfigured,-} from '#components/budget/goals/cleanupModel';-import type { CleanupConfig } from '#components/budget/goals/cleanupModel';+import { isCleanupConfigured } from '#components/budget/goals/cleanupModel';import { CleanupAutomation } from '#components/budget/goals/editor/CleanupAutomation';import { formatMonthLabel } from '#components/budget/goals/formatMonthLabel';-import {- validateAutomation,- validatePercentageAllocation,- validateSchedulePriorities,-} from '#components/budget/goals/validateAutomation';import { Link } from '#components/common/Link';-import { useCleanupGroups } from '#hooks/useCleanupGroups';import { useFormat } from '#hooks/useFormat';import { useLocale } from '#hooks/useLocale';-import { pushModal } from '#modals/modalsSlice';-import { useDispatch } from '#redux';import { AutomationEditorPane } from './AutomationEditorPane';import { AutomationListRow } from './AutomationListRow';@@ -50,7 +29,7 @@ import { BudgetAutomationMigrationWarning } from './BudgetAutomationMigrationWarimport { CleanupListRow } from './CleanupListRow';import { ConflictBanner } from './ConflictBanner';import { EmptyState } from './EmptyState';-import { NON_CONTRIBUTION_TYPES } from './TypePicker';+import { useBudgetAutomationsEditor } from './useBudgetAutomationsEditor';const RULE_LIST_WIDTH = 310;@@ -138,22 +117,6 @@ type BudgetAutomationsBodyProps = {onClose: () => void;};-type ActiveSelection = { kind: 'entry'; idx: number } | { kind: 'cleanup' };--function pickInitialSelection(- entries: AutomationEntry[],- cleanup: CleanupConfig,-): ActiveSelection {- if (entries.length > 0) {- const idx = entries.findIndex(- e => !NON_CONTRIBUTION_TYPES.has(e.displayType),- );- return { kind: 'entry', idx: idx >= 0 ? idx : 0 };- }- if (isCleanupConfigured(cleanup)) return { kind: 'cleanup' };- return { kind: 'entry', idx: 0 };-}-export function BudgetAutomationsBody({categoryId,categoryName,@@ -165,218 +128,48 @@ export function BudgetAutomationsBody({month,onClose,}: BudgetAutomationsBodyProps) {- const dispatch = useDispatch();const format = useFormat();const locale = useLocale();- const { groups: cleanupGroups, createGroup: createCleanupGroup } =- useCleanupGroups();-- const [entries, setEntries] = useState<AutomationEntry[]>(initialEntries);- const initialCleanupConfig = cleanupDefToEditor(initialCleanup);- const [cleanup, setCleanup] = useState<CleanupConfig>(initialCleanupConfig);- const [active, setActive] = useState<ActiveSelection>(() =>- pickInitialSelection(initialEntries, initialCleanupConfig),- );- const [saving, setSaving] = useState(false);- const [dryRun, setDryRun] = useState<{- budgeted: number;- perTemplate: number[];- } | null>(null);-- const onAddAutomation = (create?: () => AutomationEntry) => {- const fallback = getAutomationExamples().find(- e => e.displayType === 'fixed',- );- const entry = (create ?? fallback?.create)?.();- if (!entry) return;- setEntries(prev => {- const next = [...prev, entry];- setActive({ kind: 'entry', idx: next.length - 1 });- return next;- });- };-- const onAddLimitAutomation = () => {- const entry = createAutomationEntry(- {- directive: 'template',- type: 'limit',- amount: 500,- period: 'monthly',- hold: false,- priority: null,- },- 'limit',- );- setEntries(prev => {- const next = [...prev, entry];- setActive({ kind: 'entry', idx: next.length - 1 });- return next;- });- };-- const onAddGoalAutomation = () => {- const entry = createAutomationEntry(- {- directive: 'goal',- type: 'goal',- amount: 1000,- },- 'goal',- );- setEntries(prev => {- const next = [...prev, entry];- setActive({ kind: 'entry', idx: next.length - 1 });- return next;- });- };-- const onAddCleanup = () => {- if (!isCleanupConfigured(cleanup)) setCleanup(emptyCleanupConfig());- setActive({ kind: 'cleanup' });- };-- const onDeleteCleanup = () => {- setCleanup(emptyCleanupConfig());- setActive({ kind: 'entry', idx: 0 });- };-- const onDelete = (index: number) => {- setEntries(prev => {- const next = prev.filter((_, i) => i !== index);- setActive(currentActive => {- if (currentActive.kind !== 'entry') return currentActive;- if (next.length === 0) return { kind: 'entry', idx: 0 };- const idx = currentActive.idx;- if (idx >= next.length) return { kind: 'entry', idx: next.length - 1 };- if (idx > index) return { kind: 'entry', idx: idx - 1 };- return currentActive;- });- return next;- });- };-- const onSave = async () => {- if (saving) return;- setSaving(true);- try {- const templatesToSave = entries.map(({ template }) => template);- await send('budget/set-category-automations', {- categoriesWithTemplates: [- {- id: categoryId,- templates: templatesToSave,- cleanup: editorToCleanupDef(cleanup),- },- ],- source: 'ui',- });- onClose();- } finally {- setSaving(false);- }- };- const onUnmigrate = () => {- dispatch(- pushModal({- modal: {- name: 'category-automations-unmigrate',- options: {- categoryId,- templates: entries.map(({ template }) => template),- cleanup: editorToCleanupDef(cleanup),- },- },- }),- );- };-- // the react compiler wasn't memoising this properly and causing infinite- // re-renders- const templates = useMemo(() => entries.map(e => e.template), [entries]);-- const validPercentageSources = new Set<string>([- 'all income',- 'available funds',- ]);- for (const group of categories) {- for (const cat of group.categories ?? []) {- if (!cat.is_income) continue;- validPercentageSources.add(cat.id);- if (cat.name) validPercentageSources.add(cat.name.toLowerCase());- }- }-- const automationErrors = entries.map(entry =>- validateAutomation(- entry.template,- entry.displayType,- templates,- schedules,- new Date(),- validPercentageSources,- ),- );-- useEffect(() => {- if (templates.length === 0) {- setDryRun({ budgeted: 0, perTemplate: [] });- return;- }- let cancelled = false;- const run = debounce(async () => {- try {- const result = await send('budget/dry-run-category-template', {- month,- categoryId,- templates,- });- if (!cancelled) setDryRun(result);- } catch {- if (!cancelled) setDryRun(null);- }- }, 200);- void run();- return () => {- cancelled = true;- run.cancel();- };- }, [templates, month, categoryId]);-- const totalMonthly = dryRun?.budgeted ?? 0;- const contributions: (number | null)[] = entries.map((_, i) =>- dryRun?.perTemplate?.[i] != null ? dryRun.perTemplate[i] : null,- );- const hasErrors = automationErrors.some(error => error !== null);- const conflicts = [- validatePercentageAllocation(templates),- validateSchedulePriorities(templates),- ].filter(conflict => conflict !== null);-- const categoryNameMap: Record<string, string> = {};- for (const group of categories) {- for (const cat of group.categories ?? []) {- categoryNameMap[cat.id] = cat.name;- }- }-- const hasLimitAutomation = entries.some(e => e.displayType === 'limit');- const hasGoalAutomation = entries.some(e => e.displayType === 'goal');-- const isOption = (entry: AutomationEntry) =>- entry.displayType === 'limit' || entry.displayType === 'goal';- const indexedEntries = entries.map((entry, idx) => ({ entry, idx }));- const contributionEntries = indexedEntries.filter(- ({ entry }) => !isOption(entry),- );- const optionEntries = indexedEntries.filter(({ entry }) => isOption(entry));+ const {+ entries,+ cleanup,+ setCleanup,+ setActive,+ saving,+ onAddAutomation,+ onAddLimitAutomation,+ onAddGoalAutomation,+ onAddCleanup,+ onDeleteCleanup,+ onDelete,+ onSave,+ onUnmigrate,+ setEntries,+ cleanupGroups,+ createCleanupGroup,+ automationErrors,+ totalMonthly,+ contributions,+ hasErrors,+ conflicts,+ categoryNameMap,+ hasLimitAutomation,+ hasGoalAutomation,+ contributionEntries,+ optionEntries,+ safeActiveIdx,+ cleanupActive,+ } = useBudgetAutomationsEditor({+ categoryId,+ initialEntries,+ initialCleanup,+ schedules,+ categories,+ month,+ onClose,+ });- const safeActiveIdx =- active.kind === 'entry'- ? Math.min(active.idx, Math.max(0, entries.length - 1))- : -1;- const cleanupActive = active.kind === 'cleanup';const setActiveIdx = (idx: number) => setActive({ kind: 'entry', idx });return (diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBodyMobile.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBodyMobile.tsxnew file mode 100644index 0000000000..eeeedc8f77--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsBodyMobile.tsx@@ -0,0 +1,441 @@+import { useState } from 'react';+import type { CSSProperties, ReactNode } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { Button } from '@actual-app/components/button';+import { SvgDelete } from '@actual-app/components/icons/v0';+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 {+ CategoryGroupEntity,+ ScheduleEntity,+} from '@actual-app/core/types/models';+import type { CleanupTemplate } from '@actual-app/core/types/models/cleanup-templates';++import type { AutomationEntry } from '#components/budget/goals/automationExamples';+import { isCleanupConfigured } from '#components/budget/goals/cleanupModel';+import { getDisplayTemplateMeta } from '#components/budget/goals/displayTemplateMeta';+import { CleanupAutomation } from '#components/budget/goals/editor/CleanupAutomation';+import { formatMonthLabel } from '#components/budget/goals/formatMonthLabel';+import { Link } from '#components/common/Link';+import { MobileBackButton } from '#components/mobile/MobileBackButton';+import { useFormat } from '#hooks/useFormat';+import { useLocale } from '#hooks/useLocale';++import { AutomationEditorPane } from './AutomationEditorPane';+import { AutomationListRow } from './AutomationListRow';+import { BudgetAutomationMigrationWarning } from './BudgetAutomationMigrationWarning';+import { CleanupListRow } from './CleanupListRow';+import { ConflictBanner } from './ConflictBanner';+import { useBudgetAutomationsEditor } from './useBudgetAutomationsEditor';+import type { ActiveSelection } from './useBudgetAutomationsEditor';++function SectionHeader({+ children,+ style,+}: {+ children: ReactNode;+ style?: CSSProperties;+}) {+ return (+ <Text+ style={{+ flexShrink: 0,+ padding: '6px 4px',+ fontSize: 11,+ textTransform: 'uppercase',+ color: theme.pageTextLight,+ fontWeight: 600,+ letterSpacing: '0.05em',+ ...style,+ }}+ >+ {children}+ </Text>+ );+}++function AddButton({+ onPress,+ children,+}: {+ onPress: () => void;+ children: ReactNode;+}) {+ return (+ <Button+ variant="bare"+ onPress={onPress}+ style={{+ flexShrink: 0,+ width: '100%',+ height: styles.mobileMinHeight,+ border: `1px dashed ${theme.tableBorder}`,+ borderRadius: 6,+ color: theme.pageTextPositive,+ fontWeight: 600,+ justifyContent: 'center',+ }}+ >+ {children}+ </Button>+ );+}++type BudgetAutomationsBodyMobileProps = {+ categoryId: string;+ categoryName: string;+ needsMigration: boolean;+ initialEntries: AutomationEntry[];+ initialCleanup: CleanupTemplate[];+ schedules: readonly ScheduleEntity[];+ categories: CategoryGroupEntity[];+ month: string;+ onClose: () => void;+};++export function BudgetAutomationsBodyMobile({+ categoryId,+ categoryName,+ needsMigration,+ initialEntries,+ initialCleanup,+ schedules,+ categories,+ month,+ onClose,+}: BudgetAutomationsBodyMobileProps) {+ const { t } = useTranslation();+ const format = useFormat();+ const locale = useLocale();++ const {+ entries,+ cleanup,+ setCleanup,+ setActive,+ saving,+ onAddAutomation,+ onAddLimitAutomation,+ onAddGoalAutomation,+ onAddCleanup,+ onDeleteCleanup,+ onDelete,+ onSave,+ onUnmigrate,+ setEntries,+ cleanupGroups,+ createCleanupGroup,+ automationErrors,+ totalMonthly,+ contributions,+ hasErrors,+ conflicts,+ categoryNameMap,+ hasLimitAutomation,+ hasGoalAutomation,+ contributionEntries,+ optionEntries,+ safeActiveIdx,+ cleanupActive,+ } = useBudgetAutomationsEditor({+ categoryId,+ initialEntries,+ initialCleanup,+ schedules,+ categories,+ month,+ onClose,+ });++ const [screen, setScreen] = useState<'list' | 'editor'>('list');+ const backToList = () => setScreen('list');+ const goToEditor = (selection: ActiveSelection) => {+ setActive(selection);+ setScreen('editor');+ };++ const editing = screen === 'editor' && (cleanupActive || safeActiveIdx >= 0);++ const select = (idx: number) => goToEditor({ kind: 'entry', idx });+ const addAutomation = () => {+ onAddAutomation();+ setScreen('editor');+ };+ const addLimit = () => {+ onAddLimitAutomation();+ setScreen('editor');+ };+ const addGoal = () => {+ onAddGoalAutomation();+ setScreen('editor');+ };+ const addCleanup = () => {+ onAddCleanup();+ setScreen('editor');+ };+ const selectCleanup = () => goToEditor({ kind: 'cleanup' });+ const deleteEntry = (idx: number) => {+ onDelete(idx);+ backToList();+ };+ const deleteCleanup = () => {+ onDeleteCleanup();+ backToList();+ };++ const saveButton = (+ <Button+ variant="primary"+ onPress={onSave}+ isDisabled={hasErrors || conflicts.length > 0 || saving}+ >+ <Trans>Save</Trans>+ </Button>+ );++ if (editing) {+ const activeEntry = entries[safeActiveIdx];+ const title = cleanupActive+ ? t('End of month cleanup')+ : activeEntry+ ? getDisplayTemplateMeta(activeEntry.displayType).label+ : '';++ return (+ <View style={{ flex: 1, flexDirection: 'column', minHeight: 0 }}>+ <View+ style={{+ flexShrink: 0,+ flexDirection: 'row',+ alignItems: 'center',+ borderBottom: `1px solid ${theme.tableBorder}`,+ }}+ >+ <View style={{ flex: 1, minWidth: 0, alignItems: 'flex-start' }}>+ <MobileBackButton onPress={backToList} />+ </View>+ <Text+ style={{+ flexShrink: 0,+ fontWeight: 600,+ color: theme.pageText,+ textAlign: 'center',+ }}+ >+ {title}+ </Text>+ <View style={{ flex: 1, minWidth: 0 }} />+ </View>++ {cleanupActive ? (+ <View+ style={{+ flex: 1,+ padding: 16,+ overflowY: 'auto',+ overflowX: 'hidden',+ gap: 14,+ }}+ >+ <CleanupAutomation+ config={cleanup}+ groups={cleanupGroups}+ onChange={setCleanup}+ onCreateGroup={createCleanupGroup}+ />+ <Button+ variant="bare"+ onPress={deleteCleanup}+ style={{ color: theme.errorText, alignSelf: 'flex-start' }}+ >+ <span+ style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}+ >+ <SvgDelete+ width={10}+ height={10}+ style={{ color: 'inherit' }}+ />+ <Trans>Remove cleanup</Trans>+ </span>+ </Button>+ </View>+ ) : (+ <AutomationEditorPane+ entries={entries}+ activeIdx={safeActiveIdx}+ automationErrors={automationErrors}+ schedules={schedules}+ categories={categories}+ hasLimitAutomation={hasLimitAutomation}+ onAddLimitAutomation={onAddLimitAutomation}+ setEntries={setEntries}+ onDelete={deleteEntry}+ />+ )}+ </View>+ );+ }++ return (+ <View style={{ flex: 1, flexDirection: 'column', minHeight: 0 }}>+ <View+ style={{+ flexShrink: 0,+ padding: '16px 16px 12px',+ borderBottom: `1px solid ${theme.tableBorder}`,+ flexDirection: 'row',+ alignItems: 'flex-end',+ justifyContent: 'space-between',+ gap: 12,+ }}+ >+ <View style={{ minWidth: 0 }}>+ <Text style={{ fontSize: 11, color: theme.pageTextLight }}>+ <Trans>Budget automation</Trans>+ </Text>+ <Text+ style={{+ fontSize: 18,+ fontWeight: 600,+ color: theme.pageText,+ marginTop: 2,+ }}+ >+ {categoryName}+ </Text>+ </View>+ <View style={{ textAlign: 'right', flexShrink: 0 }}>+ <Text+ style={{+ fontSize: 10,+ textTransform: 'uppercase',+ color: theme.pageTextLight,+ letterSpacing: '0.04em',+ display: 'block',+ }}+ >+ <Trans>+ Projected for {{ month: formatMonthLabel(month, locale) }}+ </Trans>+ </Text>+ <Text+ style={{+ fontSize: 20,+ fontWeight: 600,+ color: theme.pageTextPositive,+ fontVariantNumeric: 'tabular-nums',+ display: 'block',+ }}+ >+ {format(totalMonthly, 'financial')}+ </Text>+ </View>+ </View>++ {needsMigration && (+ <BudgetAutomationMigrationWarning+ categoryId={categoryId}+ style={{ flexShrink: 0, margin: '12px 16px 0' }}+ />+ )}++ {conflicts.map((conflict, i) => (+ <ConflictBanner key={i} conflict={conflict} />+ ))}++ <View+ style={{+ flex: 1,+ minHeight: 0,+ overflowY: 'auto',+ padding: 12,+ gap: 6,+ }}+ >+ <SectionHeader>+ <Trans>Automations</Trans>+ </SectionHeader>+ {contributionEntries.map(({ entry, idx }) => (+ <AutomationListRow+ key={entry.id}+ index={idx}+ entry={entry}+ isActive={false}+ error={automationErrors[idx]}+ contribution={contributions[idx]}+ categoryNameMap={categoryNameMap}+ onSelect={select}+ />+ ))}+ <AddButton onPress={addAutomation}>+ + <Trans>Add an automation</Trans>+ </AddButton>++ <SectionHeader style={{ marginTop: 12 }}>+ <Trans>Options</Trans>+ </SectionHeader>+ {optionEntries.map(({ entry, idx }) => (+ <AutomationListRow+ key={entry.id}+ index={idx}+ entry={entry}+ isActive={false}+ error={automationErrors[idx]}+ contribution={contributions[idx]}+ categoryNameMap={categoryNameMap}+ onSelect={select}+ />+ ))}+ {!hasLimitAutomation && (+ <AddButton onPress={addLimit}>+ + <Trans>Add balance cap</Trans>+ </AddButton>+ )}+ {!hasGoalAutomation && (+ <AddButton onPress={addGoal}>+ + <Trans>Add long-term goal</Trans>+ </AddButton>+ )}+ {isCleanupConfigured(cleanup) ? (+ <CleanupListRow+ config={cleanup}+ groups={cleanupGroups}+ isActive={false}+ onSelect={selectCleanup}+ />+ ) : (+ <AddButton onPress={addCleanup}>+ + <Trans>Add end of month cleanup</Trans>+ </AddButton>+ )}+ </View>++ <View+ style={{+ flexShrink: 0,+ padding: 12,+ borderTop: `1px solid ${theme.tableBorder}`,+ flexDirection: 'row',+ gap: 8,+ alignItems: 'center',+ backgroundColor: theme.tableBackground,+ }}+ >+ {!needsMigration && (+ <Link variant="text" onClick={onUnmigrate}>+ <Trans>Un-migrate to text notes</Trans>+ </Link>+ )}+ <View style={{ flex: 1 }} />+ <Button onPress={onClose}>+ <Trans>Cancel</Trans>+ </Button>+ {saveButton}+ </View>+ </View>+ );+}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsxindex 78815fadd3..4629052b13 100644--- a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/BudgetAutomationsModal.tsx@@ -1,5 +1,6 @@import { useState } from 'react';+import { useResponsive } from '@actual-app/components/hooks/useResponsive';import { AnimatedLoading } from '@actual-app/components/icons/AnimatedLoading';import { View } from '@actual-app/components/view';import { currentMonth } from '@actual-app/core/shared/months';@@ -15,6 +16,7 @@ import { useCategoryCleanup } from '#hooks/useCategoryCleanup';import { useSchedules } from '#hooks/useSchedules';import { BudgetAutomationsBody } from './BudgetAutomationsBody';+import { BudgetAutomationsBodyMobile } from './BudgetAutomationsBodyMobile';import { migrateTemplatesToAutomations } from './migrateTemplatesToAutomations';import { UnsupportedDirectivesNotice } from './UnsupportedDirectivesNotice';@@ -28,6 +30,7 @@ export function BudgetAutomationsModal({categoryId: string;month?: string;}) {+ const { isNarrowWidth } = useResponsive();const [parsedTemplates, setParsedTemplates] = useState<Template[] | null>(null,);@@ -89,16 +92,27 @@ export function BudgetAutomationsModal({<Modalname="category-automations-edit"containerProps={{- style: {- width: MODAL_WIDTH,- maxWidth: '95vw',- height: MODAL_HEIGHT,- maxHeight: '90vh',- padding: 0,- overflow: 'hidden',- display: 'flex',- flexDirection: 'column',- },+ style: isNarrowWidth+ ? {+ width: '90vw',+ maxWidth: '90vw',+ height: '90dvh',+ maxHeight: '90dvh',+ padding: 0,+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column',+ }+ : {+ width: MODAL_WIDTH,+ maxWidth: '95vw',+ height: MODAL_HEIGHT,+ maxHeight: '90vh',+ padding: 0,+ overflow: 'hidden',+ display: 'flex',+ flexDirection: 'column',+ },}}>{({ state }) => (@@ -115,6 +129,18 @@ export function BudgetAutomationsModal({</View>) : hasUnsupportedDirective ? (<UnsupportedDirectivesNotice onClose={() => state.close()} />+ ) : isNarrowWidth ? (+ <BudgetAutomationsBodyMobile+ categoryId={categoryId}+ categoryName={currentCategory?.name ?? ''}+ needsMigration={needsMigration}+ initialEntries={initialEntries ?? []}+ initialCleanup={parsedCleanup}+ schedules={schedules}+ categories={categories}+ month={effectiveMonth}+ onClose={() => state.close()}+ />) : (<BudgetAutomationsBodycategoryId={categoryId}diff --git a/packages/desktop-client/src/components/modals/BudgetAutomationsModal/useBudgetAutomationsEditor.ts b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/useBudgetAutomationsEditor.tsnew file mode 100644index 0000000000..1124613b1f--- /dev/null+++ b/packages/desktop-client/src/components/modals/BudgetAutomationsModal/useBudgetAutomationsEditor.ts@@ -0,0 +1,314 @@+import { useEffect, useMemo, useState } from 'react';++import { send } from '@actual-app/core/platform/client/connection';+import type {+ CategoryGroupEntity,+ ScheduleEntity,+} from '@actual-app/core/types/models';+import type { CleanupTemplate } from '@actual-app/core/types/models/cleanup-templates';+import debounce from 'lodash/debounce';++import {+ createAutomationEntry,+ getAutomationExamples,+} from '#components/budget/goals/automationExamples';+import type { AutomationEntry } from '#components/budget/goals/automationExamples';+import {+ cleanupDefToEditor,+ editorToCleanupDef,+ emptyCleanupConfig,+ isCleanupConfigured,+} from '#components/budget/goals/cleanupModel';+import type { CleanupConfig } from '#components/budget/goals/cleanupModel';+import {+ validateAutomation,+ validatePercentageAllocation,+ validateSchedulePriorities,+} from '#components/budget/goals/validateAutomation';+import { useCleanupGroups } from '#hooks/useCleanupGroups';+import { pushModal } from '#modals/modalsSlice';+import { useDispatch } from '#redux';++import { NON_CONTRIBUTION_TYPES } from './TypePicker';++export type ActiveSelection =+ | { kind: 'entry'; idx: number }+ | { kind: 'cleanup' };++function pickInitialSelection(+ entries: AutomationEntry[],+ cleanup: CleanupConfig,+): ActiveSelection {+ if (entries.length > 0) {+ const idx = entries.findIndex(+ e => !NON_CONTRIBUTION_TYPES.has(e.displayType),+ );+ return { kind: 'entry', idx: idx >= 0 ? idx : 0 };+ }+ if (isCleanupConfigured(cleanup)) return { kind: 'cleanup' };+ return { kind: 'entry', idx: 0 };+}++type UseBudgetAutomationsEditorArgs = {+ categoryId: string;+ initialEntries: AutomationEntry[];+ initialCleanup: CleanupTemplate[];+ schedules: readonly ScheduleEntity[];+ categories: CategoryGroupEntity[];+ month: string;+ onClose: () => void;+};++export function useBudgetAutomationsEditor({+ categoryId,+ initialEntries,+ initialCleanup,+ schedules,+ categories,+ month,+ onClose,+}: UseBudgetAutomationsEditorArgs) {+ const dispatch = useDispatch();+ const { groups: cleanupGroups, createGroup: createCleanupGroup } =+ useCleanupGroups();++ const [entries, setEntries] = useState<AutomationEntry[]>(initialEntries);+ const initialCleanupConfig = cleanupDefToEditor(initialCleanup);+ const [cleanup, setCleanup] = useState<CleanupConfig>(initialCleanupConfig);+ const [active, setActive] = useState<ActiveSelection>(() =>+ pickInitialSelection(initialEntries, initialCleanupConfig),+ );+ const [saving, setSaving] = useState(false);+ const [dryRun, setDryRun] = useState<{+ budgeted: number;+ perTemplate: number[];+ } | null>(null);++ const onAddAutomation = (create?: () => AutomationEntry) => {+ const fallback = getAutomationExamples().find(+ e => e.displayType === 'fixed',+ );+ const entry = (create ?? fallback?.create)?.();+ if (!entry) return;+ setEntries(prev => {+ const next = [...prev, entry];+ setActive({ kind: 'entry', idx: next.length - 1 });+ return next;+ });+ };++ const onAddLimitAutomation = () => {+ const entry = createAutomationEntry(+ {+ directive: 'template',+ type: 'limit',+ amount: 500,+ period: 'monthly',+ hold: false,+ priority: null,+ },+ 'limit',+ );+ setEntries(prev => {+ const next = [...prev, entry];+ setActive({ kind: 'entry', idx: next.length - 1 });+ return next;+ });+ };++ const onAddGoalAutomation = () => {+ const entry = createAutomationEntry(+ {+ directive: 'goal',+ type: 'goal',+ amount: 1000,+ },+ 'goal',+ );+ setEntries(prev => {+ const next = [...prev, entry];+ setActive({ kind: 'entry', idx: next.length - 1 });+ return next;+ });+ };++ const onAddCleanup = () => {+ if (!isCleanupConfigured(cleanup)) setCleanup(emptyCleanupConfig());+ setActive({ kind: 'cleanup' });+ };++ const onDeleteCleanup = () => {+ setCleanup(emptyCleanupConfig());+ setActive({ kind: 'entry', idx: 0 });+ };++ const onDelete = (index: number) => {+ setEntries(prev => {+ const next = prev.filter((_, i) => i !== index);+ setActive(currentActive => {+ if (currentActive.kind !== 'entry') return currentActive;+ if (next.length === 0) return { kind: 'entry', idx: 0 };+ const idx = currentActive.idx;+ if (idx >= next.length) return { kind: 'entry', idx: next.length - 1 };+ if (idx > index) return { kind: 'entry', idx: idx - 1 };+ return currentActive;+ });+ return next;+ });+ };++ const onSave = async () => {+ if (saving) return;+ setSaving(true);+ try {+ const templatesToSave = entries.map(({ template }) => template);+ await send('budget/set-category-automations', {+ categoriesWithTemplates: [+ {+ id: categoryId,+ templates: templatesToSave,+ cleanup: editorToCleanupDef(cleanup),+ },+ ],+ source: 'ui',+ });+ onClose();+ } finally {+ setSaving(false);+ }+ };++ const onUnmigrate = () => {+ dispatch(+ pushModal({+ modal: {+ name: 'category-automations-unmigrate',+ options: {+ categoryId,+ templates: entries.map(({ template }) => template),+ cleanup: editorToCleanupDef(cleanup),+ },+ },+ }),+ );+ };++ // the react compiler wasn't memoising this properly and causing infinite+ // re-renders+ const templates = useMemo(() => entries.map(e => e.template), [entries]);++ const validPercentageSources = new Set<string>([+ 'all income',+ 'available funds',+ ]);+ for (const group of categories) {+ for (const cat of group.categories ?? []) {+ if (!cat.is_income) continue;+ validPercentageSources.add(cat.id);+ if (cat.name) validPercentageSources.add(cat.name.toLowerCase());+ }+ }++ const automationErrors = entries.map(entry =>+ validateAutomation(+ entry.template,+ entry.displayType,+ templates,+ schedules,+ new Date(),+ validPercentageSources,+ ),+ );++ useEffect(() => {+ if (templates.length === 0) {+ setDryRun({ budgeted: 0, perTemplate: [] });+ return;+ }+ let cancelled = false;+ const run = debounce(async () => {+ try {+ const result = await send('budget/dry-run-category-template', {+ month,+ categoryId,+ templates,+ });+ if (!cancelled) setDryRun(result);+ } catch {+ if (!cancelled) setDryRun(null);+ }+ }, 200);+ void run();+ return () => {+ cancelled = true;+ run.cancel();+ };+ }, [templates, month, categoryId]);++ const totalMonthly = dryRun?.budgeted ?? 0;+ const contributions: (number | null)[] = entries.map((_, i) =>+ dryRun?.perTemplate?.[i] != null ? dryRun.perTemplate[i] : null,+ );+ const hasErrors = automationErrors.some(error => error !== null);+ const conflicts = [+ validatePercentageAllocation(templates),+ validateSchedulePriorities(templates),+ ].filter(conflict => conflict !== null);++ const categoryNameMap: Record<string, string> = {};+ for (const group of categories) {+ for (const cat of group.categories ?? []) {+ categoryNameMap[cat.id] = cat.name;+ }+ }++ const hasLimitAutomation = entries.some(e => e.displayType === 'limit');+ const hasGoalAutomation = entries.some(e => e.displayType === 'goal');++ const isOption = (entry: AutomationEntry) =>+ entry.displayType === 'limit' || entry.displayType === 'goal';+ const indexedEntries = entries.map((entry, idx) => ({ entry, idx }));+ const contributionEntries = indexedEntries.filter(+ ({ entry }) => !isOption(entry),+ );+ const optionEntries = indexedEntries.filter(({ entry }) => isOption(entry));++ const safeActiveIdx =+ active.kind === 'entry'+ ? Math.min(active.idx, Math.max(0, entries.length - 1))+ : -1;+ const cleanupActive = active.kind === 'cleanup';++ return {+ entries,+ setEntries,+ cleanup,+ setCleanup,+ active,+ setActive,+ saving,+ onAddAutomation,+ onAddLimitAutomation,+ onAddGoalAutomation,+ onAddCleanup,+ onDeleteCleanup,+ onDelete,+ onSave,+ onUnmigrate,+ cleanupGroups,+ createCleanupGroup,+ automationErrors,+ totalMonthly,+ contributions,+ hasErrors,+ conflicts,+ categoryNameMap,+ hasLimitAutomation,+ hasGoalAutomation,+ indexedEntries,+ contributionEntries,+ optionEntries,+ safeActiveIdx,+ cleanupActive,+ };+}diff --git a/packages/desktop-client/src/components/modals/CategoryMenuModal.tsx b/packages/desktop-client/src/components/modals/CategoryMenuModal.tsxindex 5c401892bc..65f8926c40 100644--- a/packages/desktop-client/src/components/modals/CategoryMenuModal.tsx+++ b/packages/desktop-client/src/components/modals/CategoryMenuModal.tsx@@ -5,6 +5,7 @@ import { Trans, useTranslation } from 'react-i18next';import { Button } from '@actual-app/components/button';import {+ SvgChartPie,SvgDotsHorizontalTriple,SvgTrash,} from '@actual-app/components/icons/v1';@@ -42,6 +43,7 @@ export function CategoryMenuModal({onEditNotes,onDelete,onToggleVisibility,+ onEditAutomations,onClose,}: CategoryMenuModalProps) {const { t } = useTranslation();@@ -70,6 +72,10 @@ export function CategoryMenuModal({onDelete?.(category.id);};+ const _onEditAutomations = () => {+ onEditAutomations?.(category.id);+ };+const buttonStyle: CSSProperties = {...styles.mediumText,height: styles.mobileMinHeight,@@ -140,6 +146,7 @@ export function CategoryMenuModal({flexWrap: 'wrap',justifyContent: 'space-between',alignContent: 'space-between',+ gap: 8,paddingTop: 10,}}>@@ -151,6 +158,16 @@ export function CategoryMenuModal({/><Trans>Edit notes</Trans></Button>+ {onEditAutomations && (+ <Button style={buttonStyle} onPress={_onEditAutomations}>+ <SvgChartPie+ width={20}+ height={20}+ style={{ paddingRight: 5 }}+ />+ <Trans>Budget automations</Trans>+ </Button>+ )}</View></View></>diff --git a/packages/desktop-client/src/components/select/DateSelect.tsx b/packages/desktop-client/src/components/select/DateSelect.tsxindex 3f799fbfb8..4ee71cc70c 100644--- a/packages/desktop-client/src/components/select/DateSelect.tsx+++ b/packages/desktop-client/src/components/select/DateSelect.tsx@@ -458,6 +458,7 @@ function DateSelectDesktop({}function DateSelectMobile(props: DateSelectProps) {+ const { style: inputStyle, ...restInputProps } = props.inputProps ?? {};return (<InputFieldid={props.id}@@ -466,8 +467,8 @@ function DateSelectMobile(props: DateSelectProps) {onChange={event => {props.onSelect(event.target.value);}}- style={{ height: 28 }}- {...props.inputProps}+ style={{ height: 28, ...inputStyle }}+ {...restInputProps}/>);}diff --git a/packages/desktop-client/src/components/util/GenericInput.tsx b/packages/desktop-client/src/components/util/GenericInput.tsxindex 6d0832b645..d49b863bbe 100644--- a/packages/desktop-client/src/components/util/GenericInput.tsx+++ b/packages/desktop-client/src/components/util/GenericInput.tsx@@ -19,6 +19,7 @@ import { FilterAutocomplete } from '#components/autocomplete/FilterAutocomplete'import { PayeeAutocomplete } from '#components/autocomplete/PayeeAutocomplete';import { ReportAutocomplete } from '#components/autocomplete/ReportAutocomplete';import { Checkbox } from '#components/forms';+import { hideNativeDateIconClassName } from '#components/mobile/MobileForms';import { DateSelect } from '#components/select/DateSelect';import { RecurringSchedulePicker } from '#components/select/RecurringSchedulePicker';import { useCategories } from '#hooks/useCategories';@@ -407,7 +408,19 @@ export const GenericInput = ({value={props.value}dateFormat={dateFormat}openOnFocus={false}- inputProps={{ placeholder: dateFormat.toLowerCase() }}+ inputProps={{+ placeholder: dateFormat.toLowerCase(),+ className: hideNativeDateIconClassName,+ style: {+ marginLeft: 0,+ marginRight: 0,+ // ios renders native date inputs taller than other fields;+ // border-box + appearance reset bring it back in line+ boxSizing: 'border-box',+ WebkitAppearance: 'none',+ appearance: 'none',+ },+ }}onSelect={props.onChange}/>);diff --git a/packages/desktop-client/src/components/util/PercentInput.tsx b/packages/desktop-client/src/components/util/PercentInput.tsxindex 8a9761bbd6..38959569ff 100644--- a/packages/desktop-client/src/components/util/PercentInput.tsx+++ b/packages/desktop-client/src/components/util/PercentInput.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useRef, useState } from 'react';+import { useEffect, useRef, useState } from 'react';import type { CSSProperties, FocusEvent, FocusEventHandler, Ref } from 'react';import { Input } from '@actual-app/components/input';@@ -39,16 +39,19 @@ export function PercentInput({}: PercentInputProps) {const format = useFormat();+ const [isFocused, setIsFocused] = useState(focused ?? false);const [value, setValue] = useState(() =>format(clampToPercent(initialValue, max), 'percentage'),);+useEffect(() => {- const clampedInitialValue = clampToPercent(initialValue, max);- if (clampedInitialValue !== initialValue) {- setValue(format(clampedInitialValue, 'percentage'));- onUpdatePercent?.(clampedInitialValue);+ const clamped = clampToPercent(initialValue, max);+ if (clamped !== initialValue) {+ onUpdatePercent?.(clamped);}- }, [initialValue, max, onUpdatePercent, format]);+ // drop the symbol while editing so the value can be edited freely+ setValue(isFocused ? String(clamped) : format(clamped, 'percentage'));+ }, [initialValue, max, isFocused, onUpdatePercent, format]);const ref = useRef<HTMLInputElement>(null);const mergedRef = useMergedRefs<HTMLInputElement>(inputRef, ref);@@ -59,43 +62,31 @@ export function PercentInput({}}, [focused]);- function onSelectionChange() {- if (!ref.current) {- return;- }-- const selectionStart = ref.current.selectionStart;- const selectionEnd = ref.current.selectionEnd;- if (- selectionStart === selectionEnd &&- selectionStart !== null &&- selectionStart >= ref.current.value.length- ) {- ref.current.setSelectionRange(- ref.current.value.length - 1,- ref.current.value.length - 1,- );- }- }-function onInputTextChange(val: string) {const number = val.replace(/[^0-9.]/g, '');- setValue(number ? format(number, 'percentage') : '');+ setValue(number);onChangeValue?.(number);}function fireUpdate() {- const clampedValue = clampToPercent(+ const clamped = clampToPercent(evalArithmetic(value.replace('%', ''), 0) ?? 0,max,);- onUpdatePercent?.(clampedValue);- onInputTextChange(String(clampedValue));+ onUpdatePercent?.(clamped);+ return clamped;+ }++ function onInputFocus(e: FocusEvent<HTMLInputElement>) {+ setIsFocused(true);+ onFocus?.(e);}- function onInputAmountBlur(e: FocusEvent<HTMLInputElement>) {+ function onInputBlur(e: FocusEvent<HTMLInputElement>) {if (!ref.current?.contains(e.relatedTarget)) {- fireUpdate();+ const clamped = fireUpdate();+ setIsFocused(false);+ setValue(format(clamped, 'percentage'));}onBlur?.(e);}@@ -110,9 +101,8 @@ export function PercentInput({style={{ flex: 1, alignItems: 'stretch', ...style }}onEnter={fireUpdate}onChangeValue={onInputTextChange}- onBlur={onInputAmountBlur}- onFocus={onFocus}- onSelect={onSelectionChange}+ onBlur={onInputBlur}+ onFocus={onInputFocus}/>);}diff --git a/packages/desktop-client/src/modals/modalsSlice.ts b/packages/desktop-client/src/modals/modalsSlice.tsindex 611b500287..510def197e 100644--- a/packages/desktop-client/src/modals/modalsSlice.ts+++ b/packages/desktop-client/src/modals/modalsSlice.ts@@ -364,6 +364,7 @@ export type Modal =onEditNotes: (id: NoteEntity['id']) => void;onDelete: (categoryId: CategoryEntity['id']) => void;onToggleVisibility: (categoryId: CategoryEntity['id']) => void;+ onEditAutomations?: (categoryId: CategoryEntity['id']) => void;onClose?: () => void;};}diff --git a/upcoming-release-notes/8099.md b/upcoming-release-notes/8099.mdnew file mode 100644index 0000000000..bff331655d--- /dev/null+++ b/upcoming-release-notes/8099.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [matt-fidd]+---++Automation UI: add mobile support