Cardiac_Monitor_API / app /static /dashboard.html
Sanuka0523's picture
Deploy web-dashboard e3fd9173: dashboard sign-up, shared '*' devices
f394214 verified
Raw History Blame Contribute Delete
35.7 kB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cardiac Monitor · Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
/* Design tokens mirror app/cardiac_monitor/lib/config/theme.dart */
:root {
--bg: #F2F4F7; --card: #FFFFFF; --text: #1A1D21; --text2: #6B7280; --text3: #9CA3AF;
--surface: #F8F9FA; --divider: #E5E7EB; --accent: #0D9488; --grid: #EEF0F3;
--shadow: 0 8px 20px rgba(0,0,0,.06); --dim: rgba(255,255,255,.75);
--normal: #22C55E; --low: #84CC16; --moderate: #EAB308; --elevated: #F97316; --high: #EF4444;
--playback: #7C3AED;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0F1419; --card: #1A1F26; --text: #E8ECF0; --text2: #8B949E; --text3: #6B7280;
--surface: #21262D; --divider: #2D333B; --accent: #14B8A6; --grid: #252B33;
--shadow: 0 8px 20px rgba(0,0,0,.3); --dim: rgba(0,0,0,.6);
}
}
* { box-sizing: border-box; }
html, body { margin: 0; background: var(--bg); color: var(--text);
font-family: "Plus Jakarta Sans", system-ui, -apple-system, "Segoe UI", sans-serif; }
.hidden { display: none !important; }
button, input, select { font: inherit; }
/* ── Login ── */
.login { min-height: 100vh; display: grid; place-items: center; padding: 16px; }
.login-card { width: 100%; max-width: 380px; background: var(--card); border-radius: 24px;
box-shadow: var(--shadow); padding: 32px 28px; }
.logo { width: 56px; height: 56px; border-radius: 18px; display: grid; place-items: center;
background: linear-gradient(90deg, #0D9488, #06B6D4); box-shadow: 0 6px 16px rgba(13,148,136,.35); }
.login h1 { font-size: 24px; font-weight: 800; margin: 18px 0 4px; }
.login p { color: var(--text2); font-size: 14px; margin: 0 0 22px; }
.field { display: block; margin-bottom: 14px; }
.field span { display: block; font-size: 12px; font-weight: 600; color: var(--text2); margin-bottom: 6px; }
.field input { width: 100%; padding: 13px 16px; border-radius: 12px; border: 1px solid var(--divider);
background: var(--surface); color: var(--text); outline: none; }
.field input:focus { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
.btn-primary { width: 100%; height: 52px; border: 0; border-radius: 14px; color: #fff; font-weight: 700;
font-size: 16px; cursor: pointer; background: linear-gradient(90deg, #0D9488, #06B6D4);
box-shadow: 0 6px 16px rgba(13,148,136,.35); }
.btn-primary:disabled { opacity: .6; cursor: progress; }
.error { color: var(--high); font-size: 13px; min-height: 18px; margin: 4px 0 10px; }
.tabs { display: flex; gap: 4px; padding: 4px; border-radius: 14px; background: var(--surface); margin-bottom: 20px; }
.tabs button { flex: 1; border: 0; padding: 10px 0; border-radius: 10px; background: none; color: var(--text2);
font-size: 14px; font-weight: 600; cursor: pointer; }
.tabs button[aria-selected="true"] { color: #fff; background: linear-gradient(90deg, #0D9488, #06B6D4); }
/* ── Layout ── */
.wrap { max-width: 1120px; margin: 0 auto; padding: 16px 16px 32px; }
header.top { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 16px; margin: 8px 0 24px; }
.greet { flex: 1 1 260px; min-width: 0; }
.greet h1 { font-size: 28px; font-weight: 800; margin: 0; line-height: 1.2; }
.greet .date { color: var(--text2); font-size: 14px; font-weight: 500; margin-top: 4px; }
.controls { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
.pill { display: inline-flex; align-items: center; gap: 8px; padding: 8px 14px; border-radius: 24px;
background: var(--card); box-shadow: var(--shadow); font-size: 13px; font-weight: 600; color: var(--text2);
white-space: nowrap; }
.pill select { border: 0; background: transparent; color: var(--text); font-weight: 700; outline: none;
max-width: 260px; cursor: pointer; }
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text3); flex: none; }
.dot.live { background: var(--normal); box-shadow: 0 0 0 0 rgba(34,197,94,.6); animation: pulse 1.6s infinite; }
@keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(34,197,94,.55); } 70% { box-shadow: 0 0 0 8px rgba(34,197,94,0); }
100% { box-shadow: 0 0 0 0 rgba(34,197,94,0); } }
.btn-ghost { border: 0; background: var(--card); box-shadow: var(--shadow); color: var(--text2);
border-radius: 24px; padding: 8px 14px; font-weight: 600; font-size: 13px; cursor: pointer; }
.grid { display: grid; gap: 20px; grid-template-columns: repeat(3, minmax(0, 1fr)); }
.span-2 { grid-column: span 2; } .span-3 { grid-column: span 3; }
@media (max-width: 860px) { .grid { grid-template-columns: minmax(0, 1fr); } .span-2, .span-3 { grid-column: auto; } }
.card { background: var(--card); border-radius: 24px; box-shadow: var(--shadow); padding: 22px; min-width: 0; }
.card-head { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 12px; margin-bottom: 18px; }
.card-head h2 { font-size: 16px; font-weight: 700; margin: 0; flex: 1 1 200px; min-width: 0; }
.card-head .sub { display: block; font-size: 12px; font-weight: 500; color: var(--text3); margin-top: 2px; }
.icon-box { width: 34px; height: 34px; border-radius: 12px; display: grid; place-items: center; flex: none; }
.chip { display: inline-flex; align-items: center; gap: 6px; padding: 4px 9px; border-radius: 8px;
font-size: 11px; font-weight: 700; white-space: nowrap; background: var(--surface); color: var(--text2); }
/* ── Heart-rate card (VitalCard) ── */
.vital { border-radius: 24px; padding: 20px; color: #fff; display: flex; flex-direction: column;
background: linear-gradient(135deg, #FF6B6B, #EE5A24); box-shadow: 0 8px 16px rgba(255,107,107,.35); }
.vital .top { display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 600; opacity: .9; }
.vital .top span { flex: 1; }
.vital .status { font-style: normal; background: rgba(255,255,255,.2); border-radius: 8px; padding: 3px 8px; font-size: 10px; font-weight: 700; }
.vital .big { text-align: center; font-size: 52px; font-weight: 800; line-height: 1; margin: 26px 0 6px; }
.vital .unit { text-align: center; font-size: 14px; font-weight: 500; opacity: .75; }
.vital .bar { height: 6px; border-radius: 4px; background: rgba(255,255,255,.2); margin-top: auto; overflow: hidden; }
.vital .bar i { display: block; height: 100%; width: 0; background: #fff; border-radius: 4px; transition: width .6s ease; }
.vital .foot { margin-top: 18px; }
/* ── Risk card (RiskIndicator) ── */
.risk-row { display: flex; align-items: flex-end; gap: 4px; }
.risk-num { font-size: 52px; font-weight: 800; line-height: 1; transition: color .3s; }
.risk-pct { font-size: 22px; font-weight: 600; opacity: .7; padding-bottom: 6px; }
.risk-label { margin-left: auto; padding: 6px 14px; border-radius: 20px; font-size: 13px; font-weight: 700;
text-transform: capitalize; }
.risk-bar { position: relative; height: 10px; border-radius: 6px; margin-top: 18px; overflow: hidden;
background: linear-gradient(90deg, #22C55E, #84CC16, #EAB308, #F97316, #EF4444); }
.risk-bar i { position: absolute; top: 0; right: 0; bottom: 0; background: var(--dim); transition: width .6s ease; }
.scale { display: flex; justify-content: space-between; color: var(--text3); font-size: 10px; font-weight: 500; margin-top: 8px; }
.meta { color: var(--text2); font-size: 12px; margin-top: 14px; display: flex; flex-wrap: wrap; gap: 6px 14px; }
.notice { margin-top: 14px; padding: 10px 12px; border-radius: 12px; font-size: 12.5px; font-weight: 500;
background: rgba(234,179,8,.12); color: var(--text); border: 1px solid rgba(234,179,8,.35); }
/* ── ECG card ── */
.ecg-wrap { position: relative; height: 230px; }
canvas { display: block; width: 100%; height: 100%; }
.overlay { position: absolute; inset: 0; display: grid; place-items: center; text-align: center;
color: var(--text2); font-size: 14px; font-weight: 600; pointer-events: none; }
.overlay small { display: block; color: var(--text3); font-weight: 500; font-size: 12px; margin-top: 4px; }
.live-badge { background: rgba(34,197,94,.12); color: var(--normal); }
.playback-badge { background: rgba(124,58,237,.12); color: var(--playback); }
.source { color: var(--playback); font-size: 12.5px; font-weight: 600; margin: -8px 0 12px; }
/* ── Trend + status ── */
.trend-wrap { height: 150px; }
.status-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 12px; }
.stat { display: flex; align-items: center; gap: 10px; min-width: 0; }
.stat .icon-box { width: 38px; height: 38px; border-radius: 14px; background: var(--surface); color: var(--text3); }
.stat.ok .icon-box { background: rgba(34,197,94,.1); color: var(--normal); }
.stat.warn .icon-box { background: rgba(234,179,8,.14); color: var(--moderate); }
.stat > div { min-width: 0; }
.stat b { display: block; font-size: 12px; font-weight: 700; }
.stat span { display: block; font-size: 11.5px; color: var(--text2); overflow-wrap: anywhere; }
footer { color: var(--text3); font-size: 12px; text-align: center; margin-top: 28px; line-height: 1.5; }
</style>
</head>
<body>
<!-- ─────────────── Login ─────────────── -->
<section id="login" class="login hidden">
<form id="login-form" class="login-card" autocomplete="on">
<div class="logo" aria-hidden="true">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12h4l2-5 4 10 2-5h6"/></svg>
</div>
<h1>Cardiac Monitor</h1>
<p>Real-time heart health monitoring</p>
<div class="tabs" role="tablist">
<button id="tab-login" type="button" role="tab" aria-selected="true">Login</button>
<button id="tab-register" type="button" role="tab" aria-selected="false">Register</button>
</div>
<label id="name-field" class="field hidden"><span>Full name</span><input id="name" type="text" maxlength="100" autocomplete="name"></label>
<label class="field"><span>Email</span><input id="email" type="email" required minlength="5" maxlength="100" autocomplete="username"></label>
<label class="field"><span>Password</span><input id="password" type="password" required minlength="6" maxlength="100" autocomplete="current-password"></label>
<div id="login-error" class="error" role="alert"></div>
<button id="login-btn" class="btn-primary" type="submit">Sign In</button>
</form>
</section>
<!-- ─────────────── Dashboard ─────────────── -->
<main id="app" class="wrap hidden">
<header class="top">
<div class="greet">
<h1 id="greeting">Hello</h1>
<div class="date" id="today"></div>
</div>
<div class="controls">
<label class="pill" title="Device"><span>Device</span><select id="device"></select></label>
<span class="pill" id="link" aria-live="polite"><span class="dot" id="link-dot"></span><span id="link-text">Connecting…</span></span>
<button class="btn-ghost" id="logout" type="button">Log out</button>
</div>
</header>
<div class="grid">
<!-- Heart rate -->
<div class="vital">
<div class="top">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1-1.1a5.5 5.5 0 1 0-7.8 7.8L12 21l8.8-8.6a5.5 5.5 0 0 0 0-7.8z"/><path d="M3.5 12h4l1.5-3 3 6 1.5-3h7"/></svg>
<span>Heart Rate</span><em class="status" id="hr-status"></em>
</div>
<div class="big" id="hr">--</div>
<div class="unit" id="hr-unit">bpm</div>
<div class="foot"><div class="bar"><i id="hr-bar"></i></div></div>
</div>
<!-- Risk assessment -->
<div class="card span-2">
<div class="card-head">
<div class="icon-box" id="risk-icon">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></svg>
</div>
<h2>Risk Assessment<span class="sub">ECGFounder + XGBoost ensemble · abnormal-ECG screening</span></h2>
</div>
<div class="risk-row">
<span class="risk-num" id="risk-num">--</span><span class="risk-pct" id="risk-pct"></span>
<span class="risk-label" id="risk-label">N/A</span>
</div>
<div class="risk-bar"><i id="risk-dim" style="width:100%"></i></div>
<div class="scale"><span>Low</span><span>High</span></div>
<div class="meta" id="risk-meta"></div>
<div class="notice hidden" id="risk-notice"></div>
</div>
<!-- ECG -->
<div class="card span-3">
<div class="card-head">
<div class="icon-box" style="background:rgba(13,148,136,.12);color:#0D9488">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12h4l2-6 4 12 2-6h8"/></svg>
</div>
<h2>ECG Waveform<span class="sub" id="ecg-sub">Latest 10 s window</span></h2>
<span class="chip hidden" id="quality-chip"></span>
<span class="chip" id="ecg-badge"></span>
</div>
<div class="source hidden" id="source"></div>
<div class="ecg-wrap">
<canvas id="ecg"></canvas>
<div class="overlay hidden" id="ecg-overlay"></div>
</div>
</div>
<!-- Risk trend -->
<div class="card span-2">
<div class="card-head">
<div class="icon-box" style="background:rgba(13,148,136,.12);color:#0D9488">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M7 15l4-4 3 3 5-6"/></svg>
</div>
<h2>Risk Trend<span class="sub">Last 30 assessments</span></h2>
</div>
<div class="trend-wrap"><canvas id="trend"></canvas></div>
</div>
<!-- Device status -->
<div class="card">
<div class="card-head"><h2 style="font-size:12px;letter-spacing:.5px;color:var(--text2)">DEVICE STATUS</h2></div>
<div class="status-grid">
<div class="stat" id="st-link"><div class="icon-box"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12.5a10 10 0 0 1 14 0"/><path d="M8.5 16a5 5 0 0 1 7 0"/><path d="M12 19.5h.01"/></svg></div><div><b>Data link</b><span>–</span></div></div>
<div class="stat" id="st-leads"><div class="icon-box"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12h4l2-6 4 12 2-6h8"/></svg></div><div><b>Electrodes</b><span>–</span></div></div>
<div class="stat" id="st-signal"><div class="icon-box"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20V14"/><path d="M10 20V9"/><path d="M16 20V4"/></svg></div><div><b>Signal</b><span>–</span></div></div>
<div class="stat" id="st-model"><div class="icon-box"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="5" width="14" height="14" rx="2"/><path d="M9 1v4M15 1v4M9 19v4M15 19v4M1 9h4M1 15h4M19 9h4M19 15h4"/></svg></div><div><b>Risk model</b><span>–</span></div></div>
</div>
</div>
</div>
<footer>
Prototype screening tool — not a medical device. Devices marked <b>RECORDED</b> replay stored ECGs and are not live.<br>
<span id="updated"></span>
</footer>
</main>
<script>
(() => {
"use strict";
// Same-origin by default; ?api=https://… lets a local copy talk to a deployed API.
const API = (new URLSearchParams(location.search).get("api") || "").replace(/\/$/, "");
const POLL_MS = 5000;
const LIVE_WINDOW_S = 40; // a new window arrives every ~10 s; allow upload latency
const TOKEN_KEY = "cm_dashboard_token";
const DEVICE_KEY = "cm_dashboard_device";
const REQUEST_TIMEOUT_MS = 20000; // a hung request must never freeze the page
const RISK = [[0.2, "normal", "#22C55E"], [0.4, "low", "#84CC16"], [0.6, "moderate", "#EAB308"],
[0.8, "elevated", "#F97316"], [Infinity, "high", "#EF4444"]];
const $ = (id) => document.getElementById(id);
const store = {
get(k) { try { return localStorage.getItem(k); } catch { return null; } },
set(k, v) { try { localStorage.setItem(k, v); } catch { /* private mode */ } },
del(k) { try { localStorage.removeItem(k); } catch { /* private mode */ } },
};
let token = store.get(TOKEN_KEY);
let device = null;
let pollTimer = null;
let refreshSeq = 0; // only the newest refresh may update the screen
let lastEcg = null, lastTrend = [];
// ── helpers ──
const utc = (s) => s ? new Date(/[zZ]|[+-]\d\d:?\d\d$/.test(s) ? s : s + "Z") : null; // API sends naive UTC
const hms = (d) => d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
const ago = (d) => {
const s = Math.max(0, (Date.now() - d.getTime()) / 1000);
if (s < 60) return `${Math.round(s)} s ago`;
if (s < 3600) return `${Math.round(s / 60)} min ago`;
if (s < 86400) return `${Math.round(s / 3600)} h ago`;
return `${Math.round(s / 86400)} d ago`;
};
const riskColor = (score) => RISK.find(([max]) => score < max)[2];
const isPlayback = (id) => id.startsWith("PLAYBACK_");
const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
async function timedFetch(url, opts = {}) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), REQUEST_TIMEOUT_MS);
try { return await fetch(url, Object.assign({}, opts, { signal: ctrl.signal })); }
catch (err) { throw new Error(err.name === "AbortError" ? "The server took too long to respond." : "Cannot reach the server."); }
finally { clearTimeout(timer); }
}
async function api(path, opts = {}) {
const headers = Object.assign({ "Content-Type": "application/json" }, opts.headers || {});
if (token) headers.Authorization = `Bearer ${token}`;
const res = await timedFetch(API + path, Object.assign({}, opts, { headers }));
if (res.status === 401 && token) { logout("Your session expired. Please sign in again."); throw new Error("unauthorized"); }
return res;
}
// ── auth ──
function showLogin(message = "") {
stopPolling();
$("app").classList.add("hidden");
$("login").classList.remove("hidden");
$("login-error").textContent = message;
}
function logout(message = "") {
token = null; store.del(TOKEN_KEY);
showLogin(message);
}
// Login / Register toggle, as in the app's login screen
let registering = false;
function setMode(register) {
registering = register;
$("tab-login").setAttribute("aria-selected", String(!register));
$("tab-register").setAttribute("aria-selected", String(register));
$("name-field").classList.toggle("hidden", !register);
$("name").required = register;
$("password").autocomplete = register ? "new-password" : "current-password";
$("login-btn").textContent = register ? "Create Account" : "Sign In";
$("login-error").textContent = "";
}
$("tab-login").addEventListener("click", () => setMode(false));
$("tab-register").addEventListener("click", () => setMode(true));
$("login-form").addEventListener("submit", async (e) => {
e.preventDefault();
const btn = $("login-btn");
btn.disabled = true; $("login-error").textContent = "";
try {
const creds = { email: $("email").value.trim(), password: $("password").value };
if (registering) creds.name = $("name").value.trim();
if (registering && !creds.name) throw new Error("Name required");
const res = await timedFetch(API + (registering ? "/api/v1/auth/register" : "/api/v1/auth/login"), {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify(creds),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
if (typeof body.detail === "string") throw new Error(body.detail);
throw new Error(registering ? "Please check your name, email and password." : "Sign-in failed");
}
token = body.access_token; store.set(TOKEN_KEY, token);
$("password").value = ""; $("name").value = "";
setMode(false);
await start();
} catch (err) {
$("login-error").textContent = err.message;
} finally { btn.disabled = false; }
});
$("logout").addEventListener("click", () => logout());
// ── startup ──
async function start() {
const res = await api("/api/v1/auth/me");
if (!res.ok) { logout(); return; }
const me = await res.json();
$("greeting").textContent = `Hello, ${(me.name || "there").split(" ")[0]}`;
$("today").textContent = new Date().toLocaleDateString([], { weekday: "long", month: "long", day: "numeric" });
const sel = $("device");
sel.textContent = "";
const ids = me.device_ids || [];
if (!ids.length) {
sel.append(new Option("No devices", ""));
}
for (const id of ids) sel.append(new Option(isPlayback(id) ? `${id} (recorded)` : id, id));
const saved = store.get(DEVICE_KEY);
device = ids.includes(saved) ? saved : await pickDefaultDevice(ids);
if (device) sel.value = device;
$("login").classList.add("hidden");
$("app").classList.remove("hidden");
startPolling();
}
// Prefer the live device that uploaded most recently: an account can also list unused IDs
// (e.g. a name typed into the app's "Device ID" field) that would open on an empty screen.
async function pickDefaultDevice(ids) {
const live = ids.filter((id) => !isPlayback(id));
const latest = await Promise.all(live.map(async (id) => {
try {
const r = await api(`/api/v1/vitals/${encodeURIComponent(id)}/latest`);
return [id, r.ok ? utc((await r.json()).created_at).getTime() : -1];
} catch { return [id, -1]; }
}));
latest.sort((a, b) => b[1] - a[1]);
return (latest.length && latest[0][1] >= 0 ? latest[0][0] : live[0]) || ids[0] || null;
}
$("device").addEventListener("change", (e) => {
device = e.target.value; store.set(DEVICE_KEY, device);
lastEcg = null; lastTrend = [];
startPolling();
});
function startPolling() { stopPolling(); refresh(); pollTimer = setInterval(refresh, POLL_MS); }
function stopPolling() { if (pollTimer) clearInterval(pollTimer); pollTimer = null; }
document.addEventListener("visibilitychange", () => {
if (!token || $("app").classList.contains("hidden")) return;
document.hidden ? stopPolling() : startPolling();
});
// ── data refresh ──
async function refresh() {
if (!device) { renderEmpty("No device is linked to this account."); return; }
const seq = ++refreshSeq, dev = device;
const stale = () => seq !== refreshSeq || dev !== device; // device switched or a newer refresh started
try {
const enc = encodeURIComponent(dev);
const [vRes, pRes] = await Promise.all([
api(`/api/v1/vitals/${enc}/latest?include_ecg=true`),
api(`/api/v1/predictions/${enc}?limit=30`),
]);
if (stale()) return;
if (vRes.status === 403) { renderEmpty("This account has no access to this device."); return; }
const vitals = vRes.status === 404 ? null : (vRes.ok ? await vRes.json() : undefined);
const preds = pRes.ok ? (await pRes.json()).predictions || [] : [];
if (vitals === undefined) throw new Error(`HTTP ${vRes.status}`);
if (stale()) return;
render(vitals, preds);
$("updated").textContent = `Dashboard updated ${hms(new Date())}`;
} catch (err) {
if (err.message === "unauthorized" || stale()) return;
setLink(false, "Server unreachable");
$("updated").textContent = `Last refresh failed (${err.message}) — retrying…`;
}
}
function setLink(live, text) {
$("link-dot").classList.toggle("live", live);
$("link-text").textContent = text;
}
function setStat(id, state, text) {
const el = $(id);
el.classList.remove("ok", "warn");
if (state) el.classList.add(state);
el.querySelector("span").textContent = text;
}
function renderEmpty(message) {
setLink(false, "No data");
showOverlay(message, "");
lastEcg = null; drawEcg();
renderRisk(null, null, null);
renderHr(null);
lastTrend = []; drawTrend();
}
function render(v, preds) {
if (!v) { renderEmpty("No ECG received from this device yet."); renderTrend(preds); return; }
const created = utc(v.created_at);
const ageS = (Date.now() - created.getTime()) / 1000;
const live = ageS <= LIVE_WINDOW_S && !isPlayback(v.device_id);
const playback = isPlayback(v.device_id) || !!v.source;
// header status
setLink(live, playback ? "Recorded data" : live ? "Live" : `Offline · last data ${ago(created)}`);
// ECG card
const badge = $("ecg-badge");
badge.className = "chip";
if (playback) { badge.classList.add("playback-badge"); badge.textContent = "RECORDED · NOT LIVE"; }
else if (live) { badge.classList.add("live-badge"); badge.innerHTML = '<span class="dot live" style="width:6px;height:6px"></span>LIVE'; }
else { badge.textContent = hms(created); }
$("source").classList.toggle("hidden", !v.source);
$("source").textContent = v.source || "";
const rate = v.sample_rate_hz || 250;
$("ecg-sub").textContent = `${((v.ecg_samples || []).length / rate).toFixed(0)} s window · ${rate} Hz · ${hms(created)}`;
const q = v.signal_quality;
const qc = $("quality-chip");
qc.classList.toggle("hidden", !q);
qc.textContent = q === "good" ? "Signal good" : q === "poor" ? "Signal poor" : q === "lead_off" ? "Leads off" : "";
qc.style.background = q === "good" ? "rgba(34,197,94,.12)" : "rgba(234,179,8,.14)";
qc.style.color = q === "good" ? "var(--normal)" : "var(--moderate)";
lastEcg = { samples: v.ecg_samples || [], rate, leadOff: v.ecg_lead_off };
if (v.ecg_lead_off) showOverlay("Electrodes are off", "No ECG in the latest window — attach all three pads");
else hideOverlay();
drawEcg();
// Heart rate
renderHr(v.heart_rate_bpm > 0 ? v.heart_rate_bpm : null, v.heart_rate_source);
// Risk: the latest window's own prediction, else the most recent stored one (clearly labelled)
const latestPred = preds[0] || null;
renderRisk(v, v.prediction, latestPred);
renderTrend(preds);
// Device status
setStat("st-link", live ? "ok" : null, playback ? "Recorded session" : live ? "Uploading every 10 s" : `Last seen ${ago(created)}`);
setStat("st-leads", v.ecg_lead_off ? "warn" : "ok", v.ecg_lead_off ? "Not attached" : "Attached");
setStat("st-signal", q === "good" ? "ok" : q ? "warn" : null, q === "good" ? "Clean ECG" : q === "poor" ? "Too noisy to score" : q === "lead_off" ? "No signal" : "–");
setStat("st-model", latestPred ? "ok" : null, latestPred ? `${preds.length} recent assessments` : "No assessments yet");
}
function renderHr(hr, source) {
$("hr").textContent = hr ? Math.round(hr) : "--";
$("hr-unit").textContent = hr ? (source === "ecg" ? "bpm · from ECG" : "bpm") : "bpm";
$("hr-status").textContent = !hr ? "" : hr < 60 ? "Low" : hr > 100 ? "High" : "Normal";
$("hr-status").classList.toggle("hidden", !hr);
$("hr-bar").style.width = hr ? `${Math.min(100, Math.max(0, (hr - 40) / 120 * 100))}%` : "0";
}
function renderRisk(v, windowPred, latestPred) {
const p = windowPred || latestPred;
const num = $("risk-num"), label = $("risk-label"), icon = $("risk-icon");
const notice = $("risk-notice");
if (!p) {
num.textContent = "--"; num.style.color = "var(--text3)"; $("risk-pct").textContent = "";
label.textContent = "N/A"; label.style.background = "var(--surface)"; label.style.color = "var(--text2)";
icon.style.background = "var(--surface)"; icon.style.color = "var(--text3)";
$("risk-dim").style.width = "100%";
$("risk-meta").textContent = "";
notice.classList.toggle("hidden", !v);
notice.textContent = v ? "No risk assessment yet — the model only scores clean ECG windows." : "";
return;
}
const score = p.risk_score, color = riskColor(score);
num.textContent = Math.round(score * 100); num.style.color = color; $("risk-pct").textContent = "%";
$("risk-pct").style.color = color;
label.textContent = p.risk_label; label.style.background = color + "1F"; label.style.color = color;
icon.style.background = color + "1F"; icon.style.color = color;
$("risk-dim").style.width = `${(1 - Math.min(1, Math.max(0, score))) * 100}%`;
const when = p.created_at ? hms(utc(p.created_at)) : (v ? hms(utc(v.created_at)) : "");
const meta = $("risk-meta");
meta.textContent = "";
for (const t of [`Confidence ${Math.round((p.confidence || 0) * 100)}%`, `Assessed ${when}`]) {
const s = document.createElement("span"); s.textContent = t; meta.append(s);
}
if (!windowPred && v) {
const why = v.ecg_lead_off ? "electrodes were off" : v.signal_quality === "poor" ? "the signal was too noisy" : "it has not been scored";
notice.textContent = `The latest window was not scored because ${why}. Showing the last assessment from ${when}.`;
notice.classList.remove("hidden");
} else { notice.classList.add("hidden"); notice.textContent = ""; }
}
function renderTrend(preds) {
lastTrend = preds.slice().reverse(); // oldest → newest
drawTrend();
}
// ── canvas drawing ──
function setupCanvas(canvas) {
const dpr = window.devicePixelRatio || 1;
const w = canvas.clientWidth, h = canvas.clientHeight;
if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) {
canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr);
}
const ctx = canvas.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, w, h);
return { ctx, w, h };
}
function showOverlay(title, detail) {
const o = $("ecg-overlay");
o.textContent = "";
const t = document.createElement("div"); t.textContent = title;
const d = document.createElement("small"); d.textContent = detail;
t.append(d); o.append(t); o.classList.remove("hidden");
}
function hideOverlay() { $("ecg-overlay").classList.add("hidden"); }
function drawEcg() {
const { ctx, w, h } = setupCanvas($("ecg"));
const padB = 20, plotH = h - padB;
const data = lastEcg && !lastEcg.leadOff ? lastEcg.samples : [];
const secs = lastEcg ? Math.max(1, Math.round(lastEcg.samples.length / lastEcg.rate)) : 10;
// grid: one vertical line per second (ECG paper style), 4 horizontal lines
ctx.strokeStyle = css("--grid"); ctx.lineWidth = 1;
ctx.beginPath();
for (let s = 0; s <= secs; s++) { const x = Math.round((s / secs) * (w - 1)) + 0.5; ctx.moveTo(x, 0); ctx.lineTo(x, plotH); }
for (let i = 0; i <= 4; i++) { const y = Math.round((i / 4) * (plotH - 1)) + 0.5; ctx.moveTo(0, y); ctx.lineTo(w, y); }
ctx.stroke();
ctx.fillStyle = css("--text3"); ctx.font = "500 10px 'Plus Jakarta Sans', sans-serif";
ctx.textBaseline = "bottom";
for (let s = 0; s <= secs; s += 2) {
const x = (s / secs) * (w - 1);
ctx.textAlign = s === 0 ? "left" : s === secs ? "right" : "center";
ctx.fillText(`${s}s`, x, h - 2);
}
if (!data.length) return;
// y range with padding
let lo = Infinity, hi = -Infinity;
for (const v of data) { if (v < lo) lo = v; if (v > hi) hi = v; }
const pad = Math.max(20, (hi - lo) * 0.1); lo -= pad; hi += pad;
const y = (v) => plotH - ((v - lo) / (hi - lo)) * plotH;
// peak-preserving draw: min and max of each pixel column, in time order
const n = data.length, cols = Math.max(1, Math.floor(w));
const accent = css("--accent");
ctx.beginPath();
for (let c = 0; c < cols; c++) {
const a = Math.floor((c / cols) * n), b = Math.max(a + 1, Math.floor(((c + 1) / cols) * n));
let mi = a, ma = a;
for (let i = a; i < b && i < n; i++) { if (data[i] < data[mi]) mi = i; if (data[i] > data[ma]) ma = i; }
const first = Math.min(mi, ma), second = Math.max(mi, ma);
const x = (c / (cols - 1 || 1)) * (w - 1);
if (c === 0) ctx.moveTo(x, y(data[first])); else ctx.lineTo(x, y(data[first]));
if (second !== first) ctx.lineTo(x, y(data[second]));
}
ctx.strokeStyle = accent; ctx.lineWidth = 1.4; ctx.lineJoin = "round"; ctx.stroke();
}
function drawTrend() {
const { ctx, w, h } = setupCanvas($("trend"));
const padL = 40, padB = 18, padT = 6, plotW = w - padL - 6, plotH = h - padB - padT;
// risk bands
let prev = 0;
for (const [max, , color] of RISK) {
const top = Math.min(1, max);
ctx.fillStyle = color + "14";
ctx.fillRect(padL, padT + plotH * (1 - top), plotW, plotH * (top - prev));
prev = top;
}
ctx.fillStyle = css("--text3"); ctx.font = "500 10px 'Plus Jakarta Sans', sans-serif";
ctx.textAlign = "right"; ctx.textBaseline = "middle";
for (const v of [0, 0.5, 1]) ctx.fillText(`${v * 100}%`, padL - 6, padT + plotH * (1 - v));
if (!lastTrend.length) {
ctx.textAlign = "center"; ctx.fillText("No assessments yet", padL + plotW / 2, padT + plotH / 2);
return;
}
const pts = lastTrend.map((p, i) => [
padL + (lastTrend.length === 1 ? plotW / 2 : (i / (lastTrend.length - 1)) * plotW),
padT + plotH * (1 - p.risk_score), p.risk_score]);
ctx.beginPath();
pts.forEach(([x, yy], i) => (i ? ctx.lineTo(x, yy) : ctx.moveTo(x, yy)));
ctx.strokeStyle = css("--accent"); ctx.lineWidth = 1.5; ctx.stroke();
for (const [x, yy, s] of pts) {
ctx.beginPath(); ctx.arc(x, yy, 3.2, 0, Math.PI * 2);
ctx.fillStyle = riskColor(s); ctx.fill();
}
ctx.textBaseline = "bottom"; ctx.fillStyle = css("--text3");
ctx.textAlign = "left"; ctx.fillText(hms(utc(lastTrend[0].created_at)), padL, h);
ctx.textAlign = "right"; ctx.fillText(hms(utc(lastTrend[lastTrend.length - 1].created_at)), padL + plotW, h);
}
let resizeT;
window.addEventListener("resize", () => { clearTimeout(resizeT); resizeT = setTimeout(() => { drawEcg(); drawTrend(); }, 100); });
window.matchMedia("(prefers-color-scheme: dark)").addEventListener?.("change", () => { drawEcg(); drawTrend(); });
// ── go ──
// A 401 inside start() has already logged out with a message; only fall back for other errors
if (token) start().catch(() => { if (token) showLogin("Cannot reach the server. Please try again."); });
else showLogin();
})();
</script>
</body>
</html>