Android-Back: @capacitor/app verdrahtet, Zurueck-Geste beendet die App nicht mehr

Capacitor 7 behandelt Zurueck gar nicht selbst, das macht @capacitor/app -- das
Plugin fehlte, also lief jede Zurueck-Geste an der WebView vorbei direkt in
finish(). Die History-Eintraege pro Sheet (#63) haben nur im Browser gewirkt.

Neu: lib/back.js entscheidet Sheet -> Seite -> zweimal Zurueck zum Beenden
(exitApp, weil das Plugin mit registriertem Listener nie mehr selbst beendet),
gesperrte Sheets schlucken Zurueck weiterhin. Version auf 1.2.8/versionCode 9.
This commit is contained in:
Duarte Santos committed 2026-08-19 16:30:32 +02:00
1 parent e69673d3cd
commit 19a441d93e
21 files changed
+215 -5

No files matched your search

+12
View File
@@ -1,5 +1,17 @@
# Changelog
## Unreleased
### Fixes
- ⬅️ **The back gesture no longer quits the app** (Android). The packaged app never listened for
the system back event at all — Capacitor leaves that to `@capacitor/app`, which was not
installed — so a back swipe went straight past the WebView and finished the activity from
wherever you were. The per-sheet history entries added in [#63] only ever did anything in a
browser tab. Back now dismisses the open sheet, then walks back through the screens you came
from, and only leaves the app after a second press at the root ("Press back again to exit").
A sheet that is locked mid-task still swallows back, as it does in the browser.
## v1.2.7 — 2026-08-18
The muscle map answers a third question. Balance showed where the volume went and Fatigue what was
+2 -2
View File
@@ -7,8 +7,8 @@ android {
applicationId "ch.duartesantos.opengym"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 8
versionName "1.2.7"
versionCode 9
versionName "1.2.8"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
@@ -9,6 +9,7 @@ android {
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-app')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-local-notifications')
implementation project(':capacitor-share')
@@ -2,6 +2,9 @@
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
include ':capacitor-app'
project(':capacitor-app').projectDir = new File('../node_modules/@capacitor/app/android')
include ':capacitor-filesystem'
project(':capacitor-filesystem').projectDir = new File('../node_modules/@capacitor/filesystem/android')
+1
View File
@@ -11,6 +11,7 @@ install! 'cocoapods', :disable_input_output_paths => true
def capacitor_pods
pod 'Capacitor', :path => '../../node_modules/@capacitor/ios'
pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios'
pod 'CapacitorApp', :path => '../../node_modules/@capacitor/app'
pod 'CapacitorFilesystem', :path => '../../node_modules/@capacitor/filesystem'
pod 'CapacitorLocalNotifications', :path => '../../node_modules/@capacitor/local-notifications'
pod 'CapacitorShare', :path => '../../node_modules/@capacitor/share'
+11 -2
View File
@@ -1,14 +1,15 @@
{
"name": "opengym-frontend",
"version": "1.2.6",
"version": "1.2.7",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opengym-frontend",
"version": "1.2.6",
"version": "1.2.7",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/app": "^7.1.2",
"@capacitor/core": "^7.6.8",
"@capacitor/filesystem": "^7.1.8",
"@capacitor/local-notifications": "^7.0.7",
@@ -62,6 +63,14 @@
"@capacitor/core": "^7.6.0"
}
},
"node_modules/@capacitor/app": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/@capacitor/app/-/app-7.1.2.tgz",
"integrity": "sha512-d4I/oF/PRu4megL7/IGKYfe5j7yzSON1FRFgq6kH+m5kH6g7V+wyjHRLauCzGNjdRx4S+nWOumINds0qcRBtKg==",
"peerDependencies": {
"@capacitor/core": ">=7.0.0"
}
},
"node_modules/@capacitor/assets": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/@capacitor/assets/-/assets-3.0.5.tgz",
+2 -1
View File
@@ -1,7 +1,7 @@
{
"name": "opengym-frontend",
"private": true,
"version": "1.2.7",
"version": "1.2.8",
"type": "module",
"scripts": {
"dev": "vite",
@@ -14,6 +14,7 @@
},
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/app": "^7.1.2",
"@capacitor/core": "^7.6.8",
"@capacitor/filesystem": "^7.1.8",
"@capacitor/local-notifications": "^7.0.7",
+7
View File
@@ -6,6 +6,7 @@ import { bindUI } from './components/ui.jsx'
import { ACCENTS } from './lib/format.js'
import { setLang, useLang } from './lib/i18n.js'
import { setNav } from './lib/nav.js'
import { initBackButton } from './lib/back.js'
import { useWakeLock } from './lib/wakelock.js'
import { startFlow } from './sheets.jsx'
import Icon from './components/Icon.jsx'
@@ -92,5 +93,11 @@ function Shell() {
export default function App() {
const boot = useStore(s => s.boot)
useEffect(() => { boot() }, [boot])
// Android system back — sheet, then page, then press-again-to-exit (see lib/back.js)
useEffect(() => {
let stop = null, gone = false
initBackButton().then(fn => { if (gone) fn(); else stop = fn })
return () => { gone = true; stop?.() }
}, [])
return <HashRouter><Shell /></HashRouter>
}
+62
View File
@@ -0,0 +1,62 @@
// Android system back (the gesture and the hardware/nav button are the same event).
//
// Capacitor's BridgeActivity does not handle back at all — without a JS listener the
// activity simply finishes, so a back swipe quit the app from anywhere, whatever the
// WebView history said. That made the sheet history entries from #63 dead weight in the
// packaged app: they only ever worked in a browser tab, where the browser walks history
// itself.
//
// Once a `backButton` listener exists, the plugin stops falling through to finish() —
// back can then ONLY leave the app through App.exitApp(), which is why the last step is
// an explicit press-again-to-exit rather than a silent no-op.
import { MOBILE } from './mobile.js'
import { useUI } from '../store/useUI.js'
import { t } from './i18n.js'
// How long a first back press stays armed as "press again to exit" (the toast shows 2.2s).
export const EXIT_WINDOW = 2000
// What a back press means, given what is on screen. Pure, so the table below is testable.
export function decideBack({ top, canGoBack, exitArmed }) {
if (top) return top.locked ? 'ignore' : 'sheet' // a locked sheet swallows back on purpose
if (canGoBack) return 'history' // a page/tab we pushed ourselves
return exitArmed ? 'exit' : 'arm-exit'
}
export function makeBackHandler({ getSheets, closeSheet, toast, goBack, exit, now = Date.now }) {
let armedAt = -Infinity
return (ev = {}) => {
const sheets = getSheets()
const action = decideBack({
top: sheets[sheets.length - 1],
canGoBack: !!ev.canGoBack,
exitArmed: now() - armedAt < EXIT_WINDOW,
})
if (action !== 'arm-exit') armedAt = -Infinity
if (action === 'sheet') closeSheet(sheets[sheets.length - 1].id)
else if (action === 'history') goBack()
else if (action === 'arm-exit') { armedAt = now(); toast(t('Press back again to exit')) }
else if (action === 'exit') exit()
return action
}
}
// Registers the listener for the native shell. No-op in web builds, where the browser
// (or the PWA shell) walks history on its own and there is no plugin to talk to.
export async function initBackButton() {
if (!MOBILE) return () => {}
try {
const { App } = await import('@capacitor/app')
const handler = makeBackHandler({
getSheets: () => useUI.getState().sheets,
closeSheet: id => useUI.getState().closeSheet(id),
toast: msg => useUI.getState().toast(msg),
goBack: () => window.history.back(),
exit: () => App.exitApp(),
})
const sub = await App.addListener('backButton', handler)
return () => sub.remove()
} catch (e) {
return () => {} // no plugin (older install): leave back to the default behaviour
}
}
+103
View File
@@ -0,0 +1,103 @@
// @vitest-environment happy-dom
import { describe, expect, it } from 'vitest'
import { decideBack, makeBackHandler, EXIT_WINDOW } from './back.js'
// Back on Android has to serve three layers with one event: the sheet stack on top, the
// page history under it, and — because a registered listener stops the plugin from ever
// finishing the activity itself — a deliberate way out of the app at the bottom.
describe('decideBack', () => {
it('dismisses the top sheet before touching history', () => {
expect(decideBack({ top: { id: 's1' }, canGoBack: true, exitArmed: false })).toBe('sheet')
})
it('lets a locked sheet swallow the press', () => {
expect(decideBack({ top: { id: 's1', locked: true }, canGoBack: true, exitArmed: true })).toBe('ignore')
})
it('walks history when nothing is open', () => {
expect(decideBack({ top: undefined, canGoBack: true, exitArmed: false })).toBe('history')
})
it('arms the exit at the bottom of the stack, and exits on the second press', () => {
expect(decideBack({ top: undefined, canGoBack: false, exitArmed: false })).toBe('arm-exit')
expect(decideBack({ top: undefined, canGoBack: false, exitArmed: true })).toBe('exit')
})
})
function harness() {
const calls = { closed: [], toasts: [], back: 0, exit: 0 }
let sheets = []
let now = 1000
const handler = makeBackHandler({
getSheets: () => sheets,
closeSheet: id => { calls.closed.push(id); sheets = sheets.filter(s => s.id !== id) },
toast: m => calls.toasts.push(m),
goBack: () => { calls.back++ },
exit: () => { calls.exit++ },
now: () => now,
})
return { calls, handler, setSheets: s => { sheets = s }, tick: ms => { now += ms } }
}
describe('makeBackHandler', () => {
it('closes stacked sheets one press at a time', () => {
const h = harness()
h.setSheets([{ id: 'a' }, { id: 'b' }])
expect(h.handler({ canGoBack: true })).toBe('sheet')
expect(h.handler({ canGoBack: true })).toBe('sheet')
expect(h.calls.closed).toEqual(['b', 'a'])
expect(h.calls.back).toBe(0)
})
it('does not close a locked sheet, and does not arm the exit behind it', () => {
const h = harness()
h.setSheets([{ id: 'a', locked: true }])
expect(h.handler({ canGoBack: false })).toBe('ignore')
expect(h.calls.closed).toEqual([])
expect(h.calls.toasts).toEqual([])
expect(h.calls.exit).toBe(0)
})
it('goes back a page while the WebView still has app history', () => {
const h = harness()
expect(h.handler({ canGoBack: true })).toBe('history')
expect(h.calls.back).toBe(1)
expect(h.calls.exit).toBe(0)
})
// The whole point of the fix: one press at the root must never be the end of the app.
it('warns once, then exits on a second press inside the window', () => {
const h = harness()
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
expect(h.calls.toasts).toHaveLength(1)
expect(h.calls.exit).toBe(0)
h.tick(EXIT_WINDOW - 1)
expect(h.handler({ canGoBack: false })).toBe('exit')
expect(h.calls.exit).toBe(1)
})
it('re-arms rather than exiting once the window has passed', () => {
const h = harness()
h.handler({ canGoBack: false })
h.tick(EXIT_WINDOW + 1)
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
expect(h.calls.exit).toBe(0)
expect(h.calls.toasts).toHaveLength(2)
})
// A sheet opened (or a page pushed) after the warning means the user is still using the
// app — the next back belongs to that sheet, and the one after must warn again.
it('disarms the exit as soon as another press does real work', () => {
const h = harness()
h.handler({ canGoBack: false })
h.setSheets([{ id: 'a' }])
expect(h.handler({ canGoBack: true })).toBe('sheet')
expect(h.handler({ canGoBack: false })).toBe('arm-exit')
expect(h.calls.exit).toBe(0)
})
it('treats a missing event payload as no history', () => {
const h = harness()
expect(h.handler()).toBe('arm-exit')
})
})
+1
View File
@@ -3,6 +3,7 @@ export default {
// --- generic ---
'Confirm': 'Bestätigen',
'Cancel': 'Abbrechen',
'Press back again to exit': 'Zum Beenden erneut zurück drücken',
'Delete': 'Löschen',
'Save': 'Speichern',
'Import': 'Importieren',
+1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Confirmar',
'Cancel': 'Cancelar',
'Press back again to exit': 'Pulsa atrás otra vez para salir',
'Delete': 'Eliminar',
'Save': 'Guardar',
'Import': 'Importar',
+1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Confirmer',
'Cancel': 'Annuler',
'Press back again to exit': 'Appuyez de nouveau pour quitter',
'Delete': 'Supprimer',
'Save': 'Enregistrer',
'Import': 'Importer',
+1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'पुष्टि करें',
'Cancel': 'रद्द करें',
'Press back again to exit': 'बाहर निकलने के लिए फिर से बैक दबाएँ',
'Delete': 'हटाएँ',
'Save': 'सहेजें',
'Import': 'आयात करें',
+1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Conferma',
'Cancel': 'Annulla',
'Press back again to exit': 'Premi di nuovo indietro per uscire',
'Delete': 'Elimina',
'Save': 'Salva',
'Import': 'Importa',
+1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': '확인',
'Cancel': '취소',
'Press back again to exit': '뒤로를 한 번 더 누르면 종료됩니다',
'Delete': '삭제',
'Save': '저장',
'Import': '가져오기',
+1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Potwierdź',
'Cancel': 'Anuluj',
'Press back again to exit': 'Naciśnij wstecz ponownie, aby wyjść',
'Delete': 'Usuń',
'Save': 'Zapisz',
'Import': 'Importuj',
+1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Confirmar',
'Cancel': 'Cancelar',
'Press back again to exit': 'Prima novamente para sair',
'Delete': 'Eliminar',
'Save': 'Guardar',
'Import': 'Importar',
+1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Подтвердить',
'Cancel': 'Отмена',
'Press back again to exit': 'Нажмите «Назад» ещё раз, чтобы выйти',
'Delete': 'Удалить',
'Save': 'Сохранить',
'Import': 'Импорт',
+1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': 'Onayla',
'Cancel': 'İptal',
'Press back again to exit': 'Çıkmak için geri tuşuna tekrar basın',
'Delete': 'Sil',
'Save': 'Kaydet',
'Import': 'İçe aktar',
+1
View File
@@ -2,6 +2,7 @@
export default {
'Confirm': '确认',
'Cancel': '取消',
'Press back again to exit': '再按一次返回退出',
'Delete': '删除',
'Save': '保存',
'Import': '导入',