dika/public/app.js
Peppa f93f436070
All checks were successful
peppa/lint lint: success за 1с
peppa/test test: success за 1с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 8s
deploy / deploy (pull_request) Successful in 13s
DIK-44: районы убраны из продукта, без места показывается весь список
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 15:27:42 +05:00

122 lines
6.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

let t = {}, pos = null, lastMsg = null, lastNote = null;
const $ = (id) => document.getElementById(id);
const fmt = (s, o) => s.replace(/\{(\w+)\}/g, (_, k) => o[k]);
const ruDate = (iso) => iso.split("-").reverse().join(".");
const dist = (m) => (m < 1000 ? m + " " + t.m : (m / 1000).toFixed(1) + " " + t.km);
const LANGS = ["ru", "kk", "en"];
const saved = () => { try { return localStorage.getItem("lang"); } catch { return null; } };
const ptext = (s) => (t.promoTexts && t.promoTexts[s]) || s;
async function setLang(l) {
try { localStorage.setItem("lang", l); } catch {}
t = await (await fetch(`i18n/${l}.json`)).json();
document.documentElement.lang = l;
document.querySelectorAll("[data-i]").forEach((e) => (e.textContent = t[e.dataset.i]));
document.querySelectorAll("[data-ph]").forEach((e) => (e.placeholder = t[e.dataset.ph]));
document.querySelectorAll("[data-al]").forEach((e) => e.setAttribute("aria-label", t[e.dataset.al]));
document.querySelectorAll("[data-ti]").forEach((e) => (e.title = t[e.dataset.ti]));
document.title = t.title;
document.querySelectorAll("[data-l]").forEach((b) => {
b.classList.toggle("on", b.dataset.l === l); b.setAttribute("aria-pressed", String(b.dataset.l === l));
});
load(); // список и сообщение над ним — тоже на новом языке
}
function msg(key) { lastMsg = key; $("out").innerHTML = `<div class="msg">${t[key]}</div>`; }
async function load() {
try { await show(); } catch { msg("error"); }
}
async function show() {
msg("searching");
const place = pos ? `lat=${pos.lat}&lng=${pos.lng}&` : "";
const q = (only) => `/api/venues?${place}only=${only}`;
const r = await fetch(q($("only").checked ? 1 : 0));
if (!r.ok) return msg("error");
let list = await r.json(), note = lastNote, everywhere = !pos;
if (!list.length && pos) {
// с фильтром пусто: далеко от заведений или просто нет предложений?
const near = $("only").checked ? await (await fetch(q(0))).json() : [];
if (near.length) return msg("noOffers");
// рядом ничего нет — показываем весь список без привязки к месту
note = "noneNearby"; everywhere = true;
list = await (await fetch(`/api/venues?only=${$("only").checked ? 1 : 0}`)).json();
if (!list.length) return msg("noOffers");
}
if (!list.length) return msg($("only").checked ? "noOffers" : "listPreparing");
const out = $("out"); out.textContent = "";
if (note) { const w = document.createElement("div"); w.className = "msg"; w.textContent = t[note]; out.append(w) }
const sum = document.createElement("div"); sum.className = "msg note"; sum.id = "summary";
sum.textContent = fmt(everywhere ? t.resultsNoPlace : $("only").checked ? t.resultsOffers : t.resultsAll, { n: list.length }); out.append(sum);
for (const v of list) {
const c = document.createElement("div"); c.className = "card";
const body = document.createElement("div"); body.className = "body";
const top = document.createElement("div"); top.className = "top";
const h = document.createElement("h2"); h.textContent = v.name;
top.append(h);
if (v.distance != null) { const d = document.createElement("span"); d.className = "dist"; d.textContent = dist(v.distance); top.append(d); }
const m = document.createElement("div"); m.className = "meta"; m.textContent = v.address;
const desc = document.createElement("p"); desc.className = "desc" + (v.description ? "" : " empty");
desc.textContent = v.description || t.noDescription;
body.append(top, m, desc);
c.append(photo(v), body);
if (v.lunch) body.append(tag(fmt(t.lunch, { price: v.lunch.price, from: v.lunch.from, to: v.lunch.to }), "lunch"));
if (v.promo) body.append(tag(fmt(v.promo.until ? t.promo : t.promoOpen, { text: ptext(v.promo.text), until: v.promo.until && ruDate(v.promo.until) }), "promo"));
if ((v.lunch || v.promo) && v.checked) {
const n = document.createElement("div"); n.className = "meta"; n.textContent = fmt(t.checkedOn, { date: ruDate(v.checked) }); body.append(n);
} else if (v.unconfirmed) {
const n = document.createElement("div"); n.className = "meta"; n.textContent = t.notConfirmed; body.append(n);
}
out.append(c);
}
}
// Фото или заглушка: пустого места на карточке не бывает, в том числе если картинка не загрузилась.
function photo(v) {
const box = document.createElement("div"); box.className = "photo";
const stub = () => { box.className = "photo stub"; box.textContent = "🍽"; box.setAttribute("role", "img"); box.setAttribute("aria-label", t.noPhoto); };
if (!v.photo) { stub(); return box; }
const img = document.createElement("img"); img.src = v.photo; img.alt = fmt(t.photoAlt, { name: v.name }); img.loading = "lazy";
img.onerror = () => { img.remove(); stub(); };
box.append(img); return box;
}
function tag(s, cls) { const d = document.createElement("span"); d.className = "badge " + cls; d.textContent = s; return d; }
// Места нет: объясняем причину, даём ввести адрес и показываем весь список
function noPlace(key) { pos = null; lastNote = key; load(); }
$("geo").onclick = () => {
if (!navigator.geolocation) return noPlace("geoFailed");
msg("searching");
navigator.geolocation.getCurrentPosition(
(p) => { pos = { lat: p.coords.latitude, lng: p.coords.longitude }; lastNote = null; load(); },
(e) => noPlace(e.code === 1 ? "geoDenied" : e.code === 3 ? "geoSlow" : "geoFailed"),
{ timeout: 10000 });
};
$("addrBtn").onclick = async () => {
msg("searching");
try {
const r = await fetch("/api/locate?q=" + encodeURIComponent($("addr").value));
if (!r.ok) return noPlace("addrNotFound");
pos = await r.json(); lastNote = null;
} catch { return msg("error"); }
load();
};
$("addr").onkeydown = (e) => { if (e.key === "Enter") $("addrBtn").click(); };
$("only").onchange = load;
const menu = $("menu"), veil = $("veil");
const toggle = (open) => { menu.classList.toggle("open", open); veil.hidden = !open; $("burger").setAttribute("aria-expanded", String(open)); };
$("burger").onclick = () => toggle(!menu.classList.contains("open"));
veil.onclick = () => toggle(false);
document.addEventListener("keydown", (e) => { if (e.key === "Escape") toggle(false); });
function route() {
const id = location.hash === "#about" ? "about" : "nearby";
document.querySelectorAll("section").forEach((e) => e.classList.toggle("on", e.id === id));
toggle(false);
}
window.onhashchange = route;
document.querySelectorAll("[data-l]").forEach((b) => (b.onclick = () => { setLang(b.dataset.l); toggle(false); }));
await setLang(LANGS.includes(saved()) ? saved() : "ru");
route();