-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddToAppButton.tsx
More file actions
164 lines (145 loc) · 5.24 KB
/
AddToAppButton.tsx
File metadata and controls
164 lines (145 loc) · 5.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import React, { useState, useEffect } from 'react'
import { Box, Button, Snackbar, Alert, IconButton } from '@mui/material'
import { GetApp, Close, PhoneIphone, LaptopMac } from '@mui/icons-material'
interface BeforeInstallPromptEvent extends Event {
prompt(): Promise<void>
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>
}
export function AddToAppButton() {
const [deferredPrompt, setDeferredPrompt] = useState<BeforeInstallPromptEvent | null>(null)
const [showIOSInstructions, setShowIOSInstructions] = useState(false)
const [isInstallable, setIsInstallable] = useState(false)
const [showDebugInfo, setShowDebugInfo] = useState(false)
useEffect(() => {
const handleBeforeInstallPrompt = (e: Event) => {
console.log('PWA: beforeinstallprompt event fired')
e.preventDefault()
setDeferredPrompt(e as BeforeInstallPromptEvent)
setIsInstallable(true)
}
const handleAppInstalled = () => {
console.log('PWA: app installed')
setIsInstallable(false)
setDeferredPrompt(null)
}
window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
window.addEventListener('appinstalled', handleAppInstalled)
// Debug logging
console.log('PWA: Component mounted, checking conditions...')
console.log('PWA: isIOS =', isIOS())
console.log('PWA: isInStandaloneMode =', isInStandaloneMode())
console.log('PWA: hasBeforeInstallPrompt =', 'onbeforeinstallprompt' in window)
console.log('PWA: hostname =', window.location.hostname)
// For localhost development: if no beforeinstallprompt after 2 seconds,
// assume it's available for testing (but only on localhost)
const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
const isDev = process.env.NODE_ENV === 'development'
let timeoutId: NodeJS.Timeout | null = null
if (isDev && isLocalhost) {
timeoutId = setTimeout(() => {
if (!isInstallable && !isIOS()) {
console.log('PWA: No beforeinstallprompt after 2s, enabling for localhost testing')
setIsInstallable(true)
}
}, 2000)
}
return () => {
window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
window.removeEventListener('appinstalled', handleAppInstalled)
if (timeoutId) clearTimeout(timeoutId)
}
}, [])
const isIOS = () => {
return /iPad|iPhone|iPod/.test(navigator.userAgent)
}
const isInStandaloneMode = () => {
try {
const matchMediaResult = window.matchMedia('(display-mode: standalone)')
return (matchMediaResult && matchMediaResult.matches) ||
(window.navigator as any).standalone === true
} catch (e) {
// Fallback for test environments or browsers without matchMedia
return (window.navigator as any).standalone === true
}
}
const handleInstallClick = async () => {
if (isIOS()) {
setShowIOSInstructions(true)
return
}
if (deferredPrompt) {
deferredPrompt.prompt()
const { outcome } = await deferredPrompt.userChoice
if (outcome === 'accepted') {
setDeferredPrompt(null)
setIsInstallable(false)
}
}
}
// Don't show the button if already installed
if (isInStandaloneMode()) {
console.log('PWA: Button hidden - already in standalone mode')
return null
}
// Show button if:
// 1. Actually installable (beforeinstallprompt fired), OR
// 2. iOS device (can always install via Safari), OR
// 3. Development mode AND localhost (for testing)
const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1'
const isDev = process.env.NODE_ENV === 'development'
const shouldShowButton = isInstallable || isIOS() || (isDev && isLocalhost)
if (!shouldShowButton) {
console.log('PWA: Button hidden - not installable, not iOS, not dev+localhost')
return null
}
console.log('PWA: Button will show - installable:', isInstallable, 'iOS:', isIOS(), 'dev+localhost:', isDev && isLocalhost)
return (
<>
<Box
sx={{
display: 'flex',
justifyContent: 'center',
mt: 2,
mb: 1,
}}
>
<Button
variant="outlined"
startIcon={isIOS() ? <PhoneIphone /> : <LaptopMac />}
onClick={handleInstallClick}
sx={{
borderRadius: 2,
textTransform: 'none',
px: 3,
py: 1,
}}
>
Add to {isIOS() ? 'Home Screen' : 'Desktop'}
</Button>
</Box>
{/* iOS Installation Instructions */}
<Snackbar
open={showIOSInstructions}
onClose={() => setShowIOSInstructions(false)}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
autoHideDuration={8000}
>
<Alert
severity="info"
sx={{ maxWidth: '90vw' }}
action={
<IconButton
size="small"
color="inherit"
onClick={() => setShowIOSInstructions(false)}
>
<Close fontSize="small" />
</IconButton>
}
>
To install: tap the Share button in Safari, then tap "Add to Home Screen"
</Alert>
</Snackbar>
</>
)
}