@messenger-box/platform-mobile 10.0.3-alpha.20 → 10.0.3-alpha.201

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