import AppKit import SwiftUI /// Configures macOS window appearance and text-field blur for `@effect/ui-native` apps. /// /// Call `configure` or use the SwiftUI `.effectUIWindow(...)` modifier to opt in. /// Call `transparentRoot(_:)` from `customize(_:)` to reveal the backdrop. @MainActor public enum EffectUIWindow { /// Window backdrop rendered behind uncovered React Native content. public enum Backdrop: Hashable, Sendable { /// Liquid Glass on macOS 26+ when built with Swift 6.2+; otherwise an /// `NSVisualEffectView` with `.hudWindow` material and `.behindWindow` blending. case glass /// An `NSVisualEffectView` with the given material and `.behindWindow` blending. case material(NSVisualEffectView.Material) /// Removes the backdrop and restores any opacity and background color saved by this helper. case none } /// Title bar and toolbar style. public enum Toolbar: Hashable, Sendable { /// Hides the title and uses a unified toolbar to align traffic lights with a 52pt top row. /// Adds an empty toolbar if the window has none. case unifiedInset /// Restores title bar settings changed by this helper and removes any toolbar it added. case none } private static var windowStateKey: UInt8 = 0 private static var blurHooks: (monitor: Any, close: NSObjectProtocol)? private static var blurWindowCount = 0 /// Configures a macOS window's backdrop, toolbar, and text-field blur. /// /// When `backdrop` is not `.none`, the window is made non-opaque with a clear /// background and the backdrop view is placed behind `window.contentView`'s /// subviews. Pair with `EffectUIWindow.transparentRoot(_:)` in `customize(_:)`. /// By default, outside clicks and unmodified Escape end text editing. public static func configure( _ window: NSWindow, backdrop: Backdrop = .none, toolbar: Toolbar = .none, blurOnOutsideClick: Bool = true ) { let state = windowState(for: window) state.backdropView?.removeFromSuperview() if let contentView = window.contentView, let view = makeBackdropView(for: backdrop) { view.frame = contentView.bounds view.autoresizingMask = [.width, .height] contentView.addSubview(view, positioned: .below, relativeTo: nil) state.backdropView = view } configureWindow( window, owner: nil, WindowSettings( clearBackground: backdrop != .none, toolbar: toolbar, blurOnOutsideClick: blurOnOutsideClick ) ) } /// Clears a React Native root view's background so the window backdrop shows /// where the app draws no background. Call from `customize(_:)`. public static func transparentRoot(_ rootView: NSView) { if rootView.responds(to: NSSelectorFromString("setBackgroundColor:")) { rootView.setValue(NSColor.clear, forKey: "backgroundColor") } else { rootView.wantsLayer = true rootView.layer?.backgroundColor = NSColor.clear.cgColor } } fileprivate static func configureWindow( _ window: NSWindow, owner: ObjectIdentifier?, _ settings: WindowSettings ) { let state = windowState(for: window) state.owner = owner if settings.clearBackground { if state.savedAppearance == nil { state.savedAppearance = (window.isOpaque, window.backgroundColor) } window.isOpaque = false window.backgroundColor = .clear } else if let saved = state.savedAppearance { window.isOpaque = saved.isOpaque window.backgroundColor = saved.backgroundColor state.savedAppearance = nil } applyToolbar(settings.toolbar, to: window, state: state) setBlurOnOutsideClick(settings.blurOnOutsideClick, state: state) } private static func setBlurOnOutsideClick(_ enabled: Bool, state: WindowState) { if enabled { guard !state.blurRegistered else { return } if blurHooks == nil { guard let monitor = NSEvent.addLocalMonitorForEvents( matching: [.leftMouseDown, .keyDown], handler: { event in let consume = MainActor.assumeIsolated { guard let window = event.window, Self.existingWindowState(for: window)?.blurRegistered == true else { return false } return Self.endEditing(window, for: event) } return consume ? nil : event }) else { return } let close = NotificationCenter.default.addObserver( forName: NSWindow.willCloseNotification, object: nil, queue: nil ) { notification in MainActor.assumeIsolated { guard let window = notification.object as? NSWindow, let state = Self.existingWindowState(for: window), state.blurRegistered else { return } Self.setBlurOnOutsideClick(false, state: state) } } blurHooks = (monitor, close) } state.blurRegistered = true blurWindowCount += 1 } else { guard state.blurRegistered else { return } state.blurRegistered = false releaseBlurWindowCount() } } fileprivate static func releaseBlurWindowCount() { blurWindowCount = max(0, blurWindowCount - 1) guard blurWindowCount == 0, let hooks = blurHooks else { return } NSEvent.removeMonitor(hooks.monitor) NotificationCenter.default.removeObserver(hooks.close) blurHooks = nil } fileprivate static func release(_ window: NSWindow, owner: ObjectIdentifier) { guard existingWindowState(for: window)?.owner == owner else { return } configureWindow(window, owner: nil, WindowSettings()) } fileprivate static func makeBackdropView(for backdrop: Backdrop) -> NSView? { switch backdrop { case .none: return nil case .glass: #if compiler(>=6.2) if #available(macOS 26.0, *) { return NSGlassEffectView() } #endif return makeVisualEffectView(material: .hudWindow) case .material(let material): return makeVisualEffectView(material: material) } } private static func makeVisualEffectView(material: NSVisualEffectView.Material) -> NSVisualEffectView { let view = NSVisualEffectView() view.material = material view.blendingMode = .behindWindow view.state = .followsWindowActiveState return view } private static func applyToolbar(_ toolbar: Toolbar, to window: NSWindow, state: WindowState) { switch toolbar { case .none: guard let saved = state.savedToolbar else { return } if let installed = saved.installedToolbar, window.toolbar === installed { window.toolbar = nil } if !saved.hadFullSizeContentView { window.styleMask.remove(.fullSizeContentView) } window.toolbarStyle = saved.toolbarStyle window.titleVisibility = saved.titleVisibility window.titlebarAppearsTransparent = saved.titlebarAppearsTransparent state.savedToolbar = nil case .unifiedInset: if state.savedToolbar == nil { state.savedToolbar = WindowState.SavedToolbar( hadFullSizeContentView: window.styleMask.contains(.fullSizeContentView), toolbarStyle: window.toolbarStyle, titleVisibility: window.titleVisibility, titlebarAppearsTransparent: window.titlebarAppearsTransparent ) } if window.toolbar == nil { let bar = NSToolbar(identifier: "EffectUIWindowToolbar") window.toolbar = bar state.savedToolbar?.installedToolbar = bar } window.styleMask.insert(.fullSizeContentView) window.toolbarStyle = .unified window.titleVisibility = .hidden window.titlebarAppearsTransparent = true } } // AppKit keeps text fields focused through clicks on non-focusable React views. // Resigning first responder lets React Native emit `topBlur` and update ui-native's focus state. // Consume Escape only when the editor resigns; always pass clicks through. private static func endEditing(_ window: NSWindow, for event: NSEvent) -> Bool { if event.type == .keyDown { // 53 is kVK_Escape. Preserve Escape during IME composition. guard event.keyCode == 53, event.modifierFlags.isDisjoint(with: [.command, .option, .control, .shift]), window.firstResponder is NSText, (window.firstResponder as? NSTextView)?.hasMarkedText() != true else { return false } return window.makeFirstResponder(nil) } guard window.firstResponder is NSText else { return false } let root = window.contentView?.superview ?? window.contentView if let hit = root?.hitTest(event.locationInWindow), sequence(first: hit, next: { $0.superview }).contains(where: { $0 is NSText || $0 is NSTextField || ($0 as? NSScrollView)?.documentView is NSText }) { return false } window.makeFirstResponder(nil) return false } private static func existingWindowState(for window: NSWindow) -> WindowState? { objc_getAssociatedObject(window, &windowStateKey) as? WindowState } private static func windowState(for window: NSWindow) -> WindowState { if let existing = existingWindowState(for: window) { return existing } let state = WindowState() objc_setAssociatedObject(window, &windowStateKey, state, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return state } } private struct WindowSettings: Equatable { var clearBackground = false var toolbar = EffectUIWindow.Toolbar.none var blurOnOutsideClick = false } private final class WindowState { struct SavedToolbar { weak var installedToolbar: NSToolbar? = nil let hadFullSizeContentView: Bool let toolbarStyle: NSWindow.ToolbarStyle let titleVisibility: NSWindow.TitleVisibility let titlebarAppearsTransparent: Bool } var owner: ObjectIdentifier? var blurRegistered = false weak var backdropView: NSView? var savedAppearance: (isOpaque: Bool, backgroundColor: NSColor?)? var savedToolbar: SavedToolbar? deinit { if blurRegistered { if Thread.isMainThread { MainActor.assumeIsolated { EffectUIWindow.releaseBlurWindowCount() } } else { Task { @MainActor in EffectUIWindow.releaseBlurWindowCount() } } } } } public extension View { /// Sets the hosting window's backdrop and toolbar, with text-field blur on /// outside click or unmodified Escape enabled by default. /// /// Detaching restores saved window settings and disables blur unless another /// modifier or `configure` call has taken over the window. func effectUIWindow( backdrop: EffectUIWindow.Backdrop = .none, toolbar: EffectUIWindow.Toolbar = .none, blurOnOutsideClick: Bool = true ) -> some View { modifier( EffectUIWindowModifier( backdrop: backdrop, settings: WindowSettings( clearBackground: backdrop != .none, toolbar: toolbar, blurOnOutsideClick: blurOnOutsideClick ) ) ) } } private struct EffectUIWindowModifier: ViewModifier { let backdrop: EffectUIWindow.Backdrop let settings: WindowSettings func body(content: Content) -> some View { content .ignoresSafeArea(edges: settings.toolbar == .unifiedInset ? .all : []) .background { if backdrop != .none { EffectUIBackdropView(backdrop: backdrop) .id(backdrop) .ignoresSafeArea() } EffectUIWindowConfigurator(settings: settings) } } } private struct EffectUIBackdropView: NSViewRepresentable { let backdrop: EffectUIWindow.Backdrop func makeNSView(context: Context) -> NSView { EffectUIWindow.makeBackdropView(for: backdrop) ?? NSView() } func updateNSView(_ nsView: NSView, context: Context) {} } private struct EffectUIWindowConfigurator: NSViewRepresentable { let settings: WindowSettings func makeNSView(context: Context) -> EffectUIWindowObserverView { let view = EffectUIWindowObserverView() view.settings = settings return view } func updateNSView(_ nsView: EffectUIWindowObserverView, context: Context) { nsView.settings = settings } static func dismantleNSView(_ nsView: EffectUIWindowObserverView, coordinator: ()) { nsView.detach() } } private final class EffectUIWindowObserverView: NSView { var settings = WindowSettings() { didSet { if settings != oldValue { apply() } } } private weak var attachedWindow: NSWindow? override func viewDidMoveToWindow() { super.viewDidMoveToWindow() if attachedWindow !== window { detach() attachedWindow = window } apply() } func detach() { if let window = attachedWindow { attachedWindow = nil EffectUIWindow.release(window, owner: ObjectIdentifier(self)) } } override func hitTest(_ point: NSPoint) -> NSView? { nil } private func apply() { if let window = attachedWindow { EffectUIWindow.configureWindow(window, owner: ObjectIdentifier(self), settings) } } }