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