Touch and scroll polish: chip rows own the horizontal axis, sheets lock an axis before following the finger and close on a flick, the slider drags relative to the knob, steppers repeat on hold, back-navigation restores the scroll position, a dropped row is tappable at once, the picker search stays above the keyboard, tappable rows work from the keyboard, bigger hit areas in the set row

This commit is contained in:
Duarte Santos committed 2026-08-30 20:18:50 +02:00
1 parent e1fadadadb
commit 60df0cf0dd
19 files changed
+574 -88

No files matched your search

+2 -1
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef } from 'react'
import { fmtVol, isoOf, todayISO, MONTHS } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { tappable } from '../lib/use-sheet-keyboard.js'
// GitHub-style activity heatmap, shaded by time trained per day.
export default function Heatmap({ S, onDay }) {
@@ -38,7 +39,7 @@ export default function Heatmap({ S, onDay }) {
const cls = 'hm-c l' + level(a) + (key === todayISO() ? ' today' : '') + (day > today ? ' future' : '')
cells.push(<div key={d} className={cls}
title={key + (a ? ` · ${t(a.n === 1 ? '{0} workout' : '{0} workouts', a.n)} · ${a.min} min · ${fmtVol(a.vol, S.unit)}` : '')}
onClick={a ? () => onDay(key) : undefined} />)
{...tappable(a ? () => onDay(key) : undefined)} />)
}
cols.push(<div key={wk} className="hm-col">{cells}</div>)
}
+2 -2
View File
@@ -18,7 +18,7 @@ export default function Media({ ex, id, compact, minimizable }) {
const toggleSize = e => { e.stopPropagation(); update(s => { s.gifSize = mini ? 'full' : 'mini' }) }
return (
<div className={'exmedia' + (compact ? ' compact' : '') + (mini ? ' mini' : '')} id={id} onClick={() => setPlaying(p => !p)}>
<img decoding="async" src={playing ? gifSrc(ex) : imgSrc(ex)} alt={exerciseNameFor(ex)} />
<img decoding="async" draggable={false} src={playing ? gifSrc(ex) : imgSrc(ex)} alt={exerciseNameFor(ex)} />
{minimizable && (
<button className="giftoggle" onClick={toggleSize}>
<Icon name={mini ? 'expand' : 'minimize'} />{mini ? t('Expand') : t('Minimize')}
@@ -35,5 +35,5 @@ export default function Media({ ex, id, compact, minimizable }) {
export function Thumb({ ex }) {
if (!ex.img) return <div className="thumb thumb-x"><Icon name="dumbbell" /></div>
return <img className="thumb" loading="lazy" decoding="async" src={imgSrc(ex)} alt="" />
return <img className="thumb" loading="lazy" decoding="async" draggable={false} src={imgSrc(ex)} alt="" />
}
+44 -35
View File
@@ -5,56 +5,65 @@ import { useUI } from '../store/useUI.js'
function Sheet({ sheet }) {
const { closeSheet } = useUI()
const ref = useRef(null)
const drag = useRef({ startY: null, delta: 0 })
// startY null = no gesture. axis stays null until the finger has travelled far enough to
// tell a vertical pull from a sideways scroll; 'x' hands the gesture to whatever scrolls
// horizontally under it (chip strips, heatmap) and the sheet stays put.
const idle = () => ({ startX: null, startY: null, axis: null, delta: 0, vy: 0, lastY: 0, lastT: 0 })
const drag = useRef(idle())
const onTouchStart = e => {
// a gesture that begins on a slider (or opted-out control) belongs to that control, not to
// the sheet's swipe-to-dismiss — so it keeps working while you drag. Horizontal strips are
// opted out too: a sideways scroll must never wobble or pull down the sheet.
const NODRAG = 'input[type=range], [data-nodrag], .chips, .hm-wrap'
const begin = (target, x, y) => {
const el = ref.current
// a gesture that begins on a slider (or opted-out control) belongs to that control,
// not to the sheet's swipe-to-dismiss — so it keeps working while you drag
if (e.target.closest && e.target.closest('input[type=range], [data-nodrag]')) {
drag.current = { startY: null, delta: 0 }
return
}
drag.current = { startY: el.scrollTop <= 0 ? e.touches[0].clientY : null, delta: 0 }
if (target.closest && target.closest(NODRAG)) { drag.current = idle(); return }
if (el.scrollTop > 0) { drag.current = idle(); return }
drag.current = { ...idle(), startX: x, startY: y, lastY: y, lastT: performance.now() }
}
const onTouchMove = e => {
const move = (e, x, y) => {
const el = ref.current, d = drag.current
if (d.startY === null) return
d.delta = e.touches[0].clientY - d.startY
if (d.delta > 0 && el.scrollTop <= 0) {
// synthetic events (tests) may carry no x at all: treat that as straight down
const dx = Number.isFinite(x) ? x - d.startX : 0, dy = y - d.startY
if (d.axis === null) {
// axis lock after ~8px: clearly-more-vertical wins the sheet, anything else is a scroll
if (Math.abs(dx) < 8 && Math.abs(dy) < 8) return
d.axis = Math.abs(dy) > Math.abs(dx) * 1.2 ? 'y' : 'x'
if (d.axis === 'x') return
}
if (d.axis === 'x') return
const now = performance.now()
// velocity from the last move, so a fast short flick can still be told from a slow drag
if (now > d.lastT) { d.vy = (y - d.lastY) / (now - d.lastT); d.lastY = y; d.lastT = now }
if (dy > 0 && el.scrollTop <= 0) {
e.preventDefault()
d.delta = dy
el.style.transition = 'none'
el.style.transform = `translateY(${d.delta}px)`
} else d.delta = 0
el.style.transform = `translateY(${dy}px)`
} else if (d.delta > 0) {
// the pull reversed above the start: snap back before the sheet is allowed to scroll,
// otherwise it scrolls while still hanging below its resting place
e.preventDefault()
d.delta = 0
el.style.transform = 'translateY(0px)'
}
}
const onTouchStart = e => begin(e.target, e.touches[0].clientX, e.touches[0].clientY)
const onTouchMove = e => move(e, e.touches[0].clientX, e.touches[0].clientY)
const onTouchEnd = () => {
const el = ref.current, d = drag.current
if (d.startY === null) return
el.style.transition = 'transform .2s'
if (d.delta > 90 && !sheet.locked) { el.style.transform = 'translateY(110%)'; setTimeout(() => closeSheet(sheet.id), 180) }
// a long pull, or a short but fast flick, dismisses
const flick = d.delta > 30 && d.vy > 0.6
if ((d.delta > 90 || flick) && !sheet.locked) { el.style.transform = 'translateY(110%)'; setTimeout(() => closeSheet(sheet.id), 180) }
else el.style.transform = ''
d.startY = null
drag.current = idle()
}
// Mouse drag (desktop testing / trackpads): same swipe-to-dismiss behaviour.
const onMouseDown = e => {
if (e.button !== 0) return
if (e.target.closest && e.target.closest('input[type=range], [data-nodrag]')) {
drag.current = { startY: null, delta: 0 }
return
}
const el = ref.current
drag.current = { startY: el.scrollTop <= 0 ? e.clientY : null, delta: 0 }
}
const onMouseMove = e => {
const el = ref.current, d = drag.current
if (d.startY === null) return
d.delta = e.clientY - d.startY
if (d.delta > 0 && el.scrollTop <= 0) {
e.preventDefault()
el.style.transition = 'none'
el.style.transform = `translateY(${d.delta}px)`
} else d.delta = 0
}
const onMouseDown = e => { if (e.button === 0) begin(e.target, e.clientX, e.clientY) }
const onMouseMove = e => move(e, e.clientX, e.clientY)
const onMouseUp = () => onTouchEnd()
// non-passive touchmove so preventDefault works (bottom sheets only; centered dialogs have no ref)
+95 -2
View File
@@ -74,10 +74,11 @@ async function popstate() {
await act(async () => { window.dispatchEvent(new dom.Event('popstate')) })
}
function mouse(target, type, clientY) {
function mouse(target, type, clientY, clientX = 0) {
const event = new dom.Event(type, { bubbles: true })
Object.defineProperties(event, {
button: { value: 0 },
clientX: { value: clientX },
clientY: { value: clientY },
})
target.dispatchEvent(event)
@@ -181,13 +182,16 @@ describe('Modals mouse dragging', () => {
})
it('releases a drag when mouseup occurs outside the sheet', async () => {
// a slow pull: synthetic events fire in the same tick, which would read as a flick
let now = 0
vi.spyOn(performance, 'now').mockImplementation(() => now)
await setSheets([sheet('drag')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
mouse(sheetEl, 'mousemove', 60)
now = 300; mouse(sheetEl, 'mousemove', 60)
})
expect(sheetEl.style.transform).toBe('translateY(50px)')
@@ -199,3 +203,92 @@ describe('Modals mouse dragging', () => {
expect(mocks.state.sheets).toHaveLength(1)
})
})
describe('Modals drag axis lock and dismiss', () => {
it('ignores a sideways gesture instead of wobbling the sheet', async () => {
await setSheets([sheet('x')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10, 10)
mouse(sheetEl, 'mousemove', 20, 60)
// once locked to x, even a clearly downward move stays with the horizontal gesture
mouse(sheetEl, 'mousemove', 120, 70)
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
it('leaves horizontal chip strips to their own scrolling', async () => {
await setSheets([sheet('chips', {
render: () => React.createElement('div', { className: 'chips' }, React.createElement('button', { className: 'chip' }, 'a')),
})])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(container.querySelector('.chip'), 'mousedown', 10)
mouse(sheetEl, 'mousemove', 150)
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
it('snaps back to zero when the pull reverses instead of scrolling while offset', async () => {
await setSheets([sheet('rev')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
mouse(sheetEl, 'mousemove', 110)
})
expect(sheetEl.style.transform).toBe('translateY(100px)')
await act(async () => { mouse(sheetEl, 'mousemove', 5) })
expect(sheetEl.style.transform).toBe('translateY(0px)')
await act(async () => { window.dispatchEvent(new dom.Event('mouseup')) })
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
it('dismisses on a short but fast flick', async () => {
vi.useFakeTimers()
let now = 0
vi.spyOn(performance, 'now').mockImplementation(() => now)
await setSheets([sheet('flick')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
now = 20; mouse(sheetEl, 'mousemove', 40)
now = 60; mouse(sheetEl, 'mousemove', 80) // 70px in 60ms: ~1 px/ms
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('translateY(110%)')
await act(async () => { vi.advanceTimersByTime(200) })
expect(mocks.state.sheets).toHaveLength(0)
vi.useRealTimers()
})
it('keeps a short slow pull open', async () => {
let now = 0
vi.spyOn(performance, 'now').mockImplementation(() => now)
await setSheets([sheet('slow')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
now = 400; mouse(sheetEl, 'mousemove', 80)
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
})
+52 -4
View File
@@ -117,14 +117,50 @@ export function Segmented({ options, value, onChange, className = '' }) {
export function Stepper({ value, step = 1, onChange, decimal = true, className = '', label, unit, invalid = false }) {
const set = v => onChange(Math.max(0, Math.round((v || 0) * 100) / 100))
// Holding a button repeats the step; the latest value/step live in a ref so
// the interval doesn't keep stepping from the value it was started with.
const live = useRef({ value, step, set })
live.current = { value, step, set }
const hold = useRef({ delay: null, tick: null, count: 0, repeated: false })
const bump = dir => { const { value, step, set } = live.current; set((+value || 0) + dir * step) }
const stopHold = () => {
const h = hold.current
window.clearTimeout(h.delay); window.clearInterval(h.tick)
h.delay = h.tick = null
}
const startHold = dir => {
stopHold()
const h = hold.current
h.repeated = false; h.count = 0
h.delay = window.setTimeout(() => {
const run = () => {
h.repeated = true; h.count++
bump(dir)
// modest acceleration after a bit of holding so a long hold covers ground
if (h.count === 15) { window.clearInterval(h.tick); h.tick = window.setInterval(run, 40) }
}
h.tick = window.setInterval(run, 80)
}, 400)
}
// The click that follows pointerup must not add a step once the hold repeated.
const click = dir => {
if (hold.current.repeated) { hold.current.repeated = false; return }
bump(dir)
}
useEffect(() => stopHold, [])
const holdProps = dir => ({
onPointerDown: e => { if (e.button === 0 || e.button == null) startHold(dir) },
onPointerUp: stopHold, onPointerCancel: stopHold, onPointerLeave: stopHold, onBlur: stopHold,
onClick: () => click(dir),
})
const inner = (
<div className={'stp ' + className}>
<button onClick={() => set((+value || 0) - step)} aria-label="Decrease"><Icon name="minus" /></button>
<button {...holdProps(-1)} aria-label="Decrease"><Icon name="minus" /></button>
<span className="val">
<NumberField value={value} decimal={decimal} onChange={onChange} aria-invalid={invalid ? 'true' : undefined} />
{unit && <i>{unit}</i>}
</span>
<button onClick={() => set((+value || 0) + step)} aria-label="Increase"><Icon name="plus" /></button>
<button {...holdProps(1)} aria-label="Increase"><Icon name="plus" /></button>
</div>
)
if (!label) return inner
@@ -136,9 +172,13 @@ export function Stepper({ value, step = 1, onChange, decimal = true, className =
// Pointer-driven so the fill, track and thumb are all ours — no ::-webkit-*
// pseudo-elements, which is the only way the control looks identical on every
// platform and can pick up the accent colour.
export const SLIDER_GRAB_PX = 22
export function Slider({ value, min = 0, max = 100, step = 1, onChange, className = '' }) {
const ref = useRef(null)
const [drag, setDrag] = useState(false)
// Grabbing the knob drags it relative to where the finger landed; a finger
// is ~22px wide, so a touch that far off still means "the knob", not "jump".
const offset = useRef(0)
const pct = Math.min(100, Math.max(0, ((value - min) / (max - min)) * 100))
const posToValue = useCallback(clientX => {
@@ -156,7 +196,7 @@ export function Slider({ value, min = 0, max = 100, step = 1, onChange, classNam
if (!drag) return
const move = e => {
e.preventDefault()
onChange(posToValue(e.touches ? e.touches[0].clientX : e.clientX))
onChange(posToValue((e.touches ? e.touches[0].clientX : e.clientX) - offset.current))
}
const up = () => setDrag(false)
window.addEventListener('pointermove', move)
@@ -186,7 +226,15 @@ export function Slider({ value, min = 0, max = 100, step = 1, onChange, classNam
aria-valuenow={value} aria-valuemin={min} aria-valuemax={max}
data-nodrag /* keeps the sheet from swipe-dismissing */
onKeyDown={key}
onPointerDown={e => { e.currentTarget.setPointerCapture?.(e.pointerId); setDrag(true); onChange(posToValue(e.clientX)) }}
onPointerDown={e => {
e.currentTarget.setPointerCapture?.(e.pointerId)
const r = e.currentTarget.getBoundingClientRect()
const knobX = r.left + (pct / 100) * r.width
const d = e.clientX - knobX
offset.current = Math.abs(d) <= SLIDER_GRAB_PX ? d : 0
setDrag(true)
if (!offset.current) onChange(posToValue(e.clientX))
}}
>
<span className="sld-track"><span className="sld-fill" style={{ width: pct + '%' }} /></span>
<span className="sld-knob" style={{ left: pct + '%' }} />
+108
View File
@@ -0,0 +1,108 @@
// @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 { Slider, Stepper, SLIDER_GRAB_PX } from './ui.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
let host, root
beforeEach(() => {
vi.useFakeTimers()
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
vi.useRealTimers()
})
function pointer(target, type, { x = 0, y = 0, button = 0 } = {}) {
const event = new Event(type, { bubbles: true, cancelable: true })
for (const [k, v] of Object.entries({ pointerId: 1, pointerType: 'touch', isPrimary: true, button, clientX: x, clientY: y })) {
Object.defineProperty(event, k, { configurable: true, value: v })
}
act(() => target.dispatchEvent(event))
return event
}
describe('Slider', () => {
// 300px track from x=100 to x=400 over 0..300 so 1px == 1 unit
const mountSlider = (value, onChange) => {
act(() => root.render(<Slider value={value} min={0} max={300} step={1} onChange={onChange} />))
const el = host.querySelector('.sld')
vi.spyOn(el, 'getBoundingClientRect').mockReturnValue({ left: 100, right: 400, width: 300, top: 0, bottom: 20, height: 20, x: 100, y: 0 })
return el
}
it('drags relative to the grab point when the touch lands on the knob', () => {
const onChange = vi.fn()
const el = mountSlider(80, onChange) // knob at x=180
pointer(el, 'pointerdown', { x: 180 + SLIDER_GRAB_PX - 2 })
expect(onChange).not.toHaveBeenCalled() // grabbing must not jump
pointer(window, 'pointermove', { x: 180 + SLIDER_GRAB_PX - 2 + 60 })
expect(onChange).toHaveBeenLastCalledWith(140) // moved by 60, not to the finger
pointer(window, 'pointerup')
})
it('still jumps to the touched position away from the knob', () => {
const onChange = vi.fn()
const el = mountSlider(80, onChange)
pointer(el, 'pointerdown', { x: 350 })
expect(onChange).toHaveBeenLastCalledWith(250)
pointer(window, 'pointermove', { x: 360 })
expect(onChange).toHaveBeenLastCalledWith(260)
pointer(window, 'pointerup')
})
})
describe('Stepper', () => {
// controlled like every real caller: the parent re-renders with the new value
function Host({ initial, onChange, step }) {
const [v, setV] = React.useState(initial)
return <Stepper value={v} step={step} onChange={n => { setV(n); onChange(n) }} />
}
const mountStepper = (value, onChange, step = 1) => {
act(() => root.render(<Host initial={value} step={step} onChange={onChange} />))
return host.querySelector('button[aria-label="Increase"]')
}
it('steps once for a short tap (pointerdown, pointerup, click)', () => {
const onChange = vi.fn()
const plus = mountStepper(10, onChange)
pointer(plus, 'pointerdown'); pointer(plus, 'pointerup')
act(() => plus.click())
expect(onChange).toHaveBeenCalledTimes(1)
expect(onChange).toHaveBeenCalledWith(11)
})
it('repeats while held and swallows the trailing click', () => {
let value = 10
const onChange = vi.fn(v => { value = v })
const plus = mountStepper(value, onChange)
pointer(plus, 'pointerdown')
act(() => vi.advanceTimersByTime(399))
expect(onChange).not.toHaveBeenCalled()
// one act per tick: in the browser every interval callback is its own task
act(() => vi.advanceTimersByTime(1 + 80))
act(() => vi.advanceTimersByTime(80))
act(() => vi.advanceTimersByTime(80))
expect(onChange).toHaveBeenCalledTimes(3)
// each repeat builds on the latest value, not the one the hold started with
expect(onChange).toHaveBeenLastCalledWith(13)
pointer(plus, 'pointerup')
act(() => plus.click())
expect(onChange).toHaveBeenCalledTimes(3)
act(() => vi.advanceTimersByTime(1000))
expect(onChange).toHaveBeenCalledTimes(3) // nothing keeps ticking after release
})
it('keeps working from the keyboard (click without a pointer)', () => {
const onChange = vi.fn()
const plus = mountStepper(10, onChange)
act(() => plus.click())
expect(onChange).toHaveBeenCalledWith(11)
})
})