|
1 | 1 | import React, { createContext, FC, PropsWithChildren, useContext, useState } from 'react'
|
2 |
| -import { useAddToHomescreenPrompt } from '../hooks' |
3 | 2 | import { isDisplayMode } from '../helpers'
|
4 | 3 |
|
| 4 | +interface IBeforeInstallPromptEvent extends Event { |
| 5 | + readonly platforms: string[] |
| 6 | + readonly userChoice: Promise<{ |
| 7 | + outcome: 'accepted' | 'dismissed' |
| 8 | + platform: string |
| 9 | + }> |
| 10 | + prompt(): Promise<void> |
| 11 | +} |
| 12 | + |
5 | 13 | interface DeviceContextType {
|
6 | 14 | isInstalled: boolean
|
7 |
| - isInstallable: boolean |
8 |
| - promptToInstall: () => void |
| 15 | + beforeInstallPromptEvent: IBeforeInstallPromptEvent | null |
9 | 16 | }
|
10 | 17 |
|
11 | 18 | const DeviceContext = createContext<DeviceContextType>({
|
12 | 19 | isInstalled: false,
|
13 |
| - isInstallable: false, |
14 |
| - promptToInstall: () => {return}, |
| 20 | + beforeInstallPromptEvent: null, |
15 | 21 | })
|
16 | 22 |
|
17 | 23 | const DeviceProvider: FC<PropsWithChildren> = ({ children }) => {
|
18 |
| - const [prompt, promptToInstall] = useAddToHomescreenPrompt() |
19 |
| - const [isInstalled] = useState(isDisplayMode('standalone')) |
20 |
| - const [isInstallable, setInstallableState] = useState(false) |
21 |
| - |
22 |
| - React.useEffect( |
23 |
| - () => { |
24 |
| - if (prompt) { |
25 |
| - setInstallableState(true) |
26 |
| - } |
27 |
| - }, |
28 |
| - [prompt] |
29 |
| - ) |
30 |
| - |
31 |
| - return <DeviceContext.Provider value={{ isInstalled, isInstallable, promptToInstall }}>{children}</DeviceContext.Provider> |
| 24 | + const [beforeInstallPromptEvent, setBeforeInstallPromptEventState] = useState<IBeforeInstallPromptEvent | null>(null) |
| 25 | + const [isInstalled, setInstalledState] = useState(isDisplayMode('standalone')) |
| 26 | + |
| 27 | + React.useEffect(() => { |
| 28 | + const ready = (e: IBeforeInstallPromptEvent) => { |
| 29 | + e.preventDefault() |
| 30 | + setBeforeInstallPromptEventState(e) |
| 31 | + } |
| 32 | + const installed = () => setInstalledState(true) |
| 33 | + window.addEventListener('beforeinstallprompt', ready as any) |
| 34 | + window.addEventListener('appinstalled', installed) |
| 35 | + return () => { |
| 36 | + window.removeEventListener('beforeinstallprompt', ready as any) |
| 37 | + window.removeEventListener('appinstalled', installed) |
| 38 | + } |
| 39 | + }, []) |
| 40 | + |
| 41 | + return <DeviceContext.Provider value={{ isInstalled, beforeInstallPromptEvent }}>{children}</DeviceContext.Provider> |
32 | 42 | }
|
33 | 43 |
|
34 | 44 | export { DeviceProvider }
|
|
0 commit comments