index.tsx 9.2 KB

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