|
| 1 | +import { useState, useCallback, useEffect } from 'react'; |
| 2 | +import type { Annotation, ImageAttachment, ReviewSession } from '../types'; |
| 3 | + |
| 4 | +interface UseCollaborativeSessionResult { |
| 5 | + isCollaborativeSession: boolean; |
| 6 | + sessionId: string; |
| 7 | + sessionVersion: number; |
| 8 | + isLoading: boolean; |
| 9 | + error: string; |
| 10 | + createSession: () => Promise<string | null>; |
| 11 | + joinSession: (sessionId: string) => Promise<boolean>; |
| 12 | + submitAnnotations: ( |
| 13 | + annotations: Annotation[], |
| 14 | + globalAttachments?: ImageAttachment[] |
| 15 | + ) => Promise<boolean>; |
| 16 | + refreshSession: () => Promise<boolean>; |
| 17 | + reviewerCount: number; |
| 18 | + lastUpdatedAt: number; |
| 19 | +} |
| 20 | + |
| 21 | +export function useCollaborativeSession( |
| 22 | + markdown: string, |
| 23 | + setAnnotations: React.Dispatch<React.SetStateAction<Annotation[]>>, |
| 24 | + setGlobalAttachments: React.Dispatch<React.SetStateAction<ImageAttachment[]>>, |
| 25 | + pasteApiUrl?: string |
| 26 | +): UseCollaborativeSessionResult { |
| 27 | + const [isCollaborativeSession, setIsCollaborativeSession] = useState(false); |
| 28 | + const [sessionId, setSessionId] = useState(''); |
| 29 | + const [sessionVersion, setSessionVersion] = useState(0); |
| 30 | + const [isLoading, setIsLoading] = useState(false); |
| 31 | + const [error, setError] = useState(''); |
| 32 | + const [reviewerCount, setReviewerCount] = useState(0); |
| 33 | + const [lastUpdatedAt, setLastUpdatedAt] = useState(0); |
| 34 | + |
| 35 | + const apiBase = pasteApiUrl || 'https://plannotator-paste.plannotator.workers.dev'; |
| 36 | + |
| 37 | + const createSession = useCallback(async (): Promise<string | null> => { |
| 38 | + setIsLoading(true); |
| 39 | + setError(''); |
| 40 | + |
| 41 | + try { |
| 42 | + const response = await fetch(`${apiBase}/api/review-session`, { |
| 43 | + method: 'POST', |
| 44 | + headers: { 'Content-Type': 'application/json' }, |
| 45 | + body: JSON.stringify({ plan: markdown }), |
| 46 | + signal: AbortSignal.timeout(10_000), |
| 47 | + }); |
| 48 | + |
| 49 | + if (!response.ok) { |
| 50 | + const errData = await response.json().catch(() => ({ error: 'Failed to create session' })); |
| 51 | + setError(errData.error || 'Failed to create session'); |
| 52 | + return null; |
| 53 | + } |
| 54 | + |
| 55 | + const { session, shareUrl } = await response.json(); |
| 56 | + |
| 57 | + setIsCollaborativeSession(true); |
| 58 | + setSessionId(session.id); |
| 59 | + setSessionVersion(session.version); |
| 60 | + setReviewerCount(session.reviewerCount); |
| 61 | + setLastUpdatedAt(session.lastUpdatedAt); |
| 62 | + |
| 63 | + return shareUrl; |
| 64 | + } catch { |
| 65 | + setError('Network error while creating session'); |
| 66 | + return null; |
| 67 | + } finally { |
| 68 | + setIsLoading(false); |
| 69 | + } |
| 70 | + }, [markdown, apiBase]); |
| 71 | + |
| 72 | + const joinSession = useCallback( |
| 73 | + async (id: string): Promise<boolean> => { |
| 74 | + setIsLoading(true); |
| 75 | + setError(''); |
| 76 | + |
| 77 | + try { |
| 78 | + const response = await fetch(`${apiBase}/api/review-session/${id}`, { |
| 79 | + signal: AbortSignal.timeout(10_000), |
| 80 | + }); |
| 81 | + |
| 82 | + if (!response.ok) { |
| 83 | + setError('Session not found or expired'); |
| 84 | + return false; |
| 85 | + } |
| 86 | + |
| 87 | + const { session } = await response.json(); |
| 88 | + |
| 89 | + setIsCollaborativeSession(true); |
| 90 | + setSessionId(session.id); |
| 91 | + setSessionVersion(session.version); |
| 92 | + setReviewerCount(session.reviewerCount); |
| 93 | + setLastUpdatedAt(session.lastUpdatedAt); |
| 94 | + |
| 95 | + setAnnotations(session.annotations); |
| 96 | + if (session.globalAttachments?.length) { |
| 97 | + setGlobalAttachments(session.globalAttachments); |
| 98 | + } |
| 99 | + |
| 100 | + return true; |
| 101 | + } catch { |
| 102 | + setError('Failed to join session'); |
| 103 | + return false; |
| 104 | + } finally { |
| 105 | + setIsLoading(false); |
| 106 | + } |
| 107 | + }, |
| 108 | + [apiBase, setAnnotations, setGlobalAttachments] |
| 109 | + ); |
| 110 | + |
| 111 | + const submitAnnotations = useCallback( |
| 112 | + async (annotations: Annotation[], globalAttachments?: ImageAttachment[]): Promise<boolean> => { |
| 113 | + if (!isCollaborativeSession) return false; |
| 114 | + |
| 115 | + setIsLoading(true); |
| 116 | + setError(''); |
| 117 | + |
| 118 | + try { |
| 119 | + const response = await fetch(`${apiBase}/api/review-session/${sessionId}/annotations`, { |
| 120 | + method: 'PATCH', |
| 121 | + headers: { 'Content-Type': 'application/json' }, |
| 122 | + body: JSON.stringify({ |
| 123 | + annotations, |
| 124 | + globalAttachments, |
| 125 | + expectedVersion: sessionVersion, |
| 126 | + }), |
| 127 | + signal: AbortSignal.timeout(10_000), |
| 128 | + }); |
| 129 | + |
| 130 | + if (!response.ok) { |
| 131 | + if (response.status === 409) { |
| 132 | + setError('Session was updated by another reviewer — refreshing...'); |
| 133 | + await refreshSession(); |
| 134 | + } else { |
| 135 | + const errData = await response.json().catch(() => ({ error: 'Failed to submit' })); |
| 136 | + setError(errData.error || 'Failed to submit annotations'); |
| 137 | + } |
| 138 | + return false; |
| 139 | + } |
| 140 | + |
| 141 | + const { session } = await response.json(); |
| 142 | + |
| 143 | + setSessionVersion(session.version); |
| 144 | + setReviewerCount(session.reviewerCount); |
| 145 | + setLastUpdatedAt(session.lastUpdatedAt); |
| 146 | + |
| 147 | + return true; |
| 148 | + } catch { |
| 149 | + setError('Network error while submitting annotations'); |
| 150 | + return false; |
| 151 | + } finally { |
| 152 | + setIsLoading(false); |
| 153 | + } |
| 154 | + }, |
| 155 | + [isCollaborativeSession, sessionId, sessionVersion, apiBase] |
| 156 | + ); |
| 157 | + |
| 158 | + const refreshSession = useCallback(async (): Promise<boolean> => { |
| 159 | + if (!isCollaborativeSession) return false; |
| 160 | + |
| 161 | + setIsLoading(true); |
| 162 | + setError(''); |
| 163 | + |
| 164 | + try { |
| 165 | + const response = await fetch(`${apiBase}/api/review-session/${sessionId}`, { |
| 166 | + signal: AbortSignal.timeout(10_000), |
| 167 | + }); |
| 168 | + |
| 169 | + if (!response.ok) { |
| 170 | + setError('Failed to refresh session'); |
| 171 | + return false; |
| 172 | + } |
| 173 | + |
| 174 | + const { session } = await response.json(); |
| 175 | + |
| 176 | + setSessionVersion(session.version); |
| 177 | + setReviewerCount(session.reviewerCount); |
| 178 | + setLastUpdatedAt(session.lastUpdatedAt); |
| 179 | + |
| 180 | + setAnnotations((prev) => { |
| 181 | + const merged = [...prev]; |
| 182 | + const existingSet = new Set(merged.map((a) => `${a.originalText}|${a.type}|${a.text || ''}`)); |
| 183 | + |
| 184 | + const newFromServer = session.annotations.filter((ann: Annotation) => { |
| 185 | + const key = `${ann.originalText}|${ann.type}|${ann.text || ''}`; |
| 186 | + return !existingSet.has(key); |
| 187 | + }); |
| 188 | + |
| 189 | + return [...merged, ...newFromServer]; |
| 190 | + }); |
| 191 | + |
| 192 | + if (session.globalAttachments?.length) { |
| 193 | + setGlobalAttachments((prev) => { |
| 194 | + const existingPaths = new Set(prev.map((g) => g.path)); |
| 195 | + const newAttachments = session.globalAttachments.filter((g: ImageAttachment) => !existingPaths.has(g.path)); |
| 196 | + return [...prev, ...newAttachments]; |
| 197 | + }); |
| 198 | + } |
| 199 | + |
| 200 | + return true; |
| 201 | + } catch { |
| 202 | + setError('Failed to refresh session'); |
| 203 | + return false; |
| 204 | + } finally { |
| 205 | + setIsLoading(false); |
| 206 | + } |
| 207 | + }, [isCollaborativeSession, sessionId, apiBase, setAnnotations, setGlobalAttachments]); |
| 208 | + |
| 209 | + // Check URL for /s/<id> pattern on mount |
| 210 | + useEffect(() => { |
| 211 | + const pathMatch = window.location.pathname.match(/^\/s\/([A-Za-z0-9]{6,16})$/); |
| 212 | + if (pathMatch) { |
| 213 | + const id = pathMatch[1]; |
| 214 | + joinSession(id).then((success) => { |
| 215 | + if (success) { |
| 216 | + window.history.replaceState({}, '', '/'); |
| 217 | + } |
| 218 | + }); |
| 219 | + } |
| 220 | + }, [joinSession]); |
| 221 | + |
| 222 | + return { |
| 223 | + isCollaborativeSession, |
| 224 | + sessionId, |
| 225 | + sessionVersion, |
| 226 | + isLoading, |
| 227 | + error, |
| 228 | + createSession, |
| 229 | + joinSession, |
| 230 | + submitAnnotations, |
| 231 | + refreshSession, |
| 232 | + reviewerCount, |
| 233 | + lastUpdatedAt, |
| 234 | + }; |
| 235 | +} |
0 commit comments