From 2b394257a4787ea93cc64a56875d539bd679a879 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 07:45:32 +0000 Subject: [PATCH] Personal: illustration v2 for the muscle map - Shaded, outlined front/back figure with fibre lines and landmarks; five new muscles (neck, serratus, rhomboids, hip abductors, soleus), 25 in all. - Five-band colour coding with text labels and hatch patterns, plus a last-worked colouring; descriptive only. - Purposeful motion, all under prefers-reduced-motion: no-preference: head to feet fill-in, band colour glide, 3D front/back turn with swipe, peak glow, selection pulse, hover caption. - Four-week replay with play/scrub, from the user's own workouts. - No schema change; imports P1-B code but edits none of it. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_018caQbyr5kMzA8YcRwCNrt8 --- docs/DESIGN.md | 4 +- docs/P1_MUSCLE_EXPLORER.md | 12 + src/app/me/body/page.tsx | 9 +- src/components/personal/body-map/body-map.css | 339 +++++++++++++++--- src/components/personal/body-map/body-map.tsx | 288 ++++++++++++--- .../personal/body-map/body-paths.ts | 126 ++++--- .../personal/body-map/muscle-explorer.tsx | 242 ++++++++++--- src/lib/personal/exercise-catalog.ts | 52 ++- src/lib/personal/load-bands.ts | 51 +++ src/lib/personal/muscle-explorer-service.ts | 14 +- src/lib/personal/muscle-map.ts | 35 +- src/lib/personal/muscle-timeline.ts | 36 ++ tests/integration/personal-service.test.mjs | 22 ++ tests/unit/personal-load-bands.test.mjs | 85 +++++ 14 files changed, 1094 insertions(+), 221 deletions(-) create mode 100644 src/lib/personal/load-bands.ts create mode 100644 src/lib/personal/muscle-timeline.ts create mode 100644 tests/unit/personal-load-bands.test.mjs diff --git a/docs/DESIGN.md b/docs/DESIGN.md index be089504..9d88fdc3 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -64,6 +64,7 @@ Rules: ## Motion - Subtle only (`human-motion-motion.css`). Everything is disabled under `prefers-reduced-motion` (see the media query at the end of `human-motion.css`). +- **Exception, owner decision 19 Nov 2026:** the Personal body map (`src/components/personal/body-map/`) may use expressive motion because it is a signature feature. The limits still hold: every animation must communicate something (what is loaded, what changed, what is selected), stay inside the warm sage, terracotta and cocoa palette, and sit entirely inside `@media (prefers-reduced-motion: no-preference)`. With reduced motion the map must remain fully usable and static, and no information may exist only in motion. ## Theme switching @@ -110,7 +111,8 @@ The separate Personal health experience (see [DELIVERY_PLAN.md](DELIVERY_PLAN.md - Regions are keyboard-focusable buttons (Enter/Space); the mirrored half is hidden from assistive tech. - Colour transitions run only under `prefers-reduced-motion: no-preference`. - Illustration is decorative anatomy, not medical imagery, and never implies diagnosis or injury. -- The map is interactive (Planned / Logged / Preview, with a 7, 28 or 90 day period): see [P1_MUSCLE_EXPLORER.md](P1_MUSCLE_EXPLORER.md). Segmented controls reuse the Front/Back tab styling with 44px targets; the figure never moves when controls change. +- The map is interactive (Planned / Logged / Preview, a 7, 28 or 90 day period, colour by how much or last worked, and a four-week replay): see [P1_MUSCLE_EXPLORER.md](P1_MUSCLE_EXPLORER.md). Segmented controls reuse the Front/Back tab styling with 44px targets. +- **Colour coding** uses five bands (none, light, moderate, high, peak) on a sage, amber, terracotta, deep terracotta ramp. Colour is never the only signal: each band has a text label, its own hatch pattern, and appears in the text list. ## History: Luxe (superseded) diff --git a/docs/P1_MUSCLE_EXPLORER.md b/docs/P1_MUSCLE_EXPLORER.md index 5281b380..6c3edd7c 100644 --- a/docs/P1_MUSCLE_EXPLORER.md +++ b/docs/P1_MUSCLE_EXPLORER.md @@ -29,3 +29,15 @@ Built to avoid Codex's in-flight work: it imports P1-B code but edits none of it ## Known limits - The exercise catalogue covers common lifts and cardio only; unusual names go to "not counted". A user-editable mapping is a possible follow-up. - Set-equivalents are a descriptive volume count, not a validated training-load model. + +## Illustration v2 (19 Nov 2026) +- **Art:** shaded, outlined front and back figure with fibre lines and anatomical landmarks. Five muscles added (neck, serratus, rhomboids, hip abductors, soleus), 25 in all. Existing ids are never renamed or split, and no stored data refers to muscle ids, so nothing needed migrating. +- **Colour coding:** five load bands (none, light, moderate, high, peak) with hatch patterns and text labels, so colour is never the only signal. A second mode colours by **last worked** (today, 1–2, 3–6, 7+ days, not in period). Both are descriptive; neither says anything about recovery or readiness. Pure rules: `src/lib/personal/load-bands.ts`. +- **Motion** (all inside `prefers-reduced-motion: no-preference`): muscles fill in head to feet; colour glides between bands; the figure turns in 3D between front and back (tap or swipe); the heaviest muscles breathe a slow warm glow; selecting a muscle pulses once; hover or focus shows a caption chip. With reduced motion everything is static and the turn is instant. +- **Replay:** a scrubbable, playable time-lapse of the last four weeks. Each day shows the trailing seven days of the user's own training, on one shared scale (`muscle-timeline.ts`). Dates are UTC. +- **Same privacy as before:** own rows only, behind P1-B's wellness gate and adult rule; absent when the gate is off. No schema change. + +### Known limits +- Replay day labels are UTC calendar dates, so they can differ by a day from the user's local date. +- Hatch patterns and glow are tuned for the two shipped themes; a third theme would need re-tuning `--bm-*`. +- Saving or sharing the map as an image is not built (CSS-variable styling needs inlining first); a possible follow-up. diff --git a/src/app/me/body/page.tsx b/src/app/me/body/page.tsx index ea49a070..039154cf 100644 --- a/src/app/me/body/page.tsx +++ b/src/app/me/body/page.tsx @@ -8,7 +8,7 @@ import { MuscleExplorer } from "@/components/personal/body-map/muscle-explorer"; export default async function BodyPage() { const session = await requireSession(); - const { overview: o, logged } = await getMuscleExplorer(prisma, session.user.id); + const { overview: o, logged, timeline } = await getMuscleExplorer(prisma, session.user.id); // Latest logged girth per muscle, across left and right. const notes: Partial> = {}; @@ -31,7 +31,12 @@ export default async function BodyPage() {

My muscle map

Tap a muscle to see what trains it.

