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.

fix(offline): English exercise steps are precached, and a failed load is tried again

Duarte Santos53ad901c16c5
diff --git a/frontend/scripts/sw-stamp.mjs b/frontend/scripts/sw-stamp.mjs
index 24d2c3f9f..b3faadb93 100644
--- a/frontend/scripts/sw-stamp.mjs
+++ b/frontend/scripts/sw-stamp.mjs
@@ -7,6 +7,11 @@
// and offline it was simply missing until the page had needed it once with a network: the first
// photo after an update, added at the gym, failed.
const PACK = /[\\/]src[\\/](?:locales|instr|exercise-names)[\\/]/
+// …except the English steps: every language falls back to them, they are no longer in the main
+// bundle (i18n.js loads them on the first exercise opened), and left out, a phone that had not
+// opened one with a network showed no steps at all offline. exercise-desc/ is not a PACK and
+// stays in the list, English descriptions included.
+const KEEP = /[\\/]src[\\/]instr[\\/]en\.js$/
/** The built files the worker fetches at install besides what index.html names: every chunk and
* stylesheet but the packs, as './assets/…' the way index.html writes them. */
@@ -15,7 +20,7 @@ export function lazyAssets(bundle) {
for (const [file, item] of Object.entries(bundle)) {
if (!/\.(?:js|css)$/.test(file)) continue
const ids = item.type === 'chunk' ? (item.moduleIds?.length ? item.moduleIds : Object.keys(item.modules || {})) : []
- if (ids.length && ids.every(id => PACK.test(id))) continue
+ if (ids.length && ids.every(id => PACK.test(id) && !KEEP.test(id))) continue
out.push('./' + file)
}
return out.sort()
diff --git a/frontend/src/lib/i18n-core.js b/frontend/src/lib/i18n-core.js
index 0dc2447bb..28e00f869 100644
--- a/frontend/src/lib/i18n-core.js
+++ b/frontend/src/lib/i18n-core.js
@@ -136,6 +136,25 @@ const askDetails = () => {
detailsLoader()
}
+// A load that failed: the next reader to ask after a pause tries again, and so does the browser
+// coming back online. Not at once: every render asks, and offline every try fails at once.
+let retryTimer = null
+let onOnline = null
+function clearRetry() {
+ clearTimeout(retryTimer)
+ retryTimer = null
+ if (onOnline && typeof globalThis.removeEventListener === 'function') globalThis.removeEventListener('online', onOnline)
+ onOnline = null
+}
+export function _detailsFailed(retryMs = 20000) {
+ clearRetry()
+ retryTimer = setTimeout(() => { clearRetry(); detailsAsked = false }, retryMs)
+ if (typeof globalThis.addEventListener === 'function') {
+ onOnline = () => { clearRetry(); detailsAsked = false; askDetails() }
+ globalThis.addEventListener('online', onOnline)
+ }
+}
+
// Instructions for an exercise in the current language (English steps as fallback). `st` on the
// exercise itself still wins over nothing: a custom exercise or an older plan file carries its own.
export const instrFor = ex => {
@@ -159,12 +178,15 @@ export const descFor = ex => {
}
// i18n.js hands over the loader here; core itself never imports a chunk.
-export function _setDetailsLoader(fn) { detailsLoader = fn; detailsAsked = false }
+export function _setDetailsLoader(fn) { detailsLoader = fn; detailsAsked = false; clearRetry() }
-// Called once the English packs (and the language's descriptions, if any) have loaded.
+// Called once the English packs (and the language's descriptions, if any) have loaded. A pack
+// that did not come (offline, before the worker had it) stays missing, not empty: an empty one
+// would show no steps until the next reload.
export function _setDetails(newEnInstr, newEnDescs, newDescs) {
- enInstr = newEnInstr || enInstr || {}
- enDescs = newEnDescs || enDescs || {}
+ enInstr = newEnInstr || enInstr
+ enDescs = newEnDescs || enDescs
+ if (enInstr && enDescs) clearRetry()
descs = lang === 'en' ? null : (newDescs || null)
version++
return version
diff --git a/frontend/src/lib/i18n-details-retry.test.js b/frontend/src/lib/i18n-details-retry.test.js
new file mode 100644
index 000000000..fadb0963f
--- /dev/null
+++ b/frontend/src/lib/i18n-details-retry.test.js
@@ -0,0 +1,52 @@
+// @vitest-environment happy-dom
+/* The English steps and descriptions come in their own chunk the first time an exercise is shown.
+ A load that failed (offline, before the worker had the chunk) used to leave them empty and
+ never ask again, so every exercise showed no steps until the app was reloaded. Now the next
+ reader after a pause, or the browser coming back online, tries again. */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const net = { up: false, loads: 0 }
+const offline = () => { throw new TypeError('Failed to fetch dynamically imported module') }
+
+const ex = { id: '9999', st: [] }
+const settle = async () => { for (let i = 0; i < 5; i++) await Promise.resolve(); await new Promise(r => setTimeout(r, 0)) }
+
+let i18n
+beforeEach(async () => {
+ vi.resetModules()
+ net.up = false
+ net.loads = 0
+ vi.doMock('../instr/en.js', async () => { net.loads++; return net.up ? { default: { 9999: ['Stand tall.', 'Lift.'] } } : offline() })
+ vi.doMock('../exercise-desc/en.js', async () => (net.up ? { default: { 9999: 'A lift.' } } : offline()))
+ i18n = await import('./i18n.js')
+})
+afterEach(() => { vi.useRealTimers() })
+
+describe('a failed load of the English steps', () => {
+ it('is not mistaken for no steps: tried again on the next ask after a pause', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ expect(i18n.instrFor(ex)).toEqual([])
+ await vi.advanceTimersByTimeAsync(0)
+ expect(net.loads).toBe(1)
+ // asked again at once (every render asks): no new try yet
+ i18n.instrFor(ex)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(net.loads).toBe(1)
+ net.up = true
+ await vi.advanceTimersByTimeAsync(20000)
+ expect(net.loads).toBe(1) // nothing asked yet: no load on its own
+ i18n.instrFor(ex)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(i18n.instrFor(ex)).toEqual(['Stand tall.', 'Lift.'])
+ })
+
+ it('tried again as soon as the browser is back online', async () => {
+ i18n.instrFor(ex)
+ await settle()
+ expect(net.loads).toBe(1)
+ net.up = true
+ window.dispatchEvent(new Event('online'))
+ await settle()
+ expect(i18n.instrFor(ex)).toEqual(['Stand tall.', 'Lift.'])
+ })
+})
diff --git a/frontend/src/lib/i18n.js b/frontend/src/lib/i18n.js
index 88d363eaa..f1a57d33b 100644
--- a/frontend/src/lib/i18n.js
+++ b/frontend/src/lib/i18n.js
@@ -7,7 +7,7 @@ import { useSyncExternalStore } from 'react'
import {
LANGS, INSTR_LANGS, EXERCISE_NAME_LANGS, DATE_LOCALES, DERIVED_LOCALES, RTL_LANGS,
getLang, dateLocale, t, tn, instrFor, exerciseNameFor, exerciseNameSearchText, getVersion,
- baseLang, derivePack, _setLangState, exerciseNameClass, descFor, instrTranslated, _setDetailsLoader, _setDetails
+ baseLang, derivePack, _setLangState, exerciseNameClass, descFor, instrTranslated, _setDetailsLoader, _setDetails, _detailsFailed
} from './i18n-core.js'
export {
@@ -34,8 +34,10 @@ async function loadDetails() {
load(descPacks, '../exercise-desc/en.js'),
base === 'en' ? null : load(descPacks, '../exercise-desc/' + base + '.js'),
])
- detailsLoaded = true
+ // Either English pack missing is a failed load (both always exist): core asks again later.
+ if (en && enDesc) detailsLoaded = true
_setDetails(en, enDesc, derivePack(getLang(), desc))
+ if (!en || !enDesc) _detailsFailed()
notify()
}
_setDetailsLoader(loadDetails)
diff --git a/frontend/src/lib/sw-lazy.test.js b/frontend/src/lib/sw-lazy.test.js
index 994bc1a90..60f601ed7 100644
--- a/frontend/src/lib/sw-lazy.test.js
+++ b/frontend/src/lib/sw-lazy.test.js
@@ -55,7 +55,7 @@ describe('the worker keeps the on-demand code too', () => {
expect(asked).toEqual(['index.html', './assets/index-new.js'])
})
- it('the build lists code and styles, not the language packs', () => {
+ it('the build lists code and styles, not the language packs (but the English steps)', () => {
const chunk = (...moduleIds) => ({ type: 'chunk', moduleIds })
const bundle = {
'assets/index-a.js': chunk('/app/frontend/src/main.jsx'),
@@ -65,8 +65,12 @@ describe('the worker keeps the on-demand code too', () => {
'assets/ru-e.js': chunk('/app/frontend/src/exercise-names/ru.js'),
'assets/index-f.css': { type: 'asset' },
'icon-512.png': { type: 'asset' },
+ // the English steps and descriptions every language falls back to: offline as well
+ 'assets/en-g.js': chunk('/app/frontend/src/instr/en.js'),
+ 'assets/en-h.js': chunk('/app/frontend/src/exercise-desc/en.js'),
+ 'assets/de-i.js': chunk('/app/frontend/src/exercise-desc/de.js'),
}
- expect(lazyAssets(bundle)).toEqual(['./assets/index-a.js', './assets/index-f.css', './assets/media-ingest-b.js'])
+ expect(lazyAssets(bundle)).toEqual(['./assets/de-i.js', './assets/en-g.js', './assets/en-h.js', './assets/index-a.js', './assets/index-f.css', './assets/media-ingest-b.js'])
})
it('the build stamps the worker with both', () => {