feat(input): Add minimum value constraint and enhance number handling in EnhancedInput

This commit is contained in:
web@ppanel 2025-03-13 17:32:36 +07:00
parent 092477b2d3
commit ce3197298d
3 changed files with 89 additions and 37 deletions

View File

@ -113,6 +113,7 @@ export function BasicInfoForm({ user, refetch }: { user: API.User; refetch: () =
<FormControl> <FormControl>
<EnhancedInput <EnhancedInput
type='number' type='number'
min={0}
value={field.value} value={field.value}
prefix={currency?.currency_symbol ?? '$'} prefix={currency?.currency_symbol ?? '$'}
formatInput={(value) => unitConversion('centsToDollars', value)} formatInput={(value) => unitConversion('centsToDollars', value)}
@ -136,6 +137,7 @@ export function BasicInfoForm({ user, refetch }: { user: API.User; refetch: () =
<FormControl> <FormControl>
<EnhancedInput <EnhancedInput
type='number' type='number'
min={0}
value={field.value} value={field.value}
prefix={currency?.currency_symbol ?? '$'} prefix={currency?.currency_symbol ?? '$'}
formatInput={(value) => unitConversion('centsToDollars', value)} formatInput={(value) => unitConversion('centsToDollars', value)}
@ -159,6 +161,7 @@ export function BasicInfoForm({ user, refetch }: { user: API.User; refetch: () =
<FormControl> <FormControl>
<EnhancedInput <EnhancedInput
type='number' type='number'
min={0}
value={field.value} value={field.value}
prefix={currency?.currency_symbol ?? '$'} prefix={currency?.currency_symbol ?? '$'}
formatInput={(value) => unitConversion('centsToDollars', value)} formatInput={(value) => unitConversion('centsToDollars', value)}

View File

@ -6,7 +6,7 @@ export interface EnhancedInputProps
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'prefix'> { extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'prefix'> {
prefix?: string | ReactNode; prefix?: string | ReactNode;
suffix?: string | ReactNode; suffix?: string | ReactNode;
formatInput?: (value: string | number) => string; formatInput?: (value: string | number) => string | number;
formatOutput?: (value: string | number) => string | number; formatOutput?: (value: string | number) => string | number;
onValueChange?: (value: string | number) => void; onValueChange?: (value: string | number) => void;
onValueBlur?: (value: string | number) => void; onValueBlur?: (value: string | number) => void;
@ -26,50 +26,94 @@ export function EnhancedInput({
...props ...props
}: EnhancedInputProps) { }: EnhancedInputProps) {
const getProcessedValue = (inputValue: unknown) => { const getProcessedValue = (inputValue: unknown) => {
const newValue = inputValue === '' || inputValue === 0 ? '' : String(inputValue ?? ''); if (inputValue === '' || inputValue === 0 || inputValue === '0') return '';
const newValue = String(inputValue ?? '');
return formatInput ? formatInput(newValue) : newValue; return formatInput ? formatInput(newValue) : newValue;
}; };
const [value, setValue] = useState<string>(() => getProcessedValue(initialValue)); const [value, setValue] = useState<string | number>(() => getProcessedValue(initialValue));
// @ts-expect-error - This is a controlled component
const [internalValue, setInternalValue] = useState<string | number>(initialValue ?? '');
useEffect(() => { useEffect(() => {
if (initialValue !== value) { if (initialValue !== internalValue) {
const newValue = getProcessedValue(initialValue); const newValue = getProcessedValue(initialValue);
if (value !== newValue) setValue(newValue); if (value !== newValue) {
setValue(newValue);
// @ts-expect-error - This is a controlled component
setInternalValue(initialValue ?? '');
}
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [initialValue, formatInput]); }, [initialValue, formatInput]);
const processValue = (inputValue: string) => { const processValue = (inputValue: string | number) => {
let processedValue: number | string = inputValue?.toString().trim(); let processedValue: number | string = inputValue?.toString().trim();
if (processedValue === '0' && props.type === 'number') {
return 0;
}
if (processedValue && props.type === 'number') processedValue = Number(processedValue); if (processedValue && props.type === 'number') processedValue = Number(processedValue);
return formatOutput ? formatOutput(processedValue) : processedValue; return formatOutput ? formatOutput(processedValue) : processedValue;
}; };
const handleChange = (e: ChangeEvent<HTMLInputElement>) => { const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
let inputValue = e.target.value; let inputValue = e.target.value;
if (props.type === 'number' && inputValue) {
const numericValue = Number(inputValue); if (props.type === 'number') {
if (!isNaN(numericValue)) { if (inputValue === '0') {
const min = Number.isFinite(props.min) ? props.min : -Infinity; setValue('');
const max = Number.isFinite(props.max) ? props.max : Infinity; setInternalValue(0);
inputValue = String(Math.max(min!, Math.min(max!, numericValue))); onValueChange?.(0);
return;
}
if (/^-?\d*\.?\d*$/.test(inputValue) || inputValue === '-' || inputValue === '.') {
const numericValue = Number(inputValue);
if (!isNaN(numericValue) && inputValue !== '-' && inputValue !== '.') {
const min = Number.isFinite(props.min) ? props.min : -Infinity;
const max = Number.isFinite(props.max) ? props.max : Infinity;
const constrainedValue = Math.max(min!, Math.min(max!, numericValue));
inputValue = String(constrainedValue);
setInternalValue(constrainedValue);
} else {
setInternalValue(inputValue);
}
setValue(inputValue === '0' ? '' : inputValue);
} }
setValue(inputValue === '0' ? '' : inputValue);
} else { } else {
setValue(inputValue); setValue(inputValue);
setInternalValue(inputValue);
} }
const outputValue = processValue(inputValue); const outputValue = processValue(inputValue);
console.log();
onValueChange?.(outputValue); onValueChange?.(outputValue);
}; };
const handleBlur = () => { const handleBlur = () => {
if (props.type === 'number' && value) {
if (value === '-' || value === '.') {
setValue('');
setInternalValue('');
onValueBlur?.('');
return;
}
// 确保0值显示为空
if (value === '0') {
setValue('');
onValueBlur?.(0);
return;
}
}
const outputValue = processValue(value); const outputValue = processValue(value);
if ((initialValue || '') !== outputValue) { if ((initialValue || '') !== outputValue) {
onValueBlur?.(outputValue); onValueBlur?.(outputValue);
} }
}; };
const renderPrefix = () => { const renderPrefix = () => {
return typeof prefix === 'string' ? ( return typeof prefix === 'string' ? (
<div className='bg-muted relative mr-px flex h-9 items-center text-nowrap px-3'>{prefix}</div> <div className='bg-muted relative mr-px flex h-9 items-center text-nowrap px-3'>{prefix}</div>
@ -77,6 +121,7 @@ export function EnhancedInput({
prefix prefix
); );
}; };
const renderSuffix = () => { const renderSuffix = () => {
return typeof suffix === 'string' ? ( return typeof suffix === 'string' ? (
<div className='bg-muted relative ml-px flex h-9 items-center text-nowrap px-3'>{suffix}</div> <div className='bg-muted relative ml-px flex h-9 items-center text-nowrap px-3'>{suffix}</div>
@ -95,6 +140,7 @@ export function EnhancedInput({
> >
{renderPrefix()} {renderPrefix()}
<Input <Input
step={0.01}
{...props} {...props}
value={value} value={value}
className='block rounded-none border-none' className='block rounded-none border-none'

View File

@ -1,32 +1,35 @@
import { evaluate, format } from 'mathjs'; import { evaluate, format } from 'mathjs';
export function unitConversion( type ConversionType =
type: 'centsToDollars' | 'dollarsToCents' | 'bitsToMb' | 'mbToBits' | 'bytesToGb' | 'gbToBytes', | 'centsToDollars'
value?: number | string, | 'dollarsToCents'
) { | 'bitsToMb'
if (!value) return; | 'mbToBits'
switch (type) { | 'bytesToGb'
case 'centsToDollars': | 'gbToBytes';
return evaluate(`${value} / 100`);
case 'dollarsToCents': const conversionConfig: Record<ConversionType, { formula: string; precision: number }> = {
return evaluate(`${value} * 100`); centsToDollars: { formula: 'value / 100', precision: 2 },
case 'bitsToMb': dollarsToCents: { formula: 'value * 100', precision: 0 },
return evaluate(`${value} / 1024 / 1024`); bitsToMb: { formula: 'value / 1024 / 1024', precision: 2 },
case 'mbToBits': mbToBits: { formula: 'value * 1024 * 1024', precision: 0 },
return evaluate(`${value} * 1024 * 1024`); bytesToGb: { formula: 'value / 1024 / 1024 / 1024', precision: 2 },
case 'bytesToGb': gbToBytes: { formula: 'value * 1024 * 1024 * 1024', precision: 0 },
return evaluate(`${value} / 1024 / 1024 / 1024`); };
case 'gbToBytes':
return evaluate(`${value} * 1024 * 1024 * 1024`); export function unitConversion(type: ConversionType, value?: number | string) {
default: if (!value) return 0;
throw new Error('Invalid conversion type');
} const config = conversionConfig[type];
if (!config) throw new Error('Invalid conversion type');
const formula = config.formula.replace('value', `${value}`);
const result = evaluate(formula);
return Number(format(result, { notation: 'fixed', precision: config.precision }));
} }
export function evaluateWithPrecision(expression: string) { export function evaluateWithPrecision(expression: string) {
const result = evaluate(expression); const result = evaluate(expression);
const formatted = format(result, { notation: 'fixed', precision: 2 }); const formatted = format(result, { notation: 'fixed', precision: 2 });
return Number(formatted); return Number(formatted);
} }