@messenger-box/platform-mobile 10.0.3-alpha.36 → 10.0.3-alpha.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/lib/screens/inbox/components/CachedImage/index.js +125 -93
  3. package/lib/screens/inbox/components/CachedImage/index.js.map +1 -1
  4. package/lib/screens/inbox/components/DialogsListItem.js +74 -288
  5. package/lib/screens/inbox/components/DialogsListItem.js.map +1 -1
  6. package/lib/screens/inbox/components/ServiceDialogsListItem.js +184 -415
  7. package/lib/screens/inbox/components/ServiceDialogsListItem.js.map +1 -1
  8. package/lib/screens/inbox/components/SlackMessageContainer/SlackBubble.js +0 -2
  9. package/lib/screens/inbox/components/SlackMessageContainer/SlackBubble.js.map +1 -1
  10. package/lib/screens/inbox/containers/ConversationView.js +621 -951
  11. package/lib/screens/inbox/containers/ConversationView.js.map +1 -1
  12. package/lib/screens/inbox/containers/Dialogs.js +212 -628
  13. package/lib/screens/inbox/containers/Dialogs.js.map +1 -1
  14. package/lib/screens/inbox/containers/ThreadConversationView.js +409 -1364
  15. package/lib/screens/inbox/containers/ThreadConversationView.js.map +1 -1
  16. package/package.json +3 -3
  17. package/src/screens/inbox/components/CachedImage/index.tsx +191 -140
  18. package/src/screens/inbox/components/DialogsListItem.tsx +122 -386
  19. package/src/screens/inbox/components/ServiceDialogsListItem.tsx +69 -377
  20. package/src/screens/inbox/components/SlackMessageContainer/SlackBubble.tsx +2 -4
  21. package/src/screens/inbox/containers/ConversationView.tsx +793 -1064
  22. package/src/screens/inbox/containers/ConversationView.tsx.bk +1467 -0
  23. package/src/screens/inbox/containers/Dialogs.tsx +301 -763
  24. package/src/screens/inbox/containers/ThreadConversationView.tsx +661 -1887
  25. package/lib/screens/inbox/components/workflow/dialogs-list-item-xstate.js +0 -175
  26. package/lib/screens/inbox/components/workflow/dialogs-list-item-xstate.js.map +0 -1
  27. package/lib/screens/inbox/components/workflow/service-dialogs-list-item-xstate.js +0 -191
  28. package/lib/screens/inbox/components/workflow/service-dialogs-list-item-xstate.js.map +0 -1
  29. package/lib/screens/inbox/containers/workflow/conversation-xstate.js +0 -380
  30. package/lib/screens/inbox/containers/workflow/conversation-xstate.js.map +0 -1
  31. package/lib/screens/inbox/containers/workflow/dialogs-xstate.js +0 -211
  32. package/lib/screens/inbox/containers/workflow/dialogs-xstate.js.map +0 -1
  33. package/lib/screens/inbox/containers/workflow/thread-conversation-xstate.js +0 -438
  34. package/lib/screens/inbox/containers/workflow/thread-conversation-xstate.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import React__default,{useState,useRef,useCallback,useEffect,useMemo}from'react';import {Box,Button,ButtonText,HStack,Avatar,AvatarFallbackText,AvatarImage,Text,Image,Spinner}from'@admin-layout/gluestack-ui-mobile';import {Platform,View,TouchableHighlight}from'react-native';import {useNavigation,useIsFocused,useFocusEffect}from'@react-navigation/native';import {navigationRef}from'@common-stack/client-react';import {useSelector}from'react-redux';import {uniqBy,orderBy,startCase}from'lodash-es';import*as ImagePicker from'expo-image-picker';import'base-64';import {MaterialCommunityIcons,Ionicons}from'@expo/vector-icons';import {Send,MessageText,InputToolbar,GiftedChat,Actions as Actions$1}from'react-native-gifted-chat';import {RoomType,PreDefinedRole}from'common';import {useAddDirectChannelMutation,useSendMessagesMutation,useSendExpoNotificationOnPostMutation,useMessagesQuery,OnChatMessageAddedDocument}from'common/graphql';import {useUploadFilesNative}from'@messenger-box/platform-client';import {objectId}from'@messenger-box/core';import {userSelector}from'@adminide-stack/user-auth0-client';import {isToday,isYesterday,format}from'date-fns';import Message from'../components/SlackMessageContainer/SlackMessage.js';import ImageViewerModal from'../components/SlackMessageContainer/ImageViewerModal.js';import CachedImage from'../components/CachedImage/index.js';import {config}from'../config/config.js';import {Actions,BaseState,MainState}from'./workflow/conversation-xstate.js';import colors from'tailwindcss/colors';var __defProp = Object.defineProperty;
1
+ import React__default,{useState,useRef,useMemo,useEffect,useCallback}from'react';import {Box,Button,ButtonText,HStack,Avatar,AvatarFallbackText,AvatarImage,Text,Image,Spinner,Skeleton}from'@admin-layout/gluestack-ui-mobile';import {Platform,View,TouchableHighlight}from'react-native';import {useNavigation,useIsFocused,useFocusEffect}from'@react-navigation/native';import {navigationRef}from'@common-stack/client-react';import {useSelector}from'react-redux';import {uniqBy,orderBy,startCase}from'lodash-es';import*as ImagePicker from'expo-image-picker';import {MaterialCommunityIcons,Ionicons}from'@expo/vector-icons';import {Send,MessageText,InputToolbar,GiftedChat,Actions}from'react-native-gifted-chat';import {RoomType,PreDefinedRole}from'common';import {useAddDirectChannelMutation,useSendMessagesMutation,useSendExpoNotificationOnPostMutation,useMessagesQuery,MessagesDocument,OnChatMessageAddedDocument}from'common/graphql';import {useUploadFilesNative}from'@messenger-box/platform-client';import {objectId}from'@messenger-box/core';import {userSelector}from'@adminide-stack/user-auth0-client';import {isToday,isYesterday,format}from'date-fns';import Message from'../components/SlackMessageContainer/SlackMessage.js';import ImageViewerModal from'../components/SlackMessageContainer/ImageViewerModal.js';import CachedImage from'../components/CachedImage/index.js';import {config}from'../config/config.js';import colors from'tailwindcss/colors';var __defProp = Object.defineProperty;
2
2
  var __defProps = Object.defineProperties;
3
3
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
@@ -46,189 +46,9 @@ const createdAtText = (value) => {
46
46
  return "Yesterday";
47
47
  return format(new Date(value), "MMM dd, yyyy");
48
48
  };
