-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathMessageItemView.swift
More file actions
437 lines (388 loc) Β· 15.1 KB
/
MessageItemView.swift
File metadata and controls
437 lines (388 loc) Β· 15.1 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
//
// Copyright Β© 2026 Stream.io Inc. All rights reserved.
//
import StreamChat
import SwiftUI
/// A view that renders a single message item in the message list, including
/// the avatar, bubble, reactions, thread replies, delivery status, and gesture handling.
public struct MessageItemView<Factory: ViewFactory>: View {
@StateObject var messageViewModel: MessageViewModel
@Environment(\.highlightedMessageId) var highlightedMessageId
@Injected(\.colors) private var colors
@Injected(\.utils) private var utils
@Injected(\.tokens) private var tokens
let factory: Factory
let channel: ChatChannel
let message: ChatMessage
let width: CGFloat?
let fixedContentWidth: CGFloat?
let showsAllInfo: Bool
let shownAsPreview: Bool
let isInThread: Bool
let isLast: Bool
@Binding var scrolledId: String?
@Binding var quotedMessage: ChatMessage?
let onLongPress: (MessageDisplayInfo) -> Void
@State private var frame: CGRect = .zero
@State private var computeFrame = false
/// Creates a new message item view.
/// - Parameters:
/// - factory: The view factory used to create subviews.
/// - channel: The channel the message belongs to.
/// - message: The message to display.
/// - width: The available width for laying out the message content.
/// - showsAllInfo: Whether to show the full message info (avatar, timestamp, delivery status).
/// - shownAsPreview: Whether the message is rendered as a preview (e.g. on the reactions overlay).
/// - isInThread: Whether the message is displayed inside a thread.
/// - isLast: Whether this is the last (topmost) message in the list.
/// - scrolledId: Binding to the currently scrolled-to message ID.
/// - quotedMessage: Binding to the message being quoted via swipe-to-reply.
/// - onLongPress: Called when the user long-presses or double-taps the message bubble.
/// - viewModel: An optional pre-existing view model; one is created automatically when `nil`.
public init(
factory: Factory,
channel: ChatChannel,
message: ChatMessage,
width: CGFloat? = nil,
fixedContentWidth: CGFloat? = nil,
showsAllInfo: Bool,
shownAsPreview: Bool = false,
isInThread: Bool,
isLast: Bool,
scrolledId: Binding<String?>,
quotedMessage: Binding<ChatMessage?>,
onLongPress: @escaping (MessageDisplayInfo) -> Void,
viewModel: MessageViewModel? = nil
) {
self.factory = factory
self.channel = channel
self.message = message
self.width = width
self.fixedContentWidth = fixedContentWidth
self.showsAllInfo = showsAllInfo
self.shownAsPreview = shownAsPreview
self.isInThread = isInThread
self.isLast = isLast
self.onLongPress = onLongPress
_messageViewModel = .init(
wrappedValue: viewModel ?? MessageViewModel(
message: message,
channel: channel,
isInThread: isInThread
)
)
_scrolledId = scrolledId
_quotedMessage = quotedMessage
}
public var body: some View {
HStack(alignment: .bottom) {
if messageViewModel.systemMessageShown {
factory.makeSystemMessageView(options: SystemMessageViewOptions(message: message))
} else {
MessageContainerView(
messageViewModel: messageViewModel,
factory: factory,
channel: channel,
message: message,
contentWidth: contentWidth,
showsAllInfo: showsAllInfo,
shownAsPreview: shownAsPreview,
isLast: isLast,
scrolledId: $scrolledId,
onGesture: { handleGestureForMessage(showsMessageActions: $0) }
)
.background(
GeometryReader { proxy in
Rectangle().fill(Color.clear)
.onChange(of: computeFrame, perform: { _ in
frame = proxy.frame(in: .global)
})
}
)
.contentShape(Rectangle())
.modifier(MessageActionsGestureModifier(
shownAsPreview: shownAsPreview,
isDoubleTapEnabled: messageViewModel.isDoubleTapOverlayEnabled,
onActionsTriggered: { handleGestureForMessage(showsMessageActions: true) }
))
.modifier(SwipeToReplyModifier(
message: message,
channel: channel,
isSwipeToQuoteReplyPossible: !shownAsPreview && messageViewModel.isSwipeToQuoteReplyPossible,
quotedMessage: $quotedMessage
))
}
}
.background(
Group {
if messageViewModel.isHighlighted(messageId: highlightedMessageId) {
Color(colors.backgroundCoreHighlight)
} else if messageViewModel.isPinned && !shownAsPreview {
Color(colors.backgroundCoreHighlight)
}
}
)
.padding(.bottom, messageViewModel.isPinned && !shownAsPreview ? tokens.spacingXs : 0)
.transition(
message.isSentByCurrentUser ?
messageListConfig.messageDisplayOptions.currentUserMessageTransition :
messageListConfig.messageDisplayOptions.otherUserMessageTransition
)
.accessibilityElement(children: .contain)
.accessibilityIdentifier("MessageItemView")
.onChange(of: message) { message in messageViewModel.message = message }
.onChange(of: channel) { channel in messageViewModel.channel = channel }
}
// MARK: - Computed Properties
private var contentWidth: CGFloat {
if let fixedContentWidth {
return fixedContentWidth
}
let minimumWidth: CGFloat = 240
var padding = messageListConfig.messagePaddings.horizontal
if utils.messageListConfig.messageDisplayOptions.showAvatars(for: channel, incoming: !messageViewModel.isRightAligned) {
padding += AvatarSize.medium + tokens.spacingXs
}
let available = (width ?? 0) - spacerWidth - padding
return max(minimumWidth, available)
}
private var spacerWidth: CGFloat {
messageListConfig.messageDisplayOptions.spacerWidth(width ?? 0)
}
private var messageListConfig: MessageListConfig {
utils.messageListConfig
}
// MARK: - Gesture Handling
func handleGestureForMessage(
showsMessageActions: Bool
) {
guard message.isInteractionEnabled else {
return
}
computeFrame.toggle()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
triggerHapticFeedback(style: .medium)
onLongPress(
MessageDisplayInfo(
message: message,
frame: frame,
contentWidth: contentWidth,
isFirst: showsAllInfo,
showsMessageActions: showsMessageActions
)
)
}
}
}
// MARK: - Message Actions Gesture
/// Attaches the double-tap and long-press gestures that open the message actions
/// overlay on a `MessageItemView`.
///
/// When the message is rendered as a preview inside the reactions overlay
/// (`shownAsPreview == true`), both gestures are intentionally skipped. Keeping
/// them would force SwiftUI to wait for double-tap / long-press disambiguation
/// before delivering a single tap to the overlay's dismiss handler, introducing
/// a noticeable delay when the user taps the empty space around the message
/// bubble to dismiss.
struct MessageActionsGestureModifier: ViewModifier {
/// Whether the message is rendered inside the reactions overlay.
/// When `true`, no gestures are attached.
let shownAsPreview: Bool
/// Whether double-tap should trigger the message actions overlay.
let isDoubleTapEnabled: Bool
/// Invoked when either the double-tap or long-press is recognized.
let onActionsTriggered: () -> Void
private let longPressMinimumDuration: Double = 0.3
@ViewBuilder
func body(content: Content) -> some View {
if shownAsPreview {
content
} else {
content
.onTapGesture(count: 2) {
if isDoubleTapEnabled {
onActionsTriggered()
}
}
.highPriorityGesture(
LongPressGesture(minimumDuration: longPressMinimumDuration)
.onEnded { _ in
onActionsTriggered()
}
)
}
}
}
// MARK: - Swipe to Reply
/// Areas that should not trigger swipe-to-reply (e.g. waveform sliders).
struct SwipeToReplyExcludedFrameKey: PreferenceKey {
nonisolated static let defaultValue: [CGRect] = []
static func reduce(value: inout [CGRect], nextValue: () -> [CGRect]) {
value.append(contentsOf: nextValue())
}
}
struct SwipeToReplyModifier: ViewModifier {
let message: ChatMessage
let channel: ChatChannel
let isSwipeToQuoteReplyPossible: Bool
@Binding var quotedMessage: ChatMessage?
@Environment(\.layoutDirection) private var layoutDirection
@Injected(\.images) private var images
@Injected(\.utils) private var utils
@Injected(\.colors) private var colors
@Injected(\.tokens) private var tokens
@State private var offsetX: CGFloat
@State private var swipeExcludedFrames: [CGRect] = []
@GestureState private var offset: CGSize = .zero
private let replyThreshold: CGFloat = 60
init(
message: ChatMessage,
channel: ChatChannel,
isSwipeToQuoteReplyPossible: Bool,
quotedMessage: Binding<ChatMessage?>,
initialOffsetX: CGFloat = 0
) {
self.message = message
self.channel = channel
self.isSwipeToQuoteReplyPossible = isSwipeToQuoteReplyPossible
self._quotedMessage = quotedMessage
self._offsetX = State(initialValue: initialOffsetX)
}
private let feedbackGenerator = UIImpactFeedbackGenerator(style: .medium)
private var isRTL: Bool {
layoutDirection == .rightToLeft
}
func body(content: Content) -> some View {
content
.coordinateSpace(name: "swipeToReply")
.offset(x: min(offsetX, maximumHorizontalSwipeDisplacement))
.gesture(
DragGesture(
minimumDistance: minimumSwipeDistance,
coordinateSpace: .named("swipeToReply")
)
.updating($offset) { (value, gestureState, _) in
guard isSwipeToQuoteReplyPossible else {
return
}
if swipeExcludedFrames.contains(where: { $0.contains(value.startLocation) }) {
return
}
let diff = CGSize(
width: value.location.x - value.startLocation.x,
height: value.location.y - value.startLocation.y
)
if diff == .zero {
gestureState = .zero
} else {
gestureState = value.translation
}
}
)
.onChange(of: offset, perform: { _ in
if !channel.config.quotesEnabled {
return
}
if offset == .zero {
setOffsetX(value: 0)
} else {
dragChanged(to: offset.width)
}
})
.onPreferenceChange(SwipeToReplyExcludedFrameKey.self) { frames in
swipeExcludedFrames = frames
}
.overlay(
offsetX > 20 ? HStack {
Image(systemName: "arrowshape.turn.up.left")
.foregroundColor(colors.buttonSecondaryTextOnAccent.toColor)
.padding(.all, tokens.spacingXs)
.background(colors.buttonSecondaryBackground.toColor)
.clipShape(Circle())
.offset(x: min(offsetX / 2, 50) + (message.isRightAligned ? 30 : 0))
Spacer()
} : nil
)
}
private var maximumHorizontalSwipeDisplacement: CGFloat {
replyThreshold + 30
}
private var minimumSwipeDistance: CGFloat {
utils.messageListConfig.messageDisplayOptions.minimumSwipeGestureDistance
}
private func dragChanged(to value: CGFloat) {
let horizontalTranslation = isRTL ? -value : value
if horizontalTranslation < 0 {
return
}
if horizontalTranslation >= minimumSwipeDistance {
offsetX = horizontalTranslation
} else {
offsetX = 0
}
if offsetX > replyThreshold && quotedMessage != message {
feedbackGenerator.impactOccurred()
withAnimation {
quotedMessage = message
}
}
}
private func setOffsetX(value: CGFloat) {
withAnimation(.interpolatingSpring(stiffness: 170, damping: 20)) {
offsetX = value
}
}
}
// MARK: - Environment
private struct HighlightedMessageIdKey: EnvironmentKey {
static let defaultValue: String? = nil
}
extension EnvironmentValues {
var highlightedMessageId: String? {
get { self[HighlightedMessageIdKey.self] }
set { self[HighlightedMessageIdKey.self] = newValue }
}
}
// MARK: - Supporting Types
struct SendFailureIndicator: View {
@Injected(\.colors) private var colors
@Injected(\.images) private var images
var body: some View {
TopRightView {
Image(uiImage: images.messageListErrorIndicator)
.customizable()
.frame(width: 20, height: 20)
.foregroundColor(Color(colors.badgeBackgroundError))
.padding(2)
.background(Color(colors.badgeBorder))
.clipShape(Circle())
.offset(x: 14, y: 6)
}
.accessibilityElement(children: .contain)
.accessibilityIdentifier("SendFailureIndicator")
}
}
// MARK: - Message Display Info
public final class MessageDisplayInfo: Sendable {
public let message: ChatMessage
public let frame: CGRect
public let contentWidth: CGFloat
public let isFirst: Bool
public let showsMessageActions: Bool
public let keyboardWasShown: Bool
public init(
message: ChatMessage,
frame: CGRect,
contentWidth: CGFloat,
isFirst: Bool,
showsMessageActions: Bool = true,
keyboardWasShown: Bool = false
) {
self.message = message
self.frame = frame
self.contentWidth = contentWidth
self.isFirst = isFirst
self.showsMessageActions = showsMessageActions
self.keyboardWasShown = keyboardWasShown
}
}