index.tsx 11 KB

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