DismissAction.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /// An action that dismisses the current presentation context.
  2. ///
  3. /// Use the `dismiss` environment value to get an instance of this action,
  4. /// then call it to dismiss (close) the enclosing sheet.
  5. ///
  6. /// If you want to close the enclosing window, use ``EnvironmentValues/dismissWindow``
  7. /// instead.
  8. ///
  9. /// Example usage:
  10. /// ```swift
  11. /// struct SheetContentView: View {
  12. /// @Environment(\.dismiss) var dismiss
  13. ///
  14. /// var body: some View {
  15. /// VStack {
  16. /// Text("Sheet Content")
  17. /// Button("Close") {
  18. /// dismiss()
  19. /// }
  20. /// }
  21. /// }
  22. /// }
  23. /// ```
  24. @MainActor
  25. public struct DismissAction {
  26. private let action: @Sendable @MainActor () -> Void
  27. nonisolated internal init(action: @escaping @Sendable @MainActor () -> Void) {
  28. self.action = action
  29. }
  30. /// Dismisses the current presentation context.
  31. public func callAsFunction() {
  32. action()
  33. }
  34. }
  35. /// Environment key for the dismiss action.
  36. private struct DismissActionKey: EnvironmentKey {
  37. static var defaultValue: DismissAction {
  38. DismissAction(action: {
  39. #if DEBUG
  40. logger.warning("dismiss() called but no presentation context is available")
  41. #endif
  42. })
  43. }
  44. }
  45. extension EnvironmentValues {
  46. /// An action that dismisses the current presentation context.
  47. ///
  48. /// Use this environment value to get a dismiss action that can be called
  49. /// to dismiss (close) the enclosing sheet, popover, or other presentation.
  50. ///
  51. /// If you want to close the enclosing window, use ``EnvironmentValues/dismissWindow``
  52. /// instead.
  53. ///
  54. /// Example:
  55. /// ```swift
  56. /// struct SheetContentView: View {
  57. /// @Environment(\.dismiss) var dismiss
  58. ///
  59. /// var body: some View {
  60. /// Button("Close") {
  61. /// dismiss()
  62. /// }
  63. /// }
  64. /// }
  65. /// ```
  66. @MainActor
  67. public var dismiss: DismissAction {
  68. get { self[DismissActionKey.self] }
  69. set { self[DismissActionKey.self] = newValue }
  70. }
  71. }