diff --git a/api/openapi.yaml b/api/openapi.yaml index 14ecfdf..fd2f23d 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -50,7 +50,11 @@ info: - Errors are always `{"error": ""}`. - Unknown method+path pairs return `404 {"error":"not found"}`; an unhandled exception returns `500 {"error":"server error"}`. - - Request bodies are parsed as JSON regardless of Content-Type; max 5 MiB. + - Request bodies are parsed as JSON regardless of Content-Type. A body that does + not parse, or parses to anything but an object (`null`, a string, an array), is + `400 {"error":"invalid json"}` on every route that reads one; an empty body counts + as `{}`. A body over 5 MiB is `413 {"error":"body too large"}`; the rest of the + upload is discarded so the answer reaches the client. - CORS: the request's `Origin` is reflected in `Access-Control-Allow-Origin` **without** `Allow-Credentials` — cross-origin callers can only ever authenticate with a Bearer token, never with the cookie. @@ -556,8 +560,10 @@ paths: - type: 'null' '400': description: >- - `state` missing or not an object, or `workouts`/`routines` set to anything - other than an array or null. + `state` missing or not an object, `state` an array, or `workouts`/`routines` + set to anything other than an array or null. Entries inside those two arrays + that are not objects (`null`, numbers, nested arrays) are dropped before the + write rather than refused, so a client with a damaged copy still syncs. content: application/json: schema: { $ref: '#/components/schemas/Error' } @@ -725,7 +731,8 @@ paths: operationId: pushRestTimer summary: Schedule a server-side rest-timer push description: | - Schedules one push after `seconds` (clamped to 1–3600). One pending timer per + Schedules one push after `seconds` (a number or numeric string ≥ 1, clamped to + 3600). One pending timer per device — `deviceId`, the same token the subscription was registered with; a new call from the same device replaces it, and the push goes only to that device's subscriptions. Without a `deviceId` there is one timer per account @@ -733,9 +740,6 @@ paths: on rest start/extend and cancels on skip or on-screen completion — the push only actually fires when the tab was backgrounded/suspended and never got to cancel it. Timers live in memory: an API restart drops them. - - Note: the documented `400 seconds required` exists in the code but is - unreachable — the clamp turns any missing/invalid value into 1. requestBody: required: true content: @@ -759,6 +763,12 @@ paths: content: application/json: schema: { $ref: '#/components/schemas/Ok' } + '400': + description: '`seconds` missing, not numeric, or below 1. Nothing is scheduled.' + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "seconds required" } '401': { $ref: '#/components/responses/Unauthorized' } /api/push/rest-timer/cancel: diff --git a/api/server.js b/api/server.js index 5f2745c..8da9389 100644 --- a/api/server.js +++ b/api/server.js @@ -513,21 +513,53 @@ function json(res, code, obj, extraHeaders) { res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...(extraHeaders || {}) }); res.end(body); } +// A request the caller got wrong. The catch-all at the bottom answers it with this status and +// message and does not log it: three of the routes below are reachable without a session, and a +// stack trace per malformed body would let anyone fill the container log with noise that looks +// like a crash. Anything else that escapes a handler is still a real 500 and still logged. +class HttpError extends Error { + constructor(status, message) { super(message); this.status = status; } +} function readBody(req) { return new Promise((resolve, reject) => { - let size = 0; const chunks = []; + let size = 0, over = false; const chunks = []; req.on('data', d => { size += d.length; - if (size > MAX_BODY) { reject(new Error('body too large')); req.destroy(); return; } + if (over) { + // The 413 is already on its way. The rest of the upload is read and thrown away rather + // than the socket destroyed under it: closing with unread bytes on the wire makes the + // kernel send a reset, and a client (node's own http client included) that hits the + // reset before it has parsed the answer reports a dropped connection instead of the + // 413. A client that keeps streaming past twice the cap is not a mistaken one, and is + // cut off. + if (size > 2 * MAX_BODY) req.destroy(); + return; + } + if (size > MAX_BODY) { + over = true; chunks.length = 0; + reject(new HttpError(413, 'body too large')); + return; + } chunks.push(d); }); req.on('end', () => { - try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); } - catch { reject(new Error('bad json')); } + if (over) return; + if (!chunks.length) return resolve({}); + let body; + try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } + catch { return reject(new HttpError(400, 'invalid json')); } + // Every handler reads fields off the result, so a JSON `null`, string, number or array is + // as much a client mistake as unparseable text — refused once here rather than dereferenced + // (and turned into a TypeError) in each route. + if (!body || typeof body !== 'object' || Array.isArray(body)) return reject(new HttpError(400, 'invalid json')); + resolve(body); }); req.on('error', reject); }); } +// A caller-supplied field that is meant to be text. String() alone is not safe on a parsed body: +// `{"code":{"toString":1}}` is valid JSON and String() throws on it. +const text = v => (typeof v === 'string' ? v : typeof v === 'number' ? String(v) : ''); const b64uToBuf = s => Buffer.from(s, 'base64url'); /* ---------- live presence (in-memory) ---------- */ @@ -658,9 +690,9 @@ const routes = { 'POST /api/register/options': async (req, res) => { const body = await readBody(req); - const name = String(body.name || '').trim().slice(0, 40); + const name = text(body.name).trim().slice(0, 40); if (!name) return json(res, 400, { error: 'name required' }); - const code = String(body.code || '').trim().toUpperCase(); + const code = text(body.code).trim().toUpperCase(); if (INVITE_ONLY && !db.invites.some(i => i.code === code && !i.usedBy && !i.revoked)) { // The rejected code itself is never recorded — a near-miss guess in the log is a liability. audit(req, 'auth.register.denied', { ok: false, name, msg: 'invite-rejected' }); @@ -830,7 +862,7 @@ const routes = { // the code IS the credential, one-shot and 5-minute-lived like a WebAuthn challenge. 'POST /api/pair/redeem': async (req, res) => { const body = await readBody(req); - const code = String(body.code || '').trim().toUpperCase(); + const code = text(body.code).trim().toUpperCase(); const p = pairings.get(code); if (p) pairings.delete(code); if (!p || p.exp < Date.now()) { @@ -871,9 +903,17 @@ const routes = { if (!body.state || typeof body.state !== 'object') return json(res, 400, { error: 'state required' }); // The reminder tick and the admin routes iterate these two on the server's side, so a truthy // non-array would throw there on every pass for as long as it sat on disk. Absent or null is - // fine — every client fills its own defaults. + // fine — every client fills its own defaults. An array is `typeof 'object'` but no document: + // `_rev` set on it is dropped by JSON.stringify, so the file would read back as rev 0 while + // the response claimed the next revision. const list = v => v == null || Array.isArray(v); - if (!list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' }); + if (Array.isArray(body.state) || !list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' }); + // The same readers dereference every entry (`w.d`, `w.name`), so a null or non-object entry + // would throw there — and blank the admin's drill-down of this profile. Dropped, not refused: + // such an entry carries nothing worth keeping, whereas a 400 would strand a client whose own + // copy is already malformed — it keeps re-sending the same document and never syncs again. + const record = x => x && typeof x === 'object' && !Array.isArray(x); + for (const k of ['workouts', 'routines']) if (Array.isArray(body.state[k])) body.state[k] = body.state[k].filter(record); // Conditional write: a `baseRev` that is not the current revision means this client last // read an older document — another device has written since — and the copy it is about to // push would silently drop that write. The current document travels back with the 409, so @@ -954,8 +994,13 @@ const routes = { const user = readSession(req); if (!user) return json(res, 401, { error: 'not signed in' }); const body = await readBody(req); - const sec = Math.max(1, Math.min(3600, Math.round(+body.seconds || 0))); - if (!sec) return json(res, 400, { error: 'seconds required' }); + // Validated before it is clamped: the clamp used to run first, which turned a missing or + // unusable value into a 1-second push and made the 400 below unreachable. `Number()` only + // on a number or a string — on an object it can throw. + const raw = body.seconds; + const n = typeof raw === 'number' || typeof raw === 'string' ? Number(raw) : NaN; + if (!(n >= 1)) return json(res, 400, { error: 'seconds required' }); + const sec = Math.min(3600, Math.round(n)); scheduleRestTimer(user.id, deviceIdOf(body.deviceId), sec, readState(user.id)?.lang); json(res, 200, { ok: true }); }, @@ -975,7 +1020,7 @@ const routes = { const body = await readBody(req); if (body.active) { presence.set(user.id, { - name: String(body.name || '').slice(0, 60), + name: text(body.name).slice(0, 60), exIdx: +body.exIdx || 0, exTotal: +body.exTotal || 0, setsDone: +body.setsDone || 0, setsTotal: +body.setsTotal || 0, startedAt: +body.startedAt || Date.now(), @@ -1054,7 +1099,7 @@ const routes = { // good, so the code itself has to be the thing that isn't worth guessing. Codes already in // db.json keep working — validation is an exact string compare, never a length or format check. do { code = crypto.randomBytes(8).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code)); - const invite = { code, note: String(body.note || '').slice(0, 60), createdBy: admin.id, created: new Date().toISOString() }; + const invite = { code, note: text(body.note).slice(0, 60), createdBy: admin.id, created: new Date().toISOString() }; db.invites.push(invite); saveDb(); audit(req, 'admin.invite.create', { user: admin, msg: code }); @@ -1064,7 +1109,7 @@ const routes = { 'POST /api/admin/invites/revoke': async (req, res) => { const admin = requireAdmin(req, res); if (!admin) return; const body = await readBody(req); - const inv = db.invites.find(i => i.code === String(body.code || '').toUpperCase()); + const inv = db.invites.find(i => i.code === text(body.code).toUpperCase()); if (!inv) return json(res, 404, { error: 'no such code' }); if (inv.usedBy) return json(res, 400, { error: 'already used — cannot revoke' }); db.invites = db.invites.filter(i => i.code !== inv.code); @@ -1166,6 +1211,10 @@ http.createServer(async (req, res) => { } try { await handler(req, res); } catch (e) { + if (e instanceof HttpError) { + if (!res.headersSent) json(res, e.status, { error: e.message }); + return; + } console.error(key, e); if (!res.headersSent) json(res, 500, { error: 'server error' }); } diff --git a/api/test/server-bad-input.test.js b/api/test/server-bad-input.test.js new file mode 100644 index 0000000..a734fe2 --- /dev/null +++ b/api/test/server-bad-input.test.js @@ -0,0 +1,183 @@ +/* A client's mistake is a 400 (or a 413), never a 500 with a stack trace in the log: unparseable + or non-object JSON bodies, a state document that is an array, null entries inside it, and a + rest-timer request without a usable `seconds` (QA C17, C19, C20). Real server.js in a child. */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import net from 'node:net'; +import http from 'node:http'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..'); +const SECRET = crypto.randomBytes(32).toString('hex'); + +// Same construction as server.js makeSession(): payload `uid:exp:sv`, HMAC-SHA256 over SECRET. +function mintSession(uid, sv = 0) { + const payload = `${uid}:${Date.now() + 86400000}:${sv}`; + return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url'); +} +const UID = 'u_bad_1'; +const authed = { Cookie: `gymsid=${mintSession(UID)}`, 'Content-Type': 'application/json' }; +const anon = { 'Content-Type': 'application/json' }; + +const freePort = () => new Promise(r => { + const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); }); +}); + +async function startServer(t) { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-bad-')); + fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 }); + fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ + users: [{ id: UID, name: 'One', created: new Date().toISOString() }], creds: [], subs: [], invites: [] + })); + const port = await freePort(); + const child = spawn(process.execPath, ['server.js'], { + cwd: API, stdio: ['ignore', 'pipe', 'pipe'], + env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' } + }); + const h = { api: `http://127.0.0.1:${port}`, log: '', dataDir }; + child.stdout.on('data', d => h.log += d); + child.stderr.on('data', d => h.log += d); + t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); }); + let up = false; + for (let i = 0; i < 100 && !up; i++) { + try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ } + if (!up) await new Promise(r => setTimeout(r, 100)); + } + assert.ok(up, `server never came up:\n${h.log}`); + // The boot line is fine; anything that looks like a stack frame after this is a defect. + h.stackFrames = () => h.log.split('\n').filter(l => /^\s+at /.test(l)).length; + return h; +} + +const send = (h, method, p, headers, body) => fetch(`${h.api}${p}`, { method, headers, body }); +const status = async (h, method, p, headers, body) => { + const r = await send(h, method, p, headers, body); + return { status: r.status, body: await r.json() }; +}; + +test('malformed and non-object JSON bodies are a 400 with no stack trace, on every route', async t => { + const h = await startServer(t); + const bad = ['not json', '{bad', 'null', '"str"', '42', '[]']; + const routes = [ + ['POST', '/api/register/options', anon], + ['POST', '/api/register/verify', anon], + ['POST', '/api/pair/redeem', anon], + ['PUT', '/api/data', authed], + ['POST', '/api/push/rest-timer', authed] + ]; + for (const [method, p, headers] of routes) { + for (const b of bad) { + const r = await status(h, method, p, headers, b); + assert.equal(r.status, 400, `${method} ${p} with body ${b}`); + assert.equal(r.body.error, 'invalid json', `${method} ${p} with body ${b}`); + } + } + // A field whose toString is not callable is valid JSON; String() on it used to throw. + let r = await status(h, 'POST', '/api/register/options', anon, JSON.stringify({ name: 'x', code: { toString: 1 } })); + assert.notEqual(r.status, 500); + r = await status(h, 'POST', '/api/pair/redeem', anon, JSON.stringify({ code: { toString: 1 } })); + assert.equal(r.status, 400); + r = await status(h, 'POST', '/api/register/options', anon, JSON.stringify({ name: { toString: 1 } })); + assert.equal(r.status, 400); + assert.equal(r.body.error, 'name required'); + // An empty body is still "no fields", as the routes that send none rely on. + r = await status(h, 'POST', '/api/logout', { Cookie: authed.Cookie }); + assert.equal(r.status, 200); + // Well-formed controls keep their own answers. + r = await status(h, 'POST', '/api/register/options', anon, '{}'); + assert.deepEqual(r, { status: 400, body: { error: 'name required' } }); + r = await status(h, 'PUT', '/api/data', authed, JSON.stringify({ state: { workouts: [], routines: [] }, baseRev: 0 })); + assert.equal(r.status, 200); + assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`); + assert.doesNotMatch(h.log, /bad json|TypeError/); +}); + +// node's own http client, writing the whole body in one go on a keep-alive socket: the client +// the QA proxy (and any node-side caller) is, and the one that used to report a reset instead +// of the 413 when the server closed the socket under the still-running upload. +const rawPut = (h, agent, body) => new Promise((resolve, reject) => { + const rq = http.request(`${h.api}/api/data`, { method: 'PUT', headers: authed, agent }, res => { + let data = ''; res.on('data', d => data += d); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); + }); + rq.on('error', reject); + rq.end(body); +}); + +test('a body over the 5 MiB cap is a 413 that every client gets to read, and nothing is written', async t => { + const h = await startServer(t); + const big = JSON.stringify({ state: { workouts: [], routines: [], pad: 'x'.repeat(6 * 1024 * 1024) }, baseRev: 0 }); + let r = await status(h, 'PUT', '/api/data', authed, big); + assert.equal(r.status, 413); + assert.equal(r.body.error, 'body too large'); + assert.equal(fs.existsSync(path.join(h.dataDir, `state-${UID}.json`)), false, 'nothing was written'); + const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); + t.after(() => agent.destroy()); + for (let i = 0; i < 3; i++) { + r = await rawPut(h, agent, big); + assert.equal(r.status, 413, `node client, attempt ${i + 1}`); + } + // The same keep-alive socket, and the server as a whole, are still fine afterwards. + r = await rawPut(h, agent, JSON.stringify({ state: { workouts: [], routines: [] }, baseRev: 0 })); + assert.equal(r.status, 200); + // Past twice the cap the upload is cut off rather than drained: the 413 may or may not + // arrive, but the process must not be left reading, and must still serve. + const huge = 'x'.repeat(11 * 1024 * 1024); + await rawPut(h, new http.Agent(), huge).catch(() => {}); + r = await status(h, 'GET', '/api/health', {}); + assert.equal(r.status, 200); + assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`); +}); + +test('PUT /api/data: an array is not a document, and null entries never reach the disk', async t => { + const h = await startServer(t); + const put = body => status(h, 'PUT', '/api/data', authed, JSON.stringify(body)); + const onDisk = () => JSON.parse(fs.readFileSync(path.join(h.dataDir, `state-${UID}.json`), 'utf8')); + + let r = await put({ state: { _ts: 100, workouts: [{ id: 'w1', d: '2026-09-01' }], routines: [], unit: 'kg' }, baseRev: 0 }); + assert.equal(r.status, 200); + assert.equal(r.body.rev, 1); + + // An array passes `typeof === 'object'`; it used to be written as `[]`, losing the document + // and, since `_rev` cannot live on an array, resetting the revision to 0 while the response + // claimed rev 2. + r = await put({ state: [], baseRev: 1 }); + assert.equal(r.status, 400); + assert.equal(r.body.error, 'invalid state'); + assert.equal(onDisk()._rev, 1); + assert.deepEqual(onDisk().workouts.map(w => w.id), ['w1']); + r = await status(h, 'GET', '/api/data/rev', authed); + assert.deepEqual(r.body, { rev: 1 }); + + // Null and other non-object entries are dropped: every server-side reader of the document + // (reminder tick, admin drill-down) dereferences the entries, and a 400 would strand a client + // whose own copy is already malformed. + r = await put({ state: { workouts: [null, { id: 'w2', d: '2026-09-02' }, 7, 'x', [], { id: 'w3', d: '2026-09-03' }], routines: [null, { id: 'r1', name: 'A', ex: [] }] }, baseRev: 1 }); + assert.equal(r.status, 200); + assert.equal(r.body.rev, 2); + assert.deepEqual(onDisk().workouts.map(w => w.id), ['w2', 'w3']); + assert.deepEqual(onDisk().routines.map(x => x.id), ['r1']); + // Absent lists stay absent — every client fills its own defaults. + r = await put({ state: { unit: 'kg' }, baseRev: 2 }); + assert.equal(r.status, 200); + assert.equal('workouts' in onDisk(), false); + assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`); +}); + +test('POST /api/push/rest-timer: a missing or invalid `seconds` is a 400, never a 1-second timer', async t => { + const h = await startServer(t); + const post = b => status(h, 'POST', '/api/push/rest-timer', authed, b); + for (const b of ['{}', '{"seconds":"abc"}', '{"seconds":0}', '{"seconds":-5}', '{"seconds":null}', '{"seconds":0.4}', '{"seconds":{"valueOf":1}}', '{"seconds":[90]}']) { + const r = await post(b); + assert.deepEqual(r, { status: 400, body: { error: 'seconds required' } }, `body ${b}`); + } + for (const b of ['{"seconds":90}', '{"seconds":"90"}', '{"seconds":1}', '{"seconds":99999}']) { + const r = await post(b); + assert.deepEqual(r, { status: 200, body: { ok: true } }, `body ${b}`); + } + assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`); +}); diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 6d21984..28ff0eb 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -85,7 +85,7 @@ function Shell() { // Forward navigation starts at the top; going back lands where you left off. // The position is recorded from scroll events rather than read at route // change, because by then a shorter page may already have clamped it. - const pathRef = useRef(loc.pathname) + const pathRef = useRef(null) // iOS leaves the page displaced after the keyboard goes away (see lib/viewport-guard.js). useEffect(() => installViewportGuard(), []) // Click-drag a horizontal chip strip to scroll it sideways (lib/hchips.js) — on a desktop @@ -108,8 +108,16 @@ function Shell() { return () => window.removeEventListener('scroll', onScroll) }, []) useLayoutEffect(() => { + const samePath = pathRef.current === loc.pathname pathRef.current = loc.pathname if (navType !== 'POP') { window.scrollTo(0, 0); return } + // A POP that stays on the route we are on is not a back-navigation: it is the history + // entry a sheet pushed (Modals.jsx, #63) being unwound as the sheet closes. Nothing new + // mounted, Modals puts the page back where it was itself, and a view that scrolled on + // purpose because the sheet closed — the workout list going to the current exercise after + // ⋯ → Layout → List (#224) — must not be dragged back to a position recorded before that + // scroll's event had even been dispatched. + if (samePath) return const y = scrollPositions.get(loc.pathname) || 0 // the restored view needs a layout pass before it is tall enough to scroll to y const frame = window.requestAnimationFrame(() => window.scrollTo(0, y)) diff --git a/frontend/src/components/Modals.jsx b/frontend/src/components/Modals.jsx index 397ccc4..39156cd 100644 --- a/frontend/src/components/Modals.jsx +++ b/frontend/src/components/Modals.jsx @@ -1,5 +1,6 @@ import { useEffect, useRef } from 'react' import { useUI } from '../store/useUI.js' +import { keyboardOpen } from '../lib/viewport-guard.js' // One bottom sheet (or centered dialog) with swipe-to-dismiss. function Sheet({ sheet }) { @@ -180,6 +181,12 @@ export default function Modals() { // iOS scrolls the page again while the keyboard dismisses — after the line above ran. // Ask once more when that animation is over. The window-level guard in // lib/viewport-guard.js covers the keyboard closing while a sheet stays open. + // Only with the keyboard up, though: without one there is nothing to undo, and a late + // restore would overwrite a scroll the page behind made on purpose because the sheet + // closed — the workout list going to the current exercise after ⋯ → Layout → List + // (issue #224). At this point the sheet's field is already out of the DOM but the + // keyboard has not started to go, so the visual viewport still tells the truth. + if (!keyboardOpen()) return window.setTimeout(() => { if (document.body.style.position !== 'fixed') window.scrollTo(0, y) }, 350) } }, [sheets.length > 0]) diff --git a/frontend/src/components/Modals.test.jsx b/frontend/src/components/Modals.test.jsx index 09038a7..3bdb4f6 100644 --- a/frontend/src/components/Modals.test.jsx +++ b/frontend/src/components/Modals.test.jsx @@ -292,3 +292,38 @@ describe('Modals drag axis lock and dismiss', () => { expect(mocks.state.sheets).toHaveLength(1) }) }) + +describe('Modals scroll restore on close', () => { + // The body is pinned while a sheet is open and the page is put back where it was on close. + // The second, delayed restore exists for one reason — iOS scrolling the page again while the + // keyboard dismisses — so it must only be armed when the keyboard is actually up (QA C1). + async function openAndClose() { + dom.scrollY = 320 + await setSheets([sheet('menu')]) + expect(document.body.style.position).toBe('fixed') + dom.scrollTo.mockClear() + await setSheets([]) + } + + it('restores the position once and leaves a scroll the page made afterwards alone', async () => { + vi.useFakeTimers() + await openAndClose() + expect(dom.scrollTo).toHaveBeenCalledTimes(1) + expect(dom.scrollTo).toHaveBeenCalledWith(0, 320) + await act(async () => { vi.advanceTimersByTime(400) }) + expect(dom.scrollTo).toHaveBeenCalledTimes(1) + vi.useRealTimers() + }) + + it('restores again after the keyboard dismiss animation when the sheet closed with the keyboard up', async () => { + vi.useFakeTimers() + dom.innerHeight = 800 + dom.visualViewport = { height: 460 } + await openAndClose() + expect(dom.scrollTo).toHaveBeenCalledTimes(1) + await act(async () => { vi.advanceTimersByTime(400) }) + expect(dom.scrollTo).toHaveBeenCalledTimes(2) + expect(dom.scrollTo).toHaveBeenLastCalledWith(0, 320) + vi.useRealTimers() + }) +}) diff --git a/frontend/src/components/MuscleExplorer.jsx b/frontend/src/components/MuscleExplorer.jsx index f628d95..43b6531 100644 --- a/frontend/src/components/MuscleExplorer.jsx +++ b/frontend/src/components/MuscleExplorer.jsx @@ -1,6 +1,6 @@ import { useMemo, useState } from 'react' import { useStore } from '../store/useStore.js' -import { BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js' +import { BODYPARTS, allExercises, equipmentOf, searchExercises } from '../lib/exercises.js' import { activeProfile, exAvailable } from '../lib/equipment.js' import { bestWeightFor } from '../lib/history.js' import { fmtNum } from '../lib/format.js' @@ -35,7 +35,7 @@ export default function MuscleExplorer({ onPick, onDetail, onPlan }) { ])), [catalog]) const pick = muscle => { setSelected(muscle === selected ? null : muscle); setEq(''); setShown(40) } const targeted = selected ? catalog.filter(e => musclesOf(e)[selected]) : [] - const base = targeted.filter(e => (!bp || e.bp === bp) && matchExercise(e, q)) + const base = searchExercises(targeted.filter(e => !bp || e.bp === bp), q) const eqOpts = equipmentOf(base) const eqOn = eqOpts.includes(eq) ? eq : '' // Favourites float to the top of whatever the filters left (issue #6), the rest keeps its order. diff --git a/frontend/src/index.css b/frontend/src/index.css index 9fbcc37..10936fd 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -1165,8 +1165,10 @@ body.chips-dragging *{cursor:inherit} border-radius:var(--r-lg);padding:14px 14px 4px; background:var(--surface-2); } -/* scrolled to when the list opens (#224): clear the sticky header above it */ -.wl-unit{scroll-margin-top:calc(var(--sat) + 96px)} +/* scrolled to when the list opens (#224): clear the sticky header above it. Workout.jsx + measures the header (--whdr-h on .workout-list, safe area included) because it grows when + the session name wraps; the fallback is the height of a one-line header. */ +.wl-unit{scroll-margin-top:calc(var(--whdr-h, var(--sat) + 80px) + 16px)} .wl-unit.cur{box-shadow:inset 0 0 0 1.5px var(--acc-line)} .wl-hd{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:10px} @media (max-width:400px){ diff --git a/frontend/src/lib/audit.js b/frontend/src/lib/audit.js index 6acdbfb..d3d65ac 100644 --- a/frontend/src/lib/audit.js +++ b/frontend/src/lib/audit.js @@ -21,6 +21,11 @@ const LABELS = { 'auth.register.denied': 'Signup refused', 'auth.logout': 'Signed out', 'auth.logout.all': 'Signed out everywhere', + // Device pairing (Settings → "Pair the mobile app"): the code is minted in a signed-in browser + // tab and redeemed by the app, so "ok" is the phone coming online, not a sign-in. + 'auth.pair.create': 'Created a pairing code', + 'auth.pair.ok': 'Paired a phone', + 'auth.pair.fail': 'Pairing failed', 'admin.user.disable': 'Disabled an account', 'admin.user.enable': 'Re-enabled an account', 'admin.invite.create': 'Created an invite code', @@ -41,7 +46,9 @@ const REASONS = { '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' + 'invite-rejected': 'wrong or already-used invite code', + 'code-invalid': 'wrong or expired pairing code', + 'user-unavailable': 'the profile behind the pairing code is disabled or gone' } export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '') diff --git a/frontend/src/lib/audit.test.js b/frontend/src/lib/audit.test.js index c39c1e9..f8b95cc 100644 --- a/frontend/src/lib/audit.test.js +++ b/frontend/src/lib/audit.test.js @@ -1,19 +1,15 @@ import { describe, it, expect } from 'vitest' +import { readFileSync } from 'node:fs' 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). +// Every event name and reason code the server can emit, read off api/server.js itself rather +// than kept as a second list here: the hand-kept copy silently missed the three pairing events +// for several releases, and the dashboard printed 'auth.pair.create' at the operator (QA C18). // 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' -] +const SERVER = readFileSync(new URL('../../../api/server.js', import.meta.url), 'utf8') +const EVENTS = [...new Set([...SERVER.matchAll(/audit\(req, '([a-z.]+)'/g)].map(m => m[1]))] +const REASONS = [...new Set([...SERVER.matchAll(/msg: '([a-z-]+)'/g)].map(m => m[1]))] describe('auditLabel', () => { it('has a sentence for every event the server emits', () => { @@ -58,6 +54,14 @@ describe('auditReason', () => { }) describe('auditLine', () => { + it('reads the server lists off api/server.js, pairing events included', () => { + // Guards the extraction itself: an empty match would make the two loops above vacuous. + expect(EVENTS).toEqual(expect.arrayContaining(['auth.login.ok', 'auth.pair.create', 'auth.pair.ok', 'auth.pair.fail', 'admin.audit.clear'])) + expect(REASONS).toEqual(expect.arrayContaining(['challenge-expired', 'code-invalid', 'user-unavailable'])) + expect(auditLine({ ev: 'auth.pair.fail', ok: false, msg: 'code-invalid' })).toEqual({ title: 'Pairing failed', sub: 'unknown caller · wrong or expired pairing code' }) + expect(auditLine({ ev: 'auth.pair.ok', ok: true, name: 'Verifier' })).toEqual({ title: 'Paired a phone', sub: 'Verifier' }) + }) + 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' }) diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.js index de64d69..3523d66 100644 --- a/frontend/src/lib/exercises.js +++ b/frontend/src/lib/exercises.js @@ -172,28 +172,38 @@ export const normalizeStr = s => (s || '') // 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. +// +// Each entry keeps the full corpus for substring matching and, separately, the words of the +// name (English and localized) that the typo tolerance below is allowed to compare against. const corpusCache = new WeakMap() function corpusOf(e) { const v = getVersion() const hit = corpusCache.get(e) - if (hit && hit.v === v) return hit.s + if (hit && hit.v === v) return hit const sm = Array.isArray(e?.sm) ? e.sm : [] + const name = normalizeStr(exerciseNameSearchText(e)) const s = normalizeStr([ - exerciseNameSearchText(e), + name, 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 + const entry = { v, s, nameWords: name.split(/\s+/).filter(Boolean) } + corpusCache.set(e, entry) + return entry } // Allow one missing, extra or substituted character, or an adjacent transposition, in long // query tokens. Short tokens stay exact/substring-only: words such as "row" and "curl" are too // common for fuzzy matching to be useful. +// +// Only the exercise's own name words are ever compared this way. Body part, target and +// equipment words are shared by a whole slice of the catalogue, so one accidental neighbour +// ("wrist" ~ "waist", "power" ~ "lower arms", "drucken" ~ "rucken") would list hundreds of +// unrelated exercises ahead of the real hits (QA C26). function nearWord(a, b) { if (a.length < 5 || Math.abs(a.length - b.length) > 1) return false let i = 0 @@ -206,12 +216,33 @@ function nearWord(a, b) { return a.length > b.length ? a.slice(i + 1) === b.slice(i) : a.slice(i) === b.slice(i + 1) } +const queryTokens = query => normalizeStr(query || '').split(/\s+/).filter(Boolean) + +// Every token has to appear in the corpus; a token listed in `fuzzy` may instead be one edit +// away from a name word. +const matchTokens = (e, tokens, fuzzy) => { + const { s, nameWords } = corpusOf(e) + return tokens.every(tok => s.includes(tok) || (fuzzy.has(tok) && nameWords.some(word => nearWord(tok, word)))) +} + +// Single-exercise check, used where the list is filtered one option at a time (the exercise +// progress picker). Every token may fall back to the typo tolerance; lists go through +// searchExercises below, which knows whether a token needs it at all. export function matchExercise(e, query) { - if (!query) return true - const tokens = normalizeStr(query).split(/\s+/).filter(Boolean) + const tokens = queryTokens(query) if (!tokens.length) return true if (!e || typeof e !== 'object') return false - const corpus = corpusOf(e) - const words = corpus.split(/\s+/) - return tokens.every(tok => corpus.includes(tok) || words.some(word => nearWord(tok, word))) + return matchTokens(e, tokens, new Set(tokens)) +} + +// Search a list, exact hits first: a token that appears literally in at least one exercise is +// taken at its word for the whole list, and only a token with no exact hit anywhere ("bnech", +// "dumbell", "wirst") is allowed the typo tolerance. Otherwise a correctly spelled query such +// as "squat" or "clean" would also drag in "squad" and "lean", and since the callers keep +// catalogue order those strays would land ahead of the real matches (QA C26). +export function searchExercises(list, query) { + const tokens = queryTokens(query) + if (!tokens.length) return list + const fuzzy = new Set(tokens.filter(tok => !list.some(e => corpusOf(e).s.includes(tok)))) + return list.filter(e => matchTokens(e, tokens, fuzzy)) } diff --git a/frontend/src/lib/format.js b/frontend/src/lib/format.js index 374d540..3817119 100644 --- a/frontend/src/lib/format.js +++ b/frontend/src/lib/format.js @@ -36,6 +36,7 @@ export const fmtNum = n => (Math.round(n * 10) / 10).toLocaleString(dateLocale() export const fmtVol = (v, unit) => fmtNum(v) + ' ' + unit // Plural forms are not automatic when the English string is the key. export const exCount = n => t(n === 1 ? '{0} exercise' : '{0} exercises', n) +export const routineCount = n => t(n === 1 ? '{0} routine' : '{0} routines', n) /* ---------------------------------------------------------------- week start -- Where a week begins is a local convention, not a fact: most of Europe starts on diff --git a/frontend/src/lib/import-csv.js b/frontend/src/lib/import-csv.js index f15e6df..114529e 100644 --- a/frontend/src/lib/import-csv.js +++ b/frontend/src/lib/import-csv.js @@ -286,7 +286,13 @@ const NAME_BP = [ [/\bneck\b/, 'neck'], [/\bgrip\b/, 'lower arms'], ] -export const bpFromName = name => (NAME_BP.find(([re]) => re.test(name)) || [])[1] || null +// Hyphens, underscores and slashes read as spaces first: "Stiff-Legged Deadlift" and +// "Chest-Supported Row" are the same names the rules above spell with a space, and the +// matcher (wordsOf) already treats the two spellings as one exercise — the body part has to agree. +export const bpFromName = name => { + const n = String(name || '').toLowerCase().replace(/[-_/]+/g, ' ').replace(/\s+/g, ' ').trim() + return (NAME_BP.find(([re]) => re.test(n)) || [])[1] || null +} // Categories the exporters use -> the dataset's body parts, for exercises we invent. const CATEGORY_BP = { @@ -492,7 +498,9 @@ export function parseWorkoutCSV(text, { unit = 'kg' } = {}) { id: 'iw' + uid(), d, start, end: end > start ? end : start, routineId: null, name: day.name || 'Imported', entries, prs: [], } - w.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (s.w || 0) * (s.r || 0), 0), 0) + // Work sets only, like `workoutVolume` for a workout finished in the app: warm-ups are + // promised to stay out of the volume, and this number is stored with the workout for good. + w.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (isWarmupRow(s) ? 0 : (s.w || 0) * (s.r || 0)), 0), 0) return w }) @@ -589,10 +597,23 @@ export function mergeImport(S, parsed) { return { added: fresh.length, skipped: parsed.bodyweight.length - fresh.length } } const have = new Set(S.workouts.map(w => w.d)) + // Every parse invents fresh ids for the names it cannot match, and a later export of the same + // account names those exercises again. So a custom exercise is looked up by name among the ones + // already here — from an earlier import or made by hand — and the new days are pointed at it, + // the way mergeHevyRoutines and mergePlan do; otherwise the Library lists "Grip Trainer" twice, + // each with half the history. Only a name with no match becomes a new exercise. + S.customEx = S.customEx || [] + const nameKey = n => String(n || '').toLowerCase().replace(/\s+/g, ' ').trim() + const exIdMap = {} + parsed.customEx.forEach(c => { + const same = S.customEx.find(x => x.id !== c.id && nameKey(x.n) === nameKey(c.n)) + if (same) exIdMap[c.id] = same.id + }) const fresh = parsed.workouts.filter(w => !have.has(w.d)) + .map(w => ({ ...w, entries: w.entries.map(e => (exIdMap[e.id] ? { ...e, id: exIdMap[e.id] } : e)) })) const used = new Set(fresh.flatMap(w => w.entries.map(e => e.id))) const customs = parsed.customEx.filter(c => used.has(c.id) && !EXIDX[c.id]) - S.customEx = [...(S.customEx || []), ...customs] + S.customEx = [...S.customEx, ...customs] S.workouts = [...S.workouts, ...fresh].sort((a, b) => (a.d < b.d ? -1 : 1)) // seed the weight suggestions from the newest imported set of each lift fresh.forEach(w => w.entries.forEach(e => { diff --git a/frontend/src/lib/import-csv.test.js b/frontend/src/lib/import-csv.test.js index 6f392f6..a7fd749 100644 --- a/frontend/src/lib/import-csv.test.js +++ b/frontend/src/lib/import-csv.test.js @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' -import { parseWorkoutCSV } from './import-csv.js' +import { parseWorkoutCSV, mergeImport } from './import-csv.js' +import { workoutVolume } from './history.js' const CSV = [ 'Date,Exercise,Weight,Reps,Set Type', @@ -50,3 +51,57 @@ describe('gravl export', () => { expect(cardio.entries[0].sets).toEqual([{ min: 0.4, speed: 0, done: true }]) }) }) + +// A finished workout stores `vol = workoutVolume(w)`, which leaves warm-ups out; an imported one +// wrote the sum of every set, so the History row, the heatmap and the month totals read a number +// the app's own arithmetic never produces — and it stays wrong forever (QA C14). +const HEVY_WARMUPS = [ + 'title,start_time,end_time,description,exercise_title,superset_id,exercise_notes,set_index,set_type,weight_kg,reps,distance_km,duration_seconds,rpe', + '"QA","03 Mar 2025, 18:00","03 Mar 2025, 19:00","","Bench Press (Barbell)",,"",0,warmup,20,10,,,', + '"QA","03 Mar 2025, 18:00","03 Mar 2025, 19:00","","Bench Press (Barbell)",,"",1,normal,60,5,,,', + '"QA","03 Mar 2025, 18:00","03 Mar 2025, 19:00","","Bench Press (Barbell)",,"",2,normal,60,5,,,', + '"QA","03 Mar 2025, 18:00","03 Mar 2025, 19:00","","Squat (Barbell)",,"",0,warmup,40,5,,,', + '"QA","03 Mar 2025, 18:00","03 Mar 2025, 19:00","","Squat (Barbell)",,"",1,normal,100,5,,,', +].join('\n') + +describe('imported volume', () => { + it('stores the work-set volume, the same number workoutVolume computes', () => { + const [w] = parseWorkoutCSV(HEVY_WARMUPS, { unit: 'kg' }).workouts + expect(w.vol).toBe(1100) + expect(w.vol).toBe(workoutVolume(w)) + }) +}) + +// Two exports of the same account, the second one a week later. Each parse invents fresh ids for +// the names it cannot match, so the merge has to find the custom exercise the first import created +// — otherwise the Library lists "Zorb Roller" twice with half the history each (QA C12). +const hevyDay = (title, day, name, w, r) => + `"${title}","${day} Mar 2025, 18:00","${day} Mar 2025, 19:00","","${name}",,"",0,normal,${w},${r},,,` +const HEVY_HEAD = HEVY_WARMUPS.split('\n')[0] +const EXPORT_A = [HEVY_HEAD, hevyDay('Day A', '02', 'Zorb Roller', 49, 8), hevyDay('Day A', '02', 'Bench Press (Barbell)', 80, 5)].join('\n') +const EXPORT_B = [HEVY_HEAD, hevyDay('Day A', '02', 'Zorb Roller', 49, 8), hevyDay('Day B', '09', 'Zorb Roller', 30, 15)].join('\n') + +describe('mergeImport and custom exercises', () => { + const fresh = () => ({ workouts: [], customEx: [], exWeights: {}, bodyweight: [] }) + + it('reuses the custom exercise an earlier import created for the same name', () => { + const S = fresh() + mergeImport(S, parseWorkoutCSV(EXPORT_A, { unit: 'kg' })) + const [zorb] = S.customEx + expect(zorb.n).toBe('zorb roller') + + expect(mergeImport(S, parseWorkoutCSV(EXPORT_B, { unit: 'kg' }))).toEqual({ added: 1, skipped: 1 }) + expect(S.customEx).toHaveLength(1) + // The new day points at the existing exercise, so its history is one line, not two. + expect(S.workouts.map(w => w.entries[0].id)).toEqual([zorb.id, zorb.id]) + expect(S.exWeights[zorb.id]).toEqual({ w: 30, d: '2025-03-09' }) + }) + + it('matches the name regardless of case and spacing, including one the user made by hand', () => { + const S = fresh() + S.customEx.push({ id: 'mine', n: 'Zorb Roller ', bp: 'waist', custom: true }) + mergeImport(S, parseWorkoutCSV(EXPORT_A, { unit: 'kg' })) + expect(S.customEx).toHaveLength(1) + expect(S.workouts[0].entries.map(e => e.id)).toEqual(['mine', '0025']) + }) +}) diff --git a/frontend/src/lib/import-hevy.js b/frontend/src/lib/import-hevy.js index b66c871..bed02b3 100644 --- a/frontend/src/lib/import-hevy.js +++ b/frontend/src/lib/import-hevy.js @@ -267,7 +267,8 @@ export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) { id: 'iw' + uid(), d, start: startMs, end: endMs > startMs ? endMs : startMs, routineId: null, name: day.name || 'Imported', entries, prs: [], } - workout.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (s.w || 0) * (s.r || 0), 0), 0) + // Work sets only, the number `workoutVolume` gives a workout finished in the app; it is stored for good. + workout.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (isWarmupRow(s) ? 0 : (s.w || 0) * (s.r || 0)), 0), 0) return workout }) diff --git a/frontend/src/lib/import-hevy.test.js b/frontend/src/lib/import-hevy.test.js index 7d7bc39..b395ea7 100644 --- a/frontend/src/lib/import-hevy.test.js +++ b/frontend/src/lib/import-hevy.test.js @@ -124,6 +124,9 @@ describe('parseHevyWorkouts', () => { expect(pulldown.topW).toBe(52) expect(parsed.warmups).toBe(1) expect(parsed.rpeSets).toBe(1) + // The stored volume leaves the warm-up out, like a workout finished in the app (QA C14): + // 52×15 + 52×10 + 20×12 = 1,540, not 1,915. + expect(parsed.workouts[0].vol).toBe(1540) const custom = entries.find(e => String(e.id).startsWith('im')) expect(custom).toBeTruthy() diff --git a/frontend/src/lib/import-name-bodypart.test.js b/frontend/src/lib/import-name-bodypart.test.js index 976731b..0191f7c 100644 --- a/frontend/src/lib/import-name-bodypart.test.js +++ b/frontend/src/lib/import-name-bodypart.test.js @@ -27,6 +27,19 @@ describe('body part from an exercise name', () => { expect(bp('Deadlift')).toBe('back') }) + // The rules are written with spaces, but people hyphenate these names as often as not (QA C28). + // The matcher already treats "chest-supported row" and "chest supported row" as one exercise; + // the body-part fallback has to agree with it, or the two spellings land on different maps. + it('reads the hyphenated, underscored and slashed spellings like the spaced ones', () => { + expect(bp('Stiff-Legged Deadlift')).toBe('upper legs') + expect(bp('Straight-Leg Deadlift')).toBe('upper legs') + expect(bp('Stiff_Leg Deadlift')).toBe('upper legs') + expect(bp('Chest-Supported Row')).toBe('back') + expect(bp('Chest-Supported T-Bar Row')).toBe('back') + expect(bp('Chest/Supported Row')).toBe('back') + expect(bp('Sit-Up')).toBe('waist') + }) + it('still reads a bare grip exercise as forearms, and the rest as before', () => { expect(bp('Grip Trainer')).toBe('lower arms') expect(bp('Back Squat')).toBe('back') // unchanged: "back" is matched before "squat" diff --git a/frontend/src/lib/muscles.js b/frontend/src/lib/muscles.js index eb913e1..92a96c5 100644 --- a/frontend/src/lib/muscles.js +++ b/frontend/src/lib/muscles.js @@ -31,13 +31,15 @@ export const inMuscleOrder = list => { // Drawn as the silhouette, never shaded: they carry no training load. export const INERT = ['head', 'hair', 'neck', 'hands', 'feet', 'knees', 'ankles'] -// English display names; these strings are the i18n keys (see lib/i18n.js). +// English display names; these strings are the i18n keys (see lib/i18n.js). The packs know +// the cardio pseudo-muscle only under the dataset's own lowercase spelling, and every place +// that shows it capitalises with CSS — a capitalised key here rendered English everywhere. export const MUSCLE_NAME = { trapezius: 'Traps', deltoids: 'Shoulders', chest: 'Chest', 'upper-back': 'Upper back', serratus: 'Serratus', biceps: 'Biceps', triceps: 'Triceps', forearm: 'Forearms', abs: 'Abs', obliques: 'Obliques', 'lower-back': 'Lower back', gluteal: 'Glutes', quadriceps: 'Quads', hamstring: 'Hamstrings', adductors: 'Adductors', - 'hip-flexors': 'Hip flexors', calves: 'Calves', tibialis: 'Shins', 'cardiovascular system': 'Cardiovascular system', + 'hip-flexors': 'Hip flexors', calves: 'Calves', tibialis: 'Shins', 'cardiovascular system': 'cardiovascular system', } // Every spelling that occurs in the dataset's `tg` and `sm` fields. null = not drawable. diff --git a/frontend/src/lib/muscles.test.js b/frontend/src/lib/muscles.test.js index 9294ac7..e0f29f0 100644 --- a/frontend/src/lib/muscles.test.js +++ b/frontend/src/lib/muscles.test.js @@ -210,3 +210,17 @@ describe('muscle balance windows and ranking', () => { expect(loadOfWorkouts([{ entries: [deleted] }])).toEqual({ chest: 1 }) }) }) + +// MUSCLE_NAME values are the i18n keys — a value no pack defines renders English in every +// language. The Library list showed "Cardiovascular system" untranslated for every cardio +// exercise (QA copy): the packs only ever had the dataset's own lowercase spelling. +describe('MUSCLE_NAME as i18n keys', () => { + const packs = import.meta.glob('../locales/*.js', { eager: true }) + it('every display name is a key in every locale pack', () => { + expect(Object.keys(packs).length).toBe(14) + for (const [file, mod] of Object.entries(packs)) { + const missing = Object.values(MUSCLE_NAME).filter(name => !(name in mod.default)) + expect(missing, file).toEqual([]) + } + }) +}) diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.js index 6089047..affc02f 100644 --- a/frontend/src/lib/plan-share.js +++ b/frontend/src/lib/plan-share.js @@ -14,6 +14,7 @@ import { deriveSessionName } from './session-merge.js' import { uid, todayISO, DAYN, weekOrder, weekStartOf, fmtNum, exCount } from './format.js' import { t, exerciseNameFor } from './i18n-core.js' import { convertWeight } from './units.js' +import { MUSCLES, inMuscleOrder } from './muscles.js' const PLAN_FMT = 1 const WEEK_DAYS = [1, 2, 3, 4, 5, 6, 0] // every getDay() index; only the reader's own @@ -133,6 +134,32 @@ function cleanIntensifier(x) { return null } +// The muscles the map can draw, plus the one label the form gives a cardio exercise. +const CUSTOM_MUSCLES = new Set([...MUSCLES, 'cardiovascular system']) +const muscleList = v => inMuscleOrder([...new Set((Array.isArray(v) ? v : []).filter(m => CUSTOM_MUSCLES.has(m)))]) + +/** A custom exercise with its own metadata — equipment, muscles, description — in the shape + * CustomExForm writes, minus the recipient-side `custom`/`sm` fields mergePlan adds. The bundle + * used to carry only {id, n, bp}, so the exercise arrived with an empty equipment tag, no muscle + * credit, and (stored without `custom: true`) no way to edit or delete it (QA C7). The same gate + * runs on the way in as on the way out, since a plan file is someone else's data: only muscles the + * map can draw, a secondary never repeating a primary, the way the form itself enforces. Fields + * that are empty stay absent, so a file written before this change reads the same as one after. */ +function cleanCustom(c) { + const o = { id: c.id, n: c.n, bp: c.bp } + if (c.desc) o.desc = c.desc + if (typeof c.eq === 'string' && c.eq) o.eq = c.eq + const prim = muscleList(c.primaries) + const sm = muscleList(c.secondaries).filter(m => !prim.includes(m)) + // `tg` is the legacy single primary; the form keeps it equal to the first primary. + const tg = prim[0] || (CUSTOM_MUSCLES.has(c.tg) ? c.tg : '') + if (tg) o.tg = tg + if (prim.length) o.primaries = prim + if (sm.length) o.secondaries = sm + if (prim.length || sm.length) o.muscleGroups = [...prim, ...sm] + return o +} + /** Build the shareable bundle: every routine, the week schedule, referenced customs. */ export function buildPlanBundle(S, name) { const unit = planUnit(S.unit == null ? 'kg' : S.unit) @@ -146,7 +173,7 @@ export function buildPlanBundle(S, name) { const usedIds = new Set(routines.flatMap(r => r.ex.map(e => e.id))) const customEx = (S.customEx || []) .filter(c => usedIds.has(c.id)) - .map(c => ({ id: c.id, n: c.n, bp: c.bp, ...(c.desc ? { desc: c.desc } : {}) })) + .map(cleanCustom) // A weekday can hold several routines (merge order preserved). `[].concat` normalises a // legacy scalar id to a one-element list, so a bundle written before this change and one // written after are read the same way at the other end. @@ -226,7 +253,10 @@ export function mergePlan(s, bundle, { schedule } = {}) { if (same) { exIdMap[c.id] = same.id; return } const nid = uid() exIdMap[c.id] = nid - s.customEx.push({ id: nid, n: c.n, bp: c.bp, ...(c.desc ? { desc: c.desc } : {}) }) + // Stored exactly as the form would have created it — `custom: true` is what lets the recipient + // edit or delete it, and `sm` mirrors the secondaries the way the form writes them. + const clean = cleanCustom(c) + s.customEx.push({ ...clean, id: nid, ...(clean.secondaries ? { sm: clean.secondaries } : {}), custom: true }) }) const ridMap = {} source.routines.forEach(r => { diff --git a/frontend/src/lib/plan-share.test.js b/frontend/src/lib/plan-share.test.js index 73f3388..a114faf 100644 --- a/frontend/src/lib/plan-share.test.js +++ b/frontend/src/lib/plan-share.test.js @@ -195,3 +195,64 @@ describe('week schedule as a routine-id list', () => { expect(parsePlan({ opengym_plan: 1, routines: [], customEx: [], week: { 1: ['a'], 2: [], 4: 'b' } }).scheduledDays).toBe(2) }) }) + +// ---- custom exercises travel whole (QA C7) ---- +// The bundle used to carry only {id, n, bp} and mergePlan stored exactly that: the recipient's copy +// showed an empty equipment tag, no muscle credit, and — without `custom: true` — no Edit or Delete, +// so a wrong import could only be fixed by hand-editing localStorage. +describe('custom exercises in a shared plan', () => { + // The shape CustomExForm writes, in the map's order. + const landmine = { + id: 'c1', n: 'QA Landmine Row', bp: 'back', desc: 'Bar in the corner', tg: 'upper-back', sm: ['biceps'], + muscleGroups: ['upper-back', 'biceps'], primaries: ['upper-back'], secondaries: ['biceps'], eq: 'barbell', custom: true, + } + const source = { + routines: [{ id: 'r', name: 'Back day', ex: [{ id: 'c1', sets: 3, reps: 8, weight: 40 }] }], + week: {}, customEx: [landmine], + } + + it('exports equipment, muscles and description with the custom exercise', () => { + expect(buildPlanBundle(source, 'Plan').customEx[0]).toEqual({ + id: 'c1', n: 'QA Landmine Row', bp: 'back', desc: 'Bar in the corner', eq: 'barbell', tg: 'upper-back', + primaries: ['upper-back'], secondaries: ['biceps'], muscleGroups: ['upper-back', 'biceps'], + }) + }) + + it('stores the imported custom exercise the way the form would have created it', () => { + const parsed = parsePlan(JSON.stringify(buildPlanBundle(source, 'Plan'))) + const target = { routines: [], week: {}, customEx: [] } + mergePlan(target, parsed) + const stored = target.customEx[0] + expect(stored).toMatchObject({ ...landmine, id: stored.id }) + expect(stored.id).not.toBe('c1') + expect(target.routines[0].ex[0].id).toBe(stored.id) + }) + + // A file written before the metadata travelled has only a name and a body part; it still imports, + // and the recipient can now add the equipment and muscles themselves. + it('keeps importing an old name-plus-body-part file, editable at the other end', () => { + const legacy = { opengym_plan: 1, routines: [{ id: 'r', name: 'R', ex: [{ id: 'x', sets: 3, reps: 5 }] }], customEx: [{ id: 'x', n: 'Old one', bp: 'legs' }] } + const target = { routines: [], week: {}, customEx: [] } + mergePlan(target, parsePlan(legacy)) + expect(target.customEx[0]).toEqual({ id: target.customEx[0].id, n: 'Old one', bp: 'legs', custom: true }) + expect(target.routines[0].ex[0].id).toBe(target.customEx[0].id) + }) + + // A plan file is someone else's data: only muscles the map can draw are kept, and a muscle listed + // as both primary and secondary counts once, as the form itself enforces. + it('drops muscles it cannot draw and a secondary that repeats a primary', () => { + const bundle = { opengym_plan: 1, routines: [], customEx: [{ id: 'x', n: 'Odd', bp: 'back', eq: 'barbell', primaries: ['upper-back', 'wings'], secondaries: ['upper-back', 'biceps', 7] }] } + const target = { routines: [], week: {}, customEx: [] } + mergePlan(target, parsePlan(bundle)) + expect(target.customEx[0]).toMatchObject({ primaries: ['upper-back'], secondaries: ['biceps'], muscleGroups: ['upper-back', 'biceps'], tg: 'upper-back', sm: ['biceps'] }) + }) + + it('still reuses a custom the recipient already has under the same name and body part', () => { + const parsed = parsePlan(JSON.stringify(buildPlanBundle(source, 'Plan'))) + const mine = { id: 'mine', n: 'qa landmine row', bp: 'back', eq: 'landmine', custom: true } + const target = { routines: [], week: {}, customEx: [mine] } + mergePlan(target, parsed) + expect(target.customEx).toEqual([mine]) + expect(target.routines[0].ex[0].id).toBe('mine') + }) +}) diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js index 72a71fc..42c163a 100644 --- a/frontend/src/lib/pt-br-locale.test.js +++ b/frontend/src/lib/pt-br-locale.test.js @@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => { .sort(byCodeUnit) const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex') - expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(644) - expect(inherited).toHaveLength(648) + expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(645) + expect(inherited).toHaveLength(647) // 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('32e5fc261a849772b42241c352d99ecf49a4a8ec640b52379031b6654f53deb8') + expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('185cca3dfbc438a4a2177956d1d18da2bbdc907281c5eb4c858ba34afaf9f38e') }) test('does not leak European Portuguese UI terms', () => { diff --git a/frontend/src/lib/search-typo.test.js b/frontend/src/lib/search-typo.test.js index 8182599..18838c4 100644 --- a/frontend/src/lib/search-typo.test.js +++ b/frontend/src/lib/search-typo.test.js @@ -1,5 +1,5 @@ import { expect, it } from 'vitest' -import { matchExercise } from './exercises.js' +import { EXDB, matchExercise, normalizeStr, searchExercises } from './exercises.js' const benchPress = { n: 'dumbbell bench press', bp: 'chest', tg: 'pectorals', eq: 'dumbbell', @@ -24,3 +24,47 @@ it('keeps existing exact substring and all-token behavior', () => { expect(matchExercise(benchPress, 'press bench')).toBe(true) expect(matchExercise(benchPress, 'bench squat')).toBe(false) }) + +// QA C26: a correctly spelled word one edit away from a body part / target / equipment word +// used to pull in that whole body part ("wrist" ~ "waist" listed every abs exercise first). +it('never fuzzy-matches body part, target, equipment or description words', () => { + const sitUp = { n: '3/4 sit-up', bp: 'waist', tg: 'abs', eq: 'body weight', sm: [], desc: 'Keep the lower back flat.' } + for (const query of ['wrist', 'power', 'bodz weight']) { + expect(matchExercise(sitUp, query), query).toBe(false) + } + // The exact substring path still covers those fields. + expect(matchExercise(sitUp, 'waist')).toBe(true) + expect(matchExercise(sitUp, 'lower')).toBe(true) +}) + +it('searchExercises takes a word literally when it hits anything exactly, and only then falls back to typos', () => { + const list = [ + { n: 'band wrist curl', bp: 'lower arms', eq: 'band' }, + { n: 'waist twist', bp: 'waist', eq: 'body weight' }, + { n: 'all fours squad stretch', bp: 'upper legs', eq: 'body weight' }, + { n: 'barbell squat', bp: 'upper legs', eq: 'barbell' }, + { n: 'side plank', bp: 'waist', eq: 'body weight' }, + { n: 'slide lunge', bp: 'upper legs', eq: 'body weight' }, + benchPress, + ] + const names = q => searchExercises(list, q).map(e => e.n) + expect(names('wrist')).toEqual(['band wrist curl']) + expect(names('squat')).toEqual(['barbell squat']) + expect(names('slide')).toEqual(['slide lunge']) + // No exact hit anywhere: the typo-tolerant path finds the exercise, name words only. + expect(names('wirst')).toEqual(['band wrist curl']) + expect(names('bnech press')).toEqual(['dumbbell bench press']) + expect(names('dumbell bench')).toEqual(['dumbbell bench press']) + expect(names('sqat')).toEqual([]) + expect(searchExercises(list, ' ')).toBe(list) +}) + +it('searchExercises over the real catalogue returns only exact hits for correctly spelled words', () => { + const plain = (e, q) => normalizeStr([e.n, e.tg, e.eq, e.bp, ...(e.sm || [])].join(' ')).includes(q) + for (const q of ['wrist', 'power', 'slide', 'thigh', 'squat', 'clean']) { + const got = searchExercises(EXDB, q) + expect(got.length, q).toBe(EXDB.filter(e => plain(e, q)).length) + expect(got.every(e => plain(e, q)), q).toBe(true) + } + expect(searchExercises(EXDB, 'wrist')[0].n).toBe('band reverse wrist curl') +}) diff --git a/frontend/src/lib/units.js b/frontend/src/lib/units.js index 3c22eed..41ae4d0 100644 --- a/frontend/src/lib/units.js +++ b/frontend/src/lib/units.js @@ -3,6 +3,7 @@ // can load: lb to the nearest 0.5, kg to the nearest 0.25 — enough that a value converted there // and back lands where it started for any plate-loadable number. import { isSideSet, syncSideAggregate } from './workout-model.js' +import { workoutVolume } from './history.js' const LB_PER_KG = 2.2046226218 @@ -13,6 +14,15 @@ export function convertWeight(value, from, to) { return Math.round(v / LB_PER_KG * 4) / 4 } +// Body weight is not loaded on a bar: the weigh-in sheet steps and stores it at 0.1, so plate +// rounding would move most weigh-ins on a kg → lb → kg round trip (78.6 → 173.5 → 78.75; QA C15). +// A tenth in either unit is fine enough that kg → lb → kg comes home for every 0.1-kg value. +export function convertBodyWeight(value, from, to) { + if (from === to || value == null || value === '' || !Number.isFinite(Number(value))) return value + const v = Number(value) + return Math.round((to === 'lb' ? v * LB_PER_KG : v / LB_PER_KG) * 10) / 10 +} + const convSet = (set, from, to) => { if (!set || typeof set !== 'object') return set const out = { ...set } @@ -47,13 +57,24 @@ export function convertStateUnit(S, to) { const from = S.unit || 'kg' if (from === to) return S const c = v => convertWeight(v, from, to) + const bw = v => convertBodyWeight(v, from, to) + // A session carries its body weight of the day and a cached total volume; History rows, the + // detail header, the month calendar and the heatmap tooltips read those rather than summing + // sets, so they must move with the sets or show kg totals under an lb label (QA C11). The + // volume is re-added from the converted sets, so it agrees with the set list to the number. + const convSession = s => { + const out = { ...s, entries: (s.entries || []).map(e => convEntry(e, from, to)) } + if (out.bw != null) out.bw = bw(out.bw) + if (Number.isFinite(out.vol)) out.vol = workoutVolume({ entries: out.entries.filter(e => Array.isArray(e?.sets)) }) + return out + } const out = { ...S, unit: to } - if (Array.isArray(S.bodyweight)) out.bodyweight = S.bodyweight.map(b => ({ ...b, w: c(b.w) })) - if (S.targetW != null) out.targetW = c(S.targetW) + if (Array.isArray(S.bodyweight)) out.bodyweight = S.bodyweight.map(b => ({ ...b, w: bw(b.w) })) + if (S.targetW != null) out.targetW = bw(S.targetW) if (S.exWeights) out.exWeights = Object.fromEntries(Object.entries(S.exWeights).map(([k, v]) => [k, v && typeof v === 'object' ? { ...v, w: c(v.w) } : c(v)])) if (S.barWeights) out.barWeights = Object.fromEntries(Object.entries(S.barWeights).map(([k, v]) => [k, c(v)])) if (Array.isArray(S.routines)) out.routines = S.routines.map(r => ({ ...r, ex: (r.ex || []).map(cfg => convTarget(cfg, from, to)) })) - if (Array.isArray(S.workouts)) out.workouts = S.workouts.map(w => ({ ...w, entries: (w.entries || []).map(e => convEntry(e, from, to)) })) - if (S.active) out.active = { ...S.active, entries: (S.active.entries || []).map(e => convEntry(e, from, to)) } + if (Array.isArray(S.workouts)) out.workouts = S.workouts.map(convSession) + if (S.active) out.active = convSession(S.active) return out } diff --git a/frontend/src/lib/units.test.js b/frontend/src/lib/units.test.js index cfdd404..6066d37 100644 --- a/frontend/src/lib/units.test.js +++ b/frontend/src/lib/units.test.js @@ -1,5 +1,6 @@ import { describe, it, expect } from 'vitest' import { convertWeight, convertStateUnit } from './units.js' +import { workoutVolume } from './history.js' describe('convertWeight', () => { it('rounds lb to a half and kg to a quarter', () => { @@ -32,8 +33,8 @@ describe('convertStateUnit', () => { it('converts every stored weight and keeps everything else', () => { const out = convertStateUnit(S, 'lb') expect(out.unit).toBe('lb') - expect(out.targetW).toBe(176.5) - expect(out.bodyweight[0]).toEqual({ d: '2026-01-01', w: 181.5, t: 1 }) + expect(out.targetW).toBe(176.4) // body weight keeps its 0.1, see below + expect(out.bodyweight[0]).toEqual({ d: '2026-01-01', w: 181.7, t: 1 }) expect(out.exWeights['0025'].w).toBe(176.5) expect(out.exWeights.legacy).toBe(220.5) expect(out.barWeights['0025']).toBe(44) @@ -49,4 +50,36 @@ describe('convertStateUnit', () => { it('is a no-op for the unit already in use', () => { expect(convertStateUnit(S, 'kg')).toBe(S) }) + // History rows, the detail header, the month calendar and the heatmap tooltips read the + // cached `vol` and `bw` off the saved workout rather than summing sets, so a conversion that + // skips them shows kg totals under an lb label (QA C11). + it('converts each workout\'s cached volume and session body weight, and the active session\'s (QA C11)', () => { + const drop = { id: '0025', sets: [{ w: 80, r: 5, done: true, type: 'dropset', drops: [{ w: 60, r: 5 }] }, { w: 40, r: 8, done: true, phase: 'warmup' }] } + const state = { ...S, + workouts: [{ id: 'w', vol: 700, bw: 82.4, entries: [drop] }, { id: 'x', entries: [] }], + active: { ...S.active, bw: 82.4 } } + const out = convertStateUnit(state, 'lb') + // 176.5 × 5 plus the 132.5 × 5 drop, warm-up left out — what the converted set list adds up to. + expect(out.workouts[0].vol).toBe(1545) + expect(workoutVolume(out.workouts[0])).toBe(1545) + expect(out.workouts[0].bw).toBe(181.7) + expect(out.active.bw).toBe(181.7) + // A workout that never had a cached volume does not grow one. + expect(out.workouts[1]).not.toHaveProperty('vol') + expect(state.workouts[0].vol).toBe(700) // the input is not mutated + }) + // Body weight is weighed in and edited at 0.1, not loaded on a bar: rounding it to plate steps + // moved 22 of 24 weigh-ins on a kg → lb → kg round trip (QA C15). The goal weight is one too. + it('keeps body weight at 0.1 resolution and brings a kg → lb → kg round trip home (QA C15)', () => { + const state = { unit: 'kg', targetW: 77, bodyweight: [78.6, 82.1, 82.2, 81.8, 81.4].map((w, i) => ({ d: `2026-01-0${i + 1}`, w, t: i })), + workouts: [{ id: 'w', bw: 78.6, entries: [] }], active: { id: 'a', bw: 78.6, entries: [] } } + const lb = convertStateUnit(state, 'lb') + expect(lb.bodyweight.map(b => b.w)).toEqual([173.3, 181, 181.2, 180.3, 179.5]) + expect(lb.targetW).toBe(169.8) + const back = convertStateUnit(lb, 'kg') + expect(back.bodyweight.map(b => b.w)).toEqual([78.6, 82.1, 82.2, 81.8, 81.4]) + expect(back.targetW).toBe(77) + expect(back.workouts[0].bw).toBe(78.6) + expect(back.active.bw).toBe(78.6) + }) }) diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js index e1fd7d5..c54dff9 100644 --- a/frontend/src/locales/de.js +++ b/frontend/src/locales/de.js @@ -504,7 +504,6 @@ export default { 'Hip flexors': 'Hüftbeuger', 'Calves': 'Waden', 'Shins': 'Schienbein', - 'Cardiovascular system': 'Herz-Kreislauf', // --- import from another app --- 'Import from another app': 'Aus anderer App importieren', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — oder Körpergewicht aus Apple Health', @@ -581,6 +580,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': '{0} Übungen aus der Datei sind nicht in deiner Bibliothek und wurden weggelassen.', 'Use this weekly schedule': 'Diesen Wochenplan verwenden', 'Replaces your current Mon–Sun assignments.': 'Ersetzt deine aktuelle Mo–So-Belegung.', + 'Added {0} routine to your plan': '{0} Routine zu deinem Plan hinzugefügt', 'Added {0} routines to your plan': '{0} Routinen zu deinem Plan hinzugefügt', 'this isn’t an openGym plan file': 'das ist keine openGym-Plandatei', 'Shared routine': 'Geteilte Routine', diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index fd07819..b77e136 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -485,7 +485,6 @@ export default { 'Hip flexors': 'Flexores de cadera', 'Calves': 'Gemelos', 'Shins': 'Tibiales', - 'Cardiovascular system': 'sistema cardiovascular', // --- import from another app --- 'Import from another app': 'Importar de otra app', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — o peso corporal de Apple Health', @@ -562,6 +561,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': '{0} ejercicios del archivo no están en tu biblioteca y se han omitido.', 'Use this weekly schedule': 'Usar este horario semanal', 'Replaces your current Mon–Sun assignments.': 'Reemplaza tu asignación actual de lun–dom.', + 'Added {0} routine to your plan': 'Se añadió {0} rutina a tu plan', 'Added {0} routines to your plan': 'Se añadieron {0} rutinas a tu plan', 'this isn’t an openGym plan file': 'esto no es un archivo de plan de openGym', 'Shared routine': 'Rutina compartida', diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js index 1fab885..5feda70 100644 --- a/frontend/src/locales/fr.js +++ b/frontend/src/locales/fr.js @@ -485,7 +485,6 @@ export default { 'Hip flexors': 'Fléchisseurs de hanche', 'Calves': 'Mollets', 'Shins': 'Tibiaux', - 'Cardiovascular system': 'système cardiovasculaire', // --- import from another app --- 'Import from another app': 'Importer depuis une autre app', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — ou le poids depuis Apple Santé', @@ -562,6 +561,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': '{0} exercices du fichier ne sont pas dans ta bibliothèque et ont été ignorés.', 'Use this weekly schedule': 'Utiliser ce planning hebdomadaire', 'Replaces your current Mon–Sun assignments.': 'Remplace ton attribution lun–dim actuelle.', + 'Added {0} routine to your plan': '{0} routine ajoutée à ton plan', 'Added {0} routines to your plan': '{0} routines ajoutées à ton plan', 'this isn’t an openGym plan file': 'ce n\'est pas un fichier de plan openGym', 'Shared routine': 'Routine partagée', diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js index 854265f..485de72 100644 --- a/frontend/src/locales/hi.js +++ b/frontend/src/locales/hi.js @@ -485,7 +485,6 @@ export default { 'Hip flexors': 'हिप फ्लेक्सर', 'Calves': 'पिंडली', 'Shins': 'पिंडली की हड्डी', - 'Cardiovascular system': 'हृदय प्रणाली', // --- import from another app --- 'Import from another app': 'दूसरे ऐप से आयात करें', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — या Apple Health से वज़न', @@ -562,6 +561,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': 'फ़ाइल के {0} व्यायाम आपकी लाइब्रेरी में नहीं हैं और छोड़ दिए गए।', 'Use this weekly schedule': 'यह साप्ताहिक कार्यक्रम इस्तेमाल करें', 'Replaces your current Mon–Sun assignments.': 'आपके मौजूदा सोम–रवि निर्धारण को बदल देता है।', + 'Added {0} routine to your plan': 'आपके प्लान में {0} रूटीन जोड़ा गया', 'Added {0} routines to your plan': 'आपके प्लान में {0} रूटीन जोड़े गए', 'this isn’t an openGym plan file': 'यह openGym प्लान फ़ाइल नहीं है', 'Shared routine': 'साझा किया गया रूटीन', diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js index fea8eb6..0cfa720 100644 --- a/frontend/src/locales/hu.js +++ b/frontend/src/locales/hu.js @@ -490,7 +490,6 @@ export default { 'Hip flexors': 'Csípőhajlító', 'Calves': 'Vádli', 'Shins': 'Sípcsont', - 'Cardiovascular system': 'szív-érrendszer', // --- import from another app --- 'Import from another app': 'Importálás másik appból', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — vagy testsúly az Apple Healthből', @@ -541,6 +540,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': '{0} gyakorlat a fájlban nincs a könyvtáradban, ezért kimaradt.', 'Use this weekly schedule': 'Heti beosztás alkalmazása', 'Replaces your current Mon–Sun assignments.': 'Lecseréli a jelenlegi H–V beosztásod.', + 'Added {0} routine to your plan': '{0} rutin hozzáadva a tervedhez', 'Added {0} routines to your plan': '{0} rutin hozzáadva a tervedhez', 'this isn’t an openGym plan file': 'ez nem egy openGym tervfájl', 'Shared routine': 'Megosztott rutin', diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js index 99533bc..8e80cd7 100644 --- a/frontend/src/locales/it.js +++ b/frontend/src/locales/it.js @@ -485,7 +485,6 @@ export default { 'Hip flexors': 'Flessori dell\'anca', 'Calves': 'Polpacci', 'Shins': 'Tibiali', - 'Cardiovascular system': 'sistema cardiovascolare', // --- import from another app --- 'Import from another app': 'Importa da un\'altra app', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — o il peso da Apple Salute', @@ -562,6 +561,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': '{0} esercizi del file non sono nella tua libreria e sono stati esclusi.', 'Use this weekly schedule': 'Usa questo programma settimanale', 'Replaces your current Mon–Sun assignments.': 'Sostituisce la tua assegnazione lun–dom attuale.', + 'Added {0} routine to your plan': 'Aggiunta {0} routine al tuo piano', 'Added {0} routines to your plan': 'Aggiunte {0} routine al tuo piano', 'this isn’t an openGym plan file': 'questo non è un file di piano openGym', 'Shared routine': 'Routine condivisa', diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js index 65420b2..d5b13d3 100644 --- a/frontend/src/locales/ko.js +++ b/frontend/src/locales/ko.js @@ -485,7 +485,6 @@ export default { 'Hip flexors': '고관절 굴곡근', 'Calves': '종아리', 'Shins': '정강이', - 'Cardiovascular system': '심혈관계', // --- import from another app --- 'Import from another app': '다른 앱에서 가져오기', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — 또는 Apple 건강의 체중', @@ -562,6 +561,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': '파일의 운동 {0}개가 라이브러리에 없어 제외했습니다.', 'Use this weekly schedule': '이 주간 일정 사용', 'Replaces your current Mon–Sun assignments.': '현재 월–일 배정을 대체합니다.', + 'Added {0} routine to your plan': '계획에 루틴 {0}개를 추가했습니다', 'Added {0} routines to your plan': '계획에 루틴 {0}개를 추가했습니다', 'this isn’t an openGym plan file': 'openGym 계획 파일이 아닙니다', 'Shared routine': '공유된 루틴', diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js index dd2a845..2d3321e 100644 --- a/frontend/src/locales/pl.js +++ b/frontend/src/locales/pl.js @@ -485,7 +485,6 @@ export default { 'Hip flexors': 'Zginacze bioder', 'Calves': 'Łydki', 'Shins': 'Piszczele', - 'Cardiovascular system': 'układ krążenia', // --- import from another app --- 'Import from another app': 'Importuj z innej aplikacji', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — albo masa ciała z Apple Health', @@ -562,6 +561,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': '{0} ćwiczeń z pliku nie ma w Twojej bibliotece i zostały pominięte.', 'Use this weekly schedule': 'Użyj tego harmonogramu tygodnia', 'Replaces your current Mon–Sun assignments.': 'Zastępuje Twój obecny przydział pon–niedz.', + 'Added {0} routine to your plan': 'Dodano {0} plan treningowy do Twojego planu', 'Added {0} routines to your plan': 'Dodano {0} planów treningowych do Twojego planu', 'this isn’t an openGym plan file': 'to nie jest plik planu openGym', 'Shared routine': 'Udostępniony plan treningowy', diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js index 324b0f2..087c696 100644 --- a/frontend/src/locales/pt-BR.js +++ b/frontend/src/locales/pt-BR.js @@ -210,6 +210,7 @@ export const PT_BR_OVERRIDES = { '{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} routine to your plan': '{0} rotina adicionada ao seu plano', '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.', diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js index 22af99c..7619b0f 100644 --- a/frontend/src/locales/pt.js +++ b/frontend/src/locales/pt.js @@ -485,7 +485,6 @@ export default { 'Hip flexors': 'Flexores do quadril', 'Calves': 'Panturrilhas', 'Shins': 'Tibiais', - 'Cardiovascular system': 'sistema cardiovascular', // --- import from another app --- 'Import from another app': 'Importar de outra app', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — ou o peso da Apple Saúde', @@ -562,6 +561,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': '{0} exercícios do ficheiro não estão na tua biblioteca e foram ignorados.', 'Use this weekly schedule': 'Usar este horário semanal', 'Replaces your current Mon–Sun assignments.': 'Substitui a tua atribuição atual de seg–dom.', + 'Added {0} routine to your plan': 'Adicionada {0} rotina ao teu plano', 'Added {0} routines to your plan': 'Adicionadas {0} rotinas ao teu plano', 'this isn’t an openGym plan file': 'isto não é um ficheiro de plano openGym', 'Shared routine': 'Rotina partilhada', diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js index 6e60694..85aaa63 100644 --- a/frontend/src/locales/ru.js +++ b/frontend/src/locales/ru.js @@ -485,7 +485,6 @@ export default { 'Hip flexors': 'Сгибатели бедра', 'Calves': 'Икры', 'Shins': 'Голени', - 'Cardiovascular system': 'сердечно-сосудистая система', // --- import from another app --- 'Import from another app': 'Импорт из другого приложения', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — или вес из Apple Health', @@ -562,6 +561,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': '{0} упражнений из файла отсутствуют в вашей библиотеке и были пропущены.', 'Use this weekly schedule': 'Использовать это расписание недели', 'Replaces your current Mon–Sun assignments.': 'Заменяет твоё текущее распределение пн–вс.', + 'Added {0} routine to your plan': 'В твой план добавлена {0} программа', 'Added {0} routines to your plan': 'В твой план добавлено программ: {0}', 'this isn’t an openGym plan file': 'это не файл плана openGym', 'Shared routine': 'Общая программа', diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js index d75ff9a..bd0c87c 100644 --- a/frontend/src/locales/th.js +++ b/frontend/src/locales/th.js @@ -490,7 +490,6 @@ export default { 'Hip flexors': 'กล้ามเนื้องอสะโพก', 'Calves': 'น่อง', 'Shins': 'หน้าแข้ง', - 'Cardiovascular system': 'ระบบหัวใจและหลอดเลือด', // --- import from another app --- 'Import from another app': 'นำเข้าจากแอปอื่น', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — หรือน้ำหนักตัวจาก Apple Health', @@ -541,6 +540,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': 'มี {0} ท่าในไฟล์ที่ไม่มีในคลังของคุณ จึงถูกข้ามไป', 'Use this weekly schedule': 'ใช้ตารางรายสัปดาห์นี้', 'Replaces your current Mon–Sun assignments.': 'จะแทนที่ตารางจันทร์–อาทิตย์ปัจจุบันของคุณ', + 'Added {0} routine to your plan': 'เพิ่ม {0} รูทีนเข้าแผนของคุณแล้ว', 'Added {0} routines to your plan': 'เพิ่ม {0} รูทีนเข้าแผนของคุณแล้ว', 'this isn’t an openGym plan file': 'นี่ไม่ใช่ไฟล์แผนของ openGym', 'Shared routine': 'รูทีนที่แชร์มา', diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js index 61ae963..4bad8ce 100644 --- a/frontend/src/locales/tr.js +++ b/frontend/src/locales/tr.js @@ -485,7 +485,6 @@ export default { 'Hip flexors': 'Kalça fleksörleri', 'Calves': 'Baldırlar', 'Shins': 'İncik', - 'Cardiovascular system': 'kalp-damar sistemi', // --- import from another app --- 'Import from another app': 'Başka uygulamadan içe aktar', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes, Strong, Hevy — veya Apple Health\'ten vücut ağırlığı', @@ -562,6 +561,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': 'Dosyadaki {0} egzersiz kitaplığında yok ve atlandı.', 'Use this weekly schedule': 'Bu hafta programını kullan', 'Replaces your current Mon–Sun assignments.': 'Mevcut Pzt–Paz atamanı değiştirir.', + 'Added {0} routine to your plan': 'Planına {0} rutin eklendi', 'Added {0} routines to your plan': 'Planına {0} rutin eklendi', 'this isn’t an openGym plan file': 'bu bir openGym plan dosyası değil', 'Shared routine': 'Paylaşılan rutin', diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js index 241528a..96f33b9 100644 --- a/frontend/src/locales/zh.js +++ b/frontend/src/locales/zh.js @@ -485,7 +485,6 @@ export default { 'Hip flexors': '髋屈肌', 'Calves': '小腿', 'Shins': '胫前肌', - 'Cardiovascular system': '心血管系统', // --- import from another app --- 'Import from another app': '从其他应用导入', 'FitNotes, Strong, Hevy — or body weight from Apple Health': 'FitNotes、Strong、Hevy — 或来自 Apple 健康的体重', @@ -562,6 +561,7 @@ export default { '{0} exercises in the file aren’t in your library and were left out.': '文件中有 {0} 个动作不在你的动作库中,已略过。', 'Use this weekly schedule': '使用此每周日程', 'Replaces your current Mon–Sun assignments.': '替换你当前的周一至周日安排。', + 'Added {0} routine to your plan': '已向你的计划添加 {0} 个训练日', 'Added {0} routines to your plan': '已向你的计划添加 {0} 个训练日', 'this isn’t an openGym plan file': '这不是 openGym 计划文件', 'Shared routine': '共享的训练日', diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index e5ef020..40acaf9 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -1,9 +1,9 @@ import { useEffect, useMemo, 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, matchExercise, exOr } from './lib/exercises.js' +import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, searchExercises, exOr } from './lib/exercises.js' import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js' -import { fmtDate, fmtNum, capWords, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js' +import { fmtDate, fmtNum, capWords, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, routineCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js' import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineIds, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js' import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride } from './lib/bar.js' import { toScale, rirOf, EFFORT_PRESETS, effortColor } from './lib/effort.js' @@ -891,7 +891,7 @@ function ExercisePicker({ onPick, close }) { const all = allExercises(st) const profile = activeProfile(st) const inScope = e => bp === '★' ? usage[e.id] : bp === '☆' ? isFav(st, e.id) : (!bp || e.bp === bp) - let base = all.filter(e => inScope(e) && matchExercise(e, q)) + let base = searchExercises(all.filter(inScope), 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) @@ -1523,13 +1523,13 @@ function PlanImport({ bundle, close }) { const apply = () => { update(s => mergePlan(s, bundle, { schedule })) close() - toast(t('Added {0} routines to your plan', bundle.routineCount)) + toast(t(bundle.routineCount === 1 ? 'Added {0} routine to your plan' : 'Added {0} routines to your plan', bundle.routineCount)) nav('/plan') } return <>

