fix(badges): improve unread count calculation and background session highlight badges
- getUnreadInfo: guard stale-count clamp with roomHaveUnread; exclude own messages from clamp trigger; walk live timeline to compute real fallback counts using PushProcessor instead of hard-coding dot badge - roomToUnreadAtom: remove mDirectAtom dependency for DM parent filtering; add ClientEvent.Room handler to seed badge state when rooms join - sessionsHighlightAtom added to track highlight counts per inactive session - AccountSwitcherTab: show UnreadBadge on inactive session rows and sidebar icon
This commit is contained in:
1 parent
c996e5e31b
commit
c2a43ec43a
4 files changed
+100
-25
No files matched your search
@@ -17,8 +17,14 @@ import {
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { sessionsAtom, activeSessionIdAtom, Session } from '$state/sessions';
|
||||
import { SidebarItem, SidebarItemTooltip, SidebarAvatar } from '$components/sidebar';
|
||||
import { sessionsAtom, activeSessionIdAtom, Session, sessionsHighlightAtom } 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';
|
||||
@@ -42,6 +48,7 @@ function AccountRow({
|
||||
displayName,
|
||||
avatarUrl,
|
||||
isBusy,
|
||||
highlightCount,
|
||||
onSwitch,
|
||||
onSignOut,
|
||||
}: {
|
||||
@@ -50,6 +57,7 @@ function AccountRow({
|
||||
displayName?: string;
|
||||
avatarUrl?: string;
|
||||
isBusy?: boolean;
|
||||
highlightCount?: number;
|
||||
onSwitch: (session: Session) => void;
|
||||
onSignOut: (session: Session) => void;
|
||||
}) {
|
||||
@@ -77,6 +85,9 @@ function AccountRow({
|
||||
}
|
||||
after={
|
||||
<Box gap="200" alignItems="Center" shrink="No">
|
||||
{!isActive && highlightCount != null && highlightCount > 0 && (
|
||||
<UnreadBadge highlight count={highlightCount} />
|
||||
)}
|
||||
{isActive && (
|
||||
<Icon size="200" src={Icons.Check} style={{ color: 'var(--mx-c-success)' }} />
|
||||
)}
|
||||
@@ -126,6 +137,7 @@ 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 [menuAnchor, setMenuAnchor] = useState<RectCords>();
|
||||
@@ -161,8 +173,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) => {
|
||||
const next = { ...prev };
|
||||
delete next[session.userId];
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[navigate, setActiveSessionId]
|
||||
[navigate, setActiveSessionId, setSessionHighlights]
|
||||
);
|
||||
|
||||
const handleSignOut = useCallback(
|
||||
@@ -219,6 +237,10 @@ 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 (
|
||||
@@ -240,6 +262,11 @@ export function AccountSwitcherTab() {
|
||||
</SidebarAvatar>
|
||||
)}
|
||||
</SidebarItemTooltip>
|
||||
{inactiveHighlightTotal > 0 && (
|
||||
<SidebarItemBadge hasCount>
|
||||
<UnreadBadge highlight count={inactiveHighlightTotal} />
|
||||
</SidebarItemBadge>
|
||||
)}
|
||||
|
||||
<PopOut
|
||||
anchor={menuAnchor}
|
||||
@@ -283,6 +310,7 @@ export function AccountSwitcherTab() {
|
||||
displayName={rowDisplayName}
|
||||
avatarUrl={rowAvatarUrl}
|
||||
isBusy={busyUserIds.has(session.userId)}
|
||||
highlightCount={sessionHighlights[session.userId]}
|
||||
onSwitch={handleSwitch}
|
||||
onSignOut={handleSignOut}
|
||||
/>
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
ReceiptContent,
|
||||
ReceiptType,
|
||||
EventType,
|
||||
ClientEvent,
|
||||
} from '$types/matrix-sdk';
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import {
|
||||
@@ -32,7 +33,6 @@ import { useSyncState } from '$hooks/useSyncState';
|
||||
import { useRoomsNotificationPreferencesContext } from '$hooks/useRoomsNotificationPreferences';
|
||||
import { getClientSyncDiagnostics } from '$client/initMatrix';
|
||||
import { roomToParentsAtom } from './roomToParents';
|
||||
import { mDirectAtom } from '../mDirectList';
|
||||
|
||||
export type RoomToUnreadAction =
|
||||
| {
|
||||
@@ -123,14 +123,13 @@ const baseRoomToUnread = atom<RoomToUnread>(new Map());
|
||||
export const roomToUnreadAtom = atom<RoomToUnread, [RoomToUnreadAction], undefined>(
|
||||
(get) => get(baseRoomToUnread),
|
||||
(get, set, action) => {
|
||||
const dmRoomIds = get(mDirectAtom);
|
||||
const getEffectiveParents = (roomId: string): Set<string> =>
|
||||
dmRoomIds.has(roomId) ? new Set() : getAllParents(get(roomToParentsAtom), roomId);
|
||||
const allParentsOf = (roomId: string): Set<string> =>
|
||||
getAllParents(get(roomToParentsAtom), roomId);
|
||||
|
||||
if (action.type === 'RESET') {
|
||||
const draftRoomToUnread: RoomToUnread = new Map();
|
||||
action.unreadInfos.forEach((unreadInfo) => {
|
||||
putUnreadInfo(draftRoomToUnread, getEffectiveParents(unreadInfo.roomId), unreadInfo);
|
||||
putUnreadInfo(draftRoomToUnread, allParentsOf(unreadInfo.roomId), unreadInfo);
|
||||
});
|
||||
set(baseRoomToUnread, draftRoomToUnread);
|
||||
return;
|
||||
@@ -144,7 +143,7 @@ export const roomToUnreadAtom = atom<RoomToUnread, [RoomToUnreadAction], undefin
|
||||
produce(get(baseRoomToUnread), (draftRoomToUnread) =>
|
||||
deleteUnreadInfo(
|
||||
draftRoomToUnread,
|
||||
getEffectiveParents(unreadInfo.roomId),
|
||||
allParentsOf(unreadInfo.roomId),
|
||||
unreadInfo.roomId
|
||||
)
|
||||
)
|
||||
@@ -154,14 +153,14 @@ export const roomToUnreadAtom = atom<RoomToUnread, [RoomToUnreadAction], undefin
|
||||
}
|
||||
const currentUnread = get(baseRoomToUnread).get(unreadInfo.roomId);
|
||||
if (currentUnread && unreadEqual(currentUnread, unreadInfoToUnread(unreadInfo))) {
|
||||
// Do not update if unread data has not changes
|
||||
// Do not update if unread data has not changed
|
||||
// like total & highlight
|
||||
return;
|
||||
}
|
||||
set(
|
||||
baseRoomToUnread,
|
||||
produce(get(baseRoomToUnread), (draftRoomToUnread) =>
|
||||
putUnreadInfo(draftRoomToUnread, getEffectiveParents(unreadInfo.roomId), unreadInfo)
|
||||
putUnreadInfo(draftRoomToUnread, allParentsOf(unreadInfo.roomId), unreadInfo)
|
||||
)
|
||||
);
|
||||
return;
|
||||
@@ -170,7 +169,7 @@ export const roomToUnreadAtom = atom<RoomToUnread, [RoomToUnreadAction], undefin
|
||||
set(
|
||||
baseRoomToUnread,
|
||||
produce(get(baseRoomToUnread), (draftRoomToUnread) =>
|
||||
deleteUnreadInfo(draftRoomToUnread, getEffectiveParents(action.roomId), action.roomId)
|
||||
deleteUnreadInfo(draftRoomToUnread, allParentsOf(action.roomId), action.roomId)
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -329,6 +328,25 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo
|
||||
};
|
||||
}, [mx, setUnreadAtom]);
|
||||
|
||||
// Seed badge state immediately when a room is first registered with the client
|
||||
// (e.g. after joining or receiving an invite that gets auto-accepted).
|
||||
// This avoids the brief window after refresh where badges are invisible until
|
||||
// the next timeline event arrives. Notifications are NOT triggered here —
|
||||
// ClientNonUIFeatures handles live notification pop-ups via its own listener.
|
||||
useEffect(() => {
|
||||
const handleRoomAdded = (room: Room) => {
|
||||
if (room.isSpaceRoom() || room.getMyMembership() !== Membership.Join) return;
|
||||
const unreadInfo = getUnreadInfo(room, { applyFixup: shouldApplyUnreadFixup() });
|
||||
if (unreadInfo.total > 0 || unreadInfo.highlight > 0) {
|
||||
setUnreadAtom({ type: 'PUT', unreadInfo });
|
||||
}
|
||||
};
|
||||
mx.on(ClientEvent.Room, handleRoomAdded as (room: Room) => void);
|
||||
return () => {
|
||||
mx.removeListener(ClientEvent.Room, handleRoomAdded as (room: Room) => void);
|
||||
};
|
||||
}, [mx, setUnreadAtom, shouldApplyUnreadFixup]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (spaceChildResetTimerRef.current !== null) {
|
||||
|
||||
@@ -165,8 +165,15 @@ export const activeSessionIdAtom = atom<string | undefined, [string | undefined]
|
||||
|
||||
export type PendingNotification = {
|
||||
roomId: string;
|
||||
eventId: string;
|
||||
eventId?: string;
|
||||
targetSessionId?: string;
|
||||
};
|
||||
|
||||
export const pendingNotificationAtom = atom<PendingNotification | null>(null);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export const sessionsHighlightAtom = atom<Record<string, number>>({});
|
||||
+34
-12
@@ -13,6 +13,7 @@ import {
|
||||
MatrixEvent,
|
||||
MsgType,
|
||||
NotificationCountType,
|
||||
PushProcessor,
|
||||
RelationType,
|
||||
Room,
|
||||
RoomMember,
|
||||
@@ -240,18 +241,24 @@ export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadIn
|
||||
}
|
||||
|
||||
let total = room.getUnreadNotificationCount(NotificationCountType.Total);
|
||||
let highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight);
|
||||
let syntheticDotUnread = false;
|
||||
const highlight = room.getUnreadNotificationCount(NotificationCountType.Highlight);
|
||||
|
||||
// If our latest main-timeline notification event is confirmed read, clamp its stale count.
|
||||
// Only apply to the room (non-thread) portion so thread reply counts are preserved.
|
||||
if (userId && total > 0 && highlight === 0) {
|
||||
// Guard: only clamp when the room has NO receipt-confirmed unread events; if roomHaveUnread
|
||||
// is true then there genuinely are unread messages and the SDK count is not fully stale.
|
||||
if (userId && total > 0 && highlight === 0 && !roomHaveUnread(room.client, room)) {
|
||||
const roomTotal = room.getRoomUnreadNotificationCount(NotificationCountType.Total);
|
||||
if (roomTotal > 0) {
|
||||
const liveEvents = room.getLiveTimeline().getEvents();
|
||||
// Exclude the user's own messages: own sent events are always "read" (hasUserReadEvent
|
||||
// returns true for them), which would cause the clamp to fire incorrectly.
|
||||
const latestNotification = [...liveEvents]
|
||||
.reverse()
|
||||
.find((event) => !event.isSending() && isNotificationEvent(event));
|
||||
.find(
|
||||
(event) =>
|
||||
!event.isSending() && event.getSender() !== userId && isNotificationEvent(event)
|
||||
);
|
||||
const latestNotificationId = latestNotification?.getId();
|
||||
if (latestNotificationId && room.hasUserReadEvent(userId, latestNotificationId)) {
|
||||
// Subtract only the stale main-timeline count; thread totals remain intact.
|
||||
@@ -260,19 +267,34 @@ export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadIn
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for cases where SDK counters are stale/zero but unread-by-receipt state still exists.
|
||||
// Represent as a dot badge (count=0) rather than a numeric badge.
|
||||
if (total === 0 && highlight === 0 && roomHaveUnread(room.client, room)) {
|
||||
highlight = 1;
|
||||
syntheticDotUnread = true;
|
||||
// Fallback: SDK counters are stale/zero but there are receipt-confirmed unread
|
||||
// messages. Walk the live timeline to compute real counts so the badge number
|
||||
// and highlight colour reflect actual state rather than a hard-coded stub.
|
||||
if (total === 0 && highlight === 0 && userId && roomHaveUnread(room.client, room)) {
|
||||
const readUpToId = room.getEventReadUpTo(userId);
|
||||
const liveEvents = room.getLiveTimeline().getEvents();
|
||||
let fallbackTotal = 0;
|
||||
let fallbackHighlight = 0;
|
||||
const pushProcessor = new PushProcessor(room.client);
|
||||
for (let i = liveEvents.length - 1; i >= 0; i -= 1) {
|
||||
const event = liveEvents[i];
|
||||
if (!event) break;
|
||||
if (event.getId() === readUpToId) break;
|
||||
if (isNotificationEvent(event) && event.getSender() !== userId) {
|
||||
fallbackTotal += 1;
|
||||
const pushActions = pushProcessor.actionsForEvent(event);
|
||||
if (pushActions?.tweaks?.highlight) fallbackHighlight += 1;
|
||||
}
|
||||
}
|
||||
if (fallbackTotal > 0) {
|
||||
return { roomId: room.roomId, highlight: fallbackHighlight, total: fallbackTotal };
|
||||
}
|
||||
}
|
||||
|
||||
const resolvedTotal = syntheticDotUnread ? total : Math.max(total, highlight);
|
||||
|
||||
return {
|
||||
roomId: room.roomId,
|
||||
highlight,
|
||||
total: resolvedTotal,
|
||||
total: Math.max(total, highlight),
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user