(() => { "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) => "" + escapeHTML(letter) + "").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", ''); 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 '' + escapeHTML(media.alt || label || ' + (pageUrl ? '打开来源' : ""); } if (media.type === "video") { const source = safeRemoteUrl(media.mediaUrl, "video"); if (!source) return ""; const poster = safeRemoteUrl(media.posterUrl, "image"); return ''; } if (media.type === "webpage") { const pageUrl = safeRemoteUrl(media.pageUrl); if (!pageUrl) return ""; const preview = safeRemoteUrl(media.mediaUrl, "image"); const body = media.embed === true ? '' : (preview ? '' + escapeHTML(media.alt || media.title || ' : ""); return body + '' + escapeHTML(media.title || label || "打开网页") + '' + escapeHTML(media.description || "新窗口打开") + ""; } 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 = ''; } else if (type === "harbor") { background = "#ced9d9"; content = ''; } else if (type === "satellite") { background = "#16191e"; content = ''; } else if (type === "creative-city") { background = "#eadfc8"; content = ''; } else if (type === "station") { background = "#b9d2d7"; content = ''; } else if (type === "studio") { background = "#1f2c3b"; content = ''; } else if (type === "bulletin") { background = "#233344"; content = ''; } else if (type === "ocean") { background = "#326779"; content = ''; } else if (type === "logistics") { background = "#dde4e0"; content = ''; } else if (type === "market") { background = "#d8cbb6"; content = ''; } else if (type === "device") { background = "#163143"; content = ''; } else { background = "#c8d9d1"; content = ''; } return '' + content + ""; }; 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) => '' + escapeHTML(item.label) + "" ).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) + '' + escapeHTML(data.moreLabel) + ' '; 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 = '
' + escapeHTML(data.kicker) + "

" + escapeHTML(data.title) + '

' + escapeHTML(data.summary) + '

' + escapeHTML(data.byline) + "" + escapeHTML(data.time) + '' + escapeHTML(data.section) + '
' + visualSvg(data.media || data.visual, data.visualLabel) + '' + escapeHTML(data.stamp) + '' + escapeHTML(data.credit) + "
"; }; 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) => '" ).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) => '

' + escapeHTML(item.title) + '

' + (item.live ? '正在直播 · ' + escapeHTML(String(item.meta || "").replace(/^正在直播\s*·\s*/, "")) : escapeHTML(item.meta)) + "
" ).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) => '
' + visualSvg(item.media || item.visual, item.title) + '
' + escapeHTML(item.kicker) + "

" + escapeHTML(item.title) + '

' + escapeHTML(item.time) + "
" ).join(""); qs("#rankingTitle").textContent = data.rankingTitle || ""; const ranking = Array.isArray(data.ranking) ? data.ranking : []; qs("#rankingList").innerHTML = ranking.map((item, index) => '" ).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) => '
' + escapeHTML(item.region) + '' + escapeHTML(item.title) + "
" ).join(""); qs("#weatherTitle").textContent = data.weatherTitle || ""; const weather = Array.isArray(data.weather) ? data.weather : []; qs("#weatherGrid").innerHTML = '
' + escapeHTML(data.weatherLabel) + "
" + weather.map((item) => '
' + escapeHTML(item.city) + '
' + escapeHTML(item.temperature) + '
' + escapeHTML(item.condition) + "
" ).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) => '' + escapeHTML(item.label) + "" ).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 = "

页面模块

" + 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.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;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(); })();