Move the dashboard and setup pages to a Vue SPA
The pages are now a Vue 3 + Vite + TypeScript app in web/, built into internal/web/dist/app and embedded in the binary. Go still serves index.html for / and /setup behind the admin gate, plus the hashed /assets/* (public, cached forever). The router takes its base from the current URL, so it works under nginx's /tracker/ prefix unchanged. Only dist/.gitkeep is committed, so go build and go test need no Node; an unbuilt binary shows a "run make web" page at /. The Dockerfile gains a Node stage, CI typechecks and builds the app, and make build/run build it first. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+4
-3
@@ -43,9 +43,10 @@ func New(s *store.Store, admin auth.Checker, loc *time.Location, log *slog.Logge
|
||||
})
|
||||
mux.HandleFunc("GET /readyz", srv.ready)
|
||||
mux.HandleFunc("GET /tracker.user.js", web.UserScript)
|
||||
mux.HandleFunc("GET /style.css", web.Style)
|
||||
mux.Handle("GET /{$}", srv.adminPage(web.Page(web.Index)))
|
||||
mux.Handle("GET /setup", srv.adminPage(web.Page(web.Setup)))
|
||||
mux.Handle("GET /assets/", web.Assets())
|
||||
// The Vue app's routes; it sends visitors between them itself.
|
||||
mux.Handle("GET /{$}", srv.adminPage(http.HandlerFunc(web.App)))
|
||||
mux.Handle("GET /setup", srv.adminPage(http.HandlerFunc(web.App)))
|
||||
|
||||
api := http.NewServeMux()
|
||||
api.Handle("POST /desktop/events", srv.device(srv.ingestEvents(ingest.Desktop)))
|
||||
|
||||
Vendored
@@ -1,146 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Activity Tracker</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<nav class="topbar">
|
||||
<span class="brand">Activity Tracker</span>
|
||||
<div class="tabs">
|
||||
<a href="./" aria-current="page">Dashboard</a>
|
||||
<a href="setup">Setup</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<div class="row spread">
|
||||
<h1 id="title">Today</h1>
|
||||
<div class="row">
|
||||
<button id="prev" aria-label="Previous day">‹</button>
|
||||
<input type="date" id="date" aria-label="Day">
|
||||
<button id="next" aria-label="Next day">›</button>
|
||||
<button id="today">Today</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p id="status" class="muted"></p>
|
||||
<div id="content" hidden>
|
||||
<div class="tiles">
|
||||
<div class="tile"><div class="k">Desktop time</div><div class="v" id="t-desktop">–</div></div>
|
||||
<div class="tile"><div class="k">Browser time</div><div class="v" id="t-browser">–</div></div>
|
||||
<div class="tile"><div class="k">Top site or app</div><div class="v" id="t-top">–</div></div>
|
||||
<div class="tile"><div class="k">Goals met</div><div class="v" id="t-goals">–</div></div>
|
||||
</div>
|
||||
<section class="card"><h2>Goals</h2><div class="tablewrap"><table id="goals"></table></div></section>
|
||||
<section class="card"><h2>By kind</h2><div class="tablewrap"><table id="kinds"></table></div></section>
|
||||
<section class="card"><h2>Top labels</h2><div class="tablewrap"><table id="labels"></table></div></section>
|
||||
<section class="card"><h2>Timeline</h2><div class="tablewrap"><table id="timeline"></table></div></section>
|
||||
</div>
|
||||
</main>
|
||||
<script>
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
function dur(s) {
|
||||
s = Math.round(s);
|
||||
const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60);
|
||||
if (h) return `${h}h ${String(m).padStart(2, "0")}m`;
|
||||
return m ? `${m}m` : `${s}s`;
|
||||
}
|
||||
const time = t => new Date(t).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
const esc = s => String(s ?? "").replace(/[&<>"]/g, c => ({ "&":"&", "<":"<", ">":">", '"':""" }[c]));
|
||||
// Friendlier names for the kinds collectors send; anything else shows as is.
|
||||
const KINDS = { app_focus: "desktop", tab_focus: "browser", at_desk: "at desk", in_bed: "in bed" };
|
||||
const kind = k => esc(KINDS[k] || k);
|
||||
const today = () => new Date().toLocaleDateString("en-CA"); // YYYY-MM-DD in local time
|
||||
|
||||
async function api(path) {
|
||||
// Authenticated by the main site's session cookies, which the browser sends.
|
||||
const r = await fetch("api/v1/" + path);
|
||||
const body = await r.json().catch(() => ({}));
|
||||
if (r.status === 401) { location.reload(); throw new Error("session expired"); } // reload goes to the login page
|
||||
if (!r.ok) throw new Error(body.error || r.statusText);
|
||||
return body;
|
||||
}
|
||||
|
||||
function rows(el, items, render, empty) {
|
||||
el.innerHTML = items.length ? items.map(render).join("") : `<tr><td class="muted">${empty}</td></tr>`;
|
||||
}
|
||||
|
||||
function setTitle(date) {
|
||||
const d = new Date(date + "T12:00:00");
|
||||
const diff = Math.round((new Date(today() + "T12:00:00") - d) / 864e5);
|
||||
$("title").textContent = diff === 0 ? "Today" : diff === 1 ? "Yesterday"
|
||||
: d.toLocaleDateString([], { weekday: "long", day: "numeric", month: "long" });
|
||||
$("today").disabled = diff === 0;
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const date = $("date").value;
|
||||
setTitle(date);
|
||||
$("status").textContent = "Loading…";
|
||||
try {
|
||||
const sum = await api("summary/daily?date=" + date);
|
||||
const q = new URLSearchParams({ from: sum.from, to: sum.to, limit: "500" });
|
||||
const { activities } = await api("activities?" + q);
|
||||
|
||||
$("t-desktop").textContent = dur(sum.by_kind.app_focus || 0);
|
||||
$("t-browser").textContent = dur(sum.by_kind.tab_focus || 0);
|
||||
const focus = sum.totals.filter(t => t.kind === "app_focus" || t.kind === "tab_focus")
|
||||
.sort((a, b) => b.seconds - a.seconds)[0];
|
||||
$("t-top").textContent = focus ? focus.label || "—" : "–";
|
||||
$("t-goals").textContent = sum.goals.length ? `${sum.goals.filter(g => g.met).length} / ${sum.goals.length}` : "–";
|
||||
|
||||
rows($("goals"), sum.goals, g => `<tr>
|
||||
<td class="label">${kind(g.kind)}${g.label ? " · " + esc(g.label) : ""}
|
||||
<span class="muted">${esc(g.op)} ${dur(g.target_s)}</span></td>
|
||||
<td class="num">${dur(g.actual_s)}</td>
|
||||
<td class="num ${g.met ? "ok" : "bad"}">${g.met ? "✓ met" : "✗ missed"}</td></tr>`,
|
||||
`No goals yet. See <a href="setup#goals">Setup</a>.`);
|
||||
|
||||
const kinds = Object.entries(sum.by_kind).sort((a, b) => b[1] - a[1]);
|
||||
const maxK = kinds[0]?.[1] || 1;
|
||||
rows($("kinds"), kinds, ([k, s]) => `<tr>
|
||||
<td class="label">${kind(k)}<div class="bar" style="width:${s / maxK * 100}%"></div></td>
|
||||
<td class="num">${dur(s)}</td></tr>`, "Nothing recorded.");
|
||||
|
||||
const labels = [...sum.totals].sort((a, b) => b.seconds - a.seconds).slice(0, 15);
|
||||
const maxL = labels[0]?.seconds || 1;
|
||||
rows($("labels"), labels, t => `<tr>
|
||||
<td class="label">${esc(t.label || "—")} <span class="badge">${kind(t.kind)}</span>
|
||||
<div class="bar" style="width:${t.seconds / maxL * 100}%"></div></td>
|
||||
<td class="num">${dur(t.seconds)}</td></tr>`, "Nothing recorded.");
|
||||
|
||||
const acts = activities.filter(a => a.duration_s >= 60)
|
||||
.sort((a, b) => new Date(b.started_at) - new Date(a.started_at));
|
||||
rows($("timeline"), acts, a => `<tr>
|
||||
<td class="time">${time(a.started_at)}–${time(a.ended_at)}</td>
|
||||
<td class="label">${esc(a.label || a.kind)} <span class="badge">${kind(a.kind)}</span>
|
||||
${a.attrs?.title ? `<div class="muted small-text">${esc(a.attrs.title)}</div>` : ""}</td>
|
||||
<td class="num">${dur(a.duration_s)}</td></tr>`, "No activities of a minute or longer.");
|
||||
|
||||
$("content").hidden = false;
|
||||
$("status").textContent = activities.length >= 500 ? "Timeline shows the first 500 activities." : "";
|
||||
} catch (e) {
|
||||
$("status").innerHTML = `<span class="err">${esc(e.message)}</span>`;
|
||||
}
|
||||
}
|
||||
|
||||
function shift(days) {
|
||||
const d = new Date($("date").value + "T12:00:00");
|
||||
d.setDate(d.getDate() + days);
|
||||
$("date").value = d.toLocaleDateString("en-CA");
|
||||
load();
|
||||
}
|
||||
|
||||
$("prev").onclick = () => shift(-1);
|
||||
$("next").onclick = () => shift(1);
|
||||
$("today").onclick = () => { $("date").value = today(); load(); };
|
||||
$("date").onchange = load;
|
||||
$("date").value = today();
|
||||
load();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,278 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Activity Tracker Setup</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<nav class="topbar">
|
||||
<span class="brand">Activity Tracker</span>
|
||||
<div class="tabs">
|
||||
<a href="./">Dashboard</a>
|
||||
<a href="setup" aria-current="page">Setup</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<h1>Setup</h1>
|
||||
<p class="muted">Each collector uploads to <code class="base"></code> with its own API key. Open a collector below and click <b>Generate key</b>; the key is filled into its steps. A key is shown only once.</p>
|
||||
|
||||
<section class="card">
|
||||
<div class="row spread"><h2>Devices</h2></div>
|
||||
<div class="tablewrap"><table id="devices"><tr><td class="muted">Loading…</td></tr></table></div>
|
||||
<form class="row" id="create" style="margin-top:12px">
|
||||
<select id="kind" aria-label="Kind">
|
||||
<option value="browser">Browser</option>
|
||||
<option value="hyprland">Hyprland</option>
|
||||
<option value="health">Apple Health</option>
|
||||
<option value="manual">Script / manual</option>
|
||||
<option value="presence">Presence</option>
|
||||
</select>
|
||||
<input id="name" placeholder="Name (optional)" aria-label="Name" style="flex:1; min-width:140px">
|
||||
<button class="primary">Generate key</button>
|
||||
</form>
|
||||
<div class="keyslot"></div>
|
||||
<p id="status" class="small-text"></p>
|
||||
</section>
|
||||
|
||||
<details class="collector" id="browser" open>
|
||||
<summary><b>Browser</b><span class="muted">Violentmonkey userscript · time per site</span></summary>
|
||||
<div class="body">
|
||||
<p>Records <code>tab_focus</code> intervals labelled by hostname. A tab counts only while it's the selected tab of the focused window, and stops after 5 minutes without input unless video or audio is playing.</p>
|
||||
<button class="primary" data-kind="browser">Generate key for this browser</button>
|
||||
<div class="keyslot"></div>
|
||||
<ol>
|
||||
<li>Install Violentmonkey: <a href="https://addons.mozilla.org/firefox/addon/violentmonkey/" target="_blank" rel="noopener">Firefox</a> · <a href="https://chromewebstore.google.com/detail/violentmonkey/jinjaccalgkegednnccohejagnlnfdag" target="_blank" rel="noopener">Chrome / Chromium</a></li>
|
||||
<li>Open <a class="script" href="tracker.user.js"></a> and click <b>Install</b>. Violentmonkey checks this URL for updates.</li>
|
||||
<li>Click the Violentmonkey toolbar icon, then <b>Activity Tracker → Set server and API key</b>. Enter the server and key:
|
||||
<pre class="base"></pre>
|
||||
<pre class="key">trk_… (generate a key above)</pre></li>
|
||||
<li>Check it with <b>Status / upload now</b> in the same menu. Uploads happen every minute.</li>
|
||||
</ol>
|
||||
<p class="muted small-text">The menu also turns full URLs and page titles on or off (both off by default), sets hosts to ignore, and changes the idle timeout. It runs on every web page and on local <code>file://</code> pages (labelled <code>file</code>; in Chrome, turn on <b>Allow access to file URLs</b> in Violentmonkey's extension details). Browsers block all extensions on <code>about:</code> pages, the new tab page, extension stores and the PDF viewer, so those aren't recorded; Hyprland still counts them as browser time.</p>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="collector" id="hyprland">
|
||||
<summary><b>Hyprland desktop</b><span class="muted">focused window, idle and locked time</span></summary>
|
||||
<div class="body">
|
||||
<p>Records <code>app_focus</code> intervals labelled by window class, with the title.</p>
|
||||
<button class="primary" data-kind="hyprland">Generate key for this machine</button>
|
||||
<div class="keyslot"></div>
|
||||
<h3>1. Install the agent</h3>
|
||||
<pre>git clone ssh://[email protected]:2222/adamf/ccp.git && cd ccp
|
||||
make install-agent # ~/.local/bin/hypr-agent and the systemd user unit</pre>
|
||||
<h3>2. Configure and start it</h3>
|
||||
<pre>mkdir -p ~/.config/hypr-agent
|
||||
cat > ~/.config/hypr-agent/env <<EOF
|
||||
TRACKER_URL=<span class="base"></span>
|
||||
TRACKER_API_KEY=<span class="key">trk_…</span>
|
||||
# HYPR_AGENT_TITLES=false # don't send window titles at all
|
||||
# HYPR_AGENT_REDACT=(?i)bank|private # replace matching titles with [redacted]
|
||||
EOF
|
||||
chmod 600 ~/.config/hypr-agent/env
|
||||
systemctl --user enable --now hypr-agent</pre>
|
||||
<h3>3. Idle and lock (optional)</h3>
|
||||
<p>Add to <code>~/.config/hypr/hypridle.conf</code>:</p>
|
||||
<pre>general {
|
||||
lock_cmd = hypr-agent lock; pidof hyprlock || hyprlock
|
||||
unlock_cmd = hypr-agent unlock
|
||||
}
|
||||
|
||||
listener {
|
||||
timeout = 300
|
||||
on-timeout = hypr-agent idle
|
||||
on-resume = hypr-agent resume
|
||||
}</pre>
|
||||
<p class="muted small-text">Check it with <code>journalctl --user -u hypr-agent -f</code>. Events upload every minute and wait in <code>~/.local/state/hypr-agent/buffer.jsonl</code> while the server can't be reached.</p>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="collector" id="health">
|
||||
<summary><b>Apple Health</b><span class="muted">walks, workouts, steps, sleep</span></summary>
|
||||
<div class="body">
|
||||
<p>Workouts become activities (<code>walk</code>, <code>run</code>, <code>workout</code>); step counts, sleep and other metrics become samples.</p>
|
||||
<button class="primary" data-kind="health">Generate key for Health Auto Export</button>
|
||||
<div class="keyslot"></div>
|
||||
<p>In the Health Auto Export iOS app, create a <b>REST API</b> automation:</p>
|
||||
<ul>
|
||||
<li>URL: <code><span class="base"></span>/api/v1/health/hae</code></li>
|
||||
<li>Header: <code>Authorization</code> = <code>Bearer <span class="key">trk_…</span></code></li>
|
||||
<li>Format: JSON · Sync cadence: hourly</li>
|
||||
<li>Data: Workouts, plus metrics such as Step Count and Sleep Analysis</li>
|
||||
</ul>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="collector" id="manual">
|
||||
<summary><b>Scripts</b><span class="muted">post any interval with curl</span></summary>
|
||||
<div class="body">
|
||||
<button class="primary" data-kind="manual">Generate key for scripts</button>
|
||||
<div class="keyslot"></div>
|
||||
<pre>curl -X POST <span class="base"></span>/api/v1/manual/events \
|
||||
-H 'Authorization: Bearer <span class="key">trk_…</span>' -H 'Content-Type: application/json' \
|
||||
-d '{"events":[{"id":"reading-2026-10-14","kind":"reading","label":"book",
|
||||
"started_at":"2026-10-14T20:00:00Z","ended_at":"2026-10-14T20:45:00Z"}]}'</pre>
|
||||
<p class="muted small-text">The <code>id</code> makes re-sending safe: a duplicate is ignored. Webcam presence (<code>/api/v1/presence/events</code>) has an endpoint but no agent yet.</p>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="collector" id="goals">
|
||||
<summary><b>Goals</b><span class="muted">daily targets on the dashboard</span></summary>
|
||||
<div class="body">
|
||||
<p>Managed on the Pi. An empty label matches every label of that kind.</p>
|
||||
<pre>docker exec activity-tracker tracker goal add --kind tab_focus --label youtube.com --op '<=' --target 1h
|
||||
docker exec activity-tracker tracker goal add --kind walk --op '>=' --target 30m
|
||||
docker exec activity-tracker tracker goal list
|
||||
docker exec activity-tracker tracker goal rm --id 2</pre>
|
||||
</div>
|
||||
</details>
|
||||
</main>
|
||||
<script>
|
||||
const $ = id => document.getElementById(id);
|
||||
const esc = s => String(s ?? "").replace(/[&<>"]/g, c => ({ "&":"&", "<":"<", ">":">", '"':""" }[c]));
|
||||
|
||||
function ago(t) {
|
||||
if (!t) return "never";
|
||||
const s = (Date.now() - new Date(t)) / 1000;
|
||||
if (s < 90) return "just now";
|
||||
if (s < 3600) return Math.round(s / 60) + " min ago";
|
||||
if (s < 86400) return Math.round(s / 3600) + " h ago";
|
||||
return new Date(t).toLocaleDateString([], { day: "numeric", month: "short", year: "numeric" });
|
||||
}
|
||||
|
||||
// The tracker's public URL, e.g. https://www.adam-french.co.uk/tracker
|
||||
const base = new URL(".", location.href).href.replace(/\/$/, "");
|
||||
document.querySelectorAll(".base").forEach(el => el.textContent = base);
|
||||
document.querySelectorAll("a.script").forEach(el => el.textContent = base + "/tracker.user.js");
|
||||
|
||||
async function api(method, path, body) {
|
||||
const r = await fetch("api/v1/" + path, {
|
||||
method, headers: body ? { "Content-Type": "application/json" } : {},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
const out = await r.json().catch(() => ({}));
|
||||
if (r.status === 401) { location.reload(); throw new Error("session expired"); }
|
||||
if (!r.ok) throw new Error(out.error || r.statusText);
|
||||
return out;
|
||||
}
|
||||
|
||||
function status(msg, cls) {
|
||||
$("status").className = "small-text " + (cls || "");
|
||||
$("status").textContent = msg;
|
||||
}
|
||||
|
||||
async function copy(text, btn) {
|
||||
try { await navigator.clipboard.writeText(text); btn.textContent = "Copied"; }
|
||||
catch { btn.textContent = "Copy failed"; }
|
||||
setTimeout(() => btn.textContent = "Copy", 1500);
|
||||
}
|
||||
|
||||
// A Copy button on every command block.
|
||||
document.querySelectorAll("pre").forEach(pre => {
|
||||
const wrap = document.createElement("div");
|
||||
wrap.className = "codeblock";
|
||||
pre.replaceWith(wrap);
|
||||
wrap.append(pre);
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "small copy"; btn.type = "button"; btn.textContent = "Copy";
|
||||
btn.onclick = () => copy(pre.innerText, btn);
|
||||
wrap.append(btn);
|
||||
});
|
||||
|
||||
// ---- devices and keys ----
|
||||
|
||||
let devices = [];
|
||||
|
||||
async function loadDevices() {
|
||||
try {
|
||||
({ devices } = await api("GET", "devices"));
|
||||
const active = devices.filter(d => !d.revoked_at);
|
||||
const revoked = devices.filter(d => d.revoked_at);
|
||||
$("devices").innerHTML = `<tr><th>Name</th><th>Kind</th><th>Last upload</th><th></th></tr>` +
|
||||
(active.length ? active.map(d => `<tr>
|
||||
<td class="label">${esc(d.name)}</td>
|
||||
<td><span class="badge">${esc(d.kind)}</span></td>
|
||||
<td class="time">${ago(d.last_seen_at)}</td>
|
||||
<td class="num"><button class="small" data-revoke="${esc(d.name)}">Revoke</button></td></tr>`).join("")
|
||||
: `<tr><td colspan="4" class="muted">No devices yet.</td></tr>`) +
|
||||
(revoked.length ? `<tr><td colspan="4" class="muted small-text">${revoked.length} revoked: ${revoked.map(d => esc(d.name)).join(", ")}</td></tr>` : "");
|
||||
} catch (e) {
|
||||
status(e.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
// A readable name that isn't taken yet (names stay taken after revoking).
|
||||
function suggestName(kind) {
|
||||
let stem = { health: "iphone-health", manual: "script" }[kind] || kind;
|
||||
if (kind === "browser") {
|
||||
const ua = navigator.userAgent;
|
||||
stem = /Firefox\//.test(ua) ? "firefox" : /Edg\//.test(ua) ? "edge" : /Chrome\//.test(ua) ? "chrome" : "browser";
|
||||
}
|
||||
const taken = new Set(devices.map(d => d.name));
|
||||
let name = stem;
|
||||
for (let i = 2; taken.has(name); i++) name = `${stem}-${i}`;
|
||||
return name;
|
||||
}
|
||||
|
||||
function showKey(slot, device, key) {
|
||||
document.querySelectorAll(".keyslot").forEach(s => s.innerHTML = "");
|
||||
slot.innerHTML = `<div class="keybox">
|
||||
<div>Key for <b>${esc(device.name)}</b> <span class="badge">${esc(device.kind)}</span>. Copy it now; it won't be shown again.</div>
|
||||
<div class="codeblock"><pre>${esc(key)}</pre><button class="small copy" type="button">Copy</button></div>
|
||||
</div>`;
|
||||
const btn = slot.querySelector("button");
|
||||
btn.onclick = () => copy(key, btn);
|
||||
copy(key, btn);
|
||||
}
|
||||
|
||||
async function generate(kind, name, slot, button) {
|
||||
button.disabled = true;
|
||||
try {
|
||||
if (!devices.length) await loadDevices();
|
||||
const { device, key } = await api("POST", "devices", { kind, name: name || suggestName(kind) });
|
||||
showKey(slot, device, key);
|
||||
// Fill the key into this collector's steps so they can be copied as-is.
|
||||
const section = $(kind);
|
||||
if (section) {
|
||||
section.open = true;
|
||||
section.querySelectorAll(".key").forEach(el => el.textContent = key);
|
||||
}
|
||||
status("");
|
||||
loadDevices();
|
||||
return true;
|
||||
} catch (e) {
|
||||
status(e.message, "err");
|
||||
return false;
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
$("create").onsubmit = e => {
|
||||
e.preventDefault();
|
||||
const btn = e.submitter || $("create").querySelector("button");
|
||||
generate($("kind").value, $("name").value.trim(), $("create").nextElementSibling, btn)
|
||||
.then(ok => { if (ok) $("name").value = ""; });
|
||||
};
|
||||
document.querySelectorAll("button[data-kind]").forEach(btn => {
|
||||
btn.onclick = () => generate(btn.dataset.kind, "", btn.nextElementSibling, btn);
|
||||
});
|
||||
|
||||
$("devices").onclick = async e => {
|
||||
const name = e.target.dataset?.revoke;
|
||||
if (!name || !confirm(`Revoke ${name}? Its collector will stop being able to upload.`)) return;
|
||||
try {
|
||||
await api("DELETE", "devices/" + encodeURIComponent(name));
|
||||
status(`Revoked ${name}.`, "ok");
|
||||
loadDevices();
|
||||
} catch (err) { status(err.message, "err"); }
|
||||
};
|
||||
|
||||
if (location.hash && $(location.hash.slice(1))?.tagName === "DETAILS") $(location.hash.slice(1)).open = true;
|
||||
loadDevices();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,82 +0,0 @@
|
||||
/* Shared by the dashboard and setup pages. */
|
||||
:root {
|
||||
--bg:#f6f6f4; --card:#ffffff; --fg:#1b1b1b; --muted:#6b6b6b; --line:#e4e4e0;
|
||||
--accent:#3d6fc4; --accent-soft:#e8eefa; --ok:#2e8b57; --bad:#c0392b; --code:#f2f2ef;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg:#121212; --card:#1b1b1b; --fg:#e8e8e8; --muted:#9a9a9a; --line:#2c2c2c;
|
||||
--accent:#7aa2ea; --accent-soft:#1e2a40; --ok:#5cc28a; --bad:#e2685a; --code:#232323;
|
||||
}
|
||||
}
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; background:var(--bg); color:var(--fg); font:15px/1.5 system-ui, sans-serif; }
|
||||
main { max-width:800px; margin:0 auto; padding:0 16px 56px; }
|
||||
a { color:var(--accent); }
|
||||
|
||||
/* ---- top bar ---- */
|
||||
.topbar { display:flex; align-items:center; gap:20px; padding:16px 0; margin-bottom:8px; border-bottom:1px solid var(--line); }
|
||||
.brand { font-weight:650; font-size:17px; }
|
||||
.tabs { display:flex; gap:4px; }
|
||||
.tabs a { color:var(--muted); text-decoration:none; padding:5px 10px; border-radius:6px; }
|
||||
.tabs a:hover { color:var(--fg); }
|
||||
.tabs a[aria-current="page"] { color:var(--fg); background:var(--accent-soft); }
|
||||
|
||||
/* ---- controls ---- */
|
||||
input, select, button { font:inherit; color:inherit; background:var(--card); border:1px solid var(--line); border-radius:6px; padding:5px 10px; }
|
||||
button { cursor:pointer; }
|
||||
button:hover { border-color:var(--muted); }
|
||||
button.primary { background:var(--accent); border-color:var(--accent); color:#fff; }
|
||||
button.primary:hover { filter:brightness(1.08); }
|
||||
button.small { padding:2px 8px; font-size:13px; }
|
||||
button:disabled { opacity:.6; cursor:default; }
|
||||
:focus-visible { outline:2px solid var(--accent); outline-offset:1px; }
|
||||
|
||||
/* ---- layout pieces ---- */
|
||||
.row { display:flex; flex-wrap:wrap; gap:8px; align-items:center; }
|
||||
.spread { justify-content:space-between; }
|
||||
.card { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:16px; margin-top:16px; }
|
||||
.card > h2:first-child, .card > .row:first-child h2 { margin-top:0; }
|
||||
h1 { font-size:20px; margin:16px 0 0; }
|
||||
h2 { font-size:15px; margin:0 0 10px; }
|
||||
h3 { font-size:14px; margin:16px 0 6px; }
|
||||
.muted { color:var(--muted); }
|
||||
.small-text { font-size:13px; }
|
||||
.ok { color:var(--ok); } .bad, .err { color:var(--bad); }
|
||||
.badge { display:inline-block; font-size:12px; padding:1px 7px; border-radius:999px; background:var(--accent-soft); color:var(--accent); white-space:nowrap; }
|
||||
|
||||
.tiles { display:grid; grid-template-columns:repeat(auto-fit, minmax(160px, 1fr)); gap:12px; margin-top:16px; }
|
||||
.tile { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:12px 14px; }
|
||||
.tile .k { font-size:13px; color:var(--muted); }
|
||||
.tile .v { font-size:22px; font-weight:650; font-variant-numeric:tabular-nums; overflow-wrap:anywhere; }
|
||||
|
||||
/* ---- tables ---- */
|
||||
.tablewrap { overflow-x:auto; }
|
||||
table { width:100%; border-collapse:collapse; }
|
||||
th, td { padding:7px 8px 7px 0; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; }
|
||||
tr:last-child td { border-bottom:0; }
|
||||
th { font-weight:600; font-size:13px; color:var(--muted); }
|
||||
td.num { text-align:right; white-space:nowrap; font-variant-numeric:tabular-nums; padding-left:12px; padding-right:0; }
|
||||
td.label { overflow-wrap:anywhere; width:100%; }
|
||||
td.time { white-space:nowrap; color:var(--muted); font-variant-numeric:tabular-nums; }
|
||||
.bar { height:4px; background:var(--accent); border-radius:2px; margin-top:4px; opacity:.85; }
|
||||
|
||||
/* ---- code ---- */
|
||||
code, pre { font:13px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; background:var(--code); border-radius:6px; }
|
||||
code { padding:1px 5px; overflow-wrap:anywhere; }
|
||||
pre { padding:10px 12px; overflow-x:auto; margin:0; }
|
||||
.codeblock { position:relative; margin:8px 0; }
|
||||
.codeblock .copy { position:absolute; top:6px; right:6px; }
|
||||
ol, ul { padding-left:22px; margin:8px 0; }
|
||||
li { margin:6px 0; }
|
||||
|
||||
/* ---- setup ---- */
|
||||
.keybox { margin-top:12px; padding:12px; border:1px solid var(--ok); border-radius:8px; }
|
||||
.keybox pre { margin:8px 0; }
|
||||
details.collector { background:var(--card); border:1px solid var(--line); border-radius:10px; margin-top:12px; }
|
||||
details.collector > summary { cursor:pointer; padding:14px 16px; list-style:none; display:flex; gap:10px; align-items:baseline; }
|
||||
details.collector > summary::-webkit-details-marker { display:none; }
|
||||
details.collector > summary::before { content:"▸"; color:var(--muted); }
|
||||
details.collector[open] > summary::before { content:"▾"; }
|
||||
details.collector > summary b { font-size:15px; }
|
||||
details.collector > .body { padding:0 16px 16px; }
|
||||
+36
-23
@@ -1,42 +1,55 @@
|
||||
// Package web holds the dashboard pages, which read /api/v1 with the main
|
||||
// site's session cookies, and the browser userscript.
|
||||
// Package web serves the dashboard, a Vue app in /web that reads /api/v1 with
|
||||
// the main site's session cookies, and the browser userscript.
|
||||
package web
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"embed"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
//go:embed index.html
|
||||
Index []byte
|
||||
// LoginRedirect is served instead of a page when the visitor isn't the
|
||||
// dist holds the Vue build in dist/app (`make web`). Only dist/.gitkeep is
|
||||
// committed, so the Go code builds and tests without Node.
|
||||
//go:embed all:dist
|
||||
dist embed.FS
|
||||
// LoginRedirect is served instead of the app when the visitor isn't the
|
||||
// site's admin.
|
||||
//go:embed login.html
|
||||
LoginRedirect []byte
|
||||
//go:embed setup.html
|
||||
Setup []byte
|
||||
//go:embed tracker.user.js
|
||||
userScript []byte
|
||||
//go:embed style.css
|
||||
style []byte
|
||||
)
|
||||
|
||||
// Style serves the stylesheet the pages share. It's public: the login
|
||||
// redirect doesn't use it, but there's nothing private in it either.
|
||||
func Style(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/css; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Write(style)
|
||||
var app, _ = fs.Sub(dist, "dist/app")
|
||||
|
||||
// notBuilt stands in for the app in a binary built without `make web`.
|
||||
var notBuilt = []byte(`<!doctype html><meta charset="utf-8"><title>Activity Tracker</title>
|
||||
<p>The dashboard wasn't built into this binary. Run <code>make web</code> and rebuild.</p>`)
|
||||
|
||||
// App serves the app's index.html, for every route the app handles.
|
||||
func App(w http.ResponseWriter, r *http.Request) {
|
||||
page, err := fs.ReadFile(app, "index.html")
|
||||
if err != nil {
|
||||
page = notBuilt
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Write(page)
|
||||
}
|
||||
|
||||
// Page serves a static HTML page.
|
||||
func Page(page []byte) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Write(page)
|
||||
}
|
||||
// Assets serves the app's scripts and styles. Their names carry a content
|
||||
// hash, so they can be cached forever, and they hold no secrets, so they are
|
||||
// public.
|
||||
func Assets() http.Handler {
|
||||
files := http.FileServerFS(app)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := fs.Stat(app, strings.TrimPrefix(r.URL.Path, "/")); err == nil {
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
}
|
||||
files.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// UserScript serves the browser collector. Opening a *.user.js URL in a
|
||||
|
||||
Reference in New Issue
Block a user