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
refactor(frontend): Phase 1 foundation — styling policy, ScheduleCard hooks fix, shared utils
Juan Denis128a5333d700
diff --git a/AGENTS.md b/AGENTS.mdindex 96643fba..33d0c66c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -102,6 +102,45 @@ ServerKit deploys on Linux (bare metal, VPS, or Docker). Development may happen- Minimal, focused diffs — don't silently refactor surrounding code- Branch naming: `feature/`, `fix/`, `docs/`, `refactor/` prefixes+## Styling Standard++**SCSS only.** ServerKit standardizes on its internal SCSS design system. Do not+add Tailwind utility classes, CSS-in-JS, or new inline styles.++- **Forbidden**: Tailwind utility strings (`flex gap-3 px-4`, `text-sm`,+ `bg-card`, `border-border`, `rounded-full`, etc.), `tailwindcss`/`tailwind-merge`+ imports, and CSS-in-JS. Inline `style={{ ... }}` is allowed **only** for true+ dynamic values (a width computed from a prop, chart dimensions).+- **Class namespaces**:+ - `.sk-*` — redesign "infra console" design-system primitives.+ - Legacy BEM (`.page-container`, `.card`, `.modal-*`, `.form-*`,+ `.empty-state__title`) — allowed during migration; deprecate gradually.+ - No utility-class strings.+- **Shared primitives** (reuse before rewrite):+ - Buttons — `styles/components/_buttons.scss` (`.btn`, `.btn-primary`,+ `.btn-danger`, `.btn-ghost`, `.btn-sm`, `.btn-icon`).+ - Cards — `styles/components/_cards.scss` (`.card`, `.card-header`,+ `.stat-strip`).+ - Modals — `styles/components/_modals.scss` (`.modal-overlay`, `.modal`,+ `.modal-lg`, `.modal-header`, `.modal-body`, `.modal-actions`).+ - Forms — `styles/components/_forms.scss` (`.form-group`, `.form-field`,+ `.form-row`, `.error-message`); prefer the `FormField` component.+ - Tables — `.sk-dtable` in `styles/components/_design-system.scss`; prefer the+ `components/ds/DataTable.jsx` primitive.+ - Pills/badges — `.sk-pill`, `.sk-state`, `.sk-tag`.+ - Tokens — `styles/_variables.scss`, `styles/_theme-variables.scss`.+- **Shared utilities** (reuse before rewrite):+ - `utils/formatBytes.js` — byte/size formatting (no local `formatBytes`/+ `formatSize`/`formatMemory`).+ - `utils/time.js` — `timeAgo` (compact) and `formatRelativeTime` (verbose).+ - `utils/clipboard.js` + `hooks/useClipboard.js` — copy-to-clipboard with+ toast feedback (no raw `navigator.clipboard.writeText` call sites).+- **Fonts**: `IBM Plex Sans` / `IBM Plex Mono` (the established SCSS stack).++**Migration status**: Tailwind removal is in progress (see+`docs/plans/FRONTEND_UX_TAILWIND_CLEANUP_PLAN.md`). Do not introduce new Tailwind+usage; convert any you touch to the SCSS equivalents above.+## Adding a New Feature (Full Stack)1. **Model**: Add SQLAlchemy model in `backend/app/models/`diff --git a/frontend/src/components/backups/ScheduleCard.jsx b/frontend/src/components/backups/ScheduleCard.jsxindex 5d73c04c..3cb557bd 100644--- a/frontend/src/components/backups/ScheduleCard.jsx+++ b/frontend/src/components/backups/ScheduleCard.jsx@@ -81,35 +81,25 @@ function buildCron(frequency, time, days) {}const ScheduleCard = ({ policy, remoteConfigured, onSave, saving }) => {- if (!policy) {- return (- <div className="app-panel schedule-card">- <div className="app-panel-header">- <Calendar size={16} />- <span>Schedule</span>- </div>- <div className="app-panel-body">- <p className="app-panel-hint">Loading backup schedule...</p>- </div>- </div>- );- }-- const initial = deriveFromCron(policy.schedule_cron);+ // All hooks run unconditionally, before any early return (Rules of Hooks).+ // The form is only shown once a policy exists, so the seed values used when+ // `policy` is null are throwaway and get re-seeded by the effect on load.+ const initial = deriveFromCron(policy?.schedule_cron);const [frequency, setFrequency] = useState(initial.frequency);const [time, setTime] = useState(initial.time);const [days, setDays] = useState(initial.days);- const [retentionCount, setRetentionCount] = useState(String(policy.retention_count));- const [retentionDays, setRetentionDays] = useState(String(policy.retention_days));- const [fullEvery, setFullEvery] = useState(String(policy.full_every_n_days));- const [compression, setCompression] = useState(policy.compression);- const [remoteCopy, setRemoteCopy] = useState(!!policy.remote_copy);+ const [retentionCount, setRetentionCount] = useState(String(policy?.retention_count ?? ''));+ const [retentionDays, setRetentionDays] = useState(String(policy?.retention_days ?? ''));+ const [fullEvery, setFullEvery] = useState(String(policy?.full_every_n_days ?? ''));+ const [compression, setCompression] = useState(policy?.compression ?? 'balanced');+ const [remoteCopy, setRemoteCopy] = useState(!!policy?.remote_copy);// Re-seed the form when the saved policy changes (e.g. external reload after// a successful save). Keyed on the persisted values so it only fires when// the source of truth actually moves, not on every render.useEffect(() => {+ if (!policy) return;const next = deriveFromCron(policy.schedule_cron);setFrequency(next.frequency);setTime(next.time);@@ -120,16 +110,32 @@ const ScheduleCard = ({ policy, remoteConfigured, onSave, saving }) => {setCompression(policy.compression);setRemoteCopy(!!policy.remote_copy);}, [- policy.schedule_cron,- policy.retention_count,- policy.retention_days,- policy.full_every_n_days,- policy.compression,- policy.remote_copy,+ policy,+ policy?.schedule_cron,+ policy?.retention_count,+ policy?.retention_days,+ policy?.full_every_n_days,+ policy?.compression,+ policy?.remote_copy,]);const currentCron = useMemo(() => buildCron(frequency, time, days), [frequency, time, days]);+ // Conditional render AFTER all hooks have run.+ if (!policy) {+ return (+ <div className="app-panel schedule-card">+ <div className="app-panel-header">+ <Calendar size={16} />+ <span>Schedule</span>+ </div>+ <div className="app-panel-body">+ <p className="app-panel-hint">Loading backup schedule...</p>+ </div>+ </div>+ );+ }+const toggleDay = (i) => {setDays((prev) =>prev.includes(i) ? prev.filter((d) => d !== i) : [...prev, i].sort((a, b) => a - b)diff --git a/frontend/src/hooks/useClipboard.js b/frontend/src/hooks/useClipboard.jsnew file mode 100644index 00000000..2fedc5e6--- /dev/null+++ b/frontend/src/hooks/useClipboard.js@@ -0,0 +1,44 @@+import { useCallback, useRef, useState } from 'react';+import { useToast } from '@/contexts/ToastContext';+import { copyToClipboard } from '@/utils/clipboard';++// Copy-to-clipboard hook with toast feedback and a transient `copied` flag.+//+// const { copy, copied } = useClipboard();+// <button onClick={() => copy(apiKey)}>Copy</button>+//+// const { copy } = useClipboard({ successMessage: 'Token copied' });+// copy(token);+// copy(value, 'Custom one-off message'); // per-call override+//+// `copied` flips true for `resetDelay` ms after a successful copy so the+// trigger can show a check icon without each caller wiring its own timer.+export function useClipboard({+ successMessage = 'Copied to clipboard',+ errorMessage = 'Failed to copy',+ resetDelay = 2000,+} = {}) {+ const toast = useToast();+ const [copied, setCopied] = useState(false);+ const timer = useRef(null);++ const copy = useCallback(+ async (text, message) => {+ const ok = await copyToClipboard(text);+ if (ok) {+ setCopied(true);+ if (message !== null) toast.success(message ?? successMessage);+ if (timer.current) clearTimeout(timer.current);+ timer.current = setTimeout(() => setCopied(false), resetDelay);+ } else {+ toast.error(errorMessage);+ }+ return ok;+ },+ [toast, successMessage, errorMessage, resetDelay]+ );++ return { copy, copied };+}++export default useClipboard;diff --git a/frontend/src/utils/clipboard.js b/frontend/src/utils/clipboard.jsnew file mode 100644index 00000000..e543ed26--- /dev/null+++ b/frontend/src/utils/clipboard.js@@ -0,0 +1,38 @@+// Canonical copy-to-clipboard helper.+//+// Wraps navigator.clipboard.writeText with a legacy execCommand fallback for+// insecure contexts / older browsers, so call sites don't each reinvent it.+// Returns true on success, false on failure (never throws).++export async function copyToClipboard(text) {+ const value = String(text ?? '');++ // Preferred path: async Clipboard API (requires a secure context).+ if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {+ try {+ await navigator.clipboard.writeText(value);+ return true;+ } catch {+ // Fall through to the legacy path below.+ }+ }++ // Legacy fallback: a hidden textarea + execCommand('copy').+ if (typeof document === 'undefined') return false;+ try {+ const textarea = document.createElement('textarea');+ textarea.value = value;+ textarea.setAttribute('readonly', '');+ textarea.style.position = 'absolute';+ textarea.style.left = '-9999px';+ document.body.appendChild(textarea);+ textarea.select();+ const ok = document.execCommand('copy');+ document.body.removeChild(textarea);+ return ok;+ } catch {+ return false;+ }+}++export default copyToClipboard;diff --git a/frontend/src/utils/formatBytes.js b/frontend/src/utils/formatBytes.jsnew file mode 100644index 00000000..c8d20ff9--- /dev/null+++ b/frontend/src/utils/formatBytes.js@@ -0,0 +1,57 @@+// Canonical byte/size formatter for the whole frontend.+//+// Replaces the ~14 local `formatBytes` / `formatSize` / `formatMemory`+// implementations that had drifted apart (different decimals, different KB vs+// KiB conventions, different empty-value handling). Import this instead of+// rolling a new one.+//+// formatBytes(1536) -> "1.5 KB"+// formatBytes(1536, { binary: true }) -> "1.5 KiB"+// formatBytes(0) -> "0 B"+// formatBytes(null) -> "-"+// formatBytes(1234567, { decimals: 0 }) -> "1 MB"+// formatBytes(2048, { suffix: false }) -> "2"++const DECIMAL_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];+const BINARY_UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'];++export function formatBytes(bytes, options = {}) {+ const {+ decimals = 1,+ suffix = true,+ binary = false, // true -> KiB/MiB/GiB (1024), false -> KB/MB/GB (1000)+ defaultValue = '-',+ } = options;++ if (bytes === null || bytes === undefined || bytes === '') return defaultValue;++ const value = typeof bytes === 'string' ? Number(bytes) : bytes;+ if (!Number.isFinite(value)) return defaultValue;+ if (value === 0) return suffix ? '0 B' : '0';++ const base = binary ? 1024 : 1000;+ const units = binary ? BINARY_UNITS : DECIMAL_UNITS;++ const negative = value < 0;+ const abs = Math.abs(value);++ const exponent = Math.min(+ Math.floor(Math.log(abs) / Math.log(base)),+ units.length - 1+ );+ const scaled = abs / base ** exponent;++ // Whole-byte values never need decimals.+ const places = exponent === 0 ? 0 : decimals;+ let formatted = scaled.toFixed(places);++ // Trim trailing zeros ("1.0" -> "1", "1.50" -> "1.5") for a cleaner read.+ if (formatted.includes('.')) {+ formatted = formatted.replace(/\.?0+$/, '');+ }++ const sign = negative ? '-' : '';+ return suffix ? `${sign}${formatted} ${units[exponent]}` : `${sign}${formatted}`;+}++export default formatBytes;diff --git a/frontend/src/utils/time.js b/frontend/src/utils/time.jsnew file mode 100644index 00000000..23bd981c--- /dev/null+++ b/frontend/src/utils/time.js@@ -0,0 +1,54 @@+// Canonical relative-time helpers for the whole frontend.+//+// Two output styles existed across the codebase; keep both, but in one place:+// - timeAgo(iso) compact: "just now", "4m", "3h", "2d", else a date+// - formatRelativeTime verbose: "just now", "4m ago", "3h ago", "2d ago"+//+// Replaces the scattered local copies in Dashboard.jsx, serviceTypes.js,+// logHelpers.js, and the wordpress/* components.++// Compact relative time, e.g. "just now", "4m", "3h", "2d", else a date.+export function timeAgo(iso) {+ if (!iso) return '';+ const then = new Date(iso).getTime();+ if (Number.isNaN(then)) return '';+ const seconds = Math.floor((Date.now() - then) / 1000);+ if (seconds < 45) return 'just now';+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return `${minutes}m`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return `${hours}h`;+ const days = Math.floor(hours / 24);+ if (days < 7) return `${days}d`;+ return new Date(then).toLocaleDateString();+}++// Verbose relative time, e.g. "just now", "4m ago", "3h ago", "2d ago",+// else a localized date once past ~30 days.+export function formatRelativeTime(iso) {+ if (!iso) return '';+ const date = new Date(iso);+ const then = date.getTime();+ if (Number.isNaN(then)) return '';+ const diffSec = Math.floor((Date.now() - then) / 1000);+ const diffMin = Math.floor(diffSec / 60);+ const diffHour = Math.floor(diffMin / 60);+ const diffDay = Math.floor(diffHour / 24);++ if (diffSec < 60) return 'just now';+ if (diffMin < 60) return `${diffMin}m ago`;+ if (diffHour < 24) return `${diffHour}h ago`;+ if (diffDay < 30) return `${diffDay}d ago`;+ return date.toLocaleDateString();+}++// Humanize a duration in seconds, e.g. "45s", "3m 20s".+export function formatDuration(seconds) {+ if (!seconds || seconds < 0) return '-';+ if (seconds < 60) return `${Math.round(seconds)}s`;+ const min = Math.floor(seconds / 60);+ const sec = Math.round(seconds % 60);+ return `${min}m ${sec}s`;+}++export default timeAgo;diff --git a/frontend/src/utils/timeAgo.js b/frontend/src/utils/timeAgo.jsindex ecac0b70..ab30442b 100644--- a/frontend/src/utils/timeAgo.js+++ b/frontend/src/utils/timeAgo.js@@ -1,17 +1,4 @@-// Compact relative time, e.g. "just now", "4m", "3h", "2d", else a date.-export function timeAgo(iso) {- if (!iso) return '';- const then = new Date(iso).getTime();- if (Number.isNaN(then)) return '';- const seconds = Math.floor((Date.now() - then) / 1000);- if (seconds < 45) return 'just now';- const minutes = Math.floor(seconds / 60);- if (minutes < 60) return `${minutes}m`;- const hours = Math.floor(minutes / 60);- if (hours < 24) return `${hours}h`;- const days = Math.floor(hours / 24);- if (days < 7) return `${days}d`;- return new Date(then).toLocaleDateString();-}--export default timeAgo;+// Back-compat shim: the canonical implementation now lives in ./time.js.+// Existing imports of `utils/timeAgo` keep working; new code should import+// { timeAgo, formatRelativeTime } from 'utils/time'.+export { timeAgo, timeAgo as default } from './time';