ny
昨天 282fbc6488f4e8ceb5fda759f963ee88fbf7b999
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
<script lang="ts">
import type { CheckboxChangeEvent } from 'ant-design-vue/lib/checkbox/interface';
import type Sortable from 'sortablejs';
import type { VxeColumnPropTypes } from 'vxe-table';
 
import type { BasicColumn, BasicTableProps, ColumnChangeParam } from '../../types/table';
 
import { computed, defineComponent, nextTick, reactive, ref, toRefs, unref, watchEffect } from 'vue';
 
import { ScrollContainer } from '@jnpf/ui';
import { getPopupContainer as getParentContainer, isFunction, isNullOrUnDef } from '@jnpf/utils';
 
import { ArrowAlignLeft } from '@vben/icons';
import { $t } from '@vben/locales';
 
import { DragOutlined, SettingOutlined } from '@ant-design/icons-vue';
import { Checkbox, Divider, Popover, Tooltip } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import Sortablejs from 'sortablejs';
 
import { useTableContext } from '../../hooks/useTableContext';
 
interface State {
  checkAll: boolean;
  checkedList: string[];
  defaultCheckList: string[];
  isInit?: boolean;
}
 
interface Options {
  fixed?: VxeColumnPropTypes.Fixed;
  label: string;
  value: string;
}
 
