Compare commits
5
Commits
a37474ab82
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a01d74e9d5 | ||
|
|
f98137097c | ||
|
|
35275e6c2c | ||
|
|
a7d3575474 | ||
|
|
e2369f3a3e |
No files matched your search
@@ -136,6 +136,18 @@ of them, because logging has to be one tap from wherever you are.
|
||||
why tabbed apps get a reputation for trapping you: flick between tabs fifteen
|
||||
times and it takes fifteen presses to escape. Two presses, always, from
|
||||
anywhere.
|
||||
- **Sleep tracking can be switched off** (Settings → *Track sleep*) by an
|
||||
account that has stopped logging it. Everything that asks for sleep or shows
|
||||
it carries `data-sleep-only` and is hidden — the log buttons, the Sleep tab,
|
||||
the overview's Sleep/Awake tiles and Last sleep row, the Sleep & wake list —
|
||||
along with the bar timer, and the sleep state reads as unknown, so a
|
||||
`sleep-start` left over from before can't dim the log buttons or run a sleep
|
||||
rail through every day's history. Nothing is deleted: sleep events stay in
|
||||
History, and switching it back on brings the rest back. It is part of the
|
||||
synced profile rather than a device preference, because the server's
|
||||
reminders need it and it decides what a guest is asked to log. The field is
|
||||
the negative `sleepOff`, so a profile from before it existed, or a client too
|
||||
old to send it, means tracking.
|
||||
|
||||
## Layout
|
||||
|
||||
@@ -347,6 +359,11 @@ Opt-in push notifications for the two things that are easy to lose track of:
|
||||
night — and means an overdue rule fires promptly on waking instead. The server
|
||||
derives sleep state exactly the way `currentSleepState()` does in `app.js`,
|
||||
tie-break included, so both sides always agree.
|
||||
- **Unless sleep isn't tracked.** With *Track sleep* off, the sleep state is
|
||||
unknown whatever boundaries are left in the log: the sleep rule never fires
|
||||
and the others are never suppressed. Reading the last boundary anyway would
|
||||
hold the puppy asleep — and every other rule silent — from the day tracking
|
||||
stopped.
|
||||
- **One notification per rule.** Every push carries a `tag`, so a repeat replaces
|
||||
the previous notification instead of stacking another one on the lock screen.
|
||||
- **Late syncs cancel a reminder retroactively.** Rules measure from the event's
|
||||
|
||||
+2
-2
@@ -2,8 +2,8 @@ self: { config, lib, pkgs, ... }:
|
||||
|
||||
let
|
||||
cfg = config.services.puppy-tracker;
|
||||
staticPkg = self.packages.${pkgs.system}.static;
|
||||
serverPkg = self.packages.${pkgs.system}.server;
|
||||
staticPkg = self.packages.${pkgs.stdenv.hostPlatform.system}.static;
|
||||
serverPkg = self.packages.${pkgs.stdenv.hostPlatform.system}.server;
|
||||
in
|
||||
{
|
||||
# The feed schema read walks from is gone; a config that still sets it
|
||||
|
||||
+24
-8
@@ -84,7 +84,12 @@ type Config struct {
|
||||
// PedigreeID is the dog's SKK chip or registration number. When set, the app
|
||||
// unlocks the pedigree view and looks this dog up; empty means no pedigree.
|
||||
PedigreeID string `json:"pedigreeId"`
|
||||
UpdatedAt int64 `json:"updatedAt"`
|
||||
// SleepOff means sleep isn't being logged: the app hides its sleep buttons,
|
||||
// timer and charts, and reminders stop reading the puppy as awake or asleep.
|
||||
// Negative so that the zero value, and a client too old to send the field,
|
||||
// both mean "tracking", which is what every profile was before it existed.
|
||||
SleepOff bool `json:"sleepOff"`
|
||||
UpdatedAt int64 `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type ConfigStore struct {
|
||||
@@ -100,8 +105,8 @@ func (cs *ConfigStore) get(userID string) Config {
|
||||
// One profile row per user. A missing row is the pre-configuration state,
|
||||
// so a zero-value Config is the right answer.
|
||||
err := cs.db.QueryRow(
|
||||
`SELECT name, birthday, pedigree_id, updated FROM config WHERE user_id = ?`, userID,
|
||||
).Scan(&c.Name, &c.Birthday, &c.PedigreeID, &c.UpdatedAt)
|
||||
`SELECT name, birthday, pedigree_id, sleep_off, updated FROM config WHERE user_id = ?`, userID,
|
||||
).Scan(&c.Name, &c.Birthday, &c.PedigreeID, &c.SleepOff, &c.UpdatedAt)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
log.Printf("config get: %v", err)
|
||||
}
|
||||
@@ -111,19 +116,20 @@ func (cs *ConfigStore) get(userID string) Config {
|
||||
// merge applies an incoming config for one user with last-write-wins by
|
||||
// UpdatedAt and returns the resulting stored config (which the caller sends back).
|
||||
func (cs *ConfigStore) merge(userID string, in Config) (Config, error) {
|
||||
// Name/birthday/updated are last-write-wins: the incoming row replaces the
|
||||
// Name/birthday/sleep_off/updated are last-write-wins: the incoming row replaces the
|
||||
// stored one only when strictly newer. The pedigree id is stickier — an empty
|
||||
// incoming value never clears a stored one, so a clock race between devices
|
||||
// can't drop it; when both are set, the newer profile's id wins with the rest.
|
||||
_, err := cs.db.Exec(`
|
||||
INSERT INTO config (user_id, name, birthday, pedigree_id, updated)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
INSERT INTO config (user_id, name, birthday, pedigree_id, sleep_off, updated)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(user_id) DO UPDATE SET
|
||||
name = excluded.name, birthday = excluded.birthday,
|
||||
pedigree_id = CASE WHEN excluded.pedigree_id != '' THEN excluded.pedigree_id ELSE config.pedigree_id END,
|
||||
sleep_off = excluded.sleep_off,
|
||||
updated = excluded.updated
|
||||
WHERE excluded.updated > config.updated`,
|
||||
userID, in.Name, in.Birthday, in.PedigreeID, in.UpdatedAt)
|
||||
userID, in.Name, in.Birthday, in.PedigreeID, in.SleepOff, in.UpdatedAt)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
@@ -468,6 +474,7 @@ func openDB(path string) (*sql.DB, error) {
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
birthday TEXT NOT NULL DEFAULT '',
|
||||
pedigree_id TEXT NOT NULL DEFAULT '',
|
||||
sleep_off INTEGER NOT NULL DEFAULT 0,
|
||||
updated INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
@@ -653,6 +660,15 @@ func migrateSchema(db *sql.DB) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
hasSleepOff, err := columnExists(db, "config", "sleep_off")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !hasSleepOff {
|
||||
if _, err := db.Exec(`ALTER TABLE config ADD COLUMN sleep_off INTEGER NOT NULL DEFAULT 0`); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1029,7 +1045,7 @@ func main() {
|
||||
case http.MethodGet:
|
||||
writeConfig(configStore.get(userID(r)))
|
||||
case http.MethodPut, http.MethodPost:
|
||||
// The profile (name, birthday, pedigree id) is the owner's to set.
|
||||
// The profile (name, birthday, pedigree id, sleep tracking) is the owner's to set.
|
||||
// The GET above stays open — a guest needs the name and birthday to
|
||||
// render the header at all.
|
||||
if isGuest(r) {
|
||||
|
||||
+16
-1
@@ -188,10 +188,25 @@ type sleepState struct {
|
||||
since int64 // ms epoch of that boundary
|
||||
}
|
||||
|
||||
// sleepStateFor reads that boundary for one user. An account that has switched
|
||||
// sleep tracking off has no sleep state at all,
|
||||
// whatever boundaries are left in its log. Reading the last one anyway would
|
||||
// leave the puppy "asleep" from the day tracking stopped, with every other
|
||||
// rule silenced for good — or "awake" since then, with the sleep rule firing
|
||||
// every interval forever.
|
||||
func (sch *Scheduler) sleepStateFor(userID string) (sleepState, error) {
|
||||
var off bool
|
||||
err := sch.db.QueryRow(`SELECT sleep_off FROM config WHERE user_id = ?`, userID).Scan(&off)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return sleepState{}, err
|
||||
}
|
||||
if off {
|
||||
return sleepState{}, nil
|
||||
}
|
||||
|
||||
var typ string
|
||||
var at int64
|
||||
err := sch.db.QueryRow(`
|
||||
err = sch.db.QueryRow(`
|
||||
SELECT type, at FROM events
|
||||
WHERE user_id = ? AND deleted = 0 AND type IN ('sleep-start', 'sleep-end')
|
||||
ORDER BY at DESC, updated DESC LIMIT 1`, userID).Scan(&typ, &at)
|
||||
|
||||
@@ -188,6 +188,46 @@ func TestSleepStateMatchesLatestBoundary(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSleepStateIgnoredWhenTrackingIsOff(t *testing.T) {
|
||||
sch := testScheduler(t)
|
||||
now := int64(1_700_000_000_000)
|
||||
configs := newConfigStore(sch.db)
|
||||
|
||||
// Tracking stopped while the log still says asleep.
|
||||
addEvent(t, sch, "u1", "pee", now-90*minute)
|
||||
addEvent(t, sch, "u1", "sleep-start", now-600*minute)
|
||||
if _, err := configs.merge("u1", Config{Name: "Rex", SleepOff: true, UpdatedAt: now}); err != nil {
|
||||
t.Fatalf("merge: %v", err)
|
||||
}
|
||||
if got := configs.get("u1"); !got.SleepOff {
|
||||
t.Fatal("sleepOff did not round-trip through the config store")
|
||||
}
|
||||
s, err := sch.sleepStateFor("u1")
|
||||
if err != nil {
|
||||
t.Fatalf("sleepStateFor: %v", err)
|
||||
}
|
||||
if s.state != "" {
|
||||
t.Errorf("state = %q, want none while tracking is off", s.state)
|
||||
}
|
||||
|
||||
// So an overdue pee rule fires rather than waiting for a wake-up that will
|
||||
// never be logged, and the sleep rule stays quiet.
|
||||
if _, ok, err := sch.due("u1", Reminder{Kind: "pee", Enabled: true, IntervalMin: 60}, 0, now, s); err != nil || !ok {
|
||||
t.Errorf("pee: fired = %v (err %v), want a fire", ok, err)
|
||||
}
|
||||
if _, ok, err := sch.due("u1", Reminder{Kind: "sleep", Enabled: true, IntervalMin: 45}, 0, now, s); err != nil || ok {
|
||||
t.Errorf("sleep: fired = %v (err %v), want no fire", ok, err)
|
||||
}
|
||||
|
||||
// Switching it back on reads the log again.
|
||||
if _, err := configs.merge("u1", Config{Name: "Rex", UpdatedAt: now + 1}); err != nil {
|
||||
t.Fatalf("merge: %v", err)
|
||||
}
|
||||
if s, err := sch.sleepStateFor("u1"); err != nil || s.state != "asleep" {
|
||||
t.Errorf("tracking back on: state = %q (err %v), want asleep", s.state, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemindersStoreDefaultsAndClamping(t *testing.T) {
|
||||
sch := testScheduler(t)
|
||||
|
||||
|
||||
+114
-31
@@ -233,15 +233,16 @@
|
||||
function loadConfig() {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(configKey()));
|
||||
if (!parsed || typeof parsed !== "object") return { name: "", birthday: "", pedigreeId: "", updatedAt: 0 };
|
||||
if (!parsed || typeof parsed !== "object") return { name: "", birthday: "", pedigreeId: "", sleepOff: false, updatedAt: 0 };
|
||||
return {
|
||||
name: parsed.name || "",
|
||||
birthday: parsed.birthday || "",
|
||||
pedigreeId: parsed.pedigreeId || "",
|
||||
sleepOff: parsed.sleepOff === true,
|
||||
updatedAt: Number.isFinite(parsed.updatedAt) ? parsed.updatedAt : 0,
|
||||
};
|
||||
} catch {
|
||||
return { name: "", birthday: "", pedigreeId: "", updatedAt: 0 };
|
||||
return { name: "", birthday: "", pedigreeId: "", sleepOff: false, updatedAt: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,10 +250,11 @@
|
||||
localStorage.setItem(configKey(), JSON.stringify(cfg));
|
||||
}
|
||||
|
||||
// Reconcile a local and a server profile. Name/birthday/updatedAt are plain
|
||||
// last-write-wins by timestamp. The pedigree id is sticky: a non-empty value
|
||||
// never loses to an empty one — so it can't be dropped by a clock race between
|
||||
// devices — and when both are set the newer profile's id wins with the rest.
|
||||
// Reconcile a local and a server profile. Name/birthday/sleepOff/updatedAt
|
||||
// are plain last-write-wins by timestamp. The pedigree id is sticky: a
|
||||
// non-empty value never loses to an empty one — so it can't be dropped by a
|
||||
// clock race between devices — and when both are set the newer profile's id
|
||||
// wins with the rest.
|
||||
// (The server merge mirrors this, so a set id is only changed, never cleared,
|
||||
// by sync.)
|
||||
function reconcileConfig(local, server) {
|
||||
@@ -263,12 +265,28 @@
|
||||
pedigreeId: (local.pedigreeId && server.pedigreeId)
|
||||
? base.pedigreeId
|
||||
: (local.pedigreeId || server.pedigreeId),
|
||||
sleepOff: base.sleepOff,
|
||||
updatedAt: base.updatedAt,
|
||||
};
|
||||
}
|
||||
function sameConfig(a, b) {
|
||||
return a.name === b.name && a.birthday === b.birthday
|
||||
&& a.pedigreeId === b.pedigreeId && a.updatedAt === b.updatedAt;
|
||||
&& a.pedigreeId === b.pedigreeId && a.sleepOff === b.sleepOff
|
||||
&& a.updatedAt === b.updatedAt;
|
||||
}
|
||||
|
||||
// Sleep tracking can be switched off in Settings by an account that has
|
||||
// stopped logging it. Everything that asks for sleep or shows it then goes
|
||||
// (each such element carries data-sleep-only, plus the bar timer), and the
|
||||
// sleep state reads as unknown, so a boundary left over from before can't
|
||||
// hold the puppy "asleep" for weeks — dimming every log button and drawing a
|
||||
// sleep rail through every day's history. Nothing is deleted: sleep events
|
||||
// already logged stay in History, and switching it back on restores the rest.
|
||||
function sleepTracked() {
|
||||
return !loadConfig().sleepOff;
|
||||
}
|
||||
function trackedSleepState(events) {
|
||||
return sleepTracked() ? currentSleepState(events) : { state: null, since: 0 };
|
||||
}
|
||||
|
||||
// Age in whole days / weeks / calendar months from a "YYYY-MM-DD" birthday,
|
||||
@@ -281,7 +299,9 @@
|
||||
const birth = startOfDay(new Date(y, mo - 1, d));
|
||||
const ref = startOfDay(new Date(Number.isFinite(at) ? at : Date.now()));
|
||||
if (birth > ref) return null;
|
||||
const days = Math.floor((ref - birth) / 86_400_000);
|
||||
// Rounded, not floored: between local midnights a spring DST switch makes
|
||||
// the span an hour short of whole days, and flooring would drop a day.
|
||||
const days = Math.round((ref - birth) / 86_400_000);
|
||||
const weeks = Math.floor(days / 7);
|
||||
let months = (ref.getFullYear() - birth.getFullYear()) * 12 +
|
||||
(ref.getMonth() - birth.getMonth());
|
||||
@@ -290,7 +310,7 @@
|
||||
// Whole weeks left over after the calendar months (so "N months and M weeks").
|
||||
const anchor = startOfDay(new Date(birth.getFullYear(),
|
||||
birth.getMonth() + months, birth.getDate()));
|
||||
const remWeeks = Math.floor((ref - anchor) / 86_400_000 / 7);
|
||||
const remWeeks = Math.floor(Math.round((ref - anchor) / 86_400_000) / 7);
|
||||
return { days, weeks, months, remWeeks };
|
||||
}
|
||||
|
||||
@@ -1260,7 +1280,7 @@
|
||||
const pill = document.getElementById("bar-clock");
|
||||
const icon = document.getElementById("bar-clock-icon");
|
||||
const ptime = document.getElementById("bar-clock-time");
|
||||
const { state, since: ts } = currentSleepState(events);
|
||||
const { state, since: ts } = trackedSleepState(events);
|
||||
sleepState = state;
|
||||
sleepSince = ts;
|
||||
|
||||
@@ -1400,7 +1420,7 @@
|
||||
function historyRails(events, dayEvents, day) {
|
||||
const rails = new Map();
|
||||
const spans = [
|
||||
...sleepWindowsForDay(events, day).map(w => ({ ...w, kind: "sleep" })),
|
||||
...(sleepTracked() ? sleepWindowsForDay(events, day) : []).map(w => ({ ...w, kind: "sleep" })),
|
||||
...walkWindowsForDay(events, day).map(w => ({ ...w, kind: "walk" })),
|
||||
];
|
||||
for (const span of spans) {
|
||||
@@ -2829,8 +2849,34 @@
|
||||
// Where "now" falls in the day, 0..1 — the shared x for the charts that run
|
||||
// midnight to midnight.
|
||||
function nowDayFraction() {
|
||||
const now = new Date();
|
||||
return (now.getTime() - startOfDay(now).getTime()) / 86_400_000;
|
||||
return clockDayFraction(Date.now());
|
||||
}
|
||||
|
||||
// Wall-clock time of day as 0..1, read off the clock rather than counted
|
||||
// from midnight, so a 23- or 25-hour day (the DST switches) still fits the
|
||||
// 0h–24h axis: the hour that repeats in autumn is drawn over itself and the
|
||||
// hour skipped in spring is just a gap.
|
||||
function clockDayFraction(ts) {
|
||||
const d = new Date(ts);
|
||||
return (d.getHours() * 3_600_000 + d.getMinutes() * 60_000 +
|
||||
d.getSeconds() * 1000 + d.getMilliseconds()) / 86_400_000;
|
||||
}
|
||||
|
||||
// The instant the clock reads h:00 on the day starting at dayStart; h = 24
|
||||
// is the next midnight. On a DST day this is not dayStart + h hours, so the
|
||||
// hour-of-day charts step through the day with this rather than adding up
|
||||
// fixed hours. (A skipped hour lands on the next one; a repeated one on its
|
||||
// first pass.)
|
||||
function clockHourTs(dayStart, h) {
|
||||
const d = new Date(dayStart);
|
||||
d.setHours(h, 0, 0, 0);
|
||||
return d.getTime();
|
||||
}
|
||||
|
||||
// Hour of day 0..24 by the clock for a time within the day starting at
|
||||
// dayStart, with the next midnight as 24 rather than 0.
|
||||
function clockHourOf(ts, dayStart) {
|
||||
return ts >= clockHourTs(dayStart, 24) ? 24 : clockDayFraction(ts) * 24;
|
||||
}
|
||||
|
||||
// Vertical "now" rule for those charts: ink over a surface-coloured underlay
|
||||
@@ -2870,7 +2916,6 @@
|
||||
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)));
|
||||
@@ -2907,8 +2952,12 @@
|
||||
const s = Math.max(wdw.start, dayStart);
|
||||
const e = Math.min(wdw.end, dayEnd);
|
||||
if (e <= s) continue;
|
||||
const x = xOf((s - dayStart) / dayMs);
|
||||
const wpx = ((e - s) / dayMs) * innerW;
|
||||
// Placed by clock time, not elapsed time, so a DST day lines up with
|
||||
// the hour gridlines; a window ending at the next midnight runs to 24h.
|
||||
const fs = clockDayFraction(s);
|
||||
const fe = e >= dayEnd ? 1 : clockDayFraction(e);
|
||||
const x = xOf(fs);
|
||||
const wpx = (fe - fs) * innerW;
|
||||
parts.push(`<rect class="${barCls}" x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${Math.max(0.6, wpx).toFixed(1)}" height="${rowH.toFixed(1)}" rx="1.5"/>`);
|
||||
}
|
||||
}
|
||||
@@ -2961,7 +3010,7 @@
|
||||
// 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 MIN = 60_000;
|
||||
const windows = walkWindows(events); // an ongoing walk is already clipped to now
|
||||
const walkedMs = (from, to) => {
|
||||
let total = 0;
|
||||
@@ -2980,13 +3029,20 @@
|
||||
return d;
|
||||
};
|
||||
const dayStartTs = (daysAgo) => dayAgo(daysAgo).getTime();
|
||||
const pointsAt = (start, stops) =>
|
||||
stops.map(t => ({ x: (t - start) / HOUR, y: walkedMs(start, t) / MIN }));
|
||||
// x is the clock hour, held from stepping back inside the hour that
|
||||
// repeats when the clocks go back, so the step line never folds over.
|
||||
const pointsAt = (start, stops) => {
|
||||
let lastX = 0;
|
||||
return stops.map(t => {
|
||||
lastX = Math.max(lastX, clockHourOf(t, start));
|
||||
return { x: lastX, 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 end = capTs != null ? capTs : clockHourTs(start, 24);
|
||||
const stops = new Set([start, end]);
|
||||
for (const w of windows) {
|
||||
if (w.end <= start || w.start >= end) continue;
|
||||
@@ -2997,7 +3053,7 @@
|
||||
};
|
||||
const hourlyFor = (start) => {
|
||||
const stops = [];
|
||||
for (let h = 0; h <= 24; h++) stops.push(start + h * HOUR);
|
||||
for (let h = 0; h <= 24; h++) stops.push(clockHourTs(start, h));
|
||||
return pointsAt(start, stops);
|
||||
};
|
||||
const totalOf = (pts) => pts[pts.length - 1].y;
|
||||
@@ -3241,9 +3297,9 @@
|
||||
const curveFor = (start, capTs) => {
|
||||
const pts = [];
|
||||
for (let h = 0; h <= 24; h++) {
|
||||
const to = start + h * HOUR;
|
||||
const to = clockHourTs(start, h);
|
||||
if (capTs != null && to >= capTs) {
|
||||
pts.push({ x: (capTs - start) / HOUR, y: sleptMs(start, capTs) / HOUR });
|
||||
pts.push({ x: clockHourOf(capTs, start), y: sleptMs(start, capTs) / HOUR });
|
||||
break;
|
||||
}
|
||||
pts.push({ x: h, y: sleptMs(start, to) / HOUR });
|
||||
@@ -3882,7 +3938,7 @@
|
||||
// corrections (a mid-nap pee) are never blocked, and a genuinely missed
|
||||
// boundary is still fixable from the event log, which accepts any time.
|
||||
function renderActionHints(events) {
|
||||
const { state } = currentSleepState(events);
|
||||
const { state } = trackedSleepState(events);
|
||||
const { walking } = currentWalkState(events);
|
||||
document.querySelectorAll("button.action").forEach(btn => {
|
||||
const type = btn.dataset.type;
|
||||
@@ -3909,6 +3965,14 @@
|
||||
});
|
||||
}
|
||||
|
||||
// Show or hide everything marked data-sleep-only (see sleepTracked). The
|
||||
// Sleep tab goes with it, so a device left on that tab is moved to Today.
|
||||
function renderSleepTracking() {
|
||||
const on = sleepTracked();
|
||||
document.querySelectorAll("[data-sleep-only]").forEach(el => { el.hidden = !on; });
|
||||
if (!on && activeTab === "sleep") showTab(DEFAULT_TAB);
|
||||
}
|
||||
|
||||
function render() {
|
||||
const events = live();
|
||||
// Which days don't count is read straight off the event list, and settles
|
||||
@@ -3916,6 +3980,7 @@
|
||||
excludedSet = excludedDays(events);
|
||||
const counted = countedEvents(events);
|
||||
renderHeader();
|
||||
renderSleepTracking();
|
||||
renderDayBar();
|
||||
renderChartWindow();
|
||||
// Day-scoped panels get the full list: you navigated to this day, so you
|
||||
@@ -4113,12 +4178,15 @@
|
||||
name: body.name || "",
|
||||
birthday: body.birthday || "",
|
||||
pedigreeId: body.pedigreeId || "",
|
||||
sleepOff: body.sleepOff === true,
|
||||
updatedAt: Number.isFinite(body.updatedAt) ? body.updatedAt : 0,
|
||||
};
|
||||
const merged = reconcileConfig(local, server);
|
||||
if (!sameConfig(merged, local)) {
|
||||
saveConfig(merged);
|
||||
renderHeader();
|
||||
// A full render rather than just the header: sleep tracking switched
|
||||
// on another device changes which panels show.
|
||||
render();
|
||||
refreshPedigreeButton();
|
||||
}
|
||||
if (!sameConfig(merged, server)) {
|
||||
@@ -4140,8 +4208,8 @@
|
||||
const body = await res.json();
|
||||
// Adopt the server's answer if it turned out to be newer (another client won).
|
||||
if (Number.isFinite(body.updatedAt) && body.updatedAt > cfg.updatedAt) {
|
||||
saveConfig({ name: body.name || "", birthday: body.birthday || "", pedigreeId: body.pedigreeId || "", updatedAt: body.updatedAt });
|
||||
renderHeader();
|
||||
saveConfig({ name: body.name || "", birthday: body.birthday || "", pedigreeId: body.pedigreeId || "", sleepOff: body.sleepOff === true, updatedAt: body.updatedAt });
|
||||
render();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4532,6 +4600,7 @@
|
||||
const settingsPedigree = document.getElementById("settings-pedigree");
|
||||
const settingsTheme = document.getElementById("settings-theme");
|
||||
const settingsConfetti = document.getElementById("settings-confetti");
|
||||
const settingsSleep = document.getElementById("settings-sleep");
|
||||
const settingsProfile = document.getElementById("settings-profile");
|
||||
const settingsDanger = document.getElementById("settings-danger");
|
||||
|
||||
@@ -4539,12 +4608,18 @@
|
||||
settingsTheme.addEventListener("change", () => {
|
||||
setTheme(settingsTheme.checked ? "dark" : "light");
|
||||
});
|
||||
// Only the sleep reminder follows the switch live; the rest waits for Save.
|
||||
settingsSleep.addEventListener("change", () => {
|
||||
const row = remindersRules.querySelector('.reminder-row[data-kind="sleep"]');
|
||||
if (row) row.hidden = !settingsSleep.checked;
|
||||
});
|
||||
|
||||
function openSettingsDialog() {
|
||||
const cfg = loadConfig();
|
||||
settingsName.value = cfg.name;
|
||||
settingsBirthday.value = cfg.birthday;
|
||||
settingsPedigree.value = cfg.pedigreeId;
|
||||
settingsSleep.checked = !cfg.sleepOff;
|
||||
settingsTheme.checked = effectiveTheme() === "dark";
|
||||
settingsConfetti.checked = confettiEnabled();
|
||||
// A guest keeps the two device-local preferences and loses everything that
|
||||
@@ -4582,11 +4657,12 @@
|
||||
name: settingsName.value.trim(),
|
||||
birthday: settingsBirthday.value,
|
||||
pedigreeId: settingsPedigree.value.trim(),
|
||||
sleepOff: !settingsSleep.checked,
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
saveConfig(cfg); // cache locally for instant + offline paint
|
||||
setConfettiEnabled(settingsConfetti.checked); // device-local, not synced
|
||||
renderHeader();
|
||||
render();
|
||||
refreshPedigreeButton();
|
||||
settingsDialog.close();
|
||||
// Rules are saved with the rest of Settings; the notification toggle itself
|
||||
@@ -5012,6 +5088,10 @@
|
||||
const row = document.createElement("div");
|
||||
row.className = "reminder-row";
|
||||
row.dataset.kind = rule.kind;
|
||||
// The server never fires the sleep rule while sleep isn't tracked, so it
|
||||
// is hidden rather than shown switched on and doing nothing. It is still
|
||||
// saved as it stands, ready for when tracking comes back.
|
||||
row.hidden = rule.kind === "sleep" && !settingsSleep.checked;
|
||||
|
||||
const name = document.createElement("label");
|
||||
name.className = "reminder-name";
|
||||
@@ -6040,7 +6120,8 @@
|
||||
});
|
||||
|
||||
function showTab(id, { manageBack = true } = {}) {
|
||||
if (!tabButtons.some(b => b.dataset.tab === id)) id = DEFAULT_TAB;
|
||||
// A hidden tab (Sleep, while sleep isn't tracked) can't be shown either.
|
||||
if (!tabButtons.some(b => b.dataset.tab === id && !b.hidden)) id = DEFAULT_TAB;
|
||||
activeTab = id;
|
||||
for (const b of tabButtons) {
|
||||
const on = b.dataset.tab === id;
|
||||
@@ -6075,7 +6156,7 @@
|
||||
updateTabsMerged();
|
||||
}
|
||||
|
||||
for (const [i, btn] of tabButtons.entries()) {
|
||||
for (const btn of tabButtons) {
|
||||
btn.addEventListener("click", () => {
|
||||
// Tapping the tab you are already on is the one way to ask for the top —
|
||||
// the convention from phone apps, where it is how you get back from deep
|
||||
@@ -6091,7 +6172,9 @@
|
||||
const step = e.key === "ArrowRight" ? 1 : e.key === "ArrowLeft" ? -1 : 0;
|
||||
if (!step) return;
|
||||
e.preventDefault();
|
||||
const next = tabButtons[(i + step + tabButtons.length) % tabButtons.length];
|
||||
// Arrows step over a hidden tab rather than landing on it.
|
||||
const shown = tabButtons.filter(b => !b.hidden);
|
||||
const next = shown[(shown.indexOf(btn) + step + shown.length) % shown.length];
|
||||
showTab(next.dataset.tab);
|
||||
next.focus();
|
||||
});
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
[
|
||||
{ "date": "2026-11-12", "text": "Sleep tracking can be switched off. Turn off Track sleep in Settings and the Sleep start / Sleep end buttons, the asleep/awake timer, the Sleep tab, the Sleep and Awake figures and the Sleep & wake list all go away, and nothing is dimmed any more for being “unlikely” while asleep. Reminders stop going quiet while the log says asleep, and the Time to sleep reminder stops firing. Sleep you have already logged is kept, so you can switch it back on for a day whenever you want to track it" },
|
||||
{ "date": "2026-10-28", "text": "The Sleep trend and Walk trend charts handle the days the clocks change. Their hour axis counted hours from midnight rather than reading the clock, so on the Sunday the clocks go back the day’s line stopped at 11 pm and left out the last hour — taking it off that day’s total and off the average day built from it — and in spring the day ran on into 1 am the next morning. Today’s line also ended an hour away from the “now” marker on those days. Both charts now follow the clock, so every day runs from midnight to midnight whatever its length" },
|
||||
{ "date": "2026-10-28", "text": "His age is no longer a day short for part of the year. Depending on when he was born, counting the days since his birthday could come up one short between the clocks going forward in spring and going back in autumn, and the week and month counts in “16 weeks (3 months and 3 weeks) old” ticked over a day late" },
|
||||
{ "date": "2026-10-28", "text": "The When sleeping and When walking grids draw the days the clocks change correctly. On the Sunday the clocks go back the day is 25 hours long, and everything after 3 am was drawn an hour late — the evening sleep ran off the right-hand end of the row. In spring the 23-hour day stopped short of 24h instead. Each nap and walk now sits at the time the clock showed, lining up with the hour lines like every other day, and the “now” marker does the same on those days" },
|
||||
{ "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" },
|
||||
|
||||
+16
-6
@@ -174,7 +174,9 @@
|
||||
its own). A row per timed pair, then the two one-tap moments, and
|
||||
last the three that open a dialog to type a value. -->
|
||||
<div class="actions">
|
||||
<div class="action-row">
|
||||
<!-- data-sleep-only: hidden while sleep tracking is off in Settings,
|
||||
like everything else so marked (see renderSleepTracking). -->
|
||||
<div class="action-row" data-sleep-only>
|
||||
<button class="action sleep" data-type="sleep-start">😴 Sleep start</button>
|
||||
<button class="action sleep" data-type="sleep-end">⏰ Sleep end</button>
|
||||
</div>
|
||||
@@ -199,7 +201,7 @@
|
||||
above them: logging has to be one tap from wherever you are. -->
|
||||
<nav class="tabs" role="tablist" aria-label="Sections">
|
||||
<button type="button" class="tab" role="tab" data-tab="today" id="tab-today" aria-controls="tabpanel-today" aria-selected="false" tabindex="-1">Today</button>
|
||||
<button type="button" class="tab" role="tab" data-tab="sleep" id="tab-sleep" aria-controls="tabpanel-sleep" aria-selected="false" tabindex="-1">Sleep</button>
|
||||
<button type="button" class="tab" role="tab" data-tab="sleep" id="tab-sleep" aria-controls="tabpanel-sleep" aria-selected="false" tabindex="-1" data-sleep-only>Sleep</button>
|
||||
<button type="button" class="tab" role="tab" data-tab="walks" id="tab-walks" aria-controls="tabpanel-walks" aria-selected="false" tabindex="-1">Walks</button>
|
||||
<button type="button" class="tab" role="tab" data-tab="habits" id="tab-habits" aria-controls="tabpanel-habits" aria-selected="false" tabindex="-1">Habits</button>
|
||||
<button type="button" class="tab" role="tab" data-tab="growth" id="tab-growth" aria-controls="tabpanel-growth" aria-selected="false" tabindex="-1">Growth</button>
|
||||
@@ -242,11 +244,11 @@
|
||||
Not counted in the charts and averages. Everything below is unchanged.
|
||||
</p>
|
||||
<div class="stats">
|
||||
<div class="stat">
|
||||
<div class="stat" data-sleep-only>
|
||||
<div class="stat-label">Sleep</div>
|
||||
<div class="stat-value" id="stat-sleep">0h 0m</div>
|
||||
</div>
|
||||
<div class="stat">
|
||||
<div class="stat" data-sleep-only>
|
||||
<div class="stat-label">Awake</div>
|
||||
<div class="stat-value" id="stat-awake">0h 0m</div>
|
||||
</div>
|
||||
@@ -282,7 +284,7 @@
|
||||
<div class="last-row"><span>Last pee</span><span id="last-pee">—</span></div>
|
||||
<div class="last-row"><span>Last poo</span><span id="last-poo">—</span></div>
|
||||
<div class="last-row"><span>Last meal</span><span id="last-eat">—</span></div>
|
||||
<div class="last-row"><span>Last sleep</span><span id="last-sleep">—</span></div>
|
||||
<div class="last-row" data-sleep-only><span>Last sleep</span><span id="last-sleep">—</span></div>
|
||||
<div class="last-row"><span>Last walk</span><span id="last-walk">—</span></div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -292,7 +294,7 @@
|
||||
one alternating list rather than sitting in two panels that each show
|
||||
half the day. Every row carries its state; the open one keeps the
|
||||
highlight. -->
|
||||
<section class="sleepwake" data-panel="sleep-wake">
|
||||
<section class="sleepwake" data-panel="sleep-wake" data-sleep-only>
|
||||
<h2>Sleep & wake</h2>
|
||||
<ul id="sleep-wake-list" class="wake-list"></ul>
|
||||
<p id="sleep-wake-empty" class="empty">No sleep or wake windows yet for this day.</p>
|
||||
@@ -585,6 +587,14 @@
|
||||
placeholder="SKK chip or reg. number (optional)" />
|
||||
</label>
|
||||
<p class="settings-hint">Set your dog's SKK chip or registration number to unlock the 🌳 pedigree page.</p>
|
||||
<!-- Part of the synced profile rather than a device preference: it
|
||||
decides what a guest is asked to log, and the server needs it so
|
||||
reminders stop reading a sleep state nobody is keeping up. -->
|
||||
<label class="toggle-row">
|
||||
<span>Track sleep</span>
|
||||
<input type="checkbox" id="settings-sleep" role="switch" class="switch" />
|
||||
</label>
|
||||
<p class="settings-hint">Off hides the sleep buttons, timer and charts. Sleep already logged is kept, so you can switch it back on for a day whenever you like.</p>
|
||||
</div>
|
||||
<label class="toggle-row">
|
||||
<span>Dark mode</span>
|
||||
|
||||
Reference in new issue
Block a user