Skip to content

Commit

Permalink
Add buttons to AlertDetails
Browse files Browse the repository at this point in the history
  • Loading branch information
mpdifran committed Feb 15, 2024
1 parent ae1744c commit 57a87b1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
2 changes: 1 addition & 1 deletion Sources/AppUI/Extensions/Alert/Alert+Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import SwiftUI
public extension Alert {

init(error: Error?, onDismiss: @escaping () -> Void = { }) {
self.init(title: Text("Oops"),
self.init(title: Text("Error"),
message: Text(error?.localizedDescription ?? ""),
dismissButton: .default(Text("OK"), action: onDismiss))
}
Expand Down
36 changes: 32 additions & 4 deletions Sources/AppUI/Extensions/View/View+Alert.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@ import SwiftUI
public struct AlertDetails {
let title: String
let message: String?
public let buttons: [Button]
let onDismiss: () -> Void

public init(
title: String,
message: String?,
buttons: [Button] = [],
onDismiss: @escaping () -> Void = { }
) {
self.title = title
self.message = message
self.buttons = buttons
self.onDismiss = onDismiss
}

Expand All @@ -27,12 +30,28 @@ public struct AlertDetails {
error: Error,
onDismiss: @escaping () -> Void = { }
) {
self.title = title ?? "Oops"
self.title = title ?? "Error"
self.message = error.localizedDescription
self.buttons = []
self.onDismiss = onDismiss
}
}

public extension AlertDetails {
struct Button: Identifiable {
public let id = UUID()
public let title: String
public let role: ButtonRole?
public let action: () -> Void

public init(title: String, role: ButtonRole? = nil, action: @escaping () -> Void) {
self.title = title
self.role = role
self.action = action
}
}
}

public struct ErrorAlertDetails {
let error: Error
let onRetry: () -> Void
Expand All @@ -59,7 +78,7 @@ public extension View {
}

func alert(errorAlertDetails: Binding<ErrorAlertDetails?>) -> some View {
return alert("Oops", isPresented: Binding(isNotNil: errorAlertDetails)) {
return alert("Error", isPresented: Binding(isNotNil: errorAlertDetails)) {
Button("OK", role: .cancel) {
errorAlertDetails.wrappedValue?.onDismiss()
}
Expand All @@ -77,8 +96,17 @@ public extension View {

func alert(alertDetails: Binding<AlertDetails?>) -> some View {
return alert(alertDetails.wrappedValue?.title ?? "", isPresented: Binding(isNotNil: alertDetails)) {
Button("OK") {
alertDetails.wrappedValue?.onDismiss()
if let buttons = alertDetails.wrappedValue?.buttons, !buttons.isEmpty {
ForEach(buttons) { button in
Button(button.title, role: button.role) {
button.action()
alertDetails.wrappedValue?.onDismiss()
}
}
} else {
Button("OK") {
alertDetails.wrappedValue?.onDismiss()
}
}
} message: {
if let message = alertDetails.wrappedValue?.message {
Expand Down

0 comments on commit 57a87b1

Please sign in to comment.