multipleTab.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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).path, 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(): RouteLocationNormalized[] {
  43. return this.tabList;
  44. },
  45. getCachedTabList(): string[] {
  46. return Array.from(this.cacheTabList);
  47. },
  48. getLastDragEndIndex(): number {
  49. return this.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. // 获取动态路由层级
  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. // 这里先固定为 每个动态路由最大能打开【5】个Tab
  144. if (this.tabList.filter((e) => e.meta?.realPath ?? '' === realPath).length >= 5) {
  145. // 关闭第一个
  146. const index = this.tabList.findIndex((item) => item.meta.realPath === realPath);
  147. index !== -1 && this.tabList.splice(index, 1);
  148. }
  149. }
  150. this.tabList.push(route);
  151. }
  152. this.updateCacheTab();
  153. cacheTab && Persistent.setLocal(MULTIPLE_TABS_KEY, this.tabList);
  154. },
  155. async closeTab(tab: RouteLocationNormalized, router: Router) {
  156. const close = (route: RouteLocationNormalized) => {
  157. const { fullPath, meta: { affix } = {} } = route;
  158. if (affix) {
  159. return;
  160. }
  161. const index = this.tabList.findIndex((item) => item.fullPath === fullPath);
  162. index !== -1 && this.tabList.splice(index, 1);
  163. };
  164. const { currentRoute, replace } = router;
  165. const { path } = unref(currentRoute);
  166. if (path !== tab.path) {
  167. // Closed is not the activation tab
  168. close(tab);
  169. return;
  170. }
  171. // Closed is activated atb
  172. let toTarget: RouteLocationRaw = {};
  173. const index = this.tabList.findIndex((item) => item.path === path);
  174. // If the current is the leftmost tab
  175. if (index === 0) {
  176. // There is only one tab, then jump to the homepage, otherwise jump to the right tab
  177. if (this.tabList.length === 1) {
  178. const userStore = useUserStore();
  179. toTarget = userStore.getUserInfo.homePath || PageEnum.BASE_HOME;
  180. } else {
  181. // Jump to the right tab
  182. const page = this.tabList[index + 1];
  183. toTarget = getToTarget(page);
  184. }
  185. } else {
  186. // Close the current tab
  187. const page = this.tabList[index - 1];
  188. toTarget = getToTarget(page);
  189. }
  190. close(currentRoute.value);
  191. await replace(toTarget);
  192. },
  193. // Close according to key
  194. async closeTabByKey(key: string, router: Router) {
  195. const index = this.tabList.findIndex((item) => (item.fullPath || item.path) === key);
  196. if (index !== -1) {
  197. await this.closeTab(this.tabList[index], router);
  198. const { currentRoute, replace } = router;
  199. // 检查当前路由是否存在于tabList中
  200. const isActivated = this.tabList.findIndex((item) => {
  201. return item.fullPath === currentRoute.value.fullPath;
  202. });
  203. // 如果当前路由不存在于TabList中,尝试切换到其它路由
  204. if (isActivated === -1) {
  205. let pageIndex;
  206. if (index > 0) {
  207. pageIndex = index - 1;
  208. } else if (index < this.tabList.length - 1) {
  209. pageIndex = index + 1;
  210. } else {
  211. pageIndex = -1;
  212. }
  213. if (pageIndex >= 0) {
  214. const page = this.tabList[index - 1];
  215. const toTarget = getToTarget(page);
  216. await replace(toTarget);
  217. }
  218. }
  219. }
  220. },
  221. // Sort the tabs
  222. async sortTabs(oldIndex: number, newIndex: number) {
  223. const currentTab = this.tabList[oldIndex];
  224. this.tabList.splice(oldIndex, 1);
  225. this.tabList.splice(newIndex, 0, currentTab);
  226. this.lastDragEndIndex = this.lastDragEndIndex + 1;
  227. },
  228. // Close the tab on the right and jump
  229. async closeLeftTabs(route: RouteLocationNormalized, router: Router) {
  230. const index = this.tabList.findIndex((item) => item.path === route.path);
  231. if (index > 0) {
  232. const leftTabs = this.tabList.slice(0, index);
  233. const pathList: string[] = [];
  234. for (const item of leftTabs) {
  235. const affix = item?.meta?.affix ?? false;
  236. if (!affix) {
  237. pathList.push(item.fullPath);
  238. }
  239. }
  240. this.bulkCloseTabs(pathList);
  241. }
  242. this.updateCacheTab();
  243. handleGotoPage(router);
  244. },
  245. // Close the tab on the left and jump
  246. async closeRightTabs(route: RouteLocationNormalized, router: Router) {
  247. const index = this.tabList.findIndex((item) => item.fullPath === route.fullPath);
  248. if (index >= 0 && index < this.tabList.length - 1) {
  249. const rightTabs = this.tabList.slice(index + 1, this.tabList.length);
  250. const pathList: string[] = [];
  251. for (const item of rightTabs) {
  252. const affix = item?.meta?.affix ?? false;
  253. if (!affix) {
  254. pathList.push(item.fullPath);
  255. }
  256. }
  257. this.bulkCloseTabs(pathList);
  258. }
  259. this.updateCacheTab();
  260. handleGotoPage(router);
  261. },
  262. async closeAllTab(router: Router) {
  263. this.tabList = this.tabList.filter((item) => item?.meta?.affix ?? false);
  264. this.clearCacheTabs();
  265. this.goToPage(router);
  266. },
  267. /**
  268. * Close other tabs
  269. */
  270. async closeOtherTabs(route: RouteLocationNormalized, router: Router) {
  271. const closePathList = this.tabList.map((item) => item.fullPath);
  272. const pathList: string[] = [];
  273. for (const path of closePathList) {
  274. if (path !== route.fullPath) {
  275. const closeItem = this.tabList.find((item) => item.path === path);
  276. if (!closeItem) {
  277. continue;
  278. }
  279. const affix = closeItem?.meta?.affix ?? false;
  280. if (!affix) {
  281. pathList.push(closeItem.fullPath);
  282. }
  283. }
  284. }
  285. this.bulkCloseTabs(pathList);
  286. this.updateCacheTab();
  287. handleGotoPage(router);
  288. },
  289. /**
  290. * Close tabs in bulk
  291. */
  292. async bulkCloseTabs(pathList: string[]) {
  293. this.tabList = this.tabList.filter((item) => !pathList.includes(item.fullPath));
  294. },
  295. /**
  296. * Set tab's title
  297. */
  298. async setTabTitle(title: string, route: RouteLocationNormalized) {
  299. const findTab = this.getTabList.find((item) => item === route);
  300. if (findTab) {
  301. findTab.meta.title = title;
  302. await this.updateCacheTab();
  303. }
  304. },
  305. /**
  306. * replace tab's path
  307. * **/
  308. async updateTabPath(fullPath: string, route: RouteLocationNormalized) {
  309. const findTab = this.getTabList.find((item) => item === route);
  310. if (findTab) {
  311. findTab.fullPath = fullPath;
  312. findTab.path = fullPath;
  313. await this.updateCacheTab();
  314. }
  315. },
  316. },
  317. });
  318. // Need to be used outside the setup
  319. export function useMultipleTabWithOutStore() {
  320. return useMultipleTabStore(store);
  321. }