Fix the timeline loading a room's entire history on open (#1373)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

Opening a room paginated until it ran out of history, scrolling the view
up as it went. Worst rooms burned 8-10s of CPU per open on a Pixel 3a.

The viewport-fill effect compared `processedEvents.length` against a
value captured in the same render, so the guard was always true and the
condition reduced to `!hasRealScrollRoom || atTop`. It re-runs on every
length change, so staying near the top kept it firing. Pre-existing
since March, triggered by #1363 leaving fewer rendered events per page.

Also in here:

- `setAtBottom` was only called from the scroll handler, so a resize
(composer, keyboard) left it stale and killed auto-follow. Now
recomputed from the ResizeObserver.
- Notification sound gates on window focus instead of tab visibility. A
visible but unfocused window is now silent unless background
notification sounds is on.
- Desktop reads window focus from `onFocusChanged`, since
`focusin`/`focusout` miss app switches. Mobile and web unchanged.

Pixel 3a, release builds, CPU per room open:

| | before | after |
|---|---|---|
| Sable Announcements | 9.72s | 1.06s |
| 1 (DM) | 8.03s | 2.57s |
| 10 DMs | 31.34s | 17.19s |

Fixes #1371

#### Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
7w1 authored and GitHub committed 2026-07-26 20:54:42 +00:00
commit f5650a3a65
11 files changed
+376 -64

No files matched your search

