Complete TASK-005 dated notes and daily body weight

This commit is contained in:
rob
2026-11-11 14:15:08 +00:00
parent be0ff2b2e4
commit e3bd365add
17 changed files with 512 additions and 22 deletions
+10
View File
@@ -4,6 +4,7 @@ import { exerciseDefinitions, initialRoutine } from './data/index.js'
import { addCalendarDays, localCalendarDate, localDateKey, prescriptionLabel, restLabel, routineForDate, startOfWeek } from './routineView.js'
import HangGoalEditor from './HangGoalEditor.jsx'
import PerformanceEditor from './PerformanceEditor.jsx'
import WorkoutDetailEditor from './WorkoutDetailEditor.jsx'
import { equipmentLabels } from './performanceModel.js'
import { readDailyHangGoal, writeDailyHangGoal } from './hangGoalStorage.js'
@@ -59,6 +60,9 @@ function ExerciseList({ exercises, dateKey, period, hangGoalSeconds, hangGoalLoa
<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} />
<details className="workout-details exercise-notes"><summary>Your notes</summary>
<WorkoutDetailEditor identity={{ kind: 'exercise-note', date: dateKey, period, exerciseId }} label={`${definition.name} notes`} saveLabel="Save exercise notes" help="For this exercise on the selected date and period." />
</details>
{isHang && <HangGoalEditor goalSeconds={hangGoalSeconds} loading={hangGoalLoading} storageError={hangGoalError} onSave={onSaveHangGoal} />}
<details className="exercise-details"><summary>Exercise details</summary>
{notes && <p>{notes}</p>}
@@ -137,6 +141,12 @@ 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>}
<details className="workout-details session-details"><summary>Session notes and body weight</summary>
<div className="session-detail-fields">
<WorkoutDetailEditor identity={{ kind: 'session-note', date: localDateKey(selectedDate), period }} label={`${period === 'morning' ? 'Morning' : 'Afternoon'} session notes`} saveLabel="Save session notes" help="For this session on the selected date." />
<WorkoutDetailEditor identity={{ kind: 'body-weight', date: localDateKey(selectedDate) }} label="Body weight (kg)" saveLabel="Save body weight" help="One entry for the selected date, shared across Morning and Afternoon." />
</div>
</details>
{session.exercises.length > 0 && <ExerciseList exercises={session.exercises} period={period} dateKey={localDateKey(selectedDate)} hangGoalSeconds={hangGoalSeconds} hangGoalLoading={hangGoalLoading} hangGoalError={hangGoalError} onSaveHangGoal={onSaveHangGoal} />}
</section>
+49
View File
@@ -0,0 +1,49 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
const storage = vi.hoisted(() => ({ read: vi.fn(), save: vi.fn() }))
vi.mock('./workoutDetailStorage.js', async (original) => ({ ...await original(), readWorkoutDetail: storage.read, saveWorkoutDetail: storage.save }))
import WorkoutDetailEditor from './WorkoutDetailEditor.jsx'
const identity = { kind: 'session-note', date: '2026-11-11', period: 'morning' }
const props = { identity, label: 'Session notes', saveLabel: 'Save notes', help: 'For this session.' }
function deferred() { let resolve; const promise = new Promise((yes) => { resolve = yes }); return { promise, resolve } }
beforeEach(() => { vi.resetAllMocks(); storage.read.mockResolvedValue(null); storage.save.mockResolvedValue(undefined) })
afterEach(cleanup)
const field = () => screen.getByRole('textbox')
const ready = () => waitFor(() => expect(field().disabled).toBe(false))
it('ignores late reads after date navigation', async () => {
const old = deferred(); const next = deferred()
storage.read.mockReturnValueOnce(old.promise).mockReturnValueOnce(next.promise)
const view = render(<WorkoutDetailEditor {...props} />)
view.rerender(<WorkoutDetailEditor {...props} identity={{ ...identity, date: '2026-11-12' }} />)
await act(async () => { next.resolve({ text: 'New day' }); await next.promise })
expect(field().value).toBe('New day')
await act(async () => { old.resolve({ text: 'Old day' }); await old.promise })
expect(field().value).toBe('New day')
expect(storage.save).not.toHaveBeenCalled()
})
it('keeps an old in-flight save scoped to its original period without changing the new draft', async () => {
const job = deferred(); storage.save.mockReturnValueOnce(job.promise)
const view = render(<WorkoutDetailEditor {...props} />); await ready()
fireEvent.change(field(), { target: { value: 'Morning observation' } })
fireEvent.submit(screen.getByRole('form', { name: props.label }))
fireEvent.submit(screen.getByRole('form', { name: props.label }))
expect(storage.save).toHaveBeenCalledTimes(1)
expect(storage.save).toHaveBeenCalledWith(identity, 'Morning observation')
view.rerender(<WorkoutDetailEditor {...props} identity={{ ...identity, period: 'afternoon' }} />); await ready()
fireEvent.change(field(), { target: { value: 'Afternoon draft' } })
await act(async () => { job.resolve(); await job.promise })
expect(field().value).toBe('Afternoon draft')
expect(screen.getByRole('status').textContent).toBe('Unsaved changes.')
})
it('keeps a note draft after write failure and retries without another read', async () => {
storage.save.mockRejectedValueOnce(new Error('Quota exceeded'))
render(<WorkoutDetailEditor {...props} />); await ready()
fireEvent.change(field(), { target: { value: 'Keep my draft' } })
fireEvent.click(screen.getByRole('button', { name: 'Save notes' }))
await screen.findByRole('alert')
expect(field().value).toBe('Keep my draft')
expect(screen.getByRole('button', { name: 'Save notes' }).disabled).toBe(false)
fireEvent.click(screen.getByRole('button', { name: 'Save notes' }))
await screen.findByText('Session notes saved.')
expect(storage.read).toHaveBeenCalledTimes(1)
})
+71
View File
@@ -0,0 +1,71 @@
import { useEffect, useId, useRef, useState } from 'react'
import { Button, Form } from 'react-bootstrap'
import { detailKey, noteLimit, readWorkoutDetail, saveWorkoutDetail } from './workoutDetailStorage.js'
function DetailForm({ identity, label, saveLabel, help }) {
const id = useId()
const key = detailKey(identity)
const weight = identity.kind === 'body-weight'
const [draft, setDraft] = useState('')
const [loading, setLoading] = useState(true)
const [readFailed, setReadFailed] = useState(false)
const [saving, setSaving] = useState(false)
const [retry, setRetry] = useState(0)
const [error, setError] = useState('')
const [notice, setNotice] = useState('')
const active = useRef(false)
const inFlight = useRef(false)
useEffect(() => {
let current = true
active.current = true
setLoading(true); setReadFailed(false); setError('')
readWorkoutDetail(identity).then((record) => {
if (!current) return
setDraft(record ? String(weight ? record.weightKg : record.text) : '')
setLoading(false)
}).catch((failure) => {
if (current) { setReadFailed(true); setError(failure.message); setLoading(false) }
})
return () => { current = false; active.current = false }
}, [key, retry])
function change(value) { setDraft(value); setNotice('Unsaved changes.'); setError('') }
async function save(event) {
event.preventDefault()
if (loading || readFailed || inFlight.current) return
const value = weight ? draft.trim() === '' ? null : Number(draft) : draft
if (weight && value !== null && (!Number.isFinite(value) || value <= 0)) { setError('Enter body weight in kg above zero.'); return }
if (!weight && draft.length > noteLimit) { setError(`Use no more than ${noteLimit} characters.`); return }
inFlight.current = true
setSaving(true); setError(''); setNotice('')
try {
await saveWorkoutDetail(identity, value)
if (active.current) {
const empty = weight ? value === null : !draft.trim()
setDraft(empty ? '' : String(value))
setNotice(empty ? `${label} removed.` : `${label} saved.`)
}
} catch (failure) { if (active.current) setError(failure.message) }
finally { inFlight.current = false; if (active.current) setSaving(false) }
}
const disabled = loading || readFailed || saving
return <Form className="workout-detail-form" aria-label={label} onSubmit={save} noValidate aria-busy={loading || saving}>
<Form.Label htmlFor={id}>{label} <span className="optional-field">(optional)</span></Form.Label>
<Form.Control id={id} as={weight ? 'input' : 'textarea'} type={weight ? 'number' : undefined} rows={weight ? undefined : 3}
className={weight ? 'body-weight-input' : undefined} inputMode={weight ? 'decimal' : undefined} min={weight ? 0 : undefined} step={weight ? 'any' : undefined}
maxLength={weight ? undefined : noteLimit} value={draft} disabled={disabled} onChange={(event) => change(event.target.value)}
aria-describedby={`${id}-help${error ? ` ${id}-error` : ''}`} aria-invalid={Boolean(error)} />
<p id={`${id}-help`} className="detail-help">{help} Clear, then Save to remove a saved value.</p>
<div className="detail-actions">
<Button type="submit" size="sm" disabled={disabled}>{saving ? 'Saving…' : saveLabel}</Button>
<Button type="button" variant="outline-secondary" size="sm" disabled={disabled || draft === ''} onClick={() => change('')}>Clear</Button>
{readFailed && <Button type="button" variant="outline-secondary" size="sm" onClick={() => setRetry((value) => value + 1)}>Retry loading</Button>}
</div>
<p role="status" className="detail-status">{loading ? `Loading ${label.toLowerCase()}…` : notice}</p>
{error && <p id={`${id}-error`} className="strength-error" role="alert">{error}</p>}
</Form>
}
export default function WorkoutDetailEditor(props) {
// Every identity has independent draft/read/save state, including during navigation.
return <DetailForm key={detailKey(props.identity)} {...props} />
}
+94
View File
@@ -0,0 +1,94 @@
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 WorkoutDetailEditor from './WorkoutDetailEditor.jsx'
import App from './App.jsx'
import { readWorkoutDetail, saveWorkoutDetail } from './workoutDetailStorage.js'
import { exportBackup } from './backupStorage.js'
const identity = { kind: 'session-note', date: '2026-11-11', period: 'morning' }
const noteProps = { identity, label: 'Morning session notes', saveLabel: 'Save session notes', help: 'This session only.' }
const weightProps = { identity: { kind: 'body-weight', date: identity.date }, label: 'Body weight (kg)', saveLabel: 'Save body weight', help: 'Shared across periods.' }
const field = (label) => screen.getByLabelText(label, { exact: false, selector: 'input,textarea' })
const ready = (label) => waitFor(() => expect(field(label).disabled).toBe(false))
const fill = (label, value) => fireEvent.change(field(label), { target: { value } })
beforeEach(() => { vi.stubGlobal('indexedDB', new IDBFactory()); window.localStorage.clear() })
afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers() })
it.each([noteProps, weightProps])('saves and reloads $label only on explicit Save; Clear remains a draft', async (p) => {
const value = p === noteProps ? 'Felt comfortable\nKeep this context' : '73.25'
const before = await exportBackup()
const view = render(<WorkoutDetailEditor {...p} />); await ready(p.label)
fill(p.label, value)
expect(await exportBackup()).toBe(before)
fireEvent.click(screen.getByRole('button', { name: p.saveLabel }))
await screen.findByText(`${p.label} saved.`)
view.unmount(); render(<WorkoutDetailEditor {...p} />); await ready(p.label)
expect(field(p.label).value).toBe(value)
fireEvent.click(screen.getByRole('button', { name: 'Clear', exact: true }))
expect(await readWorkoutDetail(p.identity)).not.toBeNull()
fireEvent.click(screen.getByRole('button', { name: p.saveLabel }))
await screen.findByText(`${p.label} removed.`)
expect(await readWorkoutDetail(p.identity)).toBeNull()
})
it('rejects zero weight and preserves typed input after a failed save', async () => {
render(<WorkoutDetailEditor {...weightProps} />); await ready(weightProps.label)
fill(weightProps.label, '0')
fireEvent.click(screen.getByRole('button', { name: 'Save body weight' }))
await screen.findByText('Enter body weight in kg above zero.')
expect(await readWorkoutDetail(weightProps.identity)).toBeNull()
fill(weightProps.label, '73.5')
vi.spyOn(indexedDB, 'open').mockImplementation(() => { throw new Error('Write unavailable') })
fireEvent.click(screen.getByRole('button', { name: 'Save body weight' }))
await screen.findByText('Write unavailable')
expect(field(weightProps.label).value).toBe('73.5')
expect(screen.queryByText(/saved\./)).toBeNull()
})
it('offers recovery after an unavailable read without enabling overwrite', async () => {
vi.stubGlobal('indexedDB', undefined)
render(<WorkoutDetailEditor {...noteProps} />)
await screen.findByRole('alert')
expect(screen.getByRole('button', { name: 'Save session notes' }).disabled).toBe(true)
vi.stubGlobal('indexedDB', new IDBFactory())
fireEvent.click(screen.getByRole('button', { name: 'Retry loading' })); await ready(noteProps.label)
expect(screen.queryByRole('alert')).toBeNull()
})
it('isolates note drafts across date and period changes', async () => {
await saveWorkoutDetail(identity, 'Saved morning')
const view = render(<WorkoutDetailEditor {...noteProps} />); await ready(noteProps.label)
fill(noteProps.label, 'Unsaved morning')
view.rerender(<WorkoutDetailEditor {...noteProps} identity={{ ...identity, period: 'afternoon' }} label="Afternoon session notes" />)
await ready('Afternoon session notes')
expect(field(/Afternoon session notes/).value).toBe('')
view.rerender(<WorkoutDetailEditor {...noteProps} />); await ready(noteProps.label)
expect(field(/Morning session notes/).value).toBe('Saved morning')
})
it('integrates notes on empty sessions and shares body weight across periods without creating performance', async () => {
vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date(2026, 10, 9, 12))
render(<App />)
expect(screen.getByText('Full body stretch routine')).toBeTruthy()
const session = screen.getByText('Session notes and body weight').closest('details')
session.open = true
await ready('Morning session notes'); await ready('Body weight (kg)')
fill('Morning session notes', 'Easy stretch'); fill('Body weight (kg)', '74.2')
fireEvent.click(within(session).getByRole('button', { name: 'Save session notes' }))
await screen.findByText('Morning session notes saved.')
fireEvent.click(within(session).getByRole('button', { name: 'Save body weight' }))
await screen.findByText('Body weight (kg) saved.')
fireEvent.click(screen.getByRole('button', { name: 'Afternoon', exact: true }))
await ready('Afternoon session notes')
expect(field(/Afternoon session notes/).value).toBe('')
expect(field(/Body weight \(kg\)/).value).toBe('74.2')
const exercise = screen.getByText('Daily hanging practice').closest('.exercise-card')
within(exercise).getByText('Your notes').closest('details').open = true
await ready('Daily hanging practice notes')
fill('Daily hanging practice notes', 'Grip felt good')
fireEvent.click(within(exercise).getByRole('button', { name: 'Save exercise notes' }))
await screen.findByText('Daily hanging practice notes saved.')
const backup = JSON.parse(await exportBackup())
expect(backup.stores.performanceEntries).toEqual([])
expect(backup.stores.strengthEntries).toEqual([])
expect(backup.stores.workoutDetails).toHaveLength(3)
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
await ready('Afternoon session notes'); await ready('Body weight (kg)')
expect(field(/Body weight \(kg\)/).value).toBe('')
expect(field(/Afternoon session notes/).value).toBe('')
})
+9 -3
View File
@@ -3,8 +3,9 @@ import { initialRoutine, exerciseDefinitions } from './data/index.js'
import { openLocalDatabase } from './localDatabase.js'
import { performanceError } from './performanceModel.js'
import { performanceKey } from './performanceStorage.js'
import { detailError, detailKey } from './workoutDetailStorage.js'
import { validEntry } from './strengthStorage.js'
const stores = ['routineOverrides', 'strengthEntries', 'performanceEntries']
const stores = ['routineOverrides', 'strengthEntries', 'performanceEntries', 'workoutDetails']
function validJSON(value) {
if (value === null || typeof value === 'string' || typeof value === 'boolean') return true
@@ -15,16 +16,19 @@ 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, 3].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, 4].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.')
if (backup.version < 4 && Object.hasOwn(backup.stores, 'workoutDetails')) throw new Error('Unsupported backup store for this version.')
// Version 1 is the legacy adapter envelope with the two original stores.
for (const store of stores) {
if (store === 'workoutDetails' && backup.version < 4) continue
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 === 'workoutDetails' && (detailError(entry.value) || entry.key !== detailKey(entry.value))) throw new Error('Invalid notes or body-weight entry.')
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, 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 +47,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: 3, reference: { exerciseDefinitions, initialRoutine }, stores: data })) }
tx.oncomplete = () => { db.close(); resolve(JSON.stringify({ format: 'workout-tracker', version: 4, reference: { exerciseDefinitions, initialRoutine }, stores: data })) }
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not export local data.')) }
})
}
@@ -54,6 +58,8 @@ export async function importBackup(input, { replace = false } = {}) {
const tx = db.transaction(stores, 'readwrite')
try {
for (const name of stores) {
// Old backups never represented observations; replacing them must not erase new data.
if (name === 'workoutDetails' && backup.version < 4) continue
const store = tx.objectStore(name)
if (replace) store.clear()
for (const { key, value } of backup.stores[name]) store.add(value, key)
+2 -2
View File
@@ -1,5 +1,5 @@
const DATABASE_NAME = 'workout-tracker'
const DATABASE_VERSION = 3
const DATABASE_VERSION = 4
export function openLocalDatabase() {
return new Promise((resolve, reject) => {
@@ -15,7 +15,7 @@ export function openLocalDatabase() {
const store = request.result.createObjectStore('performanceEntries')
store.createIndex('exercisePeriodFormat', ['exerciseId', 'period', 'format'])
}
for (const store of ['routineOverrides', 'strengthEntries']) {
for (const store of ['routineOverrides', 'strengthEntries', 'workoutDetails']) {
if (!request.result.objectStoreNames.contains(store)) request.result.createObjectStore(store)
}
}
+2 -2
View File
@@ -31,8 +31,8 @@ function seedDatabase(version) {
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.version).toBe(4)
expect([...db.objectStoreNames]).toEqual(['performanceEntries', 'routineOverrides', 'strengthEntries', 'workoutDetails'])
expect(db.transaction('performanceEntries').objectStore('performanceEntries').indexNames.contains('exercisePeriodFormat')).toBe(true)
db.close()
expect(await readDailyHangGoal()).toBe(180)
+17
View File
@@ -234,3 +234,20 @@ h1 { margin: .25rem 0 .55rem; font-size: clamp(2.2rem, 4vw, 3.25rem); line-heigh
}
.strength-actions, .strength-fields, .strength-set { flex-wrap: wrap; }
.performance-head span, .performance-row label, .emom-total-fields label { overflow-wrap: anywhere; }
/* TASK-005 optional observations extend the existing disclosure/form language. */
.workout-details { margin-top: .8rem; border-top: 1px solid var(--border-subtle); font-size: .85rem; overflow-wrap: anywhere; }
.workout-details summary { padding-block: .65rem; color: var(--accent); cursor: pointer; }
.session-detail-fields { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); gap: 1rem; }
.workout-detail-form { min-width: 0; padding-block: .4rem; }
.workout-detail-form .form-label { color: var(--text-secondary); font-weight: 650; }
.workout-detail-form .form-control { min-height: 44px; background: var(--surface-input); color: var(--text-primary); border-color: var(--border-control); }
.workout-detail-form textarea { resize: vertical; }
.workout-detail-form .body-weight-input { width: var(--numeric-width); max-width: 100%; padding: .3rem .4rem; font-variant-numeric: tabular-nums; }
.workout-detail-form .form-control:disabled { background: var(--surface-panel); color: var(--text-secondary); }
.workout-detail-form .form-control:focus-visible, .workout-details summary:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; box-shadow: none; }
.optional-field, .detail-help, .detail-status { color: var(--text-secondary); font-size: .8rem; }
.detail-help, .detail-status { margin: .4rem 0; }
.detail-actions { display: flex; flex-wrap: wrap; gap: .5rem; }
.detail-actions .btn { min-height: 44px; }
@media (max-width: 767px) { .session-detail-fields { grid-template-columns: minmax(0, 1fr); } }
+51
View File
@@ -0,0 +1,51 @@
import { openLocalDatabase } from './localDatabase.js'
import { validDate } from './performanceModel.js'
export const noteLimit = 4000
export function detailKey({ kind, date, period, exerciseId }) {
if (!validDate(date)) throw new Error('Invalid observation date.')
if (kind === 'body-weight') return `${date}:body-weight`
if (!['morning', 'afternoon'].includes(period)) throw new Error('Invalid observation period.')
if (kind === 'session-note') return `${date}:${period}:session-note`
if (kind === 'exercise-note' && typeof exerciseId === 'string' && /^[a-z0-9][a-z0-9-]*$/.test(exerciseId)) return `${date}:${period}:${exerciseId}:exercise-note`
throw new Error('Invalid observation identity.')
}
export function detailError(record) {
try { detailKey(record) } catch { return 'Invalid observation identity.' }
if (record.schemaVersion !== 1) return 'Unsupported observation schema.'
const weight = record.kind === 'body-weight'
const keys = ['schemaVersion', 'kind', 'date', ...(weight ? ['weightKg'] : ['period', 'text', ...(record.kind === 'exercise-note' ? ['exerciseId'] : [])])]
if (Object.keys(record).length !== keys.length || Object.keys(record).some((key) => !keys.includes(key))) return 'Invalid observation fields.'
if (weight) {
if (typeof record.weightKg !== 'number' || !Number.isFinite(record.weightKg) || record.weightKg <= 0) return 'Enter body weight in kg above zero.'
} else if (typeof record.text !== 'string' || !record.text.trim() || record.text.length > noteLimit) return `Enter a note of up to ${noteLimit} characters.`
return null
}
async function transact(mode, action) {
const db = await openLocalDatabase()
return new Promise((resolve, reject) => {
const tx = db.transaction('workoutDetails', mode)
let value
try {
const request = action(tx.objectStore('workoutDetails'))
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 notes or body weight. Your changes were not saved.')) }
})
}
export async function readWorkoutDetail(identity) {
const key = detailKey(identity)
const record = await transact('readonly', (store) => store.get(key))
if (record !== null && (detailError(record) || detailKey(record) !== key)) throw new Error('Saved notes or body weight are invalid or unsupported. Your saved data was not changed.')
return record
}
export async function saveWorkoutDetail(identity, value) {
const key = detailKey(identity)
const empty = identity.kind === 'body-weight' ? value === null : typeof value === 'string' && !value.trim()
if (empty) { await transact('readwrite', (store) => store.delete(key)); return }
const record = { schemaVersion: 1, ...identity, ...(identity.kind === 'body-weight' ? { weightKg: value } : { text: value }) }
const error = detailError(record)
if (error) throw new Error(error)
await transact('readwrite', (store) => store.put(record, key))
}
+122
View File
@@ -0,0 +1,122 @@
import { IDBFactory } from 'fake-indexeddb'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { detailKey, readWorkoutDetail, saveWorkoutDetail } from './workoutDetailStorage.js'
import { exportBackup, importBackup, parseBackup } from './backupStorage.js'
import { openLocalDatabase } from './localDatabase.js'
import { newPerformance } from './performanceModel.js'
import { exerciseDefinitions } from './data/index.js'
const day = '2026-11-11'
const identities = [
[{ kind: 'session-note', date: day, period: 'morning' }, 'Session observation'],
[{ kind: 'exercise-note', date: day, period: 'morning', exerciseId: 'front-plank' }, 'Use a mat'],
[{ kind: 'body-weight', date: day }, 73.25],
]
beforeEach(() => vi.stubGlobal('indexedDB', new IDBFactory()))
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() })
it.each(identities)('saves, reloads and explicitly clears $kind observations only', async (identity, value) => {
const before = await exportBackup()
expect(await readWorkoutDetail(identity)).toBeNull()
expect(await exportBackup()).toBe(before)
await saveWorkoutDetail(identity, value)
expect(await readWorkoutDetail(identity)).toEqual({ schemaVersion: 1, ...identity, ...(identity.kind === 'body-weight' ? { weightKg: value } : { text: value }) })
expect(await readWorkoutDetail({ ...identity, date: '2026-11-12' })).toBeNull()
if (identity.period) expect(await readWorkoutDetail({ ...identity, period: 'afternoon' })).toBeNull()
if (identity.exerciseId) expect(await readWorkoutDetail({ ...identity, exerciseId: 'side-plank' })).toBeNull()
await saveWorkoutDetail(identity, identity.kind === 'body-weight' ? null : '')
expect(await exportBackup()).toBe(before)
})
it.each([0, -1, NaN, Infinity, '73', undefined])('rejects invalid body weight %s without mutation', async (value) => {
const [identity] = identities[2]
await saveWorkoutDetail(identity, 70)
const before = await exportBackup()
await expect(saveWorkoutDetail(identity, value)).rejects.toThrow()
expect(await exportBackup()).toBe(before)
})
it('rejects invalid notes, identities and corrupt saved observations', async () => {
await expect(saveWorkoutDetail(identities[0][0], 'x'.repeat(4001))).rejects.toThrow(/4000/)
await expect(saveWorkoutDetail({ ...identities[0][0], date: '2026-02-30' }, 'x')).rejects.toThrow(/date/)
await expect(saveWorkoutDetail({ ...identities[0][0], period: 'night' }, 'x')).rejects.toThrow(/period/)
await expect(saveWorkoutDetail({ ...identities[1][0], exerciseId: 'bad:id' }, 'x')).rejects.toThrow(/identity/)
const db = await openLocalDatabase()
await new Promise((resolve) => {
const tx = db.transaction('workoutDetails', 'readwrite')
tx.objectStore('workoutDetails').put(false, detailKey(identities[0][0]))
tx.oncomplete = resolve
})
db.close()
await expect(readWorkoutDetail(identities[0][0])).rejects.toThrow(/invalid or unsupported/)
})
it('upgrades a v3 database without changing original goals, legacy or detailed records', async () => {
const definition = exerciseDefinitions.find((d) => d.id === 'pull-up')
const performance = newPerformance(day, 'morning', definition, { kind: 'emom', rounds: 10 }, 'emom-total')
performance.rows[0] = { values: { reps: 35 }, load: { vestKg: 6 }, completed: true }
const legacy = { kind: 'emom', totalReps: 33, externalKg: 8 }
await new Promise((resolve, reject) => {
const request = indexedDB.open('workout-tracker', 3)
request.onupgradeneeded = () => {
request.result.createObjectStore('routineOverrides').put(180, 'dailyHangGoalSec')
request.result.createObjectStore('strengthEntries').put(legacy, `${day}:pull-up`)
const store = request.result.createObjectStore('performanceEntries')
store.createIndex('exercisePeriodFormat', ['exerciseId', 'period', 'format'])
store.put(performance, `${day}:morning:pull-up:emom-total`)
}
request.onsuccess = () => { request.result.close(); resolve() }
request.onerror = () => reject(request.error)
})
await readWorkoutDetail(identities[0][0])
const db = await openLocalDatabase(); expect(db.version).toBe(4); db.close()
const backup = JSON.parse(await exportBackup())
expect(backup.stores.routineOverrides).toEqual([{ key: 'dailyHangGoalSec', value: 180 }])
expect(backup.stores.strengthEntries).toEqual([{ key: `${day}:pull-up`, value: legacy }])
expect(backup.stores.performanceEntries).toEqual([{ key: `${day}:morning:pull-up:emom-total`, value: performance }])
expect(backup.stores.workoutDetails).toEqual([])
})
it('round trips v4 observations and rejects a duplicate import atomically', async () => {
for (const [identity, value] of identities) await saveWorkoutDetail(identity, value)
const before = await exportBackup()
expect(JSON.parse(before).version).toBe(4)
vi.stubGlobal('indexedDB', new IDBFactory())
await importBackup(before)
expect(await exportBackup()).toBe(before)
const duplicate = JSON.parse(before)
duplicate.stores.routineOverrides.push({ key: 'dailyHangGoalSec', value: 999 })
await expect(importBackup(duplicate)).rejects.toThrow(/Import failed/)
expect(await exportBackup()).toBe(before)
})
it.each([1, 2, 3])('imports old v%i backups without erasing new observations even with replacement', async (version) => {
for (const [identity, value] of identities) await saveWorkoutDetail(identity, value)
const prior = JSON.parse(await exportBackup()).stores.workoutDetails
const backup = { format: 'workout-tracker', version, stores: { routineOverrides: [], strengthEntries: [], ...(version > 1 ? { performanceEntries: [] } : {}) } }
await importBackup(backup, { replace: true })
expect(JSON.parse(await exportBackup()).stores.workoutDetails).toEqual(prior)
})
it('replaces observations explicitly with v4 and validates every incoming record before mutation', async () => {
await saveWorkoutDetail(...identities[0])
const backup = JSON.parse(await exportBackup())
backup.stores.workoutDetails = [{ key: detailKey(identities[2][0]), value: { schemaVersion: 1, ...identities[2][0], weightKg: 72 } }]
await importBackup(backup, { replace: true })
expect(await readWorkoutDetail(identities[0][0])).toBeNull()
const before = await exportBackup()
for (const mutate of [
(b) => { b.version = 999 },
(b) => { b.stores.workoutDetails[0].value.weightKg = -1 },
(b) => { b.stores.workoutDetails[0].key = 'wrong-key' },
(b) => { b.stores.workoutDetails[0].value.schemaVersion = 2 },
(b) => { b.stores.workoutDetails.push(b.stores.workoutDetails[0]) },
(b) => { delete b.stores.workoutDetails },
]) {
const invalid = JSON.parse(before); mutate(invalid)
await expect(importBackup(invalid, { replace: true })).rejects.toThrow()
expect(await exportBackup()).toBe(before)
}
const badNote = JSON.parse(before)
badNote.stores.workoutDetails[0] = { key: detailKey(identities[0][0]), value: { schemaVersion: 1, ...identities[0][0], text: 'x'.repeat(4001) } }
expect(() => parseBackup(badNote)).toThrow(/notes/)
})
it('reports a blocked upgrade and succeeds after the old connection closes', async () => {
const old = await new Promise((resolve) => { const request = indexedDB.open('workout-tracker', 3); request.onsuccess = () => resolve(request.result) })
await expect(readWorkoutDetail(identities[0][0])).rejects.toThrow(/blocked/)
old.close()
expect(await readWorkoutDetail(identities[0][0])).toBeNull()
})