|
| 1 | +import { onMounted, Ref, ref, onUnmounted } from '@vue/composition-api'; |
| 2 | + |
| 3 | +type NotificationOptions = { |
| 4 | + dir?: 'auto' | 'ltr' | 'rtl'; |
| 5 | + lang?: string; |
| 6 | + body?: string; |
| 7 | + tag?: string; |
| 8 | + icon?: string; |
| 9 | +}; |
| 10 | + |
| 11 | +type NotificationMethods = { |
| 12 | + onClick: ((e: Event) => void) | null; |
| 13 | + onShow: ((e: Event) => void) | null; |
| 14 | + onError: ((e: Event) => void) | null; |
| 15 | + onClose: ((e: Event) => void) | null; |
| 16 | +}; |
| 17 | + |
| 18 | +const defaultNotificationOptions = { |
| 19 | + onClick: null, |
| 20 | + onShow: null, |
| 21 | + onError: null, |
| 22 | + onClose: null |
| 23 | +}; |
| 24 | + |
| 25 | +export function useNotification( |
| 26 | + title: string, |
| 27 | + options: NotificationOptions = {}, |
| 28 | + methods: NotificationMethods = defaultNotificationOptions |
| 29 | +) { |
| 30 | + const notification: Ref<Notification | null> = ref(null); |
| 31 | + const requestPermission = async () => { |
| 32 | + if ('permission' in Notification && Notification.permission !== 'denied') { |
| 33 | + await Notification.requestPermission(); |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + onMounted(requestPermission); |
| 38 | + |
| 39 | + onUnmounted(() => { |
| 40 | + notification.value = null; |
| 41 | + }); |
| 42 | + |
| 43 | + const showNotifcation = (): void => { |
| 44 | + notification.value = new Notification(title, options); |
| 45 | + notification.value.onclick = methods.onClick; |
| 46 | + notification.value.onshow = methods.onShow; |
| 47 | + notification.value.onerror = methods.onError; |
| 48 | + notification.value.onclose = methods.onClose; |
| 49 | + }; |
| 50 | + |
| 51 | + return { showNotifcation }; |
| 52 | +} |
0 commit comments