Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Plan sharing: export/import a plan file + printable PDF
Duarte Santosaf9289dcd9b8
diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.jsnew file mode 100644index 000000000..ef8b46b99--- /dev/null+++ b/frontend/src/lib/plan-share.js@@ -0,0 +1,245 @@+// Share a weekly plan.+//+// Two jobs:+// 1. A small, self-contained file a friend can import into THEIR openGym — just the+// routines + the week schedule + the custom exercises those routines use. It never+// carries workouts, weigh-ins or settings, and importing MERGES (adds routines with+// fresh ids) so nothing the friend already has is touched.+// 2. A clean, printable page (Save as PDF) where a single exercise never splits across+// a page break — each exercise, and each routine that fits, stays in one place.++import { EXIDX, isCardio } from './exercises.js'+import { uid, todayISO, DAYN, fmtNum } from './format.js'+import { t } from './i18n.js'++const PLAN_FMT = 1+const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0] // Mon-first, matching the Plan screen++// Keep only the meaningful config fields, so the file stays small and readable.+function cleanEx(e) {+ const o = { id: e.id, sets: e.sets }+ if (isCardio(e.id)) {+ if (e.min != null) o.min = e.min+ if (e.speed != null) o.speed = e.speed+ } else {+ if (e.reps != null) o.reps = e.reps+ if (e.weight) o.weight = e.weight+ }+ if (e.sg) o.sg = e.sg+ return o+}++/** Build the shareable bundle: every routine, the week schedule, referenced customs. */+export function buildPlanBundle(S, name) {+ const routines = (S.routines || []).map(r => ({+ id: r.id, name: r.name, emoji: r.emoji, ex: (r.ex || []).map(cleanEx)+ }))+ const usedIds = new Set(routines.flatMap(r => r.ex.map(e => e.id)))+ const customEx = (S.customEx || [])+ .filter(c => usedIds.has(c.id))+ .map(c => ({ id: c.id, n: c.n, bp: c.bp, ...(c.desc ? { desc: c.desc } : {}) }))+ const week = {}+ WEEK_ORDER.forEach(d => { if (S.week?.[d]) week[d] = S.week[d] })+ return { opengym_plan: PLAN_FMT, exported: todayISO(), name: name || '', week, routines, customEx }+}++/** Validate + normalise an imported file. Throws with a friendly message if it isn't one. */+export function parsePlan(raw) {+ const data = typeof raw === 'string' ? JSON.parse(raw) : raw+ if (!data || !data.opengym_plan || !Array.isArray(data.routines)) {+ throw new Error(t('this isn’t an openGym plan file'))+ }+ const routines = data.routines.filter(r => r && Array.isArray(r.ex))+ return {+ name: (data.name || '').trim(),+ routines,+ week: data.week || {},+ customEx: Array.isArray(data.customEx) ? data.customEx : [],+ routineCount: routines.length,+ exerciseCount: routines.reduce((n, r) => n + r.ex.length, 0),+ scheduledDays: WEEK_ORDER.filter(d => data.week?.[d]).length+ }+}++/**+ * Merge a parsed bundle into a draft state `s` (call inside store.update).+ * - customs: reuse one you already have with the same name + body part, else add it fresh+ * - routines: always added as NEW routines (fresh ids) — never overwrites yours+ * - schedule: optional; when on, points your week at the freshly-added routines+ */+export function mergePlan(s, bundle, { schedule } = {}) {+ s.customEx = s.customEx || []+ const exIdMap = {}+ bundle.customEx.forEach(c => {+ const same = s.customEx.find(x => (x.n || '').toLowerCase() === (c.n || '').toLowerCase() && x.bp === c.bp)+ if (same) { exIdMap[c.id] = same.id; return }+ const nid = uid()+ exIdMap[c.id] = nid+ s.customEx.push({ id: nid, n: c.n, bp: c.bp, ...(c.desc ? { desc: c.desc } : {}) })+ })+ const ridMap = {}+ bundle.routines.forEach(r => {+ const nid = uid()+ ridMap[r.id] = nid+ s.routines.push({+ id: nid,+ name: r.name || t('Shared routine'),+ emoji: r.emoji,+ ex: (r.ex || []).map(e => ({ ...e, id: exIdMap[e.id] || e.id }))+ })+ })+ if (schedule) {+ Object.entries(bundle.week || {}).forEach(([d, oldId]) => {+ if (ridMap[oldId]) s.week[d] = ridMap[oldId]+ })+ }+ return { routines: bundle.routines.length }+}++/* ------------------------------- printable PDF ------------------------------- */++const esc = str => String(str == null ? '' : str)+ .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')++// One exercise's scheme, e.g. "3 × 10 · 60 kg" or "2 × 20 min @ 8 km/h".+function scheme(e, unit) {+ const sets = e.sets || 1+ if (isCardio(e.id)) {+ const body = `${e.min || 20} min @ ${fmtNum(e.speed || 8)} km/h`+ return sets > 1 ? `${sets} × ${body}` : body+ }+ let s = `${sets} × ${e.reps ?? 10}`+ if (e.weight) s += ` · ${fmtNum(e.weight)} ${unit}`+ return s+}++// Group consecutive exercises sharing a superset id into rendered units.+function units(ex) {+ const out = []+ ex.forEach((e, i) => {+ const prev = ex[i - 1]+ if (i > 0 && e.sg && prev?.sg === e.sg) out[out.length - 1].push(e)+ else out.push([e])+ })+ return out+}++function routineHTML(r, unit) {+ const rows = units(r.ex).map(u => {+ const items = u.map(e => {+ const ex = EXIDX[e.id]+ const name = ex ? ex.n : t('Unknown exercise')+ const part = ex && ex.bp && ex.bp !== 'cardio' ? `<span class="part">${esc(ex.bp)}</span>` : ''+ return `<div class="ex"><div class="ex-n">${esc(name)}${part}</div><div class="ex-s">${esc(scheme(e, unit))}</div></div>`+ }).join('')+ return u.length > 1+ ? `<div class="ss"><div class="ss-tag">${esc(t('Superset'))}</div><div class="ss-items">${items}</div></div>`+ : items+ }).join('')+ const count = t('{0} exercises', r.ex.length).replace('{0}', r.ex.length)+ return `<section class="routine">+ <div class="r-head"><h2>${esc(r.name)}</h2><span class="r-count">${esc(count)}</span></div>+ <div class="ex-list">${rows || `<div class="ex empty">${esc(t('No exercises yet.'))}</div>`}</div>+ </section>`+}++function weekHTML(S) {+ const rows = WEEK_ORDER.map(d => {+ const r = S.routines.find(x => x.id === S.week?.[d])+ const val = r ? esc(r.name) : `<span class="rest">${esc(t('Rest'))}</span>`+ return `<div class="w-row"><div class="w-day">${esc(t(DAYN[d]))}</div><div class="w-r">${val}</div></div>`+ }).join('')+ return `<div class="week">${rows}</div>`+}++/** Full self-contained HTML for the print/PDF view. */+export function planPrintHTML(S, owner) {+ const unit = S.unit || 'kg'+ const routines = (S.routines || []).filter(r => r.ex && r.ex.length)+ const body = routines.length+ ? routines.map(r => routineHTML(r, unit)).join('')+ : `<p class="none">${esc(t('No routines yet.'))}</p>`+ const sub = [owner, todayISO()].filter(Boolean).map(esc).join(' · ')+ return `<!doctype html><html><head><meta charset="utf-8">+<title>${esc(t('Weekly Training Plan'))}</title>+<style>+ @page { margin: 16mm 15mm; }+ * { box-sizing: border-box; }+ html { -webkit-print-color-adjust: exact; print-color-adjust: exact; }+ body {+ margin: 0; color: #16181d; background: #fff;+ font: 14px/1.5 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;+ font-variant-numeric: tabular-nums;+ }+ .doc { max-width: 720px; margin: 0 auto; }+ header { border-bottom: 2px solid #16181d; padding-bottom: 12px; margin-bottom: 20px; }+ header .kicker { font-size: 11px; letter-spacing: .14em; text-transform: uppercase; color: #6a7a3a; font-weight: 700; }+ header h1 { font-size: 27px; letter-spacing: -.02em; margin: 3px 0 0; }+ header .sub { color: #6b7180; font-size: 13px; margin-top: 4px; }++ h3.block { font-size: 12px; letter-spacing: .1em; text-transform: uppercase; color: #8a90a0; margin: 0 0 8px; font-weight: 700; }++ .week { border: 1px solid #e4e6ec; border-radius: 10px; overflow: hidden; margin-bottom: 26px; break-inside: avoid; page-break-inside: avoid; }+ .w-row { display: flex; align-items: baseline; padding: 8px 14px; border-top: 1px solid #eef0f4; }+ .w-row:first-child { border-top: 0; }+ .w-day { width: 116px; font-weight: 600; color: #16181d; flex: none; }+ .w-r { text-transform: capitalize; }+ .rest, .w-r .rest { color: #a2a8b6; text-transform: none; }++ .routine { break-inside: avoid; page-break-inside: avoid; margin-bottom: 20px; padding: 14px 16px; border: 1px solid #e4e6ec; border-radius: 12px; }+ .r-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; border-bottom: 1px solid #eef0f4; padding-bottom: 8px; margin-bottom: 8px; break-after: avoid; page-break-after: avoid; }+ .r-head h2 { font-size: 18px; letter-spacing: -.01em; margin: 0; text-transform: capitalize; }+ .r-count { font-size: 12px; color: #8a90a0; white-space: nowrap; }++ .ex-list { display: flex; flex-direction: column; }+ .ex { display: flex; align-items: baseline; justify-content: space-between; gap: 14px; padding: 6px 0; break-inside: avoid; page-break-inside: avoid; }+ .ex + .ex, .ss + .ex, .ex + .ss { border-top: 1px solid #f2f3f6; }+ .ex-n { text-transform: capitalize; font-weight: 500; }+ .ex-n .part { text-transform: capitalize; color: #9aa0ae; font-weight: 400; font-size: 12px; margin-left: 8px; }+ .ex-s { color: #3d424e; white-space: nowrap; font-variant-numeric: tabular-nums; }+ .ex.empty, .none { color: #a2a8b6; }++ .ss { break-inside: avoid; page-break-inside: avoid; border-left: 3px solid #cfe08a; padding-left: 12px; margin: 4px 0; }+ .ss-tag { font-size: 10px; letter-spacing: .08em; text-transform: uppercase; color: #6a7a3a; font-weight: 700; padding-top: 4px; }+ .ss .ex:first-of-type { padding-top: 2px; }++ footer { margin-top: 26px; padding-top: 10px; border-top: 1px solid #eef0f4; color: #a2a8b6; font-size: 11px; text-align: center; }+</style></head>+<body><div class="doc">+ <header>+ <div class="kicker">openGym</div>+ <h1>${esc(t('Weekly Training Plan'))}</h1>+ ${sub ? `<div class="sub">${sub}</div>` : ''}+ </header>+ <h3 class="block">${esc(t('Week schedule'))}</h3>+ ${weekHTML(S)}+ <h3 class="block">${esc(t('Routines'))}</h3>+ ${body}+ <footer>${esc(t('Made with openGym'))} · opengym.duarte-santos.ch</footer>+</div></body></html>`+}++/**+ * Render the plan and open the browser's print dialog (→ Save as PDF).+ * Uses a hidden iframe so we never navigate away or trip a popup blocker.+ */+export function printPlan(S, owner) {+ const ifr = document.createElement('iframe')+ ifr.setAttribute('aria-hidden', 'true')+ ifr.style.cssText = 'position:fixed;right:0;bottom:0;width:0;height:0;border:0;opacity:0;'+ document.body.appendChild(ifr)+ const cleanup = () => { try { ifr.remove() } catch (e) { /* */ } }+ const run = () => {+ const w = ifr.contentWindow+ if (!w) { cleanup(); return }+ w.onafterprint = cleanup+ setTimeout(cleanup, 60000) // safety net if afterprint never fires+ w.focus()+ try { w.print() } catch (e) { cleanup() }+ }+ const doc = ifr.contentWindow.document+ doc.open(); doc.write(planPrintHTML(S, owner)); doc.close()+ // Give the iframe a tick to lay out before printing.+ if (doc.readyState === 'complete') setTimeout(run, 120)+ else ifr.onload = () => setTimeout(run, 120)+}diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsxindex 677f7d2c8..9a271f158 100644--- a/frontend/src/sheets.jsx+++ b/frontend/src/sheets.jsx@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react'+import { useEffect, useRef, useState } from 'react'import { useStore } from './store/useStore.js'import { useUI } from './store/useUI.js'import { EXDB, EXIDX, BODYPARTS, isCardio, allExercises, equipmentOf } from './lib/exercises.js'@@ -11,11 +11,13 @@ import { starterRoutines } from './lib/starter.js'import Media, { Thumb } from './components/Media.jsx'import Stepper from './components/Stepper.jsx'import Icon from './components/Icon.jsx'-import { Button, Slider } from './components/ui.jsx'+import { Button, Slider, Switch } from './components/ui.jsx'import { glyphOf, GLYPH_GROUPS, DEFAULT_GLYPH } from './lib/glyphs.js'import BodyMap from './components/BodyMap.jsx'import { loadOfWorkouts } from './lib/muscles.js'import { parseImport, mergeImport } from './lib/import-csv.js'+import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'+import { MOBILE, shareExport } from './lib/mobile.js'const S = () => useStore.getState().Sconst update = (...a) => useStore.getState().update(...a)@@ -467,6 +469,78 @@ export const glyphPicker = (current, onPick) => {</>)}+/* ============================ share / print / import a plan ============================ */+export const planToolsSheet = () => ui().openSheet(close => <PlanTools close={close} />)++function PlanTools({ close }) {+ const st = useStore(s => s.S)+ const user = useStore(s => s.user)+ const fileRef = useRef(null)+ const hasRoutines = (st.routines || []).some(r => r.ex && r.ex.length)++ const exportFile = async () => {+ const bundle = buildPlanBundle(st, user?.name ? t('{0}’s plan', user.name) : '')+ const json = JSON.stringify(bundle, null, 2)+ const name = 'opengym-plan-' + todayISO() + '.json'+ if (MOBILE) { try { await shareExport(json, name) } catch (e) { /* dismissed */ } close(); return }+ const blob = new Blob([json], { type: 'application/json' })+ const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); URL.revokeObjectURL(a.href)+ close(); toast(t('Plan file saved — send it to a friend'))+ }+ const pickFile = ev => {+ const f = ev.target.files[0]; ev.target.value = ''; if (!f) return+ const rd = new FileReader()+ rd.onload = () => {+ try { const bundle = parsePlan(rd.result); close(); planImportSheet(bundle) }+ catch (e) { toast(t('Import failed: {0}', e.message)) }+ }+ rd.readAsText(f)+ }++ return <>+ <h3>{t('Share your plan')}</h3>+ <div className="muted small" style={{ marginBottom: 16 }}>{t('Send your routines to a friend, or put your week on paper.')}</div>+ <Button variant="primary" icon="upload" onClick={exportFile} disabled={!hasRoutines}>{t('Export plan file')}</Button>+ <div className="dim small" style={{ margin: '7px 2px 0', lineHeight: 1.4 }}>{t('A small file a friend imports into their own openGym — routines only, none of your workouts or weigh-ins.')}</div>+ {!MOBILE && <>+ <div style={{ height: 12 }} />+ <Button variant="tinted" icon="download" onClick={() => { close(); printPlan(st, user?.name || '') }} disabled={!hasRoutines}>{t('Print / Save as PDF')}</Button>+ <div className="dim small" style={{ margin: '7px 2px 0', lineHeight: 1.4 }}>{t('A clean one-page-per-plan printout — no exercise ever splits across a page.')}</div>+ </>}+ {!hasRoutines && <div className="dim small" style={{ margin: '12px 2px 0' }}>{t('Add an exercise to a routine first — an empty plan has nothing to share.')}</div>}+ <h4 className="sec">{t('Got a plan from a friend?')}</h4>+ <Button variant="ghost" icon="folder" onClick={() => fileRef.current?.click()}>{t('Import a plan file')}</Button>+ <input ref={fileRef} type="file" accept="application/json,.json" onChange={pickFile} hidden />+ </>+}++export const planImportSheet = bundle => ui().openSheet(close => <PlanImport bundle={bundle} close={close} />)++function PlanImport({ bundle, close }) {+ const [schedule, setSchedule] = useState(false)+ const apply = () => {+ update(s => mergePlan(s, bundle, { schedule }))+ close()+ toast(t('Added {0} routines to your plan', bundle.routineCount))+ nav('/plan')+ }+ return <>+ <h3>{bundle.name ? t('Import “{0}”', bundle.name) : t('Import this plan')}</h3>+ <div className="muted small" style={{ marginBottom: 14 }}>+ {t('{0} routines · {1} exercises', bundle.routineCount, bundle.exerciseCount)}+ {bundle.scheduledDays > 0 ? ' · ' + t('scheduled on {0} days', bundle.scheduledDays) : ''}+ </div>+ <div className="dim small" style={{ marginBottom: 14, lineHeight: 1.4 }}>{t('These are added as new routines — nothing you already have is changed.')}</div>+ {bundle.scheduledDays > 0 && <div className="row between" style={{ padding: '10px 2px', borderTop: '1px solid var(--sep)', borderBottom: '1px solid var(--sep)', marginBottom: 16, gap: 12 }}>+ <div><div className="tt" style={{ fontSize: 15 }}>{t('Use this weekly schedule')}</div><div className="small dim">{t('Replaces your current Mon–Sun assignments.')}</div></div>+ <Switch checked={schedule} onChange={setSchedule} />+ </div>}+ <Button variant="primary" onClick={apply}>{t('Add to my plan')}</Button>+ <div style={{ height: 8 }} />+ <Button variant="ghost" className="dim" onClick={close}>{t('Cancel')}</Button>+ </>+}+/* ============================ day override / assign ============================ */function DayOverride({ iso, close }) {const st = useStore(s => s.S)diff --git a/frontend/src/views/Plan.jsx b/frontend/src/views/Plan.jsxindex 224bee6d1..f07dd4b1b 100644--- a/frontend/src/views/Plan.jsx+++ b/frontend/src/views/Plan.jsx@@ -2,7 +2,7 @@ import { useNavigate } from 'react-router-dom'import { useStore } from '../store/useStore.js'import { DAYN, uid } from '../lib/format.js'import { t } from '../lib/i18n.js'-import { dayAssignSheet, loadStarterPlan } from '../sheets.jsx'+import { dayAssignSheet, loadStarterPlan, planToolsSheet } from '../sheets.jsx'import Icon from '../components/Icon.jsx'import { Button } from '../components/ui.jsx'import { glyphOf, DEFAULT_GLYPH } from '../lib/glyphs.js'@@ -19,7 +19,10 @@ export default function Plan() {}return <>- <div className="hdr"><div><h1>{t('Plan')}</h1><div className="sub">{t('Your weekly routine')}</div></div></div>+ <div className="hdr">+ <div><h1>{t('Plan')}</h1><div className="sub">{t('Your weekly routine')}</div></div>+ <button className="iconbtn" onClick={planToolsSheet} aria-label={t('Share your plan')} title={t('Share your plan')}><Icon name="upload" /></button>+ </div><div className="cols"><div><h4 className="sec">{t('Week schedule')}</h4><div className="list" style={{ display: 'flex', flexDirection: 'column' }}>