Add training tracking: exercises with instructions, one-tap session log, consistency overview
Exercises (name + how-to note) are a new synced collection with the same LWW/tombstone contract as events, served by POST /api/exercises/sync. Training sessions are ordinary events (type "training") referencing an exercise by id, so they ride the existing event sync unchanged. The Training panel lists each exercise with last-trained / this-week / streak stats, expandable instructions, and a one-tap Log button with the usual undo/add-note snackbar. An exercise-by-day heatmap shows the last 14 days of consistency, and history and the daily overview count training sessions like any other event.
This commit is contained in:
+307
-16
@@ -6,8 +6,9 @@
|
||||
// cached events/profile. currentUser is set by the auth gate before the app
|
||||
// boots, so these are only ever called once a user is known.
|
||||
let currentUser = null;
|
||||
const eventsKey = () => `puppy-tracker:${currentUser.id}:events:v1`;
|
||||
const configKey = () => `puppy-tracker:${currentUser.id}:config:v1`;
|
||||
const eventsKey = () => `puppy-tracker:${currentUser.id}:events:v1`;
|
||||
const configKey = () => `puppy-tracker:${currentUser.id}:config:v1`;
|
||||
const exercisesKey = () => `puppy-tracker:${currentUser.id}:exercises:v1`;
|
||||
const SYNC_URL = "api/events/sync";
|
||||
const SYNC_DEBOUNCE_MS = 1200;
|
||||
const SYNC_POLL_MS = 60_000;
|
||||
@@ -19,6 +20,7 @@
|
||||
"pee": "Pee",
|
||||
"poo": "Poo",
|
||||
"weight": "Weigh-in",
|
||||
"training": "Training",
|
||||
};
|
||||
|
||||
// ---------- photos: IndexedDB store ----------
|
||||
@@ -255,7 +257,7 @@
|
||||
return `${wk} · ${mo} old`;
|
||||
}
|
||||
|
||||
function addEvent(type, note, at, photoId, weight) {
|
||||
function addEvent(type, note, at, photoId, weight, exerciseId) {
|
||||
const events = loadAll();
|
||||
const now = Date.now();
|
||||
const ev = {
|
||||
@@ -265,6 +267,7 @@
|
||||
note: note || "",
|
||||
photoId: photoId || "",
|
||||
weight: Number.isFinite(weight) ? weight : undefined,
|
||||
exerciseId: exerciseId || "",
|
||||
updatedAt: now,
|
||||
};
|
||||
events.push(ev);
|
||||
@@ -293,6 +296,62 @@
|
||||
render();
|
||||
}
|
||||
|
||||
// ---------- exercises (training definitions) ----------
|
||||
// User-defined training exercises ("Sit", "Leash walking", …), each with
|
||||
// optional instruction text. They sync like events: UUID ids, last-write-wins
|
||||
// on updatedAt, tombstoned deletes — but as their own collection, since they
|
||||
// are definitions rather than things that happened at a point in time.
|
||||
function loadExercises() {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(exercisesKey()));
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function saveExercises(list) {
|
||||
localStorage.setItem(exercisesKey(), JSON.stringify(list));
|
||||
}
|
||||
|
||||
function liveExercises() {
|
||||
return loadExercises()
|
||||
.filter(x => !x.deleted)
|
||||
.sort((a, b) => (a.name || "").localeCompare(b.name || ""));
|
||||
}
|
||||
|
||||
function addExercise(name, note) {
|
||||
const list = loadExercises();
|
||||
list.push({ id: uuid(), name, note: note || "", updatedAt: Date.now() });
|
||||
saveExercises(list);
|
||||
scheduleSync();
|
||||
render();
|
||||
}
|
||||
|
||||
function updateExercise(id, patch) {
|
||||
saveExercises(loadExercises().map(x =>
|
||||
x.id === id ? { ...x, ...patch, updatedAt: Date.now() } : x
|
||||
));
|
||||
scheduleSync();
|
||||
render();
|
||||
}
|
||||
|
||||
function deleteExercise(id) {
|
||||
// Tombstone, like events. Logged training sessions keep referencing the id;
|
||||
// name lookups still resolve through the tombstone (see exerciseNames).
|
||||
saveExercises(loadExercises().map(x =>
|
||||
x.id === id ? { ...x, deleted: true, updatedAt: Date.now() } : x
|
||||
));
|
||||
scheduleSync();
|
||||
render();
|
||||
}
|
||||
|
||||
// id -> name across *all* exercises, tombstones included, so history rows for
|
||||
// a deleted exercise still show its name instead of a generic "Training".
|
||||
function exerciseNames() {
|
||||
return new Map(loadExercises().map(x => [x.id, x.name]));
|
||||
}
|
||||
|
||||
// ---------- helpers ----------
|
||||
function ymd(date) {
|
||||
const y = date.getFullYear();
|
||||
@@ -533,6 +592,7 @@
|
||||
document.getElementById("stat-meals").textContent = count("eat");
|
||||
document.getElementById("stat-pees").textContent = count("pee");
|
||||
document.getElementById("stat-poos").textContent = count("poo");
|
||||
document.getElementById("stat-training").textContent = count("training");
|
||||
}
|
||||
|
||||
// Gaps (ms) between consecutive events of `type` logged within the last
|
||||
@@ -691,6 +751,7 @@
|
||||
|
||||
function renderHistory(events) {
|
||||
const dayEvents = eventsForDay(events, selectedDay()).reverse();
|
||||
const exNames = exerciseNames();
|
||||
eventList.innerHTML = "";
|
||||
if (dayEvents.length === 0) {
|
||||
emptyState.hidden = false;
|
||||
@@ -698,6 +759,10 @@
|
||||
}
|
||||
emptyState.hidden = true;
|
||||
for (const ev of dayEvents) {
|
||||
let label = EVENT_LABELS[ev.type] || ev.type;
|
||||
if (ev.type === "training" && exNames.get(ev.exerciseId)) {
|
||||
label = `Training · ${exNames.get(ev.exerciseId)}`;
|
||||
}
|
||||
const li = document.createElement("li");
|
||||
li.className = "event";
|
||||
li.dataset.type = ev.type;
|
||||
@@ -705,7 +770,7 @@
|
||||
li.innerHTML = `
|
||||
<span class="dot"></span>
|
||||
<span class="time">${formatTime(ev.at)}</span>
|
||||
<span class="label">${EVENT_LABELS[ev.type] || ev.type}</span>
|
||||
<span class="label">${escapeText(label)}</span>
|
||||
<span class="note"></span>
|
||||
`;
|
||||
const noteEl = li.querySelector(".note");
|
||||
@@ -1194,6 +1259,170 @@
|
||||
drawWeightChart(weights, birthday);
|
||||
}
|
||||
|
||||
// ---------- training ----------
|
||||
// Per-exercise stats plus a consistency heatmap. Everything here is rolling
|
||||
// (last session / last 7 days / streak / last 14 days) rather than scoped to
|
||||
// the day picker — the point is keeping the habit up, not reviewing one day.
|
||||
const TRAINING_DAYS = 14;
|
||||
const expandedExercises = new Set(); // ids showing their instructions (per page load)
|
||||
|
||||
function trainingStreakDays(times) {
|
||||
// Consecutive days with ≥1 session, counting back from today — or from
|
||||
// yesterday, so a streak isn't shown as broken before today's session
|
||||
// has had a chance to happen.
|
||||
const days = new Set(times.map(t => ymd(new Date(t))));
|
||||
const d = new Date();
|
||||
if (!days.has(ymd(d))) d.setDate(d.getDate() - 1);
|
||||
let streak = 0;
|
||||
while (days.has(ymd(d))) { streak++; d.setDate(d.getDate() - 1); }
|
||||
return streak;
|
||||
}
|
||||
|
||||
function exerciseMeta(times) {
|
||||
if (times.length === 0) return "not yet trained";
|
||||
const weekFrom = startOfDay(new Date());
|
||||
weekFrom.setDate(weekFrom.getDate() - 6);
|
||||
const week = times.filter(t => t >= weekFrom.getTime()).length;
|
||||
const parts = [`last ${formatRelative(Math.max(...times))}`, `${week}× this week`];
|
||||
const streak = trainingStreakDays(times);
|
||||
if (streak >= 2) parts.push(`🔥 ${streak}-day streak`);
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
// Exercise × day grid: one row per exercise, one cell per day, opacity scaled
|
||||
// by that day's session count. Same idea as the hour heatmap, with days for
|
||||
// columns. Cells click through to the day picker via setChartSVG.
|
||||
function renderTrainingHeatmap(exercises, events) {
|
||||
const wrap = document.getElementById("training-chart-wrap");
|
||||
const svg = document.getElementById("chart-training");
|
||||
if (exercises.length === 0) { wrap.hidden = true; return; }
|
||||
wrap.hidden = false;
|
||||
|
||||
const N = TRAINING_DAYS;
|
||||
const from = startOfDay(new Date());
|
||||
from.setDate(from.getDate() - (N - 1));
|
||||
const dayList = [];
|
||||
const dayIndex = new Map(); // ymd -> column
|
||||
for (let i = 0; i < N; i++) {
|
||||
const d = new Date(from);
|
||||
d.setDate(d.getDate() + i);
|
||||
dayList.push(d);
|
||||
dayIndex.set(ymd(d), i);
|
||||
}
|
||||
const exIndex = new Map(exercises.map((x, i) => [x.id, i]));
|
||||
const counts = exercises.map(() => new Array(N).fill(0));
|
||||
for (const e of events) {
|
||||
if (e.type !== "training") continue;
|
||||
const r = exIndex.get(e.exerciseId);
|
||||
const c = dayIndex.get(ymd(new Date(e.at)));
|
||||
if (r !== undefined && c !== undefined) counts[r][c]++;
|
||||
}
|
||||
|
||||
const W = 320;
|
||||
const ML = 70, MR = 8, MT = 6, MB = 18;
|
||||
const rowH = 16, rowGap = 4;
|
||||
const H = MT + exercises.length * (rowH + rowGap) - rowGap + MB;
|
||||
svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
|
||||
const innerW = W - ML - MR;
|
||||
const cellW = innerW / N;
|
||||
|
||||
const parts = [];
|
||||
exercises.forEach((x, r) => {
|
||||
const y = MT + r * (rowH + rowGap);
|
||||
const max = Math.max(1, ...counts[r]);
|
||||
for (let c = 0; c < N; c++) {
|
||||
const n = counts[r][c];
|
||||
const op = n === 0 ? 0.06 : 0.35 + 0.65 * (n / max);
|
||||
const d = dayList[c];
|
||||
const title = `${x.name} · ${d.toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" })}: ${n}`;
|
||||
parts.push(
|
||||
`<rect class="bar hm-cell hm-training" data-day="${ymd(d)}" ` +
|
||||
`x="${(ML + c * cellW).toFixed(1)}" y="${y.toFixed(1)}" ` +
|
||||
`width="${(cellW - 1.5).toFixed(1)}" height="${rowH}" rx="2" fill-opacity="${op.toFixed(2)}">` +
|
||||
`<title>${escapeText(title)}</title></rect>`
|
||||
);
|
||||
}
|
||||
const name = x.name.length > 12 ? x.name.slice(0, 11) + "…" : x.name;
|
||||
parts.push(`<text x="${ML - 6}" y="${(y + rowH / 2 + 3).toFixed(1)}" text-anchor="end">${escapeText(name)}</text>`);
|
||||
});
|
||||
|
||||
const yAxis = H - MB + 12;
|
||||
parts.push(`<text x="${ML}" y="${yAxis}" text-anchor="start">${escapeText(dayList[0].toLocaleDateString(undefined, { month: "short", day: "numeric" }))}</text>`);
|
||||
parts.push(`<text x="${ML + innerW}" y="${yAxis}" text-anchor="end">Today</text>`);
|
||||
|
||||
setChartSVG(svg, parts);
|
||||
}
|
||||
|
||||
function renderTraining(events) {
|
||||
const list = document.getElementById("training-list");
|
||||
const empty = document.getElementById("training-empty");
|
||||
const exercises = liveExercises();
|
||||
list.innerHTML = "";
|
||||
empty.hidden = exercises.length > 0;
|
||||
|
||||
for (const ex of exercises) {
|
||||
const times = events
|
||||
.filter(e => e.type === "training" && e.exerciseId === ex.id)
|
||||
.map(e => e.at);
|
||||
|
||||
const li = document.createElement("li");
|
||||
li.className = "exercise" + (expandedExercises.has(ex.id) ? " expanded" : "");
|
||||
|
||||
const row = document.createElement("div");
|
||||
row.className = "ex-row";
|
||||
const main = document.createElement("div");
|
||||
main.className = "ex-main";
|
||||
const nameEl = document.createElement("span");
|
||||
nameEl.className = "ex-name";
|
||||
nameEl.textContent = ex.name;
|
||||
const metaEl = document.createElement("span");
|
||||
metaEl.className = "ex-meta";
|
||||
metaEl.textContent = exerciseMeta(times);
|
||||
main.appendChild(nameEl);
|
||||
main.appendChild(metaEl);
|
||||
|
||||
const logBtn = document.createElement("button");
|
||||
logBtn.type = "button";
|
||||
logBtn.className = "ex-log";
|
||||
logBtn.textContent = "Log";
|
||||
logBtn.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
const ev = addEvent("training", "", Date.now(), "", undefined, ex.id);
|
||||
showSnackbar(`${ex.name} logged`, ev);
|
||||
});
|
||||
|
||||
row.appendChild(main);
|
||||
row.appendChild(logBtn);
|
||||
row.addEventListener("click", () => {
|
||||
if (expandedExercises.has(ex.id)) expandedExercises.delete(ex.id);
|
||||
else expandedExercises.add(ex.id);
|
||||
li.classList.toggle("expanded");
|
||||
});
|
||||
|
||||
const detail = document.createElement("div");
|
||||
detail.className = "ex-detail";
|
||||
const noteEl = document.createElement("p");
|
||||
noteEl.className = "ex-note";
|
||||
noteEl.textContent = ex.note || "No instructions yet — tap Edit to add how to train this.";
|
||||
const editBtn = document.createElement("button");
|
||||
editBtn.type = "button";
|
||||
editBtn.className = "ghost ex-edit";
|
||||
editBtn.textContent = "Edit";
|
||||
editBtn.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
openExerciseDialog(ex);
|
||||
});
|
||||
detail.appendChild(noteEl);
|
||||
detail.appendChild(editBtn);
|
||||
|
||||
li.appendChild(row);
|
||||
li.appendChild(detail);
|
||||
list.appendChild(li);
|
||||
}
|
||||
|
||||
renderTrainingHeatmap(exercises, events);
|
||||
}
|
||||
|
||||
function renderDayBar() {
|
||||
const day = selectedDay();
|
||||
const isToday = ymd(day) === ymd(new Date());
|
||||
@@ -1235,6 +1464,7 @@
|
||||
renderWeekly(events);
|
||||
renderSleepTimeline(events);
|
||||
renderHourHeatmap(events);
|
||||
renderTraining(events);
|
||||
renderWeight(events);
|
||||
renderHistory(events);
|
||||
}
|
||||
@@ -1281,13 +1511,14 @@
|
||||
syncTimer = setTimeout(sync, SYNC_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
// Merge server response back into local storage. Anything local with a newer
|
||||
// updatedAt than the server's copy wins — that covers events the user added
|
||||
// during the in-flight sync request.
|
||||
function mergeServer(serverEvents) {
|
||||
const localById = new Map(loadAll().map(e => [e.id, e]));
|
||||
// Merge a server response back into local storage. Anything local with a
|
||||
// newer updatedAt than the server's copy wins — that covers items the user
|
||||
// added/edited during the in-flight sync request. Shared by the events and
|
||||
// exercises collections, which follow the same LWW contract.
|
||||
function mergeSynced(serverItems, load, save) {
|
||||
const localById = new Map(load().map(e => [e.id, e]));
|
||||
const merged = new Map();
|
||||
for (const se of serverEvents) {
|
||||
for (const se of serverItems) {
|
||||
if (se && se.id) merged.set(se.id, se);
|
||||
}
|
||||
for (const [id, le] of localById) {
|
||||
@@ -1296,7 +1527,7 @@
|
||||
merged.set(id, le);
|
||||
}
|
||||
}
|
||||
saveAll([...merged.values()]);
|
||||
save([...merged.values()]);
|
||||
}
|
||||
|
||||
async function sync() {
|
||||
@@ -1318,12 +1549,25 @@
|
||||
if (res.status === 401) { handleLoggedOut(); return; }
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const body = await res.json();
|
||||
if (Array.isArray(body.events)) {
|
||||
mergeServer(body.events);
|
||||
lastSynced = Date.now();
|
||||
lastError = null;
|
||||
render();
|
||||
|
||||
const exRes = await fetch("api/exercises/sync", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ exercises: loadExercises() }),
|
||||
});
|
||||
if (exRes.status === 401) { handleLoggedOut(); return; }
|
||||
if (!exRes.ok) throw new Error(`HTTP ${exRes.status}`);
|
||||
const exBody = await exRes.json();
|
||||
|
||||
if (Array.isArray(exBody.exercises)) {
|
||||
mergeSynced(exBody.exercises, loadExercises, saveExercises);
|
||||
}
|
||||
if (Array.isArray(body.events)) {
|
||||
mergeSynced(body.events, loadAll, saveAll);
|
||||
}
|
||||
lastSynced = Date.now();
|
||||
lastError = null;
|
||||
render();
|
||||
setStatus("synced");
|
||||
} catch (err) {
|
||||
lastError = err.message || String(err);
|
||||
@@ -1680,6 +1924,51 @@
|
||||
settingsDialog.close();
|
||||
});
|
||||
|
||||
// ---------- exercise dialog (add / edit a training exercise) ----------
|
||||
const exerciseDialog = document.getElementById("exercise-dialog");
|
||||
const exerciseForm = document.getElementById("exercise-form");
|
||||
const exerciseTitle = document.getElementById("exercise-title");
|
||||
const exerciseName = document.getElementById("exercise-name");
|
||||
const exerciseNote = document.getElementById("exercise-note");
|
||||
const exerciseDelete = document.getElementById("exercise-delete");
|
||||
let editingExerciseId = null;
|
||||
|
||||
function openExerciseDialog(ex) {
|
||||
editingExerciseId = ex ? ex.id : null;
|
||||
exerciseTitle.textContent = ex ? "Edit exercise" : "Add exercise";
|
||||
exerciseName.value = ex ? ex.name : "";
|
||||
exerciseNote.value = ex ? (ex.note || "") : "";
|
||||
exerciseDelete.hidden = !ex;
|
||||
exerciseDialog.showModal();
|
||||
setTimeout(() => exerciseName.focus(), 50);
|
||||
}
|
||||
|
||||
document.getElementById("exercise-add").addEventListener("click", () => openExerciseDialog(null));
|
||||
|
||||
exerciseForm.querySelector('button[value="save"]').addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
const name = exerciseName.value.trim();
|
||||
if (!name) { alert("Give the exercise a name."); return; }
|
||||
const note = exerciseNote.value.trim();
|
||||
if (editingExerciseId) updateExercise(editingExerciseId, { name, note });
|
||||
else addExercise(name, note);
|
||||
editingExerciseId = null;
|
||||
exerciseDialog.close();
|
||||
});
|
||||
exerciseForm.querySelector('button[value="cancel"]').addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
editingExerciseId = null;
|
||||
exerciseDialog.close();
|
||||
});
|
||||
exerciseDelete.addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
if (editingExerciseId && confirm("Delete this exercise? Logged sessions stay in history.")) {
|
||||
deleteExercise(editingExerciseId);
|
||||
}
|
||||
editingExerciseId = null;
|
||||
exerciseDialog.close();
|
||||
});
|
||||
|
||||
// ---------- delete account ----------
|
||||
const deleteAccountDialog = document.getElementById("delete-account-dialog");
|
||||
const deleteAccountPassword = document.getElementById("delete-account-password");
|
||||
@@ -1712,6 +2001,7 @@
|
||||
try {
|
||||
localStorage.removeItem(eventsKey());
|
||||
localStorage.removeItem(configKey());
|
||||
localStorage.removeItem(exercisesKey());
|
||||
} catch { /* ignore */ }
|
||||
clearUser();
|
||||
deleteAccountDialog.close();
|
||||
@@ -1968,6 +2258,7 @@
|
||||
renderWeekly(evs);
|
||||
renderSleepTimeline(evs);
|
||||
renderHourHeatmap(evs);
|
||||
renderTraining(evs);
|
||||
if (navigator.onLine && !syncing) setStatus();
|
||||
}, 60_000);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user