|
import { useState } from 'react' |
|
import type { ConversationItem } from '@/types/app' |
|
import produce from 'immer' |
|
|
|
const storageConversationIdKey = 'conversationIdInfo' |
|
|
|
type ConversationInfoType = Omit<ConversationItem, 'inputs' | 'id'> |
|
function useConversation() { |
|
const [conversationList, setConversationList] = useState<ConversationItem[]>([]) |
|
const [currConversationId, doSetCurrConversationId] = useState<string>('-1') |
|
|
|
const setCurrConversationId = (id: string, appId: string, isSetToLocalStroge = true, newConversationName = '') => { |
|
doSetCurrConversationId(id) |
|
if (isSetToLocalStroge && id !== '-1') { |
|
|
|
const conversationIdInfo = globalThis.localStorage?.getItem(storageConversationIdKey) ? JSON.parse(globalThis.localStorage?.getItem(storageConversationIdKey) || '') : {} |
|
conversationIdInfo[appId] = id |
|
globalThis.localStorage?.setItem(storageConversationIdKey, JSON.stringify(conversationIdInfo)) |
|
} |
|
} |
|
|
|
const getConversationIdFromStorage = (appId: string) => { |
|
const conversationIdInfo = globalThis.localStorage?.getItem(storageConversationIdKey) ? JSON.parse(globalThis.localStorage?.getItem(storageConversationIdKey) || '') : {} |
|
const id = conversationIdInfo[appId] |
|
return id |
|
} |
|
|
|
const isNewConversation = currConversationId === '-1' |
|
|
|
const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any> | null>(null) |
|
const resetNewConversationInputs = () => { |
|
if (!newConversationInputs) return |
|
setNewConversationInputs(produce(newConversationInputs, draft => { |
|
Object.keys(draft).forEach(key => { |
|
draft[key] = '' |
|
}) |
|
})) |
|
} |
|
const [existConversationInputs, setExistConversationInputs] = useState<Record<string, any> | null>(null) |
|
const currInputs = isNewConversation ? newConversationInputs : existConversationInputs |
|
const setCurrInputs = isNewConversation ? setNewConversationInputs : setExistConversationInputs |
|
|
|
|
|
const [newConversationInfo, setNewConversationInfo] = useState<ConversationInfoType | null>(null) |
|
const [existConversationInfo, setExistConversationInfo] = useState<ConversationInfoType | null>(null) |
|
const currConversationInfo = isNewConversation ? newConversationInfo : existConversationInfo |
|
|
|
return { |
|
conversationList, |
|
setConversationList, |
|
currConversationId, |
|
setCurrConversationId, |
|
getConversationIdFromStorage, |
|
isNewConversation, |
|
currInputs, |
|
newConversationInputs, |
|
existConversationInputs, |
|
resetNewConversationInputs, |
|
setCurrInputs, |
|
currConversationInfo, |
|
setNewConversationInfo, |
|
setExistConversationInfo |
|
} |
|
} |
|
|
|
export default useConversation; |