Blame view

src/layouts/default/tabs/useMultipleTabs.ts 2.35 KB
vben authored
1
2
3
4
import Sortable from 'sortablejs';
import { toRaw, ref, nextTick, onMounted } from 'vue';
import { RouteLocationNormalized } from 'vue-router';
import { useProjectSetting } from '/@/hooks/setting';
vben authored
5
import { useDesign } from '/@/hooks/web/useDesign';
6
import router from '/@/router';
vben authored
7
8
import { tabStore } from '/@/store/modules/tab';
import { isNullAndUnDef } from '/@/utils/is';
9
vben authored
10
11
export function initAffixTabs(): string[] {
  const affixList = ref<RouteLocationNormalized[]>([]);
12
13
14
  /**
   * @description: Filter all fixed routes
   */
vben authored
15
16
  function filterAffixTabs(routes: RouteLocationNormalized[]) {
    const tabs: RouteLocationNormalized[] = [];
17
18
19
    routes &&
      routes.forEach((route) => {
        if (route.meta && route.meta.affix) {
vben authored
20
          tabs.push(toRaw(route));
21
22
23
24
25
26
27
28
29
        }
      });
    return tabs;
  }

  /**
   * @description: Set fixed tabs
   */
  function addAffixTabs(): void {
vben authored
30
    const affixTabs = filterAffixTabs((router.getRoutes() as unknown) as RouteLocationNormalized[]);
31
    affixList.value = affixTabs;
32
    for (const tab of affixTabs) {
vben authored
33
34
35
36
37
      tabStore.addTabAction(({
        meta: tab.meta,
        name: tab.name,
        path: tab.path,
      } as unknown) as RouteLocationNormalized);
38
39
    }
  }
40
41
42
43
44
45
  let isAddAffix = false;
  if (!isAddAffix) {
    addAffixTabs();
    isAddAffix = true;
  }
46
  return affixList.value.map((item) => item.meta?.title).filter(Boolean);
47
}
vben authored
48
49
50
51

export function useTabsDrag(affixTextList: string[]) {
  const { multiTabsSetting } = useProjectSetting();
vben authored
52
53
  const { prefixCls } = useDesign('multiple-tabs');
vben authored
54
55
56
  function initSortableTabs() {
    if (!multiTabsSetting.canDrag) return;
    nextTick(() => {
vben authored
57
      const el = document.querySelectorAll(`.${prefixCls} .ant-tabs-nav > div`)?.[0] as HTMLElement;
vben authored
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

      if (!el) return;
      Sortable.create(el, {
        animation: 500,
        delay: 400,
        delayOnTouchOnly: true,
        filter: (e: ChangeEvent) => {
          const text = e?.target?.innerText;
          if (!text) return false;
          return affixTextList.includes(text);
        },
        onEnd: (evt) => {
          const { oldIndex, newIndex } = evt;

          if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || oldIndex === newIndex) {
            return;
          }

          tabStore.commitSortTabs({ oldIndex, newIndex });
        },
      });
    });
  }

  onMounted(() => {
    initSortableTabs();
  });
}