Files
Kymo/kymo/Features/Settings/SettingsWindowLifecycle.swift
T

45 lines
1.8 KiB
Swift

import SwiftUI
import AppKit
/// Keep the app discoverable while its settings window is open, including reopen.
struct SettingsWindowLifecycle: NSViewRepresentable {
var title: String
var onClose: () -> Void = {}
func makeNSView(context: Context) -> WindowObserverView { WindowObserverView() }
func updateNSView(_ nsView: WindowObserverView, context: Context) {
nsView.onClose = onClose
nsView.title = title
}
final class WindowObserverView: NSView {
override func hitTest(_ point: NSPoint) -> NSView? { nil }
var onClose: () -> Void = {}
var title = "" { didSet { window?.title = title } }
private var tokens: [NSObjectProtocol] = []
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
for token in tokens { NotificationCenter.default.removeObserver(token) }
tokens.removeAll()
guard let window else { return }
window.title = title
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) } }
}
}