import {ThemeProps, themeable} from '../theme'; import React from 'react'; import {InputBoxProps} from './InputBox'; import {uncontrollable} from 'uncontrollable'; import {Icon} from './icons'; import Input from './Input'; import {autobind} from '../utils/helper'; import {LocaleProps, localeable} from '../locale'; export interface ResultBoxProps extends ThemeProps, LocaleProps, Omit { onChange?: (value: string) => void; onResultClick?: (e: React.MouseEvent) => void; result?: Array | any; itemRender: (value: any) => JSX.Element | string; onResultChange?: (value: Array) => void; allowInput?: boolean; inputPlaceholder: string; } export class ResultBox extends React.Component { static defaultProps: Pick< ResultBoxProps, 'clearable' | 'placeholder' | 'itemRender' | 'inputPlaceholder' > = { clearable: false, placeholder: 'placeholder.noData', inputPlaceholder: 'placeholder.enter', itemRender: (option: any) => ( {`${option.scopeLabel || ''}${option.label}`} ) }; state = { isFocused: false }; inputRef: React.RefObject = React.createRef(); focus() { this.inputRef.current?.focus(); } blur() { this.inputRef.current?.blur(); } @autobind clearValue(e: React.MouseEvent) { e.preventDefault(); const onResultChange = this.props.onResultChange; onResultChange && onResultChange([]); } @autobind handleFocus(e: any) { const onFocus = this.props.onFocus; onFocus && onFocus(e); this.setState({ isFocused: true }); } @autobind handleBlur(e: any) { const onBlur = this.props.onBlur; onBlur && onBlur(e); this.setState({ isFocused: false }); } @autobind removeItem(e: React.MouseEvent) { e.stopPropagation(); e.preventDefault(); const {result, onResultChange} = this.props; const index = parseInt(e.currentTarget.getAttribute('data-index')!, 10); const newResult = Array.isArray(result) ? result.concat() : []; newResult.splice(index, 1); onResultChange && onResultChange(newResult); } @autobind handleChange(e: React.ChangeEvent) { const {onChange} = this.props; onChange?.(e.currentTarget.value); } render() { const { className, classnames: cx, classPrefix, clearable, disabled, hasError, result, value, placeholder, children, itemRender, allowInput, inputPlaceholder, onResultChange, onChange, onResultClick, translate: __, locale, onKeyPress, onFocus, onBlur, ...rest } = this.props; const isFocused = this.state.isFocused; return (
{Array.isArray(result) && result.length ? ( result.map((item, index) => (
{itemRender(item)} {!disabled ? ( ) : null}
)) ) : result && !Array.isArray(result) ? ( {result} ) : allowInput && !disabled ? null : ( {__(placeholder || 'placeholder.noData')} )} {allowInput && !disabled ? ( ) : null} {children} {clearable && !disabled && (Array.isArray(result) ? result.length : result) ? ( ) : null}
); } } export default themeable( localeable( uncontrollable(ResultBox, { value: 'onChange', result: 'onResultChange' }) ) );