-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathContentView.swift
More file actions
562 lines (511 loc) · 21.3 KB
/
ContentView.swift
File metadata and controls
562 lines (511 loc) · 21.3 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
import Ably
import AblyChat
import SwiftUI
private enum Environment: Equatable {
// Set ``current`` to `.live` if you wish to connect to actual instances of the Chat client in either Prod or Sandbox environments. Setting the mode to `.mock` will use the `MockChatClient`, and therefore simulate all features of the Chat app.
static let current: Self = .mock
case mock
/// - Parameters:
/// - key: Your Ably API key.
/// - clientId: A string that identifies this client.
case live(key: String, clientID: String)
@MainActor
func createChatClient() -> any ChatClientProtocol {
switch self {
case .mock:
return MockChatClient(
clientOptions: ChatClientOptions(),
)
case let .live(key: key, clientID: clientID):
let realtimeOptions = ARTClientOptions()
realtimeOptions.key = key
realtimeOptions.clientId = clientID
let realtime = ARTRealtime(options: realtimeOptions)
return ChatClient(realtime: realtime, clientOptions: .init())
}
}
}
struct ContentView: View {
#if os(macOS)
let screenWidth = NSScreen.main?.frame.width ?? 500
let screenHeight = NSScreen.main?.frame.height ?? 500
#else
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
#endif
// Can be replaced with your own room name
private let roomName = "DemoRoom"
@State private var chatClient = Environment.current.createChatClient()
@State private var currentClientID: String?
@State private var isLoadingHistory = true
@State private var reactions: [Reaction] = []
@State private var newMessage = ""
@State private var typingInfo = ""
@State private var occupancyInfo = "Connections: 0"
@State private var statusInfo = ""
@State private var listItems = [ListItem]()
@State private var editingItemID: String?
enum ListItem: Identifiable {
case message(MessageListItem)
case presence(PresenceListItem)
var id: String {
switch self {
case let .message(item):
item.message.serial
case let .presence(item):
item.presence.member.updatedAt.description
}
}
var message: Message? {
switch self {
case let .message(item):
item.message
case .presence:
nil
}
}
}
func listItemWithMessageSerial(_ serial: String) -> MessageListItem? {
listItems.compactMap { listItem -> MessageListItem? in
if case let .message(messageItem) = listItem, messageItem.message.serial == serial {
return messageItem
}
return nil
}.first
}
private func room() async throws -> any Room {
try await chatClient.rooms.get(named: roomName, options: .init(occupancy: .init(enableEvents: true)))
}
private var sendTitle: String {
if newMessage.isEmpty {
ReactionName.like.emoji
} else if editingItemID != nil {
"Update"
} else {
"Send"
}
}
var body: some View {
ZStack {
VStack {
Text("In \(roomName) as \(currentClientID ?? "<not yet known>")")
.font(.headline)
.padding(5)
HStack {
Text("")
Text(occupancyInfo)
Text(statusInfo)
}
.font(.footnote)
.frame(height: 12)
.padding(.horizontal, 8)
if isLoadingHistory {
VStack(spacing: 16) {
ProgressView()
Text("Loading messages...")
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
// Don't show the scroll view until we've loaded history, since the defaultScrollAnchor doesn't behave well when you insert a load of messages (i.e. it doesn't remain anchored at bottom).
ScrollView {
// The ideal here would be to use LazyVStack, but that seems to not interact very well with the defaultScrollAnchor; sometimes (e.g. presence message display) new content arrives in the scroll view and it doesn't scroll to the bottom.
//
// No doubt there are performance implications of not using LazyVStack, but we can deal with that some other time.
VStack(alignment: .leading, spacing: 8) {
ForEach(listItems, id: \.id) { item in
Group {
switch item {
case let .message(messageItem):
if messageItem.message.action == .messageDelete {
DeletedMessageView(item: messageItem)
} else {
MessageView(
currentClientID: currentClientID,
item: messageItem,
isEditing: Binding(get: {
editingItemID == messageItem.message.serial
}, set: { editing in
editingItemID = editing ? messageItem.message.serial : nil
newMessage = editing ? messageItem.message.text : ""
}),
onDeleteMessage: {
deleteMessage(messageItem.message)
},
onAddReaction: { reaction in
addMessageReaction(reaction, messageSerial: messageItem.message.serial)
},
onDeleteReaction: { reaction in
deleteMessageReaction(reaction, messageSerial: messageItem.message.serial)
},
).id(item.id)
}
case let .presence(item):
PresenceMessageView(item: item)
}
}
.padding(.horizontal, 12)
}
}
}
// Keep the scroll view scrolled to the bottom (unless the user manually scrolls away).
.defaultScrollAnchor(.bottom)
}
#if !os(tvOS)
HStack {
TextField("Type a message...", text: $newMessage)
.onChange(of: newMessage) {
// this ensures that typing events are sent only when the message is actually changed whilst editing
if let index = listItems.firstIndex(where: { $0.id == editingItemID }) {
if case let .message(messageItem) = listItems[index] {
if newMessage != messageItem.message.text {
startTyping()
}
}
} else {
startTyping()
}
}
// Send message when user presses Enter
.onSubmit {
sendButtonAction()
}
.textFieldStyle(.roundedBorder)
Button(action: sendButtonAction) {
#if os(iOS)
Text(sendTitle)
.foregroundColor(.white)
.padding(.vertical, 6)
.padding(.horizontal, 12)
.background(Color.blue)
.cornerRadius(15)
#else
Text(sendTitle)
#endif
}
if editingItemID != nil {
Button("", systemImage: "xmark.circle.fill") {
editingItemID = nil
newMessage = ""
}
.foregroundStyle(.red.opacity(0.8))
.transition(.scale.combined(with: .opacity))
}
}
.animation(.easeInOut, value: editingItemID)
.padding(.horizontal, 12)
#endif
HStack {
Text(typingInfo)
.font(.footnote)
Spacer()
}
.frame(height: 12)
.padding(.horizontal, 14)
.padding(.bottom, 5)
}
ForEach(reactions) { reaction in
Text(reaction.emoji)
.font(.largeTitle)
.position(x: reaction.xPosition, y: reaction.yPosition)
.scaleEffect(reaction.scale)
.opacity(reaction.opacity)
.rotationEffect(.degrees(reaction.rotationAngle))
.onAppear {
withAnimation(.easeOut(duration: reaction.duration)) {
moveReactionUp(reaction: reaction)
}
// Start rotation animation
withAnimation(Animation.linear(duration: reaction.duration).repeatForever(autoreverses: false)) {
startRotation(reaction: reaction)
}
}
}
}
.task {
do {
let room = try await room()
subscribeToConnectionStatus()
subscribeToReactions(room: room)
subscribeToRoomStatus(room: room)
subscribeToTypingEvents(room: room)
subscribeToOccupancy(room: room)
subscribeToPresence(room: room)
subscribeToMessageReactions(room: room)
try await room.attach()
try await showOccupancy(room: room)
try await room.presence.enter(withData: ["status": "📱 Online"])
try await showMessages(room: room)
} catch {
print("Failed to initialize room: \(error)") // TODO: replace with logger (+ message to the user?)
}
}
}
func sendButtonAction() {
if newMessage.isEmpty {
sendRoomReaction(ReactionName.like.emoji)
} else if editingItemID != nil {
Task {
try await sendEditedMessage()
editingItemID = nil
}
} else {
Task {
try await sendMessage()
}
}
}
func showMessages(room: any Room) async throws {
let subscription = room.messages.subscribe { event in
let message = event.message
switch event.type {
case .created:
withAnimation {
listItems.append(
.message(
.init(
message: message,
isSender: message.clientID == currentClientID,
),
),
)
}
case .updated, .deleted:
if let index = listItems.firstIndex(where: { $0.id == message.serial }) {
do {
if let oldMessage = listItems[index].message {
let message = try oldMessage.with(event)
listItems[index] = .message(
.init(
message: message,
isSender: message.clientID == currentClientID,
),
)
}
} catch {
print("Can't update message with newer message: \(error)")
}
}
}
}
let previousMessages = try await subscription.historyBeforeSubscribe(withParams: .init())
defer { isLoadingHistory = false }
// previousMessages are in newest-to-oldest order
for message in previousMessages.items {
switch message.action {
case .messageCreate, .messageUpdate, .messageDelete:
listItems.insert(.message(.init(message: message, isSender: message.clientID == currentClientID)), at: 0)
}
}
}
func subscribeToReactions(room: any Room) {
room.reactions.subscribe { event in
withAnimation {
showReaction(event.reaction.displayedText)
}
}
}
func subscribeToMessageReactions(room: any Room) {
room.messages.reactions.subscribe { summaryEvent in
do {
try withAnimation {
if let reactedMessageItem = listItemWithMessageSerial(summaryEvent.messageSerial) {
if let index = listItems.firstIndex(where: { $0.id == reactedMessageItem.message.serial }) {
listItems[index] = try .message(
.init(
message: reactedMessageItem.message.with(summaryEvent),
isSender: reactedMessageItem.message.clientID == currentClientID,
),
)
}
}
}
} catch {
print("Can't update message with reaction: \(error)")
}
}
}
func subscribeToPresence(room: any Room) {
room.presence.subscribe { event in
withAnimation {
listItems.append(
.presence(
.init(
presence: event,
),
),
)
}
}
}
func subscribeToTypingEvents(room: any Room) {
room.typing.subscribe { typing in
withAnimation {
// Set the typing info to the list of users currently typing
let reset = typing.currentlyTyping.isEmpty || typing.currentlyTyping.count == 1 && typing.change.type == .stopped
typingInfo = reset ? "" : "Typing: \(typing.currentlyTyping.joined(separator: ", "))..."
}
}
}
func showOccupancy(room: any Room) async throws {
let occupancy = try await room.occupancy.get()
occupancyInfo = "Connections: \(occupancy.presenceMembers) (\(occupancy.connections))"
}
func subscribeToOccupancy(room: any Room) {
room.occupancy.subscribe { event in
withAnimation {
occupancyInfo = "Connections: \(event.occupancy.presenceMembers) (\(event.occupancy.connections))"
}
}
}
func subscribeToConnectionStatus() {
chatClient.connection.onStatusChange { [weak chatClient] status in
print("Connection status changed to: `\(status.current)` from `\(status.previous)`")
currentClientID = chatClient?.clientID
}
}
func subscribeToRoomStatus(room: any Room) {
room.onStatusChange { status in
withAnimation {
if status.current == .attaching {
statusInfo = "\(status.current)...".capitalized
} else {
statusInfo = "\(status.current)".capitalized
if status.current == .attached {
after(1) {
withAnimation {
statusInfo = ""
}
}
}
}
}
}
}
func sendMessage() async throws {
guard !newMessage.isEmpty else {
return
}
_ = try await room().messages.send(withParams: .init(text: newMessage))
newMessage = ""
}
func sendEditedMessage() async throws {
guard !newMessage.isEmpty else {
return
}
if let editingMessageItem = listItems.compactMap({ listItem -> MessageListItem? in
if case let .message(message) = listItem, message.message.serial == editingItemID {
return message
}
return nil
}).first {
_ = try await room().messages.update(
withSerial: editingMessageItem.message.serial,
params: .init(
text: newMessage,
metadata: editingMessageItem.message.metadata,
headers: editingMessageItem.message.headers,
),
details: nil,
)
}
newMessage = ""
}
func deleteMessage(_ message: Message) {
Task {
_ = try await room().messages.delete(withSerial: message.serial, details: nil)
}
}
func sendRoomReaction(_ reaction: String) {
Task {
try await room().reactions.send(withParams: .init(name: reaction))
}
}
func addMessageReaction(_ reaction: String, messageSerial: String) {
Task {
try await room().messages.reactions.send(forMessageWithSerial: messageSerial, params: .init(name: reaction, type: .distinct))
}
}
func deleteMessageReaction(_ reaction: String, messageSerial: String) {
Task {
try await room().messages.reactions.delete(fromMessageWithSerial: messageSerial, params: .init(name: reaction, type: .distinct))
}
}
func startTyping() {
Task {
if newMessage.isEmpty {
try await room().typing.stop()
} else {
try await room().typing.keystroke()
}
}
}
}
extension ContentView {
struct Reaction: Identifiable {
let id: UUID
let emoji: String
var xPosition: CGFloat
var yPosition: CGFloat
var scale: CGFloat
var opacity: Double
var rotationAngle: Double // New: stores the current rotation angle
var rotationSpeed: Double // New: stores the random rotation speed
var duration: Double
}
func showReaction(_ emoji: String) {
let screenWidth = screenWidth
let centerX = screenWidth / 2
// Reduce the spread to 1/5th of the screen width
let reducedSpreadRange = screenWidth / 5
// Random x position now has a smaller range, centered around the middle of the screen
let startXPosition = CGFloat.random(in: centerX - reducedSpreadRange ... centerX + reducedSpreadRange)
let randomRotationSpeed = Double.random(in: 30 ... 360) // Random rotation speed
let duration = Double.random(in: 2 ... 4)
let newReaction = Reaction(
id: UUID(),
emoji: emoji,
xPosition: startXPosition,
yPosition: screenHeight - 100,
scale: 1.0,
opacity: 1.0,
rotationAngle: 0, // Initial angle
rotationSpeed: randomRotationSpeed,
duration: duration,
)
reactions.append(newReaction)
// Remove the reaction after the animation completes
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
reactions.removeAll { $0.id == newReaction.id }
}
}
func moveReactionUp(reaction: Reaction) {
if let index = reactions.firstIndex(where: { $0.id == reaction.id }) {
reactions[index].yPosition = 0 // Move it to the top of the screen
reactions[index].scale = 0.5 // Shrink
reactions[index].opacity = 0.5 // Fade out
}
}
func startRotation(reaction: Reaction) {
if let index = reactions.firstIndex(where: { $0.id == reaction.id }) {
reactions[index].rotationAngle += 360 // Continuous rotation over time
}
}
}
#Preview {
ContentView()
}
extension PresenceEventType {
var displayedText: String {
switch self {
case .enter:
"has entered the room"
case .leave:
"has left the room"
case .present:
"has presented at the room"
case .update:
"has updated presence"
}
}
}