Эх сурвалжийг харах

feat: enhance ZmTable column controls

Zimo 2 өдөр өмнө
parent
commit
8b54c24bcf

+ 1 - 0
package.json

@@ -95,6 +95,7 @@
     "video.js": "^7.21.5",
     "vue": "3.5.12",
     "vue-dompurify-html": "^4.1.4",
+    "vue-draggable-plus": "^0.6.1",
     "vue-echarts": "^7.0.3",
     "vue-i18n": "9.10.2",
     "vue-json-viewer": "^3.0.4",

+ 40 - 0
pnpm-lock.yaml

@@ -218,6 +218,9 @@ importers:
       vue-dompurify-html:
         specifier: ^4.1.4
         version: 4.1.4(vue@3.5.12(typescript@5.3.3))
+      vue-draggable-plus:
+        specifier: ^0.6.1
+        version: 0.6.1(@types/sortablejs@1.15.9)
       vue-echarts:
         specifier: ^7.0.3
         version: 7.0.3(@vue/runtime-core@3.5.12)(echarts@5.6.0)(vue@3.5.12(typescript@5.3.3))
@@ -1546,36 +1549,42 @@ packages:
     engines: {node: '>= 10.0.0'}
     cpu: [arm]
     os: [linux]
+    libc: [glibc]
 
   '@parcel/watcher-linux-arm-musl@2.5.0':
     resolution: {integrity: sha512-6uHywSIzz8+vi2lAzFeltnYbdHsDm3iIB57d4g5oaB9vKwjb6N6dRIgZMujw4nm5r6v9/BQH0noq6DzHrqr2pA==}
     engines: {node: '>= 10.0.0'}
     cpu: [arm]
     os: [linux]
+    libc: [musl]
 
   '@parcel/watcher-linux-arm64-glibc@2.5.0':
     resolution: {integrity: sha512-BfNjXwZKxBy4WibDb/LDCriWSKLz+jJRL3cM/DllnHH5QUyoiUNEp3GmL80ZqxeumoADfCCP19+qiYiC8gUBjA==}
     engines: {node: '>= 10.0.0'}
     cpu: [arm64]
     os: [linux]
+    libc: [glibc]
 
   '@parcel/watcher-linux-arm64-musl@2.5.0':
     resolution: {integrity: sha512-S1qARKOphxfiBEkwLUbHjCY9BWPdWnW9j7f7Hb2jPplu8UZ3nes7zpPOW9bkLbHRvWM0WDTsjdOTUgW0xLBN1Q==}
     engines: {node: '>= 10.0.0'}
     cpu: [arm64]
     os: [linux]
+    libc: [musl]
 
   '@parcel/watcher-linux-x64-glibc@2.5.0':
     resolution: {integrity: sha512-d9AOkusyXARkFD66S6zlGXyzx5RvY+chTP9Jp0ypSTC9d4lzyRs9ovGf/80VCxjKddcUvnsGwCHWuF2EoPgWjw==}
     engines: {node: '>= 10.0.0'}
     cpu: [x64]
     os: [linux]
+    libc: [glibc]
 
   '@parcel/watcher-linux-x64-musl@2.5.0':
     resolution: {integrity: sha512-iqOC+GoTDoFyk/VYSFHwjHhYrk8bljW6zOhPuhi5t9ulqiYq1togGJB5e3PwYVFFfeVgc6pbz3JdQyDoBszVaA==}
     engines: {node: '>= 10.0.0'}
     cpu: [x64]
     os: [linux]
+    libc: [musl]
 
   '@parcel/watcher-win32-arm64@2.5.0':
     resolution: {integrity: sha512-twtft1d+JRNkM5YbmexfcH/N4znDtjgysFaV9zvZmmJezQsKpkfLYJ+JFV3uygugK6AtIM2oADPkB2AdhBrNig==}
@@ -1684,46 +1693,55 @@ packages:
     resolution: {integrity: sha512-9OwUnK/xKw6DyRlgx8UizeqRFOfi9mf5TYCw1uolDaJSbUmBxP85DE6T4ouCMoN6pXw8ZoTeZCSEfSaYo+/s1w==}
     cpu: [arm]
     os: [linux]
+    libc: [glibc]
 
   '@rollup/rollup-linux-arm-musleabihf@4.27.4':
     resolution: {integrity: sha512-Vgdo4fpuphS9V24WOV+KwkCVJ72u7idTgQaBoLRD0UxBAWTF9GWurJO9YD9yh00BzbkhpeXtm6na+MvJU7Z73A==}
     cpu: [arm]
     os: [linux]
+    libc: [musl]
 
   '@rollup/rollup-linux-arm64-gnu@4.27.4':
     resolution: {integrity: sha512-pleyNgyd1kkBkw2kOqlBx+0atfIIkkExOTiifoODo6qKDSpnc6WzUY5RhHdmTdIJXBdSnh6JknnYTtmQyobrVg==}
     cpu: [arm64]
     os: [linux]
+    libc: [glibc]
 
   '@rollup/rollup-linux-arm64-musl@4.27.4':
     resolution: {integrity: sha512-caluiUXvUuVyCHr5DxL8ohaaFFzPGmgmMvwmqAITMpV/Q+tPoaHZ/PWa3t8B2WyoRcIIuu1hkaW5KkeTDNSnMA==}
     cpu: [arm64]
     os: [linux]
+    libc: [musl]
 
   '@rollup/rollup-linux-powerpc64le-gnu@4.27.4':
     resolution: {integrity: sha512-FScrpHrO60hARyHh7s1zHE97u0KlT/RECzCKAdmI+LEoC1eDh/RDji9JgFqyO+wPDb86Oa/sXkily1+oi4FzJQ==}
     cpu: [ppc64]
     os: [linux]
+    libc: [glibc]
 
   '@rollup/rollup-linux-riscv64-gnu@4.27.4':
     resolution: {integrity: sha512-qyyprhyGb7+RBfMPeww9FlHwKkCXdKHeGgSqmIXw9VSUtvyFZ6WZRtnxgbuz76FK7LyoN8t/eINRbPUcvXB5fw==}
     cpu: [riscv64]
     os: [linux]
+    libc: [glibc]
 
   '@rollup/rollup-linux-s390x-gnu@4.27.4':
     resolution: {integrity: sha512-PFz+y2kb6tbh7m3A7nA9++eInGcDVZUACulf/KzDtovvdTizHpZaJty7Gp0lFwSQcrnebHOqxF1MaKZd7psVRg==}
     cpu: [s390x]
     os: [linux]
+    libc: [glibc]
 
   '@rollup/rollup-linux-x64-gnu@4.27.4':
     resolution: {integrity: sha512-Ni8mMtfo+o/G7DVtweXXV/Ol2TFf63KYjTtoZ5f078AUgJTmaIJnj4JFU7TK/9SVWTaSJGxPi5zMDgK4w+Ez7Q==}
     cpu: [x64]
     os: [linux]
+    libc: [glibc]
 
   '@rollup/rollup-linux-x64-musl@4.27.4':
     resolution: {integrity: sha512-5AeeAF1PB9TUzD+3cROzFTnAJAcVUGLuR8ng0E0WXGkYhp6RD6L+6szYVX+64Rs0r72019KHZS1ka1q+zU/wUw==}
     cpu: [x64]
     os: [linux]
+    libc: [musl]
 
   '@rollup/rollup-win32-arm64-msvc@4.27.4':
     resolution: {integrity: sha512-yOpVsA4K5qVwu2CaS3hHxluWIK5HQTjNV4tWjQXluMiiiu4pJj4BN98CvxohNCpcjMeTXk/ZMJBRbgRg8HBB6A==}
@@ -1769,24 +1787,28 @@ packages:
     engines: {node: '>=10'}
     cpu: [arm64]
     os: [linux]
+    libc: [glibc]
 
   '@swc/core-linux-arm64-musl@1.9.3':
     resolution: {integrity: sha512-tzVH480RY6RbMl/QRgh5HK3zn1ZTFsThuxDGo6Iuk1MdwIbdFYUY034heWUTI4u3Db97ArKh0hNL0xhO3+PZdg==}
     engines: {node: '>=10'}
     cpu: [arm64]
     os: [linux]
+    libc: [musl]
 
   '@swc/core-linux-x64-gnu@1.9.3':
     resolution: {integrity: sha512-ivXXBRDXDc9k4cdv10R21ccBmGebVOwKXT/UdH1PhxUn9m/h8erAWjz5pcELwjiMf27WokqPgaWVfaclDbgE+w==}
     engines: {node: '>=10'}
     cpu: [x64]
     os: [linux]
