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
feat: add cancellable swipe previews for workout cards
Space-Hermesa60eda5b16a5
diff --git a/frontend/src/components/SwipeCards.jsx b/frontend/src/components/SwipeCards.jsxnew file mode 100644index 000000000..b6d930683--- /dev/null+++ b/frontend/src/components/SwipeCards.jsx@@ -0,0 +1,124 @@+import { useEffect, useLayoutEffect, useRef, useState } from 'react'++const IGNORED_TARGETS = 'button,input,textarea,select,a,[role="button"],[role="checkbox"],[role="switch"],[role="slider"],[contenteditable="true"],.exmedia,[data-swipe-ignore]'+const AXIS_SLOP = 8+const AXIS_RATIO = 1.5+const COMMIT_DISTANCE = 70+const GAP = 12+const DURATION = 200++export default function SwipeCards({ children, renderPreview, onNavigate, index, count, revision, timerKey, workKey }) {+ const surface = useRef(null)+ const card = useRef(null)+ const preview = useRef(null)+ const gesture = useRef(null)+ const pending = useRef(null)+ const latest = useRef({ revision, timerKey, workKey })+ const [direction, setDirection] = useState(null)+ latest.current = { revision, timerKey, workKey }++ const paint = (offset, animate = false, toward = gesture.current?.direction) => {+ if (card.current) {+ card.current.style.transition = animate ? `transform ${DURATION}ms ease-out` : 'none'+ card.current.style.transform = `translateX(${offset}px)`+ }+ if (preview.current && toward) {+ preview.current.style.transition = animate ? `transform ${DURATION}ms ease-out` : 'none'+ const start = toward > 0 ? '100% + ' : '-100% - '+ preview.current.style.transform = `translateX(calc(${start}${GAP}px + ${offset}px))`+ }+ }++ const reset = () => {+ clearTimeout(pending.current)+ pending.current = null+ gesture.current = null+ setDirection(null)+ for (const node of [card.current, preview.current]) {+ node?.style.removeProperty('transform')+ node?.style.removeProperty('transition')+ }+ }++ useEffect(() => {+ reset()+ return () => clearTimeout(pending.current)+ }, [revision, timerKey, workKey, index, count])++ useLayoutEffect(() => {+ if (gesture.current) paint(gesture.current.offset, false, direction)+ }, [direction])++ const onPointerDown = event => {+ if (pending.current || gesture.current) return+ if (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen') return+ if (event.target.closest?.(IGNORED_TARGETS)) return+ gesture.current = {+ id: event.pointerId,+ x: event.clientX,+ y: event.clientY,+ offset: 0,+ direction: null,+ revision,+ timerKey,+ workKey,+ }+ }++ const onPointerMove = event => {+ const active = gesture.current+ if (!active || active.id !== event.pointerId) return+ const dx = event.clientX - active.x+ const dy = event.clientY - active.y+ if (!active.direction) {+ if (Math.max(Math.abs(dx), Math.abs(dy)) < AXIS_SLOP) return+ if (Math.abs(dx) <= Math.abs(dy) * AXIS_RATIO) {+ gesture.current = null+ return+ }+ event.currentTarget.setPointerCapture?.(event.pointerId)+ }++ const nextDirection = dx < 0 ? 1 : -1+ const available = index + nextDirection >= 0 && index + nextDirection < count+ active.direction = nextDirection+ active.offset = available ? dx : dx * 0.35+ setDirection(available ? nextDirection : null)+ paint(active.offset, false, nextDirection)+ }++ const finish = (event, cancelled = false) => {+ const active = gesture.current+ if (!active || active.id !== event.pointerId) return+ const dx = event.clientX - active.x+ const dy = event.clientY - active.y+ const available = index + active.direction >= 0 && index + active.direction < count+ const commit = !cancelled && active.direction != null && available && Math.abs(dx) >= COMMIT_DISTANCE && Math.abs(dx) > Math.abs(dy) * AXIS_RATIO+ const reducedMotion = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches+ const width = surface.current?.getBoundingClientRect().width || 360+ const stillCurrent = () => {+ const current = latest.current+ return current.revision === active.revision && current.timerKey === active.timerKey && current.workKey === active.workKey+ }+ const complete = () => {+ const navigate = commit && stillCurrent()+ const completedDirection = active.direction+ reset()+ if (navigate) onNavigate(completedDirection)+ }++ paint(commit ? -active.direction * (width + GAP) : 0, !reducedMotion, active.direction)+ if (reducedMotion) complete()+ else pending.current = setTimeout(complete, DURATION)+ }++ return <div ref={surface} className="workout-swipe-surface workout-swipe-stack" data-testid="workout-swipe-surface"+ onPointerDown={onPointerDown} onPointerMove={onPointerMove}+ onPointerUp={event => finish(event)} onPointerCancel={event => finish(event, true)}+ onLostPointerCapture={event => {+ if (event.target === event.currentTarget && !pending.current && gesture.current?.id === event.pointerId) reset()+ }}>+ {direction != null && <div ref={preview} className="workout-swipe-preview" aria-hidden="true" inert>{renderPreview(direction)}</div>}+ <div ref={card} className="workout-swipe-card">{children}</div>+ </div>+}diff --git a/frontend/src/components/SwipeCards.test.jsx b/frontend/src/components/SwipeCards.test.jsxnew file mode 100644index 000000000..62a17ae7f--- /dev/null+++ b/frontend/src/components/SwipeCards.test.jsx@@ -0,0 +1,141 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import SwipeCards from './SwipeCards.jsx'++let host+let root+let props++beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ vi.useFakeTimers()+ host = document.createElement('div')+ document.body.append(host)+ root = createRoot(host)+ props = {+ index: 0,+ count: 3,+ revision: { id: 'session' },+ onNavigate: vi.fn(),+ renderPreview: direction => <div>Adjacent {direction}</div>,+ }+})++afterEach(() => {+ act(() => root.unmount())+ host.remove()+ vi.useRealTimers()+})++const render = () => act(() => root.render(+ <SwipeCards {...props}><div>Current card<button>Set control</button></div></SwipeCards>,+))++function pointer(type, x, y = 20, target = host.querySelector('[data-testid="workout-swipe-surface"]'), pointerType = 'touch') {+ const event = new Event(type, { bubbles: true })+ Object.assign(event, { pointerId: 1, pointerType, clientX: x, clientY: y })+ act(() => target.dispatchEvent(event))+}++describe('SwipeCards', () => {+ it('shows an inert adjacent card while keeping navigation pending until the animation completes', () => {+ render()+ pointer('pointerdown', 250)+ pointer('pointermove', 100)++ const preview = host.querySelector('.workout-swipe-preview')+ expect(preview.textContent).toContain('Adjacent 1')+ expect(preview.getAttribute('aria-hidden')).toBe('true')+ expect(preview.hasAttribute('inert')).toBe(true)+ expect(props.onNavigate).not.toHaveBeenCalled()++ pointer('pointerup', 100)+ expect(props.onNavigate).not.toHaveBeenCalled()+ act(() => vi.advanceTimersByTime(201))+ expect(props.onNavigate).toHaveBeenCalledExactlyOnceWith(1)+ expect(host.querySelector('.workout-swipe-preview')).toBeNull()+ })++ it('cancels short, vertical, interrupted, and stale gestures without navigating', () => {+ render()++ pointer('pointerdown', 200)+ pointer('pointermove', 170)+ pointer('pointerup', 170)+ act(() => vi.advanceTimersByTime(201))++ pointer('pointerdown', 200)+ pointer('pointermove', 170, 100)+ pointer('pointerup', 170, 100)++ pointer('pointerdown', 250)+ pointer('pointermove', 100)+ pointer('pointercancel', 100)+ act(() => vi.advanceTimersByTime(201))++ pointer('pointerdown', 250)+ pointer('pointermove', 100)+ pointer('pointerup', 100)+ props = { ...props, revision: { id: 'changed' } }+ render()+ act(() => vi.advanceTimersByTime(201))++ expect(props.onNavigate).not.toHaveBeenCalled()+ expect(host.querySelector('.workout-swipe-preview')).toBeNull()+ })++ it('resists unavailable edges and leaves controls, mouse input, and vertical scrolling alone', () => {+ render()++ pointer('pointerdown', 100)+ pointer('pointermove', 240)+ expect(host.querySelector('.workout-swipe-preview')).toBeNull()+ pointer('pointerup', 240)+ act(() => vi.advanceTimersByTime(201))++ const button = host.querySelector('button')+ pointer('pointerdown', 250, 20, button)+ pointer('pointermove', 100)+ pointer('pointerup', 100)++ pointer('pointerdown', 250, 20, undefined, 'mouse')+ pointer('pointermove', 100, 20, undefined, 'mouse')+ pointer('pointerup', 100, 20, undefined, 'mouse')++ expect(props.onNavigate).not.toHaveBeenCalled()+ expect(host.querySelector('.workout-swipe-preview')).toBeNull()+ })++ it('cancels a pending commit when timer or timed-work ownership changes', () => {+ props = { ...props, timerKey: 'rest:0', workKey: null }+ render()+ pointer('pointerdown', 250)+ pointer('pointermove', 100)+ pointer('pointerup', 100)+ props = { ...props, timerKey: 'rest:1' }+ render()+ act(() => vi.advanceTimersByTime(201))+ expect(props.onNavigate).not.toHaveBeenCalled()++ pointer('pointerdown', 250)+ pointer('pointermove', 100)+ pointer('pointerup', 100)+ props = { ...props, workKey: 'work:0' }+ render()+ act(() => vi.advanceTimersByTime(201))+ expect(props.onNavigate).not.toHaveBeenCalled()+ })++ it('keeps dragging when pointer capture transfers from a child to the surface', () => {+ render()+ pointer('pointerdown', 250)+ pointer('pointermove', 100)+ pointer('lostpointercapture', 100, 20, host.querySelector('.workout-swipe-card > div'))+ expect(host.querySelector('.workout-swipe-preview')).toBeTruthy()+ pointer('pointerup', 100)+ act(() => vi.advanceTimersByTime(201))+ expect(props.onNavigate).toHaveBeenCalledExactlyOnceWith(1)+ })+})diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 12a1643b4..3683da45b 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -1129,6 +1129,10 @@ body.chips-dragging *{cursor:inherit}background:var(--surface);box-shadow:inset 0 0 0 1.5px var(--acc-line);}.workout-swipe-surface{touch-action:pan-y}+.workout-swipe-stack{position:relative;isolation:isolate;overflow:hidden}+.workout-swipe-stack>.workout-swipe-card,.workout-swipe-stack>.workout-swipe-preview{min-width:0}+.workout-swipe-card{position:relative;z-index:2;background:var(--bg)}+.workout-swipe-preview{position:absolute;z-index:1;inset:0 auto auto 0;width:100%;pointer-events:none;background:var(--bg)}/* A superset nests a card inside the page's own gutter, so its inset is paid twice. On anarrow phone that left the weight and reps steppers too tight to show a three-digitnumber — reported as "the reps textbox becomes too small when superset on mobile". Thediff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex 8e772d080..98fa9531d 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -1,4 +1,5 @@import { useEffect, useRef, useState } from 'react'+import SwipeCards from '../components/SwipeCards.jsx'import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'import { workoutControls } from '../lib/workout-controls.js'@@ -22,10 +23,6 @@ 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'-const SWIPE_MIN_DISTANCE = 48-const SWIPE_AXIS_RATIO = 1.25-const SWIPE_IGNORED_TARGETS = 'button,input,textarea,select,a,[role="button"],[role="checkbox"],[role="switch"],[role="slider"],[contenteditable="true"],.exmedia,[data-swipe-ignore]'-/* ---------- start chooser (no active workout) ---------- */function StartChooser() {const nav = useNavigate()@@ -507,7 +504,7 @@ function ActiveWorkout() {const nav = useNavigate()const S = useStore(s => s.S)const update = useStore(s => s.update)- const { startRest: liveRest, stopRest, stopWork, work } = useUI()+ const { startRest: liveRest, stopRest, stopWork, work, timer } = useUI()const A = S.active// A past workout has no rest to time — the sets were done days ago. The work timer for// timed sets stays, since counting a hold is how its duration gets entered.@@ -553,7 +550,6 @@ function ActiveWorkout() {if (!refs.size) setRefs.current.delete(entry)}}- const swipe = useRef(null)const progressHighWater = useRef(A.entries.map(e => e.sets.filter(s => s.done).length))// The marks are index-keyed, and removing an exercise shifts every index above it down// (removeActiveExercise splices). Re-baseline whenever the list length changes, otherwise a@@ -705,24 +701,6 @@ function ActiveWorkout() {{ icon: 'list', label: t('Layout'), sub: LAYOUT_LABEL[workoutView] || LAYOUT_LABEL.cards, onClick: openLayoutMenu },],})- const onSwipePointerDown = event => {- if (swipe.current || (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen')) return- if (event.target.closest?.(SWIPE_IGNORED_TARGETS)) return- swipe.current = { id: event.pointerId, x: event.clientX, y: event.clientY }- event.currentTarget.setPointerCapture?.(event.pointerId)- }- const finishSwipe = (event, navigate) => {- const start = swipe.current- if (!start || start.id !== event.pointerId) return- swipe.current = null- event.currentTarget.releasePointerCapture?.(event.pointerId)- if (!navigate) return- const dx = event.clientX - start.x- const dy = event.clientY - start.y- if (Math.abs(dx) < SWIPE_MIN_DISTANCE || Math.abs(dx) < Math.abs(dy) * SWIPE_AXIS_RATIO) return- navigateUnit(dx < 0 ? 1 : -1)- }-const openProgressionSettings = idx => {const state = useStore.getState().Sconst entry = state.active?.entries?.[idx]@@ -983,12 +961,20 @@ function ActiveWorkout() {</div>) : <><div className="muted small" style={{ marginBottom: 6 }}>{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}</div>- <div className="workout-swipe-surface" data-testid="workout-swipe-surface"- onPointerDown={onSwipePointerDown}- onPointerUp={event => finishSwipe(event, true)}- onPointerCancel={event => finishSwipe(event, false)}- onLostPointerCapture={event => {- if (swipe.current?.id === event.pointerId) swipe.current = null+ <SwipeCards index={unitIdx} count={units.length} revision={A}+ timerKey={timer && `${timer.endsAt}:${timer.forIdx ?? ''}`} workKey={work?.endsAt}+ onNavigate={navigateUnit} renderPreview={direction => {+ const adjacent = units[unitIdx + direction] || []+ if (!adjacent.length) return null+ return adjacent.length > 1 ? (+ <div className="ss-card">+ <div className="ss-hd"><Icon name="link" />{t('Superset · do these back-to-back, rest when done')}</div>+ {adjacent.map((idx, k) => <div key={idx} className="ss-ex">+ {k > 0 && <div className="ss-amp">+</div>}+ <ExerciseBlock entryIdx={idx} compact />+ </div>)}+ </div>+ ) : <ExerciseBlock entryIdx={adjacent[0]} />}}>{isSuperset ? (<div className="ss-card">@@ -1008,7 +994,7 @@ function ActiveWorkout() {) : (<ExerciseBlock entryIdx={cur} onPairPrev={onPairPrev} onPairNext={onPairNext} {...blockProps(cur)} />)}- </div>+ </SwipeCards></>) : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</div>}<div style={{ height: 12 }} />