feat: enhance live collaboration features by introducing useLive hook for real-time event handling across motivators, sessions, and year reviews; refactor existing hooks to utilize this new functionality
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 2m39s
All checks were successful
Deploy with Docker Compose / deploy (push) Successful in 2m39s
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useTransition } from 'react';
|
import { useState, useTransition, useEffect } from 'react';
|
||||||
import {
|
import {
|
||||||
DndContext,
|
DndContext,
|
||||||
closestCenter,
|
closestCenter,
|
||||||
@@ -35,6 +35,11 @@ export function MotivatorBoard({ sessionId, cards: initialCards, canEdit }: Moti
|
|||||||
const [step, setStep] = useState<Step>('ranking');
|
const [step, setStep] = useState<Step>('ranking');
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
|
|
||||||
|
// Sync local state with props when they change (e.g., from SSE refresh)
|
||||||
|
useEffect(() => {
|
||||||
|
setCards(initialCards);
|
||||||
|
}, [initialCards]);
|
||||||
|
|
||||||
const sensors = useSensors(
|
const sensors = useSensors(
|
||||||
useSensor(PointerSensor, {
|
useSensor(PointerSensor, {
|
||||||
activationConstraint: {
|
activationConstraint: {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { forwardRef, useState, useTransition, ReactNode } from 'react';
|
import { forwardRef, useState, useTransition, useRef, ReactNode } from 'react';
|
||||||
import type { SwotCategory } from '@prisma/client';
|
import type { SwotCategory } from '@prisma/client';
|
||||||
import { createSwotItem } from '@/actions/swot';
|
import { createSwotItem } from '@/actions/swot';
|
||||||
import { QuadrantHelpPanel } from './QuadrantHelp';
|
import { QuadrantHelpPanel } from './QuadrantHelp';
|
||||||
@@ -43,15 +43,17 @@ export const SwotQuadrant = forwardRef<HTMLDivElement, SwotQuadrantProps>(
|
|||||||
const [newContent, setNewContent] = useState('');
|
const [newContent, setNewContent] = useState('');
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
const [showHelp, setShowHelp] = useState(false);
|
const [showHelp, setShowHelp] = useState(false);
|
||||||
|
const isSubmittingRef = useRef(false);
|
||||||
|
|
||||||
const styles = categoryStyles[category];
|
const styles = categoryStyles[category];
|
||||||
|
|
||||||
async function handleAdd() {
|
async function handleAdd() {
|
||||||
if (!newContent.trim()) {
|
if (isSubmittingRef.current || !newContent.trim()) {
|
||||||
setIsAdding(false);
|
setIsAdding(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
isSubmittingRef.current = true;
|
||||||
startTransition(async () => {
|
startTransition(async () => {
|
||||||
await createSwotItem(sessionId, {
|
await createSwotItem(sessionId, {
|
||||||
content: newContent.trim(),
|
content: newContent.trim(),
|
||||||
@@ -59,6 +61,7 @@ export const SwotQuadrant = forwardRef<HTMLDivElement, SwotQuadrantProps>(
|
|||||||
});
|
});
|
||||||
setNewContent('');
|
setNewContent('');
|
||||||
setIsAdding(false);
|
setIsAdding(false);
|
||||||
|
isSubmittingRef.current = false;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,7 +141,12 @@ export const SwotQuadrant = forwardRef<HTMLDivElement, SwotQuadrantProps>(
|
|||||||
value={newContent}
|
value={newContent}
|
||||||
onChange={(e) => setNewContent(e.target.value)}
|
onChange={(e) => setNewContent(e.target.value)}
|
||||||
onKeyDown={handleKeyDown}
|
onKeyDown={handleKeyDown}
|
||||||
onBlur={handleAdd}
|
onBlur={(e) => {
|
||||||
|
// Don't trigger on blur if clicking on a button
|
||||||
|
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
|
||||||
|
handleAdd();
|
||||||
|
}
|
||||||
|
}}
|
||||||
placeholder="Décrivez cet élément..."
|
placeholder="Décrivez cet élément..."
|
||||||
className="w-full resize-none rounded border-0 bg-transparent p-1 text-sm text-foreground placeholder:text-muted focus:outline-none focus:ring-0"
|
className="w-full resize-none rounded border-0 bg-transparent p-1 text-sm text-foreground placeholder:text-muted focus:outline-none focus:ring-0"
|
||||||
rows={2}
|
rows={2}
|
||||||
@@ -156,6 +164,9 @@ export const SwotQuadrant = forwardRef<HTMLDivElement, SwotQuadrantProps>(
|
|||||||
Annuler
|
Annuler
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
|
onMouseDown={(e) => {
|
||||||
|
e.preventDefault(); // Prevent blur from textarea
|
||||||
|
}}
|
||||||
onClick={handleAdd}
|
onClick={handleAdd}
|
||||||
disabled={isPending || !newContent.trim()}
|
disabled={isPending || !newContent.trim()}
|
||||||
className={`rounded px-2 py-1 text-xs font-medium ${styles.text} hover:bg-white/50 disabled:opacity-50`}
|
className={`rounded px-2 py-1 text-xs font-medium ${styles.text} hover:bg-white/50 disabled:opacity-50`}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { forwardRef, useState, useTransition, ReactNode } from 'react';
|
import { forwardRef, useState, useTransition, useRef, ReactNode } from 'react';
|
||||||
import type { YearReviewCategory } from '@prisma/client';
|
import type { YearReviewCategory } from '@prisma/client';
|
||||||
import { createYearReviewItem } from '@/actions/year-review';
|
import { createYearReviewItem } from '@/actions/year-review';
|
||||||
import { YEAR_REVIEW_BY_CATEGORY } from '@/lib/types';
|
import { YEAR_REVIEW_BY_CATEGORY } from '@/lib/types';
|
||||||
@@ -17,15 +17,17 @@ export const YearReviewSection = forwardRef<HTMLDivElement, YearReviewSectionPro
|
|||||||
const [isAdding, setIsAdding] = useState(false);
|
const [isAdding, setIsAdding] = useState(false);
|
||||||
const [newContent, setNewContent] = useState('');
|
const [newContent, setNewContent] = useState('');
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
|
const isSubmittingRef = useRef(false);
|
||||||
|
|
||||||
const config = YEAR_REVIEW_BY_CATEGORY[category];
|
const config = YEAR_REVIEW_BY_CATEGORY[category];
|
||||||
|
|
||||||
async function handleAdd() {
|
async function handleAdd() {
|
||||||
if (!newContent.trim()) {
|
if (isSubmittingRef.current || !newContent.trim()) {
|
||||||
setIsAdding(false);
|
setIsAdding(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
isSubmittingRef.current = true;
|
||||||
startTransition(async () => {
|
startTransition(async () => {
|
||||||
await createYearReviewItem(sessionId, {
|
await createYearReviewItem(sessionId, {
|
||||||
content: newContent.trim(),
|
content: newContent.trim(),
|
||||||
@@ -33,6 +35,7 @@ export const YearReviewSection = forwardRef<HTMLDivElement, YearReviewSectionPro
|
|||||||
});
|
});
|
||||||
setNewContent('');
|
setNewContent('');
|
||||||
setIsAdding(false);
|
setIsAdding(false);
|
||||||
|
isSubmittingRef.current = false;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -97,7 +100,12 @@ export const YearReviewSection = forwardRef<HTMLDivElement, YearReviewSectionPro
|
|||||||
value={newContent}
|
value={newContent}
|
||||||
onChange={(e) => setNewContent(e.target.value)}
|
onChange={(e) => setNewContent(e.target.value)}
|
||||||
onKeyDown={handleKeyDown}
|
onKeyDown={handleKeyDown}
|
||||||
onBlur={handleAdd}
|
onBlur={(e) => {
|
||||||
|
// Don't trigger on blur if clicking on a button
|
||||||
|
if (!e.currentTarget.contains(e.relatedTarget as Node)) {
|
||||||
|
handleAdd();
|
||||||
|
}
|
||||||
|
}}
|
||||||
placeholder={`Décrivez ${config.title.toLowerCase()}...`}
|
placeholder={`Décrivez ${config.title.toLowerCase()}...`}
|
||||||
className="w-full resize-none rounded border-0 bg-transparent p-1 text-sm text-foreground placeholder:text-muted focus:outline-none focus:ring-0"
|
className="w-full resize-none rounded border-0 bg-transparent p-1 text-sm text-foreground placeholder:text-muted focus:outline-none focus:ring-0"
|
||||||
rows={2}
|
rows={2}
|
||||||
@@ -115,6 +123,9 @@ export const YearReviewSection = forwardRef<HTMLDivElement, YearReviewSectionPro
|
|||||||
Annuler
|
Annuler
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
|
onMouseDown={(e) => {
|
||||||
|
e.preventDefault(); // Prevent blur from textarea
|
||||||
|
}}
|
||||||
onClick={handleAdd}
|
onClick={handleAdd}
|
||||||
disabled={isPending || !newContent.trim()}
|
disabled={isPending || !newContent.trim()}
|
||||||
className="rounded px-2 py-1 text-xs font-medium text-primary hover:bg-primary/10 disabled:opacity-50"
|
className="rounded px-2 py-1 text-xs font-medium text-primary hover:bg-primary/10 disabled:opacity-50"
|
||||||
@@ -131,4 +142,3 @@ export const YearReviewSection = forwardRef<HTMLDivElement, YearReviewSectionPro
|
|||||||
);
|
);
|
||||||
|
|
||||||
YearReviewSection.displayName = 'YearReviewSection';
|
YearReviewSection.displayName = 'YearReviewSection';
|
||||||
|
|
||||||
|
|||||||
134
src/hooks/useLive.ts
Normal file
134
src/hooks/useLive.ts
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useState, useRef } from 'react';
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
|
||||||
|
export type LiveEvent = {
|
||||||
|
type: string;
|
||||||
|
payload: Record<string, unknown>;
|
||||||
|
userId?: string;
|
||||||
|
user?: { id: string; name: string | null; email: string };
|
||||||
|
timestamp: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
interface UseLiveOptions {
|
||||||
|
sessionId: string;
|
||||||
|
apiPath: string; // e.g., 'sessions', 'motivators', 'year-review'
|
||||||
|
currentUserId?: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
onEvent?: (event: LiveEvent) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UseLiveReturn {
|
||||||
|
isConnected: boolean;
|
||||||
|
lastEvent: LiveEvent | null;
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useLive({
|
||||||
|
sessionId,
|
||||||
|
apiPath,
|
||||||
|
currentUserId,
|
||||||
|
enabled = true,
|
||||||
|
onEvent,
|
||||||
|
}: UseLiveOptions): UseLiveReturn {
|
||||||
|
const [isConnected, setIsConnected] = useState(false);
|
||||||
|
const [lastEvent, setLastEvent] = useState<LiveEvent | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const router = useRouter();
|
||||||
|
const eventSourceRef = useRef<EventSource | null>(null);
|
||||||
|
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
|
const reconnectAttemptsRef = useRef(0);
|
||||||
|
const onEventRef = useRef(onEvent);
|
||||||
|
const currentUserIdRef = useRef(currentUserId);
|
||||||
|
|
||||||
|
// Keep refs updated
|
||||||
|
useEffect(() => {
|
||||||
|
onEventRef.current = onEvent;
|
||||||
|
}, [onEvent]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
currentUserIdRef.current = currentUserId;
|
||||||
|
}, [currentUserId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!enabled || typeof window === 'undefined') return;
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
// Close existing connection
|
||||||
|
if (eventSourceRef.current) {
|
||||||
|
eventSourceRef.current.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const eventSource = new EventSource(`/api/${apiPath}/${sessionId}/subscribe`);
|
||||||
|
eventSourceRef.current = eventSource;
|
||||||
|
|
||||||
|
eventSource.onopen = () => {
|
||||||
|
setIsConnected(true);
|
||||||
|
setError(null);
|
||||||
|
reconnectAttemptsRef.current = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
eventSource.onmessage = (event) => {
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(event.data) as LiveEvent;
|
||||||
|
|
||||||
|
// Handle connection event
|
||||||
|
if (data.type === 'connected') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client-side filter: ignore events created by current user
|
||||||
|
// This prevents duplicates when revalidatePath already refreshed the data
|
||||||
|
if (currentUserIdRef.current && data.userId === currentUserIdRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLastEvent(data);
|
||||||
|
onEventRef.current?.(data);
|
||||||
|
|
||||||
|
// Refresh the page data when we receive an event from another user
|
||||||
|
router.refresh();
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to parse SSE event:', e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
eventSource.onerror = () => {
|
||||||
|
setIsConnected(false);
|
||||||
|
eventSource.close();
|
||||||
|
|
||||||
|
// Exponential backoff reconnect
|
||||||
|
const delay = Math.min(1000 * Math.pow(2, reconnectAttemptsRef.current), 30000);
|
||||||
|
reconnectAttemptsRef.current++;
|
||||||
|
|
||||||
|
if (reconnectAttemptsRef.current <= 5) {
|
||||||
|
reconnectTimeoutRef.current = setTimeout(connect, delay);
|
||||||
|
} else {
|
||||||
|
setError('Connexion perdue. Rechargez la page.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} catch (e) {
|
||||||
|
setError('Impossible de se connecter au mode live');
|
||||||
|
console.error('Failed to create EventSource:', e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
connect();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (eventSourceRef.current) {
|
||||||
|
eventSourceRef.current.close();
|
||||||
|
eventSourceRef.current = null;
|
||||||
|
}
|
||||||
|
if (reconnectTimeoutRef.current) {
|
||||||
|
clearTimeout(reconnectTimeoutRef.current);
|
||||||
|
reconnectTimeoutRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [sessionId, apiPath, enabled, router]);
|
||||||
|
|
||||||
|
return { isConnected, lastEvent, error };
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,15 +1,8 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useState, useRef } from 'react';
|
import { useLive, type LiveEvent } from './useLive';
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
|
|
||||||
export type MotivatorLiveEvent = {
|
export type MotivatorLiveEvent = LiveEvent;
|
||||||
type: string;
|
|
||||||
payload: Record<string, unknown>;
|
|
||||||
userId?: string;
|
|
||||||
user?: { id: string; name: string | null; email: string };
|
|
||||||
timestamp: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
interface UseMotivatorLiveOptions {
|
interface UseMotivatorLiveOptions {
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
@@ -30,101 +23,11 @@ export function useMotivatorLive({
|
|||||||
enabled = true,
|
enabled = true,
|
||||||
onEvent,
|
onEvent,
|
||||||
}: UseMotivatorLiveOptions): UseMotivatorLiveReturn {
|
}: UseMotivatorLiveOptions): UseMotivatorLiveReturn {
|
||||||
const [isConnected, setIsConnected] = useState(false);
|
return useLive({
|
||||||
const [lastEvent, setLastEvent] = useState<MotivatorLiveEvent | null>(null);
|
sessionId,
|
||||||
const [error, setError] = useState<string | null>(null);
|
apiPath: 'motivators',
|
||||||
const router = useRouter();
|
currentUserId,
|
||||||
const eventSourceRef = useRef<EventSource | null>(null);
|
enabled,
|
||||||
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
onEvent,
|
||||||
const reconnectAttemptsRef = useRef(0);
|
});
|
||||||
const onEventRef = useRef(onEvent);
|
|
||||||
const currentUserIdRef = useRef(currentUserId);
|
|
||||||
|
|
||||||
// Keep refs updated
|
|
||||||
useEffect(() => {
|
|
||||||
onEventRef.current = onEvent;
|
|
||||||
}, [onEvent]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
currentUserIdRef.current = currentUserId;
|
|
||||||
}, [currentUserId]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!enabled || typeof window === 'undefined') return;
|
|
||||||
|
|
||||||
function connect() {
|
|
||||||
// Close existing connection
|
|
||||||
if (eventSourceRef.current) {
|
|
||||||
eventSourceRef.current.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const eventSource = new EventSource(`/api/motivators/${sessionId}/subscribe`);
|
|
||||||
eventSourceRef.current = eventSource;
|
|
||||||
|
|
||||||
eventSource.onopen = () => {
|
|
||||||
setIsConnected(true);
|
|
||||||
setError(null);
|
|
||||||
reconnectAttemptsRef.current = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
eventSource.onmessage = (event) => {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(event.data) as MotivatorLiveEvent;
|
|
||||||
|
|
||||||
// Handle connection event
|
|
||||||
if (data.type === 'connected') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client-side filter: ignore events created by current user
|
|
||||||
if (currentUserIdRef.current && data.userId === currentUserIdRef.current) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setLastEvent(data);
|
|
||||||
onEventRef.current?.(data);
|
|
||||||
|
|
||||||
// Refresh the page data when we receive an event from another user
|
|
||||||
router.refresh();
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to parse SSE event:', e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
eventSource.onerror = () => {
|
|
||||||
setIsConnected(false);
|
|
||||||
eventSource.close();
|
|
||||||
|
|
||||||
// Exponential backoff reconnect
|
|
||||||
const delay = Math.min(1000 * Math.pow(2, reconnectAttemptsRef.current), 30000);
|
|
||||||
reconnectAttemptsRef.current++;
|
|
||||||
|
|
||||||
if (reconnectAttemptsRef.current <= 5) {
|
|
||||||
reconnectTimeoutRef.current = setTimeout(connect, delay);
|
|
||||||
} else {
|
|
||||||
setError('Connexion perdue. Rechargez la page.');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (e) {
|
|
||||||
setError('Impossible de se connecter au mode live');
|
|
||||||
console.error('Failed to create EventSource:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
connect();
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if (eventSourceRef.current) {
|
|
||||||
eventSourceRef.current.close();
|
|
||||||
eventSourceRef.current = null;
|
|
||||||
}
|
|
||||||
if (reconnectTimeoutRef.current) {
|
|
||||||
clearTimeout(reconnectTimeoutRef.current);
|
|
||||||
reconnectTimeoutRef.current = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [sessionId, enabled, router]);
|
|
||||||
|
|
||||||
return { isConnected, lastEvent, error };
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,10 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useState, useRef } from 'react';
|
import { useLive, type LiveEvent } from './useLive';
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
|
|
||||||
export type LiveEvent = {
|
|
||||||
type: string;
|
|
||||||
payload: Record<string, unknown>;
|
|
||||||
userId?: string; // ID of the user who created the event
|
|
||||||
user?: { id: string; name: string | null; email: string };
|
|
||||||
timestamp: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
interface UseSessionLiveOptions {
|
interface UseSessionLiveOptions {
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
currentUserId?: string; // Current user ID for client-side filtering
|
currentUserId?: string;
|
||||||
enabled?: boolean;
|
enabled?: boolean;
|
||||||
onEvent?: (event: LiveEvent) => void;
|
onEvent?: (event: LiveEvent) => void;
|
||||||
}
|
}
|
||||||
@@ -30,102 +21,13 @@ export function useSessionLive({
|
|||||||
enabled = true,
|
enabled = true,
|
||||||
onEvent,
|
onEvent,
|
||||||
}: UseSessionLiveOptions): UseSessionLiveReturn {
|
}: UseSessionLiveOptions): UseSessionLiveReturn {
|
||||||
const [isConnected, setIsConnected] = useState(false);
|
return useLive({
|
||||||
const [lastEvent, setLastEvent] = useState<LiveEvent | null>(null);
|
sessionId,
|
||||||
const [error, setError] = useState<string | null>(null);
|
apiPath: 'sessions',
|
||||||
const router = useRouter();
|
currentUserId,
|
||||||
const eventSourceRef = useRef<EventSource | null>(null);
|
enabled,
|
||||||
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
onEvent,
|
||||||
const reconnectAttemptsRef = useRef(0);
|
});
|
||||||
const onEventRef = useRef(onEvent);
|
|
||||||
const currentUserIdRef = useRef(currentUserId);
|
|
||||||
|
|
||||||
// Keep refs updated
|
|
||||||
useEffect(() => {
|
|
||||||
onEventRef.current = onEvent;
|
|
||||||
}, [onEvent]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
currentUserIdRef.current = currentUserId;
|
|
||||||
}, [currentUserId]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!enabled || typeof window === 'undefined') return;
|
|
||||||
|
|
||||||
function connect() {
|
|
||||||
// Close existing connection
|
|
||||||
if (eventSourceRef.current) {
|
|
||||||
eventSourceRef.current.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
export type { LiveEvent };
|
||||||
const eventSource = new EventSource(`/api/sessions/${sessionId}/subscribe`);
|
|
||||||
eventSourceRef.current = eventSource;
|
|
||||||
|
|
||||||
eventSource.onopen = () => {
|
|
||||||
setIsConnected(true);
|
|
||||||
setError(null);
|
|
||||||
reconnectAttemptsRef.current = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
eventSource.onmessage = (event) => {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(event.data) as LiveEvent;
|
|
||||||
|
|
||||||
// Handle connection event
|
|
||||||
if (data.type === 'connected') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client-side filter: ignore events created by current user
|
|
||||||
// This prevents duplicates when revalidatePath already refreshed the data
|
|
||||||
if (currentUserIdRef.current && data.userId === currentUserIdRef.current) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setLastEvent(data);
|
|
||||||
onEventRef.current?.(data);
|
|
||||||
|
|
||||||
// Refresh the page data when we receive an event from another user
|
|
||||||
router.refresh();
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to parse SSE event:', e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
eventSource.onerror = () => {
|
|
||||||
setIsConnected(false);
|
|
||||||
eventSource.close();
|
|
||||||
|
|
||||||
// Exponential backoff reconnect
|
|
||||||
const delay = Math.min(1000 * Math.pow(2, reconnectAttemptsRef.current), 30000);
|
|
||||||
reconnectAttemptsRef.current++;
|
|
||||||
|
|
||||||
if (reconnectAttemptsRef.current <= 5) {
|
|
||||||
reconnectTimeoutRef.current = setTimeout(connect, delay);
|
|
||||||
} else {
|
|
||||||
setError('Connexion perdue. Rechargez la page.');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (e) {
|
|
||||||
setError('Impossible de se connecter au mode live');
|
|
||||||
console.error('Failed to create EventSource:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
connect();
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if (eventSourceRef.current) {
|
|
||||||
eventSourceRef.current.close();
|
|
||||||
eventSourceRef.current = null;
|
|
||||||
}
|
|
||||||
if (reconnectTimeoutRef.current) {
|
|
||||||
clearTimeout(reconnectTimeoutRef.current);
|
|
||||||
reconnectTimeoutRef.current = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [sessionId, enabled, router]);
|
|
||||||
|
|
||||||
return { isConnected, lastEvent, error };
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,15 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useEffect, useState, useRef } from 'react';
|
import { useLive, type LiveEvent } from './useLive';
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
|
|
||||||
export type YearReviewLiveEvent = {
|
|
||||||
type: string;
|
|
||||||
payload: Record<string, unknown>;
|
|
||||||
userId?: string;
|
|
||||||
user?: { id: string; name: string | null; email: string };
|
|
||||||
timestamp: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
interface UseYearReviewLiveOptions {
|
interface UseYearReviewLiveOptions {
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
@@ -24,108 +15,19 @@ interface UseYearReviewLiveReturn {
|
|||||||
error: string | null;
|
error: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type YearReviewLiveEvent = LiveEvent;
|
||||||
|
|
||||||
export function useYearReviewLive({
|
export function useYearReviewLive({
|
||||||
sessionId,
|
sessionId,
|
||||||
currentUserId,
|
currentUserId,
|
||||||
enabled = true,
|
enabled = true,
|
||||||
onEvent,
|
onEvent,
|
||||||
}: UseYearReviewLiveOptions): UseYearReviewLiveReturn {
|
}: UseYearReviewLiveOptions): UseYearReviewLiveReturn {
|
||||||
const [isConnected, setIsConnected] = useState(false);
|
return useLive({
|
||||||
const [lastEvent, setLastEvent] = useState<YearReviewLiveEvent | null>(null);
|
sessionId,
|
||||||
const [error, setError] = useState<string | null>(null);
|
apiPath: 'year-review',
|
||||||
const router = useRouter();
|
currentUserId,
|
||||||
const eventSourceRef = useRef<EventSource | null>(null);
|
enabled,
|
||||||
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
onEvent,
|
||||||
const reconnectAttemptsRef = useRef(0);
|
});
|
||||||
const onEventRef = useRef(onEvent);
|
|
||||||
const currentUserIdRef = useRef(currentUserId);
|
|
||||||
|
|
||||||
// Keep refs updated
|
|
||||||
useEffect(() => {
|
|
||||||
onEventRef.current = onEvent;
|
|
||||||
}, [onEvent]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
currentUserIdRef.current = currentUserId;
|
|
||||||
}, [currentUserId]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!enabled || typeof window === 'undefined') return;
|
|
||||||
|
|
||||||
function connect() {
|
|
||||||
// Close existing connection
|
|
||||||
if (eventSourceRef.current) {
|
|
||||||
eventSourceRef.current.close();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
const eventSource = new EventSource(`/api/year-review/${sessionId}/subscribe`);
|
|
||||||
eventSourceRef.current = eventSource;
|
|
||||||
|
|
||||||
eventSource.onopen = () => {
|
|
||||||
setIsConnected(true);
|
|
||||||
setError(null);
|
|
||||||
reconnectAttemptsRef.current = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
eventSource.onmessage = (event) => {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(event.data) as YearReviewLiveEvent;
|
|
||||||
|
|
||||||
// Handle connection event
|
|
||||||
if (data.type === 'connected') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client-side filter: ignore events created by current user
|
|
||||||
if (currentUserIdRef.current && data.userId === currentUserIdRef.current) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setLastEvent(data);
|
|
||||||
onEventRef.current?.(data);
|
|
||||||
|
|
||||||
// Refresh the page data when we receive an event from another user
|
|
||||||
router.refresh();
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Failed to parse SSE event:', e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
eventSource.onerror = () => {
|
|
||||||
setIsConnected(false);
|
|
||||||
eventSource.close();
|
|
||||||
|
|
||||||
// Exponential backoff reconnect
|
|
||||||
const delay = Math.min(1000 * Math.pow(2, reconnectAttemptsRef.current), 30000);
|
|
||||||
reconnectAttemptsRef.current++;
|
|
||||||
|
|
||||||
if (reconnectAttemptsRef.current <= 5) {
|
|
||||||
reconnectTimeoutRef.current = setTimeout(connect, delay);
|
|
||||||
} else {
|
|
||||||
setError('Connexion perdue. Rechargez la page.');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} catch (e) {
|
|
||||||
setError('Impossible de se connecter au mode live');
|
|
||||||
console.error('Failed to create EventSource:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
connect();
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
if (eventSourceRef.current) {
|
|
||||||
eventSourceRef.current.close();
|
|
||||||
eventSourceRef.current = null;
|
|
||||||
}
|
|
||||||
if (reconnectTimeoutRef.current) {
|
|
||||||
clearTimeout(reconnectTimeoutRef.current);
|
|
||||||
reconnectTimeoutRef.current = null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}, [sessionId, enabled, router]);
|
|
||||||
|
|
||||||
return { isConnected, lastEvent, error };
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user