Add markdown support to the webclient
This commit is contained in:
parent
88e58bb79c
commit
4b7fe624bb
2 changed files with 16 additions and 2 deletions
|
|
@ -8,6 +8,7 @@ from flask import Flask, request, jsonify
|
|||
from flask_socketio import SocketIO, emit, join_room, leave_room
|
||||
from flask_cors import CORS
|
||||
from datetime import datetime # Import for timestamps
|
||||
import markdown # Import the markdown library
|
||||
|
||||
# Flask app for REST API and WebSocket
|
||||
app = Flask(__name__)
|
||||
|
|
@ -78,6 +79,9 @@ def handle_message(username, chat_room, message):
|
|||
# Add a timestamp to the message
|
||||
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
# Convert the message to HTML using Markdown
|
||||
html_message = markdown.markdown(message)
|
||||
|
||||
# Store the message in the chat room's history
|
||||
if chat_room not in message_history:
|
||||
message_history[chat_room] = []
|
||||
|
|
@ -86,7 +90,7 @@ def handle_message(username, chat_room, message):
|
|||
# Broadcast the message to WebSocket clients in the chat room
|
||||
socketio.emit('message', {
|
||||
'username': username,
|
||||
'message': message,
|
||||
'message': html_message, # Send the HTML-rendered message
|
||||
'timestamp': timestamp,
|
||||
'chat_room': chat_room
|
||||
}, room=chat_room)
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@
|
|||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Web Chat Client</title>
|
||||
<script src="https://cdn.socket.io/4.5.0/socket.io.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
|
||||
<style>
|
||||
/* Light Mode Styles */
|
||||
body.light-mode {
|
||||
|
|
@ -199,7 +201,15 @@
|
|||
const messageElement = document.createElement('div');
|
||||
const timestamp = data.timestamp ? `[${data.timestamp}]` : '';
|
||||
const chatRoomInfo = data.chat_room ? `(${data.chat_room})` : '';
|
||||
messageElement.textContent = `${timestamp} ${data.username || 'Server'} ${chatRoomInfo}: ${data.message}`;
|
||||
|
||||
// Render the message as HTML using marked.js
|
||||
const renderedMessage = marked.parse(data.message);
|
||||
|
||||
// Sanitize the HTML using DOMPurify
|
||||
const sanitizedMessage = DOMPurify.sanitize(renderedMessage);
|
||||
|
||||
// Set the inner HTML of the message element
|
||||
messageElement.innerHTML = `${timestamp} ${data.username || 'Server'} ${chatRoomInfo}: ${sanitizedMessage}`;
|
||||
chatDiv.appendChild(messageElement);
|
||||
chatDiv.scrollTop = chatDiv.scrollHeight; // Auto-scroll to the bottom
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue