index.tsx 12 KB

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