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.

Routine editor: swipe an exercise out with Undo (the sheet's Remove too); the long press still reorders, and SwipeToDelete goes

Duarte Santos50ddf85aa640
diff --git a/frontend/src/components/SwipeToDelete.jsx b/frontend/src/components/SwipeToDelete.jsx
deleted file mode 100644
index c9c636d31..000000000
--- a/frontend/src/components/SwipeToDelete.jsx
+++ /dev/null
@@ -1,122 +0,0 @@
-import { useEffect, useRef } from 'react'
-import { t } from '../lib/i18n.js'
-
-// Swipe-left-to-reveal-delete, same touch/mouse-drag shape Modals.jsx already uses for
-// swipe-to-dismiss (drag ref, transform during move, snap on release) — horizontal instead
-// of vertical, and it reveals a button rather than acting outright, since a swipe that goes
-// through by accident is a worse mistake than a sheet that closes by accident.
-//
-// touchmove has to be a real (non-passive) listener, not React's onTouchMove prop — the same
-// reason Modals.jsx attaches its own via addEventListener({ passive: false }) rather than the
-// JSX prop: React's synthetic touch handlers are passive, so preventDefault from inside one is
-// silently ignored, and on iOS Safari a touch that starts on a row gets claimed for page
-// scroll before a passive handler ever gets a say. Axis-locking matters just as much: this
-// only calls preventDefault once a touch has clearly gone more horizontal than vertical, so a
-// normal vertical scroll — or a long-press-then-drag reorder gesture elsewhere on the same
-// row (RoutineEdit's own drag-to-reorder) — is never hijacked; both start with the touch
-// essentially stationary or moving on the y axis, and this backs off the instant it can tell.
-// This deliberately does NOT set data-nodrag on the wrapper: that would opt every row out of
-// drag-to-reorder entirely (confirmed by RoutineEdit.drag.test.jsx failing when it was here)
-// rather than just out of this one gesture. A fast horizontal swipe cancels the reorder's
-// pending long-press before it ever fires (movement clears its slop threshold too soon), and
-// a genuine long-press-drag is vertical, so the axis lock below hands it back untouched —
-// the two are already mutually exclusive by shape, without needing to be forced apart.
-//
-// The row keeps its own opaque background rather than trusting whatever sits behind it in the
-// DOM (a `.card`'s fill, usually) — without it the red button peeks out at the row's edge even
-// at rest, since a transparent row lets an absolutely-positioned sibling show straight through.
-//
-// A swipe is a pointer gesture, so the keyboard needs its own way through. role, tabIndex and
-// onKeyDown (what tappable() hands a row) land on the row itself, so a row that was reachable
-// with Tab and opened with Enter or Space before it learned to swipe still is. The delete
-// button sits in the tab order right before its row but under it on screen, so focusing it
-// slides the row open the way a swipe would, and moving focus on closes it again: otherwise
-// Tab would land on a button nobody can see.
-//
-// The red button is transparent while the row is shut. Both are clipped by the same rounded
-// corners, and anti-aliasing at a curve lets some of what is underneath through: in dark mode a
-// red hairline traced every corner of every row at rest (QA 1.3.9). It shows as soon as the row
-// moves, and goes once the row has slid shut again.
-//
-// The button sits at the row's inline end: the right in a left-to-right language, the left in
-// Arabic. Offsets below are kept in that logical sense (negative = towards the start, opening)
-// and turned into pixels only in setX, so one gesture reads the same in both directions.
-const REVEAL = 76
-const endSide = () => (document.documentElement.dir === 'rtl' ? -1 : 1)
-export default function SwipeToDelete({ children, onDelete, deleteLabel, className, onClick, role, tabIndex, onKeyDown }) {
- const outerRef = useRef(null)
- const rowRef = useRef(null)
- const btnRef = useRef(null)
- const hideTimer = useRef(null)
- const drag = useRef({ startX: null, startY: null, delta: 0, open: false, axis: null })
- // Set while the row is open only because the delete button has focus, so a blur closes what
- // the focus opened and leaves a row the finger swiped open alone.
- const focusOpened = useRef(false)
-
- const setX = (x, animate) => {
- const el = rowRef.current
- if (!el) return
- el.style.transition = animate ? 'transform .18s ease-out' : 'none'
- el.style.transform = `translateX(${x * endSide()}px)`
- const btn = btnRef.current
- if (!btn) return
- window.clearTimeout(hideTimer.current)
- if (x !== 0) btn.style.opacity = '1'
- else if (!animate) btn.style.opacity = '0'
- else hideTimer.current = window.setTimeout(() => { if (!drag.current.open) btn.style.opacity = '0' }, 200)
- }
- useEffect(() => () => window.clearTimeout(hideTimer.current), [])
- const start = (x, y) => { drag.current = { startX: x, startY: y, delta: 0, open: drag.current.open, axis: null } }
- const move = (x, y, ev) => {
- const d = drag.current
- if (d.startX === null) return
- const dx = x - d.startX, dy = y - d.startY
- if (d.axis === null) {
- if (Math.abs(dx) < 8 && Math.abs(dy) < 8) return
- d.axis = Math.abs(dx) > Math.abs(dy) ? 'x' : 'y'
- }
- if (d.axis === 'y') return
- ev?.preventDefault?.()
- d.delta = dx * endSide()
- const base = d.open ? -REVEAL : 0
- setX(Math.max(-REVEAL - 12, Math.min(0, base + dx)), false)
- }
- const end = () => {
- const d = drag.current
- if (d.startX === null) return
- if (d.axis !== 'x') { d.startX = null; return }
- const traveled = (d.open ? -REVEAL : 0) + d.delta
- d.open = traveled < -REVEAL / 2
- setX(d.open ? -REVEAL : 0, true)
- d.startX = null
- }
-
- useEffect(() => {
- const el = outerRef.current
- if (!el) return
- const onTouchMove = e => move(e.touches[0].clientX, e.touches[0].clientY, e)
- el.addEventListener('touchmove', onTouchMove, { passive: false })
- return () => el.removeEventListener('touchmove', onTouchMove)
- }, [])
-
- return (
- <div ref={outerRef} style={{ position: 'relative', overflow: 'hidden', borderRadius: 'var(--r-card)' }}
- onTouchStart={e => { if (e.target.closest('button,input')) return; start(e.touches[0].clientX, e.touches[0].clientY) }}
- onTouchEnd={end}
- onMouseDown={e => { if (e.button !== 0 || e.target.closest('button,input')) return; start(e.clientX, e.clientY) }}
- onMouseMove={e => { if (drag.current.startX !== null && e.buttons === 1) move(e.clientX, e.clientY) }}
- onMouseUp={end}
- onMouseLeave={() => { if (drag.current.startX !== null) end() }}>
- <button ref={btnRef} className="swipe-del" aria-label={deleteLabel || t('Delete')}
- style={{ position: 'absolute', top: 0, bottom: 0, insetInlineEnd: 0, width: REVEAL, background: 'var(--red)', color: '#fff', fontSize: 12, fontWeight: 600, opacity: 0 }}
- onFocus={() => { if (drag.current.open) return; focusOpened.current = true; drag.current.open = true; setX(-REVEAL, true) }}
- onBlur={() => { if (!focusOpened.current) return; focusOpened.current = false; drag.current.open = false; setX(0, true) }}
- onClick={() => { setX(0, true); drag.current.open = false; onDelete() }}>{t('Delete')}</button>
- <div ref={rowRef} className={className} role={role} tabIndex={tabIndex} onKeyDown={onKeyDown}
- onClick={e => { if (drag.current.open) { e.stopPropagation(); setX(0, true); drag.current.open = false; return } onClick && onClick(e) }}
- style={{ background: 'var(--surface)', position: 'relative' }}>
- {children}
- </div>
- </div>
- )
-}
diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx
index 6280465fc..a0933dd3c 100644
--- a/frontend/src/views/RoutineEdit.jsx
+++ b/frontend/src/views/RoutineEdit.jsx
@@ -12,7 +12,9 @@ import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet } from '../she
import Icon from '../components/Icon.jsx'
import { glyphOf } from '../lib/glyphs.js'
import { Button, Row, SelectRow, Switch } from '../components/ui.jsx'
-import SwipeToDelete from '../components/SwipeToDelete.jsx'
+import SwipeRow from '../components/SwipeRow.jsx'
+import { workoutControls } from '../lib/workout-controls.js'
+import { tappable } from '../lib/use-sheet-keyboard.js'
import { copyRoutine, deleteRoutine, replaceSlotExercise } from '../lib/routines.js'
import { planPrintHTML, printPlan } from '../lib/plan-share.js'
import { MOBILE, printHtml } from '../lib/mobile.js'
@@ -312,7 +314,45 @@ function useRoutineReorder(routineIdentity, exercises, onDrop) {
window.clearTimeout(suppressTimerRef.current)
event.preventDefault(); event.stopPropagation()
}
- return { listRef, drag, onClickCapture }
+ // Whether a long press has picked a row up: the row's swipe stays out of the way while it has.
+ const lifted = () => !!gestureRef.current?.active
+ return { listRef, drag, onClickCapture, lifted }
+}
+
+/**
+ * Takes exercise `i` out of routine `routineId` with an Undo (v1.3.11: the row's swipe and the
+ * exercise sheet's Remove). While the routine's exercises are still what the removal left, Undo
+ * puts the list back as it was, superset links included (a partner left alone loses its link,
+ * cleanupSg). Once something else changed them, the exercise goes back in at its old place.
+ */
+export function removeRoutineExercise(routineId, i) {
+ const st = useStore.getState()
+ const routine = st.S.routines.find(x => x.id === routineId)
+ const slot = routine?.ex?.[i]
+ if (!slot) return false
+ const before = structuredClone(routine.ex)
+ st.update(s => {
+ const ex = s.routines.find(x => x.id === routineId)?.ex
+ if (!ex) return
+ ex.splice(i, 1); cleanupSg(ex)
+ })
+ const after = JSON.stringify(useStore.getState().S.routines.find(x => x.id === routineId)?.ex)
+ useUI.getState().toast(t('“{0}” left the routine.', exerciseNameText(exOr(slot.id))),
+ { action: t('Undo'), onAction: () => undoRemoveRoutineExercise({ routineId, i, before, after }) })
+ return true
+}
+export function undoRemoveRoutineExercise({ routineId, i, before, after }) {
+ if (!useStore.getState().S.routines.some(x => x.id === routineId)) {
+ useUI.getState().toast(t('Too late, that one’s gone'))
+ return false
+ }
+ useStore.getState().update(s => {
+ const routine = s.routines.find(x => x.id === routineId)
+ if (JSON.stringify(routine.ex) === after) { routine.ex = structuredClone(before); return }
+ routine.ex.splice(Math.min(i, routine.ex.length), 0, structuredClone(before[i]))
+ cleanupSg(routine.ex)
+ })
+ return true
}
export default function RoutineEdit() {
@@ -403,6 +443,7 @@ export default function RoutineEdit() {
const inSS = new Set(units.filter(u => u.length > 1).flat())
const profile = activeProfile(S)
const missingCount = profile ? r.ex.filter(e => !exAvailable(S, exOr(e.id))).length : 0
+ const swipe = workoutControls(S).swipeSets
return <div className="narrow">
<div className="hdr">
@@ -462,16 +503,12 @@ export default function RoutineEdit() {
const leavesUp = inSS.has(i) && !linkedPrev
const leavesDown = inSS.has(i) && r.ex[i + 1]?.sg !== e.sg
const isDragging = reorder.drag && i >= reorder.drag.first && i <= reorder.drag.last
- return <div key={i} data-routine-row data-ex-index={i}
- className={'routine-drag-row' + (isDragging ? ' is-dragging' : '')}
- style={isDragging ? { transform: `translate3d(0, ${reorder.drag.deltaY}px, 0)` } : undefined}>
- {unitFirst.has(i) && <div className="ss-label"><Icon name="link" />{t('Superset')}</div>}
- <SwipeToDelete className={'item' + (inSS.has(i) ? ' in-ss' : '')}
- deleteLabel={t('Remove from routine')}
- onDelete={() => edit(x => { x.splice(i, 1); cleanupSg(x) })}
- onClick={() => {
- exConfigSheet(ex, e, cfg => edit(x => { x[i] = { id: x[i].id, sg: x[i].sg, ...cfg } }), () => edit(x => { x.splice(i, 1); cleanupSg(x) }), r, null, () => replace(i))
- }}>
+ const removeHere = () => removeRoutineExercise(id, i)
+ // A keyboard button too (tappable): with the swipe's delete button gone from the tab order,
+ // Enter opens the exercise's sheet, and its Remove is the keyboard's way to take it out.
+ const item = <div className={'item' + (inSS.has(i) ? ' in-ss' : '')} {...tappable(() => {
+ exConfigSheet(ex, e, cfg => edit(x => { x[i] = { id: x[i].id, sg: x[i].sg, ...cfg } }), removeHere, r, null, () => replace(i))
+ })}>
{/* Shown on pointer devices only (index.css .routine-grip); the Move buttons and the
long press stay the way in for a keyboard and a finger. */}
<span className="routine-grip" data-drag-handle aria-hidden="true" title={t('Reorder exercises')}><Icon name="grip" /></span>
@@ -486,7 +523,19 @@ export default function RoutineEdit() {
<button className="iconbtn" aria-label={t('Move down')} title={leavesDown ? t('Move out of the superset') : t('Move down')} disabled={!moveRoutineEntry(r.ex, i, 1)} style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, 1) }}><Icon name="chevronDown" /></button>
</div>
</div>
- </SwipeToDelete>
+ </div>
+ return <div key={i} data-routine-row data-ex-index={i}
+ className={'routine-drag-row' + (isDragging ? ' is-dragging' : '')}
+ style={isDragging ? { transform: `translate3d(0, ${reorder.drag.deltaY}px, 0)` } : undefined}>
+ {unitFirst.has(i) && <div className="ss-label"><Icon name="link" />{t('Superset')}</div>}
+ {/* Swipe (v1.3.11, Settings → Swipe actions): toward the start takes the exercise out,
+ with an Undo; nothing on the other side. The long press still picks the row up to
+ reorder it (a press that has lifted keeps the swipe out), and the row's sheet keeps
+ Remove for a keyboard. Rows are keyed by index, so the row shuts when the count changes. */}
+ {swipe
+ ? <SwipeRow className="swrow-item" deleteLabel={t('Remove')} deleteIcon="minus" closeKey={r.ex.length}
+ canSwipe={() => !reorder.lifted()} onDelete={removeHere}>{item}</SwipeRow>
+ : item}
</div>
})}{reorder.drag && <div className="routine-drop-indicator" data-testid="routine-drop-indicator"
aria-hidden="true" style={{ top: `${reorder.drag.indicatorTop}px` }} />}</div> : <div className="empty"><div className="ico"><Icon name="dumbbell" /></div>{t('No exercises yet. Add your first one!')}</div>}
diff --git a/frontend/src/views/RoutineEdit.swipe.test.jsx b/frontend/src/views/RoutineEdit.swipe.test.jsx
new file mode 100644
index 000000000..7b89b44df
--- /dev/null
+++ b/frontend/src/views/RoutineEdit.swipe.test.jsx
@@ -0,0 +1,136 @@
+// @vitest-environment happy-dom
+// Swipe actions in the routine editor (v1.3.11): toward the start takes an exercise out, with an
+// Undo, and there is nothing on the other side. The long press still reorders, and a row it has
+// picked up does not swipe. The exercise's sheet keeps Remove, with the same Undo.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { MemoryRouter, Route, Routes } from 'react-router-dom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const sheets = vi.hoisted(() => ({
+ exConfigSheet: vi.fn(), exercisePicker: vi.fn(), glyphPicker: vi.fn(), confirmSheet: vi.fn(),
+}))
+vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), beacon: vi.fn(), appBase: () => '/' }))
+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))
+vi.mock('../sheets.jsx', () => sheets)
+vi.mock('../components/Media.jsx', () => ({ Thumb: ({ ex }) => <span data-thumb={ex.id} /> }))
+vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
+
+import RoutineEdit, { ROUTINE_LONG_PRESS_MS, removeRoutineExercise } from './RoutineEdit.jsx'
+import { DEF, useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { closeOpenRow } from '../lib/use-swipe-row.js'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+const clone = value => JSON.parse(JSON.stringify(value))
+const configured = (id, extra = {}) => ({ id, mode: 'reps', sets: 3, reps: 5, weight: 0, ...extra })
+let root, host, widthSpy
+
+function mount(entries, wc) {
+ const S = clone(DEF)
+ S.routines = [{ id: 'r1', name: 'Swipe routine', emoji: 'dumbbell', prog: 'linear', ex: entries }]
+ if (wc) S.wc = { ...S.wc, ...wc }
+ useStore.setState({ S, user: null })
+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
+ act(() => root.render(<MemoryRouter initialEntries={['/plan/r/r1']}><Routes><Route path="/plan/r/:id" element={<RoutineEdit />} /></Routes></MemoryRouter>))
+}
+const ex = () => useStore.getState().S.routines[0].ex
+const swrows = () => [...host.querySelectorAll('.swrow')]
+function pointer(target, type, x, y = 300) {
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ for (const [key, value] of Object.entries({ pointerId: 7, pointerType: 'touch', isPrimary: true, button: 0, clientX: x, clientY: y })) {
+ Object.defineProperty(event, key, { configurable: true, value })
+ }
+ act(() => { target.dispatchEvent(event) })
+}
+const click = target => act(() => { target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })) })
+function swipe(target, x0, x1) {
+ pointer(target, 'pointerdown', x0)
+ pointer(target, 'pointermove', (x0 + x1) / 2)
+ pointer(target, 'pointermove', x1)
+ pointer(target, 'pointerup', x1)
+ click(target)
+ act(() => vi.advanceTimersByTime(800))
+}
+const undo = () => act(() => useUI.getState().runToastAction())
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ Object.values(sheets).forEach(mock => mock.mockReset())
+ document.documentElement.dir = 'ltr'
+ useUI.setState({ sheets: [], toastMsg: '', toastAction: null })
+ widthSpy = vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(360)
+})
+afterEach(() => {
+ closeOpenRow(true)
+ act(() => root.unmount()); host.remove()
+ widthSpy.mockRestore()
+ vi.clearAllTimers(); vi.useRealTimers()
+})
+
+describe('swiping an exercise out of a routine', () => {
+ it('is remove-only: one pane, out of reach while shut, and a swipe toward the end does nothing', () => {
+ mount([configured('1001'), configured('1002')])
+ expect(swrows()).toHaveLength(2)
+ expect(host.querySelector('.swpane.cp')).toBeNull()
+ const pane = swrows()[0].querySelector('.swpane.del')
+ expect(pane.textContent).toBe('Remove')
+ expect(pane.getAttribute('aria-hidden')).toBe('true')
+ expect(pane.querySelector('button').tabIndex).toBe(-1)
+ swipe(swrows()[0].querySelector('.item'), 60, 330)
+ expect(ex().map(e => e.id)).toEqual(['1001', '1002'])
+ expect(swrows()[0].querySelector('.swfront').style.transform).toBe('')
+ })
+
+ it('a long swipe toward the start removes, and Undo brings back the superset link too', () => {
+ const entries = [configured('1001', { sg: 'g1' }), configured('1002', { sg: 'g1' }), configured('1003')]
+ mount(clone(entries))
+ swipe(swrows()[1].querySelector('.item'), 330, 60)
+ expect(ex().map(e => e.id)).toEqual(['1001', '1003'])
+ expect(ex()[0].sg).toBeUndefined() // a lone partner loses its link
+ expect(useUI.getState().toastMsg).toMatch(/” left the routine\.$/)
+ undo()
+ expect(ex()).toEqual(entries)
+ })
+
+ it('Undo after another edit puts the exercise back at its old place', () => {
+ mount([configured('1001'), configured('1002'), configured('1003')])
+ act(() => { removeRoutineExercise('r1', 1) })
+ const pending = useUI.getState().toastAction
+ act(() => useStore.getState().update(s => { s.routines[0].ex.push(configured('1004')) }))
+ act(() => pending.run())
+ expect(ex().map(e => e.id)).toEqual(['1001', '1002', '1003', '1004'])
+ })
+
+ it('the row stays a keyboard button, and the sheet’s Remove has the same Undo', () => {
+ mount([configured('1001'), configured('1002')])
+ const item = swrows()[1].querySelector('.item')
+ expect(item.getAttribute('role')).toBe('button')
+ act(() => { item.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) })
+ expect(sheets.exConfigSheet).toHaveBeenCalledOnce()
+ const onDelete = sheets.exConfigSheet.mock.calls[0][3]
+ act(() => onDelete())
+ expect(ex().map(e => e.id)).toEqual(['1001'])
+ undo()
+ expect(ex().map(e => e.id)).toEqual(['1001', '1002'])
+ })
+
+ it('a row the long press has picked up does not swipe', () => {
+ mount([configured('1001'), configured('1002')])
+ const item = swrows()[0].querySelector('.item')
+ pointer(item, 'pointerdown', 200)
+ act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
+ expect(host.querySelector('.is-dragging')).toBeTruthy()
+ pointer(item, 'pointermove', 60)
+ expect(swrows()[0].classList.contains('go-del')).toBe(false)
+ pointer(item, 'pointerup', 60)
+ act(() => vi.advanceTimersByTime(800))
+ expect(ex().map(e => e.id)).toEqual(['1001', '1002'])
+ })
+
+ it('is the plain row with the setting off', () => {
+ mount([configured('1001')], { swipeSets: false })
+ expect(swrows()).toHaveLength(0)
+ expect(host.querySelectorAll('[data-routine-row] .item')).toHaveLength(1)
+ })
+})