49
- function useSafeMachine(machine) {
50
- const [state, setState] = useState({
51
- context: {
52
- channelId: null,
53
- channelMessages: [],
54
- totalCount: 0,
55
- skip: 0,
56
- loading: false,
57
- loadingOldMessages: false,
58
- error: null,
59
- selectedImage: "",
60
- files: [],
61
- images: [],
62
- messageText: "",
63
- imageLoading: false
64
- },
65
- value: "idle"
66
- });
67
- const send = useCallback((event) => {
68
- try {
69
- console.log("Event received:", event.type);
70
- if (event.type === Actions.INITIAL_CONTEXT) {
71
- setState((prev) => {
72
- var _a;
73
- return __spreadProps(__spreadValues({}, prev), {
74
- context: __spreadProps(__spreadValues({}, prev.context), {
75
- channelId: ((_a = event.data) == null ? void 0 : _a.channelId) || null
76
- }),
77
- value: BaseState.FetchMessages
78
- });
79
- });
80
- } else if (event.type === Actions.SET_CHANNEL_MESSAGES) {
81
- setState((prev) => {
82
- var _a, _b;
83
- return __spreadProps(__spreadValues({}, prev), {
84
- context: __spreadProps(__spreadValues({}, prev.context), {
85
- channelMessages: ((_a = event.data) == null ? void 0 : _a.messages) || [],
86
- totalCount: ((_b = event.data) == null ? void 0 : _b.totalCount) || 0,
87
- loading: false,
88
- loadingOldMessages: false
89
- }),
90
- value: "active"
91
- });
92
- });
93
- } else if (event.type === Actions.CLEAR_MESSAGES) {
94
- setState((prev) => __spreadProps(__spreadValues({}, prev), {
95
- context: __spreadProps(__spreadValues({}, prev.context), {
96
- channelMessages: [],
97
- totalCount: 0
98
- })
99
- }));
100
- } else if (event.type === Actions.SET_MESSAGE_TEXT) {
101
- setState((prev) => {
102
- var _a;
103
- return __spreadProps(__spreadValues({}, prev), {
104
- context: __spreadProps(__spreadValues({}, prev.context), {
105
- messageText: ((_a = event.data) == null ? void 0 : _a.messageText) || ""
106
- })
107
- });
108
- });
109
- } else if (event.type === Actions.FETCH_MORE_MESSAGES) {
110
- setState((prev) => __spreadProps(__spreadValues({}, prev), {
111
- context: __spreadProps(__spreadValues({}, prev.context), {
112
- loadingOldMessages: true
113
- }),
114
- value: MainState.FetchMoreMessages
115
- }));
116
- } else if (event.type === Actions.SET_IMAGE) {
117
- setState((prev) => {
118
- var _a, _b;
119
- return __spreadProps(__spreadValues({}, prev), {
120
- context: __spreadProps(__spreadValues({}, prev.context), {
121
- selectedImage: ((_a = event.data) == null ? void 0 : _a.image) || "",
122
- images: ((_b = event.data) == null ? void 0 : _b.images) || [],
123
- imageLoading: false
124
- })
125
- });
126
- });
127
- } else if (event.type === Actions.CLEAR_IMAGE) {
128
- setState((prev) => __spreadProps(__spreadValues({}, prev), {
129
- context: __spreadProps(__spreadValues({}, prev.context), {
130
- selectedImage: "",
131
- images: []
132
- })
133
- }));
134
- } else if (event.type === Actions.START_LOADING) {
135
- setState((prev) => __spreadProps(__spreadValues({}, prev), {
136
- context: __spreadProps(__spreadValues({}, prev.context), {
137
- loading: true
138
- })
139
- }));
140
- } else if (event.type === Actions.STOP_LOADING) {
141
- setState((prev) => __spreadProps(__spreadValues({}, prev), {
142
- context: __spreadProps(__spreadValues({}, prev.context), {
143
- loading: false
144
- })
145
- }));
146
- } else if (event.type === Actions.SEND_MESSAGE) {
147
- setState((prev) => __spreadProps(__spreadValues({}, prev), {
148
- context: __spreadProps(__spreadValues({}, prev.context), {
149
- loading: true
150
- }),
151
- value: MainState.SendMessage
152
- }));
153
- } else if (event.type === Actions.SEND_MESSAGE_WITH_FILE) {
154
- setState((prev) => __spreadProps(__spreadValues({}, prev), {
155
- context: __spreadProps(__spreadValues({}, prev.context), {
156
- loading: true
157
- }),
158
- value: MainState.SendMessageWithFile
159
- }));
160
- } else if (event.type === Actions.CREATE_DIRECT_CHANNEL) {
161
- setState((prev) => __spreadProps(__spreadValues({}, prev), {
162
- context: __spreadProps(__spreadValues({}, prev.context), {
163
- loading: true
164
- }),
165
- value: MainState.CreateDirectChannel
166
- }));
167
- } else if (event.type === "SEND_MESSAGE_SUCCESS" || event.type === "SEND_MESSAGE_WITH_FILE_SUCCESS") {
168
- setState((prev) => __spreadProps(__spreadValues({}, prev), {
169
- context: __spreadProps(__spreadValues({}, prev.context), {
170
- loading: false,
171
- messageText: "",
172
- images: [],
173
- selectedImage: ""
174
- }),
175
- value: "active"
176
- }));
177
- } else if (event.type === "CREATE_DIRECT_CHANNEL_SUCCESS") {
178
- setState((prev) => {
179
- var _a;
180
- return __spreadProps(__spreadValues({}, prev), {
181
- context: __spreadProps(__spreadValues({}, prev.context), {
182
- loading: false,
183
- channelId: ((_a = event.data) == null ? void 0 : _a.channelId) || prev.context.channelId,
184
- messageText: ""
185
- }),
186
- value: BaseState.FetchMessages
187
- });
188
- });
189
- } else if (event.type === "FETCH_MORE_MESSAGES_SUCCESS") {
190
- setState((prev) => {
191
- var _a;
192
- const newMessages = ((_a = event.data) == null ? void 0 : _a.messages) || [];
193
- return __spreadProps(__spreadValues({}, prev), {
194
- context: __spreadProps(__spreadValues({}, prev.context), {
195
- loadingOldMessages: false,
196
- channelMessages: uniqBy([...prev.context.channelMessages, ...newMessages], ({
197
- id
198
- }) => id)
199
- }),
200
- value: "active"
201
- });
202
- });
203
- } else if (event.type === "ERROR") {
204
- setState((prev) => {
205
- var _a;
206
- return __spreadProps(__spreadValues({}, prev), {
207
- context: __spreadProps(__spreadValues({}, prev.context), {
208
- loading: false,
209
- loadingOldMessages: false,
210
- error: ((_a = event.data) == null ? void 0 : _a.message) || "Unknown error"
211
- }),
212
- value: "error"
213
- });
214
- });
215
- }
216
- } catch (error) {
217
- console.error("Error in send function:", error);
218
- }
219
- }, []);
220
- const stateWithMatches = useMemo(() => {
221
- return __spreadProps(__spreadValues({}, state), {
222
- matches: (checkState) => {
223
- return state.value === checkState;
224
- }
225
- });
226
- }, [state]);
227
- return [stateWithMatches, send];
228
- }
229
49
  const ConversationViewComponent = (_a) => {
230
50
  var _b = _a, {
231
- channelId: ChannelId,
51
+ channelId: initialChannelId,
232
52
  role,
233
53
  isShowThreadMessage
234
54
  } = _b, rest = __objRest(_b, [
@@ -236,114 +56,23 @@ const ConversationViewComponent = (_a) => {
236
56
  "role",
237
57
  "isShowThreadMessage"
238
58
  ]);
239
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
240
- const [channelToTop, setChannelToTop] = useState(0);
241
- const isMountedRef = useRef(true);
242
- const [state, send] = useSafeMachine();
243
- useCallback(() => {
244
- try {
245
- return (state == null ? void 0 : state.context) || {};
246
- } catch (error) {
247
- console.error("Error accessing state.context:", error);
248
- return {};
249
- }
250
- }, [state]);
251
- const safeContextProperty = useCallback((property, defaultValue = null) => {
252
- var _a3, _b3;
253
- try {
254
- return (_b3 = (_a3 = state == null ? void 0 : state.context) == null ? void 0 : _a3[property]) != null ? _b3 : defaultValue;
255
- } catch (error) {
256
- console.error(`Error accessing state.context.${property}:`, error);
257
- return defaultValue;
258
- }
259
- }, [state]);
260
- useCallback((stateValue) => {
261
- var _a3;
262
- try {
263
- return ((_a3 = state == null ? void 0 : state.matches) == null ? void 0 : _a3.call(state, stateValue)) || false;
264
- } catch (error) {
265
- console.error(`Error calling state.matches with ${stateValue}:`, error);
266
- return false;
267
- }
268
- }, [state]);
269
- const safeSend = useCallback((event) => {
270
- var _a3;
271
- try {
272
- console.log("\u{1F6E0}\uFE0F Safe send event:", event.type);
273
- send(event);
274
- if (event.type === Actions.SET_CHANNEL_MESSAGES) {
275
- setTimeout(() => {
276
- var _a4, _b3;
277
- if (state.context.channelMessages.length === 0 && ((_b3 = (_a4 = event.data) == null ? void 0 : _a4.messages) == null ? void 0 : _b3.length) > 0) {
278
- console.warn("\u{1F6E0}\uFE0F SET_CHANNEL_MESSAGES did not update state - messages still empty");
279
- }
280
- }, 100);
281
- }
282
- } catch (error) {
283
- console.error("\u{1F6E0}\uFE0F Error in safeSend:", error, "Event type:", event.type);
284
- if (event.type === Actions.SET_CHANNEL_MESSAGES && ((_a3 = event.data) == null ? void 0 : _a3.messages)) {
285
- console.log("\u{1F6E0}\uFE0F Attempting fallback for SET_CHANNEL_MESSAGES");
286
- try {
287
- send({
288
- type: "DIRECT_STATE_UPDATE",
289
- data: event.data
290
- });
291
- } catch (fallbackError) {
292
- console.error("\u{1F6E0}\uFE0F Even fallback failed:", fallbackError);
293
- }
294
- }
295
- }
296
- }, [send, state.context.channelMessages.length]);
297
- useEffect(() => {
298
- if (ChannelId) {
299
- console.log("Setting initial channel ID on mount:", ChannelId);
300
- try {
301
- send({
302
- type: Actions.INITIAL_CONTEXT,
303
- data: {
304
- channelId: ChannelId
305
- }
306
- });
307
- } catch (error) {
308
- console.error("Error sending initial context:", error);
309
- }
310
- }
311
- }, []);
312
- const stateRef = useRef(state);
313
- useEffect(() => {
314
- stateRef.current = state;
315
- }, [state]);
316
- const safeGetContext = useCallback(() => {
317
- if (stateRef.current && stateRef.current.context) {
318
- return stateRef.current.context;
319
- }
320
- return {
321
- channelId: null,
322
- channelMessages: [],
323
- totalCount: 0,
324
- skip: 0,
325
- loading: false,
326
- loadingOldMessages: false,
327
- error: null,
328
- selectedImage: "",
329
- files: [],
330
- images: [],
331
- messageText: "",
332
- imageLoading: false
333
- };
334
- }, []);
335
- useEffect(() => {
336
- return () => {
337
- isMountedRef.current = false;
338
- };
339
- }, []);
340
- const auth = useSelector(userSelector);
341
- const currentRoute = navigationRef.isReady() ? (_a2 = navigationRef) == null ? void 0 : _a2.getCurrentRoute() : null;
342
- const navigation = useNavigation();
343
- const [selectedImage, setImage] = useState("");
59
+ var _a2, _b2, _c, _d;
60
+ const [channelId, setChannelId] = useState(initialChannelId || null);
61
+ const [messageText, setMessageText] = useState("");
62
+ const [skip, setSkip] = useState(0);
63
+ const [loading, setLoading] = useState(false);
64
+ const [loadingOldMessages, setLoadingOldMessages] = useState(false);
65
+ const [error, setError] = useState(null);
66
+ const [selectedImage, setSelectedImage] = useState("");
67
+ const [images, setImages] = useState([]);
344
68
  const [isShowImageViewer, setImageViewer] = useState(false);
345
69
  const [imageObject, setImageObject] = useState({});
346
70
  const messageRootListRef = useRef(null);
71
+ const isMounted = useRef(true);
72
+ const fetchOldDebounceRef = useRef(false);
73
+ const auth = useSelector(userSelector);
74
+ const currentRoute = navigationRef.isReady() ? (_a2 = navigationRef) == null ? void 0 : _a2.getCurrentRoute() : null;
75
+ const navigation = useNavigation();
347
76
  const isFocused = useIsFocused();
348
77
  const [addDirectChannel] = useAddDirectChannelMutation();
349
78
  const {
@@ -359,105 +88,65 @@ const ConversationViewComponent = (_a) => {
359
88
  subscribeToMore
360
89
  } = useMessagesQuery({
361
90
  variables: {
362
- channelId: (_b2 = state.context.channelId) == null ? void 0 : _b2.toString(),
91
+ channelId: channelId == null ? void 0 : channelId.toString(),
363
92
  parentId: null,
364
93
  limit: MESSAGES_PER_PAGE,
365
- skip: state.context.skip
94
+ skip
366
95
  },
367
- skip: !state.context.channelId,
96
+ skip: !channelId,
368
97
  fetchPolicy: "cache-and-network",
369
98
  nextFetchPolicy: "cache-first",
370
99
  refetchWritePolicy: "merge",
371
- onCompleted: (queryData) => {
372
- var _a3;
373
- console.log("MESSAGE QUERY COMPLETED:", queryData);
374
- if ((_a3 = queryData == null ? void 0 : queryData.messages) == null ? void 0 : _a3.data) {
375
- console.log("Raw message data from query:", JSON.stringify(queryData.messages.data).substring(0, 100) + "...");
376
- console.log("Message count from query:", queryData.messages.data.length);
377
- console.log("Total count from query:", queryData.messages.totalCount);
378
- if (queryData.messages.data.length > 0) {
379
- console.log("\u{1F504} IMMEDIATE STATE UPDATE with messages:", queryData.messages.data.length);
380
- safeSend({
381
- type: Actions.SET_CHANNEL_MESSAGES,
382
- data: {
383
- messages: queryData.messages.data,
384
- totalCount: queryData.messages.totalCount
385
- }
386
- });
387
- }
388
- }
389
- },
390
- onError: (error) => {
391
- console.error("MESSAGE QUERY ERROR:", error);
392
- safeSend({
393
- type: "ERROR",
394
- data: {
395
- message: String(error)
396
- }
397
- });
100
+ notifyOnNetworkStatusChange: true,
101
+ onError: (error2) => {
102
+ setError(String(error2));
398
103
  }
399
104
  });
400
- const fetchMessagesDirectly = useCallback(async () => {
105
+ const channelMessages = useMemo(() => {
401
106
  var _a3;
402
- const channelId = safeGetContext().channelId;
403
- if (!channelId) {
404
- console.warn("Cannot fetch messages: No channel ID");
405
- return;
107
+ return ((_a3 = data == null ? void 0 : data.messages) == null ? void 0 : _a3.data) || [];
108
+ }, [(_b2 = data == null ? void 0 : data.messages) == null ? void 0 : _b2.data]);
109
+ const totalCount = useMemo(() => {
110
+ var _a3;
111
+ return ((_a3 = data == null ? void 0 : data.messages) == null ? void 0 : _a3.totalCount) || 0;
112
+ }, [(_c = data == null ? void 0 : data.messages) == null ? void 0 : _c.totalCount]);
113
+ useEffect(() => {
114
+ return () => {
115
+ isMounted.current = false;
116
+ };
117
+ }, []);
118
+ useEffect(() => {
119
+ var _a3;
120
+ const currentChannelId = initialChannelId || ((_a3 = currentRoute == null ? void 0 : currentRoute.params) == null ? void 0 : _a3.channelId);
121
+ if (currentChannelId) {
122
+ setChannelId(currentChannelId);
406
123
  }
407
- try {
408
- console.log("\u{1F4AB} FETCHING messages for channel:", channelId);
409
- send({
410
- type: Actions.START_LOADING
411
- });
412
- const response = await refetch({
413
- channelId: channelId.toString(),
414
- parentId: null,
415
- limit: MESSAGES_PER_PAGE,
416
- skip: 0
417
- });
418
- if ((_a3 = response == null ? void 0 : response.data) == null ? void 0 : _a3.messages) {
419
- const {
420
- data: messages,
421
- totalCount
422
- } = response.data.messages;
423
- if (messages && messages.length > 0) {
424
- safeSend({
425
- type: Actions.SET_CHANNEL_MESSAGES,
426
- data: {
427
- messages,
428
- totalCount
429
- }
430
- });
431
- } else {
432
- console.warn("No messages found for channel", channelId);
433
- send({
434
- type: Actions.STOP_LOADING
435
- });
436
- }
437
- } else {
438
- console.warn("Query returned no messages data");
439
- send({
440
- type: Actions.STOP_LOADING
441
- });
442
- }
443
- } catch (error) {
444
- console.error("ERROR fetching messages:", error);
445
- send({
446
- type: Actions.STOP_LOADING
447
- });
124
+ }, [initialChannelId, currentRoute]);
125
+ useFocusEffect(React__default.useCallback(() => {
126
+ if (channelId) {
127
+ refetch();
448
128
  }
449
- }, [safeGetContext, refetch, safeSend]);
129
+ return () => {
130
+ };
131
+ }, [channelId, isFocused, refetch]));
132
+ useEffect(() => {
133
+ if (selectedImage) {
134
+ setLoading(false);
135
+ }
136
+ }, [selectedImage]);
450
137
  const fetchMoreMessagesImpl = useCallback(async () => {
451
- var _a3, _b3, _c2;
138
+ var _a3, _b3;
452
139
  try {
140
+ setLoadingOldMessages(true);
453
141
  const response = await fetchMoreMessages({
454
142
  variables: {
455
- channelId: (_a3 = state.context.channelId) == null ? void 0 : _a3.toString(),
143
+ channelId: channelId == null ? void 0 : channelId.toString(),
456
144
  parentId: null,
457
- skip: state.context.channelMessages.length
145
+ skip: channelMessages.length
458
146
  }
459
147
  });
460
- if (!((_c2 = (_b3 = response == null ? void 0 : response.data) == null ? void 0 : _b3.messages) == null ? void 0 : _c2.data)) {
148
+ setLoadingOldMessages(false);
149
+ if (!((_b3 = (_a3 = response == null ? void 0 : response.data) == null ? void 0 : _a3.messages) == null ? void 0 : _b3.data)) {
461
150
  return {
462
151
  error: "No messages returned"
463
152
  };
@@ -465,19 +154,23 @@ const ConversationViewComponent = (_a) => {
465
154
  return {
466
155
  messages: response.data.messages.data
467
156
  };
468
- } catch (error) {
157
+ } catch (error2) {
158
+ setLoadingOldMessages(false);
159
+ setError(String(error2));
469
160
  return {
470
- error: String(error)
161
+ error: String(error2)
471
162
  };
472
163
  }
473
- }, [state.context.channelId, state.context.channelMessages.length, fetchMoreMessages]);
164
+ }, [channelId, channelMessages.length, fetchMoreMessages]);
474
165
  const sendMessageImpl = useCallback(async () => {
475
166
  var _a3;
476
167
  try {
168
+ const currentMessageText = messageText;
169
+ setMessageText("");
477
170
  const notificationData = {
478
171
  url: config.INBOX_MESSEGE_PATH,
479
172
  params: {
480
- channelId: state.context.channelId,
173
+ channelId,
481
174
  hideTabBar: true
482
175
  },
483
176
  screen: "DialogMessages",
@@ -485,29 +178,111 @@ const ConversationViewComponent = (_a) => {
485
178
  sound: Platform.OS === "android" ? void 0 : "default"
486
179
  }
487
180
  };
181
+ const messageId = objectId();
182
+ const optimisticMessage = {
183
+ __typename: "Post",
184
+ id: messageId,
185
+ message: currentMessageText,
186
+ createdAt: new Date().toISOString(),
187
+ updatedAt: new Date().toISOString(),
188
+ author: {
189
+ __typename: "UserAccount",
190
+ id: auth == null ? void 0 : auth.id,
191
+ picture: (auth == null ? void 0 : auth.picture) || "",
192
+ givenName: (auth == null ? void 0 : auth.givenName) || "",
193
+ familyName: (auth == null ? void 0 : auth.familyName) || "",
194
+ email: (auth == null ? void 0 : auth.email) || "",
195
+ username: (auth == null ? void 0 : auth.username) || "",
196
+ alias: [],
197
+ tokens: []
198
+ },
199
+ isDelivered: true,
200
+ isRead: false,
201
+ type: "TEXT",
202
+ parentId: null,
203
+ fromServer: false,
204
+ channel: {
205
+ __typename: "Channel",
206
+ id: channelId
207
+ },
208
+ propsConfiguration: {
209
+ __typename: "MachineConfiguration",
210
+ resource: ""
211
+ },
212
+ props: {},
213
+ files: {
214
+ __typename: "FilesInfo",
215
+ data: [],
216
+ totalCount: 0
217
+ },
218
+ replies: {
219
+ __typename: "Messages",
220
+ data: [],
221
+ totalCount: 0
222
+ }
223
+ };
488
224
  const response = await sendMsg({
489
225
  variables: {
490
- channelId: state.context.channelId,
491
- content: state.context.messageText,
226
+ channelId,
227
+ content: currentMessageText,
492
228
  notificationParams: notificationData
229
+ },
230
+ optimisticResponse: {
231
+ __typename: "Mutation",
232
+ sendMessage: optimisticMessage
233
+ },
234
+ update: (cache, {
235
+ data: data2
236
+ }) => {
237
+ if (data2 == null ? void 0 : data2.sendMessage) {
238
+ try {
239
+ const existingData = cache.readQuery({
240
+ query: MessagesDocument,
241
+ variables: {
242
+ channelId: channelId == null ? void 0 : channelId.toString(),
243
+ parentId: null,
244
+ limit: MESSAGES_PER_PAGE,
245
+ skip: 0
246
+ }
247
+ });
248
+ if (!existingData)
249
+ return;
250
+ cache.writeQuery({
251
+ query: MessagesDocument,
252
+ variables: {
253
+ channelId: channelId == null ? void 0 : channelId.toString(),
254
+ parentId: null,
255
+ limit: MESSAGES_PER_PAGE,
256
+ skip: 0
257
+ },
258
+ data: {
259
+ messages: __spreadProps(__spreadValues({}, existingData.messages), {
260
+ data: [data2.sendMessage, ...existingData.messages.data],
261
+ totalCount: (existingData.messages.totalCount || 0) + 1
262
+ })
263
+ }
264
+ });
265
+ } catch (error2) {
266
+ console.error("Error updating cache:", error2);
267
+ }
268
+ }
493
269
  }
494
270
  });
495
271
  return {
496
272
  message: (_a3 = response.data) == null ? void 0 : _a3.sendMessage
497
273
  };
498
- } catch (error) {
274
+ } catch (error2) {
275
+ setLoading(false);
276
+ setError(String(error2));
499
277
  return {
500
- error: String(error)
278
+ error: String(error2)
501
279
  };
502
280
  }
503
- }, [state.context.channelId, state.context.messageText, sendMsg]);
281
+ }, [channelId, messageText, sendMsg, auth]);
504
282
  const onSelectImages = async () => {
505
- var _a3, _b3, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2;
506
- safeSend({
507
- type: Actions.START_LOADING
508
- });
283
+ var _a3;
284
+ setLoading(true);
509
285
  try {
510
- console.log("Starting image picker...");
511
286
  let imageSource = await ImagePicker.launchImageLibraryAsync({
512
287
  mediaTypes: ImagePicker.MediaTypeOptions.Images,
513
288
  allowsEditing: true,
@@ -517,19 +292,9 @@ const ConversationViewComponent = (_a) => {
517
292
  exif: false
518
293
  });
519
294
  if (!(imageSource == null ? void 0 : imageSource.canceled)) {
520
- console.log("Image selected. Asset details:", JSON.stringify({
521
- uri: ((_c2 = (_b3 = (_a3 = imageSource == null ? void 0 : imageSource.assets) == null ? void 0 : _a3[0]) == null ? void 0 : _b3.uri) == null ? void 0 : _c2.substring(0, 30)) + "...",
522
- width: (_e2 = (_d2 = imageSource == null ? void 0 : imageSource.assets) == null ? void 0 : _d2[0]) == null ? void 0 : _e2.width,
523
- height: (_g2 = (_f2 = imageSource == null ? void 0 : imageSource.assets) == null ? void 0 : _f2[0]) == null ? void 0 : _g2.height,
524
- hasBase64: !!((_i2 = (_h2 = imageSource == null ? void 0 : imageSource.assets) == null ? void 0 : _h2[0]) == null ? void 0 : _i2.base64),
525
- hasUri: !!((_k2 = (_j2 = imageSource == null ? void 0 : imageSource.assets) == null ? void 0 : _j2[0]) == null ? void 0 : _k2.uri)
526
- }));
527
- const selectedAsset = (_l2 = imageSource == null ? void 0 : imageSource.assets) == null ? void 0 : _l2[0];
295
+ const selectedAsset = (_a3 = imageSource == null ? void 0 : imageSource.assets) == null ? void 0 : _a3[0];
528
296
  if (!selectedAsset) {
529
- console.error("No asset found in selected image");
530
- safeSend({
531
- type: Actions.STOP_LOADING
532
- });
297
+ setLoading(false);
533
298
  return;
534
299
  }
535
300
  const base64Data = selectedAsset.base64;
@@ -539,43 +304,26 @@ const ConversationViewComponent = (_a) => {
539
304
  fileName: selectedAsset.fileName || `image_${Date.now()}.jpg`,
540
305
  mimeType: "image/jpeg"
541
306
  });
542
- console.log("Prepared image asset for upload:", {
543
- hasUrl: !!asset.url,
544
- hasFileName: !!asset.fileName,
545
- hasMimeType: !!asset.mimeType,
546
- previewAvailable: !!previewImage
547
- });
548
- safeSend({
549
- type: Actions.SET_IMAGE,
550
- data: {
551
- image: previewImage,
552
- images: [asset]
553
- }
554
- });
555
- console.log("Image state updated successfully");
307
+ setSelectedImage(previewImage);
308
+ setImages([asset]);
556
309
  } else {
557
- console.log("Image selection cancelled");
558
- safeSend({
559
- type: Actions.STOP_LOADING
560
- });
310
+ setLoading(false);
561
311
  }
562
- } catch (error) {
563
- console.error("Error selecting image:", error);
564
- safeSend({
565
- type: Actions.STOP_LOADING
566
- });
312
+ } catch (error2) {
313
+ setLoading(false);
567
314
  }
568
315
  };
316
+ const [uploadingMessageId, setUploadingMessageId] = useState(null);
569
317
  const sendMessageWithFileImpl = useCallback(async () => {
570
- var _a3, _b3, _c2, _d2, _e2, _f2;
318
+ var _a3, _b3, _c2, _d2, _e, _f;
571
319
  try {
572
- console.log("Executing sendMessageWithFileImpl");
320
+ setLoading(true);
573
321
  const postId = objectId();
574
- console.log("Generated postId for file upload:", postId);
322
+ setUploadingMessageId(postId);
575
323
  const notificationData = {
576
324
  url: config.INBOX_MESSEGE_PATH,
577
325
  params: {
578
- channelId: state.context.channelId,
326
+ channelId,
579
327
  hideTabBar: true
580
328
  },
581
329
  screen: "DialogMessages",
@@ -583,31 +331,77 @@ const ConversationViewComponent = (_a) => {
583
331
  sound: Platform.OS === "android" ? void 0 : "default"
584
332
  }
585
333
  };
586
- if (!state.context.images || state.context.images.length === 0) {
587
- console.error("No images found in state");
334
+ if (!images || images.length === 0) {
335
+ setLoading(false);
336
+ setUploadingMessageId(null);
588
337
  return {
589
338
  error: "No images available to upload"
590
339
  };
591
340
  }
592
- const imagesToUpload = state.context.images.map((img) => {
341
+ const imagesToUpload = images.map((img) => {
593
342
  return __spreadProps(__spreadValues({}, img), {
594
343
  uri: img.uri || img.url,
595
344
  type: "image/jpeg",
596
345
  name: img.fileName || `image_${Date.now()}.jpg`
597
346
  });
598
347
  });
599
- console.log("Formatted images for upload:", imagesToUpload.map((img) => {
600
- var _a4;
601
- return {
602
- hasUri: !!img.uri,
603
- hasUrl: !!img.url,
604
- hasName: !!img.name,
605
- hasType: !!img.type,
606
- hasFileName: !!img.fileName,
607
- uri: ((_a4 = img.uri) == null ? void 0 : _a4.substring(0, 30)) + "..."
608
- };
609
- }));
610
- console.log("Starting file upload...");
348
+ const currentMessageText = messageText;
349
+ setMessageText("");
350
+ const fileId = objectId();
351
+ const optimisticMessage = {
352
+ __typename: "Post",
353
+ id: postId,
354
+ message: currentMessageText || " ",
355
+ createdAt: new Date().toISOString(),
356
+ updatedAt: new Date().toISOString(),
357
+ author: {
358
+ __typename: "UserAccount",
359
+ id: auth == null ? void 0 : auth.id,
360
+ picture: (auth == null ? void 0 : auth.picture) || "",
361
+ givenName: (auth == null ? void 0 : auth.givenName) || "",
362
+ familyName: (auth == null ? void 0 : auth.familyName) || "",
363
+ email: (auth == null ? void 0 : auth.email) || "",
364
+ username: (auth == null ? void 0 : auth.username) || "",
365
+ alias: [],
366
+ tokens: []
367
+ },
368
+ isDelivered: true,
369
+ isRead: false,
370
+ type: "TEXT",
371
+ parentId: null,
372
+ fromServer: false,
373
+ channel: {
374
+ __typename: "Channel",
375
+ id: channelId
376
+ },
377
+ propsConfiguration: {
378
+ __typename: "MachineConfiguration",
379
+ resource: ""
380
+ },
381
+ props: {},
382
+ files: {
383
+ __typename: "FilesInfo",
384
+ data: [{
385
+ __typename: "FileInfo",
386
+ id: fileId,
387
+ url: selectedImage,
388
+ name: ((_a3 = imagesToUpload[0]) == null ? void 0 : _a3.name) || "image.jpg",
389
+ extension: "jpg",
390
+ mimeType: "image/jpeg",
391
+ height: ((_b3 = imagesToUpload[0]) == null ? void 0 : _b3.height) || 0,
392
+ width: ((_c2 = imagesToUpload[0]) == null ? void 0 : _c2.width) || 0,
393
+ size: ((_d2 = imagesToUpload[0]) == null ? void 0 : _d2.fileSize) || 0,
394
+ refType: "Post",
395
+ ref: postId
396
+ }],
397
+ totalCount: 1
398
+ },
399
+ replies: {
400
+ __typename: "Messages",
401
+ data: [],
402
+ totalCount: 0
403
+ }
404
+ };
611
405
  const uploadResponse = await startUpload({
612
406
  file: imagesToUpload,
613
407
  saveUploadedFile: {
@@ -621,85 +415,144 @@ const ConversationViewComponent = (_a) => {
621
415
  }
622
416
  }
623
417
  });
624
- console.log("Upload response received:", (uploadResponse == null ? void 0 : uploadResponse.data) ? "Has data" : "No data", "Error:", (uploadResponse == null ? void 0 : uploadResponse.error) ? uploadResponse.error : "None");
625
418
  if (uploadResponse == null ? void 0 : uploadResponse.error) {
626
- console.error("Upload error:", uploadResponse.error);
419
+ setLoading(false);
420
+ setUploadingMessageId(null);
627
421
  return {
628
422
  error: String(uploadResponse.error)
629
423
  };
630
424
  }
631
425
  const uploadedFiles = uploadResponse.data;
632
- console.log("Uploaded files:", uploadedFiles ? JSON.stringify(uploadedFiles.map((f) => {
633
- var _a4;
634
- return {
635
- id: f.id,
636
- url: ((_a4 = f.url) == null ? void 0 : _a4.substring(0, 30)) + "..."
637
- };
638
- })) : "null");
639
- const files = (_a3 = uploadedFiles == null ? void 0 : uploadedFiles.map((f) => f.id)) != null ? _a3 : null;
640
- console.log("Files uploaded successfully. File IDs:", files);
641
- console.log("Sending message with files:", {
642
- postId,
643
- channelId: state.context.channelId,
644
- content: state.context.messageText || " ",
645
- hasFiles: !!files,
646
- fileCount: (files == null ? void 0 : files.length) || 0
426
+ const files = (_e = uploadedFiles == null ? void 0 : uploadedFiles.map((f) => f.id)) != null ? _e : null;
427
+ const realMessage = __spreadProps(__spreadValues({}, optimisticMessage), {
428
+ files: {
429
+ __typename: "FilesInfo",
430
+ data: uploadedFiles.map((file) => ({
431
+ __typename: "FileInfo",
432
+ id: file.id,
433
+ url: file.url,
434
+ name: file.name,
435
+ extension: file.extension,
436
+ mimeType: file.mimeType,
437
+ height: file.height,
438
+ width: file.width,
439
+ size: file.size,
440
+ refType: file.refType,
441
+ ref: postId
442
+ })),
443
+ totalCount: uploadedFiles.length
444
+ }
647
445
  });
648
446
  const response = await sendMsg({
649
447
  variables: {
650
448
  postId,
651
- channelId: state.context.channelId,
652
- content: state.context.messageText || " ",
449
+ channelId,
450
+ content: currentMessageText || " ",
653
451
  files,
654
452
  notificationParams: notificationData
453
+ },
454
+ optimisticResponse: {
455
+ __typename: "Mutation",
456
+ sendMessage: realMessage
457
+ },
458
+ update: (cache, {
459
+ data: data2
460
+ }) => {
461
+ if (data2 == null ? void 0 : data2.sendMessage) {
462
+ try {
463
+ const existingData = cache.readQuery({
464
+ query: MessagesDocument,
465
+ variables: {
466
+ channelId: channelId == null ? void 0 : channelId.toString(),
467
+ parentId: null,
468
+ limit: MESSAGES_PER_PAGE,
469
+ skip: 0
470
+ }
471
+ });
472
+ if (!existingData)
473
+ return;
474
+ const messageWithFiles = __spreadProps(__spreadValues({}, data2.sendMessage), {
475
+ files: data2.sendMessage.files || {
476
+ __typename: "FilesInfo",
477
+ data: uploadedFiles.map((file) => ({
478
+ __typename: "FileInfo",
479
+ id: file.id,
480
+ url: file.url,
481
+ name: file.name,
482
+ extension: file.extension,
483
+ mimeType: file.mimeType,
484
+ height: file.height,
485
+ width: file.width,
486
+ size: file.size,
487
+ refType: file.refType,
488
+ ref: postId
489
+ })),
490
+ totalCount: uploadedFiles.length
491
+ }
492
+ });
493
+ cache.writeQuery({
494
+ query: MessagesDocument,
495
+ variables: {
496
+ channelId: channelId == null ? void 0 : channelId.toString(),
497
+ parentId: null,
498
+ limit: MESSAGES_PER_PAGE,
499
+ skip: 0
500
+ },
501
+ data: {
502
+ messages: __spreadProps(__spreadValues({}, existingData.messages), {
503
+ data: [messageWithFiles, ...existingData.messages.data],
504
+ totalCount: (existingData.messages.totalCount || 0) + 1
505
+ })
506
+ }
507
+ });
508
+ setSelectedImage("");
509
+ setImages([]);
510
+ } catch (error2) {
511
+ console.error("Error updating cache:", error2);
512
+ }
513
+ }
655
514
  }
656
515
  });
657
- if ((_b3 = response == null ? void 0 : response.data) == null ? void 0 : _b3.sendMessage) {
658
- console.log("Message with file sent successfully:", response.data.sendMessage.id);
659
- if ((_c2 = response.data.sendMessage.files) == null ? void 0 : _c2.data) {
660
- console.log("\u{1F4F7} Message response file data:", JSON.stringify({
661
- fileCount: response.data.sendMessage.files.data.length,
662
- fileUrl: ((_e2 = (_d2 = response.data.sendMessage.files.data[0]) == null ? void 0 : _d2.url) == null ? void 0 : _e2.substring(0, 30)) + "..."
663
- }));
664
- }
665
- setTimeout(() => {
666
- safeSend({
667
- type: Actions.CLEAR_IMAGE
668
- });
669
- }, 100);
670
- } else {
671
- console.error("Failed to send message with file:", response == null ? void 0 : response.errors);
672
- }
516
+ setLoading(false);
517
+ setUploadingMessageId(null);
673
518
  return {
674
- message: (_f2 = response.data) == null ? void 0 : _f2.sendMessage
519
+ message: (_f = response.data) == null ? void 0 : _f.sendMessage
675
520
  };
676
- } catch (error) {
677
- console.error("Error in sendMessageWithFileImpl:", error);
521
+ } catch (error2) {
522
+ setLoading(false);
523
+ setUploadingMessageId(null);
524
+ setError(String(error2));
678
525
  return {
679
- error: String(error)
526
+ error: String(error2)
680
527
  };
681
528
  }
682
- }, [state.context.channelId, state.context.messageText, state.context.images, startUpload, sendMsg, safeSend]);
529
+ }, [channelId, messageText, images, selectedImage, startUpload, sendMsg, auth]);
683
530
  const createDirectChannelImpl = useCallback(async () => {
684
- var _a3, _b3, _c2, _d2, _e2, _f2, _g2, _h2;
531
+ var _a3, _b3, _c2, _d2, _e, _f, _g, _h;
685
532
  try {
533
+ setLoading(true);
686
534
  if (!(rest == null ? void 0 : rest.isCreateNewChannel) || ((_a3 = rest == null ? void 0 : rest.newChannelData) == null ? void 0 : _a3.type) !== ((_b3 = RoomType) == null ? void 0 : _b3.Direct) || !((_d2 = (_c2 = rest == null ? void 0 : rest.newChannelData) == null ? void 0 : _c2.userIds) == null ? void 0 : _d2.length)) {
535
+ setLoading(false);
687
536
  return {
688
537
  error: "Invalid channel data"
689
538
  };
690
539
  }
540
+ const currentMessageText = messageText;
541
+ setMessageText("");
691
542
  const response = await addDirectChannel({
692
543
  variables: {
693
- receiver: [...(_f2 = (_e2 = rest == null ? void 0 : rest.newChannelData) == null ? void 0 : _e2.userIds) != null ? _f2 : []],
544
+ receiver: [...(_f = (_e = rest == null ? void 0 : rest.newChannelData) == null ? void 0 : _e.userIds) != null ? _f : []],
694
545
  displayName: "DIRECT CHANNEL"
695
546
  }
696
547
  });
697
- if (!((_h2 = (_g2 = response == null ? void 0 : response.data) == null ? void 0 : _g2.createDirectChannel) == null ? void 0 : _h2.id)) {
548
+ if (!((_h = (_g = response == null ? void 0 : response.data) == null ? void 0 : _g.createDirectChannel) == null ? void 0 : _h.id)) {
549
+ setLoading(false);
698
550
  return {
699
551
  error: "Failed to create channel"
700
552
  };
701
553
  }
702
554
  const newChannelId = response.data.createDirectChannel.id;
555
+ setChannelId(newChannelId);
703
556
  const notificationData = {
704
557
  url: config.INBOX_MESSEGE_PATH,
705
558
  params: {
@@ -711,132 +564,110 @@ const ConversationViewComponent = (_a) => {
711
564
  sound: Platform.OS === "android" ? void 0 : "default"
712
565
  }
713
566
  };
567
+ const messageId = objectId();
568
+ const optimisticMessage = {
569
+ __typename: "Post",
570
+ id: messageId,
571
+ message: currentMessageText,
572
+ createdAt: new Date().toISOString(),
573
+ updatedAt: new Date().toISOString(),
574
+ author: {
575
+ __typename: "UserAccount",
576
+ id: auth == null ? void 0 : auth.id,
577
+ picture: (auth == null ? void 0 : auth.picture) || "",
578
+ givenName: (auth == null ? void 0 : auth.givenName) || "",
579
+ familyName: (auth == null ? void 0 : auth.familyName) || "",
580
+ email: (auth == null ? void 0 : auth.email) || "",
581
+ username: (auth == null ? void 0 : auth.username) || "",
582
+ alias: [],
583
+ tokens: []
584
+ },
585
+ isDelivered: true,
586
+ isRead: false,
587
+ type: "TEXT",
588
+ parentId: null,
589
+ fromServer: false,
590
+ channel: {
591
+ __typename: "Channel",
592
+ id: newChannelId
593
+ },
594
+ propsConfiguration: {
595
+ __typename: "MachineConfiguration",
596
+ resource: ""
597
+ },
598
+ props: {},
599
+ files: {
600
+ __typename: "FilesInfo",
601
+ data: [],
602
+ totalCount: 0
603
+ },
604
+ replies: {
605
+ __typename: "Messages",
606
+ data: [],
607
+ totalCount: 0
608
+ }
609
+ };
714
610
  await sendMsg({
715
611
  variables: {
716
612
  channelId: newChannelId,
717
- content: state.context.messageText,
613
+ content: currentMessageText,
718
614
  notificationParams: notificationData
615
+ },
616
+ optimisticResponse: {
617
+ __typename: "Mutation",
618
+ sendMessage: optimisticMessage
619
+ },
620
+ update: (cache, {
621
+ data: data2
622
+ }) => {
623
+ if (data2 == null ? void 0 : data2.sendMessage) {
624
+ try {
625
+ cache.writeQuery({
626
+ query: MessagesDocument,
627
+ variables: {
628
+ channelId: newChannelId,
629
+ parentId: null,
630
+ limit: MESSAGES_PER_PAGE,
631
+ skip: 0
632
+ },
633
+ data: {
634
+ messages: {
635
+ __typename: "Messages",
636
+ messagesRefId: newChannelId,
637
+ data: [data2.sendMessage],
638
+ totalCount: 1
639
+ }
640
+ }
641
+ });
642
+ } catch (error2) {
643
+ console.error("Error updating cache:", error2);
644
+ }
645
+ }
719
646
  }
720
647
  });
648
+ setLoading(false);
721
649
  return {
722
650
  channelId: newChannelId
723
651
  };
724
- } catch (error) {
652
+ } catch (error2) {
653
+ setLoading(false);
654
+ setError(String(error2));
725
655
  return {
726
- error: String(error)
656
+ error: String(error2)
727
657
  };
728
658
  }
729
- }, [rest, state.context.messageText, addDirectChannel, sendMsg]);
730
- useEffect(() => {
731
- }, [state.value, sendMsg, refetch, fetchMoreMessages, addDirectChannel, startUpload, rest, state.context]);
732
- React__default.useEffect(() => {
733
- return () => {
734
- send({
735
- type: Actions.CLEAR_MESSAGES
736
- });
737
- };
738
- }, []);
739
- useFocusEffect(React__default.useCallback(() => {
740
- if (state.context.channelId) {
741
- send({
742
- type: Actions.INITIAL_CONTEXT,
743
- data: {
744
- channelId: state.context.channelId
745
- }
746
- });
747
- }
748
- return () => {
749
- send({
750
- type: Actions.CLEAR_MESSAGES
751
- });
752
- };
753
- }, [state.context.channelId, isFocused]));
754
- React__default.useEffect(() => {
755
- var _a3;
756
- const currentChannelId = ChannelId || ((_a3 = currentRoute == null ? void 0 : currentRoute.params) == null ? void 0 : _a3.channelId);
757
- if (currentChannelId) {
758
- console.log("Setting initial channel ID:", currentChannelId);
759
- send({
760
- type: Actions.INITIAL_CONTEXT,
761
- data: {
762
- channelId: currentChannelId
763
- }
764
- });
765
- }
766
- }, [ChannelId, currentRoute]);
767
- React__default.useEffect(() => {
768
- if (state.context.selectedImage) {
769
- send({
770
- type: Actions.STOP_LOADING
771
- });
772
- }
773
- }, [state.context.selectedImage]);
774
- useEffect(() => {
775
- var _a3, _b3, _c2, _d2;
776
- if ((_a3 = data == null ? void 0 : data.messages) == null ? void 0 : _a3.data) {
777
- console.log("\u{1F4E9} QUERY DATA CHANGED - Messages received:", data.messages.data.length);
778
- const {
779
- data: messages,
780
- totalCount: messageTotalCount
781
- } = data.messages;
782
- if (messages && messages.length > 0) {
783
- console.log("\u{1F4E9} QUERY DATA - Setting channel messages, count:", messages.length);
784
- setTimeout(() => {
785
- safeSend({
786
- type: Actions.SET_CHANNEL_MESSAGES,
787
- data: {
788
- messages: uniqBy([...messages, ...state.context.channelMessages], ({
789
- id
790
- }) => id),
791
- totalCount: messageTotalCount
792
- }
793
- });
794
- setTimeout(() => {
795
- var _a4;
796
- const currentMessagesCount = ((_a4 = state.context.channelMessages) == null ? void 0 : _a4.length) || 0;
797
- console.log("\u{1F4E9} STATE UPDATE VERIFICATION - Current message count:", currentMessagesCount);
798
- if (currentMessagesCount === 0) {
799
- console.warn("\u26A0\uFE0F STATE NOT UPDATED after message data received - triggering fallback");
800
- safeSend({
801
- type: Actions.SET_CHANNEL_MESSAGES,
802
- data: {
803
- messages,
804
- totalCount: messageTotalCount
805
- }
806
- });
807
- }
808
- }, 500);
809
- }, 0);
810
- if (messages[0]) {
811
- const sample = messages[0];
812
- console.log("\u{1F4E9} SAMPLE MESSAGE:", JSON.stringify({
813
- id: sample.id,
814
- message: sample.message,
815
- author: {
816
- id: (_b3 = sample.author) == null ? void 0 : _b3.id,
817
- name: `${(_c2 = sample.author) == null ? void 0 : _c2.givenName} ${(_d2 = sample.author) == null ? void 0 : _d2.familyName}`
818
- },
819
- createdAt: sample.createdAt
820
- }));
821
- }
822
- }
823
- }
824
- }, [data, safeSend]);
659
+ }, [rest, messageText, addDirectChannel, sendMsg, auth]);
825
660
  const onFetchOld = useCallback(() => {
826
- var _a3, _b3, _c2, _d2;
827
661
  if (fetchOldDebounceRef.current)
828
662
  return;
829
- if (((_a3 = state == null ? void 0 : state.context) == null ? void 0 : _a3.totalCount) > ((_c2 = (_b3 = state == null ? void 0 : state.context) == null ? void 0 : _b3.channelMessages) == null ? void 0 : _c2.length) && !((_d2 = state == null ? void 0 : state.context) == null ? void 0 : _d2.loadingOldMessages)) {
663
+ if (totalCount > channelMessages.length && !loadingOldMessages) {
830
664
  fetchOldDebounceRef.current = true;
831
- send({
832
- type: Actions.FETCH_MORE_MESSAGES
833
- });
665
+ fetchMoreMessagesImpl();
834
666
  setTimeout(() => {
835
667
  fetchOldDebounceRef.current = false;
836
668
  }, 1e3);
837
669
  }
838
- }, [(_c = state == null ? void 0 : state.context) == null ? void 0 : _c.totalCount, (_d = state == null ? void 0 : state.context) == null ? void 0 : _d.channelMessages, (_e = state == null ? void 0 : state.context) == null ? void 0 : _e.loadingOldMessages]);
839
- const fetchOldDebounceRef = useRef(false);
670
+ }, [totalCount, channelMessages.length, loadingOldMessages, fetchMoreMessagesImpl]);
840
671
  const isCloseToTop = ({
841
672
  layoutMeasurement,
842
673
  contentOffset,
@@ -845,124 +676,27 @@ const ConversationViewComponent = (_a) => {
845
676
  const paddingToTop = 60;
846
677
  return contentSize.height - layoutMeasurement.height - paddingToTop <= contentOffset.y;
847
678
  };
848
- const renderSend = useCallback((props) => {
849
- var _a3, _b3, _c2;
850
- const hasContent = !!props.text || ((_b3 = (_a3 = state == null ? void 0 : state.context) == null ? void 0 : _a3.images) == null ? void 0 : _b3.length) > 0;
851
- const canSend = (((_c2 = state == null ? void 0 : state.context) == null ? void 0 : _c2.channelId) || (rest == null ? void 0 : rest.isCreateNewChannel)) && hasContent;
852
- return /* @__PURE__ */ React__default.createElement(Send, __spreadProps(__spreadValues({}, props), { disabled: !canSend, containerStyle: {
853
- justifyContent: "center",
854
- alignItems: "center",
855
- height: 40,
856
- width: 44,
857
- marginRight: 4,
858
- marginBottom: 0,
859
- marginLeft: 4
860
- } }), /* @__PURE__ */ React__default.createElement(View, { style: {
861
- padding: 4
862
- } }, /* @__PURE__ */ React__default.createElement(MaterialCommunityIcons, { name: "send-circle", size: 32, color: canSend ? colors.blue[500] : colors.gray[400] })));
863
- }, [(_f = state == null ? void 0 : state.context) == null ? void 0 : _f.channelId, (_g = state == null ? void 0 : state.context) == null ? void 0 : _g.images, rest == null ? void 0 : rest.isCreateNewChannel]);
864
- const handleSend = useCallback(async (messages) => {
865
- var _a3, _b3, _c2, _d2;
866
- const messageText = messages && messages.length > 0 ? ((_a3 = messages[0]) == null ? void 0 : _a3.text) || " " : " ";
867
- console.log("Sending message:", messageText);
868
- console.log("Images:", (_b3 = state.context.images) == null ? void 0 : _b3.length);
869
- if (!state.context.channelId && !(rest == null ? void 0 : rest.isCreateNewChannel)) {
870
- console.log("Cannot send - no channel");
871
- return;
872
- }
873
- const hasText = !!messageText && messageText !== " ";
874
- const hasImages = state.context.images && state.context.images.length > 0;
875
- if (!hasText && !hasImages) {
876
- console.log("Nothing to send - no text or images");
877
- return;
878
- }
879
- safeSend({
880
- type: Actions.SET_MESSAGE_TEXT,
881
- data: {
882
- messageText
883
- }
884
- });
885
- if ((rest == null ? void 0 : rest.isCreateNewChannel) && !state.context.channelId) {
886
- if (((_c2 = rest == null ? void 0 : rest.newChannelData) == null ? void 0 : _c2.type) === ((_d2 = RoomType) == null ? void 0 : _d2.Direct)) {
887
- safeSend({
888
- type: Actions.CREATE_DIRECT_CHANNEL
889
- });
890
- }
891
- return;
892
- }
893
- if (hasImages) {
894
- console.log("Sending message with file");
895
- safeSend({
896
- type: Actions.SEND_MESSAGE_WITH_FILE
897
- });
898
- } else {
899
- console.log("Sending text-only message");
900
- safeSend({
901
- type: Actions.SEND_MESSAGE
902
- });
903
- }
904
- }, [state.context.channelId, state.context.images, rest == null ? void 0 : rest.isCreateNewChannel, (_h = rest == null ? void 0 : rest.newChannelData) == null ? void 0 : _h.type, safeSend]);
905
- const fetchMessagesWithFallback = useCallback(async () => {
906
- var _a3, _b3, _c2;
907
- if (!state.context.channelId)
908
- return;
909
- try {
910
- console.log("\u{1F504} DIRECT FETCH: Using direct approach for channel:", state.context.channelId);
911
- const response = await refetch({
912
- channelId: (_a3 = state.context.channelId) == null ? void 0 : _a3.toString(),
913
- parentId: null,
914
- limit: MESSAGES_PER_PAGE,
915
- skip: 0
916
- });
917
- if ((_c2 = (_b3 = response == null ? void 0 : response.data) == null ? void 0 : _b3.messages) == null ? void 0 : _c2.data) {
918
- const messages = response.data.messages.data;
919
- console.log("\u2705 DIRECT FETCH: Got messages:", messages.length);
920
- send({
921
- type: Actions.SET_CHANNEL_MESSAGES,
922
- data: {
923
- messages,
924
- totalCount: response.data.messages.totalCount
925
- }
926
- });
927
- }
928
- } catch (error) {
929
- console.error("\u274C DIRECT FETCH ERROR:", error);
930
- }
931
- }, [state.context.channelId, refetch]);
932
- useEffect(() => {
933
- let timeoutId;
934
- if (state.context.channelId && state.context.channelMessages.length === 0) {
935
- timeoutId = setTimeout(() => {
936
- console.log("\u26A0\uFE0F ACTIVATING FALLBACK - XState not updating after timeout");
937
- fetchMessagesWithFallback();
938
- }, 3e3);
939
- }
940
- return () => {
941
- if (timeoutId)
942
- clearTimeout(timeoutId);
943
- };
944
- }, [state.context.channelId, state.context.channelMessages, fetchMessagesWithFallback]);
945
679
  const messageList = useMemo(() => {
946
- var _a3;
947
- console.log("\u{1F504} CALCULATING MESSAGE LIST - Optimized version");
948
- if (!((_a3 = state == null ? void 0 : state.context) == null ? void 0 : _a3.channelMessages) || state.context.channelMessages.length === 0) {
949
- console.log("No messages to process");
680
+ if (!channelMessages || channelMessages.length === 0) {
950
681
  return [];
951
682
  }
952
- const filteredMessages = uniqBy(state.context.channelMessages, ({
683
+ const filteredMessages = uniqBy(channelMessages, ({
953
684
  id
954
685
  }) => id);
955
686
  if (filteredMessages.length === 0) {
956
687
  return [];
957
688
  }
958
689
  return orderBy(filteredMessages, ["createdAt"], ["desc"]).map((msg) => {
959
- var _a4, _b3, _c2, _d2, _e2, _f2;
690
+ var _a3, _b3, _c2, _d2, _e;
960
691
  const date = new Date(msg.createdAt);
961
692
  let imageUrl = null;
962
- if (((_a4 = msg.files) == null ? void 0 : _a4.data) && msg.files.data.length > 0) {
963
- const fileData = msg.files.data[0];
964
- if (fileData && fileData.url) {
965
- imageUrl = fileData.url;
693
+ if (msg.files && typeof msg.files === "object") {
694
+ const filesData = msg.files.data || (Array.isArray(msg.files) ? msg.files : null);
695
+ if (filesData && filesData.length > 0) {
696
+ const fileData = filesData[0];
697
+ if (fileData && typeof fileData === "object" && fileData.url) {
698
+ imageUrl = fileData.url;
699
+ }
966
700
  }
967
701
  }
968
702
  return {
@@ -970,42 +704,81 @@ const ConversationViewComponent = (_a) => {
970
704
  text: msg.message,
971
705
  createdAt: date,
972
706
  user: {
973
- _id: ((_b3 = msg.author) == null ? void 0 : _b3.id) || "",
974
- name: `${((_c2 = msg.author) == null ? void 0 : _c2.givenName) || ""} ${((_d2 = msg.author) == null ? void 0 : _d2.familyName) || ""}`,
975
- avatar: ((_e2 = msg.author) == null ? void 0 : _e2.picture) || ""
707
+ _id: ((_a3 = msg.author) == null ? void 0 : _a3.id) || "",
708
+ name: `${((_b3 = msg.author) == null ? void 0 : _b3.givenName) || ""} ${((_c2 = msg.author) == null ? void 0 : _c2.familyName) || ""}`,
709
+ avatar: ((_d2 = msg.author) == null ? void 0 : _d2.picture) || ""
976
710
  },
977
711
  image: imageUrl,
978
712
  sent: msg == null ? void 0 : msg.isDelivered,
979
713
  received: msg == null ? void 0 : msg.isRead,
980
714
  type: msg == null ? void 0 : msg.type,
981
715
  propsConfiguration: msg == null ? void 0 : msg.propsConfiguration,
982
- replies: (_f2 = msg == null ? void 0 : msg.replies) != null ? _f2 : [],
716
+ replies: (_e = msg == null ? void 0 : msg.replies) != null ? _e : [],
983
717
  isShowThreadMessage
984
718
  };
985
719
  });
986
- }, [(_i = state == null ? void 0 : state.context) == null ? void 0 : _i.channelMessages, isShowThreadMessage]);
720
+ }, [channelMessages, isShowThreadMessage]);
721
+ const renderSend = useCallback((props) => {
722
+ const hasContent = !!props.text || (images == null ? void 0 : images.length) > 0;
723
+ const canSend = (channelId || (rest == null ? void 0 : rest.isCreateNewChannel)) && hasContent;
724
+ return /* @__PURE__ */ React__default.createElement(Send, __spreadProps(__spreadValues({}, props), { disabled: !canSend, containerStyle: {
725
+ justifyContent: "center",
726
+ alignItems: "center",
727
+ height: 40,
728
+ width: 44,
729
+ marginRight: 4,
730
+ marginBottom: 0,
731
+ marginLeft: 4
732
+ } }), /* @__PURE__ */ React__default.createElement(View, { style: {
733
+ padding: 4
734
+ } }, /* @__PURE__ */ React__default.createElement(MaterialCommunityIcons, { name: "send-circle", size: 32, color: canSend ? colors.blue[500] : colors.gray[400] })));
735
+ }, [channelId, images, rest == null ? void 0 : rest.isCreateNewChannel]);
736
+ const handleSend = useCallback(async (messages) => {
737
+ var _a3, _b3, _c2;
738
+ const newMessageText = messages && messages.length > 0 ? ((_a3 = messages[0]) == null ? void 0 : _a3.text) || " " : " ";
739
+ if (!channelId && !(rest == null ? void 0 : rest.isCreateNewChannel)) {
740
+ return;
741
+ }
742
+ const hasText = !!newMessageText && newMessageText !== " ";
743
+ const hasImages = images && images.length > 0;
744
+ if (!hasText && !hasImages) {
745
+ return;
746
+ }
747
+ setMessageText(newMessageText);
748
+ if ((rest == null ? void 0 : rest.isCreateNewChannel) && !channelId) {
749
+ if (((_b3 = rest == null ? void 0 : rest.newChannelData) == null ? void 0 : _b3.type) === ((_c2 = RoomType) == null ? void 0 : _c2.Direct)) {
750
+ createDirectChannelImpl();
751
+ }
752
+ return;
753
+ }
754
+ if (hasImages) {
755
+ sendMessageWithFileImpl();
756
+ } else {
757
+ sendMessageImpl();
758
+ }
759
+ }, [channelId, images, rest == null ? void 0 : rest.isCreateNewChannel, (_d = rest == null ? void 0 : rest.newChannelData) == null ? void 0 : _d.type, createDirectChannelImpl, sendMessageWithFileImpl, sendMessageImpl]);
987
760
  const renderMessageText = useCallback((props) => {
988
- var _a3, _b3, _c2, _d2, _e2, _f2, _g2, _h2, _i2, _j2, _k2, _l2, _m2, _n2, _o2, _p2, _q2, _r2, _s2, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U;
761
+ var _a3, _b3, _c2, _d2, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U;
989
762
  const {
990
763
  currentMessage
991
764
  } = props;
992
765
  const lastReply = ((_b3 = (_a3 = currentMessage == null ? void 0 : currentMessage.replies) == null ? void 0 : _a3.data) == null ? void 0 : _b3.length) > 0 ? (_d2 = (_c2 = currentMessage == null ? void 0 : currentMessage.replies) == null ? void 0 : _c2.data) == null ? void 0 : _d2[0] : null;
993
766
  if (currentMessage.type === "ALERT") {
994
- const attachment = (_f2 = (_e2 = currentMessage == null ? void 0 : currentMessage.propsConfiguration) == null ? void 0 : _e2.contents) == null ? void 0 : _f2.attachment;
767
+ const attachment = (_f = (_e = currentMessage == null ? void 0 : currentMessage.propsConfiguration) == null ? void 0 : _e.contents) == null ? void 0 : _f.attachment;
995
768
  let action = "";
996
769
  let actionId = "";
997
770
  let params = {};
998
- if ((_g2 = attachment == null ? void 0 : attachment.callToAction) == null ? void 0 : _g2.extraParams) {
999
- const extraParams = (_h2 = attachment == null ? void 0 : attachment.callToAction) == null ? void 0 : _h2.extraParams;
1000
- const route = (_i2 = extraParams == null ? void 0 : extraParams.route) != null ? _i2 : null;
771
+ if ((_g = attachment == null ? void 0 : attachment.callToAction) == null ? void 0 : _g.extraParams) {
772
+ const extraParams = (_h = attachment == null ? void 0 : attachment.callToAction) == null ? void 0 : _h.extraParams;
773
+ const route = (_i = extraParams == null ? void 0 : extraParams.route) != null ? _i : null;
1001
774
  let path = null;
1002
775
  let param = null;
1003
776
  if (role && role == PreDefinedRole.Guest) {
1004
- path = ((_j2 = route == null ? void 0 : route.guest) == null ? void 0 : _j2.name) ? (_l2 = (_k2 = route == null ? void 0 : route.guest) == null ? void 0 : _k2.name) != null ? _l2 : null : null;
1005
- param = ((_m2 = route == null ? void 0 : route.guest) == null ? void 0 : _m2.params) ? (_o2 = (_n2 = route == null ? void 0 : route.guest) == null ? void 0 : _n2.params) != null ? _o2 : null : null;
777
+ path = ((_j = route == null ? void 0 : route.guest) == null ? void 0 : _j.name) ? (_l = (_k = route == null ? void 0 : route.guest) == null ? void 0 : _k.name) != null ? _l : null : null;
778
+ param = ((_m = route == null ? void 0 : route.guest) == null ? void 0 : _m.params) ? (_o = (_n = route == null ? void 0 : route.guest) == null ? void 0 : _n.params) != null ? _o : null : null;
1006
779
  } else if (role && role == PreDefinedRole.Owner) {
1007
- path = ((_p2 = route == null ? void 0 : route.host) == null ? void 0 : _p2.name) ? (_r2 = (_q2 = route == null ? void 0 : route.host) == null ? void 0 : _q2.name) != null ? _r2 : null : null;
1008
- param = ((_s2 = route == null ? void 0 : route.host) == null ? void 0 : _s2.params) ? (_u = (_t = route == null ? void 0 : route.host) == null ? void 0 : _t.params) != null ? _u : null : null;
780
+ path = ((_p = route == null ? void 0 : route.host) == null ? void 0 : _p.name) ? (_r = (_q = route == null ? void 0 : route.host) == null ? void 0 : _q.name) != null ? _r : null : null;
781
+ param = ((_s = route == null ? void 0 : route.host) == null ? void 0 : _s.params) ? (_u = (_t = route == null ? void 0 : route.host) == null ? void 0 : _t.params) != null ? _u : null : null;
1009
782
  } else {
1010
783
  path = ((_v = route == null ? void 0 : route.host) == null ? void 0 : _v.name) ? (_x = (_w = route == null ? void 0 : route.host) == null ? void 0 : _w.name) != null ? _x : null : null;
1011
784
  param = ((_y = route == null ? void 0 : route.host) == null ? void 0 : _y.params) ? (_A = (_z = route == null ? void 0 : route.host) == null ? void 0 : _z.params) != null ? _A : null : null;
@@ -1028,10 +801,9 @@ const ConversationViewComponent = (_a) => {
1028
801
  } }))) : /* @__PURE__ */ React__default.createElement(TouchableHighlight, { underlayColor: "#c0c0c0", style: {
1029
802
  width: "100%"
1030
803
  }, onPress: () => {
1031
- var _a4;
1032
804
  if (currentMessage == null ? void 0 : currentMessage.isShowThreadMessage)
1033
805
  navigation.navigate(config.THREAD_MESSEGE_PATH, {
1034
- channelId: (_a4 = state == null ? void 0 : state.context) == null ? void 0 : _a4.channelId,
806
+ channelId,
1035
807
  title: "Message",
1036
808
  postParentId: currentMessage == null ? void 0 : currentMessage._id,
1037
809
  isPostParentIdThread: true
@@ -1061,10 +833,9 @@ const ConversationViewComponent = (_a) => {
1061
833
  return /* @__PURE__ */ React__default.createElement(TouchableHighlight, { underlayColor: "#c0c0c0", style: {
1062
834
  width: "100%"
1063
835
  }, onPress: () => {
1064
- var _a4;
1065
836
  if (currentMessage == null ? void 0 : currentMessage.isShowThreadMessage)
1066
837
  navigation.navigate(config.THREAD_MESSEGE_PATH, {
1067
- channelId: (_a4 = state == null ? void 0 : state.context) == null ? void 0 : _a4.channelId,
838
+ channelId,
1068
839
  title: "Message",
1069
840
  postParentId: currentMessage == null ? void 0 : currentMessage._id,
1070
841
  isPostParentIdThread: true
@@ -1091,10 +862,10 @@ const ConversationViewComponent = (_a) => {
1091
862
  fontSize: 12
1092
863
  }, className: "font-bold color-gray-500" }, lastReply ? createdAtText(lastReply == null ? void 0 : lastReply.createdAt) : ""))));
1093
864
  }
1094
- }, [navigation, (_j = state == null ? void 0 : state.context) == null ? void 0 : _j.channelId, role]);
865
+ }, [navigation, channelId, role]);
1095
866
  const renderActions = (props) => {
1096
867
  return /* @__PURE__ */ React__default.createElement(
1097
- Actions$1,
868
+ Actions,
1098
869
  __spreadProps(__spreadValues({}, props), {
1099
870
  options: {
1100
871
  ["Choose from Library"]: onSelectImages,
@@ -1118,68 +889,93 @@ const ConversationViewComponent = (_a) => {
1118
889
  })
1119
890
  );
1120
891
  };
1121
- const renderAccessory = useCallback((props) => {
1122
- var _a3, _b3;
1123
- const selectedImage2 = safeContextProperty("selectedImage", "");
1124
- if (!selectedImage2) {
892
+ const renderAccessory = useCallback(() => {
893
+ var _a3;
894
+ if (!selectedImage) {
1125
895
  return null;
1126
896
  }
1127
897
  return /* @__PURE__ */ React__default.createElement(View, { style: {
1128
- height: 50,
1129
- padding: 3,
898
+ height: 70,
1130
899
  backgroundColor: "white",
1131
900
  borderTopWidth: 1,
1132
901
  borderTopColor: "#e0e0e0",
1133
902
  flexDirection: "row",
1134
903
  alignItems: "center",
1135
904
  margin: 0,
1136
- paddingBottom: 0,
1137
- paddingTop: 5,
905
+ padding: 0,
906
+ paddingVertical: 0,
1138
907
  position: "absolute",
1139
- bottom: 0,
908
+ bottom: Platform.OS === "ios" ? 105 : 95,
1140
909
  left: 0,
1141
910
  right: 0,
1142
- zIndex: 999
1143
- } }, /* @__PURE__ */ React__default.createElement(View, { style: {
1144
- flex: 1,
1145
- flexDirection: "row",
1146
- alignItems: "center",
1147
- paddingHorizontal: 15
1148
- } }, /* @__PURE__ */ React__default.createElement(Image, { key: (_a3 = state == null ? void 0 : state.context) == null ? void 0 : _a3.selectedImage, alt: "selected image", source: {
1149
- uri: (_b3 = state == null ? void 0 : state.context) == null ? void 0 : _b3.selectedImage
1150
- }, style: {
1151
- width: 36,
1152
- height: 36,
1153
- borderRadius: 5,
1154
- marginRight: 15
1155
- }, size: "xs" }), /* @__PURE__ */ React__default.createElement(TouchableHighlight, { underlayColor: "#dddddd", onPress: () => safeSend({
1156
- type: Actions.CLEAR_IMAGE
1157
- }), style: {
1158
- backgroundColor: "#f44336",
1159
- paddingVertical: 2,
1160
- paddingHorizontal: 5,
1161
- borderRadius: 5,
1162
- marginLeft: 10,
911
+ zIndex: 1,
1163
912
  elevation: 3,
1164
913
  shadowColor: "#000",
1165
914
  shadowOffset: {
1166
915
  width: 0,
1167
- height: 1
916
+ height: -1
1168
917
  },
1169
- shadowOpacity: 0.3,
918
+ shadowOpacity: 0.05,
1170
919
  shadowRadius: 2
920
+ } }, /* @__PURE__ */ React__default.createElement(View, { style: {
921
+ flex: 1,
922
+ flexDirection: "row",
923
+ alignItems: "center",
924
+ paddingLeft: 15,
925
+ paddingRight: 5
926
+ } }, /* @__PURE__ */ React__default.createElement(View, { style: {
927
+ width: 56,
928
+ height: 56,
929
+ marginRight: 15,
930
+ borderRadius: 4,
931
+ backgroundColor: colors.gray[200],
932
+ overflow: "hidden",
933
+ borderWidth: 1,
934
+ borderColor: "#e0e0e0"
935
+ } }, /* @__PURE__ */ React__default.createElement(Image, { key: selectedImage, alt: "selected image", source: {
936
+ uri: selectedImage
937
+ }, style: {
938
+ width: "100%",
939
+ height: "100%"
940
+ }, size: "md" }), loading && /* @__PURE__ */ React__default.createElement(View, { style: {
941
+ position: "absolute",
942
+ top: 0,
943
+ left: 0,
944
+ right: 0,
945
+ bottom: 0,
946
+ backgroundColor: "rgba(255, 255, 255, 0.7)",
947
+ justifyContent: "center",
948
+ alignItems: "center"
949
+ } }, /* @__PURE__ */ React__default.createElement(Spinner, { size: "small", color: colors.blue[500] }))), /* @__PURE__ */ React__default.createElement(View, { style: {
950
+ flex: 1
1171
951
  } }, /* @__PURE__ */ React__default.createElement(Text, { style: {
1172
- color: "white",
1173
- fontWeight: "bold"
1174
- } }, "X"))));
1175
- }, [(_k = state == null ? void 0 : state.context) == null ? void 0 : _k.selectedImage, safeSend]);
952
+ fontSize: 14,
953
+ fontWeight: "400",
954
+ color: colors.gray[800]
955
+ } }, ((_a3 = images[0]) == null ? void 0 : _a3.fileName) || "image_" + new Date().getTime() + ".jpg"), /* @__PURE__ */ React__default.createElement(Text, { style: {
956
+ fontSize: 12,
957
+ color: colors.gray[500],
958
+ marginTop: 2
959
+ } }, loading ? "Preparing..." : "Ready to send")), /* @__PURE__ */ React__default.createElement(TouchableHighlight, { underlayColor: "rgba(0,0,0,0.1)", onPress: () => {
960
+ setSelectedImage("");
961
+ setImages([]);
962
+ }, style: {
963
+ backgroundColor: colors.red[500],
964
+ borderRadius: 24,
965
+ width: 36,
966
+ height: 36,
967
+ alignItems: "center",
968
+ justifyContent: "center",
969
+ marginRight: 10
970
+ } }, /* @__PURE__ */ React__default.createElement(Ionicons, { name: "close", size: 20, color: "white" }))));
971
+ }, [selectedImage, loading, images]);
1176
972
  const setImageViewerObject = (obj, v) => {
1177
973
  setImageObject(obj);
1178
974
  setImageViewer(v);
1179
975
  };
1180
976
  const modalContent = React__default.useMemo(() => {
1181
- if (!imageObject)
1182
- return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null);
977
+ if (!imageObject || !imageObject.image)
978
+ return null;
1183
979
  const {
1184
980
  image,
1185
981
  _id
@@ -1187,14 +983,42 @@ const ConversationViewComponent = (_a) => {
1187
983
  return /* @__PURE__ */ React__default.createElement(CachedImage, { style: {
1188
984
  width: "100%",
1189
985
  height: "100%"
1190
- }, resizeMode: "cover", cacheKey: `${_id}-slack-bubble-imageKey`, source: {
986
+ }, resizeMode: "cover", cacheKey: `${_id}-modal-imageKey`, source: {
1191
987
  uri: image,
1192
988
  expiresIn: 86400
1193
989
  }, alt: "image" });
1194
990
  }, [imageObject]);
1195
991
  const renderMessage = useCallback((props) => {
992
+ const isUploading = props.currentMessage._id === uploadingMessageId && loading;
993
+ if (isUploading && props.currentMessage.image) {
994
+ return /* @__PURE__ */ React__default.createElement(View, { style: {
995
+ padding: 10,
996
+ marginBottom: 10,
997
+ marginRight: 10,
998
+ alignSelf: "flex-end",
999
+ borderRadius: 15,
1000
+ backgroundColor: colors.gray[100],
1001
+ maxWidth: "80%"
1002
+ } }, props.currentMessage.text && props.currentMessage.text.trim() !== "" && /* @__PURE__ */ React__default.createElement(Box, { style: {
1003
+ height: 15,
1004
+ borderRadius: 4,
1005
+ backgroundColor: colors.gray[200],
1006
+ overflow: "hidden",
1007
+ marginBottom: 8
1008
+ } }, /* @__PURE__ */ React__default.createElement(Skeleton, { variant: "rounded", style: {
1009
+ flex: 1
1010
+ } })), /* @__PURE__ */ React__default.createElement(Box, { style: {
1011
+ height: 150,
1012
+ width: 150,
1013
+ borderRadius: 10,
1014
+ backgroundColor: colors.gray[200],
1015
+ overflow: "hidden"
1016
+ } }, /* @__PURE__ */ React__default.createElement(Skeleton, { variant: "rounded", style: {
1017
+ flex: 1
1018
+ } })));
1019
+ }
1196
1020
  return /* @__PURE__ */ React__default.createElement(Message, __spreadProps(__spreadValues({}, props), { isShowImageViewer, setImageViewer: setImageViewerObject }));
1197
- }, [isShowImageViewer]);
1021
+ }, [isShowImageViewer, uploadingMessageId, loading]);
1198
1022
  let onScroll = false;
1199
1023
  const onMomentumScrollBegin = async ({
1200
1024
  nativeEvent
@@ -1205,194 +1029,18 @@ const ConversationViewComponent = (_a) => {
1205
1029
  }
1206
1030
  };
1207
1031
  const onEndReached = () => {
1208
- console.log("on end reached");
1209
1032
  if (!onScroll)
1210
1033
  return;
1211
1034
  onScroll = false;
1212
1035
  };
1213
- useEffect(() => {
1214
- console.log("Current channel ID:", state.context.channelId);
1215
- console.log("Current state:", state.value);
1216
- console.log("Channel messages count:", state.context.channelMessages.length);
1217
- }, [state.context.channelId, state.value, state.context.channelMessages]);
1218
- useEffect(() => {
1219
- if (state && typeof state.matches === "function") {
1220
- if (state.matches(BaseState.FetchMessages)) {
1221
- console.log("In FetchMessages state, attempting to fetch messages");
1222
- if (!fetchInProgressRef.current) {
1223
- fetchInProgressRef.current = true;
1224
- fetchMessagesDirectly().finally(() => {
1225
- fetchInProgressRef.current = false;
1226
- });
1227
- }
1228
- } else if (state.matches(MainState.FetchMoreMessages)) {
1229
- if (!fetchMoreInProgressRef.current) {
1230
- fetchMoreInProgressRef.current = true;
1231
- fetchMoreMessagesImpl().then((result) => {
1232
- if (result.error) {
1233
- console.error("Error fetching more messages:", result.error);
1234
- safeSend({
1235
- type: "ERROR",
1236
- data: {
1237
- message: result.error
1238
- }
1239
- });
1240
- } else {
1241
- safeSend({
1242
- type: "FETCH_MORE_MESSAGES_SUCCESS",
1243
- data: result
1244
- });
1245
- }
1246
- fetchMoreInProgressRef.current = false;
1247
- });
1248
- }
1249
- } else if (state.matches(MainState.SendMessage)) {
1250
- if (!sendInProgressRef.current) {
1251
- sendInProgressRef.current = true;
1252
- sendMessageImpl().then((result) => {
1253
- if (result.error) {
1254
- console.error("Error sending message:", result.error);
1255
- safeSend({
1256
- type: "ERROR",
1257
- data: {
1258
- message: result.error
1259
- }
1260
- });
1261
- } else {
1262
- safeSend({
1263
- type: "SEND_MESSAGE_SUCCESS",
1264
- data: result
1265
- });
1266
- }
1267
- sendInProgressRef.current = false;
1268
- });
1269
- }
1270
- } else if (state.matches(MainState.SendMessageWithFile)) {
1271
- if (!sendFileInProgressRef.current) {
1272
- sendFileInProgressRef.current = true;
1273
- sendMessageWithFileImpl().then((result) => {
1274
- if (result.error) {
1275
- console.error("Error sending message with file:", result.error);
1276
- safeSend({
1277
- type: "ERROR",
1278
- data: {
1279
- message: result.error
1280
- }
1281
- });
1282
- } else {
1283
- safeSend({
1284
- type: "SEND_MESSAGE_WITH_FILE_SUCCESS",
1285
- data: result
1286
- });
1287
- }
1288
- sendFileInProgressRef.current = false;
1289
- });
1290
- }
1291
- } else if (state.matches(MainState.CreateDirectChannel)) {
1292
- if (!createChannelInProgressRef.current) {
1293
- createChannelInProgressRef.current = true;
1294
- createDirectChannelImpl().then((result) => {
1295
- if (result.error) {
1296
- console.error("Error creating direct channel:", result.error);
1297
- safeSend({
1298
- type: "ERROR",
1299
- data: {
1300
- message: result.error
1301
- }
1302
- });
1303
- } else {
1304
- safeSend({
1305
- type: "CREATE_DIRECT_CHANNEL_SUCCESS",
1306
- data: result
1307
- });
1308
- }
1309
- createChannelInProgressRef.current = false;
1310
- });
1311
- }
1312
- }
1313
- }
1314
- }, [state == null ? void 0 : state.value, fetchMessagesDirectly, fetchMoreMessagesImpl, sendMessageImpl, sendMessageWithFileImpl, createDirectChannelImpl, safeSend]);
1315
- const fetchInProgressRef = useRef(false);
1316
- const fetchMoreInProgressRef = useRef(false);
1317
- const sendInProgressRef = useRef(false);
1318
- const sendFileInProgressRef = useRef(false);
1319
- const createChannelInProgressRef = useRef(false);
1320
- const renderChatFooter = useCallback(() => {
1321
- var _a3, _b3;
1322
- return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement(ImageViewerModal, { isVisible: isShowImageViewer, setVisible: setImageViewer, modalContent }), /* @__PURE__ */ React__default.createElement(SubscriptionHandler, { channelId: (_b3 = (_a3 = state == null ? void 0 : state.context) == null ? void 0 : _a3.channelId) == null ? void 0 : _b3.toString(), subscribeToNewMessages: () => {
1323
- var _a4, _b4;
1324
- return subscribeToMore({
1325
- document: OnChatMessageAddedDocument,
1326
- variables: {
1327
- channelId: (_b4 = (_a4 = state == null ? void 0 : state.context) == null ? void 0 : _a4.channelId) == null ? void 0 : _b4.toString()
1328
- },
1329
- updateQuery: (prev, {
1330
- subscriptionData
1331
- }) => {
1332
- var _a5, _b5, _c2, _d2;
1333
- try {
1334
- console.log("\u{1F514} Subscription data received for channel:", (_a5 = state == null ? void 0 : state.context) == null ? void 0 : _a5.channelId);
1335
- if (!((_b5 = subscriptionData == null ? void 0 : subscriptionData.data) == null ? void 0 : _b5.chatMessageAdded)) {
1336
- console.log("\u{1F514} No valid message in subscription data");
1337
- return prev;
1338
- }
1339
- const newMessage = subscriptionData.data.chatMessageAdded;
1340
- console.log("\u{1F514} New message received:", newMessage.id);
1341
- const currentMessages = ((_c2 = prev == null ? void 0 : prev.messages) == null ? void 0 : _c2.data) || [];
1342
- if (currentMessages.some((msg) => msg.id === newMessage.id)) {
1343
- console.log("\u{1F514} Message already in cache, skipping update");
1344
- return prev;
1345
- }
1346
- setTimeout(() => {
1347
- try {
1348
- console.log("\u{1F514} Directly updating state machine with new message");
1349
- safeSend({
1350
- type: Actions.SET_CHANNEL_MESSAGES,
1351
- data: {
1352
- messages: [...state.context.channelMessages, newMessage],
1353
- totalCount: (state.context.totalCount || 0) + 1
1354
- }
1355
- });
1356
- } catch (error) {
1357
- console.error("\u{1F514} Error updating state with subscription data:", error);
1358
- }
1359
- }, 0);
1360
- const updatedData = __spreadProps(__spreadValues({}, prev), {
1361
- messages: __spreadProps(__spreadValues({}, prev.messages), {
1362
- data: [...currentMessages, newMessage],
1363
- totalCount: (((_d2 = prev == null ? void 0 : prev.messages) == null ? void 0 : _d2.totalCount) || 0) + 1
1364
- })
1365
- });
1366
- console.log("\u{1F514} Returning updated query data with new messages");
1367
- return updatedData;
1368
- } catch (error) {
1369
- console.error("\u{1F514} Error in subscription updateQuery:", error);
1370
- return prev;
1371
- }
1372
- }
1373
- });
1374
- } }));
1375
- }, [isShowImageViewer, modalContent, (_l = state == null ? void 0 : state.context) == null ? void 0 : _l.channelId, (_m = state == null ? void 0 : state.context) == null ? void 0 : _m.channelMessages, subscribeToMore, safeSend]);
1376
- const listViewProps = useMemo(() => ({
1377
- onEndReached,
1378
- onEndReachedThreshold: 0.5,
1379
- onMomentumScrollBegin,
1380
- removeClippedSubviews: true,
1381
- initialNumToRender: 10,
1382
- maxToRenderPerBatch: 7,
1383
- windowSize: 7,
1384
- updateCellsBatchingPeriod: 50,
1385
- keyExtractor: (item) => item._id
1386
- }), [onEndReached, onMomentumScrollBegin]);
1387
1036
  const renderLoadEarlier = useCallback(() => {
1388
- var _a3;
1389
- return ((_a3 = state == null ? void 0 : state.context) == null ? void 0 : _a3.loadingOldMessages) ? /* @__PURE__ */ React__default.createElement(View, { style: {
1037
+ return loadingOldMessages ? /* @__PURE__ */ React__default.createElement(View, { style: {
1390
1038
  padding: 10,
1391
1039
  backgroundColor: "rgba(255,255,255,0.8)",
1392
1040
  borderRadius: 10,
1393
1041
  marginTop: 10
1394
1042
  } }, /* @__PURE__ */ React__default.createElement(Spinner, { size: "small", color: "#3b82f6" })) : null;
1395
- }, [(_n = state == null ? void 0 : state.context) == null ? void 0 : _n.loadingOldMessages]);
1043
+ }, [loadingOldMessages]);
1396
1044
  const renderInputToolbar = useCallback((props) => {
1397
1045
  return /* @__PURE__ */ React__default.createElement(InputToolbar, __spreadProps(__spreadValues({}, props), { containerStyle: {
1398
1046
  backgroundColor: "white",
@@ -1407,10 +1055,42 @@ const ConversationViewComponent = (_a) => {
1407
1055
  alignItems: "center"
1408
1056
  } }));
1409
1057
  }, []);
1058
+ const imageViewerModal = useMemo(() => /* @__PURE__ */ React__default.createElement(ImageViewerModal, { isVisible: isShowImageViewer, setVisible: setImageViewer, modalContent }), [isShowImageViewer, modalContent]);
1059
+ const subscriptionHandler = useMemo(() => /* @__PURE__ */ React__default.createElement(SubscriptionHandler, { channelId: channelId == null ? void 0 : channelId.toString(), subscribeToNewMessages: () => subscribeToMore({
1060
+ document: OnChatMessageAddedDocument,
1061
+ variables: {
1062
+ channelId: channelId == null ? void 0 : channelId.toString()
1063
+ }
1064
+ }) }), [channelId, subscribeToMore, auth == null ? void 0 : auth.id]);
1065
+ const renderChatFooter = useCallback(() => {
1066
+ return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, imageViewerModal, subscriptionHandler);
1067
+ }, [imageViewerModal, subscriptionHandler]);
1068
+ const listViewProps = useMemo(() => ({
1069
+ onEndReached,
1070
+ onEndReachedThreshold: 0.5,
1071
+ onMomentumScrollBegin,
1072
+ removeClippedSubviews: true,
1073
+ initialNumToRender: 10,
1074
+ maxToRenderPerBatch: 7,
1075
+ windowSize: 7,
1076
+ updateCellsBatchingPeriod: 50,
1077
+ keyExtractor: (item) => item._id
1078
+ }), [onEndReached, onMomentumScrollBegin]);
1079
+ useCallback((message, prefix = "Message") => {
1080
+ var _a3, _b3, _c2, _d2, _e, _f, _g, _h, _i;
1081
+ if (__DEV__) {
1082
+ console.log(`${prefix} ID: ${message == null ? void 0 : message.id}, Has files object: ${!!(message == null ? void 0 : message.files)}, Files typename: ${(_a3 = message == null ? void 0 : message.files) == null ? void 0 : _a3.__typename}, Files data exists: ${!!((_b3 = message == null ? void 0 : message.files) == null ? void 0 : _b3.data)}, Files count: ${((_d2 = (_c2 = message == null ? void 0 : message.files) == null ? void 0 : _c2.data) == null ? void 0 : _d2.length) || 0}`);
1083
+ if (((_e = message == null ? void 0 : message.files) == null ? void 0 : _e.data) && ((_g = (_f = message == null ? void 0 : message.files) == null ? void 0 : _f.data) == null ? void 0 : _g.length) > 0) {
1084
+ const file = (_h = message == null ? void 0 : message.files) == null ? void 0 : _h.data[0];
1085
+ console.log(`File[0] ID: ${file == null ? void 0 : file.id}, URL: ${(_i = file == null ? void 0 : file.url) == null ? void 0 : _i.substring(0, 30)}..., Name: ${file == null ? void 0 : file.name}, Type: ${file == null ? void 0 : file.mimeType}`);
1086
+ }
1087
+ }
1088
+ }, []);
1410
1089
  return /* @__PURE__ */ React__default.createElement(View, { style: {
1411
1090
  flex: 1,
1412
- backgroundColor: "white"
1413
- } }, (state == null ? void 0 : state.matches) && state.matches(BaseState.FetchMessages) && /* @__PURE__ */ React__default.createElement(Spinner, { color: "#3b82f6" }), /* @__PURE__ */ React__default.createElement(
1091
+ backgroundColor: "white",
1092
+ position: "relative"
1093
+ } }, messageLoading && /* @__PURE__ */ React__default.createElement(Spinner, { color: "#3b82f6" }), selectedImage ? renderAccessory() : null, /* @__PURE__ */ React__default.createElement(
1414
1094
  GiftedChat,
1415
1095
  {
1416
1096
  ref: messageRootListRef,
@@ -1419,19 +1099,13 @@ const ConversationViewComponent = (_a) => {
1419
1099
  messages: messageList,
1420
1100
  listViewProps: __spreadProps(__spreadValues({}, listViewProps), {
1421
1101
  contentContainerStyle: {
1422
- paddingBottom: 10
1423
- },
1424
- keyboardShouldPersistTaps: "handled"
1425
- }),
1426
- onSend: handleSend,
1427
- text: safeContextProperty("messageText", " ") || " ",
1428
- onInputTextChanged: (text) => safeSend({
1429
- type: Actions.SET_MESSAGE_TEXT,
1430
- data: {
1431
- messageText: text
1102
+ paddingBottom: selectedImage ? 90 : 0
1432
1103
  }
1433
1104
  }),
1434
- renderFooter: () => safeContextProperty("loading") || safeContextProperty("imageLoading") ? /* @__PURE__ */ React__default.createElement(Spinner, { color: "#3b82f6" }) : null,
1105
+ onSend: handleSend,
1106
+ text: messageText || " ",
1107
+ onInputTextChanged: (text) => setMessageText(text),
1108
+ renderFooter: () => loading && !images.length ? /* @__PURE__ */ React__default.createElement(Spinner, { color: "#3b82f6" }) : null,
1435
1109
  scrollToBottom: true,
1436
1110
  user: {
1437
1111
  _id: (auth == null ? void 0 : auth.id) || ""
@@ -1442,14 +1116,13 @@ const ConversationViewComponent = (_a) => {
1442
1116
  renderMessageText,
1443
1117
  renderInputToolbar,
1444
1118
  minInputToolbarHeight: 50,
1445
- renderActions: safeContextProperty("channelId") && renderActions,
1446
- renderAccessory: !!((_o = state == null ? void 0 : state.context) == null ? void 0 : _o.selectedImage) ? renderAccessory : void 0,
1119
+ renderActions: channelId && renderActions,
1447
1120
  renderMessage,
1448
1121
  renderChatFooter,
1449
1122
  renderLoadEarlier,
1450
- loadEarlier: ((_p = state == null ? void 0 : state.context) == null ? void 0 : _p.totalCount) > ((_r = (_q = state == null ? void 0 : state.context) == null ? void 0 : _q.channelMessages) == null ? void 0 : _r.length),
1451
- isLoadingEarlier: (_s = state == null ? void 0 : state.context) == null ? void 0 : _s.loadingOldMessages,
1452
- bottomOffset: Platform.OS === "ios" ? 10 : 0,
1123
+ loadEarlier: totalCount > channelMessages.length,
1124
+ isLoadingEarlier: loadingOldMessages,
1125
+ bottomOffset: Platform.OS === "ios" ? selectedImage ? 90 : 10 : 0,
1453
1126
  textInputProps: {
1454
1127
  style: {
1455
1128
  borderWidth: 1,
@@ -1494,15 +1167,12 @@ const SubscriptionHandler = ({
1494
1167
  const channelIdRef = useRef(channelId);
1495
1168
  useEffect(() => {
1496
1169
  if (!channelId) {
1497
- console.log("\u26A0\uFE0F No channel ID for subscription");
1498
1170
  return;
1499
1171
  }
1500
- console.log("\u{1F504} Setting up NEW subscription for channel:", channelId);
1501
1172
  const unsubscribe = subscribeToNewMessages();
1502
1173
  channelIdRef.current = channelId;
1503
1174
  return () => {
1504
1175
  if (unsubscribe && typeof unsubscribe === "function") {
1505
- console.log("\u{1F504} Cleaning up subscription for channel:", channelIdRef.current);
1506
1176
  unsubscribe();
1507
1177
  }
1508
1178
  };