| // src/context/OfflineContext.tsx | |
| import { createContext, useContext, useEffect, useState, useCallback, useRef, ReactNode } from "react"; | |
| import { useWebSocket } from "./WebSocketContext"; | |
| import { useToast } from "./ToastContext"; | |
| import type { OfflineQueueItem, SyncStatus } from "@/types/flow"; | |
| // ============================================ | |
| // Types | |
| // ============================================ | |
| interface QueuedAction { | |
| id: string; | |
| type: string; | |
| payload: any; | |
| retries: number; | |
| timestamp: number; | |
| } | |
| interface OfflineContextValue { | |
| isOnline: boolean; | |
| wasOffline: boolean; | |
| queue: OfflineQueueItem[]; | |
| queueLength: number; | |
| syncStatus: SyncStatus; | |
| syncProgress: number | null; | |
| lastSyncTime: string | null; | |
| addToQueue: (action: Omit<QueuedAction, "id" | "retries" | "timestamp">) => void; | |
| enqueue: (type: OfflineQueueItem["type"], payload: any) => Promise<void>; | |
| processQueue: () => Promise<void>; | |
| clearQueue: () => void; | |
| retryFailedActions: () => void; | |
| } | |
| // ============================================ | |
| // Constants | |
| // ============================================ | |
| const DB_NAME = "ie_research_offline_queue"; | |
| const DB_VERSION = 1; | |
| const QUEUE_STORE = "sync_queue"; | |
| const RETRY_DELAY = 15000; // 15 seconds | |
| const getBrowserOnline = () => (typeof navigator === "undefined" ? true : navigator.onLine); | |
| function getFriendlyName(type: OfflineQueueItem["type"]): string { | |
| switch (type) { | |
| case "message": return "Send Message"; | |
| case "message-edit": return "Edit Message"; | |
| case "message-delete": return "Delete Message"; | |
| case "upload": return "File Upload"; | |
| case "comment": return "Post Comment"; | |
| case "review": return "Submit Review"; | |
| case "profile-update": return "Update Profile"; | |
| case "project-update": return "Update Project"; | |
| case "project-create": return "Create Project"; | |
| case "article-create": return "Create Article"; | |
| case "article-update": return "Update Article"; | |
| case "event-rsvp": return "Event RSVP"; | |
| case "event-register": return "Event Registration"; | |
| case "event-create": return "Create Event"; | |
| case "tool-create": return "Create Tool"; | |
| case "tool-update": return "Update Tool"; | |
| case "group-update": return "Update Group"; | |
| case "group-create": return "Create Group"; | |
| default: return type; | |
| } | |
| } | |
| async function syncItem(item: OfflineQueueItem) { | |
| const { default: api } = await import("@/lib/api"); | |
| switch (item.type) { | |
| case "message": { | |
| const { route, method, payload } = item.payload || {}; | |
| if (route && method) { | |
| if (method === "post") return api.post(route, payload); | |
| if (method === "put") return api.put(route, payload); | |
| if (method === "delete") return api.delete(route, { data: payload }); | |
| } | |
| return api.post(`/messages/${item.payload.recipient || item.payload.username}`, { content: item.payload.content }); | |
| } | |
| case "message-edit": | |
| return api.put(`/messages/${item.payload.id}`, item.payload); | |
| case "message-delete": | |
| return api.delete(`/messages/${item.payload.id}`); | |
| case "upload": { | |
| const formData = new FormData(); | |
| formData.append("file", item.payload.file); | |
| return api.post("/media/upload", formData); | |
| } | |
| case "comment": | |
| return api.post("/comments", item.payload); | |
| case "review": | |
| return api.post(`/tools/${item.payload.toolId}/reviews`, item.payload); | |
| case "profile-update": | |
| return api.put("/users/profile", item.payload); | |
| case "project-update": | |
| return api.put(`/projects/${item.payload.id}`, item.payload); | |
| case "project-create": | |
| return api.post("/projects", item.payload); | |
| case "article-create": | |
| return api.post("/articles", item.payload); | |
| case "article-update": | |
| return api.put(`/articles/${item.payload.id}`, item.payload); | |
| case "event-rsvp": | |
| return api.post(`/events/${item.payload.id}/rsvp`, { status: item.payload.status }); | |
| case "event-register": | |
| if (item.payload.register) { | |
| return api.post(`/events/${item.payload.id}/register`); | |
| } else { | |
| return api.delete(`/events/${item.payload.id}/register`); | |
| } | |
| case "event-create": | |
| return api.post("/events", item.payload); | |
| case "tool-create": { | |
| const formData = new FormData(); | |
| Object.entries(item.payload).forEach(([key, value]) => { | |
| if (value === undefined || value === null) return; | |
| if (key === "tags" && Array.isArray(value)) { | |
| formData.append("tags", JSON.stringify(value)); | |
| } else { | |
| formData.append(key, typeof value === "string" ? value : String(value)); | |
| } | |
| }); | |
| return api.post("/tools", formData, { | |
| headers: { "Content-Type": "multipart/form-data" }, | |
| }); | |
| } | |
| case "tool-update": { | |
| const formData = new FormData(); | |
| Object.entries(item.payload.patch || item.payload).forEach(([key, value]) => { | |
| if (value === undefined || value === null) return; | |
| if (key === "tags" && Array.isArray(value)) { | |
| formData.append("tags", JSON.stringify(value)); | |
| } else { | |
| formData.append(key, typeof value === "string" ? value : String(value)); | |
| } | |
| }); | |
| const id = item.payload.id || item.payload.toolId; | |
| return api.put(`/tools/${id}`, formData, { | |
| headers: { "Content-Type": "multipart/form-data" }, | |
| }); | |
| } | |
| case "group-update": | |
| return api.put(`/groups/${item.payload.id}`, item.payload); | |
| case "group-create": | |
| return api.post("/groups", item.payload); | |
| default: | |
| throw new Error(`Unknown item type: ${item.type}`); | |
| } | |
| } | |
| // ============================================ | |
| // Context | |
| // ============================================ | |
| const OfflineContext = createContext<OfflineContextValue | null>(null); | |
| export function OfflineProvider({ children }: { children: ReactNode }) { | |
| const { connectionStatus } = useWebSocket(); | |
| const toast = useToast(); | |
| const [isOnline, setIsOnline] = useState(getBrowserOnline); | |
| const [wasOffline, setWasOffline] = useState(false); | |
| const [queue, setQueue] = useState<OfflineQueueItem[]>([]); | |
| const [queueLength, setQueueLength] = useState(0); | |
| const [syncStatus, setSyncStatus] = useState<SyncStatus>("synced"); | |
| const [syncProgress, setSyncProgress] = useState<number | null>(null); | |
| const [lastSyncTime, setLastSyncTime] = useState<string | null>(null); | |
| const dbRef = useRef<IDBDatabase | null>(null); | |
| const processingRef = useRef(false); | |
| const syncTimerRef = useRef<ReturnType<typeof setInterval> | null>(null); | |
| // Get or Initialize IndexedDB connection | |
| const getDb = (): Promise<IDBDatabase> => { | |
| return new Promise((resolve, reject) => { | |
| if (dbRef.current) { | |
| resolve(dbRef.current); | |
| return; | |
| } | |
| const req = indexedDB.open(DB_NAME, DB_VERSION); | |
| req.onupgradeneeded = () => { | |
| const db = req.result; | |
| if (!db.objectStoreNames.contains(QUEUE_STORE)) { | |
| db.createObjectStore(QUEUE_STORE, { keyPath: "id" }); | |
| } | |
| }; | |
| req.onsuccess = () => { | |
| dbRef.current = req.result; | |
| resolve(req.result); | |
| }; | |
| req.onerror = () => reject(req.error); | |
| }); | |
| }; | |
| // Load queue from IndexedDB | |
| const loadQueue = useCallback(async () => { | |
| try { | |
| const db = await getDb(); | |
| const tx = db.transaction(QUEUE_STORE, "readonly"); | |
| const store = tx.objectStore(QUEUE_STORE); | |
| const req = store.getAll(); | |
| req.onsuccess = () => { | |
| const list = (req.result ?? []) as OfflineQueueItem[]; | |
| list.sort((a, b) => a.createdAt - b.createdAt); | |
| setQueue(list); | |
| setQueueLength(list.length); | |
| if (list.length > 0 && syncStatus === "synced") { | |
| setSyncStatus("pending"); | |
| } | |
| }; | |
| } catch (err) { | |
| console.error("Failed to load offline queue:", err); | |
| } | |
| }, [syncStatus]); | |
| // Open IndexedDB on mount | |
| useEffect(() => { | |
| getDb().then(() => { | |
| loadQueue(); | |
| }).catch(err => { | |
| console.error("Could not initialize IndexedDB offline queue:", err); | |
| }); | |
| return () => { | |
| dbRef.current?.close(); | |
| dbRef.current = null; | |
| }; | |
| }, []); | |
| // Enqueue an action | |
| const enqueue = useCallback(async (type: OfflineQueueItem["type"], payload: any) => { | |
| const item: OfflineQueueItem = { | |
| id: `offline-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, | |
| type, | |
| payload, | |
| createdAt: Date.now(), | |
| retryCount: 0, | |
| maxRetries: 5, | |
| status: "queued" | |
| }; | |
| try { | |
| const db = await getDb(); | |
| const tx = db.transaction(QUEUE_STORE, "readwrite"); | |
| tx.objectStore(QUEUE_STORE).put(item); | |
| setQueue(prev => [...prev, item]); | |
| setQueueLength(prev => prev + 1); | |
| setSyncStatus("pending"); | |
| if (navigator.onLine) { | |
| // Trigger processing immediately | |
| setTimeout(() => processQueue(), 50); | |
| } | |
| } catch (err) { | |
| console.error("Failed to enqueue action:", err); | |
| } | |
| }, []); | |
| // Compatibility wrapper for original addToQueue signature | |
| const addToQueue = useCallback((action: Omit<QueuedAction, "id" | "retries" | "timestamp">) => { | |
| enqueue(action.type as OfflineQueueItem["type"], action.payload); | |
| }, [enqueue]); | |
| // Process the queue | |
| const processQueue = useCallback(async () => { | |
| if (processingRef.current) return; | |
| if (!navigator.onLine) { | |
| setSyncStatus("offline"); | |
| return; | |
| } | |
| try { | |
| const db = await getDb(); | |
| const tx = db.transaction(QUEUE_STORE, "readonly"); | |
| const store = tx.objectStore(QUEUE_STORE); | |
| const req = store.getAll(); | |
| const items = await new Promise<OfflineQueueItem[]>((resolve, reject) => { | |
| req.onsuccess = () => resolve((req.result ?? []) as OfflineQueueItem[]); | |
| req.onerror = () => reject(req.error); | |
| }); | |
| if (items.length === 0) { | |
| setSyncStatus("synced"); | |
| setSyncProgress(null); | |
| return; | |
| } | |
| processingRef.current = true; | |
| setSyncStatus("syncing"); | |
| setSyncProgress(0); | |
| items.sort((a, b) => a.createdAt - b.createdAt); | |
| let processedCount = 0; | |
| for (const item of items) { | |
| if (item.status === "failed" && item.retryCount >= item.maxRetries) { | |
| processedCount++; | |
| setSyncProgress((processedCount / items.length) * 100); | |
| continue; | |
| } | |
| const updatedItem: OfflineQueueItem = { ...item, status: "processing" }; | |
| const writeTx = db.transaction(QUEUE_STORE, "readwrite"); | |
| writeTx.objectStore(QUEUE_STORE).put(updatedItem); | |
| setQueue(prev => prev.map(q => q.id === item.id ? updatedItem : q)); | |
| try { | |
| await syncItem(item); | |
| const deleteTx = db.transaction(QUEUE_STORE, "readwrite"); | |
| deleteTx.objectStore(QUEUE_STORE).delete(item.id); | |
| setQueue(prev => prev.filter(q => q.id !== item.id)); | |
| setQueueLength(prev => Math.max(0, prev - 1)); | |
| setLastSyncTime(new Date().toISOString()); | |
| toast.success(`Synced offline action: ${getFriendlyName(item.type)}`); | |
| } catch (err: any) { | |
| console.error(`Failed to sync offline item ${item.id}:`, err); | |
| const status = err.response?.status; | |
| const isPermanent = status && (status >= 400 && status < 500) && status !== 408 && status !== 429; | |
| if (isPermanent) { | |
| if (status === 409) { | |
| toast.warning(`Conflict resolved: Local changes for "${getFriendlyName(item.type)}" were discarded since newer changes exist on the server.`); | |
| } else if (status === 404) { | |
| toast.error(`Sync discarded: Resource for "${getFriendlyName(item.type)}" was not found.`); | |
| } else { | |
| toast.error(`Sync failed for "${getFriendlyName(item.type)}": ${err.response?.data?.error || "Invalid request."}`); | |
| } | |
| const deleteTx = db.transaction(QUEUE_STORE, "readwrite"); | |
| deleteTx.objectStore(QUEUE_STORE).delete(item.id); | |
| setQueue(prev => prev.filter(q => q.id !== item.id)); | |
| setQueueLength(prev => Math.max(0, prev - 1)); | |
| } else { | |
| const nextRetries = item.retryCount + 1; | |
| const failedItem: OfflineQueueItem = { | |
| ...item, | |
| retryCount: nextRetries, | |
| status: "failed" | |
| }; | |
| if (nextRetries >= item.maxRetries) { | |
| toast.error(`Failed to sync "${getFriendlyName(item.type)}" after ${item.maxRetries} attempts. Action discarded.`); | |
| const deleteTx = db.transaction(QUEUE_STORE, "readwrite"); | |
| deleteTx.objectStore(QUEUE_STORE).delete(item.id); | |
| setQueue(prev => prev.filter(q => q.id !== item.id)); | |
| setQueueLength(prev => Math.max(0, prev - 1)); | |
| } else { | |
| const saveTx = db.transaction(QUEUE_STORE, "readwrite"); | |
| saveTx.objectStore(QUEUE_STORE).put(failedItem); | |
| setQueue(prev => prev.map(q => q.id === item.id ? failedItem : q)); | |
| setSyncStatus("error"); | |
| break; // Stop syncing remaining items since we hit a network issue | |
| } | |
| } | |
| } | |
| processedCount++; | |
| setSyncProgress((processedCount / items.length) * 100); | |
| } | |
| // Final count check | |
| const finalTx = db.transaction(QUEUE_STORE, "readonly"); | |
| const finalStore = finalTx.objectStore(QUEUE_STORE); | |
| const finalReq = finalStore.getAll(); | |
| finalReq.onsuccess = () => { | |
| const remaining = (finalReq.result ?? []).length; | |
| if (remaining === 0) { | |
| setSyncStatus("synced"); | |
| setSyncProgress(null); | |
| } else { | |
| setSyncStatus("pending"); | |
| } | |
| }; | |
| } catch (err) { | |
| console.error("Error during queue processing:", err); | |
| setSyncStatus("error"); | |
| } finally { | |
| processingRef.current = false; | |
| } | |
| }, [toast]); | |
| // Clear queue | |
| const clearQueue = useCallback(async () => { | |
| try { | |
| const db = await getDb(); | |
| const tx = db.transaction(QUEUE_STORE, "readwrite"); | |
| tx.objectStore(QUEUE_STORE).clear(); | |
| setQueue([]); | |
| setQueueLength(0); | |
| setSyncStatus("synced"); | |
| toast.info("Offline sync queue cleared."); | |
| } catch (err) { | |
| console.error("Failed to clear queue:", err); | |
| } | |
| }, [toast]); | |
| // Reset and retry | |
| const retryFailedActions = useCallback(async () => { | |
| try { | |
| const db = await getDb(); | |
| const tx = db.transaction(QUEUE_STORE, "readwrite"); | |
| const store = tx.objectStore(QUEUE_STORE); | |
| const req = store.getAll(); | |
| req.onsuccess = () => { | |
| const items = req.result as OfflineQueueItem[]; | |
| for (const item of items) { | |
| const resetItem = { ...item, retryCount: 0, status: "queued" as const }; | |
| store.put(resetItem); | |
| } | |
| }; | |
| tx.oncomplete = () => { | |
| loadQueue(); | |
| setTimeout(() => processQueue(), 50); | |
| }; | |
| } catch (err) { | |
| console.error("Failed to retry failed actions:", err); | |
| } | |
| }, [processQueue, loadQueue]); | |
| // ============================================ | |
| // Monitor Online/Offline Status | |
| // ============================================ | |
| useEffect(() => { | |
| const handleOnline = () => { | |
| setIsOnline(true); | |
| toast.success("Connection restored"); | |
| processQueue(); | |
| }; | |
| const handleOffline = () => { | |
| setIsOnline(false); | |
| setWasOffline(true); | |
| setSyncStatus("offline"); | |
| toast.warning("You are offline. Actions will be queued."); | |
| }; | |
| window.addEventListener("online", handleOnline); | |
| window.addEventListener("offline", handleOffline); | |
| return () => { | |
| window.removeEventListener("online", handleOnline); | |
| window.removeEventListener("offline", handleOffline); | |
| }; | |
| }, [toast, processQueue]); | |
| // ============================================ | |
| // React to WebSocket Connection | |
| // ============================================ | |
| useEffect(() => { | |
| if (connectionStatus === "connected") { | |
| processQueue(); | |
| } | |
| }, [connectionStatus, processQueue]); | |
| // Background retry timer | |
| useEffect(() => { | |
| syncTimerRef.current = setInterval(() => { | |
| if (navigator.onLine && queue.some(q => q.status === "failed")) { | |
| processQueue(); | |
| } | |
| }, RETRY_DELAY); | |
| return () => { | |
| if (syncTimerRef.current) clearInterval(syncTimerRef.current); | |
| }; | |
| }, [queue, processQueue]); | |
| // ============================================ | |
| // Value | |
| // ============================================ | |
| const value: OfflineContextValue = { | |
| isOnline, | |
| wasOffline, | |
| queue, | |
| queueLength, | |
| syncStatus, | |
| syncProgress, | |
| lastSyncTime, | |
| addToQueue, | |
| enqueue, | |
| processQueue, | |
| clearQueue, | |
| retryFailedActions, | |
| }; | |
| return ( | |
| <OfflineContext.Provider value={value}> | |
| {children} | |
| </OfflineContext.Provider> | |
| ); | |
| } | |
| export const useOffline = () => { | |
| const ctx = useContext(OfflineContext); | |
| if (!ctx) throw new Error("useOffline must be used within OfflineProvider"); | |
| return ctx; | |
| }; |
Xet Storage Details
- Size:
- 17.2 kB
- Xet hash:
- 2bbc91675f47e645e7aa729e24e99063896b1589d4882b687dfd36e8607452d6
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.