696 lines
45 KiB
JavaScript
696 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 escapeHTML = (value) => String(value ?? "").replace(/[&<>'"]/g, (char) => ({"&": "&", "<": "<", ">": ">", "'": "'", '"': """})[char]);
|
|
const safeHref = (value) => String(value || "").startsWith("#") ? String(value) : "#top";
|
|
const safeRemoteUrl = (value, kind = "link") => {
|
|
const source = String(value || "").trim();
|
|
if (!source) return "";
|
|
const lowered = source.toLowerCase();
|
|
if (kind === "image" && lowered.startsWith("data:image/")) return source;
|
|
if (kind === "video" && lowered.startsWith("data:video/")) return source;
|
|
try { const url = new URL(source); return ["http:", "https:"].includes(url.protocol) ? url.href : ""; }
|
|
catch (_error) { return ""; }
|
|
};
|
|
const validateRemoteMediaTree = (value, path = "当前模块") => {
|
|
if (Array.isArray(value)) return value.forEach((item, index) => validateRemoteMediaTree(item, path + "[" + index + "]"));
|
|
if (!isObject(value)) return;
|
|
const media = value.media;
|
|
if (media && ["image", "video", "webpage"].includes(media.type)) {
|
|
if (["image", "video"].includes(media.type) && !safeRemoteUrl(media.mediaUrl, media.type)) throw new Error(path + ".media.mediaUrl 无效");
|
|
if (media.type === "webpage" && !safeRemoteUrl(media.pageUrl)) throw new Error(path + ".media.pageUrl 无效");
|
|
if (media.posterUrl && !safeRemoteUrl(media.posterUrl, "image")) throw new Error(path + ".media.posterUrl 无效");
|
|
}
|
|
Object.entries(value).forEach(([key, item]) => { if (key !== "media") validateRemoteMediaTree(item, path + "." + key); });
|
|
};
|
|
const MODULES = ["site", "navigation", "hero", "notice", "updates", "priorities", "administration", "calendar", "participation", "footer"];
|
|
const MODULE_META = {
|
|
site: ["站点信息", "品牌、办公室、语言和主题"],
|
|
navigation: ["页面导航", "页头、菜单和搜索"],
|
|
hero: ["首页主视觉", "核心信息、简报和直播弹窗"],
|
|
notice: ["公众公告", "公告标签、内容和日期"],
|
|
updates: ["最新动态", "官方新闻和简报"],
|
|
priorities: ["施政重点", "政策卡片和详细内容"],
|
|
administration: ["行政团队", "领导层说明和链接"],
|
|
calendar: ["公共日历", "月份、活动和倒计时"],
|
|
participation: ["公众参与", "参与入口和订阅信息"],
|
|
footer: ["页面页脚", "链接栏目和法律说明"]
|
|
};
|
|
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
const isCompleteData = (value) => isObject(value) && MODULES.every((name) => isObject(value[name]));
|
|
const initialData = JSON.parse(qs("#whiteHousePageData").textContent);
|
|
const fingerprint = (() => {
|
|
const text = JSON.stringify(initialData);
|
|
let hash = 2166136261;
|
|
for (let index = 0; index < text.length; index += 1) {
|
|
hash ^= text.charCodeAt(index);
|
|
hash = Math.imul(hash, 16777619);
|
|
}
|
|
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
})();
|
|
const storageKey = "white-house-page-data-v1:" + fingerprint;
|
|
const themeKey = "white-house-page-theme-v1:" + fingerprint;
|
|
const readStorage = (key) => { try { return window.localStorage.getItem(key); } catch (_error) { return null; } };
|
|
const writeStorage = (key, value) => { try { window.localStorage.setItem(key, value); return true; } catch (_error) { return false; } };
|
|
const removeStorage = (key) => { try { window.localStorage.removeItem(key); } catch (_error) { /* optional storage */ } };
|
|
let pageData = clone(initialData);
|
|
try {
|
|
const saved = readStorage(storageKey);
|
|
const parsed = saved ? JSON.parse(saved) : null;
|
|
if (isCompleteData(parsed)) pageData = parsed;
|
|
} catch (_error) {
|
|
pageData = clone(initialData);
|
|
}
|
|
const saveData = () => writeStorage(storageKey, JSON.stringify(pageData));
|
|
|
|
const toast = qs("#toast");
|
|
let toastTimer = 0;
|
|
const note = (message) => {
|
|
if (qs("#settingsOverlay").classList.contains("open")) {
|
|
const status = qs("#jsonStatus");
|
|
status.textContent = message;
|
|
status.className = "json-status valid";
|
|
return;
|
|
}
|
|
window.clearTimeout(toastTimer);
|
|
toast.textContent = message;
|
|
toast.classList.add("show");
|
|
toastTimer = window.setTimeout(() => toast.classList.remove("show"), 2300);
|
|
};
|
|
|
|
const sealWordmark = () => pageData.site.brandName || "美国白宫";
|
|
document.head.insertAdjacentHTML("beforeend", '<style data-external-media>.hero-art>img,.hero-art>video,.hero-art>iframe,.card-art>img,.card-art>video,.card-art>iframe,.involve-bg>img,.involve-bg>video,.involve-bg>iframe{width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}.hero-art>iframe,.card-art>iframe,.involve-bg>iframe{object-fit:initial}.external-open{position:absolute;right:10px;bottom:10px;z-index:4;padding:7px 11px;color:#fff;background:rgba(0,0,0,.72);text-decoration:none;font-size:12px;font-weight:700}.external-copy{position:absolute;left:10px;right:10px;bottom:10px;z-index:4;padding:9px;color:#fff;background:rgba(0,0,0,.72);text-decoration:none}.external-copy strong,.external-copy span{display:block}.external-copy span{margin-top:3px;font-size:12px}</style>');
|
|
const externalMediaMarkup = (media, label) => {
|
|
if (!isObject(media)) return "";
|
|
if (media.type === "image") {
|
|
const source = safeRemoteUrl(media.mediaUrl, "image");
|
|
if (!source) return "";
|
|
const pageUrl = safeRemoteUrl(media.pageUrl);
|
|
return '<img src="' + escapeHTML(source) + '" alt="' + escapeHTML(media.alt || label || "页面图片") + '" loading="lazy" referrerpolicy="no-referrer"/>' + (pageUrl ? '<a class="external-open" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer">打开来源</a>' : "");
|
|
}
|
|
if (media.type === "video") {
|
|
const source = safeRemoteUrl(media.mediaUrl, "video");
|
|
const poster = safeRemoteUrl(media.posterUrl, "image");
|
|
return source ? '<video src="' + escapeHTML(source) + '"' + (poster ? ' poster="' + escapeHTML(poster) + '"' : "") + ' controls playsinline preload="metadata" aria-label="' + escapeHTML(media.alt || label || "页面视频") + '"></video>' : "";
|
|
}
|
|
if (media.type === "webpage") {
|
|
const pageUrl = safeRemoteUrl(media.pageUrl);
|
|
if (!pageUrl) return "";
|
|
const preview = safeRemoteUrl(media.mediaUrl, "image");
|
|
const body = media.embed === true ? '<iframe src="' + escapeHTML(pageUrl) + '" title="' + escapeHTML(media.title || "网页预览") + '" loading="lazy" referrerpolicy="no-referrer" sandbox="allow-forms allow-popups allow-scripts"></iframe>' : (preview ? '<img src="' + escapeHTML(preview) + '" alt="' + escapeHTML(media.alt || media.title || "网页预览图") + '" loading="lazy" referrerpolicy="no-referrer"/>' : "");
|
|
return body + '<a class="external-copy" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer"><strong>' + escapeHTML(media.title || label || "打开网页") + '</strong><span>' + escapeHTML(media.description || "新窗口打开") + "</span></a>";
|
|
}
|
|
return "";
|
|
};
|
|
const heroArt = () => '<svg viewBox="0 0 1600 900" preserveAspectRatio="xMidYMid slice" aria-hidden="true"><defs><linearGradient id="heroSky" x2="0" y2="1"><stop stop-color="#809aac"/><stop offset=".48" stop-color="#d8c2a2"/><stop offset="1" stop-color="#263d50"/></linearGradient><linearGradient id="lawn" x2="0" y2="1"><stop stop-color="#345a4d"/><stop offset="1" stop-color="#172e29"/></linearGradient></defs><rect width="1600" height="900" fill="url(#heroSky)"/><circle cx="1283" cy="150" r="84" fill="#f1daa1" opacity=".8"/><path d="M0 661c269-110 498-131 792-75 267 51 483 47 808-55v369H0Z" fill="url(#lawn)"/><g transform="translate(647 215)"><path d="M-280 378h796" stroke="#dcd8ca" stroke-width="20"/><path d="M-181 362V174h594v188" fill="#e9e7df"/><path d="M-226 178h684L115-12Z" fill="#ddd9cc"/><path d="M-160 209h552v14h-552Z" fill="#c5c3ba"/><path d="M-139 226h55v119h-55Zm107 0h55v119h-55Zm107 0h55v119H75Zm107 0h55v119h-55Zm107 0h55v119h-55Z" fill="#f6f4eb" stroke="#a9aaa7" stroke-width="3"/><path d="M89 166h52v-56H89Z" fill="#e8e6dd"/><path d="M115 110V37" stroke="#d4d1c6" stroke-width="8"/><path d="m115 37 72 22-72 18Z" fill="#a7282f"/><g fill="#31465a"><path d="M-122 247h21v46h-21Zm107 0H6v46h-21Zm107 0h21v46H92Zm107 0h21v46h-21Zm107 0h21v46h-21Z"/></g></g><path d="M0 774c403-126 839-104 1600 9" stroke="#4f7667" stroke-width="86" fill="none"/></svg>';
|
|
const visualSvg = (type, title) => {
|
|
if (isObject(type)) {
|
|
const external = externalMediaMarkup(type, title);
|
|
if (external) return external;
|
|
type = "hall";
|
|
}
|
|
let background = "#d7c9b5";
|
|
let content = '<path d="M80 380h540M150 350V165h400v185" fill="#e5dfd3" stroke="#8e877b" stroke-width="8"/><path d="M115 170h470L350 55Z" fill="#f0eadf"/>';
|
|
if (type === "hall") {
|
|
background = "#d6c8b3";
|
|
content = '<path d="M95 450V95h510v355" fill="#d6c8b3"/><path d="M65 100h570L350 0Z" fill="#e6dccb"/><g fill="#f4eee2" stroke="#9d8b75" stroke-width="4"><rect x="125" y="135" width="72" height="250"/><rect x="252" y="135" width="72" height="250"/><rect x="378" y="135" width="72" height="250"/><rect x="505" y="135" width="72" height="250"/></g><path d="M0 390h700v60H0Z" fill="#263a4e"/>';
|
|
} else if (type === "mobility") {
|
|
background = "#cbd8dc";
|
|
content = '<path d="M0 330 125 198l90 83 144-165 341 245v89H0Z" fill="#667d72"/><path d="M0 388c214-78 428-78 700-2" stroke="#e9e3d5" stroke-width="20" fill="none"/><g fill="#394f58"><rect x="185" y="305" width="112" height="72"/><rect x="366" y="265" width="145" height="112"/></g>';
|
|
} else if (type === "science") {
|
|
background = "#132941";
|
|
content = '<circle cx="355" cy="215" r="136" fill="#2c5478"/><path d="M258 272c39-121 170-180 278-134-59 35-83 76-108 132-31 68-93 72-170 2Z" fill="#5d9ab6"/><path d="M80 385h540" stroke="#c9a45c" stroke-width="10"/>';
|
|
} else if (type === "statement") {
|
|
background = "#e3dacb";
|
|
content = '<rect x="125" y="75" width="450" height="310" rx="4" fill="#fffdf8"/><path d="M180 145h340M180 205h285M180 265h310M180 325h210" stroke="#9b9387" stroke-width="16"/><circle cx="520" cy="330" r="38" fill="#a7282f"/>';
|
|
} else if (type === "action") {
|
|
background = "#17314a";
|
|
content = '<path d="M145 375h410V125H145Z" fill="#ede8dd"/><path d="M205 195h290M205 250h240M205 305h275" stroke="#7f7568" stroke-width="14"/><path d="m495 325 77 75" stroke="#c9a45c" stroke-width="24"/>';
|
|
} else if (type === "portrait") {
|
|
background = "#d7c9b5";
|
|
content = '<path d="M0 400h700v50H0Z" fill="#17314a"/><circle cx="355" cy="165" r="90" fill="#d7b79a"/><path d="M265 150c20-95 170-120 205 5-39-27-71-37-111-37-43 0-70 10-94 32Z" fill="#6b594a"/><path d="M210 450c22-165 78-245 145-245s123 80 145 245Z" fill="#1b2b3a"/><path d="m295 230 60 90 60-90 37 220H258Z" fill="#eff0ec"/><path d="m356 318 24 132h-49Z" fill="#9f2930"/>';
|
|
} else if (type === "visit") {
|
|
background = "#9db2bd";
|
|
content = '<path d="M0 390c180-80 385-95 700-20v80H0Z" fill="#405f54"/><g transform="translate(145 105)"><path d="M-50 300h510" stroke="#e6e1d3" stroke-width="16"/><path d="M0 282V120h408v162" fill="#e6e3da"/><path d="M-30 124h468L204 0Z" fill="#d8d4c8"/><g fill="#faf8ef" stroke="#aaa" stroke-width="3"><rect x="27" y="154" width="48" height="113"/><rect x="111" y="154" width="48" height="113"/><rect x="195" y="154" width="48" height="113"/><rect x="279" y="154" width="48" height="113"/></g></g>';
|
|
} else if (type === "letter") {
|
|
background = "#15314c";
|
|
content = '<path d="M85 90h530v300H85Z" fill="#e8e1d4"/><path d="m85 90 265 185L615 90" stroke="#a7282f" stroke-width="16" fill="none"/><circle cx="350" cy="275" r="58" fill="#c9a45c"/>';
|
|
} else if (type === "service") {
|
|
background = "#d6cab7";
|
|
content = '<circle cx="350" cy="155" r="90" fill="#b29272"/><path d="M110 450c34-165 112-240 240-240s206 75 240 240Z" fill="#1e3c57"/><g fill="#f2eee5"><circle cx="95" cy="85" r="20"/><circle cx="590" cy="110" r="18"/><circle cx="100" cy="320" r="16"/></g>';
|
|
}
|
|
return '<svg viewBox="0 0 700 450" preserveAspectRatio="xMidYMid slice" role="img" aria-label="' + escapeHTML(title) + '"><rect width="700" height="450" fill="' + background + '"/>' + content + "</svg>";
|
|
};
|
|
|
|
let themeInitialized = false;
|
|
const syncTheme = () => qs("#themeToggle").setAttribute("aria-label", document.body.classList.contains("dark") ? "切换为浅色模式" : "切换为深色模式");
|
|
const applyInitialTheme = () => {
|
|
if (themeInitialized) return;
|
|
themeInitialized = true;
|
|
const stored = readStorage(themeKey);
|
|
const configured = pageData.site.theme;
|
|
const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme:dark)").matches;
|
|
const dark = stored === "dark" || (!stored && (configured === "dark" || (configured === "auto" && prefersDark)));
|
|
document.body.classList.toggle("dark", dark);
|
|
syncTheme();
|
|
};
|
|
const toggleTheme = () => {
|
|
const dark = document.body.classList.toggle("dark");
|
|
writeStorage(themeKey, dark ? "dark" : "light");
|
|
syncTheme();
|
|
note(dark ? pageData.navigation.themeDarkLabel : pageData.navigation.themeLightLabel);
|
|
};
|
|
const linksMarkup = (items, className = "") => (items || []).map((item) => '<a class="' + className + '" href="' + safeHref(item.href) + '">' + escapeHTML(item.label) + "</a>").join("");
|
|
|
|
const renderSite = () => {
|
|
const data = pageData.site;
|
|
document.documentElement.lang = data.language || "zh-CN";
|
|
document.title = data.pageTitle || data.brandName || "美国白宫";
|
|
qs('meta[name="description"]').content = data.description || "";
|
|
qs("#skipLink").textContent = data.skipLabel || "";
|
|
qs("#brandName").textContent = data.brandName || "";
|
|
qs("#officeName").textContent = data.officeName || "";
|
|
qs("#wordmark").setAttribute("aria-label", (data.brandName || "") + "首页");
|
|
qs("#footerBrand").textContent = data.brandName || "";
|
|
qs("#menuBrand").textContent = data.brandName || "";
|
|
qs("#searchBrand").textContent = data.brandName || "";
|
|
applyInitialTheme();
|
|
};
|
|
const renderNavigation = () => {
|
|
const data = pageData.navigation;
|
|
qs("#menuButtonLabel").textContent = data.menuLabel || "";
|
|
qs("#menuOpen").setAttribute("aria-label", data.menuLabel || "打开菜单");
|
|
qs("#searchOpen").setAttribute("aria-label", data.searchLabel || "搜索");
|
|
qs("#leftNav").innerHTML = linksMarkup(data.leftLinks, "nav-link");
|
|
qs("#rightNav").innerHTML = linksMarkup(data.rightLinks, "nav-link");
|
|
const menu = data.menu || {};
|
|
qs("#menuEyebrow").textContent = menu.eyebrow || "";
|
|
qs("#menuTitle").textContent = menu.title || "";
|
|
qs("#menuText").textContent = menu.text || "";
|
|
qs("#menuCta").textContent = menu.ctaLabel || "";
|
|
qs("#menuCta").href = safeHref(menu.ctaHref);
|
|
qs("#menuColumns").innerHTML = (menu.columns || []).map((column) => '<nav class="menu-col"><h3>' + escapeHTML(column.title) + "</h3>" + (column.links || []).map((link) => '<a href="' + safeHref(link.href) + '" data-close-menu>' + escapeHTML(link.label) + "</a>").join("") + "</nav>").join("");
|
|
const search = data.search || {};
|
|
qs("#searchTitle").textContent = search.title || "";
|
|
qs("#searchInput").placeholder = search.placeholder || "";
|
|
};
|
|
const renderHero = () => {
|
|
const data = pageData.hero;
|
|
qs("#heroArt").innerHTML = externalMediaMarkup(data.media, data.title) || heroArt();
|
|
qs("#heroKicker").textContent = data.kicker || "";
|
|
qs("#heroTitle").innerHTML = escapeHTML(data.title) + "<span>" + escapeHTML(data.subtitle) + "</span>";
|
|
qs("#heroSummary").textContent = data.summary || "";
|
|
qs("#heroPrimary").textContent = data.primaryAction?.label || "";
|
|
qs("#heroPrimary").href = safeHref(data.primaryAction?.href);
|
|
qs("#heroLive span").textContent = data.liveActionLabel || "";
|
|
const brief = data.brief || {};
|
|
qs("#briefLabel").textContent = brief.label || "";
|
|
qs("#briefTime").textContent = brief.time || "";
|
|
qs("#briefTitle").textContent = brief.title || "";
|
|
qs("#briefSummary").textContent = brief.summary || "";
|
|
qs("#scrollLabel").textContent = data.scrollLabel || "";
|
|
const modal = data.liveModal || {};
|
|
qs("#liveTitle").textContent = modal.title || "";
|
|
qs("#liveStreamTitle").textContent = modal.streamTitle || "";
|
|
qs("#liveStreamSubtitle").textContent = modal.streamSubtitle || "";
|
|
qs("#liveLocation").textContent = modal.location || "";
|
|
qs("#captionToggle").textContent = modal.captionsOn || "字幕:已开启";
|
|
};
|
|
const renderNotice = () => {
|
|
const data = pageData.notice;
|
|
qs("#noticeLabel").textContent = data.label || "";
|
|
qs("#noticeText").textContent = data.text || "";
|
|
qs("#noticeText").href = safeHref(data.href);
|
|
qs("#noticeDate").textContent = data.date || "";
|
|
};
|
|
const renderUpdates = () => {
|
|
const data = pageData.updates;
|
|
qs("#updatesEyebrow").textContent = data.eyebrow || "";
|
|
qs("#updatesTitle").textContent = data.title || "";
|
|
qs("#updatesSummary").textContent = data.summary || "";
|
|
qs("#newsGrid").innerHTML = (data.items || []).map((item, index) => '<article class="news-card' + (index === 0 ? " feature" : "") + '"><div class="card-art">' + visualSvg(item.media || item.visual, item.title) + '</div><div class="news-type">' + escapeHTML(item.type) + "</div><h3>" + escapeHTML(item.title) + "</h3><p>" + escapeHTML(item.summary) + "</p><time>" + escapeHTML(item.date) + "</time></article>").join("");
|
|
};
|
|
let activePriority = "";
|
|
const renderPriorities = () => {
|
|
const data = pageData.priorities;
|
|
const items = data.items || [];
|
|
if (!items.some((item) => item.id === activePriority)) activePriority = items[0]?.id || "";
|
|
qs("#prioritiesEyebrow").textContent = data.eyebrow || "";
|
|
qs("#prioritiesTitle").textContent = data.title || "";
|
|
qs("#prioritiesSummary").textContent = data.summary || "";
|
|
qs("#priorityGrid").innerHTML = items.map((item, index) => '<button class="priority' + (item.id === activePriority ? " active" : "") + '" data-priority="' + escapeHTML(item.id) + '"><span class="priority-arrow"><svg viewBox="0 0 24 24"><path d="m9 6 6 6-6 6"/></svg></span><span class="priority-no">' + String(index + 1).padStart(2, "0") + "</span><h3>" + escapeHTML(item.title) + "</h3><p>" + escapeHTML(item.summary) + "</p></button>").join("");
|
|
const selected = items.find((item) => item.id === activePriority) || items[0] || {};
|
|
qs("#priorityTitle").textContent = selected.title || "";
|
|
qs("#priorityText").textContent = selected.detail || "";
|
|
qs("#priorityAgenda").textContent = data.agendaLabel || "";
|
|
qs("#priorityAgenda").href = safeHref(data.agendaHref);
|
|
};
|
|
const renderAdministration = () => {
|
|
const data = pageData.administration;
|
|
qs("#adminArt").innerHTML = visualSvg(data.media || "portrait", data.title);
|
|
qs("#adminEyebrow").textContent = data.eyebrow || "";
|
|
qs("#adminTitle").textContent = data.title || "";
|
|
qs("#adminQuote").textContent = data.quote || "";
|
|
qs("#adminDescription").textContent = data.description || "";
|
|
qs("#adminSignature").textContent = data.signature || "";
|
|
qs("#adminLinks").innerHTML = linksMarkup(data.links);
|
|
};
|
|
let activeMonth = 0;
|
|
const renderCalendar = () => {
|
|
const data = pageData.calendar;
|
|
const months = data.months || [];
|
|
if (activeMonth >= months.length) activeMonth = 0;
|
|
qs("#calendarEyebrow").textContent = data.eyebrow || "";
|
|
qs("#calendarTitle").textContent = data.title || "";
|
|
qs("#countdownValue").textContent = data.countdownValue || "";
|
|
qs("#countdownLabel").textContent = data.countdownLabel || "";
|
|
qs("#calendarPanelEyebrow").textContent = data.panelEyebrow || "";
|
|
qs("#calendarPanelTitle").textContent = data.panelTitle || "";
|
|
qs("#calendarPanelText").textContent = data.panelText || "";
|
|
const month = months[activeMonth];
|
|
qs("#monthLabel").textContent = month?.label || "";
|
|
qs("#events").innerHTML = (month?.events || []).map((item) => '<article class="event"><div class="event-date"><b>' + escapeHTML(item.day) + "</b><span>" + escapeHTML(item.month) + "</span></div><div><h3>" + escapeHTML(item.title) + "</h3><p>" + escapeHTML(item.summary) + '</p></div><span class="event-tag">' + escapeHTML(item.tag) + "</span></article>").join("");
|
|
};
|
|
const renderParticipation = () => {
|
|
const data = pageData.participation;
|
|
qs("#participationEyebrow").textContent = data.eyebrow || "";
|
|
qs("#participationTitle").textContent = data.title || "";
|
|
qs("#participationSummary").textContent = data.summary || "";
|
|
qs("#participationGrid").innerHTML = (data.cards || []).map((item) => '<article class="involve-card"><div class="involve-bg">' + visualSvg(item.media || item.visual, item.title) + '</div><div class="involve-copy"><span>' + escapeHTML(item.kicker) + "</span><h3>" + escapeHTML(item.title) + "</h3><p>" + escapeHTML(item.summary) + '</p><a href="' + safeHref(item.actionHref) + '">' + escapeHTML(item.actionLabel) + "</a></div></article>").join("");
|
|
const newsletter = data.newsletter || {};
|
|
qs("#newsletterTitle").textContent = newsletter.title || "";
|
|
qs("#newsletterText").textContent = newsletter.text || "";
|
|
qs("#email").placeholder = newsletter.placeholder || "";
|
|
qs("#newsletterButton").textContent = newsletter.button || "";
|
|
};
|
|
const renderFooter = () => {
|
|
const data = pageData.footer;
|
|
qs("#footerDescription").textContent = data.description || "";
|
|
qs("#footerColumns").innerHTML = (data.columns || []).map((column) => '<nav class="foot-col"><h3>' + escapeHTML(column.title) + "</h3>" + (column.links || []).map((link) => '<a href="' + safeHref(link.href) + '"' + (/live/i.test(link.label) ? ' class="open-live"' : "") + ">" + escapeHTML(link.label) + "</a>").join("") + "</nav>").join("");
|
|
qs("#copyright").textContent = data.copyright || "";
|
|
qs("#legal").textContent = data.legal || "";
|
|
};
|
|
|
|
const renderAll = () => {
|
|
renderSite();
|
|
renderNavigation();
|
|
renderHero();
|
|
renderNotice();
|
|
renderUpdates();
|
|
renderPriorities();
|
|
renderAdministration();
|
|
renderCalendar();
|
|
renderParticipation();
|
|
renderFooter();
|
|
bindDynamicInteractions();
|
|
};
|
|
|
|
const siteHead = qs("#siteHead");
|
|
window.addEventListener("scroll", () => siteHead.classList.toggle("scrolled", window.scrollY > 80), {passive: true});
|
|
qs("#themeToggle").addEventListener("click", toggleTheme);
|
|
const menuOverlay = qs("#menuOverlay");
|
|
const searchOverlay = qs("#searchOverlay");
|
|
const liveOverlay = qs("#liveOverlay");
|
|
let lastFocus = null;
|
|
const openLayer = (layer, focusTarget) => {
|
|
lastFocus = document.activeElement;
|
|
layer.classList.add("open");
|
|
document.body.style.overflow = "hidden";
|
|
window.setTimeout(() => focusTarget?.focus(), 20);
|
|
};
|
|
const closeLayer = (layer) => {
|
|
layer.classList.remove("open");
|
|
document.body.style.overflow = "";
|
|
if (lastFocus) lastFocus.focus();
|
|
};
|
|
qs("#menuOpen").addEventListener("click", () => openLayer(menuOverlay, qs("#menuClose")));
|
|
qs("#menuClose").addEventListener("click", () => closeLayer(menuOverlay));
|
|
qs("#searchOpen").addEventListener("click", () => openLayer(searchOverlay, qs("#searchInput")));
|
|
qs("#searchClose").addEventListener("click", () => closeLayer(searchOverlay));
|
|
qs("#liveClose").addEventListener("click", () => closeLayer(liveOverlay));
|
|
[menuOverlay, searchOverlay, liveOverlay].forEach((layer) => layer.addEventListener("click", (event) => { if (event.target === layer) closeLayer(layer); }));
|
|
const bindDynamicInteractions = () => {
|
|
qsa("[data-close-menu]").forEach((link) => link.addEventListener("click", () => closeLayer(menuOverlay)));
|
|
qsa(".open-live").forEach((button) => button.addEventListener("click", (event) => { event.preventDefault(); openLayer(liveOverlay, qs("#liveClose")); }));
|
|
qsa("[data-priority]").forEach((button) => button.addEventListener("click", () => { activePriority = button.dataset.priority; renderPriorities(); bindDynamicInteractions(); }));
|
|
};
|
|
const collectStrings = (value, output = []) => {
|
|
if (typeof value === "string" && !value.startsWith("#")) output.push(value);
|
|
else if (Array.isArray(value)) value.forEach((item) => collectStrings(item, output));
|
|
else if (isObject(value)) Object.values(value).forEach((item) => collectStrings(item, output));
|
|
return output;
|
|
};
|
|
qs("#searchForm").addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
const raw = qs("#searchInput").value.trim();
|
|
const query = raw.toLocaleLowerCase();
|
|
const search = pageData.navigation.search || {};
|
|
const count = query ? collectStrings(pageData).filter((value) => value.toLocaleLowerCase().includes(query)).length : 0;
|
|
qs("#searchResult").textContent = query ? count + " " + (search.resultPrefix || "条相关结果,关键词为") + "“" + raw + "”" : (search.emptyMessage || "");
|
|
});
|
|
qs("#captionToggle").addEventListener("click", (event) => {
|
|
const modal = pageData.hero.liveModal || {};
|
|
const isOn = event.currentTarget.textContent === modal.captionsOn;
|
|
event.currentTarget.textContent = isOn ? modal.captionsOff : modal.captionsOn;
|
|
note(isOn ? "字幕已关闭" : "字幕已开启");
|
|
});
|
|
qs("#nextMonth").addEventListener("click", () => {
|
|
const length = pageData.calendar.months?.length || 1;
|
|
activeMonth = (activeMonth + 1) % length;
|
|
renderCalendar();
|
|
});
|
|
qs("#prevMonth").addEventListener("click", () => {
|
|
const length = pageData.calendar.months?.length || 1;
|
|
activeMonth = (activeMonth - 1 + length) % length;
|
|
renderCalendar();
|
|
});
|
|
qs("#subForm").addEventListener("submit", (event) => {
|
|
event.preventDefault();
|
|
const email = qs("#email").value.trim();
|
|
qs("#subStatus").textContent = (pageData.participation.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.style.overflow = "hidden";
|
|
window.setTimeout(() => jsonEditor.focus(), 80);
|
|
};
|
|
const closeSettings = () => {
|
|
settingsOverlay.classList.remove("open");
|
|
settingsOverlay.setAttribute("aria-hidden", "true");
|
|
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;
|
|
activePriority = "";
|
|
activeMonth = 0;
|
|
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 = "white-house-page-data.json";
|
|
link.click();
|
|
window.setTimeout(() => URL.revokeObjectURL(link.href), 0);
|
|
note("JSON 已下载");
|
|
});
|
|
document.addEventListener("keydown", (event) => {
|
|
if (event.key === "Escape") {
|
|
[menuOverlay, searchOverlay, liveOverlay].forEach((layer) => { if (layer.classList.contains("open")) closeLayer(layer); });
|
|
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();
|
|
})();
|