Complete workout recording baseline and project context

This commit is contained in:
rob
2026-11-04 21:41:17 +00:00
parent e86a2e7850
commit 669bfc3910
29 changed files with 3288 additions and 297 deletions
+183 -16
View File
@@ -1,28 +1,192 @@
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { Button, Container, Nav, Navbar } from 'react-bootstrap'
import { exerciseDefinitions, initialRoutine } from './data/index.js'
import { addCalendarDays, loadLabel, localCalendarDate, localDateKey, prescriptionLabel, restLabel, routineForDate, startOfWeek } from './routineView.js'
import HangGoalEditor from './HangGoalEditor.jsx'
import StrengthEntryEditor from './StrengthEntryEditor.jsx'
import { readDailyHangGoal, writeDailyHangGoal } from './hangGoalStorage.js'
const sections = [
{ id: 'today', label: 'Today', title: 'Your workout, at a glance', description: 'Your daily sessions will appear here when the routine is added.' },
{ id: 'week', label: 'Week', title: 'The week ahead', description: 'The seven-day programme will appear here when the routine is added.' },
{ id: 'today', label: 'Today', title: "Today's plan" },
{ id: 'week', label: 'Week', title: 'Your week' },
{ id: 'history', label: 'History', title: 'Your training history', description: 'Completed workouts will appear here once tracking is available.' },
{ id: 'plan', label: 'Plan', title: 'Your training plan', description: 'Routine editing will become available in a later task.' },
{ id: 'settings', label: 'Settings', title: 'Your data and preferences', description: 'Local backup and app settings will become available in a later task.' },
]
const exerciseNames = new Map(exerciseDefinitions.map(({ id, name }) => [id, name]))
const initialHangGoalSeconds = initialRoutine.days.monday.afternoon.exercises.find(({ exerciseId }) => exerciseId === 'daily-hang').prescription.goalDurationSec
const dateFormatter = new Intl.DateTimeFormat('en-IE', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })
const weekdayFormatter = new Intl.DateTimeFormat('en-IE', { weekday: 'short' })
const weekFormatter = new Intl.DateTimeFormat('en-IE', { day: 'numeric', month: 'long', year: 'numeric' })
const clockFormatter = new Intl.DateTimeFormat('en-IE', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false })
function WallClock() {
const [currentTime, setCurrentTime] = useState(() => new Date())
useEffect(() => {
const refresh = () => setCurrentTime(new Date())
const id = window.setInterval(refresh, 1000)
window.addEventListener('focus', refresh)
document.addEventListener('visibilitychange', refresh)
return () => {
window.clearInterval(id)
window.removeEventListener('focus', refresh)
document.removeEventListener('visibilitychange', refresh)
}
}, [])
return <span className="wall-clock"><span>Local time</span><time aria-label="Current local time" aria-live="off">{clockFormatter.format(currentTime)}</time></span>
}
function savedPeriod() {
try {
return window.localStorage.getItem('workout-period') === 'afternoon' ? 'afternoon' : 'morning'
} catch {
return 'morning'
}
}
function ExerciseList({ exercises, dateKey, hangGoalSeconds, hangGoalLoading, hangGoalError, onSaveHangGoal }) {
return (
<ol className="exercise-list">
{exercises.map(({ order, exerciseId, prescription, optional, rest, load }) => (
<li className="exercise-card" key={`${order}-${exerciseId}`}>
<span className="exercise-number" aria-hidden="true">{order}</span>
<div className="exercise-copy">
<div className="exercise-title-row">
<h3>{exerciseNames.get(exerciseId)}</h3>
{optional && <span className="optional-tag">Optional</span>}
</div>
<p className="prescription">{prescriptionLabel(exerciseId === 'daily-hang' ? { ...prescription, goalDurationSec: hangGoalSeconds } : prescription)}</p>
{(rest || load) && <p className="exercise-meta">{[restLabel(rest), loadLabel(load)].filter(Boolean).join(' · ')}</p>}
{(['emom', 'repetitions'].includes(prescription.kind) || ['suitcase-carry', 'front-plank'].includes(exerciseId)) && <StrengthEntryEditor key={`${dateKey}-${exerciseId}`} dateKey={dateKey} exerciseId={exerciseId} kind={prescription.kind === 'emom' ? 'emom' : ['suitcase-carry', 'front-plank'].includes(exerciseId) ? 'load-sets' : 'sets'} load={load} />}
{exerciseId === 'daily-hang' && <HangGoalEditor goalSeconds={hangGoalSeconds} loading={hangGoalLoading} storageError={hangGoalError} onSave={onSaveHangGoal} />}
</div>
</li>
))}
</ol>
)
}
function RoutineView({ selectedDate, setSelectedDate, period, setPeriod, setActiveId, hangGoalSeconds, hangGoalLoading, hangGoalError, onSaveHangGoal }) {
const today = localCalendarDate(new Date())
const weekStart = startOfWeek(selectedDate)
const days = Array.from({ length: 7 }, (_, index) => addCalendarDays(weekStart, index))
const routine = routineForDate(selectedDate)
const session = routine[period]
const isToday = localDateKey(selectedDate) === localDateKey(today)
function chooseDate(date) {
setSelectedDate(date)
setActiveId(localDateKey(date) === localDateKey(today) ? 'today' : 'week')
}
function changePeriod(nextPeriod) {
setPeriod(nextPeriod)
try {
window.localStorage.setItem('workout-period', nextPeriod)
} catch {
// The period still works for this page if browser storage is unavailable.
}
}
return (
<div className="routine-view">
<div className="period-switch" role="group" aria-label="Workout period">
{['morning', 'afternoon'].map((value) => (
<Button key={value} type="button" variant="link" aria-pressed={period === value} onClick={() => changePeriod(value)}>
{value === 'morning' ? 'Morning' : 'Afternoon'}
</Button>
))}
</div>
<div className="week-controls">
<Button type="button" variant="link" onClick={() => chooseDate(addCalendarDays(selectedDate, -7))} aria-label="Previous week">← Previous week</Button>
<span className="week-range">Week of {weekFormatter.format(days[0])}</span>
<Button type="button" variant="link" onClick={() => chooseDate(addCalendarDays(selectedDate, 7))} aria-label="Next week">Next week →</Button>
</div>
<nav className="day-strip" aria-label="Choose workout date">
{days.map((date) => {
const selected = localDateKey(date) === localDateKey(selectedDate)
return (
<Button
key={localDateKey(date)}
type="button"
variant="link"
className="day-button"
aria-label={dateFormatter.format(date)}
aria-pressed={selected}
onClick={() => chooseDate(date)}
>
<span>{weekdayFormatter.format(date)}</span>
<strong>{date.getDate()}</strong>
</Button>
)
})}
</nav>
<section className="routine-panel" aria-labelledby="session-title">
<div className="routine-heading">
<div>
<p className="panel-kicker">{isToday ? 'Today' : dateFormatter.format(selectedDate)} · {period}</p>
<h2 id="session-title">{session.title}</h2>
</div>
{session.exercises.length > 0 && <span className="session-count">{session.exercises.length} exercises</span>}
</div>
{session.targetEffortRpe && <p className="session-guidance">Target effort: RPE {session.targetEffortRpe.min}–{session.targetEffortRpe.max} · One round to start; a second round only if recovery remains good.</p>}
{session.exercises.length > 0 && <ExerciseList exercises={session.exercises} dateKey={localDateKey(selectedDate)} hangGoalSeconds={hangGoalSeconds} hangGoalLoading={hangGoalLoading} hangGoalError={hangGoalError} onSaveHangGoal={onSaveHangGoal} />}
</section>
<p className="shell-note">Enter actual reps and the relevant weights for strength work. Other recording will be added later.</p>
</div>
)
}
export default function App() {
const [activeId, setActiveId] = useState('today')
const [selectedDate, setSelectedDate] = useState(() => localCalendarDate(new Date()))
const [period, setPeriod] = useState(savedPeriod)
const [hangGoalSeconds, setHangGoalSeconds] = useState(initialHangGoalSeconds)
const [hangGoalLoading, setHangGoalLoading] = useState(true)
const [hangGoalError, setHangGoalError] = useState('')
const activeSection = sections.find((section) => section.id === activeId)
const showingRoutine = activeId === 'today' || activeId === 'week'
useEffect(() => {
let mounted = true
readDailyHangGoal().then((savedGoal) => {
if (!mounted) return
if (savedGoal != null) setHangGoalSeconds(savedGoal)
setHangGoalLoading(false)
}).catch((error) => {
if (!mounted) return
setHangGoalError(error.message)
setHangGoalLoading(false)
})
return () => { mounted = false }
}, [])
async function saveHangGoal(seconds) {
await writeDailyHangGoal(seconds)
setHangGoalSeconds(seconds)
setHangGoalError('')
}
function selectSection(id) {
setActiveId(id)
if (id === 'today') setSelectedDate(localCalendarDate(new Date()))
}
return (
<div className="app-shell">
<a className="skip-link" href="#main-content">Skip to content</a>
<Navbar className="site-header" aria-label="Main navigation">
<Container className="header-inner">
<Navbar.Brand className="brand" href="#main-content" onClick={() => setActiveId('today')}>
<Navbar.Brand className="brand" href="#main-content" onClick={() => selectSection('today')}>
<span className="brand-mark" aria-hidden="true">W</span>
<span>Workout Tracker</span>
</Navbar.Brand>
<span className="header-note">A private space to keep moving</span>
<span className="header-trailing"><span className="header-note">A private space to keep moving</span><WallClock /></span>
</Container>
</Navbar>
@@ -31,7 +195,7 @@ export default function App() {
<div>
<p className="eyebrow">YOUR TRAINING SPACE</p>
<h1>{activeSection.title}</h1>
<p className="intro">A simple place for your plan, sessions and progress.</p>
<p className="intro">{showingRoutine ? 'Browse your week and choose the session you want to see.' : 'A simple place for your plan, sessions and progress.'}</p>
</div>
<span className="local-badge">Local to this browser</span>
</div>
@@ -43,7 +207,7 @@ export default function App() {
className="section-link"
variant="link"
aria-current={activeId === section.id ? 'page' : undefined}
onClick={() => setActiveId(section.id)}
onClick={() => selectSection(section.id)}
>
{section.label}
</Button>
@@ -52,15 +216,18 @@ export default function App() {
</Nav>
<main id="main-content" tabIndex="-1">
<section className="content-panel" aria-labelledby="panel-title">
<div className="panel-icon" aria-hidden="true">{activeId === 'today' ? '↗' : '•'}</div>
<div>
<p className="panel-kicker">{activeSection.label}</p>
<h2 id="panel-title">A clear place to begin</h2>
<p>{activeSection.description}</p>
</div>
</section>
<p className="shell-note">Your workout data will stay on this device when local storage is added.</p>
{showingRoutine ? (
<RoutineView selectedDate={selectedDate} setSelectedDate={setSelectedDate} period={period} setPeriod={setPeriod} setActiveId={setActiveId} hangGoalSeconds={hangGoalSeconds} hangGoalLoading={hangGoalLoading} hangGoalError={hangGoalError} onSaveHangGoal={saveHangGoal} />
) : (
<section className="content-panel" aria-labelledby="panel-title">
<div className="panel-icon" aria-hidden="true">•</div>
<div>
<p className="panel-kicker">{activeSection.label}</p>
<h2 id="panel-title">A clear place to begin</h2>
<p>{activeSection.description}</p>
</div>
</section>
)}
</main>
</Container>
</div>
+79 -10
View File
@@ -1,15 +1,84 @@
import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import App from './App.jsx'
describe('application shell', () => {
it('shows the Today section and changes sections without workout behavior', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(new Date(2026, 9, 25, 12))
window.localStorage.clear()
})
afterEach(() => {
cleanup()
vi.useRealTimers()
})
describe('routine navigation', () => {
it('keeps the large local clock across views without workout timers', () => {
render(<App />)
expect(screen.getByRole('heading', { level: 1, name: 'Your workout, at a glance' })).toBeTruthy()
const week = screen.getByRole('button', { name: 'Week' })
fireEvent.click(week)
expect(screen.getByRole('heading', { level: 1, name: 'The week ahead' })).toBeTruthy()
expect(week.getAttribute('aria-current')).toBe('page')
expect(screen.getByRole('main')).toBeTruthy()
const clock = screen.getByLabelText('Current local time')
expect(clock.textContent).toBe('12:00:00')
expect(screen.queryByRole('region', { name: 'Workout timers' })).toBeNull()
expect(screen.queryByRole('button', { name: /Start EMOM|Start workout clock|Sound on|Sound off/ })).toBeNull()
act(() => vi.advanceTimersByTime(2000))
expect(clock.textContent).toBe('12:00:02')
fireEvent.click(screen.getByRole('button', { name: 'History' }))
expect(screen.getByLabelText('Current local time')).toBe(clock)
})
it('shows today’s morning exercises without dog walks', () => {
render(<App />)
expect(screen.getByRole('heading', { level: 1, name: "Today's plan" })).toBeTruthy()
expect(screen.getByRole('heading', { name: 'Push 2 — Shoulders + Triceps + Core' })).toBeTruthy()
expect(screen.getByText('Standing single-arm dumbbell shoulder press')).toBeTruthy()
expect(screen.getByText('Single-arm triceps extensions')).toBeTruthy()
expect(screen.getByText('Optional')).toBeTruthy()
expect(screen.queryByText('Daily hanging practice')).toBeNull()
expect(screen.queryByText(/dog walks/i)).toBeNull()
})
it('shows one period, preserves it across date changes, and remembers it locally', () => {
const view = render(<App />)
fireEvent.click(screen.getByRole('button', { name: 'Afternoon' }))
expect(screen.getByText('Daily hanging practice')).toBeTruthy()
expect(screen.queryByText('Standing single-arm dumbbell shoulder press')).toBeNull()
expect(screen.getByRole('button', { name: 'Afternoon' }).getAttribute('aria-pressed')).toBe('true')
expect(window.localStorage.getItem('workout-period')).toBe('afternoon')
fireEvent.click(screen.getByRole('button', { name: /Monday.*19 October 2026/ }))
expect(screen.getByText('Daily hanging practice')).toBeTruthy()
expect(screen.getByText('Target effort: RPE 5–6 · One round to start; a second round only if recovery remains good.')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
expect(screen.getByText('Week of 26 October 2026')).toBeTruthy()
expect(screen.getByRole('button', { name: 'Afternoon' }).getAttribute('aria-pressed')).toBe('true')
view.unmount()
render(<App />)
expect(screen.getByRole('button', { name: 'Afternoon' }).getAttribute('aria-pressed')).toBe('true')
fireEvent.click(screen.getByRole('button', { name: 'Today' }))
expect(screen.getByRole('heading', { name: 'Afternoon isometrics and daily hang' })).toBeTruthy()
})
it('shows the stretch routine heading without invented movements and uses focusable buttons', () => {
render(<App />)
const monday = screen.getByRole('button', { name: /Monday.*19 October 2026/ })
monday.focus()
expect(document.activeElement).toBe(monday)
fireEvent.click(monday)
expect(screen.getByRole('heading', { name: 'Full body stretch routine' })).toBeTruthy()
expect(screen.queryByText('Rest day')).toBeNull()
expect(document.querySelectorAll('.exercise-card')).toHaveLength(0)
expect(screen.queryByText('Pull-ups')).toBeNull()
expect(window.localStorage.length).toBe(0)
expect(screen.getByRole('button', { name: 'Morning' }).getAttribute('aria-pressed')).toBe('true')
})
it('keeps existing top-level sections accessible', () => {
render(<App />)
fireEvent.click(screen.getByRole('button', { name: 'History' }))
expect(screen.getByRole('heading', { level: 1, name: 'Your training history' })).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Today' }))
expect(screen.getByRole('heading', { name: 'Push 2 — Shoulders + Triceps + Core' })).toBeTruthy()
})
})
+40
View File
@@ -0,0 +1,40 @@
import { useEffect, useState } from 'react'
import { Button } from 'react-bootstrap'
export default function HangGoalEditor({ goalSeconds, loading, storageError, onSave }) {
const [draft, setDraft] = useState(String(goalSeconds))
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
useEffect(() => setDraft(String(goalSeconds)), [goalSeconds])
async function submit(event) {
event.preventDefault()
const seconds = Number(draft)
if (!Number.isSafeInteger(seconds) || seconds <= 0) {
setError('Enter a whole number of seconds above zero.')
return
}
setSaving(true)
setError('')
try {
await onSave(seconds)
} catch (saveError) {
setError(saveError.message || 'Could not save the hanging goal.')
} finally {
setSaving(false)
}
}
return (
<div className="hang-goal-editor">
<form onSubmit={submit}>
<label htmlFor="daily-hang-goal">Hang goal (seconds)</label>
<input id="daily-hang-goal" type="number" min="1" step="1" value={draft} disabled={loading || saving} onChange={(event) => setDraft(event.target.value)} />
<Button type="submit" size="sm" variant="outline-success" disabled={loading || saving}>Save goal</Button>
</form>
{loading && <p role="status">Loading saved goal…</p>}
{(error || storageError) && <p className="goal-error" role="alert">{error || storageError}</p>}
</div>
)
}
+55
View File
@@ -0,0 +1,55 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const saved = vi.hoisted(() => ({ goal: null, fail: false }))
vi.mock('./hangGoalStorage.js', () => ({
readDailyHangGoal: vi.fn(async () => saved.goal),
writeDailyHangGoal: vi.fn(async (seconds) => {
if (saved.fail) throw new Error('Could not save the hanging goal.')
saved.goal = seconds
}),
}))
import App from './App.jsx'
beforeEach(() => {
saved.goal = null
saved.fail = false
window.localStorage.clear()
})
afterEach(() => cleanup())
describe('daily hanging goal', () => {
it('changes the goal across days and reloads without hold times or vest details', async () => {
const view = render(<App />)
fireEvent.click(screen.getByRole('button', { name: 'Afternoon' }))
await waitFor(() => expect(screen.getByLabelText('Hang goal (seconds)').disabled).toBe(false))
expect(screen.getByText('Goal: 2 min')).toBeTruthy()
expect(screen.getByText('Deep squat hold').closest('.exercise-card').querySelector('.prescription').textContent).toBe('Hold')
expect(screen.queryByText(/Vest load not specified/)).toBeNull()
fireEvent.change(screen.getByLabelText('Hang goal (seconds)'), { target: { value: '180' } })
fireEvent.click(screen.getByRole('button', { name: 'Save goal' }))
await screen.findByText('Goal: 3 min')
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
expect(screen.getByText('Goal: 3 min')).toBeTruthy()
view.unmount()
render(<App />)
fireEvent.click(screen.getByRole('button', { name: 'Afternoon' }))
await screen.findByText('Goal: 3 min')
})
it('shows a save failure without changing the displayed goal', async () => {
saved.fail = true
render(<App />)
fireEvent.click(screen.getByRole('button', { name: 'Afternoon' }))
await waitFor(() => expect(screen.getByLabelText('Hang goal (seconds)').disabled).toBe(false))
fireEvent.change(screen.getByLabelText('Hang goal (seconds)'), { target: { value: '240' } })
fireEvent.click(screen.getByRole('button', { name: 'Save goal' }))
expect((await screen.findByRole('alert')).textContent).toMatch(/Could not save/)
expect(screen.getByText('Goal: 2 min')).toBeTruthy()
})
})
+142
View File
@@ -0,0 +1,142 @@
import { useEffect, useState } from 'react'
import { Button } from 'react-bootstrap'
import { fieldsForExercise, totalExternalKg } from './strengthLoad.js'
import { readStrengthEntry, writeStrengthEntry } from './strengthStorage.js'
function emptyWeight(load) {
const fields = fieldsForExercise(load)
return { load: fields.length ? Object.fromEntries(fields.map(({ key }) => [key, ''])) : { bodyweightOnly: true } }
}
function weightDraft(record, load) {
if (!record) return emptyWeight(load)
if (!record.load || (record.load.bodyweightOnly && fieldsForExercise(load).length > 0)) return { legacy: true, externalKg: String(record.externalKg) }
return { load: Object.fromEntries(Object.entries(record.load).map(([key, value]) => [key, typeof value === 'number' ? String(value) : value])) }
}
function emptySet(load, previous) {
return { reps: '', ...(previous ? previous.legacy ? { legacy: true, externalKg: previous.externalKg } : { load: { ...previous.load } } : emptyWeight(load)) }
}
function entryDraft(entry, kind, load) {
if (kind === 'emom') return { totalReps: entry?.totalReps?.toString() ?? '', ...weightDraft(entry, load) }
return entry?.sets?.map((row) => ({ reps: row.reps?.toString() ?? '', ...weightDraft(row, load) })) ?? [emptySet(load)]
}
function numberFromInput(value, whole) {
if (String(value).trim() === '') return null
const number = Number(value)
return Number.isFinite(number) && number >= 0 && (!whole || Number.isSafeInteger(number)) ? number : null
}
function recordedWeight(draft) {
if (draft.legacy) {
const externalKg = numberFromInput(draft.externalKg, false)
return externalKg == null ? null : { externalKg }
}
const load = Object.fromEntries(Object.entries(draft.load).map(([key, value]) => [key, key === 'bodyweightOnly' ? value : numberFromInput(value, false)]))
const externalKg = totalExternalKg(load)
return externalKg == null ? null : { externalKg, load }
}
export default function StrengthEntryEditor({ dateKey, exerciseId, kind, load }) {
const fields = fieldsForExercise(load)
const [draft, setDraft] = useState(() => entryDraft(null, kind, load))
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const [saved, setSaved] = useState(false)
useEffect(() => {
let active = true
readStrengthEntry(dateKey, exerciseId).then((entry) => {
if (!active) return
setDraft(entryDraft(entry, kind, load))
setLoading(false)
}).catch((failure) => {
if (!active) return
setError(failure.message)
setLoading(false)
})
return () => { active = false }
}, [dateKey, exerciseId, kind, load])
function updateSet(index, field, value) {
setDraft((rows) => rows.map((row, rowIndex) => rowIndex === index
? field === 'reps' || field === 'externalKg' ? { ...row, [field]: value } : { ...row, load: { ...row.load, [field]: value } }
: row))
setSaved(false)
}
function updateEmom(field, value) {
setDraft((current) => field === 'totalReps' || field === 'externalKg'
? { ...current, [field]: value }
: { ...current, load: { ...current.load, [field]: value } })
setSaved(false)
}
function replaceLegacyWeight(index) {
if (index == null) setDraft((current) => ({ totalReps: current.totalReps, ...emptyWeight(load) }))
else setDraft((rows) => rows.map((row, rowIndex) => rowIndex === index ? { reps: row.reps, ...emptyWeight(load) } : row))
setSaved(false)
}
function weightInputs(row, index) {
const prefix = index == null ? '' : `Set ${index + 1} `
if (row.legacy) return <>
<label>Previously recorded total external weight (kg)<input type="number" min="0" step="any" aria-label={`${prefix}previously recorded total external weight (kg)`} value={row.externalKg} disabled={loading || saving} onChange={(event) => index == null ? updateEmom('externalKg', event.target.value) : updateSet(index, 'externalKg', event.target.value)} /></label>
{fields.length > 0 && <Button type="button" variant="link" disabled={loading || saving} onClick={() => replaceLegacyWeight(index)}>Enter specific weights</Button>}
</>
if (fields.length === 0) return <small>No added weight</small>
return fields.map(({ key, label }) => <label key={key}>{label}<input type="number" min="0" step="any" aria-label={`${prefix}${label.toLowerCase()}`} value={row.load[key]} disabled={loading || saving} onChange={(event) => index == null ? updateEmom(key, event.target.value) : updateSet(index, key, event.target.value)} /></label>)
}
async function save(event) {
event.preventDefault()
const entry = kind === 'emom'
? { kind, totalReps: numberFromInput(draft.totalReps, true), ...recordedWeight(draft) }
: { kind, sets: draft.map((row) => ({ ...(kind === 'load-sets' ? {} : { reps: numberFromInput(row.reps, true) }), ...recordedWeight(row) })) }
if (kind === 'emom' ? entry.totalReps == null || entry.externalKg == null : entry.sets.some(({ reps, externalKg }) => (kind !== 'load-sets' && reps == null) || externalKg == null)) {
setError(kind === 'load-sets' ? 'Enter each shown weight as zero or more kilograms for every row.' : 'Enter whole-number reps and each shown weight as zero or more kilograms for every row.')
return
}
setSaving(true)
setError('')
try {
await writeStrengthEntry(dateKey, exerciseId, entry)
setSaved(true)
} catch (failure) {
setError(failure.message)
setSaved(false)
} finally {
setSaving(false)
}
}
return (
<form className="strength-entry" onSubmit={save}>
<strong>{kind === 'emom' ? 'Record EMOM total' : 'Record sets'}</strong>
{kind === 'emom' ? (
<div className="strength-fields">
<label>Total reps<input type="number" min="0" step="1" value={draft.totalReps} disabled={loading || saving} onChange={(event) => updateEmom('totalReps', event.target.value)} /></label>
{weightInputs(draft, null)}
</div>
) : (
<>
{draft.map((row, index) => (
<div className="strength-set" key={index}>
<span>Set {index + 1}</span>
{kind !== 'load-sets' && <label>Reps<input type="number" min="0" step="1" aria-label={`Set ${index + 1} reps`} value={row.reps} disabled={loading || saving} onChange={(event) => updateSet(index, 'reps', event.target.value)} /></label>}
{weightInputs(row, index)}
{draft.length > 1 && <Button type="button" variant="link" disabled={loading || saving} onClick={() => { setDraft((rows) => rows.filter((_, rowIndex) => rowIndex !== index)); setSaved(false) }}>Remove</Button>}
</div>
))}
<Button type="button" variant="outline-secondary" size="sm" disabled={loading || saving} onClick={() => { setDraft((rows) => [...rows, emptySet(load, rows.at(-1))]); setSaved(false) }}>Add set</Button>
</>
)}
<div className="strength-actions"><Button type="submit" size="sm" disabled={loading || saving}>{saving ? 'Saving…' : kind === 'load-sets' ? 'Save weight' : 'Save reps and weight'}</Button>{saved && <span role="status">Saved</span>}</div>
{error && <p className="strength-error" role="alert">{error}</p>}
<small>Record actual weights, not prescribed targets. Body weight is excluded.</small>
</form>
)
}
+229
View File
@@ -0,0 +1,229 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const saved = vi.hoisted(() => ({ entries: new Map(), fail: false }))
vi.mock('./strengthStorage.js', () => ({
readStrengthEntry: vi.fn(async (dateKey, exerciseId) => saved.entries.get(`${dateKey}:${exerciseId}`) ?? null),
writeStrengthEntry: vi.fn(async (dateKey, exerciseId, entry) => {
if (saved.fail) throw new Error('Could not save the strength entry.')
saved.entries.set(`${dateKey}:${exerciseId}`, entry)
}),
}))
vi.mock('./hangGoalStorage.js', () => ({ readDailyHangGoal: vi.fn(async () => null), writeDailyHangGoal: vi.fn(async () => {}) }))
import App from './App.jsx'
beforeEach(() => {
saved.entries.clear()
saved.fail = false
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(new Date(2026, 9, 27, 12))
window.localStorage.clear()
})
afterEach(() => {
cleanup()
vi.useRealTimers()
})
describe('strength recording without timers', () => {
it('saves one EMOM total and actual external weight by date', async () => {
const view = render(<App />)
const pullUps = screen.getByText('Pull-ups').closest('.exercise-card')
await waitFor(() => expect(within(pullUps).getByLabelText('Total reps').disabled).toBe(false))
expect(within(pullUps).getByText('10 min EMOM · 3–4 reps each minute')).toBeTruthy()
expect(screen.queryByRole('region', { name: 'Workout timers' })).toBeNull()
expect(screen.queryByRole('button', { name: /Start EMOM|Start workout clock|Sound on|Sound off/ })).toBeNull()
fireEvent.change(within(pullUps).getByLabelText('Total reps'), { target: { value: '36' } })
fireEvent.change(within(pullUps).getByLabelText('vest weight (kg)'), { target: { value: '6' } })
fireEvent.click(within(pullUps).getByRole('button', { name: 'Save reps and weight' }))
await within(pullUps).findByText('Saved')
expect(saved.entries.get('2026-10-27:pull-up')).toEqual({ kind: 'emom', totalReps: 36, externalKg: 6, load: { vestKg: 6 } })
view.unmount()
render(<App />)
const again = screen.getByText('Pull-ups').closest('.exercise-card')
await waitFor(() => expect(within(again).getByLabelText('Total reps').value).toBe('36'))
expect(within(again).getByLabelText('vest weight (kg)').value).toBe('6')
})
it('saves separate regular sets and keeps dates separate', async () => {
render(<App />)
fireEvent.click(screen.getByRole('button', { name: 'Previous week' }))
fireEvent.click(screen.getByRole('button', { name: /Sunday.*25 October 2026/ }))
const press = screen.getByText('Standing single-arm dumbbell shoulder press').closest('.exercise-card')
await waitFor(() => expect(within(press).getByLabelText('Set 1 reps').disabled).toBe(false))
fireEvent.change(within(press).getByLabelText('Set 1 reps'), { target: { value: '10' } })
fireEvent.change(within(press).getByLabelText('Set 1 dumbbell weight (kg)'), { target: { value: '12' } })
fireEvent.click(within(press).getByRole('button', { name: 'Add set' }))
expect(within(press).getByLabelText('Set 2 dumbbell weight (kg)').value).toBe('12')
expect(within(press).getByLabelText('Set 2 reps').value).toBe('')
fireEvent.change(within(press).getByLabelText('Set 2 reps'), { target: { value: '8' } })
fireEvent.change(within(press).getByLabelText('Set 2 dumbbell weight (kg)'), { target: { value: '14' } })
fireEvent.click(within(press).getByRole('button', { name: 'Add set' }))
expect(within(press).getByLabelText('Set 3 dumbbell weight (kg)').value).toBe('14')
fireEvent.change(within(press).getByLabelText('Set 3 reps'), { target: { value: '7' } })
fireEvent.click(within(press).getByRole('button', { name: 'Save reps and weight' }))
await within(press).findByText('Saved')
expect(saved.entries.get('2026-10-25:single-arm-shoulder-press')).toEqual({ kind: 'sets', sets: [{ reps: 10, externalKg: 12, load: { dumbbellKg: 12 } }, { reps: 8, externalKg: 14, load: { dumbbellKg: 14 } }, { reps: 7, externalKg: 14, load: { dumbbellKg: 14 } }] })
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
fireEvent.click(screen.getByRole('button', { name: /Sunday.*1 November 2026/ }))
const future = screen.getByText('Standing single-arm dumbbell shoulder press').closest('.exercise-card')
await waitFor(() => expect(within(future).getByLabelText('Set 1 reps').disabled).toBe(false))
expect(within(future).getByLabelText('Set 1 reps').value).toBe('')
expect(saved.entries.size).toBe(1)
})
it('records flys as dumbbell weight per dumbbell, without a vest field', async () => {
render(<App />)
fireEvent.click(screen.getByRole('button', { name: /Wednesday.*28 October 2026/ }))
const flys = screen.getByText('Dumbbell floor flys').closest('.exercise-card')
await waitFor(() => expect(within(flys).getByLabelText('Set 1 dumbbell weight (kg each)').disabled).toBe(false))
expect(within(flys).queryByLabelText(/vest weight/i)).toBeNull()
fireEvent.change(within(flys).getByLabelText('Set 1 reps'), { target: { value: '12' } })
fireEvent.change(within(flys).getByLabelText('Set 1 dumbbell weight (kg each)'), { target: { value: '8' } })
fireEvent.click(within(flys).getByRole('button', { name: 'Add set' }))
expect(within(flys).getByLabelText('Set 2 dumbbell weight (kg each)').value).toBe('8')
fireEvent.change(within(flys).getByLabelText('Set 2 reps'), { target: { value: '10' } })
fireEvent.click(within(flys).getByRole('button', { name: 'Save reps and weight' }))
await within(flys).findByText('Saved')
expect(saved.entries.get('2026-10-28:dumbbell-floor-fly')).toEqual({ kind: 'sets', sets: [
{ reps: 12, externalKg: 16, load: { dumbbellKgEach: 8 } },
{ reps: 10, externalKg: 16, load: { dumbbellKgEach: 8 } },
] })
})
it('keeps vest and dumbbell weights separate for mixed-load sets', async () => {
render(<App />)
fireEvent.click(screen.getByRole('button', { name: /Thursday.*29 October 2026/ }))
const squats = screen.getByText('Squats').closest('.exercise-card')
await waitFor(() => expect(within(squats).getByLabelText('Set 1 vest weight (kg)').disabled).toBe(false))
fireEvent.change(within(squats).getByLabelText('Set 1 reps'), { target: { value: '10' } })
fireEvent.change(within(squats).getByLabelText('Set 1 vest weight (kg)'), { target: { value: '10' } })
fireEvent.change(within(squats).getByLabelText('Set 1 dumbbell weight (kg each)'), { target: { value: '12' } })
fireEvent.click(within(squats).getByRole('button', { name: 'Add set' }))
expect(within(squats).getByLabelText('Set 2 vest weight (kg)').value).toBe('10')
expect(within(squats).getByLabelText('Set 2 dumbbell weight (kg each)').value).toBe('12')
fireEvent.change(within(squats).getByLabelText('Set 2 reps'), { target: { value: '8' } })
fireEvent.click(within(squats).getByRole('button', { name: 'Save reps and weight' }))
await within(squats).findByText('Saved')
expect(saved.entries.get('2026-10-29:squat')).toEqual({ kind: 'sets', sets: [
{ reps: 10, externalKg: 34, load: { vestKg: 10, dumbbellKgEach: 12 } },
{ reps: 8, externalKg: 34, load: { vestKg: 10, dumbbellKgEach: 12 } },
] })
})
it('keeps older total-weight entries as totals rather than reinterpreting them', async () => {
saved.entries.set('2026-10-27:ez-bar-bent-over-row', { kind: 'sets', sets: [{ reps: 10, externalKg: 25 }] })
render(<App />)
const rows = screen.getByText('EZ-bar bent-over rows').closest('.exercise-card')
await waitFor(() => expect(within(rows).getByLabelText('Set 1 previously recorded total external weight (kg)').value).toBe('25'))
fireEvent.click(within(rows).getByRole('button', { name: 'Add set' }))
expect(within(rows).getByLabelText('Set 2 previously recorded total external weight (kg)').value).toBe('25')
fireEvent.change(within(rows).getByLabelText('Set 2 reps'), { target: { value: '8' } })
fireEvent.click(within(rows).getByRole('button', { name: 'Save reps and weight' }))
await within(rows).findByText('Saved')
expect(saved.entries.get('2026-10-27:ez-bar-bent-over-row')).toEqual({ kind: 'sets', sets: [{ reps: 10, externalKg: 25 }, { reps: 8, externalKg: 25 }] })
fireEvent.click(within(rows).getAllByRole('button', { name: 'Enter specific weights' })[0])
expect(within(rows).getByLabelText('Set 1 ez-bar total weight (kg)').value).toBe('')
fireEvent.change(within(rows).getByLabelText('Set 1 ez-bar total weight (kg)'), { target: { value: '25' } })
fireEvent.click(within(rows).getByRole('button', { name: 'Save reps and weight' }))
await within(rows).findByText('Saved')
expect(saved.entries.get('2026-10-27:ez-bar-bent-over-row')).toEqual({ kind: 'sets', sets: [{ reps: 10, externalKg: 25, load: { ezBarTotalKg: 25 } }, { reps: 8, externalKg: 25 }] })
})
it('records suitcase-carry weights per set without requiring reps and restores them', async () => {
const view = render(<App />)
const carry = screen.getByText('Suitcase carries').closest('.exercise-card')
await waitFor(() => expect(within(carry).getByLabelText('Set 1 dumbbell weight (kg)').disabled).toBe(false))
expect(within(carry).queryByLabelText(/reps/i)).toBeNull()
expect(within(carry).queryByLabelText(/vest/i)).toBeNull()
fireEvent.click(within(carry).getByRole('button', { name: 'Save weight' }))
expect(within(carry).getByRole('alert').textContent).toMatch(/each shown weight/)
fireEvent.change(within(carry).getByLabelText('Set 1 dumbbell weight (kg)'), { target: { value: '20' } })
fireEvent.click(within(carry).getByRole('button', { name: 'Add set' }))
expect(within(carry).getByLabelText('Set 2 dumbbell weight (kg)').value).toBe('20')
fireEvent.change(within(carry).getByLabelText('Set 2 dumbbell weight (kg)'), { target: { value: '0' } })
fireEvent.click(within(carry).getByRole('button', { name: 'Save weight' }))
await within(carry).findByText('Saved')
expect(saved.entries.get('2026-10-27:suitcase-carry')).toEqual({ kind: 'load-sets', sets: [
{ externalKg: 20, load: { dumbbellKg: 20 } },
{ externalKg: 0, load: { dumbbellKg: 0 } },
] })
view.unmount()
render(<App />)
const restored = screen.getByText('Suitcase carries').closest('.exercise-card')
await waitFor(() => expect(within(restored).getByLabelText('Set 1 dumbbell weight (kg)').value).toBe('20'))
expect(within(restored).getByLabelText('Set 2 dumbbell weight (kg)').value).toBe('0')
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
const nextWeek = screen.getByText('Suitcase carries').closest('.exercise-card')
await waitFor(() => expect(within(nextWeek).getByLabelText('Set 1 dumbbell weight (kg)').disabled).toBe(false))
expect(within(nextWeek).getByLabelText('Set 1 dumbbell weight (kg)').value).toBe('')
expect(saved.entries.size).toBe(1)
})
it.each([
['Thursday', '29 October 2026', 'Front plank', 'front-plank', '2026-10-29', 'load-sets'],
['Sunday', '1 November 2026', 'Side-plank hip raises', 'side-plank-hip-raise', '2026-11-01', 'sets'],
])('records vest weights for %s plank work without irrelevant load fields', async (day, date, name, id, dateKey, kind) => {
const view = render(<App />)
fireEvent.click(screen.getByRole('button', { name: new RegExp(`${day}.*${date}`) }))
const card = screen.getByText(name).closest('.exercise-card')
await waitFor(() => expect(within(card).getByLabelText('Set 1 vest weight (kg)').disabled).toBe(false))
expect(within(card).queryByLabelText(/dumbbell|bar total/i)).toBeNull()
expect(within(card).getByLabelText('Set 1 vest weight (kg)').value).toBe('')
if (kind === 'load-sets') expect(within(card).queryByLabelText(/reps/i)).toBeNull()
else fireEvent.change(within(card).getByLabelText('Set 1 reps'), { target: { value: '12' } })
fireEvent.change(within(card).getByLabelText('Set 1 vest weight (kg)'), { target: { value: '6' } })
fireEvent.click(within(card).getByRole('button', { name: 'Add set' }))
expect(within(card).getByLabelText('Set 2 vest weight (kg)').value).toBe('6')
fireEvent.change(within(card).getByLabelText('Set 2 vest weight (kg)'), { target: { value: '0' } })
if (kind === 'sets') fireEvent.change(within(card).getByLabelText('Set 2 reps'), { target: { value: '10' } })
fireEvent.click(within(card).getByRole('button', { name: kind === 'sets' ? 'Save reps and weight' : 'Save weight' }))
await within(card).findByText('Saved')
expect(saved.entries.get(`${dateKey}:${id}`)).toEqual({ kind, sets: [
{ ...(kind === 'sets' ? { reps: 12 } : {}), externalKg: 6, load: { vestKg: 6 } },
{ ...(kind === 'sets' ? { reps: 10 } : {}), externalKg: 0, load: { vestKg: 0 } },
] })
view.unmount()
render(<App />)
fireEvent.click(screen.getByRole('button', { name: new RegExp(`${day}.*${date}`) }))
const restored = screen.getByText(name).closest('.exercise-card')
await waitFor(() => expect(within(restored).getByLabelText('Set 1 vest weight (kg)').value).toBe('6'))
expect(within(restored).getByLabelText('Set 2 vest weight (kg)').value).toBe('0')
})
it('keeps historical bodyweight-only hip raises until explicitly entering vest weights', async () => {
const old = { kind: 'sets', sets: [{ reps: 12, externalKg: 0, load: { bodyweightOnly: true } }] }
saved.entries.set('2026-11-01:side-plank-hip-raise', old)
render(<App />)
fireEvent.click(screen.getByRole('button', { name: /Sunday.*1 November 2026/ }))
const card = screen.getByText('Side-plank hip raises').closest('.exercise-card')
await waitFor(() => expect(within(card).getByLabelText('Set 1 previously recorded total external weight (kg)').value).toBe('0'))
expect(saved.entries.get('2026-11-01:side-plank-hip-raise')).toEqual(old)
fireEvent.click(within(card).getByRole('button', { name: 'Enter specific weights' }))
expect(within(card).getByLabelText('Set 1 vest weight (kg)').value).toBe('')
fireEvent.change(within(card).getByLabelText('Set 1 vest weight (kg)'), { target: { value: '5' } })
fireEvent.click(within(card).getByRole('button', { name: 'Save reps and weight' }))
await within(card).findByText('Saved')
expect(saved.entries.get('2026-11-01:side-plank-hip-raise')).toEqual({ kind: 'sets', sets: [{ reps: 12, externalKg: 5, load: { vestKg: 5 } }] })
})
it('rejects incomplete rows and shows storage failures', async () => {
saved.fail = true
render(<App />)
const pullUps = screen.getByText('Pull-ups').closest('.exercise-card')
await waitFor(() => expect(within(pullUps).getByLabelText('Total reps').disabled).toBe(false))
fireEvent.click(within(pullUps).getByRole('button', { name: 'Save reps and weight' }))
expect(within(pullUps).getByRole('alert').textContent).toMatch(/whole-number reps/)
expect(saved.entries.size).toBe(0)
fireEvent.change(within(pullUps).getByLabelText('Total reps'), { target: { value: '0' } })
fireEvent.change(within(pullUps).getByLabelText('vest weight (kg)'), { target: { value: '0' } })
fireEvent.click(within(pullUps).getByRole('button', { name: 'Save reps and weight' }))
await waitFor(() => expect(within(pullUps).getByRole('alert').textContent).toMatch(/Could not save/))
})
})
+15
View File
@@ -0,0 +1,15 @@
# Initial routine data
`exerciseDefinitions.json` holds stable IDs, names, and categories. `initialRoutine.json` holds the versioned seven-day prescription and refers to definitions by ID. Neither file contains completed workout records or user edits.
Each day has separate `morning` and `afternoon` sessions. An exercise's `order` is one-based within its session. A `{ "min", "max" }` pair preserves a documented range; equal bounds represent a single target. Durations use seconds unless the field says `Min`. `null` means the source does not specify a value, especially for current hanging ability, finger-hang duration, and unknown loads. A `goalDurationSec` is a goal, not an achieved duration.
Loads keep vest, dumbbell, and EZ-bar components separate. The 6 kg and 10 kg values are prescribed vest settings only. The source is [`docs/WORKOUT_ROUTINE.md`](../../docs/WORKOUT_ROUTINE.md); any approved change to the initial programme must update that document and this seed together. A future broader storage adapter must copy this seed only when creating a new local routine, then preserve user edits and history.
Strength entry fields follow each exercise's `load` keys. `dumbbellKgEach` means the mass of each of two dumbbells; `dumbbellKg` means one dumbbell. Mixed `vestKg` and dumbbell keys produce separate inputs. Actual entries do not assume the seed's prescribed weights. New records retain components and a derived total external weight; older entries with only `externalKg` remain legacy totals.
Afternoon isometric holds have no prescribed duration. The daily hang starts with a two-minute goal but no vest field. A user-changed hanging goal is stored separately in IndexedDB by `hangGoalStorage.js`; seed updates must not overwrite it.
Suitcase carries also expose their single-dumbbell load as dated weight-only set entries (`kind: load-sets`). These contain actual load and derived external kilograms, without fabricated repetitions or performed duration. The carry duration-per-side prescription remains separate. Existing repetition sets and EMOM totals are unchanged; no IndexedDB store upgrade is needed.
Seed v7 adds vest-only support (`vestKg: null`) to front planks and side-plank hip raises without prescribing a numeric load. Front planks reuse weight-only `load-sets`; hip raises retain repetition sets. Historical bodyweight-only entries remain prior totals until the user explicitly chooses component entry. No database migration is required.
+32
View File
@@ -0,0 +1,32 @@
[
{"id":"pull-up","name":"Pull-ups","category":"strength"},
{"id":"ez-bar-bent-over-row","name":"EZ-bar bent-over rows","category":"strength"},
{"id":"single-arm-dumbbell-row","name":"Single-arm dumbbell rows","category":"strength"},
{"id":"suitcase-carry","name":"Suitcase carries","category":"strength"},
{"id":"weighted-deep-push-up","name":"Weighted deep push-ups using dumbbells as handles","category":"strength"},
{"id":"dumbbell-floor-fly","name":"Dumbbell floor flys","category":"strength"},
{"id":"push-up-plus","name":"Push-up plus","category":"strength"},
{"id":"feet-elevated-weighted-push-up","name":"Feet-elevated weighted push-ups","category":"strength"},
{"id":"bulgarian-split-squat","name":"Bulgarian split squats","category":"strength"},
{"id":"single-leg-romanian-deadlift","name":"Single-leg Romanian deadlifts","category":"strength"},
{"id":"squat","name":"Squats","category":"strength"},
{"id":"single-leg-calf-raise","name":"Single-leg calf raises","category":"strength"},
{"id":"front-plank","name":"Front plank","category":"strength"},
{"id":"chin-up","name":"Chin-ups","category":"strength"},
{"id":"hanging-knee-raise","name":"Hanging knee raises","category":"strength"},
{"id":"finger-hang","name":"Finger hangs","category":"strength"},
{"id":"single-arm-preacher-curl","name":"Single-arm preacher curls over a chair","category":"strength"},
{"id":"hammer-curl","name":"Hammer curls","category":"strength"},
{"id":"single-arm-shoulder-press","name":"Standing single-arm dumbbell shoulder press","category":"strength"},
{"id":"leaning-single-arm-lateral-raise","name":"Leaning single-arm lateral raises","category":"strength"},
{"id":"bent-over-rear-delt-fly","name":"Bent-over rear-delt flys","category":"strength"},
{"id":"lying-dumbbell-triceps-extension","name":"Lying dumbbell triceps extensions","category":"strength"},
{"id":"single-arm-triceps-extension","name":"Single-arm triceps extensions","category":"strength"},
{"id":"side-plank-hip-raise","name":"Side-plank hip raises","category":"strength"},
{"id":"deep-squat-hold","name":"Deep squat hold","category":"isometric"},
{"id":"ninety-ninety-hip-hold","name":"90/90 hip hold","category":"isometric"},
{"id":"bird-dog-hold","name":"Bird-dog hold","category":"isometric"},
{"id":"single-leg-balance","name":"Single-leg balance","category":"isometric"},
{"id":"prone-swimmer-iso","name":"Prone swimmer iso","category":"isometric"},
{"id":"daily-hang","name":"Daily hanging practice","category":"hang"}
]
+4
View File
@@ -0,0 +1,4 @@
import exerciseDefinitions from './exerciseDefinitions.json'
import initialRoutine from './initialRoutine.json'
export { exerciseDefinitions, initialRoutine }
File diff suppressed because it is too large Load Diff
+107
View File
@@ -0,0 +1,107 @@
import { describe, expect, it } from 'vitest'
import { exerciseDefinitions, initialRoutine } from './index.js'
const weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
const isometricIds = ['deep-squat-hold', 'ninety-ninety-hip-hold', 'bird-dog-hold', 'single-leg-balance', 'prone-swimmer-iso']
const morningIds = {
monday: [],
tuesday: ['pull-up', 'ez-bar-bent-over-row', 'single-arm-dumbbell-row', 'suitcase-carry'],
wednesday: ['weighted-deep-push-up', 'dumbbell-floor-fly', 'push-up-plus', 'feet-elevated-weighted-push-up'],
thursday: ['bulgarian-split-squat', 'single-leg-romanian-deadlift', 'squat', 'single-leg-calf-raise', 'front-plank'],
friday: [],
saturday: ['chin-up', 'hanging-knee-raise', 'finger-hang', 'single-arm-preacher-curl', 'hammer-curl'],
sunday: ['single-arm-shoulder-press', 'leaning-single-arm-lateral-raise', 'bent-over-rear-delt-fly', 'lying-dumbbell-triceps-extension', 'single-arm-triceps-extension', 'side-plank-hip-raise'],
}
const exercise = (day, period, id) => initialRoutine.days[day][period].exercises.find((item) => item.exerciseId === id)
const range = (min, max = min) => ({ min, max })
describe('documented initial routine', () => {
it('is versioned, has one stable definition per used exercise, and retains every day and exercise order', () => {
expect(initialRoutine.version).toBe(7)
expect(initialRoutine.source).toBe('docs/WORKOUT_ROUTINE.md')
expect(Object.keys(initialRoutine.days)).toEqual(weekdays)
const definitionIds = exerciseDefinitions.map(({ id }) => id)
expect(new Set(definitionIds).size).toBe(definitionIds.length)
const usedIds = new Set()
for (const day of weekdays) {
const sessions = initialRoutine.days[day]
expect(sessions.morning.sessionType).toBe(day === 'monday' || day === 'friday' ? 'stretching' : 'strength')
expect(sessions.morning.exercises.map(({ exerciseId }) => exerciseId)).toEqual(morningIds[day])
expect(sessions.afternoon.sessionType).toBe('isometrics-and-hang')
expect(sessions.afternoon.exercises.map(({ exerciseId }) => exerciseId)).toEqual([...isometricIds, 'daily-hang'])
expect(sessions).not.toHaveProperty('walks')
for (const session of Object.values(sessions)) {
expect(session.exercises.map(({ order }) => order)).toEqual(session.exercises.map((_, index) => index + 1))
for (const item of session.exercises) {
expect(definitionIds).toContain(item.exerciseId)
expect(typeof item.optional).toBe('boolean')
usedIds.add(item.exerciseId)
}
}
}
expect([...usedIds].sort()).toEqual([...definitionIds].sort())
expect(definitionIds).toHaveLength(30)
expect(definitionIds).not.toContain('dog-walk')
expect(initialRoutine).not.toHaveProperty('activityReference')
expect(exerciseDefinitions.some(({ category }) => category === 'stretch')).toBe(false)
})
it('preserves strength ranges, EMOM timing, rest, and separate known and unknown load components', () => {
for (const [day, id] of [['tuesday', 'pull-up'], ['saturday', 'chin-up']]) {
const item = exercise(day, 'morning', id)
expect(item.prescription).toMatchObject({ kind: 'emom', rounds: 10, intervalSec: 60, repsPerRound: range(3, 4) })
expect(item.rest).toEqual({ kind: 'remainder-of-interval', intervalSec: 60 })
expect(item.load).toEqual({ vestKg: 6 })
}
expect(exercise('tuesday', 'morning', 'pull-up').prescription.initialRepsPerRound).toBe(4)
expect(exercise('tuesday', 'morning', 'single-arm-dumbbell-row').prescription).toMatchObject({ sets: range(3, 4), reps: range(8, 15), per: 'side' })
expect(exercise('tuesday', 'morning', 'suitcase-carry').prescription).toMatchObject({ sets: range(3), durationSec: range(30, 60), per: 'side' })
expect(exercise('wednesday', 'morning', 'weighted-deep-push-up').load).toEqual({ vestKg: 10 })
expect(exercise('wednesday', 'morning', 'feet-elevated-weighted-push-up').load).toEqual({ vestKg: 10 })
expect(exercise('wednesday', 'morning', 'dumbbell-floor-fly').load).toEqual({ dumbbellKgEach: null })
expect(exercise('thursday', 'morning', 'bulgarian-split-squat').load).toEqual({ vestKg: 10, dumbbellKgEach: null })
expect(exercise('thursday', 'morning', 'squat').load).toEqual({ vestKg: 10, dumbbellKgEach: null })
expect(exercise('thursday', 'morning', 'front-plank').prescription.durationSec).toEqual(range(30, 60))
expect(exercise('thursday', 'morning', 'front-plank').load).toEqual({ vestKg: null })
expect(exercise('sunday', 'morning', 'side-plank-hip-raise').load).toEqual({ vestKg: null })
expect(exercise('saturday', 'morning', 'finger-hang').prescription).toMatchObject({ sets: range(2, 3), durationSec: null })
expect(exercise('sunday', 'morning', 'single-arm-triceps-extension')).toMatchObject({ optional: true, prescription: { sets: range(2, 3), reps: range(10, 15), per: 'arm' } })
expect(initialRoutine.days.sunday.morning.exercises.filter(({ optional }) => optional).map(({ exerciseId }) => exerciseId)).toEqual(['single-arm-triceps-extension'])
})
it('keeps untimed afternoon holds and daily hanging practice separate from Saturday finger hangs', () => {
const efforts = {
monday: range(5, 6), tuesday: range(3, 4), wednesday: range(3, 4),
thursday: range(3, 4), friday: range(6, 7), saturday: range(3, 4), sunday: range(3, 4),
}
for (const day of weekdays) {
const afternoon = initialRoutine.days[day].afternoon
expect(afternoon.targetEffortRpe).toEqual(efforts[day])
expect(afternoon.exercises.slice(0, 5).every(({ prescription }) => prescription.kind === 'isometric-hold' && !('durationSec' in prescription))).toBe(true)
expect(afternoon.exercises[1].prescription.per).toBe('side')
expect(afternoon.exercises[2].prescription.per).toBe('side')
expect(afternoon.exercises[3].prescription.per).toBe('leg')
expect(afternoon.initialRounds).toBe(1)
expect(afternoon.optionalProgressionRounds).toBe(2)
expect(afternoon.progressionCondition).toBe('Only if recovery remains good')
expect(afternoon).not.toHaveProperty('restBetweenHoldsSec')
expect(afternoon.targetsAreMandatory).toBe(false)
expect(exercise(day, 'afternoon', 'daily-hang')).toMatchObject({
prescription: { goalDurationSec: 120, currentDurationSec: null, attemptCount: null, breaks: null, goalFormat: null },
})
expect(exercise(day, 'afternoon', 'daily-hang')).not.toHaveProperty('load')
}
expect(exercise('saturday', 'morning', 'finger-hang').exerciseId).not.toBe(exercise('saturday', 'afternoon', 'daily-hang').exerciseId)
})
it('keeps Monday and Friday stretch headings free of unspecified exercises', () => {
for (const day of ['monday', 'friday']) {
const morning = initialRoutine.days[day].morning
expect(morning).toEqual({ sessionType: 'stretching', title: 'Full body stretch routine', exercises: [] })
}
})
})
+34
View File
@@ -0,0 +1,34 @@
import { openLocalDatabase } from './localDatabase.js'
const STORE_NAME = 'routineOverrides'
const GOAL_KEY = 'dailyHangGoalSec'
export async function readDailyHangGoal() {
const db = await openLocalDatabase()
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readonly')
const request = transaction.objectStore(STORE_NAME).get(GOAL_KEY)
request.onsuccess = () => {
const value = request.result
if (value == null) resolve(null)
else if (Number.isSafeInteger(value) && value > 0) resolve(value)
else reject(new Error('The saved hanging goal is invalid.'))
}
request.onerror = () => reject(new Error('Could not read the hanging goal.'))
transaction.oncomplete = () => db.close()
transaction.onerror = () => { db.close(); reject(new Error('Could not read the hanging goal.')) }
transaction.onabort = () => { db.close(); reject(new Error('Could not read the hanging goal.')) }
})
}
export async function writeDailyHangGoal(seconds) {
if (!Number.isSafeInteger(seconds) || seconds <= 0) throw new Error('Enter a whole number of seconds above zero.')
const db = await openLocalDatabase()
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite')
transaction.objectStore(STORE_NAME).put(seconds, GOAL_KEY)
transaction.oncomplete = () => { db.close(); resolve() }
transaction.onerror = () => { db.close(); reject(new Error('Could not save the hanging goal.')) }
transaction.onabort = () => { db.close(); reject(new Error('Could not save the hanging goal.')) }
})
}
+74
View File
@@ -0,0 +1,74 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { readDailyHangGoal, writeDailyHangGoal } from './hangGoalStorage.js'
function memoryIndexedDB() {
const values = new Map()
const stores = new Set()
const db = {
objectStoreNames: { contains: (name) => stores.has(name) },
createObjectStore: (name) => stores.add(name),
close() {},
transaction() {
const transaction = {
objectStore() {
return {
get(key) {
const request = {}
queueMicrotask(() => {
request.result = values.get(key)
request.onsuccess?.()
queueMicrotask(() => transaction.oncomplete?.())
})
return request
},
put(value, key) {
values.set(key, value)
queueMicrotask(() => transaction.oncomplete?.())
},
}
},
}
return transaction
},
}
return {
open() {
const request = { result: db }
queueMicrotask(() => {
if (!stores.has('routineOverrides')) request.onupgradeneeded?.()
request.onsuccess?.()
})
return request
},
}
}
afterEach(() => vi.unstubAllGlobals())
describe('daily hanging goal storage', () => {
it('reads and writes a local goal without changing the seed', async () => {
vi.stubGlobal('indexedDB', memoryIndexedDB())
expect(await readDailyHangGoal()).toBeNull()
await writeDailyHangGoal(180)
expect(await readDailyHangGoal()).toBe(180)
})
it('rejects invalid values and unavailable storage', async () => {
vi.stubGlobal('indexedDB', memoryIndexedDB())
await expect(writeDailyHangGoal(0)).rejects.toThrow('whole number')
await expect(writeDailyHangGoal(2.5)).rejects.toThrow('whole number')
vi.stubGlobal('indexedDB', undefined)
await expect(readDailyHangGoal()).rejects.toThrow('unavailable')
})
it('reports a blocked database upgrade', async () => {
vi.stubGlobal('indexedDB', {
open() {
const request = {}
queueMicrotask(() => request.onblocked?.())
return request
},
})
await expect(readDailyHangGoal()).rejects.toThrow('blocked by another tab')
})
})
+25
View File
@@ -0,0 +1,25 @@
const DATABASE_NAME = 'workout-tracker'
const DATABASE_VERSION = 2
export function openLocalDatabase() {
return new Promise((resolve, reject) => {
if (!globalThis.indexedDB) {
reject(new Error('Local workout storage is unavailable in this browser.'))
return
}
const request = globalThis.indexedDB.open(DATABASE_NAME, DATABASE_VERSION)
let blocked = false
request.onupgradeneeded = () => {
for (const store of ['routineOverrides', 'strengthEntries']) {
if (!request.result.objectStoreNames.contains(store)) request.result.createObjectStore(store)
}
}
request.onsuccess = () => {
if (blocked) request.result.close()
else resolve(request.result)
}
request.onerror = () => reject(new Error('Could not open local workout storage.'))
request.onblocked = () => { blocked = true; reject(new Error('Local workout storage is blocked by another tab.')) }
})
}
+76
View File
@@ -0,0 +1,76 @@
import { initialRoutine } from './data/index.js'
const weekdayKeys = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
export function localCalendarDate(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 12)
}
export function addCalendarDays(date, days) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12)
}
export function startOfWeek(date) {
return addCalendarDays(date, -((date.getDay() + 6) % 7))
}
export function localDateKey(date) {
const pad = (value) => String(value).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}
export function routineForDate(date) {
return initialRoutine.days[weekdayKeys[date.getDay()]]
}
function rangeLabel(range) {
return range.min === range.max ? String(range.min) : `${range.min}–${range.max}`
}
function durationLabel(range) {
if (range.min % 60 === 0 && range.max % 60 === 0) {
return `${rangeLabel({ min: range.min / 60, max: range.max / 60 })} min`
}
return `${rangeLabel(range)} sec`
}
export function prescriptionLabel(prescription) {
const per = prescription.per ? ` per ${prescription.per}` : ''
switch (prescription.kind) {
case 'emom':
return `${prescription.rounds} min EMOM · ${rangeLabel(prescription.repsPerRound)} reps each minute`
case 'repetitions':
return prescription.sets
? `${rangeLabel(prescription.sets)} × ${rangeLabel(prescription.reps)} reps${per}`
: `${rangeLabel(prescription.reps)} ${prescription.tempo || ''} reps${per}`.replace(/\s+/g, ' ').trim()
case 'timed-sets':
return prescription.durationSec
? `${rangeLabel(prescription.sets)} × ${durationLabel(prescription.durationSec)}${per}`
: `${rangeLabel(prescription.sets)} sets · duration not specified`
case 'timed-hold':
return `${durationLabel(prescription.durationSec)}${per}`
case 'isometric-hold':
return `Hold${per}`
case 'hanging-practice':
return `Goal: ${durationLabel({ min: prescription.goalDurationSec, max: prescription.goalDurationSec })}`
default:
return ''
}
}
export function restLabel(rest) {
if (!rest) return null
if (rest.kind === 'remainder-of-interval') return 'Rest: remainder of each minute'
if (rest.kind === 'approximate') return `Rest: about ${durationLabel({ min: rest.seconds, max: rest.seconds })}`
return `Rest: ${durationLabel(rest.seconds)}`
}
export function loadLabel(load) {
if (!load) return null
if (load.bodyweightOnly) return 'Bodyweight only'
const parts = []
if ('vestKg' in load) parts.push(load.vestKg === null ? 'Vest load not specified' : `${load.vestKg} kg vest`)
if ('dumbbellKg' in load || 'dumbbellKgEach' in load) parts.push('Dumbbell load not specified')
if ('ezBarTotalKg' in load) parts.push('EZ-bar load not specified')
return parts.join(' · ')
}
+21
View File
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest'
import { addCalendarDays, loadLabel, localDateKey, prescriptionLabel, restLabel, routineForDate, startOfWeek } from './routineView.js'
describe('routine view helpers', () => {
it('uses local calendar dates across month and year boundaries', () => {
const newYear = new Date(2026, 0, 1, 12)
expect(localDateKey(startOfWeek(newYear))).toBe('2025-12-29')
expect(localDateKey(addCalendarDays(newYear, -1))).toBe('2025-12-31')
expect(localDateKey(addCalendarDays(newYear, 7))).toBe('2026-01-08')
expect(routineForDate(new Date(2026, 9, 25, 12)).morning.title).toBe('Push 2 — Shoulders + Triceps + Core')
})
it('shows ranges and unknown values without treating goals as completed work', () => {
expect(prescriptionLabel({ kind: 'emom', rounds: 10, repsPerRound: { min: 3, max: 4 } })).toBe('10 min EMOM · 3–4 reps each minute')
expect(prescriptionLabel({ kind: 'timed-sets', sets: { min: 2, max: 3 }, durationSec: null })).toBe('2–3 sets · duration not specified')
expect(prescriptionLabel({ kind: 'hanging-practice', goalDurationSec: 120 })).toBe('Goal: 2 min')
expect(prescriptionLabel({ kind: 'isometric-hold', per: 'side' })).toBe('Hold per side')
expect(restLabel({ kind: 'range', seconds: { min: 120, max: 180 } })).toBe('Rest: 2–3 min')
expect(loadLabel({ vestKg: 10, dumbbellKgEach: null })).toBe('10 kg vest · Dumbbell load not specified')
})
})
+26
View File
@@ -0,0 +1,26 @@
export const loadFields = [
{ key: 'vestKg', label: 'Vest weight (kg)', multiplier: 1 },
{ key: 'dumbbellKgEach', label: 'Dumbbell weight (kg each)', multiplier: 2 },
{ key: 'dumbbellKg', label: 'Dumbbell weight (kg)', multiplier: 1 },
{ key: 'ezBarTotalKg', label: 'EZ-bar total weight (kg)', multiplier: 1 },
]
export function fieldsForExercise(load) {
return loadFields.filter(({ key }) => load && Object.hasOwn(load, key))
}
export function totalExternalKg(load) {
if (!load || typeof load !== 'object' || Array.isArray(load)) return null
const keys = Object.keys(load)
if (keys.length === 1 && load.bodyweightOnly === true) return 0
if (keys.length === 0 || keys.some((key) => !loadFields.some((field) => field.key === key))) return null
let total = 0
for (const { key, multiplier } of loadFields) {
if (!Object.hasOwn(load, key)) continue
const weight = load[key]
if (typeof weight !== 'number' || !Number.isFinite(weight) || weight < 0) return null
total += weight * multiplier
}
return Number.isFinite(total) ? total : null
}
+62
View File
@@ -0,0 +1,62 @@
import { openLocalDatabase } from './localDatabase.js'
import { totalExternalKg } from './strengthLoad.js'
const STORE_NAME = 'strengthEntries'
function entryKey(dateKey, exerciseId) {
if (!/^\d{4}-\d{2}-\d{2}$/.test(dateKey) || !exerciseId) throw new Error('A date and exercise are required.')
return `${dateKey}:${exerciseId}`
}
function validReps(value) {
return Number.isSafeInteger(value) && value >= 0
}
function validWeight(value) {
return typeof value === 'number' && Number.isFinite(value) && value >= 0
}
function validRecordedWeight(record) {
if (!validWeight(record.externalKg)) return false
if (record.load == null) return true // Entries saved before separate load fields remain valid.
const total = totalExternalKg(record.load)
return total != null && Math.abs(total - record.externalKg) < 1e-9
}
function validEntry(entry) {
if (entry?.kind === 'emom') return validReps(entry.totalReps) && validRecordedWeight(entry)
if (entry?.kind === 'load-sets') return Array.isArray(entry.sets) && entry.sets.length > 0 && entry.sets.every((row) => row && validRecordedWeight(row))
if (entry?.kind === 'sets') return Array.isArray(entry.sets) && entry.sets.length > 0 && entry.sets.every((row) => row && validReps(row.reps) && validRecordedWeight(row))
return false
}
export async function readStrengthEntry(dateKey, exerciseId) {
const key = entryKey(dateKey, exerciseId)
const db = await openLocalDatabase()
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readonly')
const request = transaction.objectStore(STORE_NAME).get(key)
request.onsuccess = () => {
if (request.result == null) resolve(null)
else if (validEntry(request.result)) resolve(request.result)
else reject(new Error('The saved strength entry is invalid.'))
}
request.onerror = () => reject(new Error('Could not read the strength entry.'))
transaction.oncomplete = () => db.close()
transaction.onerror = () => { db.close(); reject(new Error('Could not read the strength entry.')) }
transaction.onabort = () => { db.close(); reject(new Error('Could not read the strength entry.')) }
})
}
export async function writeStrengthEntry(dateKey, exerciseId, entry) {
const key = entryKey(dateKey, exerciseId)
if (!validEntry(entry)) throw new Error('Enter whole-number reps and external weight of zero or more kilograms.')
const db = await openLocalDatabase()
return new Promise((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite')
transaction.objectStore(STORE_NAME).put(entry, key)
transaction.oncomplete = () => { db.close(); resolve() }
transaction.onerror = () => { db.close(); reject(new Error('Could not save the strength entry.')) }
transaction.onabort = () => { db.close(); reject(new Error('Could not save the strength entry.')) }
})
}
+118
View File
@@ -0,0 +1,118 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { readDailyHangGoal, writeDailyHangGoal } from './hangGoalStorage.js'
import { readStrengthEntry, writeStrengthEntry } from './strengthStorage.js'
function existingV1Database() {
const stores = new Map([['routineOverrides', new Map([['dailyHangGoalSec', 180]])]])
let version = 1
const db = {
objectStoreNames: { contains: (name) => stores.has(name) },
createObjectStore(name) { stores.set(name, new Map()) },
close() {},
transaction(name) {
const transaction = {
objectStore() {
return {
get(key) {
const request = {}
queueMicrotask(() => {
request.result = stores.get(name).get(key)
request.onsuccess?.()
queueMicrotask(() => transaction.oncomplete?.())
})
return request
},
put(value, key) {
stores.get(name).set(key, value)
queueMicrotask(() => transaction.oncomplete?.())
},
}
},
}
return transaction
},
}
return {
stores,
indexedDB: {
open(name, requestedVersion) {
const request = { result: db }
queueMicrotask(() => {
if (name !== 'workout-tracker') throw new Error('Unexpected database')
if (requestedVersion > version) {
request.onupgradeneeded?.()
version = requestedVersion
}
request.onsuccess?.()
})
return request
},
},
}
}
afterEach(() => vi.unstubAllGlobals())
describe('strength entry storage', () => {
it('upgrades the existing hanging-goal database and keeps dated entries separate', async () => {
const database = existingV1Database()
vi.stubGlobal('indexedDB', database.indexedDB)
expect(await readDailyHangGoal()).toBe(180)
expect(database.stores.has('strengthEntries')).toBe(true)
await writeStrengthEntry('2026-10-27', 'pull-up', { kind: 'emom', totalReps: 36, externalKg: 6 })
await writeStrengthEntry('2026-10-26', 'pull-up', { kind: 'emom', totalReps: 32, externalKg: 6 })
await writeStrengthEntry('2026-10-27', 'squat', { kind: 'sets', sets: [{ reps: 10, externalKg: 20 }, { reps: 8, externalKg: 22.5 }] })
expect(await readStrengthEntry('2026-10-27', 'pull-up')).toEqual({ kind: 'emom', totalReps: 36, externalKg: 6 })
expect(await readStrengthEntry('2026-10-26', 'pull-up')).toEqual({ kind: 'emom', totalReps: 32, externalKg: 6 })
expect(await readStrengthEntry('2026-10-27', 'squat')).toEqual({ kind: 'sets', sets: [{ reps: 10, externalKg: 20 }, { reps: 8, externalKg: 22.5 }] })
expect(await readStrengthEntry('2026-10-28', 'pull-up')).toBeNull()
await writeDailyHangGoal(240)
expect(await readDailyHangGoal()).toBe(240)
})
it('rejects missing or invalid reps and weights without saving', async () => {
const database = existingV1Database()
vi.stubGlobal('indexedDB', database.indexedDB)
await expect(writeStrengthEntry('2026-10-27', 'pull-up', { kind: 'emom', totalReps: 2.5, externalKg: 6 })).rejects.toThrow('whole-number reps')
await expect(writeStrengthEntry('2026-10-27', 'squat', { kind: 'sets', sets: [{ reps: 8, externalKg: -1 }] })).rejects.toThrow('whole-number reps')
expect(database.stores.get('strengthEntries')).toBeUndefined()
})
it('stores separate load components and rejects an inconsistent total', async () => {
const database = existingV1Database()
vi.stubGlobal('indexedDB', database.indexedDB)
const entry = { kind: 'sets', sets: [{ reps: 10, externalKg: 34, load: { vestKg: 10, dumbbellKgEach: 12 } }] }
await writeStrengthEntry('2026-10-29', 'squat', entry)
expect(await readStrengthEntry('2026-10-29', 'squat')).toEqual(entry)
await expect(writeStrengthEntry('2026-10-29', 'squat', { kind: 'sets', sets: [{ reps: 10, externalKg: 22, load: { vestKg: 10, dumbbellKgEach: 12 } }] })).rejects.toThrow('whole-number reps')
expect(await readStrengthEntry('2026-10-29', 'squat')).toEqual(entry)
})
it('preserves weight-only carry sets without fabricating repetitions', async () => {
const database = existingV1Database()
vi.stubGlobal('indexedDB', database.indexedDB)
const entry = { kind: 'load-sets', sets: [
{ externalKg: 20, load: { dumbbellKg: 20 } },
{ externalKg: 22, load: { dumbbellKg: 22 } },
] }
await writeStrengthEntry('2026-11-03', 'suitcase-carry', entry)
expect(await readStrengthEntry('2026-11-03', 'suitcase-carry')).toEqual(entry)
await expect(writeStrengthEntry('2026-11-03', 'suitcase-carry', { kind: 'load-sets', sets: [] })).rejects.toThrow()
await expect(writeStrengthEntry('2026-11-03', 'suitcase-carry', { kind: 'load-sets', sets: [{ externalKg: 20, load: { dumbbellKg: 22 } }] })).rejects.toThrow()
expect(await readStrengthEntry('2026-11-03', 'suitcase-carry')).toEqual(entry)
expect(await readDailyHangGoal()).toBe(180)
})
it('reports unavailable local storage', async () => {
vi.stubGlobal('indexedDB', undefined)
await expect(readStrengthEntry('2026-10-27', 'pull-up')).rejects.toThrow('unavailable')
})
it('reports a malformed saved entry', async () => {
const database = existingV1Database()
vi.stubGlobal('indexedDB', database.indexedDB)
await readStrengthEntry('2026-10-27', 'squat')
database.stores.get('strengthEntries').set('2026-10-27:squat', { kind: 'sets', sets: [null] })
await expect(readStrengthEntry('2026-10-27', 'squat')).rejects.toThrow('invalid')
})
})
+89 -10
View File
@@ -1,29 +1,108 @@
:root { font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: #202923; background: #f4f1ea; }
:root {
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: #202923;
background: #f4f1ea;
}
body { min-width: 320px; margin: 0; }
button { font: inherit; }
.app-shell { min-height: 100vh; background: #f4f1ea; }
.skip-link { position: absolute; left: 1rem; top: -5rem; z-index: 10; padding: .6rem 1rem; background: #fff; color: #173d32; }
.skip-link:focus { top: .5rem; }
.site-header { min-height: 76px; background: #173d32; color: #fff; }
.header-inner { display: flex; justify-content: space-between; gap: 1rem; }
.site-header { position: sticky; top: 0; z-index: 20; min-height: 92px; background: #173d32; color: #fff; }
.header-inner { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
.brand, .brand:hover, .brand:focus { display: inline-flex; align-items: center; gap: .75rem; color: #fff; font-size: 1.1rem; font-weight: 700; letter-spacing: -.02em; text-decoration: none; }
.brand-mark { display: grid; width: 36px; height: 36px; place-items: center; border-radius: 10px; background: #d6ec77; color: #173d32; font-weight: 800; }
.header-note { color: #d0e3db; font-size: .875rem; }
.page-content { padding-top: clamp(2rem, 5vw, 4rem); padding-bottom: 3rem; }
.header-trailing { display: flex; align-items: center; gap: 1.5rem; }
.wall-clock { display: flex; flex-direction: column; align-items: flex-end; color: #e1eae4; font-size: .8rem; white-space: nowrap; }
.wall-clock time { color: #fff; font-size: clamp(1.65rem, 2.4vw, 2.2rem); font-variant-numeric: tabular-nums; font-weight: 800; letter-spacing: .02em; line-height: 1.15; }
.page-content { padding-top: clamp(1.5rem, 3vw, 2.5rem); padding-bottom: 3rem; }
.page-heading { display: flex; justify-content: space-between; align-items: end; gap: 1.5rem; }
.eyebrow, .panel-kicker { color: #476656; font-size: .73rem; font-weight: 800; letter-spacing: .16em; text-transform: uppercase; }
h1 { max-width: 16ch; margin: .25rem 0 .7rem; font-size: clamp(2.2rem, 5vw, 3.75rem); line-height: 1.08; letter-spacing: -.045em; }
.intro { margin: 0; color: #5b685f; font-size: 1.08rem; }
h1 { margin: .25rem 0 .55rem; font-size: clamp(2.2rem, 4vw, 3.25rem); line-height: 1.08; letter-spacing: -.045em; }
.intro { margin: 0; color: #5b685f; font-size: 1.03rem; }
.local-badge { flex: 0 0 auto; margin-bottom: .25rem; padding: .45rem .75rem; border: 1px solid #bbccc0; border-radius: 999px; color: #315847; font-size: .8rem; font-weight: 600; }
.section-nav { display: flex; flex-wrap: wrap; gap: .2rem; margin: 2.5rem 0 1.25rem; padding-bottom: .55rem; border-bottom: 1px solid #d4dcd4; }
.section-nav { display: flex; flex-wrap: wrap; gap: .2rem; margin: 1.7rem 0 1.25rem; padding-bottom: .55rem; border-bottom: 1px solid #d4dcd4; }
.section-link.btn { min-height: 44px; padding: .55rem 1rem; border-radius: 8px; color: #445e50; font-weight: 650; text-decoration: none; }
.section-link.btn:hover { background: #e6ebe2; color: #173d32; }
.section-link.btn[aria-current="page"] { background: #173d32; color: #fff; }
.section-link.btn:focus-visible, .brand:focus-visible { outline: 3px solid #9fc45c; outline-offset: 3px; }
.section-link.btn:focus-visible, .brand:focus-visible, .period-switch .btn:focus-visible, .week-controls .btn:focus-visible, .day-button.btn:focus-visible, .strength-entry button:focus-visible, .strength-entry input:focus-visible { outline: 3px solid #9fc45c; outline-offset: 3px; }
.content-panel { display: flex; align-items: flex-start; gap: 1.5rem; min-height: 280px; padding: clamp(1.5rem, 4vw, 3rem); border: 1px solid #e0e5dd; border-radius: 20px; background: #fff; box-shadow: 0 14px 36px rgba(22, 54, 43, .045); }
.panel-icon { display: grid; flex: 0 0 56px; width: 56px; height: 56px; place-items: center; border-radius: 16px; background: #e8efd9; color: #315847; font-size: 2rem; line-height: 1; }
.content-panel h2 { margin: .4rem 0 .7rem; font-size: clamp(1.5rem, 3vw, 2rem); letter-spacing: -.03em; }
.content-panel p:last-child { max-width: 48ch; color: #5b685f; line-height: 1.6; }
.shell-note { margin: 1rem 0; color: #627067; font-size: .875rem; }
@media (max-width: 575px) { .site-header { min-height: 68px; } .header-note, .local-badge { display: none; } .page-heading { display: block; } .section-nav { flex-wrap: wrap; margin-top: 2rem; } .section-link.btn { white-space: nowrap; padding-inline: .75rem; } .content-panel { gap: 1rem; min-height: 240px; border-radius: 16px; } .panel-icon { flex-basis: 42px; width: 42px; height: 42px; font-size: 1.5rem; } }
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { scroll-behavior: auto !important; animation-duration: .01ms !important; transition-duration: .01ms !important; } }
.routine-view { max-width: 1100px; }
.period-switch { display: inline-flex; padding: 4px; border: 1px solid #c8d4c9; border-radius: 12px; background: #e9ede6; }
.period-switch .btn { min-width: 118px; min-height: 44px; border-radius: 8px; color: #365548; font-weight: 700; text-decoration: none; }
.period-switch .btn[aria-pressed="true"] { background: #173d32; color: #fff; }
.period-switch .btn:hover:not([aria-pressed="true"]) { background: #dce5da; }
.week-controls { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: .5rem; margin: 1.25rem 0 .55rem; }
.week-controls .btn { min-height: 44px; padding: .35rem .5rem; color: #315847; font-weight: 700; text-decoration: none; }
.week-controls .btn:first-child { justify-self: start; }
.week-controls .btn:last-child { justify-self: end; }
.week-range { color: #52665a; font-size: .9rem; font-weight: 650; text-align: center; }
.day-strip { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: .5rem; margin-bottom: 1.25rem; }
.day-button.btn { display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 68px; padding: .4rem .2rem; border: 1px solid #d6dfd4; border-radius: 12px; background: #fff; color: #3d5e4d; text-decoration: none; }
.day-button span { font-size: .78rem; font-weight: 650; }
.day-button strong { font-size: 1.15rem; }
.day-button.btn:hover { border-color: #819e86; background: #ecf1e8; }
.day-button.btn[aria-pressed="true"] { border-color: #173d32; background: #173d32; color: #fff; }
.routine-panel { padding: clamp(1.15rem, 2.8vw, 2rem); border: 1px solid #e0e5dd; border-radius: 18px; background: #fff; box-shadow: 0 10px 30px rgba(22, 54, 43, .04); }
.routine-heading { display: flex; align-items: start; justify-content: space-between; gap: 1rem; }
.routine-heading .panel-kicker { margin: 0 0 .35rem; }
.routine-heading h2 { margin: 0; font-size: clamp(1.5rem, 2.8vw, 2rem); letter-spacing: -.03em; }
.session-count { flex: 0 0 auto; padding: .35rem .65rem; border-radius: 999px; background: #eaf0e3; color: #315847; font-size: .8rem; font-weight: 700; }
.session-guidance { margin: .8rem 0 0; color: #53675a; line-height: 1.5; }
.exercise-list { display: grid; gap: .65rem; margin: 1.2rem 0 0; padding: 0; list-style: none; }
.exercise-card { display: flex; align-items: flex-start; gap: .9rem; padding: .9rem 1rem; border: 1px solid #e2e8e0; border-radius: 12px; background: #fbfcf9; }
.exercise-number { display: grid; flex: 0 0 30px; height: 30px; place-items: center; border-radius: 50%; background: #e8efd9; color: #315847; font-size: .8rem; font-weight: 800; }
.exercise-copy { min-width: 0; flex: 1; }
.exercise-title-row { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; }
.exercise-title-row h3 { margin: 0; font-size: 1.05rem; line-height: 1.35; }
.optional-tag { padding: .12rem .4rem; border-radius: 999px; background: #f4eecf; color: #66521e; font-size: .72rem; font-weight: 700; }
.prescription { margin: .3rem 0 0; color: #315847; font-weight: 700; }
.exercise-meta { margin: .25rem 0 0; color: #5f6c62; font-size: .86rem; line-height: 1.4; }
.strength-entry { display: grid; justify-items: start; gap: .55rem; margin-top: .8rem; padding-top: .8rem; border-top: 1px solid #e2e8e0; }
.strength-entry > strong { color: #315847; font-size: .88rem; }
.strength-fields, .strength-set { display: flex; flex-wrap: wrap; align-items: end; gap: .55rem; }
.strength-set > span { align-self: center; min-width: 3rem; color: #52665a; font-size: .84rem; font-weight: 700; }
.strength-entry label { display: grid; gap: .2rem; color: #52665a; font-size: .8rem; font-weight: 650; }
.strength-entry input { width: 7rem; min-height: 38px; padding: .3rem .45rem; border: 1px solid #b6c7b8; border-radius: 6px; color: #254838; }
.strength-entry button { min-height: 38px; }
.strength-actions { display: flex; align-items: center; gap: .7rem; }
.strength-actions span { color: #315847; font-size: .84rem; font-weight: 700; }
.strength-entry small { color: #657468; }
.strength-error { margin: 0; color: #9b3126; font-size: .84rem; }
.hang-goal-editor { margin-top: .65rem; }
.hang-goal-editor form { display: flex; flex-wrap: wrap; align-items: center; gap: .45rem; }
.hang-goal-editor label { color: #53675a; font-size: .82rem; font-weight: 650; }
.hang-goal-editor input { width: 5.5rem; min-height: 38px; padding: .3rem .45rem; border: 1px solid #b6c7b8; border-radius: 6px; color: #254838; }
.hang-goal-editor .btn { min-height: 38px; }
.hang-goal-editor p { margin: .35rem 0 0; font-size: .82rem; }
.hang-goal-editor .goal-error { color: #9b3126; }
@media (max-width: 575px) {
.site-header { min-height: 80px; }
.header-inner { gap: .5rem; }
.header-note, .local-badge { display: none; }
.brand { gap: .5rem; font-size: .95rem; }
.wall-clock span { line-height: 1.1; }
.wall-clock time { font-size: 1.6rem; }
.page-heading { display: block; }
.section-nav { margin-top: 1.4rem; }
.section-link.btn { white-space: nowrap; padding-inline: .75rem; }
.content-panel { gap: 1rem; min-height: 240px; border-radius: 16px; }
.panel-icon { flex-basis: 42px; width: 42px; height: 42px; font-size: 1.5rem; }
.week-controls { grid-template-columns: 1fr 1fr; }
.week-range { grid-column: 1 / -1; grid-row: 1; }
.day-strip { gap: .25rem; }
.day-button.btn { min-height: 60px; border-radius: 8px; }
.routine-heading { display: block; }
.session-count { display: inline-block; margin-top: .65rem; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { scroll-behavior: auto !important; animation-duration: .01ms !important; transition-duration: .01ms !important; }
}