Expand tracker analytics and dashboard UX
Test and publish / publish (push) Successful in 4m27s
Test and publish / test (push) Successful in 9m45s

This commit is contained in:
2026-10-23 20:16:50 +01:00
parent e0f8399ff7
commit 667091efb0
17 changed files with 1140 additions and 81 deletions
+3 -2
View File
@@ -1,12 +1,13 @@
<template>
<main>
<a class="skip-link" href="#main-content">Skip to content</a>
<nav class="topbar">
<span class="brand">Activity Tracker</span>
<div class="tabs">
<div class="tabs" aria-label="Primary navigation">
<RouterLink to="/">Dashboard</RouterLink>
<RouterLink to="/setup">Setup</RouterLink>
</div>
</nav>
<RouterView />
<div id="main-content" tabindex="-1"><RouterView /></div>
</main>
</template>
+18 -1
View File
@@ -1,9 +1,10 @@
// Calls /api/v1 with the main site's session cookies, which the browser sends.
export async function api<T>(method: string, path: string, body?: unknown): Promise<T> {
export async function api<T>(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<T> {
const r = await fetch("api/v1/" + path, {
method,
headers: body ? { "Content-Type": "application/json" } : {},
body: body ? JSON.stringify(body) : undefined,
signal,
});
const out = await r.json().catch(() => ({}));
// The server serves the login redirect instead of the app, so a reload signs in again.
@@ -22,6 +23,7 @@ export interface Summary {
totals: Total[]; by_kind: Record<string, number>; goals: Goal[];
}
export interface Activity {
id: number; device: string; source: string;
kind: string; label: string;
started_at: string; ended_at: string; duration_s: number;
attrs?: Record<string, unknown>;
@@ -31,6 +33,21 @@ export interface Device {
last_seen_at?: string | null; revoked_at?: string | null;
}
export interface AdminGoal {
id: number; kind: string; label: string; op: string;
target_s: number; period?: string;
}
export interface Report {
id: number; period_start: string; period_end: string;
model: string; prompt_hash: string; body: string; created_at: string;
}
export interface NotificationSettings {
ntfy_server: string; ntfy_topic: string; enabled: boolean;
retention_days: number; updated_at?: string;
}
export function dur(s: number): string {
s = Math.round(s);
const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60);
+6 -1
View File
@@ -5,11 +5,16 @@ import { copy } from "../copy";
// A command block with a Copy button, which copies the text as rendered.
const pre = ref<HTMLPreElement>();
const label = ref("Copy");
const feedback = ref("");
function copyCode() {
copy(pre.value?.innerText || "", s => { label.value = s; feedback.value = s === "Copied" ? "Code copied to clipboard." : "Could not copy code."; });
}
</script>
<template>
<div class="codeblock">
<pre ref="pre"><slot /></pre>
<button class="small copy" type="button" @click="copy(pre!.innerText, s => label = s)">{{ label }}</button>
<button class="small copy" type="button" @click="copyCode">{{ label }}</button>
<span class="sr-only" role="status" aria-live="polite">{{ feedback }}</span>
</div>
</template>
+15 -5
View File
@@ -1,11 +1,12 @@
<script setup lang="ts">
import { computed } from "vue";
import { computed, ref } from "vue";
import { IDLE, dur, kindName, seriesKey, slotColor, type Activity } from "../api";
import { useTip } from "../tip";
import Tooltip from "./Tooltip.vue";
const props = defineProps<{ activities: Activity[]; from: string; to: string; slots: Map<string, number> }>();
const { tip, show, hide } = useTip();
const selected = ref<Activity | null>(null);
// Lanes in a fixed order so they don't jump between days; unknown kinds go last.
const ORDER = ["place", "app_focus", "tab_focus", "at_desk", "in_bed", "away", "idle", "locked"];
@@ -59,24 +60,28 @@ const legend = computed(() => {
return items;
});
function enter(e: MouseEvent, s: { a: Activity; color: string }) {
function enter(e: MouseEvent | FocusEvent, s: { a: Activity; color: string }) {
show(e, [
{ text: dur(s.a.duration_s) },
{ text: `${s.a.label || kindName(s.a.kind)} · ${kindName(s.a.kind)}`, color: s.color },
{ text: `${time(s.a.started_at)}–${time(s.a.ended_at)}` },
]);
}
function select(a: Activity) { selected.value = selected.value === a ? null : a; }
const details = (a: Activity) => `${a.label || kindName(a.kind)}, ${time(a.started_at)} to ${time(a.ended_at)}, ${dur(a.duration_s)}`;
</script>
<template>
<div class="timeline" @mouseleave="hide">
<div class="timeline" role="region" aria-label="Activity timeline" @mouseleave="hide">
<div v-for="l in lanes" :key="l.kind" class="lane">
<div class="lane-name">{{ kindName(l.kind) }}</div>
<div class="track">
<div v-for="t in ticks" :key="t.left" class="grid" :style="{ left: t.left + '%' }"></div>
<div v-for="(s, i) in l.segs" :key="i" class="seg"
<button v-for="s in l.segs" :key="s.a.id" type="button" class="seg"
:aria-label="details(s.a)" :aria-pressed="selected === s.a"
:style="{ left: s.left + '%', width: `max(1px, calc(${s.width}% - 1px))`, background: s.color }"
@mousemove="enter($event, s)" @mouseleave="hide"></div>
@mousemove="enter($event, s)" @mouseleave="hide" @focus="enter($event, s)" @blur="hide"
@click="select(s.a)"></button>
<div v-if="now !== null" class="now" :style="{ left: now + '%' }"></div>
</div>
</div>
@@ -94,6 +99,11 @@ function enter(e: MouseEvent, s: { a: Activity; color: string }) {
<span v-if="it.kind" class="muted small-text">{{ it.kind }}</span>
</span>
</div>
<div v-if="selected" class="timeline-detail" role="status" aria-live="polite">
<strong>{{ selected.label || kindName(selected.kind) }}</strong>
<span class="muted">{{ time(selected.started_at) }}–{{ time(selected.ended_at) }} · {{ dur(selected.duration_s) }}</span>
<div v-if="selected.attrs?.title" class="muted small-text">{{ selected.attrs.title }}</div>
</div>
<Tooltip :tip="tip" />
</div>
</template>
+2 -2
View File
@@ -30,8 +30,8 @@ function enter(e: MouseEvent | FocusEvent, date: string, g?: Goal) {
</script>
<template>
<div class="history" @mouseleave="hide">
<div v-for="r in rows" :key="r.k" class="hrow">
<div class="history" role="table" aria-label="Goal history" @mouseleave="hide">
<div v-for="r in rows" :key="r.k" class="hrow" role="row">
<div class="name">{{ r.name }}</div>
<div class="cells">
<button v-for="c in r.cells" :key="c.date" class="cell"
+7 -2
View File
@@ -6,7 +6,11 @@ import { copy } from "../copy";
// A freshly created key, copied to the clipboard as soon as it's shown.
const props = defineProps<{ device: Device; apiKey: string }>();
const label = ref("Copy");
onMounted(() => copy(props.apiKey, s => label.value = s));
const feedback = ref("");
function copyKey() {
copy(props.apiKey, s => { label.value = s; feedback.value = s === "Copied" ? "API key copied to clipboard." : "Could not copy API key."; });
}
onMounted(copyKey);
</script>
<template>
@@ -14,7 +18,8 @@ onMounted(() => copy(props.apiKey, s => label.value = s));
<div>Key for <b>{{ device.name }}</b> <span class="badge">{{ device.kind }}</span>. Copy it now; it won't be shown again.</div>
<div class="codeblock">
<pre>{{ apiKey }}</pre>
<button class="small copy" type="button" @click="copy(apiKey, s => label = s)">{{ label }}</button>
<button class="small copy" type="button" @click="copyKey">{{ label }}</button>
</div>
<span class="sr-only" role="status" aria-live="polite">{{ feedback }}</span>
</div>
</template>
+4 -3
View File
@@ -44,12 +44,13 @@ function enter(e: MouseEvent | FocusEvent, c: (typeof cols.value)[number]) {
<template>
<div class="trend">
<div class="row spread">
<h2>Last {{ days.length }} days</h2>
<h2>Last {{ days.length }} days <span class="muted chart-subtitle">Daily {{ kindName(kind) }} time</span></h2>
<select v-model="kind" aria-label="Measure">
<option v-for="k in kinds" :key="k" :value="k">{{ kindName(k) }}</option>
</select>
</div>
<div class="plot">
<p v-if="!kinds.length" class="empty-chart" role="status">No activity data is available for this period.</p>
<div v-else class="plot" role="region" :aria-label="`Daily ${kindName(kind)} time for the last ${days.length} days`">
<div class="yaxis">
<span v-for="l in scale.lines" :key="l" :style="{ bottom: h(l) }">{{ tick(l) }}</span>
</div>
@@ -63,7 +64,7 @@ function enter(e: MouseEvent | FocusEvent, c: (typeof cols.value)[number]) {
</button>
</div>
</div>
<div class="xaxis">
<div v-if="kinds.length" class="xaxis" aria-hidden="true">
<span v-for="c in cols" :key="c.date" :class="{ sel: c.date === selected }">{{ c.day }}</span>
</div>
<Tooltip :tip="tip" />
+48 -1
View File
@@ -23,6 +23,8 @@ 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); }
.skip-link { position:absolute; left:-999px; top:8px; z-index:20; padding:8px 12px; background:var(--card); border:1px solid var(--accent); border-radius:6px; }
.skip-link:focus { left:8px; }
.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; }
@@ -44,10 +46,13 @@ button:disabled { opacity:.6; cursor:default; }
.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; }
.section-head { margin-bottom:10px; }
.filter { display:flex; align-items:center; gap:6px; color:var(--muted); font-size:13px; }
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); }
.sr-only { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0; }
.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; }
@@ -79,6 +84,32 @@ li { margin:6px 0; }
/* ---- setup ---- */
.keybox { margin-top:12px; padding:12px; border:1px solid var(--ok); border-radius:8px; }
.status-dot { display:inline-block; width:8px; height:8px; margin-right:5px; border-radius:50%; background:var(--muted); }
.status-dot.good { background:var(--ok); }
.status-dot.warn { background:var(--s4); }
.status-dot.bad { background:var(--bad); }
.confirm { margin-top:12px; padding:12px; border:1px solid var(--bad); border-radius:8px; background:var(--bad-soft); }
.danger { color:var(--bad); border-color:var(--bad); }
.button-like { display:inline-block; padding:5px 10px; border:1px solid var(--line); border-radius:6px; color:var(--fg); text-decoration:none; background:var(--card); }
.button-like:hover { border-color:var(--muted); }
.setup-progress { display:grid; gap:7px; margin-bottom:0; }
.setup-progress li { margin:0; }
.setup-progress li.ok b { color:var(--ok); }
.goal-form { display:grid; grid-template-columns:1fr 1fr auto auto; gap:8px; align-items:end; }
.goal-form label { display:grid; gap:3px; font-size:13px; color:var(--muted); }
.settings-form { display:grid; grid-template-columns:1fr 1fr; gap:8px; align-items:end; margin-top:12px; }
.settings-form label, .privacy-tools label { display:grid; gap:3px; font-size:13px; color:var(--muted); }
.settings-form .check { display:flex; align-items:center; gap:6px; }
.settings-form .check input { width:auto; }
.data-actions { margin:10px 0 14px; }
.privacy-tools { border-top:1px solid var(--line); margin-top:16px; padding-top:12px; }
.privacy-tools h3 { margin-top:0; }
.report-list { border-top:1px solid var(--line); margin-top:16px; padding-top:12px; }
.report { border-bottom:1px solid var(--line); padding:8px 0; }
.report:last-child { border-bottom:0; }
.report p { margin:4px 0 0; white-space:pre-wrap; }
@media (max-width:620px) { .goal-form { grid-template-columns:1fr 1fr; } .goal-form button { grid-column:span 2; } }
@media (max-width:620px) { .settings-form { grid-template-columns:1fr; } }
.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; }
@@ -104,8 +135,10 @@ details.collector > .body { padding:0 16px 16px; }
.timeline .track { position:relative; flex:1; height:18px; min-width:0; }
.timeline .axis .track { height:16px; }
.timeline .grid { position:absolute; top:-3px; bottom:-3px; width:1px; background:var(--grid); }
.timeline .seg { position:absolute; top:0; bottom:0; border-radius:3px; }
.timeline .seg { position:absolute; top:0; bottom:0; border:0; border-radius:3px; padding:0; }
.timeline .seg:hover { filter:brightness(1.15); }
.timeline .seg[aria-pressed="true"] { outline:2px solid var(--fg); outline-offset:1px; z-index:1; }
.timeline-detail { margin:12px 0 0 72px; padding:9px 10px; border-left:3px solid var(--accent); background:var(--accent-soft); display:grid; gap:2px; }
.timeline .now { position:absolute; top:-4px; bottom:-4px; width:2px; margin-left:-1px; background:var(--fg); border-radius:1px; }
.timeline .tick { position:absolute; transform:translateX(-50%); font-size:12px; color:var(--muted); font-variant-numeric:tabular-nums; white-space:nowrap; }
.timeline .tick.first { transform:none; }
@@ -132,6 +165,8 @@ details.collector > .body { padding:0 16px 16px; }
.trend .xaxis { display:flex; margin-left:40px; margin-top:4px; }
.trend .xaxis span { flex:1; text-align:center; font-size:12px; color:var(--muted); font-variant-numeric:tabular-nums; }
.trend .xaxis span.sel { color:var(--fg); font-weight:650; }
.chart-subtitle { font-size:13px; font-weight:400; }
.empty-chart { min-height:140px; display:grid; place-items:center; margin:22px 0 0; border:1px dashed var(--line); color:var(--muted); }
.history .hrow { display:grid; grid-template-columns:minmax(0, 1fr) auto 76px; gap:6px 12px; align-items:center;
padding:7px 0; border-bottom:1px solid var(--line); }
@@ -140,9 +175,21 @@ details.collector > .body { padding:0 16px 16px; }
.history .cells { display:flex; gap:2px; }
.history .streak { text-align:right; white-space:nowrap; }
@media (max-width:620px) {
.dashboard-head { align-items:flex-start; }
.dashboard-head > .row { width:100%; justify-content:space-between; }
.dashboard-head input[type="date"] { flex:1; min-width:0; }
.section-head { align-items:flex-start; }
.section-head .filter { width:100%; }
.section-head select { flex:1; }
.history .hrow { grid-template-columns:1fr auto; }
.history .cells { grid-row:2; grid-column:1 / -1; }
}
@media (max-width:420px) {
main { padding-left:10px; padding-right:10px; }
.card { padding:12px; }
.tile .v { font-size:19px; }
th, td { padding-right:5px; }
}
.history .cell { width:22px; height:22px; padding:0; border:0; border-radius:4px; font-size:12px; line-height:22px; text-align:center; flex:none; }
@media (max-width:420px) { .history .cell { width:auto; flex:1; } }
.history .cell.met { background:var(--ok-soft); color:var(--ok); }
+40 -30
View File
@@ -15,6 +15,7 @@ const sum = ref<Summary | null>(null);
const activities = ref<Activity[]>([]);
const loading = ref(false);
const error = ref("");
const activityKind = ref("all");
// Summaries for the trend charts, kept across day changes. The selected day's
// is always refetched since today's is still growing.
const history = reactive<Record<string, Summary>>({});
@@ -25,31 +26,48 @@ const title = computed(() => daysAgo.value === 0 ? "Today" : daysAgo.value === 1
// Ignore a response for a day that's no longer selected.
let seq = 0;
let controller: AbortController | null = null;
async function request<T>(path: string, signal: AbortSignal): Promise<T> {
return api<T>("GET", path, undefined, signal);
}
async function load() {
const n = ++seq;
controller?.abort();
controller = new AbortController();
const signal = controller.signal;
loading.value = true;
error.value = "";
try {
const s = await api<Summary>("GET", "summary/daily?date=" + date.value);
const s = await request<Summary>("summary/daily?date=" + date.value, signal);
const q = new URLSearchParams({ from: s.from, to: s.to, limit: String(LIMIT) });
const { activities: acts } = await api<{ activities: Activity[] }>("GET", "activities?" + q);
const [{ activities: acts }, ...trend] = await Promise.all([
request<{ activities: Activity[] }>("activities?" + q, signal),
...trendDates(date.value).map(d => request<Summary>("summary/daily?date=" + d, signal)
.then(x => [d, x] as const).catch(() => null)),
]);
if (n !== seq) return;
sum.value = s;
activities.value = acts;
history[s.date] = s;
for (const item of trend) if (item) history[item[0]] = item[1];
} catch (e) {
if (n === seq) error.value = (e as Error).message;
if (n === seq && (e as Error).name !== "AbortError") error.value = (e as Error).message;
} finally {
if (n === seq) loading.value = false;
}
}
watch(date, load, { immediate: true });
const addDays = (d: string, n: number) => {
const x = noon(d);
x.setDate(x.getDate() + n);
return x.toLocaleDateString("en-CA");
};
const trendDates = (selected: string) => {
let end = selected;
for (let i = 0; i < TREND_DAYS / 2 && end < today(); i++) end = addDays(end, 1);
return Array.from({ length: TREND_DAYS }, (_, i) => addDays(end, i - TREND_DAYS + 1))
.filter(d => d !== selected && d <= today());
};
const trendDays = computed(() => {
// Runs up to a week past the selected day, but never past today.
let end = date.value;
@@ -57,16 +75,7 @@ const trendDays = computed(() => {
return Array.from({ length: TREND_DAYS }, (_, i) => addDays(end, i - TREND_DAYS + 1))
.map(d => ({ date: d, sum: history[d] ?? null }));
});
const pending = new Set<string>();
watch(() => trendDays.value.map(d => d.date), days => {
for (const d of days) {
if (d in history || d === date.value || pending.has(d)) continue;
pending.add(d);
api<Summary>("GET", "summary/daily?date=" + d)
.then(s => { history[d] = s; }, () => {})
.finally(() => pending.delete(d));
}
}, { immediate: true });
watch(date, load, { immediate: true });
const shift = (days: number) => { date.value = addDays(date.value, days); };
const slots = computed(() => seriesSlots(sum.value?.totals ?? []));
@@ -81,7 +90,9 @@ const goalsMet = computed(() => {
const kinds = computed(() => Object.entries(sum.value?.by_kind ?? {}).sort((a, b) => b[1] - a[1]));
const labels = computed(() => [...sum.value?.totals ?? []].sort((a, b) => b.seconds - a.seconds).slice(0, 15));
const timeline = computed(() => activities.value.filter(a => a.duration_s >= 60)
.filter(a => activityKind.value === "all" || a.kind === activityKind.value)
.sort((a, b) => +new Date(b.started_at) - +new Date(a.started_at)));
const activityKinds = computed(() => [...new Set(activities.value.map(a => a.kind))].sort());
const time = (t: string) => new Date(t).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const pct = (v: number, max: number) => `${v / (max || 1) * 100}%`;
@@ -93,7 +104,7 @@ const meter = (g: Summary["goals"][number]) => {
</script>
<template>
<div class="row spread">
<div class="row spread dashboard-head">
<h1>{{ title }}</h1>
<div class="row">
<button aria-label="Previous day" @click="shift(-1)">‹</button>
@@ -103,8 +114,8 @@ const meter = (g: Summary["goals"][number]) => {
</div>
</div>
<p class="muted">
<span v-if="error" class="err">{{ error }}</span>
<p class="muted status" role="status" aria-live="polite" aria-atomic="true">
<span v-if="error" class="err" role="alert">{{ error }}</span>
<template v-else-if="loading">Loading…</template>
<template v-else-if="activities.length >= LIMIT">Timeline shows the first {{ LIMIT }} activities.</template>
</p>
@@ -117,8 +128,8 @@ const meter = (g: Summary["goals"][number]) => {
<div class="tile"><div class="k">Goals met</div><div class="v">{{ goalsMet }}</div></div>
</div>
<section class="card"><h2>Goals</h2><div class="tablewrap"><table>
<tr v-for="(g, i) in sum.goals" :key="i">
<section class="card"><h2>Goals</h2><div class="tablewrap"><table>
<caption class="sr-only">Goals for {{ title }}</caption><thead><tr><th scope="col">Goal</th><th scope="col">Actual</th><th scope="col">Status</th></tr></thead><tbody><tr v-for="(g, i) in sum.goals" :key="i">
<td class="label">{{ kindName(g.kind) }}{{ g.label ? " · " + g.label : "" }}
<span class="muted">{{ g.op }} {{ dur(g.target_s) }}</span>
<div class="meter" :class="g.met ? 'ok' : 'bad'">
@@ -127,8 +138,7 @@ const meter = (g: Summary["goals"][number]) => {
</div></td>
<td class="num">{{ dur(g.actual_s) }}</td>
<td class="num" :class="g.met ? 'ok' : 'bad'">{{ g.met ? "✓ met" : "✗ missed" }}</td>
</tr>
<tr v-if="!sum.goals.length"><td class="muted">No goals yet. See <RouterLink to="/setup#goals">Setup</RouterLink>.</td></tr>
</tr><tr v-if="!sum.goals.length"><td colspan="3" class="muted">No goals yet. See <RouterLink to="/setup#goals">Setup</RouterLink>.</td></tr></tbody>
</table></div></section>
<section class="card"><h2>Day at a glance</h2>
@@ -143,31 +153,31 @@ const meter = (g: Summary["goals"][number]) => {
<GoalHistory :days="trendDays" :selected="date" @select="date = $event" />
</section>
<section class="card"><h2>By kind</h2><div class="tablewrap"><table>
<tr v-for="[k, s] in kinds" :key="k">
<section class="card"><h2>By kind</h2><div class="tablewrap"><table><caption class="sr-only">Time by activity kind</caption><thead><tr><th scope="col">Kind</th><th scope="col">Time</th></tr></thead><tbody>
<tr v-for="[k, s] in kinds" :key="k">
<td class="label">{{ kindName(k) }}<div class="bar" :style="{ width: pct(s, kinds[0][1]) }"></div></td>
<td class="num">{{ dur(s) }}</td>
</tr>
<tr v-if="!kinds.length"><td class="muted">Nothing recorded.</td></tr>
<tr v-if="!kinds.length"><td colspan="2" class="muted">Nothing recorded.</td></tr></tbody>
</table></div></section>
<section class="card"><h2>Top labels</h2><div class="tablewrap"><table>
<tr v-for="t in labels" :key="t.kind + '\0' + t.label">
<section class="card"><h2>Top labels</h2><div class="tablewrap"><table><caption class="sr-only">Top labels by time</caption><thead><tr><th scope="col">Label</th><th scope="col">Time</th></tr></thead><tbody>
<tr v-for="t in labels" :key="t.kind + '\0' + t.label">
<td class="label">{{ t.label || "—" }} <span class="badge">{{ kindName(t.kind) }}</span>
<div class="bar" :style="{ width: pct(t.seconds, labels[0].seconds), background: slotColor(slots.get(seriesKey(t.kind, t.label))) }"></div></td>
<td class="num">{{ dur(t.seconds) }}</td>
</tr>
<tr v-if="!labels.length"><td class="muted">Nothing recorded.</td></tr>
<tr v-if="!labels.length"><td colspan="2" class="muted">Nothing recorded.</td></tr></tbody>
</table></div></section>
<section class="card"><h2>Timeline</h2><div class="tablewrap"><table>
<tr v-for="(a, i) in timeline" :key="i">
<section class="card"><div class="row spread section-head"><h2>Activity details</h2><label class="filter">Filter <select v-model="activityKind" aria-label="Filter activity details"><option value="all">All activity</option><option v-for="k in activityKinds" :key="k" :value="k">{{ kindName(k) }}</option></select></label></div><div class="tablewrap"><table><caption class="sr-only">Activities lasting at least one minute</caption><thead><tr><th scope="col">Time</th><th scope="col">Activity</th><th scope="col">Duration</th></tr></thead><tbody>
<tr v-for="a in timeline" :key="a.id">
<td class="time">{{ time(a.started_at) }}–{{ time(a.ended_at) }}</td>
<td class="label">{{ a.label || a.kind }} <span class="badge">{{ kindName(a.kind) }}</span>
<div v-if="a.attrs?.title" class="muted small-text">{{ a.attrs.title }}</div></td>
<td class="num">{{ dur(a.duration_s) }}</td>
</tr>
<tr v-if="!timeline.length"><td class="muted">No activities of a minute or longer.</td></tr>
<tr v-if="!timeline.length"><td colspan="3" class="muted">No matching activities of a minute or longer.</td></tr></tbody>
</table></div></section>
</div>
</template>
+201 -15
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { api, type Device } from "../api";
import { api, type AdminGoal, type Device, type NotificationSettings, type Report } from "../api";
import CodeBlock from "../components/CodeBlock.vue";
import Collector from "../components/Collector.vue";
import KeyBox from "../components/KeyBox.vue";
@@ -14,6 +14,17 @@ const loaded = ref(false);
const status = ref<{ msg: string; cls?: string }>({ msg: "" });
const active = computed(() => devices.value.filter(d => !d.revoked_at));
const revoked = computed(() => devices.value.filter(d => d.revoked_at));
const goals = ref<AdminGoal[]>([]);
const goalLoaded = ref(false);
const goalForm = reactive({ kind: "tab_focus", label: "", op: ">=", target: "30m" });
const editingGoal = ref<number | null>(null);
const goalBusy = ref(false);
const pendingRevoke = ref<Device | null>(null);
const revokeCancel = ref<HTMLButtonElement>();
const reports = ref<Report[]>([]);
const notifications = reactive<NotificationSettings>({ ntfy_server: "https://ntfy.sh", ntfy_topic: "", enabled: false, retention_days: 0 });
const purgeBefore = ref(new Date(Date.now() - 90 * 86400000).toISOString().slice(0, 10));
const privacyBusy = ref(false);
// Which collector sections are open: the browser's by default, and the one a
// #section in the URL names.
@@ -45,6 +56,24 @@ function ago(t?: string | null) {
return new Date(t).toLocaleDateString([], { day: "numeric", month: "short", year: "numeric" });
}
function deviceStatus(d: Device) {
if (d.revoked_at) return { label: "Revoked", cls: "bad" };
if (!d.last_seen_at) return { label: "Never seen", cls: "warn" };
const age = Date.now() - +new Date(d.last_seen_at);
return age < 2 * 86400000 ? { label: "Healthy", cls: "good" } : { label: "Stale", cls: "warn" };
}
function parseDuration(value: string) {
const m = value.trim().match(/^(?:(\d+(?:\.\d+)?)h)?\s*(?:(\d+(?:\.\d+)?)m)?\s*(?:(\d+(?:\.\d+)?)s)?$/i);
if (!m || !m[1] && !m[2] && !m[3]) return 0;
return Math.round((Number(m[1] || 0) * 3600) + (Number(m[2] || 0) * 60) + Number(m[3] || 0));
}
function formatDuration(s: number) {
const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60), sec = s % 60;
return h ? `${h}h${m ? ` ${m}m` : ""}` : m ? `${m}m${sec ? ` ${sec}s` : ""}` : `${sec}s`;
}
async function loadDevices() {
try {
({ devices: devices.value } = await api<{ devices: Device[] }>("GET", "devices"));
@@ -53,7 +82,26 @@ async function loadDevices() {
status.value = { msg: (e as Error).message, cls: "err" };
}
}
onMounted(loadDevices);
async function loadGoals() {
try {
const out = await api<{ goals: AdminGoal[] }>("GET", "goals");
goals.value = out.goals;
goalLoaded.value = true;
} catch (e) {
status.value = { msg: (e as Error).message, cls: "err" };
}
}
async function loadAdminData() {
try {
const [notification, reportList] = await Promise.all([
api<{ settings: NotificationSettings }>("GET", "notifications/status"),
api<{ reports: Report[] }>("GET", "reports"),
]);
Object.assign(notifications, notification.settings);
reports.value = reportList.reports;
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
}
onMounted(() => { loadDevices(); loadGoals(); loadAdminData(); });
// A readable name that isn't taken yet (names stay taken after revoking).
function suggestName(kind: string) {
@@ -93,36 +141,124 @@ async function create() {
}
async function revoke(name: string) {
if (!confirm(`Revoke ${name}? Its collector will stop being able to upload.`)) return;
pendingRevoke.value = devices.value.find(d => d.name === name) || null;
}
watch(pendingRevoke, value => { if (value) nextTick(() => revokeCancel.value?.focus()); });
async function confirmRevoke() {
const device = pendingRevoke.value;
if (!device) return;
try {
await api("DELETE", "devices/" + encodeURIComponent(name));
status.value = { msg: `Revoked ${name}.`, cls: "ok" };
await api("DELETE", "devices/" + encodeURIComponent(device.name));
status.value = { msg: `Revoked ${device.name}.`, cls: "ok" };
pendingRevoke.value = null;
loadDevices();
} catch (e) {
status.value = { msg: (e as Error).message, cls: "err" };
}
}
async function addGoal() {
const target_s = parseDuration(goalForm.target);
if (!goalForm.kind.trim() || target_s <= 0) { status.value = { msg: "Enter a kind and a duration such as 30m or 1h.", cls: "err" }; return; }
goalBusy.value = true;
try {
const body = { kind: goalForm.kind.trim(), label: goalForm.label.trim(), op: goalForm.op, target_s };
if (editingGoal.value === null) {
const out = await api<AdminGoal>("POST", "goals", body);
goals.value.push(out);
status.value = { msg: "Goal added.", cls: "ok" };
} else {
const out = await api<AdminGoal>("PUT", "goals/" + encodeURIComponent(String(editingGoal.value)), body);
goals.value = goals.value.map(g => g.id === editingGoal.value ? out : g);
status.value = { msg: "Goal updated.", cls: "ok" };
}
resetGoalForm();
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
finally { goalBusy.value = false; }
}
function editGoal(goal: AdminGoal) {
editingGoal.value = goal.id;
goalForm.kind = goal.kind;
goalForm.label = goal.label;
goalForm.op = goal.op;
goalForm.target = formatDuration(goal.target_s).replace(" ", "");
}
function resetGoalForm() {
editingGoal.value = null;
goalForm.kind = "tab_focus";
goalForm.label = "";
goalForm.op = ">=";
goalForm.target = "30m";
}
async function removeGoal(goal: AdminGoal) {
try {
await api("DELETE", "goals/" + encodeURIComponent(String(goal.id)));
goals.value = goals.value.filter(g => g.id !== goal.id);
status.value = { msg: "Goal removed.", cls: "ok" };
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
}
async function saveNotifications() {
privacyBusy.value = true;
try {
Object.assign(notifications, await api<NotificationSettings>("PUT", "notifications/config", notifications));
status.value = { msg: "Notification and retention settings saved.", cls: "ok" };
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
finally { privacyBusy.value = false; }
}
async function purgeData() {
if (!purgeBefore.value) return;
privacyBusy.value = true;
try {
const before = new Date(purgeBefore.value + "T00:00:00").toISOString();
const out = await api<{ deleted: number }>("POST", "privacy/purge?before=" + encodeURIComponent(before));
status.value = { msg: `Deleted ${out.deleted} records before ${purgeBefore.value}.`, cls: "ok" };
} catch (e) { status.value = { msg: (e as Error).message, cls: "err" }; }
finally { privacyBusy.value = false; }
}
const setupProgress = computed(() => {
const done = [active.value.length > 0, goals.value.length > 0, active.value.some(d => d.last_seen_at)].filter(Boolean).length;
return { done, total: 3 };
});
</script>
<template>
<h1>Setup</h1>
<p class="muted">Each collector uploads to <code>{{ 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" aria-labelledby="progress-title">
<div class="row spread"><h2 id="progress-title">Getting started</h2><span class="badge">{{ setupProgress.done }}/{{ setupProgress.total }} complete</span></div>
<ol class="setup-progress">
<li :class="{ ok: active.length }"><b>{{ active.length ? "Device created" : "Create a device key" }}</b><span class="muted"> Generate a key below, then follow that collector's instructions.</span></li>
<li :class="{ ok: goals.length }"><b>{{ goals.length ? "Goals configured" : "Add a daily goal" }}</b><span class="muted"> Optional targets are managed here and appear on the dashboard.</span></li>
<li :class="{ ok: active.some(d => d.last_seen_at) }"><b>{{ active.some(d => d.last_seen_at) ? "First upload received" : "Check device health" }}</b><span class="muted"> A healthy device has uploaded in the last two days.</span></li>
</ol>
</section>
<section class="card">
<div class="row spread"><h2>Devices</h2></div>
<div class="tablewrap"><table>
<tr v-if="!loaded"><td class="muted">Loading…</td></tr>
<template v-else>
<tr><th>Name</th><th>Kind</th><th>Last upload</th><th></th></tr>
<caption class="sr-only">Collector devices and upload health</caption>
<thead><tr><th scope="col">Name</th><th scope="col">Kind</th><th scope="col">Health</th><th scope="col">Last upload</th><th scope="col"><span class="sr-only">Actions</span></th></tr></thead>
<tbody v-if="!loaded"><tr><td colspan="5" class="muted">Loading…</td></tr></tbody>
<tbody v-else>
<tr v-for="d in active" :key="d.name">
<td class="label">{{ d.name }}</td>
<td><span class="badge">{{ d.kind }}</span></td>
<td><span class="status-dot" :class="deviceStatus(d).cls"></span>{{ deviceStatus(d).label }}</td>
<td class="time">{{ ago(d.last_seen_at) }}</td>
<td class="num"><button class="small" @click="revoke(d.name)">Revoke</button></td>
</tr>
<tr v-if="!active.length"><td colspan="4" class="muted">No devices yet.</td></tr>
<tr v-if="revoked.length"><td colspan="4" class="muted small-text">{{ revoked.length }} revoked: {{ revoked.map(d => d.name).join(", ") }}</td></tr>
</template>
<tr v-if="!active.length"><td colspan="5" class="muted">No devices yet.</td></tr>
<tr v-if="revoked.length"><td colspan="5" class="muted small-text">{{ revoked.length }} revoked: {{ revoked.map(d => d.name).join(", ") }}</td></tr>
</tbody>
</table></div>
<form class="row" style="margin-top:12px" @submit.prevent="create">
<select v-model="kindSel" aria-label="Kind">
@@ -137,6 +273,11 @@ async function revoke(name: string) {
</form>
<KeyBox v-if="issued?.slot === 'create'" :key="issued.key" :device="issued.device" :api-key="issued.key" />
<p class="small-text" :class="status.cls">{{ status.msg }}</p>
<div v-if="pendingRevoke" class="confirm" role="alertdialog" aria-modal="true" aria-labelledby="revoke-title" aria-describedby="revoke-copy" @keydown.esc="pendingRevoke = null">
<h3 id="revoke-title">Revoke {{ pendingRevoke.name }}?</h3>
<p id="revoke-copy">This stops the collector from uploading. Existing data is not deleted, but the key cannot be used again.</p>
<div class="row"><button ref="revokeCancel" class="small" @click="pendingRevoke = null">Keep device</button><button class="small danger" @click="confirmRevoke">Revoke device</button></div>
</div>
</section>
<Collector id="browser" title="Browser" hint="Violentmonkey userscript · time per site" v-model:open="open.browser">
@@ -144,7 +285,7 @@ async function revoke(name: string) {
<button class="primary" :disabled="busy === 'browser'" @click="generate('browser', '', 'browser')">Generate key for this browser</button>
<KeyBox v-if="issued?.slot === 'browser'" :key="issued.key" :device="issued.device" :api-key="issued.key" />
<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>Install Violentmonkey: <a href="https://addons.mozilla.org/firefox/addon/violentmonkey/" target="_blank" rel="noopener">Firefox <span class="sr-only">(opens in a new tab)</span></a> · <a href="https://chromewebstore.google.com/detail/violentmonkey/jinjaccalgkegednnccohejagnlnfdag" target="_blank" rel="noopener">Chrome / Chromium <span class="sr-only">(opens in a new tab)</span></a></li>
<li>Open <a :href="base + '/tracker.user.js'">{{ base }}/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:
<CodeBlock>{{ base }}</CodeBlock>
@@ -223,10 +364,55 @@ listener {
</Collector>
<Collector id="goals" title="Goals" hint="daily targets on the dashboard" v-model:open="open.goals">
<p>Managed on the server. An empty label matches every label of that kind.</p>
<p>Daily targets are managed here. An empty label matches every label of that kind. Durations accept values such as <code>30m</code>, <code>1h</code>, or <code>1h 30m</code>.</p>
<form class="goal-form" @submit.prevent="addGoal">
<label>Kind<input v-model="goalForm.kind" required placeholder="tab_focus"></label>
<label>Label <span class="muted">(optional)</span><input v-model="goalForm.label" placeholder="youtube.com"></label>
<label>Rule<select v-model="goalForm.op"><option value=">=">At least</option><option value="<=">At most</option></select></label>
<label>Target per day<input v-model="goalForm.target" required placeholder="30m"></label>
<div class="row"><button class="primary" :disabled="goalBusy">{{ goalBusy ? "Saving…" : editingGoal === null ? "Add goal" : "Save goal" }}</button><button v-if="editingGoal !== null" type="button" class="small" @click="resetGoalForm">Cancel</button></div>
</form>
<div class="tablewrap" v-if="goalLoaded || goals.length">
<table>
<caption class="sr-only">Configured daily goals</caption>
<thead><tr><th scope="col">Kind</th><th scope="col">Label</th><th scope="col">Rule</th><th scope="col">Target</th><th scope="col"><span class="sr-only">Actions</span></th></tr></thead>
<tbody><tr v-for="goal in goals" :key="goal.id"><td>{{ goal.kind }}</td><td>{{ goal.label || "Any label" }}</td><td>{{ goal.op === ">=" ? "At least" : "At most" }}</td><td>{{ formatDuration(goal.target_s) }}</td><td class="num"><button class="small" @click="editGoal(goal)">Edit</button> <button class="small" @click="removeGoal(goal)">Remove</button></td></tr><tr v-if="!goals.length"><td colspan="5" class="muted">No goals configured.</td></tr></tbody>
</table>
</div>
<CodeBlock>docker exec activity-tracker tracker goal add --kind tab_focus --label youtube.com --op '&lt;=' --target 1h
docker exec activity-tracker tracker goal add --kind walk --op '&gt;=' --target 30m
docker exec activity-tracker tracker goal list
docker exec activity-tracker tracker goal rm --id 2</CodeBlock>
docker exec activity-tracker tracker goal rm --id 2</CodeBlock>
</Collector>
<section class="card" aria-labelledby="data-title">
<div class="row spread"><h2 id="data-title">Data and notifications</h2><span class="badge">Admin only</span></div>
<p class="muted small-text">Export your activity data, configure optional goal nudges, and control how long records are retained.</p>
<div class="row data-actions">
<a class="button-like" :href="base + '/api/v1/activities/export?format=csv'" download>Export activity CSV</a>
<a class="button-like" :href="base + '/api/v1/activities/export?format=json'" download>Export activity JSON</a>
</div>
<form class="settings-form" @submit.prevent="saveNotifications">
<label>ntfy server<input v-model="notifications.ntfy_server" placeholder="https://ntfy.sh"></label>
<label>Topic<input v-model="notifications.ntfy_topic" placeholder="private-topic"></label>
<label class="check"><input v-model="notifications.enabled" type="checkbox"> Enable goal nudges</label>
<label>Retention days <span class="muted">(0 = keep forever)</span><input v-model.number="notifications.retention_days" type="number" min="0"></label>
<button class="primary" :disabled="privacyBusy">Save settings</button>
</form>
<div class="privacy-tools">
<h3>Delete old records</h3>
<p class="muted small-text">This permanently deletes activities, samples, and reports before the selected date.</p>
<form class="row" @submit.prevent="purgeData">
<label>Delete before <input v-model="purgeBefore" type="date" required></label>
<button class="danger" :disabled="privacyBusy">Delete records</button>
</form>
</div>
<div v-if="reports.length" class="report-list">
<h3>Saved insights</h3>
<article v-for="report in reports.slice(0, 5)" :key="report.id" class="report">
<div class="row spread"><b>{{ report.model }}</b><span class="muted small-text">{{ new Date(report.period_start).toLocaleDateString() }}–{{ new Date(report.period_end).toLocaleDateString() }}</span></div>
<p>{{ report.body }}</p>
</article>
</div>
</section>
</template>