This repository has been archived on 2026-10-25. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
Sable/src/sw/pushNotification.ts
T
Evie Gauthier c996e5e31b fix(notifications): iOS reliability, SW click handling, and account switching
- HandleNotificationClick moved outside ClientRoot loading gate so SW postMessages
  are never dropped during account-switch reloads
- iOS Safari event.source=null guard removed; type-check used instead
- ToRoomEvent simplified: writes pendingNotificationAtom + sets active session,
  delegates navigation to NotificationJumper
- NotificationJumper: jumpingRef prevents repeated navigation; stable performJumpRef
  avoids re-registering listeners on every atom change during account switch
- BackgroundNotifications: uses SW showNotification for reliable tap routing on iOS;
  dedupeId is now userId+eventId scoped; visibility guard prevents backgrounded
  in-app popups; ref pattern avoids stale closure on settings
- SW: persist/restore notification settings across iOS SW restarts via Cache API;
  group notifications by room (tag + renotify); prefer navigate() over postMessage
  when available; prefer visible tab on notificationclick
- pushNotification: resolveSilent respects tweaks.sound; recipientId in title;
  fallbackNotification removed (redundant)
- RoomTimeline: use ref for handleOpenEvent to stop re-pulling on every new message
2026-03-04 22:24:19 -05:00

172 lines
5.9 KiB
TypeScript

import { EventType } from 'matrix-js-sdk/lib/@types/event';
import {
buildRoomMessageNotification,
DEFAULT_NOTIFICATION_ICON,
DEFAULT_NOTIFICATION_BADGE,
resolveNotificationPreviewText,
} from '../app/utils/notificationStyle';
type NotificationSettings = {
notificationSoundEnabled: boolean;
showMessageContent: boolean;
showEncryptedMessageContent: boolean;
};
export const createPushNotifications = (
self: ServiceWorkerGlobalScope,
getNotificationSettings: () => NotificationSettings
) => {
const resolveSilent = (silent: unknown, tweakSound?: unknown): boolean => {
if (typeof silent === 'boolean') return silent;
// If the push rule doesn't request a sound tweak, the notification should be silent
// (no sound), regardless of the user's global sound preference.
if (!tweakSound) return true;
return !getNotificationSettings().notificationSoundEnabled;
};
const showNotificationWithData = async (
title: string,
body: string | undefined,
data: any,
silent?: boolean,
icon?: string,
badge?: string
) => {
const roomId: string | undefined = data?.room_id;
// Group by room so new messages in the same room replace the previous
// notification rather than stacking individually. renotify: true ensures
// the user is still alerted when the existing tag is replaced.
const tag = roomId ? `room-${roomId}` : (data?.event_id ?? 'Cinny');
const renotify = !!roomId;
// `renotify` is a valid Web API property absent from TypeScript's NotificationOptions type.
// Build the options object separately to avoid the excess-property check, then cast.
const notifOptions = {
body,
icon: icon ?? DEFAULT_NOTIFICATION_ICON,
badge: badge ?? DEFAULT_NOTIFICATION_BADGE,
tag,
renotify,
silent,
data,
};
await self.registration.showNotification(title, notifOptions as NotificationOptions);
};
const handleRoomMessageNotification = async (pushData: any) => {
const data = {
type: pushData?.type,
room_id: pushData?.room_id,
event_id: pushData?.event_id,
user_id: pushData?.user_id,
timestamp: Date.now(),
...pushData.data,
};
const notificationPayload = buildRoomMessageNotification({
roomName: pushData?.room_name,
username: pushData?.sender_display_name,
roomAvatar: pushData?.room_avatar_url,
previewText: resolveNotificationPreviewText({
content: pushData?.content,
eventType: pushData?.type,
isEncryptedRoom: false,
showMessageContent: getNotificationSettings().showMessageContent,
showEncryptedMessageContent: getNotificationSettings().showEncryptedMessageContent,
}),
silent: resolveSilent(pushData?.silent, pushData?.tweaks?.sound),
eventId: pushData?.event_id,
recipientId: typeof pushData?.user_id === 'string' ? pushData.user_id : undefined,
data,
});
await showNotificationWithData(
notificationPayload.title,
notificationPayload.options.body,
data,
notificationPayload.options.silent ?? undefined,
notificationPayload.options.icon,
notificationPayload.options.badge
);
};
const handleEncryptedMessageNotification = async (pushData: any) => {
const data = {
type: pushData?.type,
room_id: pushData?.room_id,
event_id: pushData?.event_id,
user_id: pushData?.user_id,
timestamp: Date.now(),
...pushData.data,
};
const notificationPayload = buildRoomMessageNotification({
roomName: pushData?.room_name,
username: pushData?.sender_display_name,
roomAvatar: pushData?.room_avatar_url,
previewText: resolveNotificationPreviewText({
content: pushData?.content,
eventType: pushData?.type,
isEncryptedRoom: true,
showMessageContent: getNotificationSettings().showMessageContent,
showEncryptedMessageContent: getNotificationSettings().showEncryptedMessageContent,
}),
silent: resolveSilent(pushData?.silent, pushData?.tweaks?.sound),
eventId: pushData?.event_id,
recipientId: typeof pushData?.user_id === 'string' ? pushData.user_id : undefined,
data,
});
await showNotificationWithData(
notificationPayload.title,
notificationPayload.options.body,
data,
notificationPayload.options.silent ?? undefined,
notificationPayload.options.icon,
notificationPayload.options.badge
);
};
const handleInvitationNotification = async (pushData: any) => {
const senderDisplayName = pushData?.sender_display_name;
const roomName = pushData?.room_name;
let body = '';
if (senderDisplayName && roomName) body = `${senderDisplayName} invites you to ${roomName}`;
if (senderDisplayName && !roomName) body = `from ${senderDisplayName}`;
if (!senderDisplayName && roomName) body = `to ${roomName}`;
if (!senderDisplayName && !roomName) body = '';
const data = {
type: pushData?.type,
content: pushData?.content,
user_id: pushData?.user_id,
timestamp: Date.now(),
...pushData.data,
};
await showNotificationWithData('New Invitation', body, data, resolveSilent(pushData?.silent));
};
const handlePushNotificationPushData = async (pushData: any) => {
const eventType = pushData?.type as EventType | undefined;
if (!eventType) {
console.warn('no event type');
}
switch (eventType) {
case EventType.RoomMessage:
case EventType.Sticker:
await handleRoomMessageNotification(pushData);
break;
case EventType.RoomMessageEncrypted:
await handleEncryptedMessageNotification(pushData);
break;
case EventType.RoomMember:
if (!(pushData?.content?.membership === 'invite')) break;
await handleInvitationNotification(pushData);
break;
default:
// no voip support in app anyway
break;
}
};
return { handlePushNotificationPushData };
};