Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 49 additions & 9 deletions packages/devui-vue/devui/table/__tests__/table.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,27 @@ let data: Array<Record<string, any>> = [];
describe('d-table', () => {
beforeEach(() => {
data = [
{
firstName: 'Mark',
lastName: 'Otto',
date: '1990/01/11',
gender: 'Male',
},
{
firstName: 'Jacob',
lastName: 'Thornton',
gender: 'Female',
date: '1990/01/12',
},
{
firstName: 'Mark',
lastName: 'Otto',
date: '1990/01/11',
gender: 'Male',
},
{
firstName: 'Danni',
lastName: 'Chen',
gender: 'Male',
gender: 'Female',
date: '1990/01/13',
},
{
firstName: 'green',
lastName: 'gerong',
firstName: 'Green',
lastName: 'Gerong',
gender: 'Male',
date: '1990/01/14',
},
Expand Down Expand Up @@ -232,4 +232,44 @@ describe('d-table', () => {
expect(tableHeader.findAll('tr')[0].findAll('th')[1].attributes('rowspan')).toBe('2');
wrapper.unmount();
});

it('sort', async () => {
const handleSortChange = jest.fn();
const wrapper = mount({
setup() {
const sortDateMethod = (a, b) => {
return a.date > b.date;
};
return () => (
<DTable data={data} onSortChange={handleSortChange}>
<DColumn field="firstName" header="First Name"></DColumn>
<DColumn field="lastName" header="Last Name"></DColumn>
<DColumn field="gender" header="Gender"></DColumn>
<DColumn field="date" header="Date of birth" sortable sort-direction="ASC" sort-method={sortDateMethod}></DColumn>
</DTable>
);
},
});

await nextTick();
await nextTick();

const table = wrapper.find('.devui-table');
const tableHeader = table.find('.devui-table__thead');
const lastTh = tableHeader.find('tr').findAll('th')[3];
expect(lastTh.classes()).toContain('sort-active');

const tableBody = table.find('.devui-table__tbody');
const lastTd = tableBody.find('tr').findAll('td')[3];
expect(lastTd.text()).toBe('1990/01/11');

const sortIcon = lastTh.find('.sort-clickable');
await sortIcon.trigger('click');
expect(lastTd.text()).toBe('1990/01/14');
expect(handleSortChange).toBeCalled();

await sortIcon.trigger('click');
expect(lastTd.text()).toBe('1990/01/12');
expect(handleSortChange).toBeCalled();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { defineComponent, toRef, inject } from 'vue';
import type { PropType } from 'vue';
import { Column } from '../column/column-types';
import { TABLE_TOKEN } from '../../table-types';
import { useFixedColumn } from '../../composable/use-table';
import { useFixedColumn } from '../../composables/use-table';

export default defineComponent({
name: 'DTableBodyTd',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import { TableStore } from '../../store/store-types';
// eslint-disable-next-line no-use-before-define
export type Formatter = (row: DefaultRow, column: Column, cellValue: any, rowIndex: number) => VNode;

export type CompareFn<T = any> = (field: string, a: T, b: T) => boolean;
export type SortMethod<T = any> = (a: T, b: T) => boolean;

export type ColumnType = 'checkable' | 'index' | '';

export type SortDirection = 'ASC' | 'DESC' | '';

export interface FilterConfig {
id: number | string;
name: string;
Expand Down Expand Up @@ -47,9 +49,12 @@ export const tableColumnProps = {
type: Boolean,
default: false,
},
compareFn: {
type: Function as PropType<CompareFn>,
default: (field: string, a: any, b: any): boolean => a[field] < b[field],
sortDirection: {
type: String as PropType<SortDirection>,
default: '',
},
sortMethod: {
type: Function as PropType<SortMethod>,
},
filterable: {
type: Boolean,
Expand Down Expand Up @@ -92,6 +97,7 @@ export interface Column {
header?: string;
order?: number;
sortable?: boolean;
sortDirection: SortDirection;
filterable?: boolean;
filterMultiple?: boolean;
filterList?: FilterConfig[];
Expand All @@ -100,7 +106,7 @@ export interface Column {
renderHeader?: (column: Column, store: TableStore) => VNode;
renderCell?: (rowData: DefaultRow, columnItem: Column, store: TableStore, rowIndex: number) => VNode;
formatter?: Formatter;
compareFn?: CompareFn;
sortMethod: SortMethod;
customFilterTemplate?: CustomFilterSlot;
subColumns?: Slot;
}
Expand Down
16 changes: 11 additions & 5 deletions packages/devui-vue/devui/table/src/components/column/use-column.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ export function createColumn(props: ToRefs<TableColumnProps>, slots: Slots): Col
field,
header,
sortable,
sortDirection,
width,
minWidth,
formatter,
compareFn,
sortMethod,
filterable,
filterList,
filterMultiple,
Expand Down Expand Up @@ -51,10 +52,15 @@ export function createColumn(props: ToRefs<TableColumnProps>, slots: Slots): Col
);

// 排序功能
watch([sortable, compareFn], ([sortableVal, compareFnVal]) => {
column.sortable = sortableVal;
column.compareFn = compareFnVal;
});
watch(
[sortable, sortDirection, sortMethod],
([sortableVal, sortDirectionVal, sortMethodVal]) => {
column.sortable = sortableVal;
column.sortDirection = sortDirectionVal;
column.sortMethod = sortMethodVal;
},
{ immediate: true }
);

// 过滤功能
watch(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { defineComponent, inject, toRefs } from 'vue';
import type { PropType } from 'vue';
import { Column } from '../column/column-types';
import { TABLE_TOKEN } from '../../table-types';
import { Sort } from '../sort';
import Sort from '../sort/sort';
import { Filter } from '../filter';
import { useFixedColumn } from '../../composable/use-table';
import { useFixedColumn } from '../../composables/use-table';
import { useSort, useFilter } from './use-header-th';

export default defineComponent({
Expand All @@ -15,22 +15,25 @@ export default defineComponent({
required: true,
},
},
setup(props: { column: Column }) {
setup(props: { column: Column }, { expose }) {
const table = inject(TABLE_TOKEN);
const store = table.store;
const { column } = toRefs(props);
const directionRef = useSort(table.store, column);
const filteredRef = useFilter(table.store, column);
const { direction, sortClass, handleSort, clearSortOrder } = useSort(column);
const filteredRef = useFilter(store, column);
const { stickyClass, stickyStyle } = useFixedColumn(column);

expose({ clearSortOrder });

return () => (
<th class={stickyClass.value} style={stickyStyle.value}>
<th class={[stickyClass.value, sortClass.value]} style={stickyStyle.value}>
<div class="header-container">
{props.column.renderHeader?.(column.value, table.store)}
{props.column.filterable && (
{column.value.renderHeader?.(column.value, store)}
{column.value.filterable && (
<Filter v-model={filteredRef.value} filterList={props.column.filterList} customTemplate={props.column.customFilterTemplate} />
)}
{column.value.sortable && <Sort sort-direction={direction.value} onSort={handleSort} />}
</div>
{props.column.sortable && <Sort v-model={directionRef.value} />}
</th>
);
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,48 @@
import { ref, watch, Ref, shallowRef } from 'vue';
import { Column, FilterResults } from '../column/column-types';
import { ref, watch, Ref, shallowRef, computed, getCurrentInstance, inject, onMounted } from 'vue';
import type { ComputedRef } from 'vue';
import { Column, FilterResults, SortDirection } from '../column/column-types';
import { TableStore } from '../../store/store-types';
import { SortDirection } from '../../table-types';
import { TABLE_TOKEN } from '../../table-types';

export const useSort = (store: TableStore, column: Ref<Column>): Ref<SortDirection> => {
// 排序功能
const directionRef = ref<SortDirection>('DESC');
watch(
[directionRef, column],
([direction, column]) => {
if (column.sortable) {
store.sortData(column.field, direction, column.compareFn);
interface UseSort {
direction: Ref<SortDirection>;
sortClass: ComputedRef<Record<string, boolean>>;
handleSort: (val: SortDirection) => void;
clearSortOrder: () => void;
}

export const useSort = (column: Ref<Column>): UseSort => {
const table = inject(TABLE_TOKEN);
const store = table.store;
const direction = ref<SortDirection>(column.value.sortDirection);
const sortClass = computed(() => ({
'sort-active': Boolean(direction.value),
}));
const thInstance = getCurrentInstance();
thInstance && store.states.thList.push(thInstance);
onMounted(() => {
column.value.sortable && column.value.sortDirection && store.sortData?.(direction.value, column.value.sortMethod);
});
const execClearSortOrder = () => {
store.states.thList.forEach((th) => {
if (th !== thInstance) {
th.exposed?.clearSortOrder?.();
}
},
{ immediate: true }
);
});
};

const handleSort = (val: SortDirection) => {
direction.value = val;
execClearSortOrder();
store.sortData?.(direction.value, column.value.sortMethod);
table.emit('sort-change', { field: column.value.field, direction: direction.value });
};

const clearSortOrder = () => {
direction.value = '';
};

return directionRef;
return { direction, sortClass, handleSort, clearSortOrder };
};

export const useFilter = (store: TableStore, column: Ref<Column>): Ref<FilterResults> => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@
border: none;
border-bottom: 1px solid $devui-line;
}

.sort-active {
background-color: $devui-list-item-hover-bg;
border-radius: $devui-border-radius 0 0 $devui-border-radius;
}
}

.header-container {
Expand Down

This file was deleted.

11 changes: 11 additions & 0 deletions packages/devui-vue/devui/table/src/components/sort/sort-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { ExtractPropTypes, PropType } from 'vue';
import { SortDirection } from '../column/column-types';

export const sortProps = {
sortDirection: {
type: String as PropType<SortDirection>,
default: '',
},
};

export type SortProps = ExtractPropTypes<typeof sortProps>;
73 changes: 28 additions & 45 deletions packages/devui-vue/devui/table/src/components/sort/sort.tsx
Original file line number Diff line number Diff line change
@@ -1,64 +1,47 @@
import { defineComponent, PropType } from 'vue';
import { SortDirection } from '../../table-types';
import { defineComponent } from 'vue';
import { sortProps, SortProps } from './sort-types';
import './sort.scss';

export const Sort = defineComponent({
props: {
modelValue: {
type: String as PropType<SortDirection>,
default: '',
},
'onUpdate:modelValue': {
type: Function as PropType<(v: SortDirection) => void>,
},
},
emits: ['update:modelValue'],
setup(props, ctx) {
export default defineComponent({
props: sortProps,
emits: ['sort'],
setup(props: SortProps, ctx) {
const directionMap = {
ASC: 'DESC',
DESC: '',
default: 'ASC',
};
const changeDirection = () => {
let direction = '';
if (props.modelValue === 'ASC') {
direction = 'DESC';
} else if (props.modelValue === 'DESC') {
direction = '';
} else {
direction = 'ASC';
}
ctx.emit('update:modelValue', direction);
ctx.emit('sort', directionMap[props.sortDirection || 'default']);
};

return () => (
<span onClick={changeDirection} class='sort-clickable'>
<span onClick={changeDirection} class="sort-clickable">
<i
class={[
'datatable-svg',
{
'sort-icon-default': !props.modelValue,
'sort-icon-asc': props.modelValue === 'ASC',
'sort-icon-desc': props.modelValue === 'DESC',
'sort-icon-default': !props.sortDirection,
'sort-icon-asc': props.sortDirection === 'ASC',
'sort-icon-desc': props.sortDirection === 'DESC',
},
]}>
<svg
width='16px'
height='16px'
viewBox='0 0 16 16'
version='1.1'
xmlns='http://www.w3.org/2000/svg'
xmlns:xlink='http://www.w3.org/1999/xlink'>
<svg width="16px" height="16px" viewBox="0 0 16 16" version="1.1" xmlns="http://www.w3.org/2000/svg">
<defs>
<circle id='sort-svg-path-1' cx='8' cy='8' r='8'></circle>
<filter x='-34.4%' y='-21.9%' width='168.8%' height='168.8%' filterUnits='objectBoundingBox' id='filter-2'>
<feOffset dx='0' dy='2' in='SourceAlpha' result='shadowOffsetOuter1'></feOffset>
<feGaussianBlur stdDeviation='1.5' in='shadowOffsetOuter1' result='shadowBlurOuter1'></feGaussianBlur>
<circle id="sort-svg-path-1" cx="8" cy="8" r="8"></circle>
<filter x="-34.4%" y="-21.9%" width="168.8%" height="168.8%" filterUnits="objectBoundingBox" id="filter-2">
<feOffset dx="0" dy="2" in="SourceAlpha" result="shadowOffsetOuter1"></feOffset>
<feGaussianBlur stdDeviation="1.5" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
<feColorMatrix
values='0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.085309222 0'
type='matrix'
in='shadowBlurOuter1'></feColorMatrix>
values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.085309222 0"
type="matrix"
in="shadowBlurOuter1"></feColorMatrix>
</filter>
</defs>
<g stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'>
<use fill-rule='evenodd' xlink:href='#sort-svg-path-1'></use>
<polygon points='8 4 11 7 5 7'></polygon>
<polygon points='8 12 5 9 11 9'></polygon>
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<use fill-rule="evenodd" xlink:href="#sort-svg-path-1"></use>
<polygon points="8 4 11 7 5 7"></polygon>
<polygon points="8 12 5 9 11 9"></polygon>
</g>
</svg>
</i>
Expand Down
Loading