-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathMessageListView.cs
More file actions
310 lines (244 loc) · 10 KB
/
MessageListView.cs
File metadata and controls
310 lines (244 loc) · 10 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
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StreamChat.Core.Models;
using StreamChat.Core.StatefulModels;
using StreamChat.Libs.Utils;
using StreamChat.SampleProject.Popups;
using StreamChat.SampleProject.Utils;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace StreamChat.SampleProject.Views
{
/// <summary>
/// Channel message list view
/// </summary>
public class MessageListView : BaseView
{
protected override void OnInited()
{
base.OnInited();
State.ActiveChanelChanged += OnActiveChannelChanged;
_scrollRect = GetComponent<ScrollRect>();
}
protected override void OnUpdate()
{
base.OnUpdate();
#if (UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR
HideContextMenuIfTouchedOutside();
#endif
if (_scrollRect.content.rect.height < _scrollRect.viewport.rect.height)
{
// if scroll view doesn't fill whole screen the verticalNormalizedPosition is 1 so it calls for previous messages on empty message list
return;
}
// Check against 1f + threshold because idle ScrollRect after scrolling can have fractional values above 1f
if (_scrollRect.verticalNormalizedPosition >= 1.05f && !IsScrollListRebuilding)
{
TryLoadPreviousMessagesAsync().LogIfFailed();
}
}
protected override void OnDisposing()
{
State.ActiveChanelChanged -= OnActiveChannelChanged;
ClearAll();
base.OnDisposing();
}
private readonly List<MessageView> _messages = new List<MessageView>();
private readonly UnityImageWebLoader _imageLoader = new UnityImageWebLoader();
[SerializeField]
private Transform _messagesContainer;
[SerializeField]
private MessageView _messageViewPrefab;
[SerializeField]
private MessageView _localUserMessageViewPrefab;
private ScrollRect _scrollRect;
private int _scrollListLastUpdateFrame;
private Task _loadPreviousMessagesTask;
private IStreamChannel _activeChannel;
private MessageOptionsPopup _activePopup;
private int _frameShownPopup;
//we wait 2 frames before depending on scroll list position in order for the list to render and update its internal state
private bool IsScrollListRebuilding => _scrollListLastUpdateFrame + 2 > Time.frameCount;
private void OnActiveChannelChanged(IStreamChannel channel)
{
if (_activeChannel != null)
{
_activeChannel.MessageReceived -= OnMessageReceived;
_activeChannel.MessageDeleted -= OnMessageDeleted;
_activeChannel.MessageUpdated -= OnMessageUpdated;
_activeChannel.ReactionAdded -= OnReactionAdded;
_activeChannel.ReactionUpdated -= OnReactionUpdated;
_activeChannel.ReactionRemoved -= OnReactionRemoved;
}
if (channel == null)
{
ClearAll();
return;
}
_activeChannel = channel;
_activeChannel.MessageReceived += OnMessageReceived;
_activeChannel.MessageDeleted += OnMessageDeleted;
_activeChannel.MessageUpdated += OnMessageUpdated;
_activeChannel.ReactionAdded += OnReactionAdded;
_activeChannel.ReactionUpdated += OnReactionUpdated;
_activeChannel.ReactionRemoved += OnReactionRemoved;
RebuildMessages(channel, scrollToBottom: true);
}
private void OnReactionRemoved(IStreamChannel channel, IStreamMessage message, StreamReaction reaction)
=> RebuildMessages(channel, scrollToBottom: false);
private void OnReactionUpdated(IStreamChannel channel, IStreamMessage message, StreamReaction reaction)
=> RebuildMessages(channel, scrollToBottom: false);
private void OnReactionAdded(IStreamChannel channel, IStreamMessage message, StreamReaction reaction)
=> RebuildMessages(channel, scrollToBottom: false);
private void OnMessageUpdated(IStreamChannel channel, IStreamMessage message)
=> RebuildMessages(channel, scrollToBottom: false);
private void OnMessageDeleted(IStreamChannel channel, IStreamMessage message, bool isharddelete)
=> RebuildMessages(channel, scrollToBottom: false);
private void OnMessageReceived(IStreamChannel channel, IStreamMessage message)
=> RebuildMessages(channel, scrollToBottom: true);
private void ClearAll()
{
foreach (var m in _messages)
{
m.PointedDown -= OnMessagePointedDown;
Destroy(m.gameObject);
}
_messages.Clear();
}
private void RebuildMessages(IStreamChannel channel, bool scrollToBottom)
{
ClearAll();
foreach (var message in channel.Messages)
{
var messageView = CreateMessageView(message);
messageView.UpdateData(message, _imageLoader);
_messages.Add(messageView);
if (message == channel.Messages.Last())
{
messageView.TryPlay();
}
}
_scrollListLastUpdateFrame = Time.frameCount;
if (scrollToBottom)
{
StartCoroutine(ScrollToBottomAfterResized());
}
}
private async Task TryLoadPreviousMessagesAsync()
{
if (!_loadPreviousMessagesTask?.IsCompleted ?? false)
{
return;
}
var lastTopMessageId = State.ActiveChannel?.Messages.FirstOrDefault()?.Id;
_loadPreviousMessagesTask = State.LoadPreviousMessagesAsync();
await _loadPreviousMessagesTask;
await Task.Delay(1); //wait 1 frame for the scroll rect render to update
if (lastTopMessageId == null)
{
return;
}
TryScrollToPreviouslyTopMessage(lastTopMessageId);
}
private void TryScrollToPreviouslyTopMessage(string lastTopMessageId)
{
var currentTopMessageId = State.ActiveChannel.Messages.FirstOrDefault()?.Id;
if (currentTopMessageId == lastTopMessageId)
{
return;
}
var lastTopMessage = _messages.FirstOrDefault(_ => _.Message.Id == lastTopMessageId);
if (lastTopMessage == null)
{
return;
}
_scrollRect.content.localPosition =
GetSnapToPositionToBringChildIntoView(_scrollRect, (RectTransform)lastTopMessage.transform);
}
private static Vector2 GetSnapToPositionToBringChildIntoView(ScrollRect instance, RectTransform child)
{
Canvas.ForceUpdateCanvases();
var viewportLocalPosition = instance.viewport.localPosition;
var childLocalPosition = child.localPosition;
var result = new Vector2(
0 - (viewportLocalPosition.x + childLocalPosition.x),
0 - (viewportLocalPosition.y + childLocalPosition.y)
);
return result;
}
//StreamTodo: extract to ViewFactory
private MessageView CreateMessageView(IStreamMessage message)
{
var isLocal = Client.IsLocalUser(message.User);
var prefab = isLocal ? _localUserMessageViewPrefab : _messageViewPrefab;
var view = Instantiate(prefab, _messagesContainer);
view.Init(ViewContext);
view.PointedDown += OnMessagePointedDown;
return view;
}
private IEnumerator ScrollToBottomAfterResized()
{
//wait for renderer to update
yield return new WaitForEndOfFrame();
yield return new WaitForEndOfFrame();
GetComponent<ScrollRect>().verticalNormalizedPosition = 0;
}
private void OnMessagePointedDown(MessageView messageView, PointerEventData pointerEventData)
{
#if UNITY_STANDALONE
if (!InputSystem.GetMouseButton(1))
{
return;
}
#endif
ShowContextMenu(messageView, pointerEventData);
}
private void ShowContextMenu(MessageView parent, PointerEventData pointerEventData)
{
HideContextMenu();
Debug.Log("ShowContextMenu on fame " + Time.frameCount);
var pointerPosition = pointerEventData.position;
_activePopup = Factory.CreateMessageOptionsPopup(parent, State);
var rectTransform = ((RectTransform)_activePopup.transform);
rectTransform.position = pointerPosition + new Vector2(-10, 10);
_frameShownPopup = Time.frameCount;
}
private void HideContextMenu()
{
if (_activePopup != null)
{
Debug.Log("HideContextMenu on fame " + Time.frameCount);
Destroy(_activePopup.gameObject);
_activePopup = null;
}
}
private void HideContextMenuIfTouchedOutside()
{
if (_frameShownPopup == Time.frameCount)
{
return;
}
if (Input.touchCount == 0 || _activePopup == null)
{
return;
}
var anyTouchOnPopup = false;
for (int i = 0; i < Input.touchCount; i++)
{
var touch = Input.GetTouch(i);
if (RectTransformUtility.RectangleContainsScreenPoint(_activePopup.RectTransform,
touch.position))
{
anyTouchOnPopup = true;
}
}
if (!anyTouchOnPopup)
{
HideContextMenu();
}
}
}
}