vben
2020-12-03 c303ec1a23c4b1fbad4fbda9007af2147dc327e2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
import Sortable from 'sortablejs';
import { toRaw, ref, nextTick, onMounted } from 'vue';
import { RouteLocationNormalized } from 'vue-router';
import { useProjectSetting } from '/@/hooks/setting';
import router from '/@/router';
import { tabStore } from '/@/store/modules/tab';
import { isNullAndUnDef } from '/@/utils/is';
 
export function initAffixTabs(): string[] {
  const affixList = ref<RouteLocationNormalized[]>([]);
  /**
   * @description: Filter all fixed routes
   */
  function filterAffixTabs(routes: RouteLocationNormalized[]) {
    const tabs: RouteLocationNormalized[] = [];
    routes &&
      routes.forEach((route) => {
        if (route.meta && route.meta.affix) {
          tabs.push(toRaw(route));
        }
      });
    return tabs;
  }
 
  /**
   * @description: Set fixed tabs
   */
  function addAffixTabs(): void {
    const affixTabs = filterAffixTabs((router.getRoutes() as unknown) as RouteLocationNormalized[]);
    affixList.value = affixTabs;
    for (const tab of affixTabs) {
      tabStore.addTabAction(({
        meta: tab.meta,
        name: tab.name,
        path: tab.path,
      } as unknown) as RouteLocationNormalized);
    }
  }
 
  let isAddAffix = false;
  if (!isAddAffix) {
    addAffixTabs();
    isAddAffix = true;
  }
  return affixList.value.map((item) => item.meta?.title).filter(Boolean);
}
 
export function useTabsDrag(affixTextList: string[]) {
  const { multiTabsSetting } = useProjectSetting();
 
  function initSortableTabs() {
    if (!multiTabsSetting.canDrag) return;
    nextTick(() => {
      const el = document.querySelectorAll(
        '.multiple-tabs .ant-tabs-nav > div'
      )?.[0] as HTMLElement;
 
      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();
  });
}