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.

PDF exports: new printout design with the openGym logo, page numbers and break rules; performance report and workout PDF

Duarte Santosa0f0e6bb7993
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/PrintPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/PrintPlugin.java
index 750d2f9cd..955eb25d1 100644
--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/PrintPlugin.java
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/PrintPlugin.java
@@ -38,6 +38,12 @@ public class PrintPlugin extends Plugin {
return;
}
final String jobName = call.getString("name", "openGym");
+ // The sheet starts on the paper people use where the phone is (lib/print-doc.js paperFor);
+ // it can be changed there. Page numbers and margins come from the document's own @page
+ // rules, which this WebView (Chromium) prints.
+ final PrintAttributes.MediaSize media = "letter".equals(call.getString("paper", "a4"))
+ ? PrintAttributes.MediaSize.NA_LETTER
+ : PrintAttributes.MediaSize.ISO_A4;
getActivity().runOnUiThread(() -> {
WebView webView = new WebView(getContext());
@@ -54,7 +60,7 @@ public class PrintPlugin extends Plugin {
PrintDocumentAdapter adapter = view.createPrintDocumentAdapter(jobName);
printManager.print(jobName, adapter,
new PrintAttributes.Builder()
- .setMediaSize(PrintAttributes.MediaSize.ISO_A4)
+ .setMediaSize(media)
.build());
call.resolve();
}
diff --git a/frontend/ios/App/App/PrintPlugin.swift b/frontend/ios/App/App/PrintPlugin.swift
index 3edbad8bf..95c0cad66 100644
--- a/frontend/ios/App/App/PrintPlugin.swift
+++ b/frontend/ios/App/App/PrintPlugin.swift
@@ -1,54 +1,147 @@
import Foundation
import Capacitor
import UIKit
+import WebKit
/**
* Minimal local Capacitor plugin that hands a self-contained HTML document to the iOS system
- * print sheet (Save to Files as PDF, share, a real printer). The printable plan page
- * (lib/plan-share.js planPrintHTML) reaches a PDF this way without bundling a PDF library —
- * UIKit renders it.
+ * print sheet (Save to Files as PDF, share, a real printer). The printouts (lib/print-doc.js:
+ * the plan, a routine, a workout, the performance report) reach a PDF this way without bundling
+ * a PDF library.
+ *
+ * The page is laid out by an off-screen WKWebView, the same WebKit as the app, so its CSS is
+ * honoured: the page-break rules that keep an exercise whole, the inline SVG charts, flex and
+ * grid. (UIMarkupTextPrintFormatter, used before, is a far older HTML importer that ignores
+ * break-inside and @page, so exercises could be cut in half and the text ran to the paper edge.)
+ * WebKit has no @page margin boxes, so the margins and the footer ("opengym.ch" and
+ * "Page 1 of 3") are drawn here by a UIPrintPageRenderer.
*
* Usage from JS:
* import { registerPlugin } from '@capacitor/core';
* const Print = registerPlugin('Print');
- * await Print.printHtml({ html: '<!doctype html>…', name: 'Weekly Training Plan' });
+ * await Print.printHtml({ html: '<!doctype html>…', name: 'Weekly Training Plan',
+ * footer: { left: 'opengym.ch', page: 'Page {0} of {1}' } });
*/
@objc(PrintPlugin)
-public class PrintPlugin: CAPPlugin, CAPBridgedPlugin {
+public class PrintPlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDelegate {
public let identifier = "PrintPlugin"
public let jsName = "Print"
public let pluginMethods: [CAPPluginMethod] = [
CAPPluginMethod(name: "printHtml", returnType: CAPPluginReturnPromise),
]
+ // Held until the print sheet is done: the web view must outlive the layout and the spooling.
+ private var webView: WKWebView?
+ private var pending: CAPPluginCall?
+
@objc func printHtml(_ call: CAPPluginCall) {
guard let html = call.getString("html"), !html.isEmpty else {
call.reject("html is required")
return
}
- let jobName = call.getString("name") ?? "openGym"
-
DispatchQueue.main.async {
- let controller = UIPrintInteractionController.shared
-
- let info = UIPrintInfo(dictionary: nil)
- info.outputType = .general
- info.jobName = jobName
- controller.printInfo = info
-
- // The document carries its own @page margins; keep the formatter's own insets at 0
- // so they don't stack on top.
- let formatter = UIMarkupTextPrintFormatter(markupText: html)
- formatter.perPageContentInsets = .zero
- controller.printFormatter = formatter
-
- controller.present(animated: true) { (_, completed, error) in
- if let error = error {
- call.reject(error.localizedDescription)
- } else {
- call.resolve(["completed": completed])
- }
+ // One print at a time is all the UI can start; a second tap replaces the first.
+ self.pending?.reject("replaced by a newer print")
+ self.cleanUp()
+ self.pending = call
+ // A4 width in points, so the page lays out the way it will print.
+ let view = WKWebView(frame: CGRect(x: 0, y: 0, width: 595, height: 842), configuration: WKWebViewConfiguration())
+ view.isHidden = true
+ view.navigationDelegate = self
+ // In the window (hidden): WebKit only lays out a view that is in one.
+ self.bridge?.viewController?.view.addSubview(view)
+ self.webView = view
+ // The renderer below draws the margins, so the document's own @page margins go.
+ let page = html.replacingOccurrences(of: "</head>", with: "<style>@page { margin: 0 !important; }</style></head>")
+ view.loadHTMLString(page, baseURL: nil)
+ }
+ }
+
+ public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
+ // Fonts and SVG settle a moment after the load event.
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { self.present(webView) }
+ }
+
+ public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
+ finish(error: error.localizedDescription)
+ }
+
+ public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
+ finish(error: error.localizedDescription)
+ }
+
+ private func present(_ webView: WKWebView) {
+ guard let call = pending, webView === self.webView else { return }
+ let footer = call.getObject("footer")
+ let renderer = FooterPageRenderer(
+ left: footer?["left"] as? String ?? "opengym.ch",
+ page: footer?["page"] as? String ?? "{0} / {1}"
+ )
+ renderer.addPrintFormatter(webView.viewPrintFormatter(), startingAtPageAt: 0)
+
+ let info = UIPrintInfo(dictionary: nil)
+ info.outputType = .general
+ info.jobName = call.getString("name") ?? "openGym"
+
+ let controller = UIPrintInteractionController.shared
+ controller.printInfo = info
+ controller.printPageRenderer = renderer
+ controller.present(animated: true) { (_, completed, error) in
+ if let error = error {
+ self.finish(error: error.localizedDescription)
+ } else {
+ self.pending?.resolve(["completed": completed])
+ self.pending = nil
+ self.cleanUp()
}
}
}
+
+ private func finish(error: String) {
+ pending?.reject(error)
+ pending = nil
+ cleanUp()
+ }
+
+ private func cleanUp() {
+ webView?.navigationDelegate = nil
+ webView?.removeFromSuperview()
+ webView = nil
+ }
+}
+
+/// Margins around the page content, and a footer line on every page: the site on the leading
+/// side, the page number on the trailing side, in the reader's language and direction.
+final class FooterPageRenderer: UIPrintPageRenderer {
+ private let left: String
+ private let page: String
+ // 15 mm top and 14 mm sides like the printouts' own @page margins (lib/print-doc.js); the
+ // bottom holds the footer line (footerHeight) above a 7 mm edge.
+ private let insets = UIEdgeInsets(top: 42.5, left: 39.7, bottom: 20, right: 39.7)
+
+ init(left: String, page: String) {
+ self.left = left
+ self.page = page
+ super.init()
+ footerHeight = 28
+ }
+
+ override var printableRect: CGRect { paperRect.inset(by: insets) }
+
+ override func drawFooterForPage(at pageIndex: Int, in footerRect: CGRect) {
+ let attrs: [NSAttributedString.Key: Any] = [
+ .font: UIFont.systemFont(ofSize: 7.5),
+ .foregroundColor: UIColor(red: 0.6, green: 0.63, blue: 0.68, alpha: 1),
+ ]
+ let number = page
+ .replacingOccurrences(of: "{0}", with: String(pageIndex + 1))
+ .replacingOccurrences(of: "{1}", with: String(numberOfPages))
+ let rtl = UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft
+ let leading = NSAttributedString(string: left, attributes: attrs)
+ let trailing = NSAttributedString(string: number, attributes: attrs)
+ let (first, second) = rtl ? (trailing, leading) : (leading, trailing)
+ let y = footerRect.maxY - first.size().height
+ first.draw(at: CGPoint(x: footerRect.minX, y: y))
+ second.draw(at: CGPoint(x: footerRect.maxX - second.size().width, y: y))
+ }
}
diff --git a/frontend/scripts/pdf/check-pdf.py b/frontend/scripts/pdf/check-pdf.py
new file mode 100644
index 000000000..8517b48f5
--- /dev/null
+++ b/frontend/scripts/pdf/check-pdf.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python3
+"""Layout checks for openGym's printed PDFs (scripts/pdf/render-samples.mjs).
+
+Documents rendered with `probe: true` carry invisible marks:
+ ~s:<id>~ / ~e:<id>~ first and last line of a block that must stay on one page
+ (an exercise, a superset, a chart, a summary card row, a list row)
+ ~h:<id>~ a heading; the block it introduces carries ~s:<id>~ too
+ ~split:<id>~ a block too tall for any page; it may break, but only between its rows
+The check finds the page every mark landed on, from the PDF's own text layer, and fails when
+ - a block's start and end are on different pages (it was cut across a page break),
+ - a heading sits on a different page than the first block it introduces (an orphan),
+ - any visible text runs past the page's printable area (overflow).
+With --png it also writes page images next to each PDF (<pdf>-p<N>.png, 110 dpi).
+Needs PyMuPDF: pip install pymupdf
+"""
+import re
+import sys
+
+import fitz # PyMuPDF
+
+MARK = re.compile(r"~([seh]|split):([A-Za-z0-9_.-]+)~")
+
+
+def check(path, png=False, do_check=True):
+ doc = fitz.open(path)
+ pages = {}
+ problems = []
+ for pno, page in enumerate(doc):
+ width = page.rect.width
+ for x0, y0, x1, y1, text, *_ in page.get_text("words"):
+ for kind, ident in MARK.findall(text):
+ pages.setdefault((kind, ident), []).append(pno + 1)
+ if MARK.search(text):
+ continue
+ # 6 mm from the paper edge: text there is outside any sane printable area.
+ if x1 > width - 17 or x0 < 17:
+ problems.append(f"p{pno + 1}: text past the edge: {text!r} x={x0:.0f}..{x1:.0f} of {width:.0f}")
+ if png:
+ page.get_pixmap(dpi=110).save(f"{path[:-4]}-p{pno + 1}.png")
+ blocks = sorted({ident for kind, ident in pages if kind == "s"})
+ for ident in blocks:
+ start = pages.get(("s", ident), [None])[0]
+ end = pages.get(("e", ident), [None])[-1]
+ if end is None:
+ problems.append(f"block {ident}: end mark missing")
+ elif start != end:
+ problems.append(f"block {ident}: split across pages {start}-{end}")
+ head = pages.get(("h", ident))
+ if head and head[0] != start:
+ problems.append(f"heading {ident}: on page {head[0]}, its first block on page {start} (orphan)")
+ n = len(doc)
+ status = "OK" if not problems else "FAIL"
+ if do_check:
+ print(f"{status} {path}: {n} page(s), {len(blocks)} block(s) checked")
+ for p in problems:
+ print(" ", p)
+ else:
+ print(f"{path}: {n} page(s)")
+ return not problems or not do_check
+
+
+def main(argv):
+ png = "--png" in argv
+ do_check = "--no-check" not in argv
+ files = [a for a in argv if not a.startswith("--")]
+ ok = all([check(f, png, do_check) for f in files])
+ return 0 if ok else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/frontend/scripts/pdf/chrome-pdf.mjs b/frontend/scripts/pdf/chrome-pdf.mjs
new file mode 100644
index 000000000..0d31ed74e
--- /dev/null
+++ b/frontend/scripts/pdf/chrome-pdf.mjs
@@ -0,0 +1,91 @@
+// Print HTML files to PDF with a headless Chrome over the DevTools protocol: the same engine
+// as Android's WebView print and desktop Chrome's "Save as PDF". One browser for the whole run,
+// one tab at a time, nothing fetched from the network. Needs Node 22+ (global WebSocket).
+//
+// const chrome = await launchChrome()
+// await chrome.print('file:///…/page.html', 'out.pdf', { paper: 'A4' })
+// await chrome.close()
+import { spawn } from 'node:child_process'
+import { mkdtempSync, readFileSync, rmSync, existsSync, readdirSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+// Paper in inches, as printToPDF takes it.
+export const PAPER = { A4: { w: 8.27, h: 11.69 }, Letter: { w: 8.5, h: 11 } }
+
+function findChrome() {
+ if (process.env.CHROME) return process.env.CHROME
+ const base = join(process.env.HOME || '/root', '.cache/puppeteer/chrome')
+ if (existsSync(base)) {
+ const dirs = readdirSync(base).sort().reverse()
+ for (const d of dirs) {
+ const bin = join(base, d, 'chrome-linux64/chrome')
+ if (existsSync(bin)) return bin
+ }
+ }
+ for (const bin of ['/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser']) if (existsSync(bin)) return bin
+ throw new Error('No Chrome found. Set CHROME=/path/to/chrome.')
+}
+
+export async function launchChrome() {
+ const profile = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'og-pdf-'))
+ const proc = spawn(findChrome(), [
+ '--headless=new', '--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage',
+ '--no-first-run', '--no-default-browser-check', '--disable-extensions',
+ '--host-resolver-rules=MAP * ~NOTFOUND',
+ `--user-data-dir=${profile}`, '--remote-debugging-port=0', 'about:blank',
+ ], { stdio: ['ignore', 'ignore', 'pipe'] })
+ let stderr = ''
+ proc.stderr.on('data', d => { stderr += d })
+ const portFile = join(profile, 'DevToolsActivePort')
+ for (let i = 0; i < 200 && !existsSync(portFile); i++) await new Promise(r => setTimeout(r, 100))
+ if (!existsSync(portFile)) { proc.kill('SIGKILL'); throw new Error('Chrome did not start:\n' + stderr.slice(-2000)) }
+ const [port] = readFileSync(portFile, 'utf8').split('\n')
+ const targets = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()
+ const page = targets.find(t => t.type === 'page')
+ const ws = new WebSocket(page.webSocketDebuggerUrl)
+ await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej })
+ let seq = 0
+ const pending = new Map()
+ const waiters = []
+ ws.onmessage = ev => {
+ const msg = JSON.parse(ev.data)
+ if (msg.id && pending.has(msg.id)) {
+ const { res, rej } = pending.get(msg.id); pending.delete(msg.id)
+ msg.error ? rej(new Error(msg.error.message)) : res(msg.result)
+ } else if (msg.method) {
+ for (const w of waiters.slice()) if (w.method === msg.method) { waiters.splice(waiters.indexOf(w), 1); w.res(msg.params) }
+ }
+ }
+ const send = (method, params = {}) => new Promise((res, rej) => { const id = ++seq; pending.set(id, { res, rej }); ws.send(JSON.stringify({ id, method, params })) })
+ const once = method => new Promise(res => waiters.push({ method, res }))
+ await send('Page.enable')
+ await send('Runtime.enable')
+
+ return {
+ send,
+ /** Load `url`, wait for it and its fonts, and write a PDF of it to `out`. */
+ async print(url, out, { paper = 'A4' } = {}) {
+ const loaded = once('Page.loadEventFired')
+ await send('Page.navigate', { url })
+ await loaded
+ await send('Runtime.evaluate', { expression: 'document.fonts.ready.then(() => true)', awaitPromise: true })
+ const size = PAPER[paper]
+ // The document's own @page margins win; these are only Chrome's fallback.
+ const { data } = await send('Page.printToPDF', {
+ paperWidth: size.w, paperHeight: size.h, printBackground: true,
+ displayHeaderFooter: false, preferCSSPageSize: false,
+ marginTop: 0.4, marginBottom: 0.4, marginLeft: 0.4, marginRight: 0.4,
+ })
+ writeFileSync(out, Buffer.from(data, 'base64'))
+ return out
+ },
+ async close() {
+ try { ws.close() } catch { /* */ }
+ proc.kill('SIGTERM')
+ await new Promise(r => setTimeout(r, 300))
+ try { proc.kill('SIGKILL') } catch { /* */ }
+ rmSync(profile, { recursive: true, force: true })
+ },
+ }
+}
diff --git a/frontend/scripts/pdf/fixture.mjs b/frontend/scripts/pdf/fixture.mjs
new file mode 100644
index 000000000..da475f0ae
--- /dev/null
+++ b/frontend/scripts/pdf/fixture.mjs
@@ -0,0 +1,71 @@
+// A worst-case profile for the PDF exports: the 12-week demo history plus one routine and one
+// workout built to break a printout. Fifteen exercises, the longest German catalogue names, a
+// custom exercise with a sentence for a name, supersets, drop-sets, timed and cardio work, notes
+// that wrap, and up to ten sets in one exercise. Nothing here touches exercise media.
+
+const LONG_CUSTOM = {
+ id: 'pdf-long-custom', custom: true, eq: 'dumbbell', bp: 'shoulders', tg: 'delts',
+ n: 'Single-arm half-kneeling landmine press with a two-second pause and slow eccentric (left side first)',
+}
+
+// [id, sets, reps, weight, extra]
+const PLAN = [
+ ['0025', 5, 5, 100, { note: 'Pause every rep on the chest. Shoulder blades pinned, feet planted, and breathe before the press.' }],
+ ['11718', 4, 12, 35, { sg: 'a' }],
+ ['5448', 4, 12, 60, { sg: 'a' }],
+ ['6515', 4, 10, 40, { repsMin: 8 }],
+ ['3096', 3, 12, 70, { intensifier: { type: 'dropset', count: 2, pct: 20 } }],
+ ['1679', 3, 12, 14, { sg: 'b' }],
+ ['10670', 3, 10, 30, { sg: 'b' }],
+ ['6517', 3, 10, 40, {}],
+ ['0027', 4, 8, 60, { intensifier: { type: 'restpause', totalReps: 20, restSec: 15 } }],
+ ['pdf-long-custom', 3, 8, 22.5, { note: 'Left side first, then right. Stop one rep short of failure.' }],
+ ['4950', 3, 12, 0, {}],
+ ['0043', 10, 3, 140, { note: 'Ten singles-ish triples, climbing.' }],
+ ['0085', 3, 10, 60, {}],
+ ['0464', 3, 45, 0, { mode: 'time', sec: 45 }],
+ ['3567', 2, 10, 0, {}],
+]
+
+function routineEx() {
+ return PLAN.map(([id, sets, reps, weight, extra]) => {
+ const e = { id, sets, mode: 'reps', reps, weight, ...extra }
+ if (extra.mode === 'time') { e.mode = 'time'; e.sec = extra.sec; delete e.reps }
+ return e
+ })
+}
+
+function workoutEntries() {
+ return PLAN.map(([id, sets, reps, weight, extra], i) => {
+ const rows = []
+ if (weight > 40) rows.push({ w: Math.round(weight * 0.5), r: 8, done: true, warmup: true })
+ for (let s = 0; s < sets; s++) {
+ if (extra.mode === 'time') rows.push({ sec: extra.sec + s * 5, done: true })
+ else rows.push({ w: weight + (id === '0043' ? s * 2.5 : 0), r: Math.max(1, reps - (s > 1 ? 1 : 0)), done: true, rir: s === sets - 1 ? 1 : 2 })
+ }
+ const entry = { id, sets: rows, ...(extra.sg ? { sg: extra.sg } : {}), ...(extra.note ? { note: extra.note } : {}) }
+ if (i === 0 || i === 11) entry.topW = weight
+ return entry
+ })
+}
+
+/** Adds the stress-test routine and workout to a demo state, in place, and returns it. */
+export function addStressCase(S, { now = Date.now() } = {}) {
+ S.customEx = [...(S.customEx || []), LONG_CUSTOM]
+ S.routines = [...S.routines, { id: 'pdf-long', name: 'Ganzkörper Hypertrophie Donnerstag (lang)', emoji: 'dumbbell', ex: routineEx() }]
+ S.week = { ...(S.week || {}), 4: ['pdf-long'] }
+ const day = new Date(now - 86400000); day.setHours(18, 5, 0, 0)
+ const start = day.getTime()
+ const iso = day.toISOString().slice(0, 10)
+ const w = {
+ id: 'pdf-long-w', d: iso, start, end: start + 104 * 60000, routineId: 'pdf-long',
+ name: 'Ganzkörper Hypertrophie Donnerstag (lang)', bw: 80.4,
+ entries: workoutEntries(), prs: ['0025', '0043', 'pdf-long-custom'],
+ note: 'Felt strong today. Gym was packed, so the supersets took a while. Next time: start with the deadlifts.',
+ }
+ S.workouts = [...S.workouts.filter(x => x.d <= iso), w, ...S.workouts.filter(x => x.d > iso)]
+ return S
+}
+
+export const STRESS_ROUTINE_ID = 'pdf-long'
+export const STRESS_WORKOUT_ID = 'pdf-long-w'
diff --git a/frontend/scripts/pdf/render-samples.mjs b/frontend/scripts/pdf/render-samples.mjs
new file mode 100644
index 000000000..c1ee6f00e
--- /dev/null
+++ b/frontend/scripts/pdf/render-samples.mjs
@@ -0,0 +1,98 @@
+#!/usr/bin/env node
+// Render the PDF exports of a stress-test profile (scripts/pdf/fixture.mjs) with headless Chrome,
+// in several languages and paper sizes, and (with --check) assert that no exercise block, chart or
+// list row is split across a page, that no heading is left alone at the bottom of a page and that
+// nothing runs past the page edge. The check reads the PDF itself (scripts/pdf/check-pdf.py, PyMuPDF):
+// the documents are rendered with invisible probe marks at the top and bottom of every block that
+// must stay whole, and the check finds the page each mark landed on.
+//
+// node scripts/pdf/render-samples.mjs --out /tmp/pdf [--langs en,de,ar] [--paper A4,Letter] [--check] [--png]
+//
+// Needs Node 22, a Chrome (CHROME=… or the Puppeteer cache) and, for --check/--png, python3 with
+// PyMuPDF (pip install pymupdf). Runs one browser, one page at a time: light on the machine.
+import { createServer } from 'vite'
+import { mkdirSync, writeFileSync, existsSync } from 'node:fs'
+import { join, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { spawnSync } from 'node:child_process'
+import { launchChrome } from './chrome-pdf.mjs'
+import { addStressCase, STRESS_ROUTINE_ID, STRESS_WORKOUT_ID } from './fixture.mjs'
+
+const here = fileURLToPath(new URL('.', import.meta.url))
+const root = resolve(here, '../..')
+const arg = (name, def) => {
+ const i = process.argv.indexOf('--' + name)
+ return i < 0 ? def : process.argv[i + 1]
+}
+const flag = name => process.argv.includes('--' + name)
+const out = resolve(arg('out', join(root, 'pdf-samples')))
+const langs = arg('langs', 'en,de,ar').split(',').filter(Boolean)
+const papers = arg('paper', 'A4').split(',').filter(Boolean)
+const only = arg('only', '')
+const owner = arg('owner', 'Ana Duarte')
+mkdirSync(out, { recursive: true })
+
+const server = await createServer({
+ root, configFile: false, logLevel: 'error', appType: 'custom',
+ server: { middlewareMode: true, hmr: false, ws: false },
+ define: { __APP_VERSION__: JSON.stringify('dev') },
+})
+const load = p => server.ssrLoadModule(p)
+const core = await load('/src/lib/i18n-core.js')
+const { registerCustom } = await load('/src/lib/exercises.js')
+const { buildDemoState } = await load('/src/lib/demoSeed.js')
+const plan = await load('/src/lib/plan-share.js')
+const hasReport = existsSync(join(root, 'src/lib/report-print.js'))
+const report = hasReport ? await load('/src/lib/report-print.js') : null
+
+async function useLang(l) {
+ const base = core.baseLang(l)
+ const pack = async p => { try { return (await load(p)).default } catch { return null } }
+ const dict = base === 'en' ? {} : await pack(`/src/locales/${base}.js`)
+ const names = base === 'en' || !core.EXERCISE_NAME_LANGS.includes(base) ? null : await pack(`/src/exercise-names/${base}.js`)
+ core._setLangState(l, core.derivePack(l, dict || {}), null, core.derivePack(l, names), true, false)
+}
+
+// A fixed "now" keeps the samples comparable from run to run.
+const S = addStressCase(buildDemoState())
+registerCustom(S.customEx)
+const W = S.workouts.find(w => w.id === STRESS_WORKOUT_ID)
+
+const docs = [
+ ['plan-week', () => plan.planPrintHTML(S, owner, { probe: true })],
+ ['plan-routine', () => plan.planPrintHTML(S, owner, { routineId: STRESS_ROUTINE_ID, probe: true })],
+]
+if (report) {
+ docs.push(['workout', () => report.workoutPrintHTML(S, W, { owner, probe: true })])
+ docs.push(['report-7d', () => report.reportPrintHTML(S, { range: '7d', owner, probe: true })])
+ docs.push(['report-4w', () => report.reportPrintHTML(S, { range: '4w', owner, probe: true })])
+ docs.push(['report-3m', () => report.reportPrintHTML(S, { range: '3m', owner, probe: true })])
+}
+
+const chrome = await launchChrome()
+const made = []
+try {
+ for (const l of langs) {
+ await useLang(l)
+ for (const [name, html] of docs) {
+ if (only && !only.split(',').includes(name)) continue
+ const file = join(out, `${name}-${l}.html`)
+ writeFileSync(file, html())
+ for (const paper of papers) {
+ const pdf = join(out, `${name}-${l}-${paper}.pdf`)
+ await chrome.print('file://' + file, pdf, { paper })
+ made.push(pdf)
+ console.log('wrote', pdf)
+ }
+ }
+ }
+} finally {
+ await chrome.close()
+ await server.close()
+}
+
+if (flag('check') || flag('png')) {
+ const args = [join(here, 'check-pdf.py'), ...(flag('png') ? ['--png'] : []), ...(flag('check') ? [] : ['--no-check']), ...made]
+ const r = spawnSync('python3', args, { stdio: 'inherit' })
+ process.exit(r.status ?? 1)
+}
diff --git a/frontend/src/components/ReportSheet.jsx b/frontend/src/components/ReportSheet.jsx
new file mode 100644
index 000000000..c91625d8a
--- /dev/null
+++ b/frontend/src/components/ReportSheet.jsx
@@ -0,0 +1,49 @@
+// "Performance report (PDF)": pick a stretch of days, get everything it adds up to on paper
+// (lib/report-print.js). Opened from Stats, History and Settings > Data.
+import { useState } from 'react'
+import { useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { t, tn } from '../lib/i18n.js'
+import { todayISO, fmtDate } from '../lib/format.js'
+import { reportRange, inRange } from '../lib/report.js'
+import { printReport } from '../lib/report-print.js'
+import { Button, Segmented, Row } from './ui.jsx'
+
+export function ReportSheet({ close }) {
+ const S = useStore(s => s.S)
+ const today = todayISO()
+ const [range, setRange] = useState('4w')
+ const [from, setFrom] = useState(() => reportRange('4w', { today }).from)
+ const [to, setTo] = useState(today)
+ const r = reportRange(range, { from, to, today })
+ const count = inRange(S, r).length
+ const make = () => {
+ const owner = useStore.getState().user?.name || ''
+ close()
+ printReport(S, { range, from: r.from, to: r.to, owner })
+ }
+ return <>
+ <h3>{t('Performance report')}</h3>
+ <div className="muted small" style={{ marginBottom: 12 }}>
+ {t('Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.')}
+ </div>
+ <Segmented value={range} onChange={setRange} options={[
+ { value: '7d', label: t('7 days') },
+ { value: '4w', label: t('4 weeks') },
+ { value: '3m', label: t('3 months') },
+ { value: 'custom', label: t('Custom') },
+ ]} />
+ {range === 'custom' && <div style={{ marginTop: 10 }}>
+ <Row icon="calendar" title={t('From')}>
+ <input type="date" className="timef" value={from} max={to || today} onChange={e => setFrom(e.target.value)} /></Row>
+ <Row icon="calendar" title={t('To')}>
+ <input type="date" className="timef" value={to} min={from} max={today} onChange={e => setTo(e.target.value)} /></Row>
+ </div>}
+ <div className="small dim" style={{ margin: '10px 2px 14px' }} data-report-summary>
+ {(r.from === r.to ? fmtDate(r.from, true, true) : fmtDate(r.from, false, true) + ' – ' + fmtDate(r.to, false, true)) + ' · ' + tn('{0} workout', '{0} workouts', count)}
+ </div>
+ <Button variant="primary" icon="note" onClick={make}>{t('Create PDF')}</Button>
+ </>
+}
+
+export const reportSheet = () => useUI.getState().openSheet(close => <ReportSheet close={close} />)
diff --git a/frontend/src/components/ReportSheet.test.jsx b/frontend/src/components/ReportSheet.test.jsx
new file mode 100644
index 000000000..9416449c5
--- /dev/null
+++ b/frontend/src/components/ReportSheet.test.jsx
@@ -0,0 +1,62 @@
+// @vitest-environment happy-dom
+// "Performance report (PDF)": the range picker says what it will cover and hands that range to
+// the printout, the four-week default included.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+const mocks = vi.hoisted(() => ({ S: null, printReport: vi.fn() }))
+vi.mock('../store/useStore.js', () => {
+ const snap = () => ({ S: mocks.S, user: { name: 'Ana' } })
+ const useStore = selector => (selector ? selector(snap()) : snap())
+ useStore.getState = snap
+ return { useStore }
+})
+vi.mock('../lib/report-print.js', () => ({ printReport: (...a) => mocks.printReport(...a) }))
+
+const { ReportSheet } = await import('./ReportSheet.jsx')
+const { todayISO } = await import('../lib/format.js')
+const { reportRange } = await import('../lib/report.js')
+
+let root, host, close
+const iso = n => { const d = new Date(); d.setHours(12); d.setDate(d.getDate() - n); return d.toISOString().slice(0, 10) }
+
+beforeEach(() => {
+ mocks.printReport.mockReset()
+ mocks.S = { unit: 'kg', workouts: [{ id: 'a', d: iso(2), entries: [] }, { id: 'b', d: iso(20), entries: [] }, { id: 'c', d: iso(60), entries: [] }], bodyweight: [] }
+ close = vi.fn()
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ act(() => root.render(<ReportSheet close={close} />))
+})
+afterEach(() => { act(() => root.unmount()); host.remove() })
+
+const button = text => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text)
+const summary = () => host.querySelector('[data-report-summary]').textContent
+
+describe('ReportSheet', () => {
+ it('starts on four weeks and counts the workouts in it', () => {
+ expect(button('4 weeks').getAttribute('aria-pressed')).toBe('true')
+ expect(summary()).toContain('2 workouts')
+ })
+
+ it('switches range and prints exactly that range for the signed-in person', () => {
+ act(() => button('7 days').click())
+ expect(summary()).toContain('1 workout')
+ act(() => button('Create PDF').click())
+ expect(close).toHaveBeenCalled()
+ const [S, opts] = mocks.printReport.mock.calls[0]
+ expect(S).toBe(mocks.S)
+ expect(opts).toMatchObject({ range: '7d', owner: 'Ana', from: reportRange('7d', { today: todayISO() }).from, to: todayISO() })
+ })
+
+ it('custom shows two dates', () => {
+ act(() => button('Custom').click())
+ expect(host.querySelectorAll('input[type="date"]')).toHaveLength(2)
+ act(() => button('3 months').click())
+ expect(summary()).toContain('3 workouts')
+ })
+})
diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.js
index c77b93f0f..c9933708a 100644
--- a/frontend/src/lib/mobile.js
+++ b/frontend/src/lib/mobile.js
@@ -290,10 +290,14 @@ export async function shareExportBlob(blob, filename) {
// platform renders the PDF, so no PDF library rides in the bundle. The local `Print` plugin is
// registered natively (android MainActivity, ios PrintPlugin.m); on the web build this file's
// callers gate on MOBILE and never reach here.
-export async function printHtml(html, name) {
+// `paper` ('a4' | 'letter') is the size the sheet starts on (lib/print-doc.js paperFor); Android
+// uses it, iOS takes the printer's or the region's own default. `footer` is the bottom line the
+// iOS plugin draws itself, since WebKit has no @page margin boxes: { left, page } with {0}/{1}
+// in `page` for the page number and the page count.
+export async function printHtml(html, name, { paper = 'a4', footer } = {}) {
const { registerPlugin } = await import('@capacitor/core')
const Print = registerPlugin('Print')
- await Print.printHtml({ html, name })
+ await Print.printHtml({ html, name, paper, ...(footer ? { footer } : {}) })
}
// "Auto-backup on changes" (Settings): a dated snapshot dropped into Documents/openGym/ —
diff --git a/frontend/src/lib/plan-print.test.js b/frontend/src/lib/plan-print.test.js
index 35284f433..3fabbbf3c 100644
--- a/frontend/src/lib/plan-print.test.js
+++ b/frontend/src/lib/plan-print.test.js
@@ -35,7 +35,10 @@ describe('planPrintHTML', () => {
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 ·')
+ // The masthead: the openGym logo, who it is for, the count under the title.
+ expect(html).toContain('class="logo-mark"')
+ expect(html).toMatch(/<div class="mast-meta"><b>Ana<\/b><br>/)
+ expect(html).toMatch(/<div class="facts">3 exercises<\/div>/)
expect(body).toContain('barbell bench press')
expect(body).toContain('3 × 5 · 80 kg')
expect(body).toContain('pause on the chest')
@@ -95,3 +98,44 @@ describe('planPrintHTML prints the exercise as it is prescribed', () => {
expect(text(html)).toContain('Dropsatz 2×')
})
})
+
+// The redesign (v1.4.3): what keeps a printout readable across pages.
+describe('planPrintHTML page breaks', () => {
+ const many = { unit: 'kg', week: { 1: ['r'] }, routines: [{ id: 'r', name: 'Long day', ex: Array.from({ length: 6 }, (_, i) => ({ id: '0025', sets: 3, mode: 'reps', reps: 5, weight: 60 + i, ...(i === 2 || i === 3 ? { sg: 's' } : {}) })) }] }
+
+ it('keeps every exercise and superset in a block of its own, and the routine heading with the first one', () => {
+ const html = planPrintHTML(many, '')
+ // 6 exercises, two of them a superset: 5 blocks, plus the week table.
+ expect(html.match(/<div class="keep">/g)).toHaveLength(6)
+ // The routine heading is inside the first exercise block, never on its own.
+ expect(html).toMatch(/<div class="keep"><h3 class="sec-h">Routines<\/h3><div class="r-head"><h2>Long day<\/h2>[^]*?<div class="ex">/)
+ // The whole routine is not one unbreakable block any more (it left pages blank).
+ expect(html).not.toMatch(/\.routine \{[^}]*break-inside: avoid/)
+ })
+
+ it('numbers the exercises and gives the single-routine sheet a box per set', () => {
+ const html = planPrintHTML(many, '', { routineId: 'r' })
+ expect(html.match(/<div class="ex-num">/g)).toHaveLength(6)
+ expect(html.match(/<div class="ticks">(<i><\/i>){3}<\/div>/g)).toHaveLength(6)
+ expect(planPrintHTML(many, '')).not.toContain('class="ticks"')
+ })
+
+ it('puts the English title of a translated name on its own line instead of in parentheses', () => {
+ _setLangState('de', {}, null, { '0025': 'Bankdrücken mit Langhantel' })
+ try {
+ const html = planPrintHTML(many, '', { routineId: 'r' })
+ expect(html).toContain('>Bankdrücken mit Langhantel <span class="part">')
+ expect(html).toContain('<div class="ex-en">barbell bench press</div>')
+ } finally { _setLangState('en', {}, null, null) }
+ })
+
+ it('carries page numbers in the reader’s language and no probe marks unless asked', () => {
+ _setLangState('de', { 'Page {0} of {1}': 'Seite {0} von {1}' }, null, null)
+ try {
+ const html = planPrintHTML(many, '')
+ expect(html).toContain('@bottom-right { content: "Seite " counter(page) " von " counter(pages); }')
+ expect(html).not.toContain('class="probe"')
+ expect(planPrintHTML(many, '', { probe: true })).toContain('<i class="probe">~s:')
+ } finally { _setLangState('en', {}, null, null) }
+ })
+})
diff --git a/frontend/src/lib/plan-share.js b/frontend/src/lib/plan-share.js
index 72b760cca..9754e8758 100644
--- a/frontend/src/lib/plan-share.js
+++ b/frontend/src/lib/plan-share.js
@@ -17,12 +17,13 @@ import { isPyramid, normalizePyramid, normalizePyramidRest, normalizePyramidWeig
import { isBackoff } from './backoff.js'
import { dbLoadOf } from './dumbbells.js'
import { MAX_TRIPLE_SETS } from './progression.js'
-import { uid, todayISO, DAYN, weekOrder, weekStartOf, exCount } from './format.js'
-import { t, exerciseNameFor, exerciseNameClass, getLang, RTL_LANGS } from './i18n-core.js'
+import { uid, todayISO, DAYN, weekOrder, weekStartOf, exCount, routineCount } from './format.js'
+import { t, exerciseNameFor, exerciseNameClass } from './i18n-core.js'
import { convertWeight } from './units.js'
import { fmtSpeed, speedUnitOf } from './speed.js'
import { MUSCLES, inMuscleOrder } from './muscles.js'
import { SG_NAME_MAX } from './superset-meta.js'
+import { esc, printShell, printDocument, probeMarks } from './print-doc.js'
const PLAN_FMT = 1
const WEEK_DAYS = [1, 2, 3, 4, 5, 6, 0] // every getDay() index; only the reader's own
@@ -350,24 +351,27 @@ export function mergePlan(s, bundle, { schedule } = {}) {
/* ------------------------------- printable PDF ------------------------------- */
-const esc = str => String(str == null ? '' : str)
- .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
-
// One exercise's scheme, e.g. "3 × 8–12 · 60 kg · drop-set 1× −20%", "3 × 0:45" or
// "2 × 20 min @ 8 km/h" — the speed in the profile's unit (lib/speed.js), like the weight. The
// reps half is exLine's, so a double-progression range prints as the range it is ("8–12", not
// the top alone) and a per-side split reads "8/side" exactly as the routine editor shows it.
-function scheme(e, unit, speedUnit) {
+// As parts: the sets line, then what comes on top of it, each printed on a line of its own so the
+// sets line never wraps in the middle of "4 × 12 · 35 kg".
+function schemeParts(e, unit, speedUnit) {
const sets = e.sets || 1
const mode = modeOf(e)
if (mode === 'cardio') {
const body = `${e.min || 20} min @ ${fmtSpeed(e.speed || 8, speedUnit)}`
- return sets > 1 ? `${sets} × ${body}` : body
+ return [sets > 1 ? `${sets} × ${body}` : body]
}
const line = exLine({ ...e, reps: e.reps ?? 10 }, unit, speedUnit)
const extras = [intensifierLine(e.intensifier), e.lastToFailure === true ? t('Last set to failure') : ''].filter(Boolean)
- return [line, ...extras].join(' · ')
+ return [line, ...extras]
}
+// The extra lines keep their " · " in the text (hidden on paper), so copied text reads as one line.
+const schemeHTML = parts => parts.map((p, i) => i === 0
+ ? `<span class="s-main">${esc(p)}</span>`
+ : `<span class="s-x"><span class="sep"> · </span>${esc(p)}</span>`).join('')
// A drop-set or rest-pause is how the exercise is prescribed, so the printout names it — the
// sheet at the rack otherwise reads as plain straight sets.
@@ -390,142 +394,131 @@ function units(ex) {
return out
}
-// `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, speedUnit } = {}) {
- const rows = units(r.ex).map(u => {
- const items = u.map(e => {
- const ex = EXIDX[e.id]
- const name = ex ? exerciseNameFor(ex) : t('Unknown exercise')
- // Translated, and set apart by a real space: glued to the name, "capitalize" read the two as
- // one word and printed "Curlupper Legs".
- const part = ex && ex.bp && ex.bp !== 'cardio' ? ` <span class="part">${esc(t(ex.bp))}</span>` : ''
- const note = e.note ? `<div class="ex-note">${esc(e.note)}</div>` : ''
- return `<div class="ex"><div class="ex-row"><div class="ex-n ${ex ? exerciseNameClass(ex) : ''}">${esc(name)}${part}</div><div class="ex-s">${esc(scheme(e, unit, speedUnit))}</div></div>${note}</div>`
- }).join('')
- return u.length > 1
- ? `<div class="ss"><div class="ss-tag">${esc(t('Superset'))}</div><div class="ss-items">${items}</div></div>`
+/**
+ * An exercise's printed name: the display name, and on a line of its own the English title the
+ * app adds in parentheses to a translated one ("Bankdrücken mit Langhantel (barbell bench press)"),
+ * so a long German name wraps once instead of three times. Shared with the workout printouts.
+ */
+export function printedName(ex, fallback) {
+ if (!ex) return { name: fallback || t('Unknown exercise'), en: '', cls: '' }
+ const full = exerciseNameFor(ex)
+ const suffix = ` (${ex.n})`
+ const split = ex.n && full !== ex.n && full.endsWith(suffix)
+ return { name: split ? full.slice(0, -suffix.length) : full, en: split ? ex.n : '', cls: exerciseNameClass(ex) }
+}
+
+// One exercise row. `n` is its number in the routine; `ticks` draws a box per set to tick off at
+// the gym (the single-routine sheet, which is the one you take with you).
+function exerciseHTML(e, n, unit, { speedUnit, ticks }) {
+ const ex = EXIDX[e.id]
+ const { name, en, cls } = printedName(ex)
+ // Translated, and set apart by a real space: glued to the name, "capitalize" read the two as
+ // one word and printed "Curlupper Legs".
+ const part = ex && ex.bp && ex.bp !== 'cardio' ? ` <span class="part">${esc(t(ex.bp))}</span>` : ''
+ const boxes = ticks ? `<div class="ticks">${'<i></i>'.repeat(Math.min(12, Math.max(1, e.sets || 1)))}</div>` : ''
+ return `<div class="ex"><div class="ex-num">${n}</div><div class="ex-main">`
+ + `<div class="ex-n ${ex ? cls : ''}">${esc(name)}${part}</div>`
+ + (en ? `<div class="ex-en">${esc(en)}</div>` : '')
+ + (e.note ? `<div class="ex-note">${esc(e.note)}</div>` : '')
+ + `</div><div class="ex-s">${schemeHTML(schemeParts(e, unit, speedUnit))}${boxes}</div></div>`
+}
+
+// A routine as a run of blocks that each stay whole on a page: one per exercise, one per superset.
+// The routine's heading (and, for the first routine, the section heading above it) travels inside
+// the first block, so it can never be stranded at the bottom of a page with its exercises overleaf.
+// The routine itself may run over a page: holding all of it together left whole pages blank.
+function routineHTML(r, unit, { bare = false, speedUnit, ticks = false, lead = '', m, key }) {
+ let n = 0
+ const list = units(r.ex)
+ const blocks = list.map((u, bi) => {
+ const items = u.map(e => exerciseHTML(e, ++n, unit, { speedUnit, ticks })).join('')
+ const body = u.length > 1
+ ? `<div class="ss"><div class="ss-tag">${esc(t('Superset'))}</div>${items}</div>`
: items
- }).join('')
- const count = exCount(r.ex.length)
- return `<section class="routine">
- ${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>`
+ const id = `${key}-${bi}`
+ const head = bi === 0
+ ? lead + (bare ? '' : `${m.h(id)}<div class="r-head"><h2>${esc(r.name)}</h2><span class="r-count">${esc(exCount(r.ex.length))}</span></div>`)
+ : ''
+ return `<div class="keep">${m.s(id)}${head}${body}${m.e(id)}</div>`
+ })
+ if (!blocks.length) blocks.push(`<div class="keep">${lead}${bare ? '' : `<div class="r-head"><h2>${esc(r.name)}</h2></div>`}<div class="none">${esc(t('No exercises yet.'))}</div></div>`)
+ return `<section class="routine">${blocks.join('')}</section>`
}
-function weekHTML(S) {
+function weekHTML(S, m) {
// The printout is read by whoever exported it, so the week runs in their order.
const rows = weekOrder(weekStartOf(S)).map(d => {
const names = [].concat(S.week?.[d] || [])
.map(id => S.routines.find(x => x.id === id)?.name)
.filter(Boolean)
const val = names.length ? esc(deriveSessionName(names)) : `<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>`
+ return `<tr><th scope="row">${esc(t(DAYN[d]))}</th><td>${val}</td></tr>`
}).join('')
- return `<div class="week">${rows}</div>`
+ return `<div class="keep">${m.s('week')}${m.h('week')}<h3 class="sec-h first">${esc(t('Week schedule'))}</h3><table class="week">${rows}</table>${m.e('week')}</div>`
}
+const PLAN_CSS = `
+ .routine { margin-bottom: 8pt; }
+ .r-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10pt; margin: 14pt 0 2pt; padding-bottom: 4pt; border-bottom: 1.5px solid var(--ink); }
+ .r-head h2 { font-size: 13pt; letter-spacing: -.01em; margin: 0; overflow-wrap: anywhere; }
+ .r-count { font-size: 8pt; color: var(--muted); white-space: nowrap; }
+
+ .ex { display: flex; align-items: flex-start; gap: 8pt; padding: 6pt 0; border-bottom: 1px solid var(--rule-soft); }
+ .ex-num { flex: none; width: 14pt; height: 14pt; margin-top: 1pt; border-radius: 50%; background: var(--tint); color: var(--muted);
+ font-size: 7pt; font-weight: 700; line-height: 14pt; text-align: center; }
+ .ex-main { flex: 1 1 auto; min-width: 0; }
+ .ex-n { font-weight: 600; overflow-wrap: anywhere; }
+ .ex-n.capitalize { text-transform: capitalize; }
+ .ex-n .part { display: inline-block; text-transform: none; color: var(--faint); font-weight: 400; font-size: 8pt; margin-inline-start: 3pt; }
+ .ex-n .part::first-letter { text-transform: uppercase; }
+ .ex-en { color: var(--faint); font-size: 8pt; text-transform: capitalize; overflow-wrap: anywhere; }
+ .ex-note { color: var(--ink-2); font-size: 8.5pt; margin-top: 2pt; font-style: italic; }
+ .ex-s { flex: none; max-width: 46%; text-align: end; color: var(--ink-2); font-weight: 500; }
+ .ex-s .s-main { display: block; white-space: nowrap; }
+ .ex-s .s-x { display: block; font-size: 8pt; font-weight: 400; color: var(--muted); }
+ .ex-s .sep { display: none; }
+ .ticks { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 3pt; margin-top: 4pt; }
+ .ticks i { display: block; width: 9pt; height: 9pt; border: 1px solid #c4c9d2; border-radius: 2pt; }
+
+ .ss { border-inline-start: 2.5pt solid var(--lime); padding-inline-start: 8pt; margin: 4pt 0; }
+ .ss-tag { font-size: 7pt; letter-spacing: .1em; text-transform: uppercase; color: var(--lime-ink); font-weight: 700; padding-top: 5pt; }
+ .ss .ex:last-child { border-bottom: 0; }
+
+ table.week th { width: 32%; text-transform: none; letter-spacing: 0; font-size: 9pt; color: var(--ink); font-weight: 600; padding: 4pt 8pt 4pt 0; border-bottom: 1px solid var(--rule-soft); }
+ table.week td { padding: 4pt 0; }
+ table.week tr:last-child th, table.week tr:last-child td { border-bottom: 0; }
+ .rest { color: var(--faint); }
+`
+
/**
* 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.
+ * schedule is left out and the routine's name is the page title. `probe` is for the layout check
+ * (lib/print-doc.js probeMarks), never set in the app.
*/
-export function planPrintHTML(S, owner, { routineId } = {}) {
+export function planPrintHTML(S, owner, { routineId, probe = false } = {}) {
+ const m = probeMarks(probe)
const unit = S.unit || 'kg'
+ const speedUnit = speedUnitOf(S)
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 lead = routineId ? '' : `<h3 class="sec-h">${esc(t('Routines'))}</h3>`
const body = routines.length
- ? routines.map(r => routineHTML(r, unit, { bare: !!single, speedUnit: speedUnitOf(S) })).join('')
+ ? routines.map((r, i) => routineHTML(r, unit, { bare: !!single, speedUnit, ticks: !!single, lead: i === 0 ? lead : '', m, key: 'r' + i })).join('')
: `<p class="none">${esc(t('No routines yet.'))}</p>`
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 lang="${getLang()}" dir="${RTL_LANGS.has(getLang()) ? 'rtl' : 'ltr'}"><head><meta charset="utf-8">
-<title>${esc(title)}</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; flex-direction: column; padding: 6px 0; break-inside: avoid; page-break-inside: avoid; }
- .ex + .ex, .ss + .ex, .ex + .ss { border-top: 1px solid #f2f3f6; }
- .ex-row { display: flex; align-items: baseline; justify-content: space-between; gap: 14px; }
- .ex-n { font-weight: 500; }
- .ex-n.capitalize { text-transform: capitalize; }
- .ex-n .part { display: inline-block; text-transform: none; color: #9aa0ae; font-weight: 400; font-size: 12px; margin-inline-start: 4px; }
- .ex-n .part::first-letter { text-transform: uppercase; }
- .ex-s { color: #3d424e; white-space: nowrap; font-variant-numeric: tabular-nums; }
- .ex-note { color: #6a7080; font-size: 12px; margin-top: 2px; }
- .ex.empty, .none { color: #a2a8b6; }
-
- .ss { break-inside: avoid; page-break-inside: avoid; border-inline-start: 3px solid #cfe08a; padding-inline-start: 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(title)}</h1>
- ${sub ? `<div class="sub">${sub}</div>` : ''}
- </header>
- ${week}
- ${body}
- <footer>${esc(t('Made with openGym'))} · opengym.ch</footer>
-</div></body></html>`
+ const facts = single ? [exCount(single.ex.length)] : [routineCount(routines.length)]
+ return printShell({
+ title, kicker: single ? t('Routine') : t('Training plan'), facts, owner, date: todayISO(),
+ body: (routineId ? '' : weekHTML(S, m)) + body,
+ css: PLAN_CSS,
+ })
}
/**
- * 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.
+ * Print the plan: the browser's print dialog (→ Save as PDF) on the web.
* `opts` is planPrintHTML's: `{ routineId }` prints a single routine.
*/
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;'
- 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, 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)
+ return printDocument(planPrintHTML(S, owner, opts), opts?.routineId ? (S.routines || []).find(r => r.id === opts.routineId)?.name : t('Weekly Training Plan'))
}
diff --git a/frontend/src/lib/print-doc.js b/frontend/src/lib/print-doc.js
new file mode 100644
index 000000000..03ab9b95e
--- /dev/null
+++ b/frontend/src/lib/print-doc.js
@@ -0,0 +1,204 @@
+// The paper side of openGym: one page shell every printout shares (the weekly plan, one routine,
+// one workout, the performance report), and the one way to send it to a printer or a PDF.
+//
+// What every printout gets from here:
+// - the openGym logo top left, the title, a line of facts, and who it is for and when;
+// - page numbers and opengym.ch in the bottom margin (CSS @page margin boxes: Chrome, Android's
+// WebView, desktop Chrome/Edge; the iOS app draws the same line natively, PrintPlugin.swift);
+// - a white, ink-light page: thin rules, grey text, the lime accent only as a small mark;
+// - the page-break rules: anything marked .keep stays on one page, a heading is printed inside
+// the same .keep as the first block under it so it can never be left alone at a page bottom,
+// and long tables repeat their header row on the next page. All of it in plain block layout,
+// because WebKit (the iPhone's print path) does not split flex or grid containers cleanly.
+//
+// The `probe` option adds invisible marks at the top and bottom of every .keep block (and on
+// headings), which scripts/pdf/check-pdf.py reads back out of a rendered PDF to prove no block
+// was cut across a page. Never set in the app.
+//
+// Nothing here bundles a PDF library: the browser's print dialog or the phone's print sheet
+// renders the PDF.
+import { t, getLang, RTL_LANGS, dateLocale } from './i18n-core.js'
+import { MOBILE, printHtml } from './mobile.js'
+
+export const esc = str => String(str == null ? '' : str)
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
+
+// A CSS string literal: for the page-number line in @page, which is CSS, not HTML.
+const cssStr = s => '"' + String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/[\n\r]/g, ' ') + '"'
+
+/**
+ * Probe marks for the layout check. `m.s(id)` / `m.e(id)` open and close a block that must stay on
+ * one page, `m.h(id)` marks a heading that belongs with block `id`. All empty strings unless
+ * `probe` is on, so the app's printouts never carry them.
+ */
+export function probeMarks(probe) {
+ if (!probe) return { s: () => '', e: () => '', h: () => '' }
+ const mark = (k, id) => `<i class="probe">~${k}:${String(id).replace(/[^A-Za-z0-9_.-]/g, '_')}~</i>`
+ return { s: id => mark('s', id), e: id => mark('e', id), h: id => mark('h', id) }
+}
+
+// The app icon (frontend/resources/icon.svg), drawn small: the lime dumbbell on its dark tile.
+export const LOGO_SVG = '<svg class="logo-mark" viewBox="0 0 512 512" aria-hidden="true"><rect width="512" height="512" rx="112" fill="#0c0e12"/>'
+ + '<g fill="#a3e635"><rect x="80" y="242" width="352" height="28"/><rect x="80" y="199" width="36" height="114"/>'
+ + '<rect x="131" y="169" width="47" height="174"/><rect x="334" y="169" width="47" height="174"/>'
+ + '<rect x="396" y="199" width="36" height="114"/></g></svg>'
+
+// "Page {0} of {1}" in the reader's language, as the content of an @page margin box: the text
+// around the two numbers comes from the translation, the numbers from CSS counters.
+export function pageNumberContent() {
+ const parts = t('Page {0} of {1}').split(/(\{0\}|\{1\})/)
+ return parts.filter(p => p !== '').map(p => p === '{0}' ? 'counter(page)' : p === '{1}' ? 'counter(pages)' : cssStr(p)).join(' ')
+}
+
+// A day as people write it on paper, in the reader's language: "15 Oct 2026".
+export function paperDate(iso) {
+ if (!iso) return ''
+ const d = new Date(iso + 'T12:00:00')
+ if (Number.isNaN(d.getTime())) return iso
+ return d.toLocaleDateString(dateLocale(), { day: 'numeric', month: 'short', year: 'numeric' })
+}
+
+// The shared look. Sizes in pt so the page reads the same on A4 and Letter; colours are print
+// colours (no dark mode on paper).
+export const PRINT_CSS = `
+ @page {
+ size: auto;
+ margin: 15mm 14mm 17mm;
+ @bottom-left { content: "opengym.ch"; font: 7.5pt/1 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; color: #9aa0ad; }
+ @bottom-right { font: 7.5pt/1 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; color: #9aa0ad; }
+ }
+ :root {
+ --ink: #15171c; --ink-2: #3b404b; --muted: #6b7180; --faint: #9aa0ad;
+ --rule: #e3e6ec; --rule-soft: #eff1f5; --tint: #f6f7f9;
+ --lime: #a3e635; --lime-ink: #4d7c0f; --lime-soft: #f1f9e1;
+ }
+ * { box-sizing: border-box; }
+ html { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
+ body {
+ margin: 0; color: var(--ink); background: #fff;
+ font: 9.5pt/1.45 -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, "Noto Sans", Helvetica, Arial, sans-serif;
+ font-variant-numeric: tabular-nums;
+ -webkit-text-size-adjust: 100%;
+ }
+ .doc { max-width: 182mm; margin: 0 auto; }
+ /* Screen preview only (a browser that shows the page before its print dialog): a sheet. */
+ @media screen { body { background: #f2f3f6; padding: 24px 12px; } .doc { background: #fff; padding: 18mm 15mm; box-shadow: 0 1px 4px rgba(0,0,0,.08); } }
+
+ .keep { break-inside: avoid; page-break-inside: avoid; }
+ .probe { display: block; height: 0; overflow: visible; font: 2px/0 sans-serif; color: #fff; font-style: normal; }
+
+ /* ---- masthead ---- */
+ .mast { display: block; border-bottom: 1.5px solid var(--ink); padding-bottom: 9pt; margin-bottom: 14pt; }
+ .mast-top { display: flex; align-items: center; justify-content: space-between; gap: 12pt; margin-bottom: 11pt; }
+ .brand { display: flex; align-items: center; gap: 6pt; font-weight: 650; font-size: 11pt; letter-spacing: -.01em; color: var(--ink); white-space: nowrap; }
+ .logo-mark { width: 18pt; height: 18pt; flex: none; }
+ .mast-meta { font-size: 8pt; color: var(--muted); text-align: end; line-height: 1.35; }
+ .mast-meta b { color: var(--ink-2); font-weight: 600; }
+ .kicker { font-size: 7.5pt; letter-spacing: .12em; text-transform: uppercase; color: var(--lime-ink); font-weight: 700; margin-bottom: 2pt; }
+ h1 { font-size: 19pt; line-height: 1.15; letter-spacing: -.02em; margin: 0; font-weight: 700; overflow-wrap: anywhere; }
+ .facts { color: var(--muted); font-size: 9pt; margin-top: 4pt; }
+ .facts .dot { color: var(--faint); padding: 0 4pt; }
+
+ /* ---- sections ---- */
+ .sec-h { font-size: 7.5pt; letter-spacing: .12em; text-transform: uppercase; color: var(--muted); font-weight: 700;
+ margin: 16pt 0 6pt; padding-bottom: 3pt; border-bottom: 1px solid var(--rule); }
+ .keep > .sec-h:first-child, .sec-h.first { margin-top: 4pt; }
+ .muted { color: var(--muted); }
+ .faint { color: var(--faint); }
+ .small { font-size: 8pt; }
+ .none { color: var(--faint); padding: 6pt 0; }
+
+ /* ---- tables (repeat their header row when they continue on the next page) ---- */
+ table { width: 100%; border-collapse: collapse; }
+ thead { display: table-header-group; }
+ tr { break-inside: avoid; page-break-inside: avoid; }
+ th { text-align: start; font-size: 7pt; letter-spacing: .08em; text-transform: uppercase; color: var(--faint); font-weight: 700; padding: 3pt 6pt 3pt 0; border-bottom: 1px solid var(--rule); }
+ td { padding: 4pt 6pt 4pt 0; border-bottom: 1px solid var(--rule-soft); vertical-align: top; }
+ td.num, th.num { text-align: end; padding-inline-end: 0; white-space: nowrap; }
+
+ .end { margin-top: 18pt; padding-top: 7pt; border-top: 1px solid var(--rule); color: var(--faint); font-size: 7.5pt; text-align: center; }
+
+ [dir="rtl"] .facts .dot { display: inline-block; }
+`
+
+/**
+ * One printable page, complete and self-contained (inline styles, no fetches): the masthead
+ * with logo, title and facts, then `body`, then a closing line.
+ * - `title` the big heading, also the document title (a saved PDF's default file name)
+ * - `kicker` small line above the title ("Performance report")
+ * - `facts` short strings under the title, joined with dots
+ * - `owner` who it is for (optional); `date` the day it was made (ISO, default today)
+ */
+export function printShell({ title, kicker = '', facts = [], owner = '', date, body, css = '' }) {
+ const lang = getLang()
+ const made = paperDate(date || new Date().toISOString().slice(0, 10))
+ const meta = [owner ? `<b>${esc(owner)}</b>` : '', esc(made)].filter(Boolean).join('<br>')
+ const factLine = facts.filter(Boolean).map(esc).join('<span class="dot">·</span>')
+ return `<!doctype html><html lang="${esc(lang)}" dir="${RTL_LANGS.has(lang) ? 'rtl' : 'ltr'}"><head><meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>${esc(title)}</title>
+<style>${PRINT_CSS}
+ @page { @bottom-right { content: ${pageNumberContent()}; } }
+${css}</style></head>
+<body><div class="doc">
+ <header class="mast keep">
+ <div class="mast-top"><div class="brand">${LOGO_SVG}<span>openGym</span></div><div class="mast-meta">${meta}</div></div>
+ ${kicker ? `<div class="kicker">${esc(kicker)}</div>` : ''}
+ <h1>${esc(title)}</h1>
+ ${factLine ? `<div class="facts">${factLine}</div>` : ''}
+ </header>
+ ${body}
+ <div class="end keep">${esc(t('Made with openGym'))} · opengym.ch</div>
+</div></body></html>`
+}
+
+// Letter paper where people use it (the US, Canada, Mexico, the Philippines, parts of Latin
+// America), A4 everywhere else: only a hint for the phone's print sheet, which lets you change it.
+const LETTER = new Set(['US', 'CA', 'MX', 'PH', 'CL', 'CO', 'VE', 'GT', 'CR', 'PA', 'DO', 'PR', 'SV', 'NI'])
+export function paperFor(locale) {
+ const region = String(locale || '').split(/[-_]/)[1]?.toUpperCase()
+ return region && LETTER.has(region) ? 'letter' : 'a4'
+}
+
+/** What the phone's print sheet needs besides the page: the paper it starts on and the footer
+ * the iOS plugin draws (lib/mobile.js printHtml). */
+export function printOptions() {
+ let locale = ''
+ try { locale = navigator.language || '' } catch (e) { /* */ }
+ return { paper: paperFor(locale), footer: { left: 'opengym.ch', page: t('Page {0} of {1}') } }
+}
+
+// The web: a hidden iframe and the browser's own print dialog (→ Save as PDF), so we never
+// navigate away or trip a popup blocker.
+function printInFrame(html) {
+ 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(html); doc.close()
+ // Give the iframe a tick to lay out (and its fonts to load) before printing.
+ const go = () => setTimeout(run, 150)
+ if (doc.readyState === 'complete') go()
+ else ifr.onload = go
+}
+
+/**
+ * Print `html` (a printShell page): the browser's print dialog on the web, the phone's print
+ * sheet in the app (Android's WebView has no window.print()). `name` names the print job and the
+ * suggested PDF file; Android refuses a job without one.
+ */
+export function printDocument(html, name) {
+ if (MOBILE) return printHtml(html, name || 'openGym', printOptions()).catch(() => { /* dismissed */ })
+ printInFrame(html)
+ return Promise.resolve()
+}
diff --git a/frontend/src/lib/print-doc.test.js b/frontend/src/lib/print-doc.test.js
new file mode 100644
index 000000000..c17a30478
--- /dev/null
+++ b/frontend/src/lib/print-doc.test.js
@@ -0,0 +1,44 @@
+// The shared printout shell (lib/print-doc.js).
+import { afterEach, describe, expect, it } from 'vitest'
+import { esc, paperFor, pageNumberContent, printShell, probeMarks, LOGO_SVG } from './print-doc.js'
+import { _setLangState } from './i18n-core.js'
+
+afterEach(() => _setLangState('en', {}, null, null))
+
+describe('print-doc', () => {
+ it('escapes what it prints', () => {
+ expect(esc('<b>"A&B"</b>')).toBe('&lt;b&gt;&quot;A&amp;B&quot;&lt;/b&gt;')
+ })
+
+ it('starts the print sheet on Letter where people use it, A4 everywhere else', () => {
+ expect(paperFor('en-US')).toBe('letter')
+ expect(paperFor('es_MX')).toBe('letter')
+ expect(paperFor('en-GB')).toBe('a4')
+ expect(paperFor('de')).toBe('a4')
+ expect(paperFor('')).toBe('a4')
+ })
+
+ it('builds the page-number line from the translation, numbers anywhere in it', () => {
+ expect(pageNumberContent()).toBe('"Page " counter(page) " of " counter(pages)')
+ _setLangState('ko', { 'Page {0} of {1}': '{1}쪽 중 {0}쪽' }, null, null)
+ expect(pageNumberContent()).toBe('counter(pages) "쪽 중 " counter(page) "쪽"')
+ _setLangState('de', { 'Page {0} of {1}': 'Seite "{0}" \\ {1}' }, null, null)
+ expect(pageNumberContent()).toBe('"Seite \\"" counter(page) "\\" \\\\ " counter(pages)')
+ })
+
+ it('a page: logo, title, facts, owner and date, right to left in Arabic', () => {
+ const html = printShell({ title: 'Leg <day>', kicker: 'Routine', facts: ['3 exercises', '', 'x'], owner: 'Ana', date: '2026-10-15', body: '<p>b</p>' })
+ expect(html).toContain(LOGO_SVG)
+ expect(html).toContain('<title>Leg &lt;day&gt;</title>')
+ expect(html).toContain('<div class="facts">3 exercises<span class="dot">·</span>x</div>')
+ expect(html).toContain('<b>Ana</b>')
+ expect(html).toContain('dir="ltr"')
+ _setLangState('ar', {}, null, null)
+ expect(printShell({ title: 't', body: '' })).toContain('dir="rtl"')
+ })
+
+ it('probe marks only when asked', () => {
+ expect(probeMarks(false).s('a')).toBe('')
+ expect(probeMarks(true).s('a b')).toBe('<i class="probe">~s:a_b~</i>')
+ })
+})
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index 2ce700ee8..d315915d1 100644
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@ -41,7 +41,7 @@ describe('Brazilian Portuguese locale', () => {
// has to be taught is a number nobody reads. What the numbers stood for is asserted above.
// If the hash fails, review the changed keys and wording before accepting a new one. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('7ec991d955078ae3097c247e0ec238b77782e428630daa6e36d14281bd91d2f3')
+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('760ff9e9f2b61b1ab437280e6713fdc9b2cc7b8364b75a46646ef1a9fdbf51e8')
})
// pt-PT labelled Unpair 'Desfazer': Undo, in Portuguese (it is pt-BR's Undo), on the button that
diff --git a/frontend/src/lib/report-print.js b/frontend/src/lib/report-print.js
new file mode 100644
index 000000000..1282e7a97
--- /dev/null
+++ b/frontend/src/lib/report-print.js
@@ -0,0 +1,474 @@
+// Paper versions of training that happened: one finished workout (its detail sheet's "Save as
+// PDF"), and the performance report over a stretch of days (Stats, History and Settings > Data).
+// The numbers come from lib/report.js; the page shell, the page-break rules and the printing from
+// lib/print-doc.js. Charts are inline SVG drawn here, so they stay sharp at any zoom and print the
+// same on every platform. No exercise media is ever put on paper.
+import { EXIDX } from './exercises.js'
+import { setLabel, sessionSections, workoutVolume, workoutDuration, workoutDay } from './history.js'
+import { isWarmupRow, hasCompletedWork } from './workout-model.js'
+import { fmtNum, fmtVol, fmtDur, fmtDate, todayISO, DAYS, weekOrder, weekDayOffset } from './format.js'
+import { t, tn, dateLocale } from './i18n-core.js'
+import { speedUnitOf } from './speed.js'
+import { printedName } from './plan-share.js'
+import { esc, printShell, printDocument, probeMarks, paperDate } from './print-doc.js'
+import { reportData, workSetsOf } from './report.js'
+
+/* ----------------------------------- pieces ----------------------------------- */
+
+const nameParts = e => printedName(EXIDX[e.id], e.n || e.muscleSnapshot?.n || e.id)
+
+function nameHTML(e, { pr = false } = {}) {
+ const ex = EXIDX[e.id]
+ const { name, en, cls } = nameParts(e)
+ const part = ex && ex.bp && ex.bp !== 'cardio' ? ` <span class="part">${esc(t(ex.bp))}</span>` : ''
+ return `<div class="ex-n ${cls}">${esc(name)}${part}${pr ? ` <span class="pr">${esc(t('New best'))}</span>` : ''}</div>`
+ + (en ? `<div class="ex-en">${esc(en)}</div>` : '')
+}
+
+// Short day + date for lists: "Thu 15 Oct".
+const listDate = iso => (iso ? fmtDate(iso, true) : '')
+const clock = ms => (Number.isFinite(ms) && ms > 0 ? new Date(ms).toLocaleTimeString(dateLocale(), { hour: 'numeric', minute: '2-digit' }) : '')
+const signed = (n, digits = 1) => {
+ if (n == null || !Number.isFinite(n)) return ''
+ const r = Math.round(n * 10 ** digits) / 10 ** digits
+ return (r > 0 ? '+' : r < 0 ? '−' : '±') + fmtNum(Math.abs(r))
+}
+// Change against the stretch before, as a small arrow line under a card's number.
+function delta(now, before, { pct = true } = {}) {
+ if (!(before > 0) || now == null) return ''
+ const p = Math.round((now - before) / before * 100)
+ if (!p) return `<div class="delta flat">± 0%</div>`
+ return `<div class="delta ${p > 0 ? 'up' : 'down'}">${p > 0 ? '▲' : '▼'} ${pct ? Math.abs(p) + '%' : ''}</div>`
+}
+
+// A stat card: label, value, an optional line under it.
+const card = (label, value, sub = '') => `<div class="card"><div class="c-l">${esc(label)}</div><div class="c-v">${value}</div>${sub}</div>`
+
+/* ----------------------------------- charts ----------------------------------- */
+// Shared rules: a recessive grid (three hairlines, labelled at the start edge), thin marks, the
+// accent only on the mark that matters (the latest bar, the best point), labels in text ink.
+
+const NICE = [1, 2, 2.5, 5, 10]
+function niceMax(v) {
+ if (!(v > 0)) return 1
+ const p = 10 ** Math.floor(Math.log10(v))
+ for (const n of NICE) if (n * p >= v) return n * p
+ return 10 * p
+}
+const compact = v => (v >= 10000 ? fmtNum(Math.round(v / 100) / 10) + 'k' : fmtNum(Math.round(v)))
+
+/** Vertical bars, one per bucket. `bars` = [{ label, value, title }]. */
+export function barChartSVG(bars, { w = 680, h = 170, unit = '' } = {}) {
+ const padL = 44, padR = 8, padT = 12, padB = 22
+ const max = niceMax(Math.max(0, ...bars.map(b => b.value)))
+ const iw = w - padL - padR, ih = h - padT - padB
+ const n = Math.max(1, bars.length)
+ const slot = iw / n
+ const bw = Math.max(2, Math.min(36, slot * 0.62))
+ const y = v => padT + ih - (v / max) * ih
+ const grid = [0, 0.5, 1].map(f => {
+ const v = max * f, yy = y(v)
+ return `<line x1="${padL}" x2="${w - padR}" y1="${yy}" y2="${yy}" class="g${f === 0 ? ' base' : ''}"/><text x="${padL - 6}" y="${yy + 3}" class="ax" text-anchor="end">${esc(compact(v))}</text>`
+ }).join('')
+ // Every label when they fit, else every k-th so they never collide.
+ const every = Math.ceil(n / Math.max(1, Math.floor(iw / 46)))
+ const last = bars.length - 1
+ const marks = bars.map((b, i) => {
+ const x = padL + slot * i + (slot - bw) / 2
+ const hh = Math.max(0, (b.value / max) * ih)
+ const r = Math.min(3, bw / 2, hh)
+ const top = padT + ih - hh
+ const shape = hh > 0
+ ? `<path d="M${x},${padT + ih} V${top + r} Q${x},${top} ${x + r},${top} H${x + bw - r} Q${x + bw},${top} ${x + bw},${top + r} V${padT + ih} Z" class="${i === last ? 'bar hot' : 'bar'}"><title>${esc(b.title || '')}</title></path>`
+ : ''
+ const lab = i % every === 0 || i === last ? `<text x="${x + bw / 2}" y="${h - 6}" class="ax" text-anchor="middle">${esc(b.label)}</text>` : ''
+ return shape + lab
+ }).join('')
+ return `<svg class="chart" viewBox="0 0 ${w} ${h}" width="100%" role="img" aria-label="${esc(unit)}">${grid}${marks}</svg>`
+}
+
+/** A line over time. `pts` = [{ t, y }] ascending; `from`/`to` fix the time axis (ms). */
+export function lineChartSVG(pts, { w = 680, h = 150, from, to, fmt = fmtNum, labels = [] } = {}) {
+ const padL = 44, padR = 12, padT = 14, padB = 22
+ const iw = w - padL - padR, ih = h - padT - padB
+ if (!pts.length) return ''
+ const ys = pts.map(p => p.y)
+ let lo = Math.min(...ys), hi = Math.max(...ys)
+ if (hi - lo < 1e-9) { lo -= 1; hi += 1 }
+ // Round numbers on the axis: two or three steps of 1, 2, 2.5 or 5 × a power of ten.
+ const step = niceMax((hi - lo) / 2)
+ lo = Math.floor(lo / step) * step
+ hi = Math.ceil(hi / step) * step
+ if (hi - lo < step * 2) hi = lo + step * 2
+ const ticks = []
+ for (let v = lo; v <= hi + step / 2; v += step) ticks.push(v)
+ const t0 = from ?? pts[0].t, t1 = Math.max(to ?? pts[pts.length - 1].t, t0 + 1)
+ const x = tt => padL + ((tt - t0) / (t1 - t0)) * iw
+ const y = v => padT + ih - ((v - lo) / (hi - lo)) * ih
+ const grid = ticks.map(v => {
+ const yy = y(v)
+ return `<line x1="${padL}" x2="${w - padR}" y1="${yy}" y2="${yy}" class="g"/><text x="${padL - 6}" y="${yy + 3}" class="ax" text-anchor="end">${esc(fmt(v))}</text>`
+ }).join('')
+ const path = pts.map((p, i) => `${i ? 'L' : 'M'}${x(p.t).toFixed(1)},${y(p.y).toFixed(1)}`).join(' ')
+ let best = 0
+ pts.forEach((p, i) => { if (p.y > pts[best].y) best = i })
+ const dots = pts.map((p, i) => `<circle cx="${x(p.t).toFixed(1)}" cy="${y(p.y).toFixed(1)}" r="${i === best ? 3.6 : 2.2}" class="${i === best ? 'dot hot' : 'dot'}"/>`).join('')
+ // Direct labels on the last point and the best one, not on every point.
+ const lab = (i, above) => {
+ const p = pts[i]
+ const xx = Math.min(w - padR, Math.max(padL, x(p.t)))
+ const anchor = xx > w - padR - 30 ? 'end' : xx < padL + 30 ? 'start' : 'middle'
+ return `<text x="${xx}" y="${y(p.y) + (above ? -7 : 13)}" class="val" text-anchor="${anchor}">${esc(fmt(p.y))}</text>`
+ }
+ // Above the point, unless the line comes down into it (then below, clear of the line).
+ const vlabels = [...new Set([best, pts.length - 1])].map(i => lab(i, i === best || !(i > 0 && pts[i - 1].y > pts[i].y))).join('')
+ const xl = labels.map(([tt, text], i) => `<text x="${x(tt)}" y="${h - 6}" class="ax" text-anchor="${i === 0 ? 'start' : i === labels.length - 1 ? 'end' : 'middle'}">${esc(text)}</text>`).join('')
+ return `<svg class="chart" viewBox="0 0 ${w} ${h}" width="100%" role="img">${grid}<path d="${path}" class="line"/>${dots}${vlabels}${xl}</svg>`
+}
+
+/** The consistency calendar: one column per week, one row per weekday, shaded by volume. */
+export function calendarSVG(days, ws, { cell = 13, gap = 3 } = {}) {
+ if (!days.length) return ''
+ // Two weeks or less: one strip of days, each named under its square.
+ if (days.length <= 14) {
+ const c = 22, g = 4
+ const w = days.length * (c + g), h = c + 16
+ const cells = days.map((day, i) => {
+ const label = new Date(day.d + 'T12:00:00').toLocaleDateString(dateLocale(), { weekday: 'narrow' })
+ return `<rect x="${i * (c + g)}" y="0" width="${c}" height="${c}" rx="4" class="l${day.level}"><title>${esc(day.d)}</title></rect>`
+ + `<text x="${i * (c + g) + c / 2}" y="${c + 12}" class="ax" text-anchor="middle">${esc(label)}</text>`
+ }).join('')
+ return `<svg class="cal" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" role="img">${cells}</svg>`
+ }
+ const first = new Date(days[0].d + 'T12:00:00')
+ const lead = weekDayOffset(first.getDay(), ws)
+ const cols = Math.ceil((lead + days.length) / 7)
+ const left = 26, top = 4
+ const w = left + cols * (cell + gap), h = top + 7 * (cell + gap)
+ const rows = weekOrder(ws).map((d, i) => (i % 2 === 0 ? `<text x="${left - 5}" y="${top + i * (cell + gap) + cell - 3}" class="ax" text-anchor="end">${esc(t(DAYS[d]))}</text>` : '')).join('')
+ const cells = days.map((day, i) => {
+ const k = lead + i
+ const cx = left + Math.floor(k / 7) * (cell + gap), cy = top + (k % 7) * (cell + gap)
+ return `<rect x="${cx}" y="${cy}" width="${cell}" height="${cell}" rx="2.5" class="l${day.level}"><title>${esc(day.d)}</title></rect>`
+ }).join('')
+ return `<svg class="cal" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" role="img">${rows}${cells}</svg>`
+}
+
+const CHART_CSS = `
+ svg.chart { display: block; overflow: visible; }
+ svg .g { stroke: #e9ebf0; stroke-width: 1; }
+ svg .g.base { stroke: #c9cdd6; }
+ svg .ax { font-size: 9px; fill: #8a909d; font-family: inherit; }
+ svg .val { font-size: 9.5px; fill: #3b404b; font-weight: 600; font-family: inherit; }
+ svg .bar { fill: #6b7180; }
+ svg .bar.hot { fill: #4d7c0f; }
+ svg .line { fill: none; stroke: #3b404b; stroke-width: 1.6; stroke-linejoin: round; stroke-linecap: round; }
+ svg .dot { fill: #3b404b; stroke: #fff; stroke-width: 1.2; }
+ svg .dot.hot { fill: #a3e635; stroke: #3f6212; stroke-width: 1.4; }
+ svg.cal { display: block; }
+ svg.cal .l0 { fill: #f0f1f4; } svg.cal .l1 { fill: #e2f5bd; } svg.cal .l2 { fill: #bfe57a; }
+ svg.cal .l3 { fill: #84cc16; } svg.cal .l4 { fill: #3f6212; }
+`
+
+/* ------------------------------- shared page CSS ------------------------------- */
+
+const REPORT_CSS = `
+ .cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6pt; }
+ .card { border: 1px solid var(--rule); border-radius: 6pt; padding: 7pt 9pt; min-width: 0; }
+ .c-l { font-size: 7pt; letter-spacing: .08em; text-transform: uppercase; color: var(--muted); font-weight: 700; }
+ .c-v { font-size: 15pt; font-weight: 700; letter-spacing: -.01em; margin-top: 1pt; white-space: nowrap; }
+ .c-v small { font-size: 8.5pt; font-weight: 500; color: var(--muted); margin-inline-start: 2pt; }
+ .c-s { font-size: 7.5pt; color: var(--muted); }
+ .delta { font-size: 7.5pt; color: var(--muted); }
+ .delta.up { color: var(--lime-ink); }
+ .note-line { font-size: 7.5pt; color: var(--faint); margin-top: 4pt; }
+
+ .panel { margin-top: 2pt; }
+ .two { display: grid; grid-template-columns: 1fr 1fr; gap: 8pt 14pt; }
+ .lift { min-width: 0; }
+ .lift-h { display: flex; justify-content: space-between; gap: 6pt; align-items: baseline; }
+ .lift-h .ex-n { font-size: 9pt; }
+ .lift-c { font-size: 8pt; color: var(--muted); white-space: nowrap; }
+ .lift-c b { color: var(--ink-2); }
+ .lift-c b.up { color: var(--lime-ink); }
+
+ .facts-row { display: flex; flex-wrap: wrap; gap: 4pt 16pt; margin-top: 6pt; font-size: 8.5pt; color: var(--ink-2); }
+ .facts-row b { font-weight: 700; }
+ .cal-wrap { display: flex; gap: 18pt; align-items: flex-start; flex-wrap: wrap; }
+ .legend { display: flex; gap: 3pt; align-items: center; font-size: 7.5pt; color: var(--faint); margin-top: 4pt; }
+ .legend i { display: inline-block; width: 8pt; height: 8pt; border-radius: 2pt; }
+ .legend .l0 { background: #f0f1f4; } .legend .l1 { background: #e2f5bd; } .legend .l2 { background: #bfe57a; }
+ .legend .l3 { background: #84cc16; } .legend .l4 { background: #3f6212; }
+ .keep-next { break-after: avoid; page-break-after: avoid; }
+
+ table.mus td { padding: 2.5pt 6pt 2.5pt 0; border-bottom: 0; }
+ table.mus td.m { width: 26%; white-space: nowrap; }
+ table.mus td.v { width: 16%; text-align: end; white-space: nowrap; color: var(--muted); }
+ .hbar { height: 7pt; border-radius: 2pt; background: #6b7180; }
+ .hbar.top { background: #4d7c0f; }
+
+ .ex-n { font-weight: 600; overflow-wrap: anywhere; }
+ .ex-n.capitalize { text-transform: capitalize; }
+ .ex-n .part { display: inline-block; text-transform: none; color: var(--faint); font-weight: 400; font-size: 8pt; margin-inline-start: 2pt; }
+ .ex-n .part::first-letter { text-transform: uppercase; }
+ td.num + td.num, th.num + th.num { padding-inline-start: 12pt; }
+ .ex-en { color: var(--faint); font-size: 8pt; text-transform: capitalize; overflow-wrap: anywhere; }
+ .pr { display: inline-block; font-size: 6.5pt; letter-spacing: .06em; text-transform: uppercase; font-weight: 700;
+ color: #3f6212; background: var(--lime-soft); border: 1px solid #d3eba4; border-radius: 3pt; padding: 0 3pt; vertical-align: 1pt; margin-inline-start: 3pt; }
+
+ /* one workout in the report's list */
+ .wk { margin-bottom: 6pt; }
+ .wk-h { display: flex; justify-content: space-between; align-items: baseline; gap: 8pt; padding: 5pt 0 3pt; border-bottom: 1px solid var(--ink); }
+ .wk-h .t { font-weight: 700; overflow-wrap: anywhere; }
+ .wk-h .t span { color: var(--muted); font-weight: 500; margin-inline-end: 6pt; }
+ .wk-h .f { font-size: 8pt; color: var(--muted); white-space: nowrap; }
+ table.wk-t td { font-size: 8.5pt; padding: 2.5pt 6pt 2.5pt 0; }
+ table.wk-t td.n { width: 38%; }
+ table.wk-t td.n .ex-n { font-weight: 500; }
+ table.wk-t td.s { color: var(--ink-2); }
+ .wk-note { font-size: 8pt; color: var(--muted); font-style: italic; padding-top: 3pt; }
+
+ /* one exercise of a single workout */
+ .wx { padding: 6pt 0 7pt; border-bottom: 1px solid var(--rule-soft); }
+ .wx-h { display: flex; gap: 8pt; align-items: flex-start; }
+ .wx-num { flex: none; width: 14pt; height: 14pt; margin-top: 1pt; border-radius: 50%; background: var(--tint); color: var(--muted); font-size: 7pt; font-weight: 700; line-height: 14pt; text-align: center; }
+ .wx-main { flex: 1; min-width: 0; }
+ .wx-sum { flex: none; font-size: 8pt; color: var(--muted); white-space: nowrap; text-align: end; }
+ .sets { margin: 4pt 0 0 22pt; font-size: 0; }
+ [dir="rtl"] .sets { margin: 4pt 22pt 0 0; }
+ .set { display: inline-block; vertical-align: top; min-width: 23mm; margin: 0 4pt 4pt 0; padding: 3pt 6pt; border: 1px solid var(--rule); border-radius: 4pt; font-size: 8.5pt; }
+ [dir="rtl"] .set { margin: 0 0 4pt 4pt; }
+ .set .k { display: block; font-size: 6.5pt; letter-spacing: .06em; text-transform: uppercase; color: var(--faint); font-weight: 700; }
+ .set .v { font-weight: 600; white-space: nowrap; }
+ .set.warm { border-style: dashed; color: var(--muted); }
+ .set.warm .v { font-weight: 500; }
+ .set.skip { color: var(--faint); }
+ .wx-note { margin: 2pt 0 0 22pt; font-size: 8.5pt; color: var(--ink-2); font-style: italic; }
+ [dir="rtl"] .wx-note { margin: 2pt 22pt 0 0; }
+ .ss { border-inline-start: 2.5pt solid var(--lime); padding-inline-start: 8pt; margin: 4pt 0; }
+ .ss-tag { font-size: 7pt; letter-spacing: .1em; text-transform: uppercase; color: var(--lime-ink); font-weight: 700; padding-top: 5pt; }
+ .ss .wx:last-child { border-bottom: 0; }
+ .session-note { border-inline-start: 2.5pt solid var(--rule); padding: 4pt 0 4pt 9pt; color: var(--ink-2); font-style: italic; white-space: pre-wrap; }
+ ${CHART_CSS}
+`
+
+/* ------------------------------- one workout ------------------------------- */
+
+function workoutUnits(w) {
+ const entries = w.entries || []
+ return sessionSections(entries).flatMap(s => s.units).map(u => u.map(i => entries[i]).filter(Boolean)).filter(u => u.length)
+}
+
+// The sets of one exercise as small boxes: warm-ups dashed, sets not done faint. Wraps onto as
+// many lines as it needs and never runs past the page edge.
+function setsHTML(e, speedUnit) {
+ let n = 0
+ const rows = (e.sets || []).map(s => {
+ const warm = isWarmupRow(s)
+ const done = hasCompletedWork(s)
+ const key = warm ? t('Warm-up') : t('Set {0}', ++n)
+ const value = done ? setLabel(e.id, s, e.target, speedUnit) : '–'
+ return `<div class="set${warm ? ' warm' : ''}${done ? '' : ' skip'}"><span class="k">${esc(key)}</span><span class="v">${esc(value)}</span></div>`
+ })
+ return rows.length ? `<div class="sets">${rows.join('')}</div>` : ''
+}
+
+function entryVolume(e) { return workoutVolume({ entries: [e] }) }
+
+/**
+ * One finished workout on paper: what it was, when, how long and how heavy, then every exercise
+ * with every set. Each exercise, and each superset, stays whole on a page.
+ */
+export function workoutPrintHTML(S, w, { owner = '', probe = false } = {}) {
+ const m = probeMarks(probe)
+ const unit = S.unit || 'kg'
+ const speedUnit = speedUnitOf(S)
+ const prs = new Set(w.prs || [])
+ const ms = workoutDuration(w)
+ const day = workoutDay(w)
+ const sets = workSetsOf(w)
+ const vol = w.vol ?? workoutVolume(w)
+ const cards = [
+ ms >= 60000 ? card(t('Duration'), esc(fmtDur(ms))) : '',
+ card(t('Sets'), esc(fmtNum(sets))),
+ card(t('Volume'), esc(fmtVol(vol, unit))),
+ card(t('New bests'), esc(fmtNum(prs.size))),
+ w.bw ? card(t('Body weight'), esc(fmtNum(w.bw) + ' ' + unit)) : '',
+ card(t('Exercises'), esc(fmtNum((w.entries || []).length))),
+ ].filter(Boolean).slice(0, 6)
+ let num = 0
+ const exHTML = e => {
+ const v = entryVolume(e)
+ const done = (e.sets || []).filter(s => !isWarmupRow(s) && hasCompletedWork(s)).length
+ const sum = [t('{0} sets', done), v > 0 ? fmtVol(v, unit) : ''].filter(Boolean).join(' · ')
+ return `<div class="wx"><div class="wx-h"><div class="wx-num">${++num}</div><div class="wx-main">${nameHTML(e, { pr: prs.has(e.id) })}</div><div class="wx-sum">${esc(sum)}</div></div>`
+ + setsHTML(e, speedUnit)
+ + (e.note ? `<div class="wx-note">${esc(e.note)}</div>` : '') + '</div>'
+ }
+ const units = workoutUnits(w)
+ const blocks = units.map((u, i) => {
+ const inner = u.length > 1 ? `<div class="ss"><div class="ss-tag">${esc(t('Superset'))}</div>${u.map(exHTML).join('')}</div>` : exHTML(u[0])
+ const head = i === 0 ? `${m.h('x0')}<h3 class="sec-h">${esc(t('Exercises'))}</h3>` : ''
+ return `<div class="keep">${m.s('x' + i)}${head}${inner}${m.e('x' + i)}</div>`
+ }).join('')
+ const note = w.note ? `<div class="keep">${m.s('note')}<h3 class="sec-h">${esc(t('Session note'))}</h3><div class="session-note">${esc(w.note)}</div>${m.e('note')}</div>` : ''
+ const facts = [day ? paperDate(day) : '', [clock(w.start), clock(w.end)].filter(Boolean).join(' – ')]
+ const body = `<div class="keep">${m.s('cards')}<div class="cards">${cards.join('')}</div>${m.e('cards')}</div>`
+ + (blocks || `<p class="none">${esc(t('no sets'))}</p>`) + note
+ return printShell({ title: w.name || t('Workout'), kicker: t('Workout'), facts, owner, date: todayISO(), body, css: REPORT_CSS })
+}
+
+/* ---------------------------- the performance report ---------------------------- */
+
+function rangeTitle(r) {
+ if (r.kind === '7d') return t('Last 7 days')
+ if (r.kind === '4w') return t('Last 4 weeks')
+ if (r.kind === '3m') return t('Last 3 months')
+ return t('{0} days', r.days)
+}
+
+const bucketLabel = (b, unit) => {
+ const d = new Date(b.from + 'T12:00:00')
+ if (unit === 'day') return d.toLocaleDateString(dateLocale(), { weekday: 'short' }).replace(/\.$/, '')
+ if (unit === 'month') return d.toLocaleDateString(dateLocale(), { month: 'short' })
+ return d.toLocaleDateString(dateLocale(), { day: 'numeric', month: 'numeric' })
+}
+
+function summaryHTML(R, unit) {
+ const T = R.totals, P = R.prev
+ const bw = T.bwChange != null
+ ? card(t('Body weight'), `${esc(signed(T.bwChange))}<small>${esc(unit)}</small>`, `<div class="c-s">${esc(fmtNum(T.bwStart))} → ${esc(fmtNum(T.bwEnd))} ${esc(unit)}</div>`)
+ : card(t('Body weight'), T.bwEnd != null ? `${esc(fmtNum(T.bwEnd))}<small>${esc(unit)}</small>` : '–', `<div class="c-s">${esc(T.bwEnd != null ? t('One weigh-in') : t('No weigh-ins'))}</div>`)
+ return `<div class="cards">${[
+ card(t('Workouts'), esc(fmtNum(T.workouts)), delta(T.workouts, P.workouts)),
+ card(t('Volume'), `${esc(compact(T.volume))}<small>${esc(unit)}</small>`, delta(T.volume, P.volume)),
+ card(t('Work sets'), esc(fmtNum(T.sets)), delta(T.sets, P.sets)),
+ card(t('Training time'), esc(T.ms >= 60000 ? fmtDur(T.ms) : '–'), delta(T.ms, P.ms)),
+ card(t('New bests'), esc(fmtNum(T.prs)), delta(T.prs, P.prs)),
+ bw,
+ ].join('')}</div><div class="note-line">${esc(t('Arrows compare with the {0} days before.', R.range.days))}</div>`
+}
+
+function volumeHTML(R, unit) {
+ const { unit: per, buckets } = R.buckets
+ const bars = buckets.map(b => ({ label: bucketLabel(b, per), value: b.volume, title: `${b.from}: ${fmtVol(b.volume, unit)}` }))
+ const title = per === 'day' ? t('Volume per day') : per === 'week' ? t('Volume per week') : t('Volume per month')
+ return { title, html: barChartSVG(bars, { unit }) + `<div class="note-line">${esc(unit)} · ${esc(t('Work sets only, warm-ups left out.'))}</div>` }
+}
+
+function calendarHTML(R) {
+ const s = R.streak
+ const facts = [
+ [t('Active days'), `${fmtNum(s.activeDays)} / ${fmtNum(R.range.days)}`],
+ [t('Workouts per week'), fmtNum(R.perWeek)],
+ [t('Most days in a row'), fmtNum(s.longestDays)],
+ [t('Week streak'), fmtNum(s.weeks ?? s.longestWeeks)],
+ ]
+ const legend = `<div class="legend">${esc(t('Less'))} ${[0, 1, 2, 3, 4].map(l => `<i class="lg l${l}"></i>`).join('')} ${esc(t('More'))}</div>`
+ return `<div class="cal-wrap"><div>${calendarSVG(R.calendar, R.weekStart)}${legend}</div>`
+ + `<div class="facts-row" style="flex-direction:column;gap:3pt">${facts.map(([k, v]) => `<div>${esc(k)}: <b>${esc(v)}</b></div>`).join('')}</div></div>`
+}
+
+function musclesHTML(R, m) {
+ const list = R.muscles.worked
+ if (!list.length) return `<p class="none">${m.s('muscles')}${m.e('muscles')}${esc(t('No muscle work in this period.'))}</p>`
+ const max = list[0].sets || 1
+ const rows = list.map((x, i) => `<tr><td class="m">${i === 0 ? m.s('muscles') + m.e('muscles') : ''}${esc(t(x.name))}</td><td><div class="hbar${i === 0 ? ' top' : ''}" style="width:${Math.max(2, Math.round(x.sets / max * 100))}%"></div></td><td class="v">${esc(t('{0} sets', fmtNum(x.sets)))}</td></tr>`).join('')
+ const missed = R.muscles.missed.length ? `<div class="note-line">${esc(t('Not trained:'))} ${esc(R.muscles.missed.map(x => t(x.name)).join(', '))}</div>` : ''
+ return `<table class="mus">${rows}</table>${missed}<div class="note-line">${esc(t('Effective sets: a set counts fully for its main muscle and partly for the ones that help.'))}</div>`
+}
+
+function liftsHTML(R, unit, range, m) {
+ const t0 = new Date(range.from + 'T00:00:00').getTime(), t1 = new Date(range.to + 'T23:59:59').getTime()
+ return R.lifts.map((l, i) => {
+ const e = { id: l.id }
+ const change = l.change != null ? `<b class="${l.change > 0 ? 'up' : ''}">${esc(signed(l.change))} ${esc(unit)}</b>` : ''
+ const best = l.best ? `${esc(t('Best:'))} ${esc(fmtNum(l.best.y))} ${esc(unit)}` : ''
+ const chart = l.points.length > 1
+ ? lineChartSVG(l.points, { w: 330, h: 120, from: t0, to: t1, labels: [[t0, fmtDate(range.from)], [t1, fmtDate(range.to)]] })
+ : `<p class="none small">${esc(t('One session in this period.'))} ${best}</p>`
+ return `<div class="lift keep">${m.s('lift' + i)}<div class="lift-h">${nameHTML(e)}<div class="lift-c">${[change, best].filter(Boolean).join(' · ')}</div></div>${chart}${m.e('lift' + i)}</div>`
+ })
+}
+
+function prsHTML(R, unit, m) {
+ const rows = R.prs.map((p, i) => {
+ const e = p.entry || { id: p.id }
+ const set = p.best ? `${fmtNum(p.best.w)} ${unit} × ${p.best.r}` : (p.entry ? (p.entry.sets || []).filter(s => !isWarmupRow(s) && hasCompletedWork(s)).map(s => setLabel(p.id, s, p.entry.target)).slice(-1)[0] || '' : '')
+ const mark = i === 0 ? m.s('prs') + m.e('prs') : ''
+ return `<tr><td style="white-space:nowrap">${mark}${esc(listDate(p.d))}</td><td>${nameHTML(e)}</td><td class="num">${esc(set)}</td><td class="num">${p.best ? esc(fmtNum(p.best.est) + ' ' + unit) : '–'}</td></tr>`
+ }).join('')
+ return `<table><thead><tr><th>${esc(t('Date'))}</th><th>${esc(t('Exercise'))}</th><th class="num">${esc(t('Best set'))}</th><th class="num">${esc(t('Est. 1RM'))}</th></tr></thead><tbody>${rows}</tbody></table>`
+}
+
+function workoutListItem(S, w, unit, speedUnit, m, id, lead = '') {
+ const prs = new Set(w.prs || [])
+ const ms = workoutDuration(w)
+ const facts = [ms >= 60000 ? fmtDur(ms) : '', fmtVol(w.vol ?? workoutVolume(w), unit), t('{0} sets', workSetsOf(w))].filter(Boolean).join(' · ')
+ const rows = workoutUnits(w).flat().map(e => {
+ const sets = (e.sets || []).filter(s => !isWarmupRow(s) && hasCompletedWork(s)).map(s => setLabel(e.id, s, e.target, speedUnit))
+ if (!sets.length) return ''
+ return `<tr><td class="n">${nameHTML(e, { pr: prs.has(e.id) })}</td><td class="s">${esc(sets.join(', '))}</td></tr>`
+ }).join('')
+ return `<div class="wk keep">${m.s(id)}${lead}<div class="wk-h"><div class="t"><span>${esc(listDate(workoutDay(w)))}</span>${esc(w.name || t('Workout'))}</div><div class="f">${esc(facts)}</div></div>`
+ + (rows ? `<table class="wk-t"><tbody>${rows}</tbody></table>` : '')
+ + (w.note ? `<div class="wk-note">${esc(w.note)}</div>` : '') + `${m.e(id)}</div>`
+}
+
+/**
+ * The performance report for `range` ('7d' | '4w' | '3m' | 'custom' with from/to, ISO days):
+ * summary cards with the change against the stretch before, the charts (volume, consistency
+ * calendar, muscles, estimated 1RM of the top lifts, body weight), and the lists (new bests,
+ * every workout with its sets).
+ */
+export function reportPrintHTML(S, { range = '4w', from, to, owner = '', probe = false, today } = {}) {
+ const m = probeMarks(probe)
+ const unit = S.unit || 'kg'
+ const speedUnit = speedUnitOf(S)
+ const R = reportData(S, { range, from, to, today })
+ const r = R.range
+ // A section: its heading travels with its first block, which stays whole on a page.
+ const section = (id, title, html) => `<div class="keep panel">${m.s(id)}${m.h(id)}<h3 class="sec-h">${esc(title)}</h3>${html}${m.e(id)}</div>`
+ const parts = []
+ parts.push(`<div class="keep">${m.s('summary')}${summaryHTML(R, unit)}${m.e('summary')}</div>`)
+ if (!R.workouts.length) {
+ parts.push(`<p class="none">${esc(t('No workouts in this period.'))}</p>`)
+ } else {
+ const vol = volumeHTML(R, unit)
+ parts.push(section('volume', vol.title, vol.html))
+ parts.push(section('consistency', t('Consistency'), calendarHTML(R)))
+ // Up to eighteen rows: a list that may run over a page, row by row, its heading kept with it.
+ parts.push(`<div class="panel">${m.h('muscles')}<h3 class="sec-h keep-next">${esc(t('Sets per muscle'))}</h3>${musclesHTML(R, m)}</div>`)
+ if (R.lifts.length) {
+ // Two charts a row; the heading rides with the first row.
+ const blocks = liftsHTML(R, unit, r, m)
+ parts.push(`<div class="keep panel">${m.s('lifts-h')}${m.h('lifts-h')}<h3 class="sec-h">${esc(t('Estimated 1RM, top lifts'))}</h3><div class="two">${blocks.slice(0, 2).join('')}</div>${m.e('lifts-h')}</div>`)
+ if (blocks.length > 2) parts.push(`<div class="keep two" style="margin-top:8pt">${blocks.slice(2).join('')}</div>`)
+ }
+ }
+ if (R.bodyweight.length > 1) {
+ const t0 = new Date(r.from + 'T00:00:00').getTime(), t1 = new Date(r.to + 'T23:59:59').getTime()
+ const pts = R.bodyweight.map(b => ({ t: b.t, y: b.w }))
+ parts.push(section('bw', t('Body weight'), lineChartSVG(pts, { from: t0, to: t1, labels: [[t0, fmtDate(r.from)], [t1, fmtDate(r.to)]] })
+ + `<div class="note-line">${esc(unit)} · ${esc(tn('{0} weigh-in', '{0} weigh-ins', R.bodyweight.length))}</div>`))
+ }
+ // A long list may run over a page: its rows never split and its header row repeats. The heading
+ // stays with the first rows (break-after: avoid, and the probe checks it).
+ if (R.prs.length) parts.push(`<div class="panel">${m.h('prs')}<h3 class="sec-h keep-next">${esc(t('New bests'))}</h3>${prsHTML(R, unit, m)}</div>`)
+ if (R.workouts.length) {
+ const lead = `${m.h('wk0')}<h3 class="sec-h">${esc(t('All workouts'))}</h3>`
+ R.workouts.forEach((w, i) => parts.push(workoutListItem(S, w, unit, speedUnit, m, 'wk' + i, i === 0 ? lead : '')))
+ }
+ const facts = [`${paperDate(r.from)} – ${paperDate(r.to)}`, tn('{0} workout', '{0} workouts', R.workouts.length)]
+ return printShell({ title: rangeTitle(r), kicker: t('Performance report'), facts, owner, date: today || todayISO(), body: parts.join(''), css: REPORT_CSS })
+}
+
+/** Print the report (see printDocument): the dialog on the web, the print sheet in the app. */
+export function printReport(S, opts) {
+ return printDocument(reportPrintHTML(S, opts), t('Performance report'))
+}
+
+/** Print one finished workout. */
+export function printWorkout(S, w, opts) {
+ return printDocument(workoutPrintHTML(S, w, opts), w.name || t('Workout'))
+}
diff --git a/frontend/src/lib/report.js b/frontend/src/lib/report.js
new file mode 100644
index 000000000..2d7e83abf
--- /dev/null
+++ b/frontend/src/lib/report.js
@@ -0,0 +1,242 @@
+// The performance report: everything a stretch of training adds up to, as plain data. The PDF
+// (lib/report-print.js) draws it; this file only counts, so every number on the paper is tested
+// here without a browser.
+//
+// The rules are the app's own, read through the same helpers the Stats screen uses:
+// - volume is workoutVolume (work sets only, both sides of a per-side set, both dumbbells when
+// logged per bell); sets are ticked work sets, a per-side set counting once per side, like the
+// share card (lib/workout-card.js);
+// - muscles are loadOfWorkouts, the Muscle balance card's effective sets;
+// - the 1RM trend is e1rmSeries, the Exercise progress card's "Est. 1RM";
+// - new bests are the ones each workout recorded when it was finished (w.prs).
+// Nothing here writes to the state.
+import { workoutVolume, workoutDuration, workoutDay, workoutAt, doneUnits, streakWeeks } from './history.js'
+import { isWarmupRow } from './workout-model.js'
+import { loadOfWorkouts, rankOf, MUSCLE_NAME } from './muscles.js'
+import { e1rmSeries, bestSetOf, formulaOf } from './onerm.js'
+import { isAssisted } from './exercises.js'
+import { weighInAt } from './bodyweight.js'
+import { isoOf, todayISO, weekKey, weekStartOf } from './format.js'
+
+export const REPORT_RANGES = ['7d', '4w', '3m', 'custom']
+const DAY = 86400000
+
+const dateOf = iso => new Date(iso + 'T12:00:00')
+const addDays = (iso, n) => { const d = dateOf(iso); d.setDate(d.getDate() + n); return isoOf(d) }
+const daysBetween = (a, b) => Math.round((dateOf(b) - dateOf(a)) / DAY)
+const validIso = s => typeof s === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(s) && isoOf(dateOf(s)) === s
+
+/**
+ * The days a report covers, both ends included. '7d' is the last seven days with today, '4w' the
+ * last 28, '3m' back to the same date three months ago (the day after it, so 15 Jul – 15 Oct is
+ * not one day too long). 'custom' takes `from`/`to`; swapped ends are put the right way round,
+ * and an end in the future is cut to today.
+ */
+export function reportRange(range, { from, to, today = todayISO() } = {}) {
+ let start, end = today
+ if (range === '7d') start = addDays(today, -6)
+ else if (range === '4w') start = addDays(today, -27)
+ else if (range === '3m') {
+ const d = dateOf(today); const day = d.getDate()
+ d.setDate(1); d.setMonth(d.getMonth() - 3)
+ d.setDate(Math.min(day, new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate()))
+ start = addDays(isoOf(d), 1)
+ } else {
+ start = validIso(from) ? from : addDays(today, -27)
+ end = validIso(to) ? to : today
+ if (start > end) [start, end] = [end, start]
+ if (end > today) end = today
+ if (start > end) start = end
+ }
+ return { from: start, to: end, days: daysBetween(start, end) + 1 }
+}
+
+// Ticked work sets: warm-ups left out, a per-side set counted once per side.
+export const workSetsOf = w => (w.entries || []).reduce((n, e) => n + (e.sets || []).reduce((m, s) => m + (isWarmupRow(s) ? 0 : doneUnits(s)), 0), 0)
+
+// Legacy records without entries only carry the cached volume (the activity heatmap's rule).
+const volumeOf = w => Array.isArray(w?.entries) ? Math.max(0, Number(workoutVolume(w)) || 0) : Math.max(0, Number(w?.vol) || 0)
+
+export const inRange = (S, { from, to }) => (S.workouts || [])
+ .filter(w => { const d = workoutDay(w); return d && d >= from && d <= to })
+ .sort((a, b) => (workoutAt(a) || 0) - (workoutAt(b) || 0))
+
+/** Headline numbers for a list of workouts (and the weigh-ins over the same days). */
+export function totalsOf(workouts, bodyweight = []) {
+ const t = { workouts: workouts.length, volume: 0, sets: 0, ms: 0, prs: 0, days: 0 }
+ const days = new Set()
+ for (const w of workouts) {
+ t.volume += volumeOf(w)
+ t.sets += workSetsOf(w)
+ t.ms += workoutDuration(w)
+ t.prs += new Set(w.prs || []).size
+ days.add(workoutDay(w))
+ }
+ t.days = days.size
+ t.volume = Math.round(t.volume * 10) / 10
+ const bw = bodyweight.filter(b => b && b.w > 0)
+ t.bwStart = bw.length ? bw[0].w : null
+ t.bwEnd = bw.length ? bw[bw.length - 1].w : null
+ t.bwChange = bw.length > 1 ? Math.round((bw[bw.length - 1].w - bw[0].w) * 10) / 10 : null
+ return t
+}
+
+const weighInsIn = (S, { from, to }) => (S.bodyweight || [])
+ .filter(b => b && validIso(b.d) && b.d >= from && b.d <= to && b.w > 0)
+ .sort((a, b) => weighInAt(a) - weighInAt(b))
+
+/**
+ * Volume, sets and workouts in buckets for the bar chart: one bar per day for a range of two
+ * weeks or less, per week (the profile's first weekday) up to about four months, per month beyond.
+ * Every bucket in the range is there, the empty ones too, so the gaps show.
+ */
+export function bucketsOf(workouts, { from, to, days }, ws) {
+ const unit = days <= 14 ? 'day' : days <= 124 ? 'week' : 'month'
+ const keyOf = iso => unit === 'day' ? iso : unit === 'week' ? weekKey(iso, ws) : iso.slice(0, 7) + '-01'
+ const buckets = []
+ const byKey = {}
+ for (let d = from; d <= to; d = addDays(d, 1)) {
+ const k = keyOf(d)
+ if (!byKey[k]) { byKey[k] = { key: k, from: d, volume: 0, sets: 0, workouts: 0 }; buckets.push(byKey[k]) }
+ }
+ for (const w of workouts) {
+ const b = byKey[keyOf(workoutDay(w))]
+ if (!b) continue
+ b.volume += volumeOf(w); b.sets += workSetsOf(w); b.workouts++
+ }
+ buckets.forEach(b => { b.volume = Math.round(b.volume * 10) / 10 })
+ return { unit, buckets }
+}
+
+/** Every day of the range for the consistency calendar, shaded 0–4 by volume like the heatmap. */
+export function calendarOf(workouts, { from, to }) {
+ const agg = {}
+ for (const w of workouts) {
+ const d = workoutDay(w)
+ const a = agg[d] = agg[d] || { n: 0, volume: 0 }
+ a.n++; a.volume += volumeOf(w)
+ }
+ const values = Object.values(agg).map(a => a.volume).filter(v => v > 0).sort((a, b) => a - b)
+ const q = p => (values.length ? values[Math.min(values.length - 1, Math.floor(p * values.length))] : 0)
+ const t1 = q(0.25), t2 = q(0.5), t3 = q(0.75)
+ const out = []
+ for (let d = from; d <= to; d = addDays(d, 1)) {
+ const a = agg[d]
+ const level = !a ? 0 : !a.volume ? 1 : a.volume >= t3 ? 4 : a.volume >= t2 ? 3 : a.volume >= t1 ? 2 : 1
+ out.push({ d, n: a ? a.n : 0, volume: a ? Math.round(a.volume * 10) / 10 : 0, level })
+ }
+ return out
+}
+
+/**
+ * The lifts worth a trend line: the exercises with the most sessions in the range that produced
+ * an estimated 1RM (ties: the heavier estimate first), at most `max`. Each with its points in the
+ * range, its best, and the change from its first to its last session in the range.
+ */
+export function topLiftsOf(S, workouts, { from, to }, max = 4) {
+ const formula = formulaOf(S)
+ const seen = {}
+ for (const w of workouts) {
+ for (const e of w.entries || []) {
+ if (!e?.id || isAssisted({ id: e.id })) continue
+ const best = bestSetOf(e, formula)
+ if (!best) continue
+ const s = seen[e.id] = seen[e.id] || { id: e.id, sessions: new Set(), top: 0 }
+ s.sessions.add(w.id || workoutAt(w))
+ s.top = Math.max(s.top, best.est)
+ }
+ }
+ return Object.values(seen)
+ .sort((a, b) => b.sessions.size - a.sessions.size || b.top - a.top)
+ .slice(0, max)
+ .map(({ id }) => {
+ const points = e1rmSeries(S, id, formula).filter(p => p.d >= from && p.d <= to).map(p => ({ d: p.d, t: p.t, y: p.y, w: p.w, r: p.r }))
+ const first = points[0], last = points[points.length - 1]
+ const best = points.reduce((b, p) => (!b || p.y > b.y ? p : b), null)
+ return { id, points, best, change: points.length > 1 ? Math.round((last.y - first.y) * 10) / 10 : null }
+ })
+}
+
+/** Each new best a workout in the range recorded, newest first, with the set behind it. */
+export function prsOf(S, workouts) {
+ const formula = formulaOf(S)
+ const out = []
+ for (const w of workouts) {
+ const ids = [...new Set(w.prs || [])]
+ for (const id of ids) {
+ const entry = (w.entries || []).find(e => e.id === id)
+ out.push({ id, d: workoutDay(w), workout: w.name || '', entry: entry || null, best: entry ? bestSetOf(entry, formula) : null })
+ }
+ }
+ return out.sort((a, b) => (a.d < b.d ? 1 : a.d > b.d ? -1 : 0))
+}
+
+/** Muscles by effective sets in the range (Muscle balance), and the ones the range never reached. */
+export function musclesOfRange(workouts) {
+ const load = loadOfWorkouts(workouts)
+ const { worked, missed } = rankOf(load)
+ return {
+ worked: worked.map(slug => ({ slug, name: MUSCLE_NAME[slug] || slug, sets: Math.round(load[slug] * 10) / 10 })),
+ missed: missed.map(slug => ({ slug, name: MUSCLE_NAME[slug] || slug })),
+ }
+}
+
+// Longest run of weeks in a row with at least one workout, within the range.
+function longestWeekRun(workouts, ws) {
+ const weeks = [...new Set(workouts.map(w => weekKey(workoutDay(w), ws)))].sort()
+ let best = 0, run = 0, prev = null
+ for (const k of weeks) {
+ run = prev && daysBetween(prev, k) === 7 ? run + 1 : 1
+ best = Math.max(best, run)
+ prev = k
+ }
+ return best
+}
+
+// Longest run of days in a row with a workout, within the range.
+function longestDayRun(workouts) {
+ const days = [...new Set(workouts.map(workoutDay))].sort()
+ let best = 0, run = 0, prev = null
+ for (const d of days) {
+ run = prev && daysBetween(prev, d) === 1 ? run + 1 : 1
+ best = Math.max(best, run)
+ prev = d
+ }
+ return best
+}
+
+/**
+ * The whole report for `range` (reportRange's '7d' | '4w' | '3m' | 'custom' with from/to).
+ * `prev` holds the same totals for the stretch of equal length just before, for the "vs before"
+ * line under each number.
+ */
+export function reportData(S, { range = '4w', from, to, today = todayISO() } = {}) {
+ const r = reportRange(range, { from, to, today })
+ const ws = weekStartOf(S)
+ const workouts = inRange(S, r)
+ const weighIns = weighInsIn(S, r)
+ const before = { from: addDays(r.from, -r.days), to: addDays(r.from, -1), days: r.days }
+ const prevWorkouts = inRange(S, before)
+ const totals = totalsOf(workouts, weighIns)
+ return {
+ range: { ...r, kind: range },
+ workouts,
+ totals,
+ prev: totalsOf(prevWorkouts, weighInsIn(S, before)),
+ perWeek: Math.round(workouts.length / (r.days / 7) * 10) / 10,
+ buckets: bucketsOf(workouts, r, ws),
+ calendar: calendarOf(workouts, r),
+ muscles: musclesOfRange(workouts),
+ lifts: topLiftsOf(S, workouts, r),
+ prs: prsOf(S, workouts),
+ bodyweight: weighIns.map(b => ({ d: b.d, t: weighInAt(b), w: b.w })),
+ streak: {
+ weeks: r.to === today ? streakWeeks(S) : null,
+ longestWeeks: longestWeekRun(workouts, ws),
+ longestDays: longestDayRun(workouts),
+ activeDays: totals.days,
+ restDays: r.days - totals.days,
+ },
+ weekStart: ws,
+ }
+}
diff --git a/frontend/src/lib/report.test.js b/frontend/src/lib/report.test.js
new file mode 100644
index 000000000..02bf11646
--- /dev/null
+++ b/frontend/src/lib/report.test.js
@@ -0,0 +1,155 @@
+// The performance report's numbers (lib/report.js): every figure the PDF prints is counted here.
+import { describe, it, expect } from 'vitest'
+import { reportRange, reportData, totalsOf, bucketsOf, calendarOf, topLiftsOf, prsOf, inRange, workSetsOf } from './report.js'
+import { reportPrintHTML, workoutPrintHTML, barChartSVG, lineChartSVG } from './report-print.js'
+
+const at = (iso, h = 18) => new Date(iso + `T${String(h).padStart(2, '0')}:00:00`).getTime()
+const workout = (d, entries, extra = {}) => ({ id: 'w' + d, d, start: at(d), end: at(d) + 60 * 60000, name: 'Push', entries, ...extra })
+const bench = (w, reps = [5, 5, 5], warm = true) => ({
+ id: '0025',
+ sets: [...(warm ? [{ w: w / 2, r: 8, done: true, warmup: true }] : []), ...reps.map(r => ({ w, r, done: true }))],
+})
+
+function state() {
+ return {
+ unit: 'kg', weekStart: 1, routines: [], week: {},
+ workouts: [
+ workout('2026-09-10', [bench(80)]), // before both ranges
+ workout('2026-09-30', [bench(90)]), // the 4 weeks before (prev)
+ workout('2026-10-06', [bench(95)], { prs: ['0025'] }),
+ workout('2026-10-08', [bench(97.5, [5, 5, 4])]),
+ workout('2026-10-09', [bench(100), { id: '0027', sets: [{ w: 60, r: 8, done: true }, { w: 60, r: 8, done: false }] }], { prs: ['0025', '0025'], note: 'Good one' }),
+ workout('2026-10-14', [{ id: '0464', mode: 'time', sets: [{ sec: 45, done: true }] }]),
+ ],
+ bodyweight: [{ d: '2026-10-01', w: 81 }, { d: '2026-10-07', w: 80.5 }, { d: '2026-10-14', w: 79.8 }],
+ }
+}
+const TODAY = '2026-10-15'
+
+describe('reportRange', () => {
+ it('counts both ends: 7 days with today, 28 for four weeks', () => {
+ expect(reportRange('7d', { today: TODAY })).toEqual({ from: '2026-10-09', to: TODAY, days: 7 })
+ expect(reportRange('4w', { today: TODAY })).toEqual({ from: '2026-09-18', to: TODAY, days: 28 })
+ })
+ it('three months back to the day after the same date, short months clamped', () => {
+ expect(reportRange('3m', { today: TODAY })).toMatchObject({ from: '2026-07-16', to: TODAY })
+ expect(reportRange('3m', { today: '2026-05-31' })).toMatchObject({ from: '2026-03-01', to: '2026-05-31' })
+ })
+ it('custom: swapped ends put right, the future cut to today, junk falls back to four weeks', () => {
+ expect(reportRange('custom', { from: '2026-10-10', to: '2026-10-01', today: TODAY })).toEqual({ from: '2026-10-01', to: '2026-10-10', days: 10 })
+ expect(reportRange('custom', { from: '2026-10-10', to: '2027-01-01', today: TODAY })).toMatchObject({ to: TODAY })
+ expect(reportRange('custom', { from: 'nope', to: '', today: TODAY })).toMatchObject({ from: '2026-09-18', to: TODAY })
+ })
+})
+
+describe('totals', () => {
+ it('counts work sets only (warm-ups and unticked sets out), volume, time and distinct new bests', () => {
+ const S = state()
+ const ws = inRange(S, reportRange('7d', { today: TODAY }))
+ expect(ws.map(w => w.d)).toEqual(['2026-10-09', '2026-10-14'])
+ const t = totalsOf(ws)
+ expect(t.workouts).toBe(2)
+ expect(t.sets).toBe(3 + 1 + 1) // 3 bench + 1 row (the second not done) + 1 plank
+ expect(t.volume).toBe(100 * 15 + 60 * 8) // warm-up left out
+ expect(t.ms).toBe(2 * 3600000)
+ expect(t.prs).toBe(1) // the same lift twice in one workout is one best
+ expect(workSetsOf(ws[0])).toBe(4)
+ })
+ it('body weight change from the first to the last weigh-in in the range', () => {
+ const R = reportData(state(), { range: '4w', today: TODAY })
+ expect(R.totals.bwStart).toBe(81)
+ expect(R.totals.bwEnd).toBe(79.8)
+ expect(R.totals.bwChange).toBe(-1.2)
+ expect(R.bodyweight).toHaveLength(3)
+ })
+ it('compares with the stretch of the same length just before', () => {
+ const R = reportData(state(), { range: '4w', today: TODAY })
+ expect(R.workouts).toHaveLength(5)
+ expect(R.prev.workouts).toBe(1) // 10 Sep: 2026-08-21 .. 2026-09-17
+ expect(R.prev.volume).toBe(80 * 15)
+ })
+})
+
+describe('charts data', () => {
+ it('a bucket for every day of a short range, every week of a longer one, the empty ones too', () => {
+ const S = state()
+ const r7 = reportRange('7d', { today: TODAY })
+ const b7 = bucketsOf(inRange(S, r7), r7, 1)
+ expect(b7.unit).toBe('day')
+ expect(b7.buckets).toHaveLength(7)
+ expect(b7.buckets.find(b => b.key === '2026-10-09').volume).toBe(1980)
+ const r4 = reportRange('4w', { today: TODAY })
+ const b4 = bucketsOf(inRange(S, r4), r4, 1)
+ expect(b4.unit).toBe('week')
+ expect(b4.buckets.map(b => b.key)).toEqual(['2026-09-14', '2026-09-21', '2026-09-28', '2026-10-05', '2026-10-12'])
+ expect(b4.buckets.find(b => b.key === '2026-10-05').workouts).toBe(3)
+ const r = reportRange('custom', { from: '2026-01-01', to: '2026-10-15', today: TODAY })
+ expect(bucketsOf([], r, 1).unit).toBe('month')
+ })
+ it('the calendar has every day, shaded 0 for rest days', () => {
+ const S = state()
+ const r = reportRange('7d', { today: TODAY })
+ const cal = calendarOf(inRange(S, r), r)
+ expect(cal).toHaveLength(7)
+ expect(cal.filter(d => d.n).map(d => d.d)).toEqual(['2026-10-09', '2026-10-14'])
+ expect(cal.find(d => d.d === '2026-10-10').level).toBe(0)
+ expect(cal.find(d => d.d === '2026-10-09').level).toBeGreaterThan(0)
+ })
+ it('top lifts: most sessions first, with the 1RM change across the range', () => {
+ const S = state()
+ const r = reportRange('4w', { today: TODAY })
+ const [first, second] = topLiftsOf(S, inRange(S, r), r)
+ expect(first.id).toBe('0025')
+ expect(first.points.map(p => p.d)).toEqual(['2026-09-30', '2026-10-06', '2026-10-08', '2026-10-09'])
+ expect(first.change).toBeGreaterThan(0)
+ expect(second.id).toBe('0027')
+ expect(second.change).toBeNull() // one session: no change to report
+ })
+ it('new bests newest first, each with the set behind it', () => {
+ const S = state()
+ const prs = prsOf(S, inRange(S, reportRange('4w', { today: TODAY })))
+ expect(prs.map(p => p.d)).toEqual(['2026-10-09', '2026-10-06'])
+ expect(prs[0].best).toMatchObject({ w: 100, r: 5 })
+ })
+ it('streaks and muscles', () => {
+ const R = reportData(state(), { range: '4w', today: TODAY })
+ expect(R.streak.activeDays).toBe(5)
+ expect(R.streak.longestDays).toBe(2) // 8 and 9 Oct
+ expect(R.streak.longestWeeks).toBe(3) // weeks of 28 Sep, 5 Oct, 12 Oct
+ expect(R.muscles.worked[0].slug).toBe('chest')
+ expect(R.muscles.missed.length).toBeGreaterThan(0)
+ })
+})
+
+describe('report and workout printouts', () => {
+ it('an empty range still prints, and says so', () => {
+ const html = reportPrintHTML({ unit: 'kg', workouts: [], bodyweight: [] }, { range: '7d', today: TODAY })
+ expect(html).toContain('No workouts in this period.')
+ expect(html).toContain('<title>Last 7 days</title>')
+ })
+ it('has every section for a range with training in it', () => {
+ const html = reportPrintHTML(state(), { range: '4w', today: TODAY, owner: 'Ana' })
+ for (const s of ['Volume per week', 'Consistency', 'Sets per muscle', 'Estimated 1RM, top lifts', 'Body weight', 'New bests', 'All workouts']) expect(html).toContain(s)
+ expect(html.match(/<svg class="chart"/g).length).toBeGreaterThanOrEqual(2)
+ expect(html).toContain('Good one')
+ // No exercise media on paper, ever.
+ expect(html).not.toMatch(/<img|\.webp|\.gif|\.mp4/)
+ })
+ it('a workout: every exercise with every set, warm-ups marked', () => {
+ const S = state()
+ const html = workoutPrintHTML(S, S.workouts[4], { owner: 'Ana' })
+ expect(html.match(/<div class="wx">/g)).toHaveLength(2)
+ expect(html).toContain('<span class="k">Warm-up</span>')
+ expect(html).toContain('100×5')
+ expect(html).toContain('class="pr"')
+ expect(html).not.toMatch(/<img|\.webp|\.gif|\.mp4/)
+ })
+ it('charts are plain SVG with round axis numbers', () => {
+ const bars = barChartSVG([{ label: 'a', value: 1200 }, { label: 'b', value: 0 }, { label: 'c', value: 3100 }])
+ expect(bars).toContain('class="bar hot"')
+ expect(bars).toContain('>5,000<')
+ const line = lineChartSVG([{ t: 0, y: 101 }, { t: 1, y: 117 }, { t: 2, y: 113 }])
+ expect(line).toMatch(/>100<|>120</)
+ expect(lineChartSVG([])).toBe('')
+ })
+})
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 2618d79ec..617e5a8cf 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -2469,4 +2469,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'على هذا الجهاز تمرين واحد ليس في هذه النسخة الاحتياطية. الاستبدال يحذفه.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'على هذا الجهاز {0} تمارين ليست في هذه النسخة الاحتياطية. الاستبدال يحذفها.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'الصفحة {0} من {1}',
+ 'Training plan': 'خطة التدريب',
+ 'New best': 'رقم قياسي جديد',
+ 'New bests': 'أرقام قياسية جديدة',
+ 'Last 7 days': 'آخر 7 أيام',
+ 'Last 4 weeks': 'آخر 4 أسابيع',
+ 'Last 3 months': 'آخر 3 أشهر',
+ '{0} days': '{0} أيام',
+ 'One weigh-in': 'وزن واحد',
+ 'No weigh-ins': 'لا توجد أوزان مسجلة',
+ 'Training time': 'وقت التدريب',
+ 'Arrows compare with the {0} days before.': 'تقارن الأسهم بالأيام الـ {0} السابقة.',
+ 'Volume per day': 'الحجم يوميًا',
+ 'Volume per week': 'الحجم أسبوعيًا',
+ 'Volume per month': 'الحجم شهريًا',
+ 'Work sets only, warm-ups left out.': 'مجموعات العمل فقط، بدون الإحماء.',
+ 'Active days': 'أيام النشاط',
+ 'Workouts per week': 'تمارين في الأسبوع',
+ 'Most days in a row': 'أكثر أيام متتالية',
+ 'No muscle work in this period.': 'لا يوجد عمل عضلي في هذه الفترة.',
+ 'Not trained:': 'لم يتم تدريبها:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'المجموعات الفعلية: تُحسب المجموعة كاملة للعضلة الأساسية وجزئيًا للعضلات المساعدة.',
+ 'One session in this period.': 'حصة واحدة في هذه الفترة.',
+ 'No workouts in this period.': 'لا توجد تمارين في هذه الفترة.',
+ 'Consistency': 'الانتظام',
+ 'Sets per muscle': 'مجموعات لكل عضلة',
+ 'Estimated 1RM, top lifts': '1RM التقديري، أهم التمارين',
+ 'All workouts': 'كل التمارين',
+ 'Performance report': 'تقرير الأداء',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'تدريبك على الورق: المجاميع والرسوم البيانية والأرقام القياسية الجديدة وكل مجموعة. علّقه في إطار أو اطبعه أو أرسله لمدربك.',
+ '7 days': '7 أيام',
+ '4 weeks': '4 أسابيع',
+ '3 months': '3 أشهر',
+ 'From': 'من',
+ 'To': 'إلى',
+ 'Create PDF': 'إنشاء PDF',
+ 'Save as PDF': 'حفظ كملف PDF',
+ 'Performance report (PDF)': 'تقرير الأداء (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'رسوم بيانية ومجاميع وكل تمرين في الأيام أو الأسابيع الأخيرة.',
}
diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.js
index 80b006ca5..dead25f80 100644
--- a/frontend/src/locales/bn.js
+++ b/frontend/src/locales/bn.js
@@ -2493,4 +2493,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'এই ডিভাইসে ১টি ওয়ার্কআউট আছে যা এই ব্যাকআপে নেই। প্রতিস্থাপন করলে এটি মুছে যাবে।',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'এই ডিভাইসে {0}টি ওয়ার্কআউট আছে যা এই ব্যাকআপে নেই। প্রতিস্থাপন করলে এগুলো মুছে যাবে।',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'পৃষ্ঠা {0} / {1}',
+ 'Training plan': 'ট্রেনিং প্ল্যান',
+ 'New best': 'নতুন রেকর্ড',
+ 'New bests': 'নতুন রেকর্ড',
+ 'Last 7 days': 'শেষ ৭ দিন',
+ 'Last 4 weeks': 'শেষ ৪ সপ্তাহ',
+ 'Last 3 months': 'শেষ ৩ মাস',
+ '{0} days': '{0} দিন',
+ 'One weigh-in': 'একবার ওজন মাপা',
+ 'No weigh-ins': 'কোনো ওজন মাপা নেই',
+ 'Training time': 'ট্রেনিংয়ের সময়',
+ 'Arrows compare with the {0} days before.': 'তীরচিহ্ন আগের {0} দিনের সাথে তুলনা করে।',
+ 'Volume per day': 'প্রতিদিনের ভলিউম',
+ 'Volume per week': 'প্রতি সপ্তাহের ভলিউম',
+ 'Volume per month': 'প্রতি মাসের ভলিউম',
+ 'Work sets only, warm-ups left out.': 'শুধু ওয়ার্ক সেট, ওয়ার্ম-আপ বাদে।',
+ 'Active days': 'সক্রিয় দিন',
+ 'Workouts per week': 'সপ্তাহে ওয়ার্কআউট',
+ 'Most days in a row': 'টানা সবচেয়ে বেশি দিন',
+ 'No muscle work in this period.': 'এই সময়ে কোনো মাসল ওয়ার্ক নেই।',
+ 'Not trained:': 'ট্রেন করা হয়নি:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'কার্যকর সেট: একটি সেট মূল পেশির জন্য পুরো এবং সাহায্যকারী পেশির জন্য আংশিক গোনা হয়।',
+ 'One session in this period.': 'এই সময়ে একটি সেশন।',
+ 'No workouts in this period.': 'এই সময়ে কোনো ওয়ার্কআউট নেই।',
+ 'Consistency': 'নিয়মিততা',
+ 'Sets per muscle': 'প্রতি পেশিতে সেট',
+ 'Estimated 1RM, top lifts': 'আনুমানিক 1RM, প্রধান ব্যায়াম',
+ 'All workouts': 'সব ওয়ার্কআউট',
+ 'Performance report': 'পারফরম্যান্স রিপোর্ট',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'কাগজে আপনার ট্রেনিং: মোট হিসাব, চার্ট, নতুন রেকর্ড আর প্রতিটি সেট। ফ্রেমে বাঁধান, প্রিন্ট করুন বা কোচকে পাঠান।',
+ '7 days': '৭ দিন',
+ '4 weeks': '৪ সপ্তাহ',
+ '3 months': '৩ মাস',
+ 'From': 'থেকে',
+ 'To': 'পর্যন্ত',
+ 'Create PDF': 'PDF তৈরি করুন',
+ 'Save as PDF': 'PDF হিসেবে সেভ করুন',
+ 'Performance report (PDF)': 'পারফরম্যান্স রিপোর্ট (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'গত কয়েক দিন বা সপ্তাহের চার্ট, মোট হিসাব আর প্রতিটি ওয়ার্কআউট।',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index e092e5278..8a34e3951 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -2434,4 +2434,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Auf diesem Gerät ist 1 Training, das nicht in diesem Backup ist. Ersetzen löscht es.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Auf diesem Gerät sind {0} Trainings, die nicht in diesem Backup sind. Ersetzen löscht sie.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'Seite {0} von {1}',
+ 'Training plan': 'Trainingsplan',
+ 'New best': 'Neue Bestleistung',
+ 'New bests': 'Neue Bestleistungen',
+ 'Last 7 days': 'Letzte 7 Tage',
+ 'Last 4 weeks': 'Letzte 4 Wochen',
+ 'Last 3 months': 'Letzte 3 Monate',
+ '{0} days': '{0} Tage',
+ 'One weigh-in': 'Eine Wägung',
+ 'No weigh-ins': 'Keine Wägungen',
+ 'Training time': 'Trainingszeit',
+ 'Arrows compare with the {0} days before.': 'Die Pfeile vergleichen mit den {0} Tagen davor.',
+ 'Volume per day': 'Volumen pro Tag',
+ 'Volume per week': 'Volumen pro Woche',
+ 'Volume per month': 'Volumen pro Monat',
+ 'Work sets only, warm-ups left out.': 'Nur Arbeitssätze, ohne Aufwärmen.',
+ 'Active days': 'Aktive Tage',
+ 'Workouts per week': 'Trainings pro Woche',
+ 'Most days in a row': 'Meiste Tage am Stück',
+ 'No muscle work in this period.': 'In diesem Zeitraum keine Muskelarbeit.',
+ 'Not trained:': 'Nicht trainiert:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'Effektive Sätze: Ein Satz zählt voll für den Hauptmuskel und anteilig für die Helfer.',
+ 'One session in this period.': 'Eine Einheit in diesem Zeitraum.',
+ 'No workouts in this period.': 'Keine Trainings in diesem Zeitraum.',
+ 'Consistency': 'Regelmässigkeit',
+ 'Sets per muscle': 'Sätze pro Muskel',
+ 'Estimated 1RM, top lifts': 'Geschätztes 1RM, Top-Übungen',
+ 'All workouts': 'Alle Trainings',
+ 'Performance report': 'Leistungsbericht',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'Dein Training auf Papier: Summen, Diagramme, neue Bestleistungen und jeder Satz. Einrahmen, ausdrucken oder deinem Coach schicken.',
+ '7 days': '7 Tage',
+ '4 weeks': '4 Wochen',
+ '3 months': '3 Monate',
+ 'From': 'Von',
+ 'To': 'Bis',
+ 'Create PDF': 'PDF erstellen',
+ 'Save as PDF': 'Als PDF speichern',
+ 'Performance report (PDF)': 'Leistungsbericht (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'Diagramme, Summen und jedes Training der letzten Tage oder Wochen.',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 27517af80..ad31bdf22 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -2414,4 +2414,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tiene 1 entrenamiento que no está en esta copia. Reemplazar lo elimina.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tiene {0} entrenamientos que no están en esta copia. Reemplazar los elimina.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'Página {0} de {1}',
+ 'Training plan': 'Plan de entrenamiento',
+ 'New best': 'Nuevo récord',
+ 'New bests': 'Nuevos récords',
+ 'Last 7 days': 'Últimos 7 días',
+ 'Last 4 weeks': 'Últimas 4 semanas',
+ 'Last 3 months': 'Últimos 3 meses',
+ '{0} days': '{0} días',
+ 'One weigh-in': 'Un pesaje',
+ 'No weigh-ins': 'Sin pesajes',
+ 'Training time': 'Tiempo de entrenamiento',
+ 'Arrows compare with the {0} days before.': 'Las flechas comparan con los {0} días anteriores.',
+ 'Volume per day': 'Volumen por día',
+ 'Volume per week': 'Volumen por semana',
+ 'Volume per month': 'Volumen por mes',
+ 'Work sets only, warm-ups left out.': 'Solo series efectivas, sin calentamiento.',
+ 'Active days': 'Días activos',
+ 'Workouts per week': 'Entrenamientos por semana',
+ 'Most days in a row': 'Más días seguidos',
+ 'No muscle work in this period.': 'Sin trabajo muscular en este periodo.',
+ 'Not trained:': 'Sin entrenar:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'Series efectivas: una serie cuenta entera para su músculo principal y en parte para los que ayudan.',
+ 'One session in this period.': 'Una sesión en este periodo.',
+ 'No workouts in this period.': 'Sin entrenamientos en este periodo.',
+ 'Consistency': 'Constancia',
+ 'Sets per muscle': 'Series por músculo',
+ 'Estimated 1RM, top lifts': '1RM estimado, ejercicios principales',
+ 'All workouts': 'Todos los entrenamientos',
+ 'Performance report': 'Informe de rendimiento',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'Tu entrenamiento en papel: totales, gráficos, nuevos récords y cada serie. Enmárcalo, imprímelo o mándaselo a tu entrenador.',
+ '7 days': '7 días',
+ '4 weeks': '4 semanas',
+ '3 months': '3 meses',
+ 'From': 'Desde',
+ 'To': 'Hasta',
+ 'Create PDF': 'Crear PDF',
+ 'Save as PDF': 'Guardar como PDF',
+ 'Performance report (PDF)': 'Informe de rendimiento (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'Gráficos, totales y cada entrenamiento de los últimos días o semanas.',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 314f49ae5..9fb253162 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -2414,4 +2414,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Cet appareil a 1 séance absente de cette sauvegarde. Remplacer la supprime.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Cet appareil a {0} séances absentes de cette sauvegarde. Remplacer les supprime.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'Page {0} sur {1}',
+ 'Training plan': 'Programme d’entraînement',
+ 'New best': 'Nouveau record',
+ 'New bests': 'Nouveaux records',
+ 'Last 7 days': '7 derniers jours',
+ 'Last 4 weeks': '4 dernières semaines',
+ 'Last 3 months': '3 derniers mois',
+ '{0} days': '{0} jours',
+ 'One weigh-in': 'Une pesée',
+ 'No weigh-ins': 'Aucune pesée',
+ 'Training time': 'Temps d’entraînement',
+ 'Arrows compare with the {0} days before.': 'Les flèches comparent aux {0} jours précédents.',
+ 'Volume per day': 'Volume par jour',
+ 'Volume per week': 'Volume par semaine',
+ 'Volume per month': 'Volume par mois',
+ 'Work sets only, warm-ups left out.': 'Séries de travail seulement, sans échauffement.',
+ 'Active days': 'Jours actifs',
+ 'Workouts per week': 'Séances par semaine',
+ 'Most days in a row': 'Plus de jours d’affilée',
+ 'No muscle work in this period.': 'Aucun travail musculaire sur cette période.',
+ 'Not trained:': 'Pas entraînés :',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'Séries effectives : une série compte en entier pour le muscle principal et en partie pour ceux qui aident.',
+ 'One session in this period.': 'Une séance sur cette période.',
+ 'No workouts in this period.': 'Aucune séance sur cette période.',
+ 'Consistency': 'Régularité',
+ 'Sets per muscle': 'Séries par muscle',
+ 'Estimated 1RM, top lifts': '1RM estimé, exercices phares',
+ 'All workouts': 'Toutes les séances',
+ 'Performance report': 'Rapport de performance',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'Ton entraînement sur papier : totaux, graphiques, nouveaux records et chaque série. À encadrer, imprimer ou envoyer à ton coach.',
+ '7 days': '7 jours',
+ '4 weeks': '4 semaines',
+ '3 months': '3 mois',
+ 'From': 'Du',
+ 'To': 'Au',
+ 'Create PDF': 'Créer le PDF',
+ 'Save as PDF': 'Enregistrer en PDF',
+ 'Performance report (PDF)': 'Rapport de performance (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'Graphiques, totaux et chaque séance des derniers jours ou semaines.',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 9890c6b8f..abc3a2946 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -2414,4 +2414,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'इस डिवाइस पर 1 वर्कआउट है जो इस बैकअप में नहीं है। बदलने से यह मिट जाएगा।',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'इस डिवाइस पर {0} वर्कआउट हैं जो इस बैकअप में नहीं हैं। बदलने से ये मिट जाएँगे।',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'पेज {0} / {1}',
+ 'Training plan': 'ट्रेनिंग प्लान',
+ 'New best': 'नया रिकॉर्ड',
+ 'New bests': 'नए रिकॉर्ड',
+ 'Last 7 days': 'पिछले 7 दिन',
+ 'Last 4 weeks': 'पिछले 4 हफ़्ते',
+ 'Last 3 months': 'पिछले 3 महीने',
+ '{0} days': '{0} दिन',
+ 'One weigh-in': 'एक वज़न',
+ 'No weigh-ins': 'कोई वज़न नहीं',
+ 'Training time': 'ट्रेनिंग का समय',
+ 'Arrows compare with the {0} days before.': 'तीर पिछले {0} दिनों से तुलना करते हैं।',
+ 'Volume per day': 'प्रति दिन वॉल्यूम',
+ 'Volume per week': 'प्रति हफ़्ता वॉल्यूम',
+ 'Volume per month': 'प्रति महीना वॉल्यूम',
+ 'Work sets only, warm-ups left out.': 'सिर्फ़ वर्क सेट, वार्म-अप शामिल नहीं।',
+ 'Active days': 'सक्रिय दिन',
+ 'Workouts per week': 'हर हफ़्ते वर्कआउट',
+ 'Most days in a row': 'लगातार सबसे ज़्यादा दिन',
+ 'No muscle work in this period.': 'इस अवधि में कोई मसल वर्क नहीं।',
+ 'Not trained:': 'ट्रेन नहीं हुए:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'प्रभावी सेट: एक सेट मुख्य मसल के लिए पूरा और मदद करने वाली मसल्स के लिए आंशिक गिना जाता है।',
+ 'One session in this period.': 'इस अवधि में एक सेशन।',
+ 'No workouts in this period.': 'इस अवधि में कोई वर्कआउट नहीं।',
+ 'Consistency': 'नियमितता',
+ 'Sets per muscle': 'प्रति मसल सेट',
+ 'Estimated 1RM, top lifts': 'अनुमानित 1RM, मुख्य एक्सरसाइज़',
+ 'All workouts': 'सभी वर्कआउट',
+ 'Performance report': 'परफ़ॉर्मेंस रिपोर्ट',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'कागज़ पर आपकी ट्रेनिंग: टोटल, चार्ट, नए रिकॉर्ड और हर सेट। फ़्रेम करें, प्रिंट करें या अपने कोच को भेजें।',
+ '7 days': '7 दिन',
+ '4 weeks': '4 हफ़्ते',
+ '3 months': '3 महीने',
+ 'From': 'से',
+ 'To': 'तक',
+ 'Create PDF': 'PDF बनाएँ',
+ 'Save as PDF': 'PDF के रूप में सेव करें',
+ 'Performance report (PDF)': 'परफ़ॉर्मेंस रिपोर्ट (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'पिछले दिनों या हफ़्तों के चार्ट, टोटल और हर वर्कआउट।',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 0b91e9e3c..c426962ea 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -2417,4 +2417,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Ezen az eszközön 1 edzés van, amely nincs ebben a mentésben. A csere törli.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Ezen az eszközön {0} edzés van, amely nincs ebben a mentésben. A csere törli őket.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': '{0}. oldal / {1}',
+ 'Training plan': 'Edzésterv',
+ 'New best': 'Új csúcs',
+ 'New bests': 'Új csúcsok',
+ 'Last 7 days': 'Utolsó 7 nap',
+ 'Last 4 weeks': 'Utolsó 4 hét',
+ 'Last 3 months': 'Utolsó 3 hónap',
+ '{0} days': '{0} nap',
+ 'One weigh-in': 'Egy mérés',
+ 'No weigh-ins': 'Nincs mérés',
+ 'Training time': 'Edzésidő',
+ 'Arrows compare with the {0} days before.': 'A nyilak az előző {0} nappal vetnek össze.',
+ 'Volume per day': 'Volumen naponta',
+ 'Volume per week': 'Volumen hetente',
+ 'Volume per month': 'Volumen havonta',
+ 'Work sets only, warm-ups left out.': 'Csak munkasorozatok, bemelegítés nélkül.',
+ 'Active days': 'Aktív napok',
+ 'Workouts per week': 'Edzés hetente',
+ 'Most days in a row': 'Legtöbb nap egymás után',
+ 'No muscle work in this period.': 'Ebben az időszakban nem volt izommunka.',
+ 'Not trained:': 'Nem edzett:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'Effektív sorozatok: egy sorozat teljesen számít a fő izomnak, részben a segítőknek.',
+ 'One session in this period.': 'Egy edzés ebben az időszakban.',
+ 'No workouts in this period.': 'Ebben az időszakban nincs edzés.',
+ 'Consistency': 'Rendszeresség',
+ 'Sets per muscle': 'Sorozatok izmonként',
+ 'Estimated 1RM, top lifts': 'Becsült 1RM, fő gyakorlatok',
+ 'All workouts': 'Összes edzés',
+ 'Performance report': 'Teljesítményjelentés',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'Az edzésed papíron: összesítők, grafikonok, új csúcsok és minden sorozat. Keretezd be, nyomtasd ki vagy küldd el az edződnek.',
+ '7 days': '7 nap',
+ '4 weeks': '4 hét',
+ '3 months': '3 hónap',
+ 'From': 'Ettől',
+ 'To': 'Eddig',
+ 'Create PDF': 'PDF készítése',
+ 'Save as PDF': 'Mentés PDF-ként',
+ 'Performance report (PDF)': 'Teljesítményjelentés (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'Grafikonok, összesítők és minden edzés az elmúlt napokból vagy hetekből.',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 2a694f890..5e8899160 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -2414,4 +2414,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Su questo dispositivo c’è 1 allenamento che non è in questo backup. Sostituire lo elimina.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Su questo dispositivo ci sono {0} allenamenti che non sono in questo backup. Sostituire li elimina.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'Pagina {0} di {1}',
+ 'Training plan': 'Piano di allenamento',
+ 'New best': 'Nuovo record',
+ 'New bests': 'Nuovi record',
+ 'Last 7 days': 'Ultimi 7 giorni',
+ 'Last 4 weeks': 'Ultime 4 settimane',
+ 'Last 3 months': 'Ultimi 3 mesi',
+ '{0} days': '{0} giorni',
+ 'One weigh-in': 'Una pesata',
+ 'No weigh-ins': 'Nessuna pesata',
+ 'Training time': 'Tempo di allenamento',
+ 'Arrows compare with the {0} days before.': 'Le frecce confrontano con i {0} giorni precedenti.',
+ 'Volume per day': 'Volume al giorno',
+ 'Volume per week': 'Volume a settimana',
+ 'Volume per month': 'Volume al mese',
+ 'Work sets only, warm-ups left out.': 'Solo serie allenanti, riscaldamento escluso.',
+ 'Active days': 'Giorni attivi',
+ 'Workouts per week': 'Allenamenti a settimana',
+ 'Most days in a row': 'Più giorni di fila',
+ 'No muscle work in this period.': 'Nessun lavoro muscolare in questo periodo.',
+ 'Not trained:': 'Non allenati:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'Serie effettive: una serie conta per intero per il muscolo principale e in parte per quelli che aiutano.',
+ 'One session in this period.': 'Una sessione in questo periodo.',
+ 'No workouts in this period.': 'Nessun allenamento in questo periodo.',
+ 'Consistency': 'Costanza',
+ 'Sets per muscle': 'Serie per muscolo',
+ 'Estimated 1RM, top lifts': '1RM stimato, esercizi principali',
+ 'All workouts': 'Tutti gli allenamenti',
+ 'Performance report': 'Report delle prestazioni',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'Il tuo allenamento su carta: totali, grafici, nuovi record e ogni serie. Incornicialo, stampalo o mandalo al tuo coach.',
+ '7 days': '7 giorni',
+ '4 weeks': '4 settimane',
+ '3 months': '3 mesi',
+ 'From': 'Dal',
+ 'To': 'Al',
+ 'Create PDF': 'Crea PDF',
+ 'Save as PDF': 'Salva come PDF',
+ 'Performance report (PDF)': 'Report delle prestazioni (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'Grafici, totali e ogni allenamento degli ultimi giorni o settimane.',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index d1d796aec..2fab59ed9 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -2414,4 +2414,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': '이 기기에 이 백업에 없는 운동이 1개 있습니다. 바꾸면 삭제됩니다.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': '이 기기에 이 백업에 없는 운동이 {0}개 있습니다. 바꾸면 삭제됩니다.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': '{1}쪽 중 {0}쪽',
+ 'Training plan': '운동 계획',
+ 'New best': '새 기록',
+ 'New bests': '새 기록',
+ 'Last 7 days': '최근 7일',
+ 'Last 4 weeks': '최근 4주',
+ 'Last 3 months': '최근 3개월',
+ '{0} days': '{0}일',
+ 'One weigh-in': '체중 기록 1회',
+ 'No weigh-ins': '체중 기록 없음',
+ 'Training time': '운동 시간',
+ 'Arrows compare with the {0} days before.': '화살표는 직전 {0}일과 비교한 값이에요.',
+ 'Volume per day': '일별 볼륨',
+ 'Volume per week': '주별 볼륨',
+ 'Volume per month': '월별 볼륨',
+ 'Work sets only, warm-ups left out.': '본 세트만, 워밍업 제외.',
+ 'Active days': '운동한 날',
+ 'Workouts per week': '주당 운동 횟수',
+ 'Most days in a row': '최장 연속 운동일',
+ 'No muscle work in this period.': '이 기간에는 근육 운동이 없어요.',
+ 'Not trained:': '운동하지 않은 부위:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': '유효 세트: 세트는 주동근에 온전히, 보조근에 일부 계산돼요.',
+ 'One session in this period.': '이 기간에 한 번 운동했어요.',
+ 'No workouts in this period.': '이 기간에는 운동 기록이 없어요.',
+ 'Consistency': '꾸준함',
+ 'Sets per muscle': '근육별 세트',
+ 'Estimated 1RM, top lifts': '예상 1RM, 주요 운동',
+ 'All workouts': '모든 운동',
+ 'Performance report': '운동 성과 리포트',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': '종이에 담은 내 운동: 합계, 차트, 새 기록, 모든 세트. 액자에 걸거나 인쇄하거나 코치에게 보내 보세요.',
+ '7 days': '7일',
+ '4 weeks': '4주',
+ '3 months': '3개월',
+ 'From': '시작',
+ 'To': '끝',
+ 'Create PDF': 'PDF 만들기',
+ 'Save as PDF': 'PDF로 저장',
+ 'Performance report (PDF)': '운동 성과 리포트 (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': '최근 며칠 또는 몇 주의 차트, 합계, 모든 운동.',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 2188107d2..aaafdc5af 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -2414,4 +2414,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Na tym urządzeniu jest 1 trening, którego nie ma w tej kopii. Zastąpienie danych go usunie.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Na tym urządzeniu są treningi, których nie ma w tej kopii ({0}). Zastąpienie danych je usunie.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'Strona {0} z {1}',
+ 'Training plan': 'Plan treningowy',
+ 'New best': 'Nowy rekord',
+ 'New bests': 'Nowe rekordy',
+ 'Last 7 days': 'Ostatnie 7 dni',
+ 'Last 4 weeks': 'Ostatnie 4 tygodnie',
+ 'Last 3 months': 'Ostatnie 3 miesiące',
+ '{0} days': 'Dni: {0}',
+ 'One weigh-in': 'Jedno ważenie',
+ 'No weigh-ins': 'Brak ważeń',
+ 'Training time': 'Czas treningu',
+ 'Arrows compare with the {0} days before.': 'Strzałki porównują z {0} dniami wcześniej.',
+ 'Volume per day': 'Objętość na dzień',
+ 'Volume per week': 'Objętość na tydzień',
+ 'Volume per month': 'Objętość na miesiąc',
+ 'Work sets only, warm-ups left out.': 'Tylko serie robocze, bez rozgrzewki.',
+ 'Active days': 'Aktywne dni',
+ 'Workouts per week': 'Treningi na tydzień',
+ 'Most days in a row': 'Najwięcej dni z rzędu',
+ 'No muscle work in this period.': 'Brak pracy mięśni w tym okresie.',
+ 'Not trained:': 'Nietrenowane:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'Serie efektywne: seria liczy się w całości dla głównego mięśnia i częściowo dla pomocniczych.',
+ 'One session in this period.': 'Jedna sesja w tym okresie.',
+ 'No workouts in this period.': 'Brak treningów w tym okresie.',
+ 'Consistency': 'Regularność',
+ 'Sets per muscle': 'Serie na mięsień',
+ 'Estimated 1RM, top lifts': 'Szacowany 1RM, główne ćwiczenia',
+ 'All workouts': 'Wszystkie treningi',
+ 'Performance report': 'Raport wyników',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'Twój trening na papierze: sumy, wykresy, nowe rekordy i każda seria. Oprawić, wydrukować albo wysłać trenerowi.',
+ '7 days': '7 dni',
+ '4 weeks': '4 tygodnie',
+ '3 months': '3 miesiące',
+ 'From': 'Od',
+ 'To': 'Do',
+ 'Create PDF': 'Utwórz PDF',
+ 'Save as PDF': 'Zapisz jako PDF',
+ 'Performance report (PDF)': 'Raport wyników (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'Wykresy, sumy i każdy trening z ostatnich dni lub tygodni.',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 8722ba9e7..b621a34e3 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1535,6 +1535,9 @@ export const PT_BR_OVERRIDES = {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tem 1 treino que não está neste backup. Substituir exclui esse treino.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tem {0} treinos que não estão neste backup. Substituir exclui esses treinos.',
+ // --- PDF exports and the performance report ---
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'Seu treino no papel: totais, gráficos, novos recordes e cada série. Coloque num quadro, imprima ou envie para o seu treinador.',
+ 'Save as PDF': 'Salvar como PDF',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index ed106827d..981dfba74 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -2414,4 +2414,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Este dispositivo tem 1 treino que não está nesta cópia. Substituir elimina-o.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Este dispositivo tem {0} treinos que não estão nesta cópia. Substituir elimina-os.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'Página {0} de {1}',
+ 'Training plan': 'Plano de treino',
+ 'New best': 'Novo recorde',
+ 'New bests': 'Novos recordes',
+ 'Last 7 days': 'Últimos 7 dias',
+ 'Last 4 weeks': 'Últimas 4 semanas',
+ 'Last 3 months': 'Últimos 3 meses',
+ '{0} days': '{0} dias',
+ 'One weigh-in': 'Uma pesagem',
+ 'No weigh-ins': 'Sem pesagens',
+ 'Training time': 'Tempo de treino',
+ 'Arrows compare with the {0} days before.': 'As setas comparam com os {0} dias anteriores.',
+ 'Volume per day': 'Volume por dia',
+ 'Volume per week': 'Volume por semana',
+ 'Volume per month': 'Volume por mês',
+ 'Work sets only, warm-ups left out.': 'Só séries de trabalho, sem aquecimento.',
+ 'Active days': 'Dias ativos',
+ 'Workouts per week': 'Treinos por semana',
+ 'Most days in a row': 'Mais dias seguidos',
+ 'No muscle work in this period.': 'Sem trabalho muscular neste período.',
+ 'Not trained:': 'Não treinados:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'Séries efetivas: uma série conta por inteiro para o músculo principal e em parte para os que ajudam.',
+ 'One session in this period.': 'Uma sessão neste período.',
+ 'No workouts in this period.': 'Sem treinos neste período.',
+ 'Consistency': 'Regularidade',
+ 'Sets per muscle': 'Séries por músculo',
+ 'Estimated 1RM, top lifts': '1RM estimado, exercícios principais',
+ 'All workouts': 'Todos os treinos',
+ 'Performance report': 'Relatório de desempenho',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'O teu treino em papel: totais, gráficos, novos recordes e cada série. Emoldura, imprime ou envia ao teu treinador.',
+ '7 days': '7 dias',
+ '4 weeks': '4 semanas',
+ '3 months': '3 meses',
+ 'From': 'De',
+ 'To': 'Até',
+ 'Create PDF': 'Criar PDF',
+ 'Save as PDF': 'Guardar como PDF',
+ 'Performance report (PDF)': 'Relatório de desempenho (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'Gráficos, totais e cada treino dos últimos dias ou semanas.',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index c3bfc0ddb..c68305a35 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -2418,4 +2418,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'На этом устройстве есть 1 тренировка, которой нет в этой копии. Замена её удалит.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'На этом устройстве есть тренировки, которых нет в этой копии ({0}). Замена их удалит.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'Страница {0} из {1}',
+ 'Training plan': 'План тренировок',
+ 'New best': 'Новый рекорд',
+ 'New bests': 'Новые рекорды',
+ 'Last 7 days': 'Последние 7 дней',
+ 'Last 4 weeks': 'Последние 4 недели',
+ 'Last 3 months': 'Последние 3 месяца',
+ '{0} days': 'Дней: {0}',
+ 'One weigh-in': 'Одно взвешивание',
+ 'No weigh-ins': 'Нет взвешиваний',
+ 'Training time': 'Время тренировок',
+ 'Arrows compare with the {0} days before.': 'Стрелки сравнивают с {0} днями до этого.',
+ 'Volume per day': 'Объём по дням',
+ 'Volume per week': 'Объём по неделям',
+ 'Volume per month': 'Объём по месяцам',
+ 'Work sets only, warm-ups left out.': 'Только рабочие подходы, без разминки.',
+ 'Active days': 'Активные дни',
+ 'Workouts per week': 'Тренировок в неделю',
+ 'Most days in a row': 'Больше всего дней подряд',
+ 'No muscle work in this period.': 'За этот период нет работы мышц.',
+ 'Not trained:': 'Не тренировались:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'Эффективные подходы: подход считается полностью для основной мышцы и частично для помогающих.',
+ 'One session in this period.': 'Одна тренировка за этот период.',
+ 'No workouts in this period.': 'За этот период нет тренировок.',
+ 'Consistency': 'Регулярность',
+ 'Sets per muscle': 'Подходы на мышцу',
+ 'Estimated 1RM, top lifts': 'Оценка 1ПМ, главные упражнения',
+ 'All workouts': 'Все тренировки',
+ 'Performance report': 'Отчёт о прогрессе',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'Твои тренировки на бумаге: итоги, графики, новые рекорды и каждый подход. Повесь в рамку, распечатай или отправь тренеру.',
+ '7 days': '7 дней',
+ '4 weeks': '4 недели',
+ '3 months': '3 месяца',
+ 'From': 'С',
+ 'To': 'По',
+ 'Create PDF': 'Создать PDF',
+ 'Save as PDF': 'Сохранить как PDF',
+ 'Performance report (PDF)': 'Отчёт о прогрессе (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'Графики, итоги и каждая тренировка за последние дни или недели.',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index b75bf9b03..5d187b416 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -2425,4 +2425,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'อุปกรณ์นี้มีการออกกำลังกาย 1 รายการที่ไม่อยู่ในข้อมูลสำรองนี้ การแทนที่จะลบรายการนั้น',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'อุปกรณ์นี้มีการออกกำลังกาย {0} รายการที่ไม่อยู่ในข้อมูลสำรองนี้ การแทนที่จะลบรายการเหล่านั้น',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'หน้า {0} จาก {1}',
+ 'Training plan': 'แผนการฝึก',
+ 'New best': 'สถิติใหม่',
+ 'New bests': 'สถิติใหม่',
+ 'Last 7 days': '7 วันล่าสุด',
+ 'Last 4 weeks': '4 สัปดาห์ล่าสุด',
+ 'Last 3 months': '3 เดือนล่าสุด',
+ '{0} days': '{0} วัน',
+ 'One weigh-in': 'ชั่งน้ำหนัก 1 ครั้ง',
+ 'No weigh-ins': 'ยังไม่มีการชั่งน้ำหนัก',
+ 'Training time': 'เวลาฝึก',
+ 'Arrows compare with the {0} days before.': 'ลูกศรเทียบกับ {0} วันก่อนหน้า',
+ 'Volume per day': 'วอลุ่มต่อวัน',
+ 'Volume per week': 'วอลุ่มต่อสัปดาห์',
+ 'Volume per month': 'วอลุ่มต่อเดือน',
+ 'Work sets only, warm-ups left out.': 'นับเฉพาะเซ็ตทำงาน ไม่รวมวอร์มอัพ',
+ 'Active days': 'วันที่ฝึก',
+ 'Workouts per week': 'การฝึกต่อสัปดาห์',
+ 'Most days in a row': 'ฝึกติดกันมากที่สุด (วัน)',
+ 'No muscle work in this period.': 'ช่วงนี้ไม่มีการฝึกกล้ามเนื้อ',
+ 'Not trained:': 'ยังไม่ได้ฝึก:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'เซ็ตที่มีผล: หนึ่งเซ็ตนับเต็มให้กล้ามเนื้อหลัก และนับบางส่วนให้กล้ามเนื้อที่ช่วย',
+ 'One session in this period.': 'ช่วงนี้มีการฝึกครั้งเดียว',
+ 'No workouts in this period.': 'ช่วงนี้ไม่มีการฝึก',
+ 'Consistency': 'ความสม่ำเสมอ',
+ 'Sets per muscle': 'เซ็ตต่อกล้ามเนื้อ',
+ 'Estimated 1RM, top lifts': '1RM โดยประมาณ ท่าหลัก',
+ 'All workouts': 'การฝึกทั้งหมด',
+ 'Performance report': 'รายงานผลการฝึก',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'การฝึกของคุณบนกระดาษ: ยอดรวม กราฟ สถิติใหม่ และทุกเซ็ต ใส่กรอบ พิมพ์ หรือส่งให้โค้ชก็ได้',
+ '7 days': '7 วัน',
+ '4 weeks': '4 สัปดาห์',
+ '3 months': '3 เดือน',
+ 'From': 'ตั้งแต่',
+ 'To': 'ถึง',
+ 'Create PDF': 'สร้าง PDF',
+ 'Save as PDF': 'บันทึกเป็น PDF',
+ 'Performance report (PDF)': 'รายงานผลการฝึก (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'กราฟ ยอดรวม และการฝึกทุกครั้งในช่วงวันหรือสัปดาห์ที่ผ่านมา',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index dad1e4041..c8f4f8788 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -2414,4 +2414,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'Bu cihazda bu yedekte olmayan 1 antrenman var. Değiştirmek onu siler.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'Bu cihazda bu yedekte olmayan {0} antrenman var. Değiştirmek onları siler.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'Sayfa {0}/{1}',
+ 'Training plan': 'Antrenman planı',
+ 'New best': 'Yeni rekor',
+ 'New bests': 'Yeni rekorlar',
+ 'Last 7 days': 'Son 7 gün',
+ 'Last 4 weeks': 'Son 4 hafta',
+ 'Last 3 months': 'Son 3 ay',
+ '{0} days': '{0} gün',
+ 'One weigh-in': 'Bir tartılma',
+ 'No weigh-ins': 'Tartılma yok',
+ 'Training time': 'Antrenman süresi',
+ 'Arrows compare with the {0} days before.': 'Oklar önceki {0} günle karşılaştırır.',
+ 'Volume per day': 'Günlük hacim',
+ 'Volume per week': 'Haftalık hacim',
+ 'Volume per month': 'Aylık hacim',
+ 'Work sets only, warm-ups left out.': 'Sadece çalışma setleri, ısınma hariç.',
+ 'Active days': 'Aktif günler',
+ 'Workouts per week': 'Haftada antrenman',
+ 'Most days in a row': 'Üst üste en çok gün',
+ 'No muscle work in this period.': 'Bu dönemde kas çalışması yok.',
+ 'Not trained:': 'Çalışılmayanlar:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'Etkili setler: bir set ana kas için tam, yardımcı kaslar için kısmen sayılır.',
+ 'One session in this period.': 'Bu dönemde tek seans.',
+ 'No workouts in this period.': 'Bu dönemde antrenman yok.',
+ 'Consistency': 'Düzenlilik',
+ 'Sets per muscle': 'Kas başına set',
+ 'Estimated 1RM, top lifts': 'Tahmini 1RM, ana hareketler',
+ 'All workouts': 'Tüm antrenmanlar',
+ 'Performance report': 'Performans raporu',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'Antrenmanın kâğıtta: toplamlar, grafikler, yeni rekorlar ve her set. Çerçevele, yazdır ya da koçuna gönder.',
+ '7 days': '7 gün',
+ '4 weeks': '4 hafta',
+ '3 months': '3 ay',
+ 'From': 'Başlangıç',
+ 'To': 'Bitiş',
+ 'Create PDF': 'PDF oluştur',
+ 'Save as PDF': 'PDF olarak kaydet',
+ 'Performance report (PDF)': 'Performans raporu (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'Son günlerin veya haftaların grafikleri, toplamları ve her antrenmanı.',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index 90e0836d8..709c76f77 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -2411,4 +2411,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': 'На цьому пристрої є 1 тренування, якого немає в цій копії. Заміна його видалить.',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': 'На цьому пристрої є тренування, яких немає в цій копії ({0}). Заміна їх видалить.',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': 'Сторінка {0} з {1}',
+ 'Training plan': 'План тренувань',
+ 'New best': 'Новий рекорд',
+ 'New bests': 'Нові рекорди',
+ 'Last 7 days': 'Останні 7 днів',
+ 'Last 4 weeks': 'Останні 4 тижні',
+ 'Last 3 months': 'Останні 3 місяці',
+ '{0} days': 'Днів: {0}',
+ 'One weigh-in': 'Одне зважування',
+ 'No weigh-ins': 'Немає зважувань',
+ 'Training time': 'Час тренувань',
+ 'Arrows compare with the {0} days before.': 'Стрілки порівнюють із {0} днями перед тим.',
+ 'Volume per day': 'Обсяг за день',
+ 'Volume per week': 'Обсяг за тиждень',
+ 'Volume per month': 'Обсяг за місяць',
+ 'Work sets only, warm-ups left out.': 'Лише робочі підходи, без розминки.',
+ 'Active days': 'Активні дні',
+ 'Workouts per week': 'Тренувань на тиждень',
+ 'Most days in a row': 'Найбільше днів поспіль',
+ 'No muscle work in this period.': 'За цей період немає роботи м’язів.',
+ 'Not trained:': 'Не тренувалися:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': 'Ефективні підходи: підхід рахується повністю для основного м’яза і частково для тих, що допомагають.',
+ 'One session in this period.': 'Одне тренування за цей період.',
+ 'No workouts in this period.': 'За цей період немає тренувань.',
+ 'Consistency': 'Регулярність',
+ 'Sets per muscle': 'Підходи на м’яз',
+ 'Estimated 1RM, top lifts': 'Оцінка 1ПМ, головні вправи',
+ 'All workouts': 'Усі тренування',
+ 'Performance report': 'Звіт про прогрес',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': 'Твої тренування на папері: підсумки, графіки, нові рекорди й кожен підхід. Повісь у рамку, роздрукуй або надішли тренерові.',
+ '7 days': '7 днів',
+ '4 weeks': '4 тижні',
+ '3 months': '3 місяці',
+ 'From': 'З',
+ 'To': 'До',
+ 'Create PDF': 'Створити PDF',
+ 'Save as PDF': 'Зберегти як PDF',
+ 'Performance report (PDF)': 'Звіт про прогрес (PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': 'Графіки, підсумки й кожне тренування за останні дні або тижні.',
}
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index 5077a4e61..4e6bf4563 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -2407,4 +2407,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': '此裝置上有 1 筆訓練紀錄不在此備份中。覆蓋將會刪除它。',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': '此裝置上有 {0} 筆訓練紀錄不在此備份中。覆蓋將會將其全數刪除。',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': '第 {0} 頁,共 {1} 頁',
+ 'Training plan': '訓練計畫',
+ 'New best': '新紀錄',
+ 'New bests': '新紀錄',
+ 'Last 7 days': '最近 7 天',
+ 'Last 4 weeks': '最近 4 週',
+ 'Last 3 months': '最近 3 個月',
+ '{0} days': '{0} 天',
+ 'One weigh-in': '一次量體重',
+ 'No weigh-ins': '沒有體重紀錄',
+ 'Training time': '訓練時間',
+ 'Arrows compare with the {0} days before.': '箭頭是和之前 {0} 天的比較。',
+ 'Volume per day': '每日訓練量',
+ 'Volume per week': '每週訓練量',
+ 'Volume per month': '每月訓練量',
+ 'Work sets only, warm-ups left out.': '只算正式組,不含熱身。',
+ 'Active days': '訓練天數',
+ 'Workouts per week': '每週訓練次數',
+ 'Most days in a row': '最長連續訓練天數',
+ 'No muscle work in this period.': '這段期間沒有肌肉訓練。',
+ 'Not trained:': '未訓練:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': '有效組數:一組對主要肌肉算一整組,對輔助肌肉算一部分。',
+ 'One session in this period.': '這段期間只練了一次。',
+ 'No workouts in this period.': '這段期間沒有訓練。',
+ 'Consistency': '規律性',
+ 'Sets per muscle': '每塊肌肉的組數',
+ 'Estimated 1RM, top lifts': '估算 1RM,主要動作',
+ 'All workouts': '全部訓練',
+ 'Performance report': '訓練表現報告',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': '紙上的訓練:總計、圖表、新紀錄和每一組。裱起來、印出來,或傳給你的教練。',
+ '7 days': '7 天',
+ '4 weeks': '4 週',
+ '3 months': '3 個月',
+ 'From': '從',
+ 'To': '到',
+ 'Create PDF': '產生 PDF',
+ 'Save as PDF': '儲存為 PDF',
+ 'Performance report (PDF)': '訓練表現報告(PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': '最近幾天或幾週的圖表、總計和每次訓練。',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 7857c181c..1165bafe8 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -2414,4 +2414,44 @@ export default {
// --- import with no account: workouts on this device ---
'This device has 1 workout that is not in this backup. Replacing deletes it.': '此设备上有 1 次训练不在此备份中。替换会删除它。',
'This device has {0} workouts that are not in this backup. Replacing deletes them.': '此设备上有 {0} 次训练不在此备份中。替换会删除它们。',
+ // --- PDF exports and the performance report ---
+ 'Page {0} of {1}': '第 {0} 页,共 {1} 页',
+ 'Training plan': '训练计划',
+ 'New best': '新纪录',
+ 'New bests': '新纪录',
+ 'Last 7 days': '最近 7 天',
+ 'Last 4 weeks': '最近 4 周',
+ 'Last 3 months': '最近 3 个月',
+ '{0} days': '{0} 天',
+ 'One weigh-in': '一次称重',
+ 'No weigh-ins': '没有称重记录',
+ 'Training time': '训练时长',
+ 'Arrows compare with the {0} days before.': '箭头是和之前 {0} 天的对比。',
+ 'Volume per day': '每日训练量',
+ 'Volume per week': '每周训练量',
+ 'Volume per month': '每月训练量',
+ 'Work sets only, warm-ups left out.': '只算正式组,不含热身。',
+ 'Active days': '训练天数',
+ 'Workouts per week': '每周训练次数',
+ 'Most days in a row': '最长连续训练天数',
+ 'No muscle work in this period.': '这段时间没有肌肉训练。',
+ 'Not trained:': '未训练:',
+ 'Effective sets: a set counts fully for its main muscle and partly for the ones that help.': '有效组数:一组对主要肌肉算一整组,对辅助肌肉算一部分。',
+ 'One session in this period.': '这段时间只练了一次。',
+ 'No workouts in this period.': '这段时间没有训练。',
+ 'Consistency': '规律性',
+ 'Sets per muscle': '每块肌肉的组数',
+ 'Estimated 1RM, top lifts': '估算 1RM,主要动作',
+ 'All workouts': '全部训练',
+ 'Performance report': '训练表现报告',
+ 'Your training on paper: totals, charts, new bests and every set. Frame it, print it or send it to your coach.': '纸上的训练:总计、图表、新纪录和每一组。裱起来、打印出来,或者发给你的教练。',
+ '7 days': '7 天',
+ '4 weeks': '4 周',
+ '3 months': '3 个月',
+ 'From': '从',
+ 'To': '到',
+ 'Create PDF': '生成 PDF',
+ 'Save as PDF': '保存为 PDF',
+ 'Performance report (PDF)': '训练表现报告(PDF)',
+ 'Charts, totals and every workout of the last days or weeks.': '最近几天或几周的图表、总计和每次训练。',
}
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 0ee471643..f2f42c7ab 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -34,6 +34,8 @@ import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, muscleWei
import { parseImport, mergeImport } from './lib/import-csv.js'
import { importHevyData, HevyApiError, HEVY_DEV_SETTINGS, mergeHevyRoutines } from './lib/import-hevy.js'
import { buildPlanBundle, parsePlan, mergePlan, printPlan, planPrintHTML } from './lib/plan-share.js'
+import { printOptions } from './lib/print-doc.js'
+import { printWorkout } from './lib/report-print.js'
import { estimate1RM, best1RM, is1RMRecord, REP_CAP, formulaOf, FORMULA_NAMES } from './lib/onerm.js'
import { exerciseHistory } from './lib/exercise-history.js'
import { isBellEx, dbLoadOf, dbLoadFor, withDbLoad, withMeaning, historyAs, entryDbLoad, currentDbLoad, isOneArm, ownedWeightsFor, dumbbellsOf, ownsDumbbells, withDumbbells, presetWeights, cleanWeights } from './lib/dumbbells.js'
@@ -2311,7 +2313,7 @@ export async function exportPlanFile() {
// Print plugin — Android WebView has no window.print(). Same printable HTML both ways.
export function printWholePlan() {
const st = S(), owner = useStore.getState().user?.name || ''
- if (MOBILE) printHtml(planPrintHTML(st, owner), t('Weekly Training Plan')).catch(() => { /* dismissed */ })
+ if (MOBILE) printHtml(planPrintHTML(st, owner), t('Weekly Training Plan'), printOptions()).catch(() => { /* dismissed */ })
else printPlan(st, owner)
}
// A picked plan file → the import sheet, or a toast saying why not.
@@ -2676,6 +2678,11 @@ function WorkoutDetail({ w, close }) {
catch (e) { toast(t('Could not create the file')); return }
saveFitFile(new Blob([bytes], { type: 'application/vnd.ant.fit' }), fitFileName(rec))
}
+ const saveAsPdf = () => {
+ saveNote()
+ const rec = { ...(st.workouts.find(x => sameWorkout(x, w)) || w), note: note.trim() }
+ printWorkout(st, rec, { owner: useStore.getState().user?.name || '' })
+ }
const shareAsImage = () => {
const rec = st.workouts.find(x => sameWorkout(x, w)) || w
ui().openSheet(c2 => <ShareWorkoutImage w={rec} nameOf={nameOf} close={c2} />)
@@ -2757,6 +2764,9 @@ function WorkoutDetail({ w, close }) {
<div style={{ height: 8 }} />
<Button icon="share" onClick={shareAsImage}>{t('Share as image')}</Button>
<div style={{ height: 8 }} />
+ {/* On paper: every exercise and every set, the browser's print dialog or the phone's print sheet. */}
+ <Button icon="note" onClick={saveAsPdf}>{t('Save as PDF')}</Button>
+ <div style={{ height: 8 }} />
<Button icon="download" onClick={exportFit}>{t('Export as .fit file')}</Button>
<div style={{ height: 10 }} />
{/* Matched the way the edits above are, not by id: a workout from before ids has none, and
diff --git a/frontend/src/views/History.jsx b/frontend/src/views/History.jsx
index 504c45427..dbcff9f8e 100644
--- a/frontend/src/views/History.jsx
+++ b/frontend/src/views/History.jsx
@@ -5,6 +5,7 @@ import { WorkoutRow, DayNoteRow, workoutDetailSheet, logPastWorkoutSheet } from
import { Button } from '../components/ui.jsx'
import Icon from '../components/Icon.jsx'
import { dayNoteOf } from '../lib/day-notes.js'
+import { reportSheet } from '../components/ReportSheet.jsx'
// Newest first: every workout, and in between them the days off you left a note on (#261). A
// note on a day that has a workout too stays in the day sheet; the workout speaks for that day.
@@ -22,7 +23,8 @@ export default function History() {
const rows = historyRows(S)
return <>
<div className="hdr"><button className="iconbtn" data-back="/stats" onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button>
- <div style={{ flex: 1, marginInlineStart: 12 }}><h1>{t('History')}</h1><div className="sub">{tn('{0} workout', '{0} workouts', S.workouts.length)}</div></div></div>
+ <div style={{ flex: 1, marginInlineStart: 12 }}><h1>{t('History')}</h1><div className="sub">{tn('{0} workout', '{0} workouts', S.workouts.length)}</div></div>
+ {S.workouts.length > 0 && <button className="iconbtn" onClick={reportSheet} aria-label={t('Performance report')} title={t('Performance report')}><Icon name="note" /></button>}</div>
<Button icon="plus" onClick={logPastWorkoutSheet} style={{ marginBottom: 12 }}>{t('Log a past workout')}</Button>
{rows.length ? <div className="list">{rows.map(r => r.w
? <WorkoutRow key={r.w.id} w={r.w} onClick={() => workoutDetailSheet(r.w)} />
diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx
index 65b86f275..2bb058986 100644
--- a/frontend/src/views/RoutineEdit.jsx
+++ b/frontend/src/views/RoutineEdit.jsx
@@ -18,6 +18,7 @@ import SwipeRow from '../components/SwipeRow.jsx'
import { workoutControls } from '../lib/workout-controls.js'
import { copyRoutine, deleteRoutine, replaceSlotExercise } from '../lib/routines.js'
import { planPrintHTML, printPlan } from '../lib/plan-share.js'
+import { printOptions } from '../lib/print-doc.js'
import { markEntryUndone } from '../lib/sync-merge.js'
import { MOBILE, printHtml } from '../lib/mobile.js'
import { speedUnitOf } from '../lib/speed.js'
@@ -425,7 +426,7 @@ export default function RoutineEdit() {
const owner = useStore.getState().user?.name || ''
// Android's print manager refuses a job without a name. The editor never leaves a name blank,
// but a routine that arrived from an import or another client may have none.
- if (MOBILE) printHtml(planPrintHTML(S, owner, { routineId: id }), r.name || t('Routine')).catch(() => { /* dismissed */ })
+ if (MOBILE) printHtml(planPrintHTML(S, owner, { routineId: id }), r.name || t('Routine'), printOptions()).catch(() => { /* dismissed */ })
else printPlan(S, owner, { routineId: id })
}
const toggleLink = i => edit(ex => {
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index 23ccc5958..dc6ba8289 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -51,6 +51,7 @@ import { PAGES, ROOT_GROUPS, pageVisible, searchSettings, pageTrail } from './se
import { platformNow } from '../lib/platform-now.js'
import { pathBefore } from '../lib/nav.js'
import WatchSettingsPage from './WatchSettings.jsx'
+import { reportSheet } from '../components/ReportSheet.jsx'
/* Settings (v1.3.11). The root is one screen: an account card, eleven rows that each open a page
(/settings/<page>), and a search over every row. Rare things live one level further down
@@ -830,6 +831,7 @@ export default function Settings({ page = null, find = null, via = null, entryKe
<Section title={t('Back up')}>
<Row icon="share" iconTint="var(--blue)" title={t('Export backup (JSON)')} subtitle={hasMedia ? t('Without photos and videos') : undefined} accessory="chevron" onClick={doExport} />
{hasMedia && <Row icon="share" iconTint="var(--blue)" title={t('Export with photos & videos (.zip)')} accessory="chevron" onClick={doExportZip} />}
+ <Row icon="note" iconTint="var(--green)" title={t('Performance report (PDF)')} subtitle={t('Charts, totals and every workout of the last days or weeks.')} accessory="chevron" onClick={reportSheet} />
{/* 14 is AUTO_BACKUP_KEEP in lib/mobile.js, written out because the Settings tests mock
that module wholesale; mobile.autobackup.test.js pins the two together. */}
{MOBILE && <Row icon="folder" iconTint="var(--blue)" title={t('Auto-backup on changes')}
diff --git a/frontend/src/views/Stats.jsx b/frontend/src/views/Stats.jsx
index 4ffd3a403..2c3a2a30b 100644
--- a/frontend/src/views/Stats.jsx
+++ b/frontend/src/views/Stats.jsx
@@ -11,6 +11,7 @@ import { bwSheet, goalSheet, calendarSheet, dayOverrideSheet, workoutDetailSheet
import LineChart from '../components/LineChart.jsx'
import Heatmap from '../components/Heatmap.jsx'
import Icon from '../components/Icon.jsx'
+import { reportSheet } from '../components/ReportSheet.jsx'
import BodyMap, { BodyMapLegend } from '../components/BodyMap.jsx'
import { loadOfWeeklyPlan, loadOfWorkouts, muscleBalanceWindow, rankOf, MUSCLES, MUSCLE_NAME, musclesOf } from '../lib/muscles.js'
import { fatigueOf, strengthOf, STRENGTH_FLOOR, LB_TO_KG } from '../lib/recovery.js'
@@ -640,7 +641,10 @@ export default function Stats() {
return <>
<div className="hdr"><div><h1>{t('Stats')}</h1><div className="sub">{t('Progress & history')}</div></div>
- <button className="iconbtn" onClick={() => nav('/history')} aria-label={t('History')}><Icon name="history" /></button></div>
+ <div className="row" style={{ gap: 8 }}>
+ <button className="iconbtn" onClick={reportSheet} aria-label={t('Performance report')} title={t('Performance report')}><Icon name="note" /></button>
+ <button className="iconbtn" onClick={() => nav('/history')} aria-label={t('History')}><Icon name="history" /></button>
+ </div></div>
<div className="tiles">
<div className="tile"><div className="l"><Icon name="dumbbell" />{t('Workouts')}</div><div className="v">{workouts.length}</div></div>
diff --git a/frontend/src/views/settings-pages.js b/frontend/src/views/settings-pages.js
index b6c805a3c..055278773 100644
--- a/frontend/src/views/settings-pages.js
+++ b/frontend/src/views/settings-pages.js
@@ -120,6 +120,7 @@ export const SEARCH = [
// Data & backup
{ page: 'data', title: 'Export backup (JSON)', icon: 'share', tint: 'var(--blue)', kw: 'export backup json download save' },
{ page: 'data', title: 'Export with photos & videos (.zip)', icon: 'share', tint: 'var(--blue)', kw: 'zip media export backup', when: c => c.hasMedia },
+ { page: 'data', title: 'Performance report (PDF)', icon: 'note', tint: 'var(--green)', kw: 'pdf print report performance progress summary charts export paper' },
{ page: 'data', title: 'Auto-backup on changes', icon: 'folder', tint: 'var(--blue)', kw: 'auto backup automatic', when: c => c.mobile },
{ page: 'data', title: 'Backup folder', icon: 'folder', tint: 'var(--blue)', kw: 'auto backup folder location directory', when: c => c.mobile && c.android && c.autoBackup },
{ page: 'data', title: 'Import backup', icon: 'download', tint: 'var(--teal)', kw: 'import restore backup json zip' },