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: the first photo after an update works without a network

Duarte Santos4fb65108bec6
diff --git a/frontend/public/sw.js b/frontend/public/sw.js
index a404f13cb..3f703eb9d 100644
--- a/frontend/public/sw.js
+++ b/frontend/public/sw.js
@@ -35,6 +35,12 @@ const MEDIA_GUESS_BYTES = 64 * 1024
const MEDIA_TRIM_EVERY = 20
const isMediaPath = p => p.includes('/img/') || p.includes('/gif/')
+// The code the app loads only when it needs it (the photo and video ingest, the QR reader...),
+// listed by the build (vite.config.js, scripts/sw-stamp.mjs). Without it the first photo added
+// offline after an update had no ingest to run. Unstamped (a dev server, a test) it is empty.
+const LAZY = '__LAZY__'
+const lazyAssets = () => { try { const a = JSON.parse(LAZY); return Array.isArray(a) ? a : [] } catch { return [] } }
+
// What the shell needs to boot without a network: index.html plus every script/style/icon it
// references. Read from the served index.html so the list follows the build, not a hand-kept
// manifest that would go stale the first time a chunk is renamed.
@@ -68,6 +74,14 @@ async function precache() {
await c.put(u, r)
}))
await Promise.all(refs.filter(u => !code.includes(u)).map(u => c.add(u).catch(() => {})))
+ // Best effort, like the icons: a chunk missing here is fetched when it is needed, as before, and
+ // must not keep a working build from installing. Fetched by hand for the same redirect reason.
+ await Promise.all(lazyAssets().filter(u => !code.includes(u)).map(async u => {
+ try {
+ const r = await fetch(u, { cache: 'no-cache' })
+ if (r.ok && !r.redirected) await c.put(u, r)
+ } catch { /* fetched on demand instead */ }
+ }))
// The shell goes in last, so activate's guard — an index.html in THIS build's cache — means the
// whole shell is there rather than just its first file.
await c.put('index.html', new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } }))
diff --git a/frontend/scripts/sw-stamp.mjs b/frontend/scripts/sw-stamp.mjs
new file mode 100644
index 000000000..24d2c3f9f
--- /dev/null
+++ b/frontend/scripts/sw-stamp.mjs
@@ -0,0 +1,29 @@
+// What vite.config.js writes into the built public/sw.js. Kept here so the worker's tests can
+// stamp a copy exactly the way a build does.
+
+// Language, instruction and exercise-name packs: a few hundred kB each, seventeen of them, and
+// the worker already keeps the one in use once it has loaded. Everything else that is split off
+// and loaded on demand (the photo and video ingest, the QR reader, the local Coach) is small,
+// 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)[\\/]/
+
+/** 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. */
+export function lazyAssets(bundle) {
+ const out = []
+ 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
+ out.push('./' + file)
+ }
+ return out.sort()
+}
+
+/** The worker with its build stamp and its list in place of the two placeholders. */
+export function stampSw(source, { stamp, lazy = [] }) {
+ return source
+ .replace('__BUILD__', () => stamp)
+ .replace("'__LAZY__'", () => JSON.stringify(JSON.stringify(lazy)))
+}
diff --git a/frontend/src/components/CustomMediaField.jsx b/frontend/src/components/CustomMediaField.jsx
index 9cd1d8826..c0cd66361 100644
--- a/frontend/src/components/CustomMediaField.jsx
+++ b/frontend/src/components/CustomMediaField.jsx
@@ -39,10 +39,17 @@ export function mediaErrorText(e) {
case 'too-large': return t('That file is too big. Max {0} MB.', fmtMB(e.mb))
case 'too-long': return t('That video is too long. Max {0} seconds.', e.sec)
case 'photo-too-big': return t('That photo is too large to process on this device.')
+ case 'offline': return t('You’re offline. Try again once you’re back online.')
default: return t('This browser cannot read that file.')
}
}
+// The ingest is split off and loaded on first use. A failed load is not remembered here, so the
+// next pick (back online) tries again.
+const loadIngest = () => import('../lib/media-ingest.js').catch(() => {
+ throw Object.assign(new Error('media ingest did not load'), { code: 'offline' })
+})
+
const KIND_ICON = { image: 'image', gif: 'play', video: 'play' }
/**
@@ -82,7 +89,8 @@ export function useMediaPicker() {
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')
+ // Offline before that code was ever cached, the load fails: that is no fault of the file.
+ const { ingestMediaFile } = await loadIngest()
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
diff --git a/frontend/src/components/CustomMediaField.offline.test.jsx b/frontend/src/components/CustomMediaField.offline.test.jsx
new file mode 100644
index 000000000..45194ad30
--- /dev/null
+++ b/frontend/src/components/CustomMediaField.offline.test.jsx
@@ -0,0 +1,54 @@
+// @vitest-environment happy-dom
+// The photo and video ingest is split off and loads on first use. Offline, before the worker had
+// ever cached it, that load failed and the toast said "This browser cannot read that file." about
+// a perfectly good photo; the next pick, back online, has to try the load again.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+const h = vi.hoisted(() => ({ offline: true, toast: vi.fn() }))
+vi.mock('../lib/media-ingest.js', () => {
+ if (h.offline) throw new TypeError('Failed to fetch dynamically imported module')
+ return { ingestMediaFile: async () => ({ blobs: [], warnings: [], media: { kind: 'image', hash: 'h' } }) }
+})
+vi.mock('../lib/media-store.js', () => ({ mediaStore: { ready: async () => {}, persistent: true, put: async () => {} } }))
+vi.mock('../store/useUI.js', () => {
+ const useUI = sel => sel({ toast: h.toast })
+ useUI.getState = () => ({ toast: h.toast })
+ return { useUI }
+})
+
+const { useMediaPicker, mediaErrorText } = await import('./CustomMediaField.jsx')
+
+let host, root, picker
+function Probe() { picker = useMediaPicker(); return null }
+
+beforeEach(() => {
+ h.offline = true
+ h.toast.mockReset()
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ act(() => root.render(<Probe />))
+})
+afterEach(() => { act(() => root.render(null)); host.remove() })
+
+describe('picking a photo with the ingest not loaded', () => {
+ it('says the device is offline, not that the file is bad', async () => {
+ let out
+ await act(async () => { out = await picker.pick(new Blob(['x'], { type: 'image/jpeg' })) })
+ expect(out).toBeNull()
+ expect(h.toast).toHaveBeenCalledWith('You’re offline. Try again once you’re back online.')
+ expect(mediaErrorText({ code: 'offline' })).toBe('You’re offline. Try again once you’re back online.')
+ })
+
+ it('loads it on the next pick once the network is back', async () => {
+ await act(async () => { await picker.pick(new Blob(['x'], { type: 'image/jpeg' })) })
+ h.offline = false
+ let out
+ await act(async () => { out = await picker.pick(new Blob(['x'], { type: 'image/jpeg' })) })
+ expect(out).toEqual({ kind: 'image', hash: 'h' })
+ })
+})
diff --git a/frontend/src/lib/sw-lazy.test.js b/frontend/src/lib/sw-lazy.test.js
new file mode 100644
index 000000000..994bc1a90
--- /dev/null
+++ b/frontend/src/lib/sw-lazy.test.js
@@ -0,0 +1,80 @@
+/* The code the app splits off and loads on demand (the photo and video ingest, the QR reader, the
+ * local Coach) was cached only once the page had needed it with a network. The first photo added
+ * offline after an update had no ingest to run. The build now lists those chunks into sw.js and
+ * the install fetches them, best effort, leaving the big language packs to load as they always did. */
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import vm from 'node:vm'
+import { describe, expect, it } from 'vitest'
+import { lazyAssets, stampSw } from '../../scripts/sw-stamp.mjs'
+
+const source = readFileSync(fileURLToPath(new URL('../../public/sw.js', import.meta.url)), 'utf8')
+const shell = '<html><head><script src="./assets/index-new.js"></script></head></html>'
+
+function install(sw, fetchImpl) {
+ const listeners = {}
+ const caches = new Map()
+ const open = async n => { if (!caches.has(n)) caches.set(n, new Map()); const m = caches.get(n); return { put: async (k, v) => { m.set(String(k), v) }, add: async () => {}, match: async k => m.get(String(k)), keys: async () => [...m.keys()] } }
+ const context = {
+ self: { addEventListener: (t, f) => { listeners[t] = f }, skipWaiting: () => {}, clients: { claim: async () => {} }, registration: {} },
+ caches: { open, keys: async () => [...caches.keys()], delete: async n => caches.delete(n), match: async () => undefined },
+ fetch: fetchImpl, location: { origin: 'https://gym.example' }, URL, setTimeout, clearTimeout, console, Response,
+ }
+ vm.runInNewContext(sw, context)
+ let done
+ listeners.install({ waitUntil: p => { done = p } })
+ return done.then(() => [...caches.values()][0])
+}
+
+const ok = body => ({ ok: true, status: 200, redirected: false, text: async () => body })
+
+describe('the worker keeps the on-demand code too', () => {
+ it('fetches every listed chunk at install', async () => {
+ const sw = stampSw(source, { stamp: 'abc', lazy: ['./assets/index-new.js', './assets/media-ingest-x.js', './assets/jsQR-y.js'] })
+ const asked = []
+ const cache = await install(sw, async u => { asked.push(String(u)); return String(u) === 'index.html' ? ok(shell) : ok('') })
+ expect(asked.filter(u => u === './assets/index-new.js')).toHaveLength(1)
+ expect([...cache.keys()]).toEqual(expect.arrayContaining(['./assets/media-ingest-x.js', './assets/jsQR-y.js', 'index.html']))
+ })
+
+ it('a chunk that will not come is no reason to fail the install', async () => {
+ const sw = stampSw(source, { stamp: 'abc', lazy: ['./assets/media-ingest-x.js', './assets/gone.js'] })
+ const cache = await install(sw, async u => {
+ if (String(u) === 'index.html') return ok(shell)
+ if (String(u).includes('gone')) throw new TypeError('network down')
+ if (String(u).includes('media-ingest')) return { ok: true, status: 200, redirected: true }
+ return ok('')
+ })
+ expect([...cache.keys()]).toContain('index.html')
+ expect([...cache.keys()]).not.toContain('./assets/media-ingest-x.js') // a login page is not the ingest
+ })
+
+ it('an unstamped worker (dev, tests) has nothing extra to fetch', async () => {
+ const asked = []
+ await install(source, async u => { asked.push(String(u)); return String(u) === 'index.html' ? ok(shell) : ok('') })
+ expect(asked).toEqual(['index.html', './assets/index-new.js'])
+ })
+
+ it('the build lists code and styles, not the language packs', () => {
+ const chunk = (...moduleIds) => ({ type: 'chunk', moduleIds })
+ const bundle = {
+ 'assets/index-a.js': chunk('/app/frontend/src/main.jsx'),
+ 'assets/media-ingest-b.js': chunk('/app/frontend/src/lib/media-ingest.js'),
+ 'assets/de-c.js': chunk('/app/frontend/src/locales/de.js'),
+ 'assets/de-d.js': chunk('/app/frontend/src/instr/de.js'),
+ 'assets/ru-e.js': chunk('/app/frontend/src/exercise-names/ru.js'),
+ 'assets/index-f.css': { type: 'asset' },
+ 'icon-512.png': { type: 'asset' },
+ }
+ expect(lazyAssets(bundle)).toEqual(['./assets/index-a.js', './assets/index-f.css', './assets/media-ingest-b.js'])
+ })
+
+ it('the build stamps the worker with both', () => {
+ const vite = readFileSync(fileURLToPath(new URL('../../vite.config.js', import.meta.url)), 'utf8')
+ expect(vite).toMatch(/generateBundle\(_, bundle\) \{ lazy = lazyAssets\(bundle\) \}/)
+ expect(vite).toMatch(/stampSw\(readFileSync\(sw, 'utf8'\), \{ stamp, lazy \}\)/)
+ const sw = stampSw(source, { stamp: 'abc', lazy: ["./assets/it's.js"] })
+ expect(sw).toContain("const CACHE = 'opengym-rt-abc'")
+ expect(sw).not.toContain('__LAZY__')
+ })
+})
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 141badc71..f8493053a 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1628,6 +1628,7 @@ export default {
'That file is too big. Max {0} MB.': 'هذا الملف كبير جدًا. الحد الأقصى {0} م.ب.',
'That video is too long. Max {0} seconds.': 'هذا الفيديو طويل جدًا. الحد الأقصى {0} ثانية.',
'That photo is too large to process on this device.': 'هذه الصورة أكبر من أن تُعالَج على هذا الجهاز.',
+ 'You’re offline. Try again once you’re back online.': 'أنت غير متصل بالإنترنت. حاول مجددًا عند عودة الاتصال.',
'This browser cannot read that file.': 'لا يستطيع هذا المتصفح قراءة ذلك الملف.',
'There is no room left on this device for that file.': 'لم تعد هناك مساحة على هذا الجهاز لذلك الملف.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'قد لا يعمل هذا الفيديو على كل الأجهزة. صيغة MP4 (H.264) تعمل في كل مكان.',
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 5b11386c2..418141d63 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1602,6 +1602,7 @@ export default {
'That file is too big. Max {0} MB.': 'Diese Datei ist zu groß. Höchstens {0} MB.',
'That video is too long. Max {0} seconds.': 'Dieses Video ist zu lang. Höchstens {0} Sekunden.',
'That photo is too large to process on this device.': 'Dieses Foto ist zu groß, um es auf diesem Gerät zu verarbeiten.',
+ 'You’re offline. Try again once you’re back online.': 'Du bist offline. Versuch es nochmal, sobald du wieder Netz hast.',
'This browser cannot read that file.': 'Dieser Browser kann diese Datei nicht lesen.',
'There is no room left on this device for that file.': 'Auf diesem Gerät ist kein Platz mehr für diese Datei.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'Dieses Video läuft womöglich nicht auf jedem Gerät. MP4 (H.264) läuft überall.',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index dea765ad8..aa5c2d292 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1582,6 +1582,7 @@ export default {
'That file is too big. Max {0} MB.': 'Ese archivo es demasiado grande. Máximo {0} MB.',
'That video is too long. Max {0} seconds.': 'Ese vídeo es demasiado largo. Máximo {0} segundos.',
'That photo is too large to process on this device.': 'Esa foto es demasiado grande para procesarla en este dispositivo.',
+ 'You’re offline. Try again once you’re back online.': 'Estás sin conexión. Vuelve a intentarlo cuando tengas red.',
'This browser cannot read that file.': 'Este navegador no puede leer ese archivo.',
'There is no room left on this device for that file.': 'No queda espacio en este dispositivo para ese archivo.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'Puede que este vídeo no se reproduzca en todos los dispositivos. MP4 (H.264) funciona en todas partes.',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 52a520745..060ce9be2 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1582,6 +1582,7 @@ export default {
'That file is too big. Max {0} MB.': 'Ce fichier est trop volumineux. {0} Mo maximum.',
'That video is too long. Max {0} seconds.': 'Cette vidéo est trop longue. {0} secondes maximum.',
'That photo is too large to process on this device.': 'Cette photo est trop grande pour être traitée sur cet appareil.',
+ 'You’re offline. Try again once you’re back online.': 'Tu es hors ligne. Réessaie dès que tu as du réseau.',
'This browser cannot read that file.': 'Ce navigateur ne peut pas lire ce fichier.',
'There is no room left on this device for that file.': 'Il n’y a plus de place sur cet appareil pour ce fichier.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'Cette vidéo risque de ne pas se lire sur tous les appareils. Le MP4 (H.264) se lit partout.',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 6042d6301..43436d6ca 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1582,6 +1582,7 @@ export default {
'That file is too big. Max {0} MB.': 'यह फ़ाइल बहुत बड़ी है। अधिकतम {0} MB।',
'That video is too long. Max {0} seconds.': 'यह वीडियो बहुत लंबा है। अधिकतम {0} सेकंड।',
'That photo is too large to process on this device.': 'यह फ़ोटो इस डिवाइस पर प्रोसेस करने के लिए बहुत बड़ी है।',
+ 'You’re offline. Try again once you’re back online.': 'आप ऑफ़लाइन हैं। इंटरनेट वापस आने पर फिर से कोशिश करें।',
'This browser cannot read that file.': 'यह ब्राउज़र उस फ़ाइल को नहीं पढ़ सकता।',
'There is no room left on this device for that file.': 'इस डिवाइस पर उस फ़ाइल के लिए जगह नहीं बची है।',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'यह वीडियो शायद हर डिवाइस पर न चले। MP4 (H.264) हर जगह चलता है।',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 679fc7e6b..e78065e09 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1585,6 +1585,7 @@ export default {
'That file is too big. Max {0} MB.': 'Ez a fájl túl nagy. Legfeljebb {0} MB.',
'That video is too long. Max {0} seconds.': 'Ez a videó túl hosszú. Legfeljebb {0} másodperc.',
'That photo is too large to process on this device.': 'Ez a fotó túl nagy ahhoz, hogy ezen az eszközön feldolgozható legyen.',
+ 'You’re offline. Try again once you’re back online.': 'Nincs internetkapcsolat. Próbáld újra, ha újra van net.',
'This browser cannot read that file.': 'Ez a böngésző nem tudja beolvasni a fájlt.',
'There is no room left on this device for that file.': 'Ezen az eszközön nincs már hely ehhez a fájlhoz.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'Lehet, hogy ez a videó nem minden eszközön játszható le. Az MP4 (H.264) mindenhol megy.',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 26829fee0..16d95fa4d 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1582,6 +1582,7 @@ export default {
'That file is too big. Max {0} MB.': 'Il file è troppo grande. Massimo {0} MB.',
'That video is too long. Max {0} seconds.': 'Il video è troppo lungo. Massimo {0} secondi.',
'That photo is too large to process on this device.': 'Questa foto è troppo grande per essere elaborata su questo dispositivo.',
+ 'You’re offline. Try again once you’re back online.': 'Sei offline. Riprova appena torni online.',
'This browser cannot read that file.': 'Questo browser non riesce a leggere il file.',
'There is no room left on this device for that file.': 'Su questo dispositivo non c’è più spazio per il file.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'Questo video potrebbe non funzionare su tutti i dispositivi. L’MP4 (H.264) funziona ovunque.',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 1242f7a56..266878f80 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1582,6 +1582,7 @@ export default {
'That file is too big. Max {0} MB.': '파일이 너무 큽니다. 최대 {0} MB.',
'That video is too long. Max {0} seconds.': '동영상이 너무 깁니다. 최대 {0}초.',
'That photo is too large to process on this device.': '이 사진은 이 기기에서 처리하기에 너무 큽니다.',
+ 'You’re offline. Try again once you’re back online.': '오프라인 상태예요. 다시 연결되면 한 번 더 해 보세요.',
'This browser cannot read that file.': '이 브라우저는 해당 파일을 읽을 수 없습니다.',
'There is no room left on this device for that file.': '이 기기에 해당 파일을 저장할 공간이 없습니다.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': '이 동영상은 일부 기기에서 재생되지 않을 수 있어요. MP4(H.264)는 어디서나 재생돼요.',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index fe625c47c..3977ab68b 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1582,6 +1582,7 @@ export default {
'That file is too big. Max {0} MB.': 'Ten plik jest za duży. Maksymalnie {0} MB.',
'That video is too long. Max {0} seconds.': 'Ten film jest za długi. Maksymalnie {0} sekund.',
'That photo is too large to process on this device.': 'To zdjęcie jest za duże, by przetworzyć je na tym urządzeniu.',
+ 'You’re offline. Try again once you’re back online.': 'Jesteś offline. Spróbuj ponownie, gdy wróci internet.',
'This browser cannot read that file.': 'Ta przeglądarka nie może odczytać tego pliku.',
'There is no room left on this device for that file.': 'Na tym urządzeniu nie ma już miejsca na ten plik.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'Ten film może nie działać na każdym urządzeniu. MP4 (H.264) działa wszędzie.',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 90060ed15..c8df6a0c3 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -948,6 +948,7 @@ export const PT_BR_OVERRIDES = {
'That file is too big. Max {0} MB.': 'Esse arquivo é grande demais. Máximo de {0} MB.',
'That video is too long. Max {0} seconds.': 'Esse vídeo é longo demais. Máximo de {0} segundos.',
'That photo is too large to process on this device.': 'Essa foto é grande demais para ser processada neste dispositivo.',
+ 'You’re offline. Try again once you’re back online.': 'Você está offline. Tente de novo quando a conexão voltar.',
'This browser cannot read that file.': 'Este navegador não consegue ler esse arquivo.',
'There is no room left on this device for that file.': 'Não há mais espaço neste dispositivo para esse arquivo.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'Este vídeo pode não rodar em todos os dispositivos. MP4 (H.264) roda em qualquer lugar.',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index fd5d9ead3..1a7428554 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1582,6 +1582,7 @@ export default {
'That file is too big. Max {0} MB.': 'Esse ficheiro é demasiado grande. Máximo {0} MB.',
'That video is too long. Max {0} seconds.': 'Esse vídeo é demasiado longo. Máximo {0} segundos.',
'That photo is too large to process on this device.': 'Essa foto é demasiado grande para ser processada neste dispositivo.',
+ 'You’re offline. Try again once you’re back online.': 'Estás offline. Tenta de novo quando voltares a ter rede.',
'This browser cannot read that file.': 'Este navegador não consegue ler esse ficheiro.',
'There is no room left on this device for that file.': 'Já não há espaço neste dispositivo para esse ficheiro.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'Este vídeo pode não reproduzir em todos os dispositivos. MP4 (H.264) funciona em todo o lado.',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 257e1418a..8c11c76e0 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1548,6 +1548,7 @@ export default {
'That file is too big. Max {0} MB.': 'Файл слишком большой. Максимум {0} МБ.',
'That video is too long. Max {0} seconds.': 'Видео слишком длинное. Максимум {0} секунд.',
'That photo is too large to process on this device.': 'Это фото слишком большое, чтобы обработать его на этом устройстве.',
+ 'You’re offline. Try again once you’re back online.': 'Ты офлайн. Попробуй ещё раз, когда появится интернет.',
'This browser cannot read that file.': 'Этот браузер не может прочитать файл.',
'There is no room left on this device for that file.': 'На этом устройстве не осталось места для этого файла.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'Это видео может воспроизводиться не на всех устройствах. MP4 (H.264) работает везде.',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index efea72a3b..215b5b498 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1593,6 +1593,7 @@ export default {
'That file is too big. Max {0} MB.': 'ไฟล์ใหญ่เกินไป สูงสุด {0} MB',
'That video is too long. Max {0} seconds.': 'วิดีโอยาวเกินไป สูงสุด {0} วินาที',
'That photo is too large to process on this device.': 'รูปนี้ใหญ่เกินกว่าจะประมวลผลบนอุปกรณ์นี้ได้',
+ 'You’re offline. Try again once you’re back online.': 'ตอนนี้ออฟไลน์อยู่ ลองอีกครั้งเมื่อกลับมาออนไลน์นะ',
'This browser cannot read that file.': 'เบราว์เซอร์นี้อ่านไฟล์นั้นไม่ได้',
'There is no room left on this device for that file.': 'อุปกรณ์นี้ไม่มีพื้นที่เหลือสำหรับไฟล์นั้น',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'วิดีโอนี้อาจเล่นไม่ได้ในบางอุปกรณ์ MP4 (H.264) เล่นได้ทุกที่',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 423a56dfe..242b78114 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1582,6 +1582,7 @@ export default {
'That file is too big. Max {0} MB.': 'Bu dosya çok büyük. En fazla {0} MB.',
'That video is too long. Max {0} seconds.': 'Bu video çok uzun. En fazla {0} saniye.',
'That photo is too large to process on this device.': 'Bu fotoğraf bu cihazda işlenemeyecek kadar büyük.',
+ 'You’re offline. Try again once you’re back online.': 'Çevrimdışısın. İnternet gelince tekrar dene.',
'This browser cannot read that file.': 'Bu tarayıcı bu dosyayı okuyamıyor.',
'There is no room left on this device for that file.': 'Bu cihazda bu dosya için yer kalmadı.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'Bu video her cihazda oynamayabilir. MP4 (H.264) her yerde oynar.',
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index 13dab5332..ed94e47e4 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1572,6 +1572,7 @@ export default {
'That file is too big. Max {0} MB.': 'Файл завеликий. Максимум {0} МБ.',
'That video is too long. Max {0} seconds.': 'Відео задовге. Максимум {0} секунд.',
'That photo is too large to process on this device.': 'Це фото завелике, щоб обробити його на цьому пристрої.',
+ 'You’re offline. Try again once you’re back online.': 'Ти офлайн. Спробуй ще раз, коли з’явиться інтернет.',
'This browser cannot read that file.': 'Цей браузер не може прочитати файл.',
'There is no room left on this device for that file.': 'На цьому пристрої не залишилося місця для цього файлу.',
'This video may not play on every device. MP4 (H.264) plays everywhere.': 'Це відео може не відтворюватися на всіх пристроях. MP4 (H.264) працює скрізь.',
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index 9020ee1ea..6f9f885b7 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -1566,6 +1566,7 @@ export default {
'That file is too big. Max {0} MB.': '檔案太大了。上限 {0} MB。',
'That video is too long. Max {0} seconds.': '影片太長了。最長 {0} 秒。',
'That photo is too large to process on this device.': '照片解析度過大,無法在此裝置上進行運算處理。',
+ 'You’re offline. Try again once you’re back online.': '目前離線。等網路恢復後再試一次。',
'This browser cannot read that file.': '此瀏覽器無法讀取該檔案。',
'There is no room left on this device for that file.': '此裝置可用儲存空間已不足以存放該檔案。',
'This video may not play on every device. MP4 (H.264) plays everywhere.': '此影片可能無法在所有裝置上播放。MP4(H.264)到哪都能播。',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 966f906a5..5383c8358 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1582,6 +1582,7 @@ export default {
'That file is too big. Max {0} MB.': '文件太大了。最大 {0} MB。',
'That video is too long. Max {0} seconds.': '视频太长了。最长 {0} 秒。',
'That photo is too large to process on this device.': '照片太大,无法在此设备上处理。',
+ 'You’re offline. Try again once you’re back online.': '当前离线。等网络恢复后再试一次。',
'This browser cannot read that file.': '此浏览器无法读取该文件。',
'There is no room left on this device for that file.': '此设备上已没有空间存放该文件。',
'This video may not play on every device. MP4 (H.264) plays everywhere.': '此视频可能无法在所有设备上播放。MP4(H.264)在哪儿都能播。',
diff --git a/frontend/vite.config.js b/frontend/vite.config.js
index 1469f7fec..50d3c4ace 100644
--- a/frontend/vite.config.js
+++ b/frontend/vite.config.js
@@ -4,6 +4,7 @@ import { join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
+import { lazyAssets, stampSw } from './scripts/sw-stamp.mjs'
const backend = process.env.API_TARGET || 'http://127.0.0.1:3000'
// The API refuses a state-changing request that a browser sent from anywhere other than its own
@@ -38,16 +39,20 @@ const umami = {
// stamp is a hash of the built index.html — it changes exactly when the bundle does.
// The directory is the one this build wrote to (`--outDir` included), not a fixed ./dist/: a
// build into a private outDir left `__BUILD__` unstamped in its sw.js.
+// The worker also gets the build's code that loads on demand (`__LAZY__`, scripts/sw-stamp.mjs),
+// so it is there offline before the page has ever needed it.
let outDir = fileURLToPath(new URL('./dist/', import.meta.url))
+let lazy = []
const swStamp = {
name: 'opengym-sw-stamp',
apply: 'build',
configResolved(config) { outDir = resolve(config.root, config.build.outDir) },
+ generateBundle(_, bundle) { lazy = lazyAssets(bundle) },
closeBundle() {
const html = join(outDir, 'index.html'), sw = join(outDir, 'sw.js')
if (!existsSync(html) || !existsSync(sw)) return
const stamp = createHash('sha256').update(readFileSync(html)).digest('hex').slice(0, 10)
- writeFileSync(sw, readFileSync(sw, 'utf8').replace('__BUILD__', stamp))
+ writeFileSync(sw, stampSw(readFileSync(sw, 'utf8'), { stamp, lazy }))
}
}