520 lines
42 KiB
JavaScript
520 lines
42 KiB
JavaScript
(() => {
|
||
"use strict";
|
||
|
||
const MODULES = ["site", "navigation", "ticker", "lead", "pulse", "regions", "opinion", "sections", "media", "footer"];
|
||
const MODULE_META = {
|
||
site: "站点信息",
|
||
navigation: "页面导航",
|
||
ticker: "突发快讯",
|
||
lead: "头条新闻",
|
||
pulse: "经济脉搏",
|
||
regions: "地区新闻",
|
||
opinion: "评论观点",
|
||
sections: "商业体育",
|
||
media: "视频与数字报",
|
||
footer: "页面页脚"
|
||
};
|
||
const node = (id) => document.getElementById(id);
|
||
const initialText = node("manilaTimesPageData").textContent;
|
||
const initialData = JSON.parse(initialText);
|
||
const clone = (value) => JSON.parse(JSON.stringify(value));
|
||
const fingerprint = (() => {
|
||
let hash = 2166136261;
|
||
for (let index = 0; index < initialText.length; index += 1) {
|
||
hash ^= initialText.charCodeAt(index);
|
||
hash = Math.imul(hash, 16777619);
|
||
}
|
||
return (hash >>> 0).toString(36);
|
||
})();
|
||
const dataKey = "manila-times-page-data-v1:" + fingerprint;
|
||
const themeKey = "manila-times-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); return true; } catch (_error) { return false; }
|
||
};
|
||
const saved = readStorage(dataKey);
|
||
let data = initialData;
|
||
if (saved) {
|
||
try { data = JSON.parse(saved); } catch (_error) { data = initialData; }
|
||
}
|
||
let currentModule = MODULES[0];
|
||
let activeFeed = "latest";
|
||
let activeRegion = data.regions.tabs[0]?.id || "";
|
||
let weatherIndex = 0;
|
||
let editionIndex = 0;
|
||
let captionsOn = true;
|
||
const savedStories = new Set();
|
||
|
||
const esc = (value) => String(value ?? "").replace(/[&<>'"]/g, (character) => ({"&":"&","<":"<",">":">","'":"'",'"':"""})[character]);
|
||
const safeHref = (value) => typeof value === "string" && value.startsWith("#") ? value : "#";
|
||
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 linkMarkup = (item) => `<a href="${esc(safeHref(item.href))}">${esc(item.label)}</a>`;
|
||
const setText = (id, value) => { const element = node(id); if (element) element.textContent = value ?? ""; };
|
||
const setLink = (id, item) => { const element = node(id); if (!element) return; element.textContent = item.label ?? ""; element.href = safeHref(item.href); };
|
||
const allText = (value, output = []) => {
|
||
if (Array.isArray(value)) value.forEach((item) => allText(item, output));
|
||
else if (value && typeof value === "object") Object.values(value).forEach((item) => allText(item, output));
|
||
else if (typeof value === "string") output.push(value);
|
||
return output;
|
||
};
|
||
document.head.insertAdjacentHTML("beforeend", '<style data-external-media>[data-visual]>img,[data-visual]>video,[data-visual]>iframe{position:absolute;inset:0;z-index:1;width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}[data-visual]>iframe{object-fit:initial}[data-visual].has-external-media::before,[data-visual].has-external-media::after{display:none!important}[data-visual].has-external-media>.duration{z-index:3}.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 externalMedia = (media, label) => {
|
||
if (!media || typeof media !== "object") return "";
|
||
if (media.type === "image") { const source=safeRemoteUrl(media.mediaUrl,"image"),page=safeRemoteUrl(media.pageUrl); return source ? `<img src="${esc(source)}" alt="${esc(media.alt||label||"新闻图片")}" loading="lazy" referrerpolicy="no-referrer">${page?`<a class="external-open" href="${esc(page)}" target="_blank" rel="noopener noreferrer">打开来源</a>`:""}` : ""; }
|
||
if (media.type === "video") { const source=safeRemoteUrl(media.mediaUrl,"video"),poster=safeRemoteUrl(media.posterUrl,"image"); return source ? `<video src="${esc(source)}"${poster?` poster="${esc(poster)}"`:""} controls playsinline preload="metadata" aria-label="${esc(media.alt||label||"新闻视频")}"></video>` : ""; }
|
||
if (media.type === "webpage") { const page=safeRemoteUrl(media.pageUrl),preview=safeRemoteUrl(media.mediaUrl,"image"); if(!page)return ""; const body=media.embed===true?`<iframe src="${esc(page)}" title="${esc(media.title||"网页预览")}" loading="lazy" referrerpolicy="no-referrer" sandbox="allow-forms allow-popups allow-scripts"></iframe>`:(preview?`<img src="${esc(preview)}" alt="${esc(media.alt||media.title||"网页预览图")}" loading="lazy" referrerpolicy="no-referrer">`:""); return `${body}<a class="external-copy" href="${esc(page)}" target="_blank" rel="noopener noreferrer"><strong>${esc(media.title||label||"打开网页")}</strong><span>${esc(media.description||"新窗口打开")}</span></a>`; }
|
||
return "";
|
||
};
|
||
const visual = (kind, className = "story-visual", media = null, extra = "", mediaPath = "") => {
|
||
const mediaMarkup = externalMedia(media, media?.title);
|
||
const classes = `${className}${mediaMarkup ? " has-external-media" : ""}`;
|
||
const pathAttribute = mediaPath ? ` data-media-path="${esc(mediaPath)}"` : "";
|
||
return `<div class="${classes}" data-visual="${esc(kind)}"${pathAttribute} aria-hidden="true">${mediaMarkup}${extra}</div>`;
|
||
};
|
||
|
||
function renderChrome() {
|
||
document.documentElement.lang = data.site.language;
|
||
document.title = data.site.pageTitle;
|
||
document.querySelector('meta[name="description"]')?.setAttribute("content", data.site.description);
|
||
setText("skipLink", data.site.skipLabel);
|
||
setText("brandKicker", data.site.kicker); setText("brandPrefix", data.site.brandPrefix); setText("brandAccent", data.site.brandAccent); setText("brandTagline", data.site.tagline);
|
||
setText("dateLabel", data.site.dateLabel); setText("editionLabel", data.site.editionLabel); setText("menuLabel", data.navigation.menuLabel); setText("searchLabel", data.navigation.searchLabel);
|
||
node("utilityLeft").innerHTML = data.navigation.utilityLeft.map(linkMarkup).join("");
|
||
node("utilityRight").innerHTML = data.navigation.utilityRight.map(linkMarkup).join("") + `<button class="nav-action" id="themeToggle" type="button"></button>`;
|
||
node("primaryLinks").innerHTML = data.navigation.primary.map(linkMarkup).join("");
|
||
setText("tickerLabel", data.ticker.label); setLink("tickerText", {label:data.ticker.text,href:data.ticker.href}); setText("tickerTime", data.ticker.time);
|
||
const storedTheme = readStorage(themeKey);
|
||
const initialTheme = storedTheme || (data.site.theme === "auto" ? (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light") : data.site.theme);
|
||
applyTheme(initialTheme);
|
||
node("themeToggle").addEventListener("click", () => applyTheme(document.body.classList.contains("night") ? "light" : "dark", true));
|
||
setText("drawerBrand", `${data.site.brandPrefix} ${data.site.brandAccent}`); setText("searchBrand", `${data.site.brandPrefix} ${data.site.brandAccent}`);
|
||
setText("drawerEyebrow", data.navigation.drawer.eyebrow); setText("drawerTitle", data.navigation.drawer.title); setText("drawerText", data.navigation.drawer.text); setLink("drawerCta", {label:data.navigation.drawer.ctaLabel,href:data.navigation.drawer.ctaHref});
|
||
node("drawerLinks").innerHTML = data.navigation.primary.map(linkMarkup).join("");
|
||
setText("searchTitle", data.navigation.search.title); node("searchInput").placeholder = data.navigation.search.placeholder;
|
||
setText("footerBrand", `${data.site.brandPrefix} ${data.site.brandAccent}`);
|
||
renderWeather();
|
||
}
|
||
|
||
function applyTheme(theme, persist = false) {
|
||
const dark = theme === "dark";
|
||
document.body.classList.toggle("night", dark);
|
||
const button = node("themeToggle");
|
||
if (button) button.textContent = dark ? `☀ ${data.navigation.themeLightLabel}` : `◐ ${data.navigation.themeDarkLabel}`;
|
||
if (persist) writeStorage(themeKey, dark ? "dark" : "light");
|
||
}
|
||
|
||
function renderWeather() {
|
||
const items = data.site.weather;
|
||
if (!items.length) return;
|
||
weatherIndex %= items.length;
|
||
const weather = items[weatherIndex];
|
||
setText("weatherCity", weather.city); setText("weatherTemp", weather.temp); setText("weatherNote", weather.condition);
|
||
}
|
||
|
||
function saveButton(id) {
|
||
const saved = savedStories.has(id);
|
||
return `<button class="save-btn${saved ? " saved" : ""}" data-save="${esc(id)}" aria-label="${saved ? "取消收藏" : "收藏新闻"}">${saved ? "✓" : "+"}</button>`;
|
||
}
|
||
|
||
function renderLead() {
|
||
setText("datelineLeft", data.lead.datelineLeft); setText("datelineRight", data.lead.datelineRight);
|
||
const story = data.lead.main;
|
||
node("leadMain").innerHTML = `${saveButton(story.id)}<div class="kicker">${esc(story.kicker)}</div><h1 class="lead-title">${esc(story.title)}</h1><p class="summary">${esc(story.summary)}</p><div class="byline">${esc(story.byline)} · ${esc(story.time)}</div>${visual(story.visual,"story-visual",story.media,"","lead.main")}`;
|
||
node("sideStories").innerHTML = data.lead.sideStories.map((item, index) => `<article class="side-story">${saveButton(item.id)}${visual(item.visual,"story-visual",item.media,"",`lead.sideStories.${index}`)}<div class="kicker">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3><p class="summary">${esc(item.summary)}</p><div class="byline">${esc(item.byline)} · ${esc(item.time)}</div></article>`).join("");
|
||
if (!data.lead.feeds.some((feed) => feed.id === activeFeed)) activeFeed = data.lead.feeds[0]?.id;
|
||
node("feedTabs").innerHTML = data.lead.feeds.map((feed) => `<button class="feed-tab${feed.id === activeFeed ? " active" : ""}" data-feed="${esc(feed.id)}">${esc(feed.label)}</button>`).join("");
|
||
const feed = data.lead.feeds.find((item) => item.id === activeFeed) || data.lead.feeds[0];
|
||
node("feedItems").innerHTML = feed.items.map((item) => `<li class="feed-item"><span class="feed-time">${esc(item.time)}</span><span>${esc(item.title)}</span></li>`).join("");
|
||
}
|
||
|
||
function renderPulse() {
|
||
setText("pulseLabel", data.pulse.label); setText("pulseTitle", data.pulse.title);
|
||
node("pulseItems").innerHTML = data.pulse.items.map((item) => `<div class="pulse-item"><div class="pulse-label">${esc(item.label)}</div><div class="pulse-value">${esc(item.value)}</div><div class="direction-${esc(item.direction)}">${esc(item.change)}</div></div>`).join("");
|
||
}
|
||
|
||
function renderRegions() {
|
||
setText("regionsEyebrow", data.regions.eyebrow); setText("regionsTitle", data.regions.title); setLink("regionsMore", {label:data.regions.moreLabel,href:data.regions.moreHref});
|
||
if (!data.regions.tabs.some((tab) => tab.id === activeRegion)) activeRegion = data.regions.tabs[0]?.id;
|
||
node("regionTabs").innerHTML = data.regions.tabs.map((tab) => `<button class="region-tab${tab.id === activeRegion ? " active" : ""}" data-region="${esc(tab.id)}">${esc(tab.label)}</button>`).join("");
|
||
const tab = data.regions.tabs.find((item) => item.id === activeRegion) || data.regions.tabs[0];
|
||
const feature = tab.feature;
|
||
const tabIndex = data.regions.tabs.indexOf(tab);
|
||
node("regionContent").innerHTML = `<article class="region-feature"><div class="region-copy"><div class="kicker">${esc(feature.kicker)}</div><h3>${esc(feature.title)}</h3><p class="summary">${esc(feature.summary)}</p></div>${visual(feature.visual,"region-visual",feature.media,"",`regions.tabs.${tabIndex}.feature`)}</article><div class="region-list">${tab.items.map((item) => `<article class="region-story"><div class="region-location">${esc(item.location)}</div><h3>${esc(item.title)}</h3><p>${esc(item.summary)}</p></article>`).join("")}</div>`;
|
||
}
|
||
|
||
function renderOpinion() {
|
||
setText("opinionEyebrow", data.opinion.eyebrow); setText("opinionTitle", data.opinion.title); setText("opinionSummary", data.opinion.summary);
|
||
node("opinionGrid").innerHTML = data.opinion.columns.map((item) => `<article class="opinion-card"><div class="author"><span class="author-initial">${esc(item.initial)}</span><span>${esc(item.name)}</span></div><h3>${esc(item.title)}</h3><p>${esc(item.summary)}</p></article>`).join("");
|
||
}
|
||
|
||
function renderSections() {
|
||
const business = data.sections.business;
|
||
setText("businessEyebrow", business.eyebrow); setText("businessTitle", business.title); setLink("businessMore", {label:business.moreLabel,href:business.moreHref});
|
||
node("businessItems").innerHTML = business.items.map((item, index) => `<article class="story-card">${visual(item.visual,"mini-visual",item.media,"",`sections.business.items.${index}`)}<div><div class="kicker">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3><p class="summary">${esc(item.summary)}</p></div></article>`).join("");
|
||
const sports = data.sections.sports;
|
||
setText("sportsEyebrow", sports.eyebrow); setText("sportsTitle", sports.title); setLink("sportsMore", {label:sports.moreLabel,href:sports.moreHref});
|
||
node("sportsHero").innerHTML = `<div class="kicker">${esc(sports.hero.kicker)}</div><h3>${esc(sports.hero.title)}</h3><p>${esc(sports.hero.summary)}</p>`;
|
||
node("sportsItems").innerHTML = sports.items.map((item, index) => `<article class="story-card">${visual(item.visual,"mini-visual",item.media,"",`sections.sports.items.${index}`)}<div><div class="kicker">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3></div></article>`).join("");
|
||
node("marketBoard").innerHTML = `<h3>${esc(data.sections.market.title)}</h3><div class="market-board">${data.sections.market.items.map((item) => `<div class="market-cell"><span>${esc(item.label)}</span><strong class="direction-${esc(item.direction)}">${esc(item.value)}</strong></div>`).join("")}</div>`;
|
||
}
|
||
|
||
function renderMedia() {
|
||
const watch = data.media.watch;
|
||
setText("watchEyebrow", watch.eyebrow); setText("watchTitle", watch.title); setLink("watchMore", {label:watch.moreLabel,href:watch.moreHref});
|
||
node("videoGrid").innerHTML = watch.videos.map((item, index) => `<button class="video-card" data-video="${esc(item.id)}">${visual(item.visual,"video-visual",item.media,`<span class="duration">${esc(item.duration)}</span>`,`media.watch.videos.${index}`)}<div class="video-copy"><div class="kicker">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3><p>${esc(item.summary)}</p></div></button>`).join("");
|
||
setText("videoModalTitle", watch.modal.title); setText("videoSubtitle", watch.modal.streamSubtitle);
|
||
const edition = data.media.edition;
|
||
setText("editionEyebrow", edition.eyebrow); setText("editionTitle", edition.title); setText("editionSummary", edition.summary); setText("openEdition", edition.openLabel); setLink("editionSubscribe", {label:edition.subscribeLabel,href:edition.subscribeHref}); setText("editionModalTitle", edition.modalTitle);
|
||
const newsletter = data.media.newsletter;
|
||
setText("newsletterEyebrow", newsletter.eyebrow); setText("newsletterTitle", newsletter.title); setText("newsletterText", newsletter.text); node("newsletterEmail").placeholder = newsletter.placeholder; setText("newsletterButton", newsletter.button);
|
||
}
|
||
|
||
function renderFooter() {
|
||
setText("footerDescription", data.footer.description); setText("footerCopyright", data.footer.copyright); setText("footerLegal", data.footer.legal);
|
||
node("footerColumns").innerHTML = data.footer.columns.map((column) => `<div><h3>${esc(column.title)}</h3>${column.links.map(linkMarkup).join("")}</div>`).join("");
|
||
}
|
||
|
||
function renderAll() {
|
||
renderChrome(); renderLead(); renderPulse(); renderRegions(); renderOpinion(); renderSections(); renderMedia(); renderFooter(); bindDynamicControls();
|
||
}
|
||
|
||
function bindDynamicControls() {
|
||
document.querySelectorAll("[data-save]").forEach((button) => button.addEventListener("click", () => { const id = button.dataset.save; savedStories.has(id) ? savedStories.delete(id) : savedStories.add(id); renderLead(); bindDynamicControls(); }));
|
||
document.querySelectorAll("[data-feed]").forEach((button) => button.addEventListener("click", () => { activeFeed = button.dataset.feed; renderLead(); bindDynamicControls(); }));
|
||
document.querySelectorAll("[data-region]").forEach((button) => button.addEventListener("click", () => { activeRegion = button.dataset.region; renderRegions(); bindDynamicControls(); }));
|
||
document.querySelectorAll("[data-video]").forEach((button) => button.addEventListener("click", () => openVideo(button.dataset.video)));
|
||
}
|
||
|
||
function openOverlay(id) {
|
||
const overlay = node(id); overlay.classList.add("open"); overlay.setAttribute("aria-hidden", "false"); document.body.style.overflow = "hidden";
|
||
}
|
||
function closeOverlay(id) {
|
||
const overlay = node(id); overlay.classList.remove("open"); overlay.setAttribute("aria-hidden", "true");
|
||
if (!document.querySelector(".screen-overlay.open,.modal-overlay.open,.settings-overlay.open")) document.body.style.overflow = "";
|
||
}
|
||
function openVideo(id) {
|
||
const item = data.media.watch.videos.find((video) => video.id === id); if (!item) return;
|
||
captionsOn = true; setText("videoPlayingTitle", item.title); setText("videoCaption", item.summary); updateCaption(); openOverlay("videoOverlay");
|
||
}
|
||
function updateCaption() {
|
||
setText("captionToggle", captionsOn ? data.media.watch.modal.captionsOn : data.media.watch.modal.captionsOff);
|
||
node("videoCaption").hidden = !captionsOn;
|
||
}
|
||
function renderEditionPage() {
|
||
const pages = data.media.edition.pages; editionIndex = Math.max(0, Math.min(editionIndex, pages.length - 1)); const page = pages[editionIndex];
|
||
node("editionPage").innerHTML = `<div class="paper-brand">${esc(data.site.brandPrefix)} ${esc(data.site.brandAccent)}</div><div class="kicker">${esc(page.label)} · ${esc(data.media.edition.date)}</div><h2>${esc(page.headline)}</h2><p>${esc(page.text)}</p>`;
|
||
setText("editionPageCount", `${editionIndex + 1} / ${pages.length}`); node("editionPrev").disabled = editionIndex === 0; node("editionNext").disabled = editionIndex === pages.length - 1;
|
||
}
|
||
|
||
function searchStories() {
|
||
const query = node("searchInput").value.trim().toLowerCase();
|
||
const candidates = [];
|
||
const collect = (value) => {
|
||
if (Array.isArray(value)) value.forEach(collect);
|
||
else if (value && typeof value === "object") { if (typeof value.title === "string") candidates.push({title:value.title,kicker:value.kicker || value.location || "Story"}); Object.values(value).forEach(collect); }
|
||
};
|
||
collect({lead:data.lead,regions:data.regions,opinion:data.opinion,sections:data.sections,media:data.media.watch});
|
||
const unique = Array.from(new Map(candidates.map((item) => [item.title,item])).values());
|
||
const results = query ? unique.filter((item) => `${item.title} ${item.kicker}`.toLowerCase().includes(query)) : unique.slice(0,8);
|
||
setText("searchMeta", results.length ? `${results.length} ${data.navigation.search.resultPrefix}` : data.navigation.search.emptyMessage);
|
||
node("searchResults").innerHTML = results.map((item) => `<button class="search-result"><span class="kicker">${esc(item.kicker)}</span><br>${esc(item.title)}</button>`).join("");
|
||
}
|
||
|
||
function validateClientDocument(candidate) {
|
||
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) throw new Error("顶层 JSON 必须是对象。");
|
||
const keys = Object.keys(candidate); const missing = MODULES.filter((name) => !keys.includes(name)); const extra = keys.filter((name) => !MODULES.includes(name));
|
||
if (missing.length) throw new Error(`缺少模块:${missing.join("、")}`); if (extra.length) throw new Error(`存在未知模块:${extra.join("、")}`);
|
||
MODULES.forEach((name) => { if (!candidate[name] || typeof candidate[name] !== "object" || Array.isArray(candidate[name])) throw new Error(`${name} 必须是对象。`); });
|
||
const text = JSON.stringify(candidate).toLowerCase(); if (["<script","<iframe","javascript:"].some((token) => text.includes(token))) throw new Error("不允许使用 HTML 或脚本。");
|
||
const validateMedia=(value,path="当前模块")=>{if(Array.isArray(value))return value.forEach((item,index)=>validateMedia(item,`${path}[${index}]`));if(!value||typeof value!=="object")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")validateMedia(item,`${path}.${key}`)})};validateMedia(candidate);
|
||
if (candidate.site.language !== "zh-CN") throw new Error("site.language 必须是 zh-CN。");
|
||
const technicalKeys = new Set(["id","href","visual","direction","theme","language","type","mediaUrl","posterUrl","pageUrl"]);
|
||
const checkChinese = (value, key = "") => {
|
||
if (Array.isArray(value)) value.forEach((item) => checkChinese(item, key));
|
||
else if (value && typeof value === "object") Object.entries(value).forEach(([childKey,item]) => checkChinese(item, childKey));
|
||
else if (typeof value === "string" && !technicalKeys.has(key) && !key.toLowerCase().endsWith("id") && !key.toLowerCase().endsWith("href") && !key.toLowerCase().endsWith("url")) {
|
||
if (/[A-Za-z]/.test(value) && !/[\u3400-\u9fff]/.test(value)) throw new Error("所有读者可见文案必须使用简体中文。");
|
||
}
|
||
};
|
||
checkChinese(candidate);
|
||
if (!Array.isArray(candidate.regions.tabs) || !candidate.regions.tabs.length) throw new Error("regions.tabs 不能为空。");
|
||
if (!Array.isArray(candidate.media.edition.pages) || !candidate.media.edition.pages.length) throw new Error("media.edition.pages 不能为空。");
|
||
return true;
|
||
}
|
||
|
||
function showModule(name) {
|
||
currentModule = name; node("jsonEditor").value = JSON.stringify(data[name], null, 2); setText("editorModule", MODULE_META[name]); setText("jsonValidity", "JSON 有效");
|
||
node("moduleTabs").querySelectorAll("button").forEach((button) => button.classList.toggle("active", button.dataset.module === name));
|
||
}
|
||
function renderSettingsTabs() {
|
||
node("moduleTabs").innerHTML = MODULES.map((name) => `<button class="module-tab" data-module="${name}">${MODULE_META[name]}</button>`).join("");
|
||
node("moduleTabs").querySelectorAll("button").forEach((button) => button.addEventListener("click", () => showModule(button.dataset.module))); showModule(currentModule);
|
||
}
|
||
function parseEditor() {
|
||
try { const value = JSON.parse(node("jsonEditor").value); if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("当前模块必须是对象。"); setText("jsonValidity", "JSON 有效"); return value; }
|
||
catch (error) { setText("jsonValidity", "JSON 无效"); throw error; }
|
||
}
|
||
function setStatus(message) { setText("settingsStatus", message); }
|
||
async function copyJson() {
|
||
const text = JSON.stringify({...data,[currentModule]:parseEditor()}, null, 2);
|
||
try { await navigator.clipboard.writeText(text); setStatus("完整 JSON 已复制。"); }
|
||
catch (_error) { node("jsonEditor").select(); document.execCommand("copy"); setStatus("已选中当前模块,可手动复制。"); }
|
||
}
|
||
function downloadJson() {
|
||
const candidate = {...data,[currentModule]:parseEditor()}; validateClientDocument(candidate); const blob = new Blob([JSON.stringify(candidate,null,2)+"\n"],{type:"application/json"}); const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href=url; anchor.download="manila-times-page-data.json"; anchor.click(); URL.revokeObjectURL(url); setStatus("JSON 下载文件已生成。");
|
||
}
|
||
function applyEditor() {
|
||
try { const candidate = {...data,[currentModule]:parseEditor()}; validateClientDocument(candidate); data=candidate; writeStorage(dataKey,JSON.stringify(data)); renderAll(); renderSettingsTabs(); setStatus("JSON 已应用并完成渲染。"); }
|
||
catch (error) { setStatus(error.message); setText("jsonValidity","JSON 无效"); }
|
||
}
|
||
|
||
node("weatherButton").addEventListener("click", () => { weatherIndex += 1; renderWeather(); });
|
||
node("openDrawer").addEventListener("click", () => openOverlay("drawerOverlay"));
|
||
node("openSearch").addEventListener("click", () => { openOverlay("searchOverlay"); searchStories(); setTimeout(() => node("searchInput").focus(),0); });
|
||
node("searchInput").addEventListener("input", searchStories);
|
||
node("captionToggle").addEventListener("click", () => { captionsOn = !captionsOn; updateCaption(); });
|
||
node("openEdition").addEventListener("click", () => { editionIndex=0; renderEditionPage(); openOverlay("editionOverlay"); });
|
||
node("editionPrev").addEventListener("click", () => { editionIndex -= 1; renderEditionPage(); });
|
||
node("editionNext").addEventListener("click", () => { editionIndex += 1; renderEditionPage(); });
|
||
node("newsletterForm").addEventListener("submit", (event) => { event.preventDefault(); setText("newsletterNote", `${data.media.newsletter.successPrefix} ${node("newsletterEmail").value}.`); });
|
||
node("openSettings").addEventListener("click", () => { renderSettingsTabs(); setStatus(""); openOverlay("settingsOverlay"); });
|
||
node("validateJson").addEventListener("click", () => { try { const candidate={...data,[currentModule]:parseEditor()}; validateClientDocument(candidate); setStatus("完整 JSON 校验通过。"); } catch(error) { setStatus(error.message); } });
|
||
node("copyJson").addEventListener("click", () => copyJson().catch((error) => setStatus(error.message)));
|
||
node("downloadJson").addEventListener("click", () => { try { downloadJson(); } catch(error) { setStatus(error.message); } });
|
||
node("resetJson").addEventListener("click", () => { data=clone(initialData); removeStorage(dataKey); removeStorage(themeKey); currentModule=MODULES[0]; activeFeed="latest"; activeRegion=data.regions.tabs[0].id; renderAll(); renderSettingsTabs(); setStatus("已恢复内嵌初始 JSON。"); });
|
||
node("applyJson").addEventListener("click", applyEditor);
|
||
document.querySelectorAll("[data-close]").forEach((button) => button.addEventListener("click", () => closeOverlay(button.dataset.close)));
|
||
["drawerOverlay","searchOverlay","videoOverlay","editionOverlay","settingsOverlay"].forEach((id) => node(id).addEventListener("click", (event) => { if (event.target === node(id)) closeOverlay(id); }));
|
||
document.addEventListener("keydown", (event) => { if (event.key === "Escape") document.querySelectorAll(".screen-overlay.open,.modal-overlay.open,.settings-overlay.open").forEach((overlay) => closeOverlay(overlay.id)); });
|
||
window.addEventListener("scroll", () => node("primaryNav").classList.toggle("stuck", window.scrollY > 180), {passive:true});
|
||
document.addEventListener("click", (event) => { const anchor=event.target.closest("a[href^='#']"); if (anchor && anchor.closest(".screen-overlay")) closeOverlay(anchor.closest(".screen-overlay").id); });
|
||
|
||
validateClientDocument(data);
|
||
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,.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 exactPathTarget = (element) => {
|
||
const host = element.closest("[data-media-path]");
|
||
const path = host && host.dataset ? host.dataset.mediaPath : "";
|
||
if (!path) return null;
|
||
const owner = path.split(".").reduce((value, segment) => {
|
||
if (Array.isArray(value)) return value[Number(segment)];
|
||
return value && typeof value === "object" ? value[segment] : null;
|
||
}, getRootData());
|
||
if (!owner || typeof owner !== "object" || Array.isArray(owner)) return null;
|
||
return { owner, previous: owner.media && typeof owner.media === "object" ? owner.media : { type: "image" }, key: "mediaUrl" };
|
||
};
|
||
const chooseVisualTarget = (element) => {
|
||
const exact = exactPathTarget(element);
|
||
if (exact) return exact;
|
||
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 exact = exactPathTarget(element);
|
||
if (exact) return exact;
|
||
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();
|
||
})();
|