User-friendly vchess presentation on index + some code cleaning
[vchess.git] / public / javascripts / index.js
CommitLineData
772d7245 1new Vue({
1d184b4c
BA
2 el: "#indexPage",
3 data: {
4 counts: {},
5 curPrefix: "",
772d7245 6 conn: null,
1d184b4c
BA
7 },
8 computed: {
9 sortedCounts: function () {
10 const variantsCounts = variantArray.map( v => {
11 return {
12 name: v.name,
13 desc: v.description,
14 count: this.counts[v.name] || 0,
15 };
16 });
17 return variantsCounts.sort((a,b) => {
18 if (a.count != b.count)
19 return b.count - a.count;
20 // Else, alphabetic ordering
21 return a.name.localeCompare(b.name);
22 });
23 },
24 },
772d7245
BA
25 created: function() {
26 const url = socketUrl;
b019d603 27 const sid = getRandString();
772d7245
BA
28 this.conn = new WebSocket(url + "/?sid=" + sid + "&page=index");
29 const socketMessageListener = msg => {
30 const data = JSON.parse(msg.data);
31 if (data.code == "counts")
32 this.counts = data.counts;
33 else if (data.code == "increase")
34 this.counts[data.vname]++;
35 else if (data.code == "decrease")
36 this.counts[data.vname]--;
37 };
38 const socketCloseListener = () => {
772d7245
BA
39 this.conn = new WebSocket(url + "/?sid=" + sid + "&page=index");
40 this.conn.addEventListener('message', socketMessageListener);
41 this.conn.addEventListener('close', socketCloseListener);
42 };
43 this.conn.onmessage = socketMessageListener;
44 this.conn.onclose = socketCloseListener;
45 },
1d184b4c
BA
46 mounted: function() {
47 // Handle key stroke
48 document.onkeydown = event => {
49 // Is it Back or Esc? If yes, apply action on current word
50 if (event.keyCode == 8) //Back
51 {
52 event.preventDefault();
53 this.curPrefix = this.curPrefix.slice(0,-1);
54 }
55 else if (event.keyCode == 27) //Esc
56 {
57 event.preventDefault();
58 this.curPrefix = "";
59 }
60 // Is it alphanumeric? If yes, stack it
61 else if (_.range(48,58).includes(event.keyCode)
62 || _.range(65,91).includes(event.keyCode)
63 || _.range(97,123).includes(event.keyCode))
64 {
65 let newChar = String.fromCharCode(event.keyCode);
66 this.curPrefix += this.curPrefix.length==0
67 ? newChar.toUpperCase()
68 : newChar.toLowerCase();
69 }
70 // ...ignore everything else
71 };
b019d603
BA
72 // Show welcome dialog box if "first visit"
73 const visited = getCookie("visited");
74 if (!visited || visited !== "1")
75 document.getElementById("modal-welcome").checked = true;
1d184b4c
BA
76 },
77});