+    libc: [glibc]
 
   '@swc/core-linux-x64-musl@1.9.3':
     resolution: {integrity: sha512-ILsGMgfnOz1HwdDz+ZgEuomIwkP1PHT6maigZxaCIuC6OPEhKE8uYna22uU63XvYcLQvZYDzpR3ms47WQPuNEg==}
     engines: {node: '>=10'}
     cpu: [x64]
     os: [linux]
+    libc: [musl]
 
   '@swc/core-win32-arm64-msvc@1.9.3':
     resolution: {integrity: sha512-e+XmltDVIHieUnNJHtspn6B+PCcFOMYXNJB1GqoCcyinkEIQNwC8KtWgMqUucUbEWJkPc35NHy9k8aCXRmw9Kg==}
@@ -1980,6 +2002,9 @@ packages:
   '@types/semver@7.5.8':
     resolution: {integrity: sha512-I8EUhyrgfLrcTkzV3TSsGyl1tSuPrEDzr0yd5m90UgNxQkyDXULk3b6MlQqTCpZpNtWe1K0hzclnZkTcLBe2UQ==}
 
+  '@types/sortablejs@1.15.9':
+    resolution: {integrity: sha512-7HP+rZGE2p886PKV9c9OJzLBI6BBJu1O7lJGYnPyG3fS4/duUCcngkNCjsLwIMV+WMqANe3tt4irrXHSIe68OQ==}
+
   '@types/trusted-types@2.0.7':
     resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
 
@@ -5399,6 +5424,15 @@ packages:
     peerDependencies:
       vue: ^2.7.0 || ^3.0.0
 
+  vue-draggable-plus@0.6.1:
+    resolution: {integrity: sha512-FbtQ/fuoixiOfTZzG3yoPl4JAo9HJXRHmBQZFB9x2NYCh6pq0TomHf7g5MUmpaDYv+LU2n6BPq2YN9sBO+FbIg==}
+    peerDependencies:
+      '@types/sortablejs': ^1.15.0
+      '@vue/composition-api': '*'
+    peerDependenciesMeta:
+      '@vue/composition-api':
+        optional: true
+
   vue-echarts@7.0.3:
     resolution: {integrity: sha512-/jSxNwOsw5+dYAUcwSfkLwKPuzTQ0Cepz1LxCOpj2QcHrrmUa/Ql0eQqMmc1rTPQVrh2JQ29n2dhq75ZcHvRDw==}
     peerDependencies:
@@ -7389,6 +7423,8 @@ snapshots:
 
   '@types/semver@7.5.8': {}
 
+  '@types/sortablejs@1.15.9': {}
+
   '@types/trusted-types@2.0.7':
     optional: true
 
@@ -11180,6 +11216,10 @@ snapshots:
     transitivePeerDependencies:
       - '@vue/composition-api'
 
+  vue-draggable-plus@0.6.1(@types/sortablejs@1.15.9):
+    dependencies:
+      '@types/sortablejs': 1.15.9
+
   vue-echarts@7.0.3(@vue/runtime-core@3.5.12)(echarts@5.6.0)(vue@3.5.12(typescript@5.3.3)):
     dependencies:
       echarts: 5.6.0

+ 283 - 135
src/components/ZmTable/ZmTableColumn.vue

@@ -1,55 +1,91 @@
 <script lang="ts" setup generic="T">
 import { type TableColumnCtx } from 'element-plus'
-import { computed, useAttrs, inject, ref } from 'vue'
-import { Filter } from '@element-plus/icons-vue'
-import { SortOrder, TableContextKey } from './token'
-import { DefaultRow } from 'element-plus/es/components/table/src/table/defaults'
+import { computed, inject, nextTick, ref, useAttrs, watch } from 'vue'
+import { TableContextKey } from './token'
+import ZmTableColumnSettingTree from './ZmTableColumnSettingTree.vue'
+import type { ColumnSettingItem, SortChangePayload, SortOrder } from './token'
+import type { DefaultRow } from 'element-plus/es/components/table/src/table/defaults'
 
 interface Props
   extends /* @vue-ignore */ Partial<
     Omit<TableColumnCtx<T extends DefaultRow ? T : DefaultRow>, 'prop'>
   > {
   prop?: (keyof T & string) | (string & {})
+  action?: boolean
+  hideInColumnSettings?: boolean
+  isParent?: boolean
   zmSortable?: boolean
   zmFilterable?: boolean
+  sortOrder?: SortOrder | null
+  defaultSortOrder?: SortOrder | null
+  zmSortMethod?: (prop: string, order: SortOrder | null) => void
+  filterActive?: boolean
   filterModelValue?: any
   realValue?: (...args: any[]) => any
   coverFormatter?: boolean
 }
 
-const emits = defineEmits(['update:filterModelValue'])
+const emits = defineEmits<{
+  'update:filterModelValue': [value: any]
+  'update:sortOrder': [order: SortOrder | null]
+  'sort-change': [payload: SortChangePayload]
+  'filter-click': [payload: { prop?: string }]
+  'filter-visible-change': [visible: boolean]
+}>()
+
 const props = defineProps<Props>()
 const attrs = useAttrs()
 
 const tableContext = inject(TableContextKey, {
   data: ref([]),
-  sortingFields: ref([]),
-  onQuery: () => {},
-  onSort: () => {},
-  loading: ref(false)
+  loading: ref(false),
+  columnMaxWidth: ref(360),
+  columnSettings: ref([]),
+  updateColumnVisible: () => {},
+  updateColumnFixed: () => {},
+  updateColumnOrder: () => {},
+  resetColumnSettings: () => {}
 })
 
+const innerSortOrder = ref<SortOrder | null>(props.defaultSortOrder ?? null)
+const filterVisible = ref(false)
+const settingVisible = ref(false)
+
 const defaultOptions = ref<Partial<Props>>({
   align: 'center',
   resizable: true,
-  showOverflowTooltip: true,
-  coverFormatter: false
+  showOverflowTooltip: true
 })
 
 const bindProps = computed(() => {
+  const {
+    action,
+    hideInColumnSettings,
+    zmSortable,
+    zmFilterable,
+    sortOrder,
+    defaultSortOrder,
+    zmSortMethod,
+    filterActive,
+    filterModelValue,
+    realValue,
+    coverFormatter,
+    isParent,
+    ...columnProps
+  } = props
   const resolvedAlign =
-    props.zmSortable || props.zmFilterable
+    action || zmSortable || zmFilterable
       ? 'left'
       : attrs.align || props.align || defaultOptions.value.align
 
   return {
     ...defaultOptions.value,
     ...attrs,
-    ...props,
+    ...columnProps,
     prop: props.prop,
     align: resolvedAlign,
-    className: (props.className ?? '') + ' ' + props.prop,
-    formatter: props.coverFormatter ? props.realValue : props.formatter
+    className: [props.className, props.prop].filter(Boolean).join(' '),
+    formatter: coverFormatter ? realValue : props.formatter
   }
 })
 
@@ -58,18 +94,27 @@ const alignMap: Record<string, string> = {
   left: 'justify-between',
   right: 'justify-end'
 }
-const headerFlexClass = computed(
-  () => alignMap[bindProps.value.align as string] || 'justify-center'
-)
+const headerFlexClass = computed(() => alignMap[String(bindProps.value.align)] || 'justify-center')
 
