777 lines
48 KiB
JavaScript
777 lines
48 KiB
JavaScript
(() => {
|
|
"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", "videos", "sidebar", "comments", "share"];
|
|
const MODULE_META = {
|
|
site: ["站点信息", "品牌、标题与当前账号"],
|
|
navigation: ["导航", "侧栏、频道与移动导航"],
|
|
videos: ["短视频", "作者、文案、视觉与互动量"],
|
|
sidebar: ["侧栏推荐", "登录提示与推荐账号"],
|
|
comments: ["评论", "评论抽屉内容"],
|
|
share: ["分享", "分享面板选项"]
|
|
};
|
|
const NAV_ICONS = new Set(["i-home", "i-compass", "i-users", "i-live", "i-user", "i-message", "i-plus"]);
|
|
const SHARE_ICONS = new Set(["i-link", "i-message", "i-code", "i-flag"]);
|
|
const VISUALS = {
|
|
"neon-city": "<svg viewBox=\"0 0 450 800\" preserveAspectRatio=\"xMidYMid slice\"><defs><linearGradient id=\"v1bg\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\"><stop stop-color=\"#2a144c\"/><stop offset=\".55\" stop-color=\"#11224c\"/><stop offset=\"1\" stop-color=\"#06111d\"/></linearGradient><linearGradient id=\"road\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\"><stop stop-color=\"#1f2b42\"/><stop offset=\"1\" stop-color=\"#06090f\"/></linearGradient></defs><rect width=\"450\" height=\"800\" fill=\"url(#v1bg)\"/><circle class=\"pulse\" cx=\"335\" cy=\"145\" r=\"64\" fill=\"#ff668c\" opacity=\".82\"/><g class=\"drift\" opacity=\".55\"><ellipse cx=\"110\" cy=\"160\" rx=\"90\" ry=\"25\" fill=\"#8e86ff\"/><ellipse cx=\"235\" cy=\"215\" rx=\"110\" ry=\"22\" fill=\"#47d9ff\"/></g><g fill=\"#111b33\"><rect x=\"0\" y=\"290\" width=\"82\" height=\"310\"/><rect x=\"70\" y=\"235\" width=\"88\" height=\"365\"/><rect x=\"150\" y=\"320\" width=\"75\" height=\"280\"/><rect x=\"215\" y=\"195\" width=\"108\" height=\"405\"/><rect x=\"314\" y=\"265\" width=\"80\" height=\"335\"/><rect x=\"388\" y=\"220\" width=\"72\" height=\"380\"/></g><g fill=\"#4de5f2\" opacity=\".8\"><rect x=\"25\" y=\"325\" width=\"7\" height=\"38\"/><rect x=\"45\" y=\"385\" width=\"7\" height=\"38\"/><rect x=\"96\" y=\"280\" width=\"10\" height=\"55\"/><rect x=\"123\" y=\"360\" width=\"10\" height=\"55\"/><rect x=\"250\" y=\"245\" width=\"12\" height=\"68\"/><rect x=\"283\" y=\"338\" width=\"12\" height=\"68\"/><rect x=\"345\" y=\"322\" width=\"9\" height=\"52\"/><rect x=\"413\" y=\"272\" width=\"9\" height=\"52\"/></g><g fill=\"#ff4670\" opacity=\".9\"><rect x=\"18\" y=\"445\" width=\"11\" height=\"54\"/><rect x=\"102\" y=\"410\" width=\"11\" height=\"54\"/><rect x=\"185\" y=\"372\" width=\"10\" height=\"47\"/><rect x=\"274\" y=\"445\" width=\"10\" height=\"47\"/><rect x=\"362\" y=\"401\" width=\"10\" height=\"47\"/></g><path d=\"M0 800V560l145-65h160l145 65v240Z\" fill=\"url(#road)\"/><path d=\"m223 570-18 230m18-230 18 230\" stroke=\"#ecf8ff\" stroke-width=\"8\" stroke-dasharray=\"34 28\" opacity=\".8\"/><g class=\"float\"><rect x=\"102\" y=\"585\" width=\"70\" height=\"36\" rx=\"8\" fill=\"#ff365f\"/><rect x=\"112\" y=\"592\" width=\"50\" height=\"17\" rx=\"4\" fill=\"#e9f8ff\" opacity=\".75\"/><ellipse cx=\"116\" cy=\"622\" rx=\"10\" ry=\"5\" fill=\"#090b11\"/><ellipse cx=\"159\" cy=\"622\" rx=\"10\" ry=\"5\" fill=\"#090b11\"/></g><g class=\"drift\"><rect x=\"282\" y=\"675\" width=\"58\" height=\"30\" rx=\"7\" fill=\"#33d9ee\"/><rect x=\"291\" y=\"681\" width=\"40\" height=\"14\" rx=\"3\" fill=\"#e9f8ff\" opacity=\".7\"/></g></svg>",
|
|
"coffee": "<svg viewBox=\"0 0 450 800\" preserveAspectRatio=\"xMidYMid slice\"><defs><linearGradient id=\"v2bg\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"><stop stop-color=\"#f7c874\"/><stop offset=\".55\" stop-color=\"#e87f66\"/><stop offset=\"1\" stop-color=\"#5b315c\"/></linearGradient><radialGradient id=\"coffee\" cx=\"50%\" cy=\"40%\"><stop stop-color=\"#9d6a44\"/><stop offset=\"1\" stop-color=\"#382116\"/></radialGradient></defs><rect width=\"450\" height=\"800\" fill=\"url(#v2bg)\"/><circle class=\"pulse\" cx=\"110\" cy=\"145\" r=\"80\" fill=\"#fff3b5\" opacity=\".68\"/><path d=\"M0 390c150-60 240-25 450-100v510H0Z\" fill=\"#5b315c\" opacity=\".42\"/><g class=\"float\"><rect x=\"55\" y=\"300\" width=\"340\" height=\"340\" rx=\"38\" fill=\"#f9e8cf\" transform=\"rotate(-5 225 470)\"/><ellipse cx=\"235\" cy=\"475\" rx=\"122\" ry=\"90\" fill=\"#d69b6d\" opacity=\".45\"/><circle cx=\"225\" cy=\"435\" r=\"93\" fill=\"#fff7e9\"/><circle cx=\"225\" cy=\"435\" r=\"72\" fill=\"url(#coffee)\"/><path d=\"M165 415c35-42 80-35 120 0-32 10-38 36-60 44-26-6-34-33-60-44Z\" fill=\"#f1d4a2\" opacity=\".8\"/><path d=\"M301 404c68-10 74 84 11 92\" fill=\"none\" stroke=\"#fff7e9\" stroke-width=\"25\" stroke-linecap=\"round\"/></g><g class=\"drift\"><rect x=\"34\" y=\"675\" width=\"160\" height=\"72\" rx=\"12\" fill=\"#23324a\" transform=\"rotate(6 114 711)\"/><rect x=\"50\" y=\"689\" width=\"128\" height=\"8\" rx=\"4\" fill=\"#f07b68\"/><rect x=\"50\" y=\"706\" width=\"95\" height=\"8\" rx=\"4\" fill=\"#f1c46d\"/></g><g class=\"float\"><path d=\"M330 140c35 52 24 100-25 128-8-54-1-95 25-128Z\" fill=\"#417d5d\"/><path d=\"M328 268v72\" stroke=\"#315c48\" stroke-width=\"8\"/></g></svg>",
|
|
"mountain": "<svg viewBox=\"0 0 450 800\" preserveAspectRatio=\"xMidYMid slice\"><defs><linearGradient id=\"v3bg\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\"><stop stop-color=\"#9ec9df\"/><stop offset=\".48\" stop-color=\"#efc796\"/><stop offset=\"1\" stop-color=\"#d46f74\"/></linearGradient><linearGradient id=\"lake\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\"><stop stop-color=\"#4c9291\"/><stop offset=\"1\" stop-color=\"#1b4c5b\"/></linearGradient></defs><rect width=\"450\" height=\"800\" fill=\"url(#v3bg)\"/><circle class=\"pulse\" cx=\"320\" cy=\"165\" r=\"66\" fill=\"#fff1b3\"/><g class=\"drift\" opacity=\".6\" fill=\"#fff\"><ellipse cx=\"100\" cy=\"130\" rx=\"90\" ry=\"20\"/><ellipse cx=\"220\" cy=\"215\" rx=\"115\" ry=\"17\"/></g><path d=\"M-30 500 105 305l90 120 90-190 190 265Z\" fill=\"#54746d\"/><path d=\"m190 425 95-190 47 63-42-14-28 58-32-15Z\" fill=\"#e8eee5\" opacity=\".9\"/><path d=\"M-20 530 125 410l75 75 92-130 180 180v265H-20Z\" fill=\"#285b57\"/><path d=\"M0 555c145-28 250-15 450 8v237H0Z\" fill=\"url(#lake)\"/><path d=\"M0 610c150-28 270-20 450 25M0 680c135-18 275-8 450 35\" fill=\"none\" stroke=\"#b8ded0\" stroke-width=\"6\" opacity=\".42\"/><g class=\"float\"><path d=\"M135 530c25-42 55-42 80 0Z\" fill=\"#ffca61\"/><rect x=\"171\" y=\"530\" width=\"8\" height=\"45\" fill=\"#2c3034\"/><circle cx=\"175\" cy=\"577\" r=\"16\" fill=\"#20252a\"/></g><g class=\"drift\"><path d=\"M300 642c28-10 58-7 82 8-27 7-57 6-82-8Z\" fill=\"#f3e4c8\" opacity=\".85\"/></g></svg>"
|
|
};
|
|
const embeddedData = JSON.parse(qs("#tiktokPageData").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 = "tiktok-page-data-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) => {
|
|
const href = String(value || "#");
|
|
return href.startsWith("#") ? escapeHTML(href) : "#";
|
|
};
|
|
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, allowed, fallback) => allowed.has(value) ? value : fallback;
|
|
const icon = (id) => '<svg aria-hidden="true"><use href="#' + id + '"/></svg>';
|
|
const colors = (person) => {
|
|
const list = person && Array.isArray(person.colors) ? person.colors : [];
|
|
return [safeColor(list[0], "#6249e7"), safeColor(list[1], "#d946ef")];
|
|
};
|
|
const avatar = (person, className) => {
|
|
const pair = colors(person || {});
|
|
return '<span class="avatar ' + (className || "") + '" style="--a:' + pair[0] + ";--b:" + pair[1] + '">' + escapeHTML((person && person.initial) || "T") + "</span>";
|
|
};
|
|
const formatCount = (value) => {
|
|
const number = Number(value) || 0;
|
|
if (number >= 10000) return (number / 10000).toFixed(1).replace(".0", "") + "万";
|
|
return number.toLocaleString("zh-CN");
|
|
};
|
|
|
|
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 sections = [];
|
|
let activeIndex = 0;
|
|
let feedObserver = null;
|
|
|
|
const setActive = (index) => {
|
|
if (!sections.length) return;
|
|
activeIndex = Math.max(0, Math.min(sections.length - 1, index));
|
|
sections.forEach((section, itemIndex) => {
|
|
section.classList.toggle("active", itemIndex === activeIndex);
|
|
const card = qs(".video-card", section);
|
|
const media = qs("video", card);
|
|
if (itemIndex === activeIndex) {
|
|
card.classList.remove("paused");
|
|
if (media) media.play().catch(() => {});
|
|
} else {
|
|
card.classList.add("paused");
|
|
if (media) media.pause();
|
|
}
|
|
});
|
|
};
|
|
const goTo = (index) => {
|
|
if (!sections.length) return;
|
|
const target = Math.max(0, Math.min(sections.length - 1, index));
|
|
sections[target].scrollIntoView({ behavior: "smooth", block: "start" });
|
|
setActive(target);
|
|
};
|
|
|
|
const renderSite = () => {
|
|
const site = pageData.site;
|
|
const user = site.currentUser || {};
|
|
document.title = site.pageTitle || site.brand || "TikTok";
|
|
qs('meta[name="description"]').content = site.description || "";
|
|
qs("#brandLink").setAttribute("aria-label", (site.brand || "TikTok") + " 首页");
|
|
qs("#brandText").textContent = site.brand || "TikTok";
|
|
qs("#feedTitle").textContent = site.feedTitle || "TikTok 短视频推荐流";
|
|
qs("#searchInput").placeholder = site.searchPlaceholder || "搜索";
|
|
qs("#uploadButton span").textContent = site.uploadLabel || "上传";
|
|
qs("#headerUser").innerHTML = avatar(user, "avatar-sm");
|
|
const badge = qs("#notificationBadge");
|
|
badge.textContent = String(Math.max(0, Number(user.notifications) || 0));
|
|
badge.hidden = !(Number(user.notifications) > 0);
|
|
};
|
|
|
|
const renderNavigation = () => {
|
|
const navigation = pageData.navigation;
|
|
const primary = Array.isArray(navigation.primary) ? navigation.primary : [];
|
|
qs("#sideNav").innerHTML = primary.map((item, index) => '<a class="nav-link' + (index === 0 ? " active" : "") + '" href="' + safeHref(item.href) + '">' + icon(safeIcon(item.icon, NAV_ICONS, "i-home")) + "<span>" + escapeHTML(item.label) + "</span></a>").join("");
|
|
const channels = Array.isArray(navigation.channels) ? navigation.channels : [];
|
|
const defaultActive = Math.min(1, Math.max(0, channels.length - 1));
|
|
qs("#channelTabs").innerHTML = channels.map((label, index) => '<button class="channel-tab' + (index === defaultActive ? " active" : "") + '" role="tab" aria-selected="' + (index === defaultActive ? "true" : "false") + '">' + escapeHTML(label) + "</button>").join("");
|
|
qsa(".channel-tab").forEach((tab) => tab.addEventListener("click", () => {
|
|
qsa(".channel-tab").forEach((item) => {
|
|
item.classList.remove("active");
|
|
item.setAttribute("aria-selected", "false");
|
|
});
|
|
tab.classList.add("active");
|
|
tab.setAttribute("aria-selected", "true");
|
|
showToast("已切换到" + tab.textContent);
|
|
}));
|
|
const mobile = Array.isArray(navigation.mobile) ? navigation.mobile : [];
|
|
qs("#mobileNav").innerHTML = mobile.map((item, index) => {
|
|
const itemIcon = safeIcon(item.icon, NAV_ICONS, "i-home");
|
|
if (itemIcon === "i-plus") {
|
|
return '<button aria-label="' + escapeHTML(item.label) + '"><span class="mobile-create">' + icon("i-plus") + '</span><span class="sr-only">' + escapeHTML(item.label) + "</span></button>";
|
|
}
|
|
return '<button class="' + (index === 0 ? "active" : "") + '" aria-label="' + escapeHTML(item.label) + '">' + icon(itemIcon) + "<span>" + escapeHTML(item.label) + "</span></button>";
|
|
}).join("");
|
|
qsa("#mobileNav button").forEach((button) => button.addEventListener("click", () => {
|
|
qsa("#mobileNav button").forEach((item) => item.classList.remove("active"));
|
|
button.classList.add("active");
|
|
}));
|
|
qs("#sideFooter").innerHTML = escapeHTML(navigation.footer || "").replace(/\n/g, "<br />");
|
|
};
|
|
|
|
const renderSidebar = () => {
|
|
const sidebar = pageData.sidebar;
|
|
qs("#loginPrompt").textContent = sidebar.loginPrompt || "";
|
|
qs("#loginButton").textContent = sidebar.loginLabel || "登录";
|
|
qs("#sidebarTitle").textContent = sidebar.title || "推荐关注";
|
|
const recommendations = Array.isArray(sidebar.recommendations) ? sidebar.recommendations : [];
|
|
qs("#sidebarRecommendations").innerHTML = recommendations.map((person) => '<div class="following-row">' + avatar(person, "avatar-sm") + '<span class="following-copy"><strong>' + escapeHTML(person.name) + "</strong><span>" + escapeHTML(person.handle) + "</span></span></div>").join("");
|
|
};
|
|
|
|
document.head.insertAdjacentHTML("beforeend", '<style data-external-media>.video-visual>img,.video-visual>video,.video-visual>iframe{width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}.video-visual>iframe{object-fit:initial}.video-visual .external-page-link{position:absolute;left:16px;right:16px;top:58px;z-index:4;padding:11px 13px;border-radius:12px;color:#fff;background:rgba(0,0,0,.7);text-decoration:none;font-weight:700;backdrop-filter:blur(8px)}.video-visual .external-page-link span{display:block;margin-top:4px;font-size:12px;font-weight:500;opacity:.8}</style>');
|
|
const mediaMarkup = (media, fallback, title) => {
|
|
if (!media || typeof media !== "object") return fallback;
|
|
if (media.type === "image") {
|
|
const source = safeRemoteUrl(media.mediaUrl, "image");
|
|
return source ? '<img src="' + escapeHTML(source) + '" alt="' + escapeHTML(media.alt || title || "短视频图片") + '" loading="lazy" referrerpolicy="no-referrer"/>' : fallback;
|
|
}
|
|
if (media.type === "video") {
|
|
const source = safeRemoteUrl(media.mediaUrl, "video");
|
|
if (!source) return fallback;
|
|
const poster = safeRemoteUrl(media.posterUrl, "image");
|
|
return '<video src="' + escapeHTML(source) + '"' + (poster ? ' poster="' + escapeHTML(poster) + '"' : "") + ' playsinline loop muted preload="metadata" aria-label="' + escapeHTML(media.alt || title || "短视频") + '"></video>';
|
|
}
|
|
if (media.type === "webpage") {
|
|
const pageUrl = safeRemoteUrl(media.pageUrl);
|
|
if (!pageUrl) return fallback;
|
|
const preview = safeRemoteUrl(media.mediaUrl, "image");
|
|
const body = media.embed === true ? '<iframe src="' + escapeHTML(pageUrl) + '" title="' + escapeHTML(media.title || "网页预览") + '" loading="lazy" referrerpolicy="no-referrer" sandbox="allow-forms allow-popups allow-scripts"></iframe>' : (preview ? '<img src="' + escapeHTML(preview) + '" alt="' + escapeHTML(media.alt || media.title || "网页预览图") + '" loading="lazy" referrerpolicy="no-referrer"/>' : fallback);
|
|
return body + '<a class="external-page-link" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer">' + escapeHTML(media.title || "打开网页") + '<span>' + escapeHTML(media.description || pageUrl) + "</span></a>";
|
|
}
|
|
return fallback;
|
|
};
|
|
|
|
const videoMarkup = (video, index) => {
|
|
const metrics = video.metrics || {};
|
|
const tags = Array.isArray(video.tags) ? video.tags : [];
|
|
const tagMarkup = tags.map((tag) => ' <a href="#tag-' + encodeURIComponent(String(tag)) + '">#' + escapeHTML(tag) + "</a>").join("");
|
|
const visual = mediaMarkup(video.media, VISUALS[video.visual] || VISUALS["neon-city"], video.text);
|
|
return '<article class="video-section' + (index === 0 ? " active" : "") + '" data-video-id="' + escapeHTML(video.id) + '" data-search="' + escapeHTML([video.author, video.handle, video.text, video.music].concat(tags).join(" ")) + '"><div class="video-layout"><div class="video-card' + (index === 0 ? "" : " paused") + '" tabindex="0" role="button" aria-label="' + escapeHTML(video.ariaLabel) + '"><div class="video-visual">' + visual + '</div><div class="video-top"><button class="glass-button mute-button" aria-label="静音">' + icon("i-volume") + '</button></div><div class="play-indicator">' + icon("i-play") + '</div><div class="heart-burst">' + icon("i-heart") + '</div><div class="video-copy"><div class="author-line"><strong>' + escapeHTML(video.handle) + '</strong><button class="follow-inline">关注</button></div><p>' + escapeHTML(video.text) + tagMarkup + '</p><div class="music-line">' + icon("i-music") + "<span>" + escapeHTML(video.music) + '</span></div></div><div class="progress"><span></span></div></div><div class="action-rail"><div class="creator-action">' + avatar(video, "") + '<button class="follow-plus" aria-label="关注' + escapeHTML(video.author) + '">' + icon("i-plus") + '</button></div><button class="rail-button like-button"><span class="rail-icon">' + icon("i-heart") + '</span><span class="rail-count">' + formatCount(metrics.likes) + '</span></button><button class="rail-button comment-button"><span class="rail-icon">' + icon("i-comment") + '</span><span class="rail-count">' + formatCount(metrics.comments) + '</span></button><button class="rail-button save-button"><span class="rail-icon">' + icon("i-bookmark") + '</span><span class="rail-count">' + formatCount(metrics.saves) + '</span></button><button class="rail-button share-button"><span class="rail-icon">' + icon("i-share") + '</span><span class="rail-count">分享</span></button><div class="record">' + avatar(video, "") + "</div></div></div></article>";
|
|
};
|
|
|
|
const bindVideo = (section) => {
|
|
const card = qs(".video-card", section);
|
|
let lastTap = 0;
|
|
let tapTimer = 0;
|
|
card.addEventListener("click", (event) => {
|
|
if (event.target.closest("button,a")) return;
|
|
const now = Date.now();
|
|
if (now - lastTap < 330) {
|
|
window.clearTimeout(tapTimer);
|
|
const like = qs(".like-button", section);
|
|
if (!like.classList.contains("liked")) like.click();
|
|
const burst = qs(".heart-burst", card);
|
|
burst.classList.remove("show");
|
|
void burst.offsetWidth;
|
|
burst.classList.add("show");
|
|
} else {
|
|
tapTimer = window.setTimeout(() => {
|
|
const paused = card.classList.toggle("paused");
|
|
const media = qs("video", card);
|
|
if (media) paused ? media.pause() : media.play().catch(() => {});
|
|
}, 340);
|
|
}
|
|
lastTap = now;
|
|
});
|
|
card.addEventListener("keydown", (event) => {
|
|
if (event.key === " " || event.key === "Enter") {
|
|
event.preventDefault();
|
|
const paused = card.classList.toggle("paused");
|
|
const media = qs("video", card);
|
|
if (media) paused ? media.pause() : media.play().catch(() => {});
|
|
}
|
|
});
|
|
qs(".mute-button", section).addEventListener("click", (event) => {
|
|
const button = event.currentTarget;
|
|
const media = qs("video", card);
|
|
const muted = media ? !media.muted : !button.classList.contains("muted");
|
|
if (media) media.muted = muted;
|
|
button.classList.toggle("muted", muted);
|
|
button.innerHTML = icon(muted ? "i-mute" : "i-volume");
|
|
button.setAttribute("aria-label", muted ? "取消静音" : "静音");
|
|
showToast(muted ? "已静音" : "声音已开启");
|
|
});
|
|
qs(".like-button", section).addEventListener("click", (event) => {
|
|
const button = event.currentTarget;
|
|
const liked = button.classList.toggle("liked");
|
|
button.setAttribute("aria-pressed", String(liked));
|
|
showToast(liked ? "已点赞" : "已取消点赞");
|
|
});
|
|
qs(".save-button", section).addEventListener("click", (event) => {
|
|
const saved = event.currentTarget.classList.toggle("saved");
|
|
showToast(saved ? "已收藏" : "已取消收藏");
|
|
});
|
|
qs(".comment-button", section).addEventListener("click", openComments);
|
|
qs(".share-button", section).addEventListener("click", openShare);
|
|
qsa(".follow-inline,.follow-plus", section).forEach((button) => button.addEventListener("click", () => {
|
|
const inline = qs(".follow-inline", section);
|
|
const following = inline.classList.toggle("following");
|
|
inline.textContent = following ? "已关注" : "关注";
|
|
qs(".follow-plus", section).style.visibility = following ? "hidden" : "visible";
|
|
showToast(following ? "关注成功" : "已取消关注");
|
|
}));
|
|
};
|
|
|
|
const applySearch = () => {
|
|
const query = qs("#searchInput").value.trim().toLocaleLowerCase();
|
|
sections.forEach((section) => {
|
|
section.hidden = Boolean(query && !section.dataset.search.toLocaleLowerCase().includes(query));
|
|
});
|
|
};
|
|
|
|
const renderVideos = () => {
|
|
const items = Array.isArray(pageData.videos.items) ? pageData.videos.items : [];
|
|
if (feedObserver) feedObserver.disconnect();
|
|
qs("#feedScroll").innerHTML = items.map(videoMarkup).join("");
|
|
sections = qsa(".video-section");
|
|
activeIndex = 0;
|
|
sections.forEach(bindVideo);
|
|
if (typeof IntersectionObserver === "function") {
|
|
feedObserver = new IntersectionObserver((entries) => {
|
|
const visible = entries.filter((entry) => entry.isIntersecting).sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];
|
|
if (visible) setActive(sections.indexOf(visible.target));
|
|
}, { root: qs("#feedScroll"), threshold: [0.62, 0.8] });
|
|
sections.forEach((section) => feedObserver.observe(section));
|
|
}
|
|
setActive(0);
|
|
applySearch();
|
|
};
|
|
|
|
const commentMarkup = (comment) => '<article class="comment">' + avatar(comment, "avatar-sm") + '<div class="comment-copy"><strong>' + escapeHTML(comment.name) + "</strong><p>" + escapeHTML(comment.text) + "</p><time>" + escapeHTML(comment.time) + '</time></div><button class="comment-like" aria-label="赞这条评论">' + icon("i-heart") + "<span>" + formatCount(comment.likes) + "</span></button></article>";
|
|
|
|
const renderComments = () => {
|
|
const comments = pageData.comments;
|
|
qs("#commentInput").placeholder = comments.inputPlaceholder || "说点什么…";
|
|
const items = Array.isArray(comments.items) ? comments.items : [];
|
|
qs("#commentsList").innerHTML = items.map(commentMarkup).join("");
|
|
qsa(".comment-like").forEach((button) => button.addEventListener("click", () => button.classList.toggle("liked")));
|
|
};
|
|
|
|
const renderShare = () => {
|
|
const share = pageData.share;
|
|
qs("#shareTitle").textContent = share.title || "分享给朋友";
|
|
const options = Array.isArray(share.options) ? share.options : [];
|
|
qs("#shareOptions").innerHTML = options.map((option) => '<button class="share-option" data-action="' + escapeHTML(option.action) + '" data-toast="' + escapeHTML(option.toast) + '">' + icon(safeIcon(option.icon, SHARE_ICONS, "i-link")) + "<span>" + escapeHTML(option.label) + "</span></button>").join("");
|
|
qsa(".share-option").forEach((button) => button.addEventListener("click", async () => {
|
|
if (button.dataset.action === "copy-link") {
|
|
try {
|
|
if (navigator.clipboard) await navigator.clipboard.writeText(location.href);
|
|
} catch (_error) {
|
|
/* Clipboard may be unavailable in a sandbox. */
|
|
}
|
|
}
|
|
closeShare();
|
|
showToast(button.dataset.toast || "操作完成");
|
|
}));
|
|
};
|
|
|
|
const renderAll = () => {
|
|
closeComments();
|
|
closeShare();
|
|
renderSite();
|
|
renderNavigation();
|
|
renderSidebar();
|
|
renderComments();
|
|
renderShare();
|
|
renderVideos();
|
|
};
|
|
|
|
const commentsBackdrop = qs("#commentsBackdrop");
|
|
function openComments() {
|
|
const video = pageData.videos.items[activeIndex] || {};
|
|
const metrics = video.metrics || {};
|
|
qs("#commentsTitle").textContent = formatCount(metrics.comments) + " " + (pageData.comments.titleSuffix || "条评论");
|
|
commentsBackdrop.classList.add("open");
|
|
commentsBackdrop.setAttribute("aria-hidden", "false");
|
|
window.setTimeout(() => qs("#commentInput").focus(), 180);
|
|
}
|
|
const closeComments = () => {
|
|
commentsBackdrop.classList.remove("open");
|
|
commentsBackdrop.setAttribute("aria-hidden", "true");
|
|
};
|
|
qs("#closeComments").addEventListener("click", closeComments);
|
|
commentsBackdrop.addEventListener("click", (event) => {
|
|
if (event.target === commentsBackdrop) closeComments();
|
|
});
|
|
qs(".comment-form").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("评论已发布");
|
|
});
|
|
|
|
const shareSheet = qs("#shareSheet");
|
|
function openShare() {
|
|
shareSheet.classList.add("open");
|
|
shareSheet.setAttribute("aria-hidden", "false");
|
|
}
|
|
const closeShare = () => {
|
|
shareSheet.classList.remove("open");
|
|
shareSheet.setAttribute("aria-hidden", "true");
|
|
};
|
|
qs("#closeShare").addEventListener("click", closeShare);
|
|
|
|
qs("#prevVideo").addEventListener("click", () => goTo(activeIndex - 1));
|
|
qs("#nextVideo").addEventListener("click", () => goTo(activeIndex + 1));
|
|
qs("#searchInput").addEventListener("input", applySearch);
|
|
qs("#uploadButton").addEventListener("click", () => showToast("上传入口已打开"));
|
|
qs("#loginButton").addEventListener("click", () => showToast("登录入口已打开"));
|
|
|
|
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 = "<span>" + MODULE_META[name][0] + "</span><small>" + name + "</small>";
|
|
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 = "tiktok-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") {
|
|
if (settingsModal.classList.contains("open")) closeSettings();
|
|
else {
|
|
closeComments();
|
|
closeShare();
|
|
}
|
|
}
|
|
if (settingsModal.classList.contains("open") || commentsBackdrop.classList.contains("open")) return;
|
|
if (event.key === "ArrowDown") goTo(activeIndex + 1);
|
|
if (event.key === "ArrowUp") goTo(activeIndex - 1);
|
|
});
|
|
|
|
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 = ".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 platformStyle = document.createElement("style");
|
|
platformStyle.dataset.tiktokInlineUpload = "true";
|
|
platformStyle.textContent = ".video-card>.df-inline-media-button{z-index:45;top:12px;right:62px}@media(max-width:720px){.video-card>.df-inline-media-button{top:max(62px,calc(env(safe-area-inset-top) + 55px));right:62px}}";
|
|
document.head.appendChild(platformStyle);
|
|
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 = '<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;
|
|
const buttonHost = host.matches(".video-visual") ? host.closest(".video-card") || host : host;
|
|
attachButton(buttonHost, 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";
|
|
const buttonHost = host.matches(".video-visual") ? host.closest(".video-card") || host : host;
|
|
attachButton(buttonHost, 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();
|
|
})();
|