Browse Source

chat add some fixes

serg155alternate 2 years ago
parent
commit
c1a87f3751
3 changed files with 87 additions and 40 deletions
  1. 1 1
      HW14 await paradise/index.html
  2. 84 38
      HW14 await paradise/script.js
  3. 2 1
      HW14 await paradise/style.css

+ 1 - 1
HW14 await paradise/index.html

@@ -14,7 +14,7 @@
             <input type="text" id='nickname'>
             <input type="text" id='nickname'>
             <label for="nickname">Enter NickName</label>
             <label for="nickname">Enter NickName</label>
             <div>
             <div>
-                <input type="text" id='message'>
+                <textarea type="text" id='message'> </textarea>
                 <label for="nickname">Enter your message</label>
                 <label for="nickname">Enter your message</label>
                 <button class='btn'>Send message</button>
                 <button class='btn'>Send message</button>
             </div>
             </div>

+ 84 - 38
HW14 await paradise/script.js

@@ -1,12 +1,8 @@
 //Chat Homework
 //Chat Homework
 
 
-/* Этапы.
-//Используя функцию jsonPost на адрес http://students.a-level.com.ua:10012 напишите чат-клиент, который:
-Stage 0
-Для поиграться скопируйте в консоль функцию jsonPost (или запустите её с этой страницы) и вызовите её с теми или иными объектами в качестве второго параметра. см. RPC. */
 function dataToDataTimeLocal(date) {
 function dataToDataTimeLocal(date) {
     let timeStamp = date.getTime();
     let timeStamp = date.getTime();
-    let timeZoneoffset = - date.getTimezoneOffset() * 60 * 1000;
+    let timeZoneoffset = -date.getTimezoneOffset() * 60 * 1000;
     let localTime = timeStamp + timeZoneoffset;
     let localTime = timeStamp + timeZoneoffset;
     return new Date(localTime).toISOString().slice(0, -1);
     return new Date(localTime).toISOString().slice(0, -1);
 }
 }
@@ -17,61 +13,90 @@ let nick = document.querySelector('#nickname');
 let btn = document.querySelector('.btn');
 let btn = document.querySelector('.btn');
 
 
 btn.addEventListener('click', () => {
 btn.addEventListener('click', () => {
-     nickName = nickname.value;
-     userMessage = message.value;
-     sendMessage(nickName , userMessage);
-     getMasseges();
-     message.value = '';
+    nickName = nickname.value;
+    userMessage = message.value;
+    sendMessage(nickName, userMessage);
+    getMasseges();
+    message.value = '';
 });
 });
 
 
+btn.disabled = 'true';
 
 
+message.addEventListener('input', () => {
+    if (nick.value && message.value) {
+        btn.disabled = '';
+    } else if (nick.value == '' || message.value == '') btn.disabled = 'true';
+})
 
 
-function jsonPost(url, data)
-{
+function jsonPost(url, data) {
     return new Promise((resolve, reject) => {
     return new Promise((resolve, reject) => {
-        var x = new XMLHttpRequest();   
+        var x = new XMLHttpRequest();
         x.onerror = () => reject(new Error('jsonPost failed'))
         x.onerror = () => reject(new Error('jsonPost failed'))
         //x.setRequestHeader('Content-Type', 'application/json');
         //x.setRequestHeader('Content-Type', 'application/json');
         x.open("POST", url, true);
         x.open("POST", url, true);
         x.send(JSON.stringify(data))
         x.send(JSON.stringify(data))
 
 
         x.onreadystatechange = () => {
         x.onreadystatechange = () => {
-            if (x.readyState == XMLHttpRequest.DONE && x.status == 200){
+            if (x.readyState == XMLHttpRequest.DONE && x.status == 200) {
                 resolve(JSON.parse(x.responseText))
                 resolve(JSON.parse(x.responseText))
-            }
-            else if (x.status != 200){
+            } else if (x.status != 200) {
                 reject(new Error('status is not 200'))
                 reject(new Error('status is not 200'))
             }
             }
         }
         }
     })
     })
 }
 }
