feat: add cross-platform PWA install prompt
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export type InstallPromptState = "unsupported" | "available" | "ios-instructions" | "installed";
|
||||
|
||||
interface BeforeInstallPromptEvent extends Event {
|
||||
prompt: () => Promise<void>;
|
||||
userChoice: Promise<{ outcome: "accepted" | "dismissed"; platform: string }>;
|
||||
}
|
||||
|
||||
function isStandalone() {
|
||||
return window.matchMedia("(display-mode: standalone)").matches ||
|
||||
("standalone" in navigator && Boolean((navigator as Navigator & { standalone?: boolean }).standalone));
|
||||
}
|
||||
|
||||
function isIOSSafari() {
|
||||
const ua = navigator.userAgent;
|
||||
const ios = /iPad|iPhone|iPod/.test(ua) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
|
||||
return ios && /Safari/i.test(ua) && !/CriOS|FxiOS|EdgiOS|OPiOS/i.test(ua);
|
||||
}
|
||||
|
||||
export function useInstallPrompt() {
|
||||
const [state, setState] = useState<InstallPromptState>(() => {
|
||||
if (typeof window === "undefined") return "unsupported";
|
||||
if (isStandalone()) return "installed";
|
||||
return isIOSSafari() ? "ios-instructions" : "unsupported";
|
||||
});
|
||||
const [deferred, setDeferred] = useState<BeforeInstallPromptEvent | null>(null);
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (isStandalone()) {
|
||||
setState("installed");
|
||||
return;
|
||||
}
|
||||
|
||||
const onBeforeInstallPrompt = (event: Event) => {
|
||||
event.preventDefault();
|
||||
setDeferred(event as BeforeInstallPromptEvent);
|
||||
setState("available");
|
||||
};
|
||||
const onInstalled = () => {
|
||||
setDeferred(null);
|
||||
setState("installed");
|
||||
};
|
||||
|
||||
window.addEventListener("beforeinstallprompt", onBeforeInstallPrompt);
|
||||
window.addEventListener("appinstalled", onInstalled);
|
||||
return () => {
|
||||
window.removeEventListener("beforeinstallprompt", onBeforeInstallPrompt);
|
||||
window.removeEventListener("appinstalled", onInstalled);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const install = async () => {
|
||||
if (!deferred) return;
|
||||
const event = deferred;
|
||||
setDeferred(null);
|
||||
await event.prompt();
|
||||
const choice = await event.userChoice;
|
||||
if (choice.outcome === "accepted") setState("installed");
|
||||
else setDismissed(true);
|
||||
};
|
||||
|
||||
return { state: dismissed ? "unsupported" : state, install, dismiss: () => setDismissed(true) };
|
||||
}
|
||||
Reference in New Issue
Block a user