index.tsx 19 KB

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