* 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>
35 lines
1.4 KiB
TypeScript
35 lines
1.4 KiB
TypeScript
import { addNewMessageAtom, updateMessageAtom } from "@/_helpers/atoms/ChatMessage.atom";
|
|
import { toChatMessage } from "@/_models/ChatMessage";
|
|
import { events, EventName, NewMessageResponse } from "@janhq/plugin-core";
|
|
import { useSetAtom } from "jotai";
|
|
import { ReactNode, useEffect } from "react";
|
|
|
|
export default function EventHandler({ children }: { children: ReactNode }) {
|
|
const addNewMessage = useSetAtom(addNewMessageAtom);
|
|
const updateMessage = useSetAtom(updateMessageAtom);
|
|
|
|
function handleNewMessageResponse(message: NewMessageResponse) {
|
|
const newResponse = toChatMessage(message);
|
|
addNewMessage(newResponse);
|
|
}
|
|
async function handleMessageResponseUpdate(messageResponse: NewMessageResponse) {
|
|
if (messageResponse.conversationId && messageResponse._id && messageResponse.message)
|
|
updateMessage(messageResponse._id, messageResponse.conversationId, messageResponse.message);
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (window.corePlugin.events) {
|
|
events.on(EventName.OnNewMessageResponse, handleNewMessageResponse);
|
|
events.on(EventName.OnMessageResponseUpdate, handleMessageResponseUpdate);
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
events.off(EventName.OnNewMessageResponse, handleNewMessageResponse);
|
|
events.off(EventName.OnMessageResponseUpdate, handleMessageResponseUpdate);
|
|
};
|
|
}, []);
|
|
return <> {children}</>;
|
|
}
|