multipleTab.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. import type { RouteLocationNormalized, RouteLocationRaw, Router } from 'vue-router';
  2. import { toRaw, unref } from 'vue';
  3. import { defineStore } from 'pinia';
  4. import { store } from '@/store';
  5. import { useGo, useRedo } from '@/hooks/web/usePage';
  6. import { Persistent } from '@/utils/cache/persistent';
  7. import { PageEnum } from '@/enums/pageEnum';
  8. import { PAGE_NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '@/router/routes/basic';
  9. import { getRawRoute } from '@/utils';
  10. import { MULTIPLE_TABS_KEY } from '@/enums/cacheEnum';
  11. import projectSetting from '@/settings/projectSetting';
  12. import { useUserStore } from '@/store/modules/user';
  13. export interface MultipleTabState {
  14. cacheTabList: Set<string>;
  15. tabList: RouteLocationNormalized[];
  16. lastDragEndIndex: number;
  17. }
  18. function handleGotoPage(router: Router) {
  19. const go = useGo(router);
  20. go(unref(router.currentRoute).fullPath, true);
  21. }
  22. const getToTarget = (tabItem: RouteLocationNormalized) => {
  23. const { params, path, query } = tabItem;
  24. return {
  25. params: params || {},
  26. path,
  27. query: query || {},
  28. };
  29. };
  30. const cacheTab = projectSetting.multiTabsSetting.cache;
  31. export const useMultipleTabStore = defineStore({
  32. id: 'app-multiple-tab',
  33. state: (): MultipleTabState => ({
  34. // Tabs that need to be cached
  35. cacheTabList: new Set(),
  36. // multiple tab list
  37. tabList: cacheTab ? Persistent.getLocal(MULTIPLE_TABS_KEY) || [] : [],
  38. // Index of the last moved tab
  39. lastDragEndIndex: 0,
  40. }),
  41. getters: {
  42. getTabList(state): RouteLocationNormalized[] {
  43. return state.tabList;
  44. },
  45. getCachedTabList(state): string[] {
  46. return Array.from(state.cacheTabList);
  47. },
  48. getLastDragEndIndex(state): number {
  49. return state.lastDragEndIndex;
  50. },
  51. },
  52. actions: {
  53. /**
  54. * Update the cache according to the currently opened tabs
  55. */
  56. async updateCacheTab() {
  57. const cacheMap: Set<string> = new Set();
  58. for (const tab of this.tabList) {
  59. const item = getRawRoute(tab);
  60. // Ignore the cache
  61. const needCache = !item.meta?.ignoreKeepAlive;
  62. if (!needCache) {
  63. continue;
  64. }
  65. const name = item.name as string;
  66. cacheMap.add(name);
  67. }
  68. this.cacheTabList = cacheMap;
  69. },
  70. /**
  71. * Refresh tabs
  72. */
  73. async refreshPage(router: Router) {
  74. const { currentRoute } = router;
  75. const route = unref(currentRoute);
  76. const name = route.name;
  77. const findTab = this.getCachedTabList.find((item) => item === name);
  78. if (findTab) {
  79. this.cacheTabList.delete(findTab);
  80. }
  81. const redo = useRedo(router);
  82. await redo();
  83. },
  84. clearCacheTabs(): void {
  85. this.cacheTabList = new Set();
  86. },
  87. resetState(): void {
  88. this.tabList = [];
  89. this.clearCacheTabs();
  90. },
  91. goToPage(router: Router) {
  92. const go = useGo(router);
  93. const len = this.tabList.length;
  94. const { path } = unref(router.currentRoute);
  95. let toPath: PageEnum | string = PageEnum.BASE_HOME;
  96. if (len > 0) {
  97. const page = this.tabList[len - 1];
  98. const p = page.fullPath || page.path;
  99. if (p) {
  100. toPath = p;
  101. }
  102. }
  103. // Jump to the current page and report an error
  104. path !== toPath && go(toPath as PageEnum, true);
  105. },
  106. async addTab(route: RouteLocationNormalized) {
  107. const { path, name, fullPath, params, query, meta } = getRawRoute(route);
  108. // 404 The page does not need to add a tab
  109. if (
  110. path === PageEnum.ERROR_PAGE ||
  111. path === PageEnum.BASE_LOGIN ||
  112. !name ||
  113. [REDIRECT_ROUTE.name, PAGE_NOT_FOUND_ROUTE.name].includes(name as string)
  114. ) {
  115. return;
  116. }
  117. let updateIndex = -1;
  118. // Existing pages, do not add tabs repeatedly
  119. const tabHasExits = this.tabList.some((tab, index) => {
  120. updateIndex = index;
  121. return (tab.fullPath || tab.path) === (fullPath || path);
  122. });
  123. // If the tab already exists, perform the update operation
  124. if (tabHasExits) {
  125. const curTab = toRaw(this.tabList)[updateIndex];
  126. if (!curTab) {
  127. return;
  128. }
  129. curTab.params = params || curTab.params;
  130. curTab.query = query || curTab.query;
  131. curTab.fullPath = fullPath || curTab.fullPath;
  132. this.tabList.splice(updateIndex, 1, curTab);
  133. } else {
  134. // Add tab
  135. // 获取动态路由打开数,超过 0 即代表需要控制打开数
  136. const dynamicLevel = meta?.dynamicLevel ?? -1;
  137. if (dynamicLevel > 0) {
  138. // 如果动态路由层级大于 0 了,那么就要限制该路由的打开数限制了
  139. // 首先获取到真实的路由,使用配置方式减少计算开销.
  140. // const realName: string = path.match(/(\S*)\//)![1];
  141. const realPath = meta?.realPath ?? '';
  142. // 获取到已经打开的动态路由数, 判断是否大于某一个值
  143. if (
  144. this.tabList.filter((e) => e.meta?.realPath ?? '' === realPath).length >= dynamicLevel
  145. ) {
  146. // 关闭第一个
  147. const index = this.tabList.findIndex((item) => item.meta.realPath === realPath);
  148. index !== -1 && this.tabList.splice(index, 1);
  149. }
  150. }
  151. this.tabList.push(route);
  152. }
  153. this.updateCacheTab();
  154. cacheTab && Persistent.setLocal(MULTIPLE_TABS_KEY, this.tabList);
  155. },
  156. async closeTab(tab: RouteLocationNormalized, router: Router) {
  157. const close = (route: RouteLocationNormalized) => {
  158. const { fullPath, meta: { affix } = {} } = route;
  159. if (affix) {
  160. return;
  161. }
  162. const index = this.tabList.findIndex((item) => item.fullPath === fullPath);
  163. index !== -1 && this.tabList.splice(index, 1);
  164. };
  165. const { currentRoute, replace } = router;
  166. const { path } = unref(currentRoute);
  167. if (path !== tab.path) {
  168. // Closed is not the activation tab
  169. close(tab);
  170. this.updateCacheTab();
  171. return;
  172. }
  173. // Closed is activated atb
  174. let toTarget: RouteLocationRaw = {};
  175. const index = this.tabList.findIndex((item) => item.path === path);
  176. // If the current is the leftmost tab
  177. if (index === 0) {
  178. // There is only one tab, then jump to the homepage, otherwise jump to the right tab
  179. if (this.tabList.length === 1) {
  180. const userStore = useUserStore();
  181. toTarget = userStore.getUserInfo.homePath || PageEnum.BASE_HOME;
  182. } else {
  183. // Jump to the right tab
  184. const page = this.tabList[index + 1];
  185. toTarget = getToTarget(page);
  186. }
  187. } else {
  188. // Close the current tab
  189. const page = this.tabList[index - 1];
  190. toTarget = getToTarget(page);
  191. }
  192. close(currentRoute.value);
  193. await replace(toTarget);
  194. },
  195. // Close according to key
  196. async closeTabByKey(key: string, router: Router) {
  197. const index = this.tabList.findIndex((item) => (item.fullPath || item.path) === key);
  198. if (index !== -1) {
  199. await this.closeTab(this.tabList[index], router);
  200. const { currentRoute, replace } = router;
  201. // 检查当前路由是否存在于tabList中
  202. const isActivated = this.tabList.findIndex((item) => {
  203. return item.fullPath === currentRoute.value.fullPath;
  204. });
  205. // 如果当前路由不存在于TabList中,尝试切换到其它路由
  206. if (isActivated === -1) {
  207. let pageIndex;
  208. if (index > 0) {
  209. pageIndex = index - 1;
  210. } else if (index < this.tabList.length - 1) {
  211. pageIndex = index + 1;
  212. } else {
  213. pageIndex = -1;
  214. }
  215. if (pageIndex >= 0) {
  216. const page = this.tabList[index - 1];
  217. const toTarget = getToTarget(page);
  218. await replace(toTarget);
  219. }
  220. }
  221. }
  222. },
  223. // Sort the tabs
  224. async sortTabs(oldIndex: number, newIndex: number) {
  225. const currentTab = this.tabList[oldIndex];
  226. this.tabList.splice(oldIndex, 1);
  227. this.tabList.splice(newIndex, 0, currentTab);
  228. this.lastDragEndIndex = this.lastDragEndIndex + 1;
  229. },
  230. // Close the tab on the right and jump
  231. async closeLeftTabs(route: RouteLocationNormalized, router: Router) {
  232. const index = this.tabList.findIndex((item) => item.path === route.path);
  233. if (index > 0) {
  234. const leftTabs = this.tabList.slice(0, index);
  235. const pathList: string[] = [];
  236. for (const item of leftTabs) {
  237. const affix = item?.meta?.affix ?? false;
  238. if (!affix) {
  239. pathList.push(item.fullPath);
  240. }
  241. }
  242. this.bulkCloseTabs(pathList);
  243. }
  244. this.updateCacheTab();
  245. handleGotoPage(router);
  246. },
  247. // Close the tab on the left and jump
  248. async closeRightTabs(route: RouteLocationNormalized, router: Router) {
  249. const index = this.tabList.findIndex((item) => item.fullPath === route.fullPath);
  250. if (index >= 0 && index < this.tabList.length - 1) {
  251. const rightTabs = this.tabList.slice(index + 1, this.tabList.length);
  252. const pathList: string[] = [];
  253. for (const item of rightTabs) {
  254. const affix = item?.meta?.affix ?? false;
  255. if (!affix) {
  256. pathList.push(item.fullPath);
  257. }
  258. }
  259. this.bulkCloseTabs(pathList);
  260. }
  261. this.updateCacheTab();
  262. handleGotoPage(router);
  263. },
  264. async closeAllTab(router: Router) {
  265. this.tabList = this.tabList.filter((item) => item?.meta?.affix ?? false);
  266. this.clearCacheTabs();
  267. this.goToPage(router);
  268. },
  269. /**
  270. * Close other tabs
  271. */
  272. async closeOtherTabs(route: RouteLocationNormalized, router: Router) {
  273. const closePathList = this.tabList.map((item) => item.fullPath);
  274. const pathList: string[] = [];
  275. for (const path of closePathList) {
  276. if (path !== route.fullPath) {
  277. const closeItem = this.tabList.find((item) => item.fullPath === path);
  278. if (!closeItem) {
  279. continue;
  280. }
  281. const affix = closeItem?.meta?.affix ?? false;
  282. if (!affix) {
  283. pathList.push(closeItem.fullPath);
  284. }
  285. }
  286. }
  287. this.bulkCloseTabs(pathList);
  288. this.updateCacheTab();
  289. Persistent.setLocal(MULTIPLE_TABS_KEY, this.tabList, true);
  290. handleGotoPage(router);
  291. },
  292. /**
  293. * Close tabs in bulk
  294. */
  295. async bulkCloseTabs(pathList: string[]) {
  296. this.tabList = this.tabList.filter((item) => !pathList.includes(item.fullPath));
  297. },
  298. /**
  299. * Set tab's title
  300. */
  301. async setTabTitle(title: string, route: RouteLocationNormalized) {
  302. const findTab = this.getTabList.find((item) => item === route);
  303. if (findTab) {
  304. findTab.meta.title = title;
  305. await this.updateCacheTab();
  306. }
  307. },
  308. /**
  309. * replace tab's path
  310. * **/
  311. async updateTabPath(fullPath: string, route: RouteLocationNormalized) {
  312. const findTab = this.getTabList.find((item) => item === route);
  313. if (findTab) {
  314. findTab.fullPath = fullPath;
  315. findTab.path = fullPath;
  316. await this.updateCacheTab();
  317. }
  318. },
  319. },
  320. });
  321. // Need to be used outside the setup
  322. export function useMultipleTabWithOutStore() {
  323. return useMultipleTabStore(store);
  324. }