{bundle.name ? t('Import “{0}”', bundle.name) : t('Import this plan')}

- {t(bundle.routineCount === 1 ? '{0} routine' : '{0} routines', bundle.routineCount)} + {routineCount(bundle.routineCount)} {' · ' + exCount(bundle.exerciseCount)} {bundle.scheduledDays > 0 ? ' · ' + t(bundle.scheduledDays === 1 ? 'scheduled on {0} day' : 'scheduled on {0} days', bundle.scheduledDays) diff --git a/frontend/src/sheets.plan-import-toast.test.jsx b/frontend/src/sheets.plan-import-toast.test.jsx new file mode 100644 index 0000000..27915fd --- /dev/null +++ b/frontend/src/sheets.plan-import-toast.test.jsx @@ -0,0 +1,56 @@ +// @vitest-environment happy-dom +// Importing a one-routine plan file toasted "Added 1 routines to your plan" (QA copy): the +// sheet's summary line already picked the singular, the toast after the merge did not. +import React, { act } from 'react' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { createRoot } from 'react-dom/client' +import { useStore } from './store/useStore.js' +import { useUI } from './store/useUI.js' +import { planImportSheet } from './sheets.jsx' +import { parsePlan } from './lib/plan-share.js' +import { EXDB } from './lib/exercises.js' + +const clone = v => JSON.parse(JSON.stringify(v)) +const ids = EXDB.filter(e => e.bp !== 'cardio').slice(0, 2).map(e => e.id) +const mounted = [] + +function renderTop() { + 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 buttonFor = (host, label) => [...host.querySelectorAll('button')].find(b => b.textContent === label) +const bundleOf = routines => parsePlan({ opengym_plan: 1, unit: 'kg', week: {}, routines, customEx: [] }, 'kg') +const routine = (id, name) => ({ id, name, emoji: null, ex: [{ id: ids[0], sets: 3, reps: 8, weight: 40 }] }) + +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + useUI.setState({ sheets: [], toastMsg: '' }) + document.body.innerHTML = '' + const S = clone(useStore.getState().S) + S.routines = [] + S.week = {} + useStore.setState({ S, user: null }) +}) +afterEach(() => { act(() => { mounted.splice(0).forEach(r => r.unmount()) }) }) + +describe('Plan import sheet — the toast counts what it added', () => { + it('says "1 routine" for a single routine', () => { + planImportSheet(bundleOf([routine('a', 'Push')])) + const host = renderTop() + act(() => { buttonFor(host, 'Add to my plan').click() }) + expect(useStore.getState().S.routines).toHaveLength(1) + expect(useUI.getState().toastMsg).toBe('Added 1 routine to your plan') + }) + + it('keeps the plural for several', () => { + planImportSheet(bundleOf([routine('a', 'Push'), routine('b', 'Pull')])) + const host = renderTop() + act(() => { buttonFor(host, 'Add to my plan').click() }) + expect(useUI.getState().toastMsg).toBe('Added 2 routines to your plan') + }) +}) diff --git a/frontend/src/views/Admin.jsx b/frontend/src/views/Admin.jsx index e52d1e9..8ca0409 100644 --- a/frontend/src/views/Admin.jsx +++ b/frontend/src/views/Admin.jsx @@ -36,6 +36,12 @@ function UserDetail({ id, onChanged, close }) { useEffect(() => { api('/api/admin/user?id=' + encodeURIComponent(id)).then(setD).catch(e => toast(e.message)) }, [id]) if (!d) return
Loading…
const u = d.user + // The document comes straight off the user's state file. PUT /api/data drops null and + // shapeless entries now, but a file written before it did still answers with them, and this + // sheet renders outside the route's ErrorBoundary: one throw here blanked the whole app and + // left exactly this account un-disableable. setsDone/workoutVolume walk entries and sets, so + // an entry that lacks either has nothing to show and is skipped rather than drawn. + const workouts = (d.workouts || []).filter(w => w && Array.isArray(w.entries) && w.entries.every(e => e && Array.isArray(e.sets))) const setDisabled = disabled => { api('/api/admin/user/disable', { method: 'POST', body: JSON.stringify({ id: u.id, disabled }) }) .then(() => { toast(disabled ? 'User disabled' : 'User enabled'); onChanged(); close() }) @@ -50,7 +56,7 @@ function UserDetail({ id, onChanged, close }) { joined {u.created ? fmtDate(u.created.slice(0, 10)) : '—'}
-
Workouts
{d.workouts.length}
+
Workouts
{workouts.length}
Weigh-ins
{d.bodyweight.length}
Routines
{d.routines.length}
Last sync
{rel(d.lastSync)}
@@ -63,8 +69,8 @@ function UserDetail({ id, onChanged, close }) {
{u.disabled ? 'Enabling lets them sign in and sync again.' : 'Disabling signs them out everywhere and blocks sign-in. Nothing is deleted.'}
}

Workout history

- {d.workouts.length ?
- {d.workouts.slice(0, 60).map(w =>
+ {workouts.length ?
+ {workouts.slice(0, 60).map(w =>
{w.name}
{fmtDate(w.d, true)} · {fmtDur((w.end || w.start) - w.start)} · {setsDone(w)} sets{w.prs?.length ? ' · ' + w.prs.length + ' PR' : ''}
{fmtVol(w.vol ?? workoutVolume(w), d.unit)} diff --git a/frontend/src/views/Admin.test.jsx b/frontend/src/views/Admin.test.jsx new file mode 100644 index 0000000..d3cdba6 --- /dev/null +++ b/frontend/src/views/Admin.test.jsx @@ -0,0 +1,84 @@ +// @vitest-environment happy-dom +// The admin drill-down (QA C16): a profile whose stored workouts hold a null or otherwise +// shapeless entry must still open, because the sheet host sits outside the route's +// ErrorBoundary — a throw here blanked the whole app and left the account un-disableable. +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import Admin from './Admin.jsx' + +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +const mocks = vi.hoisted(() => ({ answers: {}, sheets: [] })) +vi.mock('../lib/api.js', () => ({ + api: path => { + const key = path.split('?')[0] + return key in mocks.answers ? Promise.resolve(mocks.answers[key]) : Promise.reject(new Error('not found')) + } +})) +vi.mock('../store/useStore.js', () => { + const snap = () => ({ user: { id: 'adm', name: 'Admin', admin: true }, S: {} }) + const useStore = selector => selector ? selector(snap()) : snap() + useStore.getState = snap + return { useStore } +}) +vi.mock('../store/useUI.js', () => { + const snap = () => ({ toast: () => {}, openSheet: render => mocks.sheets.push(render) }) + const useUI = selector => selector ? selector(snap()) : snap() + useUI.getState = snap + return { useUI } +}) +vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) +vi.mock('../sheets.jsx', () => ({ confirmSheet: vi.fn() })) +vi.mock('./AdminCoach.jsx', () => ({ default: () => null })) + +const mounted = [] +function render(el) { + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + mounted.push(root) + act(() => root.render(el)) + return host +} +const settle = () => act(() => new Promise(r => setTimeout(r, 0))) + +const good = { id: 'w1', name: 'Push day', d: '2026-09-10', start: 1000, end: 61000, entries: [{ sets: [{ done: true }, { done: false }] }] } + +beforeEach(() => { + document.body.innerHTML = '' + mocks.sheets.length = 0 + mocks.answers = { + '/api/admin/users': { users: [{ id: 'u1', name: 'Mallory', workouts: 2, lastSync: null, disabled: false }], invite_only: false }, + '/api/admin/invites': { invites: [] }, + '/api/admin/audit': { rows: [] }, + '/api/admin/user': { + user: { id: 'u1', name: 'Mallory', created: '2026-09-01T00:00:00Z', disabled: false, admin: false }, + unit: 'kg', lastSync: null, routines: [], bodyweight: [], + // What GET /api/admin/user hands over for a document written before PUT /api/data dropped + // such entries: a null, and a bare object without entries, next to a real session. + workouts: [null, good, {}] + } + } +}) +afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) }) + +describe('Admin user drill-down', () => { + it('opens a profile with malformed workout entries and still offers "Disable account"', async () => { + const page = render() + await settle() + const row = [...page.querySelectorAll('.item')].find(el => el.textContent.includes('Mallory')) + expect(row).toBeTruthy() + act(() => row.click()) + expect(mocks.sheets.length).toBe(1) + const sheet = render(mocks.sheets[0](() => {})) + await settle() + const buttons = [...sheet.querySelectorAll('button')].map(b => b.textContent) + expect(buttons).toContain('Disable account') + // The one real session is listed; the two shapeless entries are skipped, not drawn as blanks. + const rows = [...sheet.querySelectorAll('.list > div')] + expect(rows.length).toBe(1) + expect(rows[0].textContent).toContain('Push day') + expect(rows[0].textContent).toContain('1 sets') + }) +}) diff --git a/frontend/src/views/Library.jsx b/frontend/src/views/Library.jsx index f02836d..84ffd7d 100644 --- a/frontend/src/views/Library.jsx +++ b/frontend/src/views/Library.jsx @@ -1,7 +1,7 @@ import { useRef, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' -import { EXDB, BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js' +import { EXDB, BODYPARTS, allExercises, equipmentOf, searchExercises } from '../lib/exercises.js' import { MUSCLE_NAME } from '../lib/muscles.js' import { activeProfile, exAvailable } from '../lib/equipment.js' import { bestWeightFor } from '../lib/history.js' @@ -24,7 +24,7 @@ export default function Library() { const [shown, setShown] = useState(40) const bpStrip = useRef(null), eqStrip = useRef(null) const profile = activeProfile(S) - const base = allExercises(S).filter(e => (!bp || e.bp === bp) && matchExercise(e, q)) + const base = searchExercises(allExercises(S).filter(e => !bp || e.bp === bp), 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. diff --git a/frontend/src/views/Plan.jsx b/frontend/src/views/Plan.jsx index bd933e3..bacca3c 100644 --- a/frontend/src/views/Plan.jsx +++ b/frontend/src/views/Plan.jsx @@ -1,6 +1,6 @@ import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' -import { DAYN, weekOrder, weekStartOf, uid, exCount } from '../lib/format.js' +import { DAYN, weekOrder, weekStartOf, uid, exCount, routineCount } from '../lib/format.js' import { t } from '../lib/i18n.js' import { dayAssignSheet, dayAddRoutineSheet, starterPlanSheet, planToolsSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' @@ -65,7 +65,7 @@ export default function Plan() { return
{t(DAYN[d])}
-
{t('{0} routines', dayRoutines.length)}
+
{routineCount(dayRoutines.length)}
{dayRoutines.map(r =>
diff --git a/frontend/src/views/Plan.routine-count.test.jsx b/frontend/src/views/Plan.routine-count.test.jsx new file mode 100644 index 0000000..1c00ed5 --- /dev/null +++ b/frontend/src/views/Plan.routine-count.test.jsx @@ -0,0 +1,60 @@ +// @vitest-environment happy-dom +// A weekday with one routine read "1 routines" (QA copy): the header formatted the count +// with the plural key only, although both forms have been in every pack for a long time. +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import Plan from './Plan.jsx' + +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +const mocks = vi.hoisted(() => { + const state = { S: null } + state.snapshot = () => ({ + S: state.S, + user: null, + update: mut => { + const next = structuredClone(state.S) + mut(next) + state.S = next + }, + }) + return state +}) +vi.mock('../store/useStore.js', () => { + const useStore = selector => (selector ? selector(mocks.snapshot()) : mocks.snapshot()) + useStore.getState = mocks.snapshot + return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false } +}) +vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) +vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() })) +vi.mock('../sheets.jsx', () => ({ + starterPlanSheet: vi.fn(), dayAssignSheet: vi.fn(), dayAddRoutineSheet: vi.fn(), planToolsSheet: vi.fn(), +})) + +let host, root +beforeEach(() => { + mocks.S = { + unit: 'kg', workouts: [], exWeights: {}, week: {}, dayPlan: {}, + routines: [{ id: 'r1', name: 'Push', emoji: null, ex: [] }, { id: 'r2', name: 'Pull', emoji: null, ex: [] }], + } + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) +}) +afterEach(() => { + act(() => root.unmount()) + host.remove() +}) + +const mount = () => act(() => root.render()) +const countOn = day => [...host.querySelectorAll('.item')].find(el => el.querySelector('.tt')?.textContent === day)?.querySelector('.small.dim')?.textContent + +describe('Plan — the day header counts its routines', () => { + it('uses the singular for one routine and the plural for more', () => { + mocks.S.week = { 1: ['r1'], 2: ['r1', 'r2'] } + mount() + expect(countOn('Monday')).toBe('1 routine') + expect(countOn('Tuesday')).toBe('2 routines') + }) +}) diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx index 636e266..692b854 100644 --- a/frontend/src/views/Stats.jsx +++ b/frontend/src/views/Stats.jsx @@ -5,7 +5,7 @@ import { EXIDX, matchExercise } from '../lib/exercises.js' import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js' import { fmtNum, fmtDate, fmtVol, todayISO, weekStartOf } from '../lib/format.js' import { t, exerciseNameFor, getLang } from '../lib/i18n.js' -import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx' +import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, exerciseHistorySheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx' import LineChart from '../components/LineChart.jsx' import Heatmap from '../components/Heatmap.jsx' import Icon from '../components/Icon.jsx' @@ -189,8 +189,10 @@ function MuscleBalance({ S }) {
{t('Strength shows retained muscle strength. Train again to reset it.')}
{sel && <>

{t('Exercises')} · {t(MUSCLE_NAME[sel])}

+ {/* A row quotes the exercise's estimated 1RM, so a tap opens the exercise history + sheet — the curve behind that number plus the last sessions set by set. */} {muscleExercises.length ? muscleExercises.map(row => ( -
onExercise && onExercise(row.id))}> +
exerciseHistorySheet(row.id))}> {row.name} diff --git a/frontend/src/views/Stats.recovery.test.jsx b/frontend/src/views/Stats.recovery.test.jsx index 402981f..93c1052 100644 --- a/frontend/src/views/Stats.recovery.test.jsx +++ b/frontend/src/views/Stats.recovery.test.jsx @@ -20,6 +20,7 @@ const LEGACY_SNAPSHOT_ID = 'legacy-snapshot-only' const mocks = vi.hoisted(() => ({ maps: [], mapMounts: 0, + exerciseHistorySheet: vi.fn(), S: { unit: 'kg', body: 'male', effort: 'rir', targetW: null, bodyweight: [], routines: [], workouts: [], @@ -32,6 +33,7 @@ vi.mock('../store/useStore.js', () => ({ vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} })) vi.mock('../sheets.jsx', () => ({ bwSheet: () => {}, goalSheet: () => {}, calendarSheet: () => {}, workoutDetailSheet: () => {}, + exerciseHistorySheet: mocks.exerciseHistorySheet, WorkoutRow: () => React.createElement('div'), bwDeltaColor: () => 'inherit', })) vi.mock('../components/LineChart.jsx', () => ({ default: () => React.createElement('div') })) @@ -139,6 +141,7 @@ function resetFixture(workouts = lifecycleWorkouts()) { mocks.S.workouts = workouts mocks.maps.length = 0 mocks.mapMounts = 0 + mocks.exerciseHistorySheet.mockClear() useUI.setState({ sheets: [] }) } @@ -306,6 +309,36 @@ describe('Stats muscle recovery view runtime', () => { }) }) +describe('Stats strength exercise rows', () => { + // The rows under "Exercises · " are presented as buttons (role, tabIndex, pointer + // cursor) but for a year called a handler that never existed, so every tap threw + // "onExercise is not defined" and opened nothing (QA C13). A tap now opens the exercise's + // history sheet — the one place that already draws the Est. 1RM curve the row quotes. + it('opens the exercise history sheet when a row is tapped instead of throwing', async () => { + resetFixture(exercisePickerWorkouts()) + await mountStats() + const thrown = [] + dom.addEventListener('error', e => { thrown.push(e.error || e.message); e.preventDefault() }) + + await click(viewButton('Strength')) + await click(muscleCard().querySelector('[data-muscle="chest"]')) + expect(muscleCard().textContent).toContain('Exercises · Chest') + const row = [...muscleCard().querySelectorAll('.mrow[role="button"]')].find(el => el.textContent.includes('Est. 1RM')) + expect(row, 'expected a tappable exercise row for the chest').toBeTruthy() + expect(row.textContent).toContain('barbell bench press') + + await click(row) + expect(thrown).toEqual([]) + expect(mocks.exerciseHistorySheet).toHaveBeenCalledTimes(1) + expect(mocks.exerciseHistorySheet).toHaveBeenCalledWith('0025') + + // The keyboard path of tappable() must land in the same place. + await act(async () => { row.dispatchEvent(new dom.KeyboardEvent('keydown', { key: 'Enter', bubbles: true })) }) + expect(thrown).toEqual([]) + expect(mocks.exerciseHistorySheet).toHaveBeenCalledTimes(2) + }) +}) + describe('Stats exercise progress picker', () => { it('filters with the shared exercise matcher and still selects from the mounted sheet', async () => { resetFixture(exercisePickerWorkouts()) diff --git a/frontend/src/views/Stats.test.js b/frontend/src/views/Stats.test.js index 50f5ec7..179f892 100644 --- a/frontend/src/views/Stats.test.js +++ b/frontend/src/views/Stats.test.js @@ -19,7 +19,10 @@ describe('Stats mixed-entry metric contract', () => { it('renders one clickable muscle exercise list rather than a duplicate non-clickable copy', () => { expect((source.match(/muscleExercises\.length \? muscleExercises\.map\(row =>/g) || []).length).toBe(1) - expect(source).toContain('{...tappable(() => onExercise && onExercise(row.id))}') + // The handler must be one that exists: the previous `onExercise` was never defined and + // every tap threw (QA C13), so the row opens the exercise history sheet instead. + expect(source).toContain('{...tappable(() => exerciseHistorySheet(row.id))}') + expect(source).not.toContain('onExercise') }) it('uses the shared metric mode and row helpers rather than entryMode as a chart gate', () => { diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsx index 1ff1106..08273a1 100644 --- a/frontend/src/views/Workout.jsx +++ b/frontend/src/views/Workout.jsx @@ -582,13 +582,36 @@ function ActiveWorkout() { // The list opens at the exercise you are on, not at the top of the session (issue #224): you // switch to it mid-workout to look at what comes before and after. Only on the way in — once // the list is open, "current" moves because you tick rows in it, and a list that scrolls - // itself under your thumb is worse than one that stays put. + // itself under your thumb is worse than one that stays put. List ↔ Compact counts as a way + // in: the rows change height, so the same scroll offset lands somewhere else. + // + // The scroll waits for the next frame rather than running in the effect itself. App.jsx + // restores the route's remembered position in a frame it asked for during the same commit + // (a reload, a back navigation), and a sheet closing (⋯ → Layout → List) puts the page back + // where it was before the sheet opened, in an effect cleanup that runs before this one — + // both would win over a scroll made right here. A frame asked for now runs after theirs. const listRef = useRef(null) + const hdrRef = useRef(null) useEffect(() => { if (!listMode) return - const el = listRef.current?.querySelector('.wl-unit.cur') - if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ block: 'start' }) - }, [listMode]) + const schedule = callback => window.requestAnimationFrame + ? window.requestAnimationFrame(callback) + : window.setTimeout(callback, 0) + const cancel = frame => window.cancelAnimationFrame + ? window.cancelAnimationFrame(frame) + : window.clearTimeout(frame) + const frame = schedule(() => { + const list = listRef.current + const el = list?.querySelector('.wl-unit.cur') + if (!el || typeof el.scrollIntoView !== 'function') return + // The sticky header grows when the workout name wraps; the unit's scroll margin (index.css) + // clears whatever height it has right now, with a one-line height as the fallback. + const hdrH = hdrRef.current?.offsetHeight + if (hdrH) list.style.setProperty('--whdr-h', hdrH + 'px') + el.scrollIntoView({ block: 'start' }) + }) + return () => cancel(frame) + }, [workoutView]) const total = setUnitsTotal(A.entries) const done = setsDoneActive(A) @@ -943,7 +966,7 @@ function ActiveWorkout() { {/* In list mode the whole session scrolls under the header, so the header (name, clock, set counter, discard/finish, progress) stays pinned — the one thing you want in view while you are somewhere in the middle of a long stack. Cards mode never scrolls far. */} -
+
{A.name}
{A.backfill ? fmtDate(A.d, true) : } · {t('{0} sets', done + '/' + total)}
diff --git a/frontend/src/views/Workout.test.jsx b/frontend/src/views/Workout.test.jsx index c58ceee..e3b669d 100644 --- a/frontend/src/views/Workout.test.jsx +++ b/frontend/src/views/Workout.test.jsx @@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => { exConfigSheet: vi.fn(), toast: vi.fn(), scrollCalls: [], + headerHeight: 0, swapActiveWorkoutExercise: vi.fn(), menuSheet: vi.fn(), effortPickerSheet: vi.fn(), @@ -121,6 +122,10 @@ function installDom() { dom.Element.prototype.scrollIntoView = vi.fn(function (options) { mocks.scrollCalls.push({ node: this, options }) }) + // linkedom has no layout; the sticky workout header reports the height a test gives it. + Object.defineProperty(dom.HTMLElement.prototype, 'offsetHeight', { + configurable: true, get() { return this.classList.contains('whdr') ? mocks.headerHeight : 0 }, + }) globalThis.IS_REACT_ACT_ENVIRONMENT = true container = document.getElementById('root') root = createRoot(container) @@ -185,6 +190,11 @@ async function addExerciseThroughSheets(ex = { id: 'added-exercise' }, cfg = { m await act(async () => { configCall[2](cfg) }) } +// The list's scroll-to-current waits for the next frame (linkedom has no rAF, so a 0 ms timer). +async function flushFrame() { + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)) }) +} + async function rerenderAt(cur) { mocks.S.active.cur = cur await act(async () => { root.render(React.createElement(Workout)) }) @@ -195,6 +205,7 @@ beforeEach(() => { mocks.timer = null mocks.work = null mocks.scrollCalls.length = 0 + mocks.headerHeight = 0 }) afterEach(async () => { @@ -1014,11 +1025,39 @@ describe('workout list view', () => { it('opens at the current exercise instead of the top of the session (#224)', async () => { await mount([exercise('plain-bench', [true]), exercise('plain-row', [true]), exercise('plain-curl', [false])], 2, { workoutView: 'list' }) + // Not in the mount's own effect pass: App restores the route's scroll position in a frame + // of its own, so the list scrolls in the frame after it, or the restore would win. + expect(mocks.scrollCalls.length).toBe(0) + await flushFrame() expect(mocks.scrollCalls.length).toBe(1) expect(mocks.scrollCalls[0].node).toBe(units()[2]) expect(mocks.scrollCalls[0].node.classList.contains('cur')).toBe(true) }) + it('clears the sticky header at its measured height, not a one-line guess (QA C27)', async () => { + mocks.headerHeight = 143 // a routine name that wraps to three lines at 368 px + await mount([exercise('plain-bench', [true]), exercise('plain-row', [true]), exercise('plain-curl', [false])], 2, { workoutView: 'list' }) + await flushFrame() + expect(mocks.scrollCalls.length).toBe(1) + expect(container.querySelector('.workout-list').style.getPropertyValue('--whdr-h')).toBe('143px') + }) + + it('re-anchors on the current exercise when the layout changes between list and compact (QA C1)', async () => { + await mount([exercise('plain-bench', [true]), exercise('plain-row', [true]), exercise('plain-curl', [false])], 2, { workoutView: 'list' }) + await flushFrame() + mocks.scrollCalls.length = 0 + mocks.S.active.workoutView = 'compact' + await rerender() + await flushFrame() + expect(mocks.scrollCalls.length).toBe(1) + expect(mocks.scrollCalls[0].node.classList.contains('cur')).toBe(true) + // ...but not when "current" merely moves inside the open list (that was #224's rule). + mocks.scrollCalls.length = 0 + await rerenderAt(1) + await flushFrame() + expect(mocks.scrollCalls.length).toBe(0) + }) + it('stacks every exercise, labels each unit, and hides card navigation', async () => { await mount([exercise('plain-bench', [false, false]), exercise('plain-row', [false])], 0, { workoutView: 'list' })