import dynamic from "next/dynamic" ; import { useState , useEffect } from "react" ; import Swal from "sweetalert2" ; import PrimaryButton from "../common/PrimaryButton" ; import { logEvent } from "../../utils/analytics" ; const PWAPrompt = dynamic ( ( ) => import ( "react-ios-pwa-prompt" ) , { ssr : false , } ) ; let deferredPrompt ; if ( typeof window !== "undefined" ) { window . addEventListener ( "beforeinstallprompt" , ( e ) => { e . preventDefault ( ) ; deferredPrompt = e ; } ) ; } const AddAppButton = ( ) : JSX . Element => { const [ isLoading , setIsLoading ] = useState ( false ) ; const [ isiOS , setIsiOS ] = useState ( false ) ; const [ showiOS , setShowiOS ] = useState ( false ) ; useEffect ( ( ) => { setIsiOS ( /iPad|iPhone|iPod/ . test ( navigator . userAgent ) && ! window . MSStream ) ; } , [ ] ) ; const handleAddApp = ( ) => { setIsLoading ( true ) ; logEvent ( "home-clickAddApp" ) ; if ( isiOS ) { setShowiOS ( true ) ; logEvent ( "home-addApp-iOS" ) ; } else if ( deferredPrompt ) { deferredPrompt . prompt ( ) ; deferredPrompt . userChoice . then ( ( ) => setIsLoading ( false ) ) ; logEvent ( "home-addApp-native" ) ; } else { Swal . fire ( { title : "Hmm..." , text : "Failed to add rocketcrab as an app on this device. Try refreshing the page!" , icon : "error" , heightAuto : false , } ) ; setIsLoading ( false ) ; logEvent ( "home-addApp-failed" ) ; } } ; return ( < > < PrimaryButton onClick = { handleAddApp } disabled = { isLoading } manualWidth type = "default" loading = { isLoading } > Add 🚀 🦀 App < /PrimaryButton> { showiOS && ( < PWAPrompt debug = { true } permanentlyHideOnDismiss = { false } onClose = { ( ) => { setShowiOS ( false ) ; setIsLoading ( false ) ; } } />)} < />); } ; export default AddAppButton ;