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(frontend): Phase 3 §6.3 — consolidate byte/relative-time formatters

Juan Denis064e00c7f081
diff --git a/frontend/src/components/databases/BackupsTab.jsx b/frontend/src/components/databases/BackupsTab.jsx
index 86a69632..1a08e3ed 100644
--- a/frontend/src/components/databases/BackupsTab.jsx
+++ b/frontend/src/components/databases/BackupsTab.jsx
@@ -4,14 +4,7 @@ import api from '../../services/api';
import EmptyState from '../EmptyState';
import { useConfirm } from '../../hooks/useConfirm';
import { ConfirmDialog } from '../ConfirmDialog';
-
-function formatBytes(bytes) {
- if (!bytes) return '0 B';
- const k = 1024;
- const sizes = ['B', 'KB', 'MB', 'GB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
-}
+import { formatBytes } from '@/utils/formatBytes';
const FILTERS = [
{ id: 'all', label: 'All' },
@@ -91,7 +84,7 @@ export default function BackupsTab() {
<span className={`dbx-engine-tag is-${b.type}`}>{b.type === 'mysql' ? 'MySQL' : 'PostgreSQL'}</span>
</td>
<td className="dbx-mono">{b.filename}</td>
- <td className="dbx-mono">{formatBytes(b.size)}</td>
+ <td className="dbx-mono">{formatBytes(b.size, { decimals: 2, defaultValue: '0 B' })}</td>
<td className="dbx-mono">{new Date(b.created_at).toLocaleString()}</td>
<td className="dbx-grid-actions">
<button type="button" className="dbx-icon-btn is-danger" onClick={() => remove(b.filename)} aria-label={`Delete ${b.filename}`}>
diff --git a/frontend/src/components/file-manager/fileTypes.js b/frontend/src/components/file-manager/fileTypes.js
index 012c92c7..021ff5d0 100644
--- a/frontend/src/components/file-manager/fileTypes.js
+++ b/frontend/src/components/file-manager/fileTypes.js
@@ -27,12 +27,8 @@ export function getFileExt(entry) {
return parts.pop().toUpperCase().slice(0, 4);
}
-export function formatBytes(bytes) {
- if (!bytes) return '0 B';
- const units = ['B', 'KB', 'MB', 'GB', 'TB'];
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
- return `${(bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1)} ${units[i]}`;
-}
+// Re-export the canonical byte formatter so all importers share one impl.
+export { formatBytes } from '@/utils/formatBytes';
// Folders that anchor the left-sidebar tree. Backend ALLOWED_ROOTS are
// /home, /var/www, /opt, /srv, /var/log, plus the SERVERKIT_DIR.
diff --git a/frontend/src/components/log-viewer/logHelpers.js b/frontend/src/components/log-viewer/logHelpers.js
index 849ea2d7..15f297e9 100644
--- a/frontend/src/components/log-viewer/logHelpers.js
+++ b/frontend/src/components/log-viewer/logHelpers.js
@@ -63,22 +63,8 @@ export function splitOnMatch(text, query) {
.map((p) => ({ text: p, match: re.test(p) && p.toLowerCase() === query.toLowerCase() }));
}
-// Bytes formatter shared by sidebar and status bar.
-export function formatBytes(bytes) {
- if (bytes == null) return '';
- if (bytes < 1024) return `${bytes} B`;
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
- if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
- return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
-}
+// Bytes formatter shared by sidebar and status bar — canonical impl.
+export { formatBytes } from '@/utils/formatBytes';
-export function formatRelativeTime(iso) {
- if (!iso) return '';
- const d = new Date(iso);
- const diff = (Date.now() - d.getTime()) / 1000;
- if (diff < 60) return 'just now';
- if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
- if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
- if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;
- return d.toLocaleDateString();
-}
+// Relative-time formatter — canonical impl.
+export { formatRelativeTime } from '@/utils/time';
diff --git a/frontend/src/components/security/QuarantineTab.jsx b/frontend/src/components/security/QuarantineTab.jsx
index 76fc7731..d12538f7 100644
--- a/frontend/src/components/security/QuarantineTab.jsx
+++ b/frontend/src/components/security/QuarantineTab.jsx
@@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react';
import api from '../../services/api';
import { Button } from '@/components/ui/button';
+import { formatBytes } from '@/utils/formatBytes';
const QuarantineTab = () => {
const [files, setFiles] = useState([]);
@@ -34,14 +35,6 @@ const QuarantineTab = () => {
}
}
- function formatBytes(bytes) {
- if (!bytes) return '0 B';
- const k = 1024;
- const sizes = ['B', 'KB', 'MB', 'GB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
- }
-
return (
<div className="quarantine-tab">
{message && (
@@ -84,7 +77,7 @@ const QuarantineTab = () => {
{files.map((file, index) => (
<tr key={index}>
<td className="sk-cell-mono sec-path sec-path--red">{file.name}</td>
- <td className="sk-cell-mono">{formatBytes(file.size)}</td>
+ <td className="sk-cell-mono">{formatBytes(file.size, { defaultValue: '0 B' })}</td>
<td className="sk-cell-mono sec-faint">{new Date(file.quarantined_at).toLocaleString()}</td>
<td>
<Button
diff --git a/frontend/src/components/settings/SystemTab.jsx b/frontend/src/components/settings/SystemTab.jsx
index 9d13b987..27899c03 100644
--- a/frontend/src/components/settings/SystemTab.jsx
+++ b/frontend/src/components/settings/SystemTab.jsx
@@ -6,17 +6,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';
-
-function formatBytes(bytes) {
- if (!bytes) return '-';
- const units = ['B', 'KB', 'MB', 'GB', 'TB'];
- let i = 0;
- while (bytes >= 1024 && i < units.length - 1) {
- bytes /= 1024;
- i++;
- }
- return `${bytes.toFixed(1)} ${units[i]}`;
-}
+import { formatBytes } from '@/utils/formatBytes';
function formatUptime(seconds) {
if (!seconds) return '-';
diff --git a/frontend/src/components/wordpress/ActivityFeed.jsx b/frontend/src/components/wordpress/ActivityFeed.jsx
index 6665af9d..f5009dfa 100644
--- a/frontend/src/components/wordpress/ActivityFeed.jsx
+++ b/frontend/src/components/wordpress/ActivityFeed.jsx
@@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react';
import { ArrowUpRight, ArrowDownLeft, Database, GitBranch, Lock, Unlock, Trash2, Play, Square, RefreshCw, Camera, AlertCircle } from 'lucide-react';
import wordpressApi from '../../services/wordpress';
+import { formatRelativeTime } from '@/utils/time';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
@@ -35,22 +36,6 @@ const ACTION_BADGE_VARIANTS = {
restarted: 'info'
};
-function formatRelativeTime(dateString) {
- if (!dateString) return '';
- const date = new Date(dateString);
- const now = new Date();
- const diffMs = now - date;
- const diffMinutes = Math.floor(diffMs / 60000);
- const diffHours = Math.floor(diffMs / 3600000);
- const diffDays = Math.floor(diffMs / 86400000);
-
- if (diffMinutes < 1) return 'Just now';
- if (diffMinutes < 60) return `${diffMinutes}m ago`;
- if (diffHours < 24) return `${diffHours}h ago`;
- if (diffDays < 7) return `${diffDays}d ago`;
- return date.toLocaleDateString();
-}
-
const ActivityFeed = ({ projectId, envId, limit = 20, compact = false }) => {
const [activities, setActivities] = useState([]);
const [loading, setLoading] = useState(true);
diff --git a/frontend/src/components/wordpress/DiskUsageBar.jsx b/frontend/src/components/wordpress/DiskUsageBar.jsx
index 8c8d9e96..23a37ea2 100644
--- a/frontend/src/components/wordpress/DiskUsageBar.jsx
+++ b/frontend/src/components/wordpress/DiskUsageBar.jsx
@@ -1,5 +1,6 @@
import React from 'react';
import { HardDrive } from 'lucide-react';
+import { formatBytes } from '@/utils/formatBytes';
const REFERENCE_THRESHOLD = 10 * 1024 * 1024 * 1024; // 10 GB reference
@@ -21,20 +22,11 @@ const DiskUsageBar = ({ usage, showBreakdown = true, compact = false }) => {
const colorClass = percent < 70 ? 'green' : percent < 90 ? 'yellow' : 'red';
- function formatSize(bytes) {
- if (!bytes) return '0 B';
- for (const unit of ['B', 'KB', 'MB', 'GB']) {
- if (bytes < 1024) return `${bytes.toFixed(1)} ${unit}`;
- bytes /= 1024;
- }
- return `${bytes.toFixed(1)} TB`;
- }
-
if (compact) {
return (
- <div className="disk-usage-compact" title={`Disk: ${formatSize(total)}`}>
+ <div className="disk-usage-compact" title={`Disk: ${formatBytes(total)}`}>
<HardDrive size={10} />
- <span className="disk-usage-compact-text">{formatSize(total)}</span>
+ <span className="disk-usage-compact-text">{formatBytes(total)}</span>
</div>
);
}
@@ -43,24 +35,24 @@ const DiskUsageBar = ({ usage, showBreakdown = true, compact = false }) => {
<div className="disk-usage-bar-container">
<div className="disk-usage-header">
<HardDrive size={14} />
- <span className="disk-usage-total">{formatSize(total)}</span>
+ <span className="disk-usage-total">{formatBytes(total)}</span>
</div>
<div className="disk-usage-bar">
<div
className={`disk-usage-segment wordpress ${colorClass}`}
style={{ width: `${wpPercent}%` }}
- title={`WordPress: ${formatSize(wordpress)}`}
+ title={`WordPress: ${formatBytes(wordpress)}`}
/>
<div
className="disk-usage-segment mysql"
style={{ width: `${dbPercent}%` }}
- title={`MySQL: ${formatSize(mysql)}`}
+ title={`MySQL: ${formatBytes(mysql)}`}
/>
<div
className="disk-usage-segment snapshots"
style={{ width: `${snapPercent}%` }}
- title={`Snapshots: ${formatSize(snapshots)}`}
+ title={`Snapshots: ${formatBytes(snapshots)}`}
/>
</div>
@@ -68,15 +60,15 @@ const DiskUsageBar = ({ usage, showBreakdown = true, compact = false }) => {
<div className="disk-usage-legend">
<div className="disk-usage-legend-item">
<span className="disk-usage-legend-dot wordpress" />
- <span>WordPress {formatSize(wordpress)}</span>
+ <span>WordPress {formatBytes(wordpress)}</span>
</div>
<div className="disk-usage-legend-item">
<span className="disk-usage-legend-dot mysql" />
- <span>MySQL {formatSize(mysql)}</span>
+ <span>MySQL {formatBytes(mysql)}</span>
</div>
<div className="disk-usage-legend-item">
<span className="disk-usage-legend-dot snapshots" />
- <span>Snapshots {formatSize(snapshots)}</span>
+ <span>Snapshots {formatBytes(snapshots)}</span>
</div>
</div>
)}
diff --git a/frontend/src/components/wordpress/PipelineView.jsx b/frontend/src/components/wordpress/PipelineView.jsx
index 9eb6b34b..a4cbed4f 100644
--- a/frontend/src/components/wordpress/PipelineView.jsx
+++ b/frontend/src/components/wordpress/PipelineView.jsx
@@ -10,6 +10,7 @@ import { HealthDot } from './HealthStatusPanel';
import DiskUsageBar from './DiskUsageBar';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
+import { formatRelativeTime } from '@/utils/time';
const PipelineView = ({
pipeline,
@@ -289,20 +290,6 @@ const PipelineCard = ({
const envType = env.environment_type || (isProduction ? 'production' : 'development');
const domain = env.application?.domains?.[0] || env.url || '';
- function formatRelativeTime(dateString) {
- if (!dateString) return null;
- const date = new Date(dateString);
- const now = new Date();
- const diffMs = now - date;
- const diffDays = Math.floor(diffMs / 86400000);
- const diffHours = Math.floor(diffMs / 3600000);
-
- if (diffHours < 1) return 'Just now';
- if (diffHours < 24) return `${diffHours}h ago`;
- if (diffDays < 7) return `${diffDays}d ago`;
- return date.toLocaleDateString();
- }
-
return (
<div className={`pipeline-card ${isProduction ? 'production' : ''} ${env.is_locked ? 'locked' : ''}`}>
<div className="pipeline-card-header">
@@ -475,19 +462,6 @@ const MultidevCard = ({
const isRunning = env.status === 'running' || env.application?.status === 'running';
const domain = env.application?.domains?.[0] || env.url || '';
- function formatRelativeTime(dateString) {
- if (!dateString) return null;
- const date = new Date(dateString);
- const now = new Date();
- const diffMs = now - date;
- const diffDays = Math.floor(diffMs / 86400000);
- const diffHours = Math.floor(diffMs / 3600000);
- if (diffHours < 1) return 'Just now';
- if (diffHours < 24) return `${diffHours}h ago`;
- if (diffDays < 7) return `${diffDays}d ago`;
- return date.toLocaleDateString();
- }
-
const promoteTarget = devEnv || stagingEnv || production;
return (
diff --git a/frontend/src/components/wordpress/SnapshotTable.jsx b/frontend/src/components/wordpress/SnapshotTable.jsx
index ce6d7db7..6a26d909 100644
--- a/frontend/src/components/wordpress/SnapshotTable.jsx
+++ b/frontend/src/components/wordpress/SnapshotTable.jsx
@@ -1,20 +1,13 @@
import React, { useState } from 'react';
import { Download, RotateCcw, Trash2, GitCommit, Tag } from 'lucide-react';
import { ConfirmDialog } from '../ConfirmDialog';
+import { formatBytes } from '@/utils/formatBytes';
const SnapshotTable = ({ snapshots, onRestore, onDelete, loading = false }) => {
const [actionLoading, setActionLoading] = useState({});
const [confirmRestore, setConfirmRestore] = useState(null);
const [confirmDelete, setConfirmDelete] = useState(null);
- function formatBytes(bytes) {
- if (!bytes || bytes === 0) return '0 B';
- const k = 1024;
- const sizes = ['B', 'KB', 'MB', 'GB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
- }
-
function formatDate(dateString) {
if (!dateString) return '-';
return new Date(dateString).toLocaleString();
diff --git a/frontend/src/pages/ApplicationDetail.jsx b/frontend/src/pages/ApplicationDetail.jsx
index 971bdfaf..c633d9a8 100644
--- a/frontend/src/pages/ApplicationDetail.jsx
+++ b/frontend/src/pages/ApplicationDetail.jsx
@@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { GitBranch, GitMerge, Boxes } from 'lucide-react';
import api from '../services/api';
+import { formatBytes } from '@/utils/formatBytes';
import EmptyState from '../components/EmptyState';
import useTabParam from '../hooks/useTabParam';
import { useToast } from '../contexts/ToastContext';
@@ -665,15 +666,6 @@ const RoutingDiagnosticsPanel = ({ appId }) => {
);
};
-// Helper function
-function formatBytes(bytes) {
- if (!bytes || bytes === 0) return '0 B';
- const k = 1024;
- const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
-}
-
// ============================================
// EXISTING TAB COMPONENTS (preserved)
// ============================================
diff --git a/frontend/src/pages/Backups.jsx b/frontend/src/pages/Backups.jsx
index ccc2f420..b9366bd3 100644
--- a/frontend/src/pages/Backups.jsx
+++ b/frontend/src/pages/Backups.jsx
@@ -2,6 +2,7 @@ import { useState, useEffect } from 'react';
import useTabParam from '../hooks/useTabParam';
import { Upload, Check, AlertTriangle, Clock, Database, Package, FolderArchive, HardDrive, Cloud, CloudOff, RefreshCw, Trash2, Plus, CheckCircle, XCircle, FileArchive, DollarSign, TrendingUp } from 'lucide-react';
import api from '../services/api';
+import { formatBytes } from '@/utils/formatBytes';
import { useToast } from '../contexts/ToastContext';
import { useConfirm } from '../hooks/useConfirm';
import { ConfirmDialog } from '../components/ConfirmDialog';
@@ -358,18 +359,6 @@ const Backups = () => {
});
};
- const formatSize = (bytes) => {
- if (!bytes) return '0 B';
- const units = ['B', 'KB', 'MB', 'GB', 'TB'];
- let unitIndex = 0;
- let size = bytes;
- while (size >= 1024 && unitIndex < units.length - 1) {
- size /= 1024;
- unitIndex++;
- }
- return `${size.toFixed(1)} ${units[unitIndex]}`;
- };
-
const formatTimestamp = (timestamp) => {
return new Date(timestamp).toLocaleString();
};
@@ -514,7 +503,7 @@ const Backups = () => {
<span className={`bk-type bk-type--${backup.type}`}>{backup.type}</span>
</td>
<td>{backup.app_name || backup.name?.split('_')[0] || '—'}</td>
- <td className="sk-cell-mono">{formatSize(backup.size)}</td>
+ <td className="sk-cell-mono">{formatBytes(backup.size, { defaultValue: '0 B' })}</td>
<td>{getRemoteStatusPill(backup.remote_status)}</td>
<td className="bk-when">{formatTimestamp(backup.timestamp)}</td>
<td className="sk-cell-mono">{formatMoney(((backup.size || 0) / (1024 ** 3)) * (costSummary?.cost_rates?.local || 0))}</td>
@@ -1244,7 +1233,7 @@ const Backups = () => {
</div>
<div className="sk-info-row">
<span className="k">Size</span>
- <span className="v">{formatSize(selectedBackup.size)}</span>
+ <span className="v">{formatBytes(selectedBackup.size, { defaultValue: '0 B' })}</span>
</div>
</div>
</div>
diff --git a/frontend/src/pages/Dashboard.jsx b/frontend/src/pages/Dashboard.jsx
index 638fb103..e1720547 100644
--- a/frontend/src/pages/Dashboard.jsx
+++ b/frontend/src/pages/Dashboard.jsx
@@ -15,6 +15,7 @@ import useDashboardLayout from '../hooks/useDashboardLayout';
import { Button } from '@/components/ui/button';
import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover';
import { MetricCard, Pill, Feed, FeedItem } from '@/components/ds';
+import { formatRelativeTime } from '@/utils/time';
// Map an audit action verb to a tinted icon + semantic tone token.
// Falls back to a neutral history icon for unrecognised actions.
@@ -42,23 +43,6 @@ function describeActivity(item) {
return { actor, verb, target };
}
-// Short relative time from an ISO timestamp ("just now", "5m ago", "3h ago",
-// "2d ago"), falling back to a localized date for older entries.
-function formatRelativeTime(iso) {
- if (!iso) return '';
- const then = new Date(iso);
- if (isNaN(then)) return '';
- const secs = Math.floor((Date.now() - then.getTime()) / 1000);
- if (secs < 60) return 'just now';
- const mins = Math.floor(secs / 60);
- if (mins < 60) return `${mins}m ago`;
- const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `${hrs}h ago`;
- const days = Math.floor(hrs / 24);
- if (days < 7) return `${days}d ago`;
- return then.toLocaleDateString();
-}
-
// Refresh interval options in seconds
const REFRESH_OPTIONS = [
{ label: 'Off', value: 0 },
diff --git a/frontend/src/pages/Databases.jsx b/frontend/src/pages/Databases.jsx
index d2c3073e..c4a8bb3b 100644
--- a/frontend/src/pages/Databases.jsx
+++ b/frontend/src/pages/Databases.jsx
@@ -5,6 +5,7 @@ import {
Trash2, DatabaseBackup, Copy, FileCode2, Lock,
} from 'lucide-react';
import api from '../services/api';
+import { formatBytes } from '@/utils/formatBytes';
import { useToast } from '../contexts/ToastContext';
import { useConfirm } from '../hooks/useConfirm';
import { ConfirmDialog } from '../components/ConfirmDialog';
@@ -21,14 +22,6 @@ import { listTables, connKey, connLabel, quoteIdent, ENGINE_META } from '../comp
const SIDEBAR_KEY = 'serverkit-dbx-sidebar';
-function formatBytes(bytes) {
- if (!bytes) return null;
- const k = 1024;
- const sizes = ['B', 'KB', 'MB', 'GB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
-}
-
function engineState(engine, status) {
if (engine !== 'mysql' && engine !== 'postgresql') return 'available';
const s = status?.[engine];
@@ -42,7 +35,7 @@ function dbNode(engine, conn, label, size, idOverride) {
return {
id: idOverride || `${engine}:db:${label}`,
kind: 'database', engine, label, expandable: true, conn,
- sizeText: formatBytes(size),
+ sizeText: size ? formatBytes(size) : null,
};
}
diff --git a/frontend/src/pages/Monitoring.jsx b/frontend/src/pages/Monitoring.jsx
index 756f5029..c55c0c91 100644
--- a/frontend/src/pages/Monitoring.jsx
+++ b/frontend/src/pages/Monitoring.jsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import useTabParam from '../hooks/useTabParam';
import api from '../services/api';
+import { formatBytes } from '@/utils/formatBytes';
import { useToast } from '../contexts/ToastContext';
import EmptyState from '../components/EmptyState';
import { Button } from '@/components/ui/button';
@@ -67,14 +68,6 @@ function formatMetric(value, unit = '%') {
return `${value.toFixed(unit === '' ? 2 : 1)}${unit}`;
}
-function formatBytes(bytes) {
- if (typeof bytes !== 'number' || Number.isNaN(bytes)) return '-';
- const gib = bytes / (1024 ** 3);
- if (gib >= 100) return `${Math.round(gib)} GB`;
- if (gib >= 1) return `${gib.toFixed(1)} GB`;
- return `${Math.round(bytes / (1024 ** 2))} MB`;
-}
-
function getSeverityTone(severity) {
switch (severity) {
case 'critical':
diff --git a/frontend/src/pages/ServerDetail.jsx b/frontend/src/pages/ServerDetail.jsx
index e296dc26..8d79d9db 100644
--- a/frontend/src/pages/ServerDetail.jsx
+++ b/frontend/src/pages/ServerDetail.jsx
@@ -35,6 +35,7 @@ import ProxyStackPanel from '../components/proxy/ProxyStackPanel';
import RemoteAccess from '../pages/RemoteAccess';
import TagsPanel from '../components/shared/TagsPanel';
import EmptyState from '../components/EmptyState';
+import { formatBytes } from '@/utils/formatBytes';
import { BellRing, Boxes, Container, Clock3, Cloud } from 'lucide-react';
// Server status → ds Pill tone (shared by the header pill and the
@@ -419,13 +420,6 @@ const ServerDetail = () => {
};
const OverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => {
- const formatBytes = (bytes) => {
- if (!bytes) return 'N/A';
- const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
- return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${sizes[i]}`;
- };
-
const formatUptime = (seconds) => {
if (!seconds) return 'N/A';
const days = Math.floor(seconds / 86400);
@@ -546,8 +540,8 @@ const OverviewTab = ({ server, metrics, systemInfo, onRefreshServer }) => {
(cpuModel || 'N/A') + (cpuCores ? ` (${cpuCores} cores)` : '')
}
/>
- <InfoRow icon={<MemoryIcon />} label="Total Memory" value={formatBytes(totalMemory)} mono />
- <InfoRow icon={<DiskIcon />} label="Total Disk" value={formatBytes(totalDisk)} mono />
+ <InfoRow icon={<MemoryIcon />} label="Total Memory" value={formatBytes(totalMemory, { defaultValue: 'N/A' })} mono />
+ <InfoRow icon={<DiskIcon />} label="Total Disk" value={formatBytes(totalDisk, { defaultValue: 'N/A' })} mono />
</ul>
</div>
@@ -1738,13 +1732,6 @@ const CloudflaredLoginCard = ({ login, onCancel }) => {
};
const MetricsTab = ({ serverId, metrics }) => {
- const formatBytes = (bytes) => {
- if (!bytes) return 'N/A';
- const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
- return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${sizes[i]}`;
- };
-
return (
<div className="metrics-tab">
<MetricsGraph serverId={serverId} />
@@ -1768,11 +1755,11 @@ const MetricsTab = ({ serverId, metrics }) => {
</div>
<div className="live-stat">
<span className="live-stat-label">Net TX</span>
- <span className="live-stat-value">{formatBytes(metrics.network_sent)}/s</span>
+ <span className="live-stat-value">{formatBytes(metrics.network_sent, { defaultValue: 'N/A' })}/s</span>
</div>
<div className="live-stat">
<span className="live-stat-label">Net RX</span>
- <span className="live-stat-value">{formatBytes(metrics.network_recv)}/s</span>
+ <span className="live-stat-value">{formatBytes(metrics.network_recv, { defaultValue: 'N/A' })}/s</span>
</div>
<div className="live-stat">
<span className="live-stat-label">Containers</span>
diff --git a/frontend/src/pages/Terminal.jsx b/frontend/src/pages/Terminal.jsx
index 66e772ee..d5817afe 100644
--- a/frontend/src/pages/Terminal.jsx
+++ b/frontend/src/pages/Terminal.jsx
@@ -10,6 +10,7 @@ import LogFileList from '../components/log-viewer/LogFileList';
import LogToolbar from '../components/log-viewer/LogToolbar';
import LogContent from '../components/log-viewer/LogContent';
import { formatBytes, logKindFromPath } from '../components/log-viewer/logHelpers';
+import { formatBytes as formatMemory } from '@/utils/formatBytes';
import { Pill, PageTopbar } from '../components/ds';
import { Button } from '@/components/ui/button';
import {
@@ -1640,18 +1641,6 @@ const ServicesTab = () => {
);
};
-// Helper functions
-function formatMemory(bytes) {
- if (!bytes) return '-';
- const units = ['B', 'KB', 'MB', 'GB'];
- let i = 0;
- while (bytes >= 1024 && i < units.length - 1) {
- bytes /= 1024;
- i++;
- }
- return `${bytes.toFixed(1)} ${units[i]}`;
-}
-
// Map a process status onto a ds Pill tone.
function processStatusKind(status) {
switch (status?.toLowerCase()) {
diff --git a/frontend/src/utils/formatBytes.js b/frontend/src/utils/formatBytes.js
index c8d20ff9..e6b2bc5b 100644
--- a/frontend/src/utils/formatBytes.js
+++ b/frontend/src/utils/formatBytes.js
@@ -1,25 +1,25 @@
// 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.
+// implementations that had drifted apart. The codebase universally treats
+// sizes as binary (divide by 1024) with conventional KB/MB/GB labels, so that
+// is the default here — displayed values stay identical after migration.
//
// 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(1234567, { decimals: 2 }) -> "1.18 MB"
+// formatBytes(2048, { iec: true }) -> "2 KiB"
// 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'];
+const IEC_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)
+ iec = false, // true -> KiB/MiB/GiB labels (divisor is always 1024)
defaultValue = '-',
} = options;
@@ -29,17 +29,16 @@ export function formatBytes(bytes, options = {}) {
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 units = iec ? IEC_UNITS : DECIMAL_UNITS;
const negative = value < 0;
const abs = Math.abs(value);
const exponent = Math.min(
- Math.floor(Math.log(abs) / Math.log(base)),
+ Math.floor(Math.log(abs) / Math.log(1024)),
units.length - 1
);
- const scaled = abs / base ** exponent;
+ const scaled = abs / 1024 ** exponent;
// Whole-byte values never need decimals.
const places = exponent === 0 ? 0 : decimals;
diff --git a/frontend/src/utils/serviceTypes.js b/frontend/src/utils/serviceTypes.js
index 971b99b5..0a1e1cd3 100644
--- a/frontend/src/utils/serviceTypes.js
+++ b/frontend/src/utils/serviceTypes.js
@@ -101,22 +101,9 @@ export function isDockerApp(appType) {
return appType === 'docker';
}
-export function formatRelativeTime(dateString) {
- if (!dateString) return '';
- const date = new Date(dateString);
- const now = new Date();
- const diffMs = now - date;
- const diffSec = Math.floor(diffMs / 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();
-}
+// Re-export the canonical verbose relative-time helper so existing imports
+// from this module keep working.
+export { formatRelativeTime } from '@/utils/time';
export function formatDuration(seconds) {
if (!seconds || seconds < 0) return '-';