index.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. readonly: false,
  121. type: 'text',
  122. showClear: false,
  123. hideSuffix: false,
  124. placeholder: '',
  125. size: 'default',
  126. className: '',
  127. onClear: noop,
  128. onChange: noop,
  129. onBlur: noop,
  130. onFocus: noop,
  131. onInput: noop,
  132. onKeyDown: noop,
  133. onKeyUp: noop,
  134. onKeyPress: noop,
  135. onEnterPress: noop,
  136. validateStatus: 'default',
  137. };
  138. inputRef!: React.RefObject<HTMLInputElement>;
  139. prefixRef!: React.RefObject<React.ReactNode>;
  140. suffixRef!: React.RefObject<React.ReactNode>;
  141. foundation!: InputFoundation;
  142. constructor(props: InputProps) {
  143. super(props);
  144. this.state = {
  145. value: '',
  146. cachedValue: null, // Cache current props.value value
  147. disabled: false,
  148. props: {},
  149. paddingLeft: '',
  150. isFocus: false,
  151. isHovering: false,
  152. eyeClosed: props.mode === 'password',
  153. minLength: props.minLength,
  154. };
  155. this.inputRef = React.createRef();
  156. this.prefixRef = React.createRef();
  157. this.suffixRef = React.createRef();
  158. this.foundation = new InputFoundation(this.adapter);
  159. }
  160. get adapter() {
  161. return {
  162. ...super.adapter,
  163. setValue: (value: string) => this.setState({ value }),
  164. setEyeClosed: (value: boolean) => this.setState({ eyeClosed: value }),
  165. toggleFocusing: (isFocus: boolean) => {
  166. const input = this.inputRef && this.inputRef.current;
  167. if (isFocus) {
  168. input && input.focus();
  169. } else {
  170. input && input.blur();
  171. }
  172. this.setState({ isFocus });
  173. },
  174. toggleHovering: (isHovering: boolean) => this.setState({ isHovering }),
  175. getIfFocusing: () => this.state.isFocus,
  176. notifyChange: (cbValue: string, e: React.ChangeEvent<HTMLInputElement>) => this.props.onChange(cbValue, e),
  177. notifyBlur: (val: string, e: React.FocusEvent<HTMLInputElement>) => this.props.onBlur(e),
  178. notifyFocus: (val: string, e: React.FocusEvent<HTMLInputElement>) => this.props.onFocus(e),
  179. notifyInput: (e: React.MouseEvent<HTMLInputElement>) => this.props.onInput(e),
  180. notifyKeyPress: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyPress(e),
  181. notifyKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyDown(e),
  182. notifyKeyUp: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyUp(e),
  183. notifyEnterPress: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onEnterPress(e),
  184. notifyClear: (e: React.MouseEvent<HTMLDivElement>) => this.props.onClear(e),
  185. setPaddingLeft: (paddingLeft: string) => this.setState({ paddingLeft }),
  186. setMinLength: (minLength: number) => this.setState({ minLength }),
  187. isEventTarget: (e: React.MouseEvent) => e && e.target === e.currentTarget,
  188. };
  189. }
  190. static getDerivedStateFromProps(props: InputProps, state: InputState) {
  191. const willUpdateStates: Partial<InputState> = {};
  192. if (props.value !== state.cachedValue) {
  193. willUpdateStates.value = props.value;
  194. willUpdateStates.cachedValue = props.value;
  195. }
  196. return willUpdateStates;
  197. }
  198. componentDidUpdate(prevProps: InputProps) {
  199. const { mode } = this.props;
  200. if (prevProps.mode !== mode) {
  201. this.handleModeChange(mode);
  202. }
  203. }
  204. handleClear = (e: React.MouseEvent<HTMLInputElement>) => {
  205. this.foundation.handleClear(e);
  206. };
  207. handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
  208. this.foundation.handleClick(e);
  209. };
  210. handleMouseOver = (e: React.MouseEvent<HTMLDivElement>) => {
  211. this.setState({ isHovering: true });
  212. };
  213. handleMouseLeave = (e: React.MouseEvent<HTMLDivElement>) => {
  214. this.setState({ isHovering: false });
  215. };
  216. handleModeChange = (mode: string) => {
  217. this.foundation.handleModeChange(mode);
  218. };
  219. handleClickEye = (e: React.MouseEvent<HTMLInputElement>) => {
  220. this.foundation.handleClickEye(e);
  221. };
  222. handleMouseDown = (e: React.MouseEvent<HTMLInputElement>) => {
  223. this.foundation.handleMouseDown(e);
  224. };
  225. handleMouseUp = (e: React.MouseEvent<HTMLInputElement>) => {
  226. this.foundation.handleMouseUp(e);
  227. };
  228. handleModeEnterPress = (e: React.KeyboardEvent<HTMLDivElement>) => {
  229. this.foundation.handleModeEnterPress(e);
  230. };
  231. handleClickPrefixOrSuffix = (e: React.MouseEvent<HTMLInputElement>) => {
  232. this.foundation.handleClickPrefixOrSuffix(e);
  233. };
  234. handlePreventMouseDown = (e: React.MouseEvent<HTMLInputElement>) => {
  235. this.foundation.handlePreventMouseDown(e);
  236. };
  237. renderPrepend() {
  238. const { addonBefore } = this.props;
  239. if (addonBefore) {
  240. const prefixWrapperCls = cls({
  241. [`${prefixCls}-prepend`]: true,
  242. [`${prefixCls}-prepend-text`]: addonBefore && isString(addonBefore),
  243. [`${prefixCls}-prepend-icon`]: isSemiIcon(addonBefore),
  244. });
  245. return (
  246. <div className={prefixWrapperCls} x-semi-prop="addonBefore">
  247. {addonBefore}
  248. </div>
  249. );
  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 (
  262. <div className={prefixWrapperCls} x-semi-prop="addonAfter">
  263. {addonAfter}
  264. </div>
  265. );
  266. }
  267. return null;
  268. }
  269. renderClearBtn() {
  270. const clearCls = cls(`${prefixCls}-clearbtn`);
  271. const allowClear = this.foundation.isAllowClear();
  272. // use onMouseDown to fix issue 1203
  273. if (allowClear) {
  274. return (
  275. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  276. <div
  277. className={clearCls}
  278. onMouseDown={this.handleClear}
  279. >
  280. <IconClear />
  281. </div>
  282. );
  283. }
  284. return null;
  285. }
  286. renderModeBtn() {
  287. const { eyeClosed } = this.state;
  288. const { mode, disabled } = this.props;
  289. const modeCls = cls(`${prefixCls}-modebtn`);
  290. const modeIcon = eyeClosed ? <IconEyeClosedSolid /> : <IconEyeOpened />;
  291. // alway show password button for a11y
  292. const showModeBtn = mode === 'password' && !disabled;
  293. const ariaLabel = eyeClosed ? 'Show password' : 'Hidden password';
  294. if (showModeBtn) {
  295. return (
  296. <div
  297. role="button"
  298. tabIndex={0}
  299. aria-label={ariaLabel}
  300. className={modeCls}
  301. onClick={this.handleClickEye}
  302. onMouseDown={this.handleMouseDown}
  303. onMouseUp={this.handleMouseUp}
  304. onKeyPress={this.handleModeEnterPress}
  305. >
  306. {modeIcon}
  307. </div>
  308. );
  309. }
  310. return null;
  311. }
  312. renderPrefix() {
  313. const { prefix, insetLabel, insetLabelId } = this.props;
  314. const labelNode = prefix || insetLabel;
  315. if (!labelNode) {
  316. return null;
  317. }
  318. const prefixWrapperCls = cls({
  319. [`${prefixCls}-prefix`]: true,
  320. [`${prefixCls}-inset-label`]: insetLabel,
  321. [`${prefixCls}-prefix-text`]: labelNode && isString(labelNode),
  322. [`${prefixCls}-prefix-icon`]: isSemiIcon(labelNode),
  323. });
  324. return (
  325. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  326. <div
  327. className={prefixWrapperCls}
  328. onMouseDown={this.handlePreventMouseDown}
  329. onClick={this.handleClickPrefixOrSuffix}
  330. id={insetLabelId}
  331. x-semi-prop="prefix,insetLabel"
  332. >
  333. {labelNode}
  334. </div>
  335. );
  336. }
  337. showClearBtn() {
  338. const { value, isFocus, isHovering } = this.state;
  339. const { disabled, showClear } = this.props;
  340. return Boolean(value) && showClear && !disabled && (isFocus || isHovering);
  341. }
  342. renderSuffix(suffixAllowClear: boolean) {
  343. const { suffix, hideSuffix } = this.props;
  344. if (!suffix) {
  345. return null;
  346. }
  347. const suffixWrapperCls = cls({
  348. [`${prefixCls}-suffix`]: true,
  349. [`${prefixCls}-suffix-text`]: suffix && isString(suffix),
  350. [`${prefixCls}-suffix-icon`]: isSemiIcon(suffix),
  351. [`${prefixCls}-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  352. });
  353. return (
  354. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  355. <div
  356. className={suffixWrapperCls}
  357. onMouseDown={this.handlePreventMouseDown}
  358. onClick={this.handleClickPrefixOrSuffix}
  359. x-semi-prop="suffix"
  360. >
  361. {suffix}
  362. </div>
  363. );
  364. }
  365. render() {
  366. const {
  367. addonAfter,
  368. addonBefore,
  369. autofocus,
  370. className,
  371. disabled,
  372. defaultValue,
  373. placeholder,
  374. prefix,
  375. mode,
  376. insetLabel,
  377. insetLabelId,
  378. validateStatus,
  379. type,
  380. readonly,
  381. size,
  382. suffix,
  383. style,
  384. showClear,
  385. onEnterPress,
  386. onClear,
  387. hideSuffix,
  388. inputStyle,
  389. forwardRef,
  390. maxLength,
  391. getValueLength,
  392. ...rest
  393. } = this.props;
  394. const { value, paddingLeft, isFocus, minLength: stateMinLength } = this.state;
  395. const suffixAllowClear = this.showClearBtn();
  396. const suffixIsIcon = isSemiIcon(suffix);
  397. const ref = forwardRef || this.inputRef;
  398. const wrapperPrefix = `${prefixCls}-wrapper`;
  399. const wrapperCls = cls(wrapperPrefix, className, {
  400. [`${prefixCls}-wrapper__with-prefix`]: prefix || insetLabel,
  401. [`${prefixCls}-wrapper__with-suffix`]: suffix,
  402. [`${prefixCls}-wrapper__with-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  403. [`${prefixCls}-wrapper__with-suffix-icon`]: suffixIsIcon,
  404. [`${prefixCls}-wrapper__with-append`]: addonBefore,
  405. [`${prefixCls}-wrapper__with-prepend`]: addonAfter,
  406. [`${prefixCls}-wrapper__with-append-only`]: addonBefore && !addonAfter,
  407. [`${prefixCls}-wrapper__with-prepend-only`]: !addonBefore && addonAfter,
  408. [`${wrapperPrefix}-readonly`]: readonly,
  409. [`${wrapperPrefix}-disabled`]: disabled,
  410. [`${wrapperPrefix}-warning`]: validateStatus === 'warning',
  411. [`${wrapperPrefix}-error`]: validateStatus === 'error',
  412. [`${wrapperPrefix}-focus`]: isFocus,
  413. [`${wrapperPrefix}-clearable`]: showClear,
  414. [`${wrapperPrefix}-modebtn`]: mode === 'password',
  415. [`${wrapperPrefix}-hidden`]: type === 'hidden',
  416. [`${wrapperPrefix}-${size}`]: size,
  417. });
  418. const inputCls = cls(prefixCls, {
  419. [`${prefixCls}-${size}`]: size,
  420. [`${prefixCls}-disabled`]: disabled,
  421. [`${prefixCls}-sibling-clearbtn`]: this.foundation.isAllowClear(),
  422. [`${prefixCls}-sibling-modebtn`]: mode === 'password',
  423. });
  424. const inputValue = value === null || value === undefined ? '' : value;
  425. const inputProps: React.InputHTMLAttributes<HTMLInputElement> = {
  426. ...rest,
  427. style: { paddingLeft, ...inputStyle },
  428. autoFocus: autofocus,
  429. className: inputCls,
  430. disabled,
  431. readOnly: readonly,
  432. type: this.foundation.handleInputType(type),
  433. placeholder: placeholder as string,
  434. onInput: e => this.foundation.handleInput(e),
  435. onChange: e => this.foundation.handleChange(e.target.value, e),
  436. onFocus: e => this.foundation.handleFocus(e),
  437. onBlur: e => this.foundation.handleBlur(e),
  438. onKeyUp: e => this.foundation.handleKeyUp(e),
  439. onKeyDown: e => this.foundation.handleKeyDown(e),
  440. onKeyPress: e => this.foundation.handleKeyPress(e),
  441. value: inputValue,
  442. };
  443. if (!isFunction(getValueLength)) {
  444. inputProps.maxLength = maxLength;
  445. }
  446. if (stateMinLength) {
  447. inputProps.minLength = stateMinLength;
  448. }
  449. if (validateStatus === 'error') {
  450. inputProps['aria-invalid'] = 'true';
  451. }
  452. return (
  453. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  454. <div
  455. className={wrapperCls}
  456. style={style}
  457. onMouseEnter={e => this.handleMouseOver(e)}
  458. onMouseLeave={e => this.handleMouseLeave(e)}
  459. onClick={e => this.handleClick(e)}
  460. >
  461. {this.renderPrepend()}
  462. {this.renderPrefix()}
  463. <input {...inputProps} ref={ref} />
  464. {this.renderClearBtn()}
  465. {this.renderSuffix(suffixAllowClear)}
  466. {this.renderModeBtn()}
  467. {this.renderAppend()}
  468. </div>
  469. );
  470. }
  471. }
  472. const ForwardInput = React.forwardRef<HTMLInputElement, Omit<InputProps, 'forwardRef'>>((props, ref) => <Input {...props} forwardRef={ref} />);
  473. export default ForwardInput;
  474. export { Input };