From af9289dcd9b877aac446ab475e50c8caf1e9531a Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Fri, 24 Jul 2026 01:12:07 +0200 Subject: [PATCH] Plan sharing: export/import a plan file + printable PDF MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New "Share your plan" action in the Plan header (lib/plan-share.js): - Export plan file: a small JSON with just your routines, the week schedule and any custom exercises they use — a friend imports it into their own openGym. Import merges (adds routines with fresh ids, dedupes customs by name+body part, optional "use this schedule"), so nothing they already have is overwritten. - Print / Save as PDF: a clean, one-page-per-plan printout rendered in a hidden iframe; break-inside:avoid keeps every exercise (and each routine that fits) whole, so an exercise never splits across a page. --- frontend/src/lib/plan-share.js | 245 +++++++++++++++++++++++++++++++++ frontend/src/sheets.jsx | 78 ++++++++++- frontend/src/views/Plan.jsx | 7 +- 3 files changed, 326 insertions(+), 4 deletions(-) create mode 100644 frontend/src/lib/plan-share.js diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.js new file mode 100644 index 0000000..ef8b46b --- /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, '"') + +// 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' ? `${esc(ex.bp)}` : '' + return `
${esc(name)}${part}
${esc(scheme(e, unit))}
` + }).join('') + return u.length > 1 + ? `
${esc(t('Superset'))}
${items}
` + : items + }).join('') + const count = t('{0} exercises', r.ex.length).replace('{0}', r.ex.length) + return `
+

${esc(r.name)}

${esc(count)}
+
${rows || `
${esc(t('No exercises yet.'))}
`}
+
` +} + +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) : `${esc(t('Rest'))}` + return `
${esc(t(DAYN[d]))}
${val}
` + }).join('') + return `
${rows}
` +} + +/** 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('') + : `

${esc(t('No routines yet.'))}

` + const sub = [owner, todayISO()].filter(Boolean).map(esc).join(' · ') + return ` +${esc(t('Weekly Training Plan'))} + +
+
+
openGym
+

${esc(t('Weekly Training Plan'))}

+ ${sub ? `
${sub}
` : ''} +
+

${esc(t('Week schedule'))}

+ ${weekHTML(S)} +

${esc(t('Routines'))}

+ ${body} +
${esc(t('Made with openGym'))} · opengym.duarte-santos.ch
+
` +} + +/** + * 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.jsx index 677f7d2..9a271f1 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().S const 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 => ) + +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 <> +

{t('Share your plan')}

+
{t('Send your routines to a friend, or put your week on paper.')}
+ +
{t('A small file a friend imports into their own openGym — routines only, none of your workouts or weigh-ins.')}
+ {!MOBILE && <> +
+ +
{t('A clean one-page-per-plan printout — no exercise ever splits across a page.')}
+ } + {!hasRoutines &&
{t('Add an exercise to a routine first — an empty plan has nothing to share.')}
} +

{t('Got a plan from a friend?')}

+ + + +} + +export const planImportSheet = bundle => ui().openSheet(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 <> +

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

+
+ {t('{0} routines · {1} exercises', bundle.routineCount, bundle.exerciseCount)} + {bundle.scheduledDays > 0 ? ' · ' + t('scheduled on {0} days', bundle.scheduledDays) : ''} +
+
{t('These are added as new routines — nothing you already have is changed.')}
+ {bundle.scheduledDays > 0 &&
+
{t('Use this weekly schedule')}
{t('Replaces your current Mon–Sun assignments.')}
+ +
} + +
+ + +} + /* ============================ 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.jsx index 224bee6..f07dd4b 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 <> -

{t('Plan')}

{t('Your weekly routine')}
+
+

{t('Plan')}

{t('Your weekly routine')}
+ +

{t('Week schedule')}