Skip to content

Commit

Permalink
Cleanup, fixes and adjustments
Browse files Browse the repository at this point in the history
  • Loading branch information
arnautov-anton committed May 29, 2024
1 parent ab46f34 commit 9c6acc3
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 58 deletions.
18 changes: 0 additions & 18 deletions examples/vite/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,22 +96,4 @@ const Threads = () => {
);
};

/* {activeThread && (
<ThreadProvider thread={activeThread}>
<ThreadHeader />
<MessageList />
<MessageInput />
</ThreadProvider>
)} */

// const Wrapper = () => {
// const { activeThread } = useThreadContext();

// console.log({ activeThread });

// if (!activeThread) return;

// return <VirtualizedMessageList />;
// };

export default App;
31 changes: 19 additions & 12 deletions examples/vite/src/index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ body,
display: flex;
height: 100%;

.str-chat__thread-list {
width: 50%;
height: 100%;
}
// .str-chat__thread-list {
// width: 50%;
// height: 100%;
// }

.str-chat__thread-list-item {
all: unset;
Expand Down Expand Up @@ -99,7 +99,7 @@ body,
.str-chat__thread {
width: 100%;
height: 100%;
position: fixed;
position: absolute;
z-index: 1;
}

Expand All @@ -122,6 +122,18 @@ body,
}
}

.str-chat.threads {
display: flex;
height: 100%;
width: 100%;

.vml {
display: flex;
flex-direction: column;
width: 70%;
}
}

@media screen and (min-width: 768px) {
//.str-chat__channel-list.thread-open {
// &.menu-open {
Expand All @@ -146,11 +158,6 @@ body,
position: initial;
z-index: 0;
}

.str-chat__thread {
position: initial;
z-index: 0;
}
}

@media screen and (min-width: 1024px) {
Expand All @@ -162,8 +169,8 @@ body,

.str-chat__thread {
width: 45%;
//position: initial;
//z-index: 0;
position: initial;
z-index: 0;
}

.str-chat__channel-header .str-chat__header-hamburger {
Expand Down
9 changes: 7 additions & 2 deletions src/components/Channel/Channel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ import type { URLEnrichmentConfig } from '../MessageInput/hooks/useLinkPreviews'
import { defaultReactionOptions, ReactionOptions } from '../Reactions';
import { EventComponent } from '../EventComponent';
import { DateSeparator } from '../DateSeparator';
import { useThreadContext } from '../Threads';

type ChannelPropsForwardedToComponentContext<
StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics
Expand Down Expand Up @@ -399,6 +400,8 @@ const ChannelInner = <
windowsEmojiClass,
} = useChannelContainerClasses({ customClasses });

const thread = useThreadContext();

const [channelConfig, setChannelConfig] = useState(channel.getConfig());
const [notifications, setNotifications] = useState<ChannelNotifications>([]);
const [quotedMessage, setQuotedMessage] = useState<StreamMessage<StreamChatGenerics>>();
Expand Down Expand Up @@ -1055,20 +1058,22 @@ const ChannelInner = <
channel.state.filterErrorMessages();

const messagePreview = {
__html: text,
attachments,
created_at: new Date(),
html: text,
id: customMessageData?.id ?? `${client.userID}-${nanoid()}`,
mentioned_users,
parent_id: parent?.id,
reactions: [],
status: 'sending',
text,
type: 'regular',
user: client.user,
...(parent?.id ? { parent_id: parent.id } : null),
};

// @ts-expect-error
if (thread.channel) thread.upsertReply({ message: messagePreview });

updateMessage(messagePreview);

await doSendMessage(messagePreview, customMessageData, options);
Expand Down
6 changes: 6 additions & 0 deletions src/components/Message/hooks/useReactionHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import type { Reaction, ReactionResponse } from 'stream-chat';

import type { DefaultStreamChatGenerics } from '../../../types/types';

import { useThreadContext } from '../../Threads';

export const reactionHandlerWarning = `Reaction handler was called, but it is missing one of its required arguments.
Make sure the ChannelAction and ChannelState contexts are properly set and the hook is initialized with a valid message.`;

Expand All @@ -19,6 +21,7 @@ export const useReactionHandler = <
>(
message?: StreamMessage<StreamChatGenerics>,
) => {
const thread = useThreadContext();
const { updateMessage } = useChannelActionContext<StreamChatGenerics>('useReactionHandler');
const { channel, channelCapabilities } = useChannelStateContext<StreamChatGenerics>(
'useReactionHandler',
Expand Down Expand Up @@ -93,15 +96,18 @@ export const useReactionHandler = <

try {
updateMessage(tempMessage);
if (thread.channel) thread.upsertReply({ message: tempMessage });

const messageResponse = add
? await channel.sendReaction(id, { type } as Reaction<StreamChatGenerics>)
: await channel.deleteReaction(id, type);

// seems useless as we're expecting WS event to come in and replace this anyway
updateMessage(messageResponse.message);
} catch (error) {
// revert to the original message if the API call fails
updateMessage(message);
if (thread.channel) thread.upsertReply({ message });
}
}, 1000);

Expand Down
4 changes: 2 additions & 2 deletions src/components/Thread/Thread.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ const ThreadInner = <
thread,
threadHasMore,
threadLoadingMore,
threadMessages,
threadMessages = [],
threadSuppressAutoscroll,
} = useChannelStateContext<StreamChatGenerics>('Thread');
const { closeThread, loadMoreThread } = useChannelActionContext<StreamChatGenerics>('Thread');
Expand Down Expand Up @@ -164,7 +164,7 @@ const ThreadInner = <
loadMore={parentMessage ? threadInstance.loadPreviousPage : loadMoreThread}
Message={MessageUIComponent}
messageActions={messageActions}
messages={threadInstance.channel ? latestReplies : threadMessages ?? []}
messages={parentMessage ? latestReplies : threadMessages}
suppressAutoscroll={threadSuppressAutoscroll}
threadList
{...(virtualized ? additionalVirtualizedMessageListProps : additionalMessageListProps)}
Expand Down
25 changes: 12 additions & 13 deletions src/components/Threads/ThreadContext.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import React, { createContext, useContext } from 'react';
import React, { createContext, useContext, useMemo } from 'react';

