import { Capacitor, registerPlugin, type PluginListenerHandle } from "@capacitor/core"; export type FoldPosture = "flat" | "tabletop" | "book" | "unknown"; export interface PostureChangedEvent { posture: FoldPosture; hingeTop: number; hingeBottom: number; hingeLeft: number; hingeRight: number; hingeHeight: number; } interface FoldPlugin { startMonitoring(): Promise<{ posture: FoldPosture }>; stopMonitoring(): Promise; addListener( event: "postureChanged", fn: (e: PostureChangedEvent) => void, ): Promise | PluginListenerHandle; } const Fold = registerPlugin("Fold"); export async function startFoldMonitoring( onChange: (e: PostureChangedEvent) => void, ): Promise<() => void> { if (!Capacitor.isNativePlatform() || Capacitor.getPlatform() !== "android") { return () => {}; } let initial: FoldPosture = "flat"; try { const r = await Fold.startMonitoring(); initial = r.posture; } catch { return () => {}; } onChange({ posture: initial, hingeTop: 0, hingeBottom: 0, hingeLeft: 0, hingeRight: 0, hingeHeight: 0, }); const handle = await Fold.addListener("postureChanged", onChange); return () => { void handle.remove(); void Fold.stopMonitoring().catch(() => {}); }; }