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
Follow-up to #286: a routine row still opens from the keyboard, its delete button slides into view when it has focus, and Plan, RoutineEdit and the Coach delete a routine through one helper (the Coach's missed a combined day)
Duarte Santos585f372559c1
diff --git a/frontend/src/components/SwipeToDelete.jsx b/frontend/src/components/SwipeToDelete.jsxindex bdec5ba32..4a5e89018 100644--- a/frontend/src/components/SwipeToDelete.jsx+++ b/frontend/src/components/SwipeToDelete.jsx@@ -25,11 +25,21 @@ import { t } from '../lib/i18n.js'// 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.const REVEAL = 76-export default function SwipeToDelete({ children, onDelete, deleteLabel, className, onClick }) {+export default function SwipeToDelete({ children, onDelete, deleteLabel, className, onClick, role, tabIndex, onKeyDown }) {const outerRef = useRef(null)const rowRef = 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@@ -80,8 +90,10 @@ export default function SwipeToDelete({ children, onDelete, deleteLabel, classNaonMouseLeave={() => { if (drag.current.startX !== null) end() }}><button className="swipe-del" aria-label={deleteLabel || t('Delete')}style={{ position: 'absolute', inset: '0 0 0 auto', width: REVEAL, background: 'var(--red)', color: '#fff', fontSize: 12, fontWeight: 600 }}+ 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}+ <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}diff --git a/frontend/src/lib/coach.js b/frontend/src/lib/coach.jsindex ea4f6e919..1487ebf11 100644--- a/frontend/src/lib/coach.js+++ b/frontend/src/lib/coach.js@@ -16,6 +16,7 @@ import { EXIDX } from './exercises.js'import { modeOf, isBw, isPerSide, cleanupSg } from './history.js'import { uid, todayISO, DAYN } from './format.js'import { mergePlan } from './plan-share.js'+import { deleteRoutine } from './routines.js'import { POLICIES } from './progression.js'import { t } from './i18n.js'@@ -502,18 +503,10 @@ const CHANGE_APPLY = {})},'remove-routine': (s, c) => {- const id = c.target.routineId- s.routines = s.routines.filter(r => r.id !== id)- // A week pointing at a routine that no longer exists reads as a rest day anyway; clearing- // it keeps the plan honest rather than merely harmless.- Object.keys(s.week || {}).forEach(d => { if (s.week[d] === id) delete s.week[d] })- // RoutineEdit does the same on a hand-deleted routine. A pointer left behind here is not- // merely inert: the day still counts as overridden, so it wears a "rescheduled" badge for good.- const dropped = {}- Object.keys(s.dayPlan || {}).forEach(iso => {- if (s.dayPlan[iso] === id) { dropped[iso] = id; delete s.dayPlan[iso] }- })- recordDayPlanDrops(s, dropped)+ // The same delete as Plan and RoutineEdit. It used to compare each weekday with ===, which+ // missed a combined day (a list) and left the deleted id on it. The week comes back from the+ // snapshot on a revert; the dropped reschedules are not in the snapshot, so they are recorded.+ recordDayPlanDrops(s, deleteRoutine(s, c.target.routineId))},'rename-routine': (s, c) => { need(findRoutine(s, c.target.routineId)).name = c.after },week: (s, c) => {diff --git a/frontend/src/lib/coach.test.js b/frontend/src/lib/coach.test.jsindex 6ad25cc60..274754934 100644--- a/frontend/src/lib/coach.test.js+++ b/frontend/src/lib/coach.test.js@@ -597,6 +597,16 @@ describe('removing a routine takes its per-date reschedules with it', () => {expect(revertLast(s)).toBe(true)expect(s.dayPlan['2099-01-01']).toBe('r2')})++ it('pulls it from a combined day too, and a revert puts the day back whole', () => {+ // The Coach compared each weekday with ===, so a combined day (a list) kept the deleted id.+ const S = state({ week: { 1: ['r1', 'r2'], 3: ['r2'] } })+ const s = apply(S, proposal([c]), ['c1'])+ expect(s.week[1]).toEqual(['r1'])+ expect(s.week[3]).toBeUndefined()+ expect(revertLast(s)).toBe(true)+ expect(s.week[1]).toEqual(['r1', 'r2'])+ })})describe('what the log keeps, so a decision never makes a proposal vanish', () => {diff --git a/frontend/src/lib/routines.js b/frontend/src/lib/routines.jsindex 13678f012..8ca81ae61 100644--- a/frontend/src/lib/routines.js+++ b/frontend/src/lib/routines.js@@ -13,3 +13,30 @@ export function copyRoutine(routine, suffix = 'Copy') {copy.name = m ? m[1] + ' (' + suffix + ' ' + ((Number(m[2]) || 1) + 1) + ')' : routine.name + ' (' + suffix + ')'return copy}++/**+ * Delete a routine and every pointer to it, in place on a store draft. A weekday holds a list of+ * routine ids, so the deleted one is pulled from each day and the key dropped when it empties+ * (never store []); a day that never named it is left exactly as it was. A per-date reschedule+ * (dayPlan) naming it goes too: left behind, the day still counts as overridden and wears a+ * "rescheduled" badge for good with no way to clear it.+ *+ * Plan's swipe, RoutineEdit's button and the Coach's remove-routine all delete through here, so+ * the next thing that learns to point at a routine is cleaned up in one place, not three.+ * Returns the dropped dayPlan entries ({ iso: id }), which the Coach records so a revert can put+ * them back.+ */+export function deleteRoutine(s, id) {+ s.routines = s.routines.filter(r => r.id !== id)+ Object.keys(s.week || {}).forEach(d => {+ const ids = [].concat(s.week[d])+ if (!ids.includes(id)) return+ const next = ids.filter(rid => rid !== id)+ if (next.length) s.week[d] = next; else delete s.week[d]+ })+ const dropped = {}+ Object.keys(s.dayPlan || {}).forEach(iso => {+ if (s.dayPlan[iso] === id) { dropped[iso] = id; delete s.dayPlan[iso] }+ })+ return dropped+}diff --git a/frontend/src/lib/routines.test.js b/frontend/src/lib/routines.test.jsindex 8f14ebca2..f5b8a530a 100644--- a/frontend/src/lib/routines.test.js+++ b/frontend/src/lib/routines.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest'-import { copyRoutine } from './routines.js'+import { copyRoutine, deleteRoutine } from './routines.js'const routine = {id: 'r1',@@ -88,3 +88,34 @@ describe('copyRoutine of a copy', () => {expect(copyRoutine({ id: 'r', name: 'Push (Kopie)', ex: [] }, 'Kopie').name).toBe('Push (Kopie 2)')})})++describe('deleteRoutine', () => {+ const store = () => ({+ routines: [{ id: 'r1', name: 'Push', ex: [] }, { id: 'r2', name: 'Pull', ex: [] }],+ // Monday combines both, Wednesday is Pull alone, Friday a legacy scalar day.+ week: { 1: ['r1', 'r2'], 3: ['r2'], 5: 'r1' },+ dayPlan: { '2099-01-01': 'r2', '2099-01-02': 'r1', '2099-01-03': 'rest' }+ })++ it('removes the routine and pulls it from every day, dropping a day it leaves empty', () => {+ const s = store()+ deleteRoutine(s, 'r2')+ expect(s.routines.map(r => r.id)).toEqual(['r1'])+ expect(s.week[1]).toEqual(['r1'])+ expect(s.week[3]).toBeUndefined()+ expect(s.week[5]).toBe('r1') // a day that never named it is left as it was+ })++ it('drops the reschedules naming it and returns them, leaving every other one', () => {+ const s = store()+ expect(deleteRoutine(s, 'r2')).toEqual({ '2099-01-01': 'r2' })+ expect(s.dayPlan).toEqual({ '2099-01-02': 'r1', '2099-01-03': 'rest' })+ })++ it('reads a legacy scalar day as a list of one', () => {+ const s = store()+ deleteRoutine(s, 'r1')+ expect(s.week[5]).toBeUndefined()+ expect(s.week[1]).toEqual(['r2'])+ })+})diff --git a/frontend/src/views/Plan.jsx b/frontend/src/views/Plan.jsxindex 7bb9c84a6..d1b7d08ca 100644--- a/frontend/src/views/Plan.jsx+++ b/frontend/src/views/Plan.jsx@@ -6,6 +6,7 @@ import { dayAssignSheet, dayAddRoutineSheet, starterPlanSheet, planToolsSheet, cimport Icon from '../components/Icon.jsx'import { Button } from '../components/ui.jsx'import SwipeToDelete from '../components/SwipeToDelete.jsx'+import { deleteRoutine } from '../lib/routines.js'import { tappable } from '../lib/use-sheet-keyboard.js'import { glyphOf, DEFAULT_GLYPH } from '../lib/glyphs.js'import { DEMO } from '../lib/demo.js'@@ -47,19 +48,11 @@ export default function Plan() {if (next.length) s.week[d] = next; else delete s.week[d]})- // Same delete RoutineEdit's own "Delete routine" button does (id, name confirmed there) —- // duplicated here rather than shared, since RoutineEdit's version also navigates back to- // /plan afterwards, which this screen is already on.- const deleteRoutine = r => confirmSheet({+ // The same confirmation and the same delete as RoutineEdit's "Delete routine" button, minus+ // its navigation back to /plan, which this screen already is.+ const confirmDelete = r => confirmSheet({title: t('Delete routine?'), message: t('“{0}” and its exercises will be removed.', r.name), confirmText: t('Delete'), danger: true,- onConfirm: () => update(s => {- s.routines = s.routines.filter(x => x.id !== r.id)- Object.keys(s.week).forEach(k => {- const next = [].concat(s.week[k]).filter(rid => rid !== r.id)- if (next.length) s.week[k] = next; else delete s.week[k]- })- Object.keys(s.dayPlan).forEach(k => { if (s.dayPlan[k] === r.id) delete s.dayPlan[k] })- })+ onConfirm: () => update(s => { deleteRoutine(s, r.id) })})return <>@@ -109,7 +102,7 @@ export default function Plan() {<Button size="sm" variant="tinted" icon="plus" onClick={addRoutine}>{t('New')}</Button></div>{S.routines.length ? <div className="list">{S.routines.map((r, i) => <SwipeToDelete key={r.id} className="item"- deleteLabel={t('Delete routine')} onDelete={() => deleteRoutine(r)} onClick={() => nav('/plan/r/' + r.id)}>+ deleteLabel={t('Delete routine')} onDelete={() => confirmDelete(r)} {...tappable(() => nav('/plan/r/' + r.id))}><span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span><div className="grow"><div className="tt">{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>{/* The order of this list is the order of `S.routines`, and every other screen reads thediff --git a/frontend/src/views/Plan.swipe-delete.test.jsx b/frontend/src/views/Plan.swipe-delete.test.jsxnew file mode 100644index 000000000..40d3a77a9--- /dev/null+++ b/frontend/src/views/Plan.swipe-delete.test.jsx@@ -0,0 +1,66 @@+// @vitest-environment happy-dom+// PR #286 put the routine rows inside SwipeToDelete. The rows used to be tappable() — a button to+// the keyboard, opened with Enter or Space — and the swipe must not take that away, nor leave a+// delete button in the tab order that nobody can see.+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { useStore } from '../store/useStore.js'+import Plan from './Plan.jsx'++const nav = vi.fn()+vi.mock('react-router-dom', () => ({ useNavigate: () => nav }))+vi.mock('../sheets.jsx', () => ({+ dayAssignSheet: vi.fn(), dayAddRoutineSheet: vi.fn(), starterPlanSheet: vi.fn(), planToolsSheet: vi.fn(),+ // Say yes straight away: the sheet itself is not what is under test.+ confirmSheet: ({ onConfirm }) => onConfirm(),+}))++const routine = (id, name) => ({ id, name, emoji: null, ex: [{ id: '0025' }] })+let host, root+beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ nav.mockClear()+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)+ useStore.setState(s => ({ S: { ...s.S,+ routines: [routine('a', 'Push A'), routine('b', 'Pull A')],+ week: { 1: ['a', 'b'], 3: ['b'] }, dayPlan: { '2099-01-01': 'b' } }, user: null }))+ act(() => root.render(<Plan />))+})+afterEach(() => { act(() => root.unmount()); host.remove() })++const row = name => [...host.querySelectorAll('.item[role="button"]')].find(e => e.querySelector('.tt')?.textContent === name)+const del = name => row(name).parentElement.querySelector('button.swipe-del')++describe('routine rows after swipe-to-delete', () => {+ it('stay a keyboard button that opens the routine on Enter and on Space', () => {+ const r = row('Pull A')+ expect(r.tabIndex).toBe(0)+ act(() => { r.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) })+ expect(nav).toHaveBeenLastCalledWith('/plan/r/b')+ act(() => { row('Push A').dispatchEvent(new KeyboardEvent('keydown', { key: ' ', bubbles: true })) })+ expect(nav).toHaveBeenLastCalledWith('/plan/r/a')+ })++ it('still open the routine on a plain click', () => {+ act(() => { row('Push A').dispatchEvent(new MouseEvent('click', { bubbles: true })) })+ expect(nav).toHaveBeenLastCalledWith('/plan/r/a')+ })++ it('slide open while the delete button has focus, and close when focus moves on', () => {+ const r = row('Push A')+ act(() => { del('Push A').focus() })+ expect(r.style.transform).toBe('translateX(-76px)')+ act(() => { r.focus() })+ expect(r.style.transform).toBe('translateX(0px)')+ })++ it('delete through the shared helper: the routine, its days and its reschedules', () => {+ act(() => { del('Pull A').dispatchEvent(new MouseEvent('click', { bubbles: true })) })+ const S = useStore.getState().S+ expect(S.routines.map(r => r.id)).toEqual(['a'])+ expect(S.week).toEqual({ 1: ['a'] })+ expect(S.dayPlan).toEqual({})+ expect(nav).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsxindex b6b18d103..03e018306 100644--- a/frontend/src/views/RoutineEdit.jsx+++ b/frontend/src/views/RoutineEdit.jsx@@ -13,7 +13,7 @@ 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 { copyRoutine } from '../lib/routines.js'+import { copyRoutine, deleteRoutine } from '../lib/routines.js'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'@@ -448,16 +448,7 @@ export default function RoutineEdit() {<Button variant="danger" onClick={() => confirmSheet({title: t('Delete routine?'), message: t('“{0}” and its exercises will be removed.', r.name), confirmText: t('Delete'), danger: true,onConfirm: () => {- update(s => {- s.routines = s.routines.filter(x => x.id !== id)- // A weekday holds a routine-id list: pull the deleted id from each day, drop the- // key when it empties (never store []). dayPlan stays scalar.- Object.keys(s.week).forEach(k => {- const next = [].concat(s.week[k]).filter(rid => rid !== id)- if (next.length) s.week[k] = next; else delete s.week[k]- })- Object.keys(s.dayPlan).forEach(k => { if (s.dayPlan[k] === id) delete s.dayPlan[k] })- })+ update(s => { deleteRoutine(s, id) })nav('/plan')}})}>{t('Delete routine')}</Button>