-
Notifications
You must be signed in to change notification settings - Fork 120
/
index.tsx
127 lines (120 loc) · 3.52 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import React from 'react';
import { useCallback } from 'react';
import update from 'immutability-helper';
import {
prefixClaName,
getBEMElement,
getBEMModifier,
classNames,
} from 'mo/common/className';
import { Tab, ITabProps } from './tab';
import DragAndDrop from './dragAndDrop';
import type { UniqueId } from 'mo/common/types';
export type TabsType = 'line' | 'card';
/**
* TODO: Get rid of the generic and remove the ComponentProps
*/
export interface ITabsProps<T = any> extends React.ComponentProps<any> {
className?: string;
style?: React.CSSProperties;
role?: string;
/**
* @deprecated For now, we don't need to control the global closable
*/
closable?: boolean;
/**
* @deprecated For now, we don't need to control the global editable
*/
editable?: boolean;
data?: ITabProps[];
activeTab?: UniqueId;
/**
* Default is line
*/
type?: TabsType;
onCloseTab?: (key: UniqueId) => void;
onContextMenu?: (e: React.MouseEvent, tab: ITabProps) => void;
onMoveTab?: (tabs: ITabProps[]) => void;
onSelectTab?: (key: UniqueId) => void;
}
export const tabsClassName = prefixClaName('tabs');
export const tabsHeader = getBEMElement(tabsClassName, 'header');
export function Tabs(props: ITabsProps) {
const {
role,
activeTab,
className,
data = [],
type = 'line',
style,
onMoveTab,
onCloseTab,
onSelectTab,
onContextMenu,
} = props;
const onChangeTab = useCallback(
(dragIndex, hoverIndex) => {
const dragTab = data[dragIndex];
onMoveTab?.(
update(data, {
$splice: [
[dragIndex, 1],
[hoverIndex, 0, dragTab],
],
})
);
},
[data]
);
const handleDrag = (
source: ITabProps,
target: ITabProps,
infos: Record<string, any>
) => {
const dragIndex = data.indexOf(source);
const hoverIndex = data.indexOf(target);
const { hoverClientX, hoverMiddleX } = infos;
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
return;
}
// drag down
if (dragIndex < hoverIndex && hoverClientX < hoverMiddleX) {
return;
}
// drag up
if (dragIndex > hoverIndex && hoverClientX > hoverMiddleX) {
return;
}
onChangeTab?.(dragIndex, hoverIndex);
};
return (
<DragAndDrop>
<div
style={style}
className={classNames(
tabsClassName,
getBEMModifier(tabsClassName, type as string),
className
)}
role={role}
>
<div className={tabsHeader}>
{data.map((tab, index) => {
return (
<Tab
key={tab.id}
active={activeTab === tab.id}
tab={tab}
onDrag={handleDrag}
onCloseTab={onCloseTab}
onContextMenu={onContextMenu}
onSelectTab={onSelectTab}
/>
);
})}
</div>
</div>
</DragAndDrop>
);
}