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.

History: share a finished workout as an image (#453)

Claude9f7b5676703f
diff --git a/frontend/src/lib/workout-card.js b/frontend/src/lib/workout-card.js
new file mode 100644
index 000000000..1c9d06cf2
--- /dev/null
+++ b/frontend/src/lib/workout-card.js
@@ -0,0 +1,172 @@
+// A finished workout as a picture, for "Share as image" in its detail sheet (#453): plain text
+// loses its layout in most chat apps, a card keeps it. Three steps, so the part that decides what
+// the card says and where it goes is testable without a canvas:
+// workoutCardModel — what the card says: name, date, duration, sets, volume, new bests
+// layoutWorkoutCard — where each line goes, given a way to measure text
+// drawWorkoutCard — paints a layout onto a 2D canvas context
+// Nothing here stores anything; the workout is read, never written.
+import { sessionSections, workoutVolume, workoutDuration, workoutDay, doneUnits } from './history.js'
+import { EXIDX } from './exercises.js'
+import { isWarmupRow } from './workout-model.js'
+import { fmtDate, fmtVol, durPart, capWords } from './format.js'
+import { t, tn, exerciseNameClass } from './i18n-core.js'
+
+export const CARD_WIDTH = 1080
+const PAD = 88
+const MIN_HEIGHT = 720
+// More than this many new bests and the rest are counted instead of listed: a card that grows
+// past a phone screen is not glanceable any more.
+export const MAX_RECORDS = 6
+const TITLE_LINES = 2
+
+/**
+ * What the card says. `unit` is the profile's, `nameOf(entry)` the exercise's display name — the
+ * same pair "Copy as text" takes (workoutText). Sets are work sets, as the volume is: warm-ups are
+ * left out of both, the way they are left out of records and progression everywhere else. A
+ * per-side set counts once per side, as the workout screen counts it.
+ */
+export function workoutCardModel(w, { unit, nameOf }) {
+ const entries = w.entries || []
+ const sets = entries.reduce((n, e) => n + (e.sets || []).reduce((m, s) => m + (isWarmupRow(s) ? 0 : doneUnits(s)), 0), 0)
+ // New bests in the order the sheet lists the exercises, each named once — a combined session
+ // can hold the same lift twice.
+ const prs = new Set(w.prs || [])
+ const records = []
+ for (const i of sessionSections(entries).flatMap(section => section.units).flat()) {
+ const entry = entries[i]
+ if (!entry || !prs.has(entry.id) || records.some(r => r.id === entry.id)) continue
+ const name = nameOf(entry)
+ records.push({ id: entry.id, name: exerciseNameClass(EXIDX[entry.id]) ? capWords(name) : name })
+ }
+ const day = workoutDay(w)
+ return {
+ title: w.name || '',
+ date: day ? fmtDate(day, true, true) : '',
+ facts: [...durPart(workoutDuration(w)), tn('{0} set', '{0} sets', sets), fmtVol(w.vol ?? workoutVolume(w), unit)],
+ records: records.map(r => r.name),
+ }
+}
+
+// Greedy word wrap to `max` lines; the last line that does not fit is cut with an ellipsis.
+// A word wider than the line on its own (a long German compound) is cut too, never overflowed.
+export function wrapText(text, width, measure, max) {
+ const words = String(text || '').split(/\s+/).filter(Boolean)
+ const lines = []
+ let line = ''
+ for (let i = 0; i < words.length; i++) {
+ const next = line ? line + ' ' + words[i] : words[i]
+ if (measure(next) <= width) { line = next; continue }
+ if (line) lines.push(line)
+ line = words[i]
+ if (lines.length === max) break
+ }
+ if (line && lines.length < max) lines.push(line)
+ const rest = lines.join(' ').length < words.join(' ').length
+ return lines.map((l, i) => (i === lines.length - 1 && (rest || measure(l) > width) ? ellipsize(l, width, measure) : l))
+}
+function ellipsize(text, width, measure) {
+ let s = text
+ while (s && measure(s + '…') > width) s = s.slice(0, -1)
+ return s.trimEnd() + '…'
+}
+
+/**
+ * Where everything goes. `measure(text, weight, size)` returns a width in pixels — the canvas's
+ * measureText in the app, a fake in the tests. `rtl` mirrors the card for Arabic: text anchors
+ * at the right edge and the trophy sits to the right of its line. Returns the canvas size and a
+ * flat list of items for drawWorkoutCard; an item carries its size and weight, the font family is
+ * the drawer's.
+ */
+export function layoutWorkoutCard(model, { measure, rtl = false, width = CARD_WIDTH }) {
+ const items = []
+ const inner = width - PAD * 2
+ const start = rtl ? width - PAD : PAD
+ const dir = rtl ? -1 : 1
+ let y = PAD
+ const text = (str, size, weight, color, x = start) => {
+ items.push({ kind: 'text', text: str, x, y: y + size, size, weight, color })
+ y += Math.round(size * 1.3)
+ }
+
+ items.push({ kind: 'bar', x: start, y, w: 96 * dir, h: 10 })
+ y += 10 + 56
+ for (const line of wrapText(model.title, inner, s => measure(s, 700, 76), TITLE_LINES)) text(line, 76, 700, 'label')
+ if (model.date) { y += 8; text(model.date, 40, 400, 'label2') }
+ y += 40
+ for (const line of wrapText(model.facts.join(' · '), inner, s => measure(s, 600, 46), 2)) text(line, 46, 600, 'label')
+
+ if (model.records.length) {
+ y += 56
+ text(t('New personal records'), 36, 600, 'acc')
+ y += 12
+ const icon = 44
+ const indent = icon + 22
+ const shown = model.records.length > MAX_RECORDS ? model.records.slice(0, MAX_RECORDS - 1) : model.records
+ for (const name of shown) {
+ items.push({ kind: 'trophy', x: rtl ? start - icon : start, y: y + 4, size: icon })
+ const [line] = wrapText(name, inner - indent, s => measure(s, 500, 42), 1)
+ text(line, 42, 500, 'label', start + indent * dir)
+ y += 14
+ }
+ if (shown.length < model.records.length) text(t('and {0} more', model.records.length - shown.length), 38, 400, 'label2', start + indent * dir)
+ }
+
+ y += 64
+ const height = Math.max(MIN_HEIGHT, y + 34 + PAD)
+ items.push({ kind: 'text', text: 'openGym', x: start, y: height - PAD, size: 34, weight: 700, color: 'acc' })
+ return { width, height, rtl, items }
+}
+
+// The trophy from components/Icon.jsx, on its 24×24 grid, so the card and the app agree.
+const TROPHY = [
+ 'M7.6 4h8.8v4.6a4.4 4.4 0 0 1-8.8 0Z',
+ 'M7.6 5.6H4.9v1.5a3 3 0 0 0 2.9 3M16.4 5.6h2.7v1.5a3 3 0 0 1-2.9 3M12 13v3.4M8.6 20.4h6.8l-.7-4H9.3Z',
+]
+export const CARD_FONT = "-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',Roboto,system-ui,sans-serif"
+
+/**
+ * Paint a layout. `colors` holds bg, surface, label, label2 and acc as CSS colours — the app's
+ * current theme and accent, read off the root element by the caller.
+ */
+export function drawWorkoutCard(ctx, layout, colors, family = CARD_FONT) {
+ const { width, height, rtl, items } = layout
+ ctx.fillStyle = colors.bg
+ ctx.fillRect(0, 0, width, height)
+ const inset = 36
+ ctx.fillStyle = colors.surface
+ roundRect(ctx, inset, inset, width - inset * 2, height - inset * 2, 48)
+ ctx.fill()
+ ctx.direction = rtl ? 'rtl' : 'ltr'
+ ctx.textAlign = 'start'
+ ctx.textBaseline = 'alphabetic'
+ for (const item of items) {
+ if (item.kind === 'bar') {
+ ctx.fillStyle = colors.acc
+ roundRect(ctx, Math.min(item.x, item.x + item.w), item.y, Math.abs(item.w), item.h, item.h / 2)
+ ctx.fill()
+ } else if (item.kind === 'trophy') {
+ ctx.save()
+ ctx.translate(item.x, item.y)
+ ctx.scale(item.size / 24, item.size / 24)
+ ctx.strokeStyle = colors.acc
+ ctx.lineWidth = 1.7
+ ctx.lineCap = 'round'
+ ctx.lineJoin = 'round'
+ for (const d of TROPHY) ctx.stroke(new Path2D(d))
+ ctx.restore()
+ } else {
+ ctx.fillStyle = colors[item.color] || colors.label
+ ctx.font = `${item.weight} ${item.size}px ${family}`
+ ctx.fillText(item.text, item.x, item.y)
+ }
+ }
+}
+function roundRect(ctx, x, y, w, h, r) {
+ ctx.beginPath()
+ ctx.moveTo(x + r, y)
+ ctx.arcTo(x + w, y, x + w, y + h, r)
+ ctx.arcTo(x + w, y + h, x, y + h, r)
+ ctx.arcTo(x, y + h, x, y, r)
+ ctx.arcTo(x, y, x + w, y, r)
+ ctx.closePath()
+}
diff --git a/frontend/src/lib/workout-card.test.js b/frontend/src/lib/workout-card.test.js
new file mode 100644
index 000000000..adaa6a2f9
--- /dev/null
+++ b/frontend/src/lib/workout-card.test.js
@@ -0,0 +1,118 @@
+import { describe, expect, it } from 'vitest'
+import { workoutCardModel, layoutWorkoutCard, wrapText, MAX_RECORDS, CARD_WIDTH } from './workout-card.js'
+import { fmtDate } from './format.js'
+
+// #453: a finished workout shared as a picture. A fake measure stands in for the canvas — every
+// character is half its font size wide — so the layout can be checked without one.
+const measure = (text, weight, size) => String(text).length * size * 0.5
+
+describe('workoutCardModel', () => {
+ const names = { bench: 'barbell bench press', curl: 'dumbbell curl', lunge: 'dumbbell lunge' }
+ const nameOf = e => names[e.id] || e.id
+ const w = {
+ id: 'w1', d: '2026-09-03', start: 0, end: 58 * 60000, name: 'Push', vol: 1790,
+ prs: ['curl', 'bench', 'curl'],
+ entries: [
+ { id: 'bench', target: { mode: 'reps' }, sets: [
+ { w: 40, r: 8, done: true, phase: 'warmup' },
+ { w: 60, r: 8, done: true },
+ { w: 60, r: 6, done: true },
+ { w: 60, r: 8, done: false },
+ ] },
+ { id: 'curl', target: { mode: 'reps' }, sets: [{ w: 12, r: 10, done: true }] },
+ { id: 'lunge', target: { mode: 'reps', side: true }, sets: [
+ { w: 10, r: 16, done: true, sides: { L: { w: 10, r: 8, done: true }, R: { w: 10, r: 8, done: true } } },
+ ] },
+ ],
+ }
+
+ it('says the name, the dated day, duration, work sets and volume', () => {
+ const m = workoutCardModel(w, { unit: 'kg', nameOf })
+ expect(m.title).toBe('Push')
+ expect(m.date).toBe(fmtDate('2026-09-03', true, true))
+ // 2 bench work sets (the warm-up and the unticked set are not counted), 1 curl, and the
+ // per-side lunge set once per side.
+ expect(m.facts).toEqual(['58 min', '5 sets', '1,790 kg'])
+ })
+
+ it('lists each new best once, in the order the workout lists the exercises, title-cased', () => {
+ expect(workoutCardModel(w, { unit: 'kg', nameOf }).records).toEqual(['Barbell Bench Press', 'Dumbbell Curl'])
+ })
+
+ it('leaves out a duration it does not know and works the volume out when none was saved', () => {
+ const imported = { ...w, start: undefined, end: undefined, vol: undefined, prs: undefined }
+ const m = workoutCardModel(imported, { unit: 'lb', nameOf })
+ // 60×8 + 60×6 bench, 12×10 curl, 10×8 a side on the lunge; the warm-up adds nothing.
+ expect(m.facts).toEqual(['5 sets', '1,120 lb'])
+ expect(m.records).toEqual([])
+ })
+})
+
+describe('wrapText', () => {
+ const width = 100
+ const m = s => s.length * 10
+
+ it('keeps a line that fits as it is', () => {
+ expect(wrapText('Leg day', width, m, 2)).toEqual(['Leg day'])
+ })
+
+ it('wraps at words and cuts the last line with an ellipsis when it runs out of lines', () => {
+ const lines = wrapText('upper body strength and conditioning', width, m, 2)
+ expect(lines).toHaveLength(2)
+ expect(lines[0]).toBe('upper body')
+ expect(lines[1].endsWith('…')).toBe(true)
+ for (const line of lines) expect(m(line)).toBeLessThanOrEqual(width)
+ })
+
+ it('cuts a single word wider than the line instead of overflowing', () => {
+ const [line] = wrapText('Oberkörpertrainingseinheit', width, m, 1)
+ expect(line.endsWith('…')).toBe(true)
+ expect(m(line)).toBeLessThanOrEqual(width)
+ })
+})
+
+describe('layoutWorkoutCard', () => {
+ const model = { title: 'Push', date: 'Thu, 3 Sep 2026', facts: ['58 min', '5 sets', '1,790 kg'], records: ['Barbell Bench Press'] }
+ const texts = layout => layout.items.filter(i => i.kind === 'text').map(i => i.text)
+
+ it('stacks the title, date, facts, records and the openGym footer, top to bottom', () => {
+ const layout = layoutWorkoutCard(model, { measure })
+ expect(layout.width).toBe(CARD_WIDTH)
+ expect(texts(layout)).toEqual(['Push', 'Thu, 3 Sep 2026', '58 min · 5 sets · 1,790 kg', 'New personal records', 'Barbell Bench Press', 'openGym'])
+ const ys = layout.items.filter(i => i.kind === 'text').map(i => i.y)
+ expect([...ys].sort((a, b) => a - b)).toEqual(ys)
+ expect(layout.items.filter(i => i.kind === 'trophy')).toHaveLength(1)
+ expect(Math.max(...ys)).toBeLessThan(layout.height)
+ })
+
+ it('keeps every line inside the card', () => {
+ const long = { ...model, title: 'A very long routine name that will never fit on one line of the card at all', records: ['an exercise with a name far too long to fit on one line of the card'] }
+ const layout = layoutWorkoutCard(long, { measure })
+ for (const item of layout.items.filter(i => i.kind === 'text')) {
+ expect(item.x + measure(item.text, item.weight, item.size), item.text).toBeLessThanOrEqual(layout.width)
+ }
+ })
+
+ it('counts the new bests past the limit instead of growing without end', () => {
+ const many = { ...model, records: Array.from({ length: 9 }, (_, i) => 'lift ' + i) }
+ const layout = layoutWorkoutCard(many, { measure })
+ expect(layout.items.filter(i => i.kind === 'trophy')).toHaveLength(MAX_RECORDS - 1)
+ expect(texts(layout)).toContain('and 4 more')
+ })
+
+ it('leaves the records section out when there are none', () => {
+ const layout = layoutWorkoutCard({ ...model, records: [] }, { measure })
+ expect(texts(layout)).not.toContain('New personal records')
+ expect(layout.items.some(i => i.kind === 'trophy')).toBe(false)
+ })
+
+ it('mirrors for a right-to-left language: lines start at the right edge', () => {
+ const ltr = layoutWorkoutCard(model, { measure })
+ const rtl = layoutWorkoutCard(model, { measure, rtl: true })
+ expect(rtl.rtl).toBe(true)
+ const title = l => l.items.find(i => i.text === 'Push')
+ expect(title(rtl).x).toBe(rtl.width - title(ltr).x)
+ const trophy = l => l.items.find(i => i.kind === 'trophy')
+ expect(trophy(rtl).x).toBeGreaterThan(rtl.width / 2)
+ })
+})
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index b92f6745e..c58430cd2 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1433,6 +1433,12 @@ export default {
'Copy as text': 'نسخ كنص',
'Copied': 'تم النسخ',
'Could not copy': 'تعذّر النسخ',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'مشاركة كصورة',
+ 'Could not create the image': 'تعذّر إنشاء الصورة',
+ 'Image saved': 'تم حفظ الصورة',
+ 'New personal records': 'أرقام شخصية جديدة',
+ 'and {0} more': 'و{0} أخرى',
'Log this workout': 'سجّل هذا التمرين',
'Mark all sets done': 'تحديد كل المجموعات كمكتملة',
'All weigh-ins': 'كل قياسات الوزن',
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 7fdb20e04..422fc2f57 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1531,6 +1531,12 @@ export default {
'Copy as text': 'Als Text kopieren',
'Copied': 'Kopiert',
'Could not copy': 'Kopieren nicht möglich',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'Als Bild teilen',
+ 'Could not create the image': 'Das Bild konnte nicht erstellt werden',
+ 'Image saved': 'Bild gespeichert',
+ 'New personal records': 'Neue persönliche Rekorde',
+ 'and {0} more': 'und {0} weitere',
// --- a missed day logged afterwards (#284) ---
'Log this workout': 'Dieses Training eintragen',
'Mark all sets done': 'Alle Sätze abhaken',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 592a333e1..e0a76343a 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1511,6 +1511,12 @@ export default {
'Copy as text': 'Copiar como texto',
'Copied': 'Copiado',
'Could not copy': 'No se pudo copiar',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'Compartir como imagen',
+ 'Could not create the image': 'No se pudo crear la imagen',
+ 'Image saved': 'Imagen guardada',
+ 'New personal records': 'Nuevos récords personales',
+ 'and {0} more': 'y {0} más',
// --- a missed day logged afterwards (#284) ---
'Log this workout': 'Registrar este entrenamiento',
'Mark all sets done': 'Marcar todas las series como hechas',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index a6c2a3d84..3cadeb278 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1511,6 +1511,12 @@ export default {
'Copy as text': 'Copier en texte',
'Copied': 'Copié',
'Could not copy': 'Copie impossible',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'Partager en image',
+ 'Could not create the image': 'Impossible de créer l’image',
+ 'Image saved': 'Image enregistrée',
+ 'New personal records': 'Nouveaux records personnels',
+ 'and {0} more': 'et {0} de plus',
// --- a missed day logged afterwards (#284) ---
'Log this workout': 'Enregistrer cette séance',
'Mark all sets done': 'Cocher toutes les séries',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 8c05a4933..16bbd1781 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1511,6 +1511,12 @@ export default {
'Copy as text': 'टेक्स्ट के रूप में कॉपी करें',
'Copied': 'कॉपी हो गया',
'Could not copy': 'कॉपी नहीं हो सका',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'छवि के रूप में साझा करें',
+ 'Could not create the image': 'छवि नहीं बन सकी',
+ 'Image saved': 'छवि सहेजी गई',
+ 'New personal records': 'नए व्यक्तिगत रिकॉर्ड',
+ 'and {0} more': 'और {0} अन्य',
// --- a missed day logged afterwards (#284) ---
'Log this workout': 'यह वर्कआउट दर्ज करें',
'Mark all sets done': 'सभी सेट पूरे मार्क करें',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 3b8a3698f..94848dbf7 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1514,6 +1514,12 @@ export default {
'Copy as text': 'Másolás szövegként',
'Copied': 'Kimásolva',
'Could not copy': 'Nem sikerült másolni',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'Megosztás képként',
+ 'Could not create the image': 'Nem sikerült létrehozni a képet',
+ 'Image saved': 'Kép mentve',
+ 'New personal records': 'Új egyéni csúcsok',
+ 'and {0} more': 'és még {0}',
// --- a missed day logged afterwards (#284) ---
'Log this workout': 'Az edzés rögzítése',
'Mark all sets done': 'Összes sorozat késznek jelölése',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 81f392217..944fe09d9 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1511,6 +1511,12 @@ export default {
'Copy as text': 'Copia come testo',
'Copied': 'Copiato',
'Could not copy': 'Impossibile copiare',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'Condividi come immagine',
+ 'Could not create the image': 'Impossibile creare l’immagine',
+ 'Image saved': 'Immagine salvata',
+ 'New personal records': 'Nuovi record personali',
+ 'and {0} more': 'e altri {0}',
// --- a missed day logged afterwards (#284) ---
'Log this workout': 'Registra questo allenamento',
'Mark all sets done': 'Segna tutte le serie come fatte',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index fc4f356c8..6b1965863 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1511,6 +1511,12 @@ export default {
'Copy as text': '텍스트로 복사',
'Copied': '복사됨',
'Could not copy': '복사할 수 없음',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': '이미지로 공유',
+ 'Could not create the image': '이미지를 만들 수 없습니다',
+ 'Image saved': '이미지를 저장했습니다',
+ 'New personal records': '새 개인 기록',
+ 'and {0} more': '외 {0}개',
// --- a missed day logged afterwards (#284) ---
'Log this workout': '이 운동 기록',
'Mark all sets done': '모든 세트 완료로 표시',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 92579d18f..bcf3645ce 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1511,6 +1511,12 @@ export default {
'Copy as text': 'Kopiuj jako tekst',
'Copied': 'Skopiowano',
'Could not copy': 'Nie udało się skopiować',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'Udostępnij jako obraz',
+ 'Could not create the image': 'Nie udało się utworzyć obrazu',
+ 'Image saved': 'Obraz zapisany',
+ 'New personal records': 'Nowe rekordy życiowe',
+ 'and {0} more': 'i {0} więcej',
// --- a missed day logged afterwards (#284) ---
'Log this workout': 'Zapisz ten trening',
'Mark all sets done': 'Oznacz wszystkie serie jako zrobione',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index c2c52d5f7..1f5b01cef 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1212,6 +1212,12 @@ export const PT_BR_OVERRIDES = {
'Greys show lighter in dark mode, so buttons don’t look switched off.': 'Os cinzas ficam mais claros no modo escuro, para os botões não parecerem desligados.',
'Greys show darker in light mode, so buttons don’t look switched off.': 'Os cinzas ficam mais escuros no modo claro, para os botões não parecerem desligados.',
'Signed in from another tab. Your workout came along, keep going here.': 'Login feito em outra aba. Seu treino veio junto, continue por aqui.',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'Compartilhar como imagem',
+ 'Could not create the image': 'Não foi possível criar a imagem',
+ 'Image saved': 'Imagem salva',
+ 'New personal records': 'Novos recordes pessoais',
+ 'and {0} more': 'e mais {0}',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index ad06595ac..345e75448 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1511,6 +1511,12 @@ export default {
'Copy as text': 'Copiar como texto',
'Copied': 'Copiado',
'Could not copy': 'Não foi possível copiar',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'Partilhar como imagem',
+ 'Could not create the image': 'Não foi possível criar a imagem',
+ 'Image saved': 'Imagem guardada',
+ 'New personal records': 'Novos recordes pessoais',
+ 'and {0} more': 'e mais {0}',
// --- a missed day logged afterwards (#284) ---
'Log this workout': 'Registar este treino',
'Mark all sets done': 'Marcar todas as séries como feitas',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 576e5cbe6..926542698 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1480,6 +1480,12 @@ export default {
'Copy as text': 'Скопировать как текст',
'Copied': 'Скопировано',
'Could not copy': 'Не удалось скопировать',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'Поделиться картинкой',
+ 'Could not create the image': 'Не удалось создать изображение',
+ 'Image saved': 'Изображение сохранено',
+ 'New personal records': 'Новые личные рекорды',
+ 'and {0} more': 'и ещё {0}',
// --- a missed day logged afterwards (#284) ---
'Log this workout': 'Записать эту тренировку',
'Mark all sets done': 'Отметить все подходы выполненными',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 1031f9448..026fc972d 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1522,6 +1522,12 @@ export default {
'Copy as text': 'คัดลอกเป็นข้อความ',
'Copied': 'คัดลอกแล้ว',
'Could not copy': 'คัดลอกไม่ได้',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'แชร์เป็นรูปภาพ',
+ 'Could not create the image': 'สร้างรูปภาพไม่ได้',
+ 'Image saved': 'บันทึกรูปภาพแล้ว',
+ 'New personal records': 'สถิติส่วนตัวใหม่',
+ 'and {0} more': 'และอีก {0} รายการ',
// --- a missed day logged afterwards (#284) ---
'Log this workout': 'บันทึกการฝึกนี้',
'Mark all sets done': 'ทำเครื่องหมายทุกเซ็ตว่าเสร็จแล้ว',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index d6fa067cf..2715021db 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1511,6 +1511,12 @@ export default {
'Copy as text': 'Metin olarak kopyala',
'Copied': 'Kopyalandı',
'Could not copy': 'Kopyalanamadı',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'Görsel olarak paylaş',
+ 'Could not create the image': 'Görsel oluşturulamadı',
+ 'Image saved': 'Görsel kaydedildi',
+ 'New personal records': 'Yeni kişisel rekorlar',
+ 'and {0} more': 've {0} tane daha',
// --- a missed day logged afterwards (#284) ---
'Log this workout': 'Bu antrenmanı kaydet',
'Mark all sets done': 'Tüm setleri tamamlandı olarak işaretle',
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index a4a775ede..ac876d5a4 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1377,6 +1377,12 @@ export default {
'Copy as text': 'Скопіювати як текст',
'Copied': 'Скопійовано',
'Could not copy': 'Не вдалося скопіювати',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': 'Поділитися зображенням',
+ 'Could not create the image': 'Не вдалося створити зображення',
+ 'Image saved': 'Зображення збережено',
+ 'New personal records': 'Нові особисті рекорди',
+ 'and {0} more': 'і ще {0}',
'Log this workout': 'Записати це тренування',
'Mark all sets done': 'Позначити всі підходи виконаними',
'All weigh-ins': 'Усі зважування',
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index 0ab17d0bf..fcc3d5c05 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -1495,6 +1495,12 @@ export default {
'Copy as text': '複製為純文字',
'Copied': '已複製',
'Could not copy': '無法複製',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': '分享為圖片',
+ 'Could not create the image': '無法產生圖片',
+ 'Image saved': '圖片已儲存',
+ 'New personal records': '新個人紀錄',
+ 'and {0} more': '以及另外 {0} 項',
// --- a missed day logged afterwards (#284) ---
'Log this workout': '補記本次訓練',
'Mark all sets done': '將所有組數標記為已完成',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 07765586e..72c89bce7 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1511,6 +1511,12 @@ export default {
'Copy as text': '复制为文本',
'Copied': '已复制',
'Could not copy': '无法复制',
+ // --- a past workout shared as an image (#453) ---
+ 'Share as image': '分享为图片',
+ 'Could not create the image': '无法生成图片',
+ 'Image saved': '图片已保存',
+ 'New personal records': '新个人纪录',
+ 'and {0} more': '以及另外 {0} 项',
// --- a missed day logged afterwards (#284) ---
'Log this workout': '补记这次训练',
'Mark all sets done': '将所有组标为完成',
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index e5e4a6928..871177ee9 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -35,7 +35,7 @@ import { exerciseHistory } from './lib/exercise-history.js'
import { policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS, weightIncrement } from './lib/progression.js'
import { normalizeRepRange } from './lib/rep-range.js'
import { isPyramid, normalizePyramid, normalizePyramidRest, pyramidFromFlat, flatFromPyramid, pyramidLabel, PYRAMID_MAX, MAX_PYRAMID_SETS, PYRAMID_PRESETS } from './lib/pyramid.js'
-import { MOBILE, shareExport, printHtml } from './lib/mobile.js'
+import { MOBILE, shareExport, shareExportBlob, printHtml } from './lib/mobile.js'
import { speedUnitOf, toSpeed, fromSpeed } from './lib/speed.js'
import { buildCompletedWorkout, sessionEnd } from './lib/finish-workout.js'
import { refillAfter } from './lib/rotation.js'
@@ -54,6 +54,7 @@ import { editCompletedSession, editLeftEmpty, editedRecord, editChangesNothing }
import { stampWorkout } from './lib/sync-merge.js'
import { weeklyWeights } from './lib/bodyweight.js'
import { workoutText } from './lib/workout-text.js'
+import { workoutCardModel, layoutWorkoutCard, drawWorkoutCard, CARD_FONT } from './lib/workout-card.js'
import { copyText } from './lib/clipboard.js'
import { queueRemaining, pinState } from './lib/queue.js'
@@ -2213,6 +2214,13 @@ function WorkoutDetail({ w, close }) {
const rec = { ...(st.workouts.find(x => sameWorkout(x, w)) || w), note: note.trim() }
toast(await copyText(workoutText(rec, { unit: st.unit, nameOf, speedUnit: speedUnitOf(st) })) ? t('Copied') : t('Could not copy'))
}
+ const shareAsImage = async () => {
+ const rec = st.workouts.find(x => sameWorkout(x, w)) || w
+ let blob
+ try { blob = await workoutCardImage(rec, { unit: st.unit, nameOf }) } catch (e) { blob = null }
+ if (!blob) { toast(t('Could not create the image')); return }
+ await shareImage(blob, 'opengym-workout-' + (workoutDay(rec) || todayISO()) + '.png', rec.name || 'openGym')
+ }
// A combined session's entries carry a `rid`; group them into per-routine sections in merge
// order, with each section's supersets paired inside it (sessionSections, which "Copy as text"
// reads the workout through too). A legacy single-routine workout (one routineIds, or no rid
@@ -2287,12 +2295,42 @@ function WorkoutDetail({ w, close }) {
})}>{t('Save as routine')}</Button>
<div style={{ height: 8 }} />
<Button icon="copy" onClick={copyAsText}>{t('Copy as text')}</Button>
+ <div style={{ height: 8 }} />
+ <Button icon="share" onClick={shareAsImage}>{t('Share as image')}</Button>
<div style={{ height: 10 }} />
{/* Matched the way the edits above are, not by id: a workout from before ids has none, and
filtering on `x.id !== undefined` took every other one of them with it. */}
<Button variant="danger" onClick={() => confirmSheet({ title: t('Delete workout?'), message: t('This removes it from your history for good.') + mediaGoesToo(S().workouts.find(x => sameWorkout(x, w))), confirmText: t('Delete'), danger: true, onConfirm: () => { update(s => { s.workouts = s.workouts.filter(x => !sameWorkout(x, w)) }); close(); toast(t('Workout deleted')) } })}>{t('Delete workout')}</Button>
</>
}
+// "Share as image" (#453): the card lib/workout-card.js lays out, painted in the theme and accent
+// the app is showing right now, as a PNG.
+async function workoutCardImage(w, opts) {
+ const root = getComputedStyle(document.documentElement)
+ const css = (name, fallback) => root.getPropertyValue(name).trim() || fallback
+ const colors = { bg: css('--bg', '#000'), surface: css('--surface', '#1c1c1e'), label: css('--label', '#fff'), label2: css('--label-2', '#999'), acc: css('--acc', '#30d158') }
+ const canvas = document.createElement('canvas')
+ const ctx = canvas.getContext('2d')
+ if (!ctx) return null
+ const measure = (text, weight, size) => { ctx.font = `${weight} ${size}px ${CARD_FONT}`; return ctx.measureText(text).width }
+ const layout = layoutWorkoutCard(workoutCardModel(w, opts), { measure, rtl: document.documentElement.dir === 'rtl' })
+ canvas.width = layout.width
+ canvas.height = layout.height
+ drawWorkoutCard(ctx, layout, colors)
+ return new Promise(resolve => canvas.toBlob(resolve, 'image/png'))
+}
+// The phone app goes through the OS share sheet the way a backup does; a browser that can share
+// files (most phones) opens its own; anything else saves the picture as a download.
+async function shareImage(blob, name, title) {
+ if (MOBILE) { try { await shareExportBlob(blob, name) } catch (e) { /* share sheet dismissed */ } return }
+ const file = typeof File === 'function' ? new File([blob], name, { type: 'image/png' }) : null
+ if (file && navigator.canShare?.({ files: [file] })) {
+ try { await navigator.share({ files: [file], title }) } catch (e) { /* dismissed */ }
+ return
+ }
+ const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = name; a.click(); URL.revokeObjectURL(a.href)
+ toast(t('Image saved'))
+}
// The sentence a workout's Delete adds when its photos and videos go with it — every file the
// record lists, shown or not. Empty when it has none.
function mediaGoesToo(rec) {