dika/public/app.js
Peppa 1e37870d40
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 0с
peppa/build build: success за 1с
ci / checks (pull_request) Successful in 10s
deploy / deploy (pull_request) Successful in 16s
DIK-22: видимый отклик после кнопки и галочки: «Ищем…» под кнопкой, прокрутка к итогу, понятный итог с галочкой
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 17:10:37 +05:00

186 lines
11 KiB
JavaScript
Raw Permalink 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, statusKey = null, locating = false, seq = 0;
const $ = (id) => document.getElementById(id);
const fmt = (s, o) => s.replace(/\{(\w+)\}/g, (_, k) => o[k] ?? ""); // без undefined на экране
const ruDate = (iso) => iso.split("-").reverse().join(".");
const dist = (m) => (m < 1000 ? m + " " + t.m : (m / 1000).toFixed(1) + " " + t.km);
const walk = (w) => fmt(w.approx ? t.walkApprox : t.walkExact, { dist: dist(w.m), min: w.min });
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));
});
status(statusKey); busy(locating);
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>`; }
// Строка под кнопкой: «Ищем…» или почему место не определилось — рядом с полем адреса, на экране (DIK-22)
function status(key) {
statusKey = key; const s = $("status");
s.hidden = !key; s.textContent = key ? t[key] : "";
}
// Кнопка на время поиска места: «Ищем…» и не нажимается повторно
function busy(on) {
locating = on;
for (const id of ["geo", "addrBtn"]) $(id).disabled = on;
$("geo").textContent = on ? t.searchingBtn : t.useLocation;
}
// Итог или сообщение должны оказаться в видимой части экрана, а не под его краем
function reveal(block) {
const el = $("summary") || $("out").firstElementChild;
if (el && el.scrollIntoView) el.scrollIntoView({ behavior: "smooth", block });
}
async function load(block) {
const my = ++seq;
try { await show(() => my !== seq); } catch { if (my === seq) msg("error"); }
if (my !== seq) return;
if (statusKey === "searching") { status(null); busy(false); } // место найдено и список готов
if (block) reveal(block);
}
async function show(stale) {
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 (stale()) return;
if (!r.ok) return msg("error");
let list = await r.json(), note = lastNote, everywhere = !pos;
if (stale()) return;
const onlyAlone = () => $("only").checked && !$("maxKm").value && !$("maxPrice").value;
if (!list.length && pos) {
// с фильтром пусто: далеко от заведений или просто нет предложений?
const base = await (await fetch(q(0, "&maxKm=&maxPrice="))).json();
if (stale()) return;
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 (stale()) return;
}
if (!list.length) return filtersOn() ? noMatch(onlyAlone() ? "noOffers" : "noMatch") : msg("listPreparing");
const out = $("out"); out.textContent = "";
if (note === "noneNearby") { 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";
// итог называет, что именно показано: весь список, только с предложением или под фильтры
const extra = $("maxKm").value || $("maxPrice").value, only = $("only").checked;
const key = everywhere ? (extra ? "resultsNoPlaceFiltered" : only ? "resultsNoPlaceOffers" : "resultsNoPlace")
: extra ? "resultsFiltered" : only ? "resultsOffers" : "resultsAll";
sum.textContent = fmt(t[key], { 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);
}
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.walk) { const d = document.createElement("span"); d.className = "dist"; d.textContent = walk(v.walk); 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);
const ds = srcNote(v.description && v.descriptionSource); if (ds) body.append(ds);
const ps = srcNote(v.photo && v.photoSource, true); if (ps) body.append(ps);
c.append(photo(v), body);
// Цена и акция: действующие — плашкой, иначе понятной фразой, а не пустым местом (DIK-26)
if (v.lunch) body.append(tag(fmt(t.lunch, { price: v.lunch.price, from: v.lunch.from, to: v.lunch.to }), "lunch"));
else body.append(meta(v.lunchHours ? fmt(t.lunchLater, v.lunchHours) : t.notConfirmed, "offer-none"));
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"));
else body.append(meta(v.promoState === "ended" ? t.promoEnded : t.promoNone, "offer-none"));
if ((v.lunch || v.promo) && v.checked) body.append(meta(fmt(t.checkedOn, { date: ruDate(v.checked) })));
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;
}
// «Источник: 2ГИС» — название ссылкой, если рядом адрес страницы; адреса не показываем (DIK-58)
function srcNote(source, isPhoto) {
if (!source) return null;
const m = /^(.*?)\s*(https?:\/\/\S+)$/.exec(source);
let name = (m ? m[1] : source).replace(/[\s—-]+$/, "");
if (name === "владелец") name = t.srcOwner;
const d = document.createElement("div"); d.className = "meta srcnote";
d.append((isPhoto ? t.srcPhotoLabel : t.srcLabel) + " ");
if (m) { const a = document.createElement("a"); a.href = m[2]; a.textContent = name || m[2]; a.target = "_blank"; a.rel = "noopener noreferrer"; d.append(a); }
else d.append(name);
return d;
}
function meta(s, cls) { const d = document.createElement("div"); d.className = "meta" + (cls ? " " + cls : ""); d.textContent = s; return d; }
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; busy(false); status(key); load(); }
// Место есть: прокручиваем к итогу «Найдено мест: N»
function gotPlace(p) { pos = p; lastNote = null; load("start"); }
$("geo").onclick = () => {
if (locating) return;
if (!navigator.geolocation) return noPlace("geoFailed");
busy(true); status("searching");
navigator.geolocation.getCurrentPosition(
(p) => gotPlace({ lat: p.coords.latitude, lng: p.coords.longitude }),
(e) => noPlace(e.code === 1 ? "geoDenied" : e.code === 3 ? "geoSlow" : "geoFailed"),
{ timeout: 10000 });
};
$("addrBtn").onclick = async () => {
if (locating) return;
busy(true); status("searching");
let p;
try {
const r = await fetch("/api/locate?q=" + encodeURIComponent($("addr").value));
if (!r.ok) return noPlace("addrNotFound");
p = await r.json();
} catch { busy(false); return status("error"); }
gotPlace(p);
};
$("addr").onkeydown = (e) => { if (e.key === "Enter") $("addrBtn").click(); };
const onFilter = () => load("nearest");
$("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();