8230e9f853ae01ca35c2fea68846ad05c2277cef
[vchess.git] / client / next_src / components / chat.js
1 // TODO: myname, opppnents (optional, different style), people
2 // --> also show messages like "X offers draw ?" (probably not)
3 // myname: localStorage["username"] || "anonymous",
4 Vue.component("my-chat", {
5 props: ["conn","myname","opponents","people"],
6 data: function() {
7 return {
8 chats: [], //chat messages after human game
9 };
10 },
11 // TODO: Chat modal sur petit écran, dans la page pour grand écran
12 template: `
13 <div>
14 <input id="modal-chat" type="checkbox" class="modal">
15 <div role="dialog" aria-labelledby="titleChat">
16 <div class="card smallpad">
17 <label id="close-chat" for="modal-chat" class="modal-close"></label>
18 <h3 v-if="!!opponents" id="titleChat" class="section">
19 <span>{{ translate("Chat with ") }}</span>
20 <span v-for="o in opponents">{{ o.name }}</span>
21 </h3>
22 <p v-for="chat in chats" :class={
23 "my-chatmsg": "chat.uid==user.id",
24 "opp-chatmsg": "opponents.any(o => o.id == chat.uid)"}
25 v-html="chat.msg"
26 >
27 TODO: why chat.msg fails here?
28 </p>
29 <input id="input-chat" type="text" placeholder="translate('Type here')"
30 @keyup.enter="sendChat"/>
31 <button id="sendChatBtn" @click="sendChat">{{ translate("Send") }}</button>
32 </div>
33 </div>
34 </div>
35 `,
36 created: function() {
37 const socketMessageListener = msg => {
38 const data = JSON.parse(msg.data);
39 switch (data.code)
40 {
41 case "newchat":
42 // TODO: new chat just arrived: data contain all informations
43 // (uid, name, message; no need for timestamp, we can use local time here)
44 this.chats.push({msg:data.msg, author:this.oppid});
45 break;
46 // TODO: distinguish these (dis)connect events from their analogs in game.js
47 // TODO: implement and harmonize: opponents and people are arrays, not objects ?!
48 case "connect":
49 this.players.push({name:data.name, id:data.uid});
50 break;
51 case "disconnect":
52 const pIdx = this.players.findIndex(p => p.id == data.uid);
53 this.players.splice(pIdx);
54 break;
55 }
56 };
57 const socketCloseListener = () => {
58 this.conn.addEventListener('message', socketMessageListener);
59 this.conn.addEventListener('close', socketCloseListener);
60 };
61 this.conn.onmessage = socketMessageListener;
62 this.conn.onclose = socketCloseListener;
63 },
64 methods: {
65 translate: translate,
66 // TODO: complete this component
67 sendChat: function() {
68 let chatInput = document.getElementById("input-chat");
69 const chatTxt = chatInput.value;
70 chatInput.value = "";
71 this.chats.push({msg:chatTxt, author:this.myid});
72 this.conn.send(JSON.stringify({
73 code:"newchat", oppid: this.oppid, msg: chatTxt}));
74 },
75 // startChat: function(e) {
76 // document.getElementById("modal-chat").checked = true;
77 // },
78 },
79 });