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.

feat(routines): add long-press reorder

Space_Hermes5770f3bc04c4
diff --git a/frontend/src/index.css b/frontend/src/index.css
index a34845995..eaf4ee38c 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -376,6 +376,16 @@ h4.sec{
transition:background var(--fast);text-align:left;width:100%;
}
.item:active{background:var(--surface-2)}
+.routine-list{position:relative}
+.routine-drag-row{touch-action:pan-y;position:relative;transition:transform var(--fast) var(--ease)}
+.routine-list.is-reordering{user-select:none;-webkit-user-select:none}
+.routine-list.is-reordering .routine-drag-row{transition:none}
+.routine-drag-row.is-dragging{z-index:2;pointer-events:none}
+.routine-drag-row.is-dragging .item{box-shadow:0 10px 28px rgba(0,0,0,.22);background:var(--surface-2)}
+.routine-drop-indicator{
+ position:absolute;left:6px;right:6px;height:3px;border-radius:99px;
+ background:var(--acc);transform:translateY(-50%);pointer-events:none;z-index:3;
+}
.thumb{width:50px;height:50px;border-radius:9px;object-fit:cover;background:#fff;flex:none}
.thumb-x{
display:flex;align-items:center;justify-content:center;font-size:21px;
diff --git a/frontend/src/views/RoutineEdit.drag.test.jsx b/frontend/src/views/RoutineEdit.drag.test.jsx
new file mode 100644
index 000000000..54273878d
--- /dev/null
+++ b/frontend/src/views/RoutineEdit.drag.test.jsx
@@ -0,0 +1,281 @@
+// @vitest-environment happy-dom
+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({})) }))
+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_DRAG_SLOP, ROUTINE_LONG_PRESS_MS, reorderRoutineUnit } from './RoutineEdit.jsx'
+import { DEF, useStore } from '../store/useStore.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
+let host
+
+function stateFor(entries) {
+ const S = clone(DEF)
+ S.routines = [{ id: 'r1', name: 'Drag routine', emoji: 'dumbbell', prog: 'linear', ex: entries }]
+ return S
+}
+function rect(top, height, left = 20, width = 340) {
+ return { x: left, y: top, left, right: left + width, top, bottom: top + height, width, height }
+}
+const rows = () => [...host.querySelectorAll('[data-routine-row]')]
+function geometry(heights = rows().map(() => 70)) {
+ const list = host.querySelector('.routine-list')
+ let top = 100
+ const tops = [], bottoms = [], centers = []
+ rows().forEach((row, i) => {
+ const height = heights[i] ?? 70
+ tops.push(top); bottoms.push(top + height); centers.push(top + height / 2)
+ vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => rect(tops[i], height))
+ top += height + 10
+ })
+ const listRect = rect(80, top - 80)
+ vi.spyOn(list, 'getBoundingClientRect').mockImplementation(() => listRect)
+ return { list, tops, bottoms, centers, listRect }
+}
+function mount(entries) {
+ useStore.setState({ S: stateFor(entries), 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>))
+ return geometry()
+}
+function pointer(target, type, { id = 7, kind = 'touch', primary = true, button = 0, x = 120, y = 120 } = {}) {
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ for (const [key, value] of Object.entries({ pointerId: id, pointerType: kind, isPrimary: primary, button, clientX: x, clientY: y })) {
+ Object.defineProperty(event, key, { configurable: true, value })
+ }
+ act(() => target.dispatchEvent(event))
+ return event
+}
+function lift(row, y, x = 120) {
+ pointer(row.querySelector('.item'), 'pointerdown', { x, y })
+ act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
+}
+const exercises = () => useStore.getState().S.routines[0].ex
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => window.setTimeout(() => cb(Date.now()), 16))
+ vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(id => window.clearTimeout(id))
+ localStorage.clear()
+ Object.values(sheets).forEach(mock => mock.mockReset())
+ root = null; host = null
+})
+afterEach(() => {
+ if (root) act(() => root.unmount())
+ host?.remove()
+ vi.clearAllTimers(); vi.restoreAllMocks(); vi.useRealTimers()
+})
+
+describe('routine long-press reorder', () => {
+ it('exports the frozen threshold/slop and keeps a short press as a normal click', () => {
+ expect(ROUTINE_LONG_PRESS_MS).toBe(380)
+ expect(ROUTINE_DRAG_SLOP).toBe(8)
+ const layout = mount([configured('1001'), configured('1002')])
+ const item = rows()[0].querySelector('.item')
+ pointer(item, 'pointerdown', { y: layout.centers[0] })
+ act(() => vi.advanceTimersByTime(379))
+ expect(host.querySelector('.is-dragging')).toBeNull()
+ pointer(item, 'pointerup', { y: layout.centers[0] })
+ act(() => item.click())
+ expect(sheets.exConfigSheet).toHaveBeenCalledOnce()
+ expect(exercises().map(e => e.id)).toEqual(['1001', '1002'])
+ })
+
+ it('lifts at exactly 380 ms and yields pre-lift movement strictly over 8 px to scrolling', () => {
+ let layout = mount([configured('1001'), configured('1002')])
+ let item = rows()[0].querySelector('.item')
+ pointer(item, 'pointerdown', { x: 100, y: layout.centers[0] })
+ const atEight = pointer(item, 'pointermove', { x: 108, y: layout.centers[0] })
+ expect(atEight.defaultPrevented).toBe(false)
+ act(() => vi.advanceTimersByTime(380))
+ expect(rows()[0].classList.contains('is-dragging')).toBe(true)
+ pointer(item, 'pointercancel', { x: 108, y: layout.centers[0] })
+
+ act(() => root.unmount()); host.remove(); root = null; host = null
+ layout = mount([configured('1001'), configured('1002')])
+ item = rows()[0].querySelector('.item')
+ pointer(item, 'pointerdown', { x: 100, y: layout.centers[0] })
+ const atNine = pointer(item, 'pointermove', { x: 109, y: layout.centers[0] })
+ act(() => vi.advanceTimersByTime(380))
+ expect(atNine.defaultPrevented).toBe(false)
+ expect(host.querySelector('.is-dragging')).toBeNull()
+ })
+
+ it('owns active movement, renders an indicator, and suppresses the compatibility click after cancel', () => {
+ const layout = mount([configured('1001'), configured('1002'), configured('1003')])
+ const row = rows()[1], item = row.querySelector('.item')
+ const capture = vi.fn(), release = vi.fn()
+ item.setPointerCapture = capture; item.releasePointerCapture = release
+ lift(row, layout.centers[1])
+ expect(capture).toHaveBeenCalledWith(7)
+ expect(row.classList.contains('is-dragging')).toBe(true)
+ expect(host.querySelector('[data-testid="routine-drop-indicator"]')).toBeTruthy()
+ const move = pointer(item, 'pointermove', { y: layout.centers[2] })
+ expect(move.defaultPrevented).toBe(true)
+ pointer(item, 'pointercancel', { y: layout.centers[2] })
+ expect(release).toHaveBeenCalledWith(7)
+ act(() => item.click())
+ expect(sheets.exConfigSheet).not.toHaveBeenCalled()
+ expect(exercises().map(e => e.id)).toEqual(['1001', '1002', '1003'])
+ })
+
+ it('moves across measured slots and persists one complete changed order', () => {
+ const layout = mount([configured('a'), configured('b'), configured('c'), configured('d')])
+ const before = localStorage.getItem('gym_state_v1')
+ const writes = vi.spyOn(Storage.prototype, 'setItem')
+ const row = rows()[0], item = row.querySelector('.item')
+ lift(row, layout.centers[0])
+ pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
+ pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
+ expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a', 'd'])
+ expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines[0].ex.map(e => e.id)).toEqual(['b', 'c', 'a', 'd'])
+ expect(localStorage.getItem('gym_state_v1')).not.toBe(before)
+ expect(writes).toHaveBeenCalledTimes(1)
+ })
+
+ it('moves a whole grouped unit, never splits another group, and preserves every occurrence payload', () => {
+ const pairA = configured('dup', { sg: 'pair', weight: 11, note: 'first', future: { a: 1 } })
+ const pairB = configured('dup', { sg: 'pair', weight: 22, note: 'second', future: { b: 2 } })
+ const layout = mount([pairA, pairB, configured('c'), configured('d')])
+ const row = rows()[1], item = row.querySelector('.item')
+ lift(row, layout.centers[1])
+ expect(rows().slice(0, 2).every(node => node.classList.contains('is-dragging'))).toBe(true)
+ pointer(item, 'pointermove', { y: layout.listRect.bottom - 1 })
+ pointer(item, 'pointerup', { y: layout.listRect.bottom - 1 })
+ expect(exercises()).toEqual([configured('c'), configured('d'), pairA, pairB])
+
+ act(() => root.unmount()); host.remove(); root = null; host = null
+ const splitLayout = mount([configured('a'), configured('b', { sg: 'g' }), configured('c', { sg: 'g' }), configured('tail')])
+ const tail = rows()[3], tailItem = tail.querySelector('.item')
+ lift(tail, splitLayout.centers[3])
+ const betweenMembers = (splitLayout.bottoms[1] + splitLayout.tops[2]) / 2
+ pointer(tailItem, 'pointermove', { y: betweenMembers })
+ pointer(tailItem, 'pointerup', { y: betweenMembers })
+ expect(exercises().map(e => e.id)).toEqual(['a', 'tail', 'b', 'c'])
+ })
+
+ it('moves the selected duplicate occurrence rather than finding by catalogue id', () => {
+ const first = configured('dup', { weight: 10, reps: 3, note: 'first' })
+ const second = configured('dup', { weight: 20, reps: 9, note: 'second' })
+ const layout = mount([first, configured('middle'), second, configured('tail')])
+ const row = rows()[2], item = row.querySelector('.item')
+ lift(row, layout.centers[2])
+ pointer(item, 'pointermove', { y: layout.tops[0] + 1 })
+ pointer(item, 'pointerup', { y: layout.tops[0] + 1 })
+ expect(exercises()).toEqual([second, first, configured('middle'), configured('tail')])
+ })
+
+ it('cancels without persistence on outside release, lost capture, Escape, blur, hidden document, or second pointer', () => {
+ const cancelCases = ['outside', 'lost', 'escape', 'blur', 'hidden', 'second']
+ for (const cancel of cancelCases) {
+ if (root) { act(() => root.unmount()); host.remove(); root = null; host = null }
+ const layout = mount([configured('a'), configured('b'), configured('c')])
+ const row = rows()[0], item = row.querySelector('.item')
+ const before = localStorage.getItem('gym_state_v1')
+ lift(row, layout.centers[0])
+ pointer(item, 'pointermove', { y: layout.centers[2] })
+ if (cancel === 'outside') pointer(item, 'pointerup', { x: layout.listRect.right + 20, y: layout.centers[2] })
+ if (cancel === 'lost') pointer(item, 'lostpointercapture', { y: layout.centers[2] })
+ if (cancel === 'escape') act(() => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })))
+ if (cancel === 'blur') act(() => window.dispatchEvent(new Event('blur')))
+ if (cancel === 'hidden') {
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' })
+ act(() => document.dispatchEvent(new Event('visibilitychange')))
+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' })
+ }
+ if (cancel === 'second') pointer(rows()[1].querySelector('.item'), 'pointerdown', { id: 8, y: layout.centers[1] })
+ expect(exercises().map(e => e.id), cancel).toEqual(['a', 'b', 'c'])
+ expect(localStorage.getItem('gym_state_v1'), cancel).toBe(before)
+ expect(host.querySelector('.is-dragging'), cancel).toBeNull()
+ }
+ })
+
+ it('ignores non-primary/control pointers and leaves accessible move buttons working', () => {
+ const layout = mount([configured('a'), configured('b')])
+ const down = host.querySelector('button[aria-label="Move down"]')
+ pointer(down, 'pointerdown', { y: layout.centers[0] })
+ act(() => vi.advanceTimersByTime(380))
+ expect(host.querySelector('.is-dragging')).toBeNull()
+ act(() => down.click())
+ expect(exercises().map(e => e.id)).toEqual(['b', 'a'])
+ const item = rows()[0].querySelector('.item')
+ pointer(item, 'pointerdown', { primary: false, y: layout.centers[0] })
+ act(() => vi.advanceTimersByTime(380))
+ expect(host.querySelector('.is-dragging')).toBeNull()
+ })
+
+ it('autoscrolls only after lift and stops frames on cancel', () => {
+ const layout = mount([configured('a'), configured('b'), configured('c'), configured('d')])
+ host.style.overflowY = 'auto'
+ Object.defineProperty(host, 'clientHeight', { configurable: true, value: 320 })
+ Object.defineProperty(host, 'scrollHeight', { configurable: true, value: 900 })
+ host.scrollTop = 100
+ vi.spyOn(host, 'getBoundingClientRect').mockImplementation(() => rect(0, 320))
+ const row = rows()[2], item = row.querySelector('.item')
+ pointer(item, 'pointerdown', { y: 310 })
+ act(() => vi.advanceTimersByTime(16))
+ expect(host.scrollTop).toBe(100)
+ act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS - 16 + 16))
+ expect(host.scrollTop).toBeGreaterThan(100)
+ pointer(item, 'pointercancel', { y: 310 })
+ const stopped = host.scrollTop
+ act(() => vi.advanceTimersByTime(64))
+ expect(host.scrollTop).toBe(stopped)
+ })
+
+ it('fails closed when row geometry disappears during an active drag', () => {
+ const layout = mount([configured('a'), configured('b'), configured('c')])
+ const row = rows()[0], item = row.querySelector('.item')
+ const before = localStorage.getItem('gym_state_v1')
+ lift(row, layout.centers[0])
+ rows()[1].getBoundingClientRect.mockReturnValue(undefined)
+ pointer(item, 'pointermove', { y: layout.centers[2] })
+ pointer(item, 'pointerup', { y: layout.centers[2] })
+ expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
+ expect(localStorage.getItem('gym_state_v1')).toBe(before)
+ expect(host.querySelector('.is-dragging')).toBeNull()
+ })
+
+ it('cleans pending and active gestures on unmount without late writes', () => {
+ const layout = mount([configured('a'), configured('b')])
+ const item = rows()[0].querySelector('.item')
+ const before = localStorage.getItem('gym_state_v1')
+ pointer(item, 'pointerdown', { y: layout.centers[0] })
+ act(() => root.unmount()); root = null
+ act(() => vi.advanceTimersByTime(1000))
+ expect(localStorage.getItem('gym_state_v1')).toBe(before)
+
+ const activeLayout = mount([configured('a'), configured('b')])
+ const activeItem = rows()[0].querySelector('.item')
+ const release = vi.fn()
+ activeItem.releasePointerCapture = release
+ lift(rows()[0], activeLayout.centers[0])
+ act(() => root.unmount()); root = null
+ act(() => vi.advanceTimersByTime(1000))
+ expect(release).toHaveBeenCalledWith(7)
+ expect(localStorage.getItem('gym_state_v1')).toBe(before)
+ })
+})
+
+describe('reorderRoutineUnit', () => {
+ it('splices complete units at canonical slots and cleans true orphans', () => {
+ const items = [configured('a', { sg: 'pair' }), configured('b', { sg: 'pair' }), configured('c', { sg: 'orphan' }), configured('d')]
+ expect(reorderRoutineUnit(items, 3, 1)).toBe(true)
+ expect(items.map(e => e.id)).toEqual(['a', 'b', 'd', 'c'])
+ expect(items[0].sg).toBe('pair'); expect(items[1].sg).toBe('pair'); expect(items[3].sg).toBeUndefined()
+ })
+})
diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx
index a8c492c4d..8adf9ada7 100644
--- a/frontend/src/views/RoutineEdit.jsx
+++ b/frontend/src/views/RoutineEdit.jsx
@@ -1,5 +1,5 @@
import { useNavigate, useParams } from 'react-router-dom'
-import { useEffect } from 'react'
+import { useEffect, useRef, useState } from 'react'
import { useStore } from '../store/useStore.js'
import { exOr } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
@@ -15,6 +15,266 @@ import { POLICIES_FOR, POLICY_NAME, POLICY_DESC } from '../lib/progression.js'
import BodyMap from '../components/BodyMap.jsx'
import { loadOfRoutine, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
+export const ROUTINE_LONG_PRESS_MS = 380
+export const ROUTINE_DRAG_SLOP = 8
+
+const clamp = (value, low, high) => Math.max(low, Math.min(high, value))
+
+// Slots are defined after removing the source unit, so a grouped run can never be split.
+export function reorderRoutineUnit(exercises, sourceIndex, targetSlot) {
+ if (!Array.isArray(exercises) || !exercises.length) return false
+ const units = supersetUnits(exercises)
+ const sourcePosition = units.findIndex(unit => unit.includes(sourceIndex))
+ if (sourcePosition < 0) return false
+ const remaining = units.filter((_, position) => position !== sourcePosition)
+ const slot = clamp(Number.isFinite(targetSlot) ? Math.trunc(targetSlot) : sourcePosition, 0, remaining.length)
+ if (slot === sourcePosition) return false
+ const source = units[sourcePosition]
+ const moved = exercises.splice(source[0], source.length)
+ const insertAt = remaining.slice(0, slot).reduce((count, unit) => count + unit.length, 0)
+ exercises.splice(insertAt, 0, ...moved)
+ cleanupSg(exercises)
+ return true
+}
+
+function unitGeometry(list, exercises) {
+ const rows = new Map([...list.querySelectorAll('[data-routine-row]')]
+ .map(row => [Number(row.dataset.exIndex), row]))
+ const units = supersetUnits(exercises)
+ const geometry = units.map((unit, position) => {
+ const rects = unit.map(index => rows.get(index)?.getBoundingClientRect()).filter(Boolean)
+ if (rects.length !== unit.length) return null
+ const top = Math.min(...rects.map(rect => rect.top))
+ const bottom = Math.max(...rects.map(rect => rect.bottom))
+ return { unit, position, top, bottom, center: top + (bottom - top) / 2 }
+ })
+ return geometry.every(Boolean) ? geometry : null
+}
+
+function scrollHostFor(node) {
+ for (let parent = node.parentElement; parent && parent !== document.body; parent = parent.parentElement) {
+ const overflowY = window.getComputedStyle(parent).overflowY
+ if (/(auto|scroll)/.test(overflowY) && parent.scrollHeight > parent.clientHeight) return parent
+ }
+ return window
+}
+
+function autoScrollStep(host, clientY) {
+ const edge = 64
+ const maxStep = 14
+ let top, bottom, scrollTop, maxScroll
+ if (host === window) {
+ const root = document.scrollingElement || document.documentElement
+ top = window.visualViewport?.offsetTop || 0
+ bottom = top + (window.visualViewport?.height || window.innerHeight || root.clientHeight)
+ scrollTop = window.scrollY || root.scrollTop || 0
+ maxScroll = Math.max(root.scrollHeight, document.body?.scrollHeight || 0) - (bottom - top)
+ } else {
+ const rect = host.getBoundingClientRect()
+ top = rect.top; bottom = rect.bottom
+ scrollTop = host.scrollTop; maxScroll = host.scrollHeight - host.clientHeight
+ }
+ if (clientY < top + edge && scrollTop > 0) return -Math.ceil(maxStep * clamp((top + edge - clientY) / edge, 0, 1))
+ if (clientY > bottom - edge && scrollTop < maxScroll) return Math.ceil(maxStep * clamp((clientY - bottom + edge) / edge, 0, 1))
+ return 0
+}
+
+function useRoutineReorder(exercises, onDrop) {
+ const listRef = useRef(null)
+ const gestureRef = useRef(null)
+ const exercisesRef = useRef(exercises)
+ const onDropRef = useRef(onDrop)
+ const suppressClickRef = useRef(false)
+ const suppressTimerRef = useRef(null)
+ const [drag, setDrag] = useState(null)
+ exercisesRef.current = exercises
+ onDropRef.current = onDrop
+ const hasRows = exercises.length > 0
+
+ useEffect(() => {
+ const list = listRef.current
+ if (!list) return undefined
+ let frame = null
+
+ const clearFrame = () => {
+ if (frame != null) window.cancelAnimationFrame(frame)
+ frame = null
+ }
+ const clearTimer = gesture => {
+ if (gesture?.timer != null) window.clearTimeout(gesture.timer)
+ if (gesture) gesture.timer = null
+ }
+ const matchesSnapshot = gesture => JSON.stringify(exercisesRef.current) === gesture.snapshot
+ const releaseCapture = gesture => {
+ const target = gesture?.captureTarget
+ if (!target?.releasePointerCapture) return
+ try { target.releasePointerCapture(gesture.pointerId) } catch { /* already released */ }
+ }
+ const finish = (gesture, commit, x = gesture?.lastX, y = gesture?.lastY) => {
+ if (!gesture || gestureRef.current !== gesture) return
+ clearTimer(gesture)
+ clearFrame()
+ gestureRef.current = null
+ if (!gesture.active) return
+ releaseCapture(gesture)
+ suppressClickRef.current = true
+ window.clearTimeout(suppressTimerRef.current)
+ suppressTimerRef.current = window.setTimeout(() => { suppressClickRef.current = false }, 500)
+ setDrag(null)
+ const rect = list.getBoundingClientRect()
+ const inside = x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom
+ const geometry = unitGeometry(list, exercisesRef.current)
+ if (commit && inside && geometry && matchesSnapshot(gesture) && gesture.targetSlot !== gesture.sourcePosition) {
+ onDropRef.current(gesture.sourceIndex, gesture.targetSlot)
+ }
+ }
+ const indicatorTop = (geometry, gesture, slot, listRect) => {
+ if (slot === gesture.sourcePosition) return clamp(gesture.sourceTop - listRect.top, 0, listRect.height)
+ const remaining = geometry.filter(unit => unit.position !== gesture.sourcePosition)
+ let top
+ if (slot <= 0) top = remaining[0]?.top ?? gesture.sourceTop
+ else if (slot >= remaining.length) top = remaining.at(-1)?.bottom ?? gesture.sourceBottom
+ else top = (remaining[slot - 1].bottom + remaining[slot].top) / 2
+ return clamp(top - listRect.top, 0, listRect.height)
+ }
+ const updateDrag = (gesture, x, y, schedule = true) => {
+ if (gestureRef.current !== gesture || !gesture.active || !matchesSnapshot(gesture)) {
+ if (gestureRef.current === gesture) finish(gesture, false)
+ return
+ }
+ const geometry = unitGeometry(list, exercisesRef.current)
+ if (!geometry) { finish(gesture, false); return }
+ const listRect = list.getBoundingClientRect()
+ const remaining = geometry.filter(unit => unit.position !== gesture.sourcePosition)
+ const probeY = clamp(y, listRect.top, listRect.bottom)
+ const moved = Math.hypot(x - gesture.startX, y - gesture.startY) > ROUTINE_DRAG_SLOP
+ const slot = moved ? remaining.reduce((count, unit) => count + (probeY > unit.center ? 1 : 0), 0) : gesture.sourcePosition
+ const rawDelta = y - gesture.grabOffset - gesture.sourceTop
+ const deltaY = clamp(rawDelta, listRect.top - gesture.sourceTop, listRect.bottom - gesture.sourceBottom)
+ gesture.lastX = x; gesture.lastY = y; gesture.targetSlot = slot
+ setDrag({ first: gesture.sourceUnit[0], last: gesture.sourceUnit.at(-1), deltaY, indicatorTop: indicatorTop(geometry, gesture, slot, listRect) })
+ if (schedule && frame == null) frame = window.requestAnimationFrame(runAutoScroll)
+ }
+ function runAutoScroll() {
+ frame = null
+ const gesture = gestureRef.current
+ if (!gesture?.active) return
+ const step = autoScrollStep(gesture.scrollHost, gesture.lastY)
+ if (!step) return
+ if (gesture.scrollHost === window) window.scrollBy(0, step)
+ else gesture.scrollHost.scrollTop += step
+ updateDrag(gesture, gesture.lastX, gesture.lastY, false)
+ if (gestureRef.current === gesture) frame = window.requestAnimationFrame(runAutoScroll)
+ }
+ const lift = gesture => {
+ if (gestureRef.current !== gesture || !matchesSnapshot(gesture)) return
+ const geometry = unitGeometry(list, exercisesRef.current)
+ const source = geometry?.find(unit => unit.unit.includes(gesture.sourceIndex))
+ if (!source) { finish(gesture, false); return }
+ gesture.active = true; gesture.timer = null
+ gesture.sourcePosition = source.position; gesture.sourceUnit = source.unit
+ gesture.sourceTop = source.top; gesture.sourceBottom = source.bottom
+ gesture.grabOffset = gesture.lastY - source.top; gesture.targetSlot = source.position
+ gesture.scrollHost = scrollHostFor(list)
+ gesture.captureTarget = gesture.downTarget
+ try { gesture.captureTarget.setPointerCapture?.(gesture.pointerId) } catch { /* unsupported */ }
+ suppressClickRef.current = true
+ window.clearTimeout(suppressTimerRef.current)
+ updateDrag(gesture, gesture.lastX, gesture.lastY)
+ }
+ const onPointerDown = event => {
+ const current = gestureRef.current
+ if (current) {
+ if (event.pointerId !== current.pointerId) finish(current, false)
+ return
+ }
+ if (event.isPrimary === false || (event.pointerType === 'mouse' && event.button !== 0)) return
+ const target = event.target
+ if (!target?.closest || target.closest('button,a,input,textarea,select,[data-nodrag]')) return
+ const row = target.closest('[data-routine-row]')
+ if (!row || !list.contains(row)) return
+ const sourceIndex = Number(row.dataset.exIndex)
+ if (!Number.isInteger(sourceIndex)) return
+ const gesture = {
+ pointerId: event.pointerId, sourceIndex, downTarget: target,
+ startX: event.clientX, startY: event.clientY, lastX: event.clientX, lastY: event.clientY,
+ snapshot: JSON.stringify(exercisesRef.current), active: false, timer: null,
+ }
+ gesture.timer = window.setTimeout(() => lift(gesture), ROUTINE_LONG_PRESS_MS)
+ gestureRef.current = gesture
+ }
+ const onPointerMove = event => {
+ const gesture = gestureRef.current
+ if (!gesture || event.pointerId !== gesture.pointerId) return
+ if (!gesture.active) {
+ if (Math.hypot(event.clientX - gesture.startX, event.clientY - gesture.startY) > ROUTINE_DRAG_SLOP) {
+ clearTimer(gesture); gestureRef.current = null
+ } else { gesture.lastX = event.clientX; gesture.lastY = event.clientY }
+ return
+ }
+ event.preventDefault()
+ updateDrag(gesture, event.clientX, event.clientY)
+ }
+ const onPointerUp = event => {
+ const gesture = gestureRef.current
+ if (!gesture || event.pointerId !== gesture.pointerId) return
+ if (gesture.active) event.preventDefault()
+ finish(gesture, gesture.active, event.clientX, event.clientY)
+ }
+ const onPointerCancel = event => {
+ const gesture = gestureRef.current
+ if (gesture && event.pointerId === gesture.pointerId) finish(gesture, false)
+ }
+ const onLostCapture = event => {
+ const gesture = gestureRef.current
+ if (gesture?.active && event.pointerId === gesture.pointerId) finish(gesture, false)
+ }
+ const cancelActive = () => finish(gestureRef.current, false)
+ const onKeyDown = event => {
+ if (event.key !== 'Escape' || !gestureRef.current) return
+ event.preventDefault(); cancelActive()
+ }
+ const onVisibility = () => { if (document.visibilityState === 'hidden') cancelActive() }
+ const onContextMenu = event => { if (gestureRef.current?.active && event.target.closest?.('[data-routine-row]')) event.preventDefault() }
+ const onDragStart = event => { if (event.target.closest?.('[data-routine-row]')) event.preventDefault() }
+
+ list.addEventListener('pointerdown', onPointerDown)
+ document.addEventListener('pointermove', onPointerMove, { passive: false })
+ document.addEventListener('pointerup', onPointerUp, { passive: false })
+ document.addEventListener('pointercancel', onPointerCancel)
+ document.addEventListener('lostpointercapture', onLostCapture)
+ document.addEventListener('keydown', onKeyDown)
+ document.addEventListener('visibilitychange', onVisibility)
+ list.addEventListener('contextmenu', onContextMenu)
+ list.addEventListener('dragstart', onDragStart)
+ window.addEventListener('blur', cancelActive)
+ return () => {
+ const gesture = gestureRef.current
+ clearTimer(gesture); clearFrame(); releaseCapture(gesture)
+ gestureRef.current = null; suppressClickRef.current = false
+ window.clearTimeout(suppressTimerRef.current)
+ list.removeEventListener('pointerdown', onPointerDown)
+ document.removeEventListener('pointermove', onPointerMove)
+ document.removeEventListener('pointerup', onPointerUp)
+ document.removeEventListener('pointercancel', onPointerCancel)
+ document.removeEventListener('lostpointercapture', onLostCapture)
+ document.removeEventListener('keydown', onKeyDown)
+ document.removeEventListener('visibilitychange', onVisibility)
+ list.removeEventListener('contextmenu', onContextMenu)
+ list.removeEventListener('dragstart', onDragStart)
+ window.removeEventListener('blur', cancelActive)
+ }
+ }, [hasRows])
+
+ const onClickCapture = event => {
+ if (!suppressClickRef.current) return
+ suppressClickRef.current = false
+ window.clearTimeout(suppressTimerRef.current)
+ event.preventDefault(); event.stopPropagation()
+ }
+ return { listRef, drag, onClickCapture }
+}
+
export default function RoutineEdit() {
const nav = useNavigate()
const { id } = useParams()
@@ -26,9 +286,11 @@ export default function RoutineEdit() {
// auto-backup on the way out (not per keystroke) covers the whole editing session, deletion
// included: this still unmounts after the delete button navigates away.
useEffect(() => () => useStore.getState().autoBackupNow(), [])
- if (!r) return null
-
const edit = fn => update(s => { fn(s.routines.find(x => x.id === id).ex) })
+ const reorder = useRoutineReorder(r?.ex || [], (sourceIndex, targetSlot) => {
+ edit(exercises => { reorderRoutineUnit(exercises, sourceIndex, targetSlot) })
+ })
+ if (!r) return null
const move = (i, dir) => edit(ex => { const j = i + dir; if (j < 0 || j >= ex.length) return;[ex[i], ex[j]] = [ex[j], ex[i]]; cleanupSg(ex) })
const toggleLink = i => edit(ex => {
if (i < 1) return
@@ -70,13 +332,17 @@ export default function RoutineEdit() {
</div>
</div>}
- {r.ex.length ? <div className="list">{r.ex.map((e, i) => {
+ {r.ex.length ? <div ref={reorder.listRef} onClickCapture={reorder.onClickCapture}
+ className={'list routine-list' + (reorder.drag ? ' is-reordering' : '')}>{r.ex.map((e, i) => {
// An unresolvable id is shown rather than skipped — hiding it left an entry you
// could neither see nor delete, but that still turned up in the workout.
const ex = exOr(e.id)
const noEquip = profile && !exAvailable(S, ex)
const linkedPrev = i > 0 && e.sg && r.ex[i - 1].sg === e.sg
- return <div key={i}>
+ 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>}
<div className={'item' + (inSS.has(i) ? ' in-ss' : '')} 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)
@@ -94,7 +360,8 @@ export default function RoutineEdit() {
</div>
</div>
</div>
- })}</div> : <div className="empty"><div className="ico"><Icon name="dumbbell" /></div>{t('No exercises yet — add your first one.')}</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>}
{/* Coverage of the routine as planned, so a gap shows up while you're building it
rather than after a month of training around it. */}