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.

Custom exercises: a photo, GIF or video of your own, and a link to a video or guide — in the editor, and wherever an exercise's picture shows

Duarte Santos6bb5da9b4b4f
diff --git a/frontend/src/components/CustomMedia.jsx b/frontend/src/components/CustomMedia.jsx
new file mode 100644
index 000000000..c28e6b66d
--- /dev/null
+++ b/frontend/src/components/CustomMedia.jsx
@@ -0,0 +1,276 @@
+// The photo, GIF, video or link of a custom exercise, wherever an exercise's media shows: the
+// detail sheet, the exercise config, the workout card, the picker, the library, a past workout,
+// the routine editor and the muscle explorer. Media.jsx sends every custom exercise here, so no
+// call site needed to change.
+//
+// Nothing here ever loads a file from a server URL. Every file is shown from the local media
+// store (lib/media-store.js); when it is not there yet and this device is signed in to a server
+// that stores media, it is fetched into the store first, checked against its sha256, and shown
+// from there. That is what makes a paired phone work (an <img src> cannot carry its Bearer token)
+// and what keeps a workout showing its pictures offline. Lists only ever load posters.
+//
+// Videos up to 15 s behave like the catalogue's GIFs: muted, looping, tap to pause — except in
+// the workout's list layout (several cards at once must not run several decoders), under reduced
+// motion, and while the file is not here on a connection that should not fetch it unasked; there
+// the poster shows and a tap plays. Longer videos show their poster and play with sound and the
+// browser's own controls on a tap.
+//
+// A link is only ever opened, after a tap, in a new browsing context without an opener or a
+// referrer. Nothing fetches it: no thumbnail, no favicon, no embed.
+import { useEffect, useRef, useState } from 'react'
+import { useStore } from '../store/useStore.js'
+import { t, exerciseNameFor } from '../lib/i18n.js'
+import { mediaOf, cleanUrl, linkKind } from '../lib/media-refs.js'
+import { mediaStore } from '../lib/media-store.js'
+import { fetchToStore, mayFetch } from '../lib/media-sync.js'
+import { prefetchAllowed } from '../lib/media-prefetch.js'
+import { LOOP_MAX_SEC } from '../lib/media-limits.js'
+import Icon from './Icon.jsx'
+
+/** Opens a link after a tap: sanitised again here, since plan files and backups can bring any
+ * string in, and in a new browsing context with no opener and no Referer. */
+export function openExternal(url) {
+ const u = cleanUrl(url)
+ if (u) window.open(u, '_blank', 'noopener,noreferrer')
+}
+
+/**
+ * A URL for one stored file ({ hash, mime, size } — a MediaRef or its poster), from the local
+ * store, fetching it there first when it is missing and `auto` allows. { url, status, load }:
+ * status 'ready' | 'loading' | 'idle' (not here, waiting for a tap) | 'missing' (nobody has it
+ * for this device) | 'offline' | 'none' (no file given). load() fetches now, past the backoff —
+ * a tap on a tile that failed.
+ */
+export function useMediaUrl(file, { auto = true } = {}) {
+ const hash = file && typeof file.hash === 'string' ? file.hash : null
+ const canFetch = useStore(s => !!(s.user && s.config?.media))
+ const [state, setState] = useState({ url: null, status: hash ? 'loading' : 'none' })
+ const [asked, setAsked] = useState(0)
+ const [rev, setRev] = useState(0)
+ const ready = state.status === 'ready'
+ // A file that arrives some other way (the plan's prefetch, another card, the editor) shows up
+ // without a tap; and one that failed for lack of a network is tried again when it returns.
+ useEffect(() => {
+ if (!hash || ready) return
+ const bump = () => setRev(v => v + 1)
+ const off = mediaStore.subscribe(bump)
+ globalThis.addEventListener?.('online', bump)
+ return () => { off(); globalThis.removeEventListener?.('online', bump) }
+ }, [hash, ready])
+ useEffect(() => {
+ if (!hash) { setState({ url: null, status: 'none' }); return }
+ let alive = true
+ let held = false
+ const show = url => {
+ if (!alive) { mediaStore.release(hash); return }
+ held = true
+ setState({ url, status: 'ready' })
+ }
+ ;(async () => {
+ const here = await mediaStore.url(hash).catch(() => null)
+ if (here) return show(here)
+ if (!alive) return
+ if (!canFetch) return setState({ url: null, status: 'missing' })
+ if (!auto && !asked) return setState({ url: null, status: 'idle' })
+ if (!asked && !mayFetch(hash)) return setState({ url: null, status: 'missing' })
+ setState(s => (s.status === 'loading' ? s : { url: null, status: 'loading' }))
+ try { await fetchToStore(hash, file, { force: asked > 0 }) }
+ catch (e) { if (alive) setState({ url: null, status: e?.code === 'offline' ? 'offline' : 'missing' }); return }
+ const got = await mediaStore.url(hash).catch(() => null)
+ if (got) show(got)
+ else if (alive) setState({ url: null, status: 'missing' })
+ })()
+ return () => { alive = false; if (held) mediaStore.release(hash) }
+ // `file` is described by its hash; the rest of it cannot change without the hash changing.
+ }, [hash, auto, asked, canFetch, rev])
+ return { ...state, load: () => setAsked(n => n + 1) }
+}
+
+const reducedMotion = () => {
+ try { return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches } catch { return false }
+}
+
+/* ------------------------------------------------------------------ thumbnails ----------- */
+
+// A still that will not load gets the same neutral tile as an exercise without media, like the
+// catalogue's thumbs (#281). While a poster is on its way the tile shows too, so a row never jumps.
+export function CustomThumb({ ex }) {
+ const m = mediaOf(ex)
+ const link = m ? null : cleanUrl(ex?.url)
+ const poster = useMediaUrl(m?.poster || null)
+ const [broken, setBroken] = useState(null)
+ if (poster.url && broken !== poster.url) {
+ return <img className="thumb" loading="lazy" decoding="async" draggable={false} src={poster.url} alt="" onError={() => setBroken(poster.url)} />
+ }
+ const icon = m?.kind === 'video' || (link && linkKind(link) === 'video') ? 'play' : link ? 'link' : 'dumbbell'
+ return <div className="thumb thumb-x"><Icon name={icon} /></div>
+}
+
+/* ------------------------------------------------------------------ links ---------------- */
+
+// #246's card, as a <button> rather than a link: nothing on the page points at the address, so
+// the browser has nothing to prefetch or preconnect to.
+export function LinkCard({ url, compact, mini }) {
+ const u = cleanUrl(url)
+ if (!u) return null
+ const video = linkKind(u) === 'video'
+ let host = ''
+ try { host = new URL(u).hostname } catch { /* cleanUrl already vouched for it */ }
+ return (
+ <button type="button" className={'exlink-card' + (compact ? ' compact' : '') + (mini ? ' mini' : '')} data-swipe-ignore
+ onClick={e => { e.stopPropagation(); openExternal(u) }}>
+ <span className="exlink-icon"><Icon name={video ? 'play' : 'link'} /></span>
+ <span className="exlink-meta">
+ <span className="exlink-title">{video ? t('Watch video') : t('Open link')}</span>
+ {!mini && host && <span className="exlink-sub" dir="ltr">{host}</span>}
+ </span>
+ <Icon name="chevronRight" className="exlink-arr" />
+ </button>
+ )
+}
+
+/* ------------------------------------------------------------------ the big picture ------- */
+
+export default function CustomMedia({ ex, id, compact, minimizable }) {
+ const gifSize = useStore(s => s.S.gifSize)
+ const update = useStore(s => s.update)
+ // The workout's list layout, from the store: only the workout card is minimizable.
+ const listLayout = useStore(s => !!minimizable && ((s.S.active?.workoutView || s.S.workoutView) === 'list'))
+ const m = mediaOf(ex)
+ const link = cleanUrl(ex?.url)
+ if (!m && !link) return null
+ if (minimizable && gifSize === 'off') return null
+ const mini = !!minimizable && gifSize === 'mini'
+ const toggleSize = e => { e.stopPropagation(); update(s => { s.gifSize = mini ? 'full' : 'mini' }) }
+ const toggle = minimizable
+ ? <button className="giftoggle" onClick={toggleSize}><Icon name={mini ? 'expand' : 'minimize'} />{mini ? t('Expand') : t('Minimize')}</button>
+ : null
+ const cls = 'exmedia' + (compact ? ' compact' : '') + (mini ? ' mini' : '')
+ const name = exerciseNameFor(ex)
+ if (!m) return <LinkCard url={link} compact={compact} mini={mini} />
+ const body = m.kind === 'video'
+ ? <CustomVideo key={m.hash} m={m} id={id} cls={cls} name={name} toggle={toggle} mini={mini} still={listLayout || reducedMotion()} />
+ : m.kind === 'gif'
+ ? <CustomGif key={m.hash} m={m} id={id} cls={cls} name={name} toggle={toggle} mini={mini} />
+ : <CustomImage key={m.hash} m={m} id={id} cls={cls} name={name} toggle={toggle} />
+ return <>
+ {body}
+ {link && !mini && <LinkCard url={link} compact />}
+ </>
+}
+
+// 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>
+
+function CustomImage({ m, id, cls, name, toggle }) {
+ const main = useMediaUrl(m)
+ const [broken, setBroken] = useState(false)
+ const ok = main.url && !broken
+ return (
+ <div className={cls + (ok ? '' : ' broken')} id={id} onClick={() => { if (!ok) { setBroken(false); main.load() } }}>
+ {ok ? <img decoding="async" draggable={false} src={main.url} alt={name} onError={() => setBroken(true)} /> : <Tile />}
+ {toggle}
+ </div>
+ )
+}
+
+// Like the catalogue's GIFs: the animation plays, a tap switches to the still (the poster) and
+// back, and a file that will not load falls back to the still, then to the tile.
+function CustomGif({ m, id, cls, name, toggle, mini }) {
+ const [playing, setPlaying] = useState(true)
+ const main = useMediaUrl(m)
+ const poster = useMediaUrl(m.poster || null)
+ const [failed, setFailed] = useState(null) // 'gif' → the still is showing; 'all' → the tile
+ const showGif = playing && failed == null && !!main.url
+ const src = showGif ? main.url : poster.url || (failed == null ? main.url : null)
+ const broken = !src || failed === 'all'
+ const onTap = () => {
+ if (broken || failed) { setFailed(null); setPlaying(true); main.load(); poster.load(); return }
+ setPlaying(p => !p)
+ }
+ return (
+ <div className={cls + (broken ? ' broken' : '')} id={id} onClick={onTap}>
+ {broken ? <Tile /> : <img decoding="async" draggable={false} src={src} alt={name} onError={() => setFailed(showGif ? 'gif' : 'all')} />}
+ {toggle}
+ {!mini && !broken && !failed && (
+ <span className="gifhint"><Icon name={playing ? 'pause' : 'play'} />{playing ? t('tap to pause') : t('tap to play')}</span>
+ )}
+ </div>
+ )
+}
+
+// iOS plays a video inline and unasked only when it is muted from the start, and React sets
+// `muted` as a property after the element exists — too late for Safari's autoplay check. So the
+// attribute is written by hand before the source is attached.
+const mute = el => {
+ if (!el) return
+ el.muted = true
+ el.defaultMuted = true
+ el.setAttribute('muted', '')
+}
+
+function CustomVideo({ m, id, cls, name, toggle, mini, still }) {
+ const loop = m.dur != null && m.dur <= LOOP_MAX_SEC
+ const poster = useMediaUrl(m.poster || null)
+ // The file itself only comes down unasked where a few MB cost nothing; otherwise on the tap.
+ const main = useMediaUrl(m, { auto: prefetchAllowed() })
+ const ref = useRef(null)
+ const box = useRef(null)
+ // A short clip loops by itself where it may; a long one, or one that may not, waits for a tap.
+ const [wantPlay, setWantPlay] = useState(loop && !still)
+ const [playing, setPlaying] = useState(false)
+ const [broken, setBroken] = useState(false)
+ // A long video is playing with sound and controls since its tap.
+ const [open, setOpen] = useState(false)
+
+ useEffect(() => {
+ const el = ref.current
+ if (!el || !main.url) return
+ if (wantPlay) el.play().then(() => setPlaying(true)).catch(() => { setPlaying(false); setWantPlay(false) })
+ else { el.pause(); setPlaying(false) }
+ }, [wantPlay, main.url])
+
+ // Scrolled out of view, a playing video stops: in the list layout it would otherwise go on
+ // decoding (and, for a long one, talking) below the fold.
+ useEffect(() => {
+ const el = box.current
+ if (!el || typeof IntersectionObserver !== 'function') return
+ const io = new IntersectionObserver(([e]) => { if (!e.isIntersecting && ref.current && !ref.current.paused) { ref.current.pause(); setPlaying(false); setWantPlay(false) } })
+ io.observe(el)
+ return () => io.disconnect()
+ }, [])
+
+ const onTap = () => {
+ if (broken) { setBroken(false); main.load(); poster.load(); return }
+ if (!main.url) { main.load(); setWantPlay(true); if (!loop) setOpen(true); return }
+ if (!loop) {
+ // The first tap on a long video hands it the browser's own controls, with sound; after
+ // that the controls are the video's, and taps on it are theirs.
+ if (!open) { setOpen(true); setWantPlay(true) }
+ return
+ }
+ setWantPlay(p => !p)
+ }
+
+ const loading = !main.url && main.status === 'loading'
+ const hint = !mini && !broken && !(open && main.url)
+ return (
+ <div ref={box} className={cls + (broken || (!main.url && !poster.url) ? ' broken' : '')} id={id} onClick={open && main.url ? undefined : onTap}>
+ {main.url && !broken
+ ? <video ref={el => { ref.current = el; if (el && !open) mute(el) }} src={main.url} poster={poster.url || undefined}
+ playsInline loop={loop && !open} autoPlay={loop && !still} controls={open} muted={!open}
+ preload={loop ? 'auto' : 'metadata'} aria-label={name}
+ onPlay={() => setPlaying(true)} onPause={() => setPlaying(false)} onError={() => setBroken(true)} />
+ : poster.url && !broken
+ ? <img decoding="async" draggable={false} src={poster.url} alt={name} />
+ : <Tile />}
+ {toggle}
+ {hint && (
+ <span className="gifhint">
+ <Icon name={playing ? 'pause' : 'play'} />{loading ? t('Loading…') : playing ? t('tap to pause') : t('tap to play')}
+ </span>
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/components/CustomMediaField.jsx b/frontend/src/components/CustomMediaField.jsx
new file mode 100644
index 000000000..74d187f5d
--- /dev/null
+++ b/frontend/src/components/CustomMediaField.jsx
@@ -0,0 +1,110 @@
+// The editor's part of a custom exercise's photo, GIF or video, and its link (CustomExForm in
+// sheets.jsx). The row follows #295's picture field (horusglez) — the thumb of the draft, a
+// tinted Add/Change and a ghost Remove — and the link field is #246's (Vaibhav159).
+//
+// A picked file is turned into what the state keeps right here (lib/media-ingest.js: re-encoded
+// or scrubbed, hashed, with a poster) and put into the local store as pending before the form is
+// saved. That order is safe: an abandoned draft's files are unreferenced and the local clean-up
+// takes them after an hour; the server marks an upload that nothing references yet and keeps it
+// for its grace period, so the state push landing after the upload changes nothing.
+//
+// The file input accepts image/* and video/* and nothing more specific: iOS converts a HEIC
+// photo to JPEG only when the page does not explicitly ask for HEIC, and every format is checked
+// on its bytes anyway.
+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 { mediaOf, fmtClip } from '../lib/media-refs.js'
+import { mediaStore } from '../lib/media-store.js'
+import { limitsFrom, fmtMB, MB } from '../lib/media-limits.js'
+import { CustomThumb } from './CustomMedia.jsx'
+import { Row, Button } from './ui.jsx'
+import Icon from './Icon.jsx'
+
+const toast = m => useUI.getState().toast(m)
+
+/** The sentence for a refused file (MediaError codes from lib/media-ingest.js). */
+export function mediaErrorText(e) {
+ switch (e?.code) {
+ case 'type': return t('That file type is not supported — use a photo, a GIF, or an MP4, MOV or WebM video.')
+ case 'too-large': return t('That file is too large — up to {0} MB.', fmtMB(e.mb))
+ case 'too-long': return t('That video is too long — up to {0} seconds.', e.sec)
+ case 'photo-too-big': return t('That photo is too large to process on this device.')
+ default: return t('This browser cannot read that file.')
+ }
+}
+
+const KIND_ICON = { image: 'image', gif: 'play', video: 'play' }
+
+export default function CustomMediaField({ media, url, onChange }) {
+ const user = useStore(s => s.user)
+ const config = useStore(s => s.config)
+ const [busy, setBusy] = useState(false)
+ const [warning, setWarning] = useState(null)
+ // 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 })
+ // 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.
+ const serverLacks = !!user && !!config && !config.media
+ const canAdd = storable && !serverLacks
+
+ 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
+ setBusy(true)
+ setWarning(null)
+ try {
+ // The ingest (decoders, canvas, the MP4 walk) only loads when someone picks a file.
+ const { ingestMediaFile } = await import('../lib/media-ingest.js')
+ const out = await ingestMediaFile(file, limitsFrom(config))
+ for (const b of out.blobs) await mediaStore.put(b.hash, b.blob, { mime: b.mime, pending: true })
+ // 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.'))
+ } catch (e) {
+ toast(mediaErrorText(e))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ const sizeLine = m ? [m.dur != null && m.kind !== 'image' ? fmtClip(m.dur) : null, (Math.max(0.1, Math.round((m.size / MB) * 10) / 10)).toFixed(1) + ' MB'].filter(Boolean).join(' · ') : null
+ 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}>
+ <div className="cmf-act">
+ {m && <span className="cmf-thumb"><CustomThumb ex={{ custom: true, media: m }} /></span>}
+ {canAdd && <Button variant="tinted" size="sm" icon={busy ? undefined : 'image'} disabled={busy} 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 }) }} />}
+ </div>
+ </Row>
+ <input ref={fileRef} type="file" accept="image/*,video/*" hidden onChange={onFile} />
+ {warning && <div className="small dim cmf-note">{warning}</div>}
+ {note && <div className="small dim cmf-note">{note}</div>}
+ <input className="input cmf-link" type="url" inputMode="url" autoCapitalize="off" autoCorrect="off" spellCheck={false}
+ dir={url ? 'ltr' : undefined} placeholder={t('Video or guide link (optional)')}
+ value={url || ''} onChange={e => onChange({ url: e.target.value })} />
+ </div>
+}
diff --git a/frontend/src/components/Media.jsx b/frontend/src/components/Media.jsx
index 0781e8149..6ce889175 100644
--- a/frontend/src/components/Media.jsx
+++ b/frontend/src/components/Media.jsx
@@ -3,15 +3,23 @@ import { imgSrc, gifSrc } from '../lib/exercises.js'
import { useStore } from '../store/useStore.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import Icon from './Icon.jsx'
+import CustomMedia, { CustomThumb } from './CustomMedia.jsx'
+
+// An exercise's picture, wherever one shows. A custom exercise goes to CustomMedia.jsx — its own
+// photo, GIF, video or link, from the local media store — and never through imgSrc/gifSrc, which
+// name files of the shipped dataset (a stray img/gif on a custom exercise, written by a fork, is
+// ignored). The split is by component, not by branch, so each side keeps its own hooks in order.
+export default function Media(p) {
+ return p.ex?.custom ? <CustomMedia {...p} /> : <BuiltinMedia {...p} />
+}
// Big autoplaying animation; tap toggles to the still frame. `compact` shrinks it (superset cards).
-// Custom exercises have no media — the animation stays blank by design (issue #11).
// `minimizable` (workout view) adds a persistent minimize/expand control so the animation stops
// eating the screen; the chosen size is saved to settings and carries across exercises and
// future workouts (issue #12). Settings can also turn workout media off entirely
// (gifSize 'off') — then nothing renders here and the exercise card closes up, exactly like
-// a custom exercise without media. Any other/legacy value behaves as 'full'.
-export default function Media({ ex, id, compact, minimizable }) {
+// an exercise without media. Any other/legacy value behaves as 'full'.
+function BuiltinMedia({ ex, id, compact, minimizable }) {
const [playing, setPlaying] = useState(true)
// 'gif' → the animation failed, the still is showing; 'all' → the still failed too. Media is
// fetched from wherever the build points (a mount, a CDN): a dropped connection, an expired
@@ -54,7 +62,10 @@ export default function Media({ ex, id, compact, minimizable }) {
// CDN hiccup) gets the same neutral tile as an exercise without media, instead of the browser's
// broken-image glyph in a list of them (#281). The failure is remembered per image, so a list
// that re-renders does not ask again; a new exercise in the same slot tries its own.
-export function Thumb({ ex }) {
+export function Thumb(p) {
+ return p.ex?.custom ? <CustomThumb {...p} /> : <BuiltinThumb {...p} />
+}
+function BuiltinThumb({ ex }) {
const src = ex.img ? imgSrc(ex) : null
const [broken, setBroken] = useState(null)
if (!src || broken === src) return <div className="thumb thumb-x"><Icon name="dumbbell" /></div>
diff --git a/frontend/src/components/Media.test.jsx b/frontend/src/components/Media.test.jsx
index 40e5b4099..de91754cd 100644
--- a/frontend/src/components/Media.test.jsx
+++ b/frontend/src/components/Media.test.jsx
@@ -2,7 +2,8 @@
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import Media from './Media.jsx'
+import Media, { Thumb } from './Media.jsx'
+import { createMediaStore, memoryBackend, _setMediaStore } from '../lib/media-store.js'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
@@ -72,3 +73,182 @@ describe('Media gifSize', () => {
expect(host.querySelector('.exmedia.mini')).toBeFalsy()
})
})
+
+/* ---------------------------------------------------------------- custom exercises -------- */
+
+const H = c => c.repeat(64)
+const MAIN = H('a'), POSTER = H('b')
+const still = { hash: POSTER, mime: 'image/webp', size: 3, width: 48, height: 36 }
+const image = { kind: 'image', hash: MAIN, mime: 'image/webp', size: 3, width: 80, height: 60, poster: still, at: 1 }
+const anim = { ...image, kind: 'gif', mime: 'image/gif', dur: 1.2 }
+const clip = (dur, over = {}) => ({ kind: 'video', hash: MAIN, mime: 'video/mp4', size: 3, width: 64, height: 36, dur, codec: 'avc1', poster: still, at: 1, ...over })
+const custom = over => ({ id: 'c1', n: 'sandbag carry', bp: 'back', custom: true, ...over })
+
+// Object URLs the store hands out, by file, so a test can tell which file an element shows.
+let media, made
+const settle = async () => { for (let i = 0; i < 6; i++) await act(async () => { await new Promise(r => setTimeout(r, 0)) }) }
+const mountCustom = async (ex, props = {}) => { act(() => root.render(<Media ex={ex} {...props} />)); await settle() }
+async function holding(...hashes) {
+ for (const h of hashes) await media.put(h, new Blob(['x']), { mime: h === MAIN ? 'image/webp' : 'image/webp', pending: false })
+}
+
+describe('Media — a custom exercise', () => {
+ beforeEach(() => {
+ made = []
+ media = createMediaStore(memoryBackend(), {
+ objectURL: { createObjectURL: b => { const u = 'blob:t/' + made.length; made.push(u); return u }, revokeObjectURL: () => {} },
+ canPlayType: () => ''
+ })
+ _setMediaStore(media)
+ HTMLMediaElement.prototype.play = vi.fn(function () { return Promise.resolve() })
+ HTMLMediaElement.prototype.pause = vi.fn()
+ })
+ afterEach(() => { _setMediaStore(null); delete window.matchMedia })
+
+ it('shows its photo from the local store, never a dataset path', async () => {
+ await holding(MAIN, POSTER)
+ await mountCustom(custom({ media: image, img: 'fork.jpg', gif: 'fork.gif' }))
+ const img = host.querySelector('.exmedia img')
+ expect(img.getAttribute('src')).toMatch(/^blob:t\//)
+ expect(host.innerHTML).not.toContain('fork.')
+ })
+
+ it('a GIF animates, and a tap switches to its still and back', async () => {
+ await holding(MAIN, POSTER)
+ await mountCustom(custom({ media: anim }))
+ const src = () => host.querySelector('.exmedia img').getAttribute('src')
+ const animated = src()
+ expect(host.querySelector('.gifhint').textContent).toContain('tap to pause')
+ act(() => { host.querySelector('.exmedia').click() })
+ expect(src()).not.toBe(animated)
+ expect(host.querySelector('.gifhint').textContent).toContain('tap to play')
+ act(() => { host.querySelector('.exmedia').click() })
+ expect(src()).toBe(animated)
+ })
+
+ it('a short video loops muted and inline, and plays by itself', async () => {
+ await holding(MAIN, POSTER)
+ await mountCustom(custom({ media: clip(8) }))
+ const v = host.querySelector('.exmedia video')
+ expect(v).toBeTruthy()
+ expect(v.muted).toBe(true)
+ expect(v.hasAttribute('muted')).toBe(true)
+ expect(v.loop).toBe(true)
+ expect(v.hasAttribute('playsinline')).toBe(true)
+ expect(v.hasAttribute('controls')).toBe(false)
+ expect(v.getAttribute('poster')).toMatch(/^blob:t\//)
+ expect(HTMLMediaElement.prototype.play).toHaveBeenCalled()
+ expect(host.querySelector('.gifhint').textContent).toContain('tap to pause')
+ })
+
+ it('does not play by itself in the workout\'s list layout, nor under reduced motion', async () => {
+ await holding(MAIN, POSTER)
+ mocks.S = { gifSize: 'full', workoutView: 'list' }
+ await mountCustom(custom({ media: clip(8) }), { minimizable: true })
+ expect(HTMLMediaElement.prototype.play).not.toHaveBeenCalled()
+ expect(host.querySelector('.gifhint').textContent).toContain('tap to play')
+ act(() => root.render(<div />))
+ mocks.S = { gifSize: 'full' }
+ window.matchMedia = q => ({ matches: q.includes('reduce'), addEventListener() {}, removeEventListener() {} })
+ await mountCustom(custom({ media: clip(8) }))
+ expect(HTMLMediaElement.prototype.play).not.toHaveBeenCalled()
+ act(() => { host.querySelector('.exmedia').click() })
+ await settle()
+ expect(HTMLMediaElement.prototype.play).toHaveBeenCalled()
+ })
+
+ it('a long video waits for a tap, then plays with sound and its own controls', async () => {
+ await holding(MAIN, POSTER)
+ await mountCustom(custom({ media: clip(45) }))
+ let v = host.querySelector('.exmedia video')
+ expect(v.hasAttribute('controls')).toBe(false)
+ expect(v.loop).toBe(false)
+ expect(HTMLMediaElement.prototype.play).not.toHaveBeenCalled()
+ act(() => { host.querySelector('.exmedia').click() })
+ await settle()
+ v = host.querySelector('.exmedia video')
+ expect(v.hasAttribute('controls')).toBe(true)
+ expect(v.muted).toBe(false)
+ expect(HTMLMediaElement.prototype.play).toHaveBeenCalled()
+ })
+
+ it("follows gifSize in the workout: nothing when 'off', the mini box when 'mini'", async () => {
+ await holding(MAIN, POSTER)
+ mocks.S = { gifSize: 'off' }
+ await mountCustom(custom({ media: image, url: 'https://youtu.be/x' }), { minimizable: true })
+ expect(host.innerHTML).toBe('')
+ mocks.S = { gifSize: 'mini' }
+ await mountCustom(custom({ media: image, url: 'https://youtu.be/x' }), { minimizable: true })
+ expect(host.querySelector('.exmedia.mini')).toBeTruthy()
+ expect(host.querySelector('.exlink-card')).toBeNull() // the card waits for the full size
+ })
+
+ it('a link alone is a card that opens it without an opener or a referrer — no img, no iframe, nothing fetched', async () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null)
+ await mountCustom(custom({ url: 'youtube.com/watch?v=abc' }))
+ expect(host.querySelector('img')).toBeNull()
+ expect(host.querySelector('iframe')).toBeNull()
+ expect(host.querySelector('a[href]')).toBeNull()
+ const card = host.querySelector('button.exlink-card')
+ expect(card.textContent).toContain('Watch video')
+ expect(card.textContent).toContain('youtube.com')
+ act(() => { card.click() })
+ expect(open).toHaveBeenCalledWith('https://youtube.com/watch?v=abc', '_blank', 'noopener,noreferrer')
+ open.mockRestore()
+ })
+
+ it('a link that is not a web address renders nothing and opens nothing', async () => {
+ await mountCustom(custom({ url: 'javascript:alert(1)' }))
+ expect(host.innerHTML).toBe('')
+ })
+
+ it('a photo and a link: the card sits under the picture, and says Open link for a guide', async () => {
+ await holding(MAIN, POSTER)
+ await mountCustom(custom({ media: image, url: 'https://exrx.net/guide' }))
+ expect(host.querySelector('.exmedia img')).toBeTruthy()
+ expect(host.querySelector('.exlink-card').textContent).toContain('Open link')
+ })
+
+ it('a file that is not here, with no server to ask, shows the tile', async () => {
+ await mountCustom(custom({ media: image }))
+ expect(host.querySelector('.exmedia.broken .exmedia-x')).toBeTruthy()
+ expect(host.querySelector('img')).toBeNull()
+ })
+})
+
+describe('Thumb — a custom exercise', () => {
+ beforeEach(() => {
+ made = []
+ media = createMediaStore(memoryBackend(), { objectURL: { createObjectURL: () => 'blob:t/' + made.push(1), revokeObjectURL: () => {} } })
+ _setMediaStore(media)
+ })
+ afterEach(() => _setMediaStore(null))
+ const mountThumb = async ex => { act(() => root.render(<Thumb ex={ex} />)); await settle() }
+
+ it('loads the poster and nothing else', async () => {
+ const asked = []
+ const url = media.url
+ media.url = h => { asked.push(h); return url(h) }
+ await holding(MAIN, POSTER)
+ await mountThumb(custom({ media: clip(30) }))
+ expect(host.querySelector('img.thumb')).toBeTruthy()
+ expect(asked).toEqual([POSTER])
+ })
+
+ it('a video without a poster shows play; a link shows play for a video site and link otherwise; nothing shows the dumbbell', async () => {
+ await mountThumb(custom({ media: clip(30, { poster: undefined }) }))
+ expect(host.querySelector('.thumb-x [data-icon="play"]')).toBeTruthy()
+ await mountThumb(custom({ url: 'https://vimeo.com/1' }))
+ expect(host.querySelector('.thumb-x [data-icon="play"]')).toBeTruthy()
+ await mountThumb(custom({ url: 'https://exrx.net/x' }))
+ expect(host.querySelector('.thumb-x [data-icon="link"]')).toBeTruthy()
+ await mountThumb(custom({}))
+ expect(host.querySelector('.thumb-x [data-icon="dumbbell"]')).toBeTruthy()
+ })
+
+ it('a poster that is not here shows the tile while nothing can fetch it', async () => {
+ await mountThumb(custom({ media: image }))
+ expect(host.querySelector('.thumb-x')).toBeTruthy()
+ expect(host.querySelector('img')).toBeNull()
+ })
+})
diff --git a/frontend/src/index.css b/frontend/src/index.css
index 3414feff1..285124581 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -772,6 +772,55 @@ body.chips-dragging *{cursor:inherit}
.exmedia-x{width:100%;height:320px;display:flex;align-items:center;justify-content:center;color:var(--label-3);font-size:34px}
.exmedia.compact .exmedia-x{height:120px}
.exmedia.mini .exmedia-x{height:84px}
+/* a custom exercise's own video (components/CustomMedia.jsx): the same box as a picture, on black
+ so a clip that does not fill it is letterboxed like any player */
+.exmedia video{width:100%;height:320px;object-fit:contain;display:block;background:#000}
+.exmedia.compact video{height:120px}
+.exmedia.mini video{height:84px}
+.exmedia:has(> video){background:#000}
+
+/* the link to a video or a guide (#246): a quiet action tile under the picture, or in its place.
+ A <button>, so the reset of the browser's button look comes first. */
+.exlink-card{
+ display:flex;align-items:center;gap:12px;width:100%;text-align:start;font:inherit;border:0;
+ background:var(--surface);border-radius:var(--r-card);
+ padding:10px 14px;margin-bottom:12px;
+ cursor:pointer;color:var(--label);
+ transition:background var(--fast),transform var(--fast);
+ user-select:none;-webkit-user-select:none;
+}
+.exlink-card:active{background:var(--surface-2);transform:scale(.98)}
+.exlink-icon{
+ width:34px;height:34px;border-radius:9px;
+ display:flex;align-items:center;justify-content:center;
+ background:var(--surface-2);color:var(--label);font-size:18px;flex:none;
+}
+.exlink-meta{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}
+.exlink-title{
+ font-size:15px;font-weight:500;color:var(--label);line-height:1.25;
+ white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
+}
+/* a host name reads left to right in every language; text-align keeps it on the reading side */
+.exlink-sub{
+ font-size:12px;color:var(--label-2);line-height:1.2;text-align:start;unicode-bidi:plaintext;
+ white-space:nowrap;overflow:hidden;text-overflow:ellipsis;
+}
+.exlink-arr{color:var(--label-3);font-size:14px;flex:none}
+.exlink-card.mini{padding:6px 12px;gap:10px}
+.exlink-card.mini .exlink-icon{width:28px;height:28px;font-size:15px;border-radius:7px}
+.exlink-card.mini .exlink-title{font-size:13px}
+
+/* the editor's field (components/CustomMediaField.jsx): the row, a 36px thumb of the draft, the
+ buttons beside it, the notes under it and the link input */
+.cmf{margin-top:8px}
+.cmf .lrow{padding-inline:4px}
+.cmf-act{display:flex;align-items:center;gap:6px;flex:none}
+.cmf-thumb .thumb{width:36px;height:36px;border-radius:8px}
+.cmf-thumb .thumb-x{font-size:16px}
+.cmf-sub{display:inline-flex;align-items:center;gap:4px}
+.cmf-sub .icn{font-size:13px}
+.cmf-note{margin:0 4px 6px;line-height:1.35}
+.cmf-link{margin-top:4px}
.sethead{
display:flex;align-items:center;gap:8px;padding:0 0 6px;
@@ -1506,7 +1555,7 @@ body.chips-dragging *{cursor:inherit}
/* 520px fits the clock, the bar and all three controls on one line again */
#timer.rest{flex-direction:row;align-items:center;gap:14px}
#timer.rest .head{flex:1;min-width:0}
- .exmedia img{height:380px}
+ .exmedia img,.exmedia video{height:380px}
.hm-wrap{display:flex;flex-direction:column;align-items:center}
}
diff --git a/frontend/src/lib/media-ingest.js b/frontend/src/lib/media-ingest.js
new file mode 100644
index 000000000..c3798f4f7
--- /dev/null
+++ b/frontend/src/lib/media-ingest.js
@@ -0,0 +1,289 @@
+/* A picked file → what the state keeps (a MediaRef) and what the local store keeps (the blobs).
+ *
+ * Nothing leaves the device as it was picked:
+ * - A photo (JPEG, PNG, WebP, HEIC, AVIF) is decoded and drawn again on a canvas — WebP where
+ * the browser can really write it, else JPEG on white (Safari) — at most 1600 px on its long
+ * edge, plus a 480 px poster. EXIF, GPS and colour profiles do not survive a canvas, so the
+ * location a phone wrote into the photo is gone by construction, not by a scrub that could
+ * miss a field. Before decoding, the header's pixel count is checked: a 100-megapixel photo
+ * would need several hundred MB just to open.
+ * - A GIF keeps its frames and loses its comment and metadata blocks (media-sniff cleanGif). A
+ * GIF of one frame is a photo and goes down that path.
+ * - An MP4/MOV keeps its video and sound; its metadata boxes and the samples of any track that is
+ * neither (timed metadata, GPS telemetry) are zeroed in place (media-sniff scrubMp4). A WebM is
+ * kept as it is — its scrub is deferred, and the docs say so.
+ * Every video is then opened in a hidden <video> once (probeVideo) for its size, its length when
+ * the file does not say, and a poster frame. A video this browser cannot play is still accepted
+ * — another device may play it — with a warning and no poster.
+ *
+ * The original file name is never kept anywhere.
+ */
+import { sniffKind, imageDims, inspectGif, cleanGif, inspectMp4, scrubMp4, inspectWebm } from './media-sniff.js'
+import { normalizeMediaRef } from './media-refs.js'
+import { sha256Hex } from './sha256.js'
+import { MB, IMAGE_MAX_EDGE, POSTER_EDGE, MAX_PHOTO_MP, DEFAULT_LIMITS } from './media-limits.js'
+import { playType } from './media-store.js'
+
+/** A refusal the editor turns into a sentence: code 'type' | 'too-large' (mb) | 'too-long'
+ * (sec) | 'photo-too-big' | 'unreadable'. */
+export class MediaError extends Error {
+ constructor(code, extra = {}) { super(code); this.code = code; Object.assign(this, extra) }
+}
+
+const WARN_CODEC = 'codec' // the editor's "may not play on every device" line
+const round1 = n => Math.round(n * 10) / 10
+
+/* ---------------------------------------------------------------- photos */
+
+/**
+ * A decoded picture to draw from: { source, width, height, close() }. createImageBitmap first,
+ * which applies the photo's own orientation; an <img> otherwise (older Safari). Throws
+ * MediaError('unreadable') when neither can read it — a HEIC on a browser without HEIC support.
+ */
+export async function decodeImage(blob, mime, { doc = globalThis.document } = {}) {
+ if (typeof globalThis.createImageBitmap === 'function') {
+ try {
+ const bmp = await globalThis.createImageBitmap(blob, { imageOrientation: 'from-image' })
+ return { source: bmp, width: bmp.width, height: bmp.height, close: () => { try { bmp.close() } catch { /* gone */ } } }
+ } catch { /* the <img> path below */ }
+ }
+ if (!doc) throw new MediaError('unreadable')
+ // Typed with the sniffed image type, never the file's own: see media-store.js on blob: URLs.
+ const url = URL.createObjectURL(new Blob([blob], { type: mime }))
+ const img = doc.createElement('img')
+ try {
+ img.src = url
+ await img.decode()
+ if (!img.naturalWidth || !img.naturalHeight) throw new Error('empty')
+ return { source: img, width: img.naturalWidth, height: img.naturalHeight, close: () => URL.revokeObjectURL(url) }
+ } catch {
+ URL.revokeObjectURL(url)
+ throw new MediaError('unreadable')
+ }
+}
+
+const toBlob = (canvas, type, q) => new Promise(resolve => {
+ try { canvas.toBlob(b => resolve(b), type, q) } catch { resolve(null) }
+})
+const isWebp = async blob => {
+ if (!blob || blob.type !== 'image/webp') return false
+ const h = new Uint8Array(await blob.slice(0, 16).arrayBuffer())
+ return sniffKind(h)?.mime === 'image/webp'
+}
+
+/**
+ * `pic` drawn at most `edge` px on its long side and encoded: { blob, mime, width, height }.
+ * WebP when toBlob really returns WebP — checked on the bytes, since Safari silently hands back
+ * a PNG for a WebP request, and a PNG would slip past the size cap and keep the alpha channel
+ * nobody asked for — else JPEG drawn on white. The canvas is emptied afterwards: a phone keeps
+ * canvas memory until it is.
+ */
+export async function encodeImage(pic, edge, quality, { doc = globalThis.document } = {}) {
+ const scale = Math.min(1, edge / Math.max(pic.width, pic.height))
+ const w = Math.max(1, Math.round(pic.width * scale))
+ const h = Math.max(1, Math.round(pic.height * scale))
+ const canvas = doc.createElement('canvas')
+ canvas.width = w
+ canvas.height = h
+ try {
+ const ctx = canvas.getContext('2d')
+ ctx.imageSmoothingQuality = 'high'
+ ctx.drawImage(pic.source, 0, 0, w, h)
+ const webp = await toBlob(canvas, 'image/webp', quality)
+ if (await isWebp(webp)) return { blob: webp, mime: 'image/webp', width: w, height: h }
+ ctx.globalCompositeOperation = 'destination-over'
+ ctx.fillStyle = '#fff'
+ ctx.fillRect(0, 0, w, h)
+ const jpeg = await toBlob(canvas, 'image/jpeg', quality)
+ const head = jpeg ? new Uint8Array(await jpeg.slice(0, 4).arrayBuffer()) : null
+ if (!jpeg || sniffKind(head)?.mime !== 'image/jpeg') throw new MediaError('unreadable')
+ return { blob: jpeg, mime: 'image/jpeg', width: w, height: h }
+ } finally {
+ canvas.width = 0
+ canvas.height = 0
+ }
+}
+
+// The photo itself, under the image cap: a busy 1600 px photo can come out above 2 MB at 0.85,
+// so the quality steps down once and then the size, before the photo is refused.
+async function encodeMain(pic, limits, deps) {
+ const cap = limits.imageMB * MB
+ for (const [edge, q] of [[IMAGE_MAX_EDGE, 0.85], [IMAGE_MAX_EDGE, 0.7], [1200, 0.7], [960, 0.6]]) {
+ const out = await deps.encodeImage(pic, edge, q, deps)
+ if (out.blob.size <= cap) return out
+ }
+ throw new MediaError('too-large', { mb: limits.imageMB })
+}
+
+async function photo(file, sniffed, limits, deps) {
+ if (file.size > limits.rawPhotoMB * MB) throw new MediaError('too-large', { mb: limits.rawPhotoMB })
+ if (!sniffed.input) {
+ const head = new Uint8Array(await file.slice(0, 256 * 1024).arrayBuffer())
+ const d = imageDims(head)
+ if (d && d.width * d.height > MAX_PHOTO_MP * 1e6) throw new MediaError('photo-too-big')
+ }
+ const pic = await deps.decodeImage(file, sniffed.mime, deps)
+ try {
+ if (pic.width * pic.height > MAX_PHOTO_MP * 1e6) throw new MediaError('photo-too-big')
+ const main = await encodeMain(pic, limits, deps)
+ const poster = await deps.encodeImage(pic, POSTER_EDGE, 0.8, deps)
+ return { kind: 'image', main, poster }
+ } finally { pic.close() }
+}
+
+/* ---------------------------------------------------------------- GIFs */
+
+async function gif(file, limits, deps) {
+ if (file.size > limits.gifMB * MB) throw new MediaError('too-large', { mb: limits.gifMB })
+ const bytes = new Uint8Array(await file.arrayBuffer())
+ const info = inspectGif(bytes)
+ if (!info) throw new MediaError('unreadable')
+ if (info.frames === 1) return photo(new Blob([bytes], { type: 'image/gif' }), { mime: 'image/gif' }, limits, deps)
+ let clean
+ try { clean = cleanGif(bytes) } catch { throw new MediaError('unreadable') }
+ const main = { blob: new Blob([clean], { type: 'image/gif' }), mime: 'image/gif', width: info.width, height: info.height }
+ // The poster is the first frame: a decode of a GIF gives exactly that.
+ let poster = null
+ const pic = await deps.decodeImage(main.blob, 'image/gif', deps)
+ try { poster = await deps.encodeImage(pic, POSTER_EDGE, 0.8, deps) } finally { pic.close() }
+ return { kind: 'gif', main, poster, dur: round1(info.durMs / 1000) }
+}
+
+/* ---------------------------------------------------------------- videos */
+
+const once = (el, ok, ms) => new Promise((resolve, reject) => {
+ const done = v => { clearTimeout(t); el.removeEventListener(ok, onOk); el.removeEventListener('error', onErr); v instanceof Error ? reject(v) : resolve(v) }
+ const onOk = () => done(true)
+ const onErr = () => done(new Error('media error'))
+ const t = setTimeout(() => done(new Error('timeout')), ms)
+ el.addEventListener(ok, onOk)
+ el.addEventListener('error', onErr)
+})
+
+/**
+ * Opens a video once in a detached, muted <video>: { width, height, duration, poster } — or
+ * null when this browser cannot play it. duration is NaN when even a seek to the end does not
+ * tell (a recording that never wrote its length). The poster is a frame half a second in (or
+ * half-way through a shorter clip), drawn after a muted play/pause, since iOS may otherwise draw
+ * black. Everything it made is taken down again before it returns.
+ */
+export async function probeVideo(blob, mime, { doc = globalThis.document, timeoutMs = 8000, encode = encodeImage } = {}) {
+ if (!doc) return null
+ const video = doc.createElement('video')
+ const url = URL.createObjectURL(new Blob([blob], { type: mime }))
+ video.muted = true
+ video.playsInline = true
+ video.setAttribute('playsinline', '')
+ video.preload = 'auto'
+ try {
+ video.src = url
+ await once(video, 'loadedmetadata', timeoutMs)
+ let duration = video.duration
+ if (!Number.isFinite(duration)) {
+ // Chrome's MediaRecorder WebM and fragmented MP4s say Infinity until the end is reached.
+ try {
+ video.currentTime = 1e7
+ await once(video, 'seeked', 3000)
+ duration = video.duration
+ } catch { /* unknown, then */ }
+ }
+ const width = video.videoWidth, height = video.videoHeight
+ let poster = null
+ try {
+ await video.play().catch(() => {})
+ video.pause()
+ const at = Number.isFinite(duration) && duration > 0 ? Math.min(0.5, duration / 2) : 0.1
+ video.currentTime = at
+ await once(video, 'seeked', 3000)
+ if (width && height) poster = await encode({ source: video, width, height }, POSTER_EDGE, 0.8, { doc })
+ } catch { poster = null }
+ return { width, height, duration, poster }
+ } catch {
+ return null
+ } finally {
+ try { video.pause() } catch { /* never played */ }
+ video.removeAttribute('src')
+ try { video.load() } catch { /* nothing loaded */ }
+ URL.revokeObjectURL(url)
+ }
+}
+
+async function video(file, sniffed, limits, deps) {
+ if (file.size > limits.videoMB * MB) throw new MediaError('too-large', { mb: limits.videoMB })
+ let bytes = new Uint8Array(await file.arrayBuffer())
+ let info = null
+ let mime = sniffed.mime
+ if (mime === 'video/webm') {
+ info = inspectWebm(bytes)
+ if (!info) throw new MediaError('unreadable')
+ } else {
+ info = inspectMp4(bytes)
+ if (!info) throw new MediaError('unreadable')
+ // The same rule as the server: a length it says is checked, an unknown one passes.
+ if (info.durationSec != null && info.durationSec > limits.videoSec + 1) throw new MediaError('too-long', { sec: limits.videoSec })
+ try { bytes = scrubMp4(bytes) } catch { throw new MediaError('unreadable') }
+ mime = info.brand === 'qt ' ? 'video/quicktime' : 'video/mp4'
+ }
+ const blob = new Blob([bytes], { type: mime })
+ bytes = null
+ const probe = await deps.probeVideo(blob, mime === 'video/quicktime' ? deps.playType(mime) : mime, deps)
+ let dur = info.durationSec > 0 ? info.durationSec : (probe && Number.isFinite(probe.duration) && probe.duration > 0 ? probe.duration : null)
+ if (dur != null && dur > limits.videoSec + 1) throw new MediaError('too-long', { sec: limits.videoSec })
+ const width = info.width || probe?.width || 0
+ const height = info.height || probe?.height || 0
+ if (!width || !height) throw new MediaError('unreadable')
+ const codec = info.codec || 'other'
+ const warn = !probe || mime === 'video/webm' || codec !== 'avc1'
+ return {
+ kind: 'video',
+ main: { blob, mime, width, height },
+ poster: probe?.poster || null,
+ dur: dur != null ? round1(dur) : null,
+ codec,
+ warnings: warn ? [WARN_CODEC] : []
+ }
+}
+
+/* ---------------------------------------------------------------- the whole ingest */
+
+const DEFAULT_DEPS = { decodeImage, encodeImage, probeVideo, playType: m => playType(m) }
+
+/**
+ * A picked File → { media, blobs: [{ hash, blob, mime }], warnings }. `media` is a MediaRef that
+ * passes normalizeMediaRef; `blobs` are the main file and its poster, to go into the local store
+ * as pending. Throws MediaError. `deps` swaps the browser parts (decoding, encoding, the probe)
+ * for the tests.
+ */
+export async function ingestMediaFile(file, limits = DEFAULT_LIMITS, deps = {}) {
+ const d = { ...DEFAULT_DEPS, ...deps }
+ const lim = { ...DEFAULT_LIMITS, ...limits }
+ const head = new Uint8Array(await file.slice(0, 64).arrayBuffer())
+ const sniffed = sniffKind(head)
+ if (!sniffed) throw new MediaError('type')
+ const out = sniffed.kind === 'video' ? await video(file, sniffed, lim, d)
+ : sniffed.kind === 'gif' ? await gif(file, lim, d)
+ : await photo(file, sniffed, lim, d)
+ const blobs = []
+ const withHash = async part => {
+ const hash = await sha256Hex(part.blob)
+ if (!blobs.some(b => b.hash === hash)) blobs.push({ hash, blob: part.blob, mime: part.mime })
+ return hash
+ }
+ const ref = {
+ kind: out.kind,
+ hash: await withHash(out.main),
+ mime: out.main.mime,
+ size: out.main.blob.size,
+ width: out.main.width,
+ height: out.main.height,
+ at: Date.now()
+ }
+ if (out.dur != null) ref.dur = out.dur
+ if (out.codec) ref.codec = out.codec
+ if (out.poster) {
+ ref.poster = { hash: await withHash(out.poster), mime: out.poster.mime, size: out.poster.blob.size, width: out.poster.width, height: out.poster.height }
+ }
+ const media = normalizeMediaRef(ref)
+ if (!media) throw new MediaError('unreadable')
+ return { media, blobs, warnings: out.warnings || [] }
+}
diff --git a/frontend/src/lib/media-ingest.test.js b/frontend/src/lib/media-ingest.test.js
new file mode 100644
index 000000000..bd56ca0a5
--- /dev/null
+++ b/frontend/src/lib/media-ingest.test.js
@@ -0,0 +1,163 @@
+// @vitest-environment happy-dom
+// The ingest's own decisions, with the browser parts (decoding, canvas encoding, the <video>
+// probe) swapped for stand-ins: which path a file takes, what is refused and why, what the ref
+// says, and that what goes into the store is the scrubbed file under its own hash.
+import { describe, it, expect, vi } from 'vitest'
+import { ingestMediaFile } from './media-ingest.js'
+import { sha256Hex } from './sha256.js'
+import { bytes, latin1, fill, jpeg, png, gif, gce, frame, comment, appExt, box, mp4, webm } from './media-samples.test-util.js'
+
+const MB = 1024 * 1024
+const LIMITS = { imageMB: 2, rawPhotoMB: 40, gifMB: 8, videoMB: 40, videoSec: 60 }
+const webpBlob = (n = 100) => new Blob([bytes('RIFF', [0, 0, 0, 0], 'WEBP', 'VP8 ', fill(n))], { type: 'image/webp' })
+const has = async (blob, needle) => {
+ const hay = new Uint8Array(await blob.arrayBuffer())
+ const n = latin1(needle)
+ outer: for (let i = 0; i + n.length <= hay.length; i++) { for (let k = 0; k < n.length; k++) if (hay[i + k] !== n[k]) continue outer; return true }
+ return false
+}
+function deps(over = {}) {
+ return {
+ decodeImage: vi.fn(async (blob, mime) => ({ source: {}, width: 4032, height: 3024, close: vi.fn() })),
+ encodeImage: vi.fn(async (pic, edge) => {
+ const scale = Math.min(1, edge / Math.max(pic.width, pic.height))
+ return { blob: webpBlob(edge), mime: 'image/webp', width: Math.round(pic.width * scale), height: Math.round(pic.height * scale) }
+ }),
+ probeVideo: vi.fn(async () => ({ width: 1920, height: 1080, duration: 12.5, poster: { blob: webpBlob(7), mime: 'image/webp', width: 480, height: 270 } })),
+ playType: m => (m === 'video/quicktime' ? 'video/mp4' : m),
+ ...over
+ }
+}
+const file = (b, name = 'file') => new File([b], name)
+
+describe('photos', () => {
+ it('re-encodes to at most 1600 px plus a 480 px poster, and keeps neither the file nor its name', async () => {
+ const d = deps()
+ const out = await ingestMediaFile(file(jpeg(4032, 3024), 'IMG_0001.JPG'), LIMITS, d)
+ expect(d.encodeImage.mock.calls.map(c => c[1])).toEqual([1600, 480])
+ expect(out.media).toMatchObject({ kind: 'image', mime: 'image/webp', width: 1600, height: 1200, poster: { mime: 'image/webp', width: 480, height: 360 } })
+ expect(out.blobs).toHaveLength(2)
+ expect(out.media.hash).toBe(await sha256Hex(out.blobs[0].blob))
+ expect(out.media.poster.hash).toBe(await sha256Hex(out.blobs[1].blob))
+ expect(JSON.stringify(out.media)).not.toContain('IMG_0001')
+ expect(out.warnings).toEqual([])
+ })
+
+ it('refuses a photo over 52 megapixels on its header, before decoding it', async () => {
+ const d = deps()
+ await expect(ingestMediaFile(file(jpeg(9000, 7000)), LIMITS, d)).rejects.toMatchObject({ code: 'photo-too-big' })
+ expect(d.decodeImage).not.toHaveBeenCalled()
+ })
+
+ it('refuses a raw photo over its cap, and steps the quality down before refusing an encoded one', async () => {
+ await expect(ingestMediaFile(file(bytes(jpeg(), fill(41 * MB))), LIMITS, deps())).rejects.toMatchObject({ code: 'too-large', mb: 40 })
+ const d = deps({ encodeImage: vi.fn(async (pic, edge) => ({ blob: new Blob([new Uint8Array(3 * MB)]), mime: 'image/webp', width: edge, height: edge })) })
+ await expect(ingestMediaFile(file(png()), LIMITS, d)).rejects.toMatchObject({ code: 'too-large', mb: 2 })
+ expect(d.encodeImage.mock.calls.length).toBe(4)
+ })
+
+ it('reads a HEIC as a photo to re-encode', async () => {
+ const d = deps()
+ const heic = bytes(box('ftyp', 'heic', [0, 0, 0, 0], 'mif1heic'), fill(100))
+ const out = await ingestMediaFile(file(heic), LIMITS, d)
+ expect(d.decodeImage.mock.calls[0][1]).toBe('image/heic')
+ expect(out.media.mime).toBe('image/webp')
+ })
+
+ it('refuses what is not a photo, a GIF or a video, whatever it is called', async () => {
+ await expect(ingestMediaFile(file(latin1('<svg onload="alert(1)"/>'), 'x.jpg'), LIMITS, deps())).rejects.toMatchObject({ code: 'type' })
+ await expect(ingestMediaFile(file(latin1('%PDF-1.7'), 'x.mp4'), LIMITS, deps())).rejects.toMatchObject({ code: 'type' })
+ })
+
+ it('says so when this browser cannot decode it', async () => {
+ const d = deps({ decodeImage: vi.fn(async () => { throw Object.assign(new Error('x'), { code: 'unreadable' }) }) })
+ await expect(ingestMediaFile(file(png()), LIMITS, d)).rejects.toMatchObject({ code: 'unreadable' })
+ })
+})
+
+describe('GIFs', () => {
+ it('keeps the animation without its comment, with a poster and a length', async () => {
+ const d = deps({ decodeImage: vi.fn(async () => ({ source: {}, width: 40, height: 30, close: vi.fn() })) })
+ const g = gif({ w: 40, h: 30, blocks: [appExt('NETSCAPE2.0', bytes([1, 0, 0])), comment('made at home'), gce(50), frame(40, 30), gce(70), frame(40, 30)] })
+ const out = await ingestMediaFile(file(g), LIMITS, d)
+ expect(out.media).toMatchObject({ kind: 'gif', mime: 'image/gif', width: 40, height: 30, dur: 1.2 })
+ expect(await has(out.blobs[0].blob, 'made at home')).toBe(false)
+ expect(await has(out.blobs[0].blob, 'NETSCAPE2.0')).toBe(true)
+ expect(out.media.poster.mime).toBe('image/webp')
+ })
+
+ it('a GIF of one frame is a photo', async () => {
+ const d = deps({ decodeImage: vi.fn(async () => ({ source: {}, width: 40, height: 30, close: vi.fn() })) })
+ const out = await ingestMediaFile(file(gif({ delays: [10] })), LIMITS, d)
+ expect(out.media).toMatchObject({ kind: 'image', mime: 'image/webp' })
+ })
+
+ it('refuses one over the GIF cap', async () => {
+ await expect(ingestMediaFile(file(bytes(gif(), fill(9 * MB))), LIMITS, deps())).rejects.toMatchObject({ code: 'too-large', mb: 8 })
+ })
+})
+
+describe('videos', () => {
+ const withGps = (over = {}) => mp4({
+ tracks: [{ handler: 'vide', fourcc: 'avc1', w: 1920, h: 1080, payload: fill(64, 0x77) }, { handler: 'meta', fourcc: 'gpmd', payload: latin1('+47.37+008.54/') }],
+ moovExtra: [box('udta', box('\xa9xyz', latin1('+47.37+008.54/')))],
+ ...over
+ }).file
+
+ it('an MP4 is stored scrubbed, under the hash of what is stored, with length, size, codec and poster', async () => {
+ const d = deps()
+ const out = await ingestMediaFile(file(withGps({ seconds: 12.5 })), LIMITS, d)
+ expect(out.media).toMatchObject({ kind: 'video', mime: 'video/mp4', width: 1920, height: 1080, dur: 12.5, codec: 'avc1', poster: { width: 480, height: 270 } })
+ const stored = out.blobs[0].blob
+ expect(await has(stored, '47.37')).toBe(false)
+ expect(out.media.hash).toBe(await sha256Hex(stored))
+ expect(out.warnings).toEqual([])
+ })
+
+ it('a MOV stays a MOV, and is probed as something this browser plays', async () => {
+ const d = deps()
+ const out = await ingestMediaFile(file(withGps({ brand: 'qt ' })), LIMITS, d)
+ expect(out.media.mime).toBe('video/quicktime')
+ expect(d.probeVideo.mock.calls[0][1]).toBe('video/mp4')
+ })
+
+ it('refuses one longer than the cap, one bigger than the cap, and one that does not parse', async () => {
+ await expect(ingestMediaFile(file(withGps({ seconds: 75 })), LIMITS, deps())).rejects.toMatchObject({ code: 'too-long', sec: 60 })
+ await expect(ingestMediaFile(file(withGps({ seconds: 61 })), LIMITS, deps())).resolves.toBeTruthy() // the server's +1 s
+ await expect(ingestMediaFile(file(bytes(withGps(), fill(41 * MB))), LIMITS, deps())).rejects.toMatchObject({ code: 'too-large', mb: 40 })
+ const broken = withGps()
+ await expect(ingestMediaFile(file(broken.subarray(0, broken.length - 20)), LIMITS, deps())).rejects.toMatchObject({ code: 'unreadable' })
+ })
+
+ it('HEVC is kept with the warning that it may not play everywhere', async () => {
+ const hevc = mp4({ tracks: [{ handler: 'vide', fourcc: 'hvc1', w: 1920, h: 1080, payload: fill(10) }] }).file
+ const out = await ingestMediaFile(file(hevc), LIMITS, deps())
+ expect(out.media.codec).toBe('hvc1')
+ expect(out.warnings).toEqual(['codec'])
+ })
+
+ it('a video this browser cannot play is kept, without a poster, with the warning', async () => {
+ const out = await ingestMediaFile(file(withGps()), LIMITS, deps({ probeVideo: vi.fn(async () => null) }))
+ expect(out.media.poster).toBeUndefined()
+ expect(out.blobs).toHaveLength(1)
+ expect(out.warnings).toEqual(['codec'])
+ })
+
+ it('a WebM is kept as it is, its size and codec read from its header, always with the warning', async () => {
+ const w = webm({ w: 1280, h: 720, codec: 'V_VP9', durationMs: 5000 })
+ const out = await ingestMediaFile(file(w), LIMITS, deps({ probeVideo: vi.fn(async () => ({ width: 0, height: 0, duration: NaN, poster: null })) }))
+ expect(out.media).toMatchObject({ kind: 'video', mime: 'video/webm', width: 1280, height: 720, codec: 'vp9', dur: 5 })
+ expect(out.media.hash).toBe(await sha256Hex(w))
+ expect(out.warnings).toEqual(['codec'])
+ })
+
+ it('a length the file does not state comes from the probe, and is checked the same', async () => {
+ const w = webm({ durationMs: null })
+ const out = await ingestMediaFile(file(w), LIMITS, deps())
+ expect(out.media.dur).toBe(12.5)
+ await expect(ingestMediaFile(file(w), LIMITS, deps({ probeVideo: vi.fn(async () => ({ width: 640, height: 360, duration: 90, poster: null })) })))
+ .rejects.toMatchObject({ code: 'too-long' })
+ const unknown = await ingestMediaFile(file(w), LIMITS, deps({ probeVideo: vi.fn(async () => ({ width: 640, height: 360, duration: Infinity, poster: null })) }))
+ expect(unknown.media.dur).toBeUndefined()
+ })
+})
diff --git a/frontend/src/sheets.custom-media.test.jsx b/frontend/src/sheets.custom-media.test.jsx
new file mode 100644
index 000000000..67dfa8c61
--- /dev/null
+++ b/frontend/src/sheets.custom-media.test.jsx
@@ -0,0 +1,173 @@
+// @vitest-environment happy-dom
+// The photo, GIF or video of a custom exercise, and its link, in the create/edit form: a picked
+// file becomes a MediaRef in the draft (the ingest itself is lib/media-ingest.js, mocked here —
+// its parts have their own tests), Save writes the ref and the cleaned link, Remove takes the
+// ref off, a link that is not a web address stops the save, and an edit that leaves the media
+// alone keeps it.
+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 { registerCustom } from './lib/exercises.js'
+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 { customExSheet } from './sheets.jsx'
+
+bindUI(useUI)
+
+const mounted = []
+const S = () => useStore.getState().S
+const HASH = 'a'.repeat(64)
+const POSTER = 'b'.repeat(64)
+const REF = { kind: 'image', hash: HASH, mime: 'image/webp', size: 204800, width: 1600, height: 1200, poster: { hash: POSTER, mime: 'image/webp', size: 20480, width: 480, height: 360 }, at: 1727000000000 }
+
+function renderTop() {
+ const sheet = useUI.getState().sheets.at(-1)
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push(root)
+ act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id))))
+ return host
+}
+function type(el, value) {
+ Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
+ el.dispatchEvent(new Event('input', { bubbles: true }))
+}
+const click = (host, sel, text) => {
+ const el = [...host.querySelectorAll(sel)].find(e => e.textContent.trim() === text)
+ if (!el) throw new Error(`nothing with text "${text}"`)
+ act(() => el.click())
+}
+const settle = async () => { for (let i = 0; i < 6; i++) await act(async () => { await new Promise(r => setTimeout(r, 0)) }) }
+// The picked file goes through a dynamic import of the ingest; a busy run needs more than a
+// fixed number of ticks, so this waits for the form to stop being busy.
+async function pick(form, file = new File(['x'], 'IMG_0042.HEIC', { type: 'image/heic' })) {
+ const input = form.querySelector('input[type="file"]')
+ Object.defineProperty(input, 'files', { value: [file], configurable: true })
+ act(() => { input.dispatchEvent(new Event('change', { bubbles: true })) })
+ const end = Date.now() + 4000
+ const busy = () => form.textContent.includes('Loading…') || !h.ingest.mock.calls.length
+ while (busy() && Date.now() < end) await act(async () => { await new Promise(r => setTimeout(r, 10)) })
+ await settle()
+}
+const custom = (over = {}) => ({ id: 'cm1', n: 'Sandbag carry', bp: 'back', eq: 'barbell', custom: true, desc: '', tg: '', sm: [], primaries: [], secondaries: [], muscleGroups: [], ...over })
+function seed(ex) {
+ useStore.setState(s => ({ S: { ...s.S, customEx: [ex] } }))
+ registerCustom([ex])
+}
+
+let media
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ useUI.setState({ sheets: [], toastMsg: '' })
+ useStore.setState({ S: structuredClone(DEF), user: null, config: null })
+ registerCustom([])
+ _setLangState('en', null, null, null)
+ document.body.innerHTML = ''
+ media = createMediaStore({ ...memoryBackend(), persistent: true, name: 'test' }, { objectURL: { createObjectURL: () => 'blob:t/1', revokeObjectURL() {} } })
+ _setMediaStore(media)
+ h.ingest = vi.fn(async () => ({
+ media: REF,
+ blobs: [{ hash: HASH, blob: new Blob(['main']), mime: 'image/webp' }, { hash: POSTER, blob: new Blob(['poster']), mime: 'image/webp' }],
+ warnings: []
+ }))
+})
+afterEach(() => {
+ act(() => { mounted.splice(0).forEach(root => root.unmount()) })
+ _setMediaStore(null)
+ registerCustom([])
+})
+
+describe('custom exercise photo, GIF or video, and link', () => {
+ it('asks for images and videos, nothing more specific', () => {
+ customExSheet(null)
+ const form = renderTop()
+ expect(form.querySelector('input[type="file"]').getAttribute('accept')).toBe('image/*,video/*')
+ })
+
+ it('a picked file shows in the form, and Create saves its ref and the cleaned link — never the file name', async () => {
+ customExSheet(null)
+ const form = renderTop()
+ act(() => type(form.querySelector('input.input'), 'Sandbag carry'))
+ click(form, '.chip', 'back')
+ click(form, '.chip', 'barbell')
+ await pick(form)
+ expect(h.ingest).toHaveBeenCalledTimes(1)
+ expect(form.querySelector('.cmf-thumb')).toBeTruthy()
+ expect(form.textContent).toContain('0.2 MB')
+ expect(form.textContent).toContain('Change')
+ // The files are in the local store, waiting for the server, before the form is even saved.
+ expect([...media.pendingNow()].sort()).toEqual([HASH, POSTER])
+ act(() => type(form.querySelector('input[type="url"]'), ' youtu.be/dQw4w9WgXcQ '))
+ click(form, 'button', 'Create exercise')
+ const c = S().customEx.find(x => x.n === 'Sandbag carry')
+ expect(c.media).toEqual(REF)
+ expect(c.url).toBe('https://youtu.be/dQw4w9WgXcQ')
+ expect(JSON.stringify(S())).not.toContain('IMG_0042')
+ })
+
+ it('Remove takes the photo off on save', async () => {
+ seed(custom({ media: REF }))
+ customExSheet(S().customEx[0])
+ const form = renderTop()
+ await settle()
+ act(() => { form.querySelector('button[aria-label="Remove"]').click() })
+ expect(form.querySelector('.cmf-thumb')).toBeNull()
+ click(form, 'button', 'Save')
+ expect(S().customEx[0].media).toBeUndefined()
+ })
+
+ it('a link that is not a web address says so and saves nothing', () => {
+ seed(custom({ url: 'https://exrx.net/a' }))
+ customExSheet(S().customEx[0])
+ const form = renderTop()
+ act(() => type(form.querySelector('input[type="url"]'), 'javascript:alert(1)'))
+ click(form, 'button', 'Save')
+ expect(useUI.getState().toastMsg).toBe('That link is not a web address')
+ expect(S().customEx[0].url).toBe('https://exrx.net/a')
+ expect(useUI.getState().sheets).toHaveLength(1) // the form stays open with the edit
+ })
+
+ it('an edit that leaves the media alone keeps it; an empty link field removes the link', () => {
+ seed(custom({ media: REF, url: 'https://exrx.net/a' }))
+ customExSheet(S().customEx[0])
+ const form = renderTop()
+ act(() => type(form.querySelector('input.input'), 'Sandbag carry, heavy'))
+ act(() => type(form.querySelector('input[type="url"]'), ''))
+ click(form, 'button', 'Save')
+ expect(S().customEx[0]).toMatchObject({ n: 'Sandbag carry, heavy', media: REF })
+ expect(S().customEx[0].url).toBeUndefined()
+ })
+
+ it('a refused file becomes the sentence for it, and the draft stays as it was', async () => {
+ h.ingest = vi.fn(async () => { throw Object.assign(new Error('too-large'), { code: 'too-large', mb: 40 }) })
+ customExSheet(null)
+ const form = renderTop()
+ await pick(form)
+ expect(useUI.getState().toastMsg).toBe('That file is too large — up to 40 MB.')
+ expect(form.querySelector('.cmf-thumb')).toBeNull()
+ })
+
+ it('says a guest keeps it on this device only, and hides Add on a server that stores no media', async () => {
+ customExSheet(null)
+ let form = renderTop()
+ await settle()
+ expect(form.textContent).toContain('Kept on this device only')
+ act(() => { mounted.splice(0).forEach(root => root.unmount()) })
+ useUI.setState({ sheets: [] })
+ useStore.setState({ user: { id: 'u1', name: 'A' }, config: { invite_only: false } })
+ customExSheet(null)
+ form = renderTop()
+ await settle()
+ expect(form.textContent).toContain('Your server does not store photos and videos yet.')
+ expect([...form.querySelectorAll('button')].some(b => b.textContent.trim() === 'Add')).toBe(false)
+ expect(form.querySelector('input[type="url"]')).toBeTruthy() // the link still works
+ })
+})
diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx
index dbf65a836..304f99160 100644
--- a/frontend/src/sheets.jsx
+++ b/frontend/src/sheets.jsx
@@ -13,6 +13,9 @@ import { t, dateLocale, instrFor, exerciseNameFor, exerciseNameClass, getLang, I
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 { mediaOf, normalizeMediaRef, cleanUrl } from './lib/media-refs.js'
+import { syncMedia } from './lib/media-sync.js'
import LineChart from './components/LineChart.jsx'
import Stepper from './components/Stepper.jsx'
import Icon from './components/Icon.jsx'
@@ -909,7 +912,9 @@ export const addToRoutineSheet = ex => ui().openSheet(close => <AddToRoutine ex=
/* ============================ custom exercises (issue #11) ============================ */
// Name + body part is all it takes — the exercise then behaves like any built-in one
-// (planning, logging, PRs, stats), just without an animation.
+// (planning, logging, PRs, stats). A photo, GIF or video of your own, and a link to a video or
+// guide, are optional (components/CustomMediaField.jsx): the state keeps a small reference to the
+// file, never the file itself, and the link is cleaned on save and again whenever it is opened.
function CustomExForm({ existing, prefill, onDone, close }) {
const nameRef = useRef(null)
const onNameFocus = useSheetKeyboard(nameRef)
@@ -917,6 +922,12 @@ function CustomExForm({ existing, prefill, onDone, close }) {
const [bp, setBp] = useState(existing ? existing.bp : '')
const [eq, setEq] = useState(existing ? (existing.eq || '') : '')
const [desc, setDesc] = useState(existing ? (existing.desc || '') : '')
+ const [media, setMedia] = useState(() => mediaOf(existing))
+ const [url, setUrl] = useState(existing && typeof existing.url === 'string' ? existing.url : '')
+ const onMedia = patch => {
+ if ('media' in patch) setMedia(patch.media)
+ if ('url' in patch) setUrl(patch.url)
+ }
const [primaries, setPrimaries] = useState(() => {
if (existing && Array.isArray(existing.primaries) && existing.primaries.length) return [...existing.primaries]
if (existing?.bp === 'cardio') return ['cardiovascular system']
@@ -946,6 +957,10 @@ function CustomExForm({ existing, prefill, onDone, close }) {
const dup = allExercises(S()).find(e => e.n.toLowerCase() === name.toLowerCase() && e.id !== (existing || {}).id)
if (dup) { toast(t('“{0}” already exists', dup.n)); return }
const d = desc.trim().slice(0, 1000)
+ // An empty field removes the link; anything else has to be a web address.
+ const link = url.trim() ? cleanUrl(url) : null
+ if (url.trim() && !link) { toast(t('That link is not a web address')); return }
+ const ref = normalizeMediaRef(media)
// Stored in the map's order, not the order the chips were tapped in — the tags on the exercise
// used to shuffle with every edit.
const prim = bp === 'cardio' ? ['cardiovascular system'] : inMuscleOrder(primaries)
@@ -959,20 +974,28 @@ function CustomExForm({ existing, prefill, onDone, close }) {
// for the user who drops the target and adds nothing in its place.
const tg = (existing && prim.includes(existing.tg)) ? existing.tg : (primaryTaps.find(m => prim.includes(m)) || prim[0] || '')
let id = existing && existing.id
+ const extra = c => {
+ if (ref) c.media = ref; else delete c.media
+ if (link) c.url = link; else delete c.url
+ }
if (existing) update(s => { const c = (s.customEx || []).find(x => x.id === id); if (c) {
c.n = name; c.bp = bp; c.desc = d; c.tg = tg; c.sm = sm; c.muscleGroups = groups; c.primaries = prim; c.secondaries = sm; c.eq = eq
+ extra(c)
} })
else {
id = 'c' + uid()
- update(s => { (s.customEx = s.customEx || []).push({ id, n: name, bp, desc: d, tg, sm, muscleGroups: groups, primaries: prim, secondaries: sm, eq, custom: true }) })
+ update(s => { const c = { id, n: name, bp, desc: d, tg, sm, muscleGroups: groups, primaries: prim, secondaries: sm, eq, custom: true }; extra(c); (s.customEx = s.customEx || []).push(c) })
}
+ // The file goes to the server now rather than after the state's own debounce: another device
+ // that sees the reference first shows a tile until it arrives.
+ if (ref) syncMedia({ force: true })
close()
toast(existing ? t('Saved') : t('“{0}” created', name))
onDone && onDone(EXIDX[id])
}
return <>
<h3>{existing ? t('Edit custom exercise') : t('Create your own exercise')}</h3>
- <div className="muted small" style={{ marginBottom: 12 }}>{t('Name it and pick a body part — it behaves like any other exercise, just without an animation.')}</div>
+ <div className="muted small" style={{ marginBottom: 12 }}>{t('Name it and pick a body part — it behaves like any other exercise.')}</div>
<input ref={nameRef} className="input" placeholder={t('Exercise name')} value={n} onFocus={onNameFocus} onChange={e => setN(e.target.value)} />
<div className="chips" style={{ margin: '12px 0' }}>
{BODYPARTS.map(b => <button key={b} className={'chip' + (bp === b ? ' on' : '')} onClick={() => setBp(b)}>{t(b)}</button>)}
@@ -994,6 +1017,7 @@ function CustomExForm({ existing, prefill, onDone, close }) {
{bp === 'cardio' && <div className="small dim row" style={{ marginBottom: 10, gap: 5 }}><Icon name="figureRun" style={{ fontSize: 13 }} />{t('Cardio exercises log time + speed instead of weight × reps.')}</div>}
<textarea className="input" rows={4} maxLength={1000} placeholder={t('Description (optional) — setup, cues, anything you want to remember')}
value={desc} onChange={e => setDesc(e.target.value)} />
+ <CustomMediaField media={media} url={url} onChange={onMedia} />
<div style={{ height: 14 }} />
<Button variant="primary" onClick={save}>{existing ? t('Save') : t('Create exercise')}</Button>
{existing && <><div style={{ height: 8 }} /><Button variant="danger" icon="trash" onClick={() => { close(); deleteCustomEx(existing) }}>{t('Delete exercise')}</Button></>}
@@ -1105,7 +1129,7 @@ function ExercisePicker({ onPick, title, close }) {
<div className="list">
{!special && <div className="item" {...tappable(() => customExSheet(null, ex => onPick(ex), q.trim()))}>
<div className="thumb thumb-x"><Icon name="sparkles" /></div>
- <div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, no animation')}</div></div><Icon name="plus" className="chev" />
+ <div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, and a photo or video if you like')}</div></div><Icon name="plus" className="chev" />
</div>}
{f.slice(0, shown).map(e => <div key={e.id} className="item" {...tappable(() => onPick(e))}>
<Thumb ex={e} /><div className="grow"><div className={`tt ${exerciseNameClass(e)}`}>{isFav(st, e.id) && <Icon name="starFill" className="fav-star" />}{exerciseNameFor(e)}</div><div className="ss capitalize">{t(MUSCLE_NAME[e.tg] || e.tg || e.bp)} · {t(e.eq)}</div></div>
diff --git a/frontend/src/views/Library.jsx b/frontend/src/views/Library.jsx
index 16726888f..d6608895a 100644
--- a/frontend/src/views/Library.jsx
+++ b/frontend/src/views/Library.jsx
@@ -65,7 +65,7 @@ export default function Library() {
<div className="list">
<div className="item" {...tappable(() => customExSheet(null, ex => exerciseDetailSheet(ex), q.trim()))}>
<div className="thumb thumb-x"><Icon name="sparkles" /></div>
- <div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, no animation')}</div></div><Icon name="plus" className="chev" />
+ <div className="grow"><div className="tt">{t('Create your own exercise')}</div><div className="ss">{t('name + body part, and a photo or video if you like')}</div></div><Icon name="plus" className="chev" />
</div>
{f.slice(0, shown).map(e => {
const best = bestWeightFor(S, e.id)