|
@@ -0,0 +1,95 @@
|
|
|
+//stage 0 - 4
|
|
|
+function jsonPost(url, data) {
|
|
|
+ return new Promise((resolve, reject) => {
|
|
|
+ var x = new XMLHttpRequest();
|
|
|
+ x.onerror = () => reject(new Error('jsonPost failed'))
|
|
|
+ // //x.setRequestHeader('Content-Type', 'application/json');
|
|
|
+ x.open("POST", url, true);
|
|
|
+ x.send(JSON.stringify(data))
|
|
|
+
|
|
|
+ x.onreadystatechange = () => {
|
|
|
+ if (x.readyState == XMLHttpRequest.DONE && x.status == 200) {
|
|
|
+ resolve(JSON.parse(x.responseText))
|
|
|
+ }
|
|
|
+ else if (x.status != 200) {
|
|
|
+ reject(new Error('status is not 200'))
|
|
|
+ }
|
|
|
+ }
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
+let timeConverter = timestamp => {
|
|
|
+ let date = new Date(timestamp);
|
|
|
+ let optionsDate = { year: "numeric", month: 'long', day: 'numeric' }
|
|
|
+ let optionsTime = { hour: '2-digit', minute: '2-digit' }
|
|
|
+ let convertedDate = date.toLocaleDateString("ua-UA", optionsDate) + " " + date.toLocaleTimeString("ua-UA", optionsTime)
|
|
|
+
|
|
|
+ return convertedDate;
|
|
|
+}
|
|
|
+
|
|
|
+let updateScroll = () => {
|
|
|
+ setTimeout(() => chatWindow.scrollTop = chatWindow.scrollHeight, 350)
|
|
|
+}
|
|
|
+
|
|
|
+btn.onclick = e => {
|
|
|
+ if (nick.value !== "" && msg.value !== "") {
|
|
|
+ jsonPost("http://students.a-level.com.ua:10012", { func: 'addMessage', nick: nick.value, message: msg.value })
|
|
|
+
|
|
|
+ msg.value = ""
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+let msgId = 0;
|
|
|
+
|
|
|
+let chatWindowShower = () => {
|
|
|
+ jsonPost("http://students.a-level.com.ua:10012", { func: "getMessages", messageId: msgId })
|
|
|
+ .then(json => {
|
|
|
+
|
|
|
+ if (json.nextMessageId !== msgId) {
|
|
|
+ updateScroll()
|
|
|
+ msgId = json.nextMessageId;
|
|
|
+ }
|
|
|
+
|
|
|
+ for (let key of json.data) {
|
|
|
+ let div = document.createElement("div");
|
|
|
+ let spanNick = document.createElement("span");
|
|
|
+ let spanMsg = document.createElement("span");
|
|
|
+ let spanDate = document.createElement("span");
|
|
|
+ spanNick.innerText = key.nick;
|
|
|
+ spanMsg.innerText = key.message;
|
|
|
+ spanDate.innerText = timeConverter(key.timestamp);
|
|
|
+
|
|
|
+ div.append(spanNick, spanMsg, spanDate)
|
|
|
+
|
|
|
+ chatWindow.append(div)
|
|
|
+ }
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
+setInterval(chatWindowShower, 2000)
|
|
|
+
|
|
|
+//stage 5
|
|
|
+async function sendMessage(nick, message) {
|
|
|
+
|
|
|
+}
|
|
|
+
|
|
|
+async function getMessages() {
|
|
|
+
|
|
|
+}
|
|
|
+
|
|
|
+async function sendAndCheck() {
|
|
|
+
|
|
|
+}
|
|
|
+
|
|
|
+async function checkLoop() {
|
|
|
+
|
|
|
+}
|
|
|
+
|
|
|
+//stage 6
|
|
|
+/*
|
|
|
+async function jsonPost(url, data) {
|
|
|
+ const response = await fetch(url, { method: 'POST', body: JSON.stringify(data) });
|
|
|
+ let result = await response.json()
|
|
|
+ return result;
|
|
|
+}
|
|
|
+*/
|