Complete TASK-019 conditional previous-session availability
This commit is contained in:
@@ -3,10 +3,13 @@ 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 usePreviousAvailability from './usePreviousAvailability.js'
|
||||
import StrengthEntryEditor from './StrengthEntryEditor.jsx'
|
||||
|
||||
export default function DetailedPerformanceEditor({ dateKey, period, definition, prescription, goalSeconds, historicalOnly = false }) {
|
||||
const id = useId()
|
||||
const contextKey = JSON.stringify([dateKey, period, definition])
|
||||
const [loadedContext, setLoadedContext] = useState(null)
|
||||
const [record, setRecord] = useState(() => newPerformance(dateKey, period, definition, prescription))
|
||||
const [legacy, setLegacy] = useState(null)
|
||||
const [hasSaved, setHasSaved] = useState(false)
|
||||
@@ -19,10 +22,12 @@ export default function DetailedPerformanceEditor({ dateKey, period, definition,
|
||||
const [dirty, setDirty] = useState(false)
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
setLoadedContext(null)
|
||||
setLoading(true)
|
||||
Promise.all([readPerformance(dateKey, period, definition.id), period === 'morning' ? readStrengthEntry(dateKey, definition.id) : Promise.resolve(null)])
|
||||
.then(([saved, old]) => {
|
||||
if (!active) return
|
||||
setLoadedContext(contextKey)
|
||||
setRecord(saved ?? newPerformance(dateKey, period, definition, prescription))
|
||||
setLegacy(old)
|
||||
setHasSaved(Boolean(saved))
|
||||
@@ -34,6 +39,10 @@ export default function DetailedPerformanceEditor({ dateKey, period, definition,
|
||||
return () => { active = false }
|
||||
}, [dateKey, period, definition, retry])
|
||||
|
||||
const previousAvailability = usePreviousAvailability({
|
||||
dateKey, period, record, contextKey,
|
||||
enabled: loadedContext === contextKey && !loading && !readFailed,
|
||||
})
|
||||
function change(next) { setRecord(next); setDirty(true); setNotice(''); setError('') }
|
||||
function update(index, group, key, raw, sharedKeys) {
|
||||
const value = raw === '' ? null : Number(raw)
|
||||
@@ -98,9 +107,13 @@ export default function DetailedPerformanceEditor({ dateKey, period, definition,
|
||||
</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>
|
||||
{previousAvailability.available && <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>
|
||||
{previousAvailability.error && <div>
|
||||
<p role="alert" className="strength-error">Could not check previous sessions. {previousAvailability.error}</p>
|
||||
<Button type="button" variant="outline-secondary" size="sm" disabled={disabled} onClick={previousAvailability.retry}>Retry previous-session lookup</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>}
|
||||
|
||||
+14
-1
@@ -3,10 +3,13 @@ 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 usePreviousAvailability from './usePreviousAvailability.js'
|
||||
import DetailedPerformanceEditor from './DetailedPerformanceEditor.jsx'
|
||||
|
||||
export default function EmomTotalEditor({ dateKey, period, definition, prescription, ...rest }) {
|
||||
const id = useId()
|
||||
const contextKey = JSON.stringify([dateKey, period, definition])
|
||||
const [loadedContext, setLoadedContext] = useState(null)
|
||||
const [record, setRecord] = useState(null)
|
||||
const [historyOpen, setHistoryOpen] = useState(false)
|
||||
const [historical, setHistorical] = useState(false)
|
||||
@@ -18,15 +21,21 @@ export default function EmomTotalEditor({ dateKey, period, definition, prescript
|
||||
const [saved, setSaved] = useState(false)
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
setLoadedContext(null)
|
||||
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
|
||||
setLoadedContext(contextKey)
|
||||
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])
|
||||
const previousAvailability = usePreviousAvailability({
|
||||
dateKey, period, record, contextKey,
|
||||
enabled: loadedContext === contextKey && !failed && Boolean(record),
|
||||
})
|
||||
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('')
|
||||
@@ -60,9 +69,13 @@ export default function EmomTotalEditor({ dateKey, period, definition, prescript
|
||||
<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>
|
||||
{previousAvailability.available && <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>
|
||||
{previousAvailability.error && <div>
|
||||
<p role="alert" className="strength-error">Could not check previous sessions. {previousAvailability.error}</p>
|
||||
<Button type="button" variant="outline-secondary" size="sm" disabled={busy || failed} onClick={previousAvailability.retry}>Retry previous-session lookup</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>}
|
||||
|
||||
@@ -80,10 +80,10 @@ it('suggests only aggregate history without saving or overwriting current input'
|
||||
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/)
|
||||
fireEvent.click(await screen.findByRole('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.')
|
||||
fill('Total reps', '35'); fireEvent.click(await screen.findByRole('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 () => {
|
||||
|
||||
@@ -95,13 +95,13 @@ it('applies previous-session suggestions only to empty drafts and never marks co
|
||||
const p = props('front-plank'); memory.previous = newPerformance('2026-10-29', p.period, p.definition, p.prescription)
|
||||
memory.previous.rows[0] = { values: { seconds: 45 }, load: { vestKg: 8 }, completed: true }
|
||||
render(<PerformanceEditor {...p} />); await ready()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Use previous session' }))
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Use previous session' }))
|
||||
await screen.findByText(/Suggested from 2026-10-29/)
|
||||
expect(screen.getByLabelText('Set 1 seconds').value).toBe('45')
|
||||
expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy()
|
||||
expect(memory.records.size).toBe(0)
|
||||
fill('Set 1 vest (kg)', 9)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Use previous session' }))
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Use previous session' }))
|
||||
await screen.findByText(/Current entries kept/)
|
||||
expect(screen.getByLabelText('Set 1 vest (kg)').value).toBe('9')
|
||||
})
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { IDBFactory } from 'fake-indexeddb'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import PerformanceEditor from './PerformanceEditor.jsx'
|
||||
import DetailedPerformanceEditor from './DetailedPerformanceEditor.jsx'
|
||||
import { exerciseDefinitions } from './data/index.js'
|
||||
import { newPerformance } from './performanceModel.js'
|
||||
import * as storage from './performanceStorage.js'
|
||||
import { exportBackup } from './backupStorage.js'
|
||||
|
||||
const cases = [
|
||||
['reps', 'dumbbell-floor-fly', 'sets', 'Set 1 reps'],
|
||||
['hold', 'front-plank', 'sets', 'Set 1 seconds'],
|
||||
['hang', 'daily-hang', 'attempts', 'Attempt 1 seconds'],
|
||||
['EMOM total', 'pull-up', 'emom-total', 'Total reps'],
|
||||
]
|
||||
function props(id, format = 'sets') {
|
||||
return { dateKey: '2026-11-10', period: 'morning', definition: exerciseDefinitions.find((d) => d.id === id), prescription: { kind: format.startsWith('emom') ? 'emom' : 'sets', rounds: 10 }, goalSeconds: 120 }
|
||||
}
|
||||
function completed(p, format, date = '2026-11-03') {
|
||||
const entry = newPerformance(date, p.period, p.definition, p.prescription, format)
|
||||
const row = entry.rows[0]
|
||||
for (const key of Object.keys(row.values)) row.values[key] = 0
|
||||
for (const key of Object.keys(row.load)) if (key !== 'dumbbellCount') row.load[key] = 0
|
||||
row.completed = true
|
||||
return entry
|
||||
}
|
||||
const action = () => screen.queryByRole('button', { name: 'Use previous session' })
|
||||
async function settledLookup(spy) {
|
||||
await waitFor(() => expect(spy).toHaveBeenCalled())
|
||||
await act(async () => { await spy.mock.results.at(-1).value })
|
||||
}
|
||||
beforeEach(() => vi.stubGlobal('indexedDB', new IDBFactory()))
|
||||
afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() })
|
||||
|
||||
it.each(cases)('keeps the action absent in fresh %s editors and never writes during lookup', async (_, id, format) => {
|
||||
const p = props(id, format)
|
||||
const before = await exportBackup()
|
||||
const lookup = vi.spyOn(storage, 'previousPerformance')
|
||||
render(<PerformanceEditor {...p} />)
|
||||
expect(action()).toBeNull()
|
||||
await settledLookup(lookup)
|
||||
expect(action()).toBeNull()
|
||||
expect(await exportBackup()).toBe(before)
|
||||
})
|
||||
|
||||
it.each(cases)('offers compatible zero-valued %s history without applying or saving it automatically', async (_, id, format, label) => {
|
||||
const p = props(id, format)
|
||||
const prior = completed(p, format)
|
||||
await storage.writePerformance(prior)
|
||||
const before = await exportBackup()
|
||||
render(<PerformanceEditor {...p} />)
|
||||
const button = await screen.findByRole('button', { name: 'Use previous session' })
|
||||
expect(screen.getByLabelText(label).value).toBe('')
|
||||
expect(await exportBackup()).toBe(before)
|
||||
fireEvent.click(button)
|
||||
await screen.findByText(/Suggested from/)
|
||||
expect(screen.getByLabelText(label).value).toBe('0')
|
||||
expect(await exportBackup()).toBe(before)
|
||||
// Existing entry protection remains even though history is available.
|
||||
fireEvent.change(screen.getByLabelText(label), { target: { value: '17' } })
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Use previous session' }))
|
||||
await screen.findByText(/Current entries kept/)
|
||||
expect(screen.getByLabelText(label).value).toBe('17')
|
||||
expect(await exportBackup()).toBe(before)
|
||||
})
|
||||
|
||||
it.each(['draft', 'current', 'future', 'incompatible', 'other period', 'other exercise'])('ignores %s regular history', async (kind) => {
|
||||
const p = props('front-plank')
|
||||
const source = completed(p, 'sets')
|
||||
if (kind === 'draft') source.rows[0].completed = false
|
||||
if (kind === 'current') source.date = p.dateKey
|
||||
if (kind === 'future') source.date = '2026-11-11'
|
||||
if (kind === 'incompatible') { source.definition.equipment = ['bodyweight']; source.rows[0].load = {} }
|
||||
if (kind === 'other period') source.period = 'afternoon'
|
||||
if (kind === 'other exercise') { source.exerciseId = 'side-plank'; source.definition.id = 'side-plank' }
|
||||
await storage.writePerformance(source)
|
||||
const lookup = vi.spyOn(storage, 'previousPerformance')
|
||||
render(<PerformanceEditor {...p} />)
|
||||
await settledLookup(lookup)
|
||||
expect(action()).toBeNull()
|
||||
})
|
||||
|
||||
it.each(['draft', 'current', 'future', 'minute format'])('ignores %s EMOM history', async (kind) => {
|
||||
const p = props('pull-up', 'emom-total')
|
||||
const source = completed(p, kind === 'minute format' ? 'emom' : 'emom-total')
|
||||
if (kind === 'draft') source.rows[0].completed = false
|
||||
if (kind === 'current') source.date = p.dateKey
|
||||
if (kind === 'future') source.date = '2026-11-11'
|
||||
await storage.writePerformance(source)
|
||||
const lookup = vi.spyOn(storage, 'previousPerformance')
|
||||
render(<PerformanceEditor {...p} />)
|
||||
await settledLookup(lookup)
|
||||
expect(action()).toBeNull()
|
||||
})
|
||||
|
||||
it('checks a saved historical definition instead of reinterpreting it using the current definition', async () => {
|
||||
const p = props('front-plank')
|
||||
await storage.writePerformance(completed(p, 'sets'))
|
||||
const saved = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
|
||||
await storage.writePerformance(saved)
|
||||
render(<PerformanceEditor {...p} definition={{ ...p.definition, equipment: ['bodyweight'], version: 2 }} />)
|
||||
expect(await screen.findByRole('button', { name: 'Use previous session' })).toBeTruthy()
|
||||
expect(screen.getByLabelText('Set 1 vest (kg)').value).toBe('')
|
||||
expect(await storage.readPerformance(p.dateKey, p.period, p.definition.id)).toEqual(saved)
|
||||
})
|
||||
|
||||
it('keeps minute-history availability separate from aggregate history', async () => {
|
||||
const p = props('pull-up', 'emom-total')
|
||||
await storage.writePerformance(completed(p, 'emom-total'))
|
||||
const minute = completed(p, 'emom', p.dateKey)
|
||||
await storage.writePerformance(minute)
|
||||
const lookup = vi.spyOn(storage, 'previousPerformance')
|
||||
render(<DetailedPerformanceEditor historicalOnly {...p} />)
|
||||
await settledLookup(lookup)
|
||||
expect(action()).toBeNull()
|
||||
expect(screen.getByLabelText('Minute 1 reps').value).toBe('0')
|
||||
})
|
||||
|
||||
it('copies completed source rows only, leaving newer partial source values out of suggestions', async () => {
|
||||
const p = props('front-plank')
|
||||
const source = completed(p, 'sets')
|
||||
source.rows.push({ values: { seconds: 99 }, load: { vestKg: null }, completed: false })
|
||||
await storage.writePerformance(source)
|
||||
render(<PerformanceEditor {...p} />)
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Use previous session' }))
|
||||
await screen.findByText(/Suggested from/)
|
||||
expect(screen.getByLabelText('Set 1 seconds').value).toBe('0')
|
||||
expect(screen.queryByLabelText('Set 2 seconds')).toBeNull()
|
||||
expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy()
|
||||
expect(await storage.readPerformance(source.date, p.period, p.definition.id)).toEqual(source)
|
||||
expect(await storage.readPerformance(p.dateKey, p.period, p.definition.id)).toBeNull()
|
||||
})
|
||||
|
||||
it('offers compatible minute history in its original editor without applying aggregate data', async () => {
|
||||
const p = props('pull-up', 'emom-total')
|
||||
await storage.writePerformance(completed(p, 'emom'))
|
||||
await storage.writePerformance(completed(p, 'emom', p.dateKey))
|
||||
render(<DetailedPerformanceEditor historicalOnly {...p} />)
|
||||
expect(await screen.findByRole('button', { name: 'Use previous session' })).toBeTruthy()
|
||||
expect(screen.getByLabelText('Minute 1 reps').value).toBe('0')
|
||||
expect(await storage.readPerformance(p.dateKey, p.period, p.definition.id, 'emom-total')).toBeNull()
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { useLayoutEffect } from 'react'
|
||||
const storage = vi.hoisted(() => ({ read: vi.fn(), lookup: vi.fn(), write: vi.fn() }))
|
||||
vi.mock('./performanceStorage.js', () => ({
|
||||
readPerformance: storage.read, previousPerformance: storage.lookup, writePerformance: storage.write,
|
||||
}))
|
||||
vi.mock('./strengthStorage.js', () => ({ readStrengthEntry: vi.fn(async () => null) }))
|
||||
import DetailedPerformanceEditor from './DetailedPerformanceEditor.jsx'
|
||||
import EmomTotalEditor from './EmomTotalEditor.jsx'
|
||||
import { exerciseDefinitions } from './data/index.js'
|
||||
import { newPerformance } from './performanceModel.js'
|
||||
|
||||
const editors = [
|
||||
['regular', DetailedPerformanceEditor, 'front-plank', 'Set 1 seconds'],
|
||||
['EMOM', EmomTotalEditor, 'pull-up', 'Total reps'],
|
||||
]
|
||||
const definition = (id) => exerciseDefinitions.find((d) => d.id === id)
|
||||
const props = (id) => ({ dateKey: '2026-11-10', period: 'morning', definition: definition(id), prescription: { kind: id === 'pull-up' || id === 'chin-up' ? 'emom' : 'sets', rounds: 10 } })
|
||||
const action = () => screen.queryByRole('button', { name: 'Use previous session' })
|
||||
function deferred() {
|
||||
let resolve
|
||||
let reject
|
||||
const promise = new Promise((yes, no) => { resolve = yes; reject = no })
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
async function flush(job, value, reject = false) {
|
||||
await act(async () => { job[reject ? 'reject' : 'resolve'](value); await job.promise.catch(() => {}) })
|
||||
}
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
storage.read.mockResolvedValue(null)
|
||||
storage.lookup.mockResolvedValue(null)
|
||||
storage.write.mockResolvedValue(undefined)
|
||||
})
|
||||
afterEach(cleanup)
|
||||
|
||||
it.each(editors)('keeps unknown %s availability hidden, without blocking manual entry', async (_, Editor, id, label) => {
|
||||
const job = deferred()
|
||||
storage.lookup.mockReturnValue(job.promise)
|
||||
render(<Editor {...props(id)} />)
|
||||
expect(action()).toBeNull()
|
||||
await waitFor(() => expect(storage.lookup).toHaveBeenCalledTimes(1))
|
||||
expect(screen.getByLabelText(label).disabled).toBe(false)
|
||||
fireEvent.change(screen.getByLabelText(label), { target: { value: '19' } })
|
||||
expect(action()).toBeNull()
|
||||
await flush(job, { date: '2026-11-03' })
|
||||
expect(action()).toBeTruthy()
|
||||
expect(screen.getByLabelText(label).value).toBe('19')
|
||||
expect(storage.write).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(editors)('retries a %s lookup failure without reloading or losing typed values', async (_, Editor, id, label) => {
|
||||
storage.lookup.mockRejectedValueOnce(new Error('Lookup unavailable')).mockResolvedValue({ date: '2026-11-03' })
|
||||
render(<Editor {...props(id)} />)
|
||||
expect((await screen.findByRole('alert')).textContent).toMatch(/Could not check previous sessions.*Lookup unavailable/)
|
||||
expect(action()).toBeNull()
|
||||
fireEvent.change(screen.getByLabelText(label), { target: { value: '23' } })
|
||||
const reads = storage.read.mock.calls.length
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Retry previous-session lookup' }))
|
||||
expect(await screen.findByRole('button', { name: 'Use previous session' })).toBeTruthy()
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
expect(screen.getByLabelText(label).value).toBe('23')
|
||||
expect(storage.read).toHaveBeenCalledTimes(reads)
|
||||
expect(storage.write).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
for (const [name, Editor, id] of editors) {
|
||||
it.each(['date', 'period', 'exercise', 'definition'])(`ignores stale ${name} lookup results after a %s change`, async (dimension) => {
|
||||
const first = deferred()
|
||||
const second = deferred()
|
||||
storage.lookup.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
|
||||
const p = props(id)
|
||||
const view = render(<Editor {...p} />)
|
||||
await waitFor(() => expect(storage.lookup).toHaveBeenCalledTimes(1))
|
||||
const next = { ...p }
|
||||
if (dimension === 'date') next.dateKey = '2026-11-11'
|
||||
if (dimension === 'period') next.period = 'afternoon'
|
||||
if (dimension === 'exercise') next.definition = definition(id === 'pull-up' ? 'chin-up' : 'deep-squat-hold')
|
||||
if (dimension === 'definition') next.definition = { ...p.definition, version: p.definition.version + 1 }
|
||||
view.rerender(<Editor {...next} />)
|
||||
expect(action()).toBeNull()
|
||||
await waitFor(() => expect(storage.lookup).toHaveBeenCalledTimes(2))
|
||||
await flush(second, null)
|
||||
await flush(first, { date: '2026-11-03' })
|
||||
expect(action()).toBeNull()
|
||||
expect(storage.lookup.mock.calls[1]).toEqual([next.dateKey, next.period, next.definition, id === 'pull-up' ? 'emom-total' : 'sets'])
|
||||
})
|
||||
}
|
||||
|
||||
it.each(editors)('never flashes old %s availability while a new saved definition loads', async (_, Editor, id) => {
|
||||
storage.lookup.mockResolvedValue({ date: '2026-11-03' })
|
||||
const observations = []
|
||||
function Probe({ p }) {
|
||||
useLayoutEffect(() => { observations.push(Boolean(action())) })
|
||||
return <Editor {...p} />
|
||||
}
|
||||
const p = props(id)
|
||||
const view = render(<Probe p={p} />)
|
||||
await screen.findByRole('button', { name: 'Use previous session' })
|
||||
const job = deferred()
|
||||
storage.read.mockReturnValue(job.promise)
|
||||
const next = { ...p, definition: { ...p.definition, version: p.definition.version + 1 } }
|
||||
view.rerender(<Probe p={next} />)
|
||||
expect(observations.at(-1)).toBe(false)
|
||||
expect(action()).toBeNull()
|
||||
expect(storage.lookup).toHaveBeenCalledTimes(1)
|
||||
await flush(job, null)
|
||||
await screen.findByRole('button', { name: 'Use previous session' })
|
||||
expect(storage.lookup.mock.calls.at(-1)[2]).toEqual(next.definition)
|
||||
})
|
||||
|
||||
it('rechecks a loaded historical format when the date changes, without mixing minutes and totals', async () => {
|
||||
const p = props('pull-up')
|
||||
storage.read.mockResolvedValueOnce(newPerformance(p.dateKey, p.period, p.definition, p.prescription, 'emom'))
|
||||
const view = render(<DetailedPerformanceEditor {...p} />)
|
||||
await waitFor(() => expect(storage.lookup).toHaveBeenCalledTimes(1))
|
||||
expect(storage.lookup.mock.calls.at(-1)[3]).toBe('emom')
|
||||
const nextDate = '2026-11-11'
|
||||
storage.read.mockResolvedValueOnce(newPerformance(nextDate, p.period, p.definition, p.prescription, 'sets'))
|
||||
view.rerender(<DetailedPerformanceEditor {...p} dateKey={nextDate} />)
|
||||
await waitFor(() => expect(storage.lookup).toHaveBeenCalledTimes(2))
|
||||
expect(storage.lookup.mock.calls.at(-1)[3]).toBe('sets')
|
||||
expect(action()).toBeNull()
|
||||
})
|
||||
@@ -52,7 +52,7 @@ it('records a hold through one seconds input and suggests both sides as an unsav
|
||||
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/)
|
||||
fireEvent.click(await screen.findByRole('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')
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { previousPerformance } from './performanceStorage.js'
|
||||
|
||||
// Key both the loaded saved definition and its owning editor context. Never
|
||||
// expose the previous context's result while the next read/effect is pending.
|
||||
export default function usePreviousAvailability({ dateKey, period, record, contextKey, enabled }) {
|
||||
const key = JSON.stringify([contextKey, dateKey, period, record?.definition, record?.format])
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
const [result, setResult] = useState(null)
|
||||
useEffect(() => {
|
||||
setResult(null)
|
||||
if (!enabled) return
|
||||
let active = true
|
||||
const [, date, sessionPeriod, definition, format] = JSON.parse(key)
|
||||
previousPerformance(date, sessionPeriod, definition, format)
|
||||
.then((previous) => {
|
||||
if (active) setResult({ key, attempt, available: Boolean(previous), error: '' })
|
||||
})
|
||||
.catch((failure) => {
|
||||
if (active) setResult({ key, attempt, available: false, error: failure.message || 'Previous-session lookup failed.' })
|
||||
})
|
||||
return () => { active = false }
|
||||
}, [key, enabled, attempt])
|
||||
const current = enabled && result?.key === key && result.attempt === attempt ? result : null
|
||||
return {
|
||||
available: current?.available ?? false,
|
||||
error: current?.error ?? '',
|
||||
retry: () => setAttempt((value) => value + 1),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user