forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToast.swift
More file actions
71 lines (59 loc) · 1.84 KB
/
Toast.swift
File metadata and controls
71 lines (59 loc) · 1.84 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
import Foundation
import SwiftUI
import Dependencies
public enum ToastType {
case info
case warning
case error
}
public struct ToastKey: EnvironmentKey {
public static var defaultValue: (String, ToastType) -> Void = { _, _ in }
}
public extension EnvironmentValues {
var toast: (String, ToastType) -> 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, ToastType) -> Void {
get { toastController.toast }
}
}
public class ToastController: ObservableObject {
public struct Message: Identifiable {
public var id: UUID
public var type: ToastType
public var content: Text
public init(id: UUID, type: ToastType, content: Text) {
self.id = id
self.type = type
self.content = content
}
}
@Published public var messages: [Message] = []
public init(messages: [Message]) {
self.messages = messages
}
public func toast(content: String, type: ToastType) {
let id = UUID()
let message = Message(id: id, type: type, content: Text(content))
Task { @MainActor in
withAnimation(.easeInOut(duration: 0.2)) {
messages.append(message)
messages = messages.suffix(3)
}
try await Task.sleep(nanoseconds: 4_000_000_000)
withAnimation(.easeInOut(duration: 0.2)) {
messages.removeAll { $0.id == id }
}
}
}
}