import { Channel } from '../../components';

import type { PropsWithChildren } from 'react';
import { Thread } from 'stream-chat';
import { useChatContext } from '../../context';

/**
* TODO:
* - make it easier for current state of the SDK to use thread methods (meaning thread should be fully initialized and checks like `thread.channel && ...` shouldn't exist (these checks are due to a "placeholder" which is used anytime components are utilised under normal circumstances - not under ThreadContext)
*/

export type ThreadContextValue = Thread | undefined;

export const ThreadContext = createContext<ThreadContextValue>(undefined);
Expand All @@ -14,7 +19,12 @@ export const useThreadContext = () => {
const { client } = useChatContext();
const thread = useContext(ThreadContext);

if (!thread) return new Thread({ client, registerEventHandlers: false, threadData: {} });
const placeholder = useMemo(
() => new Thread({ client, registerEventHandlers: false, threadData: {} }),
[client],
);

if (!thread) return placeholder;

return thread;
};
Expand All @@ -25,17 +35,6 @@ export const ThreadProvider = ({ children, thread }: PropsWithChildren<{ thread?
</ThreadContext.Provider>
);

// export const ThreadFacilitator = ({
// children,
// thread,
// }: PropsWithChildren<{
// thread: Thread;
// }>) => {
// <ThreadProvider thread={thread}>
// <Channel channel={thread.channel}>{children}</Channel>;
// </ThreadProvider>;
// };

/**
*
* client {
Expand Down
27 changes: 16 additions & 11 deletions src/components/Threads/ThreadList/ThreadList.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,38 @@
import React, { useEffect } from 'react';
import { ComputeItemKey, Virtuoso } from 'react-virtuoso';
import { StreamChat } from 'stream-chat';

import type { ComponentType, PointerEvent } from 'react';
import type { InferStoreValueType, Thread } from 'stream-chat';
import type { InferStoreValueType, Thread, ThreadManager } from 'stream-chat';

import { ThreadListItem } from './ThreadListItem';
import { useChatContext } from '../../../context';
import { useSimpleStateStore } from '../hooks/useSimpleStateStore';

import type { ThreadListItemProps } from './ThreadListItem';

const selector = (v: InferStoreValueType<StreamChat['threads']>) => [v.threads] as const;
/**
* TODO:
* - add virtuosoProps override \w support for supplying custom threads array (typed virtuoso props, Thread[] only)
* - register event handlers of each of the threads (ThreadManager - threads.<de/register>EventHandlers(), maybe simplify API)
* - add Header with re-query button + logic to ThreadManager
* - add Footer with "Loading"
* - move str-chat someplace else, think of a different name (str-chat__thread-list already used)
* - move itemContent to a component instead
*
* NICE TO HAVE:
* - probably good idea to move component context up to a Chat component
*/

const selector = (nextValue: InferStoreValueType<ThreadManager>) => [nextValue.threads] as const;

const computeItemKey: ComputeItemKey<Thread, unknown> = (_, item) => item.id;

type ThreadListProps = {
onItemPointerDown?: (event: PointerEvent<HTMLButtonElement>, thread: Thread) => void;
ThreadListItem?: ComponentType<ThreadListItemProps>;
// TODO: should support supplying custom threads array
// threads?: Thread[]
};

// TODO: probably good idea to move component context up to a Chat component

export const ThreadList = ({
ThreadListItem: PropsThreadListItem = ThreadListItem,
onItemPointerDown,
Expand All @@ -37,11 +46,7 @@ export const ThreadList = ({

return (
<Virtuoso
atBottomStateChange={(atBottom) =>
// TODO: figure out - handle next page load blocking client-side or here?
atBottom && client.threads.loadNextPage()
}
// TODO: str-chat class name does not belong here, str-chat__thread-list is already used (FUCK ME SIDEWAYS)
atBottomStateChange={(atBottom) => atBottom && client.threads.loadNextPage()}
className='str-chat str-chat__thread-list'
computeItemKey={computeItemKey}
data={threads}
Expand Down

0 comments on commit 9c6acc3

Please sign in to comment.