Add a custom from–to date range for the charts

The chart window was fixed to the last 7/14/30 days. A Custom option
picks any range up to a year, which may end in the past. chartRange()
replaces the day count as the source of truth; every day-window chart,
the timing gaps, the hour heatmap and the average-day curves read it,
and headings and trend sentences name the dates.

Long ranges get tighter bar gaps, date axis labels and thinner actogram
rows. weeklyData now builds sleep/walk intervals and per-day buckets
once instead of rescanning the log per day, and chart date labels use
cached Intl formatters, which together cut a year-long render ~3x.
This commit is contained in:
Alexander Heldt committed 2026-10-03 11:16:35 +00:00
1 parent e17856b9fe
commit ffa15ff2e7
4 files changed
+376 -135

No files matched your search

+349 -134
View File
@@ -808,6 +808,13 @@
// consecutive sleep-start → sleep-end pairs across the whole event log, and
// clipped to the day window. Unmatched sleep-start = ongoing sleep (clipped to now).
function sleepMsInRange(events, fromTs, toTs) {
return msInIntervals(sleepIntervals(events), fromTs, toTs);
}
// The [start, end] pairs sleepMsInRange clips. Split out so a caller
// measuring many days (weeklyData, over up to a year) can build them once
// instead of re-sorting the whole log for every day.
function sleepIntervals(events) {
const sorted = [...events].sort((a, b) => a.at - b.at);
const intervals = [];
let openStart = null;
@@ -820,7 +827,10 @@
}
}
if (openStart !== null) intervals.push([openStart, Date.now()]);
return intervals;
}
function msInIntervals(intervals, fromTs, toTs) {
let total = 0;
for (const [start, end] of intervals) {
const s = Math.max(start, fromTs);
@@ -1019,17 +1029,14 @@
document.getElementById("stat-training").textContent = count("training");
}
// Gaps (ms) between consecutive events of `type` logged within the last
// `days` days, sorted ascending. These intervals are what tell you how
// often the puppy needs to go out. Defaults to the picked chart window, so
// the 7d/14d/30d buttons widen the timing panel along with the charts —
// read at call time, not at definition, so a change takes on the next render.
function gapsBetween(events, type, days = chartDays()) {
const cutoff = startOfDay(new Date());
cutoff.setDate(cutoff.getDate() - (days - 1));
const from = cutoff.getTime();
// Gaps (ms) between consecutive events of `type` logged within the picked
// chart window, sorted ascending. These intervals are what tell you how
// often the puppy needs to go out. The window is read at call time, so a
// change on the "Charts cover" row takes on the next render.
function gapsBetween(events, type) {
const { from, to } = chartSpan();
const times = events
.filter(e => e.type === type && e.at >= from)
.filter(e => e.type === type && e.at >= from && e.at < to)
.map(e => e.at)
.sort((a, b) => a - b);
const gaps = [];
@@ -1094,13 +1101,12 @@
note.hidden = false;
// Several logged but none sharing a day (one meal a day, say) is a
// different case from one logged: every gap there was overnight.
const cutoff = startOfDay(new Date());
cutoff.setDate(cutoff.getDate() - (chartDays() - 1));
const inWindow = events.filter(e => e.type === row.type && e.at >= cutoff.getTime()).length;
const span = chartSpan();
const inWindow = events.filter(e => e.type === row.type && e.at >= span.from && e.at < span.to).length;
note.textContent = since == null
? `No ${row.noun}s logged in the last ${chartDays()} days.`
? `No ${row.noun}s logged in ${chartWindowText()}.`
: inWindow >= 2
? `No two ${row.noun}s on the same day in the last ${chartDays()} days — the gap overnight isn't counted, so there is nothing to measure yet.`
? `No two ${row.noun}s on the same day in ${chartWindowText()} — the gap overnight isn't counted, so there is nothing to measure yet.`
: `One ${row.noun} logged, ${formatDuration(since)} ago — log another to see the typical gap.`;
return;
}
@@ -1145,7 +1151,7 @@
const parts = [
`<rect class="tm-track" x="${ML}" y="${trackY}" width="${innerW}" height="${trackH}" rx="${trackH / 2}"/>`,
bandRect(`tm-range ${row.cls}`, xShort, xLong,
`<title>${escapeText(`${formatDuration(shortest)}–${formatDuration(longest)} between ${row.noun}s over the last ${chartDays()} days`)}</title>`),
`<title>${escapeText(`${formatDuration(shortest)}–${formatDuration(longest)} between ${row.noun}s over ${chartWindowText()}`)}</title>`),
bandRect(`tm-band ${row.cls}`, xShort, xTypical,
`<title>${escapeText(`Typically ${formatDuration(typical)} between ${row.noun}s`)}</title>`),
];
@@ -1837,19 +1843,149 @@
});
// ---------- chart window ----------
// How many days the rolling charts cover. Device-global (like the theme),
// picked via the 7d/14d/30d buttons in the charts card and applied to every
// day-window chart: daily bars, sleep timeline, hour heatmap, training grid.
// Which days the cross-day charts cover. Device-global (like the theme),
// picked on the "Charts cover" row and applied to every day-window chart:
// daily bars, sleep timeline, hour heatmap, training grid, timing.
//
// Either a preset — the last 7/14/30 days, always ending today — or a custom
// from–to pair of dates, which may end in the past to look back at history.
// CHART_DAYS_KEY holds the preset number or "custom"; the custom dates live
// under their own key so flipping back to a preset and to Custom again
// brings the same dates back.
const CHART_DAYS_KEY = "puppy-tracker:chart-days:v1";
const CHART_RANGE_KEY = "puppy-tracker:chart-range:v1";
const CHART_DAY_CHOICES = [7, 14, 30];
function chartDays() {
const v = Number(localStorage.getItem(CHART_DAYS_KEY));
return CHART_DAY_CHOICES.includes(v) ? v : 7;
// A year of one-per-day bars and rows is already well past what a phone
// screen can tell apart; longer just costs render time.
const CHART_MAX_DAYS = 366;
const parseYmd = (s) => {
if (typeof s !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(s)) return null;
const [y, m, d] = s.split("-").map(Number);
const date = new Date(y, m - 1, d);
return Number.isNaN(date.getTime()) ? null : date;
};
const addDays = (date, n) => {
const d = new Date(date);
d.setDate(d.getDate() + n);
return d;
};
// Whole calendar days from a to b, by date rather than by 24h, so a DST
// change inside the range can't round a day away.
const daysBetween = (a, b) =>
Math.round((Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()) -
Date.UTC(a.getFullYear(), a.getMonth(), a.getDate())) / 86_400_000);
function storedCustomRange() {
try {
const r = JSON.parse(localStorage.getItem(CHART_RANGE_KEY));
return r && typeof r === "object" ? r : null;
} catch { return null; }
}
// { from, to, days, custom, endsToday } — from and to are the first and last
// day (local midnight), both inclusive. Whatever is stored is clamped into
// something drawable: never past today, never backwards, never over a year.
function chartRange() {
const today = startOfDay(new Date());
let mode = null;
try { mode = localStorage.getItem(CHART_DAYS_KEY); } catch { /* ignore */ }
if (mode === "custom") {
const r = storedCustomRange();
let to = parseYmd(r?.to);
let from = parseYmd(r?.from);
if (from && to) {
if (to > today) to = today;
if (from > to) from = to;
if (daysBetween(from, to) >= CHART_MAX_DAYS) from = addDays(to, -(CHART_MAX_DAYS - 1));
const days = daysBetween(from, to) + 1;
return { from, to, days, custom: true, endsToday: ymd(to) === ymd(today) };
}
}
const n = CHART_DAY_CHOICES.includes(Number(mode)) ? Number(mode) : 7;
return { from: addDays(today, -(n - 1)), to: today, days: n, custom: false, endsToday: true };
}
function chartDays() { return chartRange().days; }
// The days in the window as Dates, oldest first.
function chartDayList() {
const { from, days } = chartRange();
return Array.from({ length: days }, (_, i) => addDays(from, i));
}
// The days the sleep and walk "average day" curves are averaged over, for
// a selected day. A preset keeps its rolling meaning — the N full days
// before the selected one — so picking a day still compares it with the
// week before it. A custom range means "this stretch", so it is the range's
// own days, minus the selected day (it is the line being compared) and
// today (not over yet).
function averageDays(selected) {
const r = chartRange();
if (!r.custom) {
return Array.from({ length: r.days }, (_, i) => addDays(startOfDay(selected), -(i + 1)));
}
const skip = new Set([ymd(selected), ymd(new Date())]);
return chartDayList().filter(d => !skip.has(ymd(d)));
}
// The window as epoch ms, [from, to): to is the end of the last day, or now
// when the window runs up to today.
function chartSpan() {
const r = chartRange();
return {
from: r.from.getTime(),
to: r.endsToday ? Date.now() : endOfDay(r.to).getTime() + 1,
};
}
// toLocaleDateString builds a fresh Intl formatter on every call, which on
// a year-long chart window (a tooltip and a label per day, per chart) was
// most of the render. Same output, one formatter per set of options.
const dateFormatters = new Map();
function fmtDate(date, opts) {
const key = JSON.stringify(opts);
let f = dateFormatters.get(key);
if (!f) dateFormatters.set(key, f = new Intl.DateTimeFormat(undefined, opts));
return f.format(date);
}
function shortDate(date, withYear) {
return fmtDate(date, withYear
? { month: "short", day: "numeric", year: "numeric" }
: { month: "short", day: "numeric" });
}
// "Mar 3 – Jun 30", with years only when the range isn't all this year.
function chartRangeDates() {
const { from, to } = chartRange();
const thisYear = new Date().getFullYear();
const withYear = from.getFullYear() !== thisYear || to.getFullYear() !== thisYear;
return `${shortDate(from, withYear)} – ${shortDate(to, withYear)}`;
}
// The window as a noun phrase for sentences: "the last 30 days", or for a
// custom range "Mar 3 – Jun 30" — which reads after "over" and "in" alike.
function chartWindowText() {
const r = chartRange();
if (r.custom) return r.endsToday ? `the last ${r.days} days (${chartRangeDates()})` : chartRangeDates();
return `the last ${r.days} days`;
}
function setChartDays(n) {
try { localStorage.setItem(CHART_DAYS_KEY, String(n)); } catch { /* ignore */ }
render();
}
function setCustomRange(fromYmd, toYmd) {
try {
localStorage.setItem(CHART_RANGE_KEY, JSON.stringify({ from: fromYmd, to: toYmd }));
localStorage.setItem(CHART_DAYS_KEY, "custom");
} catch { /* ignore */ }
render();
}
// Bar spacing that shrinks with the window so a long one still fits: at a
// few months the bars butt up against each other and read as an area.
const barGapFor = (n) => n <= 14 ? 4 : n <= 31 ? 2 : n <= 90 ? 0.5 : 0;
// Which metrics the daily-counts chart shows. Device-global, toggled via the
// checkboxes under the chart. At least one is always kept on so the chart is
@@ -1872,15 +2008,31 @@
render();
}
// Sync every "(last N days)" header and the picker's active button.
// Sync every "(last N days)" header, the picker's active button and the
// custom date fields.
function renderChartWindow() {
const n = chartDays();
const r = chartRange();
const label = r.custom ? `(${chartRangeDates()})` : `(last ${r.days} days)`;
document.querySelectorAll("[data-chart-days-label]").forEach(el => {
el.textContent = `(last ${n} days)`;
el.textContent = label;
});
document.querySelectorAll(".chart-days-picker button").forEach(b => {
b.classList.toggle("active", Number(b.dataset.days) === n);
document.querySelectorAll(".chart-days-picker button[data-days]").forEach(b => {
b.classList.toggle("active", !r.custom && Number(b.dataset.days) === r.days);
});
document.getElementById("chart-range-custom").classList.toggle("active", r.custom);
const fields = document.getElementById("chart-range-fields");
fields.hidden = !r.custom;
const fromInput = document.getElementById("chart-range-from");
const toInput = document.getElementById("chart-range-to");
const today = ymd(new Date());
fromInput.max = today;
toInput.max = today;
if (r.custom) {
fromInput.value = ymd(r.from);
toInput.value = ymd(r.to);
document.getElementById("chart-range-days").textContent =
`${r.days} ${r.days === 1 ? "day" : "days"}`;
}
const on = countsMetrics();
document.querySelectorAll("#counts-metrics input[data-metric]").forEach(cb => {
cb.checked = on.includes(cb.dataset.metric);
@@ -1889,25 +2041,37 @@
// ---------- daily charts ----------
function weeklyData(events) {
const today = startOfDay(new Date());
const todayYmd = ymd(new Date());
const now = Date.now();
const days = [];
for (let i = chartDays() - 1; i >= 0; i--) {
const d = new Date(today);
d.setDate(d.getDate() - i);
// Built once for the whole window rather than per day: a custom range can
// be a year long, and per-day scans of the full log added up to a visible
// stall on every render.
const sleeps = sleepIntervals(events);
const walks = walkWindows(events).map(w => [w.start, w.end]);
const byDay = new Map();
for (const e of events) {
const k = ymd(new Date(e.at));
let list = byDay.get(k);
if (!list) byDay.set(k, list = []);
list.push(e);
}
for (const d of chartDayList()) {
const isToday = ymd(d) === todayYmd;
const from = startOfDay(d).getTime();
const to = (i === 0) ? now : endOfDay(d).getTime();
const to = isToday ? now : endOfDay(d).getTime();
// A day marked "not counted" keeps its slot on the axis — dropping it
// would make consecutive bars stop being consecutive days — but carries
// no figures. Zeroing them here rather than in each chart means every
// axis maximum, total and tooltip downstream is already right, and the
// drawers only have to decide what to paint in the empty slot.
const excluded = isExcluded(d);
const sleepMs = excluded ? 0 : sleepMsInRange(events, from, to);
const dayEvents = excluded ? [] : eventsForDay(events, d);
const sleepMs = excluded ? 0 : msInIntervals(sleeps, from, to);
const dayEvents = excluded ? [] : (byDay.get(ymd(d)) || []);
days.push({
date: d,
ymd: ymd(d),
isToday,
excluded,
sleepHours: sleepMs / 3_600_000,
pees: dayEvents.filter(e => e.type === "pee").length,
@@ -1931,7 +2095,7 @@
acc[id] = (acc[id] || 0) + e.grams;
return acc;
}, {}),
walkMinutes: excluded ? 0 : walkMsInRange(events, from, to) / 60_000,
walkMinutes: excluded ? 0 : msInIntervals(walks, from, to) / 60_000,
});
}
return days;
@@ -1941,23 +2105,36 @@
// the gap reads as deliberate rather than as a day the puppy barely did
// anything. Shared by all four daily bar charts, which differ only in height.
function excludedSlot(d, x, barW, top, innerH) {
const title = `${d.date.toLocaleDateString(undefined, { weekday: "long", month: "short", day: "numeric" })} — not counted`;
const title = `${fmtDate(d.date, { weekday: "long", month: "short", day: "numeric" })} — not counted`;
return `<rect class="bar bar-excluded" data-day="${d.ymd}" x="${x}" y="${top}" ` +
`width="${barW}" height="${innerH}" rx="3"><title>${escapeText(title)}</title></rect>`;
}
function dayLabel(date, isToday) {
// Weekday names until the window is long enough that "Tue" no longer says
// which Tuesday; past a month the axis gives dates instead.
function dayLabel(date, isToday, len) {
if (isToday) return "Today";
return date.toLocaleDateString(undefined, { weekday: "short" });
if (len > 31) return fmtDate(date, { month: "short", day: "numeric" });
return fmtDate(date, { weekday: "short" });
}
// Wider windows can't fit a label under every bar: label today and every
// 2nd (or 4th) day counting back from it, depending on the window.
// Wider windows can't fit a label under every bar: label the last day and
// every 2nd (or 4th) day counting back from it, depending on the window.
// Past a month the labels are dates, which are wider, so about six fit.
function showDayLabel(i, len) {
const every = len <= 8 ? 1 : len <= 16 ? 2 : 4;
const every = len <= 8 ? 1 : len <= 16 ? 2 : len <= 31 ? 4 : Math.ceil(len / 6);
return (len - 1 - i) % every === 0;
}
// Where a day label sits under its slot. Centred, except that a slot at
// either end too narrow to hold its label — every slot, on a long window —
// gets the label aligned to the plot's edge instead of cut off by it.
function dayLabelPos(i, len, left, width) {
if (width < 24 && i === len - 1) return `x="${(left + width).toFixed(1)}" text-anchor="end"`;
if (width < 24 && i === 0) return `x="${left.toFixed(1)}" text-anchor="start"`;
return `x="${(left + width / 2).toFixed(1)}" text-anchor="middle"`;
}
// Pick a chart Y maximum and tick count so every tick label is a clean
// whole number (avoids 0, 0, 1, 1, 2 from rounding fractional steps):
// 1-unit gridlines up to 10, 2-unit up to 20, 5-unit beyond.
@@ -2023,7 +2200,7 @@
const rawMax = Math.max(...days.map(d => d.sleepHours));
const { yMax, steps: ySteps } = niceAxisSleepHours(rawMax);
const gap = days.length > 14 ? 2 : 4;
const gap = barGapFor(days.length);
const barW = (innerW - (days.length - 1) * gap) / days.length;
// Label every 1h gridline; smaller text once the axis is dense so the
@@ -2040,12 +2217,12 @@
const selYmd = ymd(selectedDay());
days.forEach((d, i) => {
const isToday = i === days.length - 1;
const isToday = d.isToday;
const isSel = d.ymd === selYmd;
const x = ML + i * (barW + gap);
const h = (d.sleepHours / yMax) * innerH;
const y = MT + innerH - h;
const title = `${d.date.toLocaleDateString(undefined, { weekday: "long", month: "short", day: "numeric" })} — ${d.sleepHours.toFixed(1)}h`;
const title = `${fmtDate(d.date, { weekday: "long", month: "short", day: "numeric" })} — ${d.sleepHours.toFixed(1)}h`;
if (isSel) {
parts.push(`<rect class="day-highlight" x="${(x - gap / 2).toFixed(1)}" y="${MT}" width="${(barW + gap).toFixed(1)}" height="${innerH}" rx="3"/>`);
}
@@ -2062,8 +2239,8 @@
// windows that would otherwise skip it.
if (showDayLabel(i, days.length) || isSel) {
parts.push(
`<text class="${isSel ? "day-label-sel" : ""}" x="${x + barW / 2}" y="${H - MB + 14}" text-anchor="middle">` +
`${escapeText(dayLabel(d.date, isToday))}</text>`
`<text class="${isSel ? "day-label-sel" : ""}" ${dayLabelPos(i, days.length, x, barW)} y="${H - MB + 14}">` +
`${escapeText(dayLabel(d.date, isToday, days.length))}</text>`
);
}
});
@@ -2074,8 +2251,8 @@
// fitting it as a real zero would drag the line through the floor.
const trend = dailyTrend(days, d => d.sleepHours > 0 ? d.sleepHours : null);
if (trend) parts.push(trendLineSVG("sleep-trend", trend, { ML, MT, innerH, barW, gap, yMax }));
const blank = days.filter((d, i) => i < days.length - 1 && !d.excluded && !(d.sleepHours > 0)).length;
renderTrendNote("sleep-note", sleepTrendSentence(trend, chartDays()), blank, "with no sleep logged");
const blank = days.filter(d => !d.isToday && !d.excluded && !(d.sleepHours > 0)).length;
renderTrendNote("sleep-note", sleepTrendSentence(trend, chartWindowText()), blank, "with no sleep logged");
setChartSVG(svg, parts);
}
@@ -2084,11 +2261,8 @@
// fitted ends are the line's guess, not a reading — `step` hours for sleep,
// minutes for walks), and no direction claimed unless the move outruns the
// day-to-day scatter and is at least `minChange`, worth acting on.
function amountTrendSentence(trend, windowDays, { what, step, minChange, fmt }) {
const window = `the last ${windowDays} days`;
if (!trend) {
return `Not enough complete days in ${window} to draw a trend — it needs four, and today doesn't count until it's over.`;
}
function amountTrendSentence(trend, window, { what, step, minChange, fmt }) {
if (!trend) return noTrendSentence(window);
const round = (v) => Math.round(Math.max(0, v) / step) * step;
const amount = (v) => fmt(round(v));
const slight = Math.abs(trend.change) < minChange || Math.abs(trend.change) < trend.mean * 0.05;
@@ -2106,12 +2280,18 @@
` — from roughly ${fmt(from)} a day to ${fmt(to)}.`;
}
function sleepTrendSentence(trend, windowDays) {
return amountTrendSentence(trend, windowDays,
// Why there is no line. Today only gets a mention when the window has it.
function noTrendSentence(window) {
return `Not enough complete days in ${window} to draw a trend — it needs four` +
(chartRange().endsToday ? ", and today doesn't count until it's over." : ".");
}
function sleepTrendSentence(trend, window) {
return amountTrendSentence(trend, window,
{ what: "daily sleep", step: 0.5, minChange: 0.25, fmt: (h) => `${h}h` });
}
function walkTrendSentence(trend, windowDays) {
return amountTrendSentence(trend, windowDays,
function walkTrendSentence(trend, window) {
return amountTrendSentence(trend, window,
{ what: "daily walking", step: 5, minChange: 5, fmt: (m) => formatDuration(m * 60_000) });
}
@@ -2155,8 +2335,8 @@
const rawMax = Math.max(0, ...days.flatMap(d => series.map(s => d[s.key])));
const { yMax, steps: ySteps } = niceAxis(rawMax);
const groupGap = days.length > 14 ? 2 : 4;
const innerBarGap = days.length > 14 ? 0.5 : 1.5;
const groupGap = barGapFor(days.length);
const innerBarGap = days.length > 31 ? 0 : days.length > 14 ? 0.5 : 1.5;
const groupW = (innerW - (days.length - 1) * groupGap) / days.length;
const barW = (groupW - (series.length - 1) * innerBarGap) / series.length;
@@ -2170,7 +2350,7 @@
const selYmd = ymd(selectedDay());
days.forEach((d, i) => {
const isToday = i === days.length - 1;
const isToday = d.isToday;
const isSel = d.ymd === selYmd;
const groupX = ML + i * (groupW + groupGap);
@@ -2186,7 +2366,7 @@
const x = groupX + j * (barW + innerBarGap);
const h = (val / yMax) * innerH;
const y = MT + innerH - h;
const title = `${d.date.toLocaleDateString(undefined, { weekday: "long", month: "short", day: "numeric" })} — ${s.label}: ${val}`;
const title = `${fmtDate(d.date, { weekday: "long", month: "short", day: "numeric" })} — ${s.label}: ${val}`;
parts.push(
`<rect class="bar ${s.cls} ${isToday ? "" : "bar-faded"}" data-day="${d.ymd}" ` +
`x="${x}" y="${y}" width="${barW}" height="${Math.max(0, h)}" rx="2">` +
@@ -2197,8 +2377,8 @@
if (showDayLabel(i, days.length) || isSel) {
parts.push(
`<text class="${isSel ? "day-label-sel" : ""}" x="${groupX + groupW / 2}" y="${H - MB + 14}" text-anchor="middle">` +
`${escapeText(dayLabel(d.date, isToday))}</text>`
`<text class="${isSel ? "day-label-sel" : ""}" ${dayLabelPos(i, days.length, groupX, groupW)} y="${H - MB + 14}">` +
`${escapeText(dayLabel(d.date, isToday, days.length))}</text>`
);
}
});
@@ -2224,7 +2404,7 @@
const pts = [];
days.forEach((d, i) => {
if (d.excluded) return;
if (i === days.length - 1) return; // today, still in progress
if (d.isToday) return; // still in progress
const y = valueOf(d);
if (y == null) return;
pts.push({ x: i, y });
@@ -2276,7 +2456,7 @@
const { yMax, steps: ySteps } = niceAxisLinear(Math.max(...days.map(d => d.grams)));
const gap = days.length > 14 ? 2 : 4;
const gap = barGapFor(days.length);
const barW = (innerW - (days.length - 1) * gap) / days.length;
const series = foodSeriesFor(days);
@@ -2291,12 +2471,12 @@
const selYmd = ymd(selectedDay());
days.forEach((d, i) => {
const isToday = i === days.length - 1;
const isToday = d.isToday;
const isSel = d.ymd === selYmd;
const x = ML + i * (barW + gap);
const h = (d.grams / yMax) * innerH;
const y = MT + innerH - h;
const title = `${d.date.toLocaleDateString(undefined, { weekday: "long", month: "short", day: "numeric" })} — ${Math.round(d.grams)} g`;
const title = `${fmtDate(d.date, { weekday: "long", month: "short", day: "numeric" })} — ${Math.round(d.grams)} g`;
if (isSel) {
parts.push(`<rect class="day-highlight" x="${(x - gap / 2).toFixed(1)}" y="${MT}" width="${(barW + gap).toFixed(1)}" height="${innerH}" rx="3"/>`);
}
@@ -2333,8 +2513,8 @@
}
if (showDayLabel(i, days.length) || isSel) {
parts.push(
`<text class="${isSel ? "day-label-sel" : ""}" x="${x + barW / 2}" y="${H - MB + 14}" text-anchor="middle">` +
`${escapeText(dayLabel(d.date, isToday))}</text>`
`<text class="${isSel ? "day-label-sel" : ""}" ${dayLabelPos(i, days.length, x, barW)} y="${H - MB + 14}">` +
`${escapeText(dayLabel(d.date, isToday, days.length))}</text>`
);
}
});
@@ -2428,7 +2608,7 @@
const day = days.find(d => d.ymd === ymd(selectedDay()));
if (!day) { el.hidden = true; return; } // not a day this window draws
const date = day.date.toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" });
const date = fmtDate(day.date, { weekday: "short", month: "short", day: "numeric" });
el.hidden = false;
if (day.excluded) {
el.textContent = `${date} — not counted.`;
@@ -2493,14 +2673,11 @@
// measurements — quoting "287 g" would dress a guess up as a reading.
// bare: drop the "Over the last N days" opener, for when the caller is
// listing several kinds and has already said which window they share.
function foodTrendSentence(trend, windowDays, { bare = false } = {}) {
const window = `the last ${windowDays} days`;
function foodTrendSentence(trend, window, { bare = false } = {}) {
const opener = bare ? "" : `Over ${window}, `;
if (!trend) {
// Says why there is no line. Without this the chart looks broken on a
// short window, or on one where most days are marked.
return `Not enough complete days in ${window} to draw a trend — it needs four, and today doesn't count until it's over.`;
}
if (!trend) return noTrendSentence(window);
const round10 = (v) => Math.round(Math.max(0, v) / 10) * 10;
// Under a twentieth of a typical day is not a move anyone could act on,
// whatever the arithmetic says.
@@ -2525,20 +2702,20 @@
// rest are folded into a clause. Both rules are dailyTrend's, not new ones:
// a kind with too few days has no fit, and one whose move is under its own
// scatter is not claimed.
function foodSeriesSentences(series, windowDays) {
function foodSeriesSentences(series, window) {
// Unsplit: the original single sentence, unchanged.
if (series.length <= 1) return [foodTrendSentence(series[0]?.trend ?? null, windowDays)];
if (series.length <= 1) return [foodTrendSentence(series[0]?.trend ?? null, window)];
const moving = series.filter(s => s.trend && foodTrendMoves(s.trend));
const rest = series.filter(s => !moving.includes(s));
const out = moving.map(s => `${s.name}: ${foodTrendSentence(s.trend, windowDays, { bare: true })}`);
const out = moving.map(s => `${s.name}: ${foodTrendSentence(s.trend, window, { bare: true })}`);
if (rest.length > 0) {
const names = rest.map(s => s.name);
const list = names.length === 1 ? names[0]
: `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
out.push(moving.length === 0
? `Over the last ${windowDays} days, no kind shows a trend bigger than its day-to-day variation (${list}).`
? `Over ${window}, no kind shows a trend bigger than its day-to-day variation (${list}).`
: `${list} ${rest.length === 1 ? "shows" : "show"} no clear trend.`);
}
return out;
@@ -2559,7 +2736,7 @@
// The window comes from the 7/14/30 picker, and naming it is the only way
// the reader can tell that switching it changed the answer — the line
// itself often moves too little to notice.
const lines = foodSeriesSentences(series, chartDays());
const lines = foodSeriesSentences(series, chartWindowText());
const missing = days.reduce((s, d) => s + (d.mealsMissingGrams || 0), 0);
if (missing > 0) {
@@ -2586,7 +2763,7 @@
const { yMax, steps: ySteps } = niceAxisLinear(Math.max(...days.map(d => d.walkMinutes)));
const gap = days.length > 14 ? 2 : 4;
const gap = barGapFor(days.length);
const barW = (innerW - (days.length - 1) * gap) / days.length;
const parts = [];
@@ -2600,12 +2777,12 @@
const selYmd = ymd(selectedDay());
days.forEach((d, i) => {
const isToday = i === days.length - 1;
const isToday = d.isToday;
const isSel = d.ymd === selYmd;
const x = ML + i * (barW + gap);
const h = (d.walkMinutes / yMax) * innerH;
const y = MT + innerH - h;
const title = `${d.date.toLocaleDateString(undefined, { weekday: "long", month: "short", day: "numeric" })} — ${formatDuration(d.walkMinutes * 60_000)}`;
const title = `${fmtDate(d.date, { weekday: "long", month: "short", day: "numeric" })} — ${formatDuration(d.walkMinutes * 60_000)}`;
if (isSel) {
parts.push(`<rect class="day-highlight" x="${(x - gap / 2).toFixed(1)}" y="${MT}" width="${(barW + gap).toFixed(1)}" height="${innerH}" rx="3"/>`);
}
@@ -2620,8 +2797,8 @@
}
if (showDayLabel(i, days.length) || isSel) {
parts.push(
`<text class="${isSel ? "day-label-sel" : ""}" x="${x + barW / 2}" y="${H - MB + 14}" text-anchor="middle">` +
`${escapeText(dayLabel(d.date, isToday))}</text>`
`<text class="${isSel ? "day-label-sel" : ""}" ${dayLabelPos(i, days.length, x, barW)} y="${H - MB + 14}">` +
`${escapeText(dayLabel(d.date, isToday, days.length))}</text>`
);
}
});
@@ -2632,8 +2809,8 @@
// start the line at zero and show a climb that never happened.
const trend = dailyTrend(days, d => d.ymd < firstWalkYmd ? null : d.walkMinutes);
if (trend) parts.push(trendLineSVG("walk-trend-line", trend, { ML, MT, innerH, barW, gap, yMax }));
const before = days.filter((d, i) => i < days.length - 1 && !d.excluded && d.ymd < firstWalkYmd).length;
renderTrendNote("walk-note", walkTrendSentence(trend, chartDays()), before, "from before the first walk was logged");
const before = days.filter(d => !d.isToday && !d.excluded && d.ymd < firstWalkYmd).length;
renderTrendNote("walk-note", walkTrendSentence(trend, chartWindowText()), before, "from before the first walk was logged");
setChartSVG(svg, parts);
}
@@ -2680,19 +2857,25 @@
function drawActogram(svgId, windows, barCls) {
const svg = document.getElementById(svgId);
if (!svg) return;
const N = chartDays();
const range = chartRange();
const dayList = chartDayList();
const N = dayList.length;
const W = 320;
const ML = 44, MR = 8, MT = 16, MB = 4;
const innerW = W - ML - MR;
const rowGap = 2;
// Fixed row height, chart grows with the window (13px × 14 days matches
// the original 228-high viewBox; wider windows use thinner rows).
const rowH = N > 14 ? 9 : 13;
// the original 228-high viewBox; wider windows use thinner rows, down to
// hairlines at a few months so a year stays a scroll rather than a wall).
const rowH = N <= 14 ? 13 : N <= 31 ? 9 : N <= 90 ? 4 : 2;
const rowGap = N <= 31 ? 2 : N <= 90 ? 1 : 0;
const H = MT + MB + N * rowH + (N - 1) * rowGap;
svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
const dayMs = 86_400_000;
// Rows thinner than the text get a label only every so often — enough
// rows apart that labels don't overlap — counted back from the last day.
const labelEvery = Math.max(1, Math.ceil(11 / (rowH + rowGap)));
const todayYmd = ymd(new Date());
const today = startOfDay(new Date());
const xOf = (frac) => ML + frac * innerW;
const parts = [];
@@ -2705,11 +2888,10 @@
const selYmd = ymd(selectedDay());
for (let i = 0; i < N; i++) {
const day = new Date(today);
day.setDate(day.getDate() - (N - 1 - i)); // oldest at top, today at bottom
const day = dayList[i]; // oldest at top, newest at bottom
const dayStart = startOfDay(day).getTime();
const dayEnd = dayStart + dayMs;
const isToday = ymd(day) === ymd(new Date());
const dayEnd = endOfDay(day).getTime() + 1;
const isToday = ymd(day) === todayYmd;
const isSel = ymd(day) === selYmd;
const y = MT + i * (rowH + rowGap);
@@ -2731,17 +2913,20 @@
}
}
const label = isToday ? "Today" : `${day.toLocaleDateString(undefined, { weekday: "short" })} ${day.getDate()}`;
parts.push(`<text class="stl-day ${isToday ? "stl-today" : ""}${isSel ? " stl-sel" : ""}" x="${ML - 6}" y="${(y + rowH / 2 + 3).toFixed(1)}" text-anchor="end">${escapeText(label)}</text>`);
const label = isToday ? "Today"
: N > 31 ? shortDate(day, false)
: `${fmtDate(day, { weekday: "short" })} ${day.getDate()}`;
if ((N - 1 - i) % labelEvery === 0 || isSel) parts.push(`<text class="stl-day ${isToday ? "stl-today" : ""}${isSel ? " stl-sel" : ""}" x="${ML - 6}" y="${(y + rowH / 2 + 3).toFixed(1)}" text-anchor="end">${escapeText(label)}</text>`);
const dateText = day.toLocaleDateString(undefined, { weekday: "long", month: "short", day: "numeric" });
const dateText = fmtDate(day, { weekday: "long", month: "short", day: "numeric" });
const title = isExcluded(day) ? `${dateText} — not counted` : dateText;
parts.push(`<rect class="bar stl-hit" data-day="${ymd(day)}" x="${ML}" y="${y.toFixed(1)}" width="${innerW}" height="${rowH.toFixed(1)}"><title>${escapeText(title)}</title></rect>`);
}
// The window always ends today, so one rule marks both the live edge of the
// bottom row and the same time of day on every row above it.
parts.push(...nowRuleParts(xOf(nowDayFraction()), MT, H - MB));
// When the window ends today, one rule marks both the live edge of the
// bottom row and the same time of day on every row above it. A window
// ending in the past has no live edge, so no rule.
if (range.endsToday) parts.push(...nowRuleParts(xOf(nowDayFraction()), MT, H - MB));
setChartSVG(svg, parts); // wires the .bar[data-day] click → select that day
}
@@ -2828,11 +3013,12 @@
// Mean of the last N days, skipping days that don't count and days with no
// walk at all, so a gap in logging doesn't drag the average toward zero.
const avgDays = chartDays();
const avgList = averageDays(day);
const avgDays = avgList.length;
const dayCurves = [];
for (let i = 1; i <= avgDays; i++) {
if (isExcluded(dayAgo(i))) continue;
const c = hourlyFor(dayStartTs(i));
for (const d of avgList) {
if (isExcluded(d)) continue;
const c = hourlyFor(d.getTime());
if (c[24].y > 0) dayCurves.push(c);
}
let avg = null;
@@ -2940,7 +3126,7 @@
const svg = document.getElementById("chart-hour-heatmap");
if (!svg) return;
const info = document.getElementById("hour-heatmap-info");
const from = startOfDay(new Date(Date.now() - (chartDays() - 1) * 86_400_000)).getTime();
const { from, to } = chartSpan();
const series = [
{ type: "pee", label: "Pees", cls: "hm-pee", one: "pee", many: "pees" },
@@ -2950,7 +3136,7 @@
const counts = {};
for (const s of series) counts[s.type] = new Array(24).fill(0);
for (const e of events) {
if (e.at < from) continue;
if (e.at < from || e.at >= to) continue;
if (counts[e.type]) counts[e.type][new Date(e.at).getHours()]++;
}
@@ -3087,11 +3273,12 @@
// Mean of the last N full days, skipping days that don't count and days
// with no sleep at all, so a young log (or a tracking gap) doesn't drag the
// average toward zero.
const avgDays = chartDays();
const avgList = averageDays(day);
const avgDays = avgList.length;
const dayCurves = [];
for (let i = 1; i <= avgDays; i++) {
if (isExcluded(dayAgo(i))) continue;
const c = curveFor(dayStartTs(i));
for (const d of avgList) {
if (isExcluded(d)) continue;
const c = curveFor(d.getTime());
if (c[24].y > 0) dayCurves.push(c);
}
let avg = null;
@@ -3456,17 +3643,10 @@
if (exercises.length === 0) { wrap.hidden = true; return; }
wrap.hidden = false;
const N = chartDays();
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 range = chartRange();
const dayList = chartDayList();
const N = dayList.length;
const dayIndex = new Map(dayList.map((d, i) => [ymd(d), i])); // ymd -> column
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) {
@@ -3483,6 +3663,9 @@
svg.setAttribute("viewBox", `0 0 ${W} ${H}`);
const innerW = W - ML - MR;
const cellW = innerW / N;
// Space between cells, shrinking with them so a long window's cells
// don't vanish into the gaps.
const cellGap = Math.min(1.5, cellW * 0.2);
const parts = [];
const selCol = dayIndex.get(ymd(selectedDay()));
@@ -3498,15 +3681,15 @@
for (let c = 0; c < N; c++) {
const n = counts[r][c];
const d = dayList[c];
const dateText = d.toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric" });
const dateText = fmtDate(d, { weekday: "short", month: "short", day: "numeric" });
// A day that doesn't count would otherwise show as the palest cell —
// indistinguishable from "trained nothing that day", which is the one
// reading the mark is there to rule out.
if (isExcluded(d)) {
parts.push(
`<rect class="bar bar-excluded" data-day="${ymd(d)}" ` +
`x="${(ML + c * cellW).toFixed(1)}" y="${y.toFixed(1)}" ` +
`width="${(cellW - 1.5).toFixed(1)}" height="${rowH}" rx="2">` +
`x="${(ML + c * cellW).toFixed(2)}" y="${y.toFixed(1)}" ` +
`width="${(cellW - cellGap).toFixed(2)}" height="${rowH}" rx="2">` +
`<title>${escapeText(`${x.name} · ${dateText}: not counted`)}</title></rect>`
);
continue;
@@ -3514,8 +3697,8 @@
const op = n === 0 ? 0.06 : 0.35 + 0.65 * (n / max);
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)}">` +
`x="${(ML + c * cellW).toFixed(2)}" y="${y.toFixed(1)}" ` +
`width="${(cellW - cellGap).toFixed(2)}" height="${rowH}" rx="2" fill-opacity="${op.toFixed(2)}">` +
`<title>${escapeText(`${x.name} · ${dateText}: ${n}`)}</title></rect>`
);
}
@@ -3524,8 +3707,9 @@
});
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>`);
parts.push(`<text x="${ML}" y="${yAxis}" text-anchor="start">${escapeText(fmtDate(dayList[0], { month: "short", day: "numeric" }))}</text>`);
const lastLabel = range.endsToday ? "Today" : fmtDate(dayList[N - 1], { month: "short", day: "numeric" });
parts.push(`<text x="${ML + innerW}" y="${yAxis}" text-anchor="end">${escapeText(lastLabel)}</text>`);
setChartSVG(svg, parts);
}
@@ -3577,7 +3761,7 @@
now.getHours(), now.getMinutes(), now.getSeconds()).getTime();
}
const ev = addEvent("training", "", at, { exerciseId: ex.id });
const dayStr = day.toLocaleDateString(undefined, { month: "short", day: "numeric" });
const dayStr = fmtDate(day, { month: "short", day: "numeric" });
showSnackbar(onToday ? `${ex.name} logged` : `${ex.name} logged for ${dayStr}`, ev);
});
@@ -3628,12 +3812,12 @@
// Year-less date on the picker's face — the year is implicit and the
// saved width keeps the bar on one row on small phones.
document.getElementById("day-date-face").textContent =
day.toLocaleDateString(undefined, { month: "short", day: "numeric" });
fmtDate(day, { month: "short", day: "numeric" });
const title = document.getElementById("overview-title");
if (title) {
title.textContent = isToday
? "Today's overview"
: day.toLocaleDateString(undefined, { weekday: "long", month: "short", day: "numeric" });
: fmtDate(day, { weekday: "long", month: "short", day: "numeric" });
}
renderExcludeToggle(day);
}
@@ -5976,10 +6160,41 @@
quickLog("walk-end");
});
document.querySelectorAll(".chart-days-picker button").forEach(b => {
document.querySelectorAll(".chart-days-picker button[data-days]").forEach(b => {
b.addEventListener("click", () => setChartDays(Number(b.dataset.days)));
});
// Custom opens on the dates used last time, or on the current window the
// first time, so it starts from what's on screen rather than from blanks.
document.getElementById("chart-range-custom").addEventListener("click", () => {
const stored = storedCustomRange();
if (parseYmd(stored?.from) && parseYmd(stored?.to)) {
setCustomRange(stored.from, stored.to);
} else {
const r = chartRange();
setCustomRange(ymd(r.from), ymd(r.to));
}
});
// Moving one end past the other drags the other along, rather than
// refusing the change or silently swapping them.
const chartFromInput = document.getElementById("chart-range-from");
const chartToInput = document.getElementById("chart-range-to");
chartFromInput.addEventListener("change", () => {
const from = parseYmd(chartFromInput.value);
if (!from) { renderChartWindow(); return; }
let to = parseYmd(chartToInput.value) || startOfDay(new Date());
if (to < from) to = from;
setCustomRange(ymd(from), ymd(to));
});
chartToInput.addEventListener("change", () => {
const to = parseYmd(chartToInput.value);
if (!to) { renderChartWindow(); return; }
let from = parseYmd(chartFromInput.value) || to;
if (from > to) from = to;
setCustomRange(ymd(from), ymd(to));
});
document.querySelectorAll("#counts-metrics input[data-metric]").forEach(cb => {
cb.addEventListener("change", () => {
const on = [...document.querySelectorAll("#counts-metrics input[data-metric]:checked")]
+1
View File
@@ -1,4 +1,5 @@
[
{ "date": "2026-10-03", "text": "The charts can cover any stretch of dates, not just the last 7, 14 or 30 days. Tap Custom on the “Charts cover” row and pick a from and a to date — up to a year at a time, and the to date can be in the past, so you can look back at, say, May on its own and see how much he slept or walked then. Every chart and panel that follows the 7 / 14 / 30 buttons follows the custom dates too, and their headings and trend sentences name the dates (“Over May 1 – Jun 15, daily sleep is down about 2h”). On a long range the daily bars sit edge to edge and the axis shows dates instead of weekdays, and the When sleeping and When walking grids use thinner rows so a few months still fit on the screen. The “average day” line on the Sleep trend and Walk trend is averaged over the custom dates as well. Tapping 7d, 14d or 30d goes back to the rolling window, and Custom remembers the dates you picked last" },
{ "date": "2026-10-01", "text": "The app opens straight away when you have no connection. It used to check in with the server before showing anything, and on a weak signal or with the server out of reach that check could take a long while to give up, leaving a blank screen even though all your data was already on the phone. It now opens on the account you were last signed in to and checks in the background; if that sign-in has run out you are taken to the login screen as before" },
{ "date": "2026-09-30", "text": "The Waking → pee and Meal → poo rows are gone from the Timing panel again. With a puppy who takes lots of short naps, most wake-ups were followed by another nap before any pee, so Waking → pee was built from a handful of odd cases and was hard to make sense of. The Pees, Poos and Meals rows are unchanged" },
{ "date": "2026-09-29", "text": "The Walks chart (minutes per day) has a trend line too, with a sentence under it in the same style as the sleep one: “daily walking is up about 20m — from roughly 35m a day to 55m”, or roughly steady with the average when the days vary more than they move. A day with no walk counts as a real zero — a rest day is a real figure — but the days before the very first walk you logged are left out, so starting to track walks partway through the window doesn't read as a sudden climb. Today and days marked “not counted” are left out as on every other trend" },
+9
View File
@@ -215,6 +215,15 @@
<button type="button" class="ghost" data-days="7">7d</button>
<button type="button" class="ghost" data-days="14">14d</button>
<button type="button" class="ghost" data-days="30">30d</button>
<button type="button" class="ghost" id="chart-range-custom">Custom</button>
</div>
<!-- Shown only while Custom is picked. Either end may be in the past,
so a stretch of history can be looked at on its own. -->
<div class="chart-range-fields" id="chart-range-fields" hidden>
<input type="date" id="chart-range-from" aria-label="Charts cover from" />
<span aria-hidden="true">–</span>
<input type="date" id="chart-range-to" aria-label="Charts cover to" />
<span class="muted-note" id="chart-range-days"></span>
</div>
</div>
+17 -1
View File
@@ -889,10 +889,26 @@ dialog menu {
and the buttons sitting on the page background between two cards. */
.chart-window {
display: flex;
flex-wrap: wrap; /* a fourth button leaves no room for the label on a small phone */
align-items: center;
gap: 10px;
gap: 8px 10px;
padding: 0 4px;
}
/* Custom dates get a row of their own under the buttons. */
.chart-range-fields {
flex-basis: 100%;
display: flex;
align-items: center;
gap: 6px;
}
.chart-range-fields input[type="date"] {
flex: 1;
width: auto; /* the global input rule sets 100%, which would push the row */
min-width: 0;
padding: 4px 8px;
font-size: 0.85rem;
}
.chart-range-fields .muted-note { flex: none; white-space: nowrap; }
.chart-window-label {
font-size: 0.75rem;
text-transform: uppercase;