Browse Source

Chat Homework done

Vladimir 3 years ago
parent
commit
c0d2730872
5 changed files with 265 additions and 0 deletions
  1. BIN
      HW 13/chat-background.jpg
  2. 32 0
      HW 13/index.html
  3. 87 0
      HW 13/main.js
  4. 16 0
      HW 13/send.svg
  5. 130 0
      HW 13/style.css

BIN
HW 13/chat-background.jpg


+ 32 - 0
HW 13/index.html

@@ -0,0 +1,32 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+    <link rel="stylesheet" href="style.css">
+</head>
+<body>
+    <div class="chat__wrapper">
+        <div class="chat__messages-box">
+            
+        </div>
+        <div class="chat__inputs-wrapp">
+            <input class="chat__input chat__input--nick" type="text" name="user-nick" maxlength="10" placeholder="Ваш nickname">
+            <input class="chat__input chat__input--message" type="text" name="user-message" maxlength="350" placeholder="Ваше сообщение">
+            <button class="chat__send-button"><span class="visually-hidden">Отправить</span></button>
+        </div>
+    </div>
+    <template id="chat__message-template">
+        <div class="chat__message-wrap">
+            <div class="chat__message-head">
+                <span class="chat__user-nick">User nick</span>
+                <span class="chat__timespan">20:53</span>
+            </div>
+            <p class="chat__user-message">User message</p>
+        </div>
+    </template>
+    <script src="main.js"></script>
+</body>
+</html>

+ 87 - 0
HW 13/main.js

@@ -0,0 +1,87 @@
+let chatMessageTemplate = document.querySelector("#chat__message-template").content.querySelector(".chat__message-wrap");
+let chatMessageBox      = document.querySelector(".chat__messages-box");
+let chatInputNick       = document.querySelector(".chat__input--nick");
+let chatInputMessage    = document.querySelector(".chat__input--message");
+let chatSendButton      = document.querySelector(".chat__send-button");
+
+let messageId = 0;
+
+async function jsonPost(url, data) {
+    const res = await fetch(url, {
+        method: "POST",
+        body: JSON.stringify(data)
+    });
+
+    return await res.json();
+};
+
+let delay = function(ms) {
+    return new Promise((resolve, reject) => {
+        setTimeout(() => resolve(ms), ms);
+    });
+};
+
+let drawAllMessage = async function() {  // Отрисовка всех сообщений, функция вызывается один раз и после не используется
+    let data = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: 0});
+
+    messageId = data["nextMessageId"]; // Получаю id последнего сообщения
+
+    for(let item of data["data"]) { // Рисую все сообщения
+        let chatMessage = chatMessageTemplate.cloneNode(true);
+        let timespan = new Date(item["timestamp"]);
+
+        chatMessage.querySelector(".chat__user-nick").textContent    = item["nick"];
+        chatMessage.querySelector(".chat__user-message").textContent = item["message"];
+        chatMessage.querySelector(".chat__timespan").textContent     = `${timespan.getHours()}:${timespan.getMinutes()}`;
+
+        chatMessageBox.appendChild(chatMessage);
+        chatMessageBox.scrollTo(0, chatMessageBox.scrollHeight);
+    }
+}
+
+drawAllMessage(); 
+
+async function sendMessage(nick, message) {
+    let nextMessageId = await jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: nick, message: message});
+
+    messageId = nextMessageId["nextMessageId"]; // После отправки сообщения переприсваиваю новый id
+    chatInputMessage.value = "";                // Удаляю все что написал пользователь из поля сообщения после нажатия "Отправить"
+}
+
+async function getMessages(data) { // Отрисовка одного последнего сообщения
+    let chatMessage = chatMessageTemplate.cloneNode(true); // Копирую уже заверстаный в HTML шаблон сообщения в переменную chatMessage
+    let timespan = new Date(data["data"][0]["timestamp"]);
+
+    chatMessage.querySelector(".chat__user-nick").textContent    = data["data"][0]["nick"];
+    chatMessage.querySelector(".chat__user-message").textContent = data["data"][0]["message"];
+    chatMessage.querySelector(".chat__timespan").textContent     = `${timespan.getHours()}:${timespan.getMinutes()}`;
+
+    chatMessageBox.appendChild(chatMessage);
+    chatMessageBox.scrollTo(0, chatMessageBox.scrollHeight); // Скрол в самый низ
+}
+
+async function sendAndCheck() {
+    await sendMessage(chatInputNick.value, chatInputMessage.value);
+
+    let data = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: messageId - 1});
+
+    await getMessages(data);
+}
+
+async function checkLoop() {
+    while(true) {
+        await delay(3000);
+
+        let data = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: messageId});
+
+        if(messageId != data["nextMessageId"]) { // Если id не совпадают то было написано новое сообщение
+            messageId = data["nextMessageId"];
+
+            getMessages(data);
+        }
+    }
+}
+
+checkLoop();
+
+chatSendButton.addEventListener("click", sendAndCheck);

