Skip to content

Commit

Permalink
refactor: add auto highlights the entire content functionality to num…
Browse files Browse the repository at this point in the history
…ber input component
  • Loading branch information
hamed-musallam committed Oct 28, 2024
1 parent d9624b0 commit 55d358f
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions src/component/elements/NumberInput2.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,40 @@ import {
useState,
isValidElement,
forwardRef,
useRef,
} from 'react';
import type { ForwardedRef } from 'react';

import useCombinedRefs from '../hooks/useCombinedRefs.js';

interface ValueProps
extends Pick<React.InputHTMLAttributes<HTMLInputElement>, 'name' | 'style'>,
Pick<NumericInputProps, 'onValueChange' | 'value'> {
checkValue?: (element?: number) => boolean;
debounceTime?: number;
autoSelect?: boolean;
}
interface UseInputProps extends Omit<ValueProps, 'name'> {
ref: ForwardedRef<HTMLInputElement>;
}
type UseInputProps = Omit<ValueProps, 'name'>;
export interface NumberInput2Props
extends Omit<HTMLInputProps & NumericInputProps, 'value' | 'onValueChange'>,
ValueProps {
format?: () => (element: string) => number | string;
autoSelect?: boolean;
}

function useNumberInput(props: UseInputProps) {
const {
value: externalValue,
debounceTime,
onValueChange,
ref,
autoSelect,
checkValue,
} = props;
const [internalValue, setValue] = useState<number | string>();
const localRef = useRef<HTMLInputElement>();
const innerRef = useCombinedRefs([ref, localRef]);
const value = debounceTime ? internalValue : externalValue;
const [isDebounced, setDebouncedStatus] = useState<boolean>(false);

Expand All @@ -57,6 +67,12 @@ function useNumberInput(props: UseInputProps) {
}
}, [debounceTime, externalValue]);

useEffect(() => {
if (autoSelect) {
innerRef?.current?.select();
}
}, [autoSelect, innerRef]);

function handleValueChange(
valueAsNumber: number,
valueAsString: string,
Expand All @@ -79,6 +95,7 @@ function useNumberInput(props: UseInputProps) {
debounceOnValueChange,
isDebounced,
value,
innerRef,
};
}

Expand Down Expand Up @@ -110,9 +127,11 @@ function InnerNumberInput(props: NumberInput2Props, ref) {
...otherInputProps
} = props;

const { handleValueChange, isDebounced, value } = useNumberInput({
const { handleValueChange, isDebounced, value, innerRef } = useNumberInput({
value: externalValue,
debounceTime,
autoSelect,
ref,
onValueChange,
checkValue,
});
Expand All @@ -124,7 +143,7 @@ function InnerNumberInput(props: NumberInput2Props, ref) {
<NumericInput
leftIcon={icon}
inputClassName={classes}
inputRef={ref}
inputRef={innerRef}
onValueChange={handleValueChange}
value={value}
selectAllOnFocus={autoSelect}
Expand Down

0 comments on commit 55d358f

Please sign in to comment.