mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 09:01:17 -08:00
Merge pull request #173 from CloudHub-Social/pr/fix/sw-notifications
fix(notifications): SW push deep-links, visibility suppression, settings decoupling, nav fix
This commit is contained in:
9 files changed
+366
-196
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Service worker push notifications now correctly deep-link to the right account and room on cold PWA launch. Notifications are automatically suppressed when the app window is already visible. The In-App (pill banner) and System (OS) notification settings are now independent: desktop shows both controls, mobile shows Push and In-App only. Tapping an in-app notification pill on mobile now opens the room timeline directly instead of routing through the space navigation panel.
|
||||
@@ -14,6 +14,7 @@ import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useClientConfig } from '$hooks/useClientConfig';
|
||||
import { SequenceCardStyle } from '$features/settings/styles.css';
|
||||
import { pushSubscriptionAtom } from '$state/pushSubscription';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
import {
|
||||
requestBrowserNotificationPermission,
|
||||
enablePushNotifications,
|
||||
@@ -165,6 +166,10 @@ function WebPushNotificationSetting() {
|
||||
|
||||
export function SystemNotification() {
|
||||
const [showInAppNotifs, setShowInAppNotifs] = useSetting(settingsAtom, 'useInAppNotifications');
|
||||
const [showSystemNotifs, setShowSystemNotifs] = useSetting(
|
||||
settingsAtom,
|
||||
'useSystemNotifications'
|
||||
);
|
||||
const [isNotificationSounds, setIsNotificationSounds] = useSetting(
|
||||
settingsAtom,
|
||||
'isNotificationSounds'
|
||||
@@ -177,18 +182,14 @@ export function SystemNotification() {
|
||||
settingsAtom,
|
||||
'showMessageContentInEncryptedNotifications'
|
||||
);
|
||||
const [clearNotificationsOnRead, setClearNotificationsOnRead] = useSetting(
|
||||
settingsAtom,
|
||||
'clearNotificationsOnRead'
|
||||
);
|
||||
|
||||
return (
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">System & Notifications</Text>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<WebPushNotificationSetting />
|
||||
</SequenceCard>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
@@ -197,10 +198,34 @@ export function SystemNotification() {
|
||||
>
|
||||
<SettingTile
|
||||
title="In-App Notifications"
|
||||
description="Show a notification when a message arrives while the app is open (but not focused on the room)."
|
||||
description="Show a notification banner inside the app when a message arrives."
|
||||
after={<Switch value={showInAppNotifs} onChange={setShowInAppNotifs} />}
|
||||
/>
|
||||
</SequenceCard>
|
||||
{mobileOrTablet() && (
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<WebPushNotificationSetting />
|
||||
</SequenceCard>
|
||||
)}
|
||||
{!mobileOrTablet() && (
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<SettingTile
|
||||
title="System Notifications"
|
||||
description="Show an OS-level notification banner when a message arrives while the app is open. On mobile, the in-app banner is used instead."
|
||||
after={<Switch value={showSystemNotifs} onChange={setShowSystemNotifs} />}
|
||||
/>
|
||||
</SequenceCard>
|
||||
)}
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
@@ -231,6 +256,18 @@ export function SystemNotification() {
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<SettingTile
|
||||
title="Clear Notifications When Read Elsewhere"
|
||||
description="Automatically dismiss notifications on this device when you read messages on another device."
|
||||
after={<Switch value={clearNotificationsOnRead} onChange={setClearNotificationsOnRead} />}
|
||||
/>
|
||||
</SequenceCard>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import { useAtom, useAtomValue } from 'jotai';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { SyncState, ClientEvent } from '$types/matrix-sdk';
|
||||
import { activeSessionIdAtom, pendingNotificationAtom } from '../state/sessions';
|
||||
import { mDirectAtom } from '../state/mDirectList';
|
||||
import { useSyncState } from './useSyncState';
|
||||
import { useMatrixClient } from './useMatrixClient';
|
||||
import { useRoomNavigate } from './useRoomNavigate';
|
||||
import { getCanonicalAliasOrRoomId } from '../utils/matrix';
|
||||
import { getDirectRoomPath, getHomeRoomPath } from '../pages/pathUtils';
|
||||
import { createLogger } from '../utils/debug';
|
||||
|
||||
export function NotificationJumper() {
|
||||
const [pending, setPending] = useAtom(pendingNotificationAtom);
|
||||
const activeSessionId = useAtomValue(activeSessionIdAtom);
|
||||
const mDirects = useAtomValue(mDirectAtom);
|
||||
const mx = useMatrixClient();
|
||||
const { navigateRoom } = useRoomNavigate();
|
||||
const navigate = useNavigate();
|
||||
const log = createLogger('NotificationJumper');
|
||||
|
||||
// Set true the moment we fire navigateRoom. Only reset when `pending` changes
|
||||
@@ -45,9 +49,16 @@ export function NotificationJumper() {
|
||||
const isJoined = room?.getMyMembership() === 'join';
|
||||
|
||||
if (isSyncing && isJoined) {
|
||||
log.log('jumping to:', pending.roomId);
|
||||
log.log('jumping to:', pending.roomId, pending.eventId);
|
||||
jumpingRef.current = true;
|
||||
navigateRoom(pending.roomId, pending.eventId);
|
||||
// Navigate directly to home or direct path — bypasses space routing which
|
||||
// on mobile shows the space-nav panel first instead of the room timeline.
|
||||
const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, pending.roomId);
|
||||
if (mDirects.has(pending.roomId)) {
|
||||
navigate(getDirectRoomPath(roomIdOrAlias, pending.eventId));
|
||||
} else {
|
||||
navigate(getHomeRoomPath(roomIdOrAlias, pending.eventId));
|
||||
}
|
||||
setPending(null);
|
||||
// jumpingRef stays true until pending changes — see effect below.
|
||||
} else {
|
||||
@@ -57,7 +68,7 @@ export function NotificationJumper() {
|
||||
membership: room?.getMyMembership(),
|
||||
});
|
||||
}
|
||||
}, [pending, activeSessionId, mx, navigateRoom, setPending, log]);
|
||||
}, [pending, activeSessionId, mx, mDirects, navigate, setPending, log]);
|
||||
|
||||
// Reset the guard only when pending is replaced (new notification or cleared).
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useAtomValue, useSetAtom } from 'jotai';
|
||||
import { ReactNode, useCallback, useEffect, useRef } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { EventType, PushProcessor, RoomEvent, RoomEventHandlerMap } from '$types/matrix-sdk';
|
||||
import { PushProcessor, RoomEvent, RoomEventHandlerMap } from '$types/matrix-sdk';
|
||||
import { roomToUnreadAtom } from '$state/room/roomToUnread';
|
||||
import LogoSVG from '$public/res/svg/cinny.svg';
|
||||
import { NotificationBanner } from '$components/notification-banner';
|
||||
@@ -28,13 +28,13 @@ import { useSelectedRoom } from '$hooks/router/useSelectedRoom';
|
||||
import { useInboxNotificationsSelected } from '$hooks/router/useInbox';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { registrationAtom } from '$state/serviceWorkerRegistration';
|
||||
import { activeSessionIdAtom, pendingNotificationAtom, inAppBannerAtom } from '$state/sessions';
|
||||
import { pendingNotificationAtom, inAppBannerAtom, activeSessionIdAtom } from '$state/sessions';
|
||||
import {
|
||||
buildRoomMessageNotification,
|
||||
resolveNotificationPreviewText,
|
||||
} from '$utils/notificationStyle';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
import { getInboxInvitesPath, getInboxNotificationsPath } from '../pathUtils';
|
||||
import { getInboxInvitesPath } from '../pathUtils';
|
||||
import { BackgroundNotifications } from './BackgroundNotifications';
|
||||
|
||||
function SystemEmojiFeature() {
|
||||
@@ -70,9 +70,11 @@ function FaviconUpdater() {
|
||||
let notification = false;
|
||||
let highlight = false;
|
||||
let total = 0;
|
||||
let highlightTotal = 0;
|
||||
roomToUnread.forEach((unread) => {
|
||||
if (unread.from === null) {
|
||||
total += unread.total;
|
||||
highlightTotal += unread.highlight;
|
||||
}
|
||||
if (unread.total > 0) {
|
||||
notification = true;
|
||||
@@ -88,12 +90,17 @@ function FaviconUpdater() {
|
||||
setFavicon(LogoSVG);
|
||||
}
|
||||
try {
|
||||
navigator.setAppBadge(total);
|
||||
// Only badge with highlight (mention) counts — total unread is too noisy
|
||||
// for an OS-level app badge.
|
||||
if (highlightTotal > 0) {
|
||||
navigator.setAppBadge(highlightTotal);
|
||||
} else {
|
||||
navigator.clearAppBadge();
|
||||
}
|
||||
if (usePushNotifications) {
|
||||
if (total === 0) {
|
||||
// All rooms read — clear every notification and the badge.
|
||||
// All rooms read — clear every notification.
|
||||
registration.getNotifications().then((notifs) => notifs.forEach((n) => n.close()));
|
||||
navigator.clearAppBadge();
|
||||
} else {
|
||||
// Dismiss notifications for individual rooms that are now fully read.
|
||||
registration.getNotifications().then((notifs) => {
|
||||
@@ -123,7 +130,7 @@ function InviteNotifications() {
|
||||
const mx = useMatrixClient();
|
||||
|
||||
const navigate = useNavigate();
|
||||
const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications');
|
||||
const [showSystemNotifications] = useSetting(settingsAtom, 'useSystemNotifications');
|
||||
const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications');
|
||||
const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds');
|
||||
|
||||
@@ -152,26 +159,26 @@ function InviteNotifications() {
|
||||
useEffect(() => {
|
||||
if (invites.length <= perviousInviteLen || mx.getSyncState() !== 'SYNCING') return;
|
||||
|
||||
// Page hidden: if push is enabled, SW handles the OS notification. If not, nothing to do.
|
||||
if (document.visibilityState !== 'visible') return;
|
||||
// SW push (via Sygnal) handles invite notifications when the app is backgrounded.
|
||||
if (document.visibilityState !== 'visible' && usePushNotifications) return;
|
||||
|
||||
// Page is visible — show in-app experience.
|
||||
// On mobile with push: iOS-style — play sound only, no OS notification (SW is silent when
|
||||
// the app is visible on mobile, matching foreground behaviour of native chat apps).
|
||||
// On desktop with push: SW skipped (saw a visible client), so we show the OS notification.
|
||||
// Without push: always show OS notification when page is visible.
|
||||
const isVisibleMobileWithPush = usePushNotifications && mobileOrTablet();
|
||||
if (!isVisibleMobileWithPush && showNotifications && notificationPermission('granted')) {
|
||||
notify(invites.length - perviousInviteLen);
|
||||
// OS notification for invites — desktop only.
|
||||
if (!mobileOrTablet() && showSystemNotifications && notificationPermission('granted')) {
|
||||
try {
|
||||
notify(invites.length - perviousInviteLen);
|
||||
} catch {
|
||||
// window.Notification may be unavailable in sandboxed environments.
|
||||
}
|
||||
}
|
||||
if (notificationSound) {
|
||||
// Audio API requires a visible document; skip when hidden.
|
||||
if (document.visibilityState === 'visible' && notificationSound) {
|
||||
playSound();
|
||||
}
|
||||
}, [
|
||||
mx,
|
||||
invites,
|
||||
perviousInviteLen,
|
||||
showNotifications,
|
||||
showSystemNotifications,
|
||||
usePushNotifications,
|
||||
notificationSound,
|
||||
notify,
|
||||
@@ -189,9 +196,14 @@ function InviteNotifications() {
|
||||
function MessageNotifications() {
|
||||
const audioRef = useRef<HTMLAudioElement>(null);
|
||||
const notifiedEventsRef = useRef<Set<string>>(new Set());
|
||||
// Record mount time so we can distinguish live events from historical backfill
|
||||
// on sliding sync proxies that don't set num_live (which causes liveEvent=false
|
||||
// for all events, including actually-new messages).
|
||||
const clientStartTimeRef = useRef(Date.now());
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications');
|
||||
const [showSystemNotifications] = useSetting(settingsAtom, 'useSystemNotifications');
|
||||
const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications');
|
||||
const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds');
|
||||
const [showMessageContent] = useSetting(settingsAtom, 'showMessageContentInNotifications');
|
||||
@@ -225,9 +237,23 @@ function MessageNotifications() {
|
||||
if (mx.getSyncState() !== 'SYNCING') return;
|
||||
if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) return;
|
||||
|
||||
// Older sliding sync proxies (e.g. matrix-sliding-sync) omit num_live,
|
||||
// which causes every event to arrive with fromCache=true and therefore
|
||||
// liveEvent=false — silently blocking all notifications. Fall back to an
|
||||
// age check: treat the event as potentially live only when it was sent
|
||||
// within 60 s of this component mounting (tight enough to avoid phantom
|
||||
// notifications for pre-existing unread messages, generous enough for
|
||||
// messages that arrived during a brief offline window).
|
||||
// Additionally, skip the event if the user already has a read receipt
|
||||
// covering it (message was read on another device before this session).
|
||||
const isHistoricalEvent =
|
||||
!data.liveEvent &&
|
||||
(mEvent.getTs() < clientStartTimeRef.current - 60 * 1000 ||
|
||||
(!!room && room.hasUserReadEvent(mx.getSafeUserId(), mEvent.getId()!)));
|
||||
|
||||
if (
|
||||
!room ||
|
||||
!data.liveEvent ||
|
||||
isHistoricalEvent ||
|
||||
room.isSpaceRoom() ||
|
||||
!isNotificationEvent(mEvent) ||
|
||||
getNotificationType(mx, room.roomId) === NotificationType.Mute
|
||||
@@ -309,10 +335,9 @@ function MessageNotifications() {
|
||||
});
|
||||
}
|
||||
|
||||
// On desktop without push: also fire an OS notification as a secondary fallback
|
||||
// so the user is alerted even if the browser window is minimised.
|
||||
const isVisibleMobileWithPush = usePushNotifications && mobileOrTablet();
|
||||
if (!isVisibleMobileWithPush && showNotifications && notificationPermission('granted')) {
|
||||
// On desktop: also fire an OS notification so the user is alerted even
|
||||
// if the browser window is minimised (respects System Notifications toggle).
|
||||
if (!mobileOrTablet() && showSystemNotifications && notificationPermission('granted')) {
|
||||
const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption);
|
||||
const avatarMxc =
|
||||
room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl();
|
||||
@@ -345,7 +370,10 @@ function MessageNotifications() {
|
||||
};
|
||||
}
|
||||
|
||||
if (notificationSound && loudByRule) {
|
||||
// In-app audio: play whenever notification sounds are enabled.
|
||||
// Not gated on loudByRule — that only controls the OS-level silent flag.
|
||||
// Audio API requires a visible, focused document; skip when hidden.
|
||||
if (document.visibilityState === 'visible' && notificationSound) {
|
||||
playSound();
|
||||
}
|
||||
};
|
||||
@@ -358,6 +386,7 @@ function MessageNotifications() {
|
||||
notificationSound,
|
||||
notificationSelected,
|
||||
showNotifications,
|
||||
showSystemNotifications,
|
||||
showMessageContent,
|
||||
showEncryptedMessageContent,
|
||||
usePushNotifications,
|
||||
@@ -395,54 +424,38 @@ type ClientNonUIFeaturesProps = {
|
||||
};
|
||||
|
||||
export function HandleNotificationClick() {
|
||||
const navigate = useNavigate();
|
||||
const setActiveSessionId = useSetAtom(activeSessionIdAtom);
|
||||
const setPending = useSetAtom(pendingNotificationAtom);
|
||||
const setActiveSessionId = useSetAtom(activeSessionIdAtom);
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const handleNotificationClickEvent = (event: any) => {
|
||||
if (!event.data) return;
|
||||
// Note: do NOT guard on event.source — iOS Safari sets it to null for
|
||||
// SW-to-client postMessages (Webkit divergence from spec). The type check
|
||||
// below is the correct way to filter unrelated messages.
|
||||
const eventData = event.data;
|
||||
if (!(eventData?.type === 'notificationToRoomEvent')) return;
|
||||
const messageData = eventData?.message;
|
||||
if (!messageData) {
|
||||
navigate(getInboxNotificationsPath());
|
||||
if (!('serviceWorker' in navigator)) return undefined;
|
||||
|
||||
const handleMessage = (ev: MessageEvent) => {
|
||||
const { data } = ev;
|
||||
if (!data || data.type !== 'notificationClick') return;
|
||||
|
||||
const { userId, roomId, eventId, isInvite } = data as {
|
||||
userId?: string;
|
||||
roomId?: string;
|
||||
eventId?: string;
|
||||
isInvite?: boolean;
|
||||
};
|
||||
|
||||
if (userId) setActiveSessionId(userId);
|
||||
|
||||
if (isInvite) {
|
||||
navigate(getInboxInvitesPath());
|
||||
return;
|
||||
}
|
||||
const targetSessionId =
|
||||
typeof messageData?.user_id === 'string' ? messageData.user_id : undefined;
|
||||
|
||||
const eventType = messageData!.type as EventType;
|
||||
switch (eventType) {
|
||||
case EventType.RoomMessage:
|
||||
case EventType.RoomMessageEncrypted:
|
||||
// Always set the target session — jotai ignores no-ops if already active.
|
||||
// This ensures we never accidentally navigate under the wrong account.
|
||||
if (targetSessionId) setActiveSessionId(targetSessionId);
|
||||
setPending({
|
||||
roomId: messageData!.room_id,
|
||||
eventId: messageData!.event_id,
|
||||
targetSessionId,
|
||||
});
|
||||
return;
|
||||
case EventType.RoomMember:
|
||||
if (!(messageData?.content?.membership === 'invite')) return;
|
||||
if (targetSessionId) setActiveSessionId(targetSessionId);
|
||||
navigate(getInboxInvitesPath());
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (!roomId) return;
|
||||
setPending({ roomId, eventId, targetSessionId: userId });
|
||||
};
|
||||
|
||||
navigator.serviceWorker.addEventListener('message', handleNotificationClickEvent);
|
||||
return () => {
|
||||
navigator.serviceWorker.removeEventListener('message', handleNotificationClickEvent);
|
||||
};
|
||||
}, [navigate, setActiveSessionId, setPending]);
|
||||
navigator.serviceWorker.addEventListener('message', handleMessage);
|
||||
return () => navigator.serviceWorker.removeEventListener('message', handleMessage);
|
||||
}, [setPending, setActiveSessionId, navigate]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -455,25 +468,45 @@ function SyncNotificationSettingsWithServiceWorker() {
|
||||
settingsAtom,
|
||||
'showMessageContentInEncryptedNotifications'
|
||||
);
|
||||
const [clearNotificationsOnRead] = useSetting(settingsAtom, 'clearNotificationsOnRead');
|
||||
|
||||
useEffect(() => {
|
||||
if (!('serviceWorker' in navigator)) return undefined;
|
||||
|
||||
const postVisibility = () => {
|
||||
const visible = document.visibilityState === 'visible';
|
||||
const msg = { type: 'setAppVisible', visible };
|
||||
navigator.serviceWorker.controller?.postMessage(msg);
|
||||
navigator.serviceWorker.ready.then((reg) => reg.active?.postMessage(msg));
|
||||
};
|
||||
|
||||
// Report initial visibility immediately, then track changes.
|
||||
postVisibility();
|
||||
document.addEventListener('visibilitychange', postVisibility);
|
||||
return () => document.removeEventListener('visibilitychange', postVisibility);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!('serviceWorker' in navigator)) return;
|
||||
// preferPushOnMobile=false: SW skips push when page is visible on all devices.
|
||||
// The in-app path handles the visible case (sound on mobile, OS notification on desktop).
|
||||
const preferPushOnMobile = false;
|
||||
const payload = {
|
||||
type: 'setNotificationSettings' as const,
|
||||
notificationSoundEnabled: notificationSound,
|
||||
preferPushOnMobile,
|
||||
showMessageContent,
|
||||
showEncryptedMessageContent,
|
||||
clearNotificationsOnRead,
|
||||
};
|
||||
|
||||
navigator.serviceWorker.controller?.postMessage(payload);
|
||||
navigator.serviceWorker.ready.then((registration) => {
|
||||
registration.active?.postMessage(payload);
|
||||
});
|
||||
}, [notificationSound, usePushNotifications, showMessageContent, showEncryptedMessageContent]);
|
||||
}, [
|
||||
notificationSound,
|
||||
usePushNotifications,
|
||||
showMessageContent,
|
||||
showEncryptedMessageContent,
|
||||
clearNotificationsOnRead,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,35 +1,34 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useParams, useSearchParams } from 'react-router-dom';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { useSetAtom } from 'jotai';
|
||||
import { activeSessionIdAtom, pendingNotificationAtom } from '$state/sessions';
|
||||
|
||||
// ToRoomEvent handles the /to/:room_id/:event_id route used by the SW when it
|
||||
// opens a new window for a push notification (killed-app case) OR by client.navigate()
|
||||
// on iOS where postMessage is unreliable after focus().
|
||||
// ToRoomEvent handles /to/:user_id/:room_id/:event_id? — the canonical deep-link
|
||||
// URL used by the service worker's notificationclick handler.
|
||||
//
|
||||
// It does NOT navigate itself. Instead it writes to pendingNotificationAtom so
|
||||
// that NotificationJumper handles the actual navigation once the correct client
|
||||
// is synced. This survives the ClientRoot account-switch reload that happens when
|
||||
// setActiveSessionId() changes the active session: ToRoomEvent unmounts as soon
|
||||
// as ClientRoot calls navigate(getHomePath()), but the atom value persists and
|
||||
// NotificationJumper picks it up once the new client is ready.
|
||||
// The :user_id segment lets the SW embed the target Matrix user ID directly in
|
||||
// the URL (e.g. %40alice%3Aserver.tld) so the correct account is always
|
||||
// activated before navigation, even on a cold launch where the app restarts
|
||||
// from scratch after the PWA was killed by the OS.
|
||||
//
|
||||
// This component does NOT navigate itself — it writes to pendingNotificationAtom
|
||||
// so NotificationJumper can navigate once the Matrix client has finished its
|
||||
// initial sync. The atom survives the ClientRoot reload that happens when
|
||||
// setActiveSessionId() triggers an account switch.
|
||||
export function ToRoomEvent() {
|
||||
const { room_id: roomId, event_id: eventId } = useParams();
|
||||
const [searchParams] = useSearchParams();
|
||||
const targetUserId = searchParams.get('uid') ?? undefined;
|
||||
const { user_id: userId, room_id: roomId, event_id: eventId } = useParams();
|
||||
const setActiveSessionId = useSetAtom(activeSessionIdAtom);
|
||||
const setPending = useSetAtom(pendingNotificationAtom);
|
||||
|
||||
useEffect(() => {
|
||||
if (!roomId) return;
|
||||
const rid = roomId; // narrowed to string
|
||||
if (targetUserId) setActiveSessionId(targetUserId);
|
||||
setPending({ roomId: rid, eventId, targetSessionId: targetUserId });
|
||||
// Push a clean entry onto history so the back button doesn't return to /to/…
|
||||
if (window.history.length <= 2) {
|
||||
window.history.pushState({}, '', '/');
|
||||
}
|
||||
}, [roomId, eventId, targetUserId, setActiveSessionId, setPending]);
|
||||
// Switch to the target account first so the notification jumper navigates
|
||||
// under the correct session.
|
||||
if (userId) setActiveSessionId(userId);
|
||||
setPending({ roomId, eventId, targetSessionId: userId });
|
||||
// Replace /to/… in history so the back button doesn't return to this route.
|
||||
window.history.replaceState({}, '', '/');
|
||||
}, [userId, roomId, eventId, setActiveSessionId, setPending]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -86,7 +86,10 @@ export const INBOX_NOTIFICATIONS_PATH = `/inbox/${NOTIFICATIONS_PATH_SEGMENT}`;
|
||||
export const INBOX_INVITES_PATH = `/inbox/${INVITES_PATH_SEGMENT}`;
|
||||
|
||||
export const TO_PATH = '/to';
|
||||
export const TO_ROOM_EVENT_PATH = `${TO_PATH}/:room_id/:event_id?`;
|
||||
// Deep-link route used by push notification click-back URLs.
|
||||
// Format: /to/:user_id/:room_id/:event_id?
|
||||
// e.g. /to/%40alice%3Aserver/%21room%3Aserver/%24event%3Aserver
|
||||
export const TO_ROOM_EVENT_PATH = `${TO_PATH}/:user_id/:room_id/:event_id?`;
|
||||
|
||||
export const SPACE_SETTINGS_PATH = '/space-settings/';
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { atom } from 'jotai';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
|
||||
const STORAGE_KEY = 'settings';
|
||||
export type DateFormat = 'D MMM YYYY' | 'DD/MM/YYYY' | 'MM/DD/YYYY' | 'YYYY/MM/DD' | '';
|
||||
@@ -45,9 +46,11 @@ export interface Settings {
|
||||
|
||||
usePushNotifications: boolean;
|
||||
useInAppNotifications: boolean;
|
||||
useSystemNotifications: boolean;
|
||||
isNotificationSounds: boolean;
|
||||
showMessageContentInNotifications: boolean;
|
||||
showMessageContentInEncryptedNotifications: boolean;
|
||||
clearNotificationsOnRead: boolean;
|
||||
|
||||
hour24Clock: boolean;
|
||||
dateFormatString: string;
|
||||
@@ -103,11 +106,17 @@ const defaultSettings: Settings = {
|
||||
showHiddenEvents: false,
|
||||
legacyUsernameColor: false,
|
||||
|
||||
usePushNotifications: false,
|
||||
// Push notifications (SW/Sygnal): default on for mobile, opt-in on desktop.
|
||||
// In-app pill banner: always on — it's the primary foreground alert on mobile
|
||||
// and a useful secondary alert on desktop.
|
||||
// System (OS) notifications: desktop-only; hidden and disabled on mobile.
|
||||
usePushNotifications: mobileOrTablet(),
|
||||
useInAppNotifications: true,
|
||||
useSystemNotifications: !mobileOrTablet(),
|
||||
isNotificationSounds: true,
|
||||
showMessageContentInNotifications: false,
|
||||
showMessageContentInEncryptedNotifications: false,
|
||||
clearNotificationsOnRead: false,
|
||||
|
||||
hour24Clock: false,
|
||||
dateFormatString: 'D MMM YYYY',
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
/// <reference lib="WebWorker" />
|
||||
// eslint-disable-next-line import-x/no-extraneous-dependencies
|
||||
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
|
||||
import { EventType } from 'matrix-js-sdk/lib/@types/event';
|
||||
|
||||
import { createPushNotifications } from './sw/pushNotification';
|
||||
|
||||
export type {};
|
||||
declare const self: ServiceWorkerGlobalScope;
|
||||
|
||||
let notificationSoundEnabled = true;
|
||||
let preferPushOnMobile = false;
|
||||
// Tracks whether a page client has reported itself as visible.
|
||||
// The clients.matchAll() visibilityState is unreliable on iOS Safari PWA,
|
||||
// so we use this explicit flag as a fallback.
|
||||
let appIsVisible = false;
|
||||
let showMessageContent = false;
|
||||
let showEncryptedMessageContent = false;
|
||||
let clearNotificationsOnRead = false;
|
||||
const { handlePushNotificationPushData } = createPushNotifications(self, () => ({
|
||||
notificationSoundEnabled,
|
||||
showMessageContent,
|
||||
@@ -29,9 +33,9 @@ async function persistSettings() {
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
notificationSoundEnabled,
|
||||
preferPushOnMobile,
|
||||
showMessageContent,
|
||||
showEncryptedMessageContent,
|
||||
clearNotificationsOnRead,
|
||||
}),
|
||||
{ headers: { 'Content-Type': 'application/json' } }
|
||||
)
|
||||
@@ -49,10 +53,11 @@ async function loadPersistedSettings() {
|
||||
const s = await response.json();
|
||||
if (typeof s.notificationSoundEnabled === 'boolean')
|
||||
notificationSoundEnabled = s.notificationSoundEnabled;
|
||||
if (typeof s.preferPushOnMobile === 'boolean') preferPushOnMobile = s.preferPushOnMobile;
|
||||
if (typeof s.showMessageContent === 'boolean') showMessageContent = s.showMessageContent;
|
||||
if (typeof s.showEncryptedMessageContent === 'boolean')
|
||||
showEncryptedMessageContent = s.showEncryptedMessageContent;
|
||||
if (typeof s.clearNotificationsOnRead === 'boolean')
|
||||
clearNotificationsOnRead = s.clearNotificationsOnRead;
|
||||
} catch {
|
||||
// Ignore — stale or missing cache is fine; we fall back to defaults.
|
||||
}
|
||||
@@ -159,6 +164,11 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => {
|
||||
setSession(client.id, accessToken, baseUrl);
|
||||
event.waitUntil(cleanupDeadClients());
|
||||
}
|
||||
if (type === 'setAppVisible') {
|
||||
if (typeof (data as { visible?: unknown }).visible === 'boolean') {
|
||||
appIsVisible = (data as { visible: boolean }).visible;
|
||||
}
|
||||
}
|
||||
if (type === 'setNotificationSettings') {
|
||||
if (
|
||||
typeof (data as { notificationSoundEnabled?: unknown }).notificationSoundEnabled === 'boolean'
|
||||
@@ -166,9 +176,6 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => {
|
||||
notificationSoundEnabled = (data as { notificationSoundEnabled: boolean })
|
||||
.notificationSoundEnabled;
|
||||
}
|
||||
if (typeof (data as { preferPushOnMobile?: unknown }).preferPushOnMobile === 'boolean') {
|
||||
preferPushOnMobile = (data as { preferPushOnMobile: boolean }).preferPushOnMobile;
|
||||
}
|
||||
if (typeof (data as { showMessageContent?: unknown }).showMessageContent === 'boolean') {
|
||||
showMessageContent = (data as { showMessageContent: boolean }).showMessageContent;
|
||||
}
|
||||
@@ -179,12 +186,27 @@ self.addEventListener('message', (event: ExtendableMessageEvent) => {
|
||||
showEncryptedMessageContent = (data as { showEncryptedMessageContent: boolean })
|
||||
.showEncryptedMessageContent;
|
||||
}
|
||||
if (
|
||||
typeof (data as { clearNotificationsOnRead?: unknown }).clearNotificationsOnRead === 'boolean'
|
||||
) {
|
||||
clearNotificationsOnRead = (data as { clearNotificationsOnRead: boolean })
|
||||
.clearNotificationsOnRead;
|
||||
}
|
||||
// Persist so settings survive SW restart (iOS kills the SW aggressively).
|
||||
event.waitUntil(persistSettings());
|
||||
}
|
||||
});
|
||||
|
||||
const MEDIA_PATHS = ['/_matrix/client/v1/media/download', '/_matrix/client/v1/media/thumbnail'];
|
||||
const MEDIA_PATHS = [
|
||||
'/_matrix/client/v1/media/download',
|
||||
'/_matrix/client/v1/media/thumbnail',
|
||||
// Legacy unauthenticated endpoints — servers that require auth return 404/403
|
||||
// for these when no token is present, so intercept and add auth here too.
|
||||
'/_matrix/media/v3/download',
|
||||
'/_matrix/media/v3/thumbnail',
|
||||
'/_matrix/media/r0/download',
|
||||
'/_matrix/media/r0/thumbnail',
|
||||
];
|
||||
|
||||
function mediaPath(url: string): boolean {
|
||||
try {
|
||||
@@ -233,10 +255,17 @@ self.addEventListener('fetch', (event: FetchEvent) => {
|
||||
const { clientId } = event;
|
||||
if (!clientId) return;
|
||||
|
||||
// For browser sub-resource loads (images, video, audio, etc.), 'follow' is
|
||||
// the correct mode: the auth header is sent to the Matrix server which owns
|
||||
// the first hop; any CDN redirect it issues is followed natively by the
|
||||
// Fetch machinery. 'manual' would return an opaque-redirect Response that
|
||||
// the browser cannot render as an <img>/<video>/etc.
|
||||
const redirect: RequestRedirect = 'follow';
|
||||
|
||||
const session = sessions.get(clientId);
|
||||
if (session) {
|
||||
if (validMediaRequest(url, session.baseUrl)) {
|
||||
event.respondWith(fetch(url, fetchConfig(session.accessToken)));
|
||||
event.respondWith(fetch(url, { ...fetchConfig(session.accessToken), redirect }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -244,7 +273,7 @@ self.addEventListener('fetch', (event: FetchEvent) => {
|
||||
event.respondWith(
|
||||
requestSessionWithTimeout(clientId).then((s) => {
|
||||
if (s && validMediaRequest(url, s.baseUrl)) {
|
||||
return fetch(url, fetchConfig(s.accessToken));
|
||||
return fetch(url, { ...fetchConfig(s.accessToken), redirect });
|
||||
}
|
||||
return fetch(event.request);
|
||||
})
|
||||
@@ -252,39 +281,58 @@ self.addEventListener('fetch', (event: FetchEvent) => {
|
||||
});
|
||||
|
||||
const onPushNotification = async (event: PushEvent) => {
|
||||
if (!event?.data) {
|
||||
return;
|
||||
}
|
||||
if (!event?.data) return;
|
||||
|
||||
// The SW may have been restarted by the OS (iOS is aggressive about this),
|
||||
// so in-memory settings would be at their defaults. Reload from the cache.
|
||||
await loadPersistedSettings();
|
||||
// so in-memory settings would be at their defaults. Reload from cache and
|
||||
// match active clients in parallel — they are independent operations.
|
||||
const [, clients] = await Promise.all([
|
||||
loadPersistedSettings(),
|
||||
self.clients.matchAll({ type: 'window', includeUncontrolled: true }),
|
||||
]);
|
||||
|
||||
const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
|
||||
const hasVisibleClient = clients.some((client) => client.visibilityState === 'visible');
|
||||
if (hasVisibleClient && !preferPushOnMobile) {
|
||||
// If the app is open and visible, skip the OS push notification — the in-app
|
||||
// pill notification handles the alert instead.
|
||||
// Combine clients.matchAll() visibility with the explicit appIsVisible flag
|
||||
// because iOS Safari PWA often returns empty or stale results from matchAll().
|
||||
const hasVisibleClient =
|
||||
appIsVisible || clients.some((client) => client.visibilityState === 'visible');
|
||||
console.debug(
|
||||
'[SW push] appIsVisible:',
|
||||
appIsVisible,
|
||||
'| clients:',
|
||||
clients.map((c) => ({ url: c.url, visibility: c.visibilityState }))
|
||||
);
|
||||
console.debug('[SW push] hasVisibleClient:', hasVisibleClient);
|
||||
if (hasVisibleClient) {
|
||||
console.debug('[SW push] suppressing OS notification — app is visible');
|
||||
return;
|
||||
}
|
||||
|
||||
const pushData = event.data.json();
|
||||
console.debug('[SW push] raw payload:', JSON.stringify(pushData, null, 2));
|
||||
|
||||
// try {
|
||||
// if (typeof pushData?.unread === 'number') {
|
||||
// self.navigator.setAppBadge(pushData.unread);
|
||||
|
||||
// if (pushData.unread == 0) {
|
||||
// self.registration
|
||||
// .getNotifications()
|
||||
// .then((notifications) => notifications.forEach((notification) => notification.close()));
|
||||
// await navigator.clearAppBadge();
|
||||
// return;
|
||||
// }
|
||||
// } else {
|
||||
// await navigator.clearAppBadge();
|
||||
// }
|
||||
// } catch (_) {
|
||||
// // Likely Firefox/Gecko-based and doesn't support badging API
|
||||
// }
|
||||
try {
|
||||
if (typeof pushData?.unread === 'number') {
|
||||
if (pushData.unread === 0) {
|
||||
// All messages read elsewhere — clear the home-screen badge and,
|
||||
// if the user opted in, dismiss outstanding lock-screen notifications.
|
||||
await (self.navigator as any).clearAppBadge();
|
||||
if (clearNotificationsOnRead) {
|
||||
const notifs = await self.registration.getNotifications();
|
||||
notifs.forEach((n) => n.close());
|
||||
}
|
||||
return;
|
||||
}
|
||||
// unread > 0: update the PWA badge with the current count.
|
||||
await (self.navigator as any).setAppBadge(pushData.unread);
|
||||
} else {
|
||||
// No unread field in payload — clear badge to avoid a stale count.
|
||||
await (self.navigator as any).clearAppBadge();
|
||||
}
|
||||
} catch {
|
||||
// Badging API absent (Firefox/Gecko) — continue to show the notification.
|
||||
}
|
||||
|
||||
await handlePushNotificationPushData(pushData);
|
||||
};
|
||||
@@ -294,68 +342,92 @@ self.addEventListener('push', (event: PushEvent) => event.waitUntil(onPushNotifi
|
||||
self.addEventListener('notificationclick', (event: NotificationEvent) => {
|
||||
event.notification.close();
|
||||
|
||||
const messageData = event.notification.data;
|
||||
const { data } = event.notification;
|
||||
const { scope } = self.registration;
|
||||
|
||||
const eventType = messageData?.type as EventType | undefined;
|
||||
if (!eventType) return Promise.resolve();
|
||||
const pushUserId: string | undefined = data?.user_id ?? undefined;
|
||||
const pushRoomId: string | undefined = data?.room_id ?? undefined;
|
||||
const pushEventId: string | undefined = data?.event_id ?? undefined;
|
||||
const isInvite = data?.content?.membership === 'invite';
|
||||
|
||||
let targetUrl = `${scope}inbox/`;
|
||||
if (
|
||||
(eventType === EventType.RoomMessage || eventType === EventType.RoomMessageEncrypted) &&
|
||||
messageData?.room_id &&
|
||||
messageData?.event_id
|
||||
) {
|
||||
// Include the target user ID as ?uid= so ToRoomEvent can switch to the
|
||||
// correct account before navigating. This covers client.navigate() on iOS
|
||||
// Safari where postMessage is unreliable after focus().
|
||||
const uidParam =
|
||||
typeof messageData?.user_id === 'string'
|
||||
? `?uid=${encodeURIComponent(messageData.user_id)}`
|
||||
: '';
|
||||
targetUrl = `${scope}to/${messageData.room_id}/${messageData.event_id}${uidParam}`;
|
||||
console.debug('[SW notificationclick] notification data:', JSON.stringify(data, null, 2));
|
||||
console.debug('[SW notificationclick] resolved fields:', {
|
||||
pushUserId,
|
||||
pushRoomId,
|
||||
pushEventId,
|
||||
isInvite,
|
||||
scope,
|
||||
});
|
||||
|
||||
// Build a canonical deep-link URL.
|
||||
//
|
||||
// Room messages: /to/:user_id/:room_id/:event_id?
|
||||
// e.g. https://sable.cloudhub.social/to/%40alice%3Aserver/%21room%3Aserver/%24event%3Aserver
|
||||
// The :user_id segment ensures ToRoomEvent switches to the correct account
|
||||
// before navigating — required for background-account notifications.
|
||||
//
|
||||
// Invites: /inbox/invites/?uid=:user_id
|
||||
// Navigates straight to the invites page for the correct account.
|
||||
let targetUrl: string;
|
||||
if (isInvite) {
|
||||
const u = new URL('inbox/invites/', scope);
|
||||
if (pushUserId) u.searchParams.set('uid', pushUserId);
|
||||
targetUrl = u.href;
|
||||
} else if (pushUserId && pushRoomId) {
|
||||
const segments = pushEventId
|
||||
? `to/${encodeURIComponent(pushUserId)}/${encodeURIComponent(pushRoomId)}/${encodeURIComponent(pushEventId)}/`
|
||||
: `to/${encodeURIComponent(pushUserId)}/${encodeURIComponent(pushRoomId)}/`;
|
||||
targetUrl = new URL(segments, scope).href;
|
||||
} else {
|
||||
// Fallback: no room ID or no user ID in payload.
|
||||
targetUrl = new URL('inbox/notifications/', scope).href;
|
||||
}
|
||||
if (eventType === EventType.RoomMember && messageData?.content?.membership === 'invite')
|
||||
targetUrl = `${scope}inbox/invites/`;
|
||||
|
||||
const postMessageToClient = (client: WindowClient) => {
|
||||
client.postMessage({
|
||||
type: 'notificationToRoomEvent',
|
||||
message: messageData,
|
||||
});
|
||||
};
|
||||
console.debug('[SW notificationclick] targetUrl:', targetUrl);
|
||||
|
||||
event.waitUntil(
|
||||
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
|
||||
// Prefer a visible (foreground) tab; fall back to any open window client.
|
||||
const focusedClient =
|
||||
clientList.find((c) => c.visibilityState === 'visible') ??
|
||||
clientList.find((c): c is WindowClient => 'focus' in c);
|
||||
if (focusedClient) {
|
||||
return focusedClient.focus().then((wc) => {
|
||||
// Prefer client.navigate() — draft API, available on Chrome/Chromium
|
||||
// (all Android PWAs and desktop), unavailable on iOS Safari / Firefox.
|
||||
const client = wc ?? focusedClient;
|
||||
if ('navigate' in client && typeof (client as any).navigate === 'function') {
|
||||
return (client as any).navigate(targetUrl);
|
||||
}
|
||||
// navigate() unavailable: use postMessage. The existing client (whether
|
||||
// it was in the foreground or just minimized) has a live JS context by
|
||||
// the time focus() resolves. HandleNotificationClick in the page will
|
||||
// receive the message and dispatch the account-switch + deep link.
|
||||
postMessageToClient(client);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
// No existing client — open a new window. ToRoomEvent handles the route.
|
||||
if (self.clients.openWindow) {
|
||||
return self.clients.openWindow(targetUrl).then(() => null);
|
||||
}
|
||||
return null;
|
||||
})
|
||||
);
|
||||
(async () => {
|
||||
const clientList = (await self.clients.matchAll({
|
||||
type: 'window',
|
||||
includeUncontrolled: true,
|
||||
})) as WindowClient[];
|
||||
|
||||
return Promise.resolve();
|
||||
console.debug(
|
||||
'[SW notificationclick] window clients:',
|
||||
clientList.map((c) => ({ url: c.url, visibility: c.visibilityState, focused: c.focused }))
|
||||
);
|
||||
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
for (const wc of clientList) {
|
||||
console.debug('[SW notificationclick] postMessage to existing client:', wc.url);
|
||||
try {
|
||||
// Post notification data directly to the running app so its
|
||||
// ServiceWorkerClickHandler can call setActiveSessionId + setPending
|
||||
// (same path as the pill-style in-app banner) without navigating to
|
||||
// the /to/ route first.
|
||||
wc.postMessage({
|
||||
type: 'notificationClick',
|
||||
userId: pushUserId,
|
||||
roomId: pushRoomId,
|
||||
eventId: pushEventId,
|
||||
isInvite,
|
||||
});
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await wc.focus();
|
||||
return;
|
||||
} catch (err) {
|
||||
console.debug('[SW notificationclick] postMessage/focus failed:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// No existing window clients — open a new window.
|
||||
// ToRoomEvent handles the /to/ URL on cold launch (account switch + pending atom).
|
||||
console.debug('[SW notificationclick] falling back to openWindow()', targetUrl);
|
||||
if (self.clients.openWindow) {
|
||||
await self.clients.openWindow(targetUrl);
|
||||
}
|
||||
})()
|
||||
);
|
||||
});
|
||||
|
||||
if (self.__WB_MANIFEST) {
|
||||
|
||||
@@ -49,6 +49,7 @@ export const createPushNotifications = (
|
||||
silent,
|
||||
data,
|
||||
};
|
||||
console.debug('[SW showNotification] title:', title, '| data:', JSON.stringify(data, null, 2));
|
||||
await self.registration.showNotification(title, notifOptions as NotificationOptions);
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user