diff --git a/src/app.js b/src/app.js index b01c722..300b567 100644 --- a/src/app.js +++ b/src/app.js @@ -1601,12 +1601,14 @@ // ---------- pattern charts ---------- - // Actogram: one row per day (oldest at top), a midnight-to-midnight track with - // the puppy's sleep shaded. Sleep windows are clipped to each day, so a night - // that crosses midnight shows correctly split across two rows. Today's open - // sleep runs to now (sleepWindows already clips ongoing sleep to Date.now()). - function renderSleepTimeline(events) { - const svg = document.getElementById("chart-sleep-timeline"); + // Actogram: one row per day (oldest at top), a midnight-to-midnight track + // with the given windows shaded. Windows are clipped to each day, so one that + // crosses midnight shows correctly split across two rows, and an open one + // runs to now (both window builders already clip ongoing to Date.now()). + // Sleep and walks are the same picture drawn from different windows, so the + // drawing lives here once and each caller brings its windows and their fill. + function drawActogram(svgId, windows, barCls) { + const svg = document.getElementById(svgId); if (!svg) return; const N = chartDays(); const W = 320; @@ -1621,7 +1623,6 @@ const dayMs = 86_400_000; const today = startOfDay(new Date()); - const windows = sleepWindows(events); const xOf = (frac) => ML + frac * innerW; const parts = []; @@ -1650,7 +1651,7 @@ if (e <= s) continue; const x = xOf((s - dayStart) / dayMs); const wpx = ((e - s) / dayMs) * innerW; - parts.push(``); + parts.push(``); } const label = isToday ? "Today" : `${day.toLocaleDateString(undefined, { weekday: "short" })} ${day.getDate()}`; @@ -1663,6 +1664,207 @@ setChartSVG(svg, parts); // wires the .bar[data-day] click → select that day } + function renderSleepTimeline(events) { + drawActogram("chart-sleep-timeline", sleepWindows(events), "stl-sleep"); + } + + // The walk patterns are only worth a panel once there is a walk to draw, so + // both hide themselves rather than showing an empty day grid to someone who + // doesn't track walks. + function renderWalkPatterns(events) { + const windows = walkWindows(events); + const any = windows.length > 0; + for (const key of ["walk-timeline", "walk-trend"]) { + const section = document.querySelector(`section[data-panel="${key}"]`); + if (section) section.hidden = !any; + } + if (!any) return; + drawActogram("chart-walk-timeline", windows, "wtl-walk"); + renderWalkTrend(events); + } + + // Cumulative minutes walked through the day, as a step per walk: flat while + // the puppy is in, climbing only while a walk is on. Today and yesterday are + // built from their own walk boundaries so the steps stay square; the average + // is sampled hourly instead, since a mean over many days is a smooth + // reference with no steps of its own to preserve. + // + // Unlike the sleep trend there is no projected tail. Sleep is a state the + // puppy drifts back into, so "what the average day adds from here" is a fair + // guess; walks are decisions, and projecting them would be predicting the + // handler, not the dog. + function walkTrendCurves(events) { + const HOUR = 3_600_000, MIN = 60_000, DAY = 86_400_000; + const windows = walkWindows(events); // an ongoing walk is already clipped to now + const walkedMs = (from, to) => { + let total = 0; + for (const w of windows) { + const s = Math.max(w.start, from); + const e = Math.min(w.end, to); + if (e > s) total += e - s; + } + return total; + }; + const day = selectedDay(); + const isToday = ymd(day) === ymd(new Date()); + const dayStartTs = (daysAgo) => { + const d = startOfDay(day); + d.setDate(d.getDate() - daysAgo); + return d.getTime(); + }; + const pointsAt = (start, stops) => + stops.map(t => ({ x: (t - start) / HOUR, y: walkedMs(start, t) / MIN })); + + // Every boundary falling inside the day, plus the day's two ends, is a + // corner of the step line. capTs (today only) ends it at "now". + const curveFor = (start, capTs) => { + const end = capTs != null ? capTs : start + DAY; + const stops = new Set([start, end]); + for (const w of windows) { + if (w.end <= start || w.start >= end) continue; + stops.add(Math.max(w.start, start)); + stops.add(Math.min(w.end, end)); + } + return pointsAt(start, [...stops].sort((a, b) => a - b)); + }; + const hourlyFor = (start) => { + const stops = []; + for (let h = 0; h <= 24; h++) stops.push(start + h * HOUR); + return pointsAt(start, stops); + }; + const totalOf = (pts) => pts[pts.length - 1].y; + + const today = curveFor(dayStartTs(0), isToday ? Date.now() : null); + const prev = curveFor(dayStartTs(1)); + const yesterday = totalOf(prev) > 0 ? prev : null; + + // Mean of the last N days, skipping days with no walk at all so a gap in + // logging doesn't drag the average toward zero. + const avgDays = chartDays(); + const dayCurves = []; + for (let i = 1; i <= avgDays; i++) { + const c = hourlyFor(dayStartTs(i)); + if (c[24].y > 0) dayCurves.push(c); + } + let avg = null; + if (dayCurves.length > 0) { + avg = []; + for (let h = 0; h <= 24; h++) { + avg.push({ x: h, y: dayCurves.reduce((s, c) => s + c[h].y, 0) / dayCurves.length }); + } + } + + const fmtDay = (daysAgo) => + new Date(dayStartTs(daysAgo)).toLocaleDateString(undefined, { month: "short", day: "numeric" }); + return { + today, yesterday, avg, avgDays, + dayLabel: isToday ? "Today" : fmtDay(0), + prevDayLabel: isToday ? "Yesterday" : fmtDay(1), + }; + } + + function drawWalkTrendChart(curves, target) { + const svg = document.getElementById("chart-walk-trend"); + if (!svg) return; + const W = 320, H = 180; + const ML = 30, MR = 8, MT = 10, MB = 22; + const innerW = W - ML - MR; + const innerH = H - MT - MB; + + const series = [ + // Reference lines first so today draws on top of them. + { pts: curves.avg, cls: "wtrend-avg", label: `${curves.avgDays}-day average` }, + { pts: curves.yesterday, cls: "wtrend-yesterday", label: curves.prevDayLabel }, + { pts: curves.today, cls: "wtrend-today", label: curves.dayLabel }, + ].filter(s => s.pts && s.pts.length > 1); + + // The axis has to reach the goal even on a day that fell well short of it, + // or the line it is measured against would sit off the top of the chart. + const rawMax = Math.max( + target ? target.total : 0, + ...series.flatMap(s => s.pts.map(p => p.y)), + ); + const { yMax, steps } = niceAxisLinear(rawMax); + // Minutes are linear all the way down, so no split axis: the sleep trend + // stretches its top because the interesting hours cluster near a 16h goal, + // while a walk total is as readable at 10 minutes as at 60. + const xOf = (hour) => ML + (hour / 24) * innerW; + const yOf = (v) => MT + innerH * (1 - v / yMax); + + const parts = []; + for (let i = 0; i <= steps; i++) { + const v = yMax * i / steps; + const y = yOf(v); + parts.push(``); + parts.push(`${Math.round(v)}m`); + } + for (const hr of [0, 6, 12, 18, 24]) { + const x = xOf(hr); + parts.push(``); + const anchor = hr === 0 ? "start" : hr === 24 ? "end" : "middle"; + parts.push(`${pad2(hr)}`); + } + + // The five-minute rule as one line rather than a band: it is a target to + // reach, with no upper bound a band would imply. + if (target) { + const y = yOf(Math.min(target.total, yMax)); + parts.push( + `` + + `${escapeText(`Goal ~${target.total} min (${target.perWalk} min × ${target.walks})`)}` + ); + } + + for (const s of series) { + const d = s.pts + .map((p, i) => `${i === 0 ? "M" : "L"}${xOf(p.x).toFixed(1)} ${yOf(p.y).toFixed(1)}`) + .join(" "); + const last = s.pts[s.pts.length - 1]; + parts.push( + `` + + `${escapeText(`${s.label} — ${Math.round(last.y)} min walked`)}` + ); + } + + svg.innerHTML = parts.join(""); + } + + function renderWalkTrend(events) { + const curves = walkTrendCurves(events); + const target = walkTargetFor(loadConfig().birthday); + drawWalkTrendChart(curves, target); + + const chip = (id) => document.getElementById(id); + const mins = (pts) => `${Math.round(pts[pts.length - 1].y)} min`; + // With no projection to carry it, the ✓ goes on today's own chip: the goal + // is a total for the day, so today's line is what meets it or doesn't. + let mark = ""; + if (target) { + const done = curves.today[curves.today.length - 1].y >= target.total; + mark = done ? " ✓" : ""; + chip("legend-wtrend-today-text").parentElement.title = done + ? "Past the walking goal for this age" + : `Goal is about ${target.total} min a day at this age`; + } + chip("legend-wtrend-today-text").textContent = `${curves.dayLabel} ${mins(curves.today)}${mark}`; + + const yLegend = chip("legend-wtrend-yesterday"); + yLegend.hidden = !curves.yesterday; + if (curves.yesterday) { + chip("legend-wtrend-yesterday-text").textContent = `${curves.prevDayLabel} ${mins(curves.yesterday)}`; + } + const aLegend = chip("legend-wtrend-avg"); + aLegend.hidden = !curves.avg; + if (curves.avg) { + chip("legend-wtrend-avg-text").textContent = `${curves.avgDays}-day avg ${mins(curves.avg)}`; + } + const gLegend = chip("legend-wtrend-goal"); + gLegend.hidden = !target; + if (target) { + chip("legend-wtrend-goal-text").textContent = `Goal ~${target.total} min`; + } + } + // Which heatmap block is focused, remembered across re-renders so a background // sync doesn't wipe the block the user just tapped. The counts behind it are // recomputed every render, so the readout stays current. @@ -2344,6 +2546,8 @@ // gender; fall back to a neutral phrase when no name is configured. const sleepTitle = document.getElementById("sleep-timeline-title"); if (sleepTitle) sleepTitle.textContent = cfg.name ? `When ${cfg.name} sleeps` : "When sleeping"; + const walkTitle = document.getElementById("walk-timeline-title"); + if (walkTitle) walkTitle.textContent = cfg.name ? `When ${cfg.name} walks` : "When walking"; } // Dim the quick actions that don't fit the current state — a nudge @@ -2396,6 +2600,7 @@ renderWalks(events); renderWeekly(events); renderSleepTimeline(events); + renderWalkPatterns(events); renderSleepTrend(events); renderHourHeatmap(events); renderTraining(events); @@ -4269,6 +4474,7 @@ renderWalks(evs); renderWeekly(evs); renderSleepTimeline(evs); + renderWalkPatterns(evs); renderSleepTrend(evs); renderHourHeatmap(evs); renderTraining(evs); diff --git a/src/changelog.json b/src/changelog.json index 2b01ba3..87ed00a 100644 --- a/src/changelog.json +++ b/src/changelog.json @@ -1,4 +1,5 @@ [ + { "date": "2026-08-31", "text": "Walks now get the same two pattern views sleep has. “When … walks” is a day-per-row grid shaded where a walk was on, so you can see at a glance whether the routine is actually regular or drifts around. “Walk trend” draws the minutes walked so far at each point of the day against yesterday and the average over the picked window, with the age-based goal as a line and a ✓ once the day clears it — the line climbs only while a walk is on, so every step is one walk. Both appear under the Walks panel as soon as you have logged a walk, and stay out of the way until then" }, { "date": "2026-08-31", "text": "The 7d / 14d / 30d buttons now set the window for the Timing panel too. Until now the typical, shortest and longest gaps between pees, poos and meals were always measured over the last 7 days whatever you picked; switch to 30d and they are measured over 30, which settles down the typical gap once there is a month of history to draw on" }, { "date": "2026-08-31", "text": "The charts are grouped by subject instead of all sharing one “Last 7 days” panel. Sleep hours per day is now its own Sleep panel, sitting just above the “When … sleeps” timeline with the rest of the sleep views. Daily counts and Food have joined the by-hour chart in one “Pees, poos & meals” panel, so how many a day, how much food went with them and what hours they fall in read together. Minutes walked per day has moved into the Walks panel. The 7d / 14d / 30d picker now sits in the Sleep panel and still sets the window for every one of these charts" }, { "date": "2026-08-31", "text": "A sleep or walk pair is now tied together in the History log by a dotted rail down the side, in that pair's colour, running from the start row to the end row. Anything logged in between sits inside the bracket, so a pee taken on a walk reads as having happened during it. A pair still in progress, or one that ran over from yesterday, leaves its end of the rail open" }, diff --git a/src/index.html b/src/index.html index 21717de..a8ef363 100644 --- a/src/index.html +++ b/src/index.html @@ -243,6 +243,27 @@ + + + + +