index.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. import React from 'react';
  2. import cls from 'classnames';
  3. import PropTypes from 'prop-types';
  4. import InputFoundation from '@douyinfe/semi-foundation/input/foundation';
  5. import { cssClasses, strings } from '@douyinfe/semi-foundation/input/constants';
  6. import { isSemiIcon } from '../_utils';
  7. import BaseComponent from '../_base/baseComponent';
  8. import '@douyinfe/semi-foundation/input/input.scss';
  9. import { isString, noop, isFunction, isUndefined } from 'lodash';
  10. import { IconClear, IconEyeOpened, IconEyeClosedSolid } from '@douyinfe/semi-icons';
  11. const prefixCls = cssClasses.PREFIX;
  12. const sizeSet = strings.SIZE;
  13. const statusSet = strings.STATUS;
  14. const modeSet = strings.MODE;
  15. export type { InputGroupProps } from './inputGroup';
  16. export type { TextAreaProps } from './textarea';
  17. export type InputSize = 'small' | 'large' | 'default';
  18. export type InputMode = 'password';
  19. // still keep success as ValidateStatus optional value because form will pass success as props.validateStatus in sometime
  20. // 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
  21. export type ValidateStatus = "default" | "error" | "warning" | "success";
  22. export interface InputProps extends
  23. Omit<React.InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'prefix' | 'size' | 'placeholder' | 'onFocus' | 'onBlur'> {
  24. 'aria-label'?: React.AriaAttributes['aria-label'];
  25. 'aria-describedby'?: React.AriaAttributes['aria-describedby'];
  26. 'aria-errormessage'?: React.AriaAttributes['aria-errormessage'];
  27. 'aria-invalid'?: React.AriaAttributes['aria-invalid'];
  28. 'aria-labelledby'?: React.AriaAttributes['aria-labelledby'];
  29. 'aria-required'?: React.AriaAttributes['aria-required'];
  30. addonBefore?: React.ReactNode;
  31. addonAfter?: React.ReactNode;
  32. borderless?: boolean;
  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. type?: string;
  41. showClear?: boolean;
  42. hideSuffix?: boolean;
  43. placeholder?: React.ReactText;
  44. insetLabel?: React.ReactNode;
  45. insetLabelId?: string;
  46. size?: InputSize;
  47. className?: string;
  48. clearIcon?: React.ReactNode;
  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. /** internal prop, DatePicker use it */
  65. showClearIgnoreDisabled?: boolean;
  66. onlyBorder?: number
  67. }
  68. export interface InputState {
  69. value: React.ReactText;
  70. cachedValue: React.ReactText;
  71. disabled: boolean;
  72. props: Record<string, any>;
  73. isFocus: boolean;
  74. isHovering: boolean;
  75. eyeClosed: boolean;
  76. minLength: number
  77. }
  78. class Input extends BaseComponent<InputProps, InputState> {
  79. static propTypes = {
  80. 'aria-label': PropTypes.string,
  81. 'aria-labelledby': PropTypes.string,
  82. 'aria-invalid': PropTypes.bool,
  83. 'aria-errormessage': PropTypes.string,
  84. 'aria-describedby': PropTypes.string,
  85. 'aria-required': PropTypes.bool,
  86. addonBefore: PropTypes.node,
  87. addonAfter: PropTypes.node,
  88. clearIcon: PropTypes.node,
  89. prefix: PropTypes.node,
  90. suffix: PropTypes.node,
  91. mode: PropTypes.oneOf(modeSet),
  92. value: PropTypes.any,
  93. defaultValue: PropTypes.any,
  94. disabled: PropTypes.bool,
  95. readonly: PropTypes.bool,
  96. autoFocus: PropTypes.bool,
  97. type: PropTypes.string,
  98. showClear: PropTypes.bool,
  99. hideSuffix: PropTypes.bool,
  100. placeholder: PropTypes.any,
  101. size: PropTypes.oneOf(sizeSet),
  102. className: PropTypes.string,
  103. style: PropTypes.object,
  104. validateStatus: PropTypes.oneOf(statusSet),
  105. onClear: PropTypes.func,
  106. onChange: PropTypes.func,
  107. onBlur: PropTypes.func,
  108. onFocus: PropTypes.func,
  109. onInput: PropTypes.func,
  110. onKeyDown: PropTypes.func,
  111. onKeyUp: PropTypes.func,
  112. onKeyPress: PropTypes.func,
  113. onEnterPress: PropTypes.func,
  114. insetLabel: PropTypes.node,
  115. insetLabelId: PropTypes.string,
  116. inputStyle: PropTypes.object,
  117. getValueLength: PropTypes.func,
  118. preventScroll: PropTypes.bool,
  119. borderless: PropTypes.bool,
  120. };
  121. static defaultProps = {
  122. addonBefore: '',
  123. addonAfter: '',
  124. prefix: '',
  125. suffix: '',
  126. readonly: false,
  127. type: 'text',
  128. showClear: false,
  129. hideSuffix: false,
  130. placeholder: '',
  131. size: 'default',
  132. className: '',
  133. onClear: noop,
  134. onChange: noop,
  135. onBlur: noop,
  136. onFocus: noop,
  137. onInput: noop,
  138. onKeyDown: noop,
  139. onKeyUp: noop,
  140. onKeyPress: noop,
  141. onEnterPress: noop,
  142. validateStatus: 'default',
  143. borderless: false,
  144. };
  145. inputRef!: React.RefObject<HTMLInputElement>;
  146. prefixRef!: React.RefObject<React.ReactNode>;
  147. suffixRef!: React.RefObject<React.ReactNode>;
  148. foundation!: InputFoundation;
  149. constructor(props: InputProps) {
  150. super(props);
  151. const initValue = 'value' in props ? props.value : props.defaultValue;
  152. this.state = {
  153. value: initValue,
  154. cachedValue: props.value, // 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. componentDidMount(): void {
  210. // autofocus is changed from the original support of input to the support of manually calling the focus method,
  211. // so that preventScroll can still take effect under the setting of autofocus
  212. const { disabled, autoFocus, preventScroll } = this.props;
  213. if (!disabled && (autoFocus || this.props['autofocus'])) {
  214. this.inputRef.current.focus({ preventScroll });
  215. }
  216. }
  217. handleClear = (e: React.MouseEvent<HTMLInputElement>) => {
  218. this.foundation.handleClear(e);
  219. };
  220. handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
  221. this.foundation.handleClick(e);
  222. };
  223. handleMouseOver = (e: React.MouseEvent<HTMLDivElement>) => {
  224. this.setState({ isHovering: true });
  225. };
  226. handleMouseLeave = (e: React.MouseEvent<HTMLDivElement>) => {
  227. this.setState({ isHovering: false });
  228. };
  229. handleModeChange = (mode: string) => {
  230. this.foundation.handleModeChange(mode);
  231. };
  232. handleClickEye = (e: React.MouseEvent<HTMLInputElement>) => {
  233. this.foundation.handleClickEye(e);
  234. };
  235. handleMouseDown = (e: React.MouseEvent<HTMLInputElement>) => {
  236. this.foundation.handleMouseDown(e);
  237. };
  238. handleMouseUp = (e: React.MouseEvent<HTMLInputElement>) => {
  239. this.foundation.handleMouseUp(e);
  240. };
  241. handleModeEnterPress = (e: React.KeyboardEvent<HTMLDivElement>) => {
  242. this.foundation.handleModeEnterPress(e);
  243. };
  244. handleClickPrefixOrSuffix = (e: React.MouseEvent<HTMLInputElement>) => {
  245. this.foundation.handleClickPrefixOrSuffix(e);
  246. };
  247. handlePreventMouseDown = (e: React.MouseEvent<HTMLInputElement>) => {
  248. this.foundation.handlePreventMouseDown(e);
  249. };
  250. renderPrepend() {
  251. const { addonBefore } = this.props;
  252. if (addonBefore) {
  253. const prefixWrapperCls = cls({
  254. [`${prefixCls}-prepend`]: true,
  255. [`${prefixCls}-prepend-text`]: addonBefore && isString(addonBefore),
  256. [`${prefixCls}-prepend-icon`]: isSemiIcon(addonBefore),
  257. });
  258. return (
  259. <div className={prefixWrapperCls} x-semi-prop="addonBefore">
  260. {addonBefore}
  261. </div>
  262. );
  263. }
  264. return null;
  265. }
  266. renderAppend() {
  267. const { addonAfter } = this.props;
  268. if (addonAfter) {
  269. const prefixWrapperCls = cls({
  270. [`${prefixCls}-append`]: true,
  271. [`${prefixCls}-append-text`]: addonAfter && isString(addonAfter),
  272. [`${prefixCls}-append-icon`]: isSemiIcon(addonAfter),
  273. });
  274. return (
  275. <div className={prefixWrapperCls} x-semi-prop="addonAfter">
  276. {addonAfter}
  277. </div>
  278. );
  279. }
  280. return null;
  281. }
  282. renderClearBtn() {
  283. const clearCls = cls(`${prefixCls}-clearbtn`);
  284. const { clearIcon } = this.props;
  285. const allowClear = this.foundation.isAllowClear();
  286. // use onMouseDown to fix issue 1203
  287. if (allowClear) {
  288. return (
  289. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  290. <div
  291. className={clearCls}
  292. onMouseDown={this.handleClear}
  293. >
  294. {clearIcon ? clearIcon : <IconClear />}
  295. </div>
  296. );
  297. }
  298. return null;
  299. }
  300. renderModeBtn() {
  301. const { eyeClosed } = this.state;
  302. const { mode, disabled } = this.props;
  303. const modeCls = cls(`${prefixCls}-modebtn`);
  304. const modeIcon = eyeClosed ? <IconEyeClosedSolid /> : <IconEyeOpened />;
  305. // alway show password button for a11y
  306. const showModeBtn = mode === 'password' && !disabled;
  307. const ariaLabel = eyeClosed ? 'Show password' : 'Hidden password';
  308. if (showModeBtn) {
  309. return (
  310. <div
  311. role="button"
  312. tabIndex={0}
  313. aria-label={ariaLabel}
  314. className={modeCls}
  315. onClick={this.handleClickEye}
  316. onMouseDown={this.handleMouseDown}
  317. onMouseUp={this.handleMouseUp}
  318. onKeyPress={this.handleModeEnterPress}
  319. >
  320. {modeIcon}
  321. </div>
  322. );
  323. }
  324. return null;
  325. }
  326. renderPrefix() {
  327. const { prefix, insetLabel, insetLabelId } = this.props;
  328. const labelNode = prefix || insetLabel;
  329. if (!labelNode) {
  330. return null;
  331. }
  332. const prefixWrapperCls = cls({
  333. [`${prefixCls}-prefix`]: true,
  334. [`${prefixCls}-inset-label`]: insetLabel,
  335. [`${prefixCls}-prefix-text`]: labelNode && isString(labelNode),
  336. [`${prefixCls}-prefix-icon`]: isSemiIcon(labelNode),
  337. });
  338. return (
  339. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  340. <div
  341. className={prefixWrapperCls}
  342. onMouseDown={this.handlePreventMouseDown}
  343. onClick={this.handleClickPrefixOrSuffix}
  344. id={insetLabelId}
  345. x-semi-prop="prefix,insetLabel"
  346. >
  347. {labelNode}
  348. </div>
  349. );
  350. }
  351. renderSuffix(suffixAllowClear: boolean) {
  352. const { suffix, hideSuffix } = this.props;
  353. if (!suffix) {
  354. return null;
  355. }
  356. const suffixWrapperCls = cls({
  357. [`${prefixCls}-suffix`]: true,
  358. [`${prefixCls}-suffix-text`]: suffix && isString(suffix),
  359. [`${prefixCls}-suffix-icon`]: isSemiIcon(suffix),
  360. [`${prefixCls}-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  361. });
  362. return (
  363. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  364. <div
  365. className={suffixWrapperCls}
  366. onMouseDown={this.handlePreventMouseDown}
  367. onClick={this.handleClickPrefixOrSuffix}
  368. x-semi-prop="suffix"
  369. >
  370. {suffix}
  371. </div>
  372. );
  373. }
  374. getInputRef() {
  375. const { forwardRef } = this.props;
  376. if (!isUndefined(forwardRef)) {
  377. if (typeof forwardRef === 'function') {
  378. return (node: HTMLInputElement) => {
  379. forwardRef(node);
  380. this.inputRef = { current: node };
  381. };
  382. } else if (Object.prototype.toString.call(forwardRef) === '[object Object]') {
  383. this.inputRef = forwardRef;
  384. return forwardRef;
  385. }
  386. }
  387. return this.inputRef;
  388. }
  389. render() {
  390. const {
  391. addonAfter,
  392. addonBefore,
  393. autoFocus,
  394. clearIcon,
  395. className,
  396. disabled,
  397. defaultValue,
  398. placeholder,
  399. prefix,
  400. mode,
  401. insetLabel,
  402. insetLabelId,
  403. validateStatus,
  404. type,
  405. readonly,
  406. size,
  407. suffix,
  408. style,
  409. showClear,
  410. onEnterPress,
  411. onClear,
  412. hideSuffix,
  413. inputStyle,
  414. forwardRef,
  415. maxLength,
  416. getValueLength,
  417. preventScroll,
  418. borderless,
  419. showClearIgnoreDisabled,
  420. onlyBorder,
  421. ...rest
  422. } = this.props;
  423. const { value, isFocus, minLength: stateMinLength } = this.state;
  424. const suffixAllowClear = this.foundation.isAllowClear();
  425. const suffixIsIcon = isSemiIcon(suffix);
  426. const ref = this.getInputRef();
  427. const wrapperPrefix = `${prefixCls}-wrapper`;
  428. const wrapperCls = cls(wrapperPrefix, className, {
  429. [`${prefixCls}-wrapper__with-prefix`]: prefix || insetLabel,
  430. [`${prefixCls}-wrapper__with-suffix`]: suffix,
  431. [`${prefixCls}-wrapper__with-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  432. [`${prefixCls}-wrapper__with-suffix-icon`]: suffixIsIcon,
  433. [`${prefixCls}-wrapper__with-append`]: addonBefore,
  434. [`${prefixCls}-wrapper__with-prepend`]: addonAfter,
  435. [`${prefixCls}-wrapper__with-append-only`]: addonBefore && !addonAfter,
  436. [`${prefixCls}-wrapper__with-prepend-only`]: !addonBefore && addonAfter,
  437. [`${wrapperPrefix}-readonly`]: readonly,
  438. [`${wrapperPrefix}-disabled`]: disabled,
  439. [`${wrapperPrefix}-warning`]: validateStatus === 'warning',
  440. [`${wrapperPrefix}-error`]: validateStatus === 'error',
  441. [`${wrapperPrefix}-focus`]: isFocus,
  442. [`${wrapperPrefix}-clearable`]: showClear,
  443. [`${wrapperPrefix}-modebtn`]: mode === 'password',
  444. [`${wrapperPrefix}-hidden`]: type === 'hidden',
  445. [`${wrapperPrefix}-${size}`]: size,
  446. [`${prefixCls}-borderless`]: borderless,
  447. [`${prefixCls}-only_border`]: onlyBorder !== undefined && onlyBorder !== null,
  448. });
  449. const inputCls = cls(prefixCls, {
  450. [`${prefixCls}-${size}`]: size,
  451. [`${prefixCls}-disabled`]: disabled,
  452. [`${prefixCls}-sibling-clearbtn`]: this.foundation.isAllowClear(),
  453. [`${prefixCls}-sibling-modebtn`]: mode === 'password',
  454. });
  455. const inputValue = value === null || value === undefined ? '' : value;
  456. const inputProps: React.InputHTMLAttributes<HTMLInputElement> = {
  457. ...rest,
  458. style: inputStyle,
  459. className: inputCls,
  460. disabled,
  461. readOnly: readonly,
  462. type: this.foundation.handleInputType(type),
  463. placeholder: placeholder as string,
  464. onInput: e => this.foundation.handleInput(e),
  465. onChange: e => this.foundation.handleChange(e.target.value, e),
  466. onFocus: e => this.foundation.handleFocus(e),
  467. onBlur: e => this.foundation.handleBlur(e),
  468. onKeyUp: e => this.foundation.handleKeyUp(e),
  469. onKeyDown: e => this.foundation.handleKeyDown(e),
  470. onKeyPress: e => this.foundation.handleKeyPress(e),
  471. value: inputValue,
  472. };
  473. if (!isFunction(getValueLength)) {
  474. inputProps.maxLength = maxLength;
  475. }
  476. if (stateMinLength) {
  477. inputProps.minLength = stateMinLength;
  478. }
  479. if (validateStatus === 'error') {
  480. inputProps['aria-invalid'] = 'true';
  481. }
  482. let wrapperStyle = { ...style };
  483. if (onlyBorder !== undefined) {
  484. wrapperStyle = {
  485. borderWidth: onlyBorder,
  486. ...style
  487. };
  488. }
  489. return (
  490. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  491. <div
  492. className={wrapperCls}
  493. style={wrapperStyle}
  494. onMouseEnter={e => this.handleMouseOver(e)}
  495. onMouseLeave={e => this.handleMouseLeave(e)}
  496. onClick={e => this.handleClick(e)}
  497. >
  498. {this.renderPrepend()}
  499. {this.renderPrefix()}
  500. <input {...inputProps} ref={ref} />
  501. {this.renderClearBtn()}
  502. {this.renderSuffix(suffixAllowClear)}
  503. {this.renderModeBtn()}
  504. {this.renderAppend()}
  505. </div>
  506. );
  507. }
  508. }
  509. const ForwardInput = React.forwardRef<HTMLInputElement, Omit<InputProps, 'forwardRef'>>((props, ref) => <Input {...props} forwardRef={ref} />);
  510. export default ForwardInput;
  511. export { Input };