From 740a082e9237a10346b524f7116a21fe3ef4be73 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Sun, 26 Jul 2026 14:02:59 +0200 Subject: [PATCH] feat(desktop): source window focus from the OS instead of DOM focus events --- src/app/components/app-shell/AppShell.tsx | 2 + .../tauri/TauriWindowFocus.test.tsx | 114 ++++++++++++++++++ src/app/components/tauri/TauriWindowFocus.tsx | 50 ++++++++ src/app/features/room/RoomTimeline.tsx | 4 +- src/app/hooks/timeline/useTimelineSync.ts | 7 +- src/app/hooks/useDocumentFocusChange.ts | 17 ++- src/app/utils/dom.ts | 23 +++- 7 files changed, 201 insertions(+), 16 deletions(-) create mode 100644 src/app/components/tauri/TauriWindowFocus.test.tsx create mode 100644 src/app/components/tauri/TauriWindowFocus.tsx diff --git a/src/app/components/app-shell/AppShell.tsx b/src/app/components/app-shell/AppShell.tsx index c79e92a9d..4c29e0fab 100644 --- a/src/app/components/app-shell/AppShell.tsx +++ b/src/app/components/app-shell/AppShell.tsx @@ -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 ( <> +
({ + mockIsTauri: vi.fn<() => boolean>(), + mockOsType: vi.fn<() => string>(), + mockIsFocused: vi.fn<() => Promise>(), + 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(); + await waitFor(() => expect(isWindowFocused()).toBe(false)); + }); + + it('tracks later focus changes and notifies subscribers', async () => { + render(); + 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(); + await waitFor(() => expect(mockOnFocusChanged).not.toHaveBeenCalled()); + }); + + it('does not subscribe outside Tauri', async () => { + mockIsTauri.mockReturnValue(false); + render(); + 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((resolve) => { + resolveInitial = resolve; + }) + ); + + render(); + 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(); + 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(); + await waitFor(() => expect(mockOnFocusChanged).toHaveBeenCalled()); + unmount(); + await waitFor(() => expect(stop).toHaveBeenCalled()); + }); +}); diff --git a/src/app/components/tauri/TauriWindowFocus.tsx b/src/app/components/tauri/TauriWindowFocus.tsx new file mode 100644 index 000000000..6aa6aaa15 --- /dev/null +++ b/src/app/components/tauri/TauriWindowFocus.tsx @@ -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; +} diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index d0ec68e1a..66122468e 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -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, @@ -887,8 +888,7 @@ export function RoomTimeline({ ); useEffect(() => { - if (atBottomState && document.hasFocus() && timelineSync.liveTimelineLinked) - tryAutoMarkAsRead(); + if (atBottomState && isWindowFocused() && timelineSync.liveTimelineLinked) tryAutoMarkAsRead(); }, [ atBottomState, timelineSync.liveTimelineLinked, diff --git a/src/app/hooks/timeline/useTimelineSync.ts b/src/app/hooks/timeline/useTimelineSync.ts index 5b7beff14..177ba1cc1 100644 --- a/src/app/hooks/timeline/useTimelineSync.ts +++ b/src/app/hooks/timeline/useTimelineSync.ts @@ -27,6 +27,7 @@ import { getRoomUnreadInfo, PAGINATION_LIMIT, } from '$utils/timeline'; +import { isWindowFocused } from '$utils/dom'; const EVENT_TIMELINE_LOAD_TIMEOUT_MS = 12000; @@ -535,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; diff --git a/src/app/hooks/useDocumentFocusChange.ts b/src/app/hooks/useDocumentFocusChange.ts index ae171b64a..16343d815 100644 --- a/src/app/hooks/useDocumentFocusChange.ts +++ b/src/app/hooks/useDocumentFocusChange.ts @@ -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]); }; diff --git a/src/app/utils/dom.ts b/src/app/utils/dom.ts index cadb9de65..eedf20b09 100644 --- a/src/app/utils/dom.ts +++ b/src/app/utils/dom.ts @@ -323,5 +323,24 @@ export const loadImageElementFromMediaUrl = async ( // 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. -export const isWindowFocused = (): boolean => document.hasFocus(); +// 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); + }; +};