-
-
Save Jeehut/7601bdbce1af1f848b1ea98f697a0f95 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import AppKit | |
import Dependencies | |
import SwiftUI | |
@available(iOS 16.0, macOS 13.0, *) | |
@available(tvOS, unavailable) | |
@available(watchOS, unavailable) | |
private enum CloseWindowKey: DependencyKey { | |
static let liveValue = CloseWindowEffect { id in | |
Task { @MainActor in | |
if let window = await NSWindow.find(windowId: id) { | |
window.close() | |
} | |
} | |
} | |
static let testValue = CloseWindowEffect { _ in | |
XCTFail(#"Unimplemented: @Dependency(\.closeWindow)"#) | |
} | |
} | |
public struct CloseWindowEffect: Sendable { | |
private let handler: @Sendable (String) async -> Void | |
public init(handler: @escaping @Sendable (String) async -> Void) { | |
self.handler = handler | |
} | |
public func callAsFunction<Window: Identifiable>(_ window: Window) async where Window.ID == String { | |
await self.handler(window.id) | |
} | |
} | |
extension DependencyValues { | |
/// A dependency that closes a window. | |
@available(iOS 16.0, macOS 13.0, *) | |
@available(tvOS, unavailable) | |
@available(watchOS, unavailable) | |
public var closeWindow: CloseWindowEffect { | |
get { self[CloseWindowKey.self] } | |
set { self[CloseWindowKey.self] = newValue } | |
} | |
} | |
extension NSWindow { | |
public static func find(windowId: String) async -> NSWindow? { | |
if let window = self.search(for: windowId) { return window } | |
try? await Task.sleep(for: .milliseconds(50)) | |
if let window = self.search(for: windowId) { return window } | |
try? await Task.sleep(for: .milliseconds(100)) | |
return self.search(for: windowId) | |
} | |
private static func search(for windowId: String) -> NSWindow? { | |
NSApplication.shared.windows.first(where: { $0.identifier?.rawValue.contains(windowId) ?? false }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment