index.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. clearIcon?: React.ReactNode;
  50. style?: React.CSSProperties;
  51. validateStatus?: ValidateStatus;
  52. onClear?: (e: React.MouseEvent<HTMLDivElement>) => void;
  53. onChange?: (value: string, e: React.ChangeEvent<HTMLInputElement>) => void;
  54. onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void;
  55. onFocus?: (e: React.FocusEvent<HTMLInputElement>) => void;
  56. onInput?: (e: React.MouseEvent<HTMLInputElement>) => void;
  57. onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  58. onKeyUp?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  59. onKeyPress?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  60. onEnterPress?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  61. inputStyle?: React.CSSProperties;
  62. getValueLength?: (value: string) => number;
  63. forwardRef?: ((instance: any) => void) | React.MutableRefObject<any> | null;
  64. preventScroll?: boolean
  65. }
  66. export interface InputState {
  67. value: React.ReactText;
  68. cachedValue: React.ReactText;
  69. disabled: boolean;
  70. props: Record<string, any>;
  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. clearIcon: PropTypes.node,
  87. prefix: PropTypes.node,
  88. suffix: PropTypes.node,
  89. mode: PropTypes.oneOf(modeSet),
  90. value: PropTypes.any,
  91. defaultValue: PropTypes.any,
  92. disabled: PropTypes.bool,
  93. readonly: PropTypes.bool,
  94. autofocus: PropTypes.bool,
  95. type: PropTypes.string,
  96. showClear: PropTypes.bool,
  97. hideSuffix: PropTypes.bool,
  98. placeholder: PropTypes.any,
  99. size: PropTypes.oneOf(sizeSet),
  100. className: PropTypes.string,
  101. style: PropTypes.object,
  102. validateStatus: PropTypes.oneOf(statusSet),
  103. onClear: PropTypes.func,
  104. onChange: PropTypes.func,
  105. onBlur: PropTypes.func,
  106. onFocus: PropTypes.func,
  107. onInput: PropTypes.func,
  108. onKeyDown: PropTypes.func,
  109. onKeyUp: PropTypes.func,
  110. onKeyPress: PropTypes.func,
  111. onEnterPress: PropTypes.func,
  112. insetLabel: PropTypes.node,
  113. insetLabelId: PropTypes.string,
  114. inputStyle: PropTypes.object,
  115. getValueLength: PropTypes.func,
  116. preventScroll: PropTypes.bool,
  117. };
  118. static defaultProps = {
  119. addonBefore: '',
  120. addonAfter: '',
  121. prefix: '',
  122. suffix: '',
  123. readonly: false,
  124. type: 'text',
  125. showClear: false,
  126. hideSuffix: false,
  127. placeholder: '',
  128. size: 'default',
  129. className: '',
  130. onClear: noop,
  131. onChange: noop,
  132. onBlur: noop,
  133. onFocus: noop,
  134. onInput: noop,
  135. onKeyDown: noop,
  136. onKeyUp: noop,
  137. onKeyPress: noop,
  138. onEnterPress: noop,
  139. validateStatus: 'default',
  140. };
  141. inputRef!: React.RefObject<HTMLInputElement>;
  142. prefixRef!: React.RefObject<React.ReactNode>;
  143. suffixRef!: React.RefObject<React.ReactNode>;
  144. foundation!: InputFoundation;
  145. constructor(props: InputProps) {
  146. super(props);
  147. this.state = {
  148. value: '',
  149. cachedValue: null, // Cache current props.value value
  150. disabled: false,
  151. props: {},
  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. this.setState({ isFocus });
  169. },
  170. focusInput: () => {
  171. const { preventScroll } = this.props;
  172. const input = this.inputRef && this.inputRef.current;
  173. input && input.focus({ preventScroll });
  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. 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 { clearIcon } = this.props;
  272. const allowClear = this.foundation.isAllowClear();
  273. // use onMouseDown to fix issue 1203
  274. if (allowClear) {
  275. return (
  276. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  277. <div
  278. className={clearCls}
  279. onMouseDown={this.handleClear}
  280. >
  281. { clearIcon ? clearIcon : <IconClear />}
  282. </div>
  283. );
  284. }
  285. return null;
  286. }
  287. renderModeBtn() {
  288. const { eyeClosed } = this.state;
  289. const { mode, disabled } = this.props;
  290. const modeCls = cls(`${prefixCls}-modebtn`);
  291. const modeIcon = eyeClosed ? <IconEyeClosedSolid /> : <IconEyeOpened />;
  292. // alway show password button for a11y
  293. const showModeBtn = mode === 'password' && !disabled;
  294. const ariaLabel = eyeClosed ? 'Show password' : 'Hidden password';
  295. if (showModeBtn) {
  296. return (
  297. <div
  298. role="button"
  299. tabIndex={0}
  300. aria-label={ariaLabel}
  301. className={modeCls}
  302. onClick={this.handleClickEye}
  303. onMouseDown={this.handleMouseDown}
  304. onMouseUp={this.handleMouseUp}
  305. onKeyPress={this.handleModeEnterPress}
  306. >
  307. {modeIcon}
  308. </div>
  309. );
  310. }
  311. return null;
  312. }
  313. renderPrefix() {
  314. const { prefix, insetLabel, insetLabelId } = this.props;
  315. const labelNode = prefix || insetLabel;
  316. if (!labelNode) {
  317. return null;
  318. }
  319. const prefixWrapperCls = cls({
  320. [`${prefixCls}-prefix`]: true,
  321. [`${prefixCls}-inset-label`]: insetLabel,
  322. [`${prefixCls}-prefix-text`]: labelNode && isString(labelNode),
  323. [`${prefixCls}-prefix-icon`]: isSemiIcon(labelNode),
  324. });
  325. return (
  326. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  327. <div
  328. className={prefixWrapperCls}
  329. onMouseDown={this.handlePreventMouseDown}
  330. onClick={this.handleClickPrefixOrSuffix}
  331. id={insetLabelId}
  332. x-semi-prop="prefix,insetLabel"
  333. >
  334. {labelNode}
  335. </div>
  336. );
  337. }
  338. showClearBtn() {
  339. const { value, isFocus, isHovering } = this.state;
  340. const { disabled, showClear } = this.props;
  341. return Boolean(value) && showClear && !disabled && (isFocus || isHovering);
  342. }
  343. renderSuffix(suffixAllowClear: boolean) {
  344. const { suffix, hideSuffix } = this.props;
  345. if (!suffix) {
  346. return null;
  347. }
  348. const suffixWrapperCls = cls({
  349. [`${prefixCls}-suffix`]: true,
  350. [`${prefixCls}-suffix-text`]: suffix && isString(suffix),
  351. [`${prefixCls}-suffix-icon`]: isSemiIcon(suffix),
  352. [`${prefixCls}-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  353. });
  354. return (
  355. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  356. <div
  357. className={suffixWrapperCls}
  358. onMouseDown={this.handlePreventMouseDown}
  359. onClick={this.handleClickPrefixOrSuffix}
  360. x-semi-prop="suffix"
  361. >
  362. {suffix}
  363. </div>
  364. );
  365. }
  366. getInputRef() {
  367. const { forwardRef } = this.props;
  368. if (!isUndefined(forwardRef)) {
  369. if (typeof forwardRef === 'function') {
  370. return (node: HTMLInputElement) => {
  371. forwardRef(node);
  372. this.inputRef = { current: node } ;
  373. };
  374. } else if (Object.prototype.toString.call(forwardRef) === '[object Object]') {
  375. this.inputRef = forwardRef;
  376. return forwardRef;
  377. }
  378. }
  379. return this.inputRef;
  380. }
  381. render() {
  382. const {
  383. addonAfter,
  384. addonBefore,
  385. autofocus,
  386. clearIcon,
  387. className,
  388. disabled,
  389. defaultValue,
  390. placeholder,
  391. prefix,
  392. mode,
  393. insetLabel,
  394. insetLabelId,
  395. validateStatus,
  396. type,
  397. readonly,
  398. size,
  399. suffix,
  400. style,
  401. showClear,
  402. onEnterPress,
  403. onClear,
  404. hideSuffix,
  405. inputStyle,
  406. forwardRef,
  407. maxLength,
  408. getValueLength,
  409. preventScroll,
  410. ...rest
  411. } = this.props;
  412. const { value, isFocus, minLength: stateMinLength } = this.state;
  413. const suffixAllowClear = this.showClearBtn();
  414. const suffixIsIcon = isSemiIcon(suffix);
  415. const ref = this.getInputRef();
  416. const wrapperPrefix = `${prefixCls}-wrapper`;
  417. const wrapperCls = cls(wrapperPrefix, className, {
  418. [`${prefixCls}-wrapper__with-prefix`]: prefix || insetLabel,
  419. [`${prefixCls}-wrapper__with-suffix`]: suffix,
  420. [`${prefixCls}-wrapper__with-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  421. [`${prefixCls}-wrapper__with-suffix-icon`]: suffixIsIcon,
  422. [`${prefixCls}-wrapper__with-append`]: addonBefore,
  423. [`${prefixCls}-wrapper__with-prepend`]: addonAfter,
  424. [`${prefixCls}-wrapper__with-append-only`]: addonBefore && !addonAfter,
  425. [`${prefixCls}-wrapper__with-prepend-only`]: !addonBefore && addonAfter,
  426. [`${wrapperPrefix}-readonly`]: readonly,
  427. [`${wrapperPrefix}-disabled`]: disabled,
  428. [`${wrapperPrefix}-warning`]: validateStatus === 'warning',
  429. [`${wrapperPrefix}-error`]: validateStatus === 'error',
  430. [`${wrapperPrefix}-focus`]: isFocus,
  431. [`${wrapperPrefix}-clearable`]: showClear,
  432. [`${wrapperPrefix}-modebtn`]: mode === 'password',
  433. [`${wrapperPrefix}-hidden`]: type === 'hidden',
  434. [`${wrapperPrefix}-${size}`]: size,
  435. });
  436. const inputCls = cls(prefixCls, {
  437. [`${prefixCls}-${size}`]: size,
  438. [`${prefixCls}-disabled`]: disabled,
  439. [`${prefixCls}-sibling-clearbtn`]: this.foundation.isAllowClear(),
  440. [`${prefixCls}-sibling-modebtn`]: mode === 'password',
  441. });
  442. const inputValue = value === null || value === undefined ? '' : value;
  443. const inputProps: React.InputHTMLAttributes<HTMLInputElement> = {
  444. ...rest,
  445. style: inputStyle,
  446. autoFocus: autofocus,
  447. className: inputCls,
  448. disabled,
  449. readOnly: readonly,
  450. type: this.foundation.handleInputType(type),
  451. placeholder: placeholder as string,
  452. onInput: e => this.foundation.handleInput(e),
  453. onChange: e => this.foundation.handleChange(e.target.value, e),
  454. onFocus: e => this.foundation.handleFocus(e),
  455. onBlur: e => this.foundation.handleBlur(e),
  456. onKeyUp: e => this.foundation.handleKeyUp(e),
  457. onKeyDown: e => this.foundation.handleKeyDown(e),
  458. onKeyPress: e => this.foundation.handleKeyPress(e),
  459. value: inputValue,
  460. };
  461. if (!isFunction(getValueLength)) {
  462. inputProps.maxLength = maxLength;
  463. }
  464. if (stateMinLength) {
  465. inputProps.minLength = stateMinLength;
  466. }
  467. if (validateStatus === 'error') {
  468. inputProps['aria-invalid'] = 'true';
  469. }
  470. return (
  471. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  472. <div
  473. className={wrapperCls}
  474. style={style}
  475. onMouseEnter={e => this.handleMouseOver(e)}
  476. onMouseLeave={e => this.handleMouseLeave(e)}
  477. onClick={e => this.handleClick(e)}
  478. >
  479. {this.renderPrepend()}
  480. {this.renderPrefix()}
  481. <input {...inputProps} ref={ref} />
  482. {this.renderClearBtn()}
  483. {this.renderSuffix(suffixAllowClear)}
  484. {this.renderModeBtn()}
  485. {this.renderAppend()}
  486. </div>
  487. );
  488. }
  489. }
  490. const ForwardInput = React.forwardRef<HTMLInputElement, Omit<InputProps, 'forwardRef'>>((props, ref) => <Input {...props} forwardRef={ref} />);
  491. export default ForwardInput;
  492. export { Input };