Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(datatable): multi-column sorting, column visibility, standard footer

Juan Denisfc2c4f669791
diff --git a/frontend/src/components/ds/ColumnsMenu.jsx b/frontend/src/components/ds/ColumnsMenu.jsx
new file mode 100644
index 00000000..f6111a05
--- /dev/null
+++ b/frontend/src/components/ds/ColumnsMenu.jsx
@@ -0,0 +1,62 @@
+import { Columns3, Eye, EyeOff } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { cn } from '@/lib/utils';
+
+// Toolbar popover for column show/hide (datatables.net "column visibility"
+// button). Lists every hideable column with an eye toggle; the trigger shows
+// how many columns are currently hidden. Pair with useColumnVisibility and
+// pass the same hiddenKeys to DataTable.
+//
+// const { hiddenKeys, toggleColumn, showAllColumns } = useColumnVisibility();
+// <ColumnsMenu columns={columns} hiddenKeys={hiddenKeys}
+// onToggle={toggleColumn} onShowAll={showAllColumns} />
+export function ColumnsMenu({ columns = [], hiddenKeys = [], onToggle, onShowAll, className }) {
+ const hideable = columns.filter((c) => c.hideable !== false);
+ const labelFor = (column) => (
+ typeof column.header === 'string' && column.header ? column.header : column.key
+ );
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className={cn('sk-filter-btn', hiddenKeys.length > 0 && 'sk-filter-btn--active', className)}
+ >
+ <Columns3 aria-hidden="true" />
+ Columns
+ {hiddenKeys.length > 0 && <span className="sk-filter-btn__badge">{hiddenKeys.length}</span>}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="sk-tablemenu">
+ <div className="sk-tablemenu__title">Toggle columns</div>
+ <div className="sk-tablemenu__list">
+ {hideable.map((column) => {
+ const hidden = hiddenKeys.includes(column.key);
+ return (
+ <button
+ key={column.key}
+ type="button"
+ className={cn('sk-tablemenu__item', 'sk-tablemenu__item--toggle', hidden && 'is-off')}
+ onClick={() => onToggle?.(column.key)}
+ aria-pressed={!hidden}
+ >
+ {hidden ? <EyeOff size={13} /> : <Eye size={13} />}
+ {labelFor(column)}
+ </button>
+ );
+ })}
+ </div>
+ <div className="sk-tablemenu__footer">
+ <Button variant="ghost" size="sm" onClick={onShowAll} disabled={hiddenKeys.length === 0}>
+ Show all
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+export default ColumnsMenu;
diff --git a/frontend/src/components/ds/DataTable.jsx b/frontend/src/components/ds/DataTable.jsx
index 6ce3e03a..3b416bb8 100644
--- a/frontend/src/components/ds/DataTable.jsx
+++ b/frontend/src/components/ds/DataTable.jsx
@@ -1,4 +1,4 @@
-import { useState, useMemo } from 'react';
+import { useMemo } from 'react';
import { ChevronUp, ChevronDown } from 'lucide-react';
import {
Table,
@@ -9,23 +9,34 @@ import {
TableRow,
} from '@/components/ui/table';
import { cn } from '@/lib/utils';
+import { applyTableSorts, nextSorts, useTableSort } from '@/hooks/useTableSort';
+import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import EmptyState from '../EmptyState';
/**
* Declarative data table built on top of the shadcn/ui Table primitives.
*
- * Supports sorting, empty states, loading states, clickable rows, and custom
- * cell rendering. Styling uses the existing `.ui-table` / `.sk-dtable` specs.
+ * Multi-column sorting (datatables.net style): a plain header click makes that
+ * column the only sort (asc -> desc -> none); shift+click stacks additional
+ * sort levels. Sort state is uncontrolled by default; pass `sorts` +
+ * `onSortsChange` to control it (e.g. to pair with <SortMenu> in a toolbar).
+ * Column visibility works the same way via `hiddenKeys` + `onHiddenKeysChange`
+ * and ds/ColumnsMenu. `storageKey` persists both to localStorage.
*
* Example:
* <DataTable
* columns={[
- * { key: 'name', header: 'Server', sortable: true, render: s => <ServerCell server={s} /> },
- * { key: 'status', header: 'Status', render: s => <Pill kind={s.status}>{s.status}</Pill> },
- * { key: 'actions', header: '', className: 'text-right', render: s => <Actions server={s} /> },
+ * { key: 'name', header: 'Server', sortable: true, hideable: false,
+ * render: s => <ServerCell server={s} /> },
+ * { key: 'status', header: 'Status', sortable: true,
+ * render: s => <Pill kind={s.status}>{s.status}</Pill> },
+ * { key: 'actions', header: '', className: 'text-right', sortable: false,
+ * hideable: false, render: s => <Actions server={s} /> },
* ]}
* data={servers}
* keyField="id"
+ * storageKey="serverkit-table-servers"
+ * footer={<DataTableFooter shown={rows.length} total={rows.length} />}
* emptyTitle="No servers"
* emptyMessage="Add your first server to start monitoring."
* />
@@ -35,49 +46,55 @@ export function DataTable({
data,
keyField = 'id',
sortable = true,
+ // Legacy single-sort default; prefer defaultSorts.
defaultSort = null,
+ defaultSorts,
+ // Controlled sort state (optional).
+ sorts: controlledSorts,
+ onSortsChange,
+ // Controlled column visibility (optional).
+ hiddenKeys: controlledHiddenKeys,
+ storageKey,
emptyState,
emptyTitle = 'No results',
emptyMessage = 'Nothing to show yet.',
loading = false,
onRowClick,
renderRow,
+ footer,
className,
rowClassName,
tableClassName,
}) {
- const [sort, setSort] = useState(defaultSort);
+ const internal = useTableSort({
+ defaultSorts: defaultSorts ?? (defaultSort ? [defaultSort] : []),
+ storageKey: storageKey ? `${storageKey}-sort` : undefined,
+ });
+ const sorts = controlledSorts ?? internal.sorts;
+ const toggleSort = useMemo(() => (
+ onSortsChange
+ ? (key, additive) => onSortsChange(nextSorts(sorts, key, additive))
+ : internal.toggleSort
+ ), [onSortsChange, sorts, internal.toggleSort]);
- const sortedData = useMemo(() => {
- if (!sort || !sortable) return data;
- const column = columns.find((c) => c.key === sort.key);
- if (!column) return data;
+ const internalCols = useColumnVisibility({
+ storageKey: storageKey ? `${storageKey}-cols` : undefined,
+ });
+ const hiddenKeys = controlledHiddenKeys ?? internalCols.hiddenKeys;
- const direction = sort.direction === 'desc' ? -1 : 1;
- const getValue = column.sortValue || ((row) => row[column.key]);
+ const visibleColumns = useMemo(
+ () => columns.filter((c) => !hiddenKeys.includes(c.key)),
+ [columns, hiddenKeys],
+ );
- return [...data].sort((a, b) => {
- const av = getValue(a);
- const bv = getValue(b);
- if (av == null && bv == null) return 0;
- if (av == null) return direction;
- if (bv == null) return -direction;
- if (typeof av === 'number' && typeof bv === 'number') {
- return (av - bv) * direction;
- }
- return String(av).localeCompare(String(bv)) * direction;
- });
- }, [data, sort, sortable, columns]);
+ const sortedData = useMemo(
+ () => (sortable ? applyTableSorts(data, sorts, columns) : data),
+ [data, sorts, sortable, columns],
+ );
- const handleHeaderClick = (column) => {
+ const handleHeaderClick = (event, column) => {
if (!sortable || !column.sortable) return;
- setSort((prev) => {
- if (prev?.key === column.key) {
- if (prev.direction === 'asc') return { key: column.key, direction: 'desc' };
- return null;
- }
- return { key: column.key, direction: 'asc' };
- });
+ toggleSort(column.key, event.shiftKey);
};
if (loading) {
@@ -89,26 +106,31 @@ export function DataTable({
return <EmptyState title={emptyTitle} message={emptyMessage} />;
}
+ const multiSort = sorts.length > 1;
+
return (
<div className={cn('sk-dtable-wrap', className)}>
<Table className={cn('sk-dtable', tableClassName)}>
<TableHeader>
<TableRow>
- {columns.map((column) => {
- const isSorted = sort?.key === column.key;
+ {visibleColumns.map((column) => {
+ const sortIndex = sorts.findIndex((s) => s.key === column.key);
+ const isSorted = sortIndex !== -1;
const canSort = sortable && column.sortable;
return (
<TableHead
key={column.key}
className={cn(
column.className,
- canSort && 'is-sortable'
+ canSort && 'is-sortable',
+ isSorted && 'is-sorted',
)}
style={column.width ? { width: column.width } : undefined}
- onClick={() => handleHeaderClick(column)}
+ onClick={(event) => handleHeaderClick(event, column)}
+ title={canSort ? 'Click to sort · Shift+click to add a sort level' : undefined}
aria-sort={
isSorted
- ? sort.direction === 'asc'
+ ? sorts[sortIndex].direction === 'asc'
? 'ascending'
: 'descending'
: 'none'
@@ -118,13 +140,16 @@ export function DataTable({
{column.header}
{canSort && (
<span className="sk-dtable__sort">
- {isSorted && sort.direction === 'asc' ? (
+ {isSorted && sorts[sortIndex].direction === 'asc' ? (
<ChevronUp size={14} />
- ) : isSorted && sort.direction === 'desc' ? (
+ ) : isSorted ? (
<ChevronDown size={14} />
) : (
<ChevronUp size={14} className="sk-dtable__sort-placeholder" />
)}
+ {isSorted && multiSort && (
+ <span className="sk-dtable__sort-priority">{sortIndex + 1}</span>
+ )}
</span>
)}
</span>
@@ -153,7 +178,7 @@ export function DataTable({
)}
onClick={onRowClick ? () => onRowClick(row) : undefined}
>
- {columns.map((column) => (
+ {visibleColumns.map((column) => (
<TableCell
key={`${key}-${column.key}`}
className={column.cellClassName}
@@ -168,6 +193,7 @@ export function DataTable({
})}
</TableBody>
</Table>
+ {footer}
</div>
);
}
diff --git a/frontend/src/components/ds/DataTableFooter.jsx b/frontend/src/components/ds/DataTableFooter.jsx
new file mode 100644
index 00000000..0359f83f
--- /dev/null
+++ b/frontend/src/components/ds/DataTableFooter.jsx
@@ -0,0 +1,96 @@
+import { ChevronLeft, ChevronRight } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { SegControl } from './SegControl';
+import { cn } from '@/lib/utils';
+
+// Shared table footer — one standard way to answer "how much am I looking at
+// and how do I see more", replacing the four ad-hoc pagers pages grew
+// (Prev/Next labels, bare "Load more", server params, nothing).
+//
+// Client-side slicing:
+// <DataTableFooter shown={rows.length} total={rows.length}
+// pageSize={pageSize} onPageSizeChange={setPageSize} />
+//
+// Incremental loading (server or client):
+// <DataTableFooter shown={rows.length} total={total}
+// hasMore={hasMore} onLoadMore={loadMore} loading={loading} />
+//
+// Paged server data:
+// <DataTableFooter shown={rows.length} total={total}
+// page={page} totalPages={pages} onPageChange={setPage} />
+export function DataTableFooter({
+ shown,
+ total,
+ noun = 'row',
+ // client-side page-size segment (omit to hide)
+ pageSize,
+ pageSizeOptions = [25, 50, 100],
+ onPageSizeChange,
+ // load-more mode
+ hasMore = false,
+ onLoadMore,
+ loading = false,
+ // paged mode
+ page,
+ totalPages,
+ onPageChange,
+ className,
+}) {
+ const label = total == null || total === shown
+ ? `${shown} ${noun}${shown === 1 ? '' : 's'}`
+ : `Shown ${shown} of ${total} ${noun}s`;
+
+ const paged = page != null && totalPages != null && onPageChange;
+
+ return (
+ <div className={cn('sk-dtable-footer', className)}>
+ <span className="sk-dtable-footer__count">{label}</span>
+ <div className="sk-dtable-footer__controls">
+ {onPageSizeChange && (
+ <SegControl
+ className="sk-dtable-footer__sizes"
+ value={String(pageSize)}
+ onChange={(value) => onPageSizeChange(value === 'all' ? 'all' : Number(value))}
+ options={[
+ ...pageSizeOptions.map((n) => ({ value: String(n), label: String(n) })),
+ { value: 'all', label: 'All' },
+ ]}
+ aria-label="Rows per page"
+ />
+ )}
+ {onLoadMore && hasMore && (
+ <Button variant="outline" size="sm" onClick={onLoadMore} disabled={loading}>
+ {loading ? 'Loading…' : 'Load more'}
+ </Button>
+ )}
+ {paged && totalPages > 1 && (
+ <div className="sk-dtable-footer__pager">
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => onPageChange(page - 1)}
+ disabled={page <= 1}
+ aria-label="Previous page"
+ >
+ <ChevronLeft aria-hidden="true" />
+ </Button>
+ <span className="sk-dtable-footer__page">
+ {page} / {totalPages}
+ </span>
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => onPageChange(page + 1)}
+ disabled={page >= totalPages}
+ aria-label="Next page"
+ >
+ <ChevronRight aria-hidden="true" />
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default DataTableFooter;
diff --git a/frontend/src/components/ds/SortMenu.jsx b/frontend/src/components/ds/SortMenu.jsx
new file mode 100644
index 00000000..9aa9c7c0
--- /dev/null
+++ b/frontend/src/components/ds/SortMenu.jsx
@@ -0,0 +1,103 @@
+import { ArrowDownUp, ArrowUp, ArrowDown, X } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { cn } from '@/lib/utils';
+
+// Toolbar popover for user-controllable multi-column sorting (Frappe CRM
+// style). Each active sort is a row: field label, asc/desc toggle, remove.
+// "Add sort level" stacks another column; priority is the row order. The
+// trigger button carries a count badge while any sort is active.
+//
+// const { sorts, setSorts } = useTableSort();
+// <SortMenu columns={columns} sorts={sorts} onChange={setSorts} />
+export function SortMenu({ columns = [], sorts = [], onChange, className }) {
+ const sortableColumns = columns.filter((c) => c.sortable);
+ const labelFor = (key) => {
+ const column = sortableColumns.find((c) => c.key === key);
+ if (!column) return key;
+ // Column headers may be React nodes; only plain text makes a usable label.
+ return typeof column.header === 'string' ? column.header : column.key;
+ };
+
+ const flip = (key) => onChange?.(
+ sorts.map((s) => (s.key === key
+ ? { ...s, direction: s.direction === 'asc' ? 'desc' : 'asc' }
+ : s)),
+ );
+ const remove = (key) => onChange?.(sorts.filter((s) => s.key !== key));
+ const add = (key) => onChange?.([...sorts, { key, direction: 'asc' }]);
+ const clear = () => onChange?.([]);
+
+ const available = sortableColumns.filter((c) => !sorts.some((s) => s.key === c.key));
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className={cn('sk-filter-btn', sorts.length > 0 && 'sk-filter-btn--active', className)}
+ >
+ <ArrowDownUp aria-hidden="true" />
+ Sort
+ {sorts.length > 0 && <span className="sk-filter-btn__badge">{sorts.length}</span>}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="sk-tablemenu">
+ <div className="sk-tablemenu__title">Sort by</div>
+ {sorts.length === 0 && (
+ <div className="sk-tablemenu__empty">No sorting applied</div>
+ )}
+ {sorts.map((sort, index) => (
+ <div key={sort.key} className="sk-tablemenu__row">
+ {sorts.length > 1 && (
+ <span className="sk-tablemenu__priority">{index + 1}</span>
+ )}
+ <span className="sk-tablemenu__field">{labelFor(sort.key)}</span>
+ <button
+ type="button"
+ className="sk-tablemenu__dir"
+ onClick={() => flip(sort.key)}
+ aria-label={`Sort ${labelFor(sort.key)} ${sort.direction === 'asc' ? 'descending' : 'ascending'}`}
+ title={sort.direction === 'asc' ? 'Ascending' : 'Descending'}
+ >
+ {sort.direction === 'asc' ? <ArrowUp size={13} /> : <ArrowDown size={13} />}
+ </button>
+ <button
+ type="button"
+ className="sk-tablemenu__remove"
+ onClick={() => remove(sort.key)}
+ aria-label={`Remove sort on ${labelFor(sort.key)}`}
+ >
+ <X size={13} />
+ </button>
+ </div>
+ ))}
+ {available.length > 0 && (
+ <>
+ <div className="sk-tablemenu__section">Add sort level</div>
+ <div className="sk-tablemenu__list">
+ {available.map((c) => (
+ <button
+ key={c.key}
+ type="button"
+ className="sk-tablemenu__item"
+ onClick={() => add(c.key)}
+ >
+ {labelFor(c.key)}
+ </button>
+ ))}
+ </div>
+ </>
+ )}
+ <div className="sk-tablemenu__footer">
+ <Button variant="ghost" size="sm" onClick={clear} disabled={sorts.length === 0}>
+ Clear
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+export default SortMenu;
diff --git a/frontend/src/components/ds/index.js b/frontend/src/components/ds/index.js
index 0dfec490..ea3b3859 100644
--- a/frontend/src/components/ds/index.js
+++ b/frontend/src/components/ds/index.js
@@ -19,5 +19,8 @@ export {
} from './FilterDrawer';
export { PageTopbar } from './PageTopbar';
export { DataTable } from './DataTable';
+export { SortMenu } from './SortMenu';
+export { ColumnsMenu } from './ColumnsMenu';
+export { DataTableFooter } from './DataTableFooter';
export { ResourceCard, ResourceList } from './ResourceCard';
export { svcGrad, initials, gaugeColor } from './utils';
diff --git a/frontend/src/hooks/useColumnVisibility.js b/frontend/src/hooks/useColumnVisibility.js
new file mode 100644
index 00000000..b329e79b
--- /dev/null
+++ b/frontend/src/hooks/useColumnVisibility.js
@@ -0,0 +1,47 @@
+import { useCallback, useEffect, useState } from 'react';
+
+// Column-visibility state for DataTable, paired with ds/ColumnsMenu.
+// `hiddenKeys` is a string[] of column keys currently hidden. Columns opt out
+// of hiding with `hideable: false` (e.g. a primary name column or an actions
+// column) — those never appear in the menu and can never be hidden.
+//
+// const { hiddenKeys, toggleColumn, showAllColumns } = useColumnVisibility({
+// storageKey: 'serverkit-cols-servers', // optional localStorage persistence
+// });
+
+function readStored(storageKey) {
+ if (!storageKey) return null;
+ try {
+ const raw = window.localStorage.getItem(storageKey);
+ if (!raw) return null;
+ const parsed = JSON.parse(raw);
+ return Array.isArray(parsed) ? parsed.filter((k) => typeof k === 'string') : null;
+ } catch {
+ return null;
+ }
+}
+
+export function useColumnVisibility({ defaultHidden = [], storageKey } = {}) {
+ const [hiddenKeys, setHiddenKeys] = useState(() => readStored(storageKey) ?? defaultHidden);
+
+ useEffect(() => {
+ if (!storageKey) return;
+ try {
+ window.localStorage.setItem(storageKey, JSON.stringify(hiddenKeys));
+ } catch {
+ /* private mode / quota — the choice just doesn't persist */
+ }
+ }, [hiddenKeys, storageKey]);
+
+ const toggleColumn = useCallback((key) => {
+ setHiddenKeys((prev) => (
+ prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]
+ ));
+ }, []);
+
+ const showAllColumns = useCallback(() => setHiddenKeys([]), []);
+
+ return { hiddenKeys, setHiddenKeys, toggleColumn, showAllColumns };
+}
+
+export default useColumnVisibility;
diff --git a/frontend/src/hooks/useTableSort.js b/frontend/src/hooks/useTableSort.js
new file mode 100644
index 00000000..541d1ab9
--- /dev/null
+++ b/frontend/src/hooks/useTableSort.js
@@ -0,0 +1,119 @@
+import { useCallback, useEffect, useState } from 'react';
+
+// Multi-column sort state for DataTable, datatables.net style.
+//
+// `sorts` is an ORDERED array — sorts[0] is the primary key, later entries
+// break ties. Interaction model:
+//
+// click header -> make that column the only sort (asc -> desc -> none)
+// shift+click header -> add/toggle an additional sort level
+// SortMenu rows -> same upsert, plus explicit removal and "clear all"
+//
+// A column-level `sortValue(row)` accessor is honored, values compare as
+// numbers when both are numeric, otherwise localeCompare; nulls always last.
+//
+// const { sorts, toggleSort, clearSorts } = useTableSort({
+// defaultSorts: [{ key: 'name', direction: 'asc' }],
+// storageKey: 'serverkit-sort-servers', // optional localStorage persistence
+// });
+
+export function applyTableSorts(data, sorts, columns) {
+ if (!sorts?.length) return data;
+ const active = sorts
+ .map((sort) => {
+ const column = columns.find((c) => c.key === sort.key);
+ if (!column) return null;
+ return {
+ direction: sort.direction === 'desc' ? -1 : 1,
+ getValue: column.sortValue || ((row) => row[column.key]),
+ };
+ })
+ .filter(Boolean);
+ if (!active.length) return data;
+
+ return [...data].sort((a, b) => {
+ for (const { getValue, direction } of active) {
+ const av = getValue(a);
+ const bv = getValue(b);
+ if (av == null && bv == null) continue;
+ if (av == null) return direction;
+ if (bv == null) return -direction;
+ let cmp;
+ if (typeof av === 'number' && typeof bv === 'number') {
+ cmp = av - bv;
+ } else {
+ cmp = String(av).localeCompare(String(bv));
+ }
+ if (cmp !== 0) return cmp * direction;
+ }
+ return 0;
+ });
+}
+
+function readStoredSorts(storageKey) {
+ if (!storageKey) return null;
+ try {
+ const raw = window.localStorage.getItem(storageKey);
+ if (!raw) return null;
+ const parsed = JSON.parse(raw);
+ return Array.isArray(parsed) && parsed.every((s) => s && typeof s.key === 'string')
+ ? parsed
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+export function useTableSort({ defaultSorts = [], storageKey } = {}) {
+ const [sorts, setSorts] = useState(() => readStoredSorts(storageKey) ?? defaultSorts);
+
+ useEffect(() => {
+ if (!storageKey) return;
+ try {
+ window.localStorage.setItem(storageKey, JSON.stringify(sorts));
+ } catch {
+ /* private mode / quota — the choice just doesn't persist */
+ }
+ }, [sorts, storageKey]);
+
+ // Upsert-toggle a sort level. additive=false replaces the whole array
+ // (plain header click); additive=true stacks a level (shift+click).
+ const toggleSort = useCallback((key, additive = false) => {
+ setSorts((prev) => {
+ const index = prev.findIndex((s) => s.key === key);
+ if (index === -1) {
+ const next = { key, direction: 'asc' };
+ return additive ? [...prev, next] : [next];
+ }
+ const current = prev[index];
+ if (current.direction === 'asc') {
+ const next = [...prev];
+ next[index] = { key, direction: 'desc' };
+ return additive ? next : [next[index]];
+ }
+ // desc -> remove the level entirely
+ return prev.filter((s) => s.key !== key);
+ });
+ }, []);
+
+ const clearSorts = useCallback(() => setSorts([]), []);
+
+ return { sorts, setSorts, toggleSort, clearSorts };
+}
+
+// Same upsert-toggle as the hook's toggleSort, exported so controlled-mode
+// hosts can compute the next sorts array without duplicating the logic.
+export function nextSorts(prev, key, additive = false) {
+ const index = prev.findIndex((s) => s.key === key);
+ if (index === -1) {
+ return additive ? [...prev, { key, direction: 'asc' }] : [{ key, direction: 'asc' }];
+ }
+ if (prev[index].direction === 'asc') {
+ const next = [...prev];
+ next[index] = { key, direction: 'desc' };
+ return additive ? next : [next[index]];
+ }
+ return prev.filter((s) => s.key !== key);
+}
+
+export default useTableSort;