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(analytics): dashboard frontend, six tabs (Phase 4)

Juan Denis0def46470363
diff --git a/builtin-extensions/serverkit-analytics/frontend/components/AnalyticsPage.jsx b/builtin-extensions/serverkit-analytics/frontend/components/AnalyticsPage.jsx
index 267281db..41bdb9f1 100644
--- a/builtin-extensions/serverkit-analytics/frontend/components/AnalyticsPage.jsx
+++ b/builtin-extensions/serverkit-analytics/frontend/components/AnalyticsPage.jsx
@@ -1,14 +1,141 @@
-// Web Analytics dashboard (serverkit-analytics). Placeholder scaffold — the six
-// tabs (Overview / Pages / Referrers / Devices / Realtime / Sites) land in
-// Phase 4. Kept minimal so the frontend builds from Phase 0.
+import { useCallback, useEffect, useState } from 'react';
+import { NavLink, useParams, useNavigate } from 'react-router-dom';
+import { BarChart3, FileText, Link2, Monitor, Radio, Globe, Plus } from 'lucide-react';
+import api from '@/services/api';
import { PageTopbar } from '@/components/ds';
+import EmptyState from '@/components/EmptyState';
+import { Button } from '@/components/ui/button';
+import { useToast } from '@/contexts/ToastContext';
+
+import OverviewTab from './tabs/OverviewTab.jsx';
+import PagesTab from './tabs/PagesTab.jsx';
+import ReferrersTab from './tabs/ReferrersTab.jsx';
+import DevicesTab from './tabs/DevicesTab.jsx';
+import RealtimeTab from './tabs/RealtimeTab.jsx';
+import SitesTab from './tabs/SitesTab.jsx';
+
+import '../styles/analytics.scss';
+
+// Route-driven tabs. plugin.json maps /analytics and /analytics/:tab here, so the
+// active tab is read from useParams().tab (undefined => overview).
+const TABS = [
+ { slug: 'overview', to: '/analytics', label: 'Overview', end: true, icon: <BarChart3 size={15} /> },
+ { slug: 'pages', to: '/analytics/pages', label: 'Pages', icon: <FileText size={15} /> },
+ { slug: 'referrers', to: '/analytics/referrers', label: 'Referrers', icon: <Link2 size={15} /> },
+ { slug: 'devices', to: '/analytics/devices', label: 'Devices', icon: <Monitor size={15} /> },
+ { slug: 'realtime', to: '/analytics/realtime', label: 'Realtime', icon: <Radio size={15} /> },
+ { slug: 'sites', to: '/analytics/sites', label: 'Sites', icon: <Globe size={15} /> },
+];
+const VALID_TABS = TABS.map((t) => t.slug);
+const REPORT_TABS = ['overview', 'pages', 'referrers', 'devices', 'realtime'];
export function AnalyticsPage() {
+ const toast = useToast();
+ const navigate = useNavigate();
+ const { tab } = useParams();
+ const activeTab = VALID_TABS.includes(tab) ? tab : 'overview';
+
+ const [sites, setSites] = useState([]);
+ const [sitesLoading, setSitesLoading] = useState(true);
+ const [selectedSiteId, setSelectedSiteId] = useState(null);
+
+ const loadSites = useCallback(async () => {
+ setSitesLoading(true);
+ try {
+ const data = await api.request('/analytics/sites');
+ setSites(data?.sites || []);
+ } catch (error) {
+ toast.error(`Could not load sites: ${error.message}`);
+ setSites([]);
+ } finally {
+ setSitesLoading(false);
+ }
+ }, [toast]);
+
+ useEffect(() => { loadSites(); }, [loadSites]);
+
+ // Keep a valid selection: default to the first site, and re-point if the
+ // current selection disappears (e.g. after a delete).
+ useEffect(() => {
+ if (sites.length === 0) { setSelectedSiteId(null); return; }
+ setSelectedSiteId((prev) => {
+ if (prev != null && sites.some((s) => String(s.id) === String(prev))) return prev;
+ return String(sites[0].id);
+ });
+ }, [sites]);
+
+ const isReport = REPORT_TABS.includes(activeTab);
+
+ const renderReportBody = () => {
+ if (sitesLoading || (sites.length > 0 && selectedSiteId == null)) {
+ return <EmptyState loading title="Loading analytics…" />;
+ }
+ if (sites.length === 0) {
+ return (
+ <div className="analytics-empty">
+ <EmptyState
+ icon={Globe}
+ title="No tracked sites yet"
+ description="Add a site to generate a tracking snippet and start collecting privacy-first analytics."
+ action={(
+ <Button variant="default" size="sm" onClick={() => navigate('/analytics/sites')}>
+ <Plus size={14} /> Add a site
+ </Button>
+ )}
+ />
+ </div>
+ );
+ }
+ // Remount on site change so each tab resets its own range/loading state.
+ switch (activeTab) {
+ case 'pages': return <PagesTab key={selectedSiteId} siteId={selectedSiteId} />;
+ case 'referrers': return <ReferrersTab key={selectedSiteId} siteId={selectedSiteId} />;
+ case 'devices': return <DevicesTab key={selectedSiteId} siteId={selectedSiteId} />;
+ case 'realtime': return <RealtimeTab key={selectedSiteId} siteId={selectedSiteId} />;
+ default: return <OverviewTab key={selectedSiteId} siteId={selectedSiteId} />;
+ }
+ };
+
+ // Report tabs get a site picker in the topbar; the Sites tab manages its own.
+ const topbarActions = isReport && sites.length > 0 ? (
+ <select
+ className="analytics-site-select"
+ value={selectedSiteId ?? ''}
+ onChange={(e) => setSelectedSiteId(e.target.value)}
+ aria-label="Selected site"
+ >
+ {sites.map((s) => (
+ <option key={s.id} value={String(s.id)}>{s.name}</option>
+ ))}
+ </select>
+ ) : null;
+
return (
<div className="analytics-page">
- <PageTopbar title="Web Analytics" />
- <div className="sk-tabgroup__inner">
- <p>Web Analytics is installing. The dashboard will appear here.</p>
+ <PageTopbar
+ icon={<BarChart3 size={18} />}
+ title="Web Analytics"
+ actions={topbarActions}
+ />
+
+ <nav className="analytics-tabs" aria-label="Web Analytics sections">
+ {TABS.map((t) => (
+ <NavLink
+ key={t.slug}
+ to={t.to}
+ end={t.end}
+ className={({ isActive }) => `analytics-tabs__tab${isActive ? ' is-active' : ''}`}
+ >
+ {t.icon}
+ {t.label}
+ </NavLink>
+ ))}
+ </nav>
+
+ <div className="analytics-page__body">
+ {activeTab === 'sites'
+ ? <SitesTab sites={sites} loading={sitesLoading} reload={loadSites} />
+ : renderReportBody()}
</div>
</div>
);
diff --git a/builtin-extensions/serverkit-analytics/frontend/components/RangePicker.jsx b/builtin-extensions/serverkit-analytics/frontend/components/RangePicker.jsx
new file mode 100644
index 00000000..aa86c32a
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/frontend/components/RangePicker.jsx
@@ -0,0 +1,28 @@
+// Shared date-range picker for the report tabs. Rendered as a small segmented
+// button group styled by our own `.analytics-range` rules (isolated SCSS).
+const RANGES = [
+ { value: '1d', label: '24h' },
+ { value: '7d', label: '7d' },
+ { value: '14d', label: '14d' },
+ { value: '30d', label: '30d' },
+ { value: '90d', label: '90d' },
+];
+
+export default function RangePicker({ value, onChange }) {
+ return (
+ <div className="analytics-range" role="tablist" aria-label="Date range">
+ {RANGES.map((r) => (
+ <button
+ key={r.value}
+ type="button"
+ role="tab"
+ aria-selected={value === r.value}
+ className={`analytics-range__btn${value === r.value ? ' is-active' : ''}`}
+ onClick={() => onChange(r.value)}
+ >
+ {r.label}
+ </button>
+ ))}
+ </div>
+ );
+}
diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/DevicesTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/DevicesTab.jsx
new file mode 100644
index 00000000..7bb48205
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/frontend/components/tabs/DevicesTab.jsx
@@ -0,0 +1,73 @@
+import { useCallback, useEffect, useState } from 'react';
+import { Monitor, Globe, Cpu, MapPin } from 'lucide-react';
+import api from '@/services/api';
+import { DataTable } from '@/components/ds';
+import EmptyState from '@/components/EmptyState';
+import { useToast } from '@/contexts/ToastContext';
+import RangePicker from '../RangePicker.jsx';
+import { formatInt, labelOrDirect } from '../../utils/format.js';
+
+const makeColumns = (header) => [
+ { key: 'value', header, className: 'analytics-col-grow', render: (r) => (
+ <span title={r.value}>{labelOrDirect(r.value)}</span>
+ ) },
+ { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },
+ { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },
+];
+
+const SECTIONS = [
+ { key: 'device', label: 'Device class', icon: Monitor, columns: makeColumns('Device') },
+ { key: 'browser', label: 'Browser', icon: Globe, columns: makeColumns('Browser') },
+ { key: 'os', label: 'Operating system', icon: Cpu, columns: makeColumns('OS') },
+ { key: 'country', label: 'Country', icon: MapPin, columns: makeColumns('Country') },
+];
+
+export default function DevicesTab({ siteId }) {
+ const toast = useToast();
+ const [range, setRange] = useState('7d');
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${siteId}/devices?range=${range}`);
+ setData(res);
+ } catch (error) {
+ toast.error(`Could not load devices: ${error.message}`);
+ setData(null);
+ } finally {
+ setLoading(false);
+ }
+ }, [siteId, range, toast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar">
+ <RangePicker value={range} onChange={setRange} />
+ </div>
+ {loading ? (
+ <EmptyState loading title="Loading devices…" />
+ ) : (
+ <div className="analytics-grid analytics-grid--devices">
+ {SECTIONS.map(({ key, label, icon: Icon, columns }) => (
+ <div className="analytics-panel" key={key}>
+ <div className="analytics-panel__head">
+ <Icon size={15} /> {label}
+ </div>
+ <DataTable
+ columns={columns}
+ data={data?.[key] || []}
+ keyField="value"
+ emptyTitle={`No ${label.toLowerCase()} data`}
+ emptyMessage="Nothing recorded in this range yet."
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/OverviewTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/OverviewTab.jsx
new file mode 100644
index 00000000..8bad763b
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/frontend/components/tabs/OverviewTab.jsx
@@ -0,0 +1,160 @@
+import { useCallback, useEffect, useState } from 'react';
+import {
+ ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
+} from 'recharts';
+import { Users, Eye, TrendingDown, Zap, Radio, BarChart3 } from 'lucide-react';
+import api from '@/services/api';
+import { DataTable } from '@/components/ds';
+import EmptyState from '@/components/EmptyState';
+import { useToast } from '@/contexts/ToastContext';
+import RangePicker from '../RangePicker.jsx';
+import { formatInt, formatMs, formatPct, formatDay, labelOrDirect } from '../../utils/format.js';
+
+const KPIS = [
+ { key: 'visitors', label: 'Visitors', icon: Users, tone: 'accent', fmt: formatInt },
+ { key: 'pageviews', label: 'Pageviews', icon: Eye, tone: 'cyan', fmt: formatInt },
+ { key: 'bounce_rate', label: 'Bounce rate', icon: TrendingDown, tone: 'amber', fmt: formatPct },
+ { key: 'avg_load_ms', label: 'Avg load', icon: Zap, tone: 'violet', fmt: formatMs },
+];
+
+const pageColumns = [
+ { key: 'value', header: 'Page', className: 'analytics-col-grow', render: (r) => (
+ <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>
+ ) },
+ { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },
+ { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },
+ { key: 'avg_load_ms', header: 'Avg load', render: (r) => formatMs(r.avg_load_ms) },
+];
+
+const referrerColumns = [
+ { key: 'value', header: 'Referrer', className: 'analytics-col-grow', render: (r) => (
+ <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>
+ ) },
+ { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },
+ { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },
+];
+
+export default function OverviewTab({ siteId }) {
+ const toast = useToast();
+ const [range, setRange] = useState('7d');
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${siteId}/overview?range=${range}`);
+ setData(res);
+ } catch (error) {
+ toast.error(`Could not load overview: ${error.message}`);
+ setData(null);
+ } finally {
+ setLoading(false);
+ }
+ }, [siteId, range, toast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ const totals = data?.totals || {};
+ const timeseries = data?.timeseries || [];
+ const realtime = data?.realtime || {};
+ const hasTraffic = (totals.pageviews || 0) > 0 || (totals.visitors || 0) > 0;
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar">
+ <RangePicker value={range} onChange={setRange} />
+ <span className="analytics-live" title="Active visitors in the last 30 minutes">
+ <Radio size={14} className="analytics-live__dot" />
+ {formatInt(realtime.active_visitors)} active now
+ </span>
+ </div>
+
+ <div className="analytics-kpis">
+ {KPIS.map(({ key, label, icon: Icon, tone, fmt }) => (
+ <div className="analytics-kpi" key={key}>
+ <span className={`analytics-kpi__icon analytics-kpi__icon--${tone}`}>
+ <Icon size={16} />
+ </span>
+ <div className="analytics-kpi__val">{loading ? '—' : fmt(totals[key])}</div>
+ <div className="analytics-kpi__label">{label}</div>
+ </div>
+ ))}
+ </div>
+
+ {loading ? (
+ <EmptyState loading title="Loading overview…" />
+ ) : !hasTraffic ? (
+ <div className="analytics-empty">
+ <EmptyState
+ icon={BarChart3}
+ title="No traffic in this range yet"
+ description="Once the tracking snippet is installed and visitors arrive, their pageviews show up here."
+ />
+ </div>
+ ) : (
+ <>
+ <div className="analytics-chart-card">
+ <div className="analytics-chart-card__head">Visitors &amp; pageviews</div>
+ <ResponsiveContainer width="100%" height={260}>
+ <AreaChart data={timeseries} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>
+ <defs>
+ <linearGradient id="anVisitors" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor="#6d7cff" stopOpacity={0.35} />
+ <stop offset="95%" stopColor="#6d7cff" stopOpacity={0} />
+ </linearGradient>
+ <linearGradient id="anPageviews" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor="#22c7d6" stopOpacity={0.3} />
+ <stop offset="95%" stopColor="#22c7d6" stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid strokeDasharray="3 3" stroke="#888" strokeOpacity={0.15} />
+ <XAxis
+ dataKey="date"
+ tickFormatter={formatDay}
+ tick={{ fontSize: 11, fill: '#888' }}
+ minTickGap={24}
+ axisLine={false}
+ tickLine={false}
+ />
+ <YAxis
+ allowDecimals={false}
+ tick={{ fontSize: 11, fill: '#888' }}
+ width={40}
+ axisLine={false}
+ tickLine={false}
+ />
+ <Tooltip labelFormatter={formatDay} />
+ <Area type="monotone" dataKey="visitors" name="Visitors" stroke="#8b93ff" fill="url(#anVisitors)" strokeWidth={2} />
+ <Area type="monotone" dataKey="pageviews" name="Pageviews" stroke="#22c7d6" fill="url(#anPageviews)" strokeWidth={2} />
+ </AreaChart>
+ </ResponsiveContainer>
+ </div>
+
+ <div className="analytics-grid">
+ <div className="analytics-panel">
+ <div className="analytics-panel__head">Top pages</div>
+ <DataTable
+ columns={pageColumns}
+ data={data?.top_pages || []}
+ keyField="value"
+ emptyTitle="No pages yet"
+ emptyMessage="Pageviews will appear here once visitors browse the site."
+ />
+ </div>
+ <div className="analytics-panel">
+ <div className="analytics-panel__head">Top referrers</div>
+ <DataTable
+ columns={referrerColumns}
+ data={data?.top_referrers || []}
+ keyField="value"
+ emptyTitle="No referrers yet"
+ emptyMessage="Sources that send traffic to the site will appear here."
+ />
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/PagesTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/PagesTab.jsx
new file mode 100644
index 00000000..a4c70add
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/frontend/components/tabs/PagesTab.jsx
@@ -0,0 +1,56 @@
+import { useCallback, useEffect, useState } from 'react';
+import api from '@/services/api';
+import { DataTable } from '@/components/ds';
+import { useToast } from '@/contexts/ToastContext';
+import RangePicker from '../RangePicker.jsx';
+import { formatInt, formatMs, labelOrDirect } from '../../utils/format.js';
+
+const columns = [
+ { key: 'value', header: 'Page', className: 'analytics-col-grow', render: (r) => (
+ <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>
+ ) },
+ { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },
+ { key: 'pageviews', header: 'Pageviews', sortable: true, render: (r) => formatInt(r.pageviews) },
+ { key: 'avg_load_ms', header: 'Avg load', sortable: true, sortValue: (r) => r.avg_load_ms ?? -1, render: (r) => formatMs(r.avg_load_ms) },
+];
+
+export default function PagesTab({ siteId }) {
+ const toast = useToast();
+ const [range, setRange] = useState('7d');
+ const [rows, setRows] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${siteId}/pages?range=${range}`);
+ setRows(res?.rows || []);
+ } catch (error) {
+ toast.error(`Could not load pages: ${error.message}`);
+ setRows([]);
+ } finally {
+ setLoading(false);
+ }
+ }, [siteId, range, toast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar">
+ <RangePicker value={range} onChange={setRange} />
+ </div>
+ <div className="analytics-panel">
+ <DataTable
+ columns={columns}
+ data={rows}
+ keyField="value"
+ loading={loading}
+ defaultSort={{ key: 'pageviews', direction: 'desc' }}
+ emptyTitle="No pages yet"
+ emptyMessage="Pageviews will appear here once visitors browse the site."
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/RealtimeTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/RealtimeTab.jsx
new file mode 100644
index 00000000..6a8af6b2
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/frontend/components/tabs/RealtimeTab.jsx
@@ -0,0 +1,102 @@
+import { useCallback, useEffect, useState } from 'react';
+import { Radio, Users, Eye } from 'lucide-react';
+import api from '@/services/api';
+import { DataTable } from '@/components/ds';
+import { useToast } from '@/contexts/ToastContext';
+import { formatInt, formatClock, labelOrDirect } from '../../utils/format.js';
+
+const MINUTE_OPTIONS = [5, 15, 30, 60];
+const POLL_MS = 15000;
+
+const columns = [
+ { key: 'ts', header: 'Time', render: (r) => <span className="analytics-cell-mono">{formatClock(r.ts)}</span> },
+ { key: 'path', header: 'Page', className: 'analytics-col-grow', render: (r) => (
+ <span className="analytics-cell-mono" title={r.path}>{labelOrDirect(r.path)}</span>
+ ) },
+ { key: 'referrer_host', header: 'Referrer', render: (r) => labelOrDirect(r.referrer_host) },
+ { key: 'device_class', header: 'Device', render: (r) => r.device_class || '—' },
+ { key: 'country', header: 'Country', render: (r) => r.country || '—' },
+];
+
+export default function RealtimeTab({ siteId }) {
+ const toast = useToast();
+ const [minutes, setMinutes] = useState(30);
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ // `silent` polls skip the loading skeleton so the feed refreshes without flicker.
+ const load = useCallback(async (silent = false) => {
+ if (!silent) setLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${siteId}/realtime?minutes=${minutes}`);
+ setData(res);
+ } catch (error) {
+ if (!silent) {
+ toast.error(`Could not load realtime: ${error.message}`);
+ setData(null);
+ }
+ } finally {
+ if (!silent) setLoading(false);
+ }
+ }, [siteId, minutes, toast]);
+
+ useEffect(() => {
+ load(false);
+ const id = setInterval(() => load(true), POLL_MS);
+ return () => clearInterval(id);
+ }, [load]);
+
+ // Realtime events carry no id; synthesize a stable unique key per row so the
+ // table never collides two hits sharing a timestamp.
+ const recent = (data?.recent || []).map((r, i) => ({ ...r, _rid: `${r.ts || 'x'}-${i}` }));
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar">
+ <div className="analytics-range" role="tablist" aria-label="Time window">
+ {MINUTE_OPTIONS.map((m) => (
+ <button
+ key={m}
+ type="button"
+ role="tab"
+ aria-selected={minutes === m}
+ className={`analytics-range__btn${minutes === m ? ' is-active' : ''}`}
+ onClick={() => setMinutes(m)}
+ >
+ {m}m
+ </button>
+ ))}
+ </div>
+ <span className="analytics-live" title="Auto-refreshing">
+ <Radio size={14} className="analytics-live__dot" />
+ Live · last {data?.minutes ?? minutes} min
+ </span>
+ </div>
+
+ <div className="analytics-realtime">
+ <div className="analytics-realtime__stat">
+ <span className="analytics-realtime__icon analytics-realtime__icon--accent"><Users size={18} /></span>
+ <div className="analytics-realtime__val">{loading ? '—' : formatInt(data?.active_visitors)}</div>
+ <div className="analytics-realtime__label">Active visitors</div>
+ </div>
+ <div className="analytics-realtime__stat">
+ <span className="analytics-realtime__icon analytics-realtime__icon--cyan"><Eye size={18} /></span>
+ <div className="analytics-realtime__val">{loading ? '—' : formatInt(data?.pageviews)}</div>
+ <div className="analytics-realtime__label">Pageviews</div>
+ </div>
+ </div>
+
+ <div className="analytics-panel">
+ <div className="analytics-panel__head">Recent activity</div>
+ <DataTable
+ columns={columns}
+ data={recent}
+ keyField="_rid"
+ loading={loading}
+ emptyTitle="No activity yet"
+ emptyMessage="Hits from the last few minutes will stream in here."
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/ReferrersTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/ReferrersTab.jsx
new file mode 100644
index 00000000..b86b093d
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/frontend/components/tabs/ReferrersTab.jsx
@@ -0,0 +1,55 @@
+import { useCallback, useEffect, useState } from 'react';
+import api from '@/services/api';
+import { DataTable } from '@/components/ds';
+import { useToast } from '@/contexts/ToastContext';
+import RangePicker from '../RangePicker.jsx';
+import { formatInt, labelOrDirect } from '../../utils/format.js';
+
+const columns = [
+ { key: 'value', header: 'Referrer', className: 'analytics-col-grow', render: (r) => (
+ <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>
+ ) },
+ { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },
+ { key: 'pageviews', header: 'Pageviews', sortable: true, render: (r) => formatInt(r.pageviews) },
+];
+
+export default function ReferrersTab({ siteId }) {
+ const toast = useToast();
+ const [range, setRange] = useState('7d');
+ const [rows, setRows] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${siteId}/referrers?range=${range}`);
+ setRows(res?.rows || []);
+ } catch (error) {
+ toast.error(`Could not load referrers: ${error.message}`);
+ setRows([]);
+ } finally {
+ setLoading(false);
+ }
+ }, [siteId, range, toast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar">
+ <RangePicker value={range} onChange={setRange} />
+ </div>
+ <div className="analytics-panel">
+ <DataTable
+ columns={columns}
+ data={rows}
+ keyField="value"
+ loading={loading}
+ defaultSort={{ key: 'pageviews', direction: 'desc' }}
+ emptyTitle="No referrers yet"
+ emptyMessage="Sources that send traffic to the site will appear here."
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/builtin-extensions/serverkit-analytics/frontend/components/tabs/SitesTab.jsx b/builtin-extensions/serverkit-analytics/frontend/components/tabs/SitesTab.jsx
new file mode 100644
index 00000000..3aeaee43
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/frontend/components/tabs/SitesTab.jsx
@@ -0,0 +1,318 @@
+import { useCallback, useEffect, useState } from 'react';
+import { Plus, Trash2, RefreshCw, Copy, Check, Code2, Power, Globe } from 'lucide-react';
+import api from '@/services/api';
+import { DataTable, Pill } from '@/components/ds';
+import Modal from '@/components/Modal';
+import ConfirmDialog from '@/components/ConfirmDialog';
+import EmptyState from '@/components/EmptyState';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { useToast } from '@/contexts/ToastContext';
+import { useClipboard } from '@/hooks/useClipboard';
+
+const INITIAL_FORM = { name: '', hostnames: '', allowedOrigins: '', honorDnt: true, enabled: true };
+
+// Split a textarea value on newlines/commas into a clean list of tokens.
+const parseList = (raw) => (raw || '').split(/[\n,]/).map((s) => s.trim()).filter(Boolean);
+
+export default function SitesTab({ sites, loading, reload }) {
+ const toast = useToast();
+ const { copy, copied } = useClipboard({ successMessage: 'Snippet copied' });
+
+ const [busy, setBusy] = useState(false);
+ const [confirm, setConfirm] = useState(null);
+
+ // Add-site modal
+ const [addOpen, setAddOpen] = useState(false);
+ const [form, setForm] = useState(INITIAL_FORM);
+
+ // Snippet modal
+ const [snippetSite, setSnippetSite] = useState(null);
+ const [snippetData, setSnippetData] = useState(null);
+ const [snippetLoading, setSnippetLoading] = useState(false);
+ const [snippetOutlinks, setSnippetOutlinks] = useState(false);
+
+ const fetchSnippet = useCallback(async (site, outlinks) => {
+ setSnippetLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${site.id}/snippet?outlinks=${outlinks}`);
+ setSnippetData(res);
+ } catch (error) {
+ toast.error(`Could not load snippet: ${error.message}`);
+ setSnippetData(null);
+ } finally {
+ setSnippetLoading(false);
+ }
+ }, [toast]);
+
+ useEffect(() => {
+ if (snippetSite) fetchSnippet(snippetSite, snippetOutlinks);
+ }, [snippetSite, snippetOutlinks, fetchSnippet]);
+
+ const openAdd = () => { setForm(INITIAL_FORM); setAddOpen(true); };
+ const openSnippet = (site) => { setSnippetOutlinks(false); setSnippetSite(site); };
+ const closeSnippet = () => { setSnippetSite(null); setSnippetData(null); };
+
+ const handleCreate = async () => {
+ const name = form.name.trim();
+ const hostnames = parseList(form.hostnames);
+ if (!name) { toast.error('Name is required.'); return; }
+ if (hostnames.length === 0) { toast.error('Add at least one hostname.'); return; }
+ setBusy(true);
+ try {
+ const site = await api.request('/analytics/sites', {
+ method: 'POST',
+ body: {
+ name,
+ hostnames,
+ allowed_origins: parseList(form.allowedOrigins),
+ honor_dnt: form.honorDnt,
+ enabled: form.enabled,
+ },
+ });
+ setAddOpen(false);
+ toast.success(`Site "${site.name}" created`);
+ await reload();
+ openSnippet(site);
+ } catch (error) {
+ toast.error(`Could not create site: ${error.message}`);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const handleToggle = async (site) => {
+ try {
+ await api.request(`/analytics/sites/${site.id}`, { method: 'PUT', body: { enabled: !site.enabled } });
+ await reload();
+ } catch (error) {
+ toast.error(`Could not update site: ${error.message}`);
+ }
+ };
+
+ const handleRotate = (site) => setConfirm({
+ title: `Rotate key for ${site.name}?`,
+ message: 'A new site key is generated immediately. The old key stops accepting hits, so update the installed snippet afterward.',
+ confirmText: 'Rotate key',
+ variant: 'warning',
+ onConfirm: async () => {
+ setConfirm(null);
+ setBusy(true);
+ try {
+ await api.request(`/analytics/sites/${site.id}/rotate-key`, { method: 'POST' });
+ toast.success('Site key rotated');
+ await reload();
+ if (snippetSite && snippetSite.id === site.id) fetchSnippet(site, snippetOutlinks);
+ } catch (error) {
+ toast.error(`Could not rotate key: ${error.message}`);
+ } finally {
+ setBusy(false);
+ }
+ },
+ });
+
+ const handleDelete = (site) => setConfirm({
+ title: `Delete ${site.name}?`,
+ message: 'This removes the site and all of its collected analytics. This cannot be undone.',
+ confirmText: 'Delete',
+ variant: 'danger',
+ onConfirm: async () => {
+ setConfirm(null);
+ setBusy(true);
+ try {
+ await api.request(`/analytics/sites/${site.id}`, { method: 'DELETE' });
+ toast.success('Site deleted');
+ if (snippetSite && snippetSite.id === site.id) closeSnippet();
+ await reload();
+ } catch (error) {
+ toast.error(`Could not delete site: ${error.message}`);
+ } finally {
+ setBusy(false);
+ }
+ },
+ });
+
+ const columns = [
+ { key: 'name', header: 'Site', sortable: true, render: (s) => (
+ <div className="analytics-site-name">
+ <span className="analytics-site-name__title">{s.name}</span>
+ <span className="analytics-cell-mono analytics-site-name__key">{s.site_key}</span>
+ </div>
+ ) },
+ { key: 'hostnames', header: 'Hostnames', render: (s) => {
+ const list = (s.hostnames || []).join(', ');
+ return <span className="analytics-cell-mono" title={list}>{list || '—'}</span>;
+ } },
+ { key: 'enabled', header: 'Status', render: (s) => (
+ s.enabled ? <Pill kind="green">Enabled</Pill> : <Pill kind="gray">Disabled</Pill>
+ ) },
+ { key: 'actions', header: '', className: 'analytics-col-actions', render: (s) => (
+ <div className="analytics-row-actions">
+ <Button variant="secondary" size="sm" onClick={() => openSnippet(s)} title="Tracking snippet">
+ <Code2 size={14} />
+ </Button>
+ <Button variant="secondary" size="sm" onClick={() => handleToggle(s)} title={s.enabled ? 'Disable' : 'Enable'}>
+ <Power size={14} />
+ </Button>
+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRotate(s)} title="Rotate key">
+ <RefreshCw size={14} />
+ </Button>
+ <Button variant="destructive" size="sm" onClick={() => handleDelete(s)} title="Delete">
+ <Trash2 size={14} />
+ </Button>
+ </div>
+ ) },
+ ];
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar analytics-toolbar--between">
+ <span className="analytics-toolbar__hint">
+ {sites.length} site{sites.length === 1 ? '' : 's'} tracked
+ </span>
+ <Button variant="default" size="sm" onClick={openAdd}>
+ <Plus size={14} /> Add site
+ </Button>
+ </div>
+
+ <div className="analytics-panel">
+ <DataTable
+ columns={columns}
+ data={sites}
+ keyField="id"
+ loading={loading}
+ emptyState={(
+ <EmptyState
+ icon={Globe}
+ title="No tracked sites yet"
+ description="Add a site to generate a tracking snippet and start collecting privacy-first analytics."
+ action={(
+ <Button variant="default" size="sm" onClick={openAdd}>
+ <Plus size={14} /> Add site
+ </Button>
+ )}
+ />
+ )}
+ />
+ </div>
+
+ {/* Add-site modal */}
+ <Modal
+ open={addOpen}
+ onClose={() => setAddOpen(false)}
+ title="Add a site"
+ size="lg"
+ footer={(
+ <>
+ <Button variant="outline" onClick={() => setAddOpen(false)}>Cancel</Button>
+ <Button variant="default" onClick={handleCreate} disabled={busy || !form.name.trim()}>
+ <Plus size={14} /> Create site
+ </Button>
+ </>
+ )}
+ >
+ <div className="analytics-form">
+ <div className="form-group">
+ <Label>Name</Label>
+ <Input
+ value={form.name}
+ placeholder="My website"
+ autoFocus
+ onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
+ />
+ </div>
+ <div className="form-group">
+ <Label>Hostnames</Label>
+ <textarea
+ className="analytics-textarea"
+ value={form.hostnames}
+ placeholder={'example.com\nwww.example.com'}
+ spellCheck={false}
+ onChange={(e) => setForm((f) => ({ ...f, hostnames: e.target.value }))}
+ />
+ <p className="analytics-form__hint">One per line (or comma-separated). Hits are accepted from these hostnames.</p>
+ </div>
+ <div className="form-group">
+ <Label>Allowed origins (optional)</Label>
+ <textarea
+ className="analytics-textarea"
+ value={form.allowedOrigins}
+ placeholder={'https://example.com'}
+ spellCheck={false}
+ onChange={(e) => setForm((f) => ({ ...f, allowedOrigins: e.target.value }))}
+ />
+ <p className="analytics-form__hint">Restrict the collector to these CORS origins. Leave empty to allow any.</p>
+ </div>
+ <label className="analytics-check">
+ <input
+ type="checkbox"
+ checked={form.honorDnt}
+ onChange={(e) => setForm((f) => ({ ...f, honorDnt: e.target.checked }))}
+ />
+ <span>Honor the browser&apos;s Do Not Track signal</span>
+ </label>
+ <label className="analytics-check">
+ <input
+ type="checkbox"
+ checked={form.enabled}
+ onChange={(e) => setForm((f) => ({ ...f, enabled: e.target.checked }))}
+ />
+ <span>Start collecting immediately</span>
+ </label>
+ </div>
+ </Modal>
+
+ {/* Tracking snippet modal */}
+ <Modal
+ open={!!snippetSite}
+ onClose={closeSnippet}
+ title={snippetSite ? `Tracking snippet · ${snippetSite.name}` : 'Tracking snippet'}
+ size="lg"
+ footer={<Button variant="outline" onClick={closeSnippet}>Close</Button>}
+ >
+ {snippetLoading ? (
+ <EmptyState loading title="Loading snippet…" />
+ ) : !snippetData ? (
+ <EmptyState title="Snippet unavailable" description="Could not load the tracking snippet for this site." />
+ ) : (
+ <div className="analytics-snippet-wrap">
+ <p className="analytics-form__hint">
+ Paste this into the &lt;head&gt; of every page you want to track. It is cookieless and under 4&nbsp;KB.
+ </p>
+ <label className="analytics-check">
+ <input
+ type="checkbox"
+ checked={snippetOutlinks}
+ onChange={(e) => setSnippetOutlinks(e.target.checked)}
+ />
+ <span>Include outbound-link tracking</span>
+ </label>
+ <pre className="analytics-snippet"><code>{snippetData.snippet}</code></pre>
+ <div className="analytics-snippet__foot">
+ <span className="analytics-cell-mono analytics-snippet__key" title={snippetData.tracker_url}>
+ {snippetData.site_key}
+ </span>
+ <Button variant="default" size="sm" onClick={() => copy(snippetData.snippet)}>
+ {copied ? <Check size={14} /> : <Copy size={14} />}
+ {copied ? 'Copied' : 'Copy'}
+ </Button>
+ </div>
+ </div>
+ )}
+ </Modal>
+
+ {confirm && (
+ <ConfirmDialog
+ isOpen
+ title={confirm.title}
+ message={confirm.message}
+ confirmText={confirm.confirmText}
+ variant={confirm.variant}
+ onConfirm={confirm.onConfirm}
+ onCancel={() => setConfirm(null)}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/builtin-extensions/serverkit-analytics/frontend/styles/analytics.scss b/builtin-extensions/serverkit-analytics/frontend/styles/analytics.scss
new file mode 100644
index 00000000..818fab99
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/frontend/styles/analytics.scss
@@ -0,0 +1,410 @@
+/* serverkit-analytics — isolated plugin styles.
+ Compiled in ISOLATION from the host: no SCSS $variables, no @import of host
+ partials. Colours come from the host theme via CSS custom properties
+ (var(--token, fallback)) plus neutral rgba(128,128,128,α) tints, so the
+ dashboard tracks light/dark automatically.
+
+ Every in-page rule is namespaced under .analytics-page. The Modal /
+ ConfirmDialog primitives portal to <body> — OUTSIDE the .analytics-page
+ subtree — so the modal-content rules near the bottom of this file are
+ intentionally top-level (same idiom as the tramo extension). All of our
+ class names are `.analytics-*` prefixed, so the few top-level rules cannot
+ collide with the host or other plugins. */
+
+.analytics-page {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+
+ &__body {
+ padding: 18px 24px 28px;
+ }
+
+ /* ── Route-driven tab bar (replaces sidebar sub-menus) ── */
+ .analytics-tabs {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 0 24px;
+ border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.18));
+ overflow-x: auto;
+
+ &__tab {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ padding: 11px 14px;
+ font-size: 13.5px;
+ font-weight: 500;
+ color: var(--text-secondary, rgba(128, 128, 128, 0.9));
+ text-decoration: none;
+ border-bottom: 2px solid transparent;
+ white-space: nowrap;
+ transition: color 0.15s ease, border-color 0.15s ease;
+
+ svg { opacity: 0.8; }
+
+ &:hover { color: var(--text-primary, inherit); }
+
+ &.is-active {
+ color: var(--accent-bright, #6366f1);
+ border-bottom-color: var(--accent-bright, #6366f1);
+ }
+ }
+ }
+
+ /* Site picker in the topbar actions slot */
+ .analytics-site-select {
+ height: 32px;
+ max-width: 220px;
+ padding: 0 10px;
+ border-radius: 8px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.3));
+ background: var(--bg-elevated, rgba(128, 128, 128, 0.06));
+ color: inherit;
+ font-size: 13px;
+ cursor: pointer;
+
+ &:focus { outline: 0; border-color: var(--accent-bright, #6366f1); }
+ }
+
+ /* ── Tab body scaffolding ── */
+ .analytics-tabbody {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ }
+
+ .analytics-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ flex-wrap: wrap;
+
+ &--between { justify-content: space-between; }
+
+ &__hint {
+ font-size: 12.5px;
+ opacity: 0.65;
+ }
+ }
+
+ .analytics-live {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ margin-left: auto;
+ font-size: 12.5px;
+ font-weight: 500;
+ color: var(--green, #22c55e);
+
+ &__dot {
+ color: var(--green, #22c55e);
+ animation: analytics-pulse 1.8s ease-in-out infinite;
+ }
+ }
+
+ /* Range / minutes segmented control */
+ .analytics-range {
+ display: inline-flex;
+ gap: 2px;
+ padding: 3px;
+ border-radius: 9px;
+ background: rgba(128, 128, 128, 0.1);
+
+ &__btn {
+ border: 0;
+ background: transparent;
+ color: var(--text-secondary, inherit);
+ font-size: 12.5px;
+ font-weight: 500;
+ padding: 5px 11px;
+ border-radius: 7px;
+ cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease;
+
+ &:hover { color: var(--text-primary, inherit); }
+
+ &.is-active {
+ background: var(--bg-card, rgba(128, 128, 128, 0.9));
+ color: var(--accent-bright, #6366f1);
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12);
+ }
+ }
+ }
+
+ /* ── KPI tiles ── */
+ .analytics-kpis {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ gap: 12px;
+ }
+
+ .analytics-kpi {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 16px;
+ border-radius: 12px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.16));
+ background: var(--bg-card, rgba(128, 128, 128, 0.03));
+
+ &__icon {
+ width: 34px;
+ height: 34px;
+ border-radius: 9px;
+ display: grid;
+ place-items: center;
+ background: rgba(128, 128, 128, 0.14);
+ color: var(--accent-bright, #818cf8);
+
+ &--accent { background: rgba(99, 102, 241, 0.16); color: #818cf8; }
+ &--cyan { background: rgba(34, 199, 214, 0.16); color: #22c7d6; }
+ &--amber { background: rgba(234, 179, 8, 0.16); color: #eab308; }
+ &--violet { background: rgba(139, 92, 246, 0.16); color: #a78bfa; }
+ }
+
+ &__val {
+ font-size: 24px;
+ font-weight: 700;
+ line-height: 1.1;
+ color: var(--text-primary, inherit);
+ }
+
+ &__label {
+ font-size: 12.5px;
+ opacity: 0.65;
+ }
+ }
+
+ /* ── Chart card ── */
+ .analytics-chart-card {
+ padding: 16px 16px 8px;
+ border-radius: 12px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.16));
+ background: var(--bg-card, rgba(128, 128, 128, 0.03));
+
+ &__head {
+ font-size: 13px;
+ font-weight: 600;
+ margin-bottom: 12px;
+ opacity: 0.85;
+ }
+ }
+
+ /* ── Grids of tables ── */
+ .analytics-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 16px;
+
+ &--devices {
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
+ }
+
+ @media (max-width: 720px) {
+ grid-template-columns: 1fr;
+ }
+ }
+
+ .analytics-panel {
+ border-radius: 12px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.16));
+ background: var(--bg-card, rgba(128, 128, 128, 0.03));
+ overflow: hidden;
+
+ &__head {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 12px 16px;
+ font-size: 13px;
+ font-weight: 600;
+ border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.12));
+ opacity: 0.9;
+
+ svg { opacity: 0.7; }
+ }
+ }
+
+ /* ── Realtime counters ── */
+ .analytics-realtime {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+ gap: 12px;
+
+ &__stat {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 18px;
+ border-radius: 12px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.16));
+ background: var(--bg-card, rgba(128, 128, 128, 0.03));
+ }
+
+ &__icon {
+ width: 38px;
+ height: 38px;
+ border-radius: 10px;
+ display: grid;
+ place-items: center;
+ background: rgba(128, 128, 128, 0.14);
+
+ &--accent { background: rgba(99, 102, 241, 0.16); color: #818cf8; }
+ &--cyan { background: rgba(34, 199, 214, 0.16); color: #22c7d6; }
+ }
+
+ &__val {
+ font-size: 30px;
+ font-weight: 700;
+ line-height: 1;
+ color: var(--text-primary, inherit);
+ }
+
+ &__label {
+ font-size: 12.5px;
+ opacity: 0.65;
+ }
+ }
+
+ /* ── Sites table cells ── */
+ .analytics-site-name {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+
+ &__title { font-weight: 600; font-size: 13.5px; }
+ &__key { font-size: 11px; opacity: 0.55; }
+ }
+
+ .analytics-row-actions {
+ display: flex;
+ gap: 6px;
+ justify-content: flex-end;
+ flex-wrap: wrap;
+ }
+
+ .analytics-col-actions {
+ text-align: right;
+ white-space: nowrap;
+ }
+
+ .analytics-col-grow {
+ min-width: 150px;
+ }
+
+ /* In-page empty/dashed wrapper */
+ .analytics-empty {
+ border-radius: 12px;
+ border: 1px dashed var(--border, rgba(128, 128, 128, 0.3));
+ background: var(--bg-card, rgba(128, 128, 128, 0.03));
+ }
+}
+
+/* Shared monospace utility — used in-page (tables) AND inside the portaled
+ snippet modal, so it lives at top level to match both DOM locations. */
+.analytics-cell-mono {
+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
+ font-size: 12.5px;
+}
+
+@keyframes analytics-pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.35; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .analytics-live__dot { animation: none; }
+}
+
+/* ── Portaled modal content (Modal / ConfirmDialog render into <body>, OUTSIDE
+ .analytics-page) — these MUST stay top-level or they never match. ── */
+.analytics-form {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+
+ .form-group { margin: 0; }
+
+ &__hint {
+ margin: 6px 0 0;
+ font-size: 12px;
+ line-height: 1.45;
+ opacity: 0.62;
+ }
+}
+
+.analytics-textarea {
+ width: 100%;
+ min-height: 78px;
+ resize: vertical;
+ padding: 10px 12px;
+ border-radius: 9px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.3));
+ background: var(--bg-elevated, rgba(128, 128, 128, 0.05));
+ color: inherit;
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-size: 12.5px;
+ line-height: 1.5;
+
+ &:focus { outline: 0; border-color: var(--accent-bright, #6366f1); }
+ &::placeholder { opacity: 0.4; }
+}
+
+.analytics-check {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ font-size: 13px;
+ cursor: pointer;
+
+ input {
+ width: 15px;
+ height: 15px;
+ cursor: pointer;
+ accent-color: var(--accent-bright, #6366f1);
+ }
+}
+
+.analytics-snippet-wrap {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.analytics-snippet {
+ margin: 0;
+ max-height: 260px;
+ overflow: auto;
+ padding: 14px;
+ border-radius: 10px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.25));
+ background: var(--bg-elevated, rgba(128, 128, 128, 0.08));
+ color: var(--text-primary, inherit);
+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
+ font-size: 12px;
+ line-height: 1.55;
+ white-space: pre-wrap;
+ word-break: break-all;
+
+ code {
+ font: inherit;
+ color: inherit;
+ background: none;
+ }
+
+ &__foot {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ }
+
+ &__key {
+ opacity: 0.7;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+}
diff --git a/builtin-extensions/serverkit-analytics/frontend/utils/format.js b/builtin-extensions/serverkit-analytics/frontend/utils/format.js
new file mode 100644
index 00000000..47bd7469
--- /dev/null
+++ b/builtin-extensions/serverkit-analytics/frontend/utils/format.js
@@ -0,0 +1,28 @@
+// Small, dependency-free formatting helpers for the analytics dashboard.
+// Kept isolated (no host imports) so the plugin bundle stays self-contained.
+
+export const formatInt = (n) => Number(n ?? 0).toLocaleString();
+
+export const formatMs = (ms) => (ms == null ? '—' : `${Math.round(ms)} ms`);
+
+export const formatPct = (n) => `${Number(n ?? 0).toFixed(1)}%`;
+
+// A 'YYYY-MM-DD' rollup date → a short "Jul 18" label. Parsed as local midnight
+// (append time) so the label never drifts a day across time zones.
+export const formatDay = (iso) => {
+ if (!iso) return '';
+ const d = new Date(`${iso}T00:00:00`);
+ if (Number.isNaN(d.getTime())) return iso;
+ return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
+};
+
+// An ISO timestamp → a wall-clock "14:03:21" label for the realtime feed.
+export const formatClock = (iso) => {
+ if (!iso) return '—';
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return '—';
+ return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
+};
+
+// Referrer/path dimension value → a readable label ("Direct / none" for empties).
+export const labelOrDirect = (value) => (value && value.trim() ? value : 'Direct / none');
diff --git a/frontend/src/plugins/serverkit-analytics/components/AnalyticsPage.jsx b/frontend/src/plugins/serverkit-analytics/components/AnalyticsPage.jsx
index 267281db..41bdb9f1 100644
--- a/frontend/src/plugins/serverkit-analytics/components/AnalyticsPage.jsx
+++ b/frontend/src/plugins/serverkit-analytics/components/AnalyticsPage.jsx
@@ -1,14 +1,141 @@
-// Web Analytics dashboard (serverkit-analytics). Placeholder scaffold — the six
-// tabs (Overview / Pages / Referrers / Devices / Realtime / Sites) land in
-// Phase 4. Kept minimal so the frontend builds from Phase 0.
+import { useCallback, useEffect, useState } from 'react';
+import { NavLink, useParams, useNavigate } from 'react-router-dom';
+import { BarChart3, FileText, Link2, Monitor, Radio, Globe, Plus } from 'lucide-react';
+import api from '@/services/api';
import { PageTopbar } from '@/components/ds';
+import EmptyState from '@/components/EmptyState';
+import { Button } from '@/components/ui/button';
+import { useToast } from '@/contexts/ToastContext';
+
+import OverviewTab from './tabs/OverviewTab.jsx';
+import PagesTab from './tabs/PagesTab.jsx';
+import ReferrersTab from './tabs/ReferrersTab.jsx';
+import DevicesTab from './tabs/DevicesTab.jsx';
+import RealtimeTab from './tabs/RealtimeTab.jsx';
+import SitesTab from './tabs/SitesTab.jsx';
+
+import '../styles/analytics.scss';
+
+// Route-driven tabs. plugin.json maps /analytics and /analytics/:tab here, so the
+// active tab is read from useParams().tab (undefined => overview).
+const TABS = [
+ { slug: 'overview', to: '/analytics', label: 'Overview', end: true, icon: <BarChart3 size={15} /> },
+ { slug: 'pages', to: '/analytics/pages', label: 'Pages', icon: <FileText size={15} /> },
+ { slug: 'referrers', to: '/analytics/referrers', label: 'Referrers', icon: <Link2 size={15} /> },
+ { slug: 'devices', to: '/analytics/devices', label: 'Devices', icon: <Monitor size={15} /> },
+ { slug: 'realtime', to: '/analytics/realtime', label: 'Realtime', icon: <Radio size={15} /> },
+ { slug: 'sites', to: '/analytics/sites', label: 'Sites', icon: <Globe size={15} /> },
+];
+const VALID_TABS = TABS.map((t) => t.slug);
+const REPORT_TABS = ['overview', 'pages', 'referrers', 'devices', 'realtime'];
export function AnalyticsPage() {
+ const toast = useToast();
+ const navigate = useNavigate();
+ const { tab } = useParams();
+ const activeTab = VALID_TABS.includes(tab) ? tab : 'overview';
+
+ const [sites, setSites] = useState([]);
+ const [sitesLoading, setSitesLoading] = useState(true);
+ const [selectedSiteId, setSelectedSiteId] = useState(null);
+
+ const loadSites = useCallback(async () => {
+ setSitesLoading(true);
+ try {
+ const data = await api.request('/analytics/sites');
+ setSites(data?.sites || []);
+ } catch (error) {
+ toast.error(`Could not load sites: ${error.message}`);
+ setSites([]);
+ } finally {
+ setSitesLoading(false);
+ }
+ }, [toast]);
+
+ useEffect(() => { loadSites(); }, [loadSites]);
+
+ // Keep a valid selection: default to the first site, and re-point if the
+ // current selection disappears (e.g. after a delete).
+ useEffect(() => {
+ if (sites.length === 0) { setSelectedSiteId(null); return; }
+ setSelectedSiteId((prev) => {
+ if (prev != null && sites.some((s) => String(s.id) === String(prev))) return prev;
+ return String(sites[0].id);
+ });
+ }, [sites]);
+
+ const isReport = REPORT_TABS.includes(activeTab);
+
+ const renderReportBody = () => {
+ if (sitesLoading || (sites.length > 0 && selectedSiteId == null)) {
+ return <EmptyState loading title="Loading analytics…" />;
+ }
+ if (sites.length === 0) {
+ return (
+ <div className="analytics-empty">
+ <EmptyState
+ icon={Globe}
+ title="No tracked sites yet"
+ description="Add a site to generate a tracking snippet and start collecting privacy-first analytics."
+ action={(
+ <Button variant="default" size="sm" onClick={() => navigate('/analytics/sites')}>
+ <Plus size={14} /> Add a site
+ </Button>
+ )}
+ />
+ </div>
+ );
+ }
+ // Remount on site change so each tab resets its own range/loading state.
+ switch (activeTab) {
+ case 'pages': return <PagesTab key={selectedSiteId} siteId={selectedSiteId} />;
+ case 'referrers': return <ReferrersTab key={selectedSiteId} siteId={selectedSiteId} />;
+ case 'devices': return <DevicesTab key={selectedSiteId} siteId={selectedSiteId} />;
+ case 'realtime': return <RealtimeTab key={selectedSiteId} siteId={selectedSiteId} />;
+ default: return <OverviewTab key={selectedSiteId} siteId={selectedSiteId} />;
+ }
+ };
+
+ // Report tabs get a site picker in the topbar; the Sites tab manages its own.
+ const topbarActions = isReport && sites.length > 0 ? (
+ <select
+ className="analytics-site-select"
+ value={selectedSiteId ?? ''}
+ onChange={(e) => setSelectedSiteId(e.target.value)}
+ aria-label="Selected site"
+ >
+ {sites.map((s) => (
+ <option key={s.id} value={String(s.id)}>{s.name}</option>
+ ))}
+ </select>
+ ) : null;
+
return (
<div className="analytics-page">
- <PageTopbar title="Web Analytics" />
- <div className="sk-tabgroup__inner">
- <p>Web Analytics is installing. The dashboard will appear here.</p>
+ <PageTopbar
+ icon={<BarChart3 size={18} />}
+ title="Web Analytics"
+ actions={topbarActions}
+ />
+
+ <nav className="analytics-tabs" aria-label="Web Analytics sections">
+ {TABS.map((t) => (
+ <NavLink
+ key={t.slug}
+ to={t.to}
+ end={t.end}
+ className={({ isActive }) => `analytics-tabs__tab${isActive ? ' is-active' : ''}`}
+ >
+ {t.icon}
+ {t.label}
+ </NavLink>
+ ))}
+ </nav>
+
+ <div className="analytics-page__body">
+ {activeTab === 'sites'
+ ? <SitesTab sites={sites} loading={sitesLoading} reload={loadSites} />
+ : renderReportBody()}
</div>
</div>
);
diff --git a/frontend/src/plugins/serverkit-analytics/components/RangePicker.jsx b/frontend/src/plugins/serverkit-analytics/components/RangePicker.jsx
new file mode 100644
index 00000000..aa86c32a
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/components/RangePicker.jsx
@@ -0,0 +1,28 @@
+// Shared date-range picker for the report tabs. Rendered as a small segmented
+// button group styled by our own `.analytics-range` rules (isolated SCSS).
+const RANGES = [
+ { value: '1d', label: '24h' },
+ { value: '7d', label: '7d' },
+ { value: '14d', label: '14d' },
+ { value: '30d', label: '30d' },
+ { value: '90d', label: '90d' },
+];
+
+export default function RangePicker({ value, onChange }) {
+ return (
+ <div className="analytics-range" role="tablist" aria-label="Date range">
+ {RANGES.map((r) => (
+ <button
+ key={r.value}
+ type="button"
+ role="tab"
+ aria-selected={value === r.value}
+ className={`analytics-range__btn${value === r.value ? ' is-active' : ''}`}
+ onClick={() => onChange(r.value)}
+ >
+ {r.label}
+ </button>
+ ))}
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/DevicesTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/DevicesTab.jsx
new file mode 100644
index 00000000..7bb48205
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/components/tabs/DevicesTab.jsx
@@ -0,0 +1,73 @@
+import { useCallback, useEffect, useState } from 'react';
+import { Monitor, Globe, Cpu, MapPin } from 'lucide-react';
+import api from '@/services/api';
+import { DataTable } from '@/components/ds';
+import EmptyState from '@/components/EmptyState';
+import { useToast } from '@/contexts/ToastContext';
+import RangePicker from '../RangePicker.jsx';
+import { formatInt, labelOrDirect } from '../../utils/format.js';
+
+const makeColumns = (header) => [
+ { key: 'value', header, className: 'analytics-col-grow', render: (r) => (
+ <span title={r.value}>{labelOrDirect(r.value)}</span>
+ ) },
+ { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },
+ { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },
+];
+
+const SECTIONS = [
+ { key: 'device', label: 'Device class', icon: Monitor, columns: makeColumns('Device') },
+ { key: 'browser', label: 'Browser', icon: Globe, columns: makeColumns('Browser') },
+ { key: 'os', label: 'Operating system', icon: Cpu, columns: makeColumns('OS') },
+ { key: 'country', label: 'Country', icon: MapPin, columns: makeColumns('Country') },
+];
+
+export default function DevicesTab({ siteId }) {
+ const toast = useToast();
+ const [range, setRange] = useState('7d');
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${siteId}/devices?range=${range}`);
+ setData(res);
+ } catch (error) {
+ toast.error(`Could not load devices: ${error.message}`);
+ setData(null);
+ } finally {
+ setLoading(false);
+ }
+ }, [siteId, range, toast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar">
+ <RangePicker value={range} onChange={setRange} />
+ </div>
+ {loading ? (
+ <EmptyState loading title="Loading devices…" />
+ ) : (
+ <div className="analytics-grid analytics-grid--devices">
+ {SECTIONS.map(({ key, label, icon: Icon, columns }) => (
+ <div className="analytics-panel" key={key}>
+ <div className="analytics-panel__head">
+ <Icon size={15} /> {label}
+ </div>
+ <DataTable
+ columns={columns}
+ data={data?.[key] || []}
+ keyField="value"
+ emptyTitle={`No ${label.toLowerCase()} data`}
+ emptyMessage="Nothing recorded in this range yet."
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/OverviewTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/OverviewTab.jsx
new file mode 100644
index 00000000..8bad763b
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/components/tabs/OverviewTab.jsx
@@ -0,0 +1,160 @@
+import { useCallback, useEffect, useState } from 'react';
+import {
+ ResponsiveContainer, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
+} from 'recharts';
+import { Users, Eye, TrendingDown, Zap, Radio, BarChart3 } from 'lucide-react';
+import api from '@/services/api';
+import { DataTable } from '@/components/ds';
+import EmptyState from '@/components/EmptyState';
+import { useToast } from '@/contexts/ToastContext';
+import RangePicker from '../RangePicker.jsx';
+import { formatInt, formatMs, formatPct, formatDay, labelOrDirect } from '../../utils/format.js';
+
+const KPIS = [
+ { key: 'visitors', label: 'Visitors', icon: Users, tone: 'accent', fmt: formatInt },
+ { key: 'pageviews', label: 'Pageviews', icon: Eye, tone: 'cyan', fmt: formatInt },
+ { key: 'bounce_rate', label: 'Bounce rate', icon: TrendingDown, tone: 'amber', fmt: formatPct },
+ { key: 'avg_load_ms', label: 'Avg load', icon: Zap, tone: 'violet', fmt: formatMs },
+];
+
+const pageColumns = [
+ { key: 'value', header: 'Page', className: 'analytics-col-grow', render: (r) => (
+ <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>
+ ) },
+ { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },
+ { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },
+ { key: 'avg_load_ms', header: 'Avg load', render: (r) => formatMs(r.avg_load_ms) },
+];
+
+const referrerColumns = [
+ { key: 'value', header: 'Referrer', className: 'analytics-col-grow', render: (r) => (
+ <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>
+ ) },
+ { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },
+ { key: 'pageviews', header: 'Views', sortable: true, render: (r) => formatInt(r.pageviews) },
+];
+
+export default function OverviewTab({ siteId }) {
+ const toast = useToast();
+ const [range, setRange] = useState('7d');
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${siteId}/overview?range=${range}`);
+ setData(res);
+ } catch (error) {
+ toast.error(`Could not load overview: ${error.message}`);
+ setData(null);
+ } finally {
+ setLoading(false);
+ }
+ }, [siteId, range, toast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ const totals = data?.totals || {};
+ const timeseries = data?.timeseries || [];
+ const realtime = data?.realtime || {};
+ const hasTraffic = (totals.pageviews || 0) > 0 || (totals.visitors || 0) > 0;
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar">
+ <RangePicker value={range} onChange={setRange} />
+ <span className="analytics-live" title="Active visitors in the last 30 minutes">
+ <Radio size={14} className="analytics-live__dot" />
+ {formatInt(realtime.active_visitors)} active now
+ </span>
+ </div>
+
+ <div className="analytics-kpis">
+ {KPIS.map(({ key, label, icon: Icon, tone, fmt }) => (
+ <div className="analytics-kpi" key={key}>
+ <span className={`analytics-kpi__icon analytics-kpi__icon--${tone}`}>
+ <Icon size={16} />
+ </span>
+ <div className="analytics-kpi__val">{loading ? '—' : fmt(totals[key])}</div>
+ <div className="analytics-kpi__label">{label}</div>
+ </div>
+ ))}
+ </div>
+
+ {loading ? (
+ <EmptyState loading title="Loading overview…" />
+ ) : !hasTraffic ? (
+ <div className="analytics-empty">
+ <EmptyState
+ icon={BarChart3}
+ title="No traffic in this range yet"
+ description="Once the tracking snippet is installed and visitors arrive, their pageviews show up here."
+ />
+ </div>
+ ) : (
+ <>
+ <div className="analytics-chart-card">
+ <div className="analytics-chart-card__head">Visitors &amp; pageviews</div>
+ <ResponsiveContainer width="100%" height={260}>
+ <AreaChart data={timeseries} margin={{ top: 8, right: 8, left: -16, bottom: 0 }}>
+ <defs>
+ <linearGradient id="anVisitors" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor="#6d7cff" stopOpacity={0.35} />
+ <stop offset="95%" stopColor="#6d7cff" stopOpacity={0} />
+ </linearGradient>
+ <linearGradient id="anPageviews" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor="#22c7d6" stopOpacity={0.3} />
+ <stop offset="95%" stopColor="#22c7d6" stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ <CartesianGrid strokeDasharray="3 3" stroke="#888" strokeOpacity={0.15} />
+ <XAxis
+ dataKey="date"
+ tickFormatter={formatDay}
+ tick={{ fontSize: 11, fill: '#888' }}
+ minTickGap={24}
+ axisLine={false}
+ tickLine={false}
+ />
+ <YAxis
+ allowDecimals={false}
+ tick={{ fontSize: 11, fill: '#888' }}
+ width={40}
+ axisLine={false}
+ tickLine={false}
+ />
+ <Tooltip labelFormatter={formatDay} />
+ <Area type="monotone" dataKey="visitors" name="Visitors" stroke="#8b93ff" fill="url(#anVisitors)" strokeWidth={2} />
+ <Area type="monotone" dataKey="pageviews" name="Pageviews" stroke="#22c7d6" fill="url(#anPageviews)" strokeWidth={2} />
+ </AreaChart>
+ </ResponsiveContainer>
+ </div>
+
+ <div className="analytics-grid">
+ <div className="analytics-panel">
+ <div className="analytics-panel__head">Top pages</div>
+ <DataTable
+ columns={pageColumns}
+ data={data?.top_pages || []}
+ keyField="value"
+ emptyTitle="No pages yet"
+ emptyMessage="Pageviews will appear here once visitors browse the site."
+ />
+ </div>
+ <div className="analytics-panel">
+ <div className="analytics-panel__head">Top referrers</div>
+ <DataTable
+ columns={referrerColumns}
+ data={data?.top_referrers || []}
+ keyField="value"
+ emptyTitle="No referrers yet"
+ emptyMessage="Sources that send traffic to the site will appear here."
+ />
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/PagesTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/PagesTab.jsx
new file mode 100644
index 00000000..a4c70add
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/components/tabs/PagesTab.jsx
@@ -0,0 +1,56 @@
+import { useCallback, useEffect, useState } from 'react';
+import api from '@/services/api';
+import { DataTable } from '@/components/ds';
+import { useToast } from '@/contexts/ToastContext';
+import RangePicker from '../RangePicker.jsx';
+import { formatInt, formatMs, labelOrDirect } from '../../utils/format.js';
+
+const columns = [
+ { key: 'value', header: 'Page', className: 'analytics-col-grow', render: (r) => (
+ <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>
+ ) },
+ { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },
+ { key: 'pageviews', header: 'Pageviews', sortable: true, render: (r) => formatInt(r.pageviews) },
+ { key: 'avg_load_ms', header: 'Avg load', sortable: true, sortValue: (r) => r.avg_load_ms ?? -1, render: (r) => formatMs(r.avg_load_ms) },
+];
+
+export default function PagesTab({ siteId }) {
+ const toast = useToast();
+ const [range, setRange] = useState('7d');
+ const [rows, setRows] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${siteId}/pages?range=${range}`);
+ setRows(res?.rows || []);
+ } catch (error) {
+ toast.error(`Could not load pages: ${error.message}`);
+ setRows([]);
+ } finally {
+ setLoading(false);
+ }
+ }, [siteId, range, toast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar">
+ <RangePicker value={range} onChange={setRange} />
+ </div>
+ <div className="analytics-panel">
+ <DataTable
+ columns={columns}
+ data={rows}
+ keyField="value"
+ loading={loading}
+ defaultSort={{ key: 'pageviews', direction: 'desc' }}
+ emptyTitle="No pages yet"
+ emptyMessage="Pageviews will appear here once visitors browse the site."
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/RealtimeTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/RealtimeTab.jsx
new file mode 100644
index 00000000..6a8af6b2
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/components/tabs/RealtimeTab.jsx
@@ -0,0 +1,102 @@
+import { useCallback, useEffect, useState } from 'react';
+import { Radio, Users, Eye } from 'lucide-react';
+import api from '@/services/api';
+import { DataTable } from '@/components/ds';
+import { useToast } from '@/contexts/ToastContext';
+import { formatInt, formatClock, labelOrDirect } from '../../utils/format.js';
+
+const MINUTE_OPTIONS = [5, 15, 30, 60];
+const POLL_MS = 15000;
+
+const columns = [
+ { key: 'ts', header: 'Time', render: (r) => <span className="analytics-cell-mono">{formatClock(r.ts)}</span> },
+ { key: 'path', header: 'Page', className: 'analytics-col-grow', render: (r) => (
+ <span className="analytics-cell-mono" title={r.path}>{labelOrDirect(r.path)}</span>
+ ) },
+ { key: 'referrer_host', header: 'Referrer', render: (r) => labelOrDirect(r.referrer_host) },
+ { key: 'device_class', header: 'Device', render: (r) => r.device_class || '—' },
+ { key: 'country', header: 'Country', render: (r) => r.country || '—' },
+];
+
+export default function RealtimeTab({ siteId }) {
+ const toast = useToast();
+ const [minutes, setMinutes] = useState(30);
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ // `silent` polls skip the loading skeleton so the feed refreshes without flicker.
+ const load = useCallback(async (silent = false) => {
+ if (!silent) setLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${siteId}/realtime?minutes=${minutes}`);
+ setData(res);
+ } catch (error) {
+ if (!silent) {
+ toast.error(`Could not load realtime: ${error.message}`);
+ setData(null);
+ }
+ } finally {
+ if (!silent) setLoading(false);
+ }
+ }, [siteId, minutes, toast]);
+
+ useEffect(() => {
+ load(false);
+ const id = setInterval(() => load(true), POLL_MS);
+ return () => clearInterval(id);
+ }, [load]);
+
+ // Realtime events carry no id; synthesize a stable unique key per row so the
+ // table never collides two hits sharing a timestamp.
+ const recent = (data?.recent || []).map((r, i) => ({ ...r, _rid: `${r.ts || 'x'}-${i}` }));
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar">
+ <div className="analytics-range" role="tablist" aria-label="Time window">
+ {MINUTE_OPTIONS.map((m) => (
+ <button
+ key={m}
+ type="button"
+ role="tab"
+ aria-selected={minutes === m}
+ className={`analytics-range__btn${minutes === m ? ' is-active' : ''}`}
+ onClick={() => setMinutes(m)}
+ >
+ {m}m
+ </button>
+ ))}
+ </div>
+ <span className="analytics-live" title="Auto-refreshing">
+ <Radio size={14} className="analytics-live__dot" />
+ Live · last {data?.minutes ?? minutes} min
+ </span>
+ </div>
+
+ <div className="analytics-realtime">
+ <div className="analytics-realtime__stat">
+ <span className="analytics-realtime__icon analytics-realtime__icon--accent"><Users size={18} /></span>
+ <div className="analytics-realtime__val">{loading ? '—' : formatInt(data?.active_visitors)}</div>
+ <div className="analytics-realtime__label">Active visitors</div>
+ </div>
+ <div className="analytics-realtime__stat">
+ <span className="analytics-realtime__icon analytics-realtime__icon--cyan"><Eye size={18} /></span>
+ <div className="analytics-realtime__val">{loading ? '—' : formatInt(data?.pageviews)}</div>
+ <div className="analytics-realtime__label">Pageviews</div>
+ </div>
+ </div>
+
+ <div className="analytics-panel">
+ <div className="analytics-panel__head">Recent activity</div>
+ <DataTable
+ columns={columns}
+ data={recent}
+ keyField="_rid"
+ loading={loading}
+ emptyTitle="No activity yet"
+ emptyMessage="Hits from the last few minutes will stream in here."
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/ReferrersTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/ReferrersTab.jsx
new file mode 100644
index 00000000..b86b093d
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/components/tabs/ReferrersTab.jsx
@@ -0,0 +1,55 @@
+import { useCallback, useEffect, useState } from 'react';
+import api from '@/services/api';
+import { DataTable } from '@/components/ds';
+import { useToast } from '@/contexts/ToastContext';
+import RangePicker from '../RangePicker.jsx';
+import { formatInt, labelOrDirect } from '../../utils/format.js';
+
+const columns = [
+ { key: 'value', header: 'Referrer', className: 'analytics-col-grow', render: (r) => (
+ <span className="analytics-cell-mono" title={r.value}>{labelOrDirect(r.value)}</span>
+ ) },
+ { key: 'visitors', header: 'Visitors', sortable: true, render: (r) => formatInt(r.visitors) },
+ { key: 'pageviews', header: 'Pageviews', sortable: true, render: (r) => formatInt(r.pageviews) },
+];
+
+export default function ReferrersTab({ siteId }) {
+ const toast = useToast();
+ const [range, setRange] = useState('7d');
+ const [rows, setRows] = useState([]);
+ const [loading, setLoading] = useState(true);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${siteId}/referrers?range=${range}`);
+ setRows(res?.rows || []);
+ } catch (error) {
+ toast.error(`Could not load referrers: ${error.message}`);
+ setRows([]);
+ } finally {
+ setLoading(false);
+ }
+ }, [siteId, range, toast]);
+
+ useEffect(() => { load(); }, [load]);
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar">
+ <RangePicker value={range} onChange={setRange} />
+ </div>
+ <div className="analytics-panel">
+ <DataTable
+ columns={columns}
+ data={rows}
+ keyField="value"
+ loading={loading}
+ defaultSort={{ key: 'pageviews', direction: 'desc' }}
+ emptyTitle="No referrers yet"
+ emptyMessage="Sources that send traffic to the site will appear here."
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/serverkit-analytics/components/tabs/SitesTab.jsx b/frontend/src/plugins/serverkit-analytics/components/tabs/SitesTab.jsx
new file mode 100644
index 00000000..3aeaee43
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/components/tabs/SitesTab.jsx
@@ -0,0 +1,318 @@
+import { useCallback, useEffect, useState } from 'react';
+import { Plus, Trash2, RefreshCw, Copy, Check, Code2, Power, Globe } from 'lucide-react';
+import api from '@/services/api';
+import { DataTable, Pill } from '@/components/ds';
+import Modal from '@/components/Modal';
+import ConfirmDialog from '@/components/ConfirmDialog';
+import EmptyState from '@/components/EmptyState';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { useToast } from '@/contexts/ToastContext';
+import { useClipboard } from '@/hooks/useClipboard';
+
+const INITIAL_FORM = { name: '', hostnames: '', allowedOrigins: '', honorDnt: true, enabled: true };
+
+// Split a textarea value on newlines/commas into a clean list of tokens.
+const parseList = (raw) => (raw || '').split(/[\n,]/).map((s) => s.trim()).filter(Boolean);
+
+export default function SitesTab({ sites, loading, reload }) {
+ const toast = useToast();
+ const { copy, copied } = useClipboard({ successMessage: 'Snippet copied' });
+
+ const [busy, setBusy] = useState(false);
+ const [confirm, setConfirm] = useState(null);
+
+ // Add-site modal
+ const [addOpen, setAddOpen] = useState(false);
+ const [form, setForm] = useState(INITIAL_FORM);
+
+ // Snippet modal
+ const [snippetSite, setSnippetSite] = useState(null);
+ const [snippetData, setSnippetData] = useState(null);
+ const [snippetLoading, setSnippetLoading] = useState(false);
+ const [snippetOutlinks, setSnippetOutlinks] = useState(false);
+
+ const fetchSnippet = useCallback(async (site, outlinks) => {
+ setSnippetLoading(true);
+ try {
+ const res = await api.request(`/analytics/sites/${site.id}/snippet?outlinks=${outlinks}`);
+ setSnippetData(res);
+ } catch (error) {
+ toast.error(`Could not load snippet: ${error.message}`);
+ setSnippetData(null);
+ } finally {
+ setSnippetLoading(false);
+ }
+ }, [toast]);
+
+ useEffect(() => {
+ if (snippetSite) fetchSnippet(snippetSite, snippetOutlinks);
+ }, [snippetSite, snippetOutlinks, fetchSnippet]);
+
+ const openAdd = () => { setForm(INITIAL_FORM); setAddOpen(true); };
+ const openSnippet = (site) => { setSnippetOutlinks(false); setSnippetSite(site); };
+ const closeSnippet = () => { setSnippetSite(null); setSnippetData(null); };
+
+ const handleCreate = async () => {
+ const name = form.name.trim();
+ const hostnames = parseList(form.hostnames);
+ if (!name) { toast.error('Name is required.'); return; }
+ if (hostnames.length === 0) { toast.error('Add at least one hostname.'); return; }
+ setBusy(true);
+ try {
+ const site = await api.request('/analytics/sites', {
+ method: 'POST',
+ body: {
+ name,
+ hostnames,
+ allowed_origins: parseList(form.allowedOrigins),
+ honor_dnt: form.honorDnt,
+ enabled: form.enabled,
+ },
+ });
+ setAddOpen(false);
+ toast.success(`Site "${site.name}" created`);
+ await reload();
+ openSnippet(site);
+ } catch (error) {
+ toast.error(`Could not create site: ${error.message}`);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const handleToggle = async (site) => {
+ try {
+ await api.request(`/analytics/sites/${site.id}`, { method: 'PUT', body: { enabled: !site.enabled } });
+ await reload();
+ } catch (error) {
+ toast.error(`Could not update site: ${error.message}`);
+ }
+ };
+
+ const handleRotate = (site) => setConfirm({
+ title: `Rotate key for ${site.name}?`,
+ message: 'A new site key is generated immediately. The old key stops accepting hits, so update the installed snippet afterward.',
+ confirmText: 'Rotate key',
+ variant: 'warning',
+ onConfirm: async () => {
+ setConfirm(null);
+ setBusy(true);
+ try {
+ await api.request(`/analytics/sites/${site.id}/rotate-key`, { method: 'POST' });
+ toast.success('Site key rotated');
+ await reload();
+ if (snippetSite && snippetSite.id === site.id) fetchSnippet(site, snippetOutlinks);
+ } catch (error) {
+ toast.error(`Could not rotate key: ${error.message}`);
+ } finally {
+ setBusy(false);
+ }
+ },
+ });
+
+ const handleDelete = (site) => setConfirm({
+ title: `Delete ${site.name}?`,
+ message: 'This removes the site and all of its collected analytics. This cannot be undone.',
+ confirmText: 'Delete',
+ variant: 'danger',
+ onConfirm: async () => {
+ setConfirm(null);
+ setBusy(true);
+ try {
+ await api.request(`/analytics/sites/${site.id}`, { method: 'DELETE' });
+ toast.success('Site deleted');
+ if (snippetSite && snippetSite.id === site.id) closeSnippet();
+ await reload();
+ } catch (error) {
+ toast.error(`Could not delete site: ${error.message}`);
+ } finally {
+ setBusy(false);
+ }
+ },
+ });
+
+ const columns = [
+ { key: 'name', header: 'Site', sortable: true, render: (s) => (
+ <div className="analytics-site-name">
+ <span className="analytics-site-name__title">{s.name}</span>
+ <span className="analytics-cell-mono analytics-site-name__key">{s.site_key}</span>
+ </div>
+ ) },
+ { key: 'hostnames', header: 'Hostnames', render: (s) => {
+ const list = (s.hostnames || []).join(', ');
+ return <span className="analytics-cell-mono" title={list}>{list || '—'}</span>;
+ } },
+ { key: 'enabled', header: 'Status', render: (s) => (
+ s.enabled ? <Pill kind="green">Enabled</Pill> : <Pill kind="gray">Disabled</Pill>
+ ) },
+ { key: 'actions', header: '', className: 'analytics-col-actions', render: (s) => (
+ <div className="analytics-row-actions">
+ <Button variant="secondary" size="sm" onClick={() => openSnippet(s)} title="Tracking snippet">
+ <Code2 size={14} />
+ </Button>
+ <Button variant="secondary" size="sm" onClick={() => handleToggle(s)} title={s.enabled ? 'Disable' : 'Enable'}>
+ <Power size={14} />
+ </Button>
+ <Button variant="secondary" size="sm" disabled={busy} onClick={() => handleRotate(s)} title="Rotate key">
+ <RefreshCw size={14} />
+ </Button>
+ <Button variant="destructive" size="sm" onClick={() => handleDelete(s)} title="Delete">
+ <Trash2 size={14} />
+ </Button>
+ </div>
+ ) },
+ ];
+
+ return (
+ <div className="analytics-tabbody">
+ <div className="analytics-toolbar analytics-toolbar--between">
+ <span className="analytics-toolbar__hint">
+ {sites.length} site{sites.length === 1 ? '' : 's'} tracked
+ </span>
+ <Button variant="default" size="sm" onClick={openAdd}>
+ <Plus size={14} /> Add site
+ </Button>
+ </div>
+
+ <div className="analytics-panel">
+ <DataTable
+ columns={columns}
+ data={sites}
+ keyField="id"
+ loading={loading}
+ emptyState={(
+ <EmptyState
+ icon={Globe}
+ title="No tracked sites yet"
+ description="Add a site to generate a tracking snippet and start collecting privacy-first analytics."
+ action={(
+ <Button variant="default" size="sm" onClick={openAdd}>
+ <Plus size={14} /> Add site
+ </Button>
+ )}
+ />
+ )}
+ />
+ </div>
+
+ {/* Add-site modal */}
+ <Modal
+ open={addOpen}
+ onClose={() => setAddOpen(false)}
+ title="Add a site"
+ size="lg"
+ footer={(
+ <>
+ <Button variant="outline" onClick={() => setAddOpen(false)}>Cancel</Button>
+ <Button variant="default" onClick={handleCreate} disabled={busy || !form.name.trim()}>
+ <Plus size={14} /> Create site
+ </Button>
+ </>
+ )}
+ >
+ <div className="analytics-form">
+ <div className="form-group">
+ <Label>Name</Label>
+ <Input
+ value={form.name}
+ placeholder="My website"
+ autoFocus
+ onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
+ />
+ </div>
+ <div className="form-group">
+ <Label>Hostnames</Label>
+ <textarea
+ className="analytics-textarea"
+ value={form.hostnames}
+ placeholder={'example.com\nwww.example.com'}
+ spellCheck={false}
+ onChange={(e) => setForm((f) => ({ ...f, hostnames: e.target.value }))}
+ />
+ <p className="analytics-form__hint">One per line (or comma-separated). Hits are accepted from these hostnames.</p>
+ </div>
+ <div className="form-group">
+ <Label>Allowed origins (optional)</Label>
+ <textarea
+ className="analytics-textarea"
+ value={form.allowedOrigins}
+ placeholder={'https://example.com'}
+ spellCheck={false}
+ onChange={(e) => setForm((f) => ({ ...f, allowedOrigins: e.target.value }))}
+ />
+ <p className="analytics-form__hint">Restrict the collector to these CORS origins. Leave empty to allow any.</p>
+ </div>
+ <label className="analytics-check">
+ <input
+ type="checkbox"
+ checked={form.honorDnt}
+ onChange={(e) => setForm((f) => ({ ...f, honorDnt: e.target.checked }))}
+ />
+ <span>Honor the browser&apos;s Do Not Track signal</span>
+ </label>
+ <label className="analytics-check">
+ <input
+ type="checkbox"
+ checked={form.enabled}
+ onChange={(e) => setForm((f) => ({ ...f, enabled: e.target.checked }))}
+ />
+ <span>Start collecting immediately</span>
+ </label>
+ </div>
+ </Modal>
+
+ {/* Tracking snippet modal */}
+ <Modal
+ open={!!snippetSite}
+ onClose={closeSnippet}
+ title={snippetSite ? `Tracking snippet · ${snippetSite.name}` : 'Tracking snippet'}
+ size="lg"
+ footer={<Button variant="outline" onClick={closeSnippet}>Close</Button>}
+ >
+ {snippetLoading ? (
+ <EmptyState loading title="Loading snippet…" />
+ ) : !snippetData ? (
+ <EmptyState title="Snippet unavailable" description="Could not load the tracking snippet for this site." />
+ ) : (
+ <div className="analytics-snippet-wrap">
+ <p className="analytics-form__hint">
+ Paste this into the &lt;head&gt; of every page you want to track. It is cookieless and under 4&nbsp;KB.
+ </p>
+ <label className="analytics-check">
+ <input
+ type="checkbox"
+ checked={snippetOutlinks}
+ onChange={(e) => setSnippetOutlinks(e.target.checked)}
+ />
+ <span>Include outbound-link tracking</span>
+ </label>
+ <pre className="analytics-snippet"><code>{snippetData.snippet}</code></pre>
+ <div className="analytics-snippet__foot">
+ <span className="analytics-cell-mono analytics-snippet__key" title={snippetData.tracker_url}>
+ {snippetData.site_key}
+ </span>
+ <Button variant="default" size="sm" onClick={() => copy(snippetData.snippet)}>
+ {copied ? <Check size={14} /> : <Copy size={14} />}
+ {copied ? 'Copied' : 'Copy'}
+ </Button>
+ </div>
+ </div>
+ )}
+ </Modal>
+
+ {confirm && (
+ <ConfirmDialog
+ isOpen
+ title={confirm.title}
+ message={confirm.message}
+ confirmText={confirm.confirmText}
+ variant={confirm.variant}
+ onConfirm={confirm.onConfirm}
+ onCancel={() => setConfirm(null)}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/plugins/serverkit-analytics/styles/analytics.scss b/frontend/src/plugins/serverkit-analytics/styles/analytics.scss
new file mode 100644
index 00000000..818fab99
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/styles/analytics.scss
@@ -0,0 +1,410 @@
+/* serverkit-analytics — isolated plugin styles.
+ Compiled in ISOLATION from the host: no SCSS $variables, no @import of host
+ partials. Colours come from the host theme via CSS custom properties
+ (var(--token, fallback)) plus neutral rgba(128,128,128,α) tints, so the
+ dashboard tracks light/dark automatically.
+
+ Every in-page rule is namespaced under .analytics-page. The Modal /
+ ConfirmDialog primitives portal to <body> — OUTSIDE the .analytics-page
+ subtree — so the modal-content rules near the bottom of this file are
+ intentionally top-level (same idiom as the tramo extension). All of our
+ class names are `.analytics-*` prefixed, so the few top-level rules cannot
+ collide with the host or other plugins. */
+
+.analytics-page {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+
+ &__body {
+ padding: 18px 24px 28px;
+ }
+
+ /* ── Route-driven tab bar (replaces sidebar sub-menus) ── */
+ .analytics-tabs {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 0 24px;
+ border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.18));
+ overflow-x: auto;
+
+ &__tab {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ padding: 11px 14px;
+ font-size: 13.5px;
+ font-weight: 500;
+ color: var(--text-secondary, rgba(128, 128, 128, 0.9));
+ text-decoration: none;
+ border-bottom: 2px solid transparent;
+ white-space: nowrap;
+ transition: color 0.15s ease, border-color 0.15s ease;
+
+ svg { opacity: 0.8; }
+
+ &:hover { color: var(--text-primary, inherit); }
+
+ &.is-active {
+ color: var(--accent-bright, #6366f1);
+ border-bottom-color: var(--accent-bright, #6366f1);
+ }
+ }
+ }
+
+ /* Site picker in the topbar actions slot */
+ .analytics-site-select {
+ height: 32px;
+ max-width: 220px;
+ padding: 0 10px;
+ border-radius: 8px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.3));
+ background: var(--bg-elevated, rgba(128, 128, 128, 0.06));
+ color: inherit;
+ font-size: 13px;
+ cursor: pointer;
+
+ &:focus { outline: 0; border-color: var(--accent-bright, #6366f1); }
+ }
+
+ /* ── Tab body scaffolding ── */
+ .analytics-tabbody {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ }
+
+ .analytics-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ flex-wrap: wrap;
+
+ &--between { justify-content: space-between; }
+
+ &__hint {
+ font-size: 12.5px;
+ opacity: 0.65;
+ }
+ }
+
+ .analytics-live {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ margin-left: auto;
+ font-size: 12.5px;
+ font-weight: 500;
+ color: var(--green, #22c55e);
+
+ &__dot {
+ color: var(--green, #22c55e);
+ animation: analytics-pulse 1.8s ease-in-out infinite;
+ }
+ }
+
+ /* Range / minutes segmented control */
+ .analytics-range {
+ display: inline-flex;
+ gap: 2px;
+ padding: 3px;
+ border-radius: 9px;
+ background: rgba(128, 128, 128, 0.1);
+
+ &__btn {
+ border: 0;
+ background: transparent;
+ color: var(--text-secondary, inherit);
+ font-size: 12.5px;
+ font-weight: 500;
+ padding: 5px 11px;
+ border-radius: 7px;
+ cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease;
+
+ &:hover { color: var(--text-primary, inherit); }
+
+ &.is-active {
+ background: var(--bg-card, rgba(128, 128, 128, 0.9));
+ color: var(--accent-bright, #6366f1);
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12);
+ }
+ }
+ }
+
+ /* ── KPI tiles ── */
+ .analytics-kpis {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ gap: 12px;
+ }
+
+ .analytics-kpi {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 16px;
+ border-radius: 12px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.16));
+ background: var(--bg-card, rgba(128, 128, 128, 0.03));
+
+ &__icon {
+ width: 34px;
+ height: 34px;
+ border-radius: 9px;
+ display: grid;
+ place-items: center;
+ background: rgba(128, 128, 128, 0.14);
+ color: var(--accent-bright, #818cf8);
+
+ &--accent { background: rgba(99, 102, 241, 0.16); color: #818cf8; }
+ &--cyan { background: rgba(34, 199, 214, 0.16); color: #22c7d6; }
+ &--amber { background: rgba(234, 179, 8, 0.16); color: #eab308; }
+ &--violet { background: rgba(139, 92, 246, 0.16); color: #a78bfa; }
+ }
+
+ &__val {
+ font-size: 24px;
+ font-weight: 700;
+ line-height: 1.1;
+ color: var(--text-primary, inherit);
+ }
+
+ &__label {
+ font-size: 12.5px;
+ opacity: 0.65;
+ }
+ }
+
+ /* ── Chart card ── */
+ .analytics-chart-card {
+ padding: 16px 16px 8px;
+ border-radius: 12px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.16));
+ background: var(--bg-card, rgba(128, 128, 128, 0.03));
+
+ &__head {
+ font-size: 13px;
+ font-weight: 600;
+ margin-bottom: 12px;
+ opacity: 0.85;
+ }
+ }
+
+ /* ── Grids of tables ── */
+ .analytics-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 16px;
+
+ &--devices {
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
+ }
+
+ @media (max-width: 720px) {
+ grid-template-columns: 1fr;
+ }
+ }
+
+ .analytics-panel {
+ border-radius: 12px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.16));
+ background: var(--bg-card, rgba(128, 128, 128, 0.03));
+ overflow: hidden;
+
+ &__head {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 12px 16px;
+ font-size: 13px;
+ font-weight: 600;
+ border-bottom: 1px solid var(--border, rgba(128, 128, 128, 0.12));
+ opacity: 0.9;
+
+ svg { opacity: 0.7; }
+ }
+ }
+
+ /* ── Realtime counters ── */
+ .analytics-realtime {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+ gap: 12px;
+
+ &__stat {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 18px;
+ border-radius: 12px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.16));
+ background: var(--bg-card, rgba(128, 128, 128, 0.03));
+ }
+
+ &__icon {
+ width: 38px;
+ height: 38px;
+ border-radius: 10px;
+ display: grid;
+ place-items: center;
+ background: rgba(128, 128, 128, 0.14);
+
+ &--accent { background: rgba(99, 102, 241, 0.16); color: #818cf8; }
+ &--cyan { background: rgba(34, 199, 214, 0.16); color: #22c7d6; }
+ }
+
+ &__val {
+ font-size: 30px;
+ font-weight: 700;
+ line-height: 1;
+ color: var(--text-primary, inherit);
+ }
+
+ &__label {
+ font-size: 12.5px;
+ opacity: 0.65;
+ }
+ }
+
+ /* ── Sites table cells ── */
+ .analytics-site-name {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+
+ &__title { font-weight: 600; font-size: 13.5px; }
+ &__key { font-size: 11px; opacity: 0.55; }
+ }
+
+ .analytics-row-actions {
+ display: flex;
+ gap: 6px;
+ justify-content: flex-end;
+ flex-wrap: wrap;
+ }
+
+ .analytics-col-actions {
+ text-align: right;
+ white-space: nowrap;
+ }
+
+ .analytics-col-grow {
+ min-width: 150px;
+ }
+
+ /* In-page empty/dashed wrapper */
+ .analytics-empty {
+ border-radius: 12px;
+ border: 1px dashed var(--border, rgba(128, 128, 128, 0.3));
+ background: var(--bg-card, rgba(128, 128, 128, 0.03));
+ }
+}
+
+/* Shared monospace utility — used in-page (tables) AND inside the portaled
+ snippet modal, so it lives at top level to match both DOM locations. */
+.analytics-cell-mono {
+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
+ font-size: 12.5px;
+}
+
+@keyframes analytics-pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.35; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .analytics-live__dot { animation: none; }
+}
+
+/* ── Portaled modal content (Modal / ConfirmDialog render into <body>, OUTSIDE
+ .analytics-page) — these MUST stay top-level or they never match. ── */
+.analytics-form {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+
+ .form-group { margin: 0; }
+
+ &__hint {
+ margin: 6px 0 0;
+ font-size: 12px;
+ line-height: 1.45;
+ opacity: 0.62;
+ }
+}
+
+.analytics-textarea {
+ width: 100%;
+ min-height: 78px;
+ resize: vertical;
+ padding: 10px 12px;
+ border-radius: 9px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.3));
+ background: var(--bg-elevated, rgba(128, 128, 128, 0.05));
+ color: inherit;
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-size: 12.5px;
+ line-height: 1.5;
+
+ &:focus { outline: 0; border-color: var(--accent-bright, #6366f1); }
+ &::placeholder { opacity: 0.4; }
+}
+
+.analytics-check {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ font-size: 13px;
+ cursor: pointer;
+
+ input {
+ width: 15px;
+ height: 15px;
+ cursor: pointer;
+ accent-color: var(--accent-bright, #6366f1);
+ }
+}
+
+.analytics-snippet-wrap {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.analytics-snippet {
+ margin: 0;
+ max-height: 260px;
+ overflow: auto;
+ padding: 14px;
+ border-radius: 10px;
+ border: 1px solid var(--border, rgba(128, 128, 128, 0.25));
+ background: var(--bg-elevated, rgba(128, 128, 128, 0.08));
+ color: var(--text-primary, inherit);
+ font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
+ font-size: 12px;
+ line-height: 1.55;
+ white-space: pre-wrap;
+ word-break: break-all;
+
+ code {
+ font: inherit;
+ color: inherit;
+ background: none;
+ }
+
+ &__foot {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ }
+
+ &__key {
+ opacity: 0.7;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+}
diff --git a/frontend/src/plugins/serverkit-analytics/utils/format.js b/frontend/src/plugins/serverkit-analytics/utils/format.js
new file mode 100644
index 00000000..47bd7469
--- /dev/null
+++ b/frontend/src/plugins/serverkit-analytics/utils/format.js
@@ -0,0 +1,28 @@
+// Small, dependency-free formatting helpers for the analytics dashboard.
+// Kept isolated (no host imports) so the plugin bundle stays self-contained.
+
+export const formatInt = (n) => Number(n ?? 0).toLocaleString();
+
+export const formatMs = (ms) => (ms == null ? '—' : `${Math.round(ms)} ms`);
+
+export const formatPct = (n) => `${Number(n ?? 0).toFixed(1)}%`;
+
+// A 'YYYY-MM-DD' rollup date → a short "Jul 18" label. Parsed as local midnight
+// (append time) so the label never drifts a day across time zones.
+export const formatDay = (iso) => {
+ if (!iso) return '';
+ const d = new Date(`${iso}T00:00:00`);
+ if (Number.isNaN(d.getTime())) return iso;
+ return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
+};
+
+// An ISO timestamp → a wall-clock "14:03:21" label for the realtime feed.
+export const formatClock = (iso) => {
+ if (!iso) return '—';
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return '—';
+ return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
+};
+
+// Referrer/path dimension value → a readable label ("Direct / none" for empties).
+export const labelOrDirect = (value) => (value && value.trim() ? value : 'Direct / none');