dika/public/cards.js

79 lines
4.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.

// Карточки заведений — общий модуль для сервера и браузера (DIK-67).
// Чистые функции: получают данные и тексты выбранного языка, отдают HTML-строку.
// Цена и акция на карточке есть всегда: действующие — плашкой, иначе понятной фразой.
export const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
export const fmt = (s, o) => String(s ?? "").replace(/\{(\w+)\}/g, (_, k) => o[k] ?? ""); // без undefined на экране
export const ruDate = (iso) => (iso ? iso.split("-").reverse().join(".") : "");
const safe = (u) => /^https?:\/\//.test(u || "");
const promoText = (t, s) => (t.promoTexts && t.promoTexts[s]) || s;
const descText = (t, s) => (t.descTexts && t.descTexts[s]) || s;
const MAX_AGE_DAYS = 14;
const dayNum = (iso) => Math.floor(Date.parse(iso + "T00:00:00Z") / 86400000);
// Сегодня по Астане (UTC+5), YYYY-MM-DD
export const astanaToday = (now = new Date()) => new Date(now.getTime() + 5 * 3600000).toISOString().slice(0, 10);
export function walkText(w, t) {
const dist = w.m < 1000 ? w.m + " " + t.m : (w.m / 1000).toFixed(1) + " " + t.km;
return fmt(w.approx ? t.walkApprox : t.walkExact, { dist, min: w.min });
}
function photo(v, t) {
if (!v.photo || !safe(v.photo)) return `<div class="photo stub" role="img" aria-label="${esc(t.noPhoto)}">🍽</div>`;
return `<div class="photo"><img src="${esc(v.photo)}" alt="${esc(fmt(t.photoAlt, { name: v.name }))}" loading="lazy"></div>`;
}
// «Источник: 2ГИС» — название ссылкой, если рядом адрес страницы (DIK-58)
function srcNote(source, t, isPhoto) {
if (!source) return "";
const m = /^(.*?)\s*(https?:\/\/\S+)$/.exec(source);
let name = (m ? m[1] : source).replace(/[\s—-]+$/, "");
if (name === "владелец") name = t.srcOwner;
const label = esc(isPhoto ? t.srcPhotoLabel : t.srcLabel);
const val = m ? `<a href="${esc(m[2])}" target="_blank" rel="noopener noreferrer">${esc(name || m[2])}</a>` : esc(name);
return `<div class="meta srcnote">${label} ${val}</div>`;
}
const badge = (text, cls) => `<span class="badge ${cls}">${esc(text)}</span>`;
const line = (text, cls) => `<div class="meta${cls ? " " + cls : ""}">${esc(text)}</div>`;
function card(v, t, offer, extra = "") {
const desc = v.description
? `<p class="desc">${esc(descText(t, v.description))}</p>`
: `<p class="desc empty">${esc(t.noDescription)}</p>`;
return `<div class="card">${photo(v, t)}<div class="body"><div class="top"><h2>${esc(v.name)}</h2>${extra}</div>`
+ line(v.address) + desc
+ srcNote(v.description && v.descriptionSource, t) + srcNote(v.photo && v.photoSource, t, true)
+ offer + "</div></div>";
}
// Карточка главной: v — элемент ответа /api/venues (buildList)
export function homeCard(v, t) {
let offer = v.lunch ? badge(fmt(t.lunch, v.lunch), "lunch")
: line(v.lunchHours ? fmt(t.lunchLater, v.lunchHours) : t.notConfirmed, "offer-none");
offer += v.promo ? badge(fmt(v.promo.until ? t.promo : t.promoOpen, { text: promoText(t, v.promo.text), until: ruDate(v.promo.until) }), "promo")
: line(v.promoState === "ended" ? t.promoEnded : t.promoNone, "offer-none");
if ((v.lunch || v.promo) && v.checked) offer += line(fmt(t.checkedOn, { date: ruDate(v.checked) }));
const dist = v.walk ? `<span class="dist">${esc(walkText(v.walk, t))}</span>` : "";
return card(v, t, offer, dist);
}
// Цена и акция для записи «Все заведения» (v — запись /api/base); правила свежести как на главной
export function baseOffer(v, t, today) {
const stale = Boolean(v.checked) && dayNum(today) - dayNum(v.checked) > MAX_AGE_DAYS;
const lunch = v.lunch && !stale ? { text: fmt(t.lunch, v.lunch), active: true } : { text: t.notConfirmed, active: false };
const ended = v.promo && v.promo.until && v.promo.until < today;
const promo = ended ? { text: t.promoEnded, active: false }
: v.promo && !stale ? { text: fmt(v.promo.until ? t.promo : t.promoOpen, { text: promoText(t, v.promo.text), until: ruDate(v.promo.until) }), active: true }
: { text: t.promoNone, active: false };
const checked = v.checked ? fmt(t.checkedOn, { date: ruDate(v.checked) }) : t.cardNotChecked;
return { lunch, promo, checked };
}
export function baseCard(v, t, today) {
const o = baseOffer(v, t, today);
const show = (x, cls) => (x.active ? badge(x.text, cls) : line(x.text, "offer-none"));
return card(v, t, show(o.lunch, "lunch") + show(o.promo, "promo") + line(o.checked));
}