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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
fix(media): the Android app plays exercise clips from memory, without a poster
Duarte Santos39975e71a25c
diff --git a/frontend/src/components/Media.clip-memory.test.jsx b/frontend/src/components/Media.clip-memory.test.jsxnew file mode 100644index 000000000..700460eb9--- /dev/null+++ b/frontend/src/components/Media.clip-memory.test.jsx@@ -0,0 +1,44 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { useClipInMemory } from './Media.jsx'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++// The phone app plays a clip from memory: Capacitor's local server answered every loop's seek+// with a slow fresh read, and the animations crawled and stalled. The web keeps the plain URL.+function Probe({ src, inApp, out }) { out.value = useClipInMemory(src, inApp); return null }+const mount = props => { const host = document.createElement('div'); const root = createRoot(host); act(() => root.render(<Probe {...props} />)); return root }++describe('useClipInMemory', () => {+ afterEach(() => vi.restoreAllMocks())++ it('keeps the URL on the web', () => {+ const out = {}+ mount({ src: 'exercise-media/clip/0001.mp4', inApp: false, out })+ expect(out.value).toBe('exercise-media/clip/0001.mp4')+ })++ it('in the app, shows nothing until the clip is in memory, then a blob URL, read once', async () => {+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(new Blob(['x'], { type: 'video/mp4' })))+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:clip-1')+ const out = {}+ mount({ src: 'exercise-media/clip/0002.mp4', inApp: true, out })+ expect(out.value).toBe(null)+ await act(async () => { await new Promise(r => setTimeout(r, 0)) })+ expect(out.value).toBe('blob:clip-1')+ const again = {}+ mount({ src: 'exercise-media/clip/0002.mp4', inApp: true, out: again })+ expect(again.value).toBe('blob:clip-1')+ expect(fetchSpy).toHaveBeenCalledTimes(1)+ })++ it('falls back to the URL when the read fails', async () => {+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('offline'))+ const out = {}+ mount({ src: 'exercise-media/clip/0003.mp4', inApp: true, out })+ await act(async () => { await new Promise(r => setTimeout(r, 0)) })+ expect(out.value).toBe('exercise-media/clip/0003.mp4')+ })+})diff --git a/frontend/src/components/Media.jsx b/frontend/src/components/Media.jsxindex 723d119c7..cd473c440 100644--- a/frontend/src/components/Media.jsx+++ b/frontend/src/components/Media.jsx@@ -1,5 +1,6 @@-import { useState } from 'react'+import { useEffect, useState } from 'react'import { imgSrc, gifSrc, isVideoSrc, isCustomEx, figureOf } from '../lib/exercises.js'+import { MOBILE } from '../lib/mobile.js'import { useStore } from '../store/useStore.js'import { t, exerciseNameFor } from '../lib/i18n.js'import Icon from './Icon.jsx'@@ -30,6 +31,8 @@ function BuiltinMedia({ ex, id, compact, minimizable }) {const gifSize = useStore(s => s.S.gifSize)const body = useStore(s => figureOf(s.S))const update = useStore(s => s.update)+ const clip = ex.gif && isVideoSrc(gifSrc(ex, body)) ? gifSrc(ex, body) : null+ const clipSrc = useClipInMemory(clip)if (!ex.gif) return nullif (minimizable && gifSize === 'off') return nullconst mini = minimizable && gifSize === 'mini'@@ -44,9 +47,14 @@ function BuiltinMedia({ ex, id, compact, minimizable }) {<div className={'exmedia' + (compact ? ' compact' : '') + (mini ? ' mini' : '') + (failed === 'all' ? ' broken' : '')} id={id} onClick={onTap}>{failed === 'all'? <div className="exmedia-x"><Icon name="dumbbell" /></div>- : showGif && isVideoSrc(gifSrc(ex, body))- ? <video ref={autoplayMuted} className="catvid" src={gifSrc(ex, body)} poster={imgSrc(ex, body)} autoPlay muted loop playsInline disablePictureInPicture+ : showGif && clip && clipSrc+ // No poster: Android's WebView went back to it at every loop and stalled there (the+ // still above stands in while the clip loads, so nothing is lost without it).+ ? <video ref={autoplayMuted} className="catvid" src={clipSrc} autoPlay muted loop playsInline disablePictureInPicturearia-label={exerciseNameFor(ex)} onError={onError} />+ : showGif && clip+ // the phone app is still reading the clip into memory: the still holds its place+ ? <img decoding="async" draggable={false} src={imgSrc(ex, body)} alt={exerciseNameFor(ex)} />: <img decoding="async" draggable={false} src={showGif ? gifSrc(ex, body) : imgSrc(ex, body)} alt={exerciseNameFor(ex)} onError={onError} />}{minimizable && (<button className="giftoggle" onClick={toggleSize}>@@ -62,6 +70,50 @@ function BuiltinMedia({ ex, id, compact, minimizable }) {)}+// In the phone app the clips come out of the app package through Capacitor's local server, which+// answers every seek with a fresh, slow read: each loop jumped back to 0 and sat there for one to+// five seconds, and users saw "slow and buggy" animations (the web, with its HTTP cache, never+// did). So the app reads a clip into memory once (20-40 KB) and plays it from there; the last few+// stay, so reopening an exercise is instant. The web keeps its URL and the browser's cache.+const MEMORY_CLIPS = 30+const clipCache = new Map() // src -> object URL, oldest first+const clipLoads = new Map() // src -> pending promise+function loadClip(src) {+ if (clipCache.has(src)) {+ const url = clipCache.get(src)+ clipCache.delete(src); clipCache.set(src, url) // most recently used last+ return Promise.resolve(url)+ }+ if (!clipLoads.has(src)) {+ clipLoads.set(src, fetch(src)+ .then(r => (r.ok ? r.blob() : Promise.reject(new Error('HTTP ' + r.status))))+ .then(blob => {+ const url = URL.createObjectURL(blob)+ clipCache.set(src, url)+ while (clipCache.size > MEMORY_CLIPS) {+ const [old, oldUrl] = clipCache.entries().next().value+ clipCache.delete(old); URL.revokeObjectURL(oldUrl)+ }+ return url+ })+ .finally(() => clipLoads.delete(src)))+ }+ return clipLoads.get(src)+}++export function useClipInMemory(src, inApp = MOBILE) {+ const [url, setUrl] = useState(() => (src && inApp ? clipCache.get(src) || null : src))+ useEffect(() => {+ if (!src || !inApp) { setUrl(src); return }+ let alive = true+ setUrl(clipCache.get(src) || null)+ // A read that fails falls back to the URL itself: playing slowly beats not playing.+ loadClip(src).then(u => { if (alive) setUrl(u) }, () => { if (alive) setUrl(src) })+ return () => { alive = false }+ }, [src, inApp])+ return url+}+// React sets `muted` as a property only, never as the attribute, and Android's WebView (the phone// app) allows autoplay only for a video that carries the attribute: the loop sat on its first frame// there while every desktop browser played it. Set it before the first frame and start playback