SubNav.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 '@douyinfe/semi-foundation/navigation/navigation.scss';
  8. import isNullOrUndefined from '@douyinfe/semi-foundation/utils/isNullOrUndefined';
  9. import SubNavFoundation, { SubNavAdapter } from '@douyinfe/semi-foundation/navigation/subNavFoundation';
  10. import { strings, numbers, cssClasses } from '@douyinfe/semi-foundation/navigation/constants';
  11. import { IconChevronDown, IconChevronUp, IconChevronRight } from '@douyinfe/semi-icons';
  12. import NavItem from './Item';
  13. import Dropdown, { DropdownProps } from '../dropdown';
  14. import NavContext, { NavContextType } from './nav-context';
  15. import { times, get } from 'lodash';
  16. import Collapsible from "../collapsible";
  17. import CSSAnimation from "../_cssAnimation";
  18. export interface SubNavProps extends BaseProps {
  19. disabled?: boolean;
  20. dropdownStyle?: React.CSSProperties;
  21. icon?: React.ReactNode;
  22. indent?: boolean | number;
  23. isCollapsed?: boolean;
  24. isOpen?: boolean;
  25. itemKey?: string | number;
  26. level?: number;
  27. maxHeight?: number;
  28. onMouseEnter?: React.MouseEventHandler<HTMLLIElement>;
  29. onMouseLeave?: React.MouseEventHandler<HTMLLIElement>;
  30. text?: React.ReactNode;
  31. expandIcon?: React.ReactNode
  32. }
  33. export interface SubNavState {
  34. isHovered: boolean
  35. }
  36. export default class SubNav extends BaseComponent<SubNavProps, SubNavState> {
  37. static contextType = NavContext;
  38. static propTypes = {
  39. /**
  40. * Unique identification
  41. */
  42. itemKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  43. /**
  44. * Copywriting
  45. */
  46. text: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  47. /**
  48. * Whether child navigation is expanded
  49. */
  50. isOpen: PropTypes.bool,
  51. /**
  52. * Whether it is in the state of being stowed to the sidebar
  53. */
  54. isCollapsed: PropTypes.bool,
  55. /**
  56. * Whether to keep the left Icon placeholder
  57. */
  58. indent: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]),
  59. /**
  60. * Nested child elements
  61. */
  62. children: PropTypes.node,
  63. style: PropTypes.object,
  64. /**
  65. * Icon name on the left
  66. */
  67. icon: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  68. /**
  69. * Maximum height (for animation)
  70. */
  71. maxHeight: PropTypes.number,
  72. onMouseEnter: PropTypes.func,
  73. onMouseLeave: PropTypes.func,
  74. // Is it disabled
  75. disabled: PropTypes.bool,
  76. level: PropTypes.number
  77. };
  78. static defaultProps = {
  79. level: 0,
  80. indent: false,
  81. isCollapsed: false,
  82. isOpen: false,
  83. maxHeight: numbers.DEFAULT_SUBNAV_MAX_HEIGHT,
  84. disabled: false,
  85. };
  86. titleRef: React.RefObject<HTMLDivElement>;
  87. itemRef: React.RefObject<HTMLLIElement>;
  88. foundation: SubNavFoundation;
  89. context: NavContextType;
  90. constructor(props: SubNavProps) {
  91. super(props);
  92. this.state = {
  93. isHovered: false,
  94. };
  95. this.adapter.setCache('firstMounted', true);
  96. this.titleRef = React.createRef();
  97. this.itemRef = React.createRef();
  98. this.foundation = new SubNavFoundation(this.adapter);
  99. }
  100. setItemRef = (ref: HTMLLIElement | React.RefObject<HTMLLIElement>) => {
  101. if (ref && (ref as React.RefObject<HTMLLIElement>).current) {
  102. this.itemRef = ref as React.RefObject<HTMLLIElement>;
  103. } else {
  104. this.itemRef = { current: ref as HTMLLIElement };
  105. }
  106. };
  107. setTitleRef = (ref: HTMLDivElement | React.RefObject<HTMLDivElement>) => {
  108. if (ref && (ref as React.RefObject<HTMLDivElement>).current) {
  109. this.titleRef = ref as React.RefObject<HTMLDivElement>;
  110. } else {
  111. this.titleRef = { current: ref as HTMLDivElement };
  112. }
  113. };
  114. _invokeContextFunc(funcName: string, ...args: any[]) {
  115. if (funcName && this.context && typeof this.context[funcName] === 'function') {
  116. return this.context[funcName](...args);
  117. }
  118. return null;
  119. }
  120. get adapter(): SubNavAdapter<SubNavProps, SubNavState> {
  121. return {
  122. ...super.adapter,
  123. updateIsHovered: isHovered => this.setState({ isHovered }),
  124. getOpenKeys: () => this.context && this.context.openKeys,
  125. getOpenKeysIsControlled: () => this.context && this.context.openKeysIsControlled,
  126. getCanUpdateOpenKeys: () => this.context && this.context.canUpdateOpenKeys,
  127. updateOpen: isOpen =>
  128. this._invokeContextFunc(isOpen ? 'addOpenKeys' : 'removeOpenKeys', this.props.itemKey),
  129. notifyGlobalOpenChange: (...args) => this._invokeContextFunc('onOpenChange', ...args),
  130. notifyGlobalOnSelect: (...args) => this._invokeContextFunc('onSelect', ...args),
  131. notifyGlobalOnClick: (...args) => this._invokeContextFunc('onClick', ...args),
  132. getIsSelected: itemKey => Boolean(!isNullOrUndefined(itemKey) && get(this.context, 'selectedKeys', []).includes(String(itemKey))),
  133. getIsOpen: () =>
  134. Boolean(this.context && this.context.openKeys && this.context.openKeys.includes(String(this.props.itemKey))),
  135. };
  136. }
  137. handleClick = (e: React.MouseEvent) => {
  138. this.foundation.handleClick(e && e.nativeEvent, this.titleRef && this.titleRef.current);
  139. };
  140. handleKeyPress = (e: React.KeyboardEvent) => {
  141. this.foundation.handleKeyPress(e && e.nativeEvent, this.titleRef && this.titleRef.current);
  142. }
  143. handleDropdownVisible = (visible: boolean) => this.foundation.handleDropdownVisibleChange(visible);
  144. renderIcon(icon: React.ReactNode, pos: string, withTransition?: boolean, isToggleIcon = false, key: number | string = 0) {
  145. const { prefixCls } = this.context;
  146. let iconSize = 'large';
  147. if (pos === strings.ICON_POS_RIGHT) {
  148. iconSize = 'default';
  149. }
  150. const className = cls(`${prefixCls}-item-icon`, {
  151. [`${prefixCls}-item-icon-toggle-${this.context.toggleIconPosition}`]: isToggleIcon,
  152. [`${prefixCls}-item-icon-info`]: !isToggleIcon
  153. });
  154. const isOpen = this.adapter.getIsOpen();
  155. const iconElem = React.isValidElement(icon) ? (withTransition ? (
  156. <CSSAnimation animationState={isOpen?"enter":"leave"} startClassName={`${cssClasses.PREFIX}-icon-rotate-${isOpen?"180":"0"}`}>
  157. {({ animationClassName })=>{
  158. // @ts-ignore
  159. return React.cloneElement(icon, { size: iconSize, className: animationClassName });
  160. }}
  161. </CSSAnimation>
  162. // @ts-ignore
  163. ) : React.cloneElement(icon, { size: iconSize })) : null;
  164. return <i key={key} className={className}>{iconElem}</i>;
  165. }
  166. renderTitleDiv() {
  167. const { text, icon, itemKey, indent, disabled, level, expandIcon } = this.props;
  168. const { mode, isInSubNav, isCollapsed, prefixCls, subNavMotion, limitIndent } = this.context;
  169. const isOpen = this.adapter.getIsOpen();
  170. const titleCls = cls(`${prefixCls}-sub-title`, {
  171. [`${prefixCls}-sub-title-selected`]: this.adapter.getIsSelected(itemKey),
  172. [`${prefixCls}-sub-title-disabled`]: disabled,
  173. });
  174. let withTransition = false;
  175. let toggleIconType: React.ReactNode = '';
  176. if (isCollapsed) {
  177. if (isInSubNav) {
  178. toggleIconType = <IconChevronRight />;
  179. } else {
  180. toggleIconType = null;
  181. }
  182. } else if (mode === strings.MODE_HORIZONTAL) {
  183. if (isInSubNav) {
  184. toggleIconType = <IconChevronRight aria-hidden={true} />;
  185. } else {
  186. toggleIconType = expandIcon ? expandIcon : <IconChevronDown aria-hidden={true} />;
  187. // Horizontal mode does not require animation fix#1198
  188. // withTransition = true;
  189. }
  190. } else {
  191. if (subNavMotion) {
  192. withTransition = true;
  193. }
  194. toggleIconType = expandIcon ? expandIcon : <IconChevronDown aria-hidden={true} />;
  195. }
  196. let placeholderIcons = null;
  197. if (mode === strings.MODE_VERTICAL && !limitIndent && !isCollapsed) {
  198. /* Different icons' amount means different indents.*/
  199. const iconAmount = (icon && !indent) ? level : level - 1;
  200. placeholderIcons = times(iconAmount, index => this.renderIcon(null, strings.ICON_POS_RIGHT, false, false, index));
  201. }
  202. const isIconChevronRightShow = (!isCollapsed && isInSubNav && mode === strings.MODE_HORIZONTAL) || (isCollapsed && isInSubNav);
  203. const titleDiv = (
  204. <div
  205. role="menuitem"
  206. // to avoid nested horizontal navigation be focused
  207. tabIndex={isIconChevronRightShow ? -1 : 0}
  208. ref={this.setTitleRef as any}
  209. className={titleCls}
  210. onClick={this.handleClick}
  211. onKeyPress={this.handleKeyPress}
  212. aria-expanded={isOpen ? 'true' : 'false'}
  213. >
  214. <div className={`${prefixCls}-item-inner`}>
  215. {placeholderIcons}
  216. {this.context.toggleIconPosition === strings.TOGGLE_ICON_LEFT && this.renderIcon(toggleIconType, strings.ICON_POS_RIGHT, withTransition, true, 'key-toggle-position-left')}
  217. {icon || indent || (isInSubNav && mode !== strings.MODE_HORIZONTAL)
  218. ? this.renderIcon(icon, strings.ICON_POS_LEFT, false, false, 'key-inSubNav-position-left')
  219. : null}
  220. <span className={`${prefixCls}-item-text`}>{text}</span>
  221. {this.context.toggleIconPosition === strings.TOGGLE_ICON_RIGHT && this.renderIcon(toggleIconType, strings.ICON_POS_RIGHT, withTransition, true, 'key-toggle-position-right')}
  222. </div>
  223. </div>
  224. );
  225. return titleDiv;
  226. }
  227. renderSubUl() {
  228. const { children, maxHeight } = this.props;
  229. const { isCollapsed, mode, subNavMotion, prefixCls } = this.context;
  230. const isOpen = this.adapter.getIsOpen();
  231. const isHorizontal = mode === strings.MODE_HORIZONTAL;
  232. const subNavCls = cls(`${prefixCls}-sub`, {
  233. [`${prefixCls}-sub-open`]: isOpen,
  234. [`${prefixCls}-sub-popover`]: isCollapsed || isHorizontal,
  235. });
  236. const ulWithMotion = <Collapsible motion={subNavMotion} isOpen={isOpen} keepDOM={false} fade={true}>
  237. {
  238. !isCollapsed ? <ul
  239. className={subNavCls}
  240. >
  241. {children}
  242. </ul>: null
  243. }
  244. </Collapsible>;
  245. const finalDom = isHorizontal ? null : subNavMotion ? (
  246. ulWithMotion
  247. ) : isOpen && !isCollapsed ? (
  248. <ul className={subNavCls}>{children}</ul>
  249. ) : null;
  250. return finalDom;
  251. }
  252. wrapDropdown(elem: React.ReactNode = '') {
  253. let _elem: React.ReactNode = elem;
  254. const { children, dropdownStyle, disabled } = this.props;
  255. const { mode, isInSubNav, isCollapsed, subNavCloseDelay, subNavOpenDelay, prefixCls, getPopupContainer } = this.context;
  256. const isOpen = this.adapter.getIsOpen();
  257. const openKeysIsControlled = this.adapter.getOpenKeysIsControlled();
  258. const subNavCls = cls({
  259. [`${prefixCls}-popover`]: isCollapsed,
  260. });
  261. const dropdownProps: DropdownProps = {
  262. trigger: 'hover',
  263. style: dropdownStyle,
  264. };
  265. if (openKeysIsControlled) {
  266. dropdownProps.trigger = 'custom';
  267. dropdownProps.visible = isOpen;
  268. }
  269. if (getPopupContainer) {
  270. dropdownProps.getPopupContainer = getPopupContainer;
  271. }
  272. if (isCollapsed || mode === strings.MODE_HORIZONTAL) {
  273. // Do not show dropdown when disabled
  274. _elem = !disabled ? (
  275. <Dropdown
  276. className={subNavCls}
  277. render={(
  278. <Dropdown.Menu>
  279. {/* <li className={`${prefixCls}-popover-crumb`} /> */}
  280. {children}
  281. </Dropdown.Menu>
  282. )}
  283. position={mode === strings.MODE_HORIZONTAL && !isInSubNav ? 'bottomLeft' : 'rightTop'}
  284. mouseEnterDelay={subNavOpenDelay}
  285. mouseLeaveDelay={subNavCloseDelay}
  286. onVisibleChange={this.handleDropdownVisible}
  287. {...dropdownProps}
  288. >
  289. {_elem}
  290. </Dropdown>
  291. ) : _elem;
  292. }
  293. return _elem;
  294. }
  295. render() {
  296. const { itemKey, style, onMouseEnter, onMouseLeave, disabled, text } = this.props;
  297. const { mode, isCollapsed, prefixCls } = this.context;
  298. let titleDiv: React.ReactNode = this.renderTitleDiv();
  299. const subUl = this.renderSubUl();
  300. // When mode=horizontal, it is displayed in Dropdown
  301. if (isCollapsed || mode === strings.MODE_HORIZONTAL) {
  302. titleDiv = this.wrapDropdown(titleDiv);
  303. }
  304. return (
  305. <NavItem
  306. style={style}
  307. isSubNav={true}
  308. itemKey={itemKey}
  309. forwardRef={this.setItemRef}
  310. isCollapsed={isCollapsed}
  311. className={`${prefixCls}-sub-wrap`}
  312. onMouseEnter={onMouseEnter}
  313. onMouseLeave={onMouseLeave}
  314. disabled={disabled}
  315. text={text}
  316. >
  317. <NavContext.Provider value={{ ...this.context, isInSubNav: true }}>
  318. {titleDiv}
  319. {subUl}
  320. </NavContext.Provider>
  321. </NavItem>
  322. );
  323. }
  324. }