1
0

textarea.tsx 11 KB

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