| 1 | import { useEffect } from "react"; |
| 2 | |
| 3 | import { desktopHost } from "../lib/desktopHost"; |
| 4 | import { setMainWindowMaximised } from "../store/windowChrome"; |
| 5 | |
| 6 | // Module-owned sync state for the single AppRuntime host: the enabled gate |
| 7 | // mirrors the active lifecycle, and the generation ticket discards |
| 8 | // out-of-order IsMainWindowMaximised resolutions. |
| 9 | let syncEnabled = false; |
| 10 | let syncGeneration = 0; |
| 11 | |
| 12 | /** |
| 13 | * Re-reads the native maximised flag into the windowChrome store. Event |
| 14 | * handlers call this after a toggle/zoom; a no-op while the lifecycle is |
| 15 | * disabled so a non-frameless platform never issues the bridge call. |
| 16 | */ |
| 17 | export function syncMainWindowMaximised(): void { |
| 18 | if (!syncEnabled) return; |
| 19 | const generation = ++syncGeneration; |
| 20 | void desktopHost().native.isWindowMaximised() |
| 21 | .then((value) => { if (generation === syncGeneration) setMainWindowMaximised(value); }) |
| 22 | .catch(() => { if (generation === syncGeneration) setMainWindowMaximised(false); }); |
| 23 | } |
| 24 | |
| 25 | /** |
| 26 | * Owns the maximised-sync lifecycle: initial sync, resize/focus listeners and |
| 27 | * the disabled/unmount reset. The flag itself lives in the windowChrome store; |
| 28 | * consumers select `mainWindowMaximised` from there. |
| 29 | */ |
| 30 | export function useWindowsMaximisedSync(enabled: boolean): void { |
| 31 | useEffect(() => { |
| 32 | if (!enabled) { |
| 33 | syncEnabled = false; |
| 34 | syncGeneration += 1; |
| 35 | setMainWindowMaximised(false); |
| 36 | return; |
| 37 | } |
| 38 | syncEnabled = true; |
| 39 | syncMainWindowMaximised(); |
| 40 | window.addEventListener("resize", syncMainWindowMaximised); |
| 41 | window.addEventListener("focus", syncMainWindowMaximised); |
| 42 | return () => { |
| 43 | syncEnabled = false; |
| 44 | syncGeneration += 1; |
| 45 | window.removeEventListener("resize", syncMainWindowMaximised); |
| 46 | window.removeEventListener("focus", syncMainWindowMaximised); |
| 47 | }; |
| 48 | }, [enabled]); |
| 49 | } |
| 50 | |
| 51 | export const nativeWindowCommands = { |
| 52 | minimize: () => desktopHost().native.minimiseWindow(), |
| 53 | toggleMaximize: () => desktopHost().native.toggleMaximiseWindow(), |
| 54 | close: () => desktopHost().native.closeWindow(), |
| 55 | }; |
| 56 |