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.

Plan: swipe a routine left to delete it with Undo, right to duplicate it; swipe a routine out of the loop with Undo; the edit-mode minus gets the same Undo instead of a confirm

Duarte Santos938d763bc6ef
diff --git a/frontend/src/index.css b/frontend/src/index.css
index 1f7cab562..98c36e0bc 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -1091,6 +1091,8 @@ body.chips-dragging *{cursor:inherit}
pan-y leaves vertical scroll to the browser and hands sideways moves to the row. */
.swrow{position:relative;overflow:hidden;border-radius:10px;touch-action:pan-y;-webkit-touch-callout:none}
.swrow.dragging{-webkit-user-select:none;user-select:none}
+/* Plan's lists (v1.3.11): the row is a whole .item card, so the swipe clips to the card's corners */
+.swrow.swrow-item{border-radius:var(--r-card)}
.swfront{position:relative;z-index:1;background:var(--surface);will-change:transform}
.swpane{position:absolute;top:0;bottom:0;width:0;overflow:hidden;z-index:0}
.swpane.del{inset-inline-end:0;background:color-mix(in srgb,var(--red) 22%,var(--surface))}
diff --git a/frontend/src/lib/routines.js b/frontend/src/lib/routines.js
index b820fc0e5..d956e5e1b 100644
--- a/frontend/src/lib/routines.js
+++ b/frontend/src/lib/routines.js
@@ -45,6 +45,60 @@ export function deleteRoutine(s, id) {
return dropped
}
+/**
+ * Everything deleteRoutine is about to take away, so an Undo can put the routine back where it
+ * was (Plan's swipe and minus, v1.3.11): the routine itself and its place in the list, its place
+ * on each weekday that holds it, the reschedules that name it, and its places in the saved loop
+ * and the live queue. deleteRoutine leaves the last two alone (an id that no longer resolves is
+ * skipped where they are read), but a save in between may have dropped it, so they are kept too.
+ * Null when there is no such routine.
+ */
+export function routineSnapshot(S, id) {
+ const index = (S.routines || []).findIndex(r => r.id === id)
+ if (index < 0) return null
+ const week = {}
+ Object.keys(S.week || {}).forEach(d => {
+ const at = [].concat(S.week[d]).indexOf(id)
+ if (at >= 0) week[d] = at
+ })
+ const dayPlan = {}
+ Object.keys(S.dayPlan || {}).forEach(iso => { if (S.dayPlan[iso] === id) dayPlan[iso] = id })
+ const seqAt = Array.isArray(S.rotation?.sequence) ? S.rotation.sequence.indexOf(id) : -1
+ const queueAt = Array.isArray(S.queue?.ids) ? S.queue.ids.indexOf(id) : -1
+ return { routine: structuredClone(S.routines[index]), index, week, dayPlan, seqAt, queueAt }
+}
+
+const putBack = (list, at, id) => {
+ if (list.includes(id)) return list
+ const next = list.slice()
+ next.splice(Math.min(at, next.length), 0, id)
+ return next
+}
+
+/**
+ * Undo for deleteRoutine, in place on a store draft, from a routineSnapshot taken just before it.
+ * Each pointer goes back to its old position, or to the end of a list that has since got
+ * shorter; a reschedule only where that date has not been planned again since. False, and nothing
+ * changed, when a routine with that id exists again (another device put it back first).
+ */
+export function restoreRoutine(s, snap) {
+ if (!snap?.routine || !Array.isArray(s.routines)) return false
+ const id = snap.routine.id
+ if (s.routines.some(r => r.id === id)) return false
+ s.routines.splice(Math.min(snap.index, s.routines.length), 0, structuredClone(snap.routine))
+ if (Object.keys(snap.week).length) s.week = s.week || {}
+ Object.entries(snap.week).forEach(([d, at]) => {
+ s.week[d] = putBack(s.week[d] == null ? [] : [].concat(s.week[d]), at, id)
+ })
+ if (Object.keys(snap.dayPlan).length) s.dayPlan = s.dayPlan || {}
+ Object.keys(snap.dayPlan).forEach(iso => { if (s.dayPlan[iso] == null) s.dayPlan[iso] = id })
+ if (snap.seqAt >= 0 && Array.isArray(s.rotation?.sequence)) {
+ s.rotation = { ...s.rotation, sequence: putBack(s.rotation.sequence, snap.seqAt, id) }
+ }
+ if (snap.queueAt >= 0 && Array.isArray(s.queue?.ids)) s.queue = { ...s.queue, ids: putBack(s.queue.ids, snap.queueAt, id) }
+ return true
+}
+
/**
* A routine slot with another exercise in it (#110): the machine you planned around is gone, or
* a variation takes over the lift for a block. The slot keeps its place and what was set up for
diff --git a/frontend/src/views/Plan.jsx b/frontend/src/views/Plan.jsx
index a9bd10615..6e10cd3a0 100644
--- a/frontend/src/views/Plan.jsx
+++ b/frontend/src/views/Plan.jsx
@@ -1,6 +1,7 @@
import { useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
import { DAYN, DAYS, weekOrder, weekStartOf, uid, exCount, routineCount, todayISO, fmtDate } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import {
@@ -9,8 +10,9 @@ import {
} from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button, Row, Section, Segmented } from '../components/ui.jsx'
-import SwipeToDelete from '../components/SwipeToDelete.jsx'
-import { deleteRoutine } from '../lib/routines.js'
+import SwipeRow from '../components/SwipeRow.jsx'
+import { copyRoutine, deleteRoutine, restoreRoutine, routineSnapshot } from '../lib/routines.js'
+import { workoutControls } from '../lib/workout-controls.js'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { useListReorder, moved } from '../lib/use-list-reorder.js'
import { glyphOf, DEFAULT_GLYPH } from '../lib/glyphs.js'
@@ -32,6 +34,63 @@ const readView = () => {
try { return localStorage.getItem(PLAN_VIEW_KEY) === 'routines' ? 'routines' : 'schedule' } catch { return 'schedule' }
}
+/* Undo for Plan's two removals (v1.3.11). Both go through the store's normal update, so sync
+ sees an ordinary edit (a routine put back clears its own removal stamp, lib/sync-merge.js). */
+
+/** Deletes a routine with an Undo toast in place of a confirm: the toast puts it back exactly,
+ * list place, weekdays, reschedules and loop included (lib/routines.js routineSnapshot). */
+export function deleteRoutineWithUndo(id) {
+ const st = useStore.getState()
+ const snap = routineSnapshot(st.S, id)
+ if (!snap) return false
+ st.update(s => { deleteRoutine(s, id) })
+ useUI.getState().toast(t('“{0}” gone.', snap.routine.name), { action: t('Undo'), onAction: () => undoDeleteRoutine(snap) })
+ return true
+}
+export function undoDeleteRoutine(snap) {
+ let ok = false
+ useStore.getState().update(s => { ok = restoreRoutine(s, snap) })
+ return ok
+}
+
+/** Takes a routine out of the loop (the swipe and the edit-mode minus), with an Undo. The removal
+ * is the editor's own (`setSeq`), which may sweep the routine's future pins or roll a finished
+ * round over; so while the loop is still what the removal left, Undo puts the loop, the round and
+ * the swept pins back as they were. Once something else changed the loop, it just slots the
+ * routine back in at its old place, through the same save an edit uses. */
+export function takeOutOfLoop(id, setSeq, seq, label) {
+ const at = seq.indexOf(id)
+ if (at < 0) return false
+ const before = useStore.getState().S
+ const snap = structuredClone({ rotation: before.rotation ?? null, queue: before.queue ?? null, dayPlan: before.dayPlan ?? {} })
+ setSeq(seq.filter(x => x !== id))
+ const after = useStore.getState().S
+ const mark = JSON.stringify([after.rotation ?? null, after.queue ?? null])
+ const name = before.routines.find(r => r.id === id)?.name ?? id
+ useUI.getState().toast(t('“{0}” is out of the loop.', name), { action: t('Undo'), onAction: () => undoTakeOut({ id, at, label, snap, mark }) })
+ return true
+}
+export function undoTakeOut({ id, at, label, snap, mark }) {
+ useStore.getState().update(s => {
+ if (!s.routines.some(r => r.id === id)) return
+ if (JSON.stringify([s.rotation ?? null, s.queue ?? null]) === mark) {
+ s.rotation = snap.rotation
+ s.queue = snap.queue
+ const pins = Object.entries(snap.dayPlan).filter(([iso]) => s.dayPlan?.[iso] == null)
+ if (pins.length) s.dayPlan = { ...(s.dayPlan || {}), ...Object.fromEntries(pins) }
+ return
+ }
+ const ids = queueOf(s)?.ids ?? rotationIds(s)
+ if (ids.includes(id)) return
+ const next = ids.slice()
+ next.splice(Math.min(at, next.length), 0, id)
+ saveRotation(s, next, s.queue?.label || s.rotation?.label || label)
+ })
+}
+
+// The flash a row lands with when a swipe brought it (a duplicate, an undo): one per new value.
+let flashSeq = 0
+
export default function Plan() {
const nav = useNavigate()
const S = useStore(s => s.S)
@@ -131,6 +190,8 @@ function Schedule({ S, update, nav, mode }) {
}
})
const loopReorder = useListReorder(seq.length, (from, to) => setSeq(moved(seq, from, to)))
+ const takeOut = id => takeOutOfLoop(id, setSeq, seq, seqLabel)
+ const swipe = workoutControls(S).swipeSets && !external
const addToSeq = () => menuSheet({
title: t('Add to the rotation'),
items: S.routines.filter(r => !seq.includes(r.id)).map(r => ({
@@ -225,9 +286,12 @@ function Schedule({ S, update, nav, mode }) {
{seq.map((id, i) => {
const r = routineOf(id)
const item = qv?.items[i]
- return <div key={id} data-reorder-row className={'item rotation-row' + (item?.state === 'done' ? ' is-done' : '')} style={loopReorder.rowStyle(i)}>
+ // The loop's swipe is remove-only (v1.3.11): a routine is in the loop once, so there is
+ // nothing to copy. The row the reorder measures is the swipe's outer element.
+ const reorderProps = { 'data-reorder-row': '', style: loopReorder.rowStyle(i) }
+ const row = <div {...(swipe ? {} : { key: id, ...reorderProps })} className={'item rotation-row' + (item?.state === 'done' ? ' is-done' : '')}>
{editing && <button className="plan-minus" aria-label={t('Remove {0}', r?.name ?? id)} title={t('Remove')}
- onClick={() => setSeq(seq.filter(x => x !== id))}><Icon name="minus" /></button>}
+ onClick={() => takeOut(id)}><Icon name="minus" /></button>}
<span className={'plan-order' + (item?.state === 'next' ? ' next' : '')}>{item?.state === 'done' ? <Icon name="check" /> : i + 1}</span>
<span className="lrow-i"><Icon name={glyphOf(r?.emoji)} /></span>
<div className="grow" style={{ minWidth: 0 }}>
@@ -237,6 +301,10 @@ function Schedule({ S, update, nav, mode }) {
{editing && seq.length > 1 && <button className="plan-handle" aria-label={t('Move {0}', r?.name ?? id)} title={t('Drag to reorder')}
{...loopReorder.handle(i)}><Icon name="chevronsUpDown" /></button>}
</div>
+ return swipe
+ ? <SwipeRow key={id} {...reorderProps} className="swrow-item" deleteLabel={t('Remove')} deleteIcon="minus"
+ onDelete={() => takeOut(id)}>{row}</SwipeRow>
+ : row
})}
</div> : <div className="empty">{t('No rotation yet. Add routines in the order you want to train them. The first one you haven’t logged stays up next.')}</div>}
{seq.length > 0 && <p className="sect-f">
@@ -276,6 +344,8 @@ function Schedule({ S, update, nav, mode }) {
function Routines({ S, update, nav }) {
const [edit, setEdit] = useState(false)
+ const [flash, setFlash] = useState(null)
+ const swipe = workoutControls(S).swipeSets
const routines = S.routines
// The order of this list is the order of `S.routines`, and every other screen reads the same
// array (the Start screen, the day sheets, the routine pickers), so moving a routine here moves
@@ -291,12 +361,20 @@ function Routines({ S, update, nav }) {
update(s => { s.routines.push(r) })
nav('/plan/r/' + r.id)
}
- // 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 => { deleteRoutine(s, r.id) })
- })
+ // The same delete as RoutineEdit's "Delete routine" button (lib/routines.js), with an Undo in
+ // place of its confirm (v1.3.11): the swipe and the edit-mode minus both land here.
+ const remove = r => deleteRoutineWithUndo(r.id)
+ // The swipe's other side: a copy right below the original, named the way "Copy routine" names
+ // one, and staying on this list rather than opening it.
+ const duplicate = r => {
+ const copy = copyRoutine(r, t('Copy'))
+ update(s => {
+ const at = s.routines.findIndex(x => x.id === r.id)
+ s.routines.splice(at < 0 ? s.routines.length : at + 1, 0, copy)
+ })
+ setFlash({ id: copy.id, n: ++flashSeq })
+ useUI.getState().toast(t('Copied as “{0}”.', copy.name))
+ }
// The weekdays a routine is on, short, in the order the week runs.
const order = weekOrder(weekStartOf(S))
const daysOf = id => order.filter(d => [].concat(S.week[d] || []).includes(id)).map(d => t(DAYS[d]))
@@ -313,17 +391,26 @@ function Routines({ S, update, nav }) {
{edit
? <div className="list routine-list plan-routines is-editing" ref={reorder.listRef}>{routines.map((r, i) =>
<div key={r.id} data-reorder-row className="item plan-routine" style={reorder.rowStyle(i)}>
- <button className="plan-minus" aria-label={t('Delete {0}', r.name)} title={t('Delete routine')} onClick={() => confirmDelete(r)}><Icon name="minus" /></button>
+ <button className="plan-minus" aria-label={t('Delete {0}', r.name)} title={t('Delete routine')} onClick={() => remove(r)}><Icon name="minus" /></button>
<span className="lrow-i"><Icon name={glyphOf(r.emoji)} /></span>
<div className="grow"><div className="tt">{r.name}</div><div className="ss">{sub(r)}</div></div>
{routines.length > 1 && <button className="plan-handle" aria-label={t('Move {0}', r.name)} title={t('Drag to reorder')}
{...reorder.handle(i)}><Icon name="chevronsUpDown" /></button>}
</div>)}</div>
- : <div className="list routine-list plan-routines">{routines.map(r => <SwipeToDelete key={r.id} className="item plan-routine"
- 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">{sub(r)}</div></div>
- <Icon name="chevronRight" className="chev" /></SwipeToDelete>)}</div>}
+ : <div className="list routine-list plan-routines">{routines.map(r => {
+ const row = <div key={r.id} className="item plan-routine" {...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">{sub(r)}</div></div>
+ <Icon name="chevronRight" className="chev" /></div>
+ // Swipe (v1.3.11, Settings → Swipe actions): toward the start deletes with an Undo,
+ // toward the end duplicates. Edit's minus and the routine's own page stay the way in
+ // for a keyboard and a screen reader.
+ return swipe
+ ? <SwipeRow key={r.id} className="swrow-item" copyLabel={t('Duplicate')}
+ onDelete={() => remove(r)} onCopy={() => duplicate(r)}
+ flash={flash?.id === r.id ? flash.n : 0}>{row}</SwipeRow>
+ : row
+ })}</div>}
<p className="sect-f">{edit ? t('Drag to reorder. Tap the minus to delete.') : t('Tap a routine to edit it. Reorder and delete are behind Edit.')}</p>
</> : <>
<div className="empty"><div className="ico"><Icon name="clipboard" /></div>{t('No routines yet.')}<br />{t('Make one, or grab the starter plan to get going.')}</div>
diff --git a/frontend/src/views/Plan.routine-order.test.jsx b/frontend/src/views/Plan.routine-order.test.jsx
index 976bde749..ef8af5cac 100644
--- a/frontend/src/views/Plan.routine-order.test.jsx
+++ b/frontend/src/views/Plan.routine-order.test.jsx
@@ -8,6 +8,7 @@ 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 { useUI } from '../store/useUI.js'
import Plan from './Plan.jsx'
const nav = vi.fn()
@@ -111,16 +112,19 @@ describe('routine order', () => {
expect(stored()).toEqual(['Push A', 'Pull A', 'Legs A'])
})
- it('the red minus deletes only after the confirmation, routine, days and all', () => {
+ // v1.3.11: an Undo in place of the confirmation, the same as the row's swipe (Plan.swipe.test.jsx).
+ it('the red minus deletes at once, routine, days and all, and Undo puts it all back', () => {
mount()
edit()
+ const week = useStore.getState().S.week
click(rows()[1].querySelector('button[aria-label="Delete Pull A"]'))
- expect(stored()).toEqual(['Push A', 'Pull A', 'Legs A'])
- expect(confirmSheet).toHaveBeenCalledTimes(1)
- expect(confirmSheet.mock.calls[0][0].message).toContain('Pull A')
- act(() => confirmSheet.mock.calls[0][0].onConfirm())
+ expect(confirmSheet).not.toHaveBeenCalled()
expect(stored()).toEqual(['Push A', 'Legs A'])
expect(useStore.getState().S.week).toEqual({})
+ expect(useUI.getState().toastMsg).toBe('“Pull A” gone.')
+ act(() => useUI.getState().runToastAction())
+ expect(stored()).toEqual(['Push A', 'Pull A', 'Legs A'])
+ expect(useStore.getState().S.week).toEqual(week)
})
it('leaves the handle out when there is nothing to reorder', () => {
diff --git a/frontend/src/views/Plan.swipe-delete.test.jsx b/frontend/src/views/Plan.swipe-delete.test.jsx
deleted file mode 100644
index 66419bec5..000000000
--- a/frontend/src/views/Plan.swipe-delete.test.jsx
+++ /dev/null
@@ -1,100 +0,0 @@
-// @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()
- localStorage.setItem('gym_plan_view', 'routines') // the Routines view (v1.3.11)
- 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(); localStorage.removeItem('gym_plan_view') })
-
-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)')
- })
-
- // QA 1.3.9: at rest the red button showed as a hairline round the row's rounded corners in
- // dark mode. It is transparent until the row moves, and again once it has slid shut.
- it('keep the red button invisible while shut, and show it while open', () => {
- vi.useFakeTimers()
- try {
- const r = row('Push A'), b = del('Push A')
- expect(b.style.opacity).toBe('0')
- act(() => { b.focus() })
- expect(b.style.opacity).toBe('1')
- act(() => { r.focus() })
- expect(b.style.opacity).toBe('1') // still visible while the row slides back
- act(() => { vi.advanceTimersByTime(250) })
- expect(b.style.opacity).toBe('0')
- } finally { vi.useRealTimers() }
- })
-
- // In Arabic the button sits at the row's inline end, the left, so the row slides the other way.
- it('slide towards the right in a right-to-left language, where the button is on the left', () => {
- document.documentElement.dir = 'rtl'
- try {
- const r = row('Push A')
- act(() => { del('Push A').focus() })
- expect(r.style.transform).toBe('translateX(76px)')
- const start = new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 100, clientY: 10 })
- act(() => { r.focus() })
- expect(r.style.transform).toBe('translateX(0px)')
- act(() => { r.dispatchEvent(start) })
- act(() => { r.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, buttons: 1, clientX: 180, clientY: 12 })) })
- act(() => { r.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, clientX: 180, clientY: 12 })) })
- expect(r.style.transform).toBe('translateX(76px)')
- } finally { document.documentElement.dir = '' }
- })
-
- 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/Plan.swipe.test.jsx b/frontend/src/views/Plan.swipe.test.jsx
new file mode 100644
index 000000000..0550e3ce3
--- /dev/null
+++ b/frontend/src/views/Plan.swipe.test.jsx
@@ -0,0 +1,237 @@
+// @vitest-environment happy-dom
+// Swipe actions on Plan (v1.3.11). The routines list: toward the start deletes with an Undo (no
+// confirm), toward the end duplicates. The loop: toward the start takes the routine out, with an
+// Undo, and nothing on the other side. Weekday rows do not swipe. The rows stay keyboard buttons.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { DEF, useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { closeOpenRow } from '../lib/use-swipe-row.js'
+import { restoreRoutine, routineSnapshot, deleteRoutine } from '../lib/routines.js'
+import Plan from './Plan.jsx'
+
+const nav = vi.fn()
+vi.mock('react-router-dom', () => ({ useNavigate: () => nav }))
+vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), chime: vi.fn(), vibrate: vi.fn(), alertBuzz: vi.fn(), unlock: vi.fn() }))
+vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})), beacon: vi.fn(), appBase: () => '/' }))
+const confirmSheet = vi.hoisted(() => vi.fn())
+vi.mock('../sheets.jsx', () => ({
+ dayAssignSheet: vi.fn(), starterPlanSheet: vi.fn(), menuSheet: vi.fn(), confirmSheet,
+ planHasRoutines: () => true, exportPlanFile: vi.fn(), printWholePlan: vi.fn(), importPlanFile: vi.fn(),
+}))
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+const clone = value => JSON.parse(JSON.stringify(value))
+const routine = (id, name) => ({ id, name, emoji: null, ex: [{ id: '0025' }] })
+let host, root, widthSpy
+
+function mount(view, extra = {}) {
+ localStorage.setItem('gym_plan_view', view)
+ const S = clone(DEF)
+ Object.assign(S, {
+ routines: [routine('a', 'Push A'), routine('b', 'Pull A'), routine('c', 'Legs')],
+ week: { 1: ['a', 'b'], 3: ['b'], 5: ['c'] }, dayPlan: { '2099-01-01': 'b' },
+ }, extra)
+ useStore.setState({ S, user: null })
+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
+ act(() => root.render(<Plan />))
+}
+const S = () => useStore.getState().S
+const swrows = () => [...host.querySelectorAll('.swrow')]
+const rowOf = name => swrows().find(r => r.querySelector('.tt')?.textContent === name)
+function pointer(target, type, x, y = 300) {
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ Object.assign(event, { pointerId: 7, pointerType: 'touch', clientX: x, clientY: y })
+ act(() => { target.dispatchEvent(event) })
+}
+const click = target => act(() => { target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })) })
+function swipe(target, x0, x1) {
+ pointer(target, 'pointerdown', x0)
+ pointer(target, 'pointermove', (x0 + x1) / 2)
+ pointer(target, 'pointermove', x1)
+ pointer(target, 'pointerup', x1)
+ click(target)
+ act(() => vi.advanceTimersByTime(800))
+}
+const undo = () => act(() => useUI.getState().runToastAction())
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ nav.mockClear(); confirmSheet.mockClear()
+ document.documentElement.dir = 'ltr'
+ useUI.setState({ sheets: [], toastMsg: '', toastAction: null })
+ // happy-dom lays nothing out: a phone's width, so the thresholds mean what they do there.
+ widthSpy = vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(360)
+})
+afterEach(() => {
+ closeOpenRow(true)
+ act(() => root.unmount()); host.remove()
+ localStorage.removeItem('gym_plan_view')
+ widthSpy.mockRestore()
+ vi.clearAllTimers(); vi.useRealTimers()
+})
+
+describe('the routines list', () => {
+ it('rows stay keyboard buttons that open the routine, with both panes out of reach while shut', () => {
+ mount('routines')
+ expect(swrows()).toHaveLength(3)
+ const r = rowOf('Pull A').querySelector('.item')
+ expect(r.getAttribute('role')).toBe('button')
+ expect(r.tabIndex).toBe(0)
+ act(() => { r.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) })
+ expect(nav).toHaveBeenLastCalledWith('/plan/r/b')
+ click(rowOf('Push A').querySelector('.item'))
+ expect(nav).toHaveBeenLastCalledWith('/plan/r/a')
+ const panes = rowOf('Push A').querySelectorAll('.swpane')
+ expect(panes).toHaveLength(2)
+ for (const pane of panes) {
+ expect(pane.getAttribute('aria-hidden')).toBe('true')
+ expect(pane.hasAttribute('inert')).toBe(true)
+ expect(pane.querySelector('button').tabIndex).toBe(-1)
+ }
+ expect(rowOf('Push A').querySelector('.swpane.cp').textContent).toBe('Duplicate')
+ })
+
+ it('a long swipe toward the start deletes without a confirm, and Undo puts everything back', () => {
+ mount('routines')
+ const before = clone(S())
+ swipe(rowOf('Pull A'), 330, 60)
+ expect(confirmSheet).not.toHaveBeenCalled()
+ expect(S().routines.map(r => r.id)).toEqual(['a', 'c'])
+ expect(S().week).toEqual({ 1: ['a'], 5: ['c'] })
+ expect(S().dayPlan).toEqual({})
+ expect(useUI.getState().toastMsg).toBe('“Pull A” gone.')
+ expect(nav).not.toHaveBeenCalled()
+
+ undo()
+ // the same routines in the same order; the store stamps the one put back as an edit (_ts)
+ expect(S().routines.map(({ _ts, ...r }) => r)).toEqual(before.routines)
+ expect(S().routines[1]._ts).toBeGreaterThan(0)
+ expect(S().week).toEqual(before.week)
+ expect(S().dayPlan).toEqual(before.dayPlan)
+ expect(rowOf('Pull A')).toBeTruthy()
+ })
+
+ it('a long swipe toward the end duplicates right below, and stays on the list', () => {
+ mount('routines')
+ swipe(rowOf('Push A'), 100, 330)
+ expect(S().routines.map(r => r.name)).toEqual(['Push A', 'Push A (Copy)', 'Pull A', 'Legs'])
+ const copy = S().routines[1]
+ expect(copy.id).not.toBe('a')
+ expect(copy.ex).toEqual(S().routines[0].ex)
+ expect(S().week).toEqual({ 1: ['a', 'b'], 3: ['b'], 5: ['c'] }) // a copy is not planned anywhere
+ expect(useUI.getState().toastMsg).toBe('Copied as “Push A (Copy)”.')
+ expect(nav).not.toHaveBeenCalled()
+ })
+
+ it('Edit’s minus deletes the same way, with the Undo in place of the confirm', () => {
+ mount('routines')
+ click(host.querySelector('.plan-textbtn'))
+ click(host.querySelector('button[aria-label="Delete Legs"]'))
+ expect(confirmSheet).not.toHaveBeenCalled()
+ expect(S().routines.map(r => r.id)).toEqual(['a', 'b'])
+ undo()
+ expect(S().routines.map(r => r.id)).toEqual(['a', 'b', 'c'])
+ expect(S().week[5]).toEqual(['c'])
+ })
+
+ it('is a plain list with the setting off', () => {
+ mount('routines', { wc: { ...DEF.wc, swipeSets: false } })
+ expect(swrows()).toHaveLength(0)
+ expect(host.querySelectorAll('.item.plan-routine')).toHaveLength(3)
+ })
+})
+
+describe('the loop', () => {
+ const loop = { rotation: { id: 'rot', sequence: ['a', 'b', 'c'], label: 'My loop' },
+ queue: { ids: ['a', 'b', 'c'], since: 1, startsOn: '2026-10-01', label: 'My loop', rotationId: 'rot' },
+ scheduleMode: 'rotation', week: {}, dayPlan: { '2099-01-01': 'b' } }
+
+ it('a swipe toward the start takes the routine out, and Undo puts the loop and its pin back', () => {
+ mount('schedule', clone(loop))
+ expect(swrows()).toHaveLength(3)
+ // remove-only: no copy pane, and a swipe toward the end does nothing
+ expect(rowOf('Pull A').querySelector('.swpane.cp')).toBeNull()
+ expect(rowOf('Pull A').querySelector('.swpane.del').textContent).toBe('Remove')
+ swipe(rowOf('Pull A'), 60, 330)
+ expect(S().queue.ids).toEqual(['a', 'b', 'c'])
+
+ swipe(rowOf('Pull A'), 330, 60)
+ expect(S().queue.ids).toEqual(['a', 'c'])
+ expect(S().rotation.sequence).toEqual(['a', 'c'])
+ expect(S().dayPlan).toEqual({}) // its future pin was swept with it
+ expect(S().routines).toHaveLength(3) // out of the loop, not deleted
+ expect(useUI.getState().toastMsg).toBe('“Pull A” is out of the loop.')
+
+ undo()
+ expect(S().queue).toEqual(loop.queue)
+ expect(S().rotation).toEqual(loop.rotation)
+ expect(S().dayPlan).toEqual(loop.dayPlan)
+ })
+
+ it('Undo after the loop changed again slots the routine back at its old place', () => {
+ mount('schedule', clone(loop))
+ swipe(rowOf('Pull A'), 330, 60)
+ const pending = useUI.getState().toastAction
+ act(() => useStore.getState().update(s => { s.queue = { ...s.queue, ids: ['c', 'a'] }; s.rotation = { ...s.rotation, sequence: ['c', 'a'] } }))
+ act(() => pending.run())
+ expect(S().queue.ids).toEqual(['c', 'b', 'a'])
+ expect(S().rotation.sequence).toEqual(['c', 'b', 'a'])
+ })
+
+ it('the edit-mode minus has the same Undo, and weekday rows never swipe', () => {
+ mount('schedule', { ...clone(loop), week: { 1: ['c'], 2: ['a'] } })
+ click([...host.querySelectorAll('.plan-textbtn')].find(b => b.textContent === 'Edit'))
+ click(host.querySelector('button[aria-label="Remove Legs"]'))
+ expect(S().queue.ids).toEqual(['a', 'b'])
+ undo()
+ expect(S().queue.ids).toEqual(['a', 'b', 'c'])
+ act(() => root.unmount()); host.remove()
+
+ mount('schedule', { week: { 1: ['a'], 3: ['b'] } }) // a fixed week
+ expect(host.querySelectorAll('.plan-day').length).toBeGreaterThan(0)
+ expect(swrows()).toHaveLength(0)
+ })
+
+ it('a coach’s own queue does not swipe', () => {
+ mount('schedule', { ...clone(loop), queue: { ...loop.queue, rotationId: 'someone-else' } })
+ expect(swrows()).toHaveLength(0)
+ })
+})
+
+describe('restoreRoutine', () => {
+ const base = () => ({
+ routines: [routine('a', 'A'), routine('b', 'B'), routine('c', 'C')],
+ week: { 1: ['a', 'b'], 3: 'b' }, dayPlan: { '2099-01-01': 'b', '2099-01-02': 'a' },
+ rotation: { id: 'r', sequence: ['b', 'c'] }, queue: { ids: ['c', 'b'] },
+ })
+
+ it('puts back what deleteRoutine took, at the same places', () => {
+ const s = base()
+ const snap = routineSnapshot(s, 'b')
+ deleteRoutine(s, 'b')
+ s.rotation.sequence = ['c']; s.queue.ids = ['c'] // a save in between dropped it too
+ expect(restoreRoutine(s, snap)).toBe(true)
+ expect(s.routines.map(r => r.id)).toEqual(['a', 'b', 'c'])
+ expect(s.week).toEqual({ 1: ['a', 'b'], 3: ['b'] })
+ expect(s.dayPlan).toEqual(base().dayPlan)
+ expect(s.rotation.sequence).toEqual(['b', 'c'])
+ expect(s.queue.ids).toEqual(['c', 'b'])
+ })
+
+ it('fits into lists that got shorter, keeps a date planned since, and never doubles a routine', () => {
+ const s = base()
+ const snap = routineSnapshot(s, 'b')
+ deleteRoutine(s, 'b')
+ s.routines = [s.routines[1]] // A deleted meanwhile
+ delete s.week[1]
+ s.dayPlan['2099-01-01'] = 'c'
+ expect(restoreRoutine(s, snap)).toBe(true)
+ expect(s.routines.map(r => r.id)).toEqual(['c', 'b'])
+ expect(s.week[1]).toEqual(['b'])
+ expect(s.dayPlan['2099-01-01']).toBe('c')
+ expect(restoreRoutine(s, snap)).toBe(false)
+ expect(s.routines.map(r => r.id)).toEqual(['c', 'b'])
+ })
+})