Blame view

src/store/modules/tab.ts 9.39 KB
vben authored
1
import { toRaw } from 'vue';
陈文彬 authored
2
3
4
5
6
7

import { unref } from 'vue';
import { Action, Module, Mutation, VuexModule, getModule } from 'vuex-module-decorators';
import { hotModuleUnregisterModule } from '/@/utils/helper/vuexHelper';

import { PageEnum } from '/@/enums/pageEnum';
8
import { userStore } from './user';
陈文彬 authored
9
10
11
12

import store from '/@/store';
import router from '/@/router';
import { PAGE_NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '/@/router/constant';
vben authored
13
14
15
import { RouteLocationNormalized, RouteLocationRaw } from 'vue-router';
import { getRoute } from '/@/router/helper/routeHelper';
import { useGo, useRedo } from '/@/hooks/web/usePage';
陈文彬 authored
16
17
18
19

// declare namespace TabsStore {

const NAME = 'tab';
20
陈文彬 authored
21
22
hotModuleUnregisterModule(NAME);
vben authored
23
24
25
26
27
28
export const PAGE_LAYOUT_KEY = '__PAGE_LAYOUT__';

function isGotoPage() {
  const go = useGo();
  go(unref(router.currentRoute).path, true);
}
陈文彬 authored
29
30
31

@Module({ namespaced: true, name: NAME, dynamic: true, store })
class Tab extends VuexModule {
vben authored
32
  cachedMapState = new Map<string, string[]>();
陈文彬 authored
33
vben authored
34
35
  // tab list
  tabsState: RouteLocationNormalized[] = [];
陈文彬 authored
36
37
  // Last route change
vben authored
38
39
40
  lastChangeRouteState: RouteLocationNormalized | null = null;

  lastDragEndIndexState = 0;
41
陈文彬 authored
42
43
44
45
  get getTabsState() {
    return this.tabsState;
  }
46
47
48
49
  get getLastChangeRouteState() {
    return this.lastChangeRouteState;
  }
vben authored
50
51
52
  get getCurrentTab(): RouteLocationNormalized {
    const route = unref(router.currentRoute);
    return this.tabsState.find((item) => item.path === route.path)!;
陈文彬 authored
53
54
  }
vben authored
55
56
  get getCachedMapState(): Map<string, string[]> {
    return this.cachedMapState;
陈文彬 authored
57
58
  }
vben authored
59
60
  get getLastDragEndIndexState(): number {
    return this.lastDragEndIndexState;
陈文彬 authored
61
62
63
  }

  @Mutation
vben authored
64
  commitLastChangeRouteState(route: RouteLocationNormalized): void {
65
66
67
68
69
    if (!userStore.getTokenState) return;
    this.lastChangeRouteState = route;
  }

  @Mutation
陈文彬 authored
70
  commitClearCache(): void {
vben authored
71
    this.cachedMapState = new Map();
陈文彬 authored
72
73
74
  }

  @Mutation
vben authored
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
  goToPage() {
    const go = useGo();
    const len = this.tabsState.length;
    const { path } = unref(router.currentRoute);

    let toPath: PageEnum | string = PageEnum.BASE_HOME;

    if (len > 0) {
      const page = this.tabsState[len - 1];
      const p = page.fullPath || page.path;
      if (p) {
        toPath = p;
      }
    }
    // Jump to the current page and report an error
    path !== toPath && go(toPath as PageEnum, true);
陈文彬 authored
91
92
93
  }

  @Mutation
vben authored
94
95
96
97
98
99
  commitCachedMapState(): void {
    const cacheMap = new Map<string, string[]>();

    const pageCacheSet = new Set<string>();
    this.tabsState.forEach((tab) => {
      const item = getRoute(tab);
vben authored
100
      const needCache = !item.meta?.ignoreKeepAlive;
vben authored
101
102
      if (!needCache) return;
vben authored
103
      if (item.meta?.affix) {
vben authored
104
105
        const name = item.name as string;
        pageCacheSet.add(name);
vben authored
106
      } else if (item.matched && needCache) {
vben authored
107
108
109
110
111
112
113
114
115
116
117
118
119
        const matched = item.matched;
        const len = matched.length;

        if (len < 2) return;

        for (let i = 0; i < matched.length; i++) {
          const key = matched[i].name as string;

          if (i < 2) {
            pageCacheSet.add(key);
          }
          if (i < len - 1) {
            const { meta, name } = matched[i + 1];
vben authored
120
            if (meta && (meta.affix || needCache)) {
vben authored
121
122
123
124
125
126
127
128
129
130
131
132
133
              const mapList = cacheMap.get(key) || [];
              if (!mapList.includes(name as string)) {
                mapList.push(name as string);
              }
              cacheMap.set(key, mapList);
            }
          }
        }
      }
    });

    cacheMap.set(PAGE_LAYOUT_KEY, Array.from(pageCacheSet));
    this.cachedMapState = cacheMap;
陈文彬 authored
134
135
136
  }

  @Mutation
vben authored
137
138
  commitTabRoutesState(route: RouteLocationNormalized) {
    const { path, fullPath, params, query } = route;
vben authored
139
140
    let updateIndex = -1;
陈文彬 authored
141
    // 已经存在的页面,不重复添加tab
142
143
144
    const hasTab = this.tabsState.some((tab, index) => {
      updateIndex = index;
      return (tab.fullPath || tab.path) === (fullPath || path);
陈文彬 authored
145
    });
146
147
148
149
150
151
152
153
154
    if (hasTab) {
      const curTab = toRaw(this.tabsState)[updateIndex];
      if (!curTab) return;
      curTab.params = params || curTab.params;
      curTab.query = query || curTab.query;
      curTab.fullPath = fullPath || curTab.fullPath;
      this.tabsState.splice(updateIndex, 1, curTab);
      return;
    }
vben authored
155
    this.tabsState.push(route);
陈文彬 authored
156
157
158
159
160
161
  }

  /**
   * @description: close tab
   */
  @Mutation
vben authored
162
163
164
165
166
  commitCloseTab(route: RouteLocationNormalized): void {
    const { fullPath, meta: { affix } = {} } = route;
    if (affix) return;
    const index = this.tabsState.findIndex((item) => item.fullPath === fullPath);
    index !== -1 && this.tabsState.splice(index, 1);
陈文彬 authored
167
168
169
170
171
172
173
174
175
176
177
178
  }

  @Mutation
  commitCloseAllTab(): void {
    this.tabsState = this.tabsState.filter((item) => {
      return item.meta && item.meta.affix;
    });
  }

  @Mutation
  commitResetState(): void {
    this.tabsState = [];
vben authored
179
    this.cachedMapState = new Map();
陈文彬 authored
180
181
182
  }

  @Mutation
183
184
185
186
187
  commitSortTabs({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }): void {
    const currentTab = this.tabsState[oldIndex];

    this.tabsState.splice(oldIndex, 1);
    this.tabsState.splice(newIndex, 0, currentTab);
vben authored
188
    this.lastDragEndIndexState = this.lastDragEndIndexState + 1;
189
190
191
  }

  @Mutation
vben authored
192
  closeMultipleTab({ pathList }: { pathList: string[] }): void {
vben authored
193
    this.tabsState = toRaw(this.tabsState).filter((item) => !pathList.includes(item.fullPath));
vben authored
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
  }

  @Action
  addTabAction(route: RouteLocationNormalized) {
    const { path, name } = route;
    // 404  页面不需要添加tab
    if (
      path === PageEnum.ERROR_PAGE ||
      !name ||
      [REDIRECT_ROUTE.name, PAGE_NOT_FOUND_ROUTE.name].includes(name as string)
    ) {
      return;
    }
    this.commitTabRoutesState(getRoute(route));

    this.commitCachedMapState();
  }

  @Mutation
  commitRedoPage() {
    const route = router.currentRoute.value;
    for (const [key, value] of this.cachedMapState) {
      const index = value.findIndex((item) => item === (route.name as string));
      if (index === -1) {
        continue;
      }
      if (value.length === 1) {
        this.cachedMapState.delete(key);
        continue;
      }
      value.splice(index, 1);
      this.cachedMapState.set(key, value);
    }
    const redo = useRedo();
    redo();
  }

  @Action
  closeAllTabAction() {
    this.commitCloseAllTab();
    this.commitClearCache();
    this.goToPage();
  }

  @Action
  closeTabAction(tab: RouteLocationNormalized) {
    function getObj(tabItem: RouteLocationNormalized) {
      const { params, path, query } = tabItem;
      return {
        params: params || {},
        path,
        query: query || {},
      };
    }
    const { currentRoute, replace } = router;

    const { path } = unref(currentRoute);
    if (path !== tab.path) {
      // Closed is not the activation tab
      this.commitCloseTab(tab);
      return;
    }

    // Closed is activated atb
    let toObj: RouteLocationRaw = {};

    const index = this.getTabsState.findIndex((item) => item.path === path);

    // If the current is the leftmost tab
    if (index === 0) {
      // There is only one tab, then jump to the homepage, otherwise jump to the right tab
      if (this.getTabsState.length === 1) {
        toObj = PageEnum.BASE_HOME;
      } else {
        //  Jump to the right tab
        const page = this.getTabsState[index + 1];
        toObj = getObj(page);
      }
    } else {
      // Close the current tab
      const page = this.getTabsState[index - 1];
      toObj = getObj(page);
陈文彬 authored
276
    }
vben authored
277
278
    this.commitCloseTab(currentRoute.value);
    replace(toObj);
陈文彬 authored
279
280
281
  }

  @Action
vben authored
282
283
284
285
286
287
288
  closeTabByKeyAction(key: string) {
    const index = this.tabsState.findIndex((item) => (item.fullPath || item.path) === key);
    index !== -1 && this.closeTabAction(this.tabsState[index]);
  }

  @Action
  closeLeftTabAction(route: RouteLocationNormalized): void {
陈文彬 authored
289
290
291
292
293
294
295
296
    const index = this.tabsState.findIndex((item) => item.path === route.path);

    if (index > 0) {
      const leftTabs = this.tabsState.slice(0, index);
      const pathList: string[] = [];
      for (const item of leftTabs) {
        const affix = item.meta ? item.meta.affix : false;
        if (!affix) {
vben authored
297
          pathList.push(item.fullPath);
陈文彬 authored
298
299
        }
      }
vben authored
300
      this.closeMultipleTab({ pathList });
vben authored
301
    }
vben authored
302
303
    this.commitCachedMapState();
    isGotoPage();
304
305
306
  }

  @Action
vben authored
307
  closeRightTabAction(route: RouteLocationNormalized): void {
vben authored
308
    const index = this.tabsState.findIndex((item) => item.fullPath === route.fullPath);
陈文彬 authored
309
310
311
312
313
314
315
316

    if (index >= 0 && index < this.tabsState.length - 1) {
      const rightTabs = this.tabsState.slice(index + 1, this.tabsState.length);

      const pathList: string[] = [];
      for (const item of rightTabs) {
        const affix = item.meta ? item.meta.affix : false;
        if (!affix) {
vben authored
317
          pathList.push(item.fullPath);
陈文彬 authored
318
319
        }
      }
vben authored
320
      this.closeMultipleTab({ pathList });
陈文彬 authored
321
    }
vben authored
322
323
    this.commitCachedMapState();
    isGotoPage();
陈文彬 authored
324
325
326
  }

  @Action
vben authored
327
  closeOtherTabAction(route: RouteLocationNormalized): void {
vben authored
328
    const closePathList = this.tabsState.map((item) => item.fullPath);
陈文彬 authored
329
330
    const pathList: string[] = [];
    closePathList.forEach((path) => {
vben authored
331
      if (path !== route.fullPath) {
陈文彬 authored
332
333
334
335
        const closeItem = this.tabsState.find((item) => item.path === path);
        if (!closeItem) return;
        const affix = closeItem.meta ? closeItem.meta.affix : false;
        if (!affix) {
vben authored
336
          pathList.push(closeItem.fullPath);
陈文彬 authored
337
338
339
        }
      }
    });
vben authored
340
341
342
    this.closeMultipleTab({ pathList });
    this.commitCachedMapState();
    isGotoPage();
陈文彬 authored
343
344
345
  }
}
export const tabStore = getModule<Tab>(Tab);