index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. preventScroll: PropTypes.bool,
  45. };
  46. static defaultProps: TabsProps = {
  47. children: [],
  48. collapsible: false,
  49. keepDOM: true,
  50. lazyRender: false,
  51. onChange: () => undefined,
  52. onTabClick: () => undefined,
  53. size: 'large',
  54. tabPaneMotion: true,
  55. tabPosition: 'top',
  56. type: 'line',
  57. onTabClose: () => undefined
  58. };
  59. contentRef: RefObject<HTMLDivElement>;
  60. contentHeight: string;
  61. foundation: TabsFoundation;
  62. constructor(props: TabsProps) {
  63. super(props);
  64. this.foundation = new TabsFoundation(this.adapter);
  65. this.state = {
  66. activeKey: this.foundation.getDefaultActiveKey(),
  67. panes: [],
  68. };
  69. this.contentRef = createRef();
  70. this.contentHeight = 'auto';
  71. }
  72. get adapter(): TabsAdapter<TabsProps, TabsState> {
  73. return {
  74. ...super.adapter,
  75. collectPane: (): void => {
  76. const { tabList, children } = this.props;
  77. if (Array.isArray(tabList) && tabList.length) {
  78. this.setState({ panes: tabList });
  79. return;
  80. }
  81. const panes = React.Children.map(children, (child: any) => {
  82. if (child) {
  83. const { tab, icon, disabled, itemKey, closable } = child.props;
  84. return { tab, icon, disabled, itemKey, closable };
  85. }
  86. return undefined;
  87. });
  88. this.setState({ panes });
  89. },
  90. collectActiveKey: (): void => {
  91. let panes = [];
  92. const { tabList, children, activeKey: propsActiveKey } = this.props;
  93. if (typeof propsActiveKey !== 'undefined') {
  94. return;
  95. }
  96. const { activeKey } = this.state;
  97. if (Array.isArray(tabList) && tabList.length) {
  98. panes = tabList;
  99. } else {
  100. panes = React.Children.map(children, (child: any) => {
  101. if (child) {
  102. const { tab, icon, disabled, itemKey, closable } = child.props;
  103. return { tab, icon, disabled, itemKey, closable };
  104. }
  105. return undefined;
  106. });
  107. }
  108. if (panes.findIndex(p => p.itemKey === activeKey) === -1){
  109. if (panes.length>0){
  110. this.setState({ activeKey: panes[0].itemKey });
  111. } else {
  112. this.setState({ activeKey: '' });
  113. }
  114. }
  115. },
  116. notifyTabClick: (activeKey: string, event: MouseEvent<HTMLDivElement>): void => {
  117. this.props.onTabClick(activeKey, event);
  118. },
  119. notifyChange: (activeKey: string): void => {
  120. this.props.onChange(activeKey);
  121. },
  122. setNewActiveKey: (activeKey: string): void => {
  123. this.setState({ activeKey });
  124. },
  125. getDefaultActiveKeyFromChildren: (): string => {
  126. const { tabList, children } = this.props;
  127. let activeKey = '';
  128. const list = tabList ? tabList : React.Children.toArray(children).map((child) => isValidElement(child) ? child.props : null);
  129. list.forEach(item => {
  130. if (item && !activeKey && !item.disabled) {
  131. activeKey = item.itemKey;
  132. }
  133. });
  134. return activeKey;
  135. },
  136. notifyTabDelete: (tabKey: string) => {
  137. this.props.onTabClose && this.props.onTabClose(tabKey);
  138. }
  139. };
  140. }
  141. static getDerivedStateFromProps(props: TabsProps, state: TabsState): Partial<TabsState> {
  142. const states: Partial<TabsState> = {};
  143. if (!isNullOrUndefined(props.activeKey) && props.activeKey !== state.activeKey) {
  144. states.activeKey = props.activeKey;
  145. }
  146. return states;
  147. }
  148. componentDidUpdate(prevProps: TabsProps): void {
  149. // Panes state acts on tab bar, no need to compare TabPane children
  150. const prevChildrenProps = React.Children.toArray(prevProps.children).map((child) =>
  151. pick(isValidElement(child) ? child.props : null, panePickKeys)
  152. );
  153. const nowChildrenProps = React.Children.toArray(this.props.children).map((child) =>
  154. pick(isValidElement(child) ? child.props : null, panePickKeys)
  155. );
  156. const isTabListType = this.props.tabList || prevProps.tabList;
  157. if (!isEqual(this.props.tabList, prevProps.tabList)) {
  158. this.foundation.handleTabListChange();
  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. onTabClick = (activeKey: string, event: MouseEvent<HTMLDivElement>): void => {
  172. this.foundation.handleTabClick(activeKey, event);
  173. };
  174. /* istanbul ignore next */
  175. rePosChildren = (children: ReactElement[], activeKey: string): ReactElement[] => {
  176. const newChildren: ReactElement[] = [];
  177. const falttenChildren = React.Children.toArray(children) as ReactElement[];
  178. if (children.length) {
  179. newChildren.push(...falttenChildren.filter(child => child.props && child.props.itemKey === activeKey));
  180. newChildren.push(...falttenChildren.filter(child => child.props && child.props.itemKey !== activeKey));
  181. }
  182. return newChildren;
  183. };
  184. getActiveItem = (): ReactNode | ReactNode[] => {
  185. const { activeKey } = this.state;
  186. const { children, tabList } = this.props;
  187. if (tabList || !Array.isArray(children)) {
  188. return children;
  189. }
  190. return React.Children.toArray(children).filter((pane) => {
  191. if (isValidElement(pane) && pane.type && (pane.type as any).isTabPane) {
  192. return pane.props.itemKey === activeKey;
  193. }
  194. return true;
  195. });
  196. };
  197. deleteTabItem = (tabKey: string, event: MouseEvent<HTMLDivElement>) => {
  198. event.stopPropagation();
  199. this.foundation.handleTabDelete(tabKey);
  200. }
  201. render(): ReactNode {
  202. const {
  203. children,
  204. className,
  205. collapsible,
  206. contentStyle,
  207. keepDOM,
  208. lazyRender,
  209. renderTabBar,
  210. size,
  211. style,
  212. tabBarClassName,
  213. tabBarExtraContent,
  214. tabBarStyle,
  215. tabPaneMotion,
  216. tabPosition,
  217. type,
  218. ...restProps
  219. } = this.props;
  220. const { panes, activeKey } = this.state;
  221. const tabWrapperCls = cls(className, {
  222. [cssClasses.TABS]: true,
  223. [`${cssClasses.TABS}-${tabPosition}`]: tabPosition,
  224. });
  225. const tabContentCls = cls({
  226. [cssClasses.TABS_CONTENT]: true,
  227. [`${cssClasses.TABS_CONTENT}-${tabPosition}`]: tabPosition,
  228. });
  229. const tabBarProps = {
  230. activeKey,
  231. className: tabBarClassName,
  232. collapsible,
  233. list: panes,
  234. onTabClick: this.onTabClick,
  235. size,
  236. style: tabBarStyle,
  237. tabBarExtraContent,
  238. tabPosition,
  239. type,
  240. deleteTabItem: this.deleteTabItem,
  241. handleKeyDown: this.foundation.handleKeyDown
  242. } as TabBarProps;
  243. const tabBar = renderTabBar ? renderTabBar(tabBarProps, TabBar) : <TabBar {...tabBarProps} />;
  244. const content = keepDOM ? children : this.getActiveItem();
  245. return (
  246. <div className={tabWrapperCls} style={style} {...getDataAttr(restProps)}>
  247. {tabBar}
  248. <TabsContext.Provider
  249. value={{
  250. activeKey,
  251. lazyRender,
  252. panes,
  253. tabPaneMotion,
  254. tabPosition,
  255. }}
  256. >
  257. <div
  258. ref={this.setContentRef}
  259. className={tabContentCls}
  260. style={{ ...contentStyle }}
  261. >
  262. {content}
  263. </div>
  264. </TabsContext.Provider>
  265. </div>
  266. );
  267. }
  268. }
  269. export default Tabs;