diff --git a/evaluator.js b/evaluator.js new file mode 100644 index 0000000..8ab2a31 --- /dev/null +++ b/evaluator.js @@ -0,0 +1 @@ +onmessage = e => postMessage(eval(`parseInt(Math.round(${e.data}))`)); \ No newline at end of file diff --git a/main.js b/main.js index 45e0845..50b3b3d 100644 --- a/main.js +++ b/main.js @@ -113,18 +113,33 @@ async function addMenuItem(food) { }); const updateKcalAmount = () => { - if (!/[0-9]+/.test(itemAmount.value)) { - console.log("no match"); + if (!/^[0-9]+$/.test(itemAmount.value)) { return; } + const amount = parseInt(itemAmount.value); kcalAmount.textContent = parseInt(Math.round(food.kcal / 100 * amount)); updateSummary(); + }; + + const evaluateKcalAmount = () => { + if (/^[0-9]+$/.test(itemAmount.value)) { + return; + } + + const evaluator = new Worker("evaluator.js"); + evaluator.postMessage(itemAmount.value); + evaluator.onmessage = e => { + const amount = Math.max(parseInt(e.data), 0); + itemAmount.value = amount; + kcalAmount.textContent = parseInt(Math.round(food.kcal / 100 * amount)); + updateSummary(); + }; } - console.log(food.avg_amount); itemAmount.value = food.avg_amount ?? 100; itemAmount.addEventListener("input", updateKcalAmount); + itemAmount.addEventListener("change", evaluateKcalAmount); updateKcalAmount(); foodMenu.appendChild(node); @@ -132,6 +147,7 @@ async function addMenuItem(food) { } function updateSummary() { + console.log("asd"); let sum = 0; for (let menuItem of foodMenu.querySelectorAll(".menu-item")) { diff --git a/templates/menu-item.html b/templates/menu-item.html index d2ea993..c977010 100644 --- a/templates/menu-item.html +++ b/templates/menu-item.html @@ -7,7 +7,7 @@