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