Add several explanatory comments on code

This commit is contained in:
Zhongheng Liu 2024-01-02 17:18:01 +02:00
commit 91da28f1fb
No known key found for this signature in database

View file

@ -3,6 +3,9 @@ import { Message } from "./Message";
import { Client, Stomp } from "@stomp/stompjs";
import { MessageType } from "./types";
import { renderToStaticMarkup } from 'react-dom/server';
// The last bit of magic sauce to make this work
// EXPLANATION
//
const domain = window.location.hostname
const port = "8080"
const connectionAddress = `ws://${domain}:${port}/ws`
@ -21,20 +24,24 @@ const ChatWrapper = (
})
const destination = "/app/chat"
const subscribe = "/sub/chat"
// const [children, setChildren] = useState<React.ReactElement[]>([])
// TODO solve issue with non-static markup
stompClient.onConnect = (frame) => {
stompClient.subscribe(subscribe, (message) => {
console.log(`Collected new message: ${message.body}`);
const {from, to, content} = JSON.parse(message.body) as MessageType
const messageElement = <Message sender={from} text={content} />
// setChildren((prev) => [...prev, messageElement])
console.log(messageElement);
// Temporary solution
// The solution lacks interactibility - because it's static markup
const container = document.getElementById("chat-inner") as HTMLDivElement
// Truly horrible and disgusting
container.innerHTML += renderToStaticMarkup(messageElement)
})
}
// Generic error handlers
stompClient.onWebSocketError = (error) => {
console.error('Error with websocket', error);
};
@ -44,9 +51,12 @@ const ChatWrapper = (
console.error('Additional details: ' + frame.body);
};
// Button press event handler.
const sendDataButtonHandler = (ev: React.MouseEvent) => {
console.log("WebSockets handler invoked.")
// There must be a react-native and non-document-getElementById way to do this
// TODO Explore
const entryElement: HTMLInputElement = document.getElementById("data-entry") as HTMLInputElement
const messageData =
{
@ -54,8 +64,7 @@ const ChatWrapper = (
to: "everyone",
content: entryElement.value
}
console.log(`STOMP connection status: ${stompClient.connected}`);
console.log(`STOMP connection status: ${stompClient.connected}`);
stompClient.publish({
body: JSON.stringify(messageData),
destination: destination
@ -63,6 +72,8 @@ const ChatWrapper = (
ev.preventDefault()
}
useEffect(() => {
// Stomp client is disconnected after each re-render
// This should be actively avoided
stompClient.activate()
return () => {
stompClient.deactivate()
@ -70,10 +81,7 @@ const ChatWrapper = (
}, [])
return (
<div className="chat">
{/* <button onClick={ev => {connect()}} disabled={connected}>Connect</button>
<button onClick={ev => {disconnect()}} disabled={!connected}>Disconnect</button> */}
<div id="chat-inner">
{/* {children} */}
</div>
<span><input id="data-entry"></input><button onClick={ev => sendDataButtonHandler(ev)}>Send</button></span>
</div>