(() => {
"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", '');
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 '
' + (pageUrl ? '打开来源' : "");
}
if (media.type === "video") {
const source = safeRemoteUrl(media.mediaUrl, "video");
const poster = safeRemoteUrl(media.posterUrl, "image");
return source ? '' : "";
}
if (media.type === "webpage") {
const pageUrl = safeRemoteUrl(media.pageUrl);
if (!pageUrl) return "";
const preview = safeRemoteUrl(media.mediaUrl, "image");
const body = media.embed === true ? '' : (preview ? '
' : "");
return body + '' + escapeHTML(media.title || label || "打开网页") + '' + escapeHTML(media.description || "新窗口打开") + "";
}
return "";
};
const heroArt = () => '';
const visualSvg = (type, title) => {
if (isObject(type)) {
const external = externalMediaMarkup(type, title);
if (external) return external;
type = "hall";
}
let background = "#d7c9b5";
let content = '';
if (type === "hall") {
background = "#d6c8b3";
content = '';
} else if (type === "mobility") {
background = "#cbd8dc";
content = '';
} else if (type === "science") {
background = "#132941";
content = '';
} else if (type === "statement") {
background = "#e3dacb";
content = '';
} else if (type === "action") {
background = "#17314a";
content = '';
} else if (type === "portrait") {
background = "#d7c9b5";
content = '';
} else if (type === "visit") {
background = "#9db2bd";
content = '';
} else if (type === "letter") {
background = "#15314c";
content = '';
} else if (type === "service") {
background = "#d6cab7";
content = '';
}
return '";
};
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) => '' + escapeHTML(item.label) + "").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) => '").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) + "" + escapeHTML(data.subtitle) + "";
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) => '' + visualSvg(item.media || item.visual, item.title) + '
' + escapeHTML(item.type) + "
" + escapeHTML(item.title) + "
" + escapeHTML(item.summary) + "
").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) => '").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) => '' + escapeHTML(item.day) + "" + escapeHTML(item.month) + "
" + escapeHTML(item.title) + "
" + escapeHTML(item.summary) + '
' + escapeHTML(item.tag) + "").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) => '' + visualSvg(item.media || item.visual, item.title) + '
").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) => '").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 = "
页面模块
" + MODULES.map((name) => '").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;indexindex+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 = '';
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();
})();