refactor DataTable component

This commit is contained in:
pa
2025-12-21 00:36:05 +09:00
committed by Natsumi
parent dff3f17c9a
commit 2ea224cf8d
11 changed files with 323 additions and 282 deletions

View File

@@ -26,307 +26,338 @@
</div>
</template>
<script>
import { computed, onBeforeUnmount, ref, toRefs, watch, watchEffect } from 'vue';
<script setup>
import { computed, onBeforeUnmount, ref, toRaw, toRefs, watch } from 'vue';
import { useAppearanceSettingsStore, useVrcxStore } from '../stores';
export default {
name: 'DataTable',
props: {
data: {
type: Array,
default: () => []
},
tableProps: {
type: Object,
default: () => ({})
},
paginationProps: {
type: Object,
default: () => ({})
},
currentPage: {
type: Number,
default: 1
},
pageSize: {
type: Number,
default: 20
},
pageSizeLinked: {
type: Boolean,
default: false
},
filters: {
type: [Array, Object],
default: () => []
},
loading: {
type: Boolean,
default: false
},
layout: {
type: String,
default: 'table, pagination'
}
const props = defineProps({
data: {
type: Array,
default: () => []
},
emits: [
'update:currentPage',
'update:pageSize',
'update:tableProps',
'size-change',
'current-change',
'selection-change',
'row-click',
'filtered-data',
'sort-change'
],
setup(props, { emit }) {
const appearanceSettingsStore = useAppearanceSettingsStore();
const vrcxStore = useVrcxStore();
const { data, currentPage, pageSize, tableProps, paginationProps, filters } = toRefs(props);
tableProps: {
type: Object,
default: () => ({})
},
paginationProps: {
type: Object,
default: () => ({})
},
currentPage: {
type: Number,
default: 1
},
pageSize: {
type: Number,
default: 20
},
pageSizeLinked: {
type: Boolean,
default: false
},
filters: {
type: Array,
default: () => []
},
loading: {
type: Boolean,
default: false
},
layout: {
type: String,
default: 'table, pagination'
}
});
const internalCurrentPage = ref(currentPage.value);
const internalPageSize = ref(pageSize.value);
const sortData = ref({
prop: props.tableProps.defaultSort?.prop || 'created_at',
order: props.tableProps.defaultSort?.order || 'descending'
});
const emit = defineEmits([
'update:currentPage',
'update:pageSize',
'size-change',
'current-change',
'selection-change',
'row-click',
'sort-change'
]);
const throttledData = ref(Array.isArray(data.value) ? data.value.slice() : []);
const throttledFilters = ref(filters.value);
const throttledSortData = ref({ ...sortData.value });
const appearanceSettingsStore = useAppearanceSettingsStore();
const vrcxStore = useVrcxStore();
let throttleTimerId = null;
const { data, currentPage, pageSize, tableProps, paginationProps, filters } = toRefs(props);
const syncThrottledInputs = () => {
throttleTimerId = null;
throttledData.value = Array.isArray(data.value) ? data.value.slice() : [];
throttledFilters.value = Array.isArray(filters.value) ? filters.value.slice() : filters.value;
throttledSortData.value = { ...sortData.value };
};
const internalCurrentPage = ref(currentPage.value);
const internalPageSize = ref(pageSize.value);
const sortData = ref({
prop: props.tableProps.defaultSort?.prop || 'created_at',
order: props.tableProps.defaultSort?.order || 'descending'
});
const scheduleThrottledSync = () => {
if (throttleTimerId !== null) {
return;
}
throttleTimerId = setTimeout(syncThrottledInputs, 500);
};
const asRawArray = (value) => (Array.isArray(value) ? toRaw(value) : []);
const isEmptyFilterValue = (value) => (Array.isArray(value) ? value.length === 0 : !value);
const hasActiveFilters = (activeFilters) => {
if (!Array.isArray(activeFilters) || activeFilters.length === 0) return false;
return activeFilters.some((filter) => !isEmptyFilterValue(filter?.value));
};
watch(data, scheduleThrottledSync);
watch(() => (Array.isArray(data.value) ? data.value.length : 0), scheduleThrottledSync);
const showPagination = computed(() => {
return props.layout.includes('pagination');
});
watch(filters, scheduleThrottledSync, { deep: true });
watch(sortData, scheduleThrottledSync, { deep: true });
const effectivePageSize = computed(() => {
return props.pageSizeLinked ? appearanceSettingsStore.tablePageSize : internalPageSize.value;
});
onBeforeUnmount(() => {
if (throttleTimerId !== null) {
clearTimeout(throttleTimerId);
throttleTimerId = null;
}
});
const looksSortedByCreatedAtDesc = (src) => {
if (!Array.isArray(src) || src.length <= 2) return true;
const start = Math.max(1, src.length - effectivePageSize.value - 1);
for (let i = start; i < src.length; i++) {
const a = src[i - 1]?.created_at;
const b = src[i]?.created_at;
if (typeof a === 'string' && typeof b === 'string' && a > b) {
return false;
}
}
return true;
};
const showPagination = computed(() => {
return props.layout.includes('pagination');
});
const throttledData = ref(asRawArray(data.value));
const throttledFilters = ref(filters.value);
const throttledSortData = ref({ ...sortData.value });
const throttledLooksSortedByCreatedAt = ref(true);
const mergedTableProps = computed(() => ({
stripe: true,
...tableProps.value
}));
let throttleTimerId = null;
const syncThrottledInputs = () => {
throttleTimerId = null;
throttledData.value = asRawArray(data.value);
throttledFilters.value = Array.isArray(filters.value) ? filters.value.slice() : filters.value;
throttledSortData.value = { ...sortData.value };
const mergedPaginationProps = computed(() => ({
layout: 'sizes, prev, pager, next, total',
...paginationProps.value,
pageSizes: paginationProps.value?.pageSizes ?? appearanceSettingsStore.tablePageSizes
}));
const sort = throttledSortData.value;
const shouldCheckFastPath =
showPagination.value &&
!hasActiveFilters(throttledFilters.value) &&
sort?.prop === 'created_at' &&
sort?.order === 'descending';
throttledLooksSortedByCreatedAt.value = shouldCheckFastPath
? looksSortedByCreatedAtDesc(throttledData.value)
: false;
};
const effectivePageSize = computed(() => {
return props.pageSizeLinked ? appearanceSettingsStore.tablePageSize : internalPageSize.value;
});
const scheduleThrottledSync = () => {
if (throttleTimerId !== null) return;
throttleTimerId = setTimeout(syncThrottledInputs, 500);
};
const applyFilter = function (row, filter) {
if (Array.isArray(filter.prop)) {
return filter.prop.some((propItem) => applyFilter(row, { prop: propItem, value: filter.value }));
}
watch(data, scheduleThrottledSync);
watch(() => (Array.isArray(data.value) ? data.value.length : 0), scheduleThrottledSync);
watch(filters, scheduleThrottledSync, { deep: true });
watch(sortData, scheduleThrottledSync, { deep: true });
watch(effectivePageSize, scheduleThrottledSync);
const cellValue = row[filter.prop];
if (cellValue === undefined || cellValue === null) return false;
onBeforeUnmount(() => {
if (throttleTimerId !== null) {
clearTimeout(throttleTimerId);
throttleTimerId = null;
}
});
if (Array.isArray(filter.value)) {
// assume filter dropdown multi select
return filter.value.some((val) => String(cellValue).toLowerCase() === String(val).toLowerCase());
} else {
return String(cellValue).toLowerCase().includes(String(filter.value).toLowerCase());
}
};
const canUseFastCreatedAtDescPagination = computed(() => {
if (!showPagination.value) return false;
if (!throttledLooksSortedByCreatedAt.value) return false;
const filteredData = computed(() => {
let result = throttledData.value;
const activeFilters = throttledFilters.value;
const activeSort = throttledSortData.value;
const activeFilters = throttledFilters.value;
if (hasActiveFilters(activeFilters)) return false;
if (activeFilters && Array.isArray(activeFilters) && activeFilters.length > 0) {
activeFilters.forEach((filter) => {
if (!filter.value) {
return;
}
if (filter.filterFn) {
result = result.filter((row) => filter.filterFn(row, filter));
} else if (!Array.isArray(filter.value) || filter.value.length > 0) {
result = result.filter((row) => applyFilter(row, filter));
}
});
}
const sort = throttledSortData.value;
return sort?.prop === 'created_at' && sort?.order === 'descending';
});
if (activeSort?.prop && activeSort?.order) {
if (result === throttledData.value) {
result = [...result];
}
const { prop, order } = activeSort;
const sortKeyByRow = new Map();
const mergedTableProps = computed(() => ({
stripe: true,
...tableProps.value
}));
const getSortKey = (row) => {
if (sortKeyByRow.has(row)) {
return sortKeyByRow.get(row);
}
const mergedPaginationProps = computed(() => ({
layout: 'sizes, prev, pager, next, total',
...paginationProps.value,
pageSizes: paginationProps.value?.pageSizes ?? appearanceSettingsStore.tablePageSizes
}));
const value = row[prop];
let key;
if (value == null) {
key = null;
} else if (typeof value === 'number') {
key = value;
} else if (value instanceof Date) {
key = value.getTime();
} else {
key = String(value).toLowerCase();
}
const applyFilter = function (row, filter) {
if (Array.isArray(filter.prop)) {
return filter.prop.some((propItem) => applyFilter(row, { prop: propItem, value: filter.value }));
}
sortKeyByRow.set(row, key);
return key;
};
const cellValue = row[filter.prop];
if (cellValue === undefined || cellValue === null) return false;
result.sort((a, b) => {
const aVal = getSortKey(a);
const bVal = getSortKey(b);
let comparison = 0;
if (aVal == null && bVal == null) return 0;
if (aVal == null) return 1;
if (bVal == null) return -1;
if (typeof aVal === 'number' && typeof bVal === 'number') {
comparison = aVal - bVal;
} else {
const aStr = typeof aVal === 'string' ? aVal : String(aVal);
const bStr = typeof bVal === 'string' ? bVal : String(bVal);
if (aStr > bStr) comparison = 1;
else if (aStr < bStr) comparison = -1;
}
return order === 'descending' ? -comparison : comparison;
});
}
return result;
});
watchEffect(
() => {
emit('filtered-data', filteredData.value);
},
{ flush: 'post' }
);
const paginatedData = computed(() => {
if (!showPagination.value) {
return filteredData.value;
}
const start = (internalCurrentPage.value - 1) * effectivePageSize.value;
const end = start + effectivePageSize.value;
return filteredData.value.slice(start, end);
});
// Frictionless user experience when bigger than maxTableSize
const totalItems = computed(() => {
const length = filteredData.value.length;
const max = vrcxStore.maxTableSize;
return length > max && length < max + 51 ? max : length;
});
const handleSortChange = ({ prop, order }) => {
if (props.tableProps.defaultSort) {
const { tableProps } = props;
tableProps.defaultSort.prop = prop;
tableProps.defaultSort.order = order;
emit('update:tableProps', tableProps);
}
sortData.value = { prop, order };
emit('sort-change', sortData.value);
};
const handleSelectionChange = (selection) => {
emit('selection-change', selection);
};
const handleRowClick = (row, column, event) => {
emit('row-click', row, column, event);
};
const handleSizeChange = (size) => {
if (props.pageSizeLinked) {
appearanceSettingsStore.setTablePageSize(size);
return;
}
internalPageSize.value = size;
};
const handleCurrentChange = (page) => {
internalCurrentPage.value = page;
};
watch(currentPage, (newVal) => {
internalCurrentPage.value = newVal;
});
watch(pageSize, (newVal) => {
internalPageSize.value = newVal;
});
watch(
() => props.tableProps.defaultSort,
(newSort) => {
if (newSort) {
sortData.value = {
prop: newSort.prop,
order: newSort.order
};
}
},
{ immediate: true }
);
return {
totalItems,
internalCurrentPage,
internalPageSize,
effectivePageSize,
showPagination,
mergedTableProps,
mergedPaginationProps,
filteredData,
paginatedData,
handleSortChange,
handleSelectionChange,
handleRowClick,
handleSizeChange,
handleCurrentChange
};
if (Array.isArray(filter.value)) {
return filter.value.some((val) => String(cellValue).toLowerCase() === String(val).toLowerCase());
} else {
return String(cellValue).toLowerCase().includes(String(filter.value).toLowerCase());
}
};
const toSortKey = (value) => {
if (value == null) return null;
if (typeof value === 'number') return value;
if (value instanceof Date) return value.getTime();
return String(value).toLowerCase();
};
const compareSortKeys = (aKey, bKey) => {
if (aKey == null && bKey == null) return 0;
if (aKey == null) return 1;
if (bKey == null) return -1;
if (typeof aKey === 'number' && typeof bKey === 'number') {
if (aKey > bKey) return 1;
if (aKey < bKey) return -1;
return 0;
}
const aStr = typeof aKey === 'string' ? aKey : String(aKey);
const bStr = typeof bKey === 'string' ? bKey : String(bKey);
if (aStr > bStr) return 1;
if (aStr < bStr) return -1;
return 0;
};
const createRowSortKeyGetter = (prop) => {
const sortKeyByRow = new Map();
return (row) => {
if (sortKeyByRow.has(row)) {
return sortKeyByRow.get(row);
}
const key = toSortKey(row?.[prop]);
sortKeyByRow.set(row, key);
return key;
};
};
const sortRows = (rows, { prop, order }) => {
const getKey = createRowSortKeyGetter(prop);
rows.sort((a, b) => {
const comparison = compareSortKeys(getKey(a), getKey(b));
return order === 'descending' ? -comparison : comparison;
});
};
const filteredData = computed(() => {
let result = throttledData.value;
const activeFilters = throttledFilters.value;
const activeSort = throttledSortData.value;
if (activeFilters && Array.isArray(activeFilters) && activeFilters.length > 0) {
activeFilters.forEach((filter) => {
if (isEmptyFilterValue(filter?.value)) {
return;
}
if (filter.filterFn) {
result = result.filter((row) => filter.filterFn(row, filter));
} else if (!Array.isArray(filter.value) || filter.value.length > 0) {
result = result.filter((row) => applyFilter(row, filter));
}
});
}
if (activeSort?.prop && activeSort?.order) {
if (result === throttledData.value) {
result = [...result];
}
sortRows(result, activeSort);
}
return result;
});
const paginatedData = computed(() => {
if (!showPagination.value) {
return filteredData.value;
}
if (canUseFastCreatedAtDescPagination.value) {
const src = throttledData.value;
const page = [];
if (!Array.isArray(src) || src.length === 0) {
return page;
}
const startOffset = (internalCurrentPage.value - 1) * effectivePageSize.value;
const endOffset = startOffset + effectivePageSize.value;
for (let offset = startOffset; offset < endOffset; offset++) {
const idx = src.length - 1 - offset;
if (idx < 0) break;
page.push(src[idx]);
}
return page;
}
const start = (internalCurrentPage.value - 1) * effectivePageSize.value;
const end = start + effectivePageSize.value;
return filteredData.value.slice(start, end);
});
const totalItems = computed(() => {
const length = canUseFastCreatedAtDescPagination.value
? Array.isArray(throttledData.value)
? throttledData.value.length
: 0
: filteredData.value.length;
const max = vrcxStore.maxTableSize;
return length > max && length < max + 51 ? max : length;
});
const handleSortChange = ({ prop, order }) => {
sortData.value = { prop, order };
emit('sort-change', sortData.value);
};
const handleSelectionChange = (selection) => {
emit('selection-change', selection);
};
const handleRowClick = (row, column, event) => {
emit('row-click', row, column, event);
};
const handleSizeChange = (size) => {
if (props.pageSizeLinked) {
appearanceSettingsStore.setTablePageSize(size);
emit('update:pageSize', size);
emit('size-change', size);
return;
}
internalPageSize.value = size;
emit('update:pageSize', size);
emit('size-change', size);
};
const handleCurrentChange = (page) => {
internalCurrentPage.value = page;
emit('update:currentPage', page);
emit('current-change', page);
};
watch(currentPage, (newVal) => {
internalCurrentPage.value = newVal;
});
watch(pageSize, (newVal) => {
internalPageSize.value = newVal;
});
watch(
() => props.tableProps.defaultSort,
(newSort) => {
if (newSort) {
sortData.value = {
prop: newSort.prop,
order: newSort.order
};
}
},
{ immediate: true }
);
</script>
<style scoped>

View File

@@ -322,7 +322,17 @@
}, 80);
}
function cancelClose() {
clearTimer('close');
clearTimer('hide');
if (isPopoverOpen(tooltipEl.value)) {
isClosing.value = false;
isOpen.value = true;
}
}
onBeforeUnmount(() => {
close(true);
clearAllTimers();
});
</script>

