Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions src/components/AmountTextInput.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {useNavigation} from '@react-navigation/native';
import React from 'react';
import type {KeyboardTypeOptions, NativeSyntheticEvent, StyleProp, TextInputKeyPressEvent, TextInputSelectionChangeEvent, TextStyle, ViewStyle} from 'react-native';
import type {NativeSyntheticEvent, StyleProp, TextInputKeyPressEvent, TextInputSelectionChangeEvent, TextStyle, ViewStyle} from 'react-native';
import useLocalize from '@hooks/useLocalize';
import CONST from '@src/CONST';
import type {TextSelection} from './Composer/types';
Expand Down Expand Up @@ -46,9 +46,6 @@ type AmountTextInputProps = {

/** A unique identifier for this text input for testing purposes */
testID?: string;

/** Determines which keyboard to open */
keyboardType?: KeyboardTypeOptions;
} & Pick<BaseTextInputProps, 'autoFocus' | 'autoGrowExtraSpace' | 'submitBehavior' | 'ref' | 'onFocus' | 'onBlur' | 'disabled' | 'accessibilityLabel'>;

function AmountTextInput({
Expand Down Expand Up @@ -85,7 +82,7 @@ function AmountTextInput({
disabled={disabled}
value={formattedAmount}
placeholder={placeholder}
inputMode={!rest.keyboardType ? CONST.INPUT_MODE.DECIMAL : undefined}
inputMode={CONST.INPUT_MODE.DECIMAL}
// On android autoCapitalize="words" is necessary when keyboardType="decimal-pad" or inputMode="decimal" to prevent input lag.
// See https://github.com/Expensify/App/issues/51868 for more information
autoCapitalize="words"
Expand Down
6 changes: 1 addition & 5 deletions src/components/MoneyRequestAmountInput.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type {ForwardedRef} from 'react';
import React, {useCallback, useEffect, useRef} from 'react';
import type {BlurEvent, KeyboardTypeOptions, StyleProp, TextStyle, ViewStyle} from 'react-native';
import type {BlurEvent, StyleProp, TextStyle, ViewStyle} from 'react-native';
import useLocalize from '@hooks/useLocalize';
import {convertToFrontendAmountAsString, getCurrencyDecimals, getLocalizedCurrencySymbol} from '@libs/CurrencyUtils';
import CONST from '@src/CONST';
Expand Down Expand Up @@ -122,9 +122,6 @@ type MoneyRequestAmountInputProps = {

/** Reference to the outer element */
ref?: ForwardedRef<BaseTextInputRef>;

/** Determines which keyboard to open */
keyboardType?: KeyboardTypeOptions;
} & Pick<TextInputWithSymbolProps, 'autoGrowExtraSpace' | 'submitBehavior' | 'shouldUseDefaultLineHeightForPrefix' | 'onFocus' | 'onBlur'>;

type Selection = {
Expand Down Expand Up @@ -262,7 +259,6 @@ function MoneyRequestAmountInput({
clearNegative={clearNegative}
onFocus={props.onFocus}
accessibilityLabel={`${translate('iou.amount')} (${currency})`}
keyboardType={props.keyboardType}
/>
);
}
Expand Down
10 changes: 3 additions & 7 deletions src/components/NumberWithSymbolForm.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {useIsFocused} from '@react-navigation/native';
import type {ForwardedRef} from 'react';
import React, {useCallback, useEffect, useImperativeHandle, useRef, useState} from 'react';
import type {KeyboardTypeOptions, NativeSyntheticEvent} from 'react-native';
import type {NativeSyntheticEvent} from 'react-native';
import {View} from 'react-native';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
Expand Down Expand Up @@ -87,9 +87,6 @@ type NumberWithSymbolFormProps = {

/** Callback when the user presses the submit key (Enter) */
onSubmitEditing?: () => void;

/** Determines which keyboard to open */
keyboardType?: KeyboardTypeOptions;
} & Omit<TextInputWithSymbolProps, 'formattedAmount' | 'onAmountChange' | 'placeholder' | 'onSelectionChange' | 'onKeyPress' | 'onMouseDown' | 'onMouseUp'>;

type NumberWithSymbolFormRef = {
Expand Down Expand Up @@ -384,11 +381,11 @@ function NumberWithSymbolForm({
disabled={disabled}
prefixCharacter={symbol}
prefixStyle={styles.colorMuted}
keyboardType={props.keyboardType ?? CONST.KEYBOARD_TYPE.DECIMAL_PAD}
keyboardType={CONST.KEYBOARD_TYPE.DECIMAL_PAD}
// On android autoCapitalize="words" is necessary when keyboardType="decimal-pad" or inputMode="decimal" to prevent input lag.
Comment on lines 382 to 385

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep keyboardType override for negative split edits

Hardcoding keyboardType to DECIMAL_PAD removes the ability for callers (e.g., split amount inputs) to request a keyboard with a minus key. On iOS, decimal-pad doesn’t include “-”, so if a split amount is negative (refunds/adjustments) and the user clears or replaces the text, they can’t re-enter the negative sign. Previously SplitAmountInput passed a numbers-and-punctuation keyboard to handle this case.

Useful? React with 👍 / 👎.

// See https://github.com/Expensify/App/issues/51868 for more information
autoCapitalize="words"
inputMode={!props.keyboardType ? CONST.INPUT_MODE.DECIMAL : undefined}
inputMode={CONST.INPUT_MODE.DECIMAL}
errorText={errorText}
style={style}
autoFocus={props.autoFocus}
Expand Down Expand Up @@ -462,7 +459,6 @@ function NumberWithSymbolForm({
toggleNegative={toggleNegative}
onFocus={props.onFocus}
accessibilityLabel={props.accessibilityLabel}
keyboardType={props.keyboardType}
/>
);

Expand Down
12 changes: 4 additions & 8 deletions src/components/PercentageForm.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {ForwardedRef} from 'react';
import React, {useCallback, useMemo, useRef} from 'react';
import useLocalize from '@hooks/useLocalize';
import {addLeadingZero, replaceAllDigits, replaceCommasWithPeriod, stripSpacesFromAmount, validatePercentage} from '@libs/MoneyRequestUtils';
import {replaceAllDigits, replaceCommasWithPeriod, stripSpacesFromAmount, validatePercentage} from '@libs/MoneyRequestUtils';
import CONST from '@src/CONST';
import TextInput from './TextInput';
import type {BaseTextInputProps, BaseTextInputRef} from './TextInput/BaseTextInput/types';
Expand All @@ -25,14 +25,11 @@ type PercentageFormProps = BaseTextInputProps & {
/** Whether to allow one decimal place (0.1 precision) for more granular percentage splits. */
allowDecimal?: boolean;

/** Whether to allow negative percentages (e.g. for split expenses with negative amounts). */
allowNegative?: boolean;

/** Reference to the outer element */
ref?: ForwardedRef<BaseTextInputRef>;
};

function PercentageForm({value: amount, errorText, onInputChange, label, allowExceedingHundred = false, allowDecimal = false, allowNegative = false, ref, ...rest}: PercentageFormProps) {
function PercentageForm({value: amount, errorText, onInputChange, label, allowExceedingHundred = false, allowDecimal = false, ref, ...rest}: PercentageFormProps) {
const {toLocaleDigit, numberFormat} = useLocalize();

const textInput = useRef<BaseTextInputRef | null>(null);
Expand All @@ -48,16 +45,15 @@ function PercentageForm({value: amount, errorText, onInputChange, label, allowEx
// Remove spaces from the newAmount value because Safari on iOS adds spaces when pasting a copied value
// More info: https://github.com/Expensify/App/issues/16974
const newAmountWithoutSpaces = stripSpacesFromAmount(newAmount);
const withLeadingZero = addLeadingZero(newAmountWithoutSpaces, allowNegative);
if (!validatePercentage(withLeadingZero, allowExceedingHundred, allowDecimal, allowNegative)) {
if (!validatePercentage(newAmountWithoutSpaces, allowExceedingHundred, allowDecimal)) {
return;
}

// Convert comma to period for internal representation (commas are used as decimal separators in some locales like Spanish)
const normalizedAmount = replaceCommasWithPeriod(newAmountWithoutSpaces);
onInputChange?.(normalizedAmount);
},
[allowExceedingHundred, allowDecimal, allowNegative, onInputChange],
[allowExceedingHundred, allowDecimal, onInputChange],
);

const formattedAmount = replaceAllDigits(currentAmount, toLocaleDigit);
Expand Down
2 changes: 1 addition & 1 deletion src/components/SelectionList/ListItem/SplitListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function SplitListItem<TItem extends ListItem>({
onInputFocus,
onInputBlur,
}: SplitListItemProps<TItem>) {
const icons = useMemoizedLazyExpensifyIcons(['ArrowRight', 'Folder', 'Tag']);
const icons = useMemoizedLazyExpensifyIcons(['ArrowRight', 'Folder', 'Tag'] as const);
const theme = useTheme();
const styles = useThemeStyles();
const {didScreenTransitionEnd} = useScreenWrapperTransitionStatus();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import MoneyRequestAmountInput from '@components/MoneyRequestAmountInput';
import type {SplitListItemType} from '@components/SelectionList/ListItem/types';
import type {BaseTextInputRef} from '@components/TextInput/BaseTextInput/types';
import useThemeStyles from '@hooks/useThemeStyles';
import CONST from '@src/CONST';
import SplitAmountDisplay from './SplitAmountDisplay';

type SplitAmountInputProps = {
Expand Down Expand Up @@ -55,7 +54,6 @@ function SplitAmountInput({splitItem, formattedOriginalAmount, contentWidth, onS
shouldWrapInputInContainer={false}
onFocus={focusHandler}
onBlur={onInputBlur}
keyboardType={CONST.KEYBOARD_TYPE.NUMBERS_AND_PUNCTUATION}
/>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ function SplitPercentageInput({splitItem, contentWidth, percentageDraft, onSplit
}}
allowExceedingHundred
allowDecimal
allowNegative
/>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import Checkbox from '@components/Checkbox';
import FormHelpMessage from '@components/FormHelpMessage';
import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';

Check warning on line 10 in src/components/TextInput/BaseTextInput/implementation/index.native.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

'@components/Icon/Expensicons' import is restricted from being used by a pattern. Direct imports from Icon/Expensicons are deprecated. Please use lazy loading hooks instead. Use `useMemoizedLazyExpensifyIcons` from @hooks/useLazyAsset. See docs/LAZY_ICONS_AND_ILLUSTRATIONS.md for details

Check warning on line 10 in src/components/TextInput/BaseTextInput/implementation/index.native.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

'@components/Icon/Expensicons' import is restricted from being used. Direct imports from @components/Icon/Expensicons are deprecated. Please use lazy loading hooks instead. Use `useMemoizedLazyExpensifyIcons` from @hooks/useLazyAsset. See docs/LAZY_ICONS_AND_ILLUSTRATIONS.md for details

Check warning on line 10 in src/components/TextInput/BaseTextInput/implementation/index.native.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

'@components/Icon/Expensicons' import is restricted from being used by a pattern. Direct imports from Icon/Expensicons are deprecated. Please use lazy loading hooks instead. Use `useMemoizedLazyExpensifyIcons` from @hooks/useLazyAsset. See docs/LAZY_ICONS_AND_ILLUSTRATIONS.md for details

Check warning on line 10 in src/components/TextInput/BaseTextInput/implementation/index.native.tsx

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

'@components/Icon/Expensicons' import is restricted from being used. Direct imports from @components/Icon/Expensicons are deprecated. Please use lazy loading hooks instead. Use `useMemoizedLazyExpensifyIcons` from @hooks/useLazyAsset. See docs/LAZY_ICONS_AND_ILLUSTRATIONS.md for details
import PressableWithoutFeedback from '@components/Pressable/PressableWithoutFeedback';
import type {AnimatedMarkdownTextInputRef} from '@components/RNMarkdownTextInput';
import type {AnimatedTextInputRef} from '@components/RNTextInput';
Expand Down Expand Up @@ -281,7 +281,6 @@
// Height fix is needed only for Text single line inputs
const shouldApplyHeight = !shouldUseFullInputHeight && !isMultiline && !isMarkdownEnabled;
const accessibilityLabel = [label, hint].filter(Boolean).join(', ');
const isKeyboardType = props.keyboardType ? undefined : props.inputMode;

return (
<>
Expand All @@ -306,7 +305,6 @@
!isMultiline && styles.componentHeightLarge,
touchableInputWrapperStyle,
]}
sentryLabel={props.sentryLabel}
>
<View
style={[
Expand Down Expand Up @@ -406,7 +404,7 @@
onPressOut={inputProps.onPress}
showSoftInputOnFocus={!disableKeyboard}
keyboardType={inputProps.keyboardType}
inputMode={!disableKeyboard ? isKeyboardType : CONST.INPUT_MODE.NONE}
inputMode={!disableKeyboard ? inputProps.inputMode : CONST.INPUT_MODE.NONE}
value={uncontrolled ? undefined : value}
readOnly={isReadOnly}
defaultValue={defaultValue}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,6 @@ function BaseTextInput({
defaultValue={defaultValue}
markdownStyle={markdownStyle}
accessibilityLabel={inputProps.accessibilityLabel}
keyboardType={inputProps.keyboardType}
/>
{!!suffixCharacter && (
<View style={[styles.textInputSuffixWrapper, suffixContainerStyle]}>
Expand Down
5 changes: 1 addition & 4 deletions src/components/TextInputWithSymbol/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type {KeyboardTypeOptions, NativeSyntheticEvent, StyleProp, TextInputSelectionChangeEvent, TextStyle, ViewStyle} from 'react-native';
import type {NativeSyntheticEvent, StyleProp, TextInputSelectionChangeEvent, TextStyle, ViewStyle} from 'react-native';
import type {ValueOf} from 'type-fest';
import type {TextSelection} from '@components/Composer/types';
import type {BaseTextInputProps} from '@components/TextInput/BaseTextInput/types';
Expand Down Expand Up @@ -89,9 +89,6 @@ type BaseTextInputWithSymbolProps = {

/** The test ID of TextInput. Used to locate the view in end-to-end tests. */
testID?: string;

/** Determines which keyboard to open */
keyboardType?: KeyboardTypeOptions;
} & Pick<
BaseTextInputProps,
| 'autoFocus'
Expand Down
59 changes: 20 additions & 39 deletions src/libs/IOUUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,23 +102,20 @@ function calculateAmount(numberOfSplits: number, total: number, currency: string

/**
* Calculate a split amount in backend cents from a percentage of the original amount.
* - Supports negative percentages (for cases where someone owes money back to the group)
* - Clamps percentage to [0, 100]
* - Preserves decimal precision in percentage (supports 0.1 precision)
* - Handles all sign combinations: positive/negative amounts with positive/negative percentages
* - Preserves the sign of the original amount (negative amounts stay negative)
*/
function calculateSplitAmountFromPercentage(totalInCents: number, percentage: number): number {
// Calculate directly without clamping to support negative percentages
// This naturally handles all sign combinations:
// - Positive total × Positive % = Positive split (normal expense share)
// - Positive total × Negative % = Negative split (person owes money back)
// - Negative total × Positive % = Negative split (person gets refund share)
// - Negative total × Negative % = Positive split (person owes money on a refund)
const amount = Math.round((totalInCents * percentage) / 100);
const totalAbs = Math.abs(totalInCents);
// Clamp percentage to [0, 100] without rounding to preserve decimal precision
const clamped = Math.min(100, Math.max(0, percentage));
const amount = Math.round((totalAbs * clamped) / 100);
Comment on lines 109 to +113

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not clamp split percentages while edits allow >100

The split-by-percentage input still enables allowExceedingHundred (see SplitPercentageInput), but calculateSplitAmountFromPercentage now clamps percentage to [0,100]. When a user types 110–150% as a temporary edit (the existing UX allows this during multi-split adjustments), the amount is computed as 100%, so the amount no longer reflects the user’s input and the value snaps back when the draft clears. This makes it impossible to use the temporary >100% edits that the UI still accepts.

Useful? React with 👍 / 👎.

// Return 0 for zero amounts to avoid -0
if (amount === 0) {
return 0;
}
return amount;
return totalInCents < 0 ? -amount : amount;
}

/**
Expand All @@ -129,7 +126,6 @@ function calculateSplitAmountFromPercentage(totalInCents: number, percentage: nu
* - The remainder needed to reach 100% goes to the last item (which should be the largest)
* - When the sum of split amounts does not match the original total (over/under splits), percentages still reflect
* each amount as a percentage of the original total and may sum to something other than 100
* - Preserves the sign of amounts (negative amounts result in negative percentages)
*/
function calculateSplitPercentagesFromAmounts(amountsInCents: number[], totalInCents: number): number[] {
const totalAbs = Math.abs(totalInCents);
Expand All @@ -138,45 +134,32 @@ function calculateSplitPercentagesFromAmounts(amountsInCents: number[], totalInC
return amountsInCents.map(() => 0);
}

const amountsAbs = amountsInCents.map((amount) => Math.abs(amount ?? 0));

// Helper functions for decimal precision
const roundToOneDecimal = (value: number): number => Math.round(value * 10) / 10;
const floorToOneDecimal = (value: number): number => Math.floor(value * 10) / 10;

// Calculate percentages based on the relationship between amount sign and total sign
// When they match (both positive or both negative), show positive percentage
// When they differ, show negative percentage
const percentages = amountsInCents.map((amount) => {
if (totalAbs === 0) {
return 0;
}
let percentage = (amount / totalAbs) * 100;
// Flip sign if original total is negative (so user sees intuitive percentages)
if (totalInCents < 0) {
percentage = -percentage;
}
// For negative percentages, floor towards zero (Math.ceil for negative numbers)
return percentage < 0 ? Math.ceil(percentage * 10) / 10 : floorToOneDecimal(percentage);
});
// ALWAYS use floored percentages to guarantee equal amounts get equal percentages
const flooredPercentages = amountsAbs.map((amount) => (totalAbs > 0 ? floorToOneDecimal((amount / totalAbs) * 100) : 0));

// For remainder calculation, we need to work with absolute values to ensure equal amounts get equal percentages
const amountsAbs = amountsInCents.map((amount) => Math.abs(amount ?? 0));
const amountsTotal = amountsAbs.reduce((sum, curr) => sum + curr, 0);

// If the split amounts don't add up to the original total, return percentages as-is
// If the split amounts don't add up to the original total, return floored percentages as-is
// (the sum may not be 100, but that's expected when there's a validation error)
if (amountsTotal !== totalAbs) {
return percentages;
return flooredPercentages;
}

// Calculate remainder based on absolute sum and add it to the LAST item with MAXIMUM absolute amount
const sumOfAbsPercentages = roundToOneDecimal(percentages.map(Math.abs).reduce((sum, current) => sum + current, 0));
const remainder = roundToOneDecimal(100 - sumOfAbsPercentages);
// Calculate remainder and add it to the LAST item (which should be the largest in even splits)
const sumOfFlooredPercentages = roundToOneDecimal(flooredPercentages.reduce((sum, current) => sum + current, 0));
const remainder = roundToOneDecimal(100 - sumOfFlooredPercentages);

if (remainder <= 0) {
return percentages;
return flooredPercentages;
}

// Add remainder to the last item with the MAXIMUM absolute amount
// Add remainder to the last item with the MAXIMUM amount (not just the last item since that can be a new split with 0 amount)
// This ensures 0-amount splits stay at 0%
const maxAmount = Math.max(...amountsAbs);
let lastMaxIndex = amountsAbs.length - 1; // fallback to last
Expand All @@ -186,10 +169,8 @@ function calculateSplitPercentagesFromAmounts(amountsInCents: number[], totalInC
}
}

const adjustedPercentages = [...percentages];
const currentPercentage = adjustedPercentages.at(lastMaxIndex) ?? 0;
// Add remainder with the same sign as the current percentage
adjustedPercentages[lastMaxIndex] = roundToOneDecimal(currentPercentage + (currentPercentage < 0 ? -remainder : remainder));
const adjustedPercentages = [...flooredPercentages];
adjustedPercentages[lastMaxIndex] = roundToOneDecimal((adjustedPercentages.at(lastMaxIndex) ?? 0) + remainder);

return adjustedPercentages;
}
Expand Down
19 changes: 6 additions & 13 deletions src/libs/MoneyRequestUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,19 +60,12 @@ function validateAmount(amount: string, decimals: number, amountMaxLength: numbe
* Some callers (e.g. split-by-percentage) may temporarily allow values above 100 while the user edits; they can
* opt into this relaxed behavior via the `allowExceedingHundred` flag.
* The `allowDecimal` flag enables one decimal place (0.1 precision) for more granular percentage splits.
* The `shouldAllowNegative` flag enables negative percentages (e.g. for split expenses with negative amounts).
* Accepts both period (.) and comma (,) as decimal separators to support locale-specific input (e.g., Spanish).
*/
function validatePercentage(amount: string, allowExceedingHundred = false, allowDecimal = false, shouldAllowNegative = false): boolean {
function validatePercentage(amount: string, allowExceedingHundred = false, allowDecimal = false): boolean {
if (allowExceedingHundred) {
// Build regex pattern conditionally based on flags
const negativePattern = shouldAllowNegative ? '-?' : '';
const decimalPattern = allowDecimal ? '[.,]?\\d?' : '';
const regex = new RegExp(`^${negativePattern}\\d*${decimalPattern}$`, 'u');

if (shouldAllowNegative) {
return amount === '' || amount === '-' || regex.test(amount);
}
// Accept both period and comma as decimal separators for locale support (e.g., Spanish uses comma)
const regex = allowDecimal ? /^\d*[.,]?\d?$/u : /^\d*$/u;
return amount === '' || regex.test(amount);
}

Expand Down Expand Up @@ -104,11 +97,11 @@ function replaceAllDigits(text: string, convertFn: (char: string) => string): st
* @param amount - The amount string to process
* @param allowFlippingAmount - Whether flipping amount is allowed
* @param toggleNegative - Function to toggle negative state
* @returns The processed amount string - strips '-' prefix only if toggleNegative callback is provided
* @returns The processed amount string without the '-' prefix
*/
function handleNegativeAmountFlipping(amount: string, allowFlippingAmount: boolean, toggleNegative?: () => void): string {
if (allowFlippingAmount && amount.startsWith('-') && toggleNegative) {
toggleNegative();
if (allowFlippingAmount && amount.startsWith('-')) {
toggleNegative?.();
return amount.slice(1);
}
return amount;
Expand Down
Loading
Loading