@cometchat/chat-uikit-react-native 4.3.6 → 4.3.7

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cometchat/chat-uikit-react-native",
3
- "version": "4.3.6",
3
+ "version": "4.3.7",
4
4
  "description": "Ready-to-use Chat UI Components for React Native",
5
5
  "main": "src/index",
6
6
  "module": "src/index",
@@ -5,7 +5,7 @@ import { Text, View } from "react-native";
5
5
  import {
6
6
  backIcon, searchIcon,
7
7
  passwordGroupIcon, privateGroupIcon,
8
- rightTickIcon,
8
+ checkIcon,
9
9
  } from "./resources";
10
10
  //@ts-ignore
11
11
  import { CometChat } from "@cometchat/chat-sdk-react-native";
@@ -197,7 +197,7 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
197
197
  } = props;
198
198
 
199
199
  //context values
200
- const {theme} = React.useContext<CometChatContextType>(CometChatContext);
200
+ const { theme } = React.useContext<CometChatContextType>(CometChatContext);
201
201
 
202
202
  const groupListRef = useRef<CometChatListActionsInterface>(null);
203
203
  const activeSwipeRows = React.useRef({});
@@ -235,7 +235,11 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
235
235
  nameTextFont: theme?.typography.title1,
236
236
  ...avatarStyle
237
237
  });