View File

@@ -13,7 +13,7 @@
style="width: 150px" />
</div>
<DataTable v-loading="loading" v-bind="previousInstancesGroupDialogTable" style="margin-top: 10px">
<DataTable :loading="loading" v-bind="previousInstancesGroupDialogTable" style="margin-top: 10px">
<el-table-column :label="t('table.previous_instances.date')" prop="created_at" sortable width="170">
<template #default="scope">
<span>{{ formatDateFilter(scope.row.created_at, 'long') }}</span>

View File

@@ -15,7 +15,7 @@
style="width: 150px"
clearable></el-input>
</div>
<DataTable v-loading="loading" v-bind="dataTable" style="margin-top: 10px">
<DataTable :loading="loading" v-bind="dataTable" style="margin-top: 10px">
<el-table-column :label="t('table.previous_instances.date')" prop="created_at" sortable width="110">
<template #default="scope">
<el-tooltip placement="left">

View File

@@ -12,7 +12,7 @@
:placeholder="t('dialog.previous_instances.search_placeholder')"
style="display: block; width: 150px"></el-input>
</div>
<DataTable v-loading="loading" v-bind="previousInstancesWorldDialogTable" style="margin-top: 10px">
<DataTable :loading="loading" v-bind="previousInstancesWorldDialogTable" style="margin-top: 10px">
<el-table-column :label="t('table.previous_instances.date')" prop="created_at" sortable width="170">
<template #default="scope">
<span>{{ formatDateFilter(scope.row.created_at, 'long') }}</span>