export default defineComponent({
  components: {
    ArrowAlignLeft,
    Checkbox,
    CheckboxGroup: Checkbox.Group,
    Divider,
    DragOutlined,
    Popover,
    ScrollContainer,
    SettingOutlined,
    Tooltip,
  },
  emits: ['columnsChange'],
  name: 'ColumnSetting',
 
  setup(_, { attrs, emit }) {
    const table = useTableContext();
 
    // const defaultRowSelection = omit(table.getRowSelection(), 'selectedRowKeys');
    let inited = false;
    // 是否当前的setColums触发的
    let isSetColumnsFromThis = false;
    // 是否当前组件触发的setProps
    let isSetPropsFromThis = false;
 
    const cachePlainOptions = ref<Options[]>([]);
    const plainOptions = ref<any | Options[]>([]);
 
    const plainSortOptions = ref<Options[]>([]);
 
    const columnListRef = ref(null);
 
    const state = reactive<State>({
      checkAll: true,
      checkedList: [],
      defaultCheckList: [],
    });
    /** 缓存初始化props */
    let cacheTableProps: Partial<BasicTableProps> = {};
    const checkIndex = ref(false);
    const checkSelect = ref(false);
 
    const prefixCls = 'jnpf-basic-column-setting';
 
    const getValues = computed(() => {
      return unref(table?.getBindValues) || {};
    });
 
    watchEffect(() => {
      const columns = table.getColumns();
      setTimeout(() => {
        if (isSetColumnsFromThis) {
          isSetColumnsFromThis = false;
        } else if (columns.length > 0) {
          init();
        }
      }, 0);
    });
 
    watchEffect(() => {
      const values = unref(getValues);
      if (isSetPropsFromThis) {
        isSetPropsFromThis = false;
      } else {
        cacheTableProps = cloneDeep(values);
      }
      checkIndex.value = !!values.showIndexColumn;
      // checkSelect.value = !!values.rowSelection;
    });
 
    function getColumns() {
      const ret: Options[] = [];
      table.getColumns({ ignoreAllType: true }).forEach((item) => {
        ret.push({
          label: item.title as string,
          value: (item.dataIndex || item.title) as string,
          ...item,
        });
      });
      return ret;
    }
 
    async function init(isReset = false) {
      // Sortablejs存在bug,不知道在哪个步骤中会向el append了一个childNode,因此这里先清空childNode
      // 有可能复现上述问题的操作:拖拽一个元素,快速的上下移动,最后放到最后的位置中松手
      plainOptions.value = [];
      const columnListEl = unref(columnListRef);
      if (columnListEl && (columnListEl as any).$el) {
        const el = (columnListEl as any).$el as Element;
        [...el.children].forEach((item) => item.remove());
      }
      await nextTick();
      const columns = isReset ? cloneDeep(cachePlainOptions.value) : getColumns();
 
      const checkList = table
        .getColumns({ ignoreAllType: true })
        .map((item) => {
          if (item.defaultHidden) {
            return '';
          }
          return item.dataIndex || item.title;
        })
        .filter(Boolean) as string[];
      plainOptions.value = columns;
      plainSortOptions.value = columns;
      // 更新缓存配置
      table.setCacheColumns?.(columns);
      !isReset && (cachePlainOptions.value = cloneDeep(columns));
      state.defaultCheckList = checkList;
      state.checkedList = checkList;
      // 是否列展示全选
      state.checkAll = checkList.length === columns.length;
      inited = false;
      handleOpenChange();
    }
 
    // checkAll change
    function onCheckAllChange(e: CheckboxChangeEvent) {
      const checkList = plainSortOptions.value.map((item) => item.value);
      plainSortOptions.value.forEach((item) => ((item as BasicColumn).defaultHidden = !e.target.checked));
      if (e.target.checked) {
        state.checkedList = checkList;
        setColumns(checkList);
      } else {
        state.checkedList = [];
        setColumns([]);
      }
    }
 
    const indeterminate = computed(() => {
      const len = plainOptions.value.length;
      const checkedLen = state.checkedList.length;
      // unref(checkIndex) && checkedLen--;
      return checkedLen > 0 && checkedLen < len;
    });
 
    // Trigger when check/uncheck a column
    function onChange(checkedList: any[]) {
      const len = plainSortOptions.value.length;
      state.checkAll = checkedList.length === len;
      const sortList = unref(plainSortOptions).map((item) => item.value);
      checkedList.sort((prev, next) => {
        return sortList.indexOf(prev) - sortList.indexOf(next);
      });
      unref(plainSortOptions).forEach((item) => {
        (item as BasicColumn).defaultHidden = !checkedList.includes(item.value);
      });
      setColumns(checkedList);
    }
 
    let sortable: Sortable;
    let sortableOrder: string[] = [];
    // reset columns
    function reset() {
      setColumns(cachePlainOptions.value);
      init(true);
      checkIndex.value = !!cacheTableProps.showIndexColumn;
      // checkSelect.value = !!cacheTableProps.rowSelection;
      table.setProps({
        showIndexColumn: checkIndex.value,
        // rowSelection: checkSelect.value ? defaultRowSelection : undefined,
        // rowSelection: undefined,
      });
      sortable.sort(sortableOrder);
    }
 
    // Open the pop-up window for drag and drop initialization
    function handleOpenChange() {
      if (inited) return;
      nextTick(() => {
        const columnListEl = unref(columnListRef);
        if (!columnListEl) return;
        const el = (columnListEl as any).$el;
        if (!el) return;
        // Drag and drop sort
        sortable = Sortablejs.create(unref(el), {
          animation: 500,
          delay: 400,
          delayOnTouchOnly: true,
          handle: '.table-column-drag-icon',
          onEnd: (evt) => {
            const { newIndex, oldIndex } = evt;
            if (isNullOrUnDef(oldIndex) || isNullOrUnDef(newIndex) || oldIndex === newIndex) {
              return;
            }
            // Sort column
            const columns: any = cloneDeep(plainSortOptions.value);
 
            if (oldIndex > newIndex) {
              columns.splice(newIndex, 0, columns[oldIndex]);
              columns.splice(oldIndex + 1, 1);
            } else {
              columns.splice(newIndex + 1, 0, columns[oldIndex]);
              columns.splice(oldIndex, 1);
            }
 
            plainSortOptions.value = columns;
            setColumns(columns.filter((item) => state.checkedList.includes(item.value)));
          },
        });
        // 记录原始order 序列
        sortableOrder = sortable.toArray();
        inited = true;
      });
    }
 
    // Control whether the serial number column is displayed
    function handleIndexCheckChange(e: CheckboxChangeEvent) {
      isSetPropsFromThis = true;
      isSetColumnsFromThis = true;
      table.setProps({
        showIndexColumn: e.target.checked,
      });
    }
 
    function handleColumnFixed(item: BasicColumn, fixed?: VxeColumnPropTypes.Fixed) {
      if (!state.checkedList.includes(item.dataIndex as string)) return;
 
      const columns: any = getColumns().filter((c: BasicColumn) => state.checkedList.includes(c.dataIndex as string)) as BasicColumn[];
      const isFixed = item.fixed === fixed ? undefined : fixed;
      const index = columns.findIndex((col) => col.dataIndex === item.dataIndex);
      if (index !== -1) {
        columns[index].fixed = isFixed;
      }
      item.fixed = isFixed;
 
      if (isFixed && !item.width) {
        item.width = 100;
      }
      updateSortOption(item);
      table.setCacheColumnsByField?.(item.dataIndex as string, { fixed: isFixed });
      setColumns(columns);
    }
 
    function setColumns(columns: BasicColumn[] | string[]) {
      isSetPropsFromThis = true;
      isSetColumnsFromThis = true;
      table.setColumns(columns);
      const data: ColumnChangeParam[] = unref(plainSortOptions).map((col) => {
        const visible = columns.some((c: BasicColumn | string) => c === col.value || (typeof c !== 'string' && c.dataIndex === col.value));
        return { dataIndex: col.value, fixed: (col.fixed || undefined) as VxeColumnPropTypes.Fixed, visible };
      });
 
      emit('columnsChange', data);
    }
 
    function getPopupContainer() {
      return isFunction(attrs.getPopupContainer) ? attrs.getPopupContainer() : getParentContainer();
    }
 
    function updateSortOption(column: BasicColumn) {
      plainSortOptions.value.forEach((item) => {
        if (item.value === column.dataIndex) {
          Object.assign(item, column);
        }
      });
    }
 
    return {
      t: $t,
      ...toRefs(state),
      checkIndex,
      checkSelect,
      columnListRef,
      getPopupContainer,
      handleColumnFixed,
      handleIndexCheckChange,
      handleOpenChange,
      indeterminate,
      onChange,
      onCheckAllChange,
      plainOptions,
      prefixCls,
      reset,
    };
  },
});
</script>
<template>
  <Tooltip placement="top">
    <template #title>
      <span>{{ t('component.table.settingColumn') }}</span>
    </template>
    <Popover
      :get-popup-container="getPopupContainer"
      :overlay-class-name="`${prefixCls}__column-list`"
      placement="bottomRight"
      trigger="click"
      @open-change="handleOpenChange">
      <template #title>
        <div :class="`${prefixCls}__popover-title`">
          <Checkbox v-model:checked="checkAll" :indeterminate="indeterminate" @change="onCheckAllChange">
            {{ t('component.table.settingColumnShow') }}
          </Checkbox>
          <a-button size="small" type="link" @click="reset">
            {{ t('common.resetText') }}
          </a-button>
        </div>
      </template>
 
      <template #content>
        <ScrollContainer>
          <CheckboxGroup ref="columnListRef" v-model:value="checkedList" @change="onChange">
            <template v-for="item in plainOptions" :key="item.value">
              <div v-if="!('ifShow' in item && !item.ifShow)" :class="`${prefixCls}__check-item`">
                <DragOutlined class="table-column-drag-icon" />
                <Checkbox :value="item.value">
                  {{ item.labelI18nCode ? t(item.labelI18nCode, item.label) : item.label }}
                </Checkbox>
 
                <Tooltip :get-popup-container="getPopupContainer" :mouse-leave-delay="0.4" placement="bottomLeft">
                  <template #title>
                    {{ t('component.table.settingFixedLeft') }}
                  </template>
                  <ArrowAlignLeft
                    :class="[
                      `${prefixCls}__fixed-left`,
                      {
                        active: item.fixed === 'left',
                        disabled: !checkedList.includes(item.value),
                      },
                    ]"
                    @click="handleColumnFixed(item, 'left')" />
                </Tooltip>
                <Divider type="vertical" />
                <Tooltip :get-popup-container="getPopupContainer" :mouse-leave-delay="0.4" placement="bottomLeft">
                  <template #title>
                    {{ t('component.table.settingFixedRight') }}
                  </template>
                  <ArrowAlignLeft
                    :class="[
                      `${prefixCls}__fixed-right`,
                      {
                        active: item.fixed === 'right',
                        disabled: !checkedList.includes(item.value),
                      },
                    ]"
                    @click="handleColumnFixed(item, 'right')" />
                </Tooltip>
              </div>
            </template>
          </CheckboxGroup>
        </ScrollContainer>
      </template>
      <SettingOutlined />
    </Popover>
  </Tooltip>
