Various fixes
[vchess.git] / client / src / components / Chat.vue
CommitLineData
cf2343ce 1<template lang="pug">
4f887105
BA
2#chat.card
3 h4 Chat
4 p(v-for="chat in chats" :class="classObject(chat)" v-html="chat.msg")
5 input#inputChat(type="text" :placeholder="st.tr['Type here']"
6 @keyup.enter="sendChat")
7 button#sendChatBtn(@click="sendChat") {{ st.tr["Send"] }}
cf2343ce
BA
8</template>
9
10<script>
5c8e044f
BA
11import { store } from "@/store";
12
cf2343ce
BA
13export default {
14 name: "my-chat",
5c8e044f 15 props: ["players"],
cf2343ce
BA
16 data: function() {
17 return {
5c8e044f 18 st: store.state,
cf2343ce
BA
19 chats: [], //chat messages after human game
20 };
21 },
5c8e044f 22 created: function() {
cd0d7743 23 const curMsgListener = this.st.conn.onmessage; //from Game or Hall
5c8e044f 24 const socketMessageListener = msg => {
cd0d7743 25 curMsgListener(msg);
5c8e044f
BA
26 const data = JSON.parse(msg.data);
27 if (data.code == "newchat") //only event at this level
28 {
29 this.chats.push({msg:data.msg,
c6788ecf 30 name:data.name || "@nonymous", sid:data.from});
5c8e044f
BA
31 }
32 };
33 const socketCloseListener = () => {
34 store.socketCloseListener(); //reinitialize connexion (in store.js)
35 this.st.conn.addEventListener('message', socketMessageListener);
36 this.st.conn.addEventListener('close', socketCloseListener);
37 };
38 this.st.conn.onmessage = socketMessageListener;
39 this.st.conn.onclose = socketCloseListener;
cf2343ce 40 },
5c8e044f
BA
41 methods: {
42 classObject: function(chat) {
43 return {
44 "my-chatmsg": chat.sid == this.st.user.sid,
45 "opp-chatmsg": this.players.some(
46 p => p.sid == chat.sid && p.sid != this.st.user.sid)
47 };
48 },
49 sendChat: function() {
50 let chatInput = document.getElementById("inputChat");
51 const chatTxt = chatInput.value;
52 chatInput.value = "";
53 const chat = {msg:chatTxt, name: this.st.user.name || "@nonymous",
54 sid:this.st.user.sid};
55 this.chats.push(chat);
56 this.st.conn.send(JSON.stringify({
57 code:"newchat", msg:chatTxt, name:chat.name}));
58 },
59 },
60};
61</script>
62
4f887105 63<style lang="sass" scoped>
5c8e044f
BA
64.my-chatmsg
65 color: grey
66.opp-chatmsg
67 color: black
4f887105
BA
68#chat
69 max-width: 100%
5c8e044f 70</style>