"use strict"; const categories = new Map([ ["ai", "ИИ и автоматизация"], ["safety", "Безопасность и лидерство"], ["business", "Продукты и бизнес"], ["games", "Игры и игровые миры"], ["tech", "Техника и инфраструктура"], ["family", "Семья, дом и путешествия"], ]); const brandName = "Утренняя подборка Александра"; const state = { manifest: null, edition: null, request: 0, cache: new Map() }; const $ = (selector) => document.querySelector(selector); const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)"); const fullDate = new Intl.DateTimeFormat("ru-RU", { day: "numeric", month: "long", year: "numeric", timeZone: "Europe/Moscow", }); const dayAndMonth = new Intl.DateTimeFormat("ru-RU", { day: "numeric", month: "long", timeZone: "Europe/Moscow", }); const weekday = new Intl.DateTimeFormat("ru-RU", { weekday: "long", timeZone: "Europe/Moscow", }); const clock = new Intl.DateTimeFormat("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: "Europe/Moscow", }); const datePattern = /^\d{4}-\d{2}-\d{2}$/; function el(tag, className = "", value = "") { const item = document.createElement(tag); if (className) item.className = className; if (value) item.textContent = value; return item; } function asDate(value) { if (!value) return null; const date = new Date( datePattern.test(value) ? value + "T12:00:00+03:00" : value, ); return Number.isFinite(date.getTime()) ? date : null; } function humanDate(value, withYear = false) { const date = asDate(value); return date ? (withYear ? fullDate : dayAndMonth).format(date).replace(/\sг\.$/, "") : ""; } function capitalize(value) { return value.charAt(0).toUpperCase() + value.slice(1); } function editionLabel(value) { const date = asDate(value); return date ? `${capitalize(weekday.format(date))}, ${humanDate(value, true)}` : ""; } function safeUrl(value, allowLocal = false) { if (typeof value !== "string" || !value.trim()) return ""; try { const url = allowLocal ? new URL(value, location.origin) : new URL(value); return ["https:", "http:"].includes(url.protocol) ? url.href : ""; } catch { return ""; } } function externalLink(url, text, className = "") { const link = el("a", className, text); link.href = url; link.target = "_blank"; link.rel = "noopener noreferrer"; return link; } function pageUrl(section, date) { const url = new URL("/", location.origin); if (date) url.searchParams.set("date", date); if (section) url.searchParams.set("section", section); return url.pathname + url.search; } function route() { const query = new URLSearchParams(location.search); const section = query.get("section"); return { date: query.get("date"), section: categories.has(section) ? section : "ai", }; } function plural(number) { const rules = new Intl.PluralRules("ru").select(number); return `${number} ${{ one: "материал", few: "материала", many: "материалов", other: "материала" }[rules]}`; } function inlineText(parent, value) { // Only simple editorial emphasis is supported; source HTML never enters the page. for (const piece of String(value ?? "").split( /(\*\*[^*\n]+\*\*|\*[^*\n]+\*)/g, )) { if (piece.startsWith("**") && piece.endsWith("**")) parent.append(el("strong", "", piece.slice(2, -2))); else if (piece.startsWith("*") && piece.endsWith("*")) parent.append(el("em", "", piece.slice(1, -1))); else parent.append(document.createTextNode(piece)); } } function paragraphs(parent, content, style, prefix = "") { const parts = ( Array.isArray(content) ? content : String(content || "").split(/\n+/) ).filter(Boolean); parts.forEach((text, index) => { const node = el("p", style); if (prefix && index === 0) node.append(el("strong", "why-label", prefix + " ")); inlineText(node, text); parent.append(node); }); } function makeTabs(section, date) { const container = $("#sections"); if (!container.children.length) { for (const [id, name] of categories) { const a = el("a", "", name); a.dataset.section = id; container.append(a); } } for (const link of container.children) { link.href = pageUrl(link.dataset.section, date); if (link.dataset.section === section) link.setAttribute("aria-current", "page"); else link.removeAttribute("aria-current"); } const selected = container.querySelector("[aria-current]"); const box = container.getBoundingClientRect(); const linkBox = selected.getBoundingClientRect(); if ( container.scrollWidth > container.clientWidth && (linkBox.left < box.left + 15 || linkBox.right > box.right - 15) ) container.scrollBy({ left: linkBox.left - (box.left + (box.width - linkBox.width) / 2), behavior: "instant", }); } function graphic(story, sectionId) { const facts = (story.facts || []).filter( (value) => typeof value === "string" && value.trim(), ); if (!facts.length) return null; const panel = el("div", "fact-graphic"); panel.dataset.section = sectionId; panel.append( el("span", "graphic-origin", story.source || categories.get(sectionId)), ); const lines = el("div", "graphic-facts"); for (const fact of facts.slice(0, 3)) { const line = el("span"); inlineText(line, fact); lines.append(line); } panel.append(lines); return panel; } function credit(image) { if (!image.credit) return null; const label = image.credit.replace( /^Графика редакции по (?:данным|материалу)\s+/i, "Графика редакции · ", ); const caption = el("figcaption", "image-credit"); const link = safeUrl(image.sourceUrl); caption.append( link ? externalLink(link, label) : document.createTextNode(label), ); const license = safeUrl(image.licenseUrl, true); if (license) caption.append( document.createTextNode(" · "), externalLink(license, "Лицензия"), ); return caption; } function openImage(image) { const modal = $("#lightbox"); const box = modal.querySelector(".full-image"); const figure = el("figure"); const img = el("img"); img.src = safeUrl(image.src, true); img.alt = image.alt || ""; figure.append(img); const c = credit(image); if (c) figure.append(c); box.replaceChildren(figure); setOriginalSize(false); modal.showModal(); } function setOriginalSize(zoomed) { const modal = $("#lightbox"); modal.classList.toggle("zoomed", zoomed); const button = modal.querySelector(".zoom-original"); button.setAttribute("aria-pressed", String(zoomed)); button.textContent = zoomed ? "Вписать в экран" : "В полном размере"; } $("#lightbox .zoom-original").addEventListener("click", () => { setOriginalSize(!$("#lightbox").classList.contains("zoomed")); }); function makeMedia(story, sectionId, lead) { const figure = el("figure", "story-media"); const asset = story.image || {}; const imageUrl = safeUrl(asset.src, true); if (!imageUrl) { const visual = graphic(story, sectionId); if (!visual) return null; figure.append(visual); return figure; } const button = el("button", "media-button"); button.type = "button"; button.setAttribute("aria-label", "Увеличить изображение — " + story.title); button.addEventListener("click", () => openImage(asset)); const img = el("img"); img.alt = asset.alt || ""; img.decoding = "async"; img.loading = lead ? "eager" : "lazy"; if (lead) img.fetchPriority = "high"; img.addEventListener( "error", () => { const visual = graphic(story, sectionId); if (visual) figure.replaceChildren(visual); else figure.remove(); }, { once: true }, ); img.src = imageUrl; button.append(img); figure.append(button); const c = credit(asset); if (c) figure.append(c); return figure; } function makeStory(story, sectionId, lead) { const article = el("article", lead ? "story lead" : "story"); if (story.id) article.id = "story-" + story.id; const copy = el("div", "story-copy"); const meta = el("div", "meta"); if (lead) { meta.append(el("span", "lead-label", "Главный материал")); if (asDate(story.date)) meta.append(el("span", "divider")); } if (asDate(story.date)) { const time = el( "time", "", story.dateLabel ? `${story.dateLabel} · ${humanDate(story.date)}` : humanDate(story.date), ); time.dateTime = story.date; meta.append(time); } copy.append(meta, el("h3", "", story.title)); const body = el("div", "body-text"); paragraphs(body, story.summary, "summary"); paragraphs( body, story.why, "why", /^почему это важно/i.test(story.why || "") ? "" : "Почему это важно.", ); const facts = Array.isArray(story.facts) ? story.facts.filter((f) => typeof f === "string") : []; const extraFacts = story.image?.src ? facts : facts.slice(lead ? 3 : 2); if (extraFacts.length) { const list = el("ul", "story-facts"); for (const fact of extraFacts) { const item = el("li"); inlineText(item, fact); list.append(item); } body.append(list); } const url = safeUrl(story.url); if (url) { const link = externalLink( url, story.source || "Первоисточник", "source-link", ); link.setAttribute( "aria-label", `Первоисточник: ${story.source || story.title}`, ); const arrow = el("span", "", "↗"); arrow.setAttribute("aria-hidden", "true"); link.append(arrow); body.append(link); } const extraSources = (story.auxiliarySources || []).filter( (source) => safeUrl(source.url) && source.label, ); if (extraSources.length) { const links = el("div", "extra-sources"); for (const source of extraSources) links.append(externalLink(safeUrl(source.url), source.label)); body.append(links); } copy.append(body); article.append(copy); const figure = makeMedia(story, sectionId, lead); if (figure) article.append(figure); else article.classList.add("without-media"); return article; } function renderArchive() { const list = $("#archive .archive-list"); const selected = state.edition?.date; const fragment = document.createDocumentFragment(); for (const date of [...new Set(state.manifest.dates || [])] .filter((s) => datePattern.test(s)) .sort() .reverse()) { const link = el("a", "", humanDate(date, true)); link.href = pageUrl(route().section, date); link.dataset.date = date; const detail = el("span", "", weekday.format(asDate(date))); link.append(detail); if (date === selected) link.setAttribute("aria-current", "date"); fragment.append(link); } list.replaceChildren(fragment); $("#archive-open").disabled = !list.childElementCount; } function showEdition(data, sectionId) { state.edition = data; makeTabs(sectionId, route().date); $("#edition-date").textContent = editionLabel(data.date); const update = asDate(data.publishedAt); const published = $("#update-time"); published.replaceChildren(); if (update) published.append( el("span", "updated-prefix", "Обновлено в "), document.createTextNode(`${clock.format(update)} МСК`), ); if (update) { published.title = `Опубликовано ${editionLabel(data.publishedAt).toLowerCase()} в ${clock.format(update)} МСК`; published.setAttribute("aria-label", published.title); } const section = (data.sections || []).find((s) => s.id === sectionId); const stories = section?.stories || []; const pane = $("#stories"); const title = categories.get(sectionId); document.title = `${title} · ${humanDate(data.date)} — ${brandName}`; $("#section-title").textContent = title; $("#story-count").textContent = plural(stories.length); $("#edition-warning").replaceChildren(); const issueWarning = state.manifest.latest === data.date ? state.manifest.warning : ""; if (issueWarning) $("#edition-warning").append(el("p", "notice", issueWarning)); const fragment = document.createDocumentFragment(); if (section?.notice || section?.status === "partial") fragment.append( el( "p", "notice", section.notice || "Часть источников обновить не удалось.", ), ); if (stories.length) { fragment.append(makeStory(stories[0], sectionId, true)); if (stories.length > 1) { const other = el("div", "support"); other.dataset.count = String(stories.length - 1); for (const story of stories.slice(1)) other.append(makeStory(story, sectionId, false)); fragment.append(other); } } else { const unavailable = !section || section.status === "error"; if (!unavailable || !section?.notice) fragment.append( el( "p", "empty", unavailable ? "Данные обновить не удалось." : "Новых материалов сегодня нет", ), ); } pane.replaceChildren(fragment); pane.setAttribute("aria-busy", "false"); if (!reducedMotion.matches) { pane.classList.remove("reveal"); void pane.offsetWidth; pane.classList.add("reveal"); } renderArchive(); } function showFailure(message) { state.edition = null; $("#section-title").textContent = "Выпуск недоступен"; $("#story-count").textContent = ""; $("#edition-warning").replaceChildren(); $("#update-time").textContent = ""; $("#edition-date").textContent = "Утренняя подборка"; const pane = $("#stories"); pane.setAttribute("aria-busy", "false"); const note = el("div", "load-failure"); note.append(el("p", "", message)); const link = el( "a", "source-link", state.manifest ? "Открыть последний выпуск" : "Попробовать ещё раз", ); link.href = state.manifest ? "/" : location.href; note.append(link); pane.replaceChildren(note); } async function getJson(path) { const res = await fetch(path, { cache: "no-cache" }); if (!res.ok) throw Error("HTTP " + res.status); return res.json(); } async function navigate() { const ticket = ++state.request; const { date, section } = route(); makeTabs(section, date); $("#stories").setAttribute("aria-busy", "true"); try { if (!state.manifest) { const manifest = await getJson("/manifest.json"); if (ticket !== state.request) return; state.manifest = manifest; lastManifestCheck = Date.now(); renderArchive(); } const key = date || state.manifest.latest; if (!datePattern.test(key) || !(state.manifest.dates || []).includes(key)) { showFailure("В архиве пока нет выпуска за выбранную дату."); return; } if (!state.cache.has(key)) { const edition = await getJson("/editions/" + key + ".json"); if (edition.date !== key || !Array.isArray(edition.sections)) throw Error("Invalid edition"); state.cache.set(key, edition); } if (ticket === state.request) showEdition(state.cache.get(key), section); } catch { if (ticket === state.request) showFailure( "Не удалось загрузить выпуск. Проверьте подключение и повторите попытку.", ); } } function followInternal(event) { const link = event.target.closest("a"); if ( !link || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey ) return; event.preventDefault(); if ($("#archive").open) $("#archive").close(); if (location.href !== link.href) history.pushState(null, "", link.href); navigate(); if (window.scrollY > $(".edition-header").offsetHeight) $("#main").scrollIntoView({ block: "start", behavior: "instant" }); } $("#sections").addEventListener("click", followInternal); $("#archive .archive-list").addEventListener("click", followInternal); $("#archive-open").addEventListener("click", () => $("#archive").showModal()); $("#back-top").addEventListener("click", () => window.scrollTo({ top: 0, behavior: reducedMotion.matches ? "instant" : "smooth", }), ); for (const dialog of document.querySelectorAll("dialog")) { dialog .querySelector(".close-dialog") .addEventListener("click", () => dialog.close()); dialog.addEventListener("click", (event) => { if (event.target !== dialog) return; const r = dialog.getBoundingClientRect(); if ( event.clientX < r.left || event.clientX > r.right || event.clientY < r.top || event.clientY > r.bottom ) dialog.close(); }); } let lastManifestCheck = 0; async function refreshAfterReturn() { if ( document.visibilityState !== "visible" || !state.manifest || Date.now() - lastManifestCheck < 60000 ) return; lastManifestCheck = Date.now(); try { const manifest = await getJson("/manifest.json"); if (JSON.stringify(manifest) === JSON.stringify(state.manifest)) return; state.manifest = manifest; await navigate(); } catch { // A suspended phone can resume before its network reconnects. Keep the open edition readable. lastManifestCheck = 0; } } document.addEventListener("visibilitychange", refreshAfterReturn); window.addEventListener("pageshow", refreshAfterReturn); window.addEventListener("online", refreshAfterReturn); window.addEventListener("popstate", navigate); navigate();