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
2 changes: 1 addition & 1 deletion examples/E2ETestApp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"react-native-svg": "^15.15.5",
"react-native-teleport": "^1.2.2",
"react-native-worklets": "^0.13.0",
"stream-chat": "^10.0.0",
"stream-chat": "^10.0.1",
"stream-chat-react-native": "workspace:^"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion examples/ExpoChatGPTSample/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"react-native-svg": "15.15.5",
"react-native-teleport": "^1.2.2",
"react-native-worklets": "0.13.0",
"stream-chat": "^10.0.0",
"stream-chat": "^10.0.1",
"stream-chat-expo": "workspace:^",
"stream-chat-react-native-core": "workspace:^",
"victory-native": "^42.0.1"
Expand Down
2 changes: 1 addition & 1 deletion examples/ExpoMessaging/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"react-native-teleport": "^1.2.2",
"react-native-web": "~0.21.4",
"react-native-worklets": "0.13.0",
"stream-chat": "^10.0.0",
"stream-chat": "^10.0.1",
"stream-chat-expo": "workspace:^",
"stream-chat-react-native-core": "workspace:^"
},
Expand Down
2 changes: 1 addition & 1 deletion examples/SampleApp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
"react-native-teleport": "^1.2.2",
"react-native-video": "^6.19.3",
"react-native-worklets": "^0.13.0",
"stream-chat": "^10.0.0",
"stream-chat": "^10.0.1",
"stream-chat-react-native": "workspace:^",
"stream-chat-react-native-core": "workspace:^"
},
Expand Down
152 changes: 0 additions & 152 deletions examples/SampleApp/src/components/NewDirectMessagingSendButton.tsx

This file was deleted.

6 changes: 6 additions & 0 deletions examples/SampleApp/src/hooks/useChatClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { SqliteClient } from 'stream-chat-react-native';
import { USER_TOKENS, USERS } from '../ChatUsers';
import type { LoginConfig } from '../types';
import AsyncStore from '../utils/AsyncStore';
import { createOnFirstSend } from '../utils/startConversation';
import { clearLastToken, getTokenOrProvider, SAMPLE_APP_API_KEY } from '../utils/tokenProvider';

