textarea.tsx 12 KB

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