index.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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, isUndefined } 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 type { InputGroupProps } from './inputGroup';
  17. export type { 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. 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. preventScroll: PropTypes.bool,
  115. };
  116. static defaultProps = {
  117. addonBefore: '',
  118. addonAfter: '',
  119. prefix: '',
  120. suffix: '',
  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. 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. this.setState({ isFocus });
  167. },
  168. focusInput: () => {
  169. const { preventScroll } = this.props;
  170. const input = this.inputRef && this.inputRef.current;
  171. input && input.focus({ preventScroll });
  172. },
  173. toggleHovering: (isHovering: boolean) => this.setState({ isHovering }),
  174. getIfFocusing: () => this.state.isFocus,
  175. notifyChange: (cbValue: string, e: React.ChangeEvent<HTMLInputElement>) => this.props.onChange(cbValue, e),
  176. notifyBlur: (val: string, e: React.FocusEvent<HTMLInputElement>) => this.props.onBlur(e),
  177. notifyFocus: (val: string, e: React.FocusEvent<HTMLInputElement>) => this.props.onFocus(e),
  178. notifyInput: (e: React.MouseEvent<HTMLInputElement>) => this.props.onInput(e),
  179. notifyKeyPress: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyPress(e),
  180. notifyKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyDown(e),
  181. notifyKeyUp: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyUp(e),
  182. notifyEnterPress: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onEnterPress(e),
  183. notifyClear: (e: React.MouseEvent<HTMLDivElement>) => this.props.onClear(e),
  184. setMinLength: (minLength: number) => this.setState({ minLength }),
  185. isEventTarget: (e: React.MouseEvent) => e && e.target === e.currentTarget,
  186. };
  187. }
  188. static getDerivedStateFromProps(props: InputProps, state: InputState) {
  189. const willUpdateStates: Partial<InputState> = {};
  190. if (props.value !== state.cachedValue) {
  191. willUpdateStates.value = props.value;
  192. willUpdateStates.cachedValue = props.value;
  193. }
  194. return willUpdateStates;
  195. }
  196. componentDidUpdate(prevProps: InputProps) {
  197. const { mode } = this.props;
  198. if (prevProps.mode !== mode) {
  199. this.handleModeChange(mode);
  200. }
  201. }
  202. handleClear = (e: React.MouseEvent<HTMLInputElement>) => {
  203. this.foundation.handleClear(e);
  204. };
  205. handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
  206. this.foundation.handleClick(e);
  207. };
  208. handleMouseOver = (e: React.MouseEvent<HTMLDivElement>) => {
  209. this.setState({ isHovering: true });
  210. };
  211. handleMouseLeave = (e: React.MouseEvent<HTMLDivElement>) => {
  212. this.setState({ isHovering: false });
  213. };
  214. handleModeChange = (mode: string) => {
  215. this.foundation.handleModeChange(mode);
  216. };
  217. handleClickEye = (e: React.MouseEvent<HTMLInputElement>) => {
  218. this.foundation.handleClickEye(e);
  219. };
  220. handleMouseDown = (e: React.MouseEvent<HTMLInputElement>) => {
  221. this.foundation.handleMouseDown(e);
  222. };
  223. handleMouseUp = (e: React.MouseEvent<HTMLInputElement>) => {
  224. this.foundation.handleMouseUp(e);
  225. };
  226. handleModeEnterPress = (e: React.KeyboardEvent<HTMLDivElement>) => {
  227. this.foundation.handleModeEnterPress(e);
  228. };
  229. handleClickPrefixOrSuffix = (e: React.MouseEvent<HTMLInputElement>) => {
  230. this.foundation.handleClickPrefixOrSuffix(e);
  231. };
  232. handlePreventMouseDown = (e: React.MouseEvent<HTMLInputElement>) => {
  233. this.foundation.handlePreventMouseDown(e);
  234. };
  235. renderPrepend() {
  236. const { addonBefore } = this.props;
  237. if (addonBefore) {
  238. const prefixWrapperCls = cls({
  239. [`${prefixCls}-prepend`]: true,
  240. [`${prefixCls}-prepend-text`]: addonBefore && isString(addonBefore),
  241. [`${prefixCls}-prepend-icon`]: isSemiIcon(addonBefore),
  242. });
  243. return (
  244. <div className={prefixWrapperCls} x-semi-prop="addonBefore">
  245. {addonBefore}
  246. </div>
  247. );
  248. }
  249. return null;
  250. }
  251. renderAppend() {
  252. const { addonAfter } = this.props;
  253. if (addonAfter) {
  254. const prefixWrapperCls = cls({
  255. [`${prefixCls}-append`]: true,
  256. [`${prefixCls}-append-text`]: addonAfter && isString(addonAfter),
  257. [`${prefixCls}-append-icon`]: isSemiIcon(addonAfter),
  258. });
  259. return (
  260. <div className={prefixWrapperCls} x-semi-prop="addonAfter">
  261. {addonAfter}
  262. </div>
  263. );
  264. }
  265. return null;
  266. }
  267. renderClearBtn() {
  268. const clearCls = cls(`${prefixCls}-clearbtn`);
  269. const allowClear = this.foundation.isAllowClear();
  270. // use onMouseDown to fix issue 1203
  271. if (allowClear) {
  272. return (
  273. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  274. <div
  275. className={clearCls}
  276. onMouseDown={this.handleClear}
  277. >
  278. <IconClear />
  279. </div>
  280. );
  281. }
  282. return null;
  283. }
  284. renderModeBtn() {
  285. const { eyeClosed } = this.state;
  286. const { mode, disabled } = this.props;
  287. const modeCls = cls(`${prefixCls}-modebtn`);
  288. const modeIcon = eyeClosed ? <IconEyeClosedSolid /> : <IconEyeOpened />;
  289. // alway show password button for a11y
  290. const showModeBtn = mode === 'password' && !disabled;
  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. return (
  323. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  324. <div
  325. className={prefixWrapperCls}
  326. onMouseDown={this.handlePreventMouseDown}
  327. onClick={this.handleClickPrefixOrSuffix}
  328. id={insetLabelId}
  329. x-semi-prop="prefix,insetLabel"
  330. >
  331. {labelNode}
  332. </div>
  333. );
  334. }
  335. showClearBtn() {
  336. const { value, isFocus, isHovering } = this.state;
  337. const { disabled, showClear } = this.props;
  338. return Boolean(value) && showClear && !disabled && (isFocus || isHovering);
  339. }
  340. renderSuffix(suffixAllowClear: boolean) {
  341. const { suffix, hideSuffix } = this.props;
  342. if (!suffix) {
  343. return null;
  344. }
  345. const suffixWrapperCls = cls({
  346. [`${prefixCls}-suffix`]: true,
  347. [`${prefixCls}-suffix-text`]: suffix && isString(suffix),
  348. [`${prefixCls}-suffix-icon`]: isSemiIcon(suffix),
  349. [`${prefixCls}-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  350. });
  351. return (
  352. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  353. <div
  354. className={suffixWrapperCls}
  355. onMouseDown={this.handlePreventMouseDown}
  356. onClick={this.handleClickPrefixOrSuffix}
  357. x-semi-prop="suffix"
  358. >
  359. {suffix}
  360. </div>
  361. );
  362. }
  363. getInputRef() {
  364. const { forwardRef } = this.props;
  365. if (!isUndefined(forwardRef)) {
  366. if (typeof forwardRef === 'function') {
  367. return (node: HTMLInputElement) => {
  368. forwardRef(node);
  369. this.inputRef = { current: node } ;
  370. };
  371. } else if (Object.prototype.toString.call(forwardRef) === '[object Object]') {
  372. this.inputRef = forwardRef;
  373. return forwardRef;
  374. }
  375. }
  376. return this.inputRef;
  377. }
  378. render() {
  379. const {
  380. addonAfter,
  381. addonBefore,
  382. autofocus,
  383. className,
  384. disabled,
  385. defaultValue,
  386. placeholder,
  387. prefix,
  388. mode,
  389. insetLabel,
  390. insetLabelId,
  391. validateStatus,
  392. type,
  393. readonly,
  394. size,
  395. suffix,
  396. style,
  397. showClear,
  398. onEnterPress,
  399. onClear,
  400. hideSuffix,
  401. inputStyle,
  402. forwardRef,
  403. maxLength,
  404. getValueLength,
  405. preventScroll,
  406. ...rest
  407. } = this.props;
  408. const { value, isFocus, minLength: stateMinLength } = this.state;
  409. const suffixAllowClear = this.showClearBtn();
  410. const suffixIsIcon = isSemiIcon(suffix);
  411. const ref = this.getInputRef();
  412. const wrapperPrefix = `${prefixCls}-wrapper`;
  413. const wrapperCls = cls(wrapperPrefix, className, {
  414. [`${prefixCls}-wrapper__with-prefix`]: prefix || insetLabel,
  415. [`${prefixCls}-wrapper__with-suffix`]: suffix,
  416. [`${prefixCls}-wrapper__with-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  417. [`${prefixCls}-wrapper__with-suffix-icon`]: suffixIsIcon,
  418. [`${prefixCls}-wrapper__with-append`]: addonBefore,
  419. [`${prefixCls}-wrapper__with-prepend`]: addonAfter,
  420. [`${prefixCls}-wrapper__with-append-only`]: addonBefore && !addonAfter,
  421. [`${prefixCls}-wrapper__with-prepend-only`]: !addonBefore && addonAfter,
  422. [`${wrapperPrefix}-readonly`]: readonly,
  423. [`${wrapperPrefix}-disabled`]: disabled,
  424. [`${wrapperPrefix}-warning`]: validateStatus === 'warning',
  425. [`${wrapperPrefix}-error`]: validateStatus === 'error',
  426. [`${wrapperPrefix}-focus`]: isFocus,
  427. [`${wrapperPrefix}-clearable`]: showClear,
  428. [`${wrapperPrefix}-modebtn`]: mode === 'password',
  429. [`${wrapperPrefix}-hidden`]: type === 'hidden',
  430. [`${wrapperPrefix}-${size}`]: size,
  431. });
  432. const inputCls = cls(prefixCls, {
  433. [`${prefixCls}-${size}`]: size,
  434. [`${prefixCls}-disabled`]: disabled,
  435. [`${prefixCls}-sibling-clearbtn`]: this.foundation.isAllowClear(),
  436. [`${prefixCls}-sibling-modebtn`]: mode === 'password',
  437. });
  438. const inputValue = value === null || value === undefined ? '' : value;
  439. const inputProps: React.InputHTMLAttributes<HTMLInputElement> = {
  440. ...rest,
  441. style: inputStyle,
  442. autoFocus: autofocus,
  443. className: inputCls,
  444. disabled,
  445. readOnly: readonly,
  446. type: this.foundation.handleInputType(type),
  447. placeholder: placeholder as string,
  448. onInput: e => this.foundation.handleInput(e),
  449. onChange: e => this.foundation.handleChange(e.target.value, e),
  450. onFocus: e => this.foundation.handleFocus(e),
  451. onBlur: e => this.foundation.handleBlur(e),
  452. onKeyUp: e => this.foundation.handleKeyUp(e),
  453. onKeyDown: e => this.foundation.handleKeyDown(e),
  454. onKeyPress: e => this.foundation.handleKeyPress(e),
  455. value: inputValue,
  456. };
  457. if (!isFunction(getValueLength)) {
  458. inputProps.maxLength = maxLength;
  459. }
  460. if (stateMinLength) {
  461. inputProps.minLength = stateMinLength;
  462. }
  463. if (validateStatus === 'error') {
  464. inputProps['aria-invalid'] = 'true';
  465. }
  466. return (
  467. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  468. <div
  469. className={wrapperCls}
  470. style={style}
  471. onMouseEnter={e => this.handleMouseOver(e)}
  472. onMouseLeave={e => this.handleMouseLeave(e)}
  473. onClick={e => this.handleClick(e)}
  474. >
  475. {this.renderPrepend()}
  476. {this.renderPrefix()}
  477. <input {...inputProps} ref={ref} />
  478. {this.renderClearBtn()}
  479. {this.renderSuffix(suffixAllowClear)}
  480. {this.renderModeBtn()}
  481. {this.renderAppend()}
  482. </div>
  483. );
  484. }
  485. }
  486. const ForwardInput = React.forwardRef<HTMLInputElement, Omit<InputProps, 'forwardRef'>>((props, ref) => <Input {...props} forwardRef={ref} />);
  487. export default ForwardInput;
  488. export { Input };