const messaging = getMessaging();
Expand Down Expand Up @@ -106,6 +107,11 @@ export const useChatClient = () => {
// `linkPreviews.enabled` is deliberately not set: it defaults to `true` in v10 and is ANDed with
// the channel type's `url_enrichment`, so the server has the final say either way.
client.config.set({
// Creates a new conversation on its first message (see `NewDirectMessagingScreen`). It
// applies to every channel, and every other channel's messages are sent the usual way.
channel: {
requestHandlers: { sendMessageRequest: createOnFirstSend(client) },
},
messageComposer: {
drafts: { enabled: true },
},
Expand Down
9 changes: 7 additions & 2 deletions examples/SampleApp/src/screens/ChannelScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,13 @@ export type ChannelScreenProps = {

export type ChannelHeaderProps = {
channel: StreamChatChannel;
/** Whether a parent already applies the top safe-area inset. */
inSafeArea?: boolean;
/** Replaces the default back behaviour. */
onBack?: () => void;
};

const ChannelHeader: React.FC<ChannelHeaderProps> = ({ channel }) => {
export const ChannelHeader: React.FC<ChannelHeaderProps> = ({ channel, inSafeArea, onBack }) => {
const { closePicker } = useAttachmentPickerContext();
const membersStatus = useChannelMembersStatus(channel);
const displayName = useChannelPreviewDisplayName(channel);
Expand Down Expand Up @@ -91,7 +95,8 @@ const ChannelHeader: React.FC<ChannelHeaderProps> = ({ channel }) => {

return (
<ScreenHeader
onBack={onBackPress}
inSafeArea={inSafeArea}
onBack={onBack ?? onBackPress}
// eslint-disable-next-line react/no-unstable-nested-components
RightContent={() => (
<Pressable
Expand Down
64 changes: 50 additions & 14 deletions examples/SampleApp/src/screens/NewDirectMessagingScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,20 @@ import { SafeAreaView } from 'react-native-safe-area-context';
import { useFocusEffect } from '@react-navigation/native';
import type { RouteProp } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import type { Channel as StreamChatChannel } from 'stream-chat';
import type { ChannelStateData, Channel as StreamChatChannel } from 'stream-chat';
import {
Channel,
MessageComposer,
MessageList,
UserAdd,
WithComponents,
useChannelContext,
useStateStore,
useTheme,
TextInputRef,
} from 'stream-chat-react-native';

import { NewDirectMessagingSendButton } from '../components/NewDirectMessagingSendButton';
import { ChannelHeader } from './ChannelScreen';

import { RoundButton } from '../components/RoundButton';
import { ScreenHeader } from '../components/ScreenHeader';
import { SelectedUserTag } from '../components/UserSearch/SelectedUserTag';
Expand All @@ -27,8 +29,8 @@ import { useUserSearchContext } from '../context/UserSearchContext';
import { Group } from '../icons/Group';
import { User } from '../icons/User';
import { useLegacyColors } from '../theme/useLegacyColors';

import type { StackNavigatorParamList } from '../types';
import { startLocalConversation } from '../utils/startConversation';

const styles = StyleSheet.create({
container: {
Expand Down Expand Up @@ -88,6 +90,38 @@ const styles = StyleSheet.create({
},
});

// A conversation that doesn't exist yet has no capabilities from the server, so these let the
// composer send text and links.
const provisionalCapabilities = { sendLinks: true, sendMessage: true };

const initializedSelector = ({ initialized }: ChannelStateData) => ({ initialized });

type NewConversationHeaderProps = {
onBack: () => void;
startedAsDraft: boolean;
userSearch: React.ReactNode;
};

/**
* Shows the user search until the conversation started on this screen is created by its first
* message, then the channel's header. An existing conversation keeps the user search, so the
* recipients can still be changed.
*/
const NewConversationHeader = ({
onBack,
startedAsDraft,
userSearch,
}: NewConversationHeaderProps) => {
const { channel } = useChannelContext();
// Re-renders when `watch()` creates the channel, which ends `isProvisional`.
useStateStore(channel.state, initializedSelector);

if (startedAsDraft && !channel.isProvisional) {
return <ChannelHeader channel={channel} inSafeArea onBack={onBack} />;
}
return <>{userSearch}</>;
};

export const EmptyMessagesIndicator = () => {
const { grey } = useLegacyColors();
return (
Expand Down Expand Up @@ -212,13 +246,11 @@ export const NewDirectMessagingScreen: React.FC<NewDirectMessagingScreenProps> =
currentChannel.current = channels[0];
isDraft.current = false;
} else {
// Channel doesn't exist. `<Channel>` leaves a channel built from members alone, and the
// send button creates it with the first message.
// Channel doesn't exist. `<Channel>` leaves a channel built from members alone, and
// `createOnFirstSend` creates it with the first message, without leaving this screen.
isDraft.current = true;

currentChannel.current = chatClient.channel('messaging', {
members: members.map((user_id) => ({ user_id })),
});
currentChannel.current = startLocalConversation(chatClient, members);
}

if (messageInputRef.current) {
Expand Down Expand Up @@ -384,16 +416,20 @@ export const NewDirectMessagingScreen: React.FC<NewDirectMessagingScreenProps> =
channel={currentChannel.current}
enforceUniqueReaction
keyboardVerticalOffset={0}
overrideOwnCapabilities={{ sendMessage: true }}
overrideOwnCapabilities={
currentChannel.current.isProvisional ? provisionalCapabilities : undefined
}
setInputRef={(ref) => (messageInputRef.current = ref)}
>
{renderUserSearch({ inSafeArea: true })}
<NewConversationHeader
onBack={onBackPress}
startedAsDraft={isDraft.current}
userSearch={renderUserSearch({ inSafeArea: true })}
/>
{results && results.length >= 0 && !focusOnSearchInput && focusOnMessageInput && (
<MessageList />
)}
<WithComponents overrides={{ SendButton: NewDirectMessagingSendButton }}>
<MessageComposer />
</WithComponents>
<MessageComposer />
</Channel>
</SafeAreaView>
);
Expand Down
46 changes: 46 additions & 0 deletions examples/SampleApp/src/utils/startConversation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { localMessageToNewMessagePayload } from 'stream-chat';
import type { Channel, OperationRequestFn, StreamChat } from 'stream-chat';

/**
* A conversation with `memberIds` that exists only in this client until its first message: a
* channel created from its members, without an id, so it's provisional (`Channel.isProvisional`).
* If the client already has a loaded conversation created from exactly these members,
* `client.channel()` returns that one instead.
*/
export const startLocalConversation = (client: StreamChat, memberIds: string[]): Channel => {
const channel = client.channel('messaging', {
members: memberIds.map((user_id) => ({ user_id })),
});
if (!channel.isProvisional || channel.messagePaginator.hasResults) {
return channel;
}
// Nothing is loaded for a channel the server doesn't have yet, so an empty first page, shorter
// than a page, makes the message list show its empty state with nothing older to load.
channel.messagePaginator.placeExternalQueryPage([], channel.messagePaginator.pageSize);
return channel;
};

/**
* Sends the first message of a provisional channel. `Channel.watch()` creates the channel on the
* server and resolves with the instance to use from then on, which is this one, or the one that
* superseded it when the client already had the channel under its real cid. Messages in every
* other channel are sent the usual way.
*/
export const createOnFirstSend =
(client: StreamChat): OperationRequestFn<'send'> =>
async (params, defaultRequest) => {
const channel = client.channelManager.get(params.localMessage.cid);
if (!channel?.isProvisional) {
return defaultRequest(params);
}

const created = await channel.watch();
// Shows the new channel in the channel lists whose filters it matches.
client.channelManager.ingestChannel(created);

const { message } = await created.sendMessage({
message: params.message ?? localMessageToNewMessagePayload(params.localMessage),
...params.options,
});
return { message };
};
Loading
Loading