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(ds): useTableChrome -- one list chrome for every DataTable page

Juan Denis43c2babcf8bf
diff --git a/frontend/src/components/ds/grid/GridFilterDrawer.jsx b/frontend/src/components/ds/grid/GridFilterDrawer.jsx
index 414fa6fd..094e9b33 100644
--- a/frontend/src/components/ds/grid/GridFilterDrawer.jsx
+++ b/frontend/src/components/ds/grid/GridFilterDrawer.jsx
@@ -13,7 +13,14 @@ import {
// looking at": FILTERS decides which rows, FIELDS decides which columns (and in
// what order, at what density, with which detail line). The header menu is the
// fast path for one column; this is the whole picture at once.
-export function GridFilterDrawer({ open, onOpenChange, columns, rows, cfg, grid, noun = 'rows' }) {
+export function GridFilterDrawer({
+ open, onOpenChange, columns, rows, cfg, grid, noun = 'rows',
+ // Hosts whose table auto-sizes its columns and has no sub-detail line
+ // (i.e. <DataTable> rather than <DataGrid>) switch these off — a control
+ // that cannot change anything is worse than a missing one.
+ showRowDetail = true,
+ showDensity = true,
+}) {
const [tab, setTab] = useState('filters');
const [dragging, setDragging] = useState(null);
@@ -149,7 +156,11 @@ export function GridFilterDrawer({ open, onOpenChange, columns, rows, cfg, grid,
{rules.map((rule, i) => {
const column = map.get(rule.field);
- if (!column) return null;
+ // A rule can outlive its column's filterability — a
+ // saved view from before a column changed shape, or
+ // a column whose data went empty. Skip it rather
+ // than look up OPS[undefined] and crash the drawer.
+ if (!column || !isFilterable(column)) return null;
return (
<div key={rule.id}>
{i > 0 && (
@@ -244,7 +255,10 @@ export function GridFilterDrawer({ open, onOpenChange, columns, rows, cfg, grid,
})}
</div>
+ {(showRowDetail || showDensity) && (
<div className="sk-gridsec">
+ {showRowDetail && (
+ <>
<div className="sk-gridsec__head"><div className="sk-gridsec__t">Row detail</div></div>
<p className="sk-gridsec__hint">Extra fields printed under the first column.</p>
<div className="sk-gridsec__tags">
@@ -264,8 +278,12 @@ export function GridFilterDrawer({ open, onOpenChange, columns, rows, cfg, grid,
);
})}
</div>
+ </>
+ )}
- <div className="sk-gridsec__head" style={{ marginTop: 18 }}>
+ {showDensity && (
+ <>
+ <div className="sk-gridsec__head" style={showRowDetail ? { marginTop: 18 } : undefined}>
<div className="sk-gridsec__t">Density</div>
</div>
<div className="sk-gridseg sk-gridseg--wide">
@@ -280,7 +298,10 @@ export function GridFilterDrawer({ open, onOpenChange, columns, rows, cfg, grid,
</button>
))}
</div>
+ </>
+ )}
</div>
+ )}
</>
)}
</div>
diff --git a/frontend/src/components/ds/grid/GridToolsMenu.jsx b/frontend/src/components/ds/grid/GridToolsMenu.jsx
index 3264ed47..a52a87b9 100644
--- a/frontend/src/components/ds/grid/GridToolsMenu.jsx
+++ b/frontend/src/components/ds/grid/GridToolsMenu.jsx
@@ -9,8 +9,11 @@ import { byKey, exportRows } from './fields';
// One button instead of four keeps the top bar the same shape on every page,
// which is the whole point of putting search there.
export function GridToolsMenu({
- cfg, columns, rows, selectedRows, viewName, noun = 'rows',
+ cfg, columns, rows, selectedRows = [], viewName, noun = 'rows',
onRefresh, onReset, onDensity, onExported,
+ // Off for hosts whose table auto-sizes its rows (<DataTable>) — showing a
+ // density toggle that changes nothing is worse than not showing one.
+ showDensity = true,
}) {
const [open, setOpen] = useState(false);
const [pane, setPane] = useState('root'); // root | export
@@ -59,19 +62,23 @@ export function GridToolsMenu({
<RefreshCw size={13} />Refresh data
</button>
)}
- <div className="sk-gridmenu__sep" />
- <div className="sk-gridmenu__head">Row density</div>
- {[['cozy', 'Cozy', Rows2], ['compact', 'Compact', Rows3]].map(([value, text, Icon]) => (
- <button
- key={value}
- type="button"
- className={cn('sk-gridmenu__opt', cfg.density === value && 'is-on')}
- onClick={() => onDensity(value)}
- >
- <span className="sk-gridmenu__box"><Check size={11} /></span>
- <Icon size={13} />{text}
- </button>
- ))}
+ {showDensity && (
+ <>
+ <div className="sk-gridmenu__sep" />
+ <div className="sk-gridmenu__head">Row density</div>
+ {[['cozy', 'Cozy', Rows2], ['compact', 'Compact', Rows3]].map(([value, text, Icon]) => (
+ <button
+ key={value}
+ type="button"
+ className={cn('sk-gridmenu__opt', cfg.density === value && 'is-on')}
+ onClick={() => onDensity(value)}
+ >
+ <span className="sk-gridmenu__box"><Check size={11} /></span>
+ <Icon size={13} />{text}
+ </button>
+ ))}
+ </>
+ )}
<div className="sk-gridmenu__sep" />
<button
type="button"
diff --git a/frontend/src/components/ds/grid/index.js b/frontend/src/components/ds/grid/index.js
index 3991d97d..1004ca30 100644
--- a/frontend/src/components/ds/grid/index.js
+++ b/frontend/src/components/ds/grid/index.js
@@ -17,8 +17,10 @@ export { GridFilterDrawer } from './GridFilterDrawer';
export { GridFilterButton } from './GridFilterButton';
export { useGridConfig, makeGridConfig, GRID_DEFAULTS } from './useGridConfig';
export { useGridRows } from './useGridRows';
+export { useTableChrome } from './useTableChrome';
export {
OPS, FIELD_TYPES, opLabel, ruleId, columnLabel, fieldValue,
applyFilters, applySort, groupRows, ruleText, exportRows,
isFilterable, isGroupable, isSortable, isHideable, optionsFor, valueCounts,
+ inferColumnType, withInferredTypes, isDecorative,
} from './fields';
diff --git a/frontend/src/components/ds/grid/useTableChrome.js b/frontend/src/components/ds/grid/useTableChrome.js
new file mode 100644
index 00000000..bddcaceb
--- /dev/null
+++ b/frontend/src/components/ds/grid/useTableChrome.js
@@ -0,0 +1,188 @@
+import { useCallback, useMemo, useState } from 'react';
+import useTableViews from '@/hooks/useTableViews';
+import { OPS, emptyValueFor, isFilterable, ruleId, withInferredTypes } from './fields';
+
+const NO_FILTERS = { match: 'all', rules: [] };
+
+/**
+ * The grid chrome (view picker · chip bar · filter drawer · tools menu) for a
+ * page that renders <DataTable> with the legacy state model — sorts[] +
+ * hiddenKeys + groupBy — rather than DataGrid's single cfg object.
+ *
+ * Written once here so every list page gets the SAME chrome instead of each
+ * one growing its own toolbar. Give it the page's existing state and setters;
+ * it returns `cfg` + `api` (what the chrome components expect), the extra
+ * DataTable props, and the wired-up `views`.
+ *
+ * const chrome = useTableChrome({
+ * columns, rows: filtered, viewPageKey: 'cron', builtinViews: BUILTIN_VIEWS,
+ * sorts, setSorts, hiddenKeys, setHiddenKeys, groupBy, setGroupBy,
+ * extraState: { filter, search }, // page-owned view state
+ * applyExtra: (s) => { setFilter(s.filter); setSearch(s.search); },
+ * });
+ *
+ * <GridViewPicker views={chrome.views} … />
+ * <GridChips {...chrome.chipProps} />
+ * <DataTable {…chrome.tableProps} columns={chrome.columns} … />
+ * <GridFilterDrawer {...chrome.drawerProps} />
+ */
+export function useTableChrome({
+ columns,
+ rows = [],
+ viewPageKey,
+ builtinViews = [],
+ noun = 'rows',
+ sorts = [],
+ setSorts,
+ hiddenKeys = [],
+ setHiddenKeys,
+ groupBy = null,
+ setGroupBy,
+ extraState,
+ applyExtra,
+}) {
+ const [filters, setFilters] = useState(NO_FILTERS);
+ const [columnOrder, setColumnOrder] = useState(null);
+ const [drawerOpen, setDrawerOpen] = useState(false);
+
+ // Infer types HERE, once, and hand the same typed list to the chip bar, the
+ // drawer and <DataTable>. DataTable can infer them itself, but then the
+ // chrome would be reasoning about untyped columns while the table reasoned
+ // about typed ones — and the drawer's rule editor would look up
+ // OPS[undefined] for any rule the header menu had just created.
+ const typedColumns = useMemo(() => withInferredTypes(columns, rows), [columns, rows]);
+
+ const orderedColumns = useMemo(() => {
+ if (!columnOrder?.length) return typedColumns;
+ const byKey = new Map(typedColumns.map((c) => [c.key, c]));
+ return [
+ ...columnOrder.map((k) => byKey.get(k)).filter(Boolean),
+ ...typedColumns.filter((c) => !columnOrder.includes(c.key)),
+ ];
+ }, [typedColumns, columnOrder]);
+
+ const cfg = useMemo(() => ({
+ cols: orderedColumns.filter((c) => !hiddenKeys.includes(c.key)).map((c) => c.key),
+ sort: sorts[0] ? { key: sorts[0].key, dir: sorts[0].direction } : { key: null, dir: 'asc' },
+ group: groupBy,
+ filters,
+ density: 'cozy',
+ sub: [],
+ }), [orderedColumns, hiddenKeys, sorts, groupBy, filters]);
+
+ const removeRule = useCallback(
+ (id) => setFilters((p) => ({ ...p, rules: p.rules.filter((r) => r.id !== id) })),
+ [],
+ );
+ const clearRules = useCallback(() => setFilters((p) => ({ ...p, rules: [] })), []);
+ const setMatch = useCallback((match) => setFilters((p) => ({ ...p, match })), []);
+
+ const api = useMemo(() => ({
+ setRules: (rules) => setFilters((p) => ({ ...p, rules })),
+ setMatch,
+ addRule: (cols) => {
+ const first = cols.find(isFilterable);
+ if (!first) return;
+ setFilters((p) => ({
+ ...p,
+ rules: [...p.rules, {
+ id: ruleId(),
+ field: first.key,
+ op: OPS[first.type][0][0],
+ value: emptyValueFor(first.type),
+ }],
+ }));
+ },
+ removeRule,
+ setColumnOrder,
+ toggleColumn: (key) => setHiddenKeys?.(
+ hiddenKeys.includes(key) ? hiddenKeys.filter((k) => k !== key) : [...hiddenKeys, key],
+ ),
+ setSub: () => {},
+ setDensity: () => {},
+ resetToView: () => { clearRules(); setHiddenKeys?.([]); setColumnOrder(null); },
+ }), [setMatch, removeRule, clearRules, hiddenKeys, setHiddenKeys]);
+
+ // The saved-view key is `columnFilters`, NOT `filters`: several pages
+ // (Jobs, Monitors) already capture a `filters` key of their own, and it is
+ // the FilterDrawer's {status, kind} pair — a different thing entirely.
+ // Sharing the name would have made their presets silently cross-wire.
+ const capture = useCallback(() => ({
+ ...(extraState || {}),
+ sorts,
+ hiddenKeys,
+ groupBy,
+ columnFilters: filters,
+ columnOrder,
+ }), [extraState, sorts, hiddenKeys, groupBy, filters, columnOrder]);
+
+ const apply = useCallback((state) => {
+ applyExtra?.(state);
+ if (Array.isArray(state.sorts)) setSorts?.(state.sorts);
+ if (Array.isArray(state.hiddenKeys)) setHiddenKeys?.(state.hiddenKeys);
+ if (state.groupBy !== undefined) setGroupBy?.(state.groupBy);
+ // A preset with no rules must CLEAR the live ones, or switching views
+ // leaves the previous view's filters silently applied.
+ setFilters(state.columnFilters ?? NO_FILTERS);
+ setColumnOrder(state.columnOrder ?? null);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [applyExtra, setSorts, setHiddenKeys, setGroupBy]);
+
+ const views = useTableViews({ page: viewPageKey, builtinViews, capture, apply });
+
+ const createView = useCallback((name, fromCurrent) => {
+ if (!fromCurrent) api.resetToView();
+ return views.saveView(name);
+ }, [api, views]);
+
+ return {
+ cfg,
+ api,
+ views,
+ columns: orderedColumns,
+ noun,
+ filterCount: filters.rules.length,
+ drawerOpen,
+ setDrawerOpen,
+ createView,
+
+ // spread straight onto the matching components
+ tableProps: {
+ filters,
+ onFiltersChange: setFilters,
+ columnOrder,
+ onColumnOrderChange: setColumnOrder,
+ hiddenKeys,
+ onHiddenKeysChange: setHiddenKeys,
+ },
+ chipProps: {
+ cfg,
+ columns: orderedColumns,
+ onRemove: removeRule,
+ onClear: clearRules,
+ onMatchChange: setMatch,
+ },
+ drawerProps: {
+ open: drawerOpen,
+ onOpenChange: setDrawerOpen,
+ columns: orderedColumns,
+ rows,
+ cfg,
+ grid: api,
+ noun,
+ showRowDetail: false,
+ showDensity: false,
+ },
+ toolsProps: {
+ cfg,
+ columns: orderedColumns,
+ rows,
+ viewName: views.activeView?.name || noun,
+ noun,
+ onReset: api.resetToView,
+ showDensity: false,
+ },
+ };
+}
+
+export default useTableChrome;