hyperspace-desktop-client-w.../src/utilities/notifications.tsx

67 lines
2.0 KiB
TypeScript
Raw Normal View History

import { getUserDefaultBool, setUserDefaultBool } from "./settings";
2019-03-28 14:24:38 +01:00
/**
* Get the person's permission to send notification requests.
2020-03-24 18:06:40 +01:00
*
* @returns Promise containing the notification permission, or a rejection if
* either the browser doesn't support notifications.
2019-03-28 14:24:38 +01:00
*/
export function getNotificationRequestPermission() {
if ("Notification" in window) {
2020-03-24 18:06:40 +01:00
Notification.requestPermission().then(request => {
setUserDefaultBool(
"enablePushNotifications",
request === "granted"
);
setUserDefaultBool("userDeniedNotification", request === "denied");
});
return Promise.resolve(Notification.permission);
2019-03-28 14:24:38 +01:00
} else {
console.warn(
"Notifications aren't supported in this browser. The setting will be disabled."
);
setUserDefaultBool("enablePushNotifications", false);
2020-03-24 18:06:40 +01:00
return Promise.reject(
"Notifications are not supported in this browser."
);
2019-03-28 14:24:38 +01:00
}
}
/**
* Get the browser's notification support
* @returns Boolean value that determines whether the browser supports the Notification API
*/
export function browserSupportsNotificationRequests(): boolean {
return "Notification" in window;
2019-03-28 14:24:38 +01:00
}
/**
* Get the user default for sending push notifications
* @returns Boolean value of `enablePushNotifications`
*/
export function canSendNotifications() {
2020-03-24 18:06:40 +01:00
return (
getUserDefaultBool("enablePushNotifications") &&
Notification.permission === "granted"
);
2019-03-28 14:24:38 +01:00
}
/**
* Sends a push notification based on user preference
* @param title The primary title of the push notification
* @param body The contents of the push notification
*/
export function sendNotificationRequest(title: string, body: string) {
if (canSendNotifications()) {
let notif = new Notification(title, {
body: body
});
2019-03-28 14:24:38 +01:00
notif.onclick = () => {
window.focus();
};
} else {
console.warn("The person has opted to not receive push notifications.");
}
}