index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import React, { createRef, isValidElement, MouseEvent, ReactElement, ReactNode, RefCallback, RefObject } from 'react';
  2. import cls from 'classnames';
  3. import PropTypes from 'prop-types';
  4. import { cssClasses, strings } from '@douyinfe/semi-foundation/tabs/constants';
  5. import isNullOrUndefined from '@douyinfe/semi-foundation/utils/isNullOrUndefined';
  6. import TabsFoundation, { TabsAdapter } from '@douyinfe/semi-foundation/tabs/foundation';
  7. import { isEqual, pick } from 'lodash';
  8. import BaseComponent from '../_base/baseComponent';
  9. import '@douyinfe/semi-foundation/tabs/tabs.scss';
  10. import TabBar from './TabBar';
  11. import TabPane from './TabPane';
  12. import TabItem from './TabItem';
  13. import TabsContext from './tabs-context';
  14. import { PlainTab, TabBarProps, TabsProps } from './interface';
  15. import { getDefaultPropsFromGlobalConfig } from "../_utils";
  16. const panePickKeys = ['className', 'style', 'disabled', 'itemKey', 'tab', 'icon'];
  17. export * from './interface';
  18. export interface TabsState {
  19. activeKey: string;
  20. panes: Array<PlainTab>;
  21. prevActiveKey: string | null;
  22. forceDisableMotion: boolean
  23. }
  24. class Tabs extends BaseComponent<TabsProps, TabsState> {
  25. static TabPane = TabPane;
  26. static TabItem = TabItem;
  27. static propTypes = {
  28. activeKey: PropTypes.string,
  29. className: PropTypes.string,
  30. collapsible: PropTypes.bool,
  31. contentStyle: PropTypes.oneOfType([PropTypes.object]),
  32. defaultActiveKey: PropTypes.string,
  33. keepDOM: PropTypes.bool,
  34. lazyRender: PropTypes.bool,
  35. onChange: PropTypes.func,
  36. onTabClick: PropTypes.func,
  37. renderTabBar: PropTypes.func,
  38. showRestInDropdown: PropTypes.bool,
  39. size: PropTypes.oneOf(strings.SIZE),
  40. style: PropTypes.object,
  41. tabBarClassName: PropTypes.string,
  42. tabBarExtraContent: PropTypes.node,
  43. tabBarStyle: PropTypes.object,
  44. tabList: PropTypes.array,
  45. tabPaneMotion: PropTypes.bool,
  46. tabPosition: PropTypes.oneOf(strings.POSITION_MAP),
  47. type: PropTypes.oneOf(strings.TYPE_MAP),
  48. onTabClose: PropTypes.func,
  49. preventScroll: PropTypes.bool,
  50. more: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
  51. arrowPosition: PropTypes.string,
  52. renderArrow: PropTypes.func,
  53. dropdownProps: PropTypes.object,
  54. };
  55. static __SemiComponentName__ = "Tabs";
  56. static defaultProps: TabsProps = getDefaultPropsFromGlobalConfig(Tabs.__SemiComponentName__, {
  57. children: [],
  58. collapsible: false,
  59. keepDOM: true,
  60. lazyRender: false,
  61. onChange: () => undefined,
  62. onTabClick: () => undefined,
  63. size: 'large',
  64. tabPaneMotion: true,
  65. tabPosition: 'top',
  66. type: 'line',
  67. onTabClose: () => undefined,
  68. showRestInDropdown: true,
  69. arrowPosition: "both",
  70. });
  71. contentRef: RefObject<HTMLDivElement>;
  72. contentHeight: string;
  73. foundation: TabsFoundation;
  74. constructor(props: TabsProps) {
  75. super(props);
  76. this.foundation = new TabsFoundation(this.adapter);
  77. this.state = {
  78. activeKey: this.foundation.getDefaultActiveKey(),
  79. panes: this.getPanes(),
  80. prevActiveKey: null,
  81. forceDisableMotion: false
  82. };
  83. this.contentRef = createRef();
  84. this.contentHeight = 'auto';
  85. }
  86. get adapter(): TabsAdapter<TabsProps, TabsState> {
  87. return {
  88. ...super.adapter,
  89. collectPane: (): void => {
  90. const panes = this.getPanes();
  91. this.setState({ panes });
  92. },
  93. collectActiveKey: (): void => {
  94. const { tabList, children, activeKey: propsActiveKey } = this.props;
  95. if (typeof propsActiveKey !== 'undefined') {
  96. return;
  97. }
  98. const { activeKey } = this.state;
  99. const panes = this.getPanes();
  100. if (panes.findIndex(p => p.itemKey === activeKey) === -1) {
  101. if (panes.length > 0) {
  102. this.setState({ activeKey: panes[0].itemKey });
  103. } else {
  104. this.setState({ activeKey: '' });
  105. }
  106. }
  107. },
  108. notifyTabClick: (activeKey: string, event: MouseEvent<HTMLDivElement>): void => {
  109. this.props.onTabClick(activeKey, event);
  110. },
  111. notifyChange: (activeKey: string): void => {
  112. this.props.onChange(activeKey);
  113. },
  114. setNewActiveKey: (activeKey: string): void => {
  115. this.setState({ activeKey });
  116. },
  117. getDefaultActiveKeyFromChildren: (): string => {
  118. const { tabList, children } = this.props;
  119. let activeKey = '';
  120. const list = tabList ? tabList : React.Children.toArray(children).map((child) => isValidElement(child) ? child.props : null);
  121. list.forEach(item => {
  122. if (item && !activeKey && !item.disabled) {
  123. activeKey = item.itemKey;
  124. }
  125. });
  126. return activeKey;
  127. },
  128. notifyTabDelete: (tabKey: string) => {
  129. this.props.onTabClose && this.props.onTabClose(tabKey);
  130. }
  131. };
  132. }
  133. static getDerivedStateFromProps(props: TabsProps, state: TabsState): Partial<TabsState> {
  134. const states: Partial<TabsState> = {};
  135. if (!isNullOrUndefined(props.activeKey) && props.activeKey !== state.activeKey) {
  136. state.prevActiveKey = state.activeKey;
  137. states.activeKey = props.activeKey;
  138. }
  139. return states;
  140. }
  141. componentDidUpdate(prevProps: TabsProps, prevState: TabsState): void {
  142. // Panes state acts on tab bar, no need to compare TabPane children
  143. const prevChildrenProps = React.Children.toArray(prevProps.children).map((child) =>
  144. pick(isValidElement(child) ? child.props : null, panePickKeys)
  145. );
  146. const nowChildrenProps = React.Children.toArray(this.props.children).map((child) =>
  147. pick(isValidElement(child) ? child.props : null, panePickKeys)
  148. );
  149. const isTabListType = this.props.tabList || prevProps.tabList;
  150. if (!isEqual(this.props.tabList, prevProps.tabList)) {
  151. this.foundation.handleTabListChange();
  152. }
  153. if (prevState.activeKey !== this.state.activeKey && prevState.activeKey !== this.state.prevActiveKey) {
  154. this.setState({ prevActiveKey: prevState.activeKey });
  155. }
  156. if (prevProps.activeKey !== this.props.activeKey) {
  157. const newAddedPanelItemKey = (() => {
  158. const prevItemKeys = new Set(prevChildrenProps.map(p => p.itemKey));
  159. return nowChildrenProps.map(p => p.itemKey).filter(itemKey => !prevItemKeys.has(itemKey));
  160. })();
  161. this.setState({ forceDisableMotion: newAddedPanelItemKey.includes(this.props.activeKey) });
  162. }
  163. // children变化,tabList方式使用时,啥也不用做
  164. // children变化,非tabList方式使用,需要重新取activeKey。TabPane可能是异步更新的,若不重新取,未设activeKey时,第一个不会自动激活
  165. // children changed: do nothing in tabList case
  166. // children changed: recalc activeKey. TabPane could be updated async. If not recalc the first panel will not be activated
  167. if (!isEqual(prevChildrenProps, nowChildrenProps) && !isTabListType) {
  168. this.foundation.handleTabPanesChange();
  169. }
  170. }
  171. setContentRef: RefCallback<HTMLDivElement> = ref => {
  172. this.contentRef = { current: ref };
  173. };
  174. getPanes = (): PlainTab[] => {
  175. const { tabList, children } = this.props;
  176. if (Array.isArray(tabList) && tabList.length) {
  177. return tabList;
  178. }
  179. return React.Children.map(children, (child: any) => {
  180. if (child) {
  181. const { tab, icon, disabled, itemKey, closable } = child.props;
  182. return { tab, icon, disabled, itemKey, closable };
  183. }
  184. return undefined;
  185. });
  186. };
  187. onTabClick = (activeKey: string, event: MouseEvent<HTMLDivElement>): void => {
  188. this.foundation.handleTabClick(activeKey, event);
  189. };
  190. /* istanbul ignore next */
  191. rePosChildren = (children: ReactElement[], activeKey: string): ReactElement[] => {
  192. const newChildren: ReactElement[] = [];
  193. const falttenChildren = React.Children.toArray(children) as ReactElement[];
  194. if (children.length) {
  195. newChildren.push(...falttenChildren.filter(child => child.props && child.props.itemKey === activeKey));
  196. newChildren.push(...falttenChildren.filter(child => child.props && child.props.itemKey !== activeKey));
  197. }
  198. return newChildren;
  199. };
  200. getActiveItem = (): ReactNode | ReactNode[] => {
  201. const { activeKey } = this.state;
  202. const { children, tabList } = this.props;
  203. if (tabList || !Array.isArray(children)) {
  204. return children;
  205. }
  206. return React.Children.toArray(children).filter((pane) => {
  207. if (isValidElement(pane) && pane.type && (pane.type as any).isTabPane) {
  208. return pane.props.itemKey === activeKey;
  209. }
  210. return true;
  211. });
  212. };
  213. deleteTabItem = (tabKey: string, event: MouseEvent<HTMLDivElement>) => {
  214. event.stopPropagation();
  215. this.foundation.handleTabDelete(tabKey);
  216. }
  217. render(): ReactNode {
  218. const {
  219. children,
  220. className,
  221. collapsible,
  222. contentStyle,
  223. keepDOM,
  224. lazyRender,
  225. renderTabBar,
  226. showRestInDropdown,
  227. size,
  228. style,
  229. tabBarClassName,
  230. tabBarExtraContent,
  231. tabBarStyle,
  232. tabPaneMotion,
  233. tabPosition,
  234. type,
  235. more,
  236. onVisibleTabsChange,
  237. visibleTabsStyle,
  238. arrowPosition,
  239. renderArrow,
  240. dropdownProps,
  241. ...restProps
  242. } = this.props;
  243. const { panes, activeKey } = this.state;
  244. const tabWrapperCls = cls(className, {
  245. [cssClasses.TABS]: true,
  246. [`${cssClasses.TABS}-${tabPosition}`]: tabPosition,
  247. });
  248. const tabContentCls = cls({
  249. [cssClasses.TABS_CONTENT]: true,
  250. [`${cssClasses.TABS_CONTENT}-${tabPosition}`]: tabPosition,
  251. });
  252. const tabBarProps = {
  253. activeKey,
  254. className: tabBarClassName,
  255. collapsible,
  256. list: panes,
  257. onTabClick: this.onTabClick,
  258. showRestInDropdown,
  259. size,
  260. style: tabBarStyle,
  261. tabBarExtraContent,
  262. tabPosition,
  263. type,
  264. deleteTabItem: this.deleteTabItem,
  265. handleKeyDown: this.foundation.handleKeyDown,
  266. more,
  267. onVisibleTabsChange,
  268. visibleTabsStyle,
  269. arrowPosition,
  270. renderArrow,
  271. dropdownProps,
  272. } as TabBarProps;
  273. const tabBar = renderTabBar ? renderTabBar(tabBarProps, TabBar) : <TabBar {...tabBarProps} />;
  274. const content = keepDOM ? children : this.getActiveItem();
  275. return (
  276. <div className={tabWrapperCls} style={style} {...this.getDataAttr(restProps)}>
  277. {tabBar}
  278. <TabsContext.Provider
  279. value={{
  280. activeKey,
  281. lazyRender,
  282. panes,
  283. tabPaneMotion,
  284. tabPosition,
  285. prevActiveKey: this.state.prevActiveKey,
  286. forceDisableMotion: this.state.forceDisableMotion
  287. }}
  288. >
  289. <div
  290. ref={this.setContentRef}
  291. className={tabContentCls}
  292. style={{ ...contentStyle }}
  293. >
  294. {content}
  295. </div>
  296. </TabsContext.Provider>
  297. </div>
  298. );
  299. }
  300. }
  301. export default Tabs;