View File

@@ -12,7 +12,7 @@
:placeholder="t('dialog.previous_instances.search_placeholder')"
style="display: block; width: 150px"></el-input>
</div>
<DataTable v-loading="loading" v-bind="previousInstancesUserDialogTable" style="margin-top: 10px">
<DataTable :loading="loading" v-bind="previousInstancesUserDialogTable" style="margin-top: 10px">
<el-table-column :label="t('table.previous_instances.date')" prop="created_at" sortable width="170">
<template #default="scope">
<span>{{ formatDateFilter(scope.row.created_at, 'long') }}</span>

View File

@@ -121,7 +121,7 @@
</h2>
<pre style="white-space: pre-wrap; font-size: 12px" v-text="avatarImportDialog.errors"></pre>
</template>
<DataTable v-loading="avatarImportDialog.loading" v-bind="avatarImportTable" style="margin-top: 10px">
<DataTable :loading="avatarImportDialog.loading" v-bind="avatarImportTable" style="margin-top: 10px">
<el-table-column :label="t('table.import.image')" width="70" prop="thumbnailImageUrl">
<template #default="{ row }">
<el-popover placement="right" :width="500" trigger="hover">

View File

@@ -91,7 +91,7 @@
<h2 style="font-weight: bold; margin: 5px 0">{{ t('dialog.friend_import.errors') }}</h2>
<pre style="white-space: pre-wrap; font-size: 12px" v-text="friendImportDialog.errors"></pre>
</template>
<DataTable v-loading="friendImportDialog.loading" v-bind="friendImportTable" style="margin-top: 10px">
<DataTable :loading="friendImportDialog.loading" v-bind="friendImportTable" style="margin-top: 10px">
<el-table-column :label="t('table.import.image')" width="70" prop="currentAvatarThumbnailImageUrl">
<template #default="{ row }">
<el-popover placement="right" :width="500" trigger="hover">

