Browse Source

almost done

miskson 3 năm trước cách đây
mục cha
commit
9fabe1998c
3 tập tin đã thay đổi với 189 bổ sung0 xóa
  1. 32 0
      hw12-promiseChat/index.html
  2. 132 0
      hw12-promiseChat/script.js
  3. 25 0
      hw12-promiseChat/style.css

+ 32 - 0
hw12-promiseChat/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">
+    <link rel="stylesheet" href="./style.css">
+    <title>hw12-promiseChat</title>
+</head>
+<body>
+    <h1>promise chat client</h1>
+    <div id="msgField"></div>
+    <div id='formContainer'>
+        <input
+            id="nickbox" 
+            type="text"
+            placeholder="nickname"
+        >
+        <br>
+        <textarea 
+            name="messagebox"
+            id="msgbox"
+            cols="30"
+            rows="5"
+            placeholder="message"
+        ></textarea>
+        <br>
+        <button id="sendBtn">Send</button>
+    </div>
+    <script src="./script.js"></script>
+</body>
+</html>

+ 132 - 0
hw12-promiseChat/script.js

@@ -0,0 +1,132 @@
+async function jsonPost(url, data)
+{
+    console.log('here')
+    // 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'))
+    //         }
+    //     }
+    // })
+    const options = {
+        method: "POST",
+        headers: {
+            "Accept": "application/json",
+            "Content-Type": "application/json"
+        },
+        body: JSON.stringify(data)
+    }
+
+    try {
+        console.log('here2')
+        const response = await fetch(url, options)
+        console.log('here3')
+        const content = await response.json()
+        return content
+    } catch(e) {
+        console.error('error ocurred', e)
+    }
+}
+
+async function sendMessage(nick, message) {
+    await jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: nick, message: message})
+}
+
+async function drawHistory(messageId=0) {
+    let messages = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: messageId})
+    console.log(messages)
+    msgTotal = messages.nextMessageId
+    for(let message of messages.data) {
+        let msgDiv = document.createElement('div')
+        msgDiv.insertAdjacentHTML('beforeend', `
+            <small style="color: magenta;">${new Date(message.timestamp).toLocaleString()}</small>
+            <div>
+            <h4 style="color: yellow; display: inline; font-style: italic;">${message.nick} :</h4> ${message.message}
+            </div>
+        `)
+        msgDiv.style.width = 'fit-content'
+        msgDiv.style.borderBottom = '1px solid grey'
+        msgDiv.style.marginBottom = '25px'
+        msgScreen.prepend(msgDiv)
+    }
+    console.log(msgTotal)
+    let newStuff = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: msgTotal-1})
+    console.log('new stufff', newStuff)
+}
+drawHistory()
+
+async function checkNewMessages() {
+    let {nextMessageId} = await jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: msgTotal})
+    if(nextMessageId > msgTotal) {
+        console.log('new shit', msgTotal, nextMessageId)
+        msgTotal = nextMessageId
+        return true
+    }
+    console.log('no new shit', msgTotal, nextMessageId)
+    return false
+}
+
+async function sendAndCheck() {
+    sendMessage(nick, text)
+    let oldMsgCount = msgTotal
+    checkNewMessages()
+    drawHistory(msgTotal - (msgTotal-oldMsgCount))
+}
+
+async function checkLoop() {
+    while(true) {
+        await delay(5000)
+        let oldMsgCount = msgTotal
+        if(checkNewMessages()) {
+            drawHistory(msgTotal - (msgTotal-oldMsgCount))
+        }
+    }
+}
+checkLoop()
+
+function isFilled(field) {
+    if(field !== '' && !/^[\s]*$/.test(field)) {
+        return true
+    }
+    return false
+}
+
+async function delay(ms) {
+    return new Promise(ok => setTimeout(() => ok(ms), ms))
+}
+
+let msgScreen = document.getElementById('msgField')
+let msgTotal = 0
+
+let nickInput = document.getElementById('nickbox')
+let msgInput = document.getElementById('msgbox')
+let sendBtn = document.getElementById('sendBtn')
+sendBtn.disabled = true
+
+let nick = ''
+let text = ''
+
+nickInput.oninput = () => {
+    nick = nickInput.value;
+    isFilled(nick) && isFilled(text)? sendBtn.disabled = false : sendBtn.disabled = true 
+    console.log(nick);
+}
+msgInput.oninput = () => {
+    text = msgInput.value; 
+    isFilled(nick) && isFilled(text)? sendBtn.disabled = false : sendBtn.disabled = true 
+    console.log(text, isFilled(text), isFilled(nick));
+} 
+sendBtn.onclick = () => sendAndCheck()
+
+// setInterval(()=>{
+//     checkNewMessages()
+// }, 5000)

+ 25 - 0
hw12-promiseChat/style.css

@@ -0,0 +1,25 @@
+body {
+    font-family: 'Courier New', Courier, monospace;
+}
+
+#msgField {
+    background-color: black;
+    width: 100%;
+    min-height: 200px;
+    height: 500px;
+    border: 1px solid turquoise;
+    margin-bottom: 10px;
+    padding: 5px;
+    color: white;
+    overflow: auto;
+}
+
+#formContainer {
+    width: fit-content; 
+    text-align: center;
+}
+
+input, textarea {
+    width: 100%; 
+    margin-bottom: 5px;
+}