diff --git a/package.json b/package.json index 0cd681b..7ae4084 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@cometchat/chat-uikit-react-native", - "version": "4.3.21", + "version": "4.3.22", "description": "Ready-to-use Chat UI Components for React Native", "main": "src/index", "module": "src/index", diff --git a/src/AI/AIConversationSummary/AIConversationSummaryView.tsx b/src/AI/AIConversationSummary/AIConversationSummaryView.tsx index a0b7bd4..633ab3c 100644 --- a/src/AI/AIConversationSummary/AIConversationSummaryView.tsx +++ b/src/AI/AIConversationSummary/AIConversationSummaryView.tsx @@ -1,4 +1,3 @@ - import React, { useContext, useEffect, useState } from 'react'; import { View } from 'react-native'; import { CometChatContext, CometChatTheme, localize } from '../../shared'; @@ -6,186 +5,191 @@ import { AIConversationSummaryConfiguration } from './configuration'; import { CometChatPanel } from '../../shared/views/CometChatPanel/CometChatPanel'; import CometChatAICard from '../../shared/views/CometChatAICard/CometChatAICard'; //@ts-ignore -import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChat } from '@cometchat/chat-sdk-react-native'; interface IAIConversationSummaryProps { - getConversationSummaryCallback?: (theme?: CometChatTheme) => Promise - editReplyCallback?: (reply: string) => void - configuration?: AIConversationSummaryConfiguration - theme?: CometChatTheme, - onPanelClose: () => void -}; - -const defaultProps: IAIConversationSummaryProps = { - getConversationSummaryCallback: undefined, - editReplyCallback: undefined, - configuration: undefined, - theme: new CometChatTheme({}), - onPanelClose: () => { } + getConversationSummaryCallback?: (theme?: CometChatTheme) => Promise; + editReplyCallback?: (reply: string) => void; + configuration?: AIConversationSummaryConfiguration; + theme?: CometChatTheme; + onPanelClose: () => void; } const enum States { - loading = "loading", - error = "error", - empty = "empty", - loaded = "loaded" + loading = 'loading', + error = 'error', + empty = 'empty', + loaded = 'loaded', } let inProgress = false; const AIConversationSummaryView = (props: IAIConversationSummaryProps) => { - - const [messageListState, setMessageListState] = useState(States.loading); - const [activeView, setActiveView] = useState(null); - - const { theme } = useContext(CometChatContext) - - const errorStateText: string = localize("SOMETHING_WRONG"); - const emptyStateText: string = localize("NO_MESSAGES_FOUND"); - const loadingStateText: string = localize("GENERATING_SUMMARY"); - const titleText: string = localize("CONVERSATION_SUMMARY") - - useEffect(() => { - fetchButtonContent(); - }, []); - - function fetchButtonContent() { - setMessageListState(States.loading); - if (props && props.getConversationSummaryCallback) { - props.getConversationSummaryCallback(theme) - .then((response) => { - if (response) { - inProgress = true; - getLoadedView(response) - .then(res => { - setMessageListState(States.loaded); - setActiveView(res); - }) - .catch(err => { - inProgress = false; - setMessageListState(States.empty); - }) - } else { - inProgress = false; - setMessageListState(States.empty); - } - }) - .catch((err) => { - inProgress = false; - setMessageListState(States.error); - }) - } - } - - /** - * Create a view based on the value of the `state` prop. - */ - function getStateView(): JSX.Element | null { - let res: JSX.Element | null = null; - switch (messageListState) { - case States.loading: - res = getLoadingView(); - break; - case States.error: - res = getErrorView(); - break; - case States.empty: - res = getEmptyView(); - break; - case States.loaded: - break; - default: - const x: never = messageListState; - } - return res; - } - - /** - * Creates the loading view - */ - function getLoadingView(): JSX.Element { - let LoadingView = props.configuration?.LoadingStateView; - return ( - - - {LoadingView ? : null} - - ); + const { + getConversationSummaryCallback = undefined, + editReplyCallback = undefined, + configuration = undefined, + theme = useContext(CometChatContext)?.theme || new CometChatTheme({}), + onPanelClose = () => {}, + } = props; + + const [messageListState, setMessageListState] = useState( + States.loading + ); + const [activeView, setActiveView] = useState(null); + + const errorStateText: string = localize('SOMETHING_WRONG'); + const emptyStateText: string = localize('NO_MESSAGES_FOUND'); + const loadingStateText: string = localize('GENERATING_SUMMARY'); + const titleText: string = localize('CONVERSATION_SUMMARY'); + + useEffect(() => { + fetchButtonContent(); + }, []); + + function fetchButtonContent() { + setMessageListState(States.loading); + if (getConversationSummaryCallback) { + getConversationSummaryCallback(theme) + .then((response) => { + if (response) { + inProgress = true; + getLoadedView(response) + .then((res) => { + setMessageListState(States.loaded); + setActiveView(res); + }) + .catch((err) => { + inProgress = false; + setMessageListState(States.empty); + }); + } else { + inProgress = false; + setMessageListState(States.empty); + } + }) + .catch((err) => { + inProgress = false; + setMessageListState(States.error); + }); } - - /** - * Creates the error view - */ - function getErrorView(): JSX.Element | null { - let ErrorView = props.configuration?.ErrorStateView; - return ( - - {ErrorView ? : null} - - ); + } + + /** + * Create a view based on the value of the `state` prop. + */ + function getStateView(): JSX.Element | null { + let res: JSX.Element | null = null; + switch (messageListState) { + case States.loading: + res = getLoadingView(); + break; + case States.error: + res = getErrorView(); + break; + case States.empty: + res = getEmptyView(); + break; + case States.loaded: + break; + default: + const x: never = messageListState; } + return res; + } + + /** + * Creates the loading view + */ + function getLoadingView(): JSX.Element { + let LoadingView = configuration?.LoadingStateView; + return ( + + {LoadingView ? : null} + + ); + } - /** - * Creates the empty view - */ - function getEmptyView(): JSX.Element { - let EmptyView = props.configuration?.EmptyStateView; - return ( - - {EmptyView ? : null} - - ); - } - - /** - * Creates the loaded view - */ - async function getLoadedView(conversationSummary: string): Promise { - return new Promise((resolve, reject) => { - try { - let CustomView = props.configuration?.customView; - - if (CustomView) { - props.configuration?.customView!(conversationSummary, props.onPanelClose).then((res: any) => { - return resolve(res); - }) - .catch((err: CometChat.CometChatException) => { - return reject(err) - }) - } else { - let conversationSummaryView = - return resolve(conversationSummaryView); - } - } catch (e) { - reject(e); - } - }) - } + /** + * Creates the error view + */ + function getErrorView(): JSX.Element | null { + let ErrorView = configuration?.ErrorStateView; + return ( + + {ErrorView ? : null} + + ); + } + /** + * Creates the empty view + */ + function getEmptyView(): JSX.Element { + let EmptyView = configuration?.EmptyStateView; return ( - - {messageListState === States.loaded ? activeView : getStateView()} - + + {EmptyView ? : null} + ); + } + + /** + * Creates the loaded view + */ + async function getLoadedView( + conversationSummary: string + ): Promise { + return new Promise((resolve, reject) => { + try { + let CustomView = configuration?.customView; + + if (CustomView) { + configuration?.customView!( + conversationSummary, + onPanelClose + ) + .then((res: any) => { + return resolve(res); + }) + .catch((err: CometChat.CometChatException) => { + return reject(err); + }); + } else { + let conversationSummaryView = ( + + ); + return resolve(conversationSummaryView); + } + } catch (e) { + reject(e); + } + }); + } + + return ( + + {messageListState === States.loaded ? activeView : getStateView()} + + ); }; -AIConversationSummaryView.defaultProps = defaultProps export default AIConversationSummaryView; diff --git a/src/AI/CardView.tsx b/src/AI/CardView.tsx index af26e61..d438192 100644 --- a/src/AI/CardView.tsx +++ b/src/AI/CardView.tsx @@ -1,8 +1,12 @@ -import { useState } from 'react'; -import { contentContainerStyle, getButtonStyles, getPopoverStyle } from './style'; +import { useState } from 'react'; +import { + contentContainerStyle, + getButtonStyles, + getPopoverStyle, +} from './style'; import { CardViewStyle } from './CardViewStyle'; import { CometChatTheme } from '../shared'; -import { TouchableOpacity,Text,ScrollView, TextStyle } from 'react-native'; +import { TouchableOpacity, Text, ScrollView, TextStyle } from 'react-native'; import React from 'react'; import { View } from 'react-native'; import { AIButtonsStyle } from './utils'; @@ -10,72 +14,70 @@ export type Card = { title?: string; id?: string; onClick?: (id: string) => void; - style?:AIButtonsStyle; + style?: AIButtonsStyle; }; -interface CardProps { +interface CardProps { buttons?: Card[]; - backCallback?:(callback:()=>void) => void; - cardViewStyle?:CardViewStyle; -}; - -const defaultProps:CardProps = { - buttons: undefined, - backCallback:undefined, - cardViewStyle:undefined + backCallback?: (callback: () => void) => void; + cardViewStyle?: CardViewStyle; } - -export const CardView = (props:CardProps) => { +export const CardView = ( + { + buttons= undefined, + backCallback= undefined, + cardViewStyle= undefined, + }: CardProps +) => { const [currentSection, setCurrentSection] = useState(null); -function fetchButtonContent(button:Card){ - - - setCurrentSection(button?.id!) - if(button && button.onClick){ - button.onClick(button.id!) + function fetchButtonContent(button: Card) { + setCurrentSection(button?.id!); + if (button && button.onClick) { + button.onClick(button.id!); + } } -} - - -function getButtons():JSX.Element | null{ - return ( - - {props.buttons?.map(item => ( - fetchButtonContent(item)} - + function getButtons(): JSX.Element | null { + return ( + - {item.title} - - - ))} - ) - -} + {buttons?.map((item) => ( + fetchButtonContent(item)} + > + + {item.title} + + + ))} + + ); + } return ( - - + - {!currentSection && props.buttons && ( - - - { getButtons()} + {!currentSection && buttons && ( + + {getButtons()} - - )} - ); }; -CardView.defaultProps = defaultProps -export default CardView; \ No newline at end of file +export default CardView; diff --git a/src/CometChatCreateGroup/CometChatCreateGroup.tsx b/src/CometChatCreateGroup/CometChatCreateGroup.tsx index 1fe6004..cd44c5a 100644 --- a/src/CometChatCreateGroup/CometChatCreateGroup.tsx +++ b/src/CometChatCreateGroup/CometChatCreateGroup.tsx @@ -117,13 +117,13 @@ export const CometChatCreateGroup = (props: CometChatCreateGroupInterface) => { title = localize("NEW_GROUP"), closeIcon, createIcon, - passwordPlaceholderText, - namePlaceholderText, + namePlaceholderText= localize('NAME'), + passwordPlaceholderText= localize('ENTER_YOUR_PASSWORD'), + createGroupStyle= {}, disableCloseButton, onCreatePress, onError, onBack, - createGroupStyle, } = props; const [password, setPassword] = useState(''); const [groupType, setGroupType] = React.useState(GroupTypeConstants.public); @@ -160,7 +160,7 @@ export const CometChatCreateGroup = (props: CometChatCreateGroupInterface) => { ...(createGroupStyle?.tabTextStyle && createGroupStyle?.tabTextStyle), }, - ] as TextStyle} + ] as TextStyle[]} > {name} @@ -259,7 +259,7 @@ export const CometChatCreateGroup = (props: CometChatCreateGroupInterface) => { styles.errorTextTitle, theme.typography.body, { color: theme.palette.getError() }, - ] as TextStyle} + ] as TextStyle[]} > {error?.length > 0 ? error : localize('ERROR_GROUP_CREATE')} @@ -268,7 +268,7 @@ export const CometChatCreateGroup = (props: CometChatCreateGroupInterface) => { styles.errorText, theme.typography.body, { color: theme.palette.getError() }, - ] as TextStyle} + ] as TextStyle[]} > {localize('TRY_AGAIN_LATER')} @@ -354,7 +354,7 @@ export const CometChatCreateGroup = (props: CometChatCreateGroupInterface) => { groupName?.length > 0 ? createGroupStyle?.namePlaceholderTextStyle : createGroupStyle?.nameInputTextStyle, - ] as TextStyle} + ] as TextStyle[]} /> {groupType === GroupTypeConstants.password && ( { password?.length > 0 ? createGroupStyle?.passwordPlaceholderTextStyle : createGroupStyle?.passwordInputTextStyle, - ] as TextStyle} + ] as TextStyle[]} /> )} @@ -380,8 +380,3 @@ export const CometChatCreateGroup = (props: CometChatCreateGroupInterface) => { ); }; -CometChatCreateGroup.defaultProps = { - namePlaceholderText: localize('NAME'), - passwordPlaceholderText: localize('ENTER_YOUR_PASSWORD'), - createGroupStyle: {}, -}; diff --git a/src/CometChatGroups/CometChatGroups.tsx b/src/CometChatGroups/CometChatGroups.tsx index 73ada7d..d8361a4 100644 --- a/src/CometChatGroups/CometChatGroups.tsx +++ b/src/CometChatGroups/CometChatGroups.tsx @@ -1,199 +1,209 @@ //@ts-ignore -import React, { useState, useRef } from "react"; +import React, { useState, useRef } from 'react'; //@ts-ignore -import { Text, TextStyle, View, ViewProps } from "react-native"; +import { Text, TextStyle, View, ViewProps } from 'react-native'; import { - backIcon, - passwordGroupIcon, privateGroupIcon, - checkIcon, -} from "./resources"; + backIcon, + passwordGroupIcon as passwordGroupIconDefault, + privateGroupIcon as privateGroupIconDefault, + checkIcon, +} from './resources'; //@ts-ignore -import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { GroupsStyle, GroupsStyleInterface } from "./GroupsStyle"; -import { Style } from "./style"; -import { CometChatContext, CometChatListActionsInterface, ListItemStyleInterface, localize } from "../shared"; -import { BorderStyle, ImageType } from "../shared"; -import { GroupTypeConstants, PASSWORD_GROUP_COLOR, PRIVATE_GROUP_COLOR } from "../shared/constants/UIKitConstants"; -import { CometChatListItem, ListItemStyle } from "../shared"; -import { AvatarStyle, StatusIndicatorStyle } from "../shared"; -import { CometChatList } from "../shared"; -import { CometChatContextType, SelectionMode } from "../shared/base/Types"; -import { CometChatOptions } from "../shared/modals/CometChatOptions"; -import { AvatarStyleInterface } from "../shared/views/CometChatAvatar/AvatarStyle"; -import { StatusIndicatorStyleInterface } from "../shared/views/CometChatStatusIndicator/StatusIndicatorStyle"; -import { CometChatUIEventHandler } from "../shared/events/CometChatUIEventHandler/CometChatUIEventHandler"; - -const uiEventListener = "uiEvents_" + new Date().getTime(); +import { CometChat } from '@cometchat/chat-sdk-react-native'; +import { GroupsStyle, GroupsStyleInterface } from './GroupsStyle'; +import { Style } from './style'; +import { + CometChatContext, + CometChatListActionsInterface, + ListItemStyleInterface, + localize, +} from '../shared'; +import { BorderStyle, ImageType } from '../shared'; +import { + GroupTypeConstants, + PASSWORD_GROUP_COLOR, + PRIVATE_GROUP_COLOR, +} from '../shared/constants/UIKitConstants'; +import { CometChatListItem, ListItemStyle } from '../shared'; +import { AvatarStyle, StatusIndicatorStyle } from '../shared'; +import { CometChatList } from '../shared'; +import { CometChatContextType, SelectionMode } from '../shared/base/Types'; +import { CometChatOptions } from '../shared/modals/CometChatOptions'; +import { AvatarStyleInterface } from '../shared/views/CometChatAvatar/AvatarStyle'; +import { StatusIndicatorStyleInterface } from '../shared/views/CometChatStatusIndicator/StatusIndicatorStyle'; +import { CometChatUIEventHandler } from '../shared/events/CometChatUIEventHandler/CometChatUIEventHandler'; + +const uiEventListener = 'uiEvents_' + new Date().getTime(); export interface CometChatGroupsInterface { - /** - * Custom subtitle view - */ - SubtitleView?: (item: CometChat.Group) => JSX.Element, - /** - * Custom list item view - */ - ListItemView?: (item: CometChat.Group) => JSX.Element, - /** - * pass compoent for menu, will be shown at top right side - */ - AppBarOption?: () => JSX.Element, - /** - * Pass array of CometChatOptions type - * Tobe shown on swipe of list item - */ - options?: (item: CometChat.Group) => CometChatOptions[], - /** - * toggle the seperator - */ - hideSeperator?: boolean, - /** - * hide selection icon - */ - hideSubmitIcon?: boolean, - /** - * styles for groups - */ - groupsStyle?: GroupsStyleInterface, - /** - * styles for list item - */ - listItemStyle?: ListItemStyleInterface, - /** - * styles for avatar - */ - avatarStyle?: AvatarStyleInterface, - /** - * styles for status indicator - */ - statusIndicatorStyle?: StatusIndicatorStyleInterface, - /** - * search placeholder text - */ - searchPlaceHolderText?: string, - /** - * back button icon - */ - backButtonIcon?: ImageType, - /** - * toggle back button - */ - showBackButton?: boolean, - /** - * select items pass "none" | "single" | "multitple" - */ - selectionMode?: SelectionMode, - /** - * call back on seleciton is done - */ - onSelection?: (items: Array) => void, - /** - * icon for search box - */ - searchBoxIcon?: ImageType, - /** - * toggle seearch box - */ - hideSearch?: boolean, - /** - * title to be shown default "Groups" - */ - title?: string, - /** - * Custom Functional component for empty state - */ - EmptyStateView?: () => JSX.Element, - /** - * text to be shown in case no groups found. - */ - emptyStateText?: string, - /** - * Custom functional component for error state. - */ - ErrorStateView?: () => JSX.Element, - /** - * text to be shown in case error occured while fetching gounps for first time - */ - errorStateText?: string, - /** - * Custom image for loading state. - */ - LoadingStateView?: () => JSX.Element, - /** - * Request builder to fetch groups. - */ - groupsRequestBuilder?: CometChat.GroupsRequestBuilder, - /** - * request builder for search - */ - searchRequestBuilder?: CometChat.GroupsRequestBuilder, - /** - * pass icon for private group - */ - privateGroupIcon?: ImageType, - /** - * pass icon for password group - */ - passwordGroupIcon?: ImageType, - /** - * toogle error visibility - */ - hideError?: boolean, - /** - * function tobe called on group pressed. - */ - onItemPress?: (item: CometChat.Group) => void, - /** - * function tobe called on group long pressed. - */ - onItemLongPress?: (item: CometChat.Group) => void, - /** - * function will be called when error occured. - */ - onError?: (e: CometChat.CometChatException) => void, - /** - * function will be called when back button pressed. - */ - onBack?: () => void, + /** + * Custom subtitle view + */ + SubtitleView?: (item: CometChat.Group) => JSX.Element; + /** + * Custom list item view + */ + ListItemView?: (item: CometChat.Group) => JSX.Element; + /** + * pass compoent for menu, will be shown at top right side + */ + AppBarOption?: () => JSX.Element; + /** + * Pass array of CometChatOptions type + * Tobe shown on swipe of list item + */ + options?: (item: CometChat.Group) => CometChatOptions[]; + /** + * toggle the seperator + */ + hideSeperator?: boolean; + /** + * hide selection icon + */ + hideSubmitIcon?: boolean; + /** + * styles for groups + */ + groupsStyle?: GroupsStyleInterface; + /** + * styles for list item + */ + listItemStyle?: ListItemStyleInterface; + /** + * styles for avatar + */ + avatarStyle?: AvatarStyleInterface; + /** + * styles for status indicator + */ + statusIndicatorStyle?: StatusIndicatorStyleInterface; + /** + * search placeholder text + */ + searchPlaceHolderText?: string; + /** + * back button icon + */ + backButtonIcon?: ImageType; + /** + * toggle back button + */ + showBackButton?: boolean; + /** + * select items pass "none" | "single" | "multitple" + */ + selectionMode?: SelectionMode; + /** + * call back on seleciton is done + */ + onSelection?: (items: Array) => void; + /** + * icon for search box + */ + searchBoxIcon?: ImageType; + /** + * toggle seearch box + */ + hideSearch?: boolean; + /** + * title to be shown default "Groups" + */ + title?: string; + /** + * Custom Functional component for empty state + */ + EmptyStateView?: () => JSX.Element; + /** + * text to be shown in case no groups found. + */ + emptyStateText?: string; + /** + * Custom functional component for error state. + */ + ErrorStateView?: () => JSX.Element; + /** + * text to be shown in case error occured while fetching gounps for first time + */ + errorStateText?: string; + /** + * Custom image for loading state. + */ + LoadingStateView?: () => JSX.Element; + /** + * Request builder to fetch groups. + */ + groupsRequestBuilder?: CometChat.GroupsRequestBuilder; + /** + * request builder for search + */ + searchRequestBuilder?: CometChat.GroupsRequestBuilder; + /** + * pass icon for private group + */ + privateGroupIcon?: ImageType; + /** + * pass icon for password group + */ + passwordGroupIcon?: ImageType; + /** + * toogle error visibility + */ + hideError?: boolean; + /** + * function tobe called on group pressed. + */ + onItemPress?: (item: CometChat.Group) => void; + /** + * function tobe called on group long pressed. + */ + onItemLongPress?: (item: CometChat.Group) => void; + /** + * function will be called when error occured. + */ + onError?: (e: CometChat.CometChatException) => void; + /** + * function will be called when back button pressed. + */ + onBack?: () => void; } -const groupListenerId = "grouplist_" + new Date().getTime(); - -export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface, ref: any) => { +const groupListenerId = 'grouplist_' + new Date().getTime(); +export const CometChatGroups = React.forwardRef( + (props: CometChatGroupsInterface, ref: any) => { const { - SubtitleView, - ListItemView, - AppBarOption, - options, - hideSeperator, - hideSubmitIcon, - groupsStyle, - listItemStyle, - avatarStyle, - statusIndicatorStyle, - searchPlaceHolderText, - backButtonIcon, - showBackButton, - selectionMode, - onSelection, - searchBoxIcon, - hideSearch, - title, - EmptyStateView, - emptyStateText, - ErrorStateView, - errorStateText, - LoadingStateView, - groupsRequestBuilder, - searchRequestBuilder, - privateGroupIcon, - passwordGroupIcon, - hideError, - onItemPress, - onItemLongPress, - onError, - onBack, + SubtitleView, + ListItemView, + AppBarOption, + options, + hideSubmitIcon, + groupsStyle, + listItemStyle, + avatarStyle, + statusIndicatorStyle, + onSelection, + searchBoxIcon, + EmptyStateView, + emptyStateText, + ErrorStateView, + errorStateText, + LoadingStateView, + groupsRequestBuilder, + searchRequestBuilder, + onItemPress, + onItemLongPress, + onError, + onBack, + title = localize('GROUPS'), + searchPlaceHolderText = localize('SEARCH'), + showBackButton = false, + hideSearch = false, + hideSeperator = false, + backButtonIcon = backIcon, + selectionMode = 'none', + privateGroupIcon = privateGroupIconDefault, + passwordGroupIcon = passwordGroupIconDefault, + hideError = false, } = props; //context values @@ -202,45 +212,49 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface const groupListRef = useRef(null); const activeSwipeRows = React.useRef({}); - const [selecting, setSelecting] = useState(selectionMode != 'none' ? true : false); + const [selecting, setSelecting] = useState( + selectionMode != 'none' ? true : false + ); const [selectedGroups, setSelectedGroups] = useState([]); const _groupsStyle = new GroupsStyle({ - backgroundColor: theme?.palette.getBackgroundColor(), - backIconTint: theme?.palette.getPrimary(), - emptyTextColor: theme?.palette.getAccent400(), - emptyTextFont: theme?.typography.caption2, - errorTextColor: theme?.palette.getError(), - errorTextFont: theme?.typography.subtitle1, - searchBackgroundColor: theme?.palette.getAccent600(), - searchBorder: new BorderStyle({ - borderColor: theme?.palette.getAccent700(), - ...groupsStyle?.border, - }), - separatorColor: theme?.palette.getAccent100(), - subtitleTextColor: theme?.palette.getAccent600(), - subtitleTextFont: theme?.typography.text1, - titleColor: theme?.palette.getAccent(), - titleFont: theme?.typography.title1, - loadingIconTint: theme?.palette.getPrimary(), - ...groupsStyle + backgroundColor: theme?.palette.getBackgroundColor(), + backIconTint: theme?.palette.getPrimary(), + emptyTextColor: theme?.palette.getAccent400(), + emptyTextFont: theme?.typography.caption2, + errorTextColor: theme?.palette.getError(), + errorTextFont: theme?.typography.subtitle1, + searchBackgroundColor: theme?.palette.getAccent600(), + searchBorder: new BorderStyle({ + borderColor: theme?.palette.getAccent700(), + ...groupsStyle?.border, + }), + separatorColor: theme?.palette.getAccent100(), + subtitleTextColor: theme?.palette.getAccent600(), + subtitleTextFont: theme?.typography.text1, + titleColor: theme?.palette.getAccent(), + titleFont: theme?.typography.title1, + loadingIconTint: theme?.palette.getPrimary(), + ...groupsStyle, }); const _avatarStyle = new AvatarStyle({ - backgroundColor: theme?.palette.getAccent600(), - nameTextColor: theme?.palette.getSecondary(), - nameTextFont: theme?.typography.title1, - ...avatarStyle + backgroundColor: theme?.palette.getAccent600(), + nameTextColor: theme?.palette.getSecondary(), + nameTextFont: theme?.typography.title1, + ...avatarStyle, }); - const _statusIndicatorStyle = new StatusIndicatorStyle(statusIndicatorStyle || { + const _statusIndicatorStyle = new StatusIndicatorStyle( + statusIndicatorStyle || { borderRadius: 10, height: 15, width: 15, - }); + } + ); const _listItemStyle = new ListItemStyle({ - backgroundColor: theme?.palette?.getBackgroundColor(), - titleColor: theme?.palette.getAccent(), - titleFont: theme?.typography.name, - ...listItemStyle + backgroundColor: theme?.palette?.getBackgroundColor(), + titleColor: theme?.palette.getAccent(), + titleFont: theme?.typography.name, + ...listItemStyle, }); // const listStyle = new CometChatListStyles({ @@ -250,51 +264,63 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface // }) React.useImperativeHandle(ref, () => ({ - addGroup: addGroup, - updateGroup: updateGroup, - removeGroup: removeGroup, - getSelectedItems + addGroup: addGroup, + updateGroup: updateGroup, + removeGroup: removeGroup, + getSelectedItems, })); const getSelectedItems = () => { - return selectedGroups; - } + return selectedGroups; + }; const ErrorView = () => { - if (hideError) return null; - - if (ErrorStateView) - return ; - else - return ( - - - {errorStateText || localize("SOMETHING_WRONG")} - - - ); - } + if (hideError) return null; + + if (ErrorStateView) return ; + else + return ( + + + {errorStateText || localize('SOMETHING_WRONG')} + + + ); + }; const EmptyView = () => { - if (EmptyStateView) - return ; - else - return ( - - - {emptyStateText || localize("NO_GROUPS_FOUND")} - - - ) - } + if (EmptyStateView) return ; + else + return ( + + + {emptyStateText || localize('NO_GROUPS_FOUND')} + + + ); + }; /** * * Listener callback when a member is kicked from / has left the group */ const handleGroupMemberRemoval = (...options: any[]) => { - const group = options[3]; - groupListRef.current?.updateList(group); + const group = options[3]; + groupListRef.current?.updateList(group); }; /** @@ -302,8 +328,8 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface * Listener callback when a member is banned from the group */ const handleGroupMemberBan = (...options: any[]) => { - const group = options[3]; - groupListRef.current?.updateList(group); + const group = options[3]; + groupListRef.current?.updateList(group); }; /** @@ -311,8 +337,8 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface * Listener callback when a user joins/added to the group */ const handleGroupMemberAddition = (...options: any[]) => { - const group = options[3]; - groupListRef.current?.updateList(group); + const group = options[3]; + groupListRef.current?.updateList(group); }; /** @@ -320,303 +346,308 @@ export const CometChatGroups = React.forwardRef((props: CometChatGroupsInterface * Listener callback when a group member scope is updated */ const handleGroupMemberScopeChange = (...options: any[]) => { - const group = options[4]; - groupListRef.current?.updateList(group); + const group = options[4]; + groupListRef.current?.updateList(group); }; /** - * This will update group in the list if not found then + * This will update group in the list if not found then * @param {object} group Group object */ const updateGroup = (group: any) => { - groupListRef.current?.updateList((grp: any) => grp["guid"] == group["guid"]); - } + groupListRef.current?.updateList( + (grp: any) => grp['guid'] == group['guid'] + ); + }; /** * Add the group to the group list at first position. * @param {object} group group object */ const addGroup = (group: any) => { - groupListRef.current?.addItemToList((grp: any) => grp["guid"] == group["guid"], 0); - } + groupListRef.current?.addItemToList( + (grp: any) => grp['guid'] == group['guid'], + 0 + ); + }; /** * removes the group from the list. * @param {object} group Group object */ const removeGroup = (group: any) => { - groupListRef.current?.removeItemFromList(group["guid"]) - //remove from selected items if present - if (selecting) { - let index: any = selectedGroups.find(grp => grp['guid'] == group['guid']) - if (index > -1) { - let selectedItems = [...selectedGroups]; - selectedItems.splice(index, 1); - setSelectedGroups(selectedItems); - } + groupListRef.current?.removeItemFromList(group['guid']); + //remove from selected items if present + if (selecting) { + let index: any = selectedGroups.find( + (grp) => grp['guid'] == group['guid'] + ); + if (index > -1) { + let selectedItems = [...selectedGroups]; + selectedItems.splice(index, 1); + setSelectedGroups(selectedItems); } - } + } + }; const groupClicked = (group: any) => { - if (selecting) { - if (selectionMode == "single") { - if (selectedGroups.length > 0 && selectedGroups[0].guid == group.guid) - setSelectedGroups([]); - else - setSelectedGroups([group]); - return; - } - const index: number = selectedGroups.findIndex((value) => value.guid == group.guid) - if (index >= 0) { - let tmp = [...selectedGroups] - tmp.splice(index, 1); - setSelectedGroups([...tmp]); - } else { - setSelectedGroups([...selectedGroups, group]); - } - return; + if (selecting) { + if (selectionMode == 'single') { + if (selectedGroups.length > 0 && selectedGroups[0].guid == group.guid) + setSelectedGroups([]); + else setSelectedGroups([group]); + return; } - onItemPress && onItemPress(group) - } + const index: number = selectedGroups.findIndex( + (value) => value.guid == group.guid + ); + if (index >= 0) { + let tmp = [...selectedGroups]; + tmp.splice(index, 1); + setSelectedGroups([...tmp]); + } else { + setSelectedGroups([...selectedGroups, group]); + } + return; + } + onItemPress && onItemPress(group); + }; const groupLongPressed = (group: any) => { - if (selectionMode != "none") { - setSelecting(true); - if (selectionMode === "multiple") - setSelectedGroups([...selectedGroups, group]); - else - setSelectedGroups([group]); - } - onItemLongPress && onItemLongPress(group); - } + if (selectionMode != 'none') { + setSelecting(true); + if (selectionMode === 'multiple') + setSelectedGroups([...selectedGroups, group]); + else setSelectedGroups([group]); + } + onItemLongPress && onItemLongPress(group); + }; React.useEffect(() => { - CometChat.addGroupListener( - groupListenerId, - new CometChat.GroupListener({ - onGroupMemberScopeChanged: ( - message: any, - changedUser: any, - newScope: any, - oldScope: any, - changedGroup: any - ) => { - handleGroupMemberScopeChange( - message, - changedUser, - newScope, - oldScope, - changedGroup - ); - }, - onGroupMemberKicked: (message: any, kickedUser: any, kickedBy: any, kickedFrom: any) => { - handleGroupMemberRemoval( - message, - kickedUser, - kickedBy, - kickedFrom - ); - }, - onGroupMemberLeft: (message: any, leavingUser: any, group: any) => { - handleGroupMemberRemoval(message, leavingUser, null, group); - }, - onGroupMemberBanned: (message: any, bannedUser: any, bannedBy: any, bannedFrom: any) => { - handleGroupMemberBan( - message, - bannedUser, - bannedBy, - bannedFrom - ); - }, - onMemberAddedToGroup: ( - message: any, - userAdded: any, - userAddedBy: any, - userAddedIn: any - ) => { - handleGroupMemberAddition( - message, - userAdded, - userAddedBy, - userAddedIn - ); - }, - onGroupMemberJoined: (message: any, joinedUser: any, joinedGroup: any) => { - handleGroupMemberAddition( - message, - joinedUser, - null, - joinedGroup - ); - }, - }) - ); - CometChatUIEventHandler.addGroupListener( - uiEventListener, - { - ccGroupCreated: ({ group }: any) => { - groupListRef.current?.addItemToList(group, 0); - }, - ccGroupDeleted: ({ group }: any) => { - groupListRef.current?.removeItemFromList(group.guid); - }, - ccGroupLeft: ({ leftGroup }: any) => { - leftGroup['hasJoined'] = false; - leftGroup['membersCount'] = leftGroup['membersCount'] - 1; - console.log(leftGroup); - if (leftGroup['type'] == CometChat.GROUP_TYPE.PRIVATE) { - groupListRef.current?.removeItemFromList(leftGroup.getGuid()); - } else { - groupListRef.current?.updateList(leftGroup); - } - }, - ccGroupMemberKicked: ({ group }: any) => { - if (group['type'] == CometChat.GROUP_TYPE.PRIVATE) { - groupListRef.current?.removeItemFromList(group.getGuid()); - } else { - group.setHasJoined(false); - groupListRef.current?.updateList(group); - } - }, - ccOwnershipChanged: ({ group }: any) => { - groupListRef.current?.updateList(group); - }, - ccGroupMemberAdded: ({ userAddedIn }: { userAddedIn: CometChat.Group }) => { - groupListRef.current?.updateList(userAddedIn); - }, - ccGroupMemberJoined: ({ joinedGroup }: { joinedGroup: CometChat.Group }) => { - joinedGroup['membersCount'] = joinedGroup['membersCount'] + 1; - joinedGroup['scope'] = "participant"; - joinedGroup['hasJoined'] = true; - groupListRef.current?.updateList(joinedGroup); - } - } - ) - return () => { - CometChat.removeGroupListener(groupListenerId); - CometChatUIEventHandler.removeGroupListener(uiEventListener); - } + CometChat.addGroupListener( + groupListenerId, + new CometChat.GroupListener({ + onGroupMemberScopeChanged: ( + message: any, + changedUser: any, + newScope: any, + oldScope: any, + changedGroup: any + ) => { + handleGroupMemberScopeChange( + message, + changedUser, + newScope, + oldScope, + changedGroup + ); + }, + onGroupMemberKicked: ( + message: any, + kickedUser: any, + kickedBy: any, + kickedFrom: any + ) => { + handleGroupMemberRemoval(message, kickedUser, kickedBy, kickedFrom); + }, + onGroupMemberLeft: (message: any, leavingUser: any, group: any) => { + handleGroupMemberRemoval(message, leavingUser, null, group); + }, + onGroupMemberBanned: ( + message: any, + bannedUser: any, + bannedBy: any, + bannedFrom: any + ) => { + handleGroupMemberBan(message, bannedUser, bannedBy, bannedFrom); + }, + onMemberAddedToGroup: ( + message: any, + userAdded: any, + userAddedBy: any, + userAddedIn: any + ) => { + handleGroupMemberAddition( + message, + userAdded, + userAddedBy, + userAddedIn + ); + }, + onGroupMemberJoined: ( + message: any, + joinedUser: any, + joinedGroup: any + ) => { + handleGroupMemberAddition(message, joinedUser, null, joinedGroup); + }, + }) + ); + CometChatUIEventHandler.addGroupListener(uiEventListener, { + ccGroupCreated: ({ group }: any) => { + groupListRef.current?.addItemToList(group, 0); + }, + ccGroupDeleted: ({ group }: any) => { + groupListRef.current?.removeItemFromList(group.guid); + }, + ccGroupLeft: ({ leftGroup }: any) => { + leftGroup['hasJoined'] = false; + leftGroup['membersCount'] = leftGroup['membersCount'] - 1; + console.log(leftGroup); + if (leftGroup['type'] == CometChat.GROUP_TYPE.PRIVATE) { + groupListRef.current?.removeItemFromList(leftGroup.getGuid()); + } else { + groupListRef.current?.updateList(leftGroup); + } + }, + ccGroupMemberKicked: ({ group }: any) => { + if (group['type'] == CometChat.GROUP_TYPE.PRIVATE) { + groupListRef.current?.removeItemFromList(group.getGuid()); + } else { + group.setHasJoined(false); + groupListRef.current?.updateList(group); + } + }, + ccOwnershipChanged: ({ group }: any) => { + groupListRef.current?.updateList(group); + }, + ccGroupMemberAdded: ({ + userAddedIn, + }: { + userAddedIn: CometChat.Group; + }) => { + groupListRef.current?.updateList(userAddedIn); + }, + ccGroupMemberJoined: ({ + joinedGroup, + }: { + joinedGroup: CometChat.Group; + }) => { + joinedGroup['membersCount'] = joinedGroup['membersCount'] + 1; + joinedGroup['scope'] = 'participant'; + joinedGroup['hasJoined'] = true; + groupListRef.current?.updateList(joinedGroup); + }, + }); + return () => { + CometChat.removeGroupListener(groupListenerId); + CometChatUIEventHandler.removeGroupListener(uiEventListener); + }; }, []); const GroupItemView = ({ item }: any) => { - //custom view check - if (ListItemView) - return ListItemView(item); - - const { type, name, icon, membersCount } = item; - let image: ImageType | undefined, backgroundColor: string = "transparent"; - if (type == GroupTypeConstants.password) { - image = passwordGroupIcon || passwordGroupIcon; - backgroundColor = PASSWORD_GROUP_COLOR; - } - if (type == GroupTypeConstants.private) { - image = privateGroupIcon || privateGroupIcon; - backgroundColor = PRIVATE_GROUP_COLOR; - } - if (selecting) { - let index: number = selectedGroups.findIndex((value) => value.guid == item.guid); - if (index >= 0) { - image = checkIcon; - backgroundColor = theme?.palette?.getBackgroundColor(); - } + //custom view check + if (ListItemView) return ListItemView(item); + + const { type, name, icon, membersCount } = item; + let image: ImageType | undefined, + backgroundColor: string = 'transparent'; + if (type == GroupTypeConstants.password) { + image = passwordGroupIcon || passwordGroupIcon; + backgroundColor = PASSWORD_GROUP_COLOR; + } + if (type == GroupTypeConstants.private) { + image = privateGroupIcon || privateGroupIcon; + backgroundColor = PRIVATE_GROUP_COLOR; + } + if (selecting) { + let index: number = selectedGroups.findIndex( + (value) => value.guid == item.guid + ); + if (index >= 0) { + image = checkIcon; + backgroundColor = theme?.palette?.getBackgroundColor(); } - - return SubtitleView && SubtitleView(item) || {membersCount} {localize("MEMBERS")}} - title={name} - statusIndicatorIcon={image} - statusIndicatorColor={backgroundColor} - listItemStyle={_listItemStyle} - avatarStyle={_avatarStyle} - statusIndicatorStyle={_statusIndicatorStyle as ViewProps} - onPress={groupClicked.bind(this, item)} - onLongPress={groupLongPressed.bind(this, item)} - options={() => options && options(item) || []} - activeSwipeRows={activeSwipeRows.current} - rowOpens={(id) => { - Object.keys(activeSwipeRows.current).forEach(key => { - if (id !== key && activeSwipeRows.current[key]) { - activeSwipeRows.current[key]?.current?.closeRow?.() - delete activeSwipeRows.current[key] - } - }) - }} + } + + return ( + + (SubtitleView && SubtitleView(item)) || ( + + {membersCount} {localize('MEMBERS')} + + ) + } + title={name} + statusIndicatorIcon={image} + statusIndicatorColor={backgroundColor} + listItemStyle={_listItemStyle} + avatarStyle={_avatarStyle} + statusIndicatorStyle={_statusIndicatorStyle as ViewProps} + onPress={groupClicked.bind(this, item)} + onLongPress={groupLongPressed.bind(this, item)} + options={() => (options && options(item)) || []} + activeSwipeRows={activeSwipeRows.current} + rowOpens={(id) => { + Object.keys(activeSwipeRows.current).forEach((key) => { + if (id !== key && activeSwipeRows.current[key]) { + activeSwipeRows.current[key]?.current?.closeRow?.(); + delete activeSwipeRows.current[key]; + } + }); + }} /> + ); }; const onSelectionClicked = () => { - if(!selectedGroups.length) return - onSelection && onSelection(selectedGroups); + if (!selectedGroups.length) return; + onSelection && onSelection(selectedGroups); - setSelecting(false); - setSelectedGroups([]); - } + setSelecting(false); + setSelectedGroups([]); + }; return ( - - 0 || selecting ? selectionMode : "none"} - onSelection={onSelectionClicked} - searchBoxIcon={searchBoxIcon} - hideSearch={hideSearch} - hideSubmitIcon={hideSubmitIcon} - onError={onError} - onBack={onBack} - listStyle={{ ..._groupsStyle, background: _groupsStyle.backgroundColor }} - statusIndicatorStyle={_statusIndicatorStyle} - avatarStyle={_avatarStyle} - listItemStyle={_listItemStyle} - /> - - ) -}); - -CometChatGroups.defaultProps = { - title: localize("GROUPS"), - searchPlaceHolderText: localize("SEARCH"), - showBackButton: false, - searchBoxIcon: undefined, - hideSearch: false, - listItemStyle: undefined, - avatarStyle: undefined, - statusIndicatorStyle: undefined, - SubtitleView: undefined, - ListItemView: undefined, - AppBarOption: undefined, - options: undefined, - hideSeperator: false, - backButtonIcon: backIcon, - selectionMode: "none", - onSelection: undefined, - EmptyStateView: undefined, - emptyStateText: undefined, - LoadingStateView: undefined, - groupsRequestBuilder: undefined, - privateGroupIcon: privateGroupIcon, - passwordGroupIcon: passwordGroupIcon, - hideError: false, - onItemPress: undefined, - onItemLongPress: undefined, - onError: undefined, - onBack: undefined, -} \ No newline at end of file + + 0 || selecting ? selectionMode : 'none' + } + onSelection={onSelectionClicked} + searchBoxIcon={searchBoxIcon} + hideSearch={hideSearch} + hideSubmitIcon={hideSubmitIcon} + onError={onError} + onBack={onBack} + listStyle={{ + ..._groupsStyle, + background: _groupsStyle.backgroundColor, + }} + statusIndicatorStyle={_statusIndicatorStyle} + avatarStyle={_avatarStyle} + listItemStyle={_listItemStyle} + /> + + ); + } +); diff --git a/src/CometChatJoinProtectedGroup/CometChatJoinProtectedGroup.tsx b/src/CometChatJoinProtectedGroup/CometChatJoinProtectedGroup.tsx index d4f083e..175ef21 100644 --- a/src/CometChatJoinProtectedGroup/CometChatJoinProtectedGroup.tsx +++ b/src/CometChatJoinProtectedGroup/CometChatJoinProtectedGroup.tsx @@ -126,19 +126,20 @@ export const CometChatJoinProtectedGroup = ( ) => { const { theme } = useContext(CometChatContext); const { - group, title = localize("PROTECTED_GROUP"), joinIcon, closeIcon, passwordPlaceholderText = localize("GROUP_PASSWORD"), description, onJoinClick, - hasError, errorText, onError, onBack, - joinProtectedGroupStyle, + hasError= true, + joinProtectedGroupStyle= {}, + group= undefined } = props; + const [password, setPassword] = useState(''); const [modalVisible, setModalVisible] = useState(false); const [errorMessage, setErrorMessage] = useState(''); @@ -238,7 +239,7 @@ export const CometChatJoinProtectedGroup = ( joinProtectedGroupStyle?.descriptionTextStyle ?? theme.typography.subtitle1, { color: theme.palette.getAccent() }, - ] as TextStyle} + ] as TextStyle[]} > {description ?? `Enter password to access ${group?.['name']} Group.`} @@ -265,7 +266,3 @@ export const CometChatJoinProtectedGroup = ( ); }; -CometChatJoinProtectedGroup.defaultProps = { - hasError: true, - joinProtectedGroupStyle: {}, -}; diff --git a/src/CometChatMessageComposer/CometChatMessageComposer.tsx b/src/CometChatMessageComposer/CometChatMessageComposer.tsx index 1b7eec8..ce2c096 100644 --- a/src/CometChatMessageComposer/CometChatMessageComposer.tsx +++ b/src/CometChatMessageComposer/CometChatMessageComposer.tsx @@ -63,7 +63,10 @@ import { MessageEvents } from '../shared/events'; import { CometChatContextType } from '../shared/base/Types'; import { CometChatUIEventHandler } from '../shared/events/CometChatUIEventHandler/CometChatUIEventHandler'; import { CometChatMessageComposerActionInterface } from '../shared/helper/types'; -import { CometChatMediaRecorder, MediaRecorderStyle } from '../shared/views/CometChatMediaRecorder'; +import { + CometChatMediaRecorder, + MediaRecorderStyle, +} from '../shared/views/CometChatMediaRecorder'; import { AIOptionsStyle } from '../AI/AIOptionsStyle'; import { CommonUtils } from '../shared/utils/CommonUtils'; import { permissionUtil } from '../shared/utils/PermissionUtil'; @@ -74,10 +77,12 @@ const uiEventListenerShow = 'uiEvent_show_' + new Date().getTime(); const uiEventListenerHide = 'uiEvent_hide_' + new Date().getTime(); const MessagePreviewTray = (props: any) => { - const { shouldShow = false, text = '', onClose = () => { } } = props; + const { shouldShow = false, text = '', onClose = () => {} } = props; return shouldShow ? ( { const ImageButton = (props: any) => { const { image, onClick, buttonStyle, imageStyle, disable } = props; return ( - { } : onClick} style={buttonStyle}> + {} : onClick} + style={buttonStyle} + > ); }; const AttachIconButton = (props: any) => { - const { icon, show = false, onClick = () => { }, style, theme } = props; + const { icon, show = false, onClick = () => {}, style, theme } = props; if (show) { return ( { const EmojiBoard = (props: any) => { const { shouldShow = false, - onClose = () => { }, - emojiSelection = (emoji?: any) => { }, + onClose = () => {}, + emojiSelection = (emoji?: any) => {}, ...otherProps } = props; return shouldShow ? ( @@ -127,7 +136,7 @@ const EmojiBoard = (props: any) => { const ActionSheetBoard = (props: any) => { const { shouldShow = false, - onClose = () => { }, + onClose = () => {}, options = [], cometChatBottomSheetStyle = {}, sheetRef, @@ -151,15 +160,15 @@ const ActionSheetBoard = (props: any) => { const RecordAudio = (props: any) => { const { shouldShow = false, - onClose = () => { }, + onClose = () => {}, options = [], cometChatBottomSheetStyle = {}, sheetRef, - onPause = () => { }, - onPlay = () => { }, - onSend = (recordedFile: String) => { }, - onStop = (recordedFile: String) => { }, - onStart = () => { }, + onPause = () => {}, + onPlay = () => {}, + onSend = (recordedFile: String) => {}, + onStop = (recordedFile: String) => {}, + onStart = () => {}, mediaRecorderStyle, pauseIconUrl, playIconUrl, @@ -192,14 +201,17 @@ const RecordAudio = (props: any) => { /> ) : null; -} +}; const AIOptions = (props: any) => { const { aiStyle, shouldShow = false, - onClose = () => { }, - cometChatBottomSheetStyle = { backgroundColor: aiStyle.backgroundColor, paddingHorizontal: 0 }, + onClose = () => {}, + cometChatBottomSheetStyle = { + backgroundColor: aiStyle.backgroundColor, + paddingHorizontal: 0, + }, sheetRef, aiOptions, ...otherProps @@ -211,7 +223,6 @@ const AIOptions = (props: any) => { onClose={onClose} style={cometChatBottomSheetStyle} > - { /> ) : null; -} +}; const LiveReaction = (props: any) => { const { show = false, reaction } = props; @@ -231,7 +242,8 @@ const LiveReaction = (props: any) => { return null; }; -let recordedTime = 0, timerIntervalId = null; +let recordedTime = 0, + timerIntervalId = null; export interface MessageComposerStyleInterface extends BaseStyle { attachIconTint?: string; @@ -251,11 +263,17 @@ export interface MessageComposerStyleInterface extends BaseStyle { actionSheetLayoutModeIconTint?: string; actionSheetCancelButtonIconTint?: string; } -type Enumerate = Acc['length'] extends N +type Enumerate< + N extends number, + Acc extends number[] = [] +> = Acc['length'] extends N ? Acc[number] - : Enumerate + : Enumerate; -type IntRange = Exclude, Enumerate> +type IntRange = Exclude< + Enumerate, + Enumerate +>; export interface CometChatMessageComposerInterface { /** @@ -520,28 +538,30 @@ export interface CometChatMessageComposerInterface { */ onError?: (error: any) => void; /** - * AI Icon URL. - */ + * AI Icon URL. + */ AIIconURL?: string; /** * AI Options Style. */ aiOptionsStyle?: AIOptionsStyle; /** - * To override keyboardAvoidingViewProps. - */ - keyboardAvoidingViewProps?: KeyboardAvoidingViewProps + * To override keyboardAvoidingViewProps. + */ + keyboardAvoidingViewProps?: KeyboardAvoidingViewProps; /** * Collection of text formatter class * @type {Array} - */ - textFormatters?: Array; + */ + textFormatters?: Array< + CometChatMentionsFormatter | CometChatUrlsFormatter | CometChatTextFormatter + >; disableMentions?: boolean; /* * To manually manage image quality taken from the camera (100 means no compression). * @default 20 */ - imageQuality?: IntRange<1, 100> + imageQuality?: IntRange<1, 100>; } export const CometChatMessageComposer = React.forwardRef( (props: CometChatMessageComposerInterface, ref) => { @@ -553,7 +573,6 @@ export const CometChatMessageComposer = React.forwardRef( id, user, group, - disableSoundForMessages, customSoundForMessage, disableTypingEvents, text, @@ -562,16 +581,12 @@ export const CometChatMessageComposer = React.forwardRef( FooterView, onChangeText, maxHeight, - attachmentIcon, attachmentOptions, SecondaryButtonView, AuxiliaryButtonView, auxiliaryButtonsAlignment, SendButtonView, parentMessageId, - hideLiveReaction, - liveReactionIcon, - messageComposerStyle, onSendButtonPress, onError, hideVoiceRecording, @@ -588,7 +603,13 @@ export const CometChatMessageComposer = React.forwardRef( keyboardAvoidingViewProps, textFormatters, disableMentions, - imageQuality = 20 + imageQuality = 20, + + attachmentIcon = ICONS.ADD, + liveReactionIcon = ICONS.HEART, + hideLiveReaction = true, + disableSoundForMessages = true, + messageComposerStyle = {}, } = props; const defaultAttachmentOptions = @@ -609,15 +630,19 @@ export const CometChatMessageComposer = React.forwardRef( const messageInputRef = React.useRef(null); const chatRef = React.useRef(chatWith); const inputValueRef = React.useRef(null); - const plainTextInput = React.useRef(text ?? ""); + const plainTextInput = React.useRef(text ?? ''); let mentionMap = React.useRef>(new Map()); - let trackingCharacters = React.useRef([]) - let allFormatters = React.useRef>(new Map()); - let activeCharacter = React.useRef("") - let searchStringRef = React.useRef(""); + let trackingCharacters = React.useRef([]); + let allFormatters = React.useRef< + Map + >(new Map()); + let activeCharacter = React.useRef(''); + let searchStringRef = React.useRef(''); const [selectionPosition, setSelectionPosition] = React.useState({}); - const [inputMessage, setInputMessage] = React.useState(text || ''); + const [inputMessage, setInputMessage] = React.useState< + string | JSX.Element + >(text || ''); const [showReaction, setShowReaction] = React.useState(false); const [showEmojiboard, setShowEmojiboard] = React.useState(false); const [showActionSheet, setShowActionSheet] = React.useState(false); @@ -633,13 +658,16 @@ export const CometChatMessageComposer = React.forwardRef( const [isVisible, setIsVisible] = React.useState(false); const [kbOffset, setKbOffset] = React.useState(59); const [showMentionList, setShowMentionList] = React.useState(false); - const [mentionsSearchData, setMentionsSearchData] = React.useState>([]); - const [suggestionListLoader, setSuggestionListLoader] = React.useState(false); + const [mentionsSearchData, setMentionsSearchData] = React.useState< + Array + >([]); + const [suggestionListLoader, setSuggestionListLoader] = + React.useState(false); const bottomSheetRef = React.useRef(null); useLayoutEffect(() => { - if (Platform.OS === "ios") { + if (Platform.OS === 'ios') { if (Number.isInteger(commonVars.safeAreaInsets.top)) { setKbOffset(commonVars.safeAreaInsets.top as number); return; @@ -648,9 +676,9 @@ export const CometChatMessageComposer = React.forwardRef( if (Number.isInteger(res.top)) { commonVars.safeAreaInsets.top = res.top; commonVars.safeAreaInsets.bottom = res.bottom; - setKbOffset(res.top) + setKbOffset(res.top); } - }) + }); } }, []); @@ -664,7 +692,7 @@ export const CometChatMessageComposer = React.forwardRef( optionsSeparatorTint: theme.palette.getAccent200(), borderRadius: 0, ...aiOptionsStyle, - }) + }); let isTyping = useRef(null); @@ -677,7 +705,6 @@ export const CometChatMessageComposer = React.forwardRef( const previewMessage = ({ message, status }: any) => { if (status === messageStatus.inprogress) { - let textComponents = message?.text; let rawText = message?.text; @@ -685,20 +712,24 @@ export const CometChatMessageComposer = React.forwardRef( let users: any = {}; let regexes: Array = []; - allFormatters.current.forEach((formatter: CometChatTextFormatter, key) => { - formatter.handleComposerPreview(message); - if (!regexes.includes(formatter.getRegexPattern())) { - regexes.push(formatter.getRegexPattern()); + allFormatters.current.forEach( + (formatter: CometChatTextFormatter, key) => { + formatter.handleComposerPreview(message); + if (!regexes.includes(formatter.getRegexPattern())) { + regexes.push(formatter.getRegexPattern()); + } + let suggestionUsers = formatter.getSuggestionItems(); + suggestionUsers.forEach( + (item) => (users[item.underlyingText] = item) + ); + let resp = formatter.getFormattedText(textComponents); + textComponents = resp; } - let suggestionUsers = formatter.getSuggestionItems(); - suggestionUsers.forEach(item => users[item.underlyingText] = item); - let resp = formatter.getFormattedText(textComponents); - textComponents = resp; - }) + ); let edits: any[] = []; - regexes.forEach(regex => { + regexes.forEach((regex) => { let match; while ((match = regex.exec(rawText)) !== null) { const user = users[match[0]]; @@ -707,7 +738,7 @@ export const CometChatMessageComposer = React.forwardRef( startIndex: match.index, endIndex: regex.lastIndex, replacement: user.promptText, - user + user, }); } } @@ -716,16 +747,21 @@ export const CometChatMessageComposer = React.forwardRef( // Sort edits by startIndex to apply them in order edits.sort((a, b) => a.startIndex - b.startIndex); - plainTextInput.current = getPlainString(message?.text, edits) + plainTextInput.current = getPlainString(message?.text, edits); const hashMap = new Map(); let offset = 0; // Tracks shift in position due to replacements - edits.forEach(edit => { + edits.forEach((edit) => { const adjustedStartIndex = edit.startIndex + offset; - rawText = rawText.substring(0, adjustedStartIndex) + edit.replacement + rawText.substring(edit.endIndex); + rawText = + rawText.substring(0, adjustedStartIndex) + + edit.replacement + + rawText.substring(edit.endIndex); offset += edit.replacement.length - (edit.endIndex - edit.startIndex); - const rangeKey = `${adjustedStartIndex}_${adjustedStartIndex + edit.replacement.length}`; + const rangeKey = `${adjustedStartIndex}_${ + adjustedStartIndex + edit.replacement.length + }`; hashMap.set(rangeKey, edit.user); }); @@ -758,32 +794,27 @@ export const CometChatMessageComposer = React.forwardRef( MessageTypeConstants.image, chatWith.current ); - } + }; const fileInputHandler = async (fileType: string) => { if (fileType === MessageTypeConstants.takePhoto) { - if (!(await permissionUtil.startResourceBasedTask(["camera"]))) { + if (!(await permissionUtil.startResourceBasedTask(['camera']))) { return; } - let quality = imageQuality + let quality = imageQuality; if (isNaN(imageQuality) || imageQuality < 1 || imageQuality > 100) { - quality = 20 + quality = 20; } - if (Platform.OS === "android") { - FileManager.openCamera( - fileType, - Math.round(quality), - cameraCallback - ); + if (Platform.OS === 'android') { + FileManager.openCamera(fileType, Math.round(quality), cameraCallback); } else { - FileManager.openCamera( - fileType, - cameraCallback - ); + FileManager.openCamera(fileType, cameraCallback); } - } - else if (Platform.OS === 'ios' && fileType === MessageTypeConstants.video) { - NativeModules.VideoPickerModule.pickVideo(((file: any) => { + } else if ( + Platform.OS === 'ios' && + fileType === MessageTypeConstants.video + ) { + NativeModules.VideoPickerModule.pickVideo((file: any) => { if (file.uri) sendMediaMessage( chatWithId.current, @@ -791,9 +822,8 @@ export const CometChatMessageComposer = React.forwardRef( MessageTypeConstants.video, chatWith.current ); - })) - } - else + }); + } else FileManager.openFileChooser(fileType, async (fileInfo: any) => { if (CheckPropertyExists(fileInfo, 'error')) { return; @@ -862,7 +892,6 @@ export const CometChatMessageComposer = React.forwardRef( }; const sendTextMessage = () => { - //ignore sending new message if (messagePreview != null) { editMessage(messagePreview.message); @@ -881,14 +910,15 @@ export const CometChatMessageComposer = React.forwardRef( textMessage.setReceiver(chatWith.current); textMessage.setText(finalTextInput); textMessage.setMuid(String(getUnixTimestampInMilliseconds())); - parentMessageId && textMessage.setParentMessageId(parentMessageId as number); + parentMessageId && + textMessage.setParentMessageId(parentMessageId as number); - allFormatters.current.forEach(item => { + allFormatters.current.forEach((item) => { textMessage = item.handlePreMessageSend(textMessage); - }) + }); setMentionsSearchData([]); - plainTextInput.current = "" + plainTextInput.current = ''; if (finalTextInput.trim().length == 0) { return; @@ -920,7 +950,7 @@ export const CometChatMessageComposer = React.forwardRef( }) .catch((error: any) => { onError && onError(error); - textMessage.data.metaData = { error: true } + textMessage.data.metaData = { error: true }; CometChatUIEventHandler.emitMessageEvent( MessageEvents.ccMessageSent, { @@ -945,7 +975,8 @@ export const CometChatMessageComposer = React.forwardRef( chatWith.current ); textMessage.setId(message.id); - parentMessageId && textMessage.setParentMessageId(parentMessageId as number); + parentMessageId && + textMessage.setParentMessageId(parentMessageId as number); inputValueRef.current = ''; setInputMessage(''); @@ -1004,7 +1035,8 @@ export const CometChatMessageComposer = React.forwardRef( url: messageInput['uri'], sender: loggedInUser.current, }); - parentMessageId && mediaMessage.setParentMessageId(parentMessageId as number); + parentMessageId && + mediaMessage.setParentMessageId(parentMessageId as number); let localMessage: any = new CometChat.MediaMessage( receiverId, @@ -1025,7 +1057,8 @@ export const CometChatMessageComposer = React.forwardRef( url: messageInput['uri'], sender: loggedInUser.current, }); - parentMessageId && localMessage.setParentMessageId(parentMessageId as number); + parentMessageId && + localMessage.setParentMessageId(parentMessageId as number); localMessage.setData({ type: messageType, category: CometChat.CATEGORY_MESSAGE, @@ -1044,19 +1077,19 @@ export const CometChatMessageComposer = React.forwardRef( if (!disableSoundForMessages) playAudio(); CometChat.sendMediaMessage(mediaMessage) .then((message: any) => { - CometChatUIEventHandler.emitMessageEvent( - MessageEvents.ccMessageSent, - { - message: message, - status: messageStatus.success, - } - ); - setShowRecordAudio(false); + CometChatUIEventHandler.emitMessageEvent( + MessageEvents.ccMessageSent, + { + message: message, + status: messageStatus.success, + } + ); + setShowRecordAudio(false); }) .catch((error: any) => { setShowRecordAudio(false); onError && onError(error); - localMessage.data.metaData = { error: true } + localMessage.data.metaData = { error: true }; CometChatUIEventHandler.emitMessageEvent( MessageEvents.ccMessageSent, { @@ -1074,14 +1107,13 @@ export const CometChatMessageComposer = React.forwardRef( return false; } - //if typing is in progress, clear the previous timeout and set new timeout if (isTyping.current) { clearTimeout(isTyping.current); isTyping.current = null; } else { let metadata = typingMetadata || undefined; - + let typingNotification = new CometChat.TypingIndicator( chatWithId.current, chatWith.current, @@ -1090,7 +1122,6 @@ export const CometChatMessageComposer = React.forwardRef( CometChat.startTyping(typingNotification); } - let typingInterval = endTypingTimeout || 500; isTyping.current = setTimeout(() => { endTyping(null, typingMetadata); @@ -1133,7 +1164,7 @@ export const CometChatMessageComposer = React.forwardRef( const shouldShowAIOptions = () => { return !parentMessageId && AIOptionItems.length > 0; - } + }; const AuxiliaryButtonViewElem = () => { if (AuxiliaryButtonView && id) @@ -1141,11 +1172,13 @@ export const CometChatMessageComposer = React.forwardRef( ); else if (defaultAuxiliaryButtonOptions) - return - {defaultAuxiliaryButtonOptions} - {shouldShowAIOptions() && } - {!hideVoiceRecording && } - ; + return ( + + {defaultAuxiliaryButtonOptions} + {shouldShowAIOptions() && } + {!hideVoiceRecording && } + + ); return hideVoiceRecording ? null : ; }; @@ -1159,12 +1192,14 @@ export const CometChatMessageComposer = React.forwardRef( imageStyle={[ Style.imageStyle, { - tintColor: ((inputMessage as String).length === 0) ? theme.palette.getAccent400() : - messageComposerStyle?.sendIconTint || - theme.palette.getPrimary(), + tintColor: + (inputMessage as String).length === 0 + ? theme.palette.getAccent400() + : messageComposerStyle?.sendIconTint || + theme.palette.getPrimary(), }, ]} - disable={((inputMessage as String).length === 0)} + disable={(inputMessage as String).length === 0} onClick={sendTextMessage} /> ); @@ -1192,7 +1227,7 @@ export const CometChatMessageComposer = React.forwardRef( ); }; const PrimaryButtonView = () => { - return ((inputMessage as String).length !== 0) || hideLiveReaction ? ( + return (inputMessage as String).length !== 0 || hideLiveReaction ? ( ) : ( @@ -1209,50 +1244,62 @@ export const CometChatMessageComposer = React.forwardRef( }; const RecordAudioButtonView = () => { - return setShowRecordAudio(true)} - /> - } + return ( + setShowRecordAudio(true)} + /> + ); + }; const AIOptionsButtonView = () => { - return { - setShowAIOptions(true) - setAIOptionItems(rootAIOptionItems) - }} - /> - } + return ( + { + setShowAIOptions(true); + setAIOptionItems(rootAIOptionItems); + }} + /> + ); + }; //fetch logged in user useEffect(() => { - CometChat.getLoggedinUser().then((user: any) => (loggedInUser.current = user)); + CometChat.getLoggedinUser().then( + (user: any) => (loggedInUser.current = user) + ); let _formatter = [...(textFormatters ?? [])]; if (!disableMentions) { - let mentionsFormatter = ChatConfigurator.getDataSource().getMentionsFormatter(); - CometChatUIKit.loggedInUser && mentionsFormatter.setLoggedInUser(CometChatUIKit.loggedInUser); - mentionsFormatter.setMentionsStyle(new MentionTextStyle({ - loggedInUserTextStyle: { - color: theme.palette.getPrimary(), - ...theme.typography.title2, - fontSize: 17 - } as TextStyle, - textStyle: { - color: theme.palette.getPrimary(), - ...theme.typography.subtitle1, - fontSize: 17 - } as TextStyle - })); + let mentionsFormatter = + ChatConfigurator.getDataSource().getMentionsFormatter(); + CometChatUIKit.loggedInUser && + mentionsFormatter.setLoggedInUser(CometChatUIKit.loggedInUser); + mentionsFormatter.setMentionsStyle( + new MentionTextStyle({ + loggedInUserTextStyle: { + color: theme.palette.getPrimary(), + ...theme.typography.title2, + fontSize: 17, + } as TextStyle, + textStyle: { + color: theme.palette.getPrimary(), + ...theme.typography.subtitle1, + fontSize: 17, + } as TextStyle, + }) + ); user && mentionsFormatter.setUser(user); group && mentionsFormatter.setGroup(group); - _formatter.unshift(mentionsFormatter) + _formatter.unshift(mentionsFormatter); } _formatter.forEach((formatter) => { @@ -1264,7 +1311,7 @@ export const CometChatMessageComposer = React.forwardRef( let newFormatter = CommonUtils.clone(formatter); allFormatters.current.set(trackingCharacter, newFormatter); - }) + }); }, []); useEffect(() => { @@ -1300,6 +1347,7 @@ export const CometChatMessageComposer = React.forwardRef( } ); bottomSheetRef.current?.togglePanel(); + setShowActionSheet(false); setTimeout(() => { setCustomView(() => view); setIsVisible(true); @@ -1308,72 +1356,87 @@ export const CometChatMessageComposer = React.forwardRef( useEffect(() => { const defaultAttachmentOptions = - ChatConfigurator.dataSource.getAttachmentOptions(user, group, composerIdMap); + ChatConfigurator.dataSource.getAttachmentOptions( + user, + group, + composerIdMap + ); setActionSheetItems(() => attachmentOptions && typeof attachmentOptions === 'function' - ? attachmentOptions({ user, group, composerId: composerIdMap })?.map((item) => { - if (typeof item.CustomView === 'function') - return { - ...item, - onPress: () => handleOnClick(item.CustomView), - }; - if (typeof item.onPress == 'function') - return { - ...item, - onPress: () => { - setShowActionSheet(false); - item.onPress?.(user, group) - } - , - }; - return { - ...item, - onPress: () => fileInputHandler(item.id), - }; - }) + ? attachmentOptions({ user, group, composerId: composerIdMap })?.map( + (item) => { + if (typeof item.CustomView === 'function') + return { + ...item, + onPress: () => handleOnClick(item.CustomView), + }; + if (typeof item.onPress == 'function') + return { + ...item, + onPress: () => { + setShowActionSheet(false); + item.onPress?.(user, group); + }, + }; + return { + ...item, + onPress: () => fileInputHandler(item.id), + }; + } + ) : defaultAttachmentOptions.map((item: any) => { - if (typeof item.CustomView === 'function') + if (typeof item.CustomView === 'function') + return { + ...item, + onPress: () => handleOnClick(item.CustomView), + }; + if (typeof item.onPress === 'function') + return { + ...item, + onPress: () => item.onPress(user, group), + }; return { ...item, - onPress: () => handleOnClick(item.CustomView), + onPress: () => fileInputHandler(item.id), }; - if (typeof item.onPress === 'function') - return { - ...item, - onPress: () => item.onPress(user, group), - }; - return { - ...item, - onPress: () => fileInputHandler(item.id), - }; - }) + }) ); - const aiOptions = ChatConfigurator.dataSource.getAIOptions(user as CometChat.User, group as CometChat.Group, theme, composerIdMap, AIStyles); + const aiOptions = ChatConfigurator.dataSource.getAIOptions( + user as CometChat.User, + group as CometChat.Group, + theme, + composerIdMap, + AIStyles + ); let newAiOptions: any = _getAIOptions(aiOptions); setAIOptionItems(newAiOptions); setRootAIOptionItems(newAiOptions); }, [user, group, id, parentMessageId]); - const _getAIOptions = (options: (CometChatMessageOption | CometChatMessageComposerActionInterface)[]) => { + const _getAIOptions = ( + options: ( + | CometChatMessageOption + | CometChatMessageComposerActionInterface + )[] + ) => { let newOptions = [...options]; let newAiOptions = newOptions.map((item: any) => { if (typeof item.onPress === 'function') return { ...item, onPress: () => { - setShowAIOptions(false) - item?.onPress?.(user) + setShowAIOptions(false); + item?.onPress?.(user); }, }; return { ...item, - onPress: () => { }, + onPress: () => {}, }; - }) + }); return newAiOptions; - - } + }; useEffect(() => { CometChatUIEventHandler.addMessageListener(editMessageListenerID, { @@ -1382,9 +1445,9 @@ export const CometChatMessageComposer = React.forwardRef( CometChatUIEventHandler.addUIListener(UiEventListenerID, { ccToggleBottomSheet: (item) => { if (item?.bots) { - let newAiOptions: any = _getAIOptions(item.bots) + let newAiOptions: any = _getAIOptions(item.bots); setAIOptionItems(newAiOptions); - setShowAIOptions(true) + setShowAIOptions(true); return; } else if (item?.botView) { setCustomView(() => item.child); @@ -1399,20 +1462,22 @@ export const CometChatMessageComposer = React.forwardRef( inputValueRef.current = text?.text; plainTextInput.current = text?.text; - setInputMessage(text?.text) - + setInputMessage(text?.text); }, - ccSuggestionData(item: { id: string | number, data: Array }) { + ccSuggestionData(item: { + id: string | number; + data: Array; + }) { if (activeCharacter.current && id === item?.id) { setMentionsSearchData(item?.data); setSuggestionListLoader(false); } }, - }) + }); return () => { CometChatUIEventHandler.removeMessageListener(editMessageListenerID); CometChatUIEventHandler.removeUIListener(UiEventListenerID); - } + }; }, []); const handlePannel = (item: any) => { @@ -1444,21 +1509,24 @@ export const CometChatMessageComposer = React.forwardRef( const _sendRecordedAudio = (recordedFile: String) => { let fileObj = { - "name": "audio-recording" + recordedFile.split("/audio-recording")[1], - "type": "audio/mp4", - "uri": recordedFile - } - console.log("fileObj", fileObj); + name: 'audio-recording' + recordedFile.split('/audio-recording')[1], + type: 'audio/mp4', + uri: recordedFile, + }; + console.log('fileObj', fileObj); sendMediaMessage( chatWithId.current, fileObj, MessageTypeConstants.audio, chatWith.current ); - console.log("Send Audio"); - } + console.log('Send Audio'); + }; - function isCursorWithinMentionRange(mentionRanges: any, cursorPosition: number) { + function isCursorWithinMentionRange( + mentionRanges: any, + cursorPosition: number + ) { for (let [range, mention] of mentionRanges) { const [start, end] = range.split('_').map(Number); if (cursorPosition >= start && cursorPosition <= end) { @@ -1468,27 +1536,45 @@ export const CometChatMessageComposer = React.forwardRef( return false; // No mention found at the cursor position } - function shouldOpenList(selection: { - start: number; - end: number; - }, searchString: string, tracker: string) { - return (selection.start === selection.end - && !isCursorWithinMentionRange(mentionMap.current, selection.start - searchString.length) - && trackingCharacters.current.includes(tracker) - && (searchString === "" ? ((plainTextInput.current[selection.start - 2]?.length === 1 && plainTextInput.current[selection.start - 2]?.trim()?.length === 0) || plainTextInput.current[selection.start - 2] === undefined) : true) - && ((plainTextInput.current[selection.start - 1]?.length === 1 && plainTextInput.current[selection.start - 1]?.trim()?.length === 0) ? searchString.length > 0 : true) - ) + function shouldOpenList( + selection: { + start: number; + end: number; + }, + searchString: string, + tracker: string + ) { + return ( + selection.start === selection.end && + !isCursorWithinMentionRange( + mentionMap.current, + selection.start - searchString.length + ) && + trackingCharacters.current.includes(tracker) && + (searchString === '' + ? (plainTextInput.current[selection.start - 2]?.length === 1 && + plainTextInput.current[selection.start - 2]?.trim()?.length === + 0) || + plainTextInput.current[selection.start - 2] === undefined + : true) && + (plainTextInput.current[selection.start - 1]?.length === 1 && + plainTextInput.current[selection.start - 1]?.trim()?.length === 0 + ? searchString.length > 0 + : true) + ); } let timeoutId: any; - const openList = (selection: { - start: number; - end: number; - }) => { + const openList = (selection: { start: number; end: number }) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { - let searchString = extractTextFromCursor(plainTextInput.current, selection.start); - let tracker = searchString ? plainTextInput.current[selection.start - (searchString.length + 1)] : plainTextInput.current[selection.start - 1]; + let searchString = extractTextFromCursor( + plainTextInput.current, + selection.start + ); + let tracker = searchString + ? plainTextInput.current[selection.start - (searchString.length + 1)] + : plainTextInput.current[selection.start - 1]; if (shouldOpenList(selection, searchString, tracker)) { activeCharacter.current = tracker; @@ -1497,22 +1583,28 @@ export const CometChatMessageComposer = React.forwardRef( let formatter = allFormatters.current.get(tracker); if (formatter instanceof CometChatMentionsFormatter) { - let shouldShowMentionList = (formatter.getVisibleIn() === MentionsVisibility.both) || (formatter.getVisibleIn() === MentionsVisibility.usersConversationOnly && user) || (formatter.getVisibleIn() === MentionsVisibility.groupsConversationOnly && group); + let shouldShowMentionList = + formatter.getVisibleIn() === MentionsVisibility.both || + (formatter.getVisibleIn() === + MentionsVisibility.usersConversationOnly && + user) || + (formatter.getVisibleIn() === + MentionsVisibility.groupsConversationOnly && + group); if (shouldShowMentionList) { formatter.search(searchString); } } else { formatter?.search(searchString); } - } else { - activeCharacter.current = ""; - searchStringRef.current = ""; + activeCharacter.current = ''; + searchStringRef.current = ''; setShowMentionList(false); setMentionsSearchData([]); } }, 100); - } + }; const getRegexString = (str: string) => { // Get an array of the entries in the map using the spread operator @@ -1522,26 +1614,26 @@ export const CometChatMessageComposer = React.forwardRef( // Iterate over the array in reverse order entries.forEach(([key, value]) => { - - let [start, end] = key.split("_").map(Number); + let [start, end] = key.split('_').map(Number); let pre = uidInput.substring(0, start); let post = uidInput.substring(end); uidInput = pre + value.underlyingText + post; - }); return uidInput; + }; - } - - const getPlainString = (str: string, edits: Array<{ - "endIndex": number, - "replacement": string, - "startIndex": number, - "user": SuggestionItem - }>) => { + const getPlainString = ( + str: string, + edits: Array<{ + endIndex: number; + replacement: string; + startIndex: number; + user: SuggestionItem; + }> + ) => { // Get an array of the entries in the map using the spread operator const entries = [...edits].reverse(); @@ -1549,23 +1641,20 @@ export const CometChatMessageComposer = React.forwardRef( // Iterate over the array in reverse order entries.forEach(({ endIndex, replacement, startIndex, user }) => { - let pre = _plainString.substring(0, startIndex); let post = _plainString.substring(endIndex); _plainString = pre + replacement + post; - }); return _plainString; - - } + }; const textChangeHandler = (txt: string) => { let removing = plainTextInput.current.length > txt.length; let adding = plainTextInput.current.length < txt.length; let textDiff = txt.length - plainTextInput.current.length; - let notAtLast = (selectionPosition.start + textDiff) < txt.length; + let notAtLast = selectionPosition.start + textDiff < txt.length; plainTextInput.current = txt; onChangeText && onChangeText(txt); @@ -1576,19 +1665,30 @@ export const CometChatMessageComposer = React.forwardRef( let newMentionMap = new Map(mentionMap.current); mentionMap.current.forEach((value, key) => { - let position = { start: parseInt(key.split("_")[0]), end: parseInt(key.split("_")[1]) }; + let position = { + start: parseInt(key.split('_')[0]), + end: parseInt(key.split('_')[1]), + }; //Runs when cursor before the mention and before the last position - if (notAtLast && (((selectionPosition.start - 1) <= position.start) - || ((selectionPosition.start - textDiff) <= position.start) - )) { + if ( + notAtLast && + (selectionPosition.start - 1 <= position.start || + selectionPosition.start - textDiff <= position.start) + ) { if (removing) { - decr = ((selectionPosition.end) - selectionPosition.start) - (textDiff); - position = { start: position.start - decr, end: position.end - decr }; + decr = selectionPosition.end - selectionPosition.start - textDiff; + position = { + start: position.start - decr, + end: position.end - decr, + }; } else if (adding) { - decr = ((selectionPosition.end) - selectionPosition.start) + (textDiff); - position = { start: position.start + decr, end: position.end + decr }; + decr = selectionPosition.end - selectionPosition.start + textDiff; + position = { + start: position.start + decr, + end: position.end + decr, + }; } if (removing || adding) { let newKey = `${position.start}_${position.end}`; @@ -1598,30 +1698,36 @@ export const CometChatMessageComposer = React.forwardRef( } // Code to delete mention from hashmap 👇 - let expctedMentionPos = plainTextInput.current.substring(position.start, position.end); + let expctedMentionPos = plainTextInput.current.substring( + position.start, + position.end + ); if (expctedMentionPos !== `${value.promptText}`) { let newKey = `${position.start}_${position.end}`; newMentionMap.delete(newKey); if (!ifIdExists(value.id, newMentionMap)) { - let targetedFormatter: any = allFormatters.current.get(value.trackingCharacter); + let targetedFormatter: any = allFormatters.current.get( + value.trackingCharacter + ); let existingCCUsers = [...targetedFormatter.getSuggestionItems()]; - let userPosition = existingCCUsers.findIndex((item: SuggestionItem) => item.id === value.id); + let userPosition = existingCCUsers.findIndex( + (item: SuggestionItem) => item.id === value.id + ); if (userPosition !== -1) { existingCCUsers.splice(userPosition, 1); - (targetedFormatter as CometChatMentionsFormatter).setSuggestionItems(existingCCUsers) + ( + targetedFormatter as CometChatMentionsFormatter + ).setSuggestionItems(existingCCUsers); } } - } - }); mentionMap.current = newMentionMap; setFormattedInputMessage(); - }; const onMentionPress = (item: SuggestionItem) => { @@ -1630,61 +1736,88 @@ export const CometChatMessageComposer = React.forwardRef( let notAtLast = selectionPosition.start < plainTextInput.current.length; - let textDiff = (plainTextInput.current.length + item.promptText.length - searchStringRef.current.length) - plainTextInput.current.length; + let textDiff = + plainTextInput.current.length + + item.promptText.length - + searchStringRef.current.length - + plainTextInput.current.length; let incr = 0; let mentionPos = 0; let newMentionMap = new Map(mentionMap.current); - let targetedFormatter: any = allFormatters.current.get(activeCharacter.current); + let targetedFormatter: any = allFormatters.current.get( + activeCharacter.current + ); let existingCCUsers = [...targetedFormatter.getSuggestionItems()]; - let userAlreadyExists = existingCCUsers.find((existingUser: SuggestionItem) => existingUser.id === item.id); + let userAlreadyExists = existingCCUsers.find( + (existingUser: SuggestionItem) => existingUser.id === item.id + ); if (!userAlreadyExists) { let cometchatUIUserArray: Array = [...existingCCUsers]; cometchatUIUserArray.push(item); - (targetedFormatter as CometChatMentionsFormatter).setSuggestionItems(cometchatUIUserArray) + (targetedFormatter as CometChatMentionsFormatter).setSuggestionItems( + cometchatUIUserArray + ); } mentionMap.current.forEach((value, key) => { - let position = { start: parseInt(key.split("_")[0]), end: parseInt(key.split("_")[1]) }; + let position = { + start: parseInt(key.split('_')[0]), + end: parseInt(key.split('_')[1]), + }; if (!(selectionPosition.start <= position.start)) { mentionPos += 1; } // Code to delete mention from hashmap 👇 - if (position.end === selectionPosition.end || (selectionPosition.start > position.start && selectionPosition.end <= position.end)) { + if ( + position.end === selectionPosition.end || + (selectionPosition.start > position.start && + selectionPosition.end <= position.end) + ) { let newKey = `${position.start}_${position.end}`; newMentionMap.delete(newKey); - mentionPos -= 1 + mentionPos -= 1; } - if (notAtLast && ((selectionPosition.start - 1) <= position.start)) { - incr = (selectionPosition.end - selectionPosition.start) + (textDiff); - let newKey = `${(position.start + incr)}_${(position.end + incr)}`; + if (notAtLast && selectionPosition.start - 1 <= position.start) { + incr = selectionPosition.end - selectionPosition.start + textDiff; + let newKey = `${position.start + incr}_${position.end + incr}`; newMentionMap.set(newKey, value); newMentionMap.delete(key); } - }); mentionMap.current = newMentionMap; // When updating the input text, just get the latest plain text input and replace the selected text with the new mention - const updatedPlainTextInput = `${plainTextInput.current.substring(0, (selectionPosition.start - (1 + searchStringRef.current.length)))}${item.promptText + " "}${plainTextInput.current.substring( - (selectionPosition.end), + const updatedPlainTextInput = `${plainTextInput.current.substring( + 0, + selectionPosition.start - (1 + searchStringRef.current.length) + )}${item.promptText + ' '}${plainTextInput.current.substring( + selectionPosition.end, plainTextInput.current.length )}`; plainTextInput.current = updatedPlainTextInput; - let key = (selectionPosition.start - (1 + searchStringRef.current.length)) + "_" + ((selectionPosition.start - (searchStringRef.current.length + 1)) + item.promptText.length); - - let updatedMap = insertMentionAt(mentionMap.current, mentionPos, key, { ...item, trackingCharacter: activeCharacter.current }); + let key = + selectionPosition.start - + (1 + searchStringRef.current.length) + + '_' + + (selectionPosition.start - + (searchStringRef.current.length + 1) + + item.promptText.length); + + let updatedMap = insertMentionAt(mentionMap.current, mentionPos, key, { + ...item, + trackingCharacter: activeCharacter.current, + }); mentionMap.current = updatedMap; - setFormattedInputMessage() - - } + setFormattedInputMessage(); + }; const setFormattedInputMessage = () => { let textComponents: any = getRegexString(plainTextInput.current); @@ -1692,11 +1825,11 @@ export const CometChatMessageComposer = React.forwardRef( allFormatters.current.forEach((formatter, key) => { let resp = formatter.getFormattedText(textComponents); textComponents = resp; - }) + }); inputValueRef.current = textComponents; setInputMessage(textComponents); - } + }; function escapeRegExp(string: string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); @@ -1706,16 +1839,20 @@ export const CometChatMessageComposer = React.forwardRef( const leftText = inputText.substring(0, cursorPosition); // Escape the mentionPrefixes to safely use them in a regex pattern - const escapedPrefixes = trackingCharacters.current.map(escapeRegExp).join('|'); + const escapedPrefixes = trackingCharacters.current + .map(escapeRegExp) + .join('|'); // Build a dynamic regex pattern that matches any of the mention prefixes. // This pattern will match a prefix followed by any combination of word characters // and spaces, including a trailing space. - const mentionRegex = new RegExp(`(?:^|\\s)(${escapedPrefixes})([^${escapedPrefixes}\\s][^${escapedPrefixes}]*)$`); + const mentionRegex = new RegExp( + `(?:^|\\s)(${escapedPrefixes})([^${escapedPrefixes}\\s][^${escapedPrefixes}]*)$` + ); const match = leftText.match(mentionRegex); // If a match is found, return the first capturing group, which is the username - return match && substringUpToNthSpace(match[2], 4) || ""; + return (match && substringUpToNthSpace(match[2], 4)) || ''; } function substringUpToNthSpace(str: string, n: number) { @@ -1723,7 +1860,12 @@ export const CometChatMessageComposer = React.forwardRef( return str.split(' ', n).join(' '); } - const insertMentionAt = (mentionMap: Map, insertAt: number, key: string, value: SuggestionItem): Map => { + const insertMentionAt = ( + mentionMap: Map, + insertAt: number, + key: string, + value: SuggestionItem + ): Map => { // Convert the hashmap to an array of [key, value] pairs let mentionsArray = Array.from(mentionMap); @@ -1731,12 +1873,11 @@ export const CometChatMessageComposer = React.forwardRef( mentionsArray.splice(insertAt, 0, [key, value]); return new Map(mentionsArray); - - } + }; /** * Function to check if the id exists in the mentionMap - */ + */ const ifIdExists = (id: string, hashmap: Map) => { let exists = false; hashmap.forEach((value, key) => { @@ -1745,53 +1886,75 @@ export const CometChatMessageComposer = React.forwardRef( } }); return exists; - } + }; const onSuggestionListEndReached = () => { - let targetedFormatter = allFormatters.current.get(activeCharacter.current); + let targetedFormatter = allFormatters.current.get( + activeCharacter.current + ); if (!targetedFormatter) return; let fetchingNext = targetedFormatter.fetchNext(); fetchingNext !== null && setSuggestionListLoader(true); - } + }; const getMentionLimitView = () => { - let targetedFormatter: any = allFormatters.current.get(activeCharacter.current); + let targetedFormatter: any = allFormatters.current.get( + activeCharacter.current + ); let shouldWarn; let limit; if (targetedFormatter?.getLimit && targetedFormatter?.getLimit()) { limit = targetedFormatter?.getLimit(); - if (targetedFormatter.getUniqueUsersList && targetedFormatter.getUniqueUsersList()?.size >= limit) { + if ( + targetedFormatter.getUniqueUsersList && + targetedFormatter.getUniqueUsersList()?.size >= limit + ) { shouldWarn = true; } } if (!shouldWarn) return null; - let errorString = targetedFormatter?.getErrorString ? targetedFormatter?.getErrorString() : `${localize("MENTION_UPTO")} ${limit} ${limit === 1 ? localize("TIME") : localize("TIMES")} ${localize("AT_A_TIME")}.`; + let errorString = targetedFormatter?.getErrorString + ? targetedFormatter?.getErrorString() + : `${localize('MENTION_UPTO')} ${limit} ${ + limit === 1 ? localize('TIME') : localize('TIMES') + } ${localize('AT_A_TIME')}.`; return ( - - - {errorString} + + + + {errorString} + - ) - } + ); + }; return ( <> - {!isVisible && typeof CustomView === "function" && } + {!isVisible && typeof CustomView === 'function' && } setShowEmojiboard(false)} emojiSelection={(emoji: any) => { - let pre = plainTextInput.current.substring(0, selectionPosition.start); + let pre = plainTextInput.current.substring( + 0, + selectionPosition.start + ); let post = plainTextInput.current.substring( selectionPosition.end, plainTextInput.current.length ); - inputValueRef.current = selectionPosition.start && selectionPosition.end ? `${pre}${emoji}${post}` : `${inputValueRef.current}${emoji}`; + inputValueRef.current = + selectionPosition.start && selectionPosition.end + ? `${pre}${emoji}${post}` + : `${inputValueRef.current}${emoji}`; setInputMessage((prev) => selectionPosition.start && selectionPosition.end ? `${pre}${emoji}${post}` @@ -1845,21 +2016,22 @@ export const CometChatMessageComposer = React.forwardRef( // ...getActionSheetStyle(), ...(messageComposerStyle?.actionSheetSeparatorTint ? { - actionSheetSeparatorTint: - messageComposerStyle.actionSheetSeparatorTint, - } + actionSheetSeparatorTint: + messageComposerStyle.actionSheetSeparatorTint, + } : {}), - layoutModeIconTint: messageComposerStyle?.actionSheetLayoutModeIconTint, + layoutModeIconTint: + messageComposerStyle?.actionSheetLayoutModeIconTint, titleColor: messageComposerStyle?.actionSheetTitleColor, listItemIconTint: messageComposerStyle?.attachIconTint, - listItemTitleFont: messageComposerStyle?.actionSheetTitleFont + listItemTitleFont: messageComposerStyle?.actionSheetTitleFont, }} cometChatBottomSheetStyle={ messageComposerStyle?.actionSheetCancelButtonIconTint ? { - lineColor: - messageComposerStyle.actionSheetCancelButtonIconTint, - } + lineColor: + messageComposerStyle.actionSheetCancelButtonIconTint, + } : {} } /> @@ -1868,15 +2040,15 @@ export const CometChatMessageComposer = React.forwardRef( options={actionSheetItems} shouldShow={showRecordAudio} onClose={() => { - setShowRecordAudio(false) + setShowRecordAudio(false); }} onSend={_sendRecordedAudio} cometChatBottomSheetStyle={ messageComposerStyle?.actionSheetCancelButtonIconTint ? { - lineColor: - messageComposerStyle.actionSheetCancelButtonIconTint, - } + lineColor: + messageComposerStyle.actionSheetCancelButtonIconTint, + } : {} } mediaRecorderStyle={mediaRecorderStyle} @@ -1891,38 +2063,44 @@ export const CometChatMessageComposer = React.forwardRef( sheetRef={bottomSheetRef} shouldShow={showAIOptions} onClose={() => { - setShowAIOptions(false) + setShowAIOptions(false); }} aiOptions={AIOptionItems} aiStyle={AIStyles} /> - { - (mentionsSearchData.length > 0 && plainTextInput.current.length > 0) - && - 0 && + plainTextInput.current.length > 0 && ( + - {getMentionLimitView()} - - } + > + + {getMentionLimitView()} + + )} {HeaderView ? ( @@ -1935,17 +2113,16 @@ export const CometChatMessageComposer = React.forwardRef( text={messagePreview?.message?.text} shouldShow={messagePreview != null} /> - + { - setSelectionPosition(selection) - openList(selection) - } - } + setSelectionPosition(selection); + openList(selection); + }} maxHeight={maxHeight ?? undefined} onChangeText={textChangeHandler} SecondaryButtonView={SecondaryButtonViewElem} @@ -1966,14 +2143,3 @@ export const CometChatMessageComposer = React.forwardRef( ); } ); - -CometChatMessageComposer.defaultProps = { - user: undefined, - group: undefined, - // style: new MessageComposerStyle({}), - attachmentIcon: ICONS.ADD, - liveReactionIcon: ICONS.HEART, - hideLiveReaction: true, - disableSoundForMessages: true, - messageComposerStyle: {}, -}; diff --git a/src/CometChatMessageHeader/CometChatMessageHeader.tsx b/src/CometChatMessageHeader/CometChatMessageHeader.tsx index 67e4e38..08acb89 100644 --- a/src/CometChatMessageHeader/CometChatMessageHeader.tsx +++ b/src/CometChatMessageHeader/CometChatMessageHeader.tsx @@ -176,7 +176,6 @@ export interface CometChatMessageHeaderInterface { tailViewContainerStyle?: StyleProp; } - export const CometChatMessageHeader = ( props: CometChatMessageHeaderInterface ) => { @@ -192,9 +191,6 @@ export const CometChatMessageHeader = ( protectedGroupIcon, privateGroupIcon, AppBarOptions, - style, - user, - group, backButtonIcon, hideBackIcon, ListItemView, @@ -205,25 +201,31 @@ export const CometChatMessageHeader = ( headViewContainerStyle, bodyViewContainerStyle, tailViewContainerStyle, + + user = null, + group = null, + style = {}, } = props; const _avatarStyle = new AvatarStyle({ backgroundColor: theme?.palette?.getAccent600(), nameTextColor: theme?.palette?.getAccent(), nameTextFont: theme?.typography.body, - ...props?.avatarStyle + ...avatarStyle, }); const [groupObj, setGroupObj] = useState(group); - const [userStatus, setUserStatus] = useState((user && user.getStatus) ? user.getStatus() : ''); + const [userStatus, setUserStatus] = useState( + user && user.getStatus ? user.getStatus() : '' + ); const [typingText, setTypingText] = useState(''); const receiverTypeRef = useRef( user ? CometChat.RECEIVER_TYPE.USER : group - ? CometChat.RECEIVER_TYPE.GROUP - : null + ? CometChat.RECEIVER_TYPE.GROUP + : null ); useEffect(() => { @@ -243,8 +245,8 @@ export const CometChatMessageHeader = ( ? { uri: backButtonIcon } : typeof backButtonIcon == 'object' || typeof backButtonIcon == 'number' - ? backButtonIcon - : ICONS.BACK + ? backButtonIcon + : ICONS.BACK } style={[ styles.backButtonIconStyle, @@ -259,13 +261,16 @@ export const CometChatMessageHeader = ( if (!disableTyping && typingText !== '') return ( {typingText} @@ -273,19 +278,21 @@ export const CometChatMessageHeader = ( if (disableUsersPresence) return null; return ( {receiverTypeRef.current === CometChat.RECEIVER_TYPE.GROUP && - (groupObj?.['membersCount'] || groupObj?.['membersCount'] === 0) + (groupObj?.['membersCount'] || groupObj?.['membersCount'] === 0) ? `${groupObj['membersCount']} ${localize('MEMBERS')}` : receiverTypeRef.current === CometChat.RECEIVER_TYPE.USER - ? userStatus === UserStatusConstants.online - ? localize('ONLINE') - : localize('OFFLINE') - : ''} + ? userStatus === UserStatusConstants.online + ? localize('ONLINE') + : localize('OFFLINE') + : ''} ); }; @@ -315,7 +322,10 @@ export const CometChatMessageHeader = ( }; const handleGroupListener = (groupDetails: any) => { - if (groupDetails?.guid === groupObj?.getGuid() && groupDetails.membersCount) { + if ( + groupDetails?.guid === groupObj?.getGuid() && + groupDetails.membersCount + ) { setGroupObj(groupDetails); } }; @@ -392,17 +402,19 @@ export const CometChatMessageHeader = ( return ( {!hideBackIcon && } @@ -412,19 +424,31 @@ export const CometChatMessageHeader = ( ( - - ) + /> + ) : SubtitleViewFnc } bodyViewContainerStyle={{ @@ -440,23 +464,23 @@ export const CometChatMessageHeader = ( disableUsersPresence ? 'transparent' : user && userStatus === UserStatusConstants.online - ? style?.onlineStatusColor || theme.palette.getSuccess() - : 'transparent' + ? style?.onlineStatusColor || theme.palette.getSuccess() + : 'transparent' } statusIndicatorStyle={ (groupObj ? { - height: 15, - width: 15, - backgroundColor: - groupObj.getType() === CometChat.GROUP_TYPE.PASSWORD - ? PASSWORD_GROUP_COLOR // Note: Need to add this in palette - : groupObj.getType() === CometChat.GROUP_TYPE.PRIVATE + height: 15, + width: 15, + backgroundColor: + groupObj.getType() === CometChat.GROUP_TYPE.PASSWORD + ? PASSWORD_GROUP_COLOR // Note: Need to add this in palette + : groupObj.getType() === CometChat.GROUP_TYPE.PRIVATE ? PRIVATE_GROUP_COLOR // Note: Need to add this in palette : '', - borderRadius: 15, - ...statusIndicatorStyle, - } + borderRadius: 15, + ...statusIndicatorStyle, + } : { ...statusIndicatorStyle }) as ViewProps } statusIndicatorIcon={ @@ -466,25 +490,25 @@ export const CometChatMessageHeader = ( ? protectedGroupIcon : ICONS.PROTECTED : groupObj.getType() === CometChat.GROUP_TYPE.PRIVATE + ? privateGroupIcon ? privateGroupIcon ? privateGroupIcon - ? privateGroupIcon - : ICONS.PRIVATE - : null + : ICONS.PRIVATE : null + : null : null } TailView={ AppBarOptions ? () => ( - - ) + /> + ) : null } headViewContainerStyle={headViewContainerStyle} @@ -496,9 +520,3 @@ export const CometChatMessageHeader = ( ); }; - -CometChatMessageHeader.defaultProps = { - user: null, - group: null, - style: {}, -}; diff --git a/src/CometChatThreadedMessages/CometChatThreadedMessages.tsx b/src/CometChatThreadedMessages/CometChatThreadedMessages.tsx index 9ee1c45..723b72d 100644 --- a/src/CometChatThreadedMessages/CometChatThreadedMessages.tsx +++ b/src/CometChatThreadedMessages/CometChatThreadedMessages.tsx @@ -125,7 +125,6 @@ export const CometChatThreadedMessages = ( const { parentMessage, - title, closeIcon, BubbleView, MessageActionView, @@ -136,7 +135,8 @@ export const CometChatThreadedMessages = ( threadedMessagesStyle, hideMessageComposer, MessageComposerView, - MessageListView + MessageListView, + title= localize('THREAD'), } = props; const loggedInUser = useRef(null); @@ -286,7 +286,7 @@ export const CometChatThreadedMessages = ( { color: theme.palette.getAccent600(), }, - ] as TextStyle} + ] as TextStyle[]} > {replyCount ?? 0} {replyCount > 1 ? localize("REPLIES") : localize("REPLY")} @@ -343,8 +343,3 @@ export const CometChatThreadedMessages = ( ); }; -CometChatThreadedMessages.defaultProps = { - title: localize('THREAD'), - threadedMessagesStyle: {}, - parentMessage: {}, -}; diff --git a/src/CometChatTransferOwnership/CometChatTransferOwnership.tsx b/src/CometChatTransferOwnership/CometChatTransferOwnership.tsx index 2634612..c4cb2d6 100644 --- a/src/CometChatTransferOwnership/CometChatTransferOwnership.tsx +++ b/src/CometChatTransferOwnership/CometChatTransferOwnership.tsx @@ -65,7 +65,7 @@ export const CometChatTransferOwnership = ( const { theme } = useContext(CometChatContext); const { - title = localize("TRANSFER_OWNERSHIP"), + title = localize('TRANSFER_OWNERSHIP'), group, onTransferOwnership, transferOwnershipStyle, @@ -76,7 +76,7 @@ export const CometChatTransferOwnership = ( const [loggedInUser, setLoggedInUser] = useState(); const transferOwnership = (members: string | any[]) => { - if(!members.length) return + if (!members.length) return; let member = members[0]; let GUID: string = member.guid; let UID: string = member.uid; @@ -89,12 +89,15 @@ export const CometChatTransferOwnership = ( group['scope'] = GroupMemberScope.admin; group['owner'] = UID; onTransferOwnership && onTransferOwnership(group, member); - + //message parameter removed - CometChatUIEventHandler.emitGroupEvent(CometChatUIEvents.ccOwnershipChanged, { - group, - newOwner: member, - }); + CometChatUIEventHandler.emitGroupEvent( + CometChatUIEvents.ccOwnershipChanged, + { + group, + newOwner: member, + } + ); onBack && onBack(); }, (error: any) => { @@ -123,7 +126,7 @@ export const CometChatTransferOwnership = ( TailView={(item: any) => { return ( - + {loggedInUser?.getUid() === item.owner ? GroupMemberScope.owner : item.scope} @@ -140,8 +143,3 @@ export const CometChatTransferOwnership = ( ); }; - -CometChatTransferOwnership.defaultProps = { - group: {}, - title: localize("Transfer Ownership"), // Note: Update after localization is updated -}; diff --git a/src/CometChatUsers/CometChatUsers.tsx b/src/CometChatUsers/CometChatUsers.tsx index fb74e9d..5b469c8 100644 --- a/src/CometChatUsers/CometChatUsers.tsx +++ b/src/CometChatUsers/CometChatUsers.tsx @@ -13,7 +13,7 @@ import { CometChatListStylesInterface, CometChatOptions, } from '../shared'; -import {UsersStyle, UsersStyleInterface} from './UsersStyle' +import { UsersStyle, UsersStyleInterface } from './UsersStyle'; import { CometChatUIEventHandler } from '../shared/events/CometChatUIEventHandler/CometChatUIEventHandler'; export interface CometChatUsersInterface @@ -31,8 +31,6 @@ export interface CometChatUsersInterface | 'listItemKey' | 'onSelection' > { - - /** * * @@ -106,7 +104,18 @@ export const CometChatUsers = React.forwardRef< const ccUserBlockedId = 'ccUserBlocked_' + new Date().getTime(); const ccUserUnBlockedId = 'ccUserBlocked_' + new Date().getTime(); - const { usersRequestBuilder, usersStyle, ...newProps } = props; + const { + usersRequestBuilder = new CometChat.UsersRequestBuilder() + .setLimit(30) + .hideBlockedUsers(false) + .setRoles([]) + .friendsOnly(false) + .setStatus('') + .setTags([]) + .setUIDs([]), + usersStyle, + ...newProps + } = props; //context values const { theme } = React.useContext(CometChatContext); @@ -122,8 +131,8 @@ export const CometChatUsers = React.forwardRef< errorTextFont: theme?.typography.subtitle1, searchBackgroundColor: theme?.palette.getAccent600(), searchBorder: new BorderStyle({ - borderColor: theme?.palette.getAccent700(), - ...usersStyle?.border, + borderColor: theme?.palette.getAccent700(), + ...usersStyle?.border, }), separatorColor: theme?.palette.getAccent100(), subtitleTextColor: theme?.palette.getAccent600(), @@ -131,9 +140,9 @@ export const CometChatUsers = React.forwardRef< titleColor: theme?.palette.getAccent(), titleFont: theme?.typography.title1, loadingIconTint: theme?.palette.getPrimary(), - ...usersStyle -}); - + ...usersStyle, + }); + useImperativeHandle(ref, () => { return { updateList: userRef.current!.updateList, @@ -143,7 +152,7 @@ export const CometChatUsers = React.forwardRef< updateAndMoveToFirst: userRef.current!.updateAndMoveToFirst, getSelectedItems: userRef.current!.getSelectedItems, getAllListItems: userRef.current!.getAllListItems, - clearSelection: userRef.current!.clearSelection + clearSelection: userRef.current!.clearSelection, }; }); @@ -195,21 +204,13 @@ export const CometChatUsers = React.forwardRef< ref={userRef} title={'Users'} requestBuilder={usersRequestBuilder} - listStyle={{ ..._usersStyle, background: _usersStyle.backgroundColor }} - {...newProps as CometChatListProps} + listStyle={{ + ..._usersStyle, + background: _usersStyle.backgroundColor, + }} + {...(newProps as CometChatListProps)} listItemKey="uid" /> ); }); - -CometChatUsers.defaultProps = { - usersRequestBuilder: new CometChat.UsersRequestBuilder() - .setLimit(30) - .hideBlockedUsers(false) - .setRoles([]) - .friendsOnly(false) - .setStatus('') - .setTags([]) - .setUIDs([]), -}; diff --git a/src/extensions/CollaborativeBubble/CometChatCollaborativeBubble.tsx b/src/extensions/CollaborativeBubble/CometChatCollaborativeBubble.tsx index 691b8b0..2d6214a 100644 --- a/src/extensions/CollaborativeBubble/CometChatCollaborativeBubble.tsx +++ b/src/extensions/CollaborativeBubble/CometChatCollaborativeBubble.tsx @@ -44,44 +44,53 @@ interface CollaborativeBubbleProps { export const CometChatCollaborativeBubble = (props: CollaborativeBubbleProps) => { + const { + title= "", + subTitle= "", + buttonText= "", + icon= undefined, + style= new CollaborativeBubbleStyle({}), + url= undefined, + onPress + } = props; + const openLink = () => { - if (props.url != "") - if(props.onPress!=undefined){ - props.onPress(props.url) + if (url != "") + if(onPress!=undefined){ + onPress(url) } else { - console.log("opening uRL , ", props.url); - WebView.openUrl(props.url); + console.log("opening uRL , ", url); + WebView.openUrl(url); } } const getIcon = () => { - if (props.icon) { - if (typeof props.icon == 'number') - return props.icon - if (typeof props.icon == 'string') - return {uri: props.icon} + if (icon) { + if (typeof icon == 'number') + return icon + if (typeof icon == 'string') + return {uri: icon} } return whiteboard } const getButtonText = () => { - if (props.buttonText && props.buttonText.trim().length > 0) { - return props.buttonText; + if (buttonText && buttonText.trim().length > 0) { + return buttonText; } return ""; } - const {style} = props; return ( - {props.title} - {props.subTitle} + {title} + {subTitle} @@ -95,13 +104,3 @@ export const CometChatCollaborativeBubble = (props: CollaborativeBubbleProps) => ); } -CometChatCollaborativeBubble.defaultProps = { - title: "", - subTitle: "", - buttonText: "", - icon: undefined, - whiteboardURL: "", - loggedInUser: undefined, - style: new CollaborativeBubbleStyle({}), -} - diff --git a/src/extensions/Polls/Polls.tsx b/src/extensions/Polls/Polls.tsx index c99bad5..97971d4 100644 --- a/src/extensions/Polls/Polls.tsx +++ b/src/extensions/Polls/Polls.tsx @@ -161,21 +161,21 @@ export interface CometChatCreatePollInterface { export const CometChatCreatePoll = (props: CometChatCreatePollInterface) => { const { theme } = useContext(CometChatContext); const { - title, closeIcon, createIcon, - questionPlaceholderText, onError, - createPollsStyle, user, group, onClose, - answerPlaceholderText, answerHelpText, addAnswerText, deleteIcon, createPollIcon, - defaultAnswers, + title= localize('CREATE_POLL'), + questionPlaceholderText= localize('NAME'), + answerPlaceholderText= localize('ANSWER'), + createPollsStyle= {}, + defaultAnswers= 2, } = props; const [question, setQuestion] = React.useState(''); @@ -256,7 +256,7 @@ export const CometChatCreatePoll = (props: CometChatCreatePollInterface) => { styles.errorTextTitle, theme.typography.body, { color: theme.palette.getError() }, - ] as TextStyle} + ] as TextStyle[]} > {error?.length > 0 ? error : ''} @@ -265,7 +265,7 @@ export const CometChatCreatePoll = (props: CometChatCreatePollInterface) => { styles.errorText, theme.typography.body, { color: theme.palette.getError() }, - ] as TextStyle} + ] as TextStyle[]} > {localize('TRY_AGAIN_LATER')} @@ -353,7 +353,7 @@ export const CometChatCreatePoll = (props: CometChatCreatePollInterface) => { { color: theme.palette.getPrimary(), }, - ] as TextStyle} + ] as TextStyle[]} > {addAnswerText ?? localize('ADD_ANOTHER_ANSWER')} @@ -481,11 +481,3 @@ export const CometChatCreatePoll = (props: CometChatCreatePollInterface) => { ); }; - -CometChatCreatePoll.defaultProps = { - title: 'Create Polls', - questionPlaceholderText: localize('NAME'), - answerPlaceholderText: localize('ANSWER'), - createPollsStyle: {}, - defaultAnswers: 2, -}; diff --git a/src/extensions/Polls/PollsBubble.tsx b/src/extensions/Polls/PollsBubble.tsx index b8a4d31..e380f07 100644 --- a/src/extensions/Polls/PollsBubble.tsx +++ b/src/extensions/Polls/PollsBubble.tsx @@ -190,7 +190,7 @@ export const PollsBubble = (props: PollsBubbleInterface) => { }, theme.typography.subtitle1, pollsBubbleStyle?.pollOptionsTextStyle, - ] as TextStyle} + ] as TextStyle[]} > {value} @@ -204,7 +204,7 @@ export const PollsBubble = (props: PollsBubbleInterface) => { }, theme.typography.subtitle1, pollsBubbleStyle?.pollOptionsTextStyle, - ] as TextStyle}> + ] as TextStyle[]}> {optionsMetaData.results.options[id].count} @@ -260,7 +260,7 @@ export const PollsBubble = (props: PollsBubbleInterface) => { }, style.questionText, pollsBubbleStyle?.questionTextStyle, - ] as TextStyle} + ] as TextStyle[]} > {pollQuestion} @@ -278,7 +278,7 @@ export const PollsBubble = (props: PollsBubbleInterface) => { theme.palette.getAccent600(), }, pollsBubbleStyle?.voteCountTextStyle, - ] as TextStyle} + ] as TextStyle[]} > {optionsMetaData.results?.total} people voted @@ -342,9 +342,4 @@ const style = StyleSheet.create({ alignItems: "center", zIndex: 1, } -}); -PollsBubble.defaultProps = { - options: {}, - loggedInUser: {}, - pollsBubbleStyle: {}, -}; \ No newline at end of file +}); \ No newline at end of file diff --git a/src/extensions/SmartReplies/SmartRepliesView.tsx b/src/extensions/SmartReplies/SmartRepliesView.tsx index 411ca31..ae5162f 100644 --- a/src/extensions/SmartReplies/SmartRepliesView.tsx +++ b/src/extensions/SmartReplies/SmartRepliesView.tsx @@ -7,12 +7,9 @@ import { StyleSheet, Text, } from 'react-native'; -import { - FontStyleInterface, - ImageType, -} from '../../shared/base'; -import { CometChatSoundManager } from "../../shared/resources"; -import { CometChatContext } from "../../shared/CometChatContext"; +import { FontStyleInterface, ImageType } from '../../shared/base'; +import { CometChatSoundManager } from '../../shared/resources'; +import { CometChatContext } from '../../shared/CometChatContext'; import { ICONS } from './resources'; import { TextStyle } from 'react-native'; @@ -33,13 +30,13 @@ export interface SmartRepliesInterface { } const SmartRepliesView = (props: SmartRepliesInterface) => { const { - customOutgoingMessageSound, - enableSoundForMessages, onClose, - replies, - style, onClick, closeIcon, + customOutgoingMessageSound = null, + enableSoundForMessages = false, + style = {}, + replies = [], } = props; const { theme } = useContext(CometChatContext); @@ -108,12 +105,14 @@ const SmartRepliesView = (props: SmartRepliesInterface) => { ]} > {option} @@ -210,10 +209,5 @@ const Styles = StyleSheet.create({ textAlign: 'center', }, }); -SmartRepliesView.defaultProps = { - customOutgoingMessageSound: null, - enableSoundForMessages: false, - style: {}, - replies: [], -}; + export { SmartRepliesView }; diff --git a/src/extensions/Stickers/CometChatStickerKeyboard/CometChatStickerKeyboard.tsx b/src/extensions/Stickers/CometChatStickerKeyboard/CometChatStickerKeyboard.tsx index 2db423b..a2fb5fe 100644 --- a/src/extensions/Stickers/CometChatStickerKeyboard/CometChatStickerKeyboard.tsx +++ b/src/extensions/Stickers/CometChatStickerKeyboard/CometChatStickerKeyboard.tsx @@ -1,20 +1,27 @@ -import React from "react"; -import { View, Text, Image, ScrollView, TouchableOpacity, Dimensions } from "react-native"; -import { Hooks } from "./hooks"; -import { Styles } from "./style"; -import { localize } from "../../../shared/resources/CometChatLocalize"; -import { CometChatTheme } from "../../../shared/resources/CometChatTheme"; -import { ExtensionConstants } from "../../ExtensionConstants"; +import React from 'react'; +import { + View, + Text, + Image, + ScrollView, + TouchableOpacity, + Dimensions, +} from 'react-native'; +import { Hooks } from './hooks'; +import { Styles } from './style'; +import { localize } from '../../../shared/resources/CometChatLocalize'; +import { CometChatTheme } from '../../../shared/resources/CometChatTheme'; +import { ExtensionConstants } from '../../ExtensionConstants'; //@ts-ignore -import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { anyObject } from "../../../shared/utils"; +import { CometChat } from '@cometchat/chat-sdk-react-native'; +import { anyObject } from '../../../shared/utils'; export interface CometChatStickerKeyboardInterface { - loadingText?: string, - theme?: CometChatTheme, - onPress?: (item: CometChat.CustomMessage | anyObject) => void, - emptyText?: string, - errorText?: string, + loadingText?: string; + theme?: CometChatTheme; + onPress?: (item: CometChat.CustomMessage | anyObject) => void; + emptyText?: string; + errorText?: string; } /** @@ -28,23 +35,35 @@ export interface CometChatStickerKeyboardInterface { * */ -export const CometChatStickerKeyboard = (props: CometChatStickerKeyboardInterface) => { +export const CometChatStickerKeyboard = ( + props: CometChatStickerKeyboardInterface +) => { + const { + emptyText = localize('NO_STICKERS_FOUND'), + errorText = localize('SOMETHING_WRONG'), + loadingText = localize('LOADING'), + theme = new CometChatTheme({}), + onPress, + } = props; const [stickerList, setStickerList] = React.useState([]); const [stickerSet, setStickerSet] = React.useState(null); const [activeStickerList, setActiveStickerList] = React.useState([]); const [activeStickerSetName, setActiveStickerSetName] = React.useState(); const [decoratorMessage, setDecoratorMessage] = React.useState( - props?.loadingText || localize("LOADING") + loadingText || localize('LOADING') ); - const theme = new CometChatTheme(props?.theme || {}); - const sendStickerMessage = (stickerItem: { stickerUrl: any; stickerSetName: any; }) => { - if(stickerItem && typeof stickerItem === 'object') - props?.onPress && props?.onPress({ - ...stickerItem, - sticker_url: stickerItem?.stickerUrl, - sticker_name: stickerItem?.stickerSetName - }); + const sendStickerMessage = (stickerItem: { + stickerUrl: any; + stickerSetName: any; + }) => { + if (stickerItem && typeof stickerItem === 'object') + onPress && + onPress({ + ...stickerItem, + sticker_url: stickerItem?.stickerUrl, + sticker_name: stickerItem?.stickerSetName, + }); }; const onStickerSetClicked = (sectionItem: any) => { @@ -103,11 +122,7 @@ export const CometChatStickerKeyboard = (props: CometChatStickerKeyboardInterfac if (activeStickerList?.length === 0) { messageContainer = ( - - {decoratorMessage} - + {decoratorMessage} ); } @@ -124,36 +139,21 @@ export const CometChatStickerKeyboard = (props: CometChatStickerKeyboardInterfac setActiveStickerList, setActiveStickerSetName, setDecoratorMessage, - decoratorMessage, + decoratorMessage ); return ( - - {activeStickerList?.length > 0 ? - + + {activeStickerList?.length > 0 ? ( + {getStickerCategory()} - : getDecoratorMessage()} + ) : ( + getDecoratorMessage() + )} {getStickerList()} ); }; - -// Specifies the default values for props: -CometChatStickerKeyboard.defaultProps = { - emptyText: localize("NO_STICKERS_FOUND"), - errorText: localize("SOMETHING_WRONG"), - loadingText: localize("LOADING"), - style: { - width: "100%", - height: Dimensions.get("screen").height * 0.5, - borderRadius: 8, - }, -}; \ No newline at end of file diff --git a/src/shared/libs/datePickerModal/DateTimePickerModal.android.js b/src/shared/libs/datePickerModal/DateTimePickerModal.android.js index 3495d1b..4c0998f 100644 --- a/src/shared/libs/datePickerModal/DateTimePickerModal.android.js +++ b/src/shared/libs/datePickerModal/DateTimePickerModal.android.js @@ -11,7 +11,7 @@ const areEqual = (prevProps, nextProps) => { }; const DateTimePickerModal = memo( - ({ date, mode, isVisible, onCancel, onConfirm, onHide, ...otherProps }) => { + ( { date = new Date(), mode, isVisible = false, onCancel, onConfirm, onHide = () => {}, ...otherProps } ) => { const currentDateRef = useRef(date); const [currentMode, setCurrentMode] = useState(null); @@ -72,10 +72,4 @@ DateTimePickerModal.propTypes = { minimumDate: PropTypes.instanceOf(Date), }; -DateTimePickerModal.defaultProps = { - date: new Date(), - isVisible: false, - onHide: () => {}, -}; - export { DateTimePickerModal }; diff --git a/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.js b/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.js index 3e0b7d3..f0aa093 100644 --- a/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.js +++ b/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.js @@ -4,6 +4,7 @@ import { View, Text, TouchableOpacity, Image } from "react-native"; // import { getExtentionData, ExtensionConstants, CometChatTheme } from "../../shared"; import { Styles } from "./style"; import closeIcon from "./resources/close.png"; +import { MessagePreviewStyle } from "./MessagePreviewStyle"; /** * @@ -14,14 +15,35 @@ import closeIcon from "./resources/close.png"; * @copyright © 2022 CometChat Inc. * */ -const CometChatMessagePreview = (props) => { - let messageText = props?.messagePreviewSubtitle; +const CometChatMessagePreview = ({ + messagePreviewTitle = "", + messagePreviewSubtitle = "", + closeIconURL = closeIcon, + onCloseClick = null, + style = new MessagePreviewStyle({ + width: "100%", + height: "auto", + border: { + borderWidth: 3, + borderStyle: "solid", + borderColor: "rgba(20, 20, 20, 0.8)", + }, + backgroundColor: "rgb(255,255,255)", + borderRadius: 0, + messagePreviewTitleFont: {}, + messagePreviewTitleColor: "", + messagePreviewSubtitleColor: "", + messagePreviewSubtitleFont: {}, + closeIconTint: "", + }), +}) => { + let messageText = messagePreviewSubtitle; const theme ={} - // = new CometChatTheme(props?.theme || {}); + // = new CometChatTheme(theme || {}); //xss extensions data // const xssData = getExtentionData( - // props?.messageObject, + // messageObject, // ExtensionConstants.xssFilter // ); // if ( @@ -34,7 +56,7 @@ const CometChatMessagePreview = (props) => { //datamasking extensions data // const maskedData = getExtentionData( - // props?.messageObject, + // messageObject, // ExtensionConstants.dataMasking // ); // if ( @@ -48,7 +70,7 @@ const CometChatMessagePreview = (props) => { //profanity extensions data // const profaneData = getExtentionData( - // props?.messageObject, + // messageObject, // ExtensionConstants.profanityFilter // ); // if ( @@ -60,58 +82,28 @@ const CometChatMessagePreview = (props) => { // } let imageSource - if (props?.closeIconURL) { - if (typeof props?.closeIconURL === 'string' && props?.closeIconURL.length > 0) imageSource = { uri: props?.closeIconURL } + if (closeIconURL) { + if (typeof closeIconURL === 'string' && closeIconURL.length > 0) imageSource = { uri: closeIconURL } else imageSource = closeIcon } return ( - - + + - - {props?.messagePreviewTitle} + + {messagePreviewTitle} - + - {messageText} + {messageText} ); }; -CometChatMessagePreview.defaultProps = { - messagePreviewTitle: "", - messagePreviewSubtitle: "", - closeIconURL: closeIcon, - onCloseClick: null, - style: { - widht: "100%", - height: "auto", - border: { - borderWidth: 3, - borderStyle: "solid", - borderColor: "rgba(20, 20, 20, 0.8)" - }, - backgroundColor: "rgb(255,255,255)", - borderRadius: 0, - messagePreviewTitleFont: {}, - messagePreviewTitleColor: "", - messagePreviewSubtitleColor: "", - messagePreviewSubtitleFont: {}, - closeIconTint: "", - }, -}; - -CometChatMessagePreview.propTypes = { - messagePreviewTitle: PropTypes.string, - messagePreviewSubtitle: PropTypes.string, - closeIconURL: PropTypes.any, - onCloseClick: PropTypes.func, - style: PropTypes.object, -}; export { CometChatMessagePreview }; diff --git a/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx b/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx index 11b0641..b2d6032 100644 --- a/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx +++ b/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx @@ -149,6 +149,15 @@ interface CometChatActionSheetInterface { hideHeader?: boolean; } export const CometChatActionSheet = (props: CometChatActionSheetInterface) => { + const { + title= localize('ADD_TO_CHAT'), + layoutModeIconURL= undefined, + layoutMode= layoutType['list'], + hideLayoutMode= false, + actions= [], + style: propsStyle = {}, + hideHeader= false, + } = props; const { theme } = useContext(CometChatContext); const style: any = { ...new ActionSheetStyles({ @@ -157,15 +166,15 @@ export const CometChatActionSheet = (props: CometChatActionSheetInterface) => { listItemTitleColor: theme.palette.getAccent(), titleColor: theme.palette.getAccent(), titleFont: theme.typography.name, - backgroundColor: props.style?.backgroundColor, - paddingHorizontal: props.style?.paddingHorizontal + backgroundColor: propsStyle?.backgroundColor, + paddingHorizontal: propsStyle?.paddingHorizontal }), - ...props.style, - listItemTitleFont: {...theme.typography.subtitle1, ...(props.style.listItemTitleFont ?? {})}, + ...propsStyle, + listItemTitleFont: {...theme.typography.subtitle1, ...(propsStyle.listItemTitleFont ?? {})}, }; const [listMode, setListMode] = React.useState(true); - const [actionList, setActionList] = React.useState(props.actions); + const [actionList, setActionList] = React.useState(actions); Hooks(props, setActionList); @@ -193,7 +202,7 @@ export const CometChatActionSheet = (props: CometChatActionSheetInterface) => { style={{ height: 1, backgroundColor: - props.style?.actionSheetSeparatorTint || props.style?.optionsSeparatorTint || + style.actionSheetSeparatorTint || style.optionsSeparatorTint || theme.palette.getAccent200(), }} /> @@ -215,8 +224,8 @@ export const CometChatActionSheet = (props: CometChatActionSheetInterface) => { }; const getLayoutModeIcon = () => { - if (props.hideLayoutMode) return null; - let img = props.layoutModeIconURL; + if (hideLayoutMode) return null; + let img = layoutModeIconURL; if (img == undefined) { img = listMode ? ICONS.GRID : ICONS.LIST; } @@ -248,7 +257,7 @@ export const CometChatActionSheet = (props: CometChatActionSheetInterface) => { style?.border, ]} > - {!props.hideHeader && + {!hideHeader && { }, ]} > - {props.title} + {title} {getLayoutModeIcon()} } @@ -269,12 +278,3 @@ export const CometChatActionSheet = (props: CometChatActionSheetInterface) => { ); }; - -CometChatActionSheet.defaultProps = { - title: localize('ADD_TO_CHAT'), - layoutModeIconURL: undefined, - layoutMode: layoutType['list'], - hideLayoutMode: false, - actions: [], - style: null, -}; diff --git a/src/shared/views/CometChatAvatar/CometChatAvatar.tsx b/src/shared/views/CometChatAvatar/CometChatAvatar.tsx index fca1560..331d2f5 100644 --- a/src/shared/views/CometChatAvatar/CometChatAvatar.tsx +++ b/src/shared/views/CometChatAvatar/CometChatAvatar.tsx @@ -24,28 +24,22 @@ interface CometChatAvatarProps { } export const CometChatAvatar = (props: CometChatAvatarProps) => { + const { + image = undefined, + name: rawName = '', + style: propsStyle = new AvatarStyle({}), + } = props; const {theme} = useContext(CometChatContext); - const defaultStyleProps = new AvatarStyle({ + const style = new AvatarStyle({ backgroundColor : theme.palette.getAccent400(), nameTextColor : theme.palette.getAccent800(), nameTextFont : theme.typography.body, + ...propsStyle }); - const { image, name: rawName } = props; const name = rawName.trim(); - const style = { - ...defaultStyleProps, - ...props.style, - border: { ...defaultStyleProps.border, ...props.style?.border }, - nameTextFont: { - ...defaultStyleProps.nameTextFont, - ...props.style?.nameTextFont, - }, - outerView: { ...defaultStyleProps.outerView, ...props.style?.outerView }, - }; - const getImageView = () => { let isImage = Boolean(image); if (image && image.hasOwnProperty("uri") && typeof image.uri !== "string") { @@ -61,7 +55,7 @@ export const CometChatAvatar = (props: CometChatAvatarProps) => { color: style.nameTextColor, }, style.nameTextFont ?? {}, - ] as TextStyle} + ] as TextStyle[]} > {name.length >= 2 ? name.substring(0, 2).toUpperCase() : name} @@ -119,9 +113,3 @@ export const CometChatAvatar = (props: CometChatAvatarProps) => { ); }; - -CometChatAvatar.defaultProps = { - image: '', - name: '', - style: new AvatarStyle({}), -}; diff --git a/src/shared/views/CometChatBadge/CometChatBadge.tsx b/src/shared/views/CometChatBadge/CometChatBadge.tsx index e4b8a32..666455d 100644 --- a/src/shared/views/CometChatBadge/CometChatBadge.tsx +++ b/src/shared/views/CometChatBadge/CometChatBadge.tsx @@ -21,20 +21,19 @@ interface CometChatBadgeProps { } export const CometChatBadge = (props: CometChatBadgeProps) => { + const { + count= 0, + style: propsStyle= new BadgeStyle({}), + } = props; const { theme } = useContext(CometChatContext); - const defaultStyleProps = new BadgeStyle({ + const style = new BadgeStyle({ backgroundColor: theme?.palette.getPrimary(), textFont: theme.typography.caption2, textColor: theme.palette.getBackgroundColor(), + ...propsStyle }); - const { count } = props; - const style = { - ...defaultStyleProps, - ...props.style, - border: { ...defaultStyleProps.border, ...props.style?.border }, - textFont: { ...defaultStyleProps.textFont, ...props.style?.textFont }, - }; + if (count == 0) return null; return ( { color: style.textColor, }, style.textFont, - ] as TextStyle} + ] as TextStyle[]} > {count > 999 ? '999+' : count} ); }; - -CometChatBadge.defaultProps = { - count: 0, - style: new BadgeStyle({}), -}; diff --git a/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx b/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx index 60bb9fa..ff637bb 100644 --- a/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx +++ b/src/shared/views/CometChatBottomSheet/CometChatBottomSheet.tsx @@ -1,4 +1,10 @@ -import React, { forwardRef, useContext, useEffect, useImperativeHandle, useState } from 'react'; +import React, { + forwardRef, + useContext, + useEffect, + useImperativeHandle, + useState, +} from 'react'; import { Animated, BackHandler, @@ -7,7 +13,10 @@ import { PanResponder, TouchableOpacity, View, - Modal, ScrollView, KeyboardAvoidingView, Platform + Modal, + ScrollView, + KeyboardAvoidingView, + Platform, } from 'react-native'; import { Styles } from './style'; import { CometChatContext } from '../../CometChatContext'; @@ -26,161 +35,153 @@ export interface CometChatBottomSheetInterface { shadowColor?: string; backgroundColor?: string; lineColor?: string; - lineHeight?: number, - paddingHorizontal?: number, - borderRadius?: number, + lineHeight?: number; + paddingHorizontal?: number; + borderRadius?: number; }; } -const CometChatBottomSheet = forwardRef((props: CometChatBottomSheetInterface, ref) => { - const { theme } = useContext(CometChatContext); - const { - sliderMaxHeight, - animationDuration, - animation, - sliderMinHeight, - children, - isOpen, - onOpen, - onClose, - style, - } = props; +const CometChatBottomSheet = forwardRef( + (props: CometChatBottomSheetInterface, ref) => { + const { theme } = useContext(CometChatContext); + const { + children = , + isOpen = true, + sliderMaxHeight = Dimensions.get('screen').height * 0.9, + sliderMinHeight = 50, + animation = Easing.quad, + animationDuration = 200, + onOpen = undefined, + onClose = undefined, + style = {}, + } = props; - const [contentHeight, setContentHeight] = useState(null); - const panelHeightValue = new Animated.Value(0); + const [contentHeight, setContentHeight] = useState(null); + const panelHeightValue = new Animated.Value(0); - const togglePanel = () => { - Animated.timing(panelHeightValue, { - duration: animationDuration, - easing: animation, - toValue: - //@ts-ignore - panelHeightValue._value === 0 ? contentHeight - sliderMinHeight : 0, - useNativeDriver: false, - }).start(() => { - onClose && onClose(); - }); - return true; - }; - - useImperativeHandle(ref, () => { - return { - togglePanel + const togglePanel = () => { + Animated.timing(panelHeightValue, { + duration: animationDuration, + easing: animation, + toValue: + //@ts-ignore + panelHeightValue._value === 0 ? contentHeight - sliderMinHeight : 0, + useNativeDriver: false, + }).start(() => { + onClose && onClose(); + }); + return true; }; - }); - const _onBackPress = () => { - isOpen && togglePanel(); - return isOpen; - }; - const _handleScrollEndDrag = ({ nativeEvent }: any) => { - nativeEvent.contentOffset.y === 0 && togglePanel(); - }; + useImperativeHandle(ref, () => { + return { + togglePanel, + }; + }); + const _onBackPress = () => { + isOpen && togglePanel(); + return isOpen; + }; - const _setSize = ({ nativeEvent }: any) => { - setContentHeight(nativeEvent.layout.height); - }; + const _handleScrollEndDrag = ({ nativeEvent }: any) => { + nativeEvent.contentOffset.y === 0 && togglePanel(); + }; - let _parentPanResponder = PanResponder.create({ - onMoveShouldSetPanResponderCapture: () => !isOpen, - onPanResponderRelease: () => togglePanel(), - }); + const _setSize = ({ nativeEvent }: any) => { + setContentHeight(nativeEvent.layout.height); + }; - let _childPanResponder = PanResponder.create({ - onMoveShouldSetPanResponderCapture: (_, gestureState) => - gestureState.dy > 15, - onPanResponderRelease: (_, gestureState) => - gestureState.dy > 0 && togglePanel(), - }); + let _parentPanResponder = PanResponder.create({ + onMoveShouldSetPanResponderCapture: () => !isOpen, + onPanResponderRelease: () => togglePanel(), + }); - useEffect(() => { + let _childPanResponder = PanResponder.create({ + onMoveShouldSetPanResponderCapture: (_, gestureState) => + gestureState.dy > 15, + onPanResponderRelease: (_, gestureState) => + gestureState.dy > 0 && togglePanel(), + }); - BackHandler.addEventListener('hardwareBackPress', _onBackPress); - // onOpen ? onOpen() : () => {}; + useEffect(() => { + BackHandler.addEventListener('hardwareBackPress', _onBackPress); + // onOpen ? onOpen() : () => {}; - return () => { - BackHandler.removeEventListener('hardwareBackPress', _onBackPress); - }; - }, []); + return () => { + BackHandler.removeEventListener('hardwareBackPress', _onBackPress); + }; + }, []); - return ( - togglePanel()} - > - togglePanel()} > - - togglePanel()} - /> - { - //@ts-ignore - - + + togglePanel()} + /> + { + //@ts-ignore + - - - + + + + + + + {typeof children === 'function' + ? children(_handleScrollEndDrag) + : children} - - - {typeof children === 'function' - ? children(_handleScrollEndDrag) - : children} - - - } - - - - ); -}); - -CometChatBottomSheet.defaultProps = { - children: , - isOpen: true, - sliderMaxHeight: Dimensions.get('screen').height * 0.9, - sliderMinHeight: 50, - animation: Easing.quad, - animationDuration: 200, - onOpen: undefined, - onClose: undefined, - style: {}, -}; + + } + + + + ); + } +); export { CometChatBottomSheet }; diff --git a/src/shared/views/CometChatConfirmDialog/CometChatConfirmDialog.tsx b/src/shared/views/CometChatConfirmDialog/CometChatConfirmDialog.tsx index 86964bd..46a3143 100644 --- a/src/shared/views/CometChatConfirmDialog/CometChatConfirmDialog.tsx +++ b/src/shared/views/CometChatConfirmDialog/CometChatConfirmDialog.tsx @@ -6,7 +6,6 @@ import { CometChatContext } from '../../CometChatContext'; import { CometChatContextType } from '../../base/Types'; import { CometChatConfirmDialogStyleInterface } from './CometChatConfirmDialogStyle'; - export interface CometChatConfirmDialogInterface { onConfirm?: Function; onCancel?: Function; @@ -22,14 +21,14 @@ export const CometChatConfirmDialog = ( ) => { const { theme } = useContext(CometChatContext); const { - onConfirm, - onCancel, - isOpen, - style, - title, - messageText, - cancelButtonText, - confirmButtonText, + isOpen = false, + title = '', + confirmButtonText = 'Delete', + cancelButtonText = 'Cancel', + messageText = 'Are you sure?', + onConfirm = () => {}, + onCancel = () => {}, + style = {}, } = props; const onClick = (option: any) => { if (option === 'confirm') { @@ -52,22 +51,27 @@ export const CometChatConfirmDialog = ( ]} > {title} {messageText} @@ -82,15 +86,17 @@ export const CometChatConfirmDialog = ( ]} > {cancelButtonText?.toUpperCase()} @@ -105,15 +111,17 @@ export const CometChatConfirmDialog = ( ]} > {confirmButtonText?.toUpperCase()} @@ -124,15 +132,3 @@ export const CometChatConfirmDialog = ( ); }; - -CometChatConfirmDialog.defaultProps = { - isOpen: false, - title: '', - confirmButtonText: 'Delete', - cancelButtonText: 'Cancel', - messageText: 'Are you sure?', - onConfirm: () => {}, - onCancel: () => {}, - style: {}, -}; - diff --git a/src/shared/views/CometChatDate/CometChatDate.tsx b/src/shared/views/CometChatDate/CometChatDate.tsx index 3de2097..0349252 100644 --- a/src/shared/views/CometChatDate/CometChatDate.tsx +++ b/src/shared/views/CometChatDate/CometChatDate.tsx @@ -66,25 +66,27 @@ export interface CometChatDateInterface { */ style?: DateStyleInterface; /** - * + * */ - dateAlignment?: "auto" | "left" | "right" | "center" | "justify" | undefined; + dateAlignment?: 'auto' | 'left' | 'right' | 'center' | 'justify' | undefined; } export const CometChatDate = (props: CometChatDateInterface) => { const { theme } = useContext(CometChatContext); - const { timeStamp, pattern, customDateString, dateAlignment } = props; + const { + dateAlignment, + timeStamp = 0, + pattern = patterns.timeFormat, + customDateString = null, + style: styleProps = new DateStyle({}), + } = props; - const defaultStyleProps = new DateStyle({ + const style = new DateStyle({ textFont: theme.typography.caption1, textColor: theme.palette.getAccent500(), + ...styleProps, }); - const style = { - ...defaultStyleProps, - ...props.style, - }; - let date = new Date(timeStamp); const getWeekOfDay = () => { @@ -175,17 +177,16 @@ export const CometChatDate = (props: CometChatDateInterface) => { ]} > {customDateString ? customDateString : getFormattedDate()} ); }; - -CometChatDate.defaultProps = { - timeStamp: 0, - pattern: patterns.timeFormat, - customDateString: null, - style: new DateStyle({}), -}; diff --git a/src/shared/views/CometChatDateTimePicker/CometChatDateTimePicker.tsx b/src/shared/views/CometChatDateTimePicker/CometChatDateTimePicker.tsx index cfdfd5f..7de5888 100644 --- a/src/shared/views/CometChatDateTimePicker/CometChatDateTimePicker.tsx +++ b/src/shared/views/CometChatDateTimePicker/CometChatDateTimePicker.tsx @@ -6,30 +6,35 @@ import { TouchableOpacity, Platform, TextStyle, -} from "react-native"; -import React, { useState, useContext, useLayoutEffect } from "react"; -import DateTimePickerModal from "../../libs/datePickerModal"; -import { ICONS } from "../../assets/images"; -import { CometChatContextType } from "../../base"; -import { CometChatContext } from "../../CometChatContext"; +} from 'react-native'; +import React, { useState, useContext, useLayoutEffect } from 'react'; +import DateTimePickerModal from '../../libs/datePickerModal'; +import { ICONS } from '../../assets/images'; +import { CometChatContextType } from '../../base'; +import { CometChatContext } from '../../CometChatContext'; //@ts-ignore -import { DateTime } from "../../libs/luxon/src/luxon"; -import { convertToATimeZone } from "../../utils/SchedulerUtils"; +import { DateTime } from '../../libs/luxon/src/luxon'; +import { convertToATimeZone } from '../../utils/SchedulerUtils'; //@ts-ignore -import DateTimePicker from "@react-native-community/datetimepicker"; -import { DatePickerStyleInterface, styles } from "./DateTimePickerStyle"; -import { DateTimeElement } from "../../modals"; +import DateTimePicker from '@react-native-community/datetimepicker'; +import { DatePickerStyleInterface, styles } from './DateTimePickerStyle'; +import { DateTimeElement } from '../../modals'; export interface CometChatDateTimePickerInterface { style: DatePickerStyleInterface; - data: DateTimeElement; + data?: DateTimeElement; showError: boolean; - onChange: (selectedDateTime: string) => void; + onChange?: (selectedDateTime: string) => void; } export const CometChatDateTimePicker = ( props: CometChatDateTimePickerInterface ) => { - const { style, showError, data, onChange } = props; + const { + data, + onChange, + style = {}, + showError = true, + } = props; const mode = data.getMode(); const format = data.getDateTimeFormat(); const timeZone = data.getTimeZone(); @@ -38,28 +43,32 @@ export const CometChatDateTimePicker = ( const [isDatePickerVisible, setDatePickerVisibility] = useState(false); - const [defaultTime, setDefaultTime] = useState(data.getDefaultValue() ?? ""); + const [defaultTime, setDefaultTime] = useState( + data.getDefaultValue() ?? '' + ); const [selectedDate, setSelectedDate] = useState(); const [fromDateTime, setFromDateTime] = useState( - data.getFromDateTime() ?? "" + data.getFromDateTime() ?? '' + ); + const [toDateTime, setToDateTime] = useState( + data.getToDateTime() ?? '' ); - const [toDateTime, setToDateTime] = useState(data.getToDateTime() ?? ""); const onDateSelected = (e: any) => { setSelectedDate(() => { - if (mode === "time" && Platform.OS === "ios") { + if (mode === 'time' && Platform.OS === 'ios') { return selectedDate; } else return e; }); e = DateTime.fromJSDate(e).setZone(); setDatePickerVisibility(false); - if (mode === "date") { - e = DateTime.fromISO(e).toFormat("yyyy-MM-dd"); + if (mode === 'date') { + e = DateTime.fromISO(e).toFormat('yyyy-MM-dd'); } - if (mode === "time") { - if (Platform.OS === "ios") { - e = DateTime.fromJSDate(selectedDate as Date).toFormat("HH:mm"); - } else e = DateTime.fromISO(e).toFormat("HH:mm"); + if (mode === 'time') { + if (Platform.OS === 'ios') { + e = DateTime.fromJSDate(selectedDate as Date).toFormat('HH:mm'); + } else e = DateTime.fromISO(e).toFormat('HH:mm'); } onChange && onChange(e); @@ -71,23 +80,23 @@ export const CometChatDateTimePicker = ( return DateTime.fromJSDate(new Date(time)).toFormat(format); return DateTime.fromISO(time).toFormat(format); } - return ""; + return ''; }; const convertToATimeZoneWithModes = (time: any) => { switch (mode) { - case "dateTime": - return convertToATimeZone(time, timeZone, "toISO", "fromISO"); - case "date": + case 'dateTime': + return convertToATimeZone(time, timeZone, 'toISO', 'fromISO'); + case 'date': return convertToATimeZone( `${time}T00:00:00`, timeZone, - "toISO", - "fromISO" + 'toISO', + 'fromISO' ); - case "time": - time = time?.split(":"); - if(time && time.length) { + case 'time': + time = time?.split(':'); + if (time && time.length) { let dateTime = new Date(); dateTime.setHours(time[0]); dateTime.setMinutes(time[1]); @@ -99,13 +108,13 @@ export const CometChatDateTimePicker = ( return convertToATimeZone( dateTime.toISOString(), timeZone, - "toISO", - "fromISO" + 'toISO', + 'fromISO' ); } - return ""; + return ''; default: - return ""; + return ''; } }; useLayoutEffect(() => { @@ -124,15 +133,19 @@ export const CometChatDateTimePicker = ( setDatePickerVisibility(false)} minimumDate={new Date(fromDateTime as string)} maximumDate={new Date(toDateTime as string)} - display={Platform.OS === "ios" ? "inline" : "default"} - {...(Platform.OS === "ios" && mode?.toLowerCase() === "time" + display={Platform.OS === 'ios' ? 'inline' : 'default'} + {...(Platform.OS === 'ios' && mode?.toLowerCase() === 'time' ? { customPickerIOS: () => ( )} {data.getLabel()} - {!data.getOptional() && "*"} + {!data.getOptional() && '*'} ); }; - -CometChatDateTimePicker.defaultProps = { - style: {}, -}; diff --git a/src/shared/views/CometChatEmojiKeyboard/CometChatEmojiKeyboard.tsx b/src/shared/views/CometChatEmojiKeyboard/CometChatEmojiKeyboard.tsx index 416a628..ede2073 100644 --- a/src/shared/views/CometChatEmojiKeyboard/CometChatEmojiKeyboard.tsx +++ b/src/shared/views/CometChatEmojiKeyboard/CometChatEmojiKeyboard.tsx @@ -1,4 +1,10 @@ -import React, { useCallback, useImperativeHandle, useRef, useState, useContext } from 'react'; +import React, { + useCallback, + useImperativeHandle, + useRef, + useState, + useContext, +} from 'react'; import PropTypes from 'prop-types'; import { Emojis } from './emojis'; import { Styles } from './style'; @@ -18,65 +24,64 @@ const emojiValues = Object.values(Emojis); const viewConfig = { waitForInteraction: true, - viewAreaCoveragePercentThreshold: 30 -} + viewAreaCoveragePercentThreshold: 30, +}; type CategoryListInterface = { - theme: CometChatTheme, - onCategorySelected: (id: string, index: number) => void, + theme: CometChatTheme; + onCategorySelected: (id: string, index: number) => void; style?: { - categoryIconTint?: string - selectedCategoryIconTint?: string - } -} + categoryIconTint?: string; + selectedCategoryIconTint?: string; + }; +}; type CategoryListActions = { - updateCategory: (newCateory: string, index: number) => void -} + updateCategory: (newCateory: string, index: number) => void; +}; const CategoryList = React.forwardRef< CategoryListActions, CategoryListInterface ->(( - { theme, onCategorySelected, style }, ref) => { +>(({ theme, onCategorySelected, style }, ref) => { const [activeCategory, setActiveCategory] = useState('people'); useImperativeHandle(ref, () => { return { - updateCategory: updateCategory - } + updateCategory: updateCategory, + }; }); const updateCategory = (newCategory: any, index: any) => { setActiveCategory(newCategory); - } + }; return ( <> - { - Emojis.map((value, index) => { - let emojiCategory = Object.values(value)[0]; - return ( - { - onCategorySelected && onCategorySelected(emojiCategory.id, index); + {Emojis.map((value, index) => { + let emojiCategory = Object.values(value)[0]; + return ( + { + onCategorySelected && onCategorySelected(emojiCategory.id, index); + }} + > + - - - ); - }) - } + source={emojiCategory.symbol} + /> + + ); + })} - ) + ); }); /** @@ -94,7 +99,15 @@ const CategoryList = React.forwardRef< const CometChatEmojiKeyboard = (props: EmojiKeyboardConfiguration) => { const theme: CometChatTheme = new CometChatTheme(props?.theme ?? {}); - const { onClick, style } = props; + const { + onClick = () => {}, + style = { + width: '100%', + height: 310, + border: {}, + borderRadius: 8, + }, + } = props; const emojiRef = useRef(null); const categoryRef = useRef(null); @@ -116,18 +129,19 @@ const CometChatEmojiKeyboard = (props: EmojiKeyboardConfiguration) => { Styles.listStyle, { backgroundColor: - style?.backgroundColor || - theme?.palette?.getBackgroundColor(), + style?.backgroundColor || theme?.palette?.getBackgroundColor(), }, ]} > {item.char} @@ -143,12 +157,17 @@ const CometChatEmojiKeyboard = (props: EmojiKeyboardConfiguration) => { return ( {name} @@ -176,8 +195,7 @@ const CometChatEmojiKeyboard = (props: EmojiKeyboardConfiguration) => { width: style?.width, height: style?.height, backgroundColor: - style?.backgroundColor || - theme?.palette?.getBackgroundColor(), + style?.backgroundColor || theme?.palette?.getBackgroundColor(), } as ViewProps, ]} > @@ -200,7 +218,7 @@ const CometChatEmojiKeyboard = (props: EmojiKeyboardConfiguration) => { } }} windowSize={50} - onScrollToIndexFailed={(error) => { }} + onScrollToIndexFailed={(error) => {}} renderItem={emojiListRender} /> { { width: style?.width, backgroundColor: - style?.categoryBackground || - theme?.palette?.getBackgroundColor(), + style?.categoryBackground || theme?.palette?.getBackgroundColor(), } as ViewProps, ]} > @@ -228,20 +245,7 @@ const CometChatEmojiKeyboard = (props: EmojiKeyboardConfiguration) => { ); }; -// Specifies the default values for props: -CometChatEmojiKeyboard.defaultProps = { - // hideSearch: false, - onClick: () => { }, - style: { - width: '100%', - height: 310, - border: {}, - borderRadius: 8, - }, -}; - CometChatEmojiKeyboard.propTypes = { - // hideSearch: PropTypes.bool, onClick: PropTypes.func, style: PropTypes.object, }; diff --git a/src/shared/views/CometChatFormBubble/CometChatFormBubble.tsx b/src/shared/views/CometChatFormBubble/CometChatFormBubble.tsx index 4172a40..f458c9c 100644 --- a/src/shared/views/CometChatFormBubble/CometChatFormBubble.tsx +++ b/src/shared/views/CometChatFormBubble/CometChatFormBubble.tsx @@ -505,7 +505,7 @@ export const CometChatFormBubble = memo((props: CometChatFormBubbleInterface) => subtitle={message.getTitle()} quickViewStyle={quickViewStyle} /> - {message.getGoalCompletionText() || localize("FORM_COMPLETION_MESSAGE")} + {message.getGoalCompletionText() || localize("FORM_COMPLETION_MESSAGE")} : color: titleColor, }, titleFont, - ] as TextStyle} + ] as TextStyle[]} >{message.getTitle()} } @@ -539,9 +539,4 @@ export const CometChatFormBubble = memo((props: CometChatFormBubbleInterface) => } -}) - -//@ts-ignore -CometChatFormBubble.defaultProps = { - message: {} -} \ No newline at end of file +}) \ No newline at end of file diff --git a/src/shared/views/CometChatList/CometChatList.tsx b/src/shared/views/CometChatList/CometChatList.tsx index 6ccb327..a80873e 100644 --- a/src/shared/views/CometChatList/CometChatList.tsx +++ b/src/shared/views/CometChatList/CometChatList.tsx @@ -16,11 +16,11 @@ import { ListRenderItem, ViewProps, TextStyle, - ActivityIndicator + ActivityIndicator, //@ts-ignore } from 'react-native'; import { CometChatContext } from '../../CometChatContext'; -import { localize } from "../../resources/CometChatLocalize"; +import { localize } from '../../resources/CometChatLocalize'; import { LOADING, NO_DATA_FOUND, @@ -30,7 +30,7 @@ import { import { ICONS } from './resources'; import styles from './styles'; import { CometChatOptions } from '../../modals'; -import { CometChatListItem } from "../../views/CometChatListItem"; +import { CometChatListItem } from '../../views/CometChatListItem'; import Header from './Header'; import { ImageType } from '../../base'; import { BorderStyleInterface, FontStyleInterface } from '../../base'; @@ -48,9 +48,9 @@ export interface CometChatListActionsInterface { addItemToList: (item: any, position?: number) => void; removeItemFromList: (itemId: string | number) => void; getListItem: (itemId: string | number) => void; - getSelectedItems: () => Array, - getAllListItems: () => Array, - clearSelection: () => void, + getSelectedItems: () => Array; + getAllListItems: () => Array; + clearSelection: () => void; } export interface CometChatListStylesInterface { @@ -115,7 +115,7 @@ export interface CometChatListProps { bodyViewContainerStyle?: StyleProp; tailViewContainerStyle?: StyleProp; listStyle?: CometChatListStylesInterface; - hideSubmitIcon?: boolean + hideSubmitIcon?: boolean; } let lastCall: any; let lastReject: Function; @@ -132,7 +132,6 @@ export const CometChatList = React.forwardRef< CometChatListActionsInterface, CometChatListProps >((props, ref) => { - const connectionListenerId = 'connectionListener_' + new Date().getTime(); const { theme } = useContext(CometChatContext); @@ -147,33 +146,33 @@ export const CometChatList = React.forwardRef< searchPlaceholderText, backButtonIcon, showBackButton, - selectionMode, - onSelection, searchBoxIcon, - hideSearch, - title, EmptyStateView, - emptyStateText, - errorStateText, ErrorStateView, LoadingStateView, - requestBuilder, - searchRequestBuilder, - hideError, - onItemPress, - onItemLongPress, onError, onBack, selectionIcon, - listItemKey, statusIndicatorStyle, avatarStyle, listItemStyle, headViewContainerStyle, bodyViewContainerStyle, tailViewContainerStyle, - listStyle, hideSubmitIcon, + title = '', + hideSearch = false, + requestBuilder = undefined, + searchRequestBuilder = undefined, + emptyStateText = '', + errorStateText = localize('SOMETHING_WRONG'), + hideError = false, + onItemPress = () => {}, + onItemLongPress = () => {}, + onSelection = () => {}, + selectionMode = 'none', + listItemKey = 'uid', + listStyle = {}, } = props; // functions which can be access by parents @@ -186,7 +185,7 @@ export const CometChatList = React.forwardRef< updateAndMoveToFirst, getSelectedItems, getAllListItems, - clearSelection + clearSelection, }; }); @@ -196,31 +195,31 @@ export const CometChatList = React.forwardRef< ? searchRequestBuilder.searchKeyword : '' : requestBuilder + ? requestBuilder.searchKeyword ? requestBuilder.searchKeyword - ? requestBuilder.searchKeyword - : '' - : searchRequestBuilder - ? searchRequestBuilder.searchKeyword - ? searchRequestBuilder.searchKeyword - : '' - : '' + : '' + : searchRequestBuilder + ? searchRequestBuilder.searchKeyword + ? searchRequestBuilder.searchKeyword + : '' + : '' ); const searchInputRef = useRef( requestBuilder && searchRequestBuilder - ? searchRequestBuilder.searchKeyword ? searchRequestBuilder.searchKeyword - : '' - : requestBuilder + ? searchRequestBuilder.searchKeyword + : '' + : requestBuilder ? requestBuilder.searchKeyword ? requestBuilder.searchKeyword : '' : searchRequestBuilder + ? searchRequestBuilder.searchKeyword ? searchRequestBuilder.searchKeyword - ? searchRequestBuilder.searchKeyword - : '' : '' + : '' ); - + const [shouldSelect, setShouldSelect] = React.useState( selectionMode !== 'none' ? true : false ); @@ -265,18 +264,18 @@ export const CometChatList = React.forwardRef< const getSelectedItems = () => { let markedItems: any[] = []; - Object.keys(selectedItems).forEach(item => { + Object.keys(selectedItems).forEach((item) => { return markedItems.push(getListItem(item)); - }) + }); return markedItems; - } + }; useEffect(() => { CometChat.addConnectionListener( connectionListenerId, new CometChat.ConnectionListener({ onConnected: () => { - console.log("ConnectionListener => On Connected"); + console.log('ConnectionListener => On Connected'); if (requestBuilder) { if (searchInputRef.current) listHandlerRef.current = requestBuilder @@ -298,19 +297,18 @@ export const CometChatList = React.forwardRef< }); }, inConnecting: () => { - console.log("ConnectionListener => In connecting"); + console.log('ConnectionListener => In connecting'); }, onDisconnected: () => { - console.log("ConnectionListener => On Disconnected"); - } + console.log('ConnectionListener => On Disconnected'); + }, }) ); return () => { CometChat.removeConnectionListener(connectionListenerId); - } + }; }, []); - useEffect(() => { if (initialRunRef.current === true) { if (requestBuilder) { @@ -330,7 +328,7 @@ export const CometChatList = React.forwardRef< }, [selectionMode]); useEffect(() => { - searchInputRef.current = searchInput + searchInputRef.current = searchInput; }, [searchInput]); /** @@ -362,7 +360,7 @@ export const CometChatList = React.forwardRef< newList.splice(itemKey, 1); } setList([item, ...newList]); - } + }; const addItemToList = (item: any, position?: number) => { setList((prev: [any]) => { @@ -448,7 +446,7 @@ export const CometChatList = React.forwardRef< setSelectedItems((prev: any) => { let newState = { ...prev }; if (Object.keys(prev).includes(listItem.value[listItemKey])) { - delete newState[listItem.value[listItemKey]] + delete newState[listItem.value[listItemKey]]; return newState; } else { newState[listItem.value[listItemKey]] = listItem.value; @@ -460,9 +458,9 @@ export const CometChatList = React.forwardRef< }; const onSelectionHandler = () => { - if(onSelection) { + if (onSelection) { onSelection(Object.values(selectedItems)); - return + return; } setShouldSelect(false); setSelectedItems({}); @@ -471,7 +469,7 @@ export const CometChatList = React.forwardRef< const clearSelection = () => { setShouldSelect(false); setSelectedItems({}); - } + }; const onListItemPress = (item: any) => { if (shouldSelect) { @@ -479,7 +477,7 @@ export const CometChatList = React.forwardRef< setSelectedItems((prev: any) => { let newState = { ...prev }; if (Object.keys(prev).includes(item.value[listItemKey])) { - delete newState[item.value[listItemKey]] + delete newState[item.value[listItemKey]]; return newState; } else { newState[item.value[listItemKey]] = item.value; @@ -514,15 +512,17 @@ export const CometChatList = React.forwardRef< ]} > {headerLetter} @@ -551,13 +551,14 @@ export const CometChatList = React.forwardRef< Object.keys(selectedItems).includes(item.value[listItemKey]) ? theme.palette.getBackgroundColor() : !disableUsersPresence && item.value.status === 'online' + ? listStyle?.onlineStatusColor ? listStyle?.onlineStatusColor - ? listStyle?.onlineStatusColor - : theme.palette.getSuccess() - : '' + : theme.palette.getSuccess() + : '' } statusIndicatorIcon={ - Object.keys(selectedItems).includes(item.value[listItemKey]) && ICONS.CHECK + Object.keys(selectedItems).includes(item.value[listItemKey]) && + ICONS.CHECK } {...(SubtitleView ? { SubtitleView: () => SubtitleView(item.value) } @@ -566,23 +567,23 @@ export const CometChatList = React.forwardRef< statusIndicatorStyle={ selectedItems[item.value[listItemKey]] === true ? { - ...(statusIndicatorStyle as object), - borderRadius: 10, - height: 20, - width: 20, - } - : statusIndicatorStyle as ViewProps + ...(statusIndicatorStyle as object), + borderRadius: 10, + height: 20, + width: 20, + } + : (statusIndicatorStyle as ViewProps) } avatarStyle={avatarStyle} - options={() => options ? options(item.value) : []} + options={() => (options ? options(item.value) : [])} activeSwipeRows={activeSwipeRows.current} rowOpens={(id) => { - Object.keys(activeSwipeRows.current).forEach(key => { - if(id !== key && activeSwipeRows.current[key]) { - activeSwipeRows.current[key]?.current?.closeRow?.() - delete activeSwipeRows.current[key] - } - }) + Object.keys(activeSwipeRows.current).forEach((key) => { + if (id !== key && activeSwipeRows.current[key]) { + activeSwipeRows.current[key]?.current?.closeRow?.(); + delete activeSwipeRows.current[key]; + } + }); }} onPress={() => { onListItemPress(item); @@ -608,11 +609,14 @@ export const CometChatList = React.forwardRef< } lastCall = setTimeout(() => { - props?.fetchNext().then((listItems: any) => { - resolve(listItems); - }).catch((error: any) => { - reject(error) - }); + props + ?.fetchNext() + .then((listItems: any) => { + resolve(listItems); + }) + .catch((error: any) => { + reject(error); + }); }, 500); lastReject = reject; }); @@ -623,13 +627,16 @@ export const CometChatList = React.forwardRef< * Returns a container of users if exists else returns the corresponding decorator message */ const getMessageContainer = () => { - let messageContainer: any= null; + let messageContainer: any = null; decoratorMessage === LOADING; if (list.length === 0 && decoratorMessage.toLowerCase() === LOADING) { if (LoadingStateView) return ; messageContainer = ( - + ); } else if ( @@ -641,14 +648,16 @@ export const CometChatList = React.forwardRef< ) : ( {emptyStateText} @@ -663,14 +672,16 @@ export const CometChatList = React.forwardRef< ) : ( {errorStateText} @@ -700,12 +711,12 @@ export const CometChatList = React.forwardRef< renderItem={ ListItemView ? ({ item, index, separators }) => ( - - ) + + ) : renderListItemView } keyExtractor={(item, index) => @@ -727,17 +738,19 @@ export const CometChatList = React.forwardRef< return (
); }); - -CometChatList.defaultProps = { - title: 'Title', - hideSearch: false, - requestBuilder: undefined, - searchRequestBuilder: undefined, - emptyStateText: localize('NO_USERS_FOUND'), // Note: Need to add "No Data found" in localize - errorStateText: localize('SOMETHING_WRONG'), - hideError: false, - onItemPress: () => { }, - onItemLongPress: () => { }, - onSelection: () => { }, - selectionMode: 'none', - listItemKey: 'uid', - listStyle: {}, -}; diff --git a/src/shared/views/CometChatListItem/CometChatListItem.tsx b/src/shared/views/CometChatListItem/CometChatListItem.tsx index c7772cb..2fc1235 100644 --- a/src/shared/views/CometChatListItem/CometChatListItem.tsx +++ b/src/shared/views/CometChatListItem/CometChatListItem.tsx @@ -13,9 +13,9 @@ import { ViewProps, //@ts-ignore } from 'react-native'; -import { CometChatAvatar } from "../../views/CometChatAvatar"; +import { CometChatAvatar } from '../../views/CometChatAvatar'; import { CometChatStatusIndicator } from '../../views/CometChatStatusIndicator'; -import { CometChatContext } from "../../CometChatContext"; +import { CometChatContext } from '../../CometChatContext'; //@ts-ignore import SwipeRow from '../../helper/SwipeRow'; import { ListItemStyle } from './ListItemStyle'; @@ -71,7 +71,6 @@ export const CometChatListItem = (props: CometChatListItemInterface) => { SubtitleView, options, TailView, - hideSeparator, separatorColor, headViewContainerStyle, tailViewContainerStyle, @@ -79,27 +78,18 @@ export const CometChatListItem = (props: CometChatListItemInterface) => { onPress, onLongPress, rowOpens, - activeSwipeRows + listItemStyle: listItemStyleProp = new ListItemStyle({}), + hideSeparator = true, + activeSwipeRows = {}, } = props; - - const swipeRowRef = useRef(null) - const defaultlistItemStyleProps = new ListItemStyle({ + + const swipeRowRef = useRef(null); + const listItemStyle = new ListItemStyle({ backgroundColor: theme.palette.getBackgroundColor(), titleColor: theme.palette.getAccent(), titleFont: theme.typography.name, + ...listItemStyleProp, }); - const listItemStyle = { - ...defaultlistItemStyleProps, - ...props.listItemStyle, - border: { - ...defaultlistItemStyleProps.border, - ...props.listItemStyle?.border, - }, - titleFont: { - ...defaultlistItemStyleProps.titleFont, - ...props.listItemStyle?.titleFont, - }, - }; const [swipeRowOptions, setSwipeRowOptions] = useState([]); let cancelClick = false; @@ -153,13 +143,15 @@ export const CometChatListItem = (props: CometChatListItemInterface) => { } + style={ + [ + Style.titleTextStyle, + { + color: listItemStyle.titleColor, + }, + listItemStyle.titleFont, + ] as StyleProp + } > {title?.trim()} @@ -190,8 +182,8 @@ export const CometChatListItem = (props: CometChatListItemInterface) => { }; const rowOpened = () => { - if(activeSwipeRows) activeSwipeRows[id] = swipeRowRef - rowOpens && rowOpens(id) + if (activeSwipeRows) activeSwipeRows[id] = swipeRowRef; + rowOpens && rowOpens(id); cancelClick = true; }; @@ -205,7 +197,7 @@ export const CometChatListItem = (props: CometChatListItemInterface) => { const TailViewFc = () => { return ( - {Boolean(TailView) && typeof(TailView) === 'function' && } + {Boolean(TailView) && typeof TailView === 'function' && } ); }; @@ -250,35 +242,45 @@ export const CometChatListItem = (props: CometChatListItemInterface) => { ); }; - let ListComponent: any = ((onPress && typeof onPress == 'function') || (onLongPress && typeof onLongPress == 'function')) ? TouchableOpacity : View; - let listComponentProps = ((onPress && typeof onPress == 'function') || (onLongPress && typeof onLongPress == 'function')) ? { - activeOpacity: 1, - onPress: clickHandler, - onLongPress: longPressHandler - } : {}; + let ListComponent: any = + (onPress && typeof onPress == 'function') || + (onLongPress && typeof onLongPress == 'function') + ? TouchableOpacity + : View; + let listComponentProps = + (onPress && typeof onPress == 'function') || + (onLongPress && typeof onLongPress == 'function') + ? { + activeOpacity: 1, + onPress: clickHandler, + onLongPress: longPressHandler, + } + : {}; let WrapperComponent = swipeRowOptions.length ? SwipeRow : React.Fragment; - let wrapperComponentProps = swipeRowOptions.length ? { - ref: swipeRowRef, - key: id, - onRowDidOpen: rowOpened, - onRowDidClose: rowClosed, - disableRightSwipe: true, - disableLeftSwipe: !swipeRowOptions.length, - rightOpenValue: 0 - translate - } : {}; + let wrapperComponentProps = swipeRowOptions.length + ? { + ref: swipeRowRef, + key: id, + onRowDidOpen: rowOpened, + onRowDidClose: rowClosed, + disableRightSwipe: true, + disableLeftSwipe: !swipeRowOptions.length, + rightOpenValue: 0 - translate, + } + : {}; return ( - + {swipeRowOptions.length !== 0 && ( @@ -309,12 +311,17 @@ export const CometChatListItem = (props: CometChatListItemInterface) => { {Boolean(title) && } - {Boolean(SubtitleView) && typeof(SubtitleView) === 'function' && } + {Boolean(SubtitleView) && typeof SubtitleView === 'function' && ( + + )} {Boolean(TailView) && } @@ -322,9 +329,3 @@ export const CometChatListItem = (props: CometChatListItemInterface) => { ); }; - -CometChatListItem.defaultProps = { - listItemStyle: new ListItemStyle({}), - hideSeparator: true, - activeSwipeRows: {} -}; diff --git a/src/shared/views/CometChatMediaRecorder/CometChatMediaRecorder.tsx b/src/shared/views/CometChatMediaRecorder/CometChatMediaRecorder.tsx index b8fcac0..94e9ee3 100644 --- a/src/shared/views/CometChatMediaRecorder/CometChatMediaRecorder.tsx +++ b/src/shared/views/CometChatMediaRecorder/CometChatMediaRecorder.tsx @@ -27,7 +27,7 @@ export interface CometChatMediaRecorderInterface { let timerIntervalId: any = null; export const CometChatMediaRecorder = (props: CometChatMediaRecorderInterface) => { const { - onClose, style, onPause, onPlay, onSend, onStop, onStart, mediaRecorderStyle, + onClose, style = new MediaRecorderStyle({}), onPause, onPlay, onSend, onStop, onStart, mediaRecorderStyle, pauseIconUrl, playIconUrl, recordIconUrl, deleteIconUrl, stopIconUrl, submitIconUrl } = props; @@ -263,7 +263,7 @@ export const CometChatMediaRecorder = (props: CometChatMediaRecorderInterface) = timerTextColor ? { color: timerTextColor } : { color: "#000" }, timerTextstyle && { fontStyle: timerTextstyle }, !Boolean(recordedFile) && { marginRight: 10 } - ] as TextStyle}>{formatTime(time)} + ] as TextStyle[]}>{formatTime(time)} item.toString()} @@ -308,8 +308,4 @@ export const CometChatMediaRecorder = (props: CometChatMediaRecorderInterface) = ) -} - -CometChatMediaRecorder.defaultProps = { - style: new MediaRecorderStyle({}), } \ No newline at end of file diff --git a/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx b/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx index 069f858..b345c22 100644 --- a/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx +++ b/src/shared/views/CometChatMessageBubble/CometChatMessageBubble.tsx @@ -73,10 +73,10 @@ export const CometChatMessageBubble = memo(({ LeadingView, BottomView, ThreadView, - alignment, + alignment = 'left', id, style -}: CometChatMessageBubbleInterface) => { +}: CometChatMessageBubbleInterface ) => { const {theme} = useContext(CometChatContext); @@ -143,9 +143,4 @@ export const CometChatMessageBubble = memo(({ ) -}) - -//@ts-ignore -CometChatMessageBubble.defaultProps = { - alignment: "left" -} \ No newline at end of file +}) \ No newline at end of file diff --git a/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx b/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx index e0251d1..01cf6e4 100644 --- a/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx +++ b/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx @@ -109,33 +109,41 @@ export const CometChatMessageInput = ( ) => { const { theme } = useContext(CometChatContext); const { - text, - placeHolderText, onChangeText, - style, maxHeight, SecondaryButtonView, AuxiliaryButtonView, - auxiliaryButtonAlignment, PrimaryButtonView, onSelectionChange, - messageInputRef + messageInputRef, + placeHolderText = localize('ENTER_YOUR_MESSAGE_HERE'), + auxiliaryButtonAlignment = 'right', + style = {}, + text = '', } = props; return ( - + ); }; - -CometChatMessageInput.defaultProps = { - placeHolderText: localize('ENTER_YOUR_MESSAGE_HERE'), - auxiliaryButtonAlignment: 'right', - style: {}, - text: '', -}; diff --git a/src/shared/views/CometChatReactions/CometChatReactions.tsx b/src/shared/views/CometChatReactions/CometChatReactions.tsx index 733b0ae..270d049 100644 --- a/src/shared/views/CometChatReactions/CometChatReactions.tsx +++ b/src/shared/views/CometChatReactions/CometChatReactions.tsx @@ -1,6 +1,6 @@ import React, { useContext } from 'react'; import { Text, TextStyle, TouchableOpacity, View } from 'react-native'; -import { CometChatContext } from "../../CometChatContext"; +import { CometChatContext } from '../../CometChatContext'; import { Styles } from './style'; //@ts-ignore import { CometChat } from '@cometchat/chat-sdk-react-native'; @@ -10,17 +10,24 @@ import { MessageBubbleAlignmentType } from '../../base/Types'; export interface CometChatReactionsInterface { messageObject?: CometChat.BaseMessage; style?: ReactionsStyleInterface; - onReactionPress?: (reaction: CometChat.ReactionCount, messageObject: CometChat.BaseMessage) => void; - onReactionLongPress?: (reaction: CometChat.ReactionCount, messageObject: CometChat.BaseMessage) => void; + onReactionPress?: ( + reaction: CometChat.ReactionCount, + messageObject: CometChat.BaseMessage + ) => void; + onReactionLongPress?: ( + reaction: CometChat.ReactionCount, + messageObject: CometChat.BaseMessage + ) => void; alignment?: MessageBubbleAlignmentType; } const CometChatReactions = (props: CometChatReactionsInterface) => { const { - messageObject, - style, onReactionPress, onReactionLongPress, alignment, + + messageObject = null, + style = {}, } = props; const { theme } = useContext(CometChatContext); @@ -32,7 +39,8 @@ const CometChatReactions = (props: CometChatReactionsInterface) => { countColor: style?.countColor || theme?.palette?.getAccent(), countFont: style?.countFont || theme?.typography?.text1, backgroundColor: style?.backgroundColor || theme?.palette?.getAccent100(), - primaryBackgroundColor: style?.primaryBackgroundColor || theme?.palette?.getPrimary150(), + primaryBackgroundColor: + style?.primaryBackgroundColor || theme?.palette?.getPrimary150(), primaryBorder: style?.primaryBorder || { borderWidth: 1, borderColor: theme?.palette?.getPrimary500(), @@ -56,42 +64,60 @@ const CometChatReactions = (props: CometChatReactionsInterface) => { const reactionView = (reactionObj: any, index: any) => { let count: number = reactionObj?.count; let Emoji: string = reactionObj?.reaction; - let Count: JSX.Element = - {count} - ; + let Count: JSX.Element = ( + + {count} + + ); return count >= 1 ? ( - + { - onReactionPress && messageObject && onReactionPress(reactionObj, messageObject); + onReactionPress && + messageObject && + onReactionPress(reactionObj, messageObject); }} onLongPress={() => { - onReactionLongPress && messageObject && onReactionLongPress(reactionObj, messageObject); + onReactionLongPress && + messageObject && + onReactionLongPress(reactionObj, messageObject); }} key={Math.random()} style={[ Styles.messageReactionsStyle, { - backgroundColor: reactionObj?.reactedByMe ? primaryBackgroundColor : backgroundColor, - marginRight: 0, marginBottom: 0, + backgroundColor: reactionObj?.reactedByMe + ? primaryBackgroundColor + : backgroundColor, + marginRight: 0, + marginBottom: 0, ...(reactionObj?.reactedByMe ? primaryBorder : border), - } + }, ]} > - + {Emoji} {Count} @@ -100,43 +126,63 @@ const CometChatReactions = (props: CometChatReactionsInterface) => { }; const extraEmojisView = (numberOfExtraEmojis: number) => { - let extraEmojis = reactionRef.current.slice(reactionRef.current.length - numberOfExtraEmojis); - let hasReactedByMe = extraEmojis.some((reaction: any) => reaction.reactedByMe); + let extraEmojis = reactionRef.current.slice( + reactionRef.current.length - numberOfExtraEmojis + ); + let hasReactedByMe = extraEmojis.some( + (reaction: any) => reaction.reactedByMe + ); - let totalCount = reactionRef.current.reduce((acc: any, curr: any) => acc + curr.count, 0); - let AllObj = new CometChat.ReactionCount("All", totalCount, false); // { reaction: "All", count: totalCount }; + let totalCount = reactionRef.current.reduce( + (acc: any, curr: any) => acc + curr.count, + 0 + ); + let AllObj = new CometChat.ReactionCount('All', totalCount, false); // { reaction: "All", count: totalCount }; return ( - + { - onReactionLongPress && messageObject && onReactionLongPress(AllObj, messageObject); + onReactionLongPress && + messageObject && + onReactionLongPress(AllObj, messageObject); }} onLongPress={() => { - onReactionLongPress && messageObject && onReactionLongPress(AllObj, messageObject); + onReactionLongPress && + messageObject && + onReactionLongPress(AllObj, messageObject); }} key={Math.random()} style={[ Styles.messageReactionsStyle, { - backgroundColor: hasReactedByMe ? primaryBackgroundColor : backgroundColor, + backgroundColor: hasReactedByMe + ? primaryBackgroundColor + : backgroundColor, ...(hasReactedByMe ? primaryBorder : border), - marginRight: 0, marginBottom: 0, + marginRight: 0, + marginBottom: 0, paddingHorizontal: 6, }, ]} > - + +{numberOfExtraEmojis} - ) - } + + ); + }; React.useEffect(() => { reactionRef.current = messageObject?.getReactions() || []; @@ -144,23 +190,31 @@ const CometChatReactions = (props: CometChatReactionsInterface) => { if (messageReactions.length > 0) { if (messageReactions.length > 4) { let newMessageReactions: any[] = [...messageReactions].slice(0, 3); - newMessageReactions.push(extraEmojisView(reactionRef.current.length - 3)); + newMessageReactions.push( + extraEmojisView(reactionRef.current.length - 3) + ); setReactionList(newMessageReactions); } else setReactionList(messageReactions); } }, [messageObject]); return reactionList.length ? ( - + {reactionList} ) : null; }; -// Specifies the default values for props: -CometChatReactions.defaultProps = { - messageObject: null, - style: {}, -}; - export { CometChatReactions }; diff --git a/src/shared/views/CometChatReceipt/CometChatReceipt.tsx b/src/shared/views/CometChatReceipt/CometChatReceipt.tsx index 7ec2ea9..30c95dd 100644 --- a/src/shared/views/CometChatReceipt/CometChatReceipt.tsx +++ b/src/shared/views/CometChatReceipt/CometChatReceipt.tsx @@ -25,13 +25,20 @@ export interface CometChatReceiptInterface { style?: { height?: string | number; width?: string | number; - tintColor?: string - } + tintColor?: string; + }; } export const CometChatReceipt = (props: CometChatReceiptInterface) => { - const { waitIcon, sentIcon, deliveredIcon, readIcon, errorIcon, receipt, style } = - props; + const { + style, + waitIcon = ICONS.WAITING, + sentIcon = ICONS.GREY_TICK, + deliveredIcon = ICONS.GREY_DOUBLE_TICK, + readIcon = ICONS.BLUE_DOUBLE_TICK, + errorIcon = ICONS.ERROR_TICK, + receipt = null, + } = props; const { theme } = useContext(CometChatContext); @@ -74,16 +81,17 @@ export const CometChatReceipt = (props: CometChatReceiptInterface) => { } else if (typeof icon === 'number') { imageSource = icon; } - return ; + return ( + + ); } return null; }; - -CometChatReceipt.defaultProps = { - waitIcon: ICONS.WAITING, - sentIcon: ICONS.GREY_TICK, - deliveredIcon: ICONS.GREY_DOUBLE_TICK, - readIcon: ICONS.BLUE_DOUBLE_TICK, - errorIcon: ICONS.ERROR_TICK, - receipt: null, -}; diff --git a/src/shared/views/CometChatStatusIndicator/CometChatStatusIndicator.tsx b/src/shared/views/CometChatStatusIndicator/CometChatStatusIndicator.tsx index 79e8d71..b265333 100644 --- a/src/shared/views/CometChatStatusIndicator/CometChatStatusIndicator.tsx +++ b/src/shared/views/CometChatStatusIndicator/CometChatStatusIndicator.tsx @@ -1,6 +1,13 @@ import React from 'react'; // @ts-ignore -import { Image, View, StyleProp, ViewStyle, ViewProps, ImageStyle } from 'react-native'; +import { + Image, + View, + StyleProp, + ViewStyle, + ViewProps, + ImageStyle, +} from 'react-native'; import { Styles } from './styles'; import { StatusIndicatorStyle } from './StatusIndicatorStyle'; import { ImageType } from '../../base'; @@ -23,13 +30,18 @@ export interface CometChatStatusIndicatorInterface { export const CometChatStatusIndicator = ( props: CometChatStatusIndicatorInterface ) => { - const { backgroundImage, backgroundColor } = props; + const { + backgroundColor, + + backgroundImage = undefined, + style: styleProp = new StatusIndicatorStyle({}), + } = props; const defaultStyleProps = new StatusIndicatorStyle({}); const style = { ...defaultStyleProps, - ...(props.style as object), ...(backgroundColor ? { backgroundColor } : {}), + ...styleProp as {} }; const getView = () => { @@ -57,8 +69,3 @@ export const CometChatStatusIndicator = ( return getView(); }; - -CometChatStatusIndicator.defaultProps = { - backgroundImage: '', - style: new StatusIndicatorStyle({}), -}; diff --git a/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx b/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx index 375d810..5322af6 100644 --- a/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx +++ b/src/shared/views/CometChatTextBubble/CometChatTextBubble.tsx @@ -55,7 +55,7 @@ export interface CometChatTextBubbleInterface { export const CometChatTextBubble = (props: CometChatTextBubbleInterface) => { const { - text, + text = "", textContainerStyle, textFormatters } = props; @@ -103,11 +103,7 @@ export const CometChatTextBubble = (props: CometChatTextBubbleInterface) => { border, textContainerStyle ] as ViewProps}> - {formattedText} + {formattedText} -} - -CometChatTextBubble.defaultProps = { - text: "" } \ No newline at end of file diff --git a/src/shared/views/SwipeRow/SwipeRow.tsx b/src/shared/views/SwipeRow/SwipeRow.tsx index c046bea..3503669 100644 --- a/src/shared/views/SwipeRow/SwipeRow.tsx +++ b/src/shared/views/SwipeRow/SwipeRow.tsx @@ -21,15 +21,12 @@ export const CometChatSwipeRow: React.FC = ( const [translate, setTranslate] = useState(0); const { theme } = useContext(CometChatContext); - const { id, options, children } = props; - - // const defaultlistItemStyleProps = new ListItemStyle({ - // backgroundColor: theme.palette.getBackgroundColor(), - // titleColor: theme.palette.getAccent(), - // }); - const listItemStyle = { - ...props.listItemStyle, - }; + const { + id, + options, + children, + listItemStyle= {}, + } = props; const [swipeRowOptions, setSwipeRowOptions] = useState([]); let cancelClick = false; @@ -119,7 +116,6 @@ export const CometChatSwipeRow: React.FC = ( data={swipeRowOptions.slice(0, 3)} renderItem={OptionsListItem} keyExtractor={(_, i) => _.id ?? i} - /> )} @@ -128,7 +124,3 @@ export const CometChatSwipeRow: React.FC = ( ); }; - -CometChatSwipeRow.defaultProps = { - listItemStyle: {}, -};