gbclient/app/chat/chat-provider.tsx
Rodrigo Rodriguez (Pragmatismo) 22452abf36
Some checks failed
GBCI / build (push) Failing after 3m42s
feat: Add ChatProvider for managing chat state and API interactions
- Implemented ChatProvider to manage chat context and user state.
- Added API fetching utility for chat instance and activity handling.
- Integrated chat service with methods for sending activities.
- Updated Tailwind CSS configuration to include additional content paths and custom utilities.
- Added client-side rendering directive to mode-toggle component.
- Created README.md for settings documentation.
2025-06-21 14:30:11 -03:00

76 lines
2 KiB
TypeScript

"use client";
import React, { createContext, useContext, useState, useEffect } from 'react';
const ChatContext = createContext(undefined);
async function apiFetch(endpoint, options = {}) {
const baseUrl = 'http://localhost:4242/';
const response = await fetch(`${baseUrl}${endpoint}`, options);
if (!response.ok) throw new Error('API request failed');
return response.json();
}
export function ChatProvider({ children }) {
const [line, setLine] = useState(null);
const [instance, setInstance] = useState(null);
const [user] = useState({
id: `user_${Math.random().toString(36).slice(2)}`,
name: 'You',
});
useEffect(() => {
const initializeChat = async () => {
try {
const botId = 'doula'; // Default bot ID
const instanceData = await apiFetch(`/instances/${botId}`);
setInstance(instanceData);
const chatService = {
activity$: { subscribe: () => {} },
postActivity: () => ({
subscribe: () => {
return { unsubscribe: () => {} };
},
}),
};
setLine(chatService);
} catch (error) {
console.error('Failed to initialize chat:', error);
}
};
initializeChat();
}, []);
const sendActivity = async (activity) => {
try {
const fullActivity = {
...activity,
from: user,
timestamp: new Date().toISOString(),
};
await apiFetch('/activities', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(fullActivity),
});
line?.postActivity(fullActivity).subscribe();
} catch (error) {
console.error('Failed to send activity:', error);
}
};
return (
<ChatContext.Provider value={{ line, user, instance, sendActivity }}>
{children}
</ChatContext.Provider>
);
}
export function useChat() {
const context = useContext(ChatContext);
if (!context) {
throw new Error('useChat must be used within ChatProvider');
}
return context;
}