811 lines
45 KiB
JavaScript
811 lines
45 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", "focus", "media", "moreNews", "regions", "newsletter", "footer"];
|
|
const MODULE_META = {
|
|
site: ["站点信息", "字标、标题、账户与日期"],
|
|
navigation: ["导航", "全站、频道、搜索与抽屉"],
|
|
breaking: ["快讯", "快讯标签、标题与时间"],
|
|
lead: ["头条", "主报道与关联阅读"],
|
|
focus: ["今日焦点", "焦点新闻宫格"],
|
|
media: ["视听节目", "直播、字幕与新闻音频"],
|
|
moreNews: ["更多新闻", "短新闻和热门排行"],
|
|
regions: ["地区天气", "地区标题与城市天气"],
|
|
newsletter: ["新闻简报", "订阅文案与反馈"],
|
|
footer: ["页脚", "链接、版权与法律文案"]
|
|
};
|
|
const VISUAL_TYPES = new Set(["research-ship", "harbor", "satellite", "creative-city", "station", "studio", "bulletin", "ocean", "logistics", "market", "device", "energy"]);
|
|
const embeddedData = JSON.parse(qs("#bbcPageData").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 = "bbc-page-data-v1:" + pageFingerprint;
|
|
const themeKey = "bbc-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) {
|
|
/* Opaque 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 logoMarkup = () => (Array.isArray(pageData.site.brandLetters) ? pageData.site.brandLetters : ["B", "B", "C"])
|
|
.map((letter) => "<span>" + escapeHTML(letter) + "</span>").join("");
|
|
const toast = qs("#toast");
|
|
let toastTimer = 0;
|
|
const note = (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"), 2300);
|
|
};
|
|
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:2px;color:#fff;background:rgba(0,0,0,.75);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,.75);text-decoration:none}.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 = "harbor";
|
|
}
|
|
const type = safeVisual(requested, "harbor");
|
|
const title = escapeHTML(label || type);
|
|
let background = "#cbd7d8";
|
|
let content = "";
|
|
if (type === "research-ship") {
|
|
background = "#9fc5cf";
|
|
content = '<circle cx="555" cy="88" r="48" fill="#f2e4b5"/><path d="M0 305c130-31 225-23 343 2 145 31 270 24 457-18v161H0Z" fill="#214e5d"/><path d="M0 345c148-31 255-20 363 7 126 31 274 20 437-18" stroke="#9fcbd0" stroke-opacity=".65" stroke-width="8" fill="none"/><g transform="translate(225 185)"><path d="M0 96h326l-49 73H49Z" fill="#edf0ed"/><path d="M70 50h154v46H70Z" fill="#e8e9e4"/><path d="M92 61h35v22H92Zm53 0h35v22h-35Zm53 0h20v22h-20Z" fill="#305160"/><path d="M149 50V7m0 0 59 43" stroke="#202c31" stroke-width="7"/><rect x="84" y="110" width="124" height="11" fill="#b80000"/></g>';
|
|
} else if (type === "harbor") {
|
|
background = "#ced9d9";
|
|
content = '<path d="M0 300 145 168l102 73 168-128 285 205v132H0Z" fill="#72887b"/><path d="M0 366c151-55 298-59 448-17 116 33 186 28 252 11v90H0Z" fill="#3f6c58"/><path d="M120 332h470" stroke="#e1ded1" stroke-width="18"/><g fill="#303a3d"><rect x="205" y="270" width="116" height="74"/><rect x="367" y="247" width="136" height="97"/></g><g fill="#f5d27d"><rect x="226" y="286" width="22" height="25"/><rect x="272" y="286" width="22" height="25"/><rect x="394" y="268" width="25" height="29"/></g>';
|
|
} else if (type === "satellite") {
|
|
background = "#16191e";
|
|
content = '<circle cx="370" cy="205" r="130" fill="#35536f"/><path d="M270 258c59-140 202-162 274-124-66 33-92 79-120 130-28 48-90 54-154-6Z" fill="#65a4bf"/><g fill="#fff"><circle cx="100" cy="87" r="4"/><circle cx="560" cy="72" r="3"/><circle cx="620" cy="310" r="4"/></g><path d="M85 365h530" stroke="#b80000" stroke-width="8"/>';
|
|
} else if (type === "creative-city") {
|
|
background = "#eadfc8";
|
|
content = '<path d="M40 375h620" stroke="#27282a" stroke-width="14"/><rect x="125" y="115" width="170" height="258" fill="#554c43"/><rect x="365" y="65" width="195" height="308" fill="#6f665b"/><g fill="#eac170"><rect x="155" y="155" width="39" height="45"/><rect x="225" y="155" width="39" height="45"/><rect x="396" y="108" width="46" height="52"/><rect x="480" y="108" width="46" height="52"/><rect x="396" y="195" width="46" height="52"/></g>';
|
|
} else if (type === "station") {
|
|
background = "#b9d2d7";
|
|
content = '<path d="M0 335c142-50 245-71 370-44 122 26 219 0 330-51v210H0Z" fill="#4e796c"/><path d="M155 310V135h390v175" fill="#e8e4da"/><path d="M125 135h450L497 65H203Z" fill="#a64436"/><path d="M205 178h95v132h-95Zm195 0h95v132h-95Z" fill="#345361"/>';
|
|
} else if (type === "studio") {
|
|
background = "#1f2c3b";
|
|
content = '<path d="M0 352h700" stroke="#d13b3b" stroke-width="12"/><path d="M72 80h556v270H72Z" fill="none" stroke="#8395a8" stroke-opacity=".55" stroke-width="3"/><path d="M118 132h205v156H118Z" fill="#b80000"/><path d="M365 132h214v20H365Zm0 56h170v20H365Zm0 56h192v20H365Z" fill="#e8eaec" opacity=".82"/><circle cx="220" cy="210" r="47" fill="#e9d1bc"/>';
|
|
} else if (type === "bulletin") {
|
|
background = "#233344";
|
|
content = '<circle cx="350" cy="225" r="150" fill="none" stroke="#7591aa" stroke-width="3"/><circle cx="350" cy="225" r="100" fill="#b80000"/><path d="M210 225h280M350 85v280" stroke="#fff" stroke-opacity=".7" stroke-width="7"/>';
|
|
} else if (type === "ocean") {
|
|
background = "#326779";
|
|
content = '<g fill="#b9e5e8" opacity=".72"><circle cx="110" cy="95" r="10"/><circle cx="155" cy="145" r="6"/><circle cx="530" cy="82" r="8"/></g><path d="M70 365c105-72 190-61 275-29 102 38 190 23 280-25v139H70Z" fill="#153f43"/><path d="M300 95v215m0-165h125l35 47-160 12" stroke="#dce7df" stroke-width="13" fill="none"/>';
|
|
} else if (type === "logistics") {
|
|
background = "#dde4e0";
|
|
content = '<path d="M70 380h560" stroke="#303a3c" stroke-width="18"/><path d="M170 360V125h360v235" fill="#758b8a"/><path d="M220 170h90v115h-90Zm165 0h90v115h-90Z" fill="#f0d48f"/>';
|
|
} else if (type === "market") {
|
|
background = "#d8cbb6";
|
|
content = '<circle cx="350" cy="220" r="135" fill="#a5392f"/><path d="M130 370h440M175 320h350M225 270h250" stroke="#2d2b29" stroke-width="18"/>';
|
|
} else if (type === "device") {
|
|
background = "#163143";
|
|
content = '<path d="M75 350 210 235l110 58 150-190 150 98" stroke="#71c7dd" stroke-width="22" fill="none"/><circle cx="470" cy="103" r="23" fill="#fff"/>';
|
|
} else {
|
|
background = "#c8d9d1";
|
|
content = '<path d="M0 330c175-94 365-106 700-3v123H0Z" fill="#47705a"/><g fill="#edf0e7"><rect x="120" y="170" width="86" height="180"/><rect x="292" y="105" width="98" height="245"/><rect x="500" y="195" width="75" height="155"/></g>';
|
|
}
|
|
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 = () => {
|
|
qs("#theme").setAttribute("aria-label", document.body.classList.contains("dark") ? "切换浅色模式" : "切换深色模式");
|
|
};
|
|
const toggleTheme = () => {
|
|
const dark = document.body.classList.toggle("dark");
|
|
writeStorage(themeKey, dark ? "dark" : "light");
|
|
syncThemeLabel();
|
|
note(dark ? "深色模式已开启" : "浅色模式已开启");
|
|
};
|
|
|
|
const renderSite = () => {
|
|
const site = pageData.site || {};
|
|
document.title = site.pageTitle || "BBC 新闻";
|
|
qs('meta[name="description"]').content = site.description || "";
|
|
const logo = logoMarkup();
|
|
qs("#brandLogo").innerHTML = logo;
|
|
qs("#brandLogo").setAttribute("aria-label", (site.brandLetters || []).join("") + " 首页");
|
|
qs("#drawerLogo").innerHTML = logo;
|
|
qs("#footerLogo").innerHTML = logo;
|
|
qs("#accountLabel").textContent = site.accountLabel || "";
|
|
qs("#pageDate").textContent = site.updatedDate || "";
|
|
applyInitialTheme();
|
|
};
|
|
|
|
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 renderNavigation = () => {
|
|
const data = pageData.navigation || {};
|
|
qs("#globalNav").innerHTML = navMarkup(data.global, false);
|
|
qs("#channelTitle").textContent = data.channelTitle || "";
|
|
qs("#channelNav").innerHTML = navMarkup(data.channel, true) +
|
|
'<a class="more-link" href="#more">' + escapeHTML(data.moreLabel) +
|
|
' <svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg></a>';
|
|
qs("#searchLabel").textContent = data.searchLabel || "";
|
|
qs("#search").placeholder = data.searchPlaceholder || "";
|
|
qs("#searchButton").textContent = data.searchButton || "";
|
|
qs("#drawerLinks").innerHTML = navMarkup(data.drawer, false);
|
|
};
|
|
|
|
const renderBreaking = () => {
|
|
const data = pageData.breaking || {};
|
|
qs("#breakingLabel").textContent = data.label || "";
|
|
qs("#breakingText").textContent = data.text || "";
|
|
qs("#breakingTime").textContent = data.time || "";
|
|
};
|
|
|
|
const renderLead = () => {
|
|
const data = pageData.lead || {};
|
|
const related = Array.isArray(data.related) ? data.related : [];
|
|
qs("#leadLayout").innerHTML = '<div class="lead-copy"><div class="label">' + escapeHTML(data.kicker) +
|
|
"</div><h1>" + escapeHTML(data.title) + '</h1><p class="dek">' + escapeHTML(data.summary) +
|
|
'</p><ul class="headline-links">' + related.map((item) =>
|
|
'<li><a href="' + safeHref(item.href) + '">' + escapeHTML(item.label) + "</a></li>"
|
|
).join("") + '</ul><div class="meta"><strong>' + escapeHTML(data.byline) + "</strong><span>" +
|
|
escapeHTML(data.time) + '</span><a href="' + safeHref(data.sectionHref) + '">' + escapeHTML(data.section) +
|
|
'</a></div></div><div class="visual lead-visual">' + visualSvg(data.media || data.visual, data.visualLabel) +
|
|
'<span class="live-stamp">' + escapeHTML(data.stamp) + '</span><span class="credit">' +
|
|
escapeHTML(data.credit) + "</span></div>";
|
|
};
|
|
|
|
const renderFocus = () => {
|
|
const data = pageData.focus || {};
|
|
qs("#focusTitle").textContent = data.title || "";
|
|
qs("#focusMore").textContent = data.moreLabel || "";
|
|
const items = Array.isArray(data.items) ? data.items : [];
|
|
qs("#focusGrid").innerHTML = items.map((item, index) =>
|
|
'<article class="story' + (index === 0 ? " feature" : "") + '"><div class="visual story-media">' +
|
|
visualSvg(item.media || item.visual, item.title) + '</div><div class="label">' + escapeHTML(item.kicker) +
|
|
"</div><" + (index === 0 ? "h2" : "h3") + '><a href="' + safeHref(item.href) + '">' +
|
|
escapeHTML(item.title) + "</a></" + (index === 0 ? "h2" : "h3") + ">" +
|
|
(item.summary ? "<p>" + escapeHTML(item.summary) + "</p>" : "") +
|
|
'<div class="meta"><span>' + escapeHTML(item.time) + '</span><a href="' + safeHref(item.href) + '">' +
|
|
escapeHTML(item.section) + "</a></div></article>"
|
|
).join("");
|
|
};
|
|
|
|
let playing = false;
|
|
let audioSeconds = 0;
|
|
let audioTimer = 0;
|
|
const stopAudio = (reset) => {
|
|
window.clearInterval(audioTimer);
|
|
playing = false;
|
|
const button = qs("#audioPlay");
|
|
if (button) {
|
|
button.classList.remove("playing");
|
|
button.setAttribute("aria-label", "播放今日新闻播客");
|
|
}
|
|
if (reset) {
|
|
audioSeconds = 0;
|
|
if (qs("#audioTime")) qs("#audioTime").textContent = "00:00";
|
|
if (qs("#audioBar")) qs("#audioBar").style.width = "0%";
|
|
}
|
|
};
|
|
const renderMedia = () => {
|
|
stopAudio(true);
|
|
const data = pageData.media || {};
|
|
qs("#mediaTitle").textContent = data.title || "";
|
|
qs("#mediaMore").textContent = data.moreLabel || "";
|
|
const videos = Array.isArray(data.videos) ? data.videos : [];
|
|
qs("#mediaGrid").innerHTML = videos.map((item) =>
|
|
'<article class="live-card" data-video-id="' + escapeHTML(item.id) + '"><button class="visual story-media 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="m7 4 13 8-13 8Z"/></svg></span></button><h3>' +
|
|
escapeHTML(item.title) + '</h3><div class="live-meta">' +
|
|
(item.live ? '<span class="live-now">正在直播</span> · ' + escapeHTML(String(item.meta || "").replace(/^正在直播\s*·\s*/, "")) : escapeHTML(item.meta)) +
|
|
"</div></article>"
|
|
).join("");
|
|
const modal = data.modal || {};
|
|
qs("#liveTitle").textContent = modal.title || "";
|
|
qs("#streamTitle").textContent = modal.streamTitle || "";
|
|
qs("#streamSubtitle").textContent = modal.streamSubtitle || "";
|
|
qs("#currentProgram").textContent = modal.currentProgram || "";
|
|
const audio = data.audio || {};
|
|
qs("#audioTitle").textContent = audio.sectionTitle || "";
|
|
qs("#audioName").textContent = audio.title || "";
|
|
qs("#audioMeta").textContent = audio.meta || "";
|
|
qs("#audioDuration").textContent = audio.durationLabel || "";
|
|
};
|
|
|
|
const renderMoreNews = () => {
|
|
const data = pageData.moreNews || {};
|
|
qs("#moreTitle").textContent = data.title || "";
|
|
qs("#moreLink").textContent = data.moreLabel || "";
|
|
const items = Array.isArray(data.items) ? data.items : [];
|
|
qs("#moreList").innerHTML = items.map((item) =>
|
|
'<article class="compact"><div class="visual compact-media">' + visualSvg(item.media || item.visual, item.title) +
|
|
'</div><div><div class="label">' + escapeHTML(item.kicker) + "</div><h3>" +
|
|
escapeHTML(item.title) + '</h3><div class="meta">' + escapeHTML(item.time) + "</div></div></article>"
|
|
).join("");
|
|
qs("#rankingTitle").textContent = data.rankingTitle || "";
|
|
const ranking = Array.isArray(data.ranking) ? data.ranking : [];
|
|
qs("#rankingList").innerHTML = ranking.map((item, index) =>
|
|
'<div class="rank-item"><span class="rank">' + (index + 1) + '</span><a href="' +
|
|
safeHref(item.href) + '">' + escapeHTML(item.title) + "</a></div>"
|
|
).join("");
|
|
};
|
|
|
|
const renderRegions = () => {
|
|
const data = pageData.regions || {};
|
|
qs("#regionsTitle").textContent = data.title || "";
|
|
qs("#regionsMore").textContent = data.moreLabel || "";
|
|
const items = Array.isArray(data.items) ? data.items : [];
|
|
qs("#regionsGrid").innerHTML = items.map((item) =>
|
|
'<div class="region"><strong>' + escapeHTML(item.region) + '</strong><a href="#regions">' +
|
|
escapeHTML(item.title) + "</a></div>"
|
|
).join("");
|
|
qs("#weatherTitle").textContent = data.weatherTitle || "";
|
|
const weather = Array.isArray(data.weather) ? data.weather : [];
|
|
qs("#weatherGrid").innerHTML = '<div class="weather-title">' + escapeHTML(data.weatherLabel) + "</div>" +
|
|
weather.map((item) => '<div class="city"><b>' + escapeHTML(item.city) + '</b><div class="temp">' +
|
|
escapeHTML(item.temperature) + '</div><div class="condition">' + escapeHTML(item.condition) + "</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 links = Array.isArray(data.links) ? data.links : [];
|
|
qs("#footerLinks").innerHTML = links.map((item) =>
|
|
'<a href="' + safeHref(item.href) + '">' + escapeHTML(item.label) + "</a>"
|
|
).join("");
|
|
qs("#copyright").textContent = data.copyright || "";
|
|
qs("#legal").textContent = data.legal || "";
|
|
};
|
|
|
|
const renderAll = () => {
|
|
renderSite();
|
|
renderNavigation();
|
|
renderBreaking();
|
|
renderLead();
|
|
renderFocus();
|
|
renderMedia();
|
|
renderMoreNews();
|
|
renderRegions();
|
|
renderNewsletter();
|
|
renderFooter();
|
|
bindDynamicInteractions();
|
|
};
|
|
|
|
const modal = qs("#liveModal");
|
|
let lastFocus = null;
|
|
function openLive() {
|
|
lastFocus = document.activeElement;
|
|
modal.classList.add("open");
|
|
document.body.style.overflow = "hidden";
|
|
qs("#liveClose").focus();
|
|
}
|
|
const closeLive = () => {
|
|
modal.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(".open-live").forEach((button) => {
|
|
if (button.dataset.liveBound) return;
|
|
button.dataset.liveBound = "true";
|
|
button.addEventListener("click", openLive);
|
|
});
|
|
qsa(".drawer-links a").forEach((link) => link.addEventListener("click", closeMenu));
|
|
};
|
|
|
|
qs("#theme").addEventListener("click", toggleTheme);
|
|
qs("#searchOpen").addEventListener("click", () => {
|
|
const area = qs("#searchArea");
|
|
area.classList.toggle("open");
|
|
if (area.classList.contains("open")) window.setTimeout(() => qs("#search").focus(), 20);
|
|
});
|
|
qs("#searchForm").addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
const queryRaw = qs("#search").value.trim();
|
|
const query = queryRaw.toLocaleLowerCase();
|
|
const corpus = [
|
|
pageData.breaking.text,
|
|
pageData.lead.title,
|
|
pageData.lead.summary,
|
|
...(pageData.lead.related || []).map((item) => item.label),
|
|
...(pageData.focus.items || []).flatMap((item) => [item.title, item.summary]),
|
|
...(pageData.media.videos || []).map((item) => item.title),
|
|
pageData.media.audio.title,
|
|
...(pageData.moreNews.items || []).map((item) => item.title),
|
|
...(pageData.moreNews.ranking || []).map((item) => item.title),
|
|
...(pageData.regions.items || []).map((item) => item.title)
|
|
];
|
|
const count = query ? corpus.filter((value) => String(value || "").toLocaleLowerCase().includes(query)).length : 0;
|
|
const result = qs("#searchResult");
|
|
result.classList.add("show");
|
|
result.textContent = query ? "与“" + queryRaw + "”相关的报道:共 " + count + " 条" : "请输入搜索内容";
|
|
});
|
|
qs("#liveClose").addEventListener("click", closeLive);
|
|
modal.addEventListener("click", (event) => {
|
|
if (event.target === modal) 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("#audioPlay").addEventListener("click", () => {
|
|
const audio = pageData.media.audio || {};
|
|
const duration = Math.max(1, Number(audio.durationSeconds) || 1);
|
|
playing = !playing;
|
|
qs("#audioPlay").classList.toggle("playing", playing);
|
|
qs("#audioPlay").setAttribute("aria-label", playing ? "暂停今日新闻播客" : "播放今日新闻播客");
|
|
window.clearInterval(audioTimer);
|
|
if (!playing) return;
|
|
audioTimer = window.setInterval(() => {
|
|
audioSeconds = Math.min(audioSeconds + 1, duration);
|
|
qs("#audioBar").style.width = (audioSeconds / duration * 100) + "%";
|
|
qs("#audioTime").textContent = String(Math.floor(audioSeconds / 60)).padStart(2, "0") + ":" + String(audioSeconds % 60).padStart(2, "0");
|
|
if (audioSeconds >= duration) stopAudio(false);
|
|
}, 1000);
|
|
});
|
|
qs("#subForm").addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
const email = qs("#email").value.trim();
|
|
qs("#subStatus").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)) {
|
|
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;
|
|
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 = "bbc-page-data.json";
|
|
link.click();
|
|
window.setTimeout(() => URL.revokeObjectURL(link.href), 0);
|
|
note("JSON 已下载");
|
|
});
|
|
|
|
document.addEventListener("keydown", (event) => {
|
|
if (event.key === "Escape") {
|
|
if (modal.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,.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();
|
|
})();
|