({ children }: { children: ReactNode })
| 28 | const ChatStoreContext = createContext<ChatStore | undefined>(undefined); |
| 29 | |
| 30 | export function ChatStoreProvider({ children }: { children: ReactNode }) { |
| 31 | const [chats, setChats] = useState<Chat[]>([]); |
| 32 | const [isLoading, setIsLoading] = useState(true); |
| 33 | |
| 34 | const loadChats = useCallback(async () => { |
| 35 | try { |
| 36 | const chatList = await db.chats.orderBy("updatedAt").reverse().toArray(); |
| 37 | setChats(chatList); |
| 38 | } catch (error) { |
| 39 | console.error("Failed to load chats:", error); |
| 40 | } finally { |
| 41 | setIsLoading(false); |
| 42 | } |
| 43 | }, []); |
| 44 | |
| 45 | useEffect(() => { |
| 46 | loadChats(); |
| 47 | }, [loadChats]); |
| 48 | |
| 49 | const createChat = useCallback(async () => { |
| 50 | const id = generateId(); |
| 51 | await db.chats.add({ |
| 52 | id, |
| 53 | title: "New Chat", |
| 54 | createdAt: new Date(), |
| 55 | updatedAt: null, |
| 56 | }); |
| 57 | loadChats(); |
| 58 | return id; |
| 59 | }, [loadChats]); |
| 60 | |
| 61 | const updateChat = useCallback( |
| 62 | async (chatId: string, update: Partial<Chat>) => { |
| 63 | await db.chats.update(chatId, update); |
| 64 | loadChats(); |
| 65 | }, |
| 66 | [loadChats], |
| 67 | ); |
| 68 | |
| 69 | const deleteChat = useCallback( |
| 70 | async (chatId: string) => { |
| 71 | await db.chats.delete(chatId); |
| 72 | loadChats(); |
| 73 | }, |
| 74 | [loadChats], |
| 75 | ); |
| 76 | |
| 77 | const getChat = useCallback(async (id: string) => { |
| 78 | const chat = await db.chats.get(id); |
| 79 | if (!chat) { |
| 80 | return null; |
| 81 | } |
| 82 | const messages = await db.chatMessages.where("chatId").equals(id).toArray(); |
| 83 | return { ...chat, messages }; |
| 84 | }, []); |
| 85 | |
| 86 | const insertChatMessage = useCallback( |
| 87 | async (message: Omit<ChatMessage, "id">) => { |
nothing calls this directly
no outgoing calls
no test coverage detected