Implement TASK-015 metadata-driven exercise logging
This commit is contained in:
+28
-25
@@ -1,9 +1,10 @@
|
||||
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 { addCalendarDays, localCalendarDate, localDateKey, prescriptionLabel, restLabel, routineForDate, startOfWeek } from './routineView.js'
|
||||
import HangGoalEditor from './HangGoalEditor.jsx'
|
||||
import StrengthEntryEditor from './StrengthEntryEditor.jsx'
|
||||
import PerformanceEditor from './PerformanceEditor.jsx'
|
||||
import { equipmentLabels } from './performanceModel.js'
|
||||
import { readDailyHangGoal, writeDailyHangGoal } from './hangGoalStorage.js'
|
||||
|
||||
const sections = [
|
||||
@@ -13,7 +14,7 @@ const sections = [
|
||||
{ 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 exerciseLibrary = new Map(exerciseDefinitions.map((definition) => [definition.id, definition]))
|
||||
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' })
|
||||
@@ -46,26 +47,28 @@ function savedPeriod() {
|
||||
}
|
||||
}
|
||||
|
||||
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 ExerciseList({ exercises, dateKey, period, hangGoalSeconds, hangGoalLoading, hangGoalError, onSaveHangGoal }) {
|
||||
return <ol className="exercise-list">{exercises.map(({ order, exerciseId, prescription, optional, rest, notes }) => {
|
||||
const definition = exerciseLibrary.get(exerciseId)
|
||||
const isHang = definition.protocols?.includes('attempts')
|
||||
const target = isHang ? { ...prescription, goalDurationSec: hangGoalSeconds } : prescription
|
||||
return <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>{definition.name}</h3>{optional && <span className="optional-tag">Optional</span>}</div>
|
||||
<p className="prescription">Target: {prescriptionLabel(target).replace(/^Goal: /, '')}{isHang ? ' continuous' : ''}</p>
|
||||
<p className="exercise-meta">{definition.equipment.map((equipment) => equipmentLabels[equipment]).join(' + ')}{rest ? ` · ${restLabel(rest)}` : ''}</p>
|
||||
<PerformanceEditor key={`${dateKey}-${period}-${exerciseId}`} dateKey={dateKey} period={period} definition={definition} prescription={target} goalSeconds={hangGoalSeconds} />
|
||||
{isHang && <HangGoalEditor goalSeconds={hangGoalSeconds} loading={hangGoalLoading} storageError={hangGoalError} onSave={onSaveHangGoal} />}
|
||||
<details className="exercise-details"><summary>Exercise details</summary>
|
||||
{notes && <p>{notes}</p>}
|
||||
{definition.supports?.map((text) => <p key={text}>{text}</p>)}
|
||||
<p>Instructions and muscles worked: reviewed content is not yet available.</p>
|
||||
<p role="img" aria-label="Exercise illustration not yet available">Illustration not yet available.</p>
|
||||
</details>
|
||||
</div>
|
||||
</li>
|
||||
})}</ol>
|
||||
}
|
||||
|
||||
function RoutineView({ selectedDate, setSelectedDate, period, setPeriod, setActiveId, hangGoalSeconds, hangGoalLoading, hangGoalError, onSaveHangGoal }) {
|
||||
@@ -134,10 +137,10 @@ function RoutineView({ selectedDate, setSelectedDate, period, setPeriod, setActi
|
||||
{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} />}
|
||||
{session.exercises.length > 0 && <ExerciseList exercises={session.exercises} period={period} 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>
|
||||
<p className="shell-note">Targets describe the plan. Save actual performance to complete filled rows. Incomplete rows stay drafts; browsing never saves an entry.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { IDBFactory } from 'fake-indexeddb'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import App from './App.jsx'
|
||||
import { readPerformance } from './performanceStorage.js'
|
||||
import { readStrengthEntry, writeStrengthEntry } from './strengthStorage.js'
|
||||
import { writeDailyHangGoal } from './hangGoalStorage.js'
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('indexedDB', new IDBFactory())
|
||||
vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date(2026, 10, 3, 12))
|
||||
window.localStorage.clear()
|
||||
})
|
||||
afterEach(() => { cleanup(); vi.useRealTimers(); vi.unstubAllGlobals() })
|
||||
it('runs detailed logging through the actual UI/storage boundary while preserving original EMOM totals', async () => {
|
||||
const legacy = { kind: 'emom', totalReps: 36, externalKg: 6 }
|
||||
await writeStrengthEntry('2026-11-03', 'pull-up', legacy)
|
||||
const view = render(<App />)
|
||||
const card = screen.getByText('Pull-ups').closest('.exercise-card')
|
||||
await waitFor(() => expect(within(card).getByLabelText('Minute 1 reps').disabled).toBe(false))
|
||||
fireEvent.change(within(card).getByLabelText('Minute 1 reps'), { target: { value: '4' } })
|
||||
fireEvent.change(within(card).getByLabelText('Minute 1 vest (kg)'), { target: { value: '8' } })
|
||||
fireEvent.click(within(card).getByRole('button', { name: 'Save performance' }))
|
||||
await within(card).findByText('Saved')
|
||||
expect(await readStrengthEntry('2026-11-03', 'pull-up')).toEqual(legacy)
|
||||
const saved = await readPerformance('2026-11-03', 'morning', 'pull-up')
|
||||
expect(saved.rows[0]).toEqual({ completed: true, values: { reps: 4 }, load: { vestKg: 8 } })
|
||||
expect(saved.rows[1]).toEqual({ completed: false, values: { reps: null }, load: { vestKg: null } })
|
||||
view.unmount(); render(<App />)
|
||||
const restored = screen.getByText('Pull-ups').closest('.exercise-card')
|
||||
await waitFor(() => expect(within(restored).getByLabelText('Minute 1 vest (kg)').value).toBe('8'))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
|
||||
expect(await readPerformance('2026-11-10', 'morning', 'pull-up')).toBeNull()
|
||||
})
|
||||
it('uses a persisted continuous hang target without losing unsaved attempts when editing it', async () => {
|
||||
await writeDailyHangGoal(180)
|
||||
render(<App />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Afternoon' }))
|
||||
const hang = screen.getByText('Daily hanging practice').closest('.exercise-card')
|
||||
await within(hang).findByText('Target: 3 min continuous')
|
||||
await waitFor(() => expect(within(hang).getByLabelText('Attempt 1 seconds').disabled).toBe(false))
|
||||
fireEvent.change(within(hang).getByLabelText('Attempt 1 seconds'), { target: { value: '90' } })
|
||||
fireEvent.change(screen.getByLabelText('Hang goal (seconds)'), { target: { value: '150' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save goal' }))
|
||||
await within(hang).findByText('Target: 150 sec continuous')
|
||||
expect(within(hang).getByLabelText('Attempt 1 seconds').value).toBe('90')
|
||||
fireEvent.click(within(hang).getByRole('button', { name: 'Save performance' }))
|
||||
await within(hang).findByText('Saved')
|
||||
const saved = await readPerformance('2026-11-03', 'afternoon', 'daily-hang')
|
||||
expect(saved.prescription.goalDurationSec).toBe(150)
|
||||
expect(saved.rows[0].values.seconds).toBe(90)
|
||||
expect(saved.rows[0].completed).toBe(true)
|
||||
})
|
||||
@@ -10,36 +10,38 @@ vi.mock('./hangGoalStorage.js', () => ({
|
||||
}),
|
||||
}))
|
||||
|
||||
import { IDBFactory } from 'fake-indexeddb'
|
||||
import App from './App.jsx'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('indexedDB', new IDBFactory())
|
||||
saved.goal = null
|
||||
saved.fail = false
|
||||
window.localStorage.clear()
|
||||
})
|
||||
|
||||
afterEach(() => cleanup())
|
||||
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
|
||||
|
||||
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.getByText('Target: 2 min continuous')).toBeTruthy()
|
||||
expect(screen.getByText('Deep squat hold').closest('.exercise-card').querySelector('.prescription').textContent).toBe('Target: 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')
|
||||
await screen.findByText('Target: 3 min continuous')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
|
||||
expect(screen.getByText('Goal: 3 min')).toBeTruthy()
|
||||
expect(screen.getByText('Target: 3 min continuous')).toBeTruthy()
|
||||
view.unmount()
|
||||
|
||||
render(<App />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Afternoon' }))
|
||||
await screen.findByText('Goal: 3 min')
|
||||
await screen.findByText('Target: 3 min continuous')
|
||||
})
|
||||
|
||||
it('shows a save failure without changing the displayed goal', async () => {
|
||||
@@ -50,6 +52,6 @@ describe('daily hanging goal', () => {
|
||||
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()
|
||||
expect(screen.getByText('Target: 2 min continuous')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useEffect, useId, useState } from 'react'
|
||||
import { Button } from 'react-bootstrap'
|
||||
import { blankRow, copy, loadColumns, measurementColumns, newPerformance, performanceError, performanceTotals, preparePerformanceForSave, signature } from './performanceModel.js'
|
||||
import { previousPerformance, readPerformance, writePerformance } from './performanceStorage.js'
|
||||
import { readStrengthEntry } from './strengthStorage.js'
|
||||
import StrengthEntryEditor from './StrengthEntryEditor.jsx'
|
||||
|
||||
export default function PerformanceEditor({ dateKey, period, definition, prescription, goalSeconds }) {
|
||||
const id = useId()
|
||||
const [record, setRecord] = useState(() => newPerformance(dateKey, period, definition, prescription))
|
||||
const [legacy, setLegacy] = useState(null)
|
||||
const [hasSaved, setHasSaved] = useState(false)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [readFailed, setReadFailed] = useState(false)
|
||||
const [retry, setRetry] = useState(0)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [notice, setNotice] = useState('')
|
||||
const [dirty, setDirty] = useState(false)
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
setLoading(true)
|
||||
Promise.all([readPerformance(dateKey, period, definition.id), period === 'morning' ? readStrengthEntry(dateKey, definition.id) : Promise.resolve(null)])
|
||||
.then(([saved, old]) => {
|
||||
if (!active) return
|
||||
setRecord(saved ?? newPerformance(dateKey, period, definition, prescription))
|
||||
setLegacy(old)
|
||||
setHasSaved(Boolean(saved))
|
||||
setReadFailed(false)
|
||||
setError('')
|
||||
setDirty(false)
|
||||
setLoading(false)
|
||||
}).catch((failure) => { if (active) { setReadFailed(true); setError(failure.message); setLoading(false) } })
|
||||
return () => { active = false }
|
||||
}, [dateKey, period, definition, retry])
|
||||
|
||||
function change(next) { setRecord(next); setDirty(true); setNotice(''); setError('') }
|
||||
function update(index, group, key, raw) {
|
||||
const value = raw === '' ? null : Number(raw)
|
||||
change({ ...record, rows: record.rows.map((row, i) => i === index ? { ...row, completed: false, [group]: { ...row[group], [key]: value } } : row) })
|
||||
}
|
||||
async function save(event) {
|
||||
event.preventDefault()
|
||||
const candidate = preparePerformanceForSave(hasSaved ? record : { ...record, prescription: copy(prescription) })
|
||||
const failure = performanceError(candidate)
|
||||
if (failure) { setError(failure); return }
|
||||
setSaving(true); setError(''); setNotice('')
|
||||
try { await writePerformance(candidate); setRecord(candidate); setHasSaved(true); setDirty(false); setNotice('Saved') }
|
||||
catch (failure) { setError(failure.message) }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
async function suggest() {
|
||||
setSaving(true); setError('')
|
||||
try {
|
||||
const previous = await previousPerformance(dateKey, period, record.definition, record.format)
|
||||
if (!previous) { setNotice('No compatible previous session found.'); return }
|
||||
// Only fill a blank current record. Do not overwrite existing values or completed work.
|
||||
if (record.rows.some((row) => row.completed || Object.values(row.values).some((value) => value !== null) || Object.entries(row.load).some(([key, value]) => key === 'dumbbellCount' ? value !== record.definition.dumbbellCount : value !== null))) {
|
||||
setNotice('Current entries kept. Previous-session suggestions are available for an empty entry.'); return
|
||||
}
|
||||
const priorRows = previous.rows.filter((row) => row.completed)
|
||||
const rows = record.format === 'emom' ? record.rows.map((row, index) => previous.rows[index]?.completed ? { ...copy(previous.rows[index]), completed: false } : row) : priorRows.map((row) => ({ ...copy(row), completed: false }))
|
||||
change({ ...record, rows }); setNotice(`Suggested from ${previous.date}. Review the suggestions, then save to record completed rows.`)
|
||||
} catch (failure) { setError(failure.message) }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
const columns = [...measurementColumns(record.definition).map((column) => ({ ...column, group: 'values' })), ...loadColumns(record.definition).filter((column) => !column.hidden).map((column) => ({ ...column, group: 'load' }))]
|
||||
const disabled = loading || readFailed || saving
|
||||
const totals = performanceTotals(record)
|
||||
const rowName = record.format === 'emom' ? 'Minute' : record.format === 'attempts' ? 'Attempt' : 'Set'
|
||||
const oldLoad = legacy?.load ?? legacy?.sets?.[0]?.load
|
||||
const changedDefinition = signature(definition, record.format) !== signature(record.definition, record.format)
|
||||
const canSwitch = definition.protocols?.includes('emom') && record.rows.every((row) => !row.completed && Object.values(row.values).every((v) => v === null) && Object.entries(row.load).every(([key, value]) => key === 'dumbbellCount' || value === null))
|
||||
return (
|
||||
<div className="performance-entry">
|
||||
{legacy && <details className="legacy-entry"><summary>Earlier record · original {legacy.kind === 'emom' ? 'EMOM total' : legacy.kind === 'load-sets' ? 'weights only' : 'sets'}</summary>
|
||||
<p>Preserved separately. No minute, side or duration values have been inferred. Detailed entries below do not replace this record.</p>
|
||||
<StrengthEntryEditor dateKey={dateKey} exerciseId={definition.id} kind={legacy.kind} load={oldLoad} />
|
||||
</details>}
|
||||
{changedDefinition && <p role="status">This entry uses its saved exercise definition. Current targets above do not change its recorded equipment or measurements.</p>}
|
||||
<form onSubmit={save} aria-label={`${definition.name} actual performance`} aria-busy={loading || saving} aria-describedby={error ? `${id}-error` : undefined}>
|
||||
<div className="performance-toolbar"><strong>Actual performance{record.format === 'emom' ? ' · per minute' : ''}</strong>
|
||||
{canSwitch && <Button type="button" variant="link" size="sm" disabled={disabled} onClick={() => change(newPerformance(dateKey, period, definition, prescription, record.format === 'emom' ? 'sets' : 'emom'))}>{record.format === 'emom' ? 'Use conventional sets' : 'Use EMOM minutes'}</Button>}
|
||||
</div>
|
||||
{loading && <p role="status">Loading saved performance…</p>}
|
||||
<div className="performance-head" aria-hidden="true" style={{ '--fields': columns.length }}><span>{rowName}</span>{columns.map(({ key, label }) => <span key={key}>{label}</span>)}</div>
|
||||
<div className="performance-rows">
|
||||
{record.rows.map((row, index) => <div key={index} className={`performance-row${row.completed ? ' is-complete' : ''}`} style={{ '--fields': columns.length }}>
|
||||
<strong className="row-number">{rowName} {index + 1}</strong>
|
||||
{columns.map(({ key, label, group, whole, min = 0, max }) => <label key={key}><span className="field-label">{label}</span><input type="number" inputMode={whole ? 'numeric' : 'decimal'} min={min} max={max} step={whole ? 1 : 'any'} aria-label={`${rowName} ${index + 1} ${label.toLowerCase()}`} value={row[group][key] ?? ''} disabled={disabled} onChange={(event) => update(index, group, key, event.target.value)} /></label>)}
|
||||
|
||||
{record.format !== 'emom' && record.rows.length > 1 && <Button type="button" className="remove-row" variant="link" size="sm" disabled={disabled} aria-label={`Remove ${rowName.toLowerCase()} ${index + 1}`} onClick={() => change({ ...record, rows: record.rows.filter((_, i) => i !== index) })}>Remove</Button>}
|
||||
</div>)}
|
||||
</div>
|
||||
<div className="performance-actions">
|
||||
{record.format !== 'emom' && <Button type="button" variant="outline-secondary" size="sm" disabled={disabled || record.rows.length >= 1000} onClick={() => change({ ...record, rows: [...record.rows, blankRow(record.definition, record.rows.at(-1))] })}>Add {record.format === 'attempts' ? 'attempt' : 'set'}</Button>}
|
||||
<Button type="button" variant="link" size="sm" disabled={disabled} onClick={suggest}>Use previous session</Button>
|
||||
<Button type="submit" size="sm" disabled={disabled}>{saving ? 'Saving…' : 'Save performance'}</Button>
|
||||
</div>
|
||||
{readFailed && <Button type="button" variant="outline-secondary" onClick={() => setRetry(retry + 1)}>Retry loading</Button>}
|
||||
<p className="performance-status" role="status">{dirty ? 'Unsaved changes. ' : ''}{notice}</p>
|
||||
{error && <p id={`${id}-error`} className="strength-error" role="alert">{error}</p>}
|
||||
{record.format === 'attempts' ? <p className="performance-summary">Longest continuous: {totals.longest} sec · Total hanging: {totals.seconds} sec · {totals.longest >= goalSeconds ? 'Continuous target achieved' : `Continuous target: ${goalSeconds} sec`}</p>
|
||||
: <p className="performance-summary">{totals.completed}/{record.rows.length} {record.format === 'emom' ? 'minutes' : 'sets'} complete{record.format === 'emom' ? ` · ${totals.reps} total reps` : ''} · Partial entries can be saved.</p>}
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
const memory = vi.hoisted(() => ({ records: new Map(), legacy: null, fail: false, readFail: false, previous: null }))
|
||||
vi.mock('./performanceStorage.js', () => ({
|
||||
readPerformance: vi.fn(async (date, period, id) => { if (memory.readFail) throw new Error('Storage read failed'); return memory.records.get(`${date}:${period}:${id}`) ?? null }),
|
||||
writePerformance: vi.fn(async (record) => { if (memory.fail) throw new Error('Storage write failed'); memory.records.set(`${record.date}:${record.period}:${record.exerciseId}`, structuredClone(record)) }),
|
||||
previousPerformance: vi.fn(async () => memory.previous),
|
||||
}))
|
||||
vi.mock('./strengthStorage.js', () => ({ readStrengthEntry: vi.fn(async () => memory.legacy), writeStrengthEntry: vi.fn(async () => {}) }))
|
||||
vi.mock('./hangGoalStorage.js', () => ({ readDailyHangGoal: vi.fn(async () => null), writeDailyHangGoal: vi.fn(async () => {}) }))
|
||||
import PerformanceEditor from './PerformanceEditor.jsx'
|
||||
import App from './App.jsx'
|
||||
import { exerciseDefinitions, initialRoutine } from './data/index.js'
|
||||
import { loadColumns, measurementColumns, newPerformance } from './performanceModel.js'
|
||||
const def = (id) => exerciseDefinitions.find((item) => item.id === id)
|
||||
const rx = (id) => Object.values(initialRoutine.days).flatMap((day) => [...day.morning.exercises, ...day.afternoon.exercises]).find((item) => item.exerciseId === id).prescription
|
||||
const props = (id) => ({ dateKey: '2026-11-03', period: 'morning', definition: def(id), prescription: rx(id), goalSeconds: 120 })
|
||||
async function ready() { await waitFor(() => expect(screen.getByRole('button', { name: 'Save performance' }).disabled).toBe(false)) }
|
||||
const fill = (name, value) => fireEvent.change(screen.getByLabelText(name), { target: { value: String(value) } })
|
||||
beforeEach(() => { memory.records.clear(); memory.legacy = null; memory.fail = false; memory.readFail = false; memory.previous = null })
|
||||
afterEach(() => { cleanup(); vi.useRealTimers() })
|
||||
it.each(exerciseDefinitions)('shows only applicable controls for $id', async (definition) => {
|
||||
render(<PerformanceEditor {...props(definition.id)} />)
|
||||
await ready()
|
||||
const row = definition.protocols?.includes('attempts') ? 'Attempt' : rx(definition.id).kind === 'emom' ? 'Minute' : 'Set'
|
||||
const expected = [...measurementColumns(definition), ...loadColumns(definition).filter((column) => !column.hidden)].map((column) => column.label.toLowerCase())
|
||||
for (const label of ['reps', 'left reps', 'right reps', 'seconds', 'left seconds', 'right seconds', 'vest (kg)', 'dumbbell (kg each)', 'dumbbells used', 'ez bar total (kg)', 'straight bar total (kg)']) {
|
||||
const input = screen.queryByLabelText(`${row} 1 ${label}`)
|
||||
expect(Boolean(input), `${definition.id}: ${label}`).toBe(expected.includes(label))
|
||||
}
|
||||
expect(screen.queryByRole('button', { name: /Start.*timer|Sound|Start EMOM/ })).toBeNull()
|
||||
expect(screen.queryByRole('checkbox')).toBeNull()
|
||||
})
|
||||
it('completes filled rows on save, keeps incomplete drafts, then restores by date', async () => {
|
||||
const p = props('dumbbell-floor-fly')
|
||||
const view = render(<PerformanceEditor {...p} />); await ready()
|
||||
fill('Set 1 reps', 12); fill('Set 1 dumbbell (kg each)', 8)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add set' }))
|
||||
expect(screen.getByLabelText('Set 2 dumbbell (kg each)').value).toBe('8')
|
||||
expect(screen.getByLabelText('Set 2 reps').value).toBe('')
|
||||
fill('Set 2 dumbbell (kg each)', 0)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||
const saved = memory.records.get('2026-11-03:morning:dumbbell-floor-fly')
|
||||
expect(saved.rows[0]).toMatchObject({ completed: true, values: { reps: 12 }, load: { dumbbellKgEach: 8, dumbbellCount: 2 } })
|
||||
expect(saved.rows[1]).toMatchObject({ completed: false, values: { reps: null }, load: { dumbbellKgEach: 0 } })
|
||||
view.unmount(); render(<PerformanceEditor {...p} />); await ready()
|
||||
expect(screen.queryByRole('checkbox')).toBeNull()
|
||||
expect(screen.getByLabelText('Set 2 dumbbell (kg each)').value).toBe('0')
|
||||
cleanup(); render(<PerformanceEditor {...p} dateKey="2026-11-10" />); await ready()
|
||||
expect(screen.getByLabelText('Set 1 reps').value).toBe('')
|
||||
expect(memory.records.size).toBe(1)
|
||||
})
|
||||
it('logs independent left/right durations without repetitions and validates completed rows', async () => {
|
||||
render(<PerformanceEditor {...props('bird-dog-hold')} />); await ready()
|
||||
fill('Set 1 left seconds', 20);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' }))
|
||||
await screen.findByText('Saved')
|
||||
expect(memory.records.values().next().value.rows[0]).toMatchObject({ completed: false, values: { leftSeconds: 20, rightSeconds: null } })
|
||||
fill('Set 1 right seconds', 25)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||
expect(memory.records.values().next().value.rows[0].values).toEqual({ leftSeconds: 20, rightSeconds: 25 })
|
||||
})
|
||||
it('keeps independent vest and dumbbell loads for each mixed-equipment set', async () => {
|
||||
render(<PerformanceEditor {...props('bulgarian-split-squat')} />); await ready()
|
||||
fill('Set 1 left reps', 10); fill('Set 1 right reps', 9); fill('Set 1 vest (kg)', 5); fill('Set 1 dumbbell (kg each)', 12)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add set' }))
|
||||
fill('Set 2 vest (kg)', 0); fill('Set 2 dumbbell (kg each)', 14)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||
const rows = memory.records.values().next().value.rows
|
||||
expect(rows[0].load).toEqual({ vestKg: 5, dumbbellKgEach: 12, dumbbellCount: 2 })
|
||||
expect(rows[1].load).toEqual({ vestKg: 0, dumbbellKgEach: 14, dumbbellCount: 2 })
|
||||
})
|
||||
it('tracks minute-by-minute EMOM with separate resistance and completed-rep total', async () => {
|
||||
render(<PerformanceEditor {...props('pull-up')} />); await ready()
|
||||
expect(screen.getAllByLabelText(/^Minute \d+ reps$/)).toHaveLength(10)
|
||||
expect(screen.queryByRole('checkbox')).toBeNull()
|
||||
fill('Minute 1 reps', 4); fill('Minute 1 vest (kg)', 6);
|
||||
fill('Minute 2 reps', 3); fill('Minute 2 vest (kg)', 10);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||
expect(screen.getByText(/2\/10 minutes complete · 7 total reps/)).toBeTruthy()
|
||||
expect(memory.records.values().next().value.rows.slice(0, 2).map((row) => row.load.vestKg)).toEqual([6, 10])
|
||||
})
|
||||
it('reports cumulative hang duration without claiming continuous success', async () => {
|
||||
render(<PerformanceEditor {...props('daily-hang')} />); await ready()
|
||||
fill('Attempt 1 seconds', 60);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add attempt' }))
|
||||
fill('Attempt 2 seconds', 75);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||
expect(screen.getByText(/Longest continuous: 75 sec · Total hanging: 135 sec · Continuous target: 120 sec/)).toBeTruthy()
|
||||
expect(screen.queryByText(/target achieved/)).toBeNull()
|
||||
})
|
||||
it('applies previous-session suggestions only to empty drafts and never marks complete', async () => {
|
||||
const p = props('front-plank'); memory.previous = newPerformance('2026-10-29', p.period, p.definition, p.prescription)
|
||||
memory.previous.rows[0] = { values: { seconds: 45 }, load: { vestKg: 8 }, completed: true }
|
||||
render(<PerformanceEditor {...p} />); await ready()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Use previous session' }))
|
||||
await screen.findByText(/Suggested from 2026-10-29/)
|
||||
expect(screen.getByLabelText('Set 1 seconds').value).toBe('45')
|
||||
expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy()
|
||||
expect(memory.records.size).toBe(0)
|
||||
fill('Set 1 vest (kg)', 9)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Use previous session' }))
|
||||
await screen.findByText(/Current entries kept/)
|
||||
expect(screen.getByLabelText('Set 1 vest (kg)').value).toBe('9')
|
||||
})
|
||||
it('keeps legacy aggregate values separate and never fabricates minutes', async () => {
|
||||
memory.legacy = { kind: 'emom', totalReps: 36, externalKg: 6 }
|
||||
render(<PerformanceEditor {...props('pull-up')} />); await ready()
|
||||
await waitFor(() => expect(screen.getByLabelText('Total reps').value).toBe('36'))
|
||||
expect(screen.getByLabelText('Minute 1 reps').value).toBe('')
|
||||
expect(memory.legacy).toEqual({ kind: 'emom', totalReps: 36, externalKg: 6 })
|
||||
})
|
||||
it('recovers from storage read failure and retains entered values after write failure', async () => {
|
||||
memory.readFail = true
|
||||
render(<PerformanceEditor {...props('front-plank')} />)
|
||||
await screen.findByText('Storage read failed')
|
||||
expect(screen.getByRole('button', { name: 'Save performance' }).disabled).toBe(true)
|
||||
memory.readFail = false; fireEvent.click(screen.getByRole('button', { name: 'Retry loading' })); await ready()
|
||||
fill('Set 1 seconds', 35); memory.fail = true
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Storage write failed')
|
||||
expect(screen.getByLabelText('Set 1 seconds').value).toBe('35')
|
||||
expect(screen.queryByText('Saved')).toBeNull()
|
||||
})
|
||||
it('preserves in-progress daily-hang attempts when the editable goal changes', async () => {
|
||||
const p = props('daily-hang'); const view = render(<PerformanceEditor {...p} />); await ready()
|
||||
fill('Attempt 1 seconds', 90)
|
||||
view.rerender(<PerformanceEditor {...p} prescription={{ ...p.prescription, goalDurationSec: 150 }} goalSeconds={150} />)
|
||||
expect(screen.getByLabelText('Attempt 1 seconds').value).toBe('90')
|
||||
expect(screen.getByText(/Continuous target: 150 sec/)).toBeTruthy()
|
||||
})
|
||||
it('integrates details and applicable logging with the existing navigation', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date(2026, 10, 4, 12)); window.localStorage.clear()
|
||||
render(<App />)
|
||||
const flys = screen.getByText('Dumbbell floor flys').closest('.exercise-card')
|
||||
await waitFor(() => expect(within(flys).getByLabelText('Set 1 dumbbell (kg each)').disabled).toBe(false))
|
||||
fireEvent.click(within(flys).getByText('Exercise details'))
|
||||
expect(within(flys).getByText(/reviewed content is not yet available/)).toBeTruthy()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Afternoon' }))
|
||||
expect(screen.getByText('Bird-dog hold')).toBeTruthy()
|
||||
expect(screen.getByText('Daily hanging practice')).toBeTruthy()
|
||||
expect(screen.queryByText('Dumbbell floor flys')).toBeNull()
|
||||
expect(screen.getByLabelText('Current local time')).toBeTruthy()
|
||||
expect(memory.records.size).toBe(0)
|
||||
})
|
||||
it('snapshots the current target on first save without changing a previously saved target', async () => {
|
||||
const p = props('daily-hang'); const view = render(<PerformanceEditor {...p} />); await ready()
|
||||
view.rerender(<PerformanceEditor {...p} prescription={{ ...p.prescription, goalDurationSec: 180 }} goalSeconds={180} />)
|
||||
fill('Attempt 1 seconds', 80)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||
expect(memory.records.values().next().value.prescription.goalDurationSec).toBe(180)
|
||||
view.rerender(<PerformanceEditor {...p} prescription={{ ...p.prescription, goalDurationSec: 240 }} goalSeconds={240} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||
expect(memory.records.values().next().value.prescription.goalDurationSec).toBe(180)
|
||||
})
|
||||
it('allows switching an empty EMOM entry to conventional sets and back', async () => {
|
||||
render(<PerformanceEditor {...props('pull-up')} />); await ready()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Use conventional sets' }))
|
||||
expect(screen.getByLabelText('Set 1 reps')).toBeTruthy()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Use EMOM minutes' }))
|
||||
expect(screen.getAllByLabelText(/^Minute \d+ reps$/)).toHaveLength(10)
|
||||
expect(screen.queryByRole('checkbox')).toBeNull()
|
||||
})
|
||||
it('keeps a recorded historical dumbbell count without displaying a count input', async () => {
|
||||
const p = props('hammer-curl'); const original = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
|
||||
original.rows[0] = { values: { reps: 10 }, load: { dumbbellKgEach: 8, dumbbellCount: 1 }, completed: true }
|
||||
memory.records.set('2026-11-03:morning:hammer-curl', structuredClone(original))
|
||||
render(<PerformanceEditor {...p} />); await ready()
|
||||
expect(screen.queryByLabelText('Set 1 dumbbells used')).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||
expect(memory.records.values().next().value).toEqual(original)
|
||||
})
|
||||
it('renders straight-bar and distance controls from metadata without a seeded exercise', async () => {
|
||||
const definition = { ...def('ez-bar-bent-over-row'), equipment: ['straight-bar'], measurement: 'distance' }
|
||||
render(<PerformanceEditor {...props(definition.id)} definition={definition} />); await ready()
|
||||
expect(screen.getByLabelText('Set 1 metres')).toBeTruthy()
|
||||
expect(screen.getByLabelText('Set 1 straight bar total (kg)')).toBeTruthy()
|
||||
expect(screen.queryByLabelText('Set 1 reps')).toBeNull()
|
||||
expect(screen.queryByLabelText('Set 1 ez bar total (kg)')).toBeNull()
|
||||
})
|
||||
it('renders saved historical controls after the current exercise equipment changes', async () => {
|
||||
const p = props('front-plank')
|
||||
const prior = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
|
||||
prior.rows[0] = { values: { seconds: 45 }, load: { vestKg: 8 }, completed: true }
|
||||
memory.records.set('2026-11-03:morning:front-plank', prior)
|
||||
render(<PerformanceEditor {...p} definition={{ ...p.definition, version: 2, equipment: ['bodyweight'] }} />); await ready()
|
||||
expect(screen.getByLabelText('Set 1 vest (kg)').value).toBe('8')
|
||||
expect(screen.getByText(/uses its saved exercise definition/)).toBeTruthy()
|
||||
expect(memory.records.get('2026-11-03:morning:front-plank')).toEqual(prior)
|
||||
})
|
||||
it('hides the fixed floor-fly dumbbell count while saving two dumbbells', async () => {
|
||||
render(<PerformanceEditor {...props('dumbbell-floor-fly')} />); await ready()
|
||||
expect(screen.queryByLabelText('Set 1 dumbbells used')).toBeNull()
|
||||
fill('Set 1 reps', 12); fill('Set 1 dumbbell (kg each)', 8)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||
expect(memory.records.values().next().value.rows[0].load).toEqual({ dumbbellKgEach: 8, dumbbellCount: 2 })
|
||||
})
|
||||
it('also hides the count on earlier paired floor-fly entries without rewriting their snapshot', async () => {
|
||||
const p = props('dumbbell-floor-fly'); const record = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
|
||||
delete record.definition.fixedDumbbellCount; record.definition.version = 1
|
||||
record.rows[0] = { values: { reps: 12 }, load: { dumbbellKgEach: 8, dumbbellCount: 2 }, completed: true }
|
||||
memory.records.set('2026-11-03:morning:dumbbell-floor-fly', structuredClone(record))
|
||||
render(<PerformanceEditor {...p} />); await ready()
|
||||
expect(screen.queryByLabelText('Set 1 dumbbells used')).toBeNull()
|
||||
expect(memory.records.values().next().value).toEqual(record)
|
||||
})
|
||||
|
||||
it('fills only an unrecorded legacy draft count from the saved definition on explicit save', async () => {
|
||||
const p = props('hammer-curl'); const original = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
|
||||
original.rows[0] = { values: { reps: 10 }, load: { dumbbellKgEach: 8, dumbbellCount: null }, completed: false }
|
||||
memory.records.set('2026-11-03:morning:hammer-curl', structuredClone(original))
|
||||
render(<PerformanceEditor {...p} />); await ready()
|
||||
expect(memory.records.values().next().value.rows[0].load.dumbbellCount).toBeNull()
|
||||
expect(screen.queryByLabelText('Set 1 dumbbells used')).toBeNull()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||
expect(memory.records.values().next().value.rows[0].load.dumbbellCount).toBe(2)
|
||||
})
|
||||
it('turns an edited saved row back into a draft only when explicitly saved', async () => {
|
||||
const p = props('front-plank'); const original = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
|
||||
original.rows[0] = { values: { seconds: 45 }, load: { vestKg: 8 }, completed: true }
|
||||
memory.records.set('2026-11-03:morning:front-plank', structuredClone(original))
|
||||
render(<PerformanceEditor {...p} />); await ready()
|
||||
fill('Set 1 seconds', '')
|
||||
expect(memory.records.values().next().value.rows[0].completed).toBe(true)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||
expect(memory.records.values().next().value.rows[0]).toMatchObject({ values: { seconds: null }, completed: false })
|
||||
expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy()
|
||||
})
|
||||
it('does not count a filled row as achieved when saving fails', async () => {
|
||||
memory.fail = true
|
||||
render(<PerformanceEditor {...props('front-plank')} />); await ready()
|
||||
fill('Set 1 seconds', 45); fill('Set 1 vest (kg)', 0)
|
||||
expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Storage write failed')
|
||||
expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy()
|
||||
expect(memory.records.size).toBe(0)
|
||||
})
|
||||
@@ -1,229 +1,66 @@
|
||||
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 }))
|
||||
// Legacy editor remains available for explicitly editing original-format history.
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
const saved = vi.hoisted(() => ({ entry: null, 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)
|
||||
}),
|
||||
readStrengthEntry: vi.fn(async () => saved.entry),
|
||||
writeStrengthEntry: vi.fn(async (_date, _id, entry) => { if (saved.fail) throw new Error('Could not save the strength entry.'); saved.entry = 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()
|
||||
import StrengthEntryEditor from './StrengthEntryEditor.jsx'
|
||||
beforeEach(() => { saved.entry = null; saved.fail = false })
|
||||
afterEach(cleanup)
|
||||
const editor = (kind = 'sets', load = { dumbbellKgEach: null }) => render(<StrengthEntryEditor dateKey="2026-11-03" exerciseId="legacy-exercise" kind={kind} load={load} />)
|
||||
it('retains original EMOM totals without allocating them to minutes', async () => {
|
||||
saved.entry = { kind: 'emom', totalReps: 36, externalKg: 6 }
|
||||
editor('emom', { vestKg: null })
|
||||
await waitFor(() => expect(screen.getByLabelText('Total reps').value).toBe('36'))
|
||||
expect(screen.getByLabelText('previously recorded total external weight (kg)').value).toBe('6')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save reps and weight' }))
|
||||
await screen.findByText('Saved')
|
||||
expect(saved.entry).toEqual({ kind: 'emom', totalReps: 36, externalKg: 6 })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.useRealTimers()
|
||||
it('copies loads into subsequent legacy sets without copying reps', async () => {
|
||||
editor()
|
||||
await waitFor(() => expect(screen.getByLabelText('Set 1 reps').disabled).toBe(false))
|
||||
fireEvent.change(screen.getByLabelText('Set 1 reps'), { target: { value: '10' } })
|
||||
fireEvent.change(screen.getByLabelText('Set 1 dumbbell weight (kg each)'), { target: { value: '8' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add set' }))
|
||||
expect(screen.getByLabelText('Set 2 reps').value).toBe('')
|
||||
expect(screen.getByLabelText('Set 2 dumbbell weight (kg each)').value).toBe('8')
|
||||
fireEvent.change(screen.getByLabelText('Set 2 reps'), { target: { value: '9' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save reps and weight' }))
|
||||
await screen.findByText('Saved')
|
||||
expect(saved.entry.sets).toEqual([{ reps: 10, externalKg: 16, load: { dumbbellKgEach: 8 } }, { reps: 9, externalKg: 16, load: { dumbbellKgEach: 8 } }])
|
||||
})
|
||||
|
||||
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/))
|
||||
})
|
||||
it('preserves legacy bodyweight totals until explicit component conversion', async () => {
|
||||
saved.entry = { kind: 'sets', sets: [{ reps: 12, externalKg: 0, load: { bodyweightOnly: true } }] }
|
||||
editor('sets', { vestKg: null })
|
||||
await waitFor(() => expect(screen.getByLabelText('Set 1 previously recorded total external weight (kg)').value).toBe('0'))
|
||||
expect(saved.entry.sets[0].load).toEqual({ bodyweightOnly: true })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Enter specific weights' }))
|
||||
fireEvent.change(screen.getByLabelText('Set 1 vest weight (kg)'), { target: { value: '5' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save reps and weight' }))
|
||||
await screen.findByText('Saved')
|
||||
expect(saved.entry.sets[0]).toEqual({ reps: 12, externalKg: 5, load: { vestKg: 5 } })
|
||||
})
|
||||
it('retains weight-only sets without inventing reps or durations', async () => {
|
||||
saved.entry = { kind: 'load-sets', sets: [{ externalKg: 20, load: { dumbbellKg: 20 } }] }
|
||||
editor('load-sets', { dumbbellKg: null })
|
||||
await waitFor(() => expect(screen.getByLabelText('Set 1 dumbbell weight (kg)').value).toBe('20'))
|
||||
expect(screen.queryByLabelText(/reps/i)).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save weight' }))
|
||||
await screen.findByText('Saved')
|
||||
expect(saved.entry.sets[0]).not.toHaveProperty('reps')
|
||||
})
|
||||
it('reports incomplete entry and storage failure without showing success', async () => {
|
||||
saved.fail = true
|
||||
editor('sets', { vestKg: null })
|
||||
await waitFor(() => expect(screen.getByLabelText('Set 1 reps').disabled).toBe(false))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save reps and weight' }))
|
||||
expect(screen.getByRole('alert').textContent).toMatch(/whole-number reps/)
|
||||
fireEvent.change(screen.getByLabelText('Set 1 reps'), { target: { value: '0' } })
|
||||
fireEvent.change(screen.getByLabelText('Set 1 vest weight (kg)'), { target: { value: '0' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save reps and weight' }))
|
||||
await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/Could not save/))
|
||||
expect(screen.queryByText('Saved')).toBeNull()
|
||||
})
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// Versioned adapter only; TASK-009 owns the user-facing import/export workflow.
|
||||
import { initialRoutine, exerciseDefinitions } from './data/index.js'
|
||||
import { openLocalDatabase } from './localDatabase.js'
|
||||
import { performanceError } from './performanceModel.js'
|
||||
import { performanceKey } from './performanceStorage.js'
|
||||
import { validEntry } from './strengthStorage.js'
|
||||
const stores = ['routineOverrides', 'strengthEntries', 'performanceEntries']
|
||||
|
||||
function validJSON(value) {
|
||||
if (value === null || typeof value === 'string' || typeof value === 'boolean') return true
|
||||
if (typeof value === 'number') return Number.isFinite(value)
|
||||
return typeof value === 'object' && Object.values(value).every(validJSON)
|
||||
}
|
||||
export function parseBackup(input) {
|
||||
let backup
|
||||
try { backup = typeof input === 'string' ? JSON.parse(input) : structuredClone(input) }
|
||||
catch { throw new Error('Invalid backup JSON.') }
|
||||
if (backup?.format !== 'workout-tracker' || ![1, 2].includes(backup.version) || !backup.stores || typeof backup.stores !== 'object' || Array.isArray(backup.stores)) throw new Error('Unsupported backup schema.')
|
||||
if (Object.keys(backup.stores).some((store) => !stores.includes(store))) throw new Error('Unsupported backup store.')
|
||||
// Version 1 is the legacy adapter envelope with the two original stores.
|
||||
for (const store of stores) {
|
||||
if (backup.version === 1 && store === 'performanceEntries' && backup.stores[store] == null) backup.stores[store] = []
|
||||
if (!Array.isArray(backup.stores[store])) throw new Error(`Missing backup store: ${store}.`)
|
||||
const keys = new Set()
|
||||
for (const entry of backup.stores[store]) {
|
||||
if (!entry || typeof entry.key !== 'string' || keys.has(entry.key) || !validJSON(entry.value)) throw new Error('Invalid or duplicate backup entry.')
|
||||
keys.add(entry.key)
|
||||
if (store === 'strengthEntries' && (!/^\d{4}-\d{2}-\d{2}:.+/.test(entry.key) || !validEntry(entry.value))) throw new Error('Invalid legacy strength entry.')
|
||||
if (store === 'performanceEntries' && (performanceError(entry.value) || entry.key !== performanceKey(entry.value.date, entry.value.period, entry.value.exerciseId))) throw new Error('Invalid detailed performance entry.')
|
||||
if (store === 'routineOverrides' && entry.key === 'dailyHangGoalSec' && (!Number.isSafeInteger(entry.value) || entry.value <= 0)) throw new Error('Invalid hanging goal.')
|
||||
}
|
||||
}
|
||||
return backup
|
||||
}
|
||||
export async function exportBackup() {
|
||||
const db = await openLocalDatabase()
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(stores, 'readonly')
|
||||
const data = Object.fromEntries(stores.map((store) => [store, []]))
|
||||
for (const name of stores) {
|
||||
const cursor = tx.objectStore(name).openCursor()
|
||||
cursor.onsuccess = () => {
|
||||
if (cursor.result) { data[name].push({ key: cursor.result.key, value: cursor.result.value }); cursor.result.continue() }
|
||||
}
|
||||
}
|
||||
tx.oncomplete = () => { db.close(); resolve(JSON.stringify({ format: 'workout-tracker', version: 2, reference: { exerciseDefinitions, initialRoutine }, stores: data })) }
|
||||
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not export local data.')) }
|
||||
})
|
||||
}
|
||||
export async function importBackup(input, { replace = false } = {}) {
|
||||
const backup = parseBackup(input) // Validate everything before opening a write transaction.
|
||||
const db = await openLocalDatabase()
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(stores, 'readwrite')
|
||||
try {
|
||||
for (const name of stores) {
|
||||
const store = tx.objectStore(name)
|
||||
if (replace) store.clear()
|
||||
for (const { key, value } of backup.stores[name]) store.add(value, key)
|
||||
}
|
||||
} catch { tx.abort() }
|
||||
tx.oncomplete = () => { db.close(); resolve() }
|
||||
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Import failed; existing data was left unchanged. Duplicate keys require an explicit replacement.')) }
|
||||
})
|
||||
}
|
||||
+8
-8
@@ -1,15 +1,15 @@
|
||||
# Initial routine data
|
||||
# Exercise and 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.
|
||||
`exerciseDefinitions.json` contains stable IDs/names/categories, definition version, equipment capabilities, measurement type and optional default dumbbell count/protocols/support notes. It contains no numeric resistance. Equipment vocabulary is bodyweight, weighted-vest, dumbbells, ez-curl-bar and straight-bar. No current exercise is assigned straight-bar. Dumbbells used as push-up handles are support equipment, not lifted load.
|
||||
|
||||
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.
|
||||
`initialRoutine.json` is seed v8 with separate Morning/Afternoon prescriptions, order, ranges, optional flags, rest and historical prescription load context. All assignments follow WORKOUT_ROUTINE section 8. It preserves unknown values as null, untimed afternoon targets, Monday/Friday empty stretch headings, no walks, and the editable initial 120-second continuous daily-hang goal. Do not infer performance or overwrite local overrides from seed updates.
|
||||
|
||||
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.
|
||||
`performanceModel.js` maps definition metadata to actual measurement/load fields. New detailed records use schemaVersion 1 and definition/prescription snapshots, independent left/right measurements and per-row completion/load. Dumbbells are kg each with actual count (1/2); vest and bars are separate, with bar totals including the bar. Draft nulls differ from explicit zero. Adding rows copies loads/count, never measurements/completion. EMOM stores ten minute rows; durations and hangs never require reps.
|
||||
|
||||
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.
|
||||
IndexedDB v3 adds performanceEntries and a compound matching-session index while retaining routineOverrides and strengthEntries unchanged. Original sets, EMOM totals, total-only/component and load-sets history remain in their original store and editor. No old totals are reclassified or distributed into detailed rows. `backupStorage.js` provides adapter JSON v2 for all three stores and a v1 legacy-envelope reader, validation and atomic non-overwriting or explicit-replacement import. TASK-009 owns backup UI; this task adds no Settings controls.
|
||||
|
||||
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.
|
||||
Floor-fly definition v2 has `fixedDumbbellCount: 2`: count stays in saved load data and calculations but is hidden in the new UI. Older paired floor-fly snapshots also omit the redundant count control without being rewritten. The subsequent Captain correction hides the count input for all exercises; new rows use the defined count internally. Historical differing counts retain their original snapshot semantics.
|
||||
|
||||
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.
|
||||
All dumbbell-count controls are now hidden. Counts remain in stored loads and calculations; existing non-null historical counts are preserved. If an older partial draft has a null count, an explicit Save fills only that unrecorded value from its saved definition. Reading alone never rewrites it.
|
||||
|
||||
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.
|
||||
Completion has no checkbox. `preparePerformanceForSave` derives row completion from applicable values/load only when Save is requested; fully filled valid rows become complete, incomplete rows remain drafts and invalid actuals are rejected. The UI adopts derived completion only after a successful write, preserving failed-save/draft semantics and existing records on read. No schema migration is required.
|
||||
|
||||
@@ -1,32 +1,335 @@
|
||||
[
|
||||
{"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"}
|
||||
{
|
||||
"id": "pull-up",
|
||||
"name": "Pull-ups",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest"
|
||||
],
|
||||
"measurement": "repetitions",
|
||||
"protocols": [
|
||||
"sets",
|
||||
"emom"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "ez-bar-bent-over-row",
|
||||
"name": "EZ-bar bent-over rows",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"ez-curl-bar"
|
||||
],
|
||||
"measurement": "repetitions"
|
||||
},
|
||||
{
|
||||
"id": "single-arm-dumbbell-row",
|
||||
"name": "Single-arm dumbbell rows",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions-per-side",
|
||||
"dumbbellCount": 1
|
||||
},
|
||||
{
|
||||
"id": "suitcase-carry",
|
||||
"name": "Suitcase carries",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "duration-per-side",
|
||||
"dumbbellCount": 1
|
||||
},
|
||||
{
|
||||
"id": "weighted-deep-push-up",
|
||||
"name": "Weighted deep push-ups using dumbbells as handles",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest"
|
||||
],
|
||||
"measurement": "repetitions",
|
||||
"supports": [
|
||||
"Stable dumbbells used as handles; their weight is not lifted resistance."
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "dumbbell-floor-fly",
|
||||
"name": "Dumbbell floor flys",
|
||||
"category": "strength",
|
||||
"version": 2,
|
||||
"equipment": [
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions",
|
||||
"dumbbellCount": 2,
|
||||
"fixedDumbbellCount": 2
|
||||
},
|
||||
{
|
||||
"id": "push-up-plus",
|
||||
"name": "Push-up plus",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest"
|
||||
],
|
||||
"measurement": "repetitions"
|
||||
},
|
||||
{
|
||||
"id": "feet-elevated-weighted-push-up",
|
||||
"name": "Feet-elevated weighted push-ups",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest"
|
||||
],
|
||||
"measurement": "repetitions"
|
||||
},
|
||||
{
|
||||
"id": "bulgarian-split-squat",
|
||||
"name": "Bulgarian split squats",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest",
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions-per-side",
|
||||
"dumbbellCount": 2
|
||||
},
|
||||
{
|
||||
"id": "single-leg-romanian-deadlift",
|
||||
"name": "Single-leg Romanian deadlifts",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest",
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions-per-side",
|
||||
"dumbbellCount": 2
|
||||
},
|
||||
{
|
||||
"id": "squat",
|
||||
"name": "Squats",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest",
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions",
|
||||
"dumbbellCount": 2
|
||||
},
|
||||
{
|
||||
"id": "single-leg-calf-raise",
|
||||
"name": "Single-leg calf raises",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest",
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions-per-side",
|
||||
"dumbbellCount": 1
|
||||
},
|
||||
{
|
||||
"id": "front-plank",
|
||||
"name": "Front plank",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest"
|
||||
],
|
||||
"measurement": "duration"
|
||||
},
|
||||
{
|
||||
"id": "chin-up",
|
||||
"name": "Chin-ups",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest"
|
||||
],
|
||||
"measurement": "repetitions",
|
||||
"protocols": [
|
||||
"sets",
|
||||
"emom"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "hanging-knee-raise",
|
||||
"name": "Hanging knee raises",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"bodyweight"
|
||||
],
|
||||
"measurement": "repetitions"
|
||||
},
|
||||
{
|
||||
"id": "finger-hang",
|
||||
"name": "Finger hangs",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest"
|
||||
],
|
||||
"measurement": "duration"
|
||||
},
|
||||
{
|
||||
"id": "single-arm-preacher-curl",
|
||||
"name": "Single-arm preacher curls over a chair",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions-per-side",
|
||||
"dumbbellCount": 1
|
||||
},
|
||||
{
|
||||
"id": "hammer-curl",
|
||||
"name": "Hammer curls",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions",
|
||||
"dumbbellCount": 2
|
||||
},
|
||||
{
|
||||
"id": "single-arm-shoulder-press",
|
||||
"name": "Standing single-arm dumbbell shoulder press",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions-per-side",
|
||||
"dumbbellCount": 1
|
||||
},
|
||||
{
|
||||
"id": "leaning-single-arm-lateral-raise",
|
||||
"name": "Leaning single-arm lateral raises",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions-per-side",
|
||||
"dumbbellCount": 1
|
||||
},
|
||||
{
|
||||
"id": "bent-over-rear-delt-fly",
|
||||
"name": "Bent-over rear-delt flys",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions",
|
||||
"dumbbellCount": 2
|
||||
},
|
||||
{
|
||||
"id": "lying-dumbbell-triceps-extension",
|
||||
"name": "Lying dumbbell triceps extensions",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions",
|
||||
"dumbbellCount": 2
|
||||
},
|
||||
{
|
||||
"id": "single-arm-triceps-extension",
|
||||
"name": "Single-arm triceps extensions",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"dumbbells"
|
||||
],
|
||||
"measurement": "repetitions-per-side",
|
||||
"dumbbellCount": 1
|
||||
},
|
||||
{
|
||||
"id": "side-plank-hip-raise",
|
||||
"name": "Side-plank hip raises",
|
||||
"category": "strength",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"weighted-vest"
|
||||
],
|
||||
"measurement": "repetitions-per-side"
|
||||
},
|
||||
{
|
||||
"id": "deep-squat-hold",
|
||||
"name": "Deep squat hold",
|
||||
"category": "isometric",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"bodyweight"
|
||||
],
|
||||
"measurement": "duration"
|
||||
},
|
||||
{
|
||||
"id": "ninety-ninety-hip-hold",
|
||||
"name": "90/90 hip hold",
|
||||
"category": "isometric",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"bodyweight"
|
||||
],
|
||||
"measurement": "duration-per-side"
|
||||
},
|
||||
{
|
||||
"id": "bird-dog-hold",
|
||||
"name": "Bird-dog hold",
|
||||
"category": "isometric",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"bodyweight"
|
||||
],
|
||||
"measurement": "duration-per-side"
|
||||
},
|
||||
{
|
||||
"id": "single-leg-balance",
|
||||
"name": "Single-leg balance",
|
||||
"category": "isometric",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"bodyweight"
|
||||
],
|
||||
"measurement": "duration-per-side"
|
||||
},
|
||||
{
|
||||
"id": "prone-swimmer-iso",
|
||||
"name": "Prone swimmer iso",
|
||||
"category": "isometric",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"bodyweight"
|
||||
],
|
||||
"measurement": "duration"
|
||||
},
|
||||
{
|
||||
"id": "daily-hang",
|
||||
"name": "Daily hanging practice",
|
||||
"category": "hang",
|
||||
"version": 1,
|
||||
"equipment": [
|
||||
"bodyweight"
|
||||
],
|
||||
"measurement": "duration",
|
||||
"protocols": [
|
||||
"attempts"
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"id": "documented-baseline",
|
||||
"version": 7,
|
||||
"version": 8,
|
||||
"source": "docs/WORKOUT_ROUTINE.md",
|
||||
"days": {
|
||||
"monday": {
|
||||
@@ -63,7 +63,7 @@
|
||||
"kind": "hanging-practice",
|
||||
"goalDurationSec": 120,
|
||||
"currentDurationSec": null,
|
||||
"goalFormat": null,
|
||||
"goalFormat": "continuous",
|
||||
"attemptCount": null,
|
||||
"breaks": null
|
||||
},
|
||||
@@ -250,7 +250,7 @@
|
||||
"kind": "hanging-practice",
|
||||
"goalDurationSec": 120,
|
||||
"currentDurationSec": null,
|
||||
"goalFormat": null,
|
||||
"goalFormat": "continuous",
|
||||
"attemptCount": null,
|
||||
"breaks": null
|
||||
},
|
||||
@@ -348,7 +348,7 @@
|
||||
}
|
||||
},
|
||||
"load": {
|
||||
"bodyweightOnly": true
|
||||
"vestKg": null
|
||||
},
|
||||
"notes": "Initially unweighted; focus on shoulder-blade protraction."
|
||||
},
|
||||
@@ -439,7 +439,7 @@
|
||||
"kind": "hanging-practice",
|
||||
"goalDurationSec": 120,
|
||||
"currentDurationSec": null,
|
||||
"goalFormat": null,
|
||||
"goalFormat": "continuous",
|
||||
"attemptCount": null,
|
||||
"breaks": null
|
||||
},
|
||||
@@ -515,6 +515,7 @@
|
||||
}
|
||||
},
|
||||
"load": {
|
||||
"vestKg": null,
|
||||
"dumbbellKgEach": null
|
||||
},
|
||||
"notes": "Use suitable dumbbell loading and controlled balance."
|
||||
@@ -659,7 +660,7 @@
|
||||
"kind": "hanging-practice",
|
||||
"goalDurationSec": 120,
|
||||
"currentDurationSec": null,
|
||||
"goalFormat": null,
|
||||
"goalFormat": "continuous",
|
||||
"attemptCount": null,
|
||||
"breaks": null
|
||||
},
|
||||
@@ -738,7 +739,7 @@
|
||||
"kind": "hanging-practice",
|
||||
"goalDurationSec": 120,
|
||||
"currentDurationSec": null,
|
||||
"goalFormat": null,
|
||||
"goalFormat": "continuous",
|
||||
"attemptCount": null,
|
||||
"breaks": null
|
||||
},
|
||||
@@ -827,7 +828,10 @@
|
||||
"max": 120
|
||||
}
|
||||
},
|
||||
"notes": "Duration not specified; distinct from the daily afternoon hang."
|
||||
"notes": "Duration not specified; distinct from the daily afternoon hang.",
|
||||
"load": {
|
||||
"vestKg": null
|
||||
}
|
||||
},
|
||||
{
|
||||
"order": 4,
|
||||
@@ -938,7 +942,7 @@
|
||||
"kind": "hanging-practice",
|
||||
"goalDurationSec": 120,
|
||||
"currentDurationSec": null,
|
||||
"goalFormat": null,
|
||||
"goalFormat": "continuous",
|
||||
"attemptCount": null,
|
||||
"breaks": null
|
||||
},
|
||||
@@ -1174,7 +1178,7 @@
|
||||
"kind": "hanging-practice",
|
||||
"goalDurationSec": 120,
|
||||
"currentDurationSec": null,
|
||||
"goalFormat": null,
|
||||
"goalFormat": "continuous",
|
||||
"attemptCount": null,
|
||||
"breaks": null
|
||||
},
|
||||
|
||||
@@ -18,7 +18,7 @@ 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.version).toBe(8)
|
||||
expect(initialRoutine.source).toBe('docs/WORKOUT_ROUTINE.md')
|
||||
expect(Object.keys(initialRoutine.days)).toEqual(weekdays)
|
||||
|
||||
@@ -91,7 +91,7 @@ describe('documented initial routine', () => {
|
||||
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 },
|
||||
prescription: { goalDurationSec: 120, currentDurationSec: null, attemptCount: null, breaks: null, goalFormat: 'continuous' },
|
||||
})
|
||||
expect(exercise(day, 'afternoon', 'daily-hang')).not.toHaveProperty('load')
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ function memoryIndexedDB() {
|
||||
const stores = new Set()
|
||||
const db = {
|
||||
objectStoreNames: { contains: (name) => stores.has(name) },
|
||||
createObjectStore: (name) => stores.add(name),
|
||||
createObjectStore: (name) => { stores.add(name); return { createIndex() {} } },
|
||||
close() {},
|
||||
transaction() {
|
||||
const transaction = {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const DATABASE_NAME = 'workout-tracker'
|
||||
const DATABASE_VERSION = 2
|
||||
const DATABASE_VERSION = 3
|
||||
|
||||
export function openLocalDatabase() {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -11,13 +11,20 @@ export function openLocalDatabase() {
|
||||
const request = globalThis.indexedDB.open(DATABASE_NAME, DATABASE_VERSION)
|
||||
let blocked = false
|
||||
request.onupgradeneeded = () => {
|
||||
if (!request.result.objectStoreNames.contains('performanceEntries')) {
|
||||
const store = request.result.createObjectStore('performanceEntries')
|
||||
store.createIndex('exercisePeriodFormat', ['exerciseId', 'period', 'format'])
|
||||
}
|
||||
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)
|
||||
else {
|
||||
request.result.onversionchange = () => request.result.close()
|
||||
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.')) }
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
export const equipmentLabels = { bodyweight: 'Bodyweight only', 'weighted-vest': 'Weighted vest', dumbbells: 'Dumbbell(s)', 'ez-curl-bar': 'EZ curl bar', 'straight-bar': 'Straight bar' }
|
||||
export const measurements = {
|
||||
repetitions: [{ key: 'reps', label: 'Reps', whole: true }],
|
||||
'repetitions-per-side': [{ key: 'leftReps', label: 'Left reps', whole: true }, { key: 'rightReps', label: 'Right reps', whole: true }],
|
||||
duration: [{ key: 'seconds', label: 'Seconds' }],
|
||||
'duration-per-side': [{ key: 'leftSeconds', label: 'Left seconds' }, { key: 'rightSeconds', label: 'Right seconds' }],
|
||||
distance: [{ key: 'metres', label: 'Metres' }],
|
||||
}
|
||||
const loadDefinitions = {
|
||||
'weighted-vest': { key: 'vestKg', label: 'Vest (kg)' },
|
||||
dumbbells: { key: 'dumbbellKgEach', label: 'Dumbbell (kg each)' },
|
||||
'ez-curl-bar': { key: 'ezBarTotalKg', label: 'EZ bar total (kg)' },
|
||||
'straight-bar': { key: 'straightBarTotalKg', label: 'Straight bar total (kg)' },
|
||||
}
|
||||
export function validDate(value) {
|
||||
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false
|
||||
const date = new Date(`${value}T12:00:00Z`)
|
||||
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value
|
||||
}
|
||||
export const copy = (value) => JSON.parse(JSON.stringify(value))
|
||||
export const loadColumns = (definition) => definition.equipment.filter((equipment) => loadDefinitions[equipment]).flatMap((equipment) => equipment === 'dumbbells'
|
||||
? [loadDefinitions[equipment], { key: 'dumbbellCount', label: 'Dumbbells used', whole: true, min: definition.fixedDumbbellCount ?? 1, max: definition.fixedDumbbellCount ?? 2, hidden: true }]
|
||||
: [loadDefinitions[equipment]])
|
||||
export const measurementColumns = (definition) => measurements[definition.measurement] ?? []
|
||||
export const formatFor = (definition, prescription) => definition.protocols?.includes('attempts') ? 'attempts' : prescription.kind === 'emom' ? 'emom' : 'sets'
|
||||
export function signature(definition, format) {
|
||||
return JSON.stringify([definition.id, definition.measurement, [...definition.equipment].sort(), definition.fixedDumbbellCount ?? null, format])
|
||||
}
|
||||
export function blankRow(definition, prior) {
|
||||
return { values: Object.fromEntries(measurementColumns(definition).map(({ key }) => [key, null])), load: Object.fromEntries(loadColumns(definition).map(({ key }) => [key, key === 'dumbbellCount' ? definition.fixedDumbbellCount ?? prior?.load[key] ?? definition.dumbbellCount : prior?.load[key] ?? null])), completed: false }
|
||||
}
|
||||
export function newPerformance(date, period, definition, prescription, format = formatFor(definition, prescription)) {
|
||||
return { schemaVersion: 1, date, period, exerciseId: definition.id, format, definition: copy(definition), prescription: copy(prescription), rows: Array.from({ length: format === 'emom' ? prescription.rounds : 1 }, () => blankRow(definition)) }
|
||||
}
|
||||
function validDefinition(definition) {
|
||||
return definition && typeof definition.id === 'string' && typeof definition.name === 'string' && Number.isSafeInteger(definition.version) && definition.version > 0
|
||||
&& Object.hasOwn(measurements, definition.measurement) && Array.isArray(definition.equipment) && definition.equipment.length > 0
|
||||
&& new Set(definition.equipment).size === definition.equipment.length && definition.equipment.every((item) => Object.hasOwn(equipmentLabels, item))
|
||||
&& (!definition.equipment.includes('bodyweight') || definition.equipment.length === 1)
|
||||
&& (!definition.equipment.includes('dumbbells') || [1, 2].includes(definition.dumbbellCount))
|
||||
&& (definition.fixedDumbbellCount == null || (definition.equipment.includes('dumbbells') && [1, 2].includes(definition.fixedDumbbellCount) && definition.fixedDumbbellCount === definition.dumbbellCount))
|
||||
&& (definition.protocols == null || (Array.isArray(definition.protocols) && definition.protocols.length > 0 && definition.protocols.every((format) => ['sets', 'emom', 'attempts'].includes(format))))
|
||||
}
|
||||
export function performanceError(record) {
|
||||
if (!record || record.schemaVersion !== 1 || !validDate(record.date) || !['morning', 'afternoon'].includes(record.period)
|
||||
|| !validDefinition(record.definition) || record.exerciseId !== record.definition.id || !['sets', 'emom', 'attempts'].includes(record.format)
|
||||
|| !record.prescription || typeof record.prescription.kind !== 'string' || !Array.isArray(record.rows) || record.rows.length === 0 || record.rows.length > 1000) return 'Invalid performance record.'
|
||||
if (!(record.definition.protocols ?? ['sets']).includes(record.format)) return 'Unsupported exercise format.'
|
||||
if (record.format === 'emom' && (!record.definition.protocols?.includes('emom') || !Number.isSafeInteger(record.prescription.rounds) || record.rows.length !== record.prescription.rounds)) return 'Invalid EMOM minutes.'
|
||||
if (record.format === 'attempts' && !record.definition.protocols?.includes('attempts')) return 'Invalid attempts.'
|
||||
for (const [index, row] of record.rows.entries()) {
|
||||
const error = rowError(row, index, record.definition)
|
||||
if (error) return error
|
||||
}
|
||||
return null
|
||||
}
|
||||
function rowError(row, index, definition) {
|
||||
if (!row || typeof row.completed !== 'boolean') return `Row ${index + 1}: invalid completion.`
|
||||
const groups = [['values', measurementColumns(definition)], ['load', loadColumns(definition)]]
|
||||
for (const [group, columns] of groups) {
|
||||
if (!row[group] || typeof row[group] !== 'object' || Array.isArray(row[group]) || Object.keys(row[group]).length !== columns.length || Object.keys(row[group]).some((key) => !columns.some((column) => column.key === key))) return `Row ${index + 1}: invalid fields.`
|
||||
for (const { key, label, whole, min = 0, max = Number.MAX_VALUE } of columns) {
|
||||
const value = row[group][key]
|
||||
if (value === null && !row.completed) continue
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max || (whole && !Number.isSafeInteger(value))) return `Row ${index + 1}: enter ${label.toLowerCase()}${row.completed ? ' before marking complete' : ' as a valid number'}.`
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function preparePerformanceForSave(record) {
|
||||
return { ...record, rows: record.rows.map((row, index) => {
|
||||
const load = { ...row.load }
|
||||
if (Object.hasOwn(load, 'dumbbellCount') && load.dumbbellCount == null) load.dumbbellCount = record.definition.fixedDumbbellCount ?? record.definition.dumbbellCount
|
||||
const candidate = { ...row, load, completed: true }
|
||||
// Missing values remain draft; invalid entered values still fail performanceError.
|
||||
return { ...candidate, completed: !rowError(candidate, index, record.definition) }
|
||||
}) }
|
||||
}
|
||||
|
||||
export function externalKg(row) {
|
||||
const l = row.load
|
||||
const weights = Object.entries(l).filter(([key]) => key !== 'dumbbellCount')
|
||||
if (weights.some(([, value]) => value == null) || ('dumbbellKgEach' in l && l.dumbbellCount == null)) return null
|
||||
return weights.reduce((sum, [key, value]) => sum + value * (key === 'dumbbellKgEach' ? l.dumbbellCount : 1), 0)
|
||||
}
|
||||
export function performanceTotals(record) {
|
||||
const completed = record.rows.filter((row) => row.completed && !rowError(row, 0, record.definition))
|
||||
const durations = completed.flatMap(({ values }) => Object.entries(values).filter(([key]) => /seconds/i.test(key)).map(([, value]) => value))
|
||||
return { completed: completed.length, reps: completed.reduce((sum, { values }) => sum + Object.entries(values).filter(([key]) => /reps/i.test(key)).reduce((total, [, value]) => total + value, 0), 0), longest: Math.max(0, ...durations), seconds: durations.reduce((sum, value) => sum + value, 0), volume: completed.reduce((sum, row) => sum + Object.entries(row.values).filter(([key]) => /reps/i.test(key)).reduce((total, [, value]) => total + value, 0) * (externalKg(row) ?? 0), 0) }
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { exerciseDefinitions, initialRoutine } from './data/index.js'
|
||||
import { blankRow, equipmentLabels, externalKg, loadColumns, measurementColumns, newPerformance, performanceError, performanceTotals, preparePerformanceForSave } from './performanceModel.js'
|
||||
const def = (id) => exerciseDefinitions.find((d) => d.id === id)
|
||||
const prescription = (id) => Object.values(initialRoutine.days).flatMap((day) => [...day.morning.exercises, ...day.afternoon.exercises]).find((e) => e.exerciseId === id).prescription
|
||||
const make = (id) => newPerformance('2026-11-03', 'morning', def(id), prescription(id))
|
||||
const expectedEquipment = {
|
||||
'pull-up': ['weighted-vest'], 'ez-bar-bent-over-row': ['ez-curl-bar'], 'single-arm-dumbbell-row': ['dumbbells'], 'suitcase-carry': ['dumbbells'],
|
||||
'weighted-deep-push-up': ['weighted-vest'], 'dumbbell-floor-fly': ['dumbbells'], 'push-up-plus': ['weighted-vest'], 'feet-elevated-weighted-push-up': ['weighted-vest'],
|
||||
'bulgarian-split-squat': ['weighted-vest', 'dumbbells'], 'single-leg-romanian-deadlift': ['weighted-vest', 'dumbbells'], squat: ['weighted-vest', 'dumbbells'], 'single-leg-calf-raise': ['weighted-vest', 'dumbbells'], 'front-plank': ['weighted-vest'],
|
||||
'chin-up': ['weighted-vest'], 'hanging-knee-raise': ['bodyweight'], 'finger-hang': ['weighted-vest'], 'single-arm-preacher-curl': ['dumbbells'], 'hammer-curl': ['dumbbells'],
|
||||
'single-arm-shoulder-press': ['dumbbells'], 'leaning-single-arm-lateral-raise': ['dumbbells'], 'bent-over-rear-delt-fly': ['dumbbells'], 'lying-dumbbell-triceps-extension': ['dumbbells'], 'single-arm-triceps-extension': ['dumbbells'], 'side-plank-hip-raise': ['weighted-vest'],
|
||||
'deep-squat-hold': ['bodyweight'], 'ninety-ninety-hip-hold': ['bodyweight'], 'bird-dog-hold': ['bodyweight'], 'single-leg-balance': ['bodyweight'], 'prone-swimmer-iso': ['bodyweight'], 'daily-hang': ['bodyweight'],
|
||||
}
|
||||
describe('metadata and actual performance', () => {
|
||||
it.each(exerciseDefinitions)('audits equipment for $id without a numeric load in definitions', (d) => {
|
||||
expect(d.equipment).toEqual(expectedEquipment[d.id])
|
||||
expect(d.equipment.every((e) => e in equipmentLabels)).toBe(true)
|
||||
expect(measurementColumns(d).length).toBeGreaterThan(0)
|
||||
expect(d).not.toHaveProperty('load')
|
||||
expect(performanceError(make(d.id))).toBeNull()
|
||||
if (d.equipment[0] === 'bodyweight') expect(loadColumns(d)).toEqual([])
|
||||
})
|
||||
it('supports straight-bar totals and distance without adding seed exercises', () => {
|
||||
const d = { ...def('ez-bar-bent-over-row'), equipment: ['straight-bar'], measurement: 'distance' }
|
||||
expect(loadColumns(d).map((c) => c.key)).toEqual(['straightBarTotalKg'])
|
||||
expect(measurementColumns(d).map((c) => c.key)).toEqual(['metres'])
|
||||
expect(externalKg({ load: { straightBarTotalKg: 25 } })).toBe(25)
|
||||
})
|
||||
it('requires measurements/load for completion, permits drafts, and rejects invalid fields', () => {
|
||||
const entry = make('front-plank')
|
||||
entry.rows[0].completed = true
|
||||
expect(performanceError(entry)).toMatch(/seconds/)
|
||||
entry.rows[0].values.seconds = 45
|
||||
expect(performanceError(entry)).toMatch(/vest/)
|
||||
entry.rows[0].load.vestKg = 0
|
||||
expect(performanceError(entry)).toBeNull()
|
||||
entry.rows[0].values.reps = 2
|
||||
expect(performanceError(entry)).toMatch(/invalid fields/)
|
||||
})
|
||||
it('sums variable per-minute resistance and keeps target and actuals independent', () => {
|
||||
const entry = make('pull-up')
|
||||
expect(entry.rows).toHaveLength(10)
|
||||
expect(entry.rows[0].load.vestKg).toBeNull()
|
||||
entry.rows[0] = { values: { reps: 4 }, load: { vestKg: 6 }, completed: true }
|
||||
entry.rows[1] = { values: { reps: 3 }, load: { vestKg: 10 }, completed: true }
|
||||
expect(performanceTotals(entry)).toMatchObject({ reps: 7, completed: 2, volume: 54 })
|
||||
})
|
||||
it('records independent side values and dumbbell count without counting handles', () => {
|
||||
const entry = make('bulgarian-split-squat')
|
||||
entry.rows[0] = { values: { leftReps: 10, rightReps: 8 }, load: { vestKg: 5, dumbbellKgEach: 12, dumbbellCount: 2 }, completed: true }
|
||||
expect(externalKg(entry.rows[0])).toBe(29)
|
||||
expect(performanceTotals(entry).volume).toBe(522)
|
||||
expect(loadColumns(def('weighted-deep-push-up')).map((c) => c.key)).toEqual(['vestKg'])
|
||||
const next = blankRow(entry.definition, entry.rows[0])
|
||||
expect(next.values).toEqual({ leftReps: null, rightReps: null })
|
||||
expect(next.load).toEqual(entry.rows[0].load)
|
||||
expect(next.completed).toBe(false)
|
||||
})
|
||||
it('separates cumulative hanging time from continuous success and incomplete drafts', () => {
|
||||
const entry = make('daily-hang')
|
||||
entry.rows = [60, 75, 150].map((seconds, i) => ({ values: { seconds }, load: {}, completed: i < 2 }))
|
||||
expect(performanceTotals(entry)).toMatchObject({ longest: 75, seconds: 135, completed: 2 })
|
||||
})
|
||||
})
|
||||
it('rejects impossible dates and excludes invalid completed drafts from achieved totals', () => {
|
||||
const record = make('daily-hang')
|
||||
record.rows[0].completed = true
|
||||
expect(performanceTotals(record)).toMatchObject({ completed: 0, longest: 0, seconds: 0 })
|
||||
record.date = '2026-02-30'
|
||||
expect(performanceError(record)).toMatch(/Invalid performance/)
|
||||
})
|
||||
it('rejects unsupported exercise formats and malformed protocol metadata', () => {
|
||||
const record = make('daily-hang')
|
||||
record.format = 'sets'
|
||||
expect(performanceError(record)).toMatch(/Unsupported exercise format/)
|
||||
record.definition.protocols = 'attempts'
|
||||
expect(performanceError(record)).toMatch(/Invalid performance/)
|
||||
})
|
||||
it('fixes floor-fly count at two and calculates paired resistance from kg each', () => {
|
||||
const record = make('dumbbell-floor-fly')
|
||||
record.rows[0] = { values: { reps: 12 }, load: { dumbbellKgEach: 8, dumbbellCount: 2 }, completed: true }
|
||||
expect(performanceError(record)).toBeNull()
|
||||
expect(performanceTotals(record).volume).toBe(192)
|
||||
record.rows[0].load.dumbbellCount = 1
|
||||
expect(performanceError(record)).toMatch(/dumbbells used/)
|
||||
})
|
||||
|
||||
it('derives completion on explicit save while retaining drafts and rejecting invalid actuals', () => {
|
||||
const original = make('front-plank')
|
||||
original.rows[0] = { values: { seconds: 0 }, load: { vestKg: 0 }, completed: false }
|
||||
let prepared = preparePerformanceForSave(original)
|
||||
expect(prepared.rows[0].completed).toBe(true)
|
||||
expect(original.rows[0].completed).toBe(false)
|
||||
original.rows[0].values.seconds = null
|
||||
prepared = preparePerformanceForSave(original)
|
||||
expect(prepared.rows[0].completed).toBe(false)
|
||||
expect(performanceError(prepared)).toBeNull()
|
||||
original.rows[0].load.vestKg = -1
|
||||
expect(performanceError(preparePerformanceForSave(original))).toMatch(/vest/)
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { openLocalDatabase } from './localDatabase.js'
|
||||
import { performanceError, signature } from './performanceModel.js'
|
||||
|
||||
export const performanceKey = (date, period, exerciseId) => `${date}:${period}:${exerciseId}`
|
||||
async function transaction(mode, action) {
|
||||
const db = await openLocalDatabase()
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction('performanceEntries', mode)
|
||||
let value
|
||||
try {
|
||||
const request = action(tx.objectStore('performanceEntries'))
|
||||
if (request) request.onsuccess = () => { value = request.result }
|
||||
} catch { tx.abort() }
|
||||
tx.oncomplete = () => { db.close(); resolve(value ?? null) }
|
||||
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not access detailed performance storage. Your changes were not saved.')) }
|
||||
})
|
||||
}
|
||||
export async function readPerformance(date, period, exerciseId) {
|
||||
const record = await transaction('readonly', (store) => store.get(performanceKey(date, period, exerciseId)))
|
||||
if (record && performanceError(record)) throw new Error('The saved performance record is invalid or unsupported.')
|
||||
return record
|
||||
}
|
||||
export async function writePerformance(record) {
|
||||
const error = performanceError(record)
|
||||
if (error) throw new Error(error)
|
||||
await transaction('readwrite', (store) => store.put(record, performanceKey(record.date, record.period, record.exerciseId)))
|
||||
}
|
||||
export async function previousPerformance(date, period, definition, format) {
|
||||
const records = await transaction('readonly', (store) => store.index('exercisePeriodFormat').getAll([definition.id, period, format]))
|
||||
return (records ?? []).filter((record) => record.date < date && !performanceError(record) && signature(record.definition, record.format) === signature(definition, format) && record.rows.some((row) => row.completed))
|
||||
.sort((a, b) => b.date.localeCompare(a.date))[0] ?? null
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { IDBFactory } from 'fake-indexeddb'
|
||||
import { readPerformance, writePerformance, previousPerformance } from './performanceStorage.js'
|
||||
import { exportBackup, importBackup, parseBackup } from './backupStorage.js'
|
||||
import { newPerformance } from './performanceModel.js'
|
||||
import { exerciseDefinitions } from './data/index.js'
|
||||
import { readStrengthEntry, writeStrengthEntry } from './strengthStorage.js'
|
||||
import { readDailyHangGoal, writeDailyHangGoal } from './hangGoalStorage.js'
|
||||
import { openLocalDatabase } from './localDatabase.js'
|
||||
const definition = exerciseDefinitions.find((d) => d.id === 'front-plank')
|
||||
const prescription = { kind: 'timed-sets', sets: { min: 3, max: 3 }, durationSec: { min: 30, max: 60 } }
|
||||
const entry = (date = '2026-11-03') => newPerformance(date, 'morning', definition, prescription)
|
||||
const completedEntry = (date) => {
|
||||
const record = entry(date)
|
||||
record.rows[0] = { values: { seconds: 45 }, load: { vestKg: 8 }, completed: true }
|
||||
return record
|
||||
}
|
||||
beforeEach(() => vi.stubGlobal('indexedDB', new IDBFactory()))
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
function seedDatabase(version) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open('workout-tracker', version)
|
||||
request.onupgradeneeded = () => {
|
||||
request.result.createObjectStore('routineOverrides').put(180, 'dailyHangGoalSec')
|
||||
if (version === 2) request.result.createObjectStore('strengthEntries').put({ kind: 'emom', totalReps: 36, externalKg: 6 }, '2026-10-27:pull-up')
|
||||
}
|
||||
request.onsuccess = () => { request.result.close(); resolve() }
|
||||
request.onerror = () => reject(request.error)
|
||||
})
|
||||
}
|
||||
it.each([1, 2])('upgrades v%i additively and preserves existing data verbatim', async (version) => {
|
||||
await seedDatabase(version)
|
||||
const db = await openLocalDatabase()
|
||||
expect(db.version).toBe(3)
|
||||
expect([...db.objectStoreNames]).toEqual(['performanceEntries', 'routineOverrides', 'strengthEntries'])
|
||||
expect(db.transaction('performanceEntries').objectStore('performanceEntries').indexNames.contains('exercisePeriodFormat')).toBe(true)
|
||||
db.close()
|
||||
expect(await readDailyHangGoal()).toBe(180)
|
||||
if (version === 2) expect(await readStrengthEntry('2026-10-27', 'pull-up')).toEqual({ kind: 'emom', totalReps: 36, externalKg: 6 })
|
||||
await writePerformance(entry())
|
||||
expect(await readPerformance('2026-11-03', 'morning', 'front-plank')).toEqual(entry())
|
||||
expect(await readPerformance('2026-11-04', 'morning', 'front-plank')).toBeNull()
|
||||
expect(await readPerformance('2026-11-03', 'afternoon', 'front-plank')).toBeNull()
|
||||
})
|
||||
it('keeps saved context and actuals after source definitions/prescriptions change', async () => {
|
||||
const record = completedEntry('2026-11-03')
|
||||
const original = structuredClone(record)
|
||||
await writePerformance(record)
|
||||
record.definition.equipment = ['bodyweight']; record.prescription.durationSec.min = 999; record.rows[0].load.vestKg = 99
|
||||
expect(await readPerformance(original.date, original.period, original.exerciseId)).toEqual(original)
|
||||
})
|
||||
it('suggests only an earlier completed session with matching exercise, period, format and equipment', async () => {
|
||||
await writePerformance(completedEntry('2026-10-29'))
|
||||
await writePerformance(entry('2026-11-02')) // incomplete draft cannot become a suggestion
|
||||
await writePerformance(completedEntry('2026-11-10')) // future excluded
|
||||
const changed = completedEntry('2026-11-01'); changed.definition.equipment = ['bodyweight']; changed.rows[0].load = {}
|
||||
await writePerformance(changed)
|
||||
const prior = await previousPerformance('2026-11-03', 'morning', definition, 'sets')
|
||||
expect(prior.date).toBe('2026-10-29')
|
||||
expect(await previousPerformance('2026-11-03', 'afternoon', definition, 'sets')).toBeNull()
|
||||
})
|
||||
it('round trips detailed drafts, legacy total/component/weight-only records and goal overrides', async () => {
|
||||
await writeDailyHangGoal(180)
|
||||
await writeStrengthEntry('2026-10-27', 'pull-up', { kind: 'emom', totalReps: 36, externalKg: 6 })
|
||||
await writeStrengthEntry('2026-10-29', 'squat', { kind: 'sets', sets: [{ reps: 10, externalKg: 34, load: { vestKg: 10, dumbbellKgEach: 12 } }] })
|
||||
await writeStrengthEntry('2026-11-03', 'suitcase-carry', { kind: 'load-sets', sets: [{ externalKg: 20, load: { dumbbellKg: 20 } }] })
|
||||
await writePerformance(completedEntry('2026-11-03'))
|
||||
const backup = await exportBackup()
|
||||
vi.stubGlobal('indexedDB', new IDBFactory())
|
||||
await importBackup(backup)
|
||||
expect(await exportBackup()).toBe(backup)
|
||||
expect(await readDailyHangGoal()).toBe(180)
|
||||
expect(await readPerformance('2026-11-03', 'morning', 'front-plank')).toEqual(completedEntry('2026-11-03'))
|
||||
})
|
||||
it('imports a legacy v1 adapter envelope without inventing detailed rows', async () => {
|
||||
await importBackup({ format: 'workout-tracker', version: 1, stores: { routineOverrides: [{ key: 'dailyHangGoalSec', value: 150 }], strengthEntries: [{ key: '2026-10-27:pull-up', value: { kind: 'emom', totalReps: 36, externalKg: 6 } }] } })
|
||||
expect(await readDailyHangGoal()).toBe(150)
|
||||
expect(await readPerformance('2026-10-27', 'morning', 'pull-up')).toBeNull()
|
||||
expect(await readStrengthEntry('2026-10-27', 'pull-up')).toMatchObject({ totalReps: 36 })
|
||||
})
|
||||
it('rolls back the whole import on a duplicate, and rejects invalid data before mutation', async () => {
|
||||
await writeDailyHangGoal(180)
|
||||
const before = await exportBackup()
|
||||
const incoming = parseBackup(before)
|
||||
// First add succeeds; the following duplicate must roll it back in the same transaction.
|
||||
incoming.stores.routineOverrides.unshift({ key: 'futurePlanEdit', value: { preserved: true } })
|
||||
await expect(importBackup(incoming)).rejects.toThrow(/unchanged/)
|
||||
expect(await exportBackup()).toBe(before)
|
||||
incoming.version = 999
|
||||
await expect(importBackup(incoming, { replace: true })).rejects.toThrow(/Unsupported/)
|
||||
expect(await exportBackup()).toBe(before)
|
||||
const invalid = parseBackup(before); invalid.stores.performanceEntries.push({ key: 'bad', value: { schemaVersion: 1 } })
|
||||
await expect(importBackup(invalid, { replace: true })).rejects.toThrow(/Invalid detailed/)
|
||||
expect(await exportBackup()).toBe(before)
|
||||
})
|
||||
it('supports explicit replacement atomically and preserves unknown legacy exercise IDs', async () => {
|
||||
await writeStrengthEntry('2026-11-02', 'retired-exercise', { kind: 'sets', sets: [{ reps: 8, externalKg: 12 }] })
|
||||
const backup = await exportBackup()
|
||||
await writeDailyHangGoal(300)
|
||||
await importBackup(backup, { replace: true })
|
||||
expect(await readDailyHangGoal()).toBeNull()
|
||||
expect(await readStrengthEntry('2026-11-02', 'retired-exercise')).toEqual({ kind: 'sets', sets: [{ reps: 8, externalKg: 12 }] })
|
||||
})
|
||||
it('rejects unsupported or malformed files without silently accepting incomplete backups', () => {
|
||||
expect(() => parseBackup('no json')).toThrow(/Invalid backup JSON/)
|
||||
expect(() => parseBackup({ format: 'workout-tracker', version: 2, stores: {} })).toThrow(/Missing/)
|
||||
})
|
||||
it('rejects failed detailed writes without modifying a saved record', async () => {
|
||||
const original = completedEntry('2026-11-03')
|
||||
await writePerformance(original)
|
||||
const invalid = structuredClone(original); invalid.rows[0].load.vestKg = -5
|
||||
await expect(writePerformance(invalid)).rejects.toThrow(/vest/)
|
||||
expect(await readPerformance(original.date, original.period, original.exerciseId)).toEqual(original)
|
||||
})
|
||||
it('reports blocked v2 upgrade without overwriting existing data', async () => {
|
||||
await seedDatabase(2)
|
||||
const old = await new Promise((resolve) => { const request = indexedDB.open('workout-tracker', 2); request.onsuccess = () => resolve(request.result) })
|
||||
const pending = openLocalDatabase()
|
||||
await expect(pending).rejects.toThrow(/blocked/)
|
||||
old.close()
|
||||
// Let the pending upgrade finish and close its connection after the blocker exits.
|
||||
const db = await openLocalDatabase(); db.close()
|
||||
expect(await readDailyHangGoal()).toBe(180)
|
||||
expect(await readStrengthEntry('2026-10-27', 'pull-up')).toMatchObject({ totalReps: 36, externalKg: 6 })
|
||||
})
|
||||
@@ -23,7 +23,7 @@ function validRecordedWeight(record) {
|
||||
return total != null && Math.abs(total - record.externalKg) < 1e-9
|
||||
}
|
||||
|
||||
function validEntry(entry) {
|
||||
export 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))
|
||||
|
||||
@@ -7,7 +7,7 @@ function existingV1Database() {
|
||||
let version = 1
|
||||
const db = {
|
||||
objectStoreNames: { contains: (name) => stores.has(name) },
|
||||
createObjectStore(name) { stores.set(name, new Map()) },
|
||||
createObjectStore(name) { stores.set(name, new Map()); return { createIndex() {} } },
|
||||
close() {},
|
||||
transaction(name) {
|
||||
const transaction = {
|
||||
|
||||
@@ -106,3 +106,38 @@ h1 { margin: .25rem 0 .55rem; font-size: clamp(2.2rem, 4vw, 3.25rem); line-heigh
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { scroll-behavior: auto !important; animation-duration: .01ms !important; transition-duration: .01ms !important; }
|
||||
}
|
||||
|
||||
/* TASK-015: scoped logging layout; existing visual language retained. */
|
||||
.performance-entry { margin-top: .8rem; padding-top: .65rem; border-top: 1px solid #e2e8e0; }
|
||||
.performance-toolbar, .performance-actions { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; }
|
||||
.performance-toolbar { margin-bottom: .5rem; }
|
||||
.performance-toolbar strong { color: #315847; font-size: .88rem; }
|
||||
.performance-rows { display: grid; gap: .45rem; }
|
||||
.performance-row, .performance-head { display: grid; grid-template-columns: 4.8rem repeat(var(--fields), minmax(0, 1fr)); align-items: end; gap: .5rem; }
|
||||
.performance-head { color: #52665a; font-size: .76rem; font-weight: 650; margin-bottom: .25rem; }
|
||||
.performance-row { padding: .45rem; border: 1px solid #e2e8e0; border-radius: 8px; }
|
||||
.performance-row.is-complete { border-color: #6c946c; background: #f0f5ec; }
|
||||
.performance-row label { min-width: 0; font-size: .8rem; color: #52665a; }
|
||||
.performance-row input[type=number] { width: 100%; min-width: 0; min-height: 40px; padding: .3rem .4rem; border: 1px solid #b6c7b8; border-radius: 6px; color: #254838; }
|
||||
.performance-row .field-label { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
|
||||
.row-number { align-self: center; font-size: .8rem; color: #52665a; }
|
||||
.performance-row .remove-row { grid-column: 1 / -1; justify-self: end; padding-block: .15rem; }
|
||||
.performance-actions { margin-top: .6rem; }
|
||||
.performance-status, .performance-summary { margin: .4rem 0 0; color: #52665a; font-size: .82rem; }
|
||||
.exercise-details, .legacy-entry { margin-top: .6rem; font-size: .85rem; overflow-wrap: anywhere; }
|
||||
.exercise-details p, .legacy-entry p { margin: .5rem 0; }
|
||||
.exercise-details summary, .legacy-entry summary { cursor: pointer; color: #315847; padding-block: .4rem; }
|
||||
.performance-entry button:focus-visible, .performance-entry input:focus-visible, .exercise-details summary:focus-visible, .legacy-entry summary:focus-visible { outline: 3px solid #9fc45c; outline-offset: 2px; }
|
||||
@media (max-width: 991px) {
|
||||
.performance-head { display: none; }
|
||||
.performance-row { grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: end; }
|
||||
.performance-row .field-label { position: static; width: auto; height: auto; clip-path: none; display: block; }
|
||||
.row-number { grid-column: 1 / -1; }
|
||||
}
|
||||
@media (max-width: 575px) {
|
||||
.exercise-card { gap: .5rem; padding: .75rem .6rem; }
|
||||
.exercise-number { flex-basis: 24px; height: 24px; }
|
||||
.performance-row { grid-template-columns: minmax(0, 1fr); }
|
||||
.performance-actions > button { min-height: 44px; }
|
||||
.performance-actions { align-items: stretch; }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user