(
options: ConnectCapacitorOptions = {},
)
| 20 | * in the background. |
| 21 | */ |
| 22 | export function connectCapacitor( |
| 23 | options: ConnectCapacitorOptions = {}, |
| 24 | ): () => Promise<void> { |
| 25 | const { |
| 26 | pauseOnBackground = true, |
| 27 | pauseAudio = true, |
| 28 | forwardBackButton = true, |
| 29 | // Return the promise from `App.exitApp()` so a rejection flows |
| 30 | // through the same async-handling path used for user-provided |
| 31 | // `onUnhandledBack` handlers. |
| 32 | onUnhandledBack = () => App.exitApp(), |
| 33 | } = options; |
| 34 | |
| 35 | const handles: CapacitorListenerHandle[] = []; |
| 36 | |
| 37 | if (pauseOnBackground) { |
| 38 | handles.push( |
| 39 | App.addListener("appStateChange", ({ isActive }) => { |
| 40 | if (isActive) { |
| 41 | state.resume(pauseAudio); |
| 42 | } else { |
| 43 | state.pause(pauseAudio); |
| 44 | } |
| 45 | }) as unknown as CapacitorListenerHandle, |
| 46 | ); |
| 47 | } |
| 48 | |
| 49 | if (forwardBackButton) { |
| 50 | handles.push( |
| 51 | App.addListener("backButton", () => { |
| 52 | if (!emitBackEvent()) { |
| 53 | // `onUnhandledBack` is allowed to be async; wrap so a |
| 54 | // thrown / rejected promise surfaces as a console |
| 55 | // warning instead of an unhandled rejection. |
| 56 | try { |
| 57 | const ret = onUnhandledBack(); |
| 58 | if (ret && typeof ret.then === "function") { |
| 59 | ret.catch((err: unknown) => { |
| 60 | console.warn( |
| 61 | "[@melonjs/capacitor-plugin] onUnhandledBack rejected:", |
| 62 | err, |
| 63 | ); |
| 64 | }); |
| 65 | } |
| 66 | } catch (err) { |
| 67 | console.warn( |
| 68 | "[@melonjs/capacitor-plugin] onUnhandledBack threw:", |
| 69 | err, |
| 70 | ); |
| 71 | } |
| 72 | } |
| 73 | }) as unknown as CapacitorListenerHandle, |
| 74 | ); |
| 75 | } |
| 76 | |
| 77 | return async () => { |
| 78 | const results = await Promise.allSettled(handles.map((h) => h.remove())); |
| 79 | handles.length = 0; |
no test coverage detected