DismissWindowAction.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /// An action that closes the enclosing window.
  2. ///
  3. /// Use the ``EnvironmentValues/dismissWindow`` environment value to get an instance
  4. /// of this action, then call it to close the enclosing window.
  5. ///
  6. /// Example usage:
  7. /// ```swift
  8. /// struct ContentView: View {
  9. /// @Environment(\.dismissWindow) var dismissWindow
  10. ///
  11. /// var body: some View {
  12. /// VStack {
  13. /// Text("Window Content")
  14. /// Button("Close") {
  15. /// dismissWindow()
  16. /// }
  17. /// }
  18. /// }
  19. /// }
  20. /// ```
  21. @MainActor
  22. public struct DismissWindowAction {
  23. let backend: any BaseAppBackend
  24. let window: MainActorBox<Any?>
  25. /// Closes the enclosing window.
  26. public func callAsFunction() {
  27. guard let window = window.value else {
  28. logger.warning("dismissWindow() accessed outside of a window's scope")
  29. return
  30. }
  31. // NB: Must come after the `guard` above so that it captures the correct `window` binding
  32. func closeWindow<Backend: BackendFeatures.WindowClosing>(backend: Backend) {
  33. backend.close(window: window as! Backend.Window)
  34. }
  35. guard let backend = backend as? any BackendFeatures.WindowClosing else {
  36. logger.warnOnce(Logger.Message(stringLiteral: "\(type(of: backend)) doesn't support closing windows"))
  37. return
  38. }
  39. closeWindow(backend: backend)
  40. }
  41. }