2023-06-22 18:50:06 +03:00
|
|
|
"use client";
|
|
|
|
|
2023-07-05 10:30:22 +03:00
|
|
|
import { createContext, useState } from "react";
|
2023-06-22 18:50:06 +03:00
|
|
|
|
2023-09-12 18:44:15 +03:00
|
|
|
import { ChatMessage, Notification } from "@/app/chat/[chatId]/types";
|
2023-06-22 18:50:06 +03:00
|
|
|
|
2023-07-05 10:30:22 +03:00
|
|
|
import { ChatContextProps } from "./types";
|
2023-06-22 18:50:06 +03:00
|
|
|
|
|
|
|
export const ChatContext = createContext<ChatContextProps | undefined>(
|
|
|
|
undefined
|
|
|
|
);
|
|
|
|
|
|
|
|
export const ChatProvider = ({
|
|
|
|
children,
|
|
|
|
}: {
|
|
|
|
children: JSX.Element | JSX.Element[];
|
|
|
|
}): JSX.Element => {
|
2023-09-12 18:44:15 +03:00
|
|
|
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
|
|
|
const [notifications, setNotifications] = useState<Notification[]>([]);
|
2024-02-24 05:56:51 +03:00
|
|
|
const [sourcesMessageIndex, setSourcesMessageIndex] = useState<
|
|
|
|
number | undefined
|
|
|
|
>(undefined);
|
2023-06-30 11:10:59 +03:00
|
|
|
|
2023-09-12 18:44:15 +03:00
|
|
|
const updateStreamingHistory = (streamedChat: ChatMessage): void => {
|
|
|
|
setMessages((prevHistory: ChatMessage[]) => {
|
2023-06-30 11:10:59 +03:00
|
|
|
const updatedHistory = prevHistory.find(
|
|
|
|
(item) => item.message_id === streamedChat.message_id
|
|
|
|
)
|
2023-09-12 18:44:15 +03:00
|
|
|
? prevHistory.map((item: ChatMessage) =>
|
2023-07-03 18:39:59 +03:00
|
|
|
item.message_id === streamedChat.message_id
|
2024-01-20 09:56:24 +03:00
|
|
|
? {
|
|
|
|
...item,
|
|
|
|
assistant: item.assistant + streamedChat.assistant,
|
|
|
|
metadata: streamedChat.metadata,
|
|
|
|
}
|
2023-07-03 18:39:59 +03:00
|
|
|
: item
|
|
|
|
)
|
2023-06-30 11:10:59 +03:00
|
|
|
: [...prevHistory, streamedChat];
|
|
|
|
|
|
|
|
return updatedHistory;
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2023-11-30 14:49:04 +03:00
|
|
|
const removeMessage = (id: string): void => {
|
|
|
|
setMessages((prevHistory: ChatMessage[]) =>
|
|
|
|
prevHistory.filter((item) => item.message_id !== id)
|
|
|
|
);
|
2023-06-30 11:10:59 +03:00
|
|
|
};
|
|
|
|
|
2023-06-22 18:50:06 +03:00
|
|
|
return (
|
|
|
|
<ChatContext.Provider
|
|
|
|
value={{
|
2023-09-12 18:44:15 +03:00
|
|
|
messages,
|
|
|
|
setMessages,
|
2023-06-30 11:10:59 +03:00
|
|
|
updateStreamingHistory,
|
2023-11-30 14:49:04 +03:00
|
|
|
removeMessage,
|
2023-09-12 18:44:15 +03:00
|
|
|
notifications,
|
|
|
|
setNotifications,
|
2024-02-24 05:56:51 +03:00
|
|
|
sourcesMessageIndex,
|
|
|
|
setSourcesMessageIndex,
|
2023-06-22 18:50:06 +03:00
|
|
|
}}
|
|
|
|
>
|
|
|
|
{children}
|
|
|
|
</ChatContext.Provider>
|
|
|
|
);
|
|
|
|
};
|