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
Plan: Schedule and Routines views, one How you train control, Edit mode for routines and the loop
Duarte Santosa77e108fab78
diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 6efe40355..fb3344398 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -1733,23 +1733,44 @@ body.chips-dragging *{cursor:inherit}.cam-wrap{position:relative;width:100%;aspect-ratio:3/4;max-height:58vh;border-radius:var(--r-lg);overflow:hidden;background:#000}.cam-wrap video{width:100%;height:100%;object-fit:cover;display:block}.cam-frame{position:absolute;inset:0;margin:auto;width:62%;aspect-ratio:1;border:2px dashed rgba(255,255,255,.75);border-radius:14px;pointer-events:none}-/* ------------------------------------------------- the Coach entry on Plan -- */-.coach-cta{- display:flex;align-items:center;gap:13px;width:100%;text-align: start;- margin-bottom:12px;padding:14px 16px;border-radius:var(--r-card);- background:linear-gradient(135deg,var(--acc-soft),color-mix(in srgb,var(--acc) 6%,var(--surface)));- border:1px solid color-mix(in srgb,var(--acc) 35%,transparent);- transition:transform var(--fast),filter var(--fast)-}-.coach-cta:active{transform:scale(.985);filter:brightness(1.06)}-.coach-cta-av{- width:42px;height:42px;border-radius:13px;flex:none;display:grid;place-items:center;font-size:21px;- background:var(--acc);color:var(--on-acc);box-shadow:0 6px 18px -6px color-mix(in srgb,var(--acc) 60%,transparent)-}-.coach-cta-t{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}-.coach-cta-t b{font-size:17px;font-weight:600;letter-spacing:-.015em;color:var(--label)}-.coach-cta-t span{font-size:13px;color:var(--label-2);line-height:1.35}-.coach-cta-chev{color:var(--acc);font-size:15px;flex:none}+/* ---------------------------------------------------------------- Plan -- */+/* Schedule | Routines (views/Plan.jsx). A settings-like page, one column at every width. */+.plan-views{margin-bottom:18px}+.plan-views button{min-height:34px;font-size:15px}+.plan .plan-mode .lrow-t{white-space:nowrap}+.plan-mode-locked{margin-inline-start:auto;text-align:end}+.plan-sec-h{margin:22px 0 8px;gap:8px}+.plan-sec-h h4.sec{margin:0}+.plan-routines-bar{margin-top:0}+.plan-textbtn{color:var(--acc);font-size:16px;padding:6px 4px;position:relative}+.plan-textbtn::before{content:'';position:absolute;inset:-6px}+.plan .sect-f{margin:0 0 4px}+.plan .list+.sect-f{padding-top:8px}+/* a weekday: short day name, the routine's glyph (a moon on a rest day), what is on it */+.plan-day-n{width:30px;flex:none;font-size:15px;font-weight:600;color:var(--label-2)}+.plan-day-n.today{color:var(--acc)}+.item .lrow-i.rest{background:var(--surface-3);color:var(--label-2)}+/* the loop: a numbered position, lit when up next, a tick once done this round */+.plan-order{+ width:24px;height:24px;border-radius:50%;flex:none;display:grid;place-items:center;+ font-size:13px;font-weight:600;color:var(--label-2);background:var(--surface-3);--icon-stroke:2.6;+}+.plan-order.next{background:var(--acc);color:var(--on-acc)}+.rotation-row.is-done .tt{color:var(--label-2)}+/* Edit mode, as on an iPhone: a red minus at the start, a handle at the end */+.plan-minus{+ width:24px;height:24px;border-radius:50%;flex:none;display:grid;place-items:center;+ background:var(--red);color:#fff;font-size:14px;--icon-stroke:2.6;position:relative;+}+.plan-minus::before{content:'';position:absolute;inset:-10px}+.plan-handle{+ flex:none;align-self:stretch;display:flex;align-items:center;padding:0 6px;margin:-10px -6px -10px 0;+ color:var(--label-3);font-size:18px;cursor:grab;touch-action:none;user-select:none;-webkit-user-select:none;+}+.plan-handle:active{cursor:grabbing;color:var(--label-2)}+.plan [data-reorder-row]{transition:transform var(--fast) var(--ease)}+.plan-link{margin-top:24px}+.plan-empty{padding:28px 20px}/* ----------------------------------------------------------- RTL (Arabic) -- *//* Directional icons flip: back chevrons point right, trailing chevrons point left. */diff --git a/frontend/src/lib/use-list-reorder.js b/frontend/src/lib/use-list-reorder.jsnew file mode 100644index 000000000..6405c84ce--- /dev/null+++ b/frontend/src/lib/use-list-reorder.js@@ -0,0 +1,93 @@+import { useEffect, useRef, useState } from 'react'++// Reorder a flat list by its handle, the way iOS does in Edit mode: press the handle and the row+// follows the finger at once (no long press: the handle only exists while you are reordering, so+// there is no scroll to tell apart), the rows it passes slide out of its way, and letting go+// commits one move. The arrow keys on a focused handle move the row one place, for a keyboard.+//+// The routine editor has its own, superset-aware drag (RoutineEdit.jsx). This one is for lists+// with nothing grouped: Plan's routines and the rotation's loop.+//+// const r = useListReorder(items.length, (from, to) => …)+// <div ref={r.listRef}>{items.map((x, i) => <div data-reorder-row style={r.rowStyle(i)}>+// … <button {...r.handle(i)} /></div>)}</div>+//+// `to` is the row's index after the move, so splice(from, 1) then splice(to, 0, row) applies it.+export function useListReorder(count, onMove) {+ const listRef = useRef(null)+ const gesture = useRef(null)+ const onMoveRef = useRef(onMove)+ onMoveRef.current = onMove+ const [drag, setDrag] = useState(null) // { from, to, dy, stride } while a row is held++ useEffect(() => () => { gesture.current = null }, [])++ const end = commit => {+ const g = gesture.current+ if (!g) return+ gesture.current = null+ try { g.el.releasePointerCapture?.(g.id) } catch { /* already released */ }+ setDrag(null)+ if (commit && g.to !== g.from) onMoveRef.current(g.from, g.to)+ }++ const rowsOf = () => [...(listRef.current?.children || [])].filter(el => el.hasAttribute('data-reorder-row'))++ const handle = i => ({+ 'data-reorder-handle': '',+ onPointerDown: e => {+ if (e.button != null && e.button !== 0) return+ const rows = rowsOf()+ if (!rows[i]) return+ e.preventDefault()+ e.stopPropagation()+ const rects = rows.map(row => row.getBoundingClientRect())+ // The distance from one row to the next, gap included, is how far a passed row slides.+ const stride = rects.length > 1 ? Math.abs(rects[1].top - rects[0].top) || rects[0].height : rects[0].height+ gesture.current = { id: e.pointerId, el: e.currentTarget, from: i, to: i, y0: e.clientY, rects, stride }+ try { e.currentTarget.setPointerCapture?.(e.pointerId) } catch { /* unsupported */ }+ setDrag({ from: i, to: i, dy: 0, stride })+ },+ onPointerMove: e => {+ const g = gesture.current+ if (!g || e.pointerId !== g.id) return+ e.preventDefault()+ const dy = e.clientY - g.y0+ const held = g.rects[g.from]+ const mid = held.top + held.height / 2 + dy+ // The new index is how many of the other rows now sit above the held row's middle.+ g.to = g.rects.reduce((n, r, k) => n + (k !== g.from && r.top + r.height / 2 < mid ? 1 : 0), 0)+ setDrag({ from: g.from, to: g.to, dy, stride: g.stride })+ },+ onPointerUp: e => { if (gesture.current && e.pointerId === gesture.current.id) end(true) },+ onPointerCancel: () => end(false),+ onClick: e => e.stopPropagation(),+ onKeyDown: e => {+ const d = e.key === 'ArrowUp' ? -1 : e.key === 'ArrowDown' ? 1 : 0+ if (!d) return+ e.preventDefault()+ const to = i + d+ if (to >= 0 && to < count) onMoveRef.current(i, to)+ },+ })++ // The held row follows the pointer; the rows between where it was and where it would land+ // slide one place towards the gap it left.+ const rowStyle = i => {+ if (!drag) return undefined+ if (i === drag.from) return { transform: `translateY(${drag.dy}px)`, zIndex: 2, position: 'relative', transition: 'none' }+ if (drag.from < drag.to && i > drag.from && i <= drag.to) return { transform: `translateY(${-drag.stride}px)` }+ if (drag.to < drag.from && i >= drag.to && i < drag.from) return { transform: `translateY(${drag.stride}px)` }+ return { transform: 'translateY(0)' }+ }++ return { listRef, drag, handle, rowStyle }+}++/** `list` with the entry at `from` moved to index `to` (a new array). */+export const moved = (list, from, to) => {+ const next = [...list]+ const [x] = next.splice(from, 1)+ next.splice(to, 0, x)+ return next+}diff --git a/frontend/src/views/Plan.add-routine.test.jsx b/frontend/src/views/Plan.add-routine.test.jsxdeleted file mode 100644index 437b3d623..000000000--- a/frontend/src/views/Plan.add-routine.test.jsx+++ /dev/null@@ -1,76 +0,0 @@-// @vitest-environment happy-dom-// #276: a full-width "+ Add routine" under every planned weekday made the week read as a list of-// buttons. A populated day now offers the same action as a small + in its header; an empty day-// is still one tappable row that picks its first routine.-import React, { act } from 'react'-import { createRoot } from 'react-dom/client'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import Plan from './Plan.jsx'-import { dayAddRoutineSheet, dayAssignSheet } from '../sheets.jsx'--globalThis.IS_REACT_ACT_ENVIRONMENT = true--const mocks = vi.hoisted(() => {- const state = { S: null }- state.snapshot = () => ({- S: state.S,- user: null,- update: mut => {- const next = structuredClone(state.S)- mut(next)- state.S = next- },- })- return state-})-vi.mock('../store/useStore.js', () => {- const useStore = selector => (selector ? selector(mocks.snapshot()) : mocks.snapshot())- useStore.getState = mocks.snapshot- return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }-})-vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))-vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))-vi.mock('../sheets.jsx', () => ({- starterPlanSheet: vi.fn(), dayAssignSheet: vi.fn(), dayAddRoutineSheet: vi.fn(), planToolsSheet: vi.fn(),-}))--let host, root-beforeEach(() => {- vi.clearAllMocks()- mocks.S = {- unit: 'kg', workouts: [], exWeights: {}, week: { 1: ['r1'] }, dayPlan: {},- routines: [{ id: 'r1', name: 'Push', emoji: null, ex: [] }, { id: 'r2', name: 'Pull', emoji: null, ex: [] }],- }- host = document.createElement('div')- document.body.appendChild(host)- root = createRoot(host)-})-afterEach(() => {- act(() => root.unmount())- host.remove()-})--const mount = () => act(() => root.render(<Plan />))-const dayItem = day => [...host.querySelectorAll('.item')].find(el => el.querySelector('.tt')?.textContent === day)--describe('Plan — adding a routine to a day that already has one (#276)', () => {- it('offers a compact + in the day header instead of a full-width text button', () => {- mount()- const monday = dayItem('Monday')- expect(monday.textContent).not.toContain('Add routine')- const plus = monday.querySelector('button[aria-label="Add routine"]')- expect(plus).toBeTruthy()- // It sits in the header row with the count, not under the routine rows.- expect(plus.closest('.row.between')?.querySelector('.tt')?.textContent).toBe('Monday')- act(() => plus.click())- expect(dayAddRoutineSheet).toHaveBeenCalledWith(1)- })-- it('leaves an empty day as one row that picks its first routine', () => {- mount()- const tuesday = dayItem('Tuesday')- expect(tuesday.querySelector('button[aria-label="Add routine"]')).toBeNull()- act(() => tuesday.click())- expect(dayAssignSheet).toHaveBeenCalledWith(2)- })-})diff --git a/frontend/src/views/Plan.day-rows.test.jsx b/frontend/src/views/Plan.day-rows.test.jsxnew file mode 100644index 000000000..b70ac4123--- /dev/null+++ b/frontend/src/views/Plan.day-rows.test.jsx@@ -0,0 +1,120 @@+// @vitest-environment happy-dom+// Plan → Schedule → This week (v1.3.11): one row per weekday, whatever is on it. #276 had moved+// "add a second routine" into a small + in a planned day's header; the day's own picker now does+// all of it (one routine, several for a combined day, or a rest day), so every day is one+// tappable row that opens it, planned or not. The Coach, once a banner over the week, is the+// last entry of the Plan menu.+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Plan from './Plan.jsx'+import { dayAssignSheet, menuSheet } from '../sheets.jsx'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++const mocks = vi.hoisted(() => {+ const state = { S: null, coach: false, nav: null }+ state.snapshot = () => ({+ S: state.S,+ user: null,+ update: mut => {+ const next = structuredClone(state.S)+ mut(next)+ state.S = next+ },+ })+ return state+})+vi.mock('../store/useStore.js', () => {+ const useStore = selector => (selector ? selector(mocks.snapshot()) : mocks.snapshot())+ useStore.getState = mocks.snapshot+ return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }+})+vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.nav }))+vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))+vi.mock('../lib/coach.js', () => ({ coachAvailable: () => mocks.coach }))+vi.mock('../sheets.jsx', () => ({+ starterPlanSheet: vi.fn(), dayAssignSheet: vi.fn(), menuSheet: vi.fn(), confirmSheet: vi.fn(),+ planHasRoutines: s => (s.routines || []).some(r => r.ex.length), exportPlanFile: vi.fn(), printWholePlan: vi.fn(), importPlanFile: vi.fn(),+}))++let host, root+beforeEach(() => {+ vi.clearAllMocks()+ localStorage.removeItem('gym_plan_view')+ mocks.coach = false+ mocks.nav = vi.fn()+ mocks.S = {+ unit: 'kg', workouts: [], exWeights: {}, week: { 1: ['r1'] }, dayPlan: {},+ routines: [{ id: 'r1', name: 'Push', emoji: null, ex: [] }, { id: 'r2', name: 'Pull', emoji: null, ex: [] }],+ }+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(() => {+ act(() => root.unmount())+ host.remove()+})++const mount = () => act(() => root.render(<Plan />))+const day = name => host.querySelector(`.plan-day[aria-label="${name}"]`)++describe('Plan — the weekday rows', () => {+ it('a planned day is one row with no buttons of its own; a tap opens the day’s picker', () => {+ mount()+ const monday = day('Monday')+ expect(monday.querySelector('.tt').textContent).toBe('Push')+ expect(monday.querySelectorAll('button').length).toBe(0)+ act(() => monday.click())+ expect(dayAssignSheet).toHaveBeenCalledWith(1)+ })++ it('an empty day is a rest day that asks to be planned, and opens the same picker', () => {+ mount()+ const tuesday = day('Tuesday')+ expect(tuesday.textContent).toContain('Rest day')+ expect(tuesday.textContent).toContain('Tap to plan something')+ act(() => tuesday.click())+ expect(dayAssignSheet).toHaveBeenCalledWith(2)+ })++ it('opens on the keyboard too', () => {+ mount()+ act(() => { day('Friday').dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) })+ expect(dayAssignSheet).toHaveBeenCalledWith(5)+ })+})++describe('Plan — the menu', () => {+ const openMenu = () => {+ act(() => host.querySelector('button[aria-label="Plan options"]').click())+ return menuSheet.mock.calls.at(-1)[0]+ }++ it('has no Coach banner on the page; the Coach is the menu’s last entry when it is available', () => {+ mocks.coach = true+ mount()+ expect(host.textContent).not.toContain('Plan design and reviews')+ const menu = openMenu()+ const coach = menu.items.filter(Boolean).at(-1)+ expect(coach.label).toBe('Coach')+ act(() => coach.onClick())+ expect(mocks.nav).toHaveBeenCalledWith('/coach')+ })++ it('leaves the Coach out where it is not available', () => {+ mount()+ expect(openMenu().items.filter(Boolean).map(i => i.label)).not.toContain('Coach')+ })++ it('greys out share and print while there is nothing to share, and says why', () => {+ mount()+ const menu = openMenu()+ const item = label => menu.items.find(i => i && i.label === label)+ expect(item('Export plan file').disabled).toBe(true)+ expect(item('Print / Save as PDF').disabled).toBe(true)+ expect(item('Import a plan file').disabled).toBeFalsy()+ expect(menu.subtitle).toContain('Add an exercise to a routine first')+ })+})diff --git a/frontend/src/views/Plan.jsx b/frontend/src/views/Plan.jsxindex 490d0b038..72adbd9a5 100644--- a/frontend/src/views/Plan.jsx+++ b/frontend/src/views/Plan.jsx@@ -1,20 +1,36 @@+import { useRef, useState } from 'react'import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'-import { DAYN, weekOrder, weekStartOf, uid, exCount, routineCount, fmtNum } from '../lib/format.js'+import { DAYN, DAYS, weekOrder, weekStartOf, uid, exCount, routineCount, todayISO, fmtDate } from '../lib/format.js'import { t } from '../lib/i18n.js'-import { dayAssignSheet, dayAddRoutineSheet, starterPlanSheet, planToolsSheet, confirmSheet, menuSheet } from '../sheets.jsx'+import {+ dayAssignSheet, starterPlanSheet, confirmSheet, menuSheet,+ planHasRoutines, exportPlanFile, printWholePlan, importPlanFile,+} from '../sheets.jsx'import Icon from '../components/Icon.jsx'-import { Button } from '../components/ui.jsx'+import { Button, Row, Section, Segmented } 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 { useListReorder, moved } from '../lib/use-list-reorder.js'import { glyphOf, DEFAULT_GLYPH } from '../lib/glyphs.js'import { DEMO } from '../lib/demo.js'import { MOBILE } from '../lib/mobile.js'import { coachAvailable } from '../lib/coach.js'-import { queueOf } from '../lib/queue.js'-import { scheduleModeOf, queueRecovery, rotationIds, saveRotation, startNewPass, startPass, stopPass } from '../lib/rotation.js'-import { loadOfWeeklyPlan, MUSCLE_NAME, rankOf } from '../lib/muscles.js'+import { queueOf, queueView } from '../lib/queue.js'+import { deriveSessionName } from '../lib/session-merge.js'+import {+ scheduleModeOf, queueRecovery, rotationIds, saveRotation, startNewPass, startPass, stopPass,+ chooseRotation, chooseFixedWeek,+} from '../lib/rotation.js'++// Plan has two views (v1.3.11): Schedule (how you train, and when) and Routines (what you+// train). The last one you looked at comes back: a per-device convenience, never synced, so it+// lives in this browser's storage and not in S.+export const PLAN_VIEW_KEY = 'gym_plan_view'+const readView = () => {+ try { return localStorage.getItem(PLAN_VIEW_KEY) === 'routines' ? 'routines' : 'schedule' } catch { return 'schedule' }+}export default function Plan() {const nav = useNavigate()@@ -23,43 +39,56 @@ export default function Plan() {const config = useStore(s => s.config)const coachMode = useStore(s => s.coachLocal?.mode)const user = useStore(s => s.user)- const weeklyLoad = loadOfWeeklyPlan(S)- const weeklyMuscles = rankOf(weeklyLoad).worked+ const fileRef = useRef(null)+ const [view, setViewState] = useState(readView)+ const setView = v => {+ setViewState(v)+ try { localStorage.setItem(PLAN_VIEW_KEY, v) } catch { /* private mode: the view just isn't remembered */ }+ }- /* The Coach's only entry point in the app. Its screens have existed since the UI landed and- nothing linked to them, so the feature was reachable only by typing the URL — enabled,- configured, and invisible. The same predicate every other Coach surface uses gates it, so- an instance without the feature sees exactly the Plan screen it saw before. */+ /* The Coach's way in from Plan. It used to be a banner over the week; it is the last entry of the+ Plan menu now, gated by the same predicate every other Coach surface uses, so an instance+ without the feature sees exactly the menu it would have without it. */const showCoach = coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })- // Swap with the neighbour, the way the routine editor moves an exercise. `S.routines` is the- // one order the whole app reads, so this is all there is to it (#142).- const moveRoutine = (i, delta) => update(s => {- const to = i + delta- if (to < 0 || to >= s.routines.length) return- const [moved] = s.routines.splice(i, 1)- s.routines.splice(to, 0, moved)- })-- const addRoutine = () => {- const r = { id: uid(), name: t('New routine'), emoji: DEFAULT_GLYPH, ex: [] }- update(s => { s.routines.push(r) })- nav('/plan/r/' + r.id)+ // Share, print, import, starter plans and the Coach: one menu behind the header button, so the+ // two views below are only about the plan itself.+ const openMenu = () => {+ const has = planHasRoutines(S)+ menuSheet({+ title: t('Plan'),+ subtitle: has ? null : t('Add an exercise to a routine first. An empty plan has nothing to share.'),+ items: [+ { icon: 'share', label: t('Export plan file'), sub: t('A small file a friend can import into their own openGym. Routines only, none of your workouts or weigh-ins.'), disabled: !has, onClick: exportPlanFile },+ { icon: 'note', label: t('Print / Save as PDF'), disabled: !has, onClick: printWholePlan },+ { icon: 'download', label: t('Import a plan file'), onClick: () => fileRef.current?.click() },+ { icon: 'clipboard', label: t('Load starter plan'), onClick: starterPlanSheet },+ showCoach && { icon: 'sparkles', label: t('Coach'), sub: t('Plan design and reviews, from your own training'), onClick: () => nav('/coach') },+ ],+ })}+ const pickFile = ev => { const f = ev.target.files[0]; ev.target.value = ''; importPlanFile(f) }- // Pull one routine off a weekday; drop the key when the day empties (never store []).- const removeFromDay = (d, rid) => update(s => {- const next = [].concat(s.week[d] || []).filter(id => id !== rid)- if (next.length) s.week[d] = next; else delete s.week[d]- })+ const mode = scheduleModeOf(S)- // 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) })- })+ return <div className="narrow plan">+ <div className="hdr">+ <div><h1>{t('Plan')}</h1><div className="sub">{mode === 'rotation' ? t('Your routines in a loop') : t('Your weekly routine')}</div></div>+ <button className="iconbtn" onClick={openMenu} aria-label={t('Plan options')} title={t('Plan options')}><Icon name="share" /></button>+ </div>+ <input ref={fileRef} type="file" accept="application/json,.json" onChange={pickFile} hidden />+ <Segmented className="plan-views" value={view} onChange={setView}+ options={[{ value: 'schedule', label: t('Schedule') }, { value: 'routines', label: t('Routines') }]} />+ {view === 'routines'+ ? <Routines S={S} update={update} nav={nav} />+ : <Schedule S={S} update={update} nav={nav} mode={mode} />}+ </div>+}+/* ================================ Schedule ================================ */++function Schedule({ S, update, nav, mode }) {+ const [editLoop, setEditLoop] = useState(false)/* The rotation editor. What it shows is the live pass when there is one, otherwise the savedsequence — S.rotation is only a definition, so the pass is the truth whenever it exists.Every edit writes straight through saveRotation: an edit IS the save (and, for a queue@@ -72,25 +101,31 @@ export default function Plan() {// saved rotation here — that's what makes it someone else's to write, not this app's.const managed = !!liveQ && !!S.rotation && liveQ.rotationId === S.rotation.idconst external = !!liveQ && !managed- // The editor shows for any live queue — so "Use this rotation" stays reachable for a planner's- // week — or once Rotation is chosen with nothing built yet (S.scheduleMode). The weekday grid- // stays up for ANY live queue, managed or not: the weekday routines ride along beside it either- // way (effectiveRoutineIds, history.js) and feed the same tally (weekTally, queue.js), so hiding- // the grid would hide the very thing that explains a combined count. It is hidden only while- // Rotation is chosen with nothing built yet — there is no queue at that point for it to sit- // beside, so a plain weekday grid would just be noise — and never during recovery: a malformed- // queue (deleting every routine in the sequence leaves exactly this — S.queue and S.scheduleMode- // both still 'rotation' with nothing left for queueOf to resolve) is a fix-up, not a from-scratch- // setup, and the grid is the fallback schedule while it's sorted out.- const rotating = scheduleModeOf(S) === 'rotation' || queueRecovery(S)- const hideGrid = !liveQ && !queueRecovery(S) && S.scheduleMode === 'rotation'+ const recovery = queueRecovery(S)+ const qv = liveQ ? queueView(S, todayISO()) : null++ // "How you train" is the same switch as Settings' (lib/rotation.js chooseRotation /+ // chooseFixedWeek), on the same keys. Leaving a running loop asks first: its progress goes,+ // the loop itself and the weekdays stay. With nothing running there is nothing to lose.+ const setMode = v => {+ if (v === mode) return+ if (v === 'rotation') { update(s => { chooseRotation(s) }); return }+ if (!liveQ) { update(s => { chooseFixedWeek(s) }); return }+ confirmSheet({+ title: t('Back to a fixed week?'),+ message: t('The loop stops. Your weekdays stay as they are, and the loop is saved for later.'),+ confirmText: t('Use Fixed Week'),+ onConfirm: () => update(s => { chooseFixedWeek(s) }),+ })+ }+const setSeq = ids => update(s => {// Emptying the sequence is how you leave the rotation from here: no pass, no definition, and// the weekday plan — untouched all along — is the schedule again.if (ids.length) saveRotation(s, ids, seqLabel)else { stopPass(s); s.rotation = null; s.scheduleMode = 'week' }})- const moveInSeq = (i, d) => { const n = [...seq]; const [x] = n.splice(i, 1); n.splice(i + d, 0, x); setSeq(n) }+ const loopReorder = useListReorder(seq.length, (from, to) => setSeq(moved(seq, from, to)))const addToSeq = () => menuSheet({title: t('Add to the rotation'),items: S.routines.filter(r => !seq.includes(r.id)).map(r => ({@@ -109,139 +144,177 @@ export default function Plan() {onConfirm: () => update(s => saveRotation(s, seq, t('Rotation'))),})- return <>- <div className="hdr">- <div><h1>{t('Plan')}</h1><div className="sub">{t('Your weekly routine')}</div></div>- <button className="iconbtn" onClick={planToolsSheet} aria-label={t('Share your plan')} title={t('Share your plan')}><Icon name="upload" /></button>- </div>- {showCoach && <button className="coach-cta" onClick={() => nav('/coach')}>- <span className="coach-cta-av"><Icon name="sparkles" /></span>- <span className="coach-cta-t">- <b>{t('Coach')}</b>- <span>{t('Plan design and reviews, from your own training')}</span>- </span>- <Icon name="chevronRight" className="coach-cta-chev" />- </button>}-- <div className="cols"><div>- {/* Rotation (lib/rotation.js) shows for any live queue, so a coach's week can still be- adopted from here. The weekday grid stays up beside it either way — managed or- external — since the weekday routines ride along regardless (effectiveRoutineIds,- history.js) and the grid is what explains their share of the combined tally. */}- {rotating && <div className="rotation">- <h4 className="sec">{t('Rotation')}{external && <span className="tag" style={{ marginLeft: 8 }}>{t('Externally managed')}</span>}</h4>- {queueRecovery(S) ? <div className="empty">- {t('This rotation couldn’t be read. Another device may have written it.')}- <div style={{ marginTop: 10 }}>- {/* Also gives up S.scheduleMode='rotation' — otherwise the editor stays up with a- saved sequence and no queue, and hideGrid keeps the weekday grid (and its own- "Start pass" way out of that state) hidden along with it: a dead end. */}- <Button size="sm" variant="tinted" aria-label={t('Discard it')} onClick={() => update(s => { s.queue = null; s.scheduleMode = 'week' })}>{t('Discard it')}</Button>- </div>- </div> : <>- {seq.length ? <div className="list" style={{ display: 'flex', flexDirection: 'column' }}>- {seq.map((id, i) => {- const r = S.routines.find(x => x.id === id)- return <div key={id} className="item rotation-row">- <span className="lrow-i"><Icon name={glyphOf(r?.emoji)} /></span>- <div className="grow" style={{ minWidth: 0 }}>- <div className="tt">{r?.name ?? id}</div><div className="ss">{t('Position {0}', i + 1)}</div>- </div>- {/* A coach's own queue is read-only here: the one way to change what it holds is- to adopt it first ("Use this rotation" below), never a tap on one of its rows. */}- {!external && <>- <button className="iconbtn sm" aria-label={t('Move up')} title={t('Move up')} disabled={i === 0} onClick={() => moveInSeq(i, -1)}><Icon name="chevronUp" /></button>- <button className="iconbtn sm" aria-label={t('Move down')} title={t('Move down')} disabled={i === seq.length - 1} onClick={() => moveInSeq(i, 1)}><Icon name="chevronDown" /></button>- <button className="iconbtn sm" aria-label={t('Remove')} title={t('Remove')} onClick={() => setSeq(seq.filter(x => x !== id))}><Icon name="xmark" /></button>- </>}- </div>- })}- </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>}- <div className="row" style={{ gap: 8, marginTop: 8, flexWrap: 'wrap' }}>- {!external && <Button size="sm" variant="tinted" icon="plus" aria-label={t('Add routine to the rotation')}- disabled={S.routines.every(r => seq.includes(r.id))} onClick={addToSeq}>{t('Add routine')}</Button>}- {external && <Button size="sm" variant="tinted" aria-label={t('Use this rotation')} onClick={adopt}>{t('Use this rotation')}</Button>}- {!!liveQ && !external && <Button size="sm" aria-label={t('Start new pass')}- onClick={() => update(s => startNewPass(s))}>{t('Start new pass')}</Button>}- {!liveQ && !queueRecovery(S) && <Button size="sm" variant="tinted" aria-label={t('Cancel')} onClick={() => update(s => { s.scheduleMode = 'week' })}>{t('Cancel')}</Button>}- </div>- </>}- </div>}- {!hideGrid && <>- <h4 className="sec">{t('Week schedule')}</h4>- <div className="list" style={{ display: 'flex', flexDirection: 'column' }}>- {weekOrder(weekStartOf(S)).map(d => {- const dayRoutines = [].concat(S.week[d] || []).map(id => S.routines.find(x => x.id === id)).filter(Boolean)- // An empty day stays one tappable row → pick its first routine (today's behaviour).- if (!dayRoutines.length) return <div key={d} className="item" {...tappable(() => dayAssignSheet(d))}>- <div className="grow"><div className="tt">{t(DAYN[d])}</div></div>- <span className="tag">{t('Rest')}</span>- <Icon name="chevronRight" className="chev" /></div>- // A populated day: always-visible routine sub-rows + inline ✕. Adding a second routine- // is a small + in the day's header, centred over the ✕ column (#276): a full-width- // "+ Add routine" under every planned day made the week read as a list of buttons,- // when most people train one routine a day. The + keeps the option for those who don't.- return <div key={d} className="item" style={{ display: 'block', padding: '10px 14px' }}>- <div className="row between" style={{ marginBottom: 6 }}>- <div className="tt">{t(DAYN[d])}</div>- <div className="row" style={{ gap: 8 }}>- <div className="small dim">{routineCount(dayRoutines.length)}</div>- <button className="iconbtn sm" aria-label={t('Add routine')} title={t('Add routine')}- style={{ width: 30, height: 30, margin: '-5px 3px', fontSize: 15 }}- onClick={() => dayAddRoutineSheet(d)}><Icon name="plus" /></button>- </div>- </div>- {dayRoutines.map(r => <div key={r.id} className="row" style={{ gap: 8, padding: '4px 0 4px 8px' }}>- <span className="lrow-i" style={{ width: 26, height: 26, fontSize: 14 }}><Icon name={glyphOf(r.emoji)} /></span>- <div className="grow" style={{ minWidth: 0 }}><div className="tt" style={{ fontSize: 14 }}>{r.name}</div><div className="ss">{exCount(r.ex.length)}</div></div>- <button className="iconbtn sm" aria-label={t('Remove')} onClick={() => removeFromDay(d, r.id)}><Icon name="xmark" /></button>- </div>)}- </div>- })}- </div>- {/* Three dead ends land here with no active pass — "Discard it" on a malformed queue,- Settings' "Use Fixed Week" (which keeps the sequence on purpose), and every routine- the saved sequence names getting deleted out from under it. "Build a rotation instead"- used to stay hidden on `!S.rotation` alone, which a saved-but-now-empty sequence still- satisfies (S.rotation itself is untouched) — gated on the ids actually surviving- instead, it offers a fresh start exactly when there is nothing left to resume. */}- {!liveQ && seq.length > 0- ? <Button size="sm" variant="tinted" icon="shuffle" style={{ marginTop: 8 }}- aria-label={t('Start pass')} onClick={() => update(s => startPass(s))}>{t('Start pass')}</Button>- : !liveQ && !seq.length && <Button size="sm" variant="tinted" icon="shuffle" style={{ marginTop: 8 }}- aria-label={t('Build a rotation instead')} onClick={() => update(s => { s.scheduleMode = 'rotation' })}>{t('Build a rotation instead')}</Button>}- </>}- <div className="card" data-weekly-muscle-volume style={{ marginTop: 12 }}>- <h2>{t('Weekly muscle volume')}</h2>- {weeklyMuscles.length ? weeklyMuscles.map(muscle => <div className="mrow" key={muscle}>- <span className="nm">{t(MUSCLE_NAME[muscle])}</span>- <span className="v">{t('{0} sets', fmtNum(Math.round(weeklyLoad[muscle] * 10) / 10))}</span>- </div>) : <div className="muted small">{t('No muscle volume planned.')}</div>}+ const ws = weekStartOf(S)+ const todayDow = new Date().getDay()+ const routineOf = id => S.routines.find(x => x.id === id)+ const dayRoutines = d => [].concat(S.week[d] || []).map(routineOf).filter(Boolean)+ // One weekday: what is on it at a glance, and a tap to change it (dayAssignSheet picks one+ // routine, several for a combined day, or a rest day).+ const dayRow = d => {+ const rs = dayRoutines(d)+ return <div key={d} className="item plan-day" data-day={d} aria-label={t(DAYN[d])} {...tappable(() => dayAssignSheet(d))}>+ <span className={'plan-day-n' + (d === todayDow ? ' today' : '')} aria-hidden="true">{t(DAYS[d])}</span>+ <span className={'lrow-i' + (rs.length ? '' : ' rest')}><Icon name={rs.length ? glyphOf(rs[0].emoji) : 'moon'} /></span>+ <div className="grow">+ <div className="tt">{rs.length ? deriveSessionName(rs.map(r => r.name)) : t('Rest day')}</div>+ <div className="ss">{rs.length === 1 ? exCount(rs[0].ex.length) : rs.length ? routineCount(rs.length) : t('Tap to plan something')}</div></div>- </div><div>- <div className="row between" style={{ marginTop: 22, marginBottom: 10 }}>- <h4 className="sec" style={{ margin: 0 }}>{t('Routines')}</h4>- <Button size="sm" variant="tinted" icon="plus" onClick={addRoutine}>{t('New')}</Button>+ <Icon name="chevronRight" className="chev" />+ </div>+ }+ const plannedDays = weekOrder(ws).filter(d => dayRoutines(d).length)+ const doneCount = qv ? qv.items.filter(i => i.state === 'done').length : 0+ const stateWord = item => item.state === 'pinned' ? fmtDate(item.on, true)+ : { done: t('Done'), next: t('Up next'), later: t('Later') }[item.state]+ const editing = editLoop && !external++ return <>+ <Section className="plan-mode" footer={mode === 'rotation'+ ? t('Routines in a loop. Whatever is next stays next until you train it, whatever the day.')+ : t('The same routines on the same weekdays, every week.')}>+ <Row icon="repeat" iconTint="var(--orange)" title={t('How you train')}>+ {/* A planner's own queue is not this app's to switch off: text, not a control. */}+ {external+ ? <span className="small dim plan-mode-locked">{t('Rotation')} · {t('Externally managed')}</span>+ : <Segmented className="seg-inline" value={mode} onChange={setMode}+ options={[{ value: 'week', label: t('Fixed Week') }, { value: 'rotation', label: t('Rotation') }]} />}+ </Row>+ </Section>++ {!S.routines.length && <div className="empty plan-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 style={{ marginTop: 12 }}><Button icon="clipboard" onClick={starterPlanSheet}>{t('Load starter plan')}</Button></div>+ </div>}++ {/* A queue payload that arrived unusable: a fix-up, shown whichever way you train. Giving it+ up also gives up S.scheduleMode='rotation', or the loop would sit there with no queue. */}+ {recovery && <div className="empty">+ {t('This rotation couldn’t be read. Another device may have written it.')}+ <div style={{ marginTop: 10 }}>+ <Button size="sm" variant="tinted" aria-label={t('Discard it')} onClick={() => update(s => { s.queue = null; s.scheduleMode = 'week' })}>{t('Discard it')}</Button></div>- {S.routines.length ? <div className="list routine-list">{S.routines.map((r, i) => <SwipeToDelete key={r.id} className="item"- 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 the- same array — the Start screen, the day-assignment sheets, the routine pickers. So- moving a routine here moves it everywhere, which is what the request asked for (#142). */}- {S.routines.length > 1 && <div style={{ display: 'flex', gap: 2, flex: 'none' }}>- <button className="iconbtn" aria-label={t('Move up')} title={t('Move up')} disabled={i === 0}- style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }}- onClick={ev => { ev.stopPropagation(); moveRoutine(i, -1) }}><Icon name="chevronUp" /></button>- <button className="iconbtn" aria-label={t('Move down')} title={t('Move down')} disabled={i === S.routines.length - 1}- style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }}- onClick={ev => { ev.stopPropagation(); moveRoutine(i, 1) }}><Icon name="chevronDown" /></button>+ </div>}++ {mode === 'week' ? <>+ <h4 className="sec">{t('This week')}</h4>+ <div className="list plan-week">{weekOrder(ws).map(dayRow)}</div>+ <p className="sect-f">{t('Want two routines on one day? Tap the day and pick both.')}</p>+ </> : <div className="rotation">+ <div className="row between plan-sec-h">+ <h4 className="sec">{t('The loop')}{external && <span className="tag" style={{ marginInlineStart: 8 }}>{t('Externally managed')}</span>}</h4>+ {/* A coach's own queue is read-only here: the one way to change what it holds is to+ adopt it first ("Use this rotation" below), never a tap on one of its rows. */}+ {!external && <div className="row" style={{ gap: 6 }}>+ {seq.length > 0 && <button className="plan-textbtn" aria-pressed={editLoop} onClick={() => setEditLoop(e => !e)}>{editLoop ? t('Done') : t('Edit')}</button>}+ <Button size="sm" variant="tinted" icon="plus" aria-label={t('Add routine to the rotation')}+ disabled={S.routines.every(r => seq.includes(r.id))} onClick={addToSeq}>{t('Add')}</Button></div>}- <Icon name="chevronRight" className="chev" /></SwipeToDelete>)}</div> : <>- <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>- <Button icon="sparkles" onClick={starterPlanSheet}>{t('Load starter plan')}</Button>+ </div>+ {seq.length ? <div className="list plan-loop" ref={loopReorder.listRef}>+ {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)}>+ {editing && <button className="plan-minus" aria-label={t('Remove')} title={t('Remove')}+ onClick={() => setSeq(seq.filter(x => x !== 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 }}>+ <div className="tt">{r?.name ?? id}</div>+ <div className="ss">{item ? stateWord(item) : r ? exCount(r.ex.length) : ''}</div>+ </div>+ {editing && seq.length > 1 && <button className="plan-handle" aria-label={t('Drag to reorder')} title={t('Drag to reorder')}+ {...loopReorder.handle(i)}><Icon name="chevronsUpDown" /></button>}+ </div>+ })}+ </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">+ {qv ? (qv.waiting ? t('Next pass starts {0}', fmtDate(qv.startsOn, true)) : t('{0} of {1} done this round.', doneCount, qv.items.length)) + ' ' : ''}+ {external ? '' : editing ? t('Drag to reorder. Tap the red button to take one out.') : t('Trained out of order? Just pick another routine on Home.')}+ </p>}+ <div className="row" style={{ gap: 8, marginTop: 4, flexWrap: 'wrap' }}>+ {external && <Button size="sm" variant="tinted" aria-label={t('Use this rotation')} onClick={adopt}>{t('Use this rotation')}</Button>}+ {/* Throws the current round away and starts the saved loop again today; nothing logged+ before this moment counts for it (startNewPass, the strict pass). */}+ {!!liveQ && !external && <Button size="sm" icon="reset" aria-label={t('Start the loop over')}+ onClick={() => update(s => startNewPass(s))}>{t('Start the loop over')}</Button>}+ {/* Rotation chosen and a loop saved, but no round running (it was stopped elsewhere). */}+ {!liveQ && !recovery && seq.length > 0 && <Button size="sm" variant="tinted" icon="play" aria-label={t('Start the loop')}+ onClick={() => update(s => startPass(s))}>{t('Start the loop')}</Button>}+ </div>+ {/* The weekday routines ride along beside a loop (effectiveRoutineIds, history.js) and feed+ the same tally (weekTally, queue.js), so the days that still hold one stay in sight. */}+ {plannedDays.length > 0 && <>+ <h4 className="sec">{t('Also on fixed days')}</h4>+ <div className="list plan-week">{plannedDays.map(dayRow)}</div>+ <p className="sect-f">{t('These count on top of the loop. Tap a day to change or clear it.')}</p></>}- </div></div>+ </div>}++ {/* Weekly muscle volume is analysis: it moved to Stats, next to Muscle balance. */}+ <Section className="plan-link">+ <Row icon="chart" iconTint="var(--indigo)" title={t('Weekly muscle volume')} subtitle={t('Now in Stats, next to Muscle balance')}+ accessory="chevron" onClick={() => nav('/stats?focus=weekly-volume')} />+ </Section>+ </>+}++/* ================================ Routines ================================ */++function Routines({ S, update, nav }) {+ const [edit, setEdit] = useState(false)+ 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+ // it everywhere (#142). Reordering lives behind Edit, like on an iPhone.+ const reorder = useListReorder(routines.length, (from, to) => update(s => {+ if (to < 0 || to >= s.routines.length) return+ const [m] = s.routines.splice(from, 1)+ s.routines.splice(to, 0, m)+ }))++ const addRoutine = () => {+ const r = { id: uid(), name: t('New routine'), emoji: DEFAULT_GLYPH, ex: [] }+ 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 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]))+ const sub = r => [exCount(r.ex.length), daysOf(r.id).join(', ')].filter(Boolean).join(' · ')++ return <>+ <div className="row between plan-sec-h plan-routines-bar">+ {routines.length > 0+ ? <button className="plan-textbtn" aria-pressed={edit} onClick={() => setEdit(e => !e)}>{edit ? t('Done') : t('Edit')}</button>+ : <span />}+ <Button size="sm" variant="tinted" icon="plus" onClick={addRoutine}>{t('New routine')}</Button>+ </div>+ {routines.length ? <>+ {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 routine')} title={t('Delete routine')} onClick={() => confirmDelete(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('Drag to reorder')} 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>}+ <p className="sect-f">{edit ? t('Drag to reorder. Tap the red button 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>+ <Button icon="clipboard" onClick={starterPlanSheet}>{t('Load starter plan')}</Button>+ </>}</>}diff --git a/frontend/src/views/Plan.rotation.test.jsx b/frontend/src/views/Plan.rotation.test.jsxindex 448c6114a..0218fcfde 100644--- a/frontend/src/views/Plan.rotation.test.jsx+++ b/frontend/src/views/Plan.rotation.test.jsx@@ -1,8 +1,9 @@// @vitest-environment happy-dom-// Plan's rotation editor: one row per sequence position, add/remove/move writing straight through-// lib/rotation.js, adoption of an externally written queue, recovery for a malformed one, and the-// weekday grid staying up alongside the editor for any live queue — hidden only with Rotation-// chosen and nothing built yet, or a saved sequence whose routines are all gone.+// Plan → Schedule since v1.3.11: ONE "How you train: Fixed Week | Rotation" control (the same+// switch and keys as Settings, lib/rotation.js chooseRotation / chooseFixedWeek). Fixed Week shows+// the weekdays; Rotation shows the loop (add, Edit to reorder and remove, Start the loop over),+// with the weekdays that still hold a routine beside it. An externally written queue is read-only+// until adopted, and a malformed one offers recovery.import React, { act } from 'react'import { createRoot } from 'react-dom/client'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -10,7 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'globalThis.IS_REACT_ACT_ENVIRONMENT = trueconst mocks = vi.hoisted(() => {- const state = { S: null }+ const state = { S: null, nav: null }state.snapshot = () => ({S: state.S,update: mut => { const next = structuredClone(state.S); mut(next); state.S = next },@@ -23,10 +24,10 @@ vi.mock('../store/useStore.js', () => {useStore.getState = mocks.snapshotreturn { useStore }})-vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }))+vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.nav }))vi.mock('../sheets.jsx', () => ({- dayAssignSheet: vi.fn(), dayAddRoutineSheet: vi.fn(), starterPlanSheet: vi.fn(),- planToolsSheet: vi.fn(), menuSheet: vi.fn(), confirmSheet: vi.fn(),+ dayAssignSheet: vi.fn(), starterPlanSheet: vi.fn(), menuSheet: vi.fn(), confirmSheet: vi.fn(),+ planHasRoutines: () => true, exportPlanFile: vi.fn(), printWholePlan: vi.fn(), importPlanFile: vi.fn(),}))vi.mock('../lib/mobile.js', () => ({ MOBILE: false }))vi.mock('../lib/demo.js', () => ({ DEMO: false }))@@ -42,61 +43,110 @@ const routines = [{ id: 'c', name: 'C', emoji: null, ex: [{ id: '0025' }] },]const live = (over = {}) => ({ ids: ['a', 'b'], since: Date.now() - 86400000, startsOn: todayISO(), label: 'My split', ...over })+const saved = { id: 'r1', sequence: ['a', 'b'], label: 'My split' }const baseS = over => ({ routines, week: { 1: ['c'] }, dayPlan: {}, workouts: [], queue: null, rotation: null, scheduleMode: null, ...over })let host, root-beforeEach(() => { host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host); menuSheet.mockClear(); confirmSheet.mockClear() })+beforeEach(() => {+ localStorage.removeItem('gym_plan_view')+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)+ menuSheet.mockClear(); confirmSheet.mockClear(); mocks.nav = vi.fn()+})afterEach(() => { act(() => root.unmount()); host.remove() })+// the mocked store is not reactive: re-mount to see a write renderconst mount = over => { mocks.S = baseS(over); act(() => root.render(<Plan />)) }+const remount = () => act(() => root.render(<Plan key={Math.random()} />))const rows = () => [...host.querySelectorAll('.rotation-row')]const names = () => rows().map(r => r.querySelector('.tt').textContent)const click = el => act(() => el.dispatchEvent(new MouseEvent('click', { bubbles: true })))const byLabel = label => [...host.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === label || b.textContent.trim() === label)+const modeButtons = () => [...host.querySelectorAll('.plan-mode .seg button')]+const pickMode = label => click(modeButtons().find(b => b.textContent === label))+const selectedMode = () => modeButtons().find(b => b.className.includes('on'))?.textContent+const headings = () => [...host.querySelectorAll('h4.sec')].map(h => h.firstChild.textContent)+const subtitle = () => host.querySelector('.hdr .sub').textContent-describe('Plan — the rotation editor', () => {- it('lists the live pass in order, and keeps the weekday grid up for a managed pass too', () => {- // A managed pass no longer hides the grid: the weekday routines still ride alongside it- // (effectiveRoutineIds, history.js) and feed the same tally (weekTally, queue.js), so hiding- // the grid would hide the very thing a combined count depends on.- mount({ queue: live({ rotationId: 'r1' }), rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })- expect(names()).toEqual(['A', 'B'])- expect(host.textContent).toContain('Week schedule')- expect(host.textContent).toContain('C') // week[1] = ['c'] (baseS) rides along beside the pass- })-- it('a coach queue with S.scheduleMode stuck on "rotation" still shows Week schedule, never Build a rotation instead', () => {- // scheduleMode is stale/irrelevant once a queue is live — it only matters with no queue at- // all (the from-scratch setup gap hideGrid exists for).- mount({ queue: live(), scheduleMode: 'rotation' }) // external queue; no S.rotation- expect(host.textContent).toContain('Week schedule')+describe('Plan — How you train', () => {+ it('nothing saved: Fixed Week with the weekdays, and no rotation buttons of its own', () => {+ mount()+ expect(selectedMode()).toBe('Fixed Week')+ expect(headings()).toContain('This week')+ expect(subtitle()).toBe('Your weekly routine')+ expect(rows()).toEqual([])+ // the old duplicate controls are gone: the mode control is the one way in and outexpect(byLabel('Build a rotation instead')).toBeUndefined()+ expect(byLabel('Cancel')).toBeUndefined()})- it('nothing saved shows the weekday grid, with a button into the rotation editor', () => {+ it('Rotation with nothing saved holds the choice and shows an empty loop instead of the week', () => {mount()- expect(host.textContent).toContain('Week schedule')- expect(rows()).toEqual([])- click(byLabel('Build a rotation instead'))+ pickMode('Rotation')expect(mocks.S.scheduleMode).toBe('rotation')- // the mocked store is not reactive, so re-mount to see the persisted choice render- mount({ scheduleMode: mocks.S.scheduleMode })- expect(host.textContent).toContain('Rotation')- expect(host.textContent).not.toContain('Week schedule')+ expect(mocks.S.queue).toBe(null)+ remount()+ expect(selectedMode()).toBe('Rotation')+ expect(headings()).toContain('The loop')+ expect(headings()).not.toContain('This week')+ expect(host.textContent).toContain('No rotation yet.')+ // the subtitle stops saying "weekly" once you train in a loop+ expect(subtitle()).toBe('Your routines in a loop')})- it('Cancel gives the schedule back to the weekday plan', () => {+ it('back to Fixed Week with nothing running needs no confirmation', () => {mount({ scheduleMode: 'rotation' })- expect(host.textContent).toContain('Rotation')- click(byLabel('Cancel'))+ pickMode('Fixed Week')+ expect(confirmSheet).not.toHaveBeenCalled()expect(mocks.S.scheduleMode).toBe('week')- mount({ scheduleMode: mocks.S.scheduleMode })- expect(host.textContent).toContain('Week schedule')- expect(host.textContent).not.toContain('Rotation')})- it('adding a routine offers only the ones not in the sequence, and saves the pass', () => {- mount({ queue: live({ rotationId: 'r1' }), rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })+ it('Rotation starts a pass from a saved loop', () => {+ mount({ rotation: saved })+ pickMode('Rotation')+ expect(mocks.S.queue).toMatchObject({ ids: ['a', 'b'], rotationId: 'r1', startsOn: todayISO() })+ expect(mocks.S.scheduleMode).toBe('rotation')+ })++ it('leaving a running loop asks first, then keeps the loop and the weekdays', () => {+ mount({ queue: live({ rotationId: 'r1' }), rotation: saved, dayPlan: { [todayISO()]: 'a' } })+ expect(selectedMode()).toBe('Rotation')+ pickMode('Fixed Week')+ expect(mocks.S.queue).not.toBe(null)+ expect(confirmSheet).toHaveBeenCalledTimes(1)+ act(() => confirmSheet.mock.calls[0][0].onConfirm())+ expect(mocks.S.queue).toBe(null)+ expect(mocks.S.scheduleMode).toBe('week')+ expect(mocks.S.rotation.sequence).toEqual(['a', 'b'])+ expect(mocks.S.week).toEqual({ 1: ['c'] })+ expect(mocks.S.dayPlan).toEqual({})+ })+})++describe('Plan — the loop', () => {+ it('lists the live pass in order with its state, and keeps the weekdays that hold a routine', () => {+ mount({ queue: live({ rotationId: 'r1' }), rotation: saved })+ expect(names()).toEqual(['A', 'B'])+ expect(rows().map(r => r.querySelector('.ss').textContent)).toEqual(['Up next', 'Later'])+ expect(rows()[0].querySelector('.plan-order').className).toContain('next')+ expect(host.textContent).toContain('0 of 2 done this round.')+ // week[1] = ['c'] rides along beside the pass (effectiveRoutineIds), so it stays in sight+ expect(headings()).toContain('Also on fixed days')+ expect(host.querySelector('.plan-day[data-day="1"] .tt').textContent).toBe('C')+ expect(host.querySelectorAll('.plan-day').length).toBe(1)+ })++ it('a session done this round reads Done and moves Up next along', () => {+ const since = Date.now() - 86400000+ mount({+ queue: live({ since, rotationId: 'r1' }), rotation: saved,+ workouts: [{ id: 'w1', d: todayISO(), start: Date.now() - 1000, routineIds: ['a'], routineId: 'a', name: 'A', entries: [] }],+ })+ expect(rows().map(r => r.querySelector('.ss').textContent)).toEqual(['Done', 'Up next'])+ expect(host.textContent).toContain('1 of 2 done this round.')+ })++ it('adding a routine offers only the ones not in the loop, and saves the pass', () => {+ mount({ queue: live({ rotationId: 'r1' }), rotation: saved })click(byLabel('Add routine to the rotation'))const items = menuSheet.mock.calls[0][0].itemsexpect(items.map(i => i.label)).toEqual(['C'])@@ -105,16 +155,32 @@ describe('Plan — the rotation editor', () => {expect(mocks.S.rotation.sequence).toEqual(['a', 'b', 'c'])})- it('move down reorders without restarting the pass', () => {+ it('Edit reveals the handles; moving one reorders without restarting the pass', () => {const since = Date.now() - 86400000- mount({ queue: live({ since, rotationId: 'r1' }), rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })- click(rows()[0].querySelector('[aria-label="Move down"]'))+ mount({ queue: live({ since, rotationId: 'r1' }), rotation: saved })+ expect(host.querySelector('[data-reorder-handle]')).toBe(null)+ click(byLabel('Edit'))+ const handle = rows()[0].querySelector('[data-reorder-handle]')+ act(() => { handle.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })) })expect(mocks.S.queue.ids).toEqual(['b', 'a'])expect(mocks.S.queue.since).toBe(since)})+ it('a drag on the handle reorders the loop too', () => {+ mount({ queue: live({ ids: ['a', 'b', 'c'], rotationId: 'r1' }), rotation: { ...saved, sequence: ['a', 'b', 'c'] } })+ click(byLabel('Edit'))+ rows().forEach((row, i) => { row.getBoundingClientRect = () => ({ top: i * 68, bottom: i * 68 + 60, height: 60, left: 0, right: 300, width: 300 }) })+ const h = rows()[2].querySelector('[data-reorder-handle]')+ const fire = (type, y) => act(() => { h.dispatchEvent(new PointerEvent(type, { bubbles: true, pointerId: 7, button: 0, clientY: y })) })+ fire('pointerdown', 166)+ fire('pointermove', 20)+ fire('pointerup', 20)+ expect(mocks.S.queue.ids).toEqual(['c', 'a', 'b'])+ })+it('removing the last routine hands the schedule back to the weekday plan', () => {mount({ queue: live({ ids: ['a'], rotationId: 'r1' }), rotation: { id: 'r1', sequence: ['a'], label: 'My split' } })+ click(byLabel('Edit'))click(rows()[0].querySelector('[aria-label="Remove"]'))expect(mocks.S.queue).toBe(null)expect(mocks.S.rotation).toBe(null)@@ -122,10 +188,37 @@ describe('Plan — the rotation editor', () => {expect(mocks.S.week).toEqual({ 1: ['c'] })})- it('an externally written pass says so, keeps the weekday grid, and can be adopted behind a confirm', () => {- mount({ queue: live() }) // no rotationId, no rotation- expect(host.textContent).toContain('Externally managed')- expect(host.textContent).toContain('Week schedule')+ it('Start the loop over rewinds the current round, strictly from now', () => {+ mount({+ queue: live({ since: Date.now() - 5 * 86400000, startsOn: '2026-09-01', rotationId: 'r1' }),+ rotation: saved,+ })+ click(byLabel('Start the loop over'))+ expect(mocks.S.queue.startsOn).toBe(todayISO())+ expect(mocks.S.queue.ids).toEqual(['a', 'b'])+ expect(mocks.S.queue.strict).toBe(true)+ })++ it('a saved loop with no round running offers Start the loop', () => {+ mount({ rotation: saved, scheduleMode: 'rotation' })+ expect(names()).toEqual(['A', 'B'])+ expect(byLabel('Start the loop over')).toBeUndefined()+ click(byLabel('Start the loop'))+ expect(mocks.S.queue.ids).toEqual(['a', 'b'])+ expect(mocks.S.queue.rotationId).toBe('r1')+ })+})++describe('Plan — someone else’s queue, and a broken one', () => {+ it('an externally written pass is locked: no mode control, no edits, adoption behind a confirm', () => {+ mount({ queue: live(), scheduleMode: 'rotation' }) // no rotationId, no rotation+ expect(modeButtons()).toEqual([])+ expect(host.querySelector('.plan-mode').textContent).toContain('Externally managed')+ expect(byLabel('Build a rotation instead')).toBeUndefined()+ expect(byLabel('Edit')).toBeUndefined()+ expect(byLabel('Add routine to the rotation')).toBeUndefined()+ expect(rows()[0].querySelectorAll('button').length).toBe(0)+ expect(headings()).toContain('Also on fixed days')click(byLabel('Use this rotation'))expect(mocks.S.rotation).toBe(null) // not adopted yet — waiting on the confirmact(() => confirmSheet.mock.calls.at(-1)[0].onConfirm())@@ -135,94 +228,68 @@ describe('Plan — the rotation editor', () => {// otherwise repeat that name on every pass this app generates on its own from here on.expect(mocks.S.rotation.label).toBe('Rotation')expect(mocks.S.queue.label).toBe('Rotation')- // (the mocked store is not reactive, so re-mount to see the adopted pass render)- mount({ queue: live({ rotationId: mocks.S.rotation.id }), rotation: mocks.S.rotation })+ remount()expect(host.textContent).not.toContain('Externally managed')- expect(host.textContent).toContain('Week schedule')+ expect(selectedMode()).toBe('Rotation')})- it('an external queue keeps its rows read-only — no button but the adoption one writes rotationId', () => {- mount({ queue: live() }) // no rotationId, no rotation in state- expect(host.textContent).toContain('Externally managed')- expect(host.textContent).toContain('Week schedule')- expect(rows()[0].querySelectorAll('button').length).toBe(0) // read-only: no per-row buttons at all- expect(byLabel('Add routine to the rotation')).toBeUndefined()- // Scoped to the rotation block: the routines list further down the page has Move up/down- // buttons of its own (#142), and they are nothing to do with this pass.- const inRotation = label => [...host.querySelectorAll('.rotation button')].find(b => b.getAttribute('aria-label') === label)- expect(inRotation('Move up')).toBeUndefined()- expect(inRotation('Move down')).toBeUndefined()- expect(mocks.S.queue.rotationId).toBeUndefined()- click(byLabel('Use this rotation'))- act(() => confirmSheet.mock.calls.at(-1)[0].onConfirm())- expect(mocks.S.queue.rotationId).toBe(mocks.S.rotation.id)- })-- it('Start new pass rewinds the current one', () => {- mount({- queue: live({ since: Date.now() - 5 * 86400000, startsOn: '2026-09-01', rotationId: 'r1' }),- rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' },- })- click(byLabel('Start new pass'))- expect(mocks.S.queue.startsOn).toBe(todayISO())- expect(mocks.S.queue.ids).toEqual(['a', 'b'])- })-- it('a malformed queue offers recovery instead of an editor full of nothing', () => {+ it('a malformed queue offers recovery instead of a loop full of nothing', () => {mount({ queue: { ids: ['gone'], since: Date.now() } })expect(host.textContent).toContain('This rotation couldn’t be read')click(byLabel('Discard it'))expect(mocks.S.queue).toBe(null)})- it('Discard it leaves a clear way back in, not a hidden grid with a saved sequence stuck behind it', () => {- // A saved sequence survives the corrupt queue — without also giving up scheduleMode, that- // combination (no queue, scheduleMode still 'rotation') keeps hideGrid true and the grid's- // own "Start pass" — the way out — hidden right along with it.- mount({ queue: { ids: ['gone'], since: Date.now() }, rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })+ it('Discard it leaves a clear way back in: Rotation starts the saved loop again', () => {+ mount({ queue: { ids: ['gone'], since: Date.now() }, rotation: saved, scheduleMode: 'rotation' })click(byLabel('Discard it'))expect(mocks.S.queue).toBe(null)expect(mocks.S.scheduleMode).toBe('week')- // (the mocked store is not reactive, so re-mount to see the discarded state render)- mount({ scheduleMode: mocks.S.scheduleMode, rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })- expect(host.textContent).toContain('Week schedule')- expect(byLabel('Start pass')).toBeDefined()- click(byLabel('Start pass'))- expect(mocks.S.queue.ids).toEqual(['a', 'b'])- })-- it('a saved sequence with no live pass offers Start pass, not Build a rotation instead', () => {- // The state "Discard it" or Settings' "Use Fixed Week" leave behind: a saved rotation, no queue.- mount({ rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })- expect(host.textContent).toContain('Week schedule')- expect(byLabel('Build a rotation instead')).toBeUndefined()- click(byLabel('Start pass'))+ remount()+ expect(headings()).toContain('This week')+ pickMode('Rotation')expect(mocks.S.queue.ids).toEqual(['a', 'b'])- expect(mocks.S.queue.rotationId).toBe('r1')})- it('every routine in the rotation getting deleted still leaves a way back in, not a locked editor', () => {- // Deleting every routine from the Routines list (elsewhere in the app) leaves S.queue and- // S.rotation referencing ids that exist nowhere in S.routines any more — queueOf reads that- // as no queue at all (queueRecovery), while S.scheduleMode is still 'rotation' from before.- mount({- routines: [], // every routine gone- queue: { ids: ['a', 'b'], since: Date.now() },- rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' },- scheduleMode: 'rotation',- })- // Recovery no longer hides the grid — this is a fix-up, not the from-scratch setup gap.+ it('every routine in the loop deleted still leaves a way back in, not a locked editor', () => {+ mount({ routines: [], queue: { ids: ['a', 'b'], since: Date.now() }, rotation: saved, scheduleMode: 'rotation' })expect(host.textContent).toContain('This rotation couldn’t be read')- expect(host.textContent).toContain('Week schedule')click(byLabel('Discard it'))- expect(mocks.S.queue).toBe(null)expect(mocks.S.scheduleMode).toBe('week')- // (the mocked store is not reactive, so re-mount to see the discarded state render)- mount({ routines: [], scheduleMode: mocks.S.scheduleMode, rotation: { id: 'r1', sequence: ['a', 'b'], label: 'My split' } })- expect(host.textContent).toContain('Week schedule')- // No routine in the saved sequence survives — "Start pass" would start nothing, so the offer- // is a fresh build instead, not gated on `!S.rotation` alone (that object is still there).- expect(byLabel('Start pass')).toBeUndefined()- expect(byLabel('Build a rotation instead')).toBeDefined()+ remount()+ // nothing in the saved loop survives, so Rotation only holds the choice: a fresh build+ pickMode('Rotation')+ expect(mocks.S.queue).toBe(null)+ expect(mocks.S.scheduleMode).toBe('rotation')+ })+})++describe('Plan — Schedule extras', () => {+ it('links to the weekly muscle volume in Stats', () => {+ mount()+ click(byLabel('Weekly muscle volume') || [...host.querySelectorAll('.plan-link button')][0])+ expect(mocks.nav).toHaveBeenCalledWith('/stats?focus=weekly-volume')+ })++ it('switches to Routines and remembers it for next time', () => {+ mount()+ const seg = label => [...host.querySelectorAll('.plan-views button')].find(b => b.textContent === label)+ click(seg('Routines'))+ expect(localStorage.getItem('gym_plan_view')).toBe('routines')+ expect(host.querySelector('.plan-mode')).toBe(null)+ expect(host.querySelector('.plan-routines')).toBeTruthy()+ act(() => root.unmount()); root = createRoot(host)+ act(() => root.render(<Plan />))+ expect(seg('Routines').className).toContain('on')+ click(seg('Schedule'))+ expect(localStorage.getItem('gym_plan_view')).toBe('schedule')+ expect(host.querySelector('.plan-mode')).toBeTruthy()+ })++ it('one Plan menu holds share, print, import and the starter plans', () => {+ mount()+ click(byLabel('Plan options'))+ const items = menuSheet.mock.calls.at(-1)[0].items.filter(Boolean)+ expect(items.map(i => i.label)).toEqual(['Export plan file', 'Print / Save as PDF', 'Import a plan file', 'Load starter plan'])})})diff --git a/frontend/src/views/Plan.routine-count.test.jsx b/frontend/src/views/Plan.routine-count.test.jsxindex 1c00ed5bf..efc29633f 100644--- a/frontend/src/views/Plan.routine-count.test.jsx+++ b/frontend/src/views/Plan.routine-count.test.jsx@@ -29,7 +29,7 @@ vi.mock('../store/useStore.js', () => {vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))vi.mock('../sheets.jsx', () => ({- starterPlanSheet: vi.fn(), dayAssignSheet: vi.fn(), dayAddRoutineSheet: vi.fn(), planToolsSheet: vi.fn(),+ starterPlanSheet: vi.fn(), dayAssignSheet: vi.fn(),}))let host, root@@ -48,13 +48,14 @@ afterEach(() => {})const mount = () => act(() => root.render(<Plan />))-const countOn = day => [...host.querySelectorAll('.item')].find(el => el.querySelector('.tt')?.textContent === day)?.querySelector('.small.dim')?.textContent+// a single routine says how many exercises it has; a combined day says how many routines+const countOn = day => host.querySelector(`.plan-day[aria-label="${day}"] .ss`)?.textContentdescribe('Plan — the day header counts its routines', () => {- it('uses the singular for one routine and the plural for more', () => {+ it('names the exercises of a single routine, and counts the routines of a combined day', () => {mocks.S.week = { 1: ['r1'], 2: ['r1', 'r2'] }mount()- expect(countOn('Monday')).toBe('1 routine')+ expect(countOn('Monday')).toBe('0 exercises')expect(countOn('Tuesday')).toBe('2 routines')})})diff --git a/frontend/src/views/Plan.routine-order.test.jsx b/frontend/src/views/Plan.routine-order.test.jsxindex 63379b6b5..f9eaf7eeb 100644--- a/frontend/src/views/Plan.routine-order.test.jsx+++ b/frontend/src/views/Plan.routine-order.test.jsx@@ -1,55 +1,140 @@// @vitest-environment happy-dom// Issue #142: routines were stuck in the order they were created. `S.routines` is the single// order every screen reads — Plan, the Start screen, the day-assignment sheets — so moving one-// here moves it everywhere.+// here moves it everywhere. Since v1.3.11 the order changes in the Routines view's Edit mode,+// like on an iPhone: a handle to drag (or to move with the arrow keys) and a red minus that+// deletes behind a confirmation. No ▲▼ on every row any more.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'-vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }))+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(),+ dayAssignSheet: vi.fn(), starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), menuSheet: vi.fn(),+ planHasRoutines: () => true, exportPlanFile: vi.fn(), printWholePlan: vi.fn(), importPlanFile: vi.fn(),}))+import { confirmSheet } from '../sheets.jsx'+const routine = (id, name) => ({ id, name, emoji: null, ex: [{ id: '0025' }] })let host, rootbeforeEach(() => {globalThis.IS_REACT_ACT_ENVIRONMENT = true+ localStorage.setItem('gym_plan_view', 'routines')+ confirmSheet.mockClear(); 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'), routine('c', 'Legs A')], week: {}, dayPlan: {} }, user: null }))+ useStore.setState(s => ({ S: { ...s.S, routines: [routine('a', 'Push A'), routine('b', 'Pull A'), routine('c', 'Legs A')], week: { 1: ['b'] }, dayPlan: {} }, user: null }))})-afterEach(() => { act(() => root.unmount()); host.remove() })+afterEach(() => { act(() => root.unmount()); host.remove(); localStorage.removeItem('gym_plan_view') })const mount = () => act(() => root.render(<Plan />))-// The weekday rows above the routine list share the `.item` class, so the rows are found by the-// thing only a routine has: the move controls' own column.-const rows = () => [...host.querySelectorAll('.item')].filter(e => e.querySelector('button[aria-label="Move up"]'))+const rows = () => [...host.querySelectorAll('.plan-routines .plan-routine')]const names = () => rows().map(e => e.querySelector('.tt').textContent)-const btn = (row, label) => rows()[row].querySelector(`button[aria-label="${label}"]`)+const stored = () => useStore.getState().S.routines.map(r => r.name)+const button = text => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text)const click = el => act(() => { el.dispatchEvent(new MouseEvent('click', { bubbles: true })) })+const handles = () => [...host.querySelectorAll('[data-reorder-handle]')]+const edit = () => click(button('Edit'))+// happy-dom lays nothing out: give the rows 60px each, 68px apart (an 8px gap).+const layOut = () => rows().forEach((row, i) => {+ row.getBoundingClientRect = () => ({ top: i * 68, bottom: i * 68 + 60, height: 60, left: 0, right: 300, width: 300 })+})+const pointer = (el, type, y) => act(() => { el.dispatchEvent(new PointerEvent(type, { bubbles: true, pointerId: 1, button: 0, clientY: y })) })describe('routine order', () => {- it('moves a routine down and the stored order follows', () => {+ it('shows no move buttons outside Edit, and the days a routine is on', () => {mount()expect(names()).toEqual(['Push A', 'Pull A', 'Legs A'])- click(btn(0, 'Move down'))- expect(useStore.getState().S.routines.map(r => r.name)).toEqual(['Pull A', 'Push A', 'Legs A'])+ expect(host.querySelector('button[aria-label="Move up"]')).toBe(null)+ expect(host.querySelector('button[aria-label="Move down"]')).toBe(null)+ expect(handles()).toEqual([])+ expect(rows()[1].querySelector('.ss').textContent).toBe('1 exercise · Mo')+ })++ it('Edit shows a handle and a delete button per row; tapping a row then opens nothing', () => {+ mount()+ edit()+ expect(handles().length).toBe(3)+ expect(host.querySelectorAll('button[aria-label="Delete routine"]').length).toBe(3)+ click(rows()[0])+ expect(nav).not.toHaveBeenCalled()+ click(button('Done'))+ expect(handles()).toEqual([])+ })++ it('moves a routine with the arrow keys on its handle, and the stored order follows', () => {+ mount()+ edit()+ act(() => { handles()[0].dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })) })+ expect(stored()).toEqual(['Pull A', 'Push A', 'Legs A'])expect(names()).toEqual(['Pull A', 'Push A', 'Legs A'])+ // the ends cannot go further+ act(() => { handles()[0].dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp', bubbles: true })) })+ act(() => { handles()[2].dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })) })+ expect(stored()).toEqual(['Pull A', 'Push A', 'Legs A'])})- it('moves one up, and the ends cannot go further', () => {+ it('drags a routine by its handle to a new place', () => {mount()- click(btn(2, 'Move up'))- expect(useStore.getState().S.routines.map(r => r.name)).toEqual(['Push A', 'Legs A', 'Pull A'])- expect(btn(0, 'Move up').disabled).toBe(true)- expect(btn(2, 'Move down').disabled).toBe(true)+ edit()+ layOut()+ const h = handles()[0]+ pointer(h, 'pointerdown', 30)+ pointer(h, 'pointermove', 100)+ // while held, the row follows and the one it passed slides up into the gap+ expect(rows()[0].style.transform).toBe('translateY(70px)')+ expect(rows()[1].style.transform).toBe('translateY(-68px)')+ pointer(h, 'pointermove', 170)+ pointer(h, 'pointerup', 170)+ expect(stored()).toEqual(['Pull A', 'Legs A', 'Push A'])+ expect(rows()[0].style.transform).toBe('')})- it('leaves the arrows out when there is nothing to reorder', () => {+ it('a drag that ends where it started changes nothing, and a cancelled one neither', () => {+ mount()+ edit()+ layOut()+ const h = handles()[1]+ pointer(h, 'pointerdown', 98)+ pointer(h, 'pointermove', 110)+ pointer(h, 'pointerup', 110)+ expect(stored()).toEqual(['Push A', 'Pull A', 'Legs A'])+ pointer(h, 'pointerdown', 98)+ pointer(h, 'pointermove', 200)+ pointer(h, 'pointercancel', 200)+ expect(stored()).toEqual(['Push A', 'Pull A', 'Legs A'])+ })++ it('the red minus deletes only after the confirmation, routine, days and all', () => {+ mount()+ edit()+ click(rows()[1].querySelector('button[aria-label="Delete routine"]'))+ 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(stored()).toEqual(['Push A', 'Legs A'])+ expect(useStore.getState().S.week).toEqual({})+ })++ it('leaves the handle out when there is nothing to reorder', () => {useStore.setState(s => ({ S: { ...s.S, routines: [routine('a', 'Only one')] } }))mount()- expect(host.querySelector('button[aria-label="Move up"]')).toBe(null)+ edit()+ expect(handles()).toEqual([])+ expect(host.querySelector('button[aria-label="Delete routine"]')).toBeTruthy()+ })++ it('New routine sits at the top and opens the editor on the new routine', () => {+ mount()+ const add = button('New routine')+ expect(add.compareDocumentPosition(rows()[0]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ click(add)+ const created = useStore.getState().S.routines.at(-1)+ expect(created.name).toBe('New routine')+ expect(nav).toHaveBeenCalledWith('/plan/r/' + created.id)})})diff --git a/frontend/src/views/Plan.swipe-delete.test.jsx b/frontend/src/views/Plan.swipe-delete.test.jsxindex 2bb23a8b9..66419bec5 100644--- a/frontend/src/views/Plan.swipe-delete.test.jsx+++ b/frontend/src/views/Plan.swipe-delete.test.jsx@@ -21,13 +21,14 @@ let host, rootbeforeEach(() => {globalThis.IS_REACT_ACT_ENVIRONMENT = truenav.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() })+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')diff --git a/frontend/src/views/Plan.weekly-volume.test.jsx b/frontend/src/views/Plan.weekly-volume.test.jsxdeleted file mode 100644index 661c2543f..000000000--- a/frontend/src/views/Plan.weekly-volume.test.jsx+++ /dev/null@@ -1,69 +0,0 @@-// @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 { useStore } from '../store/useStore.js'-import Plan from './Plan.jsx'--vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }))-vi.mock('../sheets.jsx', () => ({- dayAssignSheet: vi.fn(), dayAddRoutineSheet: vi.fn(), starterPlanSheet: vi.fn(), planToolsSheet: vi.fn(),-}))--const press = { id: 'press', n: 'Press', primaries: ['chest'], secondaries: ['triceps'], custom: true }-const routines = [{ id: 'push', name: 'Push', emoji: null, ex: [{ id: press.id, sets: 2 }] }]-let host, root--beforeEach(() => {- globalThis.IS_REACT_ACT_ENVIRONMENT = true- host = document.createElement('div')- document.body.appendChild(host)- root = createRoot(host)- useStore.setState(s => ({- S: { ...s.S, lang: 'en', routines, customEx: [press], week: { 1: ['push'] }, dayPlan: {}, workouts: [] },- user: null,- }))-})-afterEach(() => { act(() => root.unmount()); host.remove() })--const mount = () => act(() => root.render(<Plan />))-const summary = () => host.querySelector('[data-weekly-muscle-volume]')--describe('Plan — weekly muscle volume', () => {- it('shows every non-zero effective-set total from the recurring schedule', () => {- mount()- expect(summary().textContent).toContain('Weekly muscle volume')- expect(summary().textContent).toContain('Chest2 sets')- expect(summary().textContent).toContain('Triceps0.8 sets')- })-- it('updates when the live weekly schedule changes', () => {- mount()- act(() => useStore.setState(s => ({ S: { ...s.S, week: { 1: ['push'], 3: 'push' } } })))- expect(summary().textContent).toContain('Chest4 sets')- expect(summary().textContent).toContain('Triceps1.6 sets')- })-- it('keeps the summary mounted when the recurring plan has no volume', () => {- useStore.setState(s => ({ S: { ...s.S, week: { 1: ['stale'] } } }))- mount()- expect(summary().textContent).toContain('No muscle volume planned.')- expect(summary().querySelector('.mrow')).toBeNull()- })-- it('omits explicit zero-weight muscles from planned volume', () => {- const zeroPress = { id: 'zero-press', n: 'Zero press', muscleWeights: { chest: 1, biceps: 0 }, custom: true }- useStore.setState(s => ({- S: {- ...s.S,- customEx: [zeroPress],- routines: [{ id: 'zero-plan', name: 'Zero plan', ex: [{ id: zeroPress.id, sets: 2 }] }],- week: { 1: ['zero-plan'] },- },- }))- mount()-- expect(summary().textContent).toContain('Chest2 sets')- expect(summary().textContent).not.toContain('Biceps')- })-})diff --git a/frontend/src/views/week-start.test.jsx b/frontend/src/views/week-start.test.jsxindex 36a510fad..d64c90c5e 100644--- a/frontend/src/views/week-start.test.jsx+++ b/frontend/src/views/week-start.test.jsx@@ -93,18 +93,17 @@ describe('Settings — week starts on', () => {describe('Plan — the week schedule follows the setting', () => {const mount = () => act(() => root.render(<Plan />))+ const planDays = () => [...host.querySelectorAll('.plan-day')].map(e => e.getAttribute('aria-label'))it('runs Monday to Sunday by default', () => {mount()- expect(dayRows().slice(0, 7)).toEqual(- ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])+ expect(planDays()).toEqual(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])})it('runs Sunday to Saturday for a Sunday profile', () => {mocks.S.weekStart = 0mount()- expect(dayRows().slice(0, 7)).toEqual(- ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])+ expect(planDays()).toEqual(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])})it('keeps a routine attached to its day, not to its position in the list', () => {@@ -112,16 +111,16 @@ describe('Plan — the week schedule follows the setting', () => {mocks.S.week = { 0: 'r1' } // Sundaymocks.S.weekStart = 0mount()- const rows = [...host.querySelectorAll('.item')]- expect(rows[0].querySelector('.tt').textContent).toBe('Sunday')- expect(rows[0].textContent).toContain('Push')+ const rows = [...host.querySelectorAll('.plan-day')]+ expect(rows[0].getAttribute('aria-label')).toBe('Sunday')+ expect(rows[0].querySelector('.tt').textContent).toBe('Push')expect(rows[1].textContent).not.toContain('Push')})})-describe('Plan — inline per-day routine management (combine routines)', () => {+describe('Plan — a combined day (combine routines)', () => {const mount = () => act(() => root.render(<Plan />))- const dayContainer = name => [...host.querySelectorAll('.item')].find(el => el.querySelector('.tt')?.textContent === name)+ const day = name => [...host.querySelectorAll('.plan-day')].find(el => el.getAttribute('aria-label') === name)beforeEach(() => {mocks.S.routines = [@@ -130,31 +129,20 @@ describe('Plan — inline per-day routine management (combine routines)', () =>]})- it('renders a sub-row per routine on a populated day, with the count hint', () => {+ it('reads as one session with both names and the routine count', () => {mocks.S.week = { 1: ['r1', 'r2'] }mount()- const mon = dayContainer('Monday')- expect(mon.textContent).toContain('Push')- expect(mon.textContent).toContain('Core')- expect(mon.textContent).toContain('2 routines')+ const mon = day('Monday')+ expect(mon.querySelector('.tt').textContent).toBe('Push + Core')+ expect(mon.querySelector('.ss').textContent).toBe('2 routines')})- it('✕ removes a routine, and drops the day key on the last removal', () => {- mocks.S.week = { 1: ['r1', 'r2'] }- mount()- const removeButtons = () => [...dayContainer('Monday').querySelectorAll('button[aria-label="Remove"]')]- act(() => { removeButtons()[1].dispatchEvent(new Event('click', { bubbles: true })) })- expect(mocks.S.week[1]).toEqual(['r1'])- mount()- act(() => { removeButtons()[0].dispatchEvent(new Event('click', { bubbles: true })) })- expect(mocks.S.week).not.toHaveProperty('1')- })-- it('an empty day stays one tappable row', () => {+ it('an empty day is a rest day, one tappable row', () => {mocks.S.week = {}mount()- const tue = dayContainer('Tuesday')- expect(tue.textContent).toContain('Rest')- expect(tue.querySelectorAll('button[aria-label="Remove"]').length).toBe(0)+ const tue = day('Tuesday')+ expect(tue.querySelector('.tt').textContent).toBe('Rest day')+ expect(tue.getAttribute('role')).toBe('button')+ expect(tue.querySelectorAll('button').length).toBe(0)})})