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
108 changes: 108 additions & 0 deletions libs/chatbot/lib/components/ChatBot/ChatBotHistory.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import * as React from 'react';
import {
ChatbotConversationHistoryNav,
ChatbotDisplayMode,
Conversation,
} from '@patternfly-6/chatbot';
import { Alert } from '@patternfly-6/react-core';
import { getErrorMessage } from './helpers';

type ConversationHistory = { conversations: { conversation_id: string; created_at: string }[] };

type ChatBotHistoryProps = {
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
onApiCall: typeof fetch;
startNewConversation: VoidFunction;
loadConversation: (id: string) => Promise<unknown>;
conversationId?: string;
};

const ChatBotHistory = ({
isOpen,
setIsOpen,
children,
onApiCall,
conversationId,
startNewConversation,
loadConversation,
}: React.PropsWithChildren<ChatBotHistoryProps>) => {
const [isLoading, setIsLoading] = React.useState(true);
const [conversations, setConversations] = React.useState<Conversation[]>([]);
const [error, setError] = React.useState<string>();

React.useEffect(() => {
if (!isOpen) {
return;
}
const abortController = new AbortController();
setIsLoading(true);
setError(undefined);
void (async () => {
try {
const resp = await onApiCall('/v1/conversations');
if (!resp.ok) {
throw Error(`Unexpected response code: ${resp.status}`);
}
const cnvs = (await resp.json()) as ConversationHistory;
setConversations(
cnvs.conversations
.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at))
.map(({ conversation_id, created_at }) => ({
id: conversation_id,
text: new Date(created_at).toLocaleString(),
})),
);
} catch (e) {
// aborting fetch trows 'AbortError', we can ignore it
if (abortController.signal.aborted) {
return;
}
setError(getErrorMessage(e));
} finally {
setIsLoading(false);
}
})();
return () => abortController.abort();
}, [isOpen, onApiCall]);

return (
<ChatbotConversationHistoryNav
setIsDrawerOpen={setIsOpen}
isDrawerOpen={isOpen}
drawerContent={children}
displayMode={ChatbotDisplayMode.default}
onDrawerToggle={() => {
setIsOpen(!isOpen);
}}
isLoading={isLoading}
conversations={conversations}
onNewChat={startNewConversation}
onSelectActiveItem={(_, itemId) => {
itemId !== undefined && void loadConversation(`${itemId}`);
setIsOpen(!isOpen);
}}
activeItemId={conversationId}
errorState={
error
? {
bodyText: (
<Alert variant="danger" isInline title="Failed to load conversation history">
{error}
</Alert>
),
}
: undefined
}
emptyState={
!isLoading && !conversations.length
? {
bodyText: 'No conversation history',
}
: undefined
}
/>
);
};

export default ChatBotHistory;
Loading
Loading