Skip to content

A local-first personal finance app

Replace mobile amount input with calculator (#8200)

Timb7ea5503a431
diff --git a/packages/component-library/src/Input.tsx b/packages/component-library/src/Input.tsx
index 9ca1f4f3ad..553f8117a2 100644
--- a/packages/component-library/src/Input.tsx
+++ b/packages/component-library/src/Input.tsx
@@ -23,7 +23,7 @@ export const baseInputStyle = {
border: '1px solid ' + theme.formInputBorder,
};
-const defaultInputClassName = css({
+export const defaultInputClassName = css({
...baseInputStyle,
color: theme.formInputText,
whiteSpace: 'nowrap',
diff --git a/packages/desktop-client/src/components/common/CalculatorButtons.test.tsx b/packages/desktop-client/src/components/common/CalculatorButtons.test.tsx
new file mode 100644
index 0000000000..2348026d85
--- /dev/null
+++ b/packages/desktop-client/src/components/common/CalculatorButtons.test.tsx
@@ -0,0 +1,134 @@
+import React, { useRef, useState } from 'react';
+
+import { evalArithmetic } from '@actual-app/core/shared/arithmetic';
+import { fireEvent, render, screen } from '@testing-library/react';
+
+import { CalculatorButtons } from './CalculatorButtons';
+
+function TestCalculator({ initialValue = '' }: { initialValue?: string }) {
+ const [value, setValue] = useState(initialValue);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ return (
+ <>
+ <input
+ ref={inputRef}
+ aria-label="Expression"
+ value={value}
+ onChange={event => setValue(event.target.value)}
+ />
+ <CalculatorButtons
+ inputRef={inputRef}
+ onClear={() => {
+ setValue('');
+ }}
+ onEquals={() => {
+ setValue(evalArithmetic(value)?.toString() ?? '');
+ }}
+ />
+ </>
+ );
+}
+
+describe('CalculatorButtons', () => {
+ it('updates a controlled external input from keypad actions', () => {
+ render(<TestCalculator />);
+
+ const input = screen.getByLabelText('Expression');
+
+ input.focus();
+
+ fireEvent.click(screen.getByRole('button', { name: '1' }));
+ fireEvent.click(screen.getByRole('button', { name: '2' }));
+ fireEvent.click(screen.getByRole('button', { name: '+' }));
+ fireEvent.click(screen.getByRole('button', { name: '3' }));
+ expect(input).toHaveValue('12+3');
+ expect(input).toHaveFocus();
+ expect(input).toHaveProperty('selectionStart', '12+3'.length);
+ expect(input).toHaveProperty('selectionEnd', '12+3'.length);
+
+ fireEvent.click(screen.getByRole('button', { name: '\u232B' }));
+ expect(input).toHaveValue('12+');
+ expect(input).toHaveFocus();
+ expect(input).toHaveProperty('selectionStart', '12+'.length);
+ expect(input).toHaveProperty('selectionEnd', '12+'.length);
+
+ fireEvent.click(screen.getByRole('button', { name: '3' }));
+ fireEvent.click(screen.getByRole('button', { name: '=' }));
+ expect(input).toHaveValue('15');
+ expect(input).toHaveFocus();
+ expect(input).toHaveProperty('selectionStart', '15'.length);
+ expect(input).toHaveProperty('selectionEnd', '15'.length);
+
+ fireEvent.click(screen.getByRole('button', { name: 'AC' }));
+ expect(input).toHaveValue('');
+ expect(input).toHaveFocus();
+ expect(input).toHaveProperty('selectionStart', 0);
+ expect(input).toHaveProperty('selectionEnd', 0);
+ });
+
+ it('inserts and deletes at the current caret position', () => {
+ render(<TestCalculator initialValue="123" />);
+
+ const input = screen.getByLabelText('Expression');
+
+ if (!(input instanceof HTMLInputElement)) {
+ throw new Error('Expected expression to be an input');
+ }
+
+ input.focus();
+ input.setSelectionRange(1, 1);
+
+ fireEvent.click(screen.getByRole('button', { name: '0' }));
+ expect(input).toHaveValue('1023');
+ expect(input).toHaveFocus();
+ expect(input).toHaveProperty('selectionStart', 2);
+ expect(input).toHaveProperty('selectionEnd', 2);
+
+ fireEvent.click(screen.getByRole('button', { name: '\u232B' }));
+ expect(input).toHaveValue('123');
+ expect(input).toHaveFocus();
+ expect(input).toHaveProperty('selectionStart', 1);
+ expect(input).toHaveProperty('selectionEnd', 1);
+
+ input.setSelectionRange(1, 3);
+ fireEvent.click(screen.getByRole('button', { name: '9' }));
+ expect(input).toHaveValue('19');
+ expect(input).toHaveFocus();
+ expect(input).toHaveProperty('selectionStart', 2);
+ expect(input).toHaveProperty('selectionEnd', 2);
+ });
+
+ it('restores input focus when a keypad press starts after blur', () => {
+ render(<TestCalculator initialValue="1+2" />);
+
+ const input = screen.getByLabelText('Expression');
+
+ if (!(input instanceof HTMLInputElement)) {
+ throw new Error('Expected expression to be an input');
+ }
+
+ input.focus();
+ input.setSelectionRange(input.value.length, input.value.length);
+ input.blur();
+
+ fireEvent.click(screen.getByRole('button', { name: '3' }));
+
+ expect(input).toHaveValue('1+23');
+ expect(input).toHaveFocus();
+
+ input.blur();
+
+ fireEvent.click(screen.getByRole('button', { name: '=' }));
+
+ expect(input).toHaveValue('24');
+ expect(input).toHaveFocus();
+
+ input.blur();
+
+ fireEvent.click(screen.getByRole('button', { name: 'AC' }));
+
+ expect(input).toHaveValue('');
+ expect(input).toHaveFocus();
+ });
+});
diff --git a/packages/desktop-client/src/components/common/CalculatorButtons.tsx b/packages/desktop-client/src/components/common/CalculatorButtons.tsx
new file mode 100644
index 0000000000..cf75d29a08
--- /dev/null
+++ b/packages/desktop-client/src/components/common/CalculatorButtons.tsx
@@ -0,0 +1,311 @@
+import React from 'react';
+import type { ReactNode, RefObject } from 'react';
+
+import { Button } from '@actual-app/components/button';
+import type { CSSProperties } from '@actual-app/components/styles';
+import { theme } from '@actual-app/components/theme';
+import { View } from '@actual-app/components/view';
+
+export function CalculatorButtons({
+ inputRef,
+ style,
+ onInteractionStart,
+ ...props
+}: {
+ readonly inputRef: RefObject<HTMLInputElement | null>;
+ readonly onClear: () => void;
+ readonly onEquals: () => void;
+ readonly onInteractionStart?: () => void;
+ readonly style?: CSSProperties;
+}) {
+ const focusInputAt = (position: number) => {
+ const input = inputRef.current;
+
+ if (!input) {
+ return;
+ }
+
+ input.focus({ preventScroll: true });
+ input.setSelectionRange(position, position);
+ };
+
+ const focusInput = () => {
+ inputRef.current?.focus({ preventScroll: true });
+ };
+
+ const getSelection = () => {
+ const input = inputRef.current;
+ const currentExpression = input?.value ?? '';
+ const start = input?.selectionStart ?? currentExpression.length;
+ const end = input?.selectionEnd ?? start;
+
+ return { currentExpression, start, end };
+ };
+
+ const updateExpression = (nextExpression: string, caretPosition: number) => {
+ const input = inputRef.current;
+
+ if (!input) {
+ return;
+ }
+
+ setNativeInputValue(input, nextExpression);
+ focusInputAt(caretPosition);
+ };
+
+ const insertExpression = (value: string) => {
+ const { currentExpression, start, end } = getSelection();
+
+ updateExpression(
+ currentExpression.slice(0, start) + value + currentExpression.slice(end),
+ start + value.length,
+ );
+ };
+
+ const backspace = () => {
+ const { currentExpression, start, end } = getSelection();
+
+ if (start !== end) {
+ updateExpression(
+ currentExpression.slice(0, start) + currentExpression.slice(end),
+ start,
+ );
+ return;
+ }
+
+ if (start === 0) {
+ updateExpression(currentExpression, start);
+ return;
+ }
+
+ updateExpression(
+ currentExpression.slice(0, start - 1) + currentExpression.slice(start),
+ start - 1,
+ );
+ };
+
+ return (
+ <View style={{ ...style, gap: 12 }}>
+ <View
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'repeat(4, 1fr)',
+ gridTemplateRows: 'repeat(5, 1fr)',
+ gap: 6,
+ height: '100%',
+ }}
+ >
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ focusInput();
+ props.onClear();
+ }}
+ >
+ AC
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('(');
+ }}
+ >
+ (
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression(')');
+ }}
+ >
+ )
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('/');
+ }}
+ >
+ {'\u00F7'}
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('7');
+ }}
+ >
+ 7
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('8');
+ }}
+ >
+ 8
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('9');
+ }}
+ >
+ 9
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('*');
+ }}
+ >
+ {'\u00D7'}
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('4');
+ }}
+ >
+ 4
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('5');
+ }}
+ >
+ 5
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('6');
+ }}
+ >
+ 6
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('-');
+ }}
+ >
+ -
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('1');
+ }}
+ >
+ 1
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('2');
+ }}
+ >
+ 2
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('3');
+ }}
+ >
+ 3
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('+');
+ }}
+ >
+ +
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ backspace();
+ }}
+ >
+ {'\u232B'}
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('0');
+ }}
+ >
+ 0
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ insertExpression('.');
+ }}
+ >
+ .
+ </CalculatorButton>
+ <CalculatorButton
+ onInteractionStart={onInteractionStart}
+ onPress={() => {
+ focusInput();
+ props.onEquals();
+ }}
+ >
+ =
+ </CalculatorButton>
+ </View>
+ </View>
+ );
+}
+
+function CalculatorButton({
+ onPress,
+ onInteractionStart,
+ children,
+ size = 20,
+}: {
+ onPress: () => void;
+ onInteractionStart?: () => void;
+ children: ReactNode;
+ size?: number;
+}) {
+ return (
+ <Button
+ variant="normal"
+ onPointerDown={e => {
+ e.preventDefault();
+ onInteractionStart?.();
+ if ('vibrate' in navigator) {
+ navigator.vibrate(3);
+ }
+ }}
+ onPress={onPress}
+ style={{
+ background: theme.pillBackground,
+ border: 0,
+ color: theme.pillText,
+ fontSize: size,
+ fontWeight: 600,
+ touchAction: 'manipulation',
+ }}
+ >
+ {children}
+ </Button>
+ );
+}
+
+function setNativeInputValue(input: HTMLInputElement, value: string) {
+ // Use the native setter so React-controlled inputs receive the change.
+ // oxlint-disable-next-line typescript-eslint/unbound-method
+ const nativeSetter = Object.getOwnPropertyDescriptor(
+ window.HTMLInputElement.prototype,
+ 'value',
+ )?.set;
+
+ nativeSetter?.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+}
diff --git a/packages/desktop-client/src/components/common/Modal.tsx b/packages/desktop-client/src/components/common/Modal.tsx
index 3ede8c91ae..89ff08b49a 100644
--- a/packages/desktop-client/src/components/common/Modal.tsx
+++ b/packages/desktop-client/src/components/common/Modal.tsx
@@ -40,6 +40,9 @@ type ModalProps = ComponentPropsWithRef<typeof ReactAriaModal> & {
noAnimation?: boolean;
style?: CSSProperties;
onClose?: () => void;
+ wrapperProps?: {
+ style?: CSSProperties;
+ };
containerProps?: {
style?: CSSProperties;
};
@@ -52,6 +55,7 @@ export const Modal = ({
style,
children,
onClose,
+ wrapperProps,
containerProps,
...props
}: ModalProps) => {
@@ -104,6 +108,7 @@ export const Modal = ({
justifyContent: 'center',
height: 'var(--visual-viewport-height)',
overflowY: 'auto',
+ ...wrapperProps?.style,
}}
>
<ReactAriaModal>
diff --git a/packages/desktop-client/src/components/mobile/transactions/AmountInput.tsx b/packages/desktop-client/src/components/mobile/transactions/AmountInput.tsx
new file mode 100644
index 0000000000..ad68ef8510
--- /dev/null
+++ b/packages/desktop-client/src/components/mobile/transactions/AmountInput.tsx
@@ -0,0 +1,100 @@
+import { memo, useEffect, useState } from 'react';
+import type { FocusEvent } from 'react';
+
+import { styles } from '@actual-app/components/styles';
+import * as Platform from '@actual-app/core/shared/platform';
+
+import { useFeatureFlag } from '#hooks/useFeatureFlag';
+
+import { CalculatorAmountInput } from './CalculatorAmountInput';
+import type { CalculatorAmountInputProps } from './CalculatorAmountInput';
+import { FocusableAmountInput } from './FocusableAmountInput';
+
+export type AmountInputProps = Omit<CalculatorAmountInputProps, 'onFocus'> & {
+ disableNativeAutoFocusOnIOS?: boolean;
+ onFocus?: (event?: FocusEvent<HTMLInputElement>) => void;
+};
+
+export const AmountInput = memo(function AmountInput({
+ autoFocus = false,
+ disableNativeAutoFocusOnIOS = false,
+ disabled,
+ inputRef,
+ negate = false,
+ onBlur,
+ onChange,
+ onEnter,
+ onFocus,
+ value,
+ variant = 'normal',
+ ...props
+}: AmountInputProps) {
+ const mobileCalculatorEnabled = useFeatureFlag('mobileCalculator');
+ const fallbackAutoFocus =
+ autoFocus && !(disableNativeAutoFocusOnIOS && Platform.isIOSAgent);
+ const [focused, setFocused] = useState(fallbackAutoFocus);
+
+ useEffect(() => {
+ if (fallbackAutoFocus) {
+ setFocused(true);
+ }
+ }, [fallbackAutoFocus]);
+
+ if (mobileCalculatorEnabled) {
+ return (
+ <CalculatorAmountInput
+ {...props}
+ autoFocus={autoFocus}
+ autoFocusIndirect={disableNativeAutoFocusOnIOS}
+ disabled={disabled}
+ inputRef={inputRef}
+ negate={negate}
+ onBlur={onBlur}
+ onChange={onChange}
+ onEnter={onEnter}
+ onFocus={onFocus}
+ value={value}
+ variant={variant}
+ />
+ );
+ }
+
+ return (
+ <FocusableAmountInput
+ {...props}
+ disabled={disabled}
+ focused={focused}
+ inputRef={inputRef}
+ onBlur={event => {
+ setFocused(false);
+ onBlur?.(event);
+ }}
+ onEnter={() => onEnter?.()}
+ onFocus={event => {
+ setFocused(true);
+ onFocus?.(event);
+ }}
+ onUpdateAmount={onChange}
+ sign={value === 0 ? undefined : value < 0 ? '-' : '+'}
+ focusedStyle={
+ variant === 'large'
+ ? {
+ width: 'auto',
+ padding: '5px',
+ paddingLeft: '20px',
+ paddingRight: '20px',
+ minWidth: '100%',
+ }
+ : undefined
+ }
+ style={props.style}
+ textStyle={
+ variant === 'large'
+ ? { ...styles.veryLargeText, textAlign: 'center' }
+ : undefined
+ }
+ value={value}
+ zeroSign={negate ? '-' : '+'}
+ />
+ );
+});
diff --git a/packages/desktop-client/src/components/mobile/transactions/CalculatorAmountInput.tsx b/packages/desktop-client/src/components/mobile/transactions/CalculatorAmountInput.tsx
new file mode 100644
index 0000000000..688459f69b
--- /dev/null
+++ b/packages/desktop-client/src/components/mobile/transactions/CalculatorAmountInput.tsx
@@ -0,0 +1,282 @@
+import React, {
+ memo,
+ useCallback,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from 'react';
+import type { CSSProperties, FocusEvent, ReactNode, RefObject } from 'react';
+
+import { defaultInputClassName } from '@actual-app/components/input';
+import { styles } from '@actual-app/components/styles';
+import { theme } from '@actual-app/components/theme';
+import { evalArithmetic } from '@actual-app/core/shared/arithmetic';
+import { isIOS } from '@actual-app/core/shared/platform';
+import { amountToCurrency } from '@actual-app/core/shared/util';
+import { css, cx } from '@emotion/css';
+
+import { makeAmountFullStyle } from '#components/budget/util';
+
+import { CalculatorKeyboard } from './CalculatorKeyboard';
+
+export const calculatorAmountLargeStyle = {
+ ...styles.veryLargeText,
+ backgroundColor: 'transparent',
+ border: 0,
+ borderBottom: '1px solid',
+ borderBottomColor: theme.formInputBorder,
+ display: 'block',
+ fieldSizing: 'content',
+ minWidth: '80px',
+ maxWidth: '100%',
+ outline: 0,
+ padding: 0,
+ textAlign: 'center',
+};
+
+export const calculatorAmountNormalStyle = {
+ boxShadow: 'none',
+ fontSize: 14,
+ outline: 0,
+ height: styles.mobileMinHeight,
+};
+
+export type CalculatorAmountInputProps = {
+ value: number;
+ variant?: 'normal' | 'large';
+ negate?: boolean;
+ style?: CSSProperties;
+ inputRef?: RefObject<HTMLInputElement | null>;
+ keyboardHeader?: ReactNode;
+ onEnter?: () => void;
+ onChange?: (value: number) => void;
+ onFocus?: (event: FocusEvent<HTMLInputElement>) => void;
+ onBlur?: (event: FocusEvent<HTMLInputElement>) => void;
+ autoFocus?: boolean;
+ autoFocusDelay?: number;
+ autoFocusIndirect?: boolean;
+ disabled?: boolean;
+};
+
+const placeholderClassName = css({
+ '&[data-focused]::placeholder': {
+ color: 'transparent',
+ },
+ '::placeholder': { color: theme.pageTextSubdued },
+});
+
+export const CalculatorAmountInput = memo(function CalculatorAmountInput({
+ value,
+ style,
+ onChange,
+ onFocus,
+ onBlur,
+ negate = false,
+ autoFocus = false,
+ autoFocusDelay,
+ autoFocusIndirect = false,
+ onEnter,
+ variant = 'normal',
+ keyboardHeader,
+ ...props
+}: CalculatorAmountInputProps) {
+ const internalInputRef = useRef<HTMLInputElement>(null);
+ const inputRef = props.inputRef ?? internalInputRef;
+ const [iosInitialInteraction, setIosInitialInteraction] = useState(
+ isIOS ? !(autoFocusIndirect && value === 0) : true,
+ );
+
+ const [liveValue, setLiveValue] = useState(() => value);
+ const [expression, setExpression] = useState(() => formatAmount(liveValue));
+ const valueIsNegative = () =>
+ isNegativeAmount(negate && value === 0 ? -value : value);
+ const isNegative = useRef(valueIsNegative());
+
+ const blurRef = useRef<HTMLDivElement>(null);
+ const [focused, setFocused] = useState(false);
+ const isKeepingFocusRef = useRef(false);
+ const keepFocusTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(
+ null,
+ );
+ const keepFocus = useCallback(() => {
+ isKeepingFocusRef.current = true;
+ if (keepFocusTimeoutRef.current) {
+ clearTimeout(keepFocusTimeoutRef.current);
+ }
+ keepFocusTimeoutRef.current = setTimeout(() => {
+ inputRef.current?.focus();
+ isKeepingFocusRef.current = false;
+ }, 200);
+ }, [inputRef]);
+ const stopKeepFocus = useCallback(() => {
+ isKeepingFocusRef.current = false;
+ if (keepFocusTimeoutRef.current) {
+ clearTimeout(keepFocusTimeoutRef.current);
+ }
+ }, []);
+
+ const onInputFocus = useCallback(() => {
+ if (isKeepingFocusRef.current) {
+ return;
+ }
+
+ if (negate && isNegative.current) {
+ setExpression(formatAmount(-value));
+ }
+ setTimeout(() => {
+ const input = inputRef.current;
+ if (!input) return;
+ input.setSelectionRange(input.value.length, input.value.length);
+ }, 0);
+
+ setFocused(true);
+ }, [inputRef, setExpression, negate, isNegative, value, setFocused]);
+
+ const onInputBlur = useCallback(() => {
+ if (isKeepingFocusRef.current) {
+ inputRef.current?.focus();
+ return false;
+ }
+
+ setFocused(false);
+ setExpression(formatAmount(liveValue));
+ if (value === liveValue) {
+ return true;
+ }
+ onChange?.(liveValue);
+ return true;
+ }, [setExpression, value, liveValue, onChange, inputRef]);
+
+ const onChangeAmount = useCallback(
+ (amount: number) => {
+ setLiveValue(amount);
+ setExpression(formatAmount(negate ? Math.abs(amount) : amount));
+ },
+ [setExpression, setLiveValue, negate],
+ );
+
+ const onChangeExpression = useCallback(
+ (text: string) => {
+ setIosInitialInteraction(true);
+
+ setExpression(text);
+ const amount = text.trim() === '' ? 0 : evalArithmetic(text);
+ if (amount === null) {
+ return;
+ }
+ setLiveValue(negate && isNegative.current ? -amount : amount);
+ },
+ [setExpression, setLiveValue, setIosInitialInteraction, negate, isNegative],
+ );
+
+ const valueRef = useRef(value);
+ if (value !== valueRef.current) {
+ valueRef.current = value;
+ isNegative.current = valueIsNegative();
+ setLiveValue(value);
+ setExpression(formatAmount(value));
+ }
+
+ useLayoutEffect(() => {
+ if (autoFocus) {
+ inputRef.current?.focus();
+ }
+ }, [inputRef, autoFocus]);
+
+ return (
+ <>
+ <div ref={blurRef} tabIndex={-1} />
+ <input
+ ref={inputRef}
+ data-testid="amount-input"
+ type="text"
+ value={expression}
+ placeholder="0.00"
+ onChange={e => onChangeExpression(e.target.value)}
+ onFocus={e => {
+ onInputFocus();
+ onFocus?.(e);
+ }}
+ onBlur={e => {
+ if (onInputBlur()) {
+ onBlur?.(e);
+ }
+ }}
+ inputMode="none"
+ autoCapitalize="none"
+ className={cx(
+ variant === 'normal' && defaultInputClassName,
+ placeholderClassName,
+ )}
+ style={{
+ ...makeAmountFullStyle(liveValue, {
+ positiveColor: theme.numberPositive,
+ negativeColor: theme.numberNegative,
+ zeroColor: theme.pageTextSubdued,
+ }),
+ scrollMarginTop: 100,
+ ...(variant === 'large'
+ ? calculatorAmountLargeStyle
+ : calculatorAmountNormalStyle),
+ ...style,
+ }}
+ disabled={props.disabled}
+ {...{
+ ...(focused &&
+ iosInitialInteraction && {
+ 'data-focused': true,
+ }),
+ ...(props.disabled && {
+ 'data-disabled': true,
+ }),
+ }}
+ />
+
+ <CalculatorKeyboard
+ inputRef={inputRef}
+ header={keyboardHeader}
+ isOpen={focused}
+ initialTransitionDelay={autoFocusDelay}
+ onInteractionStart={keepFocus}
+ onEquals={() => {
+ onChangeAmount(liveValue);
+ if (negate) {
+ isNegative.current = isNegativeAmount(liveValue);
+ }
+ }}
+ onClear={() => {
+ onChangeExpression('');
+ }}
+ onToggleSign={() => {
+ isNegative.current = !isNegative.current;
+ onChangeAmount(-liveValue);
+ }}
+ onReset={() => {
+ onChangeAmount(value);
+ isNegative.current = valueIsNegative();
+ }}
+ onDismiss={() => {
+ stopKeepFocus();
+ setLiveValue(value);
+ isNegative.current = valueIsNegative();
+ setTimeout(() => {
+ blurRef.current?.focus();
+ }, 0);
+ }}
+ onApply={() => {
+ stopKeepFocus();
+ blurRef.current?.focus();
+ onEnter?.();
+ }}
+ />
+ </>
+ );
+});
+
+function formatAmount(value: number) {
+ return value === 0 ? '' : amountToCurrency(value);
+}
+
+function isNegativeAmount(value: number) {
+ return value < 0 || Object.is(value, -0);
+}
diff --git a/packages/desktop-client/src/components/mobile/transactions/CalculatorKeyboard.tsx b/packages/desktop-client/src/components/mobile/transactions/CalculatorKeyboard.tsx
new file mode 100644
index 0000000000..5b972f5be3
--- /dev/null
+++ b/packages/desktop-client/src/components/mobile/transactions/CalculatorKeyboard.tsx
@@ -0,0 +1,162 @@
+import React, { memo, useEffect, useRef, useState } from 'react';
+import type { ReactNode, RefObject } from 'react';
+import { Trans } from 'react-i18next';
+
+import { Button } from '@actual-app/components/button';
+import { styles } from '@actual-app/components/styles';
+import { theme } from '@actual-app/components/theme';
+import { View } from '@actual-app/components/view';
+
+import { CalculatorButtons } from '#components/common/CalculatorButtons';
+
+export const CalculatorKeyboard = memo(function CalculatorAmountInput({
+ inputRef,
+ header,
+ isOpen,
+ initialTransitionDelay,
+ onToggleSign,
+ onEquals,
+ onClear,
+ onReset,
+ onDismiss,
+ onApply,
+ onInteractionStart,
+}: {
+ readonly inputRef: RefObject<HTMLInputElement | null>;
+ readonly header?: ReactNode;
+ readonly isOpen: boolean;
+ readonly initialTransitionDelay?: number;
+ readonly onEquals: () => void;
+ readonly onClear: () => void;
+ readonly onToggleSign: () => void;
+ readonly onReset: () => void;
+ readonly onDismiss: () => void;
+ readonly onApply: () => void;
+ readonly onInteractionStart: () => void;
+}) {
+ const initialTransitionRef = useRef(false);
+ const [isOpenDebounced, setIsOpenDebounced] = useState(false);
+
+ useEffect(() => {
+ if (isOpen === isOpenDebounced) return;
+
+ if (!initialTransitionRef.current && initialTransitionDelay) {
+ initialTransitionRef.current = true;
+ const handle = setTimeout(
+ () => setIsOpenDebounced(isOpen),
+ initialTransitionDelay,
+ );
+ return () => clearTimeout(handle);
+ }
+ setIsOpenDebounced(isOpen);
+ }, [isOpen, isOpenDebounced, initialTransitionDelay]);
+
+ return (
+ <View
+ style={{
+ background: theme.modalBackground,
+ borderColor: theme.tooltipBorder,
+ borderTopWidth: 1,
+ bottom: 0,
+ display: 'flex',
+ gap: 6,
+ height: '50dvh',
+ maxHeight: 400,
+ minHeight: 320,
+ left: 0,
+ overflow: 'visible',
+ position: 'fixed',
+ padding: 8,
+ paddingBottom: 'calc(20px + env(safe-area-inset-bottom))',
+ right: 0,
+ transform: isOpenDebounced ? 'translateY(0)' : 'translateY(100%)',
+ transitionProperty: 'transform',
+ transitionDuration: '100ms',
+ zIndex: 10,
+ ...styles.shadowLarge,
+ }}
+ >
+ {header}
+ <CalculatorButtons
+ style={{ flex: 1 }}
+ inputRef={inputRef}
+ onEquals={onEquals}
+ onClear={onClear}
+ onInteractionStart={onInteractionStart}
+ />
+ <View
+ style={{
+ display: 'flex',
+ flexDirection: 'row',
+ flexShrink: 0,
+ gap: 6,
+ }}
+ >
+ <NonFocusableButton
+ variant="normal"
+ onPress={onToggleSign}
+ onInteractionStart={onInteractionStart}
+ >
+ + / -
+ </NonFocusableButton>
+ <NonFocusableButton
+ variant="normal"
+ onPress={onReset}
+ onInteractionStart={onInteractionStart}
+ >
+ <Trans>Reset</Trans>
+ </NonFocusableButton>
+ <NonFocusableButton
+ variant="normal"
+ onPress={onDismiss}
+ data-testid="amount-dismiss"
+ >
+ <Trans>Dismiss</Trans>
+ </NonFocusableButton>
+ <NonFocusableButton
+ variant="primary"
+ onPress={onApply}
+ data-testid="amount-apply"
+ >
+ <Trans>Apply</Trans>
+ </NonFocusableButton>
+ </View>
+ </View>
+ );
+});
+
+const maybeVibrate = () => {
+ if ('vibrate' in navigator) {
+ navigator.vibrate(3);
+ }
+};
+
+function NonFocusableButton({
+ variant,
+ onPress,
+ onInteractionStart,
+ children,
+}: {
+ variant: 'primary' | 'normal';
+ onPress: () => void;
+ onInteractionStart?: () => void;
+ children: ReactNode;
+}) {
+ return (
+ <Button
+ variant={variant}
+ style={{
+ flex: 1,
+ height: styles.mobileMinHeight,
+ }}
+ onPointerDown={e => {
+ e.preventDefault();
+ onInteractionStart?.();
+ maybeVibrate();
+ }}
+ onPress={onPress}
+ >
+ {children}
+ </Button>
+ );
+}
diff --git a/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx b/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx
index 3b5d2574d6..100d3fdd3f 100644
--- a/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/FocusableAmountInput.tsx
@@ -2,6 +2,7 @@ import React, { memo, useEffect, useRef, useState } from 'react';
import type {
ComponentPropsWithRef,
CSSProperties,
+ FocusEvent,
HTMLProps,
Ref,
} from 'react';
@@ -166,7 +167,7 @@ const AmountInput = memo(function AmountInput({
);
});
-type FocusableAmountInputProps = Omit<AmountInputProps, 'onFocus'> & {
+export type FocusableAmountInputProps = Omit<AmountInputProps, 'onFocus'> & {
sign?: '+' | '-';
zeroSign?: '+' | '-';
focused?: boolean;
@@ -175,7 +176,7 @@ type FocusableAmountInputProps = Omit<AmountInputProps, 'onFocus'> & {
buttonProps?: Omit<ComponentPropsWithRef<typeof Button>, 'style'> & {
style?: EmotionCSSProperties;
};
- onFocus?: () => void;
+ onFocus?: (event?: FocusEvent<HTMLInputElement>) => void;
};
export const FocusableAmountInput = memo(function FocusableAmountInput({
@@ -272,7 +273,7 @@ export const FocusableAmountInput = memo(function FocusableAmountInput({
</Button>
)}
<Button
- onPress={onFocus}
+ onPress={() => onFocus?.()}
// Defines how far touch can start away from the button
// hitSlop={{ top: 5, bottom: 5, left: 5, right: 5 }}
{...buttonProps}
diff --git a/packages/desktop-client/src/components/mobile/transactions/SplitAmountInput.tsx b/packages/desktop-client/src/components/mobile/transactions/SplitAmountInput.tsx
new file mode 100644
index 0000000000..062283838c
--- /dev/null
+++ b/packages/desktop-client/src/components/mobile/transactions/SplitAmountInput.tsx
@@ -0,0 +1,98 @@
+import type { FocusEvent, ReactNode } from 'react';
+import { memo, useEffect, useState } from 'react';
+
+import { styles } from '@actual-app/components/styles';
+import { amountToInteger, integerToAmount } from '@actual-app/core/shared/util';
+
+import { AmountInput as LegacyAmountInput } from '#components/util/AmountInput';
+import { useFeatureFlag } from '#hooks/useFeatureFlag';
+import { useSyncedPref } from '#hooks/useSyncedPref';
+
+import { CalculatorAmountInput } from './CalculatorAmountInput';
+
+export type SplitAmountInputProps = {
+ value: number;
+ negate?: boolean;
+ onEnter?: () => void;
+ onChange?: (value: number) => void;
+ onFocus?: (event: FocusEvent<HTMLInputElement>) => void;
+ onBlur?: (event: FocusEvent<HTMLInputElement>) => void;
+ keyboardHeader?: ReactNode;
+ autoFocus?: boolean;
+ disabled?: boolean;
+};
+
+export const SplitAmountInput = memo(function SplitAmountInput({
+ autoFocus = false,
+ disabled,
+ negate = false,
+ onBlur,
+ onChange,
+ onEnter,
+ onFocus,
+ value,
+ keyboardHeader,
+}: SplitAmountInputProps) {
+ const mobileCalculatorEnabled = useFeatureFlag('mobileCalculator');
+ const [hideFraction] = useSyncedPref('hideFraction');
+ const [focused, setFocused] = useState(autoFocus);
+
+ useEffect(() => {
+ if (autoFocus) {
+ setFocused(true);
+ }
+ }, [autoFocus]);
+
+ if (mobileCalculatorEnabled) {
+ return (
+ <CalculatorAmountInput
+ autoFocus={autoFocus}
+ disabled={disabled}
+ keyboardHeader={keyboardHeader}
+ negate={negate}
+ onBlur={onBlur}
+ onChange={onChange}
+ onEnter={onEnter}
+ onFocus={onFocus}
+ style={{
+ ...styles.smallText,
+ marginRight: 8,
+ textAlign: 'right',
+ minWidth: 0,
+ }}
+ value={value}
+ />
+ );
+ }
+
+ return (
+ <LegacyAmountInput
+ autoDecimals={String(hideFraction) !== 'true'}
+ disabled={disabled}
+ focused={focused}
+ inputStyle={{
+ ...styles.smallText,
+ textAlign: 'right',
+ minWidth: 0,
+ }}
+ onBlur={event => {
+ setFocused(false);
+ onBlur?.(event);
+ }}
+ onEnter={() => onEnter?.()}
+ onFocus={event => {
+ setFocused(true);
+ onFocus?.(event);
+ }}
+ onUpdate={amount => {
+ const nextAmount = integerToAmount(amount);
+ if (nextAmount !== value) {
+ onChange?.(nextAmount);
+ }
+ }}
+ style={{ marginRight: 8 }}
+ value={amountToInteger(value)}
+ zeroSign={negate ? '-' : '+'}
+ />
+ );
+});
diff --git a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
index 82f534538f..17573b911b 100644
--- a/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
+++ b/packages/desktop-client/src/components/mobile/transactions/TransactionEdit.tsx
@@ -7,7 +7,7 @@ import {
useRef,
useState,
} from 'react';
-import type { RefObject } from 'react';
+import type { ReactNode, RefObject } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { useLocation, useParams, useSearchParams } from 'react-router';
@@ -37,7 +37,6 @@ import { send } from '@actual-app/core/platform/client/connection';
import { DEFAULT_MAX_DISTANCE_METERS } from '@actual-app/core/shared/constants';
import { calculateDistance } from '@actual-app/core/shared/location-utils';
import * as monthUtils from '@actual-app/core/shared/months';
-import * as Platform from '@actual-app/core/shared/platform';
import { q } from '@actual-app/core/shared/query';
import { getUpcomingDays } from '@actual-app/core/shared/schedules';
import {
@@ -83,13 +82,11 @@ import {
import { getPrettyPayee } from '#components/mobile/utils';
import { MobilePageHeader, Page } from '#components/Page';
import { createSingleTimeScheduleFromTransaction } from '#components/transactions/TransactionList';
-import { AmountInput } from '#components/util/AmountInput';
import { useAccounts } from '#hooks/useAccounts';
import { useCategories } from '#hooks/useCategories';
import { useCurrentWordRange } from '#hooks/useCurrentWordRange';
import { useCursorPosition } from '#hooks/useCursorPosition';
import { useDateFormat } from '#hooks/useDateFormat';
-import { useInitialMount } from '#hooks/useInitialMount';
import { useInputRefValue } from '#hooks/useInputRefValue';
import { useLocalPref } from '#hooks/useLocalPref';
import { useLocationPermission } from '#hooks/useLocationPermission';
@@ -112,7 +109,8 @@ import { useDispatch, useSelector } from '#redux';
import { setLastTransaction } from '#transactions/transactionsSlice';
import { getStatusLabel } from '#util/schedule';
-import { FocusableAmountInput } from './FocusableAmountInput';
+import { AmountInput } from './AmountInput';
+import { SplitAmountInput } from './SplitAmountInput';
function getFieldName(transactionId: TransactionEntity['id'], field: string) {
return `${field}-${transactionId}`;
@@ -378,9 +376,10 @@ function Footer({
}
type ChildTransactionEditProps = {
+ keyboardHeader: ReactNode;
transaction: TransactionEntity;
+ negate: boolean;
amountFocused: boolean;
- amountSign: '+' | '-';
getCategory: (transaction: TransactionEntity, isOffBudget: boolean) => string;
getPayee: (transaction: TransactionEntity) => PayeeEntity | undefined;
getTransferAccount: (
@@ -407,8 +406,8 @@ const ChildTransactionEdit = forwardRef<
(
{
transaction,
+ negate,
amountFocused,
- amountSign,
getCategory,
getPayee,
getTransferAccount,
@@ -417,13 +416,13 @@ const ChildTransactionEdit = forwardRef<
onEditField,
onUpdate,
onDelete,
+ keyboardHeader,
},
ref,
) => {
const { t } = useTranslation();
const { editingField, onRequestActiveEdit, onClearActiveEdit } =
useSingleActiveEditForm()!;
- const [hideFraction, _] = useSyncedPref('hideFraction');
const noteRef = useRef<HTMLInputElement | null>(null);
const prettyPayee = getPrettyPayee({
@@ -469,32 +468,25 @@ const ChildTransactionEdit = forwardRef<
}}
>
<FieldLabel title={t('Amount')} style={{ padding: 0 }} />
- <AmountInput
+ <SplitAmountInput
+ keyboardHeader={keyboardHeader}
disabled={
!!editingField &&
editingField !== getFieldName(transaction.id, 'amount')
}
- focused={amountFocused}
- value={amountToInteger(transaction.amount)}
- zeroSign={amountSign}
- style={{ marginRight: 8 }}
- inputStyle={{
- ...styles.smallText,
- textAlign: 'right',
- minWidth: 0,
+ value={transaction.amount}
+ negate={negate}
+ autoFocus={amountFocused}
+ onFocus={event => {
+ onRequestActiveEdit(getFieldName(transaction.id, 'amount'));
+
+ const input = event.currentTarget as HTMLInputElement;
+ input.scrollIntoView({ behavior: 'smooth', block: 'start' });
}}
- onFocus={() =>
- onRequestActiveEdit(getFieldName(transaction.id, 'amount'))
- }
- onUpdate={value => {
- const amount = integerToAmount(value);
- if (transaction.amount !== amount) {
- onUpdate(transaction, 'amount', amount);
- } else {
- onClearActiveEdit();
- }
+ onBlur={() => onClearActiveEdit()}
+ onChange={amount => {
+ onUpdate(transaction, 'amount', amount);
}}
- autoDecimals={String(hideFraction) !== 'true'}
/>
</View>
</View>
@@ -650,11 +642,6 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
const { editingField, onRequestActiveEdit, onClearActiveEdit } =
useSingleActiveEditForm()!;
- const [totalAmountFocused, setTotalAmountFocused] = useState(
- // iOS does not support automatically opening up the keyboard for the
- // total amount field. Hence we should not focus on it on page render.
- !Platform.isIOSAgent,
- );
const childTransactionElementRefMap = useRef<
Record<TransactionEntity['id'], HTMLDivElement | null>
>({});
@@ -663,21 +650,6 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
const payeesById = useMemo(() => groupById(payees), [payees]);
const accountsById = useMemo(() => groupById(accounts), [accounts]);
- const onTotalAmountEdit = useCallback(() => {
- onRequestActiveEdit?.(getFieldName(transaction.id, 'amount'), () => {
- setTotalAmountFocused(true);
- return () => setTotalAmountFocused(false);
- });
- }, [onRequestActiveEdit, transaction.id]);
-
- const isInitialMount = useInitialMount();
-
- useEffect(() => {
- if (isInitialMount && isAdding && !Platform.isIOSAgent) {
- onTotalAmountEdit();
- }
- }, [isAdding, isInitialMount, onTotalAmountEdit]);
-
const getAccount = useCallback(
(trans: TransactionEntity) => {
return trans?.account ? accountsById?.[trans.account] : undefined;
@@ -1114,10 +1086,6 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
[scrollChildTransactionIntoView],
);
- // Child transactions should always default to the signage
- // of the parent transaction
- const childAmountSign = transaction.amount <= 0 ? '-' : '+';
-
const account = getAccount(transaction);
const isOffBudget = account ? !!account.offbudget : false;
const title = getPrettyPayee({
@@ -1130,6 +1098,8 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
const transactionDate = parseDate(transaction.date, dateFormat, new Date());
const dateDefaultValue = monthUtils.dayFromDate(transactionDate);
+ const remaining = transaction.error?.difference ?? 0;
+
return (
<Page
header={
@@ -1169,21 +1139,21 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
}}
>
<FieldLabel title={t('Amount')} flush style={{ marginBottom: 0 }} />
- <FocusableAmountInput
+ <AmountInput
value={transaction.amount}
- zeroSign="-"
- focused={totalAmountFocused}
- onFocus={onTotalAmountEdit}
- onBlur={() => onClearActiveEdit()}
- onUpdateAmount={onTotalAmountUpdate}
- focusedStyle={{
- width: 'auto',
- padding: '5px',
- paddingLeft: '20px',
- paddingRight: '20px',
- minWidth: '100%',
+ negate
+ disabled={
+ !!editingField &&
+ editingField !== getFieldName(transaction.id, 'amount')
+ }
+ autoFocus={isAdding}
+ disableNativeAutoFocusOnIOS
+ onFocus={() => {
+ onRequestActiveEdit(getFieldName(transaction.id, 'amount'));
}}
- textStyle={{ ...styles.veryLargeText, textAlign: 'center' }}
+ onBlur={() => onClearActiveEdit()}
+ onChange={onTotalAmountUpdate}
+ variant="large"
/>
</View>
@@ -1316,8 +1286,8 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
<ChildTransactionEdit
key={childTrans.id}
transaction={childTrans}
+ negate={transaction.amount <= 0}
amountFocused={arr.findIndex(c => c.amount === 0) === i}
- amountSign={childAmountSign}
ref={r => {
childTransactionElementRefMap.current = {
...childTransactionElementRefMap.current,
@@ -1332,6 +1302,18 @@ const TransactionEditInner = memo<TransactionEditInnerProps>(
onUpdate={onUpdateInner}
onEditField={onEditFieldInner}
onDelete={onDeleteInner}
+ keyboardHeader={
+ <FillRemainingButton
+ remaining={remaining}
+ onPress={() => {
+ void onUpdateInner(
+ childTrans,
+ 'amount',
+ integerToAmount(remaining),
+ );
+ }}
+ />
+ }
/>
))}
@@ -2134,3 +2116,35 @@ export const TransactionEdit = (props: TransactionEditProps) => {
</SingleActiveEditFormProvider>
);
};
+
+function FillRemainingButton({
+ remaining,
+ onPress,
+}: {
+ readonly remaining: number;
+ readonly onPress: () => void;
+}) {
+ return (
+ <Button
+ variant="primary"
+ style={{ height: styles.mobileMinHeight }}
+ onPress={onPress}
+ isDisabled={remaining === 0}
+ >
+ <SvgSplit width={17} height={17} />
+ <Text
+ style={{
+ ...styles.text,
+ marginLeft: 6,
+ }}
+ >
+ <Trans>
+ Use remaining:{' '}
+ {{
+ amount: integerToCurrency(Math.abs(remaining)),
+ }}
+ </Trans>
+ </Text>
+ </Button>
+ );
+}
diff --git a/packages/desktop-client/src/components/modals/EnvelopeBudgetMenuModal.tsx b/packages/desktop-client/src/components/modals/EnvelopeBudgetMenuModal.tsx
index 34826f007a..88dc5fe72c 100644
--- a/packages/desktop-client/src/components/modals/EnvelopeBudgetMenuModal.tsx
+++ b/packages/desktop-client/src/components/modals/EnvelopeBudgetMenuModal.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from 'react';
+import React, { useState } from 'react';
import type { CSSProperties } from 'react';
import { Trans } from 'react-i18next';
@@ -12,7 +12,6 @@ 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 * as Platform from '@actual-app/core/shared/platform';
import { amountToInteger, integerToAmount } from '@actual-app/core/shared/util';
import { t } from 'i18next';
@@ -24,9 +23,10 @@ import {
ModalHeader,
ModalTitle,
} from '#components/common/Modal';
-import { FocusableAmountInput } from '#components/mobile/transactions/FocusableAmountInput';
+import { AmountInput } from '#components/mobile/transactions/AmountInput';
import { Notes } from '#components/Notes';
import { useCategory } from '#hooks/useCategory';
+import { useFeatureFlag } from '#hooks/useFeatureFlag';
import { useNotes } from '#hooks/useNotes';
import type { Modal as ModalType } from '#modals/modalsSlice';
import { envelopeBudget } from '#spreadsheet/bindings';
@@ -64,7 +64,7 @@ export function EnvelopeBudgetMenuModal({
envelopeBudget.catBudgeted(categoryId),
);
const { data: category } = useCategory(categoryId);
- const [amountFocused, setAmountFocused] = useState(false);
+ const mobileCalculatorEnabled = useFeatureFlag('mobileCalculator');
const notesId = category ? `${category.id}-${month}` : '';
const originalNotes = useNotes(notesId) ?? '';
@@ -84,20 +84,17 @@ export function EnvelopeBudgetMenuModal({
}
};
- useEffect(() => {
- // iOS does not support automatically opening up the keyboard for the
- // total amount field. Hence we should not focus on it on page render.
- if (!Platform.isIOSAgent) {
- setAmountFocused(true);
- }
- }, []);
-
if (!category) {
return null;
}
return (
- <Modal name="envelope-budget-menu">
+ <Modal
+ name="envelope-budget-menu"
+ wrapperProps={{
+ style: mobileCalculatorEnabled ? { paddingBottom: '30vh' } : undefined,
+ }}
+ >
{({ state }) => (
<>
<ModalHeader
@@ -118,23 +115,14 @@ export function EnvelopeBudgetMenuModal({
>
<Trans>Budgeted</Trans>
</Text>
- <FocusableAmountInput
+ <AmountInput
value={integerToAmount(budgeted || 0)}
- focused={amountFocused}
- onFocus={() => setAmountFocused(true)}
- onBlur={() => setAmountFocused(false)}
onEnter={() => state.close()}
- zeroSign="+"
- focusedStyle={{
- width: 'auto',
- padding: '5px',
- paddingLeft: '20px',
- paddingRight: '20px',
- minWidth: '100%',
- }}
- textStyle={{ ...styles.veryLargeText, textAlign: 'center' }}
- onUpdateAmount={_onUpdateBudget}
+ onChange={_onUpdateBudget}
data-testid="budget-amount"
+ autoFocus
+ autoFocusDelay={150}
+ variant="large"
/>
</View>
<View
diff --git a/packages/desktop-client/src/components/modals/TrackingBudgetMenuModal.tsx b/packages/desktop-client/src/components/modals/TrackingBudgetMenuModal.tsx
index 5625d6c911..5c536bdfad 100644
--- a/packages/desktop-client/src/components/modals/TrackingBudgetMenuModal.tsx
+++ b/packages/desktop-client/src/components/modals/TrackingBudgetMenuModal.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useState } from 'react';
+import React, { useState } from 'react';
import type { CSSProperties } from 'react';
import { Trans } from 'react-i18next';
@@ -12,7 +12,6 @@ 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 * as Platform from '@actual-app/core/shared/platform';
import { amountToInteger, integerToAmount } from '@actual-app/core/shared/util';
import { t } from 'i18next';
@@ -24,9 +23,10 @@ import {
ModalHeader,
ModalTitle,
} from '#components/common/Modal';
-import { FocusableAmountInput } from '#components/mobile/transactions/FocusableAmountInput';
+import { AmountInput } from '#components/mobile/transactions/AmountInput';
import { Notes } from '#components/Notes';
import { useCategory } from '#hooks/useCategory';
+import { useFeatureFlag } from '#hooks/useFeatureFlag';
import { useNotes } from '#hooks/useNotes';
import type { Modal as ModalType } from '#modals/modalsSlice';
import { trackingBudget } from '#spreadsheet/bindings';
@@ -64,11 +64,10 @@ export function TrackingBudgetMenuModal({
trackingBudget.catBudgeted(categoryId),
);
const { data: category } = useCategory(categoryId);
+ const mobileCalculatorEnabled = useFeatureFlag('mobileCalculator');
const notesId = category ? `${category.id}-${month}` : '';
const originalNotes = useNotes(notesId) ?? '';
- const [amountFocused, setAmountFocused] = useState(false);
-
const _onUpdateBudget = (amount: number) => {
onUpdateBudget?.(amountToInteger(amount));
};
@@ -85,20 +84,17 @@ export function TrackingBudgetMenuModal({
setShowMore(!showMore);
};
- useEffect(() => {
- // iOS does not support automatically opening up the keyboard for the
- // total amount field. Hence we should not focus on it on page render.
- if (!Platform.isIOSAgent) {
- setAmountFocused(true);
- }
- }, []);
-
if (!category) {
return null;
}
return (
- <Modal name="tracking-budget-menu">
+ <Modal
+ name="tracking-budget-menu"
+ wrapperProps={{
+ style: mobileCalculatorEnabled ? { paddingBottom: '30vh' } : undefined,
+ }}
+ >
{({ state }) => (
<>
<ModalHeader
@@ -119,23 +115,14 @@ export function TrackingBudgetMenuModal({
>
<Trans>Budgeted</Trans>
</Text>
- <FocusableAmountInput
+ <AmountInput
value={integerToAmount(budgeted || 0)}
- focused={amountFocused}
- onFocus={() => setAmountFocused(true)}
- onBlur={() => setAmountFocused(false)}
onEnter={() => state.close()}
- zeroSign="+"
- focusedStyle={{
- width: 'auto',
- padding: '5px',
- paddingLeft: '20px',
- paddingRight: '20px',
- minWidth: '100%',
- }}
- textStyle={{ ...styles.veryLargeText, textAlign: 'center' }}
- onUpdateAmount={_onUpdateBudget}
+ onChange={_onUpdateBudget}
data-testid="budget-amount"
+ autoFocus
+ autoFocusDelay={150}
+ variant="large"
/>
</View>
<View
diff --git a/packages/desktop-client/src/components/settings/Experimental.tsx b/packages/desktop-client/src/components/settings/Experimental.tsx
index 7239bba3e2..086ed95847 100644
--- a/packages/desktop-client/src/components/settings/Experimental.tsx
+++ b/packages/desktop-client/src/components/settings/Experimental.tsx
@@ -202,6 +202,12 @@ export function ExperimentalFeatures() {
>
<Trans>Currency support</Trans>
</FeatureToggle>
+ <FeatureToggle
+ flag="mobileCalculator"
+ feedbackLink="https://github.com/actualbudget/actual/issues/8255"
+ >
+ <Trans>Mobile calculator</Trans>
+ </FeatureToggle>
<FeatureToggle
flag="sankeyReport"
feedbackLink="https://github.com/actualbudget/actual/issues/1919"
diff --git a/packages/desktop-client/src/hooks/useFeatureFlag.ts b/packages/desktop-client/src/hooks/useFeatureFlag.ts
index e96becc595..3efc596358 100644
--- a/packages/desktop-client/src/hooks/useFeatureFlag.ts
+++ b/packages/desktop-client/src/hooks/useFeatureFlag.ts
@@ -16,6 +16,7 @@ const DEFAULT_FEATURE_FLAG_STATE: Record<FeatureFlag, boolean> = {
enableBanking: false,
sankeyReport: false,
akahuBankSync: false,
+ mobileCalculator: false,
};
export function useFeatureFlag(name: FeatureFlag): boolean {
diff --git a/packages/desktop-client/vite.config.mts b/packages/desktop-client/vite.config.mts
index e75ae4fff6..44f6777d88 100644
--- a/packages/desktop-client/vite.config.mts
+++ b/packages/desktop-client/vite.config.mts
@@ -237,6 +237,7 @@ const pluginsServiceAssets = (): Plugin => ({
export default defineConfig(async ({ mode, command }) => {
const env = loadEnv(mode, process.cwd(), '');
+ const isVitest = process.env.VITEST === 'true';
const devHeaders = {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
@@ -382,7 +383,7 @@ export default defineConfig(async ({ mode, command }) => {
}),
injectShims(),
addWatchers(),
- mode === 'desktop' ? undefined : lootCoreBackend(),
+ mode === 'desktop' || isVitest ? undefined : lootCoreBackend(),
mode === 'desktop' ? undefined : pluginsServiceAssets(),
react(),
babel({
diff --git a/packages/loot-core/src/types/prefs.ts b/packages/loot-core/src/types/prefs.ts
index 717094ce89..2557ee6f09 100644
--- a/packages/loot-core/src/types/prefs.ts
+++ b/packages/loot-core/src/types/prefs.ts
@@ -11,7 +11,8 @@ export type FeatureFlag =
| 'payeeLocations'
| 'enableBanking'
| 'sankeyReport'
- | 'akahuBankSync';
+ | 'akahuBankSync'
+ | 'mobileCalculator';
/**
* Cross-device preferences. These sync across devices when they are changed.
diff --git a/upcoming-release-notes/mobile-calculator.md b/upcoming-release-notes/mobile-calculator.md
new file mode 100644
index 0000000000..01c83c0b27
--- /dev/null
+++ b/upcoming-release-notes/mobile-calculator.md
@@ -0,0 +1,6 @@
+---
+category: Features
+authors: [tim-smart]
+---
+
+Add an experimental mobile calculator for amount inputs