import type { Column, Row } from '@tanstack/react-table' import { toSentenceFragment } from '@admin/utils/text/to-sentence-fragment' export interface TableRowGroup { key: string label: string indicator: 'on' | 'off' | null rows: Row[] } export function groupTableRows( rows: Row[], column: Column | undefined ): TableRowGroup[] { if (!column) return [{ key: 'all', label: '', indicator: null, rows }] const meta = column.columnDef.meta const labels = meta?.groupLabels ?? {} const groups = new Map>() for (const [key, label] of Object.entries(labels)) { groups.set(key, { key, label, indicator: key === 'true' ? 'on' : 'off', rows: [] }) } for (const row of rows) { const value = row.getValue(column.id) const key = value === null || value === undefined || value === '' ? '' : String(value) let group = groups.get(key) if (!group) { group = { key, label: key || `No ${toSentenceFragment(meta?.label ?? column.id)}`, indicator: null, rows: [] } groups.set(key, group) } group.rows.push(row) } return [...groups.values()] .filter((group) => group.rows.length > 0) .sort((a, b) => Number(a.key === '') - Number(b.key === '')) }