index.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. import React from 'react';
  2. import cls from 'classnames';
  3. import PropTypes from 'prop-types';
  4. import {
  5. noop,
  6. isString,
  7. isArray,
  8. isNull,
  9. isUndefined,
  10. isFunction
  11. } from 'lodash';
  12. import { cssClasses, strings } from '@douyinfe/semi-foundation/tagInput/constants';
  13. import '@douyinfe/semi-foundation/tagInput/tagInput.scss';
  14. import TagInputFoundation, { TagInputAdapter, OnSortEndProps } from '@douyinfe/semi-foundation/tagInput/foundation';
  15. import { ArrayElement } from '../_base/base';
  16. import { isSemiIcon } from '../_utils';
  17. import BaseComponent from '../_base/baseComponent';
  18. import Tag from '../tag';
  19. import Input from '../input';
  20. import Popover, { PopoverProps } from '../popover';
  21. import Paragraph from '../typography/paragraph';
  22. import { IconClear, IconHandle } from '@douyinfe/semi-icons';
  23. import { SortableContainer, SortableElement, SortableHandle } from 'react-sortable-hoc';
  24. const prefixCls = cssClasses.PREFIX;
  25. export type Size = ArrayElement<typeof strings.SIZE_SET>;
  26. export type RestTagsPopoverProps = PopoverProps;
  27. type ValidateStatus = "default" | "error" | "warning";
  28. const SortableItem = SortableElement(props => props.item);
  29. const SortableList = SortableContainer(
  30. ({ items }) => {
  31. return (
  32. <div className={`${prefixCls}-sortable-list`}>
  33. {items.map((item, index) => (
  34. // @ts-ignore skip SortableItem type check
  35. <SortableItem key={item.key} index={index} item={item.item}></SortableItem>
  36. ))}
  37. </div>
  38. );
  39. });
  40. export interface TagInputProps {
  41. className?: string;
  42. clearIcon?: React.ReactNode;
  43. defaultValue?: string[];
  44. disabled?: boolean;
  45. inputValue?: string;
  46. maxLength?: number;
  47. max?: number;
  48. maxTagCount?: number;
  49. showRestTagsPopover?: boolean;
  50. restTagsPopoverProps?: RestTagsPopoverProps;
  51. showContentTooltip?: boolean;
  52. allowDuplicates?: boolean;
  53. addOnBlur?: boolean;
  54. draggable?: boolean;
  55. expandRestTagsOnClick?: boolean;
  56. onAdd?: (addedValue: string[]) => void;
  57. onBlur?: (e: React.MouseEvent<HTMLInputElement>) => void;
  58. onChange?: (value: string[]) => void;
  59. onExceed?: ((value: string[]) => void);
  60. onFocus?: (e: React.MouseEvent<HTMLInputElement>) => void;
  61. onInputChange?: (value: string, e: React.MouseEvent<HTMLInputElement>) => void;
  62. onInputExceed?: ((value: string) => void);
  63. onKeyDown?: (e: React.MouseEvent<HTMLInputElement>) => void;
  64. onRemove?: (removedValue: string, idx: number) => void;
  65. placeholder?: string;
  66. insetLabel?: React.ReactNode;
  67. insetLabelId?: string;
  68. prefix?: React.ReactNode;
  69. renderTagItem?: (value: string, index: number, onClose: () => void) => React.ReactNode;
  70. separator?: string | string[] | null;
  71. showClear?: boolean;
  72. size?: Size;
  73. style?: React.CSSProperties;
  74. suffix?: React.ReactNode;
  75. validateStatus?: ValidateStatus;
  76. value?: string[] | undefined;
  77. autoFocus?: boolean;
  78. 'aria-label'?: string;
  79. preventScroll?: boolean
  80. }
  81. export interface TagInputState {
  82. tagsArray?: string[];
  83. inputValue?: string;
  84. focusing?: boolean;
  85. hovering?: boolean;
  86. active?: boolean;
  87. // entering: Used to identify whether the user is in a new composition session(eg,Input Chinese)
  88. entering?: boolean
  89. }
  90. class TagInput extends BaseComponent<TagInputProps, TagInputState> {
  91. static propTypes = {
  92. children: PropTypes.node,
  93. clearIcon: PropTypes.node,
  94. style: PropTypes.object,
  95. className: PropTypes.string,
  96. disabled: PropTypes.bool,
  97. allowDuplicates: PropTypes.bool,
  98. max: PropTypes.number,
  99. maxTagCount: PropTypes.number,
  100. maxLength: PropTypes.number,
  101. showRestTagsPopover: PropTypes.bool,
  102. restTagsPopoverProps: PropTypes.object,
  103. showContentTooltip: PropTypes.bool,
  104. defaultValue: PropTypes.array,
  105. value: PropTypes.array,
  106. inputValue: PropTypes.string,
  107. placeholder: PropTypes.string,
  108. separator: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
  109. showClear: PropTypes.bool,
  110. addOnBlur: PropTypes.bool,
  111. draggable: PropTypes.bool,
  112. expandRestTagsOnClick: PropTypes.bool,
  113. autoFocus: PropTypes.bool,
  114. renderTagItem: PropTypes.func,
  115. onBlur: PropTypes.func,
  116. onFocus: PropTypes.func,
  117. onChange: PropTypes.func,
  118. onInputChange: PropTypes.func,
  119. onExceed: PropTypes.func,
  120. onInputExceed: PropTypes.func,
  121. onAdd: PropTypes.func,
  122. onRemove: PropTypes.func,
  123. onKeyDown: PropTypes.func,
  124. size: PropTypes.oneOf(strings.SIZE_SET),
  125. validateStatus: PropTypes.oneOf(strings.STATUS),
  126. prefix: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  127. suffix: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  128. 'aria-label': PropTypes.string,
  129. preventScroll: PropTypes.bool,
  130. };
  131. static defaultProps = {
  132. showClear: false,
  133. addOnBlur: false,
  134. allowDuplicates: true,
  135. showRestTagsPopover: true,
  136. autoFocus: false,
  137. draggable: false,
  138. expandRestTagsOnClick: true,
  139. showContentTooltip: true,
  140. separator: ',',
  141. size: 'default' as const,
  142. validateStatus: 'default' as const,
  143. onBlur: noop,
  144. onFocus: noop,
  145. onChange: noop,
  146. onInputChange: noop,
  147. onExceed: noop,
  148. onInputExceed: noop,
  149. onAdd: noop,
  150. onRemove: noop,
  151. onKeyDown: noop,
  152. };
  153. inputRef: React.RefObject<HTMLInputElement>;
  154. tagInputRef: React.RefObject<HTMLDivElement>;
  155. foundation: TagInputFoundation;
  156. clickOutsideHandler: any;
  157. constructor(props: TagInputProps) {
  158. super(props);
  159. this.foundation = new TagInputFoundation(this.adapter);
  160. this.state = {
  161. tagsArray: props.defaultValue || [],
  162. inputValue: '',
  163. focusing: false,
  164. hovering: false,
  165. active: false,
  166. entering: false,
  167. };
  168. this.inputRef = React.createRef();
  169. this.tagInputRef = React.createRef();
  170. this.clickOutsideHandler = null;
  171. }
  172. static getDerivedStateFromProps(nextProps: TagInputProps, prevState: TagInputState) {
  173. const { value, inputValue } = nextProps;
  174. const { tagsArray: prevTagsArray } = prevState;
  175. let tagsArray: string[];
  176. if (isArray(value)) {
  177. tagsArray = value;
  178. } else if ('value' in nextProps && !value) {
  179. tagsArray = [];
  180. } else {
  181. tagsArray = prevTagsArray;
  182. }
  183. return {
  184. tagsArray,
  185. inputValue: isString(inputValue) ? inputValue : prevState.inputValue
  186. };
  187. }
  188. get adapter(): TagInputAdapter {
  189. return {
  190. ...super.adapter,
  191. setInputValue: (inputValue: string) => {
  192. this.setState({ inputValue });
  193. },
  194. setTagsArray: (tagsArray: string[]) => {
  195. this.setState({ tagsArray });
  196. },
  197. setFocusing: (focusing: boolean) => {
  198. this.setState({ focusing });
  199. },
  200. toggleFocusing: (isFocus: boolean) => {
  201. const { preventScroll } = this.props;
  202. const input = this.inputRef && this.inputRef.current;
  203. if (isFocus) {
  204. input && input.focus({ preventScroll });
  205. } else {
  206. input && input.blur();
  207. }
  208. this.setState({ focusing: isFocus });
  209. },
  210. setHovering: (hovering: boolean) => {
  211. this.setState({ hovering });
  212. },
  213. setActive: (active: boolean) => {
  214. this.setState({ active });
  215. },
  216. setEntering: (entering: boolean) => {
  217. this.setState({ entering });
  218. },
  219. getClickOutsideHandler: () => {
  220. return this.clickOutsideHandler;
  221. },
  222. notifyBlur: (e: React.MouseEvent<HTMLInputElement>) => {
  223. this.props.onBlur(e);
  224. },
  225. notifyFocus: (e: React.MouseEvent<HTMLInputElement>) => {
  226. this.props.onFocus(e);
  227. },
  228. notifyInputChange: (v: string, e: React.MouseEvent<HTMLInputElement>) => {
  229. this.props.onInputChange(v, e);
  230. },
  231. notifyTagChange: (v: string[]) => {
  232. this.props.onChange(v);
  233. },
  234. notifyTagAdd: (v: string[]) => {
  235. this.props.onAdd(v);
  236. },
  237. notifyTagRemove: (v: string, idx: number) => {
  238. this.props.onRemove(v, idx);
  239. },
  240. notifyKeyDown: e => {
  241. this.props.onKeyDown(e);
  242. },
  243. registerClickOutsideHandler: cb => {
  244. const clickOutsideHandler = (e: Event) => {
  245. const tagInputDom = this.tagInputRef && this.tagInputRef.current;
  246. const target = e.target as Element;
  247. if (tagInputDom && !tagInputDom.contains(target)) {
  248. cb(e);
  249. }
  250. };
  251. this.clickOutsideHandler = clickOutsideHandler;
  252. document.addEventListener('click', clickOutsideHandler, false);
  253. },
  254. unregisterClickOutsideHandler: () => {
  255. document.removeEventListener('click', this.clickOutsideHandler, false);
  256. this.clickOutsideHandler = null;
  257. },
  258. };
  259. }
  260. componentDidMount() {
  261. const { disabled, autoFocus, preventScroll } = this.props;
  262. if (!disabled && autoFocus) {
  263. this.inputRef.current.focus({ preventScroll });
  264. this.foundation.handleClick();
  265. }
  266. this.foundation.init();
  267. }
  268. handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  269. this.foundation.handleInputChange(e);
  270. };
  271. handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
  272. this.foundation.handleKeyDown(e);
  273. };
  274. handleInputFocus = (e: React.MouseEvent<HTMLInputElement>) => {
  275. this.foundation.handleInputFocus(e);
  276. };
  277. handleInputBlur = (e: React.MouseEvent<HTMLInputElement>) => {
  278. this.foundation.handleInputBlur(e);
  279. };
  280. handleClearBtn = (e: React.MouseEvent<HTMLDivElement>) => {
  281. this.foundation.handleClearBtn(e);
  282. };
  283. /* istanbul ignore next */
  284. handleClearEnterPress = (e: React.KeyboardEvent<HTMLDivElement>) => {
  285. this.foundation.handleClearEnterPress(e);
  286. };
  287. handleTagClose = (idx: number) => {
  288. this.foundation.handleTagClose(idx);
  289. };
  290. handleInputMouseLeave = (e: React.MouseEvent<HTMLDivElement>) => {
  291. this.foundation.handleInputMouseLeave();
  292. };
  293. handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
  294. this.foundation.handleClick(e);
  295. };
  296. handleInputMouseEnter = (e: React.MouseEvent<HTMLDivElement>) => {
  297. this.foundation.handleInputMouseEnter();
  298. };
  299. handleClickPrefixOrSuffix = (e: React.MouseEvent<HTMLInputElement>) => {
  300. this.foundation.handleClickPrefixOrSuffix(e);
  301. };
  302. handlePreventMouseDown = (e: React.MouseEvent<HTMLInputElement>) => {
  303. this.foundation.handlePreventMouseDown(e);
  304. };
  305. renderClearBtn() {
  306. const { hovering, tagsArray, inputValue } = this.state;
  307. const { showClear, disabled, clearIcon } = this.props;
  308. const clearCls = cls(`${prefixCls}-clearBtn`, {
  309. [`${prefixCls}-clearBtn-invisible`]: !hovering || (inputValue === '' && tagsArray.length === 0) || disabled,
  310. });
  311. if (showClear) {
  312. return (
  313. <div
  314. role="button"
  315. tabIndex={0}
  316. aria-label="Clear TagInput value"
  317. className={clearCls}
  318. onClick={e => this.handleClearBtn(e)}
  319. onKeyPress={e => this.handleClearEnterPress(e)}
  320. >
  321. { clearIcon ? clearIcon : <IconClear />}
  322. </div>
  323. );
  324. }
  325. return null;
  326. }
  327. renderPrefix() {
  328. const { prefix, insetLabel, insetLabelId } = this.props;
  329. const labelNode = prefix || insetLabel;
  330. if (isNull(labelNode) || isUndefined(labelNode)) {
  331. return null;
  332. }
  333. const prefixWrapperCls = cls(`${prefixCls}-prefix`, {
  334. [`${prefixCls}-inset-label`]: insetLabel,
  335. [`${prefixCls}-prefix-text`]: labelNode && isString(labelNode),
  336. // eslint-disable-next-line max-len
  337. [`${prefixCls}-prefix-icon`]: isSemiIcon(labelNode),
  338. });
  339. return (
  340. // eslint-disable-next-line jsx-a11y/no-static-element-interactions,jsx-a11y/click-events-have-key-events
  341. <div
  342. className={prefixWrapperCls}
  343. onMouseDown={this.handlePreventMouseDown}
  344. onClick={this.handleClickPrefixOrSuffix}
  345. id={insetLabelId} x-semi-prop="prefix"
  346. >
  347. {labelNode}
  348. </div>
  349. );
  350. }
  351. renderSuffix() {
  352. const { suffix } = this.props;
  353. if (isNull(suffix) || isUndefined(suffix)) {
  354. return null;
  355. }
  356. const suffixWrapperCls = cls(`${prefixCls}-suffix`, {
  357. [`${prefixCls}-suffix-text`]: suffix && isString(suffix),
  358. // eslint-disable-next-line max-len
  359. [`${prefixCls}-suffix-icon`]: isSemiIcon(suffix),
  360. });
  361. return (
  362. // eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions
  363. <div
  364. className={suffixWrapperCls}
  365. onMouseDown={this.handlePreventMouseDown}
  366. onClick={this.handleClickPrefixOrSuffix}
  367. x-semi-prop="suffix"
  368. >
  369. {suffix}
  370. </div>
  371. );
  372. }
  373. getAllTags = () => {
  374. const {
  375. size,
  376. disabled,
  377. renderTagItem,
  378. showContentTooltip,
  379. draggable,
  380. } = this.props;
  381. const { tagsArray, active } = this.state;
  382. const showIconHandler = active && draggable;
  383. const tagCls = cls(`${prefixCls}-wrapper-tag`, {
  384. [`${prefixCls}-wrapper-tag-size-${size}`]: size,
  385. [`${prefixCls}-wrapper-tag-icon`]: showIconHandler,
  386. });
  387. const typoCls = cls(`${prefixCls}-wrapper-typo`, {
  388. [`${prefixCls}-wrapper-typo-disabled`]: disabled,
  389. });
  390. const itemWrapperCls = cls({
  391. [`${prefixCls}-drag-item`]: showIconHandler,
  392. [`${prefixCls}-wrapper-tag-icon`]: showIconHandler,
  393. });
  394. const DragHandle = SortableHandle(() => <IconHandle className={`${prefixCls}-drag-handler`}></IconHandle>);
  395. return tagsArray.map((value, index) => {
  396. const elementKey = showIconHandler ? value : `${index}${value}`;
  397. const onClose = () => {
  398. !disabled && this.handleTagClose(index);
  399. };
  400. if (isFunction(renderTagItem)) {
  401. return showIconHandler? (<div className={itemWrapperCls} key={elementKey}>
  402. <DragHandle />
  403. {renderTagItem(value, index, onClose)}
  404. </div>) : renderTagItem(value, index, onClose);
  405. } else {
  406. return (
  407. <Tag
  408. className={tagCls}
  409. color="white"
  410. size={size === 'small' ? 'small' : 'large'}
  411. type="light"
  412. onClose={onClose}
  413. closable={!disabled}
  414. key={elementKey}
  415. visible
  416. aria-label={`${!disabled ? 'Closable ' : ''}Tag: ${value}`}
  417. >
  418. {/* Wrap a layer of div outside IconHandler and Value to ensure that the two are aligned */}
  419. <div className={`${prefixCls}-tag-content-wrapper`}>
  420. {showIconHandler && <DragHandle />}
  421. <Paragraph
  422. className={typoCls}
  423. ellipsis={{ showTooltip: showContentTooltip, rows: 1 }}
  424. >
  425. {value}
  426. </Paragraph>
  427. </div>
  428. </Tag>
  429. );
  430. }
  431. });
  432. }
  433. onSortEnd = (callbackProps: OnSortEndProps) => {
  434. this.foundation.handleSortEnd(callbackProps);
  435. }
  436. renderTags() {
  437. const {
  438. disabled,
  439. maxTagCount,
  440. showRestTagsPopover,
  441. restTagsPopoverProps = {},
  442. draggable,
  443. expandRestTagsOnClick,
  444. } = this.props;
  445. const { tagsArray, active } = this.state;
  446. const restTagsCls = cls(`${prefixCls}-wrapper-n`, {
  447. [`${prefixCls}-wrapper-n-disabled`]: disabled,
  448. });
  449. const allTags = this.getAllTags();
  450. let restTags: Array<React.ReactNode> = [];
  451. let tags: Array<React.ReactNode> = [...allTags];
  452. if (( !active || !expandRestTagsOnClick) && maxTagCount && maxTagCount < allTags.length){
  453. tags = allTags.slice(0, maxTagCount);
  454. restTags = allTags.slice(maxTagCount);
  455. }
  456. const restTagsContent = (
  457. <span className={restTagsCls}>+{tagsArray.length - maxTagCount}</span>
  458. );
  459. const sortableListItems = allTags.map((item, index) => ({
  460. item: item,
  461. key: tagsArray[index],
  462. }));
  463. if (active && draggable && sortableListItems.length > 0) {
  464. // helperClass:add styles to the helper(item being dragged) https://github.com/clauderic/react-sortable-hoc/issues/87
  465. // @ts-ignore skip SortableItem type check
  466. return <SortableList useDragHandle helperClass={`${prefixCls}-drag-item-move`} items={sortableListItems} onSortEnd={this.onSortEnd} axis={"xy"} />;
  467. }
  468. return (
  469. <>
  470. {tags}
  471. {
  472. restTags.length > 0 &&
  473. (
  474. showRestTagsPopover ?
  475. (
  476. <Popover
  477. content={restTags}
  478. showArrow
  479. trigger="hover"
  480. position="top"
  481. autoAdjustOverflow
  482. {...restTagsPopoverProps}
  483. >
  484. {restTagsContent}
  485. </Popover>
  486. ) : restTagsContent
  487. )
  488. }
  489. </>
  490. );
  491. }
  492. blur() {
  493. this.inputRef.current.blur();
  494. // unregister clickOutside event
  495. this.foundation.clickOutsideCallBack();
  496. }
  497. focus() {
  498. const { preventScroll, disabled } = this.props;
  499. this.inputRef.current.focus({ preventScroll });
  500. if (!disabled) {
  501. // register clickOutside event
  502. this.foundation.handleClick();
  503. }
  504. }
  505. handleInputCompositionStart = (e) => {
  506. this.foundation.handleInputCompositionStart(e);
  507. }
  508. handleInputCompositionEnd = (e) => {
  509. this.foundation.handleInputCompositionEnd(e);
  510. }
  511. render() {
  512. const {
  513. size,
  514. style,
  515. className,
  516. disabled,
  517. placeholder,
  518. validateStatus,
  519. } = this.props;
  520. const {
  521. focusing,
  522. hovering,
  523. tagsArray,
  524. inputValue,
  525. active,
  526. } = this.state;
  527. const tagInputCls = cls(prefixCls, className, {
  528. [`${prefixCls}-focus`]: focusing || active,
  529. [`${prefixCls}-disabled`]: disabled,
  530. [`${prefixCls}-hover`]: hovering && !disabled,
  531. [`${prefixCls}-error`]: validateStatus === 'error',
  532. [`${prefixCls}-warning`]: validateStatus === 'warning',
  533. [`${prefixCls}-small`]: size === 'small',
  534. [`${prefixCls}-large`]: size === 'large',
  535. });
  536. const inputCls = cls(`${prefixCls}-wrapper-input`, `${prefixCls}-wrapper-input-${size}`);
  537. const wrapperCls = cls(`${prefixCls}-wrapper`);
  538. return (
  539. // eslint-disable-next-line
  540. <div
  541. ref={this.tagInputRef}
  542. style={style}
  543. className={tagInputCls}
  544. aria-disabled={disabled}
  545. aria-label={this.props['aria-label']}
  546. aria-invalid={validateStatus === 'error'}
  547. onMouseEnter={e => {
  548. this.handleInputMouseEnter(e);
  549. }}
  550. onMouseLeave={e => {
  551. this.handleInputMouseLeave(e);
  552. }}
  553. onClick={e => {
  554. this.handleClick(e);
  555. }}
  556. >
  557. {this.renderPrefix()}
  558. <div className={wrapperCls}>
  559. {this.renderTags()}
  560. <Input
  561. aria-label='input value'
  562. ref={this.inputRef as any}
  563. className={inputCls}
  564. disabled={disabled}
  565. value={inputValue}
  566. size={size}
  567. placeholder={tagsArray.length === 0 ? placeholder : ''}
  568. onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {
  569. this.handleKeyDown(e);
  570. }}
  571. onChange={(v: string, e: React.ChangeEvent<HTMLInputElement>) => {
  572. this.handleInputChange(e);
  573. }}
  574. onBlur={(e: React.FocusEvent<HTMLInputElement>) => {
  575. this.handleInputBlur(e as any);
  576. }}
  577. onFocus={(e: React.FocusEvent<HTMLInputElement>) => {
  578. this.handleInputFocus(e as any);
  579. }}
  580. onCompositionStart={this.handleInputCompositionStart}
  581. onCompositionEnd={this.handleInputCompositionEnd}
  582. />
  583. </div>
  584. {this.renderClearBtn()}
  585. {this.renderSuffix()}
  586. </div>
  587. );
  588. }
  589. }
  590. export default TagInput;
  591. export { ValidateStatus };