(() => { "use strict"; const MODULES = ["site", "navigation", "justIn", "lead", "news", "services", "broadcast", "channels", "media", "footer"]; const MODULE_META = {site:"站点信息",navigation:"页面导航",justIn:"即时新闻",lead:"头条新闻",news:"新闻信息流",services:"天气与服务",broadcast:"电视直播",channels:"数据与频道",media:"视频广播",footer:"页面页脚"}; const node = (id) => document.getElementById(id); const clone = (value) => JSON.parse(JSON.stringify(value)); const initialText = node("gmaNewsPageData").textContent; const initialData = JSON.parse(initialText); const fingerprint = (() => { let hash=2166136261; for(let i=0;i>>0).toString(36) })(); const dataKey = "gma-news-page-data-v1:" + fingerprint; const themeKey = "gma-news-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 data = clone(initialData); try { const saved=readStorage(dataKey); if(saved)data=JSON.parse(saved) } catch(_error) { data=clone(initialData) } let weatherMiniIndex=0, activeFeed="latest", activeTopic="transit", activeWeather="manila", activeGame="649", playing=false, captionsOn=true, currentModule=MODULES[0], toastTimer=0; const esc = (value) => String(value??"").replace(/[&<>'"]/g,(char)=>({"&":"&","<":"<",">":">","'":"'",'"':"""})[char]); const safeHref = (value) => typeof value==="string"&&value.startsWith("#")?value:"#main"; const safeRemoteUrl=(value,kind="link")=>{const source=String(value||"").trim();if(!source)return"";const lower=source.toLowerCase();if(kind==="image"&&lower.startsWith("data:image/"))return source;if(kind==="video"&&lower.startsWith("data:video/"))return source;try{const url=new URL(source);return["http:","https:"].includes(url.protocol)?url.href:""}catch(_error){return""}}; const setText = (id,value) => {const el=node(id);if(el)el.textContent=value??""}; const setLink = (id,label,href) => {const el=node(id);if(el){el.textContent=label??"";el.href=safeHref(href)}}; const links = (items,className="") => (items||[]).map((item)=>`${esc(item.label)}`).join(""); document.head.insertAdjacentHTML("beforeend",''); const externalMedia=(media,label)=>{if(!media||typeof media!=="object")return"";if(media.type==="image"){const source=safeRemoteUrl(media.mediaUrl,"image"),page=safeRemoteUrl(media.pageUrl);return source?`${esc(media.alt||label||${page?`打开来源`:""}`:""}if(media.type==="video"){const source=safeRemoteUrl(media.mediaUrl,"video"),poster=safeRemoteUrl(media.posterUrl,"image");return source?``:""}if(media.type==="webpage"){const page=safeRemoteUrl(media.pageUrl),preview=safeRemoteUrl(media.mediaUrl,"image");if(!page)return"";const body=media.embed===true?``:(preview?`${esc(media.alt||media.title||`:"");return`${body}${esc(media.title||label||"打开网页")}${esc(media.description||"新窗口打开")}`}return""}; const art = (visual,className="art",media=null,mediaPath="") => {const mediaMarkup=externalMedia(media,media?.title),path=mediaPath?` data-media-path="${esc(mediaPath)}"`:"";return `
${mediaMarkup}
`}; function toast(message){const el=node("toast");el.textContent=message;el.classList.add("show");clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove("show"),2200)} function renderSite(){ document.documentElement.lang=data.site.language;document.title=data.site.pageTitle;document.querySelector('meta[name="description"]').content=data.site.description; setText("skipLink",data.site.skipLabel);setText("dateLabel",data.site.dateLabel);setText("brandPrimary",data.site.brandPrimary);setText("brandAccent",data.site.brandAccent);setText("brandTagline",data.site.tagline); setText("footerBrandPrimary",data.site.brandPrimary);setText("footerBrandAccent",data.site.brandAccent);setText("footerTagline",data.site.tagline);setText("drawerBrand",`${data.site.brandPrimary} ${data.site.brandAccent}`);setText("searchBrand",`${data.site.brandPrimary} ${data.site.brandAccent}`); const preferred=readStorage(themeKey);document.body.classList.toggle("contrast",preferred==="contrast"||(!preferred&&data.site.theme==="dark"));renderMiniWeather(); } function renderNavigation(){ node("menuOpen").setAttribute("aria-label",data.navigation.menuLabel);setText("liveLabel",data.navigation.liveLabel);node("topLinks").innerHTML=links(data.navigation.topLinks);node("primaryNav").innerHTML=data.navigation.primary.map((item,index)=>`${esc(item.label)}`).join(""); setText("drawerEyebrow",data.navigation.drawer.eyebrow);setText("drawerTitle",data.navigation.drawer.title);setText("drawerText",data.navigation.drawer.text);setLink("drawerCta",data.navigation.drawer.ctaLabel,data.navigation.drawer.ctaHref);node("drawerNav").innerHTML=links(data.navigation.primary,"drawer-link"); setText("searchTitle",data.navigation.search.title);node("searchInput").placeholder=data.navigation.search.placeholder;setText("searchResult",data.navigation.search.hint); } function renderMiniWeather(){const items=data.site.weatherMini;if(!items.length)return;weatherMiniIndex%=items.length;const item=items[weatherMiniIndex];setText("miniCity",`${item.city} · ${item.temp}`);setText("miniSky",item.condition)} function renderJustIn(){setText("justLabel",data.justIn.label);setText("justFeatured",data.justIn.featured);const open=node("justPanel").classList.contains("open");setText("justToggle",open?data.justIn.closeLabel:data.justIn.moreLabel);node("justGrid").innerHTML=data.justIn.items.map((item)=>`
${esc(item.title)}${esc(item.category)}
`).join("")} function renderLead(){ const main=data.lead.main;node("mainStory").innerHTML=`${art(main.visual,"art",main.media,"lead.main")}
${esc(main.kicker)}

${esc(main.title)}

${esc(main.summary)}

`; node("sideStories").innerHTML=data.lead.sideStories.map((item,index)=>`
${art(item.visual,"art",item.media,`lead.sideStories.${index}`)}
${esc(item.kicker)}

${esc(item.title)}

${esc(item.summary)}

`).join(""); node("headlineStrip").innerHTML=data.lead.headlines.map((item)=>`
${esc(item.kicker)}${esc(item.title)}
`).join(""); } function renderNews(){ setText("trackingTitle",data.news.trackingTitle);if(!data.news.topics.some((item)=>item.id===activeTopic))activeTopic=data.news.topics[0]?.id;node("trackingPills").innerHTML=data.news.topics.map((item)=>``).join("");const topic=data.news.topics.find((item)=>item.id===activeTopic)||data.news.topics[0];setText("trackingStatus",`${data.news.trackingStatusPrefix}:${topic.count} · ${topic.label}`); if(!data.news.feeds.some((item)=>item.id===activeFeed))activeFeed=data.news.feeds[0]?.id;node("feedTabs").innerHTML=data.news.feeds.map((feed)=>``).join("");node("feedPanels").innerHTML=data.news.feeds.map((feed,feedIndex)=>`
${feed.items.map((item,itemIndex)=>`
${art(item.visual,"feed-art",item.media,`news.feeds.${feedIndex}.items.${itemIndex}`)}
${esc(item.kicker)}

${esc(item.title)}

${esc(item.summary)}

`).join("")}
`).join(""); setText("trendingTitle",data.news.trendingTitle);setText("trendingLabel",data.news.trendingLabel);node("trendingList").innerHTML=data.news.trendingItems.map((item,index)=>`
${index+1}${esc(item.title)}
`).join(""); } function renderServices(){ setText("weatherTitle",data.services.weatherTitle);setText("weatherLive",data.services.weatherLiveLabel);if(!data.services.locations.some((item)=>item.id===activeWeather))activeWeather=data.services.locations[0]?.id;node("weatherSelect").innerHTML=data.services.locations.map((item)=>``).join("");const weather=data.services.locations.find((item)=>item.id===activeWeather)||data.services.locations[0];setText("weatherTemp",weather.temp);setText("weatherCondition",weather.condition);node("forecast").innerHTML=weather.forecast.map((item)=>`
${esc(item.day)}${esc(item.temp)}${esc(item.label)}
`).join("");setText("publicTitle",data.services.publicTitle);node("serviceLinks").innerHTML=data.services.publicItems.map((item)=>``).join(""); } function renderBroadcast(){ const hero=data.broadcast.hero,mediaMarkup=externalMedia(hero.media,hero.title),broadcastArt=node("broadcastArt"),stage=broadcastArt.closest(".tv-stage");broadcastArt.className=`tv-art${mediaMarkup?" external-media":""}`;broadcastArt.dataset.visual=hero.visual;broadcastArt.dataset.mediaPath="broadcast.hero";broadcastArt.setAttribute("aria-hidden",mediaMarkup?"false":"true");broadcastArt.innerHTML=mediaMarkup;stage.classList.toggle("has-external-media",Boolean(mediaMarkup));setText("broadcastTitle",data.broadcast.title);setLink("broadcastMore",data.broadcast.moreLabel,data.broadcast.moreHref);setText("broadcastEyebrow",data.broadcast.eyebrow);setText("broadcastHeroTitle",hero.title);setText("broadcastHeroSummary",hero.summary);setText("watchLive",`▶ ${hero.actionLabel}`);setText("scheduleTitle",data.broadcast.scheduleTitle);node("scheduleSlots").innerHTML=data.broadcast.slots.map((item)=>`
${esc(item.title)}${esc(item.summary)}
`).join("");setText("playerBrand",data.broadcast.modal.brand);setText("playerQuality",data.broadcast.modal.quality);updateCaption(); } function renderChannels(){ setText("glanceTitle",data.channels.glanceTitle);setLink("glanceMore",data.channels.glanceMoreLabel,data.channels.glanceMoreHref);node("glanceGrid").innerHTML=data.channels.glanceItems.map((item)=>`
${esc(item.kicker)}
${esc(item.value)}

${esc(item.text)}

${esc(item.actionLabel)} →
`).join("");setText("deskTitle",data.channels.deskTitle);setLink("deskMore",data.channels.deskMoreLabel,data.channels.deskMoreHref);node("channelGrid").innerHTML=data.channels.deskItems.map((item,index)=>`
${art(item.visual,"channel-art",item.media,`channels.deskItems.${index}`)}
${esc(item.kicker)}

${esc(item.title)}

${esc(item.summary)}

`).join(""); } function renderMedia(){ setText("videosTitle",data.media.videosTitle);setLink("videosMore",data.media.videosMoreLabel,data.media.videosMoreHref);node("videoGrid").innerHTML=data.media.videos.map((item,index)=>`
${externalMedia(item.media,item.title)}${esc(item.duration)}
${esc(item.kicker)}

${esc(item.title)}

${esc(item.summary)}

`).join("");setText("podcastEyebrow",data.media.podcast.eyebrow);setText("podcastTitle",data.media.podcast.title);setText("podcastText",data.media.podcast.text);node("audioPlay").setAttribute("aria-label",playing?data.media.podcast.pauseLabel:data.media.podcast.playLabel);setText("audioPlay",playing?"Ⅱ":"▶");setText("audioTime",playing?data.media.podcast.playingTime:data.media.podcast.startTime);node("audioProgress").style.width=playing?"57%":"38%"; if(!data.media.lotto.games.some((item)=>item.id===activeGame))activeGame=data.media.lotto.games[0]?.id;setText("lottoEyebrow",data.media.lotto.eyebrow);setText("lottoTitle",data.media.lotto.title);node("lottoTabs").innerHTML=data.media.lotto.games.map((item)=>``).join("");const game=data.media.lotto.games.find((item)=>item.id===activeGame)||data.media.lotto.games[0];node("lottoBalls").innerHTML=game.numbers.map((number)=>`${esc(number)}`).join("");setText("lottoNote",`${game.label} · ${data.media.lotto.date}`); setText("newsletterTitle",data.media.newsletter.title);setText("newsletterText",data.media.newsletter.text);setText("newsletterLabel",data.media.newsletter.label);node("email").placeholder=data.media.newsletter.placeholder;setText("newsletterButton",data.media.newsletter.button); } function renderFooter(){setText("footerDescription",data.footer.description);node("footerColumns").innerHTML=data.footer.columns.map((column)=>``).join("");setText("footerCopyright",data.footer.copyright);setText("footerLegal",data.footer.legal)} function renderAll(){renderSite();renderNavigation();renderJustIn();renderLead();renderNews();renderServices();renderBroadcast();renderChannels();renderMedia();renderFooter()} function openLayer(id){const el=node(id);el.classList.add("open");document.body.classList.add("locked")} function closeLayer(id){node(id).classList.remove("open");if(!document.querySelector(".drawer.open,.search-overlay.open,.player-modal.open,.settings-overlay.open"))document.body.classList.remove("locked")} function openPlayer(id){const item=data.media.videos.find((video)=>video.id===id);const isMain=id===data.lead.main.id;setText("playerTitle",item?.title||data.broadcast.modal.title);setText("playerNote",item?.summary||(isMain?data.lead.main.summary:data.broadcast.modal.note));captionsOn=true;updateCaption();openLayer("playerModal")} function updateCaption(){setText("captionToggle",captionsOn?data.broadcast.modal.captionsOn:data.broadcast.modal.captionsOff)} function searchStories(){const raw=node("searchInput").value.trim();const query=raw.toLowerCase();const strings=[];const walk=(value)=>{if(Array.isArray(value))value.forEach(walk);else if(value&&typeof value==="object")Object.values(value).forEach(walk);else if(typeof value==="string")strings.push(value)};walk(data);const count=query?strings.filter((value)=>value.toLowerCase().includes(query)).length:0;setText("searchResult",query?`${count}${data.navigation.search.resultPrefix}“${raw}”`:data.navigation.search.emptyMessage)} function validateClient(candidate){ if(!candidate||typeof candidate!=="object"||Array.isArray(candidate))throw new Error("顶层 JSON 必须是对象。");const keys=Object.keys(candidate),missing=MODULES.filter((name)=>!keys.includes(name)),extra=keys.filter((name)=>!MODULES.includes(name));if(missing.length)throw new Error(`缺少模块:${missing.join("、")}`);if(extra.length)throw new Error(`存在未知模块:${extra.join("、")}`);MODULES.forEach((name)=>{if(!candidate[name]||typeof candidate[name]!=="object"||Array.isArray(candidate[name]))throw new Error(`${name} 必须是对象。`)});const text=JSON.stringify(candidate).toLowerCase();if(["text.includes(token)))throw new Error("不允许使用 HTML 或脚本。");const validateMedia=(value,path="当前模块")=>{if(Array.isArray(value))return value.forEach((item,index)=>validateMedia(item,`${path}[${index}]`));if(!value||typeof value!=="object")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")validateMedia(item,`${path}.${key}`)})};validateMedia(candidate);if(candidate.site.language!=="zh-CN")throw new Error("site.language 必须是 zh-CN。");const technical=new Set(["id","href","visual","theme","language","brandPrimary","type","mediaUrl","posterUrl","pageUrl"]);const check=(value,key="")=>{if(Array.isArray(value))value.forEach((item)=>check(item,key));else if(value&&typeof value==="object")Object.entries(value).forEach(([child,item])=>check(item,child));else if(typeof value==="string"&&!technical.has(key)&&!key.toLowerCase().endsWith("id")&&!key.toLowerCase().endsWith("href")&&!key.toLowerCase().endsWith("url")&&/[A-Za-z]/.test(value)&&!/[\u3400-\u9fff]/.test(value))throw new Error("除品牌缩写 GMA 外,所有读者可见文案必须使用简体中文。")};check(candidate);return true; } function renderSettingsTabs(){node("moduleTabs").innerHTML=MODULES.map((name)=>``).join("");showModule(currentModule)} function showModule(name){currentModule=name;node("moduleTabs").querySelectorAll("button").forEach((button)=>button.classList.toggle("active",button.dataset.module===name));setText("editorModule",MODULE_META[name]);node("jsonEditor").value=JSON.stringify(data[name],null,2);setText("jsonValidity","JSON 有效")} function parseEditor(){try{const value=JSON.parse(node("jsonEditor").value);if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("当前模块必须是对象。");setText("jsonValidity","JSON 有效");return value}catch(error){setText("jsonValidity","JSON 无效");throw error}} const setStatus=(message)=>setText("settingsStatus",message); function applyEditor(){try{const candidate={...data,[currentModule]:parseEditor()};validateClient(candidate);data=candidate;writeStorage(dataKey,JSON.stringify(data));renderAll();renderSettingsTabs();setStatus("JSON 已应用并完成渲染。") }catch(error){setStatus(error.message);setText("jsonValidity","JSON 无效")}} async function copyJson(){const candidate={...data,[currentModule]:parseEditor()};validateClient(candidate);const text=JSON.stringify(candidate,null,2);try{await navigator.clipboard.writeText(text);setStatus("完整 JSON 已复制。") }catch(_error){node("jsonEditor").select();document.execCommand("copy");setStatus("已选中当前模块,可手动复制。")}} function downloadJson(){const candidate={...data,[currentModule]:parseEditor()};validateClient(candidate);const blob=new Blob([JSON.stringify(candidate,null,2)+"\n"],{type:"application/json"}),url=URL.createObjectURL(blob),anchor=document.createElement("a");anchor.href=url;anchor.download="gma-news-page-data.json";anchor.click();URL.revokeObjectURL(url);setStatus("JSON 下载文件已生成。")} node("justToggle").addEventListener("click",()=>{const open=node("justPanel").classList.toggle("open");node("justToggle").setAttribute("aria-expanded",String(open));renderJustIn()}); node("weatherMini").addEventListener("click",()=>{weatherMiniIndex+=1;renderMiniWeather();toast(`天气已切换至${data.site.weatherMini[weatherMiniIndex%data.site.weatherMini.length].city}`)}); node("menuOpen").addEventListener("click",()=>openLayer("drawer"));node("searchOpen").addEventListener("click",()=>{openLayer("searchOverlay");setTimeout(()=>node("searchInput").focus(),0)});node("liveButton").addEventListener("click",()=>openPlayer("live"));node("watchLive").addEventListener("click",()=>openPlayer("live")); node("contrastToggle").addEventListener("click",()=>{const on=document.body.classList.toggle("contrast");writeStorage(themeKey,on?"contrast":"standard");toast(on?data.navigation.contrastOnLabel:data.navigation.contrastOffLabel)}); node("weatherSelect").addEventListener("change",(event)=>{activeWeather=event.target.value;renderServices();toast(`天气已更新为${event.target.options[event.target.selectedIndex].text}`)}); node("searchForm").addEventListener("submit",(event)=>{event.preventDefault();searchStories()});node("captionToggle").addEventListener("click",()=>{captionsOn=!captionsOn;updateCaption();toast(captionsOn?data.broadcast.modal.captionsOn:data.broadcast.modal.captionsOff)}); node("audioPlay").addEventListener("click",()=>{playing=!playing;renderMedia();toast(playing?data.media.podcast.playLabel:data.media.podcast.pauseLabel)});node("subForm").addEventListener("submit",(event)=>{event.preventDefault();const email=node("email").value.trim();setText("subStatus",`${data.media.newsletter.successPrefix} ${email}。`);event.currentTarget.reset()}); document.addEventListener("click",(event)=>{const close=event.target.closest("[data-close]");if(close){closeLayer(close.dataset.close);return}const topic=event.target.closest("[data-topic]");if(topic){activeTopic=topic.dataset.topic;renderNews();return}const feed=event.target.closest("[data-feed]");if(feed){activeFeed=feed.dataset.feed;renderNews();return}const service=event.target.closest("[data-service]");if(service){const item=data.services.publicItems.find((value)=>value.id===service.dataset.service);if(item)toast(item.message);return}const player=event.target.closest("[data-player]");if(player){openPlayer(player.dataset.player);return}const game=event.target.closest("[data-game]");if(game){activeGame=game.dataset.game;renderMedia();return}const module=event.target.closest("[data-module]");if(module&&module.closest("#moduleTabs")){showModule(module.dataset.module)}}); ["drawer","searchOverlay","playerModal","settingsOverlay"].forEach((id)=>node(id).addEventListener("click",(event)=>{if(event.target===node(id))closeLayer(id)}));document.addEventListener("keydown",(event)=>{if(event.key==="Escape"){["drawer","searchOverlay","playerModal","settingsOverlay"].forEach((id)=>{if(node(id).classList.contains("open"))closeLayer(id)});node("justPanel").classList.remove("open")}});window.addEventListener("scroll",()=>document.body.classList.toggle("sticky",window.scrollY>220),{passive:true}); node("openSettings").addEventListener("click",()=>{renderSettingsTabs();setStatus("");openLayer("settingsOverlay")});node("validateJson").addEventListener("click",()=>{try{const candidate={...data,[currentModule]:parseEditor()};validateClient(candidate);setStatus("完整 JSON 校验通过。")}catch(error){setStatus(error.message)}});node("copyJson").addEventListener("click",()=>copyJson().catch((error)=>setStatus(error.message)));node("downloadJson").addEventListener("click",()=>{try{downloadJson()}catch(error){setStatus(error.message)}});node("resetJson").addEventListener("click",()=>{data=clone(initialData);removeStorage(dataKey);removeStorage(themeKey);currentModule=MODULES[0];activeFeed="latest";activeTopic="transit";activeWeather="manila";activeGame="649";playing=false;renderAll();renderSettingsTabs();setStatus("已恢复内嵌初始 JSON。")});node("applyJson").addEventListener("click",applyEditor); validateClient(data);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 = "[data-media-path],.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 exactPathTarget = (element) => { const host = element.closest("[data-media-path]"); const path = host && host.dataset ? host.dataset.mediaPath : ""; if (!path) return null; const owner = path.split(".").reduce((value, segment) => { if (Array.isArray(value)) return value[Number(segment)]; return value && typeof value === "object" ? value[segment] : null; }, getRootData()); if (!owner || typeof owner !== "object" || Array.isArray(owner)) return null; return { owner, previous: owner.media && typeof owner.media === "object" ? owner.media : { type: "image" }, key: "mediaUrl" }; }; const chooseVisualTarget = (element) => { const exact = exactPathTarget(element); if (exact) return exact; 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 exact = exactPathTarget(element); if (exact) return exact; 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(); })();