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: photos and videos are offered only where a file can be kept, and the viewer works from the keyboard

Duarte Santosb1150373d1d2
diff --git a/frontend/src/components/CustomMediaField.jsx b/frontend/src/components/CustomMediaField.jsx
index 3f4189bc9..d048f8caf 100644
--- a/frontend/src/components/CustomMediaField.jsx
+++ b/frontend/src/components/CustomMediaField.jsx
@@ -52,7 +52,8 @@ const KIND_ICON = { image: 'image', gif: 'play', video: 'play' }
* 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.
+ * browser that cannot store them), `showAdd` false only where the button should not even show,
+ * `storable` false where this browser cannot keep a file at all.
*/
export function useMediaPicker() {
const user = useStore(s => s.user)
@@ -100,7 +101,7 @@ export function useMediaPicker() {
: 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 }
+ return { pick, busy, warning, setWarning, note, storable, showAdd: !serverLacks, canAdd: !busy && storable && !serverLacks }
}
export default function CustomMediaField({ media, url, onChange }) {
diff --git a/frontend/src/components/WorkoutMedia.jsx b/frontend/src/components/WorkoutMedia.jsx
index 5f6327561..66bcbaece 100644
--- a/frontend/src/components/WorkoutMedia.jsx
+++ b/frontend/src/components/WorkoutMedia.jsx
@@ -31,24 +31,44 @@ const useRecord = w => useStore(s => (s.S.workouts || []).find(x => x && sameWor
/** The number of photos and videos a workout shows — for the history row's small badge. */
export const workoutMediaCount = w => workoutMediaOf(w).length
+/**
+ * Whether a workout may be offered an Add at all, beside the picker's own reasons: signed in (a
+ * paired phone included), the server has to say it keeps a workout's files (`media.workouts` in
+ * /api/config) — one from before this feature stores an exercise's picture but its GC would sweep
+ * a file only a workout names. A config not known yet (an offline start) is not that answer, and
+ * a guest or a phone in local mode keeps its files on the device either way.
+ */
+export const serverTakesWorkoutMedia = (user, config) => !user || !config || !config.media || !!config.media.workouts
+
/**
* 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.
+ * explanation shown on the finish screen while there is nothing yet. Nothing at all while there
+ * is nothing to show and nothing could be added (a server that does not keep them, a browser
+ * that cannot store them).
*/
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 user = useStore(s => s.user)
+ const config = useStore(s => s.config)
+ const { pick, busy, warning, note, storable, showAdd: pickerShowsAdd, canAdd: pickerCanAdd } = useMediaPicker()
const fileRef = useRef(null)
if (!rec) return null
const list = workoutMediaOf(rec)
const room = WORKOUT_MEDIA_MAX - list.length
+ const showAdd = pickerShowsAdd && serverTakesWorkoutMedia(user, config)
+ const canAdd = pickerCanAdd && showAdd
+ if (!list.length && !(showAdd && storable)) return null
const onFiles = async ev => {
- const files = [...(ev.target.files || [])]
+ const picked = [...(ev.target.files || [])]
ev.target.value = '' // picking the same file again still fires onChange
+ // Only as many as still fit go through the ingest: a batch of twelve on a phone would
+ // otherwise re-encode (and store as pending) six files nothing will ever name.
+ const now = useStore.getState().S.workouts?.find(x => x && sameWorkout(x, w))
+ const files = picked.slice(0, Math.max(0, WORKOUT_MEDIA_MAX - workoutMediaOf(now).length))
let added = 0
- let full = false
+ let full = files.length < picked.length
for (const file of files) {
const got = await pick(file)
if (!got) continue
@@ -56,7 +76,7 @@ export default function WorkoutMediaSection({ w, hint = false }) {
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 }
+ else if (res === 'gone') { toast(t('Workout deleted')); full = false; 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.
@@ -85,7 +105,9 @@ export default function WorkoutMediaSection({ w, hint = false }) {
{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>}
+ {/* Where the files live, or why none can be added — about the ones there are, so not
+ while there are none (the finish screen's hint says what the section is for). */}
+ {note && list.length > 0 && <div className="small dim wmedia-note">{note}</div>}
</div>
}
@@ -94,16 +116,25 @@ export function openWorkoutMediaViewer(w, index = 0) {
useUI.getState().openSheet(close => <WorkoutMediaViewer w={w} index={index} close={close} />, { kind: 'viewer' })
}
+const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select, textarea, video[controls], [tabindex]:not([tabindex="-1"])'
+
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 box = useRef(null)
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])
+ // Focus moves in on open (onto Close) and back to what opened it on the way out.
+ useEffect(() => {
+ const before = document.activeElement
+ box.current?.querySelector('button')?.focus()
+ return () => { if (before && typeof before.focus === 'function' && before.isConnected) before.focus() }
+ }, [])
if (!m) return null
const go = d => { setAsking(false); setI((at + d + list.length) % list.length) }
const remove = () => {
@@ -112,7 +143,26 @@ export function WorkoutMediaViewer({ w, index = 0, close }) {
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')}>
+ // Tab stays inside the viewer (it covers the whole screen, and the page behind is not there to
+ // reach); left and right step through the list — mirrored where the language reads right to
+ // left, as the arrows on screen are. A video's own controls keep the arrows while focused.
+ const onKeyDown = e => {
+ if (e.key === 'Tab') {
+ const items = [...(box.current?.querySelectorAll(FOCUSABLE) || [])]
+ if (!items.length) return
+ const first = items[0], last = items.at(-1)
+ const inside = box.current.contains(document.activeElement)
+ if (e.shiftKey && (!inside || document.activeElement === first || document.activeElement === box.current)) { e.preventDefault(); last.focus() }
+ else if (!e.shiftKey && (!inside || document.activeElement === last)) { e.preventDefault(); first.focus() }
+ return
+ }
+ if ((e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') || list.length < 2 || asking) return
+ if (e.target?.tagName === 'VIDEO' || e.target?.tagName === 'INPUT') return
+ const rtl = document.documentElement.dir === 'rtl'
+ e.preventDefault()
+ go((e.key === 'ArrowRight') !== rtl ? 1 : -1)
+ }
+ return <div className="mviewer" role="dialog" aria-modal="true" aria-label={t('Photos & videos')} ref={box} tabIndex={-1} onKeyDown={onKeyDown}>
<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>
diff --git a/frontend/src/sheets.workout-media.test.jsx b/frontend/src/sheets.workout-media.test.jsx
index 942f229aa..a1c70b7fc 100644
--- a/frontend/src/sheets.workout-media.test.jsx
+++ b/frontend/src/sheets.workout-media.test.jsx
@@ -16,7 +16,7 @@ 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 WorkoutMediaSection, { openWorkoutMediaViewer } from './components/WorkoutMedia.jsx'
import { WORKOUT_MEDIA_MAX } from './lib/media-refs.js'
bindUI(useUI)
@@ -41,14 +41,14 @@ function renderTop() {
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) {
+async function pick(host, count = 1, ingested = count) {
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) {
+ while ((h.ingest.mock.calls.length < before + ingested || host.textContent.includes('Loading…')) && Date.now() < end) {
await act(async () => { await new Promise(r => setTimeout(r, 10)) })
}
await settle()
@@ -133,25 +133,96 @@ describe('a workout\'s photos and videos', () => {
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)
+ await pick(host, WORKOUT_MEDIA_MAX + 1, WORKOUT_MEDIA_MAX)
expect(S().workouts[0].media).toHaveLength(WORKOUT_MEDIA_MAX)
+ expect(h.ingest).toHaveBeenCalledTimes(WORKOUT_MEDIA_MAX) // the seventh is never ingested
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', () => {
+ it('a batch bigger than the room left ingests only what fits', async () => {
+ useStore.setState(s => ({ S: { ...s.S, workouts: [workout({ media: [1, 3, 5, 7].map(n => refOf(n + 20)) })] } }))
+ workoutDetailSheet(S().workouts[0])
+ const host = renderTop()
+ await pick(host, 5, 2)
+ expect(h.ingest).toHaveBeenCalledTimes(2)
+ 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([...media.pendingNow()]).toHaveLength(4) // two files, each with its poster
+ })
+
+ it('a server without media storage: no section while there is nothing; with some, no Add and why', () => {
useStore.setState({ user: { id: 'u1', name: 'One' }, config: { passkeys: true } })
workoutDetailSheet(S().workouts[0])
+ expect(renderTop().querySelector('.wmedia')).toBeNull()
+ useStore.setState(s => ({ S: { ...s.S, workouts: [workout({ media: [refOf(1)] })] } }))
+ workoutDetailSheet(S().workouts[0])
const host = renderTop()
+ expect(host.querySelectorAll('.wmedia-item')).toHaveLength(1)
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', () => {
+ it('signed in, Add is offered only when the server says a workout may carry media', () => {
+ const caps = { imageMB: 2, gifMB: 8, videoMB: 40, videoSec: 60, quotaMB: 200 }
+ useStore.setState({ user: { id: 'u1', name: 'One' }, config: { media: caps } })
+ expect(render(<WorkoutMediaSection w={S().workouts[0]} hint />).querySelector('.wmedia')).toBeNull()
+ useStore.setState({ config: { media: { ...caps, workouts: true } } })
+ expect(render(<WorkoutMediaSection w={S().workouts[0]} hint />).querySelector('.wmedia-add')).toBeTruthy()
+ // Config not known yet (offline start): offered, the files wait here.
+ useStore.setState({ config: null })
+ expect(render(<WorkoutMediaSection w={S().workouts[0]} />).querySelector('.wmedia-add')).toBeTruthy()
+ // A guest is not held to it: the files stay on the device.
+ useStore.setState({ user: null, config: { media: caps } })
+ expect(render(<WorkoutMediaSection w={S().workouts[0]} />).querySelector('.wmedia-add')).toBeTruthy()
+ })
+
+ it('a browser that cannot store files shows no empty section', async () => {
+ media = createMediaStore({ ...memoryBackend(), persistent: false, name: 'mem' }, { objectURL: { createObjectURL: () => 'blob:t/1', revokeObjectURL() {} } })
+ _setMediaStore(media)
+ const host = render(<WorkoutMediaSection w={S().workouts[0]} hint />)
+ await settle()
+ expect(host.querySelector('.wmedia')).toBeNull()
+ })
+
+ it('signed out, the finish screen\'s section explains itself; where the files live is said once there are some', () => {
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')
+ expect(host.textContent).not.toContain('Kept on this device only')
+ useStore.setState(s => ({ S: { ...s.S, workouts: [workout({ media: [refOf(1)] })] } }))
+ const withOne = render(<WorkoutMediaSection w={S().workouts[0]} hint />)
+ expect(withOne.textContent).toContain('Kept on this device only')
+ })
+
+ it('the viewer takes focus, keeps Tab inside, and steps with the arrow keys (mirrored right to left)', () => {
+ useStore.setState(s => ({ S: { ...s.S, workouts: [workout({ media: [refOf(1), refOf(3), refOf(5)] })] } }))
+ const opener = document.createElement('button')
+ document.body.appendChild(opener)
+ opener.focus()
+ openWorkoutMediaViewer(S().workouts[0], 0)
+ const host = renderTop()
+ const box = host.querySelector('.mviewer')
+ const count = () => host.querySelector('.mviewer-count').textContent
+ expect(document.activeElement).toBe(host.querySelector('button[aria-label="Close"]'))
+ const key = (k, extra = {}) => act(() => { document.activeElement.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true, ...extra })) })
+ key('ArrowRight')
+ expect(count()).toBe('2 / 3')
+ key('ArrowLeft')
+ key('ArrowLeft')
+ expect(count()).toBe('3 / 3')
+ // Tab from the last control wraps to the first; Shift+Tab from the first to the last.
+ const buttons = [...box.querySelectorAll('button')]
+ buttons.at(-1).focus()
+ key('Tab')
+ expect(document.activeElement).toBe(buttons[0])
+ key('Tab', { shiftKey: true })
+ expect(document.activeElement).toBe(buttons.at(-1))
+ document.documentElement.dir = 'rtl'
+ try {
+ key('ArrowRight')
+ expect(count()).toBe('2 / 3')
+ } finally { document.documentElement.dir = 'ltr' }
})
it('Delete workout in the detail sheet says its photos and videos go with it', () => {