SubNav.tsx 14 KB

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