Compare commits

...

44 Commits

Author SHA1 Message Date
Alexander Heldt f9894abfc9 Add free-text day notes with an always-visible notes log
A new 📝 Note quick-action logs a free-text note (with a date, optional
photo, and any text), defaulting to the day you're viewing. Notes are a
distinct "note" event type, so they edit, sync and delete like any other
event, and a new Notes section lists them newest-first across every day —
independent of the day picker — so records like vaccinations stay visible
whatever day you're looking at.
2026-08-02 13:37:39 +00:00
Alexander Heldt 09d9d38c12 Add metric checkboxes to the daily counts chart
The Daily counts legend is now a Pees/Poos/Meals checkbox group, so you
can hide metrics and focus on just the ones you care about. The choice is
persisted per device, at least one metric is always kept visible, and the
y-axis and bar widths adapt to the selected metrics.
2026-08-02 13:26:38 +00:00
Alexander Heldt a44c75d2d4 Let the confetti fade at its peak instead of falling back
Drop the descent phase: each emoji now rises to its peak, slows (ease-out) and
fades out at the top rather than arcing back down. Removes the now-unused --endY.
2026-08-01 18:28:40 +00:00
Alexander Heldt e2f99590f1 Make the pee/poo confetti a bottom-up fireworks fountain
Rework the effect: instead of a small burst from the tapped button, 30 emoji
launch from across the bottom of the screen, rise to random peaks while
drifting sideways, then arc back down and fade — staggered launches and varied
speed/size/rotation for a fuller, firework feel. Still pointer-events:none,
self-removing, and gated by the Settings toggle and reduced-motion.
2026-08-01 18:24:33 +00:00
Alexander Heldt 52c50c97b1 Celebrate a logged pee/poo with emoji confetti
Tapping the pee or poo quick-log button now sets off a short burst of 💧/💩
particles from the button — pure DOM + CSS, pointer-events:none so it never
blocks taps, particles self-remove on animation end. It honours
prefers-reduced-motion, and there's a "Pee/poo confetti" switch in Settings
(device-local, on by default) to turn it off.
2026-08-01 18:18:26 +00:00
Alexander Heldt 1ed325b834 Keep the header and weight rows tidy when the age is long
The age counter can read "16 weeks (3 months and 3 weeks) old", which broke
two tight layouts: the header title never truncated, so a long name (or the
wide status pill) collided with the action buttons and the age wrapped to
three lines; and each weight-log row embedded the full age, wrapping to two
lines.

Add compact age formatters and use them where space is tight: formatAgeShort
("16 wk · 3 mo 3 wk") in the header, formatAgeWeeks ("16 wk") in weight rows;
the verbose form stays on the roomy weight-chart caption. Make the header
robust — the title flexes and the name ellipsis-truncates so the buttons are
never pushed, while the age wraps rather than truncating so it's never cut
off. Weight rows keep the date/age on one line with the value pinned right.
2026-08-01 18:11:03 +00:00
Alexander Heldt 69e312175b Add a radial fan-chart view of the pedigree
Add a Fan / Tree toggle in the pedigree header. The fan places the dog in a
centre disc with each generation as a ring fanning outward, so up to nine
generations fit in one compact circle instead of a tree that doubles in
width every generation. Inner rings are labelled; tap any wedge for that
dog's details. Pedigree-collapse dogs keep their stable hue, and tapping one
lights up every wedge of that dog. The existing zoom applies to the fan too.

Render dispatch is factored into renderPedigree(); the collapse-highlight
now works on any element (tree card or fan wedge) carrying a data-dogkey.
2026-07-26 11:13:16 +00:00
Alexander Heldt a2c9aa9716 Add a collapse/expand-all toggle to the pedigree
A header button folds the whole tree down to just the dog or opens every
branch at once, alongside the per-dog toggles. Grouped with the zoom
controls, which the header now wraps on narrow screens.
2026-07-26 10:50:12 +00:00
Alexander Heldt 12a5bd0548 Make the pedigree tree zoomable
Add zoom to the pedigree: −/reset/+ buttons in the header, ctrl/⌘ + wheel,
and two-finger pinch. Scaling uses the CSS `zoom` property (not transform)
so the container reflows and every part stays reachable by scrolling at any
level. Clamped to 40–160% and the level is remembered per device.
2026-07-26 10:49:54 +00:00
Alexander Heldt 01d64b682b Flag pedigree collapse with repeat badges
When a dog fills more than one position in the pedigree (pedigree collapse),
mark each copy with a ×N badge and a stable per-dog colour, and let tapping
any copy highlight every place that dog appears. Identity is the registration
number (falling back to name), so the same ancestor at different positions is
treated as one. The summary line also reports how many ancestors recur.
2026-07-26 10:39:51 +00:00
Alexander Heldt 8157e95066 Render the pedigree top-down as a family tree
Replace the indented ancestry list with a top-down chart: the dog on top,
sire (left) and dam (right) branching below, connected by lines drawn with
each node's CSS ::before/::after (a nested <ul>/<li> tree). It shows three
generations by default and each dog expands to trace the line further back;
deeper levels get wide, so the view scrolls horizontally.
2026-07-26 10:39:28 +00:00
Alexander Heldt 86e51bb851 Make the pedigree id sticky across profile sync
The dog id in the synced profile shares one last-write-wins timestamp with
name and birthday, and that timestamp comes from each device's own clock.
A device whose profile was stamped later (clock skew, or a more recent
name/birthday edit) would refuse to adopt a newer server profile that had
just gained an id, or even push its empty id back over the stored one — so
the pedigree id set on one device never reached the others.

Make the id sticky on both sides of sync: an empty value never clears a set
one, and a device/server adopts an id it is missing regardless of the blob
timestamp. When both sides have an id, the newer profile still wins, so the
dog can still be changed. Name and birthday keep plain last-write-wins.
2026-07-26 10:19:01 +00:00
Alexander Heldt c2f74e64c8 Gate pedigree behind a dog id set in settings
The pedigree view is now opt-in and tied to your own dog rather than an
always-present free-text search. Add the dog's SKK chip or registration
number in Settings (it rides the synced profile alongside name and
birthday); the 🌳 button stays hidden until one is set, then opens the
page and loads that dog's ancestry directly.

Make repeat opens cheap: memoise the id->hundid resolution server-side so
a cached tree is served without contacting SKK at all, and mirror the
finished tree in localStorage so the page paints instantly and shows the
last-known tree offline.

Adds config.pedigree_id (with an in-place migration for existing DBs).
2026-07-26 09:36:49 +00:00
Alexander Heldt 26ebe3bd86 Add pedigree lookup and ancestry tree page
New 🌳 Pedigree view: enter a dog's ISO chip or SKK registration number
and see its ancestry rendered as a tree. SKK has no public API, so the
server drives SKK Hunddata like a browser: it resolves the input to an
internal hundid via the Hund_sok.aspx/HundData page-method, renders 7
generations per pedigree page, parses the rowspan grid into ahnentafel
positions, and follows each generation's leaves deeper by reading their
hundid out of the __doPostBack response viewstate.

