-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathToast.swift
More file actions
296 lines (261 loc) · 9.28 KB
/
Toast.swift
File metadata and controls
296 lines (261 loc) · 9.28 KB
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import ComposableArchitecture
import Dependencies
import Foundation
import SwiftUI
import AppKitExtension
public enum ToastLevel {
case info
case warning
case danger
case error
var icon: String {
switch self {
case .warning: return "exclamationmark.circle.fill"
case .danger: return "exclamationmark.circle.fill"
case .error: return "xmark.circle.fill"
case .info: return "exclamationmark.triangle.fill"
}
}
var color: Color {
switch self {
case .warning: return Color(nsColor: .systemOrange)
case .danger, .error: return Color(nsColor: .systemRed)
case .info: return Color.accentColor
}
}
}
public struct ToastKey: EnvironmentKey {
public static var defaultValue: (String, ToastLevel) -> Void = { _, _ in }
}
public extension EnvironmentValues {
var toast: (String, ToastLevel) -> Void {
get { self[ToastKey.self] }
set { self[ToastKey.self] = newValue }
}
}
public struct ToastControllerDependencyKey: DependencyKey {
public static let liveValue = ToastController(messages: [])
}
public extension DependencyValues {
var toastController: ToastController {
get { self[ToastControllerDependencyKey.self] }
set { self[ToastControllerDependencyKey.self] = newValue }
}
var toast: (String, ToastLevel) -> Void {
return { content, level in
toastController.toast(content: content, level: level, namespace: nil)
}
}
var namespacedToast: (String, ToastLevel, String) -> Void {
return {
content, level, namespace in
toastController.toast(content: content, level: level, namespace: namespace)
}
}
var persistentToast: (String, String, ToastLevel) -> Void {
return { title, content, level in
toastController.toast(title: title, content: content, level: level, namespace: nil)
}
}
}
public struct ToastButton: Equatable {
public let title: String
public let action: () -> Void
public init(title: String, action: @escaping () -> Void) {
self.title = title
self.action = action
}
public static func ==(lhs: ToastButton, rhs: ToastButton) -> Bool {
lhs.title == rhs.title
}
}
public class ToastController: ObservableObject {
public struct Message: Identifiable, Equatable {
public var namespace: String?
public var title: String?
public var id: UUID
public var level: ToastLevel
public var content: Text
public var button: ToastButton?
// Convenience initializer for auto-dismissing messages (no title, no button)
public init(
id: UUID = UUID(),
level: ToastLevel,
namespace: String? = nil,
content: Text
) {
self.id = id
self.level = level
self.namespace = namespace
self.title = nil
self.content = content
self.button = nil
}
// Convenience initializer for persistent messages (title is required)
public init(
id: UUID = UUID(),
level: ToastLevel,
namespace: String? = nil,
title: String,
content: Text,
button: ToastButton? = nil
) {
self.id = id
self.level = level
self.namespace = namespace
self.title = title
self.content = content
self.button = button
}
}
@Published public var messages: [Message] = []
public init(messages: [Message]) {
self.messages = messages
}
@MainActor
private func removeMessageWithAnimation(withId id: UUID) {
withAnimation(.easeInOut(duration: 0.2)) {
messages.removeAll { $0.id == id }
}
}
private func showMessage(_ message: Message, autoDismissDelay: UInt64?) {
Task { @MainActor in
withAnimation(.easeInOut(duration: 0.2)) {
messages.append(message)
messages = messages.suffix(3)
}
if let autoDismissDelay = autoDismissDelay {
try await Task.sleep(nanoseconds: autoDismissDelay)
removeMessageWithAnimation(withId: message.id)
}
}
}
// Auto-dismissing toast (title and button are not allowed)
public func toast(
content: String,
level: ToastLevel,
namespace: String? = nil
) {
let message = Message(level: level, namespace: namespace, content: Text(content))
showMessage(message, autoDismissDelay: 4_000_000_000)
}
// Persistent toast (title is required, button is optional)
public func toast(
title: String,
content: String,
level: ToastLevel,
namespace: String? = nil,
button: ToastButton? = nil
) {
// Support markdown in persistent toasts
let contentText: Text
if let attributedString = try? AttributedString(markdown: content) {
contentText = Text(attributedString)
} else {
contentText = Text(content)
}
let message = Message(
level: level,
namespace: namespace,
title: title,
content: contentText,
button: button
)
showMessage(message, autoDismissDelay: nil)
}
public func dismissMessage(withId id: UUID) {
Task { @MainActor in
removeMessageWithAnimation(withId: id)
}
}
}
@Reducer
public struct Toast {
public typealias Message = ToastController.Message
@ObservableState
public struct State: Equatable {
var isObservingToastController = false
public var messages: [Message] = []
public init(messages: [Message] = []) {
self.messages = messages
}
}
public enum Action: Equatable {
case start
case updateMessages([Message])
case toast(String, ToastLevel, String?)
case toastPersistent(String, String, ToastLevel, String?, ToastButton?)
}
@Dependency(\.toastController) var toastController
struct CancelID: Hashable {}
public init() {}
public var body: some ReducerOf<Self> {
Reduce { state, action in
switch action {
case .start:
guard !state.isObservingToastController else { return .none }
state.isObservingToastController = true
return .run { send in
let stream = AsyncStream<[Message]> { continuation in
let cancellable = toastController.$messages.sink { newValue in
continuation.yield(newValue)
}
continuation.onTermination = { _ in
cancellable.cancel()
}
}
for await newValue in stream {
try Task.checkCancellation()
await send(.updateMessages(newValue), animation: .linear(duration: 0.2))
}
}.cancellable(id: CancelID(), cancelInFlight: true)
case let .updateMessages(messages):
state.messages = messages
return .none
case let .toast(content, level, namespace):
toastController.toast(content: content, level: level, namespace: namespace)
return .none
case let .toastPersistent(title, content, level, namespace, button):
toastController
.toast(
title: title,
content: content,
level: level,
namespace: namespace,
button: button
)
return .none
}
}
}
}
public extension NSWorkspace {
/// Opens the System Preferences/Settings app at the Extensions pane
/// - Parameter extensionPointIdentifier: Optional identifier for specific extension type
static func openExtensionsPreferences(extensionPointIdentifier: String? = nil) {
var urlString = "x-apple.systempreferences:com.apple.ExtensionsPreferences"
if let extensionPointIdentifier = extensionPointIdentifier {
urlString += "?extensionPointIdentifier=\(extensionPointIdentifier)"
}
NSWorkspace.shared.open(URL(string: urlString)!)
}
/// Opens the Xcode Extensions preferences directly
static func openXcodeExtensionsPreferences() {
openExtensionsPreferences(extensionPointIdentifier: "com.apple.dt.Xcode.extension.source-editor")
}
static func restartXcode() {
// Find current Xcode path before quitting
// Restart if we found a valid path
if let xcodeURL = getXcodeBundleURL() {
// Quit Xcode
let script = NSAppleScript(source: "tell application \"Xcode\" to quit")
script?.executeAndReturnError(nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
NSWorkspace.shared.openApplication(
at: xcodeURL,
configuration: NSWorkspace.OpenConfiguration()
)
}
}
}
}