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