what-to-cook/src/app.js
2026-11-16 05:58:49 +05:00

81 lines
2.5 KiB
JavaScript

import { submitDish, removeDish, pickDish, parseState } from "./logic.js";
import { messages, pickLang } from "./i18n.js";
const KEY = "wtc:v1";
const t = messages[pickLang(navigator.language)];
const $ = (id) => document.getElementById(id);
let state = { dishes: [], last: null };
try { state = parseState(localStorage.getItem(KEY)); } catch {}
function save() {
try { localStorage.setItem(KEY, JSON.stringify(state)); } catch {}
}
function render() {
document.documentElement.lang = pickLang(navigator.language);
document.title = t.title;
$("title").textContent = t.title;
$("listTitle").textContent = t.yourDishes;
$("name").placeholder = t.placeholder;
$("nameLabel").textContent = t.nameLabel;
$("add").textContent = t.add;
$("pick").textContent = t.pick;
$("pick").disabled = state.dishes.length === 0;
const n = state.dishes.length;
$("hint").textContent = n === 0 ? t.emptyHint : n === 1 && state.last ? t.oneHint : "";
$("hint").hidden = !$("hint").textContent;
const show = state.last !== null;
$("today").hidden = $("dish").hidden = !show;
$("today").textContent = t.today;
$("dish").textContent = state.last ?? "";
$("empty").textContent = t.listEmpty;
$("empty").hidden = n !== 0;
const ul = $("list");
ul.replaceChildren(...state.dishes.map((d) => {
const li = document.createElement("li");
const span = document.createElement("span");
span.textContent = d;
const b = document.createElement("button");
b.type = "button";
b.textContent = t.remove;
b.setAttribute("aria-label", t.removeLabel.replace("{name}", d));
b.addEventListener("click", () => {
state.dishes = removeDish(state.dishes, d);
if (state.last === d) state.last = null;
save(); render();
});
li.append(span, b);
return li;
}));
}
function showNameError(key) {
$("nameError").textContent = key ? t[key] : "";
$("nameError").hidden = !key;
if (key) $("name").setAttribute("aria-invalid", "true");
else $("name").removeAttribute("aria-invalid");
}
$("form").addEventListener("submit", (e) => {
e.preventDefault();
const r = submitDish(state.dishes, $("name").value);
showNameError(r.error);
$("name").focus();
if (r.error) return;
state.dishes = r.dishes;
$("name").value = "";
save(); render();
});
$("name").addEventListener("input", () => showNameError(null));
$("pick").addEventListener("click", () => {
state.last = pickDish(state.dishes, state.last);
save(); render();
});
render();