A lookup returns the first 7 generations immediately and crawls deeper in
the background; the client polls and fills the tree in as ancestors
arrive. Finished trees are cached per dog in a new pedigree_cache table
(pedigrees don't change), so a dog is crawled once and repeats are instant.
The endpoints sit behind auth like the rest of /api/*, and the crawl is
kept polite (warmed session, delay between requests, one coalesced job per
dog, hard caps).
2026-07-26 09:22:14 +00:00
Alexander Heldt 374e630d8f Show the age counter as weeks with a months breakdown
Weeks and calendar months disagreed at a glance ("16 weeks" but only
"3 months"). Now the counter reads "16 weeks (3 months and 3 weeks)
old" so the two units line up, and drops the weeks past 4 months to
show just the months form.
2026-07-24 15:17:09 +00:00
Alexander Heldt 22a5ea76aa Make the Sleep trend chart follow the selected day
The curves were always computed relative to today regardless of the day
picker. Anchor them to selectedDay() instead: a past day shows its full
24h curve against the day before it and the average of the days leading
up to it, with no now-cap and no projection. Legend and tooltip labels
show the actual dates when viewing a past day.
2026-07-23 08:45:26 +00:00
Alexander Heldt 0ebaa11c93 Stretch the Sleep trend y-axis above 10h
The interesting detail sits near the goal, in the upper teens of hours,
so the scale is piecewise: 0–10h shares a compressed 26% of the height
with 2h gridlines, and everything above gets the rest with 1h
gridlines. Falls back to linear while the axis is too short to split.
The caption notes the stretched axis.
2026-07-15 19:06:16 +00:00
Alexander Heldt 897311465c Show the age-based sleep goal as a band in the Sleep trend chart
The puppy's age (from the configured birthday) picks the daily goal —
0–8 weeks 20–22h, 8–16 weeks 18–20h, 16–18h to 6 months, 14–16h to 12
months — drawn as a shaded band behind the curves, with a legend chip
naming the range. The Projected chip gains a ✓/▽ marker for whether
today's projection reaches the goal's lower bound, and the y-axis
always extends to cover the band. No birthday (or an adult dog) means
no band, unchanged from before.
2026-07-15 17:35:55 +00:00
Alexander Heldt 8fe8f9d417 Log training sessions onto the selected day, not always today
The Log button stamps the selected day at the current time of day, so a
forgotten session can be back-filled from that day's view. The snackbar
says which day it landed on when it isn't today; Undo/Add note still
work on it.
2026-07-15 13:26:30 +00:00
Alexander Heldt c24d59e672 Make the Sleep trend yesterday line orange
Gray sank into the dashed grid lines; --eat orange stands apart from
today's blue and the average's teal in both themes.
2026-07-15 13:24:55 +00:00
Alexander Heldt a1a6ec8720 Give the Sleep trend average line its own color
All three blue lines were hard to tell apart; the N-day average is now
teal (the --weight token) and slightly more opaque, while the projected
tail stays blue on purpose — it continues today's line.
2026-07-15 13:18:42 +00:00
Alexander Heldt 9b6ee20b07 Don't scroll to the history when a chart day is tapped
Selecting the day (and the new selected-day highlight) is enough;
the scroll jump lost your place in the charts.
2026-07-15 12:48:23 +00:00
Alexander Heldt 3e3eee678e Show a meal's grams in the history list
Same pattern as weigh-ins: "80 g · note" or just "80 g" when there's
no note.
2026-07-15 12:47:39 +00:00
Alexander Heldt 6d54ecf238 Label every 1h gridline on both sleep charts
Instead of thinning labels on dense axes, keep them all and drop the
label font to 7px past 12 steps (bars) / 16 steps (trend).
2026-07-15 12:45:53 +00:00
Alexander Heldt 83af641a12 Use 1-hour gridlines on the daily Sleep bar chart
niceAxisSleepHours drops from 2-hour to 1-hour steps and is shared with
the trend chart again (the trend-only helper it duplicated is gone).
Labels thin to every other gridline past 12 steps — this chart's plot
area is shorter than the trend's.
2026-07-15 10:56:16 +00:00
Alexander Heldt ba6e2c5e7d Make the Sleep trend chart taller with a finer 1-hour y-axis
220px viewBox (was 160) and 1-hour gridlines via a trend-specific axis
helper, so curves that run close together separate visually. Labels
drop to every other gridline past 16 steps to keep the text readable.
2026-07-15 10:49:27 +00:00
Alexander Heldt 0e24ac989d Show each curve's slept hours in the Sleep trend legend
Today, Yesterday and the N-day average chips now carry their totals
(e.g. "Yesterday 12.8h"), matching the projected chip.
2026-07-15 10:43:22 +00:00
Alexander Heldt ab0e51108c Project today's end-of-day sleep total on the Sleep trend chart
A dashed tail continues today's line from now to midnight by adding the
increments the N-day average curve makes over the same stretch, so the
projection follows the usual daily rhythm instead of extrapolating the
current rate (which overshoots right after a long night). The legend
shows the projected total; with no history there's no average and no
projection.
2026-07-15 10:36:22 +00:00
Alexander Heldt cebe923d68 Highlight the selected day in the per-day charts
A soft accent band behind the selected day's bars/cells (sleep, counts,
food, training heatmap) — visible even when the day's values are zero —
plus an accent-colored day label, and an accent ring on the selected
row of the sleep timeline. The band tracks the day picker, so tapping
into a chart immediately shows which slice you landed on.
2026-07-15 10:24:48 +00:00
Alexander Heldt 8dc4fca4e2 Add a Sleep trend chart: cumulative sleep today vs yesterday and the recent average
Answers "is the puppy behind on sleep right now?": cumulative hours
slept sampled at each hour boundary, today's line ending at the current
moment, with yesterday and the mean of the last N days as reference
curves. N follows the 7/14/30 chart-days picker, and days with no sleep
logged are skipped so a young log doesn't drag the average down.
2026-07-15 10:18:08 +00:00
Alexander Heldt b030cfb72a Dim quick actions that don't fit the current sleep state
Asleep: everything but Sleep end fades; awake: only Sleep end fades; no
sleep history: nothing. Buttons stay clickable — it's a visual nudge for
the thumb, not a lockout, so corrections still work.
2026-07-15 10:17:20 +00:00
Alexander Heldt 7cb59a7a23 Focus a text field when the edit dialog opens, never the date input
showModal() with no explicit focus autofocuses the first control — the
date input — which on iOS pops the native calendar over the form. Focus
weight/grams/note per event type instead, like openNoteDialog does.
2026-07-15 10:16:56 +00:00
Alexander Heldt 131346a7c7 Hide dialog weight/grams fields on event types that don't use them
The JS already sets .hidden per type, but 'dialog label { display: block }'
outranks the UA [hidden] rule, so the fields rendered anyway. Add the
explicit [hidden] override, matching the pattern used elsewhere in the file.
2026-07-15 10:16:29 +00:00
Alexander Heldt b608dfc342 Show a compact year-less date in the day bar so it fits small iPhones
The native date input can't be told to drop the year, so a button face
shows e.g. "Jul 10" and the real input sits hidden behind it, still
holding the value and opening the native picker on tap.
2026-07-15 10:13:19 +00:00
Alexander Heldt cdd701f0b4 Bring back the big timer; the bar pill takes over on scroll
The big asleep/awake card returns below the frozen bar, and the bar
pill becomes its twin: both tick together, but the pill stays
visibility-hidden — slot reserved, so the bar never shifts — while the
card is on screen, appearing only once the card scrolls out of sight
(rAF-throttled scroll check against the bar's bottom edge).
2026-07-13 21:31:29 +00:00
Alexander Heldt 8981214e55 Fit the whole top bar on one row
Timer, day arrows, date picker and Today all share a single non-wrapping
row: the timer slims to 1rem, buttons and gaps tighten, arrows sit
around the picker, and a narrow-phone media query compacts further.
2026-07-13 21:26:07 +00:00
Alexander Heldt b6301156f9 Let the chart window be picked: 7, 14 or 30 days (default 7)
A 7d/14d/30d picker in the charts card sets how many days every
rolling chart covers — daily bars, sleep timeline, hour heatmap and
training consistency grid. The choice is stored per device like the
theme; headers show the current window, day labels thin out and bar
gaps tighten as the window widens, and the sleep timeline grows rows
to fit.
2026-07-13 21:20:31 +00:00
Alexander Heldt 6b12820592 Pin the timer left in the day bar with the slack before the day controls 2026-07-13 20:56:12 +00:00
Alexander Heldt cee4455651 Make the food chart y-axis much finer
The grams axis now targets ~10 segments instead of ~4, so a 240 g day
gets 25 g gridlines; steps stay round numbers at any scale.
2026-07-13 20:52:48 +00:00
Alexander Heldt 695c030f33 Make the timer pill bigger and put it first in the day bar 2026-07-13 20:50:41 +00:00
Alexander Heldt a0e084dae8 Extend the daily charts from 7 to 14 days
Sleep, daily counts and food grams now share a 14-day window like the
pattern charts. Bar gaps tighten to fit 14 columns and the x-axis
labels today plus every second day so labels don't collide; tooltips
and click-through per bar are unchanged.
2026-07-13 20:45:22 +00:00
Alexander Heldt c103082ca5 Replace the big clock with a timer pill in the frozen day bar
The full-width asleep/awake card becomes a compact colored pill next to
the day controls: state emoji plus the live counter, with "since" moved
to the tooltip. One glance at the pinned bar now gives both the day and
the current state.
2026-07-13 20:40:01 +00:00
Alexander Heldt 0009e63d23 Freeze the day picker at the top of the page
The day bar moves above everything else and sticks while scrolling, so
switching days never requires scrolling back up. A fixed strip painted
over the safe-area inset keeps content from peeking through above the
stuck bar on notched phones in standalone mode.
2026-07-13 20:39:06 +00:00
Alexander Heldt a202f3e929 Support multiple photos per event
photoId now holds one or more photo UUIDs, comma-separated. The server
never interprets the field (photos are uploaded and served individually
by UUID), so no schema change is needed and legacy single-photo events
are already valid one-element lists.

Both dialogs let you keep adding photos, previewed as thumbnails with a
per-photo remove button; the file input allows multi-select and no
longer forces the camera, so the gallery is available too. History rows
show every photo, each opening in the lightbox.
2026-07-13 20:34:07 +00:00
11 changed files with 3101 additions and 214 deletions
+20
View File
@@ -94,6 +94,26 @@ events, profile and photos.
when you pass `-secure-cookies` (enable it behind a TLS proxy), so passwords when you pass `-secure-cookies` (enable it behind a TLS proxy), so passwords
aren't sent in the clear. aren't sent in the clear.
## Pedigree lookup
Set your dog's SKK chip or registration number in **Settings** (it rides the
synced profile, next to name and birthday). Once set, a 🌳 button appears that
opens a page rendering that dog's ancestry as a tree.
- SKK has no public API, so the server drives the interactive site the way a
browser would: it resolves the id to SKK's internal dog id, fetches the
pedigree page (7 generations per request), and follows each generation's leaves
deeper. A lookup returns the first generations immediately and keeps crawling in
the background; the client polls and fills the tree in as ancestors arrive.
- Because a deep crawl is dozens of sequential upstream requests, finished trees
are cached per dog in the `pedigree_cache` table (pedigrees don't change), and
the id→dog resolution is memoised, so a dog is only ever crawled once and repeat
opens hit SKK zero times. The client also mirrors the finished tree in
`localStorage`, so the page paints instantly and shows the last-known tree even
offline.
- The lookup is behind auth like the rest of `/api/*`; the first trace of a new
dog needs to reach SKK, but after that it works from cache (including offline).
## Use it on NixOS ## Use it on NixOS
In your system flake: In your system flake:
+1 -1
View File
@@ -26,7 +26,7 @@
pname = "puppy-tracker-server"; pname = "puppy-tracker-server";
version = "0.2.0"; version = "0.2.0";
src = ./server; src = ./server;
vendorHash = "sha256-z9Kf7i4WfLAHmceRi8T42+uMitjxEzr0pmOn+STpsAU="; vendorHash = "sha256-J1lYhwbaRh2PeAh3SzyB9WgUZa1gCNXBWdaJ5isUedA=";
# Pure-Go build for a tiny static binary. # Pure-Go build for a tiny static binary.
env.CGO_ENABLED = "0"; env.CGO_ENABLED = "0";
ldflags = [ "-s" "-w" ]; ldflags = [ "-s" "-w" ];
+1
View File
@@ -4,6 +4,7 @@ go 1.25.0
require ( require (
golang.org/x/crypto v0.54.0 golang.org/x/crypto v0.54.0
golang.org/x/net v0.57.0
modernc.org/sqlite v1.53.0 modernc.org/sqlite v1.53.0
) )
+2
View File
@@ -16,6 +16,8 @@ golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4= golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=
golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ= golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+102
View File
@@ -0,0 +1,102 @@
package main
// Small helpers over golang.org/x/net/html for walking the SKK pedigree markup.
import (
"strings"
"golang.org/x/net/html"
)
func attr(n *html.Node, key string) string {
for _, a := range n.Attr {
if a.Key == key {
return a.Val
}
}
return ""
}
// findByID returns the first element in the tree with the given id attribute.
func findByID(n *html.Node, id string) *html.Node {
if n.Type == html.ElementNode && attr(n, "id") == id {
return n
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if got := findByID(c, id); got != nil {
return got
}
}
return nil
}
// descendants returns every element with the given tag anywhere under n, in
// document order.
func descendants(n *html.Node, tag string) []*html.Node {
var out []*html.Node
var walk func(*html.Node)
walk = func(x *html.Node) {
for c := x.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && c.Data == tag {
out = append(out, c)
}
walk(c)
}
}
walk(n)
return out
}
// directChildElements returns the immediate element children of n with the tag.
func directChildElements(n *html.Node, tag string) []*html.Node {
var out []*html.Node
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && c.Data == tag {
out = append(out, c)
}
}
return out
}
// findElement returns the first descendant element with the given tag.
func findElement(n *html.Node, tag string) *html.Node {
els := descendants(n, tag)
if len(els) == 0 {
return nil
}
return els[0]
}
// text concatenates all text under n.
func text(n *html.Node) string {
var sb strings.Builder
var walk func(*html.Node)
walk = func(x *html.Node) {
if x.Type == html.TextNode {
sb.WriteString(x.Data)
}
for c := x.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(n)
return sb.String()
}
// normalizeText trims and collapses internal whitespace.
func normalizeText(s string) string {
return strings.TrimSpace(wsRE.ReplaceAllString(s, " "))
}
// findBoldSpan returns the normalized text of the first bold <span> (how subject
// cells carry the registration number), or "".
func findBoldSpan(n *html.Node) string {
for _, sp := range descendants(n, "span") {
if strings.Contains(strings.ReplaceAll(attr(sp, "style"), " ", ""), "font-weight:bold") {
if t := normalizeText(text(sp)); t != "" {
return t
}
}
}
return ""
}
+75 -18
View File
@@ -28,9 +28,9 @@ type Event struct {
Type string `json:"type"` Type string `json:"type"`
At int64 `json:"at"` At int64 `json:"at"`
Note string `json:"note"` Note string `json:"note"`
PhotoID string `json:"photoId,omitempty"` PhotoID string `json:"photoId,omitempty"` // photo UUIDs, comma-separated (legacy events hold one)
Weight float64 `json:"weight,omitempty"` // kilograms, for "weight" events Weight float64 `json:"weight,omitempty"` // kilograms, for "weight" events
Grams float64 `json:"grams,omitempty"` // food eaten, for "eat" events Grams float64 `json:"grams,omitempty"` // food eaten, for "eat" events
ExerciseID string `json:"exerciseId,omitempty"` // for "training" events ExerciseID string `json:"exerciseId,omitempty"` // for "training" events
UpdatedAt int64 `json:"updatedAt"` UpdatedAt int64 `json:"updatedAt"`
Deleted bool `json:"deleted,omitempty"` Deleted bool `json:"deleted,omitempty"`
@@ -60,9 +60,12 @@ func validBirthday(s string) bool { return s == "" || birthdayRE.MatchString(s)
// every client sees the same values without configuring each device. UpdatedAt // every client sees the same values without configuring each device. UpdatedAt
// drives last-write-wins, mirroring how events sync. // drives last-write-wins, mirroring how events sync.
type Config struct { type Config struct {
Name string `json:"name"` Name string `json:"name"`
Birthday string `json:"birthday"` Birthday string `json:"birthday"`
UpdatedAt int64 `json:"updatedAt"` // 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"`
} }
type ConfigStore struct { type ConfigStore struct {
@@ -78,8 +81,8 @@ func (cs *ConfigStore) get(userID string) Config {
// One profile row per user. A missing row is the pre-configuration state, // One profile row per user. A missing row is the pre-configuration state,
// so a zero-value Config is the right answer. // so a zero-value Config is the right answer.
err := cs.db.QueryRow( err := cs.db.QueryRow(
`SELECT name, birthday, updated FROM config WHERE user_id = ?`, userID, `SELECT name, birthday, pedigree_id, updated FROM config WHERE user_id = ?`, userID,
).Scan(&c.Name, &c.Birthday, &c.UpdatedAt) ).Scan(&c.Name, &c.Birthday, &c.PedigreeID, &c.UpdatedAt)
if err != nil && !errors.Is(err, sql.ErrNoRows) { if err != nil && !errors.Is(err, sql.ErrNoRows) {
log.Printf("config get: %v", err) log.Printf("config get: %v", err)
} }
@@ -89,18 +92,32 @@ func (cs *ConfigStore) get(userID string) Config {
// merge applies an incoming config for one user with last-write-wins by // 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). // UpdatedAt and returns the resulting stored config (which the caller sends back).
func (cs *ConfigStore) merge(userID string, in Config) (Config, error) { func (cs *ConfigStore) merge(userID string, in Config) (Config, error) {
// The upsert's WHERE clause enforces last-write-wins: the incoming row only // Name/birthday/updated are last-write-wins: the incoming row replaces the
// replaces the stored one when it is strictly newer. // 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(` _, err := cs.db.Exec(`
INSERT INTO config (user_id, name, birthday, updated) INSERT INTO config (user_id, name, birthday, pedigree_id, updated)
VALUES (?, ?, ?, ?) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET ON CONFLICT(user_id) DO UPDATE SET
name = excluded.name, birthday = excluded.birthday, updated = excluded.updated name = excluded.name, birthday = excluded.birthday,
pedigree_id = CASE WHEN excluded.pedigree_id != '' THEN excluded.pedigree_id ELSE config.pedigree_id END,
updated = excluded.updated
WHERE excluded.updated > config.updated`, WHERE excluded.updated > config.updated`,
userID, in.Name, in.Birthday, in.UpdatedAt) userID, in.Name, in.Birthday, in.PedigreeID, in.UpdatedAt)
if err != nil { if err != nil {
return Config{}, err return Config{}, err
} }
// Adopt a pedigree id the server is missing even from an older-stamped profile,
// so a device that set it isn't blocked by another device's newer name/birthday
// edit. (A set id is only ever changed by a newer profile that also sets one.)
if in.PedigreeID != "" {
if _, err := cs.db.Exec(
`UPDATE config SET pedigree_id = ? WHERE user_id = ? AND pedigree_id = ''`,
in.PedigreeID, userID); err != nil {
return Config{}, err
}
}
return cs.get(userID), nil return cs.get(userID), nil
} }
@@ -295,10 +312,11 @@ func openDB(path string) (*sql.DB, error) {
); );
CREATE INDEX IF NOT EXISTS idx_exercises_user ON exercises(user_id); CREATE INDEX IF NOT EXISTS idx_exercises_user ON exercises(user_id);
CREATE TABLE IF NOT EXISTS config ( CREATE TABLE IF NOT EXISTS config (
user_id TEXT PRIMARY KEY, user_id TEXT PRIMARY KEY,
name TEXT NOT NULL DEFAULT '', name TEXT NOT NULL DEFAULT '',
birthday TEXT NOT NULL DEFAULT '', birthday TEXT NOT NULL DEFAULT '',
updated INTEGER NOT NULL DEFAULT 0 pedigree_id TEXT NOT NULL DEFAULT '',
updated INTEGER NOT NULL DEFAULT 0
); );
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
@@ -311,6 +329,13 @@ func openDB(path string) (*sql.DB, error) {
user_id TEXT NOT NULL, user_id TEXT NOT NULL,
created INTEGER NOT NULL, created INTEGER NOT NULL,
expires INTEGER NOT NULL expires INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS pedigree_cache (
hundid TEXT PRIMARY KEY,
subject TEXT NOT NULL DEFAULT '',
nodes TEXT NOT NULL DEFAULT '',
generations INTEGER NOT NULL DEFAULT 0,
fetched INTEGER NOT NULL DEFAULT 0
);` );`
if _, err := db.Exec(schema); err != nil { if _, err := db.Exec(schema); err != nil {
db.Close() db.Close()
@@ -384,6 +409,15 @@ func migrateSchema(db *sql.DB) error {
} }
} }
} }
hasPedigree, err := columnExists(db, "config", "pedigree_id")
if err != nil {
return err
}
if !hasPedigree {
if _, err := db.Exec(`ALTER TABLE config ADD COLUMN pedigree_id TEXT NOT NULL DEFAULT ''`); err != nil {
return err
}
}
return nil return nil
} }
@@ -600,6 +634,7 @@ func main() {
store := newStore(db) store := newStore(db)
configStore := newConfigStore(db) configStore := newConfigStore(db)
exerciseStore := newExerciseStore(db) exerciseStore := newExerciseStore(db)
pedigrees := newPedManager(db)
photosDir := filepath.Join(filepath.Dir(*dataPath), "photos") photosDir := filepath.Join(filepath.Dir(*dataPath), "photos")
if err := os.MkdirAll(photosDir, 0o755); err != nil { if err := os.MkdirAll(photosDir, 0o755); err != nil {
@@ -695,6 +730,10 @@ func main() {
if len(in.Name) > 100 { if len(in.Name) > 100 {
in.Name = in.Name[:100] in.Name = in.Name[:100]
} }
in.PedigreeID = strings.TrimSpace(in.PedigreeID)
if len(in.PedigreeID) > 64 {
in.PedigreeID = in.PedigreeID[:64]
}
if !validBirthday(in.Birthday) { if !validBirthday(in.Birthday) {
http.Error(w, "invalid birthday (want YYYY-MM-DD)", http.StatusBadRequest) http.Error(w, "invalid birthday (want YYYY-MM-DD)", http.StatusBadRequest)
return return
@@ -711,6 +750,24 @@ func main() {
} }
})) }))
// POST /api/pedigree — resolve a dog by chip / registration number / name and
// return its ancestry tree (immediately for the first generations, then a
// background crawl deepens it). GET /api/pedigree/status polls that crawl.
mux.HandleFunc("/api/pedigree", auth.requireUser(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
pedigrees.handleLookup(w, r)
}))
mux.HandleFunc("/api/pedigree/status", auth.requireUser(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
pedigrees.handleStatus(w, r)
}))
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok")) w.Write([]byte("ok"))
}) })
+912
View File
@@ -0,0 +1,912 @@
package main
// Pedigree lookup: resolve a dog by chip / registration number / name against
// SKK (Svenska Kennelklubben) HUNDDATA, then crawl its ancestry and expose it as
// an ahnentafel-positioned tree. SKK has no public API, so this scrapes the
// interactive ASP.NET WebForms app the same way a browser drives it:
//
// 1. Resolve — POST Hund_sok.aspx/HundData (a JSON page-method) → hundid.
// 2. Fetch — GET Hund_Stamtavla.aspx?hundid=X, then POST ddlGenerationer=7
// to render 7 generations in one page; parse its rowspan grid.
// 3. Deepen — each generation-7 leaf links via __doPostBack; POST that link
// and read the ancestor's hundid out of the response __VIEWSTATE,
// then recurse. BFS terminates when the ancestry runs out.
//
// A deep crawl is dozens of sequential requests, so a lookup returns the first
// 7 generations immediately and keeps crawling in the background; the finished
// tree is cached per hundid (pedigrees don't change) so a dog is crawled once.
import (
"bytes"
"context"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/net/html"
)
const (
skkBase = "https://hundar.skk.se/hunddata/"
skkUA = "Mozilla/5.0 (X11; Linux x86_64) puppy-tracker pedigree lookup"
skkDelay = 250 * time.Millisecond // politeness between upstream requests
crawlGens = 7 // generations SKK renders per page
maxCrawlPages = 400 // hard caps so a crawl can never run away
maxCrawlRequests = 3000
crawlDeadline = 5 * time.Minute
maxActiveJobs = 4 // concurrent background crawls, total
firstPageWait = 20 * time.Second
)
// pedNode is one dog at an ahnentafel position (1 = subject, sire = 2n, dam = 2n+1).
type pedNode struct {
Reg string `json:"reg,omitempty"`
Name string `json:"name,omitempty"`
Titles string `json:"titles,omitempty"`
Hundid string `json:"hundid,omitempty"`
}
// pedSubject is the looked-up dog's headline info, from the resolver row.
type pedSubject struct {
Hundid string `json:"hundid"`
Reg string `json:"reg"`
Name string `json:"name"`
Breed string `json:"breed"`
Chip string `json:"chip"`
Sex string `json:"sex,omitempty"`
}
// skkClient is a single browser-like session against SKK (cookie jar + UA).
type skkClient struct {
hc *http.Client
}
func newSKKClient() (*skkClient, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
return &skkClient{hc: &http.Client{Jar: jar, Timeout: 30 * time.Second}}, nil
}
func (c *skkClient) do(req *http.Request) (*http.Response, error) {
req.Header.Set("User-Agent", skkUA)
return c.hc.Do(req)
}
// warm establishes an ASP.NET session (SessionId + anti-XSRF cookies) that the
// resolver and pedigree pages both require.
func (c *skkClient) warm(ctx context.Context) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, skkBase+"Hund_sok.aspx", nil)
if err != nil {
return err
}
resp, err := c.do(req)
if err != nil {
return err
}
io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
return nil
}
// hundDataRow mirrors the fields the resolver page-method returns.
type hundDataRow struct {
Hundid string `json:"hundid"`
Regnr string `json:"Regnr"`
Hundnamn string `json:"hundnamn"`
Chipnr string `json:"chipnr"`
Rastext string `json:"rastext"`
Kon string `json:"Kon"`
IDnummer string `json:"IDnummer"`
Antal string `json:"Antal"`
IsError bool `json:"IsError"`
ErrorText string `json:"ErrorText"`
}
var digitsRE = regexp.MustCompile(`^\d+$`)
// resolve turns a user query (chip number, registration number, or name) into
// matching dogs. The field is chosen by shape: a long all-digit string is a
// chip; anything with a letter or slash is a registration number; otherwise a
// name search (which may return several rows to disambiguate).
func (c *skkClient) resolve(ctx context.Context, q string) ([]hundDataRow, error) {
body := map[string]string{
"txtRegnr": "", "txtIDnummer": "", "txtChipnr": "",
"txtHundnamn": "", "ddlRasIn": "", "ddlKon": "", "txtLicensnr": "",
}
switch {
case digitsRE.MatchString(q) && len(q) >= 10:
body["txtChipnr"] = q
case strings.ContainsAny(q, "/") || strings.IndexFunc(q, isLetter) >= 0:
body["txtRegnr"] = q
default:
body["txtHundnamn"] = q
}
buf, _ := json.Marshal(body)
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
skkBase+"Hund_sok.aspx/HundData", bytes.NewReader(buf))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json;charset=utf-8")
req.Header.Set("Referer", skkBase+"Hund_sok.aspx")
resp, err := c.do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("resolver HTTP %d", resp.StatusCode)
}
var wrap struct {
D []hundDataRow `json:"d"`
}
if err := json.Unmarshal(raw, &wrap); err != nil {
return nil, fmt.Errorf("resolver response: %w", err)
}
// SKK signals "no matches" (and other soft failures like a query needing more
// input) via a single IsError row rather than an HTTP error. Treat it as an
// empty result so the caller reports a clean "not found" instead of a 502.
if len(wrap.D) == 1 && wrap.D[0].IsError {
return nil, nil
}
return wrap.D, nil
}
func isLetter(r rune) bool {
return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
}
// fetchPage GETs a dog's pedigree then POSTs ddlGenerationer=7 (with titles on)
// to render 7 generations, returning that page's HTML. The returned HTML is used
// for both grid parsing and the __doPostBack calls that resolve its leaf dogs,
// so its hidden fields (viewstate / event validation) match its ctl ids.
func (c *skkClient) fetchPage(ctx context.Context, hundid string) (string, string, error) {
pageURL := skkBase + "Hund_Stamtavla.aspx?hundid=" + url.QueryEscape(hundid)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, pageURL, nil)
if err != nil {
return "", pageURL, err
}
req.Header.Set("Referer", skkBase+"Hund_sok.aspx")
resp, err := c.do(req)
if err != nil {
return "", pageURL, err
}
raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
resp.Body.Close()
if err != nil {
return "", pageURL, err
}
first := string(raw)
form := hiddenFields(first)
form.Set("ctl00$bodyContent$ddlGenerationer", strconv.Itoa(crawlGens))
form.Set("ctl00$bodyContent$ddlTitlar", "J")
form.Set("__EVENTTARGET", "ctl00$bodyContent$ddlGenerationer")
form.Set("__EVENTARGUMENT", "")
html7, err := c.postForm(ctx, pageURL, form)
if err != nil {
return "", pageURL, err
}
return html7, pageURL, nil
}
func (c *skkClient) postForm(ctx context.Context, pageURL string, form url.Values) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, pageURL,
strings.NewReader(form.Encode()))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Referer", pageURL)
resp, err := c.do(req)
if err != nil {
return "", err
}
raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
resp.Body.Close()
if err != nil {
return "", err
}
return string(raw), nil
}
var (
viewstateRE = regexp.MustCompile(`name="__VIEWSTATE" id="__VIEWSTATE" value="([^"]+)"`)
// The clicked dog's internal hundid, encoded in the response viewstate as the
// string "hundid", a type byte (\x05), a length byte, then ASCII digits.
vsHundidRE = regexp.MustCompile(`(?s)hundid\x05.(\d+)`)
)
// postbackHundid clicks an ancestor's __doPostBack link on the given page and
// recovers that ancestor's hundid from the response viewstate. The rendered
// pedigree table never re-roots on such a click, but the viewstate carries the
// clicked dog's id — which is exactly the handle needed to fetch its own page.
func (c *skkClient) postbackHundid(ctx context.Context, pageHTML, ctlid, pageURL string) (string, error) {
form := hiddenFields(pageHTML)
form.Set("ctl00$bodyContent$ddlGenerationer", strconv.Itoa(crawlGens))
form.Set("ctl00$bodyContent$ddlTitlar", "J")
form.Set("__EVENTTARGET", ctlid)
form.Set("__EVENTARGUMENT", "")
resp, err := c.postForm(ctx, pageURL, form)
if err != nil {
return "", err
}
m := viewstateRE.FindStringSubmatch(resp)
if m == nil {
return "", nil
}
dec := decodeB64(m[1])
mm := vsHundidRE.FindSubmatch(dec)
if mm == nil {
return "", nil
}
return string(mm[1]), nil
}
func decodeB64(s string) []byte {
if m := len(s) % 4; m != 0 {
s += strings.Repeat("=", 4-m)
}
b, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return nil
}
return b
}
// hiddenFields collects every <input type=hidden> on a page into a form value
// set, so an ASP.NET postback can echo back __VIEWSTATE / __EVENTVALIDATION etc.
func hiddenFields(pageHTML string) url.Values {
vals := url.Values{}
node, err := html.Parse(strings.NewReader(pageHTML))
if err != nil {
return vals
}
var walk func(*html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "input" {
var typ, name, val string
for _, a := range n.Attr {
switch a.Key {
case "type":
typ = a.Val
case "name":
name = a.Val
case "value":
val = a.Val
}
}
if typ == "hidden" && name != "" {
vals.Set(name, val)
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(node)
return vals
}
// gridCell is a parsed pedigree table cell.
type gridCell struct {
reg, name, titles, ctlid string
occupied bool
}
var doPostBackRE = regexp.MustCompile(`__doPostBack\('([^']+)'`)
var wsRE = regexp.MustCompile(`\s+`)
// parseGrid reconstructs the rowspan-based pedigree table into columns. Column c
// holds 2^c cells top-to-bottom; a cell's index within its column is its
// ahnentafel offset. Returns column index -> ordered cells.
func parseGrid(pageHTML string) map[int][]gridCell {
node, err := html.Parse(strings.NewReader(pageHTML))
if err != nil {
return nil
}
tbl := findByID(node, "bodyContent_tblStamtavla")
if tbl == nil {
return nil
}
occ := map[[2]int]bool{}
type placed struct {
r, c int
cell gridCell
}
var placedCells []placed
r := 0
for _, tr := range descendants(tbl, "tr") {
c := 0
for _, td := range directChildElements(tr, "td") {
for occ[[2]int{r, c}] {
c++
}
rs := 1
if v := attr(td, "rowspan"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
rs = n
}
}
for dr := 0; dr < rs; dr++ {
occ[[2]int{r + dr, c}] = true
}
placedCells = append(placedCells, placed{r, c, parseCell(td)})
c++
}
r++
}
byCol := map[int][]placed{}
for _, p := range placedCells {
byCol[p.c] = append(byCol[p.c], p)
}
out := map[int][]gridCell{}
for col, lst := range byCol {
sort.SliceStable(lst, func(i, j int) bool { return lst[i].r < lst[j].r })
cells := make([]gridCell, len(lst))
for i, p := range lst {
cells[i] = p.cell
}
out[col] = cells
}
return out
}
// parseCell extracts reg / name / titles / ctlid from one <td>, mirroring how
// SKK marks them up: a <a __doPostBack> holds the reg number (subject cells use
// a bold <span> instead), a <font> holds championship titles, and the last plain
// <span> holds the dog's name. "Uppgift saknas" placeholders are left unoccupied.
func parseCell(td *html.Node) gridCell {
var cell gridCell
if a := findElement(td, "a"); a != nil {
if href := attr(a, "href"); strings.Contains(href, "__doPostBack") {
cell.reg = normalizeText(text(a))
if m := doPostBackRE.FindStringSubmatch(html.UnescapeString(href)); m != nil {
cell.ctlid = m[1]
}
}
}
if f := findElement(td, "font"); f != nil {
cell.titles = normalizeText(text(f))
}
// Name: the last <span> whose text isn't the titles string. Subject cells put
// the reg in a leading bold span; if we found no link reg, adopt it.
for _, sp := range descendants(td, "span") {
t := normalizeText(text(sp))
if t == "" || t == cell.titles {
continue
}
cell.name = t
}
if cell.reg == "" {
if b := findBoldSpan(td); b != "" {
cell.reg = b
if cell.name == b {
cell.name = ""
}
}
}
if strings.EqualFold(cell.name, "Uppgift saknas") {
cell.name = ""
}
cell.occupied = cell.reg != "" || cell.name != ""
return cell
}
// crawlProgress is the mutable snapshot a running crawl publishes.
type crawlProgress struct {
Pages int
Distinct int
MaxGen int
Nodes map[string]pedNode
}
// crawl performs the breadth-first ancestry walk from a subject hundid, calling
// report after each page with a fresh snapshot. It places every dog at its global
// ahnentafel position and resolves each generation-7 leaf to a hundid to recurse.
func (c *skkClient) crawl(ctx context.Context, hundid string, report func(crawlProgress)) (map[string]pedNode, error) {
tree := map[string]pedNode{}
edges := map[string]string{} // subjectHundid|ctlid -> ancestor hundid
done := map[string]bool{}
type qitem struct {
hundid string
basePos uint64
}
queue := []qitem{{hundid, 1}}
pages, requests, maxGen := 0, 0, 0
snapshot := func() crawlProgress {
nodes := make(map[string]pedNode, len(tree))
for k, v := range tree {
nodes[k] = v
}
return crawlProgress{Pages: pages, Distinct: countDistinct(tree), MaxGen: maxGen, Nodes: nodes}
}
for len(queue) > 0 {
if err := ctx.Err(); err != nil {
return tree, err
}
if pages >= maxCrawlPages || requests >= maxCrawlRequests {
log.Printf("pedigree crawl %s: hit cap (pages=%d requests=%d)", hundid, pages, requests)
break
}
item := queue[0]
queue = queue[1:]
if done[item.hundid] {
continue
}
done[item.hundid] = true
time.Sleep(skkDelay)
pageHTML, pageURL, err := c.fetchPage(ctx, item.hundid)
requests += 2
if err != nil {
if pages == 0 {
return tree, err // couldn't even fetch the subject
}
log.Printf("pedigree crawl %s: fetch %s failed: %v", hundid, item.hundid, err)
continue
}
pages++
grid := parseGrid(pageHTML)
var frontier []struct {
gpos uint64
ctlid string
}
for col := 0; col <= crawlGens-1; col++ {
cells, ok := grid[col]
if !ok {
continue
}
for pos, cell := range cells {
if !cell.occupied {
continue
}
gpos := item.basePos*(1<<uint(col)) + uint64(pos)
key := strconv.FormatUint(gpos, 10)
node := tree[key]
node.Reg, node.Name, node.Titles = cell.reg, cell.name, cell.titles
if col == 0 {
node.Hundid = item.hundid
}
tree[key] = node
if g := bitsLen(gpos); g > maxGen {
maxGen = g
}
if col == crawlGens-1 && cell.ctlid != "" {
frontier = append(frontier, struct {
gpos uint64
ctlid string
}{gpos, cell.ctlid})
}
}
}
report(snapshot())
for _, f := range frontier {
if err := ctx.Err(); err != nil {
return tree, err
}
if requests >= maxCrawlRequests {
break
}
ekey := item.hundid + "|" + f.ctlid
hid, ok := edges[ekey]
if !ok {
time.Sleep(skkDelay)
hid, err = c.postbackHundid(ctx, pageHTML, f.ctlid, pageURL)
requests++
if err != nil {
continue
}
edges[ekey] = hid
}
if hid != "" {
key := strconv.FormatUint(f.gpos, 10)
node := tree[key]
node.Hundid = hid
tree[key] = node
queue = append(queue, qitem{hid, f.gpos})
}
}
}
report(snapshot())
return tree, nil
}
func bitsLen(x uint64) int {
n := 0
for x > 0 {
n++
x >>= 1
}
return n
}
// ---- job manager ---------------------------------------------------------
type jobState string
const (
jobRunning jobState = "running"
jobDone jobState = "done"
jobError jobState = "error"
)
type pedJob struct {
id string
hundid string
subject pedSubject
firstPage chan struct{} // closed once the subject's own page is parsed
mu sync.Mutex
state jobState
pages int
distinct int
maxGen int
nodes map[string]pedNode
errMsg string
}
func (j *pedJob) apply(p crawlProgress) {
j.mu.Lock()
j.pages, j.distinct, j.maxGen, j.nodes = p.Pages, p.Distinct, p.MaxGen, p.Nodes
j.mu.Unlock()
}
type pedManager struct {
db *sql.DB
mu sync.Mutex
jobs map[string]*pedJob // keyed by hundid (coalesces duplicate lookups)
resolveMu sync.Mutex
resolved map[string]string // query -> hundid, so a cache hit skips SKK entirely
}
func newPedManager(db *sql.DB) *pedManager {
return &pedManager{db: db, jobs: map[string]*pedJob{}, resolved: map[string]string{}}
}
func (m *pedManager) rememberResolve(q, hundid string) {
if q == "" || hundid == "" {
return
}
m.resolveMu.Lock()
m.resolved[q] = hundid
m.resolveMu.Unlock()
}
func (m *pedManager) resolvedHundid(q string) string {
m.resolveMu.Lock()
defer m.resolveMu.Unlock()
return m.resolved[q]
}
func (m *pedManager) activeCount() int {
n := 0
for _, j := range m.jobs {
j.mu.Lock()
if j.state == jobRunning {
n++
}
j.mu.Unlock()
}
return n
}
// startOrAttach returns the running/finished job for a hundid, or starts a new
// background crawl. The boolean reports whether a fresh job was created.
func (m *pedManager) startOrAttach(client *skkClient, subject pedSubject) (*pedJob, bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
if j, ok := m.jobs[subject.Hundid]; ok {
return j, false, nil
}
if m.activeCount() >= maxActiveJobs {
return nil, false, errors.New("busy: too many pedigree lookups in progress, try again shortly")
}
j := &pedJob{
id: subject.Hundid,
hundid: subject.Hundid,
subject: subject,
firstPage: make(chan struct{}),
state: jobRunning,
nodes: map[string]pedNode{},
}
m.jobs[subject.Hundid] = j
go m.run(client, j)
return j, true, nil
}
func (m *pedManager) run(client *skkClient, j *pedJob) {
ctx, cancel := context.WithTimeout(context.Background(), crawlDeadline)
defer cancel()
firstDone := false
report := func(p crawlProgress) {
j.apply(p)
if !firstDone && p.Pages >= 1 {
firstDone = true
close(j.firstPage)
}
}
nodes, err := client.crawl(ctx, j.hundid, report)
if !firstDone {
close(j.firstPage) // unblock waiters even if the very first fetch failed
}
j.mu.Lock()
if err != nil && len(nodes) == 0 {
j.state = jobError
j.errMsg = err.Error()
} else {
j.state = jobDone
}
j.mu.Unlock()
if len(nodes) > 0 {
m.persist(j.subject, nodes)
}
}
// snapshot copies a job's current public state under its lock.
func (j *pedJob) snapshot() (jobState, int, int, int, map[string]pedNode, string) {
j.mu.Lock()
defer j.mu.Unlock()
nodes := make(map[string]pedNode, len(j.nodes))
for k, v := range j.nodes {
nodes[k] = v
}
return j.state, j.pages, j.distinct, j.maxGen, nodes, j.errMsg
}
// ---- persistent cache ----------------------------------------------------
func (m *pedManager) persist(subject pedSubject, nodes map[string]pedNode) {
sj, _ := json.Marshal(subject)
nj, _ := json.Marshal(nodes)
_, err := m.db.Exec(`
INSERT INTO pedigree_cache (hundid, subject, nodes, generations, fetched)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(hundid) DO UPDATE SET
subject = excluded.subject, nodes = excluded.nodes,
generations = excluded.generations, fetched = excluded.fetched`,
subject.Hundid, string(sj), string(nj), maxGenerations(nodes), time.Now().UnixMilli())
if err != nil {
log.Printf("pedigree cache save %s: %v", subject.Hundid, err)
}
}
// cached returns a stored tree for a hundid, if present.
func (m *pedManager) cached(hundid string) (pedSubject, map[string]pedNode, bool) {
var sj, nj string
err := m.db.QueryRow(
`SELECT subject, nodes FROM pedigree_cache WHERE hundid = ?`, hundid,
).Scan(&sj, &nj)
if err != nil {
if !errors.Is(err, sql.ErrNoRows) {
log.Printf("pedigree cache get %s: %v", hundid, err)
}
return pedSubject{}, nil, false
}
var subject pedSubject
var nodes map[string]pedNode
json.Unmarshal([]byte(sj), &subject)
json.Unmarshal([]byte(nj), &nodes)
return subject, nodes, true
}
func maxGenerations(nodes map[string]pedNode) int {
max := 0
for k := range nodes {
if p, err := strconv.ParseUint(k, 10, 64); err == nil {
if g := bitsLen(p); g > max {
max = g
}
}
}
return max
}
// ---- HTTP handlers -------------------------------------------------------
type pedLookupResponse struct {
Status string `json:"status"` // done | running | choose
JobID string `json:"jobId,omitempty"`
Hundid string `json:"hundid,omitempty"`
Subject *pedSubject `json:"subject,omitempty"`
Generations int `json:"generations,omitempty"`
Nodes map[string]pedNode `json:"nodes,omitempty"`
Matches []hundDataRow `json:"matches,omitempty"`
}
func rowToSubject(r hundDataRow) pedSubject {
return pedSubject{
Hundid: r.Hundid,
Reg: strings.TrimSpace(r.Regnr),
Name: strings.TrimSpace(r.Hundnamn),
Breed: strings.TrimSpace(r.Rastext),
Chip: strings.TrimSpace(r.Chipnr),
Sex: strings.TrimSpace(r.Kon),
}
}
// handleLookup resolves a query and returns a cached tree, a disambiguation list,
// or an immediate 7-generation tree with a background job crawling deeper.
func (m *pedManager) handleLookup(w http.ResponseWriter, r *http.Request) {
var req struct {
Q string `json:"q"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 1<<16)).Decode(&req); err != nil {
http.Error(w, "bad json: "+err.Error(), http.StatusBadRequest)
return
}
q := strings.TrimSpace(req.Q)
if q == "" {
http.Error(w, "empty query", http.StatusBadRequest)
return
}
// Fast path: if we've resolved this query before and its tree is cached, serve
// it without contacting SKK at all (repeat opens of your own dog's pedigree).
if hundid := m.resolvedHundid(q); hundid != "" {
if subj, nodes, ok := m.cached(hundid); ok {
writeJSON(w, pedLookupResponse{
Status: "done", Hundid: subj.Hundid, Subject: &subj,
Generations: maxGenerations(nodes), Nodes: nodes,
})
return
}
}
client, err := newSKKClient()
if err != nil {
http.Error(w, "server error", http.StatusInternalServerError)
return
}
ctx := r.Context()
if err := client.warm(ctx); err != nil {
http.Error(w, "upstream unavailable", http.StatusBadGateway)
return
}
rows, err := client.resolve(ctx, q)
if err != nil {
http.Error(w, "lookup failed: "+err.Error(), http.StatusBadGateway)
return
}
rows = withHundid(rows)
switch {
case len(rows) == 0:
http.Error(w, "no dog found for "+q, http.StatusNotFound)
return
case len(rows) > 1:
writeJSON(w, pedLookupResponse{Status: "choose", Matches: rows})
return
}
subject := rowToSubject(rows[0])
m.rememberResolve(q, subject.Hundid)
if subj, nodes, ok := m.cached(subject.Hundid); ok {
writeJSON(w, pedLookupResponse{
Status: "done", Hundid: subj.Hundid, Subject: &subj,
Generations: maxGenerations(nodes), Nodes: nodes,
})
return
}
job, _, err := m.startOrAttach(client, subject)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
select {
case <-job.firstPage:
case <-time.After(firstPageWait):
case <-ctx.Done():
return
}
state, _, _, gen, nodes, msg := job.snapshot()
if state == jobError {
http.Error(w, "pedigree fetch failed: "+msg, http.StatusBadGateway)
return
}
status := "running"
if state == jobDone {
status = "done"
}
writeJSON(w, pedLookupResponse{
Status: status, JobID: job.id, Hundid: subject.Hundid,
Subject: &subject, Generations: gen, Nodes: nodes,
})
}
type pedStatusResponse struct {
Status string `json:"status"`
Pages int `json:"pages"`
Distinct int `json:"distinct"`
Generations int `json:"generations"`
Nodes map[string]pedNode `json:"nodes,omitempty"`
Error string `json:"error,omitempty"`
}
// handleStatus returns a running crawl's current partial tree so the client can
// fill the view in progressively, and the final tree when it finishes.
func (m *pedManager) handleStatus(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("job")
m.mu.Lock()
job := m.jobs[id]
m.mu.Unlock()
if job == nil {
// A finished job may have been evicted, but the cache still has the tree.
if _, nodes, ok := m.cached(id); ok {
writeJSON(w, pedStatusResponse{
Status: "done", Generations: maxGenerations(nodes),
Distinct: countDistinct(nodes), Nodes: nodes, Pages: 0,
})
return
}
http.Error(w, "unknown job", http.StatusNotFound)
return
}
state, pages, distinct, gen, nodes, msg := job.snapshot()
writeJSON(w, pedStatusResponse{
Status: string(state), Pages: pages, Distinct: distinct,
Generations: gen, Nodes: nodes, Error: msg,
})
}
// countDistinct counts unique ancestors, keyed by registration number (falling
// back to name). Pedigree collapse means one dog can fill many positions, so
// this is smaller than the number of occupied positions.
func countDistinct(nodes map[string]pedNode) int {
seen := map[string]bool{}
for _, n := range nodes {
k := n.Reg
if k == "" {
k = n.Name
}
if k != "" {
seen[k] = true
}
}
return len(seen)
}
func writeJSON(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(v)
}
// withHundid drops resolver rows lacking a usable hundid (defensive).
func withHundid(rows []hundDataRow) []hundDataRow {
out := rows[:0]
for _, r := range rows {
if strings.TrimSpace(r.Hundid) != "" {
out = append(out, r)
}
}
return out
}
+1332 -156
View File
File diff suppressed because it is too large Load Diff
+40
View File
@@ -1,4 +1,44 @@
[ [
{ "date": "2026-08-02", "text": "Added free-text notes: tap 📝 Note to jot down things that happened on a day — vaccinations, vet visits, milestones — with a date, optional photo, and any text. All your notes are collected in a new Notes section that stays visible whatever day you're viewing, so you can see at a glance when things like a tick vaccination were done" },
{ "date": "2026-08-02", "text": "The Daily counts chart now has Pees / Poos / Meals checkboxes so you can focus on just the metrics you care about — untick the rest to see, say, only poos; your choice is remembered" },
{ "date": "2026-08-01", "text": "Logging a pee or poo now sets off 💧/💩 fireworks that shoot up from the bottom of the screen — a little celebration you can switch off in Settings (and it honours a reduced-motion preference)" },
{ "date": "2026-08-01", "text": "Tidied the header on long names and ages — the name now truncates instead of shoving the buttons, and the age reads as a compact \"16 wk · 3 mo 3 wk\"; weight-log rows are a single line again (\"Aug 1 · 16 wk\")" },
{ "date": "2026-07-26", "text": "Added a fan-chart view of the pedigree (toggle it in the header): your dog at the centre with each generation fanning outward as a ring, so many generations fit at once without the tree sprawling sideways — tap a wedge for that dog, and repeated ancestors keep their colour" },
{ "date": "2026-07-26", "text": "Added a Collapse all / Expand all toggle to the pedigree, to fold the whole tree down to your dog or open every branch at once" },
{ "date": "2026-07-26", "text": "The pedigree is now zoomable — use the +/ buttons, ⌘/Ctrl-scroll, or pinch on a phone — to fit a wide tree on screen or zoom in for detail; your zoom level is remembered" },
{ "date": "2026-07-26", "text": "In the pedigree, a dog that fills more than one spot (pedigree collapse, common in a breed's older lines) now carries a ×N badge — tap it to highlight every place that dog appears in the tree" },
{ "date": "2026-07-26", "text": "The pedigree now reads top-down like a family tree — your dog on top with its sire and dam branching below — showing three generations at a glance, with each dog expandable to trace the line further back" },
{ "date": "2026-07-26", "text": "The pedigree ID set in Settings now syncs reliably to your other devices — it's no longer dropped when two devices' clocks disagree" },
{ "date": "2026-07-26", "text": "New 🌳 Pedigree page: add your dog's SKK chip or registration number in Settings to unlock it, then explore its ancestry as a tree — the first generations show at once and the line fills in further back as it's traced from SKK Hunddata. It's cached, so it reopens instantly and works offline" },
{ "date": "2026-07-24", "text": "The age counter reads \"16 weeks (3 months and 3 weeks) old\" so weeks and months line up; past 4 months it drops the weeks and shows just months (e.g. \"5 months and 2 weeks old\")" },
{ "date": "2026-07-17", "text": "The Sleep trend chart follows the selected day — pick a past day to see its full curve against the day before and the average leading up to it" },
{ "date": "2026-07-15", "text": "The Sleep trend y-axis is stretched above 10h, giving the hours around the sleep goal most of the chart" },
{ "date": "2026-07-15", "text": "The Sleep trend chart shows the sleep goal for your puppy's age as a shaded band — the projection chip gets a ✓ when today is on track" },
{ "date": "2026-07-15", "text": "Logging a training session while viewing another day puts it on that day (the snackbar tells you where it went)" },
{ "date": "2026-07-15", "text": "The Sleep trend yesterday line is orange instead of gray, which was hard to see" },
{ "date": "2026-07-15", "text": "The Sleep trend average line is teal now, so it doesn't blend in with today's blue line and its projection" },
{ "date": "2026-07-15", "text": "Tapping a day in a chart selects it without jumping down to the history" },
{ "date": "2026-07-15", "text": "Meals with an amount logged show their grams in the day's history" },
{ "date": "2026-07-15", "text": "Every 1-hour gridline on the sleep charts now shows its hour mark" },
{ "date": "2026-07-15", "text": "The Sleep chart in the last-N-days card now has 1-hour gridlines too" },
{ "date": "2026-07-15", "text": "The Sleep trend chart is taller with 1-hour gridlines, so nearby lines are easier to tell apart" },
{ "date": "2026-07-15", "text": "The Sleep trend legend shows the hours for each line — Today, Yesterday and the average, next to the projection" },
{ "date": "2026-07-15", "text": "The Sleep trend chart projects where today will land by midnight — a dashed tail continues today's line following the average day's rhythm" },
{ "date": "2026-07-15", "text": "The charts highlight the selected day, so it's easy to spot which bars, rows and cells you're looking at" },
{ "date": "2026-07-15", "text": "New Sleep trend chart: today's running sleep total through the day, against yesterday and the average over your chart window (7/14/30 days)" },
{ "date": "2026-07-15", "text": "Quick actions that don't fit right now are dimmed (asleep → everything but Sleep end; awake → Sleep end) — still tappable for corrections" },
{ "date": "2026-07-15", "text": "Editing an event no longer pops the date picker over the whole screen on iPhone" },
{ "date": "2026-07-15", "text": "Weight and amount fields no longer show up on events that don't use them (e.g. editing a pee)" },
{ "date": "2026-07-15", "text": "The date in the top bar is shorter (no year), so the whole bar fits on smaller iPhones" },
{ "date": "2026-07-13", "text": "The big timer is back at the top — scroll past it and it hops into the frozen bar instead" },
{ "date": "2026-07-13", "text": "The top bar fits on one row: timer, day arrows, date picker and Today" },
{ "date": "2026-07-13", "text": "Pick how many days the charts cover — 7, 14 or 30 (default 7)" },
{ "date": "2026-07-13", "text": "Much finer y-axis on the food chart" },
{ "date": "2026-07-13", "text": "The awake/asleep timer is bigger and sits first in the top bar" },
{ "date": "2026-07-13", "text": "The sleep, daily counts and food charts now cover the last 14 days instead of 7" },
{ "date": "2026-07-13", "text": "The awake/asleep timer lives in the frozen top bar" },
{ "date": "2026-07-13", "text": "The day picker is a bar frozen at the top of the page" },
{ "date": "2026-07-13", "text": "Attach multiple photos to an event — the photo picker now also offers the gallery with multi-select" },
{ "date": "2026-07-13", "text": "Track food by weight: logging a meal asks for grams (optional), with a daily total in the overview and a weekly chart" }, { "date": "2026-07-13", "text": "Track food by weight: logging a meal asks for grams (optional), with a daily total in the overview and a weekly chart" },
{ "date": "2026-07-12", "text": "Browse the full changelog from the bottom of the page" }, { "date": "2026-07-12", "text": "Browse the full changelog from the bottom of the page" },
{ "date": "2026-07-12", "text": "Finer-grained y-axis on the daily counts chart" }, { "date": "2026-07-12", "text": "Finer-grained y-axis on the daily counts chart" },
+106 -27
View File
@@ -70,6 +70,7 @@
<div id="puppy-age" class="puppy-age" hidden></div> <div id="puppy-age" class="puppy-age" hidden></div>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<button type="button" id="pedigree-btn" class="ghost icon-btn" aria-label="Pedigree" title="Pedigree" hidden>🌳</button>
<button type="button" id="settings-btn" class="ghost icon-btn" aria-label="Settings" title="Settings">⚙️</button> <button type="button" id="settings-btn" class="ghost icon-btn" aria-label="Settings" title="Settings">⚙️</button>
<button type="button" id="logout-btn" class="ghost icon-btn" aria-label="Log out" title="Log out">🚪</button> <button type="button" id="logout-btn" class="ghost icon-btn" aria-label="Log out" title="Log out">🚪</button>
<div id="online-status" class="status-pill"></div> <div id="online-status" class="status-pill"></div>
@@ -77,6 +78,26 @@
</header> </header>
<main> <main>
<section class="day-bar">
<!-- Compact twin of the big timer below: invisible (but keeping its
slot) while the big card is on screen, shown once it scrolls
away. Hidden entirely until a sleep event exists. -->
<div id="bar-clock" class="bar-clock" hidden>
<span id="bar-clock-icon" aria-hidden="true"></span>
<span id="bar-clock-time"></span>
</div>
<button type="button" id="day-prev" class="ghost" aria-label="Previous day"></button>
<!-- A browser won't let us shorten the text a native date input shows,
so the face button carries a compact year-less date and the real
input stays (visually hidden) as the value + native picker. -->
<span class="day-date">
<button type="button" id="day-date-face" class="ghost"></button>
<input type="date" id="day-picker" tabindex="-1" aria-hidden="true" />
</span>
<button type="button" id="day-next" class="ghost" aria-label="Next day"></button>
<button type="button" id="day-today" class="ghost">Today</button>
</section>
<section id="big-clock" class="big-clock" hidden> <section id="big-clock" class="big-clock" hidden>
<div class="bc-label" id="bc-label"></div> <div class="bc-label" id="bc-label"></div>
<div class="bc-time" id="bc-time">0:00</div> <div class="bc-time" id="bc-time">0:00</div>
@@ -92,6 +113,7 @@
<button class="action pee" data-type="pee">💧 Pee</button> <button class="action pee" data-type="pee">💧 Pee</button>
<button class="action poo" data-type="poo">💩 Poo</button> <button class="action poo" data-type="poo">💩 Poo</button>
<button class="action weight" data-type="weight">⚖️ Weigh-in</button> <button class="action weight" data-type="weight">⚖️ Weigh-in</button>
<button class="action note" data-type="note">📝 Note</button>
</div> </div>
</section> </section>
@@ -101,19 +123,12 @@
<p id="training-empty" class="empty">No exercises yet. Add one to start tracking training.</p> <p id="training-empty" class="empty">No exercises yet. Add one to start tracking training.</p>
<button type="button" id="exercise-add" class="ghost training-add">Add exercise</button> <button type="button" id="exercise-add" class="ghost training-add">Add exercise</button>
<div class="chart training-chart" id="training-chart-wrap" hidden> <div class="chart training-chart" id="training-chart-wrap" hidden>
<div class="chart-title">Consistency (last 14 days)</div> <div class="chart-title">Consistency <span data-chart-days-label>(last 7 days)</span></div>
<svg id="chart-training" class="chart-svg" viewBox="0 0 320 60" role="img" aria-label="Training sessions per exercise per day over the last 14 days"></svg> <svg id="chart-training" class="chart-svg" viewBox="0 0 320 60" role="img" aria-label="Training sessions per exercise per day"></svg>
<p class="muted-note">Darker = more sessions that day. Tap a cell to open that day.</p> <p class="muted-note">Darker = more sessions that day. Tap a cell to open that day.</p>
</div> </div>
</section> </section>
<section class="day-bar">
<button type="button" id="day-prev" class="ghost" aria-label="Previous day"></button>
<input type="date" id="day-picker" />
<button type="button" id="day-today" class="ghost">Today</button>
<button type="button" id="day-next" class="ghost" aria-label="Next day"></button>
</section>
<section class="overview" data-panel="overview"> <section class="overview" data-panel="overview">
<h2 id="overview-title">Today's overview</h2> <h2 id="overview-title">Today's overview</h2>
<div class="stats"> <div class="stats">
@@ -176,35 +191,53 @@
</section> </section>
<section class="weekly" data-panel="weekly"> <section class="weekly" data-panel="weekly">
<h2>Last 7 days</h2> <h2 id="daily-charts-title">Last 7 days</h2>
<div class="chart-days-picker" role="group" aria-label="How many days the charts cover">
<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>
</div>
<div class="chart"> <div class="chart">
<div class="chart-title">Sleep (hours)</div> <div class="chart-title">Sleep (hours)</div>
<svg id="chart-sleep" class="chart-svg" viewBox="0 0 320 160" role="img" aria-label="Sleep hours per day for the last 7 days"></svg> <svg id="chart-sleep" class="chart-svg" viewBox="0 0 320 160" role="img" aria-label="Sleep hours per day"></svg>
</div> </div>
<div class="chart"> <div class="chart">
<div class="chart-title">Daily counts</div> <div class="chart-title">Daily counts</div>
<svg id="chart-counts" class="chart-svg" viewBox="0 0 320 180" role="img" aria-label="Pee, poo and meal counts per day for the last 7 days"></svg> <svg id="chart-counts" class="chart-svg" viewBox="0 0 320 180" role="img" aria-label="Pee, poo and meal counts per day"></svg>
<div class="legend"> <div class="legend legend-toggle" id="counts-metrics" role="group" aria-label="Which counts to show">
<span class="lg pee"><span class="sw"></span>Pees</span> <label class="lg pee"><input type="checkbox" data-metric="pees" checked /><span class="sw"></span>Pees</label>
<span class="lg poo"><span class="sw"></span>Poos</span> <label class="lg poo"><input type="checkbox" data-metric="poos" checked /><span class="sw"></span>Poos</label>
<span class="lg eat"><span class="sw"></span>Meals</span> <label class="lg eat"><input type="checkbox" data-metric="meals" checked /><span class="sw"></span>Meals</label>
</div> </div>
</div> </div>
<div class="chart" id="grams-chart-wrap" hidden> <div class="chart" id="grams-chart-wrap" hidden>
<div class="chart-title">Food (grams)</div> <div class="chart-title">Food (grams)</div>
<svg id="chart-grams" class="chart-svg" viewBox="0 0 320 160" role="img" aria-label="Grams of food eaten per day for the last 7 days"></svg> <svg id="chart-grams" class="chart-svg" viewBox="0 0 320 160" role="img" aria-label="Grams of food eaten per day"></svg>
</div> </div>
</section> </section>
<section class="patterns" data-panel="sleep-timeline"> <section class="patterns" data-panel="sleep-timeline">
<h2><span id="sleep-timeline-title">When sleeping</span> <span class="muted-note">(last 14 days)</span></h2> <h2><span id="sleep-timeline-title">When sleeping</span> <span class="muted-note" data-chart-days-label>(last 7 days)</span></h2>
<svg id="chart-sleep-timeline" class="chart-svg" viewBox="0 0 320 228" role="img" aria-label="Sleep periods per day over the last 14 days"></svg> <svg id="chart-sleep-timeline" class="chart-svg" viewBox="0 0 320 125" role="img" aria-label="Sleep periods per day"></svg>
<p class="muted-note">Each row is a day, midnight to midnight; shaded = asleep. Tap a row to open that day.</p> <p class="muted-note">Each row is a day, midnight to midnight; shaded = asleep. Tap a row to open that day.</p>
</section> </section>
<section class="patterns" data-panel="sleep-trend">
<h2>Sleep trend</h2>
<svg id="chart-sleep-trend" class="chart-svg" viewBox="0 0 320 220" role="img" aria-label="Cumulative sleep hours through the selected day, the day before it, the recent average and (for today) the projected end-of-day total, with the age-based sleep goal band"></svg>
<div class="legend">
<span class="lg trend-today"><span class="sw"></span><span id="legend-trend-today-text">Today</span></span>
<span class="lg trend-projected" id="legend-trend-projected" hidden><span class="sw"></span><span id="legend-trend-projected-text">Projected</span></span>
<span class="lg trend-yesterday" id="legend-trend-yesterday"><span class="sw"></span><span id="legend-trend-yesterday-text">Yesterday</span></span>
<span class="lg trend-avg" id="legend-trend-avg"><span class="sw"></span><span id="legend-trend-avg-text">7-day avg</span></span>
<span class="lg trend-goal" id="legend-trend-goal" hidden><span class="sw"></span><span id="legend-trend-goal-text">Goal</span></span>
</div>
<p class="muted-note">Hours slept so far at each point of the day, against yesterday and the average over the picked chart window. The dashed tail continues today's line the way the average day usually plays out. The axis is stretched above 10h to give the hours around the goal more room.</p>
</section>
<section class="patterns" data-panel="hour-heatmap"> <section class="patterns" data-panel="hour-heatmap">
<h2>By hour of day <span class="muted-note">(last 14 days)</span></h2> <h2>By hour of day <span class="muted-note" data-chart-days-label>(last 7 days)</span></h2>
<svg id="chart-hour-heatmap" class="chart-svg" viewBox="0 0 320 120" role="img" aria-label="Pee, poo and meal frequency by hour of day over the last 14 days"></svg> <svg id="chart-hour-heatmap" class="chart-svg" viewBox="0 0 320 120" role="img" aria-label="Pee, poo and meal frequency by hour of day"></svg>
<p class="muted-note">Darker = happens more often at that hour.</p> <p class="muted-note">Darker = happens more often at that hour.</p>
</section> </section>
@@ -229,6 +262,12 @@
<p id="weight-empty" class="empty">No weigh-ins logged yet.</p> <p id="weight-empty" class="empty">No weigh-ins logged yet.</p>
</section> </section>
<section class="notes-log" data-panel="notes">
<h2>Notes</h2>
<ul id="notes-list" class="event-list"></ul>
<p id="notes-empty" class="empty">No notes yet. Use the 📝 Note button to jot down things like vaccinations or vet visits — they'll be listed here across every day.</p>
</section>
<section class="history" data-panel="history"> <section class="history" data-panel="history">
<h2>History</h2> <h2>History</h2>
<ul id="event-list" class="event-list"></ul> <ul id="event-list" class="event-list"></ul>
@@ -241,6 +280,39 @@
</footer> </footer>
</div><!-- /#app --> </div><!-- /#app -->
<!-- Pedigree lookup. A distinct full-screen view (hides #app while open)
that resolves a dog by chip / registration number / name against SKK
and renders its ancestry as a tree. Online-only. -->
<div id="pedigree-screen" class="pedigree-screen" hidden>
<header class="pedigree-header">
<button type="button" id="pedigree-back" class="ghost icon-btn" aria-label="Back to tracker" title="Back"></button>
<h1>🌳 Pedigree</h1>
<div class="ped-controls">
<button type="button" id="ped-view" class="ghost">Fan view</button>
<button type="button" id="ped-foldall" class="ghost">Collapse all</button>
<div class="ped-zoom" role="group" aria-label="Zoom">
<button type="button" id="ped-zoom-out" class="ghost icon-btn" aria-label="Zoom out" title="Zoom out"></button>
<button type="button" id="ped-zoom-reset" class="ghost" aria-label="Reset zoom" title="Reset zoom">100%</button>
<button type="button" id="ped-zoom-in" class="ghost icon-btn" aria-label="Zoom in" title="Zoom in">+</button>
</div>
</div>
</header>
<main class="pedigree-main">
<p class="muted-note pedigree-hint">
Your dog's ancestry from <strong>SKK Hunddata</strong>, traced from the
ID set in Settings. The first generations show at once, then the line
fills in further back.
<button type="button" id="pedigree-refresh" class="linklike">Refresh</button>
</p>
<p id="pedigree-status" class="pedigree-status" hidden></p>
<div id="pedigree-choose" class="pedigree-choose" hidden></div>
<div id="pedigree-subject" class="pedigree-subject" hidden></div>
<p id="pedigree-repeat-note" class="muted-note pedigree-repeat-note" hidden>Some ancestors appear in more than one place further back (pedigree collapse). Expand the tree to reveal their ×N badges, then tap one to highlight every spot that dog appears.</p>
<div id="pedigree-tree" class="pedigree-tree"></div>
<p id="pedigree-caption" class="pedigree-caption" hidden></p>
</main>
</div><!-- /#pedigree-screen -->
<dialog id="changelog-dialog"> <dialog id="changelog-dialog">
<form method="dialog" id="changelog-form"> <form method="dialog" id="changelog-form">
<h3>Changelog</h3> <h3>Changelog</h3>
@@ -261,10 +333,19 @@
<label>Birthday <label>Birthday
<input type="date" id="settings-birthday" /> <input type="date" id="settings-birthday" />
</label> </label>
<label>Pedigree ID
<input type="text" id="settings-pedigree" autocomplete="off" spellcheck="false"
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>
<label class="toggle-row"> <label class="toggle-row">
<span>Dark mode</span> <span>Dark mode</span>
<input type="checkbox" id="settings-theme" role="switch" class="switch" /> <input type="checkbox" id="settings-theme" role="switch" class="switch" />
</label> </label>
<label class="toggle-row">
<span>Pee/poo confetti 💩</span>
<input type="checkbox" id="settings-confetti" role="switch" class="switch" />
</label>
<menu> <menu>
<button value="cancel" class="ghost">Cancel</button> <button value="cancel" class="ghost">Cancel</button>
<button value="save" id="settings-save">Save</button> <button value="save" id="settings-save">Save</button>
@@ -332,9 +413,8 @@
<textarea id="note-input" rows="4" placeholder="e.g. pee was instant, poo took 5min, ate 300g raw food"></textarea> <textarea id="note-input" rows="4" placeholder="e.g. pee was instant, poo took 5min, ate 300g raw food"></textarea>
</label> </label>
<div class="photo-field"> <div class="photo-field">
<input type="file" id="note-photo-input" accept="image/*" capture="environment" hidden /> <input type="file" id="note-photo-input" accept="image/*" multiple hidden />
<button type="button" id="note-photo-btn" class="ghost">📷 Add photo</button> <button type="button" id="note-photo-btn" class="ghost">📷 Add photos</button>
<button type="button" id="note-photo-clear" class="ghost" hidden>Remove photo</button>
<div id="note-photo-preview" class="photo-preview" hidden></div> <div id="note-photo-preview" class="photo-preview" hidden></div>
</div> </div>
<menu> <menu>
@@ -363,9 +443,8 @@
<textarea id="edit-note" rows="4"></textarea> <textarea id="edit-note" rows="4"></textarea>
</label> </label>
<div class="photo-field"> <div class="photo-field">
<input type="file" id="edit-photo-input" accept="image/*" capture="environment" hidden /> <input type="file" id="edit-photo-input" accept="image/*" multiple hidden />
<button type="button" id="edit-photo-btn" class="ghost">📷 Add photo</button> <button type="button" id="edit-photo-btn" class="ghost">📷 Add photos</button>
<button type="button" id="edit-photo-clear" class="ghost" hidden>Remove photo</button>
<div id="edit-photo-preview" class="photo-preview" hidden></div> <div id="edit-photo-preview" class="photo-preview" hidden></div>
</div> </div>
<menu> <menu>
+510 -12
View File
@@ -11,6 +11,7 @@
--poo: #8a5a3b; --poo: #8a5a3b;
--weight: #2bb3a3; --weight: #2bb3a3;
--training: #b04ecf; --training: #b04ecf;
--note: #6f7a90;
--danger: #d64545; --danger: #d64545;
--gain: #2e9e5b; --gain: #2e9e5b;
--border: #e9e6f5; --border: #e9e6f5;
@@ -78,13 +79,24 @@ h1 {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 2px; gap: 2px;
flex: 1 1 auto;
min-width: 0; min-width: 0;
} }
/* Truncate the name so a long one never runs into the action buttons. Scoped to
the header title so the auth-screen heading is unaffected. */
#app-title {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.puppy-age { .puppy-age {
font-size: 0.8rem; font-size: 0.8rem;
color: var(--muted); color: var(--muted);
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
/* One line in the common case; on a very narrow screen it wraps rather than
truncating, so the age is never cut off. The name (#app-title) is what
truncates to keep the buttons clear. */
} }
.header-actions { .header-actions {
@@ -122,30 +134,85 @@ section {
padding: 16px; padding: 16px;
} }
.big-clock { /* Paints over the notch/status-bar strip so content scrolling behind the
text-align: center; sticky day bar never peeks through above it. Zero-height where there is no
padding: 24px 16px; safe-area inset. */
body::before {
content: "";
position: fixed;
top: 0;
left: 0;
right: 0;
height: env(safe-area-inset-top, 0px);
background: var(--bg);
z-index: 65;
} }
.day-bar { .day-bar {
position: sticky;
top: env(safe-area-inset-top, 0px);
z-index: 60;
display: flex; display: flex;
gap: 8px; gap: 6px;
align-items: center; align-items: center;
justify-content: flex-end;
flex-wrap: nowrap;
padding: 8px 10px; padding: 8px 10px;
} }
.day-bar input[type="date"] { /* The face button shows the short date; the real input sits invisibly behind
flex: 1; it so its native picker still anchors here (and .showPicker() has a target). */
min-width: 0; .day-date {
position: relative;
flex-shrink: 0;
display: inline-flex;
}
.day-date input[type="date"] {
position: absolute;
inset: 0;
width: 100%;
opacity: 0;
pointer-events: none;
}
#day-date-face {
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
white-space: nowrap;
} }
.day-bar button { .day-bar button {
padding: 8px 14px; padding: 8px 10px;
flex-shrink: 0; flex-shrink: 0;
} }
/* Keep the single row intact on narrow phones. */
@media (max-width: 370px) {
.day-bar { gap: 4px; }
.day-bar button { padding: 8px 7px; }
.bar-clock { font-size: 0.9rem; padding: 6px 8px; gap: 5px; }
}
.day-bar button:disabled { .day-bar button:disabled {
opacity: 0.4; opacity: 0.4;
cursor: not-allowed; cursor: not-allowed;
} }
.bar-clock {
display: flex;
align-items: center;
gap: 6px;
margin-right: auto; /* pin left; the flexible gap sits between it and the day controls */
padding: 7px 10px;
border-radius: 999px;
font-weight: 700;
font-size: 1rem;
font-variant-numeric: tabular-nums;
flex-shrink: 0;
}
.bar-clock[hidden] { display: none; }
/* Big timer still on screen: keep the pill's slot but show nothing. */
.bar-clock.standby { visibility: hidden; }
.bar-clock.asleep { background: color-mix(in srgb, var(--sleep) 18%, var(--surface)); color: var(--sleep); }
.bar-clock.awake { background: color-mix(in srgb, var(--accent) 18%, var(--surface)); color: var(--accent); }
.big-clock {
text-align: center;
padding: 24px 16px;
}
.big-clock .bc-label { .big-clock .bc-label {
font-size: 0.8rem; font-size: 0.8rem;
text-transform: uppercase; text-transform: uppercase;
@@ -200,6 +267,10 @@ button.action.eat { background: var(--eat); }
button.action.pee { background: var(--pee); color: #2b240a; } button.action.pee { background: var(--pee); color: #2b240a; }
button.action.poo { background: var(--poo); } button.action.poo { background: var(--poo); }
button.action.weight { background: var(--weight); } button.action.weight { background: var(--weight); }
button.action.note { background: var(--note); }
/* Unlikely given the current sleep state (see renderActionHints) dimmed
but fully tappable, so corrections are never blocked. */
button.action.unlikely { opacity: 0.4; }
button.ghost { button.ghost {
background: transparent; background: transparent;
@@ -266,6 +337,7 @@ button.danger { background: var(--danger); }
font-weight: normal; font-weight: normal;
} }
.timing-hint { margin: 10px 4px 0; line-height: 1.4; } .timing-hint { margin: 10px 4px 0; line-height: 1.4; }
.settings-hint { color: var(--muted); font-size: 0.8rem; margin: -4px 0 4px; line-height: 1.4; }
.history-controls { .history-controls {
display: flex; display: flex;
@@ -365,11 +437,16 @@ textarea { resize: vertical; }
.event[data-type="poo"] .dot { background: var(--poo); } .event[data-type="poo"] .dot { background: var(--poo); }
.event[data-type="weight"] .dot { background: var(--weight); } .event[data-type="weight"] .dot { background: var(--weight); }
.event[data-type="training"] .dot { background: var(--training); } .event[data-type="training"] .dot { background: var(--training); }
.event[data-type="note"] .dot { background: var(--note); }
.event .time { font-variant-numeric: tabular-nums; color: var(--muted); min-width: 60px; } .event .time { font-variant-numeric: tabular-nums; color: var(--muted); min-width: 60px; }
.event .label { font-weight: 600; min-width: 110px; } .event .label { font-weight: 600; min-width: 110px; }
.event .note { color: var(--muted); font-size: 0.9rem; flex: 1; } .event .note { color: var(--muted); font-size: 0.9rem; flex: 1; }
/* Notes log rows: a date instead of a time-of-day, then the note text. */
.event .note-date { font-weight: 600; white-space: nowrap; font-variant-numeric: tabular-nums; }
.event .note-text { flex: 1; white-space: pre-wrap; overflow-wrap: anywhere; }
.empty { .empty {
color: var(--muted); color: var(--muted);
text-align: center; text-align: center;
@@ -411,6 +488,9 @@ dialog::backdrop { background: rgba(0,0,0,0.4); }
dialog h3 { margin: 0 0 12px; } dialog h3 { margin: 0 0 12px; }
dialog label { display: block; font-size: 0.85rem; color: var(--muted); margin-bottom: 10px; } dialog label { display: block; font-size: 0.85rem; color: var(--muted); margin-bottom: 10px; }
/* The display rule above beats the UA [hidden] rule, so hide explicitly
otherwise the weight/grams fields show on event types that don't use them. */
dialog label[hidden] { display: none; }
dialog label input, dialog label textarea { margin-top: 4px; } dialog label input, dialog label textarea { margin-top: 4px; }
dialog menu { dialog menu {
@@ -432,13 +512,33 @@ dialog menu {
.photo-preview { .photo-preview {
margin-top: 8px; margin-top: 8px;
width: 100%; width: 100%;
display: flex;
flex-wrap: wrap;
gap: 10px;
} }
.photo-preview img { .photo-preview[hidden] { display: none; }
.photo-thumb { position: relative; }
.photo-thumb img {
display: block; display: block;
max-width: 100%; width: 76px;
max-height: 240px; height: 76px;
object-fit: cover;
border-radius: 8px; border-radius: 8px;
border: 1px solid var(--border); border: 1px solid var(--border);
background: var(--accent-soft);
}
.photo-thumb-remove {
position: absolute;
top: -7px;
right: -7px;
width: 22px;
height: 22px;
padding: 0;
border-radius: 50%;
background: var(--danger);
color: #fff;
font-size: 14px;
line-height: 1;
} }
.event .thumb { .event .thumb {
@@ -490,6 +590,21 @@ dialog menu {
.time-row input { flex: 1 1 120px; min-width: 0; } .time-row input { flex: 1 1 120px; min-width: 0; }
.time-row button { padding: 8px 12px; } .time-row button { padding: 8px 12px; }
.chart-days-picker {
display: flex;
gap: 6px;
margin: -4px 0 14px;
}
.chart-days-picker button {
padding: 5px 12px;
font-size: 0.8rem;
}
.chart-days-picker button.active {
background: var(--accent);
border-color: transparent;
color: #fff;
}
.chart { margin-bottom: 16px; } .chart { margin-bottom: 16px; }
.chart:last-child { margin-bottom: 0; } .chart:last-child { margin-bottom: 0; }
.chart-title { .chart-title {
@@ -501,12 +616,24 @@ dialog menu {
} }
.chart-svg { display: block; width: 100%; height: auto; } .chart-svg { display: block; width: 100%; height: auto; }
.chart-svg text { fill: var(--muted); font-size: 9px; } .chart-svg text { fill: var(--muted); font-size: 9px; }
/* Dense 1h y-axes: smaller labels so every gridline can carry one. */
.chart-svg text.y-dense { font-size: 7px; }
.chart-svg .grid { .chart-svg .grid {
stroke: var(--border); stroke: var(--border);
stroke-dasharray: 2 3; stroke-dasharray: 2 3;
} }
.chart-svg .bar { cursor: pointer; } .chart-svg .bar { cursor: pointer; }
.chart-svg .bar-faded { opacity: 0.7; } .chart-svg .bar-faded { opacity: 0.7; }
/* The selected day's slice in every per-day chart: a soft accent band behind
the bars/cells (visible even when the day's values are all zero) plus an
accent-colored day label. */
.chart-svg .day-highlight {
fill: var(--accent);
fill-opacity: 0.08;
stroke: var(--accent);
stroke-opacity: 0.45;
}
.chart-svg text.day-label-sel { fill: var(--accent); font-weight: 600; }
.chart-svg .bar-sleep { fill: var(--sleep); } .chart-svg .bar-sleep { fill: var(--sleep); }
.chart-svg .bar-pee { fill: var(--pee); } .chart-svg .bar-pee { fill: var(--pee); }
.chart-svg .bar-poo { fill: var(--poo); } .chart-svg .bar-poo { fill: var(--poo); }
@@ -535,7 +662,16 @@ dialog menu {
.weight-summary .stat-value.up { color: var(--gain); } .weight-summary .stat-value.up { color: var(--gain); }
.weight-summary .stat-value.down { color: var(--danger); } .weight-summary .stat-value.down { color: var(--danger); }
.ww.weight-ww { cursor: pointer; } .ww.weight-ww { cursor: pointer; }
.ww.weight-ww .ww-dur { text-align: right; } /* Keep each weight row to one line: the date/age column shrinks and ellipses,
the weight value stays a fixed size, right-aligned and always visible. */
.ww.weight-ww .ww-range {
min-width: 0;
flex: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.ww.weight-ww .ww-dur { flex: 0 0 auto; text-align: right; }
.legend { .legend {
display: flex; display: flex;
@@ -556,6 +692,15 @@ dialog menu {
.lg.poo .sw { background: var(--poo); } .lg.poo .sw { background: var(--poo); }
.lg.eat .sw { background: var(--eat); } .lg.eat .sw { background: var(--eat); }
/* Interactive legend: each item is a checkbox that toggles its metric. */
.legend-toggle label.lg { cursor: pointer; user-select: none; }
.legend-toggle input[type="checkbox"] { margin: 0; cursor: pointer; }
.legend-toggle label.pee input { accent-color: var(--pee); }
.legend-toggle label.poo input { accent-color: var(--poo); }
.legend-toggle label.eat input { accent-color: var(--eat); }
/* Dim an unchecked item so it's clear its bars are hidden. */
.legend-toggle label.lg:has(input:not(:checked)) { opacity: 0.5; }
/* ---------- auth (login / register) ---------- */ /* ---------- auth (login / register) ---------- */
.auth-screen { .auth-screen {
position: fixed; position: fixed;
@@ -801,9 +946,57 @@ input.switch:checked::after { transform: translateX(18px); }
} }
.chart-svg .stl-sleep { fill: var(--sleep); } .chart-svg .stl-sleep { fill: var(--sleep); }
.chart-svg .stl-today { fill: var(--accent); font-weight: 600; } .chart-svg .stl-today { fill: var(--accent); font-weight: 600; }
/* Selected day: accent ring on the row's track + accent label. */
.chart-svg .stl-track.stl-selected {
stroke: var(--accent);
stroke-width: 1.2;
stroke-opacity: 0.8;
}
.chart-svg .stl-sel { fill: var(--accent); }
.chart-svg .stl-hit { fill: transparent; cursor: pointer; } .chart-svg .stl-hit { fill: transparent; cursor: pointer; }
.chart-svg .stl-hit:hover { fill: var(--accent); fill-opacity: 0.08; } .chart-svg .stl-hit:hover { fill: var(--accent); fill-opacity: 0.08; }
/* Sleep trend lines: today strongest, the reference curves lighter/dashed. */
.chart-svg .trend-today {
stroke: var(--sleep);
stroke-width: 2.5;
stroke-linejoin: round;
fill: none;
}
.chart-svg .trend-yesterday {
stroke: var(--eat); /* orange — the gray it had before sank into the grid */
stroke-width: 1.5;
stroke-linejoin: round;
fill: none;
opacity: 0.85;
}
.chart-svg .trend-avg {
stroke: var(--weight); /* teal — keeps it apart from today's blue and its blue projected tail */
stroke-width: 1.5;
stroke-dasharray: 4 3;
stroke-linejoin: round;
fill: none;
opacity: 0.85;
}
/* Today's projected tail: same weight/color as today so it reads as its
continuation, dashed + faded because it hasn't happened yet. */
.chart-svg .trend-projected {
stroke: var(--sleep);
stroke-width: 2.5;
stroke-dasharray: 2 4;
stroke-linecap: round;
stroke-linejoin: round;
fill: none;
opacity: 0.55;
}
.chart-svg .trend-goal { fill: var(--sleep); fill-opacity: 0.12; }
.lg.trend-goal .sw { background: color-mix(in srgb, var(--sleep) 20%, var(--surface)); }
.lg.trend-today .sw { background: var(--sleep); }
.lg.trend-projected .sw { background: color-mix(in srgb, var(--sleep) 40%, var(--surface)); }
.lg.trend-yesterday .sw { background: var(--eat); }
.lg.trend-avg .sw { background: var(--weight); }
.lg[hidden] { display: none; }
.chart-svg .hm-cell { stroke: none; } .chart-svg .hm-cell { stroke: none; }
.chart-svg .hm-pee { fill: var(--pee); } .chart-svg .hm-pee { fill: var(--pee); }
.chart-svg .hm-poo { fill: var(--poo); } .chart-svg .hm-poo { fill: var(--poo); }
@@ -897,3 +1090,308 @@ section.collapsible > h2::after {
section.collapsed > h2::after { transform: translateY(-50%) rotate(-90deg); } section.collapsed > h2::after { transform: translateY(-50%) rotate(-90deg); }
section.collapsed > h2 { margin-bottom: 0; } section.collapsed > h2 { margin-bottom: 0; }
section.collapsed > :not(h2) { display: none; } section.collapsed > :not(h2) { display: none; }
/* ---------- pedigree lookup ---------- */
.pedigree-screen {
padding-top: 12px;
}
.pedigree-header {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 4px 8px;
}
.pedigree-header { flex-wrap: wrap; }
.pedigree-header h1 { font-size: 1.4rem; }
.ped-controls {
margin-left: auto;
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
#ped-foldall { padding: 5px 10px; font-size: 0.8rem; white-space: nowrap; }
.ped-zoom {
display: flex;
align-items: center;
gap: 4px;
flex-shrink: 0;
}
.ped-zoom .icon-btn { padding: 4px 9px; font-size: 1.1rem; }
#ped-zoom-reset {
padding: 5px 8px;
font-size: 0.8rem;
font-variant-numeric: tabular-nums;
min-width: 48px;
}
.pedigree-hint { margin: 4px 0 12px; }
/* The tree scales with the CSS `zoom` property, which reflows so the container
still scrolls to reach the edges at any zoom. */
.pedigree-tree { touch-action: pan-x pan-y; }
.pedigree-status {
margin: 10px 0;
font-size: 0.9rem;
color: var(--muted);
}
.pedigree-status.busy::before {
content: "";
display: inline-block;
width: 12px; height: 12px;
margin-right: 8px;
vertical-align: -1px;
border: 2px solid var(--accent);
border-top-color: transparent;
border-radius: 50%;
animation: ped-spin 0.8s linear infinite;
}
@keyframes ped-spin { to { transform: rotate(360deg); } }
.pedigree-status.error { color: var(--danger); }
.pedigree-status.done { color: var(--gain); }
/* disambiguation list */
.pedigree-choose {
display: grid;
gap: 8px;
margin: 8px 0 16px;
}
.ped-match {
display: flex;
flex-direction: column;
gap: 2px;
text-align: left;
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--surface);
color: var(--text);
cursor: pointer;
}
.ped-match:hover { border-color: var(--accent); }
.ped-match-name { font-weight: 600; }
.ped-match-meta { font-size: 0.8rem; color: var(--muted); }
/* looked-up dog */
.pedigree-subject {
margin: 6px 0 14px;
padding: 12px 14px;
border: 1px solid var(--border);
border-left: 4px solid var(--accent);
border-radius: var(--radius);
background: var(--surface);
}
.ped-subject-name { font-size: 1.15rem; font-weight: 700; }
.ped-subject-meta { font-size: 0.85rem; color: var(--muted); margin-top: 2px; }
/* Top-down family tree: the dog on top, parents branching below, connected by
lines drawn with each <li>'s ::before/::after (the classic CSS tree). Wider
than the screen once expanded, so the container scrolls horizontally. */
.pedigree-tree {
overflow-x: auto;
padding: 8px 0 28px;
}
.ped-tree-h, .ped-tree-h ul {
display: flex;
list-style: none;
margin: 0;
padding: 0;
}
.ped-tree-h {
/* "safe" centers when the tree fits and falls back to start-aligned (no
clipped/unreachable left edge) once it's wider than the screen. */
justify-content: safe center;
min-width: max-content;
padding: 4px 16px 12px;
}
.ped-tree-h ul {
justify-content: center;
position: relative;
padding-top: 22px; /* room for the connector from the parent above */
}
.ped-tree-h li {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
padding: 22px 6px 0;
}
/* Elbow from each child up to the horizontal bar shared by its siblings. */
.ped-tree-h li::before,
.ped-tree-h li::after {
content: "";
position: absolute;
top: 0;
width: 50%;
height: 22px;
border-top: 2px solid var(--border);
}
.ped-tree-h li::before { right: 50%; }
.ped-tree-h li::after { left: 50%; border-left: 2px solid var(--border); }
/* Vertical drop from a parent card down to its children's bar. */
.ped-tree-h ul::before {
content: "";
position: absolute;
top: 0;
left: 50%;
height: 22px;
border-left: 2px solid var(--border);
}
/* A lone parent connects with a straight line, no elbow. */
.ped-tree-h li:only-child::before,
.ped-tree-h li:only-child::after { display: none; }
/* Trim the outer half-lines at the ends of a sibling row. */
.ped-tree-h li:first-child::before,
.ped-tree-h li:last-child::after { border: 0 none; }
.ped-tree-h li:last-child::before { border-right: 2px solid var(--border); }
/* The dog sits on top with no connector above it. */
.ped-tree-h > li { padding-top: 0; }
.ped-tree-h > li::before,
.ped-tree-h > li::after { display: none; }
/* Collapsed: hide the ancestry below this dog (and its connectors go with it). */
.ped-tree-h li.collapsed > ul { display: none; }
.ped-card {
position: relative;
width: 140px;
box-sizing: border-box;
padding: 7px 18px 7px 20px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--surface);
box-shadow: var(--shadow);
text-align: center;
}
.ped-name { font-weight: 600; font-size: 0.85rem; line-height: 1.2; }
.ped-name.ped-unknown { color: var(--muted); font-weight: 500; font-style: italic; }
.ped-titles { font-size: 0.66rem; color: var(--accent); margin-top: 2px; line-height: 1.2; }
.ped-reg {
font-size: 0.66rem;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
margin-top: 1px;
}
/* sire ♂ (blue) / dam ♀ (purple) accents on the parent cards */
.ped-sire > .ped-card { border-top: 3px solid var(--sleep); }
.ped-dam > .ped-card { border-top: 3px solid var(--training); }
.ped-sire > .ped-card::after,
.ped-dam > .ped-card::after {
position: absolute;
right: 6px;
top: 5px;
font-size: 0.72rem;
}
.ped-sire > .ped-card::after { content: "♂"; color: var(--sleep); }
.ped-dam > .ped-card::after { content: "♀"; color: var(--training); }
/* pedigree collapse: a dog filling more than one position gets a ×N badge, a
stable hue, and lights up (with every copy) when tapped. */
.ped-card.ped-repeat { cursor: pointer; }
.ped-repeat-badge {
position: absolute;
right: 5px;
bottom: 5px;
font-size: 0.6rem;
font-weight: 700;
line-height: 1;
padding: 2px 5px;
border-radius: 999px;
color: #fff;
background: hsl(var(--repeat-hue, 0), 58%, 48%);
}
.ped-card.ped-lit {
border-color: hsl(var(--repeat-hue, 0), 70%, 50%);
box-shadow: 0 0 0 2px hsl(var(--repeat-hue, 0), 70%, 50%), var(--shadow);
}
.pedigree-repeat-note { margin: 0 0 10px; }
/* expand/collapse toggle (top-left of the card) */
.ped-toggle {
position: absolute;
left: 5px;
top: 5px;
width: 18px; height: 18px;
padding: 0;
font-size: 0.9rem;
line-height: 1;
border: 1px solid var(--border);
border-radius: 5px;
background: var(--bg);
color: var(--muted);
cursor: pointer;
}
.ped-toggle:hover { border-color: var(--accent); color: var(--accent); }
/* ---- radial fan chart ---- */
.ped-fan { display: block; margin: 0 auto; max-width: none; }
.ped-wedge {
cursor: pointer;
stroke: var(--border);
stroke-width: 1;
/* outer rings tint gradually darker for depth */
fill: color-mix(in srgb, var(--accent-soft) calc(var(--gen, 1) * 7%), var(--surface));
transition: filter 0.1s ease;
}
.ped-wedge:hover { filter: brightness(0.95); }
/* a dog that appears more than once is filled with its stable hue */
.ped-wedge-repeat { fill: hsl(var(--repeat-hue, 0), 60%, 80%); stroke: hsl(var(--repeat-hue, 0), 45%, 60%); }
.ped-wedge.ped-lit {
fill: hsl(var(--repeat-hue, 0), 72%, 62%);
stroke: hsl(var(--repeat-hue, 0), 72%, 38%);
stroke-width: 2;
}
.ped-wedge-label {
font-size: 8px;
fill: var(--text);
text-anchor: middle;
dominant-baseline: central;
pointer-events: none;
}
.ped-fan-center { fill: var(--accent); stroke: none; cursor: pointer; }
.ped-fan-center-label {
fill: #fff;
font-size: 9px;
font-weight: 600;
dominant-baseline: central;
pointer-events: none;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) .ped-wedge-label { fill: var(--text); }
}
.pedigree-caption {
margin: 10px 0 0;
font-size: 0.85rem;
color: var(--muted);
text-align: center;
}
/* ---- pee/poo confetti ---- */
#confetti-layer {
position: fixed;
inset: 0;
pointer-events: none;
overflow: hidden;
z-index: 9999;
}
.confetti-piece {
position: absolute;
line-height: 1;
will-change: transform, opacity;
animation-name: potty-firework;
animation-timing-function: ease-out;
/* `both` so the 0% state (invisible, at the bottom) also applies during the
per-piece launch delay no flash before it takes off. */
animation-fill-mode: both;
}
/* Launch up from the bottom, rise to a peak while spreading sideways, slowing
(ease-out) and fading out as it reaches the top a firework fountain.
Distances come from JS custom props. */
@keyframes potty-firework {
0% { opacity: 0; transform: translate(-50%, -50%) scale(0.5) rotate(0deg); }
10% { opacity: 1; }
70% { opacity: 1; }
100% { opacity: 0; transform: translate(calc(-50% + var(--dx)), calc(-50% + var(--peakY))) scale(1) rotate(var(--rot)); }
}
@media (prefers-reduced-motion: reduce) {
.confetti-piece { display: none; }
}