</template>
<style lang="scss">
.jnpf-basic-column-setting {
  &__popover-title {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 22px;
    margin-bottom: 10px;
  }
 
  &__check-item {
    display: flex;
    align-items: center;
    min-width: 100%;
    padding: 4px 16px 8px 0;
 
    .ant-checkbox-wrapper {
      display: flex;
      flex: 1;
      min-width: 0;
 
      .ant-checkbox + span {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
 
      &:hover {
        color: var(--primary-color);
      }
    }
  }
 
  &__fixed-left,
  &__fixed-right {
    flex-shrink: 0;
    color: var(--text-color-label);
    cursor: pointer;
 
    &.active,
    &:hover {
      color: var(--primary-color);
    }
 
    &.disabled {
      color: rgb(0 0 0 / 25%);
      cursor: not-allowed;
    }
  }
 
  &__fixed-right {
    transform: rotate(180deg);
  }
 
  &__column-list {
    .ant-popover-title {
      font-weight: 500;
      border-bottom: 1px solid var(--border-color-base1);
    }
 
    svg {
      width: 1em !important;
      height: 1em !important;
    }
 
    .table-column-drag-icon {
      margin: 0 5px;
      cursor: move;
    }
 
    .ant-popover-inner-content {
      // max-height: 360px;
      padding-right: 0;
      padding-left: 0;
      // overflow: auto;
    }
 
    .ant-checkbox-group {
      min-width: 260px;
      max-width: 300px;
    }
 
    .scrollbar {
      height: 220px;
    }
  }
}
</style>