2021-10-27 16:38:10 +02:00
|
|
|
// @flow
|
2021-11-01 19:51:23 +01:00
|
|
|
import React, { useEffect, useState, useMemo } from 'react';
|
|
|
|
import pushNotifications from '$web/src/push-notifications';
|
|
|
|
import { BrowserNotificationErrorModal } from '$web/component/browserNotificationHints';
|
2021-10-27 16:38:10 +02:00
|
|
|
|
|
|
|
// @todo: Once we are on Redux 7 we should have proper hooks we can use here for store access.
|
|
|
|
import { store } from '$ui/store';
|
|
|
|
import { selectUser } from 'redux/selectors/user';
|
|
|
|
|
|
|
|
export default () => {
|
|
|
|
const [pushPermission, setPushPermission] = useState(window.Notification?.permission);
|
|
|
|
const [subscribed, setSubscribed] = useState(false);
|
|
|
|
const [pushEnabled, setPushEnabled] = useState(false);
|
|
|
|
const [pushSupported, setPushSupported] = useState(false);
|
2021-11-01 19:51:23 +01:00
|
|
|
const [encounteredError, setEncounteredError] = useState(false);
|
2021-10-27 16:38:10 +02:00
|
|
|
|
|
|
|
const [user] = useState(selectUser(store.getState()));
|
|
|
|
|
|
|
|
useEffect(() => {
|
2021-11-01 19:51:23 +01:00
|
|
|
setPushSupported(pushNotifications.supported);
|
|
|
|
if (pushNotifications.supported) {
|
|
|
|
pushNotifications.subscribed(user.id).then((isSubscribed: boolean) => setSubscribed(isSubscribed));
|
|
|
|
}
|
2021-10-27 16:38:10 +02:00
|
|
|
}, [user]);
|
|
|
|
|
|
|
|
useMemo(() => setPushEnabled(pushPermission === 'granted' && subscribed), [pushPermission, subscribed]);
|
|
|
|
|
|
|
|
const subscribe = async () => {
|
2021-11-01 19:51:23 +01:00
|
|
|
setEncounteredError(false);
|
|
|
|
try {
|
|
|
|
if (await pushNotifications.subscribe(user.id)) {
|
|
|
|
setSubscribed(true);
|
|
|
|
setPushPermission(window.Notification?.permission);
|
|
|
|
return true;
|
|
|
|
} else {
|
|
|
|
setEncounteredError(true);
|
|
|
|
}
|
|
|
|
} catch {
|
|
|
|
setEncounteredError(true);
|
2021-10-27 16:38:10 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const unsubscribe = async () => {
|
2021-11-01 19:51:23 +01:00
|
|
|
if (await pushNotifications.unsubscribe(user.id)) {
|
2021-10-27 16:38:10 +02:00
|
|
|
setSubscribed(false);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const pushToggle = async () => {
|
|
|
|
return !pushEnabled ? subscribe() : unsubscribe();
|
|
|
|
};
|
|
|
|
|
|
|
|
const pushRequest = async () => {
|
|
|
|
return window.Notification?.permission !== 'granted' ? subscribe() : null;
|
|
|
|
};
|
|
|
|
|
2021-11-01 19:51:23 +01:00
|
|
|
const pushErrorModal = () => {
|
|
|
|
return <>{encounteredError && <BrowserNotificationErrorModal doHideModal={() => setEncounteredError(false)} />}</>;
|
2021-10-27 16:38:10 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
pushSupported,
|
|
|
|
pushEnabled,
|
|
|
|
pushPermission,
|
|
|
|
pushToggle,
|
|
|
|
pushRequest,
|
2021-11-01 19:51:23 +01:00
|
|
|
pushErrorModal,
|
2021-10-27 16:38:10 +02:00
|
|
|
};
|
|
|
|
};
|