# Conflicts: # frontend/src/lib/pt-br-locale.test.js
This commit is contained in:
commit
0797fda152
25 files changed
+840
-6
No files matched your search
@@ -36,6 +36,7 @@
|
||||
<!-- Permissions -->
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<!-- Workout-day reminder: lets the local-notifications plugin fire at the exact minute
|
||||
on Android 12+. Where it isn't granted, scheduling silently falls back to inexact
|
||||
alarms — the reminder still arrives, just not to the minute. -->
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package ch.duartesantos.opengym;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import androidx.core.content.FileProvider;
|
||||
import com.getcapacitor.Plugin;
|
||||
import com.getcapacitor.PluginCall;
|
||||
import com.getcapacitor.PluginMethod;
|
||||
import com.getcapacitor.annotation.CapacitorPlugin;
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Minimal local Capacitor plugin that opens the Android package installer
|
||||
* for an APK file stored in the app's cache directory.
|
||||
*
|
||||
* Usage from JS:
|
||||
* import { registerPlugin } from '@capacitor/core';
|
||||
* const Install = registerPlugin('Install');
|
||||
* await Install.installApk({ fileName: 'opengym-update.apk' });
|
||||
*/
|
||||
@CapacitorPlugin(name = "Install")
|
||||
public class InstallPlugin extends Plugin {
|
||||
|
||||
@PluginMethod
|
||||
public void installApk(PluginCall call) {
|
||||
String fileName = call.getString("fileName");
|
||||
if (fileName == null || fileName.isEmpty()) {
|
||||
call.reject("fileName is required");
|
||||
return;
|
||||
}
|
||||
|
||||
File file = new File(getContext().getCacheDir(), fileName);
|
||||
if (!file.exists()) {
|
||||
call.reject("APK file not found: " + fileName);
|
||||
return;
|
||||
}
|
||||
|
||||
Uri uri = FileProvider.getUriForFile(
|
||||
getContext(),
|
||||
getContext().getPackageName() + ".fileprovider",
|
||||
file
|
||||
);
|
||||
|
||||
Intent intent = new Intent(Intent.ACTION_VIEW);
|
||||
intent.setDataAndType(uri, "application/vnd.android.package-archive");
|
||||
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
|
||||
|
||||
getContext().startActivity(intent);
|
||||
call.resolve();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
package ch.duartesantos.opengym;
|
||||
|
||||
import android.os.Bundle;
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
|
||||
public class MainActivity extends BridgeActivity {}
|
||||
public class MainActivity extends BridgeActivity {
|
||||
@Override
|
||||
public void onCreate(Bundle savedInstanceState) {
|
||||
registerPlugin(InstallPlugin.class);
|
||||
super.onCreate(savedInstanceState);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,22 @@ import { effectiveRoutineId } from './history.js'
|
||||
|
||||
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
|
||||
|
||||
// Some features only make sense on Android. The in-app updater downloads an .apk and hands it
|
||||
// to the system package installer — there is no equivalent on iOS (App Store only) or on the
|
||||
// web build. On anything but a native Android shell this must stay off.
|
||||
//
|
||||
// @capacitor/core is imported dynamically (like every other Capacitor dependency here) so it
|
||||
// never lands in the web bundle. Capacitor.getPlatform() returns 'android' | 'ios' | 'web'.
|
||||
export async function isAndroid() {
|
||||
if (!MOBILE) return false
|
||||
try {
|
||||
const { Capacitor } = await import('@capacitor/core')
|
||||
return Capacitor.getPlatform() === 'android'
|
||||
} catch (e) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const FILE = 'opengym-state.json'
|
||||
|
||||
export async function nativeLoad() {
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// Update check — compares the installed version (__APP_VERSION__) against
|
||||
// the latest release tag on GitLab and optionally downloads + installs the APK.
|
||||
//
|
||||
// The GitLab releases API is public for this project, so no token is needed.
|
||||
// On Android (Capacitor), the APK asset is downloaded to the cache directory
|
||||
// and handed to the system installer via a content:// URI.
|
||||
|
||||
import { MOBILE } from './mobile.js'
|
||||
|
||||
const GITLAB_PROJECT_ID = 'DuarteSantos8%2Fopengym'
|
||||
const RELEASES_URL = `https://gitlab.com/api/v4/projects/${GITLAB_PROJECT_ID}/releases`
|
||||
|
||||
/**
|
||||
* Compares two semver strings (e.g. "1.2.11" vs "1.3.0").
|
||||
* Returns 1 if a > b, -1 if a < b, 0 if equal.
|
||||
*/
|
||||
function compareSemver(a, b) {
|
||||
const pa = a.replace(/^v/, '').split('.').map(Number)
|
||||
const pb = b.replace(/^v/, '').split('.').map(Number)
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const diff = (pa[i] || 0) - (pb[i] || 0)
|
||||
if (diff > 0) return 1
|
||||
if (diff < 0) return -1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the GitLab releases API for a newer version.
|
||||
* Returns { hasUpdate, latestVersion, apkUrl, hashUrl } or throws on network failure.
|
||||
* - hasUpdate: true if the latest release tag is newer than the running build
|
||||
* - latestVersion: the semver string of the latest release (without "v" prefix)
|
||||
* - apkUrl: direct download URL of the first .apk asset, or null
|
||||
* - hashUrl: direct download URL of the .apk.sha256 hash file, or null
|
||||
*/
|
||||
export async function checkForUpdate() {
|
||||
const res = await fetch(RELEASES_URL + '?per_page=1')
|
||||
if (!res.ok) throw new Error(`GitLab API ${res.status}`)
|
||||
const releases = await res.json()
|
||||
if (!releases.length) return { hasUpdate: false, latestVersion: __APP_VERSION__, apkUrl: null, hashUrl: null }
|
||||
|
||||
const latest = releases[0]
|
||||
const latestVersion = latest.tag_name.replace(/^v/, '')
|
||||
const hasUpdate = compareSemver(latestVersion, __APP_VERSION__) > 0
|
||||
|
||||
// Find the APK asset among the release links (generic package links) or assets.sources
|
||||
let apkUrl = null
|
||||
let hashUrl = null
|
||||
if (latest.assets?.links?.length) {
|
||||
const apkLink = latest.assets.links.find(l => /\.apk$/i.test(l.url) || /\.apk$/i.test(l.direct_asset_url))
|
||||
if (apkLink) apkUrl = apkLink.direct_asset_url || apkLink.url
|
||||
// Look for a matching .sha256 hash file
|
||||
const hashLink = latest.assets.links.find(l => /\.apk\.sha256$/i.test(l.url) || /\.apk\.sha256$/i.test(l.direct_asset_url) || /sha256/i.test(l.name))
|
||||
if (hashLink) hashUrl = hashLink.direct_asset_url || hashLink.url
|
||||
}
|
||||
|
||||
return { hasUpdate, latestVersion, apkUrl, hashUrl }
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the SHA-256 hash of an ArrayBuffer using the Web Crypto API.
|
||||
* Returns the hex-encoded digest string.
|
||||
*/
|
||||
export async function sha256(buffer) {
|
||||
const hash = await crypto.subtle.digest('SHA-256', buffer)
|
||||
return Array.from(new Uint8Array(hash)).map(b => b.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads the APK from `url`, verifies its SHA-256 hash against `expectedHash`
|
||||
* (if provided), and triggers the Android installer.
|
||||
* Only works on the MOBILE (Capacitor) build with Android.
|
||||
*
|
||||
* @param {string} url - Direct download URL for the APK
|
||||
* @param {string|null} expectedHash - Expected SHA-256 hex string (from .sha256 asset), or null to skip verification
|
||||
* @param {function|null} onProgress - Called with (received, total) bytes during download, or null
|
||||
*/
|
||||
export async function downloadAndInstall(url, expectedHash = null, onProgress = null) {
|
||||
if (!MOBILE) {
|
||||
// On web, just open the release page
|
||||
window.open('https://gitlab.com/DuarteSantos8/opengym/-/releases', '_blank', 'noopener')
|
||||
return
|
||||
}
|
||||
|
||||
const { Filesystem, Directory } = await import('@capacitor/filesystem')
|
||||
|
||||
// Download with progress tracking via ReadableStream
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) throw new Error(`Download failed: ${res.status}`)
|
||||
|
||||
const total = parseInt(res.headers.get('content-length') || '0', 10)
|
||||
const reader = res.body.getReader()
|
||||
const chunks = []
|
||||
let received = 0
|
||||
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
chunks.push(value)
|
||||
received += value.length
|
||||
if (onProgress) onProgress(received, total)
|
||||
}
|
||||
|
||||
// Reassemble into a single blob
|
||||
const blob = new Blob(chunks)
|
||||
|
||||
// Size check: an APK should be at least 100 KB
|
||||
if (blob.size < 100_000) {
|
||||
throw new Error('Downloaded file is too small to be a valid APK (' + blob.size + ' bytes)')
|
||||
}
|
||||
|
||||
// SHA-256 integrity check
|
||||
if (expectedHash) {
|
||||
const buffer = await blob.arrayBuffer()
|
||||
const actualHash = await sha256(buffer)
|
||||
if (actualHash !== expectedHash.toLowerCase().trim()) {
|
||||
throw new Error('SHA-256 mismatch — download may be corrupted or tampered with')
|
||||
}
|
||||
}
|
||||
|
||||
// Convert blob to base64
|
||||
const base64 = await new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(reader.result.split(',')[1])
|
||||
reader.onerror = reject
|
||||
reader.readAsDataURL(blob)
|
||||
})
|
||||
|
||||
const fileName = 'opengym-update.apk'
|
||||
await Filesystem.writeFile({
|
||||
path: fileName,
|
||||
directory: Directory.Cache,
|
||||
data: base64,
|
||||
})
|
||||
|
||||
// Use the local InstallPlugin to trigger the Android package installer
|
||||
const { registerPlugin } = await import('@capacitor/core')
|
||||
const Install = registerPlugin('Install')
|
||||
await Install.installApk({ fileName })
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { checkForUpdate, sha256 } from './update.js'
|
||||
|
||||
// __APP_VERSION__ is defined at build time by vite.config.js (reads package.json).
|
||||
// In the test environment vitest applies the same define, so it's available here.
|
||||
|
||||
describe('sha256', () => {
|
||||
it('computes the correct hash for a known input', async () => {
|
||||
const input = new TextEncoder().encode('hello world')
|
||||
const hash = await sha256(input.buffer)
|
||||
// Well-known SHA-256 of "hello world"
|
||||
expect(hash).toBe('b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9')
|
||||
})
|
||||
|
||||
it('computes a different hash for different input', async () => {
|
||||
const a = await sha256(new TextEncoder().encode('aaa').buffer)
|
||||
const b = await sha256(new TextEncoder().encode('bbb').buffer)
|
||||
expect(a).not.toBe(b)
|
||||
})
|
||||
|
||||
it('returns a 64-character hex string', async () => {
|
||||
const hash = await sha256(new TextEncoder().encode('test').buffer)
|
||||
expect(hash).toHaveLength(64)
|
||||
expect(hash).toMatch(/^[0-9a-f]{64}$/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('checkForUpdate', () => {
|
||||
let originalFetch
|
||||
|
||||
beforeEach(() => { originalFetch = globalThis.fetch })
|
||||
afterEach(() => { globalThis.fetch = originalFetch })
|
||||
|
||||
function mockFetch(body, status = 200) {
|
||||
globalThis.fetch = vi.fn(() => Promise.resolve({
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
json: () => Promise.resolve(body),
|
||||
}))
|
||||
}
|
||||
|
||||
it('reports no update when the latest release matches the current version', async () => {
|
||||
mockFetch([{ tag_name: 'v' + __APP_VERSION__, assets: { links: [] } }])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.hasUpdate).toBe(false)
|
||||
expect(result.latestVersion).toBe(__APP_VERSION__)
|
||||
expect(result.apkUrl).toBe(null)
|
||||
expect(result.hashUrl).toBe(null)
|
||||
})
|
||||
|
||||
it('reports no update when the latest release is older than current', async () => {
|
||||
mockFetch([{ tag_name: 'v0.0.1', assets: { links: [] } }])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.hasUpdate).toBe(false)
|
||||
expect(result.latestVersion).toBe('0.0.1')
|
||||
})
|
||||
|
||||
it('reports an update when the latest release is newer', async () => {
|
||||
mockFetch([{ tag_name: 'v99.0.0', assets: { links: [] } }])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.hasUpdate).toBe(true)
|
||||
expect(result.latestVersion).toBe('99.0.0')
|
||||
})
|
||||
|
||||
it('strips the v prefix from the tag name', async () => {
|
||||
mockFetch([{ tag_name: 'v99.1.2', assets: { links: [] } }])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.latestVersion).toBe('99.1.2')
|
||||
})
|
||||
|
||||
it('handles tag names without a v prefix', async () => {
|
||||
mockFetch([{ tag_name: '99.0.0', assets: { links: [] } }])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.hasUpdate).toBe(true)
|
||||
expect(result.latestVersion).toBe('99.0.0')
|
||||
})
|
||||
|
||||
it('finds the APK download URL from release asset links', async () => {
|
||||
const apkUrl = 'https://gitlab.com/project/-/releases/v2.0.0/downloads/opengym.apk'
|
||||
mockFetch([{
|
||||
tag_name: 'v99.0.0',
|
||||
assets: { links: [{ url: apkUrl, direct_asset_url: apkUrl }] }
|
||||
}])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.apkUrl).toBe(apkUrl)
|
||||
})
|
||||
|
||||
it('prefers direct_asset_url over url for APK links', async () => {
|
||||
mockFetch([{
|
||||
tag_name: 'v99.0.0',
|
||||
assets: {
|
||||
links: [{
|
||||
url: 'https://redirect.example/opengym.apk',
|
||||
direct_asset_url: 'https://direct.example/opengym.apk'
|
||||
}]
|
||||
}
|
||||
}])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.apkUrl).toBe('https://direct.example/opengym.apk')
|
||||
})
|
||||
|
||||
it('returns null apkUrl when no .apk link exists', async () => {
|
||||
mockFetch([{
|
||||
tag_name: 'v99.0.0',
|
||||
assets: { links: [{ url: 'https://example.com/changelog.md', direct_asset_url: 'https://example.com/changelog.md' }] }
|
||||
}])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.hasUpdate).toBe(true)
|
||||
expect(result.apkUrl).toBe(null)
|
||||
})
|
||||
|
||||
it('finds the .sha256 hash URL from release asset links', async () => {
|
||||
const hashUrl = 'https://gitlab.com/project/-/releases/v2.0.0/downloads/opengym.apk.sha256'
|
||||
mockFetch([{
|
||||
tag_name: 'v99.0.0',
|
||||
assets: {
|
||||
links: [
|
||||
{ url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' },
|
||||
{ url: hashUrl, direct_asset_url: hashUrl },
|
||||
]
|
||||
}
|
||||
}])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.hashUrl).toBe(hashUrl)
|
||||
})
|
||||
|
||||
it('finds hash URL by link name containing sha256', async () => {
|
||||
mockFetch([{
|
||||
tag_name: 'v99.0.0',
|
||||
assets: {
|
||||
links: [
|
||||
{ name: 'APK', url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' },
|
||||
{ name: 'SHA256 checksum', url: 'https://example.com/checksum.txt', direct_asset_url: 'https://example.com/checksum.txt' },
|
||||
]
|
||||
}
|
||||
}])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.hashUrl).toBe('https://example.com/checksum.txt')
|
||||
})
|
||||
|
||||
// The exact JSON gitlab.com returns for GET /projects/85678327/releases?per_page=1 (v1.3.1,
|
||||
// fetched 2026-09-05, description and commit trimmed). The CI publishes the APK and its
|
||||
// checksum as generic-package links, and the checksum link is listed BEFORE the APK — the
|
||||
// detection must not confuse the two.
|
||||
const REAL_RELEASE = [
|
||||
{
|
||||
"tag_name": "v1.3.1",
|
||||
"name": "openGym v1.3.1",
|
||||
"assets": {
|
||||
"count": 7,
|
||||
"sources": [
|
||||
{
|
||||
"format": "zip",
|
||||
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.zip"
|
||||
},
|
||||
{
|
||||
"format": "tar.gz",
|
||||
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.tar.gz"
|
||||
},
|
||||
{
|
||||
"format": "tar.bz2",
|
||||
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.tar.bz2"
|
||||
},
|
||||
{
|
||||
"format": "tar",
|
||||
"url": "https://gitlab.com/DuarteSantos8/opengym/-/archive/v1.3.1/opengym-v1.3.1.tar"
|
||||
}
|
||||
],
|
||||
"links": [
|
||||
{
|
||||
"id": 12790840,
|
||||
"name": "Container images (api + web)",
|
||||
"url": "https://gitlab.com/DuarteSantos8/opengym/container_registry",
|
||||
"direct_asset_url": "https://gitlab.com/DuarteSantos8/opengym/container_registry",
|
||||
"link_type": "image"
|
||||
},
|
||||
{
|
||||
"id": 12790839,
|
||||
"name": "openGym-1.3.1.apk.sha256 (checksum)",
|
||||
"url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk.sha256",
|
||||
"direct_asset_url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk.sha256",
|
||||
"link_type": "other"
|
||||
},
|
||||
{
|
||||
"id": 12790838,
|
||||
"name": "openGym-1.3.1.apk (Android, sideload)",
|
||||
"url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk",
|
||||
"direct_asset_url": "https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk",
|
||||
"link_type": "package"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
it('finds the APK and its checksum in a real gitlab.com release payload', async () => {
|
||||
mockFetch(REAL_RELEASE)
|
||||
const result = await checkForUpdate()
|
||||
expect(result.latestVersion).toBe('1.3.1')
|
||||
expect(result.apkUrl).toBe('https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk')
|
||||
expect(result.hashUrl).toBe('https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/1.3.1/openGym-1.3.1.apk.sha256')
|
||||
})
|
||||
|
||||
it('returns null hashUrl when no hash link exists', async () => {
|
||||
mockFetch([{
|
||||
tag_name: 'v99.0.0',
|
||||
assets: { links: [{ url: 'https://example.com/opengym.apk', direct_asset_url: 'https://example.com/opengym.apk' }] }
|
||||
}])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.hashUrl).toBe(null)
|
||||
})
|
||||
|
||||
it('returns no update when the releases array is empty', async () => {
|
||||
mockFetch([])
|
||||
const result = await checkForUpdate()
|
||||
expect(result.hasUpdate).toBe(false)
|
||||
expect(result.latestVersion).toBe(__APP_VERSION__)
|
||||
expect(result.hashUrl).toBe(null)
|
||||
})
|
||||
|
||||
it('throws when the API responds with an error status', async () => {
|
||||
mockFetch(null, 500)
|
||||
await expect(checkForUpdate()).rejects.toThrow('GitLab API 500')
|
||||
})
|
||||
|
||||
it('throws on network failure', async () => {
|
||||
globalThis.fetch = vi.fn(() => Promise.reject(new Error('Network error')))
|
||||
await expect(checkForUpdate()).rejects.toThrow('Network error')
|
||||
})
|
||||
})
|
||||
|
||||
describe('semver comparison (via checkForUpdate behavior)', () => {
|
||||
let originalFetch
|
||||
beforeEach(() => { originalFetch = globalThis.fetch })
|
||||
afterEach(() => { globalThis.fetch = originalFetch })
|
||||
|
||||
function mockRelease(tag) {
|
||||
globalThis.fetch = vi.fn(() => Promise.resolve({
|
||||
ok: true, status: 200,
|
||||
json: () => Promise.resolve([{ tag_name: tag, assets: { links: [] } }]),
|
||||
}))
|
||||
}
|
||||
|
||||
// Versions are derived from the running __APP_VERSION__ so the suite never breaks
|
||||
// when package.json bumps. bump(2, +1) raises the patch; bump(0, +1) raises the major.
|
||||
const [MAJ, MIN, PATCH] = __APP_VERSION__.split('.').map(Number)
|
||||
const bump = (idx, by) => {
|
||||
const parts = [MAJ, MIN, PATCH]
|
||||
parts[idx] += by
|
||||
return 'v' + parts.join('.')
|
||||
}
|
||||
|
||||
it('detects a patch bump as an update', async () => {
|
||||
mockRelease(bump(2, 1))
|
||||
expect((await checkForUpdate()).hasUpdate).toBe(true)
|
||||
})
|
||||
|
||||
it('detects a minor bump as an update', async () => {
|
||||
mockRelease(bump(1, 1))
|
||||
expect((await checkForUpdate()).hasUpdate).toBe(true)
|
||||
})
|
||||
|
||||
it('detects a major bump as an update', async () => {
|
||||
mockRelease(bump(0, 1))
|
||||
expect((await checkForUpdate()).hasUpdate).toBe(true)
|
||||
})
|
||||
|
||||
it('does not flag an older patch as an update', async () => {
|
||||
// One patch below current (current patch is always >= our test floor)
|
||||
mockRelease('v' + [MAJ, MIN, Math.max(0, PATCH - 1)].join('.'))
|
||||
// Only meaningful when we could actually go lower; when patch is 0 this equals current,
|
||||
// which correctly reports no update either way.
|
||||
expect((await checkForUpdate()).hasUpdate).toBe(false)
|
||||
})
|
||||
|
||||
it('does not flag an older minor as an update', async () => {
|
||||
// A version guaranteed lower than any 1.x+ release: same major, minor 0, patch 0,
|
||||
// minus one on the minor when possible.
|
||||
mockRelease('v' + [MAJ, Math.max(0, MIN - 1), 0].join('.'))
|
||||
expect((await checkForUpdate()).hasUpdate).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1184,4 +1184,13 @@ export default {
|
||||
'Convert the numbers': 'Zahlen umrechnen',
|
||||
'Keep the numbers, change the label': 'Zahlen behalten, nur Beschriftung ändern',
|
||||
'Switching the unit offers to convert every stored weight.': 'Beim Einheitenwechsel wird angeboten, alle gespeicherten Gewichte umzurechnen.',
|
||||
'Update to {0}?': 'Auf {0} aktualisieren?',
|
||||
'The latest version will be downloaded and the installer will open.': 'Die neueste Version wird heruntergeladen und die Installation gestartet.',
|
||||
'Download & Install': 'Herunterladen & Installieren',
|
||||
'Update failed: {0}': 'Update fehlgeschlagen: {0}',
|
||||
'openGym v{0} available': 'openGym v{0} verfügbar',
|
||||
'Starting download…': 'Download wird gestartet…',
|
||||
'Downloading update…': 'Update wird heruntergeladen…',
|
||||
'{0} %': '{0} %',
|
||||
'{0} MB': '{0} MB',
|
||||
}
|
||||
@@ -1165,4 +1165,13 @@ export default {
|
||||
'Convert the numbers': 'Convertir los números',
|
||||
'Keep the numbers, change the label': 'Mantener los números, cambiar la etiqueta',
|
||||
'Switching the unit offers to convert every stored weight.': 'Al cambiar la unidad se ofrece convertir todos los pesos guardados.',
|
||||
'Update to {0}?': '¿Actualizar a {0}?',
|
||||
'The latest version will be downloaded and the installer will open.': 'Se descargará la última versión y se abrirá el instalador.',
|
||||
'Download & Install': 'Descargar e instalar',
|
||||
'Update failed: {0}': 'Error en la actualización: {0}',
|
||||
'openGym v{0} available': 'openGym v{0} disponible',
|
||||
'Starting download…': 'Iniciando descarga…',
|
||||
'Downloading update…': 'Descargando actualización…',
|
||||
'{0} %': '{0} %',
|
||||
'{0} MB': '{0} MB',
|
||||
}
|
||||
@@ -1165,4 +1165,13 @@ export default {
|
||||
'Convert the numbers': 'Convertir les nombres',
|
||||
'Keep the numbers, change the label': 'Garder les nombres, changer l’étiquette',
|
||||
'Switching the unit offers to convert every stored weight.': 'Changer d’unité propose de convertir tous les poids enregistrés.',
|
||||
'Update to {0}?': 'Mettre à jour vers {0} ?',
|
||||
'The latest version will be downloaded and the installer will open.': 'La dernière version sera téléchargée et l’installateur s’ouvrira.',
|
||||
'Download & Install': 'Télécharger et installer',
|
||||
'Update failed: {0}': 'Échec de la mise à jour : {0}',
|
||||
'openGym v{0} available': 'openGym v{0} disponible',
|
||||
'Starting download…': 'Démarrage du téléchargement…',
|
||||
'Downloading update…': 'Téléchargement de la mise à jour…',
|
||||
'{0} %': '{0} %',
|
||||
'{0} MB': '{0} Mo',
|
||||
}
|
||||
@@ -1165,4 +1165,13 @@ export default {
|
||||
'Convert the numbers': 'संख्याएँ बदलें',
|
||||
'Keep the numbers, change the label': 'संख्याएँ रखें, लेबल बदलें',
|
||||
'Switching the unit offers to convert every stored weight.': 'इकाई बदलने पर सभी सहेजे गए वज़न बदलने का विकल्प मिलता है।',
|
||||
'Update to {0}?': '{0} में अपडेट करें?',
|
||||
'The latest version will be downloaded and the installer will open.': 'नवीनतम संस्करण डाउनलोड होगा और इंस्टॉलर खुलेगा।',
|
||||
'Download & Install': 'डाउनलोड और इंस्टॉल करें',
|
||||
'Update failed: {0}': 'अपडेट विफल: {0}',
|
||||
'openGym v{0} available': 'openGym v{0} उपलब्ध',
|
||||
'Starting download…': 'डाउनलोड शुरू हो रहा है…',
|
||||
'Downloading update…': 'अपडेट डाउनलोड हो रहा है…',
|
||||
'{0} %': '{0}%',
|
||||
'{0} MB': '{0} MB',
|
||||
}
|
||||
@@ -1168,4 +1168,13 @@ export default {
|
||||
'Convert the numbers': 'Számok átváltása',
|
||||
'Keep the numbers, change the label': 'Számok maradnak, csak a címke változik',
|
||||
'Switching the unit offers to convert every stored weight.': 'Mértékegység-váltáskor felajánlja minden tárolt súly átváltását.',
|
||||
'Update to {0}?': 'Frissítés erre: {0}?',
|
||||
'The latest version will be downloaded and the installer will open.': 'A legújabb verzió letöltődik, és megnyílik a telepítő.',
|
||||
'Download & Install': 'Letöltés és telepítés',
|
||||
'Update failed: {0}': 'A frissítés sikertelen: {0}',
|
||||
'openGym v{0} available': 'openGym v{0} elérhető',
|
||||
'Starting download…': 'Letöltés indítása…',
|
||||
'Downloading update…': 'Frissítés letöltése…',
|
||||
'{0} %': '{0} %',
|
||||
'{0} MB': '{0} MB',
|
||||
}
|
||||
@@ -1165,4 +1165,13 @@ export default {
|
||||
'Convert the numbers': 'Converti i numeri',
|
||||
'Keep the numbers, change the label': 'Tieni i numeri, cambia l’etichetta',
|
||||
'Switching the unit offers to convert every stored weight.': 'Cambiando unità viene proposto di convertire tutti i pesi salvati.',
|
||||
'Update to {0}?': 'Aggiornare a {0}?',
|
||||
'The latest version will be downloaded and the installer will open.': 'L’ultima versione verrà scaricata e si aprirà il programma di installazione.',
|
||||
'Download & Install': 'Scarica e installa',
|
||||
'Update failed: {0}': 'Aggiornamento fallito: {0}',
|
||||
'openGym v{0} available': 'openGym v{0} disponibile',
|
||||
'Starting download…': 'Avvio del download…',
|
||||
'Downloading update…': 'Download dell’aggiornamento…',
|
||||
'{0} %': '{0} %',
|
||||
'{0} MB': '{0} MB',
|
||||
}
|
||||
@@ -1165,4 +1165,13 @@ export default {
|
||||
'Convert the numbers': '숫자 변환',
|
||||
'Keep the numbers, change the label': '숫자 유지, 표시만 변경',
|
||||
'Switching the unit offers to convert every stored weight.': '단위를 바꾸면 저장된 모든 무게를 변환할지 물어봅니다.',
|
||||
'Update to {0}?': '{0}(으)로 업데이트하시겠습니까?',
|
||||
'The latest version will be downloaded and the installer will open.': '최신 버전이 다운로드되고 설치 프로그램이 열립니다.',
|
||||
'Download & Install': '다운로드 및 설치',
|
||||
'Update failed: {0}': '업데이트 실패: {0}',
|
||||
'openGym v{0} available': 'openGym v{0} 사용 가능',
|
||||
'Starting download…': '다운로드 시작 중…',
|
||||
'Downloading update…': '업데이트 다운로드 중…',
|
||||
'{0} %': '{0}%',
|
||||
'{0} MB': '{0} MB',
|
||||
}
|
||||
@@ -1165,4 +1165,13 @@ export default {
|
||||
'Convert the numbers': 'Przelicz liczby',
|
||||
'Keep the numbers, change the label': 'Zostaw liczby, zmień etykietę',
|
||||
'Switching the unit offers to convert every stored weight.': 'Zmiana jednostki proponuje przeliczenie wszystkich zapisanych ciężarów.',
|
||||
'Update to {0}?': 'Zaktualizować do {0}?',
|
||||
'The latest version will be downloaded and the installer will open.': 'Najnowsza wersja zostanie pobrana i otworzy się instalator.',
|
||||
'Download & Install': 'Pobierz i zainstaluj',
|
||||
'Update failed: {0}': 'Aktualizacja nie powiodła się: {0}',
|
||||
'openGym v{0} available': 'openGym v{0} dostępna',
|
||||
'Starting download…': 'Rozpoczynanie pobierania…',
|
||||
'Downloading update…': 'Pobieranie aktualizacji…',
|
||||
'{0} %': '{0}%',
|
||||
'{0} MB': '{0} MB',
|
||||
}
|
||||
@@ -648,6 +648,10 @@ export const PT_BR_OVERRIDES = {
|
||||
'Every stored weight — logged sets, working weights, routine targets, body weight, bar weights — is in {0}. Convert the numbers, or keep them and only change the label?': 'Todos os pesos salvos — séries registradas, pesos de trabalho, alvos das rotinas, peso corporal, pesos das barras — estão em {0}. Converter os números, ou mantê-los e mudar só o rótulo?',
|
||||
'Keep the numbers, change the label': 'Manter os números, mudar o rótulo',
|
||||
'Switching the unit offers to convert every stored weight.': 'Ao mudar de unidade é oferecido converter todos os pesos salvos.',
|
||||
'The latest version will be downloaded and the installer will open.': 'A versão mais recente será baixada e o instalador será aberto.',
|
||||
'Download & Install': 'Baixar e instalar',
|
||||
'Starting download…': 'Iniciando download…',
|
||||
'Downloading update…': 'Baixando atualização…',
|
||||
}
|
||||
|
||||
export default { ...pt, ...PT_BR_OVERRIDES }
|
||||
@@ -1165,4 +1165,13 @@ export default {
|
||||
'Convert the numbers': 'Converter os números',
|
||||
'Keep the numbers, change the label': 'Manter os números, mudar a etiqueta',
|
||||
'Switching the unit offers to convert every stored weight.': 'Ao mudar de unidade é proposto converter todos os pesos guardados.',
|
||||
'Update to {0}?': 'Atualizar para {0}?',
|
||||
'The latest version will be downloaded and the installer will open.': 'A versão mais recente será transferida e o instalador será aberto.',
|
||||
'Download & Install': 'Transferir e instalar',
|
||||
'Update failed: {0}': 'Falha na atualização: {0}',
|
||||
'openGym v{0} available': 'openGym v{0} disponível',
|
||||
'Starting download…': 'A iniciar transferência…',
|
||||
'Downloading update…': 'A transferir atualização…',
|
||||
'{0} %': '{0} %',
|
||||
'{0} MB': '{0} MB',
|
||||
}
|
||||
@@ -1165,4 +1165,13 @@ export default {
|
||||
'Convert the numbers': 'Пересчитать числа',
|
||||
'Keep the numbers, change the label': 'Оставить числа, сменить подпись',
|
||||
'Switching the unit offers to convert every stored weight.': 'При смене единицы предлагается пересчитать все сохранённые веса.',
|
||||
'Update to {0}?': 'Обновить до {0}?',
|
||||
'The latest version will be downloaded and the installer will open.': 'Последняя версия будет загружена и откроется установщик.',
|
||||
'Download & Install': 'Скачать и установить',
|
||||
'Update failed: {0}': 'Ошибка обновления: {0}',
|
||||
'openGym v{0} available': 'openGym v{0} доступна',
|
||||
'Starting download…': 'Начало загрузки…',
|
||||
'Downloading update…': 'Загрузка обновления…',
|
||||
'{0} %': '{0} %',
|
||||
'{0} MB': '{0} МБ',
|
||||
}
|
||||
@@ -1176,4 +1176,13 @@ export default {
|
||||
'Convert the numbers': 'แปลงตัวเลข',
|
||||
'Keep the numbers, change the label': 'คงตัวเลขไว้ เปลี่ยนแค่ป้าย',
|
||||
'Switching the unit offers to convert every stored weight.': 'เมื่อเปลี่ยนหน่วยจะมีตัวเลือกให้แปลงน้ำหนักที่บันทึกไว้ทั้งหมด',
|
||||
'Update to {0}?': 'อัปเดตเป็น {0} หรือไม่?',
|
||||
'The latest version will be downloaded and the installer will open.': 'เวอร์ชันล่าสุดจะถูกดาวน์โหลดและตัวติดตั้งจะเปิดขึ้น',
|
||||
'Download & Install': 'ดาวน์โหลดและติดตั้ง',
|
||||
'Update failed: {0}': 'อัปเดตล้มเหลว: {0}',
|
||||
'openGym v{0} available': 'openGym v{0} พร้อมใช้งาน',
|
||||
'Starting download…': 'กำลังเริ่มดาวน์โหลด…',
|
||||
'Downloading update…': 'กำลังดาวน์โหลดอัปเดต…',
|
||||
'{0} %': '{0}%',
|
||||
'{0} MB': '{0} MB',
|
||||
}
|
||||
@@ -1165,4 +1165,13 @@ export default {
|
||||
'Convert the numbers': 'Sayıları çevir',
|
||||
'Keep the numbers, change the label': 'Sayıları koru, etiketi değiştir',
|
||||
'Switching the unit offers to convert every stored weight.': 'Birim değiştirilince tüm kayıtlı ağırlıkları çevirme seçeneği sunulur.',
|
||||
'Update to {0}?': '{0} sürümüne güncellensin mi?',
|
||||
'The latest version will be downloaded and the installer will open.': 'En son sürüm indirilecek ve yükleyici açılacak.',
|
||||
'Download & Install': 'İndir ve Kur',
|
||||
'Update failed: {0}': 'Güncelleme başarısız: {0}',
|
||||
'openGym v{0} available': 'openGym v{0} mevcut',
|
||||
'Starting download…': 'İndirme başlatılıyor…',
|
||||
'Downloading update…': 'Güncelleme indiriliyor…',
|
||||
'{0} %': '%{0}',
|
||||
'{0} MB': '{0} MB',
|
||||
}
|
||||
@@ -1165,4 +1165,13 @@ export default {
|
||||
'Convert the numbers': '换算数值',
|
||||
'Keep the numbers, change the label': '保留数值,只改标签',
|
||||
'Switching the unit offers to convert every stored weight.': '切换单位时会提示换算所有已保存的重量。',
|
||||
'Update to {0}?': '更新到 {0}?',
|
||||
'The latest version will be downloaded and the installer will open.': '将下载最新版本并打开安装程序。',
|
||||
'Download & Install': '下载并安装',
|
||||
'Update failed: {0}': '更新失败:{0}',
|
||||
'openGym v{0} available': 'openGym v{0} 可用',
|
||||
'Starting download…': '正在开始下载…',
|
||||
'Downloading update…': '正在下载更新…',
|
||||
'{0} %': '{0}%',
|
||||
'{0} MB': '{0} MB',
|
||||
}
|
||||
@@ -38,7 +38,7 @@ vi.mock('../lib/api.js', () => ({
|
||||
}))
|
||||
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
|
||||
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
|
||||
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
|
||||
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))
|
||||
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
|
||||
vi.mock('../sheets.jsx', () => ({
|
||||
starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useEffect, useRef, useState, forwardRef } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useStore, DEF, hasData } from '../store/useStore.js'
|
||||
import { workoutControls } from '../lib/workout-controls.js'
|
||||
@@ -11,7 +11,8 @@ import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/pus
|
||||
import { wakeLockSupported } from '../lib/wakelock.js'
|
||||
import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js'
|
||||
import { DEMO, REPO } from '../lib/demo.js'
|
||||
import { MOBILE, shareExport, syncReminder } from '../lib/mobile.js'
|
||||
import { MOBILE, isAndroid, shareExport, syncReminder } from '../lib/mobile.js'
|
||||
import { checkForUpdate, downloadAndInstall } from '../lib/update.js'
|
||||
import { ConnectSheet } from './MobileOnboarding.jsx'
|
||||
import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet, menuSheet } from '../sheets.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
@@ -43,6 +44,60 @@ export default function Settings() {
|
||||
})
|
||||
}
|
||||
|
||||
// --- update check state ---
|
||||
const [updateInfo, setUpdateInfo] = useState(null) // { hasUpdate, latestVersion, apkUrl, hashUrl } | null
|
||||
|
||||
useEffect(() => {
|
||||
// The in-app updater installs an .apk, so it only applies to the native Android build.
|
||||
// On iOS and the web this check is skipped and the update row never appears. isAndroid()
|
||||
// already answers false off the mobile build; the MOBILE check on top keeps the web bundle
|
||||
// from even asking (and from calling gitlab.com on every Settings visit).
|
||||
if (!MOBILE) return
|
||||
isAndroid().then(ok => { if (ok) checkForUpdate().then(setUpdateInfo).catch(() => {}) })
|
||||
}, [])
|
||||
|
||||
const onUpdateRowClick = () => {
|
||||
if (!updateInfo?.hasUpdate) return
|
||||
if (updateInfo.apkUrl) {
|
||||
// Start download & install
|
||||
const version = updateInfo.latestVersion
|
||||
confirmSheet({
|
||||
title: t('Update to {0}?', version),
|
||||
message: t('The latest version will be downloaded and the installer will open.'),
|
||||
confirmText: t('Download & Install'),
|
||||
onConfirm: async () => {
|
||||
// Open a progress sheet
|
||||
let closeProgress = null
|
||||
let setProgress = null
|
||||
useUI.getState().openSheet(close => {
|
||||
closeProgress = close
|
||||
return <DownloadProgress ref={fn => { setProgress = fn }} />
|
||||
}, { locked: true })
|
||||
try {
|
||||
// Fetch the expected SHA-256 hash if available
|
||||
let expectedHash = null
|
||||
if (updateInfo.hashUrl) {
|
||||
try {
|
||||
const hashRes = await fetch(updateInfo.hashUrl)
|
||||
if (hashRes.ok) expectedHash = (await hashRes.text()).split(/\s/)[0]
|
||||
} catch (e) { /* proceed without hash verification */ }
|
||||
}
|
||||
await downloadAndInstall(updateInfo.apkUrl, expectedHash, (received, total) => {
|
||||
if (setProgress) setProgress(received, total)
|
||||
})
|
||||
if (closeProgress) closeProgress()
|
||||
} catch (e) {
|
||||
if (closeProgress) closeProgress()
|
||||
toast(t('Update failed: {0}', e.message))
|
||||
}
|
||||
},
|
||||
})
|
||||
} else {
|
||||
// Update available but no APK asset — open the releases page
|
||||
window.open('https://gitlab.com/DuarteSantos8/opengym/-/releases', '_blank', 'noopener')
|
||||
}
|
||||
}
|
||||
|
||||
const doExport = async () => {
|
||||
const json = JSON.stringify(S, null, 2)
|
||||
const name = 'opengym-backup-' + todayISO() + '.json'
|
||||
@@ -261,6 +316,9 @@ export default function Settings() {
|
||||
|
||||
{/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */}
|
||||
<Section title={t('Data')}>
|
||||
{MOBILE && updateInfo?.hasUpdate && <Row icon="info" iconTint="var(--purple)" title={t('openGym v{0} available', updateInfo.latestVersion)}
|
||||
accessory="chevron"
|
||||
onClick={onUpdateRowClick} />}
|
||||
<Row icon="sparkles" iconTint="var(--acc)" title={t('Load starter plan')} accessory="chevron" onClick={starterPlanSheet} />
|
||||
<Row icon="shuffle" iconTint="var(--teal)" title={t('Import from another app')}
|
||||
subtitle={t('FitNotes, Strong, Hevy — or body weight from Apple Health')}
|
||||
@@ -344,6 +402,32 @@ function workoutControlsSheet() {
|
||||
useUI.getState().openSheet(() => <WorkoutControlsSheet />)
|
||||
}
|
||||
|
||||
// Download progress sheet — receives a ref callback that exposes a (received, total) setter.
|
||||
// Uses forwardRef so the caller can push byte counts in without re-rendering the whole Settings tree.
|
||||
const DownloadProgress = forwardRef(function DownloadProgress(_, ref) {
|
||||
const [pct, setPct] = useState(0)
|
||||
const [text, setText] = useState(t('Starting download…'))
|
||||
// Expose a setter the caller can invoke directly
|
||||
if (ref) ref(function update(received, total) {
|
||||
if (total > 0) {
|
||||
const p = Math.min(100, Math.round((received / total) * 100))
|
||||
setPct(p)
|
||||
setText(t('{0} %', p))
|
||||
} else {
|
||||
setText(t('{0} MB', (received / 1_000_000).toFixed(1)))
|
||||
}
|
||||
})
|
||||
return (
|
||||
<div style={{ textAlign: 'center', padding: '8px 0' }}>
|
||||
<h3>{t('Downloading update…')}</h3>
|
||||
<div style={{ margin: '16px 0', height: 6, borderRadius: 3, background: 'var(--fill-3)', overflow: 'hidden' }}>
|
||||
<div style={{ height: '100%', width: pct + '%', background: 'var(--acc)', borderRadius: 3, transition: 'width .2s' }} />
|
||||
</div>
|
||||
<div className="muted small">{text}</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
function effortHelpSheet() {
|
||||
useUI.getState().openSheet(close => <>
|
||||
<h3>{t('Effort per set')}</h3>
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
// @vitest-environment happy-dom
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import Settings from './Settings.jsx'
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
// The updater downloads an .apk and hands it to the Android package installer, so its row
|
||||
// may only ever show on the native Android build: never on the web, never on iOS. Each test
|
||||
// flips the two gates (MOBILE flag, Capacitor platform) and watches whether Settings even
|
||||
// asks gitlab.com for the latest release.
|
||||
const mocks = vi.hoisted(() => {
|
||||
const state = { S: null, MOBILE: false, android: false }
|
||||
state.snapshot = () => ({
|
||||
S: state.S,
|
||||
user: null,
|
||||
update: mut => {
|
||||
const next = structuredClone(state.S)
|
||||
mut(next)
|
||||
state.S = next
|
||||
},
|
||||
replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(),
|
||||
signOut: vi.fn(), signOutAll: vi.fn(), resetDemo: vi.fn(), disconnectServer: vi.fn(),
|
||||
})
|
||||
state.checkForUpdate = vi.fn(() => Promise.resolve({ hasUpdate: true, latestVersion: '9.9.9', apkUrl: 'https://x/opengym.apk', hashUrl: null }))
|
||||
state.confirmSheet = vi.fn()
|
||||
return state
|
||||
})
|
||||
vi.mock('../store/useStore.js', () => {
|
||||
const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
|
||||
useStore.getState = mocks.snapshot
|
||||
return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
|
||||
})
|
||||
vi.mock('../store/useUI.js', () => {
|
||||
const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })
|
||||
const useUI = selector => selector ? selector(snap()) : snap()
|
||||
useUI.getState = snap
|
||||
return { useUI }
|
||||
})
|
||||
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
|
||||
vi.mock('../lib/api.js', () => ({
|
||||
api: vi.fn(), webauthnOK: () => false, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), IS_ANDROID: false,
|
||||
}))
|
||||
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
|
||||
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
|
||||
// MOBILE is read at render time through a getter so one module mock serves both builds.
|
||||
vi.mock('../lib/mobile.js', () => ({
|
||||
get MOBILE() { return mocks.MOBILE },
|
||||
isAndroid: () => Promise.resolve(mocks.android),
|
||||
shareExport: vi.fn(), syncReminder: vi.fn(),
|
||||
}))
|
||||
vi.mock('../lib/update.js', () => ({
|
||||
checkForUpdate: (...a) => mocks.checkForUpdate(...a),
|
||||
downloadAndInstall: vi.fn(),
|
||||
}))
|
||||
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
|
||||
vi.mock('../sheets.jsx', () => ({
|
||||
starterPlanSheet: vi.fn(), confirmSheet: (...a) => mocks.confirmSheet(...a), importFromApp: vi.fn(),
|
||||
importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: vi.fn(),
|
||||
}))
|
||||
|
||||
globalThis.__APP_VERSION__ ??= 'test'
|
||||
|
||||
let host, root
|
||||
beforeEach(() => {
|
||||
mocks.S = {
|
||||
unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none',
|
||||
gifSize: 'full', workouts: [], routines: [], exWeights: {},
|
||||
}
|
||||
mocks.MOBILE = false
|
||||
mocks.android = false
|
||||
mocks.checkForUpdate.mockClear()
|
||||
mocks.confirmSheet.mockClear()
|
||||
host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
root = createRoot(host)
|
||||
})
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
host.remove()
|
||||
})
|
||||
|
||||
// The effect resolves two promises (isAndroid, then checkForUpdate) before the row can render.
|
||||
const mount = async () => {
|
||||
await act(async () => { root.render(<Settings />) })
|
||||
await act(async () => { await Promise.resolve(); await Promise.resolve() })
|
||||
}
|
||||
const updateRow = () => [...host.querySelectorAll('.lrow')].find(r => r.textContent.includes('openGym v9.9.9 available'))
|
||||
|
||||
describe('Settings — in-app update check', () => {
|
||||
it('web build: never asks for releases and shows no update row', async () => {
|
||||
await mount()
|
||||
expect(mocks.checkForUpdate).not.toHaveBeenCalled()
|
||||
expect(updateRow()).toBeUndefined()
|
||||
})
|
||||
|
||||
it('mobile build on iOS: no check, no row', async () => {
|
||||
mocks.MOBILE = true
|
||||
await mount()
|
||||
expect(mocks.checkForUpdate).not.toHaveBeenCalled()
|
||||
expect(updateRow()).toBeUndefined()
|
||||
})
|
||||
|
||||
it('mobile build on Android: checks once and shows the row, tapping it asks before downloading', async () => {
|
||||
mocks.MOBILE = true
|
||||
mocks.android = true
|
||||
await mount()
|
||||
expect(mocks.checkForUpdate).toHaveBeenCalledTimes(1)
|
||||
expect(updateRow()).toBeTruthy()
|
||||
act(() => { updateRow().click() })
|
||||
expect(mocks.confirmSheet).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.confirmSheet.mock.calls[0][0].title).toBe('Update to 9.9.9?')
|
||||
})
|
||||
|
||||
it('Android without a newer release: no row', async () => {
|
||||
mocks.MOBILE = true
|
||||
mocks.android = true
|
||||
mocks.checkForUpdate.mockResolvedValueOnce({ hasUpdate: false, latestVersion: 'test', apkUrl: null, hashUrl: null })
|
||||
await mount()
|
||||
expect(mocks.checkForUpdate).toHaveBeenCalledTimes(1)
|
||||
expect(updateRow()).toBeUndefined()
|
||||
})
|
||||
|
||||
it('Android when gitlab.com is unreachable: stays quiet', async () => {
|
||||
mocks.MOBILE = true
|
||||
mocks.android = true
|
||||
mocks.checkForUpdate.mockRejectedValueOnce(new Error('offline'))
|
||||
await mount()
|
||||
expect(updateRow()).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -38,7 +38,7 @@ vi.mock('../lib/api.js', () => ({
|
||||
}))
|
||||
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
|
||||
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
|
||||
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
|
||||
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))
|
||||
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
|
||||
vi.mock('../sheets.jsx', () => ({
|
||||
loadStarterPlan: vi.fn(), starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
|
||||
|
||||
@@ -41,7 +41,7 @@ vi.mock('../lib/api.js', () => ({
|
||||
}))
|
||||
vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
|
||||
vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
|
||||
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, shareExport: vi.fn(), syncReminder: vi.fn() }))
|
||||
vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))
|
||||
vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
|
||||
vi.mock('../sheets.jsx', () => ({
|
||||
starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
|
||||
|
||||
Reference in new issue
Block a user