Merge pull request #139 from CloudHub-Social/feat/in-app-notification-banner-and-account-unread
feat(notifications): in-app notification banner, account unread counts, and Discord-style floating pill
This commit is contained in:
8 files changed
+565
-103
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Adds a new message pill and background app highlighted unread count.
|
||||
@@ -0,0 +1,154 @@
|
||||
import { keyframes, style } from '@vanilla-extract/css';
|
||||
import { color, config, toRem } from 'folds';
|
||||
|
||||
const slideIn = keyframes({
|
||||
from: {
|
||||
opacity: 0,
|
||||
transform: 'translateY(-100%)',
|
||||
},
|
||||
to: {
|
||||
opacity: 1,
|
||||
transform: 'translateY(0)',
|
||||
},
|
||||
});
|
||||
|
||||
const slideOut = keyframes({
|
||||
from: {
|
||||
opacity: 1,
|
||||
transform: 'translateY(0)',
|
||||
},
|
||||
to: {
|
||||
opacity: 0,
|
||||
transform: 'translateY(-100%)',
|
||||
},
|
||||
});
|
||||
|
||||
// Floats at the top of the chat area, starting after the icon sidebar.
|
||||
export const BannerContainer = style({
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
// 66px = sidebar icon strip width — overridden to 0 on mobile below
|
||||
left: toRem(66),
|
||||
right: 0,
|
||||
zIndex: 9999,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: config.space.S200,
|
||||
padding: config.space.S400,
|
||||
pointerEvents: 'none',
|
||||
alignItems: 'stretch',
|
||||
|
||||
'@media': {
|
||||
// On narrow screens the sidebar collapses, so span the full width.
|
||||
'(max-width: 768px)': {
|
||||
left: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const Banner = style({
|
||||
position: 'relative',
|
||||
overflow: 'hidden',
|
||||
pointerEvents: 'all',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: config.space.S300,
|
||||
backgroundColor: color.Surface.Container,
|
||||
color: color.Surface.OnContainer,
|
||||
border: `${config.borderWidth.B300} solid ${color.Surface.ContainerLine}`,
|
||||
borderRadius: toRem(16),
|
||||
padding: `${config.space.S300} ${config.space.S400}`,
|
||||
boxShadow: `0 ${toRem(8)} ${toRem(32)} rgba(0, 0, 0, 0.45), 0 ${toRem(2)} ${toRem(8)} rgba(0, 0, 0, 0.3)`,
|
||||
cursor: 'pointer',
|
||||
width: '100%',
|
||||
animationName: slideIn,
|
||||
animationDuration: '260ms',
|
||||
animationTimingFunction: 'cubic-bezier(0.22, 0.8, 0.6, 1)',
|
||||
animationFillMode: 'both',
|
||||
|
||||
selectors: {
|
||||
'&:hover': {
|
||||
backgroundColor: color.Surface.ContainerHover,
|
||||
},
|
||||
'&[data-dismissing=true]': {
|
||||
animationName: slideOut,
|
||||
animationDuration: '200ms',
|
||||
animationTimingFunction: 'cubic-bezier(0.4, 0, 1, 1)',
|
||||
animationFillMode: 'both',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const BannerIcon = style({
|
||||
width: toRem(44),
|
||||
height: toRem(44),
|
||||
objectFit: 'cover',
|
||||
borderRadius: config.radii.R300,
|
||||
flexShrink: 0,
|
||||
});
|
||||
|
||||
export const BannerContent = style({
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: toRem(2),
|
||||
});
|
||||
|
||||
export const BannerTitle = style({
|
||||
fontWeight: 700,
|
||||
});
|
||||
|
||||
export const BannerSubtitle = style({
|
||||
fontWeight: 400,
|
||||
opacity: 0.7,
|
||||
});
|
||||
|
||||
export const BannerRoomName = style({
|
||||
color: color.Primary.Main,
|
||||
fontWeight: 600,
|
||||
});
|
||||
|
||||
// Caps tall previews and fades the bottom edge when content overflows.
|
||||
export const BannerBody = style({
|
||||
position: 'relative',
|
||||
maxHeight: toRem(56),
|
||||
overflow: 'hidden',
|
||||
|
||||
selectors: {
|
||||
'&[data-overflow=true]::after': {
|
||||
content: '""',
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: toRem(28),
|
||||
background: `linear-gradient(to bottom, transparent, ${color.Surface.Container})`,
|
||||
pointerEvents: 'none',
|
||||
},
|
||||
'&[data-overflow=true][data-hovered=true]::after': {
|
||||
background: `linear-gradient(to bottom, transparent, ${color.Surface.ContainerHover})`,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const ProgressBar = style({
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
height: toRem(3),
|
||||
borderBottomLeftRadius: toRem(16),
|
||||
backgroundColor: color.Primary.Main,
|
||||
animationName: keyframes({
|
||||
from: { width: '100%' },
|
||||
to: { width: '0%' },
|
||||
}),
|
||||
animationTimingFunction: 'linear',
|
||||
animationFillMode: 'both',
|
||||
|
||||
selectors: {
|
||||
'&[data-paused=true]': {
|
||||
animationPlayState: 'paused',
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { useAtom } from 'jotai';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Box, Icon, IconButton, Icons, Text } from 'folds';
|
||||
import { inAppBannerAtom, InAppBannerNotification } from '$state/sessions';
|
||||
import * as css from './NotificationBanner.css';
|
||||
|
||||
const BANNER_DURATION_MS = 5000;
|
||||
|
||||
// Renders body text capped at a max height with a gradient fade when it overflows.
|
||||
function BodyText({ text, hovered }: { text: string; hovered: boolean }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [overflow, setOverflow] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
setOverflow(el.scrollHeight > el.clientHeight);
|
||||
}, [text]);
|
||||
|
||||
return (
|
||||
<div ref={ref} className={css.BannerBody} data-overflow={overflow} data-hovered={hovered}>
|
||||
<Text size="T200" priority="300">
|
||||
{text}
|
||||
</Text>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type BannerItemProps = {
|
||||
notification: InAppBannerNotification;
|
||||
onDismiss: (id: string) => void;
|
||||
};
|
||||
|
||||
function BannerItem({ notification, onDismiss }: BannerItemProps) {
|
||||
const [dismissing, setDismissing] = useState(false);
|
||||
const [paused, setPaused] = useState(false);
|
||||
const dismissedRef = useRef(false);
|
||||
const dismissAnimTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const elapsedRef = useRef(0);
|
||||
|
||||
// Use a ref to guard against double-dismiss without creating a new callback identity.
|
||||
const dismiss = useCallback(() => {
|
||||
if (dismissedRef.current) return;
|
||||
dismissedRef.current = true;
|
||||
setDismissing(true);
|
||||
dismissAnimTimerRef.current = setTimeout(() => onDismiss(notification.id), 200);
|
||||
}, [notification.id, onDismiss]);
|
||||
|
||||
// Auto-dismiss timer — only runs when not paused.
|
||||
useEffect(() => {
|
||||
if (paused) return undefined;
|
||||
const remaining = BANNER_DURATION_MS - elapsedRef.current;
|
||||
if (remaining <= 0) {
|
||||
dismiss();
|
||||
return undefined;
|
||||
}
|
||||
const startedAt = Date.now();
|
||||
const t = setTimeout(dismiss, remaining);
|
||||
return () => {
|
||||
clearTimeout(t);
|
||||
// Accumulate time spent un-paused so we can resume from the right point.
|
||||
elapsedRef.current += Date.now() - startedAt;
|
||||
};
|
||||
}, [paused, dismiss]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (dismissAnimTimerRef.current) clearTimeout(dismissAnimTimerRef.current);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const handleClick = () => {
|
||||
notification.onClick();
|
||||
dismiss();
|
||||
};
|
||||
|
||||
// When hovering, pause the auto-dismiss timer.
|
||||
const handleMouseEnter = () => setPaused(true);
|
||||
const handleMouseLeave = () => setPaused(false);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={css.Banner}
|
||||
data-dismissing={dismissing}
|
||||
onClick={handleClick}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') handleClick();
|
||||
if (e.key === 'Escape') dismiss();
|
||||
}}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
{notification.icon && (
|
||||
<img
|
||||
src={notification.icon}
|
||||
alt=""
|
||||
className={css.BannerIcon}
|
||||
onError={(e) => {
|
||||
(e.currentTarget as HTMLImageElement).style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div className={css.BannerContent}>
|
||||
<Text size="T300" truncate className={css.BannerTitle}>
|
||||
{notification.senderName ?? notification.title}
|
||||
{(notification.roomName || notification.serverName) && (
|
||||
<span className={css.BannerSubtitle}>
|
||||
{' ('}
|
||||
{notification.roomName && `#${notification.roomName}`}
|
||||
{notification.roomName && notification.serverName && ', '}
|
||||
{notification.serverName})
|
||||
</span>
|
||||
)}
|
||||
</Text>
|
||||
{notification.body && <BodyText text={notification.body} hovered={paused} />}
|
||||
</div>
|
||||
<Box shrink="No">
|
||||
<IconButton
|
||||
size="300"
|
||||
variant="Surface"
|
||||
fill="None"
|
||||
radii="300"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
dismiss();
|
||||
}}
|
||||
aria-label="Dismiss notification"
|
||||
>
|
||||
<Icon size="100" src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
<div
|
||||
className={css.ProgressBar}
|
||||
data-paused={paused}
|
||||
style={{ animationDuration: `${BANNER_DURATION_MS - elapsedRef.current}ms` }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the in-app notification banner stack.
|
||||
* Mount this once near the root of the client layout.
|
||||
*/
|
||||
export function NotificationBanner() {
|
||||
// We store an array locally so multiple rapid notifications stack briefly.
|
||||
const [banner, setBanner] = useAtom(inAppBannerAtom);
|
||||
const [queue, setQueue] = useState<InAppBannerNotification[]>([]);
|
||||
|
||||
// Push new notifications into the local queue.
|
||||
useEffect(() => {
|
||||
if (!banner) return;
|
||||
setQueue((prev) => {
|
||||
// De-duplicate by id
|
||||
if (prev.some((n) => n.id === banner.id)) return prev;
|
||||
// Keep at most 3 visible at once — drop the oldest if over limit.
|
||||
const next = [...prev, banner];
|
||||
return next.length > 3 ? next.slice(next.length - 3) : next;
|
||||
});
|
||||
// Clear the atom so the same notification doesn't re-enqueue on re-render.
|
||||
setBanner(null);
|
||||
}, [banner, setBanner]);
|
||||
|
||||
const handleDismiss = (id: string) => {
|
||||
setQueue((prev) => prev.filter((n) => n.id !== id));
|
||||
};
|
||||
|
||||
if (queue.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className={css.BannerContainer} aria-live="polite" aria-atomic="false">
|
||||
{queue.map((n) => (
|
||||
<BannerItem key={n.id} notification={n} onDismiss={handleDismiss} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { NotificationBanner } from './NotificationBanner';
|
||||
@@ -9,8 +9,15 @@ import {
|
||||
SyncState,
|
||||
PushProcessor,
|
||||
} from '$types/matrix-sdk';
|
||||
import { useAtomValue, useSetAtom } from 'jotai';
|
||||
import { sessionsAtom, activeSessionIdAtom, Session, sessionsHighlightAtom } from '$state/sessions';
|
||||
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
|
||||
import {
|
||||
sessionsAtom,
|
||||
activeSessionIdAtom,
|
||||
Session,
|
||||
pendingNotificationAtom,
|
||||
backgroundUnreadCountsAtom,
|
||||
inAppBannerAtom,
|
||||
} from '$state/sessions';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix';
|
||||
@@ -77,7 +84,7 @@ const waitForSync = (mx: MatrixClient): Promise<void> =>
|
||||
export function BackgroundNotifications() {
|
||||
const clientConfig = useClientConfig();
|
||||
const sessions = useAtomValue(sessionsAtom);
|
||||
const activeSessionId = useAtomValue(activeSessionIdAtom);
|
||||
const [activeSessionId, setActiveSessionId] = useAtom(activeSessionIdAtom);
|
||||
const [showNotifications] = useSetting(settingsAtom, 'useInAppNotifications');
|
||||
const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications');
|
||||
const [notificationSound] = useSetting(settingsAtom, 'isNotificationSounds');
|
||||
@@ -101,7 +108,14 @@ export function BackgroundNotifications() {
|
||||
showEncryptedMessageContentRef.current = showEncryptedMessageContent;
|
||||
const clientsRef = useRef<Map<string, MatrixClient>>(new Map());
|
||||
const notifiedEventsRef = useRef<Set<string>>(new Set());
|
||||
const setHighlights = useSetAtom(sessionsHighlightAtom);
|
||||
const setPending = useSetAtom(pendingNotificationAtom);
|
||||
const setBackgroundUnreads = useSetAtom(backgroundUnreadCountsAtom);
|
||||
const setInAppBanner = useSetAtom(inAppBannerAtom);
|
||||
// Stable setter refs so async handleTimeline closures never go stale.
|
||||
const setBackgroundUnreadsRef = useRef(setBackgroundUnreads);
|
||||
setBackgroundUnreadsRef.current = setBackgroundUnreads;
|
||||
const setInAppBannerRef = useRef(setInAppBanner);
|
||||
setInAppBannerRef.current = setInAppBanner;
|
||||
|
||||
const inactiveSessions = sessions.filter(
|
||||
(s) => s.userId !== (activeSessionId ?? sessions[0]?.userId)
|
||||
@@ -122,6 +136,9 @@ export function BackgroundNotifications() {
|
||||
* Must include { type, room_id, event_id, user_id } so the SW notificationclick
|
||||
* handler can route the tap through HandleNotificationClick for account switching. */
|
||||
data?: unknown;
|
||||
/** Optional callback invoked when the user clicks the notification (window.Notification
|
||||
* fallback path only; the SW path routes via its own notificationclick handler). */
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -151,14 +168,19 @@ export function BackgroundNotifications() {
|
||||
}
|
||||
}
|
||||
if ('Notification' in window && window.Notification.permission === 'granted') {
|
||||
// eslint-disable-next-line no-new
|
||||
new window.Notification(opts.title, {
|
||||
const noti = new window.Notification(opts.title, {
|
||||
icon: opts.icon,
|
||||
badge: opts.badge,
|
||||
body: opts.body,
|
||||
silent: opts.silent ?? false,
|
||||
data: opts.data,
|
||||
});
|
||||
if (opts.onClick) {
|
||||
noti.onclick = () => {
|
||||
opts.onClick?.();
|
||||
noti.close();
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,8 +189,8 @@ export function BackgroundNotifications() {
|
||||
log.log('stopping background client for', userId);
|
||||
stopClient(mx);
|
||||
current.delete(userId);
|
||||
// Clear the highlight badge when this session is no longer a background account.
|
||||
setHighlights((prev) => {
|
||||
// Clear the background unread badge when this session is no longer a background account.
|
||||
setBackgroundUnreads((prev) => {
|
||||
const next = { ...prev };
|
||||
delete next[userId];
|
||||
return next;
|
||||
@@ -226,6 +248,23 @@ export function BackgroundNotifications() {
|
||||
: LogoSVG;
|
||||
|
||||
const loudByRule = Boolean(pushActions.tweaks?.sound);
|
||||
|
||||
// Track background unread count for every notifiable event (loud or silent).
|
||||
const isHighlight = Boolean(pushActions.tweaks?.highlight);
|
||||
setBackgroundUnreadsRef.current((prev) => {
|
||||
const cur = prev[session.userId] ?? { total: 0, highlight: 0 };
|
||||
return {
|
||||
...prev,
|
||||
[session.userId]: {
|
||||
total: cur.total + 1,
|
||||
highlight: isHighlight ? cur.highlight + 1 : cur.highlight,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Silent-rule events: unread badge updated above; no OS notification or sound.
|
||||
if (!loudByRule && !isHighlight) return;
|
||||
|
||||
const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption);
|
||||
|
||||
notifiedEventsRef.current.add(dedupeId);
|
||||
@@ -235,14 +274,6 @@ export function BackgroundNotifications() {
|
||||
if (first) notifiedEventsRef.current.delete(first);
|
||||
}
|
||||
|
||||
// Track highlight count for the account switcher badge.
|
||||
if (pushActions.tweaks?.highlight) {
|
||||
setHighlights((prev) => ({
|
||||
...prev,
|
||||
[session.userId]: (prev[session.userId] ?? 0) + 1,
|
||||
}));
|
||||
}
|
||||
|
||||
// This component handles ONLY background (inactive) accounts.
|
||||
// SW push covers the active account when the app is backgrounded.
|
||||
// When the page is hidden, iOS suspends JS entirely — nothing to do here.
|
||||
@@ -275,14 +306,38 @@ export function BackgroundNotifications() {
|
||||
},
|
||||
});
|
||||
|
||||
sendNotification({
|
||||
title: notificationPayload.title,
|
||||
icon: notificationPayload.options.icon,
|
||||
badge: notificationPayload.options.badge,
|
||||
body: notificationPayload.options.body,
|
||||
silent: notificationPayload.options.silent ?? undefined,
|
||||
data: notificationPayload.options.data,
|
||||
});
|
||||
const notifOnClick = () => {
|
||||
window.focus();
|
||||
// Always switch to the background account – jotai ignores no-op updates
|
||||
setActiveSessionId(session.userId);
|
||||
setPending({ roomId: room.roomId, eventId, targetSessionId: session.userId });
|
||||
};
|
||||
|
||||
if (document.visibilityState === 'visible') {
|
||||
// App is in the foreground on a different account — show the themed in-app banner.
|
||||
setInAppBannerRef.current({
|
||||
id: dedupeId,
|
||||
title: notificationPayload.title,
|
||||
roomName: room.name ?? room.getCanonicalAlias() ?? undefined,
|
||||
senderName,
|
||||
body: notificationPayload.options.body,
|
||||
icon: notificationPayload.options.icon,
|
||||
onClick: notifOnClick,
|
||||
});
|
||||
} else if (loudByRule) {
|
||||
// App is backgrounded — fire an OS notification only for loud (sound-tweak) rules.
|
||||
// Highlight-only events are silently counted in the badge; OS noise is left to the
|
||||
// user's own push rules for that account.
|
||||
sendNotification({
|
||||
title: notificationPayload.title,
|
||||
icon: notificationPayload.options.icon,
|
||||
badge: notificationPayload.options.badge,
|
||||
body: notificationPayload.options.body,
|
||||
silent: notificationPayload.options.silent ?? undefined,
|
||||
data: notificationPayload.options.data,
|
||||
onClick: notifOnClick,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
mx.on(RoomEvent.Timeline, handleTimeline as unknown as (...args: unknown[]) => void);
|
||||
@@ -296,7 +351,15 @@ export function BackgroundNotifications() {
|
||||
current.forEach((mx) => stopClient(mx));
|
||||
current.clear();
|
||||
};
|
||||
}, [clientConfig.slidingSync, inactiveSessions, shouldRunBackgroundNotifications, setHighlights]);
|
||||
}, [
|
||||
clientConfig.slidingSync,
|
||||
inactiveSessions,
|
||||
shouldRunBackgroundNotifications,
|
||||
setActiveSessionId,
|
||||
setPending,
|
||||
setBackgroundUnreads,
|
||||
setInAppBanner,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom';
|
||||
import { EventType, 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';
|
||||
import LogoUnreadSVG from '$public/res/svg/cinny-unread.svg';
|
||||
import LogoHighlightSVG from '$public/res/svg/cinny-highlight.svg';
|
||||
import NotificationSound from '$public/sound/notification.ogg';
|
||||
@@ -27,7 +28,7 @@ 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 } from '$state/sessions';
|
||||
import { activeSessionIdAtom, pendingNotificationAtom, inAppBannerAtom } from '$state/sessions';
|
||||
import {
|
||||
buildRoomMessageNotification,
|
||||
resolveNotificationPreviewText,
|
||||
@@ -187,7 +188,6 @@ function InviteNotifications() {
|
||||
|
||||
function MessageNotifications() {
|
||||
const audioRef = useRef<HTMLAudioElement>(null);
|
||||
const notifRef = useRef<Notification>();
|
||||
const notifiedEventsRef = useRef<Set<string>>(new Set());
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
@@ -204,51 +204,10 @@ function MessageNotifications() {
|
||||
nicknamesRef.current = nicknames;
|
||||
|
||||
const setPending = useSetAtom(pendingNotificationAtom);
|
||||
const setInAppBanner = useSetAtom(inAppBannerAtom);
|
||||
const selectedRoomId = useSelectedRoom();
|
||||
const notificationSelected = useInboxNotificationsSelected();
|
||||
|
||||
const notify = useCallback(
|
||||
({
|
||||
roomName,
|
||||
roomAvatar,
|
||||
username,
|
||||
roomId,
|
||||
eventId,
|
||||
previewText,
|
||||
silent,
|
||||
}: {
|
||||
roomName: string;
|
||||
roomAvatar?: string;
|
||||
username: string;
|
||||
roomId: string;
|
||||
eventId: string;
|
||||
previewText: string;
|
||||
silent: boolean;
|
||||
}) => {
|
||||
const payload = buildRoomMessageNotification({
|
||||
roomName,
|
||||
roomAvatar,
|
||||
username,
|
||||
previewText,
|
||||
silent,
|
||||
eventId,
|
||||
});
|
||||
const noti = new window.Notification(payload.title, payload.options);
|
||||
|
||||
noti.onclick = () => {
|
||||
window.focus();
|
||||
setPending({ roomId, eventId, targetSessionId: mx.getUserId() ?? undefined });
|
||||
|
||||
noti.close();
|
||||
notifRef.current = undefined;
|
||||
};
|
||||
|
||||
notifRef.current?.close();
|
||||
notifRef.current = noti;
|
||||
},
|
||||
[mx, setPending]
|
||||
);
|
||||
|
||||
const playSound = useCallback(() => {
|
||||
const audioElement = audioRef.current;
|
||||
audioElement?.play();
|
||||
@@ -279,32 +238,85 @@ function MessageNotifications() {
|
||||
const sender = mEvent.getSender();
|
||||
const eventId = mEvent.getId();
|
||||
if (!sender || !eventId || mEvent.getSender() === mx.getUserId()) return;
|
||||
|
||||
// Deduplicate: don't show a second banner if this event fires twice
|
||||
// (e.g., decrypted events re-emitted by the SDK).
|
||||
if (notifiedEventsRef.current.has(eventId)) return;
|
||||
|
||||
const pushActions = pushProcessor.actionsForEvent(mEvent);
|
||||
if (!pushActions?.notify) return;
|
||||
const loudByRule = Boolean(pushActions.tweaks?.sound);
|
||||
const isHighlightByRule = Boolean(pushActions.tweaks?.highlight);
|
||||
|
||||
// Deduplicate: never fire the same notification twice for the same event.
|
||||
if (notifiedEventsRef.current.has(eventId)) return;
|
||||
// If neither a loud nor a highlight rule matches, nothing to show.
|
||||
if (!isHighlightByRule && !loudByRule) return;
|
||||
|
||||
// Page hidden: SW (push) handles the OS notification. Nothing to do in-app.
|
||||
if (document.visibilityState !== 'visible') return;
|
||||
|
||||
// Record as notified to prevent duplicate banners (e.g. re-emitted decrypted events).
|
||||
notifiedEventsRef.current.add(eventId);
|
||||
if (notifiedEventsRef.current.size > 200) {
|
||||
const first = notifiedEventsRef.current.values().next().value;
|
||||
if (first) notifiedEventsRef.current.delete(first);
|
||||
}
|
||||
|
||||
// Page hidden: if push is enabled, SW handles the OS notification. If not, nothing to do.
|
||||
if (document.visibilityState !== 'visible') return;
|
||||
// Page is visible — show the themed in-app notification banner for any
|
||||
// highlighted message (mention / keyword) or loud push rule.
|
||||
if ((isHighlightByRule || loudByRule) && showNotifications) {
|
||||
const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption);
|
||||
const avatarMxc =
|
||||
room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl();
|
||||
const roomAvatar = avatarMxc
|
||||
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined)
|
||||
: undefined;
|
||||
const resolvedSenderName =
|
||||
getMemberDisplayName(room, sender, nicknamesRef.current) ??
|
||||
getMxIdLocalPart(sender) ??
|
||||
sender;
|
||||
const previewText = resolveNotificationPreviewText({
|
||||
content: mEvent.getContent(),
|
||||
eventType: mEvent.getType(),
|
||||
isEncryptedRoom,
|
||||
showMessageContent,
|
||||
showEncryptedMessageContent,
|
||||
});
|
||||
const payload = buildRoomMessageNotification({
|
||||
roomName: room.name ?? 'Unknown',
|
||||
roomAvatar,
|
||||
username: resolvedSenderName,
|
||||
previewText,
|
||||
silent: !notificationSound,
|
||||
eventId,
|
||||
});
|
||||
const { roomId } = room;
|
||||
const capturedEventId = eventId;
|
||||
const capturedUserId = mx.getUserId() ?? undefined;
|
||||
const canonicalAlias = room.getCanonicalAlias();
|
||||
const serverName = canonicalAlias?.split(':')[1] ?? room.roomId.split(':')[1] ?? undefined;
|
||||
setInAppBanner({
|
||||
id: eventId,
|
||||
title: payload.title,
|
||||
roomName: room.name ?? undefined,
|
||||
serverName,
|
||||
senderName: resolvedSenderName,
|
||||
body: previewText,
|
||||
icon: roomAvatar,
|
||||
onClick: () => {
|
||||
window.focus();
|
||||
setPending({ roomId, eventId: capturedEventId, targetSessionId: capturedUserId });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 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.
|
||||
// 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')) {
|
||||
const isEncryptedRoom = !!getStateEvent(room, StateEvent.RoomEncryption);
|
||||
const avatarMxc =
|
||||
room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl();
|
||||
notify({
|
||||
const osPayload = buildRoomMessageNotification({
|
||||
roomName: room.name ?? 'Unknown',
|
||||
roomAvatar: avatarMxc
|
||||
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined)
|
||||
@@ -313,8 +325,6 @@ function MessageNotifications() {
|
||||
getMemberDisplayName(room, sender, nicknamesRef.current) ??
|
||||
getMxIdLocalPart(sender) ??
|
||||
sender,
|
||||
roomId: room.roomId,
|
||||
eventId,
|
||||
previewText: resolveNotificationPreviewText({
|
||||
content: mEvent.getContent(),
|
||||
eventType: mEvent.getType(),
|
||||
@@ -324,7 +334,15 @@ function MessageNotifications() {
|
||||
}),
|
||||
// Play sound only if the push rule requests it and the user has sounds enabled.
|
||||
silent: !notificationSound || !loudByRule,
|
||||
eventId,
|
||||
});
|
||||
const noti = new window.Notification(osPayload.title, osPayload.options);
|
||||
const { roomId } = room;
|
||||
noti.onclick = () => {
|
||||
window.focus();
|
||||
setPending({ roomId, eventId, targetSessionId: mx.getUserId() ?? undefined });
|
||||
noti.close();
|
||||
};
|
||||
}
|
||||
|
||||
if (notificationSound && loudByRule) {
|
||||
@@ -344,7 +362,8 @@ function MessageNotifications() {
|
||||
showEncryptedMessageContent,
|
||||
usePushNotifications,
|
||||
playSound,
|
||||
notify,
|
||||
setInAppBanner,
|
||||
setPending,
|
||||
selectedRoomId,
|
||||
useAuthentication,
|
||||
]);
|
||||
@@ -470,6 +489,7 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) {
|
||||
<MessageNotifications />
|
||||
<BackgroundNotifications />
|
||||
<SyncNotificationSettingsWithServiceWorker />
|
||||
<NotificationBanner />
|
||||
{children}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -17,14 +17,18 @@ import {
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { sessionsAtom, activeSessionIdAtom, Session, sessionsHighlightAtom } from '$state/sessions';
|
||||
import {
|
||||
sessionsAtom,
|
||||
activeSessionIdAtom,
|
||||
Session,
|
||||
backgroundUnreadCountsAtom,
|
||||
} from '$state/sessions';
|
||||
import {
|
||||
SidebarItem,
|
||||
SidebarItemTooltip,
|
||||
SidebarAvatar,
|
||||
SidebarItemBadge,
|
||||
} from '$components/sidebar';
|
||||
import { UnreadBadge } from '$components/unread-badge';
|
||||
import { UserAvatar } from '$components/user-avatar';
|
||||
import { nameInitials } from '$utils/common';
|
||||
import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix';
|
||||
@@ -39,6 +43,7 @@ import { Settings } from '$features/settings';
|
||||
import { Modal500 } from '$components/Modal500';
|
||||
import { createLogger } from '$utils/debug';
|
||||
import { useClientConfig } from '$hooks/useClientConfig';
|
||||
import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge';
|
||||
|
||||
const log = createLogger('AccountSwitcherTab');
|
||||
|
||||
@@ -48,7 +53,7 @@ function AccountRow({
|
||||
displayName,
|
||||
avatarUrl,
|
||||
isBusy,
|
||||
highlightCount,
|
||||
unread,
|
||||
onSwitch,
|
||||
onSignOut,
|
||||
}: {
|
||||
@@ -57,7 +62,7 @@ function AccountRow({
|
||||
displayName?: string;
|
||||
avatarUrl?: string;
|
||||
isBusy?: boolean;
|
||||
highlightCount?: number;
|
||||
unread?: { total: number; highlight: number };
|
||||
onSwitch: (session: Session) => void;
|
||||
onSignOut: (session: Session) => void;
|
||||
}) {
|
||||
@@ -85,8 +90,10 @@ function AccountRow({
|
||||
}
|
||||
after={
|
||||
<Box gap="200" alignItems="Center" shrink="No">
|
||||
{!isActive && highlightCount != null && highlightCount > 0 && (
|
||||
<UnreadBadge highlight count={highlightCount} />
|
||||
{!isActive && unread && unread.total > 0 && (
|
||||
<UnreadBadgeCenter>
|
||||
<UnreadBadge highlight={unread.highlight > 0} count={unread.total} />
|
||||
</UnreadBadgeCenter>
|
||||
)}
|
||||
{isActive && (
|
||||
<Icon size="200" src={Icons.Check} style={{ color: 'var(--mx-c-success)' }} />
|
||||
@@ -137,8 +144,17 @@ export function AccountSwitcherTab() {
|
||||
const sessions = useAtomValue(sessionsAtom);
|
||||
const [activeSessionId, setActiveSessionId] = useAtom(activeSessionIdAtom);
|
||||
const setSessions = useSetAtom(sessionsAtom);
|
||||
const [sessionHighlights, setSessionHighlights] = useAtom(sessionsHighlightAtom);
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const backgroundUnreads = useAtomValue(backgroundUnreadCountsAtom);
|
||||
const setBackgroundUnreads = useSetAtom(backgroundUnreadCountsAtom);
|
||||
|
||||
// Total unread count across all background sessions (for the sidebar badge).
|
||||
const totalBackgroundUnread = Object.entries(backgroundUnreads)
|
||||
.filter(([uid]) => uid !== (activeSessionId ?? sessions[0]?.userId))
|
||||
.reduce((acc, [, u]) => acc + u.total, 0);
|
||||
const anyBackgroundHighlight = Object.entries(backgroundUnreads)
|
||||
.filter(([uid]) => uid !== (activeSessionId ?? sessions[0]?.userId))
|
||||
.some(([, u]) => u.highlight > 0);
|
||||
|
||||
const [menuAnchor, setMenuAnchor] = useState<RectCords>();
|
||||
const [busyUserIds, setBusyUserIds] = useState<Set<string>>(new Set());
|
||||
@@ -173,14 +189,14 @@ export function AccountSwitcherTab() {
|
||||
setMenuAnchor(undefined);
|
||||
navigate(getHomePath(), { replace: true });
|
||||
setActiveSessionId(session.userId);
|
||||
// Clear the highlight badge for the account we're switching to.
|
||||
setSessionHighlights((prev) => {
|
||||
// Clear the unread badge for the account we're now switching into.
|
||||
setBackgroundUnreads((prev) => {
|
||||
const next = { ...prev };
|
||||
delete next[session.userId];
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[navigate, setActiveSessionId, setSessionHighlights]
|
||||
[navigate, setActiveSessionId, setBackgroundUnreads]
|
||||
);
|
||||
|
||||
const handleSignOut = useCallback(
|
||||
@@ -237,10 +253,6 @@ export function AccountSwitcherTab() {
|
||||
getMxIdLocalPart(activeSession?.userId ?? '') ?? activeSession?.userId ?? '';
|
||||
const label = activeDisplayName ?? activeLocalPart;
|
||||
|
||||
const inactiveHighlightTotal = sessions
|
||||
.filter((s) => s.userId !== (activeSessionId ?? sessions[0]?.userId))
|
||||
.reduce((sum, s) => sum + (sessionHighlights[s.userId] ?? 0), 0);
|
||||
|
||||
if (!activeSession) return null;
|
||||
|
||||
return (
|
||||
@@ -262,9 +274,9 @@ export function AccountSwitcherTab() {
|
||||
</SidebarAvatar>
|
||||
)}
|
||||
</SidebarItemTooltip>
|
||||
{inactiveHighlightTotal > 0 && (
|
||||
{totalBackgroundUnread > 0 && (
|
||||
<SidebarItemBadge hasCount>
|
||||
<UnreadBadge highlight count={inactiveHighlightTotal} />
|
||||
<UnreadBadge highlight={anyBackgroundHighlight} count={totalBackgroundUnread} />
|
||||
</SidebarItemBadge>
|
||||
)}
|
||||
|
||||
@@ -310,7 +322,7 @@ export function AccountSwitcherTab() {
|
||||
displayName={rowDisplayName}
|
||||
avatarUrl={rowAvatarUrl}
|
||||
isBusy={busyUserIds.has(session.userId)}
|
||||
highlightCount={sessionHighlights[session.userId]}
|
||||
unread={!isActive ? backgroundUnreads[session.userId] : undefined}
|
||||
onSwitch={handleSwitch}
|
||||
onSignOut={handleSignOut}
|
||||
/>
|
||||
|
||||
@@ -171,9 +171,36 @@ export type PendingNotification = {
|
||||
|
||||
export const pendingNotificationAtom = atom<PendingNotification | null>(null);
|
||||
|
||||
// ─── In-app notification banner ────────────────────────────────────────────
|
||||
|
||||
export type InAppBannerNotification = {
|
||||
/** Unique id; used to deduplicate rapid-fire events. */
|
||||
id: string;
|
||||
/** Primary title line – kept for backwards-compat (background accounts). */
|
||||
title: string;
|
||||
/** Room display name (used as the #channel part of the subtitle). */
|
||||
roomName?: string;
|
||||
/** Homeserver extracted from the canonical alias or room ID (e.g. matrix.org). */
|
||||
serverName?: string;
|
||||
/** Display name of the sender. */
|
||||
senderName?: string;
|
||||
body?: string;
|
||||
/** URL of an avatar or room icon to display inside the banner. */
|
||||
icon?: string;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
export const inAppBannerAtom = atom<InAppBannerNotification | null>(null);
|
||||
|
||||
// ─── Per-background-account unread counts ──────────────────────────────────
|
||||
|
||||
export type BackgroundUnread = {
|
||||
total: number;
|
||||
highlight: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Tracks the count of highlight-level (mention/keyword) notifications received
|
||||
* by each background (inactive) session. Keyed by userId.
|
||||
* Cleared when a session becomes active or is signed out.
|
||||
* Keyed by userId. Counts accumulate while a session is in the background
|
||||
* and are cleared when the user switches to that account.
|
||||
*/
|
||||
export const sessionsHighlightAtom = atom<Record<string, number>>({});
|
||||
export const backgroundUnreadCountsAtom = atom<Record<string, BackgroundUnread>>({});
|
||||
Reference in new issue
Block a user