+ 16 - 0
HW 13/send.svg

@@ -0,0 +1,16 @@
+<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+	 viewBox="0 0 512.662 512.662" style="enable-background:new 0 0 512.662 512.662;" xml:space="preserve" fill="#ffffff">
+<g>
+	<g>
+		<path d="M505.021,5.868c-0.064-0.043-0.085-0.107-0.128-0.149c-0.128-0.107-0.256-0.128-0.384-0.235
+			c-1.131-0.981-2.475-1.621-3.797-2.325c-0.427-0.213-0.747-0.576-1.195-0.768c-0.064-0.021-0.107-0.021-0.149-0.043
+			c-0.469-0.192-0.853-0.533-1.323-0.704c-1.771-0.661-3.648-0.875-5.547-1.045c-0.576-0.043-1.131-0.299-1.707-0.299
+			c-2.475-0.021-4.971,0.384-7.403,1.259L14.055,172.225c-7.445,2.709-12.779,9.323-13.867,17.173
+			c-1.045,7.851,2.304,15.637,8.768,20.245l141.888,101.355l20.032,140.309c1.237,8.533,7.488,15.488,15.851,17.643
+			c1.749,0.448,3.541,0.661,5.291,0.661c6.592,0,12.971-3.072,17.045-8.533l50.347-67.093l132.032,113.237
+			c3.947,3.371,8.875,5.141,13.909,5.141c2.389,0,4.779-0.405,7.125-1.216c7.168-2.56,12.48-8.768,13.845-16.277l85.995-468.928
+			C513.725,18.262,510.738,10.71,505.021,5.868z M240.125,348.396l-1.536,2.219l-32.747,43.669l-12.395-86.827l185.109-160.448
+			L240.125,348.396z"/>
+	</g>
+</g>
+</svg>

+ 130 - 0
HW 13/style.css

@@ -0,0 +1,130 @@
+.visually-hidden:not(:focus):not(:active),
+input[type=checkbox].visually-hidden,
+input[type=radio].visually-hidden{
+    position: absolute;
+    width: 1px;
+    height: 1px;
+    margin: -1px;
+    border: 0;
+    padding: 0;
+    white-space: nowrap;
+    -webkit-clip-path: inset(100%);
+    clip-path: inset(100%);
+    clip: rect(0 0 0 0);
+    overflow: hidden;
+}
+
+body {
+    font-family: sans-serif;
+    margin: 0;
+    height: 100vh;
+}
+
+.chat__wrapper {
+    box-sizing: border-box;
+    height: 100%;
+    background-color: #696969;
+    padding: 30px 100px;
+}
+
+.chat__messages-box {
+    display: flex;
+    flex-direction: column;
+    height: 90%;
+    overflow-y: scroll;
+    background-color: #575757;
+    background-image: url("chat-background.jpg");
+    background-position: center;
+    background-size: cover;
+    border-radius: 14px;
+    padding: 10px;
+}
+
+.chat__message-wrap {
+    align-self: flex-start;
+    background: linear-gradient(to bottom right, #483D8B, #9400D3);
+    border-radius: 14px;
+    padding: 10px;
+}
+
+.chat__message-wrap + .chat__message-wrap {
+    margin-top: 10px;
+}
+
+.chat__message-head {
+    display: flex;
+    flex-wrap: nowrap;
+    justify-content: space-between;
+    align-items: center;
+}
+
+.chat__user-nick {
+    font-size: 14px;
+    font-weight: 600;
+}
+
+.chat__timespan {
+    color: #a39a8a;
+    font-size: 10px;
+    font-weight: 600;
+}
+
+.chat__user-message {
+    color: #ffffff;
+    font-size: 18px;
+    margin: 0;
+}
+
+.chat__inputs-wrapp {
+    display: flex;
+    flex-wrap: nowrap;
+    background-color: #575757;
+    padding: 10px 15px;
+    border-radius: 12px;
+}
+
+.chat__input {
+    color: white;
+    font-size: 16px;
+    outline: none;
+    border: none;
+    background-color: #575757;
+}
+
+.chat__input::placeholder {
+    color: white;
+}
+
+.chat__input--nick {
+    width: 140px;
+}
+
+.chat__input--message {
+    flex-grow: 1;
+}
+
+.chat__send-button {
+    position: relative;
+    cursor: pointer;
+    width: 40px;
+    height: 40px;
+    background: linear-gradient(to bottom right, #483D8B, #9400D3);
+    border: none;
+    border-radius: 50%;
+    margin: 0;
+    padding: 0;
+}
+
+.chat__send-button::before {
+    content: "";
+    position: absolute;
+    top: 50%;
+    left: 50%;
+    transform: translate(-50%, -50%);
+    display: block;
+    width: 20px;
+    height: 20px;
+    background-image: url("send.svg");
+    background-position: center;
+    background-repeat: no-repeat;
+}