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

This commit is contained in:
Julien Froidefond
2025-12-16 10:41:16 +01:00
parent 246298dd82
commit fd65e0d5b9
7 changed files with 198 additions and 331 deletions

View File

@@ -1,6 +1,6 @@
'use client';
import { useState, useTransition } from 'react';
import { useState, useTransition, useEffect } from 'react';
import {
DndContext,
closestCenter,
@@ -35,6 +35,11 @@ export function MotivatorBoard({ sessionId, cards: initialCards, canEdit }: Moti
const [step, setStep] = useState<Step>('ranking');
const [isPending, startTransition] = useTransition();
// Sync local state with props when they change (e.g., from SSE refresh)
useEffect(() => {
setCards(initialCards);
}, [initialCards]);
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {

View File

@@ -1,6 +1,6 @@
'use client';
import { forwardRef, useState, useTransition, ReactNode } from 'react';
import { forwardRef, useState, useTransition, useRef, ReactNode } from 'react';
import type { SwotCategory } from '@prisma/client';
import { createSwotItem } from '@/actions/swot';
import { QuadrantHelpPanel } from './QuadrantHelp';
@@ -43,15 +43,17 @@ export const SwotQuadrant = forwardRef<HTMLDivElement, SwotQuadrantProps>(
const [newContent, setNewContent] = useState('');
const [isPending, startTransition] = useTransition();
const [showHelp, setShowHelp] = useState(false);
const isSubmittingRef = useRef(false);
const styles = categoryStyles[category];
async function handleAdd() {
if (!newContent.trim()) {
if (isSubmittingRef.current || !newContent.trim()) {
setIsAdding(false);
return;
}
isSubmittingRef.current = true;
startTransition(async () => {
await createSwotItem(sessionId, {
content: newContent.trim(),
@@ -59,6 +61,7 @@ export const SwotQuadrant = forwardRef<HTMLDivElement, SwotQuadrantProps>(
});
setNewContent('');
setIsAdding(false);
isSubmittingRef.current = false;
});
}
@@ -138,7 +141,12 @@ export const SwotQuadrant = forwardRef<HTMLDivElement, SwotQuadrantProps>(
value={newContent}
onChange={(e) => setNewContent(e.target.value)}
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..."
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}
@@ -156,6 +164,9 @@ export const SwotQuadrant = forwardRef<HTMLDivElement, SwotQuadrantProps>(
Annuler
</button>
<button
onMouseDown={(e) => {
e.preventDefault(); // Prevent blur from textarea
}}
onClick={handleAdd}
disabled={isPending || !newContent.trim()}
className={`rounded px-2 py-1 text-xs font-medium ${styles.text} hover:bg-white/50 disabled:opacity-50`}

View File

@@ -1,6 +1,6 @@
'use client';
import { forwardRef, useState, useTransition, ReactNode } from 'react';
import { forwardRef, useState, useTransition, useRef, ReactNode } from 'react';
import type { YearReviewCategory } from '@prisma/client';
import { createYearReviewItem } from '@/actions/year-review';
import { YEAR_REVIEW_BY_CATEGORY } from '@/lib/types';
@@ -17,15 +17,17 @@ export const YearReviewSection = forwardRef<HTMLDivElement, YearReviewSectionPro
const [isAdding, setIsAdding] = useState(false);
const [newContent, setNewContent] = useState('');
const [isPending, startTransition] = useTransition();
const isSubmittingRef = useRef(false);
const config = YEAR_REVIEW_BY_CATEGORY[category];
async function handleAdd() {
if (!newContent.trim()) {
if (isSubmittingRef.current || !newContent.trim()) {
setIsAdding(false);
return;
}
isSubmittingRef.current = true;
startTransition(async () => {
await createYearReviewItem(sessionId, {
content: newContent.trim(),
@@ -33,6 +35,7 @@ export const YearReviewSection = forwardRef<HTMLDivElement, YearReviewSectionPro
});
setNewContent('');
setIsAdding(false);
isSubmittingRef.current = false;
});
}
@@ -97,7 +100,12 @@ export const YearReviewSection = forwardRef<HTMLDivElement, YearReviewSectionPro
value={newContent}
onChange={(e) => setNewContent(e.target.value)}
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()}...`}
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}
@@ -115,6 +123,9 @@ export const YearReviewSection = forwardRef<HTMLDivElement, YearReviewSectionPro
Annuler
</button>
<button
onMouseDown={(e) => {
e.preventDefault(); // Prevent blur from textarea
}}
onClick={handleAdd}
disabled={isPending || !newContent.trim()}
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';

134
src/hooks/useLive.ts Normal file
View 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 };
}

View File

@@ -1,15 +1,8 @@
'use client';
import { useEffect, useState, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useLive, type LiveEvent } from './useLive';
export type MotivatorLiveEvent = {
type: string;
payload: Record<string, unknown>;
userId?: string;
user?: { id: string; name: string | null; email: string };
timestamp: string;
};
export type MotivatorLiveEvent = LiveEvent;
interface UseMotivatorLiveOptions {
sessionId: string;
@@ -30,101 +23,11 @@ export function useMotivatorLive({
enabled = true,
onEvent,
}: UseMotivatorLiveOptions): UseMotivatorLiveReturn {
const [isConnected, setIsConnected] = useState(false);
const [lastEvent, setLastEvent] = useState<MotivatorLiveEvent | 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/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 };
return useLive({
sessionId,
apiPath: 'motivators',
currentUserId,
enabled,
onEvent,
});
}

View File

@@ -1,19 +1,10 @@
'use client';
import { useEffect, useState, useRef } from 'react';
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;
};
import { useLive, type LiveEvent } from './useLive';
interface UseSessionLiveOptions {
sessionId: string;
currentUserId?: string; // Current user ID for client-side filtering
currentUserId?: string;
enabled?: boolean;
onEvent?: (event: LiveEvent) => void;
}
@@ -30,102 +21,13 @@ export function useSessionLive({
enabled = true,
onEvent,
}: UseSessionLiveOptions): UseSessionLiveReturn {
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/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 };
return useLive({
sessionId,
apiPath: 'sessions',
currentUserId,
enabled,
onEvent,
});
}
export type { LiveEvent };

View File

@@ -1,15 +1,6 @@
'use client';
import { useEffect, useState, useRef } from 'react';
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;
};
import { useLive, type LiveEvent } from './useLive';
interface UseYearReviewLiveOptions {
sessionId: string;
@@ -24,108 +15,19 @@ interface UseYearReviewLiveReturn {
error: string | null;
}
export type YearReviewLiveEvent = LiveEvent;
export function useYearReviewLive({
sessionId,
currentUserId,
enabled = true,
onEvent,
}: UseYearReviewLiveOptions): UseYearReviewLiveReturn {
const [isConnected, setIsConnected] = useState(false);
const [lastEvent, setLastEvent] = useState<YearReviewLiveEvent | 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/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 };
return useLive({
sessionId,
apiPath: 'year-review',
currentUserId,
enabled,
onEvent,
});
}