interstellar_ai/app/hooks/useChatHistory.tsx
2024-10-08 15:33:21 +02:00

55 lines
No EOL
1.3 KiB
TypeScript

import { useEffect, useState } from "react"
interface Message {
role: string
content:string
}
interface ChatMessages {
name: string
messages: Message[]
timestamp: number
}
interface GlobalChatHistory {
chats: ChatMessages[]
selectedIndex: number
}
let globalChatHistory: GlobalChatHistory = {
chats: [
{ name: "Chat 1", messages: [], timestamp: 4 }
],
selectedIndex:0
}
let listeners: ((state: GlobalChatHistory) => void)[] = []
const setGlobalState = (newState: GlobalChatHistory): void => {
globalChatHistory = newState;
listeners.forEach((listener) => listener(globalChatHistory))
}
export const useChatHistory = (): [GlobalChatHistory, (newState:GlobalChatHistory) => void, (index:number)=>void] => {
const [state, setState] = useState<GlobalChatHistory>(globalChatHistory)
useEffect(() => {
console.log("help", globalChatHistory);
const listener = (newState: GlobalChatHistory) => {
setState(newState)
}
listeners.push(listener)
return () => {
listeners = listeners.filter((l) => l!== listener)
}
}, [])
const setSelectedIndex = (index: number) => {
setGlobalState({...state,selectedIndex:index})
}
return [state, setGlobalState, setSelectedIndex]
}