import { useEffect, useId, useRef, useState } from "react"; import { activateClient, isClientActivated, watchClientActivation } from "../../lib/app-launch"; import { useProjectLink } from "../../lib/use-project-link"; import { useCopy } from "../../ui/copy"; import { Glyph } from "../../ui/icons"; import { Tooltip } from "./Tooltip"; import { Comic } from "./Comic"; import { HintComic } from "./hints"; import { LoadingStatus } from "./WaitingStatus"; import { useAnchoredPopover } from "./use-anchored-popover"; import { androidAppIntent } from "../../native/activation"; import type { AppDiscovery } from "../../native/discovery"; import type { AppReleaseIdentity } from "../../lib/release-update"; import { useReleaseUpdate } from "../../lib/use-release-update"; import { AppReleaseNotice } from "./AppReleaseNotice"; import { channelAppDiscovery } from "../../channel/app-link"; interface AppConnectionProps { onConnected?: () => void; discovery?: AppDiscovery; /** A current control connection, supplied by its owning session. */ connected?: boolean; } interface ConnectionAttempt { controller: AbortController; popup: Window | null; open?: () => void; cancel?: () => void; } export function AppConnectionButton({ onConnected, discovery = channelAppDiscovery, connected }: AppConnectionProps) { const { t, vis } = useCopy(); const [state, setState] = useState<"idle" | "waking" | "busy" | "approval" | "approving" | "ready" | "unavailable" | "incompatible">("idle"); const wakeURL = androidAppIntent("piik://app"); const [helpOpen, setHelpOpen] = useState(false); const downloadURL = useProjectLink("/#download", "https://github.com/TNTcraftHIM/Piik/releases/latest", helpOpen); const helpId = useId(); const trigger = useRef(null); const help = useRef(null); useAnchoredPopover(trigger, help); const pending = useRef(null); const healthCheck = useRef(null); const [build, setBuild] = useState(); const { update: release, refresh: checkRelease } = useReleaseUpdate(build); function rememberBuild(health: Partial | null) { setBuild(health?.version && health.revision ? { version: health.version, revision: health.revision, packageTarget: health.packageTarget } : undefined); } useEffect(() => { if (connected === false) rememberBuild(null); const refresh = async () => { if (pending.current) return; if (connected) { setState("ready"); } if (help.current?.matches(":popover-open") || (!connected && !isClientActivated())) return; healthCheck.current?.abort(); const current = healthCheck.current = new AbortController(); const native = discovery; if (current.signal.aborted) return; try { const health = await native.health({ signal: current.signal, waitForPermission: false }); if (!current.signal.aborted && !pending.current) { rememberBuild(health); if (!connected) setState(health ? "ready" : "idle"); } } catch (error) { if (!current.signal.aborted && !pending.current) { rememberBuild(null); if (!connected) setState(native.isIncompatible(error) ? "incompatible" : "idle"); } } }; // Launch/remembered activation is intent, not proof of current permission. // Recheck on return without keeping a media session or a polling timer alive. const onFocus = () => { void refresh().catch(() => undefined); }; onFocus(); window.addEventListener("focus", onFocus); const unwatch = watchClientActivation(onFocus); return () => { healthCheck.current?.abort(); window.removeEventListener("focus", onFocus); unwatch(); }; }, [discovery, connected]); useEffect(() => () => { pending.current?.controller.abort(); pending.current?.popup?.close(); }, []); function showHelp(): void { if (trigger.current) help.current?.showPopover({ source: trigger.current }); } async function connect(wake = false): Promise { if (pending.current) { pending.current.open?.(); return; } let manage = state === "ready" && connected !== false; healthCheck.current?.abort(); // Discovery and its browser permission prompt stay in the current tab. // A fresh click opens the real approval page without reserving a blank tab. const attempt: ConnectionAttempt = { controller: new AbortController(), popup: null }; pending.current = attempt; showHelp(); const signal = attempt.controller.signal; let native: AppDiscovery | undefined; let approving = false; let waking = false; const verifyApproval = async (reported = false) => { if (approving || signal.aborted) return; approving = true; const health = await native?.health({ signal }).catch(() => null); if (signal.aborted) return; approving = false; if (health) { rememberBuild(health); finish("ready"); activateClient(); onConnected?.(); } else if (reported) finish("unavailable"); else if (attempt.popup?.closed) finish("idle"); }; const onMessage = (event: MessageEvent) => { if (!attempt.popup || event.source !== attempt.popup || !approvalOrigin || event.origin !== approvalOrigin || event.data?.type !== "piik-app-approved" || event.data.site !== window.location.origin) return; // A message or browser return asks us to verify App-owned permission. void verifyApproval(true); }; let approvalOrigin = ""; const finish = (result: typeof state, keepPage = false) => { window.removeEventListener("message", onMessage); window.removeEventListener("focus", onFocus); document.removeEventListener("visibilitychange", onVisible); attempt.controller.abort(); if (!keepPage) attempt.popup?.close(); if (pending.current === attempt) { pending.current = null; setState(result); if (result === "unavailable" || result === "incompatible") showHelp(); else help.current?.hidePopover(); } }; attempt.cancel = () => finish(manage ? "ready" : "idle"); const onFocus = () => { if (waking) { attempt.open?.(); return; } if (attempt.popup) void verifyApproval(); }; const onVisible = () => { if (document.visibilityState === "visible") onFocus(); }; window.addEventListener("message", onMessage); window.addEventListener("focus", onFocus); document.addEventListener("visibilitychange", onVisible); signal.addEventListener("abort", () => { window.removeEventListener("message", onMessage); window.removeEventListener("focus", onFocus); document.removeEventListener("visibilitychange", onVisible); }, { once: true }); const discover = async () => { setState("busy"); try { native = discovery; if (signal.aborted) return; const url = await native.connect(signal); if (signal.aborted) return; if (!url) { finish("unavailable"); return; } // A compatible App was found; health may only see an older, approved App. const health = await native.health({ signal, waitForPermission: false }).catch(error => { if (native?.isIncompatible(error)) return null; throw error; }); if (signal.aborted) return; rememberBuild(health); manage = manage && health !== null; if (health && !manage) { finish("ready"); activateClient(); onConnected?.(); return; } approvalOrigin = new URL(url).origin; attempt.open = () => { if (signal.aborted || attempt.popup) return; const destination = new URL(url); if (manage) destination.searchParams.delete("site"); attempt.popup = window.open(destination.href, "_blank"); if (!attempt.popup) { finish("unavailable"); return; } attempt.open = undefined; if (manage) finish("ready", true); else { setState("approving"); help.current?.hidePopover(); } }; setState(manage ? "ready" : "approval"); } catch (error) { if (!signal.aborted) finish(native?.isIncompatible(error) ? "incompatible" : "unavailable"); } }; if (wake && wakeURL) { waking = true; attempt.open = () => { if (!waking || signal.aborted) return; waking = false; attempt.open = undefined; void discover(); }; setState("waking"); window.location.assign(wakeURL); } else await discover(); } const busy = state === "busy" || state === "waking" || state === "approving"; const label = t(({ idle: "client.connect.action", waking: "client.connect.returnToBrowser", busy: "client.connect.discovering", approval: "client.connect.found", approving: "client.connect.approving", ready: connected === false ? "client.connect.action" : "client.connect.manage", unavailable: "client.connect.unavailable", incompatible: "native.incompatible", } as const)[state]); const failed = state === "unavailable" || state === "incompatible"; const update = state === "ready" ? release : null; const availableUpdate = update?.kind === "update-available" || update?.kind === "major-update"; const title = availableUpdate ? t("client.connect.update", { current: build!.version, version: update.version }) : label; return <> ; }