Przeglądaj źródła

feat: 侧边栏宽度拖拽改为composable实现,同时修复tabbar.ts文件lint报错

zouawen 3 miesięcy temu
rodzic
commit
707b391449

+ 1 - 0
packages/@core/composables/src/index.ts

@@ -2,6 +2,7 @@ export * from './use-is-mobile';
 export * from './use-layout-style';
 export * from './use-namespace';
 export * from './use-priority-value';
+export * from './use-resizable';
 export * from './use-scroll-lock';
 export * from './use-simple-locale';
 export * from './use-sortable';

+ 72 - 0
packages/@core/composables/src/use-resizable.ts

@@ -0,0 +1,72 @@
+import { onUnmounted, ref } from 'vue';
+
+interface ResizableOptions {
+  max?: number;
+  min?: number;
+  onChange?: (newWidth: number) => void;
+}
+
+export function useResizable(options: ResizableOptions = {}) {
+  const { min = 0, max = 999, onChange } = options;
+
+  const isDragging = ref(false);
+
+  let cleanup: (() => void) | null = null;
+
+  let userSelect = '';
+  let cursor = '';
+
+  const startDrag = (e: MouseEvent, width: number) => {
+    e.preventDefault();
+    e.stopPropagation();
+
+    isDragging.value = true;
+    const startX = e.clientX;
+    const startWidth = width;
+
+    userSelect = document.body.style.userSelect;
+    cursor = document.body.style.cursor;
+
+    document.body.style.userSelect = 'none';
+    document.body.style.cursor = 'col-resize';
+
+    const onMouseMove = (moveEvent: MouseEvent) => {
+      if (!isDragging.value) return;
+
+      const deltaX = moveEvent.clientX - startX;
+      let newWidth = startWidth + deltaX;
+
+      newWidth = Math.min(max, Math.max(min, newWidth));
+
+      onChange?.(newWidth);
+    };
+
+    const onMouseUp = () => {
+      if (!isDragging.value) return;
+      cleanup?.();
+    };
+
+    document.addEventListener('mousemove', onMouseMove, { passive: true });
+    document.addEventListener('mouseup', onMouseUp);
+
+    cleanup = () => {
+      document.removeEventListener('mousemove', onMouseMove);
+      document.removeEventListener('mouseup', onMouseUp);
+
+      document.body.style.userSelect = userSelect;
+      document.body.style.cursor = cursor;
+
+      isDragging.value = false;
+      cleanup = null;
+    };
+  };
+
+  onUnmounted(() => {
+    cleanup?.();
+  });
+
+  return {
+    isDragging,
+    startDrag,
+  };
+}

+ 12 - 24
packages/@core/ui-kit/layout-ui/src/components/layout-sidebar.vue

@@ -1,8 +1,9 @@
 <script setup lang="ts">
 import type { CSSProperties } from 'vue';
 
-import { computed, ref, shallowRef, useSlots, watchEffect } from 'vue';
+import { computed, shallowRef, useSlots, watchEffect } from 'vue';
 
+import { useResizable } from '@vben-core/composables';
 import { VbenScrollbar } from '@vben-core/shadcn-ui';
 
 import { useScrollLock } from '@vueuse/core';
@@ -255,31 +256,18 @@ function handleMouseleave() {
   extraVisible.value = false;
 }
 
-const isDragging = ref(false);
-
-function handleDragSidebar(e: MouseEvent) {
-  e.preventDefault();
-
-  isDragging.value = true;
-
-  const startX = e.clientX;
-  const startWidth = props.width;
-
-  function onMouseMove(moveEvent: MouseEvent) {
-    const deltaX = moveEvent.clientX - startX;
-    const newWidth = Math.min(320, Math.max(160, startWidth + deltaX));
+const { isDragging, startDrag } = useResizable({
+  min: 160,
+  max: 320,
+  onChange: (newWidth) => {
     emit('update:width', newWidth);
-  }
-
-  function onMouseUp() {
-    isDragging.value = false;
-    document.removeEventListener('mousemove', onMouseMove);
-    document.removeEventListener('mouseup', onMouseUp);
-  }
+  },
+});
 
-  document.addEventListener('mousemove', onMouseMove);
-  document.addEventListener('mouseup', onMouseUp);
-}
+const handleDragSidebar = (e: MouseEvent) => {
+  const { width } = props;
+  startDrag(e, width);
+};
 </script>
 
 <template>

+ 1 - 5
packages/@core/ui-kit/layout-ui/src/vben-layout.vue

@@ -484,10 +484,6 @@ function handleHeaderToggle() {
 }
 
 const idMainContent = ELEMENT_ID_MAIN_CONTENT;
-
-function handleUpdateSidebarWidth(val: number) {
-  emit('update:sidebar-width', val);
-}
 </script>
 
 <template>