-const currentSortField = computed(() => {
-  if (!props.prop) return undefined
-  return tableContext.sortingFields.value.find((f: any) => f.field === props.prop)
+const isSortControlled = computed(() => props.sortOrder !== undefined)
+const currentOrder = computed<SortOrder | null>(() => {
+  return isSortControlled.value ? (props.sortOrder ?? null) : innerSortOrder.value
 })
+const isSortActive = computed(() => currentOrder.value !== null)
 
-const isSortActive = computed(() => !!currentSortField.value)
+const hasFilterValue = (value: any) => {
+  if (Array.isArray(value)) return value.length > 0
+  if (typeof value === 'string') return value.length > 0
+  return value !== undefined && value !== null && value !== ''
+}
+const isFilterActive = computed(() => props.filterActive ?? hasFilterValue(props.filterModelValue))
 
-const currentOrder = computed<SortOrder | undefined>(() => currentSortField.value?.order)
+const columnSettingsModel = computed<ColumnSettingItem[]>({
+  get: () => tableContext.columnSettings.value,
+  set: (items) => {
+    tableContext.updateColumnOrder(items.map((item) => item.key))
+  }
+})
 
 const handleSortClick = () => {
   if (!props.prop) return
@@ -82,55 +127,102 @@ const handleSortClick = () => {
     nextOrder = null
   }
 
-  tableContext.onSort(props.prop, nextOrder)
+  if (!isSortControlled.value) {
+    innerSortOrder.value = nextOrder
+  }
+
+  emits('update:sortOrder', nextOrder)
+  emits('sort-change', { prop: props.prop, order: nextOrder })
+  props.zmSortMethod?.(props.prop, nextOrder)
 }
 
-const handleSearchClick = () => {
-  if (tableContext.onQuery && props.prop) {
-    tableContext.onQuery({
-      prop: props.prop,
-      value: props.filterModelValue
-    })
+const updateFilterModelValue = (value: any) => {
+  emits('update:filterModelValue', value)
+}
+
+const closeFilterPopover = () => {
+  filterVisible.value = false
+}
+
+const setFilterVisible = (visible: boolean) => {
+  filterVisible.value = visible
+}
+
+const getFilterSlotProps = (scope: any) => ({
+  ...scope,
+  prop: props.prop,
+  filterModelValue: props.filterModelValue,
+  close: closeFilterPopover,
+  setVisible: setFilterVisible,
+  updateFilterModelValue
+})
+
+const handleFilterReferenceClick = () => {
+  emits('filter-click', { prop: props.prop })
+}
+
+watch(
+  () => props.defaultSortOrder,
+  (order) => {
+    if (!isSortControlled.value) {
+      innerSortOrder.value = order ?? null
+    }
   }
+)
+
+watch(filterVisible, (visible) => {
+  emits('filter-visible-change', visible)
+})
+
+const getTableComputedStyle = () => {
+  const tableElement = document.querySelector('.zm-table') as HTMLElement | null
+  return getComputedStyle(tableElement ?? document.documentElement)
+}
+
+const getTableStyleVariable = (name: string, fallback: string) => {
+  const style = getTableComputedStyle()
+  return style.getPropertyValue(name).trim() || fallback
 }
 
-const getTextWidth = (text: string, fontSize = 12) => {
+const getTextWidth = (text: string) => {
+  const tableStyle = getTableComputedStyle()
   const span = document.createElement('span')
   span.style.visibility = 'hidden'
   span.style.position = 'absolute'
   span.style.whiteSpace = 'nowrap'
-  span.style.fontSize = `${fontSize}px`
-  span.style.fontFamily = 'PingFang SC'
+  span.style.fontSize = getTableStyleVariable(
+    '--zm-table-column-width-measure-font-size',
+    getTableStyleVariable('--zm-table-font-size', tableStyle.fontSize || '12px')
+  )
+  span.style.fontFamily = getTableStyleVariable(
+    '--zm-table-column-width-measure-font-family',
+    tableStyle.fontFamily || 'Noto Sans SC'
+  )
   span.innerText = text
-
   document.body.appendChild(span)
   const width = span.offsetWidth
   document.body.removeChild(span)
-
   return width
 }
 
 const calculativeWidth = () => {
+  if (!props.prop) return
   const values = tableContext.data.value
-    .map((item) => props.realValue?.(item) || item[props.prop])
-    .filter(Boolean)
-
+    .map((item) => props.realValue?.(item) ?? item[props.prop as keyof typeof item])
+    .filter(hasFilterValue)
   let labelWidth = getTextWidth(bindProps.value.label || '') + 32
-
   if (props.zmFilterable || props.zmSortable) labelWidth += 8
   if (props.zmFilterable) labelWidth += 22
   if (props.zmSortable) labelWidth += 22
-
   const maxWidth = Math.min(
-    Math.max(...values.map((value) => getTextWidth(value) + 38), labelWidth),
-    360
+    Math.max(...values.map((value) => getTextWidth(String(value)) + 38), labelWidth),
+    tableContext.columnMaxWidth.value
   )
-
   defaultOptions.value.minWidth = maxWidth
 }
 
 watch(
-  () => tableContext.loading.value,
+  [() => tableContext.loading.value, () => tableContext.columnMaxWidth.value],
   () => {
     nextTick(() => {
       calculativeWidth()
@@ -145,14 +237,13 @@ watch(
     <template v-for="(_, name) in $slots" :key="name" #[name]="slotData">
       <slot v-if="name !== 'header'" :name="name" v-bind="slotData || {}"></slot>
     </template>
-
     <template #header="scope">
       <slot name="header" v-bind="scope">
         <div class="header-wrapper" :class="headerFlexClass">
           <span class="truncate" :title="scope.column.label">{{ scope.column.label }}</span>
-          <div v-if="bindProps.zmSortable || bindProps.zmFilterable" class="action-area">
+          <div v-if="props.action || props.zmSortable || props.zmFilterable" class="action-area">
             <el-tooltip
-              v-if="bindProps.zmSortable"
+              v-if="props.zmSortable"
               :content="
                 currentOrder === 'asc'
                   ? '点击降序'
@@ -163,53 +254,74 @@ watch(
               placement="top"
               :show-after="500"
             >
-              <div
+              <button
+                type="button"
                 class="icon-btn"
                 :class="{ 'is-active': isSortActive }"
                 @click.stop="handleSortClick"
               >
-                <i
-                  class="zm-sort-icon"
-                  :class="{
-                    'is-desc': currentOrder === 'desc'
-                  }"
-                ></i>
-              </div>
+                <div v-if="currentOrder === 'asc'" class="sort-icon i-lucide:arrow-up-narrow-wide">
+                </div>
+                <div
+                  v-else-if="currentOrder === 'desc'"
+                  class="sort-icon i-lucide:arrow-down-wide-narrow"
+                >
+                </div>
+                <div v-else class="sort-icon i-lucide:arrow-up-down"></div>
+              </button>
             </el-tooltip>
 
             <el-popover
-              v-if="bindProps.zmFilterable"
-              placement="top-end"
+              v-if="props.zmFilterable"
+              v-model:visible="filterVisible"
+              placement="top"
               :popper-options="{ modifiers: [{ name: 'offset', options: { offset: [16, 18] } }] }"
               trigger="click"
               :width="260"
               :show-arrow="false"
             >
               <template #reference>
-                <div
+                <button
+                  type="button"
                   class="icon-btn"
-                  :class="{ 'is-active': bindProps.filterModelValue }"
-                  @click.stop
+                  :class="{ 'is-active': isFilterActive }"
+                  @click.stop="handleFilterReferenceClick"
                 >
-                  <el-icon :size="16"><Filter /></el-icon>
-                </div>
+                  <div class="filter-icon i-lucide:list-filter"></div>
+                </button>
+              </template>
+              <slot name="filter" v-bind="getFilterSlotProps(scope)"></slot>
+            </el-popover>
+
+            <el-popover
+              v-if="props.action"
+              v-model:visible="settingVisible"
+              placement="bottom-end"
+              trigger="click"
+              :width="360"
+              :show-arrow="false"
+              popper-class="zm-table-column-setting-popper"
+            >
+              <template #reference>
+                <button type="button" class="icon-btn" title="列设置" @click.stop>
+                  <div class="setting-icon i-lucide:settings"></div>
+                </button>
               </template>
 
-              <slot name="filter" v-bind="scope">
-                <div class="filter-panel">
-                  <el-input
-                    :model-value="bindProps.filterModelValue"
-                    @input="(val) => emits('update:filterModelValue', val)"
-                    placeholder="输入关键词"
+              <div class="column-setting-panel">
+                <ZmTableColumnSettingTree v-model="columnSettingsModel" />
+
+                <div class="column-setting-footer">
+                  <el-button
+                    link
+                    type="primary"
                     size="small"
-                    clearable
-                    @keydown.enter="handleSearchClick"
-                  />
-                  <el-button type="primary" size="small" @click="handleSearchClick">
-                    搜索
+                    @click="tableContext.resetColumnSettings"
+                  >
+                    重置
                   </el-button>
                 </div>
-              </slot>
+              </div>
             </el-popover>
           </div>
         </div>
@@ -219,98 +331,134 @@ watch(
 </template>
 
 <style scoped lang="scss">
+// 表头整体容器:左侧是标题,右侧是按钮区。
 .header-wrapper {
   display: flex;
   align-items: center;
-  width: 100%;
-  height: 100%;
-  min-width: 0;
-  gap: 6px;
-  font-size: 12px;
-  font-weight: 600;
-  line-height: 16px;
-  color: #6b7f99;
+  width: var(--zm-table-header-wrapper-width, 100%);
+  height: var(--zm-table-header-wrapper-height, 100%);
+  min-width: var(--zm-table-header-wrapper-min-width, 0);
+  gap: var(--zm-table-header-wrapper-gap, 6px);
+  font-size: var(--zm-table-header-wrapper-font-size, var(--zm-table-header-font-size, 12px));
+  font-weight: var(--zm-table-header-wrapper-font-weight, var(--zm-table-header-font-weight, 600));
+  line-height: var(--zm-table-header-wrapper-line-height, 16px);
+  color: var(--zm-table-header-wrapper-text-color, var(--zm-table-header-text-color, #6b7f99));
   user-select: none;
 
   .truncate {
-    min-width: 0;
+    min-width: var(--zm-table-header-title-min-width, 0);
   }
 }
 
+// 表头右侧按钮区。
 .action-area {
   display: flex;
   flex: 0 0 auto;
-  height: 100%;
-  margin-left: 4px;
+  height: var(--zm-table-header-action-area-height, 100%);
+  margin-left: var(--zm-table-header-action-area-margin-left, 4px);
   align-items: center;
-  gap: 3px;
+  gap: var(--zm-table-header-action-area-gap, 3px);
 }
 
+// 表头小图标按钮的通用样式。
 .icon-btn {
   display: flex;
-  width: 18px;
-  height: 18px;
-  color: #8aa0b8;
+  width: var(--zm-table-header-icon-btn-size, 18px);
+  height: var(--zm-table-header-icon-btn-size, 18px);
+  padding: var(--zm-table-header-icon-btn-padding, 0);
+  color: var(--zm-table-header-icon-btn-color, #8aa0b8);
   cursor: pointer;
-  border-radius: 4px;
+  background: var(--zm-table-header-icon-btn-bg, transparent);
+  border: var(--zm-table-header-icon-btn-border, 0);
+  border-radius: var(--zm-table-header-icon-btn-radius, 4px);
+  transition:
+    color var(--zm-table-header-icon-btn-transition-duration, 0.16s)
+      var(--zm-table-header-icon-btn-transition-timing, ease),
+    background-color var(--zm-table-header-icon-btn-transition-duration, 0.16s)
+      var(--zm-table-header-icon-btn-transition-timing, ease);
   align-items: center;
   justify-content: center;
-  transition:
-    color 0.16s ease,
-    background-color 0.16s ease;
 
   &:hover {
-    color: var(--el-color-primary);
-    background-color: var(--el-color-primary-light-9);
+    color: var(--zm-table-header-icon-btn-hover-color, var(--el-color-primary));
+    background-color: var(--zm-table-header-icon-btn-hover-bg, var(--el-color-primary-light-9));
   }
 
   &.is-active {
-    color: var(--el-color-primary);
-    background-color: var(--el-color-primary-light-9);
+    color: var(--zm-table-header-icon-btn-active-color, var(--el-color-primary));
+    background-color: var(--zm-table-header-icon-btn-active-bg, var(--el-color-primary-light-9));
   }
 }
 
-.zm-sort-icon {
-  position: relative;
-  display: flex;
-  width: 10px;
-  height: 12px;
-  align-items: center;
-  justify-content: center;
-
-  &::before,
-  &::after {
-    position: absolute;
-    width: 7px;
-    height: 2px;
-    background-color: currentcolor;
-    border-radius: 2px;
-    content: '';
-    transition: transform 0.25s cubic-bezier(0.4, 0, 0.2, 1);
-  }
-
-  &::before {
-    transform: translateX(-2.2px) rotate(45deg);
-  }
-
-  &::after {
-    transform: translateX(2.2px) rotate(-45deg);
-  }
-
-  &.is-desc {
-    &::before {
-      transform: translateX(-2.2px) rotate(-45deg);
-    }
+// 排序、筛选、设置这几个图标统一大小。
+.sort-icon,
+.filter-icon,
+.setting-icon {
+  width: var(--zm-table-header-icon-size, 16px);
+  height: var(--zm-table-header-icon-size, 16px);
+}
 
-    &::after {
-      transform: translateX(2.2px) rotate(45deg);
-    }
-  }
+// 列设置面板容器。
+.column-setting-panel {
+  min-width: var(--zm-table-column-setting-panel-min-width, 0);
 }
 
-.filter-panel {
+// 面板底部区域,放重置按钮。
+.column-setting-footer {
   display: flex;
-  padding: 4px;
-  gap: 8px;
+  justify-content: flex-end;
+  padding-top: var(--zm-table-column-setting-footer-padding-top, 8px);
+  margin-top: var(--zm-table-column-setting-footer-margin-top, 8px);
+  border-top: var(--zm-table-column-setting-footer-border-width, 1px)
+    var(--zm-table-column-setting-footer-border-style, solid)
+    var(--zm-table-column-setting-footer-border-color, var(--el-border-color-lighter));
+}
+
+:global(.zm-table-column-setting-popper) {
+  --zm-table-column-setting-panel-min-width: 0;
+  --zm-table-column-setting-footer-padding-top: 8px;
+  --zm-table-column-setting-footer-margin-top: 8px;
+  --zm-table-column-setting-footer-border-width: 1px;
+  --zm-table-column-setting-footer-border-style: solid;
+  --zm-table-column-setting-footer-border-color: var(--el-border-color-lighter);
+  --zm-table-column-setting-list-min-width: 0;
+  --zm-table-column-setting-list-gap: 4px;
+  --zm-table-column-setting-list-max-height: 360px;
+  --zm-table-column-setting-child-list-padding-left: 18px;
+  --zm-table-column-setting-child-list-margin: 3px 0 6px;
+  --zm-table-column-setting-child-list-border-width: 1px;
+  --zm-table-column-setting-child-list-border-style: dashed;
+  --zm-table-column-setting-child-list-border-color: var(--el-border-color);
+  --zm-table-column-setting-child-list-gap: 3px;
+  --zm-table-column-setting-group-min-width: 0;
+  --zm-table-column-setting-item-height: 32px;
+  --zm-table-column-setting-item-min-width: 0;
+  --zm-table-column-setting-item-padding: 0 4px;
+  --zm-table-column-setting-item-font-size: 12px;
+  --zm-table-column-setting-item-font-weight: 400;
+  --zm-table-column-setting-item-text-color: var(--el-text-color-regular);
+  --zm-table-column-setting-item-radius: 6px;
+  --zm-table-column-setting-item-column-gap: 6px;
+  --zm-table-column-setting-item-grid-template-columns: 22px minmax(0, 1fr) repeat(3, 24px);
+  --zm-table-column-setting-item-hover-bg: var(--el-fill-color-lighter);
+  --zm-table-column-setting-group-font-weight: 600;
+  --zm-table-column-setting-child-item-height: 30px;
+  --zm-table-column-setting-child-item-padding-left: 2px;
+  --zm-table-column-setting-label-font-size: inherit;
+  --zm-table-column-setting-label-font-weight: inherit;
+  --zm-table-column-setting-label-text-color: currentcolor;
+  --zm-table-column-setting-icon-btn-size: 22px;
+  --zm-table-column-setting-icon-btn-padding: 0;
+  --zm-table-column-setting-icon-btn-color: #8aa0b8;
+  --zm-table-column-setting-icon-btn-bg: transparent;
+  --zm-table-column-setting-icon-btn-border: 0;
+  --zm-table-column-setting-icon-btn-radius: 4px;
+  --zm-table-column-setting-icon-btn-active-color: var(--el-color-primary);
+  --zm-table-column-setting-icon-btn-active-bg: var(--el-color-primary-light-9);
+  --zm-table-column-setting-icon-size: 15px;
+  --zm-table-column-setting-drag-cursor: grab;
+  --zm-table-column-setting-drag-active-cursor: grabbing;
+  --zm-table-column-setting-ghost-bg: var(--el-color-primary-light-9);
+  --zm-table-column-setting-ghost-opacity: 0.55;
 }
 </style>

+ 261 - 0
src/components/ZmTable/ZmTableColumnSettingTree.vue

@@ -0,0 +1,261 @@
+<script lang="ts" setup>
+import { computed, inject, ref } from 'vue'
+import { VueDraggable } from 'vue-draggable-plus'
+import { TableContextKey } from './token'
+import type { ColumnFixed, ColumnSettingItem } from './token'
+
+defineOptions({
+  name: 'ZmTableColumnSettingTree'
+})
+
+interface Props {
+  modelValue: ColumnSettingItem[]
+  parentKey?: string
+  level?: number
+}
+
+const props = withDefaults(defineProps<Props>(), {
+  level: 0
+})
+
+const emits = defineEmits<{
+  'update:modelValue': [value: ColumnSettingItem[]]
+}>()
+
+const tableContext = inject(TableContextKey, {
+  data: ref([]),
+  loading: ref(false),
+  columnMaxWidth: ref(360),
+  columnSettings: ref([]),
+  updateColumnVisible: () => {},
+  updateColumnFixed: () => {},
+  updateColumnOrder: () => {},
+  resetColumnSettings: () => {}
+})
+
+const columnList = computed<ColumnSettingItem[]>({
+  get: () => props.modelValue,
+  set: (value) => {
+    emits('update:modelValue', value)
+  }
+})
+
+const dragHandleClass = computed(() => `column-setting-drag-handle-${props.level}`)
+const dragHandleSelector = computed(() => `.${dragHandleClass.value}`)
+const dragGroup = computed(() => ({
+  name: `zm-table-column-setting-${props.parentKey || 'root'}`,
+  pull: false,
+  put: false
+}))
+
+const hasChildColumns = (item: ColumnSettingItem) => !!item.children?.length
+
+const getVisibleTooltip = (item: ColumnSettingItem) => (item.visible ? '隐藏列' : '显示列')
+
+const getFixedTooltip = (item: ColumnSettingItem, fixed: Exclude<ColumnFixed, false>) => {
+  if (item.fixed === fixed) return fixed === 'left' ? '取消固定左侧' : '取消固定右侧'
+  return fixed === 'left' ? '固定到左侧' : '固定到右侧'
+}
+
+const handleChildColumnOrder = (parentKey: string, children: ColumnSettingItem[]) => {
+  tableContext.updateColumnOrder(
+    children.map((item) => item.key),
+    parentKey
+  )
+}
+
+const toggleColumnFixed = (item: ColumnSettingItem, fixed: Exclude<ColumnFixed, false>) => {
+  tableContext.updateColumnFixed(item.key, item.fixed === fixed ? false : fixed)
+}
+</script>
+
+<template>
+  <VueDraggable
+    v-model="columnList"
+    :animation="150"
+    :handle="dragHandleSelector"
+    :group="dragGroup"
+    ghost-class="column-setting-ghost"
+    class="column-setting-list"
+    :class="{ 'is-root': level === 0, 'is-child-list': level > 0 }"
+  >
+    <div v-for="item in columnList" :key="item.key" class="column-setting-group">
+      <div
+        class="column-setting-item"
+        :class="{ 'is-group': hasChildColumns(item), 'is-child': level > 0 }"
+      >
+        <button
+          type="button"
+          class="column-setting-icon-btn column-setting-drag-handle"
+          :class="dragHandleClass"
+          title="拖拽排序"
+        >
+          <div class="i-lucide:grip-vertical"></div>
+        </button>
+        <span class="column-setting-label" :title="item.label">
+          {{ item.label }}
+        </span>
+        <el-tooltip
+          :content="getVisibleTooltip(item)"
+          placement="top"
+          :show-after="500"
+          :hide-after="0"
+        >
+          <button
+            type="button"
+            class="column-setting-icon-btn"
+            :class="{ 'is-active': item.visible }"
+            @click="tableContext.updateColumnVisible(item.key, !item.visible)"
+          >
+            <div :class="item.visible ? 'i-lucide:eye' : 'i-lucide:eye-off'"></div>
+          </button>
+        </el-tooltip>
+        <el-tooltip
+          :content="getFixedTooltip(item, 'left')"
+          placement="top"
+          :show-after="500"
+          :hide-after="0"
+        >
+          <button
+            type="button"
+            class="column-setting-icon-btn"
+            :class="{ 'is-active': item.fixed === 'left' }"
+            @click="toggleColumnFixed(item, 'left')"
+          >
+            <div class="i-lucide:panel-left"></div>
+          </button>
+        </el-tooltip>
+        <el-tooltip
+          :content="getFixedTooltip(item, 'right')"
+          placement="top"
+          :show-after="500"
+          :hide-after="0"
+        >
+          <button
+            type="button"
+            class="column-setting-icon-btn"
+            :class="{ 'is-active': item.fixed === 'right' }"
+            @click="toggleColumnFixed(item, 'right')"
+          >
+            <div class="i-lucide:panel-right"></div>
+          </button>
+        </el-tooltip>
+      </div>
+
+      <ZmTableColumnSettingTree
+        v-if="item.children?.length"
+        :model-value="item.children"
+        :parent-key="item.key"
+        :level="level + 1"
+        @update:model-value="(children) => handleChildColumnOrder(item.key, children)"
+      />
+    </div>
+  </VueDraggable>
+</template>
+
+<style scoped lang="scss">
+.column-setting-list {
+  display: flex;
+  min-width: var(--zm-table-column-setting-list-min-width, 0);
+  flex-direction: column;
+  gap: var(--zm-table-column-setting-list-gap, 4px);
+
+  &.is-root {
+    max-height: var(--zm-table-column-setting-list-max-height, 360px);
+    overflow-y: auto;
+  }
+
+  &.is-child-list {
+    padding-left: var(--zm-table-column-setting-child-list-padding-left, 18px);
+    margin: var(--zm-table-column-setting-child-list-margin, 3px 0 6px);
+    border-left: var(--zm-table-column-setting-child-list-border-width, 1px)
+      var(--zm-table-column-setting-child-list-border-style, dashed)
+      var(--zm-table-column-setting-child-list-border-color, var(--el-border-color));
+    gap: var(--zm-table-column-setting-child-list-gap, 3px);
+  }
+}
+
+.column-setting-group {
+  min-width: var(--zm-table-column-setting-group-min-width, 0);
+}
+
+.column-setting-item {
+  display: grid;
+  height: var(--zm-table-column-setting-item-height, 32px);
+  min-width: var(--zm-table-column-setting-item-min-width, 0);
+  padding: var(--zm-table-column-setting-item-padding, 0 4px);
+  font-size: var(--zm-table-column-setting-item-font-size, 12px);
+  font-weight: var(--zm-table-column-setting-item-font-weight, 400);
+  color: var(--zm-table-column-setting-item-text-color, var(--el-text-color-regular));
+  border-radius: var(--zm-table-column-setting-item-radius, 6px);
+  align-items: center;
+  column-gap: var(--zm-table-column-setting-item-column-gap, 6px);
+  grid-template-columns: var(
+    --zm-table-column-setting-item-grid-template-columns,
+    22px minmax(0, 1fr) repeat(3, 24px)
+  );
+
+  &:hover {
+    background: var(--zm-table-column-setting-item-hover-bg, var(--el-fill-color-lighter));
+  }
+
+  &.is-group {
+    font-weight: var(--zm-table-column-setting-group-font-weight, 600);
+  }
+
+  &.is-child {
+    height: var(--zm-table-column-setting-child-item-height, 30px);
+    padding-left: var(--zm-table-column-setting-child-item-padding-left, 2px);
+  }
+}
+
+.column-setting-label {
+  overflow: hidden;
+  font-size: var(--zm-table-column-setting-label-font-size, inherit);
+  font-weight: var(--zm-table-column-setting-label-font-weight, inherit);
+  color: var(--zm-table-column-setting-label-text-color, currentcolor);
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+
+.column-setting-icon-btn {
+  display: flex;
+  width: var(--zm-table-column-setting-icon-btn-size, 22px);
+  height: var(--zm-table-column-setting-icon-btn-size, 22px);
+  padding: var(--zm-table-column-setting-icon-btn-padding, 0);
+  color: var(--zm-table-column-setting-icon-btn-color, #8aa0b8);
+  cursor: pointer;
+  background: var(--zm-table-column-setting-icon-btn-bg, transparent);
+  border: var(--zm-table-column-setting-icon-btn-border, 0);
+  border-radius: var(--zm-table-column-setting-icon-btn-radius, 4px);
+  align-items: center;
+  justify-content: center;
+
+  &:hover,
+  &.is-active {
+    color: var(--zm-table-column-setting-icon-btn-active-color, var(--el-color-primary));
+    background-color: var(
+      --zm-table-column-setting-icon-btn-active-bg,
+      var(--el-color-primary-light-9)
+    );
+  }
+
+  > div {
+    width: var(--zm-table-column-setting-icon-size, 15px);
+    height: var(--zm-table-column-setting-icon-size, 15px);
+  }
+}
+
+.column-setting-drag-handle {
+  cursor: var(--zm-table-column-setting-drag-cursor, grab);
+
+  &:active {
+    cursor: var(--zm-table-column-setting-drag-active-cursor, grabbing);
+  }
+}
+
+.column-setting-ghost {
+  background: var(--zm-table-column-setting-ghost-bg, var(--el-color-primary-light-9));
+  opacity: var(--zm-table-column-setting-ghost-opacity, 0.55);
+}
+</style>

+ 412 - 77
src/components/ZmTable/index.vue

@@ -1,7 +1,30 @@
 <script lang="ts" setup generic="T">
 import type { TableInstance, TableProps } from 'element-plus'
-import { FilterPayload, SortField, SortOrder, TableContextKey } from './token'
-import { DefaultRow } from 'element-plus/es/components/table/src/table/defaults'
+import {
+  Comment,
+  Fragment,
+  Text,
+  cloneVNode,
+  computed,
+  nextTick,
+  provide,
+  ref,
+  useAttrs,
+  useSlots
+} from 'vue'
+import { TableContextKey } from './token'
+import type { ColumnFixed, ColumnSettingItem } from './token'
+import type { DefaultRow } from 'element-plus/es/components/table/src/table/defaults'
+import type { VNode } from 'vue'
+
+interface ColumnMeta {
+  key: string
+  label: string
+  action: boolean
+  configurable: boolean
+  fixed: ColumnFixed
+  children: ColumnMeta[]
+}
 
 interface Props
   extends /* @vue-ignore */ Partial<
@@ -9,21 +32,18 @@ interface Props
   > {
   data: T[]
   loading: boolean
-  handleQuery?: (payload?: FilterPayload) => void
-  sortingFields?: SortField[]
-  sortFn?: (prop: string, order: SortOrder | null) => void
   customClass?: boolean
   showBorder?: boolean
+  columnMaxWidth?: number
 }
 
 const props = defineProps<Props>()
-
-const emits = defineEmits<{
-  'update:sortingFields': [fields: SortField[]]
-}>()
-
 const attrs = useAttrs()
+const slots = useSlots()
 const tableRef = ref<TableInstance>()
+const columnSettings = ref<ColumnSettingItem[]>([])
+const columnDefaultSettings = ref<ColumnSettingItem[]>([])
+const slotColumnSignature = ref('')
 
 const defaultOptions: Partial<Props> = {
   size: 'default',
@@ -40,7 +60,13 @@ const defaultOptions: Partial<Props> = {
 }
 
 const bindProps = computed(() => {
-  const { data, sortingFields, ...otherProps } = props
+  const {
+    data,
+    customClass: _customClass,
+    showBorder: _showBorder,
+    columnMaxWidth,
+    ...otherProps
+  } = props
 
   return {
     ...defaultOptions,
@@ -50,44 +76,289 @@ const bindProps = computed(() => {
   }
 })
 
-const handleDefaultSort = (prop: string, order: SortOrder | null) => {
-  const newFields = [...(props.sortingFields || [])]
+const safeData = computed(() => props.data || [])
+const safeLoading = computed(() => props.loading)
+const safeColumnMaxWidth = computed(() => {
+  const maxWidth = Number(props.columnMaxWidth)
+  return Number.isFinite(maxWidth) && maxWidth > 0 ? maxWidth : 360
+})
+
+const forwardedSlots = computed(() => {
+  const { default: _default, ...restSlots } = slots
+  return restSlots
+})
+
+const getPropValue = (props: Record<string, any> | null | undefined, ...keys: string[]) => {
+  if (!props) return undefined
+  for (const key of keys) {
+    if (props[key] !== undefined) return props[key]
+  }
+  return undefined
+}
 
-  const idx = newFields.findIndex((f) => f.field === prop)
+const toBoolean = (value: unknown) => value === true || value === ''
 
-  if (order === null) {
-    if (idx > -1) {
-      newFields.splice(idx, 1)
+const normalizeFixed = (fixed: unknown): ColumnFixed => {
+  if (fixed === true || fixed === 'left') return 'left'
+  if (fixed === 'right') return 'right'
+  return false
+}
+
+const isColumnNode = (node: VNode) => {
+  if (!node.type && typeof node.type !== 'object') return false
+  const nodeType = node.type as { __name?: string }
+  return nodeType.__name === 'ZmTableColumn'
+}
+
+const canResolveColumnChildren = (node: VNode) => {
+  const nodeProps = node.props
+  return toBoolean(getPropValue(nodeProps, 'isParent'))
+}
+
+const getColumnKey = (node: VNode, index: number, parentKey?: string) => {
+  const nodeProps = node.props
+  const key = getPropValue(nodeProps, 'columnKey', 'column-key')
+  const prop = getPropValue(nodeProps, 'prop')
+  const type = getPropValue(nodeProps, 'type')
+  const label = getPropValue(nodeProps, 'label')
+  const fallbackKey = parentKey ? `${parentKey}.column-${index}` : `column-${index}`
+  return String(key ?? prop ?? type ?? label ?? fallbackKey)
+}
+
+const getColumnLabel = (node: VNode, index: number, parentKey?: string) => {
+  const label = getPropValue(node.props, 'label')
+  return String(label ?? getColumnKey(node, index, parentKey))
+}
+
+const getColumnChildren = (node: VNode) => {
+  if (!canResolveColumnChildren(node)) return []
+  const children = node.children
+  if (children && typeof children === 'object' && 'default' in children) {
+    const defaultSlot = (children as { default?: unknown }).default
+    if (typeof defaultSlot !== 'function') return []
+    try {
+      const slotNodes = defaultSlot()
+      const normalizedNodes = Array.isArray(slotNodes) ? slotNodes : slotNodes ? [slotNodes] : []
+      return flattenSlotNodes(normalizedNodes as VNode[]).filter(isColumnNode)
+    } catch {
+      return []
     }
-  } else {
-    if (idx > -1) {
-      newFields[idx] = { ...newFields[idx], order }
-    } else {
-      newFields.push({ field: prop, order })
+  }
+  return []
+}
+
+const getColumnMeta = (node: VNode, index: number, parentKey?: string): ColumnMeta => {
+  const key = getColumnKey(node, index, parentKey)
+  const action = toBoolean(getPropValue(node.props, 'action'))
+  const hideInColumnSettings = toBoolean(
+    getPropValue(node.props, 'hideInColumnSettings', 'hide-in-column-settings')
+  )
+  return {
+    key,
+    label: getColumnLabel(node, index, parentKey),
+    action,
+    configurable: !action && !hideInColumnSettings,
+    fixed: normalizeFixed(getPropValue(node.props, 'fixed')),
+    children: getColumnChildren(node)
+      .map((child, childIndex) => getColumnMeta(child, childIndex, key))
+      .filter((item) => item.configurable)
+  }
+}
+
+const flattenSlotNodes = (nodes: Array<VNode | null | undefined>): VNode[] => {
+  return nodes.flatMap((node) => {
+    if (!node) return []
+    if (node.type === Fragment && Array.isArray(node.children)) {
+      return flattenSlotNodes(node.children as VNode[])
     }
+    if (node.type === Comment || node.type === Text) return []
+    return [node]
+  })
+}
+
+const syncColumnSettings = (nodes: VNode[]) => {
+  const metas = nodes
+    .map((node, index) => getColumnMeta(node, index))
+    .filter((item) => item.configurable)
+  const signature = JSON.stringify(metas)
+  if (signature === slotColumnSignature.value) return
+  slotColumnSignature.value = signature
+  nextTick(() => {
+    const defaults = metas.map(createDefaultColumnSetting)
+    columnDefaultSettings.value = defaults
+    columnSettings.value = mergeColumnSettings(defaults, columnSettings.value)
+  })
+}
+
+const createDefaultColumnSetting = (meta: ColumnMeta): ColumnSettingItem => ({
+  key: meta.key,
+  label: meta.label,
+  visible: true,
+  fixed: meta.fixed,
+  children: meta.children.length ? meta.children.map(createDefaultColumnSetting) : undefined
+})
+
+const mergeColumnSettings = (
+  defaults: ColumnSettingItem[],
+  current: ColumnSettingItem[]
+): ColumnSettingItem[] => {
+  const defaultMap = new Map(defaults.map((item) => [item.key, item]))
+  const currentMap = new Map(current.map((item) => [item.key, item]))
+  const existingItems = current
+    .filter((item) => defaultMap.has(item.key))
+    .map((item) => {
+      const defaultItem = defaultMap.get(item.key)!
+      return {
+        ...defaultItem,
+        visible: item.visible,
+        fixed: item.fixed,
+        children: defaultItem.children
+          ? mergeColumnSettings(defaultItem.children, item.children || [])
+          : undefined
+      }
+    })
+  const addedItems = defaults.filter((item) => !currentMap.has(item.key))
+  return [...existingItems, ...addedItems]
+}
+
+const mapColumnSettings = (
+  items: ColumnSettingItem[],
+  mapper: (item: ColumnSettingItem) => ColumnSettingItem
+): ColumnSettingItem[] => {
+  return items.map((item) => {
+    const mappedItem = mapper(item)
+    return {
+      ...mappedItem,
+      children: mappedItem.children ? mapColumnSettings(mappedItem.children, mapper) : undefined
+    }
+  })
+}
+
+const updateColumnVisible = (key: string, visible: boolean) => {
+  columnSettings.value = mapColumnSettings(columnSettings.value, (item) =>
+    item.key === key ? { ...item, visible } : item
+  )
+}
+
+const updateColumnFixed = (key: string, fixed: ColumnFixed) => {
+  columnSettings.value = mapColumnSettings(columnSettings.value, (item) =>
+    item.key === key ? { ...item, fixed } : item
+  )
+}
+
+const sortSettingsByKeys = (items: ColumnSettingItem[], keys: string[]) => {
+  const orderMap = new Map(keys.map((key, index) => [key, index]))
+  return [...items].sort((a, b) => {
+    const orderA = orderMap.get(a.key) ?? Number.MAX_SAFE_INTEGER
+    const orderB = orderMap.get(b.key) ?? Number.MAX_SAFE_INTEGER
+    return orderA - orderB
+  })
+}
+
+const updateColumnOrder = (keys: string[], parentKey?: string) => {
+  if (!parentKey) {
+    columnSettings.value = sortSettingsByKeys(columnSettings.value, keys)
+    return
   }
 
-  emits('update:sortingFields', newFields)
-  props.handleQuery?.()
+  columnSettings.value = mapColumnSettings(columnSettings.value, (item) => {
+    if (item.key !== parentKey) return item
+
+    return {
+      ...item,
+      children: item.children ? sortSettingsByKeys(item.children, keys) : item.children
+    }
+  })
 }
 
-const safeSortingFields = computed(() => props.sortingFields || [])
-const safeData = computed(() => props.data || [])
-const safeLoading = computed(() => props.loading)
+const cloneColumnSettings = (items: ColumnSettingItem[]): ColumnSettingItem[] => {
+  return items.map((item) => ({
+    ...item,
+    children: item.children ? cloneColumnSettings(item.children) : undefined
+  }))
+}
 
-provide(TableContextKey, {
-  onQuery: (payload) => props.handleQuery?.(payload),
-  onSort: (prop, order) => {
-    if (props.sortFn) {
-      props.sortFn(prop, order)
-    } else {
-      handleDefaultSort(prop, order)
+const resetColumnSettings = () => {
+  columnSettings.value = cloneColumnSettings(columnDefaultSettings.value)
+}
+
+const applyColumnSetting = (node: VNode, setting: ColumnSettingItem) => {
+  const clonedNode = cloneVNode(
+    node,
+    {
+      columnKey: setting.key,
+      fixed: setting.fixed || undefined,
+      key: `${setting.key}-${setting.visible}-${setting.fixed || 'none'}`
+    },
+    true
+  )
+
+  const childNodes = getColumnChildren(node)
+  if (!childNodes.length || !setting.children?.length) return clonedNode
+
+  const originalChildren =
+    clonedNode.children && typeof clonedNode.children === 'object' ? clonedNode.children : {}
+
+  return {
+    ...clonedNode,
+    children: {
+      ...(originalChildren as Record<string, unknown>),
+      default: () => renderColumnNodes(childNodes, setting.children || [], setting.key)
     }
-  },
-  // 关键:传递响应式的 data 和 sortingFields
+  } as VNode
+}
+
+const isColumnVisible = (setting: ColumnSettingItem) => {
+  if (setting.visible === false) return false
+  if (!setting.children?.length) return true
+  return setting.children.some(isColumnVisible)
+}
+
+const renderColumnNodes = (nodes: VNode[], settings: ColumnSettingItem[], parentKey?: string) => {
+  const settingMap = new Map(settings.map((item) => [item.key, item]))
+  const orderMap = new Map(settings.map((item, index) => [item.key, index]))
+  const sortedConfigurableNodes = nodes
+    .map((node, index) => ({ node, meta: getColumnMeta(node, index, parentKey) }))
+    .filter(({ meta }) => {
+      const setting = settingMap.get(meta.key)
+      return meta.configurable && setting && isColumnVisible(setting)
+    })
+    .sort((a, b) => {
+      const orderA = orderMap.get(a.meta.key) ?? Number.MAX_SAFE_INTEGER
+      const orderB = orderMap.get(b.meta.key) ?? Number.MAX_SAFE_INTEGER
+      return orderA - orderB
+    })
+
+  return nodes.flatMap((node, index) => {
+    const meta = getColumnMeta(node, index, parentKey)
+
+    if (!meta.configurable) return [node]
+
+    const nextColumn = sortedConfigurableNodes.shift()
+    if (!nextColumn) return []
+
+    const setting = settingMap.get(nextColumn.meta.key)
+    return setting ? [applyColumnSetting(nextColumn.node, setting)] : [nextColumn.node]
+  })
+}
+
+const renderDefaultSlot = () => {
+  const nodes = flattenSlotNodes(slots.default?.() || [])
+  syncColumnSettings(nodes)
+  return renderColumnNodes(nodes, columnSettings.value)
+}
+
+const TableDefaultSlot = () => renderDefaultSlot()
+
+provide(TableContextKey, {
   data: safeData,
-  sortingFields: safeSortingFields,
-  loading: safeLoading
+  loading: safeLoading,
+  columnMaxWidth: safeColumnMaxWidth,
+  columnSettings,
+  updateColumnVisible,
+  updateColumnFixed,
+  updateColumnOrder,
+  resetColumnSettings
 })
 
 defineExpose({
@@ -103,34 +374,92 @@ defineExpose({
     v-bind="bindProps"
     :data="data"
   >
-    <template v-for="(_, name) in $slots" #[name]="slotData">
+    <template v-for="(_, name) in forwardedSlots" #[name]="slotData">
       <slot :name="name" v-bind="slotData || {}"></slot>
     </template>
+    <TableDefaultSlot />
   </el-table>
 </template>
 
 <style lang="scss">
 .zm-table {
+  --zm-table-width: 100%;
+  --zm-table-overflow: hidden;
   --zm-table-radius: 10px;
+  --zm-table-bg: var(--el-bg-color);
+  --zm-table-border-width: 1px;
+  --zm-table-border-style: solid;
   --zm-table-border-color: #e7edf4;
+  --zm-table-box-shadow: none;
+  --zm-table-font-family: inherit;
+  --zm-table-font-size: 12px;
   --zm-table-header-border-color: #e3eaf2;
   --zm-table-row-border-color: #edf2f7;
   --zm-table-header-bg: #f7f9fc;
   --zm-table-header-text-color: #6b7f99;
+  --zm-table-header-cell-height: 36px;
+  --zm-table-header-group-cell-height: 42px;
+  --zm-table-header-font-size: 12px;
+  --zm-table-header-font-weight: 600;
+  --zm-table-header-wrapper-width: 100%;
+  --zm-table-header-wrapper-height: 100%;
+  --zm-table-header-wrapper-min-width: 0;
+  --zm-table-header-wrapper-gap: 6px;
+  --zm-table-header-wrapper-font-size: var(--zm-table-header-font-size);
+  --zm-table-header-wrapper-font-weight: var(--zm-table-header-font-weight);
+  --zm-table-header-wrapper-line-height: 16px;
+  --zm-table-header-wrapper-text-color: var(--zm-table-header-text-color);
+  --zm-table-header-title-min-width: 0;
+  --zm-table-header-action-area-height: 100%;
+  --zm-table-header-action-area-margin-left: 4px;
+  --zm-table-header-action-area-gap: 3px;
+  --zm-table-header-icon-btn-size: 18px;
+  --zm-table-header-icon-btn-padding: 0;
+  --zm-table-header-icon-btn-color: #8aa0b8;
+  --zm-table-header-icon-btn-bg: transparent;
+  --zm-table-header-icon-btn-border: 0;
+  --zm-table-header-icon-btn-radius: 4px;
+  --zm-table-header-icon-btn-transition-duration: 0.16s;
+  --zm-table-header-icon-btn-transition-timing: ease;
+  --zm-table-header-icon-btn-hover-color: var(--el-color-primary);
+  --zm-table-header-icon-btn-hover-bg: var(--el-color-primary-light-9);
+  --zm-table-header-icon-btn-active-color: var(--el-color-primary);
+  --zm-table-header-icon-btn-active-bg: var(--el-color-primary-light-9);
+  --zm-table-header-icon-size: 16px;
   --zm-table-body-text-color: #40546d;
   --zm-table-strong-text-color: #24364d;
+  --zm-table-row-font-weight: 500;
   --zm-table-stripe-bg: #fcfdff;
   --zm-table-hover-bg: #f5f9ff;
   --zm-table-current-bg: #eef6ff;
-
-  width: 100%;
-  overflow: hidden;
-  font-size: 12px;
+  --zm-table-cell-height: 38px;
+  --zm-table-cell-padding-x: 13px;
+  --zm-table-cell-first-padding-left: 16px;
+  --zm-table-cell-last-padding-right: 16px;
+  --zm-table-cell-line-height: 18px;
+  --zm-table-cell-transition-duration: 0.16s;
+  --zm-table-cell-transition-timing: ease;
+  --zm-table-empty-min-height: 148px;
+  --zm-table-empty-bg: var(--el-bg-color);
+  --zm-table-empty-text-font-size: 12px;
+  --zm-table-empty-text-color: var(--el-text-color-secondary);
+  --zm-table-fixed-left-shadow: 6px 0 12px -10px rgb(15 23 42 / 22%);
+  --zm-table-fixed-right-shadow: -6px 0 12px -10px rgb(15 23 42 / 22%);
+  --zm-table-scrollbar-size: 7px;
+  --zm-table-scrollbar-thumb-bg: #b8c5d6;
+  --zm-table-scrollbar-thumb-radius: 999px;
+  --zm-table-scrollbar-thumb-opacity: 0.55;
+  --zm-table-scrollbar-thumb-hover-opacity: 0.85;
+
+  width: var(--zm-table-width);
+  overflow: var(--zm-table-overflow);
+  font-family: var(--zm-table-font-family);
+  font-size: var(--zm-table-font-size);
   color: var(--zm-table-body-text-color);
-  background: var(--el-bg-color);
-  border: 1px solid var(--zm-table-border-color);
+  background: var(--zm-table-bg);
+  border: var(--zm-table-border-width) var(--zm-table-border-style) var(--zm-table-border-color);
   border-radius: var(--zm-table-radius);
-  box-shadow: none;
+  box-shadow: var(--zm-table-box-shadow);
 
   &::before,
   &::after {
@@ -160,15 +489,18 @@ defineExpose({
   }
 
   .el-table__cell {
-    height: 38px;
+    height: var(--zm-table-cell-height);
     padding: 0;
     color: var(--zm-table-body-text-color);
-    background: var(--el-bg-color);
-    border-right: 1px solid var(--zm-table-row-border-color) !important;
-    border-bottom: 1px solid var(--zm-table-row-border-color) !important;
+    background: var(--zm-table-bg);
+    border-right: var(--zm-table-border-width) var(--zm-table-border-style)
+      var(--zm-table-row-border-color) !important;
+    border-bottom: var(--zm-table-border-width) var(--zm-table-border-style)
+      var(--zm-table-row-border-color) !important;
     transition:
-      background-color 0.16s ease,
-      color 0.16s ease;
+      background-color var(--zm-table-cell-transition-duration)
+        var(--zm-table-cell-transition-timing),
+      color var(--zm-table-cell-transition-duration) var(--zm-table-cell-transition-timing);
 
     &:last-child {
       border-right: none !important;
@@ -176,22 +508,24 @@ defineExpose({
   }
 
   .cell {
-    padding-right: 13px;
-    padding-left: 13px;
-    line-height: 18px;
+    padding-right: var(--zm-table-cell-padding-x);
+    padding-left: var(--zm-table-cell-padding-x);
+    line-height: var(--zm-table-cell-line-height);
   }
 
   .el-table__header {
     color: var(--zm-table-header-text-color);
 
     .el-table__cell {
-      height: 36px;
-      font-size: 12px;
-      font-weight: 600;
+      height: var(--zm-table-header-cell-height);
+      font-size: var(--zm-table-header-font-size);
+      font-weight: var(--zm-table-header-font-weight);
       color: var(--zm-table-header-text-color);
       background: var(--zm-table-header-bg) !important;
-      border-right: 1px solid var(--zm-table-header-border-color) !important;
-      border-bottom: 1px solid var(--zm-table-header-border-color) !important;
+      border-right: var(--zm-table-border-width) var(--zm-table-border-style)
+        var(--zm-table-header-border-color) !important;
+      border-bottom: var(--zm-table-border-width) var(--zm-table-border-style)
+        var(--zm-table-header-border-color) !important;
 
       .cell {
         display: flex;
@@ -223,7 +557,7 @@ defineExpose({
 
     tr:not(:last-child) {
       .el-table__cell {
-        height: 42px;
+        height: var(--zm-table-header-group-cell-height);
         border-bottom-color: var(--zm-table-header-border-color) !important;
       }
     }
@@ -253,31 +587,31 @@ defineExpose({
 
   .el-table__row {
     .el-table__cell {
-      font-weight: 500;
+      font-weight: var(--zm-table-row-font-weight);
       color: var(--zm-table-strong-text-color);
 
       &:first-child {
         .cell {
-          padding-left: 16px;
+          padding-left: var(--zm-table-cell-first-padding-left);
         }
       }
 
       &:last-child {
         .cell {
-          padding-right: 16px;
+          padding-right: var(--zm-table-cell-last-padding-right);
         }
       }
     }
   }
 
   .el-table__empty-block {
-    min-height: 148px;
-    background: var(--el-bg-color);
+    min-height: var(--zm-table-empty-min-height);
+    background: var(--zm-table-empty-bg);
   }
 
   .el-table__empty-text {
-    font-size: 12px;
-    color: var(--el-text-color-secondary);
+    font-size: var(--zm-table-empty-text-font-size);
+    color: var(--zm-table-empty-text-color);
   }
 
   .el-table__cell.el-table-fixed-column--left,
@@ -286,35 +620,36 @@ defineExpose({
   }
 
   .el-table__cell.el-table-fixed-column--left.is-last-column {
-    box-shadow: 6px 0 12px -10px rgb(15 23 42 / 22%);
+    box-shadow: var(--zm-table-fixed-left-shadow);
   }
 
   .el-table__cell.el-table-fixed-column--right.is-first-column {
-    box-shadow: -6px 0 12px -10px rgb(15 23 42 / 22%);
+    box-shadow: var(--zm-table-fixed-right-shadow);
   }
 
   .el-table__fixed-right-patch {
     background: var(--zm-table-header-bg);
-    border-bottom: 1px solid var(--zm-table-header-border-color);
+    border-bottom: var(--zm-table-border-width) var(--zm-table-border-style)
+      var(--zm-table-header-border-color);
   }
 
   .el-scrollbar__bar {
     &.is-horizontal {
-      height: 7px;
+      height: var(--zm-table-scrollbar-size);
     }
 
     &.is-vertical {
-      width: 7px;
+      width: var(--zm-table-scrollbar-size);
     }
   }
 
   .el-scrollbar__thumb {
-    background: #b8c5d6;
-    border-radius: 999px;
-    opacity: 0.55;
+    background: var(--zm-table-scrollbar-thumb-bg);
+    border-radius: var(--zm-table-scrollbar-thumb-radius);
+    opacity: var(--zm-table-scrollbar-thumb-opacity);
 
     &:hover {
-      opacity: 0.85;
+      opacity: var(--zm-table-scrollbar-thumb-hover-opacity);
     }
   }
 }

+ 17 - 10
src/components/ZmTable/token.ts

@@ -1,23 +1,30 @@
-import type { InjectionKey } from 'vue'
+import type { InjectionKey, Ref } from 'vue'
 
 export type SortOrder = 'asc' | 'desc'
+export type ColumnFixed = false | 'left' | 'right'
 
-export interface SortField {
-  field: string
-  order: SortOrder
+export interface SortChangePayload {
+  prop: string
+  order: SortOrder | null
 }
 
-export interface FilterPayload {
-  prop: string
-  value: any
+export interface ColumnSettingItem {
+  key: string
+  label: string
+  visible: boolean
+  fixed: ColumnFixed
+  children?: ColumnSettingItem[]
 }
 
 export interface TableContext<T = any> {
-  onQuery: (payload?: FilterPayload) => void
-  onSort: (prop: string, order: SortOrder | null) => void
   data: Ref<T[]>
-  sortingFields: Ref<SortField[]>
   loading: Ref<boolean>
+  columnMaxWidth: Ref<number>
+  columnSettings: Ref<ColumnSettingItem[]>
+  updateColumnVisible: (key: string, visible: boolean) => void
+  updateColumnFixed: (key: string, fixed: ColumnFixed) => void
+  updateColumnOrder: (keys: string[], parentKey?: string) => void
+  resetColumnSettings: () => void
 }
 
 export const TableContextKey: InjectionKey<TableContext> = Symbol('zm-table')