Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(DataTable): make grouping work properly when pagination is handled internally #183

Merged
merged 2 commits into from
Jan 26, 2024
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
36 changes: 36 additions & 0 deletions example/src/views/DataTableView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,33 @@
'address.street': 'Skiles Walks',
'address.city': 'Roscoeview',
},
{
'id': 501,
'name': 'Chelsey Dietrich',
'username': 'Kamren',
'email': '[email protected]',
'website': 'demarco.info',
'address.street': 'Skiles Walks',
'address.city': 'Roscoeview',
},
{
'id': 5012,
'name': 'Chelsey Dietrich',
'username': 'Kamren',
'email': '[email protected]',
'website': 'demarco.info',
'address.street': 'Skiles Walks',
'address.city': 'Roscoeview',
},
{
'id': 5013,
'name': 'Chelsey Dietrich',
'username': 'Kamren',
'email': '[email protected]',
'website': 'demarco.info',
'address.street': 'Skiles Walks',
'address.city': 'Roscoeview',
},
{
'id': 10,
'name': 'Clementina DuBuque',
Expand Down Expand Up @@ -180,6 +207,15 @@
'address.street': 'Victor Plains',
'address.city': 'Wisokyburgh',
},
{
'id': 203,
'name': 'Ervin Howell',
'username': 'Antonette',
'email': '[email protected]',
'website': 'anastasia.net',
'address.street': 'Victor Plains',
'address.city': 'Wisokyburgh',
},
{
'id': 19,
'name': 'Glenna Reichert',
Expand Down Expand Up @@ -762,7 +798,7 @@
:data-cy="title"
>
<h4>{{ title }}</h4>
<RuiDataTable

Check warning on line 801 in example/src/views/DataTableView.vue

View workflow job for this annotation

GitHub Actions / ci

File has too many lines (1038). Maximum allowed is 800

Check warning on line 801 in example/src/views/DataTableView.vue

View workflow job for this annotation

GitHub Actions / ci

File has too many lines (1038). Maximum allowed is 800
v-bind="objectOmit(table, ['modelValue', 'pagination', 'sort'])"
v-model="table.modelValue"
v-model:pagination="table.pagination"
Expand Down
191 changes: 104 additions & 87 deletions src/components/tables/DataTable.vue
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,11 @@ const { stick, table, tableScroller } = useStickyTableHeader(

const tableDefaults = useTable();

const headerSlots = computed<`header.${string}`[]>(() => Object.keys(slots).filter(isHeaderSlot));
const expandable = computed(() => props.expanded && slots['expanded-item']);

const headerSlots = computed<`header.${string}`[]>(() =>
Object.keys(slots).filter(isHeaderSlot),
);

const globalItemsPerPageSettings = computed(() => {
if (props.globalItemsPerPage !== undefined)
Expand All @@ -249,6 +253,27 @@ const globalItemsPerPageSettings = computed(() => {

const getKeys = <T extends object>(t: T) => Object.keys(t) as TableRowKey<T>[];

const groupKeys: ComputedRef<TableRowKey<T>[]> = computed(() => {
const groupBy = props.group;

if (!groupBy) {
// no grouping
return [];
}

if (!Array.isArray(groupBy)) {
// currently only supports a single grouping
// only the first item in the array is used
return [groupBy];
}

return groupBy;
});

const groupKey = computed(() => get(groupKeys).join(':'));

const isGrouped = computed(() => !!get(groupKey));

/**
* Prepare the columns from props or generate using first item in the list
*/
Expand Down Expand Up @@ -312,26 +337,6 @@ watchImmediate(collapsed, (value) => {
set(collapsedRows, value ?? []);
});

const expandable = computed(() => props.expanded && slots['expanded-item']);

/**
* Keeps the global items per page in sync with the internal state.
*/
watch(internalPaginationState, (pagination) => {
if (pagination?.limit && get(globalItemsPerPageSettings))
set(tableDefaults.itemsPerPage, pagination.limit);
});

watch(tableDefaults.itemsPerPage, (itemsPerPage) => {
if (!get(globalItemsPerPageSettings))
return;

set(paginationData, {
...get(paginationData),
limit: itemsPerPage,
});
});

/**
* Pagination is different for search
* since search is only used for internal filtering
Expand Down Expand Up @@ -406,34 +411,6 @@ const sortedMap = computed(() => {
}, mapped);
});

/**
* list if ids of the visible table rows used for check-all and uncheck-all
*/
const visibleIdentifiers = computed<T[IdType][]>(() => {
const selectBy = props.rowAttr;

if (!selectBy)
return [];

return get(filtered)
.filter(isRow)
.map(row => row[selectBy]);
});

/**
* Flag to know when all rows are selected for the current screen
*/
const isAllSelected = computed<boolean>(() => {
const selectedRows = get(selectedData);
if (!selectedRows)
return false;

return (
selectedRows.length > 0
&& get(visibleIdentifiers).every(id => selectedRows.includes(id))
);
});

/**
* rows filtered based on search query if it exists
*/
Expand Down Expand Up @@ -493,27 +470,6 @@ const sorted: ComputedRef<T[]> = computed(() => {
return data;
});

const groupKeys: ComputedRef<TableRowKey<T>[]> = computed(() => {
const groupBy = props.group;

if (!groupBy) {
// no grouping
return [];
}

if (!Array.isArray(groupBy)) {
// currently only supports a single grouping
// only the first item in the array is used
return [groupBy];
}

return groupBy;
});

const groupKey = computed(() => get(groupKeys).join(':'));

const isGrouped = computed(() => !!get(groupKey));

/**
* comprises search, sorted paginated, and grouped data
*/
Expand All @@ -534,11 +490,11 @@ const mappedGroups = computed<Record<string, GroupedTableRow<T>[]>>(() => {
const groupVal = Object.values(group).filter(isDefined).join(',');
if (!acc[groupVal]) {
acc[groupVal] = [
{
__header__: true,
group,
identifier: groupVal,
} satisfies GroupHeader<T>,
{
__header__: true,
group,
identifier: groupVal,
} satisfies GroupHeader<T>,
];
}

Expand All @@ -560,9 +516,7 @@ const grouped = computed<GroupedTableRow<T>[]>(() => {
return result;
}

return Object.values(get(mappedGroups))
.flatMap(grouped => grouped)
.filter(row => !isHiddenRow(row));
return Object.values(get(mappedGroups)).flatMap(grouped => grouped);
});

/**
Expand All @@ -576,10 +530,52 @@ const filtered = computed<GroupedTableRow<T>[]>(() => {
if (paginated && !props.paginationModifiers?.external) {
const start = (paginated.page - 1) * limit;
const end = start + limit;
return result.slice(start, end);
const preGroups = result.slice(0, start + 1).filter(item => !isRow(item));
const postGroups = result.slice(start + 1, end + preGroups.length).filter(item => !isRow(item));
const data = result.slice(start + preGroups.length, end + preGroups.length + postGroups.length);
const nearestGroup = preGroups.at(-1);
if (data.length > 0) {
// if our first item is not a group, push in the nearest group
if (isRow(data[0]) && nearestGroup)
data.unshift(nearestGroup);
const lastItem = data.at(-1);
// if our last item is a group, remove it
if (lastItem && !isRow(lastItem))
data.pop();
}

return data.filter(row => !isHiddenRow(row));
}

return result;
return result.filter(row => !isHiddenRow(row));
});

/**
* list if ids of the visible table rows used for check-all and uncheck-all
*/
const visibleIdentifiers = computed<T[IdType][]>(() => {
const selectBy = props.rowAttr;

if (!selectBy)
return [];

return get(filtered)
.filter(isRow)
.map(row => row[selectBy]);
});

/**
* Flag to know when all rows are selected for the current screen
*/
const isAllSelected = computed<boolean>(() => {
const selectedRows = get(selectedData);
if (!selectedRows)
return false;

return (
selectedRows.length > 0
&& get(visibleIdentifiers).every(id => selectedRows.includes(id))
);
});

const indeterminate = computed(() => {
Expand Down Expand Up @@ -672,7 +668,10 @@ function isExpandedGroup(value: Partial<T>) {
function isHiddenRow(row: GroupedTableRow<T>) {
const identifier = props.rowAttr;
return (
get(isGrouped) && get(collapsedRows).some(value => isRow(row) && row[identifier] === value[identifier])
get(isGrouped)
&& get(collapsedRows).some(
value => isRow(row) && row[identifier] === value[identifier],
)
);
}

Expand Down Expand Up @@ -809,15 +808,33 @@ function onPaginate() {
emit('update:expanded', []);
}

function setInternalTotal(groupedItems: GroupedTableRow<T>[]) {
function setInternalTotal(items: GroupedTableRow<T>[]) {
if (!props.paginationModifiers?.external)
set(itemsLength, groupedItems.filter(isRow).length);
set(itemsLength, items.filter(isRow).length);
}

function cellValue(row: T, key: TableColumn<T>['key']) {
return row[key as TableRowKey<T>];
}

/**
* Keeps the global items per page in sync with the internal state.
*/
watch(internalPaginationState, (pagination) => {
if (pagination?.limit && get(globalItemsPerPageSettings))
set(tableDefaults.itemsPerPage, pagination.limit);
});

watch(tableDefaults.itemsPerPage, (itemsPerPage) => {
if (!get(globalItemsPerPageSettings))
return;

set(paginationData, {
...get(paginationData),
limit: itemsPerPage,
});
});

/**
* on changing search query, need to reset pagination page to 1
*/
Expand All @@ -827,10 +844,10 @@ watch(search, () => {
pagination.page = 1;
});

watch(grouped, setInternalTotal);
watch(sorted, setInternalTotal);

onMounted(() => {
setInternalTotal(get(grouped));
setInternalTotal(get(sorted));

if (!get(globalItemsPerPageSettings))
return;
Expand Down Expand Up @@ -1004,10 +1021,10 @@ onMounted(() => {
>
<Checkbox
:data-cy="`table-toggle-check-${index}`"
:value="isSelected(row[rowIdentifier])"
:model-value="isSelected(row[rowIdentifier])"
color="primary"
hide-details
@input="onSelect($event, row[rowIdentifier])"
@update:model-value="onSelect($event, row[rowIdentifier])"
/>
</td>

Expand Down
4 changes: 2 additions & 2 deletions src/components/tables/TableHead.vue
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,11 @@ function getSortDirection(key: TableColumn<T>['key']) {
<Checkbox
:disabled="disableCheckAll"
:indeterminate="indeterminate"
:value="isAllSelected"
:model-value="isAllSelected"
color="primary"
data-cy="table-toggle-check-all"
hide-details
@input="onToggleAll($event)"
@update:model-value="onToggleAll($event)"
/>
</th>

Expand Down
Loading