feat(desktop): source window focus from the OS instead of DOM focus events

This commit is contained in:
Erwan Leboucher committed 2026-07-26 17:53:44 +02:00
1 parent 91b51fa108
commit 740a082e92
7 files changed
+201 -16

No files matched your search

@@ -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;
}
+2 -2
View File
@@ -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,
+4 -3
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;
@@ -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;
+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]);
};
+21 -2
View File
@@ -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);
};
};