Skip to content

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.

Routine editor: print a single routine or save it as a PDF (#282)

Duarte Santosf6c5f120308a
diff --git a/frontend/src/lib/plan-print.test.js b/frontend/src/lib/plan-print.test.js
new file mode 100644
index 000000000..1429a44e1
--- /dev/null
+++ b/frontend/src/lib/plan-print.test.js
@@ -0,0 +1,53 @@
+// The printable plan (#149) and one routine on its own page (#282).
+import { describe, it, expect } from 'vitest'
+import { planPrintHTML } from './plan-share.js'
+
+const S = {
+ unit: 'kg',
+ week: { 1: ['push'], 3: ['pull'] },
+ routines: [
+ { id: 'push', name: 'Push day', ex: [
+ { id: '0025', sets: 3, mode: 'reps', reps: 5, weight: 80, note: 'pause on the chest' },
+ { id: '0289', sets: 3, mode: 'reps', reps: 10, weight: 24, sg: 'g' },
+ { id: '0662', sets: 3, mode: 'reps', reps: 12, weight: 0, sg: 'g' },
+ ] },
+ { id: 'pull', name: 'Pull day', ex: [{ id: '0027', sets: 4, mode: 'reps', reps: 8, weight: 60 }] },
+ ],
+}
+const text = html => html.replace(/<style>[\s\S]*?<\/style>/, '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ')
+
+describe('planPrintHTML', () => {
+ it('prints the week and every routine by default', () => {
+ const html = planPrintHTML(S, 'Ana')
+ expect(html).toContain('<title>Weekly Training Plan</title>')
+ expect(text(html)).toContain('Week schedule')
+ expect(text(html)).toContain('Push day')
+ expect(text(html)).toContain('Pull day')
+ })
+
+ it('prints one routine on its own: its name as the title, its exercises, sets × reps, weights and notes', () => {
+ const html = planPrintHTML(S, 'Ana', { routineId: 'push' })
+ expect(html).toContain('<title>Push day</title>')
+ expect(html).toMatch(/<h1>Push day<\/h1>/)
+ const body = text(html)
+ // No week around it, and no other routine.
+ expect(body).not.toContain('Week schedule')
+ expect(body).not.toContain('Weekly Training Plan')
+ expect(body).not.toContain('Pull day')
+ expect(body).toContain('3 exercises · Ana ·')
+ expect(body).toContain('barbell bench press')
+ expect(body).toContain('3 × 5 · 80 kg')
+ expect(body).toContain('pause on the chest')
+ expect(body).toContain('3 × 10 · 24 kg')
+ // The superset is printed as one, as in the weekly printout.
+ expect(html.match(/class="ss"/g)).toHaveLength(1)
+ // The name is the page heading; the routine's block does not repeat it.
+ expect(html.match(/Push day/g)).toHaveLength(2) // <title> and <h1>
+ })
+
+ it('prints nothing it does not have for a routine that is gone', () => {
+ const body = text(planPrintHTML(S, '', { routineId: 'nope' }))
+ expect(body).toContain('No routines yet.')
+ expect(body).not.toContain('Push day')
+ })
+})
diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.js
index affc02f85..e481eb7c6 100644
--- a/frontend/src/lib/plan-share.js
+++ b/frontend/src/lib/plan-share.js
@@ -315,7 +315,9 @@ function units(ex) {
return out
}
-function routineHTML(r, unit) {
+// `bare` leaves out the routine's own heading, for a page that is this one routine and already
+// names it at the top.
+function routineHTML(r, unit, { bare = false } = {}) {
const rows = units(r.ex).map(u => {
const items = u.map(e => {
const ex = EXIDX[e.id]
@@ -330,7 +332,7 @@ function routineHTML(r, unit) {
}).join('')
const count = exCount(r.ex.length)
return `<section class="routine">
- <div class="r-head"><h2>${esc(r.name)}</h2><span class="r-count">${esc(count)}</span></div>
+ ${bare ? '' : `<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>`
}
@@ -347,16 +349,25 @@ function weekHTML(S) {
return `<div class="week">${rows}</div>`
}
-/** Full self-contained HTML for the print/PDF view. */
-export function planPrintHTML(S, owner) {
+/**
+ * Full self-contained HTML for the print/PDF view. With `routineId` it is that one routine on
+ * its own page (#282) — the session you take to the gym, not the week around it — so the week
+ * schedule is left out and the routine's name is the page title.
+ */
+export function planPrintHTML(S, owner, { routineId } = {}) {
const unit = S.unit || 'kg'
- const routines = (S.routines || []).filter(r => r.ex && r.ex.length)
+ const single = routineId ? (S.routines || []).find(r => r.id === routineId) || null : null
+ const routines = routineId ? [single].filter(Boolean) : (S.routines || []).filter(r => r.ex && r.ex.length)
const body = routines.length
- ? routines.map(r => routineHTML(r, unit)).join('')
+ ? routines.map(r => routineHTML(r, unit, { bare: !!single })).join('')
: `<p class="none">${esc(t('No routines yet.'))}</p>`
- const sub = [owner, todayISO()].filter(Boolean).map(esc).join(' · ')
+ const title = single ? single.name : t('Weekly Training Plan')
+ const sub = [single ? exCount(single.ex.length) : null, owner, todayISO()].filter(Boolean).map(esc).join(' · ')
+ const week = routineId ? '' : `<h3 class="block">${esc(t('Week schedule'))}</h3>
+ ${weekHTML(S)}
+ <h3 class="block">${esc(t('Routines'))}</h3>`
return `<!doctype html><html><head><meta charset="utf-8">
-<title>${esc(t('Weekly Training Plan'))}</title>
+<title>${esc(title)}</title>
<style>
@page { margin: 16mm 15mm; }
* { box-sizing: border-box; }
@@ -405,12 +416,10 @@ export function planPrintHTML(S, owner) {
<body><div class="doc">
<header>
<div class="kicker">openGym</div>
- <h1>${esc(t('Weekly Training Plan'))}</h1>
+ <h1>${esc(title)}</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>
+ ${week}
${body}
<footer>${esc(t('Made with openGym'))} · opengym.duarte-santos.ch</footer>
</div></body></html>`
@@ -419,8 +428,9 @@ export function planPrintHTML(S, owner) {
/**
* 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.
+ * `opts` is planPrintHTML's: `{ routineId }` prints a single routine.
*/
-export function printPlan(S, owner) {
+export function printPlan(S, owner, opts) {
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;'
@@ -435,7 +445,7 @@ export function printPlan(S, owner) {
try { w.print() } catch (e) { cleanup() }
}
const doc = ifr.contentWindow.document
- doc.open(); doc.write(planPrintHTML(S, owner)); doc.close()
+ doc.open(); doc.write(planPrintHTML(S, owner, opts)); 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/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx
index 87e924950..f54ec22fe 100644
--- a/frontend/src/views/RoutineEdit.jsx
+++ b/frontend/src/views/RoutineEdit.jsx
@@ -14,6 +14,8 @@ import { glyphOf } from '../lib/glyphs.js'
import { Button, Row, SelectRow, Switch } from '../components/ui.jsx'
import SwipeToDelete from '../components/SwipeToDelete.jsx'
import { copyRoutine, replaceSlotExercise } from '../lib/routines.js'
+import { planPrintHTML, printPlan } from '../lib/plan-share.js'
+import { MOBILE, printHtml } from '../lib/mobile.js'
import { POLICIES_FOR, POLICY_NAME, POLICY_DESC } from '../lib/progression.js'
import BodyMap from '../components/BodyMap.jsx'
import { loadOfRoutine, rankOf, MUSCLE_NAME } from '../lib/muscles.js'
@@ -349,6 +351,14 @@ export default function RoutineEdit() {
exConfigSheet(ex, next, cfg => commit(ex, slot => ({ id: ex.id, sg: slot.sg, ...cfg })), null, r)
}, { title: t('Replace exercise') })
}
+ // This routine on paper (#282): the weekly printout's page for one session, through the same
+ // two print paths — the browser's print dialog (→ Save as PDF) on the web, the native Print
+ // plugin in the app, where the WebView has no window.print().
+ const printRoutine = () => {
+ const owner = useStore.getState().user?.name || ''
+ if (MOBILE) printHtml(planPrintHTML(S, owner, { routineId: id }), r.name).catch(() => { /* dismissed */ })
+ else printPlan(S, owner, { routineId: id })
+ }
const toggleLink = i => edit(ex => {
if (i < 1) return
const cur = ex[i], prev = ex[i - 1]
@@ -464,6 +474,8 @@ export default function RoutineEdit() {
nav('/plan/r/' + copy.id)
}}>{t('Copy routine')}</Button>
<div style={{ height: 10 }} />
+ <Button disabled={!r.ex.length} onClick={printRoutine}>{t('Print / Save as PDF')}</Button>
+ <div style={{ height: 10 }} />
<Button variant="danger" onClick={() => confirmSheet({
title: t('Delete routine?'), message: t('“{0}” and its exercises will be removed.', r.name), confirmText: t('Delete'), danger: true,
onConfirm: () => {
diff --git a/frontend/src/views/RoutineEdit.print.test.jsx b/frontend/src/views/RoutineEdit.print.test.jsx
new file mode 100644
index 000000000..e3b09ab39
--- /dev/null
+++ b/frontend/src/views/RoutineEdit.print.test.jsx
@@ -0,0 +1,76 @@
+// @vitest-environment happy-dom
+// #282: a single routine goes to paper from its editor — the browser's print dialog on the web,
+// the native print flow in the app.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { MemoryRouter, Route, Routes } from 'react-router-dom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const env = vi.hoisted(() => ({ mobile: false, printHtml: null }))
+vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({})) }))
+vi.mock('../sheets.jsx', () => ({ exConfigSheet: vi.fn(), exercisePicker: vi.fn(), glyphPicker: vi.fn(), confirmSheet: vi.fn() }))
+vi.mock('../components/Media.jsx', () => ({ Thumb: () => null }))
+vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))
+vi.mock('../lib/plan-share.js', async importOriginal => ({ ...await importOriginal(), printPlan: vi.fn() }))
+vi.mock('../lib/mobile.js', async importOriginal => {
+ const real = await importOriginal()
+ env.printHtml = vi.fn(() => Promise.resolve())
+ return { ...real, get MOBILE() { return env.mobile }, printHtml: env.printHtml }
+})
+
+import RoutineEdit from './RoutineEdit.jsx'
+import { DEF, useStore } from '../store/useStore.js'
+import { printPlan } from '../lib/plan-share.js'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+let root, host
+
+function mount(ex) {
+ const S = JSON.parse(JSON.stringify(DEF))
+ S.routines = [{ id: 'r1', name: 'Push day', emoji: 'dumbbell', ex }]
+ useStore.setState({ S, user: { id: 'u1', name: 'Ana' } })
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ act(() => root.render(<MemoryRouter initialEntries={['/plan/r/r1']}><Routes><Route path="/plan/r/:id" element={<RoutineEdit />} /></Routes></MemoryRouter>))
+}
+const printButton = () => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === 'Print / Save as PDF')
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ env.mobile = false
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+})
+
+describe('RoutineEdit — print this routine (#282)', () => {
+ it('opens the print dialog with this routine alone on the web', () => {
+ mount([{ id: '0025', sets: 3, mode: 'reps', reps: 5, weight: 80 }])
+ act(() => printButton().click())
+ expect(printPlan).toHaveBeenCalledOnce()
+ const [S, owner, opts] = printPlan.mock.calls[0]
+ expect(S.routines[0].id).toBe('r1')
+ expect(owner).toBe('Ana')
+ expect(opts).toEqual({ routineId: 'r1' })
+ expect(env.printHtml).not.toHaveBeenCalled()
+ })
+
+ it('hands the page to the native print flow in the app, named after the routine', () => {
+ env.mobile = true
+ mount([{ id: '0025', sets: 3, mode: 'reps', reps: 5, weight: 80 }])
+ act(() => printButton().click())
+ expect(printPlan).not.toHaveBeenCalled()
+ expect(env.printHtml).toHaveBeenCalledOnce()
+ const [html, name] = env.printHtml.mock.calls[0]
+ expect(name).toBe('Push day')
+ expect(html).toContain('<title>Push day</title>')
+ expect(html).not.toContain('Week schedule')
+ })
+
+ it('has nothing to print for an empty routine', () => {
+ mount([])
+ expect(printButton().disabled).toBe(true)
+ })
+})