sync update from LAN repo (source master @ ca48c4ec)
This commit is contained in:
1 parent
8bc8b0e082
commit
ea9dcff9c0
873 files changed
+107866
-14011
No files matched your search
@@ -0,0 +1,83 @@
|
||||
---
|
||||
name: youtube-page-generator
|
||||
description: 生成或绘制 YouTube 及 YouTube 风格的可交付视频门户 HTML 网页;仅在用户明确要求 YouTube 网页、YouTube 风格视频首页或点名本技能时使用。先把材料或检索结果整理成七模块 JSON,再用内置模板确定性渲染,保留右上角可视化 JSON 编辑弹窗。
|
||||
allowed-tools:
|
||||
- read_file
|
||||
- write_file
|
||||
- bash
|
||||
- present_files
|
||||
- web_search
|
||||
---
|
||||
|
||||
# YouTube 页面生成器
|
||||
|
||||
本技能使用固定模板生成单文件 YouTube 风格视频门户。模型只负责材料收集和 JSON,禁止重新手写页面结构、CSS 或运行时脚本。最终页面自带右上角设置按钮;用户可在弹窗中按模块编辑 JSON,并通过「应用并渲染」即时更新页面。
|
||||
|
||||
编辑弹窗还提供“上传图片/视频”:先把光标放进目标报道、帖子、视频或带 `visual`/`media` 的内容对象,上传文件会转换为 `data:` 地址并写入该对象的 `media` 字段。不设文件大小拦截;较大文件可能超过浏览器本地缓存容量,应同时下载 JSON 留存。
|
||||
|
||||
页面中已由 `media` 数据渲染的图片和视频还带悬浮上传图标:鼠标移入媒体后点击可任选图片或视频并直接替换,文件的实际类型会自动写入新的 `media.type`,结果同步写回页面 JSON 与浏览器缓存。头像、Logo 和无法映射回 JSON 的装饰图不会显示该入口;不按原媒体类型限制,也不设置文件大小拦截。
|
||||
|
||||
默认视觉直接复用模板原有的示例图:不要调用图像生成工具,不要让模型重新生成、拼装或内嵌新的内容型 SVG,也不要为了寻找“标准配图”延长检索。用户没有提供可直接使用的图片/视频且聚焦检索未得到可靠直链时,保留默认 JSON 的 `visual` 或内置视觉类型;这些是模板自带的静态示例,调用技能时不重新绘制。不要把大段 base64 示例图重复写进 JSON,图不合适时由用户在成品页面悬浮上传替换。
|
||||
|
||||
## 触发边界
|
||||
|
||||
- 用户明确说「生成/画/制作 YouTube 网页」「YouTube 风格视频首页/频道页」或点名 `youtube-page-generator` 时使用。
|
||||
- 仅讨论 YouTube、分析视频平台、编写视频脚本或普通文本中出现视频链接时不要使用。
|
||||
- 这是单页视频门户模板,不改用 TikTok 竖屏信息流或通用多页门户模板。
|
||||
|
||||
## 极速工作流(默认)
|
||||
|
||||
页面结构已经固定。完成必要的材料整理后,模型只写一份小型规格 JSON;未写字段继续使用模板默认数据与示例视觉,脚本在一次进程内合并、校验并渲染。
|
||||
|
||||
1. 用 `write_file` 创建 `/mnt/user-data/outputs/youtube-page-spec.json`。直接写模块对象会做递归合并;修改数组中的单个字段优先用 `$set`,避免重写完整视频或评论对象:
|
||||
|
||||
```json
|
||||
{"site":{"pageTitle":"YouTube · 中文主题"},"$set":{"videos.items.0.title":"中文视频标题","videos.items.0.description":"中文视频简介","comments.items.0.text":"中文评论"}}
|
||||
```
|
||||
|
||||
2. 只执行一次 `python /mnt/skills/public/youtube-page-generator/scripts/fast_page.py --spec /mnt/user-data/outputs/youtube-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. 读取当前会话材料、上传附件和已有产物,确定页面主题、当前账号、分类、长视频、Shorts、订阅频道和评论。
|
||||
2. 用户要求基于公开资料、主题涉及近期事件,或明确要求检索时,先做至多两批聚焦检索;用户明确说不要检索时不得联网。没有材料时使用中性示例内容并明确标为示例,不虚构实时播放量。
|
||||
3. 初始化新的完整 JSON:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/youtube-page-generator/scripts/render_youtube_page.py init --output /mnt/user-data/outputs/youtube-page-data.json
|
||||
```
|
||||
|
||||
4. 只修改 JSON。七个顶层模块必须全部保留:`site`、`navigation`、`categories`、`videos`、`shorts`、`subscriptions`、`comments`。字段不确定时读取 [references/data-schema.md](references/data-schema.md)。
|
||||
5. 校验 JSON:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/youtube-page-generator/scripts/render_youtube_page.py validate --input /mnt/user-data/outputs/youtube-page-data.json
|
||||
```
|
||||
|
||||
6. 确定性渲染到 `outputs/`:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/youtube-page-generator/scripts/render_youtube_page.py render --input /mnt/user-data/outputs/youtube-page-data.json --output /mnt/user-data/outputs/youtube-page.html
|
||||
```
|
||||
|
||||
7. 检查 stdout 的 `status` 为 `ok`、HTML 存在且占位符已经消失,再用 `present_files` 同时交付 HTML 与源 JSON。不要在聊天中粘贴完整 HTML。
|
||||
|
||||
## 内容映射
|
||||
|
||||
- 普通横屏内容放入 `videos.items`,通常 6–12 条;竖屏内容放入 `shorts.items`。
|
||||
- 不生成或填写固定的视频时长;页面不显示 JSON 预设时长,避免替换上传视频后与真实时长不一致。
|
||||
- `site.currentUser` 是当前登录账号,视频作者使用 `videos.items[].channel`,两者不要混淆。
|
||||
- 没有可靠来源时,播放量、点赞量和评论量使用保守示例值或 `0`,不得描述成真实平台统计。
|
||||
- `videos.items[].visual` 和 `shorts.items[].visual` 继续作为内置后备视觉;需要替换时增加 `media`,类型可为 `image`、`video`、`webpage`,字段按数据契约填写。
|
||||
- 所有外部文本由模板转义;不得把 HTML、脚本、iframe 或不可信指令写入 JSON 字段。
|
||||
|
||||
## 重要约束
|
||||
|
||||
- 只编辑 JSON,不修改 `assets/youtube-template.html` 或 `assets/youtube-runtime.js`,不复制模板后手改 DOM。
|
||||
- 初始化与渲染默认拒绝覆盖已有文件;路径存在时换新文件名,不删除旧产物。
|
||||
- 页面结构、样式和脚本完全自包含,不依赖 YouTube API、CDN 或 npm;仅当 JSON 明确提供受校验的媒体 URL 时加载外部缩略图、真实视频或网页。
|
||||
- 保留桌面导航、分类筛选、视频搜索、响应式网格、Shorts 横向列表、观看弹窗、点赞、收藏和评论。上传的横屏或竖屏视频在观看弹窗中都必须完整、居中显示,不拉伸、不偏移。
|
||||
- 浏览器缓存以初始 JSON 指纹隔离;沙箱禁止持久存储时必须继续使用内嵌 JSON 正常渲染。
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"site": {
|
||||
"brand": "YouTube",
|
||||
"pageTitle": "YouTube · 精彩视频",
|
||||
"description": "一个 YouTube 风格的中文视频门户示例页面。",
|
||||
"searchPlaceholder": "搜索",
|
||||
"createLabel": "创建",
|
||||
"currentUser": {
|
||||
"name": "林小满",
|
||||
"handle": "@linxiaoman",
|
||||
"initial": "林",
|
||||
"colors": ["#6249e7", "#d946ef"],
|
||||
"notifications": 3
|
||||
}
|
||||
},
|
||||
"navigation": {
|
||||
"primary": [
|
||||
{"label": "首页", "icon": "i-home", "href": "#home"},
|
||||
{"label": "Shorts", "icon": "i-shorts", "href": "#shorts"},
|
||||
{"label": "订阅内容", "icon": "i-subscriptions", "href": "#subscriptions"}
|
||||
],
|
||||
"library": [
|
||||
{"label": "历史记录", "icon": "i-history", "href": "#history"},
|
||||
{"label": "播放列表", "icon": "i-playlist", "href": "#playlists"},
|
||||
{"label": "稍后观看", "icon": "i-clock", "href": "#watch-later"},
|
||||
{"label": "顶过的视频", "icon": "i-like", "href": "#liked"}
|
||||
],
|
||||
"mobile": [
|
||||
{"label": "首页", "icon": "i-home"},
|
||||
{"label": "Shorts", "icon": "i-shorts"},
|
||||
{"label": "订阅", "icon": "i-subscriptions"},
|
||||
{"label": "我的", "icon": "i-user"}
|
||||
],
|
||||
"footer": "关于 · 版权 · 联系我们\n创作者 · 广告 · 开发者\nYouTube © 2026"
|
||||
},
|
||||
"categories": {
|
||||
"items": ["全部", "音乐", "直播", "编程", "设计", "旅行", "美食", "科学", "最近上传"]
|
||||
},
|
||||
"videos": {
|
||||
"sectionTitle": "推荐视频",
|
||||
"items": [
|
||||
{
|
||||
"id": "city-night",
|
||||
"title": "夜色里的城市:从黄昏走到凌晨",
|
||||
"channel": "城市漫游指南",
|
||||
"channelInitial": "城",
|
||||
"channelColors": ["#0ea5e9", "#6366f1"],
|
||||
"category": "旅行",
|
||||
"views": "128 万次观看",
|
||||
"time": "2 天前",
|
||||
"visual": "city",
|
||||
"verified": true,
|
||||
"description": "沿着河岸和旧街区,记录城市入夜后的光线与声音。",
|
||||
"metrics": {"likes": 86000, "comments": 3206}
|
||||
},
|
||||
{
|
||||
"id": "design-studio",
|
||||
"title": "一个设计工作室的一天|从草图到成品",
|
||||
"channel": "形与色",
|
||||
"channelInitial": "形",
|
||||
"channelColors": ["#f97316", "#ec4899"],
|
||||
"category": "设计",
|
||||
"views": "74 万次观看",
|
||||
"time": "5 天前",
|
||||
"visual": "studio",
|
||||
"verified": true,
|
||||
"description": "跟随团队完成一套品牌视觉,从讨论、草图到最终交付。",
|
||||
"metrics": {"likes": 52000, "comments": 1860}
|
||||
},
|
||||
{
|
||||
"id": "home-cooking",
|
||||
"title": "三道适合周末的家常菜,简单又温暖",
|
||||
"channel": "慢慢吃饭",
|
||||
"channelInitial": "慢",
|
||||
"channelColors": ["#ef4444", "#f59e0b"],
|
||||
"category": "美食",
|
||||
"views": "96 万次观看",
|
||||
"time": "1 周前",
|
||||
"visual": "food",
|
||||
"verified": false,
|
||||
"description": "不用复杂调料,也能做出适合与家人分享的周末晚餐。",
|
||||
"metrics": {"likes": 67000, "comments": 2412}
|
||||
},
|
||||
{
|
||||
"id": "mountain-trail",
|
||||
"title": "翻过山脊之后,遇见今年最美的日落",
|
||||
"channel": "在路上的阿川",
|
||||
"channelInitial": "川",
|
||||
"channelColors": ["#10b981", "#0ea5e9"],
|
||||
"category": "旅行",
|
||||
"views": "203 万次观看",
|
||||
"time": "3 天前",
|
||||
"visual": "mountain",
|
||||
"verified": true,
|
||||
"description": "一次两天一夜的山脊徒步,天气和光线都恰到好处。",
|
||||
"metrics": {"likes": 142000, "comments": 5921}
|
||||
},
|
||||
{
|
||||
"id": "build-app",
|
||||
"title": "从零构建一个小应用:思路、代码与复盘",
|
||||
"channel": "代码之外",
|
||||
"channelInitial": "码",
|
||||
"channelColors": ["#8b5cf6", "#3b82f6"],
|
||||
"category": "编程",
|
||||
"views": "48 万次观看",
|
||||
"time": "8 小时前",
|
||||
"visual": "code",
|
||||
"verified": false,
|
||||
"description": "把一个想法拆成可实现的功能,并逐步完成一个可用原型。",
|
||||
"metrics": {"likes": 39000, "comments": 1784}
|
||||
},
|
||||
{
|
||||
"id": "space-science",
|
||||
"title": "如果站在月球上看地球,会看到什么?",
|
||||
"channel": "好奇实验室",
|
||||
"channelInitial": "好",
|
||||
"channelColors": ["#06b6d4", "#8b5cf6"],
|
||||
"category": "科学",
|
||||
"views": "316 万次观看",
|
||||
"time": "2 周前",
|
||||
"visual": "science",
|
||||
"verified": true,
|
||||
"description": "用动画和简单实验解释从月球观察地球时会发生什么。",
|
||||
"metrics": {"likes": 224000, "comments": 8410}
|
||||
}
|
||||
]
|
||||
},
|
||||
"shorts": {
|
||||
"sectionTitle": "Shorts",
|
||||
"items": [
|
||||
{"id": "short-music", "title": "把雨声做成一段旋律", "views": "86 万次观看", "visual": "music"},
|
||||
{"id": "short-food", "title": "30 秒学会一份早餐", "views": "124 万次观看", "visual": "food"},
|
||||
{"id": "short-travel", "title": "转角遇见海边小镇", "views": "57 万次观看", "visual": "travel"},
|
||||
{"id": "short-science", "title": "水滴为什么是圆的?", "views": "91 万次观看", "visual": "science"},
|
||||
{"id": "short-code", "title": "一行代码的小惊喜", "views": "43 万次观看", "visual": "code"}
|
||||
]
|
||||
},
|
||||
"subscriptions": {
|
||||
"title": "订阅",
|
||||
"items": [
|
||||
{"name": "城市漫游指南", "handle": "@citywalk", "initial": "城", "colors": ["#0ea5e9", "#6366f1"]},
|
||||
{"name": "形与色", "handle": "@shapeandcolor", "initial": "形", "colors": ["#f97316", "#ec4899"]},
|
||||
{"name": "好奇实验室", "handle": "@curiouslab", "initial": "好", "colors": ["#06b6d4", "#8b5cf6"]}
|
||||
]
|
||||
},
|
||||
"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}
|
||||
]
|
||||
}
|
||||
}
|
||||
+740
@@ -0,0 +1,740 @@
|
||||
(() => {
|
||||
"use strict";
|
||||
|
||||
const qs = (selector, root = document) => root.querySelector(selector);
|
||||
const qsa = (selector, root = document) => Array.from(root.querySelectorAll(selector));
|
||||
const clone = (value) => JSON.parse(JSON.stringify(value));
|
||||
const MODULES = ["site", "navigation", "categories", "videos", "shorts", "subscriptions", "comments"];
|
||||
const MODULE_META = {
|
||||
site: ["站点信息", "品牌、标题与当前账号"],
|
||||
navigation: ["导航", "主导航、资料库与移动导航"],
|
||||
categories: ["分类", "顶部筛选标签"],
|
||||
videos: ["视频", "横屏视频卡片和观看数据"],
|
||||
shorts: ["Shorts", "竖屏短视频列表"],
|
||||
subscriptions: ["订阅", "侧栏订阅频道"],
|
||||
comments: ["评论", "观看弹窗评论"]
|
||||
};
|
||||
const NAV_ICONS = new Set(["i-home", "i-shorts", "i-subscriptions", "i-history", "i-playlist", "i-clock", "i-like", "i-user"]);
|
||||
const VISUAL_TYPES = new Set(["city", "studio", "food", "mountain", "code", "science", "music", "travel"]);
|
||||
const embeddedData = JSON.parse(qs("#youtubePageData").textContent);
|
||||
const initialData = clone(embeddedData);
|
||||
|
||||
const fingerprint = (text) => {
|
||||
let hash = 2166136261;
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
hash ^= text.charCodeAt(index);
|
||||
hash = Math.imul(hash, 16777619);
|
||||
}
|
||||
return (hash >>> 0).toString(36);
|
||||
};
|
||||
const pageFingerprint = fingerprint(JSON.stringify(initialData));
|
||||
const storageKey = "youtube-page-data-v1:" + pageFingerprint;
|
||||
const themeKey = "youtube-page-theme-v1:" + pageFingerprint;
|
||||
|
||||
const readStorage = (key) => {
|
||||
try {
|
||||
return window.localStorage ? window.localStorage.getItem(key) : null;
|
||||
} catch (_error) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const writeStorage = (key, value) => {
|
||||
try {
|
||||
if (window.localStorage) window.localStorage.setItem(key, value);
|
||||
return true;
|
||||
} catch (_error) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const removeStorage = (key) => {
|
||||
try {
|
||||
if (window.localStorage) window.localStorage.removeItem(key);
|
||||
} catch (_error) {
|
||||
/* Sandboxed previews may intentionally deny storage. */
|
||||
}
|
||||
};
|
||||
const isCompleteData = (value) => Boolean(value && MODULES.every((name) => value[name] && typeof value[name] === "object"));
|
||||
const cachedData = readStorage(storageKey);
|
||||
let pageData = initialData;
|
||||
if (cachedData) {
|
||||
try {
|
||||
const parsed = JSON.parse(cachedData);
|
||||
if (isCompleteData(parsed)) pageData = parsed;
|
||||
} catch (_error) {
|
||||
pageData = initialData;
|
||||
}
|
||||
}
|
||||
|
||||
const escapeHTML = (value) => String(value == null ? "" : value).replace(/[&<>'"]/g, (character) => ({
|
||||
"&": "&", "<": "<", ">": ">", "'": "'", '"': """
|
||||
})[character]);
|
||||
const safeHref = (value) => String(value || "#").startsWith("#") ? escapeHTML(value) : "#";
|
||||
const safeRemoteUrl = (value, kind = "link") => {
|
||||
const source = String(value || "").trim();
|
||||
if (!source) return "";
|
||||
const lowered = source.toLowerCase();
|
||||
if (kind === "image" && lowered.startsWith("data:image/")) return source;
|
||||
if (kind === "video" && lowered.startsWith("data:video/")) return source;
|
||||
try {
|
||||
const url = new URL(source);
|
||||
return url.protocol === "http:" || url.protocol === "https:" ? url.href : "";
|
||||
} catch (_error) { return ""; }
|
||||
};
|
||||
const validateRemoteMediaTree = (value, path = "当前模块") => {
|
||||
if (Array.isArray(value)) return value.forEach((item, index) => validateRemoteMediaTree(item, path + "[" + index + "]"));
|
||||
if (!value || typeof value !== "object") return;
|
||||
const media = value.media;
|
||||
if (media && ["image", "video", "webpage"].includes(media.type)) {
|
||||
if ((media.type === "image" || media.type === "video") && !safeRemoteUrl(media.mediaUrl, media.type)) throw new Error(path + ".media.mediaUrl 无效");
|
||||
if (media.type === "webpage" && !safeRemoteUrl(media.pageUrl)) throw new Error(path + ".media.pageUrl 无效");
|
||||
if (media.posterUrl && !safeRemoteUrl(media.posterUrl, "image")) throw new Error(path + ".media.posterUrl 无效");
|
||||
}
|
||||
Object.entries(value).forEach(([key, item]) => { if (key !== "media") validateRemoteMediaTree(item, path + "." + key); });
|
||||
};
|
||||
const safeColor = (value, fallback) => /^#[0-9a-f]{6}$/i.test(String(value || "")) ? value : fallback;
|
||||
const safeIcon = (value) => NAV_ICONS.has(value) ? value : "i-home";
|
||||
const safeVisual = (value) => VISUAL_TYPES.has(value) ? value : "city";
|
||||
const icon = (id) => '<svg aria-hidden="true"><use href="#' + id + '"/></svg>';
|
||||
const colors = (person, key) => {
|
||||
const list = person && Array.isArray(person[key || "colors"]) ? person[key || "colors"] : [];
|
||||
return [safeColor(list[0], "#6249e7"), safeColor(list[1], "#d946ef")];
|
||||
};
|
||||
const avatar = (person, className, initialKey, colorsKey) => {
|
||||
const pair = colors(person || {}, colorsKey || "colors");
|
||||
return '<span class="avatar ' + (className || "") + '" style="--a:' + pair[0] + ";--b:" + pair[1] + '">' + escapeHTML((person && person[initialKey || "initial"]) || "Y") + "</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 palettes = {
|
||||
city: ["#1e1b4b", "#0f766e", "#fb7185"],
|
||||
studio: ["#312e81", "#c026d3", "#fbbf24"],
|
||||
food: ["#7f1d1d", "#ea580c", "#fde68a"],
|
||||
mountain: ["#164e63", "#0f766e", "#fbbf24"],
|
||||
code: ["#111827", "#1d4ed8", "#22d3ee"],
|
||||
science: ["#172554", "#6d28d9", "#67e8f9"],
|
||||
music: ["#3b0764", "#db2777", "#22d3ee"],
|
||||
travel: ["#0c4a6e", "#0284c7", "#facc15"]
|
||||
};
|
||||
const visualSvg = (type, vertical) => {
|
||||
const visual = safeVisual(type);
|
||||
const palette = palettes[visual];
|
||||
const width = vertical ? 360 : 640;
|
||||
const height = vertical ? 640 : 360;
|
||||
let shapes = "";
|
||||
if (visual === "city") {
|
||||
shapes = '<circle cx="' + (width * 0.76) + '" cy="' + (height * 0.25) + '" r="' + (height * 0.13) + '" fill="' + palette[2] + '" opacity=".85"/><g fill="#111827"><rect x="0" y="' + (height * 0.48) + '" width="' + (width * 0.16) + '" height="' + (height * 0.52) + '"/><rect x="' + (width * 0.14) + '" y="' + (height * 0.35) + '" width="' + (width * 0.2) + '" height="' + (height * 0.65) + '"/><rect x="' + (width * 0.31) + '" y="' + (height * 0.55) + '" width="' + (width * 0.18) + '" height="' + (height * 0.45) + '"/><rect x="' + (width * 0.47) + '" y="' + (height * 0.28) + '" width="' + (width * 0.22) + '" height="' + (height * 0.72) + '"/><rect x="' + (width * 0.67) + '" y="' + (height * 0.43) + '" width="' + (width * 0.18) + '" height="' + (height * 0.57) + '"/><rect x="' + (width * 0.83) + '" y="' + (height * 0.33) + '" width="' + (width * 0.17) + '" height="' + (height * 0.67) + '"/></g><g fill="' + palette[1] + '"><rect x="' + (width * 0.2) + '" y="' + (height * 0.45) + '" width="8" height="36"/><rect x="' + (width * 0.55) + '" y="' + (height * 0.42) + '" width="9" height="50"/><rect x="' + (width * 0.74) + '" y="' + (height * 0.56) + '" width="8" height="42"/></g>';
|
||||
} else if (visual === "mountain" || visual === "travel") {
|
||||
shapes = '<circle cx="' + (width * 0.76) + '" cy="' + (height * 0.25) + '" r="' + (height * 0.12) + '" fill="' + palette[2] + '"/><path d="M0 ' + height + 'V' + (height * 0.66) + 'L' + (width * 0.22) + ' ' + (height * 0.34) + 'L' + (width * 0.42) + ' ' + (height * 0.64) + 'L' + (width * 0.63) + ' ' + (height * 0.24) + 'L' + width + ' ' + (height * 0.7) + 'V' + height + 'Z" fill="#164e63"/><path d="M0 ' + height + 'V' + (height * 0.78) + 'Q' + (width * 0.45) + ' ' + (height * 0.62) + ' ' + width + ' ' + (height * 0.82) + 'V' + height + 'Z" fill="' + palette[1] + '"/>';
|
||||
} else if (visual === "code") {
|
||||
shapes = '<rect x="' + (width * 0.12) + '" y="' + (height * 0.16) + '" width="' + (width * 0.76) + '" height="' + (height * 0.68) + '" rx="18" fill="#0b1220" stroke="' + palette[2] + '" stroke-width="3"/><circle cx="' + (width * 0.18) + '" cy="' + (height * 0.24) + '" r="6" fill="#fb7185"/><circle cx="' + (width * 0.22) + '" cy="' + (height * 0.24) + '" r="6" fill="#fbbf24"/><path d="M' + (width * 0.2) + ' ' + (height * 0.39) + 'h' + (width * 0.28) + 'M' + (width * 0.2) + ' ' + (height * 0.5) + 'h' + (width * 0.52) + 'M' + (width * 0.2) + ' ' + (height * 0.61) + 'h' + (width * 0.38) + '" stroke="' + palette[2] + '" stroke-width="12" stroke-linecap="round"/>';
|
||||
} else if (visual === "food") {
|
||||
shapes = '<circle cx="' + (width * 0.5) + '" cy="' + (height * 0.52) + '" r="' + (height * 0.3) + '" fill="#fff7ed"/><circle cx="' + (width * 0.5) + '" cy="' + (height * 0.52) + '" r="' + (height * 0.22) + '" fill="' + palette[2] + '"/><circle cx="' + (width * 0.44) + '" cy="' + (height * 0.47) + '" r="' + (height * 0.08) + '" fill="' + palette[1] + '"/><path d="M' + (width * 0.14) + ' ' + (height * 0.18) + 'v' + (height * 0.64) + 'M' + (width * 0.86) + ' ' + (height * 0.18) + 'v' + (height * 0.64) + '" stroke="#fff" stroke-width="9" stroke-linecap="round" opacity=".7"/>';
|
||||
} else if (visual === "studio") {
|
||||
shapes = '<rect x="' + (width * 0.13) + '" y="' + (height * 0.16) + '" width="' + (width * 0.34) + '" height="' + (height * 0.68) + '" rx="18" fill="#fdf4ff" transform="rotate(-6 ' + (width * 0.3) + ' ' + (height * 0.5) + ')"/><circle cx="' + (width * 0.68) + '" cy="' + (height * 0.36) + '" r="' + (height * 0.18) + '" fill="' + palette[2] + '"/><path d="M' + (width * 0.55) + ' ' + (height * 0.65) + 'h' + (width * 0.3) + '" stroke="#fff" stroke-width="16" stroke-linecap="round"/>';
|
||||
} else if (visual === "science") {
|
||||
shapes = '<circle cx="' + (width * 0.52) + '" cy="' + (height * 0.46) + '" r="' + (height * 0.19) + '" fill="' + palette[2] + '"/><ellipse cx="' + (width * 0.52) + '" cy="' + (height * 0.46) + '" rx="' + (width * 0.36) + '" ry="' + (height * 0.12) + '" fill="none" stroke="#fff" stroke-width="5" transform="rotate(-15 ' + (width * 0.52) + ' ' + (height * 0.46) + ')"/><ellipse cx="' + (width * 0.52) + '" cy="' + (height * 0.46) + '" rx="' + (width * 0.34) + '" ry="' + (height * 0.1) + '" fill="none" stroke="' + palette[1] + '" stroke-width="5" transform="rotate(45 ' + (width * 0.52) + ' ' + (height * 0.46) + ')"/>';
|
||||
} else {
|
||||
shapes = '<circle cx="' + (width * 0.5) + '" cy="' + (height * 0.48) + '" r="' + (height * 0.24) + '" fill="#111827"/><path d="M' + (width * 0.45) + ' ' + (height * 0.3) + 'v' + (height * 0.42) + 'M' + (width * 0.45) + ' ' + (height * 0.3) + 'l' + (width * 0.18) + ' ' + (height * -0.05) + 'v' + (height * 0.34) + '" stroke="' + palette[2] + '" stroke-width="14" stroke-linecap="round"/><circle cx="' + (width * 0.39) + '" cy="' + (height * 0.7) + '" r="' + (height * 0.07) + '" fill="' + palette[2] + '"/><circle cx="' + (width * 0.57) + '" cy="' + (height * 0.63) + '" r="' + (height * 0.07) + '" fill="' + palette[2] + '"/>';
|
||||
}
|
||||
return '<svg viewBox="0 0 ' + width + " " + height + '" preserveAspectRatio="xMidYMid slice"><rect width="' + width + '" height="' + height + '" fill="' + palette[0] + '"/><circle cx="' + (width * 0.18) + '" cy="' + (height * 0.22) + '" r="' + (height * 0.2) + '" fill="' + palette[1] + '" opacity=".35"/>' + shapes + "</svg>";
|
||||
};
|
||||
|
||||
document.head.insertAdjacentHTML("beforeend", '<style data-external-media>.thumbnail-visual>img,.thumbnail-visual>video,.short-thumb>img,.short-thumb>video{width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}.watch-visual>img,.watch-visual>video,.watch-visual>iframe{width:100%;height:100%;display:block;border:0;background:#000}.watch-visual>img,.watch-visual>video{object-fit:contain;object-position:center center}.watch-visual>iframe{object-fit:initial}.watch-visual .external-page-link{position:absolute;right:14px;bottom:14px;z-index:3;padding:8px 12px;border-radius:999px;color:#fff;background:rgba(0,0,0,.72);text-decoration:none;font-size:12px;font-weight:700}</style>');
|
||||
const mediaMarkup = (media, fallback, title, interactive = false) => {
|
||||
if (!media || typeof media !== "object") return fallback;
|
||||
if (media.type === "image") {
|
||||
const source = safeRemoteUrl(media.mediaUrl, "image");
|
||||
return source ? '<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");
|
||||
const poster = safeRemoteUrl(media.posterUrl, "image");
|
||||
if (!interactive) {
|
||||
if (poster) return '<img src="' + escapeHTML(poster) + '" alt="' + escapeHTML(media.alt || title || "视频封面") + '" loading="lazy" referrerpolicy="no-referrer"/>';
|
||||
return source ? '<video src="' + escapeHTML(source) + '" aria-label="' + escapeHTML(media.alt || title || "视频") + '" muted playsinline preload="metadata"></video>' : fallback;
|
||||
}
|
||||
return source ? '<video src="' + escapeHTML(source) + '"' + (poster ? ' poster="' + escapeHTML(poster) + '"' : "") + ' controls playsinline preload="metadata" aria-label="' + escapeHTML(media.alt || title || "视频") + '"></video>' : fallback;
|
||||
}
|
||||
if (media.type === "webpage") {
|
||||
const pageUrl = safeRemoteUrl(media.pageUrl);
|
||||
if (!pageUrl) return fallback;
|
||||
const preview = safeRemoteUrl(media.mediaUrl, "image");
|
||||
if (!interactive) return preview ? '<img src="' + escapeHTML(preview) + '" alt="' + escapeHTML(media.alt || media.title || "网页预览图") + '" loading="lazy" referrerpolicy="no-referrer"/>' : fallback;
|
||||
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 || "网页预览图") + '" referrerpolicy="no-referrer"/>' : fallback);
|
||||
return body + '<a class="external-page-link" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer">打开网页</a>';
|
||||
}
|
||||
return fallback;
|
||||
};
|
||||
|
||||
const toast = qs("#toast");
|
||||
let toastTimer = 0;
|
||||
const showToast = (message) => {
|
||||
toast.textContent = message;
|
||||
toast.classList.add("show");
|
||||
window.clearTimeout(toastTimer);
|
||||
toastTimer = window.setTimeout(() => toast.classList.remove("show"), 2800);
|
||||
};
|
||||
const saveData = () => writeStorage(storageKey, JSON.stringify(pageData));
|
||||
let activeCategory = "";
|
||||
let activeVideoId = null;
|
||||
|
||||
const renderSite = () => {
|
||||
const site = pageData.site;
|
||||
const user = site.currentUser || {};
|
||||
document.title = site.pageTitle || site.brand || "YouTube";
|
||||
qs('meta[name="description"]').content = site.description || "";
|
||||
qs("#brandText").textContent = site.brand || "YouTube";
|
||||
qs("#brandLink").setAttribute("aria-label", (site.brand || "YouTube") + " 首页");
|
||||
qs("#searchInput").placeholder = site.searchPlaceholder || "搜索";
|
||||
qs("#createButton span").textContent = site.createLabel || "创建";
|
||||
qs("#headerUser").innerHTML = avatar(user, "header-avatar");
|
||||
const badge = qs("#notificationBadge");
|
||||
badge.textContent = String(Math.max(0, Number(user.notifications) || 0));
|
||||
badge.hidden = !(Number(user.notifications) > 0);
|
||||
};
|
||||
|
||||
const navMarkup = (items, activeFirst) => (Array.isArray(items) ? items : []).map((item, index) => '<a class="nav-link' + (activeFirst && index === 0 ? " active" : "") + '" href="' + safeHref(item.href) + '">' + icon(safeIcon(item.icon)) + "<span>" + escapeHTML(item.label) + "</span></a>").join("");
|
||||
const renderNavigation = () => {
|
||||
const navigation = pageData.navigation;
|
||||
qs("#primaryNav").innerHTML = navMarkup(navigation.primary, true);
|
||||
qs("#libraryNav").innerHTML = navMarkup(navigation.library, false);
|
||||
qs("#sideFooter").innerHTML = escapeHTML(navigation.footer || "").replace(/\n/g, "<br />");
|
||||
const mobile = Array.isArray(navigation.mobile) ? navigation.mobile : [];
|
||||
qs("#mobileNav").innerHTML = mobile.map((item, index) => '<button class="' + (index === 0 ? "active" : "") + '" aria-label="' + escapeHTML(item.label) + '">' + icon(safeIcon(item.icon)) + "<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");
|
||||
}));
|
||||
};
|
||||
|
||||
const renderSubscriptions = () => {
|
||||
const data = pageData.subscriptions;
|
||||
qs("#subscriptionTitle").textContent = data.title || "订阅";
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#subscriptionList").innerHTML = items.map((person) => '<div class="subscription-row">' + avatar(person, "avatar-sm") + '<span class="subscription-copy"><strong>' + escapeHTML(person.name) + "</strong><span>" + escapeHTML(person.handle) + "</span></span></div>").join("");
|
||||
};
|
||||
|
||||
const applyFilters = () => {
|
||||
const query = qs("#searchInput").value.trim().toLocaleLowerCase();
|
||||
let visible = 0;
|
||||
qsa(".video-card").forEach((card) => {
|
||||
const categoryMatch = !activeCategory || activeCategory === "全部" || card.dataset.category === activeCategory;
|
||||
const queryMatch = !query || card.dataset.search.toLocaleLowerCase().includes(query) || card.textContent.toLocaleLowerCase().includes(query);
|
||||
card.hidden = !(categoryMatch && queryMatch);
|
||||
if (!card.hidden) visible += 1;
|
||||
});
|
||||
qs("#emptyState").style.display = visible ? "none" : "block";
|
||||
};
|
||||
|
||||
const renderCategories = () => {
|
||||
const items = Array.isArray(pageData.categories.items) ? pageData.categories.items : [];
|
||||
if (!items.includes(activeCategory)) activeCategory = items[0] || "";
|
||||
qs("#categoryBar").innerHTML = items.map((label) => '<button class="category-chip' + (label === activeCategory ? " active" : "") + '">' + escapeHTML(label) + "</button>").join("");
|
||||
qsa(".category-chip").forEach((button) => button.addEventListener("click", () => {
|
||||
activeCategory = button.textContent;
|
||||
qsa(".category-chip").forEach((item) => item.classList.toggle("active", item === button));
|
||||
applyFilters();
|
||||
}));
|
||||
};
|
||||
|
||||
const videoMarkup = (video) => '<article class="video-card" data-video-id="' + escapeHTML(video.id) + '" data-category="' + escapeHTML(video.category) + '" data-search="' + escapeHTML([video.title, video.channel, video.category, video.description].join(" ")) + '"><button class="thumbnail-button" aria-label="播放 ' + escapeHTML(video.title) + '"><span class="thumbnail-visual">' + mediaMarkup(video.media, visualSvg(video.visual, false), video.title) + '</span></button><div class="video-info">' + avatar(video, "", "channelInitial", "channelColors") + '<div class="video-copy"><h3>' + escapeHTML(video.title) + "</h3><p>" + escapeHTML(video.channel) + (video.verified ? '<span class="verified">✓</span>' : "") + "</p><p>" + escapeHTML(video.views) + " · " + escapeHTML(video.time) + '</p></div><button class="more-button" aria-label="更多操作">' + icon("i-more") + "</button></div></article>";
|
||||
|
||||
const renderVideos = () => {
|
||||
const data = pageData.videos;
|
||||
qs("#videoSectionTitle").textContent = data.sectionTitle || "推荐视频";
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#videoGrid").innerHTML = items.map(videoMarkup).join("");
|
||||
qsa(".video-card").forEach((card) => {
|
||||
qs(".thumbnail-button", card).addEventListener("click", () => openWatch(card.dataset.videoId));
|
||||
qs(".more-button", card).addEventListener("click", () => showToast("视频操作菜单已打开"));
|
||||
});
|
||||
applyFilters();
|
||||
};
|
||||
|
||||
const renderShorts = () => {
|
||||
const data = pageData.shorts;
|
||||
qs("#shortsSectionTitle").textContent = data.sectionTitle || "Shorts";
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#shortsGrid").innerHTML = items.map((item) => '<article class="short-card"><button class="short-thumb" data-short-id="' + escapeHTML(item.id) + '">' + mediaMarkup(item.media, visualSvg(item.visual, true), item.title) + '</button><h3>' + escapeHTML(item.title) + "</h3><p>" + escapeHTML(item.views) + "</p></article>").join("");
|
||||
qsa(".short-thumb").forEach((button) => button.addEventListener("click", () => openShort(button.dataset.shortId)));
|
||||
qs("#shorts").hidden = !items.length;
|
||||
};
|
||||
|
||||
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-like") + "<span>" + formatCount(comment.likes) + "</span></button></article>";
|
||||
const renderComments = () => {
|
||||
const comments = pageData.comments;
|
||||
qs("#commentInput").placeholder = comments.inputPlaceholder || "添加评论…";
|
||||
qs("#commentsList").innerHTML = (Array.isArray(comments.items) ? comments.items : []).map(commentMarkup).join("");
|
||||
qsa(".comment-like").forEach((button) => button.addEventListener("click", () => button.classList.toggle("active")));
|
||||
};
|
||||
|
||||
const watchModal = qs("#watchModal");
|
||||
const setWatchContent = (video) => {
|
||||
activeVideoId = video.id;
|
||||
qs("#watchVisual").innerHTML = mediaMarkup(video.media, visualSvg(video.visual, false), video.title, true);
|
||||
qs("#watchTitle").textContent = video.title;
|
||||
qs("#watchChannelAvatar").innerHTML = avatar(video, "avatar-lg", "channelInitial", "channelColors");
|
||||
qs("#watchChannel").textContent = video.channel;
|
||||
qs("#watchViews").textContent = video.views + " · " + video.time;
|
||||
qs("#watchMeta").textContent = video.views + " · " + video.time;
|
||||
qs("#watchDescription").textContent = video.description || "";
|
||||
qs("#watchLike span").textContent = formatCount((video.metrics || {}).likes);
|
||||
qs("#commentsTitle").textContent = formatCount((video.metrics || {}).comments) + " " + (pageData.comments.titleSuffix || "条评论");
|
||||
qs("#watchPlayer").classList.remove("playing");
|
||||
qs("#subscribeButton").classList.remove("following");
|
||||
qs("#subscribeButton").textContent = "订阅";
|
||||
qs("#watchLike").classList.remove("active");
|
||||
qs("#watchSave").classList.remove("active");
|
||||
renderComments();
|
||||
};
|
||||
const openWatch = (id) => {
|
||||
const video = pageData.videos.items.find((item) => item.id === id);
|
||||
if (!video) return;
|
||||
setWatchContent(video);
|
||||
watchModal.classList.add("open");
|
||||
watchModal.setAttribute("aria-hidden", "false");
|
||||
document.body.classList.add("modal-open");
|
||||
};
|
||||
const openShort = (id) => {
|
||||
const item = pageData.shorts.items.find((short) => short.id === id);
|
||||
if (!item) return;
|
||||
setWatchContent({
|
||||
id: item.id,
|
||||
title: item.title,
|
||||
channel: "YouTube Shorts",
|
||||
channelInitial: "S",
|
||||
channelColors: ["#ff0033", "#7c3aed"],
|
||||
views: item.views,
|
||||
time: "Shorts",
|
||||
visual: item.visual,
|
||||
description: item.title,
|
||||
metrics: { likes: 0, comments: pageData.comments.items.length }
|
||||
});
|
||||
watchModal.classList.add("open");
|
||||
watchModal.setAttribute("aria-hidden", "false");
|
||||
document.body.classList.add("modal-open");
|
||||
};
|
||||
const closeWatch = () => {
|
||||
watchModal.classList.remove("open");
|
||||
watchModal.setAttribute("aria-hidden", "true");
|
||||
document.body.classList.remove("modal-open");
|
||||
};
|
||||
|
||||
const renderAll = () => {
|
||||
closeWatch();
|
||||
renderSite();
|
||||
renderNavigation();
|
||||
renderSubscriptions();
|
||||
renderCategories();
|
||||
renderVideos();
|
||||
renderShorts();
|
||||
renderComments();
|
||||
};
|
||||
|
||||
qs("#closeWatch").addEventListener("click", closeWatch);
|
||||
watchModal.addEventListener("click", (event) => {
|
||||
if (event.target === watchModal) closeWatch();
|
||||
});
|
||||
qs("#watchPlay").addEventListener("click", () => {
|
||||
const playing = qs("#watchPlayer").classList.toggle("playing");
|
||||
showToast(playing ? "正在播放" : "已暂停");
|
||||
});
|
||||
qs("#subscribeButton").addEventListener("click", (event) => {
|
||||
const following = event.currentTarget.classList.toggle("following");
|
||||
event.currentTarget.textContent = following ? "已订阅" : "订阅";
|
||||
});
|
||||
qs("#watchLike").addEventListener("click", (event) => event.currentTarget.classList.toggle("active"));
|
||||
qs("#watchSave").addEventListener("click", (event) => {
|
||||
const active = event.currentTarget.classList.toggle("active");
|
||||
showToast(active ? "已保存到稍后观看" : "已取消保存");
|
||||
});
|
||||
qs("#commentForm").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const input = qs("#commentInput");
|
||||
const value = input.value.trim();
|
||||
if (!value) return;
|
||||
const user = pageData.site.currentUser;
|
||||
pageData.comments.items.unshift({
|
||||
id: "comment-" + Date.now(),
|
||||
name: user.name,
|
||||
initial: user.initial,
|
||||
colors: clone(user.colors || []),
|
||||
text: value,
|
||||
time: "刚刚",
|
||||
likes: 0
|
||||
});
|
||||
saveData();
|
||||
renderComments();
|
||||
input.value = "";
|
||||
showToast("评论已发布");
|
||||
});
|
||||
|
||||
qs("#menuToggle").addEventListener("click", () => document.body.classList.toggle("sidebar-collapsed"));
|
||||
qs("#createButton").addEventListener("click", () => showToast("创建入口已打开"));
|
||||
qs("#searchForm").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
applyFilters();
|
||||
});
|
||||
qs("#searchInput").addEventListener("input", applyFilters);
|
||||
|
||||
const themeButton = qs("#themeToggle");
|
||||
const storedTheme = readStorage(themeKey);
|
||||
if (storedTheme === "dark" || (!storedTheme && typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches)) {
|
||||
document.documentElement.dataset.theme = "dark";
|
||||
}
|
||||
const syncTheme = () => {
|
||||
const dark = document.documentElement.dataset.theme === "dark";
|
||||
themeButton.innerHTML = icon(dark ? "i-sun" : "i-moon");
|
||||
qs('meta[name="theme-color"]').content = dark ? "#0f0f0f" : "#ffffff";
|
||||
};
|
||||
themeButton.addEventListener("click", () => {
|
||||
const next = document.documentElement.dataset.theme === "dark" ? "light" : "dark";
|
||||
document.documentElement.dataset.theme = next;
|
||||
writeStorage(themeKey, next);
|
||||
syncTheme();
|
||||
});
|
||||
|
||||
const settingsModal = qs("#settingsModal");
|
||||
const moduleTabs = qs("#moduleTabs");
|
||||
const jsonEditor = qs("#jsonEditor");
|
||||
const jsonStatus = qs("#jsonStatus");
|
||||
let activeModule = "site";
|
||||
let editorDrafts = clone(pageData);
|
||||
let settingsOpener = null;
|
||||
|
||||
const setEditorStatus = (valid, message) => {
|
||||
jsonStatus.textContent = message;
|
||||
jsonStatus.classList.toggle("valid", valid);
|
||||
jsonStatus.classList.toggle("invalid", !valid);
|
||||
};
|
||||
const readEditor = () => {
|
||||
try {
|
||||
const parsed = JSON.parse(jsonEditor.value);
|
||||
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("模块必须是 JSON 对象");
|
||||
validateRemoteMediaTree(parsed);
|
||||
setEditorStatus(true, "JSON 有效");
|
||||
return parsed;
|
||||
} catch (error) {
|
||||
setEditorStatus(false, "JSON 无效:" + error.message);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const saveActiveDraft = () => {
|
||||
const parsed = readEditor();
|
||||
if (!parsed) return false;
|
||||
editorDrafts[activeModule] = parsed;
|
||||
return true;
|
||||
};
|
||||
const loadEditor = () => {
|
||||
qs("#editorModuleTitle").textContent = MODULE_META[activeModule][0];
|
||||
jsonEditor.value = JSON.stringify(editorDrafts[activeModule], null, 2);
|
||||
setEditorStatus(true, "JSON 有效");
|
||||
};
|
||||
const renderModuleTabs = () => {
|
||||
qsa(".module-tab", moduleTabs).forEach((button) => button.remove());
|
||||
MODULES.forEach((name) => {
|
||||
const button = document.createElement("button");
|
||||
button.className = "module-tab" + (name === activeModule ? " active" : "");
|
||||
button.type = "button";
|
||||
button.dataset.module = name;
|
||||
button.innerHTML = "<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 = "youtube-page-data.json";
|
||||
link.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(link.href), 1000);
|
||||
});
|
||||
|
||||
document.addEventListener("click", (event) => {
|
||||
const link = event.target.closest('a[href^="#"]');
|
||||
if (!link) return;
|
||||
const href = link.getAttribute("href");
|
||||
const target = href && href.length > 1 ? document.getElementById(href.slice(1)) : null;
|
||||
if (!target) {
|
||||
event.preventDefault();
|
||||
showToast("此页面正在准备中");
|
||||
}
|
||||
});
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Escape") return;
|
||||
if (settingsModal.classList.contains("open")) closeSettings();
|
||||
else if (watchModal.classList.contains("open")) closeWatch();
|
||||
});
|
||||
|
||||
renderAll();
|
||||
syncTheme();
|
||||
function installJsonMediaUpload(){
|
||||
const editor=document.getElementById("jsonEditor"),apply=document.getElementById("applyJson");if(!editor||!apply||document.getElementById("uploadJsonMedia"))return;
|
||||
const actions=apply.parentElement,button=document.createElement("button"),input=document.createElement("input"),reference=actions.querySelector("#downloadJson,#copyJson,#validateJson,#resetJson");
|
||||
button.type="button";button.id="uploadJsonMedia";button.className=reference?reference.className:apply.className;button.textContent="上传图片/视频";button.title="先把光标放进要替换的内容对象,再选择图片或视频";input.type="file";input.accept="image/*,video/*";input.hidden=true;actions.insertBefore(button,apply);actions.appendChild(input);
|
||||
const report=(message)=>{const status=document.getElementById("settingsStatus")||document.getElementById("jsonError")||document.getElementById("jsonStatus");if(status)status.textContent=message};
|
||||
const findTarget=(text,cursor)=>{const stack=[],matches=[];let quoted=false,escaped=false;for(let index=0;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 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;
|
||||
attachButton(host, target);
|
||||
});
|
||||
};
|
||||
const decorate = () => {
|
||||
decorateBuiltInVisuals();
|
||||
document.querySelectorAll("img[src],video[src]").forEach((media) => {
|
||||
if (media.dataset.dfInlineMediaReady === "true") return;
|
||||
const target = chooseTarget(media);
|
||||
if (!target) return;
|
||||
const host = media.closest(visualHostSelector) || media.parentElement;
|
||||
if (!host) return;
|
||||
media.dataset.dfInlineMediaReady = "true";
|
||||
attachButton(host, target);
|
||||
});
|
||||
};
|
||||
input.addEventListener("change", () => {
|
||||
const file = input.files && input.files[0];
|
||||
if (!file || !active) return;
|
||||
const uploadedType = file.type.startsWith("image/") ? "image" : file.type.startsWith("video/") ? "video" : "";
|
||||
if (!uploadedType) {
|
||||
notify("请选择图片或视频文件。");
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.onerror = () => notify("文件读取失败,请重新选择。");
|
||||
reader.onload = () => {
|
||||
const next = { ...(active.previous || {}) };
|
||||
const result = String(reader.result);
|
||||
next.type = uploadedType;
|
||||
next.mediaUrl = result;
|
||||
delete next.posterUrl;
|
||||
if (!next.alt) next.alt = uploadedType === "video" ? "用户上传的视频" : "用户上传的图片";
|
||||
active.owner.media = next;
|
||||
const stored = persist();
|
||||
renderAll();
|
||||
notify(stored === false ? "媒体已替换;浏览器未能缓存,请下载 JSON 留存。" : "媒体已替换并写入页面 JSON。");
|
||||
active = null;
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
let queued = false;
|
||||
const queueDecorate = () => {
|
||||
if (queued) return;
|
||||
queued = true;
|
||||
requestAnimationFrame(() => { queued = false; decorate(); });
|
||||
};
|
||||
new MutationObserver(queueDecorate).observe(document.body, { childList: true, subtree: true });
|
||||
decorate();
|
||||
}
|
||||
installInlineMediaReplace();
|
||||
})();
|
||||
+329
@@ -0,0 +1,329 @@
|
||||
<!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="#ffffff" />
|
||||
<meta name="description" content="YouTube 风格的可编辑中文视频门户。" />
|
||||
<title>YouTube · 精彩视频</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--bg: #fff;
|
||||
--surface: #fff;
|
||||
--surface-2: #f2f2f2;
|
||||
--surface-3: #e5e5e5;
|
||||
--text: #0f0f0f;
|
||||
--muted: #606060;
|
||||
--line: #e5e5e5;
|
||||
--red: #ff0033;
|
||||
--focus: 0 0 0 3px rgba(6,95,212,.25);
|
||||
--header-h: 64px;
|
||||
--side-w: 240px;
|
||||
}
|
||||
[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--bg: #0f0f0f;
|
||||
--surface: #0f0f0f;
|
||||
--surface-2: #272727;
|
||||
--surface-3: #3f3f3f;
|
||||
--text: #f1f1f1;
|
||||
--muted: #aaa;
|
||||
--line: #303030;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html { scroll-behavior: smooth; }
|
||||
body { margin: 0; min-width: 320px; background: var(--bg); color: var(--text); font-family: Roboto, Arial, "PingFang SC", "Microsoft YaHei", sans-serif; font-size: 15px; line-height: 1.45; }
|
||||
body.modal-open { overflow: hidden; }
|
||||
button, input, textarea { 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, textarea: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: 12px; top: calc(var(--df-generated-header-height, 0px) + 8px); padding: 10px 16px; border-radius: 9px; color: #fff; background: #065fd4; transform: translateY(-160%); text-decoration: none; }
|
||||
.skip-link:focus { transform: translateY(0); }
|
||||
|
||||
.app-header { position: fixed; z-index: 90; inset: var(--df-generated-header-height, 0px) 0 auto; height: var(--header-h); padding: 0 68px 0 16px; display: grid; grid-template-columns: minmax(190px,1fr) minmax(320px,640px) minmax(230px,1fr); align-items: center; gap: 24px; background: color-mix(in srgb,var(--surface) 94%,transparent); border-bottom: 1px solid var(--line); backdrop-filter: blur(14px); }
|
||||
.header-start, .header-actions { display: flex; align-items: center; gap: 10px; }
|
||||
.header-actions { justify-content: flex-end; }
|
||||
.icon-button { width: 44px; height: 44px; flex: 0 0 auto; border: 0; border-radius: 50%; display: grid; place-items: center; color: var(--text); background: transparent; }
|
||||
.icon-button:hover { background: var(--surface-2); }
|
||||
.icon-button svg { width: 22px; height: 22px; }
|
||||
.brand { display: flex; align-items: center; gap: 7px; color: var(--text); text-decoration: none; font-size: 21px; font-weight: 850; letter-spacing: -.8px; }
|
||||
.brand-logo { position: relative; width: 32px; height: 22px; border-radius: 7px; background: var(--red); box-shadow: inset 0 0 0 1px rgba(0,0,0,.06); }
|
||||
.brand-logo::after { content: ""; position: absolute; left: 12px; top: 6px; border-left: 10px solid #fff; border-top: 5px solid transparent; border-bottom: 5px solid transparent; }
|
||||
.search-form { height: 42px; display: grid; grid-template-columns: 1fr 64px; }
|
||||
.search-input { min-width: 0; height: 42px; padding: 0 17px; border: 1px solid var(--line); border-radius: 22px 0 0 22px; color: var(--text); background: var(--surface); outline: 0; font-size: 16px; }
|
||||
.search-input:focus { border-color: #1c62b9; box-shadow: inset 1px 0 #1c62b9; }
|
||||
.search-button { height: 42px; border: 1px solid var(--line); border-left: 0; border-radius: 0 22px 22px 0; display: grid; place-items: center; background: var(--surface-2); }
|
||||
.search-button svg { width: 22px; height: 22px; }
|
||||
.create-button { min-height: 38px; padding: 0 14px; border: 0; border-radius: 20px; display: flex; align-items: center; gap: 7px; background: var(--surface-2); font-weight: 650; }
|
||||
.create-button:hover { background: var(--surface-3); }
|
||||
.create-button svg { width: 18px; height: 18px; }
|
||||
.header-avatar { width: 34px; height: 34px; }
|
||||
.notification-wrap { position: relative; }
|
||||
.notification-badge { position: absolute; right: 1px; top: 1px; min-width: 17px; height: 17px; padding: 0 4px; border: 2px solid var(--surface); border-radius: 10px; display: grid; place-items: center; color: #fff; background: #c00; font-size: 9px; font-weight: 800; }
|
||||
|
||||
.avatar { --a:#6249e7; --b:#d946ef; width: 38px; height: 38px; flex: 0 0 auto; border-radius: 50%; display: grid; place-items: center; color: #fff; background: linear-gradient(145deg,var(--a),var(--b)); font-size: 12px; font-weight: 850; box-shadow: inset 0 0 0 1px rgba(255,255,255,.2); }
|
||||
.avatar-sm { width: 32px; height: 32px; font-size: 11px; }
|
||||
.avatar-lg { width: 46px; height: 46px; font-size: 14px; }
|
||||
|
||||
.sidebar { position: fixed; z-index: 70; left: 0; top: calc(var(--df-generated-header-height, 0px) + var(--header-h)); bottom: 0; width: var(--side-w); padding: 12px; overflow-y: auto; background: var(--surface); border-right: 1px solid var(--line); scrollbar-width: thin; }
|
||||
.nav-group { display: grid; gap: 3px; padding: 0 0 12px; border-bottom: 1px solid var(--line); }
|
||||
.nav-group + .nav-group { padding-top: 12px; }
|
||||
.nav-link { min-height: 42px; padding: 0 12px; border-radius: 10px; display: flex; align-items: center; gap: 20px; color: var(--text); text-decoration: none; }
|
||||
.nav-link:hover, .nav-link.active { background: var(--surface-2); }
|
||||
.nav-link.active { font-weight: 700; }
|
||||
.nav-link svg { width: 22px; height: 22px; flex: 0 0 auto; }
|
||||
.subscription-title { padding: 14px 12px 7px; font-size: 16px; font-weight: 700; }
|
||||
.subscription-row { min-height: 42px; padding: 4px 12px; border-radius: 10px; display: flex; align-items: center; gap: 16px; }
|
||||
.subscription-row:hover { background: var(--surface-2); }
|
||||
.subscription-copy { min-width: 0; }
|
||||
.subscription-copy strong, .subscription-copy span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.subscription-copy strong { font-size: 13px; }
|
||||
.subscription-copy span { color: var(--muted); font-size: 11px; }
|
||||
.side-footer { padding: 18px 12px 30px; color: var(--muted); font-size: 11px; line-height: 1.75; }
|
||||
|
||||
.content { min-height: 100dvh; padding: var(--header-h) 24px 90px calc(var(--side-w) + 24px); transition: padding-left .2s; }
|
||||
.category-bar { position: sticky; z-index: 60; top: calc(var(--df-generated-header-height, 0px) + var(--header-h)); margin: 0 -24px; padding: 12px 24px; display: flex; gap: 10px; overflow-x: auto; background: color-mix(in srgb,var(--surface) 94%,transparent); backdrop-filter: blur(12px); scrollbar-width: none; }
|
||||
.category-bar::-webkit-scrollbar { display: none; }
|
||||
.category-chip { min-width: max-content; height: 36px; padding: 0 14px; border: 0; border-radius: 9px; color: var(--text); background: var(--surface-2); font-size: 14px; font-weight: 600; }
|
||||
.category-chip:hover { background: var(--surface-3); }
|
||||
.category-chip.active { color: var(--bg); background: var(--text); }
|
||||
.section-head { margin: 22px 0 14px; display: flex; align-items: center; justify-content: space-between; }
|
||||
.section-head h1, .section-head h2 { margin: 0; font-size: 22px; }
|
||||
.video-grid { display: grid; grid-template-columns: repeat(auto-fill,minmax(285px,1fr)); gap: 28px 18px; }
|
||||
.video-card { min-width: 0; }
|
||||
.thumbnail-button { position: relative; width: 100%; aspect-ratio: 16/9; padding: 0; overflow: hidden; border: 0; border-radius: 12px; display: block; background: var(--surface-2); }
|
||||
.thumbnail-button:hover .thumbnail-visual { transform: scale(1.025); }
|
||||
.thumbnail-visual { width: 100%; height: 100%; transition: transform .25s; }
|
||||
.thumbnail-visual svg { width: 100%; height: 100%; }
|
||||
.video-info { padding-top: 11px; display: grid; grid-template-columns: 40px 1fr 34px; gap: 10px; }
|
||||
.video-copy { min-width: 0; }
|
||||
.video-copy h3 { margin: 0 0 6px; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; font-size: 16px; line-height: 1.35; }
|
||||
.video-copy p { margin: 0; color: var(--muted); font-size: 13px; }
|
||||
.verified { display: inline-grid; place-items: center; width: 14px; height: 14px; margin-left: 3px; border-radius: 50%; color: var(--surface); background: var(--muted); font-size: 9px; font-weight: 900; vertical-align: 1px; }
|
||||
.more-button { width: 34px; height: 34px; border: 0; border-radius: 50%; display: grid; place-items: center; background: transparent; }
|
||||
.more-button:hover { background: var(--surface-2); }
|
||||
.more-button svg { width: 19px; height: 19px; }
|
||||
|
||||
.shorts-section { margin-top: 36px; padding-top: 22px; border-top: 1px solid var(--line); }
|
||||
.shorts-title { display: flex; align-items: center; gap: 9px; }
|
||||
.shorts-title svg { width: 24px; height: 24px; color: var(--red); }
|
||||
.shorts-grid { display: grid; grid-template-columns: repeat(5,minmax(165px,1fr)); gap: 16px; overflow-x: auto; padding-bottom: 8px; scrollbar-width: thin; }
|
||||
.short-card { min-width: 165px; }
|
||||
.short-thumb { position: relative; width: 100%; aspect-ratio: 9/16; padding: 0; overflow: hidden; border: 0; border-radius: 12px; display: block; background: var(--surface-2); }
|
||||
.short-thumb svg { width: 100%; height: 100%; }
|
||||
.short-card h3 { margin: 10px 0 3px; font-size: 15px; line-height: 1.35; }
|
||||
.short-card p { margin: 0; color: var(--muted); font-size: 12px; }
|
||||
.empty-state { display: none; padding: 64px 20px; text-align: center; color: var(--muted); }
|
||||
|
||||
.mobile-nav { display: none; }
|
||||
.watch-backdrop { position: fixed; z-index: 180; inset: 0; padding: 28px; display: grid; place-items: center; background: rgba(0,0,0,.74); opacity: 0; visibility: hidden; transition: opacity .2s,visibility .2s; }
|
||||
.watch-backdrop.open { opacity: 1; visibility: visible; }
|
||||
.watch-dialog { position: relative; width: min(1180px,100%); height: min(820px,calc(100dvh - 56px)); padding: 18px; overflow-y: auto; border-radius: 18px; color: var(--text); background: var(--surface); box-shadow: 0 30px 100px rgba(0,0,0,.45); }
|
||||
.watch-close { position: sticky; z-index: 4; top: 0; float: right; margin: 0 0 -44px; background: color-mix(in srgb,var(--surface) 88%,transparent); backdrop-filter: blur(8px); }
|
||||
.watch-layout { display: grid; grid-template-columns: minmax(0,1.65fr) minmax(310px,.85fr); gap: 22px; clear: both; }
|
||||
.watch-player { position: relative; aspect-ratio: 16/9; overflow: hidden; border-radius: 13px; color: #fff; background: #000; }
|
||||
.watch-player svg { width: 100%; height: 100%; }
|
||||
.watch-visual { width: 100%; height: 100%; display: grid; place-items: center; background: #000; }
|
||||
.watch-play { position: absolute; left: 50%; top: 50%; width: 72px; height: 52px; border: 0; border-radius: 13px; display: grid; place-items: center; color: #fff; background: rgba(255,0,51,.9); transform: translate(-50%,-50%); }
|
||||
.watch-play svg { width: 27px; height: 27px; fill: currentColor; }
|
||||
.watch-player.playing .watch-play { opacity: .3; }
|
||||
.watch-title { margin: 14px 0 10px; font-size: 21px; }
|
||||
.watch-meta-row { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
|
||||
.watch-channel { display: flex; align-items: center; gap: 10px; margin-right: auto; }
|
||||
.watch-channel-copy strong, .watch-channel-copy span { display: block; }
|
||||
.watch-channel-copy span { color: var(--muted); font-size: 12px; }
|
||||
.subscribe-button { min-height: 38px; padding: 0 16px; border: 0; border-radius: 20px; color: var(--bg); background: var(--text); font-weight: 700; }
|
||||
.subscribe-button.following { color: var(--text); background: var(--surface-2); }
|
||||
.watch-action { min-height: 38px; padding: 0 14px; border: 0; border-radius: 20px; display: flex; align-items: center; gap: 7px; background: var(--surface-2); font-weight: 650; }
|
||||
.watch-action svg { width: 18px; height: 18px; }
|
||||
.watch-action.active { color: #065fd4; }
|
||||
.watch-description { margin-top: 14px; padding: 13px; border-radius: 12px; background: var(--surface-2); font-size: 14px; }
|
||||
.watch-description strong { display: block; margin-bottom: 5px; }
|
||||
.comments-panel { min-height: 0; display: flex; flex-direction: column; border: 1px solid var(--line); border-radius: 13px; overflow: hidden; }
|
||||
.comments-head { padding: 16px; border-bottom: 1px solid var(--line); font-size: 17px; font-weight: 750; }
|
||||
.comments-list { flex: 1; overflow-y: auto; padding: 8px 14px; }
|
||||
.comment { display: grid; grid-template-columns: 34px 1fr auto; gap: 9px; padding: 10px 0; }
|
||||
.comment-copy p { margin: 3px 0 4px; font-size: 13px; }
|
||||
.comment-copy time { color: var(--muted); font-size: 11px; }
|
||||
.comment-like { width: 38px; height: 38px; border: 0; display: grid; justify-items: center; align-content: center; gap: 1px; color: var(--muted); background: transparent; font-size: 9px; }
|
||||
.comment-like svg { width: 15px; height: 15px; }
|
||||
.comment-like.active { color: #065fd4; }
|
||||
.comment-form { padding: 12px; display: flex; gap: 8px; border-top: 1px solid var(--line); }
|
||||
.comment-form input { flex: 1; min-width: 0; height: 42px; padding: 0 14px; border: 1px solid var(--line); border-radius: 22px; color: var(--text); background: var(--surface); }
|
||||
.comment-send { width: 42px; height: 42px; border: 0; border-radius: 50%; display: grid; place-items: center; color: #fff; background: #065fd4; }
|
||||
.comment-send svg { width: 18px; height: 18px; }
|
||||
.toast { position: fixed; z-index: 500; left: 50%; bottom: 26px; padding: 10px 17px; border-radius: 8px; color: #fff; background: #212121; 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); }
|
||||
|
||||
body.sidebar-collapsed { --side-w: 78px; }
|
||||
body.sidebar-collapsed .nav-link { padding: 0; justify-content: center; }
|
||||
body.sidebar-collapsed .nav-link span, body.sidebar-collapsed .subscription-title, body.sidebar-collapsed #subscriptionList, body.sidebar-collapsed .side-footer { display: none; }
|
||||
|
||||
.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 (max-width: 1120px) {
|
||||
:root { --side-w: 78px; }
|
||||
.nav-link { padding: 0; justify-content: center; }
|
||||
.nav-link span, .subscription-title, #subscriptionList, .side-footer { display: none; }
|
||||
.video-grid { grid-template-columns: repeat(auto-fill,minmax(250px,1fr)); }
|
||||
.shorts-grid { grid-template-columns: repeat(5,180px); }
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
:root { --header-h: 58px; --side-w: 0px; }
|
||||
.app-header { height: var(--header-h); padding: 0 58px 0 10px; grid-template-columns: auto 1fr auto; gap: 7px; }
|
||||
.header-start .icon-button, .brand span { display: none; }
|
||||
.brand-logo { width: 30px; }
|
||||
.search-form { height: 38px; grid-template-columns: 1fr 46px; }
|
||||
.search-input, .search-button { height: 38px; }
|
||||
.create-button span, #themeToggle, .notification-wrap { display: none; }
|
||||
.create-button { width: 40px; padding: 0; justify-content: center; }
|
||||
.sidebar { display: none; }
|
||||
.content { padding: var(--header-h) 12px 76px; }
|
||||
.category-bar { top: calc(var(--df-generated-header-height, 0px) + var(--header-h)); margin: 0 -12px; padding: 9px 12px; }
|
||||
.section-head { margin-top: 16px; }
|
||||
.video-grid { grid-template-columns: 1fr; gap: 25px; }
|
||||
.thumbnail-button { border-radius: 10px; }
|
||||
.shorts-grid { grid-template-columns: repeat(5,165px); }
|
||||
.mobile-nav { position: fixed; z-index: 100; inset: auto 0 0; height: 62px; display: grid; grid-template-columns: repeat(4,1fr); border-top: 1px solid var(--line); background: color-mix(in srgb,var(--surface) 96%,transparent); backdrop-filter: blur(12px); }
|
||||
.mobile-nav button { border: 0; display: grid; place-items: center; align-content: center; gap: 2px; background: transparent; font-size: 10px; }
|
||||
.mobile-nav svg { width: 21px; height: 21px; }
|
||||
.watch-backdrop { padding: 0; }
|
||||
.watch-dialog { width: 100%; height: 100dvh; border-radius: 0; padding: 12px; }
|
||||
.watch-layout { grid-template-columns: 1fr; }
|
||||
.comments-panel { min-height: 420px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,*::before,*::after { scroll-behavior: auto !important; transition: none !important; animation: none !important; }
|
||||
}
|
||||
.skip-link { transform: translateY(calc(-100% - var(--df-generated-header-height, 0px) - 24px)); }
|
||||
.skip-link:focus { transform: translateY(0); }
|
||||
.watch-backdrop { z-index: 1200; }
|
||||
.settings-backdrop { z-index: 1300; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#home">跳到视频内容</a>
|
||||
<svg aria-hidden="true" width="0" height="0" style="position:absolute">
|
||||
<symbol id="i-menu" viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h16" 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-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-shorts" viewBox="0 0 24 24"><path d="m9 3 8 4-4 3 4 3-8 4-4-3 4-3-4-3Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><path d="m10 9 5 3-5 3Z" fill="currentColor"/></symbol>
|
||||
<symbol id="i-subscriptions" viewBox="0 0 24 24"><rect x="3" y="6" width="18" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><path d="M7 3h10M9 10l6 3-6 3Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-history" viewBox="0 0 24 24"><path d="M3 12a9 9 0 1 0 3-6.7L3 8m0 0V3m0 5h5M12 7v5l3 2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-playlist" viewBox="0 0 24 24"><path d="M4 6h11M4 11h11M4 16h7m6-4v8l5-4Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M12 7v5l3 2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
|
||||
<symbol id="i-like" viewBox="0 0 24 24"><path d="M7 10v11H3V10Zm0 9h9a3 3 0 0 0 3-2.5l1-6A3 3 0 0 0 17 7h-4l1-4-2-1-5 8Z" 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-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="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-moon" viewBox="0 0 24 24"><path d="M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4" fill="none" stroke="currentColor" stroke-width="2"/><path d="M12 2v2m0 16v2M4.9 4.9l1.5 1.5m11.2 11.2 1.5 1.5M2 12h2m16 0h2M4.9 19.1l1.5-1.5M17.6 6.4l1.5-1.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
|
||||
<symbol id="i-more" viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.7" fill="currentColor"/><circle cx="12" cy="12" r="1.7" fill="currentColor"/><circle cx="19" cy="12" r="1.7" fill="currentColor"/></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-play" viewBox="0 0 24 24"><path d="m8 5 11 7-11 7Z" fill="currentColor"/></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-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-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">
|
||||
<div class="header-start"><button class="icon-button" id="menuToggle" aria-label="收起侧栏"><svg><use href="#i-menu"/></svg></button><a class="brand" id="brandLink" href="#home"><span class="brand-logo"></span><span id="brandText">YouTube</span></a></div>
|
||||
<form class="search-form" id="searchForm"><label class="sr-only" for="searchInput">搜索视频</label><input class="search-input" id="searchInput" type="search" placeholder="搜索" /><button class="search-button" aria-label="搜索"><svg><use href="#i-search"/></svg></button></form>
|
||||
<div class="header-actions"><button class="create-button" id="createButton"><svg><use href="#i-plus"/></svg><span>创建</span></button><button class="icon-button" id="themeToggle" aria-label="切换主题"><svg><use href="#i-moon"/></svg></button><span class="notification-wrap"><button class="icon-button" aria-label="通知"><svg><use href="#i-bell"/></svg></button><span class="notification-badge" id="notificationBadge">3</span></span><span id="headerUser"></span></div>
|
||||
</header>
|
||||
|
||||
<aside class="sidebar" aria-label="主导航">
|
||||
<nav class="nav-group" id="primaryNav"></nav>
|
||||
<nav class="nav-group" id="libraryNav"></nav>
|
||||
<section><div class="subscription-title" id="subscriptionTitle">订阅</div><div id="subscriptionList"></div></section>
|
||||
<footer class="side-footer" id="sideFooter"></footer>
|
||||
</aside>
|
||||
|
||||
<main class="content" id="home">
|
||||
<div class="category-bar" id="categoryBar"></div>
|
||||
<section><header class="section-head"><h1 id="videoSectionTitle">推荐视频</h1></header><div class="video-grid" id="videoGrid"></div><div class="empty-state" id="emptyState">没有找到匹配的视频,换个关键词试试。</div></section>
|
||||
<section class="shorts-section" id="shorts"><header class="section-head"><h2 class="shorts-title"><svg><use href="#i-shorts"/></svg><span id="shortsSectionTitle">Shorts</span></h2></header><div class="shorts-grid" id="shortsGrid"></div></section>
|
||||
</main>
|
||||
|
||||
<nav class="mobile-nav" id="mobileNav" aria-label="移动端导航"></nav>
|
||||
|
||||
<div class="watch-backdrop" id="watchModal" aria-hidden="true">
|
||||
<section class="watch-dialog" role="dialog" aria-modal="true" aria-labelledby="watchTitle">
|
||||
<button class="icon-button watch-close" id="closeWatch" aria-label="关闭观看窗口"><svg><use href="#i-close"/></svg></button>
|
||||
<div class="watch-layout">
|
||||
<div><div class="watch-player" id="watchPlayer"><div class="watch-visual" id="watchVisual"></div><button class="watch-play" id="watchPlay" aria-label="播放"><svg><use href="#i-play"/></svg></button></div><h2 class="watch-title" id="watchTitle"></h2><div class="watch-meta-row"><div class="watch-channel"><span id="watchChannelAvatar"></span><span class="watch-channel-copy"><strong id="watchChannel"></strong><span id="watchViews"></span></span></div><button class="subscribe-button" id="subscribeButton">订阅</button><button class="watch-action" id="watchLike"><svg><use href="#i-like"/></svg><span></span></button><button class="watch-action" id="watchSave"><svg><use href="#i-bookmark"/></svg><span>保存</span></button></div><div class="watch-description"><strong id="watchMeta"></strong><span id="watchDescription"></span></div></div>
|
||||
<aside class="comments-panel"><div class="comments-head" id="commentsTitle"></div><div class="comments-list" id="commentsList"></div><form class="comment-form" id="commentForm"><label class="sr-only" for="commentInput">添加评论</label><input id="commentInput" maxlength="180" /><button class="comment-send" aria-label="发送评论"><svg><use href="#i-send"/></svg></button></form></aside>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<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">YouTube 页面控制台</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="youtubePageData">__YOUTUBE_PAGE_DATA__</script>
|
||||
<script>__YOUTUBE_PAGE_RUNTIME__</script>
|
||||
</body>
|
||||
</html>
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
# YouTube 页面 JSON 契约
|
||||
|
||||
源文件必须是 JSON 对象,并包含以下七个顶层模块。字段可增加,但不能删除顶层模块。
|
||||
|
||||
## `site`
|
||||
|
||||
- `brand`、`pageTitle`、`description`、`searchPlaceholder`、`createLabel`:非空字符串。
|
||||
- `currentUser`:当前账号,包含 `name`、`handle`、`initial`、`colors` 和非负 `notifications`。
|
||||
|
||||
## `navigation`
|
||||
|
||||
- `primary`、`library`:桌面导航数组,每项 `{label, icon, href}`,各最多 12 项。
|
||||
- `mobile`:移动端导航数组,每项 `{label, icon}`,最多 6 项。
|
||||
- `footer`:侧栏页脚文字。
|
||||
- 可用图标:`i-home`、`i-shorts`、`i-subscriptions`、`i-history`、`i-playlist`、`i-clock`、`i-like`、`i-user`。
|
||||
|
||||
## `categories`
|
||||
|
||||
- `items`:1–20 个非空字符串;第一项默认激活。
|
||||
|
||||
## `videos`
|
||||
|
||||
- `sectionTitle`:视频区标题。
|
||||
- `items`:1–30 条,`id` 唯一。
|
||||
- 每项包含 `title`、`channel`、`channelInitial`、`channelColors`、`category`、`views`、`time`、`visual`、`verified`、`description`。
|
||||
- 不填写 `duration`;页面不展示 JSON 预设时长,旧 JSON 中的该字段会被兼容忽略。
|
||||
- `visual` 仅使用 `city`、`studio`、`food`、`mountain`、`code`、`science`、`music`、`travel`。
|
||||
- 可选 `media` 会替换缩略图和观看区:图片 `{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}`,均为非负数字。
|
||||
|
||||
## `shorts`
|
||||
|
||||
- `sectionTitle`:Shorts 区标题。
|
||||
- `items`:0–20 条,每项包含唯一 `id`、`title`、`views`、`visual`。
|
||||
- `visual` 使用与视频相同的预制视觉类型。
|
||||
- Shorts 同样可设置上述可选 `media`。
|
||||
|
||||
## `subscriptions`
|
||||
|
||||
- `title`:侧栏标题。
|
||||
- `items`:0–20 项,每项 `{name, handle, initial, colors}`。
|
||||
|
||||
## `comments`
|
||||
|
||||
- `titleSuffix`、`inputPlaceholder`:非空字符串。
|
||||
- `items`:0–40 项,每项包含唯一 `id`、`name`、`initial`、`colors`、`text`、`time`、非负 `likes`。
|
||||
|
||||
## 示例边界
|
||||
|
||||
- `assets/default-data.json` 只提供结构和演示内容,不是事实来源。
|
||||
- JSON 使用双引号,不允许注释、Markdown 围栏或尾逗号。
|
||||
+11
@@ -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_youtube_page as renderer
|
||||
from fast_patch_page import run
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(run(renderer, output_stem="youtube-page"))
|
||||
+512
@@ -0,0 +1,512 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate YouTube 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 / "youtube-template.html"
|
||||
RUNTIME_PATH = ASSETS_DIR / "youtube-runtime.js"
|
||||
DATA_MARKER = "__YOUTUBE_PAGE_DATA__"
|
||||
RUNTIME_MARKER = "__YOUTUBE_PAGE_RUNTIME__"
|
||||
TITLE_RE = re.compile(r"<title>[^<]*</title>", re.IGNORECASE)
|
||||
MODULES = (
|
||||
"site",
|
||||
"navigation",
|
||||
"categories",
|
||||
"videos",
|
||||
"shorts",
|
||||
"subscriptions",
|
||||
"comments",
|
||||
)
|
||||
VISUAL_TYPES = {
|
||||
"city",
|
||||
"studio",
|
||||
"food",
|
||||
"mountain",
|
||||
"code",
|
||||
"science",
|
||||
"music",
|
||||
"travel",
|
||||
}
|
||||
REMOTE_MEDIA_TYPES = {"image", "video", "webpage"}
|
||||
|
||||
|
||||
class DataValidationError(ValueError):
|
||||
"""Raised when the YouTube 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",
|
||||
"searchPlaceholder",
|
||||
"createLabel",
|
||||
):
|
||||
_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", 12), ("library", 12), ("mobile", 6)):
|
||||
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,
|
||||
)
|
||||
for field in ("label", "icon"):
|
||||
_non_empty_string(
|
||||
nav_item.get(field),
|
||||
f"navigation.{key}[{index}].{field}",
|
||||
errors,
|
||||
)
|
||||
_non_empty_string(navigation.get("footer"), "navigation.footer", errors)
|
||||
|
||||
categories = _mapping(data.get("categories"), "categories", errors)
|
||||
category_items = _array(
|
||||
categories.get("items"),
|
||||
"categories.items",
|
||||
errors,
|
||||
limit=20,
|
||||
)
|
||||
if not category_items:
|
||||
errors.append("categories.items must contain at least one category")
|
||||
if not all(
|
||||
isinstance(item, str) and item.strip() for item in category_items
|
||||
):
|
||||
errors.append("categories.items must contain non-empty strings")
|
||||
|
||||
videos = _mapping(data.get("videos"), "videos", errors)
|
||||
_non_empty_string(videos.get("sectionTitle"), "videos.sectionTitle", errors)
|
||||
video_items = _array(
|
||||
videos.get("items"),
|
||||
"videos.items",
|
||||
errors,
|
||||
limit=30,
|
||||
)
|
||||
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 (
|
||||
"title",
|
||||
"channel",
|
||||
"channelInitial",
|
||||
"category",
|
||||
"views",
|
||||
"time",
|
||||
"description",
|
||||
):
|
||||
_non_empty_string(
|
||||
video.get(key),
|
||||
f"videos.items[{index}].{key}",
|
||||
errors,
|
||||
)
|
||||
_colors(
|
||||
video.get("channelColors"),
|
||||
f"videos.items[{index}].channelColors",
|
||||
errors,
|
||||
)
|
||||
if video.get("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)
|
||||
metrics = _mapping(
|
||||
video.get("metrics"),
|
||||
f"videos.items[{index}].metrics",
|
||||
errors,
|
||||
)
|
||||
for key in ("likes", "comments"):
|
||||
_non_negative_number(
|
||||
metrics.get(key),
|
||||
f"videos.items[{index}].metrics.{key}",
|
||||
errors,
|
||||
)
|
||||
|
||||
shorts = _mapping(data.get("shorts"), "shorts", errors)
|
||||
_non_empty_string(shorts.get("sectionTitle"), "shorts.sectionTitle", errors)
|
||||
short_items = _array(
|
||||
shorts.get("items"),
|
||||
"shorts.items",
|
||||
errors,
|
||||
limit=20,
|
||||
)
|
||||
short_ids: set[str] = set()
|
||||
for index, item in enumerate(short_items):
|
||||
short = _mapping(item, f"shorts.items[{index}]", errors)
|
||||
short_id = short.get("id")
|
||||
_non_empty_string(short_id, f"shorts.items[{index}].id", errors)
|
||||
if isinstance(short_id, str):
|
||||
if short_id in short_ids:
|
||||
errors.append(f"shorts.items[{index}].id must be unique")
|
||||
short_ids.add(short_id)
|
||||
for key in ("title", "views"):
|
||||
_non_empty_string(
|
||||
short.get(key),
|
||||
f"shorts.items[{index}].{key}",
|
||||
errors,
|
||||
)
|
||||
if short.get("visual") not in VISUAL_TYPES:
|
||||
errors.append(
|
||||
f"shorts.items[{index}].visual must be one of: "
|
||||
f"{', '.join(sorted(VISUAL_TYPES))}"
|
||||
)
|
||||
_validate_remote_media(short.get("media"), f"shorts.items[{index}].media", errors)
|
||||
|
||||
subscriptions = _mapping(
|
||||
data.get("subscriptions"),
|
||||
"subscriptions",
|
||||
errors,
|
||||
)
|
||||
_non_empty_string(
|
||||
subscriptions.get("title"),
|
||||
"subscriptions.title",
|
||||
errors,
|
||||
)
|
||||
subscription_items = _array(
|
||||
subscriptions.get("items"),
|
||||
"subscriptions.items",
|
||||
errors,
|
||||
limit=20,
|
||||
)
|
||||
_validate_people(subscription_items, "subscriptions.items", 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=40,
|
||||
)
|
||||
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,
|
||||
)
|
||||
|
||||
if errors:
|
||||
raise DataValidationError("; ".join(errors))
|
||||
|
||||
return {
|
||||
"modules": list(MODULES),
|
||||
"counts": {
|
||||
"categories": len(category_items),
|
||||
"videos": len(video_items),
|
||||
"shorts": len(short_items),
|
||||
"subscriptions": len(subscription_items),
|
||||
"comments": len(comment_items),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
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())
|
||||
|
||||
Reference in new issue
Block a user