// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import classNames from 'classnames'; import React, {useState, useEffect} from 'react'; import {useIntl} from 'react-intl'; import 'renderer/css/components/Input.scss'; export enum STATUS { NONE = 'none', SUCCESS = 'success', INFO = 'info', WARNING = 'warning', ERROR = 'error', } export enum SIZE { MEDIUM = 'medium', LARGE = 'large', } export type CustomMessageInputType = { type: STATUS; value: string; } | null; interface InputProps extends React.InputHTMLAttributes { required?: boolean; hasError?: boolean; addon?: React.ReactElement; textPrefix?: string; inputPrefix?: JSX.Element; inputSuffix?: JSX.Element; label?: string; containerClassName?: string; wrapperClassName?: string; inputClassName?: string; limit?: number; useLegend?: boolean; customMessage?: CustomMessageInputType; inputSize?: SIZE; } const Input = React.forwardRef(( { name, value, label, placeholder, useLegend = true, className, hasError, required, addon, textPrefix, inputPrefix, inputSuffix, containerClassName, wrapperClassName, inputClassName, limit, customMessage, maxLength, inputSize = SIZE.MEDIUM, disabled, onFocus, onBlur, onChange, ...otherProps }: InputProps, ref?: React.Ref, ) => { const {formatMessage} = useIntl(); const [focused, setFocused] = useState(false); const [customInputLabel, setCustomInputLabel] = useState(null); useEffect(() => { if (customMessage !== undefined && customMessage !== null && customMessage.value !== '') { setCustomInputLabel(customMessage); } }, [customMessage]); const handleOnFocus = (event: React.FocusEvent) => { setFocused(true); if (onFocus) { onFocus(event); } }; const handleOnBlur = (event: React.FocusEvent) => { setFocused(false); validateInput(); if (onBlur) { onBlur(event); } }; const handleOnChange = (event: React.ChangeEvent) => { setCustomInputLabel(null); if (onChange) { onChange(event); } }; const validateInput = () => { if (!required || (value !== null && value !== '')) { return; } const validationErrorMsg = formatMessage({id: 'renderer.components.input.required', defaultMessage: 'This field is required'}); setCustomInputLabel({type: STATUS.ERROR, value: validationErrorMsg}); }; const showLegend = Boolean(focused || value); const error = customInputLabel?.type === 'error'; const limitExceeded = limit && value && !Array.isArray(value) ? value.toString().length - limit : 0; return (
0, Input_fieldset___legend: showLegend, })} > {useLegend && ( {showLegend ? label || placeholder : null} )}
{inputPrefix} {textPrefix && {textPrefix}} {limitExceeded > 0 && ( {'-'}{limitExceeded} )} {inputSuffix}
{addon}
{customInputLabel && (
{customInputLabel.type !== STATUS.INFO && ( )} {customInputLabel.value}
)}
); }); export default Input;