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 cards: a swipe can start almost anywhere on the card, and a flick turns it (#431)
Duarte Santos7c4a723f69a1
diff --git a/frontend/src/components/SwipeCards.jsx b/frontend/src/components/SwipeCards.jsxindex 723a40674..24f7aa881 100644--- a/frontend/src/components/SwipeCards.jsx+++ b/frontend/src/components/SwipeCards.jsx@@ -1,12 +1,46 @@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]'+// What a card swipe never starts on: things that take a sideways drag themselves (a slider, a+// chip row that scrolls, a video's scrubber, a text area), and what has its own swipe (a set row,+// SwipeRow, marks itself data-swipe-ignore). Buttons, fields, the tick and the animation used to+// be on this list too, and on a phone that left almost no card to swipe (#431): a swipe may now+// start on any of them, and a tap is still a tap. The click a swipe leaves behind is swallowed.+const IGNORED_TARGETS = 'textarea,select,input[type="range"],[role="slider"],[contenteditable="true"],video[controls],audio,.chips,[data-swipe-ignore]'const AXIS_SLOP = 8-const AXIS_RATIO = 1.5+const AXIS_RATIO = 1.2+const AXIS_DECIDE = 24const COMMIT_DISTANCE = 70+const FLING_DISTANCE = 30+const FLING_SPEED = 0.35const GAP = 12const DURATION = 200+/**+ * The axis a card swipe has settled on after a move of (dx, dy): null while it is still too+ * short or too diagonal to tell, 'x' to turn the card, 'y' to leave it to the page's scroll.+ * Anything at least as vertical as it is sideways is the scroll's (with touch-action: pan-y the+ * browser takes those anyway). A clearly sideways move locks at once; a diagonal one that leans+ * sideways is watched a little longer and then turns the card, instead of being dropped as it was+ * at a strict 1.5 to 1 (#431), a gesture the browser had not scrolled either, so it did nothing.+ */+export function cardAxis(dx, dy) {+ const ax = Math.abs(dx), ay = Math.abs(dy)+ if (Math.max(ax, ay) < AXIS_SLOP) return null+ if (ay >= ax) return 'y'+ if (ax >= ay * AXIS_RATIO || ax >= AXIS_DECIDE) return 'x'+ return null+}++/**+ * Whether letting go turns the card: far enough (70 px), or a flick (30 px at 0.35 px/ms or+ * more) the way the card moved. `v` is the release speed in px/ms, signed like dx.+ */+export function cardCommits(dx, dy, v = 0) {+ const ax = Math.abs(dx)+ if (ax <= Math.abs(dy)) return false+ return ax >= COMMIT_DISTANCE || (ax >= FLING_DISTANCE && v * Math.sign(dx) >= FLING_SPEED)+}+// Which physical side the next card lies on: the right in a left-to-right language, the left in// a right-to-left one (Arabic), where the exercises run from right to left like the text. A// swipe towards the other side brings the next card in. `direction` stays logical throughout@@ -47,6 +81,15 @@ export default function SwipeCards({ children, renderPreview, onNavigate, index,}}+ // The click a swipe leaves behind: the button, tick or animation the finger started on must not+ // act once the card has moved. Cleared by the next touch, or after a moment.+ const swallow = useRef({ on: false, tm: null })+ const swallowClick = () => {+ clearTimeout(swallow.current.tm)+ swallow.current.on = true+ swallow.current.tm = setTimeout(() => { swallow.current.on = false }, 600)+ }+useEffect(() => {reset()return () => clearTimeout(pending.current)@@ -56,16 +99,36 @@ export default function SwipeCards({ children, renderPreview, onNavigate, index,if (gesture.current) paint(gesture.current.offset, false, direction)}, [direction])+ // touchmove is attached by hand and not passive, so a locked sideways swipe keeps the page from+ // scrolling under it on browsers that do not honour touch-action (React's touch handlers are+ // passive). Before the lock it does nothing, so the page scrolls as usual.+ useEffect(() => {+ const el = surface.current+ if (!el) return+ const onTouchMove = e => { if (gesture.current?.locked && e.cancelable) e.preventDefault() }+ el.addEventListener('touchmove', onTouchMove, { passive: false })+ return () => {+ el.removeEventListener('touchmove', onTouchMove)+ clearTimeout(swallow.current.tm)+ }+ }, [])+const onPointerDown = event => {+ swallow.current.on = falseif (pending.current || gesture.current) returnif (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen') return- if (event.target.closest?.(IGNORED_TARGETS)) return+ const target = event.target+ if (target?.closest?.(IGNORED_TARGETS)) return+ // A field you are typing in keeps a sideways drag for its caret.+ if (typeof document !== 'undefined' && target === document.activeElement && target?.matches?.('input')) returngesture.current = {id: event.pointerId,x: event.clientX,y: event.clientY,offset: 0,direction: null,+ locked: false,+ samples: [],side: nextSide(),revision,timerKey,@@ -73,35 +136,58 @@ export default function SwipeCards({ children, renderPreview, onNavigate, index,}}+ const track = (active, event, dx) => {+ const now = event.timeStamp || Date.now()+ active.samples.push([now, dx])+ while (active.samples.length > 2 && now - active.samples[0][0] > 100) active.samples.shift()+ }+const onPointerMove = event => {const active = gesture.currentif (!active || active.id !== event.pointerId) returnconst dx = event.clientX - active.xconst 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) {+ if (!active.locked) {+ const axis = cardAxis(dx, dy)+ if (!axis) return+ if (axis === 'y') {gesture.current = nullreturn}- event.currentTarget.setPointerCapture?.(event.pointerId)+ active.locked = true+ try { event.currentTarget.setPointerCapture?.(event.pointerId) } catch { /* the gesture still tracks */ }+ swallowClick()+ const focused = typeof document !== 'undefined' ? document.activeElement : null+ if (focused && focused !== document.body && surface.current?.contains(focused)) focused.blur?.()}+ track(active, event, dx)const nextDirection = dx * active.side < 0 ? 1 : -1const available = index + nextDirection >= 0 && index + nextDirection < countactive.direction = nextDirectionactive.offset = available ? dx : dx * 0.35- setDirection(available ? nextDirection : null)+ if (direction !== (available ? nextDirection : null)) setDirection(available ? nextDirection : null)paint(active.offset, false, nextDirection)}const finish = (event, cancelled = false) => {const active = gesture.currentif (!active || active.id !== event.pointerId) return- const dx = event.clientX - active.x- const dy = event.clientY - active.y+ // A tap, or a touch that never left the slop: nothing moved, so nothing to settle. It used+ // to wait out the 200 ms settle anyway, and a swipe started inside that wait was ignored.+ if (!active.locked) {+ gesture.current = null+ return+ }+ const lifted = Number.isFinite(event.clientX)+ const dx = lifted ? event.clientX - active.x : active.offset+ const dy = lifted && Number.isFinite(event.clientY) ? event.clientY - active.y : 0+ if (lifted && !cancelled) track(active, event, dx)+ const samples = active.samples+ const dt = samples.length > 1 ? samples[samples.length - 1][0] - samples[0][0] : 0+ const speed = dt > 0 ? (samples[samples.length - 1][1] - samples[0][1]) / dt : 0const 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 commit = !cancelled && active.direction != null && available && cardCommits(dx, dy, speed)const reducedMotion = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matchesconst width = surface.current?.getBoundingClientRect().width || 360const stillCurrent = () => {@@ -123,6 +209,12 @@ export default function SwipeCards({ children, renderPreview, onNavigate, index,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)}+ onClickCapture={event => {+ if (!swallow.current.on) return+ swallow.current.on = false+ event.preventDefault()+ event.stopPropagation()+ }}onLostPointerCapture={event => {if (event.target === event.currentTarget && !pending.current && gesture.current?.id === event.pointerId) reset()}}>diff --git a/frontend/src/components/SwipeCards.test.jsx b/frontend/src/components/SwipeCards.test.jsxindex 4dfa0b674..6f16e704f 100644--- a/frontend/src/components/SwipeCards.test.jsx+++ b/frontend/src/components/SwipeCards.test.jsx@@ -2,7 +2,7 @@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'+import SwipeCards, { cardAxis, cardCommits } from './SwipeCards.jsx'let hostlet root@@ -33,9 +33,10 @@ 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') {+function pointer(type, x, y = 20, target = host.querySelector('[data-testid="workout-swipe-surface"]'), pointerType = 'touch', timeStamp) {const event = new Event(type, { bubbles: true })Object.assign(event, { pointerId: 1, pointerType, clientX: x, clientY: y })+ if (timeStamp != null) Object.defineProperty(event, 'timeStamp', { value: timeStamp })act(() => target.dispatchEvent(event))}@@ -86,7 +87,7 @@ describe('SwipeCards', () => {expect(host.querySelector('.workout-swipe-preview')).toBeNull()})- it('resists unavailable edges and leaves controls, mouse input, and vertical scrolling alone', () => {+ it('resists unavailable edges and leaves mouse input alone', () => {render()pointer('pointerdown', 100)@@ -95,17 +96,96 @@ describe('SwipeCards', () => {pointer('pointerup', 240)act(() => vi.advanceTimersByTime(201))+ 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()+ })++ // #431: buttons, fields, the tick and the animation cover most of a card, and a swipe that+ // started on any of them did nothing. It turns the card now, and the control does not act.+ it('turns the card from a swipe that starts on a control, and swallows the click it leaves', () => {+ const clicked = vi.fn()+ act(() => root.render(+ <SwipeCards {...props}><div>Current card<button onClick={clicked}>Set control</button></div></SwipeCards>,+ ))const button = host.querySelector('button')pointer('pointerdown', 250, 20, button)+ pointer('pointermove', 100, 20, button)+ pointer('pointerup', 100, 20, button)+ act(() => button.click())+ expect(clicked).not.toHaveBeenCalled()+ act(() => vi.advanceTimersByTime(201))+ expect(props.onNavigate).toHaveBeenCalledExactlyOnceWith(1)++ // A plain tap is still a tap.+ pointer('pointerdown', 250, 20, button)+ pointer('pointerup', 250, 20, button)+ act(() => button.click())+ expect(clicked).toHaveBeenCalledTimes(1)+ })++ it('leaves sliders, chip rows, set rows and a field being typed in alone', () => {+ act(() => root.render(+ <SwipeCards {...props}><div>+ <input type="range" />+ <div className="chips"><span className="chip">Chip</span></div>+ <div data-swipe-ignore=""><span className="row">Set row</span></div>+ <input className="field" />+ </div></SwipeCards>,+ ))+ const field = host.querySelector('.field')+ field.focus()+ for (const target of [host.querySelector('input[type="range"]'), host.querySelector('.chip'), host.querySelector('.row'), field]) {+ pointer('pointerdown', 250, 20, target)+ pointer('pointermove', 100, 20, target)+ pointer('pointerup', 100, 20, target)+ act(() => vi.advanceTimersByTime(201))+ }+ expect(props.onNavigate).not.toHaveBeenCalled()+ })++ it('a tap does not hold up the swipe that follows it', () => {+ render()+ pointer('pointerdown', 250)+ pointer('pointerup', 250)+ pointer('pointerdown', 250)pointer('pointermove', 100)pointer('pointerup', 100)+ act(() => vi.advanceTimersByTime(201))+ expect(props.onNavigate).toHaveBeenCalledExactlyOnceWith(1)+ })- pointer('pointerdown', 250, 20, undefined, 'mouse')- pointer('pointermove', 100, 20, undefined, 'mouse')- pointer('pointerup', 100, 20, undefined, 'mouse')+ it('a short quick flick turns the card, the same distance slowly does not', () => {+ render()+ pointer('pointerdown', 250, 20, undefined, 'touch', 0)+ pointer('pointermove', 235, 20, undefined, 'touch', 16)+ pointer('pointermove', 210, 20, undefined, 'touch', 32)+ pointer('pointerup', 205, 20, undefined, 'touch', 48)+ act(() => vi.advanceTimersByTime(201))+ expect(props.onNavigate).toHaveBeenCalledExactlyOnceWith(1)+ props.onNavigate.mockClear()+ pointer('pointerdown', 250, 20, undefined, 'touch', 1000)+ pointer('pointermove', 235, 20, undefined, 'touch', 1200)+ pointer('pointermove', 210, 20, undefined, 'touch', 1400)+ pointer('pointerup', 205, 20, undefined, 'touch', 1600)+ act(() => vi.advanceTimersByTime(201))expect(props.onNavigate).not.toHaveBeenCalled()+ })++ it('a diagonal that leans sideways is watched, then turns the card', () => {+ render()+ pointer('pointerdown', 250, 20)+ pointer('pointermove', 240, 29) // 10 across, 9 down: too close to call yetexpect(host.querySelector('.workout-swipe-preview')).toBeNull()+ pointer('pointermove', 200, 50)+ expect(host.querySelector('.workout-swipe-preview')).toBeTruthy()+ pointer('pointerup', 150, 60)+ act(() => vi.advanceTimersByTime(201))+ expect(props.onNavigate).toHaveBeenCalledExactlyOnceWith(1)})it('cancels a pending commit when timer or timed-work ownership changes', () => {@@ -170,3 +250,29 @@ describe('SwipeCards', () => {})})})++describe('cardAxis', () => {+ it('waits for 8 px, gives anything as vertical as it is sideways to the scroll', () => {+ expect(cardAxis(7, 0)).toBeNull()+ expect(cardAxis(8, 0)).toBe('x')+ expect(cardAxis(9, 9)).toBe('y')+ expect(cardAxis(2, 10)).toBe('y')+ })+ it('locks a clearly sideways move at once and a leaning diagonal by 24 px', () => {+ expect(cardAxis(12, 10)).toBe('x')+ expect(cardAxis(-12, 10)).toBe('x')+ expect(cardAxis(11, 10)).toBeNull()+ expect(cardAxis(24, 23)).toBe('x')+ })+})++describe('cardCommits', () => {+ it('turns past 70 px, or on a flick past 30 px the way the card moved', () => {+ expect(cardCommits(-70, 0)).toBe(true)+ expect(cardCommits(-69, 0)).toBe(false)+ expect(cardCommits(-30, 0, -0.4)).toBe(true)+ expect(cardCommits(-29, 0, -2)).toBe(false)+ expect(cardCommits(-40, 0, 0.5)).toBe(false) // flicked back the other way+ expect(cardCommits(80, 90)).toBe(false) // ended up more vertical than sideways+ })+})