Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle Chat Message Notifications (#316) #10

Merged
merged 15 commits into from
Jan 16, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
34 changes: 24 additions & 10 deletions packages/mgt-chat/src/components/ChatList/ChatList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,19 @@ import { makeStyles, Button, Link, FluentProvider, shorthands, webLightTheme } f
import { FluentThemeProvider } from '@azure/communication-react';
import { FluentTheme } from '@fluentui/react';
import { Chat as GraphChat } from '@microsoft/microsoft-graph-types';
import { StatefulGraphChatListClient, GraphChatListClient } from '../../statefulClient/StatefulGraphChatListClient';
import {
StatefulGraphChatListClient,
GraphChatListClient,
ChatListEvent
} from '../../statefulClient/StatefulGraphChatListClient';
import { ChatListHeader } from '../ChatListHeader/ChatListHeader';
import { IChatListMenuItemsProps } from '../ChatListHeader/EllipsisMenu';
import { ChatListButtonItem } from '../ChatListHeader/ChatListButtonItem';
import ChatListMenuItem from '../ChatListHeader/ChatListMenuItem';

export interface IChatListItemInteractionProps {
onSelected: (e: GraphChat) => void;
onMessageReceived?: () => void;
}

const useStyles = makeStyles({
Expand Down Expand Up @@ -57,15 +62,9 @@ export const ChatList = (
const styles = useStyles();
const [chatListClient, setChatListClient] = useState<StatefulGraphChatListClient | undefined>();
const [chatListState, setChatListState] = useState<GraphChatListClient | undefined>();
const chatListButtonItems = props.buttonItems === undefined ? [] : props.buttonItems;
const [menuItems, setMenuItems] = useState<ChatListMenuItem[]>(props.menuItems === undefined ? [] : props.menuItems);
const [selectedItem, setSelectedItem] = useState<string>();

// We need to have a function for "this" to work within the loadMoreChatThreads function, otherwise we get a undefined error.
const loadMore = () => {
chatListClient?.loadMoreChatThreads();
};

// wait for provider to be ready before setting client and state
useEffect(() => {
const provider = Providers.globalProvider;
Expand All @@ -89,15 +88,32 @@ export const ChatList = (
}, []);

useEffect(() => {
// handles events emitted from the chat list client
const handleChatListEvent = (event: ChatListEvent) => {
if (event.type === 'chatMessageReceived') {
if (props.onMessageReceived) {
props.onMessageReceived();
}
}
};
if (chatListClient) {
chatListClient.onStateChange(setChatListState);
chatListClient.onChatListEvent(handleChatListEvent);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this old? I thought @seekdavidlee removed onChatListEvent()

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added it back to handle this case, I'm guessing there's another way to accomplish this?

return () => {
void chatListClient.tearDown();
chatListClient.offStateChange(setChatListState);
chatListClient.offChatListEvent(handleChatListEvent);
void chatListClient.tearDown();
};
}
}, [chatListClient]);

const chatListButtonItems = props.buttonItems === undefined ? [] : props.buttonItems;

// We need to have a function for "this" to work within the loadMoreChatThreads function, otherwise we get a undefined error.
const loadMore = () => {
chatListClient?.loadMoreChatThreads();
};

return (
// This is a temporary approach to render the chatlist items. This should be replaced.
<FluentThemeProvider fluentTheme={FluentTheme}>
Expand Down Expand Up @@ -141,5 +157,3 @@ export const ChatList = (
</FluentThemeProvider>
);
};

export default ChatList;
81 changes: 68 additions & 13 deletions packages/mgt-chat/src/statefulClient/StatefulGraphChatListClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { graph } from '../utils/graph';
import { GraphConfig } from './GraphConfig';
import { GraphNotificationUserClient } from './GraphNotificationUserClient';
import { ThreadEventEmitter } from './ThreadEventEmitter';
import { ChatThreadCollection, loadChatThreads, loadChatThreadsByPage } from './graph.chat';
import { ChatThreadCollection, loadChat, loadChatThreads, loadChatThreadsByPage } from './graph.chat';
import { ChatMessageInfo, Chat as GraphChat } from '@microsoft/microsoft-graph-types';
import { error } from '@microsoft/mgt-element';
interface ODataType {
Expand Down Expand Up @@ -70,6 +70,18 @@ interface StatefulClient<T> {
* @param handler Callback to be unregistered
*/
offStateChange(handler: (state: T) => void): void;
/**
* Register a callback to receive ChatList events
*
* @param handler Callback to receive ChatList events
*/
onChatListEvent(handler: (event: ChatListEvent) => void): void;
/**
* Remove a callback to receive ChatList events
*
* @param handler Callback to be unregistered
*/
offChatListEvent(handler: (event: ChatListEvent) => void): void;

chatThreadsPerPage: number;

Expand Down Expand Up @@ -110,6 +122,7 @@ class StatefulGraphChatListClient implements StatefulClient<GraphChatListClient>
private readonly _eventEmitter: ThreadEventEmitter;
// private readonly _cache: MessageCache;
private _stateSubscribers: ((state: GraphChatListClient) => void)[] = [];
private _chatListEventSubscribers: ((state: ChatListEvent) => void)[] = [];
private readonly _graph: IGraph;
constructor(chatThreadsPerPage: number) {
this.updateUserInfo();
Expand Down Expand Up @@ -177,6 +190,31 @@ class StatefulGraphChatListClient implements StatefulClient<GraphChatListClient>
}
}

/**
* Register a callback to receive ChatList events
*
* @param {(event: ChatListEvent) => void} handler
* @memberof StatefulGraphChatListClient
*/
public onChatListEvent(handler: (event: ChatListEvent) => void): void {
if (!this._chatListEventSubscribers.includes(handler)) {
this._chatListEventSubscribers.push(handler);
}
}

/**
* Unregister a callback from receiving ChatList events
*
* @param {(event: ChatListEvent) => void} handler
* @memberof StatefulGraphChatListClient
*/
public offChatListEvent(handler: (event: ChatListEvent) => void): void {
const index = this._chatListEventSubscribers.indexOf(handler);
if (index !== -1) {
this._chatListEventSubscribers = this._chatListEventSubscribers.splice(index, 1);
}
}

private readonly _initialState: GraphChatListClient = {
status: 'initial',
activeErrorMessages: [],
Expand Down Expand Up @@ -208,23 +246,40 @@ class StatefulGraphChatListClient implements StatefulClient<GraphChatListClient>
* Handle ChatListEvent event types.
*/
private notifyChatMessageEventChange(message: ChatListEvent) {
this.notifyStateChange((draft: GraphChatListClient) => {
if (message.type === 'chatRenamed' && message.message.eventDetail) {
const eventDetail = message.message.eventDetail as EventMessageDetail;
this._chatListEventSubscribers.forEach(handler => handler(message));
if (message.type === 'chatRenamed' && message.message.eventDetail) {
const eventDetail = message.message.eventDetail as EventMessageDetail;
this.notifyStateChange((draft: GraphChatListClient) => {
const chatThread = draft.chatThreads.find(c => c.id === message.message.chatId);
if (chatThread) {
chatThread.topic = eventDetail.chatDisplayName;
}
});
}
if (message.type === 'chatMessageReceived') {
const chatThread = this._state.chatThreads.find(c => c.id === message.message.chatId);
if (chatThread) {
const msgInfo = message.message as ChatMessageInfo;
this.notifyStateChange((draft: GraphChatListClient) => {
const draftChatThread = draft.chatThreads.find(c => c.id === chatThread.id);
if (!draftChatThread) {
Error('Unexpected state discrepancy: Chat thread not found in draft state');
return;
}
draftChatThread.lastMessagePreview = msgInfo;
// remove the updated chat thread from the list and add it to the top
draft.chatThreads = draft.chatThreads.filter(c => c.id !== draftChatThread.id);
draft.chatThreads.unshift(draftChatThread);
});
} else {
// if the chat thread is not in the list, load it, add it to the top
loadChat(this._graph, message.message.chatId as string).then(chat => {
this.notifyStateChange((draft: GraphChatListClient) => {
draft.chatThreads.unshift(chat);
});
});
}

if (message.type === 'chatMessageReceived') {
const chatThread = draft.chatThreads.find(c => c.id === message.message.chatId);
if (chatThread) {
const msgInfo = message.message as ChatMessageInfo;
chatThread.lastMessagePreview = msgInfo;
}
}
});
}
}

/*
Expand Down
14 changes: 13 additions & 1 deletion samples/react-chat/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,19 @@ const ChatListWrapper = memo(({ onSelected }: { onSelected: (e: GraphChat) => vo
}
];

return <ChatList chatThreadsPerPage={3} menuItems={menus} buttonItems={buttons} onSelected={onSelected} />;
const onMessageReceived = () => {
console.log('SampleChatLog: Message received');
};

return (
<ChatList
chatThreadsPerPage={3}
menuItems={menus}
buttonItems={buttons}
onSelected={onSelected}
onMessageReceived={onMessageReceived}
/>
);
});

function App() {
Expand Down