793 lines
46 KiB
JavaScript
793 lines
46 KiB
JavaScript
(() => {
|
|
"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 MODULES = ["site", "navigation", "breaking", "lead", "latest", "video", "world", "markets", "newsletter", "footer"];
|
|
const MODULE_META = {
|
|
site: ["站点信息", "品牌、日期与工具栏"],
|
|
navigation: ["导航", "频道、搜索与移动菜单"],
|
|
breaking: ["突发新闻", "突发标签、标题与时间"],
|
|
lead: ["头条", "主报道、侧栏与实时更新"],
|
|
latest: ["最新报道", "新闻卡片与摘要"],
|
|
video: ["视频现场", "直播弹窗与视频卡片"],
|
|
world: ["全球商业", "列表报道与分析评论"],
|
|
markets: ["市场快照", "行情名称、数值与涨跌"],
|
|
newsletter: ["新闻简报", "订阅文案与反馈"],
|
|
footer: ["页脚", "栏目链接与版权信息"]
|
|
};
|
|
const VISUAL_TYPES = new Set(["summit", "train", "coast", "city", "deep-sea", "night-city", "space", "music", "trade", "market", "payments", "energy"]);
|
|
const embeddedData = JSON.parse(qs("#cnnPageData").textContent);
|
|
const initialData = clone(embeddedData);
|
|
|
|
const fingerprint = (text) => {
|
|
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(36);
|
|
};
|
|
const pageFingerprint = fingerprint(JSON.stringify(initialData));
|
|
const storageKey = "cnn-page-data-v1:" + pageFingerprint;
|
|
const themeKey = "cnn-page-theme-v1:" + pageFingerprint;
|
|
|
|
const readStorage = (key) => {
|
|
try {
|
|
return window.localStorage ? window.localStorage.getItem(key) : null;
|
|
} catch (_error) {
|
|
return null;
|
|
}
|
|
};
|
|
const writeStorage = (key, value) => {
|
|
try {
|
|
if (window.localStorage) window.localStorage.setItem(key, value);
|
|
return true;
|
|
} catch (_error) {
|
|
return false;
|
|
}
|
|
};
|
|
const removeStorage = (key) => {
|
|
try {
|
|
if (window.localStorage) window.localStorage.removeItem(key);
|
|
} catch (_error) {
|
|
/* Sandboxed previews may intentionally deny storage. */
|
|
}
|
|
};
|
|
const isObject = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
const isCompleteData = (value) => Boolean(isObject(value) && MODULES.every((name) => isObject(value[name])));
|
|
const cachedData = readStorage(storageKey);
|
|
let pageData = initialData;
|
|
if (cachedData) {
|
|
try {
|
|
const parsed = JSON.parse(cachedData);
|
|
if (isCompleteData(parsed)) pageData = parsed;
|
|
} catch (_error) {
|
|
pageData = initialData;
|
|
}
|
|
}
|
|
|
|
const escapeHTML = (value) => String(value == null ? "" : value).replace(/[&<>'"]/g, (character) => ({
|
|
"&": "&", "<": "<", ">": ">", "'": "'", '"': """
|
|
})[character]);
|
|
const safeHref = (value) => /^#[a-z0-9_-]+$/i.test(String(value || "")) ? escapeHTML(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 safeVisual = (value, fallback) => VISUAL_TYPES.has(value) ? value : fallback;
|
|
const toast = qs("#toast");
|
|
let toastTimer = 0;
|
|
const showToast = (message) => {
|
|
if (document.body.classList.contains("settings-open")) {
|
|
const status = qs("#jsonStatus");
|
|
if (status) {
|
|
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"), 2400);
|
|
};
|
|
const saveData = () => writeStorage(storageKey, JSON.stringify(pageData));
|
|
|
|
document.head.insertAdjacentHTML("beforeend", '<style data-external-media>.visual>img,.visual>video,.visual>iframe{width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}.visual>iframe{object-fit:initial}.visual .external-open{position:absolute;right:10px;bottom:10px;z-index:3;padding:7px 11px;border-radius:999px;color:#fff;background:rgba(0,0,0,.72);text-decoration:none;font-size:12px;font-weight:700}.visual .external-copy{position:absolute;left:10px;right:10px;bottom:10px;padding:10px;color:#fff;background:rgba(0,0,0,.72);border-radius:8px}.visual .external-copy strong,.visual .external-copy span{display:block}.visual .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");
|
|
if (!source) return "";
|
|
const poster = safeRemoteUrl(media.posterUrl, "image");
|
|
return '<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 = (requested, label) => {
|
|
if (isObject(requested)) {
|
|
const external = externalMediaMarkup(requested, label);
|
|
if (external) return external;
|
|
requested = "city";
|
|
}
|
|
const type = safeVisual(requested, "city");
|
|
const title = escapeHTML(label || type);
|
|
let content = "";
|
|
let background = "#253440";
|
|
if (type === "summit") {
|
|
background = "#425a70";
|
|
content = '<circle cx="610" cy="88" r="55" fill="#f3d3a0" opacity=".75"/><path d="M0 360 140 322l126 28 104-70 157 64 132-84 155 68 186-91v283H0Z" fill="#18252d"/><path d="M130 520V240l170-75 174 82v273Z" fill="#111b22"/><path d="M150 258 300 193l154 67v145H150Z" fill="#9cb3c0" opacity=".68"/><path d="M168 282h266M168 325h266M205 234v170M275 205v199M350 216v188M410 250v154" stroke="#eaf1f2" stroke-opacity=".42" stroke-width="5"/><rect x="525" y="335" width="245" height="185" fill="#25333d"/><path d="M545 370h205M545 410h205M545 450h205" stroke="#e9b77f" stroke-opacity=".65" stroke-width="7"/><path d="M0 450c190-42 345-27 525 10 173 35 307 28 475-18v78H0Z" fill="#0a1014"/>';
|
|
} else if (type === "train") {
|
|
background = "#b8d7df";
|
|
content = '<path d="M0 190 130 86l120 95L395 62l305 175v93H0Z" fill="#516e62"/><path d="M0 250c180-64 350-35 700 18v62H0Z" fill="#2c4538"/><path d="M50 284c190-48 360-37 600 20" stroke="#d4d1c4" stroke-width="10" fill="none"/><g transform="translate(260 225) rotate(5)"><path d="M0 0h225l38 34-8 31H0Z" fill="#eee9dc"/><path d="M16 12h184v25H16Z" fill="#334f5b"/><path d="M220 5l31 29h-40Z" fill="#c60000"/></g>';
|
|
} else if (type === "coast") {
|
|
background = "#acd5e6";
|
|
content = '<path d="M0 310c113-55 173-65 276-35 125 36 237-8 524-138v313H0Z" fill="#315f6a"/><path d="M0 337c125-47 195-41 313-5 122 37 293-20 487-104" stroke="#e9f0e8" stroke-width="18" fill="none" opacity=".8"/><path d="M570 215v128h-86V235Z" fill="#d0b180"/><path d="M538 145 590 215h-104Z" fill="#7d3f31"/><rect x="526" y="271" width="17" height="72" fill="#4c3027"/><circle cx="536" cy="162" r="11" fill="#ffd66f"/>';
|
|
} else if (type === "city") {
|
|
background = "#d7d1c5";
|
|
content = '<path d="M0 330 170 135l120 83L438 73l262 217v160H0Z" fill="#6e756a"/><path d="M75 450V180h175v270M370 450V122h190v328" fill="#373d3c"/><g fill="#e8c675"><rect x="105" y="220" width="34" height="42"/><rect x="175" y="220" width="34" height="42"/><rect x="400" y="165" width="41" height="50"/><rect x="485" y="165" width="41" height="50"/></g><path d="M0 385h700" stroke="#be302d" stroke-width="8"/>';
|
|
} else if (type === "deep-sea") {
|
|
background = "#10141c";
|
|
content = '<circle cx="405" cy="220" r="145" fill="#263853"/><path d="M285 270c52-132 188-205 312-183-55 41-84 89-108 148-40 100-89 137-204 35Z" fill="#4e80ac"/><g fill="#b6dbff"><circle cx="315" cy="165" r="5"/><circle cx="484" cy="110" r="4"/><circle cx="590" cy="240" r="5"/><circle cx="195" cy="268" r="4"/></g><path d="M100 374c150-40 420-48 565 5" stroke="#c60000" stroke-width="7" fill="none"/><circle cx="500" cy="360" r="14" fill="#fff"/>';
|
|
} else if (type === "night-city") {
|
|
background = "#071525";
|
|
content = '<g fill="#203247"><rect x="35" y="155" width="108" height="295"/><rect x="164" y="92" width="116" height="358"/><rect x="300" y="185" width="96" height="265"/><rect x="420" y="55" width="148" height="395"/><rect x="590" y="137" width="92" height="313"/></g><g fill="#e6ad69"><path d="M57 191h64v7H57Zm0 45h64v7H57Zm130-93h70v7h-70Zm0 49h70v7h-70Zm258-91h98v8h-98Zm0 57h98v8h-98Z"/></g><path d="M0 376c190-76 370-76 700-7" stroke="#dd1b2e" stroke-width="8" fill="none"/><path d="M0 397c210-67 430-54 700 2" stroke="#fff" stroke-opacity=".55" stroke-width="3" fill="none"/>';
|
|
} else if (type === "space") {
|
|
background = "#080b13";
|
|
content = '<circle cx="575" cy="100" r="65" fill="#94b7d3"/><g transform="translate(345 230) rotate(-14)"><rect x="-105" y="-35" width="210" height="70" rx="8" fill="#d9dce0"/><rect x="-215" y="-62" width="94" height="124" fill="#355a82"/><rect x="121" y="-62" width="94" height="124" fill="#355a82"/><circle cx="12" cy="0" r="22" fill="#8ea1b3"/></g><g fill="#fff"><circle cx="90" cy="75" r="3"/><circle cx="180" cy="355" r="3"/><circle cx="500" cy="315" r="3"/></g>';
|
|
} else if (type === "music") {
|
|
background = "#79143b";
|
|
content = '<path d="M140 340V90h420v250" stroke="#101018" stroke-width="28" fill="none"/><g fill="#f2c247"><circle cx="220" cy="130" r="20"/><circle cx="350" cy="130" r="20"/><circle cx="480" cy="130" r="20"/></g><path d="M344 148v140m-32-85h64" stroke="#fff" stroke-width="15"/><g fill="#12131b"><circle cx="92" cy="410" r="48"/><circle cx="205" cy="400" r="53"/><circle cx="330" cy="416" r="49"/><circle cx="475" cy="399" r="55"/><circle cx="610" cy="414" r="50"/></g>';
|
|
} else if (type === "trade") {
|
|
background = "#c9dae0";
|
|
content = '<path d="M0 330 210 95l150 175 120-84 220 155v109H0Z" fill="#6a837c"/><path d="M60 390h580" stroke="#fff" stroke-width="16"/><path d="M180 370V240h350v130" fill="#24343c"/>';
|
|
} else if (type === "market") {
|
|
background = "#ead7bd";
|
|
content = '<circle cx="350" cy="160" r="105" fill="#c60000" opacity=".82"/><path d="M80 380h540M120 320h460M165 260h370" stroke="#31353a" stroke-width="22"/>';
|
|
} else if (type === "payments") {
|
|
background = "#18232b";
|
|
content = '<rect x="90" y="70" width="520" height="310" rx="24" fill="#314b5e"/><path d="M155 315 255 215l82 45 150-145" stroke="#7ee0a0" stroke-width="24" fill="none"/><circle cx="487" cy="115" r="24" fill="#7ee0a0"/>';
|
|
} else {
|
|
background = "#bdd4d5";
|
|
content = '<path d="M0 315c210-82 375-112 700-35v170H0Z" fill="#4f7b6b"/><g fill="#edf2e9"><rect x="115" y="155" width="82" height="180"/><rect x="280" y="100" width="92" height="235"/><rect x="485" y="175" width="76" height="160"/></g><path d="M156 155V85m170 15V28m197 147v-62" stroke="#edf2e9" stroke-width="14"/>';
|
|
}
|
|
return '<svg viewBox="0 0 700 450" preserveAspectRatio="xMidYMid slice" role="img" aria-label="' + title + '"><rect width="700" height="450" fill="' + background + '"/>' + content + "</svg>";
|
|
};
|
|
|
|
let themeInitialized = false;
|
|
const applyInitialTheme = () => {
|
|
if (themeInitialized) return;
|
|
themeInitialized = true;
|
|
const configured = pageData.site.theme;
|
|
const stored = readStorage(themeKey);
|
|
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 syncThemeLabel = () => {
|
|
const dark = document.body.classList.contains("dark");
|
|
qs("#themeToggle").setAttribute("aria-label", dark ? "切换浅色模式" : "切换深色模式");
|
|
};
|
|
const toggleTheme = () => {
|
|
const dark = document.body.classList.toggle("dark");
|
|
writeStorage(themeKey, dark ? "dark" : "light");
|
|
syncThemeLabel();
|
|
showToast(dark ? "已切换至深色模式" : "已切换至浅色模式");
|
|
};
|
|
|
|
const renderSite = () => {
|
|
const site = pageData.site || {};
|
|
document.title = site.pageTitle || site.brand || "CNN";
|
|
qs('meta[name="description"]').content = site.description || "";
|
|
qs("#brandText").textContent = site.brand || "CNN";
|
|
qs("#brandLink").setAttribute("aria-label", (site.brand || "CNN") + " 首页");
|
|
qs("#drawerBrand").textContent = site.brand || "CNN";
|
|
const utilityLinks = Array.isArray(site.utilityLinks) ? site.utilityLinks : [];
|
|
qs("#utilityLeft").innerHTML = "<span>" + escapeHTML(site.date) + "</span>" + utilityLinks.map((label, index) =>
|
|
'<a href="' + (index === 0 ? "#markets" : "#newsletter") + '">' + escapeHTML(label) + "</a>"
|
|
).join("");
|
|
const marketSummary = Array.isArray(site.marketSummary) ? site.marketSummary : [];
|
|
qs("#utilityRight").innerHTML = marketSummary.map((item) =>
|
|
"<span>" + escapeHTML(item.label) + ' <b class="market-' + (item.direction === "down" ? "down" : item.direction === "flat" ? "flat" : "up") + '">' +
|
|
escapeHTML(item.value) + "</b></span>"
|
|
).join("") + "<span>" + escapeHTML(site.weather) + "</span>";
|
|
qs("#frontLabel").textContent = site.frontLabel || "";
|
|
applyInitialTheme();
|
|
};
|
|
|
|
const renderNavigation = () => {
|
|
const navigation = pageData.navigation || {};
|
|
const items = Array.isArray(navigation.items) ? navigation.items : [];
|
|
const markup = items.map((item, index) => '<a class="' + (index === 0 ? "active" : "") + '" href="' +
|
|
safeHref(item.href) + '">' + escapeHTML(item.label) + "</a>").join("");
|
|
qs("#desktopNav").innerHTML = markup;
|
|
qs("#drawerLinks").innerHTML = markup;
|
|
qs("#searchInput").placeholder = navigation.searchPlaceholder || "";
|
|
qs("#searchSubmit").textContent = navigation.searchButton || "搜索";
|
|
qs("#liveLabel").textContent = navigation.liveLabel || "直播";
|
|
qs("#drawerFooter").textContent = navigation.drawerFooter || "";
|
|
};
|
|
|
|
const renderBreaking = () => {
|
|
const data = pageData.breaking || {};
|
|
qs("#breakingLabel").textContent = data.label || "";
|
|
qs("#breakingCopy").textContent = data.text || "";
|
|
qs("#breakingTime").textContent = data.time || "";
|
|
};
|
|
|
|
const storyTools = () => '<div class="story-tools"><button class="tool-btn save-btn"><svg viewBox="0 0 24 24"><path d="M6 4h12v17l-6-4-6 4Z"/></svg><span>收藏</span></button><button class="tool-btn share-btn"><svg viewBox="0 0 24 24"><circle cx="18" cy="5" r="2.5"/><circle cx="6" cy="12" r="2.5"/><circle cx="18" cy="19" r="2.5"/><path d="m8.2 10.8 7.5-4.4M8.2 13.2l7.5 4.4"/></svg><span>分享</span></button></div>';
|
|
const renderLead = () => {
|
|
const data = pageData.lead || {};
|
|
const primary = data.primary || {};
|
|
const sideStories = Array.isArray(data.sideStories) ? data.sideStories : [];
|
|
const updates = Array.isArray(data.updates) ? data.updates : [];
|
|
qs("#leadGrid").innerHTML = '<article class="lead-story"><div class="kicker">' + escapeHTML(primary.kicker) +
|
|
"</div><h1>" + escapeHTML(primary.title) + '</h1><p class="dek">' + escapeHTML(primary.summary) +
|
|
'</p><div class="story-meta"><strong>' + escapeHTML(primary.byline) + "</strong><span>·</span><time>" +
|
|
escapeHTML(primary.updated) + "</time><span>·</span><span>" + escapeHTML(primary.readingTime) +
|
|
'</span></div><div class="visual lead-visual">' + visualSvg(primary.media || primary.visual, primary.visualLabel) +
|
|
'<span class="visual-tag">' + escapeHTML(primary.tag) + '</span><span class="visual-credit">' +
|
|
escapeHTML(primary.credit) + "</span></div>" + storyTools() + '</article><aside class="side-stack">' +
|
|
sideStories.map((story) => '<article class="side-story">' +
|
|
(story.visual ? '<div class="visual mini-visual">' + visualSvg(story.media || story.visual, story.title) + "</div>" : "") +
|
|
'<div class="kicker">' + escapeHTML(story.kicker) + "</div><h2>" + escapeHTML(story.title) +
|
|
"</h2><p>" + escapeHTML(story.summary) + "</p></article>").join("") +
|
|
'<div class="live-list"><div class="live-list-head"><span>' + escapeHTML(data.updatesTitle) +
|
|
'</span><button class="open-live">打开直播 →</button></div>' + updates.map((item) =>
|
|
'<div class="live-item"><time>' + escapeHTML(item.time) + "</time><span>" + escapeHTML(item.text) + "</span></div>"
|
|
).join("") + "</div></aside>";
|
|
};
|
|
|
|
const renderLatest = () => {
|
|
const data = pageData.latest || {};
|
|
qs("#latestTitle").textContent = data.title || "";
|
|
qs("#latestMore").textContent = data.moreLabel || "";
|
|
const items = Array.isArray(data.items) ? data.items : [];
|
|
qs("#latestGrid").innerHTML = items.map((item, index) =>
|
|
'<article class="news-card' + (index === 0 ? " feature" : "") + '" data-searchable><div class="card-visual visual">' +
|
|
visualSvg(item.media || item.visual, item.title) + '</div><div class="kicker">' + escapeHTML(item.kicker) + "</div><h3>" +
|
|
escapeHTML(item.title) + "</h3><p>" + escapeHTML(item.summary) + '</p><span class="timestamp">' +
|
|
escapeHTML(item.time) + "</span></article>"
|
|
).join("");
|
|
};
|
|
|
|
const renderVideo = () => {
|
|
const data = pageData.video || {};
|
|
qs("#videoTitle").textContent = data.title || "";
|
|
qs("#videoMore").textContent = data.moreLabel || "";
|
|
qs("#liveTitle").textContent = data.modalTitle || "";
|
|
qs("#playerTitle").textContent = data.liveTitle || "";
|
|
qs("#playerSubtitle").textContent = data.liveSubtitle || "";
|
|
qs("#modalNote").textContent = data.modalNote || "";
|
|
const items = Array.isArray(data.items) ? data.items : [];
|
|
qs("#videoGrid").innerHTML = items.map((item, index) =>
|
|
'<article class="video-card' + (index === 0 ? " feature" : "") + '" data-searchable><button class="card-visual visual open-live" aria-label="播放:' +
|
|
escapeHTML(item.title) + '">' + visualSvg(item.media || item.visual, item.title) +
|
|
'<span class="play"><svg viewBox="0 0 24 24"><path d="m8 5 11 7-11 7Z"/></svg></span><span class="duration">' +
|
|
escapeHTML(item.duration) + "</span></button><h3>" + escapeHTML(item.title) + '</h3><span class="timestamp">' +
|
|
escapeHTML(item.meta) + "</span></article>"
|
|
).join("");
|
|
};
|
|
|
|
const renderWorld = () => {
|
|
const data = pageData.world || {};
|
|
qs("#worldTitle").textContent = data.title || "";
|
|
qs("#worldMore").textContent = data.moreLabel || "";
|
|
const items = Array.isArray(data.items) ? data.items : [];
|
|
qs("#worldList").innerHTML = items.map((item) =>
|
|
'<article class="list-item" data-searchable><div class="list-thumb">' + visualSvg(item.media || item.visual, item.title) +
|
|
'</div><div><div class="kicker">' + escapeHTML(item.kicker) + "</div><h3>" + escapeHTML(item.title) +
|
|
'</h3><span class="timestamp">' + escapeHTML(item.time) + "</span></div></article>"
|
|
).join("");
|
|
const analysis = data.analysis || {};
|
|
qs("#opinion").innerHTML = '<div class="kicker">' + escapeHTML(analysis.kicker) + "</div><h3>" +
|
|
escapeHTML(analysis.title) + "</h3><p>" + escapeHTML(analysis.text) +
|
|
'</p><div class="author"><span class="author-mark">' + escapeHTML(analysis.initial) + "</span><span>" +
|
|
escapeHTML(analysis.author) + "<br><small>" + escapeHTML(analysis.role) + "</small></span></div>";
|
|
};
|
|
|
|
const renderMarkets = () => {
|
|
const data = pageData.markets || {};
|
|
qs("#marketsTitle").textContent = data.title || "";
|
|
qs("#marketsMore").textContent = data.moreLabel || "";
|
|
const items = Array.isArray(data.items) ? data.items : [];
|
|
qs("#marketsGrid").innerHTML = items.map((item) =>
|
|
'<div class="market"><div class="market-name">' + escapeHTML(item.name) + '</div><div class="market-val">' +
|
|
escapeHTML(item.value) + '</div><div class="market-change market-' +
|
|
(item.direction === "down" ? "down" : item.direction === "flat" ? "flat" : "up") + '">' +
|
|
escapeHTML(item.change) + "</div></div>"
|
|
).join("");
|
|
};
|
|
|
|
const renderNewsletter = () => {
|
|
const data = pageData.newsletter || {};
|
|
qs("#newsletterTitle").textContent = data.title || "";
|
|
qs("#newsletterText").textContent = data.text || "";
|
|
qs("#email").placeholder = data.placeholder || "";
|
|
qs("#newsletterButton").textContent = data.button || "";
|
|
};
|
|
|
|
const renderFooter = () => {
|
|
const data = pageData.footer || {};
|
|
const columns = Array.isArray(data.columns) ? data.columns : [];
|
|
qs("#footerGrid").innerHTML = '<div><div class="footer-brand">' + escapeHTML(pageData.site.brand) +
|
|
"</div><p>" + escapeHTML(data.tagline) + "</p></div>" + columns.map((column) =>
|
|
"<div><h3>" + escapeHTML(column.title) + "</h3>" + (Array.isArray(column.links) ? column.links : []).map((link) =>
|
|
'<a href="' + safeHref(link.href) + '">' + escapeHTML(link.label) + "</a>"
|
|
).join("") + "</div>"
|
|
).join("");
|
|
qs("#copyright").textContent = data.copyright || "";
|
|
qs("#legal").textContent = data.legal || "";
|
|
};
|
|
|
|
const renderAll = () => {
|
|
renderSite();
|
|
renderNavigation();
|
|
renderBreaking();
|
|
renderLead();
|
|
renderLatest();
|
|
renderVideo();
|
|
renderWorld();
|
|
renderMarkets();
|
|
renderNewsletter();
|
|
renderFooter();
|
|
bindDynamicInteractions();
|
|
};
|
|
|
|
const liveModal = qs("#liveModal");
|
|
let lastFocus = null;
|
|
function 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 openDrawer = () => {
|
|
drawer.classList.add("open");
|
|
document.body.style.overflow = "hidden";
|
|
qs("#drawerClose").focus();
|
|
};
|
|
const closeDrawer = () => {
|
|
drawer.classList.remove("open");
|
|
document.body.style.overflow = "";
|
|
qs("#menuOpen").focus();
|
|
};
|
|
const bindDynamicInteractions = () => {
|
|
qsa(".open-live").forEach((button) => {
|
|
if (button.dataset.liveBound) return;
|
|
button.dataset.liveBound = "true";
|
|
button.addEventListener("click", openLive);
|
|
});
|
|
qsa(".save-btn").forEach((button) => button.addEventListener("click", () => {
|
|
const saved = button.classList.toggle("saved");
|
|
qs("span", button).textContent = saved ? "已收藏" : "收藏";
|
|
showToast(saved ? "报道已加入收藏" : "已取消收藏");
|
|
}));
|
|
qsa(".share-btn").forEach((button) => button.addEventListener("click", async () => {
|
|
try {
|
|
if (navigator.share) {
|
|
await navigator.share({title: document.title, url: location.href});
|
|
} else if (navigator.clipboard) {
|
|
await navigator.clipboard.writeText(location.href);
|
|
showToast("链接已复制");
|
|
} else {
|
|
showToast("可复制浏览器地址进行分享");
|
|
}
|
|
} catch (_error) {
|
|
/* User cancellation is not an error state. */
|
|
}
|
|
}));
|
|
qsa(".drawer-links a").forEach((link) => link.addEventListener("click", closeDrawer));
|
|
};
|
|
|
|
qs("#themeToggle").addEventListener("click", toggleTheme);
|
|
qs("#searchToggle").addEventListener("click", () => {
|
|
const panel = qs("#searchPanel");
|
|
panel.classList.toggle("open");
|
|
if (panel.classList.contains("open")) window.setTimeout(() => qs("#searchInput").focus(), 20);
|
|
});
|
|
qs("#searchForm").addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
const query = qs("#searchInput").value.trim().toLocaleLowerCase();
|
|
const corpus = [
|
|
pageData.breaking.text,
|
|
pageData.lead.primary.title,
|
|
pageData.lead.primary.summary,
|
|
...(pageData.lead.sideStories || []).flatMap((item) => [item.title, item.summary]),
|
|
...(pageData.latest.items || []).flatMap((item) => [item.title, item.summary]),
|
|
...(pageData.video.items || []).map((item) => item.title),
|
|
...(pageData.world.items || []).map((item) => item.title),
|
|
pageData.world.analysis.title,
|
|
pageData.world.analysis.text
|
|
];
|
|
const matches = query ? corpus.filter((value) => String(value || "").toLocaleLowerCase().includes(query)).length : 0;
|
|
const result = qs("#searchResults");
|
|
result.classList.add("show");
|
|
result.textContent = query ? "找到与“" + qs("#searchInput").value.trim() + "”相关的 " + matches + " 篇报道" : "请输入搜索关键词";
|
|
});
|
|
qs("#liveClose").addEventListener("click", closeLive);
|
|
liveModal.addEventListener("click", (event) => {
|
|
if (event.target === liveModal) closeLive();
|
|
});
|
|
qs("#captionToggle").addEventListener("click", (event) => {
|
|
const isOn = event.currentTarget.textContent.includes("开");
|
|
event.currentTarget.textContent = "CC 字幕:" + (isOn ? "关" : "开");
|
|
showToast(isOn ? "字幕已关闭" : "字幕已开启");
|
|
});
|
|
qs("#menuOpen").addEventListener("click", openDrawer);
|
|
qs("#drawerClose").addEventListener("click", closeDrawer);
|
|
drawer.addEventListener("click", (event) => {
|
|
if (event.target === drawer) closeDrawer();
|
|
});
|
|
qs("#newsletterForm").addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
const email = qs("#email").value.trim();
|
|
qs("#formStatus").textContent = (pageData.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)) {
|
|
showToast("请修正 JSON 后再应用");
|
|
return;
|
|
}
|
|
pageData = clone(editorDraft);
|
|
saveData();
|
|
renderAll();
|
|
showToast("JSON 已应用到页面");
|
|
});
|
|
qs("#resetJson").addEventListener("click", () => {
|
|
pageData = clone(initialData);
|
|
editorDraft = clone(initialData);
|
|
removeStorage(storageKey);
|
|
removeStorage(themeKey);
|
|
themeInitialized = false;
|
|
renderAll();
|
|
renderModuleTabs();
|
|
selectModule(activeModule, true);
|
|
showToast("已恢复初始 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);
|
|
showToast("完整 JSON 已复制");
|
|
} catch (_error) {
|
|
jsonEditor.focus();
|
|
jsonEditor.select();
|
|
showToast("已选中当前模块,请手动复制");
|
|
}
|
|
});
|
|
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 = "cnn-page-data.json";
|
|
link.click();
|
|
window.setTimeout(() => URL.revokeObjectURL(link.href), 0);
|
|
showToast("JSON 已下载");
|
|
});
|
|
|
|
document.addEventListener("keydown", (event) => {
|
|
if (event.key === "Escape") {
|
|
if (liveModal.classList.contains("open")) closeLive();
|
|
if (drawer.classList.contains("open")) closeDrawer();
|
|
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,.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();
|
|
})();
|