260 lines
39 KiB
JavaScript
260 lines
39 KiB
JavaScript
(() => {
|
|
"use strict";
|
|
const MODULES=["site","navigation","breaking","lead","edition","features","news","opinion","media","footer"];
|
|
const MODULE_META={site:"站点信息",navigation:"页面导航",breaking:"速报新闻",lead:"头条新闻",edition:"数字报纸",features:"重点专题",news:"分类新闻",opinion:"社论生活",media:"视频订阅",footer:"页面页脚"};
|
|
const node=(id)=>document.getElementById(id),clone=(value)=>JSON.parse(JSON.stringify(value));
|
|
const initialText=node("yomiuriNewsPageData").textContent,initialData=JSON.parse(initialText);
|
|
const fingerprint=(()=>{let hash=2166136261;for(let i=0;i<initialText.length;i+=1){hash^=initialText.charCodeAt(i);hash=Math.imul(hash,16777619)}return(hash>>>0).toString(36)})();
|
|
const dataKey="yomiuri-news-page-data-v1:"+fingerprint,viewKey="yomiuri-news-page-view-v1:"+fingerprint;
|
|
const readStorage=(key)=>{try{return window.localStorage.getItem(key)}catch(_error){return null}},writeStorage=(key,value)=>{try{window.localStorage.setItem(key,value);return true}catch(_error){return false}},removeStorage=(key)=>{try{window.localStorage.removeItem(key)}catch(_error){/* optional */}};
|
|
let data=clone(initialData);try{const saved=readStorage(dataKey);if(saved)data=JSON.parse(saved)}catch(_error){data=clone(initialData)}
|
|
let activeCategory="society",paperIndex=0,captionsOn=true,currentModule=MODULES[0],toastTimer=0;
|
|
const esc=(value)=>String(value??"").replace(/[&<>'"]/g,(char)=>({"&":"&","<":"<",">":">","'":"'",'"':"""})[char]),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??""},setLink=(id,label,href)=>{const el=node(id);if(el){el.textContent=label??"";el.href=safeHref(href)}};
|
|
document.head.insertAdjacentHTML("beforeend",'<style data-external-media>.external-media{position:relative;overflow:hidden}.external-media::before,.external-media::after{display:none!important}.external-media>img,.external-media>video,.external-media>iframe{position:relative;z-index:1;width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}.external-media>iframe{object-fit:initial}.external-open{position:absolute;right:10px;bottom:10px;z-index:4;padding:7px 11px;color:#fff;background:rgba(0,0,0,.72);text-decoration:none;font-size:12px;font-weight:700}.external-copy{position:absolute;left:10px;right:10px;bottom:10px;z-index:4;padding:9px;color:#fff;background:rgba(0,0,0,.72);text-decoration:none}.external-copy strong,.external-copy span{display:block}.external-copy span{margin-top:3px;font-size:12px}</style>');
|
|
const 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?`<img src="${esc(source)}" alt="${esc(media.alt||label||"新闻图片")}" loading="lazy" referrerpolicy="no-referrer">${page?`<a class="external-open" href="${esc(page)}" target="_blank" rel="noopener noreferrer">打开来源</a>`:""}`:""}if(media.type==="video"){const source=safeRemoteUrl(media.mediaUrl,"video"),poster=safeRemoteUrl(media.posterUrl,"image");return source?`<video src="${esc(source)}"${poster?` poster="${esc(poster)}"`:""} controls playsinline preload="metadata" aria-label="${esc(media.alt||label||"新闻视频")}"></video>`:""}if(media.type==="webpage"){const page=safeRemoteUrl(media.pageUrl),preview=safeRemoteUrl(media.mediaUrl,"image");if(!page)return"";const body=media.embed===true?`<iframe src="${esc(page)}" title="${esc(media.title||"网页预览")}" loading="lazy" referrerpolicy="no-referrer" sandbox="allow-forms allow-popups allow-scripts"></iframe>`:(preview?`<img src="${esc(preview)}" alt="${esc(media.alt||media.title||"网页预览图")}" loading="lazy" referrerpolicy="no-referrer">`:"");return`${body}<a class="external-copy" href="${esc(page)}" target="_blank" rel="noopener noreferrer"><strong>${esc(media.title||label||"打开网页")}</strong><span>${esc(media.description||"新窗口打开")}</span></a>`}return""};
|
|
const art=(item,className,mediaPath="")=>{const mediaMarkup=externalMedia(item.media,item.title),path=mediaPath?` data-media-path="${esc(mediaPath)}"`:"";return `<div class="${className}${mediaMarkup?" external-media":""}" data-visual="${esc(item.visual)}"${path} aria-hidden="${mediaMarkup?"false":"true"}">${mediaMarkup}</div>`};
|
|
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(".mega.open,.search-overlay.open,.modal.open,.settings-overlay.open"))document.body.classList.remove("locked")}
|
|
const actionLink=(item)=>item.action?`<button data-action="${esc(item.action)}">${esc(item.label)}</button>`:`<a href="${esc(safeHref(item.href))}">${esc(item.label)}</a>`;
|
|
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("dateWeather",data.site.dateWeather);setText("brandPrimary",data.site.brandPrimary);setText("brandRoman",data.site.brandRoman);setText("subscribeButton",data.site.subscribeLabel);setText("fontSmall",data.site.fontNormal);setText("fontLarge",data.site.fontLarge);setText("memberButton",data.site.memberLabel);setText("megaBrand",`${data.site.brandPrimary} ${data.site.brandRoman}`);document.body.classList.toggle("large",readStorage(viewKey)==="large");node("fontSmall").classList.toggle("active",!document.body.classList.contains("large"));node("fontLarge").classList.toggle("active",document.body.classList.contains("large"))}
|
|
function renderNavigation(){node("topLeft").innerHTML=data.navigation.topLeft.map(actionLink).join("");node("topRight").innerHTML=data.navigation.topRight.map(actionLink).join("");node("primaryNav").innerHTML=data.navigation.primary.map((item,index)=>`<a class="${index===0?"active":""}" href="${esc(safeHref(item.href))}">${esc(item.label)}</a>`).join("")+`<button class="menu-open" id="menuOpen">${esc(data.navigation.menuLabel)}</button>`;node("mega").querySelector(".close").setAttribute("aria-label",data.navigation.menuCloseLabel);node("megaGrid").innerHTML=data.navigation.megaColumns.map((column)=>`<nav class="mega-col"><h3>${esc(column.title)}</h3>${column.links.map(actionLink).join("")}</nav>`).join("");setText("searchTitle",data.navigation.searchTitle);node("searchInput").placeholder=data.navigation.searchPlaceholder;setText("searchResult",data.navigation.searchHint);node("searchOverlay").querySelector(".close").setAttribute("aria-label",data.navigation.searchCloseLabel);setText("loginTitle",data.navigation.loginTitle);setText("loginHeading",data.navigation.loginHeading);setText("loginNote",data.navigation.loginNote);setText("loginEmailLabel",data.navigation.emailLabel);setText("loginPasswordLabel",data.navigation.passwordLabel);setText("loginButton",data.navigation.loginButton);node("loginModal").querySelector(".close").setAttribute("aria-label",data.navigation.loginCloseLabel)}
|
|
function renderBreaking(){setText("breakingLabel",data.breaking.label);setText("breakingFeatured",data.breaking.featured);const open=node("flashPanel").classList.contains("open");setText("flashToggle",open?data.breaking.closeLabel:data.breaking.openLabel);node("flashToggle").setAttribute("aria-expanded",String(open));node("flashList").innerHTML=data.breaking.items.map((item)=>`<article class="flash-item"><time>${esc(item.time)}</time><a href="${esc(safeHref(item.href))}">${esc(item.title)}</a></article>`).join("")}
|
|
function renderLead(){const main=data.lead.main;node("leadMain").innerHTML=`${art(main,"lead-art","lead.main")}<div class="eyebrow">${esc(main.kicker)}</div><h1><a href="#news">${esc(main.title)}</a></h1><p class="dek">${esc(main.summary)}</p><div class="meta"><span>${esc(main.time)}</span><button class="save" data-save aria-label="${esc(main.saveLabel)}">☆</button></div>`;node("leadSides").innerHTML=data.lead.sideStories.map((item,index)=>`<article class="side-story">${art(item,"side-art",`lead.sideStories.${index}`)}<div class="eyebrow">${esc(item.kicker)}</div><h2>${esc(item.title)}</h2><p>${esc(item.summary)}</p></article>`).join("");setText("timelineTitle",data.lead.timelineTitle);node("timelineItems").innerHTML=data.lead.timeline.map((item)=>`<article class="timeline-item"><time>${esc(item.time)}</time><a href="${esc(safeHref(item.href))}">${esc(item.title)}</a></article>`).join("");setLink("timelineMore",data.lead.timelineMoreLabel,data.lead.timelineMoreHref)}
|
|
function renderEdition(){setText("editionBrand",data.edition.brand);setText("editionCover",data.edition.coverTitle);setText("editionTitle",data.edition.title);setText("editionSummary",data.edition.summary);setText("paperButton",data.edition.paperLabel);setText("trialButton",data.edition.trialLabel);setText("paperTitle",data.edition.modalTitle);setText("paperMast",data.edition.brand);setText("paperDate",data.edition.date);node("paperModal").querySelector(".close").setAttribute("aria-label",data.edition.closeLabel);node("paperPrev").setAttribute("aria-label",data.edition.previousLabel);node("paperNext").setAttribute("aria-label",data.edition.nextLabel);renderPaper()}
|
|
function renderPaper(){if(!data.edition.pages.length)return;paperIndex=(paperIndex+data.edition.pages.length)%data.edition.pages.length;const page=data.edition.pages[paperIndex];setText("paperHeadline",page.headline);setText("paperSection",page.section);setText("paperText",page.summary);setText("paperColumns",`${page.summary} ${data.edition.summary} ${page.summary}`);setText("paperCount",`${paperIndex+1} / ${data.edition.pages.length} 页`)}
|
|
function renderFeatures(){setText("featuresTitle",data.features.title);setLink("featuresMore",data.features.moreLabel,data.features.moreHref);const main=data.features.main;node("featureMain").innerHTML=`${art(main,"topic-art","features.main")}<div class="topic-shade"></div><div class="topic-copy"><div class="eyebrow">${esc(main.kicker)}</div><h3>${esc(main.title)}</h3><p>${esc(main.summary)}</p></div>`;node("featureCards").innerHTML=data.features.cards.map((item)=>`<article class="topic-card"><div class="eyebrow">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3><p>${esc(item.summary)}</p></article>`).join("");setText("seriesTitle",data.features.seriesTitle);node("seriesList").innerHTML=data.features.series.map((item)=>`<div class="feature-item"><a href="${esc(safeHref(item.href))}">${esc(item.title)}</a><span>${esc(item.meta)}</span></div>`).join("")}
|
|
function renderNews(){setText("newsTitle",data.news.title);setLink("newsMore",data.news.moreLabel,data.news.moreHref);if(!data.news.tabs.some((tab)=>tab.id===activeCategory))activeCategory=data.news.tabs[0]?.id;node("categoryTabs").innerHTML=data.news.tabs.map((tab)=>`<button class="${tab.id===activeCategory?"active":""}" data-category="${esc(tab.id)}">${esc(tab.label)}</button>`).join("");node("categoryPanels").innerHTML=data.news.tabs.map((tab,tabIndex)=>`<div class="category-panel${tab.id===activeCategory?" active":""}" data-category-panel="${esc(tab.id)}"><article class="category-feature">${art(tab.feature,"category-art",`news.tabs.${tabIndex}.feature`)}<div><div class="eyebrow">${esc(tab.feature.kicker)}</div><h3>${esc(tab.feature.title)}</h3><p>${esc(tab.feature.summary)}</p></div></article><div class="category-list">${tab.items.map((item)=>`<article class="category-item"><div class="eyebrow">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3><span>${esc(item.time)}</span></article>`).join("")}</div></div>`).join("")}
|
|
function renderOpinion(){setText("opinionTitle",data.opinion.title);const editorial=data.opinion.editorial;node("editorial").innerHTML=`<span class="editorial-mark">${esc(editorial.label)}</span><h3>${esc(editorial.title)}</h3><p>${esc(editorial.summary)}</p><a href="${esc(safeHref(editorial.href))}">${esc(editorial.actionLabel)} →</a>`;node("opinionColumns").innerHTML=data.opinion.columns.map((item,index)=>`<article class="column">${art(item,"portrait",`opinion.columns.${index}`)}<h3>${esc(item.title)}</h3><span class="author">${esc(item.author)}</span><p>${esc(item.summary)}</p></article>`).join("");setText("lifeTitle",data.opinion.lifeTitle);node("lifeList").innerHTML=data.opinion.life.map((item,index)=>`<article class="story-row">${art(item,"story-thumb",`opinion.life.${index}`)}<div><div class="eyebrow">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3><p>${esc(item.summary)}</p></div></article>`).join("");setText("cultureTitle",data.opinion.cultureTitle);node("cultureList").innerHTML=data.opinion.culture.map((item)=>`<article class="serial-box"><div class="eyebrow">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3><p>${esc(item.summary)}</p><a href="${esc(safeHref(item.href))}">${esc(item.actionLabel)} →</a></article>`).join("")}
|
|
function renderMedia(){setText("mediaTitle",data.media.title);setLink("mediaMore",data.media.moreLabel,data.media.moreHref);node("videoGrid").innerHTML=data.media.videos.map((item,index)=>`<article class="video-card"><div class="video-art${item.media?" external-media":""}" data-visual="${esc(item.visual)}" data-media-path="media.videos.${index}">${externalMedia(item.media,item.title)}${item.media?.type==="video"?"":`<button class="play" data-video="${esc(item.id)}" aria-label="播放视频:${esc(item.title)}">▶</button>`}</div><div class="video-copy"><span>${esc(item.kicker)}</span><h3>${esc(item.title)}</h3></div></article>`).join("");setText("videoBrand",data.media.modalBrand);setText("videoNote",data.media.modalNote);node("videoModal").querySelector(".close").setAttribute("aria-label",data.media.closeLabel);updateCaption();setText("newsletterTitle",data.media.newsletterTitle);setText("newsletterText",data.media.newsletterText);setText("newsletterLabel",data.media.emailLabel);node("email").placeholder=data.media.emailPlaceholder;setText("newsletterButton",data.media.buttonLabel)}
|
|
function updateCaption(){setText("captionToggle",captionsOn?data.media.captionsOn:data.media.captionsOff)}
|
|
function renderFooter(){setText("footerBrand",data.footer.brand);setText("footerDescription",data.footer.description);node("footerColumns").innerHTML=data.footer.columns.map((column)=>`<nav class="foot-col"><h3>${esc(column.title)}</h3>${column.links.map((item)=>`<a href="${esc(safeHref(item.href))}">${esc(item.label)}</a>`).join("")}</nav>`).join("");setText("copyright",data.footer.copyright);setText("legal",data.footer.legal)}
|
|
function renderAll(){renderSite();renderNavigation();renderBreaking();renderLead();renderEdition();renderFeatures();renderNews();renderOpinion();renderMedia();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(["<script","<iframe","javascript:"].some((token)=>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","action","language","brandRoman","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("除品牌 YOMIURI ONLINE 外,所有读者可见文案必须使用简体中文。")};walk(candidate);return true}
|
|
function renderSettingsTabs(){node("moduleTabs").innerHTML=MODULES.map((name)=>`<button class="module-tab${name===currentModule?" active":""}" data-module="${name}">${MODULE_META[name]}</button>`).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="yomiuri-news-page-data.json";anchor.click();URL.revokeObjectURL(url);setStatus("JSON 下载文件已生成。")}
|
|
node("flashToggle").addEventListener("click",()=>{node("flashPanel").classList.toggle("open");renderBreaking()});node("searchForm").addEventListener("submit",(event)=>{event.preventDefault();const query=node("searchInput").value.trim();setText("searchResult",query?`${data.navigation.searchPrefix}“${query}”。`:data.navigation.searchEmpty)});node("loginForm").addEventListener("submit",(event)=>{event.preventDefault();setText("loginStatus",data.navigation.loginResult)});node("fontSmall").addEventListener("click",()=>{document.body.classList.remove("large");node("fontSmall").classList.add("active");node("fontLarge").classList.remove("active");writeStorage(viewKey,"normal");toast(data.site.fontNormalMessage)});node("fontLarge").addEventListener("click",()=>{document.body.classList.add("large");node("fontLarge").classList.add("active");node("fontSmall").classList.remove("active");writeStorage(viewKey,"large");toast(data.site.fontLargeMessage)});node("paperNext").addEventListener("click",()=>{paperIndex+=1;renderPaper()});node("paperPrev").addEventListener("click",()=>{paperIndex-=1;renderPaper()});node("captionToggle").addEventListener("click",()=>{captionsOn=!captionsOn;updateCaption();toast(captionsOn?data.media.captionsOn:data.media.captionsOff)});node("subForm").addEventListener("submit",(event)=>{event.preventDefault();const email=node("email").value.trim();setText("subStatus",`${data.media.successPrefix} ${email}。`);event.currentTarget.reset()});
|
|
document.addEventListener("click",(event)=>{const close=event.target.closest("[data-close]");if(close){closeLayer(close.dataset.close);return}const action=event.target.closest("[data-action]");if(action){const value=action.dataset.action;if(value==="paper")openLayer("paperModal");if(value==="trial")toast(data.site.trialMessage);if(value==="login")openLayer("loginModal");if(value==="search")openLayer("searchOverlay");return}if(event.target.closest("#menuOpen")){openLayer("mega");return}if(event.target.closest("#mobileSearch")){openLayer("searchOverlay");return}if(event.target.closest("[data-login]")){openLayer("loginModal");return}if(event.target.closest("[data-paper]")){renderPaper();openLayer("paperModal");return}if(event.target.closest("[data-trial]")){toast(data.site.trialMessage);return}const save=event.target.closest("[data-save]");if(save){const on=save.classList.toggle("saved");save.textContent=on?"★":"☆";save.setAttribute("aria-label",on?data.lead.main.savedLabel:data.lead.main.saveLabel);toast(on?data.lead.main.savedMessage:data.lead.main.removedMessage);return}const category=event.target.closest("[data-category]");if(category){activeCategory=category.dataset.category;renderNews();return}const video=event.target.closest("[data-video]");if(video){const item=data.media.videos.find((value)=>value.id===video.dataset.video);setText("videoTitle",item?.title||data.media.title);captionsOn=true;updateCaption();openLayer("videoModal");return}const module=event.target.closest("[data-module]");if(module&&module.closest("#moduleTabs"))showModule(module.dataset.module)});
|
|
["mega","searchOverlay","loginModal","paperModal","videoModal","settingsOverlay"].forEach((id)=>node(id).addEventListener("click",(event)=>{if(event.target===node(id))closeLayer(id)}));document.addEventListener("keydown",(event)=>{if(event.key==="Escape"){["mega","searchOverlay","loginModal","paperModal","videoModal","settingsOverlay"].forEach((id)=>{if(node(id).classList.contains("open"))closeLayer(id)});node("flashPanel").classList.remove("open")}});window.addEventListener("scroll",()=>document.body.classList.toggle("sticky",scrollY>260),{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(viewKey);activeCategory="society";paperIndex=0;captionsOn=true;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;index<text.length;index+=1){const char=text[index];if(quoted){if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char==='"')quoted=false;continue}if(char==='"'){quoted=true;continue}if(char==="{")stack.push(index);else if(char==="}"){const start=stack.pop();if(start===undefined||cursor<start||cursor>index+1)continue;try{const value=JSON.parse(text.slice(start,index+1)),own=(key)=>Object.prototype.hasOwnProperty.call(value,key);if(value&&!Array.isArray(value)&&(own("media")||own("visual")||(own("id")&&(own("text")||own("title"))&&(own("author")||own("channel")||own("user")))))matches.push({start,end:index+1,value})}catch(_error){/* full validator handles malformed JSON */}}}return matches.sort((left,right)=>(left.end-left.start)-(right.end-right.start))[0]||null};
|
|
button.addEventListener("click",()=>{input.value="";report("请选择图片或视频;文件会写入光标所在内容对象的 media 字段。");input.click()});
|
|
input.addEventListener("change",()=>{const file=input.files&&input.files[0];if(!file)return;const type=file.type.startsWith("image/")?"image":file.type.startsWith("video/")?"video":"";if(!type){report("仅支持图片或视频文件。");return}const target=findTarget(editor.value,editor.selectionStart);if(!target){report("请先把光标放进带 visual/media 的内容对象,或带 id 的帖子/视频对象内。");return}const reader=new FileReader();reader.onerror=()=>report("文件读取失败,请重新选择。");reader.onload=()=>{const previous=target.value.media&&typeof target.value.media==="object"?target.value.media:{},media={type,mediaUrl:String(reader.result)};for(const key of ["alt","label","caption","pageUrl"])if(typeof previous[key]==="string")media[key]=previous[key];if(!media.alt)media.alt=type==="image"?"用户上传的图片":"用户上传的视频";target.value.media=media;const lineStart=editor.value.lastIndexOf("\n",target.start-1)+1,indent=(editor.value.slice(lineStart,target.start).match(/^\s*/)||[""])[0],replacement=JSON.stringify(target.value,null,2).split("\n").map((line,index)=>index?indent+line:line).join("\n");editor.value=editor.value.slice(0,target.start)+replacement+editor.value.slice(target.end);editor.dispatchEvent(new Event("input",{bubbles:true}));const mediaIndex=replacement.indexOf('"media"');editor.focus();editor.setSelectionRange(target.start+Math.max(mediaIndex,0),target.start+Math.max(mediaIndex,0));report(`已把 ${file.name} 写入 JSON,请点击“应用并渲染”。${file.size>2*1024*1024?" 文件较大,建议同时下载 JSON 保存。":""}`)};reader.readAsDataURL(file)});
|
|
}
|
|
installJsonMediaUpload();
|
|
function installInlineMediaReplace() {
|
|
if (document.getElementById("dfInlineMediaInput")) return;
|
|
const visualHostSelector = "[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 = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 16V4m0 0L7.5 8.5M12 4l4.5 4.5"/><path d="M5 14v4a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4"/></svg>';
|
|
button.addEventListener("click", (event) => {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
active = { ...target };
|
|
input.accept = "image/*,video/*";
|
|
input.value = "";
|
|
input.click();
|
|
});
|
|
host.appendChild(button);
|
|
};
|
|
const decorateBuiltInVisuals = () => {
|
|
document.querySelectorAll(visualHostSelector).forEach((host) => {
|
|
if (host.querySelector("img[src],video[src],iframe[src],:scope > .df-inline-media-button")) return;
|
|
if (!host.querySelector("svg") && !host.dataset.visual) return;
|
|
const target = chooseVisualTarget(host);
|
|
if (!target) return;
|
|
attachButton(host, target);
|
|
});
|
|
};
|
|
const decorate = () => {
|
|
decorateBuiltInVisuals();
|
|
document.querySelectorAll("img[src],video[src]").forEach((media) => {
|
|
if (media.dataset.dfInlineMediaReady === "true") return;
|
|
const target = chooseTarget(media);
|
|
if (!target) return;
|
|
const host = media.closest(visualHostSelector) || media.parentElement;
|
|
if (!host) return;
|
|
media.dataset.dfInlineMediaReady = "true";
|
|
attachButton(host, target);
|
|
});
|
|
};
|
|
input.addEventListener("change", () => {
|
|
const file = input.files && input.files[0];
|
|
if (!file || !active) return;
|
|
const uploadedType = file.type.startsWith("image/") ? "image" : file.type.startsWith("video/") ? "video" : "";
|
|
if (!uploadedType) {
|
|
notify("请选择图片或视频文件。");
|
|
return;
|
|
}
|
|
const reader = new FileReader();
|
|
reader.onerror = () => notify("文件读取失败,请重新选择。");
|
|
reader.onload = () => {
|
|
const next = { ...(active.previous || {}) };
|
|
const result = String(reader.result);
|
|
next.type = uploadedType;
|
|
next.mediaUrl = result;
|
|
delete next.posterUrl;
|
|
if (!next.alt) next.alt = uploadedType === "video" ? "用户上传的视频" : "用户上传的图片";
|
|
active.owner.media = next;
|
|
const stored = persist();
|
|
renderAll();
|
|
notify(stored === false ? "媒体已替换;浏览器未能缓存,请下载 JSON 留存。" : "媒体已替换并写入页面 JSON。");
|
|
active = null;
|
|
};
|
|
reader.readAsDataURL(file);
|
|
});
|
|
let queued = false;
|
|
const queueDecorate = () => {
|
|
if (queued) return;
|
|
queued = true;
|
|
requestAnimationFrame(() => { queued = false; decorate(); });
|
|
};
|
|
new MutationObserver(queueDecorate).observe(document.body, { childList: true, subtree: true });
|
|
decorate();
|
|
}
|
|
installInlineMediaReplace();
|
|
})();
|