index.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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 } from 'lodash-es';
  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 { InputGroupProps } from './inputGroup';
  17. export { 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. addonBefore?: React.ReactNode;
  26. addonAfter?: React.ReactNode;
  27. prefix?: React.ReactNode;
  28. suffix?: React.ReactNode;
  29. mode?: InputMode;
  30. value?: React.ReactText;
  31. defaultValue?: React.ReactText;
  32. disabled?: boolean;
  33. readonly?: boolean;
  34. autofocus?: boolean;
  35. type?: string;
  36. showClear?: boolean;
  37. hideSuffix?: boolean;
  38. placeholder?: React.ReactText;
  39. insetLabel?: React.ReactNode;
  40. size?: InputSize;
  41. className?: string;
  42. style?: React.CSSProperties;
  43. validateStatus?: ValidateStatus;
  44. onClear?: (e: React.MouseEvent<HTMLDivElement>) => void;
  45. onChange?: (value: string, e: React.ChangeEvent<HTMLInputElement>) => void;
  46. onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void;
  47. onFocus?: (e: React.FocusEvent<HTMLInputElement>) => void;
  48. onInput?: (e: React.MouseEvent<HTMLInputElement>) => void;
  49. onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  50. onKeyUp?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  51. onKeyPress?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  52. onEnterPress?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
  53. inputStyle?: React.CSSProperties;
  54. getValueLength?: (value: string) => number;
  55. forwardRef?: ((instance: any) => void) | React.MutableRefObject<any> | null;
  56. }
  57. export interface InputState {
  58. value: React.ReactText;
  59. cachedValue: React.ReactText;
  60. disabled: boolean;
  61. props: Record<string, any>;
  62. paddingLeft: string;
  63. isFocus: boolean;
  64. isHovering: boolean;
  65. eyeClosed: boolean;
  66. minLength: number;
  67. }
  68. class Input extends BaseComponent<InputProps, InputState> {
  69. static propTypes = {
  70. addonBefore: PropTypes.node,
  71. addonAfter: PropTypes.node,
  72. prefix: PropTypes.node,
  73. suffix: PropTypes.node,
  74. mode: PropTypes.oneOf(modeSet),
  75. value: PropTypes.any,
  76. defaultValue: PropTypes.any,
  77. disabled: PropTypes.bool,
  78. readonly: PropTypes.bool,
  79. autofocus: PropTypes.bool,
  80. type: PropTypes.string,
  81. showClear: PropTypes.bool,
  82. hideSuffix: PropTypes.bool,
  83. placeholder: PropTypes.any,
  84. size: PropTypes.oneOf(sizeSet),
  85. className: PropTypes.string,
  86. style: PropTypes.object,
  87. validateStatus: PropTypes.oneOf(statusSet),
  88. onClear: PropTypes.func,
  89. onChange: PropTypes.func,
  90. onBlur: PropTypes.func,
  91. onFocus: PropTypes.func,
  92. onInput: PropTypes.func,
  93. onKeyDown: PropTypes.func,
  94. onKeyUp: PropTypes.func,
  95. onKeyPress: PropTypes.func,
  96. onEnterPress: PropTypes.func,
  97. insetLabel: PropTypes.node,
  98. inputStyle: PropTypes.object,
  99. getValueLength: PropTypes.func,
  100. };
  101. static defaultProps = {
  102. addonBefore: '',
  103. addonAfter: '',
  104. prefix: '',
  105. suffix: '',
  106. disabled: false,
  107. readonly: false,
  108. type: 'text',
  109. showClear: false,
  110. hideSuffix: false,
  111. placeholder: '',
  112. size: 'default',
  113. className: '',
  114. onClear: noop,
  115. onChange: noop,
  116. onBlur: noop,
  117. onFocus: noop,
  118. onInput: noop,
  119. onKeyDown: noop,
  120. onKeyUp: noop,
  121. onKeyPress: noop,
  122. onEnterPress: noop,
  123. validateStatus: 'default'
  124. };
  125. inputRef!: React.RefObject<HTMLInputElement>;
  126. prefixRef!: React.RefObject<React.ReactNode>;
  127. suffixRef!: React.RefObject<React.ReactNode>;
  128. foundation!: InputFoundation;
  129. constructor(props: InputProps) {
  130. super(props);
  131. this.state = {
  132. value: '',
  133. cachedValue: null, // Cache current props.value value
  134. disabled: false,
  135. props: {},
  136. paddingLeft: '',
  137. isFocus: false,
  138. isHovering: false,
  139. eyeClosed: props.mode === 'password',
  140. minLength: props.minLength,
  141. };
  142. this.inputRef = React.createRef();
  143. this.prefixRef = React.createRef();
  144. this.suffixRef = React.createRef();
  145. this.foundation = new InputFoundation(this.adapter);
  146. }
  147. get adapter() {
  148. return {
  149. ...super.adapter,
  150. setValue: (value: string) => this.setState({ value }),
  151. setEyeClosed: (value: boolean) => this.setState({ eyeClosed: value }),
  152. toggleFocusing: (isFocus: boolean) => {
  153. const input = this.inputRef && this.inputRef.current;
  154. if (isFocus) {
  155. input && input.focus();
  156. } else {
  157. input && input.blur();
  158. }
  159. this.setState({ isFocus });
  160. },
  161. toggleHovering: (isHovering: boolean) => this.setState({ isHovering }),
  162. getIfFocusing: () => this.state.isFocus,
  163. notifyChange: (cbValue: string, e: React.ChangeEvent<HTMLInputElement>) => this.props.onChange(cbValue, e),
  164. notifyBlur: (val: string, e: React.FocusEvent<HTMLInputElement>) => this.props.onBlur(e),
  165. notifyFocus: (val: string, e: React.FocusEvent<HTMLInputElement>) => this.props.onFocus(e),
  166. notifyInput: (e: React.MouseEvent<HTMLInputElement>) => this.props.onInput(e),
  167. notifyKeyPress: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyPress(e),
  168. notifyKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyDown(e),
  169. notifyKeyUp: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onKeyUp(e),
  170. notifyEnterPress: (e: React.KeyboardEvent<HTMLInputElement>) => this.props.onEnterPress(e),
  171. notifyClear: (e: React.MouseEvent<HTMLDivElement>) => this.props.onClear(e),
  172. setPaddingLeft: (paddingLeft: string) => this.setState({ paddingLeft }),
  173. setMinLength: (minLength: number) => this.setState({ minLength }),
  174. isEventTarget: (e: React.MouseEvent) => e && e.target === e.currentTarget
  175. };
  176. }
  177. static getDerivedStateFromProps(props: InputProps, state: InputState) {
  178. const willUpdateStates: Partial<InputState> = {};
  179. if (props.value !== state.cachedValue) {
  180. willUpdateStates.value = props.value;
  181. willUpdateStates.cachedValue = props.value;
  182. }
  183. return willUpdateStates;
  184. }
  185. componentDidUpdate(prevProps: InputProps) {
  186. const { mode } = this.props;
  187. if (prevProps.mode !== mode) {
  188. this.handleModeChange(mode);
  189. }
  190. }
  191. handleClear = (e: React.MouseEvent<HTMLInputElement>) => {
  192. this.foundation.handleClear(e);
  193. };
  194. handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
  195. this.foundation.handleClick(e);
  196. };
  197. handleMouseOver = (e: React.MouseEvent<HTMLDivElement>) => {
  198. this.setState({ isHovering: true });
  199. };
  200. handleMouseLeave = (e: React.MouseEvent<HTMLDivElement>) => {
  201. this.setState({ isHovering: false });
  202. };
  203. handleModeChange = (mode: string) => {
  204. this.foundation.handleModeChange(mode);
  205. };
  206. handleClickEye = (e: React.MouseEvent<HTMLInputElement>) => {
  207. this.foundation.handleClickEye(e);
  208. };
  209. handleMouseDown = (e: React.MouseEvent<HTMLInputElement>) => {
  210. this.foundation.handleMouseDown(e);
  211. };
  212. handleMouseUp = (e: React.MouseEvent<HTMLInputElement>) => {
  213. this.foundation.handleMouseUp(e);
  214. };
  215. handleClickPrefixOrSuffix = (e: React.MouseEvent<HTMLInputElement>) => {
  216. this.foundation.handleClickPrefixOrSuffix(e);
  217. };
  218. handlePreventMouseDown = (e: React.MouseEvent<HTMLInputElement>) => {
  219. this.foundation.handlePreventMouseDown(e);
  220. };
  221. renderPrepend() {
  222. const { addonBefore } = this.props;
  223. if (addonBefore) {
  224. const prefixWrapperCls = cls({
  225. [`${prefixCls}-prepend`]: true,
  226. [`${prefixCls}-prepend-text`]: addonBefore && isString(addonBefore),
  227. [`${prefixCls}-prepend-icon`]: isSemiIcon(addonBefore),
  228. });
  229. return <div className={prefixWrapperCls}>{addonBefore}</div>;
  230. }
  231. return null;
  232. }
  233. renderAppend() {
  234. const { addonAfter } = this.props;
  235. if (addonAfter) {
  236. const prefixWrapperCls = cls({
  237. [`${prefixCls}-append`]: true,
  238. [`${prefixCls}-append-text`]: addonAfter && isString(addonAfter),
  239. [`${prefixCls}-append-icon`]: isSemiIcon(addonAfter),
  240. });
  241. return <div className={prefixWrapperCls}>{addonAfter}</div>;
  242. }
  243. return null;
  244. }
  245. renderClearBtn() {
  246. const clearCls = cls(`${prefixCls}-clearbtn`);
  247. const allowClear = this.foundation.isAllowClear();
  248. // use onMouseDown to fix issue 1203
  249. if (allowClear) {
  250. return (
  251. <div className={clearCls} onMouseDown={this.handleClear}>
  252. <IconClear />
  253. </div>
  254. );
  255. }
  256. return null;
  257. }
  258. renderModeBtn() {
  259. const { value, isFocus, isHovering, eyeClosed } = this.state;
  260. const { mode, disabled } = this.props;
  261. const modeCls = cls(`${prefixCls}-modebtn`);
  262. const modeIcon = eyeClosed ? <IconEyeClosedSolid /> : <IconEyeOpened />;
  263. const showModeBtn = mode === 'password' && value && !disabled && (isFocus || isHovering);
  264. if (showModeBtn) {
  265. return (
  266. <div className={modeCls} onClick={this.handleClickEye} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}>
  267. {modeIcon}
  268. </div>
  269. );
  270. }
  271. return null;
  272. }
  273. renderPrefix() {
  274. const { prefix, insetLabel } = this.props;
  275. const labelNode = prefix || insetLabel;
  276. if (!labelNode) {
  277. return null;
  278. }
  279. const prefixWrapperCls = cls({
  280. [`${prefixCls}-prefix`]: true,
  281. [`${prefixCls}-inset-label`]: insetLabel,
  282. [`${prefixCls}-prefix-text`]: labelNode && isString(labelNode),
  283. [`${prefixCls}-prefix-icon`]: isSemiIcon(labelNode),
  284. });
  285. return <div className={prefixWrapperCls} onMouseDown={this.handlePreventMouseDown} onClick={this.handleClickPrefixOrSuffix}>{labelNode}</div>;
  286. }
  287. showClearBtn() {
  288. const { value, isFocus, isHovering } = this.state;
  289. const { disabled, showClear } = this.props;
  290. return Boolean(value) && showClear && !disabled && (isFocus || isHovering);
  291. }
  292. renderSuffix(suffixAllowClear: boolean) {
  293. const { suffix, hideSuffix } = this.props;
  294. if (!suffix) {
  295. return null;
  296. }
  297. const suffixWrapperCls = cls({
  298. [`${prefixCls }-suffix`]: true,
  299. [`${prefixCls }-suffix-text`]: suffix && isString(suffix),
  300. [`${prefixCls }-suffix-icon`]: isSemiIcon(suffix),
  301. [`${prefixCls}-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  302. });
  303. return <div className={suffixWrapperCls} onMouseDown={this.handlePreventMouseDown} onClick={this.handleClickPrefixOrSuffix}>{suffix}</div>;
  304. }
  305. render() {
  306. const {
  307. addonAfter,
  308. addonBefore,
  309. autofocus,
  310. className,
  311. disabled,
  312. placeholder,
  313. prefix,
  314. mode,
  315. insetLabel,
  316. validateStatus,
  317. type,
  318. readonly,
  319. size,
  320. suffix,
  321. style,
  322. showClear,
  323. onEnterPress,
  324. onClear,
  325. hideSuffix,
  326. inputStyle,
  327. forwardRef,
  328. maxLength,
  329. getValueLength,
  330. ...rest
  331. } = this.props;
  332. const { value, paddingLeft, isFocus, minLength: stateMinLength } = this.state;
  333. const suffixAllowClear = this.showClearBtn();
  334. const suffixIsIcon = isSemiIcon(suffix);
  335. const ref = forwardRef || this.inputRef;
  336. const wrapperPrefix = `${prefixCls}-wrapper`;
  337. const wrapperCls = cls(wrapperPrefix, className, {
  338. [`${prefixCls}-wrapper__with-prefix`]: prefix || insetLabel,
  339. [`${prefixCls}-wrapper__with-suffix`]: suffix,
  340. [`${prefixCls}-wrapper__with-suffix-hidden`]: suffixAllowClear && Boolean(hideSuffix),
  341. [`${prefixCls}-wrapper__with-suffix-icon`]: suffixIsIcon,
  342. [`${prefixCls}-wrapper__with-append`]: addonBefore,
  343. [`${prefixCls}-wrapper__with-prepend`]: addonAfter,
  344. [`${prefixCls}-wrapper__with-append-only`]: addonBefore && !addonAfter,
  345. [`${prefixCls}-wrapper__with-prepend-only`]: !addonBefore && addonAfter,
  346. [`${wrapperPrefix}-readonly`]: readonly,
  347. [`${wrapperPrefix}-disabled`]: disabled,
  348. [`${wrapperPrefix}-warning`]: validateStatus === 'warning',
  349. [`${wrapperPrefix}-error`]: validateStatus === 'error',
  350. [`${wrapperPrefix}-focus`]: isFocus,
  351. [`${wrapperPrefix}-clearable`]: showClear,
  352. [`${wrapperPrefix}-modebtn`]: mode === 'password',
  353. [`${wrapperPrefix}-hidden`]: type === 'hidden',
  354. [`${wrapperPrefix}-${size}`]: size,
  355. });
  356. const inputCls = cls(prefixCls, {
  357. [`${prefixCls}-${size}`]: size,
  358. [`${prefixCls}-disabled`]: disabled,
  359. [`${prefixCls}-sibling-clearbtn`]: this.foundation.isAllowClear(),
  360. [`${prefixCls}-sibling-modebtn`]: mode === 'password',
  361. });
  362. const inputValue = value === null || value === undefined ? '' : value;
  363. const inputProps: React.InputHTMLAttributes<HTMLInputElement> = {
  364. ...rest,
  365. style: { paddingLeft, ...inputStyle },
  366. autoFocus: autofocus,
  367. className: inputCls,
  368. disabled,
  369. readOnly: readonly,
  370. type: this.foundation.handleInputType(type),
  371. placeholder: placeholder as string,
  372. onInput: e => this.foundation.handleInput(e),
  373. onChange: e => this.foundation.handleChange(e.target.value, e),
  374. onFocus: e => this.foundation.handleFocus(e),
  375. onBlur: e => this.foundation.handleBlur(e),
  376. onKeyUp: e => this.foundation.handleKeyUp(e),
  377. onKeyDown: e => this.foundation.handleKeyDown(e),
  378. onKeyPress: e => this.foundation.handleKeyPress(e),
  379. value: inputValue,
  380. };
  381. if (!isFunction(getValueLength)) {
  382. inputProps.maxLength = maxLength;
  383. }
  384. if (stateMinLength) {
  385. inputProps.minLength = stateMinLength;
  386. }
  387. return (
  388. <div
  389. className={wrapperCls}
  390. style={style}
  391. onMouseEnter={e => this.handleMouseOver(e)}
  392. onMouseLeave={e => this.handleMouseLeave(e)}
  393. onClick={e => this.handleClick(e)}
  394. >
  395. {this.renderPrepend()}
  396. {this.renderPrefix()}
  397. <input {...inputProps} ref={ref} />
  398. {this.renderClearBtn()}
  399. {this.renderSuffix(suffixAllowClear)}
  400. {this.renderModeBtn()}
  401. {this.renderAppend()}
  402. </div>
  403. );
  404. }
  405. }
  406. const ForwardInput = React.forwardRef<HTMLInputElement, Omit<InputProps, 'forwardRef'>>((props, ref) => <Input {...props} forwardRef={ref} />);
  407. export default ForwardInput;
  408. export { Input };