import SwiftUI /// Presents SwiftUI views as sheets that finish with a result, for flows that ask the user something and wait for the answer. @MainActor enum SheetPresenter { /// Presents a SwiftUI view as a sheet on the window, or in a window of its own when there's no window to attach to. /// /// The view is measured once, before it's presented, so it has to keep the size it starts with. /// - Parameter content: Builds the view, which calls `finish` with its result when it's done. /// - Returns: What the view finished with. Finishing with `nil` is how a view reports that it was cancelled. static func present( from window: NSWindow?, @ViewBuilder content: (_ finish: @escaping (Output?) -> Void) -> Content ) async -> Output? { await withCheckedContinuation { continuation in let box = SheetFinishBox() let hostingView = NSHostingView(rootView: content { box.finish?($0) }) /// The title bar's inset changes as the window turns into a sheet. A hosting view that takes the inset into account /// and resizes its window to fit asks for another constraints pass every time that happens, in the middle of the /// sheet's animation, until AppKit gives up by raising an exception. /// So the view ignores the inset, and the window is sized once instead of following the view's constraints. hostingView.safeAreaRegions = [] let contentSize = hostingView.fittingSize hostingView.sizingOptions = [] let sheetWindow = NSWindow(contentRect: NSRect(origin: .zero, size: contentSize), styleMask: [.titled, .fullSizeContentView], backing: .buffered, defer: false) sheetWindow.titlebarAppearsTransparent = true sheetWindow.isReleasedWhenClosed = false sheetWindow.contentView = hostingView sheetWindow.setContentSize(contentSize) let parent = window.flatMap { $0.isVisible ? $0 : nil } var isFinished = false box.finish = { output in guard !isFinished else { return } isFinished = true box.finish = nil if let parent { parent.endSheet(sheetWindow) } sheetWindow.orderOut(nil) sheetWindow.contentView = nil continuation.resume(returning: output) } if let parent { parent.beginSheet(sheetWindow) } else { sheetWindow.level = .floating sheetWindow.center() sheetWindow.makeKeyAndOrderFront(nil) NSApp.activate() } } } } /// Lets the view hosted in a sheet finish the sheet it's in. private final class SheetFinishBox { var finish: ((Output?) -> Void)? }