(() => { "use strict"; const MODULES = ["site", "search", "services", "news", "account", "weather", "utilities", "shopping", "pulse", "footer"]; const MODULE_META = {site:"站点信息",search:"门户搜索",services:"主要服务",news:"新闻推荐",account:"账户登录",weather:"天气信息",utilities:"交通与行情",shopping:"购物推荐",pulse:"体育与热榜",footer:"抽屉与页脚"}; const node = (id) => document.getElementById(id); const clone = (value) => JSON.parse(JSON.stringify(value)); const initialText = node("yahooJapanPageData").textContent; const initialData = JSON.parse(initialText); const fingerprint = (() => { let hash=2166136261; for(let i=0;i>>0).toString(36) })(); const dataKey = "yahoo-japan-page-data-v1:" + fingerprint; const themeKey = "yahoo-japan-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 activeSearch="web",activeNews="top",activeWeather="tokyo",activeMarket="nikkei",activeSport="baseball",activeTrend="rising",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) => (items||[]).map((item)=>`${esc(item.label)}`).join(""); function toast(message){const el=node("toast");el.textContent=message;el.classList.add("show");clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove("show"),2200)} function openLayer(id){node(id).classList.add("open");document.body.classList.add("locked")} function closeLayer(id){node(id).classList.remove("open");if(!document.querySelector(".drawer.open,.modal.open,.settings-overlay.open"))document.body.classList.remove("locked")} 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("brandPrimary",data.site.brandPrimary);setText("brandAccent",data.site.brandAccent);setText("tagline",data.site.tagline);setText("drawerBrand",`${data.site.brandPrimary} ${data.site.brandAccent}`); node("utilityLeft").innerHTML=`${esc(data.site.dateLabel)}${links(data.site.utilityLeft)}`;node("utilityRight").innerHTML=links(data.site.utilityRight); setText("headerLogin",data.site.loginLabel);setText("mailLabel",data.site.mailLabel);setText("mailCount",data.site.mailCount);node("menuOpen").setAttribute("aria-label",data.site.menuLabel);node("themeToggle").setAttribute("aria-label",data.site.themeLabel); setText("noticeLabel",data.site.notice.label);setLink("noticeLink",data.site.notice.text,data.site.notice.href); const preferred=readStorage(themeKey);document.body.classList.toggle("dark",preferred==="dark"||(!preferred&&data.site.theme==="dark")); } function renderSearch(){ setText("searchTitle",data.search.title);if(!data.search.tabs.some((item)=>item.id===activeSearch))activeSearch=data.search.tabs[0]?.id;node("searchTabs").innerHTML=data.search.tabs.map((item)=>``).join("");const tab=data.search.tabs.find((item)=>item.id===activeSearch)||data.search.tabs[0];node("searchInput").placeholder=`${tab.label}${data.search.placeholderSuffix}`;setText("searchButton",data.search.button);node("suggestions").innerHTML=`${esc(data.search.hotLabel)}${data.search.suggestions.map((item)=>``).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=(item,className,mediaPath="")=>{const mediaMarkup=externalMedia(item.media,item.title),path=mediaPath?` data-media-path="${esc(mediaPath)}"`:"";return `
${mediaMarkup}
`}; const serviceCard=(item)=>`${esc(item.label.slice(0,1))}${esc(item.label)}`; function renderServices(){setText("servicesTitle",data.services.title);setLink("servicesAll",data.services.allLabel,data.services.allHref);node("servicePrimary").innerHTML=data.services.primary.map(serviceCard).join("");node("serviceExtra").innerHTML=data.services.extra.map(serviceCard).join("");const open=node("serviceExtra").classList.contains("open");setText("serviceMore",open?data.services.lessLabel:data.services.moreLabel);node("serviceMore").setAttribute("aria-expanded",String(open))} function renderNews(){ setText("newsTitle",data.news.title);setText("newsUpdated",data.news.updated);if(!data.news.tabs.some((item)=>item.id===activeNews))activeNews=data.news.tabs[0]?.id;node("newsTabs").innerHTML=data.news.tabs.map((tab)=>``).join("");node("newsLists").innerHTML=data.news.tabs.map((tab)=>`
${tab.items.map((item)=>`
${item.tag?`${esc(item.tag)}`:""}${esc(item.title)}${item.isNew?'新':""}
`).join("")}
`).join(""); const feature=data.news.feature;node("newsFeature").innerHTML=`${art(feature,"feature-art","news.feature")}
${esc(feature.kicker)}

${esc(feature.title)}

${esc(feature.summary)}

`;setLink("newsMore",data.news.moreLabel,data.news.moreHref);setLink("newsTopics",data.news.topicsLabel,data.news.topicsHref);setText("recommendTitle",data.news.recommendTitle);setText("recRefresh",data.news.refreshLabel);node("recommendGrid").innerHTML=data.news.recommendations.map((item,index)=>`
${art(item,"rec-art",`news.recommendations.${index}`)}

${esc(item.title)}

${esc(item.category)}
`).join(""); } function renderAccount(){setText("accountTitle",data.account.title);setText("accountText",data.account.text);setText("accountLogin",data.account.loginLabel);setLink("accountNew",data.account.newIdLabel,data.account.newIdHref);setLink("accountProfile",data.account.profileLabel,data.account.profileHref);node("accountStatuses").innerHTML=data.account.statuses.map((item)=>`${esc(item.label)}`).join("");setText("loginModalTitle",data.account.modalTitle);setText("loginWelcome",data.account.welcome);setText("loginNote",data.account.demoNote);setText("emailLabel",data.account.emailLabel);setText("passwordLabel",data.account.passwordLabel);setText("loginSubmit",data.account.submitLabel);node("loginModal").querySelector(".close").setAttribute("aria-label",data.account.closeLabel)} function renderWeather(){setText("weatherTitle",data.weather.title);node("weatherSelect").setAttribute("aria-label",data.weather.regionLabel);if(!data.weather.locations.some((item)=>item.id===activeWeather))activeWeather=data.weather.locations[0]?.id;node("weatherSelect").innerHTML=data.weather.locations.map((item)=>``).join("");const item=data.weather.locations.find((value)=>value.id===activeWeather)||data.weather.locations[0];setText("todayLabel",item.today.label);setText("todayHigh",item.today.high);setText("todayLow",item.today.low);setText("todaySummary",item.today.summary);setText("tomorrowLabel",item.tomorrow.label);setText("tomorrowHigh",item.tomorrow.high);setText("tomorrowLow",item.tomorrow.low);setText("tomorrowSummary",item.tomorrow.summary);node("weatherLinks").innerHTML=data.weather.links.map((link)=>``).join("")} function renderUtilities(){const transit=data.utilities.transit;setText("transitTitle",transit.title);setLink("transitDetail",transit.detailLabel,transit.detailHref);setText("transitStatus",transit.status);node("fromStation").placeholder=transit.fromLabel;node("fromStation").setAttribute("aria-label",transit.fromLabel);node("toStation").placeholder=transit.toLabel;node("toStation").setAttribute("aria-label",transit.toLabel);setText("routeButton","→");node("routeButton").setAttribute("aria-label",transit.buttonLabel);if(!node("routeResult").textContent)setText("routeResult",transit.emptyMessage);const finance=data.utilities.finance;setText("financeTitle",finance.title);setLink("financeMore",finance.moreLabel,finance.moreHref);if(!finance.markets.some((item)=>item.id===activeMarket))activeMarket=finance.markets[0]?.id;node("marketTabs").innerHTML=finance.markets.map((item)=>``).join("");const market=finance.markets.find((item)=>item.id===activeMarket)||finance.markets[0];setText("marketValue",market.value);setText("marketChange",market.change);setText("marketUpdated",finance.updated);setText("marketPrevious",`${finance.previousPrefix} ${market.previous}`)} function renderShopping(){setText("shoppingTitle",data.shopping.title);setLink("shoppingMore",data.shopping.moreLabel,data.shopping.moreHref);node("productGrid").innerHTML=data.shopping.products.map((item,index)=>`
${art(item,"product-art",`shopping.products.${index}`)}

${esc(item.title)}

${esc(item.price)}
`).join("")} function renderPulse(){setText("sportsTitle",data.pulse.sportsTitle);setLink("sportsMore",data.pulse.sportsMoreLabel,data.pulse.sportsMoreHref);if(!data.pulse.sportsTabs.some((item)=>item.id===activeSport))activeSport=data.pulse.sportsTabs[0]?.id;node("sportsTabs").innerHTML=data.pulse.sportsTabs.map((tab)=>``).join("");node("scorePanels").innerHTML=data.pulse.sportsTabs.map((tab)=>`
${tab.games.map((game)=>`
${esc(game.home)}
${esc(game.score)}
${esc(game.away)}
`).join("")}
`).join("");setText("trendsTitle",data.pulse.trendsTitle);setText("trendRefresh",data.pulse.refreshLabel);if(!data.pulse.trendTabs.some((item)=>item.id===activeTrend))activeTrend=data.pulse.trendTabs[0]?.id;node("trendTabs").innerHTML=data.pulse.trendTabs.map((tab)=>``).join("");node("trendPanels").innerHTML=data.pulse.trendTabs.map((tab)=>`
${tab.items.map((item)=>`
${esc(item.rank)}${esc(item.title)}${esc(item.meta)}
`).join("")}
`).join("")} function renderFooter(){setText("drawerTitle",data.footer.drawerTitle);setText("drawerText",data.footer.drawerText);node("drawerNav").innerHTML=links(data.footer.drawerLinks);node("footerLinks").innerHTML=links(data.footer.links);setText("copyright",data.footer.copyright);setText("legal",data.footer.legal);node("backTop").setAttribute("aria-label",data.footer.backTopLabel)} function renderAll(){renderSite();renderSearch();renderServices();renderNews();renderAccount();renderWeather();renderUtilities();renderShopping();renderPulse();renderFooter()} 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 raw=JSON.stringify(candidate).toLowerCase();if(["raw.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","brandAccent","value","price","score","change","previous","rank","type","mediaUrl","posterUrl","pageUrl"]);const walk=(value,key="")=>{if(Array.isArray(value))value.forEach((item)=>walk(item,key));else if(value&&typeof value==="object")Object.entries(value).forEach(([child,item])=>walk(item,child));else if(typeof value==="string"&&!technical.has(key)&&!key.toLowerCase().endsWith("id")&&!key.toLowerCase().endsWith("href")&&!key.toLowerCase().endsWith("url")&&(/[\u3040-\u30ff]/.test(value)||(/[A-Za-z]/.test(value)&&!/[\u3400-\u9fff]/.test(value))))throw new Error("除品牌 Yahoo! JAPAN 外,所有读者可见文案必须使用简体中文。")};walk(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="yahoo-japan-page-data.json";anchor.click();URL.revokeObjectURL(url);setStatus("JSON 下载文件已生成。")} node("searchForm").addEventListener("submit",(event)=>{event.preventDefault();const raw=node("searchInput").value.trim(),tab=data.search.tabs.find((item)=>item.id===activeSearch)||data.search.tabs[0];setText("searchStatus",raw?`${data.search.resultPrefix}${tab.label},${data.search.resultKeyword}“${raw}”。`:data.search.emptyMessage)}); node("serviceMore").addEventListener("click",()=>{node("serviceExtra").classList.toggle("open");renderServices()}); node("weatherSelect").addEventListener("change",(event)=>{activeWeather=event.target.value;renderWeather();toast(data.weather.updatedMessage)}); node("routeForm").addEventListener("submit",(event)=>{event.preventDefault();const from=node("fromStation").value.trim(),to=node("toStation").value.trim();setText("routeResult",`${data.utilities.transit.resultPrefix}:${from} → ${to},${data.utilities.transit.resultDetail}`)}); node("loginForm").addEventListener("submit",(event)=>{event.preventDefault();setText("loginStatus",data.account.resultMessage)}); node("themeToggle").addEventListener("click",()=>{const on=document.body.classList.toggle("dark");writeStorage(themeKey,on?"dark":"light");toast(on?data.site.themeDarkMessage:data.site.themeLightMessage)}); node("menuOpen").addEventListener("click",()=>openLayer("drawer"));node("backTop").addEventListener("click",()=>scrollTo({top:0,behavior:"smooth"}));window.addEventListener("scroll",()=>node("backTop").classList.toggle("show",scrollY>500),{passive:true}); document.addEventListener("click",(event)=>{const close=event.target.closest("[data-close]");if(close){closeLayer(close.dataset.close);return}const login=event.target.closest("[data-login]");if(login){if(node("drawer").classList.contains("open"))closeLayer("drawer");openLayer("loginModal");return}const search=event.target.closest("[data-search]");if(search){activeSearch=search.dataset.search;renderSearch();return}const suggestion=event.target.closest("[data-suggestion]");if(suggestion){node("searchInput").value=suggestion.dataset.suggestion;node("searchInput").focus();return}const news=event.target.closest("[data-news]");if(news){activeNews=news.dataset.news;renderNews();return}const weather=event.target.closest("[data-weather-link]");if(weather){const item=data.weather.links.find((value)=>value.id===weather.dataset.weatherLink);if(item)toast(item.message);return}const market=event.target.closest("[data-market]");if(market){activeMarket=market.dataset.market;renderUtilities();return}const product=event.target.closest("[data-product]");if(product){const saved=product.classList.toggle("saved");product.textContent=saved?"♥":"♡";product.setAttribute("aria-label",saved?data.shopping.removeLabel:data.shopping.saveLabel);toast(saved?data.shopping.savedMessage:data.shopping.removedMessage);return}const sport=event.target.closest("[data-sport]");if(sport){activeSport=sport.dataset.sport;renderPulse();return}const trend=event.target.closest("[data-trend]");if(trend){activeTrend=trend.dataset.trend;renderPulse();return}const module=event.target.closest("[data-module]");if(module&&module.closest("#moduleTabs"))showModule(module.dataset.module)}); node("recRefresh").addEventListener("click",()=>{const first=data.news.recommendations.shift();data.news.recommendations.push(first);renderNews();toast(data.news.refreshMessage)});node("trendRefresh").addEventListener("click",()=>toast(data.pulse.refreshMessage)); ["drawer","loginModal","settingsOverlay"].forEach((id)=>node(id).addEventListener("click",(event)=>{if(event.target===node(id))closeLayer(id)}));document.addEventListener("keydown",(event)=>{if(event.key==="Escape")["drawer","loginModal","settingsOverlay"].forEach((id)=>{if(node(id).classList.contains("open"))closeLayer(id)})}); 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);activeSearch="web";activeNews="top";activeWeather="tokyo";activeMarket="nikkei";activeSport="baseball";activeTrend="rising";currentModule=MODULES[0];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(); })();