-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathuseBrowserNotification.ts
More file actions
69 lines (55 loc) · 2.03 KB
/
useBrowserNotification.ts
File metadata and controls
69 lines (55 loc) · 2.03 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
'use client';
import { useCallback, useEffect, useState } from 'react';
type NotificationPermission = 'default' | 'granted' | 'denied';
interface NotificationOptions {
title: string;
body?: string;
icon?: string;
onClick?: () => void;
}
interface UseBrowserNotificationReturn {
permission: NotificationPermission;
isSupported: boolean;
requestPermission: () => Promise<NotificationPermission>;
showNotification: (options: NotificationOptions) => Notification | null;
}
export function useBrowserNotification(): UseBrowserNotificationReturn {
const isSupported = typeof window !== 'undefined' && 'Notification' in window;
const [permission, setPermission] = useState<NotificationPermission>(() => {
if (!isSupported) return 'denied';
return Notification.permission as NotificationPermission;
});
// Sync permission state if it changes externally
useEffect(() => {
if (!isSupported) return;
setPermission(Notification.permission as NotificationPermission);
}, [isSupported]);
const requestPermission = useCallback(async (): Promise<NotificationPermission> => {
if (!isSupported) return 'denied';
const result = await Notification.requestPermission();
setPermission(result as NotificationPermission);
return result as NotificationPermission;
}, [isSupported]);
const showNotification = useCallback((options: NotificationOptions): Notification | null => {
if (!isSupported || permission !== 'granted') {
return null;
}
const notification = new Notification(options.title, {
body: options.body,
icon: options.icon,
});
if (options.onClick) {
notification.onclick = () => {
options.onClick?.();
notification.close();
};
}
return notification;
}, [isSupported, permission]);
return {
permission,
isSupported,
requestPermission,
showNotification,
};
}