main init
This commit is contained in:
114
Library/mobile/kit/ads.ts
Normal file
114
Library/mobile/kit/ads.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
// Kit ads (v1) - AdMob rewarded ads with Google UMP consent (EEA/UK).
|
||||
// From _Tools\Library\mobile\kit (XP-Battleship/src/ads.ts). Needs @capacitor-community/admob.
|
||||
//
|
||||
// configureAds({ testing: false, rewarded: { revive: "ca-app-pub-xxx/yyy", double: "..." } });
|
||||
// await initAds(); // at boot (native only, no-op on web)
|
||||
// if (await showRewarded("revive")) grant();
|
||||
// if (needsPrivacyOptions()) show an "Ad settings" button -> showPrivacyOptions()
|
||||
//
|
||||
// Consent gathering is inert until a GDPR message AND a privacy-options form are published for
|
||||
// the app in the AdMob console. TESTING must be false in the Play-Store build.
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
import { resumeAudio, suspendAudio } from "./audio";
|
||||
|
||||
const TEST_REWARDED_ID = "ca-app-pub-3940256099942544/5224354917"; // Google's official test unit
|
||||
|
||||
const cfg: { testing: boolean; rewarded: Record<string, string> } = { testing: true, rewarded: {} };
|
||||
|
||||
export function configureAds(c: { testing: boolean; rewarded: Record<string, string> }): void {
|
||||
cfg.testing = c.testing;
|
||||
cfg.rewarded = c.rewarded;
|
||||
}
|
||||
|
||||
let initialized = false;
|
||||
let adShowing = false;
|
||||
let privacyOptionsRequired = false;
|
||||
|
||||
/** Fails open on purpose (no network, no published message) - only an explicit
|
||||
* canRequestAds:false (user declined) disables ads. */
|
||||
async function gatherConsent(): Promise<boolean> {
|
||||
const { AdMob, AdmobConsentStatus } = await import("@capacitor-community/admob");
|
||||
try {
|
||||
let info = await AdMob.requestConsentInfo();
|
||||
if (info.isConsentFormAvailable && info.status === AdmobConsentStatus.REQUIRED) {
|
||||
info = await AdMob.showConsentForm();
|
||||
}
|
||||
// enum not re-exported from the plugin entry point - compare the string value
|
||||
privacyOptionsRequired = String(info.privacyOptionsRequirementStatus) === "REQUIRED";
|
||||
return info.canRequestAds !== false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export function needsPrivacyOptions(): boolean {
|
||||
return privacyOptionsRequired;
|
||||
}
|
||||
|
||||
/** Google requires this entry point to stay reachable after the first consent decision. */
|
||||
export async function showPrivacyOptions(): Promise<void> {
|
||||
if (!Capacitor.isNativePlatform()) return;
|
||||
const { AdMob } = await import("@capacitor-community/admob");
|
||||
await AdMob.showPrivacyOptionsForm();
|
||||
}
|
||||
|
||||
/** True while an ad covers the game - pause the game loop. */
|
||||
export function isAdShowing(): boolean {
|
||||
return adShowing;
|
||||
}
|
||||
|
||||
export async function initAds(): Promise<void> {
|
||||
if (!Capacitor.isNativePlatform() || initialized) return;
|
||||
if (!(await gatherConsent())) return; // consent BEFORE any ad request
|
||||
const { AdMob } = await import("@capacitor-community/admob");
|
||||
await AdMob.initialize({ initializeForTesting: cfg.testing });
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
/** Resolves true if the reward was earned. On web (dev) always grants after a short delay. */
|
||||
export async function showRewarded(placement: string): Promise<boolean> {
|
||||
if (!Capacitor.isNativePlatform()) {
|
||||
await new Promise((r) => setTimeout(r, 600));
|
||||
return true;
|
||||
}
|
||||
if (!initialized) {
|
||||
// a transient failure at boot must not disable ads for the whole session
|
||||
await initAds().catch(() => {});
|
||||
if (!initialized) return false;
|
||||
}
|
||||
const adId = cfg.testing ? TEST_REWARDED_ID : cfg.rewarded[placement];
|
||||
if (!adId) return false;
|
||||
const { AdMob, RewardAdPluginEvents } = await import("@capacitor-community/admob");
|
||||
// the ad is a native activity above the WebView: the page never sees visibilitychange
|
||||
adShowing = true;
|
||||
suspendAudio();
|
||||
try {
|
||||
await AdMob.prepareRewardVideoAd({ adId });
|
||||
return await new Promise<boolean>((resolve) => {
|
||||
let rewarded = false;
|
||||
let settled = false;
|
||||
const subs: Array<Promise<{ remove: () => Promise<void> }>> = [];
|
||||
// single exit, runs once - a path that never clears adShowing freezes the game for good
|
||||
const done = (result: boolean): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(watchdog);
|
||||
for (const s of subs) void s.then((h) => h.remove()).catch(() => {});
|
||||
adShowing = false;
|
||||
resumeAudio();
|
||||
resolve(result);
|
||||
};
|
||||
subs.push(AdMob.addListener(RewardAdPluginEvents.Rewarded, () => { rewarded = true; }));
|
||||
subs.push(AdMob.addListener(RewardAdPluginEvents.Dismissed, () => done(rewarded)));
|
||||
subs.push(AdMob.addListener(RewardAdPluginEvents.FailedToShow, () => done(rewarded)));
|
||||
// backstop for a Dismissed event the SDK never delivers - un-freezes, never cuts an ad short
|
||||
const watchdog = setTimeout(() => done(rewarded), 300_000);
|
||||
AdMob.showRewardVideoAd().catch(() => done(false));
|
||||
});
|
||||
} catch {
|
||||
adShowing = false;
|
||||
resumeAudio();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
196
Library/mobile/kit/audio.ts
Normal file
196
Library/mobile/kit/audio.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
// Kit audio (v1) - WebAudio music + SFX for Vite/Capacitor apps. From _Tools\Library\mobile\kit.
|
||||
// Generalised from XP-Battleship/src/audio.ts. Everything is best effort: missing files or a
|
||||
// locked AudioContext never throw.
|
||||
//
|
||||
// configureAudio({ base: "/assets/audio/", storageKey: "mygame", preload: ["sfx_click"],
|
||||
// throttle: { sfx_laser: 90 } });
|
||||
// initAudio(); // from the first user gesture (autoplay policy)
|
||||
// playMusic("music_game"); playSfx("sfx_click", 0.8); toggleMute(); setVolumes(0.35, 1);
|
||||
|
||||
interface AudioConfig {
|
||||
base: string;
|
||||
ext: string;
|
||||
storageKey: string;
|
||||
preload: string[];
|
||||
throttle: Record<string, number>;
|
||||
}
|
||||
|
||||
const cfg: AudioConfig = { base: "/assets/audio/", ext: ".mp3", storageKey: "app", preload: [], throttle: {} };
|
||||
|
||||
let ctx: AudioContext | null = null;
|
||||
let musicGain: GainNode | null = null;
|
||||
let sfxGain: GainNode | null = null;
|
||||
let musicSource: AudioBufferSourceNode | null = null;
|
||||
let currentMusic: string | null = null;
|
||||
let muted = false;
|
||||
let musicVol = 0.35;
|
||||
let sfxVol = 1;
|
||||
|
||||
const buffers = new Map<string, AudioBuffer>();
|
||||
const loading = new Map<string, Promise<AudioBuffer | null>>();
|
||||
const lastPlayed = new Map<string, number>();
|
||||
|
||||
function muteKey(): string {
|
||||
return `${cfg.storageKey}_muted`;
|
||||
}
|
||||
|
||||
export function configureAudio(c: Partial<AudioConfig>): void {
|
||||
Object.assign(cfg, c);
|
||||
try {
|
||||
muted = localStorage.getItem(muteKey()) === "1";
|
||||
} catch {
|
||||
muted = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Suspend while hidden, resume on return - Android otherwise leaves the context suspended
|
||||
// after backgrounding, silencing the game for good.
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!ctx) return;
|
||||
if (document.hidden) void ctx.suspend().catch(() => {});
|
||||
else void ctx.resume().catch(() => {});
|
||||
});
|
||||
|
||||
function loadBuffer(name: string): Promise<AudioBuffer | null> {
|
||||
if (!ctx) return Promise.resolve(null);
|
||||
const done = buffers.get(name);
|
||||
if (done) return Promise.resolve(done);
|
||||
const inflight = loading.get(name); // parallel callers share one fetch
|
||||
if (inflight) return inflight;
|
||||
const p = (async (): Promise<AudioBuffer | null> => {
|
||||
try {
|
||||
const res = await fetch(`${cfg.base}${name}${cfg.ext}`);
|
||||
if (!res.ok) return null;
|
||||
const buf = await ctx!.decodeAudioData(await res.arrayBuffer());
|
||||
buffers.set(name, buf);
|
||||
return buf;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
loading.delete(name);
|
||||
}
|
||||
})();
|
||||
loading.set(name, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Call from a user gesture. Safe to call repeatedly. */
|
||||
export function initAudio(): void {
|
||||
if (ctx) {
|
||||
void ctx.resume().catch(() => {});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ctx = new AudioContext();
|
||||
musicGain = ctx.createGain();
|
||||
musicGain.gain.value = muted ? 0 : musicVol;
|
||||
musicGain.connect(ctx.destination);
|
||||
sfxGain = ctx.createGain();
|
||||
sfxGain.gain.value = muted ? 0 : sfxVol;
|
||||
sfxGain.connect(ctx.destination);
|
||||
for (const n of cfg.preload) void loadBuffer(n);
|
||||
} catch {
|
||||
ctx = null;
|
||||
}
|
||||
}
|
||||
|
||||
export function playMusic(name: string): void {
|
||||
if (!ctx || !musicGain || currentMusic === name) return;
|
||||
currentMusic = name;
|
||||
void ctx.resume().catch(() => {});
|
||||
void loadBuffer(name).then((buf) => {
|
||||
if (!ctx || !musicGain || currentMusic !== name) return; // another track requested meanwhile
|
||||
if (!buf) {
|
||||
currentMusic = null; // allow a retry later
|
||||
return;
|
||||
}
|
||||
musicSource?.stop();
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf;
|
||||
src.loop = true;
|
||||
src.connect(musicGain);
|
||||
src.start();
|
||||
musicSource = src;
|
||||
});
|
||||
}
|
||||
|
||||
export function stopMusic(): void {
|
||||
currentMusic = null;
|
||||
musicSource?.stop();
|
||||
musicSource = null;
|
||||
}
|
||||
|
||||
export function playSfx(name: string, volume = 1): void {
|
||||
if (!ctx || !sfxGain || muted) return;
|
||||
// mobile browsers suspend the context between plays far more readily than desktop
|
||||
void ctx.resume().catch(() => {});
|
||||
const gap = cfg.throttle[name] ?? 0;
|
||||
const now = performance.now();
|
||||
if (gap && now - (lastPlayed.get(name) ?? 0) < gap) return;
|
||||
lastPlayed.set(name, now);
|
||||
const buf = buffers.get(name);
|
||||
if (buf) {
|
||||
playBuffer(buf, volume);
|
||||
return;
|
||||
}
|
||||
// not preloaded: decode once, THEN play - otherwise the first use of a rare clip is silent
|
||||
void loadBuffer(name).then((decoded) => {
|
||||
if (decoded && ctx && sfxGain && !muted) playBuffer(decoded, volume);
|
||||
});
|
||||
}
|
||||
|
||||
function playBuffer(buf: AudioBuffer, volume: number): void {
|
||||
if (!ctx || !sfxGain) return;
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf;
|
||||
const g = ctx.createGain();
|
||||
g.gain.value = volume;
|
||||
src.connect(g);
|
||||
g.connect(sfxGain);
|
||||
src.start();
|
||||
}
|
||||
|
||||
/** Hard pause (rewarded ad showing, app hidden). */
|
||||
export function suspendAudio(): void {
|
||||
if (ctx) void ctx.suspend().catch(() => {});
|
||||
}
|
||||
|
||||
export function resumeAudio(): void {
|
||||
if (ctx && !document.hidden) void ctx.resume().catch(() => {});
|
||||
}
|
||||
|
||||
export function isMuted(): boolean {
|
||||
return muted;
|
||||
}
|
||||
|
||||
export function toggleMute(): boolean {
|
||||
muted = !muted;
|
||||
try {
|
||||
localStorage.setItem(muteKey(), muted ? "1" : "0");
|
||||
} catch {
|
||||
// storage unavailable - setting lasts for this session only
|
||||
}
|
||||
applyGains();
|
||||
return muted;
|
||||
}
|
||||
|
||||
export function setVolumes(music: number, sfx: number): void {
|
||||
musicVol = music;
|
||||
sfxVol = sfx;
|
||||
applyGains();
|
||||
}
|
||||
|
||||
function applyGains(): void {
|
||||
if (musicGain) musicGain.gain.value = muted ? 0 : musicVol;
|
||||
if (sfxGain) sfxGain.gain.value = muted ? 0 : sfxVol;
|
||||
}
|
||||
|
||||
/** Fade music out under a big moment; unduck targets the CURRENT volume/mute state. */
|
||||
export function duckMusic(on: boolean): void {
|
||||
if (!ctx || !musicGain) return;
|
||||
void ctx.resume().catch(() => {});
|
||||
const now = ctx.currentTime;
|
||||
musicGain.gain.cancelScheduledValues(now);
|
||||
musicGain.gain.setValueAtTime(musicGain.gain.value, now);
|
||||
musicGain.gain.linearRampToValueAtTime(on ? 0 : muted ? 0 : musicVol, now + (on ? 0.15 : 0.3));
|
||||
}
|
||||
58
Library/mobile/kit/haptics.ts
Normal file
58
Library/mobile/kit/haptics.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
// Kit haptics (v1) - vibration pulses, silent no-op outside the native app.
|
||||
// From _Tools\Library\mobile\kit (XP-Battleship/src/haptics.ts). Needs @capacitor/haptics.
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
import { Haptics, ImpactStyle } from "@capacitor/haptics";
|
||||
|
||||
let storageKey = "app_haptics_off";
|
||||
let off = false;
|
||||
|
||||
/** Per-device preference (like mute) - not part of the save / cloud sync. */
|
||||
export function configureHaptics(key: string): void {
|
||||
storageKey = `${key}_haptics_off`;
|
||||
try {
|
||||
off = localStorage.getItem(storageKey) === "1";
|
||||
} catch {
|
||||
off = false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isHapticsEnabled(): boolean {
|
||||
return !off;
|
||||
}
|
||||
|
||||
export function toggleHaptics(): boolean {
|
||||
off = !off;
|
||||
try {
|
||||
localStorage.setItem(storageKey, off ? "1" : "0");
|
||||
} catch {
|
||||
// session only
|
||||
}
|
||||
return !off;
|
||||
}
|
||||
|
||||
async function impact(style: ImpactStyle): Promise<void> {
|
||||
if (!Capacitor.isNativePlatform() || off) return;
|
||||
try {
|
||||
await Haptics.impact({ style });
|
||||
} catch {
|
||||
// unsupported device
|
||||
}
|
||||
}
|
||||
|
||||
let lastLight = 0;
|
||||
/** Frequent events - throttled so fast gameplay does not become constant buzzing. */
|
||||
export function hapticLight(throttleMs = 150): void {
|
||||
const now = performance.now();
|
||||
if (now - lastLight < throttleMs) return;
|
||||
lastLight = now;
|
||||
void impact(ImpactStyle.Light);
|
||||
}
|
||||
|
||||
export function hapticMedium(): void {
|
||||
void impact(ImpactStyle.Medium);
|
||||
}
|
||||
|
||||
export function hapticHeavy(): void {
|
||||
void impact(ImpactStyle.Heavy);
|
||||
}
|
||||
46
Library/mobile/kit/i18n.ts
Normal file
46
Library/mobile/kit/i18n.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
// Kit i18n (v1) - tiny translation helper. From _Tools\Library\mobile\kit.
|
||||
//
|
||||
// const en = { hello: "Hello {name}!", coins: "{n} coins" };
|
||||
// const de: Partial<typeof en> = { hello: "Hallo {name}!" }; // missing keys fall back to en
|
||||
// export const { t, lang, setLang, langs } = createI18n({ en, de }, "mygame_lang");
|
||||
// t("hello", { name: "Ana" })
|
||||
//
|
||||
// Language: saved choice, else the device language if available, else the first dictionary.
|
||||
// setLang() saves and reloads the page (all UI re-renders from scratch).
|
||||
|
||||
export function createI18n<D extends Record<string, string>>(
|
||||
dicts: { [lang: string]: Partial<D> } & { en: D },
|
||||
storageKey: string
|
||||
) {
|
||||
const langs = Object.keys(dicts);
|
||||
const pick = (): string => {
|
||||
try {
|
||||
const saved = localStorage.getItem(storageKey);
|
||||
if (saved && langs.includes(saved)) return saved;
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
const device = (navigator.language || "en").slice(0, 2).toLowerCase();
|
||||
return langs.includes(device) ? device : langs[0];
|
||||
};
|
||||
const lang = pick();
|
||||
const dict = dicts[lang] as Partial<D>;
|
||||
|
||||
function t(key: keyof D & string, vars?: Record<string, string | number>): string {
|
||||
let s = (dict[key] ?? dicts.en[key] ?? key) as string;
|
||||
if (vars) for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v));
|
||||
return s;
|
||||
}
|
||||
|
||||
function setLang(l: string): void {
|
||||
if (!langs.includes(l)) return;
|
||||
try {
|
||||
localStorage.setItem(storageKey, l);
|
||||
} catch {
|
||||
// session only
|
||||
}
|
||||
location.reload();
|
||||
}
|
||||
|
||||
return { t, lang, setLang, langs };
|
||||
}
|
||||
99
Library/mobile/kit/iap.ts
Normal file
99
Library/mobile/kit/iap.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
// Kit IAP (v1) - Google Play one-off purchases via cordova-plugin-purchase (CdvPurchase v13).
|
||||
// From _Tools\Library\mobile\kit (XP-Battleship/src/iap.ts). Native only; on web every call
|
||||
// resolves to "not bought".
|
||||
//
|
||||
// configureIap({ nonConsumable: ["premium_ship_1", "remove_ads"] });
|
||||
// const owned = await restorePurchases(); // every app start
|
||||
// const r = await purchase("remove_ads"); // "owned" | "failed" | "pending"
|
||||
// productPrice("remove_ads") ?? "2,99 €" // Play's localized price, or your fallback
|
||||
//
|
||||
// SKUs must exist as ACTIVE in-app products in the Play Console. Purchases only work in builds
|
||||
// installed from Play (internal test track and up) - sideloaded debug builds get an empty store.
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
type Cdv = any; // runtime global from the plugin
|
||||
|
||||
let skus: string[] = [];
|
||||
export function configureIap(c: { nonConsumable: string[] }): void {
|
||||
skus = c.nonConsumable;
|
||||
}
|
||||
|
||||
function cdv(): Cdv | null {
|
||||
return (window as unknown as Record<string, unknown>).CdvPurchase ?? null;
|
||||
}
|
||||
|
||||
let initPromise: Promise<boolean> | null = null;
|
||||
|
||||
function ensureStore(): Promise<boolean> {
|
||||
if (!Capacitor.isNativePlatform() || !cdv() || !skus.length) return Promise.resolve(false);
|
||||
if (!initPromise) {
|
||||
initPromise = (async (): Promise<boolean> => {
|
||||
const { store, ProductType, Platform } = cdv();
|
||||
store.register(skus.map((id) => ({ id, type: ProductType.NON_CONSUMABLE, platform: Platform.GOOGLE_PLAY })));
|
||||
store.when().approved((tx: Cdv) => tx.finish()); // Play already guarantees payment
|
||||
store.error(() => { initPromise = null; }); // billing disconnect: re-register next call
|
||||
await store.initialize([Platform.GOOGLE_PLAY]);
|
||||
return true;
|
||||
})().catch(() => {
|
||||
// never cache a failure: one offline launch must not disable buying for the session
|
||||
initPromise = null;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
return initPromise;
|
||||
}
|
||||
|
||||
/** `pending` = Play accepted the order but ownership has not arrived yet. Do NOT report it as
|
||||
* a failure - that is how paying customers get told "not completed" and ask for refunds. */
|
||||
export type PurchaseResult = "owned" | "failed" | "pending";
|
||||
|
||||
export async function purchase(sku: string): Promise<PurchaseResult> {
|
||||
if (!(await ensureStore())) return "failed";
|
||||
const { store, Platform } = cdv();
|
||||
try {
|
||||
const offer = store.get(sku, Platform.GOOGLE_PLAY)?.getOffer();
|
||||
if (!offer) return "failed";
|
||||
const err = await offer.order();
|
||||
if (err) return "failed"; // cancelled or declined
|
||||
const t0 = Date.now();
|
||||
while (Date.now() - t0 < 60_000) {
|
||||
if (store.get(sku, Platform.GOOGLE_PLAY)?.owned) return "owned";
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
}
|
||||
try {
|
||||
await store.restorePurchases();
|
||||
if (store.get(sku, Platform.GOOGLE_PLAY)?.owned) return "owned";
|
||||
} catch {
|
||||
// offline
|
||||
}
|
||||
return "pending";
|
||||
} catch {
|
||||
return "failed";
|
||||
}
|
||||
}
|
||||
|
||||
/** Play's localized price ("2,99 €", "$3.49"), or null while unknown. */
|
||||
export function productPrice(sku: string): string | null {
|
||||
if (!Capacitor.isNativePlatform() || !cdv()) return null;
|
||||
try {
|
||||
const { store, Platform } = cdv();
|
||||
const product = store.get(sku, Platform.GOOGLE_PLAY);
|
||||
return product?.getOffer()?.pricingPhases?.[0]?.price ?? product?.pricing?.price ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** SKUs the player owns (restore flow - run on every app start). */
|
||||
export async function restorePurchases(): Promise<string[]> {
|
||||
if (!(await ensureStore())) return [];
|
||||
const { store, Platform } = cdv();
|
||||
try {
|
||||
await store.restorePurchases();
|
||||
} catch {
|
||||
// offline - Play's local cache still answers below
|
||||
}
|
||||
return skus.filter((sku) => store.get(sku, Platform.GOOGLE_PLAY)?.owned);
|
||||
}
|
||||
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();
|
||||
}
|
||||
112
Library/mobile/kit/save.ts
Normal file
112
Library/mobile/kit/save.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
// Kit save (v1) - versioned localStorage save with backup slot. From _Tools\Library\mobile\kit.
|
||||
// Generalised from XP-Battleship/src/game/save.ts (lessons: cloud/RTDB drops empty arrays,
|
||||
// NaN poisons everything, a truncated write must not wipe progress, failures must be visible).
|
||||
//
|
||||
// interface Save { v: number; coins: number; owned: string[]; stats: { runs: number } }
|
||||
// const saves = createSaveStore<Save>({
|
||||
// key: "mygame_save", version: 2,
|
||||
// defaults: () => ({ v: 2, coins: 0, owned: [], stats: { runs: 0 } }),
|
||||
// normalize: (s, d) => ({ ...s, coins: num(s.coins, d.coins), owned: arr(s.owned, d.owned),
|
||||
// stats: { ...d.stats, ...s.stats } }),
|
||||
// migrate: (s, from) => { if (from < 2) { /* repair */ } return s; },
|
||||
// });
|
||||
// const save = saves.load(); ... saves.persist(save); if (saves.failed()) showWarningOnce();
|
||||
|
||||
/** Coerce to an array. RTDB drops empty arrays and returns sparse ones as key-indexed objects. */
|
||||
export function arr<T>(v: unknown, fallback: T[]): T[] {
|
||||
if (Array.isArray(v)) return v as T[];
|
||||
if (v && typeof v === "object") return Object.values(v as Record<string, T>);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** Number that must stay a finite number. */
|
||||
export function num(v: unknown, fallback: number): number {
|
||||
return typeof v === "number" && Number.isFinite(v) ? v : fallback;
|
||||
}
|
||||
|
||||
/** Shallow merge of a nested record over its defaults (stats, settings, ...). */
|
||||
export function rec<T extends object>(v: unknown, fallback: T): T {
|
||||
return { ...fallback, ...(v && typeof v === "object" && !Array.isArray(v) ? (v as Partial<T>) : {}) };
|
||||
}
|
||||
|
||||
export interface SaveStoreOptions<T extends { v: number }> {
|
||||
key: string;
|
||||
version: number;
|
||||
defaults: () => T;
|
||||
/** Fill a partial save (local OR cloud) out to a complete one. Default: shallow merge. */
|
||||
normalize?: (parsed: Partial<T>, defaults: T) => T;
|
||||
/** Repair saves from older versions; `from` is the stored version (1 if never stamped). */
|
||||
migrate?: (s: T, from: number) => T;
|
||||
/** Every Nth persist() also writes the backup slot. */
|
||||
backupEvery?: number;
|
||||
}
|
||||
|
||||
export interface SaveStore<T> {
|
||||
load(): T;
|
||||
persist(data: T): void;
|
||||
/** Normalize foreign data (cloud copy) the same way as a local load. */
|
||||
normalize(parsed: Partial<T>): T;
|
||||
clear(): void;
|
||||
failed(): boolean;
|
||||
}
|
||||
|
||||
export function createSaveStore<T extends { v: number }>(o: SaveStoreOptions<T>): SaveStore<T> {
|
||||
const backupKey = `${o.key}_bak`;
|
||||
const every = o.backupEvery ?? 12;
|
||||
let since = 0;
|
||||
let saveFailed = false;
|
||||
|
||||
function normalize(parsed: Partial<T>): T {
|
||||
const d = o.defaults();
|
||||
const from = num(parsed.v, 1);
|
||||
let s = o.normalize ? o.normalize(parsed, d) : ({ ...d, ...parsed } as T);
|
||||
if (from < o.version && o.migrate) s = o.migrate(s, from);
|
||||
s.v = o.version;
|
||||
return s;
|
||||
}
|
||||
|
||||
function readSlot(key: string): T | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(key);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
return normalize(parsed as Partial<T>);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
load: () => readSlot(o.key) ?? readSlot(backupKey) ?? o.defaults(),
|
||||
persist(data: T): void {
|
||||
try {
|
||||
const json = JSON.stringify(data);
|
||||
localStorage.setItem(o.key, json);
|
||||
if (++since >= every) {
|
||||
since = 0;
|
||||
localStorage.setItem(backupKey, json);
|
||||
}
|
||||
} catch {
|
||||
saveFailed = true; // quota / storage disabled - caller tells the player once
|
||||
}
|
||||
},
|
||||
normalize,
|
||||
clear(): void {
|
||||
try {
|
||||
localStorage.removeItem(o.key);
|
||||
localStorage.removeItem(backupKey); // a deletion that left the backup would resurrect it
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
},
|
||||
failed: () => saveFailed,
|
||||
};
|
||||
}
|
||||
|
||||
/** Offline earnings. Pass the timestamp captured at BOOT, not save.lastSeen read later -
|
||||
* autosave restamps lastSeen within seconds and the gain silently becomes zero. */
|
||||
export function offlineSeconds(since: number, capHours = 8): number {
|
||||
const elapsed = (Date.now() - num(since, Date.now())) / 1000;
|
||||
return Math.min(Math.max(elapsed, 0), capHours * 3600);
|
||||
}
|
||||
Reference in New Issue
Block a user