- + ); } diff --git a/src/components/personal/body-map/body-map.css b/src/components/personal/body-map/body-map.css index eedb337b..7bd0c069 100644 --- a/src/components/personal/body-map/body-map.css +++ b/src/components/personal/body-map/body-map.css @@ -1,8 +1,31 @@ -/* Body map: tokens come from .hm-app (src/app/human-motion.css); never raw hex. */ +/* + * Body map v2. Tokens come from .hm-app (src/app/human-motion.css); only the amber accent is local, + * because the design system has no shared amber token. + * + * Motion is expressive here by owner request (see docs/DESIGN.md), but every animation communicates + * something (what is loaded, what changed, what is selected) and ALL of it is inside + * `prefers-reduced-motion: no-preference`. With reduced motion the map is fully usable and static. + */ .hm-bodymap { + --bm-amber: #c99d52; + --bm-skin: color-mix(in oklab, var(--hm-cocoa) 11%, var(--hm-surface)); + --bm-outline: var(--hm-cocoa); + --bm-pattern: #000; + /* Five load bands: none, light, moderate, high, peak. */ + --bm-b0: color-mix(in oklab, var(--hm-sage) 14%, var(--hm-surface)); + --bm-b1: color-mix(in oklab, var(--hm-sage) 55%, var(--hm-surface)); + --bm-b2: color-mix(in oklab, var(--bm-amber) 88%, var(--hm-surface)); + --bm-b3: color-mix(in oklab, var(--hm-terracotta) 82%, var(--hm-surface)); + --bm-b4: color-mix(in oklab, var(--hm-terracotta) 86%, var(--hm-cocoa)); display: grid; gap: 1rem; } +html.dark .hm-bodymap { + --bm-amber: #dcb46a; + --bm-pattern: #fff; +} + +/* ---- Side switch ---- */ .hm-bodymap-tabs { display: inline-flex; gap: 0.25rem; @@ -27,77 +50,177 @@ background: var(--hm-action); color: var(--hm-action-text); } +.hm-bodymap-tab:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +/* ---- Stage and figure ---- */ +.bm-stage { + display: grid; + justify-items: center; + gap: 0.5rem; + perspective: 900px; +} +.bm-caption { + min-height: 1.75rem; + margin: 0; + display: flex; + align-items: center; + gap: 0.5rem; + color: var(--hm-text); + font-weight: 600; +} +.bm-caption-band { + padding: 0.125rem 0.625rem; + border-radius: 999px; + font-size: 0.75rem; + font-weight: 700; + color: var(--hm-text); + background: color-mix(in oklab, var(--bm-chip, var(--bm-b0)) 70%, var(--hm-surface)); + border: 1px solid color-mix(in oklab, var(--bm-chip, var(--bm-b0)) 80%, var(--hm-cocoa)); +} +.bm-caption-hint { + color: var(--hm-muted); + font-weight: 400; + font-size: 0.875rem; +} .hm-bodymap-figure { width: min(100%, 320px); height: auto; - justify-self: center; - touch-action: manipulation; + touch-action: pan-y; + user-select: none; + -webkit-user-select: none; } -.hm-bodymap-halo { - fill: color-mix(in oklab, var(--hm-cocoa) 10%, var(--hm-surface)); - stroke: color-mix(in oklab, var(--hm-cocoa) 10%, var(--hm-surface)); + +/* Layers: outline ring, skin fill, then the muscles on top. */ +.bm-outline { + fill: var(--bm-outline); + fill-opacity: 0.5; + stroke: var(--bm-outline); + stroke-opacity: 0.5; + stroke-width: 13.6; + stroke-linejoin: round; +} +.bm-skin { + fill: var(--bm-skin); + stroke: var(--bm-skin); stroke-width: 12; stroke-linejoin: round; } -.hm-bodymap-decor { - fill: color-mix(in oklab, var(--hm-cocoa) 14%, var(--hm-surface)); +.bm-decor { + fill: color-mix(in oklab, var(--hm-cocoa) 16%, var(--hm-surface)); stroke: var(--hm-cocoa); - stroke-opacity: 0.35; + stroke-opacity: 0.4; stroke-width: 0.8; } -.hm-bodymap-muscle path { - fill: color-mix( - in oklab, - var(--hm-terracotta) calc(var(--load, 0) * 85%), - color-mix(in oklab, var(--hm-sage) 14%, var(--hm-surface)) - ); +.bm-base { stroke: var(--hm-cocoa); - stroke-opacity: 0.55; + stroke-opacity: 0.6; stroke-width: 0.8; } -.hm-bodymap-muscle { - cursor: pointer; - outline: none; +.bm-m[data-band="0"] .bm-base { + fill: var(--bm-b0); } -.hm-bodymap-muscle:focus-visible path, -.hm-bodymap-muscle[aria-pressed="true"] path { - stroke: var(--hm-action); - stroke-opacity: 1; - stroke-width: 2; +.bm-m[data-band="1"] .bm-base { + fill: var(--bm-b1); +} +.bm-m[data-band="2"] .bm-base { + fill: var(--bm-b2); +} +.bm-m[data-band="3"] .bm-base { + fill: var(--bm-b3); +} +.bm-m[data-band="4"] .bm-base { + fill: var(--bm-b4); } -.hm-bodymap-line { +.bm-shade, +.bm-pat, +.bm-line, +.bm-landmark { + pointer-events: none; +} +.bm-shade, +.bm-pat { + stroke: none; +} +.bm-line, +.bm-landmark { fill: none; stroke: var(--hm-cocoa); - stroke-opacity: 0.35; - stroke-width: 0.7; stroke-linecap: round; - pointer-events: none; } -@media (prefers-reduced-motion: no-preference) { - .hm-bodymap-muscle path { - transition: - fill 200ms ease, - stroke-width 120ms ease; - } +.bm-line { + stroke-opacity: 0.38; + stroke-width: 0.7; +} +.bm-landmark { + stroke-opacity: 0.3; + stroke-width: 0.8; +} +.bm-m { + cursor: pointer; + outline: none; +} +/* A generous invisible hit area, so small muscles (neck, serratus) are easy to tap. */ +.bm-hit { + fill: none; + stroke: transparent; + stroke-width: 3.5; + pointer-events: all; +} +.bm-m:hover .bm-base { + filter: brightness(1.08); + stroke-opacity: 0.9; +} +.bm-m:focus-visible .bm-base, +.bm-m[aria-pressed="true"] .bm-base { + stroke: var(--hm-action); + stroke-opacity: 1; + stroke-width: 2; } -.hm-bodymap-legend { + +/* ---- Legend ---- */ +.bm-legend { display: flex; - align-items: center; + flex-wrap: wrap; justify-content: center; - gap: 0.5rem; + gap: 0.375rem 0.875rem; + margin: 0; + padding: 0; + list-style: none; color: var(--hm-muted); font-size: 0.8125rem; } -.hm-bodymap-ramp { - width: 96px; - height: 8px; - border-radius: 999px; - background: linear-gradient( - 90deg, - color-mix(in oklab, var(--hm-sage) 14%, var(--hm-surface)), - var(--hm-terracotta) - ); +.bm-legend li { + display: inline-flex; + align-items: center; + gap: 0.375rem; +} +.bm-swatch { + width: 22px; + height: 14px; + border-radius: 4px; + overflow: hidden; + border: 1px solid color-mix(in oklab, var(--hm-cocoa) 55%, transparent); +} +.bm-swatch rect:first-child[data-band="0"] { + fill: var(--bm-b0); +} +.bm-swatch rect:first-child[data-band="1"] { + fill: var(--bm-b1); +} +.bm-swatch rect:first-child[data-band="2"] { + fill: var(--bm-b2); +} +.bm-swatch rect:first-child[data-band="3"] { + fill: var(--bm-b3); } +.bm-swatch rect:first-child[data-band="4"] { + fill: var(--bm-b4); +} + +/* ---- Detail panel and text list ---- */ .hm-bodymap-detail { padding: 1rem; border-radius: 22px; @@ -136,7 +259,7 @@ font-variant-numeric: tabular-nums; } -/* Interactive explorer controls (source, period, preview). */ +/* ---- Explorer controls ---- */ .hm-explorer { display: grid; gap: 0.75rem; @@ -153,7 +276,123 @@ text-align: center; margin: 0; } -.hm-bodymap-tab:disabled { - opacity: 0.45; - cursor: not-allowed; +.bm-replay { + display: grid; + gap: 0.5rem; + padding: 0.75rem 1rem; + border-radius: 22px; + background: var(--hm-surface); + border: 1px solid var(--hm-line); +} +.bm-replay-row { + display: flex; + align-items: center; + gap: 0.75rem; +} +.bm-replay input[type="range"] { + flex: 1; + min-height: 44px; + accent-color: var(--hm-action); +} +.bm-replay-date { + font-variant-numeric: tabular-nums; + font-weight: 600; + min-width: 7.5rem; + text-align: right; +} + +/* ================= Motion (expressive, purposeful, and always optional) ================= */ +@media (prefers-reduced-motion: no-preference) { + /* Colour changes glide between bands instead of snapping. */ + .bm-base { + transition: + fill 420ms ease, + stroke-width 160ms ease, + stroke-opacity 160ms ease, + filter 160ms ease; + } + + /* Muscles fill in region by region, so the figure feels like it is being drawn from your data. */ + .bm-m { + animation: bm-fill-in 520ms cubic-bezier(0.2, 0.7, 0.2, 1) both; + animation-delay: calc(var(--i, 0) * 26ms); + transform-box: fill-box; + transform-origin: center; + } + @keyframes bm-fill-in { + from { + opacity: 0; + transform: scale(0.9); + } + to { + opacity: 1; + transform: scale(1); + } + } + + /* Front/back turn: the figure swings edge-on, swaps sides, then swings back. */ + .bm-turn { + transition: transform 170ms cubic-bezier(0.4, 0, 1, 1); + } + .bm-turn[data-phase="out"] { + transform: rotateY(90deg); + } + .bm-turn[data-phase="in"] { + animation: bm-turn-in 220ms cubic-bezier(0, 0, 0.2, 1) both; + } + @keyframes bm-turn-in { + from { + transform: rotateY(-90deg); + } + to { + transform: rotateY(0deg); + } + } + + /* The hardest-worked muscles breathe a warm glow, slowly, so they draw the eye without shouting. */ + .bm-m[data-band="4"] .bm-base { + animation: bm-peak 3.2s ease-in-out 900ms infinite; + } + @keyframes bm-peak { + 0%, + 100% { + stroke: var(--hm-cocoa); + stroke-opacity: 0.6; + stroke-width: 0.8; + } + 50% { + stroke: var(--hm-terracotta); + stroke-opacity: 1; + stroke-width: 1.9; + } + } + + /* Selecting a muscle gives one confident pulse. */ + .bm-m[aria-pressed="true"] .bm-base { + animation: bm-select 420ms ease-out; + } + @keyframes bm-select { + from { + stroke-width: 4.5; + stroke-opacity: 0.4; + } + to { + stroke-width: 2; + stroke-opacity: 1; + } + } + + .bm-caption { + animation: bm-caption-in 180ms ease-out both; + } + @keyframes bm-caption-in { + from { + opacity: 0; + transform: translateY(3px); + } + to { + opacity: 1; + transform: none; + } + } } diff --git a/src/components/personal/body-map/body-map.tsx b/src/components/personal/body-map/body-map.tsx index 9ffbe5e0..2c6e0d83 100644 --- a/src/components/personal/body-map/body-map.tsx +++ b/src/components/personal/body-map/body-map.tsx @@ -1,19 +1,31 @@ "use client"; -import { useState, type CSSProperties, type KeyboardEvent } from "react"; +import { + useEffect, + useId, + useRef, + useState, + type CSSProperties, + type KeyboardEvent, + type PointerEvent, +} from "react"; import { MUSCLE_GROUPS, activitiesForMuscle, type MuscleId, type MuscleSide, } from "@/lib/personal/muscle-map"; +import { bandInfo, loadBand, type Band, type ColorMode } from "@/lib/personal/load-bands"; +import { RECENCY_BANDS, VOLUME_BANDS } from "@/lib/personal/load-bands"; import { + BACK_LANDMARKS, BACK_LINES, BACK_REGIONS, BODY_VIEWBOX, DECOR_CENTER, DECOR_LEFT_BACK, DECOR_LEFT_FRONT, + FRONT_LANDMARKS, FRONT_LINES, FRONT_REGIONS, } from "./body-paths"; @@ -22,6 +34,9 @@ import "./body-map.css"; /** Primary activities come first, so the cap keeps the most relevant ones. */ const MAX_ACTIVITIES_SHOWN = 5; const MIRROR = "translate(200 0) scale(-1 1)"; +const SWIPE_PX = 48; +const TURN_OUT_MS = 170; +const TURN_IN_MS = 220; const SIDES: { side: MuscleSide; label: string }[] = [ { side: "front", label: "Front" }, { side: "back", label: "Back" }, @@ -30,23 +45,73 @@ const SIDES: { side: MuscleSide; label: string }[] = [ export interface BodyMapProps { /** Load per muscle on a 0..1 scale (see muscleLoad). Missing muscles count as 0. */ load: Partial>; + /** Colour band per muscle (0..4). When omitted it is derived from `load`. */ + bands?: Partial>; + /** Which legend and labels to use: how much work, or how long ago. */ + mode?: ColorMode; /** Optional short text per muscle, e.g. a recent girth measurement, shown in the detail panel. */ notes?: Partial>; /** Wording for the load figure in the detail panel, e.g. "of your most-worked muscle". */ loadPhrase?: string; } -export function BodyMap({ load, notes, loadPhrase = "of your most-worked muscle" }: BodyMapProps) { +export function BodyMap({ + load, + bands, + mode = "volume", + notes, + loadPhrase = "of your most-worked muscle", +}: BodyMapProps) { + const uid = useId().replace(/[^a-zA-Z0-9]/g, ""); const [side, setSide] = useState("front"); + const [phase, setPhase] = useState<"idle" | "out" | "in">("idle"); const [selected, setSelected] = useState(null); + const [hovered, setHovered] = useState(null); + const timers = useRef([]); + const swipe = useRef<{ x: number; at: number } | null>(null); + const justSwiped = useRef(false); + + useEffect(() => { + const pending = timers.current; + return () => pending.forEach((t) => window.clearTimeout(t)); + }, []); const regions = side === "front" ? FRONT_REGIONS : BACK_REGIONS; const lines = side === "front" ? FRONT_LINES : BACK_LINES; const decor = side === "front" ? DECOR_LEFT_FRONT : DECOR_LEFT_BACK; + const landmarks = side === "front" ? FRONT_LANDMARKS : BACK_LANDMARKS; const muscles = MUSCLE_GROUPS.filter((m) => m.side === side); + // Fill-in order follows the body, head to feet, using the top of each muscle's first outline. + const topOf = (id: MuscleId) => + Number(regions[id]?.[0]?.match(/^M\s*[\d.]+[\s,]+([\d.]+)/)?.[1] ?? 0); + const rank = new Map( + [...muscles].sort((a, b) => topOf(a.id) - topOf(b.id)).map((m, i) => [m.id, i] as const) + ); const percent = (id: MuscleId) => Math.round((load[id] ?? 0) * 100); + const bandOf = (id: MuscleId): Band => bands?.[id] ?? loadBand(load[id] ?? 0); + const labelOf = (id: MuscleId) => bandInfo(mode, bandOf(id)).label; + + function flipTo(next: MuscleSide) { + if (next === side || phase !== "idle") return; + setSelected(null); + setHovered(null); + // Reduced motion: switch instantly. Everything decorative below is also off in CSS. + if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) { + setSide(next); + return; + } + setPhase("out"); + timers.current.push( + window.setTimeout(() => { + setSide(next); + setPhase("in"); + timers.current.push(window.setTimeout(() => setPhase("idle"), TURN_IN_MS)); + }, TURN_OUT_MS) + ); + } function choose(id: MuscleId) { + if (justSwiped.current) return; setSelected((cur) => (cur === id ? null : id)); } function onKey(e: KeyboardEvent, id: MuscleId) { @@ -55,48 +120,80 @@ export function BodyMap({ load, notes, loadPhrase = "of your most-worked muscle" choose(id); } } + function onPointerDown(e: PointerEvent) { + swipe.current = { x: e.clientX, at: e.timeStamp }; + } + function onPointerUp(e: PointerEvent) { + const start = swipe.current; + swipe.current = null; + if (!start || e.timeStamp - start.at > 700) return; + if (Math.abs(e.clientX - start.x) >= SWIPE_PX) { + justSwiped.current = true; + window.setTimeout(() => (justSwiped.current = false), 300); + flipTo(side === "front" ? "back" : "front"); + } + } // Each half is drawn once and mirrored; both halves select the same muscle group. const half = (flip: boolean) => ( - + {decor.map((d) => ( - - ))} - {muscles.map((m) => ( - choose(m.id)} - onKeyDown={(e) => onKey(e, m.id)} - > - {(regions[m.id] ?? []).map((d) => ( - - ))} - + ))} + {muscles.map((m) => { + const band = bandOf(m.id); + return ( + choose(m.id)} + onKeyDown={(e) => onKey(e, m.id)} + onPointerEnter={() => setHovered(m.id)} + onPointerLeave={() => setHovered((cur) => (cur === m.id ? null : cur))} + onFocus={() => setHovered(m.id)} + onBlur={() => setHovered((cur) => (cur === m.id ? null : cur))} + > + {(regions[m.id] ?? []).map((d) => ( + + + + {band > 0 && } + + + ))} + + ); + })} {Object.values(lines) .flat() .map((d) => ( - + ))} + {landmarks.map((d) => ( + + ))} ); - const halo = (flip: boolean) => ( - + const halo = (flip: boolean, cls: string) => ( + {[...decor, ...Object.values(regions).flat()].map((d) => ( - + ))} ); const selectedMuscle = selected ? MUSCLE_GROUPS.find((m) => m.id === selected) : undefined; + const captionId = hovered ?? selected; + const caption = captionId ? MUSCLE_GROUPS.find((m) => m.id === captionId) : undefined; + const legend = mode === "volume" ? VOLUME_BANDS : RECENCY_BANDS; return (
@@ -107,43 +204,130 @@ export function BodyMap({ load, notes, loadPhrase = "of your most-worked muscle" type="button" className="hm-bodymap-tab" aria-pressed={side === s.side} - onClick={() => { - setSide(s.side); - setSelected(null); - }} + onClick={() => flipTo(s.side)} > {s.label} ))} - - {halo(false)} - {halo(true)} - {DECOR_CENTER.map((d) => ( - - ))} - {half(false)} - {half(true)} - - -
- Lighter load - - Heavier load +
+

