Spaces:
Running
Running
File size: 5,374 Bytes
74626f2 | 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 | import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { nlpApi, Resource, AgentState, Position, Notification, LearningData } from '../services/nlpApi';
interface AppContextType {
resources: Resource[];
agent: AgentState;
learningData: LearningData | null;
bookmarks: string[];
isLoading: boolean;
setResources: React.Dispatch<React.SetStateAction<Resource[]>>;
setAgent: React.Dispatch<React.SetStateAction<AgentState>>;
setBookmarks: React.Dispatch<React.SetStateAction<string[]>>;
refreshData: () => Promise<void>;
toggleBookmark: (resourceId: string) => Promise<void>;
updateAgentPosition: (position: Position) => Promise<void>;
visitResource: (resourceId: string) => Promise<void>;
levelUpMessage: string | null;
setLevelUpMessage: React.Dispatch<React.SetStateAction<string | null>>;
notifications: Notification[];
addNotification: (message: string, type?: 'info' | 'success' | 'warning') => Promise<void>;
markNotificationsAsRead: () => void;
}
const AppContext = createContext<AppContextType | undefined>(undefined);
export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [resources, setResources] = useState<Resource[]>([]);
const [agent, setAgent] = useState<AgentState>({
position: { x: 10, y: 10 },
level: 1,
totalReward: 0,
visitedResources: []
});
const [learningData, setLearningData] = useState<LearningData | null>(null);
const [bookmarks, setBookmarks] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [levelUpMessage, setLevelUpMessage] = useState<string | null>(null);
const [prevLevel, setPrevLevel] = useState<number | null>(null);
const [notifications, setNotifications] = useState<Notification[]>([]);
const addNotification = useCallback(async (message: string, type: 'info' | 'success' | 'warning' = 'info') => {
try {
const newNotif = await nlpApi.addNotification('default', message, type);
setNotifications(prev => [newNotif, ...prev]);
} catch (error) {
console.error('Failed to add notification:', error);
}
}, []);
const markNotificationsAsRead = useCallback(async () => {
setNotifications(prev => prev.map(n => ({ ...n, read: true })));
try {
await nlpApi.markNotificationsRead('default');
} catch (error) {
console.error('Failed to mark notifications as read:', error);
}
}, []);
// Trigger Notification
useEffect(() => {
if (prevLevel !== null && agent.level > prevLevel) {
const msg = `Level up! You are now Stage ${agent.level}`;
setLevelUpMessage(msg);
addNotification(msg, 'success');
setTimeout(() => setLevelUpMessage(null), 5000); // 5 sec toast
}
setPrevLevel(agent.level);
}, [agent.level, prevLevel, addNotification]);
const refreshData = useCallback(async () => {
setIsLoading(true);
try {
const [resData, agentData, bookmarkData, lData] = await Promise.all([
nlpApi.getResources(),
nlpApi.getAgentState('default'),
nlpApi.getBookmarks('default'),
nlpApi.getLearningData('default')
]);
setResources(resData);
setAgent(agentData);
setBookmarks(bookmarkData);
setLearningData(lData);
if (agentData.notifications) {
setNotifications(agentData.notifications);
}
} catch (error) {
console.error('Failed to refresh data:', error);
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
refreshData();
}, [refreshData]);
const toggleBookmark = async (resourceId: string) => {
const isBookmarked = bookmarks.includes(resourceId);
try {
if (isBookmarked) {
await nlpApi.removeBookmark('default', resourceId);
setBookmarks(prev => prev.filter(id => id !== resourceId));
} else {
await nlpApi.addBookmark('default', resourceId);
setBookmarks(prev => [...prev, resourceId]);
}
} catch (error) {
console.error('Failed to toggle bookmark:', error);
}
};
const updateAgentPosition = async (position: Position) => {
try {
const newState = await nlpApi.moveAgent('default', position);
setAgent(newState);
} catch (error) {
console.error('Failed to update agent position:', error);
}
};
const visitResource = async (resourceId: string) => {
try {
const newState = await nlpApi.visitResource('default', resourceId);
setAgent(newState);
setResources(prev => prev.map(r => r.id === resourceId ? { ...r, visited: true } : r));
} catch (error) {
console.error('Failed to visit resource:', error);
}
};
return (
<AppContext.Provider value={{
resources,
agent,
bookmarks,
isLoading,
setResources,
setAgent,
setBookmarks,
refreshData,
toggleBookmark,
updateAgentPosition,
visitResource,
levelUpMessage,
setLevelUpMessage,
learningData,
notifications,
addNotification,
markNotificationsAsRead
}}>
{children}
</AppContext.Provider>
);
};
export const useAppContext = () => {
const context = useContext(AppContext);
if (!context) {
throw new Error('useAppContext must be used within an AppProvider');
}
return context;
};
|