feat: add share dialog and typing indicator in messages
- Implemented `ShareDialog` component for sharing content directly with other users. - Added typing indicator when a user is composing a message in an active conversation. - Updated `SocketProvider` to handle improved connection management and user status updates. - Enhanced the messages UI with real-time online status and typing indicators for better feedback.
This commit is contained in:
@@ -32,8 +32,29 @@ export default function MessagesPage() {
|
||||
const [activeConv, setActiveConv] = React.useState<Conversation | null>(null);
|
||||
const [messages, setMessages] = React.useState<Message[]>([]);
|
||||
const [newMessage, setNewMessage] = React.useState("");
|
||||
const typingTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
const handleTyping = () => {
|
||||
if (!socket || !activeConv) return;
|
||||
|
||||
socket.emit("typing", {
|
||||
recipientId: activeConv.recipient.uuid,
|
||||
isTyping: true,
|
||||
});
|
||||
|
||||
if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
|
||||
|
||||
typingTimeoutRef.current = setTimeout(() => {
|
||||
socket.emit("typing", {
|
||||
recipientId: activeConv.recipient.uuid,
|
||||
isTyping: false,
|
||||
});
|
||||
}, 3000);
|
||||
};
|
||||
const [isLoadingConvs, setIsLoadingConvs] = React.useState(true);
|
||||
const [isLoadingMsgs, setIsLoadingMsgs] = React.useState(false);
|
||||
const [isOtherTyping, setIsOtherTyping] = React.useState(false);
|
||||
const [onlineUsers, setOnlineUsers] = React.useState<Set<string>>(new Set());
|
||||
|
||||
const [searchQuery, setSearchQuery] = React.useState("");
|
||||
const [searchResults, setSearchResults] = React.useState<User[]>([]);
|
||||
@@ -120,6 +141,7 @@ export default function MessagesPage() {
|
||||
(data: { conversationId: string; message: Message }) => {
|
||||
if (activeConv?.id === data.conversationId) {
|
||||
setMessages((prev) => [...prev, data.message]);
|
||||
setIsOtherTyping(false); // S'il a envoyé un message, il ne tape plus
|
||||
}
|
||||
// Mettre à jour la liste des conversations
|
||||
setConversations((prev) => {
|
||||
@@ -144,8 +166,28 @@ export default function MessagesPage() {
|
||||
},
|
||||
);
|
||||
|
||||
socket.on("user_status", (data: { userId: string; status: string }) => {
|
||||
setOnlineUsers((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (data.status === "online") {
|
||||
next.add(data.userId);
|
||||
} else {
|
||||
next.delete(data.userId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
});
|
||||
|
||||
socket.on("user_typing", (data: { userId: string; isTyping: boolean }) => {
|
||||
if (activeConv?.recipient.uuid === data.userId) {
|
||||
setIsOtherTyping(data.isTyping);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.off("new_message");
|
||||
socket.off("user_status");
|
||||
socket.off("user_typing");
|
||||
};
|
||||
}
|
||||
}, [socket, activeConv]);
|
||||
@@ -355,7 +397,17 @@ export default function MessagesPage() {
|
||||
<h3 className="font-bold leading-none">
|
||||
{activeConv.recipient.displayName || activeConv.recipient.username}
|
||||
</h3>
|
||||
<span className="text-xs text-green-500 font-medium">En ligne</span>
|
||||
<span
|
||||
className={`text-xs font-medium ${
|
||||
onlineUsers.has(activeConv.recipient.uuid)
|
||||
? "text-green-500"
|
||||
: "text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
{onlineUsers.has(activeConv.recipient.uuid)
|
||||
? "En ligne"
|
||||
: "Hors ligne"}
|
||||
</span>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
@@ -406,6 +458,17 @@ export default function MessagesPage() {
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
{isOtherTyping && (
|
||||
<div className="flex justify-start">
|
||||
<div className="bg-zinc-100 dark:bg-zinc-800 p-3 rounded-2xl rounded-bl-none">
|
||||
<div className="flex gap-1">
|
||||
<span className="w-1.5 h-1.5 bg-zinc-400 rounded-full animate-bounce [animation-delay:-0.3s]" />
|
||||
<span className="w-1.5 h-1.5 bg-zinc-400 rounded-full animate-bounce [animation-delay:-0.15s]" />
|
||||
<span className="w-1.5 h-1.5 bg-zinc-400 rounded-full animate-bounce" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
@@ -415,7 +478,10 @@ export default function MessagesPage() {
|
||||
<Input
|
||||
placeholder="Écrivez un message..."
|
||||
value={newMessage}
|
||||
onChange={(e) => setNewMessage(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setNewMessage(e.target.value);
|
||||
handleTyping();
|
||||
}}
|
||||
className="rounded-full px-4"
|
||||
/>
|
||||
<Button
|
||||
|
||||
@@ -35,6 +35,7 @@ import { useAuth } from "@/providers/auth-provider";
|
||||
import { ContentService } from "@/services/content.service";
|
||||
import { FavoriteService } from "@/services/favorite.service";
|
||||
import type { Content } from "@/types/content";
|
||||
import { ShareDialog } from "./share-dialog";
|
||||
import { UserContentEditDialog } from "./user-content-edit-dialog";
|
||||
import { ViewCounter } from "./view-counter";
|
||||
|
||||
@@ -51,6 +52,7 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
||||
const [isLiked, setIsLiked] = React.useState(content.isLiked || false);
|
||||
const [likesCount, setLikesCount] = React.useState(content.favoritesCount);
|
||||
const [editDialogOpen, setEditDialogOpen] = React.useState(false);
|
||||
const [shareDialogOpen, setShareDialogOpen] = React.useState(false);
|
||||
const [_reportDialogOpen, setReportDialogOpen] = React.useState(false);
|
||||
|
||||
const isAuthor = user?.uuid === content.authorId;
|
||||
@@ -190,7 +192,15 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuItem onClick={() => toast.success("Lien copié !")}>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
if (!isAuthenticated) {
|
||||
toast.error("Connectez-vous pour partager");
|
||||
return;
|
||||
}
|
||||
setShareDialogOpen(true);
|
||||
}}
|
||||
>
|
||||
<Share2 className="h-4 w-4 mr-2" />
|
||||
Partager
|
||||
</DropdownMenuItem>
|
||||
@@ -263,10 +273,11 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(
|
||||
`${window.location.origin}/meme/${content.slug}`,
|
||||
);
|
||||
toast.success("Lien copié !");
|
||||
if (!isAuthenticated) {
|
||||
toast.error("Connectez-vous pour partager");
|
||||
return;
|
||||
}
|
||||
setShareDialogOpen(true);
|
||||
}}
|
||||
className="hover:text-muted-foreground"
|
||||
>
|
||||
@@ -322,6 +333,13 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
||||
onOpenChange={setEditDialogOpen}
|
||||
onSuccess={() => onUpdate?.()}
|
||||
/>
|
||||
<ShareDialog
|
||||
contentId={content.id}
|
||||
contentTitle={content.title}
|
||||
contentUrl={`${typeof window !== "undefined" ? window.location.origin : ""}/meme/${content.slug}`}
|
||||
open={shareDialogOpen}
|
||||
onOpenChange={setShareDialogOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
185
frontend/src/components/share-dialog.tsx
Normal file
185
frontend/src/components/share-dialog.tsx
Normal file
@@ -0,0 +1,185 @@
|
||||
"use client";
|
||||
|
||||
import { Search, Send, X } from "lucide-react";
|
||||
import * as React from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { MessageService } from "@/services/message.service";
|
||||
import { UserService } from "@/services/user.service";
|
||||
import type { User } from "@/types/user";
|
||||
|
||||
interface ShareDialogProps {
|
||||
contentId: string;
|
||||
contentTitle: string;
|
||||
contentUrl: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function ShareDialog({
|
||||
contentId,
|
||||
contentTitle,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: Omit<ShareDialogProps, "contentUrl">) {
|
||||
const [searchQuery, setSearchQuery] = React.useState("");
|
||||
const [results, setResults] = React.useState<User[]>([]);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
const [sendingTo, setSendingTo] = React.useState<string | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) {
|
||||
setSearchQuery("");
|
||||
setResults([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const fetchInitial = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// Par défaut, montrer les conversations récentes ou suggérer des gens
|
||||
const recent = await UserService.search("");
|
||||
setResults(recent);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch users", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchInitial();
|
||||
}, [open]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (searchQuery.length < 2) return;
|
||||
|
||||
const timeout = setTimeout(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const data = await UserService.search(searchQuery);
|
||||
setResults(data);
|
||||
} catch (error) {
|
||||
console.error("Search failed", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, 300);
|
||||
|
||||
return () => clearTimeout(timeout);
|
||||
}, [searchQuery]);
|
||||
|
||||
const handleShare = async (user: User) => {
|
||||
setSendingTo(user.uuid);
|
||||
try {
|
||||
const shareUrl = `${window.location.origin}/meme/${contentId}`;
|
||||
await MessageService.sendMessage(
|
||||
user.uuid,
|
||||
`Regarde ce mème : ${contentTitle}\n${shareUrl}`,
|
||||
);
|
||||
toast.success(`Partagé avec @${user.username}`);
|
||||
onOpenChange(false);
|
||||
} catch (_error) {
|
||||
toast.error("Échec du partage");
|
||||
} finally {
|
||||
setSendingTo(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[425px] p-0 gap-0 overflow-hidden">
|
||||
<DialogHeader className="p-4 border-b">
|
||||
<DialogTitle>Partager avec</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="p-4 border-b">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Rechercher un membre..."
|
||||
className="pl-9 h-9"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
{searchQuery && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSearchQuery("")}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 p-0.5 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-full"
|
||||
>
|
||||
<X className="h-3 w-3 text-muted-foreground" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ScrollArea className="h-[300px]">
|
||||
<div className="p-2 space-y-1">
|
||||
{isLoading && results.length === 0 ? (
|
||||
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||
Chargement...
|
||||
</div>
|
||||
) : results.length === 0 ? (
|
||||
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||
Aucun membre trouvé.
|
||||
</div>
|
||||
) : (
|
||||
results.map((user) => (
|
||||
<div
|
||||
key={user.uuid}
|
||||
className="flex items-center justify-between p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-900"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Avatar className="h-9 w-9">
|
||||
<AvatarImage src={user.avatarUrl} />
|
||||
<AvatarFallback>{user.username[0].toUpperCase()}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm font-bold leading-none">
|
||||
{user.displayName || user.username}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
@{user.username}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={sendingTo === user.uuid ? "outline" : "default"}
|
||||
disabled={sendingTo !== null}
|
||||
onClick={() => handleShare(user)}
|
||||
className="h-8 px-4 rounded-full"
|
||||
>
|
||||
{sendingTo === user.uuid ? "Envoi..." : "Envoyer"}
|
||||
</Button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<div className="p-4 border-t bg-zinc-50 dark:bg-zinc-900/50">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full justify-start gap-2 h-10 rounded-xl"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(
|
||||
`${window.location.origin}/meme/${contentId}`,
|
||||
);
|
||||
toast.success("Lien copié !");
|
||||
onOpenChange(false);
|
||||
}}
|
||||
>
|
||||
<Send className="h-4 w-4" />
|
||||
Copier le lien
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -24,15 +24,25 @@ export function SocketProvider({ children }: { children: React.ReactNode }) {
|
||||
React.useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000";
|
||||
|
||||
// Initialisation du socket avec configuration optimisée pour la production
|
||||
const socketInstance = io(apiUrl, {
|
||||
withCredentials: true,
|
||||
transports: ["websocket"],
|
||||
transports: ["websocket"], // Recommandé pour éviter les problèmes de sticky sessions
|
||||
reconnectionAttempts: 5,
|
||||
reconnectionDelay: 1000,
|
||||
});
|
||||
|
||||
socketInstance.on("connect", () => {
|
||||
console.log("WebSocket connected to:", apiUrl);
|
||||
setIsConnected(true);
|
||||
});
|
||||
|
||||
socketInstance.on("connect_error", (error) => {
|
||||
console.error("WebSocket connection error:", error);
|
||||
// Si le websocket pur échoue, on peut tenter le polling en fallback (optionnel)
|
||||
});
|
||||
|
||||
socketInstance.on("disconnect", () => {
|
||||
setIsConnected(false);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user