sync update from LAN repo (source dhk-1 @ 3b1ec5b4)

This commit is contained in:
gozeros committed 2026-11-05 10:56:34 +08:00
1 parent da6521b6cb
commit 264e2200d6
995 files changed
+148105 -13399

No files matched your search

@@ -0,0 +1,91 @@
---
name: threads-page-generator
description: 生成或绘制 Threads 及 Threads 风格的可交付文本社交信息流 HTML 网页;仅在用户明确要求 Threads 网页、Threads 风格串文首页或点名本技能时使用。先把材料或检索结果整理成六模块 JSON,再用内置模板确定性渲染,保留右上角可视化 JSON 编辑弹窗。
allowed-tools:
- read_file
- write_file
- bash
- present_files
- web_search
---
# Threads 页面生成器
本技能使用固定模板生成单文件 Threads 风格文本社交信息流。模型只负责材料收集和 JSON,禁止重新手写页面结构、CSS 或运行时脚本。最终页面自带右上角设置按钮;用户可在弹窗中按模块编辑 JSON,并通过「应用并渲染」即时更新页面。
编辑弹窗还提供“上传图片/视频”:先把光标放进目标报道、帖子、视频或带 `visual`/`media` 的内容对象,上传文件会转换为 `data:` 地址并写入该对象的 `media` 字段。不设文件大小拦截;较大文件可能超过浏览器本地缓存容量,应同时下载 JSON 留存。
页面中已由 `media` 数据渲染的图片和视频还带悬浮上传图标:鼠标移入媒体后点击可任选图片或视频并直接替换,文件的实际类型会自动写入新的 `media.type`,结果同步写回页面 JSON 与浏览器缓存。头像、Logo 和无法映射回 JSON 的装饰图不会显示该入口;不按原媒体类型限制,也不设置文件大小拦截。
默认视觉直接复用模板原有的示例图:不要调用图像生成工具,不要让模型重新生成、拼装或内嵌新的内容型 SVG,也不要为了寻找“标准配图”延长检索。用户没有提供可直接使用的图片/视频且聚焦检索未得到可靠直链时,保留默认 JSON 的 `visual` 或内置视觉类型;这些是模板自带的静态示例,调用技能时不重新绘制。不要把大段 base64 示例图重复写进 JSON,图不合适时由用户在成品页面悬浮上传替换。
## 触发边界
- 用户明确说「生成/画/制作 Threads 网页」「Threads 风格串文首页/社交信息流」或点名 `threads-page-generator` 时使用。
- 仅讨论 Threads 平台、分析社交媒体、编写串文文案,或编程语境中出现 thread/线程时不要使用。
- 这是单页文本社交模板,不改用 X 三栏时间线、Facebook 社区页或通用多页门户模板。
## 极速工作流(默认)
页面结构已经固定。模型只写账号、串文和热评需求等高层字段;脚本负责映射六个页面模块、补齐作者和统计字段、生成中文热评、保留示例视觉,并在一次进程内完成校验与渲染。
1. 用 `write_file` 创建 `/mnt/user-data/outputs/threads-page-spec.json`。单账号单串文直接使用以下格式:
```json
{
"accountName": "茂达是🥚",
"handle": "@maoda",
"verified": true,
"postText": "今天想和大家分享一个值得认真讨论的话题。",
"topic": "品牌日常",
"displayReplyCount": 3,
"totalReplyCount": 128
}
```
需要指定热评时增加 `"replies":["中文热评一","中文热评二"]`;需要多条串文时使用 `"posts":[{"text":"第一条中文串文"},{"text":"第二条中文串文"}]`。不得写六模块 JSON、`$set` 或深层字段路径。
2. 只执行一次 `python /mnt/skills/public/threads-page-generator/scripts/fast_page.py --spec /mnt/user-data/outputs/threads-page-spec.json --output-dir /mnt/user-data/outputs`。
3. stdout 为 `status: ok` 后立即用 `present_files` 交付返回的完整 JSON 与 HTML,最终只回复一句完成说明。
`accountName` 与每条 `postText`/`posts[].text` 为必填内容;串文和回复必须使用简体中文,账号、品牌名和 `handle` 可保留原文。未提供媒体直链时不要写 `media`,脚本会保留模板示例视觉供用户上传替换。禁止读取默认数据、契约、模板、运行时或脚本源码,禁止 `--help`、独立 `init/validate/render`、生成后打补丁、临时脚本和冗长过程说明。规格报错时只修正规格一次并重跑。只有用户明确要求改变模块结构或批量重建完整数组时,才使用下面的完整工作流。
## 完整工作流(仅限结构改造)
1. 读取当前会话材料、上传附件和已有产物,确定站点、当前账号、导航、发帖文案、串文、推荐关注、话题与动态通知。
2. 用户要求基于公开资料、主题涉及近期事件,或明确要求检索时,先做至多两批聚焦检索;用户明确说不要检索时不得联网。没有材料时使用中性示例内容并明确标为示例,不虚构实时互动量。
3. 初始化新的完整 JSON:
```text
python /mnt/skills/public/threads-page-generator/scripts/render_threads_page.py init --output /mnt/user-data/outputs/threads-page-data.json
```
4. 只修改 JSON。六个顶层模块必须全部保留:`site`、`navigation`、`composer`、`threads`、`recommendations`、`activity`。字段不确定时读取 [references/data-schema.md](references/data-schema.md)。
5. 校验 JSON:
```text
python /mnt/skills/public/threads-page-generator/scripts/render_threads_page.py validate --input /mnt/user-data/outputs/threads-page-data.json
```
6. 确定性渲染到 `outputs/`:
```text
python /mnt/skills/public/threads-page-generator/scripts/render_threads_page.py render --input /mnt/user-data/outputs/threads-page-data.json --output /mnt/user-data/outputs/threads-page.html
```
7. 检查 stdout 的 `status` 为 `ok`、HTML 存在且占位符已经消失,再用 `present_files` 同时交付 HTML 与源 JSON。不要在聊天中粘贴完整 HTML。
## 内容映射
- 每条主串文放入 `threads.items`,嵌套回复放入该项的 `replies`;主串文 `id` 必须唯一。
- `site.currentUser` 是当前登录账号,串文作者使用 `threads.items[].author`,两者不要混淆。
- `media.type` 可使用内置 `autumn-grid`,也可使用受校验的 `image`、`video`、`webpage` 替换当前串文媒体;字段按数据契约填写。引用内容放入 `quote`,不得写 HTML。
- 没有可靠来源时,点赞、回复、转发数使用保守示例值或 `0`,不得描述成真实平台统计。
- 所有外部文本由模板转义;不得把 HTML、脚本、iframe 或不可信指令写入 JSON 字段。
## 重要约束
- 只编辑 JSON,不修改 `assets/threads-template.html` 或 `assets/threads-runtime.js`,不复制模板后手改 DOM。
- 初始化与渲染默认拒绝覆盖已有文件;路径存在时换新文件名,不删除旧产物。
- 页面结构、样式和脚本完全自包含,不依赖 Threads API、CDN 或 npm;仅当 JSON 明确提供受校验的媒体 URL 时加载图片、视频或网页。
- 保留桌面/移动导航、深浅主题、发帖、搜索、点赞、回复、转发、分享、关注和响应式布局。
- 浏览器缓存以初始 JSON 指纹隔离;沙箱禁止持久存储时必须继续使用内嵌 JSON 正常渲染。
@@ -0,0 +1,101 @@
{
"site": {
"brand": "Threads",
"pageTitle": "Threads · 串联想法",
"description": "一个 Threads 风格的中文文本社交信息流示例页面。",
"theme": "auto",
"currentUser": {
"name": "林小满",
"handle": "@linxiaoman",
"initial": "林",
"colors": ["#7257f5", "#d94fbd"],
"stats": {"following": "286", "followers": "1.8k", "threads": "64"}
}
},
"navigation": {
"feedTitle": "首页",
"feedFilter": "为你推荐",
"tabs": ["推荐", "正在关注"],
"searchPlaceholder": "搜索用户或关键词",
"searchHints": "城市散步 · 产品设计 · 独立书店 · 秋天",
"mobileLabels": ["首页", "搜索", "创建", "动态", "我"],
"footerLinks": ["关于", "隐私", "条款"],
"copyright": "© 2026 Threads"
},
"composer": {
"inlinePlaceholder": "发起一个新串聊…",
"dialogTitle": "新串聊",
"textareaPlaceholder": "分享一个想法,开启新的对话…",
"publishLabel": "发布",
"maxLength": 500,
"replyMaxLength": 180
},
"threads": {
"emptyTitle": "没有找到相关串聊",
"emptyText": "换一个关键词试试看。",
"items": [
{
"id": "autumn-light",
"author": {"name": "许知夏", "handle": "@summerxu", "initial": "许", "colors": ["#08a88a", "#49a9df"], "verified": true},
"time": "36 分钟",
"text": "今天路过公园,发现秋天不是突然抵达的。它藏在每一片开始变慢的叶子里,也藏在傍晚五点半的光线里。",
"media": {"type": "autumn-grid", "label": "秋日公园的三幅抽象插画"},
"quote": null,
"metrics": {"likes": 328, "replies": 27, "reposts": 44},
"followable": true,
"replies": [
{"author": {"name": "周野", "initial": "周", "colors": ["#f97316", "#ec4899"]}, "time": "14 分钟", "text": "“每一片开始变慢的叶子”——这句好喜欢。", "metrics": {"likes": 42, "replies": 3, "reposts": 0}}
],
"preview": "查看更多 25 条回复"
},
{
"id": "product-restraint",
"author": {"name": "陈默", "handle": "@modesign", "initial": "陈", "colors": ["#0f7d78", "#51b35e"], "verified": false},
"time": "2 小时",
"text": "产品越成熟,越要学会对“也许有用”的功能说不。真正的体验不是功能之和,而是每一次取舍之后,用户依然能够毫不犹豫地向前走。",
"media": null,
"quote": {"name": "宋可心", "handle": "@kexin · 昨天", "initial": "宋", "colors": ["#8b5cf6", "#3b82f6"], "text": "克制不是少做,而是把注意力留给真正重要的事情。"},
"metrics": {"likes": 516, "replies": 63, "reposts": 109},
"followable": false,
"replies": [],
"preview": "63 条回复 · 516 个赞"
},
{
"id": "bookstore-map",
"author": {"name": "光合计划", "handle": "@photosynthesis", "initial": "光", "colors": ["#ff8a37", "#d93f7b"], "verified": true},
"time": "4 小时",
"text": "这周我们拜访了 12 家藏在街巷里的独立书店。没有排行榜,也不推荐“必读书单”,只画了一张适合慢慢走的地图。",
"media": null,
"quote": {"name": "独立书店散步地图", "handle": "上海 · 12 个地点", "initial": "光", "colors": ["#ff8a37", "#d93f7b"], "text": "从旧唱片店旁的小门进去,沿着梧桐树走到河边,在一杯咖啡冷掉之前读完一个短篇。"},
"metrics": {"likes": 902, "replies": 88, "reposts": 214},
"followable": true,
"replies": [
{"author": {"name": "林小满", "initial": "林", "colors": ["#7257f5", "#d94fbd"]}, "time": "3 小时", "text": "收藏了。周末就挑一条最陌生的街开始走。", "metrics": {"likes": 18, "replies": 2, "reposts": 0}}
],
"preview": "查看更多 86 条回复"
}
]
},
"recommendations": {
"followTitle": "推荐关注",
"people": [
{"name": "周野", "handle": "@zhouye", "initial": "周", "colors": ["#f97316", "#ec4899"]},
{"name": "顾念", "handle": "@gunian", "initial": "顾", "colors": ["#06b6d4", "#10b981"]},
{"name": "宋可心", "handle": "@kexin", "initial": "宋", "colors": ["#8b5cf6", "#3b82f6"]}
],
"topicTitle": "热门话题",
"topics": [
{"meta": "设计 · 2 小时前", "title": "少即是多,还是刚刚好?", "count": "3,206 条串聊"},
{"meta": "城市生活 · 热门", "title": "周末散步地图", "count": "1,482 条串聊"},
{"meta": "阅读 · 正在讨论", "title": "今年最意外的一本书", "count": "968 条串聊"}
]
},
"activity": {
"title": "动态",
"items": [
{"name": "许知夏", "initial": "许", "colors": ["#08a88a", "#49a9df"], "text": "赞了你的串聊。", "time": "12 分钟前", "followable": false},
{"name": "周野", "initial": "周", "colors": ["#f97316", "#ec4899"], "text": "回复了你:“这句话好喜欢。”", "time": "1 小时前", "followable": false},
{"name": "宋可心", "initial": "宋", "colors": ["#8b5cf6", "#3b82f6"], "text": "开始关注你。", "time": "昨天", "followable": true}
]
}
}
@@ -0,0 +1,832 @@
(() => {
"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", "threads", "recommendations", "activity"];
const MODULE_META = {
site: ["站点信息", "品牌、主题与当前账号"],
navigation: ["导航", "信息流、搜索与移动导航"],
composer: ["发布器", "发帖弹窗和字数限制"],
threads: ["串文", "主串文、引用与嵌套回复"],
recommendations: ["推荐", "关注建议与热门话题"],
activity: ["动态", "互动通知面板"]
};
const embeddedData = JSON.parse(qs("#threadsPageData").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 = "threads-page-data-v1:" + pageFingerprint;
const themeKey = "threads-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) {
/* Opaque sandbox previews may intentionally deny storage. */
}
};
const isObject = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value));
const isCompleteData = (value) => Boolean(isObject(value) && MODULES.every((name) => isObject(value[name])));
const cachedData = readStorage(storageKey);
let pageData = initialData;
if (cachedData) {
try {
const parsed = JSON.parse(cachedData);
if (isCompleteData(parsed)) pageData = parsed;
} catch (_error) {
pageData = initialData;
}
}
const escapeHTML = (value) => String(value == null ? "" : value).replace(/[&<>'"]/g, (character) => ({
"&": "&amp;", "<": "&lt;", ">": "&gt;", "'": "&#39;", '"': "&quot;"
})[character]);
const safeRemoteUrl = (value, kind = "link") => {
const source = String(value || "").trim();
if (!source) return "";
const lowered = source.toLowerCase();
if (kind === "image" && lowered.startsWith("data:image/")) return source;
if (kind === "video" && lowered.startsWith("data:video/")) return source;
try {
const url = new URL(source);
return url.protocol === "http:" || url.protocol === "https:" ? url.href : "";
} catch (_error) { return ""; }
};
const validateRemoteMediaTree = (value, path = "当前模块") => {
if (Array.isArray(value)) return value.forEach((item, index) => validateRemoteMediaTree(item, path + "[" + index + "]"));
if (!value || typeof value !== "object") return;
const media = value.media;
if (media && ["image", "video", "webpage"].includes(media.type)) {
if ((media.type === "image" || media.type === "video") && !safeRemoteUrl(media.mediaUrl, media.type)) throw new Error(path + ".media.mediaUrl 无效");
if (media.type === "webpage" && !safeRemoteUrl(media.pageUrl)) throw new Error(path + ".media.pageUrl 无效");
if (media.posterUrl && !safeRemoteUrl(media.posterUrl, "image")) throw new Error(path + ".media.posterUrl 无效");
}
Object.entries(value).forEach(([key, item]) => { if (key !== "media") validateRemoteMediaTree(item, path + "." + key); });
};
const safeColor = (value, fallback) => /^#[0-9a-f]{6}$/i.test(String(value || "")) ? value : fallback;
const icon = (id) => '<svg aria-hidden="true"><use href="#' + id + '"/></svg>';
const colors = (person) => {
const list = person && Array.isArray(person.colors) ? person.colors : [];
return [safeColor(list[0], "#7257f5"), safeColor(list[1], "#d94fbd")];
};
const avatar = (person, className) => {
const pair = colors(person || {});
return '<span class="avatar ' + (className || "") + '" style="--a:' + pair[0] + ";--b:" + pair[1] + '">' + escapeHTML((person && person.initial) || "T") + "</span>";
};
const metric = (value) => {
const number = Math.max(0, Number(value) || 0);
return number ? '<span class="action-count">' + number.toLocaleString("zh-CN") + "</span>" : "";
};
const toast = qs("#toast");
let toastTimer = 0;
const showToast = (message) => {
toast.textContent = message;
toast.classList.add("show");
window.clearTimeout(toastTimer);
toastTimer = window.setTimeout(() => toast.classList.remove("show"), 2800);
};
const saveData = () => writeStorage(storageKey, JSON.stringify(pageData));
let themeInitialized = false;
const syncThemeButtons = () => {
const dark = document.documentElement.dataset.theme === "dark";
[qs("#themeToggle"), qs("#mobileTheme")].forEach((button) => {
button.innerHTML = icon(dark ? "i-sun" : "i-moon");
button.setAttribute("aria-label", dark ? "切换浅色模式" : "切换深色模式");
});
qs('meta[name="theme-color"]').content = dark ? "#0a0a0a" : "#f5f5f3";
};
const applyInitialTheme = () => {
if (themeInitialized) return;
themeInitialized = true;
const configured = pageData.site.theme;
const stored = readStorage(themeKey);
const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme:dark)").matches;
const next = configured === "dark" || configured === "light"
? configured
: (stored === "dark" || stored === "light" ? stored : (prefersDark ? "dark" : "light"));
document.documentElement.dataset.theme = next;
syncThemeButtons();
};
const toggleTheme = () => {
const next = document.documentElement.dataset.theme === "dark" ? "light" : "dark";
document.documentElement.dataset.theme = next;
writeStorage(themeKey, next);
syncThemeButtons();
};
const renderSite = () => {
const site = pageData.site || {};
const user = site.currentUser || {};
document.title = site.pageTitle || site.brand || "Threads";
qs('meta[name="description"]').content = site.description || "";
qs("#brandText").textContent = site.brand || "Threads";
qs("#brandLink").setAttribute("aria-label", (site.brand || "Threads") + " 首页");
qs("#mobileUser").innerHTML = avatar(user, "avatar-sm");
qs("#composerUser").innerHTML = avatar(user);
qs("#modalUser").innerHTML = avatar(user);
qs("#modalUserName").textContent = user.name || "";
const stats = user.stats || {};
qs("#profileSummary").innerHTML =
'<div class="profile-summary">' + avatar(user) +
'<span class="profile-copy"><strong>' + escapeHTML(user.name) + "</strong><span>" + escapeHTML(user.handle) +
'</span></span><button class="follow-button following">主页</button></div>' +
'<div class="profile-stats"><div><strong>' + escapeHTML(stats.following) + '</strong><span>关注</span></div><div><strong>' +
escapeHTML(stats.followers) + '</strong><span>关注者</span></div><div><strong>' + escapeHTML(stats.threads) +
"</strong><span>串聊</span></div></div>";
applyInitialTheme();
};
const renderNavigation = () => {
const navigation = pageData.navigation || {};
qs("#feedTitle").textContent = navigation.feedTitle || "首页";
qs("#feedFilter").textContent = navigation.feedFilter || "为你推荐";
qs("#searchInput").placeholder = navigation.searchPlaceholder || "搜索用户或关键词";
qs("#searchHints").textContent = navigation.searchHints || "";
const tabs = Array.isArray(navigation.tabs) ? navigation.tabs : [];
qs("#feedTabs").innerHTML = tabs.map((label, index) =>
'<button class="feed-tab' + (index === 0 ? " active" : "") + '">' + escapeHTML(label) + "</button>"
).join("");
const labels = Array.isArray(navigation.mobileLabels) ? navigation.mobileLabels : [];
const items = [
["i-home", ""],
["i-search", ' data-panel="searchPanel"'],
["i-plus", " data-open-composer"],
["i-heart", ' data-panel="activityPanel"'],
["i-user", ""]
];
qs("#mobileNav").innerHTML = items.map((item, index) => {
const label = labels[index] || "";
if (index === 2) return '<button' + item[1] + ' aria-label="' + escapeHTML(label) + '"><span class="mobile-create">' + icon(item[0]) + '</span><span class="sr-only">' + escapeHTML(label) + "</span></button>";
return '<button class="' + (index === 0 ? "active" : "") + '"' + item[1] + ' aria-label="' + escapeHTML(label) + '">' + icon(item[0]) + "<span>" + escapeHTML(label) + "</span></button>";
}).join("");
const links = Array.isArray(navigation.footerLinks) ? navigation.footerLinks : [];
qs("#sideFooter").innerHTML = links.map((label) => '<a href="#footer">' + escapeHTML(label) + "</a>").join("") +
"<span>" + escapeHTML(navigation.copyright) + "</span>";
};
const renderComposer = () => {
const composer = pageData.composer || {};
qs("#composerButton").textContent = composer.inlinePlaceholder || "";
qs("#inlinePublish").textContent = composer.publishLabel || "发布";
qs("#composeTitle").textContent = composer.dialogTitle || "新串聊";
qs("#composeText").placeholder = composer.textareaPlaceholder || "";
qs("#composeText").maxLength = Math.max(1, Number(composer.maxLength) || 500);
qs("#modalPublish").textContent = composer.publishLabel || "发布";
qs("#charCount").textContent = String(qs("#composeText").maxLength - qs("#composeText").value.length);
};
const autumnGrid = (label) => '<div class="image-grid" role="img" aria-label="' + escapeHTML(label) + '">' +
'<div class="main-image"><svg viewBox="0 0 400 520" preserveAspectRatio="xMidYMid slice"><defs><linearGradient id="threadAutumn1" x1="0" y1="0" x2="0" y2="1"><stop stop-color="#a9c9de"/><stop offset="1" stop-color="#f2c096"/></linearGradient></defs><rect width="400" height="520" fill="url(#threadAutumn1)"/><circle cx="300" cy="105" r="48" fill="#fff0bf"/><path d="M0 350c100-50 210-20 400-60v230H0Z" fill="#6b7f63"/><path d="M210 520V205m0 42-92-88m92 120 108-110" stroke="#62493b" stroke-width="20" stroke-linecap="round"/><g fill="#d77b50"><circle cx="108" cy="148" r="70"/><circle cx="186" cy="115" r="82"/><circle cx="292" cy="138" r="68"/><circle cx="350" cy="205" r="54"/></g></svg></div>' +
'<div class="side-image"><svg viewBox="0 0 220 220"><rect width="220" height="220" fill="#e6b16d"/><circle cx="55" cy="60" r="38" fill="#c55c50"/><circle cx="130" cy="100" r="58" fill="#e37a4e"/><path d="M110 220V105" stroke="#553d35" stroke-width="16"/><path d="M0 190c80-30 150-10 220-40v70H0Z" fill="#736a4d"/></svg></div>' +
'<div class="side-image"><svg viewBox="0 0 220 220"><rect width="220" height="220" fill="#adc5ca"/><path d="M0 160 65 110l55 34 46-70 54 66v80H0Z" fill="#5b776e"/><circle cx="47" cy="55" r="28" fill="#ffe0a1"/><path d="M40 190c50-35 95-20 150-55" stroke="#eee0bd" stroke-width="12" fill="none" stroke-linecap="round"/></svg></div></div>';
document.head.insertAdjacentHTML("beforeend", '<style data-external-media>.thread-media{position:relative;margin-top:12px;overflow:hidden;border:1px solid var(--border);border-radius:14px;background:#000}.thread-media>img,.thread-media>video,.thread-media>iframe{width:100%;max-height:520px;display:block;border:0;object-fit:cover}.thread-media>iframe{height:360px}.thread-media>a.external-open{position:absolute;right:10px;bottom:10px;padding:7px 11px;border-radius:999px;color:#fff;background:rgba(0,0,0,.72);text-decoration:none;font-size:12px;font-weight:700}.thread-page>a{display:block;padding:13px 14px;color:var(--text);background:var(--surface);text-decoration:none}.thread-page>a strong,.thread-page>a span{display:block}.thread-page>a span{margin-top:4px;color:var(--muted);font-size:13px}</style>');
const mediaMarkup = (media) => {
if (!isObject(media)) return "";
if (media.type === "autumn-grid") return autumnGrid(media.label);
if (media.type === "image") {
const source = safeRemoteUrl(media.mediaUrl, "image");
if (!source) return "";
const pageUrl = safeRemoteUrl(media.pageUrl);
return '<div class="thread-media"><img src="' + escapeHTML(source) + '" alt="' + escapeHTML(media.alt || media.label || "串文图片") + '" 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="thread-media"><video src="' + escapeHTML(source) + '"' + (poster ? ' poster="' + escapeHTML(poster) + '"' : "") + ' controls playsinline preload="metadata" aria-label="' + escapeHTML(media.alt || "串文视频") + '"></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="thread-media thread-page">' + body + '<a href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer"><strong>' + escapeHTML(media.title || pageUrl) + '</strong><span>' + escapeHTML(media.description || "打开网页") + "</span></a></div>";
}
return "";
};
const actionsMarkup = (metrics) => '<div class="post-actions">' +
'<button class="post-action like-action" aria-label="点赞">' + icon("i-heart") + metric(metrics.likes) + "</button>" +
'<button class="post-action reply-action" aria-label="回复">' + icon("i-comment") + metric(metrics.replies) + "</button>" +
'<button class="post-action repost-action" aria-label="转发">' + icon("i-repost") + metric(metrics.reposts) + "</button>" +
'<button class="post-action share" aria-label="分享">' + icon("i-share") + "</button></div>";
const quoteMarkup = (quote) => {
if (!isObject(quote)) return "";
return '<div class="quote-card"><div class="quote-head">' + avatar(quote, "avatar-xs") + "<strong>" +
escapeHTML(quote.name) + '</strong><span class="handle-time">' + escapeHTML(quote.handle) +
"</span></div><p>" + escapeHTML(quote.text) + "</p></div>";
};
const rowMarkup = (thread, reply, hasNext) => {
const person = reply ? reply.author : thread.author;
const metrics = reply ? reply.metrics : thread.metrics;
const time = reply ? "· " + reply.time : escapeHTML(person.handle) + " · " + escapeHTML(thread.time);
return '<div class="thread-row' + (hasNext ? " has-next" : "") + '"><div class="avatar-column">' +
avatar(person, reply ? "avatar-sm" : "avatar-lg") + '</div><div class="post-body"><header class="post-head"><strong>' +
escapeHTML(person.name) + "</strong>" + (!reply && person.verified ? '<svg class="verified"><use href="#i-verified"/></svg>' : "") +
'<span class="handle-time">' + time + '</span><span class="head-spacer"></span>' +
(!reply && thread.followable ? '<button class="follow-button" data-follow>关注</button>' : "") +
(!reply ? '<button class="more-button" aria-label="更多操作">' + icon("i-more") + "</button>" : "") +
'</header><p class="post-text">' + escapeHTML(reply ? reply.text : thread.text) + "</p>" +
(!reply ? mediaMarkup(thread.media) : "") +
(!reply ? quoteMarkup(thread.quote) : "") + actionsMarkup(metrics || {}) +
(!reply ? '<form class="reply-form"><label class="sr-only">回复内容</label><input maxlength="' +
Math.max(1, Number(pageData.composer.replyMaxLength) || 180) + '" placeholder="回复' + escapeHTML(person.name) +
'…" /><button class="reply-send" aria-label="发送回复">' + icon("i-send") + "</button></form>" : "") +
"</div></div>";
};
const threadMarkup = (thread) => {
const replies = Array.isArray(thread.replies) ? thread.replies : [];
const search = [thread.author && thread.author.name, thread.author && thread.author.handle, thread.text, thread.preview]
.concat(replies.map((reply) => reply.text)).join(" ");
return '<article class="card thread-card" data-thread-id="' + escapeHTML(thread.id) + '" data-search="' + escapeHTML(search) + '">' +
rowMarkup(thread, null, replies.length > 0) + replies.map((reply, index) => rowMarkup(thread, reply, index < replies.length - 1)).join("") +
'<div class="reply-preview"><span class="stacked-avatars">' +
replies.slice(0, 3).map((reply) => avatar(reply.author, "avatar-xs")).join("") +
'</span><span>' + escapeHTML(thread.preview) + '</span></div><div class="post-menu"><button>' +
icon("i-bookmark") + "收藏</button><button>" + icon("i-eye-off") + "减少此类内容</button></div></article>";
};
const renderThreads = () => {
const data = pageData.threads || {};
const items = Array.isArray(data.items) ? data.items : [];
qs("#threadList").innerHTML = items.map(threadMarkup).join("");
qs("#emptyTitle").textContent = data.emptyTitle || "";
qs("#emptyText").textContent = data.emptyText || "";
qs("#emptyState").style.display = items.length ? "none" : "block";
};
const renderRecommendations = () => {
const data = pageData.recommendations || {};
qs("#followTitle").textContent = data.followTitle || "";
qs("#suggestions").innerHTML = (Array.isArray(data.people) ? data.people : []).map((person) =>
'<div class="suggest-row">' + avatar(person, "avatar-sm") + '<span class="suggest-copy"><strong>' +
escapeHTML(person.name) + "</strong><span>" + escapeHTML(person.handle) +
'</span></span><button class="follow-button" data-follow>关注</button></div>'
).join("");
qs("#topicTitle").textContent = data.topicTitle || "";
qs("#topics").innerHTML = (Array.isArray(data.topics) ? data.topics : []).map((topic) =>
'<div class="topic"><span>' + escapeHTML(topic.meta) + "</span><strong>" + escapeHTML(topic.title) +
"</strong><small>" + escapeHTML(topic.count) + "</small></div>"
).join("");
};
const renderActivity = () => {
const data = pageData.activity || {};
qs("#activityTitle").textContent = data.title || "";
qs("#activityList").innerHTML = (Array.isArray(data.items) ? data.items : []).map((item) =>
'<div class="activity-row">' + avatar(item, "avatar-sm") + '<span class="activity-copy"><p><strong>' +
escapeHTML(item.name) + "</strong> " + escapeHTML(item.text) + "</p><time>" + escapeHTML(item.time) +
"</time></span>" + (item.followable ? '<button class="follow-button" data-follow>关注</button>' : "") + "</div>"
).join("");
};
const renderAll = () => {
renderSite();
renderNavigation();
renderComposer();
renderThreads();
renderRecommendations();
renderActivity();
bindDynamicInteractions();
};
const applySearch = () => {
const query = qs("#searchInput").value.trim().toLocaleLowerCase();
let visible = 0;
qsa(".thread-card").forEach((thread) => {
const match = !query || thread.dataset.search.toLocaleLowerCase().includes(query) || thread.textContent.toLocaleLowerCase().includes(query);
thread.hidden = !match;
if (match) visible += 1;
});
qs("#emptyState").style.display = visible ? "none" : "block";
};
const changeCount = (button, delta) => {
const count = qs(".action-count", button);
if (count) count.textContent = String(Math.max(0, (Number(count.textContent.replace(/,/g, "")) || 0) + delta));
};
const bindDynamicInteractions = () => {
qsa("[data-follow]").forEach((button) => button.addEventListener("click", () => {
const following = button.classList.toggle("following");
button.textContent = following ? "正在关注" : "关注";
showToast(following ? "已关注" : "已取消关注");
}));
qsa(".feed-tab").forEach((tab) => tab.addEventListener("click", () => {
qsa(".feed-tab").forEach((item) => item.classList.remove("active"));
tab.classList.add("active");
showToast("已切换到" + tab.textContent);
}));
qsa(".mobile-nav button").forEach((button) => button.addEventListener("click", () => {
qsa(".mobile-nav button").forEach((item) => item.classList.remove("active"));
button.classList.add("active");
}));
qsa(".like-action").forEach((button) => button.addEventListener("click", () => {
const liked = button.classList.toggle("liked");
changeCount(button, liked ? 1 : -1);
button.setAttribute("aria-pressed", String(liked));
}));
qsa(".repost-action").forEach((button) => button.addEventListener("click", () => {
const reposted = button.classList.toggle("reposted");
changeCount(button, reposted ? 1 : -1);
showToast(reposted ? "已转发" : "已撤销转发");
}));
qsa(".reply-action").forEach((button) => button.addEventListener("click", () => {
const form = qs(".reply-form", button.closest(".post-body"));
if (!form) return;
form.classList.toggle("open");
if (form.classList.contains("open")) qs("input", form).focus();
}));
qsa(".reply-form").forEach((form) => form.addEventListener("submit", (event) => {
event.preventDefault();
const input = qs("input", form);
const value = input.value.trim();
if (!value) return;
const bubble = document.createElement("div");
bubble.className = "reply-bubble";
bubble.innerHTML = "<strong>" + escapeHTML(pageData.site.currentUser.name) + " · 刚刚</strong>" + escapeHTML(value);
form.before(bubble);
input.value = "";
const button = qs(".reply-action", form.closest(".post-body"));
if (button) changeCount(button, 1);
showToast("回复已发布");
}));
qsa(".share").forEach((button) => button.addEventListener("click", async () => {
try {
if (navigator.clipboard) await navigator.clipboard.writeText(location.href);
showToast("链接已复制");
} catch (_error) {
showToast("链接已准备");
}
}));
qsa(".thread-card").forEach((thread) => {
const menu = qs(".post-menu", thread);
const more = qs(".more-button", thread);
if (menu && more) more.addEventListener("click", (event) => {
event.stopPropagation();
qsa(".post-menu.open").forEach((other) => {
if (other !== menu) other.classList.remove("open");
});
menu.classList.toggle("open");
});
});
qsa("[data-open-composer]").forEach((button) => {
if (!button.dataset.composerBound) {
button.dataset.composerBound = "true";
button.addEventListener("click", openCompose);
}
});
qsa("[data-panel]").forEach((button) => {
if (!button.dataset.panelBound) {
button.dataset.panelBound = "true";
button.addEventListener("click", openPanel);
}
});
qs("#searchInput").value = qs("#searchInput").value || "";
applySearch();
};
const overlay = qs("#composeOverlay");
const composeText = qs("#composeText");
const modalPublish = qs("#modalPublish");
const charCount = qs("#charCount");
let modalOpener = null;
function openCompose(event) {
modalOpener = event.currentTarget;
overlay.classList.add("open");
overlay.setAttribute("aria-hidden", "false");
document.body.classList.add("modal-open");
window.setTimeout(() => composeText.focus(), 80);
}
const closeCompose = () => {
overlay.classList.remove("open");
overlay.setAttribute("aria-hidden", "true");
document.body.classList.remove("modal-open");
if (modalOpener) modalOpener.focus();
};
composeText.addEventListener("input", () => {
const left = composeText.maxLength - composeText.value.length;
charCount.textContent = String(left);
charCount.classList.toggle("warn", left <= 30);
modalPublish.disabled = !composeText.value.trim();
});
modalPublish.addEventListener("click", () => {
const value = composeText.value.trim();
if (!value) return;
const user = pageData.site.currentUser;
pageData.threads.items.unshift({
id: "new-" + Date.now(),
author: {name: user.name, handle: user.handle, initial: user.initial, colors: user.colors, verified: false},
time: "刚刚",
text: value,
media: null,
quote: null,
metrics: {likes: 0, replies: 0, reposts: 0},
followable: false,
replies: [],
preview: "成为第一个回复的人"
});
saveData();
renderThreads();
bindDynamicInteractions();
composeText.value = "";
charCount.textContent = String(composeText.maxLength);
modalPublish.disabled = true;
closeCompose();
qs(".thread-card").scrollIntoView({behavior: "smooth", block: "center"});
showToast("串聊已发布");
});
qs("#closeCompose").addEventListener("click", closeCompose);
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeCompose();
});
const closePanels = () => qsa(".panel.open").forEach((panel) => {
panel.classList.remove("open");
panel.setAttribute("aria-hidden", "true");
});
function openPanel(event) {
event.stopPropagation();
const panel = qs("#" + event.currentTarget.dataset.panel);
if (!panel) return;
const willOpen = !panel.classList.contains("open");
closePanels();
if (willOpen) {
panel.classList.add("open");
panel.setAttribute("aria-hidden", "false");
if (panel.id === "searchPanel") window.setTimeout(() => qs("input", panel).focus(), 80);
}
}
qsa("[data-close-panel]").forEach((button) => button.addEventListener("click", closePanels));
qs("#searchInput").addEventListener("input", applySearch);
const settingsOverlay = qs("#settingsOverlay");
const jsonEditor = qs("#jsonEditor");
const jsonStatus = qs("#jsonStatus");
let activeModule = MODULES[0];
let editorDraft = clone(pageData);
const validateEditor = () => {
try {
const parsed = JSON.parse(jsonEditor.value);
if (!isObject(parsed)) throw new Error("模块必须是 JSON 对象");
validateRemoteMediaTree(parsed);
jsonStatus.textContent = "JSON 有效";
jsonStatus.className = "json-status valid";
return parsed;
} catch (error) {
jsonStatus.textContent = "JSON 无效:" + error.message;
jsonStatus.className = "json-status invalid";
return null;
}
};
const storeActiveDraft = () => {
const parsed = validateEditor();
if (!parsed) return false;
editorDraft[activeModule] = parsed;
return true;
};
const selectModule = (name, force) => {
if (!force && !storeActiveDraft()) return;
activeModule = name;
qsa(".module-tab").forEach((tab) => tab.classList.toggle("active", tab.dataset.module === name));
qs("#editorModuleTitle").textContent = MODULE_META[name][0];
jsonEditor.value = JSON.stringify(editorDraft[name], null, 2);
validateEditor();
};
const renderModuleTabs = () => {
qs("#moduleTabs").innerHTML = "<h3>页面模块</h3>" + MODULES.map((name) =>
'<button class="module-tab' + (name === activeModule ? " active" : "") + '" data-module="' + name + '"><strong>' +
MODULE_META[name][0] + "</strong><span>" + MODULE_META[name][1] + "</span></button>"
).join("");
qsa(".module-tab").forEach((tab) => tab.addEventListener("click", () => selectModule(tab.dataset.module, false)));
};
const openSettings = () => {
editorDraft = clone(pageData);
activeModule = MODULES[0];
renderModuleTabs();
selectModule(activeModule, true);
settingsOverlay.classList.add("open");
settingsOverlay.setAttribute("aria-hidden", "false");
document.body.classList.add("modal-open", "settings-open");
window.setTimeout(() => jsonEditor.focus(), 80);
};
const closeSettings = () => {
settingsOverlay.classList.remove("open");
settingsOverlay.setAttribute("aria-hidden", "true");
document.body.classList.remove("modal-open", "settings-open");
qs("#openSettings").focus();
};
qs("#openSettings").addEventListener("click", openSettings);
qs("#closeSettings").addEventListener("click", closeSettings);
settingsOverlay.addEventListener("click", (event) => {
if (event.target === settingsOverlay) closeSettings();
});
jsonEditor.addEventListener("input", validateEditor);
jsonEditor.addEventListener("keydown", (event) => {
if (event.key === "Tab") {
event.preventDefault();
const start = jsonEditor.selectionStart;
const end = jsonEditor.selectionEnd;
jsonEditor.setRangeText(" ", start, end, "end");
validateEditor();
}
});
qs("#applyJson").addEventListener("click", () => {
if (!storeActiveDraft() || !isCompleteData(editorDraft)) {
showToast("请修正 JSON 后再应用");
return;
}
pageData = clone(editorDraft);
saveData();
renderAll();
showToast("JSON 已应用到页面");
});
qs("#resetJson").addEventListener("click", () => {
pageData = clone(initialData);
editorDraft = clone(initialData);
removeStorage(storageKey);
removeStorage(themeKey);
themeInitialized = false;
renderAll();
renderModuleTabs();
selectModule(activeModule, true);
showToast("已恢复初始 JSON");
});
qs("#copyJson").addEventListener("click", async () => {
if (!storeActiveDraft()) return;
const text = JSON.stringify(editorDraft, null, 2);
try {
if (navigator.clipboard) await navigator.clipboard.writeText(text);
showToast("完整 JSON 已复制");
} catch (_error) {
jsonEditor.focus();
jsonEditor.select();
showToast("已选中当前模块,请手动复制");
}
});
qs("#downloadJson").addEventListener("click", () => {
if (!storeActiveDraft()) return;
const blob = new Blob([JSON.stringify(editorDraft, null, 2) + "\n"], {type: "application/json"});
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "threads-page-data.json";
link.click();
window.setTimeout(() => URL.revokeObjectURL(link.href), 0);
showToast("JSON 已下载");
});
[qs("#themeToggle"), qs("#mobileTheme")].forEach((button) => button.addEventListener("click", toggleTheme));
document.addEventListener("click", (event) => {
if (!event.target.closest(".panel") && !event.target.closest("[data-panel]")) closePanels();
if (!event.target.closest(".post-menu") && !event.target.closest(".more-button")) {
qsa(".post-menu.open").forEach((menu) => menu.classList.remove("open"));
}
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
closePanels();
if (overlay.classList.contains("open")) closeCompose();
if (settingsOverlay.classList.contains("open")) closeSettings();
}
});
qsa('a[href^="#"]').forEach((link) => link.addEventListener("click", (event) => {
const target = link.getAttribute("href");
if (target !== "#feed") {
event.preventDefault();
showToast("此页面正在准备中");
}
}));
renderAll();
function installJsonMediaUpload(){
const editor=document.getElementById("jsonEditor"),apply=document.getElementById("applyJson");if(!editor||!apply||document.getElementById("uploadJsonMedia"))return;
const actions=apply.parentElement,button=document.createElement("button"),input=document.createElement("input"),reference=actions.querySelector("#downloadJson,#copyJson,#validateJson,#resetJson");
button.type="button";button.id="uploadJsonMedia";button.className=reference?reference.className:apply.className;button.textContent="上传图片/视频";button.title="先把光标放进要替换的内容对象,再选择图片或视频";input.type="file";input.accept="image/*,video/*";input.hidden=true;actions.insertBefore(button,apply);actions.appendChild(input);
const report=(message)=>{const status=document.getElementById("settingsStatus")||document.getElementById("jsonError")||document.getElementById("jsonStatus");if(status)status.textContent=message};
const findTarget=(text,cursor)=>{const stack=[],matches=[];let quoted=false,escaped=false;for(let index=0;index<text.length;index+=1){const char=text[index];if(quoted){if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char==='"')quoted=false;continue}if(char==='"'){quoted=true;continue}if(char==="{")stack.push(index);else if(char==="}"){const start=stack.pop();if(start===undefined||cursor<start||cursor>index+1)continue;try{const value=JSON.parse(text.slice(start,index+1)),own=(key)=>Object.prototype.hasOwnProperty.call(value,key);if(value&&!Array.isArray(value)&&(own("media")||own("visual")||(own("id")&&(own("text")||own("title"))&&(own("author")||own("channel")||own("user")))))matches.push({start,end:index+1,value})}catch(_error){/* full validator handles malformed JSON */}}}return matches.sort((left,right)=>(left.end-left.start)-(right.end-right.start))[0]||null};
button.addEventListener("click",()=>{input.value="";report("请选择图片或视频;文件会写入光标所在内容对象的 media 字段。");input.click()});
input.addEventListener("change",()=>{const file=input.files&&input.files[0];if(!file)return;const type=file.type.startsWith("image/")?"image":file.type.startsWith("video/")?"video":"";if(!type){report("仅支持图片或视频文件。");return}const target=findTarget(editor.value,editor.selectionStart);if(!target){report("请先把光标放进带 visual/media 的内容对象,或带 id 的帖子/视频对象内。");return}const reader=new FileReader();reader.onerror=()=>report("文件读取失败,请重新选择。");reader.onload=()=>{const previous=target.value.media&&typeof target.value.media==="object"?target.value.media:{},media={type,mediaUrl:String(reader.result)};for(const key of ["alt","label","caption","pageUrl"])if(typeof previous[key]==="string")media[key]=previous[key];if(!media.alt)media.alt=type==="image"?"用户上传的图片":"用户上传的视频";target.value.media=media;const lineStart=editor.value.lastIndexOf("\n",target.start-1)+1,indent=(editor.value.slice(lineStart,target.start).match(/^\s*/)||[""])[0],replacement=JSON.stringify(target.value,null,2).split("\n").map((line,index)=>index?indent+line:line).join("\n");editor.value=editor.value.slice(0,target.start)+replacement+editor.value.slice(target.end);editor.dispatchEvent(new Event("input",{bubbles:true}));const mediaIndex=replacement.indexOf('"media"');editor.focus();editor.setSelectionRange(target.start+Math.max(mediaIndex,0),target.start+Math.max(mediaIndex,0));report(`已把 ${file.name} 写入 JSON,请点击“应用并渲染”。${file.size>2*1024*1024?" 文件较大,建议同时下载 JSON 保存。":""}`)};reader.readAsDataURL(file)});
}
installJsonMediaUpload();
function installInlineMediaReplace() {
if (document.getElementById("dfInlineMediaInput")) return;
const visualHostSelector = ".post-media,.video-visual,.thumbnail-visual,.short-thumb,.watch-visual,.thread-media,.image-grid,.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();
})();
@@ -0,0 +1,379 @@
<!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="#f5f5f3" />
<meta name="description" content="Weave,一个原创的串联式文本社交界面。" />
<title>Weave · 串联想法</title>
<style>
:root {
color-scheme: light;
--page: #f4f4f2;
--surface: #fff;
--surface-2: #f7f7f6;
--text: #101010;
--muted: #777779;
--muted-2: #a0a0a2;
--line: #e7e7e5;
--line-strong: #d2d2cf;
--accent: #111;
--accent-on: #fff;
--danger: #ef3f5e;
--success: #1b9b68;
--shadow: 0 10px 34px rgba(18,18,18,.06);
--focus: 0 0 0 3px rgba(0,0,0,.18);
--header-h: 70px;
}
[data-theme="dark"] {
color-scheme: dark;
--page: #0a0a0a;
--surface: #161616;
--surface-2: #1d1d1d;
--text: #f4f4f4;
--muted: #99999e;
--muted-2: #747478;
--line: #2a2a2a;
--line-strong: #3a3a3a;
--accent: #f1f1f1;
--accent-on: #0b0b0b;
--shadow: 0 12px 38px rgba(0,0,0,.25);
--focus: 0 0 0 3px rgba(255,255,255,.23);
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body { margin: 0; min-width: 320px; background: var(--page); 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.5; transition: background .2s,color .2s; }
body.modal-open { overflow: hidden; }
button, input, textarea { font: inherit; }
button { color: inherit; }
button, a { -webkit-tap-highlight-color: transparent; }
button, [role="button"] { cursor: pointer; touch-action: manipulation; }
button:focus-visible, a:focus-visible, input:focus-visible, textarea:focus-visible { outline: none; box-shadow: var(--focus); }
svg { display: block; }
.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
.skip-link { position: fixed; z-index: 500; left: 14px; top: calc(var(--df-generated-header-height, 0px) + 9px); padding: 10px 15px; border-radius: 12px; color: var(--accent-on); background: var(--accent); transform: translateY(-160%); text-decoration: none; }
.skip-link:focus { transform: translateY(0); }
.topbar { position: fixed; z-index: 80; inset: var(--df-generated-header-height, 0px) 0 auto; height: var(--header-h); padding: 0 26px; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; background: color-mix(in srgb,var(--page) 88%,transparent); backdrop-filter: blur(18px); border-bottom: 1px solid color-mix(in srgb,var(--line) 82%,transparent); }
.brand { width: fit-content; display: flex; align-items: center; gap: 9px; color: var(--text); text-decoration: none; font-size: 20px; font-weight: 800; letter-spacing: -.45px; }
.weave-mark { position: relative; width: 36px; height: 36px; display: grid; place-items: center; }
.weave-mark::before, .weave-mark::after { content: ""; position: absolute; width: 19px; height: 26px; border: 3px solid currentColor; border-radius: 50%; transform: rotate(45deg); }
.weave-mark::before { translate: -5px 1px; border-right-color: transparent; }
.weave-mark::after { translate: 5px -1px; border-left-color: transparent; }
.desktop-nav { display: flex; align-items: center; gap: 8px; }
.nav-button { position: relative; width: 58px; height: 48px; border: 0; border-radius: 14px; display: grid; place-items: center; color: var(--muted); background: transparent; transition: color .18s,background .18s,transform .18s; }
.nav-button:hover { color: var(--text); background: var(--surface); transform: translateY(-1px); }
.nav-button.active { color: var(--text); }
.nav-button.active::after { content: ""; position: absolute; bottom: -11px; width: 23px; height: 3px; border-radius: 3px; background: var(--text); }
.nav-button svg { width: 24px; height: 24px; }
.header-actions { justify-self: end; display: flex; align-items: center; gap: 8px; }
.round-button { position: relative; width: 44px; height: 44px; border: 1px solid var(--line); border-radius: 50%; display: grid; place-items: center; color: var(--text); background: var(--surface); transition: transform .18s,background .18s; }
.round-button:hover { transform: translateY(-1px); background: var(--surface-2); }
.round-button svg { width: 20px; height: 20px; }
.notification-dot { position: absolute; top: 5px; right: 5px; width: 8px; height: 8px; border: 2px solid var(--surface); border-radius: 50%; background: var(--danger); }
.avatar { --a:#7257f5; --b:#d94fbd; width: 44px; height: 44px; flex: 0 0 auto; border-radius: 50%; display: grid; place-items: center; color: #fff; background: linear-gradient(145deg,var(--a),var(--b)); font-size: 14px; font-weight: 800; box-shadow: inset 0 0 0 1px rgba(255,255,255,.18); }
.avatar-sm { width: 36px; height: 36px; font-size: 12px; }
.avatar-xs { width: 28px; height: 28px; font-size: 10px; }
.avatar-lg { width: 50px; height: 50px; }
.page-shell { width: min(1020px,calc(100% - 28px)); margin: 0 auto; padding: calc(var(--header-h) + 22px) 0 56px; display: grid; grid-template-columns: minmax(0,640px) 320px; gap: 24px; align-items: start; }
.feed-head { height: 58px; padding: 0 14px; display: flex; align-items: center; justify-content: space-between; }
.feed-head h1 { margin: 0; font-size: 22px; letter-spacing: -.45px; }
.feed-filter { min-height: 44px; padding: 0 12px; border: 1px solid var(--line); border-radius: 999px; display: flex; align-items: center; gap: 6px; color: var(--muted); background: var(--surface); font-size: 13px; font-weight: 650; }
.feed-filter svg { width: 14px; height: 14px; }
.card { background: var(--surface); border: 1px solid var(--line); border-radius: 24px; box-shadow: var(--shadow); }
.composer-card { min-height: 98px; margin-bottom: 12px; padding: 16px 17px; display: grid; grid-template-columns: 44px 1fr auto; align-items: start; gap: 12px; }
.composer-button { align-self: center; min-height: 44px; border: 0; color: var(--muted); background: transparent; text-align: left; font-size: 15px; }
.publish-inline { align-self: center; min-width: 68px; height: 44px; padding: 0 15px; border: 1px solid var(--line-strong); border-radius: 999px; color: var(--muted); background: var(--surface); font-size: 14px; font-weight: 700; }
.publish-inline:hover { color: var(--text); background: var(--surface-2); }
.feed-tabs { margin-bottom: 10px; padding: 5px; display: grid; grid-template-columns: repeat(2,1fr); border-radius: 16px; background: color-mix(in srgb,var(--surface) 72%,transparent); }
.feed-tab { min-height: 44px; border: 0; border-radius: 12px; color: var(--muted); background: transparent; font-weight: 650; }
.feed-tab.active { color: var(--text); background: var(--surface); box-shadow: 0 3px 12px rgba(0,0,0,.05); }
.thread-card { position: relative; margin-bottom: 12px; padding: 18px 18px 10px; overflow: hidden; }
.thread-row { position: relative; display: grid; grid-template-columns: 46px 1fr; gap: 11px; }
.thread-row + .thread-row { margin-top: 10px; padding-top: 2px; }
.avatar-column { position: relative; display: flex; justify-content: center; }
.thread-row.has-next .avatar-column::after { content: ""; position: absolute; z-index: 0; top: 50px; bottom: -15px; left: 50%; width: 2px; border-radius: 2px; background: var(--line-strong); transform: translateX(-50%); }
.avatar-column .avatar { position: relative; z-index: 1; }
.post-body { min-width: 0; }
.post-head { display: flex; align-items: center; gap: 5px; min-width: 0; min-height: 28px; }
.post-head strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.verified { width: 16px; height: 16px; flex: 0 0 auto; color: #1388e8; }
.handle-time { color: var(--muted); font-size: 13px; white-space: nowrap; }
.head-spacer { flex: 1; }
.follow-button { min-width: 66px; height: 44px; padding: 0 13px; border: 1px solid var(--line-strong); border-radius: 9px; color: var(--text); background: var(--surface); font-size: 13px; font-weight: 700; }
.follow-button.following { color: var(--muted); background: var(--surface-2); }
.more-button { width: 44px; height: 44px; margin-right: -8px; border: 0; border-radius: 50%; display: grid; place-items: center; color: var(--muted); background: transparent; }
.more-button:hover { color: var(--text); background: var(--surface-2); }
.more-button svg { width: 18px; height: 18px; }
.post-text { margin: 5px 0 11px; white-space: pre-wrap; overflow-wrap: anywhere; }
.post-text a { color: inherit; font-weight: 650; text-decoration: underline; text-decoration-color: var(--line-strong); text-underline-offset: 2px; }
.image-grid { display: grid; grid-template-columns: 1.2fr .8fr; gap: 3px; margin: 10px 0 6px; overflow: hidden; border: 1px solid var(--line); border-radius: 15px; background: var(--surface-2); }
.image-grid .main-image { grid-row: span 2; min-height: 255px; }
.image-grid .side-image { min-height: 126px; }
.image-grid svg { width: 100%; height: 100%; }
.quote-card { margin: 9px 0 7px; padding: 12px; border: 1px solid var(--line-strong); border-radius: 15px; background: var(--surface); }
.quote-head { display: flex; align-items: center; gap: 7px; font-size: 13px; }
.quote-card p { margin: 7px 0 0; font-size: 14px; }
.post-actions { min-height: 44px; margin-top: 5px; display: flex; align-items: center; gap: 1px; }
.post-action { min-width: 47px; height: 44px; padding: 0 7px; border: 0; border-radius: 999px; display: flex; align-items: center; gap: 5px; color: var(--muted); background: transparent; font-size: 12px; transition: color .18s,background .18s; }
.post-action:hover { color: var(--text); background: var(--surface-2); }
.post-action svg { width: 20px; height: 20px; }
.post-action.liked { color: var(--danger); }
.post-action.liked svg, .post-action.reposted svg { fill: currentColor; }
.post-action.reposted { color: var(--success); }
.post-action.share { margin-left: auto; }
.reply-preview { margin-top: 3px; padding: 9px 0 3px; display: flex; align-items: center; gap: 9px; color: var(--muted); font-size: 13px; }
.stacked-avatars { display: flex; align-items: center; min-width: 54px; }
.stacked-avatars .avatar + .avatar { margin-left: -10px; }
.reply-form { display: none; padding: 10px 0 4px; gap: 8px; }
.reply-form.open { display: flex; }
.reply-form input { flex: 1; min-width: 0; height: 44px; padding: 0 14px; border: 1px solid var(--line); border-radius: 999px; color: var(--text); background: var(--surface-2); font-size: 16px; }
.reply-send { width: 44px; height: 44px; border: 0; border-radius: 50%; display: grid; place-items: center; color: var(--accent-on); background: var(--accent); }
.reply-send svg { width: 18px; height: 18px; }
.reply-bubble { margin: 8px 0 2px; padding: 10px 12px; border-radius: 12px; background: var(--surface-2); font-size: 14px; }
.reply-bubble strong { display: block; margin-bottom: 2px; }
.post-menu { position: absolute; z-index: 20; top: 53px; right: 14px; width: 210px; padding: 7px; display: none; border: 1px solid var(--line); border-radius: 14px; background: var(--surface); box-shadow: 0 14px 40px rgba(0,0,0,.16); }
.post-menu.open { display: block; }
.post-menu button { width: 100%; min-height: 44px; padding: 0 11px; border: 0; border-radius: 9px; display: flex; align-items: center; gap: 9px; background: transparent; text-align: left; }
.post-menu button:hover { background: var(--surface-2); }
.post-menu svg { width: 18px; height: 18px; }
.empty-state { display: none; padding: 45px 20px; text-align: center; }
.empty-state svg { width: 38px; height: 38px; margin: 0 auto 12px; color: var(--muted); }
.empty-state h2 { margin: 0 0 5px; }
.empty-state p { margin: 0; color: var(--muted); }
.right-column { position: sticky; top: calc(var(--df-generated-header-height, 0px) + var(--header-h) + 22px); display: grid; gap: 12px; }
.side-card { padding: 16px; border-radius: 20px; background: var(--surface); border: 1px solid var(--line); }
.side-card h2 { margin: 0 0 12px; font-size: 16px; }
.profile-summary { display: flex; align-items: center; gap: 10px; }
.profile-copy { min-width: 0; flex: 1; }
.profile-copy strong, .profile-copy span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.profile-copy span { color: var(--muted); font-size: 13px; }
.profile-stats { margin-top: 13px; padding-top: 12px; border-top: 1px solid var(--line); display: flex; justify-content: space-around; text-align: center; }
.profile-stats strong { display: block; }
.profile-stats span { color: var(--muted); font-size: 11px; }
.suggest-row { min-height: 58px; display: flex; align-items: center; gap: 9px; }
.suggest-copy { min-width: 0; flex: 1; }
.suggest-copy strong, .suggest-copy span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.suggest-copy strong { font-size: 13px; }
.suggest-copy span { color: var(--muted); font-size: 12px; }
.topic { min-height: 64px; padding: 8px 0; border-top: 1px solid var(--line); }
.topic:first-of-type { border-top: 0; }
.topic span { color: var(--muted); font-size: 11px; }
.topic strong { display: block; margin: 2px 0; font-size: 14px; }
.topic small { color: var(--muted); }
.side-footer { padding: 2px 8px; color: var(--muted); font-size: 11px; line-height: 1.7; }
.side-footer a { color: inherit; text-decoration: none; margin-right: 7px; }
.overlay { position: fixed; z-index: 110; inset: 0; padding: 18px; display: grid; place-items: start center; background: rgba(0,0,0,.38); backdrop-filter: blur(3px); opacity: 0; visibility: hidden; transition: opacity .2s,visibility .2s; }
.overlay.open { opacity: 1; visibility: visible; }
.compose-modal { width: min(620px,100%); margin-top: 8vh; border: 1px solid var(--line); border-radius: 24px; background: var(--surface); box-shadow: 0 24px 80px rgba(0,0,0,.24); transform: translateY(10px) scale(.98); transition: transform .2s; }
.overlay.open .compose-modal { transform: translateY(0) scale(1); }
.modal-head { min-height: 62px; padding: 0 14px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--line); }
.modal-head h2 { margin: 0; font-size: 16px; }
.close-button { width: 44px; height: 44px; border: 0; border-radius: 50%; display: grid; place-items: center; background: transparent; }
.close-button:hover { background: var(--surface-2); }
.close-button svg { width: 20px; height: 20px; }
.modal-body { padding: 17px; }
.modal-compose { display: grid; grid-template-columns: 46px 1fr; gap: 11px; }
.modal-textarea { width: 100%; min-height: 140px; padding: 5px 0; resize: vertical; border: 0; outline: 0; color: var(--text); background: transparent; font-size: 17px; line-height: 1.55; }
.modal-textarea::placeholder { color: var(--muted); }
.modal-footer { min-height: 62px; padding-top: 12px; display: flex; align-items: center; justify-content: space-between; border-top: 1px solid var(--line); }
.composer-tools { display: flex; gap: 1px; }
.tool-button { width: 44px; height: 44px; border: 0; border-radius: 50%; display: grid; place-items: center; color: var(--muted); background: transparent; }
.tool-button:hover { color: var(--text); background: var(--surface-2); }
.tool-button svg { width: 20px; height: 20px; }
.modal-actions { display: flex; align-items: center; gap: 10px; }
.char-count { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
.char-count.warn { color: var(--danger); }
.modal-publish { min-width: 78px; height: 44px; border: 0; border-radius: 999px; color: var(--accent-on); background: var(--accent); font-weight: 700; }
.modal-publish:disabled { opacity: .4; cursor: not-allowed; }
.panel { position: fixed; z-index: 100; top: calc(var(--df-generated-header-height, 0px) + var(--header-h) + 8px); left: 50%; width: min(580px,calc(100vw - 24px)); max-height: calc(100dvh - var(--df-generated-header-height, 0px) - var(--header-h) - 20px); overflow: auto; padding: 15px; border: 1px solid var(--line); border-radius: 20px; background: var(--surface); box-shadow: 0 18px 55px rgba(0,0,0,.2); opacity: 0; visibility: hidden; transform: translate(-50%,-8px); transition: opacity .18s,visibility .18s,transform .18s; }
.panel.open { opacity: 1; visibility: visible; transform: translate(-50%,0); }
.panel-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
.panel-head h2 { margin: 0; font-size: 19px; }
.panel-search { position: relative; }
.panel-search svg { position: absolute; left: 14px; top: 50%; width: 18px; height: 18px; color: var(--muted); transform: translateY(-50%); }
.panel-search input { width: 100%; height: 46px; padding: 0 14px 0 42px; border: 1px solid var(--line); border-radius: 14px; color: var(--text); background: var(--surface-2); font-size: 16px; }
.search-hints { padding: 16px 5px 4px; color: var(--muted); font-size: 13px; }
.activity-row { min-height: 68px; padding: 8px 3px; display: flex; align-items: center; gap: 10px; border-top: 1px solid var(--line); }
.activity-row:first-of-type { border-top: 0; }
.activity-copy { flex: 1; }
.activity-copy p { margin: 0; font-size: 13px; }
.activity-copy time { color: var(--muted); font-size: 11px; }
.toast { position: fixed; z-index: 160; left: 50%; bottom: 25px; padding: 11px 16px; border-radius: 12px; color: var(--accent-on); background: var(--accent); box-shadow: 0 14px 38px rgba(0,0,0,.2); 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); }
.mobile-nav { display: none; }
.mobile-header { display: none; }
@media (max-width: 920px) {
.page-shell { grid-template-columns: minmax(0,640px); width: min(640px,calc(100% - 24px)); }
.right-column { display: none; }
}
@media (max-width: 680px) {
:root { --header-h: 58px; }
body { padding-bottom: calc(60px + env(safe-area-inset-bottom)); }
.topbar { display: none; }
.mobile-header { position: fixed; z-index: 75; inset: var(--df-generated-header-height, 0px) 0 auto; height: var(--header-h); padding: max(4px,env(safe-area-inset-top)) 14px 4px; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; background: color-mix(in srgb,var(--page) 91%,transparent); backdrop-filter: blur(16px); border-bottom: 1px solid var(--line); }
.mobile-header .weave-mark { width: 32px; height: 32px; }
.mobile-header strong { font-size: 17px; }
.mobile-header .round-button { justify-self: end; }
.page-shell { width: 100%; padding: calc(var(--header-h) + 8px) 0 15px; display: block; }
.feed-head { padding-inline: 13px; }
.feed-head h1 { display: none; }
.feed-filter { margin-left: auto; }
.composer-card { margin: 0 8px 9px; border-radius: 18px; box-shadow: none; grid-template-columns: 42px 1fr; }
.composer-card .publish-inline { display: none; }
.feed-tabs { margin: 0 8px 8px; }
.thread-card { margin: 0 0 8px; padding: 15px 13px 8px; border-inline: 0; border-radius: 0; box-shadow: none; }
.thread-row { grid-template-columns: 42px 1fr; gap: 9px; }
.avatar-lg { width: 44px; height: 44px; }
.post-head { flex-wrap: nowrap; }
.handle-time { max-width: 92px; overflow: hidden; text-overflow: ellipsis; }
.image-grid .main-image { min-height: 210px; }
.image-grid .side-image { min-height: 103px; }
.post-action { min-width: 44px; padding: 0 6px; }
.mobile-nav { position: fixed; z-index: 76; inset: auto 0 0; height: calc(58px + env(safe-area-inset-bottom)); padding: 3px 8px max(4px,env(safe-area-inset-bottom)); display: grid; grid-template-columns: repeat(5,1fr); background: color-mix(in srgb,var(--page) 94%,transparent); border-top: 1px solid var(--line); backdrop-filter: blur(16px); }
.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; }
.mobile-create { width: 42px; height: 32px; border: 1px solid var(--line-strong); border-radius: 11px; display: grid; place-items: center; color: var(--accent-on); background: var(--accent); }
.mobile-create svg { width: 18px; height: 18px; }
.overlay { padding: 0; }
.compose-modal { min-height: 100dvh; margin: 0; border: 0; border-radius: 0; }
.panel { top: calc(var(--df-generated-header-height, 0px) + var(--header-h) + 5px); }
.toast { bottom: calc(70px + env(safe-area-inset-bottom)); }
}
@media (max-width: 390px) {
.thread-card { padding-inline: 10px; }
.post-action .action-count { font-size: 10px; }
.post-text { font-size: 15px; }
.handle-time { max-width: 70px; }
.follow-button { min-width: 58px; padding-inline: 9px; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { scroll-behavior: auto !important; animation: none !important; transition: none !important; }
}
.header-actions { padding-right: 54px; }
.settings-trigger { position: fixed; z-index: 180; top: calc(var(--df-generated-header-height, 0px) + 12px); right: 18px; width: 46px; height: 46px; border: 1px solid var(--line-strong); border-radius: 50%; display: grid; place-items: center; color: var(--text); background: color-mix(in srgb,var(--surface) 92%,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(--surface-2); transform: rotate(12deg); }
.settings-trigger svg { width: 21px; height: 21px; }
.settings-overlay { position: fixed; z-index: 220; inset: 0; padding: 30px; display: grid; place-items: center; background: rgba(2,8,18,.76); backdrop-filter: blur(8px); opacity: 0; visibility: hidden; transition: opacity .2s,visibility .2s; }
.settings-overlay.open { opacity: 1; visibility: visible; }
body.settings-open > :not(.settings-overlay):not(svg) { visibility: hidden !important; }
.settings-modal { width: min(1280px,100%); height: min(790px,calc(100dvh - 60px)); display: grid; grid-template-rows: auto 1fr auto; overflow: hidden; border: 1px solid #2a6382; border-radius: 14px; color: #e8f3ff; background: #071321; box-shadow: 0 30px 100px rgba(0,0,0,.52); }
.settings-head, .settings-body, .settings-foot { background: #071321; }
.settings-head { min-height: 82px; padding: 16px 24px; display: flex; align-items: center; gap: 14px; border-bottom: 1px solid #21455d; }
.settings-head-copy { flex: 1; }
.settings-kicker { display: block; margin-bottom: 3px; color: #35b8ff; font-size: 13px; font-weight: 800; letter-spacing: .1em; }
.settings-head h2 { margin: 0; color: #f7fbff; font-size: 25px; }
.settings-close { width: 46px; height: 46px; border: 1px solid #2e708f; border-radius: 9px; display: grid; place-items: center; color: #f2f8ff; background: #0b1d30; }
.settings-close:hover { background: #12304b; }
.settings-close svg { width: 22px; height: 22px; }
.settings-body { min-height: 0; padding: 18px 24px; display: grid; grid-template-columns: 255px minmax(0,1fr); gap: 18px; }
.module-tabs { min-height: 0; overflow: auto; }
.module-tabs h3 { margin: 0 0 10px; color: #8fa9bf; font-size: 13px; font-weight: 650; }
.module-tab { width: 100%; min-height: 58px; margin-bottom: 7px; padding: 9px 12px; border: 1px solid #1d4660; border-radius: 9px; display: block; color: #b7cada; background: #0a1929; text-align: left; }
.module-tab:hover { background: #0d2338; }
.module-tab.active { border-color: #25adf2; color: #fff; background: #0d2a42; box-shadow: inset 3px 0 #28b6ff; }
.module-tab strong,.module-tab span { display: block; }
.module-tab span { margin-top: 2px; color: #7e9aae; font-size: 11px; }
.editor-pane { min-width: 0; min-height: 0; display: grid; grid-template-rows: auto 1fr auto; }
.editor-title { min-height: 37px; display: flex; align-items: flex-start; justify-content: space-between; color: #8fa9bf; font-size: 12px; }
.editor-title strong { color: #eef8ff; font-size: 16px; }
.json-editor { width: 100%; min-height: 0; padding: 16px; resize: none; border: 1px solid #28526b; border-radius: 10px; outline: 0; color: #d6f1ff; background: #020a12; font: 14px/1.62 ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",monospace; tab-size: 2; }
.json-editor:focus { border-color: #28b6ff; box-shadow: 0 0 0 3px rgba(40,182,255,.16); }
.editor-hint { min-height: 40px; padding-top: 9px; display: flex; justify-content: space-between; gap: 12px; color: #7894aa; font-size: 12px; }
.json-status { font-weight: 750; }
.json-status.valid { color: #48d8a0; }
.json-status.invalid { color: #ff7189; }
.settings-foot { min-height: 74px; padding: 13px 24px; display: flex; align-items: center; justify-content: flex-end; gap: 10px; border-top: 1px solid #21455d; }
.editor-button { min-height: 44px; padding: 0 17px; border: 1px solid #2d7292; border-radius: 9px; color: #e5f4ff; background: #0b1e30; font-weight: 700; }
.editor-button:hover { background: #12334f; }
.editor-button.primary { border-color: #2ab8ff; color: #03131e; background: #33b9fa; }
.editor-button.primary:hover { background: #67caff; }
@media (max-width: 680px) {
.settings-trigger { top: calc(var(--df-generated-header-height, 0px) + 7px); right: 60px; width: 40px; height: 40px; }
.settings-overlay { padding: 0; }
.settings-modal { width: 100%; height: 100dvh; border: 0; border-radius: 0; }
.settings-head { min-height: 68px; padding: 10px 14px; }
.settings-head h2 { font-size: 20px; }
.settings-body { padding: 12px; grid-template-columns: 1fr; grid-template-rows: auto minmax(0,1fr); }
.module-tabs { display: flex; gap: 7px; overflow-x: auto; }
.module-tabs h3 { display: none; }
.module-tab { width: auto; min-width: 118px; margin: 0; }
.settings-foot { padding: 10px 12px; flex-wrap: wrap; }
.editor-button { flex: 1; padding-inline: 10px; }
}
.skip-link { transform: translateY(calc(-100% - var(--df-generated-header-height, 0px) - 24px)); }
.skip-link:focus { transform: translateY(0); }
.overlay, .panel { z-index: 1200; }
.settings-overlay { z-index: 1300; }
</style>
</head>
<body>
<a class="skip-link" href="#feed">跳到动态</a>
<svg aria-hidden="true" width="0" height="0" style="position:absolute">
<symbol id="i-home" viewBox="0 0 24 24"><path d="m3 10 9-7 9 7v10a1 1 0 0 1-1 1h-5v-7H9v7H4a1 1 0 0 1-1-1Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
<symbol id="i-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-plus" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round"/></symbol>
<symbol id="i-heart" viewBox="0 0 24 24"><path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1.1-1.1a5.5 5.5 0 0 0-7.8 7.8l1.1 1.1L12 21l7.8-7.5 1.1-1.1a5.5 5.5 0 0 0-.1-7.8Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></symbol>
<symbol id="i-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-menu" viewBox="0 0 24 24"><path d="M4 7h16M4 12h16M4 17h16" 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-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.5m11.2-11.2 1.5-1.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
<symbol id="i-chevron" viewBox="0 0 24 24"><path d="m8 10 4 4 4-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-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-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-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-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-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-eye-off" viewBox="0 0 24 24"><path d="M3 3l18 18M10.6 10.6A2 2 0 0 0 13.4 13.4M9.9 4.2A10.5 10.5 0 0 1 21 12s-1.4 3-4.3 5.1M6.2 6.2C4.1 7.6 3 10 3 12c0 0 3 6 9 6 1 0 2-.2 2.8-.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></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-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-link" viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
<symbol id="i-close" viewBox="0 0 24 24"><path d="m6 6 12 12M18 6 6 18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
<symbol id="i-send" viewBox="0 0 24 24"><path d="m22 2-7 20-4-9-9-4Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><path d="M22 2 11 13" fill="none" stroke="currentColor" stroke-width="2"/></symbol>
<symbol id="i-settings" viewBox="0 0 24 24"><path d="M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7Z" fill="none" stroke="currentColor" stroke-width="2"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1-2.8 2.8-.1-.1a1.7 1.7 0 0 0-1.9-.3 1.7 1.7 0 0 0-1 1.6v.2h-4V21a1.7 1.7 0 0 0-1-1.6 1.7 1.7 0 0 0-1.9.3l-.1.1L4.2 17l.1-.1a1.7 1.7 0 0 0 .3-1.9A1.7 1.7 0 0 0 3 14H2.8v-4H3a1.7 1.7 0 0 0 1.6-1 1.7 1.7 0 0 0-.3-1.9L4.2 7 7 4.2l.1.1a1.7 1.7 0 0 0 1.9.3A1.7 1.7 0 0 0 10 3V2.8h4V3a1.7 1.7 0 0 0 1 1.6 1.7 1.7 0 0 0 1.9-.3l.1-.1L19.8 7l-.1.1a1.7 1.7 0 0 0-.3 1.9 1.7 1.7 0 0 0 1.6 1h.2v4H21a1.7 1.7 0 0 0-1.6 1Z" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></symbol>
</svg>
<header class="topbar"><a class="brand" id="brandLink" href="#feed"><span class="weave-mark"></span><span id="brandText">Threads</span></a><nav class="desktop-nav" aria-label="主导航"><button class="nav-button active" aria-label="首页"><svg><use href="#i-home"/></svg></button><button class="nav-button" data-panel="searchPanel" aria-label="搜索"><svg><use href="#i-search"/></svg></button><button class="nav-button" data-open-composer aria-label="创建动态"><svg><use href="#i-plus"/></svg></button><button class="nav-button" data-panel="activityPanel" aria-label="动态"><svg><use href="#i-heart"/></svg></button><button class="nav-button" aria-label="个人主页"><svg><use href="#i-user"/></svg></button></nav><div class="header-actions"><button class="round-button" id="themeToggle" aria-label="切换主题"><svg><use href="#i-moon"/></svg></button><button class="round-button" aria-label="菜单"><svg><use href="#i-menu"/></svg><span class="notification-dot"></span></button></div></header>
<header class="mobile-header"><span id="mobileUser"></span><span class="weave-mark"></span><button class="round-button" id="mobileTheme" aria-label="切换主题"><svg><use href="#i-moon"/></svg></button></header>
<button class="settings-trigger" id="openSettings" aria-label="编辑页面 JSON" title="编辑页面 JSON"><svg><use href="#i-settings"/></svg></button>
<main class="page-shell" id="feed">
<section class="feed-column" aria-label="对话动态">
<div class="feed-head"><h1 id="feedTitle">首页</h1><button class="feed-filter"><span id="feedFilter">为你推荐</span> <svg><use href="#i-chevron"/></svg></button></div>
<section class="card composer-card"><span id="composerUser"></span><button class="composer-button" id="composerButton" data-open-composer></button><button class="publish-inline" id="inlinePublish" data-open-composer></button></section>
<div class="feed-tabs" id="feedTabs"></div>
<div id="threadList"></div>
<section class="card empty-state" id="emptyState"><svg><use href="#i-search"/></svg><h2 id="emptyTitle"></h2><p id="emptyText"></p></section>
</section>
<aside class="right-column" aria-label="推荐内容">
<section class="side-card" id="profileSummary"></section>
<section class="side-card"><h2 id="followTitle"></h2><div id="suggestions"></div></section>
<section class="side-card"><h2 id="topicTitle"></h2><div id="topics"></div></section>
<footer class="side-footer" id="sideFooter"></footer>
</aside>
</main>
<nav class="mobile-nav" id="mobileNav" aria-label="移动端导航"></nav>
<div class="overlay" id="composeOverlay" aria-hidden="true"><section class="compose-modal" role="dialog" aria-modal="true" aria-labelledby="composeTitle"><header class="modal-head"><button class="close-button" id="closeCompose" aria-label="关闭发帖窗口"><svg><use href="#i-close"/></svg></button><h2 id="composeTitle"></h2><span style="width:44px"></span></header><div class="modal-body"><div class="modal-compose"><span id="modalUser"></span><div><strong id="modalUserName"></strong><label class="sr-only" for="composeText">串聊内容</label><textarea id="composeText" class="modal-textarea"></textarea></div></div><footer 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="添加表情"><svg><use href="#i-smile"/></svg></button><button class="tool-button" aria-label="添加链接"><svg><use href="#i-link"/></svg></button></div><div class="modal-actions"><span class="char-count" id="charCount"></span><button class="modal-publish" id="modalPublish" disabled></button></div></footer></div></section></div>
<section class="panel" id="searchPanel" aria-hidden="true"><header class="panel-head"><h2>搜索</h2><button class="close-button" data-close-panel aria-label="关闭搜索"><svg><use href="#i-close"/></svg></button></header><label class="panel-search"><span class="sr-only">搜索串聊</span><svg><use href="#i-search"/></svg><input id="searchInput" type="search" autocomplete="off" /></label><div class="search-hints"><strong>试试搜索</strong><p id="searchHints"></p></div></section>
<section class="panel" id="activityPanel" aria-hidden="true"><header class="panel-head"><h2 id="activityTitle"></h2><button class="close-button" data-close-panel aria-label="关闭动态"><svg><use href="#i-close"/></svg></button></header><div id="activityList"></div></section>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<div class="settings-overlay" id="settingsOverlay" aria-hidden="true"><section class="settings-modal" role="dialog" aria-modal="true" aria-labelledby="settingsTitle"><header class="settings-head"><div class="settings-head-copy"><span class="settings-kicker">THREADS TEMPLATE CONTROL</span><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-foot"><button class="editor-button" id="resetJson">恢复初始</button><button class="editor-button" id="copyJson">复制 JSON</button><button class="editor-button" id="downloadJson">下载 JSON</button><button class="editor-button primary" id="applyJson">应用并渲染</button></footer></section></div>
<script type="application/json" id="threadsPageData">__THREADS_PAGE_DATA__</script>
<script>__THREADS_PAGE_RUNTIME__</script>
</body>
</html>
@@ -0,0 +1,52 @@
# Threads 页面 JSON 契约
顶层必须是对象,并且完整包含 `site`、`navigation`、`composer`、`threads`、`recommendations`、`activity`。弹窗按这六个模块分别编辑,但「应用并渲染」会重新校验完整文档。
## 通用规则
- 所有 `colors` 都是两个 CSS 十六进制颜色,例如 `["#7257f5", "#d94fbd"]`。
- 互动量是非负数字;显示文案、名称和时间是非空字符串。
- 所有列表都有数量上限,避免单文件页面失控;数据文本不能包含 HTML。
## `site`
- `brand`、`pageTitle`、`description`:站点展示信息。
- `theme`:`auto`、`light` 或 `dark`。
- `currentUser`:`name`、`handle`、`initial`、`colors` 和 `stats`;`stats` 包含 `following`、`followers`、`threads`。
## `navigation`
- `feedTitle`、`feedFilter`、`searchPlaceholder`、`searchHints`、`copyright`:非空字符串。
- `tabs`:1–4 个标签。
- `mobileLabels`:恰好 5 个标签,顺序为首页、搜索、创建、动态、我。
- `footerLinks`:0–8 个页脚链接名称。
## `composer`
- `inlinePlaceholder`、`dialogTitle`、`textareaPlaceholder`、`publishLabel`:非空字符串。
- `maxLength`:1–2000;`replyMaxLength`:1–500。
## `threads`
- `emptyTitle`、`emptyText`:搜索无结果时文案。
- `items`:1–30 条,`id` 唯一。
- 每项包含 `author`、`time`、`text`、`metrics`、`followable`、`replies`、`preview`;`media`、`quote` 可为 `null`。
- `author` 包含 `name`、`handle`、`initial`、`colors`、`verified`。
- `media.type` 可为内置 `autumn-grid`,也可为 `image`、`video`、`webpage`。
- 图片使用 `{type:"image", mediaUrl, alt, pageUrl?}`;视频使用 `{type:"video", mediaUrl, posterUrl?, alt?, pageUrl?}`;网页使用 `{type:"webpage", pageUrl, title, description?, mediaUrl?, embed?}`。URL 只接受 `http(s)`;图片和视频也允许对应的 `data:` URL。
- `quote` 包含 `name`、`handle`、`initial`、`colors`、`text`。
- `metrics` 包含非负 `likes`、`replies`、`reposts`。
- `replies` 最多 8 条,每项包含作者、时间、正文和同样的 `metrics`。
## `recommendations`
- `followTitle`、`topicTitle`:侧栏标题。
- `people`:0–20 项,每项 `{name, handle, initial, colors}`。
- `topics`:0–20 项,每项 `{meta, title, count}`。
## `activity`
- `title`:动态面板标题。
- `items`:0–30 项,每项包含 `name`、`initial`、`colors`、`text`、`time`、`followable`。
JSON 使用双引号,不允许注释、Markdown 围栏或尾逗号。`assets/default-data.json` 只是结构和演示内容,不是事实来源。
@@ -0,0 +1,356 @@
#!/usr/bin/env python3
"""Generate a complete Threads page from one compact high-level JSON spec."""
from __future__ import annotations
import argparse
import copy
import json
import sys
from collections.abc import Mapping
from pathlib import Path
import render_threads_page as renderer
REPLY_NAMES = ("林夏", "周野", "陈默", "顾念", "沈言", "宋可心", "许知夏", "苏小鹿")
REPLY_COLORS = (
("#5662f6", "#9f45d8"),
("#15a88b", "#2e88cc"),
("#f97316", "#db2777"),
("#0f7d78", "#51b35e"),
)
REPLY_TEMPLATES = (
"关于“{topic}”,这个表达很有意思。",
"我也在关注“{topic}”,期待看到后续更新。",
"从另一个角度看,“{topic}”还有很多值得讨论的细节。",
"这条串文把“{topic}”说得很清楚。",
"先收藏,也想听听大家对“{topic}”的看法。",
"内容不长,但“{topic}”这个重点已经交代得很完整。",
"这正是我最近在思考的“{topic}”问题。",
"希望评论区可以继续理性讨论“{topic}”。",
)
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 _boolean(value: object, path: str, *, default: bool = False) -> bool:
if value is None:
return default
if not isinstance(value, bool):
raise renderer.DataValidationError(f"{path} must be a boolean")
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 _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 _reply_objects(
count: int,
topics: list[str],
custom_replies: list[object],
) -> list[dict[str, object]]:
if not 0 <= count <= 8:
raise renderer.DataValidationError("displayReplyCount must be between 0 and 8")
if len(custom_replies) > count:
raise renderer.DataValidationError("displayReplyCount cannot be smaller than replies.length")
replies: list[dict[str, object]] = []
for index in range(count):
name = REPLY_NAMES[index % len(REPLY_NAMES)]
reply: dict[str, object] = {
"author": {
"name": name,
"initial": name[:1],
"colors": list(REPLY_COLORS[index % len(REPLY_COLORS)]),
},
"time": f"{index + 1} 分钟",
"text": REPLY_TEMPLATES[index % len(REPLY_TEMPLATES)].format(topic=topics[index % len(topics)]),
"metrics": {
"likes": max(0, (count - index) * 9),
"replies": index % 4,
"reposts": index % 2,
},
}
if index < len(custom_replies):
custom = custom_replies[index]
if isinstance(custom, str):
reply["text"] = custom.strip()
elif isinstance(custom, Mapping):
reply["text"] = _string(
custom.get("text"),
f"replies[{index}].text",
required=True,
)
if "author" in custom:
author_name = _string(
custom.get("author"),
f"replies[{index}].author",
required=True,
)
reply["author"]["name"] = author_name
reply["author"]["initial"] = author_name[:1]
if "time" in custom:
reply["time"] = _string(
custom.get("time"),
f"replies[{index}].time",
required=True,
)
metrics = reply["metrics"]
for key in ("likes", "replies", "reposts"):
if key in custom:
metrics[key] = _integer(
custom.get(key),
f"replies[{index}].{key}",
)
else:
raise renderer.DataValidationError(f"replies[{index}] must be a string or object")
_require_chinese(str(reply["text"]), f"replies[{index}].text")
replies.append(reply)
return replies
def _media(value: object, path: str) -> dict[str, object] | None:
if value is None:
return None
if not isinstance(value, Mapping):
raise renderer.DataValidationError(f"{path} must be an object or null")
media_type = _string(value.get("type"), f"{path}.type") or "image"
if media_type not in {"image", "video", "webpage"}:
raise renderer.DataValidationError(f"{path}.type must be image, video, or webpage")
media: dict[str, object] = {"type": media_type}
if media_type == "webpage":
media["pageUrl"] = _string(
value.get("pageUrl"),
f"{path}.pageUrl",
required=True,
)
media["title"] = _string(
value.get("title"),
f"{path}.title",
required=True,
)
media["description"] = _string(
value.get("description"),
f"{path}.description",
required=True,
)
else:
media["mediaUrl"] = _string(
value.get("url"),
f"{path}.url",
required=True,
)
media["alt"] = _string(value.get("alt"), f"{path}.alt") or "用户提供的媒体"
if value.get("pageUrl"):
media["pageUrl"] = _string(value.get("pageUrl"), f"{path}.pageUrl")
return media
def build_document(spec: dict[str, object]) -> dict[str, object]:
allowed = {
"accountName",
"handle",
"verified",
"description",
"pageTitle",
"topic",
"replyTopics",
"displayReplyCount",
"totalReplyCount",
"replies",
"postText",
"posts",
"media",
"likes",
"reposts",
"following",
"followers",
"threadCount",
}
unknown = sorted(set(spec) - allowed)
if unknown:
raise renderer.DataValidationError("Unknown spec keys: " + ", ".join(unknown))
account_name = _string(spec.get("accountName"), "accountName", required=True)
handle = _string(spec.get("handle"), "handle") or "@threads_user"
topic = _string(spec.get("topic"), "topic") or account_name
reply_topics = _strings(spec.get("replyTopics"), "replyTopics") or [topic]
raw_posts = spec.get("posts")
if raw_posts is None:
raw_posts = [
{
"text": _string(spec.get("postText"), "postText", required=True),
"media": spec.get("media") if "media" in spec else "__example__",
"likes": spec.get("likes", 0),
"reposts": spec.get("reposts", 0),
}
]
if not isinstance(raw_posts, list) or not 1 <= len(raw_posts) <= 10:
raise renderer.DataValidationError("posts must contain between 1 and 10 objects")
if not all(isinstance(item, Mapping) for item in raw_posts):
raise renderer.DataValidationError("posts must contain only objects")
data = renderer._read_json(renderer.DEFAULT_DATA_PATH)
defaults = data["threads"]["items"]
custom_replies = spec.get("replies", [])
if not isinstance(custom_replies, list):
raise renderer.DataValidationError("replies must be an array")
display_reply_count = _integer(
spec.get("displayReplyCount"),
"displayReplyCount",
default=max(3, len(custom_replies)),
)
total_reply_count = _integer(
spec.get("totalReplyCount"),
"totalReplyCount",
default=display_reply_count,
)
if total_reply_count < display_reply_count:
raise renderer.DataValidationError("totalReplyCount cannot be smaller than displayReplyCount")
items: list[dict[str, object]] = []
for index, raw_post in enumerate(raw_posts):
post = copy.deepcopy(defaults[index % len(defaults)])
text = _string(
raw_post.get("text"),
f"posts[{index}].text",
required=True,
)
_require_chinese(text, f"posts[{index}].text")
author_name = _string(raw_post.get("authorName"), f"posts[{index}].authorName") or account_name
post["id"] = f"thread-{index + 1:03d}"
post["author"] = {
"name": author_name,
"handle": _string(raw_post.get("handle"), f"posts[{index}].handle") or handle,
"initial": author_name[:1],
"colors": post["author"]["colors"],
"verified": _boolean(
raw_post.get("verified"),
f"posts[{index}].verified",
default=_boolean(spec.get("verified"), "verified"),
),
}
post["time"] = _string(raw_post.get("time"), f"posts[{index}].time") or "刚刚"
post["text"] = text
post["followable"] = _boolean(
raw_post.get("followable"),
f"posts[{index}].followable",
)
post["quote"] = None
if "media" in raw_post and raw_post.get("media") != "__example__":
post["media"] = _media(raw_post.get("media"), f"posts[{index}].media")
if index == 0:
replies = _reply_objects(display_reply_count, reply_topics, custom_replies)
replies_metric = total_reply_count
else:
replies = []
replies_metric = _integer(
raw_post.get("totalReplyCount"),
f"posts[{index}].totalReplyCount",
)
post["replies"] = replies
post["metrics"] = {
"likes": _integer(raw_post.get("likes"), f"posts[{index}].likes"),
"replies": replies_metric,
"reposts": _integer(raw_post.get("reposts"), f"posts[{index}].reposts"),
}
post["preview"] = f"查看全部 {replies_metric} 条回复"
items.append(post)
data["site"]["pageTitle"] = _string(spec.get("pageTitle"), "pageTitle") or f"Threads · {account_name}"
data["site"]["description"] = _string(spec.get("description"), "description") or f"{account_name} 的 Threads 中文页面。"
data["site"]["currentUser"].update(
{
"name": account_name,
"handle": handle,
"initial": account_name[:1],
"stats": {
"following": str(spec.get("following", "0")),
"followers": str(spec.get("followers", "0")),
"threads": str(spec.get("threadCount", len(items))),
},
}
)
data["threads"]["items"] = items
return data
def _next_paths(output_dir: Path) -> tuple[Path, Path]:
for index in range(1, 1001):
stem = "threads-page" if index == 1 else f"threads-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 main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--spec", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
args = parser.parse_args(argv)
try:
data = build_document(_read_spec(args.spec))
summary = renderer.validate_document(data)
rendered = renderer.render_document(
data,
renderer.TEMPLATE_PATH.read_text(encoding="utf-8"),
renderer.RUNTIME_PATH.read_text(encoding="utf-8"),
)
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-threads-page", "error": str(exc)})
return 2
renderer._emit(
{
"status": "ok",
"action": "fast-threads-page",
"data": str(data_path),
"html": str(html_path),
**summary,
}
)
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,540 @@
#!/usr/bin/env python3
"""Validate Threads page data and inject it into the bundled HTML template."""
from __future__ import annotations
import argparse
import html as html_lib
import json
import re
import sys
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
SKILL_ROOT = Path(__file__).resolve().parent.parent
ASSETS_DIR = SKILL_ROOT / "assets"
DEFAULT_DATA_PATH = ASSETS_DIR / "default-data.json"
TEMPLATE_PATH = ASSETS_DIR / "threads-template.html"
RUNTIME_PATH = ASSETS_DIR / "threads-runtime.js"
DATA_MARKER = "__THREADS_PAGE_DATA__"
RUNTIME_MARKER = "__THREADS_PAGE_RUNTIME__"
TITLE_RE = re.compile(r"<title>[^<]*</title>", re.IGNORECASE)
MODULES = (
"site",
"navigation",
"composer",
"threads",
"recommendations",
"activity",
)
THEMES = {"auto", "light", "dark"}
MEDIA_TYPES = {"autumn-grid", "image", "video", "webpage"}
REMOTE_MEDIA_TYPES = {"image", "video", "webpage"}
class DataValidationError(ValueError):
"""Raised when the Threads 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 _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 _integer_range(
value: Any,
path: str,
minimum: int,
maximum: int,
errors: list[str],
) -> None:
if (
not isinstance(value, int)
or isinstance(value, bool)
or not minimum <= value <= maximum
):
errors.append(f"{path} must be an integer from {minimum} to {maximum}")
def _boolean(value: Any, path: str, errors: list[str]) -> None:
if not isinstance(value, bool):
errors.append(f"{path} must be a boolean")
def _colors(value: Any, path: str, errors: list[str]) -> None:
if (
not isinstance(value, list)
or len(value) != 2
or not all(isinstance(color, str) for color in value)
):
errors.append(f"{path} must contain exactly two color strings")
def _person(
value: Any,
path: str,
errors: list[str],
*,
handle: bool,
) -> dict[str, Any]:
person = _mapping(value, path, errors)
keys = ["name", "initial"]
if handle:
keys.append("handle")
for key in keys:
_non_empty_string(person.get(key), f"{path}.{key}", errors)
_colors(person.get("colors"), f"{path}.colors", errors)
return person
def _metrics(value: Any, path: str, errors: list[str]) -> None:
metrics = _mapping(value, path, errors)
for key in ("likes", "replies", "reposts"):
_non_negative_number(metrics.get(key), f"{path}.{key}", errors)
def validate_document(data: dict[str, Any]) -> dict[str, Any]:
errors: list[str] = []
for module in MODULES:
if module not in data:
errors.append(f"Missing top-level module: {module}")
site = _mapping(data.get("site"), "site", errors)
for key in ("brand", "pageTitle", "description"):
_non_empty_string(site.get(key), f"site.{key}", errors)
if site.get("theme") not in THEMES:
errors.append("site.theme must be one of: auto, dark, light")
current_user = _person(
site.get("currentUser"),
"site.currentUser",
errors,
handle=True,
)
stats = _mapping(
current_user.get("stats"),
"site.currentUser.stats",
errors,
)
for key in ("following", "followers", "threads"):
_non_empty_string(
stats.get(key),
f"site.currentUser.stats.{key}",
errors,
)
navigation = _mapping(data.get("navigation"), "navigation", errors)
for key in (
"feedTitle",
"feedFilter",
"searchPlaceholder",
"searchHints",
"copyright",
):
_non_empty_string(navigation.get(key), f"navigation.{key}", errors)
tabs = _array(navigation.get("tabs"), "navigation.tabs", errors, limit=4)
if not tabs:
errors.append("navigation.tabs must contain at least one item")
for index, label in enumerate(tabs):
_non_empty_string(label, f"navigation.tabs[{index}]", errors)
mobile_labels = _array(
navigation.get("mobileLabels"),
"navigation.mobileLabels",
errors,
limit=5,
)
if len(mobile_labels) != 5:
errors.append("navigation.mobileLabels must contain exactly 5 items")
for index, label in enumerate(mobile_labels):
_non_empty_string(
label,
f"navigation.mobileLabels[{index}]",
errors,
)
footer_links = _array(
navigation.get("footerLinks"),
"navigation.footerLinks",
errors,
limit=8,
)
for index, label in enumerate(footer_links):
_non_empty_string(
label,
f"navigation.footerLinks[{index}]",
errors,
)
composer = _mapping(data.get("composer"), "composer", errors)
for key in (
"inlinePlaceholder",
"dialogTitle",
"textareaPlaceholder",
"publishLabel",
):
_non_empty_string(composer.get(key), f"composer.{key}", errors)
_integer_range(
composer.get("maxLength"),
"composer.maxLength",
1,
2000,
errors,
)
_integer_range(
composer.get("replyMaxLength"),
"composer.replyMaxLength",
1,
500,
errors,
)
threads = _mapping(data.get("threads"), "threads", errors)
for key in ("emptyTitle", "emptyText"):
_non_empty_string(threads.get(key), f"threads.{key}", errors)
thread_items = _array(
threads.get("items"),
"threads.items",
errors,
limit=30,
)
if not thread_items:
errors.append("threads.items must contain at least one thread")
thread_ids: set[str] = set()
reply_count = 0
for index, value in enumerate(thread_items):
path = f"threads.items[{index}]"
thread = _mapping(value, path, errors)
thread_id = thread.get("id")
_non_empty_string(thread_id, f"{path}.id", errors)
if isinstance(thread_id, str):
if thread_id in thread_ids:
errors.append(f"{path}.id must be unique")
thread_ids.add(thread_id)
author = _person(
thread.get("author"),
f"{path}.author",
errors,
handle=True,
)
_boolean(
author.get("verified"),
f"{path}.author.verified",
errors,
)
for key in ("time", "text", "preview"):
_non_empty_string(thread.get(key), f"{path}.{key}", errors)
_boolean(thread.get("followable"), f"{path}.followable", errors)
_metrics(thread.get("metrics"), f"{path}.metrics", errors)
media = thread.get("media")
if media is not None:
media_data = _mapping(media, f"{path}.media", errors)
if media_data.get("type") not in MEDIA_TYPES:
errors.append(
f"{path}.media.type must be one of: "
f"{', '.join(sorted(MEDIA_TYPES))}"
)
_validate_remote_media(media_data, f"threads.items[{index}].media", errors)
if "label" in media_data:
_non_empty_string(
media_data.get("label"),
f"{path}.media.label",
errors,
)
quote = thread.get("quote")
if quote is not None:
quote_data = _person(
quote,
f"{path}.quote",
errors,
handle=True,
)
_non_empty_string(
quote_data.get("text"),
f"{path}.quote.text",
errors,
)
replies = _array(
thread.get("replies"),
f"{path}.replies",
errors,
limit=8,
)
reply_count += len(replies)
for reply_index, reply_value in enumerate(replies):
reply_path = f"{path}.replies[{reply_index}]"
reply = _mapping(reply_value, reply_path, errors)
_person(
reply.get("author"),
f"{reply_path}.author",
errors,
handle=False,
)
for key in ("time", "text"):
_non_empty_string(
reply.get(key),
f"{reply_path}.{key}",
errors,
)
_metrics(reply.get("metrics"), f"{reply_path}.metrics", errors)
recommendations = _mapping(
data.get("recommendations"),
"recommendations",
errors,
)
for key in ("followTitle", "topicTitle"):
_non_empty_string(
recommendations.get(key),
f"recommendations.{key}",
errors,
)
people = _array(
recommendations.get("people"),
"recommendations.people",
errors,
limit=20,
)
for index, value in enumerate(people):
_person(
value,
f"recommendations.people[{index}]",
errors,
handle=True,
)
topics = _array(
recommendations.get("topics"),
"recommendations.topics",
errors,
limit=20,
)
for index, value in enumerate(topics):
topic = _mapping(
value,
f"recommendations.topics[{index}]",
errors,
)
for key in ("meta", "title", "count"):
_non_empty_string(
topic.get(key),
f"recommendations.topics[{index}].{key}",
errors,
)
activity = _mapping(data.get("activity"), "activity", errors)
_non_empty_string(activity.get("title"), "activity.title", errors)
activity_items = _array(
activity.get("items"),
"activity.items",
errors,
limit=30,
)
for index, value in enumerate(activity_items):
path = f"activity.items[{index}]"
item = _person(value, path, errors, handle=False)
for key in ("text", "time"):
_non_empty_string(item.get(key), f"{path}.{key}", errors)
_boolean(item.get("followable"), f"{path}.followable", errors)
if errors:
raise DataValidationError("; ".join(errors))
return {
"modules": list(MODULES),
"counts": {
"threads": len(thread_items),
"replies": reply_count,
"people": len(people),
"topics": len(topics),
"activity": len(activity_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())