textarea.tsx 12 KB

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