111 lines
6.2 KiB
JavaScript
111 lines
6.2 KiB
JavaScript
import { homeCard } from "./cards.js";
|
||
let t = {}, pos = null, lastMsg = null, lastNote = null;
|
||
const $ = (id) => document.getElementById(id);
|
||
const fmt = (s, o) => s.replace(/\{(\w+)\}/g, (_, k) => o[k] ?? ""); // без undefined на экране
|
||
|
||
const LANGS = ["ru", "kk", "en"];
|
||
const saved = () => { try { return localStorage.getItem("lang"); } catch { return null; } };
|
||
|
||
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(); // список и сообщение над ним — тоже на новом языке
|
||
}
|
||
|
||
const filterQuery = () => `&maxKm=${$("maxKm").value}&maxPrice=${$("maxPrice").value}`;
|
||
const filtersOn = () => $("only").checked || $("maxKm").value || $("maxPrice").value;
|
||
// фильтр расстояния доступен только когда известно место пользователя
|
||
function syncFilters() { $("maxKm").disabled = !pos; $("distNote").hidden = Boolean(pos); }
|
||
function resetFilters() { $("only").checked = false; $("maxKm").value = ""; $("maxPrice").value = ""; load(); }
|
||
function noMatch(key) {
|
||
$("out").innerHTML = `<div class="msg">${t[key]}</div>`;
|
||
const b = document.createElement("button"); b.className = "btn alt"; b.id = "reset"; b.textContent = t.resetFilters; b.onclick = resetFilters;
|
||
$("out").append(b);
|
||
}
|
||
|
||
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"); syncFilters();
|
||
const place = pos ? `lat=${pos.lat}&lng=${pos.lng}&` : "";
|
||
const q = (only, f = filterQuery()) => `/api/venues?${place}only=${only}${f}`;
|
||
const r = await fetch(q($("only").checked ? 1 : 0));
|
||
if (!r.ok) return msg("error");
|
||
let list = await r.json(), note = lastNote, everywhere = !pos;
|
||
const onlyAlone = () => $("only").checked && !$("maxKm").value && !$("maxPrice").value;
|
||
if (!list.length && pos) {
|
||
// с фильтром пусто: далеко от заведений или просто нет предложений?
|
||
const base = await (await fetch(q(0, "&maxKm=&maxPrice="))).json();
|
||
if (base.length) return noMatch(onlyAlone() ? "noOffers" : "noMatch");
|
||
// рядом ничего нет — показываем весь список без привязки к месту
|
||
note = "noneNearby"; everywhere = true;
|
||
list = await (await fetch(`/api/venues?only=${$("only").checked ? 1 : 0}${filterQuery()}`)).json();
|
||
}
|
||
if (!list.length) return filtersOn() ? noMatch(onlyAlone() ? "noOffers" : "noMatch") : msg("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);
|
||
if (list.some((v) => v.walk && v.walk.approx)) {
|
||
const n = document.createElement("div"); n.className = "msg note"; n.textContent = t.walkApproxNote; out.append(n);
|
||
}
|
||
const grid = document.createElement("div"); grid.className = "list"; out.append(grid); // карточки сеткой с отступами (DIK-74)
|
||
// Карточки — общим модулем, как их сразу отдаёт сервер: цена и акция или понятная фраза (DIK-67)
|
||
grid.innerHTML = list.map((v) => homeCard(v, t)).join("");
|
||
grid.querySelectorAll(".photo img").forEach((img) => (img.onerror = () => {
|
||
const box = img.parentElement; img.remove();
|
||
box.className = "photo stub"; box.textContent = "🍽"; box.setAttribute("role", "img"); box.setAttribute("aria-label", t.noPhoto);
|
||
}));
|
||
}
|
||
|
||
// Места нет: объясняем причину, даём ввести адрес и показываем весь список
|
||
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(); };
|
||
const onFilter = load;
|
||
$("only").onchange = onFilter; $("maxKm").onchange = onFilter; $("maxPrice").onchange = onFilter;
|
||
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();
|