index.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /* eslint-disable no-unused-vars, max-len, @typescript-eslint/no-unused-vars */
  2. import React from 'react';
  3. import cls from 'classnames';
  4. import PropTypes from 'prop-types';
  5. import InputFoundation from '@douyinfe/semi-foundation/input/foundation';
  6. import { cssClasses, strings } from '@douyinfe/semi-foundation/input/constants';
  7. import { isSemiIcon } from '../_utils';
  8. import BaseComponent from '../_base/baseComponent';
  9. import '@douyinfe/semi-foundation/input/input.scss';
  10. import { isString, noop, isFunction } from 'lodash';
  11. import { IconClear, IconEyeOpened, IconEyeClosedSolid } from '@douyinfe/semi-icons';
  12. const prefixCls = cssClasses.PREFIX;
  13. const sizeSet = strings.SIZE;
  14. const statusSet = strings.STATUS;
  15. const modeSet = strings.MODE;
  16. export { InputGroupProps } from './inputGroup';
  17. export { TextAreaProps } from './textarea';
  18. export type InputSize = 'small' | 'large' | 'default';
  19. export type InputMode = 'password';
  20. // still keep success as ValidateStatus optional value because form will pass success as props.validateStatus in sometime
  21. // Although we do not consume success in the input to configure special styles, we should allow it as a legal props value, otherwise a warning will be thrown
  22. export type ValidateStatus = "default" | "error" | "warning" | "success";
  23. export interface InputProps extends
  24. Omit<React.InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'prefix' | 'size' | 'autoFocus' | 'placeholder' | 'onFocus' | 'onBlur'> {
  25. 'aria-label'?: React.AriaAttributes['aria-label'];
  26. 'aria-describedby'?: React.AriaAttributes['aria-describedby'];
  27. 'aria-errormessage'?: React.AriaAttributes['aria-errormessage'];
  28. 'aria-invalid'?: React.AriaAttributes['aria-invalid'];
  29. 'aria-labelledby'?: React.AriaAttributes['aria-labelledby'];
  30. 'aria-required'?: React.AriaAttributes['aria-required'];
  31. addonBefore?: React.ReactNode;
  32. addonAfter?: React.ReactNode;
  33. prefix?: React.ReactNode;
  34. suffix?: React.ReactNode;
  35. mode?: InputMode;
  36. value?: React.ReactText;
  37. defaultValue?: React.ReactText;
  38. disabled?: boolean;
  39. readonly?: boolean;
  40. autofocus?: boolean;
  41. type?: string;
  42. showClear?: boolean;
  43. hideSuffix?: boolean;
  44. placeholder?: React.ReactText;
  45. insetLabel?: React.ReactNode;
  46. insetLabelId?: string;
  47. size?: InputSize;
  48. className?: string;
  49. style?: React.CSSProperties;
  50. validateStatus?: ValidateStatus;
  51. onClear?: (e: React.MouseEvent<HTMLDivElement>) => void;
  52. onChange?: (value: string, e: React.ChangeEvent<HTMLInputElement>) => void;
  53. onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void;
  54. onFocus?: (e: React.FocusEvent<HTMLInputElement>) => void;
  55. onInput?: (e: React.MouseEvent<HTMLInputElement>) => void;
  56. onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  57. onKeyUp?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  58. onKeyPress?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  59. onEnterPress?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  60. inputStyle?: React.CSSProperties;
  61. getValueLength?: (value: string) => number;
  62. forwardRef?: ((instance: any) => void) | React.MutableRefObject<any> | null;
  63. }
  64. export interface InputState {
  65. value: React.ReactText;
  66. cachedValue: React.ReactText;
  67. disabled: boolean;
  68. props: Record<string, any>;
  69. paddingLeft: string;
  70. isFocus: boolean;
  71. isHovering: boolean;
  72. eyeClosed: boolean;
  73. minLength: number;
  74. }
  75. class Input extends BaseComponent<InputProps, InputState> {
  76. static propTypes = {
  77. 'aria-label': PropTypes.string,
  78. 'aria-labelledby': PropTypes.string,
  79. 'aria-invalid': PropTypes.bool,
  80. 'aria-errormessage': PropTypes.string,
  81. 'aria-describedby': PropTypes.string,
  82. 'aria-required': PropTypes.bool,
  83. addonBefore: PropTypes.node,
  84. addonAfter: PropTypes.node,
  85. prefix: PropTypes.node,
  86. suffix: PropTypes.node,
  87. mode: PropTypes.oneOf(modeSet),
  88. value: PropTypes.any,
  89. defaultValue: PropTypes.any,
  90. disabled: PropTypes.bool,
  91. readonly: PropTypes.bool,
  92. autofocus: PropTypes.bool,
  93. type: PropTypes.string,
  94. showClear: PropTypes.bool,
  95. hideSuffix: PropTypes.bool,
  96. placeholder: PropTypes.any,
  97. size: PropTypes.oneOf(sizeSet),
  98. className: PropTypes.string,
  99. style: PropTypes.object,
  100. validateStatus: PropTypes.oneOf(statusSet),
  101. onClear: PropTypes.func,
  102. onChange: PropTypes.func,
  103. onBlur: PropTypes.func,
  104. onFocus: PropTypes.func,
  105. onInput: PropTypes.func,
  106. onKeyDown: PropTypes.func,
  107. onKeyUp: PropTypes.func,
  108. onKeyPress: PropTypes.func,
  109. onEnterPress: PropTypes.func,
  110. insetLabel: PropTypes.node,
  111. insetLabelId: PropTypes.string,
  112. inputStyle: PropTypes.object,
  113. getValueLength: PropTypes.func,
  114. };
  115. static defaultProps = {
  116. addonBefore: '',
  117. addonAfter: '',
  118. prefix: '',
  119. suffix: '',
  120. disabled: false,
  121. readonly: false,
  122. type: 'text',
  123. showClear: false,
  124. hideSuffix: false,
  125. placeholder: '',
  126. size: 'default',
  127. className: '',
  128. onClear: noop,
  129. onChange: noop,
  130. onBlur: noop,
  131. onFocus: noop,
  132. onInput: noop,
  133. onKeyDown: noop,
  134. onKeyUp: noop,
  135. onKeyPress: noop,
  136. onEnterPress: noop,
  137. validateStatus: 'default'
  138. };
  139. inputRef!: React.RefObject<HTMLInputElement>;
  140. prefixRef!: React.RefObject<React.ReactNode>;
  141. suffixRef!: React.RefObject<React.ReactNode>;
  142. foundation!: InputFoundation;
  143. constructor(props: InputProps) {
  144. super(props);
  145. this.state = {
  146. value: '',
  147. cachedValue: null, // Cache current props.value value
  148. disabled: false,
  149. props: {},
  150. paddingLeft: '',
  151. isFocus: false,
  152. isHovering: false,
  153. eyeClosed: props.mode === 'password',
  154. minLength: props.minLength,
  155. };
  156. this.inputRef = React.createRef();
  157. this.prefixRef = React.createRef();
  158. this.suffixRef = React.createRef();
  159. this.foundation = new InputFoundation(this.adapter);
  160. }
  161. get adapter() {
  162. return {
  163. ...super.adapter,
  164. setValue: (value: string) => this.setState({ value }),
  165. setEyeClosed: (value: boolean) => this.setState({ eyeClosed: value }),
  166. toggleFocusing: (isFocus: boolean) => {
  167. const input = this.inputRef && this.inputRef.current;
  168. if (isFocus) {
  169. input && input.focus();
  170. } else {
  171. input && input.blur();
  172. }
  173. this.setState({ isFocus });
  174. },
  175. toggleHovering: (isHovering: boolean) => this.setState({ isHovering }),
  176. getIfFocusing: () => this.state.isFocus,
  177. notifyChange: (cbValue: string, e: React.ChangeEvent<HTMLInputElement>) => this.props.onChange(cbValue, e),
  178. notifyBlur: (val: string, e: React.FocusEvent<HTMLInputElement>) => this.props.onBlur(e),
  179. notifyFocus: (val: string, e: React.FocusEvent<HTMLInputElement>) => this.props.onFocus(e),
  180. notifyInput: (e: React.MouseEvent<HTMLInputElement>) => this.props.onInput(e),
  181. notifyKeyPress: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyPress(e),
  182. notifyKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyDown(e),
  183. notifyKeyUp: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyUp(e),
  184. notifyEnterPress: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onEnterPress(e),
  185. notifyClear: (e: React.MouseEvent<HTMLDivElement>) => this.props.onClear(e),
  186. setPaddingLeft: (paddingLeft: string) => this.setState({ paddingLeft }),
  187. setMinLength: (minLength: number) => this.setState({ minLength }),
  188. isEventTarget: (e: React.MouseEvent) => e && e.target === e.currentTarget
  189. };
  190. }
  191. static getDerivedStateFromProps(props: InputProps, state: InputState) {
  192. const willUpdateStates: Partial<InputState> = {};
  193. if (props.value !== state.cachedValue) {
  194. willUpdateStates.value = props.value;
  195. willUpdateStates.cachedValue = props.value;
  196. }
  197. return willUpdateStates;
  198. }
  199. componentDidUpdate(prevProps: InputProps) {
  200. const { mode } = this.props;
  201. if (prevProps.mode !== mode) {
  202. this.handleModeChange(mode);
  203. }
  204. }
  205. handleClear = (e: React.MouseEvent<HTMLInputElement>) => {
  206. this.foundation.handleClear(e);
  207. };
  208. handleClearEnterPress = (e: React.KeyboardEvent<HTMLDivElement>) => {
  209. this.foundation.handleClearEnterPress(e);
  210. };
  211. handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
  212. this.foundation.handleClick(e);
  213. };
  214. handleMouseOver = (e: React.MouseEvent<HTMLDivElement>) => {
  215. this.setState({ isHovering: true });
  216. };
  217. handleMouseLeave = (e: React.MouseEvent<HTMLDivElement>) => {
  218. this.setState({ isHovering: false });
  219. };
  220. handleModeChange = (mode: string) => {
  221. this.foundation.handleModeChange(mode);
  222. };
  223. handleClickEye = (e: React.MouseEvent<HTMLInputElement>) => {
  224. this.foundation.handleClickEye(e);
  225. };
  226. handleMouseDown = (e: React.MouseEvent<HTMLInputElement>) => {
  227. this.foundation.handleMouseDown(e);
  228. };
  229. handleMouseUp = (e: React.MouseEvent<HTMLInputElement>) => {
  230. this.foundation.handleMouseUp(e);
  231. };
  232. handleModeEnterPress = (e: React.KeyboardEvent<HTMLDivElement>) => {
  233. this.foundation.handleModeEnterPress(e);
  234. }
  235. handleClickPrefixOrSuffix = (e: React.MouseEvent<HTMLInputElement>) => {
  236. this.foundation.handleClickPrefixOrSuffix(e);
  237. };
  238. handlePreventMouseDown = (e: React.MouseEvent<HTMLInputElement>) => {
  239. this.foundation.handlePreventMouseDown(e);
  240. };
  241. renderPrepend() {
  242. const { addonBefore } = this.props;
  243. if (addonBefore) {
  244. const prefixWrapperCls = cls({
  245. [`${prefixCls}-prepend`]: true,
  246. [`${prefixCls}-prepend-text`]: addonBefore && isString(addonBefore),
  247. [`${prefixCls}-prepend-icon`]: isSemiIcon(addonBefore),
  248. });
  249. return <div className={prefixWrapperCls}>{addonBefore}</div>;
  250. }
  251. return null;
  252. }
  253. renderAppend() {
  254. const { addonAfter } = this.props;
  255. if (addonAfter) {
  256. const prefixWrapperCls = cls({
  257. [`${prefixCls}-append`]: true,
  258. [`${prefixCls}-append-text`]: addonAfter && isString(addonAfter),
  259. [`${prefixCls}-append-icon`]: isSemiIcon(addonAfter),
  260. });
  261. return <div className={prefixWrapperCls}>{addonAfter}</div>;
  262. }
  263. return null;
  264. }
  265. renderClearBtn() {
  266. const clearCls = cls(`${prefixCls}-clearbtn`);
  267. const allowClear = this.foundation.isAllowClear();
  268. // use onMouseDown to fix issue 1203
  269. if (allowClear) {
  270. return (
  271. <div
  272. role="button"
  273. tabIndex={0}
  274. aria-label="Clear input value"
  275. className={clearCls}
  276. onMouseDown={this.handleClear}
  277. onKeyPress={this.handleClearEnterPress}
  278. >
  279. <IconClear />
  280. </div>
  281. );
  282. }
  283. return null;
  284. }
  285. renderModeBtn() {
  286. const { value, isFocus, isHovering, eyeClosed } = this.state;
  287. const { mode, disabled } = this.props;
  288. const modeCls = cls(`${prefixCls}-modebtn`);
  289. const modeIcon = eyeClosed ? <IconEyeClosedSolid /> : <IconEyeOpened />;
  290. const showModeBtn = mode === 'password' && value && !disabled && (isFocus || isHovering);
  291. const ariaLabel = eyeClosed ? 'Show password' : 'Hidden password';
  292. if (showModeBtn) {
  293. return (
  294. <div
  295. role="button"
  296. tabIndex={0}
  297. aria-label={ariaLabel}
  298. className={modeCls}
  299. onClick={this.handleClickEye}
  300. onMouseDown={this.handleMouseDown}
  301. onMouseUp={this.handleMouseUp}
  302. onKeyPress={this.handleModeEnterPress}
  303. >
  304. {modeIcon}
  305. </div>
  306. );
  307. }
  308. return null;
  309. }
  310. renderPrefix() {
  311. const { prefix, insetLabel, insetLabelId } = this.props;
  312. const labelNode = prefix || insetLabel;
  313. if (!labelNode) {
  314. return null;
  315. }
  316. const prefixWrapperCls = cls({
  317. [`${prefixCls}-prefix`]: true,
  318. [`${prefixCls}-inset-label`]: insetLabel,
  319. [`${prefixCls}-prefix-text`]: labelNode && isString(labelNode),
  320. [`${prefixCls}-prefix-icon`]: isSemiIcon(labelNode),
  321. });
  322. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  323. return <div className={prefixWrapperCls} onMouseDown={this.handlePreventMouseDown} onClick={this.handleClickPrefixOrSuffix} id={insetLabelId}>{labelNode}</div>;
  324. }
  325. showClearBtn() {
  326. const { value, isFocus, isHovering } = this.state;
  327. const { disabled, showClear } = this.props;
  328. return Boolean(value) && showClear && !disabled && (isFocus || isHovering);
  329. }
  330. renderSuffix(suffixAllowClear: boolean) {
  331. const { suffix, hideSuffix } = this.props;
  332. if (!suffix) {
  333. return null;
  334. }
  335. const suffixWrapperCls = cls({
  336. [`${prefixCls }-suffix`]: true,
  337. [`${prefixCls }-suffix-text`]: suffix && isString(suffix),
  338. [`${prefixCls }-suffix-icon`]: isSemiIcon(suffix),
  339. [`${prefixCls}-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  340. });
  341. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  342. return <div className={suffixWrapperCls} onMouseDown={this.handlePreventMouseDown} onClick={this.handleClickPrefixOrSuffix}>{suffix}</div>;
  343. }
  344. render() {
  345. const {
  346. addonAfter,
  347. addonBefore,
  348. autofocus,
  349. className,
  350. disabled,
  351. placeholder,
  352. prefix,
  353. mode,
  354. insetLabel,
  355. insetLabelId,
  356. validateStatus,
  357. type,
  358. readonly,
  359. size,
  360. suffix,
  361. style,
  362. showClear,
  363. onEnterPress,
  364. onClear,
  365. hideSuffix,
  366. inputStyle,
  367. forwardRef,
  368. maxLength,
  369. getValueLength,
  370. ...rest
  371. } = this.props;
  372. const { value, paddingLeft, isFocus, minLength: stateMinLength } = this.state;
  373. const suffixAllowClear = this.showClearBtn();
  374. const suffixIsIcon = isSemiIcon(suffix);
  375. const ref = forwardRef || this.inputRef;
  376. const wrapperPrefix = `${prefixCls}-wrapper`;
  377. const wrapperCls = cls(wrapperPrefix, className, {
  378. [`${prefixCls}-wrapper__with-prefix`]: prefix || insetLabel,
  379. [`${prefixCls}-wrapper__with-suffix`]: suffix,
  380. [`${prefixCls}-wrapper__with-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  381. [`${prefixCls}-wrapper__with-suffix-icon`]: suffixIsIcon,
  382. [`${prefixCls}-wrapper__with-append`]: addonBefore,
  383. [`${prefixCls}-wrapper__with-prepend`]: addonAfter,
  384. [`${prefixCls}-wrapper__with-append-only`]: addonBefore && !addonAfter,
  385. [`${prefixCls}-wrapper__with-prepend-only`]: !addonBefore && addonAfter,
  386. [`${wrapperPrefix}-readonly`]: readonly,
  387. [`${wrapperPrefix}-disabled`]: disabled,
  388. [`${wrapperPrefix}-warning`]: validateStatus === 'warning',
  389. [`${wrapperPrefix}-error`]: validateStatus === 'error',
  390. [`${wrapperPrefix}-focus`]: isFocus,
  391. [`${wrapperPrefix}-clearable`]: showClear,
  392. [`${wrapperPrefix}-modebtn`]: mode === 'password',
  393. [`${wrapperPrefix}-hidden`]: type === 'hidden',
  394. [`${wrapperPrefix}-${size}`]: size,
  395. });
  396. const inputCls = cls(prefixCls, {
  397. [`${prefixCls}-${size}`]: size,
  398. [`${prefixCls}-disabled`]: disabled,
  399. [`${prefixCls}-sibling-clearbtn`]: this.foundation.isAllowClear(),
  400. [`${prefixCls}-sibling-modebtn`]: mode === 'password',
  401. });
  402. const inputValue = value === null || value === undefined ? '' : value;
  403. const inputProps: React.InputHTMLAttributes<HTMLInputElement> = {
  404. ...rest,
  405. style: { paddingLeft, ...inputStyle },
  406. autoFocus: autofocus,
  407. className: inputCls,
  408. disabled,
  409. readOnly: readonly,
  410. type: this.foundation.handleInputType(type),
  411. placeholder: placeholder as string,
  412. onInput: e => this.foundation.handleInput(e),
  413. onChange: e => this.foundation.handleChange(e.target.value, e),
  414. onFocus: e => this.foundation.handleFocus(e),
  415. onBlur: e => this.foundation.handleBlur(e),
  416. onKeyUp: e => this.foundation.handleKeyUp(e),
  417. onKeyDown: e => this.foundation.handleKeyDown(e),
  418. onKeyPress: e => this.foundation.handleKeyPress(e),
  419. value: inputValue,
  420. };
  421. if (!isFunction(getValueLength)) {
  422. inputProps.maxLength = maxLength;
  423. }
  424. if (stateMinLength) {
  425. inputProps.minLength = stateMinLength;
  426. }
  427. if (validateStatus === 'error') {
  428. inputProps['aria-invalid'] = "true";
  429. }
  430. return (
  431. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  432. <div
  433. className={wrapperCls}
  434. style={style}
  435. onMouseEnter={e => this.handleMouseOver(e)}
  436. onMouseLeave={e => this.handleMouseLeave(e)}
  437. onClick={e => this.handleClick(e)}
  438. >
  439. {this.renderPrepend()}
  440. {this.renderPrefix()}
  441. <input {...inputProps} ref={ref} />
  442. {this.renderClearBtn()}
  443. {this.renderSuffix(suffixAllowClear)}
  444. {this.renderModeBtn()}
  445. {this.renderAppend()}
  446. </div>
  447. );
  448. }
  449. }
  450. const ForwardInput = React.forwardRef<HTMLInputElement, Omit<InputProps, 'forwardRef'>>((props, ref) => <Input {...props} forwardRef={ref} />);
  451. export default ForwardInput;
  452. export { Input };