-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrt2 ui
230 lines (195 loc) · 6.13 KB
/
Prt2 ui
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
# Part 2: Frontend State Management
## Overview
This section contains the state management logic for the chat application. We use React's built-in hooks along with custom hooks for managing complex state and side effects.
## Chat Context (ChatContext.jsx)
```jsx
import React, { createContext, useContext, useReducer } from 'react';
const ChatContext = createContext(null);
// Action types
const ACTIONS = {
SET_MESSAGES: 'SET_MESSAGES',
ADD_MESSAGE: 'ADD_MESSAGE',
SET_LOADING: 'SET_LOADING',
SET_ERROR: 'SET_ERROR',
SET_CONVERSATIONS: 'SET_CONVERSATIONS',
};
// Initial state
const initialState = {
messages: [],
loading: false,
error: null,
savedConversations: [],
};
// Reducer function
function chatReducer(state, action) {
switch (action.type) {
case ACTIONS.SET_MESSAGES:
return { ...state, messages: action.payload };
case ACTIONS.ADD_MESSAGE:
return { ...state, messages: [...state.messages, action.payload] };
case ACTIONS.SET_LOADING:
return { ...state, loading: action.payload };
case ACTIONS.SET_ERROR:
return { ...state, error: action.payload };
case ACTIONS.SET_CONVERSATIONS:
return { ...state, savedConversations: action.payload };
default:
return state;
}
}
// Provider component
export function ChatProvider({ children }) {
const [state, dispatch] = useReducer(chatReducer, initialState);
return (
<ChatContext.Provider value={{ state, dispatch }}>
{children}
</ChatContext.Provider>
);
}
// Custom hook for using chat context
export function useChatContext() {
const context = useContext(ChatContext);
if (!context) {
throw new Error('useChatContext must be used within a ChatProvider');
}
return context;
}
```
## Custom Hooks (hooks/useChatActions.js)
```javascript
import { useCallback } from 'react';
import { useChatContext } from '../context/ChatContext';
import { chatApi } from '../services/api';
export function useChatActions() {
const { state, dispatch } = useChatContext();
const sendMessage = useCallback(async (content) => {
const message = {
content,
role: 'user',
timestamp: new Date().toISOString(),
};
try {
dispatch({ type: 'SET_LOADING', payload: true });
dispatch({ type: 'ADD_MESSAGE', payload: message });
const response = await chatApi.sendMessage(message);
dispatch({
type: 'ADD_MESSAGE',
payload: {
content: response.response,
role: 'assistant',
timestamp: new Date().toISOString(),
},
});
} catch (error) {
dispatch({ type: 'SET_ERROR', payload: error.message });
} finally {
dispatch({ type: 'SET_LOADING', payload: false });
}
}, [dispatch]);
const loadConversation = useCallback(async (filename) => {
try {
dispatch({ type: 'SET_LOADING', payload: true });
const data = await chatApi.loadConversation(filename);
dispatch({ type: 'SET_MESSAGES', payload: data.messages });
} catch (error) {
dispatch({ type: 'SET_ERROR', payload: error.message });
} finally {
dispatch({ type: 'SET_LOADING', payload: false });
}
}, [dispatch]);
const fetchSavedConversations = useCallback(async () => {
try {
const data = await chatApi.getSavedConversations();
dispatch({ type: 'SET_CONVERSATIONS', payload: data.conversations });
} catch (error) {
dispatch({ type: 'SET_ERROR', payload: error.message });
}
}, [dispatch]);
return {
sendMessage,
loadConversation,
fetchSavedConversations,
state,
};
}
```
## Error Handling Hook (hooks/useErrorHandler.js)
```javascript
import { useEffect } from 'react';
import { useChatContext } from '../context/ChatContext';
export function useErrorHandler() {
const { state, dispatch } = useChatContext();
useEffect(() => {
if (state.error) {
// You could implement toast notifications or other error UI here
console.error('Chat Error:', state.error);
// Clear error after 5 seconds
const timer = setTimeout(() => {
dispatch({ type: 'SET_ERROR', payload: null });
}, 5000);
return () => clearTimeout(timer);
}
}, [state.error, dispatch]);
return state.error;
}
```
## Auto-scroll Hook (hooks/useAutoScroll.js)
```javascript
import { useEffect, useRef } from 'react';
export function useAutoScroll(deps = []) {
const scrollRef = useRef(null);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollIntoView({
behavior: 'smooth',
block: 'end',
});
}
}, deps);
return scrollRef;
}
```
## Persistence Hook (hooks/usePersistence.js)
```javascript
import { useEffect } from 'react';
import { useChatContext } from '../context/ChatContext';
const STORAGE_KEY = 'chat_state';
export function usePersistence() {
const { state, dispatch } = useChatContext();
// Load state from localStorage on mount
useEffect(() => {
const savedState = localStorage.getItem(STORAGE_KEY);
if (savedState) {
try {
const parsed = JSON.parse(savedState);
dispatch({ type: 'SET_MESSAGES', payload: parsed.messages });
dispatch({ type: 'SET_CONVERSATIONS', payload: parsed.savedConversations });
} catch (error) {
console.error('Error loading saved state:', error);
}
}
}, [dispatch]);
// Save state to localStorage when it changes
useEffect(() => {
const stateToSave = {
messages: state.messages,
savedConversations: state.savedConversations,
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(stateToSave));
}, [state.messages, state.savedConversations]);
}
```
The state management system provides:
- Centralized state management using Context API
- Action creators and reducers for predictable state updates
- Custom hooks for common operations
- Error handling and persistence
- Proper TypeScript types (if using TypeScript)
- Optimized performance with useCallback and useMemo
- Local storage integration for persistence
This organization allows for:
- Clear separation of concerns
- Easy testing and debugging
- Scalable state management
- Reusable logic across components
- Consistent error handling