-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
useTabs.ts
250 lines (213 loc) · 7.79 KB
/
useTabs.ts
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import React, { useEffect, useState, useCallback } from 'react';
import { usePersistFn } from 'ahooks';
import _find from 'lodash/find';
import _findIndex from 'lodash/findIndex';
import _isEqual from 'lodash/isEqual';
import _omit from 'lodash/omit';
import { useLocation } from 'react-router';
import { useReallyPrevious } from '@/hooks/common';
import Logger from '@/utils/Logger';
import { UmiChildren, RouteTab, UseTabsOptions, BeautifulLocation } from './data';
import { getActiveTabInfo, routeTo } from './utils';
const logger = new Logger('useTabs');
function useTabs(options: UseTabsOptions) {
const location = useLocation() as BeautifulLocation;
const { mode = 'route', setTabTitle, originalMenuData, children } = options;
const [tabs, setTabs] = useState<RouteTab[]>([]);
const { id: activeKey, hash, title: activeTitle, item: menuItem } = getActiveTabInfo(location)(
mode,
originalMenuData,
setTabTitle,
);
/** 可指定 key,默认使用 activeKey */
const getTabKey = useCallback(
(key?: string) => (mode === 'args' ? `${key || activeKey}-${hash}` : key || activeKey),
[activeKey],
);
const prevActiveKey = useReallyPrevious(getTabKey());
const getTab = usePersistFn((tabKey: string) => _find(tabs, { key: tabKey }));
const processTabs = usePersistFn((_tabs: RouteTab[]) =>
_tabs.map(item => (_tabs.length === 1 ? { ...item, closable: false } : item)),
);
/** 获取激活标签页的相邻标签页 */
const getNextTab = usePersistFn(() => {
const removeIndex = _findIndex(tabs, { key: getTabKey() });
const nextIndex = removeIndex >= 1 ? removeIndex - 1 : removeIndex + 1;
return tabs[nextIndex];
});
/**
* force: 是否在目标标签页不存在的时候强制回调函数
*/
const handleSwitch = usePersistFn(
(keyToSwitch: string, callback?: () => void, force: boolean = false) => {
if (!keyToSwitch) {
return;
}
/**
* `keyToSwitch` 有值时,`targetTab` 可能为空。
*
* 如:一个会调用 `window.closeAndGoBackTab(path)` 的页面在 F5 刷新之后
*/
const targetTab = getTab(keyToSwitch);
routeTo(targetTab ? targetTab.extraTabProperties.location : keyToSwitch);
if (force) {
callback?.();
} else {
targetTab && callback?.();
}
},
);
/** 删除标签页处理事件,可接收一个 `nextTabKey` 参数,自定义需要返回的标签页 */
const handleRemove = usePersistFn(
(removeKey: string, nextTabKey?: string | false, callback?: () => void, force?: boolean) => {
const getNextTabKeyByRemove = () =>
removeKey === getTabKey() ? getNextTab()?.key : getTabKey();
/** 如果 nextTabKey 为 false 时,不执行切换便签页操作,因此需要注意如此调用后应该还有已打开的标签页 */
if (nextTabKey !== false) {
handleSwitch(nextTabKey || getNextTabKeyByRemove(), callback, force);
}
setTabs(prevTabs => processTabs(prevTabs.filter(item => item.key !== removeKey)));
},
);
const handleRemoveOthers = usePersistFn((currentKey: string, callback?: () => void) => {
handleSwitch(currentKey, callback);
setTabs(prevTabs => processTabs(prevTabs.filter(item => item.key === currentKey)));
});
const handRemoveRightTabs = usePersistFn((currentKey: string, callback?: () => void) => {
handleSwitch(getTab(currentKey)!.key, callback);
setTabs(prevTabs =>
processTabs(prevTabs.slice(0, _findIndex(prevTabs, { key: currentKey }) + 1)),
);
});
/**
* 新增第一个 tab 不可删除
*
* @param newTab
*/
const addTab = usePersistFn((newTab: RouteTab, followPath?: string) => {
setTabs(prevTabs => {
let result = [...prevTabs];
if (followPath) {
const targetIndex = _findIndex(prevTabs, { key: getTabKey(followPath) });
if (targetIndex >= 0) {
result.splice(targetIndex + 1, 0, newTab);
} else {
result = [...result, newTab];
}
} else {
result = [...result, newTab];
}
return result.map((item, index) =>
tabs.length === 0 && index === 0
? { ...item, closable: false }
: { ...item, closable: true },
);
});
});
/**
* 重载标签页,传入参数重写相关属性
*
* @param reloadKey 需要刷新的 tab key
* @param tabTitle 需要刷新的 tab 标题
* @param extraTabProperties 需要刷新的 tab 额外属性
* @param content 需要刷新的 tab 渲染的内容
*/
const reloadTab = usePersistFn(
(
reloadKey: string = getTabKey(),
tabTitle?: React.ReactNode,
extraTabProperties?: any,
content?: UmiChildren,
) => {
logger.log(`reload tab key: ${reloadKey}`);
setTabs(prevTabs =>
prevTabs.map(item => {
if (item.key === reloadKey) {
const {
tab: prevTabTitle,
extraTabProperties: prevExtraTabProperties,
content: prevContent,
...rest
} = item;
return {
...rest,
tab: tabTitle || prevTabTitle,
extraTabProperties: extraTabProperties || prevExtraTabProperties,
content: content || React.cloneElement(item.content, { key: new Date().valueOf() }),
};
}
return item;
}),
);
},
);
const goBackTab = usePersistFn((path?: string, callback?: () => void, force?: boolean) => {
if (!path && (!prevActiveKey || !getTab(prevActiveKey))) {
logger.warn('go back failed, no previous actived key or previous tab is closed.');
return;
}
handleSwitch(path || prevActiveKey!, callback, force);
});
/** 关闭后切记需要激活另一个标签页,否则会导致页面空白 */
const closeTab = usePersistFn((path?: string, callback?: () => void, force?: boolean) => {
if (path && !getTab(path)) {
logger.warn('close failed, target tab is closed.');
return;
}
handleRemove(path || getTabKey(), false, callback, force);
});
/** 关闭当前标签页并返回到上次打开的标签页 */
const closeAndGoBackTab = usePersistFn(
(path?: string, callback?: () => void, force?: boolean) => {
if (!path && (!prevActiveKey || !getTab(prevActiveKey))) {
logger.warn('close and go back failed, no previous actived key or previous tab is closed.');
return;
}
handleRemove(getTabKey(), path || prevActiveKey, callback, force);
},
);
useEffect(() => {
window.reloadTab = reloadTab;
window.goBackTab = goBackTab;
window.closeTab = closeTab;
window.closeAndGoBackTab = closeAndGoBackTab;
return () => {
const hint = () => {
logger.warn(`PageTabs had unmounted.`);
};
window.reloadTab = hint;
window.goBackTab = hint;
window.closeAndGoBackTab = hint;
};
}, []);
useEffect(() => {
const currentExtraTabProperties = { location: _omit(location, ['key']) };
const activedTab = getTab(getTabKey());
if (activedTab) {
const { extraTabProperties: prevExtraTabProperties } = activedTab;
if (!_isEqual(currentExtraTabProperties, prevExtraTabProperties)) {
reloadTab(getTabKey(), activeTitle, currentExtraTabProperties, children);
}
logger.log(`no effect of tab key: ${getTabKey()}`);
} else {
const newTab = {
tab: activeTitle,
key: getTabKey(),
content: children as any,
extraTabProperties: currentExtraTabProperties,
};
const { followPath } = menuItem || {};
logger.log(`add tab key: ${getTabKey()}`);
addTab(newTab, followPath);
}
}, [children]);
return {
tabs,
activeKey: getTabKey(),
handleSwitch,
handleRemove,
handleRemoveOthers,
handRemoveRightTabs,
};
}
export default useTabs;