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.

Offline media: only the app installed on the home screen fetches the plan's exercise media ahead, never on a cellular or Data Saver connection; a browser tab keeps what it has shown (#281)

Duarte Santoscd56813fe9b9
diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.md
index 5a0079346..7276dbcc4 100644
--- a/docs/SELF_HOSTING.md
+++ b/docs/SELF_HOSTING.md
@@ -546,7 +546,7 @@ browser (see section 2).
| The app says "Your server answered with an error (HTTP …)" | The code is what the server or its proxy sent: 502/504 usually means the API container is down or unreachable from `web`, 413 that the proxy's upload limit is too small. Changes stay on the device and go through once the server answers. |
| `docker compose pull` fails with "denied" / "unauthorized" | The prebuilt images aren't published yet, or need to be, or the GHCR package is still private — build from source instead (`docker compose up -d --build`). |
| Exercise images/GIFs blank when a routine is open | Fixed in current images (issue #79). On an older build, see the note below. |
-| An exercise shows a plain tile instead of its animation when offline | The installed web app keeps the media of every exercise in your plan and your current workout, fetched in the background once the app has settled (not on a cellular or Data Saver connection, where the browser says so), plus everything it has shown you, up to 150 MB, across updates. An exercise outside your plan that was never shown while online has nothing to show offline. The phone app loads media from a CDN and is not covered by this. |
+| An exercise shows a plain tile instead of its animation when offline | The web app installed on the home screen keeps the media of every exercise in your plan and your current workout, fetched in the background once the app has settled (not on a cellular or Data Saver connection, where the browser says so), plus everything it has shown you, up to 150 MB, across updates. In an ordinary browser tab nothing is fetched ahead: only what it has shown you is kept. An exercise outside your plan that was never shown while online has nothing to show offline. The phone app loads media from a CDN and is not covered by this. |
### `VITE_IMG_BASE` / `VITE_GIF_BASE` are build-time, not run-time
diff --git a/frontend/public/sw.js b/frontend/public/sw.js
index e99797aaf..1e9afa156 100644
--- a/frontend/public/sw.js
+++ b/frontend/public/sw.js
@@ -16,8 +16,10 @@ const CACHE = 'opengym-rt-__BUILD__'
order they were written, so a hit is written back once per worker lifetime to move it to the
end: least recently used as far as this worker has seen, which is what "LRU-ish" means here.
The whole catalogue is about 140 MB, so the cap only bites for someone who has browsed most of
- it. lib/media-prefetch.js fills this cache for the exercises in the plan and names it too, so
- a new name has to change there as well (sw-media.test.js pins the two together). */
+ it. lib/media-prefetch.js fills this cache ahead for the exercises in the plan — in the app
+ installed on the home screen only; a browser tab gets what it has shown and nothing more — and
+ names it too, so a new name has to change there as well (sw-media.test.js pins the two
+ together). */
const MEDIA = 'opengym-media-v1'
const MEDIA_MAX_BYTES = 150 * 1024 * 1024
const MEDIA_MAX_ITEMS = 3000
diff --git a/frontend/src/lib/media-prefetch.js b/frontend/src/lib/media-prefetch.js
index 372e31a4b..6ed148fd7 100644
--- a/frontend/src/lib/media-prefetch.js
+++ b/frontend/src/lib/media-prefetch.js
@@ -8,9 +8,14 @@
// it. URLs already in the cache are skipped, so after the first run this is a cache lookup per
// exercise and no traffic.
//
-// It stays off the network when the browser says data costs something: Data Saver, a cellular
-// connection, or a 2G-class one. Safari and Firefox say nothing about the connection, and there it
-// runs; the set is bounded by the plan (a few MB for a typical one) and each file goes once.
+// Only in the app installed on the home screen (installedApp). That is where a workout gets
+// opened in a gym basement with no signal; a browser tab is someone looking at the app, and
+// fetching a few megabytes of animations behind their back is not what they opened it for. A tab
+// keeps the worker's ordinary on-demand cache: whatever it has shown stays available offline.
+//
+// And never when the browser says data costs something: Data Saver, a cellular connection, or a
+// 2G-class one. Safari and Firefox say nothing about the connection, and there it runs; the set is
+// bounded by the plan (a few MB for a typical one) and each file goes once.
//
// Not in the phone app: it has no service worker, and its media comes from the CDN.
import { EXIDX, imgSrc, gifSrc } from './exercises.js'
@@ -47,6 +52,19 @@ export function planMediaUrls(S, base = globalThis.location?.href, index = EXIDX
return [...urls]
}
+const STANDALONE = '(display-mode: standalone)'
+
+/**
+ * Whether this page runs as the app installed on the home screen, not in a browser tab: the
+ * display mode the manifest asks for (`standalone`), or iOS Safari's own flag, which a home-screen
+ * app there has had since before it knew display modes. `win.matchMedia` is called on `win` —
+ * a detached matchMedia throws in a browser.
+ */
+export function installedApp(win = globalThis, nav = win?.navigator) {
+ if (nav?.standalone === true) return true
+ try { return !!win?.matchMedia?.(STANDALONE)?.matches } catch { return false }
+}
+
/** Whether the connection is one to spend a few megabytes on without asking. */
export function prefetchAllowed(nav = globalThis.navigator) {
if (!nav || nav.onLine === false) return false
@@ -85,26 +103,29 @@ export async function prefetchMedia(urls, { cache, fetchImpl = globalThis.fetch,
}
/**
- * Keep the plan's media offline for as long as the page is open. `store` is the zustand store
- * (getState/subscribe). Returns a function that stops it.
+ * Keep the plan's media offline for as long as the page is open, while it runs as the installed
+ * app. `store` is the zustand store (getState/subscribe). Returns a function that stops it.
*/
-export function startMediaPrefetch(store, { delay = PREFETCH_DELAY_MS, nav = globalThis.navigator, cachesApi = globalThis.caches } = {}) {
+export function startMediaPrefetch(store, { delay = PREFETCH_DELAY_MS, win = globalThis, nav = win?.navigator, cachesApi = globalThis.caches } = {}) {
const sw = nav?.serviceWorker
if (!sw || !cachesApi) return () => {}
let timer = null
let running = false
// The URL set the last complete run covered; the same set again has nothing left to fetch.
let done = ''
+ // Asked on every run, and between files, not once at start: a desktop browser can move an open
+ // tab into the installed app's window (and back), and a phone can leave Wi-Fi mid-run.
+ const allowed = () => installedApp(win, nav) && prefetchAllowed(nav)
const run = async () => {
timer = null
// Only through a worker that is in charge of this page: without one nothing would be kept.
- if (running || !sw.controller || !prefetchAllowed(nav)) return
+ if (running || !sw.controller || !allowed()) return
const urls = planMediaUrls(store.getState().S)
const key = urls.join('\n')
if (!urls.length || key === done) return
running = true
try {
- const r = await prefetchMedia(urls, { cache: await cachesApi.open(MEDIA_CACHE), allowed: () => prefetchAllowed(nav) })
+ const r = await prefetchMedia(urls, { cache: await cachesApi.open(MEDIA_CACHE), allowed })
if (r.fetched === r.missing) done = key
} catch (e) { /* best effort: the next change or reconnect tries again */ }
finally { running = false }
@@ -123,13 +144,18 @@ export function startMediaPrefetch(store, { delay = PREFETCH_DELAY_MS, nav = glo
seen = S
schedule()
})
+ // A tab moved into the app's window becomes the installed app without a reload.
+ let mode = null
+ try { mode = win?.matchMedia?.(STANDALONE) || null } catch { /* no display modes to follow */ }
globalThis.addEventListener?.('online', schedule)
sw.addEventListener?.('controllerchange', schedule)
+ mode?.addEventListener?.('change', schedule)
schedule()
return () => {
unsubscribe()
if (timer) clearTimeout(timer)
globalThis.removeEventListener?.('online', schedule)
sw.removeEventListener?.('controllerchange', schedule)
+ mode?.removeEventListener?.('change', schedule)
}
}
diff --git a/frontend/src/lib/media-prefetch.test.js b/frontend/src/lib/media-prefetch.test.js
index a2af499a5..19deaba62 100644
--- a/frontend/src/lib/media-prefetch.test.js
+++ b/frontend/src/lib/media-prefetch.test.js
@@ -1,9 +1,10 @@
// @vitest-environment node
-/* The page's half of offline exercise media (#281): which URLs the plan needs, when the
- * connection is one to spend them on, and fetching only what the worker's cache is missing. */
+/* The page's half of offline exercise media (#281): which URLs the plan needs, that only the
+ * installed app fetches them ahead, when the connection is one to spend them on, and fetching
+ * only what the worker's cache is missing. */
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { planMediaUrls, prefetchAllowed, prefetchMedia, startMediaPrefetch, MEDIA_CACHE, PREFETCH_DELAY_MS } from './media-prefetch.js'
+import { planMediaUrls, prefetchAllowed, prefetchMedia, startMediaPrefetch, installedApp, MEDIA_CACHE, PREFETCH_DELAY_MS } from './media-prefetch.js'
import { EXIDX, imgSrc, gifSrc } from './exercises.js'
const BASE = 'https://gym.test/app/'
@@ -57,6 +58,39 @@ describe('prefetchAllowed', () => {
})
})
+// A window as far as installedApp looks at one: its display mode, and iOS's navigator.standalone.
+function fakeWindow({ standalone = false, iosStandalone, throws = false } = {}) {
+ const listeners = new Set()
+ const mql = { media: '(display-mode: standalone)', matches: standalone, addEventListener: (ev, fn) => listeners.add(fn), removeEventListener: (ev, fn) => listeners.delete(fn) }
+ const win = {
+ navigator: iosStandalone === undefined ? {} : { standalone: iosStandalone },
+ // Called as a method, the way a browser insists on (a detached matchMedia throws there).
+ matchMedia(q) {
+ if (this !== win) throw new TypeError('Illegal invocation')
+ if (throws) throw new Error('no display modes here')
+ return q === mql.media ? mql : { media: q, matches: false }
+ },
+ }
+ win.become = v => { mql.matches = v; listeners.forEach(fn => fn({ matches: v })) }
+ win.listeners = listeners
+ return win
+}
+
+describe('installedApp', () => {
+ it('is the home-screen app: standalone display mode, or iOS Safari’s own flag', () => {
+ expect(installedApp(fakeWindow({ standalone: true }))).toBe(true)
+ expect(installedApp(fakeWindow({ iosStandalone: true }))).toBe(true)
+ })
+
+ it('a browser tab is not, nor is a browser that knows no display modes', () => {
+ expect(installedApp(fakeWindow())).toBe(false)
+ expect(installedApp(fakeWindow({ iosStandalone: false }))).toBe(false)
+ expect(installedApp(fakeWindow({ throws: true }))).toBe(false)
+ expect(installedApp({ navigator: {} })).toBe(false)
+ expect(installedApp(undefined)).toBe(false)
+ })
+})
+
describe('prefetchMedia', () => {
it('fetches only what the cache is missing, and reads each answer to the end', async () => {
const read = vi.fn(async () => new ArrayBuffer(1))
@@ -86,25 +120,26 @@ describe('prefetchMedia', () => {
})
describe('startMediaPrefetch', () => {
- function setup({ controller = {}, S = { routines: [{ ex: [{ id: bench.id }] }] } } = {}) {
+ function setup({ controller = {}, S = { routines: [{ ex: [{ id: bench.id }] }] }, win = fakeWindow({ standalone: true }) } = {}) {
const listeners = new Set()
const store = { state: { S }, getState: () => store.state, subscribe: fn => { listeners.add(fn); return () => listeners.delete(fn) } }
store.set = S => { store.state = { S }; listeners.forEach(fn => fn(store.state)) }
const cached = []
const cachesApi = { open: vi.fn(async () => cacheWith(cached)) }
- const nav = { onLine: true, serviceWorker: { controller, addEventListener() {}, removeEventListener() {} } }
+ // The window's own navigator, as in a browser: iOS's `standalone` lives there.
+ const nav = Object.assign(win.navigator, { onLine: true, serviceWorker: { controller, addEventListener() {}, removeEventListener() {} } })
const fetchImpl = vi.fn(async u => { cached.push(u); return answer() })
vi.stubGlobal('fetch', fetchImpl)
vi.stubGlobal('location', { href: BASE })
- return { store, cachesApi, nav, fetchImpl, listeners }
+ return { store, cachesApi, nav, fetchImpl, listeners, win }
}
afterEach(() => { vi.unstubAllGlobals() })
const flush = async () => { for (let i = 0; i < 10; i++) await Promise.resolve() }
it('waits for the app to settle, fetches the plan\'s media through the worker, then only what a plan change adds', async () => {
vi.useFakeTimers()
- const { store, cachesApi, nav, fetchImpl } = setup()
- const stop = startMediaPrefetch(store, { nav, cachesApi })
+ const { store, cachesApi, nav, fetchImpl, win } = setup()
+ const stop = startMediaPrefetch(store, { win, nav, cachesApi })
expect(fetchImpl).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
await flush()
@@ -128,7 +163,7 @@ describe('startMediaPrefetch', () => {
it('does nothing without a worker in charge of the page, or on a connection that costs', async () => {
vi.useFakeTimers()
const a = setup({ controller: null })
- const stopA = startMediaPrefetch(a.store, { nav: a.nav, cachesApi: a.cachesApi })
+ const stopA = startMediaPrefetch(a.store, { win: a.win, nav: a.nav, cachesApi: a.cachesApi })
await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
await flush()
expect(a.fetchImpl).not.toHaveBeenCalled()
@@ -136,12 +171,74 @@ describe('startMediaPrefetch', () => {
const b = setup()
b.nav.connection = { saveData: true }
- const stop = startMediaPrefetch(b.store, { nav: b.nav, cachesApi: b.cachesApi })
+ const stop = startMediaPrefetch(b.store, { win: b.win, nav: b.nav, cachesApi: b.cachesApi })
await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
await flush()
expect(b.fetchImpl).not.toHaveBeenCalled()
stop()
- expect(startMediaPrefetch(b.store, { nav: {}, cachesApi: b.cachesApi })).toBeTypeOf('function')
+ expect(startMediaPrefetch(b.store, { win: b.win, nav: {}, cachesApi: b.cachesApi })).toBeTypeOf('function')
+ })
+
+ it('never on a cellular connection or with Data Saver, even in the installed app on iOS', async () => {
+ vi.useFakeTimers()
+ for (const connection of [{ type: 'cellular' }, { type: 'cellular', effectiveType: '4g', saveData: false }, { type: 'wifi', saveData: true }]) {
+ const c = setup({ win: fakeWindow({ iosStandalone: true }) })
+ c.nav.connection = connection
+ const stop = startMediaPrefetch(c.store, { win: c.win, nav: c.nav, cachesApi: c.cachesApi })
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ expect(c.fetchImpl, JSON.stringify(connection)).not.toHaveBeenCalled()
+ stop()
+ }
+ })
+
+ it('a browser tab fetches nothing ahead — not at start, not after a plan change', async () => {
+ vi.useFakeTimers()
+ const { store, cachesApi, nav, fetchImpl, win } = setup({ win: fakeWindow() })
+ const stop = startMediaPrefetch(store, { win, nav, cachesApi })
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ store.set({ routines: [{ ex: [{ id: bench.id }, { id: other.id }] }] })
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ expect(fetchImpl).not.toHaveBeenCalled()
+ expect(cachesApi.open).not.toHaveBeenCalled()
+ stop()
+ })
+
+ it('the installed app on iOS fetches ahead, and so does a tab once it is moved into the app window', async () => {
+ vi.useFakeTimers()
+ const ios = setup({ win: fakeWindow({ iosStandalone: true }) })
+ const stopIos = startMediaPrefetch(ios.store, { win: ios.win, nav: ios.nav, cachesApi: ios.cachesApi })
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ expect(ios.fetchImpl).toHaveBeenCalledTimes(2)
+ stopIos()
+
+ const tab = setup({ win: fakeWindow() })
+ const stop = startMediaPrefetch(tab.store, { win: tab.win, nav: tab.nav, cachesApi: tab.cachesApi })
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ expect(tab.fetchImpl).not.toHaveBeenCalled()
+ tab.win.become(true)
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ expect(tab.fetchImpl.mock.calls.map(c => c[0]).sort()).toEqual([abs(gifSrc(bench)), abs(imgSrc(bench))].sort())
+ stop()
+ expect(tab.win.listeners.size).toBe(0)
+ })
+
+ it('stops between files when the page stops being the installed app', async () => {
+ vi.useFakeTimers()
+ const { store, cachesApi, nav, win } = setup({ S: { routines: [{ ex: [{ id: bench.id }, { id: other.id }] }] } })
+ const fetchImpl = vi.fn(async () => { win.become(false); return answer() })
+ vi.stubGlobal('fetch', fetchImpl)
+ const stop = startMediaPrefetch(store, { win, nav, cachesApi })
+ await vi.advanceTimersByTimeAsync(PREFETCH_DELAY_MS)
+ await flush()
+ // Two lanes had each started one before the first answer came back; none after it.
+ expect(fetchImpl.mock.calls.length).toBeLessThanOrEqual(2)
+ stop()
})
})
diff --git a/frontend/src/main.jsx b/frontend/src/main.jsx
index f57590454..495fdf905 100644
--- a/frontend/src/main.jsx
+++ b/frontend/src/main.jsx
@@ -16,5 +16,6 @@ createRoot(document.getElementById('root')).render(
if (!MOBILE && 'serviceWorker' in navigator && location.protocol === 'https:') {
navigator.serviceWorker.register('sw.js').catch(() => {})
// The plan's exercise media, kept by the worker for a workout opened without a network (#281).
+ // It only fetches ahead while the page runs as the installed app; a tab keeps what it has shown.
import('./lib/media-prefetch.js').then(m => m.startMediaPrefetch(useStore)).catch(() => {})
}