@@ -515,7 +511,7 @@ function handleUpdateSidebarWidth(val: number) {
       :width="getSidebarWidth"
       :z-index="sidebarZIndex"
       @leave="() => emit('sideMouseLeave')"
-      @update:width="handleUpdateSidebarWidth"
+      @update:width="(val) => emit('update:sidebar-width', val)"
     >
       <template v-if="isSideMode && !isMixedNav" #logo>
         <slot name="logo"></slot>

+ 43 - 15
packages/stores/src/modules/tabbar.ts

@@ -1,5 +1,9 @@
 import type { ComputedRef } from 'vue';
-import type { RouteLocationNormalized, Router, RouteRecordNormalized } from 'vue-router';
+import type {
+  RouteLocationNormalized,
+  Router,
+  RouteRecordNormalized,
+} from 'vue-router';
 
 import type { TabDefinition } from '@vben-core/typings';
 
@@ -66,7 +70,9 @@ export const useTabbarStore = defineStore('core-tabbar', {
      */
     async _bulkCloseByKeys(keys: string[]) {
       const keySet = new Set(keys);
-      this.tabs = this.tabs.filter((item) => !keySet.has(getTabKeyFromTab(item)));
+      this.tabs = this.tabs.filter(
+        (item) => !keySet.has(getTabKeyFromTab(item)),
+      );
       if (isVisitHistory()) {
         this.visitHistory.remove(...keys);
       }
@@ -130,20 +136,25 @@ export const useTabbarStore = defineStore('core-tabbar', {
       if (tabIndex === -1) {
         const maxCount = preferences.tabbar.maxCount;
         // 获取动态路由打开数,超过 0 即代表需要控制打开数
-        const maxNumOfOpenTab = (routeTab?.meta?.maxNumOfOpenTab ?? -1) as number;
+        const maxNumOfOpenTab = (routeTab?.meta?.maxNumOfOpenTab ??
+          -1) as number;
         // 如果动态路由层级大于 0 了,那么就要限制该路由的打开数限制了
         // 获取到已经打开的动态路由数, 判断是否大于某一个值
         if (
           maxNumOfOpenTab > 0 &&
-          this.tabs.filter((tab) => tab.name === routeTab.name).length >= maxNumOfOpenTab
+          this.tabs.filter((tab) => tab.name === routeTab.name).length >=
+            maxNumOfOpenTab
         ) {
           // 关闭第一个
-          const index = this.tabs.findIndex((item) => item.name === routeTab.name);
+          const index = this.tabs.findIndex(
+            (item) => item.name === routeTab.name,
+          );
           index !== -1 && this.tabs.splice(index, 1);
         } else if (maxCount > 0 && this.tabs.length >= maxCount) {
           // 关闭第一个
           const index = this.tabs.findIndex(
-            (item) => !Reflect.has(item.meta, 'affixTab') || !item.meta.affixTab
+            (item) =>
+              !Reflect.has(item.meta, 'affixTab') || !item.meta.affixTab,
           );
           index !== -1 && this.tabs.splice(index, 1);
         }
@@ -183,7 +194,9 @@ export const useTabbarStore = defineStore('core-tabbar', {
       this.tabs = newTabs.length > 0 ? newTabs : [...this.tabs].splice(0, 1);
       // 设置访问历史记录
       if (isVisitHistory()) {
-        this.visitHistory.retain(this.tabs.map((item) => getTabKeyFromTab(item)));
+        this.visitHistory.retain(
+          this.tabs.map((item) => getTabKeyFromTab(item)),
+        );
       }
       await this._goToDefaultTab(router);
       this.updateCacheTabs();
@@ -220,7 +233,9 @@ export const useTabbarStore = defineStore('core-tabbar', {
 
       for (const key of closeKeys) {
         if (key !== getTabKeyFromTab(tab)) {
-          const closeTab = this.tabs.find((item) => getTabKeyFromTab(item) === key);
+          const closeTab = this.tabs.find(
+            (item) => getTabKeyFromTab(item) === key,
+          );
           if (!closeTab) {
             continue;
           }
@@ -290,12 +305,14 @@ export const useTabbarStore = defineStore('core-tabbar', {
             break;
           }
         }
-        await (previousTab ? this._goToTab(previousTab, router) : this._goToDefaultTab(router));
+        await (previousTab
+          ? this._goToTab(previousTab, router)
+          : this._goToDefaultTab(router));
         return;
       }
       // 未开启访问历史记录,直接跳转下一个或上一个tab
       const index = this.getTabs.findIndex(
-        (item) => getTabKeyFromTab(item) === getTabKey(currentRoute.value)
+        (item) => getTabKeyFromTab(item) === getTabKey(currentRoute.value),
       );
 
       const before = this.getTabs[index - 1];
@@ -319,7 +336,9 @@ export const useTabbarStore = defineStore('core-tabbar', {
      */
     async closeTabByKey(key: string, router: Router) {
       const originKey = decodeURIComponent(key);
-      const index = this.tabs.findIndex((item) => getTabKeyFromTab(item) === originKey);
+      const index = this.tabs.findIndex(
+        (item) => getTabKeyFromTab(item) === originKey,
+      );
       if (index === -1) {
         return;
       }
@@ -335,7 +354,9 @@ export const useTabbarStore = defineStore('core-tabbar', {
      * @param key
      */
     getTabByKey(key: string) {
-      return this.getTabs.find((item) => getTabKeyFromTab(item) === key) as TabDefinition;
+      return this.getTabs.find(
+        (item) => getTabKeyFromTab(item) === key,
+      ) as TabDefinition;
     },
     /**
      * @zh_CN 新窗口打开标签页
@@ -656,14 +677,21 @@ function isTabShown(tab: TabDefinition) {
  * @param tab
  */
 function getTabKey(tab: RouteLocationNormalized | RouteRecordNormalized) {
-  const { fullPath, path, meta: { fullPathKey } = {}, query = {} } = tab as RouteLocationNormalized;
+  const {
+    fullPath,
+    path,
+    meta: { fullPathKey } = {},
+    query = {},
+  } = tab as RouteLocationNormalized;
   // pageKey可能是数组(查询参数重复时可能出现)
-  const pageKey = Array.isArray(query.pageKey) ? query.pageKey[0] : query.pageKey;
+  const pageKey = Array.isArray(query.pageKey)
+    ? query.pageKey[0]
+    : query.pageKey;
   let rawKey;
   if (pageKey) {
     rawKey = pageKey;
   } else {
-    rawKey = fullPathKey === false ? path : fullPath ?? path;
+    rawKey = fullPathKey === false ? path : (fullPath ?? path);
   }
   try {
     return decodeURIComponent(rawKey);