workout: allow renaming workout title from header menu

Add Rename workout option to the header 3-dot menu during an active workout session. Opens a bottom sheet modal with an auto-focused text field, disabled Save button when empty, and Enter key submission. Preserves custom titles when another routine is added to the session.
This commit is contained in:
ncbachh committed 2026-09-16 22:23:09 +07:00
1 parent a68a88d2da
commit 3a372b5744
5 files changed
+170 -4

No files matched your search

+122
View File
@@ -0,0 +1,122 @@
// @vitest-environment happy-dom
import { describe, expect, it, beforeEach, afterEach } from 'vitest'
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { renameWorkoutSheet, addRoutineToSessionSheet } from '../sheets.jsx'
import { buildCompletedWorkout } from './finish-workout.js'
const mounted = []
function render(open) {
open()
const sheet = useUI.getState().sheets.at(-1)
const host = document.createElement('div')
document.body.appendChild(host)
const root = createRoot(host)
mounted.push(root)
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
return host
}
const type = (el, value) => {
Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
el.dispatchEvent(new Event('input', { bubbles: true }))
}
const unmountAll = () => act(() => { mounted.splice(0).forEach(r => r.unmount()) })
describe('rename workout', () => {
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
useUI.setState({ sheets: [] })
document.body.innerHTML = ''
})
afterEach(unmountAll)
it('renames an active workout and disables save on empty input', () => {
useStore.setState(s => ({
S: {
...s.S,
active: { id: 'w1', d: '2026-08-25', start: 1, name: 'Leg Day', entries: [] },
},
}))
const host = render(() => renameWorkoutSheet())
const input = host.querySelector('input')
const saveBtn = [...host.querySelectorAll('button')].find(b => /save/i.test(b.textContent))
expect(input.value).toBe('Leg Day')
expect(saveBtn.disabled).toBe(false)
// Type blank whitespace
act(() => { type(input, ' ') })
expect(saveBtn.disabled).toBe(true)
// Type a new title and save
act(() => { type(input, 'Heavy Squats & Core') })
expect(saveBtn.disabled).toBe(false)
act(() => { saveBtn.click() })
const active = useStore.getState().S.active
expect(active.name).toBe('Heavy Squats & Core')
expect(active.customName).toBe(true)
// Survives completion
const completed = buildCompletedWorkout(active, { end: 2 })
expect(completed.name).toBe('Heavy Squats & Core')
})
it('submits on Enter key press', () => {
useStore.setState(s => ({
S: {
...s.S,
active: { id: 'w1', d: '2026-08-25', start: 1, name: 'Upper A', entries: [] },
},
}))
const host = render(() => renameWorkoutSheet())
const input = host.querySelector('input')
act(() => { type(input, 'Upper Power') })
act(() => {
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
})
const active = useStore.getState().S.active
expect(active.name).toBe('Upper Power')
expect(active.customName).toBe(true)
})
it('preserves custom renamed title when another routine is added to the session', () => {
useStore.setState(s => ({
S: {
...s.S,
routines: [
{ id: 'r1', name: 'Routine 1', ex: [{ id: 'bench_press' }] },
{ id: 'r2', name: 'Routine 2', ex: [{ id: 'squat' }] },
],
active: {
id: 'w1',
d: '2026-08-25',
start: 1,
name: 'My Special Workout',
customName: true,
routineIds: ['r1'],
entries: [{ id: 'bench_press', sets: [] }],
},
},
}))
const host = render(() => addRoutineToSessionSheet())
// Click on Routine 2
const items = [...host.querySelectorAll('.item')].filter(el => !el.classList.contains('disabled'))
expect(items.length).toBeGreaterThan(0)
act(() => { items[0].click() })
const active = useStore.getState().S.active
// The name should remain 'My Special Workout' instead of being overwritten with 'Routine 1 + Routine 2'
expect(active.name).toBe('My Special Workout')
expect(active.routineIds).toContain('r2')
})
})
+38 -1
View File
@@ -1875,7 +1875,9 @@ function AddRoutineToSession({ close }) {
if (!s.active) return
s.active.entries.push(...entries)
s.active.routineIds = [...[].concat(s.active.routineIds || []), r.id]
s.active.name = deriveSessionName(s.active.routineIds.map(id => s.routines.find(x => x.id === id)?.name).filter(Boolean))
if (!s.active.customName) {
s.active.name = deriveSessionName(s.active.routineIds.map(id => s.routines.find(x => x.id === id)?.name).filter(Boolean))
}
})
close()
toast(t('{0} added — {1}', r.name, exCount(r.ex.length)))
@@ -2050,6 +2052,41 @@ function SessionNote({ close }) {
}
export const sessionNoteSheet = () => ui().openSheet(close => <SessionNote close={close} />)
function RenameWorkout({ close }) {
const inputRef = useRef(null)
const onFocus = useSheetKeyboard(inputRef)
const st = useStore(s => s.S)
const update = useStore(s => s.update)
const A = st.active
const [name, setName] = useState(A?.name || '')
useEffect(() => { if (!A) close() }, [!A])
if (!A) return null
const trimmed = name.trim().slice(0, 60)
const canSave = trimmed.length > 0
const save = () => {
if (!canSave) return
update(s => {
if (!s.active) return
s.active.name = trimmed
s.active.customName = true
})
close()
}
return <>
<h3>{t('Rename workout')}</h3>
<input ref={inputRef} className="input" type="text" autoFocus maxLength={60} value={name}
placeholder={t('Workout title')}
onFocus={onFocus} onChange={e => setName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && canSave) save() }} />
<div style={{ height: 18 }} />
<Button variant="primary" disabled={!canSave} onClick={save}>{t('Save')}</Button>
</>
}
export const renameWorkoutSheet = () => ui().openSheet(close => <RenameWorkout close={close} />)
/* Drop-set drops and rest-pause bursts are edited inline on the set row itself (Workout.jsx) —
no sheet, no timer. A planned exercise (see the "Intensifier" config below) arrives with them
already computed via applyIntensifierPlan; an unplanned straight set can still grow one live
+2 -1
View File
@@ -12,7 +12,7 @@ import { t, exerciseNameFor } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor, warmupRestSecFor } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet, addRoutineToSessionSheet } from '../sheets.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, renameWorkoutSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet, addRoutineToSessionSheet } from '../sheets.jsx'
import { effortColor } from '../lib/effort.js'
import Icon from '../components/Icon.jsx'
import { Button, Check, NumberField } from '../components/ui.jsx'
@@ -701,6 +701,7 @@ function ActiveWorkout() {
// level down (it used to be the whole menu).
const openViewMenu = () => menuSheet({
items: [
{ icon: 'pencil', label: t('Rename workout'), onClick: renameWorkoutSheet },
{ icon: 'plus', label: t('Add routine'), sub: t('Bring another routine into this session'), onClick: addRoutineToSessionSheet },
{ icon: 'list', label: t('Layout'), sub: LAYOUT_LABEL[workoutView] || LAYOUT_LABEL.cards, onClick: openLayoutMenu },
],
@@ -65,6 +65,7 @@ vi.mock('../sheets.jsx', () => ({
barWeightSheet: vi.fn(),
exerciseNoteSheet: vi.fn(),
sessionNoteSheet: vi.fn(),
renameWorkoutSheet: vi.fn(),
}))
vi.mock('../components/Media.jsx', () => ({ default: () => null }))
vi.mock('../lib/api.js', () => ({
+7 -2
View File
@@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => {
menuSheet: vi.fn(),
effortPickerSheet: vi.fn(),
exerciseHistorySheet: vi.fn(),
renameWorkoutSheet: vi.fn(),
}
state.stopRest = vi.fn(() => { state.timer = null })
state.stopWork = vi.fn(() => { state.work = null })
@@ -76,6 +77,7 @@ vi.mock('../sheets.jsx', () => ({
// sessionNoteSheet during render, so a missing export is a render crash, not a no-op.
exerciseNoteSheet: vi.fn(),
sessionNoteSheet: vi.fn(),
renameWorkoutSheet: mocks.renameWorkoutSheet,
effortPickerSheet: mocks.effortPickerSheet,
exerciseHistorySheet: mocks.exerciseHistorySheet,
addRoutineToSessionSheet: vi.fn(),
@@ -1183,13 +1185,16 @@ describe('workout view header menu', () => {
return mocks.menuSheet.mock.calls.at(-1)[0]
}
it('leads with Add routine, then a Layout sheet with the three layouts marked current', async () => {
it('includes Rename workout and Add routine, then a Layout sheet with the three layouts marked current', async () => {
await mount([exercise('plain-bench', [false])], 0, { active: { workoutView: 'list', routineIds: [] } })
const menu = await openMenu()
expect(menu.items.filter(Boolean).map(it => it.label)).toEqual(['Add routine', 'Layout'])
expect(menu.items.filter(Boolean).map(it => it.label)).toEqual(['Rename workout', 'Add routine', 'Layout'])
expect(item(menu, 'Layout').sub).toBe('List')
await act(async () => { item(menu, 'Rename workout').onClick() })
expect(mocks.renameWorkoutSheet).toHaveBeenCalled()
const layout = await openLayout(menu)
expect(layout.items.filter(Boolean).map(it => it.label)).toEqual(['Cards', 'List', 'Compact'])
expect(item(layout, 'List').on).toBe(true)