From 2e8203f666f6363e5d49bcf385eea1e31a46bd9b Mon Sep 17 00:00:00 2001 From: Kevin Lakotko Date: Mon, 7 Jul 2025 12:23:27 -0400 Subject: [PATCH] Sort groups if same as sort column (#26010) * fix(grouping): if sorted by column sort group * chore: use props to group for memoization --- src/components/data-table/ha-data-table.ts | 43 +++++++++++++++++----- 1 file changed, 34 insertions(+), 9 deletions(-) diff --git a/src/components/data-table/ha-data-table.ts b/src/components/data-table/ha-data-table.ts index 0369758b29..c625e9782d 100644 --- a/src/components/data-table/ha-data-table.ts +++ b/src/components/data-table/ha-data-table.ts @@ -507,7 +507,9 @@ export class HaDataTable extends LitElement { this.hasFab, this.groupColumn, this.groupOrder, - this._collapsedGroups + this._collapsedGroups, + this.sortColumn, + this.sortDirection )} .keyFunction=${this._keyFunction} .renderItem=${renderRow} @@ -702,22 +704,37 @@ export class HaDataTable extends LitElement { hasFab: boolean, groupColumn: string | undefined, groupOrder: string[] | undefined, - collapsedGroups: string[] + collapsedGroups: string[], + sortColumn: string | undefined, + sortDirection: SortingDirection ) => { if (appendRow || hasFab || groupColumn) { let items = [...data]; if (groupColumn) { + const isGroupSortColumn = sortColumn === groupColumn; const grouped = groupBy(items, (item) => item[groupColumn]); if (grouped.undefined) { // make sure ungrouped items are at the bottom grouped[UNDEFINED_GROUP_KEY] = grouped.undefined; delete grouped.undefined; } - const sorted: Record = Object.keys( + const sortedEntries: [string, DataTableRowData[]][] = Object.keys( grouped ) .sort((a, b) => { + if (!groupOrder && isGroupSortColumn) { + const comparison = stringCompare( + a, + b, + this.hass.locale.language + ); + if (sortDirection === "asc") { + return comparison; + } + return comparison * -1; + } + const orderA = groupOrder?.indexOf(a) ?? -1; const orderB = groupOrder?.indexOf(b) ?? -1; if (orderA !== orderB) { @@ -735,12 +752,18 @@ export class HaDataTable extends LitElement { this.hass.locale.language ); }) - .reduce((obj, key) => { - obj[key] = grouped[key]; - return obj; - }, {}); + .reduce( + (entries, key) => { + const entry: [string, DataTableRowData[]] = [key, grouped[key]]; + + entries.push(entry); + return entries; + }, + [] as [string, DataTableRowData[]][] + ); + const groupedItems: DataTableRowData[] = []; - Object.entries(sorted).forEach(([groupName, rows]) => { + sortedEntries.forEach(([groupName, rows]) => { const collapsed = collapsedGroups.includes(groupName); groupedItems.push({ append: true, @@ -836,7 +859,9 @@ export class HaDataTable extends LitElement { this.hasFab, this.groupColumn, this.groupOrder, - this._collapsedGroups + this._collapsedGroups, + this.sortColumn, + this.sortDirection ); if (