-function getMasseges(messageId = 0){
-    jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: messageId})
+
+function getMasseges(messageId = 0) {
+    jsonPost("http://students.a-level.com.ua:10012", {
+            func: "getMessages",
+            messageId: messageId
+        })
         .then(res => {
         .then(res => {
-            res.data.forEach(el=> {
-            readMessage(el)});
+            res.data.forEach(el => {
+                readMessage(el)
+            });
             let prevId = res.nextMessageId;
             let prevId = res.nextMessageId;
             let currentId = messageId;
             let currentId = messageId;
             let messageInterval = setInterval((id) => {
             let messageInterval = setInterval((id) => {
-                if(currentId < prevId){
+                if (currentId < prevId) {
                     console.log('step')
                     console.log('step')
-                   jsonPost("http://students.a-level.com.ua:10012",{func: "getMessages", messageId: 0}).then(res => res.nextMessageId, res.data.forEach(el=> {
-                    readMessage(el)}))
-                   currentId = res.nextMessageId;
-                  
-                } else {console.log('not working', prevId, currentId)}
-            }  , 1000);
-            }) ;
+                    soundClick();
+                    jsonPost("http://students.a-level.com.ua:10012", {
+                        func: "getMessages",
+                        messageId: currentId + 1
+                    }).then(res => res.nextMessageId, res.data.forEach(el => {
+                        readMessage(el)
+                    }))
+                    currentId = res.nextMessageId;
+
+                }
+            }, 2000);
+        });
 }
 }
 
 
 getMasseges();
 getMasseges();
 
 
 
 
+function soundClick() {
+    const audio = new Audio();
+    audio.src = '7.mp3';
+    audio.play();
+}
+
+
 function sendMessage(nick, message) {
 function sendMessage(nick, message) {
-    jsonPost("http://students.a-level.com.ua:10012", {func: "addMessage", nick: nick, message: message})
-    .then(res => getMasseges(res.nextMessageId));
-        message.value = ''; 
-    
+
+    jsonPost("http://students.a-level.com.ua:10012", {
+            func: "addMessage",
+            nick: nick,
+            message: message
+        })
+        .then(res => getMasseges(res.nextMessageId));
+    message.value = '';
+
+
+
+
 }
 }
 
 
 let regYoutube = /http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?/; //regExp for YouTube video
 let regYoutube = /http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?/; //regExp for YouTube video
@@ -91,9 +116,9 @@ function readMessage(msg) {
     spanUserName.innerHTML += `${msg.nick  || 'NONAME'}`;
     spanUserName.innerHTML += `${msg.nick  || 'NONAME'}`;
     timeSpan.style.backgroundColor = '#afafc2';
     timeSpan.style.backgroundColor = '#afafc2';
     timeSpan.style.marginLeft = '10px';
     timeSpan.style.marginLeft = '10px';
-    timeSpan.innerText = dataToDataTimeLocal(new Date(msg.timestamp)).slice(0,19);
-    console.log(dataToDataTimeLocal(new Date(msg.timestamp)).slice(0,19));
-    
+    timeSpan.innerText = dataToDataTimeLocal(new Date(msg.timestamp)).slice(0, 19);
+    console.log(dataToDataTimeLocal(new Date(msg.timestamp)).slice(0, 19));
+
     //idMsg.innerText = nextMessageId;
     //idMsg.innerText = nextMessageId;
     /* if (msg.message.match(regYoutube)) {
     /* if (msg.message.match(regYoutube)) {
         console.log(`https://www.youtube.com/embed/${msg.message.match(regYoutube)[1]}`) // get youtube key
         console.log(`https://www.youtube.com/embed/${msg.message.match(regYoutube)[1]}`) // get youtube key
@@ -101,12 +126,33 @@ function readMessage(msg) {
     } else {
     } else {
         spanMessages.innerHTML += `  Write: ${msg.message}`;
         spanMessages.innerHTML += `  Write: ${msg.message}`;
     } */
     } */
-    spanMessages.innerHTML += msg.message || 'Send empty message';//*** */
+    spanMessages.innerHTML += msg.message || 'Send empty message'; //*** */
 
 
-    div.prepend(spanMessages,timeSpan);
+    div.prepend(spanMessages, timeSpan);
     div.prepend(spanUserName, idMsg);
     div.prepend(spanUserName, idMsg);
     answer.prepend(div)
     answer.prepend(div)
+}
+
+
 
 
+//Stage 6
+//Прогуглить и разобраться с fetch и заменить внутренности jsonPost на код, использующий fetch вместо XMLHttpRequest. 
 
 
-    
+
+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'))
+            }
+        }
+    })
 }
 }

+ 2 - 1
HW14 await paradise/style.css

@@ -40,8 +40,9 @@ input {
     width: 600px;
     width: 600px;
 }
 }
 #message {
 #message {
-    
+    height: 100px;
     background-color:rgb(252, 250, 248);
     background-color:rgb(252, 250, 248);
+    resize: none;
 }
 }
 .btn {
 .btn {
     height: 20px;
     height: 20px;