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(views): scope shareable-link params, so two tables can share a route

Juan Denis5b63620ad639
diff --git a/frontend/src/components/ds/grid/__tests__/viewLinks.test.mjs b/frontend/src/components/ds/grid/__tests__/viewLinks.test.mjs
new file mode 100644
index 00000000..4efeec4f
--- /dev/null
+++ b/frontend/src/components/ds/grid/__tests__/viewLinks.test.mjs
@@ -0,0 +1,138 @@
+// Proving tests for scoped shareable links.
+//
+// A tab that renders TWO tables (Security's allowlist + blocklist, Settings'
+// three API tables) has two chrome instances on ONE route. Every link param is
+// a global name — `view`, `sort`, `hide`, `f` — so without a scope the second
+// table reads the first's sort and then overwrites its `?view=`.
+//
+// The invariant that matters most here is the FIRST one: an unscoped call must
+// produce and accept byte-identical URLs to before scopes existed, or every
+// single-table page's links silently change meaning.
+//
+// Run: node --test src/components/ds/grid/__tests__/viewLinks.test.mjs
+import test from 'node:test';
+import assert from 'node:assert/strict';
+
+import {
+ stateToParams, paramsToState, readViewParams, withViewParam, copyableLink, scopedKey,
+} from '../viewLinks.js';
+
+const STATE = {
+ sorts: [{ key: 'name', direction: 'asc' }],
+ hiddenKeys: ['comment'],
+ columnOrder: null,
+ groupBy: null,
+ columnFilters: { match: 'any', rules: [{ id: 'r1', field: 'status', op: 'any', value: ['active', 'banned'] }] },
+ page: { search: 'nginx' },
+};
+
+// ---------------------------------------------------------------- unscoped
+
+test('unscoped params are unchanged by the introduction of scopes', () => {
+ const qs = stateToParams(STATE).toString();
+ assert.match(qs, /(^|&)sort=name%3Aasc(&|$)/);
+ assert.match(qs, /(^|&)hide=comment(&|$)/);
+ assert.match(qs, /(^|&)match=any(&|$)/);
+ assert.match(qs, /(^|&)f=status%3Aany%3Aactive%2Cbanned(&|$)/);
+ // No key carries a prefix.
+ for (const key of new URLSearchParams(qs).keys()) {
+ assert.ok(!key.includes('.'), `unscoped key should not be namespaced: ${key}`);
+ }
+});
+
+test('the page bag is flattened into the URL', () => {
+ // The envelope nests page-owned primitives under `page`. Objects are
+ // skipped by design, so without flattening a shared link silently stopped
+ // carrying the search box and status filter it used to carry.
+ const qs = stateToParams(STATE).toString();
+ assert.match(qs, /(^|&)search=nginx(&|$)/);
+ assert.equal(paramsToState(new URLSearchParams(qs)).search, 'nginx');
+});
+
+test('scopedKey is identity without a scope', () => {
+ assert.equal(scopedKey('', 'view'), 'view');
+ assert.equal(scopedKey(undefined, 'sort'), 'sort');
+ assert.equal(scopedKey('allowlist', 'view'), 'allowlist.view');
+});
+
+// ------------------------------------------------------------------ scoped
+
+test('a scope round-trips its own state', () => {
+ const qs = stateToParams(STATE, 'allowlist').toString();
+ const back = paramsToState(new URLSearchParams(qs), 'allowlist');
+ assert.deepEqual(back.sorts, STATE.sorts);
+ assert.deepEqual(back.hiddenKeys, STATE.hiddenKeys);
+ assert.equal(back.columnFilters.match, 'any');
+ assert.deepEqual(back.columnFilters.rules[0].value, ['active', 'banned']);
+ assert.equal(back.search, 'nginx');
+});
+
+test('two scopes on one query string do not see each other', () => {
+ const allow = stateToParams({ sorts: [{ key: 'ip', direction: 'asc' }] }, 'allowlist');
+ const block = stateToParams({ sorts: [{ key: 'added', direction: 'desc' }] }, 'blocklist');
+ const merged = new URLSearchParams(`${allow}&${block}`);
+
+ assert.deepEqual(paramsToState(merged, 'allowlist').sorts, [{ key: 'ip', direction: 'asc' }]);
+ assert.deepEqual(paramsToState(merged, 'blocklist').sorts, [{ key: 'added', direction: 'desc' }]);
+});
+
+test('an unscoped reader ignores another table scoped params', () => {
+ // Otherwise `blocklist.status=banned` would be swallowed as page state and
+ // pushed through the unscoped table's own setters.
+ const merged = new URLSearchParams('blocklist.sort=added:desc&blocklist.status=banned');
+ assert.equal(paramsToState(merged), null);
+});
+
+test('readViewParams reads only its own scope handle', () => {
+ const search = '?allowlist.view=trusted&blocklist.view=recent';
+ assert.deepEqual(
+ { kind: readViewParams(search, 'allowlist').kind, slug: readViewParams(search, 'allowlist').slug },
+ { kind: 'saved', slug: 'trusted' },
+ );
+ assert.equal(readViewParams(search, 'blocklist').slug, 'recent');
+ // And an unscoped reader finds neither.
+ assert.equal(readViewParams(search).kind, null);
+});
+
+test('writing one scope handle leaves the other alone', () => {
+ const next = withViewParam('?allowlist.view=trusted&blocklist.view=recent', 'flagged', 'blocklist');
+ assert.equal(next.get('allowlist.view'), 'trusted');
+ assert.equal(next.get('blocklist.view'), 'flagged');
+});
+
+test('clearing one scope handle leaves the other alone', () => {
+ const next = withViewParam('?allowlist.view=trusted&blocklist.view=recent', null, 'blocklist');
+ assert.equal(next.get('allowlist.view'), 'trusted');
+ assert.equal(next.get('blocklist.view'), null);
+});
+
+test('the legacy ?v= blob is only read unscoped', () => {
+ // Nothing has generated one since before scopes existed, so a scoped table
+ // must not adopt a blob that was written for the page as a whole.
+ const search = '?v=eyJzb3J0cyI6W119';
+ assert.equal(readViewParams(search, 'allowlist').kind, null);
+});
+
+test('copyableLink namespaces the handle it puts on the clipboard', () => {
+ const url = copyableLink({
+ pathname: '/security/ip-lists',
+ view: { name: 'Trusted', slug: 'trusted' },
+ isDirty: false,
+ state: {},
+ origin: 'https://panel.example.com',
+ scope: 'allowlist',
+ });
+ assert.equal(url, 'https://panel.example.com/security/ip-lists?allowlist.view=trusted');
+});
+
+test('a dirty scoped view copies its state, still namespaced', () => {
+ const url = copyableLink({
+ pathname: '/security/ip-lists',
+ view: { name: 'Trusted', slug: 'trusted' },
+ isDirty: true,
+ state: { sorts: [{ key: 'ip', direction: 'asc' }] },
+ origin: 'https://panel.example.com',
+ scope: 'allowlist',
+ });
+ assert.equal(url, 'https://panel.example.com/security/ip-lists?allowlist.sort=ip%3Aasc');
+});
diff --git a/frontend/src/components/ds/grid/index.js b/frontend/src/components/ds/grid/index.js
index af1e776e..6e161ca5 100644
--- a/frontend/src/components/ds/grid/index.js
+++ b/frontend/src/components/ds/grid/index.js
@@ -29,7 +29,8 @@ export {
} from './viewState';
export {
encodeState, decodeState, readViewParams, resolveView, copyableLink,
- handleFor, slugify as slugifyViewName, VIEW_PARAM, STATE_PARAM,
+ handleFor, slugify as slugifyViewName, scopedKey, stateToParams, paramsToState,
+ VIEW_PARAM, STATE_PARAM,
} from './viewLinks';
export {
OPS, FIELD_TYPES, opLabel, ruleId, columnLabel, fieldValue,
diff --git a/frontend/src/components/ds/grid/useGridViews.js b/frontend/src/components/ds/grid/useGridViews.js
index f61216dd..618d515b 100644
--- a/frontend/src/components/ds/grid/useGridViews.js
+++ b/frontend/src/components/ds/grid/useGridViews.js
@@ -26,6 +26,10 @@ import { emptyViewState, sameViewState, toEnvelope } from './viewState';
*/
export function useGridViews({
page, builtinViews = [], capture, apply, rename, resetToView,
+ // URL namespace for the shareable-link params. Required when a route
+ // renders MORE THAN ONE table — without it both write `?view=`/`?sort=`
+ // and each clobbers the other. Empty = today's unprefixed names.
+ urlScope = '',
// Optional pre-pass run on any INBOUND state (a built-in preset, a saved
// view, a shared link) before it is normalised. A host whose older states
// used a private shape converts it here — without this, `toEnvelope` files
@@ -83,6 +87,7 @@ export function useGridViews({
apply: applyEnvelope,
capture: captureEnvelope,
enabled: !!page,
+ scope: urlScope,
});
// "Save current view…" with the checkbox cleared means a CLEAN view, not
diff --git a/frontend/src/components/ds/grid/useTableChrome.js b/frontend/src/components/ds/grid/useTableChrome.js
index 87e25260..17d15358 100644
--- a/frontend/src/components/ds/grid/useTableChrome.js
+++ b/frontend/src/components/ds/grid/useTableChrome.js
@@ -48,6 +48,10 @@ export function useTableChrome({
// Legacy top-level view keys -> their name inside `page`, for pages that
// persisted a key before the envelope existed. e.g. { filters: 'serverFilters' }.
rename,
+ // URL namespace for shareable links. Pass one whenever a ROUTE renders more
+ // than one table — a tab with an allowlist AND a blocklist, say — or the two
+ // chrome instances fight over `?view=`/`?sort=` and swap each other's state.
+ urlScope,
}) {
const [filters, setFilters] = useState(NO_FILTERS);
const [columnOrder, setColumnOrder] = useState(null);
@@ -141,6 +145,7 @@ export function useTableChrome({
capture,
apply,
rename,
+ urlScope,
resetToView: api.resetToView,
});
diff --git a/frontend/src/components/ds/grid/useViewLink.js b/frontend/src/components/ds/grid/useViewLink.js
index 5aa94700..27cba3d5 100644
--- a/frontend/src/components/ds/grid/useViewLink.js
+++ b/frontend/src/components/ds/grid/useViewLink.js
@@ -17,7 +17,7 @@ import {
* `apply` is the same adapter the view picker uses, so a link and a click go
* through one code path.
*/
-export function useViewLink({ views, apply, capture, enabled = true }) {
+export function useViewLink({ views, apply, capture, enabled = true, scope = '' }) {
const location = useLocation();
const [searchParams, setSearchParams] = useSearchParams();
const appliedFromUrl = useRef(false);
@@ -29,7 +29,7 @@ export function useViewLink({ views, apply, capture, enabled = true }) {
// ---- inbound ---------------------------------------------------------
useEffect(() => {
if (!enabled || appliedFromUrl.current) return;
- const request = readViewParams(location.search);
+ const request = readViewParams(location.search, scope);
if (!request.kind) { appliedFromUrl.current = true; return; }
if (request.kind === 'state') {
@@ -65,7 +65,7 @@ export function useViewLink({ views, apply, capture, enabled = true }) {
lastHandle.current = handle;
// replace, not push: flipping through views should not fill the back
// button with table states.
- setSearchParams(withViewParam(location.search, handle), { replace: true });
+ setSearchParams(withViewParam(location.search, handle, scope), { replace: true });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [enabled, activeView]);
@@ -75,6 +75,7 @@ export function useViewLink({ views, apply, capture, enabled = true }) {
view: activeView,
isDirty: views?.isDirty,
state: capture ? capture() : {},
+ scope,
});
try {
await navigator.clipboard.writeText(url);
@@ -82,7 +83,7 @@ export function useViewLink({ views, apply, capture, enabled = true }) {
} catch {
return { url, copied: false }; // clipboard blocked: hand back the URL
}
- }, [location.pathname, activeView, views?.isDirty, capture]);
+ }, [location.pathname, activeView, views?.isDirty, capture, scope]);
return { copyLink, searchParams };
}
diff --git a/frontend/src/components/ds/grid/viewLinks.js b/frontend/src/components/ds/grid/viewLinks.js
index 7fde49b4..d7853676 100644
--- a/frontend/src/components/ds/grid/viewLinks.js
+++ b/frontend/src/components/ds/grid/viewLinks.js
@@ -21,6 +21,18 @@ export const VIEW_PARAM = 'view';
export const STATE_PARAM = 'v';
export const BUILTIN_PREFIX = 'builtin:';
+// ---------------------------------------------------------------- scoping
+// Every param below (`view`, `sort`, `hide`, `f`, …) is a GLOBAL name, which is
+// fine while one table owns the route. It stops being fine on a tab that
+// renders two: Security's IP lists (allowlist + blocklist) and Settings' API
+// tab (three tables) would both read and write the same keys, so the
+// allowlist's sort would arrive as the blocklist's.
+//
+// A `scope` prefixes every key with `<scope>.`, making each table's link its
+// own. NO scope keeps today's names byte-for-byte, so every single-table page
+// produces and accepts exactly the URLs it always did.
+export const scopedKey = (scope, key) => (scope ? `${scope}.${key}` : key);
+
export const slugify = (value) => (
(value || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 140)
);
@@ -38,7 +50,8 @@ export const slugify = (value) => (
// — `groupby` rather than `group` because pages already own a `group` param.
// Every other key in the state is a page-owned primitive (status, search,
// filter, …) and keeps its own name.
-const RESERVED = new Set(['sort', 'cols', 'hide', 'groupby', 'match', 'f', VIEW_PARAM, STATE_PARAM]);
+const RESERVED_KEYS = ['sort', 'cols', 'hide', 'groupby', 'match', 'f', VIEW_PARAM, STATE_PARAM];
+const reservedFor = (scope) => new Set(RESERVED_KEYS.map((k) => scopedKey(scope, k)));
const encodeRule = (r) => {
const value = Array.isArray(r.value) ? r.value.join(',') : String(r.value ?? '');
@@ -66,36 +79,42 @@ const decodeRule = (raw, index) => {
};
/** State -> readable URLSearchParams. */
-export function stateToParams(state = {}) {
+export function stateToParams(state = {}, scope = '') {
const params = new URLSearchParams();
+ const reserved = reservedFor(scope);
+ const key = (k) => scopedKey(scope, k);
const {
- sorts, hiddenKeys, columnOrder, groupBy, columnFilters, ...rest
+ sorts, hiddenKeys, columnOrder, groupBy, columnFilters, page, ...rest
} = state;
- if (sorts?.length) params.set('sort', sorts.map((s) => `${s.key}:${s.direction}`).join(','));
- if (columnOrder?.length) params.set('cols', columnOrder.join(','));
- if (hiddenKeys?.length) params.set('hide', hiddenKeys.join(','));
- if (groupBy) params.set('groupby', groupBy);
+ if (sorts?.length) params.set(key('sort'), sorts.map((s) => `${s.key}:${s.direction}`).join(','));
+ if (columnOrder?.length) params.set(key('cols'), columnOrder.join(','));
+ if (hiddenKeys?.length) params.set(key('hide'), hiddenKeys.join(','));
+ if (groupBy) params.set(key('groupby'), groupBy);
if (columnFilters?.rules?.length) {
- if (columnFilters.match && columnFilters.match !== 'all') params.set('match', columnFilters.match);
- columnFilters.rules.forEach((r) => params.append('f', encodeRule(r)));
+ if (columnFilters.match && columnFilters.match !== 'all') params.set(key('match'), columnFilters.match);
+ columnFilters.rules.forEach((r) => params.append(key('f'), encodeRule(r)));
}
// Page-owned primitives keep their own names, so ?status=online reads as
// what it is. Objects are skipped: they belong in a saved view, not a URL.
- Object.entries(rest).forEach(([key, value]) => {
- if (RESERVED.has(key) || value == null || value === '') return;
+ // The envelope's `page` bag is flattened here for the same reason — its
+ // primitives are exactly those page-owned values.
+ Object.entries({ ...(page || {}), ...rest }).forEach(([k, value]) => {
+ if (reserved.has(scopedKey(scope, k)) || value == null || value === '') return;
if (typeof value === 'object') return;
- params.set(key, String(value));
+ params.set(key(k), String(value));
});
return params;
}
/** Readable URLSearchParams -> state. Tolerant: junk is dropped, not fatal. */
-export function paramsToState(params) {
+export function paramsToState(params, scope = '') {
const state = {};
+ const reserved = reservedFor(scope);
+ const key = (k) => scopedKey(scope, k);
let touched = false;
- const sort = params.get('sort');
+ const sort = params.get(key('sort'));
if (sort) {
const sorts = sort.split(',').map((part) => {
const [key, dir] = part.split(':');
@@ -103,21 +122,33 @@ export function paramsToState(params) {
}).filter(Boolean);
if (sorts.length) { state.sorts = sorts; touched = true; }
}
- const cols = params.get('cols');
+ const cols = params.get(key('cols'));
if (cols) { state.columnOrder = cols.split(',').filter(Boolean); touched = true; }
- const hide = params.get('hide');
+ const hide = params.get(key('hide'));
if (hide) { state.hiddenKeys = hide.split(',').filter(Boolean); touched = true; }
- if (params.has('groupby')) { state.groupBy = params.get('groupby') || null; touched = true; }
+ if (params.has(key('groupby'))) { state.groupBy = params.get(key('groupby')) || null; touched = true; }
- const rules = params.getAll('f').map(decodeRule).filter(Boolean);
+ const rules = params.getAll(key('f')).map(decodeRule).filter(Boolean);
if (rules.length) {
- state.columnFilters = { match: params.get('match') === 'any' ? 'any' : 'all', rules };
+ state.columnFilters = { match: params.get(key('match')) === 'any' ? 'any' : 'all', rules };
touched = true;
}
- for (const [key, value] of params.entries()) {
- if (RESERVED.has(key)) continue;
- state[key] = value;
+ const prefix = scope ? `${scope}.` : '';
+ for (const [name, value] of params.entries()) {
+ if (reserved.has(name)) continue;
+ if (scope) {
+ // Only this table's params. Another table's `blocklist.status` is
+ // none of our business.
+ if (!name.startsWith(prefix)) continue;
+ state[name.slice(prefix.length)] = value;
+ } else {
+ // Unscoped: skip anything that LOOKS scoped, so an unscoped table
+ // sharing a route with a scoped one does not swallow its keys as
+ // page state. Page-owned primitives never contain a dot.
+ if (name.includes('.')) continue;
+ state[name] = value;
+ }
touched = true;
}
return touched ? state : null;
@@ -155,27 +186,30 @@ export function decodeState(encoded) {
// ---------------------------------------------------------------- reading
/** What a URL is asking for: {kind:'saved'|'builtin'|'state'|null, …}. */
-export function readViewParams(search) {
+export function readViewParams(search, scope = '') {
const params = new URLSearchParams(search);
// A saved-view handle wins: it is the more specific request, and it can be
// combined with readable params to mean "that view, tweaked".
- const handle = params.get(VIEW_PARAM);
+ const handle = params.get(scopedKey(scope, VIEW_PARAM));
if (handle) {
const base = handle.startsWith(BUILTIN_PREFIX)
? { kind: 'builtin', slug: handle.slice(BUILTIN_PREFIX.length) }
: { kind: 'saved', slug: handle };
- return { ...base, overrides: paramsToState(params) };
+ return { ...base, overrides: paramsToState(params, scope) };
}
- const readable = paramsToState(params);
+ const readable = paramsToState(params, scope);
if (readable) return { kind: 'state', state: readable };
- // Legacy: links shared before the readable format existed.
- const encoded = params.get(STATE_PARAM);
- if (encoded) {
- const state = decodeState(encoded);
- if (state) return { kind: 'state', state };
+ // Legacy: links shared before the readable format existed. Never scoped —
+ // nothing has generated one since before scopes existed.
+ if (!scope) {
+ const encoded = params.get(STATE_PARAM);
+ if (encoded) {
+ const state = decodeState(encoded);
+ if (state) return { kind: 'state', state };
+ }
}
return { kind: null };
}
@@ -208,20 +242,24 @@ export function handleFor(view) {
* send the recipient somewhere different from what the sender is looking at,
* so the state travels instead.
*/
-export function copyableLink({ pathname, view, isDirty, state, origin }) {
+export function copyableLink({ pathname, view, isDirty, state, origin, scope = '' }) {
const base = `${origin ?? window.location.origin}${pathname}`;
const handle = !isDirty && handleFor(view);
- if (handle) return `${base}?${VIEW_PARAM}=${encodeURIComponent(handle)}`;
- const params = stateToParams(state);
+ if (handle) return `${base}?${scopedKey(scope, VIEW_PARAM)}=${encodeURIComponent(handle)}`;
+ const params = stateToParams(state, scope);
const qs = params.toString();
return qs ? `${base}?${qs}` : base;
}
-/** Replace the view params on a URL without disturbing the rest of the query. */
-export function withViewParam(search, handle) {
+/**
+ * Replace the view params on a URL without disturbing the rest of the query —
+ * including, on a multi-table tab, the OTHER tables' scoped params.
+ */
+export function withViewParam(search, handle, scope = '') {
const params = new URLSearchParams(search);
- params.delete(STATE_PARAM);
- if (handle) params.set(VIEW_PARAM, handle);
- else params.delete(VIEW_PARAM);
+ if (!scope) params.delete(STATE_PARAM);
+ const name = scopedKey(scope, VIEW_PARAM);
+ if (handle) params.set(name, handle);
+ else params.delete(name);
return params;
}