index.tsx 12 KB

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