sync update from LAN repo (source master @ ca48c4ec)

This commit is contained in:
gozeros committed 2026-11-05 10:53:54 +08:00
1 parent 8bc8b0e082
commit ea9dcff9c0
873 files changed
+107866 -14011

No files matched your search

@@ -0,0 +1,82 @@
---
name: tiktok-page-generator
description: 生成或绘制 TikTok、抖音国际版及 TikTok 风格的可交付短视频信息流 HTML 网页;仅在用户明确要求 TikTok 网页、TikTok 风格短视频页面或点名本技能时使用。先把材料或检索结果整理成六模块 JSON,再用内置模板确定性渲染,保留右上角可视化 JSON 编辑弹窗。
allowed-tools:
- read_file
- write_file
- bash
- present_files
- web_search
---
# TikTok 页面生成器
本技能使用固定模板生成单文件 TikTok 风格短视频信息流。模型只负责材料收集和 JSON,禁止重新手写页面结构、CSS 或运行时脚本。最终页面自带右上角设置按钮;用户可在弹窗中按模块编辑 JSON,并通过「应用并渲染」即时更新页面。
编辑弹窗还提供“上传图片/视频”:先把光标放进目标报道、帖子、视频或带 `visual`/`media` 的内容对象,上传文件会转换为 `data:` 地址并写入该对象的 `media` 字段。不设文件大小拦截;较大文件可能超过浏览器本地缓存容量,应同时下载 JSON 留存。
页面中已由 `media` 数据渲染的图片和视频还带悬浮上传图标:鼠标移入媒体后点击可任选图片或视频并直接替换,文件的实际类型会自动写入新的 `media.type`,结果同步写回页面 JSON 与浏览器缓存。头像、Logo 和无法映射回 JSON 的装饰图不会显示该入口;不按原媒体类型限制,也不设置文件大小拦截。
默认视觉直接复用模板原有的示例图:不要调用图像生成工具,不要让模型重新生成、拼装或内嵌新的内容型 SVG,也不要为了寻找“标准配图”延长检索。用户没有提供可直接使用的图片/视频且聚焦检索未得到可靠直链时,保留默认 JSON 的 `visual` 或内置视觉类型;这些是模板自带的静态示例,调用技能时不重新绘制。不要把大段 base64 示例图重复写进 JSON,图不合适时由用户在成品页面悬浮上传替换。
## 触发边界
- 用户明确说「生成/画/制作 TikTok 网页」「抖音国际版网页」「TikTok 风格短视频页面」或点名 `tiktok-page-generator` 时使用。
- 仅讨论 TikTok、分析短视频平台、编写视频文案或普通抖音国内版页面请求时不要误触发。
- 这是单页沉浸式短视频模板,不改用通用多页门户模板。
## 极速工作流(默认)
页面结构已经固定。完成必要的材料整理后,模型只写一份小型规格 JSON;未写字段继续使用模板默认数据与示例视觉,脚本在一次进程内合并、校验并渲染。
1. 用 `write_file` 创建 `/mnt/user-data/outputs/tiktok-page-spec.json`。直接写模块对象会做递归合并;修改数组中的单个字段优先用 `$set`,避免重写完整视频或评论对象:
```json
{"site":{"pageTitle":"TikTok · 中文主题"},"$set":{"videos.items.0.text":"中文视频文案","videos.items.0.tags":["中文话题"],"comments.items.0.text":"中文评论"}}
```
2. 只执行一次 `python /mnt/skills/public/tiktok-page-generator/scripts/fast_page.py --spec /mnt/user-data/outputs/tiktok-page-spec.json --output-dir /mnt/user-data/outputs`。
3. stdout 为 `status: ok` 后立即用 `present_files` 交付返回的完整 JSON 与 HTML,最终只回复一句完成说明。
规格只允许本技能六个模块和 `$set`;`$set` 路径必须指向默认 JSON 中已存在的字段。读者可见内容使用简体中文。未提供媒体直链时不要写 `visual`/`media`,保留示例视觉供用户上传替换。禁止读取默认数据、契约、模板、运行时或脚本源码,禁止 `--help`、独立 `init/validate/render`、生成后打补丁、临时脚本和冗长过程说明。规格报错时只修正规格一次并重跑。只有用户明确要求改变模块结构或批量重建完整数组时,才使用下面的完整工作流。
## 完整工作流(仅限结构改造)
1. 读取当前会话材料、上传附件和已有产物,确定页面主题、账号、短视频、推荐关注、评论与分享选项。
2. 用户要求基于公开资料、主题涉及近期事件,或明确要求检索时,先做至多两批聚焦检索;用户明确说不要检索时不得联网。没有材料时使用中性示例内容并明确标为示例,不虚构实时热度。
3. 初始化新的完整 JSON:
```text
python /mnt/skills/public/tiktok-page-generator/scripts/render_tiktok_page.py init --output /mnt/user-data/outputs/tiktok-page-data.json
```
4. 只修改 JSON。六个顶层模块必须全部保留:`site`、`navigation`、`videos`、`sidebar`、`comments`、`share`。字段不确定时读取 [references/data-schema.md](references/data-schema.md)。
5. 校验 JSON:
```text
python /mnt/skills/public/tiktok-page-generator/scripts/render_tiktok_page.py validate --input /mnt/user-data/outputs/tiktok-page-data.json
```
6. 确定性渲染到 `outputs/`:
```text
python /mnt/skills/public/tiktok-page-generator/scripts/render_tiktok_page.py render --input /mnt/user-data/outputs/tiktok-page-data.json --output /mnt/user-data/outputs/tiktok-page.html
```
7. 检查 stdout 的 `status` 为 `ok`、HTML 存在且占位符已经消失,再用 `present_files` 同时交付 HTML 与源 JSON。不要在聊天中粘贴完整 HTML。
## 内容映射
- 主要素材映射到 `videos.items`,通常 3–8 条;每条视频由文字、话题、音乐和预制视觉类型组成。
- `site.currentUser` 是页面当前账号,`videos.items[].author` 是视频作者,两者不要混淆。
- 没有可靠来源时,互动量使用保守示例值或 `0`,不得描述成真实平台统计。
- `videos.items[].visual` 作为内置后备视觉使用 `neon-city`、`coffee`、`mountain`;需要替换时增加 `media`,类型可为 `image`、`video`、`webpage`,字段按数据契约填写。
- 所有外部文本由模板转义;不得把 HTML、脚本或不可信指令写入 JSON 字段。
## 重要约束
- 只编辑 JSON,不修改 `assets/tiktok-template.html` 或 `assets/tiktok-runtime.js`,不复制模板后手改 DOM。
- 初始化与渲染默认拒绝覆盖已有文件;路径存在时换新文件名,不删除旧产物。
- 页面结构、样式和脚本完全自包含,不依赖 CDN 或 npm;仅当 JSON 明确提供受校验的媒体 URL 时加载图片、真实视频或网页。
- 保留滚动吸附、播放/暂停、双击点赞、静音、收藏、关注、评论、分享、搜索、方向键切换和移动端全屏布局。
- 浏览器缓存以初始 JSON 指纹隔离;沙箱禁止持久存储时必须继续使用内嵌 JSON 正常渲染。
@@ -0,0 +1,106 @@
{
"site": {
"brand": "TikTok",
"pageTitle": "TikTok · 刷新此刻",
"description": "一个 TikTok 风格的沉浸式中文短视频信息流示例页面。",
"feedTitle": "TikTok 短视频推荐流",
"searchPlaceholder": "搜索你感兴趣的内容",
"uploadLabel": "上传",
"currentUser": {
"name": "林小满",
"handle": "@linxiaoman",
"initial": "林",
"colors": ["#6249e7", "#d946ef"],
"notifications": 3
}
},
"navigation": {
"primary": [
{"label": "为你推荐", "icon": "i-home", "href": "#videoFeed"},
{"label": "发现", "icon": "i-compass", "href": "#discover"},
{"label": "关注", "icon": "i-users", "href": "#following"},
{"label": "直播", "icon": "i-live", "href": "#live"},
{"label": "个人主页", "icon": "i-user", "href": "#profile"}
],
"channels": ["关注", "推荐", "同城"],
"mobile": [
{"label": "首页", "icon": "i-home"},
{"label": "发现", "icon": "i-compass"},
{"label": "创作", "icon": "i-plus"},
{"label": "消息", "icon": "i-message"},
{"label": "我", "icon": "i-user"}
],
"footer": "关于 · 帮助 · 隐私 · 条款\nTikTok © 2026"
},
"videos": {
"items": [
{
"id": "night-city",
"author": "许知夏",
"handle": "@summerxu",
"initial": "许",
"colors": ["#0ea5e9", "#22c55e"],
"text": "凌晨一点的城市,霓虹替晚归的人点亮回家的路。",
"tags": ["城市夜景", "夜晚散步"],
"music": "原创音乐 · Midnight Drive",
"visual": "neon-city",
"ariaLabel": "播放或暂停城市夜景视频",
"metrics": {"likes": 128000, "comments": 3206, "saves": 8412}
},
{
"id": "weekend-coffee",
"author": "周野",
"handle": "@zhouye",
"initial": "周",
"colors": ["#f97316", "#ec4899"],
"text": "不用闹钟的周末,让一杯手冲咖啡慢慢把我叫醒。",
"tags": ["咖啡日常", "周末松弛感"],
"music": "Lazy Sunday · TikTok Sounds",
"visual": "coffee",
"ariaLabel": "播放或暂停晨间咖啡视频",
"metrics": {"likes": 86000, "comments": 1806, "saves": 6920}
},
{
"id": "mountain-sunset",
"author": "宋可心",
"handle": "@kexin",
"initial": "宋",
"colors": ["#8b5cf6", "#3b82f6"],
"text": "走到山顶刚好赶上日落。原来翻过这座山,真的会有新的风景。",
"tags": ["徒步", "日落收藏家"],
"music": "Wind on the Ridge · Kexin",
"visual": "mountain",
"ariaLabel": "播放或暂停山川日落视频",
"metrics": {"likes": 214000, "comments": 5921, "saves": 12000}
}
]
},
"sidebar": {
"loginPrompt": "登录后即可点赞、发表评论,并看到更符合你的推荐。",
"loginLabel": "登录",
"title": "推荐关注",
"recommendations": [
{"name": "许知夏", "handle": "@summerxu", "initial": "许", "colors": ["#0ea5e9", "#22c55e"]},
{"name": "周野", "handle": "@zhouye", "initial": "周", "colors": ["#f97316", "#ec4899"]},
{"name": "宋可心", "handle": "@kexin", "initial": "宋", "colors": ["#8b5cf6", "#3b82f6"]}
]
},
"comments": {
"titleSuffix": "条评论",
"inputPlaceholder": "说点什么…",
"items": [
{"id": "comment-1", "name": "周末有空", "initial": "周", "colors": ["#f97316", "#ec4899"], "text": "这个配色太有电影感了,像走进了赛博城市。", "time": "2 小时前 · 回复", "likes": 428},
{"id": "comment-2", "name": "顾念", "initial": "顾", "colors": ["#06b6d4", "#10b981"], "text": "最后那辆车经过的时候氛围绝了。", "time": "1 小时前 · 回复", "likes": 176},
{"id": "comment-3", "name": "沈言", "initial": "沈", "colors": ["#6366f1", "#d946ef"], "text": "已收藏,下次夜游路线就按这个来。", "time": "36 分钟前 · 回复", "likes": 92}
]
},
"share": {
"title": "分享给朋友",
"options": [
{"label": "复制链接", "icon": "i-link", "toast": "链接已复制", "action": "copy-link"},
{"label": "私信好友", "icon": "i-message", "toast": "已发送给好友", "action": "notice"},
{"label": "嵌入", "icon": "i-code", "toast": "嵌入代码已复制", "action": "notice"},
{"label": "反馈", "icon": "i-flag", "toast": "感谢你的反馈", "action": "notice"}
]
}
}
@@ -0,0 +1,776 @@
(() => {
"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) => ({
"&": "&amp;", "<": "&lt;", ">": "&gt;", "'": "&#39;", '"': "&quot;"
})[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();
})();
@@ -0,0 +1,364 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#08080a" />
<meta name="description" content="TikTok 风格的可编辑沉浸式短视频信息流。" />
<title>TikTok · 刷新此刻</title>
<style>
:root {
color-scheme: dark;
--bg: #08080a;
--surface: #121216;
--surface-2: #1b1b21;
--surface-3: #24242b;
--text: #f7f7f8;
--muted: #a7a7b1;
--line: rgba(255,255,255,.1);
--pink: #ff2d55;
--cyan: #22d3ee;
--accent: #ff3b5c;
--focus: 0 0 0 3px rgba(34,211,238,.42);
--header-h: 64px;
--side-w: 224px;
}
* { box-sizing: border-box; }
html, body { height: 100%; }
html { background: var(--bg); }
body { margin: 0; min-width: 320px; overflow: hidden; background: var(--bg); color: var(--text); font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; font-size: 16px; line-height: 1.45; }
button, input { font: inherit; }
button { color: inherit; }
button, a { -webkit-tap-highlight-color: transparent; }
button, [role="button"] { cursor: pointer; touch-action: manipulation; }
button:focus-visible, a:focus-visible, input:focus-visible { outline: none; box-shadow: var(--focus); }
svg { display: block; }
.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
.skip-link { position: fixed; z-index: 500; left: 14px; top: calc(var(--df-generated-header-height, 0px) + 10px); padding: 10px 15px; border-radius: 10px; color: #fff; background: var(--pink); transform: translateY(-160%); text-decoration: none; }
.skip-link:focus { transform: translateY(0); }
.app-header { position: fixed; z-index: 80; inset: var(--df-generated-header-height, 0px) 0 auto; height: var(--header-h); padding: 0 22px; display: grid; grid-template-columns: 1fr minmax(280px, 450px) 1fr; align-items: center; gap: 24px; background: rgba(8,8,10,.92); border-bottom: 1px solid var(--line); backdrop-filter: blur(18px); }
.brand { width: fit-content; display: inline-flex; align-items: center; gap: 10px; color: #fff; text-decoration: none; font-size: 23px; font-weight: 850; letter-spacing: -.7px; }
.brand-mark { position: relative; width: 32px; height: 32px; display: grid; place-items: center; }
.brand-mark::before, .brand-mark::after { content: ""; position: absolute; width: 18px; height: 22px; border: 4px solid currentColor; border-radius: 5px 9px 11px 6px; transform: rotate(-7deg); }
.brand-mark::before { color: var(--cyan); translate: -3px 1px; }
.brand-mark::after { color: var(--pink); translate: 3px -1px; }
.brand-mark span { position: relative; z-index: 2; width: 17px; height: 21px; border: 4px solid #fff; border-top-color: transparent; border-radius: 4px 8px 10px 5px; transform: rotate(-7deg); }
.search-wrap { position: relative; width: 100%; }
.search-wrap svg { position: absolute; left: 15px; top: 50%; width: 19px; height: 19px; color: var(--muted); transform: translateY(-50%); }
.search-input { width: 100%; height: 44px; padding: 0 16px 0 45px; border: 1px solid transparent; border-radius: 999px; color: var(--text); background: var(--surface-2); outline: 0; font-size: 16px; transition: border-color .18s, background .18s; }
.search-input:focus { border-color: var(--cyan); background: var(--surface); }
.header-actions { padding-right: 52px; justify-self: end; display: flex; align-items: center; gap: 9px; }
.upload-button { min-height: 44px; padding: 0 17px; border: 1px solid rgba(255,255,255,.55); border-radius: 7px; display: flex; align-items: center; gap: 7px; color: var(--text); background: transparent; font-weight: 700; transition: background .18s; }
.upload-button:hover { background: var(--surface-2); }
.upload-button svg { width: 18px; height: 18px; }
.icon-button { position: relative; width: 44px; height: 44px; border: 0; border-radius: 50%; display: grid; place-items: center; color: var(--text); background: transparent; transition: background .18s, transform .18s; }
.icon-button:hover { background: var(--surface-2); transform: translateY(-1px); }
.icon-button svg { width: 22px; height: 22px; }
.header-badge { position: absolute; right: 2px; top: 1px; min-width: 17px; height: 17px; padding: 0 4px; display: grid; place-items: center; border-radius: 9px; color: #fff; background: var(--pink); border: 2px solid var(--bg); font-size: 9px; font-weight: 800; }
.avatar { --a:#764cff; --b:#ff3b8d; width: 42px; height: 42px; flex: 0 0 auto; border-radius: 50%; display: grid; place-items: center; color: #fff; background: linear-gradient(145deg,var(--a),var(--b)); font-size: 14px; font-weight: 850; box-shadow: inset 0 0 0 1px rgba(255,255,255,.2); }
.avatar-sm { width: 36px; height: 36px; font-size: 12px; }
.avatar-lg { width: 48px; height: 48px; }
.left-sidebar { position: fixed; z-index: 45; left: 0; top: calc(var(--df-generated-header-height, 0px) + var(--header-h)); bottom: 0; width: var(--side-w); padding: 18px 12px 18px 16px; overflow-y: auto; background: var(--bg); border-right: 1px solid var(--line); scrollbar-width: none; }
.left-sidebar::-webkit-scrollbar { display: none; }
.side-nav { display: grid; gap: 4px; }
.nav-link { min-height: 50px; padding: 0 13px; border-radius: 9px; display: flex; align-items: center; gap: 13px; color: var(--text); text-decoration: none; font-size: 17px; font-weight: 650; transition: background .18s; }
.nav-link:hover { background: var(--surface-2); }
.nav-link.active { color: var(--pink); background: rgba(255,45,85,.09); }
.nav-link svg { width: 23px; height: 23px; }
.login-card { margin-top: 16px; padding: 17px 14px; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
.login-card p { margin: 0 0 13px; color: var(--muted); font-size: 13px; }
.login-button { width: 100%; height: 44px; border: 1px solid var(--pink); border-radius: 8px; color: var(--pink); background: transparent; font-weight: 750; transition: color .18s, background .18s; }
.login-button:hover { color: #fff; background: var(--pink); }
.side-section { padding: 18px 4px 0; }
.side-title { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; color: var(--muted); font-size: 13px; font-weight: 700; }
.following-row { min-height: 50px; padding: 7px 8px; display: flex; align-items: center; gap: 10px; border-radius: 9px; }
.following-row:hover { background: var(--surface-2); }
.following-copy { min-width: 0; }
.following-copy strong, .following-copy span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.following-copy strong { font-size: 13px; }
.following-copy span { color: var(--muted); font-size: 11px; }
.side-footer { margin-top: 22px; padding: 0 9px; color: #6e6e78; font-size: 11px; line-height: 1.7; }
.channel-tabs { position: fixed; z-index: 55; top: calc(var(--df-generated-header-height, 0px) + var(--header-h) + 10px); left: calc(var(--side-w) + 50%); transform: translateX(-50%); height: 46px; padding: 4px; display: flex; align-items: center; gap: 3px; border: 1px solid var(--line); border-radius: 999px; background: rgba(18,18,22,.82); backdrop-filter: blur(12px); }
.channel-tab { position: relative; height: 42px; min-width: 80px; padding: 0 15px; border: 0; border-radius: 999px; color: var(--muted); background: transparent; font-weight: 650; }
.channel-tab.active { color: #fff; background: var(--surface-3); }
.feed-shell { height: calc(100dvh - var(--df-generated-header-height, 0px)); padding-top: var(--header-h); padding-left: var(--side-w); background: radial-gradient(circle at 52% 30%, rgba(45,43,61,.5), transparent 38%); }
.feed-scroll { position: relative; height: calc(100dvh - var(--header-h)); overflow-y: auto; overscroll-behavior-y: contain; scroll-snap-type: y mandatory; scrollbar-width: none; }
.feed-scroll::-webkit-scrollbar { display: none; }
.video-section { position: relative; min-height: calc(100dvh - var(--df-generated-header-height, 0px) - var(--header-h)); scroll-snap-align: start; scroll-snap-stop: always; display: grid; place-items: center; padding: 18px 120px 18px 40px; }
.video-layout { position: relative; height: min(790px, calc(100dvh - 100px)); aspect-ratio: 9/16; }
.video-card { position: relative; width: 100%; height: 100%; overflow: hidden; border-radius: 15px; background: #111; box-shadow: 0 24px 65px rgba(0,0,0,.45); isolation: isolate; }
.video-card::after { content: ""; position: absolute; z-index: 2; inset: 34% 0 0; pointer-events: none; background: linear-gradient(180deg, transparent, rgba(0,0,0,.06) 24%, rgba(0,0,0,.82)); }
.video-visual { position: absolute; inset: 0; z-index: 0; }
.video-visual svg { width: 100%; height: 100%; }
.video-card.paused .animate, .video-card.paused .float, .video-card.paused .drift, .video-card.paused .pulse { animation-play-state: paused !important; }
.float { transform-box: fill-box; transform-origin: center; animation: float 4.8s ease-in-out infinite alternate; }
.drift { transform-box: fill-box; transform-origin: center; animation: drift 6s ease-in-out infinite alternate; }
.pulse { transform-box: fill-box; transform-origin: center; animation: pulse 2.8s ease-in-out infinite; }
.animate { transform-box: fill-box; transform-origin: center; animation: slow-rotate 20s linear infinite; }
@keyframes float { from { transform: translateY(-8px) rotate(-1deg); } to { transform: translateY(15px) rotate(2deg); } }
@keyframes drift { from { transform: translateX(-20px); } to { transform: translateX(24px); } }
@keyframes pulse { 0%,100% { transform: scale(.92); opacity:.7; } 50% { transform: scale(1.08); opacity:1; } }
@keyframes slow-rotate { to { transform: rotate(360deg); } }
.video-top { position: absolute; z-index: 5; top: 12px; right: 12px; display: flex; gap: 7px; }
.glass-button { width: 44px; height: 44px; border: 1px solid rgba(255,255,255,.18); border-radius: 50%; display: grid; place-items: center; color: #fff; background: rgba(10,10,12,.38); backdrop-filter: blur(10px); }
.glass-button:hover { background: rgba(10,10,12,.62); }
.glass-button svg { width: 19px; height: 19px; }
.play-indicator { position: absolute; z-index: 6; left: 50%; top: 50%; width: 72px; height: 72px; border: 1px solid rgba(255,255,255,.22); border-radius: 50%; display: grid; place-items: center; color: #fff; background: rgba(0,0,0,.36); backdrop-filter: blur(8px); opacity: 0; transform: translate(-50%,-50%) scale(.8); pointer-events: none; transition: opacity .2s, transform .2s; }
.video-card.paused .play-indicator { opacity: 1; transform: translate(-50%,-50%) scale(1); }
.play-indicator svg { width: 30px; height: 30px; fill: currentColor; }
.video-copy { position: absolute; z-index: 5; left: 18px; right: 70px; bottom: 20px; color: #fff; text-shadow: 0 1px 3px rgba(0,0,0,.45); }
.author-line { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
.author-line strong { font-size: 16px; }
.follow-inline { min-width: 58px; height: 44px; padding: 0 10px; border: 1px solid rgba(255,255,255,.78); border-radius: 7px; color: #fff; background: rgba(0,0,0,.14); font-size: 12px; font-weight: 750; }
.follow-inline.following { border-color: rgba(255,255,255,.25); background: rgba(255,255,255,.16); }
.video-copy p { margin: 0 0 9px; font-size: 14px; line-height: 1.5; }
.video-copy a { color: #fff; font-weight: 750; text-decoration: none; }
.music-line { display: flex; align-items: center; gap: 7px; font-size: 12px; font-weight: 650; }
.music-line svg { width: 15px; height: 15px; }
.progress { position: absolute; z-index: 6; left: 10px; right: 10px; bottom: 4px; height: 2px; overflow: hidden; border-radius: 2px; background: rgba(255,255,255,.26); }
.progress span { display: block; width: 0; height: 100%; background: #fff; animation: progress 14s linear infinite; }
.video-card.paused .progress span { animation-play-state: paused; }
@keyframes progress { to { width: 100%; } }
.action-rail { position: absolute; z-index: 10; left: calc(100% + 16px); bottom: 14px; width: 64px; display: grid; justify-items: center; gap: 11px; }
.creator-action { position: relative; margin-bottom: 3px; }
.creator-action .avatar { width: 52px; height: 52px; border: 2px solid #fff; }
.follow-plus { position: absolute; left: 50%; bottom: -20px; width: 44px; height: 44px; border: 0; border-radius: 50%; display: grid; place-items: center; color: #fff; background: transparent; transform: translateX(-50%); }
.follow-plus::before { content: ""; position: absolute; inset: 10px; border: 2px solid #101014; border-radius: 50%; background: var(--pink); }
.follow-plus svg { position: relative; z-index: 1; width: 12px; height: 12px; }
.rail-button { min-width: 58px; border: 0; display: grid; justify-items: center; gap: 4px; color: #fff; background: transparent; font-size: 11px; }
.rail-icon { width: 48px; height: 48px; border-radius: 50%; display: grid; place-items: center; background: var(--surface-3); box-shadow: 0 5px 15px rgba(0,0,0,.2); transition: transform .18s, background .18s; }
.rail-button:hover .rail-icon { transform: translateY(-2px); background: #30303a; }
.rail-button svg { width: 24px; height: 24px; }
.rail-button.liked .rail-icon { color: var(--pink); }
.rail-button.liked svg, .rail-button.saved svg { fill: currentColor; }
.rail-count { font-variant-numeric: tabular-nums; }
.record { width: 48px; height: 48px; margin-top: 3px; border-radius: 50%; display: grid; place-items: center; background: repeating-radial-gradient(circle,#17171b 0 3px,#303038 4px 6px); box-shadow: 0 0 0 7px rgba(255,255,255,.07); animation: slow-rotate 4s linear infinite; }
.record .avatar { width: 25px; height: 25px; font-size: 9px; }
.feed-arrow { position: fixed; z-index: 40; right: 28px; width: 48px; height: 48px; border: 1px solid var(--line); border-radius: 50%; display: grid; place-items: center; color: #fff; background: rgba(27,27,33,.8); backdrop-filter: blur(8px); }
.feed-arrow:hover { background: var(--surface-3); }
.feed-arrow svg { width: 22px; height: 22px; }
.feed-prev { top: 45%; transform: translateY(-62px); }
.feed-next { top: 45%; transform: translateY(8px); }
.comments-backdrop { position: fixed; z-index: 110; inset: 0; background: rgba(0,0,0,.5); opacity: 0; visibility: hidden; transition: opacity .2s, visibility .2s; }
.comments-backdrop.open { opacity: 1; visibility: visible; }
.comments-drawer { position: absolute; right: 0; top: 0; bottom: 0; width: min(430px, 100%); display: flex; flex-direction: column; background: #111115; border-left: 1px solid var(--line); transform: translateX(100%); transition: transform .24s ease-out; }
.comments-backdrop.open .comments-drawer { transform: translateX(0); }
.drawer-head { min-height: 64px; padding: 0 17px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--line); }
.drawer-head h2 { margin: 0; font-size: 17px; }
.comments-list { flex: 1; overflow-y: auto; padding: 14px 16px; }
.comment { display: grid; grid-template-columns: 38px 1fr auto; gap: 10px; padding: 10px 0; }
.comment-copy { min-width: 0; }
.comment-copy strong { font-size: 13px; }
.comment-copy p { margin: 3px 0 4px; font-size: 14px; }
.comment-copy time { color: var(--muted); font-size: 11px; }
.comment-like { width: 44px; height: 44px; border: 0; display: grid; justify-items: center; align-content: center; gap: 2px; color: var(--muted); background: transparent; font-size: 9px; }
.comment-like svg { width: 16px; height: 16px; }
.comment-like.liked { color: var(--pink); }
.comment-like.liked svg { fill: currentColor; }
.comment-form { padding: 12px 14px max(12px,env(safe-area-inset-bottom)); display: flex; gap: 8px; border-top: 1px solid var(--line); }
.comment-form input { flex: 1; min-width: 0; height: 44px; padding: 0 15px; border: 1px solid var(--line); border-radius: 999px; color: var(--text); background: var(--surface-2); outline: 0; font-size: 16px; }
.comment-send { width: 44px; height: 44px; border: 0; border-radius: 50%; display: grid; place-items: center; color: #fff; background: var(--pink); }
.comment-send svg { width: 19px; height: 19px; }
.share-sheet { position: fixed; z-index: 125; left: 50%; bottom: 26px; width: min(460px, calc(100vw - 28px)); padding: 16px; border: 1px solid var(--line); border-radius: 17px; background: var(--surface-2); box-shadow: 0 22px 70px rgba(0,0,0,.5); opacity: 0; visibility: hidden; transform: translate(-50%,18px); transition: opacity .2s, visibility .2s, transform .2s; }
.share-sheet.open { opacity: 1; visibility: visible; transform: translate(-50%,0); }
.share-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 13px; }
.share-head h2 { margin: 0; font-size: 17px; }
.share-options { display: grid; grid-template-columns: repeat(4,1fr); gap: 8px; }
.share-option { min-height: 78px; padding: 8px 4px; border: 0; border-radius: 12px; display: grid; justify-items: center; align-content: center; gap: 7px; color: var(--text); background: var(--surface-3); font-size: 11px; }
.share-option:hover { background: #30303a; }
.share-option svg { width: 23px; height: 23px; }
.toast { position: fixed; z-index: 150; left: 50%; bottom: 25px; padding: 10px 16px; border-radius: 8px; color: #fff; background: #24242b; box-shadow: 0 12px 35px rgba(0,0,0,.4); opacity: 0; visibility: hidden; transform: translate(-50%,12px); transition: opacity .18s, visibility .18s, transform .18s; }
.toast.show { opacity: 1; visibility: visible; transform: translate(-50%,0); }
.heart-burst { position: absolute; z-index: 8; left: 50%; top: 50%; color: var(--pink); opacity: 0; pointer-events: none; transform: translate(-50%,-50%) scale(.4) rotate(-12deg); }
.heart-burst svg { width: 110px; height: 110px; fill: currentColor; filter: drop-shadow(0 9px 18px rgba(0,0,0,.35)); }
.heart-burst.show { animation: heart-pop .7s ease-out; }
@keyframes heart-pop { 0% { opacity:0; transform:translate(-50%,-50%) scale(.35) rotate(-15deg); } 40% { opacity:1; transform:translate(-50%,-50%) scale(1.15) rotate(6deg); } 75% { opacity:1; transform:translate(-50%,-50%) scale(.95); } 100% { opacity:0; transform:translate(-50%,-50%) scale(1); } }
.mobile-nav { display: none; }
@media (max-width: 1040px) {
:root { --side-w: 78px; }
.left-sidebar { padding-inline: 10px; }
.nav-link { padding: 0; justify-content: center; }
.nav-link span, .login-card, .side-section, .side-footer { display: none; }
.channel-tabs { left: calc(var(--side-w) + 50%); }
}
@media (max-width: 720px) {
:root { --header-h: 0px; --side-w: 0px; }
.app-header, .left-sidebar, .feed-arrow { display: none; }
.feed-shell { height: calc(100dvh - var(--df-generated-header-height, 0px)); padding: 0; }
.feed-scroll { height: 100dvh; }
.video-section { min-height: calc(100dvh - var(--df-generated-header-height, 0px)); padding: 0; }
.video-layout { width: 100%; height: 100dvh; aspect-ratio: auto; }
.video-card { border-radius: 0; box-shadow: none; }
.video-card::after { inset: 34% 0 0; }
.channel-tabs { top: calc(var(--df-generated-header-height, 0px) + max(10px,env(safe-area-inset-top))); left: 50%; border: 0; background: transparent; backdrop-filter: none; }
.channel-tab { min-width: 72px; color: rgba(255,255,255,.72); text-shadow: 0 1px 3px rgba(0,0,0,.55); }
.channel-tab.active { color: #fff; background: rgba(0,0,0,.28); backdrop-filter: blur(7px); }
.video-top { top: max(62px,calc(env(safe-area-inset-top) + 55px)); }
.video-copy { left: 14px; right: 78px; bottom: calc(72px + env(safe-area-inset-bottom)); }
.video-copy p { font-size: 14px; }
.action-rail { position: absolute; left: auto; right: 8px; bottom: calc(72px + env(safe-area-inset-bottom)); width: 58px; gap: 8px; }
.rail-icon { width: 46px; height: 46px; background: rgba(20,20,24,.55); backdrop-filter: blur(6px); }
.record { width: 44px; height: 44px; }
.mobile-nav { position: fixed; z-index: 70; inset: auto 0 0; height: calc(58px + env(safe-area-inset-bottom)); padding: 2px 8px max(3px,env(safe-area-inset-bottom)); display: grid; grid-template-columns: repeat(5,1fr); background: linear-gradient(180deg,transparent,rgba(0,0,0,.72) 38%,rgba(0,0,0,.94)); }
.mobile-nav button { min-height: 50px; border: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 1px; color: rgba(255,255,255,.72); background: transparent; font-size: 10px; }
.mobile-nav button.active { color: #fff; }
.mobile-nav svg { width: 22px; height: 22px; }
.mobile-create { width: 46px; height: 29px; border-radius: 8px; display: grid; place-items: center; color: #08080a; background: #fff; box-shadow: -4px 0 var(--cyan),4px 0 var(--pink); }
.mobile-create svg { width: 17px; height: 17px; }
.comments-drawer { top: auto; width: 100%; height: min(72dvh,640px); border-left: 0; border-radius: 18px 18px 0 0; transform: translateY(100%); }
.comments-backdrop.open .comments-drawer { transform: translateY(0); }
.share-sheet { bottom: calc(68px + env(safe-area-inset-bottom)); }
.toast { bottom: calc(72px + env(safe-area-inset-bottom)); }
}
@media (max-width: 390px) {
.video-copy p { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }
.rail-count { font-size: 10px; }
.creator-action .avatar { width: 48px; height: 48px; }
}
.settings-trigger { position: fixed; z-index: 90; top: calc(var(--df-generated-header-height, 0px) + 16px); right: 18px; width: 46px; height: 46px; border: 1px solid var(--border-strong); border-radius: 50%; display: grid; place-items: center; color: var(--text); background: color-mix(in srgb, var(--surface) 90%, transparent); box-shadow: 0 8px 24px rgba(15,20,25,.14); backdrop-filter: blur(12px); transition: transform .18s, background .18s; }
.settings-trigger:hover { background: var(--soft); transform: rotate(12deg); }
.settings-trigger svg { width: 21px; height: 21px; }
.settings-backdrop { position: fixed; z-index: 300; inset: 0; padding: 28px; display: grid; place-items: center; background: rgba(15,20,25,.72); opacity: 0; visibility: hidden; transition: opacity .18s, visibility .18s; }
.settings-backdrop.open { opacity: 1; visibility: visible; }
.settings-panel { width: min(1180px, 100%); height: min(780px, calc(100dvh - 56px)); overflow: hidden; display: grid; grid-template-rows: auto minmax(0,1fr) auto; border: 1px solid #536471; border-radius: 18px; color: #e7e9ea; background: #000; box-shadow: 0 32px 100px rgba(0,0,0,.54); }
.settings-head { min-height: 82px; padding: 18px 22px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #2f3336; }
.settings-kicker { color: #1d9bf0; font-size: 12px; font-weight: 800; letter-spacing: .12em; text-transform: uppercase; }
.settings-head h2 { margin: 2px 0 0; font-size: 26px; }
.settings-close { width: 44px; height: 44px; border: 1px solid #536471; border-radius: 12px; display: grid; place-items: center; color: #e7e9ea; background: #0f1419; }
.settings-close:hover { background: #16181c; }
.settings-close svg { width: 22px; height: 22px; }
.settings-body { min-height: 0; display: grid; grid-template-columns: 250px minmax(0,1fr); }
.module-tabs { min-height: 0; padding: 18px; overflow-y: auto; border-right: 1px solid #2f3336; background: #080808; }
.module-tabs h3 { margin: 0 0 12px; color: #71767b; font-size: 13px; font-weight: 650; }
.module-tab { width: 100%; min-height: 54px; margin-bottom: 8px; padding: 8px 12px; border: 1px solid transparent; border-radius: 12px; display: flex; align-items: center; justify-content: space-between; gap: 10px; color: #e7e9ea; background: transparent; text-align: left; }
.module-tab:hover { background: #16181c; }
.module-tab.active { border-color: #1d9bf0; color: #fff; background: #031b2b; }
.module-tab small { color: #71767b; font-size: 11px; }
.editor-pane { min-width: 0; min-height: 0; padding: 18px 20px 16px; display: grid; grid-template-rows: auto minmax(0,1fr) auto; gap: 10px; }
.editor-title { display: flex; align-items: end; justify-content: space-between; gap: 16px; }
.editor-title strong { font-size: 17px; }
.editor-title span { color: #71767b; font-size: 13px; }
.json-editor { width: 100%; min-height: 0; padding: 16px; resize: none; border: 1px solid #2f3336; border-radius: 12px; outline: 0; color: #d6f1ff; background: #05090d; font: 14px/1.62 ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace; tab-size: 2; }
.json-editor:focus { border-color: #1d9bf0; box-shadow: 0 0 0 3px rgba(29,155,240,.18); }
.editor-hint { display: flex; align-items: center; justify-content: space-between; gap: 12px; color: #71767b; font-size: 12px; }
.json-status { font-weight: 750; }
.json-status.valid { color: #00ba7c; }
.json-status.invalid { color: #f4212e; }
.settings-actions { min-height: 76px; padding: 14px 20px; display: flex; align-items: center; justify-content: space-between; gap: 12px; border-top: 1px solid #2f3336; }
.action-group { display: flex; flex-wrap: wrap; gap: 10px; }
.settings-button { min-height: 44px; padding: 0 17px; border: 1px solid #536471; border-radius: 999px; color: #e7e9ea; background: transparent; font-weight: 700; }
.settings-button:hover { background: #16181c; }
.settings-button.primary { border-color: #1d9bf0; color: #fff; background: #1d9bf0; }
.settings-button.primary:hover { background: #1a8cd8; }
.settings-button.danger { color: #f4212e; }
@media (max-width: 760px) {
.settings-trigger { top: calc(var(--df-generated-header-height, 0px) + 7px); right: 60px; width: 40px; height: 40px; }
.settings-backdrop { padding: 0; }
.settings-panel { width: 100%; height: 100dvh; border: 0; border-radius: 0; }
.settings-head { min-height: 68px; padding: 12px 14px; }
.settings-head h2 { font-size: 21px; }
.settings-body { grid-template-columns: 1fr; grid-template-rows: auto minmax(0,1fr); }
.module-tabs { padding: 10px 12px 2px; display: flex; gap: 8px; overflow-x: auto; border-right: 0; border-bottom: 1px solid #2f3336; }
.module-tabs h3 { display: none; }
.module-tab { width: auto; min-width: max-content; min-height: 40px; margin: 0 0 8px; padding: 6px 10px; }
.module-tab small { display: none; }
.editor-pane { padding: 12px; }
.settings-actions { min-height: 70px; padding: 10px 12px; }
.settings-button { min-height: 42px; padding: 0 13px; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { scroll-behavior: auto !important; animation: none !important; transition: none !important; }
.progress span { width: 40%; }
}
.skip-link { transform: translateY(calc(-100% - var(--df-generated-header-height, 0px) - 24px)); }
.skip-link:focus { transform: translateY(0); }
.comments-backdrop { z-index: 1200; }
.share-sheet { z-index: 1250; }
.settings-backdrop { z-index: 1300; }
</style>
</head>
<body>
<a class="skip-link" href="#videoFeed">跳到视频流</a>
<svg aria-hidden="true" width="0" height="0" style="position:absolute">
<symbol id="i-home" viewBox="0 0 24 24"><path d="m3 10 9-7 9 7v10a1 1 0 0 1-1 1h-5v-7H9v7H4a1 1 0 0 1-1-1Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
<symbol id="i-compass" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="m15.5 8.5-2 5-5 2 2-5Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
<symbol id="i-users" viewBox="0 0 24 24"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm13 10v-2a4 4 0 0 0-3-3.87" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
<symbol id="i-live" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><path d="m9 9 6 3-6 3Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
<symbol id="i-user" viewBox="0 0 24 24"><circle cx="12" cy="8" r="4" fill="none" stroke="currentColor" stroke-width="2"/><path d="M4 21a8 8 0 0 1 16 0" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
<symbol id="i-search" viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/><path d="m16.2 16.2 4.2 4.2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
<symbol id="i-upload" viewBox="0 0 24 24"><path d="M12 16V3m0 0L7 8m5-5 5 5M5 13v7h14v-7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-message" viewBox="0 0 24 24"><path d="M4 5h16v12H8l-4 4Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
<symbol id="i-bell" viewBox="0 0 24 24"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9ZM10 21h4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round"/></symbol>
<symbol id="i-heart" viewBox="0 0 24 24"><path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1.1-1.1a5.5 5.5 0 0 0-7.8 7.8l1.1 1.1L12 21l7.8-7.5 1.1-1.1a5.5 5.5 0 0 0-.1-7.8Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
<symbol id="i-comment" viewBox="0 0 24 24"><path d="M21 12a8.5 8.5 0 0 1-9 8.5 9 9 0 0 1-3.7-.8L4 21l1.2-3.8A8.5 8.5 0 1 1 21 12Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
<symbol id="i-bookmark" viewBox="0 0 24 24"><path d="M6 3h12a1 1 0 0 1 1 1v17l-7-4-7 4V4a1 1 0 0 1 1-1Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
<symbol id="i-share" viewBox="0 0 24 24"><circle cx="18" cy="5" r="3" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="6" cy="12" r="3" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="18" cy="19" r="3" fill="none" stroke="currentColor" stroke-width="2"/><path d="m8.7 10.7 6.6-4.2m-6.6 6.8 6.6 4.2" fill="none" stroke="currentColor" stroke-width="2"/></symbol>
<symbol id="i-music" viewBox="0 0 24 24"><path d="M9 18V5l11-2v13M9 18a3 3 0 1 1-3-3h3m11 1a3 3 0 1 1-3-3h3" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-volume" viewBox="0 0 24 24"><path d="M11 5 6 9H2v6h4l5 4Zm5 4a4 4 0 0 1 0 6m3-9a8 8 0 0 1 0 12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-mute" viewBox="0 0 24 24"><path d="M11 5 6 9H2v6h4l5 4Zm4 5 6 6m0-6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-play" viewBox="0 0 24 24"><path d="m8 5 11 7-11 7Z" fill="currentColor"/></symbol>
<symbol id="i-chevron" viewBox="0 0 24 24"><path d="m8 10 4 4 4-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-close" viewBox="0 0 24 24"><path d="m6 6 12 12M18 6 6 18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
<symbol id="i-send" viewBox="0 0 24 24"><path d="m22 2-7 20-4-9-9-4Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><path d="M22 2 11 13" fill="none" stroke="currentColor" stroke-width="2"/></symbol>
<symbol id="i-link" viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
<symbol id="i-code" viewBox="0 0 24 24"><path d="m8 9-4 3 4 3m8-6 4 3-4 3m-2-9-4 12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-flag" viewBox="0 0 24 24"><path d="M5 21V4m0 1h11l-2 4 2 4H5" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
<symbol id="i-settings" viewBox="0 0 24 24"><path d="M12 15.2a3.2 3.2 0 1 0 0-6.4 3.2 3.2 0 0 0 0 6.4Z" fill="none" stroke="currentColor" stroke-width="2"/><path d="M19.4 15a1.7 1.7 0 0 0 .34 1.88l.06.06-2.86 2.86-.06-.06A1.7 1.7 0 0 0 15 19.4a1.7 1.7 0 0 0-1 .6 1.7 1.7 0 0 0-.4 1.1V21H9.55v-.09A1.7 1.7 0 0 0 8.5 19.4a1.7 1.7 0 0 0-1.88.34l-.06.06-2.86-2.86.06-.06A1.7 1.7 0 0 0 4.1 15a1.7 1.7 0 0 0-.6-1 1.7 1.7 0 0 0-1.1-.4H2.3V9.55h.09A1.7 1.7 0 0 0 4.1 8.5a1.7 1.7 0 0 0-.34-1.88l-.06-.06L6.56 3.7l.06.06A1.7 1.7 0 0 0 8.5 4.1a1.7 1.7 0 0 0 1-.6 1.7 1.7 0 0 0 .4-1.1V2.3h4.05v.09A1.7 1.7 0 0 0 15 4.1a1.7 1.7 0 0 0 1.88-.34l.06-.06 2.86 2.86-.06.06A1.7 1.7 0 0 0 19.4 8.5a1.7 1.7 0 0 0 .6 1c.3.26.7.4 1.1.4h.1v4.05h-.09A1.7 1.7 0 0 0 19.4 15Z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></symbol>
</svg>
<header class="app-header">
<a class="brand" id="brandLink" href="#videoFeed" aria-label="TikTok 首页"><span class="brand-mark"><span></span></span><span id="brandText">TikTok</span></a>
<label class="search-wrap"><span class="sr-only">搜索视频</span><svg><use href="#i-search"/></svg><input id="searchInput" class="search-input" type="search" placeholder="搜索你感兴趣的内容" /></label>
<div class="header-actions"><button class="upload-button" id="uploadButton"><svg><use href="#i-upload"/></svg><span>上传</span></button><button class="icon-button" aria-label="消息"><svg><use href="#i-message"/></svg></button><button class="icon-button" aria-label="通知"><svg><use href="#i-bell"/></svg><span class="header-badge" id="notificationBadge">3</span></button><span id="headerUser"></span></div>
</header>
<aside class="left-sidebar" aria-label="侧边导航">
<nav class="side-nav" id="sideNav"></nav>
<div class="login-card"><p id="loginPrompt"></p><button class="login-button" id="loginButton"></button></div>
<section class="side-section"><div class="side-title"><span id="sidebarTitle"></span></div><div id="sidebarRecommendations"></div></section>
<footer class="side-footer" id="sideFooter"></footer>
</aside>
<div class="channel-tabs" id="channelTabs" role="tablist"></div>
<main class="feed-shell" id="videoFeed">
<h1 class="sr-only" id="feedTitle">TikTok 短视频推荐流</h1>
<div class="feed-scroll" id="feedScroll"></div>
<button class="feed-arrow feed-prev" id="prevVideo" aria-label="上一个视频"><svg style="transform:rotate(180deg)"><use href="#i-chevron"/></svg></button><button class="feed-arrow feed-next" id="nextVideo" aria-label="下一个视频"><svg><use href="#i-chevron"/></svg></button>
</main>
<nav class="mobile-nav" id="mobileNav" aria-label="移动端导航"></nav>
<div class="comments-backdrop" id="commentsBackdrop" aria-hidden="true"><section class="comments-drawer" role="dialog" aria-modal="true" aria-labelledby="commentsTitle"><header class="drawer-head"><h2 id="commentsTitle"></h2><button class="icon-button" id="closeComments" aria-label="关闭评论"><svg><use href="#i-close"/></svg></button></header><div class="comments-list" id="commentsList"></div><form class="comment-form"><label class="sr-only" for="commentInput">发表评论</label><input id="commentInput" maxlength="120" placeholder="说点什么…" /><button class="comment-send" aria-label="发送评论"><svg><use href="#i-send"/></svg></button></form></section></div>
<section class="share-sheet" id="shareSheet" aria-hidden="true"><header class="share-head"><h2 id="shareTitle"></h2><button class="icon-button" id="closeShare" aria-label="关闭分享"><svg><use href="#i-close"/></svg></button></header><div class="share-options" id="shareOptions"></div></section>
<button class="settings-trigger" id="openSettings" aria-label="编辑页面 JSON" title="编辑页面 JSON"><svg><use href="#i-settings"/></svg></button>
<div class="settings-backdrop" id="settingsModal" aria-hidden="true">
<section class="settings-panel" role="dialog" aria-modal="true" aria-labelledby="settingsTitle">
<header class="settings-head"><div><div class="settings-kicker">TikTok 页面控制台</div><h2 id="settingsTitle">JSON 编辑器</h2></div><button class="settings-close" id="closeSettings" aria-label="关闭 JSON 编辑器"><svg><use href="#i-close"/></svg></button></header>
<div class="settings-body">
<nav class="module-tabs" id="moduleTabs" aria-label="JSON 模块"><h3>页面模块</h3></nav>
<div class="editor-pane"><div class="editor-title"><strong id="editorModuleTitle">站点信息</strong><span>只编辑当前模块</span></div><textarea class="json-editor" id="jsonEditor" spellcheck="false" aria-label="当前模块 JSON"></textarea><div class="editor-hint"><span>修改后先校验,再应用到页面。</span><span class="json-status valid" id="jsonStatus">JSON 有效</span></div></div>
</div>
<footer class="settings-actions"><div class="action-group"><button class="settings-button" id="copyJson">复制完整 JSON</button><button class="settings-button" id="downloadJson">下载 JSON</button><button class="settings-button danger" id="resetJson">恢复初始数据</button></div><button class="settings-button primary" id="applyJson">应用并渲染</button></footer>
</section>
</div>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<script type="application/json" id="tiktokPageData">__TIKTOK_PAGE_DATA__</script>
<script>__TIKTOK_PAGE_RUNTIME__</script>
</body>
</html>
@@ -0,0 +1,49 @@
# TikTok 页面 JSON 契约
源文件必须是 JSON 对象,并包含以下六个顶层模块。字段可增加,但不能删除顶层模块。
## `site`
- `brand`、`pageTitle`、`description`、`feedTitle`、`searchPlaceholder`、`uploadLabel`:非空字符串。
- `currentUser`:当前登录账号,包含 `name`、`handle`、`initial`、`colors`(两个 `#RRGGBB`)和非负 `notifications`。
## `navigation`
- `primary`:桌面侧栏导航,最多 10 项;每项 `{label, icon, href}`。
- `channels`:1–5 个频道标签字符串,推荐顺序为关注、推荐、同城。
- `mobile`:移动端导航,最多 7 项;每项 `{label, icon}`,创作按钮可使用 `icon: "i-plus"`。
- `footer`:侧栏页脚文字。
- `href` 只使用页面内锚点,例如 `#videoFeed`、`#discover`。
可用图标:`i-home`、`i-compass`、`i-users`、`i-live`、`i-user`、`i-message`、`i-plus`。
## `videos`
- `items`:1–20 条,`id` 必须唯一。
- 核心字段:`id`、`author`、`handle`、`initial`、`colors`、`text`、`tags`、`music`、`visual`、`ariaLabel`。
- `visual` 仅为 `neon-city`、`coffee`、`mountain`。
- 可选 `media` 会替换内置 `visual`:图片 `{type:"image", mediaUrl, alt?, pageUrl?}`;视频 `{type:"video", mediaUrl, posterUrl?, alt?, pageUrl?}`;网页 `{type:"webpage", pageUrl, title, description?, mediaUrl?, embed?}`。URL 只接受 `http(s)`;图片和视频也允许对应的 `data:` URL。
- `metrics`:`{likes, comments, saves}`,均为非负数字。
## `sidebar`
- `loginPrompt`、`loginLabel`、`title`:非空字符串。
- `recommendations`:0–20 项,每项 `{name, handle, initial, colors}`。
## `comments`
- `titleSuffix`、`inputPlaceholder`:非空字符串。
- `items`:0–30 项,每项包含 `id`、`name`、`initial`、`colors`、`text`、`time`、非负 `likes`。
## `share`
- `title`:非空字符串。
- `options`:1–8 项,每项 `{label, icon, toast, action}`。
- `action` 只使用 `copy-link` 或 `notice`。
- 可用图标:`i-link`、`i-message`、`i-code`、`i-flag`。
## 示例边界
- `assets/default-data.json` 只提供结构和演示内容,不是事实来源。
- 所有颜色使用完整六位十六进制;无效颜色由模板回退。
- JSON 使用双引号,不允许注释、Markdown 围栏或尾逗号。
@@ -0,0 +1,11 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "_shared"))
import render_tiktok_page as renderer
from fast_patch_page import run
if __name__ == "__main__":
sys.exit(run(renderer, output_stem="tiktok-page"))
@@ -0,0 +1,495 @@
#!/usr/bin/env python3
"""Validate TikTok page data and inject it into the bundled HTML template."""
from __future__ import annotations
import argparse
import html as html_lib
import json
import re
import sys
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
SKILL_ROOT = Path(__file__).resolve().parent.parent
ASSETS_DIR = SKILL_ROOT / "assets"
DEFAULT_DATA_PATH = ASSETS_DIR / "default-data.json"
TEMPLATE_PATH = ASSETS_DIR / "tiktok-template.html"
RUNTIME_PATH = ASSETS_DIR / "tiktok-runtime.js"
DATA_MARKER = "__TIKTOK_PAGE_DATA__"
RUNTIME_MARKER = "__TIKTOK_PAGE_RUNTIME__"
TITLE_RE = re.compile(r"<title>[^<]*</title>", re.IGNORECASE)
MODULES = ("site", "navigation", "videos", "sidebar", "comments", "share")
VISUAL_TYPES = {"neon-city", "coffee", "mountain"}
REMOTE_MEDIA_TYPES = {"image", "video", "webpage"}
SHARE_ACTIONS = {"copy-link", "notice"}
class DataValidationError(ValueError):
"""Raised when the TikTok page JSON cannot satisfy the template contract."""
def _read_json(path: Path) -> dict[str, Any]:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError as exc:
raise DataValidationError(f"JSON file does not exist: {path}") from exc
except json.JSONDecodeError as exc:
raise DataValidationError(
f"Invalid JSON at line {exc.lineno}, column {exc.colno}: {exc.msg}"
) from exc
if not isinstance(data, dict):
raise DataValidationError("Top-level JSON value must be an object")
return data
def _mapping(value: Any, path: str, errors: list[str]) -> dict[str, Any]:
if not isinstance(value, dict):
errors.append(f"{path} must be an object")
return {}
return value
def _array(
value: Any,
path: str,
errors: list[str],
*,
limit: int | None = None,
) -> list[Any]:
if not isinstance(value, list):
errors.append(f"{path} must be an array")
return []
if limit is not None and len(value) > limit:
errors.append(f"{path} may contain at most {limit} items")
return value
def _non_empty_string(value: Any, path: str, errors: list[str]) -> None:
if not isinstance(value, str) or not value.strip():
errors.append(f"{path} must be a non-empty string")
def _remote_url(value: Any, path: str, errors: list[str], *, required: bool = False, data_prefix: str = "") -> None:
if value in (None, "") and not required:
return
if not isinstance(value, str) or not value.strip():
errors.append(f"{path} must be a non-empty URL")
return
candidate = value.strip()
if data_prefix and candidate.lower().startswith(data_prefix):
return
parsed = urlparse(candidate)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
errors.append(f"{path} must use an http(s) URL")
def _validate_remote_media(value: Any, path: str, errors: list[str]) -> None:
if value is None:
return
media = _mapping(value, path, errors)
media_type = media.get("type")
if media_type not in REMOTE_MEDIA_TYPES:
errors.append(f"{path}.type must be one of: {', '.join(sorted(REMOTE_MEDIA_TYPES))}")
return
if media_type in {"image", "video"}:
_remote_url(media.get("mediaUrl"), f"{path}.mediaUrl", errors, required=True, data_prefix=f"data:{media_type}/")
if media_type == "video":
_remote_url(media.get("posterUrl"), f"{path}.posterUrl", errors, data_prefix="data:image/")
if media_type == "webpage":
_remote_url(media.get("pageUrl"), f"{path}.pageUrl", errors, required=True)
_remote_url(media.get("mediaUrl"), f"{path}.mediaUrl", errors, data_prefix="data:image/")
if "embed" in media and not isinstance(media.get("embed"), bool):
errors.append(f"{path}.embed must be a boolean")
else:
_remote_url(media.get("pageUrl"), f"{path}.pageUrl", errors)
def _non_negative_number(value: Any, path: str, errors: list[str]) -> None:
if (
not isinstance(value, (int, float))
or isinstance(value, bool)
or value < 0
):
errors.append(f"{path} must be a non-negative number")
def _colors(value: Any, path: str, errors: list[str]) -> None:
if (
not isinstance(value, list)
or len(value) != 2
or not all(isinstance(color, str) for color in value)
):
errors.append(f"{path} must contain exactly two color strings")
def _validate_people(items: list[Any], path: str, errors: list[str]) -> None:
for index, item in enumerate(items):
person = _mapping(item, f"{path}[{index}]", errors)
for key in ("name", "handle", "initial"):
_non_empty_string(
person.get(key),
f"{path}[{index}].{key}",
errors,
)
_colors(person.get("colors"), f"{path}[{index}].colors", errors)
def validate_document(data: dict[str, Any]) -> dict[str, Any]:
errors: list[str] = []
for module in MODULES:
if module not in data:
errors.append(f"Missing top-level module: {module}")
site = _mapping(data.get("site"), "site", errors)
for key in (
"brand",
"pageTitle",
"description",
"feedTitle",
"searchPlaceholder",
"uploadLabel",
):
_non_empty_string(site.get(key), f"site.{key}", errors)
current_user = _mapping(site.get("currentUser"), "site.currentUser", errors)
for key in ("name", "handle", "initial"):
_non_empty_string(
current_user.get(key),
f"site.currentUser.{key}",
errors,
)
_colors(current_user.get("colors"), "site.currentUser.colors", errors)
_non_negative_number(
current_user.get("notifications"),
"site.currentUser.notifications",
errors,
)
navigation = _mapping(data.get("navigation"), "navigation", errors)
for key, limit in (("primary", 10), ("mobile", 7)):
items = _array(
navigation.get(key),
f"navigation.{key}",
errors,
limit=limit,
)
for index, item in enumerate(items):
nav_item = _mapping(
item,
f"navigation.{key}[{index}]",
errors,
)
_non_empty_string(
nav_item.get("label"),
f"navigation.{key}[{index}].label",
errors,
)
_non_empty_string(
nav_item.get("icon"),
f"navigation.{key}[{index}].icon",
errors,
)
channels = _array(
navigation.get("channels"),
"navigation.channels",
errors,
limit=5,
)
if not channels:
errors.append("navigation.channels must contain at least one channel")
if not all(isinstance(item, str) and item.strip() for item in channels):
errors.append(
"navigation.channels must contain non-empty strings"
)
_non_empty_string(navigation.get("footer"), "navigation.footer", errors)
videos = _mapping(data.get("videos"), "videos", errors)
video_items = _array(
videos.get("items"),
"videos.items",
errors,
limit=20,
)
if not video_items:
errors.append("videos.items must contain at least one video")
video_ids: set[str] = set()
for index, item in enumerate(video_items):
video = _mapping(item, f"videos.items[{index}]", errors)
video_id = video.get("id")
_non_empty_string(video_id, f"videos.items[{index}].id", errors)
if isinstance(video_id, str):
if video_id in video_ids:
errors.append(f"videos.items[{index}].id must be unique")
video_ids.add(video_id)
for key in (
"author",
"handle",
"initial",
"text",
"music",
"ariaLabel",
):
_non_empty_string(
video.get(key),
f"videos.items[{index}].{key}",
errors,
)
_colors(video.get("colors"), f"videos.items[{index}].colors", errors)
visual = video.get("visual")
if visual not in VISUAL_TYPES:
errors.append(
f"videos.items[{index}].visual must be one of: "
f"{', '.join(sorted(VISUAL_TYPES))}"
)
_validate_remote_media(video.get("media"), f"videos.items[{index}].media", errors)
tags = _array(
video.get("tags"),
f"videos.items[{index}].tags",
errors,
limit=8,
)
if not all(isinstance(tag, str) and tag.strip() for tag in tags):
errors.append(
f"videos.items[{index}].tags "
"must contain non-empty strings"
)
metrics = _mapping(
video.get("metrics"),
f"videos.items[{index}].metrics",
errors,
)
for key in ("likes", "comments", "saves"):
_non_negative_number(
metrics.get(key),
f"videos.items[{index}].metrics.{key}",
errors,
)
sidebar = _mapping(data.get("sidebar"), "sidebar", errors)
for key in ("loginPrompt", "loginLabel", "title"):
_non_empty_string(sidebar.get(key), f"sidebar.{key}", errors)
recommendations = _array(
sidebar.get("recommendations"),
"sidebar.recommendations",
errors,
limit=20,
)
_validate_people(
recommendations,
"sidebar.recommendations",
errors,
)
comments = _mapping(data.get("comments"), "comments", errors)
for key in ("titleSuffix", "inputPlaceholder"):
_non_empty_string(comments.get(key), f"comments.{key}", errors)
comment_items = _array(
comments.get("items"),
"comments.items",
errors,
limit=30,
)
comment_ids: set[str] = set()
for index, item in enumerate(comment_items):
comment = _mapping(item, f"comments.items[{index}]", errors)
comment_id = comment.get("id")
_non_empty_string(
comment_id,
f"comments.items[{index}].id",
errors,
)
if isinstance(comment_id, str):
if comment_id in comment_ids:
errors.append(
f"comments.items[{index}].id must be unique"
)
comment_ids.add(comment_id)
for key in ("name", "initial", "text", "time"):
_non_empty_string(
comment.get(key),
f"comments.items[{index}].{key}",
errors,
)
_colors(
comment.get("colors"),
f"comments.items[{index}].colors",
errors,
)
_non_negative_number(
comment.get("likes"),
f"comments.items[{index}].likes",
errors,
)
share = _mapping(data.get("share"), "share", errors)
_non_empty_string(share.get("title"), "share.title", errors)
share_options = _array(
share.get("options"),
"share.options",
errors,
limit=8,
)
if not share_options:
errors.append("share.options must contain at least one option")
for index, item in enumerate(share_options):
option = _mapping(item, f"share.options[{index}]", errors)
for key in ("label", "icon", "toast"):
_non_empty_string(
option.get(key),
f"share.options[{index}].{key}",
errors,
)
if option.get("action") not in SHARE_ACTIONS:
errors.append(
f"share.options[{index}].action must be one of: "
f"{', '.join(sorted(SHARE_ACTIONS))}"
)
if errors:
raise DataValidationError("; ".join(errors))
return {
"modules": list(MODULES),
"counts": {
"videos": len(video_items),
"recommendations": len(recommendations),
"comments": len(comment_items),
"share_options": len(share_options),
},
}
def render_document(data: dict[str, Any], template: str, runtime: str) -> str:
validate_document(data)
if template.count(DATA_MARKER) != 1:
raise DataValidationError(
"Bundled template must contain exactly one data marker"
)
if template.count(RUNTIME_MARKER) != 1:
raise DataValidationError(
"Bundled template must contain exactly one runtime marker"
)
serialized = json.dumps(data, ensure_ascii=False, indent=2).replace(
"</",
"<\\/",
)
safe_runtime = runtime.replace("</script", "<\\/script")
rendered = template.replace(DATA_MARKER, serialized)
rendered = rendered.replace(RUNTIME_MARKER, safe_runtime)
page_title = str((data.get("site") or {}).get("pageTitle") or "").strip()
if page_title:
rendered = TITLE_RE.sub(
f"<title>{html_lib.escape(page_title)}</title>",
rendered,
count=1,
)
return rendered
def _write_new(path: Path, content: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
try:
with path.open("x", encoding="utf-8", newline="\n") as handle:
handle.write(content)
except FileExistsError as exc:
raise DataValidationError(
f"Refusing to overwrite existing file: {path}"
) from exc
def _emit(payload: dict[str, Any]) -> None:
print(json.dumps(payload, ensure_ascii=False))
def _command_init(output: Path) -> dict[str, Any]:
data = _read_json(DEFAULT_DATA_PATH)
summary = validate_document(data)
_write_new(
output,
json.dumps(data, ensure_ascii=False, indent=2) + "\n",
)
return {
"status": "ok",
"action": "init",
"output": str(output),
**summary,
}
def _command_validate(input_path: Path) -> dict[str, Any]:
data = _read_json(input_path)
summary = validate_document(data)
return {
"status": "ok",
"action": "validate",
"input": str(input_path),
**summary,
}
def _command_render(input_path: Path, output: Path) -> dict[str, Any]:
data = _read_json(input_path)
template = TEMPLATE_PATH.read_text(encoding="utf-8")
runtime = RUNTIME_PATH.read_text(encoding="utf-8")
rendered = render_document(data, template, runtime)
_write_new(output, rendered)
summary = validate_document(data)
return {
"status": "ok",
"action": "render",
"input": str(input_path),
"output": str(output),
**summary,
}
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(dest="command", required=True)
init_parser = subparsers.add_parser(
"init",
help="Create a new editable JSON document",
)
init_parser.add_argument("--output", type=Path, required=True)
validate_parser = subparsers.add_parser(
"validate",
help="Validate an existing JSON document",
)
validate_parser.add_argument("--input", type=Path, required=True)
render_parser = subparsers.add_parser(
"render",
help="Render validated JSON into the bundled HTML template",
)
render_parser.add_argument("--input", type=Path, required=True)
render_parser.add_argument("--output", type=Path, required=True)
return parser
def main(argv: list[str] | None = None) -> int:
parser = _build_parser()
args = parser.parse_args(argv)
try:
if args.command == "init":
result = _command_init(args.output)
elif args.command == "validate":
result = _command_validate(args.input)
else:
result = _command_render(args.input, args.output)
except (DataValidationError, OSError) as exc:
_emit({
"status": "error",
"action": args.command,
"error": str(exc),
})
return 2
_emit(result)
return 0
if __name__ == "__main__":
sys.exit(main())