Merge main (v1.2.11) into coach: Pairing, Notizen, Aufwaerm-Saetze, GitLab-CI

Der Coach-Zweig stand seit v1.2.7. Konflikte: beide Seiten behalten (Server-Imports,
Store-Felder, Home-Titel mit naechster Einheit, history.js), das Dockerfile behaelt seine
zwei Targets und kopiert die neuen Server-Module mit, compose zeigt auf die GitLab-Registry.
pt-BR: die 139 Coach-Strings in die Sie-Form gebracht, Fingerprint nachgezogen.
This commit is contained in:
Duarte Santos committed 2026-08-29 17:03:39 +02:00
commit 4a9e1e3456
148 files changed
+24456 -761

No files matched your search

+26 -2
View File
@@ -6,6 +6,7 @@ import { bindUI } from './components/ui.jsx'
import { ACCENTS } from './lib/format.js'
import { setLang, useLang } from './lib/i18n.js'
import { setNav } from './lib/nav.js'
import { initBackButton } from './lib/back.js'
import { useWakeLock } from './lib/wakelock.js'
import { startFlow } from './sheets.jsx'
import Icon from './components/Icon.jsx'
@@ -15,6 +16,7 @@ import Modals from './components/Modals.jsx'
import Toast from './components/Toast.jsx'
import RestTimer from './components/RestTimer.jsx'
import Login from './views/Login.jsx'
import MobileOnboarding from './views/MobileOnboarding.jsx'
import Home from './views/Home.jsx'
import Plan from './views/Plan.jsx'
import RoutineEdit from './views/RoutineEdit.jsx'
@@ -30,9 +32,14 @@ import CoachProposal from './views/CoachProposal.jsx'
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.
const resolveTheme = theme => theme === 'light' || theme === 'dark'
? theme
: (window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
function applyPrefs(theme, accent) {
const de = document.documentElement
de.dataset.theme = theme === 'light' ? 'light' : 'dark'
de.dataset.theme = resolveTheme(theme)
de.dataset.accent = ACCENTS[accent] ? accent : 'lime'
const meta = document.querySelector('meta[name="theme-color"]')
if (meta) meta.content = de.dataset.theme === 'light' ? '#f2f2f7' : '#000000'
@@ -43,9 +50,20 @@ function Shell() {
const loc = useLocation()
const { S, user, ready } = useStore()
const isGuest = useStore(s => s.isGuest())
const needsMobileOnboarding = useStore(s => s.needsMobileOnboarding)
const langV = useLang() // re-renders the whole shell when the language (pack) changes
useEffect(() => { setNav(navigate) }, [navigate])
useEffect(() => { applyPrefs(S.theme, S.accent) }, [S.theme, S.accent])
// 'system' needs to react live if the OS theme flips while the app is open, not just on
// the next mount — a fixed 'dark'/'light' choice never re-fires this since matchMedia
// isn't consulted for those.
useEffect(() => {
if (S.theme !== 'system' || !window.matchMedia) return
const mql = window.matchMedia('(prefers-color-scheme: dark)')
const onChange = () => applyPrefs(S.theme, S.accent)
mql.addEventListener('change', onChange)
return () => mql.removeEventListener('change', onChange)
}, [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
@@ -68,7 +86,7 @@ function Shell() {
re-mounts the boundary, so the tab bar is always a way out */}
<div id="app" className="vfade" key={loc.pathname}>
<ErrorBoundary>
{!authed ? <Login /> : (
{!authed ? <Login /> : needsMobileOnboarding ? <MobileOnboarding /> : (
<Routes>
<Route path="/home" element={<Home />} />
<Route path="/plan" element={<Plan />} />
@@ -101,5 +119,11 @@ function Shell() {
export default function App() {
const boot = useStore(s => s.boot)
useEffect(() => { boot() }, [boot])
// Android system back — sheet, then page, then press-again-to-exit (see lib/back.js)
useEffect(() => {
let stop = null, gone = false
initBackButton().then(fn => { if (gone) fn(); else stop = fn })
return () => { gone = true; stop?.() }
}, [])
return <HashRouter><Shell /></HashRouter>
}
+1
View File
@@ -112,6 +112,7 @@ const P = {
signOut: <><path d="M14.2 4.6H7a1.9 1.9 0 0 0-1.9 1.9v11a1.9 1.9 0 0 0 1.9 1.9h7.2" /><path d="m16.8 8.4 3.6 3.6-3.6 3.6M20.4 12H10.2" /></>,
shuffle: <><path d="M3.6 7.2h2.9c1.6 0 2.8.9 3.8 2.4l3 4.8c1 1.5 2.2 2.4 3.8 2.4h2.9M3.6 16.8h2.9c1.6 0 2.8-.9 3.8-2.4l.7-1.1M15.6 9.9l.7-1.1c1-1.5 2.2-2.4 3.8-2.4h1.9" /><path d="m17.9 4.3 2.8 2.1-2.8 2.1M17.9 14.7l2.8 2.1-2.8 2.1" /></>,
info: <><circle cx="12" cy="12" r="8.2" /><path d="M12 11v5.4" /><circle cx="12" cy="7.9" r=".9" fill="currentColor" stroke="none" /></>,
warning: <><path d="M12 3.4 21.2 19.4H2.8Z" /><path d="M12 9.6v4.4" /><circle cx="12" cy="16.6" r=".9" fill="currentColor" stroke="none" /></>,
}
// A few keys are aliases so call sites can say what they mean.
+12 -3
View File
@@ -18,6 +18,12 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
const tipRef = useRef(null)
const [hover, setHover] = useState(null) // { x, y, iso, v }
// A new dataset has different coordinates and meaning, so never carry the previous
// point selection into it. Layout timing removes the marker before the new chart paints.
useLayoutEffect(() => {
setHover(null)
}, [points])
// The tooltip is placed after layout, from its measured size, because the chart
// lives in an overflow-clipped box: a fixed half-width offset (what this used to
// do) hangs the label off the edge on the first and last point, and the clip then
@@ -91,7 +97,10 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
const poly = pts.map(p => X(p.t).toFixed(1) + ',' + Y(p.y).toFixed(1)).join(' ')
const last = pts[pts.length - 1]
const gid = 'g' + Math.round(t0 % 1e7) + '_' + H
const hoverPts = (single ? [points[0]] : points).map(p => ({ x: X(p.t), y: Y(p.y), iso: p.d || isoOf(new Date(p.t)), v: p.y, note: p.note }))
const hoverSource = single ? [points[0]] : points
const hoverDates = hoverSource.map(p => p.d || isoOf(new Date(p.t)))
const showYear = new Set(hoverDates.map(iso => new Date(iso + 'T12:00:00').getFullYear())).size > 1
const hoverPts = hoverSource.map((p, i) => ({ x: X(p.t), y: Y(p.y), iso: hoverDates[i], v: p.y, note: p.note }))
const marked = points.some(p => p.m != null)
const onMove = e => {
@@ -132,8 +141,8 @@ export default function LineChart({ points, h = 150, unit = '', color = 'var(--a
</g>}
</svg>
{hover && <div className="ctip" ref={tipRef}>
{fmtDate(hover.iso, true)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}{hover.note ? ' · ' + hover.note : ''}
{fmtDate(hover.iso, true, showYear)} · {fmtNum(hover.v)}{unit ? ' ' + unit : ''}{hover.note ? ' · ' + hover.note : ''}
</div>}
</div>
)
}
}
+104
View File
@@ -0,0 +1,104 @@
// @vitest-environment happy-dom
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import LineChart from './LineChart.jsx'
import { fmtDate, isoOf } from '../lib/format.js'
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()
})
const point = (year, month, day, y) => ({
d: `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`,
t: new Date(year, month - 1, day, 12).getTime(),
y
})
const firstPoints = [
{ t: Date.UTC(2026, 0, 1), y: 80, d: '2026-01-01' },
{ t: Date.UTC(2026, 0, 15), y: 82, d: '2026-01-15' },
]
const nextPoints = [
{ t: Date.UTC(2026, 1, 1), y: 78, d: '2026-02-01' },
{ t: Date.UTC(2026, 1, 15), y: 79, d: '2026-02-15' },
]
function renderChart(points) {
act(() => root.render(<LineChart points={points} axes={false} unit="kg" />))
}
function hoverAt(clientX) {
act(() => {
container.querySelector('.chart-i').dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX }))
})
return container.querySelector('.ctip').textContent
}
describe('LineChart hover date', () => {
it('keeps same-year points in the compact format', () => {
const first = point(2026, 1, 15, 70)
renderChart([first, point(2026, 2, 15, 71)])
expect(hoverAt(0)).toBe(`${fmtDate(first.d, true)} · 70 kg`)
})
it('includes the calendar year at a short cross-year boundary', () => {
const first = point(2025, 11, 30, 70)
const last = point(2026, 2, 1, 71)
renderChart([first, last])
expect(hoverAt(0)).toBe(`${fmtDate(first.d, true, true)} · 70 kg`)
expect(hoverAt(340)).toBe(`${fmtDate(last.d, true, true)} · 71 kg`)
})
it('keeps a single point compact', () => {
const only = point(2026, 7, 4, 70)
renderChart([only])
expect(hoverAt(170)).toBe(`${fmtDate(only.d, true)} · 70 kg`)
})
it('uses timestamp-only points when deciding whether to show the year', () => {
const first = point(2025, 12, 31, 70)
const last = point(2026, 1, 1, 71)
const timestampOnly = [{ t: first.t, y: first.y }, { t: last.t, y: last.y }]
renderChart(timestampOnly)
const lastIso = isoOf(new Date(last.t))
expect(hoverAt(340)).toBe(`${fmtDate(lastIso, true, true)} · 71 kg`)
})
})
describe('LineChart hover state', () => {
it('clears the tooltip and hover markers when points are replaced, then allows hovering again', () => {
renderChart(firstPoints)
hoverAt(170)
expect(container.querySelector('.ctip')).toBeTruthy()
expect(container.querySelector('.cvl')).toBeTruthy()
expect(container.querySelector('.chl')).toBeTruthy()
renderChart(nextPoints)
expect(container.querySelector('.ctip')).toBeNull()
expect(container.querySelector('.cvl')).toBeNull()
expect(container.querySelector('.chl')).toBeNull()
hoverAt(170)
expect(container.querySelector('.ctip')).toBeTruthy()
expect(container.querySelector('.cvl')).toBeTruthy()
})
})
+2 -2
View File
@@ -1,7 +1,7 @@
import { useState } from 'react'
import { imgSrc, gifSrc } from '../lib/exercises.js'
import { useStore } from '../store/useStore.js'
import { t } from '../lib/i18n.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import Icon from './Icon.jsx'
// Big autoplaying animation; tap toggles to the still frame. `compact` shrinks it (superset cards).
@@ -18,7 +18,7 @@ export default function Media({ ex, id, compact, minimizable }) {
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={ex.n} />
<img decoding="async" 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')}
+45 -2
View File
@@ -248,7 +248,7 @@ 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 }) {
export function SelectRow({ icon, iconTint, title, value, options, onChange, sheetTitle, stackedValue = false }) {
const cur = options.find(o => o.value === value)
const open = () => {
const { openSheet } = require_ui()
@@ -270,7 +270,50 @@ export function SelectRow({ icon, iconTint, title, value, options, onChange, she
return h
}
return (
<Row icon={icon} iconTint={iconTint} title={title} value={cur ? cur.label : value} accessory="chevron" onClick={open} />
<Row icon={icon} iconTint={iconTint} title={title} value={cur ? cur.label : value} accessory="chevron" onClick={open}
className={stackedValue ? 'lrow-stack-value' : ''} />
)
}
/** 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 }) {
const selected = options.filter(o => values.includes(o.value))
const summary = selected.length ? selected.map(o => o.label).join(', ') : (noneLabel || '')
const open = () => {
const { openSheet } = require_ui()
openSheet(close => <MultiSelectSheet values={values} options={options} onToggle={onToggle}
title={sheetTitle || title} doneLabel={doneLabel} close={close} />)
}
return (
<Row icon={icon} iconTint={iconTint} title={title} value={summary} accessory="chevron" onClick={open} />
)
}
function MultiSelectSheet({ values, options, onToggle, title, doneLabel, close }) {
const [sel, setSel] = useState(values)
const toggle = value => {
setSel(current => current.includes(value) ? current.filter(x => x !== value) : [...current, value])
onToggle(value)
}
return (
<>
<h3>{title}</h3>
<div className="sect-b">
{options.map(o => {
const on = sel.includes(o.value)
return (
<button key={o.value} className={'lrow tap' + (on ? ' on' : '')} onClick={() => toggle(o.value)}>
<span className="lrow-m"><span className="lrow-t">{o.label}</span>
{o.subtitle && <span className="lrow-s">{o.subtitle}</span>}</span>
{on && <Icon name="check" className="lrow-k" />}
</button>
)
})}
</div>
<div style={{ height: 8 }} />
<Button variant="primary" onClick={close}>{doneLabel || 'Done'}</Button>
</>
)
}
+2
View File
@@ -0,0 +1,2 @@
// generated by scripts/build-pt-br-exercise-names.mjs — edit scripts/exercise-name-sources/pt-BR.json
export default {"1000":"elevação de panturrilha invertida unilateral com faixa elástica","1001":"afundo estático unilateral com faixa elástica","1002":"elevação de pernas retas deitado com faixa elástica","1003":"agachamento com remada e faixa elástica","1004":"agachamento com faixa elástica","1005":"abdominal em pé com faixa elástica","1007":"abdominal rotacional em pé com faixa elástica","1008":"subida no step com faixa elástica","1009":"levantamento terra pernas semiestendidas com faixa elástica","1010":"levantamento terra pernas estendidas com faixa elástica","1011":"torção sentado com faixa elástica","1012":"desenvolvimento acima da cabeça com rotação e faixa elástica","1013":"puxada pegada supinada com faixa elástica","1014":"abdominal em v com faixa elástica","1015":"pallof press vertical com faixa elástica","1016":"rosca de punho com faixa elástica","1017":"elevação em y com faixa elástica","1018":"encolhimento de ombros com faixa elástica","1022":"remada para deltoide posterior em pé com faixa elástica","1023":"levantamento terra pernas semiestendidas com costas retas e faixa elástica","1160":"burpee","1167":"alongamento dinâmico de peitoral (masculino)","1201":"Burpee com halteres","1253":"elevação de panturrilha burro na máquina","1254":"supino com faixa elástica","1255":"pullover declinado com barra","1256":"supino declinado pegada supinada com barra","1257":"supino inclinado pegada supinada com barra","1258":"supino pegada aberta supinada com barra","1259":"alongamento de peitoral atrás da cabeça","1260":"supino declinado unilateral no cabo","1261":"supino declinado no cabo","1262":"crucifixo declinado unilateral no cabo","1263":"crucifixo unilateral na bola de exercício no cabo","1264":"crucifixo inclinado unilateral na bola de exercício no cabo","1265":"supino inclinado unilateral no cabo","1266":"supino inclinado unilateral na bola de exercício no cabo","1267":"supino unilateral na bola de exercício no cabo","1268":"supino na bola de exercício no cabo","1269":"crossover em pé ereto no cabo","1270":"crossover para peitoral superior no cabo","1271":"alongamento de peito e parte frontal do ombro","1272":"alongamento de peito com bola de exercício","1273":"flexão de braços com palma","1274":"flexão de braços profunda","1275":"flexão de braços com queda","1276":"Crucifixo declinado unilateral com halter","1277":"Crucifixo com halteres na bola de estabilidade","1278":"Crucifixo inclinado com halteres na bola de estabilidade","1279":"Crucifixo inclinado unilateral com halter","1280":"Crucifixo inclinado unilateral com halter na bola de estabilidade","1281":"Supino inclinado unilateral com halter","1282":"Supino inclinado unilateral com halter na bola de estabilidade","1283":"Supino inclinado com halteres na bola de estabilidade","1284":"Pullover deitado na bola de estabilidade com halter","1285":"Crucifixo unilateral no banco com halter","1286":"Crucifixo unilateral na bola de estabilidade com halter","1287":"Supino declinado unilateral com halter","1288":"Crucifixo unilateral na bola de estabilidade com halter","1289":"Supino inclinado unilateral com halter","1290":"Supino unilateral na bola de estabilidade com halter","1291":"Pullover unilateral na bola de estabilidade com halter","1292":"Crucifixo com uma perna na bola de estabilidade (halteres)","1293":"Supino na bola de estabilidade com halteres","1294":"Pullover com extensão de quadril na bola de estabilidade (halteres)","1295":"Pullover na bola de estabilidade com halteres","1296":"flexão de braços em pique na bola de estabilidade","1297":"contração isométrica de peitoral","1298":"supino unilateral com kettlebell no chão","1299":"supino inclinado na máquina","1300":"supino declinado na máquina","1301":"supino interno na máquina","1302":"passe de peito com bola medicinal","1303":"empurrão de peito com bola medicinal a partir de três apoios","1304":"empurrão de peito com bola medicinal (resposta múltipla)","1305":"empurrão de peito com bola medicinal (resposta única)","1306":"flexão de braços pliométrica","1307":"flexão de braços na bosu","1308":"supino pegada aberta na máquina Smith","1309":"supino declinado pegada aberta na máquina Smith","1310":"flexão de braços com queda e peso","1311":"flexão de braços com mãos afastadas","1312":"empurrão de peito com bola medicinal com saída em corrida","1313":"remada unilateral na máquina","1314":"extensão de tronco na bola de estabilidade","1316":"pullover com braços flexionados com barra","1317":"remada no banco inclinado pegada supinada com barra","1318":"remada no banco inclinado no cabo","1319":"remada com rotação da palma no cabo","1320":"remada sentada crossover com corda no cabo","1321":"remada sentada elevada com corda no cabo","1322":"remada no banco inclinado com extensão de corda no cabo","1323":"remada sentada com corda no cabo","1324":"remada superior no cabo","1325":"puxada atrás da nuca pegada abLine truncated
+66 -8
View File
@@ -241,6 +241,17 @@ h4.sec{
.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}
.lrow.danger,.lrow.danger .lrow-t{color:var(--red)}
/* The Stats exercise name gets its own line so long names cannot run into the title.
Two columns only — label/value on the left, chevron on the right — so this is for rows
WITHOUT an icon. `.lrow-i` is not placed here; on a row that has one it would auto-place
into the grid and push the layout around. Give it a leading column before using this
anywhere else. */
.lrow.lrow-stack-value{
display:grid;grid-template-columns:minmax(0,1fr) auto;grid-template-rows:auto auto;
}
.lrow.lrow-stack-value .lrow-m{grid-column:1;grid-row:1}
.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;text-align:left}
.lrow.lrow-stack-value .lrow-c{grid-column:2;grid-row:1 / span 2;align-self:center}
/* an (i) before a row's control: painted small and dim so the control stays the loud thing,
but with a finger-sized target like everything else — the padding is the hit area and the
vertical negative margin keeps it from making the row taller. The horizontal ones pull the
@@ -272,15 +283,21 @@ h4.sec{
.btn:disabled{opacity:.32;pointer-events:none}
/* ----------------------------------------------------------- tab bar ----- */
/* Nearly opaque, and deliberately so. At the old 72% the page read straight through the bar
and the labels had to compete with whatever was scrolling behind them — nobody needs to read
the content under a navigation bar. 94% keeps a hint of movement behind the glass without
letting text through. The blur is also down from 24px to 10px: this is a fixed element, so
the WebView recomposites the blurred region on every scroll frame, and on Android that is
the single most expensive thing on the screen. See @supports below for the no-blur case. */
#tabbar{
position:fixed;left:0;right:0;bottom:0;z-index:50;
display:flex;justify-content:space-around;align-items:flex-end;
padding:7px 6px calc(6px + var(--sab));
background:color-mix(in srgb,var(--bg-el) 72%,transparent);
backdrop-filter:saturate(180%) blur(24px);-webkit-backdrop-filter:saturate(180%) blur(24px);
background:color-mix(in srgb,var(--bg-el) 94%,transparent);
-webkit-backdrop-filter:saturate(180%) blur(10px);backdrop-filter:saturate(180%) blur(10px);
border-top:var(--hair) solid var(--sep-op);
}
:root[data-theme="light"] #tabbar{background:rgba(249,249,251,.78)}
:root[data-theme="light"] #tabbar{background:rgba(249,249,251,.94)}
#tabbar button{
flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;
color:var(--label-3);font-size:10px;font-weight:500;letter-spacing:.005em;padding-top:3px;
@@ -317,6 +334,21 @@ h4.sec{
}
@keyframes ping{0%{transform:scale(1);opacity:.7}100%{transform:scale(1.45);opacity:0}}
/* NOTE on every backdrop-filter pair in this file: the -webkit- line comes first and the
standard property last, which is the order a prefixed/standard pair wants — whichever is
written last wins in the cascade, and that should be the standard name.
Where backdrop-filter is genuinely unsupported there is no glass either — only the alpha,
and the page shows through unblurred, which is the worst of both. Older Android WebViews
never had it, and "reduce transparency" accessibility settings drop it. Those surfaces go
fully opaque instead. Keep this in sync with the rules above. */
@supports not ((backdrop-filter:blur(1px)) or (-webkit-backdrop-filter:blur(1px))){
#tabbar{background:var(--bg-el)}
:root[data-theme="light"] #tabbar{background:#f9f9fb}
#timer{background:var(--surface)}
#toast{background:var(--surface-2)}
}
/* ------------------------------------------------------------ week strip -- */
.week{display:flex;justify-content:space-between;gap:4px}
.wday{
@@ -536,7 +568,7 @@ h4.sec{
position:absolute;bottom:9px;display:inline-flex;align-items:center;gap:4px;
background:rgba(0,0,0,.45);color:#fff;border-radius:99px;padding:5px 11px;
font-size:12px;font-weight:500;
backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);
-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);
}
.exmedia .gifhint{right:9px}
.exmedia .giftoggle{left:9px}
@@ -585,6 +617,18 @@ h4.sec{
.setrow.eff3 .stp .num{font-size:14px}
.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
(issue: drop-sets & rest-pause) */
.subrow{display:flex;align-items:center;gap:6px;padding:3px 0 3px 32px}
.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 .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)}
.setextra .chip.add svg{width:13px;height:13px}
.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;
@@ -614,7 +658,7 @@ h4.sec{
/* nearly opaque: the set rows underneath were reading through the old 82% and made the
clock hard to pick out mid-set. The blur stays, so it still sits above the page. */
background:color-mix(in srgb,var(--surface) 97%,transparent);
backdrop-filter:saturate(180%) blur(24px);-webkit-backdrop-filter:saturate(180%) blur(24px);
-webkit-backdrop-filter:saturate(180%) blur(10px);backdrop-filter:saturate(180%) blur(10px);
border-radius:var(--r-lg);padding:12px 14px;
display:flex;align-items:center;gap:12px;
box-shadow:0 12px 34px -8px rgba(0,0,0,.55);
@@ -647,7 +691,7 @@ h4.sec{
#modal-root.open{display:block}
.mback{
position:absolute;inset:0;background:rgba(0,0,0,.4);
backdrop-filter:blur(2px);-webkit-backdrop-filter:blur(2px);
-webkit-backdrop-filter:blur(2px);backdrop-filter:blur(2px);
touch-action:none;overscroll-behavior:none;
}
.sheet{
@@ -834,7 +878,7 @@ h4.sec{
position:fixed;left:50%;transform:translateX(-50%) translateY(6px);
bottom:calc(96px + var(--sab));z-index:200;
background:color-mix(in srgb,var(--surface-2) 88%,transparent);
backdrop-filter:saturate(180%) blur(20px);-webkit-backdrop-filter:saturate(180%) blur(20px);
-webkit-backdrop-filter:saturate(180%) blur(20px);backdrop-filter:saturate(180%) blur(20px);
border-radius:99px;padding:11px 20px;font-size:15px;font-weight:500;
box-shadow:0 10px 30px -6px rgba(0,0,0,.5);
opacity:0;pointer-events:none;transition:opacity var(--med),transform var(--med) var(--ease);
@@ -886,6 +930,13 @@ h4.sec{
border-radius:var(--r-lg);padding:14px;
background:var(--surface);box-shadow:inset 0 0 0 1.5px var(--acc-line);
}
/* 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
card only gives up its own padding; the rows inside keep their spacing. */
@media (max-width:400px){
.ss-card{padding:10px 8px}
}
.ss-hd{
font-size:12px;font-weight:600;color:var(--acc);margin-bottom:12px;
text-align:center;display:flex;align-items:center;justify-content:center;gap:5px;
@@ -897,7 +948,7 @@ h4.sec{
.today-row{
display:flex;align-items:center;justify-content:space-between;gap:10px;
margin-top:12px;padding:12px 14px;border-radius:var(--r);background:var(--surface-2);
transition:background var(--fast);width:100%;text-align:left;
transition:background var(--fast);width:100%;text-align:left;cursor:pointer;
}
.today-row:active{background:var(--surface-3)}
.today-row .lbl2{font-size:11px;font-weight:500;letter-spacing:.03em;text-transform:uppercase;color:var(--label-3)}
@@ -906,6 +957,13 @@ h4.sec{
letter-spacing:-.012em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:2px;
}
/* Only where a pointer really hovers — on a phone :hover sticks to the row after the tap.
Lighter than :active, which goes all the way to --surface-3, so the two stay distinct. */
@media (hover:hover){
.today-row:hover{background:color-mix(in srgb,var(--surface-2),var(--surface-3) 60%)}
:root[data-theme="light"] .today-row:hover{background:color-mix(in srgb,var(--surface-2),var(--surface-3) 85%)}
}
/* --------------------------------------------------- desktop (≥1000px) --- */
.cols{display:block}
@media (min-width:1000px){
+2
View File
@@ -0,0 +1,2 @@
// generated by scripts/build-pt-br-instructions.mjs — edit scripts/instruction-sources/pt-BR.json
export default {"1000":["Fique em pé com os pés afastados na largura do quadril e posicione a faixa elástica ao redor da parte anterior do pé.","Segure-se em um objeto estável para se equilibrar.","Eleve lentamente o calcanhar do chão, transferindo o peso corporal para a parte anterior do pé.","Faça uma breve pausa no alto e depois abaixe lentamente o calcanhar até a posição inicial.","Repita pelo número desejado de repetições e depois troque para a outra perna."],"1001":["Fique em pé com os pés afastados na largura do quadril e coloque uma faixa elástica ao redor dos tornozelos.","Dê um passo grande à frente com o pé direito e um passo menor para trás com o pé esquerdo.","Flexione os joelhos e abaixe o corpo até que a coxa direita fique paralela ao chão, mantendo o joelho esquerdo ligeiramente acima do chão.","Empurre o chão com o calcanhar direito para retornar à posição inicial.","Repita do outro lado."],"1002":["Deite-se de costas com as pernas retas e os pés juntos.","Coloque a faixa elástica ao redor do arco dos pés e segure as extremidades da faixa com as mãos.","Contraindo o abdômen, eleve as duas pernas do chão até ficarem perpendiculares ao chão.","Faça uma pausa no topo do movimento e, em seguida, abaixe lentamente as pernas até a posição inicial.","Repita pelo número desejado de repetições."],"1003":["Prenda a faixa elástica a um ponto de ancoragem firme na altura da cintura.","Fique em pé de frente para o ponto de ancoragem, com os pés afastados na largura dos ombros.","Segure as alças da faixa elástica com as palmas voltadas uma para a outra e os braços estendidos à frente.","Flexione os joelhos e desça até a posição de agachamento, mantendo as costas retas e o peito elevado.","A partir da posição de agachamento, puxe as alças da faixa elástica em direção ao corpo, aproximando as escápulas.","Faça uma breve pausa no final do movimento; depois, libere lentamente a tensão e retorne à posição inicial.","Repita pelo número desejado de repetições."],"1004":["Fique em pé com os pés afastados na largura dos ombros e a faixa elástica posicionada logo acima dos joelhos.","Mantendo o peito elevado e o abdômen contraído, leve o quadril para trás e flexione os joelhos para descer até a posição de agachamento.","Certifique-se de que os joelhos acompanhem a direção dos dedos dos pés e que o peso esteja sobre os calcanhares.","Faça uma breve pausa embaixo; depois, empurre o chão com os calcanhares para retornar à posição inicial.","Repita pelo número desejado de repetições."],"1005":["Fixe a faixa elástica em um ponto de ancoragem firme na altura da cintura.","Fique de pé de costas para o ponto de ancoragem, com os pés afastados na largura dos ombros.","Segure a faixa com as duas mãos e traga-a até o peito, mantendo os cotovelos dobrados e próximos ao corpo.","Contraia o abdômen e flexione o tronco lentamente para frente, levando o peito em direção aos joelhos.","Faça uma pausa no topo do movimento e, em seguida, retorne lentamente à posição inicial.","Repita pelo número desejado de repetições."],"1007":["Fique de pé com os pés afastados na largura dos ombros e passe a faixa elástica pela parte superior das costas, cruzando-a na frente do peito.","Segure as extremidades da faixa com as mãos, mantendo os cotovelos dobrados e próximos ao corpo.","Contraia o abdômen e gire o tronco para um dos lados, levando o cotovelo em direção ao joelho oposto.","Faça uma pausa e, em seguida, retorne à posição inicial.","Repita do outro lado.","Continue alternando os lados pelo número desejado de repetições."],"1008":["Coloque uma faixa elástica ao redor das coxas, logo acima dos joelhos.","Fique em pé de frente para um degrau ou plataforma, com os pés afastados na largura do quadril.","Suba na plataforma com o pé direito, empurrando-a com o calcanhar.","Estenda a perna esquerda para trás, mantendo-a reta.","Abaixe o pé esquerdo de volta ao chão.","Repita subindo na plataforma com o pé esquerdo.","Continue alternando as pernas pelo número desejado de repetições."],"1009":["Fique em pé com os pés afastados na largura dos ombros e coloque a faixa elástica ao redor dos tornozelos.","Segure a faixa elástica com as duas mãos à frente das coxas, com as palmas voltadas para o corpo.","Mantendo as costas retas e o abdômen contraído, incline o tronco à frente a partir do quadril e abaixe lentamente a parte superior do corpo em direção ao chão.","Ao descer, leve o quadril para trás e deixe os joelhos flexionarem levemente.","Abaixe a faixa elástica em direção ao chão, sentindo o alongamento nos músculos posteriores das coxas.","Faça uma breve pausa embaixo; depois, contraia os glúteos e os músculos posteriores das coxas para elevar a parte superior do corpo de volta à posição inicial.","Repita pelo número desejado de repetições."],"1010":["Fique em pé com os pés afastados na Line truncated
+25 -2
View File
@@ -3,10 +3,33 @@ export const IS_APPLE = /iPhone|iPad|iPod|Macintosh/.test(navigator.userAgent)
export const IS_ANDROID = /Android/.test(navigator.userAgent)
export const BIO = IS_APPLE ? 'Face ID / Touch ID' : IS_ANDROID ? 'fingerprint or face unlock' : 'your fingerprint, face or PIN'
export const VAULT = IS_APPLE ? 'iCloud Keychain' : IS_ANDROID ? 'Google Password Manager' : 'your password manager'
export const webauthnOK = () => !!(window.PublicKeyCredential && navigator.credentials)
// PublicKeyCredential is the WebAuthn-specific capability signal. Do not also gate the UI on
// navigator.credentials: some browsers expose WebAuthn while that generic Credential Management
// API check produces a false negative (notably Chrome on iOS). The real create/get calls still run
// only after the user chooses a passkey action and surface any genuine browser error there.
export const webauthnOK = () => typeof window.PublicKeyCredential !== 'undefined'
// The paired mobile app (lib/remote.js) is the only caller of these — everywhere else stays on
// same-origin cookies, so remoteBase/remoteToken stay empty and api() behaves exactly as before.
let remoteBase = ''
let remoteToken = null
export function setRemoteAuth(base, token) { remoteBase = base || ''; remoteToken = token || null }
export async function api(path, opts) {
const r = await fetch(path, Object.assign({ headers: { 'Content-Type': 'application/json' } }, opts))
const headers = Object.assign({ 'Content-Type': 'application/json' }, opts && opts.headers)
if (remoteToken) headers.Authorization = 'Bearer ' + remoteToken
const r = await fetch(remoteBase + path, Object.assign({}, opts, { headers }))
const data = await r.json().catch(() => ({}))
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e }
return data
}
// Bootstraps the connection itself: the base isn't configured yet (that's what this call decides),
// so it talks straight to the server the user typed in, no Authorization header.
export async function pairRedeem(serverBase, code) {
const r = await fetch(serverBase + '/api/pair/redeem', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code })
})
const data = await r.json().catch(() => ({}))
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e }
return data
+35
View File
@@ -0,0 +1,35 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it } from 'vitest'
import { webauthnOK } from './api.js'
const originalPublicKeyCredential = window.PublicKeyCredential
const originalCredentials = navigator.credentials
function setCapability(target, property, value) {
Object.defineProperty(target, property, { configurable: true, value })
}
afterEach(() => {
setCapability(window, 'PublicKeyCredential', originalPublicKeyCredential)
setCapability(navigator, 'credentials', originalCredentials)
})
describe('webauthnOK', () => {
it('accepts WebAuthn when PublicKeyCredential is exposed', () => {
setCapability(window, 'PublicKeyCredential', class PublicKeyCredential {})
setCapability(navigator, 'credentials', {})
expect(webauthnOK()).toBe(true)
})
it('does not reject WebAuthn when the generic credentials check is unavailable', () => {
setCapability(window, 'PublicKeyCredential', class PublicKeyCredential {})
setCapability(navigator, 'credentials', undefined)
expect(webauthnOK()).toBe(true)
})
it('rejects browsers without the WebAuthn credential type', () => {
setCapability(window, 'PublicKeyCredential', undefined)
setCapability(navigator, 'credentials', {})
expect(webauthnOK()).toBe(false)
})
})
+73
View File
@@ -0,0 +1,73 @@
// Rendering for the admin activity log (GET /api/admin/audit).
//
// The server stores reason codes, not sentences — `{ ev: 'auth.login.fail', msg: 'unknown-credential' }`
// rather than "someone tried a passkey we don't know". Turning those into English
// belongs here and not in Admin.jsx: it is the only part of the feature that can be wrong in a way
// a person sees, and as a plain module it is testable without mounting the dashboard.
//
// Like the rest of the admin screen this is English-only — the operator surface deliberately
// stays out of the per-language string packs (see the header of views/Admin.jsx). Times still
// follow the UI language, the way numbers and dates already do.
import { dateLocale } from './i18n-core.js'
// The first segment of an event name is also the filter chip it belongs to.
export const auditCat = ev => String(ev || '').split('.')[0]
const LABELS = {
'auth.login.ok': 'Signed in',
'auth.login.fail': 'Sign-in failed',
'auth.register.ok': 'Created a profile',
'auth.register.fail': 'Profile creation failed',
'auth.register.denied': 'Signup refused',
'auth.logout': 'Signed out',
'auth.logout.all': 'Signed out everywhere',
'admin.user.disable': 'Disabled an account',
'admin.user.enable': 'Re-enabled an account',
'admin.invite.create': 'Created an invite code',
'admin.invite.revoke': 'Revoked an invite code',
'admin.audit.clear': 'Cleared the activity log',
'admin.denied': 'Blocked from the admin dashboard'
}
// An unknown event is shown raw rather than dropped or rendered as "undefined": a dashboard
// that is one version behind the server should still say *something* truthful.
export const auditLabel = ev => LABELS[ev] || String(ev || 'Unknown event')
const REASONS = {
'challenge-expired': 'the sign-in took too long and expired',
'unknown-credential': 'unknown passkey',
'verify-error': 'the passkey could not be verified',
'not-verified': 'the passkey was rejected',
'user-missing': 'the passkey points at a profile that no longer exists',
'account-disabled': 'the account is disabled',
'credential-exists': 'that passkey already belongs to a profile',
'invite-invalid': 'the invite code was used or revoked in the meantime',
'invite-rejected': 'wrong or already-used invite code'
}
export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '')
// → { title, sub }. `sub` is the house "a · b · c" metadata line used by every list row.
export function auditLine(e) {
if (!e) return { title: '', sub: '' }
const parts = []
if (e.name) parts.push(e.name)
else if (e.uid) parts.push(e.uid)
else if (!e.ok) parts.push('unknown caller')
if (e.tname) parts.push('→ ' + e.tname)
// The reason codes and the invite codes share the msg field; only failures read as a reason.
if (e.msg) parts.push(e.ok ? e.msg : auditReason(e.msg))
if (e.ip) parts.push(e.ip)
return { title: auditLabel(e.ev), sub: parts.join(' · ') }
}
// The activity log is the one place in the app that needs a clock, and fmtDate() renders none —
// it is used by every other view and is not worth changing for this.
export function fmtWhen(ts, now = Date.now()) {
if (!ts) return ''
const d = new Date(ts)
const time = d.toLocaleTimeString(dateLocale(), { hour: '2-digit', minute: '2-digit' })
const n = new Date(now)
const sameDay = d.toDateString() === n.toDateString()
if (sameDay) return 'today ' + time
if (now - ts < 6 * 86400000 && ts <= now) return d.toLocaleDateString(dateLocale(), { weekday: 'short' }) + ' ' + time
return d.toLocaleDateString(dateLocale(), { day: 'numeric', month: 'short' }) + ' ' + time
}
+136
View File
@@ -0,0 +1,136 @@
import { describe, it, expect } from 'vitest'
import { auditCat, auditLabel, auditReason, auditLine, fmtWhen } from './audit.js'
// Every event name and reason code the server can emit (api/server.js, the audit block).
// If a new one is added there without a label here, the first test fails rather than the
// dashboard quietly printing a dotted identifier at a person.
const EVENTS = [
'auth.login.ok', 'auth.login.fail', 'auth.register.ok', 'auth.register.fail',
'auth.register.denied', 'auth.logout', 'auth.logout.all',
'admin.user.disable', 'admin.user.enable', 'admin.invite.create',
'admin.invite.revoke', 'admin.audit.clear', 'admin.denied'
]
const REASONS = [
'challenge-expired', 'unknown-credential', 'verify-error', 'not-verified',
'user-missing', 'account-disabled', 'credential-exists', 'invite-invalid', 'invite-rejected'
]
describe('auditLabel', () => {
it('has a sentence for every event the server emits', () => {
for (const ev of EVENTS) {
expect(auditLabel(ev), ev).not.toBe(ev)
expect(auditLabel(ev)).toMatch(/^[A-Z]/)
}
})
it('shows an unknown event raw instead of rendering undefined', () => {
// A dashboard one version behind the server must still say something truthful.
expect(auditLabel('auth.something.new')).toBe('auth.something.new')
expect(auditLabel(undefined)).toBe('Unknown event')
expect(auditLabel('')).toBe('Unknown event')
})
})
describe('auditCat', () => {
it('takes the filter category from the first segment', () => {
expect(auditCat('auth.login.ok')).toBe('auth')
expect(auditCat('admin.invite.create')).toBe('admin')
})
it('survives a missing event name', () => {
expect(auditCat(undefined)).toBe('')
})
it('puts every known event in exactly auth or admin', () => {
expect([...new Set(EVENTS.map(auditCat))].sort()).toEqual(['admin', 'auth'])
})
})
describe('auditReason', () => {
it('has plain English for every reason code', () => {
for (const m of REASONS) {
expect(auditReason(m), m).not.toBe(m)
expect(auditReason(m).length).toBeGreaterThan(3)
}
})
it('falls back to the raw code and tolerates none at all', () => {
expect(auditReason('brand-new-code')).toBe('brand-new-code')
expect(auditReason(undefined)).toBe('')
})
})
describe('auditLine', () => {
it('names the person who did it', () => {
expect(auditLine({ ev: 'auth.login.ok', ok: true, uid: 'u1', name: 'Duarte' }))
.toEqual({ title: 'Signed in', sub: 'Duarte' })
})
it('shows both sides of an admin action', () => {
const l = auditLine({ ev: 'admin.user.disable', ok: true, uid: 'a', name: 'Duarte', tgt: 'b', tname: 'Ana' })
expect(l.title).toBe('Disabled an account')
expect(l.sub).toBe('Duarte · → Ana')
})
it('translates the reason on a failure but not the invite code on a success', () => {
expect(auditLine({ ev: 'auth.login.fail', ok: false, msg: 'unknown-credential' }).sub)
.toBe('unknown caller · unknown passkey')
// admin.invite.* put the actual code in msg — that must not be run through auditReason.
expect(auditLine({ ev: 'admin.invite.create', ok: true, name: 'Duarte', msg: 'A1B2C3D4' }).sub)
.toBe('Duarte · A1B2C3D4')
})
it('says "unknown caller" only when a failure carries no identity', () => {
expect(auditLine({ ev: 'auth.login.fail', ok: false }).sub).toBe('unknown caller')
// A successful event without a name is not an anonymous attacker, so it stays blank.
expect(auditLine({ ev: 'auth.logout', ok: true }).sub).toBe('')
})
it('falls back to the uid when the name was never recorded', () => {
expect(auditLine({ ev: 'auth.login.fail', ok: false, uid: 'Xy1', msg: 'user-missing' }).sub)
.toBe('Xy1 · the passkey points at a profile that no longer exists')
})
it('appends the network when the operator opted into IPs', () => {
expect(auditLine({ ev: 'auth.login.ok', ok: true, name: 'Duarte', ip: '203.0.113.0/24' }).sub)
.toBe('Duarte · 203.0.113.0/24')
})
it('renders nothing rather than throwing on a missing record', () => {
expect(auditLine(undefined)).toEqual({ title: '', sub: '' })
})
})
describe('fmtWhen', () => {
const at = (y, m, d, h, min) => new Date(y, m - 1, d, h, min).getTime()
const now = at(2026, 8, 23, 15, 0) // Sunday
it('says "today" for the same calendar day', () => {
expect(fmtWhen(at(2026, 8, 23, 9, 5), now)).toMatch(/^today /)
expect(fmtWhen(at(2026, 8, 23, 0, 1), now)).toMatch(/^today /)
})
it('uses the weekday inside the last six days', () => {
const s = fmtWhen(at(2026, 8, 21, 18, 30), now)
expect(s).not.toMatch(/^today/)
expect(s).toMatch(/^[A-Za-zÀ-ÿ.]+ \d/)
})
it('falls back to a date once it is older', () => {
expect(fmtWhen(at(2026, 8, 12, 14, 32), now)).toMatch(/\d/)
expect(fmtWhen(at(2026, 8, 12, 14, 32), now)).not.toMatch(/^today/)
})
it('always carries a time of day — that is the whole point of not reusing fmtDate', () => {
for (const ts of [at(2026, 8, 23, 9, 5), at(2026, 8, 21, 18, 30), at(2026, 8, 12, 14, 32)]) {
expect(fmtWhen(ts, now)).toMatch(/\d{1,2}[:.]\d{2}/)
}
})
it('does not call a future timestamp "3 days ago"', () => {
// Clock skew between server and browser is real; a tomorrow must not read as a weekday.
expect(fmtWhen(at(2026, 8, 30, 10, 0), now)).not.toMatch(/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)/)
})
it('returns an empty string for a missing timestamp', () => {
expect(fmtWhen(0)).toBe('')
expect(fmtWhen(undefined)).toBe('')
})
})
+62
View File
@@ -0,0 +1,62 @@
// Android system back (the gesture and the hardware/nav button are the same event).
//
// Capacitor's BridgeActivity does not handle back at all — without a JS listener the
// activity simply finishes, so a back swipe quit the app from anywhere, whatever the
// WebView history said. That made the sheet history entries from #63 dead weight in the
// packaged app: they only ever worked in a browser tab, where the browser walks history
// itself.
//
// Once a `backButton` listener exists, the plugin stops falling through to finish() —
// back can then ONLY leave the app through App.exitApp(), which is why the last step is
// an explicit press-again-to-exit rather than a silent no-op.
import { MOBILE } from './mobile.js'
import { useUI } from '../store/useUI.js'
import { t } from './i18n.js'
// How long a first back press stays armed as "press again to exit" (the toast shows 2.2s).
export const EXIT_WINDOW = 2000
// What a back press means, given what is on screen. Pure, so the table below is testable.
export function decideBack({ top, canGoBack, exitArmed }) {
if (top) return top.locked ? 'ignore' : 'sheet' // a locked sheet swallows back on purpose
if (canGoBack) return 'history' // a page/tab we pushed ourselves
return exitArmed ? 'exit' : 'arm-exit'
}
export function makeBackHandler({ getSheets, closeSheet, toast, goBack, exit, now = Date.now }) {
let armedAt = -Infinity
return (ev = {}) => {
const sheets = getSheets()
const action = decideBack({
top: sheets[sheets.length - 1],
canGoBack: !!ev.canGoBack,
exitArmed: now() - armedAt < EXIT_WINDOW,
})
if (action !== 'arm-exit') armedAt = -Infinity
if (action === 'sheet') closeSheet(sheets[sheets.length - 1].id)
else if (action === 'history') goBack()
else if (action === 'arm-exit') { armedAt = now(); toast(t('Press back again to exit')) }
else if (action === 'exit') exit()
return action
}
}
// Registers the listener for the native shell. No-op in web builds, where the browser
// (or the PWA shell) walks history on its own and there is no plugin to talk to.
export async function initBackButton() {
if (!MOBILE) return () => {}
try {
const { App } = await import('@capacitor/app')
const handler = makeBackHandler({
getSheets: () => useUI.getState().sheets,
closeSheet: id => useUI.getState().closeSheet(id),
toast: msg => useUI.getState().toast(msg),
goBack: () => window.history.back(),
exit: () => App.exitApp(),
})
const sub = await App.addListener('backButton', handler)
return () => sub.remove()
} catch (e) {
return () => {} // no plugin (older install): leave back to the default behaviour
}
}
+103
View File
@@ -0,0 +1,103 @@
// @vitest-environment happy-dom
import { describe, expect, it } from 'vitest'
import { decideBack, makeBackHandler, EXIT_WINDOW } from './back.js'
// Back on Android has to serve three layers with one event: the sheet stack on top, the
// page history under it, and — because a registered listener stops the plugin from ever
// finishing the activity itself — a deliberate way out of the app at the bottom.
describe('decideBack', () => {
it('dismisses the top sheet before touching history', () => {
expect(decideBack({ top: { id: 's1' }, canGoBack: true, exitArmed: false })).toBe('sheet')
})
it('lets a locked sheet swallow the press', () => {
expect(decideBack({ top: { id: 's1', locked: true }, canGoBack: true, exitArmed: true })).toBe('ignore')
})
it('walks history when nothing is open', () => {
expect(decideBack({ top: undefined, canGoBack: true, exitArmed: false })).toBe('history')
})
it('arms the exit at the bottom of the stack, and exits on the second press', () => {
expect(decideBack({ top: undefined, canGoBack: false, exitArmed: false })).toBe('arm-exit')
expect(decideBack({ top: undefined, canGoBack: false, exitArmed: true })).toBe('exit')
})
})
function harness() {
const calls = { closed: [], toasts: [], back: 0, exit: 0 }
let sheets = []
let now = 1000
const handler = makeBackHandler({
getSheets: () => sheets,
closeSheet: id => { calls.closed.push(id); sheets = sheets.filter(s => s.id !== id) },
toast: m => calls.toasts.push(m),
goBack: () => { calls.back++ },
exit: () => { calls.exit++ },
now: () => now,
})
return { calls, handler, setSheets: s => { sheets = s }, tick: ms => { now += ms } }
}
describe('makeBackHandler', () => {
it('closes stacked sheets one press at a time', () => {
const h = harness()
h.setSheets([{ id: 'a' }, { id: 'b' }])
expect(h.handler({ canGoBack: true })).toBe('sheet')
expect(h.handler({ canGoBack: true })).toBe('sheet')
expect(h.calls.closed).toEqual(['b', 'a'])
expect(h.calls.back).toBe(0)
})
it('does not close a locked sheet, and does not arm the exit behind it', () => {
const h = harness()
h.setSheets([{ id: 'a', locked: true }])
expect(h.handler({ canGoBack: false })).toBe('ignore')
expect(h.calls.closed).toEqual([])
expect(h.calls.toasts).toEqual([])
expect(h.calls.exit).toBe(0)
})
it('goes back a page while the WebView still has app history', () => {
const h = harness()
expect(h.handler({ canGoBack: true })).toBe('history')
expect(h.calls.back).toBe(1)
expect(h.calls.exit).toBe(0)
})
// The whole point of the fix: one press at the root must never be the end of the app.
it('warns once, then exits on a second press inside the window', () => {
const h = harness()
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
expect(h.calls.toasts).toHaveLength(1)
expect(h.calls.exit).toBe(0)
h.tick(EXIT_WINDOW - 1)
expect(h.handler({ canGoBack: false })).toBe('exit')
expect(h.calls.exit).toBe(1)
})
it('re-arms rather than exiting once the window has passed', () => {
const h = harness()
h.handler({ canGoBack: false })
h.tick(EXIT_WINDOW + 1)
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
expect(h.calls.exit).toBe(0)
expect(h.calls.toasts).toHaveLength(2)
})
// A sheet opened (or a page pushed) after the warning means the user is still using the
// app — the next back belongs to that sheet, and the one after must warn again.
it('disarms the exit as soon as another press does real work', () => {
const h = harness()
h.handler({ canGoBack: false })
h.setSheets([{ id: 'a' }])
expect(h.handler({ canGoBack: true })).toBe('sheet')
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
expect(h.calls.exit).toBe(0)
})
it('treats a missing event payload as no history', () => {
const h = harness()
expect(h.handler()).toBe('arm-exit')
})
})
+1 -1
View File
@@ -11,4 +11,4 @@
// lands in a self-hosted bundle.
export const DEMO = import.meta.env.VITE_DEMO === '1'
export const DEMO_SEEDED = 'gym_demo_seeded_v1'
export const REPO = 'https://github.com/DuarteSantos8/openGym'
export const REPO = 'https://gitlab.com/DuarteSantos8/opengym'
+34
View File
@@ -0,0 +1,34 @@
import { t } from './i18n.js'
import { EXDB } from './exercises-data.js'
// Every equipment value present in the catalogue, most common first — this becomes the
// checklist Settings shows when you build a profile.
export const ALL_EQUIPMENT = (() => {
const c = {}
EXDB.forEach(e => { if (e.eq) c[e.eq] = (c[e.eq] || 0) + 1 })
return Object.keys(c).sort((a, b) => c[b] - c[a] || (a < b ? -1 : 1))
})()
// Body weight is never gated by a profile — no gym or home setup can take it away from you,
// and every profile should be able to see bodyweight exercises regardless of what's checked.
const ALWAYS_AVAILABLE = 'body weight'
export function activeProfile(S) {
if (!S.equipFilterOn) return null
const profiles = S.equipProfiles || []
return profiles.find(p => p.id === S.activeEquipId) || null
}
// Whether an exercise is usable under the active profile. With filtering off, or no profile
// selected, everything is available — this is purely additive, never a trap that hides your
// whole library because you haven't set anything up yet.
export function exAvailable(S, ex) {
const p = activeProfile(S)
if (!p) return true
if (!ex.eq || ex.eq === ALWAYS_AVAILABLE) return true
return (p.equipment || []).includes(ex.eq)
}
export function newProfile(name) {
return { id: 'eq' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6), name, equipment: [] }
}
@@ -0,0 +1,27 @@
import batch from './exercise-muscle-batch-1.json' with { type: 'json' }
import { MACHINE_BATCH_2 } from './exercise-muscle-batch-2.js'
/**
* ExRx-informed metadata for the first compound-lift batch. The raw generated catalogue remains
* untouched; exercises.js applies this layer to the runtime index.
*/
export const COMPOUND_LIFT_BATCH_1 = Object.freeze(batch)
// Keep the phase-2 artifact in its own module for auditing while preserving the phase-1 resolver
// interface consumed by exercises.js and downstream muscle helpers.
export { MACHINE_BATCH_2 }
/**
* Reserved for owner-approved corrections. This layer is intentionally separate from the
* generated batch so a correction can replace a generated body part or muscle list without
* editing generated data. Explicit metadata on a user/custom exercise wins as well.
*/
export const USER_EXERCISE_MUSCLE_OVERRIDES = Object.freeze({})
export function exerciseMuscleMetadataFor(id) {
return {
...(COMPOUND_LIFT_BATCH_1[id] || {}),
...(MACHINE_BATCH_2[id] || {}),
...(USER_EXERCISE_MUSCLE_OVERRIDES[id] || {})
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,85 @@
import { describe, expect, it } from 'vitest'
import { BODYPARTS, EXDB, EXIDX, registerCustom } from './exercises.js'
import { COMPOUND_LIFT_BATCH_1 } from './exercise-muscle-batch-1.js'
import { MUSCLES, musclesOf } from './muscles.js'
const ids = Object.keys(COMPOUND_LIFT_BATCH_1)
const catalogueIds = new Set(EXDB.map(ex => ex.id))
const duplicateFree = values => values.length === new Set(values).size
describe('compound-lift muscle metadata batch 1', () => {
it('contains a bounded first batch of compound-lift catalogue entries', () => {
expect(ids.length).toBeGreaterThanOrEqual(60)
expect(ids.length).toBeLessThanOrEqual(120)
expect(ids.every(id => catalogueIds.has(id))).toBe(true)
})
it('stores canonical primary and secondary arrays for every batch entry', () => {
for (const [id, metadata] of Object.entries(COMPOUND_LIFT_BATCH_1)) {
expect(metadata.primaries.length, id).toBeGreaterThan(0)
expect(duplicateFree(metadata.primaries), id).toBe(true)
expect(duplicateFree(metadata.secondaries), id).toBe(true)
expect(metadata.primaries.some(muscle => metadata.secondaries.includes(muscle)), id).toBe(false)
expect(metadata.primaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
expect(metadata.secondaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
expect(EXIDX[id]).toMatchObject(metadata)
}
})
it('follows the documented ExRx family templates and preserves source-known muscles', () => {
expect(COMPOUND_LIFT_BATCH_1['0043']).toEqual({
bp: 'upper legs',
primaries: ['quadriceps', 'gluteal', 'adductors'],
secondaries: ['hamstring', 'calves', 'lower-back', 'abs', 'obliques']
})
expect(COMPOUND_LIFT_BATCH_1['0032']).toEqual({
bp: 'full body',
primaries: ['gluteal', 'hamstring', 'lower-back'],
secondaries: ['quadriceps', 'adductors', 'calves', 'abs', 'obliques']
})
expect(COMPOUND_LIFT_BATCH_1['0025']).toEqual({
bp: 'chest', primaries: ['chest'], secondaries: ['triceps', 'deltoids', 'biceps']
})
expect(COMPOUND_LIFT_BATCH_1['0091']).toEqual({
bp: 'shoulders', primaries: ['deltoids'],
secondaries: ['chest', 'triceps', 'trapezius', 'serratus']
})
expect(COMPOUND_LIFT_BATCH_1['0027']).toEqual({
bp: 'back', primaries: ['upper-back'],
secondaries: ['biceps', 'deltoids', 'forearm']
})
expect(COMPOUND_LIFT_BATCH_1['0652']).toEqual({
bp: 'back', primaries: ['upper-back'], secondaries: ['biceps', 'deltoids', 'forearm']
})
expect(musclesOf(EXDB.find(exercise => exercise.id === '0587'))).toMatchObject({ chest: 0.4 })
expect(musclesOf(EXIDX['0587'])).toMatchObject({ chest: 0.4 })
})
it('keeps torso bracing secondary and does not label the twisting press full body', () => {
expect(COMPOUND_LIFT_BATCH_1['0414']).toEqual({
bp: 'shoulders', primaries: ['deltoids'], secondaries: ['triceps', 'trapezius', 'abs']
})
expect(COMPOUND_LIFT_BATCH_1['1012']).toEqual({
bp: 'shoulders', primaries: ['deltoids'],
secondaries: ['triceps', 'trapezius', 'abs', 'obliques']
})
expect(COMPOUND_LIFT_BATCH_1['1012'].primaries).not.toContain('abs')
expect(COMPOUND_LIFT_BATCH_1['1012'].secondaries).toContain('obliques')
})
it('marks the cross-region lifts as Full body while keeping classic areas available', () => {
expect(EXIDX['0069']).toMatchObject({ bp: 'full body', primaries: ['quadriceps', 'gluteal', 'adductors'] })
expect(EXIDX['0032'].bp).toBe('full body')
expect(BODYPARTS).toContain('full body')
expect(EXIDX['0025'].bp).toBe('chest')
expect(EXIDX['0652'].bp).toBe('back')
})
it('lets an explicit user exercise override the batch and restores the catalogue afterward', () => {
registerCustom([{ id: '0025', n: 'Owner bench correction', bp: 'chest', primaries: ['triceps'], secondaries: [] }])
expect(EXIDX['0025']).toMatchObject({ primaries: ['triceps'], secondaries: [] })
registerCustom([])
expect(EXIDX['0025']).toMatchObject(COMPOUND_LIFT_BATCH_1['0025'])
})
})
@@ -0,0 +1,8 @@
import batch from './exercise-muscle-batch-2.json' with { type: 'json' }
/**
* ExRx-informed metadata for machine, cable, sled, and Smith-machine catalogue entries.
* `exercises.js` applies this as a runtime overlay so the raw generated catalogue remains
* compatible with imports and historical records.
*/
export const MACHINE_BATCH_2 = Object.freeze(batch)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,135 @@
import { describe, expect, it } from 'vitest'
import { BODYPARTS, EXDB, EXIDX, registerCustom } from './exercises.js'
import { MACHINE_BATCH_2 } from './exercise-muscle-batch-2.js'
import { MUSCLES, musclesOf } from './muscles.js'
const ids = Object.keys(MACHINE_BATCH_2)
const catalogue = new Map(EXDB.map(exercise => [exercise.id, exercise]))
const duplicateFree = values => values.length === new Set(values).size
const expectMapping = (id, expected) => {
expect(MACHINE_BATCH_2[id], id).toEqual(expected)
expect(EXIDX[id], id).toMatchObject(expected)
}
describe('machine muscle metadata batch 2', () => {
it('contains a bounded batch of machine and cable catalogue entries', () => {
expect(ids.length).toBeGreaterThanOrEqual(60)
expect(ids.length).toBeLessThanOrEqual(120)
expect(ids.length).toBe(119)
expect(ids.every(id => catalogue.has(id))).toBe(true)
expect(ids.every(id => /machine|cable/.test(catalogue.get(id).eq))).toBe(true)
})
it('uses only existing body-part keys and canonical drawable muscle slugs', () => {
for (const [id, metadata] of Object.entries(MACHINE_BATCH_2)) {
expect(BODYPARTS, id).toContain(metadata.bp)
expect(metadata.primaries.length, id).toBeGreaterThan(0)
expect(duplicateFree(metadata.primaries), id).toBe(true)
expect(duplicateFree(metadata.secondaries), id).toBe(true)
expect(metadata.primaries.some(muscle => metadata.secondaries.includes(muscle)), id).toBe(false)
expect(metadata.primaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
expect(metadata.secondaries.every(muscle => MUSCLES.includes(muscle)), id).toBe(true)
expect(EXIDX[id]).toMatchObject(metadata)
}
})
it('maps the pec-deck family from the lever seated-fly template', () => {
expectMapping('0596', {
bp: 'chest', primaries: ['chest'], secondaries: ['deltoids', 'biceps', 'serratus']
})
})
it('maps chest-press machines to chest with pressing assistants', () => {
expectMapping('0577', {
bp: 'chest', primaries: ['chest'], secondaries: ['deltoids', 'triceps', 'biceps']
})
})
it('maps cable crossovers to drawing-ready upper-back support', () => {
expectMapping('0155', {
bp: 'chest', primaries: ['chest'], secondaries: ['upper-back', 'trapezius']
})
})
it('maps machine/cable lat pulldowns to upper back with arm-and-shoulder synergy', () => {
expectMapping('0579', {
bp: 'back',
primaries: ['upper-back'],
secondaries: ['biceps', 'deltoids', 'forearm', 'trapezius', 'triceps']
})
})
it('maps seated rows to upper back with the phase-1 pull template', () => {
expectMapping('1350', {
bp: 'back',
primaries: ['upper-back'],
secondaries: ['biceps', 'deltoids', 'forearm', 'trapezius', 'chest', 'triceps']
})
})
it('maps assisted triceps dip variants to full synergist support', () => {
expectMapping('0019', {
bp: 'upper arms',
primaries: ['triceps'],
secondaries: ['deltoids', 'chest', 'upper-back', 'trapezius', 'biceps']
})
expectMapping('1451', {
bp: 'upper arms',
primaries: ['triceps'],
secondaries: ['deltoids', 'chest', 'upper-back', 'trapezius', 'biceps']
})
})
it('maps lever triceps extension without ExRx synergist secondaries', () => {
expectMapping('0607', {
bp: 'upper arms', primaries: ['triceps'], secondaries: []
})
})
it('maps sled leg presses to the multi-primary lower-body template', () => {
expectMapping('0739', {
bp: 'upper legs', primaries: ['quadriceps', 'gluteal', 'adductors'], secondaries: ['hamstring', 'calves']
})
})
it('maps leg extensions as quadriceps isolation', () => {
expectMapping('0585', {
bp: 'upper legs', primaries: ['quadriceps'], secondaries: []
})
})
it('maps seated leg curls to hamstrings with calf assistance', () => {
expectMapping('0599', {
bp: 'upper legs', primaries: ['hamstring'], secondaries: ['calves', 'adductors']
})
})
it('maps machine shoulder presses to deltoids with direct press support', () => {
expectMapping('0603', {
bp: 'shoulders', primaries: ['deltoids'],
secondaries: ['chest', 'triceps', 'trapezius', 'serratus', 'biceps']
})
})
it('preserves raw dataset metadata while enriching only the runtime catalogue', () => {
const raw = catalogue.get('0577')
expect(raw).toMatchObject({ id: '0577', n: 'lever chest press', tg: 'pectorals', mg: 'triceps' })
expect(raw).not.toHaveProperty('primaries')
expect(raw).not.toHaveProperty('secondaries')
expect(musclesOf(raw)).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4 })
expect(musclesOf(EXIDX['0577'])).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4, biceps: 0.4 })
})
it('gives an explicit custom collision precedence and restores the machine overlay', () => {
registerCustom([{
id: '0577', n: 'Owner machine press correction', bp: 'chest',
primaries: ['triceps'], secondaries: []
}])
expect(EXIDX['0577']).toMatchObject({ primaries: ['triceps'], secondaries: [] })
expect(musclesOf(EXIDX['0577'])).toEqual({ triceps: 1 })
registerCustom([])
expect(EXIDX['0577']).toMatchObject(MACHINE_BATCH_2['0577'])
expect(musclesOf(EXIDX['0577'])).toEqual({ chest: 1, deltoids: 0.4, triceps: 0.4, biceps: 0.4 })
})
})
+130 -12
View File
@@ -1,8 +1,29 @@
import { EXDB } from './exercises-data.js'
import { t } from './i18n-core.js'
import { USER_EXERCISE_MUSCLE_OVERRIDES, exerciseMuscleMetadataFor } from './exercise-muscle-batch-1.js'
import { t, getVersion, exerciseNameSearchText } from './i18n-core.js'
export { EXDB }
// The generated dataset remains the compatibility/raw export. The runtime catalogue applies
// owner-approved muscle metadata as a narrow overlay, so imports and historical tests that rely
// on the upstream shape keep working while EXIDX and pickers see the corrected model.
const catalogueExercise = ex => {
const metadata = exerciseMuscleMetadataFor(ex?.id)
if (!Object.keys(metadata).length) return ex
const out = { ...ex, ...metadata }
const user = USER_EXERCISE_MUSCLE_OVERRIDES[ex?.id] || {}
// A future dataset row may carry explicit arrays of its own; preserve those over generated
// defaults unless the owner has deliberately supplied a correction for the same field.
for (const key of ['primaries', 'secondaries']) {
if (Object.prototype.hasOwnProperty.call(ex, key) && !Object.prototype.hasOwnProperty.call(user, key)) out[key] = ex[key]
}
if (Array.isArray(out.primaries)) out.primaries = [...out.primaries]
if (Array.isArray(out.secondaries)) out.secondaries = [...out.secondaries]
return out
}
export const CATALOGUE = EXDB.map(catalogueExercise)
// The generated dataset already supplies secondary muscles for most exercises. Keep the
// handful of conservative catalogue additions that are useful to the muscle map here so a
// dataset refresh does not erase them. Values follow the dataset's existing alias vocabulary.
@@ -23,8 +44,8 @@ export const smOf = ex => {
}
export const EXIDX = {}
EXDB.forEach(e => { EXIDX[e.id] = e })
export const BODYPARTS = [...new Set(EXDB.map(e => e.bp))].sort()
CATALOGUE.forEach(e => { EXIDX[e.id] = e })
export const BODYPARTS = [...new Set(CATALOGUE.map(e => e.bp))].sort()
// Equipment options present in a given list of exercises, most common first (issue #6).
// Deriving them from the *already filtered* list keeps the chip row short and means
@@ -39,25 +60,78 @@ export function equipmentOf(list) {
// merged into the id index here so every EXIDX[id] lookup keeps working unchanged.
let customIds = []
export function registerCustom(list) {
customIds.forEach(id => delete EXIDX[id])
customIds.forEach(id => {
delete EXIDX[id]
const builtIn = CATALOGUE.find(ex => ex.id === id)
if (builtIn) EXIDX[id] = builtIn
})
customIds = (list || []).map(e => e.id)
;(list || []).forEach(e => { EXIDX[e.id] = e })
}
// Full searchable catalogue — customs first so your own exercises are easy to find.
export const allExercises = st => [...(st.customEx || []), ...EXDB]
export const allExercises = st => [...(st.customEx || []), ...CATALOGUE]
function searchableText(value) {
if (Array.isArray(value)) return value.map(searchableText).join(' ')
if (value == null) return ''
try { return String(value) } catch { return '' }
}
/** Case-insensitive search over built-in and legacy custom exercise metadata. */
function isSubsequence(needle, hay) {
let i = 0
for (const ch of hay) {
if (ch === needle[i]) i++
if (i === needle.length) return true
}
return false
}
// Fuzzy match score for one exercise against a query. Best hits: exact field match, then
// field prefix, then word-boundary starts, then substrings (closer to the start scores
// better), and finally typo-tolerant ordered subsequences. Fields are weighted - the name
// dominates, target/equipment matter, muscles and description are supporting evidence.
// 0 means no match, so matchesExerciseSearch stays a boolean filter while the picker can
// rank results by score.
export function searchScore(exercise, query) {
const needle = searchableText(query).toLowerCase().trim()
if (!needle) return 1
const source = exercise && typeof exercise === 'object' ? exercise : {}
const fields = [['n', 100], ['tg', 40], ['eq', 40], ['sm', 30], ['muscleGroups', 30], ['primaries', 30], ['secondaries', 30], ['desc', 10], ['cues', 10]]
// Token-level matching: every query word must match somewhere (any order), so
// "press bench" finds "Bench Press". The score sums each token's best hit.
const tokens = needle.split(/[^a-z0-9]+/).filter(Boolean)
if (!tokens.length) return 0
let total = 0
for (const token of tokens) {
let best = 0
for (const [field, weight] of fields) {
const hay = searchableText(source[field]).toLowerCase()
if (!hay) continue
if (hay === token) best = Math.max(best, weight * 4)
else if (hay.startsWith(token)) best = Math.max(best, weight * 3)
const idx = hay.indexOf(token)
if (idx > 0) best = Math.max(best, weight * 2 - Math.min(idx, 20) * 0.5)
if (hay.split(/[^a-z0-9]+/).some(w => w.startsWith(token))) best = Math.max(best, weight * 2.5)
if (isSubsequence(token, hay)) best = Math.max(best, weight + Math.max(0, 10 - (hay.length - token.length)))
}
if (!best) return 0 // every token must match
total += best
}
return total
}
export function matchesExerciseSearch(exercise, query) {
return searchScore(exercise, query) > 0
}
// Media normally sits next to the app (img/ and gif/, mounted into the web container).
// A build can point them somewhere else — the demo build pulls them off a CDN instead of
// shipping ~140 MB of images into the deployment. `import.meta.env` is undefined in plain
// Node; the guard keeps this module loadable without Vite.
// The defaults are absolute on purpose (issue #79). A bare 'img/' resolves against the
// current document's directory, so on the one two-segment route in the app, /plan/r/:id,
// every request went to /plan/r/img/… and 404'd — and nginx's extension block has no
// try_files, so it 404s rather than falling through to index.html, leaving a blank image
// and nothing in the console.
const ENV = import.meta.env || {}
const IMG_BASE = ENV.VITE_IMG_BASE || '/img/'
const GIF_BASE = ENV.VITE_GIF_BASE || '/gif/'
const IMG_BASE = ENV.VITE_IMG_BASE || 'img/'
const GIF_BASE = ENV.VITE_GIF_BASE || 'gif/'
export const imgSrc = ex => IMG_BASE + ex.img
export const gifSrc = ex => GIF_BASE + ex.gif
@@ -77,3 +151,47 @@ export const isBodyweightEq = idOrEx =>
// down on the first `ex.n`.
export const exOr = id => EXIDX[id] ||
{ id, n: t('Unknown exercise'), bp: '', tg: '', eq: '', sm: [], st: [], missing: true }
// Normalizes text by lowercasing and stripping diacritics/accents (e.g. "elevação" -> "elevacao")
export const normalizeStr = s => (s || '')
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
// Multi-token, accent-insensitive and multilingual exercise search.
// Matches when all whitespace-separated words in the query appear anywhere in the exercise's
// name, equipment, target muscle, body part (both in English and translated to active language),
// secondary muscles or description.
//
// The haystack is built once per exercise and cached: NFD-normalising ~1300 catalogue entries
// on every keystroke costs ~8ms on a desktop and several times that on a phone. The cache key
// is the i18n version (bumped by every setLang), so switching language rebuilds the translated
// terms. Custom exercises are re-cached automatically — the store clones state on update, so an
// edited exercise arrives as a new object the WeakMap has never seen.
const corpusCache = new WeakMap()
function corpusOf(e) {
const v = getVersion()
const hit = corpusCache.get(e)
if (hit && hit.v === v) return hit.s
const sm = Array.isArray(e?.sm) ? e.sm : []
const s = normalizeStr([
exerciseNameSearchText(e),
e?.tg || '', t(e?.tg || ''),
e?.eq || '', t(e?.eq || ''),
e?.bp || '', t(e?.bp || ''),
...sm, ...sm.map(m => t(m)),
e?.desc || ''
].join(' '))
corpusCache.set(e, { v, s })
return s
}
export function matchExercise(e, query) {
if (!query) return true
const tokens = normalizeStr(query).split(/\s+/).filter(Boolean)
if (!tokens.length) return true
if (!e || typeof e !== 'object') return false
const corpus = corpusOf(e)
return tokens.every(tok => corpus.includes(tok))
}
+121
View File
@@ -0,0 +1,121 @@
import { describe, it, expect } from 'vitest'
import { matchExercise, normalizeStr } from './exercises.js'
import { _setLangState } from './i18n-core.js'
describe('normalizeStr', () => {
it('handles null, undefined and empty strings', () => {
expect(normalizeStr(null)).toBe('')
expect(normalizeStr(undefined)).toBe('')
expect(normalizeStr('')).toBe('')
})
it('lowercases text and removes diacritics / accents', () => {
expect(normalizeStr('Elevação Lateral')).toBe('elevacao lateral')
expect(normalizeStr('SUPINO INCLINADO COM HALTERES')).toBe('supino inclinado com halteres')
expect(normalizeStr('Tríceps & Panturrilhas')).toBe('triceps & panturrilhas')
expect(normalizeStr('Quadríceps / Glúteos')).toBe('quadriceps / gluteos')
})
})
describe('matchExercise', () => {
const benchPress = {
id: '0025',
n: 'barbell bench press',
bp: 'chest',
tg: 'pectorals',
eq: 'barbell',
sm: ['triceps', 'deltoids'],
desc: 'Classic chest exercise using a barbell on a flat bench.'
}
const lateralRaise = {
id: '0283',
n: 'dumbbell lateral raise',
bp: 'shoulders',
tg: 'delts',
eq: 'dumbbell',
sm: ['traps'],
desc: 'Shoulder isolation movement.'
}
it('returns true for empty or whitespace-only query', () => {
expect(matchExercise(benchPress, '')).toBe(true)
expect(matchExercise(benchPress, ' ')).toBe(true)
expect(matchExercise(benchPress, null)).toBe(true)
})
it('matches exact and partial words in exercise name regardless of case', () => {
expect(matchExercise(benchPress, 'bench')).toBe(true)
expect(matchExercise(benchPress, 'BENCH')).toBe(true)
expect(matchExercise(benchPress, 'barbell')).toBe(true)
expect(matchExercise(benchPress, 'press')).toBe(true)
expect(matchExercise(benchPress, 'squat')).toBe(false)
})
it('matches multiple tokens in ANY order (not just sequential)', () => {
// "bench barbell" is reversed order compared to "barbell bench press"
expect(matchExercise(benchPress, 'bench barbell')).toBe(true)
expect(matchExercise(benchPress, 'press bench barbell')).toBe(true)
expect(matchExercise(benchPress, 'barbell press chest')).toBe(true)
expect(matchExercise(benchPress, 'bench squat')).toBe(false)
})
it('matches target muscle, equipment, secondary muscles and description', () => {
expect(matchExercise(benchPress, 'pectorals')).toBe(true)
expect(matchExercise(benchPress, 'triceps barbell')).toBe(true)
expect(matchExercise(benchPress, 'flat bench')).toBe(true)
expect(matchExercise(lateralRaise, 'dumbbell shoulder')).toBe(true)
})
it('matches accent-insensitively', () => {
const customEx = {
id: 'custom-1',
n: 'Elevação de Panturrilha',
bp: 'lower legs',
tg: 'calves',
eq: 'body weight',
desc: 'Exercício para panturrilhas em pé.'
}
expect(matchExercise(customEx, 'elevacao')).toBe(true)
expect(matchExercise(customEx, 'elevação')).toBe(true)
expect(matchExercise(customEx, 'panturrilha elevacao')).toBe(true)
expect(matchExercise(customEx, 'ELEVACAO PE')).toBe(true)
})
it('matches translated UI terms when a language is active', () => {
_setLangState('pt', {
chest: 'peito',
barbell: 'barra',
dumbbell: 'halteres',
shoulders: 'ombros'
}, null)
// "peito" is the translated bp, "barra" is the translated eq
expect(matchExercise(benchPress, 'peito')).toBe(true)
expect(matchExercise(benchPress, 'barra')).toBe(true)
expect(matchExercise(benchPress, 'peito barra bench')).toBe(true)
expect(matchExercise(lateralRaise, 'halteres ombros')).toBe(true)
})
// The pt-BR exercise-name pack (!16) renames the catalogue in the UI. Searching has to reach
// that name as well as the canonical English one, or the library goes dark for pt-BR profiles
// the moment they type what they see on screen.
it('matches the localized exercise name as well as the English one', () => {
_setLangState('pt-BR', {}, null, { '0025': 'supino reto com barra' })
expect(matchExercise(benchPress, 'supino')).toBe(true)
expect(matchExercise(benchPress, 'supino barra')).toBe(true)
expect(matchExercise(benchPress, 'bench press')).toBe(true) // English still reaches it
expect(matchExercise(lateralRaise, 'supino')).toBe(false) // untranslated entry unaffected
})
it('rebuilds the cached haystack when the language changes', () => {
_setLangState('pt-BR', {}, null, { '0025': 'supino reto com barra' })
expect(matchExercise(benchPress, 'supino')).toBe(true)
_setLangState('en', null, null, null)
expect(matchExercise(benchPress, 'supino')).toBe(false)
expect(matchExercise(benchPress, 'bench')).toBe(true)
})
})
+11
View File
@@ -12,9 +12,19 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap
if (snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot) && Object.keys(snapshot).length) {
completed.muscleSnapshot = { ...snapshot }
}
// What you typed about this exercise today, and whether you asked to see it again next
// time. Written only when there is something to keep, so an untouched entry is byte-for-byte
// the shape it always was.
const note = (entry.note || '').trim()
if (note) {
completed.note = note
if (entry.notePin) completed.notePin = true
}
return completed
}).filter(entry => entry.sets.some(set => set.done))
const sessionNote = (active?.note || '').trim()
return {
id: active.id,
d: active.d,
@@ -25,5 +35,6 @@ export function buildCompletedWorkout(active, { end = Date.now(), prs = [], snap
bw: active.bw,
entries,
prs,
...(sessionNote ? { note: sessionNote } : {}),
}
}
+33
View File
@@ -36,3 +36,36 @@ describe('completed workout boundary', () => {
})
})
})
// Notes written during a session have to survive it, or "write a note during your workout"
// means "write a note and lose it when you tap Finish".
describe('session notes', () => {
const active = (entry) => ({
id: 'w1', d: '2026-08-25', start: 1, routineId: 'r1', name: 'Push', bw: null,
entries: [{ id: '0025', sets: [{ w: 100, r: 5, done: true }], ...entry }],
})
it('keeps a per-exercise note and its pin', () => {
const w = buildCompletedWorkout(active({ note: ' narrower grip next time ', notePin: true }))
expect(w.entries[0].note).toBe('narrower grip next time')
expect(w.entries[0].notePin).toBe(true)
})
it('keeps an unpinned note without inventing a pin', () => {
const w = buildCompletedWorkout(active({ note: 'shoulder twinged' }))
expect(w.entries[0].note).toBe('shoulder twinged')
expect('notePin' in w.entries[0]).toBe(false)
})
it('writes no note fields at all when nothing was typed', () => {
const w = buildCompletedWorkout(active({ note: ' ', notePin: true }))
expect('note' in w.entries[0]).toBe(false)
expect('notePin' in w.entries[0]).toBe(false)
})
it('keeps a whole-session note on the workout', () => {
const a = active({})
expect(buildCompletedWorkout({ ...a, note: 'slept badly' }).note).toBe('slept badly')
expect('note' in buildCompletedWorkout(a)).toBe(false)
})
})
+5 -3
View File
@@ -12,9 +12,11 @@ export const DAYS = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
export const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
export const MONTHS_LONG = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
export function fmtDate(iso, long) {
export function fmtDate(iso, long, withYear = false) {
const d = new Date(iso + 'T12:00:00')
return d.toLocaleDateString(dateLocale(), long ? { weekday: 'short', day: 'numeric', month: 'short' } : { day: 'numeric', month: 'short' })
const options = long ? { weekday: 'short', day: 'numeric', month: 'short' } : { day: 'numeric', month: 'short' }
if (withYear) options.year = 'numeric'
return d.toLocaleDateString(dateLocale(), options)
}
export function fmtDur(ms) {
const m = Math.floor(ms / 60000)
@@ -44,4 +46,4 @@ export function weekKey(d) {
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)
export const ACCENTS = { lime: '#30d158', sky: '#0a84ff', orange: '#ff9f0a', violet: '#bf5af2', pink: '#ff375f', red: '#ff453a', teal: '#40c8e0', gold: '#ffd60a' }
export const ACCENTS = { lime: '#30d158', sky: '#0a84ff', orange: '#ff9f0a', violet: '#bf5af2', pink: '#ff375f', red: '#ff453a', teal: '#40c8e0', gold: '#ffd60a' }
+183 -10
View File
@@ -1,7 +1,7 @@
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
import { isCardio, isBodyweightEq } from './exercises.js'
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode } from './workout-model.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 : {}
// Completed-state-independent work rows whose authoritative mode matches the requested mode.
const workRowsForMode = (entry = {}, mode = 'reps') => {
@@ -209,14 +209,49 @@ export function unpairSuperset(items, idx) {
export function lastEntryFor(S, exId) {
for (let i = S.workouts.length - 1; i >= 0; i--) {
const en = S.workouts[i].entries.find(e => e.id === exId)
if (!en) continue
// Work sets only. Every caller asks the same question — "what did you actually lift last
// time" — to seed the next session's rows, to size a freestyle config, and to print "Last
// time" on the card. A warm-up answers none of them: seeding position 0 from a 50% ramp row
// walks the working weight DOWN a little every session, and counting the ramp rows makes a
// 3x5 come back as a 5-set exercise. Warm-ups are already excluded from volume, records and
// progression; this is the same rule one level up.
const done = en.sets.filter(s => s.done && !isWarmupRow(s))
// `target` is what the session prescribed; finished workouts carry it so labels and the
// progression engine can read a session back the way it was logged. Older workouts have
// none — modeOf() falls back to the body part for them, which is what they were.
if (en && en.sets.some(s => s.done)) return { d: S.workouts[i].d, sets: en.sets.filter(s => s.done), target: en.target || null }
if (done.length) return { d: S.workouts[i].d, sets: done, target: en.target || null }
}
return null
}
/** How long any single note may get. Long enough for a paragraph, short enough to stay a note. */
export const NOTE_MAX = 500
/**
* The most recent session note the user pinned for this exercise, or null.
*
* A note written mid-session is about that session — "shoulder twinged today". Some of them are
* about the NEXT one instead: "go a notch narrower". The pin is how the user says which, at the
* moment of writing, when they are the only one who knows. Pinned notes surface again the next
* time the exercise comes up; unpinned ones stay in that day's history.
*
* Only the newest pinned note is returned: a pin is a message to your next self, and a stack of
* them from six sessions ago is noise, not context.
*/
export function pinnedNoteFor(S, exId) {
const workouts = S?.workouts || []
for (let i = workouts.length - 1; i >= 0; i--) {
const en = (workouts[i].entries || []).find(e => e.id === exId)
const note = (en?.note || '').trim()
if (note && en.notePin) return { note, d: workouts[i].d }
}
return null
}
/** The standing note for an exercise — the one that is true every session. */
export const exNoteFor = (S, exId) => ((S?.exNotes || {})[exId] || '').trim() || null
// A freestyle exercise starts with the last target the user actually trained, rather than the
// generic config sheet defaults used when there is no history. The set rows themselves are still
// built by buildSets(), which copies each completed set by position; only the target shape and
@@ -268,7 +303,30 @@ export function nextTrainingDay(S, iso) {
}
return null
}
/**
* Build the rows a planned exercise starts a session with: its work sets, preceded by however
* many warm-up sets the routine asks for (`cfg.warmupSets`, 0 by default so an existing plan
* behaves exactly as before).
*
* The warm-ups are stacked with insertWarmupRow, one call each, so the ramp is the same one
* the in-session "Add warm-up set" button produces: each row halves the gap left to the work
* weight, giving 50% / 75% / 87.5% for three. `options.step` is the exercise's loading step,
* passed in by the caller (see insertWarmupRow for why this module cannot read it itself).
*/
export function buildSets(S, cfg, options = {}) {
const rows = buildWorkSets(S, cfg, options)
const warm = Math.max(0, Math.min(MAX_PLANNED_WARMUPS, Math.round(cfg.warmupSets) || 0))
if (!warm) return rows
const mode = modeOf(cfg)
let out = rows
for (let i = 0; i < warm; i++) out = insertWarmupRow(out, mode, cfg, options.step)
return out
}
/** Beyond this a "warm-up" is its own workout; the config stepper stops here too. */
export const MAX_PLANNED_WARMUPS = 5
function buildWorkSets(S, cfg, options = {}) {
const last = lastEntryFor(S, cfg.id)
const n = Math.max(1, cfg.sets || 1)
const mode = modeOf(cfg)
@@ -305,11 +363,58 @@ export function buildSets(S, cfg, options = {}) {
}
return sets
}
/**
* Stamp every work row with the exercise's planned intensifier and pre-fill its drops/clusters,
* already computed and editable — the plan designs the set, not a button pressed mid-workout.
*
* Must run AFTER applyPrescription: a drop-set's chain of drops is a percentage of each row's
* own `w`, so it has to be computed from the final prescribed weight, not the pre-progression
* one buildSets started from — otherwise a bumped working weight would leave stale, cheaper
* drops sitting underneath it.
*/
export function applyIntensifierPlan(sets, cfg) {
const kind = cfg && cfg.intensifier && cfg.intensifier.type
if (kind !== 'dropset' && kind !== 'restpause') return sets
if (kind === 'dropset') {
const count = Math.max(1, Math.round(cfg.intensifier.count) || 1)
const pct = cfg.intensifier.pct
return sets.map(s => {
if (isWarmupRow(s)) return s
const drops = []
let w = s.w || 0
for (let k = 0; k < count; k++) { w = nextDropWeight(w, pct); drops.push({ w, r: s.r }) }
return { ...s, type: 'dropset', drops }
})
}
// Rest-pause trains as exactly two sets, not one per configured `sets` count: a warm-up at
// the exercise's own configured reps, then a single rest-pause work set. Doing the full
// activation+bursts protocol several times over isn't how rest-pause is actually trained, so
// planning it replaces whatever buildSets built rather than stamping each of those rows.
// The work row's own reps are the total — not "the total minus what the bursts carry" — and
// the bursts are the full breakdown of that same total, down to the last one. See
// extraVolumeOf/setTonnage: a rest-pause row's `clusters` are read-only display of how `r`
// breaks down, not extra volume on top of it, precisely so this doesn't double-count.
const restSec = Math.max(5, cfg.intensifier.restSec || 15)
const totalReps = Math.max(1, Math.round(cfg.intensifier.totalReps) || 1)
const w = (sets.find(s => !isWarmupRow(s)) || sets[0] || {}).w || 0
const warmup = { w, r: Math.max(1, Math.round(cfg.reps) || 1), done: false, phase: 'warmup' }
const work = { w, r: totalReps, done: false, type: 'restpause', clusters: splitBurstReps(totalReps).map(r => ({ r, restSec })) }
return [warmup, work]
}
export function workoutVolume(w) {
let v = 0
// No special case for unilateral work: a per-side set logs its total, so both sides are
// already in the rep count that arrives here.
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) v += (s.w || 0) * (s.r || 0) }))
// already in the rep count that arrives here. Drop-set drops and rest-pause bursts add their
// own weight x reps on top of the row's main/activation set (see extraVolumeOf).
// Warm-ups are excluded here as everywhere else. The config sheet promises it in so many
// words ("left out of volume, records and progression") and every other consumer already
// does it; this line was the one that did not, which only stopped being harmless when a
// routine started planning warm-ups by default. The number is written into the saved
// workout, so an inflated one would stay wrong forever.
w.entries.forEach(e => e.sets.forEach(s => {
if (s.done && !isWarmupRow(s)) v += (s.w || 0) * (s.r || 0) + extraVolumeOf(s)
}))
return v
}
export function setsDone(w) {
@@ -367,16 +472,84 @@ export function cascadeWeight(rows, from, value) {
return next
}
/** Insert a warm-up row before the first work row, copying the preceding warm-up's values. */
export function insertWarmupRow(rows, mode, target) {
/**
* Insert a warm-up row at the end of the warm-up block, ramping toward the working weight.
*
* Each added row halves what is left between the last warm-up and the first work set, so the
* first one lands at half the working weight, a second at three quarters, and so on — and a
* row you edited by hand is what the next one ramps from. `step` is the exercise's own loading
* step (progression.js's defaultIncrement, passed in by the caller so this module keeps no
* dependency on progression — that one already imports from here): a warm-up you cannot
* actually load onto the bar is noise.
*
* The reference is the first WORK row, never `rows[at - 1]` alone: for the first warm-up
* `at` is 0, and reading `rows[-1]` used to fall through to the *last* row — the heaviest
* work set — so "add warm-up set" handed you a full-weight set to correct by hand.
*/
/**
* Recompute the warm-up block so it ramps toward the weight the work rows ACTUALLY carry.
*
* buildSets prepends the warm-ups before a prescription is applied, and applyPrescription
* deliberately rewrites work rows only — so without this the ramp still aims at last
* session's weight. On a deload that put the last warm-up above every work set, which is
* the exact opposite of what a warm-up is for.
*
* A warm-up already logged keeps its weight and becomes what the next one ramps from: it
* happened, and rewriting performed work is data loss. Entries with nothing to ramp toward
* — cardio, bodyweight, an unloaded hold — are returned untouched.
*/
export function rerampWarmups(rows, step = 2.5) {
const firstWork = rows.findIndex(x => !isWarmupRow(x))
if (firstWork <= 0) return rows
const target = rows[firstWork].w || 0
if (!(target > 0)) return rows
const out = rows.slice()
let from = 0
for (let i = 0; i < firstWork; i++) {
if (out[i].done) { from = out[i].w || 0; continue }
const w = target > from
? Math.max(0, Math.min(target, Math.floor((from + (target - from) / 2) / step) * step))
: target
out[i] = { ...out[i], w }
from = w
}
return out
}
export function insertWarmupRow(rows, mode, target, step = 2.5) {
const firstWork = rows.findIndex(x => !isWarmupRow(x))
const at = firstWork === -1 ? rows.length : firstWork
const l = rows[at - 1] || rows[rows.length - 1]
const prev = at > 0 ? rows[at - 1] : null // the warm-up this one ramps from
const work = firstWork === -1 ? null : rows[firstWork]
const rampTo = to => {
const from = prev ? (prev.w || 0) : 0
// Nothing to ramp toward: bodyweight, cardio, a timed hold with no load.
if (!(to > 0)) return 0
// Already at or past the work weight — which happens when a warm-up was edited by hand
// above it. Returning `from` here handed the next warm-up that same too-heavy number and
// let it propagate down the block. A warm-up is never heavier than the set it warms up for.
if (to <= from) return to
// Rounded DOWN to the step: a warm-up that lands a notch light costs nothing, one that
// lands a notch heavy is a set you have to strip plates off before you can use it.
return Math.max(0, Math.min(to, Math.floor((from + (to - from) / 2) / step) * step))
}
const warm = mode === 'cardio'
? { min: l ? l.min : (target.min || 20), speed: l ? l.speed : (target.speed || 8), done: false, phase: 'warmup', warmup: true }
? {
min: prev ? prev.min : (work ? work.min : (target.min || 20)),
speed: prev ? prev.speed : (work ? work.speed : (target.speed || 8)),
done: false, phase: 'warmup', warmup: true,
}
: mode === 'time'
? { sec: l ? l.sec : (target.sec || 45), w: l ? (l.w || 0) : (target.weight || 0), done: false, phase: 'warmup', warmup: true }
: { w: l ? l.w : 0, r: l ? l.r : target.reps, done: false, phase: 'warmup', warmup: true }
? {
sec: prev ? prev.sec : (work ? work.sec : (target.sec || 45)),
w: rampTo(work ? (work.w || 0) : (target.weight || 0)),
done: false, phase: 'warmup', warmup: true,
}
: {
w: rampTo(work ? (work.w || 0) : (target.weight || 0)),
r: work ? work.r : (prev ? prev.r : target.reps),
done: false, phase: 'warmup', warmup: true,
}
const next = rows.slice()
next.splice(at, 0, warm)
return next
+165 -4
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'
import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from './history.js'
import { EXDB } from './exercises.js'
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
@@ -365,6 +365,42 @@ describe('freestyleConfig', () => {
])
})
// Planned warm-ups: the routine says how many, buildSets stacks them onto the work sets with
// the same ramp the in-session button uses. A plan without the field must not change shape.
it('adds no rows when the config asks for no warm-ups', () => {
const S = { exWeights: {}, workouts: [] }
const cfg = { id: '0025', mode: 'reps', sets: 2, reps: 5, weight: 100 }
expect(buildSets(S, cfg)).toEqual([
{ w: 100, r: 5, done: false },
{ w: 100, r: 5, done: false },
])
})
it('prepends the planned warm-ups as a ramp toward the work weight', () => {
const S = { exWeights: {}, workouts: [] }
const cfg = { id: '0025', mode: 'reps', sets: 2, reps: 5, weight: 100, warmupSets: 3 }
const rows = buildSets(S, cfg, { step: 2.5 })
expect(rows.map(r => r.w)).toEqual([50, 75, 87.5, 100, 100])
expect(rows.slice(0, 3).every(r => r.phase === 'warmup')).toBe(true)
expect(rows.slice(3).every(r => r.phase === undefined)).toBe(true)
})
it('caps the planned warm-ups and ignores nonsense values', () => {
const S = { exWeights: {}, workouts: [] }
const base = { id: '0025', mode: 'reps', sets: 1, reps: 5, weight: 100 }
expect(buildSets(S, { ...base, warmupSets: 99 }, { step: 2.5 }).filter(r => r.phase === 'warmup')).toHaveLength(5)
expect(buildSets(S, { ...base, warmupSets: -2 }, { step: 2.5 })).toHaveLength(1)
expect(buildSets(S, { ...base, warmupSets: 'x' }, { step: 2.5 })).toHaveLength(1)
})
it('keeps planned warm-ups out of the work-set count', () => {
const S = { exWeights: {}, workouts: [] }
const rows = buildSets(S, { id: '0025', mode: 'reps', sets: 3, reps: 5, weight: 100, warmupSets: 2 }, { step: 2.5 })
const logged = { entries: [{ id: '0025', sets: rows.map(r => ({ ...r, done: true })) }] }
expect(logged.entries[0].sets).toHaveLength(5)
expect(workSetsDone(logged)).toBe(3)
})
it('inherits the target for timed and cardio exercises too', () => {
const timed = {
exWeights: {},
@@ -456,6 +492,55 @@ describe('buildSets', () => {
expect(buildSets(S, { id: LIFT, sets: 2, reps: 8, weight: 50 }, { preferLast: true }))
.toEqual([{ w: 60, r: 10, done: false }, { w: 62.5, r: 8, done: false }])
})
})
describe('applyIntensifierPlan', () => {
it('pre-fills every work row with a chain of drops, each pct% lighter than the one before', () => {
const sets = [{ w: 100, r: 8, done: false }, { w: 100, r: 8, done: false }]
const out = applyIntensifierPlan(sets, { intensifier: { type: 'dropset', count: 2, pct: 20 } })
expect(out).toEqual([
{ w: 100, r: 8, done: false, type: 'dropset', drops: [{ w: 80, r: 8 }, { w: 64, r: 8 }] },
{ w: 100, r: 8, done: false, type: 'dropset', drops: [{ w: 80, r: 8 }, { w: 64, r: 8 }] },
])
})
it('collapses rest-pause to exactly two rows regardless of how many sets were configured: a warm-up at the exercise\'s own reps, then one work set whose own reps ARE the total', () => {
const sets = [{ w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }]
const out = applyIntensifierPlan(sets, { reps: 8, intensifier: { type: 'restpause', totalReps: 12, restSec: 15 } })
expect(out).toEqual([
{ w: 60, r: 8, done: false, phase: 'warmup' },
{ w: 60, r: 12, done: false, type: 'restpause', clusters: [{ r: 6, restSec: 15 }, { r: 3, restSec: 15 }, { r: 2, restSec: 15 }, { r: 1, restSec: 15 }] },
])
// the full breakdown always sums back to the row's own r — no reps missing, none double-counted
expect(out[1].clusters.reduce((sum, c) => sum + c.r, 0)).toBe(out[1].r)
})
it('the warm-up reps come from the exercise\'s own configured reps, not the rest-pause total', () => {
const sets = [{ w: 60, r: 8, done: false }]
const out = applyIntensifierPlan(sets, { reps: 5, intensifier: { type: 'restpause', totalReps: 20, restSec: 15 } })
expect(out[0]).toEqual({ w: 60, r: 5, done: false, phase: 'warmup' })
})
it('carries the prescribed weight from the built sets onto both new rows', () => {
const sets = [{ w: 82.5, r: 8, done: false }]
const out = applyIntensifierPlan(sets, { reps: 8, intensifier: { type: 'restpause', totalReps: 4, restSec: 15 } })
expect(out[0].w).toBe(82.5)
expect(out[1].w).toBe(82.5)
})
it('never touches a warm-up row', () => {
const sets = [{ w: 20, r: 8, done: false, phase: 'warmup' }, { w: 100, r: 8, done: false }]
const out = applyIntensifierPlan(sets, { intensifier: { type: 'dropset', count: 1, pct: 20 } })
expect(out[0]).toEqual({ w: 20, r: 8, done: false, phase: 'warmup' })
expect(out[1].type).toBe('dropset')
})
it('leaves sets untouched with no intensifier configured', () => {
const sets = [{ w: 100, r: 8, done: false }]
expect(applyIntensifierPlan(sets, {})).toBe(sets)
expect(applyIntensifierPlan(sets, { intensifier: { type: 'nonsense' } })).toBe(sets)
})
})
describe('workoutVolume', () => {
@@ -473,6 +558,21 @@ describe('workoutVolume', () => {
expect(workoutVolume(w)).toBe(320)
})
it('adds drop-set drops on top of the row\'s main set', () => {
const dropRow = { type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
expect(workoutVolume({ entries: [{ id: LIFT, sets: [dropRow] }] })).toBe(100 * 5 + 80 * 5 + 60 * 5)
})
it('counts a rest-pause row once — its own r is already the total across every burst', () => {
const burstRow = { type: 'restpause', w: 60, r: 20, done: true, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] }
expect(workoutVolume({ entries: [{ id: LIFT, sets: [burstRow] }] })).toBe(60 * 20)
})
it('ignores drops/bursts on a row that was never checked off', () => {
const dropRow = { type: 'dropset', w: 100, r: 5, done: false, drops: [{ w: 80, r: 5 }] }
expect(workoutVolume({ entries: [{ id: LIFT, sets: [dropRow] }] })).toBe(0)
})
it('leaves an unloaded bodyweight set at zero volume rather than inventing a number', () => {
const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] }
expect(workoutVolume(w)).toBe(0)
@@ -641,19 +741,48 @@ describe('session row helpers', () => {
expect('w' in next[2]).toBe(false)
})
it('insertWarmupRow inserts before the first work row and copies the last warm-up values', () => {
it('insertWarmupRow inserts before the first work row, ramping toward the work weight', () => {
const rows = [
{ warmup: true, w: 20, r: 8, done: true },
{ warmup: true, w: 30, r: 8, done: false },
{ w: 60, r: 8, done: false },
]
const next = insertWarmupRow(rows, 'reps', { reps: 8 })
const next = insertWarmupRow(rows, 'reps', { reps: 8 }, 2.5)
expect(next.length).toBe(4)
expect(next[2].warmup).toBe(true)
expect(next[2].w).toBe(30) // copies the preceding warm-up
expect(next[2].w).toBe(45) // halfway from the last warm-up (30) to the work set (60)
expect(next[3].w).toBe(60) // work row still after the warm-up block
})
// The first warm-up is the case that was broken: `at` is 0, so the old code read rows[-1],
// fell through to `rows[rows.length - 1]` — the heaviest work set — and handed you a
// "warm-up" at your full working weight.
it('gives the first warm-up half the working weight, not the working weight itself', () => {
const next = insertWarmupRow([{ w: 100, r: 5, done: false }], 'reps', { reps: 5 }, 2.5)
expect(next.length).toBe(2)
expect(next[0]).toMatchObject({ w: 50, r: 5, phase: 'warmup', warmup: true, done: false })
expect(next[1].w).toBe(100)
})
it('rounds the ramp to the exercise loading step', () => {
// 0 -> 95 halves to 47.5, which is not loadable in 5 kg steps: 45 is.
expect(insertWarmupRow([{ w: 95, r: 5 }], 'reps', { reps: 5 }, 5)[0].w).toBe(45)
})
it('keeps bodyweight warm-ups at zero and never exceeds the work set', () => {
expect(insertWarmupRow([{ w: 0, r: 12 }], 'reps', { reps: 12 }, 2.5)[0].w).toBe(0)
// A warm-up already at the working weight cannot ramp any further.
const at100 = insertWarmupRow([{ warmup: true, w: 100, r: 5 }, { w: 100, r: 5 }], 'reps', { reps: 5 }, 2.5)
expect(at100[1].w).toBe(100)
})
it('ramps a timed hold the same way and leaves cardio on the work row values', () => {
expect(insertWarmupRow([{ sec: 45, w: 40, done: false }], 'time', { sec: 45 }, 2.5)[0])
.toMatchObject({ sec: 45, w: 20, phase: 'warmup' })
expect(insertWarmupRow([{ min: 20, speed: 10, done: false }], 'cardio', { min: 20 }, 2.5)[0])
.toMatchObject({ min: 20, speed: 10, phase: 'warmup' })
})
it('removeRowAt never empties an entry below one row', () => {
expect(removeRowAt([{ w: 60 }], 0).length).toBe(1)
const rows = [{ w: 60 }, { w: 70 }]
@@ -734,3 +863,35 @@ describe('nextTrainingDay', () => {
expect(nextTrainingDay(off, TUE)).toMatchObject({ weekday: 5 })
})
})
describe('pinnedNoteFor', () => {
const S = {
workouts: [
{ d: '2026-08-01', entries: [{ id: '0025', note: 'felt heavy', notePin: true }] },
{ d: '2026-08-08', entries: [{ id: '0025', note: 'just a diary line' }] },
{ d: '2026-08-15', entries: [{ id: '0025', note: 'go narrower', notePin: true }] },
{ d: '2026-08-22', entries: [{ id: '0293', note: 'other exercise', notePin: true }] },
],
}
it('returns only the newest pinned note for that exercise', () => {
expect(pinnedNoteFor(S, '0025')).toEqual({ note: 'go narrower', d: '2026-08-15' })
})
it('ignores notes that were not pinned', () => {
expect(pinnedNoteFor({ workouts: [{ d: '2026-08-08', entries: [{ id: '0025', note: 'diary' }] }] }, '0025')).toBeNull()
})
it('is null for an exercise with no notes, and safe on empty state', () => {
expect(pinnedNoteFor(S, '9999')).toBeNull()
expect(pinnedNoteFor({}, '0025')).toBeNull()
})
})
describe('exNoteFor', () => {
it('reads the standing note and trims it away when blank', () => {
expect(exNoteFor({ exNotes: { '0025': ' seat 4, pin 7 ' } }, '0025')).toBe('seat 4, pin 7')
expect(exNoteFor({ exNotes: { '0025': ' ' } }, '0025')).toBeNull()
expect(exNoteFor({}, '0025')).toBeNull()
})
})
+29 -6
View File
@@ -1,21 +1,25 @@
// Runtime-agnostic core of the i18n module: state, constants and readers (t, dateLocale,
// instrFor, getLang). Plain Node-loadable — the browser-only pieces (import.meta.glob lazy
// instrFor, exerciseNameFor, getLang). Plain Node-loadable — the browser-only pieces
// (import.meta.glob lazy
// loads, the React subscription hook) live in i18n.js and re-export from here.
export const LANGS = {
en: 'English', de: 'Deutsch', es: 'Español', fr: 'Français', it: 'Italiano',
pt: 'Português', pl: 'Polski', tr: 'Türkçe', ru: 'Русский', zh: '中文',
pt: 'Português (Portugal)', 'pt-BR': 'Português (Brasil)', pl: 'Polski',
tr: 'Türkçe', ru: 'Русский', zh: '中文',
ko: '한국어', hi: 'हिन्दी'
}
export const INSTR_LANGS = ['en', 'es', 'fr', 'it', 'tr', 'ru', 'zh', 'hi', 'pl', 'ko']
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 DATE_LOCALES = {
en: 'en-GB', de: 'de-DE', es: 'es-ES', fr: 'fr-FR', it: 'it-IT', pt: 'pt-PT',
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'
}
let lang = 'en' // set only by _setLangState, called from i18n.js setLang
let dict = {} // current locale pack (empty = English fallback)
let instr = null // { exId: [steps] } for the current language, null = English
let exerciseNames = null // { exId: translated name }, null = original catalogue name
let version = 0 // bumped on every setLang; drives the React subscription selector
export const getLang = () => lang
@@ -32,13 +36,32 @@ export function t(s, ...args) {
// Instructions for an exercise in the current language (English steps as fallback).
export const instrFor = ex => (instr && instr[ex.id]) || ex.st || []
// Built-in catalogue names are bilingual when a complete translated name pack is active.
// User-created exercises have no entry in the pack and keep their exact chosen name.
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')
? translated
: `${translated} (${ex.n})`
}
// Search both the localized and canonical English title without changing persisted data.
export const exerciseNameSearchText = ex => {
const translated = exerciseNames && ex && exerciseNames[ex.id]
return translated ? `${translated} ${ex.n}` : (ex?.n || '')
}
// Called by i18n.js's setLang once the locale pack has been loaded — kept here rather than
// exported as setLang because loading packs requires import.meta.glob, which is Vite-only.
// Both `dict` and `instr` may be null to reset to English.
export function _setLangState(newLang, newDict, newInstr) {
// `dict`, `instr` and `exerciseNames` may be null to reset to their English fallbacks.
export function _setLangState(newLang, newDict, newInstr, newExerciseNames) {
lang = LANGS[newLang] ? newLang : 'en'
dict = lang === 'en' ? {} : (newDict || {})
instr = lang === 'en' || !INSTR_LANGS.includes(lang) ? null : (newInstr || null)
exerciseNames = lang === 'en' || !EXERCISE_NAME_LANGS.includes(lang) ? null : (newExerciseNames || null)
version++
return version
}
+17 -10
View File
@@ -5,16 +5,20 @@
import { useSyncExternalStore } from 'react'
import {
LANGS, INSTR_LANGS, DATE_LOCALES,
getLang, dateLocale, t, instrFor, getVersion, _setLangState
LANGS, INSTR_LANGS, EXERCISE_NAME_LANGS, DATE_LOCALES,
getLang, dateLocale, t, instrFor, exerciseNameFor, exerciseNameSearchText, getVersion, _setLangState
} from './i18n-core.js'
export { LANGS, INSTR_LANGS, DATE_LOCALES, getLang, dateLocale, t, instrFor }
export {
LANGS, INSTR_LANGS, EXERCISE_NAME_LANGS, DATE_LOCALES,
getLang, dateLocale, t, instrFor, exerciseNameFor, exerciseNameSearchText
}
// Vite code-splits each locale pack into its own chunk via import.meta.glob; instructions use
// the same mechanism in src/instr/. Both are lazy, so the production bundle ships English only.
// Vite code-splits locale, instruction and exercise-name packs via import.meta.glob. They are
// lazy, so the production bundle ships English only until another language is selected.
const localePacks = import.meta.glob('../locales/*.js')
const instrPacks = import.meta.glob('../instr/*.js')
const exerciseNamePacks = import.meta.glob('../exercise-names/*.js')
// React subscription bookkeeping — kept here, not in core, so core has zero React coupling.
const subs = new Set()
@@ -23,12 +27,15 @@ const notify = () => { subs.forEach(f => f()) }
export async function setLang(l) {
if (!LANGS[l]) l = 'en'
if (l === getLang() && getVersion() > 0) return
let dict = {}, instr = null
let dict = {}, instr = null, exerciseNames = null
try { dict = l === 'en' ? {} : (await localePacks['../locales/' + l + '.js']()).default } catch (e) { dict = {} }
try { instr = l === 'en' || !INSTR_LANGS.includes(l) ? null : (await instrPacks['../instr/' + l + '.js']()).default } catch (e) { instr = null }
try {
dict = l === 'en' ? {} : (await localePacks['../locales/' + l + '.js']()).default
instr = l === 'en' || !INSTR_LANGS.includes(l) ? null : (await instrPacks['../instr/' + l + '.js']()).default
} catch (e) { dict = {}; instr = null }
_setLangState(l, dict, instr)
exerciseNames = l === 'en' || !EXERCISE_NAME_LANGS.includes(l)
? null
: (await exerciseNamePacks['../exercise-names/' + l + '.js']()).default
} catch (e) { exerciseNames = null }
_setLangState(l, dict, instr, exerciseNames)
notify()
}
+47 -8
View File
@@ -58,9 +58,9 @@ const norm = h => h.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()
const COLUMNS = [
['exercise', ['exercise', 'exercise name', 'exercise title']],
['date', ['date', 'workout date']],
['startTime', ['start time']],
['startTime', ['start time', 'start date']],
['endTime', ['end time']],
['workoutName', ['workout name', 'title']],
['workoutName', ['workout name', 'title', 'workout']],
['category', ['category', 'body part', 'muscle group']],
['weightKg', ['weight kg']],
['weightLb', ['weight lbs', 'weight lb']],
@@ -74,10 +74,10 @@ const COLUMNS = [
['distanceKm', ['distance km']],
['distance', ['distance']],
['distanceUnit', ['distance unit']],
['seconds', ['seconds', 'duration seconds']],
['seconds', ['seconds', 'duration seconds', 'set duration sec']],
['time', ['time', 'duration']],
['setType', ['set type']],
['note', ['comment', 'comments', 'notes', 'note']],
['note', ['comment', 'comments', 'notes', 'note', 'workout notes']],
]
function mapHeader(header) {
@@ -111,7 +111,9 @@ export function detectSource(header) {
const SYN = [
[/\bbb\b/g, 'barbell'], [/\bdb\b/g, 'dumbbell'], [/\bkb\b/g, 'kettlebell'],
[/\bohp\b/g, 'overhead press'], [/\bbw\b/g, 'body weight'], [/\bbodyweight\b/g, 'body weight'],
[/\bmachine\b/g, 'lever'], [/\bsmith machine\b/g, 'smith'], [/\bez bar\b/g, 'ez barbell'],
// 'smith machine' first: the generic machine->lever rule would otherwise eat the word
// and leave 'smith lever', which matches no entry in the dataset.
[/\bsmith machine\b/g, 'smith'], [/\bmachine\b/g, 'lever'], [/\bez bar\b/g, 'ez barbell'],
[/\bpull ups?\b/g, 'pull up'], [/\bchin ups?\b/g, 'chin up'], [/\bpush ups?\b/g, 'push up'],
[/\bsit ups?\b/g, 'sit up'], [/\bdips?\b/g, 'dip'], [/\braises?\b/g, 'raise'],
[/\bcurls?\b/g, 'curl'], [/\bpresses\b/g, 'press'], [/\bextensions?\b/g, 'extension'],
@@ -185,6 +187,25 @@ const ALIAS_EX = {
// same movement, wrong equipment label, which beats leaving it uncategorised.
'pallof press': '0979', 'cable pallof press': '0979', 'vertical pallof press': '1015',
'cable core pallof press': '0979', 'core pallof press': '0979',
// Hevy's own vocabulary, from a real export. Hevy writes the equipment in parentheses
// and uses "bicep"/"chest fly"/"reverse fly" where the dataset says "biceps"/"fly"/
// "reverse fly", so these are near-misses the word-bag cannot close on its own.
'bicep curl (dumbbell)': '0294', 'bicep curl (cable)': '0868', 'bicep curl (barbell)': '0031',
'chest fly (dumbbell)': '0308', 'chest fly (machine)': '0596', 'butterfly (pec deck)': '0596',
'incline chest fly (dumbbell)': '0319', 'cable fly crossovers': '1269',
'rear delt reverse fly (dumbbell)': '0383', 'rear delt reverse fly (machine)': '0602',
'chest supported reverse fly (dumbbell)': '0383',
'bench press (smith machine)': '0748', 'overhead press (smith machine)': '0766',
'hack squat (machine)': '0743', 'iso-lateral row (machine)': '0571',
'seated cable row - bar grip': '0218', 'reverse grip lat pulldown (cable)': '0673',
'single arm lateral raise (cable)': '0192', 'plate front raise': '0310',
'back extension (weighted hyperextension)': '0573',
'behind the back bicep wrist curl (barbell)': '0104',
// A face pull is a rope rear-delt row; the dataset has no entry under that name.
'face pull': '0203',
// Cardio again: the only candidates in a 29-entry cardio vocabulary.
'jumping jack': '3220', 'jumping jacks': '3220', 'battle ropes': '0128',
'stair machine (steps)': '2311', 'stair machine': '2311',
}
let ALIAS_IDX = null
@@ -230,6 +251,23 @@ export function matchExercise(name) {
return ties === 1 ? best : 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.
const NAME_BP = [
[/\b(curl|bicep|biceps|tricep|triceps|skullcrusher|pushdown)\b/, 'upper arms'],
[/\b(wrist|forearm|forearms|grip)\b/, 'lower arms'],
[/\b(bench|chest|pec|fly|flye|crossover|crossovers|dip)\b/, 'chest'],
[/\b(row|pulldown|pullup|pull up|chin up|lat|lats|back|deadlift|shrug)\b/, 'back'],
[/\b(shoulder|delt|delts|overhead|lateral raise|front raise|face pull|press up)\b/, 'shoulders'],
[/\b(calf|calves)\b/, 'lower legs'],
[/\b(squat|lunge|leg|glute|hamstring|quad|hip thrust|deadlift)\b/, 'upper legs'],
[/\b(ab|abs|core|plank|crunch|sit up|oblique|russian twist)\b/, 'waist'],
[/\b(run|running|jog|bike|cycling|rope|ropes|jump|jacks|burpee|sprint|treadmill|stair)\b/, 'cardio'],
[/\bneck\b/, 'neck'],
]
const bpFromName = name => (NAME_BP.find(([re]) => re.test(name)) || [])[1] || null
// Categories the exporters use -> the dataset's body parts, for exercises we invent.
const CATEGORY_BP = {
chest: 'chest', back: 'back', lats: 'back', shoulders: 'shoulders', delts: 'shoulders',
@@ -258,10 +296,10 @@ const LB_TO_KG = 0.45359237
const p2 = n => String(n).padStart(2, '0')
const MON = { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 }
/** "2020-12-30 18:51:52" · "2024-03-07" · "22 Dec 2025, 08:00" · "07/03/2024" -> { d, t } */
/** "2020-12-30 18:51:52" · "2024-03-07" · "2024/03/07" · "2024.03.07" · "22 Dec 2025, 08:00" · "07/03/2024" -> { d, t } */
export function parseWhen(s) {
const v = String(s || '').trim()
let m = v.match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[T ](\d{1,2}):(\d{2}))?/)
let m = v.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})(?:[T ](\d{1,2}):(\d{2}))?/)
if (m) return { d: `${m[1]}-${p2(m[2])}-${p2(m[3])}`, t: hm(m[4], m[5]) }
m = v.match(/^(\d{1,2})\s+([A-Za-z]{3})[a-z]*\.?\s+(\d{4})(?:,?\s+(\d{1,2}):(\d{2}))?/)
if (m && MON[m[2].toLowerCase()]) return { d: `${m[3]}-${p2(MON[m[2].toLowerCase()])}-${p2(m[1])}`, t: hm(m[4], m[5]) }
@@ -358,7 +396,8 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) {
if (!c) {
c = {
id: 'im' + uid(), n: name.toLowerCase(), custom: true, eq: 'custom', tg: '', desc: '',
bp: CATEGORY_BP[cell(r, 'category').toLowerCase()] || (km || (mins && !reps) ? 'cardio' : 'upper legs'),
bp: CATEGORY_BP[cell(r, 'category').toLowerCase()] || (km || (mins && !reps) ? 'cardio' : null)
|| bpFromName(name.toLowerCase()) || 'upper legs',
}
created.set(key, c)
unmatched.add(name)
+33 -3
View File
@@ -4,7 +4,9 @@ import { parseWorkoutCSV } from './import-csv.js'
const CSV = [
'Date,Exercise,Weight,Reps,Set Type',
'2026-08-08,Bench Press,100,5,Warm-up',
'2026-08-08,Bench Press,80,5,Working',
'2026.08.08,Bench Press,80,5,Working',
'8 Aug 2026,Bench Press,80,5,Working',
'2026/08/08,Bench Press,85,3,Working',
].join('\n')
describe('CSV warm-up provenance', () => {
@@ -16,7 +18,35 @@ describe('CSV warm-up provenance', () => {
expect(entry.sets).toEqual([
{ w: 100, r: 5, done: true, phase: 'warmup' },
{ w: 80, r: 5, done: true },
{ w: 80, r: 5, done: true },
{ w: 85, r: 3, done: true },
])
expect(entry.topW).toBe(80)
expect(entry.topW).toBe(85)
})
})
})
// gravl writes its units in parentheses ("Weight (kg)", "Set Duration (sec)"). Header text is
// normalised before it is matched, so the alias table has to hold the normalised form — an alias
// written with the parentheses can never match. Sample rows are from the gravl export in !21.
const GRAVL = [
'Date,Start Date,Workout,Source,Workout Duration (min),Energy,Exercise,Superset,Set,Set Type,Reps,Weight (kg),Distance (km),Set Duration (sec),Incline,Steps,Effort,Workout Notes',
'2026/01/01,1:11 PM,Push Day,,11,11,Chin Up,No,1,Normal,11,11,0,,,,Ideal,felt strong',
'2026/01/22,2:22 PM,External Something,APP,21,22,Walking,No,0,Normal,0,0,0,22,,,,',
].join('\n')
describe('gravl export', () => {
it('reads slash dates, parenthesised weight and per-set duration', () => {
const parsed = parseWorkoutCSV(GRAVL, { unit: 'kg' })
expect(parsed.skipped).toBe(0)
expect(parsed.from).toBe('2026-01-01')
expect(parsed.to).toBe('2026-01-22')
const [lift, cardio] = parsed.workouts
expect(lift.name).toBe('Push Day')
expect(lift.entries[0].sets).toEqual([{ w: 11, r: 11, done: true }])
// "Set Duration (sec)" is seconds, not minutes: read as `time` it would land as 22 minutes.
expect(cardio.entries[0].sets).toEqual([{ min: 0.4, speed: 0, done: true }])
})
})
+62 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { matchExercise } from './import-csv.js'
import { matchExercise, parseWorkoutCSV } from './import-csv.js'
import { EXIDX } from './exercises.js'
// The names other apps actually export, and the catalogue entry each has to land on.
@@ -12,6 +12,20 @@ const MAPS = {
'Cable Core Pallof Press': '0979',
Elliptical: '2141',
'Stationary Bike': '2138',
// Hevy's vocabulary, from a real export. It writes the equipment in parentheses and says
// "bicep"/"chest fly" where the catalogue says "biceps"/"fly", so the word-bag lands one
// word off on every one of these and they arrived as custom exercises.
'Bicep Curl (Dumbbell)': '0294',
'Bicep Curl (Cable)': '0868',
'Chest Fly (Machine)': '0596',
'Butterfly (Pec Deck)': '0596',
'Incline Chest Fly (Dumbbell)': '0319',
'Rear Delt Reverse Fly (Dumbbell)': '0383',
'Face Pull': '0203',
'Battle Ropes': '0128',
'Hack Squat (Machine)': '0743',
'Seated Cable Row - Bar Grip': '0218',
'Single Arm Lateral Raise (Cable)': '0192',
}
describe('foreign exercise names resolve to the catalogue', () => {
@@ -43,8 +57,55 @@ describe('foreign exercise names resolve to the catalogue', () => {
expect(matchExercise('Deadlift')).toBe('0032')
})
// SYN rewrote 'machine' -> 'lever' before it ever reached 'smith machine' -> 'smith',
// so every Smith-machine name arrived as "smith lever ..." and could not match anything
// in the catalogue. The two rules are order-dependent; this pins the order.
it('resolves Smith-machine names rather than leaving a stray "lever"', () => {
expect(matchExercise('Bench Press (Smith Machine)')).toBe('0748')
expect(matchExercise('Overhead Press (Smith Machine)')).toBe('0766')
expect(matchExercise('Smith Machine Bench Press')).toBe('0748')
})
// The generic machine -> lever rule still has to work on its own.
it('keeps the plain machine alias working', () => {
expect(matchExercise('Seated Fly (Machine)')).toBe('0596')
})
it('still refuses to guess', () => {
expect(matchExercise('Some Movement I Invented')).toBe(null)
expect(matchExercise('')).toBe(null)
})
})
// Hevy exports no category column, so every invented exercise took the 'upper legs' default
// and a third of an imported history was attributed to the legs in the muscle map. With no
// category to read, the body part comes off the name instead.
describe('invented exercises get a body part from their name', () => {
const HEAD = 'title,start_time,end_time,description,exercise_title,superset_id,exercise_notes,set_index,set_type,weight_kg,reps,distance_km,duration_seconds,rpe'
const row = name => `W,"09 Oct 2025, 19:22","09 Oct 2025, 20:22",,"${name}",,,0,normal,40,10,,,`
const bpOf = name => {
const r = parseWorkoutCSV([HEAD, row(name)].join('\n'), { unit: 'kg' })
return r.customEx[0] && r.customEx[0].bp
}
it('reads the body part off names the catalogue does not have', () => {
expect(bpOf('Kirk Shrug Machine Thing')).toBe('back')
expect(bpOf('Bicep Curl Contraption')).toBe('upper arms')
expect(bpOf('Standing Calf Thing')).toBe('lower legs')
})
it('no longer files everything under the legs', () => {
expect(bpOf('Some Chest Contraption')).not.toBe('upper legs')
expect(bpOf('Some Chest Contraption')).toBe('chest')
})
it('leaves a genuine leg movement on the legs', () => {
expect(bpOf('Bulgarian Split Squat Machine v9')).toBe('upper legs')
})
it('still prefers an explicit category column when the file has one', () => {
const head = 'Date,Exercise,Category,Weight,Reps'
const r = parseWorkoutCSV([head, '2025-10-09,Some Invented Lift,Shoulders,40,10'].join('\n'), { unit: 'kg' })
expect(r.customEx[0].bp).toBe('shoulders')
})
})
+39
View File
@@ -10,6 +10,7 @@
// 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'
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
@@ -30,6 +31,27 @@ export async function nativeSave(state) {
} catch (e) { /* keep the localStorage copy */ }
}
// "Connect to my server" mode (lib/remote.js): which of local-only / a paired remote account this
// device chose, kept in its own file — never inside opengym-state.json, since that file's content
// is exactly what pushState() PUTs to a server, and a device's own connection secret must never
// travel as if it were training data.
const REMOTE_FILE = 'opengym-remote.json'
export async function loadRemoteFile() {
try {
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
const r = await Filesystem.readFile({ path: REMOTE_FILE, directory: Directory.Data, encoding: Encoding.UTF8 })
return JSON.parse(r.data)
} catch (e) { return null } // never decided yet
}
export async function saveRemoteFile(data) {
try {
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
await Filesystem.writeFile({ path: REMOTE_FILE, directory: Directory.Data, data: JSON.stringify(data), encoding: Encoding.UTF8 })
} 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
@@ -66,3 +88,20 @@ export async function shareExport(json, filename) {
const w = await Filesystem.writeFile({ path: filename, directory: Directory.Cache, data: json, encoding: Encoding.UTF8 })
await Share.share({ title: filename, url: w.uri })
}
// "Auto-backup on changes" (Settings): a dated snapshot dropped into the Documents folder —
// visible in Files (iOS) / a file manager (Android), unlike the private mirror nativeSave keeps
// — so whatever the user points at that folder (a sync app, a manual copy) always has something
// recent. One file per day; later triggers the same day just overwrite it.
export async function writeAutoBackup(state) {
try {
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
await Filesystem.writeFile({
path: `opengym-backup-${todayISO()}.json`,
directory: Directory.Documents,
data: JSON.stringify(state),
encoding: Encoding.UTF8,
recursive: true,
})
} catch (e) { /* best effort — the private mirror in Directory.Data still has the data */ }
}
+63 -15
View File
@@ -65,6 +65,7 @@ const BY_BODYPART = {
'upper legs': { quadriceps: 0.4, hamstring: 0.35, gluteal: 0.25 },
'lower legs': { calves: 0.8, tibialis: 0.2 },
neck: { trapezius: 1 },
'full body': { chest: 0.2, 'upper-back': 0.2, gluteal: 0.2, quadriceps: 0.2, hamstring: 0.1, abs: 0.1 },
cardio: {},
}
@@ -72,18 +73,40 @@ const SECONDARY = 0.4 // a supporting muscle counts this much against a primar
const arrayOf = value => Array.isArray(value) ? value : value == null || value === '' ? [] : [value]
function firstPresent(object, keys) {
if (!object || typeof object !== 'object') return null
for (const key of keys) {
if (Object.prototype.hasOwnProperty.call(object, key)) return object[key]
}
return null
}
// Completed history entries may retain a nested snapshot after their custom exercise is
// deleted from the profile catalogue. Prefer that snapshot when the outer entry has no muscle
// metadata of its own, while keeping direct/legacy entry fields authoritative when present.
function metadataOf(ex) {
if (!ex || typeof ex !== 'object') return ex
const hasDirect = ['muscleGroups', 'muscles', 'targetMuscles'].some(key => Object.prototype.hasOwnProperty.call(ex, key))
const DIRECT_KEYS = [
'muscleGroups', 'muscles', 'targetMuscles', 'muscleWeights',
'primaries', 'primaryMuscles', 'primary', 'secondaries', 'secondaryMuscles', 'secondary',
]
const hasDirect = DIRECT_KEYS.some(key => Object.prototype.hasOwnProperty.call(ex, key))
|| [ex.tg, ex.mg, ...arrayOf(ex.sm)].some(value => value != null && value !== '')
return !hasDirect && ex.muscleSnapshot && typeof ex.muscleSnapshot === 'object' && !Array.isArray(ex.muscleSnapshot)
? ex.muscleSnapshot
: ex
}
function explicitPartsOf(ex) {
if (!ex || typeof ex !== 'object') return null
const primary = firstPresent(ex, ['primaries', 'primaryMuscles', 'primary'])
const secondary = firstPresent(ex, ['secondaries', 'secondaryMuscles', 'secondary'])
if (primary !== null || secondary !== null) return {
primary: arrayOf(primary), secondary: arrayOf(secondary)
}
return null
}
function explicitGroupsOf(ex) {
if (!ex || typeof ex !== 'object') return null
if (Object.prototype.hasOwnProperty.call(ex, 'muscleGroups')) {
@@ -102,12 +125,14 @@ function explicitGroupsOf(ex) {
}
/** True only when the catalogue explicitly supplied muscle groups, not a body-part fallback. */
export function hasExplicitMuscleMetadata(ex) {
const source = metadataOf(ex)
if (!source || typeof source !== 'object') return false
const groups = explicitGroupsOf(source)
export function hasExplicitMuscleMetadata(entry) {
const ex = metadataOf(entry)
if (!ex || typeof ex !== 'object') return false
const parts = explicitPartsOf(ex)
if (parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))) return true
const groups = explicitGroupsOf(ex)
if (groups && groups.some(value => canonicalMuscle(value))) return true
return [source.tg, source.mg, ...arrayOf(source.sm)].some(value => canonicalMuscle(value))
return [ex.tg, ex.mg, ...arrayOf(smOf(ex))].some(value => canonicalMuscle(value))
}
function canonicalMuscle(value) {
@@ -116,17 +141,28 @@ function canonicalMuscle(value) {
return ALIAS[name] || null
}
/** Canonical unique muscle groups, accepting both new arrays and legacy single fields. */
export function muscleGroupsOf(ex) {
const sourceEx = metadataOf(ex)
const explicit = explicitGroupsOf(sourceEx)
const source = explicit || [sourceEx?.tg, sourceEx?.mg, ...arrayOf(smOf(sourceEx))]
function canonicalUnique(values) {
const out = []
source.forEach(value => {
for (const value of values || []) {
const slug = canonicalMuscle(value)
if (slug && !out.includes(slug)) out.push(slug)
})
if (!out.length && explicit == null) Object.keys(BY_BODYPART[sourceEx?.bp] || {}).forEach(slug => { if (!out.includes(slug)) out.push(slug) })
}
return out
}
/** Canonical unique muscle groups, accepting new primary/secondary arrays and legacy fields. */
export function muscleGroupsOf(entry) {
const ex = metadataOf(entry)
const parts = explicitPartsOf(ex)
const explicit = explicitGroupsOf(ex)
const useParts = parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))
const source = useParts
? [...parts.primary, ...parts.secondary]
: explicit || [ex?.tg, ex?.mg, ...arrayOf(smOf(ex))]
const out = canonicalUnique(source)
if (!out.length && !useParts && explicit == null) {
canonicalUnique(Object.keys(BY_BODYPART[ex?.bp] || {})).forEach(slug => out.push(slug))
}
return out
}
@@ -158,8 +194,13 @@ export function musclesOf(ex) {
const slug = canonicalMuscle(name)
if (slug) out[slug] = Math.max(out[slug] || 0, w)
}
const parts = explicitPartsOf(ex)
const explicit = explicitGroupsOf(ex)
if (explicit) explicit.forEach(m => add(m, 1))
const useParts = parts && [...parts.primary, ...parts.secondary].some(value => canonicalMuscle(value))
if (useParts) {
parts.primary.forEach(m => add(m, 1))
parts.secondary.forEach(m => add(m, SECONDARY))
} else if (explicit) explicit.forEach(m => add(m, 1))
else {
add(ex.tg, 1)
add(ex.mg, SECONDARY)
@@ -178,6 +219,13 @@ export function exerciseMuscleSnapshot(ex) {
if (ex.bp != null) out.bp = ex.bp
const weights = musclesOf(ex)
if (Object.keys(weights).length) out.muscleWeights = { ...weights }
const parts = explicitPartsOf(ex)
if (parts) {
const primaries = canonicalUnique(parts.primary)
const secondaries = canonicalUnique(parts.secondary).filter(slug => !primaries.includes(slug))
if (primaries.length) out.primaries = primaries
if (secondaries.length) out.secondaries = secondaries
}
if (hasExplicitMuscleMetadata(ex)) out.muscleGroups = [...muscleGroupsOf(ex)]
return out
}
+117 -5
View File
@@ -1,9 +1,45 @@
import { describe, expect, it } from 'vitest'
import { describe, it, expect } from 'vitest'
import { EXIDX, EXDB, smOf } from './exercises.js'
import { loadOfWorkouts, musclesOf } from './muscles.js'
import { MUSCLE_NAME, exerciseMuscleSnapshot, hasExplicitMuscleMetadata, loadOf, loadOfWorkouts, matchesMuscleGroups, muscleGroupsOf, musclesOf } from './muscles.js'
describe('multi-muscle exercise metadata', () => {
it('normalizes legacy primary/secondary fields and removes duplicate groups', () => {
const ex = { tg: 'pectorals', mg: 'triceps', sm: ['triceps', 'chest'] }
expect(muscleGroupsOf(ex)).toEqual(['chest', 'triceps'])
expect(musclesOf(ex)).toEqual({ chest: 1, triceps: 0.4 })
})
it('uses explicit multi-group metadata when present and supports legacy single groups', () => {
expect(muscleGroupsOf({ muscleGroups: ['chest', 'pectorals', 'triceps'] })).toEqual(['chest', 'triceps'])
expect(muscleGroupsOf({ tg: 'chest' })).toEqual(['chest'])
expect(MUSCLE_NAME.chest).toBe('Chest')
})
it('falls back to the legacy body-part map when an optional multi-group field is empty', () => {
expect(muscleGroupsOf({ bp: 'back', muscleGroups: [] })).toEqual(['upper-back', 'lower-back'])
expect(matchesMuscleGroups({ bp: 'back', muscleGroups: [] }, ['lower-back'])).toBe(true)
})
it('matches an exercise when any requested muscle group matches', () => {
const ex = { muscleGroups: ['chest', 'triceps'] }
expect(matchesMuscleGroups(ex, ['hamstring', 'triceps'])).toBe(true)
expect(matchesMuscleGroups(ex, ['hamstring', 'gluteal'])).toBe(false)
expect(matchesMuscleGroups(ex, [])).toBe(true)
})
it('counts one effective set per unique group instead of double counting duplicates', () => {
expect(loadOf([{ id: 'inline', ex: { tg: 'chest', sm: ['chest', 'triceps'] }, sets: 2 }]))
.toEqual({ chest: 2, triceps: 0.8 })
})
it('uses multi-muscle metadata carried by a history entry when its catalogue id is unavailable', () => {
expect(loadOfWorkouts([{ entries: [{
id: 'deleted-custom', muscleGroups: ['chest', 'chest', 'triceps'],
sets: [{ done: true }]
}] }])).toEqual({ chest: 1, triceps: 1 })
})
})
// The catalogue keeps the source dataset's secondary-muscle spellings; musclesOf maps
// those aliases to the canonical body-map slugs and applies the 0.4 support weight.
describe('catalogue secondary muscles', () => {
it('maps a bench press to chest, triceps and deltoids', () => {
expect(musclesOf(EXIDX['0025'])).toMatchObject({
@@ -16,7 +52,7 @@ describe('catalogue secondary muscles', () => {
it('maps a squat to glutes, quads and hamstrings', () => {
expect(musclesOf(EXIDX['0043'])).toMatchObject({
gluteal: 1,
quadriceps: 0.4,
quadriceps: 1,
hamstring: 0.4,
})
})
@@ -44,6 +80,46 @@ describe('catalogue secondary additions', () => {
})
describe('explicit multi-primary metadata', () => {
it('gives every primary full weight and secondaries supporting weight', () => {
const ex = {
bp: 'chest', tg: 'abs', mg: 'triceps', sm: ['lower back'],
primaries: ['chest', 'triceps', 'chest'], secondaries: ['deltoids', 'triceps']
}
expect(muscleGroupsOf(ex)).toEqual(['chest', 'triceps', 'deltoids'])
expect(musclesOf(ex)).toEqual({ chest: 1, triceps: 1, deltoids: 0.4 })
})
it('keeps the body-part fallback when primaries are absent or explicitly empty', () => {
const expected = { 'upper-back': 0.75, 'lower-back': 0.25 }
expect(musclesOf({ bp: 'back' })).toEqual(expected)
expect(musclesOf({ bp: 'back', primaries: [] })).toEqual(expected)
})
it('keeps legacy metadata when a new array field is present but empty', () => {
expect(exerciseMuscleSnapshot({ bp: 'chest', tg: 'abs', primaries: [] })).toMatchObject({
muscleGroups: ['abs']
})
})
it('provides a conservative Full body fallback for legacy custom exercises', () => {
expect(muscleGroupsOf({ bp: 'full body' })).toEqual(['chest', 'upper-back', 'gluteal', 'quadriceps', 'hamstring', 'abs'])
expect(musclesOf({ bp: 'full body' })).toEqual({
chest: 0.2, 'upper-back': 0.2, gluteal: 0.2, quadriceps: 0.2, hamstring: 0.1, abs: 0.1
})
})
it('preserves explicit primary and secondary arrays in history snapshots', () => {
expect(exerciseMuscleSnapshot({
n: 'Deadlift', bp: 'full body', primaries: ['gluteal', 'lower-back'], secondaries: ['hamstring']
})).toMatchObject({
n: 'Deadlift', bp: 'full body', primaries: ['gluteal', 'lower-back'], secondaries: ['hamstring'],
muscleGroups: ['gluteal', 'lower-back', 'hamstring']
})
})
})
describe('map load with warm-up phases', () => {
it('excludes warm-up sets from the by-sets-worked map', () => {
const w = {
@@ -60,3 +136,39 @@ describe('map load with warm-up phases', () => {
expect(load.chest).toBe(1)
})
})
// A custom exercise that was deleted from the catalogue survives in history only as the
// muscleSnapshot finish-workout wrote. Reading it back is what keeps those sessions in the
// body map and in Stats instead of silently contributing nothing.
describe('deleted custom exercises', () => {
const snapshotEntry = {
id: 'gone-custom-1',
sets: [{ w: 60, r: 8, done: true }],
muscleSnapshot: { n: 'Deleted custom', bp: 'chest', muscleGroups: ['chest'], muscleWeights: { chest: 1 } },
}
it('reads muscle load back out of the snapshot', () => {
expect(loadOfWorkouts([{ d: '2026-08-01', entries: [snapshotEntry] }])).toEqual({ chest: 1 })
})
it('reports the snapshot groups as explicit metadata', () => {
expect(hasExplicitMuscleMetadata(snapshotEntry)).toBe(true)
expect(muscleGroupsOf(snapshotEntry)).toEqual(['chest'])
})
it('still prefers the entry\'s own metadata when it has any', () => {
const withOwn = { ...snapshotEntry, tg: 'quadriceps' }
expect(muscleGroupsOf(withOwn)).toEqual(['quadriceps'])
})
})
// muscles.js counts completed work, so its warm-up boundary has to agree with the one the
// session runtime uses — including the legacy spellings phaseForSet normalises.
describe('warm-up boundary', () => {
it('excludes every phase spelling the workout model treats as a warm-up', () => {
const entries = spelling => [{ id: '0025', sets: [{ w: 100, r: 5, done: true, phase: spelling }] }]
for (const spelling of ['warmup', 'warm-up', 'warm_up', 'Warmup', ' warmup ']) {
expect(loadOfWorkouts([{ d: '2026-08-01', entries: entries(spelling) }]), spelling).toEqual({})
}
})
})
+89
View File
@@ -0,0 +1,89 @@
// @vitest-environment happy-dom
// The note sheet is new JSX and nothing else mounts it, so a bad hook order, a missing import or
// a wrong store path would only surface on a real device. Render it through the real sheet stack
// and drive a save, so the wiring is checked and not just the shape of the module.
import { describe, expect, it, beforeEach, afterEach } from 'vitest'
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exerciseNoteSheet } from '../sheets.jsx'
const activeWith = entry => ({ id: 'w1', d: '2026-08-25', start: 1, routineId: 'r1', name: 'Push', entries: [entry] })
// Roots have to be torn down between tests: the sheet subscribes to the store, so a root left
// mounted reacts to the next test's setState — outside act(), which React rightly complains about.
const mounted = []
function renderSheet() {
exerciseNoteSheet(0)
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(sheet_close(sheet))))
return host
}
const sheet_close = sheet => () => useUI.getState().closeSheet(sheet.id)
const type = (el, value) => {
const setter = Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set
setter.call(el, value)
el.dispatchEvent(new Event('input', { bubbles: true }))
}
describe('exercise note sheet', () => {
beforeEach(() => {
// React only treats act() as real when told it is in a test environment, and vitest shares
// a worker across files — so set it per test rather than once at module scope.
globalThis.IS_REACT_ACT_ENVIRONMENT = true
useUI.setState({ sheets: [] })
useStore.setState(s => ({
S: { ...s.S, exNotes: {}, active: activeWith({ id: 'bench', sets: [] }) },
}))
document.body.innerHTML = ''
})
afterEach(() => {
act(() => { mounted.splice(0).forEach(r => r.unmount()) })
})
it('renders the session note, the pin and the standing note', () => {
const host = renderSheet()
const areas = host.querySelectorAll('textarea')
expect(areas).toHaveLength(2)
// The pin cannot be set on an empty note — it would pin nothing.
expect(host.querySelector('[role="switch"]').disabled).toBe(true)
})
it('saves the session note with its pin and the standing note separately', () => {
const host = renderSheet()
const [today, always] = host.querySelectorAll('textarea')
act(() => { type(today, 'shoulder twinged'); type(always, 'seat at 4') })
act(() => { host.querySelector('[role="switch"]').click() })
const save = [...host.querySelectorAll('button')].find(b => /save/i.test(b.textContent))
act(() => { save.click() })
const S = useStore.getState().S
expect(S.active.entries[0].note).toBe('shoulder twinged')
expect(S.active.entries[0].notePin).toBe(true)
// The standing note belongs to the exercise, not to today's entry.
expect(S.exNotes.bench).toBe('seat at 4')
expect(useUI.getState().sheets).toHaveLength(0)
})
it('clearing the session note drops the pin with it', () => {
useStore.setState(s => ({
S: { ...s.S, active: activeWith({ id: 'bench', sets: [], note: 'old', notePin: true }) },
}))
const host = renderSheet()
const [today] = host.querySelectorAll('textarea')
act(() => { type(today, '') })
const save = [...host.querySelectorAll('button')].find(b => /save/i.test(b.textContent))
act(() => { save.click() })
const e = useStore.getState().S.active.entries[0]
expect(e.note).toBeUndefined()
expect(e.notePin).toBeUndefined()
})
})
+26
View File
@@ -148,6 +148,32 @@ describe('is1RMRecord', () => {
})
describe('drop-sets, rest-pause sets and 1RM', () => {
it('estimates only from the main/activation weight×reps, ignoring lighter drops', () => {
const entry = { id: 'x', sets: [
{ type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] },
] }
expect(bestSetOf(entry)).toEqual(bestSetOf({ id: 'x', sets: [{ w: 100, r: 5, done: true }] }))
})
it('estimates only from the row\'s own w/r, ignoring rest-pause bursts', () => {
const entry = { id: 'x', sets: [
{ type: 'restpause', w: 60, r: 8, done: true, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] },
] }
expect(bestSetOf(entry)).toEqual(bestSetOf({ id: 'x', sets: [{ w: 60, r: 8, done: true }] }))
})
it('refuses to estimate a planned rest-pause row once its total reps exceed REP_CAP, same as any other high-rep set', () => {
// A planned rest-pause row's own r is the total across every burst (see
// applyIntensifierPlan/history.js), so it commonly lands above REP_CAP — the row is real
// work, but "estimate a max from 20 broken-up reps" is exactly the fantasy REP_CAP refuses.
const entry = { id: 'x', sets: [
{ type: 'restpause', w: 60, r: 20, done: true, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] },
] }
expect(bestSetOf(entry)).toBeNull()
})
})
describe('warm-up sets and 1RM', () => {
const ENTRY = { id: 'warm-test', sets: [
{ w: 20, r: 8, done: true, warmup: true },
+43 -5
View File
@@ -9,9 +9,9 @@
// a page break — each exercise, and each routine that fits, stays in one place.
import { EXIDX, isBodyweightEq } from './exercises.js'
import { modeOf, fmtSec, isBw, isPerSide, sideReps } from './history.js'
import { modeOf, fmtSec, isBw, isPerSide, sideReps, MAX_PLANNED_WARMUPS } from './history.js'
import { uid, todayISO, DAYN, fmtNum, exCount } from './format.js'
import { t } from './i18n-core.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
@@ -45,9 +45,37 @@ function cleanEx(e) {
if (e.repsMin != null) o.repsMin = e.repsMin
if (e.repsMax != null) o.repsMax = e.repsMax
if (e.sg) o.sg = e.sg
if (e.note) o.note = e.note
const warm = cleanWarmupSets(e.warmupSets)
if (warm) o.warmupSets = warm
// Drop-sets and rest-pause are part of how the exercise is prescribed, not a logging detail.
// Without this a shared "3x5 with a double drop" arrived at the other end as a plain 3x5,
// silently — parsePlan's `dropped` counter only tracks exercises it cannot resolve at all.
const intens = cleanIntensifier(e.intensifier)
if (intens) o.intensifier = intens
return o
}
/** Clamped the same way buildSets clamps it on the way out — the stepper showed a hand-edited
* plan file's "999" verbatim, because the clamp only happened when the rows were built. */
function cleanWarmupSets(v) {
const n = Math.round(Number(v)) || 0
return n > 0 ? Math.min(MAX_PLANNED_WARMUPS, 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) {
const type = x && x.type
if (type === 'dropset') {
return { type, count: Math.max(1, Math.round(Number(x.count)) || 1), pct: Math.max(5, Math.round(Number(x.pct)) || 20) }
}
if (type === 'restpause') {
return { type, totalReps: Math.max(1, Math.round(Number(x.totalReps)) || 1), restSec: Math.max(5, Math.round(Number(x.restSec)) || 15) }
}
return null
}
/** Build the shareable bundle: every routine, the week schedule, referenced customs. */
export function buildPlanBundle(S, name) {
const routines = (S.routines || []).map(r => ({
@@ -85,6 +113,13 @@ export function parsePlan(raw) {
const ok = !!e && (known.has(e.id) || !!EXIDX[e.id])
if (!ok) dropped++
return ok
}).map(e => {
// The exercises pass through as written, so the two 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 } : {}) }
})
}))
return {
@@ -172,9 +207,10 @@ function routineHTML(r, unit) {
const rows = units(r.ex).map(u => {
const items = u.map(e => {
const ex = EXIDX[e.id]
const name = ex ? ex.n : t('Unknown exercise')
const name = ex ? exerciseNameFor(ex) : t('Unknown exercise')
const part = ex && ex.bp && ex.bp !== 'cardio' ? `<span class="part">${esc(ex.bp)}</span>` : ''
return `<div class="ex"><div class="ex-n">${esc(name)}${part}</div><div class="ex-s">${esc(scheme(e, unit))}</div></div>`
const note = e.note ? `<div class="ex-note">${esc(e.note)}</div>` : ''
return `<div class="ex"><div class="ex-row"><div class="ex-n">${esc(name)}${part}</div><div class="ex-s">${esc(scheme(e, unit))}</div></div>${note}</div>`
}).join('')
return u.length > 1
? `<div class="ss"><div class="ss-tag">${esc(t('Superset'))}</div><div class="ss-items">${items}</div></div>`
@@ -236,11 +272,13 @@ export function planPrintHTML(S, owner) {
.r-count { font-size: 12px; color: #8a90a0; white-space: nowrap; }
.ex-list { display: flex; flex-direction: column; }
.ex { display: flex; align-items: baseline; justify-content: space-between; gap: 14px; padding: 6px 0; break-inside: avoid; page-break-inside: avoid; }
.ex { display: flex; flex-direction: column; padding: 6px 0; break-inside: avoid; page-break-inside: avoid; }
.ex + .ex, .ss + .ex, .ex + .ss { border-top: 1px solid #f2f3f6; }
.ex-row { display: flex; align-items: baseline; justify-content: space-between; gap: 14px; }
.ex-n { text-transform: capitalize; font-weight: 500; }
.ex-n .part { text-transform: capitalize; color: #9aa0ae; font-weight: 400; font-size: 12px; margin-left: 8px; }
.ex-s { color: #3d424e; white-space: nowrap; font-variant-numeric: tabular-nums; }
.ex-note { color: #6a7080; font-size: 12px; margin-top: 2px; }
.ex.empty, .none { color: #a2a8b6; }
.ss { break-inside: avoid; page-break-inside: avoid; border-left: 3px solid #cfe08a; padding-left: 12px; margin: 4px 0; }
+47
View File
@@ -0,0 +1,47 @@
import { describe, expect, it } from 'vitest'
import { buildPlanBundle, 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.
const stateWith = ex => ({
routines: [{ id: 'r1', name: 'Push', ex: [{ id: '0025', sets: 3, reps: 5, weight: 100, ...ex }] }],
week: {}, customEx: [],
})
const roundTrip = ex => parsePlan(JSON.stringify(buildPlanBundle(stateWith(ex), 'Plan'))).routines[0].ex[0]
describe('what survives a shared plan', () => {
it('carries a drop-set prescription', () => {
expect(roundTrip({ intensifier: { type: 'dropset', count: 2, pct: 20 } }).intensifier)
.toEqual({ type: 'dropset', count: 2, pct: 20 })
})
it('carries a rest-pause prescription', () => {
expect(roundTrip({ intensifier: { type: 'restpause', totalReps: 12, restSec: 15 } }).intensifier)
.toEqual({ type: 'restpause', totalReps: 12, restSec: 15 })
})
it('carries planned warm-ups', () => {
expect(roundTrip({ warmupSets: 3 }).warmupSets).toBe(3)
})
it('drops an intensifier it does not recognise rather than passing it on', () => {
expect(roundTrip({ intensifier: { type: 'nonsense', count: 3 } }).intensifier).toBeUndefined()
})
it('clamps a hand-edited warm-up count instead of showing it verbatim', () => {
const bundle = { opengym_plan: 1, name: 'x', routines: [{ id: 'r', name: 'R', ex: [{ id: '0025', sets: 3, reps: 5, warmupSets: 999 }] }], week: {}, customEx: [] }
expect(parsePlan(bundle).routines[0].ex[0].warmupSets).toBe(5)
})
// 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', () => {
const bundle = { opengym_plan: 1, name: 'x', routines: [{ id: 'r', name: 'R', ex: [{ id: '0025', sets: 3, reps: 5, intensifier: { type: 'dropset', count: 0, pct: -5 } }] }], week: {}, customEx: [] }
expect(parsePlan(bundle).routines[0].ex[0].intensifier).toEqual({ type: 'dropset', count: 1, pct: 5 })
})
it('falls back to the default drop percentage when the file omits it', () => {
const bundle = { opengym_plan: 1, name: 'x', routines: [{ id: 'r', name: 'R', ex: [{ id: '0025', sets: 3, reps: 5, intensifier: { type: 'dropset' } }] }], week: {}, customEx: [] }
expect(parsePlan(bundle).routines[0].ex[0].intensifier).toEqual({ type: 'dropset', count: 1, pct: 20 })
})
})
+12 -5
View File
@@ -16,7 +16,7 @@
// · fewer sets than prescribed → miss
// So a session that fell apart can never advance the load as though it had succeeded.
import { modeOf, repStep } from './history.js'
import { modeOf, repStep, rerampWarmups } from './history.js'
import { EXIDX } from './exercises.js'
import { isWarmupRow } from './workout-model.js'
@@ -250,7 +250,7 @@ export function nextPrescription(S, cfg, routine) {
* Apply a prescription to freshly built sets. Only the fields the policy actually decided
* are touched, and only on sets that have not been logged yet.
*/
export function applyPrescription(sets, p) {
export function applyPrescription(sets, p, step = 2.5) {
if (!p || p.kind === 'off' || p.kind === 'first') return sets
const out = sets.map(s => {
// Never rewrite a logged set, and never rewrite a warm-up: the prescription speaks to
@@ -270,9 +270,16 @@ export function applyPrescription(sets, p) {
if (p.sets > workRows.length) {
// An all-warm-up entry has no work row to seed growth from - growing warm-up copies
// would both invent work and never terminate the loop. Leave the entry untouched.
if (!workRows.length) return out
if (!workRows.length) return rerampWarmups(out, step)
const seed = workRows[workRows.length - 1]
while (out.filter(s => !isWarmupRow(s)).length < p.sets) out.push({ ...seed, done: false })
// A freshly appended row hasn't been performed, so it never inherits a seed's already-
// logged drops/clusters — that would invent extra work the row never actually did. Its
// `type` is kept: that's the exercise's plan (every set is a drop-set/rest-pause), not
// something this particular row logged.
const { drops, clusters, ...plainSeed } = seed
while (out.filter(s => !isWarmupRow(s)).length < p.sets) out.push({ ...plainSeed, done: false })
}
return out
// Last, because the work rows now carry their final weight: the warm-up block ramps toward
// what you are actually about to lift, not toward what you lifted last time.
return rerampWarmups(out, step)
}
+31
View File
@@ -523,3 +523,34 @@ describe('applyPrescription never touches warm-up rows (round 3)', () => {
expect(out).toEqual(sets) // no work row to seed growth from - nothing grows, no loop
})
})
describe('drop-sets and rest-pause sets in progression', () => {
it('readSession judges a drop-set row on its own main weight/reps, ignoring the drops', () => {
const withDrops = readSession({ id: LIFT, target: { sets: 1, reps: 5 }, sets: [
{ type: 'dropset', w: 60, r: 5, done: true, drops: [{ w: 40, r: 8 }, { w: 20, r: 10 }] },
] })
const plain = readSession({ id: LIFT, target: { sets: 1, reps: 5 }, sets: [{ w: 60, r: 5, done: true }] })
expect(withDrops).toEqual(plain)
})
it('readSession judges a rest-pause row on its activation weight/reps, ignoring the bursts', () => {
const withBursts = readSession({ id: LIFT, target: { sets: 1, reps: 8 }, sets: [
{ type: 'restpause', w: 60, r: 8, done: true, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] },
] })
const plain = readSession({ id: LIFT, target: { sets: 1, reps: 8 }, sets: [{ w: 60, r: 8, done: true }] })
expect(withBursts).toEqual(plain)
})
it('applyPrescription still rewrites a drop-set/rest-pause row\'s own weight, leaving its drops/clusters untouched', () => {
const sets = [{ type: 'dropset', w: 60, r: 5, done: false, drops: [{ w: 40, r: 8 }] }]
const out = applyPrescription(sets, { kind: 'up', weight: 62.5 })
expect(out[0]).toEqual({ type: 'dropset', w: 62.5, r: 5, done: false, drops: [{ w: 40, r: 8 }] })
})
it('a newly grown row keeps the seed\'s planned type but not its already-logged drops/clusters', () => {
const sets = [{ type: 'dropset', w: 0, r: 10, done: false, drops: [{ w: 0, r: 12 }] }]
const out = applyPrescription(sets, { kind: 'up', weight: 0, reps: 10, sets: 2 })
expect(out).toHaveLength(2)
expect(out[1]).toEqual({ type: 'dropset', w: 0, r: 10, done: false })
})
})
@@ -0,0 +1,61 @@
import { afterEach, describe, expect, test } from 'vitest'
import { readFileSync } from 'node:fs'
import ptBR from '../exercise-names/pt-BR.js'
import { EXDB } from './exercises-data.js'
import {
EXERCISE_NAME_LANGS, _setLangState, exerciseNameFor, exerciseNameSearchText
} from './i18n-core.js'
describe('Brazilian Portuguese exercise names', () => {
const source = JSON.parse(readFileSync(new URL('../../../scripts/exercise-name-sources/pt-BR.json', import.meta.url), 'utf8'))
afterEach(() => _setLangState('en', {}, null, null))
test('matches the curated source and covers the complete built-in catalogue', () => {
expect(Object.keys(ptBR)).toHaveLength(EXDB.length)
expect(ptBR).toEqual(source)
expect(EXERCISE_NAME_LANGS).toContain('pt-BR')
})
test('contains a non-empty translation for every known exercise', () => {
for (const exercise of EXDB) {
expect(ptBR[exercise.id]?.trim(), exercise.id).toBeTruthy()
expect(ptBR[exercise.id], exercise.id).not.toMatch(/(?:^|[^\p{L}])(?:abdómen|anca|gémeos|ecrã|ginásio|banda|piso|omoplata|pegada inversa|pegada invertida)(?=$|[^\p{L}])/iu)
}
})
test('preserves identity-changing qualifiers and equipment', () => {
const rules = [
[/assisted/iu, /assistid/iu],
[/weighted/iu, /(?:peso|carga|lastro|ponderad)/iu],
[/(?:^|[^\p{L}])male(?=$|[^\p{L}])/iu, /masculin/iu],
[/(?:^|[^\p{L}])female(?=$|[^\p{L}])/iu, /feminin/iu],
[/barbell/iu, /barra/iu],
[/dumbbell/iu, /halter/iu],
[/kettlebell/iu, /kettlebell/iu],
[/smith/iu, /smith/iu],
[/stability ball/iu, /bola de estabilidade/iu],
[/medicine ball/iu, /bola medicinal/iu],
]
for (const exercise of EXDB) {
for (const [english, portuguese] of rules) {
if (english.test(exercise.n)) expect(ptBR[exercise.id], `${exercise.id}: ${english}`).toMatch(portuguese)
}
}
})
test('shows Portuguese first and preserves the canonical English title', () => {
const exercise = EXDB[0]
_setLangState('pt-BR', {}, null, ptBR)
expect(exerciseNameFor(exercise)).toBe(`${ptBR[exercise.id]} (${exercise.n})`)
expect(exerciseNameSearchText(exercise)).toContain(ptBR[exercise.id])
expect(exerciseNameSearchText(exercise)).toContain(exercise.n)
})
test('never translates custom exercises or changes other languages', () => {
const custom = { id: 'custom-1', n: 'Meu exercício' }
_setLangState('pt-BR', {}, null, ptBR)
expect(exerciseNameFor(custom)).toBe('Meu exercício')
_setLangState('en', {}, null, null)
expect(exerciseNameFor(EXDB[0])).toBe(EXDB[0].n)
})
})
@@ -0,0 +1,55 @@
import { describe, expect, test } from 'vitest'
import { readFileSync } from 'node:fs'
import ptBR from '../instr/pt-BR.js'
import { EXDB } from './exercises-data.js'
import { INSTR_LANGS } from './i18n-core.js'
describe('Brazilian Portuguese exercise instructions', () => {
const exercises = new Map(EXDB.map(exercise => [exercise.id, exercise]))
const source = JSON.parse(readFileSync(new URL('../../../scripts/instruction-sources/pt-BR.json', import.meta.url), 'utf8'))
test('matches the curated source and covers the complete exercise corpus', () => {
expect(Object.keys(ptBR)).toHaveLength(EXDB.length)
expect(ptBR).toEqual(source)
})
test('only enables pt-BR instructions when the pack is complete', () => {
expect(INSTR_LANGS.includes('pt-BR')).toBe(Object.keys(ptBR).length === EXDB.length)
})
test('completes Stage 1 waist and core coverage', () => {
const stage = EXDB.filter(exercise => exercise.bp === 'waist')
expect(stage).toHaveLength(169)
stage.forEach(exercise => expect(ptBR, exercise.id).toHaveProperty(exercise.id))
})
test('contains only known exercises with complete, non-empty step lists', () => {
for (const [id, steps] of Object.entries(ptBR)) {
const exercise = exercises.get(id)
expect(exercise, `unknown exercise ${id}`).toBeDefined()
expect(steps, id).toHaveLength(exercise.st.length)
steps.forEach((step, index) => {
expect(step.trim(), `${id} step ${index + 1}`).not.toBe('')
expect(step, `${id} step ${index + 1}`).not.toBe(exercise.st[index])
expect(step, `${id} step ${index + 1}`).not.toMatch(/(?:^|[^\p{L}])(?:the|your|with|from|towards?|repeat|desired|starting|slowly|hold|while|then|back|straight|ground|feet|hands|body|legs|arms|knees|shoulders)(?=$|[^\p{L}])/iu)
expect(step, `${id} step ${index + 1}`).not.toMatch(/(?:^|[^\p{L}])(?:ginásio|anca|abdómen|gémeos|ecrã|core|banda|piso|omoplata|peso de mão|barra de elevações|pegada por cima|pegada invertida|pegada inversa|bola suíça)(?=$|[^\p{L}])/iu)
expect(step, `${id} step ${index + 1}`).not.toMatch(/flexion\p{L}*\s+(?:a\s+|o\s+|os\s+|um\s+|uma\s+)?(?:barra|pesos?|halter(?:es)?|mão)(?=$|[^\p{L}])/iu)
})
}
})
test('does not replace kettlebells with dumbbells', () => {
for (const exercise of EXDB) {
exercise.st.forEach((step, index) => {
if (/kettlebells?/iu.test(step)) {
expect(ptBR[exercise.id][index], `${exercise.id} step ${index + 1}`).toMatch(/kettlebells?/iu)
}
})
}
})
test('uses wrist extension for reverse wrist curls', () => {
const reverseWristCurlIds = ['0079', '0082', '0104', '0210', '0224', '0358', '0367', '0368', '0385', '0771', '0994', '1441']
reverseWristCurlIds.forEach(id => expect(ptBR[id].join(' '), id).toMatch(/estend\p{L}*(?: lentamente)? (?:o |os )?punhos?/iu))
})
})
+54
View File
@@ -0,0 +1,54 @@
import { describe, expect, test } from 'vitest'
import { createHash } from 'node:crypto'
import pt from '../locales/pt.js'
import ptBR, { PT_BR_OVERRIDES } from '../locales/pt-BR.js'
import { DATE_LOCALES, LANGS } from './i18n-core.js'
const placeholders = value => [...String(value).matchAll(/\{\d+\}/g)].map(match => match[0]).sort()
const byCodeUnit = ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)
describe('Brazilian Portuguese locale', () => {
test('is a separately selectable locale with Brazilian date formatting', () => {
expect(LANGS.pt).toBe('Português (Portugal)')
expect(LANGS['pt-BR']).toBe('Português (Brasil)')
expect(DATE_LOCALES['pt-BR']).toBe('pt-BR')
})
test('matches the source key set and preserves interpolation placeholders', () => {
expect(Object.keys(ptBR).sort()).toEqual(Object.keys(pt).sort())
for (const [source, translated] of Object.entries(ptBR)) {
expect(placeholders(translated), source).toEqual(placeholders(source))
}
})
test('makes every inherited pt-PT value an explicit reviewed snapshot', () => {
const inherited = Object.entries(pt)
.filter(([key]) => !(key in PT_BR_OVERRIDES))
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(362)
expect(inherited).toHaveLength(517)
// 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('56fd46aefb32a69e0bd6ed0c9f263d521113d3db6f44cfdcefb66d88d26312e5')
})
test('does not leak European Portuguese UI terms', () => {
const text = Object.values(ptBR).join('\n')
const europeanPortuguese = /(?:^|[^\p{L}])(?:ficheiro\p{L}*|telemóvel\p{L}*|ecrã\p{L}*|regist(?:o|am|ado|ada|ados|adas)|eliminad\p{L}*|definições|cronómetro|detetad\p{L}*|gémeos|abdómen|anca|coifa dos rotadores|escadora|completaste|acabaste|aguentas|definires|completares|aguenta|aguentaste|ficaste|viajares)(?=$|[^\p{L}])/iu
expect(text).not.toMatch(europeanPortuguese)
expect(text).not.toMatch(/[«»]/u)
expect(ptBR.Save).toBe('Salvar')
expect(ptBR.Settings).toBe('Configurações')
expect(ptBR['Delete workout']).toBe('Excluir treino')
expect(ptBR.Superset).toBe('Superset')
expect(ptBR['Guest mode — data lives only in this browser.']).toContain('visitante')
expect(ptBR['Sign in with passkey']).toContain('chave de acesso')
expect(ptBR.band).toBe('elástico')
expect(ptBR['resistance band']).toBe('faixa elástica')
expect(ptBR.soleus).toBe('sóleo')
expect(ptBR.Unpair).toBe('Desvincular')
expect(ptBR['Starter plan loaded — Mon Push · Wed Pull · Fri Legs']).toContain('Seg Push · Qua Pull')
})
})
+24 -4
View File
@@ -1,6 +1,6 @@
import { EXIDX } from './exercises.js'
import { MUSCLES, musclesOf } from './muscles.js'
import { isWarmupRow } from './workout-model.js'
import { isWarmupRow, dropsOf } from './workout-model.js'
// A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve
// 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting
@@ -172,6 +172,25 @@ function session1RMs(workout, opts = {}) {
return best
}
// Extra tonnage from a drop-set's drops, weighted the same way as the row's own main set — a
// drop taken near failure counts the same as any other hard rep for fatigue purposes, it just
// carries its own (usually lighter) load.
//
// A rest-pause row's `clusters` are NOT extra here: the row's own `r` already is the total reps
// across every burst (see applyIntensifierPlan/history.js), so the main tonnage term below
// already covers it — adding clusters on top would double-count the same reps.
function extraTonnage(ex, entry, set, workout, oneRm, opts = {}) {
const drops = dropsOf(set)
if (!drops.length) return 0
const isBwEx = bodyweightConfigured(ex, entry, set, workout, opts)
const weigh = (load, reps) => {
if (!(load > 0) || !(reps > 0)) return 0
const raw = load * reps
return isBwEx || !(oneRm > 0) ? raw : raw * Math.min(1, load / oneRm) ** 1.5
}
return drops.reduce((sum, d) => sum + weigh(loadKgFor(ex, entry, d, workout, opts), Number(d?.r) || 0), 0)
}
// Intensity-weighted tonnage for one completed set: load x reps x (load / exercise 1RM)^1.5.
// The exponent saturates the "hard set" effect - a set at 90% of your 1RM counts ~0.81 of its
// raw tonnage, one at 50% only ~0.35. Cardio, timed holds, and sets whose exercise has no
@@ -186,13 +205,14 @@ function setTonnage(ex, entry, set, workout, oneRm, opts = {}) {
const reps = set?.r || 1
const load = loadKgFor(ex, entry, set, workout, opts)
const raw = load * reps
const extra = extraTonnage(ex, entry, set, workout, oneRm, opts)
// A bodyweight target is already an external-load-normalised total (body mass + any added
// load). It has no meaningful barbell-style 1RM intensity ratio in the legacy data model, so
// retain the monotonic total-load stimulus instead of letting a newly created low 1RM shrink
// a weighted bodyweight set below the unloaded version.
if (bodyweightConfigured(ex, entry, set, workout, opts)) return raw
if (!(oneRm > 0) || !(load > 0)) return raw
return raw * Math.min(1, load / oneRm) ** 1.5
if (bodyweightConfigured(ex, entry, set, workout, opts)) return raw + extra
if (!(oneRm > 0) || !(load > 0)) return raw + extra
return raw * Math.min(1, load / oneRm) ** 1.5 + extra
}
// One session's per-muscle stimulus, calculated only from that session. A completed zero-load
+41
View File
@@ -403,6 +403,47 @@ describe('warm-up flag in strength and fatigue', () => {
})
})
describe('drop-set drops add fatigue tonnage on top of the main set', () => {
// Same within-session Epley baseline setTonnage derives from the row's own w/r (8 reps,
// under REP_CAP), so a drop is weighted against the same 1RM as the main set.
const oneRm = 80 * (1 + 8 / 30)
it('a drop-set drop adds its own intensity-weighted tonnage', () => {
const dropRow = { done: true, type: 'dropset', w: 80, r: 8, drops: [{ w: 60, r: 6 }] }
const dropTonnage = 60 * 6 * Math.min(1, 60 / oneRm) ** 1.5
const expected = expectedFatigue([{ stimulus: V + dropTonnage }])
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [dropRow])], NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 8)
// strictly more than the plain 80x8 set alone — the drop is real extra work
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [dropRow])], NOW)[SINGLE_SLUG])
.toBeGreaterThan(fatigueOf([doneWorkoutAt(SINGLE.id, NOW)], NOW)[SINGLE_SLUG])
})
it('leaves fatigue unchanged for a straight set with no drops', () => {
const plain = { done: true, w: 80, r: 8 }
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [plain])], NOW)[SINGLE_SLUG])
.toBeCloseTo(expectedFatigue([{ stimulus: V }]), 8)
})
})
describe('a rest-pause row\'s clusters add no extra fatigue tonnage', () => {
// Its own r is already the total across every burst (see applyIntensifierPlan/history.js),
// so setTonnage's main w x r term already covers all of it — clusters are a breakdown only.
it('matches a plain set of the same w/r exactly, regardless of how the clusters break it down', () => {
const burstRow = { done: true, type: 'restpause', w: 80, r: 8, clusters: [{ r: 4, restSec: 15 }] }
const plainRow = { done: true, w: 80, r: 8 }
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [burstRow])], NOW)[SINGLE_SLUG])
.toBeCloseTo(fatigueOf([workoutAt(SINGLE.id, NOW, [plainRow])], NOW)[SINGLE_SLUG], 10)
})
it('holds for a realistic planned total too — a full descending split adds nothing beyond the row\'s own r', () => {
const burstRow = { done: true, type: 'restpause', w: 80, r: 20, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] }
const plainRow = { done: true, w: 80, r: 20 }
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [burstRow])], NOW)[SINGLE_SLUG])
.toBeCloseTo(fatigueOf([workoutAt(SINGLE.id, NOW, [plainRow])], NOW)[SINGLE_SLUG], 10)
})
})
describe('canonical loads and configured bodyweight', () => {
const loaded = EXDB.find(ex => {
const weights = musclesOf(ex)
+48
View File
@@ -0,0 +1,48 @@
// Mobile build only: "connect to my server" mode (see mobile.js's header comment for why the
// mobile flavor has no backend at all by default). This is the alternative — pairing the app to
// an already self-hosted openGym server instead of keeping data device-local.
//
// Passkeys can't be used from inside the app's own WebView (its origin never matches the
// server's RP_ID), so auth here is a short one-time code redeemed from an already signed-in
// browser tab (Settings → "Pair the mobile app") for a bearer token — see api/server.js's
// /api/pair/create + /api/pair/redeem.
import { pairRedeem, setRemoteAuth } from './api.js'
import { loadRemoteFile, saveRemoteFile } from './mobile.js'
// Accepts what someone actually types: bare host, no scheme, trailing slash, stray whitespace.
// Defaults to https:// (self-hosting docs already push for HTTPS; the one exception, localhost,
// still parses fine without a scheme). Returns null for anything that isn't a usable URL at all.
export function normalizeServerUrl(raw) {
const s = String(raw || '').trim()
if (!s) return null
const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : 'https://' + s
try {
const u = new URL(withScheme)
if (!u.hostname) return null
return u.origin
} catch (e) { return null }
}
export async function loadRemote() {
return loadRemoteFile()
}
export async function chooseLocal() {
await saveRemoteFile({ mode: 'local' })
}
export async function forgetRemote() {
await saveRemoteFile({ mode: 'local' })
setRemoteAuth('', null)
}
// Redeems the pairing code, wires api.js at the resolved base, and persists the connection so
// boot() can restore it on the next launch.
export async function connect(rawUrl, code) {
const base = normalizeServerUrl(rawUrl)
if (!base) throw new Error('Enter a valid server address')
const { token, user } = await pairRedeem(base, String(code || '').trim())
setRemoteAuth(base, token)
await saveRemoteFile({ mode: 'remote', base, token, user })
return user
}
+27
View File
@@ -0,0 +1,27 @@
// @vitest-environment happy-dom
import { describe, expect, it } from 'vitest'
import { normalizeServerUrl } from './remote.js'
// The pairing flow lives or dies on this being forgiving about what someone types on a phone
// keyboard, while still refusing input that can't possibly be a server address.
describe('normalizeServerUrl', () => {
it('accepts a bare host and adds https://', () => {
expect(normalizeServerUrl('gym.example.com')).toBe('https://gym.example.com')
})
it('keeps an explicit scheme, including http for LAN testing', () => {
expect(normalizeServerUrl('http://192.168.1.20:8080')).toBe('http://192.168.1.20:8080')
expect(normalizeServerUrl('https://gym.example.com')).toBe('https://gym.example.com')
})
it('trims whitespace and a trailing path/slash down to the origin', () => {
expect(normalizeServerUrl(' gym.example.com/ ')).toBe('https://gym.example.com')
expect(normalizeServerUrl('https://gym.example.com/some/path')).toBe('https://gym.example.com')
})
it('rejects empty or unusable input', () => {
for (const v of ['', ' ', null, undefined, 'not a url at all!!']) {
expect(normalizeServerUrl(v)).toBe(null)
}
})
})
+73
View File
@@ -0,0 +1,73 @@
// @vitest-environment happy-dom
// The session note shipped with a hole in it: buildCompletedWorkout read `active.note` and
// nothing in the app ever wrote it, so the only way to get one was after the fact — and that
// path threw the text away unless you happened to tab out of the field first.
import { describe, expect, it, beforeEach, afterEach } from 'vitest'
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { sessionNoteSheet, workoutDetailSheet } from '../sheets.jsx'
import { buildCompletedWorkout } from './finish-workout.js'
const mounted = []
function render(open) {
open()
const sheet = useUI.getState().sheets.at(-1)
const host = document.createElement('div')
document.body.appendChild(host)
const root = createRoot(host)
mounted.push(root)
act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
return host
}
const type = (el, value) => {
Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
el.dispatchEvent(new Event('input', { bubbles: true }))
}
const unmountAll = () => act(() => { mounted.splice(0).forEach(r => r.unmount()) })
const workout = () => ({
id: 'w1', d: '2026-08-25', start: 1, end: 2, name: 'Push', vol: 100,
entries: [{ id: 'bench', sets: [{ w: 100, r: 5, done: true }] }], prs: [],
})
describe('session note', () => {
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
useUI.setState({ sheets: [] })
document.body.innerHTML = ''
})
afterEach(unmountAll)
it('can be written during the workout and survives finishing', () => {
useStore.setState(s => ({
S: { ...s.S, active: { id: 'w1', d: '2026-08-25', start: 1, name: 'Push', entries: [{ id: 'bench', sets: [] }] } },
}))
const host = render(() => sessionNoteSheet())
act(() => { type(host.querySelector('textarea'), 'slept badly, still hit it') })
act(() => { [...host.querySelectorAll('button')].find(b => /save/i.test(b.textContent)).click() })
const A = useStore.getState().S.active
expect(A.note).toBe('slept badly, still hit it')
// The path buildCompletedWorkout already had a test for is now actually reachable.
expect(buildCompletedWorkout(A, { end: 2 }).note).toBe('slept badly, still hit it')
})
it('is kept when the history sheet is dismissed without blurring the field', () => {
useStore.setState(s => ({ S: { ...s.S, workouts: [workout()] } }))
const host = render(() => workoutDetailSheet(useStore.getState().S.workouts[0]))
act(() => { type(host.querySelector('textarea'), 'good session') })
// Escape / Android back / swipe all unmount without a blur.
unmountAll()
expect(useStore.getState().S.workouts[0].note).toBe('good session')
})
it('clearing it removes the note rather than storing an empty string', () => {
useStore.setState(s => ({ S: { ...s.S, workouts: [{ ...workout(), note: 'old' }] } }))
const host = render(() => workoutDetailSheet(useStore.getState().S.workouts[0]))
act(() => { type(host.querySelector('textarea'), ' ') })
unmountAll()
expect(useStore.getState().S.workouts[0].note).toBeUndefined()
})
})
+5 -4
View File
@@ -11,6 +11,7 @@ import { STRENGTH_FULL_MS, STRENGTH_HALF_LIFE_MS, STRENGTH_FLOOR, halfLifeDecay
import { musclesOf } from './muscles.js'
import { EXIDX } from './exercises.js'
import { isWarmupRow } from './workout-model.js'
import { exerciseNameFor } from './i18n-core.js'
const round1 = value => Math.round(value * 10) / 10
@@ -61,11 +62,11 @@ export function primaryMuscleOf(entry) {
return best
}
function exerciseName(entry) {
function resolvedExerciseName(entry) {
// Imported history often has no name snapshot (entries are { id, sets, topW }) - the
// catalogue (or the registered custom) is the canonical name source.
const ex = entry && typeof entry === 'object' ? EXIDX[entry.id] : null
if (ex?.n) return ex.n
if (ex?.n) return exerciseNameFor(ex)
if (entry?.muscleSnapshot?.n) return entry.muscleSnapshot.n
return entry && typeof entry === 'object' && entry.n ? entry.n : null
}
@@ -97,7 +98,7 @@ export function strengthExerciseRows(S, now) {
const decay = lastAt == null ? STRENGTH_FLOOR : strengthFromAge(Number(now) - lastAt)
rows.push({
id,
name: exerciseName(entry) || id,
name: resolvedExerciseName(entry) || id,
est: best.est,
estDate: best.d,
primary: primaryMuscleOf(entry) ? primaryMuscleOf(entry).slug : null,
@@ -129,7 +130,7 @@ export function strengthExerciseRowsForMuscle(S, now, slug) {
const primary = primaryMuscleOf(entry)
seen.set(entry.id, {
id: entry.id,
name: exerciseName(entry) || entry.id,
name: resolvedExerciseName(entry) || entry.id,
weight,
primary: primary ? primary.slug : null,
est: best.est,
+32
View File
@@ -10,6 +10,38 @@ export function setProgressHighWater(entry, previous = 0) {
return { isNew: done > previous, highWater: Math.max(previous, done) }
}
/**
* Whether completing a set should start a rest timer.
*
* A rest belongs after every completed set — the last set of an exercise included, because
* another exercise follows it and you rest before that one too. The only set with nothing
* left to time is the last set of the last exercise, where the session is over.
*
* Ordinary exercises used to "finish quietly" instead: an exercise started no rest on its
* closing set, so a two-set exercise timed one rest instead of two (issue #3) and a rest
* never carried across the gap into the next exercise. Supersets already did it this way.
*/
export function restAfterSet({ unitDone, lastUnit }) {
return !unitDone || !lastUnit
}
/**
* Whether re-checking an already-completed set should start a rest.
*
* The high-water rule deliberately swallows a re-check so that unchecking and re-checking
* finished work does not replay navigation or reopen sheets. But a re-check is still you
* telling the app a set is done, and that is the other half of issue #3 — "after the first
* set, sometimes a break doesn't appear". That is what it looks like when you uncheck a set
* to correct the reps after its rest has already run out: nothing times the rest you are
* actually about to take.
*
* So: fill a gap, never disturb a rest that is already counting down. A timer that is running
* belongs to the set you finished most recently, which is a better answer than restarting it.
*/
export function restOnRecheck({ timerRunning, unitDone, lastUnit }) {
return !timerRunning && restAfterSet({ unitDone, lastUnit })
}
// 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.
+39 -1
View File
@@ -1,8 +1,25 @@
import { describe, expect, it } from 'vitest'
import { setProgressHighWater, supersetFlowStep } from './supersetFlow.js'
import { setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from './supersetFlow.js'
const entry = done => ({ sets: done.map(value => ({ done: value })) })
describe('restAfterSet', () => {
it('rests between the sets of an exercise', () => {
expect(restAfterSet({ unitDone: false, lastUnit: false })).toBe(true)
expect(restAfterSet({ unitDone: false, lastUnit: true })).toBe(true)
})
// Issue #3: a two-set exercise timed one rest instead of two, because the closing set
// "finished quietly". The next exercise still follows it, so the rest belongs there.
it('rests after the closing set when another exercise follows', () => {
expect(restAfterSet({ unitDone: true, lastUnit: false })).toBe(true)
})
it('stays quiet only on the very last set of the session', () => {
expect(restAfterSet({ unitDone: true, lastUnit: true })).toBe(false)
})
})
describe('supersetFlowStep', () => {
it('does not create navigation or rest flow for a normal singleton exercise', () => {
const entries = [entry([true]), entry([false])]
@@ -34,3 +51,24 @@ describe('supersetFlowStep', () => {
})
})
})
// 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.
describe('rest on a re-check', () => {
it('starts the rest a swallowed re-check would otherwise cost you', () => {
expect(restOnRecheck({ timerRunning: false, unitDone: false, lastUnit: false })).toBe(true)
})
it('leaves a rest that is already counting alone', () => {
expect(restOnRecheck({ timerRunning: true, unitDone: false, lastUnit: false })).toBe(false)
})
it('still stays quiet on the last set of the last exercise', () => {
expect(restOnRecheck({ timerRunning: false, unitDone: true, lastUnit: true })).toBe(false)
})
it('rests after closing an exercise that is not the last one', () => {
expect(restOnRecheck({ timerRunning: false, unitDone: true, lastUnit: false })).toBe(true)
})
})
@@ -0,0 +1,76 @@
import { describe, expect, it } from 'vitest'
import { workoutVolume, insertWarmupRow, buildSets } from './history.js'
import { applyPrescription } from './progression.js'
// The config sheet tells users warm-ups are "left out of volume, records and progression",
// and history.js repeats that as an invariant in a comment. Volume was the one place it
// was false — harmless while warm-ups were hand-added and rare, wrong now that a routine
// plans them by default and the number is written into the saved workout for good.
describe('warm-ups and volume', () => {
const w = {
entries: [{
id: 'bench',
sets: [
{ w: 50, r: 5, done: true, phase: 'warmup', warmup: true },
{ w: 75, r: 5, done: true, phase: 'warmup', warmup: true },
{ w: 87.5, r: 5, done: true, phase: 'warmup', warmup: true },
{ w: 100, r: 5, done: true },
{ w: 100, r: 5, done: true },
{ w: 100, r: 5, done: true },
],
}],
}
it('counts only the work sets', () => {
expect(workoutVolume(w)).toBe(1500)
})
it('a warm-up adds nothing, whatever it weighs', () => {
const heavy = { entries: [{ id: 'b', sets: [{ w: 200, r: 10, done: true, phase: 'warmup', warmup: true }] }] }
expect(workoutVolume(heavy)).toBe(0)
})
})
// A warm-up must never be heavier than the set it warms you up for. The ramp branch clamps
// to the work weight; the early-return branch did not, so a hand-edited warm-up above the
// work weight propagated into every warm-up added after it.
describe('a warm-up never outweighs the work set', () => {
// The 120 is something the user typed, and it stays: silently rewriting their own edit
// would be worse than leaving it. What must not happen is the NEW row inheriting it, which
// is how one bad number used to spread through the whole warm-up block.
it('does not copy a hand-edited warm-up that sits above the work weight', () => {
const rows = [{ warmup: true, phase: 'warmup', w: 120, r: 5 }, { w: 100, r: 5 }]
const out = insertWarmupRow(rows, 'reps', { reps: 5 }, 2.5)
expect(out.map(r => r.w)).toEqual([120, 100, 100])
expect(out[1].phase).toBe('warmup')
})
it('still ramps normally when the previous warm-up is below the work weight', () => {
const rows = [{ warmup: true, phase: 'warmup', w: 50, r: 5 }, { w: 100, r: 5 }]
const out = insertWarmupRow(rows, 'reps', { reps: 5 }, 2.5)
expect(out.filter(r => r.phase === 'warmup').map(r => r.w)).toEqual([50, 75])
})
})
// buildSets prepends the warm-ups, then applyPrescription rewrites the WORK rows only — so a
// ramp built against last session's weight is stale the moment progression moves. On a deload
// that put the last warm-up above every work set.
describe('the ramp follows the prescribed weight', () => {
const S = { workouts: [], exWeights: {}, routines: [] }
const cfg = { id: 'bench', sets: 3, reps: 5, weight: 100, warmupSets: 2 }
it('re-ramps after a deload instead of aiming at the old weight', () => {
const rows = applyPrescription(buildSets(S, cfg, { step: 2.5 }), { kind: 'deload', weight: 50 })
const warm = rows.filter(r => r.phase === 'warmup').map(r => r.w)
const work = rows.filter(r => r.phase !== 'warmup').map(r => r.w)
expect(work).toEqual([50, 50, 50])
for (const x of warm) expect(x).toBeLessThanOrEqual(50)
expect(warm).toEqual([25, 37.5])
})
it('re-ramps after a bump', () => {
const rows = applyPrescription(buildSets(S, cfg, { step: 2.5 }), { kind: 'up', weight: 150 })
expect(rows.filter(r => r.phase !== 'warmup').map(r => r.w)).toEqual([150, 150, 150])
expect(rows.filter(r => r.phase === 'warmup').map(r => r.w)).toEqual([75, 112.5])
})
})
+39
View File
@@ -0,0 +1,39 @@
import { describe, expect, it } from 'vitest'
import { buildSets } from './history.js'
// A session that logged warm-ups, the way finish-workout persists it: warm-up rows and work
// rows in one `sets` array, all done.
const S = {
workouts: [{
d: '2026-08-24',
entries: [{
id: 'bench',
target: { id: 'bench', sets: 3, reps: 5, weight: 100 },
sets: [
{ w: 50, r: 5, done: true, phase: 'warmup', warmup: true },
{ w: 75, r: 5, done: true, phase: 'warmup', warmup: true },
{ w: 100, r: 5, done: true },
{ w: 100, r: 5, done: true },
{ w: 100, r: 5, done: true },
],
}],
}],
exWeights: {}, // no confirmed working weight for this exercise
routines: [],
}
describe('seeding the next session from one that had warm-ups', () => {
it('does not seed the work sets from the warm-up rows', () => {
const cfg = { id: 'bench', sets: 3, reps: 5, weight: 100 }
const rows = buildSets(S, cfg)
const work = rows.filter(r => r.phase !== 'warmup')
expect(work.map(r => r.w)).toEqual([100, 100, 100])
})
it('freestyle reproducing last time also skips the warm-ups', () => {
const cfg = { id: 'bench', sets: 3, reps: 5, weight: 100 }
const rows = buildSets(S, cfg, { preferLast: true })
const work = rows.filter(r => r.phase !== 'warmup')
expect(work.map(r => r.w)).toEqual([100, 100, 100])
})
})
+106
View File
@@ -22,6 +22,112 @@ export function isWarmupRow(set) {
return phaseForSet(set) === 'warmup'
}
// A row's shape beyond warm-up/work: 'straight' (default), 'dropset' (a main set followed by
// weight drops logged with no rest) or 'restpause' (an activation set followed by short-rest
// bursts). Both extras ride on the row itself — same card, not a new set in the array — the
// same trick `phase` uses for warm-ups, so the rest of the app can keep reading a row's own
// `w`/`r` and stay correct without knowing this field exists.
export function setType(set) {
const source = objectOf(set)
return source.type === 'dropset' || source.type === 'restpause' ? source.type : 'straight'
}
export const isDropSet = set => setType(set) === 'dropset'
export const isRestPauseSet = set => setType(set) === 'restpause'
/** A drop-set's weight drops, oldest first; empty for anything else. */
export function dropsOf(set) {
const source = objectOf(set)
return isDropSet(source) && Array.isArray(source.drops) ? source.drops : []
}
/** A rest-pause set's short-rest bursts, oldest first; empty for anything else. */
export function clustersOf(set) {
const source = objectOf(set)
return isRestPauseSet(source) && Array.isArray(source.clusters) ? source.clusters : []
}
/**
* Weight x reps from a drop-set's drops, on top of its own main set. The 1RM estimate and the
* progression engine deliberately read only a row's own `w`/`r` (the heaviest effort), so this
* is the one place a drop-set's extra volume gets added back in for totals.
*
* A rest-pause row is different: its own `r` IS the total (every burst's reps included), and
* `clusters` is only how that total breaks down — not extra volume on top of it. Adding
* `clustersOf(set)` here as well would double-count the same reps twice.
*/
export function extraVolumeOf(set) {
const drops = dropsOf(set)
return drops.reduce((v, d) => v + (Number(d?.w) || 0) * (Number(d?.r) || 0), 0)
}
/** Append a weight drop to a row, marking it a drop-set. */
export function addDrop(set, drop) {
const prev = Array.isArray(objectOf(set).drops) ? objectOf(set).drops : []
return { ...objectOf(set), type: 'dropset', drops: [...prev, { w: Number(drop?.w) || 0, r: Number(drop?.r) || 0 }] }
}
/** Append a short-rest burst to a row, marking it a rest-pause set. */
export function addCluster(set, cluster) {
const prev = Array.isArray(objectOf(set).clusters) ? objectOf(set).clusters : []
return { ...objectOf(set), type: 'restpause', clusters: [...prev, { r: Number(cluster?.r) || 0, restSec: Number(cluster?.restSec) || 0 }] }
}
/** Remove one drop by index. Clearing the last one reverts the row to a straight set. */
export function removeDropAt(set, i) {
const drops = (objectOf(set).drops || []).filter((_, idx) => idx !== i)
return drops.length ? { ...objectOf(set), drops } : { ...objectOf(set), type: 'straight', drops }
}
/** Remove one burst by index. Clearing the last one reverts the row to a straight set. */
export function removeClusterAt(set, i) {
const clusters = (objectOf(set).clusters || []).filter((_, idx) => idx !== i)
return clusters.length ? { ...objectOf(set), clusters } : { ...objectOf(set), type: 'straight', clusters }
}
/** Patch one drop's fields in place (weight/reps steppers edit an existing drop). */
export function setDropAt(set, i, patch) {
const drops = (objectOf(set).drops || []).slice()
if (!drops[i]) return set
drops[i] = { ...drops[i], ...patch }
return { ...objectOf(set), drops }
}
/** Patch one burst's fields in place (a reps stepper edits an existing burst). */
export function setClusterAt(set, i, patch) {
const clusters = (objectOf(set).clusters || []).slice()
if (!clusters[i]) return set
clusters[i] = { ...clusters[i], ...patch }
return { ...objectOf(set), clusters }
}
/** Suggested weight for the next drop: pct% lighter than the previous weight, rounded to .5. */
export function nextDropWeight(prevWeight, pct = 20) {
const p = Math.min(90, Math.max(1, Number(pct) || 20))
return Math.round(Math.max(0, (Number(prevWeight) || 0) * (1 - p / 100)) * 2) / 2
}
/** Suggested reps for the next rest-pause burst: roughly half the previous rep count. */
export function nextBurstReps(prevReps) {
return Math.max(1, Math.round((Number(prevReps) || 0) / 2))
}
/**
* Split a rest-pause total (the extra reps you want past the activation set) into a descending,
* roughly-halving sequence of bursts that adds back up to it — e.g. 12 -> [6, 3, 2, 1]. This is
* what a planned rest-pause exercise configures directly, rather than a burst count picked by
* hand: you say how many reps you want out of the whole rest-pause portion, not how many rests.
*/
export function splitBurstReps(total) {
const bursts = []
let remaining = Math.max(0, Math.round(Number(total) || 0))
while (remaining > 0) {
const burst = Math.min(remaining, nextBurstReps(remaining))
bursts.push(burst)
remaining -= burst
}
return bursts
}
export function normalizeMode(value, fallback = 'reps') {
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
if (MODES.includes(token)) return token
+181
View File
@@ -0,0 +1,181 @@
import { describe, it, expect } from 'vitest'
import {
phaseForSet, isWarmupRow, modeForSet, modeForEntry,
setType, isDropSet, isRestPauseSet, dropsOf, clustersOf, extraVolumeOf,
addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt,
nextDropWeight, nextBurstReps, splitBurstReps,
} from './workout-model.js'
describe('phaseForSet / isWarmupRow', () => {
it('reads both the explicit phase and the legacy boolean', () => {
expect(isWarmupRow({ phase: 'warmup' })).toBe(true)
expect(isWarmupRow({ warmup: true })).toBe(true)
expect(isWarmupRow({ phase: 'work' })).toBe(false)
expect(isWarmupRow({})).toBe(false)
})
})
describe('setType / isDropSet / isRestPauseSet', () => {
it('defaults to straight for anything without a recognised type', () => {
expect(setType({})).toBe('straight')
expect(setType({ type: 'nonsense' })).toBe('straight')
expect(setType(null)).toBe('straight')
expect(isDropSet({})).toBe(false)
expect(isRestPauseSet({})).toBe(false)
})
it('recognises drop-set and rest-pause rows', () => {
expect(setType({ type: 'dropset' })).toBe('dropset')
expect(isDropSet({ type: 'dropset' })).toBe(true)
expect(setType({ type: 'restpause' })).toBe('restpause')
expect(isRestPauseSet({ type: 'restpause' })).toBe(true)
})
it('is a separate axis from warm-up — a row is not both at once by construction, but phase never leaks into type', () => {
expect(setType({ phase: 'warmup', type: 'dropset' })).toBe('dropset')
expect(isWarmupRow({ phase: 'warmup', type: 'dropset' })).toBe(true)
})
})
describe('dropsOf / clustersOf', () => {
it('only return rows for their own type', () => {
const drop = { type: 'dropset', drops: [{ w: 80, r: 5 }] }
const burst = { type: 'restpause', clusters: [{ r: 4, restSec: 15 }] }
expect(dropsOf(drop)).toEqual([{ w: 80, r: 5 }])
expect(clustersOf(drop)).toEqual([])
expect(clustersOf(burst)).toEqual([{ r: 4, restSec: 15 }])
expect(dropsOf(burst)).toEqual([])
})
it('is defensive about missing/malformed arrays', () => {
expect(dropsOf({ type: 'dropset' })).toEqual([])
expect(dropsOf({ type: 'dropset', drops: 'nope' })).toEqual([])
expect(clustersOf(null)).toEqual([])
})
})
describe('extraVolumeOf', () => {
it('sums weight x reps across a drop-set\'s own drops', () => {
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 6 }] }
expect(extraVolumeOf(set)).toBe(80 * 5 + 60 * 6)
})
it('is zero for rest-pause — its own r is already the total across every burst, so clusters are a breakdown, not extra volume', () => {
const set = { type: 'restpause', w: 60, r: 20, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 } ] }
expect(extraVolumeOf(set)).toBe(0)
})
it('is zero for a straight or warm-up set', () => {
expect(extraVolumeOf({ w: 100, r: 5 })).toBe(0)
expect(extraVolumeOf({ phase: 'warmup', w: 20, r: 8 })).toBe(0)
})
})
describe('addDrop / addCluster', () => {
it('appends a drop and stamps the row as a drop-set', () => {
const set = { w: 100, r: 5, done: true }
const next = addDrop(set, { w: 80, r: 5 })
expect(next.type).toBe('dropset')
expect(next.drops).toEqual([{ w: 80, r: 5 }])
expect(set.drops).toBeUndefined() // pure — the original row is untouched
expect(addDrop(next, { w: 60, r: 4 }).drops).toEqual([{ w: 80, r: 5 }, { w: 60, r: 4 }])
})
it('appends a burst and stamps the row as a rest-pause set', () => {
const set = { w: 60, r: 8, done: true }
const next = addCluster(set, { r: 4, restSec: 15 })
expect(next.type).toBe('restpause')
expect(next.clusters).toEqual([{ r: 4, restSec: 15 }])
})
})
describe('removeDropAt / removeClusterAt', () => {
it('removes one entry by index, leaving the rest in place', () => {
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
expect(removeDropAt(set, 0).drops).toEqual([{ w: 60, r: 5 }])
})
it('removes one burst by index', () => {
const set = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] }
expect(removeClusterAt(set, 1).clusters).toEqual([{ r: 4, restSec: 15 }])
})
it('reverts the row to a straight set once its last drop/burst is removed', () => {
const drop = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }
expect(removeDropAt(drop, 0)).toEqual({ type: 'straight', w: 100, r: 5, drops: [] })
expect(isDropSet(removeDropAt(drop, 0))).toBe(false)
const burst = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }] }
expect(removeClusterAt(burst, 0)).toEqual({ type: 'straight', w: 60, r: 8, clusters: [] })
expect(isRestPauseSet(removeClusterAt(burst, 0))).toBe(false)
})
})
describe('setDropAt / setClusterAt', () => {
it('patches one drop\'s fields, leaving the others untouched', () => {
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
expect(setDropAt(set, 0, { w: 82.5 }).drops).toEqual([{ w: 82.5, r: 5 }, { w: 60, r: 5 }])
expect(setDropAt(set, 1, { r: 6 }).drops).toEqual([{ w: 80, r: 5 }, { w: 60, r: 6 }])
})
it('patches one burst\'s reps', () => {
const set = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }] }
expect(setClusterAt(set, 0, { r: 5 }).clusters).toEqual([{ r: 5, restSec: 15 }])
})
it('is a no-op for an index that does not exist', () => {
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }
expect(setDropAt(set, 3, { w: 1 })).toBe(set)
})
})
describe('nextDropWeight / nextBurstReps', () => {
it('drops by the given percentage, rounded to the nearest .5', () => {
expect(nextDropWeight(100, 20)).toBe(80)
expect(nextDropWeight(80, 20)).toBe(64)
expect(nextDropWeight(61, 10)).toBe(55)
})
it('defaults to 20% and never goes negative', () => {
expect(nextDropWeight(100)).toBe(80)
expect(nextDropWeight(0, 20)).toBe(0)
})
it('roughly halves the previous rep count, floored at 1', () => {
expect(nextBurstReps(8)).toBe(4)
expect(nextBurstReps(1)).toBe(1)
expect(nextBurstReps(0)).toBe(1)
})
})
describe('splitBurstReps', () => {
it('splits a total into a descending, roughly-halving sequence that adds back up to it', () => {
expect(splitBurstReps(12)).toEqual([6, 3, 2, 1])
expect(splitBurstReps(6)).toEqual([3, 2, 1])
expect(splitBurstReps(1)).toEqual([1])
})
it('every split sums exactly to the requested total', () => {
for (const total of [1, 2, 3, 5, 7, 10, 15, 20, 33]) {
expect(splitBurstReps(total).reduce((a, b) => a + b, 0)).toBe(total)
}
})
it('is empty for zero or invalid input', () => {
expect(splitBurstReps(0)).toEqual([])
expect(splitBurstReps(-5)).toEqual([])
expect(splitBurstReps(undefined)).toEqual([])
})
})
describe('modeForSet / modeForEntry stay reps-mode for drop-sets and rest-pause sets', () => {
it('infers reps mode from the row\'s own r field regardless of type', () => {
expect(modeForSet({ type: 'dropset', w: 100, r: 5 })).toBe('reps')
expect(modeForSet({ type: 'restpause', w: 60, r: 8 })).toBe('reps')
})
it('an entry mixing straight and drop-set rows still reads as one reps-mode entry', () => {
const entry = { sets: [{ w: 100, r: 5 }, { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }] }
expect(modeForEntry(entry)).toBe('reps')
})
})
+96 -1
View File
@@ -3,6 +3,7 @@ export default {
// --- generic ---
'Confirm': 'Bestätigen',
'Cancel': 'Abbrechen',
'Press back again to exit': 'Zum Beenden erneut zurück drücken',
'Delete': 'Löschen',
'Save': 'Speichern',
'Import': 'Importieren',
@@ -170,6 +171,24 @@ export default {
'Warm-up': 'Aufwärmen',
'Add warm-up set': 'Aufwärmsatz hinzufügen',
'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)',
'Drop-set / rest-pause': 'Dropsatz / Rest-Pause',
'Intensifier': 'Intensivierungstechnik',
'None': 'Keine',
'Drop-set': 'Dropsatz',
'Rest-pause': 'Rest-Pause',
'Drops': 'Dropsätze',
'Weight drop (%)': 'Gewichtsreduktion (%)',
'Rest-pause reps': 'Rest-Pause-Wiederholungen',
'Rest-pause rest': 'Rest-Pause-Pause',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Jeder Satz wird zum Dropsatz: nach dem Hauptsatz {0} weitere Stufe(n) ohne Pause, jede etwa {1}% leichter.',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Jeder Satz wird zu Rest-Pause: {0} Wiederholungen zu Beginn, dann {1} weitere in kurzen Bursts, mit {2}s Pause davor, dabei jedes Mal etwa halbiert.',
'Cardio logged': 'Cardio eingetragen',
'Discard workout?': 'Training verwerfen?',
'The sets you logged in this session will be lost.': 'Die in dieser Einheit eingetragenen Sätze gehen verloren.',
@@ -217,6 +236,7 @@ export default {
'Load starter plan (Push / Pull / Legs)': 'Starterplan laden (Push / Pull / Beine)',
// --- routine edit ---
'Superset with exercise above': 'Supersatz mit der Übung darüber',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Notiz (optional) — Hinweise zur Belastung, z. B. „nur die Stange, dann pro Satz +1 Scheibe pro Seite“, was immer du dir merken willst',
'No exercises yet — add your first one.': 'Noch keine Übungen — füge deine erste hinzu.',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Tippe bei einer Übung auf die Verknüpfen-Taste, um sie mit der darüber zum Supersatz zu verbinden — du machst sie direkt nacheinander.',
'Delete routine?': 'Routine löschen?',
@@ -270,6 +290,7 @@ export default {
'Theme': 'Design',
'Dark': 'Dunkel',
'Light': 'Hell',
'System': 'System',
'Accent color': 'Akzentfarbe',
'General': 'Allgemein',
'During a workout': 'Während des Trainings',
@@ -282,6 +303,8 @@ export default {
'Data': 'Daten',
'Export backup (JSON)': 'Backup exportieren (JSON)',
'Import backup': 'Backup importieren',
'Auto-backup on changes': 'Automatische Sicherung bei Änderungen',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Speichert nach jedem beendeten Training oder jeder bearbeiteten Routine eine datierte Kopie im Ordner „Dokumente" — richte eine Sync-App darauf aus oder kopiere die Datei von Hand.',
'Reset everything?': 'Alles zurücksetzen?',
'Reset everything': 'Alles zurücksetzen',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Löscht Plan, Trainings und Körpergewicht auf diesem Gerät. Das kann nicht rückgängig gemacht werden.',
@@ -737,5 +760,77 @@ export default {
'secondary': 'sekundär',
'No exercises with an estimated 1RM yet.': 'Noch keine Übungen mit geschätztem 1RM.',
'Tap a muscle to see its exercises.': 'Tippe auf einen Muskel, um seine Übungen zu sehen.',
'Unpair': 'Trennen'
'Unpair': 'Trennen',
// --- equipment profiles ---
'Showing all equipment': 'Alle Geräte werden angezeigt',
'Showing what you have in "{0}"': 'Angezeigt wird, was du in „{0}“ hast',
'Show all equipment': 'Alle Geräte zeigen',
'Filter by "{0}"': 'Nach „{0}“ filtern',
'Edit profile': 'Profil bearbeiten',
'New equipment profile': 'Neues Geräteprofil',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'Benenne es nach deinem Trainingsort — z. B. „Zuhause“ oder „Gym“ — und hake dann ab, was du dort hast.',
'Profile name': 'Profilname',
'Body-weight exercises are always available, in every profile.': 'Körpergewichtsübungen sind immer verfügbar, in jedem Profil.',
'{0} of {1} exercises need equipment outside "{2}"': '{0} von {1} Übungen brauchen Geräte außerhalb von „{2}“',
'Needs {0} — not in your active profile': 'Braucht {0} — nicht in deinem aktiven Profil',
'Filter by equipment': 'Nach Geräten filtern',
'Active profile': 'Aktives Profil',
'{0} equipment types': '{0} Gerätearten',
'Add equipment profile': 'Geräteprofil hinzufügen',
'Delete profile?': 'Profil löschen?',
'"{0}" and its equipment list will be removed.': '„{0}“ und die zugehörige Geräteliste werden entfernt.',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtert die Übungsbibliothek und die Auswahl und markiert Übungen in Routinen, die Geräte brauchen, die du im aktiven Profil nicht hast.',
// --- muscle groups ---
'Primary muscle groups': 'Primäre Muskelgruppen',
'Additional muscle groups': 'Zusätzliche Muskelgruppen',
'No explicit muscle group': 'Keine explizite Muskelgruppe',
// "Connect to my server" (mobile app pairing)
'Your server': 'Dein Server',
'Synced with your openGym server.': 'Mit deinem openGym-Server synchronisiert.',
'Disconnect': 'Trennen',
'Disconnect from your server?': 'Verbindung zum Server trennen?',
'Your data is synced to your server first, then this device switches back to local-only.': 'Deine Daten werden zuerst mit deinem Server synchronisiert, dann wechselt dieses Gerät zurück in den lokalen Modus.',
'Disconnected — back to local-only': 'Verbindung getrennt — zurück im lokalen Modus',
'Connect to my server': 'Mit meinem Server verbinden',
'Sync this device to your own self-hosted openGym instead.': 'Dieses Gerät stattdessen mit deinem eigenen self-hosted openGym synchronisieren.',
'Pair the mobile app': 'Mobile App koppeln',
'Connect the openGym app on your phone to this account.': 'Verbinde die openGym-App auf deinem Handy mit diesem Konto.',
'Could not generate a code': 'Code konnte nicht erstellt werden',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'Wähle in der openGym-App „Mit meinem Server verbinden“, gib dann diese Adresse und den Code unten ein. Er läuft in 5 Minuten ab.',
'Enter your server address and the code': 'Serveradresse und Code eingeben',
'Connected': 'Verbunden',
'Could not connect': 'Verbindung fehlgeschlagen',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'Öffne auf der openGym-Seite, bei der du bereits angemeldet bist, Einstellungen → „Mobile App koppeln“, und gib dann deren Adresse und den dort angezeigten Code ein.',
'Server address (e.g. gym.example.com)': 'Serveradresse (z. B. gym.example.com)',
'Pairing code': 'Kopplungscode',
'Connecting…': 'Verbinde …',
'Connect': 'Verbinden',
'How do you want to use openGym?': 'Wie möchtest du openGym nutzen?',
'Use on this device': 'Auf diesem Gerät nutzen',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Lokal behält alles auf diesem Handy. Verbinden synchronisiert stattdessen mit deinem eigenen openGym-Server — du kannst das später in den Einstellungen ändern.',
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — erledigt',
'Workout done': 'Training erledigt',
'reps': 'Wdh.',
'Most reps in a set per workout': 'Meiste Wdh. in einem Satz pro Training',
'Warm-up sets': 'Aufwärmsätze',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Kommen vor deine Arbeitssätze und zählen nicht für Volumen, Rekorde und Progression. Jeder halbiert den Abstand zum Arbeitsgewicht — im Training kannst du sie trotzdem jederzeit ändern.',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Aufwärmsätze vor den Arbeitssätzen, damit du sie nicht jedes Mal von Hand hinzufügen musst.',
'Note': 'Notiz',
'This session': 'Dieses Training',
'How it went, what to change — kept with today’s workout.': 'Wie es lief, was du ändern willst — bleibt beim heutigen Training.',
'Show this next time': 'Nächstes Mal anzeigen',
'Brings it up again the next time you train this exercise.': 'Erscheint wieder, wenn du diese Übung das nächste Mal trainierst.',
'Always for this exercise': 'Immer bei dieser Übung',
'Seat height, pin position, a form cue — shown every session.': 'Sitzhöhe, Pin-Position, ein Hinweis zur Ausführung — bei jedem Training sichtbar.',
'From {0}:': 'Vom {0}:',
'Session note': 'Notiz zum Training',
'Add session note': 'Notiz zum Training',
'Edit session note': 'Notiz bearbeiten',
'How the session went as a whole.': 'Wie das Training insgesamt lief.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-Pause trainiert immer als ein Aufwärmsatz mit dieser Wiederholungszahl und ein Rest-Pause-Arbeitssatz — „Sätze“ wird nicht verwendet.'
}
+96 -1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Confirmar',
'Cancel': 'Cancelar',
'Press back again to exit': 'Pulsa atrás otra vez para salir',
'Delete': 'Eliminar',
'Save': 'Guardar',
'Import': 'Importar',
@@ -163,6 +164,24 @@ export default {
'Warm-up': 'Calentamiento',
'Add warm-up set': 'Añadir serie de calentamiento',
'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)',
'Drop-set / rest-pause': 'Series descendentes / rest-pause',
'Intensifier': 'Intensificador',
'None': 'Ninguno',
'Drop-set': 'Serie descendente',
'Rest-pause': 'Rest-pause',
'Drops': 'Bajadas',
'Weight drop (%)': 'Bajada de peso (%)',
'Rest-pause reps': 'Repeticiones rest-pause',
'Rest-pause rest': 'Descanso rest-pause',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Cada serie se convierte en una serie descendente: tras la serie principal, {0} bajada(s) sin descanso, cada una un {1}% más ligera aprox.',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Cada serie se convierte en rest-pause: {0} reps para empezar, y {1} más repartidas en ráfagas cortas, con {2}s de descanso antes de cada una, bajando aprox. a la mitad cada vez.',
'Cardio logged': 'Cardio registrado',
'Discard workout?': '¿Descartar entrenamiento?',
'The sets you logged in this session will be lost.': 'Las series registradas en esta sesión se perderán.',
@@ -206,6 +225,7 @@ export default {
'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)',
'Superset with exercise above': 'Superserie con el ejercicio de arriba',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Nota (opcional) — indicaciones de carga, ej. «solo barra y +1 disco por lado en cada serie», lo que quieras recordar',
'No exercises yet — add your first one.': 'Aún no hay ejercicios — añade el primero.',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Toca el botón de enlace en un ejercicio para hacer superserie con el de arriba — los harás seguidos.',
'Delete routine?': '¿Eliminar rutina?',
@@ -256,6 +276,7 @@ export default {
'Theme': 'Tema',
'Dark': 'Oscuro',
'Light': 'Claro',
'System': 'Sistema',
'Accent color': 'Color de acento',
'General': 'General',
'During a workout': 'Durante el entrenamiento',
@@ -268,6 +289,8 @@ export default {
'Data': 'Datos',
'Export backup (JSON)': 'Exportar copia (JSON)',
'Import backup': 'Importar copia',
'Auto-backup on changes': 'Copia automática al modificar',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Guarda una copia fechada en la carpeta Documentos al terminar un entrenamiento o editar una rutina — apunta una app de sincronización a esa carpeta, o copia el archivo a mano.',
'Reset everything?': '¿Restablecer todo?',
'Reset everything': 'Restablecer todo',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina tu plan, entrenamientos y peso corporal en este dispositivo. No se puede deshacer.',
@@ -720,5 +743,77 @@ export default {
'secondary': 'secundario',
'No exercises with an estimated 1RM yet.': 'Aún no hay ejercicios con 1RM estimado.',
'Tap a muscle to see its exercises.': 'Toca un músculo para ver sus ejercicios.',
'Unpair': 'Desvincular'
'Unpair': 'Desvincular',
// --- equipment profiles ---
'Showing all equipment': 'Mostrando todo el equipo',
'Showing what you have in "{0}"': 'Mostrando lo que tienes en «{0}»',
'Show all equipment': 'Mostrar todo el equipo',
'Filter by "{0}"': 'Filtrar por «{0}»',
'Edit profile': 'Editar perfil',
'New equipment profile': 'Nuevo perfil de equipo',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'Ponle el nombre del sitio donde entrenas — p. ej. «Casa» o «Gimnasio» — y marca lo que tienes allí.',
'Profile name': 'Nombre del perfil',
'Body-weight exercises are always available, in every profile.': 'Los ejercicios con peso corporal están siempre disponibles, en todos los perfiles.',
'{0} of {1} exercises need equipment outside "{2}"': '{0} de {1} ejercicios necesitan equipo fuera de «{2}»',
'Needs {0} — not in your active profile': 'Necesita {0} — no está en tu perfil activo',
'Filter by equipment': 'Filtrar por equipo',
'Active profile': 'Perfil activo',
'{0} equipment types': '{0} tipos de equipo',
'Add equipment profile': 'Añadir perfil de equipo',
'Delete profile?': '¿Eliminar perfil?',
'"{0}" and its equipment list will be removed.': '«{0}» y su lista de equipo se eliminarán.',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtra la biblioteca de ejercicios y el selector, y marca los ejercicios de las rutinas que necesitan algo que no tienes en el perfil activo.',
// --- muscle groups ---
'Primary muscle groups': 'Grupos musculares primarios',
'Additional muscle groups': 'Grupos musculares adicionales',
'No explicit muscle group': 'Sin grupo muscular explícito',
// "Connect to my server" (mobile app pairing)
'Your server': 'Tu servidor',
'Synced with your openGym server.': 'Sincronizado con tu servidor de openGym.',
'Disconnect': 'Desconectar',
'Disconnect from your server?': '¿Desconectar de tu servidor?',
'Your data is synced to your server first, then this device switches back to local-only.': 'Tus datos se sincronizan primero con tu servidor, y luego este dispositivo vuelve a modo local.',
'Disconnected — back to local-only': 'Desconectado — de vuelta a modo local',
'Connect to my server': 'Conectar a mi servidor',
'Sync this device to your own self-hosted openGym instead.': 'Sincroniza este dispositivo con tu propio openGym self-hosted.',
'Pair the mobile app': 'Emparejar la app móvil',
'Connect the openGym app on your phone to this account.': 'Conecta la app de openGym en tu móvil a esta cuenta.',
'Could not generate a code': 'No se pudo generar un código',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'En la app de openGym, elige «Conectar a mi servidor», luego introduce esta dirección y el código de abajo. Caduca en 5 minutos.',
'Enter your server address and the code': 'Introduce la dirección de tu servidor y el código',
'Connected': 'Conectado',
'Could not connect': 'No se pudo conectar',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'En Ajustes → «Emparejar la app móvil» del sitio de openGym en el que ya has iniciado sesión, luego introduce su dirección y el código que aparece ahí.',
'Server address (e.g. gym.example.com)': 'Dirección del servidor (p. ej. gym.example.com)',
'Pairing code': 'Código de emparejamiento',
'Connecting…': 'Conectando…',
'Connect': 'Conectar',
'How do you want to use openGym?': '¿Cómo quieres usar openGym?',
'Use on this device': 'Usar en este dispositivo',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantiene todo en este teléfono. Conectar sincroniza con tu propio servidor de openGym — puedes cambiarlo luego en Ajustes.',
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — hecho',
'Workout done': 'Entrenamiento hecho',
'reps': 'reps',
'Most reps in a set per workout': 'Más reps en una serie por entrenamiento',
'Warm-up sets': 'Series de calentamiento',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Se añaden antes de tus series de trabajo y no cuentan para el volumen, los récords ni la progresión. Cada una reduce a la mitad la distancia hasta el peso de trabajo — puedes cambiarlas durante la sesión.',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Series de aproximación antes de las series de trabajo, para no añadirlas a mano cada vez.',
'Note': 'Nota',
'This session': 'Esta sesión',
'How it went, what to change — kept with today’s workout.': 'Cómo fue, qué cambiar — se guarda con el entrenamiento de hoy.',
'Show this next time': 'Mostrar la próxima vez',
'Brings it up again the next time you train this exercise.': 'Vuelve a aparecer la próxima vez que entrenes este ejercicio.',
'Always for this exercise': 'Siempre en este ejercicio',
'Seat height, pin position, a form cue — shown every session.': 'Altura del asiento, posición del pin, una indicación técnica — visible en cada sesión.',
'From {0}:': 'Del {0}:',
'Session note': 'Nota de la sesión',
'Add session note': 'Añadir nota de la sesión',
'Edit session note': 'Editar nota de la sesión',
'How the session went as a whole.': 'Cómo fue la sesión en conjunto.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause siempre entrena como una serie de calentamiento con estas reps y una serie de trabajo rest-pause — «Series» no se usa.'
}
+96 -1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Confirmer',
'Cancel': 'Annuler',
'Press back again to exit': 'Appuyez de nouveau pour quitter',
'Delete': 'Supprimer',
'Save': 'Enregistrer',
'Import': 'Importer',
@@ -163,6 +164,24 @@ export default {
'Warm-up': 'Échauffement',
'Add warm-up set': 'Ajouter une série d’échauffement',
'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)',
'Drop-set / rest-pause': 'Drop-set / rest-pause',
'Intensifier': 'Intensificateur',
'None': 'Aucun',
'Drop-set': 'Drop-set',
'Rest-pause': 'Rest-pause',
'Drops': 'Drop sets',
'Weight drop (%)': 'Baisse de poids (%)',
'Rest-pause reps': 'Répétitions rest-pause',
'Rest-pause rest': 'Repos rest-pause',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Chaque série devient un drop-set : après la série principale, {0} baisse(s) sans repos, chacune environ {1}% plus légère.',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Chaque série devient rest-pause : {0} répétitions pour commencer, puis {1} de plus réparties en courtes rafales, avec {2}s de repos avant chacune, en diminuant environ de moitié à chaque fois.',
'Cardio logged': 'Cardio noté',
'Discard workout?': 'Abandonner la séance ?',
'The sets you logged in this session will be lost.': 'Les séries notées dans cette session seront perdues.',
@@ -206,6 +225,7 @@ export default {
'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)',
'Superset with exercise above': "Superset avec l'exercice au-dessus",
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Note (optionnelle) — indications de charge, ex. « barre seule puis +1 disque par côté à chaque série », tout ce que tu veux te rappeler',
'No exercises yet — add your first one.': 'Aucun exercice — ajoute le premier.',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Appuie sur le bouton de liaison d’un exercice pour le mettre en superset avec celui au-dessus — tu les enchaîneras.',
'Delete routine?': 'Supprimer la routine ?',
@@ -256,6 +276,7 @@ export default {
'Theme': 'Thème',
'Dark': 'Sombre',
'Light': 'Clair',
'System': 'Système',
'Accent color': "Couleur d'accent",
'General': 'Général',
'During a workout': 'Pendant la séance',
@@ -268,6 +289,8 @@ export default {
'Data': 'Données',
'Export backup (JSON)': 'Exporter une sauvegarde (JSON)',
'Import backup': 'Importer une sauvegarde',
'Auto-backup on changes': 'Sauvegarde automatique',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Enregistre une copie datée dans le dossier Documents après chaque entraînement terminé ou modification de routine — pointez une appli de synchronisation dessus, ou copiez le fichier à la main.',
'Reset everything?': 'Tout réinitialiser ?',
'Reset everything': 'Tout réinitialiser',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Supprime ton plan, tes séances et ton poids corporel sur cet appareil. Irréversible.',
@@ -720,5 +743,77 @@ export default {
'secondary': 'secondaire',
"No exercises with an estimated 1RM yet.": "Aucun exercice avec un 1RM estimé pour l'instant.",
'Tap a muscle to see its exercises.': 'Touchez un muscle pour voir ses exercices.',
'Unpair': 'Dissocier'
'Unpair': 'Dissocier',
// --- equipment profiles ---
'Showing all equipment': 'Tout l’équipement est affiché',
'Showing what you have in "{0}"': 'Affichage de ce que tu as dans « {0} »',
'Show all equipment': 'Afficher tout l’équipement',
'Filter by "{0}"': 'Filtrer par « {0} »',
'Edit profile': 'Modifier le profil',
'New equipment profile': 'Nouveau profil d’équipement',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'Nomme-le d’après ton lieu d’entraînement — p. ex. « Maison » ou « Salle » — puis coche ce que tu y as.',
'Profile name': 'Nom du profil',
'Body-weight exercises are always available, in every profile.': 'Les exercices au poids du corps sont toujours disponibles, dans tous les profils.',
'{0} of {1} exercises need equipment outside "{2}"': '{0} exercices sur {1} nécessitent un équipement hors de « {2} »',
'Needs {0} — not in your active profile': 'Nécessite {0} — absent de ton profil actif',
'Filter by equipment': 'Filtrer par équipement',
'Active profile': 'Profil actif',
'{0} equipment types': '{0} types d’équipement',
'Add equipment profile': 'Ajouter un profil d’équipement',
'Delete profile?': 'Supprimer le profil ?',
'"{0}" and its equipment list will be removed.': '« {0} » et sa liste d’équipement seront supprimés.',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtre la bibliothèque d’exercices et le sélecteur, et signale les exercices de routine qui nécessitent quelque chose que tu n’as pas dans le profil actif.',
// --- muscle groups ---
'Primary muscle groups': 'Groupes musculaires principaux',
'Additional muscle groups': 'Groupes musculaires supplémentaires',
'No explicit muscle group': 'Aucun groupe musculaire explicite',
// "Connect to my server" (mobile app pairing)
'Your server': 'Votre serveur',
'Synced with your openGym server.': 'Synchronisé avec votre serveur openGym.',
'Disconnect': 'Déconnecter',
'Disconnect from your server?': 'Se déconnecter de votre serveur ?',
'Your data is synced to your server first, then this device switches back to local-only.': "Vos données sont d'abord synchronisées avec votre serveur, puis cet appareil repasse en mode local.",
'Disconnected — back to local-only': 'Déconnecté — retour en mode local',
'Connect to my server': 'Se connecter à mon serveur',
'Sync this device to your own self-hosted openGym instead.': 'Synchronise plutôt cet appareil avec votre propre openGym self-hosted.',
'Pair the mobile app': "Associer l'application mobile",
'Connect the openGym app on your phone to this account.': "Associez l'application openGym de votre téléphone à ce compte.",
'Could not generate a code': 'Impossible de générer un code',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': "Dans l'application openGym, choisissez « Se connecter à mon serveur », puis saisissez cette adresse et le code ci-dessous. Il expire dans 5 minutes.",
'Enter your server address and the code': "Saisissez l'adresse de votre serveur et le code",
'Connected': 'Connecté',
'Could not connect': 'Connexion impossible',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': "Dans Réglages → « Associer l'application mobile » sur le site openGym où vous êtes déjà connecté, saisissez ensuite son adresse et le code qui s'y affiche.",
'Server address (e.g. gym.example.com)': 'Adresse du serveur (ex. gym.example.com)',
'Pairing code': "Code d'association",
'Connecting…': 'Connexion…',
'Connect': 'Connecter',
'How do you want to use openGym?': 'Comment voulez-vous utiliser openGym ?',
'Use on this device': 'Utiliser sur cet appareil',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local garde tout sur ce téléphone. Se connecter synchronise plutôt avec votre propre serveur openGym — vous pourrez changer cela plus tard dans Réglages.',
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — terminé',
'Workout done': 'Séance terminée',
'reps': 'reps',
'Most reps in a set per workout': 'Plus de reps dans une série par séance',
'Warm-up sets': 'Séries d’échauffement',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Ajoutées avant tes séries de travail et exclues du volume, des records et de la progression. Chacune réduit de moitié l’écart avec la charge de travail — tu peux les modifier pendant la séance.',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Séries de montée en charge avant les séries de travail, pour ne pas les ajouter à la main chaque fois.',
'Note': 'Note',
'This session': 'Cette séance',
'How it went, what to change — kept with today’s workout.': 'Comment ça s’est passé, ce qu’il faut changer — conservé avec la séance du jour.',
'Show this next time': 'Afficher la prochaine fois',
'Brings it up again the next time you train this exercise.': 'Réapparaît la prochaine fois que tu travailles cet exercice.',
'Always for this exercise': 'Toujours pour cet exercice',
'Seat height, pin position, a form cue — shown every session.': 'Hauteur du siège, position de la goupille, un rappel technique — visible à chaque séance.',
'From {0}:': 'Du {0} :',
'Session note': 'Note de séance',
'Add session note': 'Ajouter une note de séance',
'Edit session note': 'Modifier la note de séance',
'How the session went as a whole.': 'Comment la séance s’est passée dans l’ensemble.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Le rest-pause s’entraîne toujours comme une série d’échauffement à ce nombre de reps, puis une série de travail rest-pause — « Séries » n’est pas utilisé.'
}
+96 -1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'पुष्टि करें',
'Cancel': 'रद्द करें',
'Press back again to exit': 'बाहर निकलने के लिए फिर से बैक दबाएँ',
'Delete': 'हटाएँ',
'Save': 'सहेजें',
'Import': 'आयात करें',
@@ -163,6 +164,24 @@ export default {
'Warm-up': 'वार्म-अप',
'Add warm-up set': 'वार्म-अप सेट जोड़ें',
'Add set': 'सेट जोड़ें',
'+ Drop': '+ ड्रॉप सेट',
'+ Burst': '+ बर्स्ट',
'Drop {0}': 'ड्रॉप सेट {0}',
'Burst {0}': 'बर्स्ट {0}',
'Remove drop': 'ड्रॉप सेट हटाएं',
'Remove burst': 'बर्स्ट हटाएं',
'Rest (s)': 'आराम (सेकंड)',
'Drop-set / rest-pause': 'ड्रॉप सेट / रेस्ट-पॉज़',
'Intensifier': 'इंटेंसिफायर',
'None': 'कोई नहीं',
'Drop-set': 'ड्रॉप सेट',
'Rest-pause': 'रेस्ट-पॉज़',
'Drops': 'ड्रॉप्स',
'Weight drop (%)': 'वज़न में कमी (%)',
'Rest-pause reps': 'रेस्ट-पॉज़ रेप्स',
'Rest-pause rest': 'रेस्ट-पॉज़ आराम',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'हर सेट ड्रॉप सेट बन जाता है: मुख्य सेट के बाद बिना आराम के {0} ड्रॉप, हर एक लगभग {1}% हल्का।',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'हर सेट रेस्ट-पॉज़ बन जाता है: शुरुआत में {0} रेप्स, फिर छोटे बर्स्ट में बंटे {1} और, हर एक से पहले {2} सेकंड आराम, हर बार लगभग आधा होते हुए।',
'Cardio logged': 'कार्डियो दर्ज हुआ',
'Discard workout?': 'वर्कआउट छोड़ें?',
'The sets you logged in this session will be lost.': 'इस सत्र में दर्ज किए सेट खो जाएँगे।',
@@ -206,6 +225,7 @@ export default {
'Create one or load the starter plan.': 'एक बनाएँ या स्टार्टर प्लान लोड करें।',
'Load starter plan (Push / Pull / Legs)': 'स्टार्टर प्लान लोड करें (पुश / पुल / लेग्स)',
'Superset with exercise above': 'ऊपर वाले व्यायाम के साथ सुपरसेट',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'नोट (वैकल्पिक) — लोडिंग संकेत, जैसे "सिर्फ़ खाली बार, फिर हर सेट में हर तरफ़ +1 प्लेट", जो भी याद रखना चाहें',
'No exercises yet — add your first one.': 'अभी कोई व्यायाम नहीं — पहला जोड़ें।',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'किसी व्यायाम पर लिंक बटन दबाएँ ताकि वह ऊपर वाले के साथ सुपरसेट बने — आप उन्हें लगातार करेंगे।',
'Delete routine?': 'रूटीन हटाएँ?',
@@ -256,6 +276,7 @@ export default {
'Theme': 'थीम',
'Dark': 'डार्क',
'Light': 'लाइट',
'System': 'सिस्टम',
'Accent color': 'एक्सेंट रंग',
'General': 'सामान्य',
'During a workout': 'वर्कआउट के दौरान',
@@ -268,6 +289,8 @@ export default {
'Data': 'डेटा',
'Export backup (JSON)': 'बैकअप निर्यात करें (JSON)',
'Import backup': 'बैकअप आयात करें',
'Auto-backup on changes': 'बदलाव पर ऑटो-बैकअप',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'वर्कआउट खत्म करने या रूटीन एडिट करने के बाद Documents फ़ोल्डर में तारीख़ वाली कॉपी सेव करता है — उस फ़ोल्डर पर कोई सिंक ऐप लगाएं, या फ़ाइल को हाथ से कॉपी करें।',
'Reset everything?': 'सब कुछ रीसेट करें?',
'Reset everything': 'सब कुछ रीसेट करें',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'इस डिवाइस पर आपकी योजना, वर्कआउट और वज़न हट जाएँगे। इसे पूर्ववत नहीं किया जा सकता।',
@@ -720,5 +743,77 @@ export default {
'secondary': 'द्वितीयक',
'No exercises with an estimated 1RM yet.': 'अभी तक अनुमानित 1RM वाला कोई व्यायाम नहीं।',
'Tap a muscle to see its exercises.': 'व्यायाम देखने के लिए किसी मांसपेशी पर टैप करें।',
'Unpair': 'अलग करें'
'Unpair': 'अलग करें',
// --- equipment profiles ---
'Showing all equipment': 'सभी उपकरण दिखाए जा रहे हैं',
'Showing what you have in "{0}"': '“{0}” में आपके पास जो है वह दिखाया जा रहा है',
'Show all equipment': 'सभी उपकरण दिखाएँ',
'Filter by "{0}"': '“{0}” से फ़िल्टर करें',
'Edit profile': 'प्रोफ़ाइल संपादित करें',
'New equipment profile': 'नई उपकरण प्रोफ़ाइल',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'जहाँ आप कसरत करते हैं उसी के नाम पर रखें — जैसे “घर” या “जिम” — फिर वहाँ जो है उसे चुनें।',
'Profile name': 'प्रोफ़ाइल का नाम',
'Body-weight exercises are always available, in every profile.': 'शरीर के वज़न वाली कसरतें हर प्रोफ़ाइल में हमेशा उपलब्ध रहती हैं।',
'{0} of {1} exercises need equipment outside "{2}"': '{1} में से {0} कसरतों को “{2}” के बाहर के उपकरण चाहिए',
'Needs {0} — not in your active profile': '{0} चाहिए — आपकी सक्रिय प्रोफ़ाइल में नहीं है',
'Filter by equipment': 'उपकरण से फ़िल्टर करें',
'Active profile': 'सक्रिय प्रोफ़ाइल',
'{0} equipment types': '{0} प्रकार के उपकरण',
'Add equipment profile': 'उपकरण प्रोफ़ाइल जोड़ें',
'Delete profile?': 'प्रोफ़ाइल हटाएँ?',
'"{0}" and its equipment list will be removed.': '“{0}” और उसकी उपकरण सूची हटा दी जाएगी।',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'कसरत लाइब्रेरी और चयनकर्ता को फ़िल्टर करता है, और उन रूटीन कसरतों को चिह्नित करता है जिनके लिए सक्रिय प्रोफ़ाइल में मौजूद न होने वाला उपकरण चाहिए।',
// --- muscle groups ---
'Primary muscle groups': 'प्राथमिक मांसपेशी समूह',
'Additional muscle groups': 'अतिरिक्त मांसपेशी समूह',
'No explicit muscle group': 'कोई स्पष्ट मांसपेशी समूह नहीं',
// "Connect to my server" (mobile app pairing)
'Your server': 'आपका सर्वर',
'Synced with your openGym server.': 'आपके openGym सर्वर के साथ सिंक हो गया।',
'Disconnect': 'डिस्कनेक्ट करें',
'Disconnect from your server?': 'क्या सर्वर से डिस्कनेक्ट करें?',
'Your data is synced to your server first, then this device switches back to local-only.': 'आपका डेटा पहले आपके सर्वर से सिंक होगा, फिर यह डिवाइस लोकल मोड में वापस चला जाएगा।',
'Disconnected — back to local-only': 'डिस्कनेक्ट हो गया — वापस लोकल मोड में',
'Connect to my server': 'मेरे सर्वर से कनेक्ट करें',
'Sync this device to your own self-hosted openGym instead.': 'इसके बजाय इस डिवाइस को अपने खुद के सेल्फ़-होस्टेड openGym से सिंक करें।',
'Pair the mobile app': 'मोबाइल ऐप पेयर करें',
'Connect the openGym app on your phone to this account.': 'अपने फ़ोन पर openGym ऐप को इस अकाउंट से जोड़ें।',
'Could not generate a code': 'कोड जनरेट नहीं हो सका',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'openGym ऐप में "मेरे सर्वर से कनेक्ट करें" चुनें, फिर यह पता और नीचे दिया कोड डालें। यह 5 मिनट में समाप्त हो जाता है।',
'Enter your server address and the code': 'अपने सर्वर का पता और कोड डालें',
'Connected': 'कनेक्ट हो गया',
'Could not connect': 'कनेक्ट नहीं हो सका',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'जिस openGym साइट में आप पहले से साइन इन हैं, वहाँ सेटिंग्स → "मोबाइल ऐप पेयर करें" खोलें, फिर उसका पता और वहाँ दिखा कोड डालें।',
'Server address (e.g. gym.example.com)': 'सर्वर का पता (जैसे gym.example.com)',
'Pairing code': 'पेयरिंग कोड',
'Connecting…': 'कनेक्ट हो रहा है…',
'Connect': 'कनेक्ट करें',
'How do you want to use openGym?': 'आप openGym का उपयोग कैसे करना चाहते हैं?',
'Use on this device': 'इस डिवाइस पर उपयोग करें',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'लोकल सब कुछ इसी फ़ोन पर रखता है। कनेक्ट करने पर इसके बजाय आपके अपने openGym सर्वर से सिंक होता है — इसे बाद में सेटिंग्स में बदला जा सकता है।',
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — पूरा',
'Workout done': 'कसरत पूरी',
'reps': 'रेप्स',
'Most reps in a set per workout': 'प्रति कसरत एक सेट में सबसे ज़्यादा रेप्स',
'Warm-up sets': 'वार्म-अप सेट',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'ये आपके वर्क सेट से पहले जुड़ते हैं और वॉल्यूम, रिकॉर्ड तथा प्रोग्रेशन में नहीं गिने जाते। हर सेट वर्क वज़न तक बची दूरी को आधा कर देता है — कसरत के दौरान आप इन्हें बदल सकते हैं।',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'वर्क सेट से पहले जुड़ने वाले तैयारी सेट, ताकि हर बार खुद जोड़ना न पड़े।',
'Note': 'नोट',
'This session': 'यह कसरत',
'How it went, what to change — kept with today’s workout.': 'कैसा रहा, क्या बदलना है — आज की कसरत के साथ सहेजा जाता है।',
'Show this next time': 'अगली बार दिखाएँ',
'Brings it up again the next time you train this exercise.': 'अगली बार यह कसरत करते समय फिर दिखेगा।',
'Always for this exercise': 'इस कसरत के लिए हमेशा',
'Seat height, pin position, a form cue — shown every session.': 'सीट की ऊँचाई, पिन की जगह, तकनीक का सुझाव — हर कसरत में दिखता है।',
'From {0}:': '{0} से:',
'Session note': 'सत्र का नोट',
'Add session note': 'सत्र का नोट जोड़ें',
'Edit session note': 'सत्र का नोट बदलें',
'How the session went as a whole.': 'पूरा सत्र कैसा रहा।',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'रेस्ट-पॉज़ हमेशा इसी रेप्स संख्या के एक वार्म-अप सेट और एक रेस्ट-पॉज़ वर्क सेट के रूप में किया जाता है — “सेट” का उपयोग नहीं होता।'
}
+96 -1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Conferma',
'Cancel': 'Annulla',
'Press back again to exit': 'Premi di nuovo indietro per uscire',
'Delete': 'Elimina',
'Save': 'Salva',
'Import': 'Importa',
@@ -163,6 +164,24 @@ export default {
'Warm-up': 'Riscaldamento',
'Add warm-up set': 'Aggiungi serie di riscaldamento',
'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)',
'Drop-set / rest-pause': 'Drop-set / rest-pause',
'Intensifier': 'Intensificatore',
'None': 'Nessuno',
'Drop-set': 'Drop-set',
'Rest-pause': 'Rest-pause',
'Drops': 'Drop set',
'Weight drop (%)': 'Riduzione peso (%)',
'Rest-pause reps': 'Ripetizioni rest-pause',
'Rest-pause rest': 'Recupero rest-pause',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Ogni serie diventa un drop-set: dopo la serie principale, {0} riduzione/i senza recupero, ciascuna circa il {1}% più leggera.',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Ogni serie diventa rest-pause: {0} ripetizioni iniziali, poi altre {1} suddivise in brevi burst, con {2}s di recupero prima di ciascuno, dimezzando circa ogni volta.',
'Cardio logged': 'Cardio registrato',
'Discard workout?': 'Scartare allenamento?',
'The sets you logged in this session will be lost.': 'Le serie registrate in questa sessione andranno perse.',
@@ -206,6 +225,7 @@ export default {
'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)',
'Superset with exercise above': "Superset con l'esercizio sopra",
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Nota (facoltativa) — indicazioni di carico, es. "solo bilanciere poi +1 disco per lato a ogni serie", qualsiasi cosa tu voglia ricordare',
'No exercises yet — add your first one.': 'Ancora nessun esercizio — aggiungi il primo.',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Tocca il pulsante di collegamento su un esercizio per farne un superset con quello sopra — li farai di seguito.',
'Delete routine?': 'Eliminare routine?',
@@ -256,6 +276,7 @@ export default {
'Theme': 'Tema',
'Dark': 'Scuro',
'Light': 'Chiaro',
'System': 'Sistema',
'Accent color': 'Colore accento',
'General': 'Generale',
'During a workout': 'Durante l’allenamento',
@@ -268,6 +289,8 @@ export default {
'Data': 'Dati',
'Export backup (JSON)': 'Esporta backup (JSON)',
'Import backup': 'Importa backup',
'Auto-backup on changes': 'Backup automatico alle modifiche',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': "Salva una copia datata nella cartella Documenti dopo aver terminato un allenamento o modificato una routine — punta un'app di sincronizzazione lì, oppure copia il file a mano.",
'Reset everything?': 'Azzerare tutto?',
'Reset everything': 'Azzera tutto',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina piano, allenamenti e peso corporeo su questo dispositivo. Irreversibile.',
@@ -720,5 +743,77 @@ export default {
'secondary': 'secondario',
'No exercises with an estimated 1RM yet.': 'Nessun esercizio con 1RM stimato finora.',
'Tap a muscle to see its exercises.': 'Tocca un muscolo per vedere i suoi esercizi.',
'Unpair': 'Separa'
'Unpair': 'Separa',
// --- equipment profiles ---
'Showing all equipment': 'Vengono mostrati tutti gli attrezzi',
'Showing what you have in "{0}"': 'Viene mostrato ciò che hai in “{0}”',
'Show all equipment': 'Mostra tutti gli attrezzi',
'Filter by "{0}"': 'Filtra per “{0}”',
'Edit profile': 'Modifica profilo',
'New equipment profile': 'Nuovo profilo attrezzi',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'Chiamalo come il posto dove ti alleni — ad es. “Casa” o “Palestra” — poi spunta ciò che hai lì.',
'Profile name': 'Nome del profilo',
'Body-weight exercises are always available, in every profile.': 'Gli esercizi a corpo libero sono sempre disponibili, in ogni profilo.',
'{0} of {1} exercises need equipment outside "{2}"': '{0} di {1} esercizi richiedono attrezzi fuori da “{2}”',
'Needs {0} — not in your active profile': 'Richiede {0} — non presente nel profilo attivo',
'Filter by equipment': 'Filtra per attrezzi',
'Active profile': 'Profilo attivo',
'{0} equipment types': '{0} tipi di attrezzi',
'Add equipment profile': 'Aggiungi profilo attrezzi',
'Delete profile?': 'Eliminare il profilo?',
'"{0}" and its equipment list will be removed.': '“{0}” e il suo elenco di attrezzi verranno rimossi.',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtra la libreria degli esercizi e il selettore, e segnala gli esercizi delle routine che richiedono qualcosa che non hai nel profilo attivo.',
// --- muscle groups ---
'Primary muscle groups': 'Gruppi muscolari primari',
'Additional muscle groups': 'Gruppi muscolari aggiuntivi',
'No explicit muscle group': 'Nessun gruppo muscolare esplicito',
// "Connect to my server" (mobile app pairing)
'Your server': 'Il tuo server',
'Synced with your openGym server.': 'Sincronizzato con il tuo server openGym.',
'Disconnect': 'Disconnetti',
'Disconnect from your server?': 'Disconnettersi dal server?',
'Your data is synced to your server first, then this device switches back to local-only.': 'I tuoi dati vengono prima sincronizzati con il tuo server, poi questo dispositivo torna alla modalità locale.',
'Disconnected — back to local-only': 'Disconnesso — tornato alla modalità locale',
'Connect to my server': 'Connettiti al mio server',
'Sync this device to your own self-hosted openGym instead.': 'Sincronizza invece questo dispositivo con il tuo openGym self-hosted.',
'Pair the mobile app': "Abbina l'app mobile",
'Connect the openGym app on your phone to this account.': "Collega l'app openGym sul tuo telefono a questo account.",
'Could not generate a code': 'Impossibile generare un codice',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': "Nell'app openGym scegli «Connettiti al mio server», poi inserisci questo indirizzo e il codice qui sotto. Scade tra 5 minuti.",
'Enter your server address and the code': "Inserisci l'indirizzo del tuo server e il codice",
'Connected': 'Connesso',
'Could not connect': 'Connessione non riuscita',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': "In Impostazioni → «Abbina l'app mobile» sul sito openGym in cui hai già effettuato l'accesso, poi inserisci il suo indirizzo e il codice mostrato lì.",
'Server address (e.g. gym.example.com)': 'Indirizzo del server (es. gym.example.com)',
'Pairing code': 'Codice di abbinamento',
'Connecting…': 'Connessione…',
'Connect': 'Connetti',
'How do you want to use openGym?': 'Come vuoi usare openGym?',
'Use on this device': 'Usa su questo dispositivo',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Locale mantiene tutto su questo telefono. Connettersi sincronizza invece con il tuo server openGym — potrai cambiarlo più tardi nelle Impostazioni.',
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — fatto',
'Workout done': 'Allenamento fatto',
'reps': 'rip.',
'Most reps in a set per workout': 'Più rip. in una serie per allenamento',
'Warm-up sets': 'Serie di riscaldamento',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Vengono aggiunte prima delle serie di lavoro e non contano per volume, record e progressione. Ognuna dimezza la distanza dal peso di lavoro — puoi comunque modificarle durante la sessione.',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Serie di avvicinamento prima delle serie di lavoro, così non devi aggiungerle a mano ogni volta.',
'Note': 'Nota',
'This session': 'Questa sessione',
'How it went, what to change — kept with today’s workout.': 'Com’è andata, cosa cambiare — resta con l’allenamento di oggi.',
'Show this next time': 'Mostra la prossima volta',
'Brings it up again the next time you train this exercise.': 'Ricompare la prossima volta che alleni questo esercizio.',
'Always for this exercise': 'Sempre per questo esercizio',
'Seat height, pin position, a form cue — shown every session.': 'Altezza del sedile, posizione del pin, un promemoria tecnico — visibile a ogni sessione.',
'From {0}:': 'Del {0}:',
'Session note': 'Nota della sessione',
'Add session note': 'Aggiungi nota della sessione',
'Edit session note': 'Modifica nota della sessione',
'How the session went as a whole.': 'Com’è andata la sessione nel complesso.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Il rest-pause si allena sempre come una serie di riscaldamento a queste ripetizioni e una serie di lavoro rest-pause — “Serie” non viene usato.'
}
+96 -1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': '확인',
'Cancel': '취소',
'Press back again to exit': '뒤로를 한 번 더 누르면 종료됩니다',
'Delete': '삭제',
'Save': '저장',
'Import': '가져오기',
@@ -163,6 +164,24 @@ export default {
'Warm-up': '워밍업',
'Add warm-up set': '워밍업 세트 추가',
'Add set': '세트 추가',
'+ Drop': '+ 드롭세트',
'+ Burst': '+ 버스트',
'Drop {0}': '드롭세트 {0}',
'Burst {0}': '버스트 {0}',
'Remove drop': '드롭세트 제거',
'Remove burst': '버스트 제거',
'Rest (s)': '휴식(초)',
'Drop-set / rest-pause': '드롭세트 / 레스트포즈',
'Intensifier': '강도 기법',
'None': '없음',
'Drop-set': '드롭세트',
'Rest-pause': '레스트포즈',
'Drops': '드롭 횟수',
'Weight drop (%)': '중량 감소(%)',
'Rest-pause reps': '레스트포즈 반복 수',
'Rest-pause rest': '레스트포즈 휴식',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': '모든 세트가 드롭세트가 됩니다: 메인 세트 후 휴식 없이 {0}회 드롭, 매번 약 {1}%씩 가벼워집니다.',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': '모든 세트가 레스트포즈가 됩니다: 처음 {0}회를 하고, 짧은 버스트로 나눠 {1}회를 더 하며, 매번 전에 {2}초씩 쉬고 매번 대략 절반으로 줄어듭니다.',
'Cardio logged': '유산소 기록됨',
'Discard workout?': '운동을 버릴까요?',
'The sets you logged in this session will be lost.': '이 세션에서 기록한 세트가 사라집니다.',
@@ -206,6 +225,7 @@ export default {
'Create one or load the starter plan.': '루틴을 만들거나 스타터 계획을 불러오세요.',
'Load starter plan (Push / Pull / Legs)': '스타터 계획 불러오기 (푸시 / 풀 / 레그)',
'Superset with exercise above': '위 운동과 슈퍼세트',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': '메모(선택 사항) — 중량 안내, 예: "빈 바로 시작 후 세트마다 양쪽 +1플레이트", 기억하고 싶은 모든 것',
'No exercises yet — add your first one.': '아직 운동이 없어요 — 첫 운동을 추가하세요.',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': '운동의 연결 버튼을 탭하면 위 운동과 슈퍼세트가 됩니다 — 연달아 수행하게 돼요.',
'Delete routine?': '루틴을 삭제할까요?',
@@ -256,6 +276,7 @@ export default {
'Theme': '테마',
'Dark': '다크',
'Light': '라이트',
'System': '시스템',
'Accent color': '강조 색상',
'General': '일반',
'During a workout': '운동 중',
@@ -268,6 +289,8 @@ export default {
'Data': '데이터',
'Export backup (JSON)': '백업 내보내기 (JSON)',
'Import backup': '백업 가져오기',
'Auto-backup on changes': '변경 시 자동 백업',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': '운동을 마치거나 루틴을 수정한 뒤 날짜가 적힌 사본을 문서 폴더에 저장합니다 — 동기화 앱이 그 폴더를 보게 하거나 파일을 직접 복사하세요.',
'Reset everything?': '전부 초기화할까요?',
'Reset everything': '전부 초기화',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': '이 기기의 계획, 운동, 체중을 삭제합니다. 되돌릴 수 없어요.',
@@ -720,5 +743,77 @@ export default {
'secondary': '보조',
'No exercises with an estimated 1RM yet.': '추정 1RM이 있는 운동이 아직 없습니다.',
'Tap a muscle to see its exercises.': '근육을 눌러 해당 운동을 확인하세요.',
'Unpair': '분리'
'Unpair': '분리',
// --- equipment profiles ---
'Showing all equipment': '모든 장비를 표시하는 중',
'Showing what you have in "{0}"': '‘{0}’에 있는 장비를 표시하는 중',
'Show all equipment': '모든 장비 표시',
'Filter by "{0}"': '‘{0}’(으)로 필터',
'Edit profile': '프로필 편집',
'New equipment profile': '새 장비 프로필',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': '운동하는 장소의 이름을 붙여 — 예: ‘집’ 또는 ‘헬스장’ — 그곳에 있는 장비를 체크하세요.',
'Profile name': '프로필 이름',
'Body-weight exercises are always available, in every profile.': '맨몸 운동은 모든 프로필에서 항상 사용할 수 있습니다.',
'{0} of {1} exercises need equipment outside "{2}"': '{1}개 운동 중 {0}개가 ‘{2}’ 외의 장비를 필요로 합니다',
'Needs {0} — not in your active profile': '{0} 필요 — 활성 프로필에 없음',
'Filter by equipment': '장비로 필터',
'Active profile': '활성 프로필',
'{0} equipment types': '장비 종류 {0}가지',
'Add equipment profile': '장비 프로필 추가',
'Delete profile?': '프로필을 삭제할까요?',
'"{0}" and its equipment list will be removed.': '‘{0}’과(와) 해당 장비 목록이 삭제됩니다.',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': '운동 라이브러리와 선택기를 필터링하고, 활성 프로필에 없는 장비가 필요한 루틴 운동을 표시합니다.',
// --- muscle groups ---
'Primary muscle groups': '주요 근육 그룹',
'Additional muscle groups': '추가 근육군',
'No explicit muscle group': '명시적 근육군 없음',
// "Connect to my server" (mobile app pairing)
'Your server': '내 서버',
'Synced with your openGym server.': 'openGym 서버와 동기화됨',
'Disconnect': '연결 해제',
'Disconnect from your server?': '서버와 연결을 해제할까요?',
'Your data is synced to your server first, then this device switches back to local-only.': '데이터가 먼저 서버와 동기화된 후, 이 기기는 로컬 모드로 돌아갑니다.',
'Disconnected — back to local-only': '연결 해제됨 — 로컬 모드로 전환',
'Connect to my server': '내 서버에 연결',
'Sync this device to your own self-hosted openGym instead.': '대신 이 기기를 직접 호스팅하는 openGym 서버와 동기화합니다.',
'Pair the mobile app': '모바일 앱 페어링',
'Connect the openGym app on your phone to this account.': '휴대폰의 openGym 앱을 이 계정에 연결하세요.',
'Could not generate a code': '코드를 생성하지 못했습니다',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'openGym 앱에서 "내 서버에 연결"을 선택한 다음, 이 주소와 아래 코드를 입력하세요. 5분 후 만료됩니다.',
'Enter your server address and the code': '서버 주소와 코드를 입력하세요',
'Connected': '연결됨',
'Could not connect': '연결하지 못했습니다',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': '이미 로그인된 openGym 사이트에서 설정 → "모바일 앱 페어링"을 열고, 주소와 거기에 표시된 코드를 입력하세요.',
'Server address (e.g. gym.example.com)': '서버 주소 (예: gym.example.com)',
'Pairing code': '페어링 코드',
'Connecting…': '연결 중…',
'Connect': '연결',
'How do you want to use openGym?': 'openGym을 어떻게 사용하시겠어요?',
'Use on this device': '이 기기에서 사용',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': '로컬 모드는 모든 것을 이 휴대폰에 보관합니다. 연결하면 대신 자신의 openGym 서버와 동기화됩니다 — 나중에 설정에서 변경할 수 있습니다.',
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — 완료',
'Workout done': '운동 완료',
'reps': '회',
'Most reps in a set per workout': '운동당 한 세트 최다 횟수',
'Warm-up sets': '워밍업 세트',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': '작업 세트 앞에 추가되며 볼륨, 기록, 진행에는 포함되지 않습니다. 각 세트는 작업 중량까지의 차이를 절반으로 줄이며, 운동 중에 언제든 바꿀 수 있습니다.',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': '작업 세트 앞에 넣는 준비 세트로, 매번 직접 추가하지 않아도 됩니다.',
'Note': '메모',
'This session': '이번 운동',
'How it went, what to change — kept with today’s workout.': '어땠는지, 무엇을 바꿀지 — 오늘 운동과 함께 저장됩니다.',
'Show this next time': '다음에 다시 보기',
'Brings it up again the next time you train this exercise.': '이 운동을 다음에 할 때 다시 표시됩니다.',
'Always for this exercise': '이 운동에 항상 표시',
'Seat height, pin position, a form cue — shown every session.': '시트 높이, 핀 위치, 자세 팁 — 매 운동마다 표시됩니다.',
'From {0}:': '{0}에서:',
'Session note': '운동 메모',
'Add session note': '운동 메모 추가',
'Edit session note': '운동 메모 편집',
'How the session went as a whole.': '이번 운동이 전체적으로 어땠는지.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': '레스트포즈는 항상 이 횟수의 워밍업 세트 하나와 레스트포즈 작업 세트 하나로 진행됩니다 — ‘세트’는 사용하지 않습니다.'
}
+96 -1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Potwierdź',
'Cancel': 'Anuluj',
'Press back again to exit': 'Naciśnij wstecz ponownie, aby wyjść',
'Delete': 'Usuń',
'Save': 'Zapisz',
'Import': 'Importuj',
@@ -163,6 +164,24 @@ export default {
'Warm-up': 'Rozgrzewka',
'Add warm-up set': 'Dodaj serię rozgrzewkową',
'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)',
'Drop-set / rest-pause': 'Seria zniżkująca / rest-pause',
'Intensifier': 'Technika intensyfikująca',
'None': 'Brak',
'Drop-set': 'Seria zniżkująca',
'Rest-pause': 'Rest-pause',
'Drops': 'Serie zniżkujące',
'Weight drop (%)': 'Redukcja ciężaru (%)',
'Rest-pause reps': 'Powtórzenia rest-pause',
'Rest-pause rest': 'Odpoczynek rest-pause',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Każda seria staje się serią zniżkującą: po serii głównej {0} redukcja(e) bez odpoczynku, każda lżejsza o ok. {1}%.',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Każda seria staje się rest-pause: {0} powtórzeń na start, potem kolejne {1} podzielone na krótkie serie, z {2}s odpoczynku przed każdą, zmniejszając się za każdym razem o połowę.',
'Cardio logged': 'Cardio zapisane',
'Discard workout?': 'Odrzucić trening?',
'The sets you logged in this session will be lost.': 'Serie zapisane w tej sesji zostaną utracone.',
@@ -206,6 +225,7 @@ export default {
'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)',
'Superset with exercise above': 'Superseria z ćwiczeniem powyżej',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Notatka (opcjonalnie) — wskazówki dot. obciążenia, np. "sama sztanga, potem +1 talerz na stronę w każdej serii", cokolwiek chcesz zapamiętać',
'No exercises yet — add your first one.': 'Brak ćwiczeń — dodaj pierwsze.',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Dotknij przycisku łączenia przy ćwiczeniu, aby połączyć je w superserię z tym powyżej — zrobisz je jedno po drugim.',
'Delete routine?': 'Usunąć plan?',
@@ -256,6 +276,7 @@ export default {
'Theme': 'Motyw',
'Dark': 'Ciemny',
'Light': 'Jasny',
'System': 'System',
'Accent color': 'Kolor akcentu',
'General': 'Ogólne',
'During a workout': 'Podczas treningu',
@@ -268,6 +289,8 @@ export default {
'Data': 'Dane',
'Export backup (JSON)': 'Eksportuj kopię (JSON)',
'Import backup': 'Importuj kopię',
'Auto-backup on changes': 'Automatyczna kopia przy zmianach',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Zapisuje datowaną kopię w folderze Dokumenty po zakończeniu treningu lub edycji rutyny — wskaż na ten folder aplikację synchronizującą albo skopiuj plik ręcznie.',
'Reset everything?': 'Zresetować wszystko?',
'Reset everything': 'Zresetuj wszystko',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Usuwa plan, treningi i masę ciała na tym urządzeniu. Nie można tego cofnąć.',
@@ -720,5 +743,77 @@ export default {
'secondary': 'drugorzędny',
'No exercises with an estimated 1RM yet.': 'Brak ćwiczeń z oszacowanym 1RM.',
'Tap a muscle to see its exercises.': 'Dotknij mięśnia, aby zobaczyć jego ćwiczenia.',
'Unpair': 'Rozłącz'
'Unpair': 'Rozłącz',
// --- equipment profiles ---
'Showing all equipment': 'Pokazywany jest cały sprzęt',
'Showing what you have in "{0}"': 'Pokazywane jest to, co masz w „{0}”',
'Show all equipment': 'Pokaż cały sprzęt',
'Filter by "{0}"': 'Filtruj według „{0}”',
'Edit profile': 'Edytuj profil',
'New equipment profile': 'Nowy profil sprzętu',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'Nazwij go tak jak miejsce, w którym trenujesz — np. „Dom” lub „Siłownia” — a potem zaznacz, co tam masz.',
'Profile name': 'Nazwa profilu',
'Body-weight exercises are always available, in every profile.': 'Ćwiczenia z masą własnego ciała są zawsze dostępne, w każdym profilu.',
'{0} of {1} exercises need equipment outside "{2}"': '{0} z {1} ćwiczeń wymaga sprzętu spoza „{2}”',
'Needs {0} — not in your active profile': 'Wymaga: {0} — brak w aktywnym profilu',
'Filter by equipment': 'Filtruj według sprzętu',
'Active profile': 'Aktywny profil',
'{0} equipment types': 'Typy sprzętu: {0}',
'Add equipment profile': 'Dodaj profil sprzętu',
'Delete profile?': 'Usunąć profil?',
'"{0}" and its equipment list will be removed.': '„{0}” i jego lista sprzętu zostaną usunięte.',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtruje bibliotekę ćwiczeń i selektor oraz oznacza ćwiczenia w rutynach, które wymagają czegoś, czego nie masz w aktywnym profilu.',
// --- muscle groups ---
'Primary muscle groups': 'Podstawowe grupy mięśniowe',
'Additional muscle groups': 'Dodatkowe grupy mięśniowe',
'No explicit muscle group': 'Brak jawnej grupy mięśniowej',
// "Connect to my server" (mobile app pairing)
'Your server': 'Twój serwer',
'Synced with your openGym server.': 'Zsynchronizowano z Twoim serwerem openGym.',
'Disconnect': 'Rozłącz',
'Disconnect from your server?': 'Rozłączyć z serwerem?',
'Your data is synced to your server first, then this device switches back to local-only.': 'Twoje dane zostaną najpierw zsynchronizowane z serwerem, a następnie to urządzenie wróci do trybu lokalnego.',
'Disconnected — back to local-only': 'Rozłączono — z powrotem w trybie lokalnym',
'Connect to my server': 'Połącz z moim serwerem',
'Sync this device to your own self-hosted openGym instead.': 'Zsynchronizuj to urządzenie z własnym, samodzielnie hostowanym openGym.',
'Pair the mobile app': 'Sparuj aplikację mobilną',
'Connect the openGym app on your phone to this account.': 'Połącz aplikację openGym na telefonie z tym kontem.',
'Could not generate a code': 'Nie udało się wygenerować kodu',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'W aplikacji openGym wybierz „Połącz z moim serwerem”, a potem wpisz ten adres i poniższy kod. Wygasa po 5 minutach.',
'Enter your server address and the code': 'Wpisz adres swojego serwera i kod',
'Connected': 'Połączono',
'Could not connect': 'Nie udało się połączyć',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'W Ustawieniach → „Sparuj aplikację mobilną” na stronie openGym, na której jesteś już zalogowany, wpisz jej adres i wyświetlony tam kod.',
'Server address (e.g. gym.example.com)': 'Adres serwera (np. gym.example.com)',
'Pairing code': 'Kod parowania',
'Connecting…': 'Łączenie…',
'Connect': 'Połącz',
'How do you want to use openGym?': 'Jak chcesz korzystać z openGym?',
'Use on this device': 'Użyj na tym urządzeniu',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Tryb lokalny zachowuje wszystko na tym telefonie. Połączenie synchronizuje zamiast tego z Twoim własnym serwerem openGym — możesz to później zmienić w Ustawieniach.',
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — zrobione',
'Workout done': 'Trening zrobiony',
'reps': 'powt.',
'Most reps in a set per workout': 'Najwięcej powt. w serii na trening',
'Warm-up sets': 'Serie rozgrzewkowe',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Dodawane przed seriami roboczymi i pomijane w objętości, rekordach i progresji. Każda zmniejsza o połowę dystans do ciężaru roboczego — w trakcie treningu nadal możesz je zmienić.',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Serie wprowadzające przed seriami roboczymi, żeby nie dodawać ich ręcznie za każdym razem.',
'Note': 'Notatka',
'This session': 'Ta sesja',
'How it went, what to change — kept with today’s workout.': 'Jak poszło, co zmienić — zostaje przy dzisiejszym treningu.',
'Show this next time': 'Pokaż następnym razem',
'Brings it up again the next time you train this exercise.': 'Pojawi się ponownie, gdy następnym razem będziesz robić to ćwiczenie.',
'Always for this exercise': 'Zawsze przy tym ćwiczeniu',
'Seat height, pin position, a form cue — shown every session.': 'Wysokość siedziska, pozycja bolca, wskazówka techniczna — widoczne w każdej sesji.',
'From {0}:': 'Z {0}:',
'Session note': 'Notatka do sesji',
'Add session note': 'Dodaj notatkę do sesji',
'Edit session note': 'Edytuj notatkę do sesji',
'How the session went as a whole.': 'Jak przebiegła cała sesja.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause zawsze trenuje się jako jedna seria rozgrzewkowa o tej liczbie powtórzeń i jedna seria robocza rest-pause — „Serie” nie są używane.'
}
+383
View File
@@ -0,0 +1,383 @@
// Brazilian Portuguese overrides. Shared, region-neutral strings inherit from pt-PT.
// Tests fingerprint every deliberately inherited entry so upstream changes require review.
// Some byte-identical overrides intentionally pin wording that must not drift with pt-PT.
import pt from './pt.js'
export const PT_BR_OVERRIDES = {
'Press back again to exit': 'Pressione voltar novamente para sair',
'Delete': 'Excluir',
'Save': 'Salvar',
'Log': 'Registrar',
'Settings': 'Configurações',
'Log body weight': 'Registrar peso corporal',
'Slide or tap to set your weight — tracked before every workout so your curve stays honest.': 'Deslize ou toque para informar seu peso — ele é registrado antes de cada treino para manter a curva precisa.',
'Save & start workout': 'Salvar e iniciar treino',
'Start without weighing in': 'Iniciar sem se pesar',
'Choose a different workout': 'Escolher outro treino',
'Recent weigh-ins': 'Pesagens recentes',
'Enter a valid weight': 'Informe um peso válido',
'Weight saved': 'Peso salvo',
'Your goal is drawn as a line through the weight charts, and gains/losses are colored by whether they move toward it.': 'Sua meta aparece como uma linha nos gráficos de peso, e os ganhos ou perdas mudam de cor conforme você se aproxima dela.',
'Save goal': 'Salvar meta',
"No entries yet — log your weight to start the curve. It's also asked before every workout.": 'Ainda não há registros — informe seu peso para começar a curva. Ele também será solicitado antes de cada treino.',
'Add to my plan': 'Adicionar ao meu plano',
'Add “{0}”': 'Adicionar “{0}”',
'“{0}” added to {1}': '“{0}” adicionado a {1}',
'Pick a routine — sets, reps & weight come next.': 'Escolha uma rotina — séries, repetições e peso vêm em seguida.',
'Create one and start with this exercise': 'Crie uma e comece com este exercício',
'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.',
'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',
'Sick, missed a day or want a different session? Pick what to train instead.': 'Ficou doente, perdeu um dia ou quer outro treino? Escolha o que treinar no lugar.',
'Tap a trained day for details · tap any other day to plan a session': 'Toque em um dia treinado para ver detalhes · toque em outro dia para planejar uma sessão',
'Delete workout?': 'Excluir treino?',
'This removes it from your history for good.': 'Isso remove o treino definitivamente do seu histórico.',
'Delete workout': 'Excluir treino',
'Confirm the weight you worked with — your highest becomes the default next time.': 'Confirme o peso usado — o maior valor será o padrão na próxima vez.',
'Then finish the superset partner.': 'Depois, termine o outro exercício do superset.',
'Save & next exercise': 'Salvar e ir para o próximo exercício',
'Save weight': 'Salvar peso',
'Tracked — next time starts at {0}': 'Registrado — na próxima vez você começa em {0}',
'Every exercise done — great work. Finish up, or keep going and add another exercise.': 'Todos os exercícios concluídos — ótimo trabalho! Finalize ou continue e adicione outro exercício.',
'Keep going — tap “+ Add exercise” below': 'Continue — toque em “+ Adicionar exercício” abaixo',
'Nothing logged yet': 'Ainda não há nada registrado',
'You haven’t checked off any sets. Finish the workout anyway?': 'Você não marcou nenhuma série. Deseja finalizar o treino mesmo assim?',
'Freestyle workout (pick as you go)': 'Treino livre (escolha durante o treino)',
'Build a plan first': 'Crie um plano primeiro',
'Cardio logged': 'Cardio registrado',
'The sets you logged in this session will be lost.': 'As séries registradas nesta sessão serão perdidas.',
'Superset · do these back-to-back, rest when done': 'Superset · faça estes exercícios em sequência e descanse ao terminar',
'Freestyle workout — add your first exercise.': 'Treino livre — adicione seu primeiro exercício.',
'Set up your weekly routine to get going — or load a ready-made Push / Pull / Legs plan.': 'Configure sua rotina semanal para começar ou carregue um plano pronto de Push / Pull / Legs.',
'Load starter plan (PPL)': 'Carregar plano inicial (PPL)',
'Build my own plan': 'Criar meu próprio plano',
'Finish your first workout to see progress curves here.': 'Finalize seu primeiro treino para ver os gráficos de progresso aqui.',
'Your weekly routine': 'Sua rotina semanal',
'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.',
'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',
'Search…': 'Buscar…',
'Starter plan loaded — Mon Push · Wed Pull · Fri Legs': 'Plano inicial carregado — Seg Push · Qua Pull · Sex Pernas',
'{0} planned for {1}': '{0} planejado para {1}',
'Planned': 'Planejado',
'Enter a name': 'Informe um nome',
'Registration failed': 'Falha no cadastro',
'Create your profile': 'Crie seu perfil',
'Pick a name, then confirm with {0}. The passkey is saved in your device — no password needed.': 'Escolha um nome e confirme com {0}. A chave de acesso fica salva no seu dispositivo — não é preciso usar senha.',
'Pick a name, then confirm with your device.': 'Escolha um nome e confirme com seu dispositivo.',
'Your name': 'Seu nome',
'Create passkey': 'Criar chave de acesso',
'Your workouts. Your weights. Your profile.': 'Seus treinos. Seus pesos. Seu perfil.',
'Create new profile': 'Criar novo perfil',
"This browser doesn't support passkeys — you can still use openGym locally on this device.": 'Este navegador não oferece suporte a chaves de acesso — você ainda pode usar o openGym localmente neste dispositivo.',
'Signed in with passkey — data syncs to this profile.': 'Sessão iniciada com chave de acesso — os dados são sincronizados com este perfil.',
'Sign out?': 'Sair?',
'Your data is synced to your profile first, then cleared from this device.': 'Seus dados serão sincronizados com o perfil e depois apagados deste dispositivo.',
'Sign out': 'Sair',
'Sign out everywhere?': 'Sair de todos os dispositivos?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Encerra a sessão deste perfil em todos os dispositivos, inclusive neste. Suas chaves de acesso continuam funcionando — entre novamente quando quiser.',
'Sign out everywhere': 'Sair de todos os dispositivos',
'Ends this profile’s sessions on all your devices.': 'Encerra as sessões deste perfil em todos os seus dispositivos.',
'Signed out on all devices': 'Sessão encerrada em todos os dispositivos',
'Could not sign out everywhere — you are still signed in.': 'Não foi possível sair de todos os dispositivos — sua sessão continua ativa.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modo visitante — os dados ficam somente neste navegador. Crie um perfil com chave de acesso para mantê-los seguros e separados por pessoa.',
'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.',
'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',
'Reset everything?': 'Redefinir tudo?',
'Reset everything': 'Redefinir tudo',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Exclui seu plano, seus treinos e seu peso corporal deste dispositivo. Esta ação não pode ser desfeita.',
'Delete everything': 'Excluir tudo',
'Backup exported': 'Backup exportado',
'Import backup?': 'Importar backup?',
'This replaces all current data with the backup file.': 'Isso substitui todos os dados atuais pelo arquivo de backup.',
'Backup imported': 'Backup importado',
'In Chrome: ⋮ menu → Add to Home screen': 'No Chrome: menu ⋮ → Adicionar à tela inicial',
'In Safari: Share → Add to Home Screen': 'No Safari: Compartilhar → Adicionar à Tela de Início',
'Your data syncs with your profile — sign in anywhere to see it.': 'Seus dados são sincronizados com o perfil — entre em qualquer dispositivo para acessá-los.',
'Guest data stays on this device — export a backup now and then!': 'Os dados de visitante ficam neste dispositivo — exporte um backup de vez em quando!',
'Only sent on days you have a routine planned and haven\'t logged a workout yet.': 'Enviado somente nos dias em que há uma rotina planejada e você ainda não registrou um treino.',
'Could not change notification settings': 'Não foi possível alterar as configurações de notificação',
'tap to pause': 'toque para pausar',
'tap to play': 'toque para reproduzir',
'Keeps your data safe and separate per person.': 'Mantém seus dados seguros e separados por pessoa.',
'Create your own exercise': 'Crie seu próprio exercício',
'Give it a name': 'Dê um nome',
'Description (optional) — setup, cues, anything you want to remember': 'Descrição (opcional) — preparação, dicas ou qualquer observação que você queira guardar',
'Name it and pick a body part — it behaves like any other exercise, just without an animation.': 'Dê um nome e escolha uma parte do corpo — ele funciona como qualquer outro exercício, mas sem animação.',
'Pick a body part': 'Escolha uma parte do corpo',
'Saved': 'Salvo',
'Delete “{0}”?': 'Excluir “{0}”?',
'It will be removed from your routines. Already-logged workouts keep their sets.': 'Ele será removido das suas rotinas. Os treinos já registrados manterão suas séries.',
'Finish your current workout first': 'Finalize o treino atual primeiro',
'Delete exercise': 'Excluir exercício',
'Edit or delete this exercise': 'Editar ou excluir este exercício',
'This app is invite-only — enter the code you were given.': 'Este aplicativo é somente para convidados — informe o código que você recebeu.',
'Passkeys use {0} — no passwords.': 'As chaves de acesso usam {0} — sem senhas.',
'Strength shows retained muscle strength. Train again to reset it.': 'A força mostra quanto da força muscular foi mantida. Treine novamente para redefinir o valor.',
'Added as your own': 'Adicionados como seus',
'The file is in {0} and your profile is in {1} — weights will be converted.': 'O arquivo está em {0} e seu perfil em {1} — os pesos serão convertidos.',
'The file does not say which unit it uses — numbers are imported as they are.': 'O arquivo não informa qual unidade utiliza — os valores serão importados como estão.',
'The file mixes kg and lb — each set is converted to {0}.': 'O arquivo mistura kg e lb — cada série será convertida para {0}.',
'{0} days already have data here and will be left alone.': '{0} dias já têm dados aqui e não serão alterados.',
'Not in the library — added as your own exercises': 'Não estão na biblioteca — foram adicionados como exercícios próprios',
'Could not read that file': 'Não foi possível ler esse arquivo',
'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',
'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.',
'{0} is on the plan today — let’s go!': 'Hoje tem {0} no plano — vamos lá!',
'Share your plan': 'Compartilhar seu plano',
'Shared routine': 'Rotina compartilhada',
'Got a plan from a friend?': 'Recebeu um plano de um amigo?',
'Send your routines to a friend, or put your week on paper.': 'Envie suas rotinas para um amigo ou coloque sua semana no papel.',
'Export plan file': 'Exportar arquivo do plano',
'A small file a friend imports into their own openGym — routines only, none of your workouts or weigh-ins.': 'Um pequeno arquivo que um amigo pode importar no próprio openGym — somente rotinas, sem seus treinos ou pesagens.',
'Print / Save as PDF': 'Imprimir / Salvar como PDF',
'Add an exercise to a routine first — an empty plan has nothing to share.': 'Adicione primeiro um exercício a uma rotina — um plano vazio não tem nada para compartilhar.',
'Import a plan file': 'Importar arquivo do plano',
'Plan file saved — send it to a friend': 'Arquivo do plano salvo — envie-o para um amigo',
'These are added as new routines — nothing you already have is changed.': 'Elas serão adicionadas como novas rotinas — nada do que você já tem será alterado.',
'{0} exercise in the file isn’t in your library and was left out.': '{0} exercício do arquivo não está na sua biblioteca e foi ignorado.',
'{0} exercises in the file aren’t in your library and were left out.': '{0} exercícios do arquivo não estão na sua biblioteca e foram ignorados.',
'Replaces your current Mon–Sun assignments.': 'Substitui os dias definidos de segunda a domingo.',
'Added {0} routines to your plan': '{0} rotinas adicionadas ao seu plano',
'this isn’t an openGym plan file': 'este não é um arquivo de plano do openGym',
'This screen could not be drawn. Your data is safe on this device.': 'Não foi possível exibir esta tela. Seus dados estão seguros neste dispositivo.',
'From your log:': 'Do seu registro:',
'Enter a weight and 1–{0} reps — beyond that an estimate is guesswork.': 'Informe um peso e de 1 a {0} repetições — acima disso, a estimativa é apenas um palpite.',
'Hold logged': 'Isometria registrada',
'Work up through a rep range at the same weight. Reach the top of the range in every set and the weight goes up, reps back to the bottom.': 'Avance por uma faixa de repetições com o mesmo peso. Ao atingir o topo da faixa em todas as séries, o peso aumenta e as repetições voltam ao mínimo.',
'Nothing logged yet — this session sets the baseline.': 'Ainda não há nada registrado — esta sessão define o ponto de partida.',
'Reminds you at this time on days that have a routine planned.': 'Lembra você neste horário nos dias em que há uma rotina planejada.',
'Each profile keeps its own plan, workouts & body weight.': 'Cada perfil mantém seu próprio plano, seus treinos e seu peso corporal.',
'Short {0} sessions in a row — back off to {1}s and build up again.': '{0} sessões seguidas abaixo da meta — reduza para {1} s e volte a progredir.',
'Top of the rep range in every set — {0} {1} more, back to {2} reps.': 'Topo da faixa de repetições em todas as séries — aumente {0} {1} e volte para {2} repetições.',
'Missed reps {0} sessions running — reset to {1} {2} and work back up.': 'Repetições não concluídas em {0} sessões seguidas — volte para {1} {2} e progrida novamente.',
'Missed reps — reset to {0} {1} and work back up.': 'Repetições não concluídas — volte para {0} {1} e progrida novamente.',
'Missed reps last time — same weight again ({0} of {1} to go).': 'Você não concluiu as repetições na última vez — mantenha o mesmo peso (faltam {0} de {1}).',
'{0} sets bring an {1} with them — switch on Effort per set in Settings to see it.': '{0} séries incluem um {1} — ative “Esforço por série” nas Configurações para exibi-lo.',
'RIR counts the reps you left; RPE reads the same effort off a 10-point scale — so RPE ≈ 10 − RIR. Pick the one you already think in.': 'O RIR conta as repetições que você ainda conseguiria fazer; o RPE representa o mesmo esforço em uma escala de 10 — portanto, RPE ≈ 10 − RIR. Escolha a escala que você já usa.',
'The highlighted row is where most working sets land. Sets you have already logged keep their own scale, and nothing else reads the value — progression and estimated 1RM are unaffected.': 'A linha destacada representa a maioria das séries de trabalho. As séries já registradas mantêm sua escala, e nenhum outro recurso usa esse valor — a progressão e o 1RM estimado não são afetados.',
'Effort per set is switched off — turn it on in Settings to keep rating.': 'O esforço por série está desativado — ative-o nas Configurações para continuar avaliando.',
'No weight to enter — just log the reps.': 'Não é preciso informar peso — registre apenas as repetições.',
'Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.': 'As repetições aumentam em uma quando todas as séries são concluídas. Defina um limite para adicionar séries em vez de aumentar repetições indefinidamente.',
'{0} reps in every set — add a set and go back to {1}.': '{0} repetições em todas as séries — adicione uma série e volte para {1}.',
'You still log the total: {0} is {1} per side.': 'Você ainda registra o total: {0} corresponde a {1} de cada lado.',
'Two straight sets plus a final set taken to failure. Beat the target on that set and the weight goes up — double if you double the reps. One failure resets 10 %.': 'Duas séries normais mais uma série final até a falha. Se você superar a meta nessa série, o peso aumenta — em dobro se você dobrar as repetições. Uma falha reduz 10%.',
'Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.': 'As repetições aumentam até {0}; depois, uma série é adicionada e as repetições recomeçam. Ao chegar a {1} séries, o app sugere adicionar peso.',
// Regional wording inherited from pt-PT would otherwise leak into pt-BR.
'Next': 'Próximo',
'{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?',
'{0} sets still unchecked. Finish the workout now?': 'Faltam {0} séries sem marcar. Finalizar o treino agora?',
'band': 'elástico',
'resistance band': 'faixa elástica',
'core': 'abdômen',
'lower back': 'lombar',
'shins': 'canelas',
'soleus': 'sóleo',
'Lower back': 'Lombar',
'Shins': 'Canelas',
'Import from another app': 'Importar de outro aplicativo',
'Stalled {0} sessions — deload to {1} {2}.': '{0} sessões sem progresso — reduza a carga para {1} {2}.',
'Bodyweight — every rep last time, so go for {0} this time.': 'Peso corporal — você concluiu todas as repetições na última vez; tente {0} desta vez.',
'Bodyweight — same target again until every set is clean.': 'Peso corporal — mantenha a mesma meta até concluir todas as séries.',
'Top of the range': 'Topo da faixa',
'Unpair': 'Desvincular',
'Skip': 'Pular',
'Rest / skip this day': 'Descansar / pular este dia',
'Workout deleted': 'Treino excluído',
'Last time you hit all reps — try {0}': 'Na última vez você concluiu todas as repetições — tente {0}',
'{0} — in progress': '{0} — em andamento',
'“{0}” and its exercises will be removed.': '“{0}” e seus exercícios serão removidos.',
'Sign-in failed': 'Falha ao entrar',
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Este navegador não oferece suporte a chaves de acesso e este servidor exige uma conta. Tente usar outro navegador ou dispositivo compatível.',
'Keep screen awake': 'Manter a tela ligada',
'All data reset': 'Todos os dados redefinidos',
'to install openGym as a full-screen app.': 'para instalar o openGym como aplicativo em tela cheia.',
'Timezone: {0} (auto-detected, updates if you travel).': 'Fuso horário: {0} (detectado automaticamente e atualizado se você viajar).',
'lower legs': 'panturrilhas',
'waist': 'abdômen',
'stepmill machine': 'simulador de escada',
'upper body ergometer': 'ergômetro de braços',
'calves': 'panturrilhas',
'levator scapulae': 'levantador da escápula',
'hip flexors': 'flexores do quadril',
'rotator cuff': 'manguito rotador',
'“{0}” already exists': '“{0}” já existe',
'“{0}” created': '“{0}” criado',
'Cardio exercises log time + speed instead of weight × reps.': 'Exercícios de cardio registram tempo e velocidade em vez de peso × repetições.',
'Exercise deleted': 'Exercício excluído',
'What you just trained': 'O que você acabou de treinar',
'Import “{0}”': 'Importar “{0}”',
'Something went wrong': 'Algo deu errado',
'Discard the running workout': 'Descartar o treino em andamento',
'A timer runs while you hold the set. Leave the weight at 0 for bodyweight holds.': 'Um cronômetro funciona enquanto você mantém a posição. Deixe o peso em 0 para isometrias com o peso do corpo.',
'Targets stay where you set them.': 'As metas permanecem como você definir.',
'Hit every rep in every set and the weight goes up. Repeated misses trigger a deload.': 'Conclua todas as repetições de todas as séries para aumentar o peso. Falhas repetidas acionam uma redução de carga.',
'Hold every set for the full duration and the target goes up.': 'Mantenha todas as séries pela duração completa para aumentar a meta.',
'Held every set for the full time — target up by {0}s.': 'Você manteve todas as séries pelo tempo completo — meta aumentada em {0} s.',
'Last time came up short — same target again.': 'Na última vez você ficou abaixo da meta — repita a mesma meta.',
'Same weight — aim for {0} reps this time.': 'Mesmo peso — desta vez, tente fazer {0} repetições.',
'Nothing left — went to failure': 'Sem repetições restantes — até a falha',
'Tap a muscle to see its exercises.': 'Toque em um músculo para ver seus exercícios.',
'Superset': 'Superset',
'Superset {0} / {1}': 'Superset {0} / {1}',
'Superset with exercise above': 'Superset com o exercício acima',
'Guest mode — data lives only in this browser.': 'Modo visitante — os dados ficam somente neste navegador.',
'Sign in with passkey': 'Entrar com chave de acesso',
'Passkeys not supported in this browser.': 'Chaves de acesso não são compatíveis com este navegador.',
'Su': 'D',
'Mo': 'S',
'Tu': 'T',
'We': 'Q',
'Th': 'Q',
'Fr': 'S',
'Sa': 'S',
// --- equipment profiles ---
'Showing all equipment': 'Mostrando todos os equipamentos',
'Showing what you have in "{0}"': 'Mostrando o que você tem em “{0}”',
'Show all equipment': 'Mostrar todos os equipamentos',
'Filter by "{0}"': 'Filtrar por “{0}”',
'Edit profile': 'Editar perfil',
'New equipment profile': 'Novo perfil de equipamentos',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'Dê a ele o nome do lugar onde você treina — por exemplo, “Casa” ou “Academia” — e marque o que você tem lá.',
'Profile name': 'Nome do perfil',
'Body-weight exercises are always available, in every profile.': 'Exercícios com o peso do corpo estão sempre disponíveis, em todos os perfis.',
'{0} of {1} exercises need equipment outside "{2}"': '{0} de {1} exercícios precisam de equipamentos fora de “{2}”',
'Needs {0} — not in your active profile': 'Precisa de {0} — não está no seu perfil ativo',
'Filter by equipment': 'Filtrar por equipamento',
'Active profile': 'Perfil ativo',
'{0} equipment types': '{0} tipos de equipamento',
'Add equipment profile': 'Adicionar perfil de equipamentos',
'Delete profile?': 'Excluir perfil?',
'"{0}" and its equipment list will be removed.': '“{0}” e sua lista de equipamentos serão removidos.',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtra a biblioteca de exercícios e o seletor, e sinaliza os exercícios das rotinas que precisam de algo que você não tem no perfil ativo.',
// --- drop-sets, auto-backup and server pairing ---
'Auto-backup on changes': 'Backup automático ao alterar',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Salva uma cópia datada na pasta Documentos depois de terminar um treino ou editar uma rotina — aponte um aplicativo de sincronização para ela, ou copie o arquivo na mão.',
'Your server': 'Seu servidor',
'Synced with your openGym server.': 'Sincronizado com o seu servidor openGym.',
'Disconnect': 'Desconectar',
'Disconnect from your server?': 'Desconectar do seu servidor?',
'Your data is synced to your server first, then this device switches back to local-only.': 'Seus dados são sincronizados com o seu servidor primeiro, depois este dispositivo volta ao modo somente local.',
'Disconnected — back to local-only': 'Desconectado — de volta ao modo somente local',
'Connect to my server': 'Conectar ao meu servidor',
'Sync this device to your own self-hosted openGym instead.': 'Sincronize este dispositivo com o seu próprio openGym auto-hospedado.',
'Pair the mobile app': 'Parear o aplicativo',
'Connect the openGym app on your phone to this account.': 'Conecte o aplicativo openGym do seu celular a esta conta.',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'No aplicativo openGym, escolha “Conectar ao meu servidor”, depois digite este endereço e o código abaixo. Ele expira em 5 minutos.',
'Enter your server address and the code': 'Digite o endereço do seu servidor e o código',
'Connected': 'Conectado',
'Could not connect': 'Não foi possível conectar',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'No site openGym em que você já está conectado, abra Configurações → “Parear o aplicativo”, depois digite o endereço e o código mostrado lá.',
'Connecting…': 'Conectando…',
'Connect': 'Conectar',
'How do you want to use openGym?': 'Como você quer usar o openGym?',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantém tudo neste celular. Conectar sincroniza com o seu próprio servidor openGym — você pode mudar depois em Configurações.',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Cada série vira uma série decrescente: depois da série principal, {0} queda(s) sem descanso, cada uma cerca de {1}% mais leve.',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Cada série vira rest-pause: {0} repetições para começar, depois mais {1} divididas em rajadas curtas, com {2}s de descanso antes de cada uma, caindo cerca de metade a cada vez.',
// --- workout notes and planned warm-ups ---
'Most reps in a set per workout': 'Mais reps em uma série por treino',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'São adicionadas antes das suas séries de trabalho e ficam de fora do volume, dos recordes e da progressão. Cada uma reduz pela metade a distância até o peso de trabalho — você ainda pode alterá-las durante o treino.',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Séries de aproximação antes das séries de trabalho, para você não precisar adicioná-las na mão a cada treino.',
'How it went, what to change — kept with today’s workout.': 'Como foi, o que mudar — fica salvo com o treino de hoje.',
'Brings it up again the next time you train this exercise.': 'Aparece de novo na próxima vez que você treinar este exercício.',
'Seat height, pin position, a form cue — shown every session.': 'Altura do banco, posição do pino, uma dica de execução — aparece em todos os treinos.',
'How the session went as a whole.': 'Como foi o treino como um todo.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'O rest-pause sempre treina como uma série de aquecimento com essas repetições e uma série de trabalho rest-pause — “Séries” não é usado.',
// --- AI Coach ---
// pt-PT addresses the lifter as "tu"; Brazil says "você", and a few words differ outright
// (ecrã → tela, anular → desfazer, controlos → controles, «» → “”).
'The Coach is reading your training…': 'O Treinador está lendo seu treino…',
'Any pending suggestion is discarded and scheduled reviews stop. Your Coach history stays, and you can turn it back on anytime.': 'Qualquer sugestão pendente é descartada e as revisões agendadas param. Seu histórico do Treinador fica, e você pode ligá-lo de novo quando quiser.',
'Undo the last Coach changes?': 'Desfazer as últimas alterações do Treinador?',
'Your plan goes back to how it was before you accepted them. Workouts you have logged since are untouched.': 'Seu plano volta ao que era antes de você aceitá-las. Os treinos registrados desde então não são alterados.',
'Undo': 'Desfazer',
'Nothing to undo': 'Nada para desfazer',
'Plan design and reviews, from your own training': 'Criação de planos e revisões, a partir do seu próprio treino',
'The Coach reads what you have actually logged since its last look and suggests changes to your plan — each one with its reason.': 'O Treinador lê o que você registrou desde a última vez e sugere alterações no seu plano — cada uma com o seu motivo.',
'Anything it should know? (optional) — e.g. “right shoulder pinches on overhead work”': 'Algo que ele deva saber? (opcional) — ex.: “o ombro direito incomoda em movimentos acima da cabeça”',
'{0} of {1} Coach runs used today': '{0} de {1} usos do Treinador hoje',
'No plan yet — the Coach can build you one from a few questions.': 'Ainda não há plano — o Treinador pode criar um a partir de algumas perguntas.',
'Let the Coach build my plan': 'Deixar o Treinador criar meu plano',
'Used by every proposal — keep limitations here up to date.': 'Usado em cada proposta — mantenha suas limitações atualizadas aqui.',
'Your answers': 'Suas respostas',
'Not set yet': 'Ainda não definido',
'Controls': 'Controles',
'Undo the last Coach changes': 'Desfazer as últimas alterações do Treinador',
'When you ask for a plan or a review, this instance sends the following to {0}, running on this server under the instance owner’s account.': 'Quando você pede um plano ou uma revisão, esta instância envia o seguinte para {0}, que roda neste servidor na conta do proprietário.',
'the configured AI provider': 'o provedor de IA configurado',
'Your name, your sign-in details and everything else about your account stay here. Other people’s data is never included.': 'Seu nome, seus dados de acesso e todo o resto da sua conta ficam aqui. Os dados de outras pessoas nunca são incluídos.',
'Nothing the Coach suggests is applied on its own — you review every change and can undo it afterwards.': 'Nada do que o Treinador sugere é aplicado sozinho — você revisa cada alteração e pode desfazê-la depois.',
'You can turn this off at any time, which also discards anything the Coach is holding for you.': 'Você pode desligar isto a qualquer momento, o que também descarta o que o Treinador estiver guardando para você.',
'The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.': 'O Treinador não é médico nem fisioterapeuta. Se algo doer, procure um profissional.',
'I understand — turn the Coach on': 'Entendi — ligar o Treinador',
'Meet the Coach': 'Conheça o Treinador',
'An AI coach that can design your plan and adjust it from what you actually log. It runs on this server, it never changes anything without your say-so, and it is off until you turn it on.': 'Um treinador com IA que cria seu plano e o ajusta com base no que você registra. Roda neste servidor, nunca muda nada sem a sua autorização e fica desligado até você ligá-lo.',
'The Coach is thinking…': 'O Treinador está pensando…',
'This takes a minute or two. You can leave this screen — it keeps going.': 'Isto leva um ou dois minutos. Você pode sair desta tela — ele continua trabalhando.',
'Your plan is ready': 'Seu plano está pronto',
'{0} routines to look over': '{0} rotinas para revisar',
'Review': 'Revisar',
'Off — the Coach only looks when you ask it to.': 'Desligado — o Treinador só analisa quando você pede.',
'You are only notified when the Coach actually has something to suggest.': 'Você só é avisado quando o Treinador realmente tem algo a sugerir.',
'On a day and time you choose': 'No dia e hora que você escolher',
'As soon as you have logged enough': 'Assim que você tiver registrado o suficiente',
'Reviewed your training': 'Revisou seu treino',
'The Coach is building your plan…': 'O Treinador está criando seu plano…',
'Your plan': 'Seu plano',
'What are you training for?': 'Para que você treina?',
'Where are you starting from?': 'De onde você está partindo?',
'Which days suit you? (optional)': 'Quais dias são melhores para você? (opcional)',
'The Coach fits the volume to the time you actually have, including rest between sets.': 'O Treinador ajusta o volume ao tempo que você realmente tem, incluindo o descanso entre séries.',
'What can you train with?': 'Com o que você pode treinar?',
'Pick everything you have access to. Leave it empty and the Coach will use the whole library.': 'Marque tudo a que você tem acesso. Se deixar vazio, o Treinador usa a biblioteca inteira.',
'Injuries, joints that complain, movements you cannot do, or practical limits like training at 6am in a flat.': 'Lesões, articulações que reclamam, movimentos que você não consegue fazer ou limites práticos como treinar às 6h em um apartamento.',
'e.g. “dodgy left shoulder — no barbell overhead press”': 'ex.: “ombro esquerdo sensível — nada de desenvolvimento com barra”',
'If something actually hurts, see a professional — the Coach will program conservatively but it cannot diagnose anything.': 'Se algo realmente doer, procure um profissional — o Treinador vai programar de forma conservadora, mas não pode diagnosticar nada.',
'Exercises you love': 'Exercícios que você adora',
'e.g. “deadlifts, anything with a kettlebell”': 'ex.: “levantamento terra, qualquer coisa com kettlebell”',
'Exercises you would rather not': 'Exercícios que você prefere evitar',
'e.g. “I hate lunges”': 'ex.: “odeio afundos”',
'Anything you want the Coach to know': 'Algo que você queira que o Treinador saiba',
'e.g. “I want visible arms progress by spring”': 'ex.: “quero ver progresso visível nos braços até a primavera”',
'Build my plan': 'Criar meu plano',
'Pick a goal and where you are starting from to continue.': 'Escolha um objetivo e seu ponto de partida para continuar.',
'Your plan is live': 'Seu plano está ativo',
'Nothing is saved, and you can ask again anytime.': 'Nada é salvo, e você pode pedir de novo quando quiser.',
'The Coach is revising it…': 'O Treinador está revisando…',
'Replaces your current week. Days this plan leaves empty become rest days.': 'Substitui sua semana atual. Os dias que este plano deixar vazios viram dias de descanso.',
'Want something different?': 'Quer algo diferente?',
'Say it in your own words and the Coach will revise the whole plan.': 'Diga com suas palavras e o Treinador revisa o plano inteiro.',
'e.g. “swap the squats for split squats, and Mondays are short”': 'ex.: “troque os agachamentos por afundos búlgaros, e às segundas tenho pouco tempo”',
'Nothing changes, and the Coach will remember you turned these down.': 'Nada muda, e o Treinador vai lembrar que você recusou estas.',
'Based on your last {0} sessions': 'Com base nas suas últimas {0} sessões',
'Your plan changed since the Coach looked at it. Suggestions that no longer match are greyed out — ask for a fresh review to see them again.': 'Seu plano mudou desde que o Treinador o viu. As sugestões que não se encaixam mais aparecem esmaecidas — peça uma nova revisão para vê-las de novo.',
'Doesn’t match your plan any more — can’t be applied.': 'Não corresponde mais ao seu plano — não pode ser aplicada.',
'Reverted the last Coach changes.': 'As últimas alterações do Treinador foram desfeitas.',
'Undid the last changes': 'Desfez as últimas alterações',
'{0}: hold time': '{0}: tempo de isometria',
'Add routine “{0}”': 'Adicionar rotina “{0}”',
'Rename routine to “{0}”': 'Renomear rotina para “{0}”'
}
export default { ...pt, ...PT_BR_OVERRIDES }
+96 -1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Confirmar',
'Cancel': 'Cancelar',
'Press back again to exit': 'Prima novamente para sair',
'Delete': 'Eliminar',
'Save': 'Guardar',
'Import': 'Importar',
@@ -163,6 +164,24 @@ export default {
'Warm-up': 'Aquecimento',
'Add warm-up set': 'Adicionar série de aquecimento',
'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)',
'Drop-set / rest-pause': 'Séries decrescentes / rest-pause',
'Intensifier': 'Intensificador',
'None': 'Nenhum',
'Drop-set': 'Série decrescente',
'Rest-pause': 'Rest-pause',
'Drops': 'Quedas',
'Weight drop (%)': 'Queda de peso (%)',
'Rest-pause reps': 'Repetições rest-pause',
'Rest-pause rest': 'Descanso rest-pause',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Cada série torna-se uma série decrescente: depois da série principal, {0} queda(s) sem descanso, cada uma cerca de {1}% mais leve.',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Cada série torna-se rest-pause: {0} repetições para começar, depois mais {1} divididas em rajadas curtas, com {2}s de descanso antes de cada uma, reduzindo cerca de metade a cada vez.',
'Cardio logged': 'Cardio registado',
'Discard workout?': 'Descartar treino?',
'The sets you logged in this session will be lost.': 'As séries registadas nesta sessão vão perder-se.',
@@ -206,6 +225,7 @@ export default {
'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)',
'Superset with exercise above': 'Supersérie com o exercício acima',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Nota (opcional) — dicas de carga, ex. "só a barra, depois +1 anilha por lado a cada série", o que quiser lembrar',
'No exercises yet — add your first one.': 'Ainda sem exercícios — adiciona o primeiro.',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Toca no botão de ligação num exercício para o juntar em supersérie com o de cima — vais fazê-los seguidos.',
'Delete routine?': 'Eliminar rotina?',
@@ -256,6 +276,7 @@ export default {
'Theme': 'Tema',
'Dark': 'Escuro',
'Light': 'Claro',
'System': 'Sistema',
'Accent color': 'Cor de destaque',
'General': 'Geral',
'During a workout': 'Durante o treino',
@@ -268,6 +289,8 @@ export default {
'Data': 'Dados',
'Export backup (JSON)': 'Exportar cópia (JSON)',
'Import backup': 'Importar cópia',
'Auto-backup on changes': 'Cópia automática ao alterar',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Guarda uma cópia datada na pasta Documentos após terminar um treino ou editar uma rotina — aponta uma app de sincronização para lá, ou copia o ficheiro à mão.',
'Reset everything?': 'Repor tudo?',
'Reset everything': 'Repor tudo',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Elimina o teu plano, treinos e peso corporal neste dispositivo. Não pode ser anulado.',
@@ -720,5 +743,77 @@ export default {
'secondary': 'secundário',
'No exercises with an estimated 1RM yet.': 'Ainda não há exercícios com 1RM estimado.',
'Tap a muscle to see its exercises.': 'Toque num músculo para ver os seus exercícios.',
'Unpair': 'Desfazer'
'Unpair': 'Desfazer',
// --- equipment profiles ---
'Showing all equipment': 'A mostrar todo o equipamento',
'Showing what you have in "{0}"': 'A mostrar o que tens em «{0}»',
'Show all equipment': 'Mostrar todo o equipamento',
'Filter by "{0}"': 'Filtrar por «{0}»',
'Edit profile': 'Editar perfil',
'New equipment profile': 'Novo perfil de equipamento',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'Dá-lhe o nome do sítio onde treinas — p. ex. «Casa» ou «Ginásio» — e marca o que tens lá.',
'Profile name': 'Nome do perfil',
'Body-weight exercises are always available, in every profile.': 'Os exercícios com o peso do corpo estão sempre disponíveis, em todos os perfis.',
'{0} of {1} exercises need equipment outside "{2}"': '{0} de {1} exercícios precisam de equipamento fora de «{2}»',
'Needs {0} — not in your active profile': 'Precisa de {0} — não está no teu perfil ativo',
'Filter by equipment': 'Filtrar por equipamento',
'Active profile': 'Perfil ativo',
'{0} equipment types': '{0} tipos de equipamento',
'Add equipment profile': 'Adicionar perfil de equipamento',
'Delete profile?': 'Eliminar perfil?',
'"{0}" and its equipment list will be removed.': '«{0}» e a respetiva lista de equipamento serão removidos.',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Filtra a biblioteca de exercícios e o seletor, e assinala os exercícios das rotinas que precisam de algo que não tens no perfil ativo.',
// --- muscle groups ---
'Primary muscle groups': 'Grupos musculares primários',
'Additional muscle groups': 'Grupos musculares adicionais',
'No explicit muscle group': 'Nenhum grupo muscular explícito',
// "Connect to my server" (mobile app pairing)
'Your server': 'O teu servidor',
'Synced with your openGym server.': 'Sincronizado com o teu servidor openGym.',
'Disconnect': 'Desligar',
'Disconnect from your server?': 'Desligar do teu servidor?',
'Your data is synced to your server first, then this device switches back to local-only.': 'Os teus dados são primeiro sincronizados com o teu servidor, depois este dispositivo volta ao modo local.',
'Disconnected — back to local-only': 'Desligado — de volta ao modo local',
'Connect to my server': 'Ligar ao meu servidor',
'Sync this device to your own self-hosted openGym instead.': 'Sincroniza este dispositivo com o teu próprio openGym self-hosted.',
'Pair the mobile app': 'Emparelhar a app móvel',
'Connect the openGym app on your phone to this account.': 'Liga a app openGym no teu telemóvel a esta conta.',
'Could not generate a code': 'Não foi possível gerar um código',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'Na app openGym, escolhe «Ligar ao meu servidor», depois introduz este endereço e o código abaixo. Expira em 5 minutos.',
'Enter your server address and the code': 'Introduz o endereço do teu servidor e o código',
'Connected': 'Ligado',
'Could not connect': 'Não foi possível ligar',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'Em Definições → «Emparelhar a app móvel» no site openGym em que já tens sessão iniciada, introduz depois o endereço e o código apresentado aí.',
'Server address (e.g. gym.example.com)': 'Endereço do servidor (ex. gym.example.com)',
'Pairing code': 'Código de emparelhamento',
'Connecting…': 'A ligar…',
'Connect': 'Ligar',
'How do you want to use openGym?': 'Como queres usar o openGym?',
'Use on this device': 'Usar neste dispositivo',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Local mantém tudo neste telemóvel. Ligar sincroniza antes com o teu próprio servidor openGym — podes mudar mais tarde em Definições.',
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — concluído',
'Workout done': 'Treino concluído',
'reps': 'reps',
'Most reps in a set per workout': 'Mais reps numa série por treino',
'Warm-up sets': 'Séries de aquecimento',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'São acrescentadas antes das tuas séries de trabalho e ficam de fora do volume, dos recordes e da progressão. Cada uma reduz a metade a distância até ao peso de trabalho — podes alterá-las durante a sessão.',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Séries de aproximação antes das séries de trabalho, para não teres de as acrescentar à mão em cada treino.',
'Note': 'Nota',
'This session': 'Esta sessão',
'How it went, what to change — kept with today’s workout.': 'Como correu, o que mudar — fica guardado com o treino de hoje.',
'Show this next time': 'Mostrar da próxima vez',
'Brings it up again the next time you train this exercise.': 'Volta a aparecer da próxima vez que treinares este exercício.',
'Always for this exercise': 'Sempre neste exercício',
'Seat height, pin position, a form cue — shown every session.': 'Altura do banco, posição do pino, uma indicação técnica — visível em todas as sessões.',
'From {0}:': 'De {0}:',
'Session note': 'Nota da sessão',
'Add session note': 'Adicionar nota da sessão',
'Edit session note': 'Editar nota da sessão',
'How the session went as a whole.': 'Como correu a sessão no seu todo.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'O rest-pause treina sempre como uma série de aquecimento com estas repetições e uma série de trabalho rest-pause — «Séries» não é usado.'
}
+96 -1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Подтвердить',
'Cancel': 'Отмена',
'Press back again to exit': 'Нажмите «Назад» ещё раз, чтобы выйти',
'Delete': 'Удалить',
'Save': 'Сохранить',
'Import': 'Импорт',
@@ -163,6 +164,24 @@ export default {
'Warm-up': 'Разминка',
'Add warm-up set': 'Добавить разминочный подход',
'Add set': 'Добавить подход',
'+ Drop': '+ Дроп-сет',
'+ Burst': '+ Серия рест-пауз',
'Drop {0}': 'Дроп-сет {0}',
'Burst {0}': 'Серия {0}',
'Remove drop': 'Убрать дроп-сет',
'Remove burst': 'Убрать серию',
'Rest (s)': 'Отдых (с)',
'Drop-set / rest-pause': 'Дроп-сет / рест-пауза',
'Intensifier': 'Интенсификатор',
'None': 'Нет',
'Drop-set': 'Дроп-сет',
'Rest-pause': 'Рест-пауза',
'Drops': 'Дроп-сеты',
'Weight drop (%)': 'Снижение веса (%)',
'Rest-pause reps': 'Повторения рест-паузы',
'Rest-pause rest': 'Отдых рест-паузы',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Каждый подход становится дроп-сетом: после основного подхода {0} снижение(й) без отдыха, каждое примерно на {1}% легче.',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Каждый подход становится рест-паузой: сначала {0} повторений, затем ещё {1}, разбитых на короткие серии, с {2} с отдыха перед каждой, каждый раз примерно вдвое меньше.',
'Cardio logged': 'Кардио записано',
'Discard workout?': 'Отменить тренировку?',
'The sets you logged in this session will be lost.': 'Подходы, записанные в этой сессии, будут потеряны.',
@@ -206,6 +225,7 @@ export default {
'Create one or load the starter plan.': 'Создай программу или загрузи стартовый план.',
'Load starter plan (Push / Pull / Legs)': 'Загрузить стартовый план (Push / Pull / Ноги)',
'Superset with exercise above': 'Суперсет с упражнением выше',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Заметка (необязательно) — подсказки по нагрузке, напр. «только гриф, затем +1 блин на сторону каждый подход», всё, что стоит запомнить',
'No exercises yet — add your first one.': 'Упражнений пока нет — добавь первое.',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Нажми кнопку связи у упражнения, чтобы объединить его в суперсет с тем, что выше — сделаешь их подряд.',
'Delete routine?': 'Удалить программу?',
@@ -256,6 +276,7 @@ export default {
'Theme': 'Тема',
'Dark': 'Тёмная',
'Light': 'Светлая',
'System': 'Системная',
'Accent color': 'Акцентный цвет',
'General': 'Основное',
'During a workout': 'Во время тренировки',
@@ -268,6 +289,8 @@ export default {
'Data': 'Данные',
'Export backup (JSON)': 'Экспорт резервной копии (JSON)',
'Import backup': 'Импорт резервной копии',
'Auto-backup on changes': 'Автосохранение копии при изменениях',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Сохраняет копию с датой в папку «Документы» после завершения тренировки или редактирования программы — направьте туда приложение синхронизации или скопируйте файл вручную.',
'Reset everything?': 'Сбросить всё?',
'Reset everything': 'Сбросить всё',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Удаляет план, тренировки и вес тела на этом устройстве. Отменить нельзя.',
@@ -720,5 +743,77 @@ export default {
'secondary': 'вспомогательная',
'No exercises with an estimated 1RM yet.': 'Пока нет упражнений с расчётным 1ПМ.',
'Tap a muscle to see its exercises.': 'Нажмите на мышцу, чтобы увидеть её упражнения.',
'Unpair': 'Разъединить'
'Unpair': 'Разъединить',
// --- equipment profiles ---
'Showing all equipment': 'Показан весь инвентарь',
'Showing what you have in "{0}"': 'Показано то, что есть в «{0}»',
'Show all equipment': 'Показать весь инвентарь',
'Filter by "{0}"': 'Фильтровать по «{0}»',
'Edit profile': 'Изменить профиль',
'New equipment profile': 'Новый профиль инвентаря',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'Назови его по месту тренировок — например, «Дом» или «Зал» — и отметь, что там есть.',
'Profile name': 'Название профиля',
'Body-weight exercises are always available, in every profile.': 'Упражнения с собственным весом доступны всегда, в любом профиле.',
'{0} of {1} exercises need equipment outside "{2}"': '{0} из {1} упражнений требуют инвентаря вне «{2}»',
'Needs {0} — not in your active profile': 'Нужен инвентарь: {0} — его нет в активном профиле',
'Filter by equipment': 'Фильтровать по инвентарю',
'Active profile': 'Активный профиль',
'{0} equipment types': 'Типов инвентаря: {0}',
'Add equipment profile': 'Добавить профиль инвентаря',
'Delete profile?': 'Удалить профиль?',
'"{0}" and its equipment list will be removed.': '«{0}» и его список инвентаря будут удалены.',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Фильтрует библиотеку упражнений и выбор, а также отмечает упражнения в программах, для которых нужно то, чего нет в активном профиле.',
// --- muscle groups ---
'Primary muscle groups': 'Основные группы мышц',
'Additional muscle groups': 'Дополнительные мышечные группы',
'No explicit muscle group': 'Без явной мышечной группы',
// "Connect to my server" (mobile app pairing)
'Your server': 'Ваш сервер',
'Synced with your openGym server.': 'Синхронизировано с вашим сервером openGym.',
'Disconnect': 'Отключить',
'Disconnect from your server?': 'Отключиться от сервера?',
'Your data is synced to your server first, then this device switches back to local-only.': 'Сначала данные синхронизируются с сервером, затем это устройство вернётся в локальный режим.',
'Disconnected — back to local-only': 'Отключено — снова локальный режим',
'Connect to my server': 'Подключиться к моему серверу',
'Sync this device to your own self-hosted openGym instead.': 'Синхронизировать это устройство с вашим собственным self-hosted openGym.',
'Pair the mobile app': 'Сопряжение мобильного приложения',
'Connect the openGym app on your phone to this account.': 'Подключите приложение openGym на телефоне к этому аккаунту.',
'Could not generate a code': 'Не удалось создать код',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'В приложении openGym выберите «Подключиться к моему серверу», затем введите этот адрес и код ниже. Он действителен 5 минут.',
'Enter your server address and the code': 'Введите адрес вашего сервера и код',
'Connected': 'Подключено',
'Could not connect': 'Не удалось подключиться',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'В Настройках → «Сопряжение мобильного приложения» на сайте openGym, где вы уже вошли, введите его адрес и показанный там код.',
'Server address (e.g. gym.example.com)': 'Адрес сервера (например, gym.example.com)',
'Pairing code': 'Код сопряжения',
'Connecting…': 'Подключение…',
'Connect': 'Подключить',
'How do you want to use openGym?': 'Как вы хотите использовать openGym?',
'Use on this device': 'Использовать на этом устройстве',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': 'Локальный режим хранит всё на этом телефоне. Подключение вместо этого синхронизирует данные с вашим сервером openGym — вы сможете изменить это позже в Настройках.',
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — сделано',
'Workout done': 'Тренировка сделана',
'reps': 'повт.',
'Most reps in a set per workout': 'Больше всего повт. в подходе за тренировку',
'Warm-up sets': 'Разминочные подходы',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Добавляются перед рабочими подходами и не учитываются в объёме, рекордах и прогрессии. Каждый вдвое сокращает разрыв до рабочего веса — во время тренировки их всё равно можно изменить.',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Подводящие подходы перед рабочими, чтобы не добавлять их вручную каждый раз.',
'Note': 'Заметка',
'This session': 'Эта тренировка',
'How it went, what to change — kept with today’s workout.': 'Как прошло, что изменить — останется с сегодняшней тренировкой.',
'Show this next time': 'Показать в следующий раз',
'Brings it up again the next time you train this exercise.': 'Появится снова, когда вы в следующий раз будете делать это упражнение.',
'Always for this exercise': 'Всегда для этого упражнения',
'Seat height, pin position, a form cue — shown every session.': 'Высота сиденья, положение фиксатора, подсказка по технике — видно на каждой тренировке.',
'From {0}:': 'От {0}:',
'Session note': 'Заметка о тренировке',
'Add session note': 'Добавить заметку',
'Edit session note': 'Изменить заметку',
'How the session went as a whole.': 'Как прошла тренировка в целом.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause всегда выполняется как один разминочный подход с этим числом повторений и один рабочий подход rest-pause — «Подходы» не используются.'
}
+96 -1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Onayla',
'Cancel': 'İptal',
'Press back again to exit': 'Çıkmak için geri tuşuna tekrar basın',
'Delete': 'Sil',
'Save': 'Kaydet',
'Import': 'İçe aktar',
@@ -163,6 +164,24 @@ export default {
'Warm-up': 'Isınma',
'Add warm-up set': 'Isınma seti ekle',
'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)',
'Drop-set / rest-pause': 'Düşüş seti / rest-pause',
'Intensifier': 'Yoğunlaştırıcı',
'None': 'Yok',
'Drop-set': 'Düşüş seti',
'Rest-pause': 'Rest-pause',
'Drops': 'Düşüşler',
'Weight drop (%)': 'Ağırlık düşüşü (%)',
'Rest-pause reps': 'Rest-pause tekrarları',
'Rest-pause rest': 'Rest-pause dinlenmesi',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': 'Her set düşüş setine dönüşür: ana setten sonra dinlenmeden {0} düşüş, her biri yaklaşık %{1} daha hafif.',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': 'Her set rest-pause olur: başlangıçta {0} tekrar, ardından kısa patlamalara bölünmüş {1} tekrar daha, her birinden önce {2} sn dinlenme, her seferinde yaklaşık yarıya inerek.',
'Cardio logged': 'Kardiyo kaydedildi',
'Discard workout?': 'Antrenman iptal edilsin mi?',
'The sets you logged in this session will be lost.': 'Bu oturumda kaydettiğin setler kaybolacak.',
@@ -206,6 +225,7 @@ export default {
'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)',
'Superset with exercise above': 'Üstteki egzersizle süperset',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': 'Not (isteğe bağlı) — yükleme ipuçları, örn. "sadece bar, sonra her sette +1 disk/taraf", aklında tutmak istediğin her şey',
'No exercises yet — add your first one.': 'Henüz egzersiz yok — ilkini ekle.',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': 'Bir egzersizde bağlama düğmesine dokunarak üsttekiyle süperset yap — arka arkaya yaparsın.',
'Delete routine?': 'Rutin silinsin mi?',
@@ -256,6 +276,7 @@ export default {
'Theme': 'Tema',
'Dark': 'Koyu',
'Light': 'Açık',
'System': 'Sistem',
'Accent color': 'Vurgu rengi',
'General': 'Genel',
'During a workout': 'Antrenman sırasında',
@@ -268,6 +289,8 @@ export default {
'Data': 'Veriler',
'Export backup (JSON)': 'Yedeği dışa aktar (JSON)',
'Import backup': 'Yedeği içe aktar',
'Auto-backup on changes': 'Değişikliklerde otomatik yedek',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': 'Bir antrenmanı bitirdikten veya bir rutini düzenledikten sonra Belgeler klasörüne tarihli bir kopya kaydeder — bir senkronizasyon uygulamasını o klasöre yönlendir ya da dosyayı elle kopyala.',
'Reset everything?': 'Her şey sıfırlansın mı?',
'Reset everything': 'Her şeyi sıfırla',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': 'Bu cihazdaki planını, antrenmanlarını ve vücut ağırlığını siler. Geri alınamaz.',
@@ -720,5 +743,77 @@ export default {
'secondary': 'ikincil',
'No exercises with an estimated 1RM yet.': 'Henüz tahmini 1RM olan egzersiz yok.',
'Tap a muscle to see its exercises.': 'Egzersizlerini görmek için bir kas seçin.',
'Unpair': 'Ayır'
'Unpair': 'Ayır',
// --- equipment profiles ---
'Showing all equipment': 'Tüm ekipman gösteriliyor',
'Showing what you have in "{0}"': '“{0}” içinde sahip olduklarını gösteriyor',
'Show all equipment': 'Tüm ekipmanı göster',
'Filter by "{0}"': '“{0}” ile filtrele',
'Edit profile': 'Profili düzenle',
'New equipment profile': 'Yeni ekipman profili',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': 'Antrenman yaptığın yerin adını ver — örn. “Ev” veya “Spor salonu” — sonra orada nelerin olduğunu işaretle.',
'Profile name': 'Profil adı',
'Body-weight exercises are always available, in every profile.': 'Vücut ağırlığı hareketleri her profilde her zaman kullanılabilir.',
'{0} of {1} exercises need equipment outside "{2}"': '{1} hareketten {0} tanesi “{2}” dışında ekipman gerektiriyor',
'Needs {0} — not in your active profile': '{0} gerekiyor — aktif profilinde yok',
'Filter by equipment': 'Ekipmana göre filtrele',
'Active profile': 'Aktif profil',
'{0} equipment types': '{0} ekipman türü',
'Add equipment profile': 'Ekipman profili ekle',
'Delete profile?': 'Profil silinsin mi?',
'"{0}" and its equipment list will be removed.': '“{0}” ve ekipman listesi kaldırılacak.',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': 'Hareket kitaplığını ve seçiciyi filtreler, ayrıca aktif profilinde olmayan bir şeye ihtiyaç duyan rutin hareketlerini işaretler.',
// --- muscle groups ---
'Primary muscle groups': 'Birincil kas grupları',
'Additional muscle groups': 'Ek kas grupları',
'No explicit muscle group': 'Açık kas grubu yok',
// "Connect to my server" (mobile app pairing)
'Your server': 'Sunucun',
'Synced with your openGym server.': 'openGym sunucunla senkronize edildi.',
'Disconnect': 'Bağlantıyı kes',
'Disconnect from your server?': 'Sunucuyla bağlantı kesilsin mi?',
'Your data is synced to your server first, then this device switches back to local-only.': 'Verilerin önce sunucunla senkronize edilir, ardından bu cihaz yerel moda geri döner.',
'Disconnected — back to local-only': 'Bağlantı kesildi — yerel moda dönüldü',
'Connect to my server': 'Sunucuma bağlan',
'Sync this device to your own self-hosted openGym instead.': "Bu cihazı bunun yerine kendi self-hosted openGym'inle senkronize et.",
'Pair the mobile app': 'Mobil uygulamayı eşleştir',
'Connect the openGym app on your phone to this account.': 'Telefonundaki openGym uygulamasını bu hesaba bağla.',
'Could not generate a code': 'Kod oluşturulamadı',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': 'openGym uygulamasında “Sunucuma bağlan”ı seç, ardından bu adresi ve aşağıdaki kodu gir. 5 dakika içinde sona erer.',
'Enter your server address and the code': 'Sunucu adresini ve kodu gir',
'Connected': 'Bağlandı',
'Could not connect': 'Bağlanılamadı',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': 'Zaten oturum açtığın openGym sitesinde Ayarlar → “Mobil uygulamayı eşleştir”i aç, ardından adresini ve orada gösterilen kodu gir.',
'Server address (e.g. gym.example.com)': 'Sunucu adresi (ör. gym.example.com)',
'Pairing code': 'Eşleştirme kodu',
'Connecting…': 'Bağlanıyor…',
'Connect': 'Bağlan',
'How do you want to use openGym?': "openGym'i nasıl kullanmak istersin?",
'Use on this device': 'Bu cihazda kullan',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': "Yerel, her şeyi bu telefonda tutar. Bağlanmak ise bunun yerine kendi openGym sunucunla senkronize eder — bunu daha sonra Ayarlar'dan değiştirebilirsin.",
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — tamamlandı',
'Workout done': 'Antrenman tamamlandı',
'reps': 'tekrar',
'Most reps in a set per workout': 'Antrenman başına bir sette en çok tekrar',
'Warm-up sets': 'Isınma setleri',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': 'Çalışma setlerinden önce eklenir; hacim, rekor ve ilerlemeye sayılmaz. Her biri çalışma ağırlığına kalan farkı yarıya indirir — antrenman sırasında yine de değiştirebilirsin.',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': 'Çalışma setlerinden önce eklenen hazırlık setleri, böylece her antrenmanda elle eklemen gerekmez.',
'Note': 'Not',
'This session': 'Bu antrenman',
'How it went, what to change — kept with today’s workout.': 'Nasıl geçti, neyi değiştirmeli — bugünün antrenmanıyla saklanır.',
'Show this next time': 'Bir dahaki sefere göster',
'Brings it up again the next time you train this exercise.': 'Bu hareketi bir dahaki çalışmanda yeniden karşına çıkar.',
'Always for this exercise': 'Bu harekette her zaman',
'Seat height, pin position, a form cue — shown every session.': 'Sehpa yüksekliği, pim konumu, bir teknik ipucu — her antrenmanda görünür.',
'From {0}:': '{0} tarihinden:',
'Session note': 'Antrenman notu',
'Add session note': 'Antrenman notu ekle',
'Edit session note': 'Antrenman notunu düzenle',
'How the session went as a whole.': 'Antrenmanın genel olarak nasıl geçtiği.',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause her zaman bu tekrar sayısında bir ısınma seti ve bir rest-pause çalışma seti olarak çalışılır — “Setler” kullanılmaz.'
}
+96 -1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': '确认',
'Cancel': '取消',
'Press back again to exit': '再按一次返回退出',
'Delete': '删除',
'Save': '保存',
'Import': '导入',
@@ -163,6 +164,24 @@ export default {
'Warm-up': '热身',
'Add warm-up set': '添加热身组',
'Add set': '加一组',
'+ Drop': '+ 递减组',
'+ Burst': '+ 爆发组',
'Drop {0}': '递减组 {0}',
'Burst {0}': '爆发组 {0}',
'Remove drop': '移除递减组',
'Remove burst': '移除爆发组',
'Rest (s)': '休息(秒)',
'Drop-set / rest-pause': '递减组 / 歇息暂停组',
'Intensifier': '强化技巧',
'None': '无',
'Drop-set': '递减组',
'Rest-pause': '歇息暂停组',
'Drops': '递减次数',
'Weight drop (%)': '减重幅度(%)',
'Rest-pause reps': '歇息暂停次数',
'Rest-pause rest': '歇息暂停休息',
'Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.': '每组都变成递减组:主组之后,无休息完成 {0} 次递减,每次约减轻 {1}%。',
'Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.': '每组都变成歇息暂停组:先做 {0} 次,再分成几个短爆发共 {1} 次,每次前休息 {2} 秒,每次数量大约减半。',
'Cardio logged': '有氧已记录',
'Discard workout?': '放弃训练?',
'The sets you logged in this session will be lost.': '本次记录的组数将丢失。',
@@ -206,6 +225,7 @@ export default {
'Create one or load the starter plan.': '创建一个或加载入门计划。',
'Load starter plan (Push / Pull / Legs)': '加载入门计划(推 / 拉 / 腿)',
'Superset with exercise above': '与上面的动作组成超级组',
'Note (optional) — loading cues, "bar only then +1 plate/side each set", anything worth remembering here': '备注(可选)— 加重提示,例如"空杠开始,之后每组每侧+1片",任何你想记住的内容',
'No exercises yet — add your first one.': '还没有动作——添加第一个吧。',
'Tap the link button on an exercise to superset it with the one above — you’ll do them back-to-back.': '点击动作上的链接按钮,可与上面的动作组成超级组——你将连续完成它们。',
'Delete routine?': '删除训练日?',
@@ -256,6 +276,7 @@ export default {
'Theme': '主题',
'Dark': '深色',
'Light': '浅色',
'System': '跟随系统',
'Accent color': '强调色',
'General': '通用',
'During a workout': '训练期间',
@@ -268,6 +289,8 @@ export default {
'Data': '数据',
'Export backup (JSON)': '导出备份(JSON)',
'Import backup': '导入备份',
'Auto-backup on changes': '变更时自动备份',
'Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.': '完成训练或编辑计划后,会在「文档」文件夹中保存一份带日期的副本——可以让同步应用指向该文件夹,或手动复制出来。',
'Reset everything?': '重置所有内容?',
'Reset everything': '重置所有内容',
'Deletes your plan, workouts and body weight on this device. This cannot be undone.': '删除本设备上的计划、训练和体重。无法撤销。',
@@ -720,5 +743,77 @@ export default {
'secondary': '次要',
'No exercises with an estimated 1RM yet.': '暂无估算1RM的动作。',
'Tap a muscle to see its exercises.': '点击肌肉查看其动作。',
'Unpair': '取消组合'
'Unpair': '取消组合',
// --- equipment profiles ---
'Showing all equipment': '正在显示全部器械',
'Showing what you have in "{0}"': '正在显示你在“{0}”拥有的器械',
'Show all equipment': '显示全部器械',
'Filter by "{0}"': '按“{0}”筛选',
'Edit profile': '编辑配置',
'New equipment profile': '新建器械配置',
'Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.': '用你训练的地点命名 —— 例如“家里”或“健身房”—— 然后勾选你在那里有的器械。',
'Profile name': '配置名称',
'Body-weight exercises are always available, in every profile.': '自重动作在每个配置中都始终可用。',
'{0} of {1} exercises need equipment outside "{2}"': '{1} 个动作中有 {0} 个需要“{2}”之外的器械',
'Needs {0} — not in your active profile': '需要{0} —— 不在你的当前配置中',
'Filter by equipment': '按器械筛选',
'Active profile': '当前配置',
'{0} equipment types': '{0} 种器械',
'Add equipment profile': '添加器械配置',
'Delete profile?': '删除配置?',
'"{0}" and its equipment list will be removed.': '“{0}”及其器械清单将被删除。',
'Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.': '筛选动作库和选择器,并标记训练计划中需要当前配置里没有的器械的动作。',
// --- muscle groups ---
'Primary muscle groups': '主要肌群',
'Additional muscle groups': '其他肌群',
'No explicit muscle group': '无明确肌群',
// "Connect to my server" (mobile app pairing)
'Your server': '你的服务器',
'Synced with your openGym server.': '已与你的 openGym 服务器同步。',
'Disconnect': '断开连接',
'Disconnect from your server?': '要断开与服务器的连接吗?',
'Your data is synced to your server first, then this device switches back to local-only.': '你的数据会先同步到服务器,然后此设备将切换回本地模式。',
'Disconnected — back to local-only': '已断开连接——已切换回本地模式',
'Connect to my server': '连接到我的服务器',
'Sync this device to your own self-hosted openGym instead.': '改为将此设备与你自己的自托管 openGym 同步。',
'Pair the mobile app': '配对手机应用',
'Connect the openGym app on your phone to this account.': '将手机上的 openGym 应用连接到此账户。',
'Could not generate a code': '无法生成配对码',
'On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.': '在 openGym 应用中选择“连接到我的服务器”,然后输入此地址和下面的配对码。5 分钟后失效。',
'Enter your server address and the code': '输入你的服务器地址和配对码',
'Connected': '已连接',
'Could not connect': '无法连接',
'Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.': '在你已登录的 openGym 网站上,打开设置 →“配对手机应用”,然后输入其地址和那里显示的配对码。',
'Server address (e.g. gym.example.com)': '服务器地址(例如 gym.example.com)',
'Pairing code': '配对码',
'Connecting…': '连接中…',
'Connect': '连接',
'How do you want to use openGym?': '你想如何使用 openGym?',
'Use on this device': '在此设备上使用',
'Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.': '本地模式会把所有内容保留在这部手机上。连接则会改为与你自己的 openGym 服务器同步——之后可以在设置中更改。',
// --- workout notes and planned warm-ups ---
'{0} — done': '{0} — 已完成',
'Workout done': '训练已完成',
'reps': '次',
'Most reps in a set per workout': '每次训练单组最多次数',
'Warm-up sets': '热身组',
'Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.': '加在正式组之前,不计入容量、纪录和进阶。每一组都把与正式重量的差距减半 —— 训练中仍可随时调整。',
'Ramp-up sets added before the work sets, so you do not have to add them by hand each session.': '在正式组之前加入的爬升组,这样就不用每次手动添加。',
'Note': '备注',
'This session': '本次训练',
'How it went, what to change — kept with today’s workout.': '感觉如何、下次要改什么 —— 随今天的训练一起保存。',
'Show this next time': '下次显示',
'Brings it up again the next time you train this exercise.': '下次练这个动作时会再次出现。',
'Always for this exercise': '这个动作始终显示',
'Seat height, pin position, a form cue — shown every session.': '座椅高度、插销位置、动作要点 —— 每次训练都会显示。',
'From {0}:': '来自 {0}:',
'Session note': '训练备注',
'Add session note': '添加训练备注',
'Edit session note': '编辑训练备注',
'How the session went as a whole.': '这次训练整体感觉如何。',
'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause 始终按这个次数练一个热身组,再加一个 rest-pause 正式组 —— 不使用“组数”。'
}
+335 -30
View File
@@ -1,20 +1,21 @@
import { useEffect, useRef, useState } from 'react'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf } from './lib/exercises.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 { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, isBw, isPerSide, sideReps, workSetsDone } from './lib/history.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 { beep, vibrate } from './lib/sound.js'
import { t, instrFor, getLang, INSTR_LANGS } from './lib/i18n.js'
import { t, instrFor, exerciseNameFor, getLang, INSTR_LANGS } from './lib/i18n.js'
import { nav } from './lib/nav.js'
import { starterRoutines } from './lib/starter.js'
import Media, { Thumb } from './components/Media.jsx'
import Stepper from './components/Stepper.jsx'
import Icon from './components/Icon.jsx'
import { Button, Slider, Switch, Segmented, SelectRow, Row } from './components/ui.jsx'
import { Button, Slider, Switch, Segmented, SelectRow, Row, TextField, MultiSelectRow } from './components/ui.jsx'
import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'
import BodyMap from './components/BodyMap.jsx'
import { exerciseMuscleSnapshot, loadOfWorkouts } from './lib/muscles.js'
import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, normalizeMuscleGroups, hasExplicitMuscleMetadata } from './lib/muscles.js'
import { parseImport, mergeImport } from './lib/import-csv.js'
import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'
import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'
@@ -106,7 +107,18 @@ function BwSheet({ required, onDone, close }) {
const recent = [...st.bodyweight].reverse().slice(0, 3)
const delEntry = d => update(s => { s.bodyweight = s.bodyweight.filter(b => b.d !== d) })
return <>
<h3>{required ? t('Quick check-in') : t('Log body weight')}</h3>
{/* This sheet opens `locked` — swipe/backdrop/Escape/Android-back all no-op on it (see
Modals.jsx) so an accidental tap on "Start" can't be walked back by reflex the way
every other sheet in the app can. The two buttons below already cover leaving it
deliberately; this is the same close a normal sheet gets everywhere else, just
opted back in explicitly instead of by omission. Plain close() — no onDone, no
nav — so it's a true no-op: the screen underneath is exactly where you left it. */}
{required
? <div className="row between" style={{ marginBottom: 14 }}>
<h3 style={{ marginBottom: 0 }}>{t('Quick check-in')}</h3>
<button className="iconbtn" aria-label={t('Cancel')} onClick={() => close()}><Icon name="xmark" /></button>
</div>
: <h3>{t('Log body weight')}</h3>}
<div className="muted small">{required ? t('Slide or tap to set your weight — tracked before every workout so your curve stays honest.') : t('Today') + ', ' + fmtDate(todayISO(), true)}</div>
<WeightInput value={v} setValue={setV} unit={unit} />
<div style={{ height: 14 }} />
@@ -287,13 +299,13 @@ function ExerciseDetail({ ex, close }) {
const last = lastEntryFor(st, ex.id)
const best = bestWeightFor(st, ex.id)
return <>
<h3 className="capitalize">{ex.n}</h3>
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
<Media ex={ex} />
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0' }}>
<span className="tag acc">{t(ex.bp)}</span>
{ex.tg && <span className="tag"><Icon name="target" />{t(ex.tg)}</span>}
{(ex.primaries?.length ? ex.primaries : (ex.tg ? [ex.tg] : [])).map((s, i) => <span key={i} className="tag"><Icon name="target" />{t(s)}</span>)}
<span className="tag"><Icon name="dumbbell" />{t(ex.eq)}</span>
{smOf(ex).slice(0, 3).map((s, i) => <span key={i} className="tag">{t(s)}</span>)}
{(ex.secondaries?.length ? ex.secondaries : smOf(ex)).slice(0, 3).map((s, i) => <span key={i} className="tag">{t(s)}</span>)}
</div>
{ex.desc && <div className="exnote">{ex.desc}</div>}
{best > 0 && <div className="small row" style={{ marginBottom: 6, gap: 5 }}><Icon name="trophy" style={{ fontSize: 14, color: 'var(--yellow)' }} />{t('Best:')} <b className="accent">{fmtNum(best)} {st.unit}</b>{last ? ` · ${t('last')} ${fmtDate(last.d)}: ${last.sets.map(s => setLabel(ex.id, s, last.target)).join(', ')}` : ''}</div>}
@@ -321,12 +333,12 @@ function AddToRoutine({ ex, close }) {
if (r) r.ex.push({ id: ex.id, ...cfg })
})
const r = isNew ? S().routines[S().routines.length - 1] : st.routines.find(x => x.id === rid)
toast(t('“{0}” added to {1}', ex.n, r ? r.name : t('routine')))
toast(t('“{0}” added to {1}', exerciseNameFor(ex), r ? r.name : t('routine')))
if (isNew && r) nav('/plan/r/' + r.id)
}, null, isNew ? null : st.routines.find(x => x.id === rid))
}
return <>
<h3 className="capitalize">{t('Add “{0}”', ex.n)}</h3>
<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)}>
@@ -348,6 +360,18 @@ function CustomExForm({ existing, prefill, onDone, close }) {
const [n, setN] = useState(existing ? existing.n : (prefill || ''))
const [bp, setBp] = useState(existing ? existing.bp : '')
const [desc, setDesc] = useState(existing ? (existing.desc || '') : '')
const [primaries, setPrimaries] = useState(() => {
if (existing && Array.isArray(existing.primaries) && existing.primaries.length) return [...existing.primaries]
const norm = hasExplicitMuscleMetadata(existing || {}) ? normalizeMuscleGroups(existing || {}) : []
return norm.length ? [norm[0]] : []
})
const [secondaries, setSecondaries] = useState(() => {
if (existing && Array.isArray(existing.primaries) && existing.primaries.length) return [...(existing.secondaries || [])]
const norm = hasExplicitMuscleMetadata(existing || {}) ? normalizeMuscleGroups(existing || {}) : []
return norm.slice(1)
})
const togglePrimary = value => setPrimaries(current => current.includes(value) ? current.filter(m => m !== value) : [...current, value])
const toggleSecondary = value => setSecondaries(current => current.includes(value) ? current.filter(m => m !== value) : [...current, value])
const save = () => {
const name = n.trim()
if (!name) { toast(t('Give it a name')); return }
@@ -355,11 +379,16 @@ function CustomExForm({ existing, prefill, onDone, close }) {
const dup = allExercises(S()).find(e => e.n.toLowerCase() === name.toLowerCase() && e.id !== (existing || {}).id)
if (dup) { toast(t('“{0}” already exists', dup.n)); return }
const d = desc.trim().slice(0, 1000)
const prim = [...primaries]
const sm = secondaries.filter(m => !prim.includes(m))
const groups = [...prim, ...sm]
let id = existing && existing.id
if (existing) update(s => { const c = (s.customEx || []).find(x => x.id === id); if (c) { c.n = name; c.bp = bp; c.desc = d } })
if (existing) update(s => { const c = (s.customEx || []).find(x => x.id === id); if (c) {
c.n = name; c.bp = bp; c.desc = d; c.tg = prim[0] || ''; c.sm = sm; c.muscleGroups = groups; c.primaries = prim; c.secondaries = sm
} })
else {
id = 'c' + uid()
update(s => { (s.customEx = s.customEx || []).push({ id, n: name, bp, desc: d, tg: '', eq: 'custom', custom: true }) })
update(s => { (s.customEx = s.customEx || []).push({ id, n: name, bp, desc: d, tg: prim[0] || '', sm, muscleGroups: groups, primaries: prim, secondaries: sm, eq: 'custom', custom: true }) })
}
close()
toast(existing ? t('Saved') : t('“{0}” created', name))
@@ -372,6 +401,16 @@ function CustomExForm({ existing, prefill, onDone, close }) {
<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>
{bp && bp !== 'cardio' && <>
<MultiSelectRow title={t('Primary muscle groups')} sheetTitle={t('Primary muscle groups')}
values={primaries}
options={MUSCLES.map(m => ({ value: m, label: t(MUSCLE_NAME[m]) }))}
onToggle={togglePrimary} noneLabel={t('No explicit muscle group')} doneLabel={t('Done')} />
<MultiSelectRow title={t('Additional muscle groups')} sheetTitle={t('Additional muscle groups')}
values={secondaries}
options={MUSCLES.filter(m => !primaries.includes(m)).map(m => ({ value: m, label: t(MUSCLE_NAME[m]) }))}
onToggle={toggleSecondary} noneLabel={t('No explicit muscle group')} doneLabel={t('Done')} />
</>}
{bp === 'cardio' && <div className="small dim row" style={{ marginBottom: 10, gap: 5 }}><Icon name="figureRun" style={{ fontSize: 13 }} />{t('Cardio exercises log time + speed instead of weight × reps.')}</div>}
<textarea className="input" rows={4} maxLength={1000} placeholder={t('Description (optional) — setup, cues, anything you want to remember')}
value={desc} onChange={e => setDesc(e.target.value)} />
@@ -421,22 +460,31 @@ function ExercisePicker({ onPick, close }) {
const [q, setQ] = useState('')
const [bp, setBp] = useState('') // '' = all, '★' = chosen, else a body part
const [eq, setEq] = useState('') // '' = any equipment
const [showAll, setShowAll] = useState(false)
const [shown, setShown] = useState(50)
const ql = q.toLowerCase().trim()
const all = allExercises(st)
const profile = activeProfile(st)
let base = all.filter(e =>
(bp === '★' ? usage[e.id] : (!bp || e.bp === bp)) &&
(!ql || e.n.toLowerCase().includes(ql) || e.tg.includes(ql) || e.eq.includes(ql) || (e.desc || '').toLowerCase().includes(ql)))
if (bp === '★') base = [...base].sort((a, b) => (usage[b.id] - usage[a.id]) || (a.n < b.n ? -1 : 1))
const eqOpts = equipmentOf(base)
matchExercise(e, q))
if (bp === '★') base = [...base].sort((a, b) => (usage[b.id] - usage[a.id]) || exerciseNameFor(a).localeCompare(exerciseNameFor(b)))
const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(st, e)) : base
const eqOpts = equipmentOf(eqFiltered)
// 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 ? base.filter(e => e.eq === eqOn) : base
const f = eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered
const chosenCount = Object.keys(usage).length
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>
{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)}
<button className="chip nocap" style={{ marginLeft: 'auto', padding: '3px 10px', fontSize: 12 }} onClick={() => setShowAll(v => !v)}>
{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' }}>
{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>
@@ -452,7 +500,7 @@ function ExercisePicker({ onPick, close }) {
<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)}>
<Thumb ex={e} /><div className="grow"><div className="tt capitalize">{e.n}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
<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>)}
{f.length === 0 && bp === '★' && <div className="empty">{t('Nothing chosen yet — add exercises and they’ll show up here.')}</div>}
@@ -462,6 +510,50 @@ function ExercisePicker({ onPick, close }) {
}
export const exercisePicker = onPick => ui().openSheet(close => <ExercisePicker onPick={onPick} close={close} />)
/* ============================ equipment profiles ============================ */
// Create or edit one profile ("Home", "Gym", ...): a name plus a checklist of what you have.
function EquipmentProfileSheet({ profile, close }) {
const update = useStore(s => s.update)
const nameRef = useRef(null)
const [checked, setChecked] = useState(new Set(profile?.equipment || []))
const toggle = k => setChecked(s => { const n = new Set(s); n.has(k) ? n.delete(k) : n.add(k); return n })
const save = () => {
const name = (nameRef.current.value || '').trim()
if (!name) { return }
update(s => {
s.equipProfiles = s.equipProfiles || []
const equipment = [...checked]
if (profile) {
const p = s.equipProfiles.find(x => x.id === profile.id)
if (p) { p.name = name; p.equipment = equipment }
} else {
const p = newProfile(name); p.equipment = equipment
s.equipProfiles.push(p)
if (!s.activeEquipId) s.activeEquipId = p.id
}
})
close()
}
return <>
<h3>{profile ? t('Edit profile') : t('New equipment profile')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>
{t('Name it after where you train — e.g. "Home" or "Gym" — then check what you have there.')}
</div>
<TextField ref={nameRef} defaultValue={profile?.name || ''} placeholder={t('Profile name')} maxLength={40} />
<div style={{ height: 12 }} />
<div className="chips">
{ALL_EQUIPMENT.map(k => (
<button key={k} className={'chip' + (checked.has(k) ? ' on' : '')} onClick={() => toggle(k)}>{t(k)}</button>
))}
</div>
<div className="dim small" style={{ marginTop: 10 }}>
{t('Body-weight exercises are always available, in every profile.')}
</div>
<div style={{ height: 14 }} /><Button variant="primary" onClick={save}>{t('Save')}</Button>
</>
}
export const equipmentProfileSheet = profile => ui().openSheet(close => <EquipmentProfileSheet profile={profile} close={close} />)
/* ============================ exercise config ============================ */
// 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
@@ -516,26 +608,43 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
// rather than carrying a flag nothing downstream can read.
const flags = {}
if (bw !== isBodyweightEq(ex.id)) flags.bodyweight = bw
if (cardio) onSave({ sets, min: Math.max(1, Math.round(c.min) || 20), speed: Math.max(0, c.speed || 8) })
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 })
// Free text, e.g. a pyramid's per-set loading ("bar only, +1 plate/side each set") — the
// sets/reps/weight fields are one flat target and have no room for that on their own.
// Mode-independent, so it is spread in below rather than folded into `flags`.
const note = (c.note || '').trim().slice(0, 500)
const withNote = note ? { note } : {}
// Only written when there are any, so a plan that never asked for warm-ups keeps the exact
// 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 })
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 }
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)))
// 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) —
// decided here, in the plan, not re-decided live each time you train it.
if (c.intensifier && c.intensifier.type) out.intensifier = c.intensifier
onSave(out)
}
}
return <>
<h3 className="capitalize">{ex.n}</h3>
<h3 className="capitalize">{exerciseNameFor(ex)}</h3>
<Media ex={ex} />
{/* The same tags the exercise detail sheet shows, secondaries included: choosing what goes
into a plan is exactly when "what else does this hit" matters, and until now that was
only visible from the Exercises tab, after the fact. */}
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '10px 0 14px' }}>
{cardio && <span className="tag acc"><Icon name="figureRun" />{t('Cardio')}</span>}
<span className="tag">{t(ex.tg || ex.bp)}</span><span className="tag">{t(ex.eq)}</span>
{!cardio && (ex.secondaries?.length ? ex.secondaries : smOf(ex)).slice(0, 3)
.map((s, i) => <span key={i} className="tag dim">{t(s)}</span>)}
</div>
{ex.desc && <div className="exnote">{ex.desc}</div>}
{!cardio && <div style={{ marginBottom: 14 }}>
@@ -552,13 +661,33 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
<Stepper label={t('Seconds')} value={c.sec} step={5} decimal={false} onChange={v => setC(x => ({ ...x, sec: v }))} />
<Stepper label={t('Weight ({0})', st.unit)} value={c.weight} step={2.5} onChange={v => setC(x => ({ ...x, weight: v }))} />
</> : <>
<Stepper label={t('Sets')} value={c.sets} step={1} decimal={false} onChange={v => setC(x => ({ ...x, sets: v }))} />
{/* Rest-pause always trains as exactly two rows — a warm-up at this rep count, then one
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 }))} />
{/* 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 }))} />}
</>}
</div>
{c.intensifier?.type === 'restpause' && <div className="small dim" style={{ marginTop: -10, marginBottom: 18 }}>
{t('Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.')}
</div>}
{/* Planned warm-ups: the session used to start at the work weight and you added every
warm-up by hand, every time. Rest-pause is excluded because it builds its own warm-up
row, and cardio because an interval plan has no load to ramp. */}
{!cardio && c.intensifier?.type !== 'restpause' && <>
<div className="row cfgrow" style={{ marginBottom: 6 }}>
<Stepper label={t('Warm-up sets')} value={c.warmupSets || 0} step={1} decimal={false}
onChange={v => setC(x => ({ ...x, warmupSets: Math.max(0, Math.min(MAX_PLANNED_WARMUPS, Math.round(v) || 0)) }))} />
</div>
<div className="small dim" style={{ marginBottom: 18 }}>
{(c.warmupSets || 0) > 0
? t('Added before your work sets and left out of volume, records and progression. Each one closes half the gap to the work weight — you can still change any of them mid-session.')
: t('Ramp-up sets added before the work sets, so you do not have to add them by hand each session.')}
</div>
</>}
{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>}
@@ -597,7 +726,47 @@ function ExConfig({ ex, existing, onSave, onDelete, close, routine, initial }) {
? t('Reps climb to {0}, then a set is added and the reps start over. At {1} sets it asks you to add weight instead.', c.repsMax, MAX_BW_SETS)
: t('Reps climb by one whenever every set was clean. Set a ceiling to add sets instead of reps forever.')}
</div>}
{mode === 'reps' && <>
<h4 className="sec">{t('Drop-set / rest-pause')}</h4>
<div className="sect-b" style={{ marginBottom: 8 }}>
<SelectRow title={t('Intensifier')} sheetTitle={t('Intensifier')} value={c.intensifier?.type || ''}
onChange={v => setC(x => ({
...x,
intensifier: !v ? undefined : v === 'dropset'
? { type: 'dropset', count: x.intensifier?.count || 1, pct: x.intensifier?.pct || 20 }
// The activation set's own reps are whatever "Reps" above already says — a
// rest-pause plan only adds two new numbers: the total extra reps wanted past
// it, and the rest between the bursts that total gets split into.
: { type: 'restpause', totalReps: x.intensifier?.totalReps || x.reps || 8, restSec: x.intensifier?.restSec || st.restPauseSec || 15 },
}))}
options={[
{ value: '', label: t('None') },
{ value: 'dropset', label: t('Drop-set') },
{ value: 'restpause', label: t('Rest-pause') },
]} />
</div>
{c.intensifier?.type === 'dropset' && <div className="row cfgrow" style={{ marginBottom: 8 }}>
<Stepper label={t('Drops')} value={c.intensifier.count} step={1} decimal={false}
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, count: Math.max(1, v) } }))} />
<Stepper label={t('Weight drop (%)')} value={c.intensifier.pct} step={5} decimal={false}
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, pct: Math.max(5, v) } }))} />
</div>}
{c.intensifier?.type === 'restpause' && <div className="row cfgrow" style={{ marginBottom: 8 }}>
<Stepper label={t('Rest-pause reps')} value={c.intensifier.totalReps} step={1} decimal={false}
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, totalReps: Math.max(1, v) } }))} />
<Stepper label={t('Rest (s)')} value={c.intensifier.restSec} step={5} decimal={false}
onChange={v => setC(x => ({ ...x, intensifier: { ...x.intensifier, restSec: Math.max(5, v) } }))} />
</div>}
{c.intensifier?.type && <div className="small dim" style={{ marginTop: -2, marginBottom: 18 }}>
{c.intensifier.type === 'dropset'
? t('Every set becomes a drop-set: after the main set, {0} drop(s) with no rest, each about {1}% lighter.', c.intensifier.count, c.intensifier.pct)
: t('Every set becomes rest-pause: {0} reps to start, then {1} more split into short bursts, {2}s rest before each, roughly halving each time.', c.reps || 0, c.intensifier.totalReps, c.intensifier.restSec)}
</div>}
</>}
<ProgressionFields ex={ex} mode={mode} c={c} setC={setC} routine={routine} unit={st.unit} />
<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>
{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></>}
@@ -755,6 +924,32 @@ export const dayAssignSheet = day => ui().openSheet(close => <DayAssign day={day
/* ============================ workout detail ============================ */
function WorkoutDetail({ w, close }) {
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
// record about a session is often clearer once you have looked at what you actually did.
const [note, setNote] = useState(w.note || '')
const saveNote = () => update(s => {
const rec = s.workouts.find(x => x.id === w.id)
if (!rec) return
const text = note.trim().slice(0, NOTE_MAX)
if (text) rec.note = text; else delete rec.note
})
// onBlur alone loses the note: Escape, the Android back gesture and swipe-to-dismiss all
// close the sheet without ever moving focus out of the textarea. Flush on unmount too. The
// ref is what makes that work — a cleanup closes over the note from its own render, which
// is the empty string this started with.
const latest = useRef(note)
latest.current = note
const initial = useRef(w.note || '')
useEffect(() => () => {
const text = latest.current.trim().slice(0, NOTE_MAX)
if (text === initial.current) return
update(s => {
const rec = s.workouts.find(x => x.id === w.id)
if (!rec) return // deleted from this very sheet
if (text) rec.note = text; else delete rec.note
})
}, [])
return <>
<h3>{w.name}</h3>
<div className="muted small" style={{ marginBottom: 12 }}>{[fmtDate(w.d, true), ...durPart(w.end - w.start), fmtVol(w.vol, st.unit), ...(w.bw ? [fmtNum(w.bw) + ' ' + st.unit] : [])].join(' · ')}</div>
@@ -762,10 +957,18 @@ function WorkoutDetail({ w, close }) {
const ex = EXIDX[e.id]
return <div key={i} className="row" style={{ marginBottom: 12, alignItems: 'flex-start' }}>
{ex && <Thumb ex={ex} />}
<div className="grow"><div className="tt capitalize" style={{ fontWeight: 600 }}>{ex ? ex.n : (e.n || e.id)} {w.prs && w.prs.includes(e.id) && <span className="pr"><Icon name="trophy" />PR</span>}</div>
<div className="ss">{e.sets.filter(s => s.done).map(s => setLabel(e.id, s, e.target)).join(' · ') || t('no sets')}</div></div>
<div className="grow"><div className="tt capitalize" style={{ fontWeight: 600 }}>{ex ? exerciseNameFor(ex) : (e.n || e.id)} {w.prs && w.prs.includes(e.id) && <span className="pr"><Icon name="trophy" />PR</span>}</div>
<div className="ss">{e.sets.filter(s => s.done).map(s => setLabel(e.id, s, e.target)).join(' · ') || t('no sets')}</div>
{e.note && <div className="small dim" style={{ marginTop: 3 }}>
{e.notePin && <Icon name="flag" style={{ fontSize: 12, marginRight: 4, verticalAlign: '-1px', color: 'var(--yellow)' }} />}{e.note}
</div>}</div>
</div>
})}
<div className="small muted" style={{ margin: '4px 0 6px' }}>{t('Session note')}</div>
<textarea 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} />
<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>
</>
}
@@ -838,7 +1041,9 @@ export function beginWorkout(routineId, bw) {
// 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)
return { id: cfg.id, sg: cfg.sg, target: { ...cfg }, plan, sets: applyPrescription(buildSets(st, cfg), plan) }
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 }
})
update(s => {
s.active = { id: uid(), d: todayISO(), start: Date.now(), routineId, name: r ? r.name : t('Freestyle'), bw: bw || null, cur: 0, entries }
@@ -883,7 +1088,7 @@ function TopWeight({ entryIdx, close }) {
} else toast(t('Tracked — next time starts at {0}', fmtNum(S().exWeights[entry.id].w) + ' ' + st.unit))
}
return <>
<h3 className="capitalize row" style={{ gap: 8 }}><Icon name="checkCircle" style={{ color: 'var(--acc)' }} />{t('{0} done', ex.n)}</h3>
<h3 className="capitalize row" style={{ gap: 8 }}><Icon name="checkCircle" style={{ color: 'var(--acc)' }} />{t('{0} done', exerciseNameFor(ex))}</h3>
<div className="muted small">{t('Confirm the weight you worked with — your highest becomes the default next time.')}{!unitDone && unit.length > 1 ? ' ' + t('Then finish the superset partner.') : ''}</div>
<WeightInput value={v} setValue={setV} unit={st.unit} />
<div style={{ height: 10 }} />
@@ -896,6 +1101,105 @@ function TopWeight({ entryIdx, close }) {
}
export const topWeightSheet = entryIdx => ui().openSheet(close => <TopWeight entryIdx={entryIdx} close={close} />)
/* ============================ exercise notes ============================
Two notes, one sheet, because from the user's side it is one question — "what do I want to
remember about this exercise?" — with two different lifetimes:
· today's note belongs to this session and is stored on the workout entry. It is history:
what happened, how it felt. The PIN is the user saying "this one is for next time", which
only they can know at the moment of writing — see pinnedNoteFor.
· the standing note belongs to the exercise itself and lives in S.exNotes. Seat height, pin
position, a form cue. True every session, so it is shown every session and never expires.
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 st = useStore(s => s.S)
const update = useStore(s => s.update)
const A = st.active
const entry = A ? A.entries[entryIdx] : null
const ex = entry ? exOr(entry.id) : null
const [note, setNote] = useState(entry?.note || '')
const [pin, setPin] = useState(!!entry?.notePin)
const [standing, setStanding] = useState(entry ? (st.exNotes?.[entry.id] || '') : '')
useEffect(() => { if (!entry) close() }, [!entry])
if (!entry) return null
const save = () => {
const today = note.trim().slice(0, NOTE_MAX)
const always = standing.trim().slice(0, NOTE_MAX)
update(s => {
const e = s.active?.entries?.[entryIdx]
if (e) {
if (today) { e.note = today; if (pin) e.notePin = true; else delete e.notePin }
else { delete e.note; delete e.notePin }
}
s.exNotes = s.exNotes || {}
if (always) s.exNotes[entry.id] = always
else delete s.exNotes[entry.id]
})
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}
placeholder={t('How it went, what to change — kept with today’s workout.')}
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')}
subtitle={t('Brings it up again the next time you train this exercise.')}>
<Switch checked={pin} onChange={setPin} disabled={!note.trim()} />
</Row>
</div>
<div style={{ height: 18 }} />
<div className="small muted" style={{ marginBottom: 6 }}>{t('Always for this exercise')}</div>
<textarea className="input" rows={2} maxLength={NOTE_MAX} value={standing}
placeholder={t('Seat height, pin position, a form cue — shown every session.')}
onChange={e => setStanding(e.target.value)} />
<div style={{ height: 18 }} />
<Button variant="primary" onClick={save}>{t('Save')}</Button>
</>
}
export const exerciseNoteSheet = entryIdx => ui().openSheet(close => <ExerciseNote entryIdx={entryIdx} close={close} />)
/* The session note: how the whole workout went, as opposed to how one exercise went. It lives
on the active session, so buildCompletedWorkout carries it onto the finished workout and it
shows up again in history — where it stays editable. Written here rather than only after the
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 st = useStore(s => s.S)
const update = useStore(s => s.update)
const A = st.active
const [note, setNote] = useState(A?.note || '')
useEffect(() => { if (!A) close() }, [!A])
if (!A) return null
const save = () => {
const text = note.trim().slice(0, NOTE_MAX)
update(s => { if (!s.active) return; if (text) s.active.note = text; else delete s.active.note })
close()
}
return <>
<h3>{t('Session note')}</h3>
<textarea className="input" rows={4} maxLength={NOTE_MAX} value={note}
placeholder={t('How the session went as a whole.')}
onChange={e => setNote(e.target.value)} />
<div style={{ height: 18 }} />
<Button variant="primary" onClick={save}>{t('Save')}</Button>
</>
}
export const sessionNoteSheet = () => ui().openSheet(close => <SessionNote close={close} />)
/* Drop-set drops and rest-pause bursts are edited inline on the set row itself (Workout.jsx) —
no sheet, no timer. A planned exercise (see the "Intensifier" config below) arrives with them
already computed via applyIntensifierPlan; an unplanned straight set can still grow one live
by tapping "+ Drop"/"+ Burst", which appends with the same suggested-next-value math. */
// Shown when the last exercise's last set is checked — finish, or keep going.
function WorkoutComplete({ close }) {
return <div style={{ textAlign: 'center', padding: '8px 0' }}>
@@ -921,8 +1225,8 @@ function FinishSummary({ w, prs, e1prs = [], close }) {
<div className="tile"><div className="l">{t('PRs')}</div><div className="v" style={{ fontSize: 20 }}>{prs.length || '—'}</div></div>
</div>
{(prs.length > 0 || e1prs.length > 0) && <div style={{ textAlign: 'left', marginBottom: 12 }}>
{prs.map(id => <div key={id} className="small accent capitalize row" style={{ gap: 5 }}><Icon name="trophy" style={{ fontSize: 13 }} />{t('New PR:')} {(EXIDX[id] || {}).n || id}</div>)}
{e1prs.map(p => <div key={p.id} className="small accent capitalize row" style={{ gap: 5 }}><Icon name="chartLine" style={{ fontSize: 13 }} />{t('Best estimated 1RM:')} {(EXIDX[p.id] || {}).n || p.id} · {fmtNum(p.est)} {st.unit}</div>)}
{prs.map(id => <div key={id} className="small accent capitalize row" style={{ gap: 5 }}><Icon name="trophy" style={{ fontSize: 13 }} />{t('New PR:')} {EXIDX[id] ? exerciseNameFor(EXIDX[id]) : id}</div>)}
{e1prs.map(p => <div key={p.id} className="small accent capitalize row" style={{ gap: 5 }}><Icon name="chartLine" style={{ fontSize: 13 }} />{t('Best estimated 1RM:')} {EXIDX[p.id] ? exerciseNameFor(EXIDX[p.id]) : p.id} · {fmtNum(p.est)} {st.unit}</div>)}
</div>}
<h4 className="sec" style={{ textAlign: 'left' }}>{t('What you just trained')}</h4>
<BodyMap load={loadOfWorkouts([w])} body={st.body} />
@@ -967,6 +1271,7 @@ function doFinishWorkout() {
s.workouts.push(w)
s.active = null
})
useStore.getState().autoBackupNow()
useUI.getState().stopRest()
beep(snd(), 880, 0.15); beep(snd(), 1100, 0.15, 0.18); beep(snd(), 1320, 0.3, 0.36)
ui().openSheet(close => <FinishSummary w={w} prs={prs} e1prs={e1prs} close={close} />, { kind: 'center', locked: true })
+69 -7
View File
@@ -1,14 +1,15 @@
import { create } from 'zustand'
import { api } from '../lib/api.js'
import { api, setRemoteAuth } from '../lib/api.js'
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 } from '../lib/mobile.js'
import { MOBILE, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js'
import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js'
const KEY = 'gym_state_v1'
export const DEF = {
unit: 'kg', restSec: 90, sound: true, keepAwake: true, lang: 'en',
unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, keepAwake: true, lang: 'en',
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full',
@@ -16,7 +17,14 @@ export const DEF = {
// that a profile which never chose (loaded state is overlaid on DEF, on every path: local,
// server pull, backup import) still falls back to the `showRir` boolean this replaced and
// keeps the column it had. See effortOf.
reminder: { on: false, time: '08:00', tz: null }, effort: null
reminder: { on: false, time: '08:00', tz: null }, effort: null, autoBackup: false,
// Equipment profiles (issue: filter Library/picker/routines by what you actually own —
// e.g. "Home" vs "Gym" — building on the session-only equipment filter from issue #6).
equipProfiles: [], activeEquipId: null, equipFilterOn: false,
// Standing per-exercise notes, keyed by exercise id: the gym-specific facts that are true
// 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: {},
}
const clone = o => JSON.parse(JSON.stringify(o))
@@ -89,6 +97,7 @@ export const useStore = create((set, get) => {
hangs off it via coachAvailable(), so an unconfigured instance renders exactly what it
always did, and a configured one is the only place any of it appears. */
config: null,
needsMobileOnboarding: false, // mobile build only — set true by boot() on a genuine first launch
// Mutate a draft of S via producer fn, then persist + schedule sync.
update(mut, push = true) {
@@ -98,6 +107,14 @@ export const useStore = create((set, get) => {
},
replaceState(S, push = false) { persist(clone(S), push) },
// Fires after the moments where losing local data would actually hurt — a workout just
// logged, a routine just edited — not on every keystroke. No-op off mobile or with the
// setting off; the private file mirror (nativePersist, above) already covers every change.
autoBackupNow() {
const S = get().S
if (MOBILE && S.autoBackup) writeAutoBackup(S)
},
isGuest: () => localStorage.getItem('gym_guest') === '1',
setGuest(v) { if (v) localStorage.setItem('gym_guest', '1'); else localStorage.removeItem('gym_guest'); set({}) },
@@ -142,6 +159,31 @@ export const useStore = create((set, get) => {
clearLocalSession()
},
// Mobile-only ("connect to my server" onboarding, see App.jsx's needsMobileOnboarding).
// Picking local — even before there's any data — persists the choice so onboarding never
// asks again.
async chooseLocalMode() {
await chooseLocal()
set({ needsMobileOnboarding: false })
},
// Redeems the pairing code shown in the browser (Settings → "Pair the mobile app") and
// switches this device over to that account, same as signing in on the web does.
async connectToServer(url, code) {
const user = await connect(url, code) // throws on a bad URL/expired code — caller shows it
get().setUser(user)
await get().pullState()
syncReminder(get().S)
set({ needsMobileOnboarding: false })
},
// Leaves remote mode and drops cleanly back to local-only, without losing whatever was last
// synced (signOut() already pushes before it clears).
async disconnectServer() {
await get().signOut()
await forgetRemote()
get().setGuest(true)
set({ ready: true })
},
// "Sign out everywhere": the server bumps this profile's session version, which kills every
// session it has on any device — this browser included, so the app has to end up exactly
// where a normal signOut leaves it. Unlike signOut the request is NOT swallowed: if it fails
@@ -163,9 +205,26 @@ export const useStore = create((set, get) => {
// Boot: ask the server who we are, then pull.
async boot() {
// Mobile build: no backend either — restore from the file mirror (the durable copy;
// localStorage may have been evicted since the last run) and go straight in.
// Mobile build: no backend by default — restore from the file mirror (the durable copy;
// localStorage may have been evicted since the last run) and go straight in. Unless this
// device was paired to a server ("connect to my server" mode, lib/remote.js), in which
// case it behaves exactly like the signed-in web flow below, straight from here.
if (MOBILE) {
const remote = await loadRemote()
if (remote?.mode === 'remote') {
setRemoteAuth(remote.base, remote.token)
try {
const me = await api('/api/me') // also catches a token revoked elsewhere (sign out everywhere)
get().setUser(me.user)
await get().pullState()
} catch (e) {
if (e.status === 401) { await forgetRemote(); get().setGuest(true) }
else get().setUser(remote.user) // offline — keep going from the last-synced local copy
}
syncReminder(get().S)
set({ ready: true })
return
}
const saved = await nativeLoad()
const S = get().S
if (saved && (!hasData(S) || (saved._ts || 0) >= (S._ts || 0))) {
@@ -175,7 +234,10 @@ export const useStore = create((set, get) => {
}
get().setGuest(true)
syncReminder(get().S)
set({ ready: true })
// Only a genuinely first launch — nothing chosen yet and nothing to lose either — offers
// the choice. Picking local (even with no data yet) persists that choice below and this
// never asks again.
set({ ready: true, needsMobileOnboarding: !remote && !hasData(get().S) })
return
}
// Demo build (GitHub Pages): no backend at all — seed once, stay in guest mode.
+3
View File
@@ -76,6 +76,9 @@ export const useUI = create((set, get) => ({
startRest(sec) {
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 } })
requestRestNotificationPermission()
+28
View File
@@ -0,0 +1,28 @@
// @vitest-environment happy-dom
// 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'
// "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.
describe('rest timer set to Off', () => {
beforeEach(() => { vi.useFakeTimers(); useUI.setState({ timer: null }) })
afterEach(() => { useUI.getState().stopRest(); vi.useRealTimers() })
it('starts nothing', () => {
useUI.getState().startRest(0)
expect(useUI.getState().timer).toBe(null)
})
it('stops a rest that is already running', () => {
useUI.getState().startRest(90)
expect(useUI.getState().timer).not.toBe(null)
useUI.getState().startRest(0)
expect(useUI.getState().timer).toBe(null)
})
it('still runs for a real duration', () => {
useUI.getState().startRest(90)
expect(useUI.getState().timer.total).toBe(90)
})
})
+63 -1
View File
@@ -4,6 +4,7 @@ import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { api } from '../lib/api.js'
import { fmtDate, fmtNum, fmtVol, fmtDur } from '../lib/format.js'
import { auditCat, auditLine, fmtWhen } from '../lib/audit.js'
import { workoutVolume, setsDone } from '../lib/history.js'
import { confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
@@ -89,6 +90,64 @@ function InvitesCard({ invites, reload }) {
</div>
}
// Who signed in, who tried and failed, what an admin changed. A card rather than its own route:
// the dashboard is deliberately one page of cards, and the 95 % use of this is a glance at the
// last twenty events. Paging follows Library.jsx's house style — "Show more", not page numbers.
function AuditCard({ tick }) {
const toast = useUI(s => s.toast)
const [meta, setMeta] = useState(null) // last response minus the rows: total, retention, …
const [rows, setRows] = useState([])
const [cat, setCat] = useState('')
const load = (c, before) => api('/api/admin/audit?limit=50&cat=' + c + (before ? '&before=' + before : ''))
.then(r => { setMeta(r); setRows(x => (before ? x.concat(r.events) : r.events)) })
.catch(e => toast(e.message))
const pick = c => { setCat(c); setRows([]); setMeta(null); load(c) }
// Reloads on mount and whenever the header's ↻ bumps the tick. Deliberately not on the 15s
// poll that drives "training now": this is history, not presence.
useEffect(() => { load(cat) }, [tick])
const clear = () => confirmSheet({
title: 'Clear the activity log?',
message: 'Every recorded event is deleted. The clear itself is logged, so the gap stays visible.',
confirmText: 'Clear', danger: true,
onConfirm: () => api('/api/admin/audit/clear', { method: 'POST', body: '{}' })
.then(() => { toast('Activity log cleared'); pick(cat) }).catch(e => toast(e.message))
})
if (meta && !meta.enabled) return null // AUDIT_LOG=0 — the card isn't there at all
return <div className="card">
<div className="row between"><h2 style={{ margin: 0 }}>Activity log</h2>
<button className="iconbtn" style={{ width: 32, height: 30, borderRadius: 8, fontSize: 15, color: 'var(--red)' }}
onClick={clear} aria-label="clear log"><Icon name="trash" /></button></div>
<div className="small muted" style={{ margin: '6px 0 10px' }}>
{meta ? fmtNum(meta.total) + ' events'
+ (meta.retention.days ? ' · last ' + meta.retention.days + ' days' : '')
+ (meta.ip_mode === 'off' ? ' · no IP addresses' : '') : 'Loading…'}</div>
<div className="chips" style={{ marginBottom: 10 }}>
{[['', 'All'], ['auth', 'Sign-ins'], ['admin', 'Admin'], ['fail', 'Failed']].map(([v, l]) =>
<button key={v} className={'chip' + (cat === v ? ' on' : '')} onClick={() => pick(v)}>{l}</button>)}
</div>
{rows.map(e => {
const line = auditLine(e)
return <div key={e.id} className="row between" style={{ padding: '8px 2px', borderBottom: '1px solid var(--sep)' }}>
<div className="grow">
<div className="small" style={{ fontWeight: 600 }}>{line.title}
{/* a red pill, not a red row: twenty fumbled Face IDs in a row shouldn't read as an incident */}
{!e.ok && <span className="tag" style={{ marginLeft: 6, color: 'var(--red)' }}>failed</span>}
{auditCat(e.ev) === 'admin' && <span className="tag acc" style={{ marginLeft: 6 }}>admin</span>}</div>
{line.sub && <div className="dim" style={{ fontSize: '.72rem' }}>{line.sub}</div>}
</div>
<span className="small muted" style={{ flex: 'none', marginLeft: 8 }}>{fmtWhen(e.ts, meta?.now)}</span>
</div>
})}
{meta && !rows.length && <div className="dim small">Nothing logged yet.</div>}
{meta?.nextBefore && <div style={{ marginTop: 10 }}>
<Button size="sm" onClick={() => load(cat, meta.nextBefore)}>Show more</Button></div>}
</div>
}
export default function Admin() {
const nav = useNavigate()
const user = useStore(s => s.user)
@@ -97,6 +156,7 @@ export default function Admin() {
const [users, setUsers] = useState(null)
const [invites, setInvites] = useState(null)
const [inviteOnly, setInviteOnly] = useState(false)
const [tick, setTick] = useState(0) // the ↻ button; the activity log listens to it
const loadUsers = () => api('/api/admin/users').then(d => { setUsers(d.users); setInviteOnly(d.invite_only) }).catch(e => toast(e.message || 'Failed to load'))
const loadInvites = () => api('/api/admin/invites').then(d => setInvites(d.invites)).catch(() => {})
@@ -114,7 +174,7 @@ export default function Admin() {
<button className="iconbtn" onClick={() => nav('/settings')} aria-label="Back"><Icon name="chevronLeft" /></button>
<div style={{ flex: 1, marginLeft: 8 }}><h1 style={{ margin: 0 }}>Admin</h1>
<div className="sub">{users ? users.length + ' users · ' + activeCount + ' active this week' : 'Loading…'}</div></div>
<button className="iconbtn" onClick={() => { loadUsers(); loadInvites() }} aria-label="refresh">↻</button>
<button className="iconbtn" onClick={() => { loadUsers(); loadInvites(); setTick(n => n + 1) }} aria-label="refresh">↻</button>
</div>
<div className="tiles" style={{ marginBottom: 12 }}>
@@ -148,5 +208,7 @@ export default function Admin() {
</div>)}
{users && !users.length && <div className="empty">No users yet.</div>}
</div>
<div style={{ marginTop: 14 }}><AuditCard tick={tick} /></div>
</div>
}
+15 -3
View File
@@ -28,6 +28,9 @@ export default function Home() {
const monday = new Date(today); monday.setDate(today.getDate() - ((today.getDay() + 6) % 7) + 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)
@@ -60,18 +63,27 @@ export default function Home() {
<button className="iconbtn" style={{ width: 30, height: 30, fontSize: 15 }} onClick={() => setWeekOffset(w => w + 1)} aria-label="Next week"><Icon name="chevronRight" /></button>
</div>
<div className="week">{strip}</div>
{/* Once today's session is logged the row stops asking for it. The week strip already
knew (its dot goes 'done'); this row did not, so a finished day kept showing the
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="row" style={{ gap: 9, minWidth: 0 }}>
<span className="lrow-i" style={{ background: S.active ? 'var(--orange)' : routine ? 'var(--acc)' : 'var(--surface-3)' }}>
<Icon name={S.active ? 'timer' : routine ? glyphOf(routine.emoji) : 'moon'} />
<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'}
style={doneToday && !S.active ? { color: 'var(--green)' } : undefined} />
</span>
<div style={{ minWidth: 0 }}>
<div className="lbl2">{t('Today')}</div>
<div className="ttl">{S.active ? t('{0} — in progress', S.active.name) : routine ? routine.name : t('Rest day')}{todayOvr && routine ? ' · ' + t('rescheduled') : ''}</div>
<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>}
</div>
</div>
{S.active ? <span className="tag" style={{ color: 'var(--orange)', background: 'color-mix(in srgb,var(--orange) 16%,transparent)' }}>{t('Resume')}</span>
: doneToday ? <span className="tag" style={{ color: 'var(--green)', background: 'color-mix(in srgb,var(--green) 16%,transparent)' }}>{t('Done')}</span>
: routine ? <span className="tag acc">{t('Start')}</span>
: <Icon name="plus" className="chev" />}
</div>
+18 -7
View File
@@ -1,9 +1,10 @@
import { useState } from 'react'
import { useStore } from '../store/useStore.js'
import { EXDB, BODYPARTS, allExercises, equipmentOf } from '../lib/exercises.js'
import { EXDB, BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js'
import { activeProfile, exAvailable } from '../lib/equipment.js'
import { bestWeightFor } from '../lib/history.js'
import { fmtNum } from '../lib/format.js'
import { t } from '../lib/i18n.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { Thumb } from '../components/Media.jsx'
import { exerciseDetailSheet, addToRoutineSheet, customExSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
@@ -14,18 +15,27 @@ export default function Library() {
const [q, setQ] = useState('')
const [bp, setBp] = useState('')
const [eq, setEq] = useState('')
const [showAll, setShowAll] = useState(false) // ignore the active equipment profile for this session
const [shown, setShown] = useState(40)
const ql = q.toLowerCase().trim()
const base = allExercises(S).filter(e => (!bp || e.bp === bp) && (!ql || e.n.toLowerCase().includes(ql) || e.tg.includes(ql) || e.eq.includes(ql) || (e.desc || '').toLowerCase().includes(ql)))
const eqOpts = equipmentOf(base)
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
const eqOpts = equipmentOf(eqFiltered)
// 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 ? base.filter(e => e.eq === eqOn) : base
const f = eqOn ? eqFiltered.filter(e => e.eq === eqOn) : eqFiltered
return <>
<div className="hdr"><div><h1>{t('Exercises')}</h1><div className="sub">{t('{0} exercises with animations', EXDB.length)}</div></div></div>
<div className="search" style={{ marginBottom: 10 }}><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…')} value={q} onChange={e => { setQ(e.target.value); setShown(40) }} /></div>
{profile && <div className="small dim row" style={{ margin: '-4px 2px 10px', gap: 6, alignItems: 'center' }}>
<Icon name="dumbbell" style={{ fontSize: 13 }} />
{showAll ? t('Showing all equipment') : t('Showing what you have in "{0}"', profile.name)}
<button className="chip nocap" style={{ marginLeft: 'auto', padding: '3px 10px', fontSize: 12 }} onClick={() => setShowAll(v => !v)}>
{showAll ? t('Filter by "{0}"', profile.name) : t('Show all equipment')}
</button>
</div>}
<div className="chips" 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>)}
@@ -43,7 +53,7 @@ export default function Library() {
const best = bestWeightFor(S, e.id)
return <div key={e.id} className="item" onClick={() => exerciseDetailSheet(e)}>
<Thumb ex={e} />
<div className="grow"><div className="tt capitalize">{e.n}</div><div className="ss capitalize">{t(e.tg || e.bp)} · {t(e.eq)}</div></div>
<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>}
<Button size="sm" variant="tinted" icon="plus" onClick={ev => { ev.stopPropagation(); addToRoutineSheet(e) }}>{t('Plan')}</Button>
</div>
@@ -53,3 +63,4 @@ export default function Library() {
{f.length > shown && <><div style={{ height: 10 }} /><Button onClick={() => setShown(s => s + 40)}>{t('Show more')}</Button></>}
</>
}
+59
View File
@@ -0,0 +1,59 @@
// Mobile build only, first launch: the choice useStore.boot() couldn't make on its own — keep
// everything on this device, or connect to a self-hosted openGym server instead. See
// lib/remote.js for the pairing flow this hands off to.
import { useState, useRef, useEffect } from 'react'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { t } from '../lib/i18n.js'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
export function ConnectSheet({ close }) {
const { connectToServer } = useStore()
const [url, setUrl] = useState('')
const [code, setCode] = useState('')
const [busy, setBusy] = useState(false)
const ref = useRef(null)
useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, [])
const go = async () => {
if (!url.trim() || !code.trim()) { useUI.getState().toast(t('Enter your server address and the code')); return }
setBusy(true)
try { await connectToServer(url.trim(), code.trim()); close(); useUI.getState().toast(t('Connected')) }
catch (e) { useUI.getState().toast(e.message || t('Could not connect')) }
finally { setBusy(false) }
}
return <>
<h3>{t('Connect to my server')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>
{t('Open Settings → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.')}
</div>
<input ref={ref} className="input" placeholder={t('Server address (e.g. gym.example.com)')} value={url}
onChange={e => setUrl(e.target.value)} autoCapitalize="none" autoCorrect="off" inputMode="url" />
<div style={{ height: 10 }} />
<input className="input" placeholder={t('Pairing code')} maxLength={8} value={code}
onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }} />
<div style={{ height: 12 }} />
<Button variant="primary" onClick={go} disabled={busy}>{busy ? t('Connecting…') : t('Connect')}</Button>
</>
}
export default function MobileOnboarding() {
const { chooseLocalMode } = useStore()
const head = <>
<div style={{ fontSize: 54, display: 'flex', justifyContent: 'center', color: 'var(--acc)' }}><Icon name="dumbbell" /></div>
<h1 style={{ fontSize: 34, fontWeight: 700, letterSpacing: '-.028em', margin: '10px 0 4px' }}>openGym</h1>
</>
const wrap = { display: 'flex', flexDirection: 'column', justifyContent: 'center', minHeight: '78vh', textAlign: 'center' }
return (
<div className="narrow" style={wrap}>
{head}
<div className="muted" style={{ marginBottom: 34 }}>{t('How do you want to use openGym?')}</div>
<Button variant="primary" icon="lock" onClick={() => chooseLocalMode()}>{t('Use on this device')}</Button>
<div style={{ height: 10 }} />
<Button icon="rocket" onClick={() => useUI.getState().openSheet(close => <ConnectSheet close={close} />)}>{t('Connect to my server')}</Button>
<div className="dim small" style={{ marginTop: 26, lineHeight: 1.5 }}>
{t('Local keeps everything on this phone. Connecting syncs to your own openGym server instead — you can switch later in Settings.')}
</div>
</div>
)
}
+19 -2
View File
@@ -2,8 +2,9 @@ import { useNavigate, useParams } from 'react-router-dom'
import { useEffect } 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 } from '../lib/i18n.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { supersetUnits, cleanupSg, exLine } from '../lib/history.js'
import { Thumb } from '../components/Media.jsx'
import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet } from '../sheets.jsx'
@@ -21,6 +22,10 @@ export default function RoutineEdit() {
const update = useStore(s => s.update)
const r = S.routines.find(x => x.id === id)
useEffect(() => { if (!r) nav('/plan') }, [!!r])
// Editing here has no explicit "save" — every field change persists immediately. A single
// 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) })
@@ -36,6 +41,8 @@ export default function RoutineEdit() {
const units = supersetUnits(r.ex)
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)
const missingCount = profile ? r.ex.filter(e => !exAvailable(S, exOr(e.id))).length : 0
return <div className="narrow">
<div className="hdr">
@@ -56,10 +63,18 @@ export default function RoutineEdit() {
{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)' }}>
<div className="row" style={{ gap: 8, alignItems: 'center' }}>
<Icon name="warning" style={{ color: 'var(--orange)' }} />
<div className="small">{t('{0} of {1} exercises need equipment outside "{2}"', missingCount, r.ex.length, profile.name)}</div>
</div>
</div>}
{r.ex.length ? <div className="list">{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}>
{unitFirst.has(i) && <div className="ss-label"><Icon name="link" />{t('Superset')}</div>}
@@ -67,7 +82,9 @@ export default function RoutineEdit() {
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)
}}>
<Thumb ex={ex} />
<div className="grow"><div className="tt capitalize">{ex.n}</div><div className="ss">{exLine(e, S.unit)}</div></div>
<div className="grow"><div className="tt capitalize">{exerciseNameFor(ex)}</div><div className="ss">{exLine(e, S.unit)}</div>
{e.note && <div className="small dim" style={{ marginTop: 2 }}>{e.note}</div>}</div>
{noEquip && <span className="tag" style={{ color: 'var(--orange)', borderColor: 'var(--orange)' }} title={t('Needs {0} — not in your active profile', t(ex.eq))}><Icon name="warning" /></span>}
<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 }}>
+99 -12
View File
@@ -10,7 +10,8 @@ import { wakeLockSupported } from '../lib/wakelock.js'
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 { loadStarterPlan, confirmSheet, importFromApp } from '../sheets.jsx'
import { ConnectSheet } from './MobileOnboarding.jsx'
import { loadStarterPlan, confirmSheet, importFromApp, equipmentProfileSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'
@@ -18,7 +19,7 @@ export default function Settings() {
const nav = useNavigate()
const S = useStore(s => s.S)
const user = useStore(s => s.user)
const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo } = useStore()
const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo, disconnectServer } = useStore()
const toast = useUI(s => s.toast)
const fileRef = useRef(null)
const importRef = useRef(null)
@@ -73,12 +74,21 @@ export default function Settings() {
</div>
{/* ---------- account (demo and mobile builds have nothing to sign in to) ---------- */}
<Section title={MOBILE ? t('Your data') : DEMO ? t('Demo') : t('Account')}>
{MOBILE ? <>
<Section title={MOBILE ? (user ? t('Your server') : t('Your data')) : DEMO ? t('Demo') : t('Account')}>
{MOBILE ? (user ? <>
<Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Synced with your openGym server.')} />
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
<Row icon="signOut" iconTint="var(--red)" title={t('Disconnect')} danger onClick={() => confirmSheet({
title: t('Disconnect from your server?'),
message: t('Your data is synced to your server first, then this device switches back to local-only.'),
confirmText: t('Disconnect'), danger: true,
onConfirm: async () => { await disconnectServer(); nav('/home'); toast(t('Disconnected — back to local-only')) },
})} />
</> : <>
<Row icon="lock" iconTint="var(--acc)" title={t('All data stays on this phone')} subtitle={t('No account, no cloud — back it up anytime with Export below.')} />
<Row icon="rocket" iconTint="var(--indigo)" title={t('Self-host openGym')} subtitle={t('Passkey sign-in, sync across your devices, your own data.')} accessory="chevron"
onClick={() => window.open(REPO, '_blank', 'noopener')} />
</> : DEMO ? <>
<Row icon="link" iconTint="var(--indigo)" title={t('Connect to my server')} subtitle={t('Sync this device to your own self-hosted openGym instead.')} accessory="chevron"
onClick={() => useUI.getState().openSheet(close => <ConnectSheet close={close} />)} />
</>) : DEMO ? <>
<Row icon="sparkles" iconTint="var(--acc)" title={t('You’re in the demo')} subtitle={t('Example data, stored only in this browser — change anything you like.')} />
<Row icon="reset" iconTint="var(--blue)" title={t('Reset demo data')} accessory="chevron"
onClick={() => confirmSheet({ title: t('Reset demo data?'), message: t('Puts the example plan, workouts and weigh-ins back the way they started.'), confirmText: t('Reset'), onConfirm: () => { resetDemo(); nav('/home'); toast(t('Demo data reset')) } })} />
@@ -87,6 +97,8 @@ export default function Settings() {
</> : user ? <>
<Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Signed in with passkey — data syncs to this profile.')} />
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
<Row icon="link" iconTint="var(--blue)" title={t('Pair the mobile app')} subtitle={t('Connect the openGym app on your phone to this account.')} accessory="chevron"
onClick={() => useUI.getState().openSheet(close => <PairSheet close={close} />)} />
<Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: () => { signOut(); nav('/home') } })} />
<Row icon="shield" iconTint="var(--red)" title={t('Sign out everywhere')} subtitle={t('Ends this profile’s sessions on all your devices.')} danger onClick={signOutEverywhere} />
</> : webauthnOK() ? <>
@@ -119,7 +131,13 @@ export default function Settings() {
<Section title={t('During a workout')} footer={wakeOK ? t('The screen stays on while a workout is running, so you don’t have to unlock your phone between sets.') : null}>
<SelectRow icon="timer" iconTint="var(--orange)" title={t('Rest timer')}
value={S.restSec} onChange={v => update(s => { s.restSec = v })}
options={[60, 90, 120, 150, 180].map(v => ({ value: v, label: v + 's' }))} />
options={[{ value: 0, label: t('Off') }, ...[60, 90, 120, 150, 180].map(v => ({ value: v, label: v + 's' }))]} />
{/* Default for a rest-pause burst added live on a plain set — a planned exercise's own
"Rest (s)" (in its Intensifier config) overrides this, same as the main rest timer
is the fallback whenever an exercise has no progression rule of its own. */}
<SelectRow icon="bolt" iconTint="var(--acc)" title={t('Rest-pause rest')}
value={S.restPauseSec} onChange={v => update(s => { s.restPauseSec = v })}
options={[10, 15, 20, 30].map(v => ({ value: v, label: v + 's' }))} />
{(wakeOK || !MOBILE) && (
<Row icon="sun" iconTint="var(--yellow)" title={t('Keep screen awake')}
subtitle={wakeOK ? null : t('Not supported in this browser.')}>
@@ -142,13 +160,20 @@ export default function Settings() {
{(user || MOBILE) && <NotificationsCard S={S} update={update} toast={toast} />}
{/* ---------- equipment ---------- */}
<EquipmentCard S={S} update={update} />
{/* ---------- appearance ---------- */}
<Section title={t('Appearance')} footer={DEMO || MOBILE ? undefined : t('synced with your profile')}>
<Row icon="moon" iconTint="var(--indigo)" title={t('Theme')}>
<Segmented
className="seg-inline"
options={[{ value: 'dark', icon: 'moon', label: t('Dark') }, { value: 'light', icon: 'sun', label: t('Light') }]}
value={S.theme === 'light' ? 'light' : 'dark'}
options={[
{ value: 'dark', icon: 'moon', label: t('Dark') },
{ value: 'light', icon: 'sun', label: t('Light') },
{ value: 'system', icon: 'gear', label: t('System') },
]}
value={S.theme || 'dark'}
onChange={v => update(s => { s.theme = v })}
/>
</Row>
@@ -180,6 +205,10 @@ export default function Settings() {
accessory="chevron" onClick={() => importRef.current.click()} />
<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')}
subtitle={t('Saves a dated copy to the Documents folder after finishing a workout or editing a routine — point a sync app at it, or copy it out by hand.')}>
<Switch checked={!!S.autoBackup} onChange={v => update(s => { s.autoBackup = v })} />
</Row>}
<Row icon="trash" iconTint="var(--red)" title={t('Reset everything')} danger onClick={() => confirmSheet({ title: t('Reset everything?'), message: t('Deletes your plan, workouts and body weight on this device. This cannot be undone.'), confirmText: t('Delete everything'), danger: true, onConfirm: () => { replaceState(JSON.parse(JSON.stringify(DEF)), true); nav('/home'); toast(t('All data reset')) } })} />
</Section>
<input ref={fileRef} type="file" accept=".json,application/json" style={{ display: 'none' }} onChange={doImport} />
@@ -194,9 +223,14 @@ export default function Settings() {
subtitle={t('to install openGym as a full-screen app.') + ' ' + (user ? t('Your data syncs with your profile — sign in anywhere to see it.') : t('Guest data stays on this device — export a backup now and then!'))} />
</Section>}
{/* The version, at the bottom of Settings — which is where the support template has been
telling people to look for it, and where it was not. On the phone build there is no
address bar and no about box, so without this there is no way to tell which build you
are running, or whether an update actually installed. */}
<div className="dim small" style={{ textAlign: 'center', marginTop: 4, lineHeight: 1.6 }}>
openGym · {t('free & open source (AGPL v3)')}<br />
<a href="https://github.com/DuarteSantos8/openGym" target="_blank" rel="noopener">source code</a> · exercise data: hasaneyldrm/exercises-dataset (CC)
openGym v{__APP_VERSION__} · {t('free & open source (AGPL v3)')}<br />
<a href="https://gitlab.com/DuarteSantos8/opengym" target="_blank" rel="noopener">source code</a> · exercise data: hasaneyldrm/exercises-dataset (MIT)<br />
exercise images and animations © <a href="https://gymvisual.com/" target="_blank" rel="noopener">Gym visual</a>
</div>
</div>
}
@@ -327,6 +361,59 @@ function PushCard({ S, update, toast }) {
</>
}
// Equipment profiles ("Home", "Gym", ...) — each an id/name/eq-list; the active one filters
// the Library, exercise picker, and flags routine entries that need something outside it
// (see lib/equipment.js). Purely local/synced state — no server changes needed.
function EquipmentCard({ S, update }) {
const profiles = S.equipProfiles || []
const remove = p => confirmSheet({
title: t('Delete profile?'), message: t('"{0}" and its equipment list will be removed.', p.name),
confirmText: t('Delete'), danger: true,
onConfirm: () => update(s => {
s.equipProfiles = (s.equipProfiles || []).filter(x => x.id !== p.id)
if (s.activeEquipId === p.id) s.activeEquipId = (s.equipProfiles[0] && s.equipProfiles[0].id) || null
}),
})
return <Section title={t('Equipment')} footer={t('Filters the exercise library and picker, and flags routine exercises that need something you don’t have in the active profile.')}>
{profiles.length > 0 && <Row icon="dumbbell" iconTint="var(--acc)" title={t('Filter by equipment')}>
<Switch checked={!!S.equipFilterOn} onChange={v => update(s => { s.equipFilterOn = v })} />
</Row>}
{profiles.length > 0 && <SelectRow icon="list" iconTint="var(--blue)" title={t('Active profile')}
value={S.activeEquipId || ''} onChange={v => update(s => { s.activeEquipId = v })}
options={profiles.map(p => ({ value: p.id, label: p.name }))} />}
{profiles.map(p => (
<Row key={p.id} icon="dumbbell" iconTint="var(--teal)" title={p.name}
subtitle={t('{0} equipment types', p.equipment.length)} accessory="chevron"
onClick={() => equipmentProfileSheet(p)}>
<button className="iconbtn" aria-label={t('Delete')} onClick={ev => { ev.stopPropagation(); remove(p) }}><Icon name="trash" /></button>
</Row>
))}
<Row icon="plus" iconTint="var(--acc)" title={t('Add equipment profile')} accessory="chevron" onClick={() => equipmentProfileSheet(null)} />
</Section>
}
// Lets the mobile app's "connect to my server" mode (lib/remote.js) authenticate without a
// WebAuthn ceremony of its own — the code is minted here, from an already signed-in session,
// and redeemed by the app for a bearer token. See /api/pair/create in api/server.js.
function PairSheet({ close }) {
const [code, setCode] = useState(null)
const [err, setErr] = useState(null)
useEffect(() => { api('/api/pair/create', { method: 'POST', body: '{}' }).then(r => setCode(r.code)).catch(e => setErr(e.message || t('Could not generate a code'))) }, [])
return <>
<h3>{t('Pair the mobile app')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>
{t('On the openGym app, choose “Connect to my server”, then enter this address and the code below. It expires in 5 minutes.')}
</div>
{err ? <div className="dim small">{err}</div> : (
<div className="card" style={{ textAlign: 'center', fontSize: 30, fontWeight: 700, letterSpacing: '.16em', padding: '18px 0' }}>
{code || '········'}
</div>
)}
<div style={{ height: 12 }} />
<Button onClick={close}>{t('Done')}</Button>
</>
}
// The same registration as the sign-in screen's, reached from Settings instead. It asks for
// the invite code on the same terms: an invite-only instance rejects a registration without
// one, so a form that cannot collect it is a form that cannot succeed.
+37 -10
View File
@@ -4,7 +4,7 @@ import { useStore } from '../store/useStore.js'
import { EXIDX } 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 { t } from '../lib/i18n.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'
@@ -102,6 +102,7 @@ function MuscleBalance({ S }) {
const [hard, setHard] = useState(false)
const [sel, setSel] = useState(null)
const now = useNow()
const lang = getLang()
const workouts = S.workouts
// The user's own last registered bodyweight drives bodyweight-exercise tonnage.
const bodyweightKg = useMemo(() => {
@@ -113,7 +114,7 @@ function MuscleBalance({ S }) {
}, [S.bodyweight, S.unit])
const fatigue = useMemo(() => fatigueOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit])
const strength = useMemo(() => strengthOf(workouts, now, { bodyweightKg, unit: S.unit }), [workouts, now, bodyweightKg, S.unit])
const muscleExercises = useMemo(() => (sel ? strengthExerciseRowsForMuscle(S, now, sel) : []), [S, now, sel])
const muscleExercises = useMemo(() => (sel ? strengthExerciseRowsForMuscle(S, now, sel) : []), [S, now, sel, lang])
const lastTrained = useMemo(() => latestMuscleTraining(workouts), [workouts])
const strengthHint = slug => {
if (lastTrained[slug] == null) return t('not trained')
@@ -191,7 +192,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' }}>
<div key={row.id} className="mrow" style={{ minHeight: 48, alignItems: 'stretch', cursor: 'pointer' }} onClick={() => 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}
@@ -290,7 +291,7 @@ 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]?.n || workouts.flatMap(w => w.entries).find(e => e.id === id)?.n || id
const nameOf = id => EXIDX[id] ? exerciseNameFor(EXIDX[id]) : (workouts.flatMap(w => w.entries).find(e => e.id === id)?.n || id)
const currentOf = id => {
for (let i = workouts.length - 1; i >= 0; i--) {
const en = workouts[i].entries.find(e => e.id === id)
@@ -299,6 +300,12 @@ export default function Stats() {
const rows = metricRowsForEntry(en, mode)
const mx = mode === 'reps' ? bestWeightForEntry(en) : Math.max(0, ...rows.map(s => mode === 'cardio' ? (s.speed || 0) : mode === 'time' ? (s.sec || 0) : (s.w || 0)))
if (mx > 0) return { mx, unit: mode === 'cardio' ? 'km/h' : mode === 'time' ? 's' : S.unit }
// Unloaded reps work still has a current figure — its rep count. Without this the whole
// picker label went blank and the exercise sorted to the bottom as if it had no history.
if (mode === 'reps') {
const reps = Math.max(0, ...rows.map(s => Number(s.r) || 0))
if (reps > 0) return { mx: reps, unit: t('reps') }
}
}
return { mx: 0, unit: S.unit }
}
@@ -320,8 +327,18 @@ export default function Stats() {
})() : 'reps'
const curCardio = curMode === 'cardio'
const curTimed = curMode === 'time'
// A pull-up or a push-up carries no weight, so its "best weight" is 0 — and dropping every
// zero point left the card reading "No data yet" for exercises with a full history behind
// them (issue #5). When nothing in an exercise's history was ever loaded, the progress IS
// the rep count, so plot that. Add a weighted set later and it switches back to weight on
// its own, which is also the honest reading: that is when load became the thing improving.
const repsOnly = curEx && curMode === 'reps' && !workouts.some(w => {
const en = w.entries.find(e => e.id === curEx)
return en && bestWeightForEntry(en) > 0
})
const bestRepsOf = en => Math.max(0, ...metricRowsForEntry(en, 'reps').map(s => Number(s.r) || 0))
const metric = s => curCardio ? (s.speed || 0) : curTimed ? (s.sec || 0) : (s.w || 0)
const exUnit = curCardio ? 'km/h' : curTimed ? 's' : S.unit
const exUnit = curCardio ? 'km/h' : curTimed ? 's' : repsOnly ? t('reps') : S.unit
let exPts = [], exList = [], exBest = 0
if (curEx) {
workouts.forEach(w => {
@@ -330,7 +347,9 @@ export default function Stats() {
const loggedMode = metricModeForEntry(en)
if (loggedMode !== curMode) return
const doneSets = metricRowsForEntry(en, curMode)
const mx = curMode === 'reps' ? bestWeightForEntry(en) : Math.max(0, ...doneSets.map(metric))
const mx = curMode === 'reps'
? (repsOnly ? bestRepsOf(en) : bestWeightForEntry(en))
: Math.max(0, ...doneSets.map(metric))
if (mx > 0) {
exPts.push({ t: w.start, y: mx, d: w.d, sets: doneSets, target: en.target })
if (mx > exBest) exBest = mx
@@ -341,7 +360,15 @@ export default function Stats() {
}
// Estimated 1RM (issue #18) — only reps-mode training produces one, so cardio and timed
// work simply have no points and the toggle stays hidden.
const e1Pts = curEx && curMode === 'reps' ? e1rmSeries(S, curEx) : []
// Both memoised on the same inputs, and it has to start at e1rmSeries: LineChart clears its
// hover whenever `points` changes identity, so a chart array rebuilt on every render made the
// tooltip vanish under your finger the moment anything else on this screen re-rendered.
// Memoising only the .map() would not have helped — its dependency was itself rebuilt each time.
const e1Pts = useMemo(
() => (curEx && curMode === 'reps' ? e1rmSeries(S, curEx) : []),
[S, curEx, curMode],
)
const e1ChartPts = useMemo(() => e1Pts.map(p => ({ t: p.t, y: p.y, d: p.d })), [e1Pts])
const e1Best = curEx && curMode === 'reps' ? best1RM(S, curEx) : null
const showE1 = e1Pts.length > 0
// Effort on this exercise, per session. It rides on the top-set curve as well as having a
@@ -400,19 +427,19 @@ export default function Stats() {
<h2>{t('Exercise progress')}</h2>
{exHist.length ? <>
<div className="sect-b" style={{ marginBottom: 10 }}>
<SelectRow title={t('Exercise')} sheetTitle={t('Exercise progress')} value={curEx} onChange={setExId}
<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 : '') }))} />
</div>
{exOpts.length > 1 && <Segmented className="seg-range" value={onEff ? 'effort' : onE1 ? 'e1rm' : 'top'} onChange={setExMetric} options={exOpts} />}
<div className="chart">
{onEff
? <LineChart points={effPts} h={150} unit={hd} color="var(--yellow)" invert={kind === 'rir'} />
: <LineChart points={onE1 ? e1Pts.map(p => ({ t: p.t, y: p.y, d: p.d })) : topPts} h={150} unit={exUnit} color="var(--blue)" />}
: <LineChart points={onE1 ? e1ChartPts : topPts} h={150} unit={exUnit} color="var(--blue)" />}
</div>
<div style={{ marginTop: 8 }}>{exList.map((p, i) => <div key={i} className="row between small" style={{ padding: '6px 0', borderBottom: 'var(--hair) solid var(--sep)' }}>
<span className="muted">{fmtDate(p.d, true)}</span><span>{p.sets.map(s => setLabel(curEx, s, p.target)).join(' ')}</span></div>)}</div>
<div className="small dim" style={{ marginTop: 8 }}>
{onEff ? t('Average effort per workout') : onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : t('Best set weight per workout')}
{onEff ? t('Average effort per workout') : onE1 ? t('Estimated 1RM per workout') : curCardio ? t('Top speed per workout') : curTimed ? t('Longest hold per workout') : repsOnly ? t('Most reps in a set per workout') : t('Best set weight per workout')}
{onEff ? '' : <> · {t('Best:')}{' '}<b className="accent">{fmtNum(onE1 ? e1Best.est : exBest)} {onE1 ? S.unit : exUnit}</b></>}
</div>
{onE1 && <div className="small dim" style={{ marginTop: 4 }}>
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest'
import { readFileSync } from 'node:fs'
import { bestWeightForEntry, metricModeForEntry, metricRowsForEntry } from '../lib/history.js'
const source = readFileSync(new URL('./Stats.jsx', import.meta.url), 'utf8')
const uiSource = readFileSync(new URL('../components/ui.jsx', import.meta.url), 'utf8')
const cssSource = readFileSync(new URL('../index.css', import.meta.url), 'utf8')
describe('Stats mixed-entry metric contract', () => {
it('selects authoritative reps rows before timed rows without stale topW', () => {
const entry = { target: { mode: 'time', sec: 60 }, topW: 200, sets: [
{ phase: 'work', mode: 'reps', w: 100, r: 5, done: true },
{ phase: 'work', mode: 'time', w: 200, sec: 60, done: true }
] }
expect(metricModeForEntry(entry)).toBe('reps')
expect(metricRowsForEntry(entry, metricModeForEntry(entry))).toEqual([entry.sets[0]])
expect(bestWeightForEntry(entry)).toBe(100)
})
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)}')
})
it('uses the shared metric mode and row helpers rather than entryMode as a chart gate', () => {
expect(source).toContain('metricModeForEntry')
expect(source).toContain('metricRowsForEntry')
expect(source).toContain('bestWeightForEntry')
expect(source).not.toContain('const loggedMode = entryMode(en)')
expect(source).not.toContain('(en.topW || 0)')
})
it('stacks the Stats exercise selector value without changing shared SelectRow defaults', () => {
expect(source).toContain("onChange={setExId} stackedValue")
expect(uiSource).toContain('sheetTitle, stackedValue = false')
expect(uiSource).toContain("className={stackedValue ? 'lrow-stack-value' : ''}")
expect(cssSource).toContain('.lrow.lrow-stack-value .lrow-m{grid-column:1;grid-row:1}')
expect(cssSource).toContain('.lrow.lrow-stack-value .lrow-v{grid-column:1;grid-row:2;text-align:left}')
expect(cssSource).toContain('overflow:hidden;text-overflow:ellipsis;white-space:nowrap')
})
})
+118 -18
View File
@@ -3,19 +3,19 @@ import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { exOr } from '../lib/exercises.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg } from '../lib/history.js'
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js'
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t } from '../lib/i18n.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import { setProgressHighWater, supersetFlowStep } from '../lib/supersetFlow.js'
import { setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet } from '../sheets.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button, Check, NumberField } from '../components/ui.jsx'
import { nextPrescription, applyPrescription } from '../lib/progression.js'
import { nextPrescription, applyPrescription, defaultIncrement } from '../lib/progression.js'
import { glyphOf } from '../lib/glyphs.js'
import { isWarmupRow } from '../lib/workout-model.js'
import { isWarmupRow, isDropSet, isRestPauseSet, dropsOf, clustersOf, addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt, nextDropWeight, nextBurstReps } from '../lib/workout-model.js'
/* ---------- start chooser (no active workout) ---------- */
function StartChooser() {
@@ -58,13 +58,48 @@ 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 }) {
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const working = useUI(s => s.work)
const entry = S.active.entries[entryIdx]
// Drops/bursts mutate the row in place — same card, not a new set with its own long rest.
// A planned exercise (see the exercise's "Intensifier" config) arrives with these already
// filled in by applyIntensifierPlan; these only add/edit/remove entries live from here on.
const mutSet = (i, fn) => update(s => { const row = s.active.entries[entryIdx].sets[i]; s.active.entries[entryIdx].sets[i] = fn(row) }, true)
const addDropRow = i => mutSet(i, row => {
const drops = dropsOf(row)
const base = drops.length ? drops[drops.length - 1].w : (row.w || 0)
const pct = entry.target?.intensifier?.type === 'dropset' ? entry.target.intensifier.pct : undefined
return addDrop(row, { w: nextDropWeight(base, pct), r: row.r })
})
// A rest-pause row's own reps are always the total across every burst (see
// applyIntensifierPlan/history.js) — clusters are the breakdown of that total, not extra on
// top of it — so adding, removing or editing one keeps `r` in step by the same delta.
const addBurstRow = i => mutSet(i, row => {
const clusters = clustersOf(row)
const base = clusters.length ? clusters[clusters.length - 1].r : (row.r || 0)
const restSec = entry.target?.intensifier?.type === 'restpause' ? entry.target.intensifier.restSec : (S.restPauseSec || 15)
const added = nextBurstReps(base)
return { ...addCluster(row, { r: added, restSec }), r: (row.r || 0) + added }
})
const removeDrop = (i, di) => mutSet(i, row => removeDropAt(row, di))
const removeCluster = (i, ci) => mutSet(i, row => {
const removed = clustersOf(row)[ci]?.r || 0
return { ...removeClusterAt(row, ci), r: Math.max(0, (row.r || 0) - removed) }
})
const setDropField = (i, di, field, v) => mutSet(i, row => setDropAt(row, di, { [field]: v }))
const setClusterField = (i, ci, v) => mutSet(i, row => {
const delta = (Number(v) || 0) - (clustersOf(row)[ci]?.r || 0)
return { ...setClusterAt(row, ci, { r: v }), r: Math.max(0, (row.r || 0) + delta) }
})
const ex = exOr(entry.id)
const mode = modeOf({ ...(entry.target || {}), id: entry.id })
const cardio = mode === 'cardio'
const timed = mode === 'time'
const last = lastEntryFor(S, entry.id)
const standingNote = exNoteFor(S, entry.id)
// Only worth surfacing while there is still work left: once the exercise is finished, a note
// telling you what to do in it is behind you, and the block is already long.
const pinnedNote = entry.sets.some(s => !s.done) ? pinnedNoteFor(S, entry.id) : null
// The same number the "confirm your working weight" sheet calls your best, so the two
// never disagree inside one session: heaviest logged set, or the working weight you kept.
const best = cardio ? 0 : Math.max(bestWeightFor(S, entry.id), (S.exWeights[entry.id] || {}).w || 0)
@@ -110,11 +145,25 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
<button aria-label="Increase" onClick={() => bump(s, i, col, 1)}><Icon name="plus" /></button>
</div>
)
// A smaller stepper for a drop's weight/reps or a burst's reps — editing what the plan (or a
// live "+ Drop"/"+ Burst" tap) already put on the row, not typing into a fresh field.
const miniStepper = (value, step, dec, onChange) => (
<div className="stp mini">
<button aria-label="Decrease" onClick={() => onChange(Math.max(0, Math.round(((value || 0) - step) * 100) / 100))}><Icon name="minus" /></button>
<span className="val"><NumberField decimal={dec} value={value ?? ''} onChange={onChange} /></span>
<button aria-label="Increase" onClick={() => onChange(Math.max(0, Math.round(((value || 0) + step) * 100) / 100))}><Icon name="plus" /></button>
</div>
)
return <>
<Media ex={ex} key={entry.id} compact={compact} minimizable />
<div className="row between" style={{ marginBottom: 6 }}>
<div style={{ fontSize: compact ? 17 : 20, fontWeight: 600, letterSpacing: '-.02em', textTransform: 'capitalize', lineHeight: 1.2 }}>{ex.n}</div>
<button className="iconbtn" aria-label={t('Details')} onClick={() => exerciseDetailSheet(ex)}><Icon name="info" /></button>
<div style={{ fontSize: compact ? 17 : 20, fontWeight: 600, letterSpacing: '-.02em', textTransform: 'capitalize', lineHeight: 1.2 }}>{exerciseNameFor(ex)}</div>
<div className="row" style={{ gap: 2, flex: 'none' }}>
<button className="iconbtn" aria-label={t('Note')} title={t('Note')}
style={entry.note ? { color: 'var(--acc)' } : undefined}
onClick={() => exerciseNoteSheet(entryIdx)}><Icon name="pencil" /></button>
<button className="iconbtn" aria-label={t('Details')} onClick={() => exerciseDetailSheet(ex)}><Icon name="info" /></button>
</div>
</div>
{!compact && (onPairPrev || onPairNext) && <div className="row" style={{ gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
{onPairPrev && <Button size="xs" variant="tinted" icon="link" title={t('Make superset with previous')} onClick={onPairPrev}>{t('Make superset with previous')}</Button>}
@@ -129,6 +178,17 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
{ex.eq && <span className="tag">{t(ex.eq)}</span>}
{best > 0 && <span className="tag nocap">{t('Best:')} {fmtNum(best)} {S.unit}</span>}
</div>
{/* Three notes can apply to one exercise and they are not interchangeable, so each keeps its
own line and its own icon: the plan's instruction (cfg.note, from the routine), the
standing fact about the movement (exNotes), and the message you pinned to yourself last
session. Today's own note is edited through the button in the header and shown last. */}
{cfg.note && <div className="exnote">{cfg.note}</div>}
{standingNote && <div className="exnote"><Icon name="info" style={{ fontSize: 13, marginRight: 5, verticalAlign: '-2px' }} />{standingNote}</div>}
{pinnedNote && <div className="exnote" style={{ color: 'var(--yellow)' }}>
<Icon name="flag" style={{ fontSize: 13, marginRight: 5, verticalAlign: '-2px' }} />
{t('From {0}:', fmtDate(pinnedNote.d, true))} {pinnedNote.note}
</div>}
{entry.note && <div className="exnote">{entry.note}</div>}
{last && <div className="small dim" style={{ marginBottom: 4 }}>{t('Last time')} ({fmtDate(last.d)}): {last.sets.map(s => setLabel(entry.id, s, last.target)).join(', ')}</div>}
{plan && plan.why && plan.kind !== 'off' && <div className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}>
<Icon name={plan.kind === 'up' ? 'arrowUp' : plan.kind === 'deload' ? 'arrowDown' : 'lightbulb'} />
@@ -159,6 +219,31 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
disabled={entry.sets.length <= 1} onClick={() => onRemoveSetAt(i)}><Icon name="xmark" /></button>}
<Check checked={s.done} onChange={() => onToggle(i)} />
</div>
{/* Drop-sets and rest-pause bursts extend this same row — no long rest, no new set.
A planned exercise arrives with these already filled in (applyIntensifierPlan);
every value here is just as editable as the main row's own weight/reps. */}
{!warm && mode === 'reps' && <>
{dropsOf(s).map((d, di) => (
<div className="subrow" key={'d' + di}>
<span className="subn">{t('Drop {0}', di + 1)}</span>
{miniStepper(d.w, 2.5, true, v => setDropField(i, di, 'w', v))}
{miniStepper(d.r, 1, false, v => setDropField(i, di, 'r', v))}
<button className="iconbtn" aria-label={t('Remove drop')} onClick={() => removeDrop(i, di)}><Icon name="xmark" /></button>
</div>
))}
{clustersOf(s).map((c, ci) => (
<div className="subrow" key={'c' + ci}>
<span className="subn">{t('Burst {0}', ci + 1)}</span>
{miniStepper(c.r, 1, false, v => setClusterField(i, ci, v))}
<span className="dim small">{c.restSec}s</span>
<button className="iconbtn" aria-label={t('Remove burst')} onClick={() => removeCluster(i, ci)}><Icon name="xmark" /></button>
</div>
))}
<div className="setextra">
{!isRestPauseSet(s) && <button className="chip add" onClick={() => addDropRow(i)}><Icon name="arrowDown" />{t('+ Drop')}</button>}
{!isDropSet(s) && <button className="chip add" onClick={() => addBurstRow(i)}><Icon name="bolt" />{t('+ Burst')}</button>}
</div>
</>}
</div>
})}
<div style={{ height: 8 }} />
@@ -238,7 +323,7 @@ function ActiveWorkout() {
const removeSet = idx => mutEntry(idx, e => { if (e.sets.length > 1) e.sets.pop() })
const addWarmup = idx => mutEntry(idx, e => {
const m = modeOf({ ...(e.target || {}), id: e.id })
e.sets = insertWarmupRow(e.sets, m, e.target || {})
e.sets = insertWarmupRow(e.sets, m, e.target || {}, defaultIncrement(e.id, S.unit))
})
const removeSetAt = (idx, i) => mutEntry(idx, e => { e.sets = removeRowAt(e.sets, i) })
const pairAt = (first, second) => update(s => {
@@ -258,7 +343,7 @@ function ActiveWorkout() {
if (!e) return
const hasDone = (e.sets || []).some(s => s.done)
confirmSheet({
title: t('Remove {0}?', exOr(e.id).n),
title: t('Remove {0}?', exerciseNameFor(exOr(e.id))),
message: hasDone
? t('The sets you logged for this exercise in this session will be lost.')
: t('This removes the exercise from your current session.'),
@@ -273,7 +358,7 @@ function ActiveWorkout() {
<div className="muted small" style={{ marginBottom: 12 }}>{t('Which exercise in this superset do you want to remove?')}</div>
<div className="list">
{unit.map(idx => <div key={idx} className="item" onClick={() => { close(); confirmRemoveExercise(idx) }}>
<div className="grow"><div className="tt">{exOr(A.entries[idx]?.id).n}</div></div>
<div className="grow"><div className="tt">{exerciseNameFor(exOr(A.entries[idx]?.id))}</div></div>
<Icon name="chevronRight" />
</div>)}
</div>
@@ -288,7 +373,7 @@ function ActiveWorkout() {
// behave exactly as they do for a reps set.
const startTimed = (idx, i) => {
const e = A.entries[idx]
useUI.getState().startWork(e.sets[i].sec || 45, exOr(e.id).n, elapsed => {
useUI.getState().startWork(e.sets[i].sec || 45, exerciseNameFor(exOr(e.id)), elapsed => {
mutEntry(idx, en => { en.sets[i].sec = elapsed })
if (!useStore.getState().S.active.entries[idx].sets[i].done) toggle(idx, i)
})
@@ -326,7 +411,6 @@ function ActiveWorkout() {
if (fresh && checked && fresh.entries[idx]) {
const progress = setProgressHighWater(fresh.entries[idx], progressHighWater.current[idx] || 0)
progressHighWater.current[idx] = progress.highWater
if (!progress.isNew) return
const freshUnits = supersetUnits(fresh.entries)
const freshUnit = freshUnits.find(u => u.includes(idx))
@@ -334,11 +418,19 @@ function ActiveWorkout() {
const freshLastUnit = freshUnitIdx >= freshUnits.length - 1
const freshUnitDone = freshUnit?.every(ui => fresh.entries[ui].sets.every(x => x.done))
// Singleton units are ordinary exercises: preserve their historical between-set rest,
// while final sets finish quietly and never enter superset navigation.
// 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)
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.
if (freshUnitDone) stopRest()
if (!freshUnit || freshUnit.length <= 1) {
if (!freshUnitDone) startRest(S.restSec)
if (restAfterSet({ unitDone: freshUnitDone, lastUnit: freshLastUnit })) startRest(S.restSec)
return
}
@@ -427,8 +519,9 @@ function ActiveWorkout() {
exConfigSheet(ex, null, cfg => update(s => {
const full = { ...cfg, id: ex.id }
const plan = freestyle ? null : nextPrescription(s, full, s.routines.find(r => r.id === s.active.routineId))
const sets = buildSets(s, full, freestyle ? { preferLast: true } : undefined)
s.active.entries.push({ id: ex.id, target: { ...cfg }, plan, sets: freestyle ? sets : applyPrescription(sets, plan) })
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
}), null, routine, seed)
})} icon="plus">{t('Add exercise')}</Button>
@@ -439,6 +532,13 @@ function ActiveWorkout() {
</div>
</>}
<div style={{ height: 10 }} />
{/* Wrapping up is when you know how the session went, so the note sits with the finish
button rather than somewhere in the header. */}
<div style={{ display: 'flex', justifyContent: 'center', marginBottom: 10 }}>
<Button size="sm" icon="pencil" variant={A.note ? 'tinted' : undefined} onClick={sessionNoteSheet}>
{A.note ? t('Edit session note') : t('Add session note')}
</Button>
</div>
{(() => {
const exDone = A.entries.filter(e => e.sets.length && e.sets.every(s => s.done)).length
const allDone = A.entries.length > 0 && exDone === A.entries.length
+2 -2
View File
@@ -110,8 +110,8 @@ describe('remove-exercise locale coverage', () => {
]
const packs = import.meta.glob('../locales/*.js', { eager: true, import: 'default' })
it('defines every new prompt in all eleven locale packs', () => {
expect(Object.keys(packs)).toHaveLength(11)
it('defines every new prompt in all twelve locale packs', () => {
expect(Object.keys(packs)).toHaveLength(12)
Object.entries(packs).forEach(([path, pack]) => {
required.forEach(key => expect(pack, `${path} is missing ${key}`).toHaveProperty(key))
})
+4
View File
@@ -46,6 +46,10 @@ vi.mock('../sheets.jsx', () => ({
finishWorkout: vi.fn(),
workoutCompleteSheet: vi.fn(),
confirmSheet: vi.fn(),
// 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(),
sessionNoteSheet: vi.fn(),
}))
vi.mock('../components/Media.jsx', () => ({ default: () => null }))
// api.js reads navigator.userAgent at module scope. This file installs its own DOM inside the