textarea.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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';
  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. foundation: TextAreaFoundation;
  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. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  191. <div
  192. className={clearCls}
  193. onClick={this.handleClear}
  194. >
  195. <IconClear />
  196. </div>
  197. );
  198. }
  199. return null;
  200. }
  201. renderCounter() {
  202. let counter: React.ReactNode,
  203. current: number,
  204. total: number,
  205. countCls: string;
  206. const { showCounter, maxCount, getValueLength } = this.props;
  207. if (showCounter || maxCount) {
  208. const { value } = this.state;
  209. // eslint-disable-next-line no-nested-ternary
  210. current = value ? isFunction(getValueLength) ? getValueLength(value) : value.length : 0;
  211. total = maxCount || null;
  212. countCls = cls(
  213. `${prefixCls}-textarea-counter`,
  214. {
  215. [`${prefixCls}-textarea-counter-exceed`]: current > total
  216. }
  217. );
  218. counter = (
  219. <div className={countCls}>
  220. {current}{total ? '/' : null}{total}
  221. </div>
  222. );
  223. } else {
  224. counter = null;
  225. }
  226. return counter;
  227. }
  228. setRef = (node: HTMLTextAreaElement) => {
  229. (this.libRef as any).current = node;
  230. const { forwardRef } = this.props;
  231. if (typeof forwardRef === 'function') {
  232. forwardRef(node);
  233. } else if (forwardRef && typeof forwardRef === 'object') {
  234. forwardRef.current = node;
  235. }
  236. };
  237. render() {
  238. const {
  239. autosize,
  240. placeholder,
  241. onEnterPress,
  242. onResize,
  243. // resize,
  244. disabled,
  245. readonly,
  246. className,
  247. showCounter,
  248. validateStatus,
  249. maxCount,
  250. defaultValue,
  251. style,
  252. forwardRef,
  253. getValueLength,
  254. maxLength,
  255. minLength,
  256. showClear,
  257. ...rest
  258. } = this.props;
  259. const { isFocus, value, minLength: stateMinLength } = this.state;
  260. const wrapperCls = cls(
  261. className,
  262. `${prefixCls}-textarea-wrapper`,
  263. {
  264. [`${prefixCls}-textarea-wrapper-disabled`]: disabled,
  265. [`${prefixCls}-textarea-wrapper-readonly`]: readonly,
  266. [`${prefixCls}-textarea-wrapper-${validateStatus}`]: Boolean(validateStatus),
  267. [`${prefixCls}-textarea-wrapper-focus`]: isFocus,
  268. // [`${prefixCls}-textarea-wrapper-resize`]: !autosize && resize,
  269. }
  270. );
  271. // const ref = this.props.forwardRef || this.textAreaRef;
  272. const itemCls = cls(
  273. `${prefixCls}-textarea`,
  274. {
  275. [`${prefixCls}-textarea-disabled`]: disabled,
  276. [`${prefixCls}-textarea-readonly`]: readonly,
  277. [`${prefixCls}-textarea-autosize`]: autosize,
  278. [`${prefixCls}-textarea-showClear`]: showClear,
  279. }
  280. );
  281. const itemProps = {
  282. ...omit(rest, 'insetLabel', 'insetLabelId', 'getValueLength', 'onClear', 'showClear'),
  283. className: itemCls,
  284. disabled,
  285. readOnly: readonly,
  286. placeholder: !placeholder ? null : placeholder,
  287. onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => this.foundation.handleChange(e.target.value, e),
  288. onFocus: (e: React.FocusEvent<HTMLTextAreaElement>) => this.foundation.handleFocus(e),
  289. onBlur: (e: React.FocusEvent<HTMLTextAreaElement>) => this.foundation.handleBlur(e.nativeEvent),
  290. onKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => this.foundation.handleKeyDown(e),
  291. value: value === null || value === undefined ? '' : value,
  292. };
  293. if (!isFunction(getValueLength)) {
  294. (itemProps as any).maxLength = maxLength;
  295. }
  296. if (stateMinLength) {
  297. (itemProps as any).minLength = stateMinLength;
  298. }
  299. return (
  300. <div
  301. className={wrapperCls}
  302. style={style}
  303. onMouseEnter={e => this.foundation.handleMouseEnter(e)}
  304. onMouseLeave={e => this.foundation.handleMouseLeave(e)}
  305. >
  306. <textarea {...itemProps} ref={this.setRef} />
  307. {this.renderClearBtn()}
  308. {this.renderCounter()}
  309. </div>
  310. );
  311. }
  312. }
  313. const ForwardTextarea = React.forwardRef<HTMLTextAreaElement, Omit<TextAreaProps, 'forwardRef'>>((props, ref) => <TextArea {...props} forwardRef={ref} />);
  314. export default ForwardTextarea;