Item.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /* eslint-disable max-len */
  2. /* eslint-disable no-nested-ternary */
  3. import BaseComponent, { BaseProps } from '../_base/baseComponent';
  4. import React from 'react';
  5. import PropTypes from 'prop-types';
  6. import cls from 'classnames';
  7. import { noop, times } from 'lodash';
  8. import isNullOrUndefined from '@douyinfe/semi-foundation/utils/isNullOrUndefined';
  9. import { cloneDeep, isSemiIcon } from '../_utils';
  10. import ItemFoundation, {
  11. ItemAdapter,
  12. ItemProps,
  13. SelectedItemProps
  14. } from '@douyinfe/semi-foundation/navigation/itemFoundation';
  15. import { cssClasses, strings } from '@douyinfe/semi-foundation/navigation/constants';
  16. import Tooltip from '../tooltip';
  17. import NavContext from './nav-context';
  18. import Dropdown from '../dropdown';
  19. const clsPrefix = `${cssClasses.PREFIX}-item`;
  20. export interface NavItemProps extends ItemProps, BaseProps {
  21. children?: React.ReactNode;
  22. disabled?: boolean;
  23. forwardRef?: (ele: HTMLLIElement) => void;
  24. icon?: React.ReactNode;
  25. itemKey?: React.ReactText;
  26. level?: number;
  27. link?: string;
  28. linkOptions?: React.HTMLAttributes<HTMLLinkElement>;
  29. text?: React.ReactNode;
  30. tooltipHideDelay?: number;
  31. tooltipShowDelay?: number;
  32. onClick?(clickItems: SelectedData): void;
  33. onMouseEnter?: React.MouseEventHandler<HTMLLIElement>;
  34. onMouseLeave?: React.MouseEventHandler<HTMLLIElement>;
  35. }
  36. export interface SelectedData extends SelectedItemProps<NavItemProps> {
  37. text?: React.ReactNode;
  38. }
  39. export interface NavItemState {
  40. tooltipShow: boolean;
  41. }
  42. export default class NavItem extends BaseComponent<NavItemProps, NavItemState> {
  43. static contextType = NavContext;
  44. static propTypes = {
  45. text: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  46. itemKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  47. onClick: PropTypes.func,
  48. onMouseEnter: PropTypes.func,
  49. onMouseLeave: PropTypes.func,
  50. children: PropTypes.node,
  51. icon: PropTypes.oneOfType([PropTypes.node]),
  52. className: PropTypes.string,
  53. toggleIcon: PropTypes.string,
  54. style: PropTypes.object,
  55. forwardRef: PropTypes.func,
  56. indent: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
  57. isCollapsed: PropTypes.bool, // Is it in a state of folding to the side
  58. isSubNav: PropTypes.bool, // Whether to navigate for children
  59. link: PropTypes.string,
  60. linkOptions: PropTypes.object,
  61. disabled: PropTypes.bool,
  62. };
  63. static defaultProps = {
  64. isSubNav: false,
  65. indent: false,
  66. forwardRef: noop,
  67. isCollapsed: false,
  68. onClick: noop,
  69. onMouseEnter: noop,
  70. onMouseLeave: noop,
  71. disabled: false,
  72. };
  73. foundation: ItemFoundation;
  74. constructor(props: NavItemProps) {
  75. super(props);
  76. this.state = {
  77. tooltipShow: false,
  78. };
  79. this.foundation = new ItemFoundation(this.adapter);
  80. }
  81. _invokeContextFunc(funcName: string, ...args: any[]) {
  82. if (funcName && this.context && typeof this.context[funcName] === 'function') {
  83. return this.context[funcName](...args);
  84. }
  85. return null;
  86. }
  87. get adapter(): ItemAdapter<NavItemProps, NavItemState> {
  88. return {
  89. ...super.adapter,
  90. cloneDeep,
  91. updateTooltipShow: tooltipShow => this.setState({ tooltipShow }),
  92. updateSelected: _selected => this._invokeContextFunc('updateSelectedKeys', [this.props.itemKey]),
  93. updateGlobalSelectedKeys: keys => this._invokeContextFunc('updateSelectedKeys', [...keys]),
  94. getSelectedKeys: () => this.context && this.context.selectedKeys,
  95. getSelectedKeysIsControlled: () => this.context && this.context.selectedKeysIsControlled,
  96. notifyGlobalOnSelect: (...args) => this._invokeContextFunc('onSelect', ...args),
  97. notifyGlobalOnClick: (...args) => this._invokeContextFunc('onClick', ...args),
  98. notifyClick: (...args) => this.props.onClick(...args),
  99. notifyMouseEnter: (...args) => this.props.onMouseEnter(...args),
  100. notifyMouseLeave: (...args) => this.props.onMouseLeave(...args),
  101. getIsCollapsed: () => this.props.isCollapsed || Boolean(this.context && this.context.isCollapsed) || false,
  102. getSelected: () =>
  103. Boolean(this.context && this.context.selectedKeys && this.context.selectedKeys.includes(this.props.itemKey)),
  104. getIsOpen: () =>
  105. Boolean(this.context && this.context.openKeys && this.context.openKeys.includes(this.props.itemKey)),
  106. };
  107. }
  108. renderIcon(icon: React.ReactNode, pos: string, isToggleIcon = false, key: number | string = 0) {
  109. if (this.props.isSubNav) {
  110. return null;
  111. }
  112. if (!icon && this.context.mode === strings.MODE_HORIZONTAL) {
  113. return null;
  114. }
  115. let iconSize = 'large';
  116. if (pos === strings.ICON_POS_RIGHT) {
  117. iconSize = 'default';
  118. }
  119. const className = cls(`${clsPrefix}-icon`, {
  120. [`${clsPrefix}-icon-toggle-${this.context.toggleIconPosition}`]: isToggleIcon,
  121. [`${clsPrefix}-icon-info`]: !isToggleIcon
  122. });
  123. return (
  124. <i className={className} key={key}>
  125. {isSemiIcon(icon) ? React.cloneElement((icon as React.ReactElement), { size: (icon as React.ReactElement).props.size || iconSize }) : icon}
  126. </i>
  127. );
  128. }
  129. setItemRef = (ref: HTMLLIElement) => {
  130. // console.log('Item - setItemRef()', ref);
  131. this.props.forwardRef && this.props.forwardRef(ref);
  132. };
  133. wrapTooltip = (node: React.ReactNode) => {
  134. const { text, tooltipHideDelay, tooltipShowDelay } = this.props;
  135. return (
  136. <Tooltip
  137. content={text}
  138. position="right"
  139. trigger={'hover'}
  140. mouseEnterDelay={tooltipShowDelay}
  141. mouseLeaveDelay={tooltipHideDelay}
  142. >
  143. {node}
  144. </Tooltip>
  145. );
  146. };
  147. handleClick = (e: React.MouseEvent) => this.foundation.handleClick(e);
  148. handleKeyPress = (e: React.KeyboardEvent) => this.foundation.handleKeyPress(e);
  149. render() {
  150. const {
  151. text,
  152. children,
  153. icon,
  154. toggleIcon,
  155. className,
  156. isSubNav,
  157. style,
  158. indent,
  159. onMouseEnter,
  160. onMouseLeave,
  161. link,
  162. linkOptions,
  163. disabled,
  164. level = 0,
  165. } = this.props;
  166. const { mode, isInSubNav, prefixCls, limitIndent } = this.context;
  167. const isCollapsed = this.adapter.getIsCollapsed();
  168. const selected = this.adapter.getSelected();
  169. let itemChildren = null;
  170. if (!isNullOrUndefined(children)) {
  171. itemChildren = children;
  172. } else {
  173. let placeholderIcons = null;
  174. if (mode === strings.MODE_VERTICAL && !limitIndent && !isCollapsed) {
  175. const iconAmount = (icon && !indent) ? level : level - 1;
  176. placeholderIcons = times(iconAmount, (index) => this.renderIcon(null, strings.ICON_POS_RIGHT, false, index));
  177. }
  178. itemChildren = (
  179. <>
  180. {placeholderIcons}
  181. {this.context.toggleIconPosition === strings.TOGGLE_ICON_LEFT && this.renderIcon(toggleIcon, strings.ICON_POS_RIGHT, true, 'key-toggle-pos-right')}
  182. {icon || indent || isInSubNav ? this.renderIcon(icon, strings.ICON_POS_LEFT, false, 'key-position-left') : null}
  183. {!isNullOrUndefined(text) ? <span className={`${cssClasses.PREFIX}-item-text`}>{text}</span> : ''}
  184. {this.context.toggleIconPosition === strings.TOGGLE_ICON_RIGHT && this.renderIcon(toggleIcon, strings.ICON_POS_RIGHT, true, 'key-toggle-pos-right')}
  185. </>
  186. );
  187. }
  188. if (typeof link === 'string') {
  189. itemChildren = (
  190. <a className={`${prefixCls}-item-link`} href={link} {...(linkOptions as any)}>
  191. {itemChildren}
  192. </a>
  193. );
  194. }
  195. let itemDom: React.ReactNode = '';
  196. if (isInSubNav && (isCollapsed || mode === strings.MODE_HORIZONTAL)) {
  197. const popoverItemCls = cls({
  198. [clsPrefix]: true,
  199. [`${clsPrefix}-sub`]: isSubNav,
  200. [`${clsPrefix}-selected`]: selected,
  201. [`${clsPrefix}-collapsed`]: isCollapsed,
  202. [`${clsPrefix}-disabled`]: disabled,
  203. });
  204. itemDom = (
  205. <Dropdown.Item
  206. selected={selected}
  207. active={selected}
  208. forwardRef={this.setItemRef}
  209. className={popoverItemCls}
  210. onClick={this.handleClick}
  211. onMouseEnter={onMouseEnter}
  212. onMouseLeave={onMouseLeave}
  213. disabled={disabled}
  214. >
  215. {itemChildren}
  216. </Dropdown.Item>
  217. );
  218. } else {
  219. // Items are divided into normal and sub-wrap
  220. const popoverItemCls = cls(`${className || `${clsPrefix}-normal`}`, {
  221. [clsPrefix]: true,
  222. [`${clsPrefix}-sub`]: isSubNav,
  223. [`${clsPrefix}-selected`]: selected && !isSubNav,
  224. [`${clsPrefix}-collapsed`]: isCollapsed,
  225. [`${clsPrefix}-disabled`]: disabled,
  226. });
  227. const ariaProps = {
  228. 'aria-disabled': disabled,
  229. };
  230. if (isSubNav) {
  231. const isOpen = this.adapter.getIsOpen();
  232. ariaProps['aria-expanded'] = isOpen;
  233. }
  234. itemDom = (
  235. <li
  236. role="menuitem"
  237. tabIndex={-1}
  238. {...ariaProps}
  239. style={style}
  240. ref={this.setItemRef}
  241. className={popoverItemCls}
  242. onClick={this.handleClick}
  243. onMouseEnter={onMouseEnter}
  244. onMouseLeave={onMouseLeave}
  245. onKeyPress={this.handleKeyPress}
  246. >
  247. {itemChildren}
  248. </li>
  249. );
  250. }
  251. // Display Tooltip when disabled and SubNav
  252. if (isCollapsed && !isInSubNav && !isSubNav || isCollapsed && isSubNav && disabled) {
  253. itemDom = this.wrapTooltip(itemDom);
  254. }
  255. return itemDom;
  256. }
  257. }