@@ -0,0 +1,5 @@
---
default: patch
---
# Keep following the timeline when a message grows after it renders
@@ -0,0 +1,5 @@
---
default: patch
---
# Stop the timeline loading a room's whole history on open
@@ -7,6 +7,7 @@ import { isTauri } from '@tauri-apps/api/core';
import { type as osType } from '@tauri-apps/plugin-os';
import { TauriFrontendReady } from '$components/tauri/TauriFrontendReady';
import { TauriWindowFocus } from '$components/tauri/TauriWindowFocus';
import { DesktopTitleBar } from '$components/tauri/DesktopTitleBar';
import { MacTitleBar } from '$components/tauri/MacTitleBar';
import { DesktopUpdater } from '$pages/client/DesktopUpdater';
@@ -80,6 +81,7 @@ function AppShellFrame({ children, portalContainer, onPortalContainerChange }: A
return (
<>
<TauriFrontendReady />
<TauriWindowFocus />
<div
style={{
display: 'flex',
@@ -0,0 +1,114 @@
import { render, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { TauriWindowFocus } from './TauriWindowFocus';
import { isWindowFocused, setNativeWindowFocused, subscribeWindowFocus } from '$utils/dom';
const { mockIsTauri, mockOsType, mockIsFocused, mockOnFocusChanged, mockGetCurrentWindow } =
vi.hoisted(() => ({
mockIsTauri: vi.fn<() => boolean>(),
mockOsType: vi.fn<() => string>(),
mockIsFocused: vi.fn<() => Promise<boolean>>(),
mockOnFocusChanged: vi.fn<(cb: (e: { payload: boolean }) => void) => Promise<() => void>>(),
mockGetCurrentWindow: vi.fn<() => unknown>(),
}));
vi.mock('@tauri-apps/api/core', () => ({ isTauri: mockIsTauri }));
vi.mock('@tauri-apps/plugin-os', () => ({ type: mockOsType }));
vi.mock('@tauri-apps/api/window', () => ({ getCurrentWindow: mockGetCurrentWindow }));
vi.mock('$utils/debug', () => ({
createLogger: () => ({
log: vi.fn<(...args: unknown[]) => void>(),
warn: vi.fn<(...args: unknown[]) => void>(),
}),
}));
describe('TauriWindowFocus', () => {
beforeEach(() => {
mockIsTauri.mockReturnValue(true);
mockOsType.mockReturnValue('linux');
mockIsFocused.mockResolvedValue(true);
mockOnFocusChanged.mockResolvedValue(() => {});
mockGetCurrentWindow.mockReturnValue({
isFocused: mockIsFocused,
onFocusChanged: mockOnFocusChanged,
});
});
afterEach(() => {
setNativeWindowFocused(undefined);
vi.clearAllMocks();
});
it('seeds focus from the OS on desktop', async () => {
mockIsFocused.mockResolvedValue(false);
render(<TauriWindowFocus />);
await waitFor(() => expect(isWindowFocused()).toBe(false));
});
it('tracks later focus changes and notifies subscribers', async () => {
render(<TauriWindowFocus />);
await waitFor(() => expect(mockOnFocusChanged).toHaveBeenCalled());
const seen: boolean[] = [];
const unsubscribe = subscribeWindowFocus((focused) => seen.push(focused));
const emit = mockOnFocusChanged.mock.calls[0]![0];
emit({ payload: false });
expect(isWindowFocused()).toBe(false);
expect(seen).toEqual([false]);
emit({ payload: true });
expect(isWindowFocused()).toBe(true);
expect(seen).toEqual([false, true]);
unsubscribe();
});
it('does not subscribe on mobile, leaving the DOM path authoritative', async () => {
mockOsType.mockReturnValue('android');
render(<TauriWindowFocus />);
await waitFor(() => expect(mockOnFocusChanged).not.toHaveBeenCalled());
});
it('does not subscribe outside Tauri', async () => {
mockIsTauri.mockReturnValue(false);
render(<TauriWindowFocus />);
await waitFor(() => expect(mockGetCurrentWindow).not.toHaveBeenCalled());
});
it('ignores a stale initial read that resolves after a focus change', async () => {
let resolveInitial: ((focused: boolean) => void) | undefined;
mockIsFocused.mockReturnValue(
new Promise<boolean>((resolve) => {
resolveInitial = resolve;
})
);
render(<TauriWindowFocus />);
await waitFor(() => expect(mockOnFocusChanged).toHaveBeenCalled());
mockOnFocusChanged.mock.calls[0]![0]({ payload: false });
expect(isWindowFocused()).toBe(false);
resolveInitial?.(true);
await Promise.resolve();
expect(isWindowFocused()).toBe(false);
});
it('releases the override on unmount so the DOM value applies again', async () => {
mockIsFocused.mockResolvedValue(false);
const { unmount } = render(<TauriWindowFocus />);
await waitFor(() => expect(isWindowFocused()).toBe(false));
unmount();
await waitFor(() => expect(isWindowFocused()).toBe(document.hasFocus()));
});
it('stops listening on unmount', async () => {
const stop = vi.fn<() => void>();
mockOnFocusChanged.mockResolvedValue(stop);
const { unmount } = render(<TauriWindowFocus />);
await waitFor(() => expect(mockOnFocusChanged).toHaveBeenCalled());
unmount();
await waitFor(() => expect(stop).toHaveBeenCalled());
});
});
@@ -0,0 +1,50 @@
import { useEffect } from 'react';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { isTauri } from '@tauri-apps/api/core';
import { type as osType } from '@tauri-apps/plugin-os';
import { setNativeWindowFocused } from '$utils/dom';
import { createLogger } from '$utils/debug';
const log = createLogger('TauriWindowFocus');
// Mobile has no window focus to report; the DOM path stays authoritative there.
const DESKTOP = new Set(['windows', 'linux', 'macos']);
export function TauriWindowFocus() {
useEffect(() => {
if (!isTauri() || !DESKTOP.has(osType())) return undefined;
let unlisten: (() => void) | undefined;
let cancelled = false;
// isFocused() is an IPC round-trip and can resolve after a newer focus change.
let sawEvent = false;
const appWindow = getCurrentWindow();
appWindow
.isFocused()
.then((focused) => {
if (!cancelled && !sawEvent) setNativeWindowFocused(focused);
})
.catch((error: unknown) => log.warn('Failed to read initial window focus:', error));
appWindow
.onFocusChanged(({ payload }) => {
sawEvent = true;
setNativeWindowFocused(payload);
})
.then((stop) => {
if (cancelled) stop();
else unlisten = stop;
})
.catch((error: unknown) => log.warn('Failed to subscribe to window focus:', error));
return () => {
cancelled = true;
unlisten?.();
setNativeWindowFocused(undefined);
};
}, []);
return null;
}
+58 -32
View File
@@ -12,7 +12,7 @@ import {
import type { Editor } from 'slate';
import { useAtomValue, useSetAtom, useStore } from 'jotai';
import type { Room, MatrixEvent, EventTimelineSet } from '$types/matrix-sdk';
import { Direction, EventType } from '$types/matrix-sdk';
import { Direction, EventTimeline, EventType } from '$types/matrix-sdk';
import classNames from 'classnames';
import type { VListHandle } from 'virtua';
import { VList } from 'virtua';
@@ -27,6 +27,7 @@ import { useMessageEdit } from '$hooks/useMessageEdit';
import { useDocumentFocusChange } from '$hooks/useDocumentFocusChange';
import { useIsInactivePanel } from '$hooks/useRoom';
import { markAsRead } from '$utils/notifications';
import { isWindowFocused } from '$utils/dom';
import { today, yesterday, timeDayMonthYear } from '$utils/time';
import {
unwrapRelationJumpTarget,
@@ -71,6 +72,8 @@ import { useTimelineRendererContext } from '$hooks/timeline/useTimelineRendererC
import { TimelineScrollingProvider, useScrollActivity } from '$hooks/useTimelineScrollActivity';
import * as css from './RoomTimeline.css';
const MAX_VIEWPORT_FILL_PAGINATIONS = 5;
const TimelineFloat = as<'div', css.TimelineFloatVariants>(
({ position, className, ...props }, ref) => (
<Box
@@ -396,6 +399,18 @@ export function RoomTimeline({
atBottomRef.current = val;
}, []);
// Resizes move the bottom without emitting a scroll event.
const syncAtBottom = useCallback(
(offset?: number) => {
const v = vListRef.current;
if (!v) return;
const scrollTop = offset ?? v.scrollOffset;
const isNowAtBottom = v.scrollSize - scrollTop - v.viewportSize < 100;
if (isNowAtBottom !== atBottomRef.current) setAtBottom(isNowAtBottom);
},
[setAtBottom]
);
const [shift, setShift] = useState(false);
const [topSpacerHeight, setTopSpacerHeight] = useState(0);
@@ -546,6 +561,7 @@ export function RoomTimeline({
const canPaginateBackRef = useRef(timelineSync.canPaginateBack);
canPaginateBackRef.current = timelineSync.canPaginateBack;
const viewportFillCountRef = useRef(0);
const liveTimelineLinkedRef = useRef(timelineSync.liveTimelineLinked);
liveTimelineLinkedRef.current = timelineSync.liveTimelineLinked;
@@ -738,18 +754,36 @@ export function RoomTimeline({
const atBottom = atBottomRef.current;
const shrank = newHeight < prev;
if (shrank && atBottom) {
const lastIndex = processedEventsRef.current.length - 1;
if (lastIndex >= 0) {
vListRef.current?.scrollToIndex(lastIndex, { align: 'end' });
}
}
prevViewportHeightRef.current = newHeight;
const lastIndex = processedEventsRef.current.length - 1;
if (shrank && atBottom && lastIndex >= 0) {
// Geometry is still pre-scroll here; the repin's own scroll event resyncs.
vListRef.current?.scrollToIndex(lastIndex, { align: 'end' });
return;
}
syncAtBottom();
});
observer.observe(el);
return () => observer.disconnect();
}, []);
}, [syncAtBottom]);
// Decrypting rows and late-loading images grow without changing eventsLength,
// so useTimelineSync's auto-scroll never re-fires for them.
const lastScrollSizeRef = useRef(0);
useLayoutEffect(() => {
const v = vListRef.current;
if (!v) return;
const grew = v.scrollSize > lastScrollSizeRef.current;
lastScrollSizeRef.current = v.scrollSize;
if (!grew || !atBottomRef.current || !liveTimelineLinkedRef.current) return;
const lastIndex = processedEventsRef.current.length - 1;
if (lastIndex >= 0) v.scrollToIndex(lastIndex, { align: 'end' });
});
const actions = useTimelineActions({
room,
@@ -870,8 +904,7 @@ export function RoomTimeline({
);
useEffect(() => {
if (atBottomState && document.hasFocus() && timelineSync.liveTimelineLinked)
tryAutoMarkAsRead();
if (atBottomState && isWindowFocused() && timelineSync.liveTimelineLinked) tryAutoMarkAsRead();
}, [
atBottomState,
timelineSync.liveTimelineLinked,
@@ -886,10 +919,7 @@ export function RoomTimeline({
if (!v) return;
const distanceFromBottom = v.scrollSize - offset - v.viewportSize;
const isNowAtBottom = distanceFromBottom < 100;
if (isNowAtBottom !== atBottomRef.current) {
setAtBottom(isNowAtBottom);
}
syncAtBottom(offset);
if (offset < 500 && canPaginateBackRef.current && backwardStatusRef.current === 'idle') {
void timelineSyncRef.current.handleTimelinePagination(true);
@@ -902,7 +932,7 @@ export function RoomTimeline({
void timelineSyncRef.current.handleTimelinePagination(false);
}
},
[notifyScroll, setAtBottom]
[notifyScroll, syncAtBottom]
);
const showLoadingPlaceholders =
@@ -965,7 +995,10 @@ export function RoomTimeline({
timelineSync.backwardStatus === 'loading' && timelineSync.eventsLength > 0;
const showFrontPaginationSpinner =
timelineSync.forwardStatus === 'loading' && timelineSync.eventsLength > 0;
const hasPowerLevelState = !!room.currentState.getStateEvents(EventType.RoomPowerLevels, '');
const hasPowerLevelState = !!room
.getLiveTimeline()
?.getState(EventTimeline.FORWARDS)
?.getStateEvents(EventType.RoomPowerLevels, '');
const hideTimelineForRoomState = roomSyncLoading && hideMemberInReadOnly && !hasPowerLevelState;
const timelineBottomFloatLift =
!atBottomState && isReady ? { bottom: `calc(${config.space.S400} + ${toRem(52)})` } : undefined;
@@ -1030,24 +1063,18 @@ export function RoomTimeline({
}, [onEditLastMessageRef, mx, actions]);
useEffect(() => {
const v = vListRef.current;
if (!v) return;
if (
canPaginateBackRef.current &&
backwardStatusRef.current === 'idle' &&
v.scrollSize <= v.viewportSize
) {
void timelineSyncRef.current.handleTimelinePagination(true);
}
}, [timelineSync.eventsLength, timelineSync.backwardStatus]);
viewportFillCountRef.current = 0;
lastScrollSizeRef.current = 0;
}, [room.roomId]);
// Re-enters on every length change, so an unfillable viewport pages to the start of the
// room. Scrolling up is handled by handleVListScroll.
useEffect(() => {
if (!canPaginateBackRef.current) return () => {};
let rafId: number;
let attempts = 0;
const MAX_ATTEMPTS = 20;
const processedLengthAtEffectStart = processedEvents.length;
const check = () => {
const v = vListRef.current;
@@ -1062,18 +1089,17 @@ export function RoomTimeline({
if (!canPaginateBackRef.current) return;
if (backwardStatusRef.current !== 'idle') return;
const atTop = v.scrollOffset < 500;
const noVisibleGrowth = processedEvents.length === processedLengthAtEffectStart;
const hasRealScrollRoom = v.scrollSize > v.viewportSize + 300;
if (viewportFillCountRef.current >= MAX_VIEWPORT_FILL_PAGINATIONS) return;
if (!hasRealScrollRoom || (atTop && noVisibleGrowth)) {
if (v.scrollSize <= v.viewportSize + 300) {
viewportFillCountRef.current += 1;
void timelineSyncRef.current.handleTimelinePagination(true);
}
};
rafId = requestAnimationFrame(check);
return () => cancelAnimationFrame(rafId);
}, [timelineSync.eventsLength, timelineSync.backwardStatus, processedEvents.length]);
}, [room.roomId, timelineSync.eventsLength, timelineSync.backwardStatus]);
return (
<Box grow="Yes" style={{ position: 'relative' }}>
@@ -3,7 +3,7 @@ import { act, renderHook } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import type { Room } from '$types/matrix-sdk';
import { RoomEvent } from '$types/matrix-sdk';
import { useTimelineSync } from './useTimelineSync';
import { countVisibleAmongNewest, useTimelineSync } from './useTimelineSync';
import { getRoomUnreadInfo } from '$utils/timeline';
import type * as TimelineUtils from '$utils/timeline';
@@ -117,6 +117,52 @@ function emitLiveTimelineEvent(
});
}
const makeTimeline = (ids: string[]) => {
const timelineSet = { id: `set-${ids.join('')}` };
return {
getEvents: () => ids.map((id) => ({ id })),
getTimelineSet: () => timelineSet,
};
};
const count = (timelines: unknown[], n: number, backwards: boolean, visibleIds: string[]) => {
const isVisible = (ev: { id: string }) => visibleIds.includes(ev.id);
return countVisibleAmongNewest(timelines as never, n, backwards, isVisible as never);
};
describe('countVisibleAmongNewest', () => {
it('counts only the newest events at the head when paginating backwards', () => {
const timelines = [makeTimeline(['a', 'b', 'c']), makeTimeline(['d', 'e'])];
expect(count(timelines, 3, true, ['a', 'c', 'e'])).toBe(2);
});
it('counts only the newest events at the tail when paginating forwards', () => {
const timelines = [makeTimeline(['a', 'b', 'c']), makeTimeline(['d', 'e'])];
expect(count(timelines, 3, false, ['a', 'c', 'e'])).toBe(2);
});
it('spans timeline boundaries when the fetched count exceeds one timeline', () => {
const timelines = [makeTimeline(['a', 'b']), makeTimeline(['c', 'd'])];
expect(count(timelines, 4, true, ['a', 'b', 'c', 'd'])).toBe(4);
});
it('returns zero when nothing fetched is rendered', () => {
const timelines = [makeTimeline(['a', 'b', 'c'])];
expect(count(timelines, 3, true, [])).toBe(0);
});
it('does not over-count when fetched exceeds the number of loaded events', () => {
const timelines = [makeTimeline(['a', 'b'])];
expect(count(timelines, 10, true, ['a', 'b'])).toBe(2);
});
it('handles empty timelines', () => {
expect(count([], 5, true, ['a'])).toBe(0);
});
});
describe('useTimelineSync', () => {
it('does not snap a non-bottom user to latest after TimelineReset', async () => {
const { room, timelineSet, events } = createRoom();
+53 -12
View File
@@ -27,6 +27,7 @@ import {
getRoomUnreadInfo,
PAGINATION_LIMIT,
} from '$utils/timeline';
import { isWindowFocused } from '$utils/dom';
const EVENT_TIMELINE_LOAD_TIMEOUT_MS = 12000;
@@ -101,6 +102,47 @@ const useEventTimelineLoader = (
[mx, room, onLoad, onError]
);
// Unbounded, a run of entirely hidden pages recurses until the room's history runs out.
const MAX_AUTO_CONTINUATIONS = 3;
// Rendered events among the `count` just-fetched ones: head of the chain when
// paginating backwards, tail when forwards.
export const countVisibleAmongNewest = (
linkedTimelines: EventTimeline[],
count: number,
backwards: boolean,
isEventVisible: (mEvent: MatrixEvent, timelineSet: EventTimelineSet) => boolean
): number => {
let remaining = count;
let visible = 0;
if (backwards) {
for (const timeline of linkedTimelines) {
const events = timeline.getEvents() ?? [];
const timelineSet = timeline.getTimelineSet();
for (let i = 0; i < events.length && remaining > 0; i += 1) {
const mEvent = events[i];
remaining -= 1;
if (mEvent && isEventVisible(mEvent, timelineSet)) visible += 1;
}
if (remaining === 0) break;
}
return visible;
}
for (let t = linkedTimelines.length - 1; t >= 0 && remaining > 0; t -= 1) {
const timeline = linkedTimelines[t];
const events = timeline?.getEvents() ?? [];
const timelineSet = timeline?.getTimelineSet();
for (let i = events.length - 1; i >= 0 && remaining > 0; i -= 1) {
const mEvent = events[i];
remaining -= 1;
if (mEvent && timelineSet && isEventVisible(mEvent, timelineSet)) visible += 1;
}
}
return visible;
};
const useTimelinePagination = (
mx: MatrixClient,
timeline: TimelineState,
@@ -124,7 +166,7 @@ const useTimelinePagination = (
startTransition(() => setTimeline(() => ({ linkedTimelines: newLTimelines })));
};
return async (backwards: boolean) => {
return async (backwards: boolean, autoContinuations = 0) => {
const directionKey = backwards ? 'backward' : 'forward';
if (fetchingRef.current[directionKey]) return;
@@ -188,17 +230,16 @@ const useTimelinePagination = (
let visibleFetched = fetched;
if (isEventVisible && fetched > 0) {
const afterEvents = getLinkedTimelines(firstTimeline).flatMap((t) =>
(t.getEvents() || []).map((ev) => ({ ev, ts: t.getTimelineSet() }))
visibleFetched = countVisibleAmongNewest(
getLinkedTimelines(firstTimeline),
fetched,
backwards,
isEventVisible
);
const newEvents = backwards
? afterEvents.slice(0, fetched)
: afterEvents.slice(afterEvents.length - fetched);
visibleFetched = newEvents.filter(({ ev, ts }) => isEventVisible(ev, ts)).length;
}
let willContinue = false;
if (fetched > 0 && visibleFetched < 5) {
if (fetched > 0 && visibleFetched < 5 && autoContinuations < MAX_AUTO_CONTINUATIONS) {
const checkTimeline = backwards
? freshLTimelines[0]
: freshLTimelines[freshLTimelines.length - 1];
@@ -216,7 +257,7 @@ const useTimelinePagination = (
fetchingRef.current[directionKey] = false;
continuing = true;
willContinue = true;
paginate(backwards);
paginate(backwards, autoContinuations + 1);
// At this point the inner paginate has synchronously set
// fetchingRef.current[directionKey] = true before hitting its own
// await. The finally below will skip the reset.
@@ -495,20 +536,20 @@ export function useTimelineSync({
if (isAtBottomRef.current && atLiveEndRef.current) {
if (
document.hasFocus() &&
isWindowFocused() &&
(!unreadInfo?.readUptoEventId || mEvt.getSender() === mx.getUserId())
) {
requestAnimationFrame(() => markAsRead(mx, mEvt.getRoomId()!, hideReadsRef.current));
}
if (!document.hasFocus() && !unreadInfo) {
if (!isWindowFocused() && !unreadInfo) {
setUnreadInfo(getRoomUnreadInfo(room));
}
// Own messages should feel immediate, and unfocused windows throttle
// scroll animations, which can leave the view stuck mid-scroll.
pendingAutoScrollBehaviorRef.current =
mEvt.getSender() === mx.getUserId() || !document.hasFocus() ? 'instant' : 'smooth';
mEvt.getSender() === mx.getUserId() || !isWindowFocused() ? 'instant' : 'smooth';
setTimeline((ct) => ({ ...ct }));
return;
+8 -9
View File
@@ -1,25 +1,24 @@
import { useEffect } from 'react';
import { isWindowFocused, subscribeWindowFocus } from '$utils/dom';
export const useDocumentFocusChange = (onChange: (focus: boolean) => void) => {
useEffect(() => {
let localFocus = document.hasFocus();
let localFocus = isWindowFocused();
const handleFocus = () => {
if (document.hasFocus()) {
if (localFocus) return;
localFocus = true;
onChange(localFocus);
} else if (localFocus) {
localFocus = false;
onChange(localFocus);
}
const focus = isWindowFocused();
if (focus === localFocus) return;
localFocus = focus;
onChange(localFocus);
};
document.addEventListener('focusin', handleFocus);
document.addEventListener('focusout', handleFocus);
const unsubscribe = subscribeWindowFocus(handleFocus);
return () => {
document.removeEventListener('focusin', handleFocus);
document.removeEventListener('focusout', handleFocus);
unsubscribe();
};
}, [onChange]);
};
@@ -15,7 +15,7 @@ import {
import LogoSVG from '$public/res/svg/logo.svg';
import NotificationSound from '$public/sound/notification.ogg';
import InviteSound from '$public/sound/invite.ogg';
import { notificationPermission } from '$utils/dom';
import { isPageVisible, isWindowFocused, notificationPermission } from '$utils/dom';
import { playNotificationSound } from '$utils/notificationSound';
import {
getTauriNotificationsApi,
@@ -125,10 +125,9 @@ export function InviteNotifications() {
if (invites.length <= perviousInviteLen || mx.getSyncState() !== SyncState.Syncing) return;
// SW push (via Sygnal) handles invite notifications when the app is backgrounded.
if (document.visibilityState !== 'visible' && usePushNotifications) return;
if (!isPageVisible() && usePushNotifications) return;
const tabVisible = document.visibilityState === 'visible';
const withSound = notificationSound && (tabVisible || backgroundNotificationSounds);
const withSound = notificationSound && (isWindowFocused() || backgroundNotificationSounds);
let soundOnNotification = false;
// OS notification for invites — desktop, plus iOS while foregrounded (testing).
@@ -227,8 +226,7 @@ export function MessageNotifications() {
}
const shouldSkipFocusCheck = eventId && skipFocusCheckEvents.has(eventId);
if (!shouldSkipFocusCheck) {
if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected))
return;
if (isWindowFocused() && (selectedRoomId === room?.roomId || notificationSelected)) return;
}
// Older sliding sync proxies (e.g. matrix-sliding-sync) omit num_live,
@@ -339,8 +337,9 @@ export function MessageNotifications() {
// in sandboxed environments, browsers with DnD active, or Electron — and
// an uncaught exception here would abort the handler before setInAppBanner
// is reached, causing in-app notifications to silently vanish too.
const tabVisible = document.visibilityState === 'visible';
const withSound = notificationSound && isLoud && (tabVisible || backgroundNotificationSounds);
const tabVisible = isPageVisible();
const withSound =
notificationSound && isLoud && (isWindowFocused() || backgroundNotificationSounds);
let soundOnNotification = false;
if (
(!isMobileOrTablet() || isIosTauri()) &&
@@ -568,7 +567,7 @@ export function SyncNotificationSettingsWithServiceWorker() {
if (!('serviceWorker' in navigator)) return undefined;
const postVisibility = () => {
const visible = document.visibilityState === 'visible';
const visible = isPageVisible();
const msg = { type: 'setAppVisible', visible };
navigator.serviceWorker.controller?.postMessage(msg);
navigator.serviceWorker.ready.then((reg) => reg.active?.postMessage(msg));
@@ -635,7 +634,7 @@ export function HandleDecryptPushEvent() {
}
const decryptMs = Math.round(performance.now() - decryptStart);
const visible = document.visibilityState === 'visible';
const visible = isPageVisible();
pushRelayLog.info('notification', 'Push relay decryption succeeded', {
eventType: mxEvent.getType(),
decryptMs,
+25
View File
@@ -319,3 +319,28 @@ export const loadImageElementFromMediaUrl = async (
URL.revokeObjectURL(objectUrl);
}
};
// Can the page be seen? Governs in-app UI and the service-worker push hand-off.
export const isPageVisible = (): boolean => document.visibilityState === 'visible';
// Stricter than visibility: a second monitor is visible but unfocused. Desktop
// overrides it from the OS, which sees app switches that focusin/focusout miss.
let nativeWindowFocused: boolean | undefined;
const windowFocusListeners = new Set<(focused: boolean) => void>();
export const isWindowFocused = (): boolean => nativeWindowFocused ?? document.hasFocus();
// undefined releases the override and restores the DOM fallback.
export const setNativeWindowFocused = (focused: boolean | undefined): void => {
if (nativeWindowFocused === focused) return;
nativeWindowFocused = focused;
const resolved = isWindowFocused();
windowFocusListeners.forEach((listener) => listener(resolved));
};
export const subscribeWindowFocus = (listener: (focused: boolean) => void): (() => void) => {
windowFocusListeners.add(listener);
return () => {
windowFocusListeners.delete(listener);
};
};