|
| 1 | +"use client" |
| 2 | + |
| 3 | +import { useEffect, useState } from "react" |
| 4 | +import { Download, X } from "lucide-react" |
| 5 | + |
| 6 | +interface BeforeInstallPromptEvent extends Event { |
| 7 | + prompt(): Promise<void> |
| 8 | + userChoice: Promise<{ outcome: "accepted" | "dismissed" }> |
| 9 | +} |
| 10 | + |
| 11 | +export function InstallPrompt() { |
| 12 | + const [deferredPrompt, setDeferredPrompt] = useState<BeforeInstallPromptEvent | null>(null) |
| 13 | + const [dismissed, setDismissed] = useState(false) |
| 14 | + |
| 15 | + useEffect(() => { |
| 16 | + // Don't show if already installed or previously dismissed this session |
| 17 | + if (window.matchMedia("(display-mode: standalone)").matches) return |
| 18 | + |
| 19 | + const handler = (e: Event) => { |
| 20 | + e.preventDefault() |
| 21 | + setDeferredPrompt(e as BeforeInstallPromptEvent) |
| 22 | + } |
| 23 | + |
| 24 | + window.addEventListener("beforeinstallprompt", handler) |
| 25 | + return () => window.removeEventListener("beforeinstallprompt", handler) |
| 26 | + }, []) |
| 27 | + |
| 28 | + if (!deferredPrompt || dismissed) return null |
| 29 | + |
| 30 | + const handleInstall = async () => { |
| 31 | + await deferredPrompt.prompt() |
| 32 | + const { outcome } = await deferredPrompt.userChoice |
| 33 | + if (outcome === "accepted") { |
| 34 | + setDeferredPrompt(null) |
| 35 | + } |
| 36 | + setDismissed(true) |
| 37 | + } |
| 38 | + |
| 39 | + return ( |
| 40 | + <div className="fixed bottom-4 left-4 right-4 z-50 mx-auto max-w-sm animate-in slide-in-from-bottom-4 duration-300"> |
| 41 | + <div className="flex items-center gap-3 rounded-xl border border-border/50 bg-card/95 p-4 shadow-lg backdrop-blur-sm"> |
| 42 | + <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10"> |
| 43 | + <Download className="h-5 w-5 text-primary" /> |
| 44 | + </div> |
| 45 | + <div className="flex-1 min-w-0"> |
| 46 | + <p className="text-sm font-medium text-foreground">Install Fast Protocol</p> |
| 47 | + <p className="text-xs text-muted-foreground">Add to home screen for the best experience</p> |
| 48 | + </div> |
| 49 | + <button |
| 50 | + onClick={handleInstall} |
| 51 | + className="shrink-0 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors" |
| 52 | + > |
| 53 | + Install |
| 54 | + </button> |
| 55 | + <button |
| 56 | + onClick={() => setDismissed(true)} |
| 57 | + className="shrink-0 rounded-md p-1 text-muted-foreground hover:text-foreground transition-colors" |
| 58 | + aria-label="Dismiss" |
| 59 | + > |
| 60 | + <X className="h-4 w-4" /> |
| 61 | + </button> |
| 62 | + </div> |
| 63 | + </div> |
| 64 | + ) |
| 65 | +} |
0 commit comments