Compare commits
2 Commits
56a9c2c3be
...
fd65e0d5b9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd65e0d5b9 | ||
|
|
246298dd82 |
@@ -1,115 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState, useTransition, useRef, useEffect } from 'react';
|
|
||||||
import { updateMotivatorSession } from '@/actions/moving-motivators';
|
|
||||||
|
|
||||||
interface EditableMotivatorTitleProps {
|
|
||||||
sessionId: string;
|
|
||||||
initialTitle: string;
|
|
||||||
isOwner: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function EditableMotivatorTitle({
|
|
||||||
sessionId,
|
|
||||||
initialTitle,
|
|
||||||
isOwner,
|
|
||||||
}: EditableMotivatorTitleProps) {
|
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
|
||||||
const [title, setTitle] = useState(initialTitle);
|
|
||||||
const [isPending, startTransition] = useTransition();
|
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
|
||||||
const prevInitialTitleRef = useRef(initialTitle);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (isEditing && inputRef.current) {
|
|
||||||
inputRef.current.focus();
|
|
||||||
inputRef.current.select();
|
|
||||||
}
|
|
||||||
}, [isEditing]);
|
|
||||||
|
|
||||||
// Update local state when prop changes (e.g., from SSE) - only when not editing
|
|
||||||
// This is a valid pattern for syncing external state (SSE updates) with local state
|
|
||||||
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isEditing && prevInitialTitleRef.current !== initialTitle) {
|
|
||||||
prevInitialTitleRef.current = initialTitle;
|
|
||||||
// Synchronizing with external prop updates (e.g., from SSE)
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
setTitle(initialTitle);
|
|
||||||
}
|
|
||||||
}, [initialTitle, isEditing]);
|
|
||||||
|
|
||||||
const handleSave = () => {
|
|
||||||
if (!title.trim()) {
|
|
||||||
setTitle(initialTitle);
|
|
||||||
setIsEditing(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (title.trim() === initialTitle) {
|
|
||||||
setIsEditing(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
startTransition(async () => {
|
|
||||||
const result = await updateMotivatorSession(sessionId, { title: title.trim() });
|
|
||||||
if (!result.success) {
|
|
||||||
setTitle(initialTitle);
|
|
||||||
console.error(result.error);
|
|
||||||
}
|
|
||||||
setIsEditing(false);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
|
||||||
if (e.key === 'Enter') {
|
|
||||||
e.preventDefault();
|
|
||||||
handleSave();
|
|
||||||
} else if (e.key === 'Escape') {
|
|
||||||
setTitle(initialTitle);
|
|
||||||
setIsEditing(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!isOwner) {
|
|
||||||
return <h1 className="text-3xl font-bold text-foreground">{title}</h1>;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isEditing) {
|
|
||||||
return (
|
|
||||||
<input
|
|
||||||
ref={inputRef}
|
|
||||||
type="text"
|
|
||||||
value={title}
|
|
||||||
onChange={(e) => setTitle(e.target.value)}
|
|
||||||
onBlur={handleSave}
|
|
||||||
onKeyDown={handleKeyDown}
|
|
||||||
disabled={isPending}
|
|
||||||
className="w-full max-w-md rounded-lg border border-border bg-input px-3 py-1.5 text-3xl font-bold text-foreground outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 disabled:opacity-50"
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
onClick={() => setIsEditing(true)}
|
|
||||||
className="group flex items-center gap-2 text-left"
|
|
||||||
title="Cliquez pour modifier"
|
|
||||||
>
|
|
||||||
<h1 className="text-3xl font-bold text-foreground">{title}</h1>
|
|
||||||
<svg
|
|
||||||
className="h-5 w-5 text-muted opacity-0 transition-opacity group-hover:opacity-100"
|
|
||||||
fill="none"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
stroke="currentColor"
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
strokeWidth={2}
|
|
||||||
d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,7 @@ import { auth } from '@/lib/auth';
|
|||||||
import { getMotivatorSessionById } from '@/services/moving-motivators';
|
import { getMotivatorSessionById } from '@/services/moving-motivators';
|
||||||
import { MotivatorBoard, MotivatorLiveWrapper } from '@/components/moving-motivators';
|
import { MotivatorBoard, MotivatorLiveWrapper } from '@/components/moving-motivators';
|
||||||
import { Badge, CollaboratorDisplay } from '@/components/ui';
|
import { Badge, CollaboratorDisplay } from '@/components/ui';
|
||||||
import { EditableMotivatorTitle } from './EditableTitle';
|
import { EditableMotivatorTitle } from '@/components/ui';
|
||||||
|
|
||||||
interface MotivatorSessionPageProps {
|
interface MotivatorSessionPageProps {
|
||||||
params: Promise<{ id: string }>;
|
params: Promise<{ id: string }>;
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { auth } from '@/lib/auth';
|
|||||||
import { getSessionById } from '@/services/sessions';
|
import { getSessionById } from '@/services/sessions';
|
||||||
import { SwotBoard } from '@/components/swot/SwotBoard';
|
import { SwotBoard } from '@/components/swot/SwotBoard';
|
||||||
import { SessionLiveWrapper } from '@/components/collaboration';
|
import { SessionLiveWrapper } from '@/components/collaboration';
|
||||||
import { EditableTitle } from '@/components/session';
|
import { EditableSessionTitle } from '@/components/ui';
|
||||||
import { Badge, CollaboratorDisplay } from '@/components/ui';
|
import { Badge, CollaboratorDisplay } from '@/components/ui';
|
||||||
|
|
||||||
interface SessionPageProps {
|
interface SessionPageProps {
|
||||||
@@ -44,7 +44,7 @@ export default async function SessionPage({ params }: SessionPageProps) {
|
|||||||
|
|
||||||
<div className="flex items-start justify-between">
|
<div className="flex items-start justify-between">
|
||||||
<div>
|
<div>
|
||||||
<EditableTitle
|
<EditableSessionTitle
|
||||||
sessionId={session.id}
|
sessionId={session.id}
|
||||||
initialTitle={session.title}
|
initialTitle={session.title}
|
||||||
isOwner={session.isOwner}
|
isOwner={session.isOwner}
|
||||||
|
|||||||
@@ -1,114 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useState, useTransition, useRef, useEffect } from 'react';
|
|
||||||
import { updateYearReviewSession } from '@/actions/year-review';
|
|
||||||
|
|
||||||
interface EditableYearReviewTitleProps {
|
|
||||||
sessionId: string;
|
|
||||||
initialTitle: string;
|
|
||||||
isOwner: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function EditableYearReviewTitle({
|
|
||||||
sessionId,
|
|
||||||
initialTitle,
|
|
||||||
isOwner,
|
|
||||||
}: EditableYearReviewTitleProps) {
|
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
|
||||||
const [title, setTitle] = useState(initialTitle);
|
|
||||||
const [isPending, startTransition] = useTransition();
|
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
|
||||||
const prevInitialTitleRef = useRef(initialTitle);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (isEditing && inputRef.current) {
|
|
||||||
inputRef.current.focus();
|
|
||||||
inputRef.current.select();
|
|
||||||
}
|
|
||||||
}, [isEditing]);
|
|
||||||
|
|
||||||
// Update local state when prop changes (e.g., from SSE) - only when not editing
|
|
||||||
// This is a valid pattern for syncing external state (SSE updates) with local state
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isEditing && prevInitialTitleRef.current !== initialTitle) {
|
|
||||||
prevInitialTitleRef.current = initialTitle;
|
|
||||||
// Synchronizing with external prop updates (e.g., from SSE)
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
setTitle(initialTitle);
|
|
||||||
}
|
|
||||||
}, [initialTitle, isEditing]);
|
|
||||||
|
|
||||||
const handleSave = () => {
|
|
||||||
if (!title.trim()) {
|
|
||||||
setTitle(initialTitle);
|
|
||||||
setIsEditing(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (title.trim() === initialTitle) {
|
|
||||||
setIsEditing(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
startTransition(async () => {
|
|
||||||
const result = await updateYearReviewSession(sessionId, { title: title.trim() });
|
|
||||||
if (!result.success) {
|
|
||||||
setTitle(initialTitle);
|
|
||||||
console.error(result.error);
|
|
||||||
}
|
|
||||||
setIsEditing(false);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
|
||||||
if (e.key === 'Enter') {
|
|
||||||
e.preventDefault();
|
|
||||||
handleSave();
|
|
||||||
} else if (e.key === 'Escape') {
|
|
||||||
setTitle(initialTitle);
|
|
||||||
setIsEditing(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!isOwner) {
|
|
||||||
return <h1 className="text-3xl font-bold text-foreground">{title}</h1>;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isEditing) {
|
|
||||||
return (
|
|
||||||
<input
|
|
||||||
ref={inputRef}
|
|
||||||
type="text"
|
|
||||||
value={title}
|
|
||||||
onChange={(e) => setTitle(e.target.value)}
|
|
||||||
onBlur={handleSave}
|
|
||||||
onKeyDown={handleKeyDown}
|
|
||||||
disabled={isPending}
|
|
||||||
className="w-full max-w-md rounded-lg border border-border bg-input px-3 py-1.5 text-3xl font-bold text-foreground outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 disabled:opacity-50"
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
onClick={() => setIsEditing(true)}
|
|
||||||
className="group flex items-center gap-2 text-left"
|
|
||||||
title="Cliquez pour modifier"
|
|
||||||
>
|
|
||||||
<h1 className="text-3xl font-bold text-foreground">{title}</h1>
|
|
||||||
<svg
|
|
||||||
className="h-5 w-5 text-muted opacity-0 transition-opacity group-hover:opacity-100"
|
|
||||||
fill="none"
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
stroke="currentColor"
|
|
||||||
>
|
|
||||||
<path
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
strokeWidth={2}
|
|
||||||
d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,7 @@ import { auth } from '@/lib/auth';
|
|||||||
import { getYearReviewSessionById } from '@/services/year-review';
|
import { getYearReviewSessionById } from '@/services/year-review';
|
||||||
import { YearReviewBoard, YearReviewLiveWrapper } from '@/components/year-review';
|
import { YearReviewBoard, YearReviewLiveWrapper } from '@/components/year-review';
|
||||||
import { Badge, CollaboratorDisplay } from '@/components/ui';
|
import { Badge, CollaboratorDisplay } from '@/components/ui';
|
||||||
import { EditableYearReviewTitle } from './EditableTitle';
|
import { EditableYearReviewTitle } from '@/components/ui';
|
||||||
|
|
||||||
interface YearReviewSessionPageProps {
|
interface YearReviewSessionPageProps {
|
||||||
params: Promise<{ id: string }>;
|
params: Promise<{ id: string }>;
|
||||||
|
|||||||
@@ -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 +0,0 @@
|
|||||||
export { EditableTitle } from './EditableTitle';
|
|
||||||
@@ -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`}
|
||||||
|
|||||||
29
src/components/ui/EditableMotivatorTitle.tsx
Normal file
29
src/components/ui/EditableMotivatorTitle.tsx
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { EditableTitle } from './EditableTitle';
|
||||||
|
import { updateMotivatorSession } from '@/actions/moving-motivators';
|
||||||
|
|
||||||
|
interface EditableMotivatorTitleProps {
|
||||||
|
sessionId: string;
|
||||||
|
initialTitle: string;
|
||||||
|
isOwner: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditableMotivatorTitle({
|
||||||
|
sessionId,
|
||||||
|
initialTitle,
|
||||||
|
isOwner,
|
||||||
|
}: EditableMotivatorTitleProps) {
|
||||||
|
return (
|
||||||
|
<EditableTitle
|
||||||
|
sessionId={sessionId}
|
||||||
|
initialTitle={initialTitle}
|
||||||
|
isOwner={isOwner}
|
||||||
|
onUpdate={async (id, title) => {
|
||||||
|
const result = await updateMotivatorSession(id, { title });
|
||||||
|
return result;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
29
src/components/ui/EditableSessionTitle.tsx
Normal file
29
src/components/ui/EditableSessionTitle.tsx
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { EditableTitle } from './EditableTitle';
|
||||||
|
import { updateSessionTitle } from '@/actions/session';
|
||||||
|
|
||||||
|
interface EditableSessionTitleProps {
|
||||||
|
sessionId: string;
|
||||||
|
initialTitle: string;
|
||||||
|
isOwner: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditableSessionTitle({
|
||||||
|
sessionId,
|
||||||
|
initialTitle,
|
||||||
|
isOwner,
|
||||||
|
}: EditableSessionTitleProps) {
|
||||||
|
return (
|
||||||
|
<EditableTitle
|
||||||
|
sessionId={sessionId}
|
||||||
|
initialTitle={initialTitle}
|
||||||
|
isOwner={isOwner}
|
||||||
|
onUpdate={async (id, title) => {
|
||||||
|
const result = await updateSessionTitle(id, title);
|
||||||
|
return result;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,20 +1,28 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useTransition, useRef, useEffect } from 'react';
|
import { useState, useTransition, useRef, useEffect, useMemo } from 'react';
|
||||||
import { updateSessionTitle } from '@/actions/session';
|
|
||||||
|
|
||||||
interface EditableTitleProps {
|
interface EditableTitleProps {
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
initialTitle: string;
|
initialTitle: string;
|
||||||
isOwner: boolean;
|
isOwner: boolean;
|
||||||
|
onUpdate: (sessionId: string, title: string) => Promise<{ success: boolean; error?: string }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function EditableTitle({ sessionId, initialTitle, isOwner }: EditableTitleProps) {
|
export function EditableTitle({
|
||||||
|
sessionId,
|
||||||
|
initialTitle,
|
||||||
|
isOwner,
|
||||||
|
onUpdate,
|
||||||
|
}: EditableTitleProps) {
|
||||||
const [isEditing, setIsEditing] = useState(false);
|
const [isEditing, setIsEditing] = useState(false);
|
||||||
const [title, setTitle] = useState(initialTitle);
|
const [editingTitle, setEditingTitle] = useState('');
|
||||||
const [isPending, startTransition] = useTransition();
|
const [isPending, startTransition] = useTransition();
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
// Use editingTitle when editing, otherwise use initialTitle (synced from SSE)
|
||||||
|
const title = useMemo(() => (isEditing ? editingTitle : initialTitle), [isEditing, editingTitle, initialTitle]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isEditing && inputRef.current) {
|
if (isEditing && inputRef.current) {
|
||||||
inputRef.current.focus();
|
inputRef.current.focus();
|
||||||
@@ -22,35 +30,28 @@ export function EditableTitle({ sessionId, initialTitle, isOwner }: EditableTitl
|
|||||||
}
|
}
|
||||||
}, [isEditing]);
|
}, [isEditing]);
|
||||||
|
|
||||||
// Update local state when prop changes (e.g., from SSE) - only when not editing
|
|
||||||
// This is a valid pattern for syncing external state (SSE updates) with local state
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isEditing) {
|
|
||||||
// Synchronizing with external prop updates (e.g., from SSE)
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
setTitle(initialTitle);
|
|
||||||
}
|
|
||||||
}, [initialTitle, isEditing]);
|
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleSave = () => {
|
||||||
if (!title.trim()) {
|
const trimmedTitle = editingTitle.trim();
|
||||||
setTitle(initialTitle);
|
if (!trimmedTitle) {
|
||||||
|
setEditingTitle('');
|
||||||
setIsEditing(false);
|
setIsEditing(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (title.trim() === initialTitle) {
|
if (trimmedTitle === initialTitle) {
|
||||||
|
setEditingTitle('');
|
||||||
setIsEditing(false);
|
setIsEditing(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
startTransition(async () => {
|
startTransition(async () => {
|
||||||
const result = await updateSessionTitle(sessionId, title.trim());
|
const result = await onUpdate(sessionId, trimmedTitle);
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
setTitle(initialTitle);
|
setEditingTitle('');
|
||||||
console.error(result.error);
|
console.error(result.error);
|
||||||
}
|
}
|
||||||
setIsEditing(false);
|
setIsEditing(false);
|
||||||
|
setEditingTitle('');
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -59,7 +60,7 @@ export function EditableTitle({ sessionId, initialTitle, isOwner }: EditableTitl
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
handleSave();
|
handleSave();
|
||||||
} else if (e.key === 'Escape') {
|
} else if (e.key === 'Escape') {
|
||||||
setTitle(initialTitle);
|
setEditingTitle('');
|
||||||
setIsEditing(false);
|
setIsEditing(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -73,8 +74,8 @@ export function EditableTitle({ sessionId, initialTitle, isOwner }: EditableTitl
|
|||||||
<input
|
<input
|
||||||
ref={inputRef}
|
ref={inputRef}
|
||||||
type="text"
|
type="text"
|
||||||
value={title}
|
value={editingTitle}
|
||||||
onChange={(e) => setTitle(e.target.value)}
|
onChange={(e) => setEditingTitle(e.target.value)}
|
||||||
onBlur={handleSave}
|
onBlur={handleSave}
|
||||||
onKeyDown={handleKeyDown}
|
onKeyDown={handleKeyDown}
|
||||||
disabled={isPending}
|
disabled={isPending}
|
||||||
@@ -85,7 +86,10 @@ export function EditableTitle({ sessionId, initialTitle, isOwner }: EditableTitl
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<button
|
<button
|
||||||
onClick={() => setIsEditing(true)}
|
onClick={() => {
|
||||||
|
setEditingTitle(initialTitle);
|
||||||
|
setIsEditing(true);
|
||||||
|
}}
|
||||||
className="group flex items-center gap-2 text-left"
|
className="group flex items-center gap-2 text-left"
|
||||||
title="Cliquez pour modifier"
|
title="Cliquez pour modifier"
|
||||||
>
|
>
|
||||||
@@ -106,3 +110,4 @@ export function EditableTitle({ sessionId, initialTitle, isOwner }: EditableTitl
|
|||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
29
src/components/ui/EditableYearReviewTitle.tsx
Normal file
29
src/components/ui/EditableYearReviewTitle.tsx
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { EditableTitle } from './EditableTitle';
|
||||||
|
import { updateYearReviewSession } from '@/actions/year-review';
|
||||||
|
|
||||||
|
interface EditableYearReviewTitleProps {
|
||||||
|
sessionId: string;
|
||||||
|
initialTitle: string;
|
||||||
|
isOwner: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditableYearReviewTitle({
|
||||||
|
sessionId,
|
||||||
|
initialTitle,
|
||||||
|
isOwner,
|
||||||
|
}: EditableYearReviewTitleProps) {
|
||||||
|
return (
|
||||||
|
<EditableTitle
|
||||||
|
sessionId={sessionId}
|
||||||
|
initialTitle={initialTitle}
|
||||||
|
isOwner={isOwner}
|
||||||
|
onUpdate={async (id, title) => {
|
||||||
|
const result = await updateYearReviewSession(id, { title });
|
||||||
|
return result;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -3,6 +3,10 @@ export { Badge } from './Badge';
|
|||||||
export { Button } from './Button';
|
export { Button } from './Button';
|
||||||
export { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from './Card';
|
export { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from './Card';
|
||||||
export { CollaboratorDisplay } from './CollaboratorDisplay';
|
export { CollaboratorDisplay } from './CollaboratorDisplay';
|
||||||
|
export { EditableTitle } from './EditableTitle';
|
||||||
|
export { EditableSessionTitle } from './EditableSessionTitle';
|
||||||
|
export { EditableMotivatorTitle } from './EditableMotivatorTitle';
|
||||||
|
export { EditableYearReviewTitle } from './EditableYearReviewTitle';
|
||||||
export { Input } from './Input';
|
export { Input } from './Input';
|
||||||
export { Modal, ModalFooter } from './Modal';
|
export { Modal, ModalFooter } from './Modal';
|
||||||
export { Textarea } from './Textarea';
|
export { Textarea } from './Textarea';
|
||||||
|
|||||||
@@ -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 {
|
|
||||||
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 };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type { LiveEvent };
|
||||||
|
|||||||
@@ -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