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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Workout: swipe on sets in Cards, List and Compact, Copy this set in the set menu, Undo for every removed set
Duarte Santos29ac9b992207
diff --git a/frontend/src/components/WorkoutSettingsSheet.jsx b/frontend/src/components/WorkoutSettingsSheet.jsxindex 1bad212e1..84f6c8778 100644--- a/frontend/src/components/WorkoutSettingsSheet.jsx+++ b/frontend/src/components/WorkoutSettingsSheet.jsx@@ -2,6 +2,7 @@ import { useStore } from '../store/useStore.js'import { useUI } from '../store/useUI.js'import { t } from '../lib/i18n.js'import { effortOf } from '../lib/history.js'+import { workoutControls } from '../lib/workout-controls.js'import { unlock, vibrateSupported, appleTouchDevice } from '../lib/sound.js'import { wakeLockSupported } from '../lib/wakelock.js'import { MOBILE } from '../lib/mobile.js'@@ -65,6 +66,10 @@ export function WorkoutSettings({ close }) {options={[{ value: 'none', label: t('Off') }, { value: 'rir', label: t('RIR') }, { value: 'rpe', label: t('RPE') }]}value={effortOf(S)} onChange={v => update(s => { s.effort = v; delete s.showRir })} /></Row>+ <Row icon="swap" iconTint="var(--indigo)" title={t('Swipe on sets')} subtitle={t('Left deletes, right copies')}>+ <Switch aria-label={t('Swipe on sets')} checked={workoutControls(S).swipeSets}+ onChange={v => update(s => { s.wc = { ...workoutControls(s), swipeSets: v } })} />+ </Row><Row icon="image" iconTint="var(--teal)" title={t('Exercise animations')}><Segmented className="seg-inline"options={[{ value: 'full', label: t('Full') }, { value: 'mini', label: t('Small') }, { value: 'off', label: t('Hidden') }]}diff --git a/frontend/src/components/WorkoutSettingsSheet.test.jsx b/frontend/src/components/WorkoutSettingsSheet.test.jsxindex a85939e56..1df2602f7 100644--- a/frontend/src/components/WorkoutSettingsSheet.test.jsx+++ b/frontend/src/components/WorkoutSettingsSheet.test.jsx@@ -50,7 +50,7 @@ describe('the in-workout settings sheet', () => {it('has the rows people change at the gym, then All settings', () => {expect([...host.querySelectorAll('.lrow-t')].map(e => e.textContent)).toEqual(['Rest timer', 'Play a sound', 'Vibrate', 'Flash the screen', 'Keep screen awake',- 'Layout', 'Effort per set', 'Exercise animations', 'All settings',+ 'Layout', 'Effort per set', 'Swipe on sets', 'Exercise animations', 'All settings',])expect(row('Rest timer').querySelector('.lrow-v').textContent).toBe('1:30')expect(row('Keep screen awake').querySelector('.lrow-s').textContent).toMatch(/^The screen stays on/)diff --git a/frontend/src/lib/use-swipe-row.js b/frontend/src/lib/use-swipe-row.jsindex c7d8f3c17..7689f0022 100644--- a/frontend/src/lib/use-swipe-row.js+++ b/frontend/src/lib/use-swipe-row.js@@ -177,7 +177,7 @@ export function useSwipeRow({ canDelete = true, onCommit, onBlocked, onStart, clouter.classList.toggle('go-del', off < 0)outer.classList.toggle('go-cp', off > 0)// A tiny buzz crossing the commit point, either way (Android; Safari has no vibrate).- if (!ms && armed !== prevArmed) {+ if (!ms && armed !== prevArmed && g.current?.lock) {const deleting = armed === 'delete' || prevArmed === 'delete'if (!(deleting && props.current.canDelete === false)) vibrate(8)}diff --git a/frontend/src/lib/workout-controls.js b/frontend/src/lib/workout-controls.jsindex f6daed879..489e58649 100644--- a/frontend/src/lib/workout-controls.js+++ b/frontend/src/lib/workout-controls.js@@ -8,6 +8,7 @@ export const WC_DEFAULT = Object.freeze({setShortcuts: false, // "+ Drop" / "+ Burst" chips on every set and the warm-up/remove/add rowpairButtons: false, // "Make superset with previous/next" in the exercise headerexerciseButtons: false, // Move up/down, Swap, Remove exercise below the exercise+ swipeSets: true, // swipe a set row: toward the start deletes (with Undo), toward the end copies})export function workoutControls(S) {diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex c5abff5d7..77f3ff9f2 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -98,6 +98,9 @@ export const DEF = {// lean layout: one "more" button per exercise and a menu on each set number. Every switch// brings one of the old always-visible button groups back (Settings → During a workout).wc: { ...WC_DEFAULT },+ // One-time hints already shown to this profile, synced so each shows once per person rather+ // than once per device: { swipeSets: true } after the first swipe-on-sets nudge (Workout.jsx).+ hints: {},// effort: which per-set effort scale is logged — 'none' | 'rir' | 'rpe'. null, not 'none', so// that a profile which never chose (loaded state is overlaid on DEF, on every path: local,// server pull, backup import) still falls back to the `showRir` boolean this replaced anddiff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.jsindex 5a9c9584a..669d76a70 100644--- a/frontend/src/store/useUI.js+++ b/frontend/src/store/useUI.js@@ -148,9 +148,12 @@ export const useUI = create((set, get) => ({sheets: [], // { id, render:(close)=>JSX, kind:'sheet'|'center', locked }toastMsg: '',toastAction: null, // { label, run, id } while the toast offers an action (Undo)+ swipeHint: null, // { idx, i, id }: the set row showing the one-time swipe hint (Workout.jsx)+ setFlash: null, // { idx, i, id }: the set row a copy or an undo just brought, flashed oncetimer: null, // rest countdown between sets — { left, total, endsAt, forIdx, ready?, paused?, kind? }// kind: 'switch' for the short pause between the two sides of a timed set// forIdx: index of the active entry whose set started the rest (undefined when unknown)+ // forSet: index of that set in the entry's rows, so removing the set stops its rest// paused: held at `left`; `endsAt` means nothing until resumeRest sets it againwork: null, // work countdown DURING a timed set (issue #16) — { left, total, endsAt, label, overtime? }timerFlashId: 0, // changing the id retriggers the theme-blink visual alert@@ -200,7 +203,7 @@ export const useUI = create((set, get) => ({if (get().toastMsg) runToast(set)},- startRest(sec, forIdx, { kind } = {}) {+ startRest(sec, forIdx, { kind, forSet } = {}) {get().stopRest()// Rest timer set to Off. Stopping and returning rather than starting a zero-length timer// keeps every caller honest: the four places that start a rest do not each need to know.@@ -220,7 +223,7 @@ export const useUI = create((set, get) => ({// with no beep, no vibration and no flash. Each timer starts from where the page is now.pageHiddenAt = document.hidden ? Date.now() : nullconst endsAt = Date.now() + sec * 1000- set({ timer: { left: sec, total: sec, endsAt, forIdx, ...(kind === 'switch' ? { kind } : {}) } })+ set({ timer: { left: sec, total: sec, endsAt, forIdx, ...(forSet != null ? { forSet } : {}), ...(kind === 'switch' ? { kind } : {}) } })bookRestEnd(endsAt, sec, kind)runRest(set, get)},@@ -255,7 +258,7 @@ export const useUI = create((set, get) => ({addRest(sec) {const tm = get().timerif (!tm) return- if (tm.ready) { if (sec > 0) get().startRest(Math.min(sec, REST_MAX), tm.forIdx); else get().stopRest(); return }+ if (tm.ready) { if (sec > 0) get().startRest(Math.min(sec, REST_MAX), tm.forIdx, { forSet: tm.forSet }); else get().stopRest(); return }// +15 s stops where the wheel does (15:00), so the two never disagree about a rest's length.if (sec > 0) sec = Math.min(sec, Math.max(0, REST_MAX - tm.left))if (!sec) return@@ -284,7 +287,7 @@ export const useUI = create((set, get) => ({followNativeRest({ endsAt, left, total, paused }) {const tm = get().timerconst forIdx = tm?.forIdx- const kind = tm?.kind === 'switch' ? { kind: 'switch' } : {}+ const kind = { ...(tm?.kind === 'switch' ? { kind: 'switch' } : {}), ...(tm?.forSet != null ? { forSet: tm.forSet } : {}) }if (paused) {stopRestTicking()set({ timer: { left, total, endsAt, forIdx, ...kind, paused: true } })@@ -403,7 +406,7 @@ const saveRest = tm => {if (!ss) returntry {if (!tm || tm.ready) ss.removeItem(REST_KEY)- else ss.setItem(REST_KEY, JSON.stringify({ endsAt: tm.endsAt, total: tm.total, forIdx: tm.forIdx ?? null, kind: tm.kind || null, paused: !!tm.paused, left: tm.left }))+ else ss.setItem(REST_KEY, JSON.stringify({ endsAt: tm.endsAt, total: tm.total, forIdx: tm.forIdx ?? null, forSet: tm.forSet ?? null, kind: tm.kind || null, paused: !!tm.paused, left: tm.left }))} catch { /* the rest just does not outlive a reload */ }}export function restoreRest(now = Date.now()) {@@ -414,7 +417,7 @@ export function restoreRest(now = Date.now()) {const total = Math.round(Number(saved.total))const ok = useStore.getState().S?.active && total > 0 && (saved.paused ? saved.left > 0 : saved.endsAt > now)if (!ok) { try { ss.removeItem(REST_KEY) } catch { /* nothing to drop */ } return false }- const base = { total, forIdx: saved.forIdx ?? undefined, ...(saved.kind === 'switch' ? { kind: 'switch' } : {}) }+ const base = { total, forIdx: saved.forIdx ?? undefined, ...(saved.forSet != null ? { forSet: saved.forSet } : {}), ...(saved.kind === 'switch' ? { kind: 'switch' } : {}) }if (saved.paused) {useUI.setState({ timer: { ...base, left: Math.round(saved.left), endsAt: saved.endsAt, paused: true } })return truediff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex 1b006a3ef..a14717939 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -527,6 +527,10 @@ export default function Settings({ page = null, find = null, via = null }) {<Row icon="bolt" iconTint="var(--orange)" title={t('Drop and burst shortcuts on every set')}><Switch checked={wc.setShortcuts} onChange={v => setWc('setShortcuts', v)} /></Row>+ {/* Swipe on sets (v1.3.11): not a button, but the same question of what a set row does. */}+ <Row icon="swap" iconTint="var(--indigo)" title={t('Swipe on sets')} subtitle={t('Left deletes, right copies')}>+ <Switch aria-label={t('Swipe on sets')} checked={wc.swipeSets} onChange={v => setWc('swipeSets', v)} />+ </Row><Row icon="link" iconTint="var(--blue)" title={t('Superset buttons in the exercise header')}><Switch checked={wc.pairButtons} onChange={v => setWc('pairButtons', v)} /></Row>diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex a0d6431f4..036af5c18 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -1,5 +1,6 @@-import { Fragment, useEffect, useRef, useState } from 'react'+import { Fragment, useEffect, useId, useRef, useState } from 'react'import SwipeCards from '../components/SwipeCards.jsx'+import SwipeRow from '../components/SwipeRow.jsx'import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'import { workoutControls } from '../lib/workout-controls.js'@@ -7,7 +8,7 @@ import { useUI } from '../store/useUI.js'import { exOr, betterWeight } from '../lib/exercises.js'import { usesBar } from '../lib/bar.js'import { loadKindFor, baseWeightFor, inventoryFor, rowLoad, sameLoad, plateDelta, dropGrid } from '../lib/plates.js'-import { effectiveRoutines, effectiveRoutineIds, lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, freestyleConfig, defaultConfig, setsDoneActive, setUnitsTotal, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, makeWarmupAt, makeWorkAt, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor, setsRepsOf } from '../lib/history.js'+import { effectiveRoutines, effectiveRoutineIds, lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, freestyleConfig, defaultConfig, setsDoneActive, setUnitsTotal, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, makeWarmupAt, makeWorkAt, removeRowAt, copyRowAt, copySpanAt, insertRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor, setsRepsOf } from '../lib/history.js'import { fmtNum, fmtPlate, exerciseNameText, fmtDate, fmtDaysAgo, todayISO, exCount, DAYN } from '../lib/format.js'import { speedUnitOf, toSpeed, fromSpeed } from '../lib/speed.js'import { beep, vibrate, unlock } from '../lib/sound.js'@@ -96,10 +97,14 @@ const RTL_LETTER = /[-ࣿיִ-﷿ﹰ-]/// enough to turn over, far shorter than the rest the set earns once both sides are held.const SWITCH_SIDES_SEC = 10-function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSide, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext, onSetRowRef, onProgressionSettings, onRest, onNoProg, routineUpdate, onSwap, onMoveUp, onMoveDown, canMoveUp, canMoveDown, onRemoveExercise, busy }) {+function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSide, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onCopySetAt, onStartTimed, onPairPrev, onPairNext, onSetRowRef, onProgressionSettings, onRest, onNoProg, routineUpdate, onSwap, onMoveUp, onMoveDown, canMoveUp, canMoveDown, onRemoveExercise, busy }) {const S = useStore(s => s.S)const update = useStore(s => s.update)const working = useUI(s => s.work)+ const restEnds = useUI(s => s.timer?.endsAt)+ const swipeHint = useUI(s => (s.swipeHint?.idx === entryIdx ? s.swipeHint : null))+ const setFlash = useUI(s => (s.setFlash?.idx === entryIdx ? s.setFlash : null))+ const optsId = useId()const entry = S.active.entries[entryIdx]// Drops/bursts mutate the row in place — same card, not a new set with its own long rest.// A planned exercise (see the exercise's "Intensifier" config) arrives with these already@@ -400,11 +405,7 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSi// A timed per-side exercise plans in L/R pairs (buildWorkSets, addSet below), so the two// halves of a pair read as one set number — "Set 1 — Left" then "Set 1 — Right" — rather than// counting every row and making the second half look like an extra set.- const setNumOf = (s, i) => {- const warm = isWarmupRow(s)- const phaseNum = entry.sets.slice(0, i + 1).filter(x => isWarmupRow(x) === warm).length- return s.side ? Math.ceil(phaseNum / 2) : phaseNum- }+ const setNumOf = (s, i) => setNumberAt(entry.sets, i)const sideTagOf = s => s.side === 'L' ? t('Left') : s.side === 'R' ? t('Right') : nullconst openSetMenu = (s, i) => {const warm = isWarmupRow(s)@@ -425,6 +426,7 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSi!warm && mode === 'reps' && !isDropSet(s) && { icon: 'bolt', label: t('Rest-pause burst'), sub: t('+ Burst'), onClick: () => addBurstRow(i) },] },{ items: [+ onCopySetAt && { icon: 'copy', label: t('Copy this set'), onClick: () => onCopySetAt(i) },{ icon: 'trash', label: t('Remove this set'), danger: true, disabled: !editing && entry.sets.length <= 1, onClick: () => onRemoveSetAt(i) },] },],@@ -550,6 +552,24 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSi<button aria-label={t('Increase')} onClick={() => onChange(snapWeightStep ? stepWeight(value, step, 1) : Math.max(0, Math.round(((value || 0) + step) * 100) / 100))}><Icon name="plus" /></button></div>)+ // Swipe on sets (v1.3.11, Settings → Workout): a set row swiped toward the start of the line is+ // removed with an Undo, toward the end copied below itself. Off, the row is the plain row it+ // was, and the Cards swipe works from it again. The row closes whenever its exercise's rows+ // change, the row is ticked, or a rest or hold starts: rows are keyed by index, so an open row+ // could otherwise end up showing another set.+ const swipeOn = !!(wc.swipeSets && onCopySetAt && onRemoveSetAt)+ const dismissHint = () => { if (useUI.getState().swipeHint) setUI({ swipeHint: null }) }+ const swipeRow = (s, i, row) => !swipeOn ? row : (+ <SwipeRow canDelete={editing || entry.sets.length > 1}+ onDelete={() => onRemoveSetAt(i)} onCopy={() => onCopySetAt(i)}+ onBlocked={() => useUI.getState().toast(t('Keep at least one set, champ'))}+ onStart={dismissHint}+ closeKey={[entry.sets.length, s.done ? 1 : 0, s.sides?.L?.done ? 1 : 0, s.sides?.R?.done ? 1 : 0, restEnds || 0, working?.endsAt || 0, S.active.cur].join('|')}+ flash={setFlash && setFlash.i === i ? setFlash.id : 0}+ peek={swipeHint && swipeHint.i === i ? swipeHint.id : 0}>+ {row}+ </SwipeRow>+ )return <>{/* Animations set to Small: a thumbnail beside the name instead of a strip above it, so thefirst set is on screen without scrolling; a tap brings the full animation back. */}@@ -613,6 +633,7 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSi{/* the header carries the same eff3/timed sizing as the rows, or the labels drift off theircolumns; over L/R rows it also has to skip the side badge that sits in front of the weight cell */}<div className={'sethead' + (col3 ? ' eff3' : '') + (timed ? ' timed' : '') + (perSide ? ' per-side' : '') + (wc.steppers ? '' : ' plain')}><span className="n-sp" /><span className="w-sp">{col1.hd}</span>{col2 && <span className="r-sp">{col2.hd}</span>}{col3 && <span className="eff-sp">{col3.hd}</span>}{timed && <span className="ck-sp" />}<span className="ck-sp" /></div>+ <span id={optsId} className="vh">{t('Options: copy, remove')}</span>{entry.sets.map((s, i) => {const warm = isWarmupRow(s)const warmBefore = i > 0 && isWarmupRow(entry.sets[i - 1])@@ -629,11 +650,11 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSiif (!rec) return nullreturn ' · ' + (rec.w > 0 ? tn('Record: {0} rep at {1}', 'Record: {0} reps at {1}', rec.r, fmtNum(rec.w) + ' ' + S.unit) : tn('Record: {0} rep', 'Record: {0} reps', rec.r))})()}</div>}- {perSide && !warm && isSideSet(s) ? (+ {swipeRow(s, i, perSide && !warm && isSideSet(s) ? (// Unilateral work set: the number sits beside a two-row L/R stack, each side logged// and ticked on its own (issue #60).<div ref={el => onSetRowRef?.(i, el)} className={'setrow-side' + (s.done ? ' done' : '')}>- <button type="button" className="n" aria-label={t('Set {0}', phaseNum)} title={t('More')} onClick={() => openSetMenu(s, i)}>{phaseNum}</button>+ <button type="button" className="n" aria-label={t('Set {0}', phaseNum)} aria-describedby={optsId} title={t('More')} onClick={() => openSetMenu(s, i)}>{phaseNum}</button><div className="side-rows">{sideRow(s, i, 'L', col1, col2, col3)}{sideExtras(s, i, 'L')}@@ -643,7 +664,7 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSi</div>) : (<div ref={el => onSetRowRef?.(i, el)} className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '') + (timed ? ' timed' : '')}>- <button type="button" className="n" aria-label={sideTagOf(s) ? t('Set {0} ({1})', setNumOf(s, i), sideTagOf(s)) : t('Set {0}', setNumOf(s, i))} title={t('More')} onClick={() => openSetMenu(s, i)}>{setNumOf(s, i)}</button>+ <button type="button" className="n" aria-label={sideTagOf(s) ? t('Set {0} ({1})', setNumOf(s, i), sideTagOf(s)) : t('Set {0}', setNumOf(s, i))} aria-describedby={optsId} title={t('More')} onClick={() => openSetMenu(s, i)}>{setNumOf(s, i)}</button>{/* Both words sit in the pill's one grid cell (::before/::after, hidden), so Left andRight are as wide as the longer of the two in every language and the inputsafter them line up (#322). */}@@ -657,7 +678,12 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSionClick={() => onStartTimed(i)}><Icon name="play" /></button>}<Check checked={s.done} onChange={() => onToggle(i)} /></div>- )}+ ))}+ {swipeHint && swipeHint.i === i && swipeOn && <div className="swhint">+ <button type="button" onClick={() => setUI({ swipeHint: null })}>+ <Icon name="swap" /><span>{t('Psst: swipe a set. Left deletes, right copies.')}</span><Icon name="xmark" />+ </button>+ </div>}{loadLine(String(i))}{/* Drop-sets and rest-pause bursts extend this same row — no long rest, no new set.A planned exercise arrives with these already filled in (applyIntensifierPlan);@@ -696,6 +722,95 @@ function ExerciseBlock({ entryIdx, compact, dense, editing, onToggle, onToggleSi</>}+/* ---------- swipe on sets: delete, undo, copy (v1.3.11) ---------- */+// The swipe, the set-number menu and the Undo on the toast all come through here, so a set is+// removed, put back and copied the same way whichever you used, and always through the store's+// normal update: the sync sees an ordinary edit (with its _rev/baseRev), never an old snapshot+// written back over newer state.+//+// Rows have no id of their own, so whatever points at a row by its index has to move with it:+// the running hold (its callback writes the seconds to a row) and the rest a set started+// (timer.forSet). Removing the set either one belongs to stops it first; Undo does not start it+// again. Rows above or below just shift.+let holdAt = null // { owner, idx, i }: the row a running hold will write to (startTimed)+let flashSeq = 0+// UI state written from here and from effects; a test that stubs the UI store without setState+// simply does not see it.+const setUI = patch => useUI.setState?.(patch)+const shiftRowRefs = (idx, from, by) => {+ if (holdAt && holdAt.idx === idx && holdAt.i >= from) holdAt = { ...holdAt, i: holdAt.i + by }+ const rest = useUI.getState().timer+ if (rest && rest.forIdx === idx && rest.forSet != null && rest.forSet >= from) setUI({ timer: { ...rest, forSet: rest.forSet + by } })+}+/** The number a set row shows: counted per phase (warm-ups and work sets each from 1), and a+ * timed per-side L/R pair as one set. */+export function setNumberAt(sets, i) {+ const s = sets[i]+ const warm = isWarmupRow(s)+ const phaseNum = sets.slice(0, i + 1).filter(x => isWarmupRow(x) === warm).length+ return s?.side ? Math.ceil(phaseNum / 2) : phaseNum+}+/** Removes set `i` of active entry `idx`, with an Undo on the toast. In a live session one set+ * always stays (removeRowAt); the editor of a saved workout may take them all. */+export function deleteActiveSet(idx, i, { editing = false } = {}) {+ const A = useStore.getState().S.active+ const e = A?.entries?.[idx]+ const row = e?.sets?.[i]+ if (!row) return false+ const ui = useUI.getState()+ if (!editing && e.sets.length <= 1) { ui.toast(t('Keep at least one set, champ')); return false }+ let stopped = false+ if (ui.work && holdAt && holdAt.idx === idx && holdAt.i === i) { holdAt = null; ui.stopWork(); stopped = true }+ const rest = ui.timer+ if (rest && rest.forIdx === idx && rest.forSet === i) { ui.stopRest(); stopped = !rest.ready || stopped }+ shiftRowRefs(idx, i + 1, -1)+ const n = setNumberAt(e.sets, i)+ const warm = isWarmupRow(row)+ const token = { activeId: A.id, idx, entryId: e.id, i, row: structuredClone(row) }+ useStore.getState().update(s => {+ const en = s.active?.entries?.[idx]+ if (!en) return+ if (editing) en.sets.splice(i, 1)+ else en.sets = removeRowAt(en.sets, i)+ }, true)+ const msg = warm ? t('Warm-up gone.') : stopped ? t('Set {0} gone. Its timer stopped too.', n) : t('Set {0} gone.', n)+ ui.toast(msg, { action: t('Undo'), onAction: () => undoDeleteSet(token) })+ return true+}+/** Puts a removed set back exactly as it was, at its old place in the same exercise. If the+ * exercise moved, it is found by its id; if it is gone, or the workout is, there is nothing to+ * put it back into. */+export function undoDeleteSet(token) {+ const A = useStore.getState().S.active+ const ui = useUI.getState()+ const at = !A || A.id !== token.activeId ? -1+ : A.entries[token.idx]?.id === token.entryId ? token.idx+ : A.entries.findIndex(en => en.id === token.entryId)+ if (at < 0) { ui.toast(t('Too late, that one’s gone')); return false }+ const i = Math.min(token.i, A.entries[at].sets.length)+ shiftRowRefs(at, i, 1)+ useStore.getState().update(s => {+ const en = s.active.entries[at]+ en.sets = insertRowAt(en.sets, i, token.row)+ }, true)+ setUI({ setFlash: { idx: at, i, id: ++flashSeq } })+ return true+}+/** "One more like this one": a copy of set `i` right below it (lib/history.js copyRowAt). */+export function copyActiveSet(idx, i) {+ const e = useStore.getState().S.active?.entries?.[idx]+ if (!e?.sets?.[i]) return false+ const { start, end } = copySpanAt(e.sets, i)+ shiftRowRefs(idx, end + 1, end - start + 1)+ useStore.getState().update(s => {+ const en = s.active?.entries?.[idx]+ if (en) en.sets = copyRowAt(en.sets, i)+ }, true)+ setUI({ setFlash: { idx, i: end + 1, id: ++flashSeq } })+ useUI.getState().toast(t('Copied. One more like that one.'))+ return true+}+/* ---------- active workout ---------- */export function removeActiveExercise(idx) {// Clear the work callback before indexes can shift. This also protects a confirmation sheet@@ -805,6 +920,47 @@ function ActiveWorkout() {useEffect(() => {progressHighWater.current = A.entries.map(e => e.sets.filter(s => s.done).length)}, [A.entries.length])+ // A removed set takes its tick with it (deleteActiveSet): the exercise's mark comes down to what+ // is ticked now, or ticking the next set would read as a re-check and start no rest. Only on the+ // way down; a set added or put back by Undo leaves the mark where it is.+ const setCounts = A.entries.map(e => e.sets.length)+ const lastCounts = useRef(setCounts)+ useEffect(() => {+ const was = lastCounts.current+ lastCounts.current = setCounts+ if (was.length !== setCounts.length) return+ setCounts.forEach((n, k) => {+ if (n < was[k]) progressHighWater.current[k] = Math.min(progressHighWater.current[k] || 0, A.entries[k].sets.filter(s => s.done).length)+ })+ }, [setCounts.join(',')])+ // The one-time swipe hint (v1.3.11): the first time the screen shows an unticked set with swiping+ // on, that row nudges toward delete and toward copy, with a chip under it saying so. Seen once+ // per person (S.hints, synced), not per device. In Cards only the exercise on screen qualifies.+ const hintSeen = !!(S.hints && S.hints.swipeSets)+ const hintTm = useRef(null)+ useEffect(() => {+ if (!wc.swipeSets || hintSeen || !A.entries.length) return+ const tm = setTimeout(() => {+ const A2 = useStore.getState().S.active+ if (!A2 || useStore.getState().S.hints?.swipeSets) return+ const c = Math.min(Math.max(A2.cur || 0, 0), A2.entries.length - 1)+ const shownUnit = unitOf(supersetUnits(A2.entries), c)+ const order = listMode ? [c, ...A2.entries.keys()] : shownUnit+ let at = null+ for (const k of order) {+ const j = A2.entries[k]?.sets.findIndex(x => !x.done) ?? -1+ if (j >= 0) { at = { idx: k, i: j }; break }+ }+ if (!at) return+ update(s => { s.hints = { ...(s.hints || {}), swipeSets: true } })+ const id = Date.now()+ setUI({ swipeHint: { ...at, id } })+ clearTimeout(hintTm.current)+ hintTm.current = setTimeout(() => { if (useUI.getState().swipeHint?.id === id) setUI({ swipeHint: null }) }, 6000)+ }, 600)+ return () => clearTimeout(tm)+ }, [wc.swipeSets, hintSeen, A.entries.length, cur, listMode])+ useEffect(() => () => { clearTimeout(hintTm.current); setUI({ swipeHint: null, setFlash: null }) }, [])useEffect(() => {const liveEntries = new Set(A.entries)for (const entry of exRefs.current.keys()) {@@ -941,10 +1097,8 @@ function ActiveWorkout() {const m = modeOf({ ...(e.target || {}), id: e.id })e.sets = insertWarmupRow(e.sets, m, e.target || {}, defaultIncrement(e.id, S.unit))})- const removeSetAt = (idx, i) => mutEntry(idx, e => {- if (editing) e.sets.splice(i, 1)- else e.sets = removeRowAt(e.sets, i)- })+ // 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 => {s.active.entries = pairAdjacent(s.active.entries, first, second)})@@ -1048,6 +1202,7 @@ function ActiveWorkout() {onRemoveSet: () => removeSet(idx),onAddWarmup: () => addWarmup(idx),onRemoveSetAt: i => removeSetAt(idx, i),+ onCopySetAt: i => copyActiveSet(idx, i),onStartTimed: i => startTimed(idx, i),onProgressionSettings: editing ? null : () => openProgressionSettings(idx),onRest: editing ? null : () => openExerciseRest(idx),@@ -1311,7 +1466,13 @@ function ActiveWorkout() {// the row is held to the end, ticked, or given a duration you typed yourself, and it never// 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)), (elapsed, { abandoned = false, chimed = false } = {}) => {+ // 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).+ const mine = holdAt?.owner === owner+ const i = mine ? holdAt.i : owner.i+ if (mine) holdAt = null// A hold a rest displaced (useUI.abandonWork: a set ticked on another row, or another// exercise) keeps its seconds and nothing else. It is not a finish: the row stays unticked// and starts no rest, because the rest that displaced the hold is already counting down —@@ -1327,6 +1488,8 @@ function ActiveWorkout() {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 })})+ // After startWork: a hold it displaced has already written its seconds to its own row.+ holdAt = { owner, idx, i }}// `quiet`: the hold that ticks this set has just ended with the chime and its buzz pattern@@ -1404,7 +1567,7 @@ function ActiveWorkout() {// still the rest you are in, held on purpose, and a re-check leaves it as it is.if (!progress.isNew) {const rest = useUI.getState().timer- if (!restBeforeWarmup && restOnRecheck({ timerRunning: !!(rest && !rest.ready), unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restAfter, idx)+ if (!restBeforeWarmup && restOnRecheck({ timerRunning: !!(rest && !rest.ready), unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restAfter, idx, { forSet: i })return}@@ -1416,7 +1579,7 @@ function ActiveWorkout() {const partner = sideOf(rows[i]) === 'L' && sideOf(rows[i + 1]) === 'R' ? rows[i + 1]: sideOf(rows[i]) === 'R' && sideOf(rows[i - 1]) === 'L' ? rows[i - 1] : nullif (m === 'time' && partner && !partner.done && restAfter > 0) {- startRest(Math.min(SWITCH_SIDES_SEC, restAfter), idx, { kind: 'switch' })+ startRest(Math.min(SWITCH_SIDES_SEC, restAfter), idx, { kind: 'switch', forSet: i })return}@@ -1425,17 +1588,17 @@ function ActiveWorkout() {// stopRest() first so a rest that belongs after this set replaces the one that was running.if (freshUnitDone) stopRest()if (!freshUnit || freshUnit.length <= 1) {- if (!restBeforeWarmup && restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restAfter, idx)+ if (!restBeforeWarmup && restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restAfter, idx, { forSet: i })return}const step = supersetFlowStep(fresh.entries, freshUnit, idx)if (!step) returnif (step.unitDone) {- if (nextUnit?.length && !restBeforeWarmup) startRest(restAfter, idx)+ 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)+ if (step.roundDone) startRest(restAfter, idx, { forSet: i })}}}diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsxindex e52af29cc..d5797081e 100644--- a/frontend/src/views/Workout.test.jsx+++ b/frontend/src/views/Workout.test.jsx@@ -273,11 +273,11 @@ describe('Workout set completion flow', () => {],})])await toggleSet(0)- expect(mocks.startRest).toHaveBeenLastCalledWith(45, expect.any(Number))+ expect(mocks.startRest).toHaveBeenLastCalledWith(45, expect.any(Number), { forSet: expect.any(Number) })await toggleSet(1)- expect(mocks.startRest).toHaveBeenLastCalledWith(150, expect.any(Number))+ expect(mocks.startRest).toHaveBeenLastCalledWith(150, expect.any(Number), { forSet: expect.any(Number) })await toggleSet(2)- expect(mocks.startRest).toHaveBeenLastCalledWith(150, expect.any(Number))+ expect(mocks.startRest).toHaveBeenLastCalledWith(150, expect.any(Number), { forSet: expect.any(Number) })expect(mocks.startRest).toHaveBeenCalledTimes(3)})@@ -286,7 +286,7 @@ describe('Workout set completion flow', () => {await toggleSet(0)expect(mocks.startRest).toHaveBeenCalledOnce()- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })expect(mocks.stopRest).not.toHaveBeenCalled()await unmount()@@ -308,7 +308,7 @@ describe('Workout set completion flow', () => {expect(mocks.S.active.entries[0].topW).toBe(60)expect(mocks.S.exWeights['plain-bench']).toBeUndefined() // written at the finish, not while tickingexpect(mocks.S.active.cur).toBe(0)- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })await pressNext()@@ -332,7 +332,7 @@ describe('Workout set completion flow', () => {await toggleSet(1)expect(mocks.S.active.cur).toBe(1)- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })await pressNext()@@ -427,7 +427,7 @@ describe('Workout set completion flow', () => {await rerender()await toggleSet(0)- expect(mocks.startRest).toHaveBeenCalledWith(90, 0)+ expect(mocks.startRest).toHaveBeenCalledWith(90, 0, { forSet: expect.any(Number) })})it('leaves a rest that is still counting down alone on a re-check', async () => {@@ -451,7 +451,7 @@ describe('Workout set completion flow', () => {await toggleSet(5)expect(mocks.S.active.cur).toBe(1)- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })})it('does not auto-select an unfinished superset after completing an ordinary exercise', async () => {@@ -467,7 +467,7 @@ describe('Workout set completion flow', () => {expect(mocks.S.active.cur).toBe(0)expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()expect(mocks.toast).toHaveBeenCalledWith('Hold logged')- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })})it('does not auto-select earlier unfinished work after completing an ordinary exercise', async () => {@@ -480,7 +480,7 @@ describe('Workout set completion flow', () => {expect(mocks.S.active.cur).toBe(1)expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })})it('leaves a completed ordinary exercise selected without declaring completion while work remains', async () => {@@ -493,7 +493,7 @@ describe('Workout set completion flow', () => {expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()expect(mocks.S.active.cur).toBe(0)- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })})it('shows workout completion only when no unfinished unit remains', async () => {@@ -1241,7 +1241,7 @@ describe('superset flow survives an exercise being removed mid-session', () => {// Partner closes the round (each still has a second set), which is what starts the rest.await toggleSet(2)- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })})})@@ -1485,7 +1485,7 @@ describe('workout list view', () => {expect(mocks.S.active.entries[0].sets[0].done).toBe(true)expect(mocks.S.active.cur).toBe(0)- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })})it('does not declare the workout complete after a set of a non-current exercise while sets remain', async () => {@@ -1500,7 +1500,7 @@ describe('workout list view', () => {expect(mocks.S.active.entries[1].sets[0].done).toBe(true)expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })})it('renders a superset as one grouped unit with its own unpair control', async () => {@@ -1616,7 +1616,7 @@ describe('workout compact view', () => {await toggleSet(0)expect(mocks.S.active.entries[0].sets[0].done).toBe(true)- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })})})@@ -1769,7 +1769,7 @@ describe('workout controls: the more menu and the set menu', () => {it('opens a per-set menu from the set number with drop, burst and remove', async () => {await mount([exercise('plain-bench', [false, false])])await act(async () => { container.querySelector('button[aria-label="Set 2"]').dispatchEvent(new dom.Event('click', { bubbles: true })) })- expect(menuItemsOf(lastMenu()).map(it => it.label)).toEqual(['Make it a warm-up set', 'Drop set', 'Rest-pause burst', 'Remove this set'])+ expect(menuItemsOf(lastMenu()).map(it => it.label)).toEqual(['Make it a warm-up set', 'Drop set', 'Rest-pause burst', 'Copy this set', 'Remove this set'])expect(item('Make it a warm-up set').icon).toBe('sunrise')await act(async () => { item('Drop set').onClick() })@@ -1838,7 +1838,7 @@ describe('effort rating auto-ends the set', () => {expect(mocks.S.active.entries[0].sets[0].rir).toBe(2)expect(mocks.S.active.entries[0].sets[0].done).toBe(true)- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })})it('does not re-toggle a set that is already done — a rating change leaves it done', async () => {@@ -1893,7 +1893,7 @@ describe('per-side effort completion', () => {await act(async () => { rightPick(scale === 'rir' ? 0 : 10) })set = mocks.S.active.entries[0].sets[0]expect(set.done).toBe(true)- expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))+ expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number), { forSet: expect.any(Number) })const calls = mocks.startRest.mock.calls.lengthawait act(async () => { rightPick(1) })expect(set.sides.R.done).toBe(true)