Skip to content

Commit

Permalink
Leave a discussion
Browse files Browse the repository at this point in the history
  • Loading branch information
Saodus committed Dec 14, 2024
1 parent 09c3e79 commit c4ac413
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 124 deletions.
13 changes: 13 additions & 0 deletions app/Http/Controllers/ChatController.php
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,17 @@ public function storeChat(Request $request)
// Rediriger avec un message de succès
return redirect()->route('dashboard')->with('success', 'Discussion créée avec succès !');
}

public function leaveChat($chatId)
{
$chat = Chat::find($chatId);

if (!$chat) {
return response()->json(['error' => 'Chat not found.'], 404);
}

$chat->users()->detach(auth()->id());

return response()->json(['message' => 'You left the chat.']);
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 11 additions & 4 deletions resources/views/components/messaging/header.blade.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
<div class="flex background-app border-b border-black h-12 items-center justify-start p-4 gap-x-4">
<img src="" alt="Discussion Picture" class="w-10 h-10 rounded-full headerImage">
<span class="text-white font-semibold headerTitle"></span>
</div>
<div class="flex background-app border-b border-black h-12 items-center justify-between p-4 gap-x-4">
<div class="flex items-center gap-x-4">
<img src="" alt="Discussion Picture" class="w-10 h-10 rounded-full headerImage">
<span class="text-white font-semibold headerTitle"></span>
</div>
<button id="leave-chat-btn"
class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded"
onclick="leaveChat()">
Quitter
</button>
</div>
177 changes: 57 additions & 120 deletions resources/views/dashboard.blade.php
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
<x-app-layout>
<div class="h-full flex background-app">
<!-- Inclure le composant de la barre de discussions -->
<x-messaging.discussion-sidebar :discussions="$discussions" :friends="$friends" />

<!-- Zone de chat avec message par défaut -->
<div id="chat-placeholder" class="flex-1 flex items-center justify-center text-white bg-gray-800">
<x-messaging.home-section />
</div>

<!-- Section de chat (initialement cachée) -->
<div id="chat-area" class="flex-1 background-app flex flex-col h-full relative hidden">

<x-messaging.header />
<x-messaging.header/>
<x-messaging.messages />
<div id="error-message" style="display: none; color: red; margin-top: 10px;"></div>
<x-messaging.chatbar />
</div>
</div>
Expand All @@ -20,17 +21,15 @@
let currentChatId = null;
let interval = null;
let allMessages = [];
const currentUserId = {{ auth()->id() }};
// Fonction pour charger la discussion
function loadChat(chatId, discussionName, discussionPicture, newOpening = true) {
const messagesContainer = document.getElementById('messages');
const messagesContainer = document.getElementById('messages');
document.getElementById('chat-placeholder').style.display = 'none';
document.getElementById('chat-area').style.display = 'flex';
// Masquer le placeholder et afficher la zone de chat
document.getElementById('chat-placeholder').style.display = 'none';
document.getElementById('chat-area').style.display = 'flex';
if (currentChatId !== chatId) {
allMessages = [];
messagesContainer.innerHTML = '';
// Vérifier si la discussion est déjà chargée
if (currentChatId !== chatId) {
// Réinitialiser la liste de tout les messages
Expand All @@ -51,7 +50,7 @@ function loadChat(chatId, discussionName, discussionPicture, newOpening = true)
if (headerTitle) headerTitle.textContent = discussionName;
const headerImage = document.querySelector('.headerImage');
if(headerImage) headerImage.src = discussionPicture;
if (headerImage) headerImage.src = discussionPicture;
}
fetch(`/chat/${chatId}/messages`, {
Expand Down Expand Up @@ -109,7 +108,7 @@ function loadChat(chatId, discussionName, discussionPicture, newOpening = true)
<source src="{{ asset('source/media/') }}/${message.media_url}" type="audio/mpeg">
Your browser does not support the audio element.
</audio>`;
}else {
} else {
mediaElement += `
<img src="{{ asset('source/media/') }}/${message.media_url}" class="w-full rounded-lg">`;
}
Expand All @@ -119,7 +118,7 @@ function loadChat(chatId, discussionName, discussionPicture, newOpening = true)
${message.message}
</p>
</div>`;
messageElement.innerHTML = mediaElement;
messageElement.innerHTML = mediaElement;
}
messagesContainer.appendChild(messageElement);
});
Expand All @@ -145,91 +144,7 @@ function loadChat(chatId, discussionName, discussionPicture, newOpening = true)
.catch(error => console.error('Erreur:', error))
}
currentChatId = chatId;
if (newOpening) {
const headerTitle = document.querySelector('.headerTitle');
if (headerTitle) headerTitle.textContent = discussionName;
const headerImage = document.querySelector('.headerImage');
if (headerImage) headerImage.src = discussionPicture;
}
fetch(`/chat/${chatId}/messages`, {
method: 'GET',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
})
.then(response => response.json())
.then(data => {
let newMessages = [];
if (JSON.stringify(allMessages) === JSON.stringify(data.messages)) {
return;
} else if (allMessages.length === 0) {
newMessages = data.messages;
} else {
newMessages = data.messages.filter(message => !allMessages.some(m => m.id === message.id));
}
const isAtBottom = messagesContainer.scrollHeight - messagesContainer.scrollTop === messagesContainer.clientHeight;
newMessages.forEach(message => {
const isCurrentUser = message.user_id === currentUserId;
const messageElement = document.createElement('div');
messageElement.className = `flex ${isCurrentUser ? 'justify-end' : 'justify-start'} mb-2`;
let messageContent = `
<p class="max-w-[45%] ${isCurrentUser ? 'secondary-background-app rounded-tl-lg' : 'tertiary-background-app rounded-tr-lg'} text-white p-2 rounded-bl-lg rounded-br-lg">
<span class="text-xs text-white block mb-1 font-bold">${message.user.name}</span>
${message.message}
</p>
`;
if (message.media_url) {
if (message.media_url.endsWith('.mp4')) {
messageContent = `
<video controls preload="none" class="w-full" poster="{{ asset('source/assets/images/') }}/video.png">
<source src="{{ asset('source/media/') }}/${message.media_url}" type="video/mp4">
</video>`;
} else if (message.media_url.endsWith('.mp3')) {
messageContent = `
<audio preload="none" controls class="w-full">
<source src="{{ asset('source/media/') }}/${message.media_url}" type="audio/mpeg">
Your browser does not support the audio element.
</audio>`;
} else {
messageContent = `
<img src="{{ asset('source/media/') }}/${message.media_url}" class="w-full rounded-lg">
<p class="mt-3">${message.message}</p>`;
}
}
messageElement.innerHTML = messageContent;
messagesContainer.appendChild(messageElement);
});
allMessages = data.messages;
const mediaElements = document.querySelectorAll('img, video');
mediaElements.forEach(mediaElement => {
mediaElement.addEventListener('load', () => {
if (isAtBottom) {
scrollToBottom();
}
});
});
if (isAtBottom) {
scrollToBottom();
}
})
.catch(error => console.error('Erreur:', error));
}
// Fonction pour démarrer la mise à jour automatique des messages
function startAutoRefresh(intervalTime = 500) {
if (interval) clearInterval(interval);
interval = setInterval(() => {
Expand All @@ -253,35 +168,57 @@ function sendMessage() {
message: messageContent
})
})
.then(response => {
return response.json();
})
.then(data => {
const errorMessage = document.getElementById('error-message');
if (data.error) {
errorMessage.textContent = data.error;
errorMessage.style.display = 'block';
} else {
document.getElementById('message-content').value = '';
errorMessage.style.display = 'none';
}
.then(() => {
document.getElementById('message-content').value = '';
})
.catch(error => {
console.error('Erreur:', error);
const errorMessage = document.getElementById('error-message');
errorMessage.textContent = 'Une erreur est survenue. Veuillez réessayer.';
errorMessage.style.display = 'block';
});
.catch(error => console.error('Erreur:', error));
}
// Fonction pour faire défiler les messages jusqu'en bas
function scrollToBottom() {
const messagesContainer = document.getElementById('messages');
if (messagesContainer) {
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
}
startAutoRefresh();
</script>
function leaveChat() {
if (!currentChatId) {
alert("Aucune discussion sélectionnée.");
return;
}
fetch(`/chat/${currentChatId}/leave`, {
method: 'DELETE',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Impossible de quitter la conversation.");
}
})
.then(data => {
alert(data.message || "Vous avez quitté la conversation.");
currentChatId = null;
// Optionnel : mise à jour locale de l'interface
document.getElementById('chat-area').style.display = 'none';
document.getElementById('chat-placeholder').style.display = 'flex';
// Recharger la page pour mettre à jour la liste des discussions
location.reload();
})
.catch(error => {
console.error("Erreur :", error);
alert("Une erreur s'est produite en essayant de quitter la conversation.");
});
}
startAutoRefresh(); // Démarrer l'auto-rafraîchissement
</script>
1 change: 1 addition & 0 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
Route::get('/chat/{discussion}/messages', [ChatController::class, 'getMessages']);
Route::post('/chat/{discussion}/messages', [ChatController::class, 'storeMessage']);
Route::post('/chat/{discussion}/capsule', [ChatController::class, 'storeCapsule']);
Route::delete('/chat/{discussion}/leave', [ChatController::class, 'leaveChat']);
Route::post('/chats', [ChatController::class, 'storeChat'])->name('chats.store');
Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
Expand Down

0 comments on commit c4ac413

Please sign in to comment.