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
+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} />
}