diff --git a/web/app/components/base/input/index.tsx b/web/app/components/base/input/index.tsx index 63ba0e89af..881aa1d610 100644 --- a/web/app/components/base/input/index.tsx +++ b/web/app/components/base/input/index.tsx @@ -1,4 +1,4 @@ -import type { CSSProperties } from 'react' +import type { CSSProperties, ChangeEventHandler, FocusEventHandler } from 'react' import React from 'react' import { useTranslation } from 'react-i18next' import { RiCloseCircleFill, RiErrorWarningLine, RiSearchLine } from '@remixicon/react' @@ -33,6 +33,8 @@ export type InputProps = { ref?: React.Ref } & Omit, 'size'> & VariantProps +const removeLeadingZeros = (value: string) => value.replace(/^(-?)0+(?=\d)/, '$1') + const Input = ({ size, disabled, @@ -46,11 +48,37 @@ const Input = ({ value, placeholder, onChange = noop, + onBlur = noop, unit, ref, ...props }: InputProps) => { const { t } = useTranslation() + const handleNumberChange: ChangeEventHandler = (e) => { + if (value === 0) { + // remove leading zeros + const formattedValue = removeLeadingZeros(e.target.value) + if (e.target.value !== formattedValue) + e.target.value = formattedValue + } + onChange(e) + } + const handleNumberBlur: FocusEventHandler = (e) => { + // remove leading zeros + const formattedValue = removeLeadingZeros(e.target.value) + if (e.target.value !== formattedValue) { + e.target.value = formattedValue + onChange({ + ...e, + type: 'change', + target: { + ...e.target, + value: formattedValue, + }, + }) + } + onBlur(e) + } return (
{showLeftIcon && } @@ -74,7 +102,8 @@ const Input = ({ ? (t('common.operation.search') || '') : (t('common.placeholder.input') || ''))} value={value} - onChange={onChange} + onChange={props.type === 'number' ? handleNumberChange : onChange} + onBlur={props.type === 'number' ? handleNumberBlur : onBlur} disabled={disabled} {...props} />