1
1
import { API } from "api/api" ;
2
2
import { buildInfo } from "api/queries/buildInfo" ;
3
+ import { experiments } from "api/queries/experiments" ;
3
4
import { useEmbeddedMetadata } from "hooks/useEmbeddedMetadata" ;
4
5
import { useEffect , useState } from "react" ;
5
6
import { useQuery } from "react-query" ;
6
7
7
- interface PushNotifications {
8
+ interface WebpushNotifications {
9
+ readonly enabled : boolean ;
8
10
readonly subscribed : boolean ;
9
11
readonly loading : boolean ;
10
12
11
13
subscribe ( ) : Promise < void > ;
12
14
unsubscribe ( ) : Promise < void > ;
13
15
}
14
16
15
- export const usePushNotifications = ( ) : PushNotifications => {
17
+ export const useWebpushNotifications = ( ) : WebpushNotifications => {
16
18
const { metadata } = useEmbeddedMetadata ( ) ;
17
19
const buildInfoQuery = useQuery ( buildInfo ( metadata [ "build-info" ] ) ) ;
20
+ const enabledExperimentsQuery = useQuery ( experiments ( metadata . experiments ) ) ;
18
21
19
22
const [ subscribed , setSubscribed ] = useState < boolean > ( false ) ;
20
23
const [ loading , setLoading ] = useState < boolean > ( true ) ;
24
+ const [ enabled , setEnabled ] = useState < boolean > ( false ) ;
21
25
22
26
useEffect ( ( ) => {
27
+ // Check if the experiment is enabled.
28
+ if ( enabledExperimentsQuery . data ?. includes ( "web-push" ) ) {
29
+ setEnabled ( true ) ;
30
+ }
31
+
23
32
// Check if browser supports push notifications
24
33
if ( ! ( "Notification" in window ) || ! ( "serviceWorker" in navigator ) ) {
25
34
setSubscribed ( false ) ;
@@ -41,14 +50,12 @@ export const usePushNotifications = (): PushNotifications => {
41
50
} ;
42
51
43
52
checkSubscription ( ) ;
44
- } , [ ] ) ;
53
+ } , [ enabledExperimentsQuery . data ] ) ;
45
54
46
55
const subscribe = async ( ) : Promise < void > => {
47
56
try {
48
57
setLoading ( true ) ;
49
58
const registration = await navigator . serviceWorker . ready ;
50
-
51
- // Note: You'd typically get this key from your server
52
59
const vapidPublicKey = buildInfoQuery . data ?. webpush_public_key ;
53
60
54
61
const subscription = await registration . pushManager . subscribe ( {
@@ -66,7 +73,6 @@ export const usePushNotifications = (): PushNotifications => {
66
73
p256dh_key : json . keys . p256dh ,
67
74
} ) ;
68
75
69
- // Send subscription to your server here
70
76
setSubscribed ( true ) ;
71
77
} catch ( error ) {
72
78
console . error ( "Subscription failed:" , error ) ;
@@ -96,6 +102,7 @@ export const usePushNotifications = (): PushNotifications => {
96
102
97
103
return {
98
104
subscribed,
105
+ enabled,
99
106
loading : loading || buildInfoQuery . isLoading ,
100
107
subscribe,
101
108
unsubscribe,
0 commit comments