multipleTab.ts 11 KB

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