238
- const _statusIndicatorStyle = new StatusIndicatorStyle(statusIndicatorStyle || {});
238
+ const _statusIndicatorStyle = new StatusIndicatorStyle(statusIndicatorStyle || {
239
+ borderRadius: 10,
240
+ height: 15,
241
+ width: 15,
242
+ });
239
243
  const _listItemStyle = new ListItemStyle({
240
244
  backgroundColor: theme?.palette?.getBackgroundColor(),
241
245
  titleColor: theme?.palette.getAccent(),
@@ -454,13 +458,13 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
454
458
  CometChatUIEventHandler.addGroupListener(
455
459
  uiEventListener,
456
460
  {
457
- ccGroupCreated: ({group}) => {
458
- groupListRef.current.addItemToList(group,0);
461
+ ccGroupCreated: ({ group }) => {
462
+ groupListRef.current.addItemToList(group, 0);
459
463
  },
460
- ccGroupDeleted: ({group}) => {
464
+ ccGroupDeleted: ({ group }) => {
461
465
  groupListRef.current?.removeItemFromList(group.guid);
462
466
  },
463
- ccGroupLeft: ({leftGroup}) => {
467
+ ccGroupLeft: ({ leftGroup }) => {
464
468
  leftGroup['hasJoined'] = false;
465
469
  leftGroup['membersCount'] = leftGroup['membersCount'] - 1;
466
470
  console.log(leftGroup);
@@ -470,7 +474,7 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
470
474
  groupListRef.current?.updateList(leftGroup);
471
475
  }
472
476
  },
473
- ccGroupMemberKicked: ({group}) => {
477
+ ccGroupMemberKicked: ({ group }) => {
474
478
  if (group['type'] == CometChat.GROUP_TYPE.PRIVATE) {
475
479
  groupListRef.current?.removeItemFromList(group.getGuid());
476
480
  } else {
@@ -478,13 +482,13 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
478
482
  groupListRef.current?.updateList(group);
479
483
  }
480
484
  },
481
- ccOwnershipChanged: ({group}) => {
485
+ ccOwnershipChanged: ({ group }) => {
482
486
  groupListRef.current?.updateList(group);
483
487
  },
484
- ccGroupMemberAdded: ({userAddedIn}: {userAddedIn: CometChat.Group}) => {
488
+ ccGroupMemberAdded: ({ userAddedIn }: { userAddedIn: CometChat.Group }) => {
485
489
  groupListRef.current?.updateList(userAddedIn);
486
490
  },
487
- ccGroupMemberJoined: ({joinedGroup}: {joinedGroup: CometChat.Group}) => {
491
+ ccGroupMemberJoined: ({ joinedGroup }: { joinedGroup: CometChat.Group }) => {
488
492
  joinedGroup['membersCount'] = joinedGroup['membersCount'] + 1;
489
493
  joinedGroup['scope'] = "participant";
490
494
  joinedGroup['hasJoined'] = true;
@@ -498,7 +502,7 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
498
502
  }
499
503
  }, []);
500
504
 
501
- const GroupItemView = ({item}) => {
505
+ const GroupItemView = ({ item }) => {
502
506
  //custom view check
503
507
  if (ListItemView)
504
508
  return ListItemView(item);
@@ -516,7 +520,7 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
516
520
  if (selecting) {
517
521
  let index: number = selectedGroups.findIndex((value) => value.guid == item.guid);
518
522
  if (index >= 0) {
519
- image = rightTickIcon;
523
+ image = checkIcon;
520
524
  backgroundColor = theme?.palette?.getBackgroundColor();
521
525
  }
522
526
  }
@@ -526,7 +530,7 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
526
530
  avatarName={name}
527
531
  avatarURL={icon}
528
532
  hideSeparator={hideSeperator}
529
- SubtitleView={() => SubtitleView && SubtitleView(item) || <Text style={{color: theme.palette.getAccent600()}}>{membersCount} <Text>{localize("MEMBERS")}</Text></Text>}
533
+ SubtitleView={() => SubtitleView && SubtitleView(item) || <Text style={{ color: theme.palette.getAccent600() }}>{membersCount} <Text>{localize("MEMBERS")}</Text></Text>}
530
534
  title={name}
531
535
  statusIndicatorIcon={image}
532
536
  statusIndicatorColor={backgroundColor}
@@ -539,7 +543,7 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
539
543
  activeSwipeRows={activeSwipeRows.current}
540
544
  rowOpens={(id) => {
541
545
  Object.keys(activeSwipeRows.current).forEach(key => {
542
- if(id !== key && activeSwipeRows.current[key]) {
546
+ if (id !== key && activeSwipeRows.current[key]) {
543
547
  activeSwipeRows.current[key]?.current?.closeRow?.()
544
548
  delete activeSwipeRows.current[key]
545
549
  }
@@ -556,7 +560,7 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
556
560
  }
557
561
 
558
562
  return (
559
- <View style={[Style.container, {backgroundColor: _groupsStyle.backgroundColor}]}>
563
+ <View style={[Style.container, { backgroundColor: _groupsStyle.backgroundColor }]}>
560
564
  <CometChatList
561
565
  title={title}
562
566
  LoadingStateView={LoadingStateView}
@@ -566,7 +570,7 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
566
570
  ListItemView={GroupItemView}
567
571
  EmptyStateView={EmptyView}
568
572
  ErrorStateView={ErrorView}
569
- requestBuilder={ groupsRequestBuilder || new CometChat.GroupsRequestBuilder()
573
+ requestBuilder={groupsRequestBuilder || new CometChat.GroupsRequestBuilder()
570
574
  .setLimit(30)
571
575
  .setSearchKeyword("")}
572
576
  searchRequestBuilder={searchRequestBuilder}
@@ -581,7 +585,7 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface
581
585
  hideSubmitIcon={hideSubmitIcon}
582
586
  onError={onError}
583
587
  onBack={onBack}
584
- listStyle={{..._groupsStyle, background: _groupsStyle.backgroundColor}}
588
+ listStyle={{ ..._groupsStyle, background: _groupsStyle.backgroundColor }}
585
589
  statusIndicatorStyle={_statusIndicatorStyle}
586
590
  avatarStyle={_avatarStyle}
587
591
  listItemStyle={_listItemStyle}
@@ -605,7 +609,7 @@ CometChatGroups.defaultProps = {
605
609
  options: undefined,
606
610
  hideSeperator: false,
607
611
  backButtonIcon: backIcon,
608
- selectionMode: "multiple",
612
+ selectionMode: "none",
609
613
  onSelection: undefined,
610
614
  EmptyStateView: undefined,
611
615
  emptyStateText: undefined,
@@ -7,6 +7,7 @@ import loadingIcon from "./spineer.png"
7
7
  import rightTickIcon from "./rightTick.png";
8
8
  import closeIcon from "./close.png";
9
9
  import moreIcon from "./more.png";
10
+ import checkIcon from './check.png';
10
11
 
11
12
  export {
12
13
  backIcon,
@@ -17,5 +18,6 @@ export {
17
18
  loadingIcon,
18
19
  rightTickIcon,
19
20
  closeIcon,
20
- moreIcon
21
+ moreIcon,
22
+ checkIcon
21
23
  }
@@ -1,7 +1,7 @@
1
1
  import React, { useContext, useEffect, useState } from 'react'
2
2
  import { Dimensions, FlatList, Image, Text, TouchableOpacity, View, ScrollView } from 'react-native'
3
3
  import { CometChat } from '@cometchat/chat-sdk-react-native'
4
- import { AvatarStyleInterface, CometChatContext, CometChatDate, CometChatListItem, CometChatMessageTemplate, CometChatReceipt, CometChatUIEventHandler, ImageType, ListItemStyleInterface, StatusIndicatorStyleInterface, localize } from '../shared'
4
+ import { AvatarStyleInterface, ChatConfigurator, CometChatContext, CometChatDate, CometChatListItem, CometChatMessageTemplate, CometChatUIEventHandler, ImageType, ListItemStyleInterface, StatusIndicatorStyleInterface, localize } from '../shared'
5
5
  import { MessageInformationStyleInterface } from './MessageInformationStyle'
6
6
  import { MessageUtils } from '../shared/utils/MessageUtils'
7
7
  import { Style } from "./styles";
@@ -42,6 +42,8 @@ export interface CometChatMessageInformationInterface {
42
42
  LoadingStateView?: () => JSX.Element,
43
43
  }
44
44
 
45
+ let templatesMap = new Map<string, CometChatMessageTemplate>();
46
+
45
47
  export const CometChatMessageInformation = (props: CometChatMessageInformationInterface) => {
46
48
  const {
47
49
  title = localize('INFORMATION'),
@@ -71,6 +73,7 @@ export const CometChatMessageInformation = (props: CometChatMessageInformationIn
71
73
  const { theme } = useContext(CometChatContext);
72
74
  const [recipients, setRecipients] = useState<Array<Recipient>>([]);
73
75
  const [listState, setListState] = useState<"loading" | "error" | "done">("loading");
76
+ const [templateLoading, setTemplateLoading] = useState(true);
74
77
 
75
78
  const {
76
79
  height,
@@ -190,6 +193,7 @@ export const CometChatMessageInformation = (props: CometChatMessageInformationIn
190
193
  }
191
194
 
192
195
  useEffect(() => {
196
+ loadTemplates()
193
197
  //add listener for message delivery
194
198
  CometChatUIEventHandler.addMessageListener(
195
199
  listenerId,
@@ -234,6 +238,15 @@ export const CometChatMessageInformation = (props: CometChatMessageInformationIn
234
238
  )
235
239
  }
236
240
 
241
+ const loadTemplates = () => {
242
+ let templates: CometChatMessageTemplate[] = ChatConfigurator.dataSource.getAllMessageTemplates(theme);
243
+ templates.forEach(template => {
244
+ if (templatesMap.get(`${template.category}_${template.type}`)) return
245
+ templatesMap.set(`${template.category}_${template.type}`, template);
246
+ });
247
+ setTemplateLoading(false)
248
+ }
249
+
237
250
  return (
238
251
  <View style={[
239
252
  {
@@ -268,14 +281,16 @@ export const CometChatMessageInformation = (props: CometChatMessageInformationIn
268
281
  <View style={Style.msgBubbleContainer}>
269
282
  <ScrollView>
270
283
  {
271
- BubbleView ?
272
- BubbleView(message) :
273
- MessageUtils.getMessageView({
274
- message,
275
- template,
276
- alignment: "right",
277
- theme
278
- })
284
+ templateLoading
285
+ ? <LoadingView />
286
+ : BubbleView
287
+ ? BubbleView(message)
288
+ : MessageUtils.getMessageView({
289
+ message,
290
+ template: template ? template : templatesMap.get(`${message.category}_${message.type}`),
291
+ alignment: "right",
292
+ theme
293
+ })
279
294
  }
280
295
  </ScrollView>
281
296
  </View>
@@ -92,6 +92,21 @@ export interface CometChatThreadedMessagesInterface {
92
92
  * @description Styling properties of the compone
93
93
  */
94
94
  threadedMessagesStyle: ThreadedMessagesStyleInterface;
95
+ /**
96
+ * Hide the MessageComposer
97
+ * @type {boolean}
98
+ */
99
+ hideMessageComposer?: boolean,
100
+ /**
101
+ * Override the default MessageComposerView
102
+ * @returns JSX.Element
103
+ */
104
+ MessageComposerView?: ({ user, group, parentMessage }: { user?: CometChat.User, group?: CometChat.Group, parentMessage: CometChat.BaseMessage }) => JSX.Element,
105
+ /**
106
+ * Override the default MessageListView
107
+ * @returns JSX.Element
108
+ */
109
+ MessageListView?: ({ user, group, parentMessage }: { user?: CometChat.User, group?: CometChat.Group, parentMessage: CometChat.BaseMessage }) => JSX.Element,
95
110
  }
96
111
 
97
112
  export interface ThreadedMessagesStyleInterface {
@@ -118,7 +133,10 @@ export const CometChatThreadedMessages = (
118
133
  messageComposerConfiguration,
119
134
  onClose,
120
135
  onError,
121
- threadedMessagesStyle
136
+ threadedMessagesStyle,
137
+ hideMessageComposer,
138
+ MessageComposerView,
139
+ MessageListView
122
140
  } = props;
123
141
 
124
142
  const loggedInUser = useRef(null);
@@ -133,13 +151,13 @@ export const CometChatThreadedMessages = (
133
151
 
134
152
  let limit: number = 30;
135
153
 
136
- const checkMessageBelongsToSameThread = (updatedMessage : CometChat.BaseMessage)=>{
154
+ const checkMessageBelongsToSameThread = (updatedMessage: CometChat.BaseMessage) => {
137
155
 
138
- return (updatedMessage.getParentMessageId() == message.getId() );
156
+ return (updatedMessage.getParentMessageId() == message.getId());
139
157
  }
140
158
 
141
- const checkAndUpdateRepliesCount = ( updatedMessage : CometChat.BaseMessage)=>{
142
- if(checkMessageBelongsToSameThread(updatedMessage)){
159
+ const checkAndUpdateRepliesCount = (updatedMessage: CometChat.BaseMessage) => {
160
+ if (checkMessageBelongsToSameThread(updatedMessage)) {
143
161
  setReplyCount((prev) => prev + 1);
144
162
  }
145
163
  }
@@ -248,7 +266,7 @@ export const CometChatThreadedMessages = (
248
266
  />
249
267
  <View style={styles.msgBubbleContainer}>
250
268
  <ScrollView>
251
- {BubbleView && BubbleView(message)}
269
+ {BubbleView && BubbleView(message)}
252
270
  </ScrollView>
253
271
  </View>
254
272
  {MessageActionView ? (
@@ -276,31 +294,38 @@ export const CometChatThreadedMessages = (
276
294
  )}
277
295
  <View style={{ flex: 1, paddingHorizontal: 8 }}>
278
296
  {(user !== null || group !== null) && (
279
- <CometChatMessageList
280
- messageRequestBuilder={new CometChat.MessagesRequestBuilder()
281
- .setLimit(limit)
282
- .setParentMessageId(message.getId())}
283
- parentMessageId={message.getId().toString()}
284
- user={user}
285
- group={group}
286
- onError={onError && onError}
287
- {...messageListConfiguration}
288
- />
297
+ MessageListView ?
298
+ <MessageListView user={user} group={group} parentMessage={message} /> :
299
+ <CometChatMessageList
300
+ messageRequestBuilder={new CometChat.MessagesRequestBuilder()
301
+ .setLimit(limit)
302
+ .setParentMessageId(message.getId())}
303
+ parentMessageId={message.getId().toString()}
304
+ user={user}
305
+ group={group}
306
+ onError={onError && onError}
307
+ {...messageListConfiguration}
308
+ />
289
309
  )}
290
310
  </View>
291
311
 
292
312
  <View style={styles.composerContainer}>
293
- <CometChatMessageComposer
294
- parentMessageId={message.getId()}
295
- messageComposerStyle={{
296
- borderRadius: 10,
297
- // backgroundColor: theme.palette.getAccent100(),
298
- }}
299
- user={user}
300
- group={group}
301
- onError={onError && onError}
302
- {...messageComposerConfiguration}
303
- />
313
+ {hideMessageComposer ?
314
+ null :
315
+ MessageComposerView ?
316
+ <MessageComposerView group={group} user={user} parentMessage={message} /> :
317
+ <CometChatMessageComposer
318
+ parentMessageId={message.getId()}
319
+ messageComposerStyle={{
320
+ borderRadius: 10,
321
+ // backgroundColor: theme.palette.getAccent100(),
322
+ }}
323
+ user={user}
324
+ group={group}
325
+ onError={onError && onError}
326
+ {...messageComposerConfiguration}
327
+ />
328
+ }
304
329
  </View>
305
330
  {Platform.OS === 'ios' && (
306
331
  <View
@@ -20,6 +20,21 @@ export class ThreadedMessagesConfiguration {
20
20
  messageListConfiguration?: MessageListConfigurationInterface;
21
21
  onClose?: () => void;
22
22
  onError?: (error: CometChat.CometChatException) => void;
23
+ /**
24
+ * Hide the MessageComposer
25
+ * @type {boolean}
26
+ */
27
+ hideMessageComposer?: boolean;
28
+ /**
29
+ * Override the default MessageComposerView
30
+ * @returns JSX.Element
31
+ */
32
+ MessageComposerView?: ({ user, group, parentMessage }: { user?: CometChat.User, group?: CometChat.Group, parentMessage: CometChat.BaseMessage }) => JSX.Element;
33
+ /**
34
+ * Override the default MessageListView
35
+ * @returns JSX.Element
36
+ */
37
+ MessageListView?: ({ user, group, parentMessage }: { user?: CometChat.User, group?: CometChat.Group, parentMessage: CometChat.BaseMessage }) => JSX.Element;
23
38
  constructor(props: ThreadedMessagesConfigurationInterface) {
24
39
  if (props)
25
40
  for (const [key, value] of Object.entries(props)) {
@@ -55,10 +55,12 @@ export class CallUtils {
55
55
  callMessageText = `${localize('MISSED_CALL')}`;
56
56
  }
57
57
  break;
58
- case CALL_BUSY:
59
58
  case CALL_REJECTED:
60
- if (this.isInitiator(initiator, loggedInUser)) {
61
59
  callMessageText = `${localize('CALL_REJECTED')}`;
60
+ break;
61
+ case CALL_BUSY:
62
+ if (this.isInitiator(initiator, loggedInUser)) {
63
+ callMessageText = `${localize('CALL_BUSY')}`;
62
64
  } else {
63
65
  callMessageText = `${localize('MISSED_CALL')}`;
64
66
  }
@@ -84,6 +84,7 @@ export const CometChatOutgoingCall = (props: CometChatOutgoingCallInterface) =>
84
84
  const callSessionId = useRef<string>(null);
85
85
  const callListener = useRef(null);
86
86
  const callSettings = useRef(null);
87
+ const isCallEnded = useRef<null | string>(undefined);
87
88
 
88
89
  const {
89
90
  backgroundColor,
@@ -114,7 +115,8 @@ export const CometChatOutgoingCall = (props: CometChatOutgoingCallInterface) =>
114
115
  CometChat.endCall((call as CometChat.Call).getSessionId())
115
116
  .then(() => {
116
117
  (call as CometChat.Call).setStatus("ended");
117
- CometChatUIEventHandler.emitCallEvent(CallUIEvents.ccCallEnded, { call });
118
+ !isCallEnded.current && CometChatUIEventHandler.emitCallEvent(CallUIEvents.ccCallEnded, { call });
119
+ isCallEnded.current = true;
118
120
  })
119
121
  .catch(err => {
120
122
  console.log("Error", err);
@@ -174,14 +176,16 @@ export const CometChatOutgoingCall = (props: CometChatOutgoingCallInterface) =>
174
176
  CometChat.clearActiveCall()
175
177
  setCallConnected(false);
176
178
  call.setStatus("ended");
177
- CometChatUIEventHandler.emitCallEvent(CallUIEvents.ccCallEnded, { call });
179
+ !isCallEnded.current && CometChatUIEventHandler.emitCallEvent(CallUIEvents.ccCallEnded, { call });
180
+ isCallEnded.current = true;
178
181
  }
179
182
  },
180
183
  onCallEndButtonPressed: () => {
181
184
  if (!checkIfDefualtCall(call)) {
182
185
  setCallConnected(false);
183
186
  call.setStatus("ended");
184
- CometChatUIEventHandler.emitCallEvent(CallUIEvents.ccCallEnded, { call });
187
+ !isCallEnded.current && CometChatUIEventHandler.emitCallEvent(CallUIEvents.ccCallEnded, { call });
188
+ isCallEnded.current = true;
185
189
  } else {
186
190
  endCallIfRequired();
187
191
  }
@@ -13,7 +13,7 @@ import {
13
13
  import React, {
14
14
  useCallback,
15
15
  useContext,
16
- useLayoutEffect,
16
+ useEffect,
17
17
  useRef,
18
18
  useState,
19
19
  } from 'react';
@@ -176,42 +176,31 @@ export const CometChatCreatePoll = (props: CometChatCreatePollInterface) => {
176
176
 
177
177
  const [question, setQuestion] = React.useState('');
178
178
  const [error, setError] = React.useState('');
179
- const [answersList, setAnswersList] = useState([]);
180
- const [answers, setAnswers] = useState({});
179
+ const [answers, setAnswers] = useState([]);
181
180
  const [kbOffset, setKbOffset] = React.useState(59);
182
181
  const [loader, setLoader] = React.useState(false);
183
182
  const loggedInUser = useRef(null);
184
- const answersFinalValues = useRef([]);
185
183
 
186
- const validate = () => {
187
- let answersValues = [];
184
+ function validate() {
188
185
  if (!question) {
189
186
  setError(localize('INVALID_POLL_QUESTION'));
190
187
  return false;
191
- }
192
- if (answersList.length === 0) {
193
- setError(localize('INVALID_POLL_OPTION'));
194
- return false;
195
- }
196
- for (const value of Object.values(answers)) {
197
- if (value) answersValues.push(value);
198
- }
199
- if (answersValues.length === 0) {
200
- setError(answerHelpText ?? localize('INVALID_POLL_OPTION'));
188
+ } else if (answers.length < 3 && !(answers.every(item => Boolean(item)))) {
189
+ setError(answerHelpText || localize('INVALID_POLL_OPTION'));
201
190
  return false;
191
+ } else {
192
+ setError('');
193
+ return true;
202
194
  }
203
- answersFinalValues.current = answersValues;
204
- setError('');
205
- return true;
206
195
  };
207
196
 
208
- const polls = () => {
197
+ function polls() {
209
198
  if (!validate()) return;
210
199
  setLoader(true);
211
200
 
212
201
  CometChat.callExtension('polls', 'POST', 'v2/create', {
213
202
  question: question,
214
- options: answersFinalValues.current,
203
+ options: answers.filter(item => item),
215
204
  receiver: user ? user['uid'] : group ? group['guid'] : '',
216
205
  receiverType: user ? 'user' : group ? 'group' : '',
217
206
  })
@@ -229,7 +218,7 @@ export const CometChatCreatePoll = (props: CometChatCreatePollInterface) => {
229
218
  });
230
219
  };
231
220
 
232
- const ErrorView = () => {
221
+ function ErrorView() {
233
222
  if (!error && error === '') return null;
234
223
 
235
224
  return (
@@ -281,107 +270,100 @@ export const CometChatCreatePoll = (props: CometChatCreatePollInterface) => {
281
270
  );
282
271
  };
283
272
 
284
- const handleAnswerTextChange = (text, index) => {
285
- setAnswers((prev) => {
286
- return { ...prev, [index]: text };
287
- });
288
- };
289
-
290
- const handleAddAnswerRow = () => {
291
- setAnswersList((prev) => [
292
- ...prev,
293
- { id: prev[prev.length - 1]['id'] + 1 },
294
- ]);
273
+ function handleAnswerTextChange(text, index) {
274
+ let existingAnswers = [...answers];
275
+ existingAnswers[index] = text;
276
+ setAnswers(existingAnswers);
295
277
  };
296
278
 
297
- const removeRow = (id) => {
298
- setAnswersList((prev) => prev.filter((_) => _.id !== id));
279
+ function handleAddAnswerRow() {
280
+ let existingAnswers = [...answers];
281
+ existingAnswers.push("");
282
+ setAnswers(existingAnswers);
299
283
  };
300
284
 
301
- const AnswersListItem = ({ item, index }) => {
302
- return (
303
- <>
304
- <CometChatSwipeRow
305
- id={item.id}
306
- options={
307
- defaultAnswers <= item.id
308
- ? () => [
309
- {
310
- id: item.id,
311
- icon: deleteIcon ?? ICONS.KICK,
312
- onPress: removeRow,
313
- },
314
- ]
315
- : () => []
316
- }
317
- >
318
- <View
319
- style={{
320
- backgroundColor:
321
- createPollsStyle?.backgroundColor ??
322
- theme.palette.getBackgroundColor(),
323
- }}
324
- >
325
- <TextInput
326
- value={answers[item.id]}
327
- onChangeText={(text) => handleAnswerTextChange(text, item.id)}
328
- placeholder={`${answerPlaceholderText} ${index + 1}`}
329
- placeholderTextColor={theme.palette.getAccent600()}
330
- style={[
331
- styles.textInputAnswers,
332
- {
333
- borderBottomColor: theme.palette.getAccent200(),
334
- color: theme.palette.getAccent(),
335
- },
336
- theme.typography.body,
337
- answers[item.id]?.length > 0
338
- ? createPollsStyle.answersPlaceholderTextStyle
339
- : createPollsStyle.answersInputTextStyle,
340
- ]}
341
- />
342
- </View>
343
- </CometChatSwipeRow>
344
- </>
345
- );
285
+ function removeRow(id) {
286
+ setAnswers((prev) => prev.filter((_, index) => id !== index));
346
287
  };
347
288
 
348
- const AddAnswer = () => {
289
+ function AnswersListItem({ item, index }: { item: string, index: number }) {
349
290
  return (
350
- <>
351
- <TouchableOpacity
352
- onPress={handleAddAnswerRow}
291
+ <CometChatSwipeRow
292
+ id={index + answers.length}
293
+ options={
294
+ defaultAnswers <= index
295
+ ? () => [
296
+ {
297
+ id: index,
298
+ icon: deleteIcon ?? ICONS.KICK,
299
+ onPress: () => removeRow(index),
300
+ },
301
+ ]
302
+ : () => []
303
+ }
304
+ >
305
+ <View
353
306
  style={{
354
- height: 56,
355
- width: '100%',
356
- justifyContent: 'center',
357
- paddingHorizontal: 5,
307
+ backgroundColor:
308
+ createPollsStyle?.backgroundColor ??
309
+ theme.palette.getBackgroundColor(),
358
310
  }}
359
311
  >
360
- <Text
312
+ <TextInput
313
+ value={item}
314
+ onChangeText={(text) => handleAnswerTextChange(text, index)}
315
+ placeholder={`${answerPlaceholderText} ${index + 1}`}
316
+ placeholderTextColor={theme.palette.getAccent600()}
361
317
  style={[
362
- theme.typography.name,
318
+ styles.textInputAnswers,
363
319
  {
364
- color: theme.palette.getPrimary(),
320
+ borderBottomColor: theme.palette.getAccent200(),
321
+ color: theme.palette.getAccent(),
365
322
  },
323
+ theme.typography.body,
324
+ item?.length > 0
325
+ ? createPollsStyle.answersPlaceholderTextStyle
326
+ : createPollsStyle.answersInputTextStyle,
366
327
  ]}
367
- >
368
- {addAnswerText ?? localize('ADD_ANOTHER_ANSWER')}
369
- </Text>
370
- </TouchableOpacity>
371
- <ErrorView />
372
- </>
328
+ />
329
+ </View>
330
+ </CometChatSwipeRow>
373
331
  );
374
332
  };
375
333
 
376
- useLayoutEffect(() => {
377
- let answerslist = [];
378
- for (let index = 0; index < defaultAnswers; index++) {
379
- answerslist.push({ id: index });
380
- }
381
- setAnswersList(answerslist);
334
+ function AddAnswer() {
335
+ return (
336
+ <TouchableOpacity
337
+ onPress={handleAddAnswerRow}
338
+ style={{
339
+ height: 56,
340
+ width: '100%',
341
+ justifyContent: 'center',
342
+ paddingHorizontal: 5,
343
+ }}
344
+ >
345
+ <Text
346
+ style={[
347
+ theme.typography.name,
348
+ {
349
+ color: theme.palette.getPrimary(),
350
+ },
351
+ ]}
352
+ >
353
+ {addAnswerText ?? localize('ADD_ANOTHER_ANSWER')}
354
+ </Text>
355
+ </TouchableOpacity>
356
+ );
357
+ };
358
+
359
+ useEffect(() => {
360
+ let answerslist = new Array(defaultAnswers).fill("");
361
+ setAnswers(answerslist);
362
+
382
363
  CometChat.getLoggedinUser()
383
364
  .then((u) => (loggedInUser.current = u))
384
365
  .catch((e) => { });
366
+
385
367
  if (Platform.OS === "ios") {
386
368
  if (Number.isInteger(commonVars.safeAreaInsets.top)) {
387
369
  setKbOffset(commonVars.safeAreaInsets.top)
@@ -395,18 +377,16 @@ export const CometChatCreatePoll = (props: CometChatCreatePollInterface) => {
395
377
  }
396
378
  })
397
379
  }
380
+
398
381
  }, []);
399
382
 
400
- const getPollAnswers = useCallback(() => {
383
+ function getPollAnswers() {
401
384
  return (
402
- answersList.map((item, index) => (
403
- <React.Fragment key={item.id}>
404
- <AnswersListItem item={item} index={index} />
405
- {index === answersList.length - 1 && <AddAnswer />}
406
- </React.Fragment>
385
+ answers.map((item: string, index: number) => (
386
+ AnswersListItem({ item, index })
407
387
  ))
408
388
  )
409
- }, [answersList])
389
+ };
410
390
 
411
391
  return (
412
392
  <KeyboardAvoidingView
@@ -479,7 +459,8 @@ export const CometChatCreatePoll = (props: CometChatCreatePollInterface) => {
479
459
  </View>
480
460
 
481
461
  {getPollAnswers()}
482
-
462
+ <AddAnswer />
463
+ <ErrorView />
483
464
  </ScrollView>
484
465
 
485
466
  {loader && <View style={{
@@ -490,10 +471,7 @@ export const CometChatCreatePoll = (props: CometChatCreatePollInterface) => {
490
471
  justifyContent: "center",
491
472
  alignItems: "center",
492
473
  }}>
493
- <ActivityIndicator
494
- size="large"
495
- color={theme.palette.getPrimary()}
496
- />
474
+ <ActivityIndicator size="large" />
497
475
  </View>}
498
476
  </KeyboardAvoidingView>
499
477
  );
@@ -1,38 +0,0 @@
1
- #import <Foundation/Foundation.h>
2
- #import <AVFoundation/AVFoundation.h>
3
- #import <SPTPersistentCache/SPTPersistentCache.h>
4
- #import <SPTPersistentCache/SPTPersistentCacheOptions.h>
5
- #import <CommonCrypto/CommonDigest.h>
6
-
7
- typedef NS_ENUM(NSUInteger, RCTVideoCacheStatus) {
8
- RCTVideoCacheStatusMissingFileExtension,
9
- RCTVideoCacheStatusUnsupportedFileExtension,
10
- RCTVideoCacheStatusNotAvailable,
11
- RCTVideoCacheStatusAvailable
12
- };
13
-
14
- @class SPTPersistentCache;
15
- @class SPTPersistentCacheOptions;
16
-
17
- @interface RCTVideoCache : NSObject
18
- {
19
- SPTPersistentCache *videoCache;
20
- NSString * _Nullable cachePath;
21
- NSString * temporaryCachePath;
22
- NSString * _Nullable cacheIdentifier;
23
- }
24
-
25
- @property(nonatomic, strong) SPTPersistentCache * _Nullable videoCache;
26
- @property(nonatomic, strong) NSString * cachePath;
27
- @property(nonatomic, strong) NSString * cacheIdentifier;
28
- @property(nonatomic, strong) NSString * temporaryCachePath;
29
-
30
- + (RCTVideoCache *)sharedInstance;
31
- - (void)storeItem:(NSData *)data forUri:(NSString *)uri withCallback:(void(^)(BOOL))handler;
32
- - (void)getItemForUri:(NSString *)url withCallback:(void(^)(RCTVideoCacheStatus, AVAsset * _Nullable)) handler;
33
- - (NSURL *)createUniqueTemporaryFileUrl:(NSString * _Nonnull)url withExtension:(NSString * _Nonnull) extension;
34
- - (AVURLAsset *)getItemFromTemporaryStorage:(NSString *)key;
35
- - (BOOL)saveDataToTemporaryStorage:(NSData *)data key:(NSString *)key;
36
- - (void) createTemporaryPath;
37
-
38
- @end
@@ -1,174 +0,0 @@
1
- #import "RCTVideoCache.h"
2
-
3
- @implementation RCTVideoCache
4
-
5
- @synthesize videoCache;
6
- @synthesize cachePath;
7
- @synthesize cacheIdentifier;
8
- @synthesize temporaryCachePath;
9
-
10
- + (RCTVideoCache *)sharedInstance {
11
- static RCTVideoCache *sharedInstance = nil;
12
- static dispatch_once_t onceToken;
13
- dispatch_once(&onceToken, ^{
14
- sharedInstance = [[self alloc] init];
15
- });
16
- return sharedInstance;
17
- }
18
-
19
- - (id)init {
20
- if (self = [super init]) {
21
- self.cacheIdentifier = @"rct.video.cache";
22
- self.temporaryCachePath = [NSTemporaryDirectory() stringByAppendingPathComponent:self.cacheIdentifier];
23
- self.cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:self.cacheIdentifier];
24
- SPTPersistentCacheOptions *options = [SPTPersistentCacheOptions new];
25
- options.cachePath = self.cachePath;
26
- options.cacheIdentifier = self.cacheIdentifier;
27
- options.defaultExpirationPeriod = 60 * 60 * 24 * 30;
28
- options.garbageCollectionInterval = (NSUInteger)(1.5 * SPTPersistentCacheDefaultGCIntervalSec);
29
- options.sizeConstraintBytes = 1024 * 1024 * 100;
30
- options.useDirectorySeparation = NO;
31
- #ifdef DEBUG
32
- options.debugOutput = ^(NSString *string) {
33
- NSLog(@"Video Cache: %@", string);
34
- };
35
- #endif
36
- [self createTemporaryPath];
37
- self.videoCache = [[SPTPersistentCache alloc] initWithOptions:options];
38
- [self.videoCache scheduleGarbageCollector];
39
- }
40
- return self;
41
- }
42
-
43
- - (void) createTemporaryPath {
44
- NSError *error = nil;
45
- BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:self.temporaryCachePath
46
- withIntermediateDirectories:YES
47
- attributes:nil
48
- error:&error];
49
- #ifdef DEBUG
50
- if (!success || error) {
51
- NSLog(@"Error while! %@", error);
52
- }
53
- #endif
54
- }
55
-
56
- - (void)storeItem:(NSData *)data forUri:(NSString *)uri withCallback:(void(^)(BOOL))handler;
57
- {
58
- NSString *key = [self generateCacheKeyForUri:uri];
59
- if (key == nil) {
60
- handler(NO);
61
- return;
62
- }
63
- [self saveDataToTemporaryStorage:data key:key];
64
- [self.videoCache storeData:data forKey:key locked:NO withCallback:^(SPTPersistentCacheResponse * _Nonnull response) {
65
- if (response.error) {
66
- #ifdef DEBUG
67
- NSLog(@"An error occured while saving the video into the cache: %@", [response.error localizedDescription]);
68
- #endif
69
- handler(NO);
70
- return;
71
- }
72
- handler(YES);
73
- } onQueue:dispatch_get_main_queue()];
74
- return;
75
- }
76
-
77
- - (AVURLAsset *)getItemFromTemporaryStorage:(NSString *)key {
78
- NSString * temporaryFilePath = [self.temporaryCachePath stringByAppendingPathComponent:key];
79
-
80
- BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:temporaryFilePath];
81
- if (!fileExists) {
82
- return nil;
83
- }
84
- NSURL *assetUrl = [[NSURL alloc] initFileURLWithPath:temporaryFilePath];
85
- AVURLAsset *asset = [AVURLAsset URLAssetWithURL:assetUrl options:nil];
86
- return asset;
87
- }
88
-
89
- - (BOOL)saveDataToTemporaryStorage:(NSData *)data key:(NSString *)key {
90
- NSString *temporaryFilePath = [self.temporaryCachePath stringByAppendingPathComponent:key];
91
- [data writeToFile:temporaryFilePath atomically:YES];
92
- return YES;
93
- }
94
-
95
- - (NSString *)generateCacheKeyForUri:(NSString *)uri {
96
- NSString *uriWithoutQueryParams = uri;
97
-
98
- // parse file extension
99
- if ([uri rangeOfString:@"?"].location != NSNotFound) {
100
- NSArray<NSString*> * components = [uri componentsSeparatedByString:@"?"];
101
- uriWithoutQueryParams = [components objectAtIndex:0];
102
- }
103
-
104
- NSString * pathExtension = [uriWithoutQueryParams pathExtension];
105
- NSArray * supportedExtensions = @[@"m4v", @"mp4", @"mov"];
106
- if ([pathExtension isEqualToString:@""]) {
107
- NSDictionary *userInfo = @{
108
- NSLocalizedDescriptionKey: NSLocalizedString(@"Missing file extension.", nil),
109
- NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"Missing file extension.", nil),
110
- NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Missing file extension.", nil)
111
- };
112
- NSError *error = [NSError errorWithDomain:@"RCTVideoCache"
113
- code:RCTVideoCacheStatusMissingFileExtension userInfo:userInfo];
114
- @throw error;
115
- } else if (![supportedExtensions containsObject:pathExtension]) {
116
- // Notably, we don't currently support m3u8 (HLS playlists)
117
- NSDictionary *userInfo = @{
118
- NSLocalizedDescriptionKey: NSLocalizedString(@"Unsupported file extension.", nil),
119
- NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"Unsupported file extension.", nil),
120
- NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Unsupported file extension.", nil)
121
- };
122
- NSError *error = [NSError errorWithDomain:@"RCTVideoCache"
123
- code:RCTVideoCacheStatusUnsupportedFileExtension userInfo:userInfo];
124
- @throw error;
125
- }
126
- return [[self generateHashForUrl:uri] stringByAppendingPathExtension:pathExtension];
127
- }
128
-
129
- - (void)getItemForUri:(NSString *)uri withCallback:(void(^)(RCTVideoCacheStatus, AVAsset * _Nullable)) handler {
130
- @try {
131
- NSString *key = [self generateCacheKeyForUri:uri];
132
- AVURLAsset * temporaryAsset = [self getItemFromTemporaryStorage:key];
133
- if (temporaryAsset != nil) {
134
- handler(RCTVideoCacheStatusAvailable, temporaryAsset);
135
- return;
136
- }
137
-
138
- [self.videoCache loadDataForKey:key withCallback:^(SPTPersistentCacheResponse * _Nonnull response) {
139
- if (response.record == nil || response.record.data == nil) {
140
- handler(RCTVideoCacheStatusNotAvailable, nil);
141
- return;
142
- }
143
- [self saveDataToTemporaryStorage:response.record.data key:key];
144
- handler(RCTVideoCacheStatusAvailable, [self getItemFromTemporaryStorage:key]);
145
- } onQueue:dispatch_get_main_queue()];
146
- } @catch (NSError * err) {
147
- switch (err.code) {
148
- case RCTVideoCacheStatusMissingFileExtension:
149
- handler(RCTVideoCacheStatusMissingFileExtension, nil);
150
- return;
151
- case RCTVideoCacheStatusUnsupportedFileExtension:
152
- handler(RCTVideoCacheStatusUnsupportedFileExtension, nil);
153
- return;
154
- default:
155
- @throw err;
156
- }
157
- }
158
- }
159
-
160
- - (NSString *)generateHashForUrl:(NSString *)string {
161
- const char *cStr = [string UTF8String];
162
- unsigned char result[CC_MD5_DIGEST_LENGTH];
163
- CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
164
-
165
- return [NSString stringWithFormat:
166
- @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
167
- result[0], result[1], result[2], result[3],
168
- result[4], result[5], result[6], result[7],
169
- result[8], result[9], result[10], result[11],
170
- result[12], result[13], result[14], result[15]
171
- ];
172
- }
173
-
174
- @end