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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(views): shareable links -- ?view=<slug> for saved, ?v=<encoded> for ad-hoc
Juan Denis48d2a371bca2
diff --git a/frontend/src/components/ds/grid/GridToolsMenu.jsx b/frontend/src/components/ds/grid/GridToolsMenu.jsxindex a52a87b9..bed0c5c0 100644--- a/frontend/src/components/ds/grid/GridToolsMenu.jsx+++ b/frontend/src/components/ds/grid/GridToolsMenu.jsx@@ -1,5 +1,5 @@import { useState } from 'react';-import { MoreVertical, Download, RefreshCw, History, Check, Rows2, Rows3 } from 'lucide-react';+import { MoreVertical, Download, RefreshCw, History, Check, Link2, Rows2, Rows3 } from 'lucide-react';import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';import { cn } from '@/lib/utils';import { byKey, exportRows } from './fields';@@ -10,7 +10,7 @@ import { byKey, exportRows } from './fields';// which is the whole point of putting search there.export function GridToolsMenu({cfg, columns, rows, selectedRows = [], viewName, noun = 'rows',- onRefresh, onReset, onDensity, onExported,+ onRefresh, onReset, onDensity, onExported, onCopyLink,// 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,@@ -18,6 +18,7 @@ export function GridToolsMenu({const [open, setOpen] = useState(false);const [pane, setPane] = useState('root'); // root | exportconst [scope, setScope] = useState('view');+ const [copied, setCopied] = useState(null);const [allCols, setAllCols] = useState(false);const map = byKey(columns);@@ -50,6 +51,22 @@ export function GridToolsMenu({<PopoverContent align="end" sideOffset={6} className="ui-popover-panel sk-gridmenu">{pane === 'root' ? (<>+ {onCopyLink && (+ <button+ type="button"+ className="sk-gridmenu__opt"+ onClick={async () => {+ const res = await onCopyLink();+ setCopied(res?.copied ? 'ok' : 'fail');+ setTimeout(() => setCopied(null), 1800);+ }}+ >+ {copied === 'ok' ? <Check size={13} /> : <Link2 size={13} />}+ {copied === 'ok' ? 'Link copied'+ : copied === 'fail' ? 'Copy failed — check permissions'+ : 'Copy link to this view'}+ </button>+ )}<button type="button" className="sk-gridmenu__opt" onClick={() => setPane('export')}><Download size={13} />Export…</button>diff --git a/frontend/src/components/ds/grid/index.js b/frontend/src/components/ds/grid/index.jsindex 1004ca30..35e8bfdd 100644--- a/frontend/src/components/ds/grid/index.js+++ b/frontend/src/components/ds/grid/index.js@@ -18,6 +18,11 @@ export { GridFilterButton } from './GridFilterButton';export { useGridConfig, makeGridConfig, GRID_DEFAULTS } from './useGridConfig';export { useGridRows } from './useGridRows';export { useTableChrome } from './useTableChrome';+export { useViewLink } from './useViewLink';+export {+ encodeState, decodeState, readViewParams, resolveView, copyableLink,+ handleFor, slugify as slugifyViewName, VIEW_PARAM, STATE_PARAM,+} from './viewLinks';export {OPS, FIELD_TYPES, opLabel, ruleId, columnLabel, fieldValue,applyFilters, applySort, groupRows, ruleText, exportRows,diff --git a/frontend/src/components/ds/grid/useTableChrome.js b/frontend/src/components/ds/grid/useTableChrome.jsindex bddcaceb..a7c72a07 100644--- a/frontend/src/components/ds/grid/useTableChrome.js+++ b/frontend/src/components/ds/grid/useTableChrome.js@@ -1,5 +1,6 @@import { useCallback, useMemo, useState } from 'react';import useTableViews from '@/hooks/useTableViews';+import useViewLink from './useViewLink';import { OPS, emptyValueFor, isFilterable, ruleId, withInferredTypes } from './fields';const NO_FILTERS = { match: 'all', rules: [] };@@ -130,6 +131,11 @@ export function useTableChrome({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 });+const createView = useCallback((name, fromCurrent) => {if (!fromCurrent) api.resetToView();return views.saveView(name);@@ -145,6 +151,7 @@ export function useTableChrome({drawerOpen,setDrawerOpen,createView,+ copyLink,// spread straight onto the matching componentstableProps: {@@ -180,6 +187,7 @@ export function useTableChrome({viewName: views.activeView?.name || noun,noun,onReset: api.resetToView,+ onCopyLink: copyLink,showDensity: false,},};diff --git a/frontend/src/components/ds/grid/useViewLink.js b/frontend/src/components/ds/grid/useViewLink.jsnew file mode 100644index 00000000..ef62c21d--- /dev/null+++ b/frontend/src/components/ds/grid/useViewLink.js@@ -0,0 +1,82 @@+import { useCallback, useEffect, useRef } from 'react';+import { useLocation, useSearchParams } from 'react-router-dom';+import {+ copyableLink, handleFor, readViewParams, resolveView, withViewParam,+} from './viewLinks';++/**+ * Keeps a list page's URL and its active view in sync, both ways.+ *+ * inbound — ?view=<slug> applies that saved/built-in view once the views+ * have loaded; ?v=<encoded> applies a self-contained state.+ * outbound — switching views rewrites ?view=; the address bar is then a+ * shareable link with no extra step.+ *+ * const { copyLink } = useViewLink({ views, apply, capture });+ *+ * `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 }) {+ const location = useLocation();+ const [searchParams, setSearchParams] = useSearchParams();+ const appliedFromUrl = useRef(false);+ const lastHandle = useRef(null);++ const activeView = views?.activeView || null;+ const loading = views?.loading;++ // ---- inbound ---------------------------------------------------------+ useEffect(() => {+ if (!enabled || appliedFromUrl.current) return;+ const request = readViewParams(location.search);+ if (!request.kind) { appliedFromUrl.current = true; return; }++ if (request.kind === 'state') {+ apply(request.state);+ appliedFromUrl.current = true;+ return;+ }+ // A slug needs the saved views to have arrived before it can resolve;+ // wait rather than silently deciding the link is broken.+ if (loading) return;+ const match = resolveView(request, {+ builtinViews: views?.builtinViews || [],+ userViews: views?.userViews || [],+ });+ if (match) views.applyView(match);+ appliedFromUrl.current = true;+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [enabled, loading, location.search]);++ // ---- outbound --------------------------------------------------------+ useEffect(() => {+ if (!enabled || !appliedFromUrl.current) return;+ const handle = handleFor(activeView);+ if (handle === lastHandle.current) return;+ 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 });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [enabled, activeView]);++ const copyLink = useCallback(async () => {+ const url = copyableLink({+ pathname: location.pathname,+ view: activeView,+ isDirty: views?.isDirty,+ state: capture ? capture() : {},+ });+ try {+ await navigator.clipboard.writeText(url);+ return { url, copied: true };+ } catch {+ return { url, copied: false }; // clipboard blocked: hand back the URL+ }+ }, [location.pathname, activeView, views?.isDirty, capture]);++ return { copyLink, searchParams };+}++export default useViewLink;diff --git a/frontend/src/components/ds/grid/viewLinks.js b/frontend/src/components/ds/grid/viewLinks.jsnew file mode 100644index 00000000..27518b46--- /dev/null+++ b/frontend/src/components/ds/grid/viewLinks.js@@ -0,0 +1,120 @@+// Shareable links for list views.+//+// Two shapes, because "share this view" and "look at what I'm looking at" are+// different requests:+//+// /domains?view=ssl-expiring a SAVED view, by slug. Short, memorable,+// and always reflects the view's current+// definition — edit the view, the link follows.+//+// /domains?v=<encoded> whatever is on screen RIGHT NOW, including+// unsaved tweaks. Self-contained: it needs no+// server lookup and no permission on anyone+// else's saved views, so it works for a+// colleague who has never opened the page.+//+// `copyableLink()` picks: a clean saved view gets the slug, anything dirty or+// unsaved gets the encoded state. Built-in views use `builtin:<slug>` so they+// resolve without a database row.++export const VIEW_PARAM = 'view';+export const STATE_PARAM = 'v';+export const BUILTIN_PREFIX = 'builtin:';++export const slugify = (value) => (+ (value || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 140)+);++// ---------------------------------------------------------------- encoding+// base64url over JSON. Not encryption and not meant to be opaque — just a+// URL-safe envelope, so a link survives being pasted into chat clients that+// mangle raw braces and quotes.+export function encodeState(state) {+ try {+ const json = JSON.stringify(state);+ const bytes = new TextEncoder().encode(json);+ let binary = '';+ bytes.forEach((b) => { binary += String.fromCharCode(b); });+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+ } catch {+ return null;+ }+}++export function decodeState(encoded) {+ if (!encoded) return null;+ try {+ const b64 = encoded.replace(/-/g, '+').replace(/_/g, '/');+ const binary = atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4));+ const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));+ const parsed = JSON.parse(new TextDecoder().decode(bytes));+ // A link is untrusted input: only take an object, never an array or a+ // primitive that would then be spread into page state.+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;+ } catch {+ return null;+ }+}++// ---------------------------------------------------------------- reading+/** What a URL is asking for: {kind:'saved'|'builtin'|'state'|null, …}. */+export function readViewParams(search) {+ const params = new URLSearchParams(search);+ const encoded = params.get(STATE_PARAM);+ if (encoded) {+ const state = decodeState(encoded);+ if (state) return { kind: 'state', state };+ }+ const handle = params.get(VIEW_PARAM);+ if (handle) {+ return handle.startsWith(BUILTIN_PREFIX)+ ? { kind: 'builtin', slug: handle.slice(BUILTIN_PREFIX.length) }+ : { kind: 'saved', slug: handle };+ }+ return { kind: null };+}++/** Find the view a URL handle refers to, across built-ins and saved views. */+export function resolveView({ kind, slug }, { builtinViews = [], userViews = [] }) {+ if (kind === 'builtin') return builtinViews.find((v) => slugify(v.name) === slug) || null;+ if (kind === 'saved') {+ return userViews.find((v) => v.slug === slug)+ // Fall back to the name so a link still works for a view saved+ // before slugs existed, or one the server has not backfilled.+ || userViews.find((v) => slugify(v.name) === slug)+ || builtinViews.find((v) => slugify(v.name) === slug)+ || null;+ }+ return null;+}++// ---------------------------------------------------------------- writing+export function handleFor(view) {+ if (!view) return null;+ return view.builtin ? `${BUILTIN_PREFIX}${slugify(view.name)}` : (view.slug || slugify(view.name));+}++/**+ * The link to put on the clipboard.+ *+ * A saved view that has NOT been modified is worth sharing by handle. The+ * moment it is dirty — or there is no active view at all — the handle would+ * 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 }) {+ const base = `${origin ?? window.location.origin}${pathname}`;+ const handle = !isDirty && handleFor(view);+ if (handle) return `${base}?${VIEW_PARAM}=${encodeURIComponent(handle)}`;+ const encoded = encodeState(state);+ return encoded ? `${base}?${STATE_PARAM}=${encoded}` : base;+}++/** Replace the view params on a URL without disturbing the rest of the query. */+export function withViewParam(search, handle) {+ const params = new URLSearchParams(search);+ params.delete(STATE_PARAM);+ if (handle) params.set(VIEW_PARAM, handle);+ else params.delete(VIEW_PARAM);+ return params;+}