import React, { useEffect, useMemo, useState } from 'react' import withDefaults from '../utils/with-defaults' import useTheme from '../styles/use-theme' import InputLabel from './input-label' import InputIcon from './input-icon' import { getSizes, getColors } from './styles' import { NormalSizes, NormalTypes } from '../utils/prop-types' interface Props { value?: string initialValue?: string placeholder?: string size?: NormalSizes status?: NormalTypes readOnly?: boolean disabled?: boolean label?: string labelRight?: string icon?: React.ReactNode iconRight?: React.ReactNode className?: string onChange?: (e: React.ChangeEvent) => void } const defaultProps = { disabled: false, readOnly: false, size: 'medium', status: 'default', className: '', placeholder: '', initialValue: '', } export type InputProps = Props & typeof defaultProps & React.InputHTMLAttributes const Input: React.FC = ({ placeholder, label, labelRight, size, status, disabled, icon, iconRight, initialValue, onChange, readOnly, value, className, ...props }) => { const theme = useTheme() const [selfValue, setSelfValue] = useState(initialValue) const [hover, setHover] = useState(false) const { heightRatio, fontSize } = useMemo(() => getSizes(size),[size]) const labelClasses = useMemo( () => labelRight ? 'right-label' : (label ? 'left-label' : ''), [label, labelRight], ) const iconClasses = useMemo( () => iconRight ? 'right-icon' : (icon ? 'left-icon' : ''), [icon, iconRight], ) const { color, borderColor, hoverBorder } = useMemo( () => getColors(theme.palette, status), [theme.palette, status], ) const changeHandler = (event: React.ChangeEvent) => { if (disabled || readOnly) return onChange && onChange(event) } useEffect(() => { if (value === undefined) return setSelfValue(value) }, [value]) return (
{label && {label}}
{icon && } setHover(true)} onBlur={() => setHover(false)} onChange={changeHandler} {...props} /> {iconRight && }
{labelRight && {labelRight}}
) } export default withDefaults(Input, defaultProps)