(() => {
"use strict";
const qs = (selector, root = document) => root.querySelector(selector);
const qsa = (selector, root = document) => Array.from(root.querySelectorAll(selector));
const clone = (value) => JSON.parse(JSON.stringify(value));
const MODULES = ["site", "navigation", "categories", "videos", "shorts", "subscriptions", "comments"];
const MODULE_META = {
site: ["站点信息", "品牌、标题与当前账号"],
navigation: ["导航", "主导航、资料库与移动导航"],
categories: ["分类", "顶部筛选标签"],
videos: ["视频", "横屏视频卡片和观看数据"],
shorts: ["Shorts", "竖屏短视频列表"],
subscriptions: ["订阅", "侧栏订阅频道"],
comments: ["评论", "观看弹窗评论"]
};
const NAV_ICONS = new Set(["i-home", "i-shorts", "i-subscriptions", "i-history", "i-playlist", "i-clock", "i-like", "i-user"]);
const VISUAL_TYPES = new Set(["city", "studio", "food", "mountain", "code", "science", "music", "travel"]);
const embeddedData = JSON.parse(qs("#youtubePageData").textContent);
const initialData = clone(embeddedData);
const fingerprint = (text) => {
let hash = 2166136261;
for (let index = 0; index < text.length; index += 1) {
hash ^= text.charCodeAt(index);
hash = Math.imul(hash, 16777619);
}
return (hash >>> 0).toString(36);
};
const pageFingerprint = fingerprint(JSON.stringify(initialData));
const storageKey = "youtube-page-data-v1:" + pageFingerprint;
const themeKey = "youtube-page-theme-v1:" + pageFingerprint;
const readStorage = (key) => {
try {
return window.localStorage ? window.localStorage.getItem(key) : null;
} catch (_error) {
return null;
}
};
const writeStorage = (key, value) => {
try {
if (window.localStorage) window.localStorage.setItem(key, value);
return true;
} catch (_error) {
return false;
}
};
const removeStorage = (key) => {
try {
if (window.localStorage) window.localStorage.removeItem(key);
} catch (_error) {
/* Sandboxed previews may intentionally deny storage. */
}
};
const isCompleteData = (value) => Boolean(value && MODULES.every((name) => value[name] && typeof value[name] === "object"));
const cachedData = readStorage(storageKey);
let pageData = initialData;
if (cachedData) {
try {
const parsed = JSON.parse(cachedData);
if (isCompleteData(parsed)) pageData = parsed;
} catch (_error) {
pageData = initialData;
}
}
const escapeHTML = (value) => String(value == null ? "" : value).replace(/[&<>'"]/g, (character) => ({
"&": "&", "<": "<", ">": ">", "'": "'", '"': """
})[character]);
const safeHref = (value) => String(value || "#").startsWith("#") ? escapeHTML(value) : "#";
const safeRemoteUrl = (value, kind = "link") => {
const source = String(value || "").trim();
if (!source) return "";
const lowered = source.toLowerCase();
if (kind === "image" && lowered.startsWith("data:image/")) return source;
if (kind === "video" && lowered.startsWith("data:video/")) return source;
try {
const url = new URL(source);
return url.protocol === "http:" || url.protocol === "https:" ? url.href : "";
} catch (_error) { return ""; }
};
const validateRemoteMediaTree = (value, path = "当前模块") => {
if (Array.isArray(value)) return value.forEach((item, index) => validateRemoteMediaTree(item, path + "[" + index + "]"));
if (!value || typeof value !== "object") return;
const media = value.media;
if (media && ["image", "video", "webpage"].includes(media.type)) {
if ((media.type === "image" || media.type === "video") && !safeRemoteUrl(media.mediaUrl, media.type)) throw new Error(path + ".media.mediaUrl 无效");
if (media.type === "webpage" && !safeRemoteUrl(media.pageUrl)) throw new Error(path + ".media.pageUrl 无效");
if (media.posterUrl && !safeRemoteUrl(media.posterUrl, "image")) throw new Error(path + ".media.posterUrl 无效");
}
Object.entries(value).forEach(([key, item]) => { if (key !== "media") validateRemoteMediaTree(item, path + "." + key); });
};
const safeColor = (value, fallback) => /^#[0-9a-f]{6}$/i.test(String(value || "")) ? value : fallback;
const safeIcon = (value) => NAV_ICONS.has(value) ? value : "i-home";
const safeVisual = (value) => VISUAL_TYPES.has(value) ? value : "city";
const icon = (id) => '';
const colors = (person, key) => {
const list = person && Array.isArray(person[key || "colors"]) ? person[key || "colors"] : [];
return [safeColor(list[0], "#6249e7"), safeColor(list[1], "#d946ef")];
};
const avatar = (person, className, initialKey, colorsKey) => {
const pair = colors(person || {}, colorsKey || "colors");
return '' + escapeHTML((person && person[initialKey || "initial"]) || "Y") + "";
};
const formatCount = (value) => {
const number = Number(value) || 0;
if (number >= 10000) return (number / 10000).toFixed(1).replace(".0", "") + "万";
return number.toLocaleString("zh-CN");
};
const palettes = {
city: ["#1e1b4b", "#0f766e", "#fb7185"],
studio: ["#312e81", "#c026d3", "#fbbf24"],
food: ["#7f1d1d", "#ea580c", "#fde68a"],
mountain: ["#164e63", "#0f766e", "#fbbf24"],
code: ["#111827", "#1d4ed8", "#22d3ee"],
science: ["#172554", "#6d28d9", "#67e8f9"],
music: ["#3b0764", "#db2777", "#22d3ee"],
travel: ["#0c4a6e", "#0284c7", "#facc15"]
};
const visualSvg = (type, vertical) => {
const visual = safeVisual(type);
const palette = palettes[visual];
const width = vertical ? 360 : 640;
const height = vertical ? 640 : 360;
let shapes = "";
if (visual === "city") {
shapes = '';
} else if (visual === "mountain" || visual === "travel") {
shapes = '';
} else if (visual === "code") {
shapes = '';
} else if (visual === "food") {
shapes = '';
} else if (visual === "studio") {
shapes = '';
} else if (visual === "science") {
shapes = '';
} else {
shapes = '';
}
return '";
};
document.head.insertAdjacentHTML("beforeend", '');
const mediaMarkup = (media, fallback, title, interactive = false) => {
if (!media || typeof media !== "object") return fallback;
if (media.type === "image") {
const source = safeRemoteUrl(media.mediaUrl, "image");
return source ? '
' : fallback;
}
if (media.type === "video") {
const source = safeRemoteUrl(media.mediaUrl, "video");
const poster = safeRemoteUrl(media.posterUrl, "image");
if (!interactive) {
if (poster) return '
';
return source ? '' : fallback;
}
return source ? '' : fallback;
}
if (media.type === "webpage") {
const pageUrl = safeRemoteUrl(media.pageUrl);
if (!pageUrl) return fallback;
const preview = safeRemoteUrl(media.mediaUrl, "image");
if (!interactive) return preview ? '
' : fallback;
const body = media.embed === true ? '' : (preview ? '
' : fallback);
return body + '打开网页';
}
return fallback;
};
const toast = qs("#toast");
let toastTimer = 0;
const showToast = (message) => {
toast.textContent = message;
toast.classList.add("show");
window.clearTimeout(toastTimer);
toastTimer = window.setTimeout(() => toast.classList.remove("show"), 2800);
};
const saveData = () => writeStorage(storageKey, JSON.stringify(pageData));
let activeCategory = "";
let activeVideoId = null;
const renderSite = () => {
const site = pageData.site;
const user = site.currentUser || {};
document.title = site.pageTitle || site.brand || "YouTube";
qs('meta[name="description"]').content = site.description || "";
qs("#brandText").textContent = site.brand || "YouTube";
qs("#brandLink").setAttribute("aria-label", (site.brand || "YouTube") + " 首页");
qs("#searchInput").placeholder = site.searchPlaceholder || "搜索";
qs("#createButton span").textContent = site.createLabel || "创建";
qs("#headerUser").innerHTML = avatar(user, "header-avatar");
const badge = qs("#notificationBadge");
badge.textContent = String(Math.max(0, Number(user.notifications) || 0));
badge.hidden = !(Number(user.notifications) > 0);
};
const navMarkup = (items, activeFirst) => (Array.isArray(items) ? items : []).map((item, index) => '' + icon(safeIcon(item.icon)) + "" + escapeHTML(item.label) + "").join("");
const renderNavigation = () => {
const navigation = pageData.navigation;
qs("#primaryNav").innerHTML = navMarkup(navigation.primary, true);
qs("#libraryNav").innerHTML = navMarkup(navigation.library, false);
qs("#sideFooter").innerHTML = escapeHTML(navigation.footer || "").replace(/\n/g, "
");
const mobile = Array.isArray(navigation.mobile) ? navigation.mobile : [];
qs("#mobileNav").innerHTML = mobile.map((item, index) => '").join("");
qsa("#mobileNav button").forEach((button) => button.addEventListener("click", () => {
qsa("#mobileNav button").forEach((item) => item.classList.remove("active"));
button.classList.add("active");
}));
};
const renderSubscriptions = () => {
const data = pageData.subscriptions;
qs("#subscriptionTitle").textContent = data.title || "订阅";
const items = Array.isArray(data.items) ? data.items : [];
qs("#subscriptionList").innerHTML = items.map((person) => '
' + avatar(person, "avatar-sm") + '' + escapeHTML(person.name) + "" + escapeHTML(person.handle) + "
").join("");
};
const applyFilters = () => {
const query = qs("#searchInput").value.trim().toLocaleLowerCase();
let visible = 0;
qsa(".video-card").forEach((card) => {
const categoryMatch = !activeCategory || activeCategory === "全部" || card.dataset.category === activeCategory;
const queryMatch = !query || card.dataset.search.toLocaleLowerCase().includes(query) || card.textContent.toLocaleLowerCase().includes(query);
card.hidden = !(categoryMatch && queryMatch);
if (!card.hidden) visible += 1;
});
qs("#emptyState").style.display = visible ? "none" : "block";
};
const renderCategories = () => {
const items = Array.isArray(pageData.categories.items) ? pageData.categories.items : [];
if (!items.includes(activeCategory)) activeCategory = items[0] || "";
qs("#categoryBar").innerHTML = items.map((label) => '").join("");
qsa(".category-chip").forEach((button) => button.addEventListener("click", () => {
activeCategory = button.textContent;
qsa(".category-chip").forEach((item) => item.classList.toggle("active", item === button));
applyFilters();
}));
};
const videoMarkup = (video) => '' + avatar(video, "", "channelInitial", "channelColors") + '
' + escapeHTML(video.title) + "
" + escapeHTML(video.channel) + (video.verified ? '✓' : "") + "
" + escapeHTML(video.views) + " · " + escapeHTML(video.time) + '
";
const renderVideos = () => {
const data = pageData.videos;
qs("#videoSectionTitle").textContent = data.sectionTitle || "推荐视频";
const items = Array.isArray(data.items) ? data.items : [];
qs("#videoGrid").innerHTML = items.map(videoMarkup).join("");
qsa(".video-card").forEach((card) => {
qs(".thumbnail-button", card).addEventListener("click", () => openWatch(card.dataset.videoId));
qs(".more-button", card).addEventListener("click", () => showToast("视频操作菜单已打开"));
});
applyFilters();
};
const renderShorts = () => {
const data = pageData.shorts;
qs("#shortsSectionTitle").textContent = data.sectionTitle || "Shorts";
const items = Array.isArray(data.items) ? data.items : [];
qs("#shortsGrid").innerHTML = items.map((item) => '' + escapeHTML(item.title) + "
" + escapeHTML(item.views) + "
").join("");
qsa(".short-thumb").forEach((button) => button.addEventListener("click", () => openShort(button.dataset.shortId)));
qs("#shorts").hidden = !items.length;
};
const commentMarkup = (comment) => '";
const renderComments = () => {
const comments = pageData.comments;
qs("#commentInput").placeholder = comments.inputPlaceholder || "添加评论…";
qs("#commentsList").innerHTML = (Array.isArray(comments.items) ? comments.items : []).map(commentMarkup).join("");
qsa(".comment-like").forEach((button) => button.addEventListener("click", () => button.classList.toggle("active")));
};
const watchModal = qs("#watchModal");
const setWatchContent = (video) => {
activeVideoId = video.id;
qs("#watchVisual").innerHTML = mediaMarkup(video.media, visualSvg(video.visual, false), video.title, true);
qs("#watchTitle").textContent = video.title;
qs("#watchChannelAvatar").innerHTML = avatar(video, "avatar-lg", "channelInitial", "channelColors");
qs("#watchChannel").textContent = video.channel;
qs("#watchViews").textContent = video.views + " · " + video.time;
qs("#watchMeta").textContent = video.views + " · " + video.time;
qs("#watchDescription").textContent = video.description || "";
qs("#watchLike span").textContent = formatCount((video.metrics || {}).likes);
qs("#commentsTitle").textContent = formatCount((video.metrics || {}).comments) + " " + (pageData.comments.titleSuffix || "条评论");
qs("#watchPlayer").classList.remove("playing");
qs("#subscribeButton").classList.remove("following");
qs("#subscribeButton").textContent = "订阅";
qs("#watchLike").classList.remove("active");
qs("#watchSave").classList.remove("active");
renderComments();
};
const openWatch = (id) => {
const video = pageData.videos.items.find((item) => item.id === id);
if (!video) return;
setWatchContent(video);
watchModal.classList.add("open");
watchModal.setAttribute("aria-hidden", "false");
document.body.classList.add("modal-open");
};
const openShort = (id) => {
const item = pageData.shorts.items.find((short) => short.id === id);
if (!item) return;
setWatchContent({
id: item.id,
title: item.title,
channel: "YouTube Shorts",
channelInitial: "S",
channelColors: ["#ff0033", "#7c3aed"],
views: item.views,
time: "Shorts",
visual: item.visual,
description: item.title,
metrics: { likes: 0, comments: pageData.comments.items.length }
});
watchModal.classList.add("open");
watchModal.setAttribute("aria-hidden", "false");
document.body.classList.add("modal-open");
};
const closeWatch = () => {
watchModal.classList.remove("open");
watchModal.setAttribute("aria-hidden", "true");
document.body.classList.remove("modal-open");
};
const renderAll = () => {
closeWatch();
renderSite();
renderNavigation();
renderSubscriptions();
renderCategories();
renderVideos();
renderShorts();
renderComments();
};
qs("#closeWatch").addEventListener("click", closeWatch);
watchModal.addEventListener("click", (event) => {
if (event.target === watchModal) closeWatch();
});
qs("#watchPlay").addEventListener("click", () => {
const playing = qs("#watchPlayer").classList.toggle("playing");
showToast(playing ? "正在播放" : "已暂停");
});
qs("#subscribeButton").addEventListener("click", (event) => {
const following = event.currentTarget.classList.toggle("following");
event.currentTarget.textContent = following ? "已订阅" : "订阅";
});
qs("#watchLike").addEventListener("click", (event) => event.currentTarget.classList.toggle("active"));
qs("#watchSave").addEventListener("click", (event) => {
const active = event.currentTarget.classList.toggle("active");
showToast(active ? "已保存到稍后观看" : "已取消保存");
});
qs("#commentForm").addEventListener("submit", (event) => {
event.preventDefault();
const input = qs("#commentInput");
const value = input.value.trim();
if (!value) return;
const user = pageData.site.currentUser;
pageData.comments.items.unshift({
id: "comment-" + Date.now(),
name: user.name,
initial: user.initial,
colors: clone(user.colors || []),
text: value,
time: "刚刚",
likes: 0
});
saveData();
renderComments();
input.value = "";
showToast("评论已发布");
});
qs("#menuToggle").addEventListener("click", () => document.body.classList.toggle("sidebar-collapsed"));
qs("#createButton").addEventListener("click", () => showToast("创建入口已打开"));
qs("#searchForm").addEventListener("submit", (event) => {
event.preventDefault();
applyFilters();
});
qs("#searchInput").addEventListener("input", applyFilters);
const themeButton = qs("#themeToggle");
const storedTheme = readStorage(themeKey);
if (storedTheme === "dark" || (!storedTheme && typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches)) {
document.documentElement.dataset.theme = "dark";
}
const syncTheme = () => {
const dark = document.documentElement.dataset.theme === "dark";
themeButton.innerHTML = icon(dark ? "i-sun" : "i-moon");
qs('meta[name="theme-color"]').content = dark ? "#0f0f0f" : "#ffffff";
};
themeButton.addEventListener("click", () => {
const next = document.documentElement.dataset.theme === "dark" ? "light" : "dark";
document.documentElement.dataset.theme = next;
writeStorage(themeKey, next);
syncTheme();
});
const settingsModal = qs("#settingsModal");
const moduleTabs = qs("#moduleTabs");
const jsonEditor = qs("#jsonEditor");
const jsonStatus = qs("#jsonStatus");
let activeModule = "site";
let editorDrafts = clone(pageData);
let settingsOpener = null;
const setEditorStatus = (valid, message) => {
jsonStatus.textContent = message;
jsonStatus.classList.toggle("valid", valid);
jsonStatus.classList.toggle("invalid", !valid);
};
const readEditor = () => {
try {
const parsed = JSON.parse(jsonEditor.value);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("模块必须是 JSON 对象");
validateRemoteMediaTree(parsed);
setEditorStatus(true, "JSON 有效");
return parsed;
} catch (error) {
setEditorStatus(false, "JSON 无效:" + error.message);
return null;
}
};
const saveActiveDraft = () => {
const parsed = readEditor();
if (!parsed) return false;
editorDrafts[activeModule] = parsed;
return true;
};
const loadEditor = () => {
qs("#editorModuleTitle").textContent = MODULE_META[activeModule][0];
jsonEditor.value = JSON.stringify(editorDrafts[activeModule], null, 2);
setEditorStatus(true, "JSON 有效");
};
const renderModuleTabs = () => {
qsa(".module-tab", moduleTabs).forEach((button) => button.remove());
MODULES.forEach((name) => {
const button = document.createElement("button");
button.className = "module-tab" + (name === activeModule ? " active" : "");
button.type = "button";
button.dataset.module = name;
button.innerHTML = "" + MODULE_META[name][0] + "" + name + "";
button.addEventListener("click", () => {
if (name === activeModule || !saveActiveDraft()) return;
activeModule = name;
renderModuleTabs();
loadEditor();
});
moduleTabs.appendChild(button);
});
};
const openSettings = (event) => {
settingsOpener = event.currentTarget;
editorDrafts = clone(pageData);
activeModule = "site";
renderModuleTabs();
loadEditor();
settingsModal.classList.add("open");
settingsModal.setAttribute("aria-hidden", "false");
document.body.classList.add("modal-open");
window.setTimeout(() => jsonEditor.focus(), 40);
};
const closeSettings = () => {
settingsModal.classList.remove("open");
settingsModal.setAttribute("aria-hidden", "true");
document.body.classList.remove("modal-open");
if (settingsOpener) settingsOpener.focus();
};
jsonEditor.addEventListener("input", readEditor);
qs("#openSettings").addEventListener("click", openSettings);
qs("#closeSettings").addEventListener("click", closeSettings);
settingsModal.addEventListener("click", (event) => {
if (event.target === settingsModal) closeSettings();
});
qs("#applyJson").addEventListener("click", () => {
if (!saveActiveDraft() || !isCompleteData(editorDrafts)) return;
pageData = clone(editorDrafts);
saveData();
renderAll();
closeSettings();
showToast("JSON 已应用到页面");
});
qs("#resetJson").addEventListener("click", () => {
editorDrafts = clone(initialData);
activeModule = "site";
removeStorage(storageKey);
renderModuleTabs();
loadEditor();
showToast("已恢复初始 JSON,点击应用后生效");
});
qs("#copyJson").addEventListener("click", async () => {
if (!saveActiveDraft()) return;
const text = JSON.stringify(editorDrafts, null, 2);
try {
if (navigator.clipboard) await navigator.clipboard.writeText(text);
else throw new Error("clipboard unavailable");
showToast("完整 JSON 已复制");
} catch (_error) {
const temporary = document.createElement("textarea");
temporary.value = text;
document.body.appendChild(temporary);
temporary.select();
document.execCommand("copy");
temporary.remove();
showToast("完整 JSON 已复制");
}
});
qs("#downloadJson").addEventListener("click", () => {
if (!saveActiveDraft()) return;
const blob = new Blob([JSON.stringify(editorDrafts, null, 2)], { type: "application/json;charset=utf-8" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "youtube-page-data.json";
link.click();
window.setTimeout(() => URL.revokeObjectURL(link.href), 1000);
});
document.addEventListener("click", (event) => {
const link = event.target.closest('a[href^="#"]');
if (!link) return;
const href = link.getAttribute("href");
const target = href && href.length > 1 ? document.getElementById(href.slice(1)) : null;
if (!target) {
event.preventDefault();
showToast("此页面正在准备中");
}
});
document.addEventListener("keydown", (event) => {
if (event.key !== "Escape") return;
if (settingsModal.classList.contains("open")) closeSettings();
else if (watchModal.classList.contains("open")) closeWatch();
});
renderAll();
syncTheme();
function installJsonMediaUpload(){
const editor=document.getElementById("jsonEditor"),apply=document.getElementById("applyJson");if(!editor||!apply||document.getElementById("uploadJsonMedia"))return;
const actions=apply.parentElement,button=document.createElement("button"),input=document.createElement("input"),reference=actions.querySelector("#downloadJson,#copyJson,#validateJson,#resetJson");
button.type="button";button.id="uploadJsonMedia";button.className=reference?reference.className:apply.className;button.textContent="上传图片/视频";button.title="先把光标放进要替换的内容对象,再选择图片或视频";input.type="file";input.accept="image/*,video/*";input.hidden=true;actions.insertBefore(button,apply);actions.appendChild(input);
const report=(message)=>{const status=document.getElementById("settingsStatus")||document.getElementById("jsonError")||document.getElementById("jsonStatus");if(status)status.textContent=message};
const findTarget=(text,cursor)=>{const stack=[],matches=[];let quoted=false,escaped=false;for(let index=0;indexindex+1)continue;try{const value=JSON.parse(text.slice(start,index+1)),own=(key)=>Object.prototype.hasOwnProperty.call(value,key);if(value&&!Array.isArray(value)&&(own("media")||own("visual")||(own("id")&&(own("text")||own("title"))&&(own("author")||own("channel")||own("user")))))matches.push({start,end:index+1,value})}catch(_error){/* full validator handles malformed JSON */}}}return matches.sort((left,right)=>(left.end-left.start)-(right.end-right.start))[0]||null};
button.addEventListener("click",()=>{input.value="";report("请选择图片或视频;文件会写入光标所在内容对象的 media 字段。");input.click()});
input.addEventListener("change",()=>{const file=input.files&&input.files[0];if(!file)return;const type=file.type.startsWith("image/")?"image":file.type.startsWith("video/")?"video":"";if(!type){report("仅支持图片或视频文件。");return}const target=findTarget(editor.value,editor.selectionStart);if(!target){report("请先把光标放进带 visual/media 的内容对象,或带 id 的帖子/视频对象内。");return}const reader=new FileReader();reader.onerror=()=>report("文件读取失败,请重新选择。");reader.onload=()=>{const previous=target.value.media&&typeof target.value.media==="object"?target.value.media:{},media={type,mediaUrl:String(reader.result)};for(const key of ["alt","label","caption","pageUrl"])if(typeof previous[key]==="string")media[key]=previous[key];if(!media.alt)media.alt=type==="image"?"用户上传的图片":"用户上传的视频";target.value.media=media;const lineStart=editor.value.lastIndexOf("\n",target.start-1)+1,indent=(editor.value.slice(lineStart,target.start).match(/^\s*/)||[""])[0],replacement=JSON.stringify(target.value,null,2).split("\n").map((line,index)=>index?indent+line:line).join("\n");editor.value=editor.value.slice(0,target.start)+replacement+editor.value.slice(target.end);editor.dispatchEvent(new Event("input",{bubbles:true}));const mediaIndex=replacement.indexOf('"media"');editor.focus();editor.setSelectionRange(target.start+Math.max(mediaIndex,0),target.start+Math.max(mediaIndex,0));report(`已把 ${file.name} 写入 JSON,请点击“应用并渲染”。${file.size>2*1024*1024?" 文件较大,建议同时下载 JSON 保存。":""}`)};reader.readAsDataURL(file)});
}
installJsonMediaUpload();
function installInlineMediaReplace() {
if (document.getElementById("dfInlineMediaInput")) return;
const visualHostSelector = ".post-media,.video-visual,.thumbnail-visual,.short-thumb,.watch-visual,.thread-media,.visual,.lead-visual,.mini-visual,.compact-media,.card-art,.story-visual,.art,.video-art,.media-art,.player-stage,.thumbnail,.thumb,.list-thumb,.focus-thumb,.involve-bg,.hero-art,#heroArt,#adminArt";
const getRootData = () => {
if (typeof pageData !== "undefined") return pageData;
if (typeof data !== "undefined") return data;
return null;
};
const input = document.createElement("input");
input.id = "dfInlineMediaInput";
input.type = "file";
input.hidden = true;
document.body.appendChild(input);
const style = document.createElement("style");
style.dataset.dfInlineMediaReplace = "true";
style.textContent = ".df-inline-media-host{position:relative!important}.df-inline-media-button{position:absolute;z-index:40;top:10px;right:10px;width:40px;height:40px;padding:0;border:1px solid rgba(255,255,255,.55);border-radius:50%;display:grid;place-items:center;color:#fff;background:rgba(8,15,28,.78);box-shadow:0 8px 24px rgba(0,0,0,.28);backdrop-filter:blur(8px);cursor:pointer;opacity:0;transform:translateY(-4px);transition:opacity .16s,transform .16s,background .16s}.df-inline-media-button:hover{background:rgba(20,110,240,.92)}.df-inline-media-button svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}.df-inline-media-host:hover>.df-inline-media-button,.df-inline-media-host:focus-within>.df-inline-media-button,.df-inline-media-button:focus-visible{opacity:1;transform:none}@media(hover:none){.df-inline-media-button{opacity:1;transform:none}}.df-inline-media-toast{position:fixed;z-index:2147483647;left:50%;bottom:28px;max-width:min(88vw,520px);padding:10px 14px;border-radius:10px;color:#fff;background:rgba(15,23,42,.94);box-shadow:0 12px 32px rgba(0,0,0,.28);font:600 13px/1.45 system-ui,sans-serif;transform:translateX(-50%)}";
document.head.appendChild(style);
const notify = (message) => {
if (typeof showToast === "function") { showToast(message); return; }
if (typeof toast === "function") { toast(message); return; }
let notice = document.getElementById("dfInlineMediaToast");
if (!notice) {
notice = document.createElement("div");
notice.id = "dfInlineMediaToast";
notice.className = "df-inline-media-toast";
document.body.appendChild(notice);
}
notice.textContent = message;
window.clearTimeout(notice._timer);
notice._timer = window.setTimeout(() => notice.remove(), 2600);
};
const sameSource = (value, source, absolute) => {
if (typeof value !== "string") return false;
if (value === source || value === absolute) return true;
try { return new URL(value, location.href).href === absolute; } catch (_error) { return false; }
};
const findMatches = (source, absolute) => {
const matches = [];
const stack = [];
const visit = (value) => {
if (Array.isArray(value)) { value.forEach(visit); return; }
if (!value || typeof value !== "object") return;
stack.push(value);
Object.entries(value).forEach(([key, item]) => {
if ((key === "mediaUrl" || key === "posterUrl") && sameSource(item, source, absolute)) {
const ancestors = stack.slice(0, -1).reverse();
const owner = ancestors.find((candidate) => candidate && typeof candidate === "object" && !Array.isArray(candidate) && ("id" in candidate || "title" in candidate || "text" in candidate || "name" in candidate || "author" in candidate)) || ancestors[0] || value;
matches.push({ owner, previous: value, key });
}
if (item && typeof item === "object") visit(item);
});
stack.pop();
};
visit(getRootData());
return matches;
};
const visualOwners = () => {
const owners = [];
const seen = new Set();
const visit = (value) => {
if (Array.isArray(value)) { value.forEach(visit); return; }
if (!value || typeof value !== "object") return;
const hasVisual = Object.prototype.hasOwnProperty.call(value, "visual") || (value.media && typeof value.media === "object");
const hasIdentity = ["id", "title", "text", "leadTitle", "feature", "name", "author"].some((key) => typeof value[key] === "string" && value[key].trim());
if (hasVisual && hasIdentity && !seen.has(value)) { seen.add(value); owners.push(value); }
Object.values(value).forEach((item) => { if (item && typeof item === "object") visit(item); });
};
visit(getRootData());
return owners;
};
const domIdentifiers = (element) => {
const values = new Set();
let cursor = element;
for (let depth = 0; cursor && cursor !== document.body && depth < 8; depth += 1, cursor = cursor.parentElement) {
Object.values(cursor.dataset || {}).forEach((value) => { if (value) values.add(String(value)); });
}
return values;
};
const chooseVisualTarget = (element) => {
const identifiers = domIdentifiers(element);
const context = element.closest("article,button,[data-post-id],[data-video-id],[data-short-id],.post,.video-card,.news-card,.story-card,.lead-story,.hero") || element.parentElement || element;
const contextText = String(context.textContent || "").replace(/\s+/g, " ").trim();
const visualNode = element.closest("[data-visual]") || element.querySelector && element.querySelector("[data-visual]");
const visualValue = visualNode && visualNode.dataset ? visualNode.dataset.visual : "";
let best = null;
let bestScore = 0;
visualOwners().forEach((owner) => {
let score = 0;
Object.entries(owner).forEach(([key, value]) => {
if (/id$/i.test(key) && identifiers.has(String(value))) score += 100;
});
["title", "text", "leadTitle", "feature", "visualLabel", "label", "author", "name", "summary"].forEach((key) => {
const value = typeof owner[key] === "string" ? owner[key].trim() : "";
if (value.length >= 2 && contextText.includes(value)) score += Math.min(40, value.length);
});
if (visualValue && owner.visual === visualValue) score += 20;
if (score > bestScore) { best = owner; bestScore = score; }
});
if (!best || bestScore <= 0) return null;
return { owner: best, previous: best.media && typeof best.media === "object" ? best.media : { type: "image" }, key: "mediaUrl" };
};
const chooseTarget = (element) => {
const source = element.getAttribute("src") || "";
const absolute = element.currentSrc || element.src || source;
const matches = findMatches(source, absolute);
if (!matches.length) return null;
const identifiers = domIdentifiers(element);
return matches.find(({ owner }) => Object.entries(owner).some(([key, value]) => /id$/i.test(key) && identifiers.has(String(value)))) || matches[0];
};
const persist = () => {
const root = getRootData();
if (typeof saveData === "function") return saveData();
if (typeof writeStorage === "function" && typeof storageKey !== "undefined") return writeStorage(storageKey, JSON.stringify(root));
if (typeof writeStorage === "function" && typeof dataKey !== "undefined") return writeStorage(dataKey, JSON.stringify(root));
return false;
};
let active = null;
const attachButton = (host, target) => {
if (!host || !target || host.querySelector(":scope > .df-inline-media-button")) return;
host.classList.add("df-inline-media-host");
const button = document.createElement("button");
button.type = "button";
button.className = "df-inline-media-button";
button.setAttribute("aria-label", "替换图片或视频");
button.title = "上传图片或视频并替换";
button.innerHTML = '';
button.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
active = { ...target };
input.accept = "image/*,video/*";
input.value = "";
input.click();
});
host.appendChild(button);
};
const decorateBuiltInVisuals = () => {
document.querySelectorAll(visualHostSelector).forEach((host) => {
if (host.querySelector("img[src],video[src],iframe[src],:scope > .df-inline-media-button")) return;
if (!host.querySelector("svg") && !host.dataset.visual) return;
const target = chooseVisualTarget(host);
if (!target) return;
attachButton(host, target);
});
};
const decorate = () => {
decorateBuiltInVisuals();
document.querySelectorAll("img[src],video[src]").forEach((media) => {
if (media.dataset.dfInlineMediaReady === "true") return;
const target = chooseTarget(media);
if (!target) return;
const host = media.closest(visualHostSelector) || media.parentElement;
if (!host) return;
media.dataset.dfInlineMediaReady = "true";
attachButton(host, target);
});
};
input.addEventListener("change", () => {
const file = input.files && input.files[0];
if (!file || !active) return;
const uploadedType = file.type.startsWith("image/") ? "image" : file.type.startsWith("video/") ? "video" : "";
if (!uploadedType) {
notify("请选择图片或视频文件。");
return;
}
const reader = new FileReader();
reader.onerror = () => notify("文件读取失败,请重新选择。");
reader.onload = () => {
const next = { ...(active.previous || {}) };
const result = String(reader.result);
next.type = uploadedType;
next.mediaUrl = result;
delete next.posterUrl;
if (!next.alt) next.alt = uploadedType === "video" ? "用户上传的视频" : "用户上传的图片";
active.owner.media = next;
const stored = persist();
renderAll();
notify(stored === false ? "媒体已替换;浏览器未能缓存,请下载 JSON 留存。" : "媒体已替换并写入页面 JSON。");
active = null;
};
reader.readAsDataURL(file);
});
let queued = false;
const queueDecorate = () => {
if (queued) return;
queued = true;
requestAnimationFrame(() => { queued = false; decorate(); });
};
new MutationObserver(queueDecorate).observe(document.body, { childList: true, subtree: true });
decorate();
}
installInlineMediaReplace();
})();
" + escapeHTML(comment.text) + "