Complete TASK-017 simplified EMOM and per-side entry

This commit is contained in:
rob
2026-11-07 15:29:12 +00:00
parent 9c0e82037f
commit 922d1f6bd7
30 changed files with 646 additions and 236 deletions
+7 -7
View File
@@ -16,20 +16,20 @@ it('runs detailed logging through the actual UI/storage boundary while preservin
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' } })
await waitFor(() => expect(within(card).getByLabelText('Total reps').disabled).toBe(false))
fireEvent.change(within(card).getByLabelText('Total reps'), { target: { value: '4' } })
fireEvent.change(within(card).getByLabelText('Weight (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')
const saved = await readPerformance('2026-11-03', 'morning', 'pull-up', 'emom-total')
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 } })
expect(saved.rows).toHaveLength(1)
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'))
await waitFor(() => expect(within(restored).getByLabelText('Weight (kg)').value).toBe('8'))
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
expect(await readPerformance('2026-11-10', 'morning', 'pull-up')).toBeNull()
expect(await readPerformance('2026-11-10', 'morning', 'pull-up', 'emom-total')).toBeNull()
})
it('uses a persisted continuous hang target without losing unsaved attempts when editing it', async () => {
await writeDailyHangGoal(180)
+112
View File
@@ -0,0 +1,112 @@
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 DetailedPerformanceEditor({ dateKey, period, definition, prescription, goalSeconds, historicalOnly = false }) {
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, sharedKeys) {
const value = raw === '' ? null : Number(raw)
change({ ...record, rows: record.rows.map((row, i) => i === index ? { ...row, completed: false, [group]: { ...row[group], ...Object.fromEntries((sharedKeys ?? [key]).map((field) => [field, 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 measurements = measurementColumns(record.definition)
const perSide = record.definition.measurement.endsWith('-per-side')
const inputMeasurements = perSide ? [{ ...measurements[0], label: record.definition.measurement === 'repetitions-per-side' ? 'Reps (each side)' : 'Seconds (each side)', sharedKeys: measurements.map(({ key }) => key) }] : measurements
const columns = [...inputMeasurements.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)
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>}
{historicalOnly && !hasSaved && loading && <p role="status">Loading earlier records…</p>}
{historicalOnly && !hasSaved && readFailed && <><p role="alert" className="strength-error">{error}</p><Button type="button" onClick={() => setRetry(retry + 1)}>Retry loading earlier records</Button></>}
{changedDefinition && <p role="status">This entry uses its saved exercise definition. Current targets above do not change its recorded equipment or measurements.</p>}
{(!historicalOnly || hasSaved) && <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>
</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, sharedKeys }) => <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={sharedKeys && !sharedKeys.every((field) => row[group][field] === row[group][key]) ? '' : row[group][key] ?? ''} disabled={disabled} onChange={(event) => update(index, group, key, event.target.value, sharedKeys)} /></label>)}
{perSide && row.values[measurements[0].key] !== row.values[measurements[1].key] && <p className="recorded-sides">Recorded: left {row.values[measurements[0].key] ?? 'blank'}, right {row.values[measurements[1].key] ?? 'blank'}. Enter a value above to replace both sides.</p>}
{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>
)
}
+75
View File
@@ -0,0 +1,75 @@
import { useEffect, useId, useState } from 'react'
import { Button } from 'react-bootstrap'
import { copy, newPerformance, performanceError, preparePerformanceForSave } from './performanceModel.js'
import { previousPerformance, readPerformance, writePerformance } from './performanceStorage.js'
import { readStrengthEntry } from './strengthStorage.js'
import DetailedPerformanceEditor from './DetailedPerformanceEditor.jsx'
export default function EmomTotalEditor({ dateKey, period, definition, prescription, ...rest }) {
const id = useId()
const [record, setRecord] = useState(null)
const [historyOpen, setHistoryOpen] = useState(false)
const [historical, setHistorical] = useState(false)
const [busy, setBusy] = useState(true)
const [failed, setFailed] = useState(false)
const [error, setError] = useState('')
const [notice, setNotice] = useState('')
const [retry, setRetry] = useState(0)
const [saved, setSaved] = useState(false)
useEffect(() => {
let active = true
setHistoryOpen(false); setBusy(true); setNotice(''); setError(''); setFailed(false); setRecord(null)
Promise.all([readPerformance(dateKey, period, definition.id, 'emom-total'), readPerformance(dateKey, period, definition.id), period === 'morning' ? readStrengthEntry(dateKey, definition.id) : null])
.then(([total, detailed, legacy]) => {
if (!active) return
setRecord(total ?? newPerformance(dateKey, period, definition, prescription, 'emom-total'))
setSaved(Boolean(total)); setHistorical(Boolean(detailed || legacy)); setBusy(false)
}).catch((failure) => { if (active) { setError(failure.message); setFailed(true); setBusy(false) } })
return () => { active = false }
}, [dateKey, period, definition, retry])
function update(group, key, raw) {
setRecord({ ...record, rows: [{ ...record.rows[0], completed: false, [group]: { ...record.rows[0][group], [key]: raw === '' ? null : Number(raw) } }] })
setNotice('Unsaved changes.'); setError('')
}
async function save(event) {
event.preventDefault()
const candidate = preparePerformanceForSave(saved ? record : { ...record, prescription: copy(prescription) })
const failure = performanceError(candidate)
if (failure) { setError(failure); return }
setBusy(true); setNotice(''); setError('')
try { await writePerformance(candidate); setRecord(candidate); setSaved(true); setNotice(candidate.rows[0].completed ? 'Saved' : 'Saved incomplete entry') }
catch (failure) { setError(failure.message) }
finally { setBusy(false) }
}
async function suggest() {
setBusy(true); setError('')
try {
if (record.rows[0].values.reps !== null || record.rows[0].load.vestKg !== null) { setNotice('Current entries kept.'); return }
const previous = await previousPerformance(dateKey, period, record.definition, 'emom-total')
if (!previous) { setNotice('No compatible previous session found.'); return }
setRecord({ ...record, rows: [{ ...copy(previous.rows[0]), completed: false }] })
setNotice(`Suggested from ${previous.date}. Review, then save.`)
} catch (failure) { setError(failure.message) }
finally { setBusy(false) }
}
return <div className="performance-entry">
<form onSubmit={save} aria-label={`${definition.name} actual performance`} aria-busy={busy} aria-describedby={error ? `${id}-error` : undefined}>
<div className="performance-toolbar"><strong>Actual performance</strong></div>
<div className="emom-total-fields">
<label>Weight (kg)<input aria-label="Weight (kg)" type="number" inputMode="decimal" min="0" step="any" value={record?.rows[0].load.vestKg ?? ''} disabled={busy || failed} onChange={(event) => update('load', 'vestKg', event.target.value)} /></label>
<label>Total reps<input aria-label="Total reps" type="number" inputMode="numeric" min="0" step="1" value={record?.rows[0].values.reps ?? ''} disabled={busy || failed} onChange={(event) => update('values', 'reps', event.target.value)} /></label>
</div>
<div className="performance-actions">
<Button type="button" variant="link" size="sm" disabled={busy || failed || !record} onClick={suggest}>Use previous session</Button>
<Button type="submit" size="sm" disabled={busy || failed || !record}>{busy ? 'Loading…' : 'Save performance'}</Button>
</div>
{failed && <Button type="button" onClick={() => setRetry(retry + 1)}>Retry loading</Button>}
<p role="status" className="performance-status">{notice}</p>
{error && <p role="alert" id={`${id}-error`} className="strength-error">{error}</p>}
</form>
{historical && <details className="legacy-entry" onToggle={(event) => setHistoryOpen(event.currentTarget.open)}><summary>Earlier records</summary>
<p>Original records are preserved separately. The total above is a separate entry for this session; do not add both representations together.</p>
{historyOpen && <DetailedPerformanceEditor historicalOnly dateKey={dateKey} period={period} definition={definition} prescription={prescription} {...rest} />}
</details>}
</div>
}
+103
View File
@@ -0,0 +1,103 @@
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 PerformanceEditor from './PerformanceEditor.jsx'
import { exerciseDefinitions } from './data/index.js'
import { newPerformance } from './performanceModel.js'
import { readPerformance, writePerformance } from './performanceStorage.js'
import { exportBackup, importBackup } from './backupStorage.js'
const definition = exerciseDefinitions.find((d) => d.id === 'pull-up')
const props = { dateKey: '2026-11-03', period: 'morning', definition, prescription: { kind: 'emom', rounds: 10, intervalSec: 60 } }
const fill = (name, value) => fireEvent.change(screen.getByLabelText(name), { target: { value } })
const ready = () => waitFor(() => expect(screen.getByLabelText('Weight (kg)').disabled).toBe(false))
beforeEach(() => vi.stubGlobal('indexedDB', new IDBFactory()))
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
it.each(['pull-up', 'chin-up'])('shows only weight and total reps for %s', async (id) => {
render(<PerformanceEditor {...props} definition={exerciseDefinitions.find((d) => d.id === id)} />); await ready()
expect(screen.getAllByRole('spinbutton')).toHaveLength(2)
expect(screen.queryByText(/Minute 1|Use conventional sets|Use EMOM minutes|Add set/)).toBeNull()
expect(screen.queryByRole('checkbox')).toBeNull()
})
it('saves zero weight and total reps, reloads and isolates dates and periods', async () => {
const view = render(<PerformanceEditor {...props} />); await ready()
fill('Weight (kg)', '0'); fill('Total reps', '37')
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
const record = await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')
expect(record.rows).toEqual([{ values: { reps: 37 }, load: { vestKg: 0 }, completed: true }])
view.unmount(); render(<PerformanceEditor {...props} />); await ready()
expect(screen.getByLabelText('Weight (kg)').value).toBe('0')
expect(screen.getByLabelText('Total reps').value).toBe('37')
expect(await readPerformance('2026-11-04', 'morning', definition.id, 'emom-total')).toBeNull()
expect(await readPerformance(props.dateKey, 'afternoon', definition.id, 'emom-total')).toBeNull()
const backup = await exportBackup(); vi.stubGlobal('indexedDB', new IDBFactory()); await importBackup(backup)
expect(await exportBackup()).toBe(backup)
})
it('keeps missing reps as an incomplete draft without inventing zero', async () => {
render(<PerformanceEditor {...props} />); await ready(); fill('Weight (kg)', '6')
expect(await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved incomplete entry')
expect((await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')).rows[0]).toMatchObject({ values: { reps: null }, completed: false })
})
it('preserves mixed historical minute loads when saving a new aggregate', async () => {
const old = newPerformance(props.dateKey, 'morning', definition, props.prescription)
old.rows[0] = { values: { reps: 4 }, load: { vestKg: 6 }, completed: true }
old.rows[1] = { values: { reps: 3 }, load: { vestKg: 10 }, completed: true }
await writePerformance(old)
render(<PerformanceEditor {...props} />); await ready()
expect(screen.getByLabelText('Weight (kg)').value).toBe('')
expect(screen.getByLabelText('Total reps').value).toBe('')
fill('Weight (kg)', '8'); fill('Total reps', '35')
const form = screen.getByRole('form', { name: 'Pull-ups actual performance' })
fireEvent.click(within(form).getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect(await readPerformance(props.dateKey, 'morning', definition.id)).toEqual(old)
const backup = await exportBackup(); vi.stubGlobal('indexedDB', new IDBFactory()); await importBackup(backup)
expect(await readPerformance(props.dateKey, 'morning', definition.id)).toEqual(old)
})
it('reports unavailable storage and offers retry without saving', async () => {
vi.stubGlobal('indexedDB', undefined)
render(<PerformanceEditor {...props} />)
await screen.findByRole('alert')
expect(screen.getByLabelText('Total reps').disabled).toBe(true)
vi.stubGlobal('indexedDB', new IDBFactory()); fireEvent.click(screen.getByRole('button', { name: 'Retry loading' })); await ready()
})
it('rejects invalid totals at storage boundary and retains drafts when a transaction fails', async () => {
render(<PerformanceEditor {...props} />); await ready()
fill('Weight (kg)', '6'); fill('Total reps', '36')
const original = indexedDB.open.bind(indexedDB)
vi.spyOn(indexedDB, 'open').mockImplementation(() => { throw new Error('Storage write failed') })
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Storage write failed')
expect(screen.getByLabelText('Total reps').value).toBe('36')
indexedDB.open.mockImplementation(original)
const invalid = newPerformance(props.dateKey, 'morning', definition, props.prescription, 'emom-total')
invalid.rows[0] = { values: { reps: 1.5 }, load: { vestKg: 6 }, completed: true }
await expect(writePerformance(invalid)).rejects.toThrow(/reps/)
invalid.rows[0] = { values: { reps: 36 }, load: { vestKg: -1 }, completed: true }
await expect(writePerformance(invalid)).rejects.toThrow(/vest/)
expect(await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')).toBeNull()
})
it('suggests only aggregate history without saving or overwriting current input', async () => {
const prior = newPerformance('2026-10-27', 'morning', definition, props.prescription, 'emom-total')
prior.rows[0] = { values: { reps: 34 }, load: { vestKg: 6 }, completed: true }
await writePerformance(prior)
render(<PerformanceEditor {...props} />); await ready()
fireEvent.click(screen.getByRole('button', { name: 'Use previous session' })); await screen.findByText(/Suggested from/)
expect(screen.getByLabelText('Total reps').value).toBe('34')
expect(await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')).toBeNull()
fill('Total reps', '35'); fireEvent.click(screen.getByRole('button', { name: 'Use previous session' })); await screen.findByText('Current entries kept.')
expect(screen.getByLabelText('Total reps').value).toBe('35')
})
it('opens original minute history for explicit edits without changing the aggregate', async () => {
const old = newPerformance(props.dateKey, 'morning', definition, props.prescription)
old.rows[0] = { values: { reps: 4 }, load: { vestKg: 6 }, completed: true }
await writePerformance(old)
render(<PerformanceEditor {...props} />); await ready()
expect(screen.queryByLabelText('Minute 1 reps')).toBeNull()
const details = screen.getByText('Earlier records').closest('details')
details.open = true; fireEvent(details, new Event('toggle'))
await waitFor(() => expect(screen.getByLabelText('Minute 1 reps').value).toBe('4'))
fill('Minute 1 reps', '3')
const historicalForm = screen.getByLabelText('Minute 1 reps').closest('form')
fireEvent.click(within(historicalForm).getByRole('button', { name: 'Save performance' })); await within(historicalForm).findByText('Saved')
expect((await readPerformance(props.dateKey, 'morning', definition.id)).rows[0].values.reps).toBe(3)
expect(await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')).toBeNull()
})
+4 -106
View File
@@ -1,108 +1,6 @@
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'
import EmomTotalEditor from './EmomTotalEditor.jsx'
import DetailedPerformanceEditor from './DetailedPerformanceEditor.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>
)
export default function PerformanceEditor(props) {
return props.prescription.kind === 'emom' ? <EmomTotalEditor {...props} /> : <DetailedPerformanceEditor {...props} />
}
+10 -17
View File
@@ -8,7 +8,7 @@ vi.mock('./performanceStorage.js', () => ({
}))
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 PerformanceEditor from './DetailedPerformanceEditor.jsx'
import App from './App.jsx'
import { exerciseDefinitions, initialRoutine } from './data/index.js'
import { loadColumns, measurementColumns, newPerformance } from './performanceModel.js'
@@ -23,8 +23,9 @@ it.each(exerciseDefinitions)('shows only applicable controls for $id', async (de
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 measurementLabels = definition.measurement.endsWith('-per-side') ? [{ label: definition.measurement === 'repetitions-per-side' ? 'Reps (each side)' : 'Seconds (each side)' }] : measurementColumns(definition)
const expected = [...measurementLabels, ...loadColumns(definition).filter((column) => !column.hidden)].map((column) => column.label.toLowerCase())
for (const label of ['reps', 'reps (each side)', 'seconds (each side)', '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))
}
@@ -51,19 +52,19 @@ it('completes filled rows on save, keeps incomplete drafts, then restores by dat
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 () => {
it('logs one duration for each side without repetitions and preserves blank drafts', async () => {
render(<PerformanceEditor {...props('bird-dog-hold')} />); await ready()
fill('Set 1 left seconds', 20);
fill('Set 1 seconds (each side)', '');
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)
expect(memory.records.values().next().value.rows[0]).toMatchObject({ completed: false, values: { leftSeconds: null, rightSeconds: null } })
fill('Set 1 seconds (each side)', 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 })
expect(memory.records.values().next().value.rows[0].values).toEqual({ leftSeconds: 25, 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)
fill('Set 1 reps (each side)', 10); 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')
@@ -153,14 +154,6 @@ it('snapshots the current target on first save without changing a previously sav
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 }
+61
View File
@@ -0,0 +1,61 @@
import { IDBFactory } from 'fake-indexeddb'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import PerformanceEditor from './PerformanceEditor.jsx'
import { exerciseDefinitions } from './data/index.js'
import { newPerformance } from './performanceModel.js'
import { readPerformance, writePerformance } from './performanceStorage.js'
const props = (id) => ({ dateKey: '2026-11-07', period: 'morning', definition: exerciseDefinitions.find((d) => d.id === id), prescription: { kind: 'sets', sets: { min: 3, max: 4 } } })
const ready = () => waitFor(() => expect(screen.getByRole('button', { name: 'Save performance' }).disabled).toBe(false))
const fill = (label, value) => fireEvent.change(screen.getByLabelText(label), { target: { value: String(value) } })
beforeEach(() => vi.stubGlobal('indexedDB', new IDBFactory()))
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
it('saves preacher curls with one reps input per set and restores both sides accurately', async () => {
const p = props('single-arm-preacher-curl')
const view = render(<PerformanceEditor {...p} />); await ready()
expect(screen.queryByLabelText(/left reps|right reps/i)).toBeNull()
expect(screen.getAllByRole('spinbutton')).toHaveLength(2)
fill('Set 1 reps (each side)', 12); fill('Set 1 dumbbell (kg each)', 8)
fireEvent.click(screen.getByRole('button', { name: 'Add set' }))
expect(screen.getByLabelText('Set 2 reps (each side)').value).toBe('')
expect(screen.getByLabelText('Set 2 dumbbell (kg each)').value).toBe('8')
fill('Set 2 reps (each side)', 0)
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
const record = await readPerformance(p.dateKey, p.period, p.definition.id)
expect(record.rows[0]).toMatchObject({ values: { leftReps: 12, rightReps: 12 }, completed: true })
expect(record.rows[1]).toMatchObject({ values: { leftReps: 0, rightReps: 0 }, completed: true })
view.unmount(); render(<PerformanceEditor {...p} />); await ready()
expect(screen.getByLabelText('Set 1 reps (each side)').value).toBe('12')
fill('Set 1 reps (each side)', '')
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect((await readPerformance(p.dateKey, p.period, p.definition.id)).rows[0]).toMatchObject({ values: { leftReps: null, rightReps: null }, completed: false })
})
it.each([[10, 8], [10, null]])('preserves historical side values %s/%s until explicitly replaced', async (left, right) => {
const p = props('single-arm-preacher-curl')
const original = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
original.rows[0] = { values: { leftReps: left, rightReps: right }, load: { dumbbellKgEach: 8, dumbbellCount: 1 }, completed: right !== null }
await writePerformance(original)
render(<PerformanceEditor {...p} />); await ready()
expect(screen.getByText(/Recorded: left 10, right/)).toBeTruthy()
expect(screen.getByLabelText('Set 1 reps (each side)').value).toBe('')
expect(await readPerformance(p.dateKey, p.period, p.definition.id)).toEqual(original)
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect(await readPerformance(p.dateKey, p.period, p.definition.id)).toEqual(original)
fill('Set 1 reps (each side)', 9)
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect((await readPerformance(p.dateKey, p.period, p.definition.id)).rows[0].values).toEqual({ leftReps: 9, rightReps: 9 })
})
it('records a hold through one seconds input and suggests both sides as an unsaved draft', async () => {
const p = props('bird-dog-hold')
const prior = newPerformance('2026-11-06', p.period, p.definition, p.prescription)
prior.rows[0] = { values: { leftSeconds: 25, rightSeconds: 25 }, load: {}, completed: true }
await writePerformance(prior)
const view = render(<PerformanceEditor {...p} />); await ready()
expect(screen.getAllByRole('spinbutton')).toHaveLength(1)
fireEvent.click(screen.getByRole('button', { name: 'Use previous session' })); await screen.findByText(/Suggested from/)
expect(screen.getByLabelText('Set 1 seconds (each side)').value).toBe('25')
expect(await readPerformance(p.dateKey, p.period, p.definition.id)).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
view.unmount(); render(<PerformanceEditor {...p} />); await ready()
expect(screen.getByLabelText('Set 1 seconds (each side)').value).toBe('25')
})
+3 -3
View File
@@ -15,7 +15,7 @@ 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 (backup?.format !== 'workout-tracker' || ![1, 2, 3].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) {
@@ -26,7 +26,7 @@ export function parseBackup(input) {
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 === 'performanceEntries' && (performanceError(entry.value) || entry.key !== performanceKey(entry.value.date, entry.value.period, entry.value.exerciseId, entry.value.format))) 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.')
}
}
@@ -43,7 +43,7 @@ export async function exportBackup() {
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.oncomplete = () => { db.close(); resolve(JSON.stringify({ format: 'workout-tracker', version: 3, reference: { exerciseDefinitions, initialRoutine }, stores: data })) }
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not export local data.')) }
})
}
+4 -2
View File
@@ -4,12 +4,14 @@
`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.
`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.
`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. New EMOM totals use format emom-total with one reps/vestKg row and a separate :emom-total key; historical ten-minute rows remain unchanged; durations and hangs never require reps.
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.
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 v3 for all three stores and v1/v2 compatibility readers, validation and atomic non-overwriting or explicit-replacement import. TASK-009 owns backup UI; this task adds no Settings controls.
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.
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.
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.
Per-side UI uses one shared reps/seconds field per set. It writes both stored side values only on explicit input; unequal/partial history remains unchanged and displays read-only values until replaced (ADR-021).
+3 -2
View File
@@ -43,10 +43,11 @@ function validDefinition(definition) {
}
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)
|| !validDefinition(record.definition) || record.exerciseId !== record.definition.id || !['sets', 'emom', 'emom-total', '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.definition.protocols ?? ['sets']).includes(record.format === 'emom-total' ? 'emom' : 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 === 'emom-total' && (record.rows.length !== 1 || record.definition.measurement !== 'repetitions' || record.definition.equipment.length !== 1 || record.definition.equipment[0] !== 'weighted-vest')) return 'Invalid EMOM total.'
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)
+10
View File
@@ -99,3 +99,13 @@ it('derives completion on explicit save while retaining drafts and rejecting inv
original.rows[0].load.vestKg = -1
expect(performanceError(preparePerformanceForSave(original))).toMatch(/vest/)
})
it('validates aggregate EMOM independently of historical minute-row shape', () => {
const record = newPerformance('2026-11-03', 'morning', def('pull-up'), prescription('pull-up'), 'emom-total')
expect(record.rows).toHaveLength(1)
record.rows[0] = { values: { reps: 36 }, load: { vestKg: 6 }, completed: true }
expect(performanceError(record)).toBeNull()
expect(performanceTotals(record)).toMatchObject({ reps: 36, volume: 216 })
record.rows.push(structuredClone(record.rows[0]))
expect(performanceError(record)).toMatch(/Invalid EMOM total/)
})
+4 -4
View File
@@ -1,7 +1,7 @@
import { openLocalDatabase } from './localDatabase.js'
import { performanceError, signature } from './performanceModel.js'
export const performanceKey = (date, period, exerciseId) => `${date}:${period}:${exerciseId}`
export const performanceKey = (date, period, exerciseId, format) => `${date}:${period}:${exerciseId}${format === 'emom-total' ? ':emom-total' : ''}`
async function transaction(mode, action) {
const db = await openLocalDatabase()
return new Promise((resolve, reject) => {
@@ -15,15 +15,15 @@ async function transaction(mode, action) {
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)))
export async function readPerformance(date, period, exerciseId, format) {
const record = await transaction('readonly', (store) => store.get(performanceKey(date, period, exerciseId, format)))
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)))
await transaction('readwrite', (store) => store.put(record, performanceKey(record.date, record.period, record.exerciseId, record.format)))
}
export async function previousPerformance(date, period, definition, format) {
const records = await transaction('readonly', (store) => store.index('exercisePeriodFormat').getAll([definition.id, period, format]))
+6
View File
@@ -123,3 +123,9 @@ it('reports blocked v2 upgrade without overwriting existing data', async () => {
expect(await readDailyHangGoal()).toBe(180)
expect(await readStrengthEntry('2026-10-27', 'pull-up')).toMatchObject({ totalReps: 36, externalKg: 6 })
})
it('still imports the previous v2 envelope without changing detailed records', async () => {
const record = completedEntry('2026-11-03')
await importBackup({ format: 'workout-tracker', version: 2, stores: { routineOverrides: [], strengthEntries: [], performanceEntries: [{ key: '2026-11-03:morning:front-plank', value: record }] } })
expect(await readPerformance(record.date, record.period, record.exerciseId)).toEqual(record)
})
+7
View File
@@ -141,3 +141,10 @@ h1 { margin: .25rem 0 .55rem; font-size: clamp(2.2rem, 4vw, 3.25rem); line-heigh
.performance-actions > button { min-height: 44px; }
.performance-actions { align-items: stretch; }
}
.emom-total-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .6rem; }
.emom-total-fields label { min-width: 0; font-size: .8rem; color: #52665a; }
.emom-total-fields input { display: block; width: 100%; min-width: 0; min-height: 40px; padding: .3rem .4rem; border: 1px solid #b6c7b8; border-radius: 6px; color: #254838; }
@media (max-width: 360px) { .emom-total-fields { grid-template-columns: minmax(0, 1fr); } }
.recorded-sides { grid-column: 1 / -1; margin: .2rem 0; font-size: .8rem; color: #52665a; }