main init
This commit is contained in:
53
Library/mobile/kit/lifecycle.ts
Normal file
53
Library/mobile/kit/lifecycle.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
// Kit lifecycle (v1) - Android back button and app pause/resume. From _Tools\Library\mobile\kit.
|
||||
// Needs @capacitor/app. On web: back = Escape key, pause/resume = visibilitychange.
|
||||
//
|
||||
// onBack(() => closeTopPanel() || confirmExit()); // return true when handled
|
||||
// onPause(() => { persist(); }); onResume(() => { ... });
|
||||
// exitApp();
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
import { App } from "@capacitor/app";
|
||||
|
||||
const backHandlers: Array<() => boolean> = [];
|
||||
|
||||
/** Handlers run newest first; the first that returns true stops the chain.
|
||||
* If none handles it, the app is minimised (Android convention) instead of closed. */
|
||||
export function onBack(fn: () => boolean): () => void {
|
||||
backHandlers.push(fn);
|
||||
return () => {
|
||||
const i = backHandlers.indexOf(fn);
|
||||
if (i >= 0) backHandlers.splice(i, 1);
|
||||
};
|
||||
}
|
||||
|
||||
function runBack(): void {
|
||||
for (let i = backHandlers.length - 1; i >= 0; i--) if (backHandlers[i]()) return;
|
||||
if (Capacitor.isNativePlatform()) void App.minimizeApp().catch(() => {});
|
||||
}
|
||||
|
||||
if (Capacitor.isNativePlatform()) {
|
||||
void App.addListener("backButton", runBack);
|
||||
} else {
|
||||
addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape") runBack();
|
||||
});
|
||||
}
|
||||
|
||||
/** App goes to background: SAVE HERE - Android may kill the process without another event. */
|
||||
export function onPause(fn: () => void): void {
|
||||
if (Capacitor.isNativePlatform()) void App.addListener("pause", fn);
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.hidden) fn();
|
||||
});
|
||||
}
|
||||
|
||||
export function onResume(fn: () => void): void {
|
||||
if (Capacitor.isNativePlatform()) void App.addListener("resume", fn);
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!document.hidden) fn();
|
||||
});
|
||||
}
|
||||
|
||||
export function exitApp(): void {
|
||||
if (Capacitor.isNativePlatform()) void App.exitApp();
|
||||
}
|
||||
Reference in New Issue
Block a user