Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

feat: add focus workout view

giulioleuci7b0b450f4c14
diff --git a/.gitignore b/.gitignore
index 41d88171b..407050cf6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,8 +16,12 @@ node_modules/
node_modules
.claude/
.agents/
+.superpowers/
# CI reports (test:* jobs write these next to the suites)
junit.xml
coverage/
frontend/bundle-size.json
+
+# Local planning notes
+docs/superpowers/plans/
diff --git a/docs/dev/LIST_VIEW.md b/docs/dev/LIST_VIEW.md
index e98182193..add1792a3 100644
--- a/docs/dev/LIST_VIEW.md
+++ b/docs/dev/LIST_VIEW.md
@@ -1,16 +1,20 @@
-# Workout view — cards / list / compact
+# Workout view — cards / list / compact / focus
-The active workout screen (`frontend/src/views/Workout.jsx`) has three layouts, chosen by
-`S.workoutView` (`'cards' | 'list' | 'compact'`, default `'cards'`). It is purely
-presentational — the same `s.active` session, entries and finish path in every layout, and
-every set handler is already entry-index parameterised, so the layouts only change what is
-rendered.
+The active workout screen (`frontend/src/views/Workout.jsx`) has four layouts, chosen by
+`S.workoutView` (`'cards' | 'list' | 'compact' | 'focus'`, default `'cards'`). All four use the
+same active session and completion pipeline.
| Value | What you see |
|---|---|
| `cards` | One unit at a time, `Prev` / `Next` + swipe. The original flow. |
| `list` | Every unit stacked and scrollable. Each non-current unit has a **Set current** chip in its header; completion still auto-advances the current marker, starts rest and can open the top-weight sheet. Blocks render with the `compact` `ExerciseBlock` prop (smaller). |
| `compact` | `list`, with each `ExerciseBlock` also rendered `dense`: no media, no tag chips (Cardio / per-side / target / equipment / **Best:**), no note lines, no "Last time …" recap, no bar-and-plates chip, no progression-guidance line, no "Make superset with previous/next". Just the name, the ⋯ menu and the set rows. |
+| `focus` | One set at a time with large load/reps controls, nullable RPE, Complete/Skip actions, and a set pager. Supersets show one member at a time in round order. Existing Prev/Next and horizontal swipe still move between exercise units. |
+
+Focus keeps its visible-set pointer in component state only. It starts at the first incomplete
+set, falls back to the final set when the exercise is complete, and is not persisted. Completing
+a set still routes through `ActiveWorkout.toggle`, so sound, haptics, rest, timed work,
+high-water protection, and superset progression remain shared with every other layout.
Everything `compact` hides is still on the ⋯ menu (note, details, history, bar weight,
progression settings) or is display-only.
@@ -18,7 +22,7 @@ progression settings) or is display-only.
Unknown / absent values read as `cards`, so a profile written before the setting existed is
unchanged.
-Orthogonal to all three: **Settings → During a workout → Workout controls** (`S.wc`) decides
+Orthogonal to all four: **Settings → During a workout → Workout controls** (`S.wc`) decides
whether Move / Swap / Remove, the pair buttons, the drop/burst shortcuts and the `+/-`
steppers show inline. The lean default keeps them in each exercise's ⋯ menu; turning
`exerciseButtons` on adds a footer Move / Swap / Remove row that acts on the current unit
@@ -26,8 +30,8 @@ steppers show inline. The lean default keeps them in each exercise's ⋯ menu; t
## Where it is set
-- **Saved default:** Settings → During a workout → **Workout view** (a 3-way `Segmented`).
-- **Per session:** the workout header's **⋮** button opens a `menuSheet` with the three
+- **Saved default:** Settings → During a workout → **Workout view** (a 4-way `Segmented`).
+- **Per session:** the workout header's **⋮** button opens a `menuSheet` with the four
layouts; picking one writes `s.active.workoutView`.
`beginWorkout` / `beginBackfill` (`frontend/src/sheets.jsx`) snapshot `S.workoutView` onto
@@ -39,7 +43,9 @@ changing the saved default never disturbs a workout already in progress.
Component-level, no new `lib/` helper:
+- `frontend/src/views/FocusView.jsx` and `frontend/src/views/FocusView.css` — Focus layout.
- `frontend/src/views/Workout.test.jsx` — `workout list view`, `workout compact view`,
- `workout view header menu` describe blocks.
-- `frontend/src/views/Settings.workoutview.test.jsx` — the 3-way Segmented.
-- `frontend/src/sheets.workoutview.test.jsx` — `beginWorkout` / backfill snapshot behaviour.
+ `workout focus view`, and `workout view header menu` describe blocks.
+- `frontend/src/views/Settings.workoutview.test.jsx` — the 4-way Segmented and Focus cases.
+- `frontend/src/sheets.workoutview.test.jsx` — `beginWorkout` / backfill snapshot behaviour and
+ Focus cases.
diff --git a/frontend/src/components/ui.jsx b/frontend/src/components/ui.jsx
index 5e179747a..716a2f948 100644
--- a/frontend/src/components/ui.jsx
+++ b/frontend/src/components/ui.jsx
@@ -141,7 +141,7 @@ export function Segmented({ options, value, onChange, className = '' }) {
// `min` and `max` hold for the buttons at once, but for typing only once the field is left:
// clamped on every keystroke, a field emptied to type a new number snapped to the minimum, and
// the digits typed next landed after it (a 48 retyped as 75 saved 175).
-export function Stepper({ value, step = 1, min = 0, max = Infinity, onChange, decimal = true, className = '', label, unit, invalid = false }) {
+export function Stepper({ value, step = 1, min = 0, max = Infinity, onChange, decimal = true, className = '', label, unit, invalid = false, disabled = false, onStep, ariaLabel }) {
const clamp = v => Math.min(max, Math.max(min, v))
const set = v => onChange(clamp(Math.round((v || 0) * 100) / 100))
// Holding a button repeats the step; the latest value/step live in a ref so
@@ -149,7 +149,7 @@ export function Stepper({ value, step = 1, min = 0, max = Infinity, onChange, de
const live = useRef({ value, step, set })
live.current = { value, step, set }
const hold = useRef({ delay: null, tick: null, count: 0, repeated: false })
- const bump = dir => { const { value, step, set } = live.current; set((+value || 0) + dir * step) }
+ const bump = dir => { const { value, step, set } = live.current; set(onStep ? onStep(value, step, dir) : (+value || 0) + dir * step) }
const stopHold = () => {
const h = hold.current
window.clearTimeout(h.delay); window.clearInterval(h.tick)
@@ -182,12 +182,12 @@ export function Stepper({ value, step = 1, min = 0, max = Infinity, onChange, de
})
const inner = (
<div className={'stp ' + className}>
- <button {...holdProps(-1)} aria-label={t('Decrease')}><Icon name="minus" /></button>
+ <button {...holdProps(-1)} aria-label={ariaLabel ? `Decrease ${ariaLabel}` : t('Decrease')} disabled={disabled}><Icon name="minus" /></button>
<span className="val" onBlur={() => { const v = +value || 0; if (clamp(v) !== v) onChange(clamp(v)) }}>
- <NumberField value={value} decimal={decimal} onChange={onChange} aria-invalid={invalid ? 'true' : undefined} />
+ <NumberField value={value} decimal={decimal} onChange={onChange} disabled={disabled} aria-invalid={invalid ? 'true' : undefined} />
{unit && <i>{unit}</i>}
</span>
- <button {...holdProps(1)} aria-label={t('Increase')}><Icon name="plus" /></button>
+ <button {...holdProps(1)} aria-label={ariaLabel ? `Increase ${ariaLabel}` : t('Increase')} disabled={disabled}><Icon name="plus" /></button>
</div>
)
if (!label) return inner
@@ -200,7 +200,7 @@ export function Stepper({ value, step = 1, min = 0, max = Infinity, onChange, de
// pseudo-elements, which is the only way the control looks identical on every
// platform and can pick up the accent colour.
export const SLIDER_GRAB_PX = 22
-export function Slider({ value, min = 0, max = 100, step = 1, onChange, className = '' }) {
+export function Slider({ value, min = 0, max = 100, step = 1, onChange, className = '', disabled = false }) {
const ref = useRef(null)
const [drag, setDrag] = useState(false)
// Grabbing the knob drags it relative to where the finger landed; a finger
@@ -240,6 +240,7 @@ export function Slider({ value, min = 0, max = 100, step = 1, onChange, classNam
}, [drag, onChange, posToValue])
const key = e => {
+ if (disabled) return
// The arrow pointing at the inline-end (max) end still increases; in RTL that is Left.
const inc = document.documentElement.dir === 'rtl' ? 'ArrowLeft' : 'ArrowRight'
const dec = document.documentElement.dir === 'rtl' ? 'ArrowRight' : 'ArrowLeft'
@@ -255,11 +256,13 @@ export function Slider({ value, min = 0, max = 100, step = 1, onChange, classNam
ref={ref}
className={'sld' + (drag ? ' dragging' : '') + ' ' + className}
role="slider"
- tabIndex={0}
+ tabIndex={disabled ? -1 : 0}
aria-valuenow={value} aria-valuemin={min} aria-valuemax={max}
+ aria-disabled={disabled}
data-nodrag /* keeps the sheet from swipe-dismissing */
onKeyDown={key}
onPointerDown={e => {
+ if (disabled) return
e.currentTarget.setPointerCapture?.(e.pointerId)
const r = e.currentTarget.getBoundingClientRect()
// The knob is measured from inline-start: left in LTR, right in RTL.
diff --git a/frontend/src/components/ui.test.jsx b/frontend/src/components/ui.test.jsx
index 2dc5576d2..6b6328ece 100644
--- a/frontend/src/components/ui.test.jsx
+++ b/frontend/src/components/ui.test.jsx
@@ -114,9 +114,9 @@ describe('Slider under dir=rtl', () => {
describe('Stepper', () => {
// controlled like every real caller: the parent re-renders with the new value
- function Host({ initial, onChange, step }) {
+ function Host({ initial, onChange, step, ...props }) {
const [v, setV] = React.useState(initial)
- return <Stepper value={v} step={step} onChange={n => { setV(n); onChange(n) }} />
+ return <Stepper value={v} step={step} onChange={n => { setV(n); onChange(n) }} {...props} />
}
const mountStepper = (value, onChange, step = 1) => {
act(() => root.render(<Host initial={value} step={step} onChange={onChange} />))
@@ -186,6 +186,32 @@ describe('Stepper', () => {
act(() => plus.click())
expect(onChange).toHaveBeenCalledWith(11)
})
+
+ it('names controls for their field when requested', () => {
+ const onChange = vi.fn()
+ act(() => root.render(<Host initial={10} step={1} onChange={onChange} ariaLabel="load" />))
+ expect(host.querySelector('button[aria-label="Decrease load"]')).toBeTruthy()
+ expect(host.querySelector('button[aria-label="Increase load"]')).toBeTruthy()
+ })
+
+ it('uses the caller step rule', () => {
+ const onChange = vi.fn()
+ act(() => root.render(<Host initial={61.3} step={2.5} onChange={onChange}
+ onStep={(value, increment, direction) => value + increment * 10 + direction} />))
+ act(() => host.querySelector('button[aria-label="Increase"]').click())
+ expect(onChange).toHaveBeenCalledWith(87.3)
+ })
+
+ it('disables all editing controls', () => {
+ const onChange = vi.fn()
+ act(() => root.render(<Host initial={61.3} step={2.5} onChange={onChange} disabled />))
+ const [minus, plus] = host.querySelectorAll('button')
+ expect(minus.disabled).toBe(true)
+ expect(plus.disabled).toBe(true)
+ expect(host.querySelector('input').disabled).toBe(true)
+ act(() => plus.click())
+ expect(onChange).not.toHaveBeenCalled()
+ })
})
describe('NumberField fit', () => {
diff --git a/frontend/src/lib/notes-render.test.jsx b/frontend/src/lib/notes-render.test.jsx
index e685b625b..f36df15de 100644
--- a/frontend/src/lib/notes-render.test.jsx
+++ b/frontend/src/lib/notes-render.test.jsx
@@ -7,7 +7,7 @@ import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
-import { exerciseNoteSheet } from '../sheets.jsx'
+import { exerciseNoteSheet, setNoteSheet } from '../sheets.jsx'
const activeWith = entry => ({ id: 'w1', d: '2026-08-25', start: 1, routineId: 'r1', name: 'Push', entries: [entry] })
@@ -25,6 +25,16 @@ function renderSheet() {
act(() => root.render(sheet.render(sheet_close(sheet))))
return host
}
+function renderSetNoteSheet(entryIdx = 0, setIdx = 0) {
+ setNoteSheet(entryIdx, setIdx)
+ const sheet = useUI.getState().sheets.at(-1)
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push(root)
+ act(() => root.render(sheet.render(sheet_close(sheet))))
+ return host
+}
const sheet_close = sheet => () => useUI.getState().closeSheet(sheet.id)
const type = (el, value) => {
@@ -86,4 +96,20 @@ describe('exercise note sheet', () => {
expect(e.note).toBeUndefined()
expect(e.notePin).toBeUndefined()
})
+
+ it('saves and clears a note on one set', () => {
+ useStore.setState(s => ({
+ S: { ...s.S, active: activeWith({ id: 'bench', sets: [{ w: 60, r: 5, done: false }] }) },
+ }))
+
+ let host = renderSetNoteSheet()
+ act(() => { type(host.querySelector('textarea'), 'Paused at the bottom') })
+ act(() => { [...host.querySelectorAll('button')].find(b => b.textContent === 'Save').click() })
+ expect(useStore.getState().S.active.entries[0].sets[0].note).toBe('Paused at the bottom')
+
+ host = renderSetNoteSheet()
+ act(() => { type(host.querySelector('textarea'), '') })
+ act(() => { [...host.querySelectorAll('button')].find(b => b.textContent === 'Save').click() })
+ expect(useStore.getState().S.active.entries[0].sets[0].note).toBeUndefined()
+ })
})
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index e5e4a6928..808104eb5 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -2642,6 +2642,40 @@ function ExerciseNote({ entryIdx, close }) {
}
export const exerciseNoteSheet = entryIdx => ui().openSheet(close => <ExerciseNote entryIdx={entryIdx} close={close} />)
+function SetNote({ entryIdx, setIdx, close }) {
+ const noteRef = useRef(null)
+ const onNoteFocus = useSheetKeyboard(noteRef)
+ const row = useStore(s => s.S.active?.entries?.[entryIdx]?.sets?.[setIdx])
+ const update = useStore(s => s.update)
+ const [note, setNote] = useState(row?.note || '')
+
+ useEffect(() => { if (!row) close() }, [!row])
+ if (!row) return null
+
+ const save = () => {
+ const text = note.trim().slice(0, NOTE_MAX)
+ update(s => {
+ const set = s.active?.entries?.[entryIdx]?.sets?.[setIdx]
+ if (!set) return
+ if (text) set.note = text
+ else delete set.note
+ }, true)
+ close()
+ }
+
+ return <>
+ <h3>{t('Set note')}</h3>
+ <textarea ref={noteRef} className="input" rows={4} maxLength={NOTE_MAX} value={note}
+ placeholder={t('Anything specific to remember about this set.')}
+ onFocus={onNoteFocus} onChange={event => setNote(event.target.value)} />
+ <div style={{ height: 18 }} />
+ <Button variant="primary" onClick={save}>{t('Save')}</Button>
+ </>
+}
+
+export const setNoteSheet = (entryIdx, setIdx) =>
+ ui().openSheet(close => <SetNote entryIdx={entryIdx} setIdx={setIdx} close={close} />)
+
/* The session note: how the whole workout went, as opposed to how one exercise went. It lives
on the active session, so buildCompletedWorkout carries it onto the finished workout and it
shows up again in history — where it stays editable. Written here rather than only after the
diff --git a/frontend/src/sheets.workoutview.test.jsx b/frontend/src/sheets.workoutview.test.jsx
index ceec22883..214d12d87 100644
--- a/frontend/src/sheets.workoutview.test.jsx
+++ b/frontend/src/sheets.workoutview.test.jsx
@@ -36,9 +36,9 @@ describe('workout view is snapshot onto the active session', () => {
afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
it('beginWorkout copies the current default onto s.active', () => {
- useStore.setState(s => ({ S: { ...s.S, workoutView: 'compact' } }))
+ useStore.setState(s => ({ S: { ...s.S, workoutView: 'focus' } }))
act(() => beginWorkout(null, null))
- expect(useStore.getState().S.active.workoutView).toBe('compact')
+ expect(useStore.getState().S.active.workoutView).toBe('focus')
})
it('beginWorkout falls back to cards when the default is unset', () => {
@@ -55,11 +55,11 @@ describe('workout view is snapshot onto the active session', () => {
})
it('a backfilled session snapshots it too', () => {
- useStore.setState(s => ({ S: { ...s.S, workoutView: 'list' } }))
+ useStore.setState(s => ({ S: { ...s.S, workoutView: 'focus' } }))
logPastWorkoutSheet()
const host = mountTopSheet()
act(() => { type(host.querySelector('input[type=date]'), '2020-01-02') })
act(() => { button(host, 'Continue').click() })
- expect(useStore.getState().S.active.workoutView).toBe('list')
+ expect(useStore.getState().S.active.workoutView).toBe('focus')
})
})
diff --git a/frontend/src/views/FocusView.css b/frontend/src/views/FocusView.css
new file mode 100644
index 000000000..1cc729daa
--- /dev/null
+++ b/frontend/src/views/FocusView.css
@@ -0,0 +1,55 @@
+.focus-view{display:grid;gap:12px}
+.focus-superset-inline{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-bottom:12px;padding-bottom:12px;border-bottom:var(--hair) solid var(--sep);color:var(--acc);font-size:13px}
+.focus-superset-inline strong{font-weight:600}
+.focus-superset-inline span{color:var(--label-2)}
+.focus-superset-inline .icn{font-size:14px}
+.focus-superset-inline .btn{min-height:32px;padding-inline:8px;color:var(--acc)}
+.focus-superset-nav{display:flex;margin-left:auto}
+.focus-superset-nav button{display:grid;place-items:center;width:44px;height:44px;color:var(--label-2)}
+.focus-superset-nav button:disabled{opacity:.3}
+.focus-card{padding:16px;border-radius:var(--r-lg);background:var(--surface);box-shadow:inset 0 0 0 1.5px var(--acc-line)}
+.focus-card-header{display:flex;align-items:center;gap:6px;padding-bottom:12px;border-bottom:var(--hair) solid var(--sep)}
+.focus-card-header h2{flex:1;font-size:20px;line-height:1.2;text-transform:capitalize}
+.focus-warmup{font-size:16px}
+.focus-context{display:grid;gap:5px;margin-top:10px}
+.focus-tags{display:flex;flex-wrap:wrap;gap:5px}
+.focus-note,.focus-last,.focus-guidance{color:var(--label-2);font-size:12px;line-height:1.35}
+.focus-note{padding-left:8px;border-left:var(--hair) solid var(--sep)}
+.focus-note.pinned{color:var(--yellow);display:flex;gap:5px;align-items:flex-start}
+.focus-note .icn{margin-top:1px;flex:none}
+.focus-guidance{display:flex;align-items:center;gap:5px;width:max-content;text-align:left;color:var(--acc);font-weight:600}
+.focus-guidance .icn{font-size:13px}
+.focus-prescription{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin:14px 0}
+.focus-progress{border-radius:99px;white-space:nowrap}
+.focus-progress{padding:6px 12px;background:var(--acc);color:var(--on-acc);font-weight:600}
+.focus-set>.stp-w,.focus-side>.stp-w{margin-top:12px}
+.focus-set.complete .stp .num:disabled,.focus-set.locked .stp .num:disabled,.focus-set.complete .focus-timed strong,.focus-set.locked .focus-timed strong{color:color-mix(in srgb,var(--label) 48%,var(--surface))!important;-webkit-text-fill-color:color-mix(in srgb,var(--label) 48%,var(--surface))!important;opacity:1}
+.focus-lock-note{margin:-4px 2px 2px;color:var(--label-2);font-size:12px;line-height:1.35}
+.focus-effort{width:100%;margin-top:16px}
+.focus-card>.btn.primary{margin-top:18px;min-height:48px}
+.focus-secondary{display:grid;grid-template-columns:1fr 44px;gap:8px;margin-top:8px}
+.focus-secondary>.iconbtn{width:44px;height:44px;border:1px solid var(--sep);border-radius:8px}
+.focus-skip{display:flex;align-items:center;justify-content:center;gap:6px;min-height:44px;border:1px solid var(--sep);border-radius:8px;color:var(--label)}
+.focus-pager{display:grid;grid-template-columns:44px 1fr 44px;align-items:center;gap:8px}
+.focus-pager>button{display:grid;place-items:center;width:44px;height:44px;border:1px solid var(--sep);border-radius:50%;color:var(--label)}
+.focus-pager>button:disabled{opacity:.3}
+.focus-dots{display:flex;align-items:center;justify-content:center;gap:4px}
+.focus-dots button{position:relative;width:44px;height:44px}
+.focus-dots button::after{content:'';position:absolute;left:50%;top:50%;width:6px;height:6px;border-radius:50%;background:var(--label-3);transform:translate(-50%,-50%)}
+.focus-dots button.active::after{width:9px;height:9px;background:var(--acc)}
+.focus-dots button.done::after{box-shadow:0 0 0 2px var(--acc-line)}
+.focus-sides{display:grid;grid-template-columns:1fr 1fr;gap:10px}
+.focus-side{min-width:0;padding:10px;border-radius:var(--r);background:var(--surface-2)}
+.focus-side-header{display:flex;align-items:center;justify-content:space-between}
+.focus-side-check{display:grid;place-items:center;width:44px;height:44px;border-radius:50%;color:var(--label-3)}
+.focus-side-check.done{background:var(--acc);color:var(--on-acc)}
+.focus-timed{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:12px;padding:12px;border-radius:var(--r);background:var(--surface-2)}
+.focus-timed .btn{width:auto;min-width:120px}
+.focus-extras{display:grid;gap:8px;margin-top:12px}
+.focus-extra{display:grid;grid-template-columns:minmax(56px,auto) 1fr 1fr;align-items:end;gap:8px;padding:8px;border-radius:var(--r-sm);background:var(--surface-2)}
+.focus-extra .stp-l{font-size:11px}
+@media (max-width:400px){
+ .focus-sides{grid-template-columns:1fr}
+ .focus-extra{grid-template-columns:1fr 1fr}
+ .focus-extra>span:first-child{grid-column:1/-1}
+}
diff --git a/frontend/src/views/FocusView.jsx b/frontend/src/views/FocusView.jsx
new file mode 100644
index 000000000..4a141ef03
--- /dev/null
+++ b/frontend/src/views/FocusView.jsx
@@ -0,0 +1,303 @@
+import { useState } from 'react'
+import { useStore } from '../store/useStore.js'
+import { exOr } from '../lib/exercises.js'
+import { exerciseNameFor, t } from '../lib/i18n.js'
+import { fmtDate, fmtNum } from '../lib/format.js'
+import { EFFORT, effortOf, modeOf } from '../lib/history.js'
+import { lastEntryFor, pinnedNoteFor } from '../lib/history.js'
+import { effortColor, rirOf } from '../lib/effort.js'
+import { progressionGuidance } from '../lib/progression-copy.js'
+import {
+ addCluster, addDrop, addSideCluster, addSideDrop, clustersOf, dropsOf,
+ isSideSet, isWarmupRow, nextBurstReps, nextDropWeight, setClusterAt,
+ setDropAt, setSideClusterAt, setSideDropAt, setSideField,
+} from '../lib/workout-model.js'
+import { weightIncrement, stepWeight } from '../lib/progression.js'
+import { effortPickerSheet, exerciseDetailSheet, exerciseHistorySheet, exerciseNoteSheet, menuSheet } from '../sheets.jsx'
+import Icon from '../components/Icon.jsx'
+import { Button, Stepper } from '../components/ui.jsx'
+import './FocusView.css'
+
+const firstIncomplete = entry => {
+ const index = entry.sets.findIndex(set => !set.done)
+ return index < 0 ? Math.max(0, entry.sets.length - 1) : index
+}
+
+const clampSet = (entry, index) => Math.min(Math.max(index, 0), Math.max(0, entry.sets.length - 1))
+
+const supersetSequence = (entries, unit) => {
+ const rounds = Math.max(0, ...unit.map(index => entries[index]?.sets?.length || 0))
+ return Array.from({ length: rounds }, (_, setIdx) =>
+ unit.filter(entryIdx => entries[entryIdx]?.sets?.[setIdx]).map(entryIdx => ({ entryIdx, setIdx })),
+ ).flat()
+}
+
+const toggleWarmup = row => {
+ const next = { ...row }
+ if (isWarmupRow(next)) {
+ delete next.phase
+ delete next.warmup
+ } else next.phase = 'warmup'
+ return next
+}
+
+const addDropTo = (row, target) => {
+ if (isSideSet(row)) return addSideDrop(row, target?.intensifier?.pct)
+ const drops = dropsOf(row).length ? dropsOf(row) : row.drops || []
+ const base = drops.at(-1)?.w ?? row.w ?? 0
+ return addDrop(row, { w: nextDropWeight(base, target?.intensifier?.pct), r: row.r || 0 })
+}
+
+const addBurstTo = (row, restSec) => {
+ if (isSideSet(row)) return addSideCluster(row, restSec)
+ const clusters = clustersOf(row).length ? clustersOf(row) : row.clusters || []
+ const reps = nextBurstReps(clusters.at(-1)?.r ?? row.r ?? 0)
+ return { ...addCluster(row, { r: reps, restSec }), r: (row.r || 0) + reps }
+}
+
+function Prescription({ entry, setIdx, unit, fallbackRest }) {
+ const target = entry.target || {}
+ const reps = target.repsMin > 0 ? `${target.repsMin}–${target.reps}` : target.reps > 0 ? String(target.reps) : ''
+ const load = target.weight > 0
+ ? `@ ${fmtNum(target.weight)}${target.weightMax > target.weight ? `–${fmtNum(target.weightMax)}` : ''} ${unit}`
+ : ''
+ const rpe = target.rpeMin > 0
+ ? `RPE ${fmtNum(target.rpeMin)}${target.rpeMax > target.rpeMin ? `–${fmtNum(target.rpeMax)}` : ''}`
+ : ''
+ const rest = target.restSec > 0 ? `Rest ${target.restSec}s` : fallbackRest > 0 ? `Rest ${fallbackRest}s` : ''
+ const badges = [reps && `${reps} Reps`, load, rpe, rest, target.tempo].filter(Boolean)
+
+ return <div className="focus-prescription">
+ <span className="focus-progress">{setIdx + 1}/{entry.sets.length}</span>
+ {badges.map(label => <span className="tag nocap" key={label}>{label}</span>)}
+ </div>
+}
+
+export default function FocusView({
+ entryIdx, unit, onToggle, onToggleSide, onField, onMutateSet, onStartTimed,
+ onAddWarmup, onRemoveSetAt, onProgressionSettings, onSwap, onRemoveExercise,
+ busy, onSelectEntry, onAdvanceUnit, onPairPrev, onPairNext, onUnpair, pointerEpoch,
+}) {
+ const S = useStore(state => state.S)
+ const entry = S.active.entries[entryIdx]
+ const ex = exOr(entry.id)
+ const last = lastEntryFor(S, entry.id)
+ const pinnedNote = pinnedNoteFor(S, entry.id)
+ const guidance = progressionGuidance(entry.plan)
+ // Exercise operations use indexes, so their local-only epoch discards stale pointers instead
+ // of letting a moved, removed, or newly inserted entry inherit one.
+ const [pointerState, setPointerState] = useState(() => ({ epoch: pointerEpoch, pointers: new Map() }))
+ const pointers = pointerState.epoch === pointerEpoch ? pointerState.pointers : new Map()
+ const stored = pointers.get(entryIdx)
+ const setIdx = clampSet(entry, Number.isInteger(stored) ? stored : firstIncomplete(entry))
+ const set = entry.sets[setIdx]
+ const firstOpenSet = firstIncomplete(entry)
+ const locked = !set.done && setIdx > firstOpenSet
+ const readOnly = set.done || locked
+ const mode = modeOf({ ...(entry.target || {}), id: entry.id })
+ const effort = effortOf(S)
+ const effortField = EFFORT[effort]?.f
+ const effortValue = effortField ? set[effortField] ?? null : null
+ const effortTint = effortValue == null ? null : effortColor(rirOf({ [effortField]: effortValue }))
+ const loadStep = weightIncrement({ ...(entry.target || {}), id: entry.id }, S.unit)
+ const selectSet = index => setPointerState(current => {
+ const next = new Map(current.epoch === pointerEpoch ? current.pointers : [])
+ next.set(entryIdx, clampSet(entry, index))
+ return { epoch: pointerEpoch, pointers: next }
+ })
+ const sequence = unit.length > 1 ? supersetSequence(S.active.entries, unit) : []
+ const sequenceIdx = sequence.findIndex(item => item.entryIdx === entryIdx && item.setIdx === setIdx)
+ const clearPointer = index => setPointerState(current => {
+ if (current.epoch !== pointerEpoch) return { epoch: pointerEpoch, pointers: new Map() }
+ if (!current.pointers.has(index)) return current
+ const next = new Map(current.pointers)
+ next.delete(index)
+ return { epoch: pointerEpoch, pointers: next }
+ })
+ const selectSequence = index => {
+ const item = sequence[index]
+ if (!item) return
+ setPointerState(current => {
+ const next = new Map(current.epoch === pointerEpoch ? current.pointers : [])
+ next.set(item.entryIdx, item.setIdx)
+ return { epoch: pointerEpoch, pointers: next }
+ })
+ onSelectEntry(item.entryIdx)
+ }
+ const drops = dropsOf(set).length ? dropsOf(set) : Array.isArray(set.drops) ? set.drops : []
+ const bursts = clustersOf(set).length ? clustersOf(set) : Array.isArray(set.clusters) ? set.clusters : []
+
+ const sideFields = side => {
+ const sideSet = set.sides[side]
+ const change = (field, value) => onMutateSet(setIdx, row => setSideField(row, side, field, value))
+ const sideDrops = dropsOf(sideSet).length ? dropsOf(sideSet) : Array.isArray(sideSet.drops) ? sideSet.drops : []
+ const sideBursts = clustersOf(sideSet).length ? clustersOf(sideSet) : Array.isArray(sideSet.clusters) ? sideSet.clusters : []
+ return <section className="focus-side" data-focus-side={side}>
+ <div className="focus-side-header">
+ <strong>{side === 'L' ? t('Left') : t('Right')}</strong>
+ <button aria-label={side === 'L' ? t('Complete left side') : t('Complete right side')}
+ className={'focus-side-check' + (sideSet.done ? ' done' : '')}
+ onClick={() => onToggleSide(setIdx, side,
+ !sideSet.done && (set.sides.L.done || set.sides.R.done) ? onProgress : undefined)}><Icon name="check" /></button>
+ </div>
+ <Stepper label={t('Load ({0})', S.unit)} ariaLabel="load" value={sideSet.w || 0} step={loadStep} onStep={stepWeight} disabled={readOnly || sideSet.done}
+ onChange={value => change('w', value)} />
+ <Stepper label={t('Reps')} ariaLabel="reps" value={sideSet.r || 0} step={1} decimal={false} disabled={readOnly || sideSet.done}
+ onChange={value => change('r', value)} />
+ <div className="focus-extras">
+ {sideDrops.map((drop, index) => <div className="focus-extra" key={`drop-${index}`}>
+ <span>{t('Drop {0}', index + 1)}</span>
+ <Stepper label={t('Load')} ariaLabel="load" value={drop.w || 0} step={loadStep} onStep={stepWeight} disabled={readOnly || sideSet.done}
+ onChange={value => onMutateSet(setIdx, row => setSideDropAt(row, side, index, { w: value }))} />
+ <Stepper label={t('Reps')} ariaLabel="reps" value={drop.r || 0} step={1} decimal={false} disabled={readOnly || sideSet.done}
+ onChange={value => onMutateSet(setIdx, row => setSideDropAt(row, side, index, { r: value }))} />
+ </div>)}
+ {sideBursts.map((burst, index) => <div className="focus-extra" key={`burst-${index}`}>
+ <span>{t('Burst {0}', index + 1)}</span>
+ <Stepper label={t('Reps')} ariaLabel="reps" value={burst.r || 0} step={1} decimal={false} disabled={readOnly || sideSet.done}
+ onChange={value => onMutateSet(setIdx, row => setSideClusterAt(row, side, index, value))} />
+ <span className="dim small">{burst.restSec}s</span>
+ </div>)}
+ </div>
+ </section>
+ }
+
+ const onProgress = ({ unitDone }) => {
+ const active = useStore.getState().S.active
+ if (!active) return
+ if (unitDone) {
+ onAdvanceUnit()
+ const nextEntryIdx = useStore.getState().S.active?.cur
+ if (nextEntryIdx !== entryIdx) clearPointer(nextEntryIdx)
+ }
+ else if (unit.length === 1) selectSet(setIdx + 1)
+ else clearPointer(active.cur)
+ }
+
+ const complete = () => {
+ if (!isSideSet(set)) return onToggle(setIdx, onProgress)
+ const sides = set.done ? ['L', 'R'] : ['L', 'R'].filter(side => !set.sides[side].done)
+ sides.forEach((side, index) => onToggleSide(setIdx, side, index === sides.length - 1 ? onProgress : undefined))
+ }
+
+ const openEffort = () => effortPickerSheet(effort, effortValue, value => onField(setIdx, effortField, value))
+
+ const openExerciseMenu = () => menuSheet({
+ title: exerciseNameFor(exOr(entry.id)),
+ items: [
+ { icon: 'pencil', label: entry.note ? t('Edit note') : t('Add note'), onClick: () => exerciseNoteSheet(entryIdx) },
+ { icon: 'info', label: t('Details'), onClick: () => exerciseDetailSheet(exOr(entry.id)) },
+ { icon: 'history', label: t('History'), onClick: () => exerciseHistorySheet(entry.id) },
+ { icon: 'chartLine', label: t('Progression settings'), onClick: onProgressionSettings },
+ onPairPrev && { icon: 'link', label: t('Make superset with previous'), onClick: onPairPrev },
+ onPairNext && { icon: 'link', label: t('Make superset with next'), onClick: onPairNext },
+ { icon: 'shuffle', label: t('Swap exercise'), onClick: onSwap, disabled: busy },
+ { icon: 'trash', label: t('Remove exercise'), onClick: onRemoveExercise, danger: true, disabled: busy },
+ ],
+ })
+
+ const openSetMenu = () => menuSheet({
+ title: t('Set {0}', setIdx + 1),
+ items: [
+ { icon: 'flame', label: isWarmupRow(set) ? t('Mark as work set') : t('Mark as warm-up'), onClick: () => onMutateSet(setIdx, toggleWarmup) },
+ { icon: 'arrowDown', label: t('Add drop set'), onClick: () => onMutateSet(setIdx, row => addDropTo(row, entry.target)) },
+ { icon: 'bolt', label: t('Add burst'), onClick: () => onMutateSet(setIdx, row => addBurstTo(row, S.restPauseSec || 15)) },
+ { icon: 'trash', label: t('Delete set'), danger: true, disabled: entry.sets.length <= 1, onClick: () => onRemoveSetAt(setIdx) },
+ ],
+ })
+
+ return <div className="focus-view" data-testid="focus-view">
+ <div className="focus-card">
+ {unit.length > 1 && <div className="focus-superset-inline">
+ <Icon name="reset" />
+ <strong>{t('Superset:')} {unit.map(index => exerciseNameFor(exOr(S.active.entries[index].id))).join(' + ')}</strong>
+ <span>{t('Round {0}', setIdx + 1)} · {t('Exercise {0} of {1}', unit.indexOf(entryIdx) + 1, unit.length)}</span>
+ <Button size="xs" variant="ghost" icon="link" aria-label={t('Unpair')} onClick={onUnpair}>{t('Unpair')}</Button>
+ <div className="focus-superset-nav">
+ <button aria-label={t('Previous superset set')} disabled={sequenceIdx <= 0} onClick={() => selectSequence(sequenceIdx - 1)}><Icon name="chevronLeft" /></button>
+ <button aria-label={t('Next superset set')} disabled={sequenceIdx < 0 || sequenceIdx >= sequence.length - 1} onClick={() => selectSequence(sequenceIdx + 1)}><Icon name="chevronRight" /></button>
+ </div>
+ </div>}
+ <header className="focus-card-header">
+ <h2>{exerciseNameFor(ex)}</h2>
+ <button className="iconbtn" aria-label={t('Details')} onClick={() => exerciseDetailSheet(ex)}><Icon name="info" /></button>
+ {isWarmupRow(set) && <span className="focus-warmup" aria-label={t('Warm-up')}>🔥</span>}
+ <button className="iconbtn" aria-label={t('More')} onClick={openExerciseMenu}><Icon name="more" /></button>
+ </header>
+
+ <div className="focus-context">
+ <div className="focus-tags">
+ {mode === 'cardio' && <span className="tag acc">{t('Cardio')}</span>}
+ {isSideSet(set) && <span className="tag acc">{t('Per side')}</span>}
+ {(ex.tg || ex.bp) && <span className="tag">{t(ex.tg || ex.bp)}</span>}
+ {ex.eq && <span className="tag">{t(ex.eq)}</span>}
+ </div>
+ {entry.target?.note && <div className="focus-note">{entry.target.note}</div>}
+ {pinnedNote && <div className="focus-note pinned"><Icon name="flag" />{t('From {0}:', fmtDate(pinnedNote.d, true))} {pinnedNote.note}</div>}
+ {entry.note && <div className="focus-note">{entry.note}</div>}
+ {last && <div className="focus-last">{t('Last time')} · {fmtDate(last.d)}</div>}
+ {guidance && <button className="focus-guidance" onClick={onProgressionSettings}><Icon name="lightbulb" />{t(guidance.policyLabel)}</button>}
+ </div>
+ <Prescription entry={entry} setIdx={setIdx} unit={S.unit} fallbackRest={S.restSec} />
+ {locked && <p className="focus-lock-note" role="status">{t('Complete set {0} to edit this one.', firstOpenSet + 1)}</p>}
+
+ <div data-testid="focus-set" className={(set.done ? 'complete ' : '') + (locked ? 'locked' : '')}>
+ {isSideSet(set) ? <div className="focus-sides">{sideFields('L')}{sideFields('R')}</div> : <>
+ {mode === 'cardio' ? <>
+ <Stepper label={t('Duration (min)')} ariaLabel="duration" value={set.min || 0} step={1} decimal={false} disabled={readOnly}
+ onChange={value => onField(setIdx, 'min', value)} />
+ <Stepper label={t('Speed (km/h)')} ariaLabel="speed" value={set.speed || 0} step={0.5} disabled={readOnly}
+ onChange={value => onField(setIdx, 'speed', value)} />
+ </> : <>
+ <Stepper label={t('Load ({0})', S.unit)} ariaLabel="load" value={set.w || 0} step={loadStep} onStep={stepWeight} disabled={readOnly}
+ onChange={value => onField(setIdx, 'w', value)} />
+ {mode === 'time' ? <div className="focus-timed">
+ <strong>{t('{0}s hold', set.sec || entry.target?.sec || 45)}</strong>
+ <Button icon="play" aria-label={t('Start set')} disabled={readOnly || busy}
+ onClick={() => onStartTimed(setIdx, onProgress)}>{t('Start')}</Button>
+ </div> : <Stepper label={t('Reps')} ariaLabel="reps" value={set.r || 0} step={1} decimal={false} disabled={readOnly}
+ onChange={value => onField(setIdx, 'r', value)} />}</>}
+ </>}
+ <div className="focus-extras">
+ {drops.map((drop, index) => <div className="focus-extra" key={`drop-${index}`}>
+ <span>{t('Drop {0}', index + 1)}</span>
+ <Stepper label={t('Load')} ariaLabel="load" value={drop.w || 0} step={loadStep} onStep={stepWeight} disabled={readOnly}
+ onChange={value => onMutateSet(setIdx, row => setDropAt(row, index, { w: value }))} />
+ <Stepper label={t('Reps')} ariaLabel="reps" value={drop.r || 0} step={1} decimal={false} disabled={readOnly}
+ onChange={value => onMutateSet(setIdx, row => setDropAt(row, index, { r: value }))} />
+ </div>)}
+ {bursts.map((burst, index) => <div className="focus-extra" key={`burst-${index}`}>
+ <span>{t('Burst {0}', index + 1)}</span>
+ <Stepper label={t('Reps')} ariaLabel="reps" value={burst.r || 0} step={1} decimal={false} disabled={readOnly}
+ onChange={value => onMutateSet(setIdx, row => {
+ const delta = (Number(value) || 0) - (clustersOf(row)[index]?.r ?? row.clusters?.[index]?.r ?? 0)
+ return { ...setClusterAt(row, index, { r: value }), r: Math.max(0, (row.r || 0) + delta) }
+ })} />
+ <span className="dim small">{burst.restSec}s</span>
+ </div>)}
+ </div>
+ {mode === 'reps' && effortField && <button className={'effcell focus-effort' + (effortValue == null ? ' is-empty' : '')}
+ style={effortTint ? { color: effortTint, borderColor: effortTint, background: `color-mix(in srgb, ${effortTint} 20%, var(--surface-2))` } : undefined}
+ aria-label={t(EFFORT[effort].hd)} disabled={readOnly} onClick={openEffort}>{effortValue == null ? t(EFFORT[effort].hd) : fmtNum(effortValue)}</button>}
+ </div>
+
+ <Button variant="primary" icon="check" aria-label={t('Complete set')} onClick={complete}>{set.done ? t('Completed') : t('Complete')}</Button>
+ <div className="focus-secondary">
+ <button className="focus-skip" aria-label={t('Skip set')} disabled={setIdx >= entry.sets.length - 1} onClick={() => selectSet(setIdx + 1)}>
+ <Icon name="play" />{t('Skip')}
+ </button>
+ <button className="iconbtn" aria-label={t('Set menu')} onClick={openSetMenu}><Icon name="more" /></button>
+ </div>
+ </div>
+
+ <footer className="focus-pager">
+ <button aria-label={t('Previous set')} disabled={setIdx === 0} onClick={() => selectSet(setIdx - 1)}><Icon name="chevronLeft" /></button>
+ <div className="focus-dots">
+ {entry.sets.map((row, index) => <button key={index} aria-label={t('Set {0}', index + 1)}
+ className={(index === setIdx ? 'active ' : '') + (row.done ? 'done' : '')}
+ onClick={() => selectSet(index)} />)}
+ </div>
+ <button aria-label={t('Next set')} disabled={setIdx === entry.sets.length - 1} onClick={() => selectSet(setIdx + 1)}><Icon name="chevronRight" /></button>
+ </footer>
+ </div>
+}
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index fd5770fce..043bd7721 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -397,7 +397,7 @@ export default function Settings({ page = null, find = null, via = null }) {
autoBackup: !!S.autoBackup, synced: !!sync, installTip: !MOBILE && !standalone(), androidWeb: IS_ANDROID,
}
const mode = scheduleModeOf(S)
- const layout = ['list', 'compact'].includes(S.workoutView) ? S.workoutView : 'cards'
+ const layout = ['list', 'compact', 'focus'].includes(S.workoutView) ? S.workoutView : 'cards'
const layoutLabel = { cards: t('Cards'), list: t('List'), compact: t('Compact') }[layout]
const activeProfile = (S.equipProfiles || []).find(p => p.id === S.activeEquipId)
const themeLabel = { dark: t('Dark'), light: t('Light'), system: t('System') }[S.theme || 'dark'] || t('Dark')
@@ -473,7 +473,7 @@ export default function Settings({ page = null, find = null, via = null }) {
unknown values read as cards. The workout's ⋯ menu can override it for one session. */}
<Row icon="layout" iconTint="var(--blue)" title={t('Layout')}>
<Segmented className="seg-inline"
- options={[{ value: 'cards', label: t('Cards') }, { value: 'list', label: t('List') }, { value: 'compact', label: t('Compact') }]}
+ options={[{ value: 'cards', label: t('Cards') }, { value: 'list', label: t('List') }, { value: 'compact', label: t('Compact') }, { value: 'focus', label: t('Focus') }]}
value={layout} onChange={v => update(s => { s.workoutView = v })} />
</Row>
</Section>
diff --git a/frontend/src/views/Settings.workoutview.test.jsx b/frontend/src/views/Settings.workoutview.test.jsx
index 809871c88..85503751c 100644
--- a/frontend/src/views/Settings.workoutview.test.jsx
+++ b/frontend/src/views/Settings.workoutview.test.jsx
@@ -67,29 +67,23 @@ const mount = () => act(() => root.render(<Settings page="workout" />))
const segButton = label => [...host.querySelectorAll('.seg button')].find(b => b.textContent === label)
describe('Settings — workout view', () => {
- it('offers Cards / List / Compact and writes workoutView to the store', () => {
+ it('offers Cards / List / Compact / Focus and writes workoutView to the store', () => {
mount()
- expect(segButton('Cards')).toBeTruthy()
- expect(segButton('List')).toBeTruthy()
- expect(segButton('Compact')).toBeTruthy()
+ expect(['Cards', 'List', 'Compact', 'Focus'].every(label => segButton(label))).toBe(true)
expect(segButton('Cards').getAttribute('aria-pressed')).toBe('true')
- act(() => { segButton('List').click() })
- expect(mocks.S.workoutView).toBe('list')
- mount()
- expect(segButton('List').getAttribute('aria-pressed')).toBe('true')
- act(() => { segButton('Compact').click() })
- expect(mocks.S.workoutView).toBe('compact')
- mount()
- expect(segButton('Compact').getAttribute('aria-pressed')).toBe('true')
- act(() => { segButton('Cards').click() })
- expect(mocks.S.workoutView).toBe('cards')
+
+ for (const [label, value] of [['List', 'list'], ['Compact', 'compact'], ['Focus', 'focus'], ['Cards', 'cards']]) {
+ act(() => { segButton(label).click() })
+ expect(mocks.S.workoutView).toBe(value)
+ mount()
+ expect(segButton(label).getAttribute('aria-pressed')).toBe('true')
+ }
})
it('shows a legacy/absent value as Cards', () => {
- delete mocks.S.workoutView
+ mocks.S.workoutView = 'grid'
mount()
expect(segButton('Cards').getAttribute('aria-pressed')).toBe('true')
- expect(segButton('List').getAttribute('aria-pressed')).toBe('false')
- expect(segButton('Compact').getAttribute('aria-pressed')).toBe('false')
+ expect(segButton('Focus').getAttribute('aria-pressed')).toBe('false')
})
})
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx
index 39a96e3d8..3a941f034 100644
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@ -40,6 +40,7 @@ import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, a
import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from '../lib/active-workout-order.js'
import { nextOpenSet, workoutKeyAction } from '../lib/workout-keys.js'
import { MUSCLE_NAME } from '../lib/muscles.js'
+import FocusView from './FocusView.jsx'
// How long after a key starts a hold the same key is not yet its "Done" (#133). A USB button
// that bounces, or a double press, sends two presses a moment apart: the first starts the hold,
@@ -907,8 +908,10 @@ function ActiveWorkout() {
// parameterised, so these only change what is rendered — completion, rest, top-weight and
// auto-advance share one path. Unknown/absent values read as cards, keeping every
// pre-existing profile (and a session started before this field) as it was.
- const workoutView = A.workoutView || S.workoutView
+ const requestedView = A.workoutView || S.workoutView
+ const workoutView = ['list', 'compact', 'focus'].includes(requestedView) ? requestedView : 'cards'
const listMode = workoutView === 'list' || workoutView === 'compact'
+ const focusMode = workoutView === 'focus'
const dense = workoutView === 'compact'
const wc = workoutControls(S)
// Superset flow: center the actionable row when completing a set moves to the partner or
@@ -916,6 +919,7 @@ function ActiveWorkout() {
// distinct, while each rendered set index identifies the existing row within that entry.
const exRefs = useRef(new Map())
const setRefs = useRef(new Map())
+ const focusPointerEpoch = useRef(0)
const bindExRef = (entry, el) => {
if (el) exRefs.current.set(entry, el)
else {
@@ -1120,9 +1124,11 @@ function ActiveWorkout() {
// The set-number menu's Remove and the swipe both go through deleteActiveSet, Undo and all.
const removeSetAt = (idx, i) => deleteActiveSet(idx, i, { editing })
const pairAt = (first, second) => update(s => {
+ if (focusMode) focusPointerEpoch.current++
s.active.entries = pairAdjacent(s.active.entries, first, second)
})
const unpairAt = idx => update(s => {
+ if (focusMode) focusPointerEpoch.current++
s.active.entries = unpairSuperset(s.active.entries, idx)
})
const onPairPrev = !isSuperset && cur > 0 ? () => pairAt(cur - 1, cur) : null
@@ -1134,6 +1140,7 @@ function ActiveWorkout() {
// Invalidate an old timed callback before indexes shift. A running rest is not cancelled:
// it belongs to an exercise (timer.forIdx), and that exercise only changes position.
ui.stopWork()
+ focusPointerEpoch.current++
update(s => {
const moved = moveActiveWorkoutUnit(s.active, at, direction)
if (!moved) return
@@ -1206,29 +1213,40 @@ function ActiveWorkout() {
// One prop object per entry so the card and list layouts share the exact same wiring. The
// exercise-level actions (swap, move, remove) address the entry itself, so the "more" menu of
// a superset member acts on that member, not on whatever the marker happens to point at.
+ const swapExercise = idx => {
+ if (focusMode) focusPointerEpoch.current++
+ swapActiveWorkoutExercise(idx)
+ }
const blockProps = idx => ({
editing,
- onSwap: () => swapActiveWorkoutExercise(idx),
+ onSwap: () => swapExercise(idx),
onMoveUp: () => moveUnitAt(idx, -1),
onMoveDown: () => moveUnitAt(idx, 1),
canMoveUp: canMoveActiveWorkoutUnit(A, idx, -1),
canMoveDown: canMoveActiveWorkoutUnit(A, idx, 1),
onRemoveExercise: () => confirmRemoveExercise(idx),
busy: !!work,
- onToggle: i => toggle(idx, i),
- onToggleSide: (i, side) => toggle(idx, i, side),
+ onToggle: (i, onFocusProgress) => toggle(idx, i, undefined, { onFocusProgress }),
+ onToggleSide: (i, side, onFocusProgress) => toggle(idx, i, side, { onFocusProgress }),
onField: (i, f, v) => setField(idx, i, f, v),
+ onMutateSet: (i, fn) => mutEntry(idx, entry => { entry.sets[i] = fn(entry.sets[i]) }),
onAddSet: () => addSet(idx),
onRemoveSet: () => removeSet(idx),
onAddWarmup: () => addWarmup(idx),
onRemoveSetAt: i => removeSetAt(idx, i),
onCopySetAt: i => copyActiveSet(idx, i),
- onStartTimed: i => startTimed(idx, i),
+ onStartTimed: (i, onFocusProgress) => startTimed(idx, i, onFocusProgress),
onProgressionSettings: editing ? null : () => openProgressionSettings(idx),
onRest: editing ? null : () => openExerciseRest(idx),
onNoProg: routineKeepsOut(A.entries[idx]) ? null : on => setNoProg(idx, on),
routineUpdate: routineUpdateFor(idx),
})
+ const selectFocusEntry = idx => update(s => { if (s.active) s.active.cur = idx })
+ const advanceFocusUnit = () => update(s => {
+ if (!s.active) return
+ const next = nextUnfinishedUnit(s.active.entries, supersetUnits(s.active.entries), s.active.cur)
+ if (next) s.active.cur = next[0]
+ })
const navigateUnit = direction => {
const targetFor = active => {
if (!active || !Array.isArray(active.entries) || !Number.isInteger(active.cur)) return null
@@ -1261,13 +1279,19 @@ function ActiveWorkout() {
// (Settings → During a workout → Workout view). It writes s.active.workoutView, which the
// render above prefers over S.workoutView.
const setWorkoutView = v => update(s => { if (s.active) s.active.workoutView = v })
- const LAYOUT_LABEL = { cards: t('Cards'), list: t('List'), compact: t('Compact') }
+ const LAYOUT_LABEL = {
+ cards: t('Cards'),
+ list: t('List'),
+ compact: t('Compact'),
+ focus: t('Focus'),
+ }
const openLayoutMenu = () => menuSheet({
title: t('Layout'),
items: [
{ icon: 'layout', label: t('Cards'), on: workoutView === 'cards', onClick: () => setWorkoutView('cards') },
{ icon: 'list', label: t('List'), on: workoutView === 'list', onClick: () => setWorkoutView('list') },
{ icon: 'compact', label: t('Compact'), on: workoutView === 'compact', onClick: () => setWorkoutView('compact') },
+ { icon: 'target', label: t('Focus'), on: workoutView === 'focus', onClick: () => setWorkoutView('focus') },
],
})
// Logging a past workout (#284): the sets were done days ago, so one tap ticks them all and
@@ -1300,22 +1324,25 @@ function ActiveWorkout() {
// sheet and carry its completed rows forward. A planned session uses its configured
// target when progression is off, while progression-enabled sessions keep their path.
const seed = freestyle ? freestyleConfig(sessionHistory(S), { id: ex.id, ...defaultConfig(ex.id) }) : null
- const commit = cfg => update(s => {
- const full = { ...cfg, id: ex.id }
- // A planned session builds the exercise the way its routine would (prescription, reps
- // source, target); freestyle reproduces what you did last time.
- // Read from before the session's day when it is logged into the past (sessionHistory).
- const past = sessionHistory(s)
- const built = freestyle
- ? { target: { ...cfg }, plan: null, sets: applyIntensifierPlan(buildSets(past, full, {
- step: modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(ex.id, s.unit), preferLast: true,
- }), full, dropGrid(s, full)) }
- : buildPlannedEntry(past, full, routine, { noProg })
- const insertAt = insertionIndexAfterCurrentUnit(supersetUnits(s.active.entries), s.active.cur, s.active.entries.length)
- s.active.entries.splice(insertAt, 0, joinSessionNoProg(s.active, { id: ex.id, ...built, ...(curRid ? { rid: curRid } : {}), ...(noProg ? { noProg: true } : {}) }))
- s.active.cur = insertAt
- useUI.getState().shiftRestOwner(insertAt, 1)
- })
+ const commit = cfg => {
+ if (focusMode) focusPointerEpoch.current++
+ update(s => {
+ const full = { ...cfg, id: ex.id }
+ // A planned session builds the exercise the way its routine would (prescription, reps
+ // source, target); freestyle reproduces what you did last time.
+ // Read from before the session's day when it is logged into the past (sessionHistory).
+ const past = sessionHistory(s)
+ const built = freestyle
+ ? { target: { ...cfg }, plan: null, sets: applyIntensifierPlan(buildSets(past, full, {
+ step: modeOf(full) === 'reps' ? weightIncrement(full, s.unit) : defaultIncrement(ex.id, s.unit), preferLast: true,
+ }), full, dropGrid(s, full)) }
+ : buildPlannedEntry(past, full, routine, { noProg })
+ const insertAt = insertionIndexAfterCurrentUnit(supersetUnits(s.active.entries), s.active.cur, s.active.entries.length)
+ s.active.entries.splice(insertAt, 0, joinSessionNoProg(s.active, { id: ex.id, ...built, ...(curRid ? { rid: curRid } : {}), ...(noProg ? { noProg: true } : {}) }))
+ s.active.cur = insertAt
+ useUI.getState().shiftRestOwner(insertAt, 1)
+ })
+ }
// The "+" on a picker row reads as "add this now" — routed through the same detail
// sheet before, so it added nothing until you'd scrolled past it and found the real
// button. Quick-add commits with the same default (or, freestyle, last-session) config
@@ -1439,7 +1466,7 @@ function ActiveWorkout() {
// Remove a whole exercise from the session. The confirmation always asks first; in a
// superset it asks WHICH exercise of the group to remove.
- const removeExercise = removeActiveExercise
+ const removeExercise = idx => { focusPointerEpoch.current++; removeActiveExercise(idx) }
const confirmRemoveExercise = idx => {
const e = A.entries[idx]
if (!e) return
@@ -1473,7 +1500,7 @@ function ActiveWorkout() {
// finish logs 0:38 of a 0:45 target rather than crediting the full prescription — and then
// checks the set off through the normal path, so rest, supersets and the finish prompt all
// behave exactly as they do for a reps set.
- const startTimed = (idx, i) => {
+ const startTimed = (idx, i, onFocusProgress) => {
if (editing) return
const e = A.entries[idx]
// This tap may be the only one before the hold's countdown beeps (a timed first exercise):
@@ -1487,13 +1514,13 @@ function ActiveWorkout() {
// reaches S.workouts (lib/finish-workout.js).
const plan = (!e.sets[i].done && e.sets[i].planSec) || e.sets[i].sec || 45
const owner = { idx, i }
- useUI.getState().startWork(plan, exerciseNameText(exOr(e.id)), holdDone(owner, plan), { idx, i, id: e.id })
+ useUI.getState().startWork(plan, exerciseNameText(exOr(e.id)), holdDone(owner, plan, onFocusProgress), { idx, i, id: e.id })
// After startWork: a hold it displaced has already written its seconds to its own row.
holdAt = { owner, idx, i }
}
// What a hold hands back to its row: on its end, its Done, or a rest displacing it. Also bound
// again to a hold restored after a reload (useUI.bindWork, below).
- const holdDone = (owner, plan) => (elapsed, { abandoned = false, chimed = false } = {}) => {
+ const holdDone = (owner, plan, onFocusProgress) => (elapsed, { abandoned = false, chimed = false } = {}) => {
const { idx } = owner
// The row may have moved while the hold ran (a set copied or removed above it): write to
// where it is now. holdAt is that place (deleteActiveSet, copyActiveSet).
@@ -1513,7 +1540,7 @@ function ActiveWorkout() {
return
}
mutEntry(idx, en => { en.sets[i].sec = elapsed; delete en.sets[i].planSec })
- if (!useStore.getState().S.active.entries[idx].sets[i].done) toggle(idx, i, undefined, { quiet: chimed })
+ if (!useStore.getState().S.active.entries[idx].sets[i].done) toggle(idx, i, undefined, { quiet: chimed, onFocusProgress })
}
// A hold that came back from a reload has no handler yet: this screen gives it its own.
const holdDoneRef = useRef(holdDone)
@@ -1531,7 +1558,7 @@ function ActiveWorkout() {
// `quiet`: the hold that ticks this set has just ended with the chime and its buzz pattern
// (store/useUI.js). The tick's own beep would sound over the chime's first note and clip it,
// and its short buzz would cut the pattern off: a new vibrate call replaces the running one.
- const toggle = (idx, i, side, { quiet = false } = {}) => {
+ const toggle = (idx, i, side, { quiet = false, onFocusProgress } = {}) => {
// Ticking a set ends the typing in that row: drop the keyboard before the rest timer, the
// effort sheet or the next exercise moves in. WebKit keeps the input focused across the
// button tap, and a focused input with its keyboard gone is what leaves the tab bar
@@ -1625,17 +1652,19 @@ function ActiveWorkout() {
if (freshUnitDone) stopRest()
if (!freshUnit || freshUnit.length <= 1) {
if (!restBeforeWarmup && restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restAfter, idx, { forSet: i })
+ onFocusProgress?.({ unitDone: freshUnitDone })
return
}
const step = supersetFlowStep(fresh.entries, freshUnit, idx)
- if (!step) return
+ if (!step) { onFocusProgress?.({ unitDone: freshUnitDone }); return }
if (step.unitDone) {
if (nextUnit?.length && !restBeforeWarmup) startRest(restAfter, idx, { forSet: i })
} else {
if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx })
if (step.roundDone) startRest(restAfter, idx, { forSet: i })
}
+ onFocusProgress?.({ unitDone: freshUnitDone })
}
}
@@ -1809,7 +1838,12 @@ function ActiveWorkout() {
</div>
) : <ExerciseBlock entryIdx={adjacent[0]} {...blockProps(adjacent[0])} />
}}>
- {isSuperset ? (
+ {focusMode ? (
+ <FocusView entryIdx={cur} unit={unit}
+ onSelectEntry={selectFocusEntry} onAdvanceUnit={advanceFocusUnit} pointerEpoch={focusPointerEpoch.current}
+ onPairPrev={onPairPrev} onPairNext={onPairNext} onUnpair={() => unpairAt(cur)}
+ {...blockProps(cur)} />
+ ) : isSuperset ? (
<div className="ss-card">
<div className="ss-hd" style={{ justifyContent: 'space-between' }}>
<span className="row" style={{ gap: 5 }}><Icon name="link" />{t('Superset · do these back-to-back, rest when done')}</span>
@@ -1849,7 +1883,7 @@ function ActiveWorkout() {
<div style={{ height: 6 }} />
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Button size="sm" icon="swap" aria-label={t('Swap exercise')} disabled={!!work}
- onClick={() => swapActiveWorkoutExercise(cur)}>{t('Swap exercise')}</Button>
+ onClick={() => swapExercise(cur)}>{t('Swap exercise')}</Button>
</div>
<div style={{ height: 6 }} />
<div style={{ display: 'flex', justifyContent: 'center' }}>
diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx
index 5e8e6384b..515f9581f 100644
--- a/frontend/src/views/Workout.test.jsx
+++ b/frontend/src/views/Workout.test.jsx
@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => {
S: null,
timer: null,
work: null,
+ startWork: vi.fn(),
startRest: vi.fn(),
startWork: vi.fn(),
stopRest: null,
@@ -36,6 +37,7 @@ const mocks = vi.hoisted(() => {
durationSheet: vi.fn(),
workoutSettingsSheet: vi.fn(),
nav: vi.fn(),
+ setNoteSheet: vi.fn(),
}
state.stopRest = vi.fn(() => { state.timer = null })
state.stopWork = vi.fn(() => { state.work = null })
@@ -88,6 +90,7 @@ vi.mock('../sheets.jsx', () => ({
// Both note sheets belong here even though the tests never open one: Workout.jsx reads
// sessionNoteSheet during render, so a missing export is a render crash, not a no-op.
exerciseNoteSheet: vi.fn(),
+ setNoteSheet: mocks.setNoteSheet,
sessionNoteSheet: vi.fn(),
renameWorkoutSheet: mocks.renameWorkoutSheet,
effortPickerSheet: mocks.effortPickerSheet,
@@ -182,6 +185,12 @@ async function pressNext() {
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
+const buttonNamed = name => container.querySelector(`button[aria-label="${name}"]`)
+const click = async element => {
+ expect(element).toBeTruthy()
+ await act(async () => { element.dispatchEvent(new dom.Event('click', { bubbles: true })) })
+}
+
async function pressProgression(index = 0) {
const button = container.querySelectorAll('.progline')[index]
expect(button).toBeTruthy()
@@ -1386,6 +1395,434 @@ describe('active exercise swap control', () => {
})
})
+describe('workout focus view', () => {
+ it('shows only the first incomplete set with its prescription and tactile controls', async () => {
+ await mount([exercise('plain-bench', [true, false, false], {
+ target: { mode: 'reps', reps: 5, repsMin: 3, weight: 60, restSec: 120 },
+ })], 0, { active: { workoutView: 'focus' }, effort: 'rpe' })
+
+ expect(container.querySelector('[data-testid="focus-view"]')).toBeTruthy()
+ expect(container.querySelectorAll('[data-testid="focus-set"]').length).toBe(1)
+ expect(container.textContent).toContain('2/3')
+ expect(container.textContent).toContain('3–5 Reps')
+ expect(container.textContent).toContain('@ 60 kg')
+ expect(container.textContent).toContain('Rest 120s')
+ expect(buttonNamed('Previous set').disabled).toBe(false)
+ expect(buttonNamed('Next set').disabled).toBe(false)
+ })
+
+ it('moves with chevrons, dots, and Skip without completing a set', async () => {
+ await mount([exercise('plain-bench', [false, false, false])], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('Next set'))
+ expect(container.textContent).toContain('2/3')
+ await click(container.querySelector('button[aria-label="Set 3"]'))
+ expect(container.textContent).toContain('3/3')
+ await click(buttonNamed('Previous set'))
+ expect(container.textContent).toContain('2/3')
+ await click(buttonNamed('Skip set'))
+ expect(container.textContent).toContain('3/3')
+ expect(mocks.S.active.entries[0].sets.every(set => !set.done)).toBe(true)
+ })
+
+ it('locks later Focus sets while keeping them inspectable', async () => {
+ await mount([exercise('plain-bench', [false, false])], 0, { active: { workoutView: 'focus' }, effort: 'rpe' })
+
+ await click(buttonNamed('Next set'))
+
+ expect(container.querySelector('[data-testid="focus-set"]').classList.contains('locked')).toBe(true)
+ expect(container.textContent).toContain('Complete set 1 to edit this one.')
+ expect(buttonNamed('Increase load').disabled).toBe(true)
+ expect(buttonNamed('Increase reps').disabled).toBe(true)
+ expect(buttonNamed('RPE').disabled).toBe(true)
+ })
+
+ it('pairs adjacent exercises from Focus and can unpair them', async () => {
+ await mount([exercise('plain-bench', [false]), exercise('plain-row', [false])], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('More'))
+ const pair = mocks.menuSheet.mock.calls.at(-1)[0].items.find(item => item?.label === 'Make superset with next')
+ expect(pair).toBeTruthy()
+ await act(async () => { pair.onClick() })
+ await rerender()
+ expect(container.querySelector('.focus-superset')).toBeNull()
+ expect(container.querySelector('.focus-card .focus-superset-inline')).toBeTruthy()
+
+ await click(buttonNamed('Unpair'))
+ await rerender()
+ expect(container.querySelector('.focus-superset')).toBeNull()
+ })
+
+ it('uses the shared effort picker for the selected RPE scale', async () => {
+ await mount([exercise('plain-bench', [false])], 0, { active: { workoutView: 'focus' }, effort: 'rpe' })
+
+ await click(buttonNamed('Increase load'))
+ await click(buttonNamed('Increase reps'))
+ await click(buttonNamed('RPE'))
+ const [, value, onPick] = mocks.effortPickerSheet.mock.calls.at(-1)
+ expect(mocks.effortPickerSheet.mock.calls.at(-1)[0]).toBe('rpe')
+ expect(value).toBeNull()
+ await act(async () => { onPick(6.5) })
+
+ expect(mocks.S.active.entries[0].sets[0].w).toBe(62.5)
+ expect(mocks.S.active.entries[0].sets[0].r).toBe(6)
+ expect(mocks.S.active.entries[0].sets[0].rpe).toBe(6.5)
+ })
+
+ it('hides effort in Focus when Settings selects none and stores the selected RIR scale', async () => {
+ await mount([exercise('plain-bench', [false])], 0, { active: { workoutView: 'focus' }, effort: 'none' })
+ expect(buttonNamed('RPE')).toBeNull()
+ expect(buttonNamed('RIR')).toBeNull()
+
+ await mount([exercise('plain-bench', [false])], 0, { active: { workoutView: 'focus' }, effort: 'rir' })
+ await click(buttonNamed('RIR'))
+ const [, , onPick] = mocks.effortPickerSheet.mock.calls.at(-1)
+ await act(async () => { onPick(2) })
+ expect(mocks.S.active.entries[0].sets[0]).toMatchObject({ rir: 2 })
+ })
+
+ it('locks completed set inputs and mutes their values', async () => {
+ await mount([exercise('plain-bench', [false])], 0, { active: { workoutView: 'focus' }, effort: 'rpe' })
+
+ await click(buttonNamed('Complete set'))
+ await rerender()
+
+ expect(container.querySelector('[data-testid="focus-set"]').classList.contains('complete')).toBe(true)
+ expect(buttonNamed('Increase load').disabled).toBe(true)
+ expect(buttonNamed('Increase reps').disabled).toBe(true)
+ expect(container.querySelectorAll('[data-testid="focus-set"] .stp input:disabled')).toHaveLength(2)
+ expect(buttonNamed('RPE').disabled).toBe(true)
+ })
+
+ it('renders and updates independent unilateral sides', async () => {
+ await mount([exercise('split-squat', [false], {
+ target: { mode: 'reps', reps: 10, weight: 20, side: true },
+ sets: [{
+ w: 20, r: 10, done: false,
+ sides: {
+ L: { w: 20, r: 5, done: false },
+ R: { w: 20, r: 5, done: false },
+ },
+ }],
+ })], 0, { active: { workoutView: 'focus' } })
+
+ expect(container.querySelectorAll('[data-focus-side]').length).toBe(2)
+ await click(container.querySelector('[data-focus-side="L"] button[aria-label="Increase reps"]'))
+ expect(mocks.S.active.entries[0].sets[0].sides.L.r).toBe(6)
+ expect(mocks.S.active.entries[0].sets[0].sides.R.r).toBe(5)
+ await click(container.querySelector('[data-focus-side="L"] button[aria-label="Complete left side"]'))
+ expect(mocks.S.active.entries[0].sets[0].sides.L.done).toBe(true)
+ expect(mocks.S.active.entries[0].sets[0].done).toBe(false)
+ })
+
+ it('completes both unilateral sides through the side mutator before advancing Focus', async () => {
+ await mount([
+ exercise('split-squat', [false], {
+ target: { mode: 'reps', reps: 10, weight: 20, side: true },
+ sets: [{ w: 20, r: 10, done: false, sides: {
+ L: { w: 20, r: 5, done: false }, R: { w: 20, r: 5, done: false },
+ } }],
+ }),
+ exercise('plain-row', [false]),
+ ], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('Complete set'))
+
+ const set = mocks.S.active.entries[0].sets[0]
+ expect(set.sides.L.done).toBe(true)
+ expect(set.sides.R.done).toBe(true)
+ expect(set.done).toBe(true)
+ expect(mocks.S.active.cur).toBe(1)
+ })
+
+ it('advances Focus when the second individual side is completed', async () => {
+ await mount([
+ exercise('split-squat', [false], {
+ target: { mode: 'reps', reps: 10, weight: 20, side: true },
+ sets: [{ w: 20, r: 10, done: false, sides: {
+ L: { w: 20, r: 5, done: false }, R: { w: 20, r: 5, done: false },
+ } }],
+ }),
+ exercise('plain-row', [false]),
+ ], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('Complete left side'))
+ await rerender()
+ await click(buttonNamed('Complete right side'))
+
+ expect(mocks.S.active.entries[0].sets[0].done).toBe(true)
+ expect(mocks.S.active.cur).toBe(1)
+ })
+
+ it('renders and edits unilateral extras added through the set menu', async () => {
+ await mount([exercise('split-squat', [false], {
+ target: { mode: 'reps', reps: 10, weight: 20, side: true },
+ sets: [{
+ w: 20, r: 10, done: false,
+ sides: {
+ L: { w: 20, r: 5, done: false },
+ R: { w: 20, r: 5, done: false },
+ },
+ }],
+ })], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('Set menu'))
+ await act(async () => { mocks.menuSheet.mock.calls.at(-1)[0].items[1].onClick() })
+ await rerender()
+ const left = container.querySelector('[data-focus-side="L"]')
+ expect(left.textContent).toContain('Drop 1')
+ await click(left.querySelectorAll('button[aria-label="Increase load"]')[1])
+ expect(mocks.S.active.entries[0].sets[0].sides.L.drops[0].w).toBe(18.5)
+ expect(mocks.S.active.entries[0].sets[0].sides.R.drops[0].w).toBe(16)
+
+ await click(buttonNamed('Set menu'))
+ await act(async () => { mocks.menuSheet.mock.calls.at(-1)[0].items[2].onClick() })
+ await rerender()
+ const burstLeft = container.querySelector('[data-focus-side="L"]')
+ expect(burstLeft.textContent).toContain('Drop 1')
+ expect(burstLeft.textContent).toContain('Burst 1')
+ const burst = [...burstLeft.querySelectorAll('.focus-extra')].find(row => row.textContent.includes('Burst 1'))
+ await click(burst.querySelector('button[aria-label="Increase reps"]'))
+ expect(mocks.S.active.entries[0].sets[0].sides.L.clusters[0].r).toBe(4)
+ expect(mocks.S.active.entries[0].sets[0].sides.R.clusters[0].r).toBe(3)
+ })
+
+ it('shows the existing timer action instead of reps for timed sets', async () => {
+ await mount([exercise('plank', [false], {
+ target: { mode: 'time', sec: 45, weight: 0 },
+ sets: [{ sec: 45, w: 0, done: false }],
+ })], 0, { active: { workoutView: 'focus' } })
+
+ expect(container.textContent).toContain('45s hold')
+ expect(buttonNamed('Start set')).toBeTruthy()
+ expect(buttonNamed('Increase reps')).toBeNull()
+ await click(buttonNamed('Start set'))
+ expect(mocks.uiSnapshot().startWork).toHaveBeenCalled()
+ })
+
+ it('advances Focus when a timed set finishes through the shared timer', async () => {
+ await mount([
+ exercise('plank', [false], {
+ target: { mode: 'time', sec: 45, weight: 0 },
+ sets: [{ sec: 45, w: 0, done: false }],
+ }),
+ exercise('plain-row', [false]),
+ ], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('Start set'))
+ await act(async () => { mocks.uiSnapshot().startWork.mock.calls.at(-1)[2](45) })
+
+ expect(mocks.S.active.entries[0].sets[0].done).toBe(true)
+ expect(mocks.S.active.cur).toBe(1)
+ })
+
+ it('does not advance Focus when rechecking a completed final set', async () => {
+ await mount([
+ exercise('plain-bench', [true]),
+ exercise('plain-row', [false]),
+ ], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('Complete set'))
+ await rerender()
+ await click(buttonNamed('Complete set'))
+
+ expect(mocks.S.active.entries[0].sets[0].done).toBe(true)
+ expect(mocks.S.active.cur).toBe(0)
+ })
+
+ it('uses the established duration and speed fields for cardio', async () => {
+ await mount([exercise('plain-treadmill', [false], {
+ target: { mode: 'cardio', min: 20, speed: 8 },
+ sets: [{ min: 20, speed: 8, done: false }],
+ })], 0, { active: { workoutView: 'focus' } })
+
+ expect(container.textContent).toContain('Duration (min)')
+ expect(container.textContent).toContain('Speed (km/h)')
+ expect(container.querySelectorAll('button[aria-label="Increase reps"]').length).toBe(0)
+ await click(container.querySelector('button[aria-label="Increase duration"]'))
+ await click(container.querySelector('button[aria-label="Increase speed"]'))
+ expect(mocks.S.active.entries[0].sets[0]).toMatchObject({ min: 21, speed: 8.5 })
+ })
+
+ it('keeps drop and burst rows editable and opens every set action', async () => {
+ await mount([exercise('plain-bench', [false], {
+ sets: [{
+ w: 60, r: 8, done: false,
+ drops: [{ w: 45, r: 8 }],
+ clusters: [{ r: 3, restSec: 15 }],
+ }],
+ })], 0, { active: { workoutView: 'focus' } })
+
+ expect(container.textContent).toContain('Drop 1')
+ expect(container.textContent).toContain('Burst 1')
+ await click(container.querySelectorAll('button[aria-label="Increase load"]')[1])
+ await click(container.querySelectorAll('button[aria-label="Increase reps"]')[2])
+ expect(mocks.S.active.entries[0].sets[0].drops[0].w).toBe(47.5)
+ expect(mocks.S.active.entries[0].sets[0].clusters[0].r).toBe(4)
+ expect(mocks.S.active.entries[0].sets[0].r).toBe(9)
+ await click(buttonNamed('Set menu'))
+ const labels = mocks.menuSheet.mock.calls.at(-1)[0].items.filter(Boolean).map(item => item.label)
+ expect(labels).toEqual(['Mark as warm-up', 'Add drop set', 'Add burst', 'Delete set'])
+ })
+
+ it('does not expose a Focus-only set note action', async () => {
+ await mount([exercise('plain-bench', [false, false])], 0, { active: { workoutView: 'focus' } })
+ await click(buttonNamed('Next set'))
+ expect(buttonNamed('Set note')).toBeNull()
+ })
+
+ it('completes, starts rest, advances sets, then advances to the next unfinished exercise', async () => {
+ await mount([
+ exercise('plain-bench', [false, false]),
+ exercise('plain-row', [false]),
+ ], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('Complete set'))
+ expect(mocks.S.active.entries[0].sets[0].done).toBe(true)
+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
+ expect(container.textContent).toContain('2/2')
+
+ await click(buttonNamed('Complete set'))
+ expect(mocks.S.active.entries[0].sets[1].done).toBe(true)
+ expect(mocks.S.active.cur).toBe(1)
+ })
+
+ it('shows one superset member and follows round-major completion order', async () => {
+ await mount([
+ exercise('0968', [false, false], { sg: 'arms' }),
+ exercise('1254', [false, false], { sg: 'arms' }),
+ exercise('squat', [false]),
+ ], 0, { active: { workoutView: 'focus' } })
+
+ expect(container.textContent).toContain('band alternating biceps curl + band bench press')
+ expect(container.textContent).toContain('Round 1')
+ expect(container.textContent).toContain('Exercise 1 of 2')
+
+ await click(buttonNamed('Complete set'))
+ expect(mocks.S.active.cur).toBe(1)
+ await rerender()
+ expect(container.textContent).toContain('Exercise 2 of 2')
+
+ await click(buttonNamed('Complete set'))
+ expect(mocks.S.active.cur).toBe(0)
+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
+ await rerender()
+ expect(container.textContent).toContain('Round 2')
+
+ await click(buttonNamed('Complete set'))
+ expect(mocks.S.active.cur).toBe(1)
+ await rerender()
+ await click(buttonNamed('Complete set'))
+ expect(mocks.S.active.cur).toBe(2)
+ })
+
+ it('uses the superset chevrons and dots for inspection without completing work', async () => {
+ await mount([
+ exercise('0968', [false, false], { sg: 'arms' }),
+ exercise('1254', [false, false], { sg: 'arms' }),
+ ], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('Next superset set'))
+ expect(mocks.S.active.cur).toBe(1)
+ await rerender()
+ expect(container.textContent).toContain('Exercise 2 of 2')
+ expect(mocks.S.active.entries.flatMap(entry => entry.sets).every(set => !set.done)).toBe(true)
+ })
+
+ it('clears inspected set pointers when superset completion auto-advances', async () => {
+ await mount([
+ exercise('0968', [false, false], { sg: 'arms' }),
+ exercise('1254', [false, false], { sg: 'arms' }),
+ ], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('Next superset set'))
+ await rerender()
+ await click(buttonNamed('Previous superset set'))
+ await rerender()
+ await click(buttonNamed('Complete set'))
+ await rerender()
+ await click(buttonNamed('Complete set'))
+ await rerender()
+
+ expect(container.textContent).toContain('Round 2')
+ expect(container.textContent).toContain('2/2')
+ })
+
+ it('clears a manually selected set when an uneven superset auto-selects the same entry', async () => {
+ await mount([
+ exercise('0968', [false, false], { sg: 'arms' }),
+ exercise('1254', [true], { sg: 'arms' }),
+ ], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('Set 1'))
+ await click(buttonNamed('Complete set'))
+ expect(mocks.S.active.cur).toBe(0)
+ await rerender()
+
+ expect(container.textContent).toContain('Round 2')
+ expect(container.textContent).toContain('2/2')
+ })
+
+ it('omits missing member sets from the superset sequence', async () => {
+ await mount([
+ exercise('0968', [false, false], { sg: 'arms' }),
+ exercise('1254', [false], { sg: 'arms' }),
+ ], 0, { active: { workoutView: 'focus' } })
+
+ await click(buttonNamed('Next superset set'))
+ await rerender()
+ await click(buttonNamed('Next superset set'))
+ await rerender()
+
+ expect(container.textContent).toContain('Round 2')
+ expect(container.textContent).toContain('Exercise 1 of 2')
+ expect(buttonNamed('Next superset set').disabled).toBe(true)
+ })
+
+ it('clears set pointers after an exercise move changes entry indexes', async () => {
+ await mount([
+ exercise('plain-bench', [false, false, false]),
+ exercise('plain-row', [false, false, false]),
+ ], 0, { active: { workoutView: 'focus' }, wc: { exerciseButtons: true } })
+
+ await click(container.querySelector('button[aria-label="Set 3"]'))
+ await rerenderAt(1)
+ await click(container.querySelector('button[aria-label="Move up"]'))
+ await rerender()
+
+ expect(container.textContent).toContain('1/3')
+ })
+
+ it('clears an inspected set pointer before Focus swaps the exercise', async () => {
+ await mount([exercise('plain-bench', [false, false, false])], 0, { active: { workoutView: 'focus' } })
+
+ await click(container.querySelector('button[aria-label="Set 3"]'))
+ await click(buttonNamed('More'))
+ await act(async () => {
+ mocks.menuSheet.mock.calls.at(-1)[0].items.find(item => item?.label === 'Swap exercise').onClick()
+ mocks.S.active.entries[0] = exercise('plain-row', [true, false, false])
+ })
+ await rerender()
+
+ expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledWith(0)
+ expect(container.textContent).toContain('2/3')
+ })
+
+ it('clears an inspected set pointer before the Focus bottom swap button', async () => {
+ await mount([exercise('plain-bench', [false, false, false])], 0, {
+ active: { workoutView: 'focus' }, wc: { exerciseButtons: true },
+ })
+
+ await click(container.querySelector('button[aria-label="Set 3"]'))
+ await click(container.querySelector('button[aria-label="Swap exercise"]'))
+ mocks.S.active.entries[0] = exercise('plain-row', [true, false, false])
+ await rerender()
+
+ expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledWith(0)
+ expect(container.textContent).toContain('2/3')
+ })
+})
+
describe('workout list view', () => {
const units = () => [...container.querySelectorAll('.wl-unit')]
const focusButton = unit => [...unit.querySelectorAll('button')].find(b => b.textContent.trim() === 'Set current')
@@ -1697,7 +2134,7 @@ describe('workout view header menu', () => {
return mocks.menuSheet.mock.calls.at(-1)[0]
}
- it('groups Workout settings, Add, This workout and Discard, then a Layout sheet with the three layouts marked current', async () => {
+ it('groups Workout settings, Add, This workout and Discard, then a Layout sheet with the four layouts marked current', async () => {
await mount([exercise('plain-bench', [false])], 0, { active: { workoutView: 'list', routineIds: [] } })
const menu = await openMenu()
@@ -1714,11 +2151,27 @@ describe('workout view header menu', () => {
expect(mocks.renameWorkoutSheet).toHaveBeenCalled()
const layout = await openLayout(menu)
- expect(menuItemsOf(layout).map(it => it.label)).toEqual(['Cards', 'List', 'Compact'])
+ expect(menuItemsOf(layout).map(it => it.label)).toEqual(['Cards', 'List', 'Compact', 'Focus'])
expect(item(layout, 'List').on).toBe(true)
expect(item(layout, 'Cards').on).toBe(false)
})
+ it('includes Rename workout, Add routine and the whole-workout progression switch, then a Layout sheet with the four layouts marked current', async () => {
+ await mount([exercise('plain-bench', [false])], 0, { active: { workoutView: 'focus', routineIds: [] } })
+
+ const menu = await openMenu()
+ expect(menu.items.filter(Boolean).map(it => it.label)).toEqual(['Rename workout', 'Add routine', 'Don’t count for progression', 'Layout'])
+ expect(item(menu, 'Layout').sub).toBe('Focus')
+
+ await act(async () => { item(menu, 'Rename workout').onClick() })
+ expect(mocks.renameWorkoutSheet).toHaveBeenCalled()
+
+ const layout = await openLayout(menu)
+ expect(layout.items.filter(Boolean).map(it => it.label)).toEqual(['Cards', 'List', 'Compact', 'Focus'])
+ expect(item(layout, 'Focus').on).toBe(true)
+ expect(item(layout, 'Cards').on).toBe(false)
+ })
+
it('writes the layout pick onto s.active without touching the global default', async () => {
await mount([exercise('plain-bench', [false])], 0, { workoutView: 'cards', active: { workoutView: 'cards', routineIds: [] } })