Item.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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, { NavContextType } 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.AnchorHTMLAttributes<HTMLAnchorElement>;
  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. context: NavContextType;
  75. constructor(props: NavItemProps) {
  76. super(props);
  77. this.state = {
  78. tooltipShow: false,
  79. };
  80. this.foundation = new ItemFoundation(this.adapter);
  81. }
  82. _invokeContextFunc(funcName: string, ...args: any[]) {
  83. if (funcName && this.context && typeof this.context[funcName] === 'function') {
  84. return this.context[funcName](...args);
  85. }
  86. return null;
  87. }
  88. get adapter(): ItemAdapter<NavItemProps, NavItemState> {
  89. return {
  90. ...super.adapter,
  91. cloneDeep,
  92. updateTooltipShow: tooltipShow => this.setState({ tooltipShow }),
  93. updateSelected: _selected => this._invokeContextFunc('updateSelectedKeys', [this.props.itemKey]),
  94. updateGlobalSelectedKeys: keys => this._invokeContextFunc('updateSelectedKeys', [...keys]),
  95. getSelectedKeys: () => this.context && this.context.selectedKeys,
  96. getSelectedKeysIsControlled: () => this.context && this.context.selectedKeysIsControlled,
  97. notifyGlobalOnSelect: (...args) => this._invokeContextFunc('onSelect', ...args),
  98. notifyGlobalOnClick: (...args) => this._invokeContextFunc('onClick', ...args),
  99. notifyClick: (...args) => this.props.onClick(...args),
  100. notifyMouseEnter: (...args) => this.props.onMouseEnter(...args),
  101. notifyMouseLeave: (...args) => this.props.onMouseLeave(...args),
  102. getIsCollapsed: () => this.props.isCollapsed || Boolean(this.context && this.context.isCollapsed) || false,
  103. getSelected: () =>
  104. Boolean(this.context && this.context.selectedKeys && this.context.selectedKeys.includes(this.props.itemKey as string)),
  105. getIsOpen: () =>
  106. Boolean(this.context && this.context.openKeys && this.context.openKeys.includes(this.props.itemKey as string)),
  107. };
  108. }
  109. renderIcon(icon: React.ReactNode, pos: string, isToggleIcon = false, key: number | string = 0) {
  110. if (this.props.isSubNav) {
  111. return null;
  112. }
  113. if (!icon && this.context.mode === strings.MODE_HORIZONTAL) {
  114. return null;
  115. }
  116. let iconSize = 'large';
  117. if (pos === strings.ICON_POS_RIGHT) {
  118. iconSize = 'default';
  119. }
  120. const className = cls(`${clsPrefix}-icon`, {
  121. [`${clsPrefix}-icon-toggle-${this.context.toggleIconPosition}`]: isToggleIcon,
  122. [`${clsPrefix}-icon-info`]: !isToggleIcon
  123. });
  124. return (
  125. <i className={className} key={key}>
  126. {isSemiIcon(icon) ? React.cloneElement((icon as React.ReactElement), { size: (icon as React.ReactElement).props.size || iconSize }) : icon}
  127. </i>
  128. );
  129. }
  130. setItemRef = (ref: HTMLLIElement) => {
  131. // console.log('Item - setItemRef()', ref);
  132. this.props.forwardRef && this.props.forwardRef(ref);
  133. };
  134. wrapTooltip = (node: React.ReactNode) => {
  135. const { text, tooltipHideDelay, tooltipShowDelay } = this.props;
  136. return (
  137. <Tooltip
  138. content={text}
  139. position="right"
  140. trigger={'hover'}
  141. mouseEnterDelay={tooltipShowDelay}
  142. mouseLeaveDelay={tooltipHideDelay}
  143. >
  144. {node}
  145. </Tooltip>
  146. );
  147. };
  148. handleClick = (e: React.MouseEvent) => this.foundation.handleClick(e);
  149. handleKeyPress = (e: React.KeyboardEvent) => this.foundation.handleKeyPress(e);
  150. render() {
  151. const {
  152. text,
  153. children,
  154. icon,
  155. toggleIcon,
  156. className,
  157. isSubNav,
  158. style,
  159. indent,
  160. onMouseEnter,
  161. onMouseLeave,
  162. link,
  163. linkOptions,
  164. disabled,
  165. level = 0,
  166. } = this.props;
  167. const { mode, isInSubNav, prefixCls, limitIndent } = this.context;
  168. const isCollapsed = this.adapter.getIsCollapsed();
  169. const selected = this.adapter.getSelected();
  170. let itemChildren = null;
  171. if (!isNullOrUndefined(children)) {
  172. itemChildren = children;
  173. } else {
  174. let placeholderIcons = null;
  175. if (mode === strings.MODE_VERTICAL && !limitIndent && !isCollapsed) {
  176. const iconAmount = (icon && !indent) ? level : level - 1;
  177. placeholderIcons = times(iconAmount, (index) => this.renderIcon(null, strings.ICON_POS_RIGHT, false, index));
  178. }
  179. itemChildren = (
  180. <>
  181. {placeholderIcons}
  182. {this.context.toggleIconPosition === strings.TOGGLE_ICON_LEFT && this.renderIcon(toggleIcon, strings.ICON_POS_RIGHT, true, 'key-toggle-pos-right')}
  183. {icon || indent || isInSubNav ? this.renderIcon(icon, strings.ICON_POS_LEFT, false, 'key-position-left') : null}
  184. {!isNullOrUndefined(text) ? <span className={`${cssClasses.PREFIX}-item-text`}>{text}</span> : ''}
  185. {this.context.toggleIconPosition === strings.TOGGLE_ICON_RIGHT && this.renderIcon(toggleIcon, strings.ICON_POS_RIGHT, true, 'key-toggle-pos-right')}
  186. </>
  187. );
  188. }
  189. if (typeof link === 'string') {
  190. itemChildren = (
  191. <a className={`${prefixCls}-item-link`} href={link} {...(linkOptions as any)}>
  192. {itemChildren}
  193. </a>
  194. );
  195. }
  196. let itemDom: React.ReactNode = '';
  197. if (isInSubNav && (isCollapsed || mode === strings.MODE_HORIZONTAL)) {
  198. const popoverItemCls = cls({
  199. [clsPrefix]: true,
  200. [`${clsPrefix}-sub`]: isSubNav,
  201. [`${clsPrefix}-selected`]: selected,
  202. [`${clsPrefix}-collapsed`]: isCollapsed,
  203. [`${clsPrefix}-disabled`]: disabled,
  204. });
  205. itemDom = (
  206. <Dropdown.Item
  207. selected={selected}
  208. active={selected}
  209. forwardRef={this.setItemRef}
  210. className={popoverItemCls}
  211. onClick={this.handleClick}
  212. onMouseEnter={onMouseEnter}
  213. onMouseLeave={onMouseLeave}
  214. disabled={disabled}
  215. >
  216. {itemChildren}
  217. </Dropdown.Item>
  218. );
  219. } else {
  220. // Items are divided into normal and sub-wrap
  221. const popoverItemCls = cls(`${className || `${clsPrefix}-normal`}`, {
  222. [clsPrefix]: true,
  223. [`${clsPrefix}-sub`]: isSubNav,
  224. [`${clsPrefix}-selected`]: selected && !isSubNav,
  225. [`${clsPrefix}-collapsed`]: isCollapsed,
  226. [`${clsPrefix}-disabled`]: disabled,
  227. });
  228. const ariaProps = {
  229. 'aria-disabled': disabled,
  230. };
  231. if (isSubNav) {
  232. const isOpen = this.adapter.getIsOpen();
  233. ariaProps['aria-expanded'] = isOpen;
  234. }
  235. itemDom = (
  236. <li
  237. role="menuitem"
  238. tabIndex={-1}
  239. {...ariaProps}
  240. style={style}
  241. ref={this.setItemRef}
  242. className={popoverItemCls}
  243. onClick={this.handleClick}
  244. onMouseEnter={onMouseEnter}
  245. onMouseLeave={onMouseLeave}
  246. onKeyPress={this.handleKeyPress}
  247. >
  248. {itemChildren}
  249. </li>
  250. );
  251. }
  252. // Display Tooltip when disabled and SubNav
  253. if (isCollapsed && !isInSubNav && !isSubNav || isCollapsed && isSubNav && disabled) {
  254. itemDom = this.wrapTooltip(itemDom);
  255. }
  256. return itemDom;
  257. }
  258. }