-
Notifications
You must be signed in to change notification settings - Fork 4
/
scripts.js
71 lines (61 loc) · 2.2 KB
/
scripts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
let foods = [];
let dishes = [];
const button = ["Generate"];
const placeholders = ["correct-horse-battery-staple", "water-rhubarb-martini"];
const pass = document.getElementById("pass");
const genButton = document.getElementById("genButton");
const fullRecipeButton = document.getElementById("fullRecipeButton");
const slider = document.getElementById("slider");
const sliderValue = document.getElementById("sliderValue");
const url = "https://api.itadakimasu.app";
function gen(len) {
let randFoods = [];
let generated = "";
//add the ingredients first
for (let i = 0; i < len - 1; i++) {
randFoods.push(foods[Math.floor(Math.random() * foods.length)]);
randFoods.push("-");
}
//append a dish type
randFoods.push(dishes[Math.floor(Math.random() * dishes.length)]);
for (let i = 0; i < len * 2 - 1; i++) {
generated += randFoods[i];
}
return generated;
}
document.addEventListener("DOMContentLoaded", async function () {
document.getElementById("pass").textContent =
placeholders[Math.floor(Math.random() * placeholders.length)];
foods = await (await fetch("./data/foods.json")).json();
dishes = await (await fetch("./data/dishes.json")).json();
});
pass.addEventListener("click", async () => {
await navigator.clipboard.writeText(pass.innerText);
});
genButton.addEventListener("click", () => {
pass.innerText = gen(slider.value);
});
fullRecipeButton.addEventListener("click", async () => {
document.getElementById("spinner").style.display = "flex";
try {
const ingredients = document.getElementById("pass").innerText;
const encodedIngredients = encodeURIComponent(ingredients);
const response = await fetch(
url + "/gen?ingredients=" + encodedIngredients
);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log("Data fetched successfully:", data);
window.location = url + data.url;
} catch (error) {
console.error("Error fetching data:", error);
} finally {
document.getElementById("spinner").style.display = "none";
}
});
slider.addEventListener("input", () => {
sliderValue.textContent = slider.value;
pass.innerText = gen(slider.value);
});