Files

709 lines
45 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.
(() => {
"use strict";
const qs = (selector, root = document) => root.querySelector(selector);
const qsa = (selector, root = document) => Array.from(root.querySelectorAll(selector));
const clone = (value) => JSON.parse(JSON.stringify(value));
const escapeHTML = (value) => String(value ?? "").replace(/[&<>'"]/g, (char) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", "'": "&#39;", '"': "&quot;"})[char]);
const safeHref = (value) => String(value || "").startsWith("#") ? String(value) : "#top";
const safeRemoteUrl = (value, kind = "link") => {
const source = String(value || "").trim();
if (!source) return "";
const lowered = source.toLowerCase();
if (kind === "image" && lowered.startsWith("data:image/")) return source;
if (kind === "video" && lowered.startsWith("data:video/")) return source;
try { const url = new URL(source); return ["http:", "https:"].includes(url.protocol) ? url.href : ""; }
catch (_error) { return ""; }
};
const validateRemoteMediaTree = (value, path = "当前模块") => {
if (Array.isArray(value)) return value.forEach((item, index) => validateRemoteMediaTree(item, path + "[" + index + "]"));
if (!isObject(value)) return;
const media = value.media;
if (media && ["image", "video", "webpage"].includes(media.type)) {
if (["image", "video"].includes(media.type) && !safeRemoteUrl(media.mediaUrl, media.type)) throw new Error(path + ".media.mediaUrl 无效");
if (media.type === "webpage" && !safeRemoteUrl(media.pageUrl)) throw new Error(path + ".media.pageUrl 无效");
if (media.posterUrl && !safeRemoteUrl(media.posterUrl, "image")) throw new Error(path + ".media.posterUrl 无效");
}
Object.entries(value).forEach(([key, item]) => { if (key !== "media") validateRemoteMediaTree(item, path + "." + key); });
};
const MODULES = ["site", "navigation", "specials", "headline", "focus", "features", "channels", "local", "services", "footer"];
const MODULE_META = {
site: ["站点信息", "机构、标识、口号与主题"],
navigation: ["导航", "多语种、主导航、搜索与抽屉"],
specials: ["专集焦点", "报道专集、焦点图与播报"],
headline: ["全媒头条", "主标题、摘要与关联阅读"],
focus: ["要闻聚焦", "分类标签与新闻列"],
features: ["专栏专题", "名专栏、专题与记者工作室"],
channels: ["频道", "网评访谈视频与行业频道"],
local: ["地方联播", "省份切换与地方报道"],
services: ["媒体服务", "媒体矩阵、直播与订阅"],
footer: ["页脚", "机构链接与版权说明"]
};
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
const isCompleteData = (value) => isObject(value) && MODULES.every((name) => isObject(value[name]));
const initialData = JSON.parse(qs("#xinhuaPageData").textContent);
const fingerprint = (() => {
const text = JSON.stringify(initialData);
let hash = 2166136261;
for (let index = 0; index < text.length; index += 1) {
hash ^= text.charCodeAt(index);
hash = Math.imul(hash, 16777619);
}
return (hash >>> 0).toString(16).padStart(8, "0");
})();
const storageKey = "xinhua-page-data-v1:" + fingerprint;
const themeKey = "xinhua-page-theme-v1:" + fingerprint;
const readStorage = (key) => { try { return window.localStorage.getItem(key); } catch (_error) { return null; } };
const writeStorage = (key, value) => { try { window.localStorage.setItem(key, value); return true; } catch (_error) { return false; } };
const removeStorage = (key) => { try { window.localStorage.removeItem(key); } catch (_error) { /* storage is optional */ } };
let pageData = clone(initialData);
try {
const saved = readStorage(storageKey);
const parsed = saved ? JSON.parse(saved) : null;
if (isCompleteData(parsed)) pageData = parsed;
} catch (_error) {
pageData = clone(initialData);
}
const saveData = () => writeStorage(storageKey, JSON.stringify(pageData));
const toast = qs("#toast");
let toastTimer = 0;
const note = (message) => {
const settings = qs("#settingsOverlay");
if (settings && settings.classList.contains("open")) {
const status = qs("#jsonStatus");
status.textContent = message;
status.className = "json-status valid";
return;
}
window.clearTimeout(toastTimer);
toast.textContent = message;
toast.classList.add("show");
toastTimer = window.setTimeout(() => toast.classList.remove("show"), 2200);
};
const sealLabel = () => pageData.site.brandName || "新华社";
document.head.insertAdjacentHTML("beforeend", '<style data-external-media>.visual>img,.visual>video,.visual>iframe,.spot-card img,.spot-card video,.spot-card iframe{width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}.visual>iframe,.spot-card iframe{object-fit:initial}.external-open{position:absolute;right:10px;bottom:10px;z-index:4;padding:7px 11px;color:#fff;background:rgba(0,0,0,.72);text-decoration:none;font-size:12px;font-weight:700}.external-copy{position:absolute;left:10px;right:10px;bottom:10px;z-index:4;padding:9px;color:#fff;background:rgba(0,0,0,.72);text-decoration:none}.external-copy strong,.external-copy span{display:block}.external-copy span{margin-top:3px;font-size:12px}</style>');
const externalMediaMarkup = (media, label) => {
if (!isObject(media)) return "";
if (media.type === "image") {
const source = safeRemoteUrl(media.mediaUrl, "image");
if (!source) return "";
const pageUrl = safeRemoteUrl(media.pageUrl);
return '<img src="' + escapeHTML(source) + '" alt="' + escapeHTML(media.alt || label || "新闻图片") + '" loading="lazy" referrerpolicy="no-referrer"/>' + (pageUrl ? '<a class="external-open" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer">打开来源</a>' : "");
}
if (media.type === "video") {
const source = safeRemoteUrl(media.mediaUrl, "video");
const poster = safeRemoteUrl(media.posterUrl, "image");
return source ? '<video src="' + escapeHTML(source) + '"' + (poster ? ' poster="' + escapeHTML(poster) + '"' : "") + ' controls playsinline preload="metadata" aria-label="' + escapeHTML(media.alt || label || "新闻视频") + '"></video>' : "";
}
if (media.type === "webpage") {
const pageUrl = safeRemoteUrl(media.pageUrl);
if (!pageUrl) return "";
const preview = safeRemoteUrl(media.mediaUrl, "image");
const body = media.embed === true ? '<iframe src="' + escapeHTML(pageUrl) + '" title="' + escapeHTML(media.title || "网页预览") + '" loading="lazy" referrerpolicy="no-referrer" sandbox="allow-forms allow-popups allow-scripts"></iframe>' : (preview ? '<img src="' + escapeHTML(preview) + '" alt="' + escapeHTML(media.alt || media.title || "网页预览图") + '" loading="lazy" referrerpolicy="no-referrer"/>' : "");
return body + '<a class="external-copy" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer"><strong>' + escapeHTML(media.title || label || "打开网页") + '</strong><span>' + escapeHTML(media.description || "新窗口打开") + "</span></a>";
}
return "";
};
const visualSvg = (type, title) => {
if (isObject(type)) {
const external = externalMediaMarkup(type, title);
if (external) return external;
type = "city";
}
let background = "#c6d8df";
let content = '<path d="M0 315 165 160l95 86 135-145 305 232v117H0Z" fill="#5f7e78"/><path d="M25 375h650" stroke="#f4eddb" stroke-width="19"/>';
if (type === "harvest") {
background = "#91bdc7";
content = '<circle cx="565" cy="86" r="50" fill="#ffe3a0"/><path d="M0 305c150-78 350-70 700-4v149H0Z" fill="#7f9048"/><path d="M20 395c177-87 393-83 640-29" stroke="#e5d16c" stroke-width="34" fill="none"/>';
} else if (type === "railway") {
background = "#bdd3da";
content = '<path d="M0 310 140 160l95 82 155-150 310 236v122H0Z" fill="#617b73"/><path d="M30 392c170-58 405-60 640 10" stroke="#ede9da" stroke-width="19" fill="none"/><path d="M225 300h245l76 48H225Z" fill="#edf1ef"/><path d="M256 315h145v15H256Z" fill="#355462"/><path d="m470 300 76 48h-76Z" fill="#c90018"/>';
} else if (type === "satellite" || type === "world") {
background = "#182333";
content = '<circle cx="350" cy="220" r="135" fill="#2f4f71"/><path d="M245 274c42-128 180-187 287-139-58 36-86 80-111 137-31 70-95 75-176 2Z" fill="#5593b3"/><g fill="#fff"><circle cx="90" cy="82" r="4"/><circle cx="590" cy="101" r="4"/></g>';
} else if (type === "culture") {
background = "#e1d4bd";
content = '<rect x="65" y="142" width="210" height="248" fill="#5b554b"/><rect x="345" y="72" width="255" height="318" fill="#756d60"/><g fill="#e8be68"><path d="M102 180h54v62h-54Zm78 0h54v62h-54Zm205-62h63v70h-63Zm92 0h63v70h-63Z"/></g><path d="M0 395h700" stroke="#c90018" stroke-width="12"/>';
} else if (type === "wetland" || type === "green") {
background = "#9fcbd1";
content = '<path d="M0 335c195-60 410-52 700 10v105H0Z" fill="#537969"/><path d="M140 132q31-34 62 0m132-38q31-34 62 0m114 64q31-34 62 0" stroke="#243d45" stroke-width="7" fill="none"/><circle cx="575" cy="91" r="42" fill="#f4d995"/>';
} else if (type === "economy") {
background = "#d9d3c3";
content = '<path d="M80 360h540M130 320l95-95 78 50 132-145 135 90" stroke="#0a4f8a" stroke-width="24" fill="none"/><circle cx="435" cy="130" r="30" fill="#c90018"/>';
} else if (type === "technology") {
background = "#173854";
content = '<g fill="none" stroke="#6ec6df" stroke-width="10"><circle cx="350" cy="225" r="125"/><path d="M175 225h350M350 50v350"/></g><circle cx="350" cy="225" r="47" fill="#c90018"/>';
} else if (type === "commentary") {
background = "#d6e0e2";
content = '<path d="M70 365h560" stroke="#23435a" stroke-width="22"/><path d="M175 345V155h350v190" fill="#627f8a"/><circle cx="350" cy="125" r="72" fill="#c90018"/>';
} else if (type === "interview") {
background = "#173854";
content = '<circle cx="235" cy="185" r="78" fill="#e2cab8"/><path d="M95 430c25-120 78-170 160-170s135 50 160 170" fill="#50748e"/><path d="M420 105h190v28H420Zm0 72h145v28H420Zm0 72h175v28H420Z" fill="#e8eef0"/>';
} else if (type === "video") {
background = "#0b3559";
content = '<circle cx="350" cy="225" r="92" fill="#fff" opacity=".92"/><path d="m325 170 82 55-82 55Z" fill="#c90018"/><path d="M0 430 700 260v190H0Z" fill="#7a1b2c" opacity=".65"/>';
} else if (type === "capital") {
background = "#c6d9df";
content = '<path d="M0 330 190 155l135 120 158-180 217 228v127H0Z" fill="#647f76"/><path d="M0 395c198-72 442-72 700 10" stroke="#f0ecdf" stroke-width="25" fill="none"/>';
} else if (type === "coast" || type === "bay") {
background = "#92c8d5";
content = '<path d="M0 345c130-55 240-42 360-9 135 37 235 25 340-25v139H0Z" fill="#2d6671"/><path d="M245 95v190m0-130h158l45 55-203 15" stroke="#f1f3ed" stroke-width="17" fill="none"/>';
} else if (type === "river") {
background = "#c8d9d1";
content = '<path d="M0 315c165-92 315-78 700-15v150H0Z" fill="#47705a"/><path d="M-20 378c180-65 430-69 750 7" stroke="#b7dce4" stroke-width="42" fill="none"/><g fill="#edf0e7"><rect x="130" y="185" width="75" height="150"/><rect x="290" y="115" width="86" height="220"/><rect x="500" y="210" width="68" height="125"/></g>';
}
return '<svg viewBox="0 0 700 450" preserveAspectRatio="xMidYMid slice" role="img" aria-label="' + escapeHTML(title) + '"><rect width="700" height="450" fill="' + background + '"/>' + content + "</svg>";
};
const iconSvg = (type) => {
if (type === "video") return '<svg viewBox="0 0 24 24"><path d="M4 6h16v12H4Z"/><path d="m9 10 6 4-6 3Z"/></svg>';
if (type === "platform") return '<svg viewBox="0 0 24 24"><path d="M5 5h14v14H5Z"/><path d="M8 9h8M8 13h6"/></svg>';
if (type === "radio") return '<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8"/><path d="M12 8v4l3 2"/></svg>';
return '<svg viewBox="0 0 24 24"><path d="M6 3h12v18H6Z"/><path d="M10 17h4"/></svg>';
};
let themeInitialized = false;
const syncThemeLabel = () => {
const dark = document.body.classList.contains("dark");
qs("#themeLabel").textContent = dark ? "日间" : "夜间";
qs("#theme").setAttribute("aria-label", dark ? "切换日间模式" : "切换夜间模式");
};
const applyInitialTheme = () => {
if (themeInitialized) return;
themeInitialized = true;
const stored = readStorage(themeKey);
const configured = pageData.site.theme;
const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme:dark)").matches;
const dark = stored === "dark" || (!stored && (configured === "dark" || (configured === "auto" && prefersDark)));
document.body.classList.toggle("dark", dark);
syncThemeLabel();
};
const toggleTheme = () => {
const dark = document.body.classList.toggle("dark");
writeStorage(themeKey, dark ? "dark" : "light");
syncThemeLabel();
note(dark ? "夜间模式已开启" : "日间模式已开启");
};
const navMarkup = (items, activeFirst) => (Array.isArray(items) ? items : []).map((item, index) => '<a class="' + (activeFirst && index === 0 ? "active" : "") + '" href="' + safeHref(item.href) + '">' + escapeHTML(item.label) + "</a>").join("");
const renderSite = () => {
const data = pageData.site;
document.title = data.pageTitle || "新华社";
qs('meta[name="description"]').content = data.description || "";
qs("#brandName").textContent = data.brandName || "";
qs("#brandEnglish").textContent = data.brandEnglish || "";
qs("#brandLink").setAttribute("aria-label", (data.brandName || "") + "首页");
qs("#motto").textContent = data.motto || "";
qs("#clientLabel").textContent = data.clientLabel || "";
qs("#footerBrand").textContent = data.brandName || "";
qs("#drawerBrand").textContent = data.brandName || "";
applyInitialTheme();
};
const renderNavigation = () => {
const data = pageData.navigation;
qs("#networkLeft").innerHTML = navMarkup(data.networkLeft, false);
qs("#networkRight").innerHTML = navMarkup(data.networkRight, false);
qs("#primaryNav").innerHTML = navMarkup(data.primary, true);
qs("#drawerLinks").innerHTML = navMarkup(data.drawer, false);
qs("#searchLabel").textContent = data.searchLabel || "";
qs("#search").placeholder = data.searchPlaceholder || "";
qs("#searchButton").textContent = data.searchButton || "";
};
let activeSpot = 0;
const renderSpecials = () => {
const data = pageData.specials;
qs("#seriesTitle").textContent = data.seriesTitle || "";
qs("#seriesEnglish").textContent = data.seriesEnglish || "";
qs("#seriesItems").innerHTML = (data.seriesItems || []).map((item, index) => '<a class="series-item" href="' + safeHref(item.href) + '"><span class="series-no">' + String(index + 1).padStart(2, "0") + "</span><b>" + escapeHTML(item.title) + "</b></a>").join("");
const spots = data.spotlightItems || [];
if (activeSpot >= spots.length) activeSpot = 0;
qs("#spotlight").innerHTML = spots.map((item, index) => '<article class="spot-card' + (index === activeSpot ? " active" : "") + '" data-spot-id="' + escapeHTML(item.id) + '" role="listitem">' + visualSvg(item.media || item.visual, item.title) + (item.tag ? '<span class="spot-type">' + escapeHTML(item.tag) + "</span>" : "") + '<span class="spot-cap">' + escapeHTML(item.title) + '</span><button class="spot-select" type="button" data-spot-index="' + index + '" aria-label="查看' + escapeHTML(item.title) + '"></button></article>').join("");
const selected = spots[activeSpot];
qs("#spotTitle").textContent = selected ? (data.spotlightLabel || "焦点图") + ":" + selected.title : "";
const latest = data.latest || {};
qs("#latestLabel").textContent = latest.label || "";
qs("#latestTitle").textContent = latest.title || "";
qs("#latestTitle").href = safeHref(latest.href);
qs("#latestTime").textContent = latest.time || "";
};
const renderHeadline = () => {
const data = pageData.headline;
qs("#headlineKicker").textContent = data.kicker || "";
qs("#headlineTitle").textContent = data.title || "";
qs("#headlineSummary").textContent = data.summary || "";
qs("#headlineLinks").innerHTML = navMarkup(data.links, false);
};
let activeFocus = "";
const renderFocus = () => {
const data = pageData.focus;
const tabs = data.tabs || [];
if (!tabs.some((tab) => tab.id === activeFocus)) activeFocus = tabs[0]?.id || "";
qs("#focusTitle").textContent = data.title || "";
qs("#focusMore").textContent = data.moreLabel || "";
qs("#focusTabs").innerHTML = tabs.map((tab) => '<button class="' + (tab.id === activeFocus ? "active" : "") + '" data-focus-tab="' + escapeHTML(tab.id) + '" role="tab">' + escapeHTML(tab.label) + "</button>").join("");
const current = tabs.find((tab) => tab.id === activeFocus) || tabs[0] || {columns: []};
qs("#focusGrid").innerHTML = (current.columns || []).map((column) => '<article class="focus-col"><div class="focus-lead"><div class="focus-thumb visual">' + visualSvg(column.media || column.visual, column.leadTitle) + "</div><div><h3>" + escapeHTML(column.leadTitle) + "</h3><p>" + escapeHTML(column.summary) + '</p></div></div><ul class="dense-list">' + (column.links || []).map((title) => '<li><a href="#focus">' + escapeHTML(title) + "</a></li>").join("") + "</ul></article>").join("");
};
const renderFeatures = () => {
const data = pageData.features;
qs("#columnTitle").innerHTML = escapeHTML(data.columnTitle || "").replace("名专栏", "<br>名专栏");
qs("#columnSubtitle").textContent = data.columnSubtitle || "";
qs("#featureTags").innerHTML = (data.tags || []).map((tag, index) => '<button class="' + (index === 0 ? "active" : "") + '">' + escapeHTML(tag) + "</button>").join("");
qs("#featureArticles").innerHTML = (data.articles || []).map((item) => '<a class="named-item" href="#features"><b>' + escapeHTML(item.title) + "</b><span>" + escapeHTML(item.meta) + "</span></a>").join("");
qs("#topicsTitle").textContent = data.topicsTitle || "";
qs("#topicsMore").textContent = data.topicsMoreLabel || "";
qs("#topicGrid").innerHTML = (data.topics || []).map((item, index) => '<a class="topic" href="#topics"><span class="topic-index">' + String(index + 1).padStart(2, "0") + "</span><h3>" + escapeHTML(item.title) + "</h3><p>" + escapeHTML(item.summary) + "</p></a>").join("");
qs("#studiosTitle").textContent = data.studiosTitle || "";
qs("#studiosMore").textContent = data.studiosMoreLabel || "";
qs("#studioGrid").innerHTML = (data.studios || []).map((item) => '<a class="studio" href="#studios"><span class="avatar">' + escapeHTML(item.initial) + "</span><span><b>" + escapeHTML(item.name) + "</b><p>" + escapeHTML(item.bio) + "</p></span></a>").join("");
};
const renderChannels = () => {
const data = pageData.channels;
qs("#editorialColumns").innerHTML = (data.editorialColumns || []).map((item) => '<article class="column-box"><h2><span>' + escapeHTML(item.accent) + "</span>" + escapeHTML(item.title) + '</h2><div class="column-feature">' + (item.live ? '<button class="visual live-button open-live" aria-label="播放' + escapeHTML(item.feature) + '">' : '<div class="visual">') + visualSvg(item.media || item.visual, item.feature) + (item.live ? "</button>" : "</div>") + "<h3>" + escapeHTML(item.feature) + '</h3></div><ul>' + (item.links || []).map((title) => '<li><a href="#media">' + escapeHTML(title) + "</a></li>").join("") + "</ul></article>").join("");
qs("#industryTitle").textContent = data.industryTitle || "";
qs("#industryMore").textContent = data.industryMoreLabel || "";
qs("#industryGrid").innerHTML = (data.industries || []).map((item) => '<div class="industry"><h3>' + escapeHTML(item.title) + '<a href="#industry">更多</a></h3><ul>' + (item.items || []).map((title) => "<li>" + escapeHTML(title) + "</li>").join("") + "</ul></div>").join("");
};
let activeProvince = "";
const renderLocal = () => {
const data = pageData.local;
const provinces = data.provinces || [];
if (!provinces.some((item) => item.id === activeProvince)) activeProvince = provinces[0]?.id || "";
qs("#localTitle").textContent = data.title || "";
qs("#localMore").textContent = data.moreLabel || "";
qs("#provinceBar").innerHTML = "<b>" + escapeHTML(data.selectorLabel) + "</b>" + provinces.map((item) => '<button class="' + (item.id === activeProvince ? "active" : "") + '" data-province="' + escapeHTML(item.id) + '">' + escapeHTML(item.name) + "</button>").join("");
const province = provinces.find((item) => item.id === activeProvince) || provinces[0];
qs("#localContent").innerHTML = province ? '<article class="local-lead"><div class="visual">' + visualSvg(province.media || province.visual, province.leadTitle) + '</div><div><span class="headline-label">' + escapeHTML(province.name) + "频道</span><h3>" + escapeHTML(province.leadTitle) + "</h3><p>" + escapeHTML(province.summary) + '</p></div></article><div class="local-list">' + (province.links || []).map((title) => '<a href="#local">' + escapeHTML(title) + "</a>").join("") + "</div>" : "";
};
const renderServices = () => {
const data = pageData.services;
qs("#mediaMatrix").innerHTML = '<div class="matrix-intro"><h2>' + escapeHTML(data.matrixTitle) + "</h2><p>" + escapeHTML(data.matrixSubtitle) + "</p></div>" + (data.matrixItems || []).map((item) => '<a class="matrix-item" href="#services"><span class="matrix-icon">' + iconSvg(item.icon) + "</span><span><b>" + escapeHTML(item.title) + "</b><small>" + escapeHTML(item.caption) + "</small></span></a>").join("");
const modal = data.liveModal || {};
qs("#liveTitle").textContent = modal.title || "";
qs("#streamTitle").textContent = modal.streamTitle || "";
qs("#streamSubtitle").textContent = modal.streamSubtitle || "";
qs("#currentProgram").textContent = modal.currentProgram || "";
const newsletter = data.newsletter || {};
qs("#newsletterTitle").textContent = newsletter.title || "";
qs("#newsletterText").textContent = newsletter.text || "";
qs("#email").placeholder = newsletter.placeholder || "";
qs("#newsletterButton").textContent = newsletter.button || "";
};
const renderFooter = () => {
const data = pageData.footer;
qs("#footerLinks").innerHTML = navMarkup(data.links, false);
qs("#copyright").textContent = data.copyright || "";
qs("#legal").textContent = data.legal || "";
};
const renderAll = () => {
renderSite();
renderNavigation();
renderSpecials();
renderHeadline();
renderFocus();
renderFeatures();
renderChannels();
renderLocal();
renderServices();
renderFooter();
bindDynamicInteractions();
};
const liveModal = qs("#liveModal");
let lastFocus = null;
const openLive = () => {
lastFocus = document.activeElement;
liveModal.classList.add("open");
document.body.style.overflow = "hidden";
qs("#liveClose").focus();
};
const closeLive = () => {
liveModal.classList.remove("open");
document.body.style.overflow = "";
if (lastFocus) lastFocus.focus();
};
const drawer = qs("#drawer");
const openMenu = () => {
drawer.classList.add("open");
document.body.style.overflow = "hidden";
qs("#menuClose").focus();
};
const closeMenu = () => {
drawer.classList.remove("open");
document.body.style.overflow = "";
qs("#menuOpen").focus();
};
const bindDynamicInteractions = () => {
qsa("[data-spot-index]").forEach((button) => button.addEventListener("click", () => { activeSpot = Number(button.dataset.spotIndex) || 0; renderSpecials(); bindDynamicInteractions(); }));
qsa("[data-focus-tab]").forEach((button) => button.addEventListener("click", () => { activeFocus = button.dataset.focusTab; renderFocus(); bindDynamicInteractions(); }));
qsa("#featureTags button").forEach((button) => button.addEventListener("click", () => { qsa("#featureTags button").forEach((item) => item.classList.remove("active")); button.classList.add("active"); }));
qsa("[data-province]").forEach((button) => button.addEventListener("click", () => { activeProvince = button.dataset.province; renderLocal(); bindDynamicInteractions(); }));
qsa(".open-live").forEach((button) => button.addEventListener("click", openLive));
qsa("#drawerLinks a").forEach((link) => link.addEventListener("click", closeMenu));
};
qs("#theme").addEventListener("click", toggleTheme);
qs("#searchOpen").addEventListener("click", () => {
const panel = qs("#searchPanel");
panel.classList.toggle("open");
if (panel.classList.contains("open")) window.setTimeout(() => qs("#search").focus(), 20);
});
const collectStrings = (value, output = []) => {
if (typeof value === "string" && !value.startsWith("#")) output.push(value);
else if (Array.isArray(value)) value.forEach((item) => collectStrings(item, output));
else if (isObject(value)) Object.values(value).forEach((item) => collectStrings(item, output));
return output;
};
qs("#searchForm").addEventListener("submit", (event) => {
event.preventDefault();
const raw = qs("#search").value.trim();
const query = raw.toLocaleLowerCase();
const count = query ? collectStrings(pageData).filter((value) => value.toLocaleLowerCase().includes(query)).length : 0;
const status = qs("#searchStatus");
status.classList.add("show");
status.textContent = query ? "找到与“" + raw + "”相关的 " + count + " 条内容" : "请输入搜索关键词";
});
qs("#liveClose").addEventListener("click", closeLive);
liveModal.addEventListener("click", (event) => { if (event.target === liveModal) closeLive(); });
qs("#caption").addEventListener("click", (event) => {
const on = event.currentTarget.textContent.includes("开");
event.currentTarget.textContent = "CC 字幕:" + (on ? "关" : "开");
note(on ? "字幕已关闭" : "字幕已开启");
});
qs("#menuOpen").addEventListener("click", openMenu);
qs("#menuClose").addEventListener("click", closeMenu);
drawer.addEventListener("click", (event) => { if (event.target === drawer) closeMenu(); });
qs("#subForm").addEventListener("submit", (event) => {
event.preventDefault();
const email = qs("#email").value.trim();
qs("#subStatus").textContent = (pageData.services.newsletter.successPrefix || "") + " " + email;
event.currentTarget.reset();
});
const settingsOverlay = qs("#settingsOverlay");
const jsonEditor = qs("#jsonEditor");
const jsonStatus = qs("#jsonStatus");
let activeModule = MODULES[0];
let editorDraft = clone(pageData);
const validateEditor = () => {
try {
const parsed = JSON.parse(jsonEditor.value);
if (!isObject(parsed)) throw new Error("模块必须是 JSON 对象");
validateRemoteMediaTree(parsed);
jsonStatus.textContent = "JSON 有效";
jsonStatus.className = "json-status valid";
return parsed;
} catch (error) {
jsonStatus.textContent = "JSON 无效:" + error.message;
jsonStatus.className = "json-status invalid";
return null;
}
};
const storeActiveDraft = () => {
const parsed = validateEditor();
if (!parsed) return false;
editorDraft[activeModule] = parsed;
return true;
};
const selectModule = (name, force) => {
if (!force && !storeActiveDraft()) return;
activeModule = name;
qsa(".module-tab").forEach((tab) => tab.classList.toggle("active", tab.dataset.module === name));
qs("#editorModuleTitle").textContent = MODULE_META[name][0];
jsonEditor.value = JSON.stringify(editorDraft[name], null, 2);
validateEditor();
};
const renderModuleTabs = () => {
qs("#moduleTabs").innerHTML = "<h3>页面模块</h3>" + MODULES.map((name) => '<button class="module-tab' + (name === activeModule ? " active" : "") + '" data-module="' + name + '"><strong>' + MODULE_META[name][0] + "</strong><span>" + MODULE_META[name][1] + "</span></button>").join("");
qsa(".module-tab").forEach((tab) => tab.addEventListener("click", () => selectModule(tab.dataset.module, false)));
};
const openSettings = () => {
editorDraft = clone(pageData);
activeModule = MODULES[0];
renderModuleTabs();
selectModule(activeModule, true);
settingsOverlay.classList.add("open");
settingsOverlay.setAttribute("aria-hidden", "false");
document.body.classList.add("settings-open");
document.body.style.overflow = "hidden";
window.setTimeout(() => jsonEditor.focus(), 80);
};
const closeSettings = () => {
settingsOverlay.classList.remove("open");
settingsOverlay.setAttribute("aria-hidden", "true");
document.body.classList.remove("settings-open");
document.body.style.overflow = "";
qs("#openSettings").focus();
};
qs("#openSettings").addEventListener("click", openSettings);
qs("#closeSettings").addEventListener("click", closeSettings);
settingsOverlay.addEventListener("click", (event) => { if (event.target === settingsOverlay) closeSettings(); });
jsonEditor.addEventListener("input", validateEditor);
jsonEditor.addEventListener("keydown", (event) => {
if (event.key === "Tab") {
event.preventDefault();
jsonEditor.setRangeText(" ", jsonEditor.selectionStart, jsonEditor.selectionEnd, "end");
validateEditor();
}
});
qs("#applyJson").addEventListener("click", () => {
if (!storeActiveDraft() || !isCompleteData(editorDraft)) {
note("请修正 JSON 后再应用");
return;
}
pageData = clone(editorDraft);
saveData();
renderAll();
note("JSON 已应用到页面");
});
qs("#resetJson").addEventListener("click", () => {
pageData = clone(initialData);
editorDraft = clone(initialData);
removeStorage(storageKey);
removeStorage(themeKey);
themeInitialized = false;
activeSpot = 0;
activeFocus = "";
activeProvince = "";
renderAll();
renderModuleTabs();
selectModule(activeModule, true);
note("已恢复初始 JSON");
});
qs("#copyJson").addEventListener("click", async () => {
if (!storeActiveDraft()) return;
const text = JSON.stringify(editorDraft, null, 2);
try {
if (navigator.clipboard) await navigator.clipboard.writeText(text);
note("完整 JSON 已复制");
} catch (_error) {
jsonEditor.focus();
jsonEditor.select();
note("已选中当前模块,请手动复制");
}
});
qs("#downloadJson").addEventListener("click", () => {
if (!storeActiveDraft()) return;
const blob = new Blob([JSON.stringify(editorDraft, null, 2) + "\n"], {type: "application/json"});
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "xinhua-page-data.json";
link.click();
window.setTimeout(() => URL.revokeObjectURL(link.href), 0);
note("JSON 已下载");
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
if (liveModal.classList.contains("open")) closeLive();
if (drawer.classList.contains("open")) closeMenu();
if (settingsOverlay.classList.contains("open")) closeSettings();
}
});
renderAll();
function installJsonMediaUpload(){
const editor=document.getElementById("jsonEditor"),apply=document.getElementById("applyJson");if(!editor||!apply||document.getElementById("uploadJsonMedia"))return;
const actions=apply.parentElement,button=document.createElement("button"),input=document.createElement("input"),reference=actions.querySelector("#downloadJson,#copyJson,#validateJson,#resetJson");button.type="button";button.id="uploadJsonMedia";button.className=reference?reference.className:apply.className;button.textContent="上传图片/视频";button.title="先把光标放进要替换的内容对象,再选择图片或视频";input.type="file";input.accept="image/*,video/*";input.hidden=true;actions.insertBefore(button,apply);actions.appendChild(input);
const report=(message)=>{const status=document.getElementById("settingsStatus")||document.getElementById("jsonError")||document.getElementById("jsonStatus");if(status)status.textContent=message};
const findTarget=(text,cursor)=>{const stack=[],matches=[];let quoted=false,escaped=false;for(let index=0;index<text.length;index+=1){const char=text[index];if(quoted){if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char==='"')quoted=false;continue}if(char==='"'){quoted=true;continue}if(char==="{")stack.push(index);else if(char==="}"){const start=stack.pop();if(start===undefined||cursor<start||cursor>index+1)continue;try{const value=JSON.parse(text.slice(start,index+1)),own=(key)=>Object.prototype.hasOwnProperty.call(value,key);if(value&&!Array.isArray(value)&&(own("media")||own("visual")||(own("id")&&(own("text")||own("title"))&&(own("author")||own("channel")||own("user")))))matches.push({start,end:index+1,value})}catch(_error){/* full validator handles malformed JSON */}}}return matches.sort((left,right)=>(left.end-left.start)-(right.end-right.start))[0]||null};
button.addEventListener("click",()=>{input.value="";report("请选择图片或视频;文件会写入光标所在内容对象的 media 字段。");input.click()});
input.addEventListener("change",()=>{const file=input.files&&input.files[0];if(!file)return;const type=file.type.startsWith("image/")?"image":file.type.startsWith("video/")?"video":"";if(!type){report("仅支持图片或视频文件。");return}const target=findTarget(editor.value,editor.selectionStart);if(!target){report("请先把光标放进带 visual/media 的内容对象,或带 id 的帖子/视频对象内。");return}const reader=new FileReader();reader.onerror=()=>report("文件读取失败,请重新选择。");reader.onload=()=>{const previous=target.value.media&&typeof target.value.media==="object"?target.value.media:{},media={type,mediaUrl:String(reader.result)};for(const key of ["alt","label","caption","pageUrl"])if(typeof previous[key]==="string")media[key]=previous[key];if(!media.alt)media.alt=type==="image"?"用户上传的图片":"用户上传的视频";target.value.media=media;const lineStart=editor.value.lastIndexOf("\n",target.start-1)+1,indent=(editor.value.slice(lineStart,target.start).match(/^\s*/)||[""])[0],replacement=JSON.stringify(target.value,null,2).split("\n").map((line,index)=>index?indent+line:line).join("\n");editor.value=editor.value.slice(0,target.start)+replacement+editor.value.slice(target.end);editor.dispatchEvent(new Event("input",{bubbles:true}));const mediaIndex=replacement.indexOf('"media"');editor.focus();editor.setSelectionRange(target.start+Math.max(mediaIndex,0),target.start+Math.max(mediaIndex,0));report(`已把 ${file.name} 写入 JSON,请点击“应用并渲染”。${file.size>2*1024*1024?" 文件较大,建议同时下载 JSON 保存。":""}`)};reader.readAsDataURL(file)});
}
installJsonMediaUpload();
function installInlineMediaReplace() {
if (document.getElementById("dfInlineMediaInput")) return;
const visualHostSelector = ".post-media,.video-visual,.thumbnail-visual,.short-thumb,.watch-visual,.thread-media,.visual,.lead-visual,.mini-visual,.compact-media,.card-art,.story-visual,.art,.video-art,.media-art,.player-stage,.thumbnail,.thumb,.list-thumb,.focus-thumb,.spot-card,.involve-bg,.hero-art,#heroArt,#adminArt";
const getRootData = () => {
if (typeof pageData !== "undefined") return pageData;
if (typeof data !== "undefined") return data;
return null;
};
const input = document.createElement("input");
input.id = "dfInlineMediaInput";
input.type = "file";
input.hidden = true;
document.body.appendChild(input);
const style = document.createElement("style");
style.dataset.dfInlineMediaReplace = "true";
style.textContent = ".df-inline-media-host{position:relative!important}.df-inline-media-button{position:absolute;z-index:40;top:10px;right:10px;width:40px;height:40px;padding:0;border:1px solid rgba(255,255,255,.55);border-radius:50%;display:grid;place-items:center;color:#fff;background:rgba(8,15,28,.78);box-shadow:0 8px 24px rgba(0,0,0,.28);backdrop-filter:blur(8px);cursor:pointer;opacity:0;transform:translateY(-4px);transition:opacity .16s,transform .16s,background .16s}.df-inline-media-button:hover{background:rgba(20,110,240,.92)}.df-inline-media-button svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}.df-inline-media-host:hover>.df-inline-media-button,.df-inline-media-host:focus-within>.df-inline-media-button,.df-inline-media-button:focus-visible{opacity:1;transform:none}@media(hover:none){.df-inline-media-button{opacity:1;transform:none}}.df-inline-media-toast{position:fixed;z-index:2147483647;left:50%;bottom:28px;max-width:min(88vw,520px);padding:10px 14px;border-radius:10px;color:#fff;background:rgba(15,23,42,.94);box-shadow:0 12px 32px rgba(0,0,0,.28);font:600 13px/1.45 system-ui,sans-serif;transform:translateX(-50%)}";
document.head.appendChild(style);
const notify = (message) => {
if (typeof showToast === "function") { showToast(message); return; }
if (typeof toast === "function") { toast(message); return; }
let notice = document.getElementById("dfInlineMediaToast");
if (!notice) {
notice = document.createElement("div");
notice.id = "dfInlineMediaToast";
notice.className = "df-inline-media-toast";
document.body.appendChild(notice);
}
notice.textContent = message;
window.clearTimeout(notice._timer);
notice._timer = window.setTimeout(() => notice.remove(), 2600);
};
const sameSource = (value, source, absolute) => {
if (typeof value !== "string") return false;
if (value === source || value === absolute) return true;
try { return new URL(value, location.href).href === absolute; } catch (_error) { return false; }
};
const findMatches = (source, absolute) => {
const matches = [];
const stack = [];
const visit = (value) => {
if (Array.isArray(value)) { value.forEach(visit); return; }
if (!value || typeof value !== "object") return;
stack.push(value);
Object.entries(value).forEach(([key, item]) => {
if ((key === "mediaUrl" || key === "posterUrl") && sameSource(item, source, absolute)) {
const ancestors = stack.slice(0, -1).reverse();
const owner = ancestors.find((candidate) => candidate && typeof candidate === "object" && !Array.isArray(candidate) && ("id" in candidate || "title" in candidate || "text" in candidate || "name" in candidate || "author" in candidate)) || ancestors[0] || value;
matches.push({ owner, previous: value, key });
}
if (item && typeof item === "object") visit(item);
});
stack.pop();
};
visit(getRootData());
return matches;
};
const visualOwners = () => {
const owners = [];
const seen = new Set();
const visit = (value) => {
if (Array.isArray(value)) { value.forEach(visit); return; }
if (!value || typeof value !== "object") return;
const hasVisual = Object.prototype.hasOwnProperty.call(value, "visual") || (value.media && typeof value.media === "object");
const hasIdentity = ["id", "title", "text", "leadTitle", "feature", "name", "author"].some((key) => typeof value[key] === "string" && value[key].trim());
if (hasVisual && hasIdentity && !seen.has(value)) { seen.add(value); owners.push(value); }
Object.values(value).forEach((item) => { if (item && typeof item === "object") visit(item); });
};
visit(getRootData());
return owners;
};
const domIdentifiers = (element) => {
const values = new Set();
let cursor = element;
for (let depth = 0; cursor && cursor !== document.body && depth < 8; depth += 1, cursor = cursor.parentElement) {
Object.values(cursor.dataset || {}).forEach((value) => { if (value) values.add(String(value)); });
}
return values;
};
const chooseVisualTarget = (element) => {
const identifiers = domIdentifiers(element);
const context = element.closest("article,button,[data-post-id],[data-video-id],[data-short-id],.post,.video-card,.news-card,.story-card,.lead-story,.hero") || element.parentElement || element;
const contextText = String(context.textContent || "").replace(/\s+/g, " ").trim();
const visualNode = element.closest("[data-visual]") || element.querySelector && element.querySelector("[data-visual]");
const visualValue = visualNode && visualNode.dataset ? visualNode.dataset.visual : "";
let best = null;
let bestScore = 0;
visualOwners().forEach((owner) => {
let score = 0;
Object.entries(owner).forEach(([key, value]) => {
if (/id$/i.test(key) && identifiers.has(String(value))) score += 100;
});
["title", "text", "leadTitle", "feature", "visualLabel", "label", "author", "name", "summary"].forEach((key) => {
const value = typeof owner[key] === "string" ? owner[key].trim() : "";
if (value.length >= 2 && contextText.includes(value)) score += Math.min(40, value.length);
});
if (visualValue && owner.visual === visualValue) score += 20;
if (score > bestScore) { best = owner; bestScore = score; }
});
if (!best || bestScore <= 0) return null;
return { owner: best, previous: best.media && typeof best.media === "object" ? best.media : { type: "image" }, key: "mediaUrl" };
};
const chooseTarget = (element) => {
const source = element.getAttribute("src") || "";
const absolute = element.currentSrc || element.src || source;
const matches = findMatches(source, absolute);
if (!matches.length) return null;
const identifiers = domIdentifiers(element);
return matches.find(({ owner }) => Object.entries(owner).some(([key, value]) => /id$/i.test(key) && identifiers.has(String(value)))) || matches[0];
};
const persist = () => {
const root = getRootData();
if (typeof saveData === "function") return saveData();
if (typeof writeStorage === "function" && typeof storageKey !== "undefined") return writeStorage(storageKey, JSON.stringify(root));
if (typeof writeStorage === "function" && typeof dataKey !== "undefined") return writeStorage(dataKey, JSON.stringify(root));
return false;
};
let active = null;
const attachButton = (host, target) => {
if (!host || !target || host.querySelector(":scope > .df-inline-media-button")) return;
host.classList.add("df-inline-media-host");
const button = document.createElement("button");
button.type = "button";
button.className = "df-inline-media-button";
button.setAttribute("aria-label", "替换图片或视频");
button.title = "上传图片或视频并替换";
button.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 16V4m0 0L7.5 8.5M12 4l4.5 4.5"/><path d="M5 14v4a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4"/></svg>';
button.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
active = { ...target };
input.accept = "image/*,video/*";
input.value = "";
input.click();
});
host.appendChild(button);
};
const decorateBuiltInVisuals = () => {
document.querySelectorAll(visualHostSelector).forEach((host) => {
if (host.querySelector("img[src],video[src],iframe[src],:scope > .df-inline-media-button")) return;
if (!host.querySelector("svg") && !host.dataset.visual) return;
const target = chooseVisualTarget(host);
if (!target) return;
attachButton(host, target);
});
};
const decorate = () => {
decorateBuiltInVisuals();
document.querySelectorAll("img[src],video[src]").forEach((media) => {
if (media.dataset.dfInlineMediaReady === "true") return;
const target = chooseTarget(media);
if (!target) return;
const host = media.closest(visualHostSelector) || media.parentElement;
if (!host) return;
media.dataset.dfInlineMediaReady = "true";
attachButton(host, target);
});
};
input.addEventListener("change", () => {
const file = input.files && input.files[0];
if (!file || !active) return;
const uploadedType = file.type.startsWith("image/") ? "image" : file.type.startsWith("video/") ? "video" : "";
if (!uploadedType) {
notify("请选择图片或视频文件。");
return;
}
const reader = new FileReader();
reader.onerror = () => notify("文件读取失败,请重新选择。");
reader.onload = () => {
const next = { ...(active.previous || {}) };
const result = String(reader.result);
next.type = uploadedType;
next.mediaUrl = result;
delete next.posterUrl;
if (!next.alt) next.alt = uploadedType === "video" ? "用户上传的视频" : "用户上传的图片";
active.owner.media = next;
const stored = persist();
renderAll();
notify(stored === false ? "媒体已替换;浏览器未能缓存,请下载 JSON 留存。" : "媒体已替换并写入页面 JSON。");
active = null;
};
reader.readAsDataURL(file);
});
let queued = false;
const queueDecorate = () => {
if (queued) return;
queued = true;
requestAnimationFrame(() => { queued = false; decorate(); });
};
new MutationObserver(queueDecorate).observe(document.body, { childList: true, subtree: true });
decorate();
}
installInlineMediaReplace();
})();