diff --git a/web/push-notif/push-notifs-handler.js b/web/push-notif/push-notifs-handler.js --- a/web/push-notif/push-notifs-handler.js +++ b/web/push-notif/push-notifs-handler.js @@ -1,6 +1,7 @@ // @flow import * as React from 'react'; +import { useDispatch } from 'react-redux'; import { setDeviceToken, @@ -15,6 +16,7 @@ import electron from '../electron.js'; import PushNotifModal from '../modals/push-notif-modal.react.js'; +import { updateNavInfoActionType } from '../redux/action-types.js'; import { useSelector } from '../redux/redux-utils.js'; function useCreatePushSubscription(): () => Promise { @@ -51,6 +53,8 @@ const modalContext = useModalContext(); const loggedIn = useSelector(isLoggedIn); + const dispatch = useDispatch(); + React.useEffect(() => { (async () => { if (!navigator.serviceWorker || electron) { @@ -87,6 +91,33 @@ prevLoggedIn.current = loggedIn; }, [createPushSubscription, loggedIn, modalContext, prevLoggedIn]); + // Redirect to thread on notification click + React.useEffect(() => { + if (!navigator.serviceWorker || electron) { + return; + } + + const callback = (event: MessageEvent) => { + if (typeof event.data !== 'object' || !event.data) { + return; + } + + if (event.data.targetThreadID) { + const payload = { + chatMode: 'view', + activeChatThreadID: event.data.targetThreadID, + tab: 'chat', + }; + + dispatch({ type: updateNavInfoActionType, payload }); + } + }; + + navigator.serviceWorker.addEventListener('message', callback); + return () => + navigator.serviceWorker?.removeEventListener('message', callback); + }, [dispatch]); + return null; } diff --git a/web/push-notif/service-worker.js b/web/push-notif/service-worker.js --- a/web/push-notif/service-worker.js +++ b/web/push-notif/service-worker.js @@ -45,4 +45,30 @@ self.addEventListener('notificationclick', (event: NotificationEvent) => { event.notification.close(); + event.waitUntil( + (async () => { + const clientList: Array = (await clients.matchAll({ + type: 'window', + }): any); + + const selectedClient = + clientList.find(client => client.focused) ?? clientList[0]; + + if (selectedClient) { + if (!selectedClient.focused) { + await selectedClient.focus(); + } + selectedClient.postMessage({ + targetThreadID: event.notification.data.threadID, + }); + } else { + const url = + (process.env.NODE_ENV === 'production' + ? 'https://web.comm.app' + : 'http://localhost:3000/comm') + + `/chat/thread/${event.notification.data.threadID}/`; + clients.openWindow(url); + } + })(), + ); });