Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(frontend): r2-h4 complete canonical sorting

Josuéd96a461f0c34
diff --git a/control-ui/components/LlmDiscoveryPanel/index.tsx b/control-ui/components/LlmDiscoveryPanel/index.tsx
index e52d9e4c2..b0303a156 100644
--- a/control-ui/components/LlmDiscoveryPanel/index.tsx
+++ b/control-ui/components/LlmDiscoveryPanel/index.tsx
@@ -1,7 +1,7 @@
'use client'
import React, { useEffect, useMemo, useRef, useState } from 'react'
-import { DataTable } from '@clerum/frontend-table-system'
+import { DataTable, useTableSort } from '@clerum/frontend-table-system'
import { LlmProviderIcon } from '@components/LlmProviderIcon'
import { IconModels } from '@components/Sidebar/icons'
import { SkeletonTableRows } from '@components/SkeletonTableRows'
@@ -20,47 +20,13 @@ import {
updateLlmModel,
} from '@lib/api'
import { formatContextWindow, getProviderDisplayLabel } from '@lib/llm'
-import { type SortDirection, TableSortHeader, compareNullsLast, toggleSort } from '@lib/tableSort'
import type { LlmDiscoveryPanelProps } from './types'
const CONFIGMAP_DEFERRED_WARNING =
'Propagation to the cluster is delayed and will reconcile shortly.'
-type ProviderModelGroup = [provider: string, models: LlmAllowedModel[]]
-
type ReviewSortKey = 'provider' | 'model' | 'vendor' | 'contextWindow'
-// Numeric columns lead descending (largest context window first); text columns
-// lead ascending (alphabetical). Picking a different column resets to that
-// column's natural default so the operator always sees the most useful order.
-const REVIEW_SORT_DEFAULT_DIR: Record<ReviewSortKey, SortDirection> = {
- contextWindow: 'desc',
- model: 'asc',
- provider: 'asc',
- vendor: 'asc',
-}
-
-function compareReviewByKey(key: ReviewSortKey) {
- return (a: LlmAllowedModel, b: LlmAllowedModel): number => {
- switch (key) {
- case 'provider':
- return getProviderDisplayLabel(a.provider).localeCompare(
- getProviderDisplayLabel(b.provider)
- )
- case 'model':
- return a.model.localeCompare(b.model)
- case 'vendor':
- return (a.vendor ?? '').localeCompare(b.vendor ?? '')
- case 'contextWindow':
- return (a.context_window_tokens ?? 0) - (b.context_window_tokens ?? 0)
- }
- }
-}
-
-function compareReviewModel(a: LlmAllowedModel, b: LlmAllowedModel): number {
- return a.model.localeCompare(b.model)
-}
-
function modelLabel(model: LlmAllowedModel): string {
return `${getProviderDisplayLabel(model.provider)}/${model.model}`
}
@@ -71,30 +37,6 @@ function formatRunAt(value: string | null | undefined): string {
return Number.isNaN(date.getTime()) ? value : date.toLocaleString()
}
-function groupByProvider(
- models: LlmAllowedModel[],
- sortKey: ReviewSortKey | null,
- sortDir: SortDirection
-): ProviderModelGroup[] {
- const rows = [...models]
- if (sortKey) {
- const direction = sortDir === 'asc' ? 1 : -1
- const byKey = compareReviewByKey(sortKey)
- rows.sort((a, b) => {
- if (sortKey === 'contextWindow') {
- const nullOrder = compareNullsLast(a.context_window_tokens, b.context_window_tokens)
- if (nullOrder !== null) return nullOrder
- }
- const diff = byKey(a, b) * direction
- if (diff !== 0) return diff
- return compareReviewModel(a, b)
- })
- } else {
- rows.sort(compareReviewModel)
- }
- return [['_all', rows]]
-}
-
export function LlmDiscoveryPanel({
items,
loading,
@@ -110,8 +52,6 @@ export function LlmDiscoveryPanel({
const [pendingId, setPendingId] = useState<string | null>(null)
const [bulkEnabling, setBulkEnabling] = useState(false)
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
- const [sortKey, setSortKey] = useState<ReviewSortKey | null>(null)
- const [sortDir, setSortDir] = useState<SortDirection>('asc')
const statusRequestGeneration = useRef(0)
const isInitialLoad = loading && items.length === 0
@@ -119,10 +59,18 @@ export function LlmDiscoveryPanel({
() => items.filter(model => model.source === 'discovery' && !model.enabled && !model.stale),
[items]
)
- const reviewGroups = useMemo(
- () => groupByProvider(reviewQueue, sortKey, sortDir),
- [reviewQueue, sortDir, sortKey]
- )
+ const reviewSort = useTableSort<LlmAllowedModel, ReviewSortKey>({
+ rows: reviewQueue,
+ defaultKey: 'provider',
+ defaultDirections: { contextWindow: 'desc' },
+ identity: model => model.id,
+ accessors: {
+ provider: model => getProviderDisplayLabel(model.provider),
+ model: model => model.model,
+ vendor: model => model.vendor,
+ contextWindow: model => model.context_window_tokens,
+ },
+ })
const selectedCount = useMemo(
() => reviewQueue.reduce((count, model) => (selectedIds.has(model.id) ? count + 1 : count), 0),
@@ -285,19 +233,6 @@ export function LlmDiscoveryPanel({
showToast(message, { tone: 'error' })
}
- const renderSortHeader = (key: ReviewSortKey, label: string) => (
- <TableSortHeader
- activeKey={sortKey}
- defaultDirections={REVIEW_SORT_DEFAULT_DIR}
- direction={sortDir}
- label={label}
- onSort={nextKey =>
- toggleSort(nextKey, sortKey, REVIEW_SORT_DEFAULT_DIR, setSortKey, setSortDir)
- }
- sortKey={key}
- />
- )
-
const reviewColumns: TableHeaderColumn[] = [
{
key: 'select',
@@ -315,17 +250,26 @@ export function LlmDiscoveryPanel({
/>
),
},
- { key: 'provider', label: renderSortHeader('provider', 'Provider'), minWidth: '9rem' },
- { key: 'model', label: renderSortHeader('model', 'Model'), minWidth: '12rem' },
- { key: 'vendor', label: renderSortHeader('vendor', 'Vendor'), width: '10rem' },
+ { key: 'provider', label: 'Provider', minWidth: '9rem' },
+ { key: 'model', label: 'Model', minWidth: '12rem' },
+ { key: 'vendor', label: 'Vendor', width: '10rem' },
{
key: 'contextWindow',
- label: renderSortHeader('contextWindow', 'Context window'),
+ label: 'Context window',
align: 'right',
width: '9rem',
},
{ key: 'actions', width: '7rem', align: 'right', ariaLabel: 'Actions' },
- ]
+ ].map(column =>
+ column.key === 'select' || column.key === 'actions'
+ ? column
+ : {
+ ...column,
+ activeDirection: reviewSort.key === column.key ? reviewSort.direction : null,
+ defaultDirection: column.key === 'contextWindow' ? 'desc' : 'asc',
+ onSort: () => reviewSort.sortBy(column.key as ReviewSortKey),
+ }
+ )
return (
<>
@@ -430,49 +374,45 @@ export function LlmDiscoveryPanel({
<thead>
<TableHeaderRow columns={reviewColumns} />
</thead>
- {reviewGroups.map(([provider, models]) => {
- return (
- <tbody key={provider} className="cu-llm-model-group">
- {models.map(model => (
- <tr key={model.id} className="cu-table__row cu-llm-model-row">
- <td>
- <input
- type="checkbox"
- checked={selectedIds.has(model.id)}
- onChange={() => toggleRow(model.id)}
- disabled={bulkEnabling}
- aria-label={`Select ${modelLabel(model)}`}
- />
- </td>
- <td>
- <span className="cu-inline-icon-label">
- <LlmProviderIcon
- provider={model.provider}
- label={getProviderDisplayLabel(model.provider)}
- />
- {getProviderDisplayLabel(model.provider)}
- </span>
- </td>
- <td className="cu-px-model">{model.model}</td>
- <td>{model.vendor || '—'}</td>
- <td className="cu-px-num">
- {formatContextWindow(model.context_window_tokens)}
- </td>
- <td className="cu-px-actions">
- <button
- type="button"
- className="cu-btn cu-btn--primary cu-btn--sm"
- onClick={() => void handleEnable(model)}
- disabled={pendingId === model.id || bulkEnabling}
- >
- {pendingId === model.id ? 'Enabling…' : 'Enable'}
- </button>
- </td>
- </tr>
- ))}
- </tbody>
- )
- })}
+ <tbody className="cu-llm-model-group">
+ {reviewSort.sortedRows.map(model => (
+ <tr key={model.id} className="cu-table__row cu-llm-model-row">
+ <td>
+ <input
+ type="checkbox"
+ checked={selectedIds.has(model.id)}
+ onChange={() => toggleRow(model.id)}
+ disabled={bulkEnabling}
+ aria-label={`Select ${modelLabel(model)}`}
+ />
+ </td>
+ <td>
+ <span className="cu-inline-icon-label">
+ <LlmProviderIcon
+ provider={model.provider}
+ label={getProviderDisplayLabel(model.provider)}
+ />
+ {getProviderDisplayLabel(model.provider)}
+ </span>
+ </td>
+ <td className="cu-px-model">{model.model}</td>
+ <td>{model.vendor || '—'}</td>
+ <td className="cu-px-num">
+ {formatContextWindow(model.context_window_tokens)}
+ </td>
+ <td className="cu-px-actions">
+ <button
+ type="button"
+ className="cu-btn cu-btn--primary cu-btn--sm"
+ onClick={() => void handleEnable(model)}
+ disabled={pendingId === model.id || bulkEnabling}
+ >
+ {pendingId === model.id ? 'Enabling…' : 'Enable'}
+ </button>
+ </td>
+ </tr>
+ ))}
+ </tbody>
</DataTable>
</div>
)}
diff --git a/control-ui/components/LlmModelTable.tsx b/control-ui/components/LlmModelTable.tsx
index 2b315fed6..7bd40f0b2 100644
--- a/control-ui/components/LlmModelTable.tsx
+++ b/control-ui/components/LlmModelTable.tsx
@@ -1,11 +1,10 @@
'use client'
import React, { useEffect, useMemo, useState } from 'react'
-import { DataTable } from '@clerum/frontend-table-system'
+import { DataTable, useTableSort } from '@clerum/frontend-table-system'
import type { LlmAllowedModel } from '@lib/api'
import { catalogGroupKey, formatContextWindow, getProviderDisplayLabel } from '@lib/llm'
import { isUnpricedAllowedModel } from '@lib/llmModelUnpriced'
-import { type SortDirection, TableSortHeader, compareNullsLast, toggleSort } from '@lib/tableSort'
import { FilterSelect } from './FilterSelect'
import type { LlmModelTableProps } from './LlmModelTable.types'
import { LlmProviderIcon } from './LlmProviderIcon'
@@ -20,40 +19,15 @@ import { TablePanelHeader } from './TablePanelHeader'
import { IconRefresh } from './icons'
import { SelectInput } from './ui'
-type ModelSortKey = 'provider' | 'model' | 'vendor' | 'displayName' | 'contextWindow'
-
-// Natural default direction per column: numeric columns read best descending
-// (largest context window first); text columns read best ascending.
-const MODEL_SORT_DEFAULT_DIR: Record<ModelSortKey, SortDirection> = {
- contextWindow: 'desc',
- displayName: 'asc',
- model: 'asc',
- provider: 'asc',
- vendor: 'asc',
-}
-
-function compareModelByKey(key: ModelSortKey) {
- return (a: LlmAllowedModel, b: LlmAllowedModel): number => {
- switch (key) {
- case 'provider':
- return getProviderDisplayLabel(catalogGroupKey(a.provider)).localeCompare(
- getProviderDisplayLabel(catalogGroupKey(b.provider))
- )
- case 'model':
- return a.model.localeCompare(b.model)
- case 'vendor':
- return (a.vendor ?? '').localeCompare(b.vendor ?? '')
- case 'displayName':
- return (a.display_name ?? '').localeCompare(b.display_name ?? '')
- case 'contextWindow':
- return (a.context_window_tokens ?? 0) - (b.context_window_tokens ?? 0)
- }
- }
-}
-
-function compareModel(a: LlmAllowedModel, b: LlmAllowedModel): number {
- return a.model.localeCompare(b.model)
-}
+type ModelSortKey =
+ | 'provider'
+ | 'model'
+ | 'credential'
+ | 'vendor'
+ | 'displayName'
+ | 'contextWindow'
+ | 'enabled'
+ | 'source'
const ALL_PROVIDERS = '__all__'
@@ -108,8 +82,6 @@ export function LlmModelTable({
const [providerFilter, setProviderFilter] = useState<string>(ALL_PROVIDERS)
const [enabledFilter, setEnabledFilter] = useState<EnabledFilter>('all')
const [sourceFilter, setSourceFilter] = useState<SourceFilter>('all')
- const [sortKey, setSortKey] = useState<ModelSortKey | null>(null)
- const [sortDir, setSortDir] = useState<SortDirection>('asc')
const normalizedSearch = searchQuery.trim().toLowerCase()
const providerOptions = useMemo(() => {
@@ -180,7 +152,7 @@ export function LlmModelTable({
})
}, [items, normalizedSearch, providerFilter, enabledFilter, sourceFilter])
- const groupedItems = useMemo(() => {
+ const displayItems = useMemo(() => {
const groups = new Map<string, LlmAllowedModel[]>()
for (const model of filteredItems) {
const family = catalogGroupKey(model.provider)
@@ -190,25 +162,26 @@ export function LlmModelTable({
}
const collapsed: DisplayModel[] = []
for (const [family, rows] of groups.entries()) {
- const display = collapseFamilyRows(family, rows)
- if (sortKey) {
- const direction = sortDir === 'asc' ? 1 : -1
- const byKey = compareModelByKey(sortKey)
- display.sort((a, b) => {
- if (sortKey === 'contextWindow') {
- const nullOrder = compareNullsLast(a.context_window_tokens, b.context_window_tokens)
- if (nullOrder !== null) return nullOrder
- }
- const diff = byKey(a, b) * direction
- if (diff !== 0) return diff
- return compareModel(a, b)
- })
- }
- collapsed.push(...display)
+ collapsed.push(...collapseFamilyRows(family, rows))
}
- if (!sortKey) collapsed.sort(compareModel)
- return [['_all', collapsed] as [string, DisplayModel[]]]
- }, [filteredItems, sortDir, sortKey])
+ return collapsed
+ }, [filteredItems])
+ const modelSort = useTableSort<DisplayModel, ModelSortKey>({
+ rows: displayItems,
+ defaultKey: 'provider',
+ defaultDirections: { contextWindow: 'desc' },
+ identity: model => model.id,
+ accessors: {
+ provider: model => getProviderDisplayLabel(catalogGroupKey(model.provider)),
+ model: model => model.model,
+ credential: model => model.credentialLabel,
+ vendor: model => model.vendor,
+ displayName: model => model.display_name,
+ contextWindow: model => model.context_window_tokens,
+ enabled: model => model.enabled,
+ source: model => `${model.source ?? 'manual'}/${model.stale ? 'stale' : 'current'}`,
+ },
+ })
const hasActiveFilter =
Boolean(normalizedSearch) ||
@@ -222,39 +195,26 @@ export function LlmModelTable({
setProviderFilter(nextProvider)
}
- const renderSortHeader = (key: ModelSortKey, label: string) => (
- <TableSortHeader
- activeKey={sortKey}
- defaultDirections={MODEL_SORT_DEFAULT_DIR}
- direction={sortDir}
- label={label}
- onSort={nextKey =>
- toggleSort(nextKey, sortKey, MODEL_SORT_DEFAULT_DIR, setSortKey, setSortDir)
- }
- sortKey={key}
- />
- )
-
const modelColumns: TableHeaderColumn[] = [
- { key: 'provider', label: renderSortHeader('provider', 'Provider'), minWidth: '9rem' },
- { key: 'model', label: renderSortHeader('model', 'Model'), minWidth: '15rem' },
+ { key: 'provider', label: 'Provider', minWidth: '9rem' },
+ { key: 'model', label: 'Model', minWidth: '15rem' },
{ key: 'credential', label: 'Credential', width: '11rem' },
- { key: 'vendor', label: renderSortHeader('vendor', 'Vendor'), width: '10rem' },
- {
- key: 'displayName',
- label: renderSortHeader('displayName', 'Display name'),
- minWidth: '10rem',
- },
- {
- key: 'contextWindow',
- label: renderSortHeader('contextWindow', 'Context window'),
- align: 'right',
- width: '9rem',
- },
+ { key: 'vendor', label: 'Vendor', width: '10rem' },
+ { key: 'displayName', label: 'Display name', minWidth: '10rem' },
+ { key: 'contextWindow', label: 'Context window', align: 'right', width: '9rem' },
{ key: 'enabled', label: 'Enabled', width: '6rem' },
{ key: 'source', label: 'Source', width: '7rem' },
{ key: 'actions', width: '5rem', align: 'right', ariaLabel: 'Actions' },
- ]
+ ].map(column =>
+ column.key === 'actions'
+ ? column
+ : {
+ ...column,
+ activeDirection: modelSort.key === column.key ? modelSort.direction : null,
+ defaultDirection: column.key === 'contextWindow' ? 'desc' : 'asc',
+ onSort: () => modelSort.sortBy(column.key as ModelSortKey),
+ }
+ )
return (
<div className="cu-card cu-card--viewport-fill cu-section-card">
@@ -353,124 +313,118 @@ export function LlmModelTable({
<thead>
<TableHeaderRow columns={modelColumns} />
</thead>
- {groupedItems.map(([provider, models]) => {
- return (
- <tbody key={provider} className="cu-llm-model-group">
- {models.map((model: DisplayModel) => (
- <tr key={model.id} className="cu-table__row cu-llm-model-row">
- <td>
- <span className="cu-inline-icon-label">
- <LlmProviderIcon
- provider={catalogGroupKey(model.provider)}
- label={getProviderDisplayLabel(catalogGroupKey(model.provider))}
- />
- {getProviderDisplayLabel(catalogGroupKey(model.provider))}
- </span>
- </td>
- <td className="cu-px-model">
- <span className="cu-px-model-content">
- {model.model}
- {isUnpricedAllowedModel(model, unpricedKeys) ? (
- <MissingPriceWarning provider={model.provider} model={model.model} />
- ) : null}
- </span>
- </td>
- <td>{model.credentialLabel || '—'}</td>
- <td>{model.vendor || '—'}</td>
- <td>{model.display_name || '—'}</td>
- <td className="cu-px-num">
- {formatContextWindow(model.context_window_tokens)}
- </td>
- <td>
- <span
- className={
- model.enabled
- ? 'cu-px-badge cu-px-badge--on'
- : 'cu-px-badge cu-px-badge--off'
- }
- >
- {model.enabled ? 'Enabled' : 'Disabled'}
- </span>
- </td>
- <td>
+ <tbody className="cu-llm-model-group">
+ {modelSort.sortedRows.map((model: DisplayModel) => (
+ <tr key={model.id} className="cu-table__row cu-llm-model-row">
+ <td>
+ <span className="cu-inline-icon-label">
+ <LlmProviderIcon
+ provider={catalogGroupKey(model.provider)}
+ label={getProviderDisplayLabel(catalogGroupKey(model.provider))}
+ />
+ {getProviderDisplayLabel(catalogGroupKey(model.provider))}
+ </span>
+ </td>
+ <td className="cu-px-model">
+ <span className="cu-px-model-content">
+ {model.model}
+ {isUnpricedAllowedModel(model, unpricedKeys) ? (
+ <MissingPriceWarning provider={model.provider} model={model.model} />
+ ) : null}
+ </span>
+ </td>
+ <td>{model.credentialLabel || '—'}</td>
+ <td>{model.vendor || '—'}</td>
+ <td>{model.display_name || '—'}</td>
+ <td className="cu-px-num">{formatContextWindow(model.context_window_tokens)}</td>
+ <td>
+ <span
+ className={
+ model.enabled
+ ? 'cu-px-badge cu-px-badge--on'
+ : 'cu-px-badge cu-px-badge--off'
+ }
+ >
+ {model.enabled ? 'Enabled' : 'Disabled'}
+ </span>
+ </td>
+ <td>
+ <>
+ <span
+ className={
+ model.source === 'discovery'
+ ? 'cu-px-badge cu-px-badge--info'
+ : 'cu-px-badge cu-px-badge--off'
+ }
+ >
+ {model.source === 'discovery' ? 'Discovered' : 'Manual'}
+ </span>
+ {model.stale ? (
<>
- <span
- className={
- model.source === 'discovery'
- ? 'cu-px-badge cu-px-badge--info'
- : 'cu-px-badge cu-px-badge--off'
- }
- >
- {model.source === 'discovery' ? 'Discovered' : 'Manual'}
- </span>
- {model.stale ? (
- <>
- {' '}
- <span className="cu-px-badge cu-px-badge--warn">Stale</span>
- </>
- ) : null}
+ {' '}
+ <span className="cu-px-badge cu-px-badge--warn">Stale</span>
</>
- </td>
- <td className="cu-px-actions">
- <RowActionsMenu
- ariaLabel={`Actions for model ${model.provider}/${model.model}`}
- horizontalTrigger
- actions={
- model.apiKeyRow && model.subscriptionRow
- ? [
- {
- key: 'edit-api-key',
- label: 'Edit API key',
- onClick: () => onEdit(model.apiKeyRow!.id),
- },
- {
- key: 'edit-subscription',
- label: 'Edit subscription',
- onClick: () => onEdit(model.subscriptionRow!.id),
- },
- {
- key: 'delete-api-key',
- label:
- deletingId === model.apiKeyRow.id
- ? 'Deleting…'
- : 'Delete API key',
- danger: true,
- disabled: deletingId === model.apiKeyRow.id,
- onClick: () => void onDelete(model.apiKeyRow!),
- },
- {
- key: 'delete-subscription',
- label:
- deletingId === model.subscriptionRow.id
- ? 'Deleting…'
- : 'Delete subscription',
- danger: true,
- disabled: deletingId === model.subscriptionRow.id,
- onClick: () => void onDelete(model.subscriptionRow!),
- },
- ]
- : [
- {
- key: 'edit',
- label: 'Edit',
- onClick: () => onEdit(model.id),
- },
- {
- key: 'delete',
- label: deletingId === model.id ? 'Deleting…' : 'Delete',
- danger: true,
- disabled: deletingId === model.id,
- onClick: () => void onDelete(model),
- },
- ]
- }
- />
- </td>
- </tr>
- ))}
- </tbody>
- )
- })}
+ ) : null}
+ </>
+ </td>
+ <td className="cu-px-actions">
+ <RowActionsMenu
+ ariaLabel={`Actions for model ${model.provider}/${model.model}`}
+ horizontalTrigger
+ actions={
+ model.apiKeyRow && model.subscriptionRow
+ ? [
+ {
+ key: 'edit-api-key',
+ label: 'Edit API key',
+ onClick: () => onEdit(model.apiKeyRow!.id),
+ },
+ {
+ key: 'edit-subscription',
+ label: 'Edit subscription',
+ onClick: () => onEdit(model.subscriptionRow!.id),
+ },
+ {
+ key: 'delete-api-key',
+ label:
+ deletingId === model.apiKeyRow.id
+ ? 'Deleting…'
+ : 'Delete API key',
+ danger: true,
+ disabled: deletingId === model.apiKeyRow.id,
+ onClick: () => void onDelete(model.apiKeyRow!),
+ },
+ {
+ key: 'delete-subscription',
+ label:
+ deletingId === model.subscriptionRow.id
+ ? 'Deleting…'
+ : 'Delete subscription',
+ danger: true,
+ disabled: deletingId === model.subscriptionRow.id,
+ onClick: () => void onDelete(model.subscriptionRow!),
+ },
+ ]
+ : [
+ {
+ key: 'edit',
+ label: 'Edit',
+ onClick: () => onEdit(model.id),
+ },
+ {
+ key: 'delete',
+ label: deletingId === model.id ? 'Deleting…' : 'Delete',
+ danger: true,
+ disabled: deletingId === model.id,
+ onClick: () => void onDelete(model),
+ },
+ ]
+ }
+ />
+ </td>
+ </tr>
+ ))}
+ </tbody>
</DataTable>
</div>
)}
diff --git a/control-ui/components/ProfileAdminHome.tsx b/control-ui/components/ProfileAdminHome.tsx
index 367f08658..4e37988ca 100644
--- a/control-ui/components/ProfileAdminHome.tsx
+++ b/control-ui/components/ProfileAdminHome.tsx
@@ -2,7 +2,7 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
-import { DataTable, TableRow } from '@clerum/frontend-table-system'
+import { DataTable, TableRow, useTableSort } from '@clerum/frontend-table-system'
import { CONTROL_ROUTES } from '@constants/routes'
import {
AdminPendingInvitationListItem,
@@ -29,12 +29,15 @@ import { SectionSearchInput } from './SectionSearchInput'
import { IconShield, IconUsers } from './Sidebar/icons'
import { SkeletonTableRows } from './SkeletonTableRows'
import { TabBar } from './TabBar'
+import { TableHeaderRow } from './TableHeaderRow'
+import type { TableHeaderColumn } from './TableHeaderRow/types'
import { TablePanelHeader } from './TablePanelHeader'
import { useToast } from './Toast'
import { IconAlertTriangle, IconRefresh, IconX } from './icons'
import { CheckboxField } from './ui'
-type TeamSortKey = 'members' | 'agents' | 'contexts'
+type TeamSortKey = 'name' | 'members' | 'agents' | 'contexts'
+type MemberSortKey = 'name' | 'email' | 'teams'
export function ProfileAdminHome({ activeTab, highlightedAdminId = '' }: ProfileAdminHomeProps) {
const router = useRouter()
@@ -50,9 +53,6 @@ export function ProfileAdminHome({ activeTab, highlightedAdminId = '' }: Profile
const [adminLoading, setAdminLoading] = useState(false)
const [adminCounts, setAdminCounts] = useState({ admins: 0, invitations: 0 })
const [filteredTeams, setFilteredTeams] = useState<TeamListItem[]>([])
- const [teamSortKey, setTeamSortKey] = useState<TeamSortKey>('members')
- const [teamSortDir, setTeamSortDir] = useState<'asc' | 'desc'>('desc')
- const [memberTeamsSortDir, setMemberTeamsSortDir] = useState<'asc' | 'desc'>('desc')
const [teamToDelete, setTeamToDelete] = useState<TeamListItem | null>(null)
const [userToDelete, setUserToDelete] = useState<AdminUser | null>(null)
@@ -181,43 +181,66 @@ export function ProfileAdminHome({ activeTab, highlightedAdminId = '' }: Profile
})
}, [pendingInvitations, searchInput, users])
- const sortedTeams = useMemo(() => {
- const sorted = [...filteredTeams]
- const direction = teamSortDir === 'asc' ? 1 : -1
- sorted.sort((a, b) => {
- let countDiff = 0
- if (teamSortKey === 'members') {
- countDiff = a.memberCount - b.memberCount
- } else if (teamSortKey === 'agents') {
- countDiff = (teamAgentCounts[a.id] ?? 0) - (teamAgentCounts[b.id] ?? 0)
- } else {
- countDiff = (teamContextCounts[a.id] ?? 0) - (teamContextCounts[b.id] ?? 0)
- }
- countDiff *= direction
- if (countDiff !== 0) return countDiff
- return a.name.localeCompare(b.name)
- })
- return sorted
- }, [filteredTeams, teamAgentCounts, teamContextCounts, teamSortDir, teamSortKey])
-
- const sortedUsers = useMemo(() => {
- const sorted = [...visibleUsers]
- const direction = memberTeamsSortDir === 'asc' ? 1 : -1
- sorted.sort((a, b) => {
- const countDiff = ((a.activeTeamCount || 0) - (b.activeTeamCount || 0)) * direction
- if (countDiff !== 0) return countDiff
- const aLabel = a.displayName || a.name || a.email
- const bLabel = b.displayName || b.name || b.email
- return aLabel.localeCompare(bLabel)
- })
- return sorted
- }, [visibleUsers, memberTeamsSortDir])
+ const teamSort = useTableSort<TeamListItem, TeamSortKey>({
+ rows: filteredTeams,
+ defaultKey: 'name',
+ defaultDirections: { agents: 'desc', contexts: 'desc', members: 'desc' },
+ identity: team => team.id,
+ accessors: {
+ name: team => team.name,
+ members: team => team.memberCount,
+ agents: team => teamAgentCounts[team.id] ?? 0,
+ contexts: team => teamContextCounts[team.id] ?? 0,
+ },
+ })
+ const memberSort = useTableSort<AdminUser, MemberSortKey>({
+ rows: visibleUsers,
+ defaultKey: 'name',
+ defaultDirections: { teams: 'desc' },
+ identity: user => user.id,
+ accessors: {
+ name: user => user.displayName || user.name || user.email,
+ email: user => user.email,
+ teams: user => user.activeTeamCount || 0,
+ },
+ })
const membersTabLabel =
activeTab === 'users'
? `Members (${visibleUsers.length}${pendingInvitations.length ? `, ${pendingInvitations.length} pending` : ''})`
: 'Members'
const teamsTabLabel = activeTab === 'teams' ? `Teams (${teams.length})` : 'Teams'
+ const teamColumns: TableHeaderColumn[] = [
+ { key: 'name', label: 'Team name' },
+ { key: 'members', label: 'Members', width: '5rem', align: 'right' },
+ { key: 'agents', label: 'Agents', width: '5rem', align: 'right' },
+ { key: 'contexts', label: 'Contexts', width: '5rem', align: 'right' },
+ { key: 'actions', width: '4.5rem', align: 'right', ariaLabel: 'Actions' },
+ ].map(column =>
+ column.key === 'actions'
+ ? column
+ : {
+ ...column,
+ activeDirection: teamSort.key === column.key ? teamSort.direction : null,
+ defaultDirection: column.key === 'name' ? 'asc' : 'desc',
+ onSort: () => teamSort.sortBy(column.key as TeamSortKey),
+ }
+ )
+ const memberColumns: TableHeaderColumn[] = [
+ { key: 'name', label: 'Name' },
+ { key: 'email', label: 'Email' },
+ { key: 'teams', label: 'Teams', width: '7rem', align: 'right' },
+ { key: 'actions', width: '4.5rem', align: 'right', ariaLabel: 'Actions' },
+ ].map(column =>
+ column.key === 'actions'
+ ? column
+ : {
+ ...column,
+ activeDirection: memberSort.key === column.key ? memberSort.direction : null,
+ defaultDirection: column.key === 'teams' ? 'desc' : 'asc',
+ onSort: () => memberSort.sortBy(column.key as MemberSortKey),
+ }
+ )
const adminsTabLabel =
activeTab === 'admins'
? `Admins (${adminCounts.admins}${
@@ -248,34 +271,6 @@ export function ProfileAdminHome({ activeTab, highlightedAdminId = '' }: Profile
router.push(CONTROL_ROUTES.usersAndTeams.newAdmin(Object.fromEntries(searchParams)))
}
- function toggleTeamSort(nextKey: TeamSortKey) {
- if (teamSortKey === nextKey) {
- setTeamSortDir(prev => (prev === 'asc' ? 'desc' : 'asc'))
- return
- }
- setTeamSortKey(nextKey)
- setTeamSortDir('desc')
- }
-
- function renderTeamSortButton(key: TeamSortKey, label: string) {
- const isActive = teamSortKey === key
- const indicator = isActive ? (teamSortDir === 'asc' ? '↑' : '↓') : ''
- const sortDirectionLabel =
- isActive && teamSortDir === 'asc' ? 'descending' : isActive ? 'ascending' : 'descending'
- return (
- <button
- type="button"
- className="cu-link cu-link--sm"
- style={{ color: 'var(--cu-text-muted)', whiteSpace: 'nowrap' }}
- onClick={() => toggleTeamSort(key)}
- aria-label={`Sort by ${label.toLowerCase()} ${sortDirectionLabel}`}
- >
- {label}
- {indicator ? ` ${indicator}` : ''}
- </button>
- )
- }
-
async function resendPendingInvitation(invitation: AdminPendingInvitationListItem) {
setResendingInvitationId(invitation.id)
setError('')
@@ -578,19 +573,7 @@ export function ProfileAdminHome({ activeTab, highlightedAdminId = '' }: Profile
<div className="eft-table-viewport cu-table-wrap">
<DataTable className="eft-table cu-table cu-table--profile cu-table--header-band">
<thead>
- <tr>
- <th>Team name</th>
- <th style={{ width: '5rem', textAlign: 'right' }}>
- {renderTeamSortButton('members', 'Members')}
- </th>
- <th style={{ width: '5rem', textAlign: 'right' }}>
- {renderTeamSortButton('agents', 'Agents')}
- </th>
- <th style={{ width: '5rem', textAlign: 'right' }}>
- {renderTeamSortButton('contexts', 'Contexts')}
- </th>
- <th style={{ width: '4.5rem', textAlign: 'right' }} aria-label="Actions" />
- </tr>
+ <TableHeaderRow columns={teamColumns} />
</thead>
<tbody>
<SkeletonTableRows columns={5} rows={5} />
@@ -605,22 +588,10 @@ export function ProfileAdminHome({ activeTab, highlightedAdminId = '' }: Profile
<div className="eft-table-viewport cu-table-wrap">
<DataTable className="eft-table cu-table cu-table--profile cu-table--header-band">
<thead>
- <tr>
- <th>Team name</th>
- <th style={{ width: '5rem', textAlign: 'right' }}>
- {renderTeamSortButton('members', 'Members')}
- </th>
- <th style={{ width: '5rem', textAlign: 'right' }}>
- {renderTeamSortButton('agents', 'Agents')}
- </th>
- <th style={{ width: '5rem', textAlign: 'right' }}>
- {renderTeamSortButton('contexts', 'Contexts')}
- </th>
- <th style={{ width: '4.5rem', textAlign: 'right' }} aria-label="Actions" />
- </tr>
+ <TableHeaderRow columns={teamColumns} />
</thead>
<tbody>
- {sortedTeams.map(team => (
+ {teamSort.sortedRows.map(team => (
<TableRow
key={team.id}
className="cu-table__row cu-table__row--clickable"
@@ -703,24 +674,7 @@ export function ProfileAdminHome({ activeTab, highlightedAdminId = '' }: Profile
<div className="eft-table-viewport cu-table-wrap">
<DataTable className="eft-table cu-table cu-table--profile cu-table--header-band">
<thead>
- <tr>
- <th>Name</th>
- <th>Email</th>
- <th style={{ width: '5rem', textAlign: 'right' }}>
- <button
- type="button"
- className="cu-link cu-link--sm"
- style={{ color: 'var(--cu-text-muted)', whiteSpace: 'nowrap' }}
- onClick={() =>
- setMemberTeamsSortDir(prev => (prev === 'asc' ? 'desc' : 'asc'))
- }
- aria-label={`Sort by team count ${memberTeamsSortDir === 'asc' ? 'descending' : 'ascending'}`}
- >
- Teams {memberTeamsSortDir === 'asc' ? '↑' : '↓'}
- </button>
- </th>
- <th style={{ width: '4.5rem', textAlign: 'right' }} aria-label="Actions" />
- </tr>
+ <TableHeaderRow columns={memberColumns} />
</thead>
<tbody>
<SkeletonTableRows columns={4} rows={5} />
@@ -834,26 +788,10 @@ export function ProfileAdminHome({ activeTab, highlightedAdminId = '' }: Profile
<div className="eft-table-viewport cu-table-wrap">
<DataTable className="eft-table cu-table cu-table--profile cu-table--header-band">
<thead>
- <tr>
- <th>Name</th>
- <th>Email</th>
- <th className="cu-table__col-count">
- <button
- type="button"
- className="cu-table__sort-link"
- onClick={() =>
- setMemberTeamsSortDir(prev => (prev === 'asc' ? 'desc' : 'asc'))
- }
- aria-label={`Sort by team count ${memberTeamsSortDir === 'asc' ? 'descending' : 'ascending'}`}
- >
- Teams {memberTeamsSortDir === 'asc' ? '↑' : '↓'}
- </button>
- </th>
- <th className="cu-table__col-actions-wide" aria-label="Actions" />
- </tr>
+ <TableHeaderRow columns={memberColumns} />
</thead>
<tbody>
- {sortedUsers.map(user => (
+ {memberSort.sortedRows.map(user => (
<TableRow
key={user.id}
className="cu-table__row cu-table__row--clickable"
diff --git a/control-ui/components/RegistryCatalog.tsx b/control-ui/components/RegistryCatalog.tsx
index e4addb34a..5982680ef 100644
--- a/control-ui/components/RegistryCatalog.tsx
+++ b/control-ui/components/RegistryCatalog.tsx
@@ -88,6 +88,7 @@ export default function RegistryCatalog() {
return {
...column,
activeDirection: sortKey === column.key ? sortDirection : null,
+ defaultDirection: column.key === 'version' ? 'desc' : 'asc',
onSort: () => toggleSort(column.key as CatalogSortKey),
}
}
diff --git a/control-ui/components/TableHeaderRow/index.tsx b/control-ui/components/TableHeaderRow/index.tsx
index e57a9db9d..5cfe57d92 100644
--- a/control-ui/components/TableHeaderRow/index.tsx
+++ b/control-ui/components/TableHeaderRow/index.tsx
@@ -13,6 +13,7 @@ export function TableHeaderRow({ columns }: { columns: TableHeaderColumn[] }) {
title={column.title}
label={column.label}
activeDirection={column.activeDirection}
+ defaultDirection={column.defaultDirection}
onSort={column.onSort}
sortLabel={column.sortLabel}
style={{
diff --git a/control-ui/components/TableHeaderRow/types.ts b/control-ui/components/TableHeaderRow/types.ts
index 41b290ce0..52ab4bd9f 100644
--- a/control-ui/components/TableHeaderRow/types.ts
+++ b/control-ui/components/TableHeaderRow/types.ts
@@ -10,6 +10,7 @@ export type TableHeaderColumn = {
title?: string
width?: string
activeDirection?: SortDirection | null
+ defaultDirection?: SortDirection
onSort?: () => void
sortLabel?: ReactNode
}
diff --git a/control-ui/components/__tests__/FrontendTableSystem.test.tsx b/control-ui/components/__tests__/FrontendTableSystem.test.tsx
index 2d6889291..134d3244f 100644
--- a/control-ui/components/__tests__/FrontendTableSystem.test.tsx
+++ b/control-ui/components/__tests__/FrontendTableSystem.test.tsx
@@ -41,6 +41,14 @@ describe('shared frontend table system', () => {
row => row.id
).map(row => row.id)
).toEqual(['a', 'b', 'c'])
+ expect(
+ stableSortRows(
+ rows,
+ row => row.name,
+ 'desc',
+ row => row.id
+ ).map(row => row.id)
+ ).toEqual(['a', 'b', 'c'])
})
it('supports pointer and keyboard row navigation without hijacking child actions', () => {
diff --git a/control-ui/components/__tests__/LlmDiscoveryPanel.test.tsx b/control-ui/components/__tests__/LlmDiscoveryPanel.test.tsx
index 35eb4c7c4..397ca0f2a 100644
--- a/control-ui/components/__tests__/LlmDiscoveryPanel.test.tsx
+++ b/control-ui/components/__tests__/LlmDiscoveryPanel.test.tsx
@@ -199,7 +199,7 @@ describe('LlmDiscoveryPanel sorting', () => {
)
expandOpenAi()
- fireEvent.click(screen.getByRole('button', { name: 'Sort by model ascending' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by Model ascending' }))
expect(rowOrder()).toEqual(['alpha', 'bravo', 'charlie'])
})
@@ -217,7 +217,7 @@ describe('LlmDiscoveryPanel sorting', () => {
)
expandOpenAi()
- fireEvent.click(screen.getByRole('button', { name: 'Sort by context window descending' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by Context window descending' }))
expect(rowOrder()).toEqual(['large', 'small', 'unknown'])
})
diff --git a/control-ui/components/__tests__/LlmModelTable.test.tsx b/control-ui/components/__tests__/LlmModelTable.test.tsx
index 3a152ee03..c64f0f7f8 100644
--- a/control-ui/components/__tests__/LlmModelTable.test.tsx
+++ b/control-ui/components/__tests__/LlmModelTable.test.tsx
@@ -392,7 +392,7 @@ describe('LlmModelTable sorting', () => {
renderTable([charlie, alpha, bravo])
expandAnthropicModels()
- fireEvent.click(screen.getByRole('button', { name: 'Sort by model ascending' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by Model ascending' }))
expect(expandedRowOrder()).toEqual(['alpha', 'bravo', 'charlie'])
})
@@ -403,11 +403,11 @@ describe('LlmModelTable sorting', () => {
renderTable([alpha, bravo])
expandAnthropicModels()
- const modelSort = screen.getByRole('button', { name: 'Sort by model ascending' })
+ const modelSort = screen.getByRole('button', { name: 'Sort by Model ascending' })
fireEvent.click(modelSort)
expect(expandedRowOrder()).toEqual(['alpha', 'bravo'])
- fireEvent.click(screen.getByRole('button', { name: 'Sort by model descending' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by Model descending' }))
expect(expandedRowOrder()).toEqual(['bravo', 'alpha'])
})
@@ -418,7 +418,7 @@ describe('LlmModelTable sorting', () => {
renderTable([small, large, unknown])
expandAnthropicModels()
- fireEvent.click(screen.getByRole('button', { name: 'Sort by context window descending' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by Context window descending' }))
expect(expandedRowOrder()).toEqual(['large', 'small', 'unknown'])
})
@@ -430,12 +430,12 @@ describe('LlmModelTable sorting', () => {
expandAnthropicModels()
// Model asc (default for text columns).
- fireEvent.click(screen.getByRole('button', { name: 'Sort by model ascending' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by Model ascending' }))
expect(expandedRowOrder()).toEqual(['alpha', 'bravo'])
// Switching to context window uses its natural default (descending) — not
// the previous direction — so the operator gets the most useful ordering.
- fireEvent.click(screen.getByRole('button', { name: 'Sort by context window descending' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by Context window descending' }))
expect(expandedRowOrder()).toEqual(['bravo', 'alpha'])
})
})
diff --git a/control-ui/components/__tests__/RegistryCatalog.test.tsx b/control-ui/components/__tests__/RegistryCatalog.test.tsx
index 087af44ce..84b0ad85c 100644
--- a/control-ui/components/__tests__/RegistryCatalog.test.tsx
+++ b/control-ui/components/__tests__/RegistryCatalog.test.tsx
@@ -232,7 +232,7 @@ describe('RegistryCatalog tabs and columns', () => {
'ascending'
)
- fireEvent.click(screen.getByRole('button', { name: 'Sort by Version ascending' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Sort by Version descending' }))
expect(listedNames()).toEqual(['alpha-search', 'zebra-search', 'brave-search'])
fireEvent.click(screen.getByRole('button', { name: 'Sort by Version ascending' }))
diff --git a/control-ui/lib/__tests__/tableSort.test.ts b/control-ui/lib/__tests__/tableSort.test.ts
deleted file mode 100644
index eee34b62e..000000000
--- a/control-ui/lib/__tests__/tableSort.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import fc from 'fast-check'
-import { compareNullsLast } from '../tableSort'
-
-function permutations<T>(items: readonly T[]): T[][] {
- if (items.length <= 1) return [[...items]]
- return items.flatMap((item, index) =>
- permutations([...items.slice(0, index), ...items.slice(index + 1)]).map(rest => [item, ...rest])
- )
-}
-
-function sortNumbersNullLast(values: Array<number | null | undefined>, direction: 'asc' | 'desc') {
- const multiplier = direction === 'asc' ? 1 : -1
- return [...values].sort((left, right) => {
- const nullOrder = compareNullsLast(left, right)
- return nullOrder ?? ((left as number) - (right as number)) * multiplier
- })
-}
-
-const nullableInteger = fc.oneof(fc.integer(), fc.constant(null), fc.constant(undefined))
-
-function multiset(values: Array<number | null | undefined>) {
- const counts = new Map<string, number>()
- for (const value of values) {
- const key = value === null ? 'null' : value === undefined ? 'undefined' : `number:${value}`
- counts.set(key, (counts.get(key) ?? 0) + 1)
- }
- return [...counts.entries()].sort(([left], [right]) => left.localeCompare(right))
-}
-
-describe('compareNullsLast invariants', () => {
- const values = [7, null, 2, undefined, 5]
-
- it('keeps nullish values last in both directions without losing values', () => {
- expect(sortNumbersNullLast(values, 'asc')).toEqual([2, 5, 7, null, undefined])
- expect(sortNumbersNullLast(values, 'desc')).toEqual([7, 5, 2, null, undefined])
- })
-
- it('produces the same ordered non-null projection for every input permutation', () => {
- for (const order of permutations([7, null, 2, 5])) {
- expect(sortNumbersNullLast(order, 'asc')).toEqual([2, 5, 7, null])
- expect(sortNumbersNullLast(order, 'desc')).toEqual([7, 5, 2, null])
- }
- })
-
- it('is antisymmetric for null ordering and neutral for two nullish values', () => {
- expect(compareNullsLast(null, 1)).toBe(-compareNullsLast(1, null)!)
- expect(compareNullsLast(null, undefined)).toBe(0)
- expect(compareNullsLast(1, 2)).toBeNull()
- })
-
- it('keeps arbitrary nullish values last while preserving and idempotently sorting the multiset', () => {
- fc.assert(
- fc.property(fc.array(nullableInteger, { maxLength: 100 }), values => {
- for (const direction of ['asc', 'desc'] as const) {
- const sorted = sortNumbersNullLast(values, direction)
- const firstNullish = sorted.findIndex(value => value == null)
-
- expect(firstNullish < 0 || sorted.slice(firstNullish).every(value => value == null)).toBe(
- true
- )
- expect(multiset(sorted)).toEqual(multiset(values))
- expect(sortNumbersNullLast(sorted, direction)).toEqual(sorted)
- expect(sortNumbersNullLast(values, direction)).toEqual(sorted)
- }
- })
- )
- })
-
- it('has a permutation-stable non-null projection for arbitrary arrays', () => {
- fc.assert(
- fc.property(
- fc
- .array(nullableInteger, { maxLength: 50 })
- .chain(values =>
- fc
- .shuffledSubarray(values, { minLength: values.length, maxLength: values.length })
- .map(shuffled => ({ values, shuffled }))
- ),
- ({ values, shuffled }) => {
- for (const direction of ['asc', 'desc'] as const) {
- const project = (input: Array<number | null | undefined>) =>
- sortNumbersNullLast(input, direction).filter(
- (value): value is number => value != null
- )
- expect(project(shuffled)).toEqual(project(values))
- }
- }
- )
- )
- })
-
- it('obeys the null-delegation and antisymmetry contract for arbitrary pairs', () => {
- fc.assert(
- fc.property(nullableInteger, nullableInteger, (left, right) => {
- const comparison = compareNullsLast(left, right)
- const reverse = compareNullsLast(right, left)
- if (left == null && right == null) {
- expect(comparison).toBe(0)
- } else if (left != null && right != null) {
- expect(comparison).toBeNull()
- expect(reverse).toBeNull()
- } else {
- expect(comparison).toBe(-reverse!)
- }
- })
- )
- })
-})
diff --git a/control-ui/lib/tableSort.tsx b/control-ui/lib/tableSort.tsx
deleted file mode 100644
index 1467da32c..000000000
--- a/control-ui/lib/tableSort.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import type { Dispatch, SetStateAction } from 'react'
-import type { SortDirection, TableSortHeaderProps } from './tableSort.types'
-
-export type { SortDirection } from './tableSort.types'
-
-export function compareNullsLast(
- left: number | null | undefined,
- right: number | null | undefined
-): number | null {
- if (left == null && right == null) return 0
- if (left == null) return 1
- if (right == null) return -1
- return null
-}
-
-export function toggleSort<TKey extends string>(
- key: TKey,
- currentKey: TKey | null,
- defaultDirections: Record<TKey, SortDirection>,
- setKey: Dispatch<SetStateAction<TKey | null>>,
- setDirection: Dispatch<SetStateAction<SortDirection>>
-) {
- if (currentKey === key) {
- setDirection(current => (current === 'asc' ? 'desc' : 'asc'))
- return
- }
- setKey(key)
- setDirection(defaultDirections[key])
-}
-
-export function TableSortHeader<TKey extends string>({
- activeKey,
- defaultDirections,
- direction,
- label,
- onSort,
- sortKey,
-}: TableSortHeaderProps<TKey>) {
- const isActive = activeKey === sortKey
- const indicator = isActive ? (direction === 'asc' ? '↑' : '↓') : ''
- const nextDirection = isActive
- ? direction === 'asc'
- ? 'descending'
- : 'ascending'
- : defaultDirections[sortKey] === 'asc'
- ? 'ascending'
- : 'descending'
-
- return (
- <button
- type="button"
- className={`cu-link cu-link--sm cu-table__sort-link${isActive ? ' is-active' : ''}`}
- onClick={() => onSort(sortKey)}
- aria-label={`Sort by ${label.toLowerCase()} ${nextDirection}`}
- aria-pressed={isActive}
- >
- {label}
- {indicator ? ` ${indicator}` : ''}
- </button>
- )
-}
diff --git a/control-ui/lib/tableSort.types.ts b/control-ui/lib/tableSort.types.ts
deleted file mode 100644
index 5e5322379..000000000
--- a/control-ui/lib/tableSort.types.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-export type SortDirection = 'asc' | 'desc'
-
-export type TableSortHeaderProps<TKey extends string> = {
- activeKey: TKey | null
- defaultDirections: Record<TKey, SortDirection>
- direction: SortDirection
- label: string
- onSort: (key: TKey) => void
- sortKey: TKey
-}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 08b386750..6104d68a7 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.492",
+ "version": "0.1.493",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.492",
+ "version": "0.1.493",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-table-system": "file:../packages/frontend-table-system",
diff --git a/control-ui/package.json b/control-ui/package.json
index c544ad35e..87bb82ece 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.492",
+ "version": "0.1.493",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/packages/frontend-table-system/src/index.tsx b/packages/frontend-table-system/src/index.tsx
index eba65978b..74e4550ee 100644
--- a/packages/frontend-table-system/src/index.tsx
+++ b/packages/frontend-table-system/src/index.tsx
@@ -164,6 +164,7 @@ export function TableCell({
export function TableHeaderCell({
activeDirection,
className,
+ defaultDirection = 'asc',
kind = 'text',
label,
onSort,
@@ -171,6 +172,7 @@ export function TableHeaderCell({
...props
}: Omit<ThHTMLAttributes<HTMLTableCellElement>, 'children'> & {
activeDirection?: SortDirection | null
+ defaultDirection?: SortDirection
kind?: CellKind
label: ReactNode
onSort?: () => void
@@ -183,7 +185,13 @@ export function TableHeaderCell({
: onSort
? 'none'
: undefined
- const nextDirection = activeDirection === 'asc' ? 'descending' : 'ascending'
+ const nextDirection = activeDirection
+ ? activeDirection === 'asc'
+ ? 'descending'
+ : 'ascending'
+ : defaultDirection === 'asc'
+ ? 'ascending'
+ : 'descending'
const accessibleSortLabel = String(sortLabel ?? label)
return (
<th
@@ -428,7 +436,11 @@ export function stableSortRows<TRow>(
return rows
.map((row, index) => ({ index, row }))
.sort((left, right) => {
- const primary = compareSortValues(value(left.row), value(right.row)) * multiplier
+ const leftValue = value(left.row)
+ const rightValue = value(right.row)
+ if (leftValue == null) return rightValue == null ? 0 : 1
+ if (rightValue == null) return -1
+ const primary = compareSortValues(leftValue, rightValue) * multiplier
if (primary !== 0) return primary
const secondary = compareSortValues(identity(left.row), identity(right.row))
return secondary || left.index - right.index
@@ -439,18 +451,22 @@ export function stableSortRows<TRow>(
export function useTableSort<TRow, TKey extends string>({
accessors,
defaultDirection = 'asc',
+ defaultDirections,
defaultKey,
identity,
rows,
}: {
accessors: Record<TKey, (row: TRow) => SortValue>
defaultDirection?: SortDirection
+ defaultDirections?: Partial<Record<TKey, SortDirection>>
defaultKey: TKey
identity: (row: TRow) => SortValue
rows: readonly TRow[]
}) {
const [key, setKey] = useState<TKey>(defaultKey)
- const [direction, setDirection] = useState<SortDirection>(defaultDirection)
+ const [direction, setDirection] = useState<SortDirection>(
+ defaultDirections?.[defaultKey] ?? defaultDirection
+ )
const sortedRows = useMemo(
() => stableSortRows(rows, accessors[key], direction, identity),
[accessors, direction, identity, key, rows]
@@ -459,7 +475,7 @@ export function useTableSort<TRow, TKey extends string>({
if (nextKey === key) setDirection(current => (current === 'asc' ? 'desc' : 'asc'))
else {
setKey(nextKey)
- setDirection('asc')
+ setDirection(defaultDirections?.[nextKey] ?? 'asc')
}
}
return { direction, key, setDirection, setKey, sortBy, sortedRows }
diff --git a/scripts/style-rules/rules.test.mjs b/scripts/style-rules/rules.test.mjs
index 4524dab23..a97c9141c 100644
--- a/scripts/style-rules/rules.test.mjs
+++ b/scripts/style-rules/rules.test.mjs
@@ -81,9 +81,12 @@ test('ordinary web record tables keep an explicit sorting model', () => {
'control-ui/components/CommunicationChannelsTable.tsx',
'control-ui/components/ControlAdminsPanel/index.tsx',
'control-ui/components/GuardrailHooksTable.tsx',
+ 'control-ui/components/LlmDiscoveryPanel/index.tsx',
+ 'control-ui/components/LlmModelTable.tsx',
'control-ui/components/LlmPriceTable.tsx',
'control-ui/components/MarketplaceOrgImages/index.tsx',
'control-ui/components/McpServerTable.tsx',
+ 'control-ui/components/ProfileAdminHome.tsx',
'control-ui/components/PublisherView/GrantedToMe.tsx',
'control-ui/components/PublisherView/OwnedEntries.tsx',
'control-ui/components/RecipesTab.tsx',
@@ -111,6 +114,10 @@ test('primary record tables keep headers mounted through data states', () => {
]
for (const file of statefulTables) {
- assert.match(readFileSync(file, 'utf8'), /TableStateRow/, `${file} must render table state rows`)
+ assert.match(
+ readFileSync(file, 'utf8'),
+ /TableStateRow/,
+ `${file} must render table state rows`
+ )
}
})