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(frontend): add resource options adapter

Juan Deniscfcc49adc212
diff --git a/frontend/src/hooks/useResourceOptions.js b/frontend/src/hooks/useResourceOptions.js
new file mode 100644
index 00000000..db6593cf
--- /dev/null
+++ b/frontend/src/hooks/useResourceOptions.js
@@ -0,0 +1,91 @@
+import { useCallback, useMemo, useState } from 'react';
+
+import { useAuth } from '../contexts/AuthContext';
+import { useServerQuery } from './useServerQuery';
+import api from '../services/api';
+import { getFavorites } from '../utils/recents';
+import {
+ getRecentResourceKeys,
+ groupResourceOptions,
+ normalizeResourceRef,
+ recordRecentResource,
+} from '../utils/resourceRefs';
+
+const stableList = (values) => [...new Set(values || [])].map(String).sort();
+
+export function useResourceOptions({
+ types,
+ scope = {},
+ capabilities = [],
+ query = '',
+ cursor = null,
+ limit = 20,
+ enabled = true,
+} = {}) {
+ const { user } = useAuth();
+ const [recentRevision, setRecentRevision] = useState(0);
+ const normalizedTypes = stableList(types);
+ const normalizedCapabilities = stableList(capabilities);
+ const normalizedScope = {
+ workspaceId: scope.workspaceId ?? scope.workspace_id ?? null,
+ projectId: scope.projectId ?? scope.project_id ?? null,
+ environmentId: scope.environmentId ?? scope.environment_id ?? null,
+ };
+ const normalizedQuery = String(query || '').trim();
+
+ const request = useServerQuery(
+ [
+ 'resource-options',
+ normalizedTypes.join(','),
+ normalizedScope.workspaceId,
+ normalizedScope.projectId,
+ normalizedScope.environmentId,
+ normalizedCapabilities.join(','),
+ normalizedQuery,
+ cursor,
+ limit,
+ ],
+ ({ signal }) => api.searchResources({
+ types: normalizedTypes,
+ scope: normalizedScope,
+ capabilities: normalizedCapabilities,
+ query: normalizedQuery,
+ cursor,
+ limit,
+ }, { signal }),
+ {
+ enabled: enabled && normalizedTypes.length > 0,
+ staleTime: 15_000,
+ },
+ );
+
+ const options = useMemo(
+ () => (request.data?.results || []).map(normalizeResourceRef).filter(Boolean),
+ [request.data],
+ );
+ const recentKeys = useMemo(
+ () => getRecentResourceKeys(user?.id, normalizedTypes),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [user?.id, normalizedTypes.join(','), recentRevision],
+ );
+ const groups = useMemo(
+ () => groupResourceOptions(options, {
+ favoriteEntries: getFavorites(),
+ recentKeys,
+ }),
+ [options, recentKeys],
+ );
+ const recordSelection = useCallback((resource) => {
+ recordRecentResource(resource, user?.id);
+ setRecentRevision((revision) => revision + 1);
+ return resource;
+ }, [user?.id]);
+
+ return {
+ ...request,
+ options,
+ groups,
+ nextCursor: request.data?.nextCursor ?? null,
+ recordSelection,
+ };
+}
diff --git a/frontend/src/services/__tests__/resourceSearch.test.mjs b/frontend/src/services/__tests__/resourceSearch.test.mjs
new file mode 100644
index 00000000..35892e17
--- /dev/null
+++ b/frontend/src/services/__tests__/resourceSearch.test.mjs
@@ -0,0 +1,27 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { buildResourceSearchQuery } from '../api/search.js';
+
+test('serializes the ResourcePicker filters without duplicating values', () => {
+ const query = buildResourceSearchQuery({
+ query: ' nyc ',
+ types: ['server', 'server', 'project'],
+ scope: { workspaceId: 4, projectId: 9 },
+ capabilities: ['docker', 'systemd', 'docker'],
+ cursor: 'djE6MjA',
+ limit: 40,
+ });
+
+ assert.equal(
+ query,
+ 'q=nyc&types=server%2Cproject&workspace_id=4&project_id=9&capabilities=docker%2Csystemd&cursor=djE6MjA&limit=40',
+ );
+});
+
+test('omits all-workspace and empty optional filters', () => {
+ assert.equal(
+ buildResourceSearchQuery({ types: ['environment'], scope: { workspaceId: 'all' } }),
+ 'types=environment&limit=20',
+ );
+});
diff --git a/frontend/src/services/api/search.js b/frontend/src/services/api/search.js
index 5a1d6337..2420c7cb 100644
--- a/frontend/src/services/api/search.js
+++ b/frontend/src/services/api/search.js
@@ -1,10 +1,58 @@
// Unified entity omnisearch (plan 41, Phase 4).
export async function search(q) {
const response = await this.request(`/search?q=${encodeURIComponent(q)}`);
+ return normalizeSearchResponse(response);
+}
+
+const appendCsv = (params, key, values) => {
+ const normalized = [...new Set((values || []).map(String).map((value) => value.trim()).filter(Boolean))];
+ if (normalized.length) params.set(key, normalized.join(','));
+};
+
+const appendScope = (params, scope = {}) => {
+ const fields = [
+ ['workspace_id', scope.workspaceId ?? scope.workspace_id],
+ ['project_id', scope.projectId ?? scope.project_id],
+ ['environment_id', scope.environmentId ?? scope.environment_id],
+ ];
+ fields.forEach(([key, value]) => {
+ if (value !== undefined && value !== null && value !== '' && value !== 'all') {
+ params.set(key, String(value));
+ }
+ });
+};
+
+export function buildResourceSearchQuery({
+ query = '',
+ types = [],
+ scope = {},
+ capabilities = [],
+ cursor = null,
+ limit = 20,
+} = {}) {
+ const params = new URLSearchParams();
+ const normalizedQuery = String(query || '').trim();
+ if (normalizedQuery) params.set('q', normalizedQuery);
+ appendCsv(params, 'types', types);
+ appendScope(params, scope);
+ appendCsv(params, 'capabilities', capabilities);
+ if (cursor) params.set('cursor', String(cursor));
+ if (limit != null) params.set('limit', String(limit));
+ return params.toString();
+}
+
+const normalizeSearchResponse = (response) => ({
+ ...response,
+ // The backend keeps `results` during the public API migration. Prefer
+ // the canonical envelope here so the browser exercises the new path.
+ results: response?.data ?? response?.results ?? [],
+});
+
+export async function searchResources(params, options = {}) {
+ const query = buildResourceSearchQuery(params);
+ const response = await this.request(`/search?${query}`, options);
return {
- ...response,
- // The backend keeps `results` during the public API migration. Prefer
- // the canonical envelope here so the browser exercises the new path.
- results: response?.data ?? response?.results ?? [],
+ ...normalizeSearchResponse(response),
+ nextCursor: response?.meta?.next_cursor ?? null,
};
}
diff --git a/frontend/src/utils/__tests__/resourceRefs.test.mjs b/frontend/src/utils/__tests__/resourceRefs.test.mjs
new file mode 100644
index 00000000..8d1dd831
--- /dev/null
+++ b/frontend/src/utils/__tests__/resourceRefs.test.mjs
@@ -0,0 +1,73 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ getRecentResourceKeys,
+ groupResourceOptions,
+ normalizeResourceRef,
+ recordRecentResource,
+} from '../resourceRefs.js';
+
+const memoryStorage = () => {
+ const entries = new Map();
+ return {
+ getItem: (key) => entries.get(key) ?? null,
+ setItem: (key, value) => entries.set(key, String(value)),
+ };
+};
+
+const server = (id, label = `server-${id}`) => ({
+ type: 'server',
+ id,
+ label,
+ sublabel: 'online',
+ path: `/servers/${id}`,
+ scope: { workspace_id: 4, project_id: null, environment_id: null },
+ status: 'online',
+ capabilities: ['systemd', 'docker', 'docker'],
+});
+
+test('normalizes API rows into the camel-case ResourceRef contract', () => {
+ assert.deepEqual(normalizeResourceRef(server(12)), {
+ type: 'server',
+ id: '12',
+ label: 'server-12',
+ sublabel: 'online',
+ path: '/servers/12',
+ scope: { workspaceId: 4, projectId: null, environmentId: null },
+ status: 'online',
+ capabilities: ['docker', 'systemd'],
+ });
+ assert.equal(normalizeResourceRef({ type: 'server' }), null);
+});
+
+test('recent selections stay isolated by user and capped per resource type', () => {
+ const storage = memoryStorage();
+ for (let id = 1; id <= 7; id += 1) recordRecentResource(server(id), 41, storage);
+ recordRecentResource({ ...server(30), type: 'project' }, 41, storage);
+ recordRecentResource(server(99), 52, storage);
+
+ assert.deepEqual(
+ getRecentResourceKeys(41, ['server'], storage),
+ ['server:7', 'server:6', 'server:5', 'server:4', 'server:3'],
+ );
+ assert.deepEqual(getRecentResourceKeys(52, ['server'], storage), ['server:99']);
+ assert.deepEqual(getRecentResourceKeys(41, ['project'], storage), ['project:30']);
+});
+
+test('favorites and recents are presentation groups, not resource mutations', () => {
+ const options = [server('a'), server('b'), server('c')].map(normalizeResourceRef);
+ const before = structuredClone(options);
+ const groups = groupResourceOptions(options, {
+ favoriteEntries: [{ type: 'server', id: 'b' }],
+ recentKeys: ['server:a', 'server:b'],
+ });
+
+ assert.deepEqual(groups.map((group) => [group.id, group.options.map((item) => item.id)]), [
+ ['favorites', ['b']],
+ ['recent', ['a']],
+ ['results', ['c']],
+ ]);
+ assert.deepEqual(options, before);
+ assert.equal('favorite' in options[1], false);
+});
diff --git a/frontend/src/utils/resourceRefs.js b/frontend/src/utils/resourceRefs.js
new file mode 100644
index 00000000..120ed5cf
--- /dev/null
+++ b/frontend/src/utils/resourceRefs.js
@@ -0,0 +1,99 @@
+const STORAGE_PREFIX = 'serverkit:resource-recents';
+const MAX_PER_TYPE = 5;
+
+const normalizeScopeValue = (value) => {
+ if (value === undefined || value === null || value === '') return null;
+ const number = Number(value);
+ return Number.isFinite(number) ? number : null;
+};
+
+export function normalizeResourceRef(row) {
+ if (!row || row.type == null || row.id == null || !row.label || !row.path) return null;
+ const scope = row.scope || {};
+ return {
+ type: String(row.type),
+ id: String(row.id),
+ label: String(row.label),
+ sublabel: String(row.sublabel || ''),
+ path: String(row.path),
+ scope: {
+ workspaceId: normalizeScopeValue(scope.workspace_id ?? scope.workspaceId),
+ projectId: normalizeScopeValue(scope.project_id ?? scope.projectId),
+ environmentId: normalizeScopeValue(scope.environment_id ?? scope.environmentId),
+ },
+ status: row.status == null ? null : String(row.status),
+ capabilities: [...new Set((row.capabilities || []).map(String))].sort(),
+ };
+}
+
+export const resourceKey = (resource) => `${resource.type}:${resource.id}`;
+
+const storageKey = (userId) => `${STORAGE_PREFIX}:${userId}`;
+
+const resolveStorage = (storage) => {
+ if (storage) return storage;
+ if (typeof localStorage !== 'undefined') return localStorage;
+ return null;
+};
+
+const load = (userId, storage) => {
+ if (userId == null) return [];
+ try {
+ const raw = resolveStorage(storage)?.getItem(storageKey(userId));
+ const parsed = raw ? JSON.parse(raw) : [];
+ return Array.isArray(parsed) ? parsed : [];
+ } catch {
+ return [];
+ }
+};
+
+export function getRecentResourceKeys(userId, types = [], storage) {
+ const allowedTypes = new Set(types || []);
+ return load(userId, storage)
+ .filter((entry) => !allowedTypes.size || allowedTypes.has(entry.type))
+ .map((entry) => `${entry.type}:${entry.id}`);
+}
+
+export function recordRecentResource(resource, userId, storage) {
+ const normalized = normalizeResourceRef(resource);
+ const target = resolveStorage(storage);
+ if (!normalized || userId == null || !target) return;
+
+ const entry = {
+ type: normalized.type,
+ id: normalized.id,
+ at: Date.now(),
+ };
+ const existing = load(userId, target)
+ .filter((candidate) => resourceKey(candidate) !== resourceKey(entry));
+ const next = [entry, ...existing].filter((candidate, index, all) => (
+ all.slice(0, index + 1).filter((item) => item.type === candidate.type).length
+ <= MAX_PER_TYPE
+ ));
+ try {
+ target.setItem(storageKey(userId), JSON.stringify(next));
+ } catch {
+ // Selection history is a convenience; storage failures never block it.
+ }
+}
+
+export function groupResourceOptions(options, { favoriteEntries = [], recentKeys = [] } = {}) {
+ const favorites = new Set(favoriteEntries.map(resourceKey));
+ const recents = new Set(recentKeys);
+ const favoriteOptions = [];
+ const recentOptions = [];
+ const remainingOptions = [];
+
+ options.forEach((option) => {
+ const key = resourceKey(option);
+ if (favorites.has(key)) favoriteOptions.push(option);
+ else if (recents.has(key)) recentOptions.push(option);
+ else remainingOptions.push(option);
+ });
+
+ return [
+ favoriteOptions.length && { id: 'favorites', options: favoriteOptions },
+ recentOptions.length && { id: 'recent', options: recentOptions },
+ remainingOptions.length && { id: 'results', options: remainingOptions },
+ ].filter(Boolean);
+}