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.

Workouts: attach photos and videos on the finish screen and in the workout's detail

Duarte Santos8add642ca4b5
diff --git a/frontend/src/components/CustomMedia.jsx b/frontend/src/components/CustomMedia.jsx
index f695b0e8f..e2ba568aa 100644
--- a/frontend/src/components/CustomMedia.jsx
+++ b/frontend/src/components/CustomMedia.jsx
@@ -159,6 +159,22 @@ export default function CustomMedia({ ex, id, compact, minimizable }) {
</>
}
+/**
+ * One stored photo, GIF or video on its own, with the same rules as an exercise's: an image
+ * shows, a GIF plays and a tap stills it, a short clip loops muted, a long one shows its poster
+ * and plays with sound and controls on a tap. What the viewer of a workout's photos and videos
+ * shows (WorkoutMedia.jsx). `m` must already have passed normalizeMediaRef.
+ */
+export function MediaView({ m, cls = 'exmedia', name = '', still = false }) {
+ if (!m) return null
+ const motionless = still || reducedMotion()
+ return m.kind === 'video'
+ ? <CustomVideo key={m.hash} m={m} cls={cls} name={name} still={motionless} />
+ : m.kind === 'gif'
+ ? <CustomGif key={m.hash} m={m} cls={cls} name={name} />
+ : <CustomImage key={m.hash} m={m} cls={cls} name={name} />
+}
+
// The tile that stands in for a file that is not here: a spinner-less dumbbell (nothing new to
// translate), and a tap that asks again.
const Tile = () => <div className="exmedia-x"><Icon name="dumbbell" /></div>
diff --git a/frontend/src/components/CustomMediaField.jsx b/frontend/src/components/CustomMediaField.jsx
index af2b7a19b..3f4189bc9 100644
--- a/frontend/src/components/CustomMediaField.jsx
+++ b/frontend/src/components/CustomMediaField.jsx
@@ -45,7 +45,16 @@ export function mediaErrorText(e) {
const KIND_ICON = { image: 'image', gif: 'play', video: 'play' }
-export default function CustomMediaField({ media, url, onChange }) {
+/**
+ * The picking half of a media field, shared by the custom-exercise editor and a workout's photos
+ * and videos (WorkoutMedia.jsx) so both run the very same ingest and store path. pick(file)
+ * turns a picked file into what the state keeps (lib/media-ingest.js: re-encoded or scrubbed,
+ * hashed, with a poster), puts its files into the local store as pending, and resolves the
+ * MediaRef — or null after it toasted why not. `note` is the dim line that says where the files
+ * will live; `canAdd` is false where nothing could keep them (a server without media, or a
+ * browser that cannot store them), `showAdd` false only where the button should not even show.
+ */
+export function useMediaPicker() {
const user = useStore(s => s.user)
const config = useStore(s => s.config)
const [busy, setBusy] = useState(false)
@@ -53,21 +62,11 @@ export default function CustomMediaField({ media, url, onChange }) {
// Whether files picked here outlive the tab: false when IndexedDB is blocked and the store runs
// in memory — then nothing is offered, since a saved exercise would point at nothing tomorrow.
const [storable, setStorable] = useState(true)
- const fileRef = useRef(null)
useEffect(() => {
let alive = true
mediaStore.ready().then(() => { if (alive) setStorable(mediaStore.persistent) }).catch(() => { if (alive) setStorable(false) })
return () => { alive = false }
}, [])
- const m = mediaOf({ media })
- // The draft's files stay out of the local clean-up for as long as this form is open: its
- // one-hour grace would otherwise take a file picked in a form left open longer, and the saved
- // exercise would point at nothing.
- const mainHash = m?.hash, posterHash = m?.poster?.hash
- useEffect(() => {
- if (!mainHash) return undefined
- return mediaStore.hold([mainHash, posterHash])
- }, [mainHash, posterHash])
// Signed in to a server that answered without a `media` block: it predates the feature or has
// MEDIA_UPLOADS=0. Nothing would ever reach it. A config not known yet (an offline start) is
// not that answer — a file picked then waits here and goes up once the server is reached. A
@@ -76,10 +75,8 @@ export default function CustomMediaField({ media, url, onChange }) {
// says nothing about it).
const serverLacks = (!!user || !MOBILE) && !!config && !config.media
- const onFile = async ev => {
- const file = ev.target.files && ev.target.files[0]
- ev.target.value = '' // picking the same file again still fires onChange
- if (!file) return
+ const pick = async file => {
+ if (!file) return null
setBusy(true)
setWarning(null)
try {
@@ -90,14 +87,41 @@ export default function CustomMediaField({ media, url, onChange }) {
// A guest's or a local phone's copy is the only one: ask the browser not to evict it under
// storage pressure. Best effort, and absent on plain http.
if (!user) { try { globalThis.navigator?.storage?.persist?.()?.catch?.(() => {}) } catch { /* not offered */ } }
- onChange({ media: out.media })
if (out.warnings.includes('codec')) setWarning(t('This video may not play on every device — MP4 (H.264) plays everywhere.'))
+ return out.media
} catch (e) {
toast(mediaErrorText(e))
+ return null
} finally {
setBusy(false)
}
}
+ const note = !storable ? t('This browser cannot store photos or videos here.')
+ : serverLacks ? t('Your server does not store photos and videos yet.')
+ : !user ? t('Kept on this device only — Export with photos & videos keeps a copy.')
+ : null
+ return { pick, busy, warning, setWarning, note, showAdd: !serverLacks, canAdd: !busy && storable && !serverLacks }
+}
+
+export default function CustomMediaField({ media, url, onChange }) {
+ const { pick, busy, warning, setWarning, note, showAdd, canAdd } = useMediaPicker()
+ const fileRef = useRef(null)
+ const m = mediaOf({ media })
+ // The draft's files stay out of the local clean-up for as long as this form is open: its
+ // one-hour grace would otherwise take a file picked in a form left open longer, and the saved
+ // exercise would point at nothing.
+ const mainHash = m?.hash, posterHash = m?.poster?.hash
+ useEffect(() => {
+ if (!mainHash) return undefined
+ return mediaStore.hold([mainHash, posterHash])
+ }, [mainHash, posterHash])
+
+ const onFile = async ev => {
+ const file = ev.target.files && ev.target.files[0]
+ ev.target.value = '' // picking the same file again still fires onChange
+ const got = await pick(file)
+ if (got) onChange({ media: got })
+ }
// "0:07 · 2.4 MB": the length of a clip or an animation, and the size of the file itself (the
// unit through the packs' own "{0} MB", so it reads Mo, МБ, م.ب where it should, and the
@@ -106,10 +130,6 @@ export default function CustomMediaField({ media, url, onChange }) {
const subtitle = m
? <span className="cmf-sub"><Icon name={KIND_ICON[m.kind]} />{sizeLine}</span>
: t('Optional — a picture makes it easier to spot in a list.')
- const note = !storable ? t('This browser cannot store photos or videos here.')
- : serverLacks ? t('Your server does not store photos and videos yet.')
- : !user ? t('Kept on this device only — Export with photos & videos keeps a copy.')
- : null
return <div className="cmf">
<Row icon="image" iconTint="var(--blue)" title={t('Photo, GIF or video')} subtitle={subtitle}>
@@ -117,7 +137,7 @@ export default function CustomMediaField({ media, url, onChange }) {
{m && <span className="cmf-thumb"><CustomThumb ex={{ custom: true, media: m }} /></span>}
{/* Hidden on a server that will never take a file; shown but off where this browser
cannot keep one, with the note below saying why. */}
- {!serverLacks && <Button variant="tinted" size="sm" icon={busy ? undefined : 'image'} disabled={busy || !storable} onClick={() => fileRef.current?.click()}>
+ {showAdd && <Button variant="tinted" size="sm" icon={busy ? undefined : 'image'} disabled={!canAdd} onClick={() => fileRef.current?.click()}>
{busy ? t('Loading…') : m ? t('Change') : t('Add')}
</Button>}
{m && <Button variant="ghost" size="sm" icon="xmark" aria-label={t('Remove')} title={t('Remove')} disabled={busy} onClick={() => { setWarning(null); onChange({ media: null }) }} />}
diff --git a/frontend/src/components/Modals.jsx b/frontend/src/components/Modals.jsx
index 64279d902..3ca3ae07e 100644
--- a/frontend/src/components/Modals.jsx
+++ b/frontend/src/components/Modals.jsx
@@ -80,6 +80,10 @@ function Sheet({ sheet }) {
}, [])
const close = () => closeSheet(sheet.id)
+ // Full screen, on black: a photo or video opened from a workout (WorkoutMedia.jsx). No
+ // backdrop to tap, no drag to dismiss — the viewer has its own close button, and back closes
+ // it like any sheet.
+ if (sheet.kind === 'viewer') return <div>{sheet.render(close)}</div>
if (sheet.kind === 'center') {
return (
<div>
diff --git a/frontend/src/components/WorkoutMedia.jsx b/frontend/src/components/WorkoutMedia.jsx
new file mode 100644
index 000000000..5f6327561
--- /dev/null
+++ b/frontend/src/components/WorkoutMedia.jsx
@@ -0,0 +1,136 @@
+// The photos and videos of a logged workout — a progress photo, a form-check clip — on the finish
+// screen and in the workout's detail sheet, and the full-screen viewer they open in.
+//
+// The same machinery as a custom exercise's picture, on purpose: a pick runs through the same
+// ingest and lands in the same local store as pending (useMediaPicker), the list is written to
+// the saved workout through lib/workout-media.js (stamped, so the sync keeps the version edited
+// last), the same sync uploads it and counts it as owed until the server has it, and thumbnails
+// and the viewer show from the local store exactly as CustomMedia does — posters only in the
+// grid, a main file only once it is opened (or made local by the sync), nothing ever loaded from
+// a server URL. They are the owner's own: no Coach payload, MCP tool, plan file or "Copy as text"
+// reads `media`; only the zip backup carries the files.
+import { useEffect, useRef, useState } from 'react'
+import { useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { t } from '../lib/i18n.js'
+import { workoutMediaOf, WORKOUT_MEDIA_MAX } from '../lib/media-refs.js'
+import { addWorkoutMedia, removeWorkoutMedia } from '../lib/workout-media.js'
+import { sameWorkout } from '../lib/workout-date.js'
+import { syncMedia } from '../lib/media-sync.js'
+import { useMediaPicker } from './CustomMediaField.jsx'
+import { CustomThumb, MediaView } from './CustomMedia.jsx'
+import { Button } from './ui.jsx'
+import Icon from './Icon.jsx'
+
+const toast = m => useUI.getState().toast(m)
+
+// The saved record `w` stands for, as the store holds it now: another device, the date row or
+// this very sheet may have written it since the caller got its copy.
+const useRecord = w => useStore(s => (s.S.workouts || []).find(x => x && sameWorkout(x, w)) || null)
+
+/** The number of photos and videos a workout shows — for the history row's small badge. */
+export const workoutMediaCount = w => workoutMediaOf(w).length
+
+/**
+ * The grid of a workout's photos and videos with its Add tile. `hint` adds the one-line
+ * explanation shown on the finish screen while there is nothing yet.
+ */
+export default function WorkoutMediaSection({ w, hint = false }) {
+ const rec = useRecord(w)
+ const update = useStore(s => s.update)
+ const { pick, busy, warning, note, showAdd, canAdd } = useMediaPicker()
+ const fileRef = useRef(null)
+ if (!rec) return null
+ const list = workoutMediaOf(rec)
+ const room = WORKOUT_MEDIA_MAX - list.length
+
+ const onFiles = async ev => {
+ const files = [...(ev.target.files || [])]
+ ev.target.value = '' // picking the same file again still fires onChange
+ let added = 0
+ let full = false
+ for (const file of files) {
+ const got = await pick(file)
+ if (!got) continue
+ let res
+ update(s => { res = addWorkoutMedia(s, w, got) })
+ if (res === 'added') added++
+ else if (res === 'full') { full = true; break }
+ else if (res === 'gone') { toast(t('Workout deleted')); break }
+ }
+ if (full) toast(t('Up to {0} photos or videos per workout.', WORKOUT_MEDIA_MAX))
+ // Straight up, like an exercise's picture on save: the state push waits for its debounce.
+ if (added) syncMedia({ force: true })
+ }
+
+ return <div className="wmedia">
+ <div className="small muted wmedia-h">{t('Photos & videos')}</div>
+ {(list.length > 0 || showAdd) && <div className="wmedia-grid">
+ {list.map((m, i) => (
+ <button key={m.hash} type="button" className="wmedia-item" data-swipe-ignore
+ aria-label={t('Photo or video {0} of {1}', i + 1, list.length)}
+ onClick={() => openWorkoutMediaViewer(w, i)}>
+ <CustomThumb ex={{ custom: true, media: m }} />
+ {m.kind !== 'image' && <span className="wmedia-kind"><Icon name="play" /></span>}
+ </button>
+ ))}
+ {showAdd && room > 0 && (
+ <button type="button" className="wmedia-add" disabled={!canAdd} onClick={() => fileRef.current?.click()}>
+ <Icon name={busy ? 'image' : 'plus'} />
+ <span>{busy ? t('Loading…') : t('Add photo or video')}</span>
+ </button>
+ )}
+ </div>}
+ <input ref={fileRef} type="file" accept="image/*,video/*" multiple hidden onChange={onFiles} />
+ {hint && !list.length && showAdd && <div className="small dim wmedia-note">{t('A progress photo or a form-check video, kept with this workout.')}</div>}
+ {room <= 0 && <div className="small dim wmedia-note">{t('Up to {0} photos or videos per workout.', WORKOUT_MEDIA_MAX)}</div>}
+ {warning && <div className="small dim wmedia-note">{warning}</div>}
+ {note && <div className="small dim wmedia-note">{note}</div>}
+ </div>
+}
+
+/** Opens the full-screen viewer on the `index`-th photo or video of the saved workout `w`. */
+export function openWorkoutMediaViewer(w, index = 0) {
+ useUI.getState().openSheet(close => <WorkoutMediaViewer w={w} index={index} close={close} />, { kind: 'viewer' })
+}
+
+export function WorkoutMediaViewer({ w, index = 0, close }) {
+ const rec = useRecord(w)
+ const update = useStore(s => s.update)
+ const list = workoutMediaOf(rec)
+ const [i, setI] = useState(index)
+ const [asking, setAsking] = useState(false)
+ const at = Math.min(i, list.length - 1)
+ const m = at >= 0 ? list[at] : null
+ // The last one removed here, or the workout deleted on another device: nothing left to show.
+ useEffect(() => { if (!m) close() }, [!m])
+ if (!m) return null
+ const go = d => { setAsking(false); setI((at + d + list.length) % list.length) }
+ const remove = () => {
+ let removed = false
+ update(s => { removed = removeWorkoutMedia(s, w, m.hash) })
+ setAsking(false)
+ if (removed && at >= list.length - 1) setI(Math.max(0, at - 1))
+ }
+ return <div className="mviewer" role="dialog" aria-modal="true" aria-label={t('Photos & videos')}>
+ <div className="mviewer-bar">
+ <button type="button" className="iconbtn" aria-label={t('Close')} onClick={close}><Icon name="xmark" /></button>
+ <span className="mviewer-count" dir="ltr">{at + 1} / {list.length}</span>
+ <button type="button" className="iconbtn" aria-label={t('Remove')} onClick={() => setAsking(a => !a)}><Icon name="trash" /></button>
+ </div>
+ <div className="mviewer-stage">
+ <MediaView key={m.hash} m={m} cls="exmedia viewer" name={rec?.name || ''} />
+ </div>
+ {asking && <div className="mviewer-ask">
+ <div className="mviewer-ask-t">{t('Remove this photo or video?')}</div>
+ <div className="mviewer-ask-b">
+ <Button variant="ghost" size="sm" onClick={() => setAsking(false)}>{t('Cancel')}</Button>
+ <Button variant="danger" size="sm" onClick={remove}>{t('Remove')}</Button>
+ </div>
+ </div>}
+ {list.length > 1 && !asking && <div className="mviewer-nav">
+ <button type="button" className="iconbtn" aria-label={t('Previous')} onClick={() => go(-1)}><Icon name="chevronLeft" /></button>
+ <button type="button" className="iconbtn" aria-label={t('Next')} onClick={() => go(1)}><Icon name="chevronRight" /></button>
+ </div>}
+ </div>
+}
diff --git a/frontend/src/index.css b/frontend/src/index.css
index 475666897..2b5ab1fc3 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -826,6 +826,46 @@ body.chips-dragging *{cursor:inherit}
.cmf-sub .icn{font-size:13px}
.cmf-note{margin:0 4px 6px;line-height:1.35}
.cmf-link{margin-top:4px}
+/* A logged workout's photos and videos (WorkoutMedia.jsx): a grid of posters with an Add tile,
+ and the full-screen viewer they open in. Logical properties only, so RTL mirrors by itself. */
+.wmedia{margin:4px 0 12px}
+.wmedia-h{margin:0 0 6px}
+.wmedia-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(72px,1fr));gap:8px}
+.wmedia-item,.wmedia-add{
+ position:relative;aspect-ratio:1;border:0;padding:0;border-radius:10px;overflow:hidden;
+ background:var(--surface-2);color:var(--label-2);cursor:pointer;font:inherit;
+}
+.wmedia-item .thumb{width:100%;height:100%;border-radius:0;display:block}
+.wmedia-item .thumb-x{font-size:22px}
+.wmedia-kind{
+ position:absolute;inset-inline-end:5px;bottom:5px;width:22px;height:22px;border-radius:99px;
+ display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.55);color:#fff;font-size:12px;
+}
+.wmedia-add{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:4px;
+ color:var(--acc);font-size:11px;line-height:1.2;text-align:center;padding:6px;
+ border:1.5px dashed var(--sep)}
+.wmedia-add .icn{font-size:20px}
+.wmedia-add:disabled{opacity:.5;cursor:default}
+.wmedia-note{margin:6px 2px 0;line-height:1.35}
+.wrow-media{display:inline-flex;align-items:center;gap:3px;font-size:12px;color:var(--label-2);flex:none}
+.wrow-media .icn{font-size:13px}
+.mviewer{
+ position:absolute;inset:0;background:#000;color:#fff;display:flex;flex-direction:column;
+ padding:var(--sat) 0 var(--sab);animation:pop-fade .2s var(--ease);
+}
+@keyframes pop-fade{from{opacity:0}to{opacity:1}}
+.mviewer-bar{display:flex;align-items:center;justify-content:space-between;padding:6px 8px;flex:none}
+.mviewer .iconbtn{color:#fff;background:rgba(255,255,255,.12)}
+.mviewer-count{font-size:14px;font-variant-numeric:tabular-nums;opacity:.85}
+.mviewer-stage{flex:1;min-height:0;display:flex}
+.exmedia.viewer{flex:1;min-width:0;margin:0;border-radius:0;background:#000;display:flex;align-items:center;justify-content:center}
+.exmedia.viewer img,.exmedia.viewer video{width:100%;height:100%;max-height:100%;object-fit:contain;background:#000}
+.exmedia.viewer .exmedia-x{height:100%;color:rgba(255,255,255,.5)}
+.mviewer-nav{display:flex;justify-content:space-between;padding:8px 12px;flex:none}
+[dir="rtl"] .mviewer-nav .icn{transform:scaleX(-1)}
+.mviewer-ask{flex:none;padding:12px 16px;background:rgba(255,255,255,.08)}
+.mviewer-ask-t{font-weight:600;margin-bottom:10px}
+.mviewer-ask-b{display:flex;gap:8px;justify-content:flex-end}
.sethead{
display:flex;align-items:center;gap:8px;padding:0 0 6px;
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index 897a1bc63..d46135ddb 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('645f13953bd5e46cda6caeb469dd207efa95b22b275c1179536075d124417e30')
+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('1af9daba9d909eb5fd32368632dadaf62f606e152f8f9ae808cb9339a070cac6')
})
test('does not leak European Portuguese UI terms', () => {
diff --git a/frontend/src/lib/session-edit.js b/frontend/src/lib/session-edit.js
index 7c6374e1a..30be88d74 100644
--- a/frontend/src/lib/session-edit.js
+++ b/frontend/src/lib/session-edit.js
@@ -110,6 +110,9 @@ export function editCompletedSession(state, ref) {
}
// Worked out again on Save, from the edited sets.
for (const k of ['vol', 'prs', '_ts']) delete active[k]
+ // The workout's photos and videos are not the editor's: they stay on the saved record, which
+ // Save spreads under the edit, and the detail sheet adds or removes them there meanwhile.
+ delete active.media
state.active = active
return active
}
diff --git a/frontend/src/lib/workout-media.js b/frontend/src/lib/workout-media.js
new file mode 100644
index 000000000..2ce29b422
--- /dev/null
+++ b/frontend/src/lib/workout-media.js
@@ -0,0 +1,60 @@
+// The photos and videos of a logged workout: a progress photo, a form-check clip.
+//
+// Nothing new under the hood: a workout's `media` is a list of the same MediaRefs a custom
+// exercise carries (lib/media-refs.js), made by the same ingest, kept in the same local store,
+// uploaded by the same sync and swept by the same GC — which is why referencedHashes walks
+// workouts[].media on both the server and the client. This file only edits the list on a saved
+// workout, the one place it is written.
+//
+// Each edit is an edit of the saved workout, so it is stamped (stampWorkout) the way a corrected
+// note or a moved date is: a conflict between two copies keeps the version edited last, and a
+// photo added on the phone is not lost to the desktop's copy just because that one logged a
+// weigh-in since (lib/sync-merge.js). Only a real change stamps — a stamp outranks whatever
+// another device wrote since.
+import { normalizeMediaRef, workoutMediaOf, WORKOUT_MEDIA_MAX } from './media-refs.js'
+import { sameWorkout } from './workout-date.js'
+import { stampWorkout } from './sync-merge.js'
+
+const recordOf = (state, w) => (Array.isArray(state?.workouts) ? state.workouts.find(x => x && sameWorkout(x, w)) : null) || null
+
+function write(rec, list, now) {
+ if (list.length) rec.media = list
+ else delete rec.media
+ stampWorkout(rec, now)
+}
+
+/**
+ * Adds a photo or video to the saved workout `w` (the record or a copy of it) inside `state`.
+ * Returns 'added', or why not: 'gone' (the workout was deleted meanwhile), 'invalid' (not a
+ * MediaRef normalizeMediaRef accepts), 'full' (already WORKOUT_MEDIA_MAX) or 'dup' (that very
+ * file is already on it). Mutates `state` — made for useStore's update().
+ */
+export function addWorkoutMedia(state, w, ref, now = Date.now()) {
+ const rec = recordOf(state, w)
+ if (!rec) return 'gone'
+ const m = normalizeMediaRef(ref)
+ if (!m) return 'invalid'
+ const list = workoutMediaOf(rec)
+ if (list.some(x => x.hash === m.hash)) return 'dup'
+ if (list.length >= WORKOUT_MEDIA_MAX) return 'full'
+ write(rec, [...list, m], now)
+ return 'added'
+}
+
+/**
+ * Takes the file `hash` off the saved workout `w`. Returns whether anything changed. The file
+ * itself is left to the GCs: another device, a stash or an exercise may still refer to it, and
+ * the server keeps it for its grace period either way.
+ */
+export function removeWorkoutMedia(state, w, hash, now = Date.now()) {
+ const rec = recordOf(state, w)
+ if (!rec) return false
+ const list = workoutMediaOf(rec)
+ const left = list.filter(x => x.hash !== hash)
+ if (left.length === list.length) return false
+ write(rec, left, now)
+ return true
+}
+
+/** Whether another photo or video still fits on `w`. */
+export const workoutMediaRoom = w => workoutMediaOf(w).length < WORKOUT_MEDIA_MAX
diff --git a/frontend/src/lib/workout-media.test.js b/frontend/src/lib/workout-media.test.js
new file mode 100644
index 000000000..4b5e46257
--- /dev/null
+++ b/frontend/src/lib/workout-media.test.js
@@ -0,0 +1,161 @@
+// The photos and videos of a logged workout: the list on the saved record (add, remove, cap,
+// stamp), what the sync merge keeps of it, what the history editor does with it, and the places
+// that must never carry it (copy as text, a routine saved from the workout, a plan file).
+import { describe, expect, it } from 'vitest'
+import { addWorkoutMedia, removeWorkoutMedia, workoutMediaRoom } from './workout-media.js'
+import { WORKOUT_MEDIA_MAX, workoutMediaOf, referencedHashes, referencedFiles, stateMediaRefs } from './media-refs.js'
+import { mergeStates } from './sync-merge.js'
+import { editCompletedSession, saveWorkoutEdit } from './session-edit.js'
+import { workoutText } from './workout-text.js'
+import { saveSessionAsRoutine } from './session-routines.js'
+import { buildPlanBundle } from './plan-share.js'
+
+const H = n => String(n).repeat(64).slice(0, 64)
+const photo = (h, poster) => ({ kind: 'image', hash: h, mime: 'image/webp', size: 1000, width: 800, height: 600, ...(poster ? { poster: { hash: poster, mime: 'image/webp', size: 100, width: 480, height: 360 } } : {}), at: 1 })
+const clip = (h, poster) => ({ kind: 'video', hash: h, mime: 'video/mp4', size: 500000, width: 1280, height: 720, dur: 8, codec: 'avc1', ...(poster ? { poster: { hash: poster, mime: 'image/webp', size: 100, width: 480, height: 270 } } : {}), at: 2 })
+const set = (w, r) => ({ w, r, done: true })
+const workout = over => ({ id: 'w1', d: '2026-09-20', start: 1000, end: 4000, name: 'Push', routineIds: [], routineId: null, entries: [{ id: 'bench', sets: [set(60, 5)], topW: 60, target: null }], prs: [], vol: 300, ...over })
+const state = (...ws) => ({ unit: 'kg', workouts: ws, routines: [], customEx: [], exWeights: {}, bodyweight: [], active: null })
+
+describe('addWorkoutMedia / removeWorkoutMedia', () => {
+ it('adds a normalised ref to the saved record and stamps it', () => {
+ const S = state(workout())
+ expect(addWorkoutMedia(S, { id: 'w1' }, { ...photo(H(1), H(2)), name: 'IMG_1.HEIC' }, 777)).toBe('added')
+ expect(S.workouts[0].media).toEqual([photo(H(1), H(2))])
+ expect(S.workouts[0]._ts).toBe(777)
+ })
+
+ it('finds a workout from before ids by its day and start', () => {
+ const legacy = workout({ id: undefined })
+ delete legacy.id
+ const S = state(legacy)
+ expect(addWorkoutMedia(S, { d: legacy.d, start: legacy.start }, photo(H(1)), 5)).toBe('added')
+ expect(S.workouts[0].media).toHaveLength(1)
+ expect(S.workouts[0].id).toBeUndefined()
+ })
+
+ it('refuses a malformed ref, the same file twice, a deleted workout and a seventh item — without stamping', () => {
+ const S = state(workout({ _ts: 3 }))
+ expect(addWorkoutMedia(S, { id: 'w1' }, { ...photo(H(1)), mime: 'image/svg+xml' }, 9)).toBe('invalid')
+ expect(addWorkoutMedia(S, { id: 'nope' }, photo(H(1)), 9)).toBe('gone')
+ expect(S.workouts[0]._ts).toBe(3)
+ for (let i = 0; i < WORKOUT_MEDIA_MAX; i++) expect(addWorkoutMedia(S, { id: 'w1' }, photo(H(i)), 10 + i)).toBe('added')
+ expect(workoutMediaRoom(S.workouts[0])).toBe(false)
+ const stamp = S.workouts[0]._ts
+ expect(addWorkoutMedia(S, { id: 'w1' }, photo(H(0)), 99)).toBe('dup')
+ expect(addWorkoutMedia(S, { id: 'w1' }, photo(H(9)), 99)).toBe('full')
+ expect(S.workouts[0].media).toHaveLength(WORKOUT_MEDIA_MAX)
+ expect(S.workouts[0]._ts).toBe(stamp)
+ })
+
+ it('removes one by hash, stamps, and drops the field with the last one', () => {
+ const S = state(workout({ media: [photo(H(1)), clip(H(2), H(3))] }))
+ expect(removeWorkoutMedia(S, { id: 'w1' }, H(1), 50)).toBe(true)
+ expect(S.workouts[0].media.map(m => m.hash)).toEqual([H(2)])
+ expect(S.workouts[0]._ts).toBe(50)
+ expect(removeWorkoutMedia(S, { id: 'w1' }, H(1), 60)).toBe(false)
+ expect(S.workouts[0]._ts).toBe(50)
+ expect(removeWorkoutMedia(S, { id: 'w1' }, H(2), 70)).toBe(true)
+ expect('media' in S.workouts[0]).toBe(false)
+ // …and its files are no longer referenced: the GCs take them (after the server's grace).
+ expect(referencedHashes(S).size).toBe(0)
+ })
+})
+
+describe('workoutMediaOf / the state walk', () => {
+ it('shows only valid refs, each file once, at most six', () => {
+ const w = workout({ media: [photo(H(1)), 'x', null, { hash: 'bad' }, photo(H(1)), ...[2, 3, 4, 5, 6, 7, 8].map(n => photo(H(n)))] })
+ expect(workoutMediaOf(w).map(m => m.hash)).toEqual([1, 2, 3, 4, 5, 6].map(H))
+ expect(workoutMediaOf(workout({ media: photo(H(1)) }))).toEqual([])
+ expect(workoutMediaOf(null)).toEqual([])
+ })
+
+ it('referencedFiles lists a workout\'s posters first, with what a download is checked against', () => {
+ const S = state(workout({ media: [clip(H(1), H(2)), photo(H(3))] }))
+ expect(referencedFiles(S)).toEqual([
+ { hash: H(2), mime: 'image/webp', size: 100, poster: true },
+ { hash: H(1), mime: 'video/mp4', size: 500000, poster: false },
+ { hash: H(3), mime: 'image/webp', size: 1000, poster: false },
+ ])
+ })
+
+ it('the session in progress is not walked (media only live on saved workouts)', () => {
+ expect(stateMediaRefs({ active: { media: [photo(H(1))] } })).toEqual([])
+ })
+})
+
+describe('the sync keeps a media edit', () => {
+ it('a photo added on the phone survives the desktop copy that is newer as a whole', () => {
+ const base = state(workout({ _ts: 10 }))
+ const phone = structuredClone(base)
+ addWorkoutMedia(phone, { id: 'w1' }, photo(H(1)), 200)
+ phone._ts = 200
+ const desktop = structuredClone(base)
+ desktop.bodyweight = [{ d: '2026-09-21', w: 80, t: 300 }]
+ desktop._ts = 300
+ for (const merged of [mergeStates(desktop, phone), mergeStates(phone, desktop)]) {
+ expect(merged.workouts[0].media.map(m => m.hash)).toEqual([H(1)])
+ expect(merged.bodyweight).toHaveLength(1)
+ }
+ })
+
+ it('a removal on one device beats the older copy that still shows it', () => {
+ const base = state(workout({ _ts: 10, media: [photo(H(1)), photo(H(2))] }))
+ const a = structuredClone(base)
+ removeWorkoutMedia(a, { id: 'w1' }, H(1), 200)
+ a._ts = 200
+ const b = structuredClone(base)
+ b._ts = 400
+ expect(mergeStates(b, a).workouts[0].media.map(m => m.hash)).toEqual([H(2)])
+ })
+
+ it('a media edit does not count as an edit of the sets (the kept loads are left alone)', () => {
+ const base = state(workout({ _ts: 10 }))
+ base.exWeights = { bench: { w: 60, d: '2026-09-20' } }
+ const a = structuredClone(base)
+ addWorkoutMedia(a, { id: 'w1' }, photo(H(1)), 200)
+ const b = structuredClone(base)
+ b.exWeights = { bench: { w: 65, d: '2026-09-22' } }
+ b._ts = 300
+ expect(mergeStates(b, a).exWeights.bench.w).toBe(65)
+ })
+})
+
+describe('the history editor (#203) leaves a workout\'s media on the record', () => {
+ it('the editor\'s copy carries none, and Save keeps the record\'s', () => {
+ const S = state(workout({ media: [photo(H(1))] }))
+ editCompletedSession(S, 'w1')
+ expect(S.active.media).toBeUndefined()
+ S.active.entries[0].sets[0].r = 6
+ const saved = saveWorkoutEdit(S, 500)
+ expect(saved.media.map(m => m.hash)).toEqual([H(1)])
+ expect(referencedHashes(S)).toEqual(new Set([H(1)]))
+ })
+
+ it('a photo removed from the detail sheet while the editor was open stays removed', () => {
+ const S = state(workout({ media: [photo(H(1)), photo(H(2))] }))
+ editCompletedSession(S, 'w1')
+ removeWorkoutMedia(S, { id: 'w1' }, H(1), 400)
+ S.active.entries[0].sets[0].r = 6
+ const saved = saveWorkoutEdit(S, 500)
+ expect(saved.media.map(m => m.hash)).toEqual([H(2)])
+ })
+})
+
+describe('workout media never leave through the side doors', () => {
+ const S = state(workout({ media: [clip(H(1), H(2))] }))
+ const leaks = v => { const s = JSON.stringify(v); return [H(1), H(2)].some(h => s.includes(h)) || /"media"/.test(s) }
+
+ it('Copy as text', () => {
+ const txt = workoutText(S.workouts[0], { unit: 'kg', nameOf: e => e.id })
+ expect(txt).not.toContain(H(1))
+ expect(txt).not.toMatch(/video|photo/i)
+ })
+
+ it('a routine saved from the workout, and a plan file built from it', () => {
+ const st = structuredClone(S)
+ const id = saveSessionAsRoutine(st, st.workouts[0], 'From workout')
+ expect(leaks(st.routines.find(r => r.id === id))).toBe(false)
+ expect(leaks(buildPlanBundle(st, 'Mine'))).toBe(false)
+ })
+})
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 7f2357780..7d7fa580f 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1641,4 +1641,14 @@ export default {
'name + body part, and a photo or video if you like': 'الاسم + جزء الجسم، وصورة أو فيديو إن أردت',
'{0} photos or videos have not reached your server yet.': 'لم تصل {0} من الصور أو مقاطع الفيديو إلى خادمك بعد.',
'{0} photo or video has not reached your server yet.': 'لم تصل {0} صورة أو مقطع فيديو إلى خادمك بعد.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'إضافة صورة أو فيديو',
+ 'Up to {0} photos or videos per workout.': 'حتى {0} من الصور أو مقاطع الفيديو لكل تمرين.',
+ 'A progress photo or a form-check video, kept with this workout.': 'صورة لتقدّمك أو فيديو لفحص أسلوب الأداء، محفوظ مع هذا التمرين.',
+ 'Photo or video {0} of {1}': 'صورة أو فيديو {0} من {1}',
+ 'Remove this photo or video?': 'إزالة هذه الصورة أو هذا الفيديو؟',
+ 'Close': 'إغلاق',
+ 'Previous': 'السابق',
+ '{0} photo or video': '{0} صورة أو فيديو',
+ '{0} photos or videos': '{0} من الصور أو مقاطع الفيديو',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index c20231a79..965859821 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1608,4 +1608,14 @@ export default {
'name + body part, and a photo or video if you like': 'Name + Körperpartie, auf Wunsch mit Foto oder Video',
'{0} photos or videos have not reached your server yet.': '{0} Fotos oder Videos sind noch nicht auf deinem Server.',
'{0} photo or video has not reached your server yet.': '{0} Foto oder Video ist noch nicht auf deinem Server.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'Foto oder Video hinzufügen',
+ 'Up to {0} photos or videos per workout.': 'Bis zu {0} Fotos oder Videos pro Training.',
+ 'A progress photo or a form-check video, kept with this workout.': 'Ein Fortschrittsfoto oder ein Video zur Technikkontrolle, gespeichert bei diesem Training.',
+ 'Photo or video {0} of {1}': 'Foto oder Video {0} von {1}',
+ 'Remove this photo or video?': 'Dieses Foto oder Video entfernen?',
+ 'Close': 'Schließen',
+ 'Previous': 'Zurück',
+ '{0} photo or video': '{0} Foto oder Video',
+ '{0} photos or videos': '{0} Fotos oder Videos',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 0d2d98b63..4d06bfe43 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1588,4 +1588,14 @@ export default {
'name + body part, and a photo or video if you like': 'nombre + parte del cuerpo, y una foto o vídeo si quieres',
'{0} photos or videos have not reached your server yet.': '{0} fotos o vídeos aún no han llegado a tu servidor.',
'{0} photo or video has not reached your server yet.': '{0} foto o vídeo aún no ha llegado a tu servidor.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'Añadir foto o vídeo',
+ 'Up to {0} photos or videos per workout.': 'Hasta {0} fotos o vídeos por entrenamiento.',
+ 'A progress photo or a form-check video, kept with this workout.': 'Una foto de progreso o un vídeo para revisar la técnica, guardados con este entrenamiento.',
+ 'Photo or video {0} of {1}': 'Foto o vídeo {0} de {1}',
+ 'Remove this photo or video?': '¿Quitar esta foto o vídeo?',
+ 'Close': 'Cerrar',
+ 'Previous': 'Anterior',
+ '{0} photo or video': '{0} foto o vídeo',
+ '{0} photos or videos': '{0} fotos o vídeos',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 4f0fa1a8a..8e6f982b1 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1588,4 +1588,14 @@ export default {
'name + body part, and a photo or video if you like': 'nom + partie du corps, et une photo ou vidéo si vous voulez',
'{0} photos or videos have not reached your server yet.': '{0} photos ou vidéos ne sont pas encore arrivées sur votre serveur.',
'{0} photo or video has not reached your server yet.': '{0} photo ou vidéo n’est pas encore arrivée sur votre serveur.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'Ajouter une photo ou une vidéo',
+ 'Up to {0} photos or videos per workout.': 'Jusqu’à {0} photos ou vidéos par séance.',
+ 'A progress photo or a form-check video, kept with this workout.': 'Une photo de progression ou une vidéo pour vérifier la technique, conservée avec cette séance.',
+ 'Photo or video {0} of {1}': 'Photo ou vidéo {0} sur {1}',
+ 'Remove this photo or video?': 'Retirer cette photo ou vidéo ?',
+ 'Close': 'Fermer',
+ 'Previous': 'Précédent',
+ '{0} photo or video': '{0} photo ou vidéo',
+ '{0} photos or videos': '{0} photos ou vidéos',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 739ce35a4..2bfffb7c3 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1588,4 +1588,14 @@ export default {
'name + body part, and a photo or video if you like': 'नाम + बॉडी पार्ट, और चाहें तो एक फ़ोटो या वीडियो',
'{0} photos or videos have not reached your server yet.': '{0} फ़ोटो या वीडियो अभी आपके सर्वर तक नहीं पहुँचे हैं।',
'{0} photo or video has not reached your server yet.': '{0} फ़ोटो या वीडियो अभी आपके सर्वर तक नहीं पहुँचा है।',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'फ़ोटो या वीडियो जोड़ें',
+ 'Up to {0} photos or videos per workout.': 'हर वर्कआउट में अधिकतम {0} फ़ोटो या वीडियो।',
+ 'A progress photo or a form-check video, kept with this workout.': 'प्रगति की फ़ोटो या तकनीक जाँचने का वीडियो, इसी वर्कआउट के साथ रखा जाता है।',
+ 'Photo or video {0} of {1}': 'फ़ोटो या वीडियो {0} / {1}',
+ 'Remove this photo or video?': 'यह फ़ोटो या वीडियो हटाएँ?',
+ 'Close': 'बंद करें',
+ 'Previous': 'पिछला',
+ '{0} photo or video': '{0} फ़ोटो या वीडियो',
+ '{0} photos or videos': '{0} फ़ोटो या वीडियो',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index e98126ecd..34fd7ccd3 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1591,4 +1591,14 @@ export default {
'name + body part, and a photo or video if you like': 'név + testrész, és ha szeretnéd, egy fotó vagy videó',
'{0} photos or videos have not reached your server yet.': '{0} fotó vagy videó még nem ért el a szerveredre.',
'{0} photo or video has not reached your server yet.': '{0} fotó vagy videó még nem ért el a szerveredre.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'Fotó vagy videó hozzáadása',
+ 'Up to {0} photos or videos per workout.': 'Edzésenként legfeljebb {0} fotó vagy videó.',
+ 'A progress photo or a form-check video, kept with this workout.': 'Egy fotó a fejlődésedről vagy egy videó a technikád ellenőrzéséhez, ehhez az edzéshez mentve.',
+ 'Photo or video {0} of {1}': '{0}. fotó vagy videó / {1}',
+ 'Remove this photo or video?': 'Eltávolítod ezt a fotót vagy videót?',
+ 'Close': 'Bezárás',
+ 'Previous': 'Előző',
+ '{0} photo or video': '{0} fotó vagy videó',
+ '{0} photos or videos': '{0} fotó vagy videó',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index dc07f8cfb..ba4b3894d 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1588,4 +1588,14 @@ export default {
'name + body part, and a photo or video if you like': 'nome + parte del corpo, e una foto o un video se vuoi',
'{0} photos or videos have not reached your server yet.': '{0} foto o video non hanno ancora raggiunto il tuo server.',
'{0} photo or video has not reached your server yet.': '{0} foto o video non ha ancora raggiunto il tuo server.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'Aggiungi foto o video',
+ 'Up to {0} photos or videos per workout.': 'Fino a {0} foto o video per allenamento.',
+ 'A progress photo or a form-check video, kept with this workout.': 'Una foto dei progressi o un video per controllare la tecnica, salvati con questo allenamento.',
+ 'Photo or video {0} of {1}': 'Foto o video {0} di {1}',
+ 'Remove this photo or video?': 'Rimuovere questa foto o video?',
+ 'Close': 'Chiudi',
+ 'Previous': 'Prec.',
+ '{0} photo or video': '{0} foto o video',
+ '{0} photos or videos': '{0} foto o video',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 4947b314d..7a46c4ab7 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1588,4 +1588,14 @@ export default {
'name + body part, and a photo or video if you like': '이름 + 부위, 원하면 사진이나 동영상도',
'{0} photos or videos have not reached your server yet.': '아직 서버에 올라가지 않은 사진·동영상이 {0}개 있습니다.',
'{0} photo or video has not reached your server yet.': '아직 서버에 올라가지 않은 사진·동영상이 {0}개 있습니다.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': '사진 또는 동영상 추가',
+ 'Up to {0} photos or videos per workout.': '운동 한 번에 사진·동영상은 최대 {0}개까지입니다.',
+ 'A progress photo or a form-check video, kept with this workout.': '진행 상황 사진이나 자세 점검 동영상을 이 운동에 함께 보관합니다.',
+ 'Photo or video {0} of {1}': '사진·동영상 {1}개 중 {0}번째',
+ 'Remove this photo or video?': '이 사진 또는 동영상을 제거할까요?',
+ 'Close': '닫기',
+ 'Previous': '이전',
+ '{0} photo or video': '사진·동영상 {0}개',
+ '{0} photos or videos': '사진·동영상 {0}개',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 87dfbfcf5..b1a49a185 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1588,4 +1588,14 @@ export default {
'name + body part, and a photo or video if you like': 'nazwa + partia ciała, a do tego zdjęcie lub film, jeśli chcesz',
'{0} photos or videos have not reached your server yet.': 'Zdjęcia lub filmy, które nie dotarły jeszcze na twój serwer: {0}.',
'{0} photo or video has not reached your server yet.': 'Zdjęcie lub film, którego jeszcze nie ma na twoim serwerze: {0}.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'Dodaj zdjęcie lub film',
+ 'Up to {0} photos or videos per workout.': 'Maksymalnie {0} zdjęć lub filmów na trening.',
+ 'A progress photo or a form-check video, kept with this workout.': 'Zdjęcie postępów albo film do sprawdzenia techniki, zapisane przy tym treningu.',
+ 'Photo or video {0} of {1}': 'Zdjęcie lub film {0} z {1}',
+ 'Remove this photo or video?': 'Usunąć to zdjęcie lub film?',
+ 'Close': 'Zamknij',
+ 'Previous': 'Wstecz',
+ '{0} photo or video': 'Zdjęcia lub filmy: {0}',
+ '{0} photos or videos': 'Zdjęcia lub filmy: {0}',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index c644d04cd..bacdadff5 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -943,6 +943,8 @@ export const PT_BR_OVERRIDES = {
'name + body part, and a photo or video if you like': 'nome + parte do corpo, e uma foto ou vídeo se quiser',
'{0} photos or videos have not reached your server yet.': '{0} fotos ou vídeos ainda não chegaram ao seu servidor.',
'{0} photo or video has not reached your server yet.': '{0} foto ou vídeo ainda não chegou ao seu servidor.',
+ // --- a logged workout's own photos and videos ---
+ 'A progress photo or a form-check video, kept with this workout.': 'Uma foto de progresso ou um vídeo para conferir a técnica, salvos com este treino.',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index d74a6a03e..9f444ccfc 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1588,4 +1588,14 @@ export default {
'name + body part, and a photo or video if you like': 'nome + parte do corpo, e uma foto ou vídeo se quiseres',
'{0} photos or videos have not reached your server yet.': '{0} fotos ou vídeos ainda não chegaram ao teu servidor.',
'{0} photo or video has not reached your server yet.': '{0} foto ou vídeo ainda não chegou ao teu servidor.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'Adicionar foto ou vídeo',
+ 'Up to {0} photos or videos per workout.': 'Até {0} fotos ou vídeos por treino.',
+ 'A progress photo or a form-check video, kept with this workout.': 'Uma foto de progresso ou um vídeo para verificar a técnica, guardados com este treino.',
+ 'Photo or video {0} of {1}': 'Foto ou vídeo {0} de {1}',
+ 'Remove this photo or video?': 'Remover esta foto ou vídeo?',
+ 'Close': 'Fechar',
+ 'Previous': 'Anterior',
+ '{0} photo or video': '{0} foto ou vídeo',
+ '{0} photos or videos': '{0} fotos ou vídeos',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index bb4a4e4a0..2b0d665ba 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1588,4 +1588,14 @@ export default {
'name + body part, and a photo or video if you like': 'название + часть тела и, по желанию, фото или видео',
'{0} photos or videos have not reached your server yet.': 'Фото и видео, ещё не попавшие на ваш сервер: {0}.',
'{0} photo or video has not reached your server yet.': 'Фото или видео, ещё не попавшее на ваш сервер: {0}.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'Добавить фото или видео',
+ 'Up to {0} photos or videos per workout.': 'Не больше {0} фото или видео на тренировку.',
+ 'A progress photo or a form-check video, kept with this workout.': 'Фото прогресса или видео для проверки техники, сохранённые вместе с этой тренировкой.',
+ 'Photo or video {0} of {1}': 'Фото или видео {0} из {1}',
+ 'Remove this photo or video?': 'Удалить это фото или видео?',
+ 'Close': 'Закрыть',
+ 'Previous': 'Назад',
+ '{0} photo or video': 'Фото или видео: {0}',
+ '{0} photos or videos': 'Фото и видео: {0}',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index fea736433..27010b344 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1599,4 +1599,14 @@ export default {
'name + body part, and a photo or video if you like': 'ชื่อ + ส่วนร่างกาย และรูปหรือวิดีโอถ้าต้องการ',
'{0} photos or videos have not reached your server yet.': 'มีรูปภาพหรือวิดีโอ {0} รายการที่ยังไม่ถึงเซิร์ฟเวอร์ของคุณ',
'{0} photo or video has not reached your server yet.': 'มีรูปภาพหรือวิดีโอ {0} รายการที่ยังไม่ถึงเซิร์ฟเวอร์ของคุณ',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'เพิ่มรูปภาพหรือวิดีโอ',
+ 'Up to {0} photos or videos per workout.': 'สูงสุด {0} รูปภาพหรือวิดีโอต่อการออกกำลังกายหนึ่งครั้ง',
+ 'A progress photo or a form-check video, kept with this workout.': 'รูปความคืบหน้าหรือวิดีโอตรวจท่าทาง เก็บไว้กับการออกกำลังกายครั้งนี้',
+ 'Photo or video {0} of {1}': 'รูปภาพหรือวิดีโอที่ {0} จาก {1}',
+ 'Remove this photo or video?': 'ลบรูปภาพหรือวิดีโอนี้ไหม',
+ 'Close': 'ปิด',
+ 'Previous': 'ก่อนหน้า',
+ '{0} photo or video': 'รูปภาพหรือวิดีโอ {0} รายการ',
+ '{0} photos or videos': 'รูปภาพหรือวิดีโอ {0} รายการ',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 4fd25a6d0..ab3605bb6 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1588,4 +1588,14 @@ export default {
'name + body part, and a photo or video if you like': 'ad + vücut bölgesi, istersen bir fotoğraf veya video',
'{0} photos or videos have not reached your server yet.': '{0} fotoğraf veya video henüz sunucuna ulaşmadı.',
'{0} photo or video has not reached your server yet.': '{0} fotoğraf veya video henüz sunucuna ulaşmadı.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'Fotoğraf veya video ekle',
+ 'Up to {0} photos or videos per workout.': 'Antrenman başına en fazla {0} fotoğraf veya video.',
+ 'A progress photo or a form-check video, kept with this workout.': 'Bir gelişim fotoğrafı ya da tekniğini kontrol etmek için bir video, bu antrenmanla birlikte saklanır.',
+ 'Photo or video {0} of {1}': 'Fotoğraf veya video {0}/{1}',
+ 'Remove this photo or video?': 'Bu fotoğraf veya video kaldırılsın mı?',
+ 'Close': 'Kapat',
+ 'Previous': 'Önceki',
+ '{0} photo or video': '{0} fotoğraf veya video',
+ '{0} photos or videos': '{0} fotoğraf veya video',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index 3939c2323..15f026892 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1585,4 +1585,14 @@ export default {
'name + body part, and a photo or video if you like': 'назва + частина тіла, а за бажання — фото чи відео',
'{0} photos or videos have not reached your server yet.': 'Фото й відео, які ще не дійшли до твого сервера: {0}.',
'{0} photo or video has not reached your server yet.': 'Фото чи відео, яке ще не дійшло до твого сервера: {0}.',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': 'Додати фото чи відео',
+ 'Up to {0} photos or videos per workout.': 'Не більше {0} фото чи відео на тренування.',
+ 'A progress photo or a form-check video, kept with this workout.': 'Фото прогресу чи відео для перевірки техніки, збережені разом із цим тренуванням.',
+ 'Photo or video {0} of {1}': 'Фото чи відео {0} з {1}',
+ 'Remove this photo or video?': 'Видалити це фото чи відео?',
+ 'Close': 'Закрити',
+ 'Previous': 'Назад',
+ '{0} photo or video': 'Фото чи відео: {0}',
+ '{0} photos or videos': 'Фото й відео: {0}',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index bf35418ca..b0b54f4e0 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1588,4 +1588,14 @@ export default {
'name + body part, and a photo or video if you like': '名称 + 身体部位,可附照片或视频',
'{0} photos or videos have not reached your server yet.': '有 {0} 个照片或视频尚未到达你的服务器。',
'{0} photo or video has not reached your server yet.': '有 {0} 个照片或视频尚未到达你的服务器。',
+ // --- a logged workout's own photos and videos ---
+ 'Add photo or video': '添加照片或视频',
+ 'Up to {0} photos or videos per workout.': '每次训练最多 {0} 个照片或视频。',
+ 'A progress photo or a form-check video, kept with this workout.': '进度照片或动作检查视频,与本次训练一起保存。',
+ 'Photo or video {0} of {1}': '第 {0} 个照片或视频,共 {1} 个',
+ 'Remove this photo or video?': '移除这个照片或视频?',
+ 'Close': '关闭',
+ 'Previous': '上一个',
+ '{0} photo or video': '{0} 个照片或视频',
+ '{0} photos or videos': '{0} 个照片或视频',
}
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index 8dfa35801..d9cb40132 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -14,6 +14,7 @@ import { nav } from './lib/nav.js'
import { buildStarterPlan, starterPlanDays, starterPlanOptions } from './lib/starter.js'
import Media, { Thumb } from './components/Media.jsx'
import CustomMediaField from './components/CustomMediaField.jsx'
+import WorkoutMediaSection, { workoutMediaCount } from './components/WorkoutMedia.jsx'
import { mediaOf, normalizeMediaRef, cleanUrl } from './lib/media-refs.js'
import { syncMedia } from './lib/media-sync.js'
import LineChart from './components/LineChart.jsx'
@@ -2021,6 +2022,8 @@ function WorkoutDetail({ w, close }) {
{entryRows(g.units)}
</div>
}) : entryRows(groups[0]?.units || [])}
+ {/* Progress photos and form-check videos: added and removed right here, on the saved record. */}
+ <WorkoutMediaSection w={w} />
<div className="small muted" style={{ margin: '4px 0 6px' }}>{t('Session note')}</div>
<textarea ref={noteRef} className="input" rows={2} maxLength={NOTE_MAX} value={note}
placeholder={t('How the session went as a whole.')}
@@ -2121,10 +2124,12 @@ export const calendarSheet = start => ui().openSheet(close => <Calendar start={s
export function WorkoutRow({ w, onClick }) {
const st = useStore(s => s.S)
const glyph = glyphOf((st.routines.find(r => r.id === w.routineId) || {}).emoji)
+ const mediaN = workoutMediaCount(w)
return <div className="item" {...tappable(onClick)}>
<span className="lrow-i" style={{ width: 34, height: 34, borderRadius: 8, fontSize: 19 }}><Icon name={glyph} /></span>
<div className="grow"><div className="tt">{w.name}</div>
<div className="ss">{[fmtDate(w.d, true), ...durPart(w.end - w.start), t('{0} sets', setsDone(w)), fmtVol(w.vol, st.unit)].join(' · ')}</div></div>
+ {mediaN > 0 && <span className="wrow-media" title={t(mediaN === 1 ? '{0} photo or video' : '{0} photos or videos', mediaN)} aria-label={t(mediaN === 1 ? '{0} photo or video' : '{0} photos or videos', mediaN)}><Icon name="image" />{mediaN}</span>}
{w.prs && w.prs.length > 0 && <span className="pr"><Icon name="trophy" />{w.prs.length} PR</span>}
<Icon name="chevronRight" className="chev" />
</div>
@@ -2576,6 +2581,9 @@ function FinishSummary({ w, prs, e1prs = [], close }) {
<h4 className="sec" style={{ textAlign: 'start' }}>{t('What you just trained')}</h4>
<BodyMap load={loadOfWorkouts([w])} body={st.body} />
<div style={{ height: 14 }} />
+ {/* The moment for a progress photo or the clip of a set: the workout is already saved, so
+ what is added here goes straight onto its record. */}
+ <div style={{ textAlign: 'start' }}><WorkoutMediaSection w={w} hint /></div>
<Button variant="primary" onClick={() => { close(); nav('/home') }}>{t('Nice!')}</Button>
</div>
}
diff --git a/frontend/src/sheets.workout-media.test.jsx b/frontend/src/sheets.workout-media.test.jsx
new file mode 100644
index 000000000..26f6d5a5d
--- /dev/null
+++ b/frontend/src/sheets.workout-media.test.jsx
@@ -0,0 +1,164 @@
+// @vitest-environment happy-dom
+// A logged workout's photos and videos in its detail sheet and the history row: a picked file
+// goes through the same ingest as an exercise's picture (mocked here — lib/media-ingest.js has its
+// own tests), lands in the local store as pending and on the saved record, stamped; the grid shows
+// posters and opens the full-screen viewer, where one can be removed; a seventh is refused.
+import React, { act } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createRoot } from 'react-dom/client'
+
+const h = vi.hoisted(() => ({ ingest: null }))
+vi.mock('./lib/media-ingest.js', () => ({ ingestMediaFile: (...a) => h.ingest(...a) }))
+
+import { DEF, useStore } from './store/useStore.js'
+import { useUI } from './store/useUI.js'
+import { _setLangState } from './lib/i18n-core.js'
+import { bindUI } from './components/ui.jsx'
+import { createMediaStore, memoryBackend, _setMediaStore } from './lib/media-store.js'
+import { workoutDetailSheet, WorkoutRow } from './sheets.jsx'
+import WorkoutMediaSection from './components/WorkoutMedia.jsx'
+import { WORKOUT_MEDIA_MAX } from './lib/media-refs.js'
+
+bindUI(useUI)
+
+const mounted = []
+const S = () => useStore.getState().S
+const hex = n => n.toString(16).padStart(2, '0').repeat(32)
+const refOf = (n, kind = 'image') => kind === 'video'
+ ? { kind: 'video', hash: hex(n), mime: 'video/mp4', size: 400000, width: 1280, height: 720, dur: 6, codec: 'avc1', poster: { hash: hex(n + 100), mime: 'image/webp', size: 2000, width: 480, height: 270 }, at: 1727000000000 }
+ : { kind: 'image', hash: hex(n), mime: 'image/webp', size: 200000, width: 1600, height: 1200, poster: { hash: hex(n + 100), mime: 'image/webp', size: 2000, width: 480, height: 360 }, at: 1727000000000 }
+
+function render(el) {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push(root)
+ act(() => root.render(el))
+ return host
+}
+function renderTop() {
+ const sheet = useUI.getState().sheets.at(-1)
+ return Object.assign(render(sheet.render(() => useUI.getState().closeSheet(sheet.id))), { sheet })
+}
+const settle = async () => { for (let i = 0; i < 6; i++) await act(async () => { await new Promise(r => setTimeout(r, 0)) }) }
+async function pick(host, count = 1) {
+ const input = host.querySelector('.wmedia input[type="file"]')
+ const files = Array.from({ length: count }, (_, i) => new File(['x' + i], `IMG_00${i}.HEIC`, { type: 'image/heic' }))
+ Object.defineProperty(input, 'files', { value: files, configurable: true })
+ const before = h.ingest.mock.calls.length
+ act(() => { input.dispatchEvent(new Event('change', { bubbles: true })) })
+ const end = Date.now() + 4000
+ while ((h.ingest.mock.calls.length < before + count || host.textContent.includes('Loading…')) && Date.now() < end) {
+ await act(async () => { await new Promise(r => setTimeout(r, 10)) })
+ }
+ await settle()
+}
+const workout = extra => ({ id: 'w1', d: '2026-09-15', start: Date.UTC(2026, 8, 15, 17), end: Date.UTC(2026, 8, 15, 18), name: 'Push', vol: 0, prs: [], routineIds: [], entries: [], _ts: 5, ...extra })
+
+let media, next
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ useUI.setState({ sheets: [], toastMsg: '' })
+ useStore.setState({ S: { ...structuredClone(DEF), workouts: [workout()] }, user: null, config: null })
+ _setLangState('en', null, null, null)
+ document.body.innerHTML = ''
+ media = createMediaStore({ ...memoryBackend(), persistent: true, name: 'test' }, { objectURL: { createObjectURL: () => 'blob:t/1', revokeObjectURL() {} } })
+ _setMediaStore(media)
+ next = 1
+ h.ingest = vi.fn(async () => {
+ const n = next++
+ const kind = n % 2 ? 'image' : 'video'
+ const r = refOf(n, kind)
+ return { media: r, blobs: [{ hash: r.hash, blob: new Blob(['main' + n]), mime: r.mime }, { hash: r.poster.hash, blob: new Blob(['poster' + n]), mime: 'image/webp' }], warnings: [] }
+ })
+})
+afterEach(() => {
+ act(() => { mounted.splice(0).forEach(root => root.unmount()) })
+ _setMediaStore(null)
+})
+
+describe('a workout\'s photos and videos', () => {
+ it('asks for images and videos, several at once', () => {
+ workoutDetailSheet(S().workouts[0])
+ const input = renderTop().querySelector('.wmedia input[type="file"]')
+ expect(input.getAttribute('accept')).toBe('image/*,video/*')
+ expect(input.multiple).toBe(true)
+ })
+
+ it('a picked photo and video land on the saved record, stamped, with their files pending — never the file name', async () => {
+ workoutDetailSheet(S().workouts[0])
+ const host = renderTop()
+ await pick(host, 2)
+ const w = S().workouts[0]
+ expect(w.media).toEqual([refOf(1), refOf(2, 'video')])
+ expect(w._ts).toBeGreaterThan(5)
+ expect([...media.pendingNow()].sort()).toEqual([hex(1), hex(101), hex(2), hex(102)].sort())
+ expect(host.querySelectorAll('.wmedia-item')).toHaveLength(2)
+ expect(host.querySelectorAll('.wmedia-kind')).toHaveLength(1) // the play badge on the video
+ expect(JSON.stringify(S())).not.toContain('IMG_00')
+ })
+
+ it('shows posters in the grid, and opens the viewer on the one tapped', async () => {
+ useStore.setState(s => ({ S: { ...s.S, workouts: [workout({ media: [refOf(1), refOf(2, 'video')] })] } }))
+ await media.put(hex(101), new Blob(['p']), { mime: 'image/webp' })
+ workoutDetailSheet(S().workouts[0])
+ const host = renderTop()
+ await settle()
+ expect(host.querySelector('.wmedia-item img.thumb')?.getAttribute('src')).toBe('blob:t/1')
+ act(() => host.querySelectorAll('.wmedia-item')[1].click())
+ const top = useUI.getState().sheets.at(-1)
+ expect(top.kind).toBe('viewer')
+ const viewer = renderTop()
+ expect(viewer.querySelector('.mviewer-count').textContent).toBe('2 / 2')
+ expect(viewer.querySelector('.exmedia.viewer')).toBeTruthy()
+ act(() => viewer.querySelector('button[aria-label="Previous"]').click())
+ expect(viewer.querySelector('.mviewer-count').textContent).toBe('1 / 2')
+ })
+
+ it('Remove in the viewer asks, then takes it off the record and stamps it', async () => {
+ useStore.setState(s => ({ S: { ...s.S, workouts: [workout({ media: [refOf(1), refOf(3)] })] } }))
+ workoutDetailSheet(S().workouts[0])
+ const detail = renderTop()
+ act(() => detail.querySelectorAll('.wmedia-item')[0].click())
+ const viewer = renderTop()
+ act(() => viewer.querySelector('button[aria-label="Remove"]').click())
+ expect(viewer.textContent).toContain('Remove this photo or video?')
+ expect(S().workouts[0].media).toHaveLength(2)
+ act(() => [...viewer.querySelectorAll('.mviewer-ask button')].find(b => b.textContent.trim() === 'Remove').click())
+ expect(S().workouts[0].media.map(m => m.hash)).toEqual([hex(3)])
+ expect(S().workouts[0]._ts).toBeGreaterThan(5)
+ expect(viewer.querySelector('.mviewer-count').textContent).toBe('1 / 1')
+ })
+
+ it('a full workout offers no Add and says how many fit; a seventh picked in a batch is refused', async () => {
+ workoutDetailSheet(S().workouts[0])
+ const host = renderTop()
+ await pick(host, WORKOUT_MEDIA_MAX + 1)
+ expect(S().workouts[0].media).toHaveLength(WORKOUT_MEDIA_MAX)
+ expect(useUI.getState().toastMsg).toBe(`Up to ${WORKOUT_MEDIA_MAX} photos or videos per workout.`)
+ expect(host.querySelector('.wmedia-add')).toBeNull()
+ expect(host.textContent).toContain(`Up to ${WORKOUT_MEDIA_MAX} photos or videos per workout.`)
+ })
+
+ it('a server without media storage gets no Add button, and says why', () => {
+ useStore.setState({ user: { id: 'u1', name: 'One' }, config: { passkeys: true } })
+ workoutDetailSheet(S().workouts[0])
+ const host = renderTop()
+ expect(host.querySelector('.wmedia-add')).toBeNull()
+ expect(host.textContent).toContain('Your server does not store photos and videos yet.')
+ })
+
+ it('signed out, the finish screen\'s section explains itself and says the files stay here', () => {
+ const host = render(<WorkoutMediaSection w={S().workouts[0]} hint />)
+ expect(host.textContent).toContain('A progress photo or a form-check video, kept with this workout.')
+ expect(host.textContent).toContain('Kept on this device only')
+ })
+
+ it('the history row shows how many a workout has', () => {
+ const plain = render(<WorkoutRow w={workout()} onClick={() => {}} />)
+ expect(plain.querySelector('.wrow-media')).toBeNull()
+ const row = render(<WorkoutRow w={workout({ media: [refOf(1), refOf(2, 'video'), { hash: 'bad' }] })} onClick={() => {}} />)
+ expect(row.querySelector('.wrow-media').textContent).toBe('2')
+ expect(row.querySelector('.wrow-media').getAttribute('aria-label')).toBe('2 photos or videos')
+ })
+})