2024-10-08 15:33:21 +02:00
import { useEffect , useState } from "react"
2024-10-08 12:56:28 +02:00
2024-10-08 15:33:21 +02:00
interface Message {
role : string
content :string
}
interface ChatMessages {
name : string
messages : Message [ ]
timestamp : number
}
2024-10-08 12:56:28 +02:00
2024-10-08 15:33:21 +02:00
interface GlobalChatHistory {
chats : ChatMessages [ ]
selectedIndex : number
}
let globalChatHistory : GlobalChatHistory = {
chats : [
2024-10-09 15:56:06 +02:00
{ name : "Welcome!" , messages : [ { role : "system" , content : "you are a helpful assistant" } , { role : "assistant" , content : "Hello! How can I help you?" } ] , timestamp : 4 } ,
2024-10-08 15:33:21 +02:00
] ,
selectedIndex :0
}
let listeners : ( ( state : GlobalChatHistory ) = > void ) [ ] = [ ]
2024-10-08 12:56:28 +02:00
2024-10-08 15:33:21 +02:00
const setGlobalState = ( newState : GlobalChatHistory ) : void = > {
globalChatHistory = newState ;
listeners . forEach ( ( listener ) = > listener ( globalChatHistory ) )
2024-10-08 12:56:28 +02:00
}
2024-10-09 14:22:31 +02:00
export const useChatHistory = ( ) : [ GlobalChatHistory , ( index :number ) = > void , ( newState :GlobalChatHistory ) = > void , ( messageIndex : number , newContent :string ) = > void ] = > {
2024-10-08 15:33:21 +02:00
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 } )
}
2024-10-09 13:32:41 +02:00
const updateMessage = ( messageIndex : number , newContent : string ) = > {
const updatedChats = [ . . . state . chats ]
const chatIndex = globalChatHistory . selectedIndex
if ( chatIndex >= 0 && chatIndex < updatedChats . length ) {
const updatedMessages = [ . . . updatedChats [ chatIndex ] . messages ]
if ( messageIndex >= 0 && messageIndex < updatedMessages . length ) {
updatedMessages [ messageIndex ] = { . . . updatedMessages [ messageIndex ] , content : newContent }
updatedChats [ chatIndex ] = { . . . updatedChats [ chatIndex ] , messages : updatedMessages }
setGlobalState ( { . . . state , chats : updatedChats } )
}
}
}
2024-10-09 14:22:31 +02:00
return [ state , setSelectedIndex , setGlobalState , updateMessage ]
2024-10-08 15:33:21 +02:00
}