textarea.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /* eslint-disable no-unused-vars */
  2. import React from 'react';
  3. import cls from 'classnames';
  4. import PropTypes from 'prop-types';
  5. import TextAreaFoundation from '@douyinfe/semi-foundation/input/textareaFoundation';
  6. import { cssClasses } from '@douyinfe/semi-foundation/input/constants';
  7. import BaseComponent, { ValidateStatus } from '../_base/baseComponent';
  8. import '@douyinfe/semi-foundation/input/textarea.scss';
  9. import { noop, omit, isFunction } from 'lodash-es';
  10. import { IconClear } from '@douyinfe/semi-icons';
  11. const prefixCls = cssClasses.PREFIX;
  12. type OmitTextareaAttr =
  13. | 'onChange'
  14. | 'onInput'
  15. | 'prefix'
  16. | 'size'
  17. | 'onFocus'
  18. | 'onBlur'
  19. | 'onKeyDown'
  20. | 'onKeyPress'
  21. | 'onKeyUp';
  22. export interface TextAreaProps extends
  23. Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, OmitTextareaAttr>,
  24. React.RefAttributes<HTMLTextAreaElement> {
  25. autosize?: boolean;
  26. placeholder?: string;
  27. value?: string;
  28. rows?: number;
  29. cols?: number;
  30. maxCount?: number;
  31. validateStatus?: ValidateStatus;
  32. defaultValue?: string;
  33. disabled?: boolean;
  34. readonly?: boolean;
  35. autofocus?: boolean;
  36. showCounter?: boolean;
  37. showClear?: boolean;
  38. onClear?: (e: React.MouseEvent<HTMLTextAreaElement>) => void;
  39. onChange?: (value: string, e: React.MouseEvent<HTMLTextAreaElement>) => void;
  40. onBlur?: (e: React.MouseEvent<HTMLTextAreaElement>) => void;
  41. onFocus?: (e: React.MouseEvent<HTMLTextAreaElement>) => void;
  42. onInput?: (e: React.MouseEvent<HTMLTextAreaElement>) => void;
  43. onKeyDown?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
  44. onKeyUp?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
  45. onKeyPress?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
  46. onEnterPress?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
  47. onPressEnter?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
  48. onResize?: (data: {height: number}) => void;
  49. getValueLength?: (value: string) => number;
  50. forwardRef?: ((instance: any) => void) | React.MutableRefObject<any> | null;
  51. }
  52. export interface TextAreaState {
  53. value: string;
  54. isFocus: boolean;
  55. isHover: boolean;
  56. height: number;
  57. minLength: number;
  58. cachedValue?: string;
  59. }
  60. class TextArea extends BaseComponent<TextAreaProps, TextAreaState> {
  61. static propTypes = {
  62. autosize: PropTypes.bool,
  63. placeholder: PropTypes.string,
  64. value: PropTypes.string,
  65. rows: PropTypes.number,
  66. cols: PropTypes.number,
  67. maxCount: PropTypes.number,
  68. onEnterPress: PropTypes.func,
  69. validateStatus: PropTypes.string,
  70. className: PropTypes.string,
  71. style: PropTypes.object,
  72. showClear: PropTypes.bool,
  73. onClear: PropTypes.func,
  74. onResize: PropTypes.func,
  75. getValueLength: PropTypes.func,
  76. // TODO
  77. // resize: PropTypes.bool,
  78. };
  79. static defaultProps = {
  80. autosize: false,
  81. rows: 4,
  82. cols: 20,
  83. showCounter: false,
  84. showClear: false,
  85. onEnterPress: noop,
  86. onChange: noop,
  87. onBlur: noop,
  88. onFocus: noop,
  89. onKeyDown: noop,
  90. onResize: noop,
  91. onClear: noop,
  92. // resize: false,
  93. };
  94. focusing: boolean;
  95. libRef: React.RefObject<React.ReactNode>;
  96. _resizeLock: boolean;
  97. _resizeListener: any;
  98. constructor(props: TextAreaProps) {
  99. super(props);
  100. this.state = {
  101. value: '',
  102. isFocus: false,
  103. isHover: false,
  104. height: 0,
  105. minLength: props.minLength,
  106. };
  107. this.focusing = false;
  108. this.foundation = new TextAreaFoundation(this.adapter);
  109. this.libRef = React.createRef();
  110. this._resizeLock = false;
  111. }
  112. get adapter() {
  113. return {
  114. ...super.adapter,
  115. setValue: (value: string) => this.setState({ value }, () => {
  116. if (this.props.autosize) {
  117. this.foundation.resizeTextarea();
  118. }
  119. }),
  120. getRef: () => this.libRef,
  121. toggleFocusing: (focusing: boolean) => this.setState({ isFocus: focusing }),
  122. toggleHovering: (hovering: boolean) => this.setState({ isHover: hovering }),
  123. notifyChange: (val: string, e: React.MouseEvent<HTMLTextAreaElement>) => {
  124. this.props.onChange(val, e);
  125. },
  126. notifyClear: (e: React.MouseEvent<HTMLTextAreaElement>) => this.props.onClear(e),
  127. notifyBlur: (val: string, e: React.MouseEvent<HTMLTextAreaElement>) => this.props.onBlur(e),
  128. notifyFocus: (val: string, e: React.MouseEvent<HTMLTextAreaElement>) => this.props.onFocus(e),
  129. notifyKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  130. this.props.onKeyDown(e);
  131. },
  132. notifyHeightUpdate: (height: number) => {
  133. this.setState({ height });
  134. this.props.onResize({ height });
  135. },
  136. notifyPressEnter: (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  137. this.props.onEnterPress && this.props.onEnterPress(e);
  138. },
  139. setMinLength: (minLength: number) => this.setState({ minLength }),
  140. };
  141. }
  142. static getDerivedStateFromProps(props: TextAreaProps, state: TextAreaState) {
  143. const willUpdateStates: Partial<TextAreaState> = {};
  144. if (props.value !== state.cachedValue) {
  145. willUpdateStates.value = props.value;
  146. willUpdateStates.cachedValue = props.value;
  147. }
  148. return willUpdateStates;
  149. }
  150. componentDidMount() {
  151. this.foundation.init();
  152. this._resizeListener = null;
  153. if (this.props.autosize) {
  154. // Working around Firefox bug which runs resize listeners even when other JS is running at the same moment
  155. // causing competing rerenders (due to setState in the listener) in React.
  156. // More can be found here - facebook/react#6324
  157. // // Reference to https://github.com/andreypopp/react-textarea-autosize/
  158. this._resizeListener = () => {
  159. if (this._resizeLock) {
  160. return;
  161. }
  162. this._resizeLock = true;
  163. this.foundation.resizeTextarea(() => {
  164. this._resizeLock = false;
  165. });
  166. };
  167. window.addEventListener('resize', this._resizeListener);
  168. }
  169. }
  170. componentWillUnmount() {
  171. this.foundation.destroy();
  172. this._resizeListener && window.removeEventListener('resize', this._resizeListener);
  173. }
  174. componentDidUpdate(prevProps: TextAreaProps, prevState: TextAreaState) {
  175. if (this.props.value !== prevProps.value && this.props.autosize) {
  176. this.foundation.resizeTextarea();
  177. }
  178. }
  179. handleClear = (e: React.MouseEvent<HTMLDivElement>) => {
  180. this.foundation.handleClear(e);
  181. };
  182. renderClearBtn() {
  183. const { showClear } = this.props;
  184. const displayClearBtn = this.foundation.isAllowClear();
  185. const clearCls = cls(`${prefixCls}-clearbtn`, {
  186. [`${prefixCls}-clearbtn-hidden`]: !displayClearBtn,
  187. });
  188. if (showClear) {
  189. return (
  190. <div className={clearCls} onClick={this.handleClear}>
  191. <IconClear />
  192. </div>
  193. );
  194. }
  195. return null;
  196. }
  197. renderCounter() {
  198. let counter,
  199. current,
  200. total,
  201. countCls;
  202. const { showCounter, maxCount, getValueLength } = this.props;
  203. if (showCounter || maxCount) {
  204. const { value } = this.state;
  205. // eslint-disable-next-line no-nested-ternary
  206. current = value ? isFunction(getValueLength) ? getValueLength(value) : value.length : 0;
  207. total = maxCount || null;
  208. countCls = cls(
  209. `${prefixCls}-textarea-counter`,
  210. {
  211. [`${prefixCls}-textarea-counter-exceed`]: current > total
  212. }
  213. );
  214. counter = (
  215. <div className={countCls}>{current}{total ? '/' : null}{total}</div>
  216. );
  217. } else {
  218. counter = null;
  219. }
  220. return counter;
  221. }
  222. setRef = (node: React.ReactNode) => {
  223. (this.libRef as any).current = node;
  224. const { forwardRef } = this.props;
  225. if (typeof forwardRef === 'function') {
  226. forwardRef(node);
  227. } else if (forwardRef && typeof forwardRef === 'object') {
  228. forwardRef.current = node;
  229. }
  230. };
  231. render() {
  232. const {
  233. autosize,
  234. placeholder,
  235. onEnterPress,
  236. onResize,
  237. // resize,
  238. disabled,
  239. readonly,
  240. className,
  241. showCounter,
  242. validateStatus,
  243. maxCount,
  244. defaultValue,
  245. style,
  246. forwardRef,
  247. getValueLength,
  248. maxLength,
  249. minLength,
  250. showClear,
  251. ...rest
  252. } = this.props;
  253. const { isFocus, value, minLength: stateMinLength } = this.state;
  254. const wrapperCls = cls(
  255. className,
  256. `${prefixCls}-textarea-wrapper`,
  257. {
  258. [`${prefixCls}-textarea-wrapper-disabled`]: disabled || readonly,
  259. [`${prefixCls}-textarea-wrapper-${validateStatus}`]: Boolean(validateStatus),
  260. [`${prefixCls}-textarea-wrapper-focus`]: isFocus,
  261. // [`${prefixCls}-textarea-wrapper-resize`]: !autosize && resize,
  262. }
  263. );
  264. // const ref = this.props.forwardRef || this.textAreaRef;
  265. const itemCls = cls(
  266. `${prefixCls}-textarea`,
  267. {
  268. [`${prefixCls}-textarea-disabled`]: disabled || readonly,
  269. [`${prefixCls}-textarea-autosize`]: autosize,
  270. [`${prefixCls}-textarea-showClear`]: showClear,
  271. }
  272. );
  273. const itemProps = {
  274. ...omit(rest, 'insetLabel', 'getValueLength', 'onClear', 'showClear'),
  275. className: itemCls,
  276. disabled,
  277. readOnly: readonly,
  278. placeholder: !placeholder ? null : placeholder,
  279. onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => this.foundation.handleChange(e.target.value, e),
  280. onFocus: (e: React.FocusEvent<HTMLTextAreaElement>) => this.foundation.handleFocus(e),
  281. onBlur: (e: React.FocusEvent<HTMLTextAreaElement>) => this.foundation.handleBlur(e.nativeEvent),
  282. onKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => this.foundation.handleKeyDown(e),
  283. value: value === null || value === undefined ? '' : value,
  284. };
  285. if (!isFunction(getValueLength)) {
  286. (itemProps as any).maxLength = maxLength;
  287. }
  288. if (stateMinLength) {
  289. (itemProps as any).minLength = stateMinLength;
  290. }
  291. return (
  292. <div
  293. className={wrapperCls}
  294. style={style}
  295. onMouseEnter={e => this.foundation.handleMouseEnter(e)}
  296. onMouseLeave={e => this.foundation.handleMouseLeave(e)}
  297. >
  298. <textarea {...itemProps} ref={this.setRef} />
  299. {this.renderClearBtn()}
  300. {this.renderCounter()}
  301. </div>
  302. );
  303. }
  304. }
  305. const ForwardTextarea = React.forwardRef((props, ref) => <TextArea {...props} forwardRef={ref} />);
  306. export default ForwardTextarea;