+ {caption ? ( + <> + {caption.label} + + {labelOf(caption.id)} + + + ) : ( + Tap a muscle. Swipe to turn. + )} +

+
+ + + + + + + + {/* One pattern per band, so colour is never the only signal. */} + + + + + + + + + + + + + + {halo(false, "bm-outline")} + {halo(true, "bm-outline")} + {halo(false, "bm-skin")} + {halo(true, "bm-skin")} + {DECOR_CENTER.map((d) => ( + + ))} + {half(false)} + {half(true)} + +
+
    + {legend.map((b) => ( +
  • + + + {b.band > 0 && } + + {b.label} + {mode === "volume" && b.range ? ` (${b.range})` : ""} +
  • + ))} +
+
{selectedMuscle ? ( <>

{selectedMuscle.label}

- Training load {percent(selectedMuscle.id)}% {loadPhrase}. + {labelOf(selectedMuscle.id)}. Training load {percent(selectedMuscle.id)}% {loadPhrase} + .

{[notes?.[selectedMuscle.id] ?? []].flat().map((line) => (

{line}

@@ -174,7 +358,9 @@ export function BodyMap({ load, notes, loadPhrase = "of your most-worked muscle" {muscles.map((m) => (
  • {m.label} - {percent(m.id)}% + + {labelOf(m.id)}, {percent(m.id)}% +
  • ))} diff --git a/src/components/personal/body-map/body-paths.ts b/src/components/personal/body-map/body-paths.ts index c55c14f4..a148b128 100644 --- a/src/components/personal/body-map/body-paths.ts +++ b/src/components/personal/body-map/body-paths.ts @@ -1,91 +1,119 @@ -// Stylised anatomy for the Personal body map. viewBox 0 0 200 400, centre line x = 100. -// Each region is drawn for the viewer's LEFT half only; the renderer mirrors it for the right half. +// Stylised anatomy for the Personal body map (v2). viewBox 0 0 200 400, centre line x = 100. +// Every region is drawn for the viewer's LEFT half only; the renderer mirrors it for the right half. // Ids must match MUSCLE_GROUPS in src/lib/personal/muscle-map.ts. export const BODY_VIEWBOX = "0 0 200 400"; -// Rounded abdominal segment, left half: rows of the "six-pack". -function absRow(y1: number, y2: number): string { - return `M98 ${y1} H89 Q85 ${y1} 85 ${y1 + 4} V${y2 - 4} Q85 ${y2} 89 ${y2} H98 Z`; +// Rounded abdominal segment, left half. Rows taper toward the waist like a real rectus abdominis. +function absRow(y1: number, y2: number, x: number): string { + return `M98.5 ${y1} H${x + 3} Q${x} ${y1} ${x} ${y1 + 3} V${y2 - 3} Q${x} ${y2} ${x + 3} ${y2} H98.5 Z`; } -// Arm silhouette shared by biceps/triceps and both forearm views. const UPPER_ARM = - "M60 101 C56 100 53 102 52 106 C50 120 50 132 52 142 C56 144 60 143 64 141 C66 130 66 112 60 101Z"; + "M58 116 C54 118 51 126 51 138 C51 148 53 156 56 162 C60 164 64 162 66 158 C68 148 68 134 66 124 C64 118 61 116 58 116Z"; const FOREARM = - "M52 146 C50 160 48 178 46 196 L56 198 C60 184 64 164 65 146 C61 147 56 147 52 146Z"; + "M54 168 C50 182 47 200 45 218 L55 222 C59 208 63 190 64 170 C60 172 57 172 54 168Z"; export const FRONT_REGIONS: Record = { - "deltoid-front": ["M70 74 C67 72 64 71 62 72 L60 99 C66 100 72 100 76 99 C72 93 69 84 70 74Z"], - "deltoid-side": ["M62 72 C57 71 52 74 50 80 C48 88 51 96 56 100 C57 100 59 100 60 99 Z"], - pectorals: ["M98 70 C90 66 78 68 70 74 C69 84 72 93 76 99 C84 103 94 102 98 100 Z"], + neck: ["M92 52 C90 58 91 64 95 72 L99 76 L99 58 C96 57 93 55 92 52Z"], + "deltoid-front": ["M72 83 C69 79 64 77 60 77 L58 113 C62 115 67 114 70 108 C71 99 72 91 72 83Z"], + "deltoid-side": ["M60 77 C55 77 51 82 50 90 C49 99 51 108 54 113 C56 114 57 114 58 113 L60 77Z"], + pectorals: [ + "M99 85 C94 81 88 80 82 81 C77 82 74 84 72 87 C71 96 73 106 78 114 C84 120 92 122 99 120 Z", + ], + serratus: [ + "M74 112 L82 116 L80 123 L72 119Z", + "M73 122 L81 126 L79 133 L72 129Z", + "M73 132 L80 136 L79 142 L73 139Z", + ], biceps: [UPPER_ARM], "forearms-front": [FOREARM], - abs: [absRow(104, 118), absRow(121, 135), absRow(138, 152), absRow(155, 170)], - obliques: ["M76 102 C74 120 75 148 80 170 L84 170 L84 104 C81 103 79 102 76 102Z"], - "hip-flexors": ["M98 173 C92 172 86 172 80 173 C78 179 78 187 80 193 C86 197 92 198 98 196 Z"], + abs: [absRow(126, 141, 86), absRow(144, 159, 87), absRow(162, 177, 88), absRow(180, 194, 90)], + obliques: ["M74 144 C72 158 73 174 78 192 L85 196 L84 146 C80 146 77 145 74 144Z"], + "hip-flexors": ["M99 198 C92 196 84 197 78 201 C76 207 78 213 84 217 C90 219 95 217 99 214Z"], quadriceps: [ - "M80 198 C73 214 70 240 73 264 C77 271 86 272 93 268 C91 250 90 228 94 200 C90 199 85 198 80 198Z", + "M80 218 C72 232 69 262 72 290 C77 298 88 298 94 292 C93 268 93 240 97 224 C92 222 86 220 80 218Z", ], - adductors: ["M94 200 C90 228 91 250 93 268 L98 270 L98 200Z"], - tibialis: ["M76 282 C74 300 74 330 78 360 L86 360 C90 330 90 300 90 282 C85 284 80 284 76 282Z"], + adductors: ["M97 224 C93 240 93 268 94 292 L100 298 L100 224Z"], + tibialis: ["M76 308 C74 326 75 348 78 370 L86 370 C89 348 90 326 90 308 C85 311 80 311 76 308Z"], }; export const BACK_REGIONS: Record = { - trapezius: ["M98 50 C90 54 80 60 70 66 C72 74 80 86 88 100 C92 108 96 120 98 130 Z"], + trapezius: [ + "M99 54 C92 58 82 62 72 68 C66 72 62 76 60 80 C64 86 72 92 82 96 C90 98 96 100 99 100Z", + ], "deltoid-rear": [ - "M70 66 C62 65 55 70 53 80 C52 90 55 96 60 99 C65 96 69 88 71 80 C72 74 71 70 70 66Z", + "M72 82 C66 76 58 76 54 82 C51 90 52 102 57 110 C62 112 68 108 71 100 C73 94 73 88 72 82Z", ], + // Outer edge is the exact inner edge of the lats, so no gap is left between them. + rhomboids: ["M99 100 C92 100 86 98 78 94 C77 104 80 112 86 120 C92 126 96 130 97 134 L99 136Z"], triceps: [UPPER_ARM], "forearms-back": [FOREARM], lats: [ - "M66 102 C70 98 73 92 74 86 C80 96 88 104 91 112 C91 126 90 140 88 152 C84 160 80 166 78 168 C74 150 68 124 66 102Z", + "M66 104 C70 100 74 96 78 94 C77 104 80 112 86 120 C92 126 96 130 97 134 C95 148 91 164 87 178 C84 184 79 184 76 178 C70 152 67 126 66 104Z", ], - "lower-back": ["M98 128 C93 130 90 140 88 152 C86 162 87 170 92 176 L98 178 Z"], - glutes: ["M98 178 C90 175 80 177 76 185 C73 195 76 207 84 213 C90 215 96 213 98 211 Z"], + "lower-back": ["M99 134 C94 136 91 146 90 158 C89 168 92 176 97 182 L99 184Z"], + "hip-abductors": ["M72 176 C67 182 65 192 67 204 C71 206 75 202 77 196 C78 188 77 181 72 176Z"], + glutes: ["M99 186 C92 183 82 184 77 190 C73 198 74 210 80 216 C87 220 94 218 99 214 Z"], hamstrings: [ - "M76 216 C72 232 71 250 73 266 C78 272 88 272 94 268 C96 250 97 230 98 216 C90 218 82 218 76 216Z", + "M76 220 C72 238 71 258 73 288 C78 296 88 296 94 290 C96 262 97 240 98 222 C90 224 82 224 76 220Z", ], calves: [ - "M75 282 C72 298 73 322 78 340 C80 346 86 348 90 344 C92 330 94 305 91 282 C86 284 80 284 75 282Z", + "M76 304 C72 318 73 336 78 348 C81 352 86 352 90 348 C93 336 94 318 91 304 C86 307 81 307 76 304Z", ], + soleus: ["M78 350 C79 358 80 366 82 372 L88 372 C89 364 90 356 90 350 C86 353 82 353 78 350Z"], }; // Non-interactive anatomy, drawn in a quiet neutral so the map reads as a body. export const DECOR_CENTER = [ - "M100 10 C108 10 116 18 116 28 C116 40 108 46 100 46 C92 46 84 40 84 28 C84 18 92 10 100 10Z", - "M93 44 L107 44 L107 58 L93 58Z", + "M100 8 C110 8 117 15 117 27 C117 40 110 52 100 52 C90 52 83 40 83 27 C83 15 90 8 100 8Z", + "M93 46 L107 46 L107 62 L93 62Z", ]; +const JOINTS = ["M52 160 C57 164 63 163 66 158 L65 171 C60 173 55 173 53 170Z"]; export const DECOR_LEFT_FRONT = [ - "M52 140 C56 143 62 142 65 139 L66 148 C61 149 56 149 51 148Z", - "M74 266 C80 272 88 272 93 268 L92 284 C86 286 80 286 76 284Z", - "M46 198 C44 208 45 216 49 220 C53 220 56 214 56 200Z", - "M78 362 C76 372 74 384 76 392 L90 392 C88 380 88 370 86 362Z", + ...JOINTS, + "M92 66 C84 70 72 74 62 78 L72 84 C78 80 88 76 99 76Z", + "M45 224 C43 234 44 242 48 246 C53 246 56 238 55 226Z", + "M76 296 C78 301 86 301 90 296 C89 306 87 308 83 308 C79 308 77 306 76 296Z", + "M78 372 C76 382 75 390 78 394 L92 394 C90 386 89 378 88 372Z", ]; export const DECOR_LEFT_BACK = [ - "M52 140 C56 143 62 142 65 139 L66 148 C61 149 56 149 51 148Z", - "M74 266 C80 272 88 272 93 268 L92 284 C86 286 80 286 76 284Z", - "M46 198 C44 208 45 216 49 220 C53 220 56 214 56 200Z", - "M78 342 C79 356 80 368 82 380 L88 380 C90 368 90 356 90 344Z", - "M78 380 C76 388 76 394 80 396 L90 396 C90 390 89 384 88 380Z", + ...JOINTS, + "M45 224 C43 234 44 242 48 246 C53 246 56 238 55 226Z", + "M76 292 C80 298 88 298 94 292 L93 304 C88 307 80 307 77 304Z", + "M78 372 C79 380 80 388 82 394 L90 394 C90 386 89 378 88 372Z", ]; // Fine fibre and striation lines, drawn inside each region at low contrast for anatomical definition. export const FRONT_LINES: Record = { - pectorals: ["M96 76 C88 76 80 79 74 84", "M96 86 C88 87 81 90 77 94"], - quadriceps: ["M84 204 C80 224 80 246 83 264", "M88 202 C86 226 86 248 88 266"], - biceps: ["M58 108 C57 120 58 132 60 140"], - "forearms-front": ["M54 152 C53 166 52 182 51 194"], - obliques: ["M77 112 L83 116", "M77 126 L83 130", "M78 140 L83 144"], - tibialis: ["M82 288 C82 312 83 336 84 356"], + pectorals: [ + "M96 88 C88 88 80 90 75 94", + "M96 98 C88 99 81 102 77 106", + "M96 108 C90 110 84 113 80 115", + ], + quadriceps: ["M84 222 C79 240 79 262 82 288", "M89 222 C86 244 86 266 88 290"], + biceps: ["M58 120 C57 132 58 146 60 158"], + "forearms-front": ["M55 172 C54 188 52 204 50 216"], + obliques: ["M77 150 L83 154", "M77 164 L83 168", "M78 178 L83 182"], + tibialis: ["M82 314 C82 332 83 350 84 366"], + "deltoid-front": ["M66 82 C65 94 64 104 64 112"], + neck: ["M94 58 C94 64 96 69 98 73"], }; export const BACK_LINES: Record = { - trapezius: ["M96 60 C90 70 90 88 94 110"], - lats: ["M72 100 C76 118 78 138 80 160", "M80 104 C82 122 84 140 84 152"], - glutes: ["M96 184 C88 184 82 190 80 200"], - hamstrings: ["M84 220 C83 238 84 256 86 266", "M90 220 C90 238 90 254 90 264"], - calves: ["M80 288 C79 306 81 326 84 340"], - triceps: ["M58 108 C57 120 58 132 60 140"], - "lower-back": ["M95 140 C93 152 93 164 95 174"], - "deltoid-rear": ["M62 72 C60 82 60 90 62 96"], + trapezius: ["M96 60 C90 70 90 84 96 98"], + lats: ["M72 104 C76 120 78 140 80 162", "M80 110 C84 128 86 146 84 162"], + glutes: ["M96 192 C88 192 82 198 80 208"], + hamstrings: ["M84 226 C83 244 84 264 86 288", "M90 226 C90 244 90 262 90 286"], + calves: ["M80 310 C79 322 81 336 84 346"], + triceps: ["M58 120 C57 132 58 146 60 158"], + "lower-back": ["M95 142 C93 154 93 168 95 178"], + "deltoid-rear": ["M62 80 C60 88 60 98 62 106"], }; + +// Whole-body anatomical landmarks (not muscles): collarbone, midline, rib hints, navel. +export const FRONT_LANDMARKS = [ + "M99 78 C90 77 80 77 70 80", + "M99 126 L99 196", + "M84 122 C88 124 94 125 98 124", +]; +export const BACK_LANDMARKS = ["M99 56 L99 184", "M62 80 C68 86 74 92 80 96"]; diff --git a/src/components/personal/body-map/muscle-explorer.tsx b/src/components/personal/body-map/muscle-explorer.tsx index 75f68c9c..7988ef7e 100644 --- a/src/components/personal/body-map/muscle-explorer.tsx +++ b/src/components/personal/body-map/muscle-explorer.tsx @@ -1,41 +1,123 @@ "use client"; import Link from "next/link"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useState } from "react"; import { ACTIVITIES, muscleLoad, type ActivityKey, type MuscleId } from "@/lib/personal/muscle-map"; +import { MUSCLE_IDS } from "@/lib/personal/muscle-map"; +import { loadBand, recencyBand, type Band, type ColorMode } from "@/lib/personal/load-bands"; +import type { MuscleTimeline } from "@/lib/personal/muscle-timeline"; import { daysAgoLabel, type MuscleTraining } from "@/lib/personal/muscle-training"; import { BodyMap } from "./body-map"; type Source = "planned" | "logged" | "preview"; type Window = 7 | 28 | 90; const WINDOWS: Window[] = [7, 28, 90]; +const REPLAY_STEP_MS = 650; export interface MuscleExplorerProps { /** Declared activities plus consented club visits, 0..1. */ planned: Record; /** Completed workouts per window; null when workout tracking is not available to this user. */ logged: Record | null; + /** Day-by-day trailing-week volume for the replay; null with `logged`. */ + timeline: MuscleTimeline | null; /** Latest logged girth per muscle, already worded (e.g. "Latest chest: 96 cm (2026-10-01)"). */ measurementNotes: Partial>; } -export function MuscleExplorer({ planned, logged, measurementNotes }: MuscleExplorerProps) { +function Segmented({ + label, + value, + options, + onChange, +}: { + label: string; + value: T; + options: { value: T; label: string; disabled?: boolean }[]; + onChange: (v: T) => void; +}) { + return ( +
    + {options.map((o) => ( + + ))} +
    + ); +} + +export function MuscleExplorer({ + planned, + logged, + timeline, + measurementNotes, +}: MuscleExplorerProps) { const hasLogged = logged !== null && logged[28].workouts + logged[90].workouts > 0; const [source, setSource] = useState(hasLogged ? "logged" : "planned"); const [days, setDays] = useState(28); + const [colorMode, setColorMode] = useState("volume"); const [lens, setLens] = useState(ACTIVITIES[0].key); + // Replay: null = off. Stepping through days is user-initiated, so it works under reduced motion too. + const [replay, setReplay] = useState<{ index: number; playing: boolean } | null>(null); const training = logged?.[days] ?? null; const lensDef = ACTIVITIES.find((a) => a.key === lens) ?? ACTIVITIES[0]; + const canReplay = source === "logged" && timeline !== null && timeline.max > 0; + const replayDay = replay && timeline ? timeline.days[replay.index] : null; + + useEffect(() => { + if (!replay?.playing || !timeline) return; + const id = window.setInterval(() => { + setReplay((cur) => { + if (!cur) return cur; + if (cur.index >= timeline.days.length - 1) return { index: cur.index, playing: false }; + return { index: cur.index + 1, playing: true }; + }); + }, REPLAY_STEP_MS); + return () => window.clearInterval(id); + }, [replay?.playing, timeline]); - const { load, notes, phrase } = useMemo(() => { + const view = useMemo(() => { const out: Partial> = {}; const push = (id: MuscleId, line: string) => (out[id] = [...(out[id] ?? []), line]); for (const [id, line] of Object.entries(measurementNotes) as [MuscleId, string][]) push(id, line); + if (source === "logged" && replayDay && timeline) { + const load = {} as Record; + for (const id of MUSCLE_IDS) { + const sets = replayDay.setEquivalents[id]; + load[id] = timeline.max === 0 ? 0 : Math.round((sets / timeline.max) * 1000) / 1000; + push( + id, + sets > 0 + ? `${sets} set-equivalents in the 7 days to ${replayDay.date}.` + : `Not worked in the 7 days to ${replayDay.date}.` + ); + } + return { + load, + bands: undefined, + mode: "volume" as ColorMode, + notes: out, + phrase: "of the busiest muscle in these four weeks", + }; + } if (source === "logged" && training) { - for (const id of Object.keys(training.load) as MuscleId[]) { + const bands = {} as Record; + for (const id of MUSCLE_IDS) { + bands[id] = + colorMode === "recent" + ? recencyBand(training.lastWorkedDaysAgo[id]) + : loadBand(training.load[id]); const sets = training.setEquivalents[id]; if (sets > 0) { const ago = training.lastWorkedDaysAgo[id]; @@ -52,6 +134,8 @@ export function MuscleExplorer({ planned, logged, measurementNotes }: MuscleExpl } return { load: training.load, + bands, + mode: colorMode, notes: out, phrase: "of your most-worked muscle in this period", }; @@ -61,51 +145,58 @@ export function MuscleExplorer({ planned, logged, measurementNotes }: MuscleExpl for (const id of lensDef.secondary) push(id, `${lensDef.label} also works this one.`); return { load: muscleLoad([{ key: lensDef.key, sessionsPerWeek: 1 }]), + bands: undefined, + mode: "volume" as ColorMode, notes: out, phrase: `of ${lensDef.label}'s heaviest muscle`, }; } - return { load: planned, notes: out, phrase: "of your most-worked muscle" }; - }, [source, training, days, lensDef, planned, measurementNotes]); + return { + load: planned, + bands: undefined, + mode: "volume" as ColorMode, + notes: out, + phrase: "of your most-worked muscle", + }; + }, [source, training, days, colorMode, lensDef, planned, measurementNotes, replayDay, timeline]); + + function chooseSource(next: Source) { + setSource(next); + setReplay(null); + } return (
    -
    - {( - [ - ["planned", "Planned"], - ["logged", "Logged"], - ["preview", "Preview"], - ] as [Source, string][] - ).map(([value, label]) => ( - - ))} -
    + + label="What to show" + value={source} + onChange={chooseSource} + options={[ + { value: "planned", label: "Planned" }, + { value: "logged", label: "Logged", disabled: logged === null }, + { value: "preview", label: "Preview" }, + ]} + /> - {source === "logged" && training && ( -
    - {WINDOWS.map((w) => ( - - ))} -
    + {source === "logged" && training && !replay && ( + <> + + label="Period" + value={days} + onChange={setDays} + options={WINDOWS.map((w) => ({ value: w, label: `${w} days` }))} + /> + + label="Colour by" + value={colorMode} + onChange={setColorMode} + options={[ + { value: "volume", label: "How much" }, + { value: "recent", label: "Last worked" }, + ]} + /> + )} {source === "preview" && ( @@ -127,7 +218,10 @@ export function MuscleExplorer({ planned, logged, measurementNotes }: MuscleExpl "Your declared activities, plus club visits you have allowed. Tap a muscle for details."} {source === "preview" && `What ${lensDef.label} trains. This is a preview, not your history.`} - {source === "logged" && training && training.workouts > 0 && ( + {source === "logged" && + replayDay && + "Replaying the last four weeks. Each day shows the week of training up to that day."} + {source === "logged" && !replayDay && training && training.workouts > 0 && ( <> {training.workouts} workout{training.workouts === 1 ? "" : "s"} in the last {days} days. {training.unmatchedExercises.length > 0 && ( @@ -139,7 +233,7 @@ export function MuscleExplorer({ planned, logged, measurementNotes }: MuscleExpl )} )} - {source === "logged" && training && training.workouts === 0 && ( + {source === "logged" && !replayDay && training && training.workouts === 0 && ( <> No workouts logged in the last {days} days.{" "} Log a workout @@ -150,7 +244,69 @@ export function MuscleExplorer({ planned, logged, measurementNotes }: MuscleExpl " Workout-based mapping appears here once workout tracking is available for your account."}

    - + + + {canReplay && timeline && ( +
    + {!replay ? ( + + ) : ( + <> +
    + + setReplay({ index: Number(e.target.value), playing: false })} + /> + + {replayDay?.date} + +
    + + + )} +
    + )}
    ); } diff --git a/src/lib/personal/exercise-catalog.ts b/src/lib/personal/exercise-catalog.ts index bbc4fb91..52048cfd 100644 --- a/src/lib/personal/exercise-catalog.ts +++ b/src/lib/personal/exercise-catalog.ts @@ -24,7 +24,7 @@ export const EXERCISES: readonly ExerciseDef[] = [ label: "Push-up", keywords: ["push up", "pushup", "press up"], primary: ["pectorals"], - secondary: ["triceps", "deltoid-front", "abs"], + secondary: ["triceps", "deltoid-front", "abs", "serratus"], }, { key: "chest-fly", @@ -66,14 +66,14 @@ export const EXERCISES: readonly ExerciseDef[] = [ label: "Rear delt work", keywords: ["rear delt", "reverse fly", "rear fly", "face pull"], primary: ["deltoid-rear"], - secondary: ["trapezius"], + secondary: ["trapezius", "rhomboids"], }, { key: "shrug", label: "Shrug", keywords: ["shrug"], primary: ["trapezius"], - secondary: ["forearms-back"], + secondary: ["forearms-back", "rhomboids", "neck"], }, { key: "pull-up", @@ -93,15 +93,15 @@ export const EXERCISES: readonly ExerciseDef[] = [ key: "row", label: "Row", keywords: ["row"], - primary: ["lats", "trapezius"], - secondary: ["biceps", "deltoid-rear", "lower-back"], + primary: ["lats", "rhomboids"], + secondary: ["biceps", "deltoid-rear", "lower-back", "trapezius"], }, { key: "deadlift", label: "Deadlift", keywords: ["deadlift"], primary: ["glutes", "hamstrings", "lower-back"], - secondary: ["trapezius", "forearms-front", "quadriceps", "lats"], + secondary: ["trapezius", "forearms-front", "quadriceps", "lats", "rhomboids"], }, { key: "romanian-deadlift", @@ -122,7 +122,7 @@ export const EXERCISES: readonly ExerciseDef[] = [ label: "Lunge", keywords: ["lunge", "split squat", "step up"], primary: ["quadriceps", "glutes"], - secondary: ["hamstrings", "adductors", "calves"], + secondary: ["hamstrings", "adductors", "calves", "hip-abductors"], }, { key: "leg-press", @@ -164,7 +164,7 @@ export const EXERCISES: readonly ExerciseDef[] = [ label: "Calf raise", keywords: ["calf raise", "calf press", "heel raise", "donkey calf"], primary: ["calves"], - secondary: [], + secondary: ["soleus"], }, { key: "tibialis", @@ -213,7 +213,7 @@ export const EXERCISES: readonly ExerciseDef[] = [ label: "Plank", keywords: ["plank", "hollow", "dead bug", "mountain climber"], primary: ["abs"], - secondary: ["obliques", "deltoid-front", "lower-back"], + secondary: ["obliques", "deltoid-front", "lower-back", "serratus"], }, { key: "leg-raise", @@ -265,26 +265,54 @@ export const EXERCISES: readonly ExerciseDef[] = [ primary: ["quadriceps", "glutes", "trapezius"], secondary: ["hamstrings", "deltoid-front", "lower-back"], }, + { + key: "seated-calf-raise", + label: "Seated calf raise", + keywords: ["seated calf"], + primary: ["soleus"], + secondary: ["calves"], + }, + { + key: "hip-abduction", + label: "Hip abduction", + keywords: ["abduction", "lateral band walk", "monster walk", "clamshell", "side leg raise"], + primary: ["hip-abductors"], + secondary: ["glutes"], + }, + { + key: "neck-work", + label: "Neck work", + keywords: ["neck curl", "neck extension", "neck bridge"], + primary: ["neck"], + secondary: ["trapezius"], + }, + { + key: "serratus", + label: "Serratus work", + keywords: ["serratus", "scapular push up", "scap push up", "pullover"], + primary: ["serratus", "lats"], + secondary: ["pectorals", "triceps"], + }, { key: "run", label: "Running", keywords: ["run", "jog", "treadmill", "sprint"], primary: ["quadriceps", "hamstrings", "calves", "glutes"], - secondary: ["hip-flexors", "tibialis", "abs"], + secondary: ["hip-flexors", "tibialis", "abs", "soleus", "hip-abductors"], }, { key: "cycle", label: "Cycling", keywords: ["cycle", "cycling", "bike", "spin"], primary: ["quadriceps", "glutes", "calves"], - secondary: ["hamstrings", "hip-flexors"], + secondary: ["hamstrings", "hip-flexors", "soleus"], }, { key: "swim", label: "Swimming", keywords: ["swim"], primary: ["lats", "deltoid-front", "deltoid-rear", "pectorals"], - secondary: ["triceps", "abs"], + secondary: ["triceps", "abs", "serratus"], }, { key: "burpee", diff --git a/src/lib/personal/load-bands.ts b/src/lib/personal/load-bands.ts new file mode 100644 index 00000000..1b998910 --- /dev/null +++ b/src/lib/personal/load-bands.ts @@ -0,0 +1,51 @@ +// Colour coding for the muscle map. Colour is never the only signal: every band also has a text label +// and a pattern in the SVG, so the map stays readable for colour-blind users and in print. + +export type Band = 0 | 1 | 2 | 3 | 4; +export type ColorMode = "volume" | "recent"; + +export interface BandInfo { + band: Band; + key: string; + label: string; + /** Short range text for the legend. */ + range: string; +} + +/** How much work a muscle got, relative to the most-worked muscle in the period. */ +export const VOLUME_BANDS: readonly BandInfo[] = [ + { band: 0, key: "none", label: "Not worked", range: "0%" }, + { band: 1, key: "light", label: "Light", range: "up to 25%" }, + { band: 2, key: "moderate", label: "Moderate", range: "26–50%" }, + { band: 3, key: "high", label: "High", range: "51–75%" }, + { band: 4, key: "peak", label: "Peak", range: "over 75%" }, +]; + +/** How long ago a muscle last got work. Descriptive only; it says nothing about readiness or recovery. */ +export const RECENCY_BANDS: readonly BandInfo[] = [ + { band: 0, key: "never", label: "Not in this period", range: "" }, + { band: 1, key: "old", label: "7+ days ago", range: "" }, + { band: 2, key: "mid", label: "3–6 days ago", range: "" }, + { band: 3, key: "recent", label: "1–2 days ago", range: "" }, + { band: 4, key: "today", label: "Today", range: "" }, +]; + +export function loadBand(load: number): Band { + if (!(load > 0)) return 0; + if (load <= 0.25) return 1; + if (load <= 0.5) return 2; + if (load <= 0.75) return 3; + return 4; +} + +export function recencyBand(daysAgo: number | undefined): Band { + if (daysAgo === undefined || !Number.isFinite(daysAgo)) return 0; + if (daysAgo <= 0) return 4; + if (daysAgo <= 2) return 3; + if (daysAgo <= 6) return 2; + return 1; +} + +export function bandInfo(mode: ColorMode, band: Band): BandInfo { + return (mode === "volume" ? VOLUME_BANDS : RECENCY_BANDS)[band]; +} diff --git a/src/lib/personal/muscle-explorer-service.ts b/src/lib/personal/muscle-explorer-service.ts index b3c435f1..27fa8251 100644 --- a/src/lib/personal/muscle-explorer-service.ts +++ b/src/lib/personal/muscle-explorer-service.ts @@ -1,6 +1,7 @@ import type { PrismaClient } from "@/generated/prisma/client"; import { OnboardingError } from "@/lib/club-onboarding"; import { getOverview } from "./personal-service"; +import { muscleTimeline, type MuscleTimeline } from "./muscle-timeline"; import { trainingFromWorkouts, type MuscleTraining } from "./muscle-training"; import { assertWellnessAdult, assertWellnessEnabled } from "./wellness-policy"; @@ -8,6 +9,8 @@ export const EXPLORER_WINDOWS = [7, 28, 90] as const; export type ExplorerWindow = (typeof EXPLORER_WINDOWS)[number]; const MAX_WORKOUTS = 400; +const TIMELINE_DAYS = 28; +const TIMELINE_TRAILING_DAYS = 7; /** * Everything the interactive muscle map needs, for the signed-in user only. @@ -16,14 +19,15 @@ const MAX_WORKOUTS = 400; */ export async function getMuscleExplorer(db: PrismaClient, userId: string, now = new Date()) { const overview = await getOverview(db, userId, now); - return { overview, logged: await loggedTraining(db, userId, now) }; + const result = await loggedTraining(db, userId, now); + return { overview, logged: result?.windows ?? null, timeline: result?.timeline ?? null }; } async function loggedTraining( db: PrismaClient, userId: string, now: Date -): Promise | null> { +): Promise<{ windows: Record; timeline: MuscleTimeline } | null> { try { assertWellnessEnabled(); await assertWellnessAdult(db, userId, now); @@ -51,7 +55,11 @@ async function loggedTraining( }, }, }); - return Object.fromEntries( + const windows = Object.fromEntries( EXPLORER_WINDOWS.map((days) => [days, trainingFromWorkouts(rows, days, now)]) ) as Record; + return { + windows, + timeline: muscleTimeline(rows, TIMELINE_DAYS, TIMELINE_TRAILING_DAYS, now), + }; } diff --git a/src/lib/personal/muscle-map.ts b/src/lib/personal/muscle-map.ts index 73b1c53b..8655d4b6 100644 --- a/src/lib/personal/muscle-map.ts +++ b/src/lib/personal/muscle-map.ts @@ -22,6 +22,12 @@ export const MUSCLE_GROUPS = [ { id: "hamstrings", label: "Hamstrings", side: "back", region: "lower" }, { id: "tibialis", label: "Shins", side: "front", region: "lower" }, { id: "calves", label: "Calves", side: "back", region: "lower" }, + // Added in v2 of the illustration. Existing ids are never renamed or split. + { id: "neck", label: "Neck", side: "front", region: "upper" }, + { id: "serratus", label: "Serratus", side: "front", region: "core" }, + { id: "rhomboids", label: "Rhomboids", side: "back", region: "upper" }, + { id: "hip-abductors", label: "Hip abductors", side: "back", region: "lower" }, + { id: "soleus", label: "Soleus", side: "back", region: "lower" }, ] as const; export type MuscleId = (typeof MUSCLE_GROUPS)[number]["id"]; @@ -62,43 +68,52 @@ export const ACTIVITIES: readonly ActivityDef[] = [ key: "gym-lifting", label: "Gym / strength", primary: ["pectorals", "lats", "quadriceps", "glutes", "deltoid-front"], - secondary: ["biceps", "triceps", "hamstrings", "abs", "lower-back", "trapezius"], + secondary: [ + "biceps", + "triceps", + "hamstrings", + "abs", + "lower-back", + "trapezius", + "rhomboids", + "serratus", + ], }, { key: "running", label: "Running", primary: ["quadriceps", "hamstrings", "calves", "glutes"], - secondary: ["hip-flexors", "tibialis", "abs"], + secondary: ["hip-flexors", "tibialis", "abs", "soleus", "hip-abductors"], }, { key: "cycling", label: "Cycling", primary: ["quadriceps", "glutes", "calves"], - secondary: ["hamstrings", "hip-flexors", "lower-back"], + secondary: ["hamstrings", "hip-flexors", "lower-back", "soleus"], }, { key: "swimming", label: "Swimming", primary: ["lats", "deltoid-front", "deltoid-rear", "pectorals"], - secondary: ["triceps", "abs", "quadriceps", "calves"], + secondary: ["triceps", "abs", "quadriceps", "calves", "serratus", "rhomboids"], }, { key: "yoga", label: "Yoga", primary: ["abs", "hamstrings", "hip-flexors", "lower-back"], - secondary: ["deltoid-side", "quadriceps", "glutes", "adductors", "triceps"], + secondary: ["deltoid-side", "quadriceps", "glutes", "adductors", "triceps", "hip-abductors"], }, { key: "dance", label: "Dance", primary: ["quadriceps", "calves", "glutes", "abs"], - secondary: ["hamstrings", "adductors", "obliques", "tibialis"], + secondary: ["hamstrings", "adductors", "obliques", "tibialis", "hip-abductors", "soleus"], }, { key: "football", label: "Football", primary: ["quadriceps", "hamstrings", "calves", "hip-flexors"], - secondary: ["glutes", "adductors", "abs", "tibialis"], + secondary: ["glutes", "adductors", "abs", "tibialis", "hip-abductors", "soleus"], }, { key: "cricket", @@ -116,19 +131,19 @@ export const ACTIVITIES: readonly ActivityDef[] = [ key: "tennis", label: "Tennis", primary: ["forearms-front", "obliques", "deltoid-side", "quadriceps"], - secondary: ["lats", "glutes", "calves", "triceps"], + secondary: ["lats", "glutes", "calves", "triceps", "serratus"], }, { key: "boxing", label: "Boxing", primary: ["deltoid-front", "triceps", "obliques", "pectorals"], - secondary: ["abs", "lats", "calves", "forearms-front", "trapezius"], + secondary: ["abs", "lats", "calves", "forearms-front", "trapezius", "neck", "serratus"], }, { key: "climbing", label: "Climbing", primary: ["lats", "forearms-front", "biceps", "forearms-back"], - secondary: ["deltoid-rear", "abs", "trapezius", "quadriceps"], + secondary: ["deltoid-rear", "abs", "trapezius", "quadriceps", "rhomboids"], }, ]; diff --git a/src/lib/personal/muscle-timeline.ts b/src/lib/personal/muscle-timeline.ts new file mode 100644 index 00000000..ffe6ffef --- /dev/null +++ b/src/lib/personal/muscle-timeline.ts @@ -0,0 +1,36 @@ +import { MUSCLE_IDS, type MuscleId } from "./muscle-map"; +import { trainingFromWorkouts, type WorkoutLike } from "./muscle-training"; + +// A day-by-day replay of the map: for each of the last N days, the training volume in the trailing +// window ending that day. Descriptive only, from the user's own completed workouts. + +export interface TimelineDay { + /** UTC calendar date of the "as of" moment, YYYY-MM-DD. */ + date: string; + setEquivalents: Record; +} +export interface MuscleTimeline { + /** Oldest first, so playing the array forward replays history in order. */ + days: TimelineDay[]; + /** The largest single-muscle volume across the whole timeline; the shared scale for every day. */ + max: number; +} + +const DAY_MS = 86_400_000; + +export function muscleTimeline( + workouts: readonly WorkoutLike[], + dayCount: number, + trailingDays: number, + now: Date +): MuscleTimeline { + const days: TimelineDay[] = []; + let max = 0; + for (let i = dayCount - 1; i >= 0; i--) { + const asOf = new Date(now.getTime() - i * DAY_MS); + const t = trainingFromWorkouts(workouts, trailingDays, asOf); + for (const id of MUSCLE_IDS) max = Math.max(max, t.setEquivalents[id]); + days.push({ date: asOf.toISOString().slice(0, 10), setEquivalents: t.setEquivalents }); + } + return { days, max }; +} diff --git a/tests/integration/personal-service.test.mjs b/tests/integration/personal-service.test.mjs index 809d41d0..546687e9 100644 --- a/tests/integration/personal-service.test.mjs +++ b/tests/integration/personal-service.test.mjs @@ -271,3 +271,25 @@ test("the muscle explorer maps only the signed-in user's own workouts", async () }); }); }); + +test("the replay timeline covers 28 days for the user's own workouts and is absent when gated off", async () => { + await inRolledBackTx(async (tx) => { + const me = await newUser(tx, "tl"); + const other = await newUser(tx, "tlo"); + for (const u of [me, other]) await svc.updateBio(tx, u.id, { birthYear: 1990 }); + await addWorkout(tx, me.id, 3, ["Bench press"]); + for (let i = 0; i < 6; i++) await addWorkout(tx, other.id, i, ["Pull-up"]); // never mine + + await withWellness("false", async () => { + assert.equal((await explorer.getMuscleExplorer(tx, me.id, NOW)).timeline, null); + }); + await withWellness("true", async () => { + const { timeline } = await explorer.getMuscleExplorer(tx, me.id, NOW); + assert.equal(timeline.days.length, 28); + assert.equal(timeline.days[27].date, "2026-11-18"); + assert.ok(timeline.max > 0); + assert.ok(timeline.days.every((d) => d.setEquivalents.lats === 0)); // the other user's pull-ups + assert.ok(timeline.days[27].setEquivalents.pectorals > 0); + }); + }); +}); diff --git a/tests/unit/personal-load-bands.test.mjs b/tests/unit/personal-load-bands.test.mjs new file mode 100644 index 00000000..a10df4dc --- /dev/null +++ b/tests/unit/personal-load-bands.test.mjs @@ -0,0 +1,85 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { register } from "node:module"; + +register("../integration/helpers/src-alias-hook.mjs", import.meta.url); +const bands = await import("../../src/lib/personal/load-bands.ts"); +const { muscleTimeline } = await import("../../src/lib/personal/muscle-timeline.ts"); +const { MUSCLE_IDS } = await import("../../src/lib/personal/muscle-map.ts"); + +test("volume bands split at 25, 50 and 75 percent and treat bad input as not worked", () => { + assert.equal(bands.loadBand(0), 0); + assert.equal(bands.loadBand(-1), 0); + assert.equal(bands.loadBand(Number.NaN), 0); + assert.equal(bands.loadBand(0.01), 1); + assert.equal(bands.loadBand(0.25), 1); + assert.equal(bands.loadBand(0.26), 2); + assert.equal(bands.loadBand(0.5), 2); + assert.equal(bands.loadBand(0.75), 3); + assert.equal(bands.loadBand(0.751), 4); + assert.equal(bands.loadBand(1), 4); +}); + +test("recency bands run from today down to not in this period", () => { + assert.equal(bands.recencyBand(undefined), 0); + assert.equal(bands.recencyBand(0), 4); + assert.equal(bands.recencyBand(1), 3); + assert.equal(bands.recencyBand(2), 3); + assert.equal(bands.recencyBand(3), 2); + assert.equal(bands.recencyBand(6), 2); + assert.equal(bands.recencyBand(7), 1); + assert.equal(bands.recencyBand(60), 1); +}); + +test("every band has a distinct text label so colour is never the only signal", () => { + for (const list of [bands.VOLUME_BANDS, bands.RECENCY_BANDS]) { + assert.equal(list.length, 5); + assert.equal(new Set(list.map((b) => b.label)).size, 5); + list.forEach((b, i) => assert.equal(b.band, i)); + } + assert.equal(bands.bandInfo("volume", 4).label, "Peak"); + assert.equal(bands.bandInfo("recent", 4).label, "Today"); +}); + +const NOW = new Date("2026-11-19T12:00:00Z"); +const ago = (d) => new Date(NOW.getTime() - d * 86_400_000); +const bench = (d) => ({ + endedAt: ago(d), + activityKey: "gym-lifting", + durationMinutes: 60, + exercises: [ + { + name: "Bench press", + sets: [ + { reps: 8, weightGrams: 60000 }, + { reps: 8, weightGrams: 60000 }, + ], + }, + ], +}); + +test("the timeline is oldest first, ends today and shares one scale", () => { + const t = muscleTimeline([bench(10), bench(2)], 28, 7, NOW); + assert.equal(t.days.length, 28); + assert.equal(t.days[27].date, "2026-11-19"); + assert.equal(t.days[0].date, "2026-10-23"); + assert.ok(t.max >= 2); + for (const d of t.days) + assert.deepEqual(Object.keys(d.setEquivalents).sort(), [...MUSCLE_IDS].sort()); +}); + +test("a workout shows in the trailing window for exactly the days that include it", () => { + const t = muscleTimeline([bench(10)], 28, 7, NOW); + const chest = t.days.map((d) => d.setEquivalents.pectorals); + // Workout was 10 days ago (index 17). It is inside the 7-day window for index 17 through 24. + assert.equal(chest[16], 0); + assert.equal(chest[17], 2); + assert.equal(chest[24], 2); + assert.equal(chest[25], 0); +}); + +test("with no workouts the timeline is all zero and max is 0", () => { + const t = muscleTimeline([], 28, 7, NOW); + assert.equal(t.max, 0); + assert.ok(t.days.every((d) => Object.values(d.setEquivalents).every((v) => v === 0))); +});