index.tsx 12 KB

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