| // src/context/CollaborationContext.tsx | |
| import { createContext, useContext, useEffect, useState, useCallback, useRef, ReactNode } from "react"; | |
| import { useAuth } from "./AuthContext"; | |
| import { useWebSocket } from "./WebSocketContext"; | |
| // ============================================ | |
| // Types | |
| // ============================================ | |
| interface CursorPosition { | |
| userId: string; | |
| username: string; | |
| documentId: string; | |
| line: number; | |
| ch: number; | |
| color: string; | |
| updatedAt: number; | |
| } | |
| interface Presence { | |
| userId: string; | |
| username: string; | |
| documentId: string; | |
| status: "active" | "away" | "offline"; | |
| lastSeen: number; | |
| } | |
| interface CollaborationContextValue { | |
| cursors: CursorPosition[]; | |
| updateCursor: (documentId: string, line: number, ch: number) => void; | |
| presences: Presence[]; | |
| setPresence: (documentId: string, status: Presence["status"]) => void; | |
| isLocked: (documentId: string) => boolean; | |
| requestLock: (documentId: string) => Promise<boolean>; | |
| releaseLock: (documentId: string) => void; | |
| lockHolder: string | null; | |
| selections: Map<string, any>; | |
| broadcastSelection: (documentId: string, selection: any) => void; | |
| } | |
| // ============================================ | |
| // Constants | |
| // ============================================ | |
| const CURSOR_TIMEOUT = 5000; | |
| const DEFAULT_COLOR = "#4ECDC4"; | |
| // ============================================ | |
| // Context | |
| // ============================================ | |
| const CollaborationContext = createContext<CollaborationContextValue | null>(null); | |
| export function CollaborationProvider({ children }: { children: ReactNode }) { | |
| const { user } = useAuth(); | |
| const { sendMessage, subscribe, connectionStatus } = useWebSocket(); | |
| const [cursors, setCursors] = useState<CursorPosition[]>([]); | |
| const [presences, setPresences] = useState<Presence[]>([]); | |
| const [locks, setLocks] = useState<Map<string, string>>(new Map()); | |
| const [selections, setSelections] = useState<Map<string, any>>(new Map()); | |
| const cursorTimeouts = useRef<Map<string, NodeJS.Timeout>>(new Map()); | |
| // ============================================ | |
| // Subscribe to WebSocket Events | |
| // ============================================ | |
| useEffect(() => { | |
| const unsubCursor = subscribe("cursor_update", (data: CursorPosition) => { | |
| setCursors(prev => { | |
| const filtered = prev.filter(c => c.userId !== data.userId || c.documentId !== data.documentId); | |
| return [...filtered, { ...data, updatedAt: Date.now() }]; | |
| }); | |
| // Clear existing timeout for this cursor | |
| const key = `${data.userId}-${data.documentId}`; | |
| if (cursorTimeouts.current.has(key)) { | |
| clearTimeout(cursorTimeouts.current.get(key)!); | |
| } | |
| // Auto-remove cursor after timeout | |
| const timeout = setTimeout(() => { | |
| setCursors(prev => prev.filter(c => | |
| !(c.userId === data.userId && c.documentId === data.documentId) | |
| )); | |
| cursorTimeouts.current.delete(key); | |
| }, CURSOR_TIMEOUT); | |
| cursorTimeouts.current.set(key, timeout); | |
| }); | |
| const unsubPresence = subscribe("presence_update", (data: Presence) => { | |
| setPresences(prev => { | |
| const filtered = prev.filter(p => p.userId !== data.userId || p.documentId !== data.documentId); | |
| return [...filtered, data]; | |
| }); | |
| }); | |
| const unsubLock = subscribe("lock_acquired", (data: { documentId: string; userId: string }) => { | |
| setLocks(prev => new Map(prev).set(data.documentId, data.userId)); | |
| }); | |
| const unsubLockRelease = subscribe("lock_released", (data: { documentId: string }) => { | |
| setLocks(prev => { | |
| const newMap = new Map(prev); | |
| newMap.delete(data.documentId); | |
| return newMap; | |
| }); | |
| }); | |
| const unsubSelection = subscribe("selection_update", (data: { documentId: string; userId: string; selection: any }) => { | |
| setSelections(prev => new Map(prev).set(`${data.documentId}-${data.userId}`, data.selection)); | |
| }); | |
| // Cleanup | |
| return () => { | |
| unsubCursor(); | |
| unsubPresence(); | |
| unsubLock(); | |
| unsubLockRelease(); | |
| unsubSelection(); | |
| // Clear all cursor timeouts | |
| for (const timeout of cursorTimeouts.current.values()) { | |
| clearTimeout(timeout); | |
| } | |
| cursorTimeouts.current.clear(); | |
| }; | |
| }, [subscribe]); | |
| // ============================================ | |
| // Update Cursor | |
| // ============================================ | |
| const updateCursor = useCallback((documentId: string, line: number, ch: number) => { | |
| if (!user || connectionStatus !== "connected") return; | |
| sendMessage({ | |
| type: "cursor_update", | |
| payload: { | |
| userId: String(user.id), | |
| username: user.username, | |
| documentId, | |
| line, | |
| ch, | |
| color: (user as any).color || DEFAULT_COLOR, | |
| updatedAt: Date.now(), | |
| }, | |
| }); | |
| }, [user, connectionStatus, sendMessage]); | |
| // ============================================ | |
| // Set Presence | |
| // ============================================ | |
| const setPresence = useCallback((documentId: string, status: Presence["status"]) => { | |
| if (!user || connectionStatus !== "connected") return; | |
| sendMessage({ | |
| type: "presence_update", | |
| payload: { | |
| userId: String(user.id), | |
| username: user.username, | |
| documentId, | |
| status, | |
| lastSeen: Date.now(), | |
| }, | |
| }); | |
| }, [user, connectionStatus, sendMessage]); | |
| // ============================================ | |
| // Lock Functions | |
| // ============================================ | |
| const isLocked = useCallback((documentId: string) => { | |
| const holder = locks.get(documentId); | |
| return !!holder && holder !== String(user?.id); | |
| }, [locks, user]); | |
| const requestLock = useCallback(async (documentId: string): Promise<boolean> => { | |
| if (!user || connectionStatus !== "connected") return false; | |
| return new Promise((resolve) => { | |
| const timeout = setTimeout(() => resolve(false), 5000); | |
| const unsub = subscribe("lock_acquired", (data: any) => { | |
| if (data.documentId === documentId && data.userId === String(user.id)) { | |
| clearTimeout(timeout); | |
| unsub(); | |
| resolve(true); | |
| } | |
| }); | |
| sendMessage({ | |
| type: "request_lock", | |
| payload: { documentId, userId: String(user.id) }, | |
| }); | |
| }); | |
| }, [user, connectionStatus, sendMessage, subscribe]); | |
| const releaseLock = useCallback((documentId: string) => { | |
| if (!user || connectionStatus !== "connected") return; | |
| sendMessage({ | |
| type: "release_lock", | |
| payload: { documentId, userId: String(user.id) }, | |
| }); | |
| setLocks(prev => { | |
| const newMap = new Map(prev); | |
| if (newMap.get(documentId) === String(user.id)) { | |
| newMap.delete(documentId); | |
| } | |
| return newMap; | |
| }); | |
| }, [user, connectionStatus, sendMessage]); | |
| const lockHolder = locks.size > 0 ? (locks.values().next().value ?? null) : null; | |
| // ============================================ | |
| // Broadcast Selection | |
| // ============================================ | |
| const broadcastSelection = useCallback((documentId: string, selection: any) => { | |
| if (!user || connectionStatus !== "connected") return; | |
| sendMessage({ | |
| type: "selection_update", | |
| payload: { documentId, userId: String(user.id), selection }, | |
| }); | |
| }, [user, connectionStatus, sendMessage]); | |
| // ============================================ | |
| // Value | |
| // ============================================ | |
| const value: CollaborationContextValue = { | |
| cursors, | |
| updateCursor, | |
| presences, | |
| setPresence, | |
| isLocked, | |
| requestLock, | |
| releaseLock, | |
| lockHolder, | |
| selections, | |
| broadcastSelection, | |
| }; | |
| return ( | |
| <CollaborationContext.Provider value={value}> | |
| {children} | |
| </CollaborationContext.Provider> | |
| ); | |
| } | |
| export const useCollaboration = () => { | |
| const ctx = useContext(CollaborationContext); | |
| if (!ctx) throw new Error("useCollaboration must be used within CollaborationProvider"); | |
| return ctx; | |
| }; |
Xet Storage Details
- Size:
- 8.1 kB
- Xet hash:
- c98aabd43f89749430d1a7e91628a75ca4b2578fa4a0f8daf8bb83a890a23955
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.