import SwiftUI import AppKit /// Keep the app discoverable while its settings window is open, including reopen. struct SettingsWindowLifecycle: NSViewRepresentable { var onClose: () -> Void = {} func makeNSView(context: Context) -> WindowObserverView { WindowObserverView() } func updateNSView(_ nsView: WindowObserverView, context: Context) { nsView.onClose = onClose } final class WindowObserverView: NSView { override func hitTest(_ point: NSPoint) -> NSView? { nil } var onClose: () -> Void = {} private var tokens: [NSObjectProtocol] = [] override func viewDidMoveToWindow() { super.viewDidMoveToWindow() for token in tokens { NotificationCenter.default.removeObserver(token) } tokens.removeAll() guard let window else { return } tokens.append(NotificationCenter.default.addObserver(forName: NSWindow.didBecomeKeyNotification, object: window, queue: .main) { _ in MainActor.assumeIsolated { if NSApp.activationPolicy() != .regular { NSApp.setActivationPolicy(.regular) } } }) tokens.append(NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification, object: window, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.onClose() NSApp.setActivationPolicy(.accessory) } }) } deinit { for token in tokens { NotificationCenter.default.removeObserver(token) } } } }