Merge remote-tracking branch 'origin/main' into feat/copy-routine
# Conflicts: # frontend/src/lib/pt-br-locale.test.js
This commit is contained in:
commit
5375dcc758
41 files changed
+962
-116
No files matched your search
@@ -9,20 +9,25 @@ import { workoutVolume, setsDone } from '../lib/history.js'
|
||||
import { confirmSheet } from '../sheets.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import { Button } from '../components/ui.jsx'
|
||||
import '../admin.css'
|
||||
|
||||
// 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.
|
||||
//
|
||||
// One page of cards, each opening with a sentence that says what it is for. An operator who
|
||||
// looks at this twice a year should not have to remember what "synced 3d ago" or an invite
|
||||
// code means.
|
||||
|
||||
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'
|
||||
if (s < 3600) return Math.floor(s / 60) + ' min 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' }
|
||||
const dur = ms => { const m = Math.max(0, Math.floor(ms / 60000)); return m < 60 ? m + ' min' : Math.floor(m / 60) + ' h ' + (m % 60) + ' min' }
|
||||
|
||||
function UserDetail({ id, onChanged, close }) {
|
||||
const [d, setD] = useState(null)
|
||||
@@ -38,10 +43,10 @@ function UserDetail({ id, onChanged, close }) {
|
||||
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>
|
||||
{u.admin && <span className="adm-pill acc">admin</span>}
|
||||
{u.disabled && <span className="adm-pill bad">disabled</span>}
|
||||
{u.invitedBy && <span className="adm-pill">invite {u.invitedBy}</span>}
|
||||
<span className="adm-pill">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>
|
||||
@@ -49,10 +54,13 @@ function UserDetail({ id, onChanged, close }) {
|
||||
<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>}
|
||||
{!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. Their data stays.', confirmText: 'Disable', danger: true, onConfirm: () => setDisabled(true) })}>
|
||||
{u.disabled ? 'Enable account' : 'Disable account'}</button>
|
||||
<div className="adm-hint">{u.disabled ? 'Enabling lets them sign in and sync again.' : 'Disabling signs them out everywhere and blocks sign-in. Nothing is deleted.'}</div>
|
||||
</>}
|
||||
<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(--sep)' }}>
|
||||
@@ -60,32 +68,49 @@ function UserDetail({ id, onChanged, close }) {
|
||||
<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 + ' PR' : ''}</div></div>
|
||||
<span className="small muted">{fmtVol(w.vol ?? workoutVolume(w), d.unit)}</span>
|
||||
</div>)}
|
||||
</div> : <div className="empty small">No workouts logged.</div>}
|
||||
</div> : <div className="adm-empty">No workouts logged.</div>}
|
||||
</>
|
||||
}
|
||||
|
||||
function InvitesCard({ invites, reload }) {
|
||||
function InvitesCard({ invites, reload, inviteOnly }) {
|
||||
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 revoke = code => confirmSheet({
|
||||
title: 'Revoke code ' + code + '?', message: 'Anyone who has it can no longer use it. People who already signed up with it are not affected.',
|
||||
confirmText: 'Revoke', danger: true,
|
||||
onConfirm: () => api('/api/admin/invites/revoke', { method: 'POST', body: JSON.stringify({ code }) })
|
||||
.then(() => { toast('Code revoked'); reload() }).catch(e => toast(e.message))
|
||||
})
|
||||
const copy = code => { navigator.clipboard?.writeText(code).catch(() => {}); toast('Copied ' + code) }
|
||||
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 variant="primary" size="sm" onClick={gen} icon="plus">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(--sep)' }}>
|
||||
<span style={{ fontFamily: 'ui-monospace,SFMono-Regular,Menlo,monospace', fontWeight: 500, letterSpacing: '.06em' }}
|
||||
onClick={() => { navigator.clipboard?.writeText(i.code).catch(() => {}); toast('Copied ' + i.code) }}>{i.code}</span>
|
||||
<button className="iconbtn" style={{ width: 32, height: 30, borderRadius: 8, fontSize: 15, color: 'var(--red)' }} onClick={() => revoke(i.code)} aria-label="revoke"><Icon name="trash" /></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>}
|
||||
<Button variant="primary" size="sm" onClick={gen} icon="plus">New code</Button></div>
|
||||
<div className="adm-lead">
|
||||
{inviteOnly
|
||||
? 'Sign-up is invite-only: someone needs one of these codes to create a profile. Each code works once.'
|
||||
: 'Sign-up is open, so codes are optional here — they only record who invited whom.'}
|
||||
</div>
|
||||
{open.length ? <>
|
||||
<div className="adm-group-t">Unused · tap to copy</div>
|
||||
{open.map(i => <div key={i.code} className="row between" style={{ padding: '6px 0', borderBottom: 'var(--hair) solid var(--sep)' }}>
|
||||
<button className="adm-code" onClick={() => copy(i.code)} aria-label={'copy ' + i.code}>{i.code}</button>
|
||||
<div className="row" style={{ gap: 4 }}>
|
||||
<button className="iconbtn adm-iconbtn" onClick={() => copy(i.code)} aria-label="copy"><Icon name="clipboard" /></button>
|
||||
<button className="iconbtn adm-iconbtn" style={{ color: 'var(--red)' }} onClick={() => revoke(i.code)} aria-label="revoke"><Icon name="trash" /></button>
|
||||
</div>
|
||||
</div>)}
|
||||
</> : null}
|
||||
{used.length ? <>
|
||||
<div className="adm-group-t" style={{ marginTop: open.length ? 12 : 0 }}>Already used</div>
|
||||
{used.map(i => <div key={i.code} className="row between dim" style={{ padding: '6px 0', fontSize: '.82rem' }}>
|
||||
<span style={{ fontFamily: 'ui-monospace,SFMono-Regular,Menlo,monospace', letterSpacing: '.06em' }}>{i.code}</span><span>→ {i.usedByName || 'used'}</span>
|
||||
</div>)}
|
||||
</> : null}
|
||||
{!open.length && !used.length && <div className="adm-empty">No codes yet. "New code" makes one and copies it to your clipboard.</div>}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -118,30 +143,31 @@ function AuditCard({ tick }) {
|
||||
|
||||
return <div className="card">
|
||||
<div className="row between"><h2 style={{ margin: 0 }}>Activity log</h2>
|
||||
<button className="iconbtn" style={{ width: 32, height: 30, borderRadius: 8, fontSize: 15, color: 'var(--red)' }}
|
||||
onClick={clear} aria-label="clear log"><Icon name="trash" /></button></div>
|
||||
<div className="small muted" style={{ margin: '6px 0 10px' }}>
|
||||
{meta ? fmtNum(meta.total) + ' events'
|
||||
+ (meta.retention.days ? ' · last ' + meta.retention.days + ' days' : '')
|
||||
+ (meta.ip_mode === 'off' ? ' · no IP addresses' : '') : 'Loading…'}</div>
|
||||
<button className="iconbtn adm-iconbtn" style={{ color: 'var(--red)' }} onClick={clear} aria-label="clear log"><Icon name="trash" /></button></div>
|
||||
<div className="adm-lead">
|
||||
Who signed in, what failed, and what an admin changed.
|
||||
{meta ? ' ' + fmtNum(meta.total) + ' events'
|
||||
+ (meta.retention.days ? ', kept for ' + meta.retention.days + ' days' : '')
|
||||
+ (meta.ip_mode === 'off' ? ', without IP addresses' : '') + '.' : ''}
|
||||
</div>
|
||||
<div className="chips" style={{ marginBottom: 10 }}>
|
||||
{[['', 'All'], ['auth', 'Sign-ins'], ['admin', 'Admin'], ['fail', 'Failed']].map(([v, l]) =>
|
||||
<button key={v} className={'chip' + (cat === v ? ' on' : '')} onClick={() => pick(v)}>{l}</button>)}
|
||||
</div>
|
||||
{rows.map(e => {
|
||||
const line = auditLine(e)
|
||||
return <div key={e.id} className="row between" style={{ padding: '8px 2px', borderBottom: '1px solid var(--sep)' }}>
|
||||
return <div key={e.id} className="row between" style={{ padding: '8px 2px', borderBottom: 'var(--hair) solid var(--sep)' }}>
|
||||
<div className="grow">
|
||||
<div className="small" style={{ fontWeight: 600 }}>{line.title}
|
||||
{/* a red pill, not a red row: twenty fumbled Face IDs in a row shouldn't read as an incident */}
|
||||
{!e.ok && <span className="tag" style={{ marginLeft: 6, color: 'var(--red)' }}>failed</span>}
|
||||
{auditCat(e.ev) === 'admin' && <span className="tag acc" style={{ marginLeft: 6 }}>admin</span>}</div>
|
||||
{!e.ok && <span className="adm-pill bad" style={{ marginLeft: 6 }}>failed</span>}
|
||||
{auditCat(e.ev) === 'admin' && <span className="adm-pill acc" style={{ marginLeft: 6 }}>admin</span>}</div>
|
||||
{line.sub && <div className="dim" style={{ fontSize: '.72rem' }}>{line.sub}</div>}
|
||||
</div>
|
||||
<span className="small muted" style={{ flex: 'none', marginLeft: 8 }}>{fmtWhen(e.ts, meta?.now)}</span>
|
||||
</div>
|
||||
})}
|
||||
{meta && !rows.length && <div className="dim small">Nothing logged yet.</div>}
|
||||
{meta && !rows.length && <div className="adm-empty">Nothing logged yet.</div>}
|
||||
{meta?.nextBefore && <div style={{ marginTop: 10 }}>
|
||||
<Button size="sm" onClick={() => load(cat, meta.nextBefore)}>Show more</Button></div>}
|
||||
</div>
|
||||
@@ -175,33 +201,40 @@ export default function Admin() {
|
||||
<div className="sub">{users ? users.length + ' users · ' + activeCount + ' active this week' : 'Loading…'}</div></div>
|
||||
<button className="iconbtn" onClick={() => { loadUsers(); loadInvites(); setTick(n => n + 1) }} aria-label="refresh">↻</button>
|
||||
</div>
|
||||
<div className="adm-intro">
|
||||
Everything about running this instance: who uses it, how they get in, and what has happened on it. Nothing here shows anyone's training data beyond counts.
|
||||
</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">Active 7 days</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 className="row" style={{ margin: '0 0 8px', gap: 6 }}><Icon name="dot" style={{ fontSize: 10, color: 'var(--green)' }} />Training now</h2>
|
||||
{liveUsers.map(u => <div key={u.id} className="row between" style={{ padding: '8px 2px', borderBottom: '1px solid var(--sep)' }} onClick={() => openUser(u.id)}>
|
||||
<h2 className="row" style={{ margin: '0 0 2px', gap: 6 }}><Icon name="dot" style={{ fontSize: 10, color: 'var(--green)' }} />Training now</h2>
|
||||
<div className="adm-lead">Sessions running at this moment. Tap a name for details.</div>
|
||||
{liveUsers.map(u => <div key={u.id} className="row between" style={{ padding: '8px 2px', borderBottom: 'var(--hair) solid var(--sep)' }} onClick={() => openUser(u.id)}>
|
||||
<div><div className="small" style={{ fontWeight: 600 }}>{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 className="dim" style={{ fontSize: '.72rem' }}>{u.live.name} · exercise {u.live.exIdx} of {u.live.exTotal} · {u.live.setsDone}/{u.live.setsTotal} sets</div></div>
|
||||
<span className="adm-pill acc">{dur(Date.now() - u.live.startedAt)}</span>
|
||||
</div>)}
|
||||
</div>}
|
||||
|
||||
<InvitesCard invites={invites} reload={loadInvites} />
|
||||
<InvitesCard invites={invites} reload={loadInvites} inviteOnly={inviteOnly} />
|
||||
|
||||
<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 && <Icon name="dot" style={{ fontSize: 9, color: 'var(--green)', display: 'inline-block', marginRight: 5 }} />}{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 && <Icon name="bell" title="push enabled" style={{ fontSize: 15, color: 'var(--label-3)' }} />}<Icon name="chevronRight" className="chev" />
|
||||
</div>)}
|
||||
{users && !users.length && <div className="empty">No users yet.</div>}
|
||||
<div className="card">
|
||||
<h2 style={{ margin: 0 }}>Users</h2>
|
||||
<div className="adm-lead">Everyone with a profile on this instance. Tap one to see their activity or to disable the account — their data is never deleted from here.</div>
|
||||
<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 && <Icon name="dot" style={{ fontSize: 9, color: 'var(--green)', display: 'inline-block', marginRight: 5 }} />}{u.name} {u.admin && <span className="adm-pill acc" style={{ marginLeft: 4 }}>admin</span>}{u.disabled && <span className="adm-pill bad" style={{ marginLeft: 4 }}>disabled</span>}</div>
|
||||
<div className="ss">{u.live ? 'training now · ' + u.live.name : u.workouts + ' workouts' + (u.lastWorkout ? ' · last ' + fmtDate(u.lastWorkout) : '') + ' · last sync ' + rel(u.lastSync)}</div></div>
|
||||
{u.hasPush && <Icon name="bell" title="push notifications on" style={{ fontSize: 15, color: 'var(--label-3)' }} />}<Icon name="chevronRight" className="chev" />
|
||||
</div>)}
|
||||
{users && !users.length && <div className="adm-empty">No users yet.</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 14 }}><AuditCard tick={tick} /></div>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { effectiveRoutine, effectiveRoutineId, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
|
||||
import { fmtNum, fmtDate, todayISO, isoOf, weekKey, DAYS } from '../lib/format.js'
|
||||
import { effectiveRoutine, effectiveRoutineId, nextTrainingDay, streakWeeks, lastBW, setsDoneActive } from '../lib/history.js'
|
||||
import { fmtNum, fmtDate, todayISO, isoOf, weekKey, weekStartOf, weekDayOffset, DAYS, DAYN } from '../lib/format.js'
|
||||
import { t, dateLocale } from '../lib/i18n.js'
|
||||
import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, loadStarterPlan, bwDeltaColor } from '../sheets.jsx'
|
||||
import LineChart from '../components/LineChart.jsx'
|
||||
@@ -21,28 +21,34 @@ export default function Home() {
|
||||
const today = new Date()
|
||||
const routine = effectiveRoutine(S, todayISO())
|
||||
const todayOvr = S.dayPlan[todayISO()] !== undefined
|
||||
// On a rest day, saying when you train next beats leaving the row as a full stop.
|
||||
const next = !S.active && !routine ? nextTrainingDay(S, todayISO()) : null
|
||||
const bw = lastBW(S)
|
||||
const prevBW = S.bodyweight.length > 1 ? S.bodyweight[S.bodyweight.length - 2] : null
|
||||
const delta = bw && prevBW ? bw.w - prevBW.w : null
|
||||
|
||||
const monday = new Date(today); monday.setDate(today.getDate() - ((today.getDay() + 6) % 7) + weekOffset * 7)
|
||||
const ws = weekStartOf(S)
|
||||
// The first day of the shown week. Named for the role, not for Monday — which day that is
|
||||
// is the setting.
|
||||
const wkStart = new Date(today)
|
||||
wkStart.setDate(today.getDate() - weekDayOffset(today.getDay(), ws) + weekOffset * 7)
|
||||
const doneDays = new Set(S.workouts.map(w => w.d))
|
||||
// The last session logged for today, if any — what the row below reports instead of asking
|
||||
// you to start the one you already did. Last wins, so a second session names itself.
|
||||
const doneToday = S.workouts.filter(w => w.d === todayISO()).at(-1) || null
|
||||
const strip = []
|
||||
for (let i = 0; i < 7; i++) {
|
||||
const d = new Date(monday); d.setDate(monday.getDate() + i)
|
||||
const d = new Date(wkStart); d.setDate(wkStart.getDate() + i)
|
||||
const iso = isoOf(d)
|
||||
const eff = effectiveRoutineId(S, iso), ovr = S.dayPlan[iso] !== undefined, done = doneDays.has(iso)
|
||||
const dot = done ? ' done' : ovr && eff ? ' ovr' : eff ? ' plan' : ''
|
||||
strip.push(<div key={i} className={'wday' + (iso === todayISO() ? ' today' : '')} {...tappable(() => dayOverrideSheet(iso))}>
|
||||
<div className="lbl">{t(DAYS[d.getDay()])}</div><div className="num">{d.getDate()}</div><div className={'dot' + dot} /></div>)
|
||||
}
|
||||
const sunday = new Date(monday); sunday.setDate(monday.getDate() + 6)
|
||||
const wkLabel = weekOffset === 0 ? t('This week') : `${monday.getDate()} ${monday.toLocaleDateString(dateLocale(), { month: 'short' })} – ${sunday.getDate()} ${sunday.toLocaleDateString(dateLocale(), { month: 'short' })}`
|
||||
const wkEnd = new Date(wkStart); wkEnd.setDate(wkStart.getDate() + 6)
|
||||
const wkLabel = weekOffset === 0 ? t('This week') : `${wkStart.getDate()} ${wkStart.toLocaleDateString(dateLocale(), { month: 'short' })} – ${wkEnd.getDate()} ${wkEnd.toLocaleDateString(dateLocale(), { month: 'short' })}`
|
||||
|
||||
const wThisWeek = S.workouts.filter(w => weekKey(w.d) === weekKey(todayISO())).length
|
||||
const wThisWeek = S.workouts.filter(w => weekKey(w.d, ws) === weekKey(todayISO(), ws)).length
|
||||
const plannedPerWeek = Object.keys(S.week).filter(k => S.week[k]).length
|
||||
const bwPoints = S.bodyweight.slice(-30).map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
|
||||
|
||||
@@ -78,6 +84,7 @@ export default function Home() {
|
||||
<div className="ttl">{S.active ? t('{0} — in progress', S.active.name)
|
||||
: doneToday ? (doneToday.name ? t('{0} — done', doneToday.name) : t('Workout done'))
|
||||
: routine ? routine.name : t('Rest day')}{todayOvr && routine && !doneToday ? ' · ' + t('rescheduled') : ''}</div>
|
||||
{next && !doneToday && <div className="ss">{t('Next session: {0}, {1}', t(DAYN[next.weekday]), next.routine.name)}</div>}
|
||||
</div>
|
||||
</div>
|
||||
{S.active ? <span className="tag" style={{ color: 'var(--orange)', background: 'color-mix(in srgb,var(--orange) 16%,transparent)' }}>{t('Resume')}</span>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { DAYN, uid, exCount } from '../lib/format.js'
|
||||
import { DAYN, weekOrder, weekStartOf, uid, exCount } from '../lib/format.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
import { dayAssignSheet, loadStarterPlan, planToolsSheet } from '../sheets.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
@@ -27,7 +27,7 @@ export default function Plan() {
|
||||
<div className="cols"><div>
|
||||
<h4 className="sec">{t('Week schedule')}</h4>
|
||||
<div className="list" style={{ display: 'flex', flexDirection: 'column' }}>
|
||||
{[1, 2, 3, 4, 5, 6, 0].map(d => {
|
||||
{weekOrder(weekStartOf(S)).map(d => {
|
||||
const r = S.routines.find(x => x.id === S.week[d])
|
||||
return <div key={d} className="item" {...tappable(() => dayAssignSheet(d))}>
|
||||
<div className="grow"><div className="tt">{t(DAYN[d])}</div></div>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useStore, DEF, hasData } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { ACCENTS, todayISO, localTZ } from '../lib/format.js'
|
||||
import { ACCENTS, todayISO, localTZ, weekStartOf, MONDAY, SUNDAY } from '../lib/format.js'
|
||||
import { effortOf } from '../lib/history.js'
|
||||
import { api, webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
|
||||
import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js'
|
||||
@@ -125,6 +125,13 @@ export default function Settings() {
|
||||
options={[{ value: 'kg', label: 'kg' }, { value: 'lb', label: 'lb' }]}
|
||||
value={S.unit} onChange={v => update(s => { s.unit = v })} />
|
||||
</Row>
|
||||
{/* Monday or Sunday — the Plan list, the Home strip, the calendar grid and every
|
||||
"this week" total follow it. Stored as a getDay() index (see lib/format.js). */}
|
||||
<Row icon="calendar" iconTint="var(--orange)" title={t('Week starts on')}>
|
||||
<Segmented className="seg-inline"
|
||||
options={[{ value: MONDAY, label: t('Monday') }, { value: SUNDAY, label: t('Sunday') }]}
|
||||
value={weekStartOf(S)} onChange={v => update(s => { s.weekStart = v })} />
|
||||
</Row>
|
||||
</Section>
|
||||
|
||||
{/* ---------- during a workout ---------- */}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { EXIDX, matchExercise } from '../lib/exercises.js'
|
||||
import { lastBW, streakWeeks, setLabel, modeOf, effortOf, metricModeForEntry, metricRowsForEntry, bestWeightForEntry } from '../lib/history.js'
|
||||
import { fmtNum, fmtDate, fmtVol, todayISO } from '../lib/format.js'
|
||||
import { fmtNum, fmtDate, fmtVol, todayISO, weekStartOf } from '../lib/format.js'
|
||||
import { t, exerciseNameFor, getLang } from '../lib/i18n.js'
|
||||
import { bwSheet, goalSheet, calendarSheet, workoutDetailSheet, WorkoutRow, bwDeltaColor } from '../sheets.jsx'
|
||||
import LineChart from '../components/LineChart.jsx'
|
||||
@@ -123,7 +123,7 @@ function MuscleBalance({ S }) {
|
||||
return t('Weeks since training: {0}', weeks)
|
||||
}
|
||||
const toggleSel = m => setSel(s => (s === m ? null : m))
|
||||
const inWin = muscleBalanceWindow(S.workouts, win, now)
|
||||
const inWin = muscleBalanceWindow(S.workouts, win, now, todayISO(), weekStartOf(S))
|
||||
// Counting only the sets taken near failure turns the map from "where did the volume go"
|
||||
// into "where did the stimulus go" — a muscle can lead on sets and still never be trained
|
||||
// hard. Offered only when the window holds ratings at all, since with none the hard map
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useNavigate } from 'react-router-dom'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { exOr } from '../lib/exercises.js'
|
||||
import { usesBar, barWeightFor, plateSplit } from '../lib/bar.js'
|
||||
import { effectiveRoutine, lastEntryFor, bestWeightFor, buildSets, freestyleConfig, defaultConfig, setsDoneActive, supersetUnits, unitOf, setLabel, modeOf, isBw, isPerSide, sideReps, repStep, EFFORT, effortOf, stepEffort, capEffort, cascadeWeight, insertWarmupRow, removeRowAt, pairAdjacent, unpairSuperset, cleanupSg, applyIntensifierPlan, pinnedNoteFor, exNoteFor } from '../lib/history.js'
|
||||
import { fmtNum, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
|
||||
import { beep, vibrate } from '../lib/sound.js'
|
||||
@@ -10,7 +11,7 @@ import { t, exerciseNameFor } from '../lib/i18n.js'
|
||||
import { api } from '../lib/api.js'
|
||||
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor } from '../lib/supersetFlow.js'
|
||||
import Media from '../components/Media.jsx'
|
||||
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise } from '../sheets.jsx'
|
||||
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, topWeightSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, swapActiveWorkoutExercise, barWeightSheet } from '../sheets.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import { Button, Check, NumberField } from '../components/ui.jsx'
|
||||
import { nextPrescription, applyPrescription, defaultIncrement } from '../lib/progression.js'
|
||||
@@ -197,6 +198,23 @@ function ExerciseBlock({ entryIdx, compact, onToggle, onField, onAddSet, onRemov
|
||||
</div>}
|
||||
{entry.note && <div className="exnote">{entry.note}</div>}
|
||||
{last && <div className="small dim" style={{ marginBottom: 4 }}>{t('Last time')} ({fmtDate(last.d)}): {last.sets.map(s => setLabel(entry.id, s, last.target)).join(', ')}</div>}
|
||||
{/* Bar + plates for barbell work: what to load per side for the set in front of you
|
||||
(first undone set; the heaviest row once everything is checked). The logged number
|
||||
stays the total — this chip is the split, and tapping it edits the bar's own weight
|
||||
(S.barWeights, per exercise) mid-workout. Weight ≤ bar leaves just the bar. */}
|
||||
{!cardio && !(bw && !added) && usesBar(ex) && (() => {
|
||||
const bar = barWeightFor(S, entry.id)
|
||||
if (!(bar > 0)) return null
|
||||
const nextW = entry.sets.find(s => !s.done)?.w
|
||||
const refW = nextW > 0 ? nextW : Math.max(0, ...entry.sets.map(s => s.w || 0))
|
||||
const split = plateSplit(refW, bar)
|
||||
return <div style={{ marginBottom: 6 }}>
|
||||
<button className="chip nocap" style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }} onClick={() => barWeightSheet(entry.id)}>
|
||||
<Icon name="dumbbell" style={{ fontSize: 12 }} />
|
||||
{t('Bar {0}', fmtNum(bar) + ' ' + S.unit)}{split != null ? ' · ' + t('{0} per side', fmtNum(split) + ' ' + S.unit) : ''}
|
||||
</button>
|
||||
</div>
|
||||
})()}
|
||||
{guidance && <button type="button" className={'progline' + (plan.kind === 'deload' ? ' warn' : '')}
|
||||
aria-label={t('Open progression settings')} onClick={onProgressionSettings}>
|
||||
<Icon name={plan.kind === 'up' ? 'arrowUp' : plan.kind === 'deload' ? 'arrowDown' : 'lightbulb'} />
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// @vitest-environment happy-dom
|
||||
// The setting is only worth anything if the screens actually follow it: the toggle has to
|
||||
// write the field, and the Plan list has to draw the week in that order.
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import Settings from './Settings.jsx'
|
||||
import Plan from './Plan.jsx'
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
const mocks = vi.hoisted(() => {
|
||||
const state = { S: null }
|
||||
state.snapshot = () => ({
|
||||
S: state.S,
|
||||
user: null,
|
||||
update: mut => {
|
||||
const next = structuredClone(state.S)
|
||||
mut(next)
|
||||
state.S = next
|
||||
},
|
||||
replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
|
||||
signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
|
||||
})
|
||||
return state
|
||||
})
|
||||
vi.mock('../store/useStore.js', () => {
|
||||
const useStore = selector => (selector ? selector(mocks.snapshot()) : mocks.snapshot())
|
||||
useStore.getState = mocks.snapshot
|
||||
return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
|
||||
})
|
||||
vi.mock('../store/useUI.js', () => {
|
||||
const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })
|
||||
const useUI = selector => (selector ? selector(snap()) : snap())
|
||||
useUI.getState = snap
|
||||
return { useUI }
|
||||
})
|
||||
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
|
||||
vi.mock('../lib/api.js', () => ({
|
||||
api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
|
||||
}))
|
||||
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
|
||||
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
|
||||
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
|
||||
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
|
||||
vi.mock('../sheets.jsx', () => ({
|
||||
loadStarterPlan: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
|
||||
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(),
|
||||
dayAssignSheet: vi.fn(), planToolsSheet: vi.fn(),
|
||||
}))
|
||||
|
||||
globalThis.__APP_VERSION__ ??= 'test'
|
||||
|
||||
let host, root
|
||||
beforeEach(() => {
|
||||
mocks.S = {
|
||||
unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
|
||||
gifSize: 'full', workouts: [], routines: [], exWeights: {}, week: {}, dayPlan: {},
|
||||
}
|
||||
host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
root = createRoot(host)
|
||||
})
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
host.remove()
|
||||
})
|
||||
|
||||
const segButton = label => [...host.querySelectorAll('.seg button')].find(b => b.textContent === label)
|
||||
const dayRows = () => [...host.querySelectorAll('.item .tt')].map(e => e.textContent)
|
||||
|
||||
describe('Settings — week starts on', () => {
|
||||
const mount = () => act(() => root.render(<Settings />))
|
||||
|
||||
it('offers Monday and Sunday and writes the getDay() index', () => {
|
||||
mount()
|
||||
expect(segButton('Monday').getAttribute('aria-pressed')).toBe('true')
|
||||
act(() => { segButton('Sunday').click() })
|
||||
expect(mocks.S.weekStart).toBe(0)
|
||||
mount()
|
||||
expect(segButton('Sunday').getAttribute('aria-pressed')).toBe('true')
|
||||
act(() => { segButton('Monday').click() })
|
||||
expect(mocks.S.weekStart).toBe(1)
|
||||
})
|
||||
|
||||
it('shows a profile written before the setting existed as Monday', () => {
|
||||
delete mocks.S.weekStart
|
||||
mount()
|
||||
expect(segButton('Monday').getAttribute('aria-pressed')).toBe('true')
|
||||
expect(segButton('Sunday').getAttribute('aria-pressed')).toBe('false')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Plan — the week schedule follows the setting', () => {
|
||||
const mount = () => act(() => root.render(<Plan />))
|
||||
|
||||
it('runs Monday to Sunday by default', () => {
|
||||
mount()
|
||||
expect(dayRows().slice(0, 7)).toEqual(
|
||||
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'])
|
||||
})
|
||||
|
||||
it('runs Sunday to Saturday for a Sunday profile', () => {
|
||||
mocks.S.weekStart = 0
|
||||
mount()
|
||||
expect(dayRows().slice(0, 7)).toEqual(
|
||||
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'])
|
||||
})
|
||||
|
||||
it('keeps a routine attached to its day, not to its position in the list', () => {
|
||||
mocks.S.routines = [{ id: 'r1', name: 'Push', emoji: null, ex: [] }]
|
||||
mocks.S.week = { 0: 'r1' } // Sunday
|
||||
mocks.S.weekStart = 0
|
||||
mount()
|
||||
const rows = [...host.querySelectorAll('.item')]
|
||||
expect(rows[0].querySelector('.tt').textContent).toBe('Sunday')
|
||||
expect(rows[0].textContent).toContain('Push')
|
||||
expect(rows[1].textContent).not.toContain('Push')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user