Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions examples/SampleApp/src/components/MessageInfoBottomSheet.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import React, { useMemo } from 'react';
import BottomSheet, { BottomSheetFlatList } from '@gorhom/bottom-sheet';
import { BottomSheetView } from '@gorhom/bottom-sheet';
import {
Avatar,
BottomSheetModal,
useChatContext,
useMessageDeliveredData,
useMessageReadData,
useTheme,
} from 'stream-chat-react-native';
import { LocalMessage, UserResponse } from 'stream-chat';
import { StyleSheet, Text, View } from 'react-native';
import { FlatList, StyleSheet, Text, View } from 'react-native';

const renderUserItem = ({ item }: { item: UserResponse }) => (
<View style={styles.userItem}>
Expand All @@ -24,10 +23,12 @@ const renderEmptyText = ({ text }: { text: string }) => (

export const MessageInfoBottomSheet = ({
message,
ref,
visible,
onClose,
}: {
message?: LocalMessage;
ref: React.RefObject<BottomSheet | null>;
visible: boolean;
onClose: () => void;
}) => {
const {
theme: { colors },
Expand All @@ -45,26 +46,26 @@ export const MessageInfoBottomSheet = ({
}, [readStatus, client?.user?.id]);

return (
<BottomSheet enablePanDownToClose ref={ref} index={-1} snapPoints={['50%']}>
<BottomSheetView style={[styles.container, { backgroundColor: colors.white_smoke }]}>
<BottomSheetModal visible={visible} onClose={onClose}>
<View style={[styles.container, { backgroundColor: colors.white_smoke }]}>
<Text style={styles.title}>Read</Text>
<BottomSheetFlatList
<FlatList
data={otherReadUsers}
renderItem={renderUserItem}
keyExtractor={(item) => item.id}
style={styles.flatList}
ListEmptyComponent={renderEmptyText({ text: 'No one has read this message.' })}
/>
<Text style={styles.title}>Delivered</Text>
<BottomSheetFlatList
<FlatList
data={otherDeliveredToUsers}
renderItem={renderUserItem}
keyExtractor={(item) => item.id}
style={styles.flatList}
ListEmptyComponent={renderEmptyText({ text: 'The message was not delivered to anyone.' })}
/>
</BottomSheetView>
</BottomSheet>
</View>
</BottomSheetModal>
);
};

Expand Down
27 changes: 16 additions & 11 deletions examples/SampleApp/src/screens/ChannelScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import React, { useCallback, useEffect, useState } from 'react';
import type { LocalMessage, Channel as StreamChatChannel } from 'stream-chat';
import { RouteProp, useFocusEffect, useNavigation } from '@react-navigation/native';
import {
Expand Down Expand Up @@ -33,7 +33,6 @@ import { channelMessageActions } from '../utils/messageActions.tsx';
import { MessageLocation } from '../components/LocationSharing/MessageLocation.tsx';
import { useStreamChatContext } from '../context/StreamChatContext.tsx';
import { CustomAttachmentPickerSelectionBar } from '../components/AttachmentPickerSelectionBar.tsx';
import BottomSheet from '@gorhom/bottom-sheet';
import { MessageInfoBottomSheet } from '../components/MessageInfoBottomSheet.tsx';

export type ChannelScreenNavigationProp = NativeStackNavigationProp<
Expand Down Expand Up @@ -130,6 +129,7 @@ export const ChannelScreen: React.FC<ChannelScreenProps> = ({
} = useTheme();
const { t } = useTranslationContext();
const { setThread } = useStreamChatContext();
const [modalVisible, setModalVisible] = useState(false);
const [selectedMessage, setSelectedMessage] = useState<LocalMessage | undefined>(undefined);

const [channel, setChannel] = useState<StreamChatChannel | undefined>(channelFromProp);
Expand Down Expand Up @@ -186,15 +186,14 @@ export const ChannelScreen: React.FC<ChannelScreenProps> = ({
[channel, navigation, setThread],
);

const messageInfoBottomSheetRef = useRef<BottomSheet>(null);
const handleMessageInfo = useCallback((message: LocalMessage) => {
setSelectedMessage(message);
setModalVisible(true);
}, []);

const handleMessageInfo = useCallback(
(message: LocalMessage) => {
setSelectedMessage(message);
messageInfoBottomSheetRef.current?.snapToIndex(1);
},
[messageInfoBottomSheetRef],
);
const handleMessageInfoClose = useCallback(() => {
setModalVisible(false);
}, []);

const messageActions = useCallback(
(params: MessageActionsParams) => {
Expand Down Expand Up @@ -249,7 +248,13 @@ export const ChannelScreen: React.FC<ChannelScreenProps> = ({
)}
<AITypingIndicatorView channel={channel} />
<MessageInput />
<MessageInfoBottomSheet message={selectedMessage} ref={messageInfoBottomSheetRef} />
{modalVisible && (
<MessageInfoBottomSheet
visible={modalVisible}
message={selectedMessage}
onClose={handleMessageInfoClose}
/>
)}
</Channel>
</View>
);
Expand Down
114 changes: 83 additions & 31 deletions package/src/components/Channel/Channel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ import {
isImagePickerAvailable,
NativeHandlers,
} from '../../native';
import * as dbApi from '../../store/apis';
import { ChannelUnreadState, FileTypes } from '../../types/types';
import { addReactionToLocalState } from '../../utils/addReactionToLocalState';
import { compressedImageURI } from '../../utils/compressImage';
Expand Down Expand Up @@ -433,6 +432,20 @@ export type ChannelPropsWithContext = Pick<ChannelContextValue, 'channel'> &
messageData: StreamMessage,
options?: SendMessageOptions,
) => Promise<SendMessageAPIResponse>;

/**
* A method invoked just after the first optimistic update of a new message,
* but before any other HTTP requests happen. Can be used to do extra work
* (such as creating a channel, or editing a message) before the local message
* is sent.
* @param channelId
* @param messageData Message object
*/
preSendMessageRequest?: (options: {
localMessage: LocalMessage;
message: StreamMessage;
options?: SendMessageOptions;
}) => Promise<SendMessageAPIResponse>;
/**
* Overrides the Stream default update message request (Advanced usage only)
* @param channelId
Expand Down Expand Up @@ -492,10 +505,24 @@ export type ChannelPropsWithContext = Pick<ChannelContextValue, 'channel'> &
* Tells if channel is rendering a thread list
*/
threadList?: boolean;
/**
* A boolean signifying whether the Channel component should run channel.watch()
* whenever it mounts up a new channel. If set to `false`, it is the integrator's
* responsibility to run channel.watch() if they wish to receive WebSocket events
* for that channel.
*
* Can be particularly useful whenever we are viewing channels in a read-only mode
* or perhaps want them in an ephemeral state (i.e not created until the first message
* is sent).
*/
initializeOnMount?: boolean;
} & Partial<
Pick<
InputMessageInputContextValue,
'openPollCreationDialog' | 'CreatePollContent' | 'StopMessageStreamingButton'
| 'openPollCreationDialog'
| 'CreatePollContent'
| 'StopMessageStreamingButton'
| 'allowSendBeforeAttachmentsUpload'
>
>;

Expand Down Expand Up @@ -567,10 +594,12 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
doFileUploadRequest,
doMarkReadRequest,
doSendMessageRequest,
preSendMessageRequest,
doUpdateMessageRequest,
EmptyStateIndicator = EmptyStateIndicatorDefault,
enableMessageGroupingByUser = true,
enableOfflineSupport,
allowSendBeforeAttachmentsUpload = enableOfflineSupport,
enableSwipeToReply = true,
enforceUniqueReaction = false,
FileAttachment = FileAttachmentDefault,
Expand Down Expand Up @@ -715,6 +744,7 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
VideoThumbnail = VideoThumbnailDefault,
isOnline,
maximumMessageLimit,
initializeOnMount = true,
} = props;

const { thread: threadProps, threadInstance } = threadFromProps;
Expand Down Expand Up @@ -881,7 +911,7 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
}

// only update channel state if the events are not the previously subscribed useEffect's subscription events
if (channel && channel.initialized) {
if (channel) {
// we skip the new message events if we've already done an optimistic update for the new message
if (event.type === 'message.new' || event.type === 'notification.message_new') {
const messageId = event.message?.id ?? '';
Expand Down Expand Up @@ -915,13 +945,14 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
}
let errored = false;

if (!channel.initialized || !channel.state.isUpToDate) {
if ((!channel.initialized || !channel.state.isUpToDate) && initializeOnMount) {
try {
await channel?.watch();
} catch (err) {
console.warn('Channel watch request failed with error:', err);
setError(true);
errored = true;
channel.offlineMode = true;
}
}

Expand Down Expand Up @@ -1078,7 +1109,7 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
});

const resyncChannel = useStableCallback(async () => {
if (!channel || syncingChannelRef.current) {
if (!channel || syncingChannelRef.current || (!channel.initialized && !channel.offlineMode)) {
return;
}
syncingChannelRef.current = true;
Expand All @@ -1099,6 +1130,7 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
limit: channelMessagesState.messages.length + 30,
},
});
channel.offlineMode = false;
}

if (!thread) {
Expand Down Expand Up @@ -1300,9 +1332,13 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
attachment.image_url = uploadResponse.file;
delete attachment.originalFile;

await dbApi.updateMessage({
message: { ...updatedMessage, cid: channel.cid },
});
client.offlineDb?.executeQuerySafely(
(db) =>
db.updateMessage({
message: { ...updatedMessage, cid: channel.cid },
}),
{ method: 'updateMessage' },
);
}

if (attachment.type !== FileTypes.Image && file?.uri) {
Expand All @@ -1321,9 +1357,13 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
}

delete attachment.originalFile;
await dbApi.updateMessage({
message: { ...updatedMessage, cid: channel.cid },
});
client.offlineDb?.executeQuerySafely(
(db) =>
db.updateMessage({
message: { ...updatedMessage, cid: channel.cid },
}),
{ method: 'updateMessage' },
);
}
}
}
Expand All @@ -1344,7 +1384,7 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
retrying?: boolean;
}) => {
let failedMessageUpdated = false;
const handleFailedMessage = async () => {
const handleFailedMessage = () => {
if (!failedMessageUpdated) {
const updatedMessage = {
...localMessage,
Expand All @@ -1355,11 +1395,13 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
threadInstance?.upsertReplyLocally?.({ message: updatedMessage });
optimisticallyUpdatedNewMessages.delete(localMessage.id);

if (enableOfflineSupport) {
await dbApi.updateMessage({
message: updatedMessage,
});
}
client.offlineDb?.executeQuerySafely(
(db) =>
db.updateMessage({
message: updatedMessage,
}),
{ method: 'updateMessage' },
);

failedMessageUpdated = true;
}
Expand Down Expand Up @@ -1397,11 +1439,14 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
status: MessageStatusTypes.RECEIVED,
};

if (enableOfflineSupport) {
await dbApi.updateMessage({
message: { ...newMessageResponse, cid: channel.cid },
});
}
client.offlineDb?.executeQuerySafely(
(db) =>
db.updateMessage({
message: { ...newMessageResponse, cid: channel.cid },
}),
{ method: 'updateMessage' },
);

if (retrying) {
replaceMessage(localMessage, newMessageResponse);
} else {
Expand All @@ -1425,16 +1470,22 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
threadInstance?.upsertReplyLocally?.({ message: localMessage });
optimisticallyUpdatedNewMessages.add(localMessage.id);

if (enableOfflineSupport) {
// While sending a message, we add the message to local db with failed status, so that
// if app gets closed before message gets sent and next time user opens the app
// then user can see that message in failed state and can retry.
// If succesfull, it will be updated with received status.
await dbApi.upsertMessages({
messages: [{ ...localMessage, cid: channel.cid, status: MessageStatusTypes.FAILED }],
});
}
// While sending a message, we add the message to local db with failed status, so that
// if app gets closed before message gets sent and next time user opens the app
// then user can see that message in failed state and can retry.
// If succesfull, it will be updated with received status.
client.offlineDb?.executeQuerySafely(
(db) =>
db.upsertMessages({
// @ts-ignore
messages: [{ ...localMessage, cid: channel.cid, status: MessageStatusTypes.FAILED }],
}),
{ method: 'upsertMessages' },
);

if (preSendMessageRequest) {
await preSendMessageRequest({ localMessage, message, options });
}
await sendMessageRequest({ localMessage, message, options });
},
);
Expand Down Expand Up @@ -1756,6 +1807,7 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =

const inputMessageInputContext = useCreateInputMessageInputContext({
additionalTextInputProps,
allowSendBeforeAttachmentsUpload,
asyncMessagesLockDistance,
asyncMessagesMinimumPressDuration,
asyncMessagesMultiSendEnabled,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ export const useCreateChannelContext = ({

const readUsers = Object.values(read);
const readUsersLength = readUsers.length;
const readUsersLastReads = readUsers.map(({ last_read }) => last_read.toISOString()).join();
const readUsersLastReads = readUsers
.map(({ last_read }) => last_read?.toISOString() ?? '')
.join();
const stringifiedChannelUnreadState = JSON.stringify(channelUnreadState);

const channelContext: ChannelContextValue = useMemo(
Expand Down
Loading
Loading