* feature: event based plugin * chore: update README.md * Update yarn script for build plugins (#363) * Update yarn script for build plugins * Plugin-core install from npmjs instead of from local --------- Co-authored-by: Hien To <> * #360 plugin preferences (#361) * feature: #360 plugin preferences * chore: update core-plugin README.md * chore: create collections on start * chore: bumb core version * chore: update README * chore: notify preferences update * fix: preference update --------- Co-authored-by: hiento09 <136591877+hiento09@users.noreply.github.com>
64 lines
2.0 KiB
TypeScript
64 lines
2.0 KiB
TypeScript
import { ChatMessage, RawMessage, toChatMessage } from "@/_models/ChatMessage";
|
|
import { executeSerial } from "@/_services/pluginService";
|
|
import { useAtomValue, useSetAtom } from "jotai";
|
|
import { useEffect, useState } from "react";
|
|
import { DataService } from "@janhq/plugin-core";
|
|
import { addOldMessagesAtom } from "@/_helpers/atoms/ChatMessage.atom";
|
|
import {
|
|
currentConversationAtom,
|
|
conversationStatesAtom,
|
|
updateConversationHasMoreAtom,
|
|
} from "@/_helpers/atoms/Conversation.atom";
|
|
|
|
/**
|
|
* Custom hooks to get chat messages for current(active) conversation
|
|
*
|
|
* @param offset for pagination purpose
|
|
* @returns
|
|
*/
|
|
const useChatMessages = (offset = 0) => {
|
|
const [loading, setLoading] = useState(true);
|
|
const addOldChatMessages = useSetAtom(addOldMessagesAtom);
|
|
const currentConvo = useAtomValue(currentConversationAtom);
|
|
const convoStates = useAtomValue(conversationStatesAtom);
|
|
const updateConvoHasMore = useSetAtom(updateConversationHasMoreAtom);
|
|
|
|
useEffect(() => {
|
|
if (!currentConvo) {
|
|
return;
|
|
}
|
|
const hasMore = convoStates[currentConvo._id ?? ""]?.hasMore ?? true;
|
|
if (!hasMore) return;
|
|
|
|
const getMessages = async () => {
|
|
executeSerial(DataService.GetConversationMessages, currentConvo._id).then((data: any) => {
|
|
if (!data) {
|
|
return;
|
|
}
|
|
const newMessages = parseMessages(data ?? []);
|
|
addOldChatMessages(newMessages);
|
|
updateConvoHasMore(currentConvo._id ?? "", false);
|
|
setLoading(false);
|
|
});
|
|
};
|
|
getMessages();
|
|
}, [offset, currentConvo?._id, convoStates, addOldChatMessages, updateConvoHasMore]);
|
|
|
|
return {
|
|
loading: loading,
|
|
error: undefined,
|
|
hasMore: convoStates[currentConvo?._id ?? ""]?.hasMore ?? true,
|
|
};
|
|
};
|
|
|
|
function parseMessages(messages: RawMessage[]): ChatMessage[] {
|
|
const newMessages: ChatMessage[] = [];
|
|
for (const m of messages) {
|
|
const chatMessage = toChatMessage(m);
|
|
newMessages.push(chatMessage);
|
|
}
|
|
return newMessages;
|
|
}
|
|
|
|
export default useChatMessages;
|