File size: 4,004 Bytes
3366d00
a47b44b
98f5a11
a47b44b
4f737fe
 
 
98f5a11
53cfa3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98f5a11
4f737fe
 
 
 
 
 
 
53cfa3e
4f737fe
 
 
 
 
 
 
 
 
98f5a11
4f737fe
 
5b6d515
 
 
 
 
53cfa3e
5b6d515
 
4f737fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a47b44b
 
 
 
 
 
 
 
 
 
 
 
 
 
4f737fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1116fd
 
4f737fe
 
 
 
 
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
let myRoomId = prompt("Room ID:")

createRoom()

const DELAYTIME = 500
let DATA;

function createRoom(roomId=myRoomId, url="https://jacobinathanialpeterson-chatbox2.hf.space/createRoom") {
    const controller = new AbortController();
	const abortSignal = controller.signal;
	fetch(url, { 
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({roomIdInput: roomId}),
			signal: abortSignal
		})
		.then(response => { if (!response.ok) { throw new Error('Network response was not ok.') } return response.json() })
		.then(data => {
			controller.abort(); 
		})
		.catch(error => { if (error.name === 'AbortError') { console.log('Fetch aborted:', error.message) } else { console.error('Error fetching data:', error.message) }});

}

function postMessage(roomId=myRoomId, url="https://jacobinathanialpeterson-chatbox2.hf.space/postMessage") {
	const controller = new AbortController();
	const abortSignal = controller.signal;
	fetch(url, { 
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({nameInput: document.getElementById("nameInputBox").value, messageInput: document.getElementById("messageInputBox").value, roomIdInput: roomId}),
			signal: abortSignal
		})
		.then(response => { if (!response.ok) { throw new Error('Network response was not ok.') } return response.json() })
		.then(data => {
			controller.abort(); 
		})
		.catch(error => { if (error.name === 'AbortError') { console.log('Fetch aborted:', error.message) } else { console.error('Error fetching data:', error.message) }});
}

function getMessages(roomId=myRoomId, url="https://jacobinathanialpeterson-chatbox2.hf.space/messages") {
	const controller = new AbortController();
	const abortSignal = controller.signal;
	fetch(url, { 
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({roomIdInput: roomId}),
			signal: abortSignal
		})
		.then(response => { if (!response.ok) { throw new Error('Network response was not ok.') } return response.json() })
		.then(data => {
			// Get the keys of the object
			const keys = Object.keys(data);

			// Sort the keys based on their natural order
			keys.sort((a, b) => {
			  // Extract numeric part of keys
			  const numA = parseInt(a.match(/\d+/)[0]);
			  const numB = parseInt(b.match(/\d+/)[0]);
			  return numA - numB;
			});

			// Create a new object with sorted keys
			DATA = {};
			keys.forEach(key => {
			  DATA[key] = data[key];
			});

			controller.abort(); 
		})
		.catch(error => { if (error.name === 'AbortError') { console.log('Fetch aborted:', error.message) } else { console.error('Error fetching data:', error.message) }});
}















let atBottom = true;

function updateUI() {
  const messagesContainer = document.getElementById("messages");
  const isAtBottom = messagesContainer.scrollHeight - messagesContainer.scrollTop === messagesContainer.clientHeight;

  let elementValue = '';
  if (DATA) {
    Object.entries(DATA).forEach(([key, value]) => {
      elementValue +=
        `<div class="msg" id="${key}">
          <div class="nme">${value.name}: </div>
          <div class="body">${value.message}</div>
        </div>`;
    });
  }
  messagesContainer.innerHTML = elementValue;

  if (atBottom || isAtBottom) {
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }
  atBottom = isAtBottom;
}

setInterval(getMessages, 100);
setTimeout(() => {
  setInterval(updateUI, 100);
}, DELAYTIME);

document.getElementById("messages").addEventListener("scroll", () => {
  const messagesContainer = document.getElementById("messages");
  const isAtBottom = messagesContainer.scrollHeight - messagesContainer.scrollTop === messagesContainer.clientHeight;
  atBottom = isAtBottom;
});

function handleKeyPress(event) {
  if (event.keyCode === 13) {
    event.preventDefault();
    postMessage();
  }
}

document.getElementById("messageInputBox").addEventListener("keypress", handleKeyPress);