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.

Workout: Space or Enter ticks the next set and the arrow keys switch exercise, for a keyboard or a USB button (#133)

Duarte Santos6181563796ee
diff --git a/frontend/src/lib/workout-keys.js b/frontend/src/lib/workout-keys.js
new file mode 100644
index 000000000..4c452ea5a
--- /dev/null
+++ b/frontend/src/lib/workout-keys.js
@@ -0,0 +1,68 @@
+// Hardware keys on the workout screen (issue #133). A keyboard, or a big USB button that types
+// a key, drives the session on a screen nobody wants to touch mid-set: a Raspberry Pi on the
+// gym wall, a laptop on the bench. Space or Enter ticks the next set; ← and → go to the previous
+// or next exercise. Only the decisions live here; views/Workout.jsx listens and acts on them.
+import { supersetUnits, unitOf } from './history.js'
+import { nextUnfinishedUnit } from './supersetFlow.js'
+import { isSideSet } from './workout-model.js'
+
+// Where a key belongs to the element rather than to the workout: every text field (the arrows
+// move the caret there), and the controls that use the arrows themselves.
+const OWNS_KEYS = 'input,textarea,select,[contenteditable=""],[contenteditable="true"],[role="textbox"],[role="slider"],[role="spinbutton"]'
+// What Space and Enter press when focus is on it.
+const CONTROL = 'button,a[href],summary,[role="button"],[role="checkbox"],[role="switch"],[role="menuitem"],[role="tab"],[role="option"]'
+
+/**
+ * What a key press means on the workout screen: 'tick', 'prev', 'next', or null when it is not
+ * one of these keys, or not the workout's to take.
+ *
+ * `tabbed` says whether focus reached its element with Tab. Someone who tabbed to a button and
+ * presses Space or Enter means that button. A click, though, also leaves focus on the button it
+ * pressed (Chrome, Firefox), and a USB button that sends Space must not press "Next" again just
+ * because the mouse was the last thing to use it — so without Tab, Space and Enter tick.
+ * Modifier combinations are left alone: they are the browser's and the system's shortcuts.
+ */
+export function workoutKeyAction(event, { tabbed = false } = {}) {
+ if (!event || event.defaultPrevented || event.repeat || event.isComposing) return null
+ if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return null
+ const target = event.target
+ const within = selector => !!(target && typeof target.closest === 'function' && target.closest(selector))
+ if (target?.isContentEditable || within(OWNS_KEYS)) return null
+ switch (event.key) {
+ case ' ':
+ case 'Spacebar':
+ case 'Enter':
+ return tabbed && within(CONTROL) ? null : 'tick'
+ case 'ArrowLeft': return 'prev'
+ case 'ArrowRight': return 'next'
+ default: return null
+ }
+}
+
+/**
+ * The set a 'tick' is for: `{ idx, i, side?, current }` (entry index, set index, 'L' or 'R' for
+ * a unilateral row, and whether it belongs to the exercise marked current), or null when
+ * nothing is left to tick.
+ *
+ * The exercise marked current comes first. In a superset that is the member whose turn it is,
+ * followed by the rest of its group. After that comes the next exercise with work left, the
+ * same one the superset and finish flow would reach (nextUnfinishedUnit, which wraps round to
+ * one skipped earlier). A unilateral set is ticked a side at a time, left first.
+ */
+export function nextOpenSet(entries, cur) {
+ if (!Array.isArray(entries) || !entries.length) return null
+ const at = Number.isInteger(cur) ? Math.min(Math.max(cur, 0), entries.length - 1) : 0
+ const units = supersetUnits(entries)
+ const unit = unitOf(units, at)
+ const pos = Math.max(0, unit.indexOf(at))
+ const order = [...unit.slice(pos), ...unit.slice(0, pos), ...(nextUnfinishedUnit(entries, units, at) || [])]
+ for (const idx of order) {
+ const sets = Array.isArray(entries[idx]?.sets) ? entries[idx].sets : []
+ const i = sets.findIndex(s => !s?.done)
+ if (i < 0) continue
+ const set = sets[i]
+ const current = unit.includes(idx)
+ return isSideSet(set) ? { idx, i, side: set.sides.L.done ? 'R' : 'L', current } : { idx, i, current }
+ }
+ return null
+}
diff --git a/frontend/src/lib/workout-keys.test.js b/frontend/src/lib/workout-keys.test.js
new file mode 100644
index 000000000..8efea9bae
--- /dev/null
+++ b/frontend/src/lib/workout-keys.test.js
@@ -0,0 +1,107 @@
+// @vitest-environment happy-dom
+import { describe, expect, it } from 'vitest'
+import { nextOpenSet, workoutKeyAction } from './workout-keys.js'
+import { makeSideSet } from './workout-model.js'
+
+const key = (k, extra = {}) => ({ key: k, target: document.body, ...extra })
+const el = html => {
+ const host = document.createElement('div')
+ host.innerHTML = html
+ document.body.appendChild(host)
+ return host.firstElementChild
+}
+
+describe('workoutKeyAction (issue #133)', () => {
+ it('Space and Enter tick, the arrows switch exercise', () => {
+ expect(workoutKeyAction(key(' '))).toBe('tick')
+ expect(workoutKeyAction(key('Spacebar'))).toBe('tick')
+ expect(workoutKeyAction(key('Enter'))).toBe('tick')
+ expect(workoutKeyAction(key('ArrowLeft'))).toBe('prev')
+ expect(workoutKeyAction(key('ArrowRight'))).toBe('next')
+ })
+
+ it('leaves every other key alone, the vertical arrows included (they scroll a list)', () => {
+ for (const k of ['a', 'Escape', 'Tab', 'ArrowUp', 'ArrowDown', 'Backspace']) expect(workoutKeyAction(key(k))).toBeNull()
+ })
+
+ it('never takes a key typed into a field', () => {
+ for (const html of ['<input>', '<textarea></textarea>', '<select></select>', '<div contenteditable="true"></div>', '<div role="slider"></div>']) {
+ const target = el(html)
+ for (const k of [' ', 'Enter', 'ArrowLeft', 'ArrowRight']) expect(workoutKeyAction(key(k, { target })), html + ' ' + k).toBeNull()
+ }
+ })
+
+ it('leaves browser and system shortcuts alone', () => {
+ for (const mod of ['altKey', 'ctrlKey', 'metaKey', 'shiftKey']) {
+ expect(workoutKeyAction(key(' ', { [mod]: true }))).toBeNull()
+ expect(workoutKeyAction(key('ArrowRight', { [mod]: true }))).toBeNull()
+ }
+ })
+
+ it('ignores a held key, a key someone else already handled, and IME composition', () => {
+ expect(workoutKeyAction(key(' ', { repeat: true }))).toBeNull()
+ expect(workoutKeyAction(key(' ', { defaultPrevented: true }))).toBeNull()
+ expect(workoutKeyAction(key('Enter', { isComposing: true }))).toBeNull()
+ })
+
+ it('a button someone tabbed to keeps Space and Enter for itself', () => {
+ const target = el('<button>Finish</button>')
+ expect(workoutKeyAction(key(' ', { target }), { tabbed: true })).toBeNull()
+ expect(workoutKeyAction(key('Enter', { target }), { tabbed: true })).toBeNull()
+ // the arrows mean nothing to a button, so they still switch exercise
+ expect(workoutKeyAction(key('ArrowRight', { target }), { tabbed: true })).toBe('next')
+ })
+
+ it('a button that only has focus because it was clicked does not swallow the next tick', () => {
+ const target = el('<button>Next</button>')
+ expect(workoutKeyAction(key(' ', { target }), { tabbed: false })).toBe('tick')
+ const check = el('<button role="checkbox"></button>')
+ expect(workoutKeyAction(key('Enter', { target: check }), { tabbed: false })).toBe('tick')
+ })
+
+ it('tabbing onto plain page content still ticks', () => {
+ expect(workoutKeyAction(key(' ', { target: el('<div>Bench press</div>') }), { tabbed: true })).toBe('tick')
+ })
+})
+
+const ex = (done, extra = {}) => ({ id: 'x', sets: done.map(d => ({ w: 60, r: 5, done: d })), ...extra })
+
+describe('nextOpenSet', () => {
+ it('is the first open set of the current exercise', () => {
+ expect(nextOpenSet([ex([true, false, false]), ex([false])], 0)).toEqual({ idx: 0, i: 1, current: true })
+ })
+
+ it('moves on to the next exercise with work left once the current one is finished', () => {
+ expect(nextOpenSet([ex([true]), ex([true]), ex([false, false])], 0)).toEqual({ idx: 2, i: 0, current: false })
+ })
+
+ it('wraps round to an exercise skipped earlier', () => {
+ expect(nextOpenSet([ex([false]), ex([true]), ex([true])], 2)).toEqual({ idx: 0, i: 0, current: false })
+ })
+
+ it('is null when every set is done, or there is nothing to tick', () => {
+ expect(nextOpenSet([ex([true]), ex([true, true])], 1)).toBeNull()
+ expect(nextOpenSet([], 0)).toBeNull()
+ expect(nextOpenSet(undefined, 0)).toBeNull()
+ })
+
+ it('in a superset, the member whose turn it is, then its partner', () => {
+ const entries = [ex([true, false], { sg: 'a' }), ex([true, false], { sg: 'a' }), ex([false])]
+ expect(nextOpenSet(entries, 1)).toEqual({ idx: 1, i: 1, current: true })
+ entries[1].sets[1].done = true
+ expect(nextOpenSet(entries, 1)).toEqual({ idx: 0, i: 1, current: true })
+ })
+
+ it('a unilateral set is ticked a side at a time, left first', () => {
+ const row = makeSideSet({ w: 20, r: 20 })
+ const entries = [{ id: 'x', sets: [row] }]
+ expect(nextOpenSet(entries, 0)).toEqual({ idx: 0, i: 0, side: 'L', current: true })
+ row.sides.L.done = true
+ expect(nextOpenSet(entries, 0)).toEqual({ idx: 0, i: 0, side: 'R', current: true })
+ })
+
+ it('reads a missing or out-of-range current exercise as the nearest one', () => {
+ expect(nextOpenSet([ex([false]), ex([false])], undefined)).toEqual({ idx: 0, i: 0, current: true })
+ expect(nextOpenSet([ex([true]), ex([false])], 9)).toEqual({ idx: 1, i: 0, current: true })
+ })
+})
diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx
index b8a9c365c..228a11c1e 100644
--- a/frontend/src/views/Workout.jsx
+++ b/frontend/src/views/Workout.jsx
@@ -22,6 +22,7 @@ import { buildPlannedEntry, plannedConfigOf } from '../lib/session-start.js'
import { glyphOf } from '../lib/glyphs.js'
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps, isSideSet, makeSideSet, setSideField, toggleSide, addSideDrop, removeSideDropAt, setSideDropAt, addSideCluster, removeSideClusterAt, setSideClusterAt } from '../lib/workout-model.js'
import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from '../lib/active-workout-order.js'
+import { nextOpenSet, workoutKeyAction } from '../lib/workout-keys.js'
import { MUSCLE_NAME } from '../lib/muscles.js'
const SWIPE_MIN_DISTANCE = 48
@@ -983,6 +984,64 @@ function ActiveWorkout() {
}
}
+ // Hardware keys (issue #133, lib/workout-keys.js): Space or Enter ticks the next set, ← and →
+ // switch exercise. The listener is added once and calls the handler of the latest render, so
+ // toggle() and navigateUnit() always see the session as it is now.
+ const tabbed = useRef(false)
+ const onKey = useRef(null)
+ // In the list the "current" exercise can be off screen. A key that moves it brings it into
+ // view the way opening the list does; ticking and tapping never scroll it (see above).
+ const showCurrent = () => {
+ if (!listMode) return
+ const scroll = () => {
+ const el = listRef.current?.querySelector('.wl-unit.cur')
+ if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ block: 'start' })
+ }
+ // After the render that moves the marker, as the effect above waits for its frame.
+ if (window.requestAnimationFrame) window.requestAnimationFrame(scroll)
+ else window.setTimeout(scroll, 0)
+ }
+ onKey.current = event => {
+ // A sheet on top owns the keyboard (Escape closes it, Enter confirms in it).
+ if (useUI.getState().sheets.length) return false
+ const action = workoutKeyAction(event, { tabbed: tabbed.current })
+ if (!action) return false
+ event.preventDefault()
+ if (action !== 'tick') { navigateUnit(action === 'next' ? 1 : -1); showCurrent(); return true }
+ // A hold being timed: the key is its "Done", which logs what was actually held.
+ if (useUI.getState().work) { useUI.getState().finishWorkEarly(); return true }
+ const fresh = useStore.getState().S.active
+ const next = nextOpenSet(fresh?.entries, fresh?.cur)
+ if (!next) return true
+ // The exercise on screen is finished: this press brings up the next one, and the one after
+ // ticks its set. A key never logs a set for an exercise that was not in front of you.
+ if (!next.current) { focusUnit(next.idx); showCurrent(); return true }
+ // A timed set is started rather than ticked, as its play button does; the timer ticks it.
+ if (!next.side && modeAt(next.idx) === 'time') startTimed(next.idx, next.i)
+ else toggle(next.idx, next.i, next.side)
+ return true
+ }
+ useEffect(() => {
+ // A Space that ticked must not also press the button a click left focus on. Preventing the
+ // keydown is enough for Chrome; Firefox presses a button on the keyup, so that goes too.
+ let spaceTaken = false
+ const down = event => {
+ if (event.key === 'Tab') { tabbed.current = true; return }
+ const taken = onKey.current?.(event) === true
+ if (event.key === ' ') spaceTaken = taken
+ }
+ const up = event => { if (event.key === ' ' && spaceTaken) { spaceTaken = false; event.preventDefault() } }
+ const pointer = () => { tabbed.current = false }
+ document.addEventListener('keydown', down)
+ document.addEventListener('keyup', up)
+ document.addEventListener('pointerdown', pointer, true)
+ return () => {
+ document.removeEventListener('keydown', down)
+ document.removeEventListener('keyup', up)
+ document.removeEventListener('pointerdown', pointer, true)
+ }
+ }, [])
+
// Live-presence heartbeat so the admin dashboard can show who's training now. Signed-in only —
// guests have no server session. Reads fresh state each tick so progress stays current.
useEffect(() => {
diff --git a/frontend/src/views/Workout.keys.test.jsx b/frontend/src/views/Workout.keys.test.jsx
new file mode 100644
index 000000000..8b9e269ef
--- /dev/null
+++ b/frontend/src/views/Workout.keys.test.jsx
@@ -0,0 +1,153 @@
+// @vitest-environment happy-dom
+// Hardware keys on the workout screen (issue #133), against the real store and timers: what a
+// key press does to the session, not only what lib/workout-keys.js decides.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { MemoryRouter } from 'react-router-dom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Workout from './Workout.jsx'
+import { DEF, useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+
+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), unlock: vi.fn() }))
+vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), appBase: () => '/' }))
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+const clone = value => JSON.parse(JSON.stringify(value))
+const entry = (id, done, extra = {}) => ({
+ id,
+ target: { sets: done.length, reps: 5, weight: 60 },
+ sets: done.map(d => ({ w: 60, r: 5, done: d })),
+ ...extra,
+})
+
+let root
+let container
+
+function renderWorkout(entries, cur = 0, extra = {}) {
+ const S = clone(DEF)
+ S.active = { id: 'keys-test', d: '2026-09-23', start: Date.now(), routineId: null, name: 'Keys', bw: null, cur, entries, ...extra }
+ useStore.setState({ S, user: null })
+ container = document.createElement('div')
+ document.body.appendChild(container)
+ root = createRoot(container)
+ act(() => root.render(<MemoryRouter><Workout /></MemoryRouter>))
+}
+
+const press = (key, target = document.body) => {
+ const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })
+ act(() => { target.dispatchEvent(event) })
+ return event
+}
+const active = () => useStore.getState().S.active
+const doneOf = idx => active().entries[idx].sets.map(s => s.done)
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ localStorage.clear()
+ useUI.setState({ sheets: [], toastMsg: '', timer: null, work: null })
+ root = null
+ container = null
+})
+
+afterEach(() => {
+ if (root) act(() => root.unmount())
+ if (container) container.remove()
+ useUI.getState().stopRest()
+ useUI.getState().stopWork()
+ vi.clearAllTimers()
+ vi.useRealTimers()
+})
+
+describe('workout keys (issue #133)', () => {
+ it('Space ticks the next open set of the current exercise and starts its rest', () => {
+ renderWorkout([entry('1001', [true, false, false]), entry('1002', [false])])
+ const event = press(' ')
+ expect(event.defaultPrevented).toBe(true) // the page does not scroll as well
+ expect(doneOf(0)).toEqual([true, true, false])
+ expect(useUI.getState().timer).not.toBeNull()
+ press('Enter')
+ expect(doneOf(0)).toEqual([true, true, true])
+ })
+
+ it('once the exercise on screen is finished, a press brings up the next one and the next press ticks it', () => {
+ renderWorkout([entry('1001', [true]), entry('1002', [false, false])])
+ press(' ')
+ expect(active().cur).toBe(1)
+ expect(doneOf(1)).toEqual([false, false])
+ press(' ')
+ expect(doneOf(1)).toEqual([true, false])
+ })
+
+ it('the arrows switch exercise', () => {
+ renderWorkout([entry('1001', [false]), entry('1002', [false]), entry('1003', [false])])
+ press('ArrowRight')
+ expect(active().cur).toBe(1)
+ press('ArrowRight')
+ expect(active().cur).toBe(2)
+ press('ArrowRight')
+ expect(active().cur).toBe(2)
+ press('ArrowLeft')
+ expect(active().cur).toBe(1)
+ expect(doneOf(0).concat(doneOf(1), doneOf(2))).toEqual([false, false, false])
+ })
+
+ it('in the list, an arrow that moves the current exercise brings it into view', () => {
+ const scrolled = []
+ const original = Element.prototype.scrollIntoView
+ Element.prototype.scrollIntoView = function () { scrolled.push(this) }
+ try {
+ renderWorkout([entry('1001', [false]), entry('1002', [false])], 0, { workoutView: 'list' })
+ act(() => { vi.advanceTimersByTime(100) })
+ scrolled.length = 0
+ press('ArrowRight')
+ act(() => { vi.advanceTimersByTime(100) })
+ expect(active().cur).toBe(1)
+ expect(scrolled).toHaveLength(1)
+ expect(scrolled[0].classList.contains('cur')).toBe(true)
+ expect(scrolled[0].getAttribute('data-exidx')).toBe('1')
+ } finally {
+ Element.prototype.scrollIntoView = original
+ }
+ })
+
+ it('keys typed into a set\'s field stay in the field', () => {
+ renderWorkout([entry('1001', [false, false]), entry('1002', [false])])
+ const input = container.querySelector('.setrow input')
+ expect(input).toBeTruthy()
+ input.focus()
+ for (const key of [' ', 'Enter', 'ArrowRight']) expect(press(key, input).defaultPrevented).toBe(false)
+ expect(doneOf(0)).toEqual([false, false])
+ expect(active().cur).toBe(0)
+ })
+
+ it('does nothing while a sheet is open on top', () => {
+ renderWorkout([entry('1001', [false]), entry('1002', [false])])
+ useUI.getState().openSheet(() => null)
+ press(' ')
+ press('ArrowRight')
+ expect(doneOf(0)).toEqual([false])
+ expect(active().cur).toBe(0)
+ })
+
+ it('a timed set is started rather than ticked, and the next press is its Done', () => {
+ const plank = { id: '1001', target: { mode: 'time', sets: 1, sec: 45 }, sets: [{ sec: 45, w: 0, done: false }] }
+ renderWorkout([plank])
+ press(' ')
+ expect(useUI.getState().work).not.toBeNull()
+ expect(doneOf(0)).toEqual([false])
+ act(() => { vi.advanceTimersByTime(10_000) })
+ press(' ')
+ expect(useUI.getState().work).toBeNull()
+ expect(doneOf(0)).toEqual([true])
+ expect(active().entries[0].sets[0].sec).toBe(10)
+ })
+
+ it('stops listening when the workout screen goes away', () => {
+ renderWorkout([entry('1001', [false])])
+ act(() => root.unmount())
+ root = null
+ press(' ')
+ expect(doneOf(0)).toEqual([false])
+ })
+})