View File

@@ -122,7 +122,7 @@
</h2>
<pre style="white-space: pre-wrap; font-size: 12px" v-text="worldImportDialog.errors"></pre>
</template>
<DataTable v-loading="worldImportDialog.loading" v-bind="worldImportTable" style="margin-top: 10px">
<DataTable :loading="worldImportDialog.loading" v-bind="worldImportTable" style="margin-top: 10px">
<el-table-column :label="t('table.import.image')" width="70" prop="thumbnailImageUrl">
<template #default="{ row }">
<el-popover placement="right" :width="500" trigger="hover">

View File

@@ -40,7 +40,7 @@
@change="gameLogTableLookup"></el-input>
</div>
<DataTable v-loading="gameLogTable.loading" v-bind="gameLogTable">
<DataTable v-bind="gameLogTable">
<el-table-column :label="t('table.gameLog.date')" prop="created_at" :sortable="true" width="130">
<template #default="scope">
<NativeTooltip placement="right">

View File

@@ -40,7 +40,7 @@
<pre style="white-space: pre-wrap; font-size: 12px" v-text="errors"></pre>
</template>
<DataTable v-loading="loading" v-bind="noteExportTable" style="margin-top: 10px">
<DataTable :loading="loading" v-bind="noteExportTable" style="margin-top: 10px">
<el-table-column :label="t('table.import.image')" width="70" prop="currentAvatarThumbnailImageUrl">
<template #default="{ row }">
<el-popover placement="right" :width="500" trigger="hover">