index.tsx 20 KB

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