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.

refactor(views): one saved-view envelope, one place that wires it up

Juan Denis37d2437a538b
diff --git a/frontend/src/components/ds/grid/index.js b/frontend/src/components/ds/grid/index.js
index 35e8bfdd..af1e776e 100644
--- a/frontend/src/components/ds/grid/index.js
+++ b/frontend/src/components/ds/grid/index.js
@@ -19,6 +19,14 @@ export { useGridConfig, makeGridConfig, GRID_DEFAULTS } from './useGridConfig';
export { useGridRows } from './useGridRows';
export { useTableChrome } from './useTableChrome';
export { useViewLink } from './useViewLink';
+// The saved-view envelope: ONE state shape for every list page. `useGridViews`
+// is the only thing that should touch `useTableViews` — pages go through
+// `useTableChrome` (DataTable) or `useGridConfig` (DataGrid).
+export { useGridViews } from './useGridViews';
+export {
+ toEnvelope, emptyViewState, sameViewState, cfgToEnvelope, envelopeToCfg,
+ COMMON_KEYS, NO_COLUMN_FILTERS,
+} from './viewState';
export {
encodeState, decodeState, readViewParams, resolveView, copyableLink,
handleFor, slugify as slugifyViewName, VIEW_PARAM, STATE_PARAM,
diff --git a/frontend/src/components/ds/grid/useGridConfig.js b/frontend/src/components/ds/grid/useGridConfig.js
index fb67541a..9c52bc7b 100644
--- a/frontend/src/components/ds/grid/useGridConfig.js
+++ b/frontend/src/components/ds/grid/useGridConfig.js
@@ -1,6 +1,6 @@
import { useCallback, useMemo, useState } from 'react';
-import useTableViews from '@/hooks/useTableViews';
-import useViewLink from './useViewLink';
+import useGridViews from './useGridViews';
+import { cfgToEnvelope, envelopeToCfg } from './viewState';
import { emptyValueFor, isFilterable, OPS, ruleId } from './fields';
// The whole of a grid's chrome is ONE serialisable object, so a saved view is
@@ -64,15 +64,32 @@ export function useGridConfig({ page, columns, initial, builtinViews = [] }) {
const [cfg, setCfg] = useState(base);
- const capture = useCallback(() => cfg, [cfg]);
- const apply = useCallback((state) => setCfg(makeGridConfig(state || {})), []);
+ // `cfg` is DataGrid's own representation and stays that way — it is what
+ // makes "move column left" a one-line splice. Saved views, though, are the
+ // SHARED envelope, so a Domains view is the same JSON as a Cron view and
+ // one shareable-link format covers both. The two are bridged here, in the
+ // one place, rather than by teaching either side about the other.
+ const allKeys = useMemo(() => columns.map((c) => c.key), [columns]);
+
+ const capture = useCallback(() => cfgToEnvelope(cfg, allKeys), [cfg, allKeys]);
+ const apply = useCallback(
+ (state) => setCfg(makeGridConfig(envelopeToCfg(state, allKeys))),
+ [allKeys],
+ );
- const views = useTableViews({ page, builtinViews, capture, apply });
+ // Saving a view with "start from current" cleared means the page's natural
+ // config, not the active view's — so this resets to `base`, not through
+ // `resetToView` below (which re-applies the active view, and would also be
+ // a dependency cycle: it needs `views`, which needs this).
+ const resetToBase = useCallback(() => setCfg(clone(base)), [base]);
- // ?view=<slug> / readable params <-> the active view. Same hook the legacy
- // chrome uses, so a DataGrid page and a DataTable page produce and accept
- // the same links.
- const { copyLink } = useViewLink({ views, apply, capture, enabled: !!page });
+ const { views, copyLink, createView } = useGridViews({
+ page,
+ builtinViews,
+ capture,
+ apply,
+ resetToView: resetToBase,
+ });
// ---- narrow setters the menus talk to ------------------------------
const patch = useCallback((next) => setCfg((prev) => ({ ...prev, ...next })), []);
@@ -186,6 +203,7 @@ export function useGridConfig({ page, columns, initial, builtinViews = [] }) {
setCfg,
views,
copyLink,
+ createView,
base,
setSort,
toggleGroup,
diff --git a/frontend/src/components/ds/grid/useGridViews.js b/frontend/src/components/ds/grid/useGridViews.js
new file mode 100644
index 00000000..afe8e138
--- /dev/null
+++ b/frontend/src/components/ds/grid/useGridViews.js
@@ -0,0 +1,92 @@
+import { useCallback, useMemo, useRef } from 'react';
+import useTableViews from './useTableViews';
+import useViewLink from './useViewLink';
+import { emptyViewState, sameViewState, toEnvelope } from './viewState';
+
+/**
+ * The ONE place saved views are wired up.
+ *
+ * Both chrome hosts go through it — `useTableChrome` (the <DataTable> pages)
+ * and `useGridConfig` (the <DataGrid> pages) — so the three things that used to
+ * be per-page are now structural:
+ *
+ * · every view is captured in the same envelope (see `viewState.js`)
+ * · every page gets shareable `?view=` links, not just the ones someone
+ * remembered to wire `useViewLink` into
+ * · a guard or control added to the chrome lands here once
+ *
+ * const views = useGridViews({
+ * page: 'cronjobs', builtinViews, capture, apply,
+ * rename: { filters: 'serverFilters' }, // legacy top-level key -> page bag
+ * });
+ *
+ * `capture` returns the page's live state and `apply` pushes one back; both are
+ * normalised to the envelope here, so a page never has to think about the
+ * shape a previous release happened to persist.
+ */
+export function useGridViews({ page, builtinViews = [], capture, apply, rename, resetToView }) {
+ // `rename` is almost always an inline literal. Freeze the first one rather
+ // than rebuilding every callback below on each render — the map is a
+ // per-page constant, and a changing identity here would reach `apply`,
+ // which several pages put in an effect dependency array.
+ const renameRef = useRef(rename);
+ const renameMap = renameRef.current;
+
+ // Presets authored before the envelope are migrated on the way in, so a
+ // page can adopt it without rewriting its built-ins in the same commit.
+ // Keyed on names for the same reason useTableViews is: an inline
+ // `builtinViews={[…]}` literal is a new array identity every render.
+ const builtinKey = builtinViews.map((v) => v.name).join(' ');
+ const migratedBuiltins = useMemo(
+ () => builtinViews.map((v) => ({ ...v, state: toEnvelope(v.state, { rename: renameMap }) })),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [builtinKey, renameMap],
+ );
+
+ const captureEnvelope = useCallback(
+ () => toEnvelope(capture?.() ?? {}, { rename: renameMap }),
+ [capture, renameMap],
+ );
+
+ const applyEnvelope = useCallback(
+ (state) => apply?.(toEnvelope(state, { rename: renameMap })),
+ [apply, renameMap],
+ );
+
+ const isSame = useCallback(
+ (a, b) => sameViewState(a, b, { rename: renameMap }),
+ [renameMap],
+ );
+
+ const views = useTableViews({
+ page,
+ builtinViews: migratedBuiltins,
+ capture: captureEnvelope,
+ apply: applyEnvelope,
+ isSame,
+ });
+
+ // ?view=<slug> / ?v=<encoded> <-> the active view, both directions.
+ // Applying a link goes through the SAME `apply` the picker uses, so a
+ // shared link and a click can never drift apart.
+ const { copyLink } = useViewLink({
+ views,
+ apply: applyEnvelope,
+ capture: captureEnvelope,
+ enabled: !!page,
+ });
+
+ // "Save current view…" with the checkbox cleared means a CLEAN view, not
+ // "this view minus its name". Reset the live grid, but persist an explicit
+ // empty envelope rather than re-reading state — the reset has not landed
+ // yet, so capture() would still return what the checkbox said to discard.
+ const createView = useCallback((name, fromCurrent) => {
+ if (fromCurrent) return views.saveView(name);
+ resetToView?.();
+ return views.saveView(name, { state: emptyViewState() });
+ }, [views, resetToView]);
+
+ return { views, copyLink, createView, captureEnvelope, applyEnvelope };
+}
+
+export default useGridViews;
diff --git a/frontend/src/components/ds/grid/useTableChrome.js b/frontend/src/components/ds/grid/useTableChrome.js
index a7c72a07..87e25260 100644
--- a/frontend/src/components/ds/grid/useTableChrome.js
+++ b/frontend/src/components/ds/grid/useTableChrome.js
@@ -1,31 +1,35 @@
import { useCallback, useMemo, useState } from 'react';
-import useTableViews from '@/hooks/useTableViews';
-import useViewLink from './useViewLink';
+import useGridViews from './useGridViews';
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.
+ * THE entry point for the grid chrome (view picker · chip bar · filter drawer ·
+ * tools menu) on a page that renders <DataTable> — i.e. the sorts[] +
+ * hiddenKeys + groupBy state model 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
+ * 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); },
+ * pageState: { filter, search }, // the page's own bag
+ * applyPage: (p) => { setFilter(p.filter); setSearch(p.search); },
* });
*
* <GridViewPicker views={chrome.views} … />
* <GridChips {...chrome.chipProps} />
* <DataTable {…chrome.tableProps} columns={chrome.columns} … />
* <GridFilterDrawer {...chrome.drawerProps} />
+ *
+ * `pageState` is the envelope's `page` bag (see `viewState.js`) — the only
+ * place a page may invent a key. Everything else is captured identically on
+ * every page, which is what makes a saved view, a shareable link and a guard
+ * one concept instead of eleven.
*/
export function useTableChrome({
columns,
@@ -39,8 +43,11 @@ export function useTableChrome({
setHiddenKeys,
groupBy = null,
setGroupBy,
- extraState,
- applyExtra,
+ pageState,
+ applyPage,
+ // Legacy top-level view keys -> their name inside `page`, for pages that
+ // persisted a key before the envelope existed. e.g. { filters: 'serverFilters' }.
+ rename,
}) {
const [filters, setFilters] = useState(NO_FILTERS);
const [columnOrder, setColumnOrder] = useState(null);
@@ -104,21 +111,20 @@ export function useTableChrome({
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.
+ // The envelope. The column rules are `columnFilters`, never `filters`:
+ // three pages persist a `filters` key of their own meaning a SERVER-side
+ // query pair, and sharing the name is what made their presets cross-wire.
const capture = useCallback(() => ({
- ...(extraState || {}),
sorts,
hiddenKeys,
groupBy,
columnFilters: filters,
columnOrder,
- }), [extraState, sorts, hiddenKeys, groupBy, filters, columnOrder]);
+ page: pageState || {},
+ }), [sorts, hiddenKeys, groupBy, filters, columnOrder, pageState]);
const apply = useCallback((state) => {
- applyExtra?.(state);
+ applyPage?.(state.page || {});
if (Array.isArray(state.sorts)) setSorts?.(state.sorts);
if (Array.isArray(state.hiddenKeys)) setHiddenKeys?.(state.hiddenKeys);
if (state.groupBy !== undefined) setGroupBy?.(state.groupBy);
@@ -127,19 +133,16 @@ export function useTableChrome({
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 });
-
- // ?view=<slug> / ?v=<encoded> <-> the active view, both directions. Applying
- // a link goes through the SAME `apply` the picker uses, so a shared link and
- // a click can never drift apart.
- const { copyLink } = useViewLink({ views, apply, capture, enabled: !!viewPageKey });
+ }, [applyPage, setSorts, setHiddenKeys, setGroupBy]);
- const createView = useCallback((name, fromCurrent) => {
- if (!fromCurrent) api.resetToView();
- return views.saveView(name);
- }, [api, views]);
+ const { views, copyLink, createView } = useGridViews({
+ page: viewPageKey,
+ builtinViews,
+ capture,
+ apply,
+ rename,
+ resetToView: api.resetToView,
+ });
return {
cfg,
diff --git a/frontend/src/components/ds/grid/useTableViews.js b/frontend/src/components/ds/grid/useTableViews.js
new file mode 100644
index 00000000..02c0845e
Binary files /dev/null and b/frontend/src/components/ds/grid/useTableViews.js differ
diff --git a/frontend/src/components/ds/grid/viewState.js b/frontend/src/components/ds/grid/viewState.js
new file mode 100644
index 00000000..ab2ea463
--- /dev/null
+++ b/frontend/src/components/ds/grid/viewState.js
@@ -0,0 +1,181 @@
+// The saved-view envelope — ONE state shape for every list page.
+//
+// {
+// sorts: [{ key, direction }], // ordered; sorts[0] is primary
+// hiddenKeys: ['next_run'], // set semantics, order is noise
+// columnOrder: ['name','status'] | null, // null = the page's natural order
+// groupBy: 'status' | null,
+// columnFilters: { match:'all', rules:[…] }, // CLIENT-side column rules
+// page: { … }, // the ONLY per-page bag
+// }
+//
+// Why an envelope at all: before this, each page named its own view state, and
+// `filters` meant column rules on three pages and a SERVER-side query object on
+// three others. Every addition to the shared chrome — the `columnFilters` key,
+// shareable links, the pre-restore guard — then had to be re-remembered per
+// page, and each one was in fact missed on at least one of them.
+//
+// Now the common half is common by construction and the private half is
+// namespaced, so a page can never again collide with the chrome.
+//
+// Nothing here is lossy for state written by older builds: `toEnvelope` folds
+// any unrecognised top-level key into `page`, so saved views persisted in the
+// flat shape keep working without a migration pass over the database.
+
+export const NO_COLUMN_FILTERS = { match: 'all', rules: [] };
+
+// The keys that mean the same thing on every page. Everything else is `page`.
+export const COMMON_KEYS = ['sorts', 'hiddenKeys', 'columnOrder', 'groupBy', 'columnFilters'];
+
+export function emptyViewState() {
+ return {
+ sorts: [],
+ hiddenKeys: [],
+ columnOrder: null,
+ groupBy: null,
+ columnFilters: { match: 'all', rules: [] },
+ page: {},
+ };
+}
+
+function normalizeFilters(value) {
+ if (!value || typeof value !== 'object' || !Array.isArray(value.rules)) {
+ return { match: 'all', rules: [] };
+ }
+ return { match: value.match === 'any' ? 'any' : 'all', rules: value.rules };
+}
+
+/**
+ * Coerce any saved-view state — current envelope, legacy flat shape, or a raw
+ * DataGrid cfg — into the envelope.
+ *
+ * `rename` maps a LEGACY top-level key to its name inside `page`, which is how
+ * the pages whose `filters` meant a server-side query move to `serverFilters`
+ * without orphaning views their users already saved:
+ *
+ * toEnvelope(saved, { rename: { filters: 'serverFilters' } })
+ */
+export function toEnvelope(state, { rename } = {}) {
+ const out = emptyViewState();
+ if (!state || typeof state !== 'object') return out;
+
+ // An explicit `page` bag always wins over a legacy top-level key of the
+ // same name — the newer write is the one that meant it.
+ const page = { ...(state.page && typeof state.page === 'object' ? state.page : {}) };
+
+ for (const [key, value] of Object.entries(state)) {
+ if (key === 'page' || value === undefined) continue;
+ if (COMMON_KEYS.includes(key)) {
+ out[key] = value;
+ continue;
+ }
+ const target = rename?.[key] ?? key;
+ if (!(target in page)) page[target] = value;
+ }
+
+ out.sorts = Array.isArray(out.sorts) ? out.sorts : [];
+ out.hiddenKeys = Array.isArray(out.hiddenKeys) ? out.hiddenKeys : [];
+ out.columnOrder = Array.isArray(out.columnOrder) ? out.columnOrder : null;
+ out.groupBy = out.groupBy ?? null;
+ out.columnFilters = normalizeFilters(out.columnFilters);
+ out.page = page;
+ return out;
+}
+
+// ---------------------------------------------------------------- comparison
+
+// Canonical form for equality: object keys sorted, undefined dropped. Rule
+// `id`s are stripped — they are generated per rule instance, so two identical
+// filter sets would otherwise never compare equal and the view would read as
+// permanently unsaved.
+function canon(value, dropId = false) {
+ if (Array.isArray(value)) return value.map((v) => canon(v, dropId));
+ if (value && typeof value === 'object') {
+ const out = {};
+ for (const key of Object.keys(value).sort()) {
+ if (key === 'id' && dropId) continue;
+ if (value[key] === undefined) continue;
+ out[key] = canon(value[key], dropId);
+ }
+ return out;
+ }
+ return value;
+}
+
+/**
+ * Is the live state the same view as the saved one? Both sides go through
+ * `toEnvelope` first, so a view saved in the flat shape does not read as dirty
+ * the instant it is applied.
+ */
+export function sameViewState(a, b, { rename } = {}) {
+ const left = toEnvelope(a, { rename });
+ const right = toEnvelope(b, { rename });
+ for (const side of [left, right]) {
+ side.hiddenKeys = [...side.hiddenKeys].sort();
+ side.columnFilters = {
+ match: side.columnFilters.match,
+ rules: side.columnFilters.rules.map((r) => canon(r, true)),
+ };
+ }
+ return JSON.stringify(canon(left)) === JSON.stringify(canon(right));
+}
+
+// ------------------------------------------------------- DataGrid cfg bridge
+
+// DataGrid keeps its chrome in one `cfg` object: `cols` is the visible columns
+// IN ORDER (so "move left" is a splice), and `sort` is a single level. The
+// envelope keeps `hiddenKeys` + `columnOrder` + `sorts[]` because that is what
+// <DataTable> pages own. Both are mapped here rather than in either hook, so a
+// Domains view and a Cron view are the same JSON and a link from one page's
+// chrome means the same thing on the other's.
+
+export function cfgToEnvelope(cfg, allKeys = []) {
+ const cols = Array.isArray(cfg?.cols) ? cfg.cols : [];
+ return {
+ sorts: cfg?.sort?.key ? [{ key: cfg.sort.key, direction: cfg.sort.dir || 'asc' }] : [],
+ hiddenKeys: allKeys.filter((k) => !cols.includes(k)),
+ columnOrder: cols.length ? cols : null,
+ groupBy: cfg?.group ?? null,
+ columnFilters: normalizeFilters(cfg?.filters),
+ page: { density: cfg?.density ?? 'cozy', sub: cfg?.sub ?? [] },
+ };
+}
+
+/**
+ * Envelope -> DataGrid cfg. `allKeys` is every column key in the page's natural
+ * order; it is what lets `columnOrder` + `hiddenKeys` rebuild `cols`, and what
+ * makes a column added in a later release show up in a view saved before it
+ * existed instead of silently vanishing.
+ */
+export function envelopeToCfg(state, allKeys = [], fallback = {}) {
+ // A view saved by an older build is the raw cfg itself.
+ const isLegacyCfg = state && typeof state === 'object'
+ && Array.isArray(state.cols) && !Array.isArray(state.sorts);
+ if (isLegacyCfg) {
+ return {
+ cols: state.cols,
+ sort: state.sort || { key: null, dir: 'asc' },
+ group: state.group ?? null,
+ filters: normalizeFilters(state.filters),
+ density: state.density || 'cozy',
+ sub: state.sub || [],
+ };
+ }
+
+ const env = toEnvelope(state);
+ const order = env.columnOrder?.length ? env.columnOrder : allKeys;
+ const ordered = [
+ ...order.filter((k) => allKeys.includes(k)),
+ ...allKeys.filter((k) => !order.includes(k)),
+ ];
+ return {
+ cols: ordered.filter((k) => !env.hiddenKeys.includes(k)),
+ sort: env.sorts[0]
+ ? { key: env.sorts[0].key, dir: env.sorts[0].direction || 'asc' }
+ : { key: null, dir: 'asc' },
+ group: env.groupBy,
+ filters: env.columnFilters,
+ density: env.page.density ?? fallback.density ?? 'cozy',
+ sub: env.page.sub ?? fallback.sub ?? [],
+ };
+}
diff --git a/frontend/src/components/layouts/ResourceListPage.jsx b/frontend/src/components/layouts/ResourceListPage.jsx
index b40a74c8..3eade819 100644
--- a/frontend/src/components/layouts/ResourceListPage.jsx
+++ b/frontend/src/components/layouts/ResourceListPage.jsx
@@ -4,15 +4,12 @@ import { cn } from '@/lib/utils';
import { SegControl, DataTableFooter, ListToolbar } from '@/components/ds';
import {
GridViewPicker, GridChips, GridFilterButton, GridToolsMenu, GridFilterDrawer,
- withInferredTypes,
+ useTableChrome,
} from '@/components/ds/grid';
import EmptyState from '../EmptyState';
import DataTable from '@/components/ds/DataTable';
import { useTableSort } from '@/hooks/useTableSort';
import { useColumnVisibility } from '@/hooks/useColumnVisibility';
-import { useTableViews } from '@/hooks/useTableViews';
-
-const NO_FILTERS = { match: 'all', rules: [] };
// Shared chrome for resource list pages (Services, Servers, …): the status
// filter + search toolbar, sort & column menus, the DataTable with a standard
@@ -115,7 +112,7 @@ export default function ResourceListPage({
const { sorts, setSorts } = useTableSort({
storageKey: storageKey ? `${storageKey}-sort` : undefined,
});
- const { hiddenKeys, setHiddenKeys, toggleColumn, showAllColumns } = useColumnVisibility({
+ const { hiddenKeys, setHiddenKeys } = useColumnVisibility({
storageKey: storageKey ? `${storageKey}-cols` : undefined,
});
const [groupBy, setGroupBy] = useState(() => {
@@ -157,26 +154,6 @@ export default function ResourceListPage({
}
};
- // Per-column filter rules + column order, owned here rather than by
- // DataTable, so they can be captured into a saved view and mirrored in the
- // chip bar and the drawer. DataTable stays the renderer.
- const [columnFilters, setColumnFilters] = useState(NO_FILTERS);
- const [columnOrder, setColumnOrder] = useState(null);
- const [filterDrawerOpen, setFilterDrawerOpen] = useState(false);
-
- const putColumnRule = useCallback((key, rule) => {
- setColumnFilters((prev) => ({
- ...prev,
- rules: [...prev.rules.filter((r) => r.field !== key), ...(rule ? [rule] : [])],
- }));
- }, []);
- const removeRule = useCallback(
- (id) => setColumnFilters((prev) => ({ ...prev, rules: prev.rules.filter((r) => r.id !== id) })),
- [],
- );
- const clearRules = useCallback(() => setColumnFilters((prev) => ({ ...prev, rules: [] })), []);
- const setMatch = useCallback((match) => setColumnFilters((prev) => ({ ...prev, match })), []);
-
const changeView = (next) => {
setView(next);
if (!viewStorageKey) return;
@@ -192,101 +169,46 @@ export default function ResourceListPage({
[items, pageSize],
);
- // ---- adapter: present this page's state as a DataGrid cfg/api pair ------
- // The grid chrome (view picker, chip bar, filter drawer, tools menu) is
- // written against ONE serialisable cfg. This page predates that and keeps
- // sorts[]/hiddenKeys/groupBy instead. Rather than fork the chrome — which
- // is exactly the per-page duplication this layout exists to stop — adapt
- // the state here, once, and every list page built on this wrapper gets the
- // same chrome for free.
- // Types are inferred HERE, once, so the chip bar, the drawer and the table
- // all reason about the same column list. Inferring separately inside
- // DataTable would leave the drawer looking up OPS[undefined] for a rule the
- // header menu had just created.
- const typedColumns = useMemo(() => withInferredTypes(columns, items), [columns, items]);
-
- const orderedColumns = useMemo(() => {
- if (!columnOrder?.length) return typedColumns;
- const byKey = new Map(typedColumns.map((c) => [c.key, c]));
- const moved = columnOrder.map((k) => byKey.get(k)).filter(Boolean);
- return [...moved, ...typedColumns.filter((c) => !columnOrder.includes(c.key))];
- }, [typedColumns, columnOrder]);
-
- const gridCfg = 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: columnFilters,
- // DataTable auto-sizes its columns and has no sub-detail line, so the
- // drawer's density / row-detail panes are switched off below rather
- // than shown as controls that do nothing.
- density: 'cozy',
- sub: [],
- }), [orderedColumns, hiddenKeys, sorts, groupBy, columnFilters]);
+ // The chrome — view picker, chip bar, filter drawer, tools menu, shareable
+ // links — comes from the shared hook rather than being adapted again here.
+ // This wrapper used to carry its own copy of that adapter, which is how it
+ // ended up the one chrome host with no `useViewLink`: every list page built
+ // on it silently had no shareable links at all.
+ //
+ // `page` is the envelope's per-page bag (see grid/viewState.js). The status
+ // filter, the search box and the page size are this wrapper's own state —
+ // everything else is captured identically to every other list page.
+ const pageState = useMemo(
+ () => ({ filter: activeFilter, search: searchTerm, pageSize }),
+ [activeFilter, searchTerm, pageSize],
+ );
- const gridApi = useMemo(() => ({
- setRules: (rules) => setColumnFilters((prev) => ({ ...prev, rules })),
- setMatch,
- addRule: (cols) => {
- const first = cols.find((c) => c.type && c.filterable !== false);
- if (!first) return;
- setColumnFilters((prev) => ({
- ...prev,
- rules: [...prev.rules, {
- id: `r${prev.rules.length}${Math.random().toString(36).slice(2, 6)}`,
- field: first.key,
- op: first.type === 'enum' ? 'any' : first.type === 'bool' ? 'is' : first.type === 'num' ? 'lt' : 'contains',
- value: first.type === 'enum' ? [] : first.type === 'bool' ? true : '',
- }],
- }));
- },
- removeRule,
- setColumnOrder,
- toggleColumn: (key) => toggleColumn(key),
- setSub: () => {},
- setDensity: () => {},
- resetToView: () => { clearRules(); showAllColumns(); setColumnOrder(null); },
- }), [setMatch, removeRule, toggleColumn, clearRules, showAllColumns]);
+ const applyPage = useCallback((saved) => {
+ if (saved.filter !== undefined) onFilterChange?.(saved.filter);
+ if (saved.search !== undefined) onSearchChange?.(saved.search);
+ if (saved.pageSize !== undefined) changePageSize(saved.pageSize);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [onFilterChange, onSearchChange]);
- // Saved views: capture/apply the full table chrome state (status filter,
- // search, sort levels, hidden columns, page size). The filter and search
- // values themselves are owned by the page — apply() routes through its
- // setters so a view can drive them.
- const captureView = useCallback(() => ({
- filter: activeFilter,
- search: searchTerm,
+ const chrome = useTableChrome({
+ columns,
+ rows: items,
+ viewPageKey,
+ builtinViews,
+ noun,
sorts,
+ setSorts,
hiddenKeys,
- pageSize,
+ setHiddenKeys,
groupBy,
- // `columnFilters`, not `filters`: `filters` is already this component's
- // prop name for the SegControl options, and other pages capture a
- // `filters` key of their own with a different shape.
- columnFilters,
- columnOrder,
- }), [activeFilter, searchTerm, sorts, hiddenKeys, pageSize, groupBy, columnFilters, columnOrder]);
-
- const applyView = useCallback((state) => {
- if (state.filter !== undefined) onFilterChange?.(state.filter);
- if (state.search !== undefined) onSearchChange?.(state.search);
- if (Array.isArray(state.sorts)) setSorts(state.sorts);
- if (Array.isArray(state.hiddenKeys)) setHiddenKeys(state.hiddenKeys);
- if (state.pageSize !== undefined) changePageSize(state.pageSize);
- if (state.groupBy !== undefined) changeGroupBy(state.groupBy);
- // A preset that sets no rules must CLEAR the live ones, or switching
- // views leaves the previous view's filters silently applied.
- setColumnFilters(state.columnFilters ?? NO_FILTERS);
- setColumnOrder(state.columnOrder ?? null);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [onFilterChange, onSearchChange, setSorts, setHiddenKeys]);
-
- const tableViews = useTableViews({
- page: viewPageKey,
- builtinViews,
- capture: captureView,
- apply: applyView,
+ setGroupBy: changeGroupBy,
+ pageState,
+ applyPage,
});
+ const orderedColumns = chrome.columns;
+ const tableViews = chrome.views;
+
if (loading) {
// Same wrapper as the loaded state below. A skeleton that renders
// outside the page's padded container occupies a different box than the
@@ -330,10 +252,7 @@ export default function ResourceListPage({
views={tableViews}
label={noun}
total={`${items.length} of ${resolvedTotal} ${noun}`}
- onCreate={(name, fromCurrent) => {
- if (!fromCurrent) gridApi.resetToView();
- tableViews.saveView(name);
- }}
+ onCreate={chrome.createView}
/>
)}
<ListToolbar
@@ -349,20 +268,14 @@ export default function ResourceListPage({
{view === 'list' && (
<>
<GridFilterButton
- count={columnFilters.rules.length}
- onClick={() => setFilterDrawerOpen(true)}
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
/>
<GridToolsMenu
- cfg={gridCfg}
- columns={orderedColumns}
- rows={items}
+ {...chrome.toolsProps}
selectedRows={selectable && selectedIds
? items.filter((i) => selectedIds.has(i[keyField]))
: []}
- viewName={tableViews.activeView?.name || noun}
- noun={noun}
- onReset={gridApi.resetToView}
- showDensity={false}
/>
</>
)}
@@ -401,15 +314,7 @@ export default function ResourceListPage({
{toolbarExtra}
</ListToolbar>
- {view === 'list' && (
- <GridChips
- cfg={gridCfg}
- columns={orderedColumns}
- onRemove={removeRule}
- onClear={clearRules}
- onMatchChange={setMatch}
- />
- )}
+ {view === 'list' && <GridChips {...chrome.chipProps} />}
{items.length === 0 ? (
<EmptyState
@@ -432,20 +337,15 @@ export default function ResourceListPage({
) : (
<div className="wp-list__card">
<DataTable
+ {...chrome.tableProps}
columns={orderedColumns}
data={pagedItems}
keyField={keyField}
sortable={sortable}
sorts={sorts}
onSortsChange={setSorts}
- hiddenKeys={hiddenKeys}
- onHiddenKeysChange={setHiddenKeys}
groupBy={groupBy}
onGroupByChange={changeGroupBy}
- filters={columnFilters}
- onFiltersChange={setColumnFilters}
- columnOrder={columnOrder}
- onColumnOrderChange={setColumnOrder}
selectable={selectable}
selectedKeys={selectable && selectedIds ? [...selectedIds] : undefined}
onToggleRow={selectable ? onToggleSelect : undefined}
@@ -486,17 +386,7 @@ export default function ResourceListPage({
)}
</div>
)}
- <GridFilterDrawer
- open={filterDrawerOpen}
- onOpenChange={setFilterDrawerOpen}
- columns={orderedColumns}
- rows={items}
- cfg={gridCfg}
- grid={gridApi}
- noun={noun}
- showRowDetail={false}
- showDensity={false}
- />
+ <GridFilterDrawer {...chrome.drawerProps} />
{children}
</div>
diff --git a/frontend/src/hooks/useTableViews.js b/frontend/src/hooks/useTableViews.js
index 49078676..9ee64b9e 100644
Binary files a/frontend/src/hooks/useTableViews.js and b/frontend/src/hooks/useTableViews.js differ
diff --git a/frontend/src/pages/CronJobs.jsx b/frontend/src/pages/CronJobs.jsx
index 9bd944db..c4bc14cb 100644
--- a/frontend/src/pages/CronJobs.jsx
+++ b/frontend/src/pages/CronJobs.jsx
@@ -160,9 +160,9 @@ const CronJobs = () => {
// Shared list chrome: view picker + filter chips + filter drawer + tools,
// driven off this page's existing sorts/hiddenKeys state. Same hook every
// other list page uses, so /cron looks and behaves like /domains.
- const extraViewState = useMemo(() => ({ search }), [search]);
- const applyExtraViewState = useCallback((state) => {
- if (state.search !== undefined) setSearch(state.search);
+ const viewPageState = useMemo(() => ({ search }), [search]);
+ const applyViewPageState = useCallback((saved) => {
+ if (saved.search !== undefined) setSearch(saved.search);
}, []);
// Drawer + modal states
@@ -412,8 +412,8 @@ const CronJobs = () => {
setSorts,
hiddenKeys,
setHiddenKeys,
- extraState: extraViewState,
- applyExtra: applyExtraViewState,
+ pageState: viewPageState,
+ applyPage: applyViewPageState,
});
return (
diff --git a/frontend/src/pages/Servers.jsx b/frontend/src/pages/Servers.jsx
index 611b1370..69b309aa 100644
--- a/frontend/src/pages/Servers.jsx
+++ b/frontend/src/pages/Servers.jsx
@@ -248,16 +248,16 @@ const Servers = () => {
// Page-owned view state (the status segment, the group select, search);
// useTableChrome owns the rest — sorts, hidden columns, grouping, column
// rules and order — and gives back the shared list chrome.
- const extraViewState = useMemo(() => ({
+ const viewPageState = useMemo(() => ({
status: selectedStatus,
group: selectedGroup,
search: searchTerm,
}), [selectedStatus, selectedGroup, searchTerm]);
- const applyExtraViewState = useCallback((state) => {
- if (state.status !== undefined) setSelectedStatus(state.status);
- if (state.group !== undefined) setSelectedGroup(state.group);
- if (state.search !== undefined) setSearchTerm(state.search);
+ const applyViewPageState = useCallback((saved) => {
+ if (saved.status !== undefined) setSelectedStatus(saved.status);
+ if (saved.group !== undefined) setSelectedGroup(saved.group);
+ if (saved.search !== undefined) setSearchTerm(saved.search);
}, []);
const loadData = useCallback(async () => {
@@ -333,8 +333,8 @@ const Servers = () => {
setHiddenKeys,
groupBy,
setGroupBy: changeGroupBy,
- extraState: extraViewState,
- applyExtra: applyExtraViewState,
+ pageState: viewPageState,
+ applyPage: applyViewPageState,
});
if (loading) {