From d8af7c3ae0d460b9f31e2e26ca5956632d9dbe06 Mon Sep 17 00:00:00 2001 From: Kai Vogelgesang Date: Sat, 18 Jul 2020 00:06:05 +0200 Subject: [PATCH] Implement user js --- static/js/user.js | 72 ++++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 35 deletions(-) diff --git a/static/js/user.js b/static/js/user.js index 5592100..7f940b7 100644 --- a/static/js/user.js +++ b/static/js/user.js @@ -1,40 +1,17 @@ "use strict" -function render_scoreboard(data) { - const users = Object.values(data.users); +const token = document.location.pathname.split("/").pop(); +const api_path = `../../api/token${token}/`; - users.sort((a, b) => b.score - a.score); - const min_score = users[users.length-1].score, - max_score = users[0].score; - - const tbody = document.querySelector("#scoreboard tbody"); - while (tbody.children.length) { - tbody.removeChild(tbody.firstChild); - } +const greeting = document.getElementById("greeting"), + currentcoins = document.getElementById("currentcoins"), + maxcoins = document.getElementById("maxcoins"), + sellvalue = document.getElementById("sellvalue"); - const template = document.querySelector("#scoreboard template"); +async function redraw() { - for (const user of users) { - - const clone = template.content.cloneNode(true); - const name = clone.querySelector(".name"), - score = clone.querySelector(".score"), - bar = clone.querySelector(".bar"); - - const score_percent = Math.floor(10 + (user.score - min_score) / (max_score - min_score) * 90) + "%"; - bar.style.width = score_percent; - - name.innerText = user.name; - score.innerText = user.score; - - tbody.appendChild(clone); - } -} - -async function update_scoreboard() { - - const r = await fetch('api/get_public_model', { + const r = await fetch(api_path + 'get_user', { method: 'POST', body: JSON.stringify({}), }); @@ -44,9 +21,34 @@ async function update_scoreboard() { return; } - const data = await r.json(); - render_scoreboard(data); + const user = await r.json(); + + greeting.innerText = `Hey, ${user.name}`; + currentcoins.innerText = user.score; + maxcoins.innerText = user.maxscore; + sellvalue.max = user.maxscore - user.score; + } -update_scoreboard(); -setInterval(update_scoreboard, 1000); \ No newline at end of file +redraw(); + +const button = document.getElementById("sell"); + +button.addEventListener("click", async () => { + const newscore = parseInt(currentcoins.innerText) + parseInt(sellvalue.value); + console.log(newscore); + + const r = await fetch(api_path + 'set_score', { + method: "POST", + body: JSON.stringify({ + newscore: newscore, + }), + }); + + if (r.status !== 200) { + console.log("something went wrong"); + return; + } + + redraw(); +}) \ No newline at end of file