index.tsx 20 KB

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