import { classNames } from '@/utils'; import React, { ChangeEventHandler, FocusEventHandler, InputHTMLAttributes, KeyboardEventHandler, useEffect, useId, useState, } from 'react'; import ErrorMessage from './ErrorMessage'; export interface SimpleInputProps { children?: React.ReactNode; addOnLeft?: React.ReactNode; addOnRight?: React.ReactNode; value?: string | number; defaultValue?: string | number; className?: string; icon?: any; label?: React.ReactNode; required?: boolean; disabled?: boolean; helpText?: React.ReactNode; errors?: string[]; counter?: boolean; input?: InputHTMLAttributes & { maxLength?: number }; onChange?: ChangeEventHandler; onKeyDown?: KeyboardEventHandler; onKeyPress?: KeyboardEventHandler; onKeyUp?: KeyboardEventHandler; onBlur?: FocusEventHandler; onFocus?: FocusEventHandler; } const SimpleInput: React.FC = (props) => { const [length, setLength] = useState(0); const Icon = props.icon; const generatedId = useId(); useEffect(() => { if (props.counter) { setLength((props.value ?? props.defaultValue)?.toString().length ?? 0); } }, [props.defaultValue, props.value]); const hasErrors = Boolean(props.errors && props.errors.length > 0); return ( <> {typeof props.label === 'string' ? ( ) : ( props.label )}
{props.addOnLeft && ( {props.addOnLeft} )} {props.icon && (
)} { if (props.counter) { setLength(e.target.value.length); } props.onChange && props.onChange(e); }} onKeyDown={props.onKeyDown} onKeyPress={props.onKeyPress} onKeyUp={props.onKeyUp} onBlur={props.onBlur} onFocus={props.onFocus} aria-invalid={hasErrors ? 'true' : 'false'} aria-describedby={`${props.input?.id ?? generatedId}-error`} {...props.input} /> {props.counter && (
{length}/{props.input?.maxLength ?? '∞'}
)} {props.addOnRight && ( {props.addOnRight} )} {props.children}
{props.helpText &&

{props.helpText}

} ); }; export default SimpleInput;