44 */
55
66import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
7+ import { emitTo } from '@tauri-apps/api/event'
78import { getAppLogger } from '$lib/logging/logger'
89
910const log = getAppLogger ( 'settings' )
1011
11- let settingsWindow : WebviewWindow | null = null
12-
1312const SETTINGS_WIDTH = 800
1413const SETTINGS_HEIGHT = 600
1514const SETTINGS_MAX_WIDTH = 852
@@ -18,29 +17,21 @@ const SETTINGS_MIN_HEIGHT = 400
1817
1918/**
2019 * Opens the settings window, or focuses it if already open.
21- * Window always opens centered on screen.
20+ * Uses `WebviewWindow.getByLabel` to reliably detect an existing window
21+ * instead of a module-level JS reference that can go stale.
2222 */
2323export async function openSettingsWindow ( ) : Promise < void > {
24- log . debug ( 'openSettingsWindow called' )
25-
26- // Check if window already exists
27- if ( settingsWindow ) {
28- log . debug ( 'Settings window already exists, attempting to focus' )
29- try {
30- await settingsWindow . setFocus ( )
31- log . debug ( 'Focused existing settings window' )
32- return
33- } catch ( error ) {
34- // Window was closed, create a new one
35- log . debug ( 'Failed to focus existing window (likely closed), creating new: {error}' , { error } )
36- settingsWindow = null
37- }
24+ const existing = await WebviewWindow . getByLabel ( 'settings' )
25+ if ( existing ) {
26+ // Emit to the settings window so it can self-focus. Cross-window setFocus()
27+ // doesn't reliably bring a window to front on macOS.
28+ await emitTo ( 'settings' , 'focus-self' )
29+ return
3830 }
3931
40- log . info ( 'Creating new settings window with url=/settings ' )
32+ log . info ( 'Creating new settings window' )
4133
42- // Create new settings window, centered on screen
43- settingsWindow = new WebviewWindow ( 'settings' , {
34+ new WebviewWindow ( 'settings' , {
4435 url : '/settings' ,
4536 title : 'Settings' ,
4637 width : SETTINGS_WIDTH ,
@@ -51,22 +42,6 @@ export async function openSettingsWindow(): Promise<void> {
5142 center : true ,
5243 resizable : true ,
5344 decorations : true ,
54- } )
55-
56- // Listen for window creation success
57- void settingsWindow . once ( 'tauri://created' , ( ) => {
58- log . info ( 'Settings window created successfully' )
59- } )
60-
61- // Listen for window close to clean up reference
62- void settingsWindow . once ( 'tauri://destroyed' , ( ) => {
63- log . debug ( 'Settings window destroyed, cleaning up reference' )
64- settingsWindow = null
65- } )
66-
67- // Handle any creation errors
68- void settingsWindow . once ( 'tauri://error' , ( e ) => {
69- log . error ( 'Failed to create settings window: {error}' , { error : e } )
70- settingsWindow = null
45+ focus : true ,
7146 } )
7247}
0 commit comments