aboutsummaryrefslogtreecommitdiff
path: root/src/Chat/Chat.tsx
blob: 1aa884a57f097636401c0a2c11a1f9f2b62933d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import React, {
        ReactElement,
        useContext,
        useEffect,
        useRef,
        useState,
} from "react";
import { MessageDisplay } from "../MessageDisplay/MessageDisplay";
import { Client } from "@stomp/stompjs";
import { Message, MessageType } from "../type/messageTypes";
import "./Chat.css";
import strings from "../Intl/strings.json";
import { LangContext } from "../context";
import { connectionAddress, endpoints } from "../consts";
const Chat = ({ user }: { user: string }): React.ReactElement => {
        const lang = useContext(LangContext);
        const chatPage = strings[lang].chat;
        const [messages, setMessages] = useState<ReactElement[]>([]);
        let stompClientRef = useRef(
                new Client({
                        brokerURL: connectionAddress,
                })
        );
        // TODO solve issue with non-static markup
        stompClientRef.current.onConnect = (frame) => {
                stompClientRef.current.subscribe(
                        endpoints.subscription,
                        (message) => {
                                console.log(
                                        `Collected new message: ${message.body}`
                                );
                                const messageBody = JSON.parse(
                                        message.body
                                ) as Message;
                                console.log(messageBody);
                                setMessages((message) => {
                                        return message.concat([
                                                <MessageDisplay
                                                        key={`${messageBody.type}@${messageBody.timeMillis}`}
                                                        {...messageBody}
                                                />,
                                        ]);
                                });
                        }
                );
                stompClientRef.current.publish({
                        body: JSON.stringify({
                                type: MessageType.HELLO,
                                fromUserId: user,
                                toUserId: "everyone",
                                content: `${user} has joined the server!`,
                                timeMillis: Date.now(),
                        }),
                        destination: endpoints.destination,
                });
        };
        // Generic error handlers
        stompClientRef.current.onWebSocketError = (error) => {
                console.error("Error with websocket", error);
        };

        stompClientRef.current.onStompError = (frame) => {
                console.error(
                        "Broker reported error: " + frame.headers["message"]
                );
                console.error("Additional details: " + frame.body);
        };

        // Button press event handler.
        const sendData = () => {
                const entryElement: HTMLInputElement = document.getElementById(
                        "data-entry"
                ) as HTMLInputElement;
                if (entryElement.value === "") {
                        return;
                }
                const messageData: Message = {
                        type: MessageType.MESSAGE,
                        fromUserId: user,
                        toUserId: "everyone",
                        content: entryElement.value,
                        timeMillis: Date.now(),
                };
                console.log(
                        `STOMP connection status: ${stompClientRef.current.connected}`
                );
                stompClientRef.current.publish({
                        body: JSON.stringify(messageData),
                        destination: endpoints.destination,
                        headers: {
                                "Content-Type":
                                        "application/json; charset=utf-8",
                        },
                });
                entryElement.value = "";
        };
        useEffect(() => {
                // Stomp client is disconnected after each re-render
                // This should be actively avoided
                stompClientRef.current.activate();
                return () => {
                        stompClientRef.current.deactivate();
                };
        }, []);
        // https://www.w3schools.com/jsref/obj_keyboardevent.asp
        document.addEventListener("keydown", (ev: KeyboardEvent) => {
                if (ev.key === "Enter") {
                        sendData();
                }
        });
        useEffect(() => {
                try {
                        const elem = document.querySelector(
                                ".chat-inner-wrapper"
                        );
                        if (elem) {
                                elem.scrollTop = elem.scrollHeight;
                        } else {
                        }
                } catch (err) {
                        console.log("error encountered");
                }
                return () => {};
        }, [messages]);
        return (
                <fieldset className="chat">
                        <legend>
                                {chatPage.window.title.replaceAll(
                                        "$userName",
                                        user
                                )}
                        </legend>
                        <div className="chat-inner-wrapper">{messages}</div>
                        <span className="entry-box">
                                <input id="data-entry"></input>
                                <button onClick={() => sendData()}>
                                        {chatPage.sendButtonPrompt}
                                </button>
                        </span>
                </fieldset>
        );
};
export default Chat;