1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
|
import SwiftUI
struct MullvadAlert: Identifiable {
enum AlertType {
case warning
case error
}
enum ActionType {
case danger
case normal
}
struct Action {
let type: MainButtonStyle.Style
let title: LocalizedStringKey
let identifier: AccessibilityIdentifier?
let handler: () async -> Void
}
let id = UUID()
let type: AlertType
let messages: [LocalizedStringKey]
let action: Action?
let dismissButtonTitle: LocalizedStringKey
}
struct AlertModifier: ViewModifier {
@Binding var alert: MullvadAlert?
@State var loading = false
func body(content: Content) -> some View {
content
.fullScreenCover(item: $alert) { alert in
alertView(for: alert)
}
.transaction {
$0.disablesAnimations = true
}
}
@ViewBuilder
private func alertView(for alert: MullvadAlert) -> some View {
VStack {
Spacer()
alertContent(for: alert)
Spacer()
}
.accessibilityElement(children: .contain)
.accessibilityIdentifier(.alertContainerView)
.padding()
.background(ClearBackgroundView())
}
@ViewBuilder
private func alertContent(for alert: MullvadAlert) -> some View {
VStack(spacing: 16) {
alertIcon(for: alert.type)
alertMessage(alert.messages)
VStack(spacing: 16) {
alertAction(for: alert.action)
alertAction(
for: MullvadAlert.Action(
type: .default,
title: alert.dismissButtonTitle,
identifier: nil,
handler: { self.alert = nil }
))
}
}
.padding()
.background(Color.mullvadBackground)
.cornerRadius(8)
}
@ViewBuilder
private func alertIcon(for type: MullvadAlert.AlertType) -> some View {
switch type {
case .error, .warning:
Image.mullvadIconAlert
.resizable()
.frame(width: 48, height: 48)
}
}
@ViewBuilder
private func alertMessage(_ messages: [LocalizedStringKey]) -> some View {
VStack {
ForEach(Array(messages.enumerated()), id: \.offset) { _, text in
HStack {
Text(text)
.font(.mullvadSmall)
.foregroundColor(.mullvadTextPrimary.opacity(0.6))
Spacer()
}
}
}
}
@ViewBuilder
private func alertAction(for action: MullvadAlert.Action?) -> some View {
if let action = action {
MainButton(
text: action.title,
style: action.type,
action: {
Task {
loading = true
await action.handler()
loading = false
}
}
)
.accessibilityIdentifier(action.identifier)
} else {
EmptyView()
}
}
}
extension View {
func mullvadAlert(item: Binding<MullvadAlert?>) -> some View {
modifier(AlertModifier(alert: item))
}
}
#Preview {
Text("Hello, World!")
.mullvadAlert(
item:
.constant(
.init(
type: .warning,
messages: ["Something needs to be done"],
action: .init(
type: .danger,
title: "Do it!",
identifier: nil,
handler: {}
),
dismissButtonTitle: "Cancel"
)
)
)
}
|