| 1 | new Vue({ |
| 2 | el: "#indexPage", |
| 3 | data: { |
| 4 | counts: {}, |
| 5 | curPrefix: "", |
| 6 | conn: null, |
| 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 | }, |
| 25 | created: function() { |
| 26 | const url = socketUrl; |
| 27 | // random enough (TODO: function) |
| 28 | const sid = (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase(); |
| 29 | this.conn = new WebSocket(url + "/?sid=" + sid + "&page=index"); |
| 30 | const socketMessageListener = msg => { |
| 31 | const data = JSON.parse(msg.data); |
| 32 | if (data.code == "counts") |
| 33 | this.counts = data.counts; |
| 34 | else if (data.code == "increase") |
| 35 | this.counts[data.vname]++; |
| 36 | else if (data.code == "decrease") |
| 37 | this.counts[data.vname]--; |
| 38 | }; |
| 39 | const socketCloseListener = () => { |
| 40 | console.log("Lost connection -- reconnect"); |
| 41 | this.conn = new WebSocket(url + "/?sid=" + sid + "&page=index"); |
| 42 | this.conn.addEventListener('message', socketMessageListener); |
| 43 | this.conn.addEventListener('close', socketCloseListener); |
| 44 | }; |
| 45 | this.conn.onmessage = socketMessageListener; |
| 46 | this.conn.onclose = socketCloseListener; |
| 47 | }, |
| 48 | mounted: function() { |
| 49 | // Handle key stroke |
| 50 | document.onkeydown = event => { |
| 51 | // Is it Back or Esc? If yes, apply action on current word |
| 52 | if (event.keyCode == 8) //Back |
| 53 | { |
| 54 | event.preventDefault(); |
| 55 | this.curPrefix = this.curPrefix.slice(0,-1); |
| 56 | } |
| 57 | else if (event.keyCode == 27) //Esc |
| 58 | { |
| 59 | event.preventDefault(); |
| 60 | this.curPrefix = ""; |
| 61 | } |
| 62 | // Is it alphanumeric? If yes, stack it |
| 63 | else if (_.range(48,58).includes(event.keyCode) |
| 64 | || _.range(65,91).includes(event.keyCode) |
| 65 | || _.range(97,123).includes(event.keyCode)) |
| 66 | { |
| 67 | let newChar = String.fromCharCode(event.keyCode); |
| 68 | this.curPrefix += this.curPrefix.length==0 |
| 69 | ? newChar.toUpperCase() |
| 70 | : newChar.toLowerCase(); |
| 71 | } |
| 72 | // ...ignore everything else |
| 73 | }; |
| 74 | }, |
| 75 | }); |