Compare commits

...
6 Commits
Author SHA1 Message Date
Duarte Santos fc36476a5f Release v1.1.3: consolidate all work since v1.1.2
v1.1.2 is the last published release; v1.1.3 and v1.1.4 were tagged but
never released. Collapse those two plus the equipment filter and the rest
timer fix into a single v1.1.3 changelog section, grouped into 'Admin
dashboard' and 'Exercises & workout'. Set frontend/package.json to 1.1.3.

Covers #12, the admin dashboard (phases 1+2), #6 and #14.
2026-07-22 14:52:32 +02:00
Duarte Santos fbf125f6a2 Filter exercises by equipment (#6)
Adds an equipment filter row under the body-part chips, in both the
Exercises library and the exercise picker sheet.

The options are derived from the exercises already matching the current
body part and search, ordered most-common-first, so the row stays short
instead of listing all 28 equipment values (many with a single exercise)
and every combination on screen has results behind it. The row hides
itself when there is nothing to choose between.

Changing the body part clears the equipment filter; a search that
narrows the chosen equipment away drops it rather than showing an empty
list. All equipment terms were already localized — only the new 'Any
equipment' label needed adding across the 11 locale packs.

Closes #6
2026-07-22 14:44:27 +02:00
Duarte Santos 33317dac91 Fix rest timer freezing at 0:01 (#14)
The tick callback shadowed the imported i18n helper `t` with the timer
object, so the final tick threw a TypeError on t('Rest over — next set!')
before reaching stopRest(). The interval kept running and re-throwing, the
display stayed on the last value it wrote, and the pending server-side
'rest over' push was never cancelled.

Closes #14
2026-07-22 14:44:15 +02:00
Duarte Santos f3ba05aece Admin dashboard (phase 2): live 'training now' heartbeat + release v1.1.4
Backend: in-memory presence map + POST /api/activity heartbeat (authed);
each /api/admin/users row carries a fresh 'live' snapshot (routine,
exercise x/y, sets done/total, started-at) with a ~70s TTL. Disabling a
user clears their presence immediately.

Frontend: the workout screen pings /api/activity every 20s (signed-in
only) and sends a leave signal on unmount (fetch + sendBeacon). The
dashboard gains a 'Training now' section and live markers, auto-
refreshing every 15s.

Cuts the complete admin-dashboard feature (phases 1+2) as v1.1.4.
2026-07-22 02:06:19 +02:00
Duarte Santos 046217079c Admin dashboard (phase 1): users, disable, invite-gated signup
Adds an operator dashboard for self-hosters, gated on a passkey-
authenticated admin flag (ADMIN_UIDS env) and enforced server-side.

Backend:
- ADMIN_UIDS / INVITE_ONLY env (both off by default, OSS-friendly).
- Invite codes in db.json; /api/register gated when INVITE_ONLY, code
  burned on successful signup.
- disabled users are rejected by readSession — locked out everywhere.
- /api/admin/{users,user,user/disable,invites,invites/new,invites/revoke}
  behind an admin guard; /api/config exposes invite_only to the login UI.
- admin flag surfaced on /api/me, register/verify, login/verify.

Frontend:
- New /admin route + Settings link, shown only to admins: user list with
  workout counts and last-sync, disable/enable, invite generation, and a
  per-user workout-history drill-down.
- Registration sheet shows an invite-code field when the instance is
  invite-only.

Phase 2 (live 'training now' via a heartbeat) is separate.
2026-07-22 01:58:33 +02:00
Duarte Santos dabffdebc0 Minimize the exercise animation during a workout (#12)
Adds a persistent minimize/expand toggle to the workout animation so the
set rows are reachable without scrolling past a full-height GIF. A new
S.gifSize setting ('full' | 'mini') is flipped by the button, saved and
synced like other prefs, and applied across exercises and future
workouts. Tapping the animation still pauses/plays it.

Closes #12
2026-07-22 01:00:50 +02:00
28 changed files with 547 additions and 50 deletions

No files matched your search

+15
View File
@@ -19,6 +19,21 @@ RP_NAME=openGym
#
# (Point your proxy at the web container's WEB_PORT. See docs/SELF_HOSTING.md.)
# ── Admin dashboard & invite-only signup (optional) ────────────────────────
# Both off by default — a fresh instance has open signup and no admin.
#
# Make yourself an admin: register your own passkey profile first, find your
# user id in ./data/db.json ("users"[].id), then list it here (comma-separated
# for several admins). Admins get an "Admin dashboard" link in Settings to see
# users, disable accounts, generate invite codes and view workout history.
#
# ADMIN_UIDS=youruserid,anotheradmin
#
# Require an invite code to create new profiles (existing accounts keep working;
# generate the codes from the admin dashboard):
#
# INVITE_ONLY=1
# ── Notifications (optional) ───────────────────────────────────────────────
# Push works out of the box — nothing to set. VAPID keys are generated on first
# run and saved to ./data/vapid.json. Each user's browser reports its own
+37
View File
@@ -1,5 +1,42 @@
# Changelog
## v1.1.3 — 2026-07-22
Admin dashboard for self-hosters (opt-in — off by default), equipment filtering, and
workout-screen fixes.
### Admin dashboard
- 🛠️ **Admin dashboard** (Settings → Admin dashboard) for whoever runs the instance: a users
overview with workout counts and last-active times, plus a per-user drill-down into their full
workout history and body-weight log.
- 🟢 **Live "training now"** — see who's mid-workout in real time, with their current exercise and
set progress, updated by a lightweight heartbeat while a workout is on screen.
- 🚫 **Disable / enable accounts** — a disabled account is signed out and locked out everywhere
until you re-enable it.
- 🔑 **Invite-only signup** (optional) — require an invite code to create a profile; generate and
revoke codes from the dashboard. Existing accounts are unaffected.
- ⚙️ Configured via environment: `ADMIN_UIDS` (comma-separated user ids who are admins) and
`INVITE_ONLY=1`; both default off, so a fresh instance stays open with no admin. See
`.env.example`. Admin access is gated by your passkey and enforced server-side.
### Exercises & workout
- 🏋️ **Filter exercises by equipment** (#6). A second filter row under the body parts lets you
narrow the list to what you actually have — body weight, dumbbell, barbell, cable, band, and so
on — in both the Exercises library and the exercise picker. The options adapt to what you've
already selected and are ordered by how many exercises use them, so every combination on screen
has results behind it and the row stays short. Building a bodyweight-only plan is now two taps
per body part.
- 🔎 **Minimize the exercise animation during a workout** (#12). A ⤡ Minimize / ⤢ Expand button
on the animation shrinks it to a thin strip so the set rows sit right under your thumb — no more
scrolling past a big GIF to tick off a set. Your choice is remembered and applied to every
exercise and future workout until you change it, so you set it once. Tapping the animation still
pauses/plays it as before.
- ⏱️ **Fixed: the rest timer froze at 0:01** (#14) instead of counting down to the end. It also
meant the timer could only be cleared with Skip, and a redundant "rest over" push notification
could still fire.
## v1.1.2 — 2026-07-22
Custom exercises, full localization, and input fixes.
+146 -6
View File
@@ -15,6 +15,10 @@ const DATA = process.env.DATA_DIR || '/data';
const RP_ID = process.env.RP_ID || 'localhost';
const ORIGIN = process.env.ORIGIN || 'http://localhost:8080';
const RP_NAME = process.env.RP_NAME || 'openGym';
// Admin dashboard (issue): admins are matched by uid; INVITE_ONLY gates new signups behind a
// code the admin generates. Both default off so a fresh self-hosted instance stays open.
const ADMIN_UIDS = (process.env.ADMIN_UIDS || '').split(',').map(s => s.trim()).filter(Boolean);
const INVITE_ONLY = /^(1|true|yes|on)$/i.test(process.env.INVITE_ONLY || '');
const SESSION_DAYS = 365;
const MAX_BODY = 5 * 1024 * 1024;
// Secure cookies require HTTPS; over plain http://localhost the flag would drop the cookie
@@ -28,9 +32,11 @@ if (!fs.existsSync(secretFile)) fs.writeFileSync(secretFile, crypto.randomBytes(
const SECRET = fs.readFileSync(secretFile, 'utf8').trim();
const dbFile = path.join(DATA, 'db.json');
let db = { users: [], creds: [], subs: [] };
let db = { users: [], creds: [], subs: [], invites: [] };
try { db = JSON.parse(fs.readFileSync(dbFile, 'utf8')); } catch {}
db.subs = db.subs || [];
db.invites = db.invites || [];
const isAdmin = user => !!user && (user.admin === true || ADMIN_UIDS.includes(user.id));
function saveDb() { atomicWrite(dbFile, JSON.stringify(db, null, 2)); }
function atomicWrite(file, content) {
const tmp = file + '.tmp';
@@ -163,7 +169,16 @@ function readSession(req) {
if (!payload) return null;
const [uid, exp] = payload.split(':');
if (!uid || +exp < Date.now()) return null;
return db.users.find(u => u.id === uid) || null;
const user = db.users.find(u => u.id === uid) || null;
if (user && user.disabled) return null; // disabled accounts are locked out everywhere
return user;
}
// Guard for /api/admin/* — resolves the caller and 401/403s if they aren't an admin.
function requireAdmin(req, res) {
const user = readSession(req);
if (!user) { json(res, 401, { error: 'not signed in' }); return null; }
if (!isAdmin(user)) { json(res, 403, { error: 'forbidden' }); return null; }
return user;
}
function sessionCookie(uid) {
return `gymsid=${makeSession(uid)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
@@ -208,20 +223,39 @@ function readBody(req) {
}
const b64uToBuf = s => Buffer.from(s, 'base64url');
/* ---------- live presence (in-memory) ---------- */
// Clients heartbeat /api/activity while a workout is on screen; the admin dashboard reads who's
// live. Purely ephemeral — never persisted. Expires shortly after the last ping.
const presence = new Map(); // uid -> { name, exIdx, exTotal, setsDone, setsTotal, startedAt, updatedAt }
const PRESENCE_TTL = 70000; // ~3.5× the 20s client heartbeat
function livePresence(uid) {
const p = presence.get(uid);
if (!p) return null;
if (Date.now() - p.updatedAt > PRESENCE_TTL) { presence.delete(uid); return null; }
return p;
}
setInterval(() => { for (const [k, v] of presence) if (Date.now() - v.updatedAt > PRESENCE_TTL) presence.delete(k); }, 30000).unref();
/* ---------- routes ---------- */
const routes = {
'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }),
// Public config the login screen needs before anyone is signed in.
'GET /api/config': async (req, res) => json(res, 200, { invite_only: INVITE_ONLY }),
'GET /api/me': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
json(res, 200, { user: { id: user.id, name: user.name } });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } });
},
'POST /api/register/options': async (req, res) => {
const body = await readBody(req);
const name = String(body.name || '').trim().slice(0, 40);
if (!name) return json(res, 400, { error: 'name required' });
const code = String(body.code || '').trim().toUpperCase();
if (INVITE_ONLY && !db.invites.some(i => i.code === code && !i.usedBy && !i.revoked))
return json(res, 403, { error: 'a valid invite code is required' });
const uid = crypto.randomBytes(12).toString('base64url');
const options = await generateRegistrationOptions({
rpName: RP_NAME, rpID: RP_ID,
@@ -230,7 +264,7 @@ const routes = {
authenticatorSelection: { residentKey: 'required', userVerification: 'preferred' },
excludeCredentials: []
});
const cid = putChallenge({ challenge: options.challenge, name, uid });
const cid = putChallenge({ challenge: options.challenge, name, uid, code });
json(res, 200, { cid, options });
},
@@ -251,7 +285,14 @@ const routes = {
if (!verification.verified) return json(res, 400, { error: 'not verified' });
const { credential } = verification.registrationInfo;
if (db.creds.find(x => x.id === credential.id)) return json(res, 409, { error: 'credential already registered' });
// Re-check the invite at the last moment (it may have been used/revoked since options), then burn it.
let invite = null;
if (INVITE_ONLY) {
invite = db.invites.find(i => i.code === c.code && !i.usedBy && !i.revoked);
if (!invite) return json(res, 403, { error: 'invite code is no longer valid — ask for a new one' });
}
const user = { id: c.uid, name: c.name, created: new Date().toISOString() };
if (invite) { user.invitedBy = invite.code; invite.usedBy = user.id; invite.usedAt = user.created; }
db.users.push(user);
db.creds.push({
id: credential.id, userId: user.id,
@@ -260,7 +301,7 @@ const routes = {
transports: body.credential?.response?.transports || []
});
saveDb();
json(res, 200, { user: { id: user.id, name: user.name } }, { 'Set-Cookie': sessionCookie(user.id) });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
},
'POST /api/login/options': async (req, res) => {
@@ -298,7 +339,8 @@ const routes = {
saveDb();
const user = db.users.find(u => u.id === cred.userId);
if (!user) return json(res, 500, { error: 'user missing' });
json(res, 200, { user: { id: user.id, name: user.name } }, { 'Set-Cookie': sessionCookie(user.id) });
if (user.disabled) return json(res, 403, { error: 'this account has been disabled' });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
},
'POST /api/logout': async (req, res) => json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie }),
@@ -367,6 +409,104 @@ const routes = {
if (!user) return json(res, 401, { error: 'not signed in' });
cancelRestTimer(user.id);
json(res, 200, { ok: true });
},
// Live-workout heartbeat: client pings while a workout is on screen; { active:false } drops it.
'POST /api/activity': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const body = await readBody(req);
if (body.active) {
presence.set(user.id, {
name: String(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(),
updatedAt: Date.now()
});
} else presence.delete(user.id);
json(res, 200, { ok: true });
},
/* ---------- admin dashboard ---------- */
// One row per user, cheap enough for a personal instance (reads each state file once).
'GET /api/admin/users': async (req, res) => {
if (!requireAdmin(req, res)) return;
const users = db.users.map(u => {
const S = readState(u.id) || {};
const workouts = S.workouts || [];
const last = workouts[workouts.length - 1];
return {
id: u.id, name: u.name, created: u.created || null,
disabled: !!u.disabled, admin: isAdmin(u), invitedBy: u.invitedBy || null,
workouts: workouts.length,
lastWorkout: last ? last.d : null,
lastSync: S._ts || null,
hasPush: db.subs.some(s => s.userId === u.id),
live: livePresence(u.id)
};
});
json(res, 200, { users, invite_only: INVITE_ONLY, now: Date.now() });
},
// Drill-down: full workout history + body-weight log for one user.
'GET /api/admin/user': async (req, res) => {
if (!requireAdmin(req, res)) return;
const id = new URL(req.url, 'http://x').searchParams.get('id');
const u = db.users.find(x => x.id === id);
if (!u) return json(res, 404, { error: 'no such user' });
const S = readState(u.id) || {};
json(res, 200, {
user: { id: u.id, name: u.name, created: u.created || null, disabled: !!u.disabled, admin: isAdmin(u), invitedBy: u.invitedBy || null },
unit: S.unit || 'kg',
lastSync: S._ts || null,
routines: (S.routines || []).map(r => ({ id: r.id, name: r.name, emoji: r.emoji, count: (r.ex || []).length })),
bodyweight: S.bodyweight || [],
workouts: (S.workouts || []).slice().reverse() // newest first for display
});
},
'POST /api/admin/user/disable': async (req, res) => {
if (!requireAdmin(req, res)) return;
const body = await readBody(req);
const u = db.users.find(x => x.id === body.id);
if (!u) return json(res, 404, { error: 'no such user' });
if (isAdmin(u)) return json(res, 400, { error: 'cannot disable an admin' });
u.disabled = !!body.disabled;
if (u.disabled) presence.delete(u.id); // drop them off "training now" at once
saveDb();
json(res, 200, { ok: true, id: u.id, disabled: u.disabled });
},
'GET /api/admin/invites': async (req, res) => {
if (!requireAdmin(req, res)) return;
// resolve usedBy uid → name for display
const invites = db.invites.map(i => ({
...i, usedByName: i.usedBy ? (db.users.find(u => u.id === i.usedBy) || {}).name || null : null
}));
json(res, 200, { invites, invite_only: INVITE_ONLY });
},
'POST /api/admin/invites/new': async (req, res) => {
const admin = requireAdmin(req, res); if (!admin) return;
const body = await readBody(req);
let code;
do { code = crypto.randomBytes(4).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() };
db.invites.push(invite);
saveDb();
json(res, 200, { invite });
},
'POST /api/admin/invites/revoke': async (req, res) => {
if (!requireAdmin(req, res)) return;
const body = await readBody(req);
const inv = db.invites.find(i => i.code === String(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);
saveDb();
json(res, 200, { ok: true });
}
};
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "opengym-frontend",
"private": true,
"version": "1.1.2",
"version": "1.1.3",
"type": "module",
"scripts": {
"dev": "vite",
+2
View File
@@ -18,6 +18,7 @@ import Stats from './views/Stats.jsx'
import History from './views/History.jsx'
import Library from './views/Library.jsx'
import Settings from './views/Settings.jsx'
import Admin from './views/Admin.jsx'
function applyPrefs(theme, accent) {
const de = document.documentElement
@@ -56,6 +57,7 @@ function Shell() {
<Route path="/history" element={<History />} />
<Route path="/library" element={<Library />} />
<Route path="/settings" element={<Settings />} />
<Route path="/admin" element={user?.admin ? <Admin /> : <Navigate to="/home" replace />} />
<Route path="*" element={<Navigate to="/home" replace />} />
</Routes>
)}
+12 -3
View File
@@ -1,16 +1,25 @@
import { useState } from 'react'
import { imgSrc, gifSrc } from '../lib/exercises.js'
import { useStore } from '../store/useStore.js'
import { t } from '../lib/i18n.js'
// Big autoplaying animation; tap toggles to the still frame. `compact` shrinks it (superset cards).
// Custom exercises have no media — the animation stays blank by design (issue #11).
export default function Media({ ex, id, compact }) {
// `minimizable` (workout view) adds a persistent minimize/expand control so the animation stops
// eating the screen; the chosen size is saved to settings and carries across exercises and
// future workouts (issue #12).
export default function Media({ ex, id, compact, minimizable }) {
const [playing, setPlaying] = useState(true)
const gifSize = useStore(s => s.S.gifSize)
const update = useStore(s => s.update)
if (!ex.gif) return null
const mini = minimizable && gifSize === 'mini'
const toggleSize = e => { e.stopPropagation(); update(s => { s.gifSize = mini ? 'full' : 'mini' }) }
return (
<div className={'exmedia' + (compact ? ' compact' : '')} id={id} onClick={() => setPlaying(p => !p)}>
<div className={'exmedia' + (compact ? ' compact' : '') + (mini ? ' mini' : '')} id={id} onClick={() => setPlaying(p => !p)}>
<img decoding="async" src={playing ? gifSrc(ex) : imgSrc(ex)} alt={ex.n} />
<span className="gifhint">{playing ? '⏸ ' + t('tap to pause') : '▶ ' + t('tap to play')}</span>
{minimizable && <button className="giftoggle" onClick={toggleSize}>{mini ? '⤢ ' + t('Expand') : '⤡ ' + t('Minimize')}</button>}
{!mini && <span className="gifhint">{playing ? '⏸ ' + t('tap to pause') : '▶ ' + t('tap to play')}</span>}
</div>
)
}
+4
View File
@@ -162,6 +162,8 @@ textarea.input{min-height:88px;resize:vertical;line-height:1.45}
.exmedia img{width:100%;height:340px;object-fit:contain;display:block}
.exmedia .gifhint{position:absolute;right:10px;bottom:10px;background:rgba(0,0,0,.62);color:#fff;
border-radius:99px;padding:4px 11px;font-size:.72rem;font-weight:600}
.exmedia .giftoggle{position:absolute;left:10px;bottom:10px;background:rgba(0,0,0,.62);color:#fff;
border:none;border-radius:99px;padding:5px 12px;font-size:.72rem;font-weight:600;cursor:pointer}
.sethead{display:flex;align-items:center;gap:9px;padding-bottom:2px;
font-size:.66rem;color:var(--dim);font-weight:700;text-transform:uppercase;letter-spacing:.05em}
.sethead .n-sp{width:26px;flex:none}
@@ -333,6 +335,8 @@ h4.sec{font-size:.8rem;text-transform:uppercase;letter-spacing:.08em;color:var(-
.ss-ex{position:relative}
.ss-amp{text-align:center;font-size:1.3rem;font-weight:800;color:var(--acc);margin:14px 0 8px}
.exmedia.compact img{height:190px}
/* minimized workout animation — small enough to keep the set rows in view (issue #12) */
.exmedia.mini img{height:88px}
/* ---------- home: today's session row under the week strip ---------- */
.today-row{display:flex;align-items:center;justify-content:space-between;gap:10px;
+2 -2
View File
@@ -45,8 +45,8 @@ function credToJSON(cred) {
}
return out
}
export async function passkeyRegister(name) {
const { cid, options } = await api('/api/register/options', { method: 'POST', body: JSON.stringify({ name }) })
export async function passkeyRegister(name, code) {
const { cid, options } = await api('/api/register/options', { method: 'POST', body: JSON.stringify({ name, code: code || '' }) })
const cred = await navigator.credentials.create({ publicKey: toCreationOptions(options) })
const res = await api('/api/register/verify', { method: 'POST', body: JSON.stringify({ cid, credential: credToJSON(cred) }) })
return res.user
+9
View File
@@ -5,6 +5,15 @@ export const EXIDX = {}
EXDB.forEach(e => { EXIDX[e.id] = e })
export const BODYPARTS = [...new Set(EXDB.map(e => e.bp))].sort()
// Equipment options present in a given list of exercises, most common first (issue #6).
// Deriving them from the *already filtered* list keeps the chip row short and means
// every body-part × equipment combination on screen has results behind it.
export function equipmentOf(list) {
const c = {}
list.forEach(e => { if (e.eq) c[e.eq] = (c[e.eq] || 0) + 1 })
return Object.keys(c).sort((a, b) => c[b] - c[a] || (a < b ? -1 : 1))
}
// Custom (user-created) exercises live in synced state S.customEx (issue #11) and are
// merged into the id index here so every EXIDX[id] lookup keeps working unchanged.
let customIds = []
+8 -1
View File
@@ -302,6 +302,7 @@ export default {
'lower legs': 'Unterschenkel', 'neck': 'Nacken', 'shoulders': 'Schultern',
'upper arms': 'Oberarme', 'upper legs': 'Oberschenkel', 'waist': 'Rumpf',
// --- data terms: equipment ---
'Any equipment': 'Alle Geräte',
'assisted': 'assistiert', 'band': 'Band', 'barbell': 'Langhantel', 'body weight': 'Körpergewicht',
'bosu ball': 'Bosu-Ball', 'cable': 'Kabelzug', 'dumbbell': 'Kurzhantel',
'elliptical machine': 'Crosstrainer', 'ez barbell': 'SZ-Stange', 'hammer': 'Hammer',
@@ -350,5 +351,11 @@ export default {
'Description (optional) — setup, cues, anything you want to remember': 'Beschreibung (optional) — Aufbau, Hinweise, was du dir merken willst',
'Delete exercise': 'Übung löschen',
'Edit or delete this exercise': 'Übung bearbeiten oder löschen',
'Remove from routine': 'Aus Routine entfernen'
'Remove from routine': 'Aus Routine entfernen',
'Minimize': 'Verkleinern',
'Expand': 'Vergrössern',
'Invite code': 'Einladungscode',
'This app is invite-only — enter the code you were given.': 'Diese App ist nur mit Einladung — gib den Code ein, den du erhalten hast.',
'An invite code is required': 'Ein Einladungscode ist erforderlich',
'Admin dashboard': 'Admin-Dashboard'
}
+8 -1
View File
@@ -285,6 +285,7 @@ export default {
'back': 'espalda', 'cardio': 'cardio', 'chest': 'pecho', 'lower arms': 'antebrazos',
'lower legs': 'pantorrillas', 'neck': 'cuello', 'shoulders': 'hombros',
'upper arms': 'brazos', 'upper legs': 'piernas', 'waist': 'abdomen',
'Any equipment': 'Cualquier equipo',
'assisted': 'asistido', 'band': 'banda', 'barbell': 'barra', 'body weight': 'peso corporal',
'bosu ball': 'bosu', 'cable': 'polea', 'dumbbell': 'mancuerna',
'elliptical machine': 'elíptica', 'ez barbell': 'barra EZ', 'hammer': 'martillo',
@@ -332,5 +333,11 @@ export default {
'Description (optional) — setup, cues, anything you want to remember': 'Descripción (opcional) — preparación, consejos, lo que quieras recordar',
'Delete exercise': 'Eliminar ejercicio',
'Edit or delete this exercise': 'Editar o eliminar este ejercicio',
'Remove from routine': 'Quitar de la rutina'
'Remove from routine': 'Quitar de la rutina',
'Minimize': 'Minimizar',
'Expand': 'Ampliar',
'Invite code': 'Código de invitación',
'This app is invite-only — enter the code you were given.': 'Esta app es solo por invitación: introduce el código que te dieron.',
'An invite code is required': 'Se requiere un código de invitación',
'Admin dashboard': 'Panel de administración'
}
+8 -1
View File
@@ -285,6 +285,7 @@ export default {
'back': 'dos', 'cardio': 'cardio', 'chest': 'pectoraux', 'lower arms': 'avant-bras',
'lower legs': 'mollets', 'neck': 'cou', 'shoulders': 'épaules',
'upper arms': 'bras', 'upper legs': 'cuisses', 'waist': 'abdos',
'Any equipment': 'Tout équipement',
'assisted': 'assisté', 'band': 'élastique', 'barbell': 'barre', 'body weight': 'poids du corps',
'bosu ball': 'bosu', 'cable': 'poulie', 'dumbbell': 'haltère',
'elliptical machine': 'vélo elliptique', 'ez barbell': 'barre EZ', 'hammer': 'marteau',
@@ -332,5 +333,11 @@ export default {
'Description (optional) — setup, cues, anything you want to remember': 'Description (facultatif) — installation, conseils, ce que vous voulez retenir',
'Delete exercise': 'Supprimer l’exercice',
'Edit or delete this exercise': 'Modifier ou supprimer cet exercice',
'Remove from routine': 'Retirer de la routine'
'Remove from routine': 'Retirer de la routine',
'Minimize': 'Réduire',
'Expand': 'Agrandir',
'Invite code': 'Code d’invitation',
'This app is invite-only — enter the code you were given.': 'Cette appli est sur invitation — saisissez le code qu’on vous a donné.',
'An invite code is required': 'Un code d’invitation est requis',
'Admin dashboard': 'Tableau d’administration'
}
+8 -1
View File
@@ -285,6 +285,7 @@ export default {
'back': 'पीठ', 'cardio': 'कार्डियो', 'chest': 'छाती', 'lower arms': 'अग्रबाहु',
'lower legs': 'पिंडलियाँ', 'neck': 'गर्दन', 'shoulders': 'कंधे',
'upper arms': 'बाजू', 'upper legs': 'जाँघें', 'waist': 'पेट',
'Any equipment': 'कोई भी उपकरण',
'assisted': 'सहायता प्राप्त', 'band': 'बैंड', 'barbell': 'बारबेल', 'body weight': 'शरीर का वज़न',
'bosu ball': 'बोसु बॉल', 'cable': 'केबल', 'dumbbell': 'डम्बल',
'elliptical machine': 'एलिप्टिकल मशीन', 'ez barbell': 'EZ बारबेल', 'hammer': 'हैमर',
@@ -332,5 +333,11 @@ export default {
'Description (optional) — setup, cues, anything you want to remember': 'विवरण (वैकल्पिक) — सेटअप, संकेत, जो कुछ भी याद रखना चाहें',
'Delete exercise': 'एक्सरसाइज़ हटाएं',
'Edit or delete this exercise': 'इस एक्सरसाइज़ को संपादित या हटाएं',
'Remove from routine': 'रूटीन से हटाएं'
'Remove from routine': 'रूटीन से हटाएं',
'Minimize': 'छोटा करें',
'Expand': 'बड़ा करें',
'Invite code': 'इनवाइट कोड',
'This app is invite-only — enter the code you were given.': 'यह ऐप केवल इनवाइट से है — आपको दिया गया कोड डालें।',
'An invite code is required': 'एक इनवाइट कोड आवश्यक है',
'Admin dashboard': 'एडमिन डैशबोर्ड'
}
+8 -1
View File
@@ -285,6 +285,7 @@ export default {
'back': 'schiena', 'cardio': 'cardio', 'chest': 'petto', 'lower arms': 'avambracci',
'lower legs': 'polpacci', 'neck': 'collo', 'shoulders': 'spalle',
'upper arms': 'braccia', 'upper legs': 'gambe', 'waist': 'addome',
'Any equipment': 'Qualsiasi attrezzo',
'assisted': 'assistito', 'band': 'elastico', 'barbell': 'bilanciere', 'body weight': 'corpo libero',
'bosu ball': 'bosu', 'cable': 'cavo', 'dumbbell': 'manubrio',
'elliptical machine': 'ellittica', 'ez barbell': 'bilanciere EZ', 'hammer': 'martello',
@@ -332,5 +333,11 @@ export default {
'Description (optional) — setup, cues, anything you want to remember': 'Descrizione (facoltativa) — setup, spunti, quello che vuoi ricordare',
'Delete exercise': 'Elimina esercizio',
'Edit or delete this exercise': 'Modifica o elimina questo esercizio',
'Remove from routine': 'Rimuovi dalla routine'
'Remove from routine': 'Rimuovi dalla routine',
'Minimize': 'Riduci',
'Expand': 'Ingrandisci',
'Invite code': 'Codice di invito',
'This app is invite-only — enter the code you were given.': 'Questa app è solo su invito: inserisci il codice che hai ricevuto.',
'An invite code is required': 'È richiesto un codice di invito',
'Admin dashboard': 'Pannello di amministrazione'
}
+8 -1
View File
@@ -285,6 +285,7 @@ export default {
'back': '등', 'cardio': '유산소', 'chest': '가슴', 'lower arms': '전완',
'lower legs': '종아리', 'neck': '목', 'shoulders': '어깨',
'upper arms': '팔', 'upper legs': '허벅지', 'waist': '복부',
'Any equipment': '모든 장비',
'assisted': '보조', 'band': '밴드', 'barbell': '바벨', 'body weight': '맨몸',
'bosu ball': '보수볼', 'cable': '케이블', 'dumbbell': '덤벨',
'elliptical machine': '일립티컬', 'ez barbell': 'EZ바', 'hammer': '해머',
@@ -332,5 +333,11 @@ export default {
'Description (optional) — setup, cues, anything you want to remember': '설명 (선택) — 세팅, 큐, 기억하고 싶은 모든 것',
'Delete exercise': '운동 삭제',
'Edit or delete this exercise': '이 운동 편집 또는 삭제',
'Remove from routine': '루틴에서 제거'
'Remove from routine': '루틴에서 제거',
'Minimize': '축소',
'Expand': '확대',
'Invite code': '초대 코드',
'This app is invite-only — enter the code you were given.': '이 앱은 초대 전용입니다 — 받은 코드를 입력하세요.',
'An invite code is required': '초대 코드가 필요합니다',
'Admin dashboard': '관리자 대시보드'
}
+8 -1
View File
@@ -285,6 +285,7 @@ export default {
'back': 'plecy', 'cardio': 'cardio', 'chest': 'klatka', 'lower arms': 'przedramiona',
'lower legs': 'łydki', 'neck': 'kark', 'shoulders': 'barki',
'upper arms': 'ramiona', 'upper legs': 'uda', 'waist': 'brzuch',
'Any equipment': 'Dowolny sprzęt',
'assisted': 'z asystą', 'band': 'guma', 'barbell': 'sztanga', 'body weight': 'masa ciała',
'bosu ball': 'bosu', 'cable': 'wyciąg', 'dumbbell': 'hantla',
'elliptical machine': 'orbitrek', 'ez barbell': 'sztanga łamana', 'hammer': 'młot',
@@ -332,5 +333,11 @@ export default {
'Description (optional) — setup, cues, anything you want to remember': 'Opis (opcjonalnie) — ustawienie, wskazówki, co chcesz zapamiętać',
'Delete exercise': 'Usuń ćwiczenie',
'Edit or delete this exercise': 'Edytuj lub usuń to ćwiczenie',
'Remove from routine': 'Usuń z planu'
'Remove from routine': 'Usuń z planu',
'Minimize': 'Zmniejsz',
'Expand': 'Powiększ',
'Invite code': 'Kod zaproszenia',
'This app is invite-only — enter the code you were given.': 'Ta aplikacja jest tylko na zaproszenie — wpisz otrzymany kod.',
'An invite code is required': 'Wymagany jest kod zaproszenia',
'Admin dashboard': 'Panel administratora'
}
+8 -1
View File
@@ -285,6 +285,7 @@ export default {
'back': 'costas', 'cardio': 'cardio', 'chest': 'peito', 'lower arms': 'antebraços',
'lower legs': 'gémeos', 'neck': 'pescoço', 'shoulders': 'ombros',
'upper arms': 'braços', 'upper legs': 'pernas', 'waist': 'abdómen',
'Any equipment': 'Qualquer equipamento',
'assisted': 'assistido', 'band': 'banda', 'barbell': 'barra', 'body weight': 'peso corporal',
'bosu ball': 'bosu', 'cable': 'cabo', 'dumbbell': 'haltere',
'elliptical machine': 'elíptica', 'ez barbell': 'barra EZ', 'hammer': 'martelo',
@@ -332,5 +333,11 @@ export default {
'Description (optional) — setup, cues, anything you want to remember': 'Descrição (opcional) — preparação, dicas, o que quiseres lembrar',
'Delete exercise': 'Eliminar exercício',
'Edit or delete this exercise': 'Editar ou eliminar este exercício',
'Remove from routine': 'Remover da rotina'
'Remove from routine': 'Remover da rotina',
'Minimize': 'Minimizar',
'Expand': 'Ampliar',
'Invite code': 'Código de convite',
'This app is invite-only — enter the code you were given.': 'Esta app é só por convite — introduz o código que recebeste.',
'An invite code is required': 'É necessário um código de convite',
'Admin dashboard': 'Painel de administração'
}
+8 -1
View File
@@ -285,6 +285,7 @@ export default {
'back': 'спина', 'cardio': 'кардио', 'chest': 'грудь', 'lower arms': 'предплечья',
'lower legs': 'голени', 'neck': 'шея', 'shoulders': 'плечи',
'upper arms': 'руки', 'upper legs': 'бёдра', 'waist': 'пресс',
'Any equipment': 'Любой инвентарь',
'assisted': 'с поддержкой', 'band': 'лента', 'barbell': 'штанга', 'body weight': 'свой вес',
'bosu ball': 'босу', 'cable': 'блок', 'dumbbell': 'гантель',
'elliptical machine': 'эллипсоид', 'ez barbell': 'EZ-гриф', 'hammer': 'молот',
@@ -332,5 +333,11 @@ export default {
'Description (optional) — setup, cues, anything you want to remember': 'Описание (необязательно) — настройка, подсказки, всё, что хотите запомнить',
'Delete exercise': 'Удалить упражнение',
'Edit or delete this exercise': 'Изменить или удалить это упражнение',
'Remove from routine': 'Убрать из программы'
'Remove from routine': 'Убрать из программы',
'Minimize': 'Свернуть',
'Expand': 'Развернуть',
'Invite code': 'Код приглашения',
'This app is invite-only — enter the code you were given.': 'Приложение только по приглашению — введите выданный вам код.',
'An invite code is required': 'Требуется код приглашения',
'Admin dashboard': 'Панель администратора'
}
+8 -1
View File
@@ -285,6 +285,7 @@ export default {
'back': 'sırt', 'cardio': 'kardiyo', 'chest': 'göğüs', 'lower arms': 'ön kollar',
'lower legs': 'baldırlar', 'neck': 'boyun', 'shoulders': 'omuzlar',
'upper arms': 'üst kollar', 'upper legs': 'bacaklar', 'waist': 'karın',
'Any equipment': 'Tüm ekipmanlar',
'assisted': 'destekli', 'band': 'bant', 'barbell': 'halter', 'body weight': 'vücut ağırlığı',
'bosu ball': 'bosu topu', 'cable': 'kablo', 'dumbbell': 'dambıl',
'elliptical machine': 'eliptik bisiklet', 'ez barbell': 'EZ bar', 'hammer': 'çekiç',
@@ -332,5 +333,11 @@ export default {
'Description (optional) — setup, cues, anything you want to remember': 'Açıklama (isteğe bağlı) — kurulum, ipuçları, hatırlamak istediklerin',
'Delete exercise': 'Egzersizi sil',
'Edit or delete this exercise': 'Bu egzersizi düzenle veya sil',
'Remove from routine': 'Rutinden çıkar'
'Remove from routine': 'Rutinden çıkar',
'Minimize': 'Küçült',
'Expand': 'Büyüt',
'Invite code': 'Davet kodu',
'This app is invite-only — enter the code you were given.': 'Bu uygulama yalnızca davetle — sana verilen kodu gir.',
'An invite code is required': 'Bir davet kodu gerekli',
'Admin dashboard': 'Yönetici paneli'
}
+8 -1
View File
@@ -285,6 +285,7 @@ export default {
'back': '背部', 'cardio': '有氧', 'chest': '胸部', 'lower arms': '前臂',
'lower legs': '小腿', 'neck': '颈部', 'shoulders': '肩部',
'upper arms': '上臂', 'upper legs': '大腿', 'waist': '腰腹',
'Any equipment': '所有器械',
'assisted': '辅助', 'band': '弹力带', 'barbell': '杠铃', 'body weight': '自重',
'bosu ball': '波速球', 'cable': '绳索', 'dumbbell': '哑铃',
'elliptical machine': '椭圆机', 'ez barbell': '曲杆杠铃', 'hammer': '锤',
@@ -332,5 +333,11 @@ export default {
'Description (optional) — setup, cues, anything you want to remember': '描述(可选)——设置、要点,任何你想记住的内容',
'Delete exercise': '删除动作',
'Edit or delete this exercise': '编辑或删除此动作',
'Remove from routine': '从计划中移除'
'Remove from routine': '从计划中移除',
'Minimize': '缩小',
'Expand': '放大',
'Invite code': '邀请码',
'This app is invite-only — enter the code you were given.': '此应用仅限邀请——请输入你收到的邀请码。',
'An invite code is required': '需要邀请码',
'Admin dashboard': '管理后台'
}
+16 -7
View File
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react'
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, allExercises } from './lib/exercises.js'
import { EXDB, EXIDX, BODYPARTS, isCardio, allExercises, equipmentOf } from './lib/exercises.js'
import { fmtDate, fmtNum, fmtVol, fmtDur, todayISO, uid, DAYN, MONTHS_LONG, ACCENTS } from './lib/format.js'
import { lastEntryFor, bestWeightFor, buildSets, effectiveRoutineId, workoutVolume, setsDone, setsDoneActive, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg } from './lib/history.js'
import { beep, vibrate } from './lib/sound.js'
@@ -280,23 +280,32 @@ function ExercisePicker({ onPick, close }) {
const usage = usageMap(st)
const [q, setQ] = useState('')
const [bp, setBp] = useState('') // '' = all, '★' = chosen, else a body part
const [eq, setEq] = useState('') // '' = any equipment
const [shown, setShown] = useState(50)
const ql = q.toLowerCase().trim()
const all = allExercises(st)
let f = all.filter(e =>
let base = all.filter(e =>
(bp === '★' ? usage[e.id] : (!bp || e.bp === bp)) &&
(!ql || e.n.toLowerCase().includes(ql) || e.tg.includes(ql) || e.eq.includes(ql) || (e.desc || '').toLowerCase().includes(ql)))
if (bp === '★') f = [...f].sort((a, b) => (usage[b.id] - usage[a.id]) || (a.n < b.n ? -1 : 1))
if (bp === '★') base = [...base].sort((a, b) => (usage[b.id] - usage[a.id]) || (a.n < b.n ? -1 : 1))
const eqOpts = equipmentOf(base)
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.
const eqOn = eqOpts.includes(eq) ? eq : ''
const f = eqOn ? base.filter(e => e.eq === eqOn) : base
const chosenCount = Object.keys(usage).length
return <>
<h3>{t('Add exercise')}</h3>
<div className="search"><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
<input className="input" placeholder={t('Search {0} exercises…', all.length)} value={q} onChange={e => { setQ(e.target.value); setShown(50) }} /></div>
<div className="chips" style={{ margin: '10px 0' }}>
{chosenCount > 0 && <button className={'chip' + (bp === '★' ? ' on' : '')} onClick={() => { setBp('★'); setShown(50) }}>⭐ {t('Chosen')} ({chosenCount})</button>}
<button className={'chip' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setShown(50) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setShown(50) }}>{t(b)}</button>)}
<div className="chips" style={{ margin: eqOpts.length > 1 ? '10px 0 6px' : '10px 0' }}>
{chosenCount > 0 && <button className={'chip' + (bp === '★' ? ' on' : '')} onClick={() => { setBp('★'); setEq(''); setShown(50) }}>⭐ {t('Chosen')} ({chosenCount})</button>}
<button className={'chip' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setEq(''); setShown(50) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setEq(''); setShown(50) }}>{t(b)}</button>)}
</div>
{eqOpts.length > 1 && <div className="chips" style={{ marginBottom: 10 }}>
<button className={'chip' + (!eqOn ? ' on' : '')} onClick={() => { setEq(''); setShown(50) }}>{t('Any equipment')}</button>
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(50) }}>{t(x)}</button>)}
</div>}
<div className="list">
{bp !== '★' && <div className="item" onClick={() => customExSheet(null, ex => onPick(ex), q.trim())}>
<div className="thumb thumb-x">✨</div>
+1 -1
View File
@@ -8,7 +8,7 @@ export const DEF = {
unit: 'kg', restSec: 90, sound: true, lang: 'en',
theme: 'dark', accent: 'lime', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], active: null, customEx: [],
exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full',
reminder: { on: false, time: '08:00', tz: null }
}
const clone = o => JSON.parse(JSON.stringify(o))
+9 -9
View File
@@ -40,26 +40,26 @@ export const useUI = create((set, get) => ({
set({ timer: { left: sec, total: sec, endsAt } })
pushRestTimer(sec)
timerTick = () => {
const t = get().timer
if (!t) return
const left = Math.max(0, Math.round((t.endsAt - Date.now()) / 1000))
if (left === t.left) return
const tm = get().timer
if (!tm) return
const left = Math.max(0, Math.round((tm.endsAt - Date.now()) / 1000))
if (left === tm.left) return
const snd = useStore.getState().S.sound
if (left <= 0) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
vibrate([200, 100, 200]); get().toast(t('Rest over — next set! 💪')); get().stopRest(); return
}
if (left <= 3) beep(snd, 660, 0.1)
set({ timer: { ...t, left } })
set({ timer: { ...tm, left } })
}
timerInt = setInterval(timerTick, 1000)
document.addEventListener('visibilitychange', timerTick)
},
addRest(sec) {
const t = get().timer
if (!t) return
const left = t.left + sec
set({ timer: { ...t, left, total: t.total + sec, endsAt: t.endsAt + sec * 1000 } })
const tm = get().timer
if (!tm) return
const left = tm.left + sec
set({ timer: { ...tm, left, total: tm.total + sec, endsAt: tm.endsAt + sec * 1000 } })
pushRestTimer(left)
},
stopRest() {
+145
View File
@@ -0,0 +1,145 @@
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { api } from '../lib/api.js'
import { fmtDate, fmtNum, fmtVol, fmtDur } from '../lib/format.js'
import { workoutVolume, setsDone } from '../lib/history.js'
import { confirmSheet } from '../sheets.jsx'
// Admin-only operator dashboard (owner passkey + admin flag; guarded again server-side).
// Deliberately English-only — it isn't part of the translated end-user surface, so it stays
// out of the per-language string packs.
const rel = ts => {
if (!ts) return 'never'
const s = Math.max(0, (Date.now() - ts) / 1000)
if (s < 60) return 'just now'
if (s < 3600) return Math.floor(s / 60) + 'm ago'
if (s < 86400) return Math.floor(s / 3600) + 'h ago'
return Math.floor(s / 86400) + 'd ago'
}
const dur = ms => { const m = Math.max(0, Math.floor(ms / 60000)); return m < 60 ? m + 'm' : Math.floor(m / 60) + 'h' + (m % 60) + 'm' }
function UserDetail({ id, onChanged, close }) {
const [d, setD] = useState(null)
const toast = useUI(s => s.toast)
useEffect(() => { api('/api/admin/user?id=' + encodeURIComponent(id)).then(setD).catch(e => toast(e.message)) }, [id])
if (!d) return <div className="muted small">Loading…</div>
const u = d.user
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() })
.catch(e => toast(e.message))
}
return <>
<h3 className="capitalize">{u.name}</h3>
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '8px 0 12px' }}>
{u.admin && <span className="tag acc">admin</span>}
{u.disabled && <span className="tag" style={{ color: 'var(--red)' }}>disabled</span>}
{u.invitedBy && <span className="tag">invite {u.invitedBy}</span>}
<span className="tag">joined {u.created ? fmtDate(u.created.slice(0, 10)) : '—'}</span>
</div>
<div className="tiles" style={{ textAlign: 'left' }}>
<div className="tile"><div className="l">Workouts</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.workouts.length}</div></div>
<div className="tile"><div className="l">Weigh-ins</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.bodyweight.length}</div></div>
<div className="tile"><div className="l">Routines</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.routines.length}</div></div>
<div className="tile"><div className="l">Last sync</div><div className="v" style={{ fontSize: '.95rem' }}>{rel(d.lastSync)}</div></div>
</div>
{!u.admin && <button className={'btn ' + (u.disabled ? 'primary' : 'danger')} style={{ margin: '12px 0 4px' }}
onClick={() => u.disabled ? setDisabled(false)
: confirmSheet({ title: 'Disable ' + u.name + '?', message: 'They are signed out everywhere and can no longer sync or log in until re-enabled.', confirmText: 'Disable', danger: true, onConfirm: () => setDisabled(true) })}>
{u.disabled ? 'Enable account' : 'Disable account'}</button>}
<h4 className="sec">Workout history</h4>
{d.workouts.length ? <div className="list" style={{ gap: 0 }}>
{d.workouts.slice(0, 60).map(w => <div key={w.id} className="row between" style={{ padding: '9px 2px', borderBottom: '1px solid var(--bg2)' }}>
<div><div className="small" style={{ fontWeight: 700 }}>{w.name}</div>
<div className="dim" style={{ fontSize: '.72rem' }}>{fmtDate(w.d, true)} · {fmtDur((w.end || w.start) - w.start)} · {setsDone(w)} sets{w.prs?.length ? ' · 🏆 ' + w.prs.length : ''}</div></div>
<span className="small muted">{fmtVol(w.vol ?? workoutVolume(w), d.unit)}</span>
</div>)}
</div> : <div className="empty small">No workouts logged.</div>}
</>
}
function InvitesCard({ invites, reload }) {
const toast = useUI(s => s.toast)
const gen = () => api('/api/admin/invites/new', { method: 'POST', body: '{}' })
.then(({ invite }) => { navigator.clipboard?.writeText(invite.code).catch(() => {}); toast('Code ' + invite.code + ' created & copied'); reload() })
.catch(e => toast(e.message))
const revoke = code => api('/api/admin/invites/revoke', { method: 'POST', body: JSON.stringify({ code }) })
.then(() => { toast('Code revoked'); reload() }).catch(e => toast(e.message))
const open = (invites || []).filter(i => !i.usedBy)
const used = (invites || []).filter(i => i.usedBy)
return <div className="card">
<div className="row between"><h2 style={{ margin: 0 }}>Invite codes</h2>
<button className="btn sm primary" onClick={gen}>+ Generate</button></div>
<div className="small muted" style={{ margin: '6px 0 10px' }}>{open.length} unused · {used.length} redeemed</div>
{open.map(i => <div key={i.code} className="row between" style={{ padding: '7px 2px', borderBottom: '1px solid var(--bg2)' }}>
<span style={{ fontFamily: 'monospace', fontWeight: 700, letterSpacing: '.06em' }}
onClick={() => { navigator.clipboard?.writeText(i.code).catch(() => {}); toast('Copied ' + i.code) }}>{i.code}</span>
<button className="iconbtn" style={{ width: 34, height: 30, fontSize: '.9rem' }} onClick={() => revoke(i.code)} aria-label="revoke">🗑</button>
</div>)}
{used.map(i => <div key={i.code} className="row between dim" style={{ padding: '7px 2px', fontSize: '.8rem' }}>
<span style={{ fontFamily: 'monospace' }}>{i.code}</span><span>→ {i.usedByName || 'used'}</span>
</div>)}
{!open.length && !used.length && <div className="dim small">No codes yet — generate one to invite someone.</div>}
</div>
}
export default function Admin() {
const nav = useNavigate()
const user = useStore(s => s.user)
const toast = useUI(s => s.toast)
const openSheet = useUI(s => s.openSheet)
const [users, setUsers] = useState(null)
const [invites, setInvites] = useState(null)
const [inviteOnly, setInviteOnly] = useState(false)
const loadUsers = () => api('/api/admin/users').then(d => { setUsers(d.users); setInviteOnly(d.invite_only) }).catch(e => toast(e.message || 'Failed to load'))
const loadInvites = () => api('/api/admin/invites').then(d => setInvites(d.invites)).catch(() => {})
// poll every 15s so the "training now" section stays live without a manual refresh
useEffect(() => { if (!user?.admin) return; loadUsers(); loadInvites(); const iv = setInterval(loadUsers, 15000); return () => clearInterval(iv) }, [])
if (!user?.admin) return null
const openUser = id => openSheet(close => <UserDetail id={id} onChanged={loadUsers} close={close} />)
const liveUsers = (users || []).filter(u => u.live)
const activeCount = (users || []).filter(u => u.lastSync && Date.now() - u.lastSync < 7 * 86400000).length
const disabledCount = (users || []).filter(u => u.disabled).length
return <div className="narrow">
<div className="hdr">
<button className="iconbtn" onClick={() => nav('/settings')}>‹</button>
<div style={{ flex: 1, marginLeft: 8 }}><h1 style={{ margin: 0 }}>Admin</h1>
<div className="sub">{users ? users.length + ' users · ' + activeCount + ' active this week' : 'Loading…'}</div></div>
<button className="iconbtn" onClick={() => { loadUsers(); loadInvites() }} aria-label="refresh">↻</button>
</div>
<div className="tiles" style={{ marginBottom: 12 }}>
<div className="tile"><div className="l">Users</div><div className="v">{users ? users.length : '—'}</div></div>
<div className="tile"><div className="l">Training now</div><div className="v" style={{ color: liveUsers.length ? 'var(--acc)' : undefined }}>{users ? liveUsers.length : '—'}</div></div>
<div className="tile"><div className="l">Active 7d</div><div className="v">{users ? activeCount : '—'}</div></div>
<div className="tile"><div className="l">Disabled</div><div className="v">{users ? disabledCount : '—'}</div></div>
</div>
{liveUsers.length > 0 && <div className="card" style={{ borderColor: 'var(--acc)' }}>
<h2 style={{ margin: '0 0 8px' }}>🟢 Training now</h2>
{liveUsers.map(u => <div key={u.id} className="row between" style={{ padding: '8px 2px', borderBottom: '1px solid var(--bg2)' }} onClick={() => openUser(u.id)}>
<div><div className="small" style={{ fontWeight: 700 }}>{u.name}</div>
<div className="dim" style={{ fontSize: '.72rem' }}>{u.live.name} · ex {u.live.exIdx}/{u.live.exTotal} · {u.live.setsDone}/{u.live.setsTotal} sets</div></div>
<span className="tag acc">{dur(Date.now() - u.live.startedAt)}</span>
</div>)}
</div>}
<InvitesCard invites={invites} reload={loadInvites} />
<h4 className="sec">Users</h4>
<div className="list">
{(users || []).map(u => <div key={u.id} className="item" onClick={() => openUser(u.id)} style={u.disabled ? { opacity: .55 } : null}>
<div className="grow"><div className="tt">{u.live && '🟢 '}{u.name} {u.admin && <span className="tag acc" style={{ marginLeft: 4 }}>admin</span>}{u.disabled && <span className="tag" style={{ marginLeft: 4, color: 'var(--red)' }}>off</span>}</div>
<div className="ss">{u.live ? 'training now · ' + u.live.name : u.workouts + ' workouts' + (u.lastWorkout ? ' · last ' + fmtDate(u.lastWorkout) : '') + ' · synced ' + rel(u.lastSync)}</div></div>
{u.hasPush && <span title="push enabled">🔔</span>}<span className="chev">›</span>
</div>)}
{users && !users.length && <div className="empty">No users yet.</div>}
</div>
</div>
}
+14 -5
View File
@@ -1,6 +1,6 @@
import { useState } from 'react'
import { useStore } from '../store/useStore.js'
import { EXDB, BODYPARTS, allExercises } from '../lib/exercises.js'
import { EXDB, BODYPARTS, allExercises, equipmentOf } from '../lib/exercises.js'
import { bestWeightFor } from '../lib/history.js'
import { fmtNum } from '../lib/format.js'
import { t } from '../lib/i18n.js'
@@ -11,18 +11,27 @@ export default function Library() {
const S = useStore(s => s.S)
const [q, setQ] = useState('')
const [bp, setBp] = useState('')
const [eq, setEq] = useState('')
const [shown, setShown] = useState(40)
const ql = q.toLowerCase().trim()
const f = allExercises(S).filter(e => (!bp || e.bp === bp) && (!ql || e.n.toLowerCase().includes(ql) || e.tg.includes(ql) || e.eq.includes(ql) || (e.desc || '').toLowerCase().includes(ql)))
const base = allExercises(S).filter(e => (!bp || e.bp === bp) && (!ql || e.n.toLowerCase().includes(ql) || e.tg.includes(ql) || e.eq.includes(ql) || (e.desc || '').toLowerCase().includes(ql)))
const eqOpts = equipmentOf(base)
// Drop the equipment filter if the search narrowed it away, so you never hit a dead end.
const eqOn = eqOpts.includes(eq) ? eq : ''
const f = eqOn ? base.filter(e => e.eq === eqOn) : base
return <>
<div className="hdr"><div><h1>{t('Exercises')}</h1><div className="sub">{t('{0} exercises with animations', EXDB.length)}</div></div></div>
<div className="search" style={{ marginBottom: 10 }}><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" /><path d="m21 21-4.3-4.3" /></svg>
<input className="input" placeholder={t('Search…')} value={q} onChange={e => { setQ(e.target.value); setShown(40) }} /></div>
<div className="chips" style={{ marginBottom: 12 }}>
<button className={'chip' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setShown(40) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setShown(40) }}>{t(b)}</button>)}
<div className="chips" style={{ marginBottom: eqOpts.length > 1 ? 8 : 12 }}>
<button className={'chip' + (!bp ? ' on' : '')} onClick={() => { setBp(''); setEq(''); setShown(40) }}>{t('All')}</button>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => { setBp(b); setEq(''); setShown(40) }}>{t(b)}</button>)}
</div>
{eqOpts.length > 1 && <div className="chips" style={{ marginBottom: 12 }}>
<button className={'chip' + (!eqOn ? ' on' : '')} onClick={() => { setEq(''); setShown(40) }}>{t('Any equipment')}</button>
{eqOpts.map(x => <button key={x} className={'chip' + (eqOn === x ? ' on' : '')} onClick={() => { setEq(x); setShown(40) }}>{t(x)}</button>)}
</div>}
<div className="list">
<div className="item" onClick={() => customExSheet(null, ex => exerciseDetailSheet(ex), q.trim())}>
<div className="thumb thumb-x">✨</div>
+12 -2
View File
@@ -1,6 +1,6 @@
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { webauthnOK, passkeyLogin, passkeyRegister, BIO } from '../lib/api.js'
import { webauthnOK, passkeyLogin, passkeyRegister, api, BIO } from '../lib/api.js'
import { hasData } from '../store/useStore.js'
import { t } from '../lib/i18n.js'
import { useState, useRef, useEffect } from 'react'
@@ -8,13 +8,17 @@ import { useState, useRef, useEffect } from 'react'
function RegisterSheet({ close }) {
const { setUser, pushState, pullState } = useStore()
const [name, setName] = useState('')
const [code, setCode] = useState('')
const [inviteOnly, setInviteOnly] = useState(false)
const ref = useRef(null)
useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, [])
useEffect(() => { api('/api/config').then(c => setInviteOnly(!!c.invite_only)).catch(() => {}) }, [])
const go = async () => {
const n = name.trim()
if (!n) { useUI.getState().toast(t('Enter a name')); return }
if (inviteOnly && !code.trim()) { useUI.getState().toast(t('An invite code is required')); return }
try {
const u = await passkeyRegister(n)
const u = await passkeyRegister(n, code.trim())
setUser(u); close()
if (hasData(useStore.getState().S)) { await pushState(); useUI.getState().toast(t('Profile created — data from this device moved into it ✓')) }
else { await pullState(); useUI.getState().toast(t('Welcome, {0} 💪', u.name)) }
@@ -24,6 +28,12 @@ function RegisterSheet({ close }) {
<h3>{t('Create your profile ✨')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>{t('Pick a name, then confirm with {0}. The passkey is saved in your device — no password needed.', BIO)}</div>
<input ref={ref} className="input" placeholder={t('Your name')} maxLength={40} value={name} onChange={e => setName(e.target.value)} />
{inviteOnly && <>
<div style={{ height: 10 }} />
<input className="input" placeholder={t('Invite code')} maxLength={40} value={code}
onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.08em', fontWeight: 700 }} />
<div className="dim small" style={{ marginTop: 6 }}>{t('This app is invite-only — enter the code you were given.')}</div>
</>}
<div style={{ height: 12 }} />
<button className="btn primary" onClick={go}>{t('Create passkey')}</button>
</>
+5 -2
View File
@@ -44,10 +44,13 @@ export default function Settings() {
<div className="card">
<h2>{t('Account')}</h2>
{user ? <div className="row between">
{user ? <>
<div className="row between">
<div><b>{user.name}</b><div className="small muted">{t('Signed in with passkey — data syncs to this profile.')}</div></div>
<button className="btn sm danger" onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: () => { signOut(); nav('/home') } })}>{t('Sign out')}</button>
</div> : <>
</div>
{user.admin && <><div style={{ height: 10 }} /><button className="btn sm" onClick={() => nav('/admin')}>🛠️ {t('Admin dashboard')}</button></>}
</> : <>
<div className="small muted" style={{ marginBottom: 10 }}>{t('Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.')}</div>
{webauthnOK() ? <>
<button className="btn primary" onClick={registerHere}>✨ {t('Create passkey profile')}</button>
+29 -1
View File
@@ -7,6 +7,7 @@ import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, setsDoneActiv
import { fmtNum, fmtDate, todayISO, DAYN } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { t } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import Media from '../components/Media.jsx'
import NumField from '../components/NumField.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet } from '../sheets.jsx'
@@ -69,7 +70,7 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onBumpAll, onAddS
</div>
)
return <>
<Media ex={ex} key={entry.id} compact={compact} />
<Media ex={ex} key={entry.id} compact={compact} minimizable />
<div className="row between" style={{ marginBottom: 6 }}>
<div style={{ fontSize: compact ? '1.05rem' : '1.2rem', fontWeight: 800, textTransform: 'capitalize', lineHeight: 1.2 }}>{ex.n}</div>
<button className="iconbtn" onClick={() => exerciseDetailSheet(ex)}>ℹ️</button>
@@ -147,6 +148,33 @@ function ActiveWorkout() {
else if (exJustDone && cardioEntry) useUI.getState().toast(t('Cardio logged 🏃'))
}
// Live-presence heartbeat so the admin dashboard can show who's training now. Signed-in only —
// guests have no server session. Reads fresh state each tick so progress stays current.
useEffect(() => {
if (!useStore.getState().user) return
let stopped = false
const ping = active => {
const A2 = useStore.getState().S.active
if (!A2) return
const u = supersetUnits(A2.entries)
const c = Math.min(A2.cur, Math.max(0, A2.entries.length - 1))
const ui = u.findIndex(x => x.includes(c))
const tot = A2.entries.reduce((n, e) => n + e.sets.length, 0)
api('/api/activity', { method: 'POST', body: JSON.stringify({
active, name: A2.name, exIdx: ui + 1, exTotal: u.length,
setsDone: setsDoneActive(A2), setsTotal: tot, startedAt: A2.start
}) }).catch(() => {})
}
ping(true)
const iv = setInterval(() => { if (!stopped) ping(true) }, 20000)
return () => {
stopped = true; clearInterval(iv)
// best-effort "left" signal: sendBeacon survives a tab close, fetch covers in-app nav
try { navigator.sendBeacon?.('/api/activity', new Blob([JSON.stringify({ active: false })], { type: 'application/json' })) } catch { /* */ }
api('/api/activity', { method: 'POST', body: JSON.stringify({ active: false }) }).catch(() => {})
}
}, [])
return <div className="narrow">
<div className="hdr">
<button className="iconbtn" onClick={() => confirmSheet({ title: t('Discard workout?'), message: t('The sets you logged in this session will be lost.'), confirmText: t('Discard'), danger: true, onConfirm: () => { update(s => { s.active = null }); stopRest(); nav('/home') } })}>✕</button>