sync update from LAN repo (source dhk-1 @ 3b1ec5b4)
This commit is contained in:
1 parent
da6521b6cb
commit
264e2200d6
995 files changed
+148105
-13399
No files matched your search
@@ -0,0 +1,107 @@
|
||||
---
|
||||
name: x-page-generator
|
||||
description: 生成或绘制 X(原 Twitter/推特)及 X 风格的可交付社交时间线 HTML 网页;仅在用户明确要求 X 平台网页、Twitter/推特网页或点名本技能时使用。先把材料或检索结果整理成六模块 JSON,再用内置模板确定性渲染,保留右上角可视化 JSON 编辑弹窗。
|
||||
allowed-tools:
|
||||
- read_file
|
||||
- write_file
|
||||
- bash
|
||||
- present_files
|
||||
- web_search
|
||||
---
|
||||
|
||||
# X 页面生成器
|
||||
|
||||
本技能使用固定模板生成单文件 X 风格 HTML。模型只负责材料收集和 JSON,禁止重新手写页面结构、CSS 或渲染脚本。最终页面自带右上角设置按钮;用户可在弹窗中按模块继续编辑 JSON,并通过「应用并渲染」即时更新页面。
|
||||
|
||||
编辑弹窗还提供“上传图片/视频”:先把光标放进目标报道、帖子、视频或带 `visual`/`media` 的内容对象,上传文件会转换为 `data:` 地址并写入该对象的 `media` 字段。不设文件大小拦截;较大文件可能超过浏览器本地缓存容量,应同时下载 JSON 留存。
|
||||
|
||||
页面中已由 `media` 数据渲染的图片和视频还带悬浮上传图标:鼠标移入媒体后点击可任选图片或视频并直接替换,文件的实际类型会自动写入新的 `media.type`,结果同步写回页面 JSON 与浏览器缓存。头像、Logo 和无法映射回 JSON 的装饰图不会显示该入口;不按原媒体类型限制,也不设置文件大小拦截。
|
||||
|
||||
默认视觉直接复用模板原有的示例图:不要调用图像生成工具,不要让模型重新生成、拼装或内嵌新的内容型 SVG,也不要为了寻找“标准配图”延长检索。用户没有提供可直接使用的图片/视频且聚焦检索未得到可靠直链时,保留默认 JSON 的 `visual` 或内置视觉类型;这些是模板自带的静态示例,调用技能时不重新绘制。不要把大段 base64 示例图重复写进 JSON,图不合适时由用户在成品页面悬浮上传替换。
|
||||
|
||||
## 触发边界
|
||||
|
||||
- 用户明确说「生成/画/制作 X 平台网页」「Twitter/推特网页」「X 风格社交时间线」或点名 `x-page-generator` 时使用。
|
||||
- 仅讨论 X/Twitter、分析社交媒体、编写普通推文或出现字母 x 时不要使用。
|
||||
- 这是单页社交时间线模板,不改用通用多页门户模板。
|
||||
|
||||
## 单帖快速路径(强制)
|
||||
|
||||
只要请求是「一个账号 + 一条推文 + N 条热评」,无论是否指定图片、总评论数、热评主题或具体热评文本,都必须走本路径。模型只生成一份小型规格 JSON;脚本负责补齐六模块数据、内部校验并一次渲染 HTML。
|
||||
|
||||
1. 用 `write_file` 创建 `/mnt/user-data/outputs/x-single-post-spec.json`。推文正文和回复必须使用简体中文;人物姓名、账号 `@handle`、品牌与必要缩写可保留原文。最小规格示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"author": "账号名称",
|
||||
"handle": "@account",
|
||||
"verified": true,
|
||||
"text": "中文推文正文",
|
||||
"topic": "中心话题",
|
||||
"tags": ["话题标签"],
|
||||
"displayReplyCount": 20,
|
||||
"totalReplyCount": 10000,
|
||||
"replyTopics": ["中美经济影响", "两岸关系"],
|
||||
"likes": 0,
|
||||
"reposts": 0,
|
||||
"views": 0
|
||||
}
|
||||
```
|
||||
|
||||
`displayReplyCount` 是实际预载展示数,最多 100;`totalReplyCount` 是页面指标,可大于展示数。脚本会围绕 `replyTopics` 自动生成不同中文热评。只有用户明确给出逐条热评时才增加 `replies: ["中文热评", ...]`;未写满的部分仍由脚本补齐。媒体直链放入 `media: {"type":"image|video","url":"...","alt":"中文说明"}`;没有可靠直链时省略 `media`,直接沿用模板示例图,禁止搜索或造 SVG。
|
||||
|
||||
2. 只执行一次:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/x-page-generator/scripts/fast_single_post.py --spec /mnt/user-data/outputs/x-single-post-spec.json --output-dir /mnt/user-data/outputs
|
||||
```
|
||||
|
||||
3. stdout 为 `status: ok` 后,立即用 `present_files` 交付返回的 `data` 与 `html`;最终回复只需一句完成说明。
|
||||
|
||||
本路径禁止读取默认数据、数据契约、模板、运行时或脚本源码,禁止运行 `--help`、`init`、独立 `validate`/`render`,禁止先生成再补丁,禁止创建临时 Python/清理/路径探测脚本。执行中不要复述需求、讨论路径或逐步解释;除工具调用外最多发一条简短进度。若脚本返回规格错误,只修正规格 JSON 一次并重跑,不得转入源码排查。用户说不搜索或直接生成时,直接把其描述写成中文情景数据,不检索、不填写 `sourceUrl`、不添加情景说明条。只有用户明确要求两条及以上帖子,或明确要求改造趋势/推荐关注等其他模块时,才进入通用工作流。
|
||||
|
||||
## 通用工作流(仅限非单帖场景)
|
||||
|
||||
1. 读取当前会话材料、上传附件和已有产物,确定页面主题、当前账号、动态、趋势与推荐关注。
|
||||
2. 用户要求基于公开资料、主题涉及近期事件,或明确要求检索时,先做至多两批聚焦检索;用户明确说不要检索时不得联网。没有材料时使用中性示例内容,不虚构实时趋势,也不在帖文中添加「情景模拟页面」或「演示内容」说明条。
|
||||
- 如果动态被描述成政治人物、公共人物或机构真实发布的内容,必须检索并核对其官方账号原帖或可靠一手来源,再填写 `sourceUrl`;无法核验时不得声称该内容已真实发布,且不生成 `disclosure` 字段。
|
||||
3. 初始化新的完整 JSON:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/x-page-generator/scripts/render_x_page.py init --output /mnt/user-data/outputs/x-page-data.json
|
||||
```
|
||||
|
||||
4. 只修改 JSON。六个顶层模块必须全部保留:`site`、`navigation`、`composer`、`posts`、`trends`、`recommendations`。字段不确定时读取 [references/data-schema.md](references/data-schema.md)。
|
||||
5. 校验 JSON:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/x-page-generator/scripts/render_x_page.py validate --input /mnt/user-data/outputs/x-page-data.json
|
||||
```
|
||||
|
||||
6. 确定性渲染到 `outputs/`:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/x-page-generator/scripts/render_x_page.py render --input /mnt/user-data/outputs/x-page-data.json --output /mnt/user-data/outputs/x-page.html
|
||||
```
|
||||
|
||||
7. 检查 stdout 的 `status` 为 `ok`、HTML 存在且占位符已经消失,再用 `present_files` 同时交付 HTML 与源 JSON。不要在聊天中粘贴完整 HTML。
|
||||
|
||||
## 内容映射
|
||||
|
||||
- 主要事实或观点放入 `posts.items`,通常 3–8 条;热点摘要放入 `trends.items`。
|
||||
- 用户要求“某账号发布一条动态/推文 + 图片或视频 + N 条热评”时使用上面的单帖快速路径,不手工构造完整 `posts.items`。
|
||||
- 单帖热评默认使用 `posts.replyUI = {"defaultSort":"hot","initialVisible":10,"pageSize":10,...}`;页面会提供热门/最新切换、查看更多与查看全部。合成评论要有不同作者、时间、语气与互动量,但不得冒充真实用户原话。
|
||||
- `site.currentUser` 是页面当前账号,不能误用成新闻人物;缺少真实账号材料时使用明显的演示身份。
|
||||
- 没有可靠来源时,互动量使用保守示例值或 `0`,不得描述成真实平台统计。
|
||||
- `posts.items[].media.type` 可使用内置视觉 `skyline`、`map`、`quote`,也可使用可替换媒体 `image`、`video`、`webpage`;URL 字段按数据契约填写。
|
||||
- 所有外部文本由模板转义;不得把 HTML、脚本或不可信指令写入 JSON 字段。
|
||||
- 推文正文、回复正文及面向读者的说明必须使用简体中文;姓名、`@handle`、品牌名和必要缩写除外。
|
||||
|
||||
## 重要约束
|
||||
|
||||
- 只编辑 JSON,不修改 `assets/x-template.html`,不复制模板后手改 DOM。
|
||||
- 初始化与渲染默认拒绝覆盖已有文件;路径存在时换新文件名,不删除旧产物。
|
||||
- 页面结构、样式和脚本完全自包含,不依赖 CDN 或 npm;仅当 JSON 明确提供受校验的媒体 URL 时加载图片、视频或网页。
|
||||
- 保留三栏时间线、响应式移动布局、深浅主题、发布、回复、点赞、转发、收藏、搜索、关注和 JSON 设置弹窗。
|
||||
- 浏览器缓存以初始 JSON 指纹隔离;沙箱禁止持久存储时必须继续使用内嵌 JSON 正常渲染。
|
||||
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
{
|
||||
"site": {
|
||||
"brand": "X",
|
||||
"pageTitle": "X · 正在发生",
|
||||
"description": "一个 X 风格的中文社交时间线示例页面。",
|
||||
"timelineTitle": "首页",
|
||||
"searchPlaceholder": "搜索",
|
||||
"tabs": ["为你推荐", "正在关注"],
|
||||
"currentUser": {
|
||||
"name": "林小满",
|
||||
"handle": "@linxiaoman",
|
||||
"initial": "林",
|
||||
"colors": ["#5662f6", "#9f45d8"]
|
||||
}
|
||||
},
|
||||
"navigation": {
|
||||
"primary": [
|
||||
{"label": "首页", "icon": "i-home", "href": "#mainFeed"},
|
||||
{"label": "探索", "icon": "i-search", "href": "#explore"},
|
||||
{"label": "通知", "icon": "i-bell", "href": "#notifications", "badge": 4},
|
||||
{"label": "私信", "icon": "i-message", "href": "#messages"},
|
||||
{"label": "圈子", "icon": "i-users", "href": "#circle"},
|
||||
{"label": "书签", "icon": "i-bookmark", "href": "#bookmarks"},
|
||||
{"label": "个人资料", "icon": "i-user", "href": "#profile"},
|
||||
{"label": "更多", "icon": "i-more", "href": "#more"}
|
||||
],
|
||||
"postLabel": "发布",
|
||||
"mobile": [
|
||||
{"label": "首页", "icon": "i-home"},
|
||||
{"label": "探索", "icon": "i-search"},
|
||||
{"label": "通知", "icon": "i-bell"},
|
||||
{"label": "私信", "icon": "i-message"},
|
||||
{"label": "书签", "icon": "i-bookmark"}
|
||||
],
|
||||
"footerLinks": [
|
||||
{"label": "服务条款", "href": "#terms"},
|
||||
{"label": "隐私政策", "href": "#privacy"},
|
||||
{"label": "Cookie", "href": "#cookies"},
|
||||
{"label": "无障碍", "href": "#accessibility"}
|
||||
],
|
||||
"copyright": "© 2026 X"
|
||||
},
|
||||
"composer": {
|
||||
"audience": "所有人",
|
||||
"placeholder": "有什么新鲜事?",
|
||||
"replyPermission": "所有人都可以回复",
|
||||
"draftsLabel": "草稿",
|
||||
"maxLength": 280
|
||||
},
|
||||
"posts": {
|
||||
"replyUI": {
|
||||
"defaultSort": "hot",
|
||||
"initialVisible": 10,
|
||||
"pageSize": 10,
|
||||
"hotLabel": "热门",
|
||||
"latestLabel": "最新",
|
||||
"showMoreLabel": "查看更多",
|
||||
"showAllLabel": "查看全部"
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "city-sky",
|
||||
"author": "许知夏",
|
||||
"handle": "@summerxu",
|
||||
"initial": "许",
|
||||
"colors": ["#15a88b", "#2e88cc"],
|
||||
"verified": true,
|
||||
"time": "32 分钟",
|
||||
"text": "今天的天空像一封刚拆开的蓝色情书。",
|
||||
"tags": ["城市漫步"],
|
||||
"media": {"type": "skyline", "caption": "南浦大桥 · 06:42", "alt": "蓝色天空与城市大桥的抽象插画"},
|
||||
"metrics": {"replies": 18, "reposts": 34, "likes": 276, "views": 84000}
|
||||
},
|
||||
{
|
||||
"id": "design-restraint",
|
||||
"author": "陈默",
|
||||
"handle": "@modesign",
|
||||
"initial": "陈",
|
||||
"colors": ["#0f7d78", "#51b35e"],
|
||||
"verified": false,
|
||||
"time": "1 小时",
|
||||
"text": "设计并不是不断加东西。更多时候,是在所有“还可以再做一点”的时刻,知道什么时候停下。",
|
||||
"tags": [],
|
||||
"media": {"type": "quote", "author": "周野", "handle": "@zhouye", "initial": "周", "colors": ["#f97316", "#db2777"], "time": "昨天", "text": "复杂很容易,克制才需要勇气。"},
|
||||
"metrics": {"replies": 12, "reposts": 91, "likes": 538, "views": 120000}
|
||||
},
|
||||
{
|
||||
"id": "bookstore-map",
|
||||
"author": "光合计划",
|
||||
"handle": "@photosynthesis",
|
||||
"initial": "光",
|
||||
"colors": ["#ff8a37", "#d93f7b"],
|
||||
"verified": true,
|
||||
"time": "3 小时",
|
||||
"text": "我们把城市里 12 家小书店画成了一张散步地图。这个周末,选一条从没走过的街,去遇见一本意料之外的书吧。",
|
||||
"tags": ["独立书店", "城市阅读"],
|
||||
"media": {"type": "map", "caption": "独立书店散步地图", "alt": "城市书店散步地图抽象插画"},
|
||||
"metrics": {"replies": 46, "reposts": 182, "likes": 902, "views": 240000}
|
||||
},
|
||||
{
|
||||
"id": "commute-playlist",
|
||||
"author": "宋可心",
|
||||
"handle": "@kexin",
|
||||
"initial": "宋",
|
||||
"colors": ["#8b5cf6", "#3b82f6"],
|
||||
"verified": false,
|
||||
"time": "5 小时",
|
||||
"text": "下班路上的随机播放,总会精准地挑中你今天最需要听到的那一句。你们最近单曲循环的是哪首?",
|
||||
"tags": ["通勤歌单"],
|
||||
"metrics": {"replies": 68, "reposts": 21, "likes": 309, "views": 56000}
|
||||
}
|
||||
]
|
||||
},
|
||||
"trends": {
|
||||
"title": "正在发生",
|
||||
"showMoreLabel": "显示更多",
|
||||
"items": [
|
||||
{"category": "中国 · 热门", "title": "#秋日城市漫步", "count": "2.8 万条动态", "href": "#trend1"},
|
||||
{"category": "科技 · 热门", "title": "AI 产品设计", "count": "1.7 万条动态", "href": "#trend2"},
|
||||
{"category": "文化 · 热门", "title": "独立书店地图", "count": "8,942 条动态", "href": "#trend3"},
|
||||
{"category": "音乐 · 趋势", "title": "通勤歌单", "count": "5,610 条动态", "href": "#trend4"}
|
||||
]
|
||||
},
|
||||
"recommendations": {
|
||||
"title": "推荐关注",
|
||||
"showMoreLabel": "显示更多",
|
||||
"items": [
|
||||
{"name": "周野", "handle": "@zhouye", "initial": "周", "colors": ["#f97316", "#db2777"]},
|
||||
{"name": "顾念", "handle": "@gunian", "initial": "顾", "colors": ["#0ea5e9", "#10b981"]},
|
||||
{"name": "理想生活研究所", "handle": "@betterlife", "initial": "理", "colors": ["#6366f1", "#ec4899"]}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,855 @@
|
||||
(() => {
|
||||
"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", "composer", "posts", "trends", "recommendations"];
|
||||
const MODULE_META = {
|
||||
site: ["站点信息", "品牌、标题与当前账号"],
|
||||
navigation: ["导航", "主导航、移动导航与页脚"],
|
||||
composer: ["发布框", "占位语与字数限制"],
|
||||
posts: ["动态", "时间线内容与互动量"],
|
||||
trends: ["趋势", "右栏热门话题"],
|
||||
recommendations: ["推荐关注", "右栏推荐账号"]
|
||||
};
|
||||
const ALLOWED_ICONS = new Set(["i-home", "i-search", "i-bell", "i-message", "i-users", "i-bookmark", "i-user", "i-more"]);
|
||||
const embeddedData = JSON.parse(qs("#xPageData").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 = "x-page-data-v1:" + pageFingerprint;
|
||||
const themeKey = "x-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) => {
|
||||
const href = String(value || "#");
|
||||
return /^(#|https?:\/\/)/i.test(href) ? escapeHTML(href) : "#";
|
||||
};
|
||||
const safeRemoteUrl = (value, kind = "link") => {
|
||||
const source = String(value || "").trim();
|
||||
if (!source) return "";
|
||||
const lowered = source.toLowerCase();
|
||||
if (kind === "image" && lowered.startsWith("data:image/")) return source;
|
||||
if (kind === "video" && lowered.startsWith("data:video/")) return source;
|
||||
try {
|
||||
const url = new URL(source);
|
||||
return url.protocol === "http:" || url.protocol === "https:" ? url.href : "";
|
||||
} catch (_error) { return ""; }
|
||||
};
|
||||
const validateRemoteMediaTree = (value, path = "当前模块") => {
|
||||
if (Array.isArray(value)) return value.forEach((item, index) => validateRemoteMediaTree(item, path + "[" + index + "]"));
|
||||
if (!value || typeof value !== "object") return;
|
||||
const media = value.media;
|
||||
if (media && ["image", "video", "webpage"].includes(media.type)) {
|
||||
if ((media.type === "image" || media.type === "video") && !safeRemoteUrl(media.mediaUrl, media.type)) throw new Error(path + ".media.mediaUrl 无效");
|
||||
if (media.type === "webpage" && !safeRemoteUrl(media.pageUrl)) throw new Error(path + ".media.pageUrl 无效");
|
||||
if (media.posterUrl && !safeRemoteUrl(media.posterUrl, "image")) throw new Error(path + ".media.posterUrl 无效");
|
||||
}
|
||||
Object.entries(value).forEach(([key, item]) => { if (key !== "media") validateRemoteMediaTree(item, path + "." + key); });
|
||||
};
|
||||
const safeColor = (value, fallback) => /^#[0-9a-f]{3,8}$/i.test(String(value || "")) ? value : fallback;
|
||||
const safeIcon = (value) => ALLOWED_ICONS.has(value) ? value : "i-more";
|
||||
const icon = (id, className) => '<svg' + (className ? ' class="' + className + '"' : "") + ' aria-hidden="true"><use href="#' + id + '"/></svg>';
|
||||
const colors = (person) => {
|
||||
const list = person && Array.isArray(person.colors) ? person.colors : [];
|
||||
return [safeColor(list[0], "#5662f6"), safeColor(list[1], "#9f45d8")];
|
||||
};
|
||||
const avatar = (person, className) => {
|
||||
const pair = colors(person || {});
|
||||
return '<span class="avatar ' + (className || "") + '" style="--a:' + pair[0] + ";--b:" + pair[1] + '">' + escapeHTML((person && person.initial) || "X") + "</span>";
|
||||
};
|
||||
const formatCount = (value) => {
|
||||
const number = Number(value) || 0;
|
||||
if (number >= 10000) return (number / 10000).toFixed(1).replace(".0", "") + "万";
|
||||
return String(number);
|
||||
};
|
||||
|
||||
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 skylineSvg = '<svg viewBox="0 0 800 500" preserveAspectRatio="xMidYMid slice"><defs><linearGradient id="g-sky" x1="0" y1="0" x2="0" y2="1"><stop stop-color="#82c9ff"/><stop offset="1" stop-color="#d8efff"/></linearGradient></defs><rect width="800" height="500" fill="url(#g-sky)"/><circle cx="640" cy="110" r="45" fill="#fff" opacity=".75"/><path d="M0 370C180 310 330 340 470 300s230-5 330 35v165H0Z" fill="#5c8fae"/><path d="M40 355h720M130 355l110-130m430 130L560 225M240 225h320" fill="none" stroke="#e9f6ff" stroke-width="13"/><path d="M130 355V208m540 147V208" stroke="#325d7c" stroke-width="18"/><path d="M80 400c150-30 260 10 380-4 120-13 210-1 340 38" fill="none" stroke="#bfe4f7" stroke-width="8" opacity=".7"/></svg>';
|
||||
const mapSvg = '<svg viewBox="0 0 800 500" preserveAspectRatio="xMidYMid slice"><rect width="800" height="500" fill="#f4ead9"/><path d="M80 70c110 90 90 220 220 250s160-100 250-30 60 120 170 140" fill="none" stroke="#df6d5a" stroke-width="12" stroke-linecap="round"/><path d="M20 390c150-80 230 10 345-60s180-210 410-165" fill="none" stroke="#497d83" stroke-width="14" stroke-linecap="round"/><path d="M160 20c40 140 180 120 180 250s-90 130-65 230M580 0c-70 150 40 215-50 330s30 110 130 170" fill="none" stroke="#e3b55a" stroke-width="10"/><g fill="#fff" stroke="#1f2937" stroke-width="4"><rect x="123" y="114" width="70" height="54" rx="8"/><rect x="339" y="277" width="70" height="54" rx="8"/><rect x="563" y="142" width="70" height="54" rx="8"/><rect x="604" y="371" width="70" height="54" rx="8"/></g><g fill="#1f2937"><path d="m141 127 17 8 17-8v27l-17 7-17-7Z"/><path d="m357 290 17 8 17-8v27l-17 7-17-7Z"/><path d="m581 155 17 8 17-8v27l-17 7-17-7Z"/><path d="m622 384 17 8 17-8v27l-17 7-17-7Z"/></g><circle cx="94" cy="388" r="15" fill="#df6d5a"/><circle cx="742" cy="166" r="15" fill="#497d83"/></svg>';
|
||||
|
||||
document.head.insertAdjacentHTML("beforeend", '<style data-external-media>.external-media{position:relative}.external-media>img,.external-media>video,.external-media>iframe{width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}.external-media>iframe{object-fit:initial}.external-open{position:absolute;right:10px;bottom:10px;padding:7px 11px;border-radius:999px;color:#fff!important;background:rgba(0,0,0,.72);text-decoration:none;font-size:12px;font-weight:700}.external-page{margin-top:12px;overflow:hidden;border:1px solid var(--border-strong);border-radius:16px;background:var(--surface)}.external-page>img,.external-page>iframe{width:100%;height:240px;display:block;border:0;object-fit:cover;background:#000}.external-page>a{display:block;padding:12px 14px;color:var(--text);text-decoration:none}.external-page>a strong,.external-page>a span{display:block}.external-page>a span{margin-top:4px;color:var(--muted);font-size:13px}</style>');
|
||||
|
||||
const renderMedia = (media) => {
|
||||
if (!media || !media.type) return "";
|
||||
if (media.type === "quote") {
|
||||
return '<div class="quote-post"><div class="quote-author">' + avatar(media, "avatar-sm") + "<strong>" + escapeHTML(media.author) + '</strong><span class="handle">' + escapeHTML(media.handle) + " · " + escapeHTML(media.time) + "</span></div><p>" + escapeHTML(media.text) + "</p></div>";
|
||||
}
|
||||
if (media.type === "image") {
|
||||
const source = safeRemoteUrl(media.mediaUrl, "image");
|
||||
if (!source) return "";
|
||||
const pageUrl = safeRemoteUrl(media.pageUrl);
|
||||
return '<div class="post-media external-media"><img src="' + escapeHTML(source) + '" alt="' + escapeHTML(media.alt || media.caption || "动态图片") + '" loading="lazy" referrerpolicy="no-referrer"/>' + (pageUrl ? '<a class="external-open" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer">打开来源</a>' : "") + "</div>";
|
||||
}
|
||||
if (media.type === "video") {
|
||||
const source = safeRemoteUrl(media.mediaUrl, "video");
|
||||
if (!source) return "";
|
||||
const poster = safeRemoteUrl(media.posterUrl, "image");
|
||||
const pageUrl = safeRemoteUrl(media.pageUrl);
|
||||
return '<div class="post-media external-media"><video src="' + escapeHTML(source) + '"' + (poster ? ' poster="' + escapeHTML(poster) + '"' : "") + ' controls playsinline preload="metadata" aria-label="' + escapeHTML(media.alt || media.caption || "动态视频") + '"></video>' + (pageUrl ? '<a class="external-open" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer">打开来源</a>' : "") + "</div>";
|
||||
}
|
||||
if (media.type === "webpage") {
|
||||
const pageUrl = safeRemoteUrl(media.pageUrl);
|
||||
if (!pageUrl) return "";
|
||||
const preview = safeRemoteUrl(media.mediaUrl, "image");
|
||||
const body = media.embed === true
|
||||
? '<iframe src="' + escapeHTML(pageUrl) + '" title="' + escapeHTML(media.title || "网页预览") + '" loading="lazy" referrerpolicy="no-referrer" sandbox="allow-forms allow-popups allow-scripts"></iframe>'
|
||||
: (preview ? '<img src="' + escapeHTML(preview) + '" alt="' + escapeHTML(media.alt || media.title || "网页预览图") + '" loading="lazy" referrerpolicy="no-referrer"/>' : "");
|
||||
return '<div class="external-page">' + body + '<a href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer"><strong>' + escapeHTML(media.title || pageUrl) + '</strong><span>' + escapeHTML(media.description || "打开网页") + "</span></a></div>";
|
||||
}
|
||||
const artwork = media.type === "map" ? mapSvg : skylineSvg;
|
||||
return '<div class="post-media" role="img" aria-label="' + escapeHTML(media.alt || media.caption || "动态配图") + '">' + artwork + '<span class="media-caption">' + escapeHTML(media.caption || "") + "</span></div>";
|
||||
};
|
||||
|
||||
const replyUI = () => Object.assign({
|
||||
defaultSort: "hot",
|
||||
initialVisible: 10,
|
||||
pageSize: 10,
|
||||
hotLabel: "热门",
|
||||
latestLabel: "最新",
|
||||
showMoreLabel: "查看更多",
|
||||
showAllLabel: "查看全部"
|
||||
}, pageData.posts && pageData.posts.replyUI ? pageData.posts.replyUI : {});
|
||||
const replyMarkup = (reply) => {
|
||||
const replyLikes = Math.max(0, Number(reply.likes) || 0);
|
||||
const replyCount = Math.max(0, Number(reply.replyCount) || 0);
|
||||
return '<div class="reply-item">' + avatar(reply, "avatar-sm") + '<div class="reply-content"><header><strong>' + escapeHTML(reply.author) + "</strong>" +
|
||||
(reply.verified ? icon("i-verified", "verified") : "") +
|
||||
(reply.handle ? '<span class="handle">' + escapeHTML(reply.handle) + "</span>" : "") +
|
||||
(reply.time ? '<span class="dot">·</span><time>' + escapeHTML(reply.time) + "</time>" : "") +
|
||||
'</header><p>' + escapeHTML(reply.text) + '</p><div class="reply-meta"><button type="button">回复</button><span>' + formatCount(replyLikes) + ' 个赞</span>' +
|
||||
(replyCount ? '<span>' + formatCount(replyCount) + ' 条回复</span>' : "") + "</div></div></div>";
|
||||
};
|
||||
const postSource = (post) => {
|
||||
const sourceUrl = safeRemoteUrl(post.sourceUrl);
|
||||
if (!sourceUrl) return "";
|
||||
return '<div class="post-source"><a href="' + escapeHTML(sourceUrl) + '" target="_blank" rel="noopener noreferrer">查看原帖</a></div>';
|
||||
};
|
||||
const renderReplyList = (postElement, postData, state) => {
|
||||
const replies = Array.isArray(postData.replies) ? postData.replies : [];
|
||||
const ui = replyUI();
|
||||
const sorted = replies.map((reply, index) => ({ reply, index }));
|
||||
if (state.sort === "hot") {
|
||||
sorted.sort((left, right) => (Number(right.reply.likes) || 0) - (Number(left.reply.likes) || 0) || (Number(right.reply.replyCount) || 0) - (Number(left.reply.replyCount) || 0) || left.index - right.index);
|
||||
}
|
||||
state.visible = Math.min(Math.max(1, state.visible), Math.max(1, replies.length));
|
||||
qs(".reply-list", postElement).innerHTML = sorted.slice(0, state.visible).map(({ reply }) => replyMarkup(reply)).join("");
|
||||
const tools = qs(".reply-tools", postElement);
|
||||
tools.hidden = replies.length === 0;
|
||||
qs(".reply-summary", postElement).textContent = replies.length + " 条回复";
|
||||
qsa(".reply-sort", postElement).forEach((button) => {
|
||||
button.textContent = button.dataset.sort === "latest" ? ui.latestLabel : ui.hotLabel;
|
||||
const active = button.dataset.sort === state.sort;
|
||||
button.classList.toggle("active", active);
|
||||
button.setAttribute("aria-pressed", String(active));
|
||||
});
|
||||
const remaining = Math.max(0, replies.length - state.visible);
|
||||
const moreButton = qs(".reply-more", postElement);
|
||||
const allButton = qs(".reply-all", postElement);
|
||||
moreButton.hidden = remaining === 0;
|
||||
allButton.hidden = remaining === 0 || remaining <= Math.max(1, Number(ui.pageSize) || 10);
|
||||
moreButton.textContent = ui.showMoreLabel + " " + Math.min(remaining, Math.max(1, Number(ui.pageSize) || 10)) + " 条";
|
||||
allButton.textContent = ui.showAllLabel + " " + replies.length + " 条";
|
||||
};
|
||||
|
||||
const postMarkup = (post) => {
|
||||
const metrics = post.metrics || {};
|
||||
const tags = Array.isArray(post.tags) ? post.tags : [];
|
||||
const tagMarkup = tags.map((tag) => ' <a href="#tag-' + encodeURIComponent(String(tag)) + '">#' + escapeHTML(tag) + "</a>").join("");
|
||||
return '<article class="post" data-post-id="' + escapeHTML(post.id) + '" data-search="' + escapeHTML([post.author, post.handle, post.text].concat(tags).join(" ")) + '">' +
|
||||
avatar(post, "avatar-lg") +
|
||||
'<div class="post-main"><header class="post-head"><strong>' + escapeHTML(post.author) + "</strong>" +
|
||||
(post.verified ? icon("i-verified", "verified") : "") +
|
||||
'<span class="handle">' + escapeHTML(post.handle) + '</span><span class="dot">·</span><time>' + escapeHTML(post.time) + '</time><button class="more" aria-label="更多操作">' + icon("i-more") + "</button></header>" +
|
||||
postSource(post) + '<p class="post-text">' + escapeHTML(post.text) + tagMarkup + "</p>" + renderMedia(post.media) +
|
||||
'<div class="post-actions"><button class="action reply"><span class="action-icon">' + icon("i-comment") + '</span><span class="action-count">' + formatCount(metrics.replies) + '</span></button><button class="action repost"><span class="action-icon">' + icon("i-repost") + '</span><span class="action-count">' + formatCount(metrics.reposts) + '</span></button><button class="action like"><span class="action-icon">' + icon("i-heart") + '</span><span class="action-count">' + formatCount(metrics.likes) + '</span></button><button class="action views"><span class="action-icon">' + icon("i-chart") + '</span><span class="action-count">' + formatCount(metrics.views) + '</span></button><button class="action bookmark-action" aria-label="收藏"><span class="action-icon">' + icon("i-bookmark") + '</span></button><button class="action share" aria-label="分享"><span class="action-icon">' + icon("i-share") + "</span></button></div></div>" +
|
||||
'<div class="reply-section' + (post.repliesExpanded === true ? " open" : "") + '"><div class="reply-tools" hidden><strong class="reply-summary"></strong><div><button type="button" class="reply-sort" data-sort="hot">热门</button><button type="button" class="reply-sort" data-sort="latest">最新</button></div></div><div class="reply-list"></div><div class="reply-pagination"><button type="button" class="reply-more"></button><button type="button" class="reply-all"></button></div><form class="reply-form"><label class="sr-only">回复内容</label><input maxlength="160" placeholder="发布你的回复" /><button class="reply-send" aria-label="发送回复">' + icon("i-send") + '</button></form></div><div class="post-menu"><button>' + icon("i-bookmark") + "收藏这条动态</button><button>" + icon("i-volume-off") + "不再关注此话题</button></div></article>";
|
||||
};
|
||||
|
||||
const renderSite = () => {
|
||||
const site = pageData.site;
|
||||
const user = site.currentUser || {};
|
||||
document.title = site.pageTitle || site.brand || "X";
|
||||
qs('meta[name="description"]').content = site.description || "";
|
||||
qs("#brandLink").setAttribute("aria-label", (site.brand || "X") + " 首页");
|
||||
qs("#timelineHeading").textContent = (site.brand || "X") + " " + (site.timelineTitle || "首页") + "时间线";
|
||||
qs("#mobileTitle").textContent = site.timelineTitle || "首页";
|
||||
qs("#mobileUser").innerHTML = avatar(user, "avatar-sm");
|
||||
qs("#composerAvatar").innerHTML = avatar(user, "avatar-lg");
|
||||
qs("#modalAvatar").innerHTML = avatar(user, "avatar-lg");
|
||||
qs("#accountSwitcher").innerHTML = avatar(user, "") + '<span class="account-copy"><strong>' + escapeHTML(user.name) + "</strong><span>" + escapeHTML(user.handle) + '</span></span>' + icon("i-more");
|
||||
qs("#searchInput").placeholder = site.searchPlaceholder || "搜索";
|
||||
const tabs = Array.isArray(site.tabs) ? site.tabs : [];
|
||||
qs("#feedTabs").innerHTML = tabs.map((label, index) => '<button class="tab' + (index === 0 ? " active" : "") + '" role="tab" aria-selected="' + (index === 0 ? "true" : "false") + '">' + escapeHTML(label) + "</button>").join("");
|
||||
qsa(".tab").forEach((tab) => tab.addEventListener("click", () => {
|
||||
qsa(".tab").forEach((item) => {
|
||||
item.classList.remove("active");
|
||||
item.setAttribute("aria-selected", "false");
|
||||
});
|
||||
tab.classList.add("active");
|
||||
tab.setAttribute("aria-selected", "true");
|
||||
qs("#timelineStatus").classList.add("show");
|
||||
window.setTimeout(() => qs("#timelineStatus").classList.remove("show"), 1600);
|
||||
}));
|
||||
};
|
||||
|
||||
const renderNavigation = () => {
|
||||
const navigation = pageData.navigation;
|
||||
const primary = Array.isArray(navigation.primary) ? navigation.primary : [];
|
||||
qs("#primaryNav").innerHTML = primary.map((item, index) => '<a class="nav-item' + (index === 0 ? " active" : "") + '" href="' + safeHref(item.href) + '">' + icon(safeIcon(item.icon)) + "<span>" + escapeHTML(item.label) + "</span>" + (item.badge ? '<b class="nav-badge">' + escapeHTML(item.badge) + "</b>" : "") + "</a>").join("");
|
||||
qs("#postCta").textContent = navigation.postLabel || "发布";
|
||||
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 footerLinks = Array.isArray(navigation.footerLinks) ? navigation.footerLinks : [];
|
||||
qs("#rightFooter").innerHTML = footerLinks.map((item) => '<a href="' + safeHref(item.href) + '">' + escapeHTML(item.label) + "</a>").join("") + "<span>" + escapeHTML(navigation.copyright || "") + "</span>";
|
||||
};
|
||||
|
||||
const renderComposer = () => {
|
||||
const composer = pageData.composer;
|
||||
const maxLength = Math.max(1, Number(composer.maxLength) || 280);
|
||||
["#composerText", "#modalText"].forEach((selector) => {
|
||||
const field = qs(selector);
|
||||
field.maxLength = maxLength;
|
||||
field.placeholder = composer.placeholder || "有什么新鲜事?";
|
||||
});
|
||||
qs("#composerAudience").textContent = composer.audience || "所有人";
|
||||
qs("#modalAudience").textContent = composer.audience || "所有人";
|
||||
qs("#replyPermission span").textContent = composer.replyPermission || "";
|
||||
qs("#modalReplyPermission").textContent = composer.replyPermission || "";
|
||||
qs("#draftsLabel").textContent = composer.draftsLabel || "草稿";
|
||||
updateCounter(qs("#composerText"), qs("#charCounter"), qs("#publishButton"));
|
||||
updateCounter(qs("#modalText"), qs("#modalCounter"), qs("#modalPublish"));
|
||||
};
|
||||
|
||||
const bindPost = (post, postData) => {
|
||||
const ui = replyUI();
|
||||
const state = {
|
||||
sort: ui.defaultSort === "latest" ? "latest" : "hot",
|
||||
visible: Math.max(1, Number(ui.initialVisible) || 10)
|
||||
};
|
||||
const paintReplies = () => renderReplyList(post, postData, state);
|
||||
const numberFrom = (text) => Number(String(text).replace(/[^0-9.]/g, "")) || 0;
|
||||
const like = qs(".like", post);
|
||||
like.addEventListener("click", () => {
|
||||
const count = qs(".action-count", like);
|
||||
const active = like.classList.toggle("liked");
|
||||
count.textContent = formatCount(Math.max(0, numberFrom(count.textContent) + (active ? 1 : -1)));
|
||||
like.setAttribute("aria-pressed", String(active));
|
||||
});
|
||||
const repost = qs(".repost", post);
|
||||
repost.addEventListener("click", () => {
|
||||
const count = qs(".action-count", repost);
|
||||
const active = repost.classList.toggle("reposted");
|
||||
count.textContent = formatCount(Math.max(0, numberFrom(count.textContent) + (active ? 1 : -1)));
|
||||
showToast(active ? "已转发" : "已撤销转发");
|
||||
});
|
||||
qs(".bookmark-action", post).addEventListener("click", (event) => {
|
||||
const active = event.currentTarget.classList.toggle("bookmarked");
|
||||
showToast(active ? "已添加到书签" : "已从书签移除");
|
||||
});
|
||||
qs(".reply", post).addEventListener("click", () => {
|
||||
const section = qs(".reply-section", post);
|
||||
section.classList.toggle("open");
|
||||
if (section.classList.contains("open")) qs("input", section).focus();
|
||||
});
|
||||
qsa(".reply-sort", post).forEach((button) => button.addEventListener("click", () => {
|
||||
state.sort = button.dataset.sort === "latest" ? "latest" : "hot";
|
||||
state.visible = Math.max(1, Number(replyUI().initialVisible) || 10);
|
||||
paintReplies();
|
||||
}));
|
||||
qs(".reply-more", post).addEventListener("click", () => {
|
||||
state.visible += Math.max(1, Number(replyUI().pageSize) || 10);
|
||||
paintReplies();
|
||||
});
|
||||
qs(".reply-all", post).addEventListener("click", () => {
|
||||
state.visible = Array.isArray(postData.replies) ? postData.replies.length : 0;
|
||||
paintReplies();
|
||||
});
|
||||
qs(".reply-form", post).addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const input = qs("input", event.currentTarget);
|
||||
const value = input.value.trim();
|
||||
if (!value) return;
|
||||
if (!Array.isArray(postData.replies)) postData.replies = [];
|
||||
const user = pageData.site.currentUser || {};
|
||||
postData.replies.unshift({
|
||||
id: "local-" + Date.now(),
|
||||
author: user.name || "我",
|
||||
handle: user.handle || "",
|
||||
initial: user.initial || "我",
|
||||
colors: user.colors || ["#5662f6", "#9f45d8"],
|
||||
time: "刚刚",
|
||||
text: value,
|
||||
likes: 0,
|
||||
replyCount: 0
|
||||
});
|
||||
postData.metrics = postData.metrics || {};
|
||||
postData.metrics.replies = Math.max(Number(postData.metrics.replies) || 0, postData.replies.length - 1) + 1;
|
||||
qs(".reply .action-count", post).textContent = formatCount(postData.metrics.replies);
|
||||
state.visible += 1;
|
||||
paintReplies();
|
||||
input.value = "";
|
||||
showToast("回复已发布");
|
||||
});
|
||||
qs(".share", post).addEventListener("click", async () => {
|
||||
try {
|
||||
if (navigator.share) await navigator.share({ title: document.title, text: qs(".post-text", post).textContent });
|
||||
else if (navigator.clipboard) {
|
||||
await navigator.clipboard.writeText(location.href);
|
||||
showToast("链接已复制");
|
||||
} else showToast("分享暂时不可用");
|
||||
} catch (error) {
|
||||
if (!error || error.name !== "AbortError") showToast("分享暂时不可用");
|
||||
}
|
||||
});
|
||||
const menu = qs(".post-menu", post);
|
||||
qs(".more", post).addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
qsa(".post-menu.open").forEach((other) => {
|
||||
if (other !== menu) other.classList.remove("open");
|
||||
});
|
||||
menu.classList.toggle("open");
|
||||
});
|
||||
paintReplies();
|
||||
};
|
||||
|
||||
const applySearch = () => {
|
||||
const query = qs("#searchInput").value.trim().toLocaleLowerCase();
|
||||
let visible = 0;
|
||||
qsa(".post").forEach((post) => {
|
||||
const match = !query || post.dataset.search.toLocaleLowerCase().includes(query) || post.textContent.toLocaleLowerCase().includes(query);
|
||||
post.hidden = !match;
|
||||
if (match) visible += 1;
|
||||
});
|
||||
qs("#emptyState").style.display = visible ? "none" : "block";
|
||||
};
|
||||
|
||||
const renderPosts = () => {
|
||||
const items = Array.isArray(pageData.posts.items) ? pageData.posts.items : [];
|
||||
qs("#posts").innerHTML = items.map(postMarkup).join("");
|
||||
qsa(".post").forEach((post, index) => bindPost(post, items[index]));
|
||||
applySearch();
|
||||
};
|
||||
|
||||
const renderTrends = () => {
|
||||
const data = pageData.trends;
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#trendsCard").innerHTML = "<h2>" + escapeHTML(data.title) + "</h2>" + items.map((item) => '<a class="trend" href="' + safeHref(item.href) + '"><span class="trend-head">' + escapeHTML(item.category) + icon("i-more") + "</span><strong>" + escapeHTML(item.title) + "</strong><small>" + escapeHTML(item.count) + "</small></a>").join("") + '<a class="show-more" href="#more-trends">' + escapeHTML(data.showMoreLabel || "显示更多") + "</a>";
|
||||
};
|
||||
|
||||
const renderRecommendations = () => {
|
||||
const data = pageData.recommendations;
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#recommendationsCard").innerHTML = "<h2>" + escapeHTML(data.title) + "</h2>" + items.map((person) => '<div class="follow-row">' + avatar(person, "avatar-sm") + '<span class="follow-copy"><strong>' + escapeHTML(person.name) + "</strong><span>" + escapeHTML(person.handle) + '</span></span><button class="follow-button">关注</button></div>').join("") + '<a class="show-more" href="#more-people">' + escapeHTML(data.showMoreLabel || "显示更多") + "</a>";
|
||||
qsa("#recommendationsCard .follow-button").forEach((button) => button.addEventListener("click", () => {
|
||||
const following = button.classList.toggle("following");
|
||||
button.textContent = following ? "正在关注" : "关注";
|
||||
showToast(following ? "已关注" : "已取消关注");
|
||||
}));
|
||||
};
|
||||
|
||||
const renderAll = () => {
|
||||
renderSite();
|
||||
renderNavigation();
|
||||
renderComposer();
|
||||
renderPosts();
|
||||
renderTrends();
|
||||
renderRecommendations();
|
||||
};
|
||||
|
||||
const updateCounter = (textarea, counter, button) => {
|
||||
const maximum = Math.max(1, Number(pageData.composer.maxLength) || 280);
|
||||
const left = maximum - textarea.value.length;
|
||||
counter.textContent = left;
|
||||
counter.classList.toggle("warn", left <= Math.min(20, Math.floor(maximum * 0.1)));
|
||||
button.disabled = !textarea.value.trim() || left < 0;
|
||||
};
|
||||
|
||||
const saveData = () => writeStorage(storageKey, JSON.stringify(pageData));
|
||||
const createPost = (rawText) => {
|
||||
const user = pageData.site.currentUser;
|
||||
const item = {
|
||||
id: "user-" + Date.now(),
|
||||
author: user.name,
|
||||
handle: user.handle,
|
||||
initial: user.initial,
|
||||
colors: clone(user.colors || []),
|
||||
verified: false,
|
||||
time: "刚刚",
|
||||
text: rawText,
|
||||
tags: [],
|
||||
metrics: { replies: 0, reposts: 0, likes: 0, views: 0 }
|
||||
};
|
||||
pageData.posts.items.unshift(item);
|
||||
saveData();
|
||||
renderPosts();
|
||||
qs(".post").scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
showToast("动态已发布");
|
||||
};
|
||||
|
||||
const composerText = qs("#composerText");
|
||||
const publishButton = qs("#publishButton");
|
||||
composerText.addEventListener("focus", () => qs("#replyPermission").classList.add("visible"));
|
||||
composerText.addEventListener("input", () => updateCounter(composerText, qs("#charCounter"), publishButton));
|
||||
publishButton.addEventListener("click", () => {
|
||||
const value = composerText.value.trim();
|
||||
if (!value) return;
|
||||
createPost(value);
|
||||
composerText.value = "";
|
||||
qs("#replyPermission").classList.remove("visible");
|
||||
updateCounter(composerText, qs("#charCounter"), publishButton);
|
||||
});
|
||||
qs("#searchInput").addEventListener("input", applySearch);
|
||||
qs("#timelineStatus").addEventListener("click", () => qs("#timelineStatus").classList.remove("show"));
|
||||
|
||||
const composeModal = qs("#composeModal");
|
||||
const modalText = qs("#modalText");
|
||||
const modalPublish = qs("#modalPublish");
|
||||
let modalOpener = null;
|
||||
const openCompose = (event) => {
|
||||
modalOpener = event.currentTarget;
|
||||
composeModal.classList.add("open");
|
||||
composeModal.setAttribute("aria-hidden", "false");
|
||||
document.body.classList.add("modal-open");
|
||||
window.setTimeout(() => modalText.focus(), 40);
|
||||
};
|
||||
const closeCompose = () => {
|
||||
composeModal.classList.remove("open");
|
||||
composeModal.setAttribute("aria-hidden", "true");
|
||||
document.body.classList.remove("modal-open");
|
||||
if (modalOpener) modalOpener.focus();
|
||||
};
|
||||
qsa("[data-open-modal]").forEach((button) => button.addEventListener("click", openCompose));
|
||||
qs("#closeModal").addEventListener("click", closeCompose);
|
||||
composeModal.addEventListener("click", (event) => {
|
||||
if (event.target === composeModal) closeCompose();
|
||||
});
|
||||
modalText.addEventListener("input", () => updateCounter(modalText, qs("#modalCounter"), modalPublish));
|
||||
modalPublish.addEventListener("click", () => {
|
||||
const value = modalText.value.trim();
|
||||
if (!value) return;
|
||||
createPost(value);
|
||||
modalText.value = "";
|
||||
updateCounter(modalText, qs("#modalCounter"), modalPublish);
|
||||
closeCompose();
|
||||
});
|
||||
|
||||
const desktopTheme = qs("#themeToggle");
|
||||
const mobileTheme = qs("#mobileTheme");
|
||||
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";
|
||||
desktopTheme.textContent = dark ? "切换浅色模式" : "切换深色模式";
|
||||
mobileTheme.innerHTML = icon(dark ? "i-sun" : "i-moon");
|
||||
qs('meta[name="theme-color"]').content = dark ? "#000000" : "#ffffff";
|
||||
};
|
||||
const toggleTheme = () => {
|
||||
const next = document.documentElement.dataset.theme === "dark" ? "light" : "dark";
|
||||
document.documentElement.dataset.theme = next;
|
||||
writeStorage(themeKey, next);
|
||||
syncTheme();
|
||||
};
|
||||
desktopTheme.addEventListener("click", toggleTheme);
|
||||
mobileTheme.addEventListener("click", toggleTheme);
|
||||
|
||||
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 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 loadEditor = () => {
|
||||
qs("#editorModuleTitle").textContent = MODULE_META[activeModule][0];
|
||||
jsonEditor.value = JSON.stringify(editorDrafts[activeModule], null, 2);
|
||||
setEditorStatus(true, "JSON 有效");
|
||||
};
|
||||
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 = "x-page-data.json";
|
||||
link.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(link.href), 1000);
|
||||
});
|
||||
|
||||
document.addEventListener("click", (event) => {
|
||||
if (!event.target.closest(".post-menu") && !event.target.closest(".more")) {
|
||||
qsa(".post-menu.open").forEach((menu) => menu.classList.remove("open"));
|
||||
}
|
||||
const link = event.target.closest('a[href^="#"]');
|
||||
if (link && !qs(link.getAttribute("href"))) {
|
||||
event.preventDefault();
|
||||
showToast("此页面正在准备中");
|
||||
}
|
||||
});
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Escape") return;
|
||||
qsa(".post-menu.open").forEach((menu) => menu.classList.remove("open"));
|
||||
if (settingsModal.classList.contains("open")) closeSettings();
|
||||
else if (composeModal.classList.contains("open")) closeCompose();
|
||||
});
|
||||
|
||||
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();
|
||||
})();
|
||||
+453
@@ -0,0 +1,453 @@
|
||||
<!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="X 风格的可编辑中文社交时间线。" />
|
||||
<title>X · 正在发生</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--bg: #fff;
|
||||
--surface: #fff;
|
||||
--surface-hover: #f7f8f8;
|
||||
--soft: #eff3f4;
|
||||
--text: #0f1419;
|
||||
--muted: #536471;
|
||||
--border: #eff3f4;
|
||||
--border-strong: #cfd9de;
|
||||
--accent: #1d9bf0;
|
||||
--accent-hover: #1a8cd8;
|
||||
--accent-soft: #e8f5fd;
|
||||
--danger: #f91880;
|
||||
--success: #00ba7c;
|
||||
--focus: 0 0 0 3px rgba(29, 155, 240, .28);
|
||||
--nav-w: 258px;
|
||||
--feed-w: 600px;
|
||||
--aside-w: 350px;
|
||||
}
|
||||
[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--bg: #000;
|
||||
--surface: #000;
|
||||
--surface-hover: #080808;
|
||||
--soft: #16181c;
|
||||
--text: #e7e9ea;
|
||||
--muted: #71767b;
|
||||
--border: #2f3336;
|
||||
--border-strong: #536471;
|
||||
--accent-soft: #031b2b;
|
||||
--focus: 0 0 0 3px rgba(29, 155, 240, .34);
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html { scroll-behavior: smooth; }
|
||||
body {
|
||||
margin: 0; min-width: 320px; background: var(--bg); color: var(--text);
|
||||
font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
font-size: 16px; line-height: 1.45;
|
||||
}
|
||||
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; padding: 0; margin: -1px; 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: 999px; color: #fff; background: var(--accent); transform: translateY(-160%); text-decoration: none; }
|
||||
.skip-link:focus { transform: translateY(0); }
|
||||
|
||||
.app { width: min(1265px, 100%); min-height: 100dvh; margin: 0 auto; display: grid; grid-template-columns: var(--nav-w) var(--feed-w) var(--aside-w); gap: 28px; }
|
||||
.left-rail { position: relative; }
|
||||
.left-fixed { position: fixed; top: var(--df-generated-header-height, 0px); width: var(--nav-w); height: calc(100dvh - var(--df-generated-header-height, 0px)); padding: 8px 18px 12px 4px; display: flex; flex-direction: column; }
|
||||
.brand { width: 52px; height: 52px; display: grid; place-items: center; border-radius: 50%; color: var(--text); text-decoration: none; transition: background .18s; }
|
||||
.brand:hover { background: var(--soft); }
|
||||
.brand svg { width: 30px; height: 30px; }
|
||||
.primary-nav { display: grid; gap: 4px; margin-top: 5px; }
|
||||
.nav-item { width: fit-content; min-height: 50px; padding: 0 17px 0 12px; border-radius: 999px; display: flex; align-items: center; gap: 19px; color: var(--text); text-decoration: none; font-size: 20px; transition: background .18s; }
|
||||
.nav-item:hover { background: var(--soft); }
|
||||
.nav-item.active { font-weight: 750; }
|
||||
.nav-item svg { width: 26px; height: 26px; }
|
||||
.nav-item.active svg { fill: currentColor; }
|
||||
.nav-badge { min-width: 18px; height: 18px; margin-left: -26px; margin-top: -25px; padding: 0 5px; display: grid; place-items: center; border: 2px solid var(--bg); border-radius: 9px; color: #fff; background: var(--accent); font-size: 10px; font-weight: 800; }
|
||||
.post-cta { width: 218px; height: 52px; margin-top: 14px; border: 0; border-radius: 999px; color: #fff; background: var(--accent); font-size: 17px; font-weight: 750; box-shadow: 0 8px 18px rgba(29,155,240,.18); transition: background .18s, transform .18s; }
|
||||
.post-cta:hover { background: var(--accent-hover); transform: translateY(-1px); }
|
||||
.account-switcher { min-height: 64px; margin-top: auto; padding: 9px 10px; border: 0; border-radius: 999px; display: flex; align-items: center; gap: 10px; background: transparent; text-align: left; transition: background .18s; }
|
||||
.account-switcher:hover { background: var(--soft); }
|
||||
.account-copy { min-width: 0; flex: 1; }
|
||||
.account-copy strong, .account-copy span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.account-copy span { color: var(--muted); font-size: 14px; }
|
||||
.account-switcher > svg { width: 19px; height: 19px; }
|
||||
|
||||
.avatar { --a: #4f46e5; --b: #a855f7; width: 42px; height: 42px; flex: 0 0 auto; border-radius: 50%; display: grid; place-items: center; color: #fff; background: linear-gradient(145deg, var(--a), var(--b)); font-weight: 800; box-shadow: inset 0 0 0 1px rgba(255,255,255,.2); }
|
||||
.avatar-sm { width: 38px; height: 38px; font-size: 13px; }
|
||||
.avatar-lg { width: 48px; height: 48px; }
|
||||
|
||||
.feed { min-width: 0; border-inline: 1px solid var(--border); }
|
||||
.feed-header { position: sticky; z-index: 30; top: var(--df-generated-header-height, 0px); background: color-mix(in srgb, var(--surface) 88%, transparent); backdrop-filter: blur(14px); border-bottom: 1px solid var(--border); }
|
||||
.mobile-title { display: none; height: 52px; padding: 0 16px; align-items: center; justify-content: space-between; }
|
||||
.mobile-title .brand { width: 42px; height: 42px; }
|
||||
.tabs { height: 53px; display: grid; grid-template-columns: 1fr 1fr; }
|
||||
.tab { position: relative; border: 0; background: transparent; color: var(--muted); font-size: 15px; font-weight: 550; transition: background .18s; }
|
||||
.tab:hover { background: color-mix(in srgb, var(--soft) 70%, transparent); }
|
||||
.tab.active { color: var(--text); font-weight: 750; }
|
||||
.tab.active::after { content: ""; position: absolute; left: 50%; bottom: 0; width: 58px; height: 4px; border-radius: 2px; background: var(--accent); transform: translateX(-50%); }
|
||||
|
||||
.composer { padding: 12px 16px 8px; display: grid; grid-template-columns: 48px 1fr; gap: 12px; border-bottom: 1px solid var(--border); }
|
||||
.composer-main { min-width: 0; }
|
||||
.audience-button { min-height: 44px; margin-bottom: 3px; padding: 1px 11px; border: 1px solid var(--border-strong); border-radius: 999px; color: var(--accent); background: transparent; font-size: 13px; font-weight: 750; }
|
||||
.composer textarea { width: 100%; min-height: 74px; max-height: 220px; padding: 8px 0; resize: vertical; border: 0; outline: 0; color: var(--text); background: transparent; font-size: 20px; line-height: 1.45; }
|
||||
.composer textarea::placeholder { color: var(--muted); }
|
||||
.reply-permission { display: none; width: fit-content; align-items: center; gap: 6px; min-height: 28px; margin: 0 0 8px; color: var(--accent); font-size: 13px; font-weight: 650; }
|
||||
.reply-permission.visible { display: flex; }
|
||||
.reply-permission svg { width: 14px; height: 14px; }
|
||||
.composer-footer { min-height: 42px; padding-top: 8px; border-top: 1px solid transparent; display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.composer-tools { display: flex; align-items: center; gap: 1px; }
|
||||
.tool-button { width: 44px; height: 44px; border: 0; border-radius: 50%; display: grid; place-items: center; color: var(--accent); background: transparent; transition: background .18s; }
|
||||
.tool-button:hover { background: var(--accent-soft); }
|
||||
.tool-button svg { width: 19px; height: 19px; }
|
||||
.composer-submit { display: flex; align-items: center; gap: 10px; }
|
||||
.char-counter { width: 26px; height: 26px; display: grid; place-items: center; border: 2px solid var(--border-strong); border-radius: 50%; color: var(--muted); font-size: 10px; font-variant-numeric: tabular-nums; }
|
||||
.char-counter.warn { color: #f4212e; border-color: #f4212e; }
|
||||
.send-button { min-width: 74px; height: 44px; padding: 0 17px; border: 0; border-radius: 999px; color: #fff; background: var(--accent); font-weight: 750; transition: opacity .18s, background .18s; }
|
||||
.send-button:hover:not(:disabled) { background: var(--accent-hover); }
|
||||
.send-button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
|
||||
.timeline-status { display: none; min-height: 48px; border-bottom: 1px solid var(--border); color: var(--accent); background: var(--surface); font-size: 14px; font-weight: 600; text-align: center; }
|
||||
.timeline-status.show { display: grid; place-items: center; }
|
||||
.post { position: relative; display: grid; grid-template-columns: 48px 1fr; gap: 10px; padding: 12px 16px 5px; border-bottom: 1px solid var(--border); transition: background .15s; }
|
||||
.post:hover { background: var(--surface-hover); }
|
||||
.post-main { min-width: 0; }
|
||||
.post-head { min-width: 0; display: flex; align-items: center; gap: 4px; line-height: 1.25; }
|
||||
.post-head strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.verified { width: 16px; height: 16px; flex: 0 0 auto; color: var(--accent); }
|
||||
.handle, .dot, time { color: var(--muted); font-size: 15px; white-space: nowrap; }
|
||||
.more { width: 44px; height: 44px; margin: -12px -8px -12px auto; flex: 0 0 auto; border: 0; border-radius: 50%; display: grid; place-items: center; color: var(--muted); background: transparent; transition: color .18s, background .18s; }
|
||||
.more:hover { color: var(--accent); background: var(--accent-soft); }
|
||||
.more svg { width: 18px; height: 18px; }
|
||||
.post-text { margin: 2px 0 10px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.post-text a { color: var(--accent); text-decoration: none; }
|
||||
.post-text a:hover { text-decoration: underline; }
|
||||
.context-label { margin: -4px 0 8px; color: var(--muted); font-size: 13px; }
|
||||
.post-source { margin: 2px 0 8px; font-size: 12px; line-height: 1.45; }
|
||||
.post-source a { color: var(--accent); font-weight: 700; text-decoration: none; }
|
||||
.post-media { position: relative; width: 100%; aspect-ratio: 16/10; overflow: hidden; border: 1px solid var(--border-strong); border-radius: 16px; background: var(--soft); }
|
||||
.post-media svg { width: 100%; height: 100%; }
|
||||
.media-caption { position: absolute; right: 10px; bottom: 10px; padding: 5px 8px; border-radius: 6px; color: #fff; background: rgba(0,0,0,.68); font-size: 11px; }
|
||||
.quote-post { margin: 8px 0 5px; padding: 12px; border: 1px solid var(--border-strong); border-radius: 16px; }
|
||||
.quote-post:hover { background: color-mix(in srgb, var(--soft) 45%, transparent); }
|
||||
.quote-author { display: flex; align-items: center; gap: 6px; font-size: 14px; }
|
||||
.quote-post p { margin: 7px 0 0; font-size: 15px; }
|
||||
.post-actions { max-width: 440px; height: 44px; margin-top: 5px; display: flex; justify-content: space-between; align-items: center; }
|
||||
.action { min-width: 48px; height: 44px; padding: 0; border: 0; border-radius: 999px; display: flex; align-items: center; gap: 5px; color: var(--muted); background: transparent; font-size: 12px; transition: color .18s; }
|
||||
.action-icon { width: 40px; height: 40px; display: grid; place-items: center; border-radius: 50%; transition: background .18s; }
|
||||
.action svg { width: 18px; height: 18px; }
|
||||
.action:hover { color: var(--accent); }
|
||||
.action:hover .action-icon { background: var(--accent-soft); }
|
||||
.action.repost:hover, .action.reposted { color: var(--success); }
|
||||
.action.repost:hover .action-icon { background: color-mix(in srgb, var(--success) 12%, transparent); }
|
||||
.action.like:hover, .action.liked { color: var(--danger); }
|
||||
.action.like:hover .action-icon { background: color-mix(in srgb, var(--danger) 12%, transparent); }
|
||||
.action.liked svg, .action.bookmarked svg { fill: currentColor; }
|
||||
.bookmark-action { min-width: 44px; }
|
||||
.post-menu { position: absolute; z-index: 20; top: 40px; right: 12px; width: 220px; padding: 7px; border: 1px solid var(--border); border-radius: 14px; background: var(--surface); box-shadow: 0 10px 32px rgba(0,0,0,.16); display: none; }
|
||||
.post-menu.open { display: block; }
|
||||
.post-menu button { width: 100%; min-height: 42px; padding: 0 12px; border: 0; border-radius: 8px; display: flex; align-items: center; gap: 10px; background: transparent; text-align: left; }
|
||||
.post-menu button:hover { background: var(--soft); }
|
||||
.post-menu svg { width: 18px; height: 18px; }
|
||||
.reply-section { display: none; grid-column: 2; padding: 7px 0 9px; }
|
||||
.reply-section.open { display: block; }
|
||||
.reply-tools { min-height: 38px; margin-bottom: 6px; display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.reply-tools[hidden] { display: none; }
|
||||
.reply-summary { font-size: 14px; }
|
||||
.reply-tools > div { display: flex; gap: 4px; }
|
||||
.reply-sort { padding: 6px 10px; border: 0; border-radius: 999px; color: var(--muted); background: transparent; font-weight: 700; }
|
||||
.reply-sort:hover, .reply-sort.active { color: var(--accent); background: var(--accent-soft); }
|
||||
.reply-list { display: grid; gap: 0; margin-bottom: 8px; }
|
||||
.reply-item { padding: 10px 0; display: flex; align-items: flex-start; gap: 10px; border-top: 1px solid var(--border); }
|
||||
.reply-content { min-width: 0; flex: 1; }
|
||||
.reply-content header { min-height: 20px; display: flex; align-items: center; gap: 4px; color: var(--muted); font-size: 13px; }
|
||||
.reply-content header strong { overflow: hidden; color: var(--text); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.reply-content header svg { width: 15px; height: 15px; flex: 0 0 auto; }
|
||||
.reply-content p { margin: 3px 0 0; font-size: 14px; line-height: 1.45; white-space: pre-wrap; }
|
||||
.reply-meta { min-height: 24px; margin-top: 3px; display: flex; align-items: center; gap: 12px; color: var(--muted); font-size: 12px; }
|
||||
.reply-meta button { padding: 0; border: 0; color: inherit; background: transparent; font-weight: 700; }
|
||||
.reply-meta button:hover { color: var(--accent); }
|
||||
.reply-pagination { margin: 0 0 9px 50px; display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.reply-pagination button { min-height: 34px; padding: 0 13px; border: 1px solid var(--border-strong); border-radius: 999px; color: var(--accent); background: var(--surface); font-weight: 700; }
|
||||
.reply-pagination button:hover { background: var(--accent-soft); }
|
||||
.reply-pagination button[hidden] { display: none; }
|
||||
.reply-form { display: flex; gap: 8px; }
|
||||
.reply-form input { flex: 1; min-width: 0; height: 44px; padding: 0 14px; border: 1px solid var(--border-strong); border-radius: 999px; color: var(--text); background: var(--surface); font-size: 16px; }
|
||||
.reply-send { width: 44px; height: 44px; border: 0; border-radius: 50%; display: grid; place-items: center; color: #fff; background: var(--accent); }
|
||||
.reply-send svg { width: 18px; height: 18px; }
|
||||
.empty-state { display: none; padding: 48px 24px; border-bottom: 1px solid var(--border); text-align: center; }
|
||||
.empty-state svg { width: 38px; height: 38px; margin: 0 auto 12px; color: var(--muted); }
|
||||
.empty-state h2 { margin: 0 0 5px; font-size: 24px; }
|
||||
.empty-state p { margin: 0; color: var(--muted); }
|
||||
|
||||
.right-rail { min-width: 0; }
|
||||
.right-fixed { position: sticky; top: var(--df-generated-header-height, 0px); max-height: calc(100dvh - var(--df-generated-header-height, 0px)); padding-top: 5px; overflow-y: auto; scrollbar-width: none; }
|
||||
.right-fixed::-webkit-scrollbar { display: none; }
|
||||
.search-box { position: sticky; z-index: 20; top: 0; padding: 0 0 10px; background: var(--bg); }
|
||||
.search-label { position: relative; display: block; }
|
||||
.search-label svg { position: absolute; left: 17px; top: 50%; width: 18px; height: 18px; color: var(--muted); transform: translateY(-50%); }
|
||||
.search-input { width: 100%; height: 44px; padding: 0 16px 0 47px; border: 1px solid transparent; border-radius: 999px; color: var(--text); background: var(--soft); outline: 0; font-size: 16px; }
|
||||
.search-input:focus { border-color: var(--accent); background: var(--surface); }
|
||||
.side-card { margin: 7px 0 16px; overflow: hidden; border-radius: 16px; background: var(--soft); }
|
||||
.side-card h2 { margin: 0; padding: 12px 16px 6px; font-size: 20px; line-height: 1.25; }
|
||||
.trend { min-height: 76px; padding: 10px 16px; display: block; color: inherit; text-decoration: none; transition: background .15s; }
|
||||
.trend:hover { background: color-mix(in srgb, var(--muted) 8%, transparent); }
|
||||
.trend-head { display: flex; justify-content: space-between; color: var(--muted); font-size: 12px; }
|
||||
.trend-head svg { width: 16px; height: 16px; }
|
||||
.trend strong { display: block; margin: 2px 0; font-size: 15px; }
|
||||
.trend small { color: var(--muted); }
|
||||
.show-more { display: block; min-height: 48px; padding: 14px 16px; color: var(--accent); text-decoration: none; font-size: 14px; }
|
||||
.show-more:hover { background: color-mix(in srgb, var(--muted) 8%, transparent); }
|
||||
.follow-row { min-height: 66px; padding: 10px 16px; display: flex; align-items: center; gap: 10px; }
|
||||
.follow-row:hover { background: color-mix(in srgb, var(--muted) 8%, transparent); }
|
||||
.follow-copy { min-width: 0; flex: 1; }
|
||||
.follow-copy strong, .follow-copy span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.follow-copy span { color: var(--muted); font-size: 14px; }
|
||||
.follow-button { min-width: 72px; height: 44px; padding: 0 15px; border: 1px solid var(--text); border-radius: 999px; color: var(--bg); background: var(--text); font-size: 14px; font-weight: 750; }
|
||||
.follow-button.following { color: var(--text); background: transparent; }
|
||||
.right-footer { padding: 0 13px 24px; color: var(--muted); font-size: 12px; line-height: 1.7; }
|
||||
.right-footer a { margin-right: 8px; color: inherit; text-decoration: none; }
|
||||
.right-footer a:hover { text-decoration: underline; }
|
||||
|
||||
.mobile-nav { display: none; }
|
||||
.floating-compose { display: none; }
|
||||
.modal-backdrop { position: fixed; z-index: 100; inset: 0; padding: 20px; display: grid; place-items: start center; background: rgba(91,112,131,.42); opacity: 0; visibility: hidden; transition: opacity .18s, visibility .18s; }
|
||||
.modal-backdrop.open { opacity: 1; visibility: visible; }
|
||||
.compose-modal { width: min(600px, 100%); min-height: 270px; margin-top: 5vh; padding: 10px 16px 16px; border-radius: 16px; background: var(--surface); box-shadow: 0 20px 70px rgba(0,0,0,.22); transform: translateY(-8px); transition: transform .2s; }
|
||||
.modal-backdrop.open .compose-modal { transform: translateY(0); }
|
||||
.modal-top { min-height: 44px; display: flex; align-items: center; justify-content: space-between; }
|
||||
.close-button { width: 44px; height: 44px; border: 0; border-radius: 50%; display: grid; place-items: center; background: transparent; }
|
||||
.close-button:hover { background: var(--soft); }
|
||||
.close-button svg { width: 20px; height: 20px; }
|
||||
.drafts { border: 0; padding: 10px; color: var(--accent); background: transparent; font-weight: 700; }
|
||||
.modal-compose-row { display: grid; grid-template-columns: 48px 1fr; gap: 12px; padding-top: 8px; }
|
||||
.modal-textarea { width: 100%; min-height: 115px; padding: 7px 0; resize: none; border: 0; outline: 0; color: var(--text); background: transparent; font-size: 20px; line-height: 1.5; }
|
||||
.modal-footer { margin-left: 60px; padding-top: 10px; border-top: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; }
|
||||
.toast { position: fixed; z-index: 200; left: 50%; bottom: 25px; padding: 10px 17px; border-radius: 6px; color: #fff; background: var(--accent); box-shadow: 0 8px 28px rgba(0,0,0,.22); 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); }
|
||||
|
||||
@media (max-width: 1120px) {
|
||||
:root { --nav-w: 78px; --aside-w: 330px; }
|
||||
.app { width: min(1040px, 100%); gap: 18px; }
|
||||
.left-fixed { width: var(--nav-w); padding-right: 8px; align-items: center; }
|
||||
.nav-item { width: 52px; padding: 0; justify-content: center; }
|
||||
.nav-item span, .account-copy, .account-switcher > svg { display: none; }
|
||||
.post-cta { width: 52px; height: 52px; font-size: 0; }
|
||||
.post-cta::after { content: "+"; font-size: 28px; font-weight: 400; }
|
||||
.account-switcher { padding: 6px; }
|
||||
}
|
||||
@media (max-width: 960px) {
|
||||
:root { --feed-w: min(600px, calc(100vw - 100px)); }
|
||||
.app { grid-template-columns: var(--nav-w) var(--feed-w); width: fit-content; gap: 0; }
|
||||
.right-rail { display: none; }
|
||||
}
|
||||
@media (max-width: 680px) {
|
||||
body { padding-bottom: calc(58px + env(safe-area-inset-bottom)); }
|
||||
.app { display: block; width: 100%; }
|
||||
.left-rail { display: none; }
|
||||
.feed { width: 100%; border-inline: 0; }
|
||||
.mobile-title { display: flex; }
|
||||
.mobile-title strong { font-size: 18px; }
|
||||
.desktop-composer { display: none; }
|
||||
.post { padding-inline: 12px; }
|
||||
.post-head { flex-wrap: nowrap; }
|
||||
.handle { max-width: 95px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.mobile-nav { position: fixed; z-index: 60; inset: auto 0 0; height: calc(58px + env(safe-area-inset-bottom)); padding: 3px 10px max(3px, env(safe-area-inset-bottom)); display: grid; grid-template-columns: repeat(5,1fr); border-top: 1px solid var(--border); background: color-mix(in srgb, var(--surface) 94%, transparent); backdrop-filter: blur(15px); }
|
||||
.mobile-nav button { min-height: 50px; border: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 1px; color: var(--muted); background: transparent; font-size: 10px; }
|
||||
.mobile-nav button.active { color: var(--text); }
|
||||
.mobile-nav svg { width: 22px; height: 22px; }
|
||||
.floating-compose { position: fixed; z-index: 55; right: 18px; bottom: calc(76px + env(safe-area-inset-bottom)); width: 54px; height: 54px; border: 0; border-radius: 50%; display: grid; place-items: center; color: #fff; background: var(--accent); box-shadow: 0 8px 24px rgba(29,155,240,.36); }
|
||||
.floating-compose svg { width: 23px; height: 23px; }
|
||||
.compose-modal { min-height: 100dvh; margin: 0; border-radius: 0; }
|
||||
.modal-backdrop { padding: 0; }
|
||||
.post-actions { max-width: none; }
|
||||
.action { min-width: 40px; }
|
||||
.action-count { font-size: 11px; }
|
||||
}
|
||||
@media (max-width: 410px) {
|
||||
.post { grid-template-columns: 42px 1fr; gap: 8px; }
|
||||
.avatar-lg { width: 42px; height: 42px; }
|
||||
.post-head { gap: 3px; }
|
||||
.handle { max-width: 72px; }
|
||||
.post-text { font-size: 15px; }
|
||||
.action.views { display: none; }
|
||||
.modal-footer { margin-left: 54px; }
|
||||
}
|
||||
|
||||
.settings-trigger { position: fixed; z-index: 90; top: calc(var(--df-generated-header-height, 0px) + 16px); right: 18px; width: 46px; height: 46px; border: 1px solid var(--border-strong); border-radius: 50%; display: grid; place-items: center; color: var(--text); background: color-mix(in srgb, var(--surface) 90%, transparent); box-shadow: 0 8px 24px rgba(15,20,25,.14); backdrop-filter: blur(12px); transition: transform .18s, background .18s; }
|
||||
.settings-trigger:hover { background: var(--soft); transform: rotate(12deg); }
|
||||
.settings-trigger svg { width: 21px; height: 21px; }
|
||||
.settings-backdrop { position: fixed; z-index: 300; inset: 0; padding: 28px; display: grid; place-items: center; background: rgba(15,20,25,.72); opacity: 0; visibility: hidden; transition: opacity .18s, visibility .18s; }
|
||||
.settings-backdrop.open { opacity: 1; visibility: visible; }
|
||||
.settings-panel { width: min(1180px, 100%); height: min(780px, calc(100dvh - 56px)); overflow: hidden; display: grid; grid-template-rows: auto minmax(0,1fr) auto; border: 1px solid #536471; border-radius: 18px; color: #e7e9ea; background: #000; box-shadow: 0 32px 100px rgba(0,0,0,.54); }
|
||||
.settings-head { min-height: 82px; padding: 18px 22px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #2f3336; }
|
||||
.settings-kicker { color: #1d9bf0; font-size: 12px; font-weight: 800; letter-spacing: .12em; text-transform: uppercase; }
|
||||
.settings-head h2 { margin: 2px 0 0; font-size: 26px; }
|
||||
.settings-close { width: 44px; height: 44px; border: 1px solid #536471; border-radius: 12px; display: grid; place-items: center; color: #e7e9ea; background: #0f1419; }
|
||||
.settings-close:hover { background: #16181c; }
|
||||
.settings-close svg { width: 22px; height: 22px; }
|
||||
.settings-body { min-height: 0; display: grid; grid-template-columns: 250px minmax(0,1fr); }
|
||||
.module-tabs { min-height: 0; padding: 18px; overflow-y: auto; border-right: 1px solid #2f3336; background: #080808; }
|
||||
.module-tabs h3 { margin: 0 0 12px; color: #71767b; font-size: 13px; font-weight: 650; }
|
||||
.module-tab { width: 100%; min-height: 54px; margin-bottom: 8px; padding: 8px 12px; border: 1px solid transparent; border-radius: 12px; display: flex; align-items: center; justify-content: space-between; gap: 10px; color: #e7e9ea; background: transparent; text-align: left; }
|
||||
.module-tab:hover { background: #16181c; }
|
||||
.module-tab.active { border-color: #1d9bf0; color: #fff; background: #031b2b; }
|
||||
.module-tab small { color: #71767b; font-size: 11px; }
|
||||
.editor-pane { min-width: 0; min-height: 0; padding: 18px 20px 16px; display: grid; grid-template-rows: auto minmax(0,1fr) auto; gap: 10px; }
|
||||
.editor-title { display: flex; align-items: end; justify-content: space-between; gap: 16px; }
|
||||
.editor-title strong { font-size: 17px; }
|
||||
.editor-title span { color: #71767b; font-size: 13px; }
|
||||
.json-editor { width: 100%; min-height: 0; padding: 16px; resize: none; border: 1px solid #2f3336; border-radius: 12px; outline: 0; color: #d6f1ff; background: #05090d; font: 14px/1.62 ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", monospace; tab-size: 2; }
|
||||
.json-editor:focus { border-color: #1d9bf0; box-shadow: 0 0 0 3px rgba(29,155,240,.18); }
|
||||
.editor-hint { display: flex; align-items: center; justify-content: space-between; gap: 12px; color: #71767b; font-size: 12px; }
|
||||
.json-status { font-weight: 750; }
|
||||
.json-status.valid { color: #00ba7c; }
|
||||
.json-status.invalid { color: #f4212e; }
|
||||
.settings-actions { min-height: 76px; padding: 14px 20px; display: flex; align-items: center; justify-content: space-between; gap: 12px; border-top: 1px solid #2f3336; }
|
||||
.action-group { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.settings-button { min-height: 44px; padding: 0 17px; border: 1px solid #536471; border-radius: 999px; color: #e7e9ea; background: transparent; font-weight: 700; }
|
||||
.settings-button:hover { background: #16181c; }
|
||||
.settings-button.primary { border-color: #1d9bf0; color: #fff; background: #1d9bf0; }
|
||||
.settings-button.primary:hover { background: #1a8cd8; }
|
||||
.settings-button.danger { color: #f4212e; }
|
||||
@media (max-width: 760px) {
|
||||
.settings-trigger { top: calc(var(--df-generated-header-height, 0px) + 7px); right: 60px; width: 40px; height: 40px; }
|
||||
.settings-backdrop { padding: 0; }
|
||||
.settings-panel { width: 100%; height: 100dvh; border: 0; border-radius: 0; }
|
||||
.settings-head { min-height: 68px; padding: 12px 14px; }
|
||||
.settings-head h2 { font-size: 21px; }
|
||||
.settings-body { grid-template-columns: 1fr; grid-template-rows: auto minmax(0,1fr); }
|
||||
.module-tabs { padding: 10px 12px 2px; display: flex; gap: 8px; overflow-x: auto; border-right: 0; border-bottom: 1px solid #2f3336; }
|
||||
.module-tabs h3 { display: none; }
|
||||
.module-tab { width: auto; min-width: max-content; min-height: 40px; margin: 0 0 8px; padding: 6px 10px; }
|
||||
.module-tab small { display: none; }
|
||||
.editor-pane { padding: 12px; }
|
||||
.settings-actions { min-height: 70px; padding: 10px 12px; }
|
||||
.settings-button { min-height: 42px; padding: 0 13px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { scroll-behavior: auto !important; 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); }
|
||||
.modal-backdrop { z-index: 1200; }
|
||||
.settings-backdrop { z-index: 1300; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<a href="#mainFeed" class="skip-link">跳到时间线</a>
|
||||
<svg aria-hidden="true" width="0" height="0" style="position:absolute">
|
||||
<symbol id="i-x-brand" viewBox="0 0 24 24"><path d="M4.2 3h4.9l4.1 5.5L18 3h2l-5.9 6.9L21 21h-4.9l-4.5-6-5.2 6h-2l6.3-7.4L4.2 3Zm4 1.7 8.8 14.6h2.1L10.3 4.7H8.2Z" fill="currentColor"/></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>
|
||||
<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-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-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-message" viewBox="0 0 24 24"><path d="M4 5h16v12H8l-4 4Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-users" viewBox="0 0 24 24"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm13 10v-2a4 4 0 0 0-3-3.87" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
|
||||
<symbol id="i-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-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-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-image" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="8.5" cy="9" r="1.5" fill="currentColor"/><path d="m4 17 5-5 4 4 2-2 5 4" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-gif" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><path d="M8.5 10H7a2 2 0 0 0 0 4h2v-2H7.7m4.3-2v4m3-4h3m-3 4v-4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-poll" viewBox="0 0 24 24"><path d="M5 20V10m7 10V4m7 16v-7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
|
||||
<symbol id="i-smile" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M8 14s1.5 2 4 2 4-2 4-2M9 9h.01M15 9h.01" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
|
||||
<symbol id="i-calendar" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><path d="M16 3v4M8 3v4M3 11h18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
|
||||
<symbol id="i-globe" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" fill="none" stroke="currentColor" stroke-width="1.5"/></symbol>
|
||||
<symbol id="i-comment" viewBox="0 0 24 24"><path d="M21 12a8.5 8.5 0 0 1-9 8.5 9 9 0 0 1-3.7-.8L4 21l1.2-3.8A8.5 8.5 0 1 1 21 12Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-repost" viewBox="0 0 24 24"><path d="m17 3 4 4-4 4M3 7h18M7 21l-4-4 4-4m14 4H3" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-heart" viewBox="0 0 24 24"><path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1.1-1.1a5.5 5.5 0 0 0-7.8 7.8l1.1 1.1L12 21l7.8-7.5 1.1-1.1a5.5 5.5 0 0 0-.1-7.8Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-chart" viewBox="0 0 24 24"><path d="M4 20V10m5 10V4m6 16v-7m5 7V7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
|
||||
<symbol id="i-share" viewBox="0 0 24 24"><path d="M12 16V3m0 0L7 8m5-5 5 5M5 13v7h14v-7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-verified" viewBox="0 0 24 24"><path d="m12 2 2.2 2.1 3-.4.9 2.9 2.7 1.4-1.3 2.8 1.3 2.8-2.7 1.4-.9 2.9-3-.4L12 22l-2.2-2.1-3 .4-.9-2.9L3.2 16l1.3-2.8-1.3-2.8L5.9 9l.9-2.9 3 .4Z" fill="currentColor"/><path d="m8.5 12 2.2 2.2 4.8-5" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-pen" viewBox="0 0 24 24"><path d="m4 20 4.5-1 10.8-10.8a2.1 2.1 0 0 0-3-3L5.5 16Zm9.8-12.3 3 3M13 20h7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
|
||||
<symbol id="i-close" viewBox="0 0 24 24"><path d="m6 6 12 12M18 6 6 18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
|
||||
<symbol id="i-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-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-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-volume-off" viewBox="0 0 24 24"><path d="M11 5 6 9H2v6h4l5 4Zm4 5 6 6m0-6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
|
||||
</svg>
|
||||
|
||||
<div class="app">
|
||||
<aside class="left-rail" aria-label="主导航">
|
||||
<div class="left-fixed">
|
||||
<a class="brand" id="brandLink" href="#mainFeed" aria-label="X 首页"><svg><use href="#i-x-brand"/></svg></a>
|
||||
<nav class="primary-nav" id="primaryNav"></nav>
|
||||
<button class="post-cta" id="postCta" data-open-modal>发布</button>
|
||||
<button class="account-switcher" id="accountSwitcher" aria-label="账户菜单"></button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main class="feed" id="mainFeed">
|
||||
<h1 class="sr-only" id="timelineHeading">X 首页时间线</h1>
|
||||
<header class="feed-header">
|
||||
<div class="mobile-title"><span id="mobileUser"></span><strong id="mobileTitle">首页</strong><button class="tool-button" id="mobileTheme" aria-label="切换主题"><svg><use href="#i-moon"/></svg></button></div>
|
||||
<div class="tabs" id="feedTabs" role="tablist"></div>
|
||||
</header>
|
||||
|
||||
<section class="composer desktop-composer" aria-label="发布动态">
|
||||
<span id="composerAvatar"></span>
|
||||
<div class="composer-main">
|
||||
<button class="audience-button" id="composerAudience">所有人</button>
|
||||
<label class="sr-only" for="composerText">动态内容</label>
|
||||
<textarea id="composerText" maxlength="280" placeholder="有什么新鲜事?"></textarea>
|
||||
<div class="reply-permission" id="replyPermission"><svg><use href="#i-globe"/></svg><span></span></div>
|
||||
<div class="composer-footer">
|
||||
<div class="composer-tools"><button class="tool-button" aria-label="添加图片"><svg><use href="#i-image"/></svg></button><button class="tool-button" aria-label="添加 GIF"><svg><use href="#i-gif"/></svg></button><button class="tool-button" aria-label="添加投票"><svg><use href="#i-poll"/></svg></button><button class="tool-button" aria-label="添加表情"><svg><use href="#i-smile"/></svg></button><button class="tool-button" aria-label="定时发布"><svg><use href="#i-calendar"/></svg></button></div>
|
||||
<div class="composer-submit"><span class="char-counter" id="charCounter">280</span><button class="send-button" id="publishButton" disabled>发布</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<button class="timeline-status" id="timelineStatus">已切换时间线</button>
|
||||
<section id="posts" aria-label="动态列表"></section>
|
||||
<section class="empty-state" id="emptyState"><svg><use href="#i-search"/></svg><h2>没有找到结果</h2><p>换一个关键词,看看正在发生的其他事情。</p></section>
|
||||
</main>
|
||||
|
||||
<aside class="right-rail" aria-label="趋势与推荐">
|
||||
<div class="right-fixed">
|
||||
<div class="search-box"><label class="search-label"><span class="sr-only">搜索动态</span><svg><use href="#i-search"/></svg><input id="searchInput" class="search-input" type="search" placeholder="搜索" autocomplete="off" /></label></div>
|
||||
<section class="side-card" id="trendsCard"></section>
|
||||
<section class="side-card" id="recommendationsCard"></section>
|
||||
<button class="follow-button following" id="themeToggle" style="margin:0 12px 18px;min-width:112px">切换深色模式</button>
|
||||
<footer class="right-footer" id="rightFooter"></footer>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<nav class="mobile-nav" id="mobileNav" aria-label="移动端导航"></nav>
|
||||
<button class="floating-compose" data-open-modal aria-label="发布动态"><svg><use href="#i-pen"/></svg></button>
|
||||
|
||||
<div class="modal-backdrop" id="composeModal" aria-hidden="true">
|
||||
<section class="compose-modal" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
|
||||
<div class="modal-top"><button class="close-button" id="closeModal" aria-label="关闭发布窗口"><svg><use href="#i-close"/></svg></button><strong id="modalTitle" class="sr-only">发布动态</strong><button class="drafts" id="draftsLabel">草稿</button></div>
|
||||
<div class="modal-compose-row"><span id="modalAvatar"></span><div><button class="audience-button" id="modalAudience">所有人</button><label class="sr-only" for="modalText">动态内容</label><textarea id="modalText" class="modal-textarea" maxlength="280" placeholder="有什么新鲜事?"></textarea><div class="reply-permission visible"><svg><use href="#i-globe"/></svg><span id="modalReplyPermission"></span></div></div></div>
|
||||
<div class="modal-footer"><div class="composer-tools"><button class="tool-button" aria-label="添加图片"><svg><use href="#i-image"/></svg></button><button class="tool-button" aria-label="添加 GIF"><svg><use href="#i-gif"/></svg></button><button class="tool-button" aria-label="添加投票"><svg><use href="#i-poll"/></svg></button><button class="tool-button" aria-label="添加表情"><svg><use href="#i-smile"/></svg></button></div><div class="composer-submit"><span class="char-counter" id="modalCounter">280</span><button class="send-button" id="modalPublish" disabled>发布</button></div></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">X 页面控制台</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="xPageData">__X_PAGE_DATA__</script>
|
||||
<script>__X_PAGE_RUNTIME__</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
# X 页面 JSON 契约
|
||||
|
||||
源文件必须是 JSON 对象,并包含以下六个顶层模块。字段可增加,但不能删除顶层模块。
|
||||
|
||||
## `site`
|
||||
|
||||
- `brand`、`pageTitle`、`description`、`timelineTitle`、`searchPlaceholder`:字符串。
|
||||
- `tabs`:1–4 个时间线标签字符串。
|
||||
- `currentUser`:当前账号,包含 `name`、`handle`、`initial`、`colors`(两个 `#RRGGBB`)。
|
||||
|
||||
## `navigation`
|
||||
|
||||
- `primary`:左侧导航,项目为 `{label, icon, href}`,可选非负 `badge`。
|
||||
- `postLabel`:发布按钮文案。
|
||||
- `mobile`:移动端导航 `{label, icon}`,最多 8 项。
|
||||
- `footerLinks`:页脚链接 `{label, href}`;`copyright` 为版权文字。
|
||||
- `href` 只使用页面内锚点,例如 `#mainFeed`、`#explore`。
|
||||
|
||||
可用图标:`i-home`、`i-search`、`i-bell`、`i-message`、`i-users`、`i-bookmark`、`i-user`、`i-more`。
|
||||
|
||||
## `composer`
|
||||
|
||||
- `audience`、`placeholder`、`replyPermission`、`draftsLabel`:字符串。
|
||||
- `maxLength`:1–1000 的整数;模板同时用于桌面发布框和弹窗发布框。
|
||||
|
||||
## `posts`
|
||||
|
||||
- `items`:1–30 条,`id` 必须唯一。
|
||||
- 可选 `replyUI` 控制预置回复区:
|
||||
- `defaultSort`:`hot`(按点赞数、子回复数降序)或 `latest`(保持 JSON 顺序,约定最新在前)。
|
||||
- `initialVisible`、`pageSize`:1–100 的整数;建议均为 `10`。
|
||||
- `hotLabel`、`latestLabel`、`showMoreLabel`、`showAllLabel`:界面中文文案。
|
||||
- 核心字段:`id`、`author`、`handle`、`initial`、`colors`、`verified`、`time`、`text`、`tags`。
|
||||
- `metrics`:`{replies, reposts, likes, views}`,均为非负数字。
|
||||
- 可选 `repliesExpanded`:布尔值;需要直接展示热评详情时设为 `true`。
|
||||
- 可选 `replies`:0–100 条预置回复。每项至少包含 `author`、`text`,建议完整填写:
|
||||
- `id`(同一动态内唯一)、`author`、`handle`、`initial`、`colors`、`verified`、`time`、`text`。
|
||||
- `likes`、`replyCount`:非负数字,用于热门排序与互动摘要。
|
||||
- 当预置 50 条热评时,数组必须实际包含 50 个对象,且 `metrics.replies >= 50`;不能用一条摘要冒充 50 条评论。
|
||||
- 可选 `sourceUrl`:已核验原帖的 `http(s)` 链接。不再生成或展示 `disclosure`;旧 JSON 中的该字段会被兼容忽略。
|
||||
- 可选 `media`:
|
||||
- `{ "type": "skyline", "caption": "...", "alt": "..." }`
|
||||
- `{ "type": "map", "caption": "...", "alt": "..." }`
|
||||
- `{ "type": "quote", "author": "...", "handle": "...", "initial": "...", "colors": ["#...", "#..."], "time": "...", "text": "..." }`
|
||||
- 图片:`{ "type": "image", "mediaUrl": "https://.../image.jpg", "alt": "图片说明", "pageUrl": "https://..." }`。
|
||||
- 视频:`{ "type": "video", "mediaUrl": "https://.../video.mp4", "posterUrl": "https://.../cover.jpg", "alt": "视频说明", "pageUrl": "https://..." }`。
|
||||
- 网页:`{ "type": "webpage", "pageUrl": "https://...", "title": "网页标题", "description": "网页摘要", "mediaUrl": "https://.../cover.jpg", "embed": false }`。目标站点不允许 iframe 时用 `embed: false`,页面仍提供新窗口链接。
|
||||
|
||||
媒体地址只接受 `http(s)`;图片和视频的 `mediaUrl` 也可使用对应的 `data:` URL。运行时会过滤其他协议。
|
||||
|
||||
### 单帖 + 热评模式
|
||||
|
||||
用户要求“某账号发布一条动态,配图,下方 N 条热评”时,`posts.items` 只放这一条动态;将图片写入该动态的 `media`,将 N 条评论逐条写入 `replies`,并设置 `repliesExpanded: true`。页面默认先显示 `replyUI.initialVisible` 条,可切换热门/最新、分批查看更多或查看全部。
|
||||
|
||||
## `trends`
|
||||
|
||||
- `title`、`showMoreLabel`:字符串。
|
||||
- `items`:0–20 项,每项 `{category, title, count, href}`。
|
||||
|
||||
## `recommendations`
|
||||
|
||||
- `title`、`showMoreLabel`:字符串。
|
||||
- `items`:0–20 项,每项 `{name, handle, initial, colors}`。
|
||||
|
||||
## 示例边界
|
||||
|
||||
- `assets/default-data.json` 只提供结构,不是事实来源。
|
||||
- 合成热评不得写成真实用户原话,也不在帖文内添加情景模拟说明条。
|
||||
- 所有颜色使用完整六位十六进制;无效颜色由模板回退。
|
||||
- JSON 使用双引号,不允许注释、Markdown 围栏或尾逗号。
|
||||
|
||||
+376
@@ -0,0 +1,376 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate a complete single-post X page in one deterministic call."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
|
||||
import render_x_page as renderer
|
||||
|
||||
REPLY_NAMES = (
|
||||
"林夏",
|
||||
"周野",
|
||||
"陈默",
|
||||
"顾念",
|
||||
"沈言",
|
||||
"宋可心",
|
||||
"许知夏",
|
||||
"苏小鹿",
|
||||
"唐梨",
|
||||
"陆川",
|
||||
"乔安",
|
||||
"白露",
|
||||
"温言",
|
||||
"江禾",
|
||||
"叶青",
|
||||
"程澄",
|
||||
"余舟",
|
||||
"夏满",
|
||||
"何川",
|
||||
"简宁",
|
||||
"顾南",
|
||||
"闻溪",
|
||||
"林深",
|
||||
"周晴",
|
||||
"陈一",
|
||||
)
|
||||
REPLY_COLORS = (
|
||||
("#5662f6", "#9f45d8"),
|
||||
("#15a88b", "#2e88cc"),
|
||||
("#f97316", "#db2777"),
|
||||
("#0f7d78", "#51b35e"),
|
||||
("#8b5cf6", "#3b82f6"),
|
||||
("#f59e0b", "#ef4444"),
|
||||
("#0ea5e9", "#10b981"),
|
||||
("#6366f1", "#ec4899"),
|
||||
)
|
||||
REPLY_TEMPLATES = (
|
||||
"这条内容把“{topic}”讲得很清楚。",
|
||||
"图片和文字放在一起,信息一下就完整了。",
|
||||
"这个角度很有意思,我会继续关注后续。",
|
||||
"最打动我的是内容里的细节,而不是结论本身。",
|
||||
"看完之后,我对“{topic}”多了一层理解。",
|
||||
"表达很克制,但重点都说到了。",
|
||||
"这张图和正文的呼应做得很好。",
|
||||
"我更关心接下来会有哪些具体变化。",
|
||||
"信息量不少,但读起来并不费力。",
|
||||
"这件事值得从不同立场继续讨论。",
|
||||
"正文里提到的关键点,我也有同感。",
|
||||
"先收藏,等有更多资料时再回来看看。",
|
||||
"比起口号,我更喜欢这种具体的表达。",
|
||||
"“{topic}”确实是这条内容最值得讨论的部分。",
|
||||
"希望后续能补充更多背景和时间线。",
|
||||
"这个内容让我想起了之前看到的一些讨论。",
|
||||
"观点很鲜明,也留下了继续思考的空间。",
|
||||
"如果有更多数据支持,会更有说服力。",
|
||||
"我赞同其中一部分,也想听听不同意见。",
|
||||
"这条动态的节奏和重点都很舒服。",
|
||||
"从普通人的视角看,这个话题很有现实感。",
|
||||
"细节比标题更值得反复看。",
|
||||
"希望评论区能保持理性,认真聊聊“{topic}”。",
|
||||
"内容不长,但已经把核心问题交代清楚了。",
|
||||
"期待作者继续更新这个系列。",
|
||||
)
|
||||
REPLY_PREFIXES = ("", "换个角度看,", "补充一点,", "我更关注的是,")
|
||||
|
||||
|
||||
def _require_chinese(value: str, path: str) -> None:
|
||||
if not any("\u3400" <= char <= "\u9fff" for char in value):
|
||||
raise renderer.DataValidationError(f"{path} must contain Simplified Chinese reader-visible text")
|
||||
|
||||
|
||||
def _replies(
|
||||
count: int,
|
||||
topics: list[str],
|
||||
custom_replies: list[object] | None = None,
|
||||
) -> list[dict[str, object]]:
|
||||
custom_replies = custom_replies or []
|
||||
result: list[dict[str, object]] = []
|
||||
for index in range(count):
|
||||
name = REPLY_NAMES[index % len(REPLY_NAMES)]
|
||||
cycle = index // len(REPLY_NAMES)
|
||||
if cycle:
|
||||
name = f"{name}{cycle + 1}"
|
||||
template = REPLY_TEMPLATES[index % len(REPLY_TEMPLATES)]
|
||||
prefix = REPLY_PREFIXES[(index // len(REPLY_TEMPLATES)) % len(REPLY_PREFIXES)]
|
||||
colors = REPLY_COLORS[index % len(REPLY_COLORS)]
|
||||
topic = topics[index % len(topics)]
|
||||
generated_text = prefix + template.format(topic=topic)
|
||||
if "{topic}" not in template:
|
||||
generated_text = f"关于“{topic}”,{generated_text}"
|
||||
reply: dict[str, object] = {
|
||||
"id": f"reply-{index + 1:03d}",
|
||||
"author": name,
|
||||
"handle": f"@reply_{index + 1:03d}",
|
||||
"initial": name[:1],
|
||||
"colors": list(colors),
|
||||
"verified": False,
|
||||
"time": f"{index + 1} 分钟",
|
||||
"text": generated_text,
|
||||
"likes": max(0, (count - index) * 7),
|
||||
"replyCount": index % 5,
|
||||
}
|
||||
if index < len(custom_replies):
|
||||
custom = custom_replies[index]
|
||||
if isinstance(custom, str):
|
||||
if not custom.strip():
|
||||
raise renderer.DataValidationError(f"replies[{index}] must not be empty")
|
||||
reply["text"] = custom.strip()
|
||||
elif isinstance(custom, Mapping):
|
||||
text = custom.get("text")
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
raise renderer.DataValidationError(f"replies[{index}].text must be a non-empty string")
|
||||
reply["text"] = text.strip()
|
||||
for key in (
|
||||
"author",
|
||||
"handle",
|
||||
"initial",
|
||||
"time",
|
||||
"likes",
|
||||
"replyCount",
|
||||
"verified",
|
||||
"colors",
|
||||
):
|
||||
if key in custom:
|
||||
reply[key] = custom[key]
|
||||
else:
|
||||
raise renderer.DataValidationError(f"replies[{index}] must be a string or object")
|
||||
_require_chinese(str(reply["text"]), f"replies[{index}].text")
|
||||
result.append(reply)
|
||||
return result
|
||||
|
||||
|
||||
def _read_spec(path: Path) -> dict[str, object]:
|
||||
try:
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError as exc:
|
||||
raise renderer.DataValidationError(f"Invalid spec JSON: {exc}") from exc
|
||||
if not isinstance(value, dict):
|
||||
raise renderer.DataValidationError("Spec JSON must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _string(value: object, path: str, *, required: bool = False) -> str:
|
||||
if value is None and not required:
|
||||
return ""
|
||||
if not isinstance(value, str) or (required and not value.strip()):
|
||||
suffix = "a non-empty string" if required else "a string"
|
||||
raise renderer.DataValidationError(f"{path} must be {suffix}")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _integer(value: object, path: str, *, default: int = 0) -> int:
|
||||
if value is None:
|
||||
return default
|
||||
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
|
||||
raise renderer.DataValidationError(f"{path} must be a non-negative integer")
|
||||
return value
|
||||
|
||||
|
||||
def _strings(value: object, path: str) -> list[str]:
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list) or not all(isinstance(item, str) and item.strip() for item in value):
|
||||
raise renderer.DataValidationError(f"{path} must be an array of non-empty strings")
|
||||
return [item.strip() for item in value]
|
||||
|
||||
|
||||
def _namespace_from_spec(cli_args: argparse.Namespace) -> argparse.Namespace:
|
||||
spec = _read_spec(cli_args.spec)
|
||||
replies = spec.get("replies", [])
|
||||
if not isinstance(replies, list):
|
||||
raise renderer.DataValidationError("replies must be an array")
|
||||
display_count = _integer(
|
||||
spec.get("displayReplyCount"),
|
||||
"displayReplyCount",
|
||||
default=len(replies),
|
||||
)
|
||||
if len(replies) > display_count:
|
||||
raise renderer.DataValidationError("displayReplyCount cannot be smaller than replies.length")
|
||||
total_count = _integer(
|
||||
spec.get("totalReplyCount"),
|
||||
"totalReplyCount",
|
||||
default=display_count,
|
||||
)
|
||||
if total_count < display_count:
|
||||
raise renderer.DataValidationError("totalReplyCount cannot be smaller than displayReplyCount")
|
||||
media = spec.get("media") or {}
|
||||
if not isinstance(media, dict):
|
||||
raise renderer.DataValidationError("media must be an object")
|
||||
verified = spec.get("verified", False)
|
||||
if not isinstance(verified, bool):
|
||||
raise renderer.DataValidationError("verified must be a boolean")
|
||||
media_type = media.get("type", "image")
|
||||
if media_type not in {"image", "video"}:
|
||||
raise renderer.DataValidationError("media.type must be image or video")
|
||||
topic = _string(spec.get("topic"), "topic")
|
||||
reply_topics = _strings(spec.get("replyTopics"), "replyTopics")
|
||||
if not reply_topics:
|
||||
reply_topics = [topic or "这条动态"]
|
||||
return argparse.Namespace(
|
||||
output_dir=cli_args.output_dir,
|
||||
author=_string(spec.get("author"), "author", required=True),
|
||||
handle=_string(spec.get("handle"), "handle", required=True),
|
||||
text=_string(spec.get("text"), "text", required=True),
|
||||
topic=topic,
|
||||
initial=_string(spec.get("initial"), "initial"),
|
||||
time=_string(spec.get("time"), "time") or "刚刚",
|
||||
page_title=_string(spec.get("pageTitle"), "pageTitle"),
|
||||
timeline_title=_string(spec.get("timelineTitle"), "timelineTitle") or "首页",
|
||||
tag=_strings(spec.get("tags"), "tags"),
|
||||
reply_count=display_count,
|
||||
total_reply_count=total_count,
|
||||
reply_topic=reply_topics,
|
||||
reply=replies,
|
||||
likes=_integer(spec.get("likes"), "likes"),
|
||||
reposts=_integer(spec.get("reposts"), "reposts"),
|
||||
views=_integer(spec.get("views"), "views"),
|
||||
verified=verified,
|
||||
media_type=media_type,
|
||||
media_url=_string(media.get("url"), "media.url"),
|
||||
media_alt=_string(media.get("alt"), "media.alt"),
|
||||
page_url=_string(media.get("pageUrl"), "media.pageUrl"),
|
||||
source_url=_string(spec.get("sourceUrl"), "sourceUrl"),
|
||||
)
|
||||
|
||||
|
||||
def _validate_cli_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
for key in ("author", "handle", "text"):
|
||||
if not getattr(args, key):
|
||||
raise renderer.DataValidationError(f"--{key.replace('_', '-')} is required unless --spec is used")
|
||||
if args.total_reply_count is None:
|
||||
args.total_reply_count = args.reply_count
|
||||
if args.total_reply_count < args.reply_count:
|
||||
raise renderer.DataValidationError("total-reply-count cannot be smaller than reply-count")
|
||||
if not args.reply_topic:
|
||||
args.reply_topic = [args.topic or args.text[:24] or "这条动态"]
|
||||
return args
|
||||
|
||||
|
||||
def _next_paths(output_dir: Path) -> tuple[Path, Path]:
|
||||
for index in range(1, 1001):
|
||||
stem = "x-page" if index == 1 else f"x-page-{index}"
|
||||
data_path = output_dir / f"{stem}-data.json"
|
||||
html_path = output_dir / f"{stem}.html"
|
||||
if not data_path.exists() and not html_path.exists():
|
||||
return data_path, html_path
|
||||
raise renderer.DataValidationError("Unable to allocate output filenames")
|
||||
|
||||
|
||||
def build_document(args: argparse.Namespace) -> dict[str, object]:
|
||||
if not 0 <= args.reply_count <= renderer.REPLY_LIMIT:
|
||||
raise renderer.DataValidationError(f"reply-count must be between 0 and {renderer.REPLY_LIMIT}")
|
||||
_require_chinese(args.text, "text")
|
||||
data = renderer._read_json(renderer.DEFAULT_DATA_PATH)
|
||||
topic = (args.topic or args.text[:24] or "这条动态").strip()
|
||||
initial = (args.initial or args.author[:1] or "发").strip()[:2]
|
||||
post: dict[str, object] = {
|
||||
"id": "single-post",
|
||||
"author": args.author,
|
||||
"handle": args.handle,
|
||||
"initial": initial,
|
||||
"colors": ["#f97316", "#ec4899"],
|
||||
"verified": args.verified,
|
||||
"time": args.time,
|
||||
"text": args.text,
|
||||
"tags": args.tag,
|
||||
"metrics": {
|
||||
"replies": args.total_reply_count,
|
||||
"reposts": args.reposts,
|
||||
"likes": args.likes,
|
||||
"views": args.views,
|
||||
},
|
||||
"repliesExpanded": args.reply_count > 0,
|
||||
"replies": _replies(args.reply_count, args.reply_topic, args.reply),
|
||||
}
|
||||
if args.media_url:
|
||||
media: dict[str, object] = {
|
||||
"type": args.media_type,
|
||||
"mediaUrl": args.media_url,
|
||||
"alt": args.media_alt or f"{topic}相关媒体",
|
||||
}
|
||||
if args.page_url:
|
||||
media["pageUrl"] = args.page_url
|
||||
post["media"] = media
|
||||
else:
|
||||
post["media"] = {
|
||||
"type": "skyline",
|
||||
"caption": topic,
|
||||
"alt": f"{topic}的模板示例图",
|
||||
}
|
||||
if args.source_url:
|
||||
post["sourceUrl"] = args.source_url
|
||||
|
||||
data["site"]["pageTitle"] = args.page_title or f"X · {args.author}"
|
||||
data["site"]["timelineTitle"] = args.timeline_title
|
||||
data["posts"]["items"] = [post]
|
||||
data["posts"]["replyUI"]["initialVisible"] = min(10, args.reply_count) or 1
|
||||
data["posts"]["replyUI"]["pageSize"] = min(10, args.reply_count) or 1
|
||||
return data
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output-dir", type=Path, required=True)
|
||||
parser.add_argument("--spec", type=Path)
|
||||
parser.add_argument("--author")
|
||||
parser.add_argument("--handle")
|
||||
parser.add_argument("--text")
|
||||
parser.add_argument("--topic", default="")
|
||||
parser.add_argument("--initial", default="")
|
||||
parser.add_argument("--time", default="刚刚")
|
||||
parser.add_argument("--page-title", default="")
|
||||
parser.add_argument("--timeline-title", default="首页")
|
||||
parser.add_argument("--tag", action="append", default=[])
|
||||
parser.add_argument("--reply-count", type=int, default=0)
|
||||
parser.add_argument("--total-reply-count", type=int)
|
||||
parser.add_argument("--reply-topic", action="append", default=[])
|
||||
parser.add_argument("--reply", action="append", default=[])
|
||||
parser.add_argument("--likes", type=int, default=0)
|
||||
parser.add_argument("--reposts", type=int, default=0)
|
||||
parser.add_argument("--views", type=int, default=0)
|
||||
parser.add_argument("--verified", action="store_true")
|
||||
parser.add_argument("--media-type", choices=("image", "video"), default="image")
|
||||
parser.add_argument("--media-url", default="")
|
||||
parser.add_argument("--media-alt", default="")
|
||||
parser.add_argument("--page-url", default="")
|
||||
parser.add_argument("--source-url", default="")
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
cli_args = _build_parser().parse_args(argv)
|
||||
try:
|
||||
args = _namespace_from_spec(cli_args) if cli_args.spec else _validate_cli_args(cli_args)
|
||||
data = build_document(args)
|
||||
summary = renderer.validate_document(data)
|
||||
template = renderer.TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||
runtime = renderer.RUNTIME_PATH.read_text(encoding="utf-8")
|
||||
rendered = renderer.render_document(data, template, runtime)
|
||||
data_path, html_path = _next_paths(args.output_dir)
|
||||
renderer._write_new(
|
||||
data_path,
|
||||
json.dumps(data, ensure_ascii=False, indent=2) + "\n",
|
||||
)
|
||||
renderer._write_new(html_path, rendered)
|
||||
except (renderer.DataValidationError, OSError, UnicodeError) as exc:
|
||||
renderer._emit({"status": "error", "action": "fast-single-post", "error": str(exc)})
|
||||
return 2
|
||||
renderer._emit(
|
||||
{
|
||||
"status": "ok",
|
||||
"action": "fast-single-post",
|
||||
"data": str(data_path),
|
||||
"html": str(html_path),
|
||||
**summary,
|
||||
}
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+478
@@ -0,0 +1,478 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate X page data and inject it into the bundled self-contained 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 / "x-template.html"
|
||||
RUNTIME_PATH = ASSETS_DIR / "x-runtime.js"
|
||||
DATA_MARKER = "__X_PAGE_DATA__"
|
||||
RUNTIME_MARKER = "__X_PAGE_RUNTIME__"
|
||||
TITLE_RE = re.compile(r"<title>[^<]*</title>", re.IGNORECASE)
|
||||
MODULES = ("site", "navigation", "composer", "posts", "trends", "recommendations")
|
||||
MEDIA_TYPES = {"skyline", "map", "quote", "image", "video", "webpage"}
|
||||
REMOTE_MEDIA_TYPES = {"image", "video", "webpage"}
|
||||
REPLY_LIMIT = 100
|
||||
|
||||
|
||||
class DataValidationError(ValueError):
|
||||
"""Raised when the X 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(media: dict[str, Any], path: str, errors: list[str]) -> None:
|
||||
media_type = media.get("type")
|
||||
if media_type not in 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 _colors(value: Any, path: str, errors: list[str]) -> None:
|
||||
if value is not None and (
|
||||
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 _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 _positive_int(
|
||||
value: Any,
|
||||
path: str,
|
||||
errors: list[str],
|
||||
*,
|
||||
maximum: int = REPLY_LIMIT,
|
||||
) -> None:
|
||||
if (
|
||||
not isinstance(value, int)
|
||||
or isinstance(value, bool)
|
||||
or not 1 <= value <= maximum
|
||||
):
|
||||
errors.append(f"{path} must be an integer between 1 and {maximum}")
|
||||
|
||||
|
||||
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)
|
||||
_non_empty_string(person.get("name"), f"{path}[{index}].name", errors)
|
||||
_non_empty_string(person.get("handle"), f"{path}[{index}].handle", errors)
|
||||
_non_empty_string(person.get("initial"), f"{path}[{index}].initial", 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", "timelineTitle"):
|
||||
_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)
|
||||
|
||||
navigation = _mapping(data.get("navigation"), "navigation", errors)
|
||||
for key, limit in (("primary", 12), ("mobile", 8), ("footerLinks", 12)):
|
||||
items = _array(navigation.get(key), f"navigation.{key}", errors, limit=limit)
|
||||
for index, item in enumerate(items):
|
||||
nav_item = _mapping(item, f"navigation.{key}[{index}]", errors)
|
||||
_non_empty_string(
|
||||
nav_item.get("label"),
|
||||
f"navigation.{key}[{index}].label",
|
||||
errors,
|
||||
)
|
||||
_non_empty_string(navigation.get("postLabel"), "navigation.postLabel", errors)
|
||||
|
||||
composer = _mapping(data.get("composer"), "composer", errors)
|
||||
for key in ("audience", "placeholder", "replyPermission", "draftsLabel"):
|
||||
_non_empty_string(composer.get(key), f"composer.{key}", errors)
|
||||
max_length = composer.get("maxLength")
|
||||
if (
|
||||
not isinstance(max_length, int)
|
||||
or isinstance(max_length, bool)
|
||||
or not 1 <= max_length <= 1000
|
||||
):
|
||||
errors.append("composer.maxLength must be an integer between 1 and 1000")
|
||||
|
||||
posts = _mapping(data.get("posts"), "posts", errors)
|
||||
reply_ui_value = posts.get("replyUI")
|
||||
if reply_ui_value is not None:
|
||||
reply_ui = _mapping(reply_ui_value, "posts.replyUI", errors)
|
||||
if reply_ui.get("defaultSort", "hot") not in {"hot", "latest"}:
|
||||
errors.append("posts.replyUI.defaultSort must be hot or latest")
|
||||
for key in ("initialVisible", "pageSize"):
|
||||
if key in reply_ui:
|
||||
_positive_int(reply_ui.get(key), f"posts.replyUI.{key}", errors)
|
||||
for key in (
|
||||
"hotLabel",
|
||||
"latestLabel",
|
||||
"showMoreLabel",
|
||||
"showAllLabel",
|
||||
):
|
||||
if key in reply_ui:
|
||||
_non_empty_string(reply_ui.get(key), f"posts.replyUI.{key}", errors)
|
||||
post_items = _array(posts.get("items"), "posts.items", errors, limit=30)
|
||||
if not post_items:
|
||||
errors.append("posts.items must contain at least one post")
|
||||
post_ids: set[str] = set()
|
||||
for index, item in enumerate(post_items):
|
||||
post = _mapping(item, f"posts.items[{index}]", errors)
|
||||
post_id = post.get("id")
|
||||
_non_empty_string(post_id, f"posts.items[{index}].id", errors)
|
||||
if isinstance(post_id, str):
|
||||
if post_id in post_ids:
|
||||
errors.append(f"posts.items[{index}].id must be unique")
|
||||
post_ids.add(post_id)
|
||||
for key in ("author", "handle", "initial", "time", "text"):
|
||||
_non_empty_string(post.get(key), f"posts.items[{index}].{key}", errors)
|
||||
_colors(post.get("colors"), f"posts.items[{index}].colors", errors)
|
||||
tags = _array(
|
||||
post.get("tags", []),
|
||||
f"posts.items[{index}].tags",
|
||||
errors,
|
||||
limit=8,
|
||||
)
|
||||
if not all(isinstance(tag, str) and tag.strip() for tag in tags):
|
||||
errors.append(f"posts.items[{index}].tags must contain non-empty strings")
|
||||
metrics = _mapping(
|
||||
post.get("metrics"),
|
||||
f"posts.items[{index}].metrics",
|
||||
errors,
|
||||
)
|
||||
for key in ("replies", "reposts", "likes", "views"):
|
||||
_non_negative_number(
|
||||
metrics.get(key),
|
||||
f"posts.items[{index}].metrics.{key}",
|
||||
errors,
|
||||
)
|
||||
replies = _array(
|
||||
post.get("replies", []),
|
||||
f"posts.items[{index}].replies",
|
||||
errors,
|
||||
limit=REPLY_LIMIT,
|
||||
)
|
||||
reply_ids: set[str] = set()
|
||||
for reply_index, reply_value in enumerate(replies):
|
||||
reply_path = f"posts.items[{index}].replies[{reply_index}]"
|
||||
reply = _mapping(reply_value, reply_path, errors)
|
||||
for key in ("author", "text"):
|
||||
_non_empty_string(reply.get(key), f"{reply_path}.{key}", errors)
|
||||
for key in ("id", "handle", "initial", "time"):
|
||||
if key in reply:
|
||||
_non_empty_string(reply.get(key), f"{reply_path}.{key}", errors)
|
||||
reply_id = reply.get("id")
|
||||
if isinstance(reply_id, str) and reply_id:
|
||||
if reply_id in reply_ids:
|
||||
errors.append(f"{reply_path}.id must be unique within its post")
|
||||
reply_ids.add(reply_id)
|
||||
_colors(reply.get("colors"), f"{reply_path}.colors", errors)
|
||||
if "verified" in reply and not isinstance(reply.get("verified"), bool):
|
||||
errors.append(f"{reply_path}.verified must be a boolean")
|
||||
for key in ("likes", "replyCount"):
|
||||
if key in reply:
|
||||
_non_negative_number(reply.get(key), f"{reply_path}.{key}", errors)
|
||||
if isinstance(metrics.get("replies"), (int, float)) and metrics.get("replies", 0) < len(replies):
|
||||
errors.append(
|
||||
f"posts.items[{index}].metrics.replies must be at least the number of preloaded replies"
|
||||
)
|
||||
if "repliesExpanded" in post and not isinstance(post.get("repliesExpanded"), bool):
|
||||
errors.append(f"posts.items[{index}].repliesExpanded must be a boolean")
|
||||
if "disclosure" in post:
|
||||
_non_empty_string(post.get("disclosure"), f"posts.items[{index}].disclosure", errors)
|
||||
if "sourceUrl" in post:
|
||||
_remote_url(post.get("sourceUrl"), f"posts.items[{index}].sourceUrl", errors, required=True)
|
||||
media = post.get("media")
|
||||
if media is not None:
|
||||
media_data = _mapping(
|
||||
media,
|
||||
f"posts.items[{index}].media",
|
||||
errors,
|
||||
)
|
||||
media_type = media_data.get("type")
|
||||
if media_type not in MEDIA_TYPES:
|
||||
errors.append(
|
||||
f"posts.items[{index}].media.type must be one of: "
|
||||
f"{', '.join(sorted(MEDIA_TYPES))}"
|
||||
)
|
||||
_validate_remote_media(media_data, f"posts.items[{index}].media", errors)
|
||||
if media_type == "quote":
|
||||
for key in ("author", "handle", "initial", "time", "text"):
|
||||
_non_empty_string(
|
||||
media_data.get(key),
|
||||
f"posts.items[{index}].media.{key}",
|
||||
errors,
|
||||
)
|
||||
_colors(
|
||||
media_data.get("colors"),
|
||||
f"posts.items[{index}].media.colors",
|
||||
errors,
|
||||
)
|
||||
|
||||
trends = _mapping(data.get("trends"), "trends", errors)
|
||||
_non_empty_string(trends.get("title"), "trends.title", errors)
|
||||
trend_items = _array(trends.get("items"), "trends.items", errors, limit=20)
|
||||
for index, item in enumerate(trend_items):
|
||||
trend = _mapping(item, f"trends.items[{index}]", errors)
|
||||
for key in ("category", "title", "count"):
|
||||
_non_empty_string(
|
||||
trend.get(key),
|
||||
f"trends.items[{index}].{key}",
|
||||
errors,
|
||||
)
|
||||
|
||||
recommendations = _mapping(
|
||||
data.get("recommendations"),
|
||||
"recommendations",
|
||||
errors,
|
||||
)
|
||||
_non_empty_string(
|
||||
recommendations.get("title"),
|
||||
"recommendations.title",
|
||||
errors,
|
||||
)
|
||||
recommendation_items = _array(
|
||||
recommendations.get("items"),
|
||||
"recommendations.items",
|
||||
errors,
|
||||
limit=20,
|
||||
)
|
||||
_validate_people(recommendation_items, "recommendations.items", errors)
|
||||
|
||||
if errors:
|
||||
raise DataValidationError("; ".join(errors))
|
||||
|
||||
return {
|
||||
"modules": list(MODULES),
|
||||
"counts": {
|
||||
"posts": len(post_items),
|
||||
"replies": sum(
|
||||
len(item.get("replies", []))
|
||||
for item in post_items
|
||||
if isinstance(item, dict) and isinstance(item.get("replies", []), list)
|
||||
),
|
||||
"trends": len(trend_items),
|
||||
"recommendations": len(recommendation_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