Merge main (v1.2.14) in coach-providers

Konflikte: zwoelf Locale-Packs (beide Seiten haengen Strings an, sechs doppelte
Schluessel bereinigt), Admin.jsx/admin.css (Coach-Karte bleibt, main-Umbau uebernommen),
Workout/Home/Plan/sheets (main gewinnt), docs.html (Coach-Kapitel war doppelt).
Ungarisch und Thai sind auf main dazugekommen und bekommen die 334 Coach-Strings.
pt-BR-Fingerprint nachgezogen.
This commit is contained in:
Duarte Santos committed 2026-09-03 22:17:29 +02:00
commit 63cf1deaed
121 files changed
+17177 -747

No files matched your search

+29 -4
View File
@@ -1,5 +1,5 @@
import { useEffect } from 'react'
import { HashRouter, Routes, Route, Navigate, useNavigate, useLocation } from 'react-router-dom'
import { useEffect, useLayoutEffect, useRef } from 'react'
import { HashRouter, Routes, Route, Navigate, useNavigate, useLocation, useNavigationType } from 'react-router-dom'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { bindUI } from './components/ui.jsx'
@@ -15,6 +15,7 @@ import ErrorBoundary from './components/ErrorBoundary.jsx'
import Modals from './components/Modals.jsx'
import Toast from './components/Toast.jsx'
import RestTimer from './components/RestTimer.jsx'
import TimerFlash from './components/TimerFlash.jsx'
import Login from './views/Login.jsx'
import MobileOnboarding from './views/MobileOnboarding.jsx'
import Home from './views/Home.jsx'
@@ -30,6 +31,9 @@ import CoachChat from './views/CoachChat.jsx'
import CoachIntake from './views/CoachIntake.jsx'
import CoachSetup from './views/CoachSetup.jsx'
// last known scrollY per route, so back-navigation can put the page where it was
const scrollPositions = new Map()
bindUI(useUI) // lets the shared controls open sheets without importing the store at module scope
// theme === 'system' follows the OS/browser preference instead of a fixed choice.
@@ -48,6 +52,7 @@ function applyPrefs(theme, accent) {
function Shell() {
const navigate = useNavigate()
const loc = useLocation()
const navType = useNavigationType()
const { S, user, ready } = useStore()
const isGuest = useStore(s => s.isGuest())
const needsMobileOnboarding = useStore(s => s.needsMobileOnboarding)
@@ -66,8 +71,27 @@ function Shell() {
}, [S.theme, S.accent])
useEffect(() => { setLang(S.lang || 'en') }, [S.lang])
useEffect(() => { document.documentElement.lang = S.lang || 'en' }, [langV, S.lang])
// every tab/route change starts at the top of the page
useEffect(() => { window.scrollTo(0, 0) }, [loc.pathname])
// Forward navigation starts at the top; going back lands where you left off.
// The position is recorded from scroll events rather than read at route
// change, because by then a shorter page may already have clamped it.
const pathRef = useRef(loc.pathname)
useEffect(() => {
const onScroll = () => {
// Modals pins the body while a sheet is open; scrollY is 0 then, not a position.
if (document.body.style.position === 'fixed') return
scrollPositions.set(pathRef.current, window.scrollY)
}
window.addEventListener('scroll', onScroll, { passive: true })
return () => window.removeEventListener('scroll', onScroll)
}, [])
useLayoutEffect(() => {
pathRef.current = loc.pathname
if (navType !== 'POP') { window.scrollTo(0, 0); return }
const y = scrollPositions.get(loc.pathname) || 0
// the restored view needs a layout pass before it is tall enough to scroll to y
const frame = window.requestAnimationFrame(() => window.scrollTo(0, y))
return () => window.cancelAnimationFrame(frame)
}, [loc.pathname, navType])
// bound to the workout, not to the route — checking Stats mid-session keeps the screen on
useWakeLock(!!S.active && S.keepAwake !== false)
@@ -114,6 +138,7 @@ function Shell() {
<RestTimer />
<Modals />
<Toast />
<TimerFlash />
</>
)
}
+3 -1
View File
@@ -1,5 +1,7 @@
/* Admin dashboard — operator-facing, English-only. Sits on top of the app's tokens; nothing
here is used outside views/Admin.jsx and views/AdminCoach.jsx. */
here is used outside views/Admin.jsx and views/AdminCoach.jsx. The page is looked at maybe
twice a year, so every card says what it is for in a sentence and every state is a word, not
a colour to decode. */
.adm-intro{color:var(--label-2);font-size:14px;line-height:1.45;margin:-6px 0 16px}
+12 -2
View File
@@ -27,8 +27,13 @@ function useBodyPaths() {
}
function View({ view, levels, onMuscle, selected }) {
const activate = (event, slug) => {
if (event.key !== 'Enter' && event.key !== ' ') return
if (event.key === ' ') event.preventDefault()
onMuscle(slug)
}
return (
<svg className="bm-v" viewBox={view.vb} role="img">
<svg className="bm-v" viewBox={view.vb} role={onMuscle ? 'group' : 'img'}>
{INERT.map(slug => (view.p[slug] || []).map((d, i) =>
<path key={slug + i} className="bm-sil" d={d} />))}
{MUSCLES.map(slug => (view.p[slug] || []).map((d, i) =>
@@ -37,6 +42,11 @@ function View({ view, levels, onMuscle, selected }) {
className={'bm-m l' + (levels[slug] || 0) + (selected === slug ? ' sel' : '')}
d={d}
onClick={onMuscle ? () => onMuscle(slug) : undefined}
onKeyDown={onMuscle ? event => activate(event, slug) : undefined}
role={onMuscle ? 'button' : undefined}
tabIndex={onMuscle ? 0 : undefined}
aria-label={onMuscle ? t(MUSCLE_NAME[slug]) : undefined}
aria-pressed={onMuscle ? selected === slug : undefined}
>
<title>{t(MUSCLE_NAME[slug])}</title>
</path>))}
@@ -66,7 +76,7 @@ export default function BodyMap({ load = {}, thresholds, body = 'male', onMuscle
}
export function BodyMapLegend() {
return <div className="hm-legend">
return <div className="hm-legend" aria-label={`${t('Less')} ${t('More')}`}>
{t('Less')} <div className="hm-c l0" /><div className="hm-c l1" /><div className="hm-c l2" />
<div className="hm-c l3" /><div className="hm-c l4" /> {t('More')}
</div>
+62
View File
@@ -0,0 +1,62 @@
// @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 BodyMap, { BodyMapLegend } from './BodyMap.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
let container
let root
beforeEach(() => {
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
})
afterEach(() => {
act(() => root.unmount())
container.remove()
})
async function renderMap(props = {}) {
await act(async () => {
root.render(<BodyMap load={{ chest: 2 }} {...props} />)
})
await vi.waitFor(() => expect(container.querySelectorAll('.bm-v')).toHaveLength(2))
return container.querySelector('.bm-m[aria-label="Chest"]')
}
describe('BodyMap interaction semantics', () => {
it('keeps noninteractive maps as images without focusable muscle controls', async () => {
await renderMap()
expect(container.querySelectorAll('svg[role="img"]')).toHaveLength(2)
expect(container.querySelector('[role="button"]')).toBeNull()
})
it('exposes interactive muscles as translated pressed buttons inside groups', async () => {
const path = await renderMap({ selected: 'chest', onMuscle: vi.fn() })
expect(container.querySelectorAll('svg[role="group"]')).toHaveLength(2)
expect(path).toBeTruthy()
expect(path.tabIndex).toBe(0)
expect(path.getAttribute('aria-pressed')).toBe('true')
})
it.each(['Enter', ' '])('activates a muscle once with %s', async key => {
const onMuscle = vi.fn()
const path = await renderMap({ onMuscle })
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })
act(() => path.dispatchEvent(event))
expect(onMuscle).toHaveBeenCalledTimes(1)
expect(onMuscle).toHaveBeenCalledWith('chest')
expect(event.defaultPrevented).toBe(key === ' ')
})
it('labels the existing legend direction for assistive technology', () => {
act(() => root.render(<BodyMapLegend />))
expect(container.querySelector('.hm-legend').getAttribute('aria-label')).toBe('Less More')
})
})
+2 -1
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef } from 'react'
import { fmtVol, isoOf, todayISO, MONTHS } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { tappable } from '../lib/use-sheet-keyboard.js'
// GitHub-style activity heatmap, shaded by time trained per day.
export default function Heatmap({ S, onDay }) {
@@ -38,7 +39,7 @@ export default function Heatmap({ S, onDay }) {
const cls = 'hm-c l' + level(a) + (key === todayISO() ? ' today' : '') + (day > today ? ' future' : '')
cells.push(<div key={d} className={cls}
title={key + (a ? ` · ${t(a.n === 1 ? '{0} workout' : '{0} workouts', a.n)} · ${a.min} min · ${fmtVol(a.vol, S.unit)}` : '')}
onClick={a ? () => onDay(key) : undefined} />)
{...tappable(a ? () => onDay(key) : undefined)} />)
}
cols.push(<div key={wk} className="hm-col">{cells}</div>)
}
+6 -3
View File
@@ -8,17 +8,20 @@ import Icon from './Icon.jsx'
// Custom exercises have no media — the animation stays blank by design (issue #11).
// `minimizable` (workout view) adds a persistent minimize/expand control so the animation stops
// eating the screen; the chosen size is saved to settings and carries across exercises and
// future workouts (issue #12).
// future workouts (issue #12). Settings can also turn workout media off entirely
// (gifSize 'off') — then nothing renders here and the exercise card closes up, exactly like
// a custom exercise without media. Any other/legacy value behaves as 'full'.
export default function Media({ ex, id, compact, minimizable }) {
const [playing, setPlaying] = useState(true)
const gifSize = useStore(s => s.S.gifSize)
const update = useStore(s => s.update)
if (!ex.gif) return null
if (minimizable && gifSize === 'off') return null
const mini = minimizable && gifSize === 'mini'
const toggleSize = e => { e.stopPropagation(); update(s => { s.gifSize = mini ? 'full' : 'mini' }) }
return (
<div className={'exmedia' + (compact ? ' compact' : '') + (mini ? ' mini' : '')} id={id} onClick={() => setPlaying(p => !p)}>
<img decoding="async" src={playing ? gifSrc(ex) : imgSrc(ex)} alt={exerciseNameFor(ex)} />
<img decoding="async" draggable={false} src={playing ? gifSrc(ex) : imgSrc(ex)} alt={exerciseNameFor(ex)} />
{minimizable && (
<button className="giftoggle" onClick={toggleSize}>
<Icon name={mini ? 'expand' : 'minimize'} />{mini ? t('Expand') : t('Minimize')}
@@ -35,5 +38,5 @@ export default function Media({ ex, id, compact, minimizable }) {
export function Thumb({ ex }) {
if (!ex.img) return <div className="thumb thumb-x"><Icon name="dumbbell" /></div>
return <img className="thumb" loading="lazy" decoding="async" src={imgSrc(ex)} alt="" />
return <img className="thumb" loading="lazy" decoding="async" draggable={false} src={imgSrc(ex)} alt="" />
}
+74
View File
@@ -0,0 +1,74 @@
// @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 Media from './Media.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const mocks = vi.hoisted(() => {
const state = { S: { gifSize: 'full' } }
state.snapshot = () => ({
S: state.S,
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
})
return state
})
vi.mock('../store/useStore.js', () => {
const useStore = selector => selector(mocks.snapshot())
useStore.getState = mocks.snapshot
return { useStore }
})
const EX = { id: 'bench', n: 'bench press', gif: 'bench.gif', img: 'bench.jpg' }
let host, root
beforeEach(() => {
mocks.S = { gifSize: 'full' }
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const mount = props => act(() => root.render(<Media ex={EX} {...props} />))
describe('Media gifSize', () => {
it('renders the full animation by default and toggles to mini in the workout', () => {
mount({ minimizable: true })
expect(host.querySelector('.exmedia img')).toBeTruthy()
expect(host.querySelector('.exmedia.mini')).toBeFalsy()
act(() => { host.querySelector('.giftoggle').click() })
expect(mocks.S.gifSize).toBe('mini')
mount({ minimizable: true })
expect(host.querySelector('.exmedia.mini')).toBeTruthy()
})
it("renders nothing at all in the workout when gifSize is 'off'", () => {
mocks.S = { gifSize: 'off' }
mount({ minimizable: true })
expect(host.querySelector('.exmedia')).toBeFalsy()
expect(host.querySelector('img')).toBeFalsy()
expect(host.innerHTML).toBe('')
})
it("'off' only applies to the workout — the detail sheet (not minimizable) still shows media", () => {
mocks.S = { gifSize: 'off' }
mount({})
expect(host.querySelector('.exmedia img')).toBeTruthy()
})
it('treats a legacy/unknown value as full', () => {
mocks.S = { gifSize: 'huge' }
mount({ minimizable: true })
expect(host.querySelector('.exmedia img')).toBeTruthy()
expect(host.querySelector('.exmedia.mini')).toBeFalsy()
})
})
+44 -35
View File
@@ -5,56 +5,65 @@ import { useUI } from '../store/useUI.js'
function Sheet({ sheet }) {
const { closeSheet } = useUI()
const ref = useRef(null)
const drag = useRef({ startY: null, delta: 0 })
// startY null = no gesture. axis stays null until the finger has travelled far enough to
// tell a vertical pull from a sideways scroll; 'x' hands the gesture to whatever scrolls
// horizontally under it (chip strips, heatmap) and the sheet stays put.
const idle = () => ({ startX: null, startY: null, axis: null, delta: 0, vy: 0, lastY: 0, lastT: 0 })
const drag = useRef(idle())
const onTouchStart = e => {
// a gesture that begins on a slider (or opted-out control) belongs to that control, not to
// the sheet's swipe-to-dismiss — so it keeps working while you drag. Horizontal strips are
// opted out too: a sideways scroll must never wobble or pull down the sheet.
const NODRAG = 'input[type=range], [data-nodrag], .chips, .hm-wrap'
const begin = (target, x, y) => {
const el = ref.current
// a gesture that begins on a slider (or opted-out control) belongs to that control,
// not to the sheet's swipe-to-dismiss — so it keeps working while you drag
if (e.target.closest && e.target.closest('input[type=range], [data-nodrag]')) {
drag.current = { startY: null, delta: 0 }
return
}
drag.current = { startY: el.scrollTop <= 0 ? e.touches[0].clientY : null, delta: 0 }
if (target.closest && target.closest(NODRAG)) { drag.current = idle(); return }
if (el.scrollTop > 0) { drag.current = idle(); return }
drag.current = { ...idle(), startX: x, startY: y, lastY: y, lastT: performance.now() }
}
const onTouchMove = e => {
const move = (e, x, y) => {
const el = ref.current, d = drag.current
if (d.startY === null) return
d.delta = e.touches[0].clientY - d.startY
if (d.delta > 0 && el.scrollTop <= 0) {
// synthetic events (tests) may carry no x at all: treat that as straight down
const dx = Number.isFinite(x) ? x - d.startX : 0, dy = y - d.startY
if (d.axis === null) {
// axis lock after ~8px: clearly-more-vertical wins the sheet, anything else is a scroll
if (Math.abs(dx) < 8 && Math.abs(dy) < 8) return
d.axis = Math.abs(dy) > Math.abs(dx) * 1.2 ? 'y' : 'x'
if (d.axis === 'x') return
}
if (d.axis === 'x') return
const now = performance.now()
// velocity from the last move, so a fast short flick can still be told from a slow drag
if (now > d.lastT) { d.vy = (y - d.lastY) / (now - d.lastT); d.lastY = y; d.lastT = now }
if (dy > 0 && el.scrollTop <= 0) {
e.preventDefault()
d.delta = dy
el.style.transition = 'none'
el.style.transform = `translateY(${d.delta}px)`
} else d.delta = 0
el.style.transform = `translateY(${dy}px)`
} else if (d.delta > 0) {
// the pull reversed above the start: snap back before the sheet is allowed to scroll,
// otherwise it scrolls while still hanging below its resting place
e.preventDefault()
d.delta = 0
el.style.transform = 'translateY(0px)'
}
}
const onTouchStart = e => begin(e.target, e.touches[0].clientX, e.touches[0].clientY)
const onTouchMove = e => move(e, e.touches[0].clientX, e.touches[0].clientY)
const onTouchEnd = () => {
const el = ref.current, d = drag.current
if (d.startY === null) return
el.style.transition = 'transform .2s'
if (d.delta > 90 && !sheet.locked) { el.style.transform = 'translateY(110%)'; setTimeout(() => closeSheet(sheet.id), 180) }
// a long pull, or a short but fast flick, dismisses
const flick = d.delta > 30 && d.vy > 0.6
if ((d.delta > 90 || flick) && !sheet.locked) { el.style.transform = 'translateY(110%)'; setTimeout(() => closeSheet(sheet.id), 180) }
else el.style.transform = ''
d.startY = null
drag.current = idle()
}
// Mouse drag (desktop testing / trackpads): same swipe-to-dismiss behaviour.
const onMouseDown = e => {
if (e.button !== 0) return
if (e.target.closest && e.target.closest('input[type=range], [data-nodrag]')) {
drag.current = { startY: null, delta: 0 }
return
}
const el = ref.current
drag.current = { startY: el.scrollTop <= 0 ? e.clientY : null, delta: 0 }
}
const onMouseMove = e => {
const el = ref.current, d = drag.current
if (d.startY === null) return
d.delta = e.clientY - d.startY
if (d.delta > 0 && el.scrollTop <= 0) {
e.preventDefault()
el.style.transition = 'none'
el.style.transform = `translateY(${d.delta}px)`
} else d.delta = 0
}
const onMouseDown = e => { if (e.button === 0) begin(e.target, e.clientX, e.clientY) }
const onMouseMove = e => move(e, e.clientX, e.clientY)
const onMouseUp = () => onTouchEnd()
// non-passive touchmove so preventDefault works (bottom sheets only; centered dialogs have no ref)
+95 -2
View File
@@ -74,10 +74,11 @@ async function popstate() {
await act(async () => { window.dispatchEvent(new dom.Event('popstate')) })
}
function mouse(target, type, clientY) {
function mouse(target, type, clientY, clientX = 0) {
const event = new dom.Event(type, { bubbles: true })
Object.defineProperties(event, {
button: { value: 0 },
clientX: { value: clientX },
clientY: { value: clientY },
})
target.dispatchEvent(event)
@@ -181,13 +182,16 @@ describe('Modals mouse dragging', () => {
})
it('releases a drag when mouseup occurs outside the sheet', async () => {
// a slow pull: synthetic events fire in the same tick, which would read as a flick
let now = 0
vi.spyOn(performance, 'now').mockImplementation(() => now)
await setSheets([sheet('drag')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
mouse(sheetEl, 'mousemove', 60)
now = 300; mouse(sheetEl, 'mousemove', 60)
})
expect(sheetEl.style.transform).toBe('translateY(50px)')
@@ -199,3 +203,92 @@ describe('Modals mouse dragging', () => {
expect(mocks.state.sheets).toHaveLength(1)
})
})
describe('Modals drag axis lock and dismiss', () => {
it('ignores a sideways gesture instead of wobbling the sheet', async () => {
await setSheets([sheet('x')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10, 10)
mouse(sheetEl, 'mousemove', 20, 60)
// once locked to x, even a clearly downward move stays with the horizontal gesture
mouse(sheetEl, 'mousemove', 120, 70)
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
it('leaves horizontal chip strips to their own scrolling', async () => {
await setSheets([sheet('chips', {
render: () => React.createElement('div', { className: 'chips' }, React.createElement('button', { className: 'chip' }, 'a')),
})])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(container.querySelector('.chip'), 'mousedown', 10)
mouse(sheetEl, 'mousemove', 150)
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
it('snaps back to zero when the pull reverses instead of scrolling while offset', async () => {
await setSheets([sheet('rev')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
mouse(sheetEl, 'mousemove', 110)
})
expect(sheetEl.style.transform).toBe('translateY(100px)')
await act(async () => { mouse(sheetEl, 'mousemove', 5) })
expect(sheetEl.style.transform).toBe('translateY(0px)')
await act(async () => { window.dispatchEvent(new dom.Event('mouseup')) })
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
it('dismisses on a short but fast flick', async () => {
vi.useFakeTimers()
let now = 0
vi.spyOn(performance, 'now').mockImplementation(() => now)
await setSheets([sheet('flick')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
now = 20; mouse(sheetEl, 'mousemove', 40)
now = 60; mouse(sheetEl, 'mousemove', 80) // 70px in 60ms: ~1 px/ms
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('translateY(110%)')
await act(async () => { vi.advanceTimersByTime(200) })
expect(mocks.state.sheets).toHaveLength(0)
vi.useRealTimers()
})
it('keeps a short slow pull open', async () => {
let now = 0
vi.spyOn(performance, 'now').mockImplementation(() => now)
await setSheets([sheet('slow')])
const sheetEl = container.querySelector('.sheet')
sheetEl.scrollTop = 0
await act(async () => {
mouse(sheetEl, 'mousedown', 10)
now = 400; mouse(sheetEl, 'mousemove', 80)
window.dispatchEvent(new dom.Event('mouseup'))
})
expect(sheetEl.style.transform).toBe('')
expect(mocks.state.sheets).toHaveLength(1)
})
})
+8
View File
@@ -0,0 +1,8 @@
import { useUI } from '../store/useUI.js'
// A new key restarts the CSS sequence even when two timers finish close together.
// The layer never catches taps and ends transparent, so it can safely stay mounted.
export default function TimerFlash() {
const id = useUI(s => s.timerFlashId)
return id ? <div key={id} className="timer-flash" aria-hidden="true" /> : null
}
+148 -25
View File
@@ -60,11 +60,11 @@ export function TextArea({ className = '', ...rest }) {
return <textarea className={'field area ' + className} {...rest} />
}
export function SearchField({ value, onChange, onClear, ...rest }) {
export const SearchField = forwardRef(function SearchField({ value, onChange, onClear, ...rest }, ref) {
return (
<div className="searchf">
<Icon name="magnifier" className="lead" />
<input className="field" value={value} onChange={onChange} {...rest} />
<input ref={ref} className="field" value={value} onChange={onChange} {...rest} />
{!!value && (
<button className="clear" onClick={onClear} aria-label="Clear">
<Icon name="xmark" />
@@ -72,7 +72,7 @@ export function SearchField({ value, onChange, onClear, ...rest }) {
)}
</div>
)
}
})
/* ============================ switch ============================ */
@@ -115,16 +115,52 @@ export function Segmented({ options, value, onChange, className = '' }) {
/* ============================ stepper ============================ */
export function Stepper({ value, step = 1, onChange, decimal = true, className = '', label, unit }) {
export function Stepper({ value, step = 1, onChange, decimal = true, className = '', label, unit, invalid = false }) {
const set = v => onChange(Math.max(0, Math.round((v || 0) * 100) / 100))
// Holding a button repeats the step; the latest value/step live in a ref so
// the interval doesn't keep stepping from the value it was started with.
const live = useRef({ value, step, set })
live.current = { value, step, set }
const hold = useRef({ delay: null, tick: null, count: 0, repeated: false })
const bump = dir => { const { value, step, set } = live.current; set((+value || 0) + dir * step) }
const stopHold = () => {
const h = hold.current
window.clearTimeout(h.delay); window.clearInterval(h.tick)
h.delay = h.tick = null
}
const startHold = dir => {
stopHold()
const h = hold.current
h.repeated = false; h.count = 0
h.delay = window.setTimeout(() => {
const run = () => {
h.repeated = true; h.count++
bump(dir)
// modest acceleration after a bit of holding so a long hold covers ground
if (h.count === 15) { window.clearInterval(h.tick); h.tick = window.setInterval(run, 40) }
}
h.tick = window.setInterval(run, 80)
}, 400)
}
// The click that follows pointerup must not add a step once the hold repeated.
const click = dir => {
if (hold.current.repeated) { hold.current.repeated = false; return }
bump(dir)
}
useEffect(() => stopHold, [])
const holdProps = dir => ({
onPointerDown: e => { if (e.button === 0 || e.button == null) startHold(dir) },
onPointerUp: stopHold, onPointerCancel: stopHold, onPointerLeave: stopHold, onBlur: stopHold,
onClick: () => click(dir),
})
const inner = (
<div className={'stp ' + className}>
<button onClick={() => set((+value || 0) - step)} aria-label="Decrease"><Icon name="minus" /></button>
<button {...holdProps(-1)} aria-label="Decrease"><Icon name="minus" /></button>
<span className="val">
<NumberField value={value} decimal={decimal} onChange={onChange} />
<NumberField value={value} decimal={decimal} onChange={onChange} aria-invalid={invalid ? 'true' : undefined} />
{unit && <i>{unit}</i>}
</span>
<button onClick={() => set((+value || 0) + step)} aria-label="Increase"><Icon name="plus" /></button>
<button {...holdProps(1)} aria-label="Increase"><Icon name="plus" /></button>
</div>
)
if (!label) return inner
@@ -136,9 +172,13 @@ export function Stepper({ value, step = 1, onChange, decimal = true, className =
// Pointer-driven so the fill, track and thumb are all ours — no ::-webkit-*
// pseudo-elements, which is the only way the control looks identical on every
// platform and can pick up the accent colour.
export const SLIDER_GRAB_PX = 22
export function Slider({ value, min = 0, max = 100, step = 1, onChange, className = '' }) {
const ref = useRef(null)
const [drag, setDrag] = useState(false)
// Grabbing the knob drags it relative to where the finger landed; a finger
// is ~22px wide, so a touch that far off still means "the knob", not "jump".
const offset = useRef(0)
const pct = Math.min(100, Math.max(0, ((value - min) / (max - min)) * 100))
const posToValue = useCallback(clientX => {
@@ -156,7 +196,7 @@ export function Slider({ value, min = 0, max = 100, step = 1, onChange, classNam
if (!drag) return
const move = e => {
e.preventDefault()
onChange(posToValue(e.touches ? e.touches[0].clientX : e.clientX))
onChange(posToValue((e.touches ? e.touches[0].clientX : e.clientX) - offset.current))
}
const up = () => setDrag(false)
window.addEventListener('pointermove', move)
@@ -186,7 +226,15 @@ export function Slider({ value, min = 0, max = 100, step = 1, onChange, classNam
aria-valuenow={value} aria-valuemin={min} aria-valuemax={max}
data-nodrag /* keeps the sheet from swipe-dismissing */
onKeyDown={key}
onPointerDown={e => { e.currentTarget.setPointerCapture?.(e.pointerId); setDrag(true); onChange(posToValue(e.clientX)) }}
onPointerDown={e => {
e.currentTarget.setPointerCapture?.(e.pointerId)
const r = e.currentTarget.getBoundingClientRect()
const knobX = r.left + (pct / 100) * r.width
const d = e.clientX - knobX
offset.current = Math.abs(d) <= SLIDER_GRAB_PX ? d : 0
setDrag(true)
if (!offset.current) onChange(posToValue(e.clientX))
}}
>
<span className="sld-track"><span className="sld-fill" style={{ width: pct + '%' }} /></span>
<span className="sld-knob" style={{ left: pct + '%' }} />
@@ -248,25 +296,12 @@ export function Row({ icon, iconTint, title, subtitle, value, accessory = 'none'
// theme entirely — on dark mode it flashes a white sheet — and can't show more
// than a bare label per option. This opens our own sheet with a checkmark on the
// current value, which is also how iOS itself handles a long option list.
export function SelectRow({ icon, iconTint, title, value, options, onChange, sheetTitle, stackedValue = false }) {
export function SelectRow({ icon, iconTint, title, value, options, onChange, sheetTitle, stackedValue = false, search }) {
const cur = options.find(o => o.value === value)
const open = () => {
const { openSheet } = require_ui()
const h = openSheet(close => (
<>
<h3>{sheetTitle || title}</h3>
<div className="sect-b">
{options.map(o => (
<button key={o.value} className="lrow tap" onClick={() => { close(); onChange(o.value) }}>
<span className="lrow-m"><span className="lrow-t">{o.label}</span>
{o.subtitle && <span className="lrow-s">{o.subtitle}</span>}</span>
{o.value === value && <Icon name="check" className="lrow-k" />}
</button>
))}
</div>
<div style={{ height: 8 }} />
</>
))
const h = openSheet(close => <SelectSheet title={sheetTitle || title} value={value} options={options}
onChange={onChange} search={search} close={close} />)
return h
}
return (
@@ -275,6 +310,94 @@ export function SelectRow({ icon, iconTint, title, value, options, onChange, she
)
}
function SelectSheet({ title, value, options, onChange, search, close }) {
const [query, setQuery] = useState('')
const inputRef = useRef(null)
const firstVisibleRef = useRef(null)
const syncPickerViewport = useCallback(() => {
const input = inputRef.current
const sheet = input?.closest('.sheet')
const viewport = window.visualViewport
if (!sheet || !viewport) return
const visualHeight = Math.max(0, viewport.height || window.innerHeight)
const visualBottom = (viewport.offsetTop || 0) + visualHeight
const bottomInset = Math.max(0, window.innerHeight - visualBottom)
sheet.style.setProperty('--picker-keyboard-bottom', `${bottomInset}px`)
sheet.style.setProperty('--picker-visual-height', `${visualHeight}px`)
}, [])
const matcher = typeof search === 'function' ? search : search?.match
const visible = matcher ? options.filter(o => matcher(o, query)) : options
useEffect(() => {
if (!search) return
const viewport = window.visualViewport
if (!viewport) return
const sync = () => syncPickerViewport()
sync()
viewport.addEventListener('resize', sync)
viewport.addEventListener('scroll', sync)
return () => {
viewport.removeEventListener('resize', sync)
viewport.removeEventListener('scroll', sync)
const sheet = inputRef.current?.closest('.sheet')
sheet?.style.removeProperty('--picker-keyboard-bottom')
sheet?.style.removeProperty('--picker-visual-height')
}
}, [search, syncPickerViewport])
// Filtering can leave the first result underneath the mobile keyboard. Keep the
// correction local to the sheet instead of letting focus/scrollIntoView move the page.
useEffect(() => {
if (!query.trim() || !visible.length) return
const input = inputRef.current
if (!input || document.activeElement !== input) return
const schedule = callback => window.requestAnimationFrame
? window.requestAnimationFrame(callback)
: window.setTimeout(callback, 0)
const cancel = frame => window.cancelAnimationFrame
? window.cancelAnimationFrame(frame)
: window.clearTimeout(frame)
const frame = schedule(() => {
if (document.activeElement !== input) return
const option = firstVisibleRef.current
const sheet = option?.closest('.sheet')
if (!option || !sheet) return
const viewport = window.visualViewport
const visualBottom = viewport ? (viewport.offsetTop || 0) + viewport.height : window.innerHeight
const sheetBottom = sheet.getBoundingClientRect().bottom || visualBottom
const hiddenBy = option.getBoundingClientRect().bottom - Math.min(visualBottom, sheetBottom) + 8
if (hiddenBy <= 0) return
const maxScroll = Math.max(0, sheet.scrollHeight - sheet.clientHeight)
const nextScroll = Math.min(maxScroll, Math.max(0, sheet.scrollTop + hiddenBy))
if (nextScroll !== sheet.scrollTop) sheet.scrollTop = nextScroll
})
return () => cancel(frame)
}, [query, visible.length])
return (
<>
<h3>{title}</h3>
{search && <div className="picker-search">
<SearchField value={query} onChange={e => setQuery(e.target.value)} onInput={e => setQuery(e.target.value)}
onClear={() => setQuery('')} onFocus={syncPickerViewport} ref={inputRef} placeholder={search.placeholder} aria-label={search.label || search.placeholder} />
</div>}
<div className="sect-b">
{visible.map((o, index) => (
<button key={o.value} ref={index === 0 ? firstVisibleRef : undefined} className="lrow tap" onClick={() => { close(); onChange(o.value) }}>
<span className="lrow-m"><span className="lrow-t">{o.label}</span>
{o.subtitle && <span className="lrow-s">{o.subtitle}</span>}</span>
{o.value === value && <Icon name="check" className="lrow-k" />}
</button>
))}
{!visible.length && search && <div className="empty">
<div className="ico"><Icon name="magnifier" /></div>{search.emptyLabel}
</div>}
</div>
<div style={{ height: 8 }} />
</>
)
}
/** Multi-select row for additive exercise metadata. The sheet mirrors selection locally so
* each tap updates its checkmark immediately while the caller persists the value. */
export function MultiSelectRow({ icon, iconTint, title, values, options, onToggle, sheetTitle, noneLabel, doneLabel }) {
+108
View File
@@ -0,0 +1,108 @@
// @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 { Slider, Stepper, SLIDER_GRAB_PX } from './ui.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
let host, root
beforeEach(() => {
vi.useFakeTimers()
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
vi.useRealTimers()
})
function pointer(target, type, { x = 0, y = 0, button = 0 } = {}) {
const event = new Event(type, { bubbles: true, cancelable: true })
for (const [k, v] of Object.entries({ pointerId: 1, pointerType: 'touch', isPrimary: true, button, clientX: x, clientY: y })) {
Object.defineProperty(event, k, { configurable: true, value: v })
}
act(() => target.dispatchEvent(event))
return event
}
describe('Slider', () => {
// 300px track from x=100 to x=400 over 0..300 so 1px == 1 unit
const mountSlider = (value, onChange) => {
act(() => root.render(<Slider value={value} min={0} max={300} step={1} onChange={onChange} />))
const el = host.querySelector('.sld')
vi.spyOn(el, 'getBoundingClientRect').mockReturnValue({ left: 100, right: 400, width: 300, top: 0, bottom: 20, height: 20, x: 100, y: 0 })
return el
}
it('drags relative to the grab point when the touch lands on the knob', () => {
const onChange = vi.fn()
const el = mountSlider(80, onChange) // knob at x=180
pointer(el, 'pointerdown', { x: 180 + SLIDER_GRAB_PX - 2 })
expect(onChange).not.toHaveBeenCalled() // grabbing must not jump
pointer(window, 'pointermove', { x: 180 + SLIDER_GRAB_PX - 2 + 60 })
expect(onChange).toHaveBeenLastCalledWith(140) // moved by 60, not to the finger
pointer(window, 'pointerup')
})
it('still jumps to the touched position away from the knob', () => {
const onChange = vi.fn()
const el = mountSlider(80, onChange)
pointer(el, 'pointerdown', { x: 350 })
expect(onChange).toHaveBeenLastCalledWith(250)
pointer(window, 'pointermove', { x: 360 })
expect(onChange).toHaveBeenLastCalledWith(260)
pointer(window, 'pointerup')
})
})
describe('Stepper', () => {
// controlled like every real caller: the parent re-renders with the new value
function Host({ initial, onChange, step }) {
const [v, setV] = React.useState(initial)
return <Stepper value={v} step={step} onChange={n => { setV(n); onChange(n) }} />
}
const mountStepper = (value, onChange, step = 1) => {
act(() => root.render(<Host initial={value} step={step} onChange={onChange} />))
return host.querySelector('button[aria-label="Increase"]')
}
it('steps once for a short tap (pointerdown, pointerup, click)', () => {
const onChange = vi.fn()
const plus = mountStepper(10, onChange)
pointer(plus, 'pointerdown'); pointer(plus, 'pointerup')
act(() => plus.click())
expect(onChange).toHaveBeenCalledTimes(1)
expect(onChange).toHaveBeenCalledWith(11)
})
it('repeats while held and swallows the trailing click', () => {
let value = 10
const onChange = vi.fn(v => { value = v })
const plus = mountStepper(value, onChange)
pointer(plus, 'pointerdown')
act(() => vi.advanceTimersByTime(399))
expect(onChange).not.toHaveBeenCalled()
// one act per tick: in the browser every interval callback is its own task
act(() => vi.advanceTimersByTime(1 + 80))
act(() => vi.advanceTimersByTime(80))
act(() => vi.advanceTimersByTime(80))
expect(onChange).toHaveBeenCalledTimes(3)
// each repeat builds on the latest value, not the one the hold started with
expect(onChange).toHaveBeenLastCalledWith(13)
pointer(plus, 'pointerup')
act(() => plus.click())
expect(onChange).toHaveBeenCalledTimes(3)
act(() => vi.advanceTimersByTime(1000))
expect(onChange).toHaveBeenCalledTimes(3) // nothing keeps ticking after release
})
it('keeps working from the keyboard (click without a pointer)', () => {
const onChange = vi.fn()
const plus = mountStepper(10, onChange)
act(() => plus.click())
expect(onChange).toHaveBeenCalledWith(11)
})
})
+2
View File
@@ -0,0 +1,2 @@
// generated by scripts/build-hu-exercise-names.mjs — edit scripts/exercise-name-sources/hu.json
export default {"1000":"gumiszalagos egylábas fordított vádliemelés","1001":"gumiszalagos egylábas terpeszguggolás","1002":"gumiszalagos fekvő nyújtott lábemelés","1003":"gumiszalagos guggoló evezés","1004":"gumiszalagos guggolás","1005":"gumiszalagos álló hasprés","1007":"gumiszalagos álló csavart hasprés","1008":"gumiszalagos fellépés","1009":"gumiszalagos feszes lábú felhúzás","1010":"gumiszalagos nyújtott lábú felhúzás","1011":"gumiszalagos ülő csavarás","1012":"gumiszalagos csavart fejnyomás","1013":"gumiszalagos alsó fogású lehúzás","1014":"gumiszalagos v-felülés","1015":"gumiszalagos függőleges pallof-nyomás","1016":"gumiszalagos csuklóhajlítás","1017":"gumiszalagos y-emelés","1018":"gumiszalagos vállvonás","1022":"gumiszalagos álló hátsó váll evezés","1023":"gumiszalagos egyenes hátú, feszes lábú felhúzás","1160":"burpee","1167":"dinamikus mellizom-nyújtás","1201":"súlyzós burpee","1253":"emelőkaros szamár vádliemelés","1254":"gumiszalagos fekvenyomás","1255":"lejtős pullover rúddal","1256":"fordított fogású lejtős fekvenyomás rúddal","1257":"fordított fogású ferde fekvenyomás rúddal","1258":"rúd széles fordított fogású fekvenyomás","1259":"mellizom nyújtás fej mögött","1260":"kábel lejtős egykaros nyomás","1261":"kábel lejtős nyomás","1262":"kábel egykaros lejtős mellizom repülés","1263":"kábel egykaros repülés fitneszlabdán","1264":"kábel egykaros ferde repülés fitneszlabdán","1265":"kábel egykaros ferde nyomás","1266":"kábel egykaros ferde nyomás fitneszlabdán","1267":"kábel egykaros nyomás fitneszlabdán","1268":"kábel nyomás fitneszlabdán","1269":"kábel álló egyenes törzsű keresztezés","1270":"kábel felső mellizom keresztezés","1271":"mell és elülső váll nyújtás","1272":"mellizom nyújtás fitneszlabdával","1273":"tapsos fekvőtámasz","1274":"mély fekvőtámasz súlyzóval","1275":"leejtős fekvőtámasz","1276":"súlyzós egykaros lejtős pados repülés","1277":"súlyzós repülés fitneszlabdán","1278":"súlyzós ferde pados repülés fitneszlabdán","1279":"súlyzós ferde pados egykaros repülés","1280":"súlyzós ferde pados egykaros repülés fitneszlabdán","1281":"súlyzós ferde pados egykaros nyomás","1282":"súlyzós ferde pados egykaros nyomás fitneszlabdán","1283":"súlyzós ferde pados nyomás fitneszlabdán","1284":"súlyzós fekvő pullover fitneszlabdán","1285":"súlyzós egykaros pados repülés","1286":"súlyzós egykaros mellizom repülés fitneszlabdán","1287":"súlyzós egykaros lejtős pados mellnyomás","1288":"súlyzós egykaros repülés fitneszlabdán","1289":"súlyzós egykaros ferde pados mellnyomás","1290":"súlyzós egykaros nyomás fitneszlabdán","1291":"súlyzós egykaros pullover fitneszlabdán","1292":"súlyzós egylábas repülés fitneszlabdán","1293":"súlyzós nyomás fitneszlabdán","1294":"súlyzós pullover csípőnyújtással fitneszlabdán","1295":"súlyzós pullover fitneszlabdán","1296":"fitneszlabdás pike fekvőtámasz","1297":"izometrikus mellizom-összenyomás","1298":"kettlebell egykaros fekvő nyomás","1299":"emelőkaros ferde mellnyomás","1300":"emelőkaros lejtős mellnyomás","1301":"gépi belső mellnyomás","1302":"medicinlabda mellpassz","1303":"medicinlabda melltolás hárompontos állásból","1304":"medicinlabda melltolás sorozatban","1305":"medicinlabda melltolás egyszer","1306":"plyometrikus fekvőtámasz","1307":"fekvőtámasz bosu labdán","1308":"széles fogású fekvenyomás Smith-gépen","1309":"széles fogású negatív fekvenyomás Smith-gépen","1310":"súlyozott ejtő fekvőtámasz","1311":"széles tenyérállású fekvőtámasz","1312":"medicinlabda melltolás nekifutásból","1313":"emelőkaros egyoldali evezés","1314":"törzsemelés fitneszlabdán","1316":"hajlított karú pullover rúddal","1317":"fordított fogású ferde evezés rúddal","1318":"kábel ferde padon evezés","1319":"kábel csuklóforgatásos evezés","1320":"kábel köteles keresztezett ülő evezés","1321":"kábel köteles emelt ülő evezés","1322":"kábel köteles ferde padon evezés nyújtással","1323":"kábel köteles ülő evezés","1324":"kábel felső evezés","1325":"kábel széles fogású tarkó mögötti lehúzás","1326":"húzódzkodás alulfogással","1327":"szűk fogású húzódzkodás alulfogással","1328":"súlyzós fekvő hátsó delta evezés","1329":"súlyzós forgó fogású döntött törzsű evezés","1330":"súlyzós fordított fogású ferde pados egykaros evezés","1331":"súlyzós fordított fogású ferde pados kétkaros evezés","1332":"fitneszlabdás váltott karemelés","1333":"fitneszlabdás hátfeszítés nyújtott karral","1334":"fitneszlabdás hátfeszítés tarkóra tett kézzel","1335":"fitneszlabdás hátfeszítés talajtól elemelt térddel","1336":"fitneszlabdás hátfeszítés csavarással","1338":"fitneszlabda-ölelés","1339":"fitneszlabdás széles hLine truncated
+77 -11
View File
@@ -183,7 +183,15 @@ body.resting #app{padding-bottom:calc(250px + var(--sab))}
transition:background var(--fast),transform var(--fast);
}
.iconbtn:active{background:var(--surface-2);transform:scale(.92)}
/* invisible hit-area extension: these look right at their size but fall short of a
finger-sized target, so the pseudo element widens what the tap lands on without
changing the painted box. Segmented buttons sit flush against each other, so they
only grow vertically or the neighbour would steal the edge of the tap. */
.iconbtn,.chip,.seg button,.helpbtn{position:relative}
.iconbtn::before,.chip::before,.seg button::before,.helpbtn::before{content:'';position:absolute;inset:-6px}
.seg button::before{inset:-6px 0}
.iconbtn.on-ss{background:var(--acc-soft);color:var(--acc)}
.iconbtn:disabled{opacity:.32}
h4.sec{
font-size:13px;font-weight:400;letter-spacing:-.004em;color:var(--label-2);
@@ -235,8 +243,12 @@ h4.sec{
.lrow-s{font-size:13px;color:var(--label-2);line-height:1.3}
/* flex:none would let a long value ("Follow the routine (Linear progression)") run straight
through the title next to it, since the title's column is already free to shrink to nothing.
Letting the value shrink and ellipsise instead keeps the two out of each other's way. */
.lrow-v{color:var(--label-2);font-size:17px;letter-spacing:-.012em;flex:0 1 auto;min-width:0;
Letting the value shrink and ellipsise instead keeps the two out of each other's way.
The cap is max-width, not flex-basis: .lrow-m is flex:1, so its basis is 0 and it absorbs
none of the shrink — a long value would otherwise take the whole row and squeeze the title
to 21px. A basis of 45% fixes that but reserves the space even for "3", costing the title
141px on the rows that need it most. A cap does neither. */
.lrow-v{color:var(--label-2);font-size:17px;letter-spacing:-.012em;flex:0 1 auto;max-width:45%;min-width:0;
overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:right}
.lrow-c{color:var(--label);font-size:15px;flex:none;--icon-stroke:2.4}
.lrow-k{color:var(--acc);font-size:17px;flex:none;--icon-stroke:2.4}
@@ -376,7 +388,20 @@ h4.sec{
transition:background var(--fast);text-align:left;width:100%;
}
.item:active{background:var(--surface-2)}
.routine-list{position:relative}
.routine-drag-row{touch-action:pan-y;-webkit-touch-callout:none;position:relative;transition:transform var(--fast) var(--ease)}
.routine-list.is-reordering{user-select:none;-webkit-user-select:none}
.routine-list.is-reordering .routine-drag-row{transition:none}
.routine-drag-row.is-dragging{z-index:2;pointer-events:none}
.routine-drag-row.is-dragging .item{box-shadow:0 10px 28px rgba(0,0,0,.22);background:var(--surface-2)}
.routine-drop-indicator{
position:absolute;left:6px;right:6px;height:3px;border-radius:99px;
background:var(--acc);transform:translateY(-50%);pointer-events:none;z-index:3;
}
.thumb{width:50px;height:50px;border-radius:9px;object-fit:cover;background:#fff;flex:none}
/* exercise pictures are decoration inside tappable rows/cards: no save-image callout on
a long press and no drag ghost when a scroll starts on the picture */
.thumb,.exmedia img{-webkit-touch-callout:none;-webkit-user-drag:none;user-select:none;-webkit-user-select:none}
.thumb-x{
display:flex;align-items:center;justify-content:center;font-size:21px;
background:var(--surface-2);color:var(--label-2);
@@ -398,6 +423,14 @@ h4.sec{
scrollbar-width:none;-webkit-overflow-scrolling:touch;
}
.chips::-webkit-scrollbar{display:none}
/* horizontal strips: keep a sideways overscroll from chaining to the page and leave a
margin when a chip is scrolled into view. The chip row also claims the horizontal axis
(touch-action:pan-x): on a phone a slightly diagonal swipe along the chips used to hand
the gesture to the page, which scrolled down instead. The row is 32px tall, so losing a
vertical scroll that happens to start on it costs nothing; the ~130px heatmap wrap keeps
both axes, there the trade-off goes the other way. */
.chips,.hm-wrap{overscroll-behavior-x:contain;scroll-padding-inline:16px}
.chips{touch-action:pan-x}
.chip{
flex:none;padding:6px 13px;border-radius:99px;background:var(--surface);
font-size:14px;font-weight:400;color:var(--label);text-transform:capitalize;
@@ -518,14 +551,19 @@ h4.sec{
.stp button:active{background:var(--surface-3)}
.stp .val{
flex:1;min-width:0;display:flex;align-items:baseline;justify-content:center;gap:3px;padding:0 2px;
align-self:stretch;
}
.stp .val i{font-style:normal;font-size:12px;color:var(--label-2);flex:none}
.stp .num{
width:100%;min-width:0;text-align:center;background:none;border:none;outline:none;
font-size:17px;font-weight:500;letter-spacing:-.012em;padding:0;
-moz-appearance:textfield;appearance:textfield;
/* the field is the whole height of the stepper, not just its 18px text line, so a tap
anywhere between the two buttons focuses it */
height:100%;min-height:40px;cursor:text;
}
.stp .num::-webkit-inner-spin-button{display:none}
.stp.invalid{box-shadow:inset 0 0 0 1px var(--red)}
/* --- slider --- */
.sld{position:relative;height:32px;display:flex;align-items:center;cursor:pointer;touch-action:none}
@@ -544,12 +582,15 @@ h4.sec{
/* --- checkbox --- */
.chk,.ck{
width:30px;height:30px;border-radius:50%;flex:none;
width:30px;height:30px;border-radius:50%;flex:none;position:relative;
display:flex;align-items:center;justify-content:center;
background:none;box-shadow:inset 0 0 0 1.8px var(--label-4);color:transparent;
transition:background var(--fast),box-shadow var(--fast),color var(--fast),transform var(--fast);
}
.chk .icn{font-size:16px;--icon-stroke:2.6}
/* 30px is the right look next to a stepper but a poor target: extend the tap area to 44px
without painting it; the left side stays shorter so the stepper's + button keeps its edge */
.chk::before,.ck::before{content:'';position:absolute;inset:-7px -7px -7px -4px}
.chk.on{background:var(--acc);box-shadow:none;color:var(--on-acc)}
.chk:active,.ck:active{transform:scale(.9)}
.ck svg{
@@ -605,16 +646,16 @@ h4.sec{
.setrow .stp button{width:32px;height:40px}
/* a 3rd stepper (RIR) needs narrower buttons and a tighter row gap to fit next to weight+reps
on narrow phones, same technique as the exercise-config sheet's three-steppers-in-a-row
(.cfgrow below) — RIR's own value is short ("1.5") so its buttons shrink the most, weight/reps
just enough to make room since their values ("82.5", "12") need more of what's left.
(.cfgrow below). The buttons stay 28px wide — anything narrower is a miss-prone target —
so the room comes from the smaller glyphs and from the value fields giving up their padding.
The header shares the numbers so its labels stay centred over the steppers they name. */
.setrow.eff3,.sethead.eff3{gap:6px}
.setrow.eff3 .stp.w,.sethead.eff3 .w-sp{flex:1.2}
.setrow.eff3 .stp.r,.sethead.eff3 .r-sp{flex:1}
.setrow.eff3 .stp.eff,.sethead.eff3 .eff-sp{flex:.85}
.setrow.eff3 .stp button{width:23px}
.setrow.eff3 .stp.eff button{width:20px}
.setrow.eff3 .stp button{width:28px;font-size:14px}
.setrow.eff3 .stp .num{font-size:14px}
.setrow.eff3 .stp .val{padding:0}
.setrow.done .n{background:var(--acc);color:var(--on-acc)}
.setrow.done{opacity:.45}
/* drop-set drops / rest-pause bursts riding on a work row, editable like the row itself
@@ -623,7 +664,7 @@ h4.sec{
.subrow .subn{font-size:11px;color:var(--label-3);flex:none;width:46px}
.subrow .stp.mini{flex:1;min-width:0}
.subrow .stp.mini button{width:26px;height:30px}
.subrow .stp.mini .num{font-size:13px}
.subrow .stp.mini .num{font-size:13px;min-height:30px}
.subrow .iconbtn{width:26px;height:26px;font-size:11px;flex:none}
.setextra{display:flex;flex-wrap:wrap;gap:6px;margin:2px 0 8px 32px}
.setextra .chip.add{display:inline-flex;align-items:center;gap:4px;color:var(--acc)}
@@ -631,8 +672,8 @@ h4.sec{
.setextra .chip.add:disabled{opacity:.35}
/* why the next target is what it is (issue #17) */
.progline{
display:flex;align-items:flex-start;gap:7px;margin:6px 0 2px;
font-size:13px;line-height:1.38;color:var(--acc);
width:100%;display:flex;align-items:flex-start;gap:7px;margin:6px 0 2px;padding:0;
text-align:left;font-size:13px;line-height:1.38;color:var(--acc);
}
.progline.warn{color:var(--yellow)}
.progline svg{flex:none;margin-top:2px}
@@ -698,14 +739,24 @@ h4.sec{
position:absolute;left:0;right:0;bottom:0;background:var(--bg-el);
border-radius:var(--r-xl) var(--r-xl) 0 0;
padding:8px 18px calc(20px + var(--sab));
max-height:90vh;overflow-y:auto;-webkit-overflow-scrolling:touch;
max-height:90vh;max-height:min(90vh,calc(100dvh - 8px));
overflow-y:auto;-webkit-overflow-scrolling:touch;scroll-padding-bottom:calc(20px + var(--sab));
animation:sheetup .34s var(--ease);
overscroll-behavior:contain;touch-action:pan-y;will-change:transform;
}
.sheet:has(.picker-search){
bottom:var(--picker-keyboard-bottom,0px);
max-height:min(90vh,calc(100dvh - 8px),calc(var(--picker-visual-height,100vh) - 8px));
}
:root[data-theme="light"] .sheet{background:var(--bg)}
@keyframes sheetup{from{transform:translateY(100%)}to{transform:none}}
.sheet .grab{width:36px;height:5px;border-radius:99px;background:var(--label-4);margin:6px auto 14px}
.sheet h3{font-size:20px;font-weight:600;letter-spacing:-.021em;margin-bottom:14px}
.picker-search{
position:sticky;top:0;z-index:2;margin-bottom:0;padding-bottom:10px;
background:var(--bg-el);
}
:root[data-theme="light"] .picker-search{background:var(--bg)}
.center{
position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);
width:min(84vw,300px);background:var(--bg-el);border-radius:var(--r-lg);padding:20px;
@@ -751,6 +802,19 @@ h4.sec{
.glyph-cell:active{transform:scale(.92)}
.glyph-cell.on{background:var(--acc);color:var(--on-acc)}
/* --- opt-in timer completion flash ---
Four deliberate pulses over 2.4s stay below three flashes per second. Transparent
gaps keep the black and white pulses visually distinct. */
.timer-flash{
position:fixed;inset:0;z-index:1000;pointer-events:none;opacity:0;
animation:timer-flash-four 2.4s linear both;
}
@keyframes timer-flash-four{
0%,20%,28%,48%,56%,76%,84%,100%{opacity:0}
4%,16%,60%,72%{background:#000;opacity:1}
32%,44%,88%,96%{background:#fff;opacity:1}
}
/* --- big weight readout --- */
.bwstep{display:flex;align-items:center;justify-content:center;gap:18px;margin:14px 0 6px}
.bw-pm{
@@ -838,6 +902,7 @@ h4.sec{
.bm-m.sel{stroke:var(--label);stroke-width:7}
.bodymap.tappable .bm-m{cursor:pointer}
.bodymap.tappable .bm-m:focus-visible{outline:none;stroke:var(--label);stroke-width:7;filter:drop-shadow(0 0 2px var(--surface))}
/* A hairline in the surface colour separates neighbouring muscles; the artwork has no
outline path of its own, so without this the body reads as one flat blob. */
.bm-v path{stroke:var(--surface);stroke-width:2.5;stroke-linejoin:round}
@@ -930,6 +995,7 @@ h4.sec{
border-radius:var(--r-lg);padding:14px;
background:var(--surface);box-shadow:inset 0 0 0 1.5px var(--acc-line);
}
.workout-swipe-surface{touch-action:pan-y}
/* A superset nests a card inside the page's own gutter, so its inset is paid twice. On a
narrow phone that left the weight and reps steppers too tight to show a three-digit
number — reported as "the reps textbox becomes too small when superset on mobile". The
+5
View File
@@ -0,0 +1,5 @@
// Hungarian exercise instructions, translated from the upstream English dataset
// (github.com/hasaneyldrm/exercises-dataset). Not produced by scripts/build-instructions.mjs —
// that dataset has no hu field upstream yet, so this pack is maintained here until an hu
// contribution lands there. See docs/SELF_HOSTING.md or the project notes for details.
export default {"1000":["Állj úgy, hogy a lábaid csípőszélességben legyenek, és helyezd a gumiszalagot a lábfejed párnás része köré.","Kapaszkodj meg egy stabil tárgyban az egyensúly megtartásához.","Lassan emeld fel a sarkadat a talajról, a testsúlyodat a lábujjaid párnájára helyezve.","Tarts egy rövid szünetet a mozdulat tetején, majd lassan engedd vissza a sarkadat a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban, majd válts a másik lábra."],"1001":["Állj úgy, hogy a lábaid csípőszélességben legyenek, és helyezz egy ellenállószalagot a bokáid köré.","Tegyél egy nagy lépést előre a jobb lábaddal, és egy kisebb lépést hátra a bal lábaddal.","Hajlítsd be a térdeidet, és ereszkedj addig, amíg a jobb combod párhuzamos nem lesz a talajjal, közben tartsd a bal térdedet kicsivel a talaj fölött.","A jobb sarkadon átnyomva térj vissza a kiindulási helyzetbe.","Ismételd a másik oldalon."],"1002":["Feküdj a hátadra úgy, hogy a lábaid egyenesen legyenek, a lábfejeidet pedig tartsd össze.","Helyezd a gumiszalagot a lábfejed boltozata köré, és fogd meg a szalag végeit a kezeiddel.","A hasadat megfeszítve emeld fel mindkét lábadat a talajról, amíg merőlegesek nem lesznek rá.","Tarts egy rövid szünetet a mozdulat tetején, majd lassan engedd vissza a lábaidat a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban."],"1003":["Rögzítsd a gumiszalagot egy stabil ponthoz derékmagasságban.","Állj szemben a rögzítési ponttal, a lábaid vállszélességben legyenek.","Tartsd a gumiszalag fogantyúit úgy, hogy a tenyered egymással szemben nézzen, a karjaid pedig magad előtt nyújtva legyenek.","Hajlítsd be a térdeidet, és ereszkedj guggolásba, közben tartsd egyenesen a hátad és emelt helyzetben a mellkasodat.","A guggolásból húzd a gumiszalag fogantyúit magad felé, összezárva a lapockáidat.","Tarts egy rövid szünetet a mozdulat tetején, majd lassan engedd fel a feszülést, és térj vissza a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban."],"1004":["Állj úgy, hogy a lábaid vállszélességben legyenek, a gumiszalagot pedig helyezd közvetlenül a térded fölé.","Tartsd emelt helyzetben a mellkasodat és feszítsd meg a törzsedet, told hátra a csípődet, és hajlítsd be a térdeidet, hogy guggolásba ereszkedj.","Ügyelj arra, hogy a térdeid a lábujjaid vonalában maradjanak, és a súlyod a sarkadon legyen.","Tarts egy rövid szünetet lent, majd a sarkadon átnyomva térj vissza a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban."],"1005":["Rögzítsd a gumiszalagot egy stabil ponthoz derékmagasságban.","Állj háttal a rögzítési pontnak, a lábaid vállszélességben legyenek.","Fogd meg a gumiszalagot mindkét kezeddel, és húzd a mellkasodhoz, közben tartsd a könyöködet behajlítva és a törzsedhez közel.","Feszítsd meg a hasadat, és lassan hajolj előre, közelítve a mellkasodat a térdeidhez.","Tarts egy rövid szünetet a felhajlítás tetején, majd lassan térj vissza a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban."],"1007":["Állj úgy, hogy a lábaid vállszélességben legyenek, és helyezd a gumiszalagot a felső hátad köré, keresztezve a mellkasod előtt.","Fogd meg a gumiszalag végeit a kezeiddel, közben tartsd a könyöködet behajlítva és a törzsedhez közel.","Feszítsd meg a hasadat, és csavard a törzsedet az egyik oldalra, közben húzd a könyöködet az ellentétes térded felé.","Tarts egy rövid szünetet, majd térj vissza a kiindulási helyzetbe.","Ismételd a másik oldalon.","Folytasd az oldalak váltogatását a kívánt ismétlésszámban."],"1008":["Helyezz egy gumiszalagot a combjaid köré, közvetlenül a térded fölé.","Állj egy lépcsővel vagy platformmal szemben, a lábaid csípőszélességben legyenek.","Lépj fel a platformra a jobb lábaddal, a sarkadon átnyomva.","Nyújtsd hátra a bal lábadat, közben tartsd egyenesen.","Engedd vissza a bal lábadat a talajra.","Ismételd úgy, hogy a bal lábaddal lépsz fel a platformra.","Folytasd a lábak váltogatását a kívánt ismétlésszámban."],"1009":["Állj úgy, hogy a lábaid vállszélességben legyenek, és helyezd a gumiszalagot a bokáid köré.","Fogd meg a gumiszalagot mindkét kezeddel a combjaid előtt, a tenyered magad felé nézzen.","Tartsd egyenesen a hátad és feszítsd meg a törzsedet, miközben előredőlsz a csípődből, és lassan engeded a felsőtested a talaj felé.","Miközben ereszkedsz, told hátra a csípődet, és engedd, hogy a térdeid enyhén behajoljanak.","Engedd a gumiszalagot a talaj felé, közben érezd a nyújtást a combhajlítóidban.","Tarts egy rövid szünetet lent, majd feszítsd meg a farizmaidat és a combhajlítóidat, hogy visszaemeld a felsőtested a kiindulási helyzetbe.","Ismételd a kívánt ismétlésszámban."],"1010":["Állj úgy, hogy a lLine truncated
+44
View File
@@ -0,0 +1,44 @@
import { supersetUnits, unitOf } from './history.js'
function hasLoggedSet(entry) {
return Array.isArray(entry?.sets) && entry.sets.some(set => set?.done === true)
}
/**
* Swap one exact active-workout occurrence.
*
* Unlogged occurrences are replaced in place. Logged results are never relabelled: after explicit
* confirmation, the replacement is inserted beside the original. A logged group member also
* requires an explicit choice to keep the replacement in the group or detach it after the group.
*/
export function swapActiveExercise(active, index, replacement, {
loggedConfirmed = false,
groupDisposition
} = {}) {
if (!active || !Array.isArray(active.entries) || !replacement || index < 0 || index >= active.entries.length) return null
const current = active.entries[index]
if (!hasLoggedSet(current)) {
const metadata = Object.fromEntries(Object.entries(current).filter(([key]) => (
!['id', 'target', 'plan', 'sets', 'sg'].includes(key)
)))
active.entries[index] = { ...metadata, ...replacement, ...(current.sg ? { sg: current.sg } : {}) }
active.cur = index
return { inserted: false, index }
}
if (!loggedConfirmed) return { needsConfirmation: true, grouped: !!current.sg, index }
if (current.sg && !['keep', 'detach'].includes(groupDisposition)) {
return { needsConfirmation: true, grouped: true, index }
}
const unit = unitOf(supersetUnits(active.entries), index)
const keepGroup = current.sg && groupDisposition === 'keep'
const insertAt = keepGroup ? index + 1 : (unit.length > 1 ? unit.at(-1) + 1 : index + 1)
active.entries.splice(insertAt, 0, {
...replacement,
...(keepGroup ? { sg: current.sg } : {})
})
active.cur = insertAt
return { inserted: true, index: insertAt }
}
@@ -0,0 +1,88 @@
import { describe, expect, it } from 'vitest'
import { swapActiveExercise } from './active-exercise-swap.js'
const entry = (id, { sg, done = false, target, sets } = {}) => ({
id,
...(sg ? { sg } : {}),
target: target || { mode: 'reps', sets: 1, reps: 5, weight: 40 },
sets: sets || [{ w: 40, r: 5, done }]
})
const replacement = () => entry('incline', {
target: { mode: 'reps', sets: 2, reps: 8, weight: 32.5, note: 'Keep elbows tucked.', intensifier: { type: 'dropset', count: 1, pct: 20 } },
sets: [{ w: 32.5, r: 8, done: false }, { w: 32.5, r: 8, done: false }]
})
describe('safe active exercise swap', () => {
it('replaces only the selected duplicate occurrence and preserves its group and replacement metadata', () => {
const first = entry('bench', { sg: 'pair' })
const selected = entry('bench', { sg: 'pair' })
selected.occurrenceId = 'bench#2'
selected.provenance = { routineIndex: 4 }
const unrelated = entry('row')
const active = { cur: 1, entries: [first, selected, unrelated] }
const next = replacement()
expect(swapActiveExercise(active, 1, next)).toEqual({ inserted: false, index: 1 })
expect(active.entries.map(value => value.id)).toEqual(['bench', 'incline', 'row'])
expect(active.entries[0]).toBe(first)
expect(active.entries[2]).toBe(unrelated)
expect(active.entries[1]).toEqual({
...next,
occurrenceId: 'bench#2',
provenance: { routineIndex: 4 },
sg: 'pair'
})
expect(active.cur).toBe(1)
})
it('fails closed before a logged standalone occurrence is explicitly confirmed', () => {
const logged = entry('bench', { sets: [{ w: 42.5, r: 7, done: true, rir: 1 }] })
const active = { cur: 0, entries: [logged, entry('row')] }
expect(swapActiveExercise(active, 0, replacement())).toEqual({ needsConfirmation: true, grouped: false, index: 0 })
expect(active.entries).toEqual([logged, active.entries[1]])
expect(active.cur).toBe(0)
})
it('preserves a confirmed logged occurrence and inserts the replacement after it', () => {
const logged = entry('bench', { sets: [{ w: 42.5, r: 7, done: true, rir: 1 }] })
const unrelated = entry('row')
const active = { cur: 0, entries: [logged, unrelated] }
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true })).toEqual({ inserted: true, index: 1 })
expect(active.entries[0]).toBe(logged)
expect(active.entries[0].sets[0]).toEqual({ w: 42.5, r: 7, done: true, rir: 1 })
expect(active.entries[1].id).toBe('incline')
expect(active.entries[2]).toBe(unrelated)
expect(active.cur).toBe(1)
})
it('requires an explicit grouped disposition before changing a logged group member', () => {
const active = { cur: 0, entries: [entry('bench', { sg: 'pair', done: true }), entry('row', { sg: 'pair' }), entry('curl')] }
const before = [...active.entries]
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true }))
.toEqual({ needsConfirmation: true, grouped: true, index: 0 })
expect(active.entries).toEqual(before)
})
it.each([
['keep', ['bench', 'incline', 'row', 'curl'], ['pair', 'pair', 'pair', undefined], 1],
['detach', ['bench', 'row', 'incline', 'curl'], ['pair', 'pair', undefined, undefined], 2]
])('%s confirmation preserves logged group data and unrelated entries', (groupDisposition, ids, groups, cursor) => {
const logged = entry('bench', { sg: 'pair', sets: [{ w: 45, r: 6, done: true }] })
const partner = entry('row', { sg: 'pair' })
const unrelated = entry('curl')
const active = { cur: 0, entries: [logged, partner, unrelated] }
expect(swapActiveExercise(active, 0, replacement(), { loggedConfirmed: true, groupDisposition }))
.toEqual({ inserted: true, index: cursor })
expect(active.entries.map(value => value.id)).toEqual(ids)
expect(active.entries.map(value => value.sg)).toEqual(groups)
expect(active.entries[0]).toBe(logged)
expect(active.entries.includes(partner)).toBe(true)
expect(active.entries.at(-1)).toBe(unrelated)
expect(active.cur).toBe(cursor)
})
})
+31
View File
@@ -0,0 +1,31 @@
import { supersetUnits } from './history.js'
function moveTarget(active, index, direction) {
if (!active || !Array.isArray(active.entries) || (direction !== -1 && direction !== 1)) return null
const units = supersetUnits(active.entries)
const source = units.findIndex(unit => unit.includes(index))
const target = source + direction
if (source < 0 || target < 0 || target >= units.length) return null
return { units, source, target }
}
export function canMoveActiveWorkoutUnit(active, index, direction) {
return moveTarget(active, index, direction) !== null
}
export function moveActiveWorkoutUnit(active, index, direction) {
const move = moveTarget(active, index, direction)
if (!move) return null
const selected = active.entries[index]
const reorderedUnits = [...move.units]
const sourceUnit = reorderedUnits[move.source]
reorderedUnits[move.source] = reorderedUnits[move.target]
reorderedUnits[move.target] = sourceUnit
const indices = reorderedUnits.flat()
const reorderedEntries = indices.map(entryIndex => active.entries[entryIndex])
active.entries.splice(0, active.entries.length, ...reorderedEntries)
active.cur = active.entries.indexOf(selected)
return { indices }
}
@@ -0,0 +1,87 @@
import { describe, expect, it } from 'vitest'
import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from './active-workout-order.js'
import { LANGS } from './i18n-core.js'
import { PT_BR_OVERRIDES } from '../locales/pt-BR.js'
const entry = (id, extra = {}) => ({
id,
target: { sets: 1, reps: 5 },
sets: [{ w: 0, r: 5, done: false }],
...extra,
})
describe('active workout whole-unit order', () => {
it('moves one standalone occurrence without conflating duplicate exercise ids', () => {
const duplicateA = entry('duplicate', { occurrenceId: 'duplicate#1' })
const selected = entry('duplicate', {
occurrenceId: 'duplicate#2',
target: { sets: 2, reps: 7, weight: 82.5, notes: 'Keep this target' },
sets: [{ w: 77.5, r: 6, done: true, rir: 2 }],
})
const active = { cur: 2, entries: [duplicateA, entry('middle'), selected] }
expect(moveActiveWorkoutUnit(active, active.cur, -1)?.indices).toEqual([0, 2, 1])
expect(active.entries.map(item => item.occurrenceId || item.id)).toEqual(['duplicate#1', 'duplicate#2', 'middle'])
expect(active.entries[0]).toBe(duplicateA)
expect(active.entries[1]).toBe(selected)
expect(active.entries[1].target).toBe(selected.target)
expect(active.entries[1].sets).toBe(selected.sets)
expect(active.cur).toBe(1)
})
it('moves a complete contiguous group one unit and preserves the selected member identity', () => {
const first = entry('group-a', { sg: 'pair', occurrenceId: 'group-a#1' })
const selected = entry('group-b', { sg: 'pair', occurrenceId: 'group-b#1' })
const groupMeta = { pair: { kind: 'complex', label: 'Carry pair', cues: 'Stay braced.' } }
const active = { cur: 2, entries: [entry('before'), first, selected, entry('after')], groupMeta }
expect(moveActiveWorkoutUnit(active, active.cur, -1)?.indices).toEqual([1, 2, 0, 3])
expect(active.entries.map(item => item.id)).toEqual(['group-a', 'group-b', 'before', 'after'])
expect(active.entries.slice(0, 2)).toEqual([first, selected])
expect(active.entries.map(item => item.sg)).toEqual(['pair', 'pair', undefined, undefined])
expect(active.groupMeta).toBe(groupMeta)
expect(active.entries[active.cur]).toBe(selected)
})
it('moves a group down by exactly one neighbouring unit', () => {
const first = entry('group-a', { sg: 'pair' })
const selected = entry('group-b', { sg: 'pair' })
const active = { cur: 1, entries: [first, selected, entry('middle'), entry('last')] }
expect(moveActiveWorkoutUnit(active, active.cur, 1)?.indices).toEqual([2, 0, 1, 3])
expect(active.entries.map(item => item.id)).toEqual(['middle', 'group-a', 'group-b', 'last'])
expect(active.entries[active.cur]).toBe(selected)
})
it('rejects boundaries and invalid directions without mutating the active workout', () => {
const active = { cur: 0, entries: [entry('first'), entry('last')] }
const entries = [...active.entries]
expect(canMoveActiveWorkoutUnit(active, 0, -1)).toBe(false)
expect(canMoveActiveWorkoutUnit(active, 1, 1)).toBe(false)
expect(moveActiveWorkoutUnit(active, 0, 0)).toBeNull()
expect(moveActiveWorkoutUnit(active, 0, -1)).toBeNull()
expect(active.entries).toEqual(entries)
expect(active.cur).toBe(0)
})
})
describe('active workout move locale coverage', () => {
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
const localeCodes = Object.keys(LANGS).filter(code => code !== 'en')
it('defines both visible move labels in every current locale pack', () => {
expect(Object.keys(packs)).toHaveLength(localeCodes.length)
for (const code of localeCodes) {
const pack = packs[`../locales/${code}.js`]
expect(pack, `${code} locale pack is missing`).toBeTruthy()
for (const key of ['Move up', 'Move down']) {
expect(Object.hasOwn(pack, key), `${code} is missing ${key}`).toBe(true)
expect(pack[key], `${code} has a blank ${key}`).toEqual(expect.any(String))
expect(pack[key].trim(), `${code} has a blank ${key}`).not.toBe('')
}
}
expect(Object.hasOwn(PT_BR_OVERRIDES, 'Move up')).toBe(true)
expect(Object.hasOwn(PT_BR_OVERRIDES, 'Move down')).toBe(true)
})
})
+39
View File
@@ -0,0 +1,39 @@
// Logging a workout after the fact. The session itself is the ordinary active workout with a
// `backfill` field on it; these helpers are the parts that differ from a live session, kept
// pure so the date arithmetic and the history surgery can be tested without the UI.
export const workoutsOn = (S, iso) => (S.workouts || []).filter(w => w.d === iso)
// Epoch of `iso` at the given wall-clock time, in the browser's zone — the same zone
// todayISO() and isoOf() use, so `d` and `start` agree the way they do for a live session.
export const backfillStart = (iso, time = '18:00') => {
const [h, m] = String(time || '18:00').split(':').map(Number)
const d = new Date(iso + 'T12:00:00')
d.setHours(h || 0, m || 0, 0, 0)
return d.getTime()
}
// A live session ends when you tap finish; a logged one ends when you said it did.
export const backfillEnd = active => active.start + Math.max(1, active.backfill?.durationMin || 60) * 60000
// The workouts array is chronological (History reverses it), so a past workout cannot just be
// pushed — it goes where its date and start time put it, after anything from the same moment.
export function insertChronological(workouts, w) {
const key = x => [x.d || '', x.start || 0]
const [d, s] = key(w)
let i = workouts.length
while (i > 0) {
const [pd, ps] = key(workouts[i - 1])
if (pd < d || (pd === d && ps <= s)) break
i--
}
return [...workouts.slice(0, i), w, ...workouts.slice(i)]
}
// The history after a backfilled session is filed: the workout it replaces (if any) is gone
// and the new one sits in date order. Returns a new array; the caller stores it.
export function completeBackfill(workouts, active, w) {
const replaceId = active.backfill?.replaceId
const kept = replaceId ? workouts.filter(x => x.id !== replaceId) : workouts
return insertChronological(kept, w)
}
+59
View File
@@ -0,0 +1,59 @@
import { describe, expect, it } from 'vitest'
import { workoutsOn, backfillStart, backfillEnd, insertChronological, completeBackfill } from './backfill.js'
const w = (id, d, start = 0) => ({ id, d, start })
describe('workoutsOn', () => {
it('returns every workout of that day and nothing else', () => {
const S = { workouts: [w('a', '2026-01-01'), w('b', '2026-01-02'), w('c', '2026-01-02')] }
expect(workoutsOn(S, '2026-01-02').map(x => x.id)).toEqual(['b', 'c'])
expect(workoutsOn(S, '2026-01-03')).toEqual([])
expect(workoutsOn({}, '2026-01-03')).toEqual([])
})
})
describe('backfillStart / backfillEnd', () => {
it('lands on the chosen day at the chosen time in local zone', () => {
const t = new Date(backfillStart('2026-03-10', '07:45'))
expect([t.getFullYear(), t.getMonth() + 1, t.getDate(), t.getHours(), t.getMinutes()]).toEqual([2026, 3, 10, 7, 45])
})
it('defaults to 18:00 and ends after the given duration', () => {
const start = backfillStart('2026-03-10')
expect(new Date(start).getHours()).toBe(18)
expect(backfillEnd({ start, backfill: { durationMin: 45 } })).toBe(start + 45 * 60000)
expect(backfillEnd({ start, backfill: {} })).toBe(start + 60 * 60000)
expect(backfillEnd({ start, backfill: { durationMin: 0 } })).toBe(start + 60 * 60000)
})
})
describe('insertChronological', () => {
const list = [w('a', '2026-01-01', 10), w('b', '2026-01-05', 10), w('c', '2026-01-05', 20), w('d', '2026-01-09', 10)]
it('places by date, then by start time, after equal keys', () => {
expect(insertChronological(list, w('x', '2026-01-03')).map(x => x.id)).toEqual(['a', 'x', 'b', 'c', 'd'])
expect(insertChronological(list, w('x', '2026-01-05', 15)).map(x => x.id)).toEqual(['a', 'b', 'x', 'c', 'd'])
expect(insertChronological(list, w('x', '2026-01-05', 20)).map(x => x.id)).toEqual(['a', 'b', 'c', 'x', 'd'])
})
it('appends at the end and inserts at the front', () => {
expect(insertChronological(list, w('x', '2026-02-01')).at(-1).id).toBe('x')
expect(insertChronological(list, w('x', '2025-12-31'))[0].id).toBe('x')
expect(insertChronological([], w('x', '2026-01-01')).map(x => x.id)).toEqual(['x'])
})
it('does not mutate the input', () => {
const copy = [...list]
insertChronological(list, w('x', '2026-01-03'))
expect(list).toEqual(copy)
})
})
describe('completeBackfill', () => {
const list = [w('a', '2026-01-01', 10), w('b', '2026-01-05', 10), w('d', '2026-01-09', 10)]
it('adds a second workout on a day in order', () => {
const out = completeBackfill(list, { backfill: { durationMin: 60, replaceId: null } }, w('x', '2026-01-05', 5))
expect(out.map(x => x.id)).toEqual(['a', 'x', 'b', 'd'])
})
it('replaces the chosen workout', () => {
const out = completeBackfill(list, { backfill: { durationMin: 60, replaceId: 'b' } }, w('x', '2026-01-05', 30))
expect(out.map(x => x.id)).toEqual(['a', 'x', 'd'])
expect(list).toHaveLength(3)
})
})
+4 -10
View File
@@ -7,7 +7,7 @@
// RIR is the internal unit because it has a real zero — a set taken to failure — where RPE's
// floor of 6 is only a convention about which sets are worth rating. RPE 8 == RIR 2.
import { EFFORT, effortOf } from './history.js'
import { weekKey } from './format.js'
import { weekKey, weekStartOf, startOfWeek } from './format.js'
import { isWarmupRow } from './workout-model.js'
// At or below this a set is close enough to failure to be the kind that drives adaptation.
@@ -95,12 +95,13 @@ export function hasEffort(S) {
* drawn — one tap should not become a peak in the curve.
*/
export function effortWeeks(S, days) {
const ws = weekStartOf(S)
const wk = new Map()
eachDoneSet(S, (s, w) => {
if (!inWindow(w, days)) return
const k = weekKey(w.d)
const k = weekKey(w.d, ws)
let e = wk.get(k)
if (!e) wk.set(k, e = { k, t: mondayOf(w.d), sum: 0, n: 0, sets: 0 })
if (!e) wk.set(k, e = { k, t: startOfWeek(w.d, ws).getTime(), sum: 0, n: 0, sets: 0 })
e.sets++
const r = rirOf(s)
if (r != null) { e.sum += r; e.n++ }
@@ -108,13 +109,6 @@ export function effortWeeks(S, days) {
return [...wk.values()].filter(e => e.n >= 2).sort((a, b) => a.t - b.t)
.map(e => ({ t: e.t, rir: e.sum / e.n, n: e.n, sets: e.sets }))
}
// The Monday of an ISO date, as ms — the x position a week's point sits at.
function mondayOf(iso) {
const d = new Date(iso + 'T12:00:00')
d.setDate(d.getDate() - ((d.getDay() + 6) % 7))
d.setHours(12, 0, 0, 0)
return +d
}
/**
* How the rated sets spread across the scale, in whole steps with everything past the top
+1
View File
@@ -35,6 +35,7 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap
bw: active.bw,
entries,
prs,
...(active.excludeFromProgression === true ? { excludeFromProgression: true } : {}),
...(sessionNote ? { note: sessionNote } : {}),
}
}
+12
View File
@@ -15,6 +15,18 @@ describe('completed workout boundary', () => {
})
})
it('persists progression exclusion only for a marked session', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000, routineId: 'routine-1', name: 'Deload', bw: 80,
excludeFromProgression: true,
entries: [{ id: '0025', sets: [{ done: true, w: 30, r: 8 }], target: { sets: 1, reps: 8 } }],
}
expect(buildCompletedWorkout(active, { end: 2000 }).excludeFromProgression).toBe(true)
const { excludeFromProgression, ...regular } = active
expect(buildCompletedWorkout(regular, { end: 2000 })).not.toHaveProperty('excludeFromProgression')
})
it('persists a muscle snapshot only when the caller supplies one', () => {
const active = {
id: 'active-1', d: '2026-08-08', start: 1000,
+33 -7
View File
@@ -34,15 +34,41 @@ export const fmtVol = (v, unit) => fmtNum(v) + ' ' + unit
// Plural forms are not automatic when the English string is the key.
export const exCount = n => t(n === 1 ? '{0} exercise' : '{0} exercises', n)
export function weekKey(d) {
const dt = new Date(d + 'T12:00:00')
const day = (dt.getDay() + 6) % 7
dt.setDate(dt.getDate() - day + 3)
const jan4 = new Date(dt.getFullYear(), 0, 4)
const week = 1 + Math.round(((dt - jan4) / 86400000 - 3 + ((jan4.getDay() + 6) % 7)) / 7)
return dt.getFullYear() + '-' + week
/* ---------------------------------------------------------------- week start --
Where a week begins is a local convention, not a fact: most of Europe starts on
Monday, most of the Americas and much of Asia on Sunday. The app used to assume
Monday everywhere — the Plan list, the Home strip, the calendar grid and every
"this week" total. It is now S.weekStart, a getDay() index, and every one of those
places asks these helpers instead of writing the assumption down again.
Only 1 and 0 are offered in the UI, but the helpers work for any weekday, so a
Saturday start (parts of the Middle East) would need a locale string and nothing
else. */
export const MONDAY = 1
export const SUNDAY = 0
/** The profile's first weekday, defaulting to Monday for every state written before this. */
export const weekStartOf = S => (S?.weekStart === SUNDAY ? SUNDAY : MONDAY)
/** getDay() indices in display order — [1..6,0] for a Monday start, [0..6] for a Sunday one. */
export const weekOrder = (ws = MONDAY) => Array.from({ length: 7 }, (_, i) => (ws + i) % 7)
/** How many days a weekday sits past the start of its week. 0..6, so it doubles as a column. */
export const weekDayOffset = (day, ws = MONDAY) => (day - ws + 7) % 7
/** The Date (noon local, so DST cannot shift the day) that starts the week `iso` falls in. */
export function startOfWeek(iso, ws = MONDAY) {
const d = new Date(iso + 'T12:00:00')
d.setDate(d.getDate() - weekDayOffset(d.getDay(), ws))
return d
}
/**
* A key that is equal for two dates in the same week: the ISO date of the week's first day.
*
* Only ever compared or used as a map key — never shown, never stored — so it does not need
* to be an ISO week number, and being one would be a liability here: "2026-35" is defined
* Monday-first, and there is no Sunday-first equivalent to fall back to.
*/
export const weekKey = (iso, ws = MONDAY) => isoOf(startOfWeek(iso, ws))
export const localTZ = () => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC' } catch { return 'UTC' } }
export const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7)
+576
View File
@@ -0,0 +1,576 @@
// AUTO-GENERATED by scripts/build-hevy-id-map.mjs — do not edit by hand.
// Hevy exercise_template id → openGym catalogue id, plus English title → id for CSV exports
// (Hevy CSV has titles, not template ids). Regenerated from the Hevy templates API +
// verified title aliases. Five title aliases whose catalogue match was wrong (crunch → weighted
// crunch, side plank → hip adduction, machine squat → barbell squat, cable triceps extension and
// cable reverse fly → lever machines) are left out; those titles import as custom exercises.
// 283 mapped · 168 left unmatched (import as custom).
// Source templates: 451 (built-in only).
export const HEVY_ID_MAP = {
"018ADC12": "3017",
"01A35BF9": "2404",
"023943F1": "0572",
"026FD047": "0407",
"0393F233": "0218",
"040BA2E3": "2612",
"046E25A2": "0673",
"0482DA98": "0826",
"05293BCA": "3142",
"059E835D": "0603",
"062AB91A": "0594",
"06745E58": "1372",
"073032BB": "1457",
"07B38369": "0314",
"084A67CA": "0128",
"08590920": "0472",
"08A2974E": "0606",
"091737FA": "0573",
"09C9F635": "0865",
"0B4C1902": "0294",
"0B841777": "0095",
"0B9B92BA": "0085",
"0EB695C9": "2611",
"0F24286A": "0099",
"0FBF7195": "0748",
"1006DF48": "0401",
"10313AFD": "0550",
"10347BAC": "0591",
"10D76E8F": "1273",
"112FC6B7": "0080",
"11A123F3": "0586",
"12017185": "0308",
"123EE239": "0439",
"1283BBA6": "0043",
"150E076B": "3655",
"18487FA7": "0301",
"19372ABC": "0662",
"19A38071": "0604",
"1B2B1E7C": "0652",
"1B89CA1B": "0521",
"1D4B3D6B": "0313",
"1DF4A847": "1350",
"1E42FD5F": "0743",
"1E9A6B8E": "0592",
"20870ED5": "0752",
"20C1A3CB": "0809",
"21310F5F": "0607",
"218DA87C": "0803",
"22578A94": "0168",
"234897AB": "0165",
"23A48484": "0175",
"23E92538": "0292",
"243710DE": "3666",
"286C1D0B": "0246",
"28BB4A95": "0591",
"29083183": "1326",
"29472BE1": "0251",
"2982AA23": "0687",
"2A48E443": "0116",
"2B4B7310": "0085",
"2C37EC5E": "0017",
"2CFED196": "0069",
"2F8D3067": "0607",
"2FA77B28": "0459",
"3092FADD": "0607",
"32B0B590": "0507",
"32C4D4A2": "0298",
"32HKJ34K": "1460",
"3303376C": "2141",
"33EDD7DB": "1460",
"35B51B87": "0030",
"3601968B": "0289",
"36E8F14E": "0165",
"3765684D": "0607",
"37FCC2BB": "0294",
"392887AA": "0662",
"39C99849": "0493",
"3A6FA3D1": "0757",
"3D0C7C75": "1760",
"3F5F8D40": "3142",
"3FF6A22E": "0544",
"40C6A9FC": "0127",
"4180C405": "0044",
"422B08F1": "0334",
"425805F4": "0499",
"43573BB8": "0003",
"4377A52B": "2311",
"4377A52C": "2311",
"473CF5B8": "0673",
"47B036EF": "0978",
"49C922A1": "1409",
"4B4BF8C2": "0019",
"4E5257DE": "2616",
"4F5866F8": "0573",
"4F942934": "0070",
"5046D0A9": "0042",
"50C613D0": "2133",
"50DFDFAB": "0047",
"5122E7D9": "1451",
"51A0EDAA": "0677",
"542F3CD5": "1700",
"55E6546F": "0027",
"56808FD2": "0970",
"582ADA23": "1636",
"5E10D0E6": "3142",
"5E1A7777": "0054",
"5F4E6DD3": "0300",
"5F8903BF": "0551",
"6120CAAB": "0795",
"6182EE83": "0607",
"651F844C": "1269",
"6575F52D": "0283",
"6622E5A0": "3142",
"67280085": "0375",
"68B83EE0": "3193",
"68F8A292": "0060",
"6A6C31A5": "2330",
"6AC96645": "0405",
"6DA40660": "0417",
"6E6EE645": "0054",
"6FCD7755": "0251",
"70D4EBBF": "0514",
"72297E8C": "5201",
"724CDE60": "0297",
"729237D1": "0652",
"72CFFAD5": "1459",
"74103F24": "0052",
"742E5BD5": "0767",
"75A4F6C4": "0585",
"78683336": "0596",
"7952B5CD": "0872",
"796E8E2C": "0834",
"797F0782": "0437",
"79D0BB3A": "0025",
"7AB9A362": "0120",
"7B8D84E8": "0091",
"7C0028C3": "0593",
"7C50F118": "1429",
"7E3BC8B6": "0312",
"7EB3F7C3": "0577",
"818BA121": "0078",
"8293E554": "0310",
"875F585F": "0060",
"878CD1D0": "0405",
"89304423": "0529",
"8A2E6481": "0180",
"8BAB2735": "0318",
"8BEBFED6": "0598",
"8C331CD8": "0196",
"8C9D2928": "1494",
"90427D4A": "1675",
"90B04F96": "0471",
"90E506D5": "3305",
"91237BDD": "2289",
"914F3A96": "0327",
"91AF29E0": "0091",
"9237BAD1": "0603",
"923874CA": "0562",
"9273BA17": "0237",
"9283BABA": "0858",
"92D858EA": "0243",
"9372FFAA": "0396",
"93A552C6": "0241",
"947DAC23": "0259",
"95F2E076": "1426",
"9694DA61": "3543",
"98237BA2": "0826",
"991833C2": "3220",
"9930DF71": "0091",
"99507114": "0032",
"99B49684": "3663",
"99C1F2AD": "0151",
"99D5F10E": "0857",
"9B13BA4B": "0548",
"9DCE2D64": "0596",
"9F48F858": "0206",
"9F9C164B": "0631",
"A01BE509": "0443",
"A05C064D": "0573",
"A0D8FA1B": "2271",
"A127DA73": "0534",
"A2D838BD": "0243",
"A41C7261": "0972",
"A57D38D5": "0815",
"A5AC6449": "0031",
"A69FF221": "2137",
"A733CC5B": "1460",
"A8814C06": "1003",
"AA1EB7D8": "0571",
"AA52E8D2": "0773",
"ABB00838": "0028",
"ABEC557F": "0406",
"AC5A4C58": "0046",
"ADA8623C": "0868",
"AF328E3D": "0575",
"B05C2C29": "0605",
"B09A1304": "0766",
"B123DD01": "2285",
"B2398CD1": "0277",
"B3B1D947": "3360",
"B537D09F": "0336",
"B582299E": "0383",
"B5D3A742": "0410",
"B5EFBF9C": "0194",
"B74A95BB": "3211",
"B8127AD1": "0586",
"B82D6418": "0043",
"B923B230": "0811",
"BB792A36": "1160",
"BB83BDDE": "0687",
"BC10A922": "0277",
"BD4E7E53": "0535",
"BD86EFD5": "0041",
"BE289E45": "0178",
"BE640BA0": "0203",
"BF6ECE89": "0431",
"C315DC2A": "0602",
"C43825EA": "0279",
"C469EA70": "0597",
"C6272009": "0032",
"C628D768": "0648",
"C6C9B8A0": "2135",
"C7973E0E": "0739",
"C7AE420A": "0688",
"C8706C80": "0624",
"CC35A01F": "0043",
"CC55119B": "0979",
"CD6DC8E5": "0830",
"D04AC939": "0043",
"D20D7BBE": "0117",
"D23C609B": "0572",
"D2FE7B2E": "2330",
"D3095577": "0028",
"D3E2AB55": "0319",
"D4A2FE7E": "2143",
"D53F2886": "0065",
"D5D0354D": "0584",
"D8281C62": "0602",
"D82EA543": "0983",
"D8460FA6": "0385",
"D8911FC4": "0276",
"D8F7F851": "2331",
"D928C232": "0832",
"D950429E": "0038",
"DA0F0470": "0033",
"DBB91A3C": "0162",
"DBE341AA": "1495",
"DBF9273A": "0310",
"DCF3B31B": "0832",
"DCFF3E9F": "0413",
"DDCC3821": "0770",
"DE68C825": "0192",
"DF200976": "0977",
"E05C2C38": "0605",
"E3EDA509": "1775",
"E53CCBE5": "1372",
"E5988A0A": "0383",
"E644F828": "1258",
"E9E4089F": "0009",
"EA820646": "0027",
"EAC7D9C5": "3124",
"EB43ADD4": "1452",
"EB813C91": "1359",
"F1258206": "1004",
"F1D60854": "0218",
"F1E57334": "0292",
"F2A37357": "1410",
"F30A4F01": "1460",
"F3717B0E": "3888",
"F49E31D6": "0630",
"F4B4C6EE": "0597",
"F5DEF1EB": "1489",
"F8356514": "0472",
"F8A0FCCA": "0549",
"F99C211D": "0535",
"FAB6EB2F": "0372",
"FAF31231": "0033",
"FB09C938": "0067",
"FBF92739": "1299",
"FE389074": "0074",
"FFABC123": "0220",
"FFC106CB": "0753",
"FFDA283B": "0381",
}
/** Lowercased Hevy English title → catalogue id (CSV / name path). */
export const HEVY_TITLE_MAP = {
"ab wheel": "0857",
"air bike": "0003",
"arnold press (dumbbell)": "2137",
"around the world": "2143",
"back extension (hyperextension)": "0573",
"back extension (machine)": "0573",
"back extension (weighted hyperextension)": "0573",
"battle ropes": "0128",
"bear crawl": "3360",
"bench dip": "0830",
"bench press (barbell)": "0025",
"bench press (cable)": "0151",
"bench press (dumbbell)": "0289",
"bench press (smith machine)": "0748",
"bench press - close grip (barbell)": "0030",
"bench press - wide grip (barbell)": "1258",
"bent over row (band)": "0027",
"bent over row (barbell)": "0027",
"bent over row (dumbbell)": "0292",
"bent over row (smith machine)": "1359",
"bicep curl (barbell)": "0031",
"bicep curl (cable)": "0868",
"bicep curl (dumbbell)": "0294",
"bicep curl (machine)": "0575",
"bicep curl (suspension)": "0294",
"bicycle crunch": "0972",
"boxing": "2271",
"bulgarian split squat (barbell)": "0099",
"bulgarian split squat (dumbbell)": "0410",
"burpee": "1160",
"butterfly (pec deck)": "0596",
"cable core pallof press": "0979",
"cable crunch": "0175",
"cable fly crossovers": "1269",
"cable pull through": "0196",
"cable twist (down to up)": "0243",
"cable twist (up to down)": "0243",
"calf press (machine)": "2289",
"chest dip": "0251",
"chest dip (assisted)": "0009",
"chest dip (weighted)": "0251",
"chest fly (dumbbell)": "0308",
"chest fly (machine)": "0596",
"chest press (band)": "3124",
"chest press (machine)": "0577",
"chest supported incline row (dumbbell)": "0327",
"chest supported reverse fly (dumbbell)": "0383",
"chin up": "1326",
"chin up (assisted)": "0572",
"chin up (weighted)": "0572",
"clap push ups": "1273",
"clean": "0028",
"clean and press": "0028",
"concentration curl": "0297",
"cross body hammer curl": "0298",
"crunch (machine)": "1452",
"crunch (weighted)": "0832",
"cycling": "2331",
"dead bug": "0276",
"deadlift (band)": "0032",
"deadlift (barbell)": "0032",
"deadlift (dumbbell)": "0300",
"deadlift (smith machine)": "0752",
"deadlift (trap bar)": "0811",
"decline bench press (barbell)": "0033",
"decline bench press (dumbbell)": "0301",
"decline bench press (machine)": "0033",
"decline bench press (smith machine)": "0753",
"decline crunch": "0277",
"decline crunch (weighted)": "0277",
"decline push up": "0279",
"diamond push up": "0283",
"drag curl": "0038",
"dumbbell row": "0292",
"dumbbell snatch": "3888",
"dumbbell step up": "0431",
"elbow to knee": "0443",
"elliptical trainer": "2141",
"ez bar biceps curl": "2404",
"face pull": "0203",
"farmers walk": "2133",
"floor press (barbell)": "0065",
"floor triceps dip": "0815",
"flutter kicks": "0459",
"front raise (band)": "0978",
"front raise (barbell)": "0041",
"front raise (cable)": "0162",
"front raise (dumbbell)": "0310",
"front raise (suspension)": "0834",
"front squat": "0042",
"full squat": "0043",
"glute bridge (barbell)": "1409",
"glute ham raise": "3193",
"goblet squat": "1760",
"good morning (barbell)": "0044",
"hack squat": "0046",
"hack squat (machine)": "0743",
"hammer curl (band)": "0313",
"hammer curl (cable)": "0165",
"hammer curl (dumbbell)": "0312",
"handstand push up": "0471",
"hang clean": "0535",
"hanging knee raise": "0472",
"hanging leg raise": "0472",
"high knees": "3655",
"hip abduction (cable)": "0597",
"hip abduction (machine)": "0597",
"hip adduction (cable)": "0168",
"hip adduction (machine)": "0598",
"incline bench press (barbell)": "0047",
"incline bench press (dumbbell)": "0314",
"incline bench press (smith machine)": "0757",
"incline chest fly (dumbbell)": "0319",
"incline chest press (machine)": "1299",
"incline push ups": "0493",
"inverted row": "0499",
"iso-lateral row (machine)": "0571",
"jackknife sit up": "0507",
"jm press (barbell)": "0052",
"jump rope": "2612",
"jump squat": "0514",
"jumping jack": "3220",
"kettlebell clean": "0535",
"kettlebell goblet squat": "0534",
"kettlebell high pull": "0548",
"kettlebell snatch": "0529",
"kettlebell swing": "0549",
"kettlebell turkish get up": "0551",
"knee raise parallel bars": "0826",
"kneeling pulldown (band)": "0983",
"kneeling push up": "3211",
"landmine 180": "0562",
"lat pulldown (band)": "2330",
"lat pulldown (cable)": "2330",
"lat pulldown (machine)": "0673",
"lat pulldown - close grip (cable)": "2616",
"lateral lunge": "1410",
"lateral raise (band)": "0977",
"lateral raise (cable)": "0178",
"lateral raise (dumbbell)": "0334",
"lateral raise (machine)": "0584",
"leg extension (machine)": "0585",
"leg press (machine)": "0739",
"leg press horizontal (machine)": "2611",
"leg raise parallel bars": "0826",
"low row (suspension)": "0180",
"lunge": "0054",
"lunge (barbell)": "0054",
"lunge (dumbbell)": "0336",
"lying leg curl (machine)": "0586",
"lying leg raise": "0865",
"mountain climber": "0630",
"muscle up": "0631",
"oblique crunch": "1495",
"overhead curl (cable)": "1636",
"overhead press (barbell)": "0091",
"overhead press (dumbbell)": "0405",
"overhead press (smith machine)": "0766",
"overhead squat": "0069",
"overhead triceps extension (cable)": "0194",
"pendlay row (barbell)": "3017",
"pistol squat": "0544",
"plank": "2135",
"plate front raise": "0310",
"power clean": "0648",
"preacher curl (barbell)": "0070",
"preacher curl (dumbbell)": "0372",
"preacher curl (machine)": "0592",
"pull up": "0652",
"pull up (assisted)": "0017",
"pull up (band)": "0970",
"pull up (weighted)": "0652",
"pullover (dumbbell)": "0375",
"pullover (machine)": "2285",
"push press": "1700",
"push up": "0662",
"push up (weighted)": "0662",
"push up - close grip": "0259",
"rack pull": "0074",
"rear delt reverse fly (dumbbell)": "0383",
"rear delt reverse fly (machine)": "0602",
"renegade row (dumbbell)": "0521",
"reverse crunch": "0872",
"reverse curl (barbell)": "0080",
"reverse curl (cable)": "0206",
"reverse grip lat pulldown (cable)": "0673",
"reverse hyperextension": "0593",
"reverse lunge (barbell)": "0078",
"reverse lunge (dumbbell)": "0381",
"reverse plank": "3663",
"reverse wrist curl (dumbbell)": "0385",
"ring dips": "0677",
"romanian deadlift (barbell)": "0085",
"romanian deadlift (dumbbell)": "1459",
"romanian deadlift (smith machine)": "0085",
"rope cable curl": "0165",
"rope straight arm pulldown": "0237",
"russian twist (bodyweight)": "0687",
"russian twist (weighted)": "0687",
"scapular pull ups": "0688",
"seated cable row - bar grip": "0218",
"seated cable row - v grip (cable)": "0218",
"seated calf raise": "0594",
"seated dip machine": "1451",
"seated incline curl (dumbbell)": "0318",
"seated lateral raise (dumbbell)": "0396",
"seated leg curl (machine)": "0586",
"seated overhead press (barbell)": "0091",
"seated overhead press (dumbbell)": "0091",
"seated palms up wrist curl": "0401",
"seated row (machine)": "1350",
"seated shoulder press (machine)": "0603",
"seated wrist curl (barbell)": "1426",
"shoulder press (dumbbell)": "0405",
"shoulder press (machine plates)": "0603",
"shrug (barbell)": "0095",
"shrug (cable)": "0220",
"shrug (dumbbell)": "0406",
"shrug (machine)": "0604",
"shrug (smith machine)": "0767",
"side bend (dumbbell)": "0407",
"single arm lateral raise (cable)": "0192",
"single leg standing calf raise (machine)": "0605",
"sissy squat (weighted)": "1489",
"skullcrusher (barbell)": "0060",
"skullcrusher (dumbbell)": "0060",
"snatch": "0067",
"spider curl (dumbbell)": "1675",
"split squat (dumbbell)": "0809",
"sprints": "0858",
"squat (band)": "1004",
"squat (barbell)": "0043",
"squat (bodyweight)": "3543",
"squat (dumbbell)": "0413",
"squat (smith machine)": "0770",
"squat (suspension)": "0043",
"squat row": "1003",
"stair machine (floors)": "2311",
"stair machine (steps)": "2311",
"standing calf raise": "1372",
"standing calf raise (barbell)": "1372",
"standing calf raise (dumbbell)": "0417",
"standing calf raise (machine)": "0605",
"standing calf raise (smith)": "0773",
"standing leg curls": "0795",
"standing military press (barbell)": "1457",
"straight leg deadlift": "0116",
"sumo deadlift": "0117",
"sumo squat": "3142",
"sumo squat (barbell)": "3142",
"sumo squat (dumbbell)": "3142",
"sumo squat (kettlebell)": "3142",
"superman": "0803",
"t bar row": "0606",
"thruster (barbell)": "3305",
"thruster (kettlebell)": "0550",
"treadmill": "3666",
"triceps dip": "0591",
"triceps dip (assisted)": "0019",
"triceps dip (weighted)": "0591",
"triceps extension (barbell)": "0607",
"triceps extension (dumbbell)": "0607",
"triceps extension (machine)": "0607",
"triceps extension (suspension)": "0607",
"triceps pushdown": "0241",
"upright row (barbell)": "0120",
"upright row (cable)": "0246",
"upright row (dumbbell)": "0437",
"waiter curl (dumbbell)": "5201",
"walking": "1460",
"walking lunge": "1460",
"walking lunge (dumbbell)": "1460",
"walking lunge (sandbag)": "1460",
"wall sit": "0624",
"wide pull up": "1429",
"yoga": "1494",
"zercher squat": "0127",
"zottman curl (dumbbell)": "0439",
}
+38 -8
View File
@@ -1,5 +1,5 @@
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
import { todayISO, isoOf, weekKey, weekStartOf, fmtNum } from './format.js'
import { isCardio, isBodyweightEq } from './exercises.js'
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, extraVolumeOf, nextDropWeight, splitBurstReps } from './workout-model.js'
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
@@ -327,13 +327,21 @@ export function buildSets(S, cfg, options = {}) {
export const MAX_PLANNED_WARMUPS = 5
function buildWorkSets(S, cfg, options = {}) {
const last = lastEntryFor(S, cfg.id)
const preferLast = !!options.preferLast
const useTarget = !!options.useTarget
// A workout flagged excludeFromProgression (a planned deload) is not "last time" for the
// next regular session either: its reps and durations must not seed the rows any more than
// its weight seeds the prescription. The deload session itself reads the routine's own target.
const regular = (S.workouts || []).some(w => w.excludeFromProgression === true)
? { ...S, workouts: S.workouts.filter(w => w.excludeFromProgression !== true) }
: S
const last = lastEntryFor(regular, cfg.id)
const n = Math.max(1, cfg.sets || 1)
const mode = modeOf(cfg)
const preferLast = !!options.preferLast
const sets = []
// Last time's set at the same position, falling back to its final set when the plan grew.
const prevAt = i => (last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null)
// A deload routine must use its own prescription instead of carrying regular-session values
// into the workout. Other planned sessions keep the existing history-first behaviour.
const prevAt = i => (!useTarget && last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null)
if (mode === 'cardio') {
for (let i = 0; i < n; i++) {
@@ -358,7 +366,12 @@ function buildWorkSets(S, cfg, options = {}) {
const usable = prev && prev.r > 0 ? prev : null
// Planned sessions may use the confirmed working weight, while freestyle should reproduce
// the load of each matching set when that option is requested.
const w = preferLast && usable ? usable.w : (conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight))
// A deload uses the routine's target weight; a routine that never set one (weight 0) falls
// back to the last regular load rather than prescribing an empty bar.
const lastRegular = last ? (last.sets[i] || last.sets[last.sets.length - 1]) : null
const w = useTarget
? (cfg.weight > 0 ? cfg.weight : (lastRegular && lastRegular.r > 0 ? lastRegular.w : cfg.weight))
: preferLast && usable ? usable.w : (conf && conf.w > 0 ? conf.w : (usable ? usable.w : cfg.weight))
sets.push({ w, r: usable ? usable.r : cfg.reps, done: false })
}
return sets
@@ -440,15 +453,32 @@ export function supersetUnits(items) {
})
return units
}
// Move the selected occurrence's complete display unit by one neighbouring unit. Returning a
// new array keeps this helper pure; the caller decides how to persist it. Index identity matters
// here because the same exercise id may appear more than once with different setup.
export function moveSupersetUnit(items, index, direction) {
if (!Array.isArray(items) || (direction !== -1 && direction !== 1)) return null
const units = supersetUnits(items)
const source = units.findIndex(unit => unit.includes(index))
const target = source + direction
if (source < 0 || target < 0 || target >= units.length) return null
const reordered = [...units]
const selected = reordered[source]
reordered[source] = reordered[target]
reordered[target] = selected
return reordered.flat().map(i => items[i])
}
export function unitOf(units, idx) { return units.find(u => u.includes(idx)) || [idx] }
export function streakWeeks(S) {
if (!S.workouts.length) return 0
const weeks = new Set(S.workouts.map(w => weekKey(w.d)))
const ws = weekStartOf(S)
const weeks = new Set(S.workouts.map(w => weekKey(w.d, ws)))
let streak = 0
const cur = new Date()
for (let i = 0; i < 520; i++) {
const wk = weekKey(isoOf(cur))
const wk = weekKey(isoOf(cur), ws)
if (weeks.has(wk)) streak++
else if (i > 0) break
cur.setDate(cur.getDate() - 7)
+58
View File
@@ -493,6 +493,14 @@ describe('buildSets', () => {
.toEqual([{ w: 60, r: 10, done: false }, { w: 62.5, r: 8, done: false }])
})
it('can use a deload target without carrying regular-session values into it', () => {
const S = { exWeights: { [LIFT]: { w: 75 } }, workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [
{ w: 75, r: 10, done: true }, { w: 75, r: 9, done: true }
] }] }] }
expect(buildSets(S, { id: LIFT, sets: 2, reps: 12, weight: 40 }, { useTarget: true }))
.toEqual([{ w: 40, r: 12, done: false }, { w: 40, r: 12, done: false }])
})
})
describe('applyIntensifierPlan', () => {
@@ -895,3 +903,53 @@ describe('exNoteFor', () => {
expect(exNoteFor({}, '0025')).toBeNull()
})
})
describe('nextTrainingDay', () => {
// 2026-08-18 is a Tuesday; the week map is keyed by getDay(), so 0 is Sunday.
const TUE = '2026-08-18'
const base = (over = {}) => ({
dayPlan: {},
routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001' }] }, { id: 'r2', name: 'B', ex: [{ id: '0002' }] }],
week: {},
...over
})
it('finds the next scheduled day and names its routine', () => {
const S = base({ week: { 4: 'r2' } }) // Thursday
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-20', weekday: 4 })
expect(nextTrainingDay(S, TUE).routine.name).toBe('B')
})
it('looks forward only — today itself is never the answer', () => {
// Only Tuesday is scheduled and today is Tuesday, so the next one is a week out. (The UI
// cannot reach this: a day with a session takes the other branch and never asks.)
const S = base({ week: { 2: 'r1' } })
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-25', weekday: 2 })
})
it('wraps around the end of the week', () => {
const S = base({ week: { 1: 'r1' } }) // Monday, six days on
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-24', weekday: 1 })
})
it('is null when every day is rest', () => {
expect(nextTrainingDay(base(), TUE)).toBeNull()
})
it('skips a day whose routine no longer exists', () => {
const S = base({ week: { 3: 'gone', 5: 'r1' } })
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-21', weekday: 5 })
})
it('skips a routine with no exercises — starting it would open an empty session', () => {
const S = base({ routines: [{ id: 'r1', name: 'A', ex: [] }, { id: 'r2', name: 'B', ex: [{ id: '1' }] }], week: { 3: 'r1', 5: 'r2' } })
expect(nextTrainingDay(S, TUE)).toMatchObject({ weekday: 5 })
})
it('respects a per-date override in both directions', () => {
const moved = base({ week: {}, dayPlan: { '2026-08-19': 'r1' } })
expect(nextTrainingDay(moved, TUE)).toMatchObject({ iso: '2026-08-19' })
const off = base({ week: { 3: 'r1', 5: 'r2' }, dayPlan: { '2026-08-19': 'rest' } })
expect(nextTrainingDay(off, TUE)).toMatchObject({ weekday: 5 })
})
})
+10 -7
View File
@@ -7,13 +7,13 @@ export const LANGS = {
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
pt: 'Português (Portugal)', 'pt-BR': 'Português (Brasil)', pl: 'Polski',
tr: 'Türkçe', ru: 'Русский', zh: '中文',
ko: '한국어', hi: 'हिन्दी'
ko: '한국어', hi: 'हिन्दी', th: 'ไทย', hu: 'Magyar'
}
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko', 'pt-BR']
export const EXERCISE_NAME_LANGS = ['pt-BR']
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko', 'pt-BR', 'hu']
export const EXERCISE_NAME_LANGS = ['pt-BR', 'hu']
export const DATE_LOCALES = {
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT', 'pt-BR': 'pt-BR',
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN'
pl: 'pl-PL', tr: 'tr-TR', ru: 'ru-RU', zh: 'zh-CN', ko: 'ko-KR', hi: 'hi-IN', th: 'th-TH', hu: 'hu-HU'
}
let lang = 'en' // set only by _setLangState, called from i18n.js setLang
@@ -41,9 +41,12 @@ export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
export const exerciseNameFor = ex => {
const translated = exerciseNames && ex && exerciseNames[ex.id]
if (!translated) return ex?.n || ''
// Some names (Burpee, Pilates, brand/model terms) are the established pt-BR term too.
// Repeating an identical loanword in parentheses adds noise rather than context.
return translated.toLocaleLowerCase('pt-BR') === ex.n.toLocaleLowerCase('en')
// Some names (Burpee, Pilates, brand/model terms) are the established term in the target
// language too. Repeating an identical loanword in parentheses adds noise rather than
// context. Compared in the active language's own casing rules, not hardcoded to one —
// this only ever differs from ordinary casing for languages with locale-specific rules
// (e.g. Turkish dotless i), which does not include any language shipped here today.
return translated.toLocaleLowerCase(lang) === ex.n.toLocaleLowerCase('en')
? translated
: `${translated} (${ex.n})`
}
+17 -1
View File
@@ -21,6 +21,7 @@
import { EXDB, EXIDX } from './exercises.js'
import { uid } from './format.js'
import { isWarmupRow } from './workout-model.js'
import { HEVY_TITLE_MAP } from './hevy-id-map.js'
/* ----------------------------------------------------------------- CSV ---- */
@@ -251,6 +252,16 @@ export function matchExercise(name) {
return ties === 1 ? best : null
}
/**
* Exact Hevy English title → catalogue id (from the generated title map).
* Used when a CSV is detected as Hevy: same deterministic table as the API import,
* keyed by title because Hevy's CSV has no template id column.
*/
export function matchHevyTitle(name) {
const id = HEVY_TITLE_MAP[String(name || '').trim().toLowerCase()]
return id && EXIDX[id] ? id : null
}
// Hevy exports no category column, so every invented exercise fell through to the
// 'upper legs' default and a third of an imported history was attributed to the legs in
// the muscle map. When there is no category, read the body part off the name instead.
@@ -389,7 +400,12 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
const key = keyOf(name)
let id = resolved.get(key)
if (id === undefined) { id = matchExercise(name); resolved.set(key, id) }
if (id === undefined) {
// Hevy CSV: prefer the generated English-title map (same table as the API import).
// Localized titles still fall through to the word-bag matcher.
id = (source === 'Hevy' ? matchHevyTitle(name) : null) || matchExercise(name)
resolved.set(key, id)
}
if (id) matched++
else {
let c = created.get(key)
+448
View File
@@ -0,0 +1,448 @@
// Import a Hevy account through the public API (https://api.hevyapp.com/docs/).
//
// Exercise identity is Hevy's `exercise_template_id`, looked up in the generated
// `hevy-id-map.js` table — never the localized title on a set. Regenerate the map
// with `node scripts/build-hevy-id-map.mjs`. The API key never leaves this module's
// callers: nothing here stores it.
import { EXIDX } from './exercises.js'
import { uid } from './format.js'
import { isWarmupRow } from './workout-model.js'
import { HEVY_ID_MAP, HEVY_TITLE_MAP } from './hevy-id-map.js'
export { HEVY_ID_MAP, HEVY_TITLE_MAP }
export const HEVY_API = 'https://api.hevyapp.com'
export const HEVY_DEV_SETTINGS = 'https://hevy.com/settings?developer'
const LB_TO_KG = 0.45359237
/* --------------------------------------------------------------- auth/fetch -- */
class HevyApiError extends Error {
constructor(status, message) {
super(message || `Hevy API error ${status}`)
this.name = 'HevyApiError'
this.status = status
}
}
async function hevyGet(path, apiKey, params = {}) {
const url = new URL(path, HEVY_API)
for (const [k, v] of Object.entries(params)) {
if (v != null && v !== '') url.searchParams.set(k, String(v))
}
// Hevy publishes no rate limit, but a large account is 100+ sequential page requests; a 429
// gets a short back-off and one more try before it surfaces as its own error kind.
for (let attempt = 0; ; attempt++) {
const res = await fetch(url, { headers: { 'api-key': apiKey } })
if (res.status === 401 || res.status === 403) {
throw new HevyApiError(res.status, 'auth')
}
if (res.status === 429 && attempt < 2) {
const after = Number(res.headers?.get?.('retry-after'))
await new Promise(r => setTimeout(r, (after > 0 && after <= 30 ? after : 2 * (attempt + 1)) * 1000))
continue
}
if (res.status === 429) throw new HevyApiError(res.status, 'rate-limit')
if (!res.ok) throw new HevyApiError(res.status, `http ${res.status}`)
return res.json()
}
}
/** Page through a Hevy list endpoint. `pageSize` caps differ per resource. */
export async function fetchHevyPages(path, apiKey, {
resultKey,
pageSize = 10,
onProgress,
} = {}) {
const items = []
let page = 1
let pageCount = 1
while (page <= pageCount) {
const data = await hevyGet(path, apiKey, { page, pageSize })
pageCount = Math.max(1, data.page_count || 1)
const batch = data[resultKey] || []
items.push(...batch)
onProgress && onProgress({ page, pageCount, loaded: items.length, resultKey })
if (!batch.length) break
page++
}
return items
}
export async function fetchHevyAccount(apiKey, { onProgress } = {}) {
const key = String(apiKey || '').trim()
if (!key) throw new HevyApiError(0, 'empty')
const templates = await fetchHevyPages('/v1/exercise_templates', key, {
resultKey: 'exercise_templates', pageSize: 100,
onProgress: p => onProgress && onProgress({ stage: 'templates', ...p }),
})
const workouts = await fetchHevyPages('/v1/workouts', key, {
resultKey: 'workouts', pageSize: 10,
onProgress: p => onProgress && onProgress({ stage: 'workouts', ...p }),
})
const routines = await fetchHevyPages('/v1/routines', key, {
resultKey: 'routines', pageSize: 10,
onProgress: p => onProgress && onProgress({ stage: 'routines', ...p }),
})
let bodyMeasurements = []
try {
bodyMeasurements = await fetchHevyPages('/v1/body_measurements', key, {
resultKey: 'body_measurements', pageSize: 10,
onProgress: p => onProgress && onProgress({ stage: 'body', ...p }),
})
} catch (e) {
// Older keys / accounts may lack measurements — workouts still import.
if (!(e instanceof HevyApiError) || e.message === 'auth') throw e
}
return { templates, workouts, routines, bodyMeasurements }
}
/* ---------------------------------------------------------- template → id -- */
// Hevy primary_muscle_group → openGym body-part for exercises we invent.
const HEVY_BP = {
biceps: 'upper arms', triceps: 'upper arms', forearms: 'lower arms',
chest: 'chest', lats: 'back', upper_back: 'back', lower_back: 'back',
traps: 'back', shoulders: 'shoulders',
abdominals: 'waist', abs: 'waist', obliques: 'waist',
quadriceps: 'upper legs', hamstrings: 'upper legs', glutes: 'upper legs',
abductors: 'upper legs', adductors: 'upper legs', calves: 'lower legs',
cardio: 'cardio', full_body: 'upper legs', other: 'upper legs', neck: 'neck',
}
/**
* Resolve a Hevy exercise template to a catalogue id.
*
* Deterministic: only `HEVY_ID_MAP` (generated by scripts/build-hevy-id-map.mjs).
* No runtime name guessing — unmatched templates become custom exercises.
*/
export function matchHevyTemplate(template) {
if (!template?.id) return null
const id = HEVY_ID_MAP[template.id]
return id && EXIDX[id] ? id : null
}
/** Build templateId → catalogue id (or null) from a templates list. */
export function buildHevyExerciseMap(templates) {
const map = new Map()
for (const t of templates || []) {
if (!t?.id) continue
map.set(t.id, matchHevyTemplate(t))
}
return map
}
/* --------------------------------------------------------------- parse ---- */
const p2 = n => String(n).padStart(2, '0')
/** Hevy ISO timestamps → local calendar date + ms-since-midnight (matches CSV import). */
export function localWhen(iso) {
const d = new Date(iso)
if (isNaN(d.getTime())) return null
const day = `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}`
const t = d.getHours() * 3600000 + d.getMinutes() * 60000 + d.getSeconds() * 1000
return { d: day, t }
}
function bpOfTemplate(t) {
const g = String(t?.primary_muscle_group || '').toLowerCase()
return HEVY_BP[g] || 'upper legs'
}
/** Shared resolver: HEVY_ID_MAP hit, else one custom exercise per Hevy template id. */
function makeResolver(templates) {
const byId = new Map((templates || []).map(t => [t.id, t]))
const created = new Map()
const unmatched = new Set()
const matchedIds = new Set()
const resolve = (templateId, fallbackTitle) => {
const pinned = templateId && HEVY_ID_MAP[templateId]
if (pinned && EXIDX[pinned]) {
matchedIds.add(pinned)
return pinned
}
const key = templateId || String(fallbackTitle || '').toLowerCase()
if (!key) return null
let c = created.get(key)
if (!c) {
const t = templateId ? byId.get(templateId) : null
const name = (t?.title || fallbackTitle || 'exercise').toLowerCase()
c = {
id: 'im' + uid(), n: name, custom: true, eq: 'custom', tg: '', desc: '',
bp: bpOfTemplate(t) || (t?.type === 'distance_duration' || t?.type === 'duration' ? 'cardio' : null)
|| 'upper legs',
}
created.set(key, c)
unmatched.add(t?.title || fallbackTitle || name)
}
return c.id
}
return {
resolve,
byId,
customEx: () => [...created.values()],
unmatchedNames: () => [...unmatched].sort(),
matchedCount: () => matchedIds.size,
createdCount: () => created.size,
}
}
const toProfileWeight = (wKg, unit) => {
if (wKg == null || !isFinite(wKg)) return 0
if (unit === 'lb') return Math.round(wKg / LB_TO_KG * 10) / 10
return Math.round(wKg * 10) / 10
}
/**
* Turn Hevy API workouts into the same shape `mergeImport` already understands.
* Mapping is by `exercise_template_id` through `HEVY_ID_MAP` only — localized
* titles on each set are never used to pick a catalogue entry.
*/
export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) {
const R = makeResolver(templates)
const byDate = new Map()
let sets = 0, skipped = 0, matched = 0, warmups = 0, rpeSets = 0
for (const w of workouts || []) {
const start = localWhen(w.start_time)
const end = localWhen(w.end_time)
if (!start) { skipped++; continue }
let day = byDate.get(start.d)
if (!day) {
day = { ex: new Map(), name: w.title || '', start: start.t, end: end?.t ?? null }
byDate.set(start.d, day)
} else if (!day.name && w.title) day.name = w.title
if (end?.t != null) day.end = end.t
for (const ex of w.exercises || []) {
const id = R.resolve(ex.exercise_template_id, ex.title)
if (!id) { skipped++; continue }
if (EXIDX[id] && !String(id).startsWith('im')) matched++
if (!day.ex.has(id)) day.ex.set(id, [])
const list = day.ex.get(id)
for (const s of ex.sets || []) {
const warmup = /warm/i.test(String(s.type || ''))
if (warmup) warmups++
const reps = s.reps != null ? Math.round(s.reps) : 0
const wgt = toProfileWeight(s.weight_kg, unit)
const secs = s.duration_seconds != null ? Number(s.duration_seconds) : 0
const km = s.distance_meters != null ? Number(s.distance_meters) / 1000 : 0
if (!wgt && !reps && !secs && !km) { skipped++; continue }
const isCardio = (km > 0 || secs > 0) && !reps
const mins = secs > 0 ? Math.round(secs / 60 * 10) / 10 : 0
const set = isCardio
? { min: mins, speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0, done: true, ...(warmup ? { phase: 'warmup' } : {}) }
: { w: wgt, r: reps || 0, done: true, ...(warmup ? { phase: 'warmup' } : {}) }
if (!isCardio && s.rpe != null && isFinite(Number(s.rpe)) && Number(s.rpe) > 0) {
set.rpe = Math.min(10, Math.round(Number(s.rpe) * 100) / 100)
rpeSets++
}
list.push(set)
sets++
}
}
}
const dates = [...byDate.keys()].sort()
const outWorkouts = dates.map(d => {
const day = byDate.get(d)
const entries = [...day.ex.entries()].map(([id, ss]) => {
const mx = Math.max(0, ...ss.filter(s => !isWarmupRow(s)).map(s => s.w || 0))
return { id, sets: ss, topW: mx || null }
})
const base = new Date(d + 'T00:00:00').getTime()
const startMs = base + (day.start ?? 18 * 3600000)
const endMs = day.end != null ? base + day.end : startMs
const workout = {
id: 'iw' + uid(), d, start: startMs, end: endMs > startMs ? endMs : startMs,
routineId: null, name: day.name || 'Imported', entries, prs: [],
}
workout.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (s.w || 0) * (s.r || 0), 0), 0)
return workout
})
return {
kind: 'workouts',
source: 'Hevy',
workouts: outWorkouts,
customEx: R.customEx(),
matched: R.matchedCount(),
matchedSets: matched,
created: R.createdCount(),
unmatchedNames: R.unmatchedNames(),
sets, skipped, warmups,
fileUnit: 'kg',
mixedUnits: false,
converted: unit === 'lb',
rpeSets, rirSets: 0,
from: dates[0] || null,
to: dates[dates.length - 1] || null,
}
}
/**
* Hevy routine → openGym routine config.
* Work sets become `sets`×`reps`/`weight`; warm-ups become `warmupSets`;
* supersets keep adjacency via `sg`. Always imported as *new* routines.
*/
export function parseHevyRoutines(routines, templates, { unit = 'kg' } = {}) {
const R = makeResolver(templates)
const out = []
for (const r of routines || []) {
const ex = []
const sgMap = new Map() // Hevy superset_id → openGym sg token
for (const he of r.exercises || []) {
const id = R.resolve(he.exercise_template_id, he.title)
if (!id) continue
const allSets = he.sets || []
const warm = allSets.filter(s => /warm/i.test(String(s.type || ''))).length
const work = allSets.filter(s => !/warm/i.test(String(s.type || '')))
if (!work.length && !warm) continue
const sample = work[0] || allSets[0]
const reps = sample?.reps != null ? Math.round(sample.reps) : 0
const secs = sample?.duration_seconds != null ? Number(sample.duration_seconds) : 0
const km = sample?.distance_meters != null ? Number(sample.distance_meters) / 1000 : 0
const wgt = toProfileWeight(sample?.weight_kg, unit)
const nWork = Math.max(1, work.length)
let cfg
if (km > 0 && !reps) {
const mins = secs > 0 ? Math.round(secs / 60 * 10) / 10 : 20
cfg = {
id, sets: nWork, min: mins || 20,
speed: mins > 0 ? Math.round(km / (mins / 60) * 10) / 10 : 0,
}
} else if (secs > 0 && !reps && !wgt) {
cfg = { id, sets: nWork, sec: Math.round(secs), weight: 0, mode: 'time' }
} else {
cfg = { id, sets: nWork, reps: reps || 10, weight: wgt || 0, mode: 'reps' }
}
if (warm > 0) cfg.warmupSets = Math.min(5, warm)
if (he.notes) cfg.note = String(he.notes).slice(0, 280)
if (he.superset_id != null && he.superset_id !== '') {
const key = String(he.superset_id)
if (!sgMap.has(key)) sgMap.set(key, 'hs' + uid())
cfg.sg = sgMap.get(key)
}
ex.push(cfg)
}
if (!ex.length) continue
// Drop singleton supersets (partner missing after drops).
ex.forEach((e, i) => {
if (e.sg && !(ex[i - 1]?.sg === e.sg || ex[i + 1]?.sg === e.sg)) delete e.sg
})
out.push({
id: 'hr' + uid(),
name: (r.title || 'Imported').trim() || 'Imported',
emoji: 'figureStrength',
hevyId: r.id || null,
ex,
})
}
return {
kind: 'routines',
source: 'Hevy',
routines: out,
customEx: R.customEx(),
matched: R.matchedCount(),
created: R.createdCount(),
unmatchedNames: R.unmatchedNames(),
exerciseCount: out.reduce((n, r) => n + r.ex.length, 0),
converted: unit === 'lb',
}
}
/** Merge Hevy routines into state — always added as new routines (fresh ids). */
export function mergeHevyRoutines(S, parsed) {
S.customEx = S.customEx || []
S.routines = S.routines || []
const exIdMap = {}
;(parsed.customEx || []).forEach(c => {
const same = S.customEx.find(x => (x.n || '').toLowerCase() === (c.n || '').toLowerCase() && x.bp === c.bp)
if (same) { exIdMap[c.id] = same.id; return }
// Keep the pre-assigned id from parse so routine configs already point at it.
if (!S.customEx.some(x => x.id === c.id)) S.customEx.push(c)
})
// A second import must not double every plan: a routine that already carries the same Hevy
// id is replaced in place (its exercises re-read from Hevy), everything else is appended.
let added = 0, updated = 0
for (const r of parsed.routines || []) {
const ex = (r.ex || []).map(e => ({ ...e, id: exIdMap[e.id] || e.id }))
const existing = r.hevyId ? S.routines.find(x => x.hevyId === r.hevyId) : null
if (existing) {
existing.name = r.name
existing.ex = ex
updated++
continue
}
S.routines.push({
id: uid(),
name: r.name,
emoji: r.emoji || 'figureStrength',
...(r.hevyId ? { hevyId: r.hevyId } : {}),
ex,
})
added++
}
return { added, updated }
}
/** Body measurements from the Hevy API → `mergeImport` bodyweight shape. */
export function parseHevyBodyweight(measurements, { unit = 'kg' } = {}) {
const out = new Map()
for (const m of measurements || []) {
const d = String(m.date || '').slice(0, 10)
if (!/^\d{4}-\d{2}-\d{2}$/.test(d)) continue
let w = Number(m.weight_kg)
if (!isFinite(w) || w <= 0) continue
if (unit === 'lb') w = Math.round(w / LB_TO_KG * 10) / 10
else w = Math.round(w * 10) / 10
const t = m.created_at ? new Date(m.created_at).getTime() : new Date(d + 'T12:00:00').getTime()
out.set(d, { d, w, t: isFinite(t) ? t : new Date(d + 'T12:00:00').getTime() })
}
const dates = [...out.keys()].sort()
return {
kind: 'bodyweight',
source: 'Hevy',
bodyweight: dates.map(d => out.get(d)),
fileUnit: 'kg',
converted: unit === 'lb',
from: dates[0] || null,
to: dates[dates.length - 1] || null,
}
}
/**
* Fetch + parse. Returns `{ workouts, routines, bodyweight }` ready to merge,
* or throws `HevyApiError`. The apiKey is only read here — never written.
*/
export async function importHevyData(apiKey, { unit = 'kg', onProgress } = {}) {
const { templates, workouts, routines, bodyMeasurements } = await fetchHevyAccount(apiKey, { onProgress })
onProgress && onProgress({ stage: 'parse' })
return {
workouts: parseHevyWorkouts(workouts, templates, { unit }),
routines: parseHevyRoutines(routines, templates, { unit }),
bodyweight: parseHevyBodyweight(bodyMeasurements, { unit }),
templateCount: templates.length,
}
}
export { HevyApiError }
+302
View File
@@ -0,0 +1,302 @@
import { describe, expect, it, vi, afterEach } from 'vitest'
import {
matchHevyTemplate, buildHevyExerciseMap, parseHevyWorkouts, parseHevyBodyweight,
parseHevyRoutines, mergeHevyRoutines, localWhen, importHevyData, HevyApiError, HEVY_ID_MAP,
} from './import-hevy.js'
import { EXIDX } from './exercises.js'
import { mergeImport } from './import-csv.js'
const TEMPLATES = [
{
id: '3303376C', title: 'Elliptical Trainer', type: 'distance_duration',
primary_muscle_group: 'cardio', secondary_muscle_groups: [], equipment: 'machine', is_custom: false,
},
{
id: '4E5257DE', title: 'Lat Pulldown - Close Grip (Cable)', type: 'weight_reps',
primary_muscle_group: 'lats', secondary_muscle_groups: [], equipment: 'machine', is_custom: false,
},
{
id: 'DEADBEEF', title: 'My Invented Landmine Twist', type: 'weight_reps',
primary_muscle_group: 'abdominals', secondary_muscle_groups: [], equipment: 'other', is_custom: true,
},
{
id: '99D5F10E', title: 'Ab Wheel', type: 'reps_only',
primary_muscle_group: 'abdominals', secondary_muscle_groups: [], equipment: 'other', is_custom: false,
},
]
const WORKOUT = {
id: 'w1',
title: 'Oberkörper 2',
start_time: '2026-08-25T10:10:24+00:00',
end_time: '2026-08-25T11:10:08+00:00',
exercises: [
{
index: 0,
title: 'Crosstrainer', // localized — must NOT drive the match
exercise_template_id: '3303376C',
sets: [{
index: 0, type: 'normal', weight_kg: null, reps: null,
distance_meters: 480, duration_seconds: 180, rpe: null,
}],
},
{
index: 1,
title: 'Latzug - Enger Griff (Kabel)',
exercise_template_id: '4E5257DE',
sets: [
{ index: 0, type: 'warmup', weight_kg: 25, reps: 15, distance_meters: null, duration_seconds: null, rpe: null },
{ index: 1, type: 'normal', weight_kg: 52, reps: 15, distance_meters: null, duration_seconds: null, rpe: 8 },
{ index: 2, type: 'normal', weight_kg: 52, reps: 10, distance_meters: null, duration_seconds: null, rpe: null },
],
},
{
index: 2,
title: 'Meine Eigenkreation',
exercise_template_id: 'DEADBEEF',
sets: [
{ index: 0, type: 'normal', weight_kg: 20, reps: 12, distance_meters: null, duration_seconds: null, rpe: null },
],
},
],
}
describe('HEVY_ID_MAP', () => {
it('only points at real catalogue ids', () => {
for (const id of Object.values(HEVY_ID_MAP)) {
expect(EXIDX[id], `catalogue missing ${id}`).toBeTruthy()
}
})
// Real import leftovers: same lifts under Hevy's naming. Map lookup is the
// only resolution path — titles are never guessed at runtime.
const PINNED = {
B5D3A742: '0410', // Bulgarian Split Squat (Dumbbell)
'914F3A96': '0327', // Chest Supported Incline Row (Dumbbell)
'98237BA2': '0826', // Knee Raise Parallel Bars
'4E5257DE': '2616', // Lat Pulldown - Close Grip (Cable)
C315DC2A: '0602', // Rear Delt Reverse Fly (Cable)
FFDA283B: '0381', // Reverse Lunge (Dumbbell)
'8BAB2735': '0318', // Seated Incline Curl (Dumbbell)
'9237BAD1': '0603', // Seated Shoulder Press (Machine)
B05C2C29: '0605', // Single Leg Standing Calf Raise (Machine)
'3303376C': '2141', // Elliptical Trainer
'99D5F10E': '0857', // Ab Wheel
}
for (const [hid, want] of Object.entries(PINNED)) {
it(`maps ${hid} → ${want} (${EXIDX[want]?.n})`, () => {
expect(HEVY_ID_MAP[hid]).toBe(want)
expect(matchHevyTemplate({ id: hid, title: 'ignored localized name' })).toBe(want)
})
}
it('leaves catalogue gaps unmapped (import as custom)', () => {
for (const id of ['68CE0B9B', '0222DB42', 'D1CD146F']) {
expect(HEVY_ID_MAP[id]).toBeUndefined()
expect(matchHevyTemplate({ id, title: 'whatever' })).toBeNull()
}
})
})
describe('matchHevyTemplate', () => {
it('is map-only — title never overrides the id', () => {
expect(matchHevyTemplate({ id: '3303376C', title: 'Totally Wrong Name' })).toBe('2141')
expect(matchHevyTemplate({ id: 'DEADBEEF', title: 'Bench Press' })).toBeNull()
})
})
describe('parseHevyWorkouts', () => {
it('maps by template id, not the localized workout title', () => {
const parsed = parseHevyWorkouts([WORKOUT], TEMPLATES, { unit: 'kg' })
expect(parsed.error).toBeUndefined()
expect(parsed.source).toBe('Hevy')
expect(parsed.workouts).toHaveLength(1)
const entries = parsed.workouts[0].entries
const elliptical = entries.find(e => e.id === '2141')
expect(elliptical).toBeTruthy()
expect(elliptical.sets[0]).toMatchObject({ min: 3, done: true })
const pulldown = entries.find(e => e.id === '2616')
expect(pulldown).toBeTruthy()
expect(pulldown.sets[0]).toMatchObject({ w: 25, r: 15, phase: 'warmup' })
expect(pulldown.sets[1]).toMatchObject({ w: 52, r: 15, rpe: 8 })
expect(pulldown.topW).toBe(52)
expect(parsed.warmups).toBe(1)
expect(parsed.rpeSets).toBe(1)
const custom = entries.find(e => String(e.id).startsWith('im'))
expect(custom).toBeTruthy()
expect(parsed.customEx.some(c => c.id === custom.id && c.n === 'my invented landmine twist')).toBe(true)
expect(parsed.customEx.find(c => c.id === custom.id).bp).toBe('waist')
expect(parsed.unmatchedNames).toContain('My Invented Landmine Twist')
})
it('converts kg weights into a lb profile', () => {
const parsed = parseHevyWorkouts([WORKOUT], TEMPLATES, { unit: 'lb' })
const pulldown = parsed.workouts[0].entries.find(e => e.id === '2616')
expect(pulldown.sets.find(s => s.r === 15 && !s.phase).w).toBeCloseTo(114.6, 0)
expect(parsed.converted).toBe(true)
})
it('merges two Hevy sessions on the same local day', () => {
const a = { ...WORKOUT, id: 'a', title: 'AM', exercises: [WORKOUT.exercises[0]] }
const b = {
...WORKOUT, id: 'b', title: 'PM',
start_time: '2026-08-25T18:00:00+00:00',
end_time: '2026-08-25T19:00:00+00:00',
exercises: [WORKOUT.exercises[1]],
}
const parsed = parseHevyWorkouts([a, b], TEMPLATES, { unit: 'kg' })
expect(parsed.workouts).toHaveLength(1)
expect(parsed.workouts[0].entries.length).toBeGreaterThanOrEqual(2)
})
})
describe('parseHevyBodyweight', () => {
it('reads weigh-ins in the profile unit', () => {
const parsed = parseHevyBodyweight([
{ id: 1, date: '2026-08-23', weight_kg: 83.2, created_at: '2026-08-23T18:22:48.070Z' },
], { unit: 'kg' })
expect(parsed.bodyweight).toEqual([{ d: '2026-08-23', w: 83.2, t: expect.any(Number) }])
})
})
describe('mergeImport with Hevy payloads', () => {
it('adds workouts and skips days that already exist', () => {
const parsed = parseHevyWorkouts([WORKOUT], TEMPLATES, { unit: 'kg' })
const S = { workouts: [], customEx: [], exWeights: {}, bodyweight: [] }
const first = mergeImport(S, parsed)
expect(first.added).toBe(1)
expect(S.customEx.length).toBe(1)
const second = mergeImport(S, parsed)
expect(second.added).toBe(0)
expect(S.workouts).toHaveLength(1)
})
})
describe('localWhen', () => {
it('parses an ISO timestamp into a local calendar day', () => {
const w = localWhen('2026-08-25T10:10:24+00:00')
expect(w.d).toMatch(/^\d{4}-\d{2}-\d{2}$/)
expect(w.t).toBeGreaterThanOrEqual(0)
})
})
describe('importHevyData', () => {
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks() })
it('pages templates and workouts, never persists the key', async () => {
const calls = []
vi.stubGlobal('fetch', vi.fn(async (url, opts) => {
calls.push({ url: String(url), key: opts.headers['api-key'] })
const u = String(url)
if (u.includes('/exercise_templates')) {
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, exercise_templates: TEMPLATES }) }
}
if (u.includes('/workouts')) {
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, workouts: [WORKOUT] }) }
}
if (u.includes('/routines')) {
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, routines: [] }) }
}
if (u.includes('/body_measurements')) {
return { ok: true, status: 200, json: async () => ({ page: 1, page_count: 1, body_measurements: [] }) }
}
return { ok: false, status: 404, json: async () => ({}) }
}))
const result = await importHevyData('test-key-not-stored', { unit: 'kg' })
expect(result.workouts.workouts).toHaveLength(1)
expect(result.routines.routines).toHaveLength(0)
expect(result.bodyweight.bodyweight).toHaveLength(0)
expect(calls.every(c => c.key === 'test-key-not-stored')).toBe(true)
})
it('surfaces a refused key as HevyApiError auth', async () => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 401, json: async () => ({}) })))
await expect(importHevyData('bad')).rejects.toMatchObject({ name: 'HevyApiError', message: 'auth' })
})
})
describe('parseHevyRoutines', () => {
const ROUTINE = {
id: 'r1',
title: 'Oberkörper 2',
exercises: [
{
title: 'Crosstrainer',
exercise_template_id: '3303376C',
superset_id: null,
sets: [{ type: 'normal', weight_kg: null, reps: null, distance_meters: 480, duration_seconds: 180 }],
},
{
title: 'Latzug',
exercise_template_id: '4E5257DE',
superset_id: 1,
sets: [
{ type: 'warmup', weight_kg: 25, reps: 15 },
{ type: 'normal', weight_kg: 52, reps: 15 },
{ type: 'normal', weight_kg: 52, reps: 12 },
{ type: 'normal', weight_kg: 52, reps: 10 },
],
},
{
title: 'Row partner',
exercise_template_id: '914F3A96', // chest supported incline row → 0327
superset_id: 1,
sets: [
{ type: 'normal', weight_kg: 20, reps: 12 },
{ type: 'normal', weight_kg: 20, reps: 12 },
],
},
],
}
it('builds openGym routine configs from Hevy sets', () => {
const parsed = parseHevyRoutines([ROUTINE], TEMPLATES, { unit: 'kg' })
expect(parsed.routines).toHaveLength(1)
expect(parsed.routines[0].name).toBe('Oberkörper 2')
expect(parsed.exerciseCount).toBe(3)
const [cardio, pull, row] = parsed.routines[0].ex
expect(cardio.id).toBe('2141')
expect(cardio).toMatchObject({ sets: 1, min: 3 })
expect(pull.id).toBe('2616')
expect(pull).toMatchObject({ sets: 3, reps: 15, weight: 52, warmupSets: 1 })
expect(row.id).toBe('0327')
expect(pull.sg).toBeTruthy()
expect(pull.sg).toBe(row.sg)
})
it('mergeHevyRoutines replaces a routine it imported before instead of duplicating it', () => {
const parsed = parseHevyRoutines([ROUTINE], TEMPLATES, { unit: 'kg' })
const S = { routines: [], customEx: [] }
expect(mergeHevyRoutines(S, parsed)).toEqual({ added: 1, updated: 0 })
expect(S.routines).toHaveLength(1)
expect(S.routines[0].hevyId).toBe(ROUTINE.id)
const firstId = S.routines[0].id
S.routines[0].name = 'renamed locally'
expect(mergeHevyRoutines(S, parsed)).toEqual({ added: 0, updated: 1 })
expect(S.routines).toHaveLength(1)
expect(S.routines[0].id).toBe(firstId)
expect(S.routines[0].name).toBe(ROUTINE.title)
})
it('mergeHevyRoutines still adds a routine that carries no Hevy id', () => {
const parsed = parseHevyRoutines([{ ...ROUTINE, id: undefined }], TEMPLATES, { unit: 'kg' })
const S = { routines: [], customEx: [] }
mergeHevyRoutines(S, parsed); mergeHevyRoutines(S, parsed)
expect(S.routines).toHaveLength(2)
})
})
describe('buildHevyExerciseMap', () => {
it('indexes every template id from the static map', () => {
const map = buildHevyExerciseMap(TEMPLATES)
expect(map.get('3303376C')).toBe('2141')
expect(map.get('4E5257DE')).toBe('2616')
expect(map.get('DEADBEEF')).toBeNull()
expect(map.size).toBe(TEMPLATES.length)
})
})
+34 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { matchExercise, parseWorkoutCSV } from './import-csv.js'
import { matchExercise, matchHevyTitle, parseWorkoutCSV, detectSource } from './import-csv.js'
import { EXIDX } from './exercises.js'
// The names other apps actually export, and the catalogue entry each has to land on.
@@ -109,3 +109,36 @@ describe('invented exercises get a body part from their name', () => {
expect(r.customEx[0].bp).toBe('shoulders')
})
})
describe('Hevy CSV uses the generated title map', () => {
const HEVY_CSV = [
'title,start_time,end_time,description,exercise_title,superset_id,exercise_notes,set_index,set_type,weight_kg,reps,distance_km,duration_seconds,rpe',
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Bulgarian Split Squat (Dumbbell),,,0,normal,40,10,0,,',
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Lat Pulldown - Close Grip (Cable),,,0,warmup,25,15,0,,',
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Lat Pulldown - Close Grip (Cable),,,1,normal,52,12,0,,8',
'Push,2026-08-01 10:00:00,2026-08-01 11:00:00,,Reverse Lunge (Dumbbell),,,0,normal,20,10,0,,',
].join('\n')
it('detects the Hevy export dialect', () => {
expect(detectSource(HEVY_CSV.split('\n')[0].split(','))).toBe('Hevy')
})
it('resolves English Hevy titles through HEVY_TITLE_MAP before the word-bag', () => {
expect(matchHevyTitle('Bulgarian Split Squat (Dumbbell)')).toBe('0410')
expect(matchHevyTitle('Lat Pulldown - Close Grip (Cable)')).toBe('2616')
expect(matchHevyTitle('Reverse Lunge (Dumbbell)')).toBe('0381')
// Word-bag alone still misses these — the title map is what makes CSV work.
expect(matchExercise('Bulgarian Split Squat (Dumbbell)')).toBeNull()
})
it('imports a Hevy CSV onto catalogue ids, not customs', () => {
const parsed = parseWorkoutCSV(HEVY_CSV, { unit: 'kg' })
expect(parsed.source).toBe('Hevy')
expect(parsed.created).toBe(0)
const ids = parsed.workouts[0].entries.map(e => e.id).sort()
expect(ids).toEqual(['0410', '0381', '2616'].sort())
const pull = parsed.workouts[0].entries.find(e => e.id === '2616')
expect(pull.sets[0]).toMatchObject({ w: 25, r: 15, phase: 'warmup' })
expect(pull.sets[1]).toMatchObject({ w: 52, r: 12, rpe: 8 })
})
})
+69 -19
View File
@@ -4,13 +4,14 @@
// mode in a browser, this is the user's only copy of their training log, so it can't depend
// on WebView localStorage alone (iOS evicts that under storage pressure). Every persist()
// therefore also lands in a JSON file in the app's private data directory, and boot()
// restores from it. The workout reminder uses native local notifications scheduled per
// planned weekday — no server involved, unlike Web Push in the self-hosted version.
// restores from it. The workout reminder uses native local notifications scheduled per future
// calendar date — no server involved, unlike Web Push in the self-hosted version.
//
// Like the demo build, MOBILE is replaced at build time, so all of this folds away in
// web bundles; the Capacitor plugins are only ever imported behind it.
import { t } from './i18n-core.js'
import { todayISO } from './format.js'
import { isoOf, todayISO } from './format.js'
import { effectiveRoutineId } from './history.js'
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
@@ -68,34 +69,83 @@ export async function saveRemoteFile(data) {
} catch (e) { /* worst case: onboarding asks again next launch */ }
}
// (Re)schedule the workout-day reminder: one repeating notification per weekday that has a
// routine in the weekly plan. Cheap enough to run after any state change — the plan or the
// reminder time may just have been edited. `interactive` gates the OS permission prompt to
// the Settings toggle; a background resync never pops a dialog.
// Keep enough dates queued to cover normal app use between foregrounds without creating an
// unbounded notification list. The next sync cancels and replaces this whole window.
export const REMINDER_WINDOW_DAYS = 60
const REMINDER_ID_BASE = 1000
const LEGACY_REMINDER_IDS = Array.from({ length: 7 }, (_, d) => ({ id: 100 + d }))
// Pure date expansion for the native reminder. `now` is injectable so the calendar boundary,
// completed-day suppression, and today's past-time rule stay deterministic in tests.
export function buildReminderNotifications(S, now = new Date()) {
const r = S?.reminder
if (!r?.on) return []
const routines = Array.isArray(S.routines) ? S.routines : []
const completed = new Set((S.workouts || []).map(w => w.d))
const state = { ...S, routines, week: S.week || {}, dayPlan: S.dayPlan || {} }
const [hour, minute] = (r.time || '08:00').split(':').map(Number)
if (!Number.isInteger(hour) || !Number.isInteger(minute)) return []
const date = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12)
const notifications = []
for (let offset = 0; offset < REMINDER_WINDOW_DAYS; offset++) {
const day = new Date(date)
day.setDate(date.getDate() + offset)
const iso = isoOf(day)
if (completed.has(iso)) continue
const rid = effectiveRoutineId(state, iso)
const routine = routines.find(x => x.id === rid)
if (!routine) continue
const at = new Date(day)
at.setHours(hour, minute, 0, 0)
if (at <= now) continue
notifications.push({
id: REMINDER_ID_BASE + offset,
title: t('Workout day'),
body: t('{0} is on the plan today — let’s go!', routine.name),
schedule: { at, allowWhileIdle: true },
})
}
return notifications
}
// (Re)schedule the workout-day reminder: one one-off notification per future calendar date in
// the bounded window. Cheap enough to run after any state change — the plan or the reminder time
// may just have been edited. `interactive` gates the OS permission prompt to the Settings toggle;
// a background resync never pops a dialog.
export async function syncReminder(S, interactive = false) {
try {
const { LocalNotifications } = await import('@capacitor/local-notifications')
await LocalNotifications.cancel({ notifications: [0, 1, 2, 3, 4, 5, 6].map(d => ({ id: 100 + d })) }).catch(() => {})
await LocalNotifications.cancel({ notifications: [
...LEGACY_REMINDER_IDS,
...Array.from({ length: REMINDER_WINDOW_DAYS }, (_, d) => ({ id: REMINDER_ID_BASE + d })),
] }).catch(() => {})
const r = S.reminder
if (!r?.on) return true
let perm = await LocalNotifications.checkPermissions()
if (perm.display !== 'granted' && interactive) perm = await LocalNotifications.requestPermissions()
if (perm.display !== 'granted') return false
const [hour, minute] = (r.time || '08:00').split(':').map(Number)
const notifications = Object.entries(S.week || {})
.filter(([, rid]) => rid && (S.routines || []).some(x => x.id === rid))
.map(([day, rid]) => ({
id: 100 + Number(day),
title: t('Workout day'),
body: t('{0} is on the plan today — let’s go!', S.routines.find(x => x.id === rid).name),
// Capacitor weekdays are 1 (Sunday) … 7 (Saturday); S.week uses getDay() 0…6.
schedule: { on: { weekday: Number(day) + 1, hour, minute }, allowWhileIdle: true },
}))
const notifications = buildReminderNotifications(S)
if (notifications.length) await LocalNotifications.schedule({ notifications })
return true
} catch (e) { return false }
}
// Capacitor emits appStateChange when the native shell returns to the foreground. The visibility
// listener also covers WebView/browser transitions, and both are harmless on a non-mobile build.
let reminderSyncStarted = false
export function initReminderSync(getState) {
if (!MOBILE || reminderSyncStarted) return
reminderSyncStarted = true
const resync = () => {
if (document.visibilityState === 'hidden') return
syncReminder(getState()).catch(() => {})
}
document.addEventListener('visibilitychange', resync)
import('@capacitor/app').then(({ App }) => {
App.addListener('appStateChange', ({ isActive }) => { if (isActive) resync() })
}).catch(() => {})
}
// WKWebView can't do blob-URL downloads, so the backup goes out through the OS share sheet
// (Files, AirDrop, mail, …) from a temp file instead.
export async function shareExport(json, filename) {
@@ -120,4 +170,4 @@ export async function writeAutoBackup(state) {
recursive: true,
})
} catch (e) { /* best effort — the private mirror in Directory.Data still has the data */ }
}
}
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, it } from 'vitest'
import { isoOf } from './format.js'
import { buildReminderNotifications } from './mobile.js'
const push = { id: 'push', name: 'Push' }
const pull = { id: 'pull', name: 'Pull' }
const legs = { id: 'legs', name: 'Legs' }
const state = (patch = {}) => ({
routines: [push, pull, legs], week: {}, dayPlan: {}, workouts: [],
reminder: { on: true, time: '08:00' }, ...patch,
})
const iso = d => isoOf(d)
describe('buildReminderNotifications', () => {
it('expands the weekly baseline into future dated notifications', () => {
const now = new Date(2026, 5, 1, 7, 0) // Monday
const notifications = buildReminderNotifications(state({ week: { 1: 'push', 3: 'pull' } }), now)
expect(notifications.slice(0, 2).map(n => iso(n.schedule.at))).toEqual([
iso(now), iso(new Date(2026, 5, 3)),
])
expect(notifications[0].body).toContain('Push')
expect(notifications[0].schedule.allowWhileIdle).toBe(true)
})
it('uses rest today and a routine override tomorrow when rescheduling', () => {
const now = new Date(2026, 5, 1, 7, 0) // Monday
const today = iso(now), tomorrow = iso(new Date(2026, 5, 2))
const notifications = buildReminderNotifications(state({
week: { 1: 'push' }, dayPlan: { [today]: 'rest', [tomorrow]: 'pull' },
}), now)
expect(notifications.slice(0, 1).map(n => [iso(n.schedule.at), n.body])).toEqual([
[tomorrow, expect.stringContaining('Pull')],
])
})
it('schedules a valid override on a weekly rest day', () => {
const now = new Date(2026, 5, 1, 7, 0) // Monday
const wednesday = new Date(2026, 5, 3)
const notifications = buildReminderNotifications(state({ dayPlan: { [iso(wednesday)]: 'legs' } }), now)
expect(notifications.some(n => iso(n.schedule.at) === iso(wednesday) && n.body.includes('Legs'))).toBe(true)
})
it('suppresses dates that already have a completed workout', () => {
const now = new Date(2026, 5, 1, 7, 0) // Monday
const notifications = buildReminderNotifications(state({
week: { 1: 'push' }, workouts: [{ d: iso(now) }],
}), now)
expect(notifications.some(n => iso(n.schedule.at) === iso(now))).toBe(false)
})
it("skips today's reminder after the configured local time has passed", () => {
const now = new Date(2026, 5, 1, 9, 0) // Monday
const notifications = buildReminderNotifications(state({ week: { 1: 'push' } }), now)
expect(notifications.some(n => iso(n.schedule.at) === iso(now))).toBe(false)
expect(notifications.some(n => iso(n.schedule.at) === iso(new Date(2026, 5, 8)))).toBe(true)
})
})
+18 -2
View File
@@ -9,6 +9,7 @@
import { isWarmupRow } from './workout-model.js'
import { EXIDX, smOf } from './exercises.js'
import { todayISO, weekKey, MONDAY } from './format.js'
// The muscles a map can shade, in head-to-toe order — also the order of any list
// built from them, so "what am I neglecting" reads top-down like a body.
@@ -160,7 +161,7 @@ export function muscleGroupsOf(entry) {
? [...parts.primary, ...parts.secondary]
: explicit || [ex?.tg, ex?.mg, ...arrayOf(smOf(ex))]
const out = canonicalUnique(source)
if (!out.length && !useParts && explicit == null) {
if (!out.length && !useParts) {
canonicalUnique(Object.keys(BY_BODYPART[ex?.bp] || {})).forEach(slug => out.push(slug))
}
return out
@@ -259,6 +260,20 @@ export const loadOfWorkouts = (workouts, pick) =>
loadOf((workouts || []).flatMap(w =>
(w.entries || []).map(e => ({ id: e.id, ex: e.exercise || e, sets: (e.sets || []).filter(s => s.done && !isWarmupRow(s) && (!pick || pick(s))).length }))))
/**
* Workouts in one existing Muscle balance range, with time injected for deterministic tests.
*
* The 7-day range is "this week", not "the last seven days", so it moves with the profile's
* first weekday — the caller passes it since this takes workouts rather than the whole state.
*/
export function muscleBalanceWindow(workouts, win, now = Date.now(), today = todayISO(), ws = MONDAY) {
return (workouts || []).filter(workout => win === 0
? true
: win === 7
? weekKey(workout.d, ws) === weekKey(today, ws)
: (workout.start || new Date(workout.d).getTime()) > now - win * 86400000)
}
/** Load a routine *would* produce, from its planned set counts. */
export const loadOfRoutine = routine =>
loadOf((routine?.ex || []).map(c => ({ id: c.id, ex: c, sets: c.sets || 1 })))
@@ -304,7 +319,8 @@ export function levelsOf(load, thresholds) {
/** Muscles sorted hardest-worked first; untrained ones last, in body order. */
export function rankOf(load) {
const worked = MUSCLES.filter(m => (load[m] || 0) > 0).sort((a, b) => load[b] - load[a])
const worked = MUSCLES.filter(m => (load[m] || 0) > 0)
.sort((a, b) => load[b] - load[a] || MUSCLES.indexOf(a) - MUSCLES.indexOf(b))
const missed = MUSCLES.filter(m => !(load[m] > 0))
return { worked, missed }
}
+39 -1
View File
@@ -1,6 +1,9 @@
import { describe, it, expect } from 'vitest'
import { EXIDX, EXDB, smOf } from './exercises.js'
import { MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, loadOf, loadOfWorkouts, matchesMuscleGroups, muscleGroupsOf, musclesOf } from './muscles.js'
import {
MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, levelsOf, loadOf,
loadOfWorkouts, matchesMuscleGroups, muscleBalanceWindow, muscleGroupsOf, musclesOf, rankOf
} from './muscles.js'
describe('multi-muscle exercise metadata', () => {
it('normalizes legacy primary/secondary fields and removes duplicate groups', () => {
@@ -20,6 +23,12 @@ describe('multi-muscle exercise metadata', () => {
expect(matchesMuscleGroups({ bp: 'back', muscleGroups: [] }, ['lower-back'])).toBe(true)
})
it('falls back consistently when explicit groups contain only unknown names', () => {
const ex = { bp: 'back', muscleGroups: ['not-a-drawable-name'] }
expect(muscleGroupsOf(ex)).toEqual(['upper-back', 'lower-back'])
expect(musclesOf(ex)).toEqual({ 'upper-back': 0.75, 'lower-back': 0.25 })
})
it('matches an exercise when any requested muscle group matches', () => {
const ex = { muscleGroups: ['chest', 'triceps'] }
expect(matchesMuscleGroups(ex, ['hamstring', 'triceps'])).toBe(true)
@@ -172,3 +181,32 @@ describe('warm-up boundary', () => {
}
})
})
describe('muscle balance windows and ranking', () => {
const now = new Date('2026-08-27T12:00:00').getTime()
const workouts = [
{ id: 'monday', d: '2026-08-24', start: new Date('2026-08-24T12:00:00').getTime() },
{ id: 'sunday', d: '2026-08-23', start: new Date('2026-08-23T12:00:00').getTime() },
{ id: 'boundary', d: '2026-07-28', start: now - 30 * 86400000 },
{ id: 'inside', d: '2026-07-29', start: now - 29 * 86400000 },
]
it('preserves calendar-week, strict trailing-day, and all-history semantics', () => {
expect(muscleBalanceWindow(workouts, 7, now, '2026-08-27').map(w => w.id)).toEqual(['monday'])
expect(muscleBalanceWindow(workouts, 30, now, '2026-08-27').map(w => w.id)).toEqual(['monday', 'sunday', 'inside'])
expect(muscleBalanceWindow(workouts, 0, now, '2026-08-27')).toEqual(workouts)
})
it('uses relative levels and canonical order to break load ties', () => {
const load = { chest: 2, deltoids: 2, biceps: 1 }
expect(rankOf(load).worked).toEqual(['deltoids', 'chest', 'biceps'])
expect(levelsOf(load)).toMatchObject({ deltoids: 4, chest: 4, biceps: 2, abs: 0 })
})
it('keeps catalogue precedence and deleted-custom snapshot weights', () => {
const known = { id: '0025', muscleGroups: ['quadriceps'], sets: [{ done: true }] }
const deleted = { id: 'deleted', muscleSnapshot: { muscleWeights: { chest: 1 } }, sets: [{ done: true }] }
expect(loadOfWorkouts([{ entries: [known] }])).toEqual({ chest: 1, triceps: 0.4, deltoids: 0.4, biceps: 0.4 })
expect(loadOfWorkouts([{ entries: [deleted] }])).toEqual({ chest: 1 })
})
})
+28 -10
View File
@@ -10,11 +10,12 @@
import { EXIDX, isBodyweightEq } from './exercises.js'
import { modeOf, fmtSec, isBw, isPerSide, sideReps, MAX_PLANNED_WARMUPS } from './history.js'
import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js'
import { uid, todayISO, DAYN, weekOrder, weekStartOf, fmtNum, exCount } from './format.js'
import { t, exerciseNameFor } from './i18n-core.js'
const PLAN_FMT = 1
const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] // Mon-first, matching the Plan screen
const WEEK_DAYS = [1, 2, 3, 4, 5, 6, 0] // every getDay() index; only the reader's own
// screen puts them in an order (see weekOrder)
// Keep only the meaningful config fields, so the file stays small and readable.
function cleanEx(e) {
@@ -44,6 +45,10 @@ function cleanEx(e) {
if (e.inc > 0) o.inc = e.inc
if (e.repsMin != null) o.repsMin = e.repsMin
if (e.repsMax != null) o.repsMax = e.repsMax
// The exercise's own rest (issue #10) is part of how it is prescribed, so it travels too —
// only when set, so a plan that never asked for one leaves the recipient's own default
// timer in charge. parsePlan and mergePlan carry it through by spread.
if (e.restSec > 0) o.restSec = e.restSec
if (e.sg) o.sg = e.sg
if (e.note) o.note = e.note
const warm = cleanWarmupSets(e.warmupSets)
@@ -63,6 +68,13 @@ function cleanWarmupSets(v) {
return n > 0 ? Math.min(MAX_PLANNED_WARMUPS, n) : 0
}
/** A positive whole number of seconds or nothing — the same gate cleanEx applies on the way
* out, so a hand-edited plan file can't hand the rest timer a string or a negative. */
function cleanRestSec(v) {
const n = Math.round(Number(v)) || 0
return n > 0 ? n : 0
}
/** Keep the floors the config sheet and applyIntensifierPlan already enforce, and nothing else:
* a plan file is someone else's data, so anything unrecognised is dropped rather than trusted. */
function cleanIntensifier(x) {
@@ -79,14 +91,17 @@ function cleanIntensifier(x) {
/** Build the shareable bundle: every routine, the week schedule, referenced customs. */
export function buildPlanBundle(S, name) {
const routines = (S.routines || []).map(r => ({
id: r.id, name: r.name, emoji: r.emoji, ...(r.prog ? { prog: r.prog } : {}), ex: (r.ex || []).map(cleanEx)
id: r.id, name: r.name, emoji: r.emoji,
...(r.prog ? { prog: r.prog } : {}),
...(r.excludeFromProgression === true ? { excludeFromProgression: true } : {}),
ex: (r.ex || []).map(cleanEx)
}))
const usedIds = new Set(routines.flatMap(r => r.ex.map(e => e.id)))
const customEx = (S.customEx || [])
.filter(c => usedIds.has(c.id))
.map(c => ({ id: c.id, n: c.n, bp: c.bp, ...(c.desc ? { desc: c.desc } : {}) }))
const week = {}
WEEK_ORDER.forEach(d => { if (S.week?.[d]) week[d] = S.week[d] })
WEEK_DAYS.forEach(d => { if (S.week?.[d]) week[d] = S.week[d] })
return { opengym_plan: PLAN_FMT, exported: todayISO(), name: name || '', week, routines, customEx }
}
@@ -114,12 +129,13 @@ export function parsePlan(raw) {
if (!ok) dropped++
return ok
}).map(e => {
// The exercises pass through as written, so the two fields that carry numbers into the
// The exercises pass through as written, so the fields that carry numbers into the
// planner get the same clamps on the way in that they get on the way out.
const warm = cleanWarmupSets(e.warmupSets)
const intens = cleanIntensifier(e.intensifier)
const { warmupSets, intensifier, ...rest } = e
return { ...rest, ...(warm ? { warmupSets: warm } : {}), ...(intens ? { intensifier: intens } : {}) }
const rest = cleanRestSec(e.restSec)
const { warmupSets, intensifier, restSec, ...passthrough } = e
return { ...passthrough, ...(warm ? { warmupSets: warm } : {}), ...(intens ? { intensifier: intens } : {}), ...(rest ? { restSec: rest } : {}) }
})
}))
return {
@@ -130,7 +146,7 @@ export function parsePlan(raw) {
dropped,
routineCount: routines.length,
exerciseCount: routines.reduce((n, r) => n + r.ex.length, 0),
scheduledDays: WEEK_ORDER.filter(d => data.week?.[d]).length
scheduledDays: WEEK_DAYS.filter(d => data.week?.[d]).length
}
}
@@ -160,11 +176,12 @@ export function mergePlan(s, bundle, { schedule } = {}) {
name: r.name || t('Shared routine'),
emoji: r.emoji,
...(r.prog ? { prog: r.prog } : {}),
...(r.excludeFromProgression === true ? { excludeFromProgression: true } : {}),
ex: (r.ex || []).map(e => ({ ...e, id: exIdMap[e.id] || e.id }))
})
})
if (schedule) {
WEEK_ORDER.forEach(d => { delete s.week[d] })
WEEK_DAYS.forEach(d => { delete s.week[d] })
Object.entries(bundle.week || {}).forEach(([d, oldId]) => {
if (ridMap[oldId]) s.week[d] = ridMap[oldId]
})
@@ -224,7 +241,8 @@ function routineHTML(r, unit) {
}
function weekHTML(S) {
const rows = WEEK_ORDER.map(d => {
// The printout is read by whoever exported it, so the week runs in their order.
const rows = weekOrder(weekStartOf(S)).map(d => {
const r = S.routines.find(x => x.id === S.week?.[d])
const val = r ? esc(r.name) : `<span class="rest">${esc(t('Rest'))}</span>`
return `<div class="w-row"><div class="w-day">${esc(t(DAYN[d]))}</div><div class="w-r">${val}</div></div>`
+42 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { buildPlanBundle, parsePlan } from './plan-share.js'
import { buildPlanBundle, mergePlan, parsePlan } from './plan-share.js'
// There was no test file for plan sharing at all, which is how a whole prescription field
// went missing without anyone noticing.
@@ -24,6 +24,37 @@ describe('what survives a shared plan', () => {
expect(roundTrip({ warmupSets: 3 }).warmupSets).toBe(3)
})
it('carries progression exclusion on a routine through export and merge', () => {
const source = stateWith({})
source.routines[0].excludeFromProgression = true
const bundle = parsePlan(buildPlanBundle(source, 'Plan'))
const target = { routines: [], week: {}, customEx: [] }
expect(bundle.routines[0].excludeFromProgression).toBe(true)
mergePlan(target, bundle)
expect(target.routines[0].excludeFromProgression).toBe(true)
})
// Issue #10: the rest an exercise prescribes is part of the prescription. A shared 5x5 whose
// rests arrive as the recipient's 60 s default is a different session than the one written.
it('carries a per-exercise rest', () => {
expect(roundTrip({ restSec: 180 }).restSec).toBe(180)
})
// The absence has to survive too: writing a 0 would pin the recipient's timer to "off"
// instead of letting the exercise keep inheriting whatever their own default is.
it('leaves an exercise that set no rest free of the field', () => {
expect('restSec' in roundTrip({})).toBe(false)
expect('restSec' in roundTrip({ restSec: 0 })).toBe(false)
})
it('carries the rest onto the routine mergePlan adds', () => {
const bundle = parsePlan(JSON.stringify(buildPlanBundle(stateWith({ restSec: 180 }), 'Plan')))
const s = { routines: [], customEx: [], week: {} }
mergePlan(s, bundle, { schedule: false })
expect(s.routines[0].ex[0].restSec).toBe(180)
})
it('drops an intensifier it does not recognise rather than passing it on', () => {
expect(roundTrip({ intensifier: { type: 'nonsense', count: 3 } }).intensifier).toBeUndefined()
})
@@ -33,6 +64,16 @@ describe('what survives a shared plan', () => {
expect(parsePlan(bundle).routines[0].ex[0].warmupSets).toBe(5)
})
// A plan file is someone else's data: a rest that arrives as a string would reach the timer's
// arithmetic as one, and a negative or garbage one has no meaning to keep.
it('normalises a hand-edited rest to a positive whole number or drops it', () => {
const withRest = restSec => ({ opengym_plan: 1, name: 'x', routines: [{ id: 'r', name: 'R', ex: [{ id: '0025', sets: 3, reps: 5, restSec }] }], week: {}, customEx: [] })
expect(parsePlan(withRest('120')).routines[0].ex[0].restSec).toBe(120)
expect(parsePlan(withRest(90.6)).routines[0].ex[0].restSec).toBe(91)
expect('restSec' in parsePlan(withRest(-30)).routines[0].ex[0]).toBe(false)
expect('restSec' in parsePlan(withRest('abc')).routines[0].ex[0]).toBe(false)
})
// The floors are the config sheet's own (count >= 1, pct >= 5); a value that is present but
// out of range is pulled up to the floor, while a missing one falls back to the default.
it('clamps out-of-range intensifier numbers to the floors the app enforces', () => {
+13
View File
@@ -0,0 +1,13 @@
import { POLICY_NAME } from './progression.js'
/**
* Presentation-only view of a progression result. The engine remains the source of truth for
* both the outcome and its explanation; this helper only makes the policy behind that result
* explicit in the workout guidance.
*/
export function progressionGuidance(plan) {
if (!plan?.why || plan.kind === 'off' || plan.policy === 'off') return null
const policyLabel = POLICY_NAME[plan.policy]
if (!policyLabel) return null
return { policyLabel, why: plan.why }
}
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest'
import { progressionGuidance } from './progression-copy.js'
describe('policy-labelled progression guidance', () => {
it('keeps the calculated outcome and identifies the policy that produced it', () => {
const why = ['Every rep last time — {0} {1} more.', 2.5, 'kg']
expect(progressionGuidance({ policy: 'linear', kind: 'up', weight: 62.5, why }))
.toEqual({ policyLabel: 'Linear progression', why })
})
it('labels hold and deload outcomes without changing their calculated reasons', () => {
const hold = ['Missed reps last time — same weight again ({0} of {1} to go).', 2, 3]
const deload = ['Missed reps — reset to {0} {1} and work back up.', 55, 'kg']
expect(progressionGuidance({ policy: 'double', kind: 'hold', why: hold }))
.toEqual({ policyLabel: 'Double progression', why: hold })
expect(progressionGuidance({ policy: 'greyskull', kind: 'deload', why: deload }))
.toEqual({ policyLabel: 'Greyskull LP', why: deload })
})
it('labels a baseline outcome and omits policies with no visible outcome', () => {
const baseline = ['Nothing logged yet — this session sets the baseline.']
expect(progressionGuidance({ policy: 'linear', kind: 'first', why: baseline }))
.toEqual({ policyLabel: 'Linear progression', why: baseline })
expect(progressionGuidance({ policy: 'off', kind: 'off' })).toBeNull()
expect(progressionGuidance({ policy: 'linear', kind: 'first' })).toBeNull()
expect(progressionGuidance(null)).toBeNull()
})
})
+8 -2
View File
@@ -19,6 +19,7 @@
import { modeOf, repStep, rerampWarmups } from './history.js'
import { EXIDX } from './exercises.js'
import { isWarmupRow } from './workout-model.js'
import { normalizeRepRange } from './rep-range.js'
export const POLICIES = ['off', 'linear', 'greyskull', 'double', 'time']
@@ -134,6 +135,10 @@ export function readSession(entry, fallback) {
export function sessionsFor(S, exId, fallback) {
const out = []
;(S.workouts || []).forEach(w => {
// A planned deload remains a real workout for history and statistics, but it cannot become
// the baseline for the next regular prescription. The routine flag is copied onto the
// active session, then onto this completed workout, so later routine edits do not rewrite it.
if (w.excludeFromProgression === true) return
const entry = w.entries.find(e => e.id === exId)
if (entry && entry.sets.some(s => s.done && !isWarmupRow(s))) out.push({ d: w.d, ...readSession(entry, fallback) })
})
@@ -210,8 +215,9 @@ export function nextPrescription(S, cfg, routine) {
return { policy, kind: 'up', weight: 0, reps: next, why: ['Bodyweight — every rep last time, so go for {0} this time.', next] }
}
if (policy === 'double') {
const top = cfg.reps || last.goal || 10
const bottom = Math.min(cfg.repsMin || Math.max(1, top - 2), top)
const range = normalizeRepRange(cfg.reps || last.goal || 10, cfg.repsMin, repStep(cfg))
const top = range.reps
const bottom = range.repsMin
if (last.ok) return { policy, kind: 'up', weight: snap(w + inc, inc), reps: bottom, why: ['Top of the rep range in every set — {0} {1} more, back to {2} reps.', inc, unit, bottom] }
if (stalls >= deloadAt) {
const dw = deloadTo(w, inc)
+26
View File
@@ -311,6 +311,13 @@ describe('double progression', () => {
expect(p.reps).toBe(8)
expect(p.weight).toBe(35) // 40 × 0.9 = 36 → nearest loadable 2.5 step
})
it('normalizes persisted per-side bounds before prescribing', () => {
const perSide = { ...cfg, reps: 13, repsMin: 7, side: true }
const p = nextPrescription(hist(LIFT, [[40, 12, 12, 12]], { sets: 3, reps: 13 }), perSide)
expect(p.kind).toBe('hold')
expect(p.reps).toBe(14)
})
})
describe('timed progression', () => {
@@ -374,6 +381,25 @@ describe('sessionsFor', () => {
expect(sessionsFor(S, LIFT).map(s => s.d)).toEqual(['2026-01-01'])
})
it('ignores marked deload workouts when it calculates the next regular target', () => {
const target = { sets: 3, reps: 5, weight: 60 }
const entry = (weight, reps) => ({
id: LIFT,
target: { ...target, weight },
sets: reps.map(r => ({ w: weight, r, done: true }))
})
const S = {
unit: 'kg',
workouts: [
{ d: '2026-01-01', entries: [entry(60, [5, 5, 5])] },
{ d: '2026-01-08', excludeFromProgression: true, entries: [entry(30, [8, 8])] }
]
}
expect(sessionsFor(S, LIFT).map(s => s.d)).toEqual(['2026-01-01'])
expect(nextPrescription(S, { id: LIFT, ...target, prog: 'linear' }).weight).toBe(62.5)
})
it('reads a legacy entry that has no target without crashing', () => {
const S = { unit: 'kg', workouts: [{ d: '2026-01-01', entries: [{ id: LIFT, sets: [{ w: 60, r: 5, done: true }] }] }] }
expect(sessionsFor(S, LIFT)).toHaveLength(1)
+3 -3
View File
@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(539)
expect(inherited).toHaveLength(545)
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(586)
expect(inherited).toHaveLength(553)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('206471a00deba14ead15903b2334353d9fcc1fadc645c00db985db2bc73d35ad')
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('4a550b06e44cabd2b69834c15607220ca547854f2b0934843cadaa60a7f61a27')
})
test('does not leak European Portuguese UI terms', () => {
+11 -4
View File
@@ -61,6 +61,12 @@ function emptyMuscleMap(value) {
return Object.fromEntries(MUSCLES.map(slug => [slug, value]))
}
// Current catalogue metadata stays authoritative. Finished entries retain a nested muscle
// snapshot specifically so deleted custom exercises can still contribute to recovery maps.
function exerciseFor(entry) {
return EXIDX[entry?.id] || entry
}
// Epley one-rep-max estimate, matching onerm.js (REP_CAP included so high-rep sets do not
// inflate the estimate). Used only to express a set's intensity relative to the lifter's own
// capacity - the same formula the app already shows for estimated 1RM.
@@ -161,7 +167,7 @@ function loadKgFor(ex, entry, set, workout, opts = {}) {
function session1RMs(workout, opts = {}) {
const best = new Map()
for (const entry of workout?.entries || []) {
const ex = EXIDX[entry.id]
const ex = exerciseFor(entry)
for (const set of entry.sets || []) {
const load = loadKgFor(ex, entry, set, workout, opts)
if (set?.done !== true || !(load > 0) || !(set.r > 0)) continue
@@ -221,10 +227,11 @@ function sessionTonnages(workout, opts = {}) {
const sums = emptyMuscleMap(0)
const oneRms = session1RMs(workout, opts)
for (const entry of workout?.entries || []) {
const weights = musclesOf(EXIDX[entry.id])
const ex = exerciseFor(entry)
const weights = musclesOf(ex)
for (const set of entry.sets || []) {
if (set?.done !== true) continue
const measured = setTonnage(EXIDX[entry.id], entry, set, workout, oneRms.get(entry.id), opts)
const measured = setTonnage(ex, entry, set, workout, oneRms.get(entry.id), opts)
const tonnage = Number.isFinite(measured) && measured > 0 ? measured : ZERO_LOAD_SET_STIMULUS
for (const [slug, weight] of Object.entries(weights)) {
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug)) sums[slug] += tonnage * weight
@@ -326,7 +333,7 @@ export function strengthOf(workouts, now, opts = {}) {
if (!Number.isFinite(timestamp)) continue
for (const entry of workout.entries || []) {
if (!(entry.sets || []).some(set => set?.done === true && !isWarmupRow(set))) continue
for (const slug of Object.keys(musclesOf(EXIDX[entry.id]))) {
for (const slug of Object.keys(musclesOf(exerciseFor(entry)))) {
if (Object.prototype.hasOwnProperty.call(MUSCLES_BY_SLUG, slug) && timestamp > latest[slug]) {
latest[slug] = timestamp
}
+37 -1
View File
@@ -17,7 +17,7 @@ import {
strengthOf,
} from './recovery.js'
import { EXDB, registerCustom } from './exercises.js'
import { MUSCLES, musclesOf } from './muscles.js'
import { MUSCLES, exerciseMuscleSnapshot, musclesOf } from './muscles.js'
import { fatigueStateOf } from './recovery-view.js'
const HOUR = 60 * 60 * 1000
@@ -128,6 +128,42 @@ describe('fatigueOf and strengthOf', () => {
expect(fatigueOf(highRep, NOW)[SINGLE_SLUG]).toBeGreaterThan(0.5)
})
it('uses a deleted exercise snapshot for the same bounded primary and secondary fatigue', () => {
const resolved = doneWorkoutAt(WEIGHTED.id, NOW)
const deleted = {
...resolved,
entries: [{
...resolved.entries[0],
id: 'deleted-weighted-exercise',
muscleSnapshot: exerciseMuscleSnapshot(WEIGHTED),
}],
}
expect(fatigueOf([deleted], NOW)).toEqual(fatigueOf([resolved], NOW))
expect(fatigueOf([deleted], NOW)[WEIGHTED_PRIMARY_SLUG]).toBeGreaterThan(0)
expect(fatigueOf([deleted], NOW)[SECONDARY_SLUG]).toBeGreaterThan(0)
})
it('uses a deleted exercise snapshot for strength without changing decay or floor semantics', () => {
const start = NOW - 15 * DAY
const resolved = doneWorkoutAt(WEIGHTED.id, start)
const deleted = {
...resolved,
entries: [{
...resolved.entries[0],
id: 'deleted-weighted-exercise',
muscleSnapshot: exerciseMuscleSnapshot(WEIGHTED),
}],
}
const untouchedSlug = MUSCLES.find(slug => !WEIGHTED_WEIGHTS[slug])
const strength = strengthOf([deleted], NOW)
expect(strength).toEqual(strengthOf([resolved], NOW))
expect(strength[WEIGHTED_PRIMARY_SLUG]).toBeCloseTo(0.5 ** (1 / 28), 10)
expect(strength[SECONDARY_SLUG]).toBeCloseTo(0.5 ** (1 / 28), 10)
expect(strength[untouchedSlug]).toBe(STRENGTH_FLOOR)
})
it('raises starting fatigue with volume, never pins, and fades without a cliff', () => {
const at0 = count => fatigueOf([doneWorkoutAt(SINGLE.id, NOW, count)], NOW)[SINGLE_SLUG]
expect(at0(1)).toBeCloseTo(1 - Math.exp(-V / FATIGUE_REF_VOLUME), 10)
+19
View File
@@ -0,0 +1,19 @@
// Normalize the two bounds used by double progression.
// `reps` is the upper bound and `repsMin` is the lower bound in persisted configs.
export function normalizeRepRange(reps, repsMin, stride = 1) {
const step = Number.isInteger(stride) && stride > 0 ? stride : 1
const upper = align(positiveInt(reps, 10), step)
const lower = align(positiveInt(repsMin, Math.max(1, upper - 2)), step)
return lower >= upper
? { reps: lower + step, repsMin: lower }
: { reps: upper, repsMin: lower }
}
function align(value, stride) {
return Math.max(stride, Math.ceil(value / stride) * stride)
}
function positiveInt(value, fallback) {
const n = Number(value)
return Number.isFinite(n) && n > 0 ? Math.max(1, Math.round(n)) : fallback
}
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { normalizeRepRange } from './rep-range.js'
describe('normalizeRepRange', () => {
it('keeps valid positive integer bounds unchanged', () => {
expect(normalizeRepRange(12, 8)).toEqual({ reps: 12, repsMin: 8 })
})
it('rounds bounds to positive integers', () => {
expect(normalizeRepRange(12.4, 7.6)).toEqual({ reps: 12, repsMin: 8 })
expect(normalizeRepRange(0, -2)).toEqual({ reps: 10, repsMin: 8 })
})
it('raises the upper bound when the lower bound reaches it', () => {
expect(normalizeRepRange(8, 8)).toEqual({ reps: 9, repsMin: 8 })
})
it('raises the upper bound when the lower bound exceeds it', () => {
expect(normalizeRepRange(8, 12)).toEqual({ reps: 13, repsMin: 12 })
})
it('keeps the lower bound at least one below a lowered upper bound', () => {
expect(normalizeRepRange(6, 8)).toEqual({ reps: 9, repsMin: 8 })
})
it('supplies a usable default lower bound for a small upper bound', () => {
expect(normalizeRepRange(1, undefined)).toEqual({ reps: 2, repsMin: 1 })
})
it('aligns both bounds to an even stride', () => {
expect(normalizeRepRange(13, 7, 2)).toEqual({ reps: 14, repsMin: 8 })
})
it('keeps a valid gap when per-side bounds are invalid', () => {
expect(normalizeRepRange(8, 9, 2)).toEqual({ reps: 12, repsMin: 10 })
expect(normalizeRepRange(0, -2, 2)).toEqual({ reps: 10, repsMin: 8 })
})
})
+21
View File
@@ -0,0 +1,21 @@
// How a session's exercise entries are built from a routine. Shared by the live start and by
// "log a past workout", which is the same screen pointed at another day — both must walk up
// to identical entries, or the two paths drift apart the first time a prescription rule changes.
// Imports both history.js and progression.js (which itself imports history.js); nothing in
// either imports this file, so there is no cycle.
import { buildSets, applyIntensifierPlan } from './history.js'
import { nextPrescription, applyPrescription, defaultIncrement } from './progression.js'
export function buildSessionEntries(st, r) {
// The prescription is applied as the session is built, so you walk up to the bar with the
// right weight already on the screen instead of being told about it afterwards. `plan` is
// kept on the entry purely so the workout can explain the number it chose.
const excluded = r?.excludeFromProgression === true
const entries = (r ? r.ex : []).map(cfg => {
const plan = excluded ? { policy: 'off', kind: 'off' } : nextPrescription(st, cfg, r)
const step = defaultIncrement(cfg.id, st.unit)
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step, useTarget: excluded }), plan, step), cfg)
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets }
})
return { entries, excluded }
}
+47
View File
@@ -2,6 +2,27 @@
// the stores makes the uneven-round and re-check rules explicit and directly testable.
const hasWork = (entries, idx) => !!entries[idx]?.sets?.some(set => !set.done)
// Return the first unfinished navigation unit after the current one, wrapping once so a user
// who completed units out of order is never offered workout completion while earlier work remains.
export function nextUnfinishedUnit(entries, units, fromIdx) {
if (!Array.isArray(entries) || !Array.isArray(units) || units.length === 0) return null
const current = units.findIndex(unit => unit.includes(fromIdx))
const ordered = current < 0
? units
: [...units.slice(current + 1), ...units.slice(0, current)]
return ordered.find(unit => unit.some(idx => hasWork(entries, idx))) || null
}
// The current exercise may be one member of a contiguous superset. Insert after that complete
// navigation unit; invalid/empty state safely falls back to the end of the entry list.
export function insertionIndexAfterCurrentUnit(units, currentIndex, entryCount) {
const length = Math.max(0, Number(entryCount) || 0)
if (!Array.isArray(units) || units.length === 0) return length
const unit = units.find(candidate => candidate.includes(currentIndex))
if (!unit?.length) return length
return Math.min(length, Math.max(...unit) + 1)
}
// A completion is new progress only when it takes this exercise beyond the largest number of
// simultaneously completed sets seen in this mounted session. Uncheck/re-check therefore does
// not repeat navigation or rest side effects, while completing an added set still can.
@@ -42,6 +63,32 @@ export function restOnRecheck({ timerRunning, unitDone, lastUnit }) {
return !timerRunning && restAfterSet({ unitDone, lastUnit })
}
/**
* How long the rest after a completed set should run, in seconds.
*
* An exercise may carry its own `restSec` in its target (issue #10) — a heavy triple and a set
* of curls do not want the same break. One that carries none inherits `defaultRestSec`, the
* global rest timer, which is what every routine did before the field existed.
*
* `unit` is the superset group the set belongs to, as entry indices — a plain exercise is a
* group of one. A group rests once, after the round, so it takes the LONGEST rest any of its
* members asked for: the shortest would send you back to the bar before the member that needs
* the most recovery is ready.
*
* `defaultRestSec` of 0 is the rest timer turned off (v1.2.11). That silences the members that
* have no rest of their own, but an exercise that explicitly asks for one still gets it — the
* setting is a default, and this field overrides the default.
*/
export function restSecFor(entries, unit, defaultRestSec) {
const fallback = defaultRestSec > 0 ? defaultRestSec : 0
const idxs = Array.isArray(unit) && unit.length ? unit : []
if (!idxs.length) return fallback
return idxs.reduce((longest, idx) => {
const own = entries?.[idx]?.target?.restSec
return Math.max(longest, own > 0 ? own : fallback)
}, 0)
}
// Decide where a newly completed superset set goes next. Spent members are skipped, including
// across the wrap. A round ends when no later member in display order has work left; this makes
// the last *active* member the boundary rather than blindly using the group's last array index.
+66 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from './supersetFlow.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from './supersetFlow.js'
const entry = done => ({ sets: done.map(value => ({ done: value })) })
@@ -52,6 +52,26 @@ describe('supersetFlowStep', () => {
})
})
describe('active workout unit ordering', () => {
it('inserts after the whole current unit', () => {
expect(insertionIndexAfterCurrentUnit([[0, 1], [2]], 0, 3)).toBe(2)
expect(insertionIndexAfterCurrentUnit([[0], [1]], 1, 2)).toBe(2)
expect(insertionIndexAfterCurrentUnit([], 0, 0)).toBe(0)
})
it('finds the next unfinished unit, skips completed units, and wraps once', () => {
const entries = [entry([false]), entry([true]), entry([false]), entry([true])]
const units = [[0], [1], [2, 3]]
expect(nextUnfinishedUnit(entries, units, 0)).toEqual([2, 3])
expect(nextUnfinishedUnit(entries, units, 2)).toEqual([0])
})
it('returns null only when every unit is complete', () => {
const entries = [entry([true]), entry([true])]
expect(nextUnfinishedUnit(entries, [[0], [1]], 1)).toBeNull()
})
})
// Issue #3 has two halves. restAfterSet covers "no break after the LAST set of an exercise";
// this covers "after the first set, sometimes a break doesn't appear" — the uncheck/re-check
// that the high-water rule swallows.
@@ -72,3 +92,48 @@ describe('rest on a re-check', () => {
expect(restOnRecheck({ timerRunning: false, unitDone: true, lastUnit: false })).toBe(true)
})
})
// Issue #10: a routine can give an exercise its own rest, and the global timer stops being the
// only answer. The resolution is the whole feature — the UI just writes the number down.
describe('restSecFor', () => {
// 0: no rest of its own, 1: 180 s, 2: 45 s — a heavy pull, a light accessory, a plain one.
const entries = [
{ id: 'a', target: { mode: 'reps' } },
{ id: 'b', target: { mode: 'reps', restSec: 180 } },
{ id: 'c', target: { mode: 'reps', restSec: 45 } },
]
it('prefers the exercise’s own rest over the global default', () => {
expect(restSecFor(entries, [1], 90)).toBe(180)
expect(restSecFor(entries, [2], 90)).toBe(45)
})
it('falls back to the global default when the exercise sets none', () => {
expect(restSecFor(entries, [0], 90)).toBe(90)
})
it('gives a superset the longest rest its members asked for', () => {
// Not the member that closed the round, and not the shortest: the group rests once, and
// the 180 s exercise is the one still recovering when the 45 s one is ready to go again.
expect(restSecFor(entries, [1, 2], 90)).toBe(180)
// A member with no rest of its own pulls in the global, which can be the longest of all.
expect(restSecFor(entries, [0, 2], 90)).toBe(90)
})
it('honours an explicit rest even with the global timer switched off', () => {
expect(restSecFor(entries, [1], 0)).toBe(180)
expect(restSecFor(entries, [0, 1], 0)).toBe(180)
})
it('stays off when the timer is off and nothing asked for a rest', () => {
expect(restSecFor(entries, [0], 0)).toBe(0)
expect(restSecFor(entries, [0, 0], 0)).toBe(0)
})
it('survives a missing unit or entry rather than timing NaN', () => {
expect(restSecFor(entries, null, 90)).toBe(90)
expect(restSecFor(entries, [], 90)).toBe(90)
expect(restSecFor(entries, [7], 90)).toBe(90)
expect(restSecFor(undefined, [0], undefined)).toBe(0)
})
})
+78
View File
@@ -0,0 +1,78 @@
import { useCallback, useEffect } from 'react'
/* Keyboard-aware sheets. When the mobile keyboard comes up the layout viewport keeps its
size, only the visual viewport shrinks — so a bottom sheet with a text input near its
foot ends up half under the keys. index.css reads two custom properties on the sheet
(--picker-keyboard-bottom / --picker-visual-height) to lift and cap it. SelectSheet in
components/ui.jsx does exactly this sync inline; the exercise picker, the custom-exercise
form and the note sheets need the same thing, hence this hook. The logic is deliberately
duplicated rather than imported so ui.jsx keeps no public surface for it.
`inputRef` points at the text input (or textarea) whose closest `.sheet` gets the vars.
`enabled` lets a caller switch the sync off (e.g. a picker without a search box). */
export function useSheetKeyboard(inputRef, enabled = true) {
const sync = useCallback(() => {
const input = inputRef.current
const sheet = input?.closest?.('.sheet')
const viewport = typeof window !== 'undefined' ? window.visualViewport : null
if (!sheet || !viewport) return
const visualHeight = Math.max(0, viewport.height || window.innerHeight)
const visualBottom = (viewport.offsetTop || 0) + visualHeight
const bottomInset = Math.max(0, window.innerHeight - visualBottom)
sheet.style.setProperty('--picker-keyboard-bottom', `${bottomInset}px`)
sheet.style.setProperty('--picker-visual-height', `${visualHeight}px`)
}, [inputRef])
useEffect(() => {
if (!enabled) return
const viewport = typeof window !== 'undefined' ? window.visualViewport : null
if (!viewport) return
sync()
viewport.addEventListener('resize', sync)
viewport.addEventListener('scroll', sync)
return () => {
viewport.removeEventListener('resize', sync)
viewport.removeEventListener('scroll', sync)
// The sheet element outlives this input when the sheet swaps content, so leave it
// the way we found it rather than pinning a stale keyboard inset on it.
const sheet = inputRef.current?.closest?.('.sheet')
sheet?.style.removeProperty('--picker-keyboard-bottom')
sheet?.style.removeProperty('--picker-visual-height')
}
}, [enabled, sync, inputRef])
// Hand back as onFocus so the first measurement happens as the keyboard opens, before
// the visualViewport events land (on iOS they can arrive a frame late).
return sync
}
/* Chip strips scroll sideways, and a filter set from code ("★ Chosen", a reset) can land the
active chip off-screen. Pull it into view along the strip only — block:'nearest' never moves
the page when the strip is already visible, which is the case for every strip we have. */
export function useRevealActiveChip(stripRef, active) {
useEffect(() => {
const strip = stripRef.current
const chip = strip?.querySelector?.('.chip.on')
if (!chip || typeof chip.scrollIntoView !== 'function') return
chip.scrollIntoView({ inline: 'nearest', block: 'nearest' })
}, [stripRef, active])
}
/* Props that make a clickable <div> behave like a button for keyboard and screen-reader
users. Kept as a div because some rows nest a real <Button> (Library), and a button inside
a button is invalid HTML. Space is swallowed so the page does not scroll under the row. */
export function tappable(onClick) {
if (!onClick) return {}
return {
role: 'button',
tabIndex: 0,
onClick,
onKeyDown: e => {
if (e.target !== e.currentTarget) return // a nested control handles its own keys
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
onClick(e)
}
}
}
}
@@ -0,0 +1,40 @@
import { describe, expect, it, vi } from 'vitest'
import { tappable } from './use-sheet-keyboard.js'
const keyEvent = (key, target) => {
const ev = { key, target, currentTarget: target, preventDefault: vi.fn() }
return ev
}
describe('tappable', () => {
it('turns a plain onClick into a keyboard-reachable button', () => {
const onClick = vi.fn()
const p = tappable(onClick)
expect(p.role).toBe('button')
expect(p.tabIndex).toBe(0)
expect(p.onClick).toBe(onClick)
const el = {}
p.onKeyDown(keyEvent('Enter', el))
expect(onClick).toHaveBeenCalledTimes(1)
const space = keyEvent(' ', el)
p.onKeyDown(space)
expect(onClick).toHaveBeenCalledTimes(2)
expect(space.preventDefault).toHaveBeenCalled() // Space must not scroll the page
})
it('ignores other keys and keys from nested controls', () => {
const onClick = vi.fn()
const p = tappable(onClick)
const el = {}
p.onKeyDown(keyEvent('a', el))
p.onKeyDown(keyEvent('Escape', el))
expect(onClick).not.toHaveBeenCalled()
const nested = { key: 'Enter', target: {}, currentTarget: el, preventDefault: vi.fn() }
p.onKeyDown(nested)
expect(onClick).not.toHaveBeenCalled()
})
it('gives an inert row nothing to react to', () => {
expect(tappable(undefined)).toEqual({})
})
})
+133
View File
@@ -0,0 +1,133 @@
import { describe, it, expect } from 'vitest'
import { MONDAY, SUNDAY, weekStartOf, weekOrder, weekDayOffset, startOfWeek, weekKey, isoOf } from './format.js'
import { streakWeeks } from './history.js'
import { muscleBalanceWindow } from './muscles.js'
import { effortWeeks } from './effort.js'
// 2026-08-19 is a Wednesday. Its Monday-first week runs Mon 17th → Sun 23rd; its Sunday-first
// week runs Sun 16th → Sat 22nd. Every case below is picked so the two disagree — a date that
// lands in the same week either way would pass without testing anything.
const WED = '2026-08-19'
describe('weekStartOf', () => {
it('defaults to Monday for state written before the setting existed', () => {
expect(weekStartOf({})).toBe(MONDAY)
expect(weekStartOf(undefined)).toBe(MONDAY)
expect(weekStartOf({ weekStart: undefined })).toBe(MONDAY)
})
it('only 0 means Sunday — a junk value is not a third week shape', () => {
expect(weekStartOf({ weekStart: SUNDAY })).toBe(SUNDAY)
expect(weekStartOf({ weekStart: 3 })).toBe(MONDAY)
expect(weekStartOf({ weekStart: null })).toBe(MONDAY)
})
})
describe('weekOrder', () => {
it('lists all seven getDay() indices from the chosen start', () => {
expect(weekOrder(MONDAY)).toEqual([1, 2, 3, 4, 5, 6, 0])
expect(weekOrder(SUNDAY)).toEqual([0, 1, 2, 3, 4, 5, 6])
})
})
describe('weekDayOffset', () => {
it('is the column a weekday sits in', () => {
expect(weekDayOffset(1, MONDAY)).toBe(0) // Monday, Monday-first
expect(weekDayOffset(0, MONDAY)).toBe(6) // Sunday closes a Monday-first week
expect(weekDayOffset(0, SUNDAY)).toBe(0)
expect(weekDayOffset(1, SUNDAY)).toBe(1)
})
})
describe('startOfWeek', () => {
it('walks back to the chosen first day', () => {
expect(isoOf(startOfWeek(WED, MONDAY))).toBe('2026-08-17')
expect(isoOf(startOfWeek(WED, SUNDAY))).toBe('2026-08-16')
})
it('leaves a date that already is the first day alone', () => {
expect(isoOf(startOfWeek('2026-08-17', MONDAY))).toBe('2026-08-17')
expect(isoOf(startOfWeek('2026-08-16', SUNDAY))).toBe('2026-08-16')
})
it('is noon local, so a DST jump cannot move it to the day before', () => {
// Europe/Zurich springs forward on 2026-03-29, a Sunday.
expect(isoOf(startOfWeek('2026-03-29', SUNDAY))).toBe('2026-03-29')
expect(isoOf(startOfWeek('2026-03-29', MONDAY))).toBe('2026-03-23')
})
})
describe('weekKey', () => {
it('is equal for two days in the same week and different across the boundary', () => {
// Sunday the 16th and Wednesday the 19th: one week Sunday-first, two Monday-first.
expect(weekKey('2026-08-16', SUNDAY)).toBe(weekKey(WED, SUNDAY))
expect(weekKey('2026-08-16', MONDAY)).not.toBe(weekKey(WED, MONDAY))
})
it('defaults to Monday when no start is passed', () => {
expect(weekKey(WED)).toBe(weekKey(WED, MONDAY))
})
it('does not collide across years', () => {
expect(weekKey('2025-08-19', MONDAY)).not.toBe(weekKey('2026-08-19', MONDAY))
})
})
describe('the week streak counts the profile’s own weeks', () => {
// Two sessions on the Sunday and the Monday that straddle a Monday-first boundary. To a
// Monday profile that is a session in each of two consecutive weeks; to a Sunday profile
// both fall in the same week and there is only one.
const iso = d => isoOf(new Date(Date.now() - d * 86400000))
const sundayBack = () => {
// The most recent Sunday that is not today, so both dates are in the past.
const d = new Date()
d.setDate(d.getDate() - ((d.getDay() + 7) % 7 || 7))
return d
}
it('splits a Sun/Mon pair into two weeks for a Monday profile, one for a Sunday profile', () => {
const sun = sundayBack()
const mon = new Date(sun); mon.setDate(sun.getDate() + 1)
const workouts = [{ d: isoOf(sun) }, { d: isoOf(mon) }]
expect(weekKey(isoOf(sun), MONDAY)).not.toBe(weekKey(isoOf(mon), MONDAY))
expect(weekKey(isoOf(sun), SUNDAY)).toBe(weekKey(isoOf(mon), SUNDAY))
expect(streakWeeks({ workouts, weekStart: SUNDAY })).toBe(1)
})
it('is zero without workouts whatever the week start', () => {
expect(streakWeeks({ workouts: [], weekStart: SUNDAY })).toBe(0)
expect(iso(0)).toBe(isoOf(new Date()))
})
})
describe('“this week” ranges follow the setting', () => {
const workouts = [{ d: '2026-08-16' }, { d: WED }] // Sunday, then Wednesday
it('muscle balance: the 7-day window is a week, not the last seven days', () => {
const mon = muscleBalanceWindow(workouts, 7, Date.now(), WED, MONDAY)
expect(mon.map(w => w.d)).toEqual([WED])
const sun = muscleBalanceWindow(workouts, 7, Date.now(), WED, SUNDAY)
expect(sun.map(w => w.d)).toEqual(['2026-08-16', WED])
})
it('muscle balance defaults to Monday when no start is passed', () => {
expect(muscleBalanceWindow(workouts, 7, Date.now(), WED).map(w => w.d)).toEqual([WED])
})
it('the effort chart groups and positions its points by the same week', () => {
// Four rated sets: two on the Sunday, two on the Wednesday. Monday-first that is two
// points (one per week, each with its two rated sets); Sunday-first it is one point.
const set = r => ({ done: true, w: 60, r: 8, rir: r })
const workout = d => ({ d, start: new Date(d + 'T10:00:00').getTime(), entries: [{ id: '0025', sets: [set(2), set(3)] }] })
const S = { effort: 'rir', workouts: [workout('2026-08-16'), workout(WED)] }
const mon = effortWeeks({ ...S, weekStart: MONDAY }, 0)
expect(mon).toHaveLength(2)
expect(mon.map(p => isoOf(new Date(p.t)))).toEqual(['2026-08-10', '2026-08-17'])
const sun = effortWeeks({ ...S, weekStart: SUNDAY }, 0)
expect(sun).toHaveLength(1)
expect(isoOf(new Date(sun[0].t))).toBe('2026-08-16')
expect(sun[0].sets).toBe(4)
})
})
+59 -5
View File
@@ -5,7 +5,6 @@ export default {
'Cancel': 'Abbrechen',
'Press back again to exit': 'Zum Beenden erneut zurück drücken',
'Delete': 'Löschen',
'Save': 'Speichern',
'Import': 'Importieren',
'Discard': 'Verwerfen',
'All': 'Alle',
@@ -36,6 +35,8 @@ export default {
'rescheduled': 'verschoben',
'Prev': 'Zurück',
'Next': 'Weiter',
'Move up': 'Nach oben',
'Move down': 'Nach unten',
// --- days & months ---
'Sunday': 'Sonntag', 'Monday': 'Montag', 'Tuesday': 'Dienstag', 'Wednesday': 'Mittwoch',
'Thursday': 'Donnerstag', 'Friday': 'Freitag', 'Saturday': 'Samstag',
@@ -95,6 +96,12 @@ export default {
'Weight ({0})': 'Gewicht ({0})',
'Add to routine': 'Zur Routine hinzufügen',
'Remove exercise': 'Übung entfernen',
'Swap exercise': 'Übung wechseln',
'Swap exercise?': 'Übung tauschen?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Aufgezeichnete Sätze bleiben bei der ursprünglichen Übung. Wähle, wo die Ersatzübung hingehört.',
'Keep replacement in this group': 'Ersatzübung in dieser Gruppe behalten',
'Insert after this group': 'Nach dieser Gruppe einfügen',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Aufgezeichnete Sätze bleiben bei der ursprünglichen Übung. Die Ersatzübung wird danach eingefügt.',
'Remove {0}?': '{0} entfernen?',
'The sets you logged for this exercise in this session will be lost.': 'Die in dieser Einheit für diese Übung protokollierten Sätze gehen verloren.',
'This removes the exercise from your current session.': 'Dadurch wird die Übung aus deiner aktuellen Einheit entfernt.',
@@ -137,7 +144,6 @@ export default {
'Tracked — next time starts at {0}': 'Gespeichert — nächstes Mal startest du bei {0}',
"That's the whole workout!": 'Das war das ganze Training!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Alle Übungen geschafft — stark! Schliesse ab oder mach weiter und füge eine Übung hinzu.',
'Finish workout': 'Training beenden',
'Continue workout': 'Weitertrainieren',
'Keep going — tap “+ Add exercise” below': 'Weiter so — tippe unten auf „+ Übung hinzufügen“',
'Workout complete!': 'Training abgeschlossen!',
@@ -173,11 +179,11 @@ export default {
'Add set': 'Satz hinzufügen',
'+ Drop': '+ Dropsatz',
'+ Burst': '+ Burst',
'Drop {0}': 'Dropsatz {0}',
'Burst {0}': 'Burst {0}',
'Remove drop': 'Dropsatz entfernen',
'Remove burst': 'Burst entfernen',
'Rest (s)': 'Pause (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Pause nach jedem Satz dieser Übung. Auf 0 lassen, um den Standard-Pausen-Timer zu nutzen.',
'Drop-set / rest-pause': 'Dropsatz / Rest-Pause',
'Intensifier': 'Intensivierungstechnik',
'None': 'Keine',
@@ -230,7 +236,6 @@ export default {
// --- plan view ---
'Your weekly routine': 'Deine Wochenroutine',
'Week schedule': 'Wochenplan',
'Routines': 'Routinen',
'No routines yet.': 'Noch keine Routinen.',
'Create one or load the starter plan.': 'Erstelle eine oder lade den Starterplan.',
'Load starter plan (Push / Pull / Legs)': 'Starterplan laden (Push / Pull / Beine)',
@@ -297,8 +302,10 @@ export default {
'Keep screen awake': 'Bildschirm anlassen',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Der Bildschirm bleibt an, solange ein Workout läuft — so musst du zwischen den Sätzen nicht entsperren.',
'Weight unit': 'Gewichtseinheit',
'Week starts on': 'Woche beginnt am',
'Rest timer': 'Pausen-Timer',
'Sounds': 'Töne',
'Flash screen when timer ends': 'Bildschirm bei Timer-Ende blinken lassen',
'Note: switching units only changes the label — logged numbers are not converted.': 'Hinweis: Der Einheitenwechsel ändert nur die Beschriftung — eingetragene Zahlen werden nicht umgerechnet.',
'Data': 'Daten',
'Export backup (JSON)': 'Backup exportieren (JSON)',
@@ -404,6 +411,10 @@ export default {
'Remove from routine': 'Aus Routine entfernen',
'Minimize': 'Verkleinern',
'Expand': 'Vergrössern',
'Exercise animations': 'Übungs-Animationen',
'Full': 'Gross',
'Small': 'Klein',
'Hidden': 'Versteckt',
'Invite code': 'Einladungscode',
'This app is invite-only — enter the code you were given.': 'Diese App ist nur mit Einladung — gib den Code ein, den du erhalten hast.',
'An invite code is required': 'Ein Einladungscode ist erforderlich',
@@ -470,6 +481,32 @@ export default {
'That file is empty': 'Diese Datei ist leer',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Die Spalten dieser Datei sind unbekannt — unterstützte Apps stehen in der Doku.',
'Nothing to import from that file': 'Aus dieser Datei gibt es nichts zu importieren',
// --- import from Hevy API ---
'Import from Hevy': 'Aus Hevy importieren',
'Pull your history with a Hevy Pro API key': 'Verlauf mit einem Hevy-Pro-API-Schlüssel holen',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Verlauf mit einem Hevy-Pro-API-Schlüssel holen. Der Schlüssel gilt nur für diesen Import und wird nicht gespeichert.',
'Hevy API key': 'Hevy-API-Schlüssel',
'Get your API key': 'API-Schlüssel holen',
'Hevy → Settings → Developer': 'Hevy → Einstellungen → Developer',
'Paste your Hevy API key first': 'Zuerst den Hevy-API-Schlüssel einfügen',
'Fetch from Hevy': 'Von Hevy laden',
'Fetching from Hevy…': 'Wird von Hevy geladen…',
'Fetching exercises… ({0}/{1})': 'Übungen werden geladen… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Trainings werden geladen… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Wiegungen werden geladen… ({0}/{1})',
'Matching exercises…': 'Übungen werden zugeordnet…',
'Could not reach Hevy — check the key and try again': 'Hevy nicht erreichbar — Schlüssel prüfen und erneut versuchen',
'That Hevy API key was refused': 'Dieser Hevy-API-Schlüssel wurde abgelehnt',
'Nothing to import from Hevy': 'Von Hevy gibt es nichts zu importieren',
'Import workouts': 'Trainings importieren',
'Import routines': 'Routinen importieren',
'Import weigh-ins': 'Wiegungen importieren',
'{0} new · {1} days already here': '{0} neu · {1} Tage schon vorhanden',
'{0} routines · {1} exercises — added as new plans': '{0} Routinen · {1} Übungen — als neue Pläne hinzugefügt',
'{0} routines imported': '{0} Routinen importiert',
'Fetching routines… ({0}/{1})': 'Routinen werden geladen… ({0}/{1})',
'Routines': 'Routinen',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy speichert Gewichte in kg — sie werden nach {0} umgerechnet.',
// --- mobile build ---
'Your data': 'Deine Daten',
'All data stays on this phone': 'Alle Daten bleiben auf diesem Handy',
@@ -537,7 +574,11 @@ export default {
'Step ({0})': 'Schritt ({0})',
'Step (seconds)': 'Schritt (Sekunden)',
'Reps from': 'Wdh. ab',
'Reps up to': 'Wdh. bis',
'No automatic progression': 'Keine automatische Progression',
'Exclude from automatic progression': 'Von der automatischen Progression ausschließen',
'Use for planned deloads. Workouts stay in history and statistics.': 'Für geplante Deloads. Workouts bleiben im Verlauf und in den Statistiken.',
'The next regular target continues from the last included workout.': 'Das nächste reguläre Ziel setzt beim letzten einbezogenen Workout fort.',
'Linear progression': 'Lineare Progression',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Doppelte Progression',
@@ -877,7 +918,6 @@ export default {
'Avoid: {0}': 'Vermeiden: {0}',
'Before we start': 'Bevor wir loslegen',
'Building your plan…': 'Dein Plan wird erstellt…',
'Continue': 'Weiter',
'Discarded. Tell me what was off and I will build a different one.': 'Verworfen. Sag mir, was nicht gepasst hat, und ich baue einen anderen.',
'Done — your plan is back to how it was before my last changes.': 'Erledigt — dein Plan ist wieder wie vor meinen letzten Änderungen.',
'Edit my answers': 'Meine Antworten bearbeiten',
@@ -1037,6 +1077,20 @@ export default {
'What should change?': 'Was soll anders sein?',
'Coach is thinking…': 'Coach denkt nach…',
'Message the Coach…': 'Nachricht an den Coach…',
'Open progression settings': 'Progressions-Einstellungen öffnen',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy drosselt die Anfragen — eine Minute warten und erneut versuchen',
// --- log a past workout ---
'Log a past workout': 'Vergangenes Training eintragen',
'Logged on the usual workout screen, without timers.': 'Wird auf dem normalen Trainingsbildschirm erfasst, nur ohne Timer.',
'Date': 'Datum',
'Start time': 'Startzeit',
'Continue': 'Weiter',
'Pick a day up to today': 'Wähle einen Tag bis heute',
'There is already a workout on that day.': 'An diesem Tag gibt es bereits ein Training.',
'Replace': 'Ersetzen',
'Add as second workout': 'Als zweites Training hinzufügen',
'Finish the current workout first.': 'Beende zuerst das laufende Training.',
'Logging a past workout — no rest timers.': 'Vergangenes Training — keine Pausen-Timer.',
// --- bar weight (plate math) ---
'Bar weight': 'Stangengewicht',
'Bar ({0})': 'Stange ({0})',
+59 -5
View File
@@ -4,7 +4,6 @@ export default {
'Cancel': 'Cancelar',
'Press back again to exit': 'Pulsa atrás otra vez para salir',
'Delete': 'Eliminar',
'Save': 'Guardar',
'Import': 'Importar',
'Discard': 'Descartar',
'All': 'Todo',
@@ -35,6 +34,8 @@ export default {
'rescheduled': 'reprogramado',
'Prev': 'Anterior',
'Next': 'Siguiente',
'Move up': 'Subir',
'Move down': 'Bajar',
'Sunday': 'Domingo', 'Monday': 'Lunes', 'Tuesday': 'Martes', 'Wednesday': 'Miércoles',
'Thursday': 'Jueves', 'Friday': 'Viernes', 'Saturday': 'Sábado',
'Su': 'Do', 'Mo': 'Lu', 'Tu': 'Ma', 'We': 'Mi', 'Th': 'Ju', 'Fr': 'Vi', 'Sa': 'Sá',
@@ -91,6 +92,12 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Añadir a la rutina',
'Remove exercise': 'Quitar ejercicio',
'Swap exercise': 'Cambiar ejercicio',
'Swap exercise?': '¿Cambiar ejercicio?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Las series registradas permanecen con el ejercicio original. Elige dónde colocar el reemplazo.',
'Keep replacement in this group': 'Mantener el reemplazo en este grupo',
'Insert after this group': 'Insertar después de este grupo',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Las series registradas permanecen con el ejercicio original. El reemplazo se insertará después.',
'Remove {0}?': '¿Quitar {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Se perderán las series que registraste para este ejercicio en esta sesión.',
'This removes the exercise from your current session.': 'Esto quita el ejercicio de tu sesión actual.',
@@ -131,7 +138,6 @@ export default {
'Tracked — next time starts at {0}': 'Registrado — la próxima vez empiezas en {0}',
"That's the whole workout!": '¡Ese era todo el entrenamiento!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Todos los ejercicios hechos — ¡buen trabajo! Termina, o sigue y añade otro ejercicio.',
'Finish workout': 'Terminar entrenamiento',
'Continue workout': 'Continuar entrenamiento',
'Keep going — tap “+ Add exercise” below': 'Sigue así — toca «+ Añadir ejercicio» abajo',
'Workout complete!': '¡Entrenamiento completado!',
@@ -166,11 +172,11 @@ export default {
'Add set': 'Añadir serie',
'+ Drop': '+ Bajada',
'+ Burst': '+ Ráfaga',
'Drop {0}': 'Bajada {0}',
'Burst {0}': 'Ráfaga {0}',
'Remove drop': 'Quitar bajada',
'Remove burst': 'Quitar ráfaga',
'Rest (s)': 'Descanso (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Descanso tras cada serie de este ejercicio. Déjalo en 0 para usar tu temporizador de descanso por defecto.',
'Drop-set / rest-pause': 'Series descendentes / rest-pause',
'Intensifier': 'Intensificador',
'None': 'Ninguno',
@@ -220,7 +226,6 @@ export default {
'No data yet': 'Aún sin datos',
'Your weekly routine': 'Tu rutina semanal',
'Week schedule': 'Horario semanal',
'Routines': 'Rutinas',
'No routines yet.': 'Aún no hay rutinas.',
'Create one or load the starter plan.': 'Crea una o carga el plan inicial.',
'Load starter plan (Push / Pull / Legs)': 'Cargar plan inicial (Push / Pull / Piernas)',
@@ -283,8 +288,10 @@ export default {
'Keep screen awake': 'Mantener la pantalla encendida',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'La pantalla se mantiene encendida mientras hay un entrenamiento en curso, así no tienes que desbloquear el móvil entre series.',
'Weight unit': 'Unidad de peso',
'Week starts on': 'La semana empieza el',
'Rest timer': 'Temporizador de descanso',
'Sounds': 'Sonidos',
'Flash screen when timer ends': 'Hacer parpadear la pantalla al finalizar el temporizador',
'Note: switching units only changes the label — logged numbers are not converted.': 'Nota: cambiar la unidad solo cambia la etiqueta — los números registrados no se convierten.',
'Data': 'Datos',
'Export backup (JSON)': 'Exportar copia (JSON)',
@@ -386,6 +393,10 @@ export default {
'Remove from routine': 'Quitar de la rutina',
'Minimize': 'Minimizar',
'Expand': 'Ampliar',
'Exercise animations': 'Animaciones de los ejercicios',
'Full': 'Completa',
'Small': 'Pequeña',
'Hidden': 'Oculta',
'Invite code': 'Código de invitación',
'This app is invite-only — enter the code you were given.': 'Esta app es solo por invitación: introduce el código que te dieron.',
'An invite code is required': 'Se requiere un código de invitación',
@@ -452,6 +463,32 @@ export default {
'That file is empty': 'Ese archivo está vacío',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'No se reconocen las columnas del archivo — consulta la documentación.',
'Nothing to import from that file': 'No hay nada que importar de ese archivo',
// --- import from Hevy API ---
'Import from Hevy': 'Importar desde Hevy',
'Pull your history with a Hevy Pro API key': 'Trae tu historial con una clave API de Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Trae tu historial con una clave API de Hevy Pro. La clave solo se usa en esta importación y no se guarda.',
'Hevy API key': 'Clave API de Hevy',
'Get your API key': 'Obtener tu clave API',
'Hevy → Settings → Developer': 'Hevy → Ajustes → Developer',
'Paste your Hevy API key first': 'Pega primero tu clave API de Hevy',
'Fetch from Hevy': 'Cargar desde Hevy',
'Fetching from Hevy…': 'Cargando desde Hevy…',
'Fetching exercises… ({0}/{1})': 'Cargando ejercicios… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Cargando entrenamientos… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Cargando pesajes… ({0}/{1})',
'Matching exercises…': 'Emparejando ejercicios…',
'Could not reach Hevy — check the key and try again': 'No se pudo contactar con Hevy — revisa la clave e inténtalo de nuevo',
'That Hevy API key was refused': 'Esa clave API de Hevy fue rechazada',
'Nothing to import from Hevy': 'No hay nada que importar desde Hevy',
'Import workouts': 'Importar entrenamientos',
'Import routines': 'Importar rutinas',
'{0} routines · {1} exercises — added as new plans': '{0} rutinas · {1} ejercicios — se añaden como planes nuevos',
'{0} routines imported': '{0} rutinas importadas',
'Fetching routines… ({0}/{1})': 'Cargando rutinas… ({0}/{1})',
'Routines': 'Rutinas',
'Import weigh-ins': 'Importar pesajes',
'{0} new · {1} days already here': '{0} nuevos · {1} días ya están',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy guarda los pesos en kg — se convertirán a {0}.',
// --- mobile build ---
'Your data': 'Tus datos',
'All data stays on this phone': 'Todos los datos se quedan en este teléfono',
@@ -519,7 +556,11 @@ export default {
'Step ({0})': 'Incremento ({0})',
'Step (seconds)': 'Incremento (segundos)',
'Reps from': 'Reps desde',
'Reps up to': 'Reps hasta',
'No automatic progression': 'Sin progresión automática',
'Exclude from automatic progression': 'Excluir de la progresión automática',
'Use for planned deloads. Workouts stay in history and statistics.': 'Úsalo para descargas planificadas. Los entrenamientos permanecen en el historial y las estadísticas.',
'The next regular target continues from the last included workout.': 'El siguiente objetivo normal continúa desde el último entrenamiento incluido.',
'Linear progression': 'Progresión lineal',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Progresión doble',
@@ -860,7 +901,6 @@ export default {
'Avoid: {0}': 'Evitar: {0}',
'Before we start': 'Antes de empezar',
'Building your plan…': 'Creando tu plan…',
'Continue': 'Continuar',
'Discarded. Tell me what was off and I will build a different one.': 'Descartado. Dime qué no encajaba y haré otro distinto.',
'Done — your plan is back to how it was before my last changes.': 'Hecho: tu plan vuelve a estar como antes de mis últimos cambios.',
'Edit my answers': 'Editar mis respuestas',
@@ -1018,6 +1058,20 @@ export default {
'What should change?': '¿Qué debería cambiar?',
'Coach is thinking…': 'El Coach está pensando…',
'Message the Coach…': 'Escribe al Coach…',
'Open progression settings': 'Abrir ajustes de progresión',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy está limitando las solicitudes: espera un minuto y vuelve a intentarlo',
// --- log a past workout ---
'Log a past workout': 'Registrar un entrenamiento pasado',
'Logged on the usual workout screen, without timers.': 'Se registra en la pantalla de entrenamiento habitual, sin temporizadores.',
'Date': 'Fecha',
'Start time': 'Hora de inicio',
'Continue': 'Continuar',
'Pick a day up to today': 'Elige un día hasta hoy',
'There is already a workout on that day.': 'Ya hay un entrenamiento ese día.',
'Replace': 'Reemplazar',
'Add as second workout': 'Añadir como segundo entrenamiento',
'Finish the current workout first.': 'Termina primero el entrenamiento actual.',
'Logging a past workout — no rest timers.': 'Registrando un entrenamiento pasado — sin temporizadores de descanso.',
// --- bar weight (plate math) ---
'Bar weight': 'Peso de la barra',
'Bar ({0})': 'Barra ({0})',
+59 -5
View File
@@ -4,7 +4,6 @@ export default {
'Cancel': 'Annuler',
'Press back again to exit': 'Appuyez de nouveau pour quitter',
'Delete': 'Supprimer',
'Save': 'Enregistrer',
'Import': 'Importer',
'Discard': 'Abandonner',
'All': 'Tout',
@@ -35,6 +34,8 @@ export default {
'rescheduled': 'reprogrammé',
'Prev': 'Préc.',
'Next': 'Suiv.',
'Move up': 'Monter',
'Move down': 'Descendre',
'Sunday': 'Dimanche', 'Monday': 'Lundi', 'Tuesday': 'Mardi', 'Wednesday': 'Mercredi',
'Thursday': 'Jeudi', 'Friday': 'Vendredi', 'Saturday': 'Samedi',
'Su': 'Di', 'Mo': 'Lu', 'Tu': 'Ma', 'We': 'Me', 'Th': 'Je', 'Fr': 'Ve', 'Sa': 'Sa',
@@ -91,6 +92,12 @@ export default {
'Weight ({0})': 'Poids ({0})',
'Add to routine': 'Ajouter à la routine',
'Remove exercise': "Retirer l'exercice",
'Swap exercise': 'Remplacer l’exercice',
'Swap exercise?': 'Remplacer l’exercice ?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Les séries enregistrées restent avec l’exercice d’origine. Choisis où placer le remplacement.',
'Keep replacement in this group': 'Garder le remplacement dans ce groupe',
'Insert after this group': 'Insérer après ce groupe',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Les séries enregistrées restent avec l’exercice d’origine. Le remplacement sera inséré après.',
'Remove {0}?': 'Retirer {0} ?',
'The sets you logged for this exercise in this session will be lost.': 'Les séries enregistrées pour cet exercice pendant cette séance seront perdues.',
'This removes the exercise from your current session.': 'Cela retire l’exercice de ta séance actuelle.',
@@ -131,7 +138,6 @@ export default {
'Tracked — next time starts at {0}': 'Noté — la prochaine fois tu démarres à {0}',
"That's the whole workout!": 'C’était toute la séance !',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Tous les exercices faits — bravo ! Termine, ou continue et ajoute un exercice.',
'Finish workout': 'Terminer la séance',
'Continue workout': 'Continuer la séance',
'Keep going — tap “+ Add exercise” below': 'Continue — tape « + Ajouter un exercice » en bas',
'Workout complete!': 'Séance terminée !',
@@ -166,11 +172,11 @@ export default {
'Add set': 'Ajouter une série',
'+ Drop': '+ Drop set',
'+ Burst': '+ Rafale',
'Drop {0}': 'Drop set {0}',
'Burst {0}': 'Rafale {0}',
'Remove drop': 'Retirer le drop set',
'Remove burst': 'Retirer la rafale',
'Rest (s)': 'Repos (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Repos après chaque série de cet exercice. Laisse à 0 pour utiliser ton minuteur de repos par défaut.',
'Drop-set / rest-pause': 'Drop-set / rest-pause',
'Intensifier': 'Intensificateur',
'None': 'Aucun',
@@ -220,7 +226,6 @@ export default {
'No data yet': 'Pas encore de données',
'Your weekly routine': 'Ta routine hebdomadaire',
'Week schedule': 'Planning de la semaine',
'Routines': 'Routines',
'No routines yet.': 'Aucune routine pour l’instant.',
'Create one or load the starter plan.': 'Crées-en une ou charge le plan de départ.',
'Load starter plan (Push / Pull / Legs)': 'Charger le plan de départ (Push / Pull / Jambes)',
@@ -283,8 +288,10 @@ export default {
'Keep screen awake': 'Garder l’écran allumé',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'L’écran reste allumé tant qu’une séance est en cours, pas besoin de déverrouiller ton téléphone entre les séries.',
'Weight unit': 'Unité de poids',
'Week starts on': 'La semaine commence le',
'Rest timer': 'Minuteur de repos',
'Sounds': 'Sons',
'Flash screen when timer ends': 'Faire clignoter l’écran à la fin du minuteur',
'Note: switching units only changes the label — logged numbers are not converted.': 'Note : changer d’unité ne change que l’étiquette — les nombres enregistrés ne sont pas convertis.',
'Data': 'Données',
'Export backup (JSON)': 'Exporter une sauvegarde (JSON)',
@@ -386,6 +393,10 @@ export default {
'Remove from routine': 'Retirer de la routine',
'Minimize': 'Réduire',
'Expand': 'Agrandir',
'Exercise animations': 'Animations des exercices',
'Full': 'Grande',
'Small': 'Petite',
'Hidden': 'Masquée',
'Invite code': 'Code d’invitation',
'This app is invite-only — enter the code you were given.': 'Cette appli est sur invitation — saisissez le code qu’on vous a donné.',
'An invite code is required': 'Un code d’invitation est requis',
@@ -452,6 +463,32 @@ export default {
'That file is empty': 'Ce fichier est vide',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colonnes non reconnues — voir la documentation pour les apps prises en charge.',
'Nothing to import from that file': 'Rien à importer depuis ce fichier',
// --- import from Hevy API ---
'Import from Hevy': 'Importer depuis Hevy',
'Pull your history with a Hevy Pro API key': 'Récupérer l’historique avec une clé API Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Récupérer l’historique avec une clé API Hevy Pro. La clé ne sert qu’à cet import et n’est pas enregistrée.',
'Hevy API key': 'Clé API Hevy',
'Get your API key': 'Obtenir votre clé API',
'Hevy → Settings → Developer': 'Hevy → Réglages → Developer',
'Paste your Hevy API key first': 'Collez d’abord votre clé API Hevy',
'Fetch from Hevy': 'Charger depuis Hevy',
'Fetching from Hevy…': 'Chargement depuis Hevy…',
'Fetching exercises… ({0}/{1})': 'Chargement des exercices… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Chargement des séances… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Chargement des pesées… ({0}/{1})',
'Matching exercises…': 'Association des exercices…',
'Could not reach Hevy — check the key and try again': 'Impossible de joindre Hevy — vérifiez la clé et réessayez',
'That Hevy API key was refused': 'Cette clé API Hevy a été refusée',
'Nothing to import from Hevy': 'Rien à importer depuis Hevy',
'Import workouts': 'Importer les séances',
'Import routines': 'Importer les routines',
'{0} routines · {1} exercises — added as new plans': '{0} routines · {1} exercices — ajoutées comme nouveaux plans',
'{0} routines imported': '{0} routines importées',
'Fetching routines… ({0}/{1})': 'Chargement des routines… ({0}/{1})',
'Routines': 'Routines',
'Import weigh-ins': 'Importer les pesées',
'{0} new · {1} days already here': '{0} nouveaux · {1} jours déjà présents',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy enregistre les poids en kg — ils seront convertis en {0}.',
// --- mobile build ---
'Your data': 'Vos données',
'All data stays on this phone': 'Toutes les données restent sur ce téléphone',
@@ -519,7 +556,11 @@ export default {
'Step ({0})': 'Palier ({0})',
'Step (seconds)': 'Palier (secondes)',
'Reps from': 'Reps à partir de',
'Reps up to': 'Reps jusqu’à',
'No automatic progression': 'Pas de progression automatique',
'Exclude from automatic progression': 'Exclure de la progression automatique',
'Use for planned deloads. Workouts stay in history and statistics.': 'À utiliser pour les semaines de décharge planifiées. Les séances restent dans l’historique et les statistiques.',
'The next regular target continues from the last included workout.': 'Le prochain objectif normal continue à partir de la dernière séance incluse.',
'Linear progression': 'Progression linéaire',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Double progression',
@@ -860,7 +901,6 @@ export default {
'Avoid: {0}': 'À éviter : {0}',
'Before we start': 'Avant de commencer',
'Building your plan…': 'Création de ton plan…',
'Continue': 'Continuer',
'Discarded. Tell me what was off and I will build a different one.': 'Abandonné. Dis-moi ce qui n’allait pas et j’en construis un autre.',
'Done — your plan is back to how it was before my last changes.': 'C’est fait — ton plan est revenu à l’état d’avant mes dernières modifications.',
'Edit my answers': 'Modifier mes réponses',
@@ -1018,6 +1058,20 @@ export default {
'What should change?': 'Que faut-il changer ?',
'Coach is thinking…': 'Le Coach réfléchit…',
'Message the Coach…': 'Écrire au Coach…',
'Open progression settings': 'Ouvrir les réglages de progression',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy limite les requêtes — attendez une minute puis réessayez',
// --- log a past workout ---
'Log a past workout': 'Enregistrer une séance passée',
'Logged on the usual workout screen, without timers.': 'Saisie sur l’écran d’entraînement habituel, sans minuteurs.',
'Date': 'Date',
'Start time': 'Heure de début',
'Continue': 'Continuer',
'Pick a day up to today': 'Choisis un jour jusqu’à aujourd’hui',
'There is already a workout on that day.': 'Il y a déjà une séance ce jour-là.',
'Replace': 'Remplacer',
'Add as second workout': 'Ajouter comme deuxième séance',
'Finish the current workout first.': 'Termine d’abord la séance en cours.',
'Logging a past workout — no rest timers.': 'Séance passée — pas de minuteurs de repos.',
// --- bar weight (plate math) ---
'Bar weight': 'Poids de la barre',
'Bar ({0})': 'Barre ({0})',
+59 -5
View File
@@ -4,7 +4,6 @@ export default {
'Cancel': 'रद्द करें',
'Press back again to exit': 'बाहर निकलने के लिए फिर से बैक दबाएँ',
'Delete': 'हटाएँ',
'Save': 'सहेजें',
'Import': 'आयात करें',
'Discard': 'छोड़ें',
'All': 'सभी',
@@ -35,6 +34,8 @@ export default {
'rescheduled': 'बदला गया',
'Prev': 'पिछला',
'Next': 'अगला',
'Move up': 'ऊपर ले जाएँ',
'Move down': 'नीचे ले जाएँ',
'Sunday': 'रविवार', 'Monday': 'सोमवार', 'Tuesday': 'मंगलवार', 'Wednesday': 'बुधवार',
'Thursday': 'गुरुवार', 'Friday': 'शुक्रवार', 'Saturday': 'शनिवार',
'Su': 'र', 'Mo': 'सो', 'Tu': 'मं', 'We': 'बु', 'Th': 'गु', 'Fr': 'शु', 'Sa': 'श',
@@ -91,6 +92,12 @@ export default {
'Weight ({0})': 'वज़न ({0})',
'Add to routine': 'रूटीन में जोड़ें',
'Remove exercise': 'व्यायाम हटाएँ',
'Swap exercise': 'व्यायाम बदलें',
'Swap exercise?': 'एक्सरसाइज़ बदलें?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'रिकॉर्ड किए गए सेट मूल एक्सरसाइज़ के साथ रहेंगे। बदलने वाली एक्सरसाइज़ की जगह चुनें।',
'Keep replacement in this group': 'बदलने वाली एक्सरसाइज़ इसी समूह में रखें',
'Insert after this group': 'इस समूह के बाद जोड़ें',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'रिकॉर्ड किए गए सेट मूल एक्सरसाइज़ के साथ रहेंगे। बदलने वाली एक्सरसाइज़ बाद में जोड़ी जाएगी।',
'Remove {0}?': '{0} हटाएँ?',
'The sets you logged for this exercise in this session will be lost.': 'इस सत्र में इस व्यायाम के लिए लॉग किए गए सेट मिट जाएँगे।',
'This removes the exercise from your current session.': 'यह व्यायाम आपके मौजूदा सत्र से हट जाएगा।',
@@ -131,7 +138,6 @@ export default {
'Tracked — next time starts at {0}': 'दर्ज हुआ — अगली बार {0} से शुरू होगा',
"That's the whole workout!": 'पूरा वर्कआउट हो गया!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'सारे व्यायाम पूरे — बढ़िया काम! समाप्त करें, या जारी रखें और एक और व्यायाम जोड़ें।',
'Finish workout': 'वर्कआउट समाप्त करें',
'Continue workout': 'वर्कआउट जारी रखें',
'Keep going — tap “+ Add exercise” below': 'जारी रखें — नीचे "+ व्यायाम जोड़ें" पर टैप करें',
'Workout complete!': 'वर्कआउट पूरा!',
@@ -166,11 +172,11 @@ export default {
'Add set': 'सेट जोड़ें',
'+ Drop': '+ ड्रॉप सेट',
'+ Burst': '+ बर्स्ट',
'Drop {0}': 'ड्रॉप सेट {0}',
'Burst {0}': 'बर्स्ट {0}',
'Remove drop': 'ड्रॉप सेट हटाएं',
'Remove burst': 'बर्स्ट हटाएं',
'Rest (s)': 'आराम (सेकंड)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'इस एक्सरसाइज़ के हर सेट के बाद आराम। अपना डिफ़ॉल्ट आराम टाइमर इस्तेमाल करने के लिए इसे 0 रहने दें।',
'Drop-set / rest-pause': 'ड्रॉप सेट / रेस्ट-पॉज़',
'Intensifier': 'इंटेंसिफायर',
'None': 'कोई नहीं',
@@ -220,7 +226,6 @@ export default {
'No data yet': 'अभी डेटा नहीं',
'Your weekly routine': 'आपका साप्ताहिक रूटीन',
'Week schedule': 'हफ़्ते का कार्यक्रम',
'Routines': 'रूटीन',
'No routines yet.': 'अभी कोई रूटीन नहीं।',
'Create one or load the starter plan.': 'एक बनाएँ या स्टार्टर प्लान लोड करें।',
'Load starter plan (Push / Pull / Legs)': 'स्टार्टर प्लान लोड करें (पुश / पुल / लेग्स)',
@@ -283,8 +288,10 @@ export default {
'Keep screen awake': 'स्क्रीन चालू रखें',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'वर्कआउट चलने के दौरान स्क्रीन चालू रहती है, ताकि सेट के बीच फ़ोन अनलॉक न करना पड़े।',
'Weight unit': 'वज़न की इकाई',
'Week starts on': 'सप्ताह शुरू होता है',
'Rest timer': 'आराम टाइमर',
'Sounds': 'ध्वनियाँ',
'Flash screen when timer ends': 'टाइमर खत्म होने पर स्क्रीन फ्लैश करें',
'Note: switching units only changes the label — logged numbers are not converted.': 'नोट: इकाई बदलने से केवल लेबल बदलता है — दर्ज संख्याएँ परिवर्तित नहीं होतीं।',
'Data': 'डेटा',
'Export backup (JSON)': 'बैकअप निर्यात करें (JSON)',
@@ -386,6 +393,10 @@ export default {
'Remove from routine': 'रूटीन से हटाएं',
'Minimize': 'छोटा करें',
'Expand': 'बड़ा करें',
'Exercise animations': 'व्यायाम एनिमेशन',
'Full': 'पूर्ण',
'Small': 'छोटा',
'Hidden': 'छिपा',
'Invite code': 'इनवाइट कोड',
'This app is invite-only — enter the code you were given.': 'यह ऐप केवल इनवाइट से है — आपको दिया गया कोड डालें।',
'An invite code is required': 'एक इनवाइट कोड आवश्यक है',
@@ -452,6 +463,32 @@ export default {
'That file is empty': 'वह फ़ाइल खाली है',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'फ़ाइल के कॉलम पहचाने नहीं गए — समर्थित ऐप्स के लिए दस्तावेज़ देखें।',
'Nothing to import from that file': 'उस फ़ाइल से आयात करने को कुछ नहीं',
// --- import from Hevy API ---
'Import from Hevy': 'Hevy से आयात करें',
'Pull your history with a Hevy Pro API key': 'Hevy Pro API कुंजी से अपना इतिहास लाएँ',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Hevy Pro API कुंजी से अपना इतिहास लाएँ। कुंजी केवल इस आयात के लिए उपयोग होती है और सहेजी नहीं जाती।',
'Hevy API key': 'Hevy API कुंजी',
'Get your API key': 'अपनी API कुंजी लें',
'Hevy → Settings → Developer': 'Hevy → सेटिंग्स → Developer',
'Paste your Hevy API key first': 'पहले अपनी Hevy API कुंजी चिपकाएँ',
'Fetch from Hevy': 'Hevy से लाएँ',
'Fetching from Hevy…': 'Hevy से लाया जा रहा है…',
'Fetching exercises… ({0}/{1})': 'व्यायाम लाए जा रहे हैं… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'वर्कआउट लाए जा रहे हैं… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'वज़न लाए जा रहे हैं… ({0}/{1})',
'Matching exercises…': 'व्यायाम मिलाए जा रहे हैं…',
'Could not reach Hevy — check the key and try again': 'Hevy से संपर्क नहीं हो सका — कुंजी जाँचकर फिर कोशिश करें',
'That Hevy API key was refused': 'वह Hevy API कुंजी अस्वीकार कर दी गई',
'Nothing to import from Hevy': 'Hevy से आयात करने के लिए कुछ नहीं',
'Import workouts': 'वर्कआउट आयात करें',
'Import routines': 'रूटीन आयात करें',
'{0} routines · {1} exercises — added as new plans': '{0} रूटीन · {1} व्यायाम — नए प्लान के रूप में जोड़े जाते हैं',
'{0} routines imported': '{0} रूटीन आयात किए गए',
'Fetching routines… ({0}/{1})': 'रूटीन लाए जा रहे हैं… ({0}/{1})',
'Routines': 'रूटीन',
'Import weigh-ins': 'वज़न आयात करें',
'{0} new · {1} days already here': '{0} नए · {1} दिन पहले से मौजूद',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy वज़न kg में रखता है — उन्हें {0} में बदला जाएगा।',
// --- mobile build ---
'Your data': 'आपका डेटा',
'All data stays on this phone': 'सारा डेटा इसी फ़ोन पर रहता है',
@@ -519,7 +556,11 @@ export default {
'Step ({0})': 'स्टेप ({0})',
'Step (seconds)': 'स्टेप (सेकंड)',
'Reps from': 'रेप्स से',
'Reps up to': 'रेप्स तक',
'No automatic progression': 'कोई स्वचालित प्रोग्रेशन नहीं',
'Exclude from automatic progression': 'स्वचालित प्रोग्रेशन से बाहर रखें',
'Use for planned deloads. Workouts stay in history and statistics.': 'योजनाबद्ध डीलोड के लिए उपयोग करें। वर्कआउट इतिहास और आँकड़ों में रहते हैं।',
'The next regular target continues from the last included workout.': 'अगला सामान्य लक्ष्य अंतिम शामिल वर्कआउट से जारी रहता है।',
'Linear progression': 'रैखिक प्रोग्रेशन',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'डबल प्रोग्रेशन',
@@ -860,7 +901,6 @@ export default {
'Avoid: {0}': 'बचें: {0}',
'Before we start': 'शुरू करने से पहले',
'Building your plan…': 'आपकी योजना बन रही है…',
'Continue': 'जारी रखें',
'Discarded. Tell me what was off and I will build a different one.': 'हटा दिया। बताएँ क्या ठीक नहीं था, मैं दूसरी बना दूँगा।',
'Done — your plan is back to how it was before my last changes.': 'हो गया — आपकी योजना मेरे पिछले बदलावों से पहले जैसी हो गई।',
'Edit my answers': 'मेरे उत्तर संपादित करें',
@@ -1018,6 +1058,20 @@ export default {
'What should change?': 'क्या बदलना चाहिए?',
'Coach is thinking…': 'कोच सोच रहा है…',
'Message the Coach…': 'कोच को संदेश…',
'Open progression settings': 'प्रगति सेटिंग्स खोलें',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy अनुरोधों को सीमित कर रहा है — एक मिनट रुकें और फिर से कोशिश करें',
// --- log a past workout ---
'Log a past workout': 'पिछला वर्कआउट दर्ज करें',
'Logged on the usual workout screen, without timers.': 'सामान्य वर्कआउट स्क्रीन पर दर्ज होता है, बस टाइमर के बिना।',
'Date': 'तारीख',
'Start time': 'शुरू होने का समय',
'Continue': 'जारी रखें',
'Pick a day up to today': 'आज तक का कोई दिन चुनें',
'There is already a workout on that day.': 'उस दिन पहले से एक वर्कआउट है।',
'Replace': 'बदलें',
'Add as second workout': 'दूसरे वर्कआउट के रूप में जोड़ें',
'Finish the current workout first.': 'पहले मौजूदा वर्कआउट पूरा करें।',
'Logging a past workout — no rest timers.': 'पिछला वर्कआउट दर्ज हो रहा है — कोई रेस्ट टाइमर नहीं।',
// --- bar weight (plate math) ---
'Bar weight': 'बार का वज़न',
'Bar ({0})': 'बार ({0})',
File diff suppressed because it is too large. Load diff
+59 -5
View File
@@ -4,7 +4,6 @@ export default {
'Cancel': 'Annulla',
'Press back again to exit': 'Premi di nuovo indietro per uscire',
'Delete': 'Elimina',
'Save': 'Salva',
'Import': 'Importa',
'Discard': 'Scarta',
'All': 'Tutti',
@@ -35,6 +34,8 @@ export default {
'rescheduled': 'riprogrammato',
'Prev': 'Prec.',
'Next': 'Succ.',
'Move up': 'Sposta su',
'Move down': 'Sposta giù',
'Sunday': 'Domenica', 'Monday': 'Lunedì', 'Tuesday': 'Martedì', 'Wednesday': 'Mercoledì',
'Thursday': 'Giovedì', 'Friday': 'Venerdì', 'Saturday': 'Sabato',
'Su': 'Do', 'Mo': 'Lu', 'Tu': 'Ma', 'We': 'Me', 'Th': 'Gi', 'Fr': 'Ve', 'Sa': 'Sa',
@@ -91,6 +92,12 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Aggiungi alla routine',
'Remove exercise': 'Rimuovi esercizio',
'Swap exercise': 'Sostituisci esercizio',
'Swap exercise?': 'Sostituire l’esercizio?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Le serie registrate restano con l’esercizio originale. Scegli dove inserire il sostituto.',
'Keep replacement in this group': 'Mantieni il sostituto in questo gruppo',
'Insert after this group': 'Inserisci dopo questo gruppo',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Le serie registrate restano con l’esercizio originale. Il sostituto verrà inserito dopo.',
'Remove {0}?': 'Rimuovere {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Le serie registrate per questo esercizio in questa sessione andranno perse.',
'This removes the exercise from your current session.': 'Questo rimuove l’esercizio dalla sessione corrente.',
@@ -131,7 +138,6 @@ export default {
'Tracked — next time starts at {0}': 'Registrato — la prossima volta parti da {0}',
"That's the whole workout!": 'Allenamento completato!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Tutti gli esercizi fatti — ottimo lavoro! Concludi, o continua e aggiungi un altro esercizio.',
'Finish workout': 'Termina allenamento',
'Continue workout': 'Continua allenamento',
'Keep going — tap “+ Add exercise” below': 'Continua così — tocca «+ Aggiungi esercizio» in basso',
'Workout complete!': 'Allenamento completato!',
@@ -166,11 +172,11 @@ export default {
'Add set': 'Aggiungi serie',
'+ Drop': '+ Drop set',
'+ Burst': '+ Burst',
'Drop {0}': 'Drop set {0}',
'Burst {0}': 'Burst {0}',
'Remove drop': 'Rimuovi drop set',
'Remove burst': 'Rimuovi burst',
'Rest (s)': 'Recupero (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Recupero dopo ogni serie di questo esercizio. Lascialo a 0 per usare il timer di riposo predefinito.',
'Drop-set / rest-pause': 'Drop-set / rest-pause',
'Intensifier': 'Intensificatore',
'None': 'Nessuno',
@@ -220,7 +226,6 @@ export default {
'No data yet': 'Ancora nessun dato',
'Your weekly routine': 'La tua routine settimanale',
'Week schedule': 'Programma settimanale',
'Routines': 'Routine',
'No routines yet.': 'Ancora nessuna routine.',
'Create one or load the starter plan.': 'Creane una o carica il piano iniziale.',
'Load starter plan (Push / Pull / Legs)': 'Carica piano iniziale (Push / Pull / Gambe)',
@@ -283,8 +288,10 @@ export default {
'Keep screen awake': 'Mantieni lo schermo acceso',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Lo schermo resta acceso mentre un allenamento è in corso, così non devi sbloccare il telefono tra una serie e l’altra.',
'Weight unit': 'Unità di peso',
'Week starts on': 'La settimana inizia il',
'Rest timer': 'Timer di riposo',
'Sounds': 'Suoni',
'Flash screen when timer ends': 'Fai lampeggiare lo schermo alla fine del timer',
'Note: switching units only changes the label — logged numbers are not converted.': 'Nota: cambiare unità cambia solo l’etichetta — i numeri registrati non vengono convertiti.',
'Data': 'Dati',
'Export backup (JSON)': 'Esporta backup (JSON)',
@@ -386,6 +393,10 @@ export default {
'Remove from routine': 'Rimuovi dalla routine',
'Minimize': 'Riduci',
'Expand': 'Ingrandisci',
'Exercise animations': 'Animazioni degli esercizi',
'Full': 'Grande',
'Small': 'Piccola',
'Hidden': 'Nascosta',
'Invite code': 'Codice di invito',
'This app is invite-only — enter the code you were given.': 'Questa app è solo su invito: inserisci il codice che hai ricevuto.',
'An invite code is required': 'È richiesto un codice di invito',
@@ -452,6 +463,32 @@ export default {
'That file is empty': 'Il file è vuoto',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colonne non riconosciute — vedi la documentazione per le app supportate.',
'Nothing to import from that file': 'Niente da importare da questo file',
// --- import from Hevy API ---
'Import from Hevy': 'Importa da Hevy',
'Pull your history with a Hevy Pro API key': 'Importa lo storico con una chiave API Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Importa lo storico con una chiave API Hevy Pro. La chiave serve solo a questo import e non viene salvata.',
'Hevy API key': 'Chiave API Hevy',
'Get your API key': 'Ottieni la chiave API',
'Hevy → Settings → Developer': 'Hevy → Impostazioni → Developer',
'Paste your Hevy API key first': 'Incolla prima la chiave API Hevy',
'Fetch from Hevy': 'Scarica da Hevy',
'Fetching from Hevy…': 'Download da Hevy…',
'Fetching exercises… ({0}/{1})': 'Download esercizi… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Download allenamenti… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Download pesate… ({0}/{1})',
'Matching exercises…': 'Abbinamento esercizi…',
'Could not reach Hevy — check the key and try again': 'Impossibile contattare Hevy — controlla la chiave e riprova',
'That Hevy API key was refused': 'Questa chiave API Hevy è stata rifiutata',
'Nothing to import from Hevy': 'Niente da importare da Hevy',
'Import workouts': 'Importa allenamenti',
'Import routines': 'Importa routine',
'{0} routines · {1} exercises — added as new plans': '{0} routine · {1} esercizi — aggiunte come nuovi piani',
'{0} routines imported': '{0} routine importate',
'Fetching routines… ({0}/{1})': 'Download routine… ({0}/{1})',
'Routines': 'Routine',
'Import weigh-ins': 'Importa pesate',
'{0} new · {1} days already here': '{0} nuovi · {1} giorni già presenti',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy memorizza i pesi in kg — verranno convertiti in {0}.',
// --- mobile build ---
'Your data': 'I tuoi dati',
'All data stays on this phone': 'Tutti i dati restano su questo telefono',
@@ -519,7 +556,11 @@ export default {
'Step ({0})': 'Incremento ({0})',
'Step (seconds)': 'Incremento (secondi)',
'Reps from': 'Rip. da',
'Reps up to': 'Rip. fino a',
'No automatic progression': 'Nessuna progressione automatica',
'Exclude from automatic progression': 'Escludi dalla progressione automatica',
'Use for planned deloads. Workouts stay in history and statistics.': 'Usa per gli scarichi programmati. Gli allenamenti restano nella cronologia e nelle statistiche.',
'The next regular target continues from the last included workout.': 'Il prossimo obiettivo normale continua dall’ultimo allenamento incluso.',
'Linear progression': 'Progressione lineare',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Doppia progressione',
@@ -860,7 +901,6 @@ export default {
'Avoid: {0}': 'Da evitare: {0}',
'Before we start': 'Prima di iniziare',
'Building your plan…': 'Sto creando il tuo piano…',
'Continue': 'Continua',
'Discarded. Tell me what was off and I will build a different one.': 'Scartato. Dimmi cosa non andava e ne costruisco un altro.',
'Done — your plan is back to how it was before my last changes.': 'Fatto: il tuo piano è tornato com’era prima delle mie ultime modifiche.',
'Edit my answers': 'Modifica le mie risposte',
@@ -1018,6 +1058,20 @@ export default {
'What should change?': 'Cosa dovrebbe cambiare?',
'Coach is thinking…': 'Il Coach sta pensando…',
'Message the Coach…': 'Scrivi al Coach…',
'Open progression settings': 'Apri le impostazioni di progressione',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy sta limitando le richieste: attendi un minuto e riprova',
// --- log a past workout ---
'Log a past workout': 'Registra un allenamento passato',
'Logged on the usual workout screen, without timers.': 'Si registra nella solita schermata di allenamento, solo senza timer.',
'Date': 'Data',
'Start time': 'Ora di inizio',
'Continue': 'Continua',
'Pick a day up to today': 'Scegli un giorno fino a oggi',
'There is already a workout on that day.': 'C’è già un allenamento quel giorno.',
'Replace': 'Sostituisci',
'Add as second workout': 'Aggiungi come secondo allenamento',
'Finish the current workout first.': 'Termina prima l’allenamento in corso.',
'Logging a past workout — no rest timers.': 'Allenamento passato — nessun timer di recupero.',
// --- bar weight (plate math) ---
'Bar weight': 'Peso del bilanciere',
'Bar ({0})': 'Bilanciere ({0})',
+59 -5
View File
@@ -4,7 +4,6 @@ export default {
'Cancel': '취소',
'Press back again to exit': '뒤로를 한 번 더 누르면 종료됩니다',
'Delete': '삭제',
'Save': '저장',
'Import': '가져오기',
'Discard': '버리기',
'All': '전체',
@@ -35,6 +34,8 @@ export default {
'rescheduled': '변경됨',
'Prev': '이전',
'Next': '다음',
'Move up': '위로 이동',
'Move down': '아래로 이동',
'Sunday': '일요일', 'Monday': '월요일', 'Tuesday': '화요일', 'Wednesday': '수요일',
'Thursday': '목요일', 'Friday': '금요일', 'Saturday': '토요일',
'Su': '일', 'Mo': '월', 'Tu': '화', 'We': '수', 'Th': '목', 'Fr': '금', 'Sa': '토',
@@ -91,6 +92,12 @@ export default {
'Weight ({0})': '무게 ({0})',
'Add to routine': '루틴에 추가',
'Remove exercise': '운동 제거',
'Swap exercise': '운동 바꾸기',
'Swap exercise?': '운동을 바꿀까요?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': '기록한 세트는 원래 운동에 남습니다. 대체 운동을 넣을 위치를 선택하세요.',
'Keep replacement in this group': '대체 운동을 이 그룹에 유지',
'Insert after this group': '이 그룹 뒤에 삽입',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': '기록한 세트는 원래 운동에 남습니다. 대체 운동은 뒤에 삽입됩니다.',
'Remove {0}?': '{0}을(를) 제거할까요?',
'The sets you logged for this exercise in this session will be lost.': '이 세션에서 이 운동에 기록한 세트가 사라집니다.',
'This removes the exercise from your current session.': '현재 세션에서 이 운동을 제거합니다.',
@@ -131,7 +138,6 @@ export default {
'Tracked — next time starts at {0}': '기록됨 — 다음번엔 {0}부터 시작합니다',
"That's the whole workout!": '오늘 운동 전부 끝!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': '모든 운동 완료 — 수고했어요! 마무리하거나, 계속해서 운동을 추가하세요.',
'Finish workout': '운동 마치기',
'Continue workout': '운동 계속하기',
'Keep going — tap “+ Add exercise” below': '계속 가요 — 아래 "+ 운동 추가"를 탭하세요',
'Workout complete!': '운동 완료!',
@@ -166,11 +172,11 @@ export default {
'Add set': '세트 추가',
'+ Drop': '+ 드롭세트',
'+ Burst': '+ 버스트',
'Drop {0}': '드롭세트 {0}',
'Burst {0}': '버스트 {0}',
'Remove drop': '드롭세트 제거',
'Remove burst': '버스트 제거',
'Rest (s)': '휴식(초)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': '이 운동의 세트마다 갖는 휴식이에요. 기본 휴식 타이머를 쓰려면 0으로 두세요.',
'Drop-set / rest-pause': '드롭세트 / 레스트포즈',
'Intensifier': '강도 기법',
'None': '없음',
@@ -220,7 +226,6 @@ export default {
'No data yet': '데이터 없음',
'Your weekly routine': '주간 루틴',
'Week schedule': '주간 일정',
'Routines': '루틴',
'No routines yet.': '아직 루틴이 없어요.',
'Create one or load the starter plan.': '루틴을 만들거나 스타터 계획을 불러오세요.',
'Load starter plan (Push / Pull / Legs)': '스타터 계획 불러오기 (푸시 / 풀 / 레그)',
@@ -283,8 +288,10 @@ export default {
'Keep screen awake': '화면 켜두기',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': '운동이 진행되는 동안 화면이 켜져 있어 세트 사이에 잠금을 해제할 필요가 없습니다.',
'Weight unit': '무게 단위',
'Week starts on': '주 시작 요일',
'Rest timer': '휴식 타이머',
'Sounds': '소리',
'Flash screen when timer ends': '타이머 종료 시 화면 깜박임',
'Note: switching units only changes the label — logged numbers are not converted.': '참고: 단위 변경은 표기만 바꿉니다 — 기록된 숫자는 환산되지 않아요.',
'Data': '데이터',
'Export backup (JSON)': '백업 내보내기 (JSON)',
@@ -386,6 +393,10 @@ export default {
'Remove from routine': '루틴에서 제거',
'Minimize': '축소',
'Expand': '확대',
'Exercise animations': '운동 애니메이션',
'Full': '전체',
'Small': '작게',
'Hidden': '숨김',
'Invite code': '초대 코드',
'This app is invite-only — enter the code you were given.': '이 앱은 초대 전용입니다 — 받은 코드를 입력하세요.',
'An invite code is required': '초대 코드가 필요합니다',
@@ -452,6 +463,32 @@ export default {
'That file is empty': '파일이 비어 있습니다',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': '열을 인식할 수 없습니다 — 지원 앱은 문서를 참고하세요.',
'Nothing to import from that file': '이 파일에서 가져올 내용이 없습니다',
// --- import from Hevy API ---
'Import from Hevy': 'Hevy에서 가져오기',
'Pull your history with a Hevy Pro API key': 'Hevy Pro API 키로 기록을 가져옵니다',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Hevy Pro API 키로 기록을 가져옵니다. 키는 이번 가져오기에만 사용되며 저장되지 않습니다.',
'Hevy API key': 'Hevy API 키',
'Get your API key': 'API 키 받기',
'Hevy → Settings → Developer': 'Hevy → 설정 → Developer',
'Paste your Hevy API key first': '먼저 Hevy API 키를 붙여넣으세요',
'Fetch from Hevy': 'Hevy에서 가져오기',
'Fetching from Hevy…': 'Hevy에서 가져오는 중…',
'Fetching exercises… ({0}/{1})': '운동 가져오는 중… ({0}/{1})',
'Fetching workouts… ({0}/{1})': '운동 기록 가져오는 중… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': '체중 가져오는 중… ({0}/{1})',
'Matching exercises…': '운동 매칭 중…',
'Could not reach Hevy — check the key and try again': 'Hevy에 연결할 수 없습니다 — 키를 확인하고 다시 시도하세요',
'That Hevy API key was refused': 'Hevy API 키가 거부되었습니다',
'Nothing to import from Hevy': 'Hevy에서 가져올 항목이 없습니다',
'Import workouts': '운동 기록 가져오기',
'Import routines': '루틴 가져오기',
'{0} routines · {1} exercises — added as new plans': '루틴 {0}개 · 운동 {1}개 — 새 계획으로 추가',
'{0} routines imported': '루틴 {0}개 가져옴',
'Fetching routines… ({0}/{1})': '루틴 가져오는 중… ({0}/{1})',
'Routines': '루틴',
'Import weigh-ins': '체중 가져오기',
'{0} new · {1} days already here': '새 {0}개 · 이미 있는 날 {1}개',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy는 무게를 kg로 저장합니다 — {0}(으)로 변환됩니다.',
// --- mobile build ---
'Your data': '내 데이터',
'All data stays on this phone': '모든 데이터는 이 휴대폰에만 저장됩니다',
@@ -519,7 +556,11 @@ export default {
'Step ({0})': '증가폭 ({0})',
'Step (seconds)': '증가폭 (초)',
'Reps from': '최소 횟수',
'Reps up to': '최대 횟수',
'No automatic progression': '자동 증가 없음',
'Exclude from automatic progression': '자동 증가에서 제외',
'Use for planned deloads. Workouts stay in history and statistics.': '계획된 디로딩에 사용합니다. 운동은 기록과 통계에 남습니다.',
'The next regular target continues from the last included workout.': '다음 일반 목표는 마지막으로 포함된 운동에서 이어집니다.',
'Linear progression': '선형 증가',
'Greyskull LP': 'Greyskull LP',
'Double progression': '이중 점증',
@@ -860,7 +901,6 @@ export default {
'Avoid: {0}': '피할 것: {0}',
'Before we start': '시작하기 전에',
'Building your plan…': '계획을 만드는 중…',
'Continue': '계속',
'Discarded. Tell me what was off and I will build a different one.': '폐기했습니다. 무엇이 맞지 않았는지 알려주시면 다른 계획을 만들게요.',
'Done — your plan is back to how it was before my last changes.': '완료 — 계획이 제 마지막 변경 전으로 돌아갔습니다.',
'Edit my answers': '내 답변 수정',
@@ -1018,6 +1058,20 @@ export default {
'What should change?': '무엇을 바꿀까요?',
'Coach is thinking…': '코치가 생각 중…',
'Message the Coach…': '코치에게 메시지…',
'Open progression settings': '진행 설정 열기',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy가 요청을 제한하고 있습니다 — 잠시 기다렸다가 다시 시도하세요',
// --- log a past workout ---
'Log a past workout': '지난 운동 기록',
'Logged on the usual workout screen, without timers.': '평소 운동 화면에서 기록하며 타이머만 없습니다.',
'Date': '날짜',
'Start time': '시작 시간',
'Continue': '계속',
'Pick a day up to today': '오늘까지의 날짜를 선택하세요',
'There is already a workout on that day.': '그날에 이미 운동이 있습니다.',
'Replace': '바꾸기',
'Add as second workout': '두 번째 운동으로 추가',
'Finish the current workout first.': '먼저 진행 중인 운동을 마치세요.',
'Logging a past workout — no rest timers.': '지난 운동 기록 중 — 휴식 타이머 없음.',
// --- bar weight (plate math) ---
'Bar weight': '바 무게',
'Bar ({0})': '바 ({0})',
+59 -5
View File
@@ -4,7 +4,6 @@ export default {
'Cancel': 'Anuluj',
'Press back again to exit': 'Naciśnij wstecz ponownie, aby wyjść',
'Delete': 'Usuń',
'Save': 'Zapisz',
'Import': 'Importuj',
'Discard': 'Odrzuć',
'All': 'Wszystkie',
@@ -35,6 +34,8 @@ export default {
'rescheduled': 'przełożono',
'Prev': 'Wstecz',
'Next': 'Dalej',
'Move up': 'Przenieś w górę',
'Move down': 'Przenieś w dół',
'Sunday': 'Niedziela', 'Monday': 'Poniedziałek', 'Tuesday': 'Wtorek', 'Wednesday': 'Środa',
'Thursday': 'Czwartek', 'Friday': 'Piątek', 'Saturday': 'Sobota',
'Su': 'Nd', 'Mo': 'Pn', 'Tu': 'Wt', 'We': 'Śr', 'Th': 'Cz', 'Fr': 'Pt', 'Sa': 'So',
@@ -91,6 +92,12 @@ export default {
'Weight ({0})': 'Ciężar ({0})',
'Add to routine': 'Dodaj do planu',
'Remove exercise': 'Usuń ćwiczenie',
'Swap exercise': 'Zamień ćwiczenie',
'Swap exercise?': 'Zamienić ćwiczenie?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Zapisane serie pozostają przy oryginalnym ćwiczeniu. Wybierz miejsce dla zamiennika.',
'Keep replacement in this group': 'Zachowaj zamiennik w tej grupie',
'Insert after this group': 'Wstaw za tą grupą',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Zapisane serie pozostają przy oryginalnym ćwiczeniu. Zamiennik zostanie wstawiony za nim.',
'Remove {0}?': 'Usunąć {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Serie zapisane dla tego ćwiczenia w tej sesji zostaną utracone.',
'This removes the exercise from your current session.': 'Spowoduje to usunięcie ćwiczenia z bieżącej sesji.',
@@ -131,7 +138,6 @@ export default {
'Tracked — next time starts at {0}': 'Zapisano — następnym razem zaczynasz od {0}',
"That's the whole workout!": 'To cały trening!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Wszystkie ćwiczenia zrobione — świetna robota! Zakończ albo kontynuuj i dodaj kolejne ćwiczenie.',
'Finish workout': 'Zakończ trening',
'Continue workout': 'Kontynuuj trening',
'Keep going — tap “+ Add exercise” below': 'Tak trzymaj — dotknij „+ Dodaj ćwiczenie” poniżej',
'Workout complete!': 'Trening ukończony!',
@@ -166,11 +172,11 @@ export default {
'Add set': 'Dodaj serię',
'+ Drop': '+ Seria zniżkująca',
'+ Burst': '+ Seria rest-pause',
'Drop {0}': 'Seria zniżkująca {0}',
'Burst {0}': 'Seria rest-pause {0}',
'Remove drop': 'Usuń serię zniżkującą',
'Remove burst': 'Usuń serię rest-pause',
'Rest (s)': 'Odpoczynek (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Odpoczynek po każdej serii tego ćwiczenia. Zostaw 0, żeby użyć domyślnego minutnika przerwy.',
'Drop-set / rest-pause': 'Seria zniżkująca / rest-pause',
'Intensifier': 'Technika intensyfikująca',
'None': 'Brak',
@@ -220,7 +226,6 @@ export default {
'No data yet': 'Brak danych',
'Your weekly routine': 'Twój plan tygodnia',
'Week schedule': 'Harmonogram tygodnia',
'Routines': 'Plany treningowe',
'No routines yet.': 'Brak planów.',
'Create one or load the starter plan.': 'Utwórz plan albo wczytaj startowy.',
'Load starter plan (Push / Pull / Legs)': 'Wczytaj plan startowy (Push / Pull / Nogi)',
@@ -283,8 +288,10 @@ export default {
'Keep screen awake': 'Nie wygaszaj ekranu',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Ekran pozostaje włączony w trakcie treningu, więc nie musisz odblokowywać telefonu między seriami.',
'Weight unit': 'Jednostka wagi',
'Week starts on': 'Tydzień zaczyna się w',
'Rest timer': 'Minutnik przerwy',
'Sounds': 'Dźwięki',
'Flash screen when timer ends': 'Migaj ekranem po zakończeniu minutnika',
'Note: switching units only changes the label — logged numbers are not converted.': 'Uwaga: zmiana jednostki zmienia tylko etykietę — zapisane liczby nie są przeliczane.',
'Data': 'Dane',
'Export backup (JSON)': 'Eksportuj kopię (JSON)',
@@ -386,6 +393,10 @@ export default {
'Remove from routine': 'Usuń z planu',
'Minimize': 'Zmniejsz',
'Expand': 'Powiększ',
'Exercise animations': 'Animacje ćwiczeń',
'Full': 'Pełna',
'Small': 'Mała',
'Hidden': 'Ukryta',
'Invite code': 'Kod zaproszenia',
'This app is invite-only — enter the code you were given.': 'Ta aplikacja jest tylko na zaproszenie — wpisz otrzymany kod.',
'An invite code is required': 'Wymagany jest kod zaproszenia',
@@ -452,6 +463,32 @@ export default {
'That file is empty': 'Ten plik jest pusty',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Nie rozpoznano kolumn — obsługiwane aplikacje znajdziesz w dokumentacji.',
'Nothing to import from that file': 'Brak danych do importu z tego pliku',
// --- import from Hevy API ---
'Import from Hevy': 'Importuj z Hevy',
'Pull your history with a Hevy Pro API key': 'Pobierz historię kluczem API Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Pobierz historię kluczem API Hevy Pro. Klucz służy tylko do tego importu i nie jest zapisywany.',
'Hevy API key': 'Klucz API Hevy',
'Get your API key': 'Pobierz klucz API',
'Hevy → Settings → Developer': 'Hevy → Ustawienia → Developer',
'Paste your Hevy API key first': 'Najpierw wklej klucz API Hevy',
'Fetch from Hevy': 'Pobierz z Hevy',
'Fetching from Hevy…': 'Pobieranie z Hevy…',
'Fetching exercises… ({0}/{1})': 'Pobieranie ćwiczeń… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Pobieranie treningów… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Pobieranie ważenia… ({0}/{1})',
'Matching exercises…': 'Dopasowywanie ćwiczeń…',
'Could not reach Hevy — check the key and try again': 'Nie udało się połączyć z Hevy — sprawdź klucz i spróbuj ponownie',
'That Hevy API key was refused': 'Ten klucz API Hevy został odrzucony',
'Nothing to import from Hevy': 'Nie ma nic do zaimportowania z Hevy',
'Import workouts': 'Importuj treningi',
'Import routines': 'Importuj rutyny',
'{0} routines · {1} exercises — added as new plans': '{0} rutyn · {1} ćwiczeń — dodane jako nowe plany',
'{0} routines imported': 'Zaimportowano {0} rutyn',
'Fetching routines… ({0}/{1})': 'Pobieranie rutyn… ({0}/{1})',
'Routines': 'Rutyny',
'Import weigh-ins': 'Importuj ważenia',
'{0} new · {1} days already here': '{0} nowych · {1} dni już jest',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy zapisuje ciężary w kg — zostaną przeliczone na {0}.',
// --- mobile build ---
'Your data': 'Twoje dane',
'All data stays on this phone': 'Wszystkie dane zostają na tym telefonie',
@@ -519,7 +556,11 @@ export default {
'Step ({0})': 'Skok ({0})',
'Step (seconds)': 'Skok (sekundy)',
'Reps from': 'Powt. od',
'Reps up to': 'Powt. do',
'No automatic progression': 'Bez automatycznej progresji',
'Exclude from automatic progression': 'Wyklucz z automatycznej progresji',
'Use for planned deloads. Workouts stay in history and statistics.': 'Użyj dla planowanych deloadów. Treningi pozostają w historii i statystykach.',
'The next regular target continues from the last included workout.': 'Następny zwykły cel bazuje na ostatnim uwzględnionym treningu.',
'Linear progression': 'Progresja liniowa',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Podwójna progresja',
@@ -860,7 +901,6 @@ export default {
'Avoid: {0}': 'Unikać: {0}',
'Before we start': 'Zanim zaczniemy',
'Building your plan…': 'Tworzę Twój plan…',
'Continue': 'Dalej',
'Discarded. Tell me what was off and I will build a different one.': 'Odrzucono. Powiedz, co było nie tak, a zbuduję inny.',
'Done — your plan is back to how it was before my last changes.': 'Gotowe — Twój plan wrócił do stanu sprzed moich ostatnich zmian.',
'Edit my answers': 'Edytuj moje odpowiedzi',
@@ -1018,6 +1058,20 @@ export default {
'What should change?': 'Co powinno się zmienić?',
'Coach is thinking…': 'Trener myśli…',
'Message the Coach…': 'Napisz do trenera…',
'Open progression settings': 'Otwórz ustawienia progresji',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy ogranicza liczbę zapytań — odczekaj minutę i spróbuj ponownie',
// --- log a past workout ---
'Log a past workout': 'Zapisz miniony trening',
'Logged on the usual workout screen, without timers.': 'Zapisujesz na zwykłym ekranie treningu, tylko bez minutników.',
'Date': 'Data',
'Start time': 'Godzina rozpoczęcia',
'Continue': 'Dalej',
'Pick a day up to today': 'Wybierz dzień do dzisiaj',
'There is already a workout on that day.': 'Tego dnia jest już trening.',
'Replace': 'Zastąp',
'Add as second workout': 'Dodaj jako drugi trening',
'Finish the current workout first.': 'Najpierw zakończ bieżący trening.',
'Logging a past workout — no rest timers.': 'Zapisywanie minionego treningu — bez minutników przerw.',
// --- bar weight (plate math) ---
'Bar weight': 'Ciężar gryfu',
'Bar ({0})': 'Gryf ({0})',
+49
View File
@@ -9,6 +9,7 @@ export const PT_BR_OVERRIDES = {
'Message the Coach…': 'Escreva ao Coach…',
'Press back again to exit': 'Pressione voltar novamente para sair',
'Reps up to': 'Reps até',
'Delete': 'Excluir',
'Save': 'Salvar',
'Log': 'Registrar',
@@ -32,6 +33,12 @@ export const PT_BR_OVERRIDES = {
'Search {0} exercises…': 'Buscar entre {0} exercícios…',
'Nothing chosen yet — add exercises and they’ll show up here.': 'Nenhum exercício escolhido — adicione exercícios e eles aparecerão aqui.',
'The sets you logged for this exercise in this session will be lost.': 'As séries registradas para este exercício nesta sessão serão perdidas.',
'Swap exercise': 'Trocar exercício',
'Swap exercise?': 'Trocar exercício?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'As séries registradas ficam com o exercício original. Escolha onde colocar o substituto.',
'Keep replacement in this group': 'Manter o substituto neste grupo',
'Insert after this group': 'Inserir depois deste grupo',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'As séries registradas ficam com o exercício original. O substituto será inserido depois.',
'This removes the exercise from your current session.': 'Isso remove o exercício da sua sessão atual.',
'Which exercise in this superset do you want to remove?': 'Qual exercício deste superset você quer remover?',
'Pick an icon': 'Escolha um ícone',
@@ -63,6 +70,9 @@ export const PT_BR_OVERRIDES = {
'Create one or load the starter plan.': 'Crie uma ou carregue o plano inicial.',
'Load starter plan (Push / Pull / Legs)': 'Carregar plano inicial (Push / Pull / Legs)',
'No exercises yet — add your first one.': 'Ainda não há exercícios — adicione o primeiro.',
'Exclude from automatic progression': 'Excluir da progressão automática',
'Use for planned deloads. Workouts stay in history and statistics.': 'Use para deloads planejados. Os treinos permanecem no histórico e nas estatísticas.',
'The next regular target continues from the last included workout.': 'A próxima meta normal continua a partir do último treino incluído.',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Toque no botão de vínculo de um exercício para combiná-lo em um superset com o exercício acima — eles serão feitos em sequência.',
'Delete routine?': 'Excluir rotina?',
'Delete routine': 'Excluir rotina',
@@ -94,6 +104,7 @@ export const PT_BR_OVERRIDES = {
'Create passkey profile': 'Criar perfil com chave de acesso',
'synced with your profile': 'sincronizado com seu perfil',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'A tela permanece ligada durante o treino, para você não precisar desbloquear o celular entre as séries.',
'Flash screen when timer ends': 'Piscar a tela quando o temporizador terminar',
'Note: switching units only changes the label — logged numbers are not converted.': 'Observação: trocar a unidade altera somente o rótulo — os valores registrados não são convertidos.',
'Export backup (JSON)': 'Exportar backup (JSON)',
'Import backup': 'Importar backup',
@@ -138,6 +149,33 @@ export const PT_BR_OVERRIDES = {
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colunas não reconhecidas — consulte a documentação dos aplicativos compatíveis.',
'That file is empty': 'Esse arquivo está vazio',
'Nothing to import from that file': 'Não há nada para importar desse arquivo',
// --- import from Hevy API ---
'Import from Hevy': 'Importar do Hevy',
'Pull your history with a Hevy Pro API key': 'Traga seu histórico com uma chave de API do Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Traga seu histórico com uma chave de API do Hevy Pro. A chave só é usada nesta importação e não é salva.',
'Hevy API key': 'Chave de API do Hevy',
'Get your API key': 'Obter sua chave de API',
'Hevy → Settings → Developer': 'Hevy → Configurações → Developer',
'Paste your Hevy API key first': 'Cole primeiro sua chave de API do Hevy',
'Fetch from Hevy': 'Buscar no Hevy',
'Fetching from Hevy…': 'Buscando no Hevy…',
'Fetching exercises… ({0}/{1})': 'Buscando exercícios… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Buscando treinos… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Buscando pesagens… ({0}/{1})',
'Matching exercises…': 'Associando exercícios…',
'Could not reach Hevy — check the key and try again': 'Não foi possível contatar o Hevy — confira a chave e tente de novo',
'That Hevy API key was refused': 'Essa chave de API do Hevy foi recusada',
'Nothing to import from Hevy': 'Nada para importar do Hevy',
'Import workouts': 'Importar treinos',
'Import routines': 'Importar rotinas',
'{0} routines · {1} exercises — added as new plans': '{0} rotinas · {1} exercícios — adicionadas como planos novos',
'{0} routines imported': '{0} rotinas importadas',
'Fetching routines… ({0}/{1})': 'Buscando rotinas… ({0}/{1})',
'Routines': 'Rotinas',
'Import weigh-ins': 'Importar pesagens',
'{0} new · {1} days already here': '{0} novos · {1} dias já existentes',
'Hevy stores weights in kg — they will be converted to {0}.': 'O Hevy guarda os pesos em kg — eles serão convertidos para {0}.',
'Back': 'Voltar',
'Your data': 'Seus dados',
'All data stays on this phone': 'Todos os dados ficam neste celular',
'No account, no cloud — back it up anytime with Export below.': 'Sem conta e sem nuvem — faça um backup quando quiser usando a opção Exportar abaixo.',
@@ -184,6 +222,8 @@ export const PT_BR_OVERRIDES = {
// Regional wording inherited from pt-PT would otherwise leak into pt-BR.
'Next': 'Próximo',
'Move up': 'Mover para cima',
'Move down': 'Mover para baixo',
'{0} to gain': '{0} para ganhar',
'{0} to lose': '{0} para perder',
'{0} set still unchecked. Finish the workout now?': 'Falta {0} série sem marcar. Finalizar o treino agora?',
@@ -555,6 +595,15 @@ export const PT_BR_OVERRIDES = {
'Back muscles': 'Costas',
'{0}: what’s planned': '{0}: previsto',
// --- per-exercise rest ---
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Descanso depois de cada série deste exercício. Deixe em 0 para usar o temporizador de descanso padrão.',
'Open progression settings': 'Abrir configurações de progressão',
'Hevy is rate-limiting requests — wait a minute and try again': 'O Hevy está limitando as solicitações — espere um minuto e tente novamente',
'Log a past workout': 'Registrar um treino passado',
'Logged on the usual workout screen, without timers.': 'Registrado na tela de treino habitual, só sem temporizadores.',
'Pick a day up to today': 'Escolha um dia até hoje',
'Finish the current workout first.': 'Termine primeiro o treino atual.',
'Logging a past workout — no rest timers.': 'Registrando um treino passado — sem temporizadores de descanso.',
// --- bar weight (plate math) --- ('Peso da barra', 'Barra ({0})', 'Barra {0}' inherit)
'Default for this bar type.': 'Padrão para este tipo de barra.',
'Set to 0 to go back to the default ({0}).': 'Defina 0 para voltar ao padrão ({0}).',
+59 -5
View File
@@ -4,7 +4,6 @@ export default {
'Cancel': 'Cancelar',
'Press back again to exit': 'Prima novamente para sair',
'Delete': 'Eliminar',
'Save': 'Guardar',
'Import': 'Importar',
'Discard': 'Descartar',
'All': 'Todos',
@@ -35,6 +34,8 @@ export default {
'rescheduled': 'reagendado',
'Prev': 'Anterior',
'Next': 'Seguinte',
'Move up': 'Mover para cima',
'Move down': 'Mover para baixo',
'Sunday': 'Domingo', 'Monday': 'Segunda-feira', 'Tuesday': 'Terça-feira', 'Wednesday': 'Quarta-feira',
'Thursday': 'Quinta-feira', 'Friday': 'Sexta-feira', 'Saturday': 'Sábado',
'Su': 'Do', 'Mo': 'Se', 'Tu': 'Te', 'We': 'Qa', 'Th': 'Qi', 'Fr': 'Sx', 'Sa': 'Sá',
@@ -91,6 +92,12 @@ export default {
'Weight ({0})': 'Peso ({0})',
'Add to routine': 'Adicionar à rotina',
'Remove exercise': 'Remover exercício',
'Swap exercise': 'Trocar exercício',
'Swap exercise?': 'Trocar exercício?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'As séries registadas ficam com o exercício original. Escolhe onde colocar o substituto.',
'Keep replacement in this group': 'Manter o substituto neste grupo',
'Insert after this group': 'Inserir depois deste grupo',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'As séries registadas ficam com o exercício original. O substituto será inserido depois.',
'Remove {0}?': 'Remover {0}?',
'The sets you logged for this exercise in this session will be lost.': 'As séries registadas para este exercício nesta sessão serão perdidas.',
'This removes the exercise from your current session.': 'Isto remove o exercício da tua sessão atual.',
@@ -131,7 +138,6 @@ export default {
'Tracked — next time starts at {0}': 'Registado — da próxima vez começas em {0}',
"That's the whole workout!": 'Era o treino todo!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Todos os exercícios feitos — bom trabalho! Termina, ou continua e adiciona outro exercício.',
'Finish workout': 'Terminar treino',
'Continue workout': 'Continuar treino',
'Keep going — tap “+ Add exercise” below': 'Continua — toca em «+ Adicionar exercício» em baixo',
'Workout complete!': 'Treino concluído!',
@@ -166,11 +172,11 @@ export default {
'Add set': 'Adicionar série',
'+ Drop': '+ Queda',
'+ Burst': '+ Rajada',
'Drop {0}': 'Queda {0}',
'Burst {0}': 'Rajada {0}',
'Remove drop': 'Remover queda',
'Remove burst': 'Remover rajada',
'Rest (s)': 'Descanso (s)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Descanso depois de cada série deste exercício. Deixa a 0 para usares o temporizador de descanso predefinido.',
'Drop-set / rest-pause': 'Séries decrescentes / rest-pause',
'Intensifier': 'Intensificador',
'None': 'Nenhum',
@@ -220,7 +226,6 @@ export default {
'No data yet': 'Ainda sem dados',
'Your weekly routine': 'A tua rotina semanal',
'Week schedule': 'Horário semanal',
'Routines': 'Rotinas',
'No routines yet.': 'Ainda sem rotinas.',
'Create one or load the starter plan.': 'Cria uma ou carrega o plano inicial.',
'Load starter plan (Push / Pull / Legs)': 'Carregar plano inicial (Push / Pull / Pernas)',
@@ -283,8 +288,10 @@ export default {
'Keep screen awake': 'Manter o ecrã ligado',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'O ecrã fica ligado enquanto há um treino a decorrer, para não teres de desbloquear o telemóvel entre séries.',
'Weight unit': 'Unidade de peso',
'Week starts on': 'Início da semana',
'Rest timer': 'Temporizador de descanso',
'Sounds': 'Sons',
'Flash screen when timer ends': 'Piscar o ecrã quando o temporizador terminar',
'Note: switching units only changes the label — logged numbers are not converted.': 'Nota: mudar a unidade só muda o rótulo — os números registados não são convertidos.',
'Data': 'Dados',
'Export backup (JSON)': 'Exportar cópia (JSON)',
@@ -386,6 +393,10 @@ export default {
'Remove from routine': 'Remover da rotina',
'Minimize': 'Minimizar',
'Expand': 'Ampliar',
'Exercise animations': 'Animações dos exercícios',
'Full': 'Grande',
'Small': 'Pequena',
'Hidden': 'Oculta',
'Invite code': 'Código de convite',
'This app is invite-only — enter the code you were given.': 'Esta app é só por convite — introduz o código que recebeste.',
'An invite code is required': 'É necessário um código de convite',
@@ -452,6 +463,32 @@ export default {
'That file is empty': 'Esse ficheiro está vazio',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Colunas não reconhecidas — vê a documentação para apps suportadas.',
'Nothing to import from that file': 'Nada para importar desse ficheiro',
// --- import from Hevy API ---
'Import from Hevy': 'Importar do Hevy',
'Pull your history with a Hevy Pro API key': 'Traz o historial com uma chave API Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Traz o historial com uma chave API Hevy Pro. A chave só é usada neste import e não é guardada.',
'Hevy API key': 'Chave API Hevy',
'Get your API key': 'Obter a chave API',
'Hevy → Settings → Developer': 'Hevy → Definições → Developer',
'Paste your Hevy API key first': 'Cola primeiro a chave API Hevy',
'Fetch from Hevy': 'Carregar do Hevy',
'Fetching from Hevy…': 'A carregar do Hevy…',
'Fetching exercises… ({0}/{1})': 'A carregar exercícios… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'A carregar treinos… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'A carregar pesagens… ({0}/{1})',
'Matching exercises…': 'A associar exercícios…',
'Could not reach Hevy — check the key and try again': 'Não foi possível contactar o Hevy — verifica a chave e tenta de novo',
'That Hevy API key was refused': 'Essa chave API Hevy foi recusada',
'Nothing to import from Hevy': 'Nada para importar do Hevy',
'Import workouts': 'Importar treinos',
'Import routines': 'Importar rotinas',
'{0} routines · {1} exercises — added as new plans': '{0} rotinas · {1} exercícios — adicionadas como planos novos',
'{0} routines imported': '{0} rotinas importadas',
'Fetching routines… ({0}/{1})': 'A carregar rotinas… ({0}/{1})',
'Routines': 'Rotinas',
'Import weigh-ins': 'Importar pesagens',
'{0} new · {1} days already here': '{0} novos · {1} dias já existentes',
'Hevy stores weights in kg — they will be converted to {0}.': 'O Hevy guarda os pesos em kg — serão convertidos para {0}.',
// --- mobile build ---
'Your data': 'Os teus dados',
'All data stays on this phone': 'Todos os dados ficam neste telemóvel',
@@ -519,7 +556,11 @@ export default {
'Step ({0})': 'Incremento ({0})',
'Step (seconds)': 'Incremento (segundos)',
'Reps from': 'Reps a partir de',
'Reps up to': 'Reps até',
'No automatic progression': 'Sem progressão automática',
'Exclude from automatic progression': 'Excluir da progressão automática',
'Use for planned deloads. Workouts stay in history and statistics.': 'Use para deloads planeados. Os treinos permanecem no histórico e nas estatísticas.',
'The next regular target continues from the last included workout.': 'O próximo objetivo normal continua a partir do último treino incluído.',
'Linear progression': 'Progressão linear',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Progressão dupla',
@@ -860,7 +901,6 @@ export default {
'Avoid: {0}': 'Evitar: {0}',
'Before we start': 'Antes de começarmos',
'Building your plan…': 'A criar o teu plano…',
'Continue': 'Continuar',
'Discarded. Tell me what was off and I will build a different one.': 'Descartado. Diz-me o que não encaixou e eu faço outro.',
'Done — your plan is back to how it was before my last changes.': 'Feito — o teu plano voltou ao que era antes das minhas últimas alterações.',
'Edit my answers': 'Editar as minhas respostas',
@@ -1018,6 +1058,20 @@ export default {
'What should change?': 'O que deve mudar?',
'Coach is thinking…': 'O Coach está a pensar…',
'Message the Coach…': 'Escreve ao Coach…',
'Open progression settings': 'Abrir definições de progressão',
'Hevy is rate-limiting requests — wait a minute and try again': 'O Hevy está a limitar os pedidos — espere um minuto e tente novamente',
// --- log a past workout ---
'Log a past workout': 'Registar um treino passado',
'Logged on the usual workout screen, without timers.': 'Registado no ecrã de treino habitual, só sem temporizadores.',
'Date': 'Data',
'Start time': 'Hora de início',
'Continue': 'Continuar',
'Pick a day up to today': 'Escolhe um dia até hoje',
'There is already a workout on that day.': 'Já existe um treino nesse dia.',
'Replace': 'Substituir',
'Add as second workout': 'Adicionar como segundo treino',
'Finish the current workout first.': 'Termina primeiro o treino em curso.',
'Logging a past workout — no rest timers.': 'A registar um treino passado — sem temporizadores de descanso.',
// --- bar weight (plate math) ---
'Bar weight': 'Peso da barra',
'Bar ({0})': 'Barra ({0})',
+59 -5
View File
@@ -4,7 +4,6 @@ export default {
'Cancel': 'Отмена',
'Press back again to exit': 'Нажмите «Назад» ещё раз, чтобы выйти',
'Delete': 'Удалить',
'Save': 'Сохранить',
'Import': 'Импорт',
'Discard': 'Отменить',
'All': 'Все',
@@ -35,6 +34,8 @@ export default {
'rescheduled': 'перенесено',
'Prev': 'Назад',
'Next': 'Далее',
'Move up': 'Переместить вверх',
'Move down': 'Переместить вниз',
'Sunday': 'Воскресенье', 'Monday': 'Понедельник', 'Tuesday': 'Вторник', 'Wednesday': 'Среда',
'Thursday': 'Четверг', 'Friday': 'Пятница', 'Saturday': 'Суббота',
'Su': 'Вс', 'Mo': 'Пн', 'Tu': 'Вт', 'We': 'Ср', 'Th': 'Чт', 'Fr': 'Пт', 'Sa': 'Сб',
@@ -91,6 +92,12 @@ export default {
'Weight ({0})': 'Вес ({0})',
'Add to routine': 'Добавить в программу',
'Remove exercise': 'Убрать упражнение',
'Swap exercise': 'Заменить упражнение',
'Swap exercise?': 'Заменить упражнение?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Записанные подходы останутся у исходного упражнения. Выберите место для замены.',
'Keep replacement in this group': 'Оставить замену в этой группе',
'Insert after this group': 'Вставить после этой группы',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Записанные подходы останутся у исходного упражнения. Замена будет вставлена после него.',
'Remove {0}?': 'Удалить {0}?',
'The sets you logged for this exercise in this session will be lost.': 'Подходы, записанные для этого упражнения в этой сессии, будут потеряны.',
'This removes the exercise from your current session.': 'Упражнение будет удалено из текущей сессии.',
@@ -131,7 +138,6 @@ export default {
'Tracked — next time starts at {0}': 'Записано — в следующий раз начнёшь с {0}',
"That's the whole workout!": 'Это была вся тренировка!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Все упражнения выполнены — отличная работа! Завершай или продолжай и добавь ещё упражнение.',
'Finish workout': 'Завершить тренировку',
'Continue workout': 'Продолжить тренировку',
'Keep going — tap “+ Add exercise” below': 'Продолжай — нажми «+ Добавить упражнение» ниже',
'Workout complete!': 'Тренировка завершена!',
@@ -166,11 +172,11 @@ export default {
'Add set': 'Добавить подход',
'+ Drop': '+ Дроп-сет',
'+ Burst': '+ Серия рест-пауз',
'Drop {0}': 'Дроп-сет {0}',
'Burst {0}': 'Серия {0}',
'Remove drop': 'Убрать дроп-сет',
'Remove burst': 'Убрать серию',
'Rest (s)': 'Отдых (с)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Отдых после каждого подхода этого упражнения. Оставь 0, чтобы работал таймер отдыха по умолчанию.',
'Drop-set / rest-pause': 'Дроп-сет / рест-пауза',
'Intensifier': 'Интенсификатор',
'None': 'Нет',
@@ -220,7 +226,6 @@ export default {
'No data yet': 'Данных пока нет',
'Your weekly routine': 'Твой недельный план',
'Week schedule': 'Расписание недели',
'Routines': 'Программы',
'No routines yet.': 'Программ пока нет.',
'Create one or load the starter plan.': 'Создай программу или загрузи стартовый план.',
'Load starter plan (Push / Pull / Legs)': 'Загрузить стартовый план (Push / Pull / Ноги)',
@@ -283,8 +288,10 @@ export default {
'Keep screen awake': 'Не гасить экран',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Экран не гаснет, пока идёт тренировка, — не нужно разблокировать телефон между подходами.',
'Weight unit': 'Единица веса',
'Week starts on': 'Неделя начинается с',
'Rest timer': 'Таймер отдыха',
'Sounds': 'Звуки',
'Flash screen when timer ends': 'Мигать экраном по окончании таймера',
'Note: switching units only changes the label — logged numbers are not converted.': 'Примечание: смена единиц меняет только подпись — записанные числа не пересчитываются.',
'Data': 'Данные',
'Export backup (JSON)': 'Экспорт резервной копии (JSON)',
@@ -386,6 +393,10 @@ export default {
'Remove from routine': 'Убрать из программы',
'Minimize': 'Свернуть',
'Expand': 'Развернуть',
'Exercise animations': 'Анимации упражнений',
'Full': 'Полная',
'Small': 'Малая',
'Hidden': 'Скрыта',
'Invite code': 'Код приглашения',
'This app is invite-only — enter the code you were given.': 'Приложение только по приглашению — введите выданный вам код.',
'An invite code is required': 'Требуется код приглашения',
@@ -452,6 +463,32 @@ export default {
'That file is empty': 'Файл пуст',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Колонки не распознаны — список поддерживаемых приложений в документации.',
'Nothing to import from that file': 'В этом файле нечего импортировать',
// --- import from Hevy API ---
'Import from Hevy': 'Импорт из Hevy',
'Pull your history with a Hevy Pro API key': 'Загрузить историю с API-ключом Hevy Pro',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Загрузить историю с API-ключом Hevy Pro. Ключ используется только для этого импорта и не сохраняется.',
'Hevy API key': 'API-ключ Hevy',
'Get your API key': 'Получить API-ключ',
'Hevy → Settings → Developer': 'Hevy → Настройки → Developer',
'Paste your Hevy API key first': 'Сначала вставьте API-ключ Hevy',
'Fetch from Hevy': 'Загрузить из Hevy',
'Fetching from Hevy…': 'Загрузка из Hevy…',
'Fetching exercises… ({0}/{1})': 'Загрузка упражнений… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Загрузка тренировок… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Загрузка взвешиваний… ({0}/{1})',
'Matching exercises…': 'Сопоставление упражнений…',
'Could not reach Hevy — check the key and try again': 'Не удалось связаться с Hevy — проверьте ключ и попробуйте снова',
'That Hevy API key was refused': 'Этот API-ключ Hevy отклонён',
'Nothing to import from Hevy': 'Из Hevy нечего импортировать',
'Import workouts': 'Импортировать тренировки',
'Import routines': 'Импортировать программы',
'{0} routines · {1} exercises — added as new plans': '{0} программ · {1} упражнений — добавляются как новые планы',
'{0} routines imported': 'Импортировано программ: {0}',
'Fetching routines… ({0}/{1})': 'Загрузка программ… ({0}/{1})',
'Routines': 'Программы',
'Import weigh-ins': 'Импортировать взвешивания',
'{0} new · {1} days already here': '{0} новых · {1} дней уже есть',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy хранит веса в кг — они будут переведены в {0}.',
// --- mobile build ---
'Your data': 'Ваши данные',
'All data stays on this phone': 'Все данные остаются на этом телефоне',
@@ -519,7 +556,11 @@ export default {
'Step ({0})': 'Шаг ({0})',
'Step (seconds)': 'Шаг (секунды)',
'Reps from': 'Повт. от',
'Reps up to': 'Повт. до',
'No automatic progression': 'Без автопрогрессии',
'Exclude from automatic progression': 'Исключить из автоматической прогрессии',
'Use for planned deloads. Workouts stay in history and statistics.': 'Используйте для плановых разгрузок. Тренировки остаются в истории и статистике.',
'The next regular target continues from the last included workout.': 'Следующая обычная цель продолжает прогрессию от последней учтённой тренировки.',
'Linear progression': 'Линейная прогрессия',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Двойная прогрессия',
@@ -860,7 +901,6 @@ export default {
'Avoid: {0}': 'Избегать: {0}',
'Before we start': 'Прежде чем начать',
'Building your plan…': 'Составляю ваш план…',
'Continue': 'Далее',
'Discarded. Tell me what was off and I will build a different one.': 'Отклонено. Скажите, что не подошло, и я составлю другой.',
'Done — your plan is back to how it was before my last changes.': 'Готово — ваш план вернулся к состоянию до моих последних изменений.',
'Edit my answers': 'Изменить мои ответы',
@@ -1018,6 +1058,20 @@ export default {
'What should change?': 'Что изменить?',
'Coach is thinking…': 'Тренер думает…',
'Message the Coach…': 'Написать тренеру…',
'Open progression settings': 'Открыть настройки прогрессии',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy ограничивает запросы — подождите минуту и попробуйте снова',
// --- log a past workout ---
'Log a past workout': 'Записать прошлую тренировку',
'Logged on the usual workout screen, without timers.': 'Записывается на обычном экране тренировки, только без таймеров.',
'Date': 'Дата',
'Start time': 'Время начала',
'Continue': 'Продолжить',
'Pick a day up to today': 'Выбери день не позже сегодняшнего',
'There is already a workout on that day.': 'В этот день уже есть тренировка.',
'Replace': 'Заменить',
'Add as second workout': 'Добавить как вторую тренировку',
'Finish the current workout first.': 'Сначала заверши текущую тренировку.',
'Logging a past workout — no rest timers.': 'Запись прошлой тренировки — без таймеров отдыха.',
// --- bar weight (plate math) ---
'Bar weight': 'Вес грифа',
'Bar ({0})': 'Гриф ({0})',
File diff suppressed because it is too large. Load diff
+59 -5
View File
@@ -4,7 +4,6 @@ export default {
'Cancel': 'İptal',
'Press back again to exit': 'Çıkmak için geri tuşuna tekrar basın',
'Delete': 'Sil',
'Save': 'Kaydet',
'Import': 'İçe aktar',
'Discard': 'Vazgeç',
'All': 'Tümü',
@@ -35,6 +34,8 @@ export default {
'rescheduled': 'ertelendi',
'Prev': 'Önceki',
'Next': 'Sonraki',
'Move up': 'Yukarı taşı',
'Move down': 'Aşağı taşı',
'Sunday': 'Pazar', 'Monday': 'Pazartesi', 'Tuesday': 'Salı', 'Wednesday': 'Çarşamba',
'Thursday': 'Perşembe', 'Friday': 'Cuma', 'Saturday': 'Cumartesi',
'Su': 'Pz', 'Mo': 'Pt', 'Tu': 'Sa', 'We': 'Ça', 'Th': 'Pe', 'Fr': 'Cu', 'Sa': 'Ct',
@@ -91,6 +92,12 @@ export default {
'Weight ({0})': 'Ağırlık ({0})',
'Add to routine': 'Rutine ekle',
'Remove exercise': 'Egzersizi kaldır',
'Swap exercise': 'Egzersizi değiştir',
'Swap exercise?': 'Egzersiz değiştirilsin mi?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': 'Kaydedilen setler özgün egzersizde kalır. Yeni egzersizin nereye geleceğini seç.',
'Keep replacement in this group': 'Yeni egzersizi bu grupta tut',
'Insert after this group': 'Bu gruptan sonra ekle',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': 'Kaydedilen setler özgün egzersizde kalır. Yeni egzersiz sonrasına eklenir.',
'Remove {0}?': '{0} kaldırılsın mı?',
'The sets you logged for this exercise in this session will be lost.': 'Bu seansta bu egzersiz için kaydettiğin setler kaybolacak.',
'This removes the exercise from your current session.': 'Bu işlem egzersizi mevcut seansından kaldırır.',
@@ -131,7 +138,6 @@ export default {
'Tracked — next time starts at {0}': 'Kaydedildi — bir dahaki sefer {0} ile başlarsın',
"That's the whole workout!": 'Antrenmanın tamamı buydu!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Tüm egzersizler bitti — harika iş! Bitir ya da devam edip yeni bir egzersiz ekle.',
'Finish workout': 'Antrenmanı bitir',
'Continue workout': 'Antrenmana devam et',
'Keep going — tap “+ Add exercise” below': 'Devam — aşağıdaki “+ Egzersiz ekle”ye dokun',
'Workout complete!': 'Antrenman tamamlandı!',
@@ -166,11 +172,11 @@ export default {
'Add set': 'Set ekle',
'+ Drop': '+ Düşüş seti',
'+ Burst': '+ Patlama',
'Drop {0}': 'Düşüş seti {0}',
'Burst {0}': 'Patlama {0}',
'Remove drop': 'Düşüş setini kaldır',
'Remove burst': 'Patlamayı kaldır',
'Rest (s)': 'Dinlenme (sn)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': 'Bu egzersizin her setinden sonraki dinlenme. Varsayılan dinlenme sayacını kullanmak için 0 bırak.',
'Drop-set / rest-pause': 'Düşüş seti / rest-pause',
'Intensifier': 'Yoğunlaştırıcı',
'None': 'Yok',
@@ -220,7 +226,6 @@ export default {
'No data yet': 'Henüz veri yok',
'Your weekly routine': 'Haftalık rutinin',
'Week schedule': 'Hafta programı',
'Routines': 'Rutinler',
'No routines yet.': 'Henüz rutin yok.',
'Create one or load the starter plan.': 'Bir tane oluştur ya da başlangıç planını yükle.',
'Load starter plan (Push / Pull / Legs)': 'Başlangıç planını yükle (Push / Pull / Bacak)',
@@ -283,8 +288,10 @@ export default {
'Keep screen awake': 'Ekranı açık tut',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': 'Antrenman sürerken ekran açık kalır, böylece setler arasında telefonunu açmak zorunda kalmazsın.',
'Weight unit': 'Ağırlık birimi',
'Week starts on': 'Hafta başlangıcı',
'Rest timer': 'Dinlenme sayacı',
'Sounds': 'Sesler',
'Flash screen when timer ends': 'Zamanlayıcı bitince ekranı yanıp söndür',
'Note: switching units only changes the label — logged numbers are not converted.': 'Not: birim değiştirmek sadece etiketi değiştirir — kayıtlı sayılar dönüştürülmez.',
'Data': 'Veriler',
'Export backup (JSON)': 'Yedeği dışa aktar (JSON)',
@@ -386,6 +393,10 @@ export default {
'Remove from routine': 'Rutinden çıkar',
'Minimize': 'Küçült',
'Expand': 'Büyüt',
'Exercise animations': 'Egzersiz animasyonları',
'Full': 'Tam',
'Small': 'Küçük',
'Hidden': 'Gizli',
'Invite code': 'Davet kodu',
'This app is invite-only — enter the code you were given.': 'Bu uygulama yalnızca davetle — sana verilen kodu gir.',
'An invite code is required': 'Bir davet kodu gerekli',
@@ -452,6 +463,32 @@ export default {
'That file is empty': 'Bu dosya boş',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': 'Sütunlar tanınmadı — desteklenen uygulamalar için belgelere bak.',
'Nothing to import from that file': 'Bu dosyada içe aktarılacak bir şey yok',
// --- import from Hevy API ---
'Import from Hevy': 'Hevy’den içe aktar',
'Pull your history with a Hevy Pro API key': 'Hevy Pro API anahtarıyla geçmişini çek',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': 'Hevy Pro API anahtarıyla geçmişini çek. Anahtar yalnızca bu içe aktarım için kullanılır ve kaydedilmez.',
'Hevy API key': 'Hevy API anahtarı',
'Get your API key': 'API anahtarını al',
'Hevy → Settings → Developer': 'Hevy → Ayarlar → Developer',
'Paste your Hevy API key first': 'Önce Hevy API anahtarını yapıştır',
'Fetch from Hevy': 'Hevy’den getir',
'Fetching from Hevy…': 'Hevy’den getiriliyor…',
'Fetching exercises… ({0}/{1})': 'Egzersizler getiriliyor… ({0}/{1})',
'Fetching workouts… ({0}/{1})': 'Antrenmanlar getiriliyor… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': 'Tartımlar getiriliyor… ({0}/{1})',
'Matching exercises…': 'Egzersizler eşleştiriliyor…',
'Could not reach Hevy — check the key and try again': 'Hevy’ye ulaşılamadı — anahtarı kontrol edip tekrar dene',
'That Hevy API key was refused': 'Bu Hevy API anahtarı reddedildi',
'Nothing to import from Hevy': 'Hevy’den içe aktarılacak bir şey yok',
'Import workouts': 'Antrenmanları içe aktar',
'Import routines': 'Rutinleri içe aktar',
'{0} routines · {1} exercises — added as new plans': '{0} rutin · {1} egzersiz — yeni plan olarak eklenir',
'{0} routines imported': '{0} rutin içe aktarıldı',
'Fetching routines… ({0}/{1})': 'Rutinler getiriliyor… ({0}/{1})',
'Routines': 'Rutinler',
'Import weigh-ins': 'Tartımları içe aktar',
'{0} new · {1} days already here': '{0} yeni · {1} gün zaten var',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy ağırlıkları kg olarak saklar — {0} birimine çevrilecek.',
// --- mobile build ---
'Your data': 'Verileriniz',
'All data stays on this phone': 'Tüm veriler bu telefonda kalır',
@@ -519,7 +556,11 @@ export default {
'Step ({0})': 'Artış ({0})',
'Step (seconds)': 'Artış (saniye)',
'Reps from': 'Tekrar en az',
'Reps up to': 'Tekrar en çok',
'No automatic progression': 'Otomatik ilerleme yok',
'Exclude from automatic progression': 'Otomatik ilerlemeden hariç tut',
'Use for planned deloads. Workouts stay in history and statistics.': 'Planlı deloadlar için kullanın. Antrenmanlar geçmişte ve istatistiklerde kalır.',
'The next regular target continues from the last included workout.': 'Sonraki normal hedef, dahil edilen son antrenmandan devam eder.',
'Linear progression': 'Doğrusal ilerleme',
'Greyskull LP': 'Greyskull LP',
'Double progression': 'Çift ilerleme',
@@ -860,7 +901,6 @@ export default {
'Avoid: {0}': 'Kaçınılacaklar: {0}',
'Before we start': 'Başlamadan önce',
'Building your plan…': 'Planın hazırlanıyor…',
'Continue': 'Devam',
'Discarded. Tell me what was off and I will build a different one.': 'Vazgeçildi. Neyin uymadığını söyle, farklı bir tane hazırlayayım.',
'Done — your plan is back to how it was before my last changes.': 'Tamam — planın son değişikliklerimden önceki haline döndü.',
'Edit my answers': 'Cevaplarımı düzenle',
@@ -1018,6 +1058,20 @@ export default {
'What should change?': 'Ne değişmeli?',
'Coach is thinking…': 'Koç düşünüyor…',
'Message the Coach…': 'Koça yaz…',
'Open progression settings': 'İlerleme ayarlarını aç',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy istekleri sınırlıyor — bir dakika bekleyip tekrar deneyin',
// --- log a past workout ---
'Log a past workout': 'Geçmiş bir antrenman kaydet',
'Logged on the usual workout screen, without timers.': 'Her zamanki antrenman ekranında kaydedilir, sadece zamanlayıcı olmadan.',
'Date': 'Tarih',
'Start time': 'Başlangıç saati',
'Continue': 'Devam',
'Pick a day up to today': 'Bugüne kadar bir gün seç',
'There is already a workout on that day.': 'O gün zaten bir antrenman var.',
'Replace': 'Değiştir',
'Add as second workout': 'İkinci antrenman olarak ekle',
'Finish the current workout first.': 'Önce mevcut antrenmanı bitir.',
'Logging a past workout — no rest timers.': 'Geçmiş antrenman kaydediliyor — dinlenme zamanlayıcısı yok.',
// --- bar weight (plate math) ---
'Bar weight': 'Bar ağırlığı',
'Bar ({0})': 'Bar ({0})',
+59 -5
View File
@@ -4,7 +4,6 @@ export default {
'Cancel': '取消',
'Press back again to exit': '再按一次返回退出',
'Delete': '删除',
'Save': '保存',
'Import': '导入',
'Discard': '放弃',
'All': '全部',
@@ -35,6 +34,8 @@ export default {
'rescheduled': '已改期',
'Prev': '上一个',
'Next': '下一个',
'Move up': '上移',
'Move down': '下移',
'Sunday': '星期日', 'Monday': '星期一', 'Tuesday': '星期二', 'Wednesday': '星期三',
'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六',
'Su': '日', 'Mo': '一', 'Tu': '二', 'We': '三', 'Th': '四', 'Fr': '五', 'Sa': '六',
@@ -91,6 +92,12 @@ export default {
'Weight ({0})': '重量({0})',
'Add to routine': '加入训练日',
'Remove exercise': '移除动作',
'Swap exercise': '更换动作',
'Swap exercise?': '要更换动作吗?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.': '已记录的组数会保留在原动作上。请选择替换动作的位置。',
'Keep replacement in this group': '将替换动作保留在此组',
'Insert after this group': '插入到此组之后',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.': '已记录的组数会保留在原动作上。替换动作将插入其后。',
'Remove {0}?': '移除 {0}?',
'The sets you logged for this exercise in this session will be lost.': '本次训练中为该动作记录的组数将丢失。',
'This removes the exercise from your current session.': '这会从当前训练中移除该动作。',
@@ -131,7 +138,6 @@ export default {
'Tracked — next time starts at {0}': '已记录——下次从 {0} 开始',
"That's the whole workout!": '训练全部完成!',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': '所有动作都完成了——干得漂亮!结束训练,或继续添加新动作。',
'Finish workout': '结束训练',
'Continue workout': '继续训练',
'Keep going — tap “+ Add exercise” below': '继续加油 ——点按下方“+ 添加动作”',
'Workout complete!': '训练完成!',
@@ -166,11 +172,11 @@ export default {
'Add set': '加一组',
'+ Drop': '+ 递减组',
'+ Burst': '+ 爆发组',
'Drop {0}': '递减组 {0}',
'Burst {0}': '爆发组 {0}',
'Remove drop': '移除递减组',
'Remove burst': '移除爆发组',
'Rest (s)': '休息(秒)',
'Rest after each set of this exercise. Leave at 0 to use your default rest timer.': '这个动作每组之后的休息时间。留在 0 就使用默认的休息计时。',
'Drop-set / rest-pause': '递减组 / 歇息暂停组',
'Intensifier': '强化技巧',
'None': '无',
@@ -220,7 +226,6 @@ export default {
'No data yet': '暂无数据',
'Your weekly routine': '你的每周安排',
'Week schedule': '每周日程',
'Routines': '训练日',
'No routines yet.': '还没有训练日。',
'Create one or load the starter plan.': '创建一个或加载入门计划。',
'Load starter plan (Push / Pull / Legs)': '加载入门计划(推 / 拉 / 腿)',
@@ -283,8 +288,10 @@ export default {
'Keep screen awake': '保持屏幕常亮',
'The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.': '训练进行时屏幕保持常亮,组间无需再解锁手机。',
'Weight unit': '重量单位',
'Week starts on': '一周开始于',
'Rest timer': '休息计时',
'Sounds': '声音',
'Flash screen when timer ends': '计时结束时闪烁屏幕',
'Note: switching units only changes the label — logged numbers are not converted.': '注意:切换单位只改变标签——已记录的数字不会换算。',
'Data': '数据',
'Export backup (JSON)': '导出备份(JSON)',
@@ -386,6 +393,10 @@ export default {
'Remove from routine': '从计划中移除',
'Minimize': '缩小',
'Expand': '放大',
'Exercise animations': '动作动画',
'Full': '完整',
'Small': '小',
'Hidden': '隐藏',
'Invite code': '邀请码',
'This app is invite-only — enter the code you were given.': '此应用仅限邀请——请输入你收到的邀请码。',
'An invite code is required': '需要邀请码',
@@ -452,6 +463,32 @@ export default {
'That file is empty': '该文件是空的',
'That file\'s columns aren\'t recognised — see the docs for supported apps.': '无法识别该文件的列 — 支持的应用请见文档。',
'Nothing to import from that file': '该文件中没有可导入的内容',
// --- import from Hevy API ---
'Import from Hevy': '从 Hevy 导入',
'Pull your history with a Hevy Pro API key': '使用 Hevy Pro API 密钥拉取训练记录',
'Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.': '使用 Hevy Pro API 密钥拉取训练记录。密钥仅用于本次导入,不会保存。',
'Hevy API key': 'Hevy API 密钥',
'Get your API key': '获取 API 密钥',
'Hevy → Settings → Developer': 'Hevy → 设置 → Developer',
'Paste your Hevy API key first': '请先粘贴 Hevy API 密钥',
'Fetch from Hevy': '从 Hevy 获取',
'Fetching from Hevy…': '正在从 Hevy 获取…',
'Fetching exercises… ({0}/{1})': '正在获取动作… ({0}/{1})',
'Fetching workouts… ({0}/{1})': '正在获取训练… ({0}/{1})',
'Fetching weigh-ins… ({0}/{1})': '正在获取体重… ({0}/{1})',
'Matching exercises…': '正在匹配动作…',
'Could not reach Hevy — check the key and try again': '无法连接 Hevy — 请检查密钥后重试',
'That Hevy API key was refused': '该 Hevy API 密钥被拒绝',
'Nothing to import from Hevy': 'Hevy 没有可导入的内容',
'Import workouts': '导入训练',
'Import routines': '导入训练计划',
'{0} routines · {1} exercises — added as new plans': '{0} 个计划 · {1} 个动作 — 作为新计划添加',
'{0} routines imported': '已导入 {0} 个训练计划',
'Fetching routines… ({0}/{1})': '正在获取计划… ({0}/{1})',
'Routines': '训练计划',
'Import weigh-ins': '导入体重',
'{0} new · {1} days already here': '{0} 条新记录 · {1} 天已有数据',
'Hevy stores weights in kg — they will be converted to {0}.': 'Hevy 以公斤存储重量 — 将换算为 {0}。',
// --- mobile build ---
'Your data': '你的数据',
'All data stays on this phone': '所有数据都保存在这部手机上',
@@ -519,7 +556,11 @@ export default {
'Step ({0})': '加量({0})',
'Step (seconds)': '加量(秒)',
'Reps from': '次数下限',
'Reps up to': '次数上限',
'No automatic progression': '不自动进阶',
'Exclude from automatic progression': '不计入自动进阶',
'Use for planned deloads. Workouts stay in history and statistics.': '用于计划性减载。训练仍保留在历史记录和统计中。',
'The next regular target continues from the last included workout.': '下一个常规目标从上一次计入的训练继续。',
'Linear progression': '线性进阶',
'Greyskull LP': 'Greyskull LP',
'Double progression': '双重进阶',
@@ -860,7 +901,6 @@ export default {
'Avoid: {0}': '避免:{0}',
'Before we start': '开始之前',
'Building your plan…': '正在制定你的计划…',
'Continue': '继续',
'Discarded. Tell me what was off and I will build a different one.': '已放弃。告诉我哪里不合适,我会重新制定一个。',
'Done — your plan is back to how it was before my last changes.': '完成——你的计划已恢复到我上次更改之前的状态。',
'Edit my answers': '编辑我的回答',
@@ -1018,6 +1058,20 @@ export default {
'What should change?': '需要改什么?',
'Coach is thinking…': '教练思考中…',
'Message the Coach…': '给教练留言…',
'Open progression settings': '打开进阶设置',
'Hevy is rate-limiting requests — wait a minute and try again': 'Hevy 正在限制请求——请稍等一分钟后重试',
// --- log a past workout ---
'Log a past workout': '补记过去的训练',
'Logged on the usual workout screen, without timers.': '在平时的训练界面记录,只是没有计时器。',
'Date': '日期',
'Start time': '开始时间',
'Continue': '继续',
'Pick a day up to today': '请选择今天或之前的日期',
'There is already a workout on that day.': '那天已经有一次训练了。',
'Replace': '替换',
'Add as second workout': '添加为第二次训练',
'Finish the current workout first.': '请先完成当前训练。',
'Logging a past workout — no rest timers.': '正在补记过去的训练 — 没有休息计时器。',
// --- bar weight (plate math) ---
'Bar weight': '杠铃杆重量',
'Bar ({0})': '杆 ({0})',
+3
View File
@@ -4,6 +4,9 @@ import App from './App.jsx'
import { MOBILE } from './lib/mobile.js'
import './index.css'
// App.jsx restores per-route scroll itself; the browser's own attempt races it.
if ('scrollRestoration' in history) history.scrollRestoration = 'manual'
createRoot(document.getElementById('root')).render(
<StrictMode><App /></StrictMode>
)
+66
View File
@@ -0,0 +1,66 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createRoot } from 'react-dom/client'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { logPastWorkoutSheet } from './sheets.jsx'
import { todayISO } from './lib/format.js'
const mounted = []
function type(el, value) {
Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
el.dispatchEvent(new Event('input', { bubbles: true }))
}
function mountTopSheet() {
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 button = (host, text) => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text)
describe('log a past workout', () => {
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
useUI.setState({ sheets: [], toasts: [] })
useStore.setState(s => ({ S: { ...s.S, active: null, routines: [], workouts: [{ id: 'old', d: todayISO(), start: 1, end: 2, name: 'Old', entries: [], prs: [] }] } }))
document.body.innerHTML = ''
})
afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
it('refuses while a workout is running', () => {
const toast = vi.fn()
useUI.setState({ toast })
useStore.setState(s => ({ S: { ...s.S, active: { id: 'a', entries: [] } } }))
logPastWorkoutSheet()
expect(useUI.getState().sheets).toHaveLength(0)
expect(toast).toHaveBeenCalledWith('Finish the current workout first.')
})
it('asks what to do when the day already has a workout', () => {
logPastWorkoutSheet()
const host = mountTopSheet()
expect(host.querySelector('h3').textContent).toBe('Log a past workout')
act(() => { type(host.querySelector('input[type=date]'), todayISO()) })
act(() => { button(host, 'Continue').click() })
const prompt = mountTopSheet()
expect(prompt.textContent).toContain('There is already a workout on that day.')
expect(['Replace', 'Add as second workout', 'Cancel'].map(t => !!button(prompt, t))).toEqual([true, true, true])
expect(useStore.getState().S.active).toBeNull()
})
it('starts a backfilled session straight away on a free day', () => {
logPastWorkoutSheet()
const host = mountTopSheet()
act(() => { type(host.querySelector('input[type=date]'), '2020-01-02') })
act(() => { button(host, 'Continue').click() })
const A = useStore.getState().S.active
expect(A.d).toBe('2020-01-02')
expect(new Date(A.start).getHours()).toBe(18)
expect(A.backfill).toEqual({ durationMin: 60, replaceId: null })
})
})
+490 -63
View File
@@ -3,7 +3,7 @@ import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js'
import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js'
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, uid, exCount, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { fmtDate, fmtNum, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js'
import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride } from './lib/bar.js'
import { beep, vibrate } from './lib/sound.js'
@@ -18,12 +18,19 @@ import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'
import BodyMap from './components/BodyMap.jsx'
import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, normalizeMuscleGroups, hasExplicitMuscleMetadata } from './lib/muscles.js'
import { parseImport, mergeImport } from './lib/import-csv.js'
import { importHevyData, HevyApiError, HEVY_DEV_SETTINGS, mergeHevyRoutines } from './lib/import-hevy.js'
import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'
import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'
import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS } from './lib/progression.js'
import { normalizeRepRange } from './lib/rep-range.js'
import { MOBILE, shareExport } from './lib/mobile.js'
import { buildCompletedWorkout } from './lib/finish-workout.js'
import { isWarmupRow } from './lib/workout-model.js'
import { nextUnfinishedUnit } from './lib/supersetFlow.js'
import { swapActiveExercise } from './lib/active-exercise-swap.js'
import { useSheetKeyboard, useRevealActiveChip, tappable } from './lib/use-sheet-keyboard.js'
import { buildSessionEntries } from './lib/session-start.js'
import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js'
const S = () => useStore.getState().S
const update = (...a) => useStore.getState().update(...a)
@@ -239,6 +246,204 @@ export function importFromApp(file, onDone) {
rd.readAsText(file)
}
/* ============================ import from Hevy API ============================ */
// The key lives in React state for this sheet only — dismissed with the sheet, never
// written to the store / localStorage / the server. After a successful fetch the user
// picks workouts and/or weigh-ins before anything is merged.
export function importFromHevy() {
ui().openSheet(close => <HevyImportSheet close={close} />)
}
function hevyProgressLabel(p) {
if (!p) return t('Fetching from Hevy…')
if (p.stage === 'templates') return t('Fetching exercises… ({0}/{1})', p.page, p.pageCount)
if (p.stage === 'workouts') return t('Fetching workouts… ({0}/{1})', p.page, p.pageCount)
if (p.stage === 'routines') return t('Fetching routines… ({0}/{1})', p.page, p.pageCount)
if (p.stage === 'body') return t('Fetching weigh-ins… ({0}/{1})', p.page, p.pageCount)
if (p.stage === 'parse') return t('Matching exercises…')
return t('Fetching from Hevy…')
}
function HevyImportSheet({ close }) {
const st = useStore(s => s.S)
const [apiKey, setApiKey] = useState('')
const [busy, setBusy] = useState(false)
const [progress, setProgress] = useState(null)
const [payload, setPayload] = useState(null) // { workouts, routines, bodyweight }
const [wantWorkouts, setWantWorkouts] = useState(true)
const [wantRoutines, setWantRoutines] = useState(true)
const [wantBody, setWantBody] = useState(true)
const keyRef = useRef(null)
// Drop the key from memory when the sheet goes away (unmount or successful import).
useEffect(() => () => { setApiKey('') }, [])
const wipeKey = () => { setApiKey(''); if (keyRef.current) keyRef.current.value = '' }
const fetchAccount = async () => {
const key = apiKey.trim()
if (!key) { toast(t('Paste your Hevy API key first')); return }
setBusy(true)
setProgress({ stage: 'templates', page: 1, pageCount: 1 })
setPayload(null)
try {
const data = await importHevyData(key, { unit: st.unit, onProgress: setProgress })
wipeKey()
const empty = !data.workouts.workouts.length && !data.routines.routines.length && !data.bodyweight.bodyweight.length
if (empty) {
toast(t('Nothing to import from Hevy'))
return
}
setWantWorkouts(!!data.workouts.workouts.length)
setWantRoutines(!!data.routines.routines.length)
setWantBody(!!data.bodyweight.bodyweight.length)
setPayload(data)
} catch (e) {
if (e instanceof HevyApiError && e.message === 'auth') toast(t('That Hevy API key was refused'))
else if (e instanceof HevyApiError && e.message === 'rate-limit') toast(t('Hevy is rate-limiting requests — wait a minute and try again'))
else if (e instanceof HevyApiError && e.message === 'empty') toast(t('Paste your Hevy API key first'))
else toast(t('Could not reach Hevy — check the key and try again'))
} finally {
setBusy(false)
setProgress(null)
}
}
const doImport = () => {
if (!payload) return
const parts = []
let addedW = 0, addedR = 0, addedB = 0
update(s => {
if (wantWorkouts && payload.workouts.workouts.length) {
const res = mergeImport(s, payload.workouts)
addedW = res.added
parts.push(t('{0} workouts imported', res.added))
}
if (wantRoutines && payload.routines.routines.length) {
const res = mergeHevyRoutines(s, payload.routines)
addedR = res.added
parts.push(t('{0} routines imported', res.added))
}
if (wantBody && payload.bodyweight.bodyweight.length) {
const res = mergeImport(s, payload.bodyweight)
addedB = res.added
parts.push(t('{0} weigh-ins imported', res.added))
}
})
close()
if (!addedW && !addedR && !addedB) toast(t('Nothing new to import'))
else toast(parts.join(' · '))
}
if (!payload) {
return <>
<h3>{t('Import from Hevy')}</h3>
<div className="muted small" style={{ marginBottom: 14, lineHeight: 1.5 }}>
{t('Pull your history with a Hevy Pro API key. The key is only used for this import and is not saved.')}
</div>
<label className="small dim" style={{ display: 'block', marginBottom: 6 }}>{t('Hevy API key')}</label>
<TextField
ref={keyRef}
type="password"
autoComplete="off"
spellCheck={false}
placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
value={apiKey}
disabled={busy}
onChange={e => setApiKey(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && !busy) fetchAccount() }}
/>
<div className="small" style={{ margin: '10px 0 16px', lineHeight: 1.45 }}>
<a href={HEVY_DEV_SETTINGS} target="_blank" rel="noopener noreferrer">{t('Get your API key')}</a>
<span className="dim"> — {t('Hevy → Settings → Developer')}</span>
</div>
{busy && <div className="small dim" style={{ marginBottom: 12 }}>{hevyProgressLabel(progress)}</div>}
<Button variant="primary" onClick={fetchAccount} disabled={busy || !apiKey.trim()}>
{busy ? t('Fetching from Hevy…') : t('Fetch from Hevy')}
</Button>
<div style={{ height: 8 }} />
<Button variant="ghost" className="dim" onClick={close} disabled={busy}>{t('Cancel')}</Button>
</>
}
const w = payload.workouts
const r = payload.routines
const b = payload.bodyweight
const haveW = w.workouts.filter(x => st.workouts.some(y => y.d === x.d)).length
const freshW = w.workouts.length - haveW
const haveB = b.bodyweight.filter(x => st.bodyweight.some(y => y.d === x.d)).length
const freshB = b.bodyweight.length - haveB
// Routines are always added as new copies (same as plan import).
const freshR = r.routines.length
const canImport = (wantWorkouts && freshW > 0) || (wantRoutines && freshR > 0) || (wantBody && freshB > 0)
const unmatched = [...new Set([
...(wantWorkouts ? w.unmatchedNames : []),
...(wantRoutines ? r.unmatchedNames : []),
])].sort()
return <>
<h3>{t('Import from Hevy')}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>
{w.from && (w.from === w.to ? fmtDate(w.from, true) : fmtDate(w.from, true) + ' – ' + fmtDate(w.to, true))}
{!w.from && b.from && (b.from === b.to ? fmtDate(b.from, true) : fmtDate(b.from, true) + ' – ' + fmtDate(b.to, true))}
</div>
<div className="tiles" style={{ textAlign: 'left' }}>
<div className="tile"><div className="l">{t('Workouts')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{w.workouts.length}</div></div>
<div className="tile"><div className="l">{t('Routines')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{r.routines.length}</div></div>
<div className="tile"><div className="l">{t('Exercises matched')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{w.matched + r.matched}</div></div>
<div className="tile"><div className="l">{t('Added as your own')}</div><div className="v" style={{ fontSize: '1.1rem' }}>{w.created + r.created}</div></div>
</div>
{w.workouts.length > 0 && <div className="row between" style={{ padding: '10px 2px', borderTop: '1px solid var(--sep)', gap: 12 }}>
<div>
<div className="tt" style={{ fontSize: 15 }}>{t('Import workouts')}</div>
<div className="small dim">{t('{0} new · {1} days already here', freshW, haveW)}</div>
</div>
<Switch checked={wantWorkouts} onChange={setWantWorkouts} />
</div>}
{r.routines.length > 0 && <div className="row between" style={{ padding: '10px 2px', borderTop: '1px solid var(--sep)', gap: 12 }}>
<div>
<div className="tt" style={{ fontSize: 15 }}>{t('Import routines')}</div>
<div className="small dim">{t('{0} routines · {1} exercises — added as new plans', freshR, r.exerciseCount)}</div>
</div>
<Switch checked={wantRoutines} onChange={setWantRoutines} />
</div>}
{b.bodyweight.length > 0 && <div className="row between" style={{ padding: '10px 2px', borderTop: '1px solid var(--sep)', borderBottom: '1px solid var(--sep)', gap: 12, marginBottom: 8 }}>
<div>
<div className="tt" style={{ fontSize: 15 }}>{t('Import weigh-ins')}</div>
<div className="small dim">{t('{0} new · {1} days already here', freshB, haveB)}</div>
</div>
<Switch checked={wantBody} onChange={setWantBody} />
</div>}
{!b.bodyweight.length && <div style={{ borderBottom: '1px solid var(--sep)', marginBottom: 8 }} />}
{(w.converted || r.converted) && <div className="small" style={{ color: 'var(--yellow)', marginBottom: 10 }}>
{t('Hevy stores weights in kg — they will be converted to {0}.', st.unit)}
</div>}
{wantWorkouts && (w.rirSets + w.rpeSets) > 0 && <div className="small dim" style={{ marginBottom: 10 }}>
{t(effortOf(st) === 'none'
? '{0} sets bring an {1} with them — switch on Effort per set in Settings to see it.'
: '{0} sets bring an {1} with them.',
w.rirSets || w.rpeSets, w.rirSets ? 'RIR' : 'RPE')}
</div>}
{unmatched.length > 0 && <>
<h4 className="sec">{t('Not in the library — added as your own exercises')}</h4>
<div className="mchips" style={{ marginBottom: 12 }}>
{unmatched.slice(0, 12).map(n => <span key={n} className="mchip capitalize">{n}</span>)}
{unmatched.length > 12 && <span className="mchip">+{unmatched.length - 12}</span>}
</div>
</>}
<Button variant="primary" onClick={doImport} disabled={!canImport}>
{canImport ? t('Import') : t('Nothing new to import')}
</Button>
<div style={{ height: 8 }} />
<Button variant="ghost" className="dim" onClick={() => { setPayload(null); wipeKey() }}>{t('Back')}</Button>
</>
}
/* ============================ target weight ============================ */
export function bwDeltaColor(delta, currentW) {
if (!delta) return 'var(--label-2)'
@@ -384,12 +589,12 @@ function AddToRoutine({ ex, close }) {
<h3 className="capitalize">{t('Add “{0}”', exerciseNameFor(ex))}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Pick a routine — sets, reps & weight come next.')}</div>
<div className="list">
{st.routines.map(r => <div key={r.id} className="item" onClick={() => pick(r.id)}>
{st.routines.map(r => <div key={r.id} className="item" {...tappable(() => pick(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>
{r.ex.some(e => e.id === ex.id) && <span className="tag">{t('already in')}</span>}<Icon name="plus" className="chev" />
</div>)}
<div className="item" onClick={() => pick('_new')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="sparkles" /></span>
<div className="item" {...tappable(() => pick('_new'))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="sparkles" /></span>
<div className="grow"><div className="tt">{t('New routine')}</div><div className="ss">{t('Create one and start with this exercise')}</div></div><Icon name="plus" className="chev" /></div>
</div>
</>
@@ -400,6 +605,8 @@ export const addToRoutineSheet = ex => ui().openSheet(close => <AddToRoutine ex=
// Name + body part is all it takes — the exercise then behaves like any built-in one
// (planning, logging, PRs, stats), just without an animation.
function CustomExForm({ existing, prefill, onDone, close }) {
const nameRef = useRef(null)
const onNameFocus = useSheetKeyboard(nameRef)
const [n, setN] = useState(existing ? existing.n : (prefill || ''))
const [bp, setBp] = useState(existing ? existing.bp : '')
const [desc, setDesc] = useState(existing ? (existing.desc || '') : '')
@@ -440,7 +647,7 @@ function CustomExForm({ existing, prefill, onDone, close }) {
return <>
<h3>{existing ? t('Edit custom exercise') : t('Create your own exercise')}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Name it and pick a body part — it behaves like any other exercise, just without an animation.')}</div>
<input className="input" placeholder={t('Exercise name')} value={n} onChange={e => setN(e.target.value)} />
<input ref={nameRef} className="input" placeholder={t('Exercise name')} value={n} onFocus={onNameFocus} onChange={e => setN(e.target.value)} />
<div className="chips" style={{ margin: '12px 0' }}>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => setBp(b)}>{t(b)}</button>)}
</div>
@@ -505,6 +712,9 @@ function ExercisePicker({ onPick, close }) {
const [eq, setEq] = useState('') // '' = any equipment
const [showAll, setShowAll] = useState(false)
const [shown, setShown] = useState(50)
const searchRef = useRef(null)
const bpStrip = useRef(null), eqStrip = useRef(null)
const onSearchFocus = useSheetKeyboard(searchRef)
const all = allExercises(st)
const profile = activeProfile(st)
let base = all.filter(e =>
@@ -517,10 +727,14 @@ function ExercisePicker({ onPick, close }) {
const eqOn = eqOpts.includes(eq) ? eq : ''
const f = eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered
const chosenCount = Object.keys(usage).length
useRevealActiveChip(bpStrip, bp)
useRevealActiveChip(eqStrip, eqOn)
return <>
<h3>{t('Add exercise')}</h3>
<div className="search"><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
<input className="input" placeholder={t('Search {0} exercises…', all.length)} value={q} onChange={e => { setQ(e.target.value); setShown(50) }} /></div>
{/* .picker-search is what index.css keys the keyboard-aware sheet layout on: the sheet
lifts above the keys and the search stays put while the list scrolls under it. */}
<div className="picker-search"><div className="search"><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
<input ref={searchRef} className="input" placeholder={t('Search {0} exercises…', all.length)} value={q} onFocus={onSearchFocus} onChange={e => { setQ(e.target.value); setShown(50) }} /></div></div>
{profile && <div className="small dim row" style={{ margin: '8px 0 2px', gap: 6, alignItems: 'center' }}>
<Icon name="dumbbell" style={{ fontSize: 13 }} />
{showAll ? t('Showing all equipment') : t('Showing what you have in "{0}"', profile.name)}
@@ -528,21 +742,21 @@ function ExercisePicker({ onPick, close }) {
{showAll ? t('Filter by "{0}"', profile.name) : t('Show all equipment')}
</button>
</div>}
<div className="chips" style={{ margin: eqOpts.length > 1 ? '10px 0 6px' : '10px 0' }}>
<div className="chips" ref={bpStrip} style={{ margin: eqOpts.length > 1 ? '10px 0 6px' : '10px 0' }}>
{chosenCount > 0 && <button className={'chip' + (bp === '★' ? ' on' : '')} onClick={() => { setBp('★'); setEq(''); setShown(50) }}><Icon name="starFill" style={{ fontSize: 12, display: 'inline-block', marginRight: 4, verticalAlign: '-1px' }} />{t('Chosen')} ({chosenCount})</button>}
<button className={'chip nocap' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setEq(''); setShown(50) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setEq(''); setShown(50) }}>{t(b)}</button>)}
</div>
{eqOpts.length > 1 && <div className="chips" style={{ marginBottom: 10 }}>
{eqOpts.length > 1 && <div className="chips" ref={eqStrip} style={{ marginBottom: 10 }}>
<button className={'chip nocap' + (!eqOn ? ' on' : '')} onClick={() => { setEq(''); setShown(50) }}>{t('Any equipment')}</button>
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(50) }}>{t(x)}</button>)}
</div>}
<div className="list">
{bp !== '★' && <div className="item" onClick={() => customExSheet(null, ex => onPick(ex), q.trim())}>
{bp !== '★' && <div className="item" {...tappable(() => customExSheet(null, ex => onPick(ex), q.trim()))}>
<div className="thumb thumb-x"><Icon name="sparkles" /></div>
<div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, no animation')}</div></div><Icon name="plus" className="chev" />
</div>}
{f.slice(0, shown).map(e => <div key={e.id} className="item" onClick={() => onPick(e)}>
{f.slice(0, shown).map(e => <div key={e.id} className="item" {...tappable(() => onPick(e))}>
<Thumb ex={e} /><div className="grow"><div className="tt capitalize">{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
{usage[e.id] && <span className="tag acc"><Icon name="starFill" /></span>}<Icon name="plus" className="chev" />
</div>)}
@@ -553,6 +767,68 @@ function ExercisePicker({ onPick, close }) {
}
export const exercisePicker = onPick => ui().openSheet(close => <ExercisePicker onPick={onPick} close={close} />)
/** Start a safe swap for one exact active-workout occurrence. */
export function swapActiveWorkoutExercise(index) {
const active = S().active
if (!active?.entries?.[index]) return
const picker = exercisePicker(ex => exConfigSheet(ex, null, cfg => {
// The picker is a chooser here, not a stack you keep adding from: one swap, then back to
// the workout. (The add flow deliberately leaves it open.)
picker.close()
const full = { ...cfg, id: ex.id }
const st = S()
// Same rows the add flow builds: last time's loads and, in a planned session, the
// prescription — swapping barbell for dumbbell bench must not start you at an empty bar.
const freestyle = !st.active?.routineId
const step = defaultIncrement(ex.id, st.unit)
const plan = freestyle ? null : nextPrescription(st, full, st.routines.find(r => r.id === st.active.routineId))
const built = buildSets(st, full, { step, ...(freestyle ? { preferLast: true } : {}) })
const replacement = {
id: ex.id,
target: { ...cfg },
plan,
sets: applyIntensifierPlan(freestyle ? built : applyPrescription(built, plan, step), full)
}
const current = S().active?.entries?.[index]
if (!current) return
const apply = options => {
// A timed callback closes over entry/set indexes. Invalidate it, and the current rest,
// before the selected occurrence can be replaced or a new entry shifts those indexes.
ui().stopWork()
ui().stopRest()
update(state => { swapActiveExercise(state.active, index, replacement, options) }, true)
}
const logged = (current.sets || []).some(set => set.done === true)
if (!logged) { apply(); return }
if (current.sg) {
ui().openSheet(close => <>
<h3>{t('Swap exercise?')}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>
{t('Logged sets stay with the original exercise. Choose where the replacement belongs.')}
</div>
<Button variant="primary" onClick={() => { close(); apply({ loggedConfirmed: true, groupDisposition: 'keep' }) }}>
{t('Keep replacement in this group')}
</Button>
<div style={{ height: 8 }} />
<Button variant="ghost" onClick={() => { close(); apply({ loggedConfirmed: true, groupDisposition: 'detach' }) }}>
{t('Insert after this group')}
</Button>
</>)
return
}
confirmSheet({
title: t('Swap exercise?'),
message: t('Logged sets stay with the original exercise. The replacement will be inserted afterward.'),
confirmText: t('Continue'),
onConfirm: () => apply({ loggedConfirmed: true })
})
}))
}
/* ============================ equipment profiles ============================ */
// Create or edit one profile ("Home", "Gym", ...): a name plus a checklist of what you have.
function EquipmentProfileSheet({ profile, close }) {
@@ -601,25 +877,49 @@ export const equipmentProfileSheet = profile => ui().openSheet(close => <Equipme
// Progression settings for one exercise (issue #17). Shown inside the config sheet because
// "how does this lift go up" belongs next to sets and reps, not in a separate screen. Left
// on "follow the routine" it inherits, so most people never touch it.
function ProgressionFields({ ex, mode, c, setC, routine, unit }) {
const progressionStepOf = (c, mode, ex, unit) =>
c.inc >= 0 ? c.inc : (mode === 'time' ? 5 : defaultIncrement(ex.id, unit))
const progressionStepIsValid = (step, policy) =>
policy === 'off' || (Number.isFinite(step) && step > 0)
function ProgressionFields({ ex, mode, c, setC, routine, unit, perSide }) {
const options = POLICIES_FOR[mode] || ['off']
if (options.length < 2) return null
const inherited = policyFor({ id: ex.id }, routine, mode)
const active = policyFor({ ...c, id: ex.id }, routine, mode)
const inc = c.inc > 0 ? c.inc : (mode === 'time' ? 5 : defaultIncrement(ex.id, unit))
const inc = progressionStepOf(c, mode, ex, unit)
const invalid = !progressionStepIsValid(inc, active)
const stride = mode === 'reps' && perSide ? 2 : 1
const range = active === 'double' ? normalizeRepRange(c.reps, c.repsMin, stride) : null
const setRule = v => setC(x => {
const next = { ...x, prog: v || undefined }
return policyFor({ ...next, id: ex.id }, routine, mode) === 'double'
? { ...next, ...normalizeRepRange(next.reps, next.repsMin, stride) }
: next
})
return <>
<h4 className="sec">{t('Progression')}</h4>
<div className="sect-b" style={{ marginBottom: 8 }}>
<SelectRow title={t('Rule')} sheetTitle={t('Progression')} value={c.prog || ''} onChange={v => setC(x => ({ ...x, prog: v || undefined }))}
<SelectRow title={t('Rule')} sheetTitle={t('Progression')} value={c.prog || ''} onChange={setRule}
options={[{ value: '', label: t('Follow the routine ({0})', t(POLICY_NAME[inherited])) },
...options.map(p => ({ value: p, label: t(POLICY_NAME[p]) }))]} />
</div>
<div className="small dim" style={{ marginBottom: active === 'off' ? 18 : 10 }}>{t(POLICY_DESC[active])}</div>
{active !== 'off' && <div className="row cfgrow" style={{ marginBottom: 18 }}>
<Stepper label={mode === 'time' ? t('Step (seconds)') : t('Step ({0})', unit)} value={inc}
step={mode === 'time' ? 5 : 1.25} decimal={mode !== 'time'} onChange={v => setC(x => ({ ...x, inc: v }))} />
{active === 'double' && <Stepper label={t('Reps from')} value={c.repsMin || Math.max(1, (c.reps || 10) - 2)}
step={1} decimal={false} onChange={v => setC(x => ({ ...x, repsMin: v }))} />}
step={mode === 'time' ? 5 : 1.25} decimal={mode !== 'time'} invalid={invalid} className={invalid ? 'invalid' : ''}
onChange={v => setC(x => ({ ...x, inc: v }))} />
{active === 'double' && <>
{/* The draft stays as typed: normalising on every keystroke turned "12" into 92 (the
"1" was pulled above the lower bound first). Save and the engine normalise anyway. */}
<Stepper label={t('Reps from')} value={c.repsMin ?? range.repsMin} step={stride} decimal={false}
onChange={v => setC(x => ({ ...x, repsMin: v }))} />
<Stepper label={t('Reps up to')} value={c.reps ?? range.reps} step={stride} decimal={false}
onChange={v => setC(x => ({ ...x, reps: v }))} />
</>}
</div>}
{invalid && <div className="small" role="alert" style={{ color: 'var(--red)', marginTop: -10, marginBottom: 18 }}>
{t('Enter a positive step to use this progression rule.')}
</div>}
</>
}
@@ -627,16 +927,32 @@ function ProgressionFields({ ex, mode, c, setC, routine, unit }) {
function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
const st = useStore(s => s.S)
const cardio = isCardio(ex.id)
const [c, setC] = useState(existing || initial || defaultConfig(ex.id))
const seed = existing || initial || defaultConfig(ex.id)
const [c, setC] = useState(() => {
const cfg = { ...seed }
return policyFor({ ...cfg, id: ex.id }, routine, modeOf({ ...cfg, id: ex.id })) === 'double'
? { ...cfg, ...normalizeRepRange(cfg.reps, cfg.repsMin, isPerSide(cfg) ? 2 : 1) }
: cfg
})
// Cardio keeps its own duration+speed form; the reps/time choice (issue #16) is offered for
// everything else, which is where the gap was — planks, hangs, wall sits, loaded carries.
const mode = cardio ? 'cardio' : modeOf({ ...c, id: ex.id })
// Both default from the dataset and are then whatever the config says — see isBw.
const bw = !cardio && isBw({ ...c, id: ex.id })
const perSide = isPerSide(c)
const progressionPolicy = policyFor({ ...c, id: ex.id }, routine, mode)
const progressionStepInvalid = !progressionStepIsValid(progressionStepOf(c, mode, ex, st.unit), progressionPolicy)
const activePolicy = policyFor({ ...c, id: ex.id }, routine, mode)
const double = mode === 'reps' && activePolicy === 'double'
// Keep whatever the other mode already had (sets, weight) and fill only what is missing.
const setMode = m => setC(x => ({ ...defaultConfig(ex.id, m), ...x, mode: m }))
const setMode = m => setC(x => {
const next = { ...defaultConfig(ex.id, m), ...x, mode: m }
return m === 'reps' && policyFor({ ...next, id: ex.id }, routine, 'reps') === 'double'
? { ...next, ...normalizeRepRange(next.reps, next.repsMin, isPerSide(next) ? 2 : 1) }
: next
})
const save = () => {
if (progressionStepInvalid) return
close()
const sets = Math.max(1, Math.round(c.sets) || (cardio ? 1 : 3))
// Only carry progression settings that differ from the inherited default, so a plan file
@@ -660,15 +976,26 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
// shape it had — and reads back as 0 either way (buildSets).
const warmupSets = Math.max(0, Math.min(MAX_PLANNED_WARMUPS, Math.round(c.warmupSets) || 0))
const withWarmups = warmupSets ? { warmupSets } : {}
if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8), ...withNote })
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...prog, ...withNote, ...withWarmups })
// Per-exercise rest (issue #10): written only when a positive value was set, so 0 keeps
// inheriting the global rest timer and a config that never touched it stays the shape it
// was. Mode-independent — a heavy triple, a plank and a cardio interval all rest.
const restSec = Math.max(0, Math.round(c.restSec) || 0)
const withRest = restSec ? { restSec } : {}
if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8), ...withNote, ...withRest })
else if (mode === 'time') onSave({ sets, mode: 'time', sec: Math.max(1, Math.round(c.sec) || 45), weight: Math.max(0, c.weight || 0), ...flags, ...prog, ...withNote, ...withWarmups, ...withRest })
else {
// A unilateral target is stored even: the split has to divide, and a typed 15 would
// otherwise plan seven reps on one side and eight on the other, every session.
const typed = Math.max(1, Math.round(c.reps) || 10)
const reps = perSide ? Math.ceil(typed / 2) * 2 : typed
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog, ...withNote, ...withWarmups }
if (policyFor({ ...c, id: ex.id }, routine, 'reps') === 'double') out.repsMin = Math.min(reps, Math.max(1, Math.round(c.repsMin) || Math.max(1, reps - 2)))
const stride = perSide ? 2 : 1
let reps = perSide ? Math.ceil(typed / stride) * stride : typed
let range = null
if (double) {
range = normalizeRepRange(reps, c.repsMin, stride)
reps = range.reps
}
const out = { sets, mode: 'reps', reps, weight: Math.max(0, c.weight || 0), ...flags, ...(perSide ? { side: true } : {}), ...prog, ...withNote, ...withWarmups, ...withRest }
if (double) out.repsMin = range.repsMin
// A ceiling below the working reps would tell you to add a set on day one.
if (bw && !(out.weight > 0) && c.repsMax > 0) out.repsMax = Math.max(reps, Math.round(c.repsMax))
// Every set in this exercise becomes a drop-set/rest-pause (buildSets stamps the rows) —
@@ -708,7 +1035,7 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
rest-pause work set — so "Sets" has nothing left to mean and only invites a mismatch. */}
{c.intensifier?.type !== 'restpause' &&
<Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />}
<Stepper label={t('Reps')} value={c.reps} step={perSide ? 2 : 1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />
{!double && <Stepper label={t('Reps')} value={c.reps} step={perSide ? 2 : 1} decimal={false} onChange={v => setC(x => ({ ...x, reps: v }))} />}
{/* On bodyweight work the weight stepper is the click #32 is about, so it is not here
until there is a belt to describe — see the added-weight row below. */}
{!bw && <Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />}
@@ -734,6 +1061,16 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
{mode === 'time' && !bw && <div className="small dim" style={{ marginBottom: 18 }}>
{t('A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.')}
</div>}
{/* Per-exercise rest (issue #10). Its own full-width row, like the other steppers with an
explanation under them, and outside every mode branch because a heavy triple, a plank
and a cardio interval all rest — they just do not all want the same break. */}
<div className="row cfgrow" style={{ marginBottom: 6 }}>
<Stepper label={t('Rest (s)')} value={c.restSec || 0} step={15} decimal={false}
onChange={v => setC(x => ({ ...x, restSec: v }))} />
</div>
<div className="small dim" style={{ marginBottom: 18 }}>
{t('Rest after each set of this exercise. Leave at 0 to use your default rest timer.')}
</div>
{/* ---------- bodyweight + per side (issues #31/#32/#33) ---------- */}
{!cardio && <div className="sect-b" style={{ marginBottom: 8 }}>
<Row icon="figureStrength" iconTint="var(--acc)" title={t('Bodyweight')}
@@ -744,7 +1081,12 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
subtitle={perSide ? t('You still log the total: {0} is {1} per side.', c.reps || 0, fmtNum(sideReps(c.reps))) : t('For lunges, single-arm rows and the like.')}>
{/* Turning it on rounds the target up to an even number, since half of an odd
total is a rep one side does not get. */}
<Switch checked={perSide} onChange={v => setC(x => ({ ...x, side: v || undefined, reps: v ? Math.ceil((x.reps || 0) / 2) * 2 : x.reps }))} />
<Switch checked={perSide} onChange={v => setC(x => {
const next = { ...x, side: v || undefined, reps: v ? Math.ceil((x.reps || 0) / 2) * 2 : x.reps }
return policyFor({ ...next, id: ex.id }, routine, 'reps') === 'double'
? { ...next, ...normalizeRepRange(next.reps, next.repsMin, v ? 2 : 1) }
: next
})} />
</Row>}
</div>}
{/* A stepper is too wide to sit in a list row next to a label — it squeezes the text to
@@ -812,11 +1154,11 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
<h4 className="sec">{t('Bar weight')}</h4>
<BarWeightEditor ex={ex} extra={t('Applies to this exercise everywhere, not just this plan.')} />
</>}
<ProgressionFields ex={ex} mode={mode} c={c} setC={setC} routine={routine} unit={st.unit} />
<ProgressionFields ex={ex} mode={mode} c={c} setC={setC} routine={routine} unit={st.unit} perSide={perSide} />
<textarea className="input" rows={3} maxLength={500} style={{ marginBottom: 18 }}
placeholder={t('Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here')}
value={c.note || ''} onChange={e => setC(x => ({ ...x, note: e.target.value }))} />
<Button variant="primary" onClick={save}>{existing ? t('Save') : t('Add to routine')}</Button>
<Button variant="primary" disabled={progressionStepInvalid} onClick={save}>{existing ? t('Save') : t('Add to routine')}</Button>
{ex.custom && <><div style={{ height: 8 }} /><Button icon="pencil" onClick={() => { close(); customExSheet(ex) }}>{t('Edit or delete this exercise')}</Button></>}
{onDelete && <><div style={{ height: 8 }} /><Button variant="danger" onClick={() => { close(); onDelete() }}>{t('Remove from routine')}</Button></>}
</>
@@ -943,12 +1285,12 @@ function DayOverride({ iso, close }) {
<h3>{fmtDate(iso, true)}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Weekly plan:')} {weeklyR ? weeklyR.name : t('Rest')}{hasOvr && <span style={{ color: 'var(--orange)' }}> · {t('changed for this day')}</span>}<br />{t('Sick, missed a day or want a different session? Pick what to train instead.')}</div>
<div className="list">
{st.routines.map(r => <div key={r.id} className="item" onClick={() => set(r.id)}>
{st.routines.map(r => <div key={r.id} className="item" {...tappable(() => set(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>
{effId === r.id && <Icon name="check" className="accent" />}</div>)}
<div className="item" onClick={() => set('rest')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest / skip this day')}</div></div>{effId === null && <Icon name="check" className="accent" />}</div>
{hasOvr && <div className="item" onClick={() => set('')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="reset" /></span><div className="grow"><div className="tt">{t('Back to weekly plan')}</div></div></div>}
<div className="item" {...tappable(() => set('rest'))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest / skip this day')}</div></div>{effId === null && <Icon name="check" className="accent" />}</div>
{hasOvr && <div className="item" {...tappable(() => set(''))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="reset" /></span><div className="grow"><div className="tt">{t('Back to weekly plan')}</div></div></div>}
</div>
</>
}
@@ -960,8 +1302,8 @@ function DayAssign({ day, close }) {
return <>
<h3>{t(DAYN[day])}</h3>
<div className="list">
<div className="item" onClick={() => set('')}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest day')}</div></div>{!st.week[day] && <Icon name="check" className="accent" />}</div>
{st.routines.map(r => <div key={r.id} className="item" onClick={() => set(r.id)}>
<div className="item" {...tappable(() => set(''))}><span className="lrow-i" style={{ background: 'var(--surface-3)' }}><Icon name="moon" /></span><div className="grow"><div className="tt">{t('Rest day')}</div></div>{!st.week[day] && <Icon name="check" className="accent" />}</div>
{st.routines.map(r => <div key={r.id} className="item" {...tappable(() => set(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>
{st.week[day] === r.id && <Icon name="check" className="accent" />}</div>)}
@@ -972,6 +1314,8 @@ export const dayAssignSheet = day => ui().openSheet(close => <DayAssign day={day
/* ============================ workout detail ============================ */
function WorkoutDetail({ w, close }) {
const noteRef = useRef(null)
const onNoteFocus = useSheetKeyboard(noteRef)
const st = useStore(s => s.S)
const update = useStore(s => s.update)
// The session note is editable here rather than only at the finish sheet: what you want to
@@ -1014,9 +1358,9 @@ function WorkoutDetail({ w, close }) {
</div>
})}
<div className="small muted" style={{ margin: '4px 0 6px' }}>{t('Session note')}</div>
<textarea className="input" rows={2} maxLength={NOTE_MAX} value={note}
<textarea ref={noteRef} className="input" rows={2} maxLength={NOTE_MAX} value={note}
placeholder={t('How the session went as a whole.')}
onChange={e => setNote(e.target.value)} onBlur={saveNote} />
onFocus={onNoteFocus} onChange={e => setNote(e.target.value)} onBlur={saveNote} />
<div style={{ height: 14 }} />
<Button variant="danger" onClick={() => confirmSheet({ title: t('Delete workout?'), message: t('This removes it from your history for good.'), confirmText: t('Delete'), danger: true, onConfirm: () => { update(s => { s.workouts = s.workouts.filter(x => x.id !== w.id) }); close(); toast(t('Workout deleted')) } })}>{t('Delete workout')}</Button>
</>
@@ -1030,7 +1374,9 @@ function Calendar({ start, close }) {
const y = cur.getFullYear(), mo = cur.getMonth()
const byDay = {}
st.workouts.forEach(w => (byDay[w.d] = byDay[w.d] || []).push(w))
const startOffset = (new Date(y, mo, 1).getDay() + 6) % 7
// Which column the 1st sits in, and therefore how many blanks come before it.
const ws = weekStartOf(st)
const startOffset = weekDayOffset(new Date(y, mo, 1).getDay(), ws)
const daysIn = new Date(y, mo + 1, 0).getDate()
const monthWs = st.workouts.filter(w => w.d.startsWith(y + '-' + String(mo + 1).padStart(2, '0')))
const monthVol = monthWs.reduce((a, w) => a + (w.vol || 0), 0)
@@ -1054,7 +1400,7 @@ function Calendar({ start, close }) {
<button className="iconbtn" onClick={() => setCur(new Date(y, mo + 1, 1))} aria-label="Next month"><Icon name="chevronRight" /></button>
</div>
<div className="small muted" style={{ textAlign: 'center' }}>{monthWs.length ? `${t(monthWs.length === 1 ? '{0} workout' : '{0} workouts', monthWs.length)} · ${fmtDur(monthMs)} · ${fmtVol(monthVol, st.unit)}` : t('No workouts this month')}</div>
<div className="cal-grid">{['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'].map(l => <div key={l} className="cal-h">{t(l)}</div>)}{cells}</div>
<div className="cal-grid">{weekOrder(ws).map(d => <div key={d} className="cal-h">{t(DAYS[d])}</div>)}{cells}</div>
<div className="cal-legend">
<span><i style={{ background: 'var(--acc)' }} />{t('Trained')}</span>
<span><i style={{ background: 'var(--label-3)' }} />{t('Planned')}</span>
@@ -1069,7 +1415,7 @@ export const calendarSheet = start => ui().openSheet(close => <Calendar start={s
export function WorkoutRow({ w, onClick }) {
const st = useStore(s => s.S)
const glyph = glyphOf((st.routines.find(r => r.id === w.routineId) || {}).emoji)
return <div className="item" onClick={onClick}>
return <div className="item" {...tappable(onClick)}>
<span className="lrow-i" style={{ width: 34, height: 34, borderRadius: 8, fontSize: 19 }}><Icon name={glyph} /></span>
<div className="grow"><div className="tt">{w.name}</div>
<div className="ss">{[fmtDate(w.d, true), ...durPart(w.end - w.start), t('{0} sets', setsDone(w)), fmtVol(w.vol, st.unit)].join(' · ')}</div></div>
@@ -1085,17 +1431,87 @@ export function startFlow(routineId) {
export function beginWorkout(routineId, bw) {
const st = S()
const r = routineId ? st.routines.find(x => x.id === routineId) : null
// The prescription is applied as the session is built, so you walk up to the bar with the
// right weight already on the screen instead of being told about it afterwards. `plan` is
// kept on the entry purely so the workout can explain the number it chose.
const entries = (r ? r.ex : []).map(cfg => {
const plan = nextPrescription(st, cfg, r)
const step = defaultIncrement(cfg.id, st.unit)
const sets = applyIntensifierPlan(applyPrescription(buildSets(st, cfg, { step }), plan, step), cfg)
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets }
})
const { entries, excluded } = buildSessionEntries(st, r)
update(s => {
s.active = { id: uid(), d: todayISO(), start: Date.now(), routineId, name: r ? r.name : t('Freestyle'), bw: bw || null, cur: 0, entries }
s.active = {
id: uid(), d: todayISO(), start: Date.now(), routineId,
name: r ? r.name : t('Freestyle'), bw: bw || null, cur: 0, entries,
...(excluded ? { excludeFromProgression: true } : {})
}
})
useUI.getState().stopRest()
nav('/workout')
}
/* ============================ log a past workout ============================ */
// The same screen as a live session, pointed at another day. `backfill` on the active
// session is what tells the workout screen to drop the clock and the rest timers, and tells
// the finish path to file the workout where its date belongs instead of at the end.
function LogPastWorkout({ close }) {
const st = useStore(s => s.S)
const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1)
const [date, setDate] = useState(isoOf(yesterday))
const [time, setTime] = useState('18:00')
const [dur, setDur] = useState(60)
const [routineId, setRoutineId] = useState('')
const today = todayISO()
const options = [{ value: '', label: t('Freestyle') }, ...st.routines.map(r => ({ value: r.id, label: r.name }))]
const go = replaceId => {
close()
beginBackfill({ iso: date, time, durationMin: dur, routineId: routineId || null, replaceId })
}
const submit = () => {
if (!date || date > today) { toast(t('Pick a day up to today')); return }
const existing = workoutsOn(st, date)
if (!existing.length) { go(null); return }
ui().openSheet(c => <SameDayChoice iso={date} existing={existing} close={c}
onReplace={id => { c(); go(id) }} onAdd={() => { c(); go(null) }} />, { kind: 'center' })
}
return <>
<h3>{t('Log a past workout')}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{t('Logged on the usual workout screen, without timers.')}</div>
<Row icon="calendar" title={t('Date')}>
<input type="date" className="timef" value={date} max={today} onChange={e => setDate(e.target.value)} /></Row>
<Row icon="clock" title={t('Start time')}>
<input type="time" className="timef" value={time} onChange={e => setTime(e.target.value)} /></Row>
<Stepper label={t('Duration')} unit="min" value={dur} step={5} decimal={false} onChange={v => setDur(Math.max(1, Math.round(v)))} />
<div style={{ height: 8 }} />
<SelectRow icon="dumbbell" title={t('Routine')} value={routineId} options={options} onChange={setRoutineId} />
<div style={{ height: 18 }} />
<Button variant="primary" onClick={submit}>{t('Continue')}</Button>
</>
}
// Three ways out when the day already has a workout. Replacing with several on that day means
// picking which one; the rest of the day is left alone.
function SameDayChoice({ iso, existing, onReplace, onAdd, close }) {
return <div style={{ textAlign: 'center', padding: '4px 0' }}>
<h3 style={{ marginBottom: 8 }}>{fmtDate(iso, true)}</h3>
<div className="muted" style={{ marginBottom: 18, lineHeight: 1.5 }}>{t('There is already a workout on that day.')}</div>
{existing.map(w => <div key={w.id} style={{ marginBottom: 8 }}>
<button className="btn danger" onClick={() => onReplace(w.id)}>{existing.length > 1 ? t('Replace') + ' · ' + w.name : t('Replace')}</button>
</div>)}
<button className="btn primary" onClick={onAdd}>{t('Add as second workout')}</button>
<div style={{ height: 8 }} />
<Button variant="ghost" className="dim" onClick={close}>{t('Cancel')}</Button>
</div>
}
export function logPastWorkoutSheet() {
if (S().active) { toast(t('Finish the current workout first.')); return }
ui().openSheet(close => <LogPastWorkout close={close} />)
}
function beginBackfill({ iso, time, durationMin, routineId, replaceId }) {
const st = S()
const r = routineId ? st.routines.find(x => x.id === routineId) : null
const { entries, excluded } = buildSessionEntries(st, r)
update(s => {
s.active = {
id: uid(), d: iso, start: backfillStart(iso, time), routineId,
name: r ? r.name : t('Freestyle'), bw: null, cur: 0, entries,
backfill: { durationMin, replaceId: replaceId || null },
...(excluded ? { excludeFromProgression: true } : {})
}
})
useUI.getState().stopRest()
nav('/workout')
@@ -1118,8 +1534,8 @@ function TopWeight({ entryIdx, close }) {
const units = supersetUnits(A ? A.entries : [])
const unit = entry ? unitOf(units, entryIdx) : []
const unitDone = !!entry && unit.every(i => A.entries[i].sets.every(s => s.done))
const unitIdx = units.findIndex(u => u === unit)
const isLastUnit = unitIdx === units.length - 1
const nextUnit = unitDone ? nextUnfinishedUnit(A.entries, units, entryIdx) : null
const workoutDone = unitDone && !nextUnit
if (!entry || !ex) return null
const commit = advance => {
@@ -1132,8 +1548,8 @@ function TopWeight({ entryIdx, close }) {
})
close()
if (advance && unitDone) {
if (isLastUnit) workoutCompleteSheet() // whole workout done → finish/continue prompt
else update(s => { s.active.cur = units[unitIdx + 1][0] })
if (workoutDone) workoutCompleteSheet() // no unfinished unit → finish/continue prompt
else update(s => { s.active.cur = nextUnit[0] })
} else toast(t('Tracked — next time starts at {0}', fmtNum(S().exWeights[entry.id].w) + ' ' + st.unit))
}
return <>
@@ -1143,7 +1559,7 @@ function TopWeight({ entryIdx, close }) {
<div style={{ height: 10 }} />
{prevBest > 0 ? <div className="small dim" style={{ textAlign: 'center', marginBottom: 12 }}>{t('Previous best:')} {fmtNum(prevBest)} {st.unit}{maxSet > prevBest && <span style={{ color: 'var(--yellow)' }}> — {t('new record!')}</span>}</div> : <div style={{ height: 4 }} />}
{unitDone ? <>
<Button variant="primary" trailingIcon={isLastUnit ? null : 'chevronRight'} onClick={() => commit(true)}>{isLastUnit ? t('Save') : t('Save & next exercise')}</Button>
<Button variant="primary" trailingIcon={workoutDone ? null : 'chevronRight'} onClick={() => commit(true)}>{workoutDone ? t('Save') : t('Save & next exercise')}</Button>
<div style={{ height: 8 }} /><Button variant="ghost" className="dim" onClick={() => commit(false)}>{t('Just close')}</Button>
</> : <Button variant="primary" onClick={() => commit(false)}>{t('Save weight')}</Button>}
</>
@@ -1163,6 +1579,8 @@ export const topWeightSheet = entryIdx => ui().openSheet(close => <TopWeight ent
A routine's own `note` (a plan's instruction for this exercise) is edited in the config sheet
and is deliberately not here: it belongs to the plan, not to the day or to the movement. */
function ExerciseNote({ entryIdx, close }) {
const noteRef = useRef(null)
const onNoteFocus = useSheetKeyboard(noteRef)
const st = useStore(s => s.S)
const update = useStore(s => s.update)
const A = st.active
@@ -1193,9 +1611,9 @@ function ExerciseNote({ entryIdx, close }) {
return <>
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
<div className="small muted" style={{ marginBottom: 6 }}>{t('This session')}</div>
<textarea className="input" rows={3} maxLength={NOTE_MAX} value={note}
<textarea ref={noteRef} className="input" rows={3} maxLength={NOTE_MAX} value={note}
placeholder={t('How it went, what to change — kept with today’s workout.')}
onChange={e => setNote(e.target.value)} />
onFocus={onNoteFocus} onChange={e => setNote(e.target.value)} />
<div style={{ height: 10 }} />
<div className="sect-b">
<Row icon="flag" iconTint="var(--yellow)" title={t('Show this next time')}
@@ -1220,6 +1638,8 @@ export const exerciseNoteSheet = entryIdx => ui().openSheet(close => <ExerciseNo
fact because "notes you can write during a workout" is the point; a note you can only add
once the session is filed is a different, smaller feature. */
function SessionNote({ close }) {
const noteRef = useRef(null)
const onNoteFocus = useSheetKeyboard(noteRef)
const st = useStore(s => s.S)
const update = useStore(s => s.update)
const A = st.active
@@ -1235,9 +1655,9 @@ function SessionNote({ close }) {
return <>
<h3>{t('Session note')}</h3>
<textarea className="input" rows={4} maxLength={NOTE_MAX} value={note}
<textarea ref={noteRef} className="input" rows={4} maxLength={NOTE_MAX} value={note}
placeholder={t('How the session went as a whole.')}
onChange={e => setNote(e.target.value)} />
onFocus={onNoteFocus} onChange={e => setNote(e.target.value)} />
<div style={{ height: 18 }} />
<Button variant="primary" onClick={save}>{t('Save')}</Button>
</>
@@ -1296,9 +1716,12 @@ function doFinishWorkout() {
const st = S()
const A = st.active
if (!A) return
const past = !!A.backfill
const prs = []
const e1prs = []
A.entries.forEach(e => {
// A workout logged into the past cannot claim records against the history that came after
// it, so a backfilled session reports none and leaves the confirmed weights alone.
if (!past) A.entries.forEach(e => {
const mx = Math.max(0, ...e.sets.filter(s => s.done && !isWarmupRow(s)).map(s => s.w))
if (mx > 0 && mx > bestWeightFor(st, e.id)) prs.push(e.id)
// A heavier estimate without a heavier top set is its own kind of progress —
@@ -1307,17 +1730,21 @@ function doFinishWorkout() {
if (rec && !prs.includes(e.id)) e1prs.push({ id: e.id, ...rec })
})
const w = buildCompletedWorkout(A, {
end: Date.now(),
end: past ? backfillEnd(A) : Date.now(),
prs,
snapshotFor: e => EXIDX[e.id]?.custom ? exerciseMuscleSnapshot(EXIDX[e.id]) : null,
})
w.vol = workoutVolume(w)
update(s => {
w.entries.forEach(e => {
const mx = Math.max(0, ...e.sets.filter(x => x.done && !isWarmupRow(x)).map(x => x.w || 0), e.topW || 0)
if (mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: w.d } }
})
s.workouts.push(w)
if (past) {
s.workouts = completeBackfill(s.workouts, A, w)
} else {
w.entries.forEach(e => {
const mx = Math.max(0, ...e.sets.filter(x => x.done && !isWarmupRow(x)).map(x => x.w || 0), e.topW || 0)
if (mx > 0) { const cur = s.exWeights[e.id]; if (!cur || mx > cur.w) s.exWeights[e.id] = { w: mx, d: w.d } }
})
s.workouts.push(w)
}
s.active = null
})
useStore.getState().autoBackupNow()
+86
View File
@@ -0,0 +1,86 @@
// @vitest-environment happy-dom
import { LANGS } from './lib/i18n-core.js'
import { act } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { swapActiveWorkoutExercise } from './sheets.jsx'
import { EXDB } from './lib/exercises.js'
import { DEF, useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
const clone = value => JSON.parse(JSON.stringify(value))
const ids = EXDB.slice(0, 3).map(exercise => exercise.id)
function entry(id, done = false) {
return {
id,
target: { mode: 'reps', sets: 1, reps: 5, weight: 40 },
sets: [{ w: 40, r: 5, done }]
}
}
function installActive() {
const S = clone(DEF)
S.active = {
id: 'swap-test', d: '2026-08-27', start: Date.now(), routineId: null,
name: 'Swap test', bw: null, cur: 1,
entries: [entry(ids[0]), entry(ids[0]), entry(ids[1])]
}
useStore.setState({ S, user: null })
}
function submitSwap(index, exercise, config) {
swapActiveWorkoutExercise(index)
const picker = useUI.getState().sheets.at(-1)
const pickerView = picker.render(picker.close)
act(() => pickerView.props.onPick(exercise))
const configSheet = useUI.getState().sheets.at(-1)
const configView = configSheet.render(configSheet.close)
act(() => configView.props.onSave(config))
}
beforeEach(() => {
vi.useFakeTimers()
localStorage.clear()
useUI.getState().stopRest()
useUI.getState().stopWork()
useUI.setState({ sheets: [], timer: null, work: null })
installActive()
})
describe('active exercise swap sheet flow', () => {
it('invalidates a timed callback and replaces only the selected duplicate', () => {
const callback = vi.fn()
useUI.getState().startWork(5, 'Hold', callback)
submitSwap(1, EXDB[2], { mode: 'reps', sets: 2, reps: 8, weight: 30, note: 'New target' })
vi.advanceTimersByTime(10_000)
const active = useStore.getState().S.active
expect(useUI.getState().work).toBeNull()
expect(callback).not.toHaveBeenCalled()
expect(active.entries.map(value => value.id)).toEqual([ids[0], ids[2], ids[1]])
expect(active.entries[1].target).toMatchObject({ mode: 'reps', sets: 2, reps: 8, weight: 30, note: 'New target' })
expect(active.entries[0].sets).toEqual([{ w: 40, r: 5, done: false }])
expect(active.entries[2].sets).toEqual([{ w: 40, r: 5, done: false }])
expect(active.cur).toBe(1)
})
})
describe('active exercise swap locale coverage', () => {
const required = [
'Swap exercise',
'Swap exercise?',
'Logged sets stay with the original exercise. Choose where the replacement belongs.',
'Keep replacement in this group',
'Insert after this group',
'Logged sets stay with the original exercise. The replacement will be inserted afterward.'
]
const packs = import.meta.glob('./locales/*.js', { eager: true, import: 'default' })
it('defines every new prompt in all twelve locale packs', () => {
expect(Object.keys(packs)).toHaveLength(Object.keys(LANGS).length - 1)
Object.entries(packs).forEach(([path, pack]) => {
required.forEach(key => expect(pack, `${path} is missing ${key}`).toHaveProperty(key))
})
})
})
+81
View File
@@ -0,0 +1,81 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createRoot } from 'react-dom/client'
import { EXDB } from './lib/exercises.js'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { exConfigSheet } from './sheets.jsx'
const ex = EXDB.find(e => e.id === '0009')
const mounted = []
function type(el, value) {
Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
el.dispatchEvent(new Event('input', { bubbles: true }))
}
function renderConfig(onSave = vi.fn()) {
exConfigSheet(ex, { sets: 3, reps: 10, weight: 0, mode: 'reps', prog: 'double' }, onSave)
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))))
const stepper = [...host.querySelectorAll('.stp-w')]
.find(el => el.querySelector('.stp-l')?.textContent.startsWith('Step'))
return { host, step: stepper.querySelector('input'), onSave }
}
describe('exercise configuration progression step', () => {
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
useUI.setState({ sheets: [] })
useStore.setState(s => ({ S: { ...s.S, unit: 'kg' } }))
document.body.innerHTML = ''
})
afterEach(() => {
act(() => { mounted.splice(0).forEach(root => root.unmount()) })
})
it('keeps the draft empty while clearing the default so a sub-one comma decimal can be entered', () => {
const { step } = renderConfig()
expect(step.value).toBe('2.5')
act(() => { type(step, '') })
expect(step.value).toBe('')
act(() => { type(step, '0,5') })
expect(step.value).toBe('0.5')
})
it('blocks saving without a positive progression step but accepts a positive decimal', () => {
const config = renderConfig()
const save = [...config.host.querySelectorAll('button')]
.find(b => /^(save|add to routine)$/i.test(b.textContent.trim()))
act(() => { type(config.step, '') })
expect(config.step.value).toBe('')
expect(config.step.getAttribute('aria-invalid')).toBe('true')
expect(save.disabled).toBe(true)
expect(config.host.textContent).toContain('Enter a positive step to use this progression rule.')
act(() => { save.click() })
expect(config.onSave).not.toHaveBeenCalled()
expect(useUI.getState().sheets).toHaveLength(1)
act(() => { type(config.step, '0') })
expect(save.disabled).toBe(true)
act(() => { type(config.step, '0,5') })
expect(config.step.value).toBe('0.5')
expect(config.step.getAttribute('aria-invalid')).not.toBe('true')
expect(save.disabled).toBe(false)
act(() => { save.click() })
expect(config.onSave).toHaveBeenCalledWith(expect.objectContaining({ inc: 0.5 }))
expect(useUI.getState().sheets).toHaveLength(0)
})
})
+23 -8
View File
@@ -4,13 +4,13 @@ import { localTZ } from '../lib/format.js'
import { registerCustom } from '../lib/exercises.js'
import { DEMO, DEMO_SEEDED } from '../lib/demo.js'
import { guestAllowed } from '../lib/guest.js'
import { MOBILE, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js'
import { MOBILE, initReminderSync, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js'
import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js'
import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js'
const KEY = 'gym_state_v1'
export const DEF = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, keepAwake: true, lang: 'en',
unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, timerFlash: false, keepAwake: true, lang: 'en',
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full',
@@ -26,6 +26,10 @@ export const DEF = {
// every time you do the movement ("seat 4, pin 7"). Distinct from a routine's `note`, which
// belongs to one exercise in one plan, and from a session note, which belongs to one day.
exNotes: {},
// First day of the week as a getDay() index — 1 Monday, 0 Sunday. Monday is the default so
// every profile written before this setting existed keeps the week it has been looking at.
// See lib/format.js: nothing reads this field directly, everything goes through the helpers.
weekStart: 1,
// Per-exercise bar weight overrides, keyed by exercise id, in the profile unit (see
// lib/bar.js). Personal equipment, so it syncs with the account but never travels in a
// shared plan. Logged weights stay the total — this only feeds the plate math.
@@ -43,10 +47,22 @@ function loadState() {
const hasData = st => !!((st.workouts || []).length || (st.routines || []).length || (st.bodyweight || []).length)
// Decide whether a pulled account state may replace the local saved state. A local active workout
// is deliberately carried forward: the server stores completed/saved state, while the in-progress
// session belongs to the device that is currently running it.
export function restoredStateFor(local, remote, dirty = false) {
if (!remote || (hasData(local) && (dirty || (remote._ts || 0) < (local._ts || 0)))) return null
const next = Object.assign(clone(DEF), remote)
if (local.active) next.active = local.active
return next
}
export const useStore = create((set, get) => {
let pushTm = null
let saveTm = null
initReminderSync(() => get().S)
// Mobile build: mirror the state into a file in the app's data directory (survives WebView
// storage eviction) and keep the native reminder schedule in step with the weekly plan.
const nativePersist = () => {
@@ -76,6 +92,7 @@ export const useStore = create((set, get) => {
clearTimeout(saveTm)
saveTm = null
nativeSave(get().S)
syncReminder(get().S)
}
if (pushTm) {
clearTimeout(pushTm)
@@ -156,11 +173,9 @@ export const useStore = create((set, get) => {
const { state } = await api('/api/data')
const S = get().S
const dirty = localStorage.getItem('gym_dirty') === '1'
if (state && (!hasData(S) || ((state._ts || 0) >= (S._ts || 0) && !dirty))) {
const active = S.active
const next = Object.assign(clone(DEF), state)
if (active) next.active = active
persist(next, false)
const restored = restoredStateFor(S, state, dirty)
if (restored) {
persist(restored, false)
} else if (hasData(S)) { await get().pushState() }
} catch (e) { /* offline — keep local */ }
},
@@ -286,4 +301,4 @@ export const useStore = create((set, get) => {
}
})
export { hasData }
export { hasData }
@@ -0,0 +1,107 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../lib/api.js', () => ({ api: vi.fn() }))
import { api } from '../lib/api.js'
import { DEF, restoredStateFor, useStore } from './useStore.js'
const clone = value => JSON.parse(JSON.stringify(value))
const routine = id => ({ id, name: id, ex: [] })
beforeEach(() => {
localStorage.clear()
api.mockReset()
useStore.setState({ S: clone(DEF), user: null, ready: false })
})
afterEach(() => {
localStorage.clear()
useStore.setState({ S: clone(DEF), user: null, ready: false })
})
describe('saved workout state sync and restore', () => {
it('returns null for an older or dirty local state', () => {
const local = { ...clone(DEF), _ts: 20, routines: [routine('local')] }
const remote = { ...clone(DEF), _ts: 10, routines: [routine('remote')] }
expect(restoredStateFor(local, remote)).toBeNull()
expect(restoredStateFor(local, { ...remote, _ts: 30 }, true)).toBeNull()
})
it('overlays defaults and carries the device-local active workout', () => {
const active = { id: 'active-1', routineId: 'local', entries: [] }
const local = { ...clone(DEF), active }
const restored = restoredStateFor(local, { _ts: 20, routines: [routine('remote')] })
expect(restored.routines.map(r => r.id)).toEqual(['remote'])
expect(restored.active).toEqual(active)
expect(restored.restSec).toBe(90)
})
it('adopts a newer clean remote state while preserving a local active workout', async () => {
const active = { id: 'active-1', d: '2026-08-29', routineId: 'local', name: 'Local', entries: [] }
const local = { ...clone(DEF), _ts: 10, routines: [routine('local')], active }
const remote = { ...clone(DEF), _ts: 20, routines: [routine('remote')], active: null }
useStore.setState({ S: local, user: { id: 'user-1' }, ready: true })
api.mockResolvedValue({ state: remote })
await useStore.getState().pullState()
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['remote'])
expect(useStore.getState().S.active).toEqual(active)
expect(JSON.parse(localStorage.getItem('gym_state_v1')).active).toEqual(active)
expect(api).toHaveBeenCalledTimes(1)
})
it('pushes local data instead of replacing it when the local state is newer', async () => {
const local = { ...clone(DEF), _ts: 20, routines: [routine('local')] }
const remote = { ...clone(DEF), _ts: 10, routines: [routine('remote')] }
useStore.setState({ S: local, user: { id: 'user-1' }, ready: true })
api.mockResolvedValueOnce({ state: remote }).mockResolvedValueOnce({})
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(2)
expect(api.mock.calls[1][0]).toBe('/api/data')
expect(JSON.parse(api.mock.calls[1][1].body).state.routines.map(r => r.id)).toEqual(['local'])
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['local'])
})
it('pushes local data instead of overwriting a dirty local state', async () => {
const local = { ...clone(DEF), _ts: 10, routines: [routine('local')] }
const remote = { ...clone(DEF), _ts: 20, routines: [routine('remote')] }
localStorage.setItem('gym_dirty', '1')
useStore.setState({ S: local, user: { id: 'user-1' }, ready: true })
api.mockResolvedValueOnce({ state: remote }).mockResolvedValueOnce({})
await useStore.getState().pullState()
expect(api).toHaveBeenCalledTimes(2)
expect(JSON.parse(api.mock.calls[1][1].body).state.routines.map(r => r.id)).toEqual(['local'])
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['local'])
})
it('restores a remote state over defaults when the local profile is empty', async () => {
const remote = { _ts: 30, routines: [routine('remote')], workouts: [] }
api.mockResolvedValue({ state: remote })
await useStore.getState().pullState()
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['remote'])
expect(useStore.getState().S.restSec).toBe(90)
expect(useStore.getState().S.lang).toBe('en')
})
it('keeps the local saved state when the restore request fails', async () => {
const local = { ...clone(DEF), _ts: 10, routines: [routine('local')] }
useStore.setState({ S: local, user: { id: 'user-1' }, ready: true })
api.mockRejectedValue(new Error('offline'))
await useStore.getState().pullState()
expect(useStore.getState().S.routines.map(r => r.id)).toEqual(['local'])
expect(api).toHaveBeenCalledTimes(1)
})
})
+19 -5
View File
@@ -56,8 +56,15 @@ let workDone = null
export const useUI = create((set, get) => ({
sheets: [], // { id, render:(close)=>JSX, kind:'sheet'|'center', locked }
toastMsg: '',
timer: null, // rest countdown between sets — { left, total, endsAt }
timer: null, // rest countdown between sets — { left, total, endsAt, forIdx }
// forIdx: index of the active entry whose set started the rest (undefined when unknown)
work: null, // work countdown DURING a timed set (issue #16) — { left, total, endsAt, label }
timerFlashId: 0, // changing the id remounts the four-pulse visual alert
flashTimer() {
if (!useStore.getState().S.timerFlash) return
set(s => ({ timerFlashId: s.timerFlashId + 1 }))
},
openSheet(render, { kind = 'sheet', locked = false } = {}) {
const id = uid()
@@ -74,13 +81,13 @@ export const useUI = create((set, get) => ({
toastTm = setTimeout(() => set({ toastMsg: '' }), 2200)
},
startRest(sec) {
startRest(sec, forIdx) {
get().stopRest()
// Rest timer set to Off. Stopping and returning rather than starting a zero-length timer
// keeps every caller honest: the four places that start a rest do not each need to know.
if (!(sec > 0)) return
const endsAt = Date.now() + sec * 1000
set({ timer: { left: sec, total: sec, endsAt } })
set({ timer: { left: sec, total: sec, endsAt, forIdx } })
requestRestNotificationPermission()
pushRestTimer(sec)
timerTick = () => {
@@ -91,7 +98,7 @@ export const useUI = create((set, get) => ({
const snd = useStore.getState().S.sound
if (left <= 0) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); maybeRestNotification(); get().toast(t('Rest over — next set!')); get().stopRest(); return
vibrate([200, 100, 200]); get().flashTimer(); maybeRestNotification(); get().toast(t('Rest over — next set!')); get().stopRest(); return
}
if (left <= 3) beep(snd, 660, 0.1)
set({ timer: { ...tm, left } })
@@ -109,6 +116,13 @@ export const useUI = create((set, get) => ({
set({ timer: { ...tm, left, total: tm.total + sec, endsAt: tm.endsAt + sec * 1000 } })
pushRestTimer(left)
},
// The active list changed shape (an exercise removed or inserted at `at`): keep the rest
// pointing at the same exercise. Returns nothing; the caller decides whether to stop instead.
shiftRestOwner(at, delta) {
const tm = get().timer
if (!tm || !(tm.forIdx >= at)) return
set({ timer: { ...tm, forIdx: tm.forIdx + delta } })
},
stopRest() {
if (timerInt) clearInterval(timerInt); timerInt = null
if (timerTick) document.removeEventListener('visibilitychange', timerTick); timerTick = null
@@ -139,7 +153,7 @@ export const useUI = create((set, get) => ({
const snd = useStore.getState().S.sound
if (left <= 0) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200])
vibrate([200, 100, 200]); get().flashTimer()
const done = workDone
get().stopWork()
if (done) done(wk.total)
+39
View File
@@ -2,6 +2,7 @@
// useUI pulls in api.js, which reads navigator.userAgent at module scope.
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'
import { useUI } from './useUI.js'
import { useStore } from './useStore.js'
// "Off" has to hold at the timer itself, not at the four places that start one — the same
// reason the rest-after-a-set rule is a shared condition rather than four copies.
@@ -26,3 +27,41 @@ describe('rest timer set to Off', () => {
expect(useUI.getState().timer.total).toBe(90)
})
})
describe('opt-in timer screen flash', () => {
let originalSettings
beforeEach(() => {
vi.useFakeTimers()
originalSettings = useStore.getState().S
useStore.setState({ S: { ...originalSettings, sound: false, timerFlash: false } })
useUI.setState({ timer: null, work: null, timerFlashId: 0 })
})
afterEach(() => {
useUI.getState().stopRest()
useUI.getState().stopWork()
useStore.setState({ S: originalSettings })
vi.useRealTimers()
})
it('stays off unless enabled in Settings', () => {
useUI.getState().startRest(1)
vi.advanceTimersByTime(1000)
expect(useUI.getState().timerFlashId).toBe(0)
})
it('flashes when the rest timer finishes', () => {
useStore.setState({ S: { ...useStore.getState().S, timerFlash: true } })
useUI.getState().startRest(1)
vi.advanceTimersByTime(1000)
expect(useUI.getState().timerFlashId).toBe(1)
})
it('flashes when a timed exercise finishes', () => {
useStore.setState({ S: { ...useStore.getState().S, timerFlash: true } })
useUI.getState().startWork(1, 'Plank', vi.fn())
vi.advanceTimersByTime(1000)
expect(useUI.getState().timerFlashId).toBe(1)
})
})
+1 -1
View File
@@ -203,7 +203,7 @@ export default function Admin() {
<button className="iconbtn" onClick={() => { loadUsers(); loadInvites(); setTick(n => n + 1) }} aria-label="refresh">↻</button>
</div>
<div className="adm-intro">
Everything about running this instance: who uses it, how they get in, and the AI Coach. Nothing here shows anyone's training data beyond counts.
Everything about running this instance: who uses it, how they get in, the AI Coach, and what has happened on it. Nothing here shows anyone's training data beyond counts.
</div>
<div className="tiles" style={{ marginBottom: 12 }}>
+3 -1
View File
@@ -1,7 +1,8 @@
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { t } from '../lib/i18n.js'
import { WorkoutRow, workoutDetailSheet } from '../sheets.jsx'
import { WorkoutRow, workoutDetailSheet, logPastWorkoutSheet } from '../sheets.jsx'
import { Button } from '../components/ui.jsx'
import Icon from '../components/Icon.jsx'
export default function History() {
@@ -10,6 +11,7 @@ export default function History() {
return <>
<div className="hdr"><button className="iconbtn" onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button>
<div style={{ flex: 1, marginLeft: 12 }}><h1>{t('History')}</h1><div className="sub">{t('{0} workouts', S.workouts.length)}</div></div></div>
<Button icon="plus" onClick={logPastWorkoutSheet} style={{ marginBottom: 12 }}>{t('Log a past workout')}</Button>
{S.workouts.length ? <div className="list">{[...S.workouts].reverse().map(w => <WorkoutRow key={w.id} w={w} onClick={() => workoutDetailSheet(w)} />)}</div>
: <div className="empty"><div className="ico"><Icon name="history" /></div>{t('No workouts yet.')}</div>}
</>
+15 -10
View File
@@ -2,12 +2,13 @@ import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { effectiveRoutine, effectiveRoutineId, nextTrainingDay, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, isoOf, weekKey, DAYS, DAYN } from '../lib/format.js'
import { fmtNum, fmtDate, todayISO, isoOf, weekKey, weekStartOf, weekDayOffset, DAYS, DAYN } from '../lib/format.js'
import { t, dateLocale } from '../lib/i18n.js'
import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, loadStarterPlan, bwDeltaColor } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { glyphOf } from '../lib/glyphs.js'
// Home = what to do now + a quick glance. Deep charts & history live in Stats.
@@ -26,24 +27,28 @@ export default function Home() {
const prevBW = S.bodyweight.length > 1 ? S.bodyweight[S.bodyweight.length - 2] : null
const delta = bw && prevBW ? bw.w - prevBW.w : null
const monday = new Date(today); monday.setDate(today.getDate() - ((today.getDay() + 6) % 7) + weekOffset * 7)
const ws = weekStartOf(S)
// The first day of the shown week. Named for the role, not for Monday — which day that is
// is the setting.
const wkStart = new Date(today)
wkStart.setDate(today.getDate() - weekDayOffset(today.getDay(), ws) + weekOffset * 7)
const doneDays = new Set(S.workouts.map(w => w.d))
// The last session logged for today, if any — what the row below reports instead of asking
// you to start the one you already did. Last wins, so a second session names itself.
const doneToday = S.workouts.filter(w => w.d === todayISO()).at(-1) || null
const strip = []
for (let i = 0; i < 7; i++) {
const d = new Date(monday); d.setDate(monday.getDate() + i)
const d = new Date(wkStart); d.setDate(wkStart.getDate() + i)
const iso = isoOf(d)
const eff = effectiveRoutineId(S, iso), ovr = S.dayPlan[iso] !== undefined, done = doneDays.has(iso)
const dot = done ? ' done' : ovr && eff ? ' ovr' : eff ? ' plan' : ''
strip.push(<div key={i} className={'wday' + (iso === todayISO() ? ' today' : '')} onClick={() => dayOverrideSheet(iso)}>
strip.push(<div key={i} className={'wday' + (iso === todayISO() ? ' today' : '')} {...tappable(() => dayOverrideSheet(iso))}>
<div className="lbl">{t(DAYS[d.getDay()])}</div><div className="num">{d.getDate()}</div><div className={'dot' + dot} /></div>)
}
const sunday = new Date(monday); sunday.setDate(monday.getDate() + 6)
const wkLabel = weekOffset === 0 ? t('This week') : `${monday.getDate()} ${monday.toLocaleDateString(dateLocale(), { month: 'short' })} – ${sunday.getDate()} ${sunday.toLocaleDateString(dateLocale(), { month: 'short' })}`
const wkEnd = new Date(wkStart); wkEnd.setDate(wkStart.getDate() + 6)
const wkLabel = weekOffset === 0 ? t('This week') : `${wkStart.getDate()} ${wkStart.toLocaleDateString(dateLocale(), { month: 'short' })} – ${wkEnd.getDate()} ${wkEnd.toLocaleDateString(dateLocale(), { month: 'short' })}`
const wThisWeek = S.workouts.filter(w => weekKey(w.d) === weekKey(todayISO())).length
const wThisWeek = S.workouts.filter(w => weekKey(w.d, ws) === weekKey(todayISO(), ws)).length
const plannedPerWeek = Object.keys(S.week).filter(k => S.week[k]).length
const bwPoints = S.bodyweight.slice(-30).map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
@@ -68,7 +73,7 @@ export default function Home() {
routine name behind a green Start tag and read as still outstanding (issue #4).
An in-progress session still wins — that one is happening right now. Tapping the
row keeps working, so a second session in one day is a tap away, just not urged. */}
<div className="today-row" onClick={onToday}>
<div className="today-row" {...tappable(onToday)}>
<div className="row" style={{ gap: 9, minWidth: 0 }}>
<span className="lrow-i" style={{ background: S.active ? 'var(--orange)' : doneToday ? 'var(--surface-3)' : routine ? 'var(--acc)' : 'var(--surface-3)' }}>
<Icon name={S.active ? 'timer' : doneToday ? 'checkCircle' : routine ? glyphOf(routine.emoji) : 'moon'}
@@ -79,7 +84,7 @@ export default function Home() {
<div className="ttl">{S.active ? t('{0} — in progress', S.active.name)
: doneToday ? (doneToday.name ? t('{0} — done', doneToday.name) : t('Workout done'))
: routine ? routine.name : t('Rest day')}{todayOvr && routine && !doneToday ? ' · ' + t('rescheduled') : ''}</div>
{next && <div className="ss">{t('Next session: {0}, {1}', t(DAYN[next.weekday]), next.routine.name)}</div>}
{next && !doneToday && <div className="ss">{t('Next session: {0}, {1}', t(DAYN[next.weekday]), next.routine.name)}</div>}
</div>
</div>
{S.active ? <span className="tag" style={{ color: 'var(--orange)', background: 'color-mix(in srgb,var(--orange) 16%,transparent)' }}>{t('Resume')}</span>
@@ -131,7 +136,7 @@ export default function Home() {
</> : <div className="muted small">{t("No entries yet — log your weight to start the curve. It's also asked before every workout.")}</div>}
</div>
<div className="card tappable" style={{ cursor: 'pointer' }} onClick={() => calendarSheet()}>
<div className="card tappable" style={{ cursor: 'pointer' }} {...tappable(() => calendarSheet())}>
<div className="row between">
<div>
<div className="row" style={{ gap: 7, fontSize: 22, fontWeight: 600, letterSpacing: '-.021em' }}>
+9 -5
View File
@@ -1,4 +1,4 @@
import { useState } from 'react'
import { useRef, useState } from 'react'
import { useStore } from '../store/useStore.js'
import { EXDB, BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
@@ -9,6 +9,7 @@ import { Thumb } from '../components/Media.jsx'
import { exerciseDetailSheet, addToRoutineSheet, customExSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable, useRevealActiveChip } from '../lib/use-sheet-keyboard.js'
export default function Library() {
const S = useStore(s => s.S)
@@ -17,6 +18,7 @@ export default function Library() {
const [eq, setEq] = useState('')
const [showAll, setShowAll] = useState(false) // ignore the active equipment profile for this session
const [shown, setShown] = useState(40)
const bpStrip = useRef(null), eqStrip = useRef(null)
const profile = activeProfile(S)
const base = allExercises(S).filter(e => (!bp || e.bp === bp) && matchExercise(e, q))
const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(S, e)) : base
@@ -24,6 +26,8 @@ export default function Library() {
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.
const eqOn = eqOpts.includes(eq) ? eq : ''
const f = eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered
useRevealActiveChip(bpStrip, bp)
useRevealActiveChip(eqStrip, eqOn)
return <>
<div className="hdr"><div><h1>{t('Exercises')}</h1><div className="sub">{t('{0} exercises with animations', EXDB.length)}</div></div></div>
@@ -36,22 +40,22 @@ export default function Library() {
{showAll ? t('Filter by "{0}"', profile.name) : t('Show all equipment')}
</button>
</div>}
<div className="chips" style={{ marginBottom: eqOpts.length > 1 ? 8 : 12 }}>
<div className="chips" ref={bpStrip} style={{ marginBottom: eqOpts.length > 1 ? 8 : 12 }}>
<button className={'chip nocap' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setEq(''); setShown(40) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setEq(''); setShown(40) }}>{t(b)}</button>)}
</div>
{eqOpts.length > 1 && <div className="chips" style={{ marginBottom: 12 }}>
{eqOpts.length > 1 && <div className="chips" ref={eqStrip} style={{ marginBottom: 12 }}>
<button className={'chip nocap' + (!eqOn ? ' on' : '')} onClick={() => { setEq(''); setShown(40) }}>{t('Any equipment')}</button>
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(40) }}>{t(x)}</button>)}
</div>}
<div className="list">
<div className="item" onClick={() => customExSheet(null, ex => exerciseDetailSheet(ex), q.trim())}>
<div className="item" {...tappable(() => customExSheet(null, ex => exerciseDetailSheet(ex), q.trim()))}>
<div className="thumb thumb-x"><Icon name="sparkles" /></div>
<div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, no animation')}</div></div><Icon name="plus" className="chev" />
</div>
{f.slice(0, shown).map(e => {
const best = bestWeightFor(S, e.id)
return <div key={e.id} className="item" onClick={() => exerciseDetailSheet(e)}>
return <div key={e.id} className="item" {...tappable(() => exerciseDetailSheet(e))}>
<Thumb ex={e} />
<div className="grow"><div className="tt capitalize">{exerciseNameFor(e)}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
{best > 0 && <span className="tag acc">{fmtNum(best)}</span>}
+6 -5
View File
@@ -1,10 +1,11 @@
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { DAYN, uid, exCount } from '../lib/format.js'
import { DAYN, weekOrder, weekStartOf, uid, exCount } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { dayAssignSheet, loadStarterPlan, planToolsSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button, Row } from '../components/ui.jsx'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { glyphOf, DEFAULT_GLYPH } from '../lib/glyphs.js'
import { DEMO } from '../lib/demo.js'
import { MOBILE } from '../lib/mobile.js'
@@ -47,9 +48,9 @@ export default function Plan() {
<div className="cols"><div>
<h4 className="sec">{t('Week schedule')}</h4>
<div className="list" style={{ display: 'flex', flexDirection: 'column' }}>
{[1, 2, 3, 4, 5, 6, 0].map(d => {
{weekOrder(weekStartOf(S)).map(d => {
const r = S.routines.find(x => x.id === S.week[d])
return <div key={d} className="item" onClick={() => dayAssignSheet(d)}>
return <div key={d} className="item" {...tappable(() => dayAssignSheet(d))}>
<div className="grow"><div className="tt">{t(DAYN[d])}</div></div>
{r ? <span className="tag acc"><Icon name={glyphOf(r.emoji)} />{r.name}</span> : <span className="tag">{t('Rest')}</span>}
<Icon name="chevronRight" className="chev" /></div>
@@ -60,7 +61,7 @@ export default function Plan() {
<h4 className="sec" style={{ margin: 0 }}>{t('Routines')}</h4>
<Button size="sm" variant="tinted" icon="plus" onClick={addRoutine}>{t('New')}</Button>
</div>
{S.routines.length ? <div className="list">{S.routines.map(r => <div key={r.id} className="item" onClick={() => nav('/plan/r/' + r.id)}>
{S.routines.length ? <div className="list">{S.routines.map(r => <div key={r.id} className="item" {...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>
<Icon name="chevronRight" className="chev" /></div>)}</div> : <>
@@ -0,0 +1,450 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const sheets = vi.hoisted(() => ({
exConfigSheet: vi.fn(), exercisePicker: vi.fn(), glyphPicker: vi.fn(), confirmSheet: vi.fn(),
}))
vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
vi.mock('../sheets.jsx', () => sheets)
vi.mock('../components/Media.jsx', () => ({ Thumb: ({ ex }) => <span data-thumb={ex.id} /> }))
vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
import RoutineEdit, { ROUTINE_DRAG_SLOP, ROUTINE_LONG_PRESS_MS, reorderRoutineUnit } from './RoutineEdit.jsx'
import { DEF, useStore } from '../store/useStore.js'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const clone = value => JSON.parse(JSON.stringify(value))
const configured = (id, extra = {}) => ({ id, mode: 'reps', sets: 3, reps: 5, weight: 0, ...extra })
let root
let host
function stateFor(entries) {
const S = clone(DEF)
S.routines = [{ id: 'r1', name: 'Drag routine', emoji: 'dumbbell', prog: 'linear', ex: entries }]
return S
}
function rect(top, height, left = 20, width = 340) {
return { x: left, y: top, left, right: left + width, top, bottom: top + height, width, height }
}
const rows = () => [...host.querySelectorAll('[data-routine-row]')]
function geometry(heights = rows().map(() => 70)) {
const list = host.querySelector('.routine-list')
let top = 100
const tops = [], bottoms = [], centers = []
rows().forEach((row, i) => {
const height = heights[i] ?? 70
tops.push(top); bottoms.push(top + height); centers.push(top + height / 2)
vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => rect(tops[i], height))
top += height + 10
})
const listRect = rect(80, top - 80)
vi.spyOn(list, 'getBoundingClientRect').mockImplementation(() => listRect)
return { list, tops, bottoms, centers, listRect }
}
function mount(entries) {
useStore.setState({ S: stateFor(entries), user: null })
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
act(() => root.render(<MemoryRouter initialEntries={['/plan/r/r1']}><Routes><Route path="/plan/r/:id" element={<RoutineEdit />} /></Routes></MemoryRouter>))
return geometry()
}
function remountCurrentState() {
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
act(() => root.render(<MemoryRouter initialEntries={['/plan/r/r1']}><Routes><Route path="/plan/r/:id" element={<RoutineEdit />} /></Routes></MemoryRouter>))
return geometry()
}
function pointer(target, type, { id = 7, kind = 'touch', primary = true, button = 0, x = 120, y = 120 } = {}) {
const event = new Event(type, { bubbles: true, cancelable: true })
for (const [key, value] of Object.entries({ pointerId: id, pointerType: kind, isPrimary: primary, button, clientX: x, clientY: y })) {
Object.defineProperty(event, key, { configurable: true, value })
}
act(() => target.dispatchEvent(event))
return event
}
function lift(row, y, x = 120) {
pointer(row.querySelector('.item'), 'pointerdown', { x, y })
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
}
const exercises = () => useStore.getState().S.routines[0].ex
beforeEach(() => {
vi.useFakeTimers()
vi.spyOn(window, 'requestAnimationFrame').mockImplementation(cb => window.setTimeout(() => cb(Date.now()), 16))
vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(id => window.clearTimeout(id))
localStorage.clear()
Object.values(sheets).forEach(mock => mock.mockReset())
root = null; host = null
})
afterEach(() => {
if (root) act(() => root.unmount())
host?.remove()
vi.clearAllTimers(); vi.restoreAllMocks(); vi.useRealTimers()
})
describe('routine long-press reorder', () => {
it('exports the frozen threshold/slop and keeps a short press as a normal click', () => {
expect(ROUTINE_LONG_PRESS_MS).toBe(380)
expect(ROUTINE_DRAG_SLOP).toBe(8)
const layout = mount([configured('1001'), configured('1002')])
const item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { y: layout.centers[0] })
act(() => vi.advanceTimersByTime(379))
expect(host.querySelector('.is-dragging')).toBeNull()
pointer(item, 'pointerup', { y: layout.centers[0] })
act(() => item.click())
expect(sheets.exConfigSheet).toHaveBeenCalledOnce()
expect(exercises().map(e => e.id)).toEqual(['1001', '1002'])
})
it('lifts at exactly 380 ms and yields pre-lift movement strictly over 8 px to scrolling', () => {
let layout = mount([configured('1001'), configured('1002')])
let item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { x: 100, y: layout.centers[0] })
const atEight = pointer(item, 'pointermove', { x: 108, y: layout.centers[0] })
expect(atEight.defaultPrevented).toBe(false)
act(() => vi.advanceTimersByTime(380))
expect(rows()[0].classList.contains('is-dragging')).toBe(true)
pointer(item, 'pointercancel', { x: 108, y: layout.centers[0] })
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('1001'), configured('1002')])
item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { x: 100, y: layout.centers[0] })
const atNine = pointer(item, 'pointermove', { x: 109, y: layout.centers[0] })
act(() => vi.advanceTimersByTime(380))
expect(atNine.defaultPrevented).toBe(false)
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('owns active movement, renders an indicator, and suppresses the compatibility click after cancel', () => {
const layout = mount([configured('1001'), configured('1002'), configured('1003')])
const row = rows()[1], item = row.querySelector('.item')
const capture = vi.fn(), release = vi.fn()
item.setPointerCapture = capture; item.releasePointerCapture = release
lift(row, layout.centers[1])
expect(capture).toHaveBeenCalledWith(7)
expect(row.classList.contains('is-dragging')).toBe(true)
expect(host.querySelector('[data-testid="routine-drop-indicator"]')).toBeTruthy()
const move = pointer(item, 'pointermove', { y: layout.centers[2] })
expect(move.defaultPrevented).toBe(true)
pointer(item, 'pointercancel', { y: layout.centers[2] })
expect(release).toHaveBeenCalledWith(7)
act(() => item.click())
expect(sheets.exConfigSheet).not.toHaveBeenCalled()
expect(exercises().map(e => e.id)).toEqual(['1001', '1002', '1003'])
})
it('moves across measured slots and persists one complete changed order', () => {
const layout = mount([configured('a'), configured('b'), configured('c'), configured('d')])
const before = localStorage.getItem('gym_state_v1')
const writes = vi.spyOn(Storage.prototype, 'setItem')
const row = rows()[0], item = row.querySelector('.item')
lift(row, layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a', 'd'])
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines[0].ex.map(e => e.id)).toEqual(['b', 'c', 'a', 'd'])
expect(localStorage.getItem('gym_state_v1')).not.toBe(before)
expect(writes).toHaveBeenCalledTimes(1)
})
it('suppresses the compatibility click after a successful changed drop', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a'])
act(() => item.click())
expect(sheets.exConfigSheet).not.toHaveBeenCalled()
})
it('lets a real tap shortly after a drop open the row again', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a'])
act(() => vi.advanceTimersByTime(200))
const target = rows()[1].querySelector('.item')
pointer(target, 'pointerdown', { y: layout.centers[1] })
pointer(target, 'pointerup', { y: layout.centers[1] })
act(() => target.click())
expect(sheets.exConfigSheet).toHaveBeenCalledTimes(1)
})
it('never eats a tap that starts with its own pointerdown, even right after a drop', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
const target = rows()[1].querySelector('.item')
pointer(target, 'pointerdown', { y: layout.centers[1] })
pointer(target, 'pointerup', { y: layout.centers[1] })
act(() => target.click())
expect(sheets.exConfigSheet).toHaveBeenCalledTimes(1)
})
it('moves a whole grouped unit, never splits another group, and preserves every occurrence payload', () => {
const pairA = configured('dup', { sg: 'pair', weight: 11, note: 'first', future: { a: 1 } })
const pairB = configured('dup', { sg: 'pair', weight: 22, note: 'second', future: { b: 2 } })
const layout = mount([pairA, pairB, configured('c'), configured('d')])
const row = rows()[1], item = row.querySelector('.item')
lift(row, layout.centers[1])
expect(rows().slice(0, 2).every(node => node.classList.contains('is-dragging'))).toBe(true)
pointer(item, 'pointermove', { y: layout.listRect.bottom - 1 })
pointer(item, 'pointerup', { y: layout.listRect.bottom - 1 })
expect(exercises()).toEqual([configured('c'), configured('d'), pairA, pairB])
act(() => root.unmount()); host.remove(); root = null; host = null
const splitLayout = mount([configured('a'), configured('b', { sg: 'g' }), configured('c', { sg: 'g' }), configured('tail')])
const tail = rows()[3], tailItem = tail.querySelector('.item')
lift(tail, splitLayout.centers[3])
const betweenMembers = (splitLayout.bottoms[1] + splitLayout.tops[2]) / 2
pointer(tailItem, 'pointermove', { y: betweenMembers })
pointer(tailItem, 'pointerup', { y: betweenMembers })
expect(exercises().map(e => e.id)).toEqual(['a', 'tail', 'b', 'c'])
})
it('moves the selected duplicate occurrence rather than finding by catalogue id', () => {
const first = configured('dup', { weight: 10, reps: 3, note: 'first' })
const second = configured('dup', { weight: 20, reps: 9, note: 'second' })
const layout = mount([first, configured('middle'), second, configured('tail')])
const row = rows()[2], item = row.querySelector('.item')
lift(row, layout.centers[2])
pointer(item, 'pointermove', { y: layout.tops[0] + 1 })
pointer(item, 'pointerup', { y: layout.tops[0] + 1 })
expect(exercises()).toEqual([second, first, configured('middle'), configured('tail')])
})
it('cancels without persistence on outside release, lost capture, Escape, blur, hidden document, or second pointer', () => {
const cancelCases = ['outside', 'lost', 'escape', 'blur', 'hidden', 'second']
for (const cancel of cancelCases) {
if (root) { act(() => root.unmount()); host.remove(); root = null; host = null }
const layout = mount([configured('a'), configured('b'), configured('c')])
const row = rows()[0], item = row.querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
lift(row, layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] })
if (cancel === 'outside') pointer(item, 'pointerup', { x: layout.listRect.right + 20, y: layout.centers[2] })
if (cancel === 'lost') pointer(item, 'lostpointercapture', { y: layout.centers[2] })
if (cancel === 'escape') act(() => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })))
if (cancel === 'blur') act(() => window.dispatchEvent(new Event('blur')))
if (cancel === 'hidden') {
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' })
act(() => document.dispatchEvent(new Event('visibilitychange')))
Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' })
}
if (cancel === 'second') pointer(rows()[1].querySelector('.item'), 'pointerdown', { id: 8, y: layout.centers[1] })
expect(exercises().map(e => e.id), cancel).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1'), cancel).toBe(before)
expect(host.querySelector('.is-dragging'), cancel).toBeNull()
}
})
it('ignores non-primary/control pointers and leaves accessible move buttons working', () => {
const layout = mount([configured('a'), configured('b')])
const down = host.querySelector('button[aria-label="Move down"]')
pointer(down, 'pointerdown', { y: layout.centers[0] })
act(() => vi.advanceTimersByTime(380))
expect(host.querySelector('.is-dragging')).toBeNull()
act(() => down.click())
expect(exercises().map(e => e.id)).toEqual(['b', 'a'])
const item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { primary: false, y: layout.centers[0] })
act(() => vi.advanceTimersByTime(380))
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('autoscrolls only after lift and stops frames on cancel', () => {
const layout = mount([configured('a'), configured('b'), configured('c'), configured('d')])
host.style.overflowY = 'auto'
Object.defineProperty(host, 'clientHeight', { configurable: true, value: 320 })
Object.defineProperty(host, 'scrollHeight', { configurable: true, value: 900 })
host.scrollTop = 100
vi.spyOn(host, 'getBoundingClientRect').mockImplementation(() => rect(0, 320))
const row = rows()[2], item = row.querySelector('.item')
pointer(item, 'pointerdown', { y: 310 })
act(() => vi.advanceTimersByTime(16))
expect(host.scrollTop).toBe(100)
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS - 16 + 16))
expect(host.scrollTop).toBeGreaterThan(100)
pointer(item, 'pointercancel', { y: 310 })
const stopped = host.scrollTop
act(() => vi.advanceTimersByTime(64))
expect(host.scrollTop).toBe(stopped)
})
it('fails closed when row geometry disappears during an active drag', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const row = rows()[0], item = row.querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
lift(row, layout.centers[0])
rows()[1].getBoundingClientRect.mockReturnValue(undefined)
pointer(item, 'pointermove', { y: layout.centers[2] })
pointer(item, 'pointerup', { y: layout.centers[2] })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1')).toBe(before)
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('cleans pending and active gestures on unmount without late writes', () => {
const layout = mount([configured('a'), configured('b')])
const item = rows()[0].querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
pointer(item, 'pointerdown', { y: layout.centers[0] })
act(() => root.unmount()); root = null
act(() => vi.advanceTimersByTime(1000))
expect(localStorage.getItem('gym_state_v1')).toBe(before)
const activeLayout = mount([configured('a'), configured('b')])
const activeItem = rows()[0].querySelector('.item')
const release = vi.fn()
activeItem.releasePointerCapture = release
lift(rows()[0], activeLayout.centers[0])
act(() => root.unmount()); root = null
act(() => vi.advanceTimersByTime(1000))
expect(release).toHaveBeenCalledWith(7)
expect(localStorage.getItem('gym_state_v1')).toBe(before)
})
it('covers reverse measured slots and an unchanged original slot', () => {
let layout = mount([configured('a'), configured('b'), configured('c'), configured('d')])
let item = rows()[3].querySelector('.item')
lift(rows()[3], layout.centers[3])
pointer(item, 'pointermove', { y: layout.tops[1] + 1 })
pointer(item, 'pointerup', { y: layout.tops[1] + 1 })
expect(exercises().map(e => e.id)).toEqual(['a', 'd', 'b', 'c'])
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('a'), configured('b'), configured('c')])
const before = localStorage.getItem('gym_state_v1')
item = rows()[1].querySelector('.item')
lift(rows()[1], layout.centers[1])
pointer(item, 'pointermove', { y: layout.centers[1] + ROUTINE_DRAG_SLOP + 1 })
pointer(item, 'pointerup', { y: layout.centers[1] + ROUTINE_DRAG_SLOP + 1 })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1')).toBe(before)
})
it('reads the persisted changed order back after a fresh remount', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] + 1 })
pointer(item, 'pointerup', { y: layout.centers[2] + 1 })
const saved = JSON.parse(localStorage.getItem('gym_state_v1'))
act(() => root.unmount()); host.remove(); root = null; host = null
useStore.setState({ S: saved, user: null })
remountCurrentState()
expect(exercises().map(e => e.id)).toEqual(['b', 'c', 'a'])
})
it('cancels active ownership for a second pointer outside the list and pending lost capture', () => {
let layout = mount([configured('a'), configured('b'), configured('c')])
let item = rows()[0].querySelector('.item')
const before = localStorage.getItem('gym_state_v1')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] })
pointer(document.body, 'pointerdown', { id: 8, y: 20 })
pointer(item, 'pointerup', { y: layout.centers[2] })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(localStorage.getItem('gym_state_v1')).toBe(before)
expect(host.querySelector('.is-dragging')).toBeNull()
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('a'), configured('b')])
item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { y: layout.centers[0] })
pointer(item, 'lostpointercapture', { y: layout.centers[0] })
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('cancels when equal serialized exercises acquire a new current routine/list identity', () => {
let layout = mount([configured('a'), configured('b'), configured('c')])
let item = rows()[0].querySelector('.item')
lift(rows()[0], layout.centers[0])
pointer(item, 'pointermove', { y: layout.centers[2] })
act(() => useStore.getState().update(s => {
const current = s.routines[0]
s.routines[0] = { ...current, ex: clone(current.ex) }
}))
pointer(item, 'pointerup', { y: layout.centers[2] })
expect(exercises().map(e => e.id)).toEqual(['a', 'b', 'c'])
expect(host.querySelector('.is-dragging')).toBeNull()
act(() => root.unmount()); host.remove(); root = null; host = null
layout = mount([configured('a'), configured('b')])
item = rows()[0].querySelector('.item')
pointer(item, 'pointerdown', { y: layout.centers[0] })
act(() => useStore.getState().update(s => {
const current = s.routines[0]
s.routines[0] = { ...current, ex: clone(current.ex) }
}))
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
expect(host.querySelector('.is-dragging')).toBeNull()
})
it('never owns nested link, Move up, or Move down controls', () => {
const layout = mount([configured('a'), configured('b')])
const controls = [
rows()[1].querySelector('button[title]'),
rows()[1].querySelector('button[aria-label="Move up"]'),
rows()[1].querySelector('button[aria-label="Move down"]'),
]
for (const control of controls) {
pointer(control, 'pointerdown', { y: layout.centers[1] })
act(() => vi.advanceTimersByTime(ROUTINE_LONG_PRESS_MS))
expect(host.querySelector('.is-dragging')).toBeNull()
pointer(control, 'pointerup', { y: layout.centers[1] })
}
})
it('falls back to page/window autoscroll without a nested scroll host', () => {
const layout = mount([configured('a'), configured('b'), configured('c')])
const rootElement = document.documentElement
Object.defineProperty(document, 'scrollingElement', { configurable: true, value: rootElement })
Object.defineProperty(rootElement, 'clientHeight', { configurable: true, value: 300 })
Object.defineProperty(rootElement, 'scrollHeight', { configurable: true, value: 900 })
Object.defineProperty(window, 'innerHeight', { configurable: true, value: 300 })
Object.defineProperty(window, 'scrollY', { configurable: true, writable: true, value: 100 })
const scrollBy = vi.spyOn(window, 'scrollBy').mockImplementation((_, delta) => { window.scrollY += delta })
const item = rows()[2].querySelector('.item')
lift(rows()[2], 295)
act(() => vi.advanceTimersByTime(16))
expect(scrollBy).toHaveBeenCalled()
expect(window.scrollY).toBeGreaterThan(100)
pointer(item, 'pointercancel', { y: 295 })
})
it('invalidates ownership before cleanup synchronously emits lost capture', () => {
const layout = mount([configured('a'), configured('b')])
const item = rows()[0].querySelector('.item')
const release = vi.fn(pointerId => pointer(document, 'lostpointercapture', { id: pointerId, y: layout.centers[0] }))
item.releasePointerCapture = release
lift(rows()[0], layout.centers[0])
act(() => root.unmount()); root = null
expect(release).toHaveBeenCalledTimes(1)
})
})
describe('reorderRoutineUnit', () => {
it('splices complete units at canonical slots and cleans true orphans', () => {
const items = [configured('a', { sg: 'pair' }), configured('b', { sg: 'pair' }), configured('c', { sg: 'orphan' }), configured('d')]
expect(reorderRoutineUnit(items, 3, 1)).toBe(true)
expect(items.map(e => e.id)).toEqual(['a', 'b', 'd', 'c'])
expect(items[0].sg).toBe('pair'); expect(items[1].sg).toBe('pair'); expect(items[3].sg).toBeUndefined()
})
})
+324 -12
View File
@@ -1,20 +1,305 @@
import { useNavigate, useParams } from 'react-router-dom'
import { useEffect } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useStore } from '../store/useStore.js'
import { exOr } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
import { uid } from '../lib/format.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { supersetUnits, cleanupSg, exLine } from '../lib/history.js'
import { supersetUnits, moveSupersetUnit, cleanupSg, exLine } from '../lib/history.js'
import { Thumb } from '../components/Media.jsx'
import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { glyphOf } from '../lib/glyphs.js'
import { Button, SelectRow } from '../components/ui.jsx'
import { Button, Row, SelectRow, Switch } from '../components/ui.jsx'
import { POLICIES_FOR, POLICY_NAME, POLICY_DESC } from '../lib/progression.js'
import BodyMap from '../components/BodyMap.jsx'
import { loadOfRoutine, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
export const ROUTINE_LONG_PRESS_MS = 380
export const ROUTINE_DRAG_SLOP = 8
const clamp = (value, low, high) => Math.max(low, Math.min(high, value))
// Slots are defined after removing the source unit, so a grouped run can never be split.
export function reorderRoutineUnit(exercises, sourceIndex, targetSlot) {
if (!Array.isArray(exercises) || !exercises.length) return false
const units = supersetUnits(exercises)
const sourcePosition = units.findIndex(unit => unit.includes(sourceIndex))
if (sourcePosition < 0) return false
const remaining = units.filter((_, position) => position !== sourcePosition)
const slot = clamp(Number.isFinite(targetSlot) ? Math.trunc(targetSlot) : sourcePosition, 0, remaining.length)
if (slot === sourcePosition) return false
const source = units[sourcePosition]
const moved = exercises.splice(source[0], source.length)
const insertAt = remaining.slice(0, slot).reduce((count, unit) => count + unit.length, 0)
exercises.splice(insertAt, 0, ...moved)
cleanupSg(exercises)
return true
}
function unitGeometry(list, exercises) {
const rows = new Map([...list.querySelectorAll('[data-routine-row]')]
.map(row => [Number(row.dataset.exIndex), row]))
const units = supersetUnits(exercises)
const geometry = units.map((unit, position) => {
const rects = unit.map(index => rows.get(index)?.getBoundingClientRect()).filter(Boolean)
if (rects.length !== unit.length) return null
const top = Math.min(...rects.map(rect => rect.top))
const bottom = Math.max(...rects.map(rect => rect.bottom))
return { unit, position, top, bottom, center: top + (bottom - top) / 2 }
})
return geometry.every(Boolean) ? geometry : null
}
function scrollHostFor(node) {
for (let parent = node.parentElement; parent && parent !== document.body; parent = parent.parentElement) {
const overflowY = window.getComputedStyle(parent).overflowY
if (/(auto|scroll)/.test(overflowY) && parent.scrollHeight > parent.clientHeight) return parent
}
return window
}
function autoScrollStep(host, clientY) {
const edge = 64
const maxStep = 14
let top, bottom, scrollTop, maxScroll
if (host === window) {
const root = document.scrollingElement || document.documentElement
top = window.visualViewport?.offsetTop || 0
bottom = top + (window.visualViewport?.height || window.innerHeight || root.clientHeight)
scrollTop = window.scrollY || root.scrollTop || 0
maxScroll = Math.max(root.scrollHeight, document.body?.scrollHeight || 0) - (bottom - top)
} else {
const rect = host.getBoundingClientRect()
top = rect.top; bottom = rect.bottom
scrollTop = host.scrollTop; maxScroll = host.scrollHeight - host.clientHeight
}
if (clientY < top + edge && scrollTop > 0) return -Math.ceil(maxStep * clamp((top + edge - clientY) / edge, 0, 1))
if (clientY > bottom - edge && scrollTop < maxScroll) return Math.ceil(maxStep * clamp((clientY - bottom + edge) / edge, 0, 1))
return 0
}
function useRoutineReorder(routineIdentity, exercises, onDrop) {
const listRef = useRef(null)
const gestureRef = useRef(null)
const exercisesRef = useRef(exercises)
const routineIdentityRef = useRef(routineIdentity)
const onDropRef = useRef(onDrop)
const suppressClickRef = useRef(false)
const suppressTimerRef = useRef(null)
const [drag, setDrag] = useState(null)
exercisesRef.current = exercises
routineIdentityRef.current = routineIdentity
onDropRef.current = onDrop
const hasRows = exercises.length > 0
useEffect(() => () => {
suppressClickRef.current = false
window.clearTimeout(suppressTimerRef.current)
}, [])
useEffect(() => {
const list = listRef.current
if (!list) return undefined
let frame = null
setDrag(current => current ? null : current)
const clearFrame = () => {
if (frame != null) window.cancelAnimationFrame(frame)
frame = null
}
const clearTimer = gesture => {
if (gesture?.timer != null) window.clearTimeout(gesture.timer)
if (gesture) gesture.timer = null
}
const matchesSnapshot = gesture => routineIdentityRef.current === gesture.routineIdentity
&& exercisesRef.current === gesture.listIdentity
&& JSON.stringify(exercisesRef.current) === gesture.snapshot
const releaseCapture = gesture => {
const target = gesture?.captureTarget
if (!target?.releasePointerCapture) return
try { target.releasePointerCapture(gesture.pointerId) } catch { /* already released */ }
}
const finish = (gesture, commit, x = gesture?.lastX, y = gesture?.lastY) => {
if (!gesture || gestureRef.current !== gesture) return
clearTimer(gesture)
clearFrame()
gestureRef.current = null
if (!gesture.active) return
releaseCapture(gesture)
suppressClickRef.current = true
window.clearTimeout(suppressTimerRef.current)
// The compatibility click lands synchronously after pointerup; anything
// later is a real tap, so the guard only needs to outlive that one event.
suppressTimerRef.current = window.setTimeout(() => { suppressClickRef.current = false }, 150)
setDrag(null)
const rect = list.getBoundingClientRect()
const inside = x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom
const geometry = unitGeometry(list, exercisesRef.current)
if (commit && inside && geometry && matchesSnapshot(gesture) && gesture.targetSlot !== gesture.sourcePosition) {
onDropRef.current(gesture.sourceIndex, gesture.targetSlot)
}
}
const indicatorTop = (geometry, gesture, slot, listRect) => {
if (slot === gesture.sourcePosition) return clamp(gesture.sourceTop - listRect.top, 0, listRect.height)
const remaining = geometry.filter(unit => unit.position !== gesture.sourcePosition)
let top
if (slot <= 0) top = remaining[0]?.top ?? gesture.sourceTop
else if (slot >= remaining.length) top = remaining.at(-1)?.bottom ?? gesture.sourceBottom
else top = (remaining[slot - 1].bottom + remaining[slot].top) / 2
return clamp(top - listRect.top, 0, listRect.height)
}
const updateDrag = (gesture, x, y, schedule = true) => {
if (gestureRef.current !== gesture || !gesture.active || !matchesSnapshot(gesture)) {
if (gestureRef.current === gesture) finish(gesture, false)
return
}
const geometry = unitGeometry(list, exercisesRef.current)
if (!geometry) { finish(gesture, false); return }
const listRect = list.getBoundingClientRect()
const remaining = geometry.filter(unit => unit.position !== gesture.sourcePosition)
const probeY = clamp(y, listRect.top, listRect.bottom)
const moved = Math.hypot(x - gesture.startX, y - gesture.startY) > ROUTINE_DRAG_SLOP
const slot = moved ? remaining.reduce((count, unit) => count + (probeY > unit.center ? 1 : 0), 0) : gesture.sourcePosition
const rawDelta = y - gesture.grabOffset - gesture.sourceTop
const deltaY = clamp(rawDelta, listRect.top - gesture.sourceTop, listRect.bottom - gesture.sourceBottom)
gesture.lastX = x; gesture.lastY = y; gesture.targetSlot = slot
setDrag({ first: gesture.sourceUnit[0], last: gesture.sourceUnit.at(-1), deltaY, indicatorTop: indicatorTop(geometry, gesture, slot, listRect) })
if (schedule && frame == null) frame = window.requestAnimationFrame(runAutoScroll)
}
function runAutoScroll() {
frame = null
const gesture = gestureRef.current
if (!gesture?.active) return
const step = autoScrollStep(gesture.scrollHost, gesture.lastY)
if (!step) return
if (gesture.scrollHost === window) window.scrollBy(0, step)
else gesture.scrollHost.scrollTop += step
updateDrag(gesture, gesture.lastX, gesture.lastY, false)
if (gestureRef.current === gesture) frame = window.requestAnimationFrame(runAutoScroll)
}
const lift = gesture => {
if (gestureRef.current !== gesture) return
if (!matchesSnapshot(gesture)) { finish(gesture, false); return }
const geometry = unitGeometry(list, exercisesRef.current)
const source = geometry?.find(unit => unit.unit.includes(gesture.sourceIndex))
if (!source) { finish(gesture, false); return }
gesture.active = true; gesture.timer = null
gesture.sourcePosition = source.position; gesture.sourceUnit = source.unit
gesture.sourceTop = source.top; gesture.sourceBottom = source.bottom
gesture.grabOffset = gesture.lastY - source.top; gesture.targetSlot = source.position
gesture.scrollHost = scrollHostFor(list)
gesture.captureTarget = gesture.downTarget
try { gesture.captureTarget.setPointerCapture?.(gesture.pointerId) } catch { /* unsupported */ }
suppressClickRef.current = true
window.clearTimeout(suppressTimerRef.current)
updateDrag(gesture, gesture.lastX, gesture.lastY)
}
const onPointerDown = event => {
// a new touch is intentional — never let the post-drop guard eat its click
suppressClickRef.current = false
window.clearTimeout(suppressTimerRef.current)
const current = gestureRef.current
if (current) {
if (event.pointerId !== current.pointerId) finish(current, false)
return
}
if (event.isPrimary === false || (event.pointerType === 'mouse' && event.button !== 0)) return
const target = event.target
if (!target?.closest || target.closest('button,a,input,textarea,select,[data-nodrag]')) return
const row = target.closest('[data-routine-row]')
if (!row || !list.contains(row)) return
const sourceIndex = Number(row.dataset.exIndex)
if (!Number.isInteger(sourceIndex)) return
const gesture = {
pointerId: event.pointerId, sourceIndex, downTarget: target,
startX: event.clientX, startY: event.clientY, lastX: event.clientX, lastY: event.clientY,
routineIdentity: routineIdentityRef.current,
listIdentity: exercisesRef.current,
snapshot: JSON.stringify(exercisesRef.current), active: false, timer: null,
}
gesture.timer = window.setTimeout(() => lift(gesture), ROUTINE_LONG_PRESS_MS)
gestureRef.current = gesture
}
const onPointerMove = event => {
const gesture = gestureRef.current
if (!gesture || event.pointerId !== gesture.pointerId) return
if (!gesture.active) {
if (Math.hypot(event.clientX - gesture.startX, event.clientY - gesture.startY) > ROUTINE_DRAG_SLOP) {
clearTimer(gesture); gestureRef.current = null
} else { gesture.lastX = event.clientX; gesture.lastY = event.clientY }
return
}
event.preventDefault()
updateDrag(gesture, event.clientX, event.clientY)
}
const onPointerUp = event => {
const gesture = gestureRef.current
if (!gesture || event.pointerId !== gesture.pointerId) return
if (gesture.active) event.preventDefault()
finish(gesture, gesture.active, event.clientX, event.clientY)
}
const onPointerCancel = event => {
const gesture = gestureRef.current
if (gesture && event.pointerId === gesture.pointerId) finish(gesture, false)
}
const onLostCapture = event => {
const gesture = gestureRef.current
if (gesture && event.pointerId === gesture.pointerId) finish(gesture, false)
}
const cancelActive = () => finish(gestureRef.current, false)
const onKeyDown = event => {
if (event.key !== 'Escape' || !gestureRef.current) return
event.preventDefault(); cancelActive()
}
const onVisibility = () => { if (document.visibilityState === 'hidden') cancelActive() }
const onContextMenu = event => { if (gestureRef.current?.active && event.target.closest?.('[data-routine-row]')) event.preventDefault() }
const onDragStart = event => { if (event.target.closest?.('[data-routine-row]')) event.preventDefault() }
// Touch: the rows keep `touch-action: pan-y` so the list still scrolls with a finger, but once
// a long-press has lifted a row the browser must not claim the vertical drag as a pan — it
// would fire pointercancel and scroll instead. preventDefault on a pointer event cannot stop
// that; only a non-passive touchmove listener can, and only while a drag is actually active.
const onTouchMove = event => { if (gestureRef.current?.active) event.preventDefault() }
document.addEventListener('pointerdown', onPointerDown)
document.addEventListener('touchmove', onTouchMove, { passive: false })
document.addEventListener('pointermove', onPointerMove, { passive: false })
document.addEventListener('pointerup', onPointerUp, { passive: false })
document.addEventListener('pointercancel', onPointerCancel)
document.addEventListener('lostpointercapture', onLostCapture)
document.addEventListener('keydown', onKeyDown)
document.addEventListener('visibilitychange', onVisibility)
list.addEventListener('contextmenu', onContextMenu)
list.addEventListener('dragstart', onDragStart)
window.addEventListener('blur', cancelActive)
return () => {
const gesture = gestureRef.current
clearTimer(gesture); clearFrame(); gestureRef.current = null
releaseCapture(gesture)
document.removeEventListener('pointerdown', onPointerDown)
document.removeEventListener('touchmove', onTouchMove)
document.removeEventListener('pointermove', onPointerMove)
document.removeEventListener('pointerup', onPointerUp)
document.removeEventListener('pointercancel', onPointerCancel)
document.removeEventListener('lostpointercapture', onLostCapture)
document.removeEventListener('keydown', onKeyDown)
document.removeEventListener('visibilitychange', onVisibility)
list.removeEventListener('contextmenu', onContextMenu)
list.removeEventListener('dragstart', onDragStart)
window.removeEventListener('blur', cancelActive)
}
}, [hasRows, routineIdentity, exercises])
const onClickCapture = event => {
if (!suppressClickRef.current) return
suppressClickRef.current = false
window.clearTimeout(suppressTimerRef.current)
event.preventDefault(); event.stopPropagation()
}
return { listRef, drag, onClickCapture }
}
export default function RoutineEdit() {
const nav = useNavigate()
const { id } = useParams()
@@ -26,10 +311,21 @@ export default function RoutineEdit() {
// auto-backup on the way out (not per keystroke) covers the whole editing session, deletion
// included: this still unmounts after the delete button navigates away.
useEffect(() => () => useStore.getState().autoBackupNow(), [])
if (!r) return null
const edit = fn => update(s => { fn(s.routines.find(x => x.id === id).ex) })
const move = (i, dir) => edit(ex => { const j = i + dir; if (j < 0 || j >= ex.length) return;[ex[i], ex[j]] = [ex[j], ex[i]]; cleanupSg(ex) })
const reorder = useRoutineReorder(r, r?.ex || [], (sourceIndex, targetSlot) => {
edit(exercises => { reorderRoutineUnit(exercises, sourceIndex, targetSlot) })
})
if (!r) return null
const move = (i, dir) => {
// Guard before update so a stale/boundary activation cannot trigger persistence or cleanup.
if (!moveSupersetUnit(r.ex, i, dir)) return
edit(ex => {
const reordered = moveSupersetUnit(ex, i, dir)
if (!reordered) return
ex.splice(0, ex.length, ...reordered)
cleanupSg(ex)
})
}
const toggleLink = i => edit(ex => {
if (i < 1) return
const cur = ex[i], prev = ex[i - 1]
@@ -39,6 +335,7 @@ export default function RoutineEdit() {
})
const units = supersetUnits(r.ex)
const unitIndex = new Map(units.flatMap((unit, index) => unit.map(i => [i, index])))
const unitFirst = new Set(units.filter(u => u.length > 1).map(u => u[0]))
const inSS = new Set(units.filter(u => u.length > 1).flat())
const profile = activeProfile(S)
@@ -58,9 +355,19 @@ export default function RoutineEdit() {
<SelectRow icon="chartLine" title={t('Progression')} sheetTitle={t('Progression')}
value={r.prog || 'linear'} onChange={v => update(s => { s.routines.find(x => x.id === id).prog = v })}
options={POLICIES_FOR.reps.map(p => ({ value: p, label: t(POLICY_NAME[p]), subtitle: t(POLICY_DESC[p]) }))} />
<Row icon="pause" iconTint="var(--orange)" title={t('Exclude from automatic progression')}
subtitle={t('Use for planned deloads. Workouts stay in history and statistics.')}>
<Switch checked={r.excludeFromProgression === true} onChange={v => update(s => {
const routine = s.routines.find(x => x.id === id)
if (v) routine.excludeFromProgression = true
else delete routine.excludeFromProgression
})} />
</Row>
</div>
<div className="small dim" style={{ margin: '-10px 2px 16px' }}>
{t('Applies to every exercise in this routine that does not set its own rule.')}
{r.excludeFromProgression
? t('The next regular target continues from the last included workout.')
: t('Applies to every exercise in this routine that does not set its own rule.')}
</div>
{missingCount > 0 && <div className="card" style={{ marginBottom: 16, borderColor: 'var(--orange)' }}>
@@ -70,13 +377,17 @@ export default function RoutineEdit() {
</div>
</div>}
{r.ex.length ? <div className="list">{r.ex.map((e, i) => {
{r.ex.length ? <div ref={reorder.listRef} onClickCapture={reorder.onClickCapture}
className={'list routine-list' + (reorder.drag ? ' is-reordering' : '')}>{r.ex.map((e, i) => {
// An unresolvable id is shown rather than skipped — hiding it left an entry you
// could neither see nor delete, but that still turned up in the workout.
const ex = exOr(e.id)
const noEquip = profile && !exAvailable(S, ex)
const linkedPrev = i > 0 && e.sg && r.ex[i - 1].sg === e.sg
return <div key={i}>
const isDragging = reorder.drag && i >= reorder.drag.first && i <= reorder.drag.last
return <div key={i} data-routine-row data-ex-index={i}
className={'routine-drag-row' + (isDragging ? ' is-dragging' : '')}
style={isDragging ? { transform: `translate3d(0, ${reorder.drag.deltaY}px, 0)` } : undefined}>
{unitFirst.has(i) && <div className="ss-label"><Icon name="link" />{t('Superset')}</div>}
<div className={'item' + (inSS.has(i) ? ' in-ss' : '')} onClick={() => {
exConfigSheet(ex, e, cfg => edit(x => { x[i] = { id: x[i].id, sg: x[i].sg, ...cfg } }), () => edit(x => { x.splice(i, 1); cleanupSg(x) }), r)
@@ -88,13 +399,14 @@ export default function RoutineEdit() {
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 'none', alignItems: 'center' }}>
{i > 0 && <button className={'iconbtn' + (linkedPrev ? ' on-ss' : '')} title={t('Superset with exercise above')} style={{ width: 32, height: 28, borderRadius: 8, fontSize: 15 }} onClick={ev => { ev.stopPropagation(); toggleLink(i) }}><Icon name="link" /></button>}
<div style={{ display: 'flex', gap: 2 }}>
<button className="iconbtn" aria-label="Move up" style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, -1) }}><Icon name="chevronUp" /></button>
<button className="iconbtn" aria-label="Move down" style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, 1) }}><Icon name="chevronDown" /></button>
<button className="iconbtn" aria-label={t('Move up')} title={t('Move up')} disabled={unitIndex.get(i) === 0} style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, -1) }}><Icon name="chevronUp" /></button>
<button className="iconbtn" aria-label={t('Move down')} title={t('Move down')} disabled={unitIndex.get(i) === units.length - 1} style={{ width: 28, height: 24, borderRadius: 7, fontSize: 12 }} onClick={ev => { ev.stopPropagation(); move(i, 1) }}><Icon name="chevronDown" /></button>
</div>
</div>
</div>
</div>
})}</div> : <div className="empty"><div className="ico"><Icon name="dumbbell" /></div>{t('No exercises yet — add your first one.')}</div>}
})}{reorder.drag && <div className="routine-drop-indicator" data-testid="routine-drop-indicator"
aria-hidden="true" style={{ top: `${reorder.drag.indicatorTop}px` }} />}</div> : <div className="empty"><div className="ico"><Icon name="dumbbell" /></div>{t('No exercises yet — add your first one.')}</div>}
{/* Coverage of the routine as planned, so a gap shows up while you're building it
rather than after a month of training around it. */}
@@ -0,0 +1,226 @@
// @vitest-environment happy-dom
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import React, { act } from 'react'
import { LANGS } from '../lib/i18n-core.js'
import { createRoot } from 'react-dom/client'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import RoutineEdit from './RoutineEdit.jsx'
import { DEF, useStore } from '../store/useStore.js'
import { _setLangState } from '../lib/i18n-core.js'
import de from '../locales/de.js'
import { buildPlanBundle, parsePlan } from '../lib/plan-share.js'
const cssSource = readFileSync(resolve(process.cwd(), 'src/index.css'), 'utf8')
const mocks = vi.hoisted(() => ({ exConfigSheet: vi.fn() }))
vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
vi.mock('../sheets.jsx', () => ({
glyphPicker: vi.fn(), exercisePicker: vi.fn(), exConfigSheet: mocks.exConfigSheet, confirmSheet: vi.fn()
}))
vi.mock('../components/Media.jsx', () => ({ Thumb: () => null }))
vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const clone = value => JSON.parse(JSON.stringify(value))
const custom = id => ({ id, n: id, bp: 'chest', eq: 'body weight', tg: 'chest', custom: true })
const entry = (id, setup, sg) => ({
id, sets: 3, reps: 5, weight: setup, note: `setup-${setup}`,
...(sg ? { sg } : {})
})
let root
let container
function setRoutine(ex) {
const S = clone(DEF)
S.routines = [{ id: 'r1', name: 'Move test', emoji: 'dumbbell', ex }]
S.customEx = ['c1', 'c2', 'c3', 'c4'].map(custom)
useStore.setState({ S, user: null })
}
function renderRoutine() {
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
act(() => root.render(
<MemoryRouter initialEntries={['/routine/r1']}>
<Routes><Route path="/routine/:id" element={<RoutineEdit />} /></Routes>
</MemoryRouter>
))
}
function itemFor(name) {
return [...container.querySelectorAll('.item')].find(item => item.textContent.includes(name))
}
function moveButton(name, direction) {
return itemFor(name).querySelector(`button[aria-label="${direction}"]`)
}
function pointerActivateArea(button) {
// Model browser hit-testing: pointer-events:none removes the disabled button
// from the target chain, exposing the clickable routine row underneath.
const disabledRule = cssSource.match(/\.iconbtn:disabled\s*\{[^}]*\}/)?.[0] || ''
const target = /pointer-events\s*:\s*none/.test(disabledRule)
? button.closest('.item')
: button
act(() => {
target.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
target.dispatchEvent(new PointerEvent('pointerup', { bubbles: true }))
if (!(target instanceof HTMLButtonElement && target.disabled)) {
target.dispatchEvent(new MouseEvent('click', { bubbles: true }))
}
})
}
beforeEach(() => {
localStorage.clear()
mocks.exConfigSheet.mockClear()
_setLangState('en', null, null, null)
root = null
container = null
})
afterEach(() => {
if (root) act(() => root.unmount())
if (container) container.remove()
_setLangState('en', null, null, null)
})
describe('routine move controls', () => {
it('moves a selected superset member as one contiguous unit and persists complete occurrences', () => {
setRoutine([
entry('c1', 10, 'g'),
entry('c2', 20, 'g'),
entry('c3', 30)
])
renderRoutine()
act(() => moveButton('setup-20', 'Move down').click())
const moved = useStore.getState().S.routines[0].ex
expect(moved).toEqual([
entry('c3', 30),
entry('c1', 10, 'g'),
entry('c2', 20, 'g')
])
expect(JSON.parse(localStorage.getItem('gym_state_v1')).routines[0].ex).toEqual(moved)
})
it('moves the selected duplicate occurrence without aliasing its configuration', () => {
setRoutine([
entry('c1', 10),
entry('c2', 20),
entry('c1', 30)
])
renderRoutine()
act(() => moveButton('setup-30', 'Move up').click())
expect(useStore.getState().S.routines[0].ex).toEqual([
entry('c1', 10),
entry('c1', 30),
entry('c2', 20)
])
})
it('moves a standalone occurrence down with every configuration field intact', () => {
const selected = {
...entry('c1', 10),
mode: 'reps', prog: 'double', repsMin: 4, repsMax: 12,
side: true, warmupSets: 2,
intensifier: { type: 'restpause', pauseSec: 20 }
}
setRoutine([selected, entry('c2', 20), entry('c3', 30)])
renderRoutine()
act(() => moveButton('setup-10', 'Move down').click())
expect(useStore.getState().S.routines[0].ex).toEqual([
entry('c2', 20), selected, entry('c3', 30)
])
})
it('disables unit-boundary directions without cleaning or persisting state', () => {
setRoutine([
entry('c1', 10, 'orphan'),
entry('c2', 20)
])
renderRoutine()
const before = useStore.getState().S
expect(moveButton('c1', 'Move up').disabled).toBe(true)
expect(moveButton('c2', 'Move down').disabled).toBe(true)
act(() => moveButton('c1', 'Move up').click())
expect(useStore.getState().S).toBe(before)
expect(useStore.getState().S.routines[0].ex[0].sg).toBe('orphan')
expect(localStorage.getItem('gym_state_v1')).toBeNull()
})
it('keeps pointer activation in both disabled boundary areas isolated from the routine row', () => {
setRoutine([
entry('c1', 10, 'orphan'),
entry('c2', 20)
])
renderRoutine()
const before = useStore.getState().S
const firstUp = moveButton('c1', 'Move up')
const lastDown = moveButton('c2', 'Move down')
expect(firstUp.disabled).toBe(true)
expect(lastDown.disabled).toBe(true)
pointerActivateArea(firstUp)
pointerActivateArea(lastDown)
expect(mocks.exConfigSheet).not.toHaveBeenCalled()
expect(useStore.getState().S).toBe(before)
expect(useStore.getState().S.routines[0].ex[0].sg).toBe('orphan')
expect(localStorage.getItem('gym_state_v1')).toBeNull()
})
it('uses localized accessible names and titles, retains button focus, and does not open config', () => {
_setLangState('de', de, null, null)
setRoutine([entry('c1', 10), entry('c2', 20)])
renderRoutine()
const button = moveButton('c2', 'Nach oben')
expect(button.title).toBe('Nach oben')
button.focus()
act(() => button.click())
expect(document.activeElement?.tagName).toBe('BUTTON')
expect(mocks.exConfigSheet).not.toHaveBeenCalled()
})
it('retains reordered occurrence order and grouping through plan export and import', () => {
setRoutine([
entry('c1', 10, 'g'),
entry('c2', 20, 'g'),
entry('c3', 30)
])
renderRoutine()
act(() => moveButton('setup-10', 'Move down').click())
const parsed = parsePlan(JSON.stringify(buildPlanBundle(useStore.getState().S, 'Move test')))
expect(parsed.routines[0].ex).toEqual([
entry('c3', 30),
entry('c1', 10, 'g'),
entry('c2', 20, 'g')
])
})
})
describe('routine move-control locale coverage', () => {
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
it('defines both accessible names in every non-English locale pack', () => {
expect(Object.keys(packs)).toHaveLength(Object.keys(LANGS).length - 1)
Object.entries(packs).forEach(([path, pack]) => {
expect(pack, `${path} is missing Move up`).toHaveProperty('Move up')
expect(pack, `${path} is missing Move down`).toHaveProperty('Move down')
})
})
})
@@ -0,0 +1,90 @@
// @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 Settings from './Settings.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
},
replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
})
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('../store/useUI.js', () => {
const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })
const useUI = selector => selector ? selector(snap()) : snap()
useUI.getState = snap
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../lib/api.js', () => ({
api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
}))
// The Settings view reads the build-time version constant at render time.
globalThis.__APP_VERSION__ ??= 'test'
let host, root
beforeEach(() => {
mocks.S = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
gifSize: 'full', workouts: [], routines: [], exWeights: {},
}
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const mount = () => act(() => root.render(<Settings />))
const segButton = label => [...host.querySelectorAll('.seg button')].find(b => b.textContent === label)
describe('Settings — exercise animations', () => {
it('offers Full / Small / Hidden and writes gifSize to the store', () => {
mount()
expect(segButton('Full')).toBeTruthy()
expect(segButton('Small')).toBeTruthy()
expect(segButton('Hidden')).toBeTruthy()
expect(segButton('Full').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('Hidden').click() })
expect(mocks.S.gifSize).toBe('off')
mount()
expect(segButton('Hidden').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('Small').click() })
expect(mocks.S.gifSize).toBe('mini')
})
it('shows a legacy/absent value as Full', () => {
delete mocks.S.gifSize
mount()
expect(segButton('Full').getAttribute('aria-pressed')).toBe('true')
expect(segButton('Hidden').getAttribute('aria-pressed')).toBe('false')
})
})
+24 -2
View File
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore, DEF, hasData } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { ACCENTS, todayISO, localTZ } from '../lib/format.js'
import { ACCENTS, todayISO, localTZ, weekStartOf, MONDAY, SUNDAY } from '../lib/format.js'
import { effortOf } from '../lib/history.js'
import { api, webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js'
@@ -11,7 +11,7 @@ import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
import { DEMO, REPO } from '../lib/demo.js'
import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js'
import { ConnectSheet } from './MobileOnboarding.jsx'
import { loadStarterPlan, confirmSheet, importFromApp, equipmentProfileSheet } from '../sheets.jsx'
import { loadStarterPlan, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'
@@ -133,6 +133,13 @@ export default function Settings() {
options={[{ value: 'kg', label: 'kg' }, { value: 'lb', label: 'lb' }]}
value={S.unit} onChange={v => update(s => { s.unit = v })} />
</Row>
{/* Monday or Sunday — the Plan list, the Home strip, the calendar grid and every
"this week" total follow it. Stored as a getDay() index (see lib/format.js). */}
<Row icon="calendar" iconTint="var(--orange)" title={t('Week starts on')}>
<Segmented className="seg-inline"
options={[{ value: MONDAY, label: t('Monday') }, { value: SUNDAY, label: t('Sunday') }]}
value={weekStartOf(S)} onChange={v => update(s => { s.weekStart = v })} />
</Row>
</Section>
{/* ---------- during a workout ---------- */}
@@ -153,9 +160,21 @@ export default function Settings() {
onChange={v => update(s => { s.keepAwake = v })} />
</Row>
)}
{/* 'full'/'mini' is also what the tap-toggle on the workout animation writes; 'off' hides
workout media entirely (library, detail sheet and picker thumbs are unaffected).
Legacy/unknown values read as 'full'. */}
<Row icon="figureRun" iconTint="var(--green)" title={t('Exercise animations')}>
<Segmented className="seg-inline"
options={[{ value: 'full', label: t('Full') }, { value: 'mini', label: t('Small') }, { value: 'off', label: t('Hidden') }]}
value={S.gifSize === 'mini' || S.gifSize === 'off' ? S.gifSize : 'full'}
onChange={v => update(s => { s.gifSize = v })} />
</Row>
<Row icon="bell" iconTint="var(--pink)" title={t('Sounds')}>
<Switch checked={!!S.sound} onChange={v => update(s => { s.sound = v })} />
</Row>
<Row icon="sun" iconTint="var(--yellow)" title={t('Flash screen when timer ends')}>
<Switch checked={!!S.timerFlash} onChange={v => update(s => { s.timerFlash = v })} />
</Row>
{/* Two names for the same judgement, so the column asks in the scale you already think in.
The (i) sits before the control — you read it on the way to the choice, not after it. */}
<Row icon="target" iconTint="var(--purple)" title={t('Effort per set')}>
@@ -211,6 +230,9 @@ export default function Settings() {
<Row icon="shuffle" iconTint="var(--teal)" title={t('Import from another app')}
subtitle={t('FitNotes, Strong, Hevy — or body weight from Apple Health')}
accessory="chevron" onClick={() => importRef.current.click()} />
<Row icon="key" iconTint="var(--teal)" title={t('Import from Hevy')}
subtitle={t('Pull your history with a Hevy Pro API key')}
accessory="chevron" onClick={importFromHevy} />
<Row icon="upload" iconTint="var(--blue)" title={t('Import backup')} accessory="chevron" onClick={() => fileRef.current.click()} />
<Row icon="download" iconTint="var(--blue)" title={t('Export backup (JSON)')} accessory="chevron" onClick={doExport} />
{MOBILE && <Row icon="history" iconTint="var(--blue)" title={t('Auto-backup on changes')}
+45 -10
View File
@@ -1,16 +1,16 @@
import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { EXIDX } from '../lib/exercises.js'
import { EXIDX, matchExercise } from '../lib/exercises.js'
import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js'
import { fmtNum, fmtDate, fmtVol, todayISO, weekKey } from '../lib/format.js'
import { fmtNum, fmtDate, fmtVol, todayISO, weekStartOf } from '../lib/format.js'
import { t, exerciseNameFor, getLang } from '../lib/i18n.js'
import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
import Heatmap from '../components/Heatmap.jsx'
import Icon from '../components/Icon.jsx'
import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'
import { loadOfWorkouts, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
import { loadOfWorkouts, muscleBalanceWindow, rankOf, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
import { fatigueOf, strengthOf, STRENGTH_FLOOR, LB_TO_KG } from '../lib/recovery.js'
import { strengthExerciseRowsForMuscle } from '../lib/strength-exercises.js'
import { fatigueStateOf } from '../lib/recovery-view.js'
@@ -20,6 +20,7 @@ import {
effortHistogram, isHardSet, HARD_RIR
} from '../lib/effort.js'
import { Button, Segmented, SelectRow } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { isWarmupRow } from '../lib/workout-model.js'
// Which muscles the training in a window actually hit — and, the point of the card,
@@ -122,10 +123,7 @@ function MuscleBalance({ S }) {
return t('Weeks since training: {0}', weeks)
}
const toggleSel = m => setSel(s => (s === m ? null : m))
const inWin = S.workouts.filter(w =>
win === 0 ? true
: win === 7 ? weekKey(w.d) === weekKey(todayISO())
: (w.start || new Date(w.d).getTime()) > now - win * 86400000)
const inWin = muscleBalanceWindow(S.workouts, win, now, todayISO(), weekStartOf(S))
// Counting only the sets taken near failure turns the map from "where did the volume go"
// into "where did the stimulus go" — a muscle can lead on sets and still never be trained
// hard. Offered only when the window holds ratings at all, since with none the hard map
@@ -192,7 +190,7 @@ function MuscleBalance({ S }) {
{sel && <>
<h4 className="sec" style={{ marginTop: 14 }}>{t('Exercises')} · {t(MUSCLE_NAME[sel])}</h4>
{muscleExercises.length ? muscleExercises.map(row => (
<div key={row.id} className="mrow" style={{ minHeight: 48, alignItems: 'stretch', cursor: 'pointer' }} onClick={() => onExercise && onExercise(row.id)}>
<div key={row.id} className="mrow" style={{ minHeight: 48, alignItems: 'stretch', cursor: 'pointer' }} {...tappable(() => onExercise && onExercise(row.id))}>
<span className="nm" style={{ whiteSpace: 'normal', lineHeight: 1.35, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
<span style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{row.name}
@@ -291,7 +289,38 @@ export default function Stats() {
const workouts = S.workouts
const monthW = workouts.filter(w => String(w.d || '').slice(0, 7) === todayISO().slice(0, 7)).length
const nameOf = id => EXIDX[id] ? exerciseNameFor(EXIDX[id]) : (workouts.flatMap(w => w.entries).find(e => e.id === id)?.n || id)
const entryOf = id => workouts.flatMap(w => w.entries).find(e => e.id === id)
const listOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value]
const firstAvailable = (...values) => {
for (const value of values) {
const list = listOf(value)
if (list.length) return list
}
return []
}
const nameOf = id => {
if (EXIDX[id]) return exerciseNameFor(EXIDX[id])
const entry = entryOf(id)
return entry?.muscleSnapshot?.n || entry?.n || id
}
const matcherOf = id => {
if (EXIDX[id]) return EXIDX[id]
const entry = entryOf(id)
const snapshot = entry?.muscleSnapshot || {}
const primaries = firstAvailable(snapshot.primaries, entry?.primaries)
const secondaries = firstAvailable(
snapshot.sm, snapshot.secondaries, snapshot.muscleGroups,
entry?.sm, entry?.secondaries, entry?.muscleGroups,
)
return {
n: snapshot.n || entry?.n || id,
bp: snapshot.bp || entry?.bp || '',
tg: primaries[0] || snapshot.tg || entry?.tg || '',
sm: secondaries,
eq: snapshot.eq || entry?.eq || '',
desc: snapshot.desc || entry?.desc || '',
}
}
const currentOf = id => {
for (let i = workouts.length - 1; i >= 0; i--) {
const en = workouts[i].entries.find(e => e.id === id)
@@ -428,7 +457,13 @@ export default function Stats() {
{exHist.length ? <>
<div className="sect-b" style={{ marginBottom: 10 }}>
<SelectRow title={t('Exercise')} sheetTitle={t('Exercise progress')} value={curEx} onChange={setExId} stackedValue
options={exHist.map(id => ({ value: id, label: nameOf(id) + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))} />
options={exHist.map(id => ({ value: id, label: nameOf(id) + (exCurrent[id].mx ? ' ' + '—' + ' ' + fmtNum(exCurrent[id].mx) + ' ' + exCurrent[id].unit : '') }))}
search={{
placeholder: t('Search…'),
label: t('Search…'),
emptyLabel: t('No match'),
match: (option, query) => matchExercise(matcherOf(option.value), query),
}} />
</div>
{exOpts.length > 1 && <Segmented className="seg-range" value={onEff ? 'effort' : onE1 ? 'e1rm' : 'top'} onChange={setExMetric} options={exOpts} />}
<div className="chart">
+108 -1
View File
@@ -1,15 +1,21 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { Window } from 'happy-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { EXIDX } from '../lib/exercises.js'
import { MUSCLES, levelsOf } from '../lib/muscles.js'
import { FATIGUE_STATES, STRENGTH_FLOOR } from '../lib/recovery.js'
import { fatigueStateOf } from '../lib/recovery-view.js'
import Stats from './Stats.jsx'
import Modals from '../components/Modals.jsx'
import { bindUI } from '../components/ui.jsx'
import { useUI } from '../store/useUI.js'
const DAY = 86400000
const HOUR = 3600000
const BASE_NOW = Date.UTC(2026, 0, 22, 12)
const LEGACY_SNAPSHOT_ID = 'legacy-snapshot-only'
const mocks = vi.hoisted(() => ({
maps: [],
@@ -50,6 +56,8 @@ vi.mock('../components/BodyMap.jsx', () => ({
BodyMapLegend: () => React.createElement('div', { 'data-balance-legend': true }),
}))
bindUI(useUI)
let dom
let root
let container
@@ -105,19 +113,43 @@ function allSubfullWorkout(now = BASE_NOW) {
return workout('all-subfull', now - 15 * DAY, [entry('1254', [set(true)])])
}
function exercisePickerWorkouts(now = BASE_NOW) {
return [
workout('bench', now, [entry('0025', [set(true, { w: 80 })])]),
workout('squat', now - DAY, [entry('0043', [set(true, { w: 60 })])]),
workout('legacy', now - 2 * DAY, [
{
id: LEGACY_SNAPSHOT_ID,
muscleSnapshot: {
n: 'Legacy shoulder press',
bp: 'shoulders',
primaries: ['deltoids'],
secondaries: ['triceps'],
muscleGroups: ['deltoids', 'triceps'],
},
sets: [set(true, { w: 50 })],
},
]),
]
}
function resetFixture(workouts = lifecycleWorkouts()) {
mocks.S.unit = 'kg'
mocks.S.bodyweight = []
mocks.S.workouts = workouts
mocks.maps.length = 0
mocks.mapMounts = 0
useUI.setState({ sheets: [] })
}
function installDom() {
dom = new Window({ url: 'http://localhost/' })
dom.scrollTo = vi.fn()
globalThis.window = dom
globalThis.document = dom.document
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
Object.defineProperty(globalThis, 'location', { configurable: true, value: dom.location })
Object.defineProperty(globalThis, 'history', { configurable: true, value: dom.history })
for (const key of ['HTMLElement', 'HTMLIFrameElement', 'Node', 'Element', 'Event', 'MouseEvent']) {
globalThis[key] = dom[key]
}
@@ -129,7 +161,7 @@ function installDom() {
async function mountStats() {
installDom()
await act(async () => { root.render(React.createElement(Stats)) })
await act(async () => { root.render(React.createElement(React.Fragment, null, React.createElement(Stats), React.createElement(Modals))) })
}
async function unmountStats() {
@@ -179,6 +211,7 @@ beforeEach(() => {
afterEach(async () => {
await unmountStats()
useUI.setState({ sheets: [] })
vi.useRealTimers()
vi.restoreAllMocks()
})
@@ -272,3 +305,77 @@ describe('Stats muscle recovery view runtime', () => {
expect(strengthMap.thresholds.at(-1)).toEqual({ at: 1, level: 4 })
})
})
describe('Stats exercise progress picker', () => {
it('filters with the shared exercise matcher and still selects from the mounted sheet', async () => {
resetFixture(exercisePickerWorkouts())
await mountStats()
expect(EXIDX[LEGACY_SNAPSHOT_ID]).toBeUndefined()
const card = [...container.querySelectorAll('.card')].find(el => el.querySelector('h2')?.textContent.trim() === 'Exercise progress')
const selector = [...card.querySelectorAll('button')].find(button => button.querySelector('.lrow-t')?.textContent.trim() === 'Exercise')
await click(selector)
const modal = document.querySelector('#modal-root')
const input = modal.querySelector('input')
expect(input).toBeTruthy()
expect(input.getAttribute('aria-label')).toBe('Search…')
expect(input.getAttribute('placeholder')).toBe('Search…')
expect(modal.querySelector('.picker-search')).toBeTruthy()
const optionButtons = () => [...modal.querySelectorAll('.sect-b button')]
const initialOptionCount = optionButtons().length
expect(initialOptionCount).toBe(3)
expect(modal.textContent).toContain('Legacy shoulder press')
expect(input.compareDocumentPosition(optionButtons()[0]) & globalThis.Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
const setter = Object.getOwnPropertyDescriptor(input.constructor.prototype, 'value').set
const setSearch = async value => act(async () => {
setter.call(input, value)
input.dispatchEvent(new Event('input', { bubbles: true }))
input.dispatchEvent(new Event('change', { bubbles: true }))
})
// A focused search can leave a newly narrowed result below the visual viewport. The
// correction must advance the sheet's own scroll position, not the page behind it.
const sheet = modal.querySelector('.sheet')
const firstOption = optionButtons()[0]
Object.defineProperties(sheet, {
clientHeight: { configurable: true, value: 400 },
scrollHeight: { configurable: true, value: 1000 },
})
vi.spyOn(sheet, 'getBoundingClientRect').mockReturnValue({ bottom: 600 })
vi.spyOn(firstOption, 'getBoundingClientRect').mockReturnValue({ bottom: 500 })
Object.defineProperty(window, 'visualViewport', { configurable: true, value: { height: 300 } })
input.focus()
expect(sheet.style.getPropertyValue('--picker-visual-height')).toBe('300px')
expect(sheet.style.getPropertyValue('--picker-keyboard-bottom')).toBe(`${Math.max(0, window.innerHeight - 300)}px`)
await setSearch('bench')
await tick(100)
expect(sheet.scrollTop).toBeGreaterThan(0)
await setSearch('no such historical exercise')
expect(modal.textContent).toContain('No match')
expect(optionButtons()).toHaveLength(0)
await click(modal.querySelector('button[aria-label="Clear"]'))
expect(input.value).toBe('')
expect(optionButtons()).toHaveLength(initialOptionCount)
expect(modal.textContent).toContain('Legacy shoulder press')
await setSearch('legacy shoulder press shoulders deltoids triceps')
expect(optionButtons()).toHaveLength(1)
expect(optionButtons()[0].textContent).toContain('Legacy shoulder press')
await click(modal.querySelector('button[aria-label="Clear"]'))
await setSearch('squat full bárbell')
expect(modal.textContent).toContain('barbell full squat')
expect(modal.textContent).not.toContain('barbell bench press')
const matching = [...modal.querySelectorAll('button')].find(button => button.textContent.includes('barbell full squat'))
await click(matching)
expect(useUI.getState().sheets).toHaveLength(0)
expect(card.querySelector('.lrow-v').textContent).toContain('barbell full squat')
})
})
+1 -1
View File
@@ -19,7 +19,7 @@ describe('Stats mixed-entry metric contract', () => {
it('renders one clickable muscle exercise list rather than a duplicate non-clickable copy', () => {
expect((source.match(/muscleExercises\.length \? muscleExercises\.map\(row =>/g) || []).length).toBe(1)
expect(source).toContain('onClick={() => onExercise && onExercise(row.id)}')
expect(source).toContain('{...tappable(() => onExercise && onExercise(row.id))}')
})
it('uses the shared metric mode and row helpers rather than entryMode as a chart gate', () => {
+201 -39
View File
@@ -9,14 +9,20 @@ import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import { setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from '../lib/supersetFlow.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, barWeightSheet } from '../sheets.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button, Check, NumberField } from '../components/ui.jsx'
import { nextPrescription, applyPrescription, defaultIncrement } from '../lib/progression.js'
import { progressionGuidance } from '../lib/progression-copy.js'
import { glyphOf } from '../lib/glyphs.js'
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps } from '../lib/workout-model.js'
import { canMoveActiveWorkoutUnit, moveActiveWorkoutUnit } from '../lib/active-workout-order.js'
const SWIPE_MIN_DISTANCE = 48
const SWIPE_AXIS_RATIO = 1.25
const SWIPE_IGNORED_TARGETS = 'button,input,textarea,select,a,[role="button"],[role="checkbox"],[role="switch"],[role="slider"],[contenteditable="true"],.exmedia,[data-swipe-ignore]'
/* ---------- start chooser (no active workout) ---------- */
function StartChooser() {
@@ -57,7 +63,7 @@ function Elapsed({ start }) {
}
/* ---------- one exercise block (reps: weight×reps · time: a held duration · cardio: duration+speed) ---------- */
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext }) {
function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemoveSet, onAddWarmup, onRemoveSetAt, onStartTimed, onPairPrev, onPairNext, onSetRowRef, onProgressionSettings }) {
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const working = useUI(s => s.work)
@@ -107,6 +113,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
// What the progression policy decided for this session, and why (issue #17). Computed when
// the session was built so the reason matches the numbers already in the rows.
const plan = entry.plan
const guidance = progressionGuidance(plan)
// A bodyweight set has no weight to type, so the column is not there (issue #32) — one
// stepper instead of two, which is the whole point of the flag. Adding a belt weight in the
// config brings it back, now labelled as the addition it is.
@@ -208,10 +215,11 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
</button>
</div>
})()}
{plan && plan.why && plan.kind !== 'off' && <div className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}>
{guidance && <button type="button" className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}
aria-label={t('Open progression settings')} onClick={onProgressionSettings}>
<Icon name={plan.kind === 'up' ? 'arrowUp' : plan.kind === 'deload' ? 'arrowDown' : 'lightbulb'} />
<span>{t(...plan.why)}</span>
</div>}
<span><strong>{t(guidance.policyLabel)}</strong> · {t(...guidance.why)}</span>
</button>}
<div className="card" style={{ marginTop: 10, marginBottom: 0 }}>
{/* the header carries the same eff3 sizing as the rows, or the labels drift off their columns */}
<div className={'sethead' + (col3 ? ' eff3' : '')}><span className="n-sp" /><span className="w-sp">{col1.hd}</span>{col2 && <span className="r-sp">{col2.hd}</span>}{col3 && <span className="eff-sp">{col3.hd}</span>}{timed && <span className="ck-sp" />}<span className="ck-sp" /></div>
@@ -224,7 +232,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
return <div key={i}>
{isFirstWarmup && <div className="setph">{t('Warm-up')}</div>}
{!warm && warmBefore && <div className="setsep" />}
<div className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
<div ref={el => onSetRowRef?.(i, el)} className={'setrow' + (s.done ? ' done' : '') + (col3 ? ' eff3' : '')}>
<div className="n">{phaseNum}</div>
{cell(s, i, col1, 'w')}
{col2 && cell(s, i, col2, 'r')}
@@ -279,6 +287,13 @@ export function removeActiveExercise(idx) {
// Clear the work callback before indexes can shift. This also protects a confirmation sheet
// that was opened first and confirmed after a timed hold started.
useUI.getState().stopWork()
// A rest countdown belongs to the exercise whose set started it (timer.forIdx). Removing that
// exercise ends the rest — there is nothing left to rest for. Removing any other exercise
// keeps the countdown and only re-points it, so a pause you are in the middle of survives
// tidying up the list.
const rest = useUI.getState().timer
if (rest && rest.forIdx === idx) useUI.getState().stopRest()
else useUI.getState().shiftRestOwner(idx + 1, -1)
useStore.getState().update(s => {
if (!s.active || !Array.isArray(s.active.entries)) return
if (idx < 0 || idx >= s.active.entries.length) return
@@ -293,16 +308,41 @@ function ActiveWorkout() {
const nav = useNavigate()
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const { startRest, stopRest, work } = useUI()
const { startRest: liveRest, stopRest, stopWork, work } = useUI()
const A = S.active
// A past workout has no rest to time — the sets were done days ago. The work timer for
// timed sets stays, since counting a hold is how its duration gets entered.
const startRest = A.backfill ? () => {} : liveRest
const units = supersetUnits(A.entries)
const cur = Math.min(A.cur, Math.max(0, A.entries.length - 1))
const cur = Number.isInteger(A.cur)
? Math.min(Math.max(A.cur, 0), Math.max(0, A.entries.length - 1))
: 0
const unit = A.entries.length ? unitOf(units, cur) : []
const unitIdx = units.findIndex(u => u === unit)
const isSuperset = unit.length > 1
// Superset flow: keep the active exercise in view - completing a set scrolls to the
// next exercise in the group, then back up to the first exercise of the next round.
const exRefs = useRef({})
// Superset flow: center the actionable row when completing a set moves to the partner or
// back to the first exercise of the next round. Entry-bound maps keep repeated exercise IDs
// distinct, while each rendered set index identifies the existing row within that entry.
const exRefs = useRef(new Map())
const setRefs = useRef(new Map())
const bindExRef = (entry, el) => {
if (el) exRefs.current.set(entry, el)
else {
exRefs.current.delete(entry)
setRefs.current.delete(entry)
}
}
const bindSetRef = (entry, setIdx, el) => {
let refs = setRefs.current.get(entry)
if (el) {
if (!refs) { refs = new Map(); setRefs.current.set(entry, refs) }
refs.set(setIdx, el)
} else if (refs) {
refs.delete(setIdx)
if (!refs.size) setRefs.current.delete(entry)
}
}
const swipe = useRef(null)
const progressHighWater = useRef(A.entries.map(e => e.sets.filter(s => s.done).length))
// The marks are index-keyed, and removing an exercise shifts every index above it down
// (removeActiveExercise splices). Re-baseline whenever the list length changes, otherwise a
@@ -310,10 +350,22 @@ function ActiveWorkout() {
useEffect(() => {
progressHighWater.current = A.entries.map(e => e.sets.filter(s => s.done).length)
}, [A.entries.length])
useEffect(() => {
const liveEntries = new Set(A.entries)
for (const entry of exRefs.current.keys()) {
if (!liveEntries.has(entry)) exRefs.current.delete(entry)
}
for (const entry of setRefs.current.keys()) {
if (!liveEntries.has(entry)) setRefs.current.delete(entry)
}
})
useEffect(() => {
if (!isSuperset) return
const el = exRefs.current[cur]
if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
const entry = A.entries[cur]
const firstIncomplete = entry?.sets.findIndex(s => !s.done) ?? -1
const setIdx = firstIncomplete >= 0 ? firstIncomplete : (entry?.sets.length ?? 0) - 1
const el = (setIdx >= 0 && setRefs.current.get(entry)?.get(setIdx)) || exRefs.current.get(entry)
if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, [cur, isSuperset, A.entries.length])
const total = A.entries.reduce((n, e) => n + e.sets.length, 0)
@@ -352,6 +404,84 @@ function ActiveWorkout() {
})
const onPairPrev = !isSuperset && cur > 0 ? () => pairAt(cur - 1, cur) : null
const onPairNext = !isSuperset && cur < A.entries.length - 1 ? () => pairAt(cur, cur + 1) : null
const moveCurrentUnit = direction => {
const ui = useUI.getState()
const active = useStore.getState().S.active
if (ui.work || !canMoveActiveWorkoutUnit(active, active?.cur, direction)) return
// Invalidate an old timed callback before indexes shift. A running rest is not cancelled:
// it belongs to an exercise (timer.forIdx), and that exercise only changes position.
ui.stopWork()
update(s => {
const moved = moveActiveWorkoutUnit(s.active, s.active?.cur, direction)
if (!moved) return
progressHighWater.current = moved.indices.map(index => progressHighWater.current[index])
const rest = useUI.getState().timer
if (rest && rest.forIdx != null) {
const forIdx = moved.indices.indexOf(rest.forIdx)
if (forIdx >= 0) useUI.setState({ timer: { ...rest, forIdx } })
}
}, true)
}
const navigateUnit = direction => {
const targetFor = active => {
if (!active || !Array.isArray(active.entries) || !Number.isInteger(active.cur)) return null
if (active.cur < 0 || active.cur >= active.entries.length) return null
const freshUnits = supersetUnits(active.entries)
const freshUnitIdx = freshUnits.findIndex(candidate => candidate.includes(active.cur))
return freshUnitIdx < 0 ? null : freshUnits[freshUnitIdx + direction]?.[0] ?? null
}
if (targetFor(useStore.getState().S.active) == null) return
update(s => {
const target = targetFor(s.active)
if (target != null) s.active.cur = target
})
}
const onSwipePointerDown = event => {
if (swipe.current || (event.pointerType && event.pointerType !== 'touch' && event.pointerType !== 'pen')) return
if (event.target.closest?.(SWIPE_IGNORED_TARGETS)) return
swipe.current = { id: event.pointerId, x: event.clientX, y: event.clientY }
event.currentTarget.setPointerCapture?.(event.pointerId)
}
const finishSwipe = (event, navigate) => {
const start = swipe.current
if (!start || start.id !== event.pointerId) return
swipe.current = null
event.currentTarget.releasePointerCapture?.(event.pointerId)
if (!navigate) return
const dx = event.clientX - start.x
const dy = event.clientY - start.y
if (Math.abs(dx) < SWIPE_MIN_DISTANCE || Math.abs(dx) < Math.abs(dy) * SWIPE_AXIS_RATIO) return
navigateUnit(dx < 0 ? 1 : -1)
}
const openProgressionSettings = idx => {
const state = useStore.getState().S
const entry = state.active?.entries?.[idx]
if (!entry) return
const routine = state.routines.find(r => r.id === state.active.routineId)
exConfigSheet(exOr(entry.id), entry.target, cfg => update(s => {
const activeEntry = s.active?.entries?.[idx]
if (!activeEntry) return
const full = { ...cfg, id: activeEntry.id }
const activeRoutine = s.routines.find(r => r.id === s.active.routineId)
const step = defaultIncrement(activeEntry.id, s.unit)
// A config without a set count keeps the rows the session already has.
if (!(full.sets > 0)) full.sets = activeEntry.sets.filter(x => !isWarmupRow(x)).length || 1
const plan = nextPrescription(s, full, activeRoutine)
// The sheet edits sets, reps, weight and warm-ups as well as the rule — so the rows are
// rebuilt from the new config the way the session was, and only what you already logged
// is kept in place (done warm-ups first, then done work sets, then the fresh remainder).
const fresh = applyIntensifierPlan(applyPrescription(buildSets(s, full, { step }), plan, step), full)
const doneWarm = activeEntry.sets.filter(x => x.done && isWarmupRow(x))
const doneWork = activeEntry.sets.filter(x => x.done && !isWarmupRow(x))
const freshWarm = fresh.filter(isWarmupRow)
const freshWork = fresh.filter(x => !isWarmupRow(x))
activeEntry.target = { ...cfg }
activeEntry.plan = plan
activeEntry.sets = [...doneWarm, ...freshWarm.slice(doneWarm.length), ...doneWork, ...freshWork.slice(doneWork.length)]
}), null, routine)
}
// Remove a whole exercise from the session. The confirmation always asks first; in a
// superset it asks WHICH exercise of the group to remove.
@@ -400,7 +530,6 @@ function ActiveWorkout() {
const toggle = (idx, i) => {
const m = modeAt(idx)
const cardioEntry = m === 'cardio'
const isLastUnit = unitIdx >= units.length - 1
let askTop = false, exJustDone = false, workoutDone = false, checked = false
mutEntry(idx, e => {
e.sets[i].done = !e.sets[i].done
@@ -408,7 +537,7 @@ function ActiveWorkout() {
if (e.sets[i].done) {
beep(S.sound, 1040, 0.12); vibrate(30)
const unitDone = unit.every(ui => (ui === idx ? e : A.entries[ui]).sets.every(x => x.done))
if (unitDone && isLastUnit) workoutDone = true // last exercise's last set → done
if (unitDone) workoutDone = !nextUnfinishedUnit(A.entries, supersetUnits(A.entries), idx)
// Only loaded reps training has a "working weight" worth confirming — a bodyweight
// plank has nothing to put in that slider, and neither does a set of push-ups
// (issue #32: the fewest taps that still record what happened).
@@ -432,38 +561,45 @@ function ActiveWorkout() {
const freshUnits = supersetUnits(fresh.entries)
const freshUnit = freshUnits.find(u => u.includes(idx))
const freshUnitIdx = freshUnits.indexOf(freshUnit)
const freshLastUnit = freshUnitIdx >= freshUnits.length - 1
const freshUnitDone = freshUnit?.every(ui => fresh.entries[ui].sets.every(x => x.done))
const nextUnit = freshUnitDone ? nextUnfinishedUnit(fresh.entries, freshUnits, idx) : null
const freshWorkoutDone = freshUnitDone && !nextUnit
const restBeforeWarmup = nextUnit?.some(ui =>
fresh.entries[ui].sets.some(set => isWarmupRow(set) && !set.done),
)
// The rest this set has earned: the exercise's own restSec when it set one, the global
// timer when it did not, and the longest of the group's across a superset (issue #10).
// Resolved once here so every branch below times the same break.
const restSec = restSecFor(fresh.entries, freshUnit || [idx], S.restSec)
// A re-check of finished work must not navigate or reopen a sheet, but it may still owe
// you a rest — see restOnRecheck, and the other half of issue #3.
if (!progress.isNew) {
if (restOnRecheck({ timerRunning: !!useUI.getState().timer, unitDone: freshUnitDone, lastUnit: freshLastUnit })) startRest(S.restSec)
if (!restBeforeWarmup && restOnRecheck({ timerRunning: !!useUI.getState().timer, unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restSec, idx)
return
}
// Singleton units are ordinary exercises: they rest between sets and after the closing
// one, and never enter superset navigation. stopRest() first so the rest that belongs
// after this set replaces the one that was running, rather than stacking on it.
// one unless the next unit has an unfinished warm-up, and never enter superset navigation.
// stopRest() first so a rest that belongs after this set replaces the one that was running.
if (freshUnitDone) stopRest()
if (!freshUnit || freshUnit.length <= 1) {
if (restAfterSet({ unitDone: freshUnitDone, lastUnit: freshLastUnit })) startRest(S.restSec)
if (freshUnitDone && !askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup && restAfterSet({ unitDone: freshUnitDone, lastUnit: freshWorkoutDone })) startRest(restSec, idx)
return
}
const step = supersetFlowStep(fresh.entries, freshUnit, idx)
if (!step) return
if (step.unitDone) {
if (!freshLastUnit) {
const nextUnit = freshUnits[freshUnitIdx + 1]
if (nextUnit?.length) {
// The top-weight sheet's explicit "Just close" path owns the choice not to advance.
if (!askTop && nextUnit?.length) update(s => { if (s.active) s.active.cur = nextUnit[0] })
startRest(S.restSec)
if (!askTop) update(s => { if (s.active) s.active.cur = nextUnit[0] })
if (!restBeforeWarmup) startRest(restSec, idx)
}
} else {
if (step.nextIdx != null) update(s => { if (s.active) s.active.cur = step.nextIdx })
if (step.roundDone) startRest(S.restSec)
if (step.roundDone) startRest(restSec, idx)
}
}
}
@@ -497,35 +633,47 @@ function ActiveWorkout() {
return <div className="narrow">
<div className="hdr">
<button className="iconbtn" aria-label={t('Discard')} onClick={() => confirmSheet({ title: t('Discard workout?'), message: t('The sets you logged in this session will be lost.'), confirmText: t('Discard'), danger: true, onConfirm: () => { update(s => { s.active = null }); stopRest(); nav('/home') } })}><Icon name="xmark" /></button>
<div style={{ textAlign: 'center' }}><div style={{ fontWeight: 600 }}>{A.name}</div><div className="sub"><Elapsed start={A.start} /> · {t('{0} sets', done + '/' + total)}</div></div>
<button className="iconbtn" aria-label={t('Discard')} onClick={() => confirmSheet({ title: t('Discard workout?'), message: t('The sets you logged in this session will be lost.'), confirmText: t('Discard'), danger: true, onConfirm: () => { update(s => { s.active = null }); stopRest(); stopWork(); nav('/home') } })}><Icon name="xmark" /></button>
<div style={{ textAlign: 'center' }}><div style={{ fontWeight: 600 }}>{A.name}</div><div className="sub">{A.backfill ? fmtDate(A.d, true) : <Elapsed start={A.start} />} · {t('{0} sets', done + '/' + total)}</div></div>
<button className="iconbtn" style={{ color: 'var(--acc)' }} aria-label={t('Finish')} onClick={finishWorkout}><Icon name="check" /></button>
</div>
<div className="wprog"><i style={{ width: (total ? done / total * 100 : 0) + '%' }} /></div>
{A.backfill && <div className="muted small" style={{ marginBottom: 8 }}>{t('Logging a past workout — no rest timers.')}</div>}
{A.entries.length ? <>
<div className="muted small" style={{ marginBottom: 6 }}>{isSuperset ? t('Superset {0} / {1}', unitIdx + 1, units.length) : t('Exercise {0} / {1}', unitIdx + 1, units.length)}</div>
<div className="workout-swipe-surface" data-testid="workout-swipe-surface"
onPointerDown={onSwipePointerDown}
onPointerUp={event => finishSwipe(event, true)}
onPointerCancel={event => finishSwipe(event, false)}
onLostPointerCapture={event => {
if (swipe.current?.id === event.pointerId) swipe.current = null
}}>
{isSuperset ? (
<div className="ss-card">
<div className="ss-hd" style={{ justifyContent: 'space-between' }}>
<span className="row" style={{ gap: 5 }}><Icon name="link" />{t('Superset · do these back-to-back, rest when done')}</span>
<Button size="xs" variant="ghost" icon="link" title={t('Unpair')} onClick={() => unpairAt(cur)}>{t('Unpair')}</Button>
</div>
{unit.map((idx, k) => <div key={idx} ref={el => { exRefs.current[idx] = el }} className="ss-ex" data-exidx={idx}>
{k > 0 && <div className="ss-amp">+</div>}
<ExerciseBlock entryIdx={idx} compact
onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} />
</div>)}
{unit.map((idx, k) => {
const entry = A.entries[idx]
return <div key={idx} ref={el => bindExRef(entry, el)} className="ss-ex" data-exidx={idx}>
{k > 0 && <div className="ss-amp">+</div>}
<ExerciseBlock entryIdx={idx} compact onSetRowRef={(setIdx, el) => bindSetRef(entry, setIdx, el)}
onToggle={i => toggle(idx, i)} onField={(i, f, v) => setField(idx, i, f, v)} onAddSet={() => addSet(idx)} onRemoveSet={() => removeSet(idx)} onAddWarmup={() => addWarmup(idx)} onRemoveSetAt={i => removeSetAt(idx, i)} onStartTimed={i => startTimed(idx, i)} onProgressionSettings={() => openProgressionSettings(idx)} />
</div>
})}
</div>
) : (
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} />
<ExerciseBlock entryIdx={cur} onToggle={i => toggle(cur, i)} onField={(i, f, v) => setField(cur, i, f, v)} onAddSet={() => addSet(cur)} onRemoveSet={() => removeSet(cur)} onAddWarmup={() => addWarmup(cur)} onRemoveSetAt={i => removeSetAt(cur, i)} onStartTimed={i => startTimed(cur, i)} onPairPrev={onPairPrev} onPairNext={onPairNext} onProgressionSettings={() => openProgressionSettings(cur)} />
)}
</div>
</> : <div className="empty"><div className="ico"><Icon name="shuffle" /></div>{t('Freestyle workout — add your first exercise.')}</div>}
<div style={{ height: 12 }} />
<div className="row">
<Button icon="chevronLeft" disabled={unitIdx <= 0} onClick={() => update(s => { s.active.cur = units[unitIdx - 1][0] })}>{t('Prev')}</Button>
<Button trailingIcon="chevronRight" disabled={unitIdx < 0 || unitIdx >= units.length - 1} onClick={() => update(s => { s.active.cur = units[unitIdx + 1][0] })}>{t('Next')}</Button>
<Button icon="chevronLeft" disabled={unitIdx <= 0} onClick={() => navigateUnit(-1)}>{t('Prev')}</Button>
<Button trailingIcon="chevronRight" disabled={unitIdx < 0 || unitIdx >= units.length - 1} onClick={() => navigateUnit(1)}>{t('Next')}</Button>
</div>
<div style={{ height: 10 }} />
<Button onClick={() => exercisePicker(ex => {
@@ -539,11 +687,25 @@ function ActiveWorkout() {
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
const sets = buildSets(s, full, { step: defaultIncrement(ex.id, s.unit), ...(freestyle ? { preferLast: true } : {}) })
const progressed = freestyle ? sets : applyPrescription(sets, plan, defaultIncrement(ex.id, s.unit))
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full) })
s.active.cur = s.active.entries.length - 1
const insertAt = insertionIndexAfterCurrentUnit(supersetUnits(s.active.entries), s.active.cur, s.active.entries.length)
s.active.entries.splice(insertAt, 0, { id: ex.id, target: { ...cfg }, plan, sets: applyIntensifierPlan(progressed, full) })
s.active.cur = insertAt
useUI.getState().shiftRestOwner(insertAt, 1)
}), null, routine, seed)
})} icon="plus">{t('Add exercise')}</Button>
{A.entries.length > 0 && <>
<div style={{ height: 6 }} />
<div className="row">
<Button size="sm" icon="chevronUp" aria-label={t('Move up')}
disabled={!!work || !canMoveActiveWorkoutUnit(A, cur, -1)} onClick={() => moveCurrentUnit(-1)}>{t('Move up')}</Button>
<Button size="sm" trailingIcon="chevronDown" aria-label={t('Move down')}
disabled={!!work || !canMoveActiveWorkoutUnit(A, cur, 1)} onClick={() => moveCurrentUnit(1)}>{t('Move down')}</Button>
</div>
<div style={{ height: 6 }} />
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Button size="sm" icon="shuffle" aria-label={t('Swap exercise')} disabled={!!work}
onClick={() => swapActiveWorkoutExercise(cur)}>{t('Swap exercise')}</Button>
</div>
<div style={{ height: 6 }} />
<div style={{ display: 'flex', justifyContent: 'center' }}>
<Button size="sm" icon="minus" style={{ color: 'var(--red)' }} disabled={!!work} onClick={removeExerciseSheet}>{t('Remove exercise')}</Button>
+123 -2
View File
@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Workout, { removeActiveExercise } from './Workout.jsx'
import { DEF, useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { LANGS } from '../lib/i18n-core.js'
vi.mock('../lib/sound.js', () => ({ beep: vi.fn(), vibrate: vi.fn() }))
vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
@@ -21,6 +22,8 @@ const entry = (id, sg) => ({
let root
let container
let sheetRoot
let sheetContainer
function setActive(entries, cur = 0) {
const S = clone(DEF)
@@ -43,6 +46,18 @@ function removeButton() {
return [...container.querySelectorAll('button')].find(button => button.textContent.includes('Remove exercise'))
}
function renderTopSheet() {
if (sheetRoot) act(() => sheetRoot.unmount())
if (sheetContainer) sheetContainer.remove()
const sheet = useUI.getState().sheets.at(-1)
expect(sheet).toBeTruthy()
sheetContainer = document.createElement('div')
document.body.appendChild(sheetContainer)
sheetRoot = createRoot(sheetContainer)
act(() => sheetRoot.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
return sheetContainer
}
beforeEach(() => {
vi.useFakeTimers()
localStorage.clear()
@@ -52,9 +67,13 @@ beforeEach(() => {
useStore.setState({ S: clone(DEF), user: null })
root = null
container = null
sheetRoot = null
sheetContainer = null
})
afterEach(() => {
if (sheetRoot) act(() => sheetRoot.unmount())
if (sheetContainer) sheetContainer.remove()
if (root) act(() => root.unmount())
if (container) container.remove()
useUI.getState().stopRest()
@@ -94,6 +113,82 @@ describe('active-session exercise removal', () => {
expect(active.entries[0].sets[0].sec).toBeUndefined()
})
it('cancels a running rest countdown when the exercise it belongs to is removed', () => {
setActive([entry('1001'), entry('1002')], 0)
useUI.getState().startRest(90, 0)
expect(useUI.getState().timer).not.toBeNull()
act(() => { removeActiveExercise(0) })
expect(useUI.getState().timer).toBeNull()
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1002'])
})
it('keeps a rest countdown that belongs to another exercise, re-pointed at it', () => {
setActive([entry('1001'), entry('1002'), entry('1003')], 1)
useUI.getState().startRest(90, 1)
act(() => { removeActiveExercise(0) })
expect(useUI.getState().timer?.forIdx).toBe(0)
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1002', '1003'])
act(() => { removeActiveExercise(1) })
expect(useUI.getState().timer?.forIdx).toBe(0)
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1002'])
act(() => { removeActiveExercise(0) })
expect(useUI.getState().timer).toBeNull()
})
it('leaves a rest countdown without a known owner running', () => {
setActive([entry('1001'), entry('1002')], 0)
useUI.getState().startRest(90)
act(() => { removeActiveExercise(0) })
expect(useUI.getState().timer).not.toBeNull()
})
it('does not mutate before confirmation, leaves state unchanged on Cancel, and removes on Confirm', () => {
renderWorkout([entry('1001'), entry('1002')])
act(() => removeButton().click())
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1001', '1002'])
let dialog = renderTopSheet()
const cancel = [...dialog.querySelectorAll('button')].find(button => button.textContent === 'Cancel')
act(() => cancel.click())
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1001', '1002'])
act(() => removeButton().click())
dialog = renderTopSheet()
const confirm = [...dialog.querySelectorAll('button')].find(button => button.textContent === 'Remove')
act(() => confirm.click())
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['1002'])
})
it('uses the selected superset member occurrence rather than its exercise id', () => {
renderWorkout([entry('1001', 'pair'), entry('1001', 'pair'), entry('1002')])
useStore.getState().update(s => {
s.active.entries[0].target.marker = 'keep-first'
s.active.entries[1].target.marker = 'remove-second'
}, false)
act(() => removeButton().click())
const chooser = renderTopSheet()
const choices = [...chooser.querySelectorAll('.item')]
expect(choices).toHaveLength(2)
act(() => choices[1].click())
const dialog = renderTopSheet()
const confirm = [...dialog.querySelectorAll('button')].find(button => button.textContent === 'Remove')
act(() => confirm.click())
const active = useStore.getState().S.active
expect(active.entries.map(e => e.id)).toEqual(['1001', '1002'])
expect(active.entries[0].target.marker).toBe('keep-first')
expect(active.entries[0].sg).toBeUndefined()
})
it('hides the remove control for an empty freestyle session', () => {
renderWorkout([])
expect(removeButton()).toBeUndefined()
@@ -109,9 +204,13 @@ describe('remove-exercise locale coverage', () => {
'Which exercise in this superset do you want to remove?'
]
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
// Every non-English language has its own pack (English is the source, so it has none) —
// derived from LANGS rather than hardcoded so adding a language doesn't silently
// understate this test's own coverage.
const nonEnglishLangCount = Object.keys(LANGS).length - 1
it('defines every new prompt in all twelve locale packs', () => {
expect(Object.keys(packs)).toHaveLength(12)
it('defines every new prompt in every non-English locale pack', () => {
expect(Object.keys(packs)).toHaveLength(nonEnglishLangCount)
Object.entries(packs).forEach(([path, pack]) => {
required.forEach(key => expect(pack, `${path} is missing ${key}`).toHaveProperty(key))
})
@@ -143,4 +242,26 @@ describe('remove-exercise edge cases', () => {
expect(A.entries.map(e => e.id)).toEqual(['b', 'c'])
expect(A.entries[A.cur].id).toBe('c')
})
it('persists the shortened active session for reload without changing completed history', () => {
const first = entry('same')
first.target.marker = 'keep-first'
const second = entry('same')
second.target.marker = 'remove-second'
setActive([first, second, entry('other')], 1)
const workouts = [{ id: 'completed', d: '2026-08-10', entries: [{ id: 'same', sets: [{ w: 42, r: 5, done: true }] }] }]
useStore.setState(state => ({ S: { ...state.S, workouts: clone(workouts) } }))
act(() => { removeActiveExercise(1) })
const persisted = JSON.parse(localStorage.getItem('gym_state_v1'))
expect(persisted.workouts).toEqual(workouts)
expect(persisted.active.entries.map(e => e.id)).toEqual(['same', 'other'])
expect(persisted.active.entries[0].target.marker).toBe('keep-first')
expect(persisted.active.cur).toBe(1)
useStore.setState({ S: Object.assign(clone(DEF), persisted), user: null })
expect(useStore.getState().S.active.entries.map(e => e.id)).toEqual(['same', 'other'])
expect(useStore.getState().S.workouts).toEqual(workouts)
})
})
+525 -15
View File
@@ -7,21 +7,40 @@ import Workout from './Workout.jsx'
const mocks = vi.hoisted(() => {
const state = {
S: null,
timer: null,
work: null,
startRest: vi.fn(),
stopRest: vi.fn(),
stopRest: null,
stopWork: null,
confirmSheet: vi.fn(),
topWeightSheet: vi.fn(),
workoutCompleteSheet: vi.fn(),
exercisePicker: vi.fn(),
exConfigSheet: vi.fn(),
toast: vi.fn(),
scrollCalls: [],
swapActiveWorkoutExercise: vi.fn(),
}
state.stopRest = vi.fn(() => { state.timer = null })
state.stopWork = vi.fn(() => { state.work = null })
state.storeSnapshot = () => ({
S: state.S,
user: null,
update: mut => mut(state.S),
update: mut => {
const next = structuredClone(state.S)
mut(next)
state.S = next
},
})
state.uiSnapshot = () => ({
work: null,
timer: state.timer,
work: state.work,
startRest: state.startRest,
stopRest: state.stopRest,
stopWork: state.stopWork,
shiftRestOwner: vi.fn(),
startWork: vi.fn(),
toast: vi.fn(),
toast: state.toast,
})
return state
})
@@ -39,13 +58,14 @@ vi.mock('../store/useUI.js', () => {
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../sheets.jsx', () => ({
startFlow: vi.fn(),
exercisePicker: vi.fn(),
exConfigSheet: vi.fn(),
exercisePicker: mocks.exercisePicker,
exConfigSheet: mocks.exConfigSheet,
exerciseDetailSheet: vi.fn(),
topWeightSheet: mocks.topWeightSheet,
finishWorkout: vi.fn(),
workoutCompleteSheet: vi.fn(),
confirmSheet: vi.fn(),
workoutCompleteSheet: mocks.workoutCompleteSheet,
confirmSheet: mocks.confirmSheet,
swapActiveWorkoutExercise: mocks.swapActiveWorkoutExercise,
// Both note sheets belong here even though the tests never open one: Workout.jsx reads
// sessionNoteSheet during render, so a missing export is a render crash, not a no-op.
exerciseNoteSheet: vi.fn(),
@@ -72,11 +92,13 @@ function exercise(id, sets, extra = {}) {
}
}
function workout(entries, cur = 0) {
function workout(entries, cur = 0, overrides = {}) {
const { active: activeOverrides = {}, ...stateOverrides } = overrides
return {
unit: 'kg', restSec: 90, sound: false, effort: 'none', gifSize: 'full',
workouts: [], exWeights: {}, routines: [],
active: { id: 'active', name: 'Test workout', start: Date.now(), cur, entries },
active: { id: 'active', name: 'Test workout', start: Date.now(), cur, entries, ...activeOverrides },
...stateOverrides,
}
}
@@ -87,13 +109,16 @@ function installDom() {
globalThis.document = dom.document
Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
for (const key of ['HTMLElement', 'Node', 'Element', 'Event', 'Blob']) globalThis[key] = dom[key]
dom.Element.prototype.scrollIntoView = vi.fn(function (options) {
mocks.scrollCalls.push({ node: this, options })
})
globalThis.IS_REACT_ACT_ENVIRONMENT = true
container = document.getElementById('root')
root = createRoot(container)
}
async function mount(entries, cur = 0) {
mocks.S = workout(entries, cur)
async function mount(entries, cur = 0, overrides = {}) {
mocks.S = workout(entries, cur, overrides)
installDom()
await act(async () => { root.render(React.createElement(Workout)) })
}
@@ -112,8 +137,48 @@ async function toggleSet(index) {
await act(async () => { checkbox.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function pressProgression(index = 0) {
const button = container.querySelectorAll('.progline')[index]
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
return button
}
async function requestDiscard() {
const button = container.querySelector('button[aria-label="Discard"]')
expect(button).toBeTruthy()
await act(async () => { button.dispatchEvent(new dom.Event('click', { bubbles: true })) })
}
async function rerender() {
await act(async () => { root.render(React.createElement(Workout)) })
}
async function addExerciseThroughSheets(ex = { id: 'added-exercise' }, cfg = { mode: 'reps', sets: 1, reps: 5, weight: 0 }) {
const addButton = [...container.querySelectorAll('button')]
.find(button => button.textContent.trim() === 'Add exercise')
expect(addButton).toBeTruthy()
await act(async () => { addButton.dispatchEvent(new dom.Event('click', { bubbles: true })) })
const pickerCall = mocks.exercisePicker.mock.calls.at(-1)
expect(pickerCall?.[0]).toEqual(expect.any(Function))
await act(async () => { pickerCall[0](ex) })
const configCall = mocks.exConfigSheet.mock.calls.at(-1)
expect(configCall?.[2]).toEqual(expect.any(Function))
await act(async () => { configCall[2](cfg) })
}
async function rerenderAt(cur) {
mocks.S.active.cur = cur
await act(async () => { root.render(React.createElement(Workout)) })
}
beforeEach(() => {
vi.clearAllMocks()
mocks.timer = null
mocks.work = null
mocks.scrollCalls.length = 0
})
afterEach(async () => {
@@ -126,7 +191,7 @@ describe('Workout set completion flow', () => {
await toggleSet(0)
expect(mocks.startRest).toHaveBeenCalledOnce()
expect(mocks.startRest).toHaveBeenCalledWith(90)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
expect(mocks.stopRest).not.toHaveBeenCalled()
await unmount()
@@ -140,6 +205,85 @@ describe('Workout set completion flow', () => {
expect(mocks.startRest).not.toHaveBeenCalled()
})
it.each(['warmup', 'warm-up', 'warm_up'])(
'does not start transition rest before an incomplete %s row in the next ordinary exercise',
async phase => {
await mount([
exercise('current', [false], { asked: true }),
exercise('next', [false, false], {
asked: true,
sets: [
{ w: 30, r: 5, done: false, phase },
{ w: 60, r: 5, done: false },
],
}),
])
await toggleSet(0)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).not.toHaveBeenCalled()
},
)
it('does not start transition rest when a completed superset advances to an incomplete warm-up', async () => {
await mount([
exercise('superset-a', [true], { sg: 'group', asked: true }),
exercise('superset-b', [false], { sg: 'group', asked: true }),
exercise('next', [false, false], {
asked: true,
sets: [
{ w: 30, r: 5, done: false, phase: 'warmup' },
{ w: 60, r: 5, done: false },
],
}),
], 1)
await toggleSet(1)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('does not start transition rest before a warm-up while top-weight confirmation owns navigation', async () => {
await mount([
exercise('current-loaded', [false]),
exercise('next', [false, false], {
asked: true,
sets: [
{ w: 30, r: 5, done: false, phase: 'warmup' },
{ w: 60, r: 5, done: false },
],
}),
])
await toggleSet(0)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(0)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('does not restart transition rest when re-checking a completed unit before an incomplete warm-up', async () => {
await mount([
exercise('current', [true], { asked: true }),
exercise('next', [false, false], {
asked: true,
sets: [
{ w: 30, r: 5, done: false, phase: 'warmup' },
{ w: 60, r: 5, done: false },
],
}),
])
await toggleSet(0)
await rerender()
await toggleSet(0)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.startRest).not.toHaveBeenCalled()
})
it('leaves a completed superset selected while its top-weight sheet owns the advance choice', async () => {
const group = 'superset-1'
await mount([
@@ -151,7 +295,243 @@ describe('Workout set completion flow', () => {
expect(mocks.topWeightSheet).toHaveBeenCalledWith(1)
expect(mocks.S.active.cur).toBe(1)
expect(mocks.startRest).toHaveBeenCalledWith(90)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('skips completed intervening units and selects the next unfinished superset as one unit', async () => {
await mount([
exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
exercise('already-done', [true], { asked: true }),
exercise('pending-a', [false], { sg: 'pending-group' }),
exercise('pending-b', [false], { sg: 'pending-group' }),
])
await toggleSet(0)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.toast).toHaveBeenCalledWith('Hold logged')
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('wraps to earlier unfinished work instead of showing a false completion prompt', async () => {
await mount([
exercise('pending-earlier', [false], { asked: true }),
exercise('current-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
], 1)
await toggleSet(0)
expect(mocks.S.active.cur).toBe(0)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
it('keeps top-weight confirmation in control without declaring completion while work remains', async () => {
await mount([
exercise('current-loaded', [false]),
exercise('pending', [false], { asked: true }),
])
await toggleSet(0)
expect(mocks.topWeightSheet).toHaveBeenCalledWith(0)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
expect(mocks.S.active.cur).toBe(0)
})
it('shows workout completion only when no unfinished unit remains', async () => {
await mount([
exercise('already-done', [true], { asked: true }),
exercise('final-hold', [false], { asked: true, target: { mode: 'time', sec: 30, weight: 0 } }),
], 1)
await toggleSet(0)
expect(mocks.workoutCompleteSheet).toHaveBeenCalledOnce()
expect(mocks.startRest).not.toHaveBeenCalled()
})
})
describe('Workout add exercise flow', () => {
it.each([
['freestyle', {}],
['planned', {
active: { routineId: 'routine-1' },
routines: [{ id: 'routine-1', ex: [] }],
}],
])('inserts after the current unit and continues to pending work in a %s session', async (_label, overrides) => {
await mount([
exercise('current', [true], { asked: true }),
exercise('pending', [false], { asked: true }),
], 0, overrides)
await addExerciseThroughSheets(
{ id: 'inserted' },
{ mode: 'time', sets: 1, sec: 30, weight: 0 },
)
expect(mocks.S.active.entries.map(entry => entry.id)).toEqual(['current', 'inserted', 'pending'])
expect(mocks.S.active.cur).toBe(1)
await rerender()
await toggleSet(0)
expect(mocks.S.active.entries[1].sets[0].done).toBe(true)
expect(mocks.S.active.cur).toBe(2)
expect(mocks.workoutCompleteSheet).not.toHaveBeenCalled()
})
it('inserts after the complete current superset without splitting the group', async () => {
await mount([
exercise('current-a', [true], { sg: 'current-group', asked: true }),
exercise('current-b', [true], { sg: 'current-group', asked: true }),
exercise('pending', [false], { asked: true }),
])
await addExerciseThroughSheets({ id: 'inserted' })
expect(mocks.S.active.entries.map(entry => entry.id)).toEqual([
'current-a', 'current-b', 'inserted', 'pending',
])
expect(mocks.S.active.entries.slice(0, 2).map(entry => entry.sg)).toEqual([
'current-group', 'current-group',
])
expect(mocks.S.active.cur).toBe(2)
})
})
describe('Workout discard timer lifecycle', () => {
it('preserves active timers while discard is awaiting confirmation', async () => {
const timer = { left: 30, total: 90, endsAt: Date.now() + 30_000 }
const work = { left: 20, total: 45, endsAt: Date.now() + 20_000, label: 'Plank' }
mocks.timer = timer
mocks.work = work
await mount([exercise('timed-plank', [false])])
await requestDiscard()
expect(mocks.confirmSheet).toHaveBeenCalledOnce()
expect(mocks.timer).toBe(timer)
expect(mocks.work).toBe(work)
expect(mocks.stopRest).not.toHaveBeenCalled()
expect(mocks.stopWork).not.toHaveBeenCalled()
expect(mocks.S.active).not.toBeNull()
})
it('clears rest and work timers only after discard is confirmed', async () => {
mocks.timer = { left: 30, total: 90, endsAt: Date.now() + 30_000 }
mocks.work = { left: 20, total: 45, endsAt: Date.now() + 20_000, label: 'Plank' }
await mount([exercise('timed-plank', [false])])
await requestDiscard()
await act(async () => { mocks.confirmSheet.mock.calls[0][0].onConfirm() })
expect(mocks.S.active).toBeNull()
expect(mocks.timer).toBeNull()
expect(mocks.work).toBeNull()
expect(mocks.stopRest).toHaveBeenCalledOnce()
expect(mocks.stopWork).toHaveBeenCalledOnce()
})
})
describe('progression guidance', () => {
it('labels the visible outcome with the policy that calculated it', async () => {
await mount([exercise('plain-bench', [false, false, false], {
plan: {
policy: 'linear',
kind: 'up',
weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
},
})])
expect(container.querySelector('.progline')?.textContent)
.toContain('Linear progression · Every rep last time — 2.5 kg more.')
})
it('is a keyboard-accessible button that opens settings for the pressed grouped entry', async () => {
const plan = {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
}
const first = exercise('plain-bench', [false], { sg: 'group', plan })
const second = exercise('plain-bench', [false], {
sg: 'group', plan, target: { mode: 'reps', reps: 8, weight: 80, bodyweight: false },
})
await mount([first, second])
const firstBefore = JSON.stringify(mocks.S.active.entries[0])
const button = await pressProgression(1)
expect(button.tagName).toBe('BUTTON')
expect(button.getAttribute('type')).toBe('button')
expect(button.getAttribute('aria-label')).toBe('Open progression settings')
expect(mocks.exConfigSheet).toHaveBeenCalledOnce()
expect(mocks.exConfigSheet.mock.calls[0][1]).toBe(second.target)
expect(mocks.exConfigSheet.mock.calls[0][4]).toBe(mocks.S.routines[0])
mocks.exConfigSheet.mock.calls[0][2]({ ...second.target, prog: 'double', repsMin: 6 })
expect(JSON.stringify(mocks.S.active.entries[0])).toBe(firstBefore)
expect(mocks.S.active.entries[1].target.prog).toBe('double')
expect(mocks.S.active.cur).toBe(0)
})
it('leaves the active entry unchanged when progression settings are cancelled', async () => {
const entry = exercise('plain-bench', [true, false], {
plan: {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
},
})
await mount([entry])
const before = JSON.stringify(mocks.S.active.entries[0])
await pressProgression()
expect(JSON.stringify(mocks.S.active.entries[0])).toBe(before)
})
it('saves the active policy, preserves completed rows, and refreshes guidance immediately', async () => {
const entry = exercise('plain-bench', [true, false], {
plan: {
policy: 'linear', kind: 'up', weight: 62.5,
why: ['Every rep last time — {0} {1} more.', 2.5, 'kg'],
},
})
await mount([entry])
mocks.S.workouts = [{
d: '2026-08-27',
entries: [{
id: entry.id,
target: { sets: 2, reps: 5, weight: 60 },
sets: [{ w: 60, r: 5, done: true }, { w: 60, r: 5, done: true }],
}],
}]
const completed = mocks.S.active.entries[0].sets[0]
await pressProgression()
const save = mocks.exConfigSheet.mock.calls[0][2]
await act(async () => {
save({ ...entry.target, prog: 'double', repsMin: 3 })
root.render(React.createElement(Workout))
})
const saved = mocks.S.active.entries[0]
expect(saved.target.prog).toBe('double')
expect(saved.sets[0]).toEqual(completed)
expect(saved.sets[0]).toEqual({ w: 60, r: 5, done: true })
expect(saved.sets[1]).toEqual({ w: 62.5, r: 3, done: false })
expect(container.querySelector('.progline')?.textContent)
.toContain('Double progression · Top of the rep range in every set — 2.5 kg more, back to 3 reps.')
const persisted = JSON.parse(JSON.stringify(mocks.S))
await unmount()
mocks.S = persisted
installDom()
await act(async () => { root.render(React.createElement(Workout)) })
expect(container.querySelector('.progline')?.textContent)
.toContain('Double progression · Top of the rep range in every set — 2.5 kg more, back to 3 reps.')
})
})
@@ -184,6 +564,136 @@ describe('superset flow survives an exercise being removed mid-session', () => {
// Partner closes the round (each still has a second set), which is what starts the rest.
await toggleSet(2)
expect(mocks.startRest).toHaveBeenCalledWith(90)
expect(mocks.startRest).toHaveBeenCalledWith(90, expect.any(Number))
})
})
describe('superset actionable-set centring', () => {
it('centres the newly active exercise first incomplete set row', async () => {
await mount([
exercise('bench', [true, false], { sg: 'g1' }),
exercise('row', [true, false, false], { sg: 'g1' }),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
const rows = container.querySelector('[data-exidx="1"]').querySelectorAll('.setrow')
expect(mocks.scrollCalls).toEqual([
{ node: rows[1], options: { behavior: 'smooth', block: 'center' } },
])
})
it('centres the last set row when the newly active exercise is complete', async () => {
await mount([
exercise('bench', [true, false], { sg: 'g1' }),
exercise('row', [true, true], { sg: 'g1' }),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
const rows = container.querySelector('[data-exidx="1"]').querySelectorAll('.setrow')
expect(mocks.scrollCalls).toEqual([
{ node: rows[1], options: { behavior: 'smooth', block: 'center' } },
])
})
it('centres the exercise wrapper when the newly active exercise has no set row', async () => {
await mount([
exercise('bench', [true, false], { sg: 'g1' }),
exercise('row', [], { sg: 'g1' }),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
const wrapper = container.querySelector('[data-exidx="1"]')
expect(mocks.scrollCalls).toEqual([
{ node: wrapper, options: { behavior: 'smooth', block: 'center' } },
])
})
it('does not auto-scroll set rows for ordinary exercise navigation', async () => {
await mount([
exercise('bench', [true, false]),
exercise('row', [false, false]),
])
mocks.scrollCalls.length = 0
await rerenderAt(1)
expect(mocks.scrollCalls).toEqual([])
})
})
describe('active workout whole-unit move controls', () => {
const action = label => container.querySelector(`button[aria-label="${label}"]`)
it('shows labelled controls and moves the selected standalone exercise one unit', async () => {
const selected = exercise('duplicate', [false], {
occurrenceId: 'duplicate#2',
target: { mode: 'reps', reps: 7, weight: 82.5, notes: 'Keep this target' },
sets: [{ w: 77.5, r: 6, done: true, rir: 2 }],
})
await mount([
exercise('duplicate', [false], { occurrenceId: 'duplicate#1' }),
exercise('middle', [false]),
selected,
], 2)
expect(action('Move up')?.textContent.trim()).toBe('Move up')
expect(action('Move down')?.textContent.trim()).toBe('Move down')
await act(async () => { action('Move up').dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.S.active.entries.map(entry => entry.occurrenceId || entry.id)).toEqual(['duplicate#1', 'duplicate#2', 'middle'])
expect(mocks.S.active.entries[1]).toEqual(selected)
expect(mocks.S.active.entries[1].target).toEqual({ mode: 'reps', reps: 7, weight: 82.5, notes: 'Keep this target' })
expect(mocks.S.active.entries[1].sets).toEqual([{ w: 77.5, r: 6, done: true, rir: 2 }])
expect(mocks.S.active.cur).toBe(1)
expect(mocks.stopWork).toHaveBeenCalledOnce()
expect(mocks.stopRest).not.toHaveBeenCalled()
})
it('moves the selected contiguous group as one unit without changing its metadata', async () => {
const first = exercise('group-a', [false], { sg: 'pair', occurrenceId: 'group-a#1' })
const selected = exercise('group-b', [true], { sg: 'pair', occurrenceId: 'group-b#1' })
const groupMeta = { pair: { kind: 'complex', label: 'Carry pair', cues: 'Stay braced.' } }
await mount([
exercise('before', [false]),
first,
selected,
exercise('after', [false]),
], 2)
mocks.S.active.groupMeta = groupMeta
await act(async () => { action('Move up').dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.S.active.entries.map(entry => entry.id)).toEqual(['group-a', 'group-b', 'before', 'after'])
expect(mocks.S.active.entries.slice(0, 2)).toEqual([first, selected])
expect(mocks.S.active.entries.slice(0, 2).map(entry => entry.sg)).toEqual(['pair', 'pair'])
expect(mocks.S.active.groupMeta).toEqual(groupMeta)
expect(mocks.S.active.entries[mocks.S.active.cur]).toEqual(selected)
})
it('disables both moves while a work timer can still write by index', async () => {
mocks.work = { left: 5, total: 5, endsAt: Date.now() + 5000 }
await mount([exercise('first', [false]), exercise('second', [false])], 1)
expect(action('Move up')?.disabled).toBe(true)
expect(action('Move down')?.disabled).toBe(true)
})
})
describe('active exercise swap control', () => {
it('opens the swap flow for the selected duplicate occurrence', async () => {
await mount([exercise('bench', [false]), exercise('bench', [false]), exercise('row', [false])], 1)
const swap = container.querySelector('button[aria-label="Swap exercise"]')
expect(swap).toBeTruthy()
await act(async () => { swap.dispatchEvent(new dom.Event('click', { bubbles: true })) })
expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledOnce()
expect(mocks.swapActiveWorkoutExercise).toHaveBeenCalledWith(1)
})
})
+120
View File
@@ -0,0 +1,120 @@
// @vitest-environment happy-dom
// The setting is only worth anything if the screens actually follow it: the toggle has to
// write the field, and the Plan list has to draw the week in that order.
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Settings from './Settings.jsx'
import Plan from './Plan.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
},
replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
})
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('../store/useUI.js', () => {
const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })
const useUI = selector => (selector ? selector(snap()) : snap())
useUI.getState = snap
return { useUI }
})
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
vi.mock('../lib/api.js', () => ({
api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
}))
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
vi.mock('../sheets.jsx', () => ({
loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(),
}))
globalThis.__APP_VERSION__ ??= 'test'
let host, root
beforeEach(() => {
mocks.S = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
gifSize: 'full', workouts: [], routines: [], exWeights: {}, week: {}, dayPlan: {},
}
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const segButton = label => [...host.querySelectorAll('.seg button')].find(b => b.textContent === label)
const dayRows = () => [...host.querySelectorAll('.item .tt')].map(e => e.textContent)
describe('Settings — week starts on', () => {
const mount = () => act(() => root.render(<Settings />))
it('offers Monday and Sunday and writes the getDay() index', () => {
mount()
expect(segButton('Monday').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('Sunday').click() })
expect(mocks.S.weekStart).toBe(0)
mount()
expect(segButton('Sunday').getAttribute('aria-pressed')).toBe('true')
act(() => { segButton('Monday').click() })
expect(mocks.S.weekStart).toBe(1)
})
it('shows a profile written before the setting existed as Monday', () => {
delete mocks.S.weekStart
mount()
expect(segButton('Monday').getAttribute('aria-pressed')).toBe('true')
expect(segButton('Sunday').getAttribute('aria-pressed')).toBe('false')
})
})
describe('Plan — the week schedule follows the setting', () => {
const mount = () => act(() => root.render(<Plan />))
it('runs Monday to Sunday by default', () => {
mount()
expect(dayRows().slice(0, 7)).toEqual(
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])
})
it('runs Sunday to Saturday for a Sunday profile', () => {
mocks.S.weekStart = 0
mount()
expect(dayRows().slice(0, 7)).toEqual(
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
})
it('keeps a routine attached to its day, not to its position in the list', () => {
mocks.S.routines = [{ id: 'r1', name: 'Push', emoji: null, ex: [] }]
mocks.S.week = { 0: 'r1' } // Sunday
mocks.S.weekStart = 0
mount()
const rows = [...host.querySelectorAll('.item')]
expect(rows[0].querySelector('.tt').textContent).toBe('Sunday')
expect(rows[0].textContent).toContain('Push')
expect(rows[1].textContent).not.toContain('Push')
})
})