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,83 @@
---
name: xinhua-page-generator
description: 生成或绘制新华社、新华网及新华社风格的可交付中文通讯社新闻门户 HTML;仅在用户明确要求新华社网页、新华网风格新闻首页或点名本技能时使用。先把材料或检索结果整理成十模块 JSON,再用内置模板确定性渲染,保留右上角模块化 JSON 编辑弹窗。
allowed-tools:
- read_file
- write_file
- bash
- present_files
- web_search
---
# 新华社页面生成器
本技能使用固定模板生成单文件新华社风格中文通讯社门户。模型只负责材料收集和 JSON,禁止重新手写页面结构、CSS 或运行时脚本。最终页面自带右上角设置按钮;用户可在弹窗中按模块编辑 JSON,并通过「应用并渲染」即时更新页面。
编辑弹窗还提供“上传图片/视频”:先把光标放进目标报道、帖子、视频或带 `visual`/`media` 的内容对象,上传文件会转换为 `data:` 地址并写入该对象的 `media` 字段。不设文件大小拦截;较大文件可能超过浏览器本地缓存容量,应同时下载 JSON 留存。
页面中已由 `media` 数据渲染的图片和视频还带悬浮上传图标:鼠标移入媒体后点击可任选图片或视频并直接替换,文件的实际类型会自动写入新的 `media.type`,结果同步写回页面 JSON 与浏览器缓存。头像、Logo 和无法映射回 JSON 的装饰图不会显示该入口;不按原媒体类型限制,也不设置文件大小拦截。
默认视觉直接复用模板原有的示例图:不要调用图像生成工具,不要让模型重新生成、拼装或内嵌新的内容型 SVG,也不要为了寻找“标准配图”延长检索。用户没有提供可直接使用的图片/视频且聚焦检索未得到可靠直链时,保留默认 JSON 的 `visual` 或内置视觉类型;这些是模板自带的静态示例,调用技能时不重新绘制。不要把大段 base64 示例图重复写进 JSON,图不合适时由用户在成品页面悬浮上传替换。
## 触发边界
- 用户明确说「生成/画/制作新华社网页」「新华网风格新闻首页」「新华社风格通讯社门户」或点名 `xinhua-page-generator` 时使用。
- 仅讨论新华社、总结新华社报道、分析新闻机构或普通文本中出现新华社时不要使用。
- 这是新华社风格单页高密度新闻门户,不改用 CNN、BBC 或通用多页门户模板。
## 极速工作流(默认)
页面结构已经固定。完成必要检索或材料整理后,模型只写一份小型规格 JSON;未写字段继续使用模板默认数据与示例视觉,脚本在一次进程内合并、校验并渲染。
1. 用 `write_file` 创建 `/mnt/user-data/outputs/xinhua-page-spec.json`。直接写模块对象会递归合并;修改现有数组项优先用 `$set`:
```json
{"site":{"pageTitle":"新华社 · 中文新闻专题"},"$set":{"headline.kicker":"新华社全媒头条","headline.title":"中文头条","headline.summary":"中文摘要"}}
```
2. 只执行一次 `python /mnt/skills/public/xinhua-page-generator/scripts/fast_page.py --spec /mnt/user-data/outputs/xinhua-page-spec.json --output-dir /mnt/user-data/outputs`。
3. stdout 为 `status: ok` 后立即用 `present_files` 交付完整 JSON 与 HTML,最终只回复一句完成说明。
规格只允许本技能十个模块和 `$set`;路径必须指向默认 JSON 的已存在字段。所有读者可见内容保持简体中文。未提供媒体直链时保留模板示例视觉。禁止读取默认数据、契约、模板、运行时或脚本源码,禁止 `--help`、独立 `init/validate/render`、生成后打补丁、临时脚本和冗长过程说明。规格报错时只修正一次并重跑。只有用户明确要求改变模块结构或批量重建完整数组时,才使用下面的完整工作流。
## 完整工作流(仅限结构改造)
1. 读取当前会话材料、上传附件和已有产物,确定站点标识、导航、报道专集、头条、焦点图、要闻分类、专栏专题、地方联播、行业频道、媒体矩阵和页脚。
2. 用户要求基于公开资料、主题涉及近期事件,或明确要求检索时,先做聚焦检索并将可靠事实整理为新闻文案;用户明确说不要检索时不得联网。没有材料时使用中性示例,不把模拟时间、直播或节目状态描述成实时事实。
3. 初始化新的完整 JSON:
```text
python /mnt/skills/public/xinhua-page-generator/scripts/render_xinhua_page.py init --output /mnt/user-data/outputs/xinhua-page-data.json
```
4. 只修改 JSON。十个顶层模块必须全部保留:`site`、`navigation`、`specials`、`headline`、`focus`、`features`、`channels`、`local`、`services`、`footer`。字段不确定时读取 [references/data-schema.md](references/data-schema.md)。
5. 校验 JSON:
```text
python /mnt/skills/public/xinhua-page-generator/scripts/render_xinhua_page.py validate --input /mnt/user-data/outputs/xinhua-page-data.json
```
6. 确定性渲染到 `outputs/`:
```text
python /mnt/skills/public/xinhua-page-generator/scripts/render_xinhua_page.py render --input /mnt/user-data/outputs/xinhua-page-data.json --output /mnt/user-data/outputs/xinhua-page.html
```
7. 检查 stdout 的 `status` 为 `ok`、HTML 存在且占位符已经消失,再用 `present_files` 同时交付 HTML 与源 JSON。不要在聊天中粘贴完整 HTML。
## 内容映射
- 机构名称、英文名、口号和主题放入 `site`;多语种入口、主导航和移动抽屉放入 `navigation`。
- 报道专集、焦点图集和最新播报放入 `specials`;唯一的总头条放入 `headline`。
- 时政、财经、国际等可切换要闻放入 `focus.tabs`;专栏、专题、记者工作室放入 `features`。
- 网评、访谈、视频与行业频道放入 `channels`;地方省份数据放入 `local.provinces`。
- 媒体矩阵和早报订阅放入 `services`;机构链接与版权放入 `footer`。
- `visual` 和 `icon` 继续作为内置后备;具有视觉的对象可增加受校验的 `media`(`image`、`video`、`webpage`)替换当前视觉。所有外部文本由模板转义,不得包含 HTML、脚本或直接 iframe。
## 重要约束
- 只编辑 JSON,不修改 `assets/xinhua-template.html` 或 `assets/xinhua-runtime.js`,不复制模板后手改 DOM。
- 初始化与渲染默认拒绝覆盖已有文件;路径存在时换新文件名,不删除旧产物。
- 页面结构、样式和脚本完全自包含,不依赖新华社 API、CDN 或 npm;仅当 JSON 明确提供受校验的媒体 URL 时加载图片、视频或网页。
- 保留多语种顶栏、蓝色主导航、报道专集、焦点图、要闻分类、地方切换、媒体矩阵、直播弹窗、字幕和订阅反馈。
- 浏览器缓存以初始 JSON 指纹隔离;沙箱禁止持久存储时必须继续使用内嵌 JSON 正常渲染。
@@ -0,0 +1,219 @@
{
"site": {
"brandName": "新华社",
"brandEnglish": "XINHUA NEWS AGENCY",
"pageTitle": "新华社|记录时代 连接世界",
"description": "新华社风格中文通讯社新闻门户示例页面。",
"theme": "light",
"motto": "记录时代 · 连接世界",
"clientLabel": "客户端"
},
"navigation": {
"networkLeft": [
{"label": "关于新华社", "href": "#about"},
{"label": "English", "href": "#languages"},
{"label": "Español", "href": "#languages"},
{"label": "Français", "href": "#languages"},
{"label": "日本語", "href": "#languages"}
],
"networkRight": [
{"label": "新华报刊", "href": "#papers"},
{"label": "地方频道", "href": "#local"},
{"label": "网站无障碍", "href": "#services"}
],
"primary": [
{"label": "首页", "href": "#top"},
{"label": "时政", "href": "#focus"},
{"label": "财经", "href": "#focus"},
{"label": "国际", "href": "#focus"},
{"label": "评论", "href": "#features"},
{"label": "地方", "href": "#local"},
{"label": "科技", "href": "#industry"},
{"label": "教育", "href": "#industry"},
{"label": "文化", "href": "#industry"},
{"label": "健康", "href": "#industry"},
{"label": "视频", "href": "#media"},
{"label": "更多", "href": "#services"}
],
"drawer": [
{"label": "要闻聚焦", "href": "#focus"},
{"label": "名专栏", "href": "#features"},
{"label": "热点专题", "href": "#topics"},
{"label": "记者工作室", "href": "#studios"},
{"label": "地方新闻", "href": "#local"},
{"label": "行业频道", "href": "#industry"},
{"label": "视频直播", "href": "#media"},
{"label": "媒体矩阵", "href": "#services"}
],
"searchLabel": "站内搜索",
"searchPlaceholder": "输入标题、栏目或关键词",
"searchButton": "搜索"
},
"specials": {
"seriesTitle": "报道专集",
"seriesEnglish": "SPECIALS",
"seriesItems": [
{"id": "series-1", "title": "以实干打开发展新天地", "href": "#features"},
{"id": "series-2", "title": "学习手记:把群众小事办实", "href": "#features"},
{"id": "series-3", "title": "中国经济样本观察", "href": "#topics"},
{"id": "series-4", "title": "走进高质量发展一线", "href": "#local"}
],
"spotlightLabel": "焦点图",
"spotlightItems": [
{"id": "spot-1", "title": "金秋大地铺展丰收画卷", "tag": "镜观中国", "visual": "harvest"},
{"id": "spot-2", "title": "跨越山海的高铁新通道", "tag": "", "visual": "railway"},
{"id": "spot-3", "title": "卫星视角下的绿色能源网", "tag": "", "visual": "satellite"},
{"id": "spot-4", "title": "老街巷里的文化新空间", "tag": "", "visual": "culture"},
{"id": "spot-5", "title": "候鸟归来,湿地重现生机", "tag": "", "visual": "wetland"}
],
"latest": {
"label": "最新播报",
"title": "综合交通枢纽融合发展规划发布,首批示范项目同步启动",
"time": "10:28",
"href": "#focus"
}
},
"headline": {
"kicker": "新华社全媒头条",
"title": "向新而行,中国经济在开放合作中积蓄澎湃动能",
"summary": "创新链与产业链深度融合,绿色转型和数字经济持续拓展发展新空间",
"links": [
{"label": "重大项目加快形成实物工作量", "href": "#focus"},
{"label": "县域产业焕发新活力", "href": "#local"},
{"label": "服务消费释放新潜能", "href": "#topics"}
]
},
"focus": {
"title": "要闻聚焦",
"moreLabel": "进入新闻中心 →",
"tabs": [
{
"id": "politics",
"label": "时政",
"columns": [
{"id": "pol-1", "leadTitle": "重大工程建设跑出惠民利民加速度", "summary": "从交通网络到公共服务,项目建设更重实效。", "visual": "city", "links": ["基层治理新实践让服务更加精准", "政策解读:这些民生举措值得关注", "记者一线观察最新进展"]},
{"id": "pol-2", "leadTitle": "绿色转型为高质量发展增添新底色", "summary": "重点行业节能改造持续推进。", "visual": "green", "links": ["法治护航新业态健康有序发展", "开放合作释放更大发展潜力", "公共服务清单加快落地"]},
{"id": "pol-3", "leadTitle": "民生保障网络向基层延伸", "summary": "便民服务正以更精准的方式抵达社区。", "visual": "technology", "links": ["养老服务站覆盖更多街道", "就业服务平台持续升级", "基层医疗资源扩容提质"]}
]
},
{
"id": "finance",
"label": "财经",
"columns": [
{"id": "fin-1", "leadTitle": "经济运行延续稳中有进态势", "summary": "消费、投资与外贸新动能不断累积。", "visual": "economy", "links": ["金融服务实体经济质效持续提升", "制造业数字化转型进入深水区", "服务消费拓展发展空间"]},
{"id": "fin-2", "leadTitle": "区域物流指数连续三月回升", "summary": "高效运输网络支撑产业链稳定运行。", "visual": "city", "links": ["县域经济展现蓬勃创新活力", "专精特新企业加速成长", "开放平台集聚全球资源"]},
{"id": "fin-3", "leadTitle": "绿色金融支持转型项目落地", "summary": "长期资本更加关注产业升级与可持续发展。", "visual": "green", "links": ["科技企业融资渠道扩容", "消费新场景不断涌现", "跨境电商释放市场潜力"]}
]
},
{
"id": "world",
"label": "国际",
"columns": [
{"id": "world-1", "leadTitle": "全球城市共议韧性与可持续未来", "summary": "交通、能源与公共空间成为共同议题。", "visual": "world", "links": ["跨境铁路为区域合作注入新动力", "国际社会呼吁加强气候行动协作", "全球科技合作聚焦开放科学"]},
{"id": "world-2", "leadTitle": "文化遗产保护迎来数字化工具", "summary": "高精度扫描让珍贵记忆得以延续。", "visual": "technology", "links": ["南南合作书写互利共赢新故事", "青年交流项目连接更多城市", "公共卫生合作机制持续完善"]},
{"id": "world-3", "leadTitle": "开放合作成为国际会议高频词", "summary": "多边协作仍是应对共同挑战的重要路径。", "visual": "city", "links": ["区域贸易便利化取得新进展", "绿色技术共享项目启动", "国际志愿服务网络扩展"]}
]
}
]
},
"features": {
"columnTitle": "新华名专栏",
"columnSubtitle": "思想 · 现场 · 观察",
"tags": ["全媒头条", "新华视点", "记者手记", "国际观察", "财经观察", "文化新观察", "民生直通车"],
"articles": [
{"id": "feature-1", "title": "发展新质生产力,关键在因地制宜", "meta": "新华时评 · 32分钟前"},
{"id": "feature-2", "title": "一座城市如何让旧空间长出新故事", "meta": "文化新观察 · 1小时前"},
{"id": "feature-3", "title": "从一条铁路看区域合作的韧性", "meta": "国际观察 · 2小时前"},
{"id": "feature-4", "title": "在田野里感受数字农业的脉动", "meta": "记者手记 · 3小时前"},
{"id": "feature-5", "title": "社区养老服务如何更精准抵达", "meta": "民生直通车 · 4小时前"},
{"id": "feature-6", "title": "制造业投资释放了哪些新信号", "meta": "财经观察 · 5小时前"}
],
"topicsTitle": "热点专题",
"topicsMoreLabel": "全部专题 →",
"topics": [
{"id": "topic-1", "title": "开局新篇章", "summary": "聚焦重点项目与发展新动能"},
{"id": "topic-2", "title": "文化中国行", "summary": "在行走中读懂历史与传承"},
{"id": "topic-3", "title": "活力中国调研行", "summary": "来自产业与基层的一线样本"},
{"id": "topic-4", "title": "美丽中国", "summary": "记录生态文明建设新实践"},
{"id": "topic-5", "title": "城市更新", "summary": "让生活空间更有温度"},
{"id": "topic-6", "title": "乡村振兴", "summary": "丰收图景里的现代化故事"},
{"id": "topic-7", "title": "全球连线", "summary": "从世界看中国,从中国看世界"},
{"id": "topic-8", "title": "科创未来", "summary": "走进实验室与制造现场"}
],
"studiosTitle": "记者工作室",
"studiosMoreLabel": "认识更多记者 →",
"studios": [
{"id": "studio-1", "initial": "林", "name": "林澄工作室", "bio": "在重大工程一线,记录建设者的每一步。"},
{"id": "studio-2", "initial": "许", "name": "许言工作室", "bio": "用数据与图表,把复杂问题讲明白。"},
{"id": "studio-3", "initial": "周", "name": "周观工作室", "bio": "观察世界变局中的合作与连接。"},
{"id": "studio-4", "initial": "宁", "name": "宁禾工作室", "bio": "走进县城乡村,捕捉生活的新变化。"}
]
},
"channels": {
"editorialColumns": [
{"id": "commentary", "accent": "新华", "title": "网评", "visual": "commentary", "feature": "让创新成果更好抵达产业一线", "links": ["公共文化空间要留住烟火气", "把“便民清单”变成“幸福账单”", "开放合作是应对挑战的必答题"], "live": false},
{"id": "interview", "accent": "新华", "title": "访谈", "visual": "interview", "feature": "数字技术如何重塑公共服务体验", "links": ["对话城市规划师:更新不是简单翻新", "科学家解读新一代气象卫星", "大国工匠谈智能制造人才"], "live": false},
{"id": "video", "accent": "新华", "title": "视频", "visual": "video", "feature": "直播:走进综合交通枢纽建设现场", "links": ["微纪录片:一粒种子的旅程", "一分钟看懂城市更新", "卫星视角记录山河新貌"], "live": true}
],
"industryTitle": "行业频道",
"industryMoreLabel": "更多频道 →",
"industries": [
{"id": "education", "title": "教育", "items": ["职业教育产教融合新实践", "校园美育打开更大空间", "青年科研团队加速成长"]},
{"id": "technology", "title": "科技", "items": ["深空科学数据开放共享", "人工智能走进实验室", "新材料连接制造未来"]},
{"id": "finance", "title": "金融", "items": ["金融服务实体经济提质", "长期资金加快入市步伐", "普惠金融覆盖更多小微"]},
{"id": "auto", "title": "汽车", "items": ["新能源汽车驶向全球市场", "智能座舱体验持续升级", "充换电网络进一步完善"]},
{"id": "health", "title": "健康", "items": ["秋冬季科学防护指南", "基层医疗服务提质扩容", "银龄健康课堂开讲"]},
{"id": "culture", "title": "文化", "items": ["博物馆里的沉浸新体验", "古籍修复让文明延续", "青年创作者讲述中国故事"]},
{"id": "rural", "title": "乡村振兴", "items": ["特色产业点亮和美乡村", "冷链物流护航新鲜农产", "数字工具服务田间生产"]},
{"id": "city", "title": "城市生活", "items": ["15分钟生活圈再升级", "口袋公园装下更多幸福", "绿色出行成为新日常"]}
]
},
"local": {
"title": "地方新闻",
"moreLabel": "地方频道首页 →",
"selectorLabel": "选择地区",
"provinces": [
{"id": "beijing", "name": "北京", "leadTitle": "城市副中心新增一批公共文化空间", "summary": "来自新华社地方频道的一线报道,记录城市发展与百姓生活的新变化。", "visual": "capital", "links": ["轨道交通服务再添便民举措", "中关村科学城发布开放实验清单", "老街区更新保留城市记忆", "民生项目清单加快落地", "科技创新平台开放共享", "基层治理案例获得推广"]},
{"id": "tianjin", "name": "天津", "leadTitle": "港产城融合打开发展新空间", "summary": "海河沿岸公共空间焕新开放,智能制造项目集中签约。", "visual": "coast", "links": ["海河沿岸公共空间焕新开放", "智能制造项目集中签约", "社区养老服务站覆盖更多街道", "港口智慧调度系统投入使用"]},
{"id": "hebei", "name": "河北", "leadTitle": "县域特色产业集群加快升级", "summary": "雄安公共服务项目建设提速,生态修复持续推进。", "visual": "mountain", "links": ["雄安公共服务项目建设提速", "太行山生态修复持续推进", "冰雪运动点亮山城生活", "县域物流体系扩容"]},
{"id": "shanghai", "name": "上海", "leadTitle": "国际科创中心建设再提速", "summary": "城市更新让里弄焕发新生,航运服务能级持续提升。", "visual": "river", "links": ["城市更新让里弄焕发新生", "航运服务能级持续提升", "社区食堂提供更多温暖", "公共文化夜校增开课程"]},
{"id": "jiangsu", "name": "江苏", "leadTitle": "先进制造业集群协同创新", "summary": "大运河文化带保护成果发布,城乡公交覆盖扩面。", "visual": "river", "links": ["大运河文化带保护成果发布", "城乡公交一体化覆盖扩面", "绿色园区建设形成新样本", "沿江科创平台共建共享"]},
{"id": "zhejiang", "name": "浙江", "leadTitle": "数字经济与实体经济深度融合", "summary": "未来乡村解锁共富新场景,海洋经济项目集中开工。", "visual": "coast", "links": ["未来乡村解锁共富新场景", "海洋经济项目集中开工", "古镇保护引入青年创意", "跨境电商服务持续升级"]},
{"id": "guangdong", "name": "广东", "leadTitle": "粤港澳大湾区通勤更加便捷", "summary": "制造业数字化改造扩面提质,滨海绿道串联城市生活。", "visual": "bay", "links": ["制造业数字化改造扩面提质", "滨海绿道串联城市生活", "县域商业体系加快完善", "青年创新创业平台扩容"]}
]
},
"services": {
"matrixTitle": "新华社媒体矩阵",
"matrixSubtitle": "权威内容,多端抵达",
"matrixItems": [
{"id": "app", "title": "新华社客户端", "caption": "即时资讯", "icon": "app"},
{"id": "video", "title": "新华视频", "caption": "移动直播", "icon": "video"},
{"id": "platform", "title": "新华号", "caption": "内容开放平台", "icon": "platform"},
{"id": "radio", "title": "新华广播", "caption": "新闻随身听", "icon": "radio"}
],
"liveModal": {
"title": "新华社全媒直播",
"streamTitle": "走进重大工程一线",
"streamSubtitle": "演示画面 · 直播文字实录同步更新",
"currentProgram": "当前节目:新华全媒现场"
},
"newsletter": {
"title": "订阅《新华早报》",
"text": "每天早晨,用五分钟了解国内外重要新闻。",
"placeholder": "请输入邮箱地址",
"button": "免费订阅",
"successPrefix": "订阅成功,确认邮件已发送至"
}
},
"footer": {
"links": [
{"label": "关于我们", "href": "#about"},
{"label": "联系我们", "href": "#about"},
{"label": "版权声明", "href": "#about"},
{"label": "隐私政策", "href": "#about"},
{"label": "网络举报", "href": "#about"}
],
"copyright": "© 2026 新华社 · 本页面为概念设计",
"legal": "新闻信息服务 · 多语种传播 · 地方频道"
}
}
@@ -0,0 +1,708 @@
(() => {
"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 escapeHTML = (value) => String(value ?? "").replace(/[&<>'"]/g, (char) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", "'": "&#39;", '"': "&quot;"})[char]);
const safeHref = (value) => String(value || "").startsWith("#") ? String(value) : "#top";
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 ["http:", "https:"].includes(url.protocol) ? url.href : ""; }
catch (_error) { return ""; }
};
const validateRemoteMediaTree = (value, path = "当前模块") => {
if (Array.isArray(value)) return value.forEach((item, index) => validateRemoteMediaTree(item, path + "[" + index + "]"));
if (!isObject(value)) return;
const media = value.media;
if (media && ["image", "video", "webpage"].includes(media.type)) {
if (["image", "video"].includes(media.type) && !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 MODULES = ["site", "navigation", "specials", "headline", "focus", "features", "channels", "local", "services", "footer"];
const MODULE_META = {
site: ["站点信息", "机构、标识、口号与主题"],
navigation: ["导航", "多语种、主导航、搜索与抽屉"],
specials: ["专集焦点", "报道专集、焦点图与播报"],
headline: ["全媒头条", "主标题、摘要与关联阅读"],
focus: ["要闻聚焦", "分类标签与新闻列"],
features: ["专栏专题", "名专栏、专题与记者工作室"],
channels: ["频道", "网评访谈视频与行业频道"],
local: ["地方联播", "省份切换与地方报道"],
services: ["媒体服务", "媒体矩阵、直播与订阅"],
footer: ["页脚", "机构链接与版权说明"]
};
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
const isCompleteData = (value) => isObject(value) && MODULES.every((name) => isObject(value[name]));
const initialData = JSON.parse(qs("#xinhuaPageData").textContent);
const fingerprint = (() => {
const text = JSON.stringify(initialData);
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(16).padStart(8, "0");
})();
const storageKey = "xinhua-page-data-v1:" + fingerprint;
const themeKey = "xinhua-page-theme-v1:" + fingerprint;
const readStorage = (key) => { try { return window.localStorage.getItem(key); } catch (_error) { return null; } };
const writeStorage = (key, value) => { try { window.localStorage.setItem(key, value); return true; } catch (_error) { return false; } };
const removeStorage = (key) => { try { window.localStorage.removeItem(key); } catch (_error) { /* storage is optional */ } };
let pageData = clone(initialData);
try {
const saved = readStorage(storageKey);
const parsed = saved ? JSON.parse(saved) : null;
if (isCompleteData(parsed)) pageData = parsed;
} catch (_error) {
pageData = clone(initialData);
}
const saveData = () => writeStorage(storageKey, JSON.stringify(pageData));
const toast = qs("#toast");
let toastTimer = 0;
const note = (message) => {
const settings = qs("#settingsOverlay");
if (settings && settings.classList.contains("open")) {
const status = qs("#jsonStatus");
status.textContent = message;
status.className = "json-status valid";
return;
}
window.clearTimeout(toastTimer);
toast.textContent = message;
toast.classList.add("show");
toastTimer = window.setTimeout(() => toast.classList.remove("show"), 2200);
};
const sealLabel = () => pageData.site.brandName || "新华社";
document.head.insertAdjacentHTML("beforeend", '<style data-external-media>.visual>img,.visual>video,.visual>iframe,.spot-card img,.spot-card video,.spot-card iframe{width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}.visual>iframe,.spot-card iframe{object-fit:initial}.external-open{position:absolute;right:10px;bottom:10px;z-index:4;padding:7px 11px;color:#fff;background:rgba(0,0,0,.72);text-decoration:none;font-size:12px;font-weight:700}.external-copy{position:absolute;left:10px;right:10px;bottom:10px;z-index:4;padding:9px;color:#fff;background:rgba(0,0,0,.72);text-decoration:none}.external-copy strong,.external-copy span{display:block}.external-copy span{margin-top:3px;font-size:12px}</style>');
const externalMediaMarkup = (media, label) => {
if (!isObject(media)) return "";
if (media.type === "image") {
const source = safeRemoteUrl(media.mediaUrl, "image");
if (!source) return "";
const pageUrl = safeRemoteUrl(media.pageUrl);
return '<img src="' + escapeHTML(source) + '" alt="' + escapeHTML(media.alt || label || "新闻图片") + '" loading="lazy" referrerpolicy="no-referrer"/>' + (pageUrl ? '<a class="external-open" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer">打开来源</a>' : "");
}
if (media.type === "video") {
const source = safeRemoteUrl(media.mediaUrl, "video");
const poster = safeRemoteUrl(media.posterUrl, "image");
return source ? '<video src="' + escapeHTML(source) + '"' + (poster ? ' poster="' + escapeHTML(poster) + '"' : "") + ' controls playsinline preload="metadata" aria-label="' + escapeHTML(media.alt || label || "新闻视频") + '"></video>' : "";
}
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 body + '<a class="external-copy" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer"><strong>' + escapeHTML(media.title || label || "打开网页") + '</strong><span>' + escapeHTML(media.description || "新窗口打开") + "</span></a>";
}
return "";
};
const visualSvg = (type, title) => {
if (isObject(type)) {
const external = externalMediaMarkup(type, title);
if (external) return external;
type = "city";
}
let background = "#c6d8df";
let content = '<path d="M0 315 165 160l95 86 135-145 305 232v117H0Z" fill="#5f7e78"/><path d="M25 375h650" stroke="#f4eddb" stroke-width="19"/>';
if (type === "harvest") {
background = "#91bdc7";
content = '<circle cx="565" cy="86" r="50" fill="#ffe3a0"/><path d="M0 305c150-78 350-70 700-4v149H0Z" fill="#7f9048"/><path d="M20 395c177-87 393-83 640-29" stroke="#e5d16c" stroke-width="34" fill="none"/>';
} else if (type === "railway") {
background = "#bdd3da";
content = '<path d="M0 310 140 160l95 82 155-150 310 236v122H0Z" fill="#617b73"/><path d="M30 392c170-58 405-60 640 10" stroke="#ede9da" stroke-width="19" fill="none"/><path d="M225 300h245l76 48H225Z" fill="#edf1ef"/><path d="M256 315h145v15H256Z" fill="#355462"/><path d="m470 300 76 48h-76Z" fill="#c90018"/>';
} else if (type === "satellite" || type === "world") {
background = "#182333";
content = '<circle cx="350" cy="220" r="135" fill="#2f4f71"/><path d="M245 274c42-128 180-187 287-139-58 36-86 80-111 137-31 70-95 75-176 2Z" fill="#5593b3"/><g fill="#fff"><circle cx="90" cy="82" r="4"/><circle cx="590" cy="101" r="4"/></g>';
} else if (type === "culture") {
background = "#e1d4bd";
content = '<rect x="65" y="142" width="210" height="248" fill="#5b554b"/><rect x="345" y="72" width="255" height="318" fill="#756d60"/><g fill="#e8be68"><path d="M102 180h54v62h-54Zm78 0h54v62h-54Zm205-62h63v70h-63Zm92 0h63v70h-63Z"/></g><path d="M0 395h700" stroke="#c90018" stroke-width="12"/>';
} else if (type === "wetland" || type === "green") {
background = "#9fcbd1";
content = '<path d="M0 335c195-60 410-52 700 10v105H0Z" fill="#537969"/><path d="M140 132q31-34 62 0m132-38q31-34 62 0m114 64q31-34 62 0" stroke="#243d45" stroke-width="7" fill="none"/><circle cx="575" cy="91" r="42" fill="#f4d995"/>';
} else if (type === "economy") {
background = "#d9d3c3";
content = '<path d="M80 360h540M130 320l95-95 78 50 132-145 135 90" stroke="#0a4f8a" stroke-width="24" fill="none"/><circle cx="435" cy="130" r="30" fill="#c90018"/>';
} else if (type === "technology") {
background = "#173854";
content = '<g fill="none" stroke="#6ec6df" stroke-width="10"><circle cx="350" cy="225" r="125"/><path d="M175 225h350M350 50v350"/></g><circle cx="350" cy="225" r="47" fill="#c90018"/>';
} else if (type === "commentary") {
background = "#d6e0e2";
content = '<path d="M70 365h560" stroke="#23435a" stroke-width="22"/><path d="M175 345V155h350v190" fill="#627f8a"/><circle cx="350" cy="125" r="72" fill="#c90018"/>';
} else if (type === "interview") {
background = "#173854";
content = '<circle cx="235" cy="185" r="78" fill="#e2cab8"/><path d="M95 430c25-120 78-170 160-170s135 50 160 170" fill="#50748e"/><path d="M420 105h190v28H420Zm0 72h145v28H420Zm0 72h175v28H420Z" fill="#e8eef0"/>';
} else if (type === "video") {
background = "#0b3559";
content = '<circle cx="350" cy="225" r="92" fill="#fff" opacity=".92"/><path d="m325 170 82 55-82 55Z" fill="#c90018"/><path d="M0 430 700 260v190H0Z" fill="#7a1b2c" opacity=".65"/>';
} else if (type === "capital") {
background = "#c6d9df";
content = '<path d="M0 330 190 155l135 120 158-180 217 228v127H0Z" fill="#647f76"/><path d="M0 395c198-72 442-72 700 10" stroke="#f0ecdf" stroke-width="25" fill="none"/>';
} else if (type === "coast" || type === "bay") {
background = "#92c8d5";
content = '<path d="M0 345c130-55 240-42 360-9 135 37 235 25 340-25v139H0Z" fill="#2d6671"/><path d="M245 95v190m0-130h158l45 55-203 15" stroke="#f1f3ed" stroke-width="17" fill="none"/>';
} else if (type === "river") {
background = "#c8d9d1";
content = '<path d="M0 315c165-92 315-78 700-15v150H0Z" fill="#47705a"/><path d="M-20 378c180-65 430-69 750 7" stroke="#b7dce4" stroke-width="42" fill="none"/><g fill="#edf0e7"><rect x="130" y="185" width="75" height="150"/><rect x="290" y="115" width="86" height="220"/><rect x="500" y="210" width="68" height="125"/></g>';
}
return '<svg viewBox="0 0 700 450" preserveAspectRatio="xMidYMid slice" role="img" aria-label="' + escapeHTML(title) + '"><rect width="700" height="450" fill="' + background + '"/>' + content + "</svg>";
};
const iconSvg = (type) => {
if (type === "video") return '<svg viewBox="0 0 24 24"><path d="M4 6h16v12H4Z"/><path d="m9 10 6 4-6 3Z"/></svg>';
if (type === "platform") return '<svg viewBox="0 0 24 24"><path d="M5 5h14v14H5Z"/><path d="M8 9h8M8 13h6"/></svg>';
if (type === "radio") return '<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8"/><path d="M12 8v4l3 2"/></svg>';
return '<svg viewBox="0 0 24 24"><path d="M6 3h12v18H6Z"/><path d="M10 17h4"/></svg>';
};
let themeInitialized = false;
const syncThemeLabel = () => {
const dark = document.body.classList.contains("dark");
qs("#themeLabel").textContent = dark ? "日间" : "夜间";
qs("#theme").setAttribute("aria-label", dark ? "切换日间模式" : "切换夜间模式");
};
const applyInitialTheme = () => {
if (themeInitialized) return;
themeInitialized = true;
const stored = readStorage(themeKey);
const configured = pageData.site.theme;
const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme:dark)").matches;
const dark = stored === "dark" || (!stored && (configured === "dark" || (configured === "auto" && prefersDark)));
document.body.classList.toggle("dark", dark);
syncThemeLabel();
};
const toggleTheme = () => {
const dark = document.body.classList.toggle("dark");
writeStorage(themeKey, dark ? "dark" : "light");
syncThemeLabel();
note(dark ? "夜间模式已开启" : "日间模式已开启");
};
const navMarkup = (items, activeFirst) => (Array.isArray(items) ? items : []).map((item, index) => '<a class="' + (activeFirst && index === 0 ? "active" : "") + '" href="' + safeHref(item.href) + '">' + escapeHTML(item.label) + "</a>").join("");
const renderSite = () => {
const data = pageData.site;
document.title = data.pageTitle || "新华社";
qs('meta[name="description"]').content = data.description || "";
qs("#brandName").textContent = data.brandName || "";
qs("#brandEnglish").textContent = data.brandEnglish || "";
qs("#brandLink").setAttribute("aria-label", (data.brandName || "") + "首页");
qs("#motto").textContent = data.motto || "";
qs("#clientLabel").textContent = data.clientLabel || "";
qs("#footerBrand").textContent = data.brandName || "";
qs("#drawerBrand").textContent = data.brandName || "";
applyInitialTheme();
};
const renderNavigation = () => {
const data = pageData.navigation;
qs("#networkLeft").innerHTML = navMarkup(data.networkLeft, false);
qs("#networkRight").innerHTML = navMarkup(data.networkRight, false);
qs("#primaryNav").innerHTML = navMarkup(data.primary, true);
qs("#drawerLinks").innerHTML = navMarkup(data.drawer, false);
qs("#searchLabel").textContent = data.searchLabel || "";
qs("#search").placeholder = data.searchPlaceholder || "";
qs("#searchButton").textContent = data.searchButton || "";
};
let activeSpot = 0;
const renderSpecials = () => {
const data = pageData.specials;
qs("#seriesTitle").textContent = data.seriesTitle || "";
qs("#seriesEnglish").textContent = data.seriesEnglish || "";
qs("#seriesItems").innerHTML = (data.seriesItems || []).map((item, index) => '<a class="series-item" href="' + safeHref(item.href) + '"><span class="series-no">' + String(index + 1).padStart(2, "0") + "</span><b>" + escapeHTML(item.title) + "</b></a>").join("");
const spots = data.spotlightItems || [];
if (activeSpot >= spots.length) activeSpot = 0;
qs("#spotlight").innerHTML = spots.map((item, index) => '<article class="spot-card' + (index === activeSpot ? " active" : "") + '" data-spot-id="' + escapeHTML(item.id) + '" role="listitem">' + visualSvg(item.media || item.visual, item.title) + (item.tag ? '<span class="spot-type">' + escapeHTML(item.tag) + "</span>" : "") + '<span class="spot-cap">' + escapeHTML(item.title) + '</span><button class="spot-select" type="button" data-spot-index="' + index + '" aria-label="查看' + escapeHTML(item.title) + '"></button></article>').join("");
const selected = spots[activeSpot];
qs("#spotTitle").textContent = selected ? (data.spotlightLabel || "焦点图") + ":" + selected.title : "";
const latest = data.latest || {};
qs("#latestLabel").textContent = latest.label || "";
qs("#latestTitle").textContent = latest.title || "";
qs("#latestTitle").href = safeHref(latest.href);
qs("#latestTime").textContent = latest.time || "";
};
const renderHeadline = () => {
const data = pageData.headline;
qs("#headlineKicker").textContent = data.kicker || "";
qs("#headlineTitle").textContent = data.title || "";
qs("#headlineSummary").textContent = data.summary || "";
qs("#headlineLinks").innerHTML = navMarkup(data.links, false);
};
let activeFocus = "";
const renderFocus = () => {
const data = pageData.focus;
const tabs = data.tabs || [];
if (!tabs.some((tab) => tab.id === activeFocus)) activeFocus = tabs[0]?.id || "";
qs("#focusTitle").textContent = data.title || "";
qs("#focusMore").textContent = data.moreLabel || "";
qs("#focusTabs").innerHTML = tabs.map((tab) => '<button class="' + (tab.id === activeFocus ? "active" : "") + '" data-focus-tab="' + escapeHTML(tab.id) + '" role="tab">' + escapeHTML(tab.label) + "</button>").join("");
const current = tabs.find((tab) => tab.id === activeFocus) || tabs[0] || {columns: []};
qs("#focusGrid").innerHTML = (current.columns || []).map((column) => '<article class="focus-col"><div class="focus-lead"><div class="focus-thumb visual">' + visualSvg(column.media || column.visual, column.leadTitle) + "</div><div><h3>" + escapeHTML(column.leadTitle) + "</h3><p>" + escapeHTML(column.summary) + '</p></div></div><ul class="dense-list">' + (column.links || []).map((title) => '<li><a href="#focus">' + escapeHTML(title) + "</a></li>").join("") + "</ul></article>").join("");
};
const renderFeatures = () => {
const data = pageData.features;
qs("#columnTitle").innerHTML = escapeHTML(data.columnTitle || "").replace("名专栏", "<br>名专栏");
qs("#columnSubtitle").textContent = data.columnSubtitle || "";
qs("#featureTags").innerHTML = (data.tags || []).map((tag, index) => '<button class="' + (index === 0 ? "active" : "") + '">' + escapeHTML(tag) + "</button>").join("");
qs("#featureArticles").innerHTML = (data.articles || []).map((item) => '<a class="named-item" href="#features"><b>' + escapeHTML(item.title) + "</b><span>" + escapeHTML(item.meta) + "</span></a>").join("");
qs("#topicsTitle").textContent = data.topicsTitle || "";
qs("#topicsMore").textContent = data.topicsMoreLabel || "";
qs("#topicGrid").innerHTML = (data.topics || []).map((item, index) => '<a class="topic" href="#topics"><span class="topic-index">' + String(index + 1).padStart(2, "0") + "</span><h3>" + escapeHTML(item.title) + "</h3><p>" + escapeHTML(item.summary) + "</p></a>").join("");
qs("#studiosTitle").textContent = data.studiosTitle || "";
qs("#studiosMore").textContent = data.studiosMoreLabel || "";
qs("#studioGrid").innerHTML = (data.studios || []).map((item) => '<a class="studio" href="#studios"><span class="avatar">' + escapeHTML(item.initial) + "</span><span><b>" + escapeHTML(item.name) + "</b><p>" + escapeHTML(item.bio) + "</p></span></a>").join("");
};
const renderChannels = () => {
const data = pageData.channels;
qs("#editorialColumns").innerHTML = (data.editorialColumns || []).map((item) => '<article class="column-box"><h2><span>' + escapeHTML(item.accent) + "</span>" + escapeHTML(item.title) + '</h2><div class="column-feature">' + (item.live ? '<button class="visual live-button open-live" aria-label="播放' + escapeHTML(item.feature) + '">' : '<div class="visual">') + visualSvg(item.media || item.visual, item.feature) + (item.live ? "</button>" : "</div>") + "<h3>" + escapeHTML(item.feature) + '</h3></div><ul>' + (item.links || []).map((title) => '<li><a href="#media">' + escapeHTML(title) + "</a></li>").join("") + "</ul></article>").join("");
qs("#industryTitle").textContent = data.industryTitle || "";
qs("#industryMore").textContent = data.industryMoreLabel || "";
qs("#industryGrid").innerHTML = (data.industries || []).map((item) => '<div class="industry"><h3>' + escapeHTML(item.title) + '<a href="#industry">更多</a></h3><ul>' + (item.items || []).map((title) => "<li>" + escapeHTML(title) + "</li>").join("") + "</ul></div>").join("");
};
let activeProvince = "";
const renderLocal = () => {
const data = pageData.local;
const provinces = data.provinces || [];
if (!provinces.some((item) => item.id === activeProvince)) activeProvince = provinces[0]?.id || "";
qs("#localTitle").textContent = data.title || "";
qs("#localMore").textContent = data.moreLabel || "";
qs("#provinceBar").innerHTML = "<b>" + escapeHTML(data.selectorLabel) + "</b>" + provinces.map((item) => '<button class="' + (item.id === activeProvince ? "active" : "") + '" data-province="' + escapeHTML(item.id) + '">' + escapeHTML(item.name) + "</button>").join("");
const province = provinces.find((item) => item.id === activeProvince) || provinces[0];
qs("#localContent").innerHTML = province ? '<article class="local-lead"><div class="visual">' + visualSvg(province.media || province.visual, province.leadTitle) + '</div><div><span class="headline-label">' + escapeHTML(province.name) + "频道</span><h3>" + escapeHTML(province.leadTitle) + "</h3><p>" + escapeHTML(province.summary) + '</p></div></article><div class="local-list">' + (province.links || []).map((title) => '<a href="#local">' + escapeHTML(title) + "</a>").join("") + "</div>" : "";
};
const renderServices = () => {
const data = pageData.services;
qs("#mediaMatrix").innerHTML = '<div class="matrix-intro"><h2>' + escapeHTML(data.matrixTitle) + "</h2><p>" + escapeHTML(data.matrixSubtitle) + "</p></div>" + (data.matrixItems || []).map((item) => '<a class="matrix-item" href="#services"><span class="matrix-icon">' + iconSvg(item.icon) + "</span><span><b>" + escapeHTML(item.title) + "</b><small>" + escapeHTML(item.caption) + "</small></span></a>").join("");
const modal = data.liveModal || {};
qs("#liveTitle").textContent = modal.title || "";
qs("#streamTitle").textContent = modal.streamTitle || "";
qs("#streamSubtitle").textContent = modal.streamSubtitle || "";
qs("#currentProgram").textContent = modal.currentProgram || "";
const newsletter = data.newsletter || {};
qs("#newsletterTitle").textContent = newsletter.title || "";
qs("#newsletterText").textContent = newsletter.text || "";
qs("#email").placeholder = newsletter.placeholder || "";
qs("#newsletterButton").textContent = newsletter.button || "";
};
const renderFooter = () => {
const data = pageData.footer;
qs("#footerLinks").innerHTML = navMarkup(data.links, false);
qs("#copyright").textContent = data.copyright || "";
qs("#legal").textContent = data.legal || "";
};
const renderAll = () => {
renderSite();
renderNavigation();
renderSpecials();
renderHeadline();
renderFocus();
renderFeatures();
renderChannels();
renderLocal();
renderServices();
renderFooter();
bindDynamicInteractions();
};
const liveModal = qs("#liveModal");
let lastFocus = null;
const openLive = () => {
lastFocus = document.activeElement;
liveModal.classList.add("open");
document.body.style.overflow = "hidden";
qs("#liveClose").focus();
};
const closeLive = () => {
liveModal.classList.remove("open");
document.body.style.overflow = "";
if (lastFocus) lastFocus.focus();
};
const drawer = qs("#drawer");
const openMenu = () => {
drawer.classList.add("open");
document.body.style.overflow = "hidden";
qs("#menuClose").focus();
};
const closeMenu = () => {
drawer.classList.remove("open");
document.body.style.overflow = "";
qs("#menuOpen").focus();
};
const bindDynamicInteractions = () => {
qsa("[data-spot-index]").forEach((button) => button.addEventListener("click", () => { activeSpot = Number(button.dataset.spotIndex) || 0; renderSpecials(); bindDynamicInteractions(); }));
qsa("[data-focus-tab]").forEach((button) => button.addEventListener("click", () => { activeFocus = button.dataset.focusTab; renderFocus(); bindDynamicInteractions(); }));
qsa("#featureTags button").forEach((button) => button.addEventListener("click", () => { qsa("#featureTags button").forEach((item) => item.classList.remove("active")); button.classList.add("active"); }));
qsa("[data-province]").forEach((button) => button.addEventListener("click", () => { activeProvince = button.dataset.province; renderLocal(); bindDynamicInteractions(); }));
qsa(".open-live").forEach((button) => button.addEventListener("click", openLive));
qsa("#drawerLinks a").forEach((link) => link.addEventListener("click", closeMenu));
};
qs("#theme").addEventListener("click", toggleTheme);
qs("#searchOpen").addEventListener("click", () => {
const panel = qs("#searchPanel");
panel.classList.toggle("open");
if (panel.classList.contains("open")) window.setTimeout(() => qs("#search").focus(), 20);
});
const collectStrings = (value, output = []) => {
if (typeof value === "string" && !value.startsWith("#")) output.push(value);
else if (Array.isArray(value)) value.forEach((item) => collectStrings(item, output));
else if (isObject(value)) Object.values(value).forEach((item) => collectStrings(item, output));
return output;
};
qs("#searchForm").addEventListener("submit", (event) => {
event.preventDefault();
const raw = qs("#search").value.trim();
const query = raw.toLocaleLowerCase();
const count = query ? collectStrings(pageData).filter((value) => value.toLocaleLowerCase().includes(query)).length : 0;
const status = qs("#searchStatus");
status.classList.add("show");
status.textContent = query ? "找到与“" + raw + "”相关的 " + count + " 条内容" : "请输入搜索关键词";
});
qs("#liveClose").addEventListener("click", closeLive);
liveModal.addEventListener("click", (event) => { if (event.target === liveModal) closeLive(); });
qs("#caption").addEventListener("click", (event) => {
const on = event.currentTarget.textContent.includes("开");
event.currentTarget.textContent = "CC 字幕:" + (on ? "关" : "开");
note(on ? "字幕已关闭" : "字幕已开启");
});
qs("#menuOpen").addEventListener("click", openMenu);
qs("#menuClose").addEventListener("click", closeMenu);
drawer.addEventListener("click", (event) => { if (event.target === drawer) closeMenu(); });
qs("#subForm").addEventListener("submit", (event) => {
event.preventDefault();
const email = qs("#email").value.trim();
qs("#subStatus").textContent = (pageData.services.newsletter.successPrefix || "") + " " + email;
event.currentTarget.reset();
});
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("settings-open");
document.body.style.overflow = "hidden";
window.setTimeout(() => jsonEditor.focus(), 80);
};
const closeSettings = () => {
settingsOverlay.classList.remove("open");
settingsOverlay.setAttribute("aria-hidden", "true");
document.body.classList.remove("settings-open");
document.body.style.overflow = "";
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();
jsonEditor.setRangeText(" ", jsonEditor.selectionStart, jsonEditor.selectionEnd, "end");
validateEditor();
}
});
qs("#applyJson").addEventListener("click", () => {
if (!storeActiveDraft() || !isCompleteData(editorDraft)) {
note("请修正 JSON 后再应用");
return;
}
pageData = clone(editorDraft);
saveData();
renderAll();
note("JSON 已应用到页面");
});
qs("#resetJson").addEventListener("click", () => {
pageData = clone(initialData);
editorDraft = clone(initialData);
removeStorage(storageKey);
removeStorage(themeKey);
themeInitialized = false;
activeSpot = 0;
activeFocus = "";
activeProvince = "";
renderAll();
renderModuleTabs();
selectModule(activeModule, true);
note("已恢复初始 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);
note("完整 JSON 已复制");
} catch (_error) {
jsonEditor.focus();
jsonEditor.select();
note("已选中当前模块,请手动复制");
}
});
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 = "xinhua-page-data.json";
link.click();
window.setTimeout(() => URL.revokeObjectURL(link.href), 0);
note("JSON 已下载");
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
if (liveModal.classList.contains("open")) closeLive();
if (drawer.classList.contains("open")) closeMenu();
if (settingsOverlay.classList.contains("open")) closeSettings();
}
});
renderAll();
function installJsonMediaUpload(){
const editor=document.getElementById("jsonEditor"),apply=document.getElementById("applyJson");if(!editor||!apply||document.getElementById("uploadJsonMedia"))return;
const actions=apply.parentElement,button=document.createElement("button"),input=document.createElement("input"),reference=actions.querySelector("#downloadJson,#copyJson,#validateJson,#resetJson");button.type="button";button.id="uploadJsonMedia";button.className=reference?reference.className:apply.className;button.textContent="上传图片/视频";button.title="先把光标放进要替换的内容对象,再选择图片或视频";input.type="file";input.accept="image/*,video/*";input.hidden=true;actions.insertBefore(button,apply);actions.appendChild(input);
const report=(message)=>{const status=document.getElementById("settingsStatus")||document.getElementById("jsonError")||document.getElementById("jsonStatus");if(status)status.textContent=message};
const findTarget=(text,cursor)=>{const stack=[],matches=[];let quoted=false,escaped=false;for(let index=0;index<text.length;index+=1){const char=text[index];if(quoted){if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char==='"')quoted=false;continue}if(char==='"'){quoted=true;continue}if(char==="{")stack.push(index);else if(char==="}"){const start=stack.pop();if(start===undefined||cursor<start||cursor>index+1)continue;try{const value=JSON.parse(text.slice(start,index+1)),own=(key)=>Object.prototype.hasOwnProperty.call(value,key);if(value&&!Array.isArray(value)&&(own("media")||own("visual")||(own("id")&&(own("text")||own("title"))&&(own("author")||own("channel")||own("user")))))matches.push({start,end:index+1,value})}catch(_error){/* full validator handles malformed JSON */}}}return matches.sort((left,right)=>(left.end-left.start)-(right.end-right.start))[0]||null};
button.addEventListener("click",()=>{input.value="";report("请选择图片或视频;文件会写入光标所在内容对象的 media 字段。");input.click()});
input.addEventListener("change",()=>{const file=input.files&&input.files[0];if(!file)return;const type=file.type.startsWith("image/")?"image":file.type.startsWith("video/")?"video":"";if(!type){report("仅支持图片或视频文件。");return}const target=findTarget(editor.value,editor.selectionStart);if(!target){report("请先把光标放进带 visual/media 的内容对象,或带 id 的帖子/视频对象内。");return}const reader=new FileReader();reader.onerror=()=>report("文件读取失败,请重新选择。");reader.onload=()=>{const previous=target.value.media&&typeof target.value.media==="object"?target.value.media:{},media={type,mediaUrl:String(reader.result)};for(const key of ["alt","label","caption","pageUrl"])if(typeof previous[key]==="string")media[key]=previous[key];if(!media.alt)media.alt=type==="image"?"用户上传的图片":"用户上传的视频";target.value.media=media;const lineStart=editor.value.lastIndexOf("\n",target.start-1)+1,indent=(editor.value.slice(lineStart,target.start).match(/^\s*/)||[""])[0],replacement=JSON.stringify(target.value,null,2).split("\n").map((line,index)=>index?indent+line:line).join("\n");editor.value=editor.value.slice(0,target.start)+replacement+editor.value.slice(target.end);editor.dispatchEvent(new Event("input",{bubbles:true}));const mediaIndex=replacement.indexOf('"media"');editor.focus();editor.setSelectionRange(target.start+Math.max(mediaIndex,0),target.start+Math.max(mediaIndex,0));report(`已把 ${file.name} 写入 JSON,请点击“应用并渲染”。${file.size>2*1024*1024?" 文件较大,建议同时下载 JSON 保存。":""}`)};reader.readAsDataURL(file)});
}
installJsonMediaUpload();
function installInlineMediaReplace() {
if (document.getElementById("dfInlineMediaInput")) return;
const visualHostSelector = ".post-media,.video-visual,.thumbnail-visual,.short-thumb,.watch-visual,.thread-media,.visual,.lead-visual,.mini-visual,.compact-media,.card-art,.story-visual,.art,.video-art,.media-art,.player-stage,.thumbnail,.thumb,.list-thumb,.focus-thumb,.spot-card,.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,87 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="description" content="新华社风格中文通讯社新闻门户示例页面。">
<meta name="theme-color" content="#0a4f8a">
<title>新华社|记录时代 连接世界</title>
<style>
:root{--red:#c90018;--blue:#0a4f8a;--blue-2:#146aa8;--navy:#07345c;--ink:#20252a;--paper:#fff;--soft:#f4f7fa;--line:#d7e0e7;--muted:#667482;--gold:#d7a429;--max:1240px;--sans:"Microsoft YaHei","Noto Sans SC",Arial,sans-serif;--serif:"Songti SC",SimSun,serif}
*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.52 var(--sans)}body.dark{--paper:#101820;--ink:#eef4f8;--soft:#182630;--line:#344957;--muted:#aebbc4;--blue-2:#65b5e9}a{color:inherit;text-decoration:none}button,input,textarea{font:inherit}button{border:0;background:none;color:inherit}button,a{cursor:pointer}svg{display:block;width:100%;height:100%}:focus-visible{outline:3px solid #f3bd22;outline-offset:3px}.wrap{width:min(var(--max),calc(100% - 40px));margin:auto}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.skip{position:fixed;left:10px;top:calc(var(--df-generated-header-height,0px) + 8px);z-index:500;background:#fff;color:#111;padding:9px 13px;font-weight:800;transform:translateY(-160%);transition:.2s}.skip:focus{transform:none}
.network{height:31px;border-bottom:1px solid #e0e5e9;background:#f9fafb;color:#5b6873;font-size:12px}.dark .network{background:#0b1218;border-color:#2c3d49}.network .wrap{height:100%;display:flex;align-items:center;justify-content:space-between}.network-links{display:flex;align-items:center;gap:16px}.network a:hover{color:var(--red)}
.mast{height:94px}.mast .wrap{height:100%;display:flex;align-items:center}.brand{display:flex;align-items:center;gap:11px}.brand-seal{width:58px;height:58px;border-radius:50%;background:var(--red);padding:8px;box-shadow:inset 0 0 0 2px rgba(255,255,255,.34);flex:0 0 auto}.brand-name{font:900 37px/1 var(--serif);letter-spacing:2px}.brand-en{display:block;margin-top:6px;font-size:9px;font-weight:800;letter-spacing:.18em;color:var(--muted)}.motto{margin-left:74px;padding-left:28px;border-left:1px solid var(--line);font-family:var(--serif);color:#66798a;letter-spacing:.2em;font-size:17px}.mast-tools{margin-left:auto;display:flex;align-items:center;gap:4px}.tool{height:44px;min-width:44px;padding:0 9px;display:flex;align-items:center;justify-content:center;gap:6px;font-size:12px;color:var(--muted);transition:background .2s,color .2s}.tool:hover{background:var(--soft);color:var(--red)}.tool svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:2}.mobile-menu{display:none}
.primary-nav{background:var(--blue);color:#fff;border-bottom:4px solid #e4ecf2}.primary-nav .wrap{height:48px;display:flex;align-items:center;overflow:hidden}.primary-nav a{height:100%;display:flex;align-items:center;padding:0 16px;white-space:nowrap;font-size:15px;font-weight:800;transition:background .2s}.primary-nav a:hover,.primary-nav a.active{background:#073a67}.primary-nav a.active{box-shadow:inset 0 -4px var(--red)}.primary-nav a:last-child{margin-left:auto}
.search-panel{display:none;background:var(--navy);color:#fff;border-bottom:4px solid var(--red)}.search-panel.open{display:block}.search-form{min-height:76px;display:flex;align-items:center;gap:10px}.search-form label{font-weight:800}.search-form input{height:44px;min-width:0;flex:1;padding:0 13px;border:0;color:#111;background:#fff}.search-form button{height:44px;padding:0 20px;background:var(--red);color:#fff;font-weight:800}.search-status{display:none;padding:0 0 12px 73px;color:#d8e6ef;font-size:13px}.search-status.show{display:block}
.settings-trigger{position:fixed;right:18px;top:calc(var(--df-generated-header-height,0px) + 122px);z-index:92;width:44px;height:44px;border-radius:4px;display:grid;place-items:center;background:#102d47;color:#fff;box-shadow:0 7px 22px rgba(0,0,0,.22);transition:.2s}.settings-trigger:hover{background:var(--red);transform:translateY(-1px)}.settings-trigger svg{width:21px;height:21px;fill:none;stroke:currentColor;stroke-width:1.9}
.series{border-bottom:1px solid var(--line);background:var(--paper)}.series .wrap{height:78px;display:grid;grid-template-columns:110px repeat(4,1fr);align-items:stretch}.series-title{background:linear-gradient(135deg,var(--red),#9e0012);color:#fff;display:flex;flex-direction:column;align-items:center;justify-content:center;font-weight:900}.series-title small{font-size:10px;letter-spacing:.14em;margin-top:3px}.series-item{padding:13px 15px;border-right:1px solid var(--line);display:flex;align-items:center;gap:10px}.series-no{font:700 27px/1 Georgia,serif;color:#c7d4de}.series-item b{font-family:var(--serif);font-size:15px;line-height:1.35}.series-item:hover b{color:var(--red)}
.headline{padding:26px 0 19px;text-align:center}.headline-label{color:var(--red);font-size:12px;font-weight:900;letter-spacing:.14em;margin-bottom:7px}.headline h1{font:900 clamp(34px,4.1vw,53px)/1.19 var(--serif);margin:0 auto 10px;max-width:1120px}.headline-dek{margin:0;color:var(--muted);font-size:16px}.headline-links{display:flex;justify-content:center;gap:10px 30px;flex-wrap:wrap;margin-top:14px;font-size:14px;font-weight:700}.headline-links a::before{content:"◆";color:var(--red);font-size:7px;margin-right:8px;vertical-align:2px}.headline-links a:hover{color:var(--red)}
.spotlight-wrap{border-top:1px solid var(--line);border-bottom:1px solid var(--line);padding:14px 0 12px}.spotlight{display:grid;grid-template-columns:1.45fr repeat(4,1fr);gap:8px}.spot-card{position:relative;height:185px;overflow:hidden;color:#fff;background:#183a55;text-align:left;padding:0}.spot-select{position:absolute;z-index:3;inset:0;width:100%;height:100%;padding:0}.spot-card svg{transition:transform .25s}.spot-card:hover svg,.spot-card.active svg{transform:scale(1.025)}.spot-card.active{box-shadow:inset 0 0 0 4px var(--red)}.spot-card.active::after{content:"";position:absolute;inset:0;border:4px solid var(--red);pointer-events:none}.spot-cap{position:absolute;left:0;right:0;bottom:0;padding:42px 11px 10px;background:linear-gradient(transparent,rgba(0,0,0,.84));font-size:14px;font-weight:800;line-height:1.35}.spot-card:first-child .spot-cap{font:800 21px/1.35 var(--serif);padding:58px 15px 13px}.spot-type{position:absolute;top:8px;left:8px;background:var(--red);padding:3px 6px;font-size:10px;font-weight:900}.spot-title{height:39px;display:flex;align-items:center;justify-content:center;font-size:13px;color:var(--muted);font-weight:700;text-align:center}
.latest{background:#f3f5f7;color:#1f2931;border-bottom:1px solid #d6dde2}.latest .wrap{min-height:42px;display:grid;grid-template-columns:auto 1fr auto;align-items:center}.latest b{align-self:stretch;background:var(--blue);color:#fff;padding:0 13px;display:flex;align-items:center;font-size:13px}.latest a{padding:0 14px;font-weight:700;font-size:13px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.latest time{font-size:12px;color:#6c767e}
.section{padding:28px 0;border-bottom:1px solid var(--line)}.section-title{min-height:40px;border-bottom:3px solid var(--blue);display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:16px}.section-title h2{margin:0;font:900 27px/1 var(--serif);color:var(--blue)}.dark .section-title h2{color:#75b8e4}.section-title h2::first-letter{color:var(--red)}.section-title a{font-size:12px;color:var(--blue-2)}
.focus-tabs{display:flex;align-items:center;gap:0;margin-bottom:13px;border-bottom:1px solid var(--line)}.focus-tabs button{height:36px;padding:0 24px;font-weight:800;border-top:3px solid transparent}.focus-tabs button.active{background:var(--blue);color:#fff;border-color:var(--red)}.focus-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:0}.focus-col{padding:0 22px;border-right:1px solid var(--line)}.focus-col:first-child{padding-left:0}.focus-col:last-child{padding-right:0;border:0}.focus-lead{display:grid;grid-template-columns:105px 1fr;gap:11px;padding-bottom:11px;border-bottom:1px solid var(--line)}.focus-thumb{aspect-ratio:1.25/1;background:#d4e0e7}.focus-lead h3{font:800 18px/1.35 var(--serif);margin:1px 0 6px}.focus-lead p{font-size:12px;color:var(--muted);margin:0}.dense-list{list-style:none;padding:0;margin:8px 0 0}.dense-list li{padding:6px 0 6px 13px;position:relative;font-size:14px;font-weight:700}.dense-list li::before{content:"";position:absolute;left:1px;top:15px;width:4px;height:4px;background:var(--blue)}.dense-list a:hover{color:var(--red)}
.named-shell{display:grid;grid-template-columns:170px 1fr;gap:24px}.named-brand{background:linear-gradient(150deg,var(--blue),var(--navy));color:#fff;padding:20px;min-height:195px;display:flex;flex-direction:column;justify-content:space-between}.named-brand h2{font:900 29px/1.15 var(--serif);margin:0}.named-brand span{font-size:12px;color:#c8dce9}.named-tags{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:15px}.named-tags button{border:1px solid var(--line);background:var(--paper);padding:7px 11px;font-size:13px;font-weight:700;transition:.2s}.named-tags button:hover,.named-tags button.active{background:var(--red);border-color:var(--red);color:#fff}.named-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:0 22px}.named-item{padding:11px 0;border-top:1px solid var(--line)}.named-item:nth-child(-n+3){border-top:0}.named-item b{display:block;font:800 17px/1.35 var(--serif)}.named-item span{font-size:12px;color:var(--muted)}
.topics{background:var(--soft)}.topic-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:12px}.topic{background:var(--paper);border-top:4px solid var(--blue);padding:14px 15px;min-height:106px;position:relative}.topic-index{position:absolute;right:12px;top:5px;font:700 38px/1 Georgia,serif;color:#e2e9ee}.dark .topic-index{color:#314450}.topic h3{position:relative;margin:0 0 9px;font:900 17px/1.35 var(--serif)}.topic p{position:relative;margin:0;color:var(--muted);font-size:12px}.topic:hover{border-color:var(--red)}
.studio-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}.studio{border:1px solid var(--line);padding:15px;display:grid;grid-template-columns:54px 1fr;gap:12px;align-items:start}.avatar{width:54px;height:54px;border-radius:50%;display:grid;place-items:center;background:var(--blue);color:#fff;font:900 24px var(--serif)}.studio:nth-child(even) .avatar{background:var(--red)}.studio b{font-size:14px}.studio p{margin:5px 0 0;font-size:12px;color:var(--muted);line-height:1.5}.studio:hover{border-color:var(--blue)}
.triple{display:grid;grid-template-columns:repeat(3,1fr);gap:25px}.column-box{border-top:4px solid var(--blue)}.column-box h2{font:900 23px var(--serif);margin:8px 0;border-bottom:1px solid var(--line);padding-bottom:8px}.column-box h2 span{color:var(--red)}.column-feature{display:grid;grid-template-columns:115px 1fr;gap:11px;margin-bottom:7px}.column-feature .visual{aspect-ratio:1.25/1}.column-feature h3{font:800 17px/1.35 var(--serif);margin:0}.column-box ul{list-style:none;padding:0;margin:0}.column-box li{padding:7px 0;border-top:1px dotted var(--line);font-size:13px;font-weight:700}.column-box a:hover{color:var(--red)}.visual{overflow:hidden;background:#c8d7df}.visual svg{width:100%;height:100%}.live-button{width:100%;padding:0;text-align:left}
.local-shell{border:1px solid var(--line)}.province-bar{display:flex;align-items:center;background:var(--soft);overflow:auto;scrollbar-width:none}.province-bar b{align-self:stretch;background:var(--blue);color:#fff;padding:0 17px;display:flex;align-items:center;white-space:nowrap}.province-bar button{height:44px;padding:0 12px;white-space:nowrap;font-size:13px}.province-bar button:hover,.province-bar button.active{color:var(--red);font-weight:900;background:var(--paper)}.local-content{padding:17px;display:grid;grid-template-columns:1.1fr 1fr;gap:28px}.local-lead{display:grid;grid-template-columns:180px 1fr;gap:15px}.local-lead .visual{aspect-ratio:4/3}.local-lead h3{font:900 22px/1.35 var(--serif);margin:0 0 8px}.local-lead p{font-size:13px;color:var(--muted);margin:0}.local-list{display:grid;grid-template-columns:1fr 1fr;gap:0 18px}.local-list a{padding:8px 0;border-bottom:1px solid var(--line);font-size:13px;font-weight:700}.local-list a:hover{color:var(--red)}
.industry-grid{display:grid;grid-template-columns:repeat(4,1fr);border:1px solid var(--line)}.industry{padding:16px;border-right:1px solid var(--line);border-bottom:1px solid var(--line);min-height:154px}.industry:nth-child(4n){border-right:0}.industry:nth-last-child(-n+4){border-bottom:0}.industry h3{margin:0 0 9px;padding-bottom:7px;border-bottom:2px solid var(--blue);font:900 18px var(--serif);display:flex;justify-content:space-between}.industry h3 a{font:12px var(--sans);color:var(--blue-2)}.industry ul{list-style:none;margin:0;padding:0}.industry li{font-size:12px;font-weight:700;padding:4px 0}.industry li::before{content:"·";color:var(--red);margin-right:5px}
.matrix{display:grid;grid-template-columns:1.3fr repeat(4,1fr);background:var(--navy);color:#fff}.matrix-intro{padding:22px}.matrix-intro h2{font:900 26px var(--serif);margin:0 0 4px}.matrix-intro p{font-size:12px;color:#c9dae6;margin:0}.matrix-item{border-left:1px solid rgba(255,255,255,.18);padding:18px;display:flex;align-items:center;gap:10px}.matrix-icon{width:42px;height:42px;border:1px solid rgba(255,255,255,.55);border-radius:8px;display:grid;place-items:center;flex:0 0 auto}.matrix-icon svg{width:21px;height:21px;fill:none;stroke:currentColor;stroke-width:2}.matrix-item b{font-size:13px}.matrix-item small{display:block;color:#bcd0de}
.newsletter{margin:27px auto;border:1px solid var(--line);border-left:7px solid var(--red);padding:20px 23px;display:grid;grid-template-columns:1fr 1fr;gap:28px;align-items:center}.newsletter h2{font:900 23px var(--serif);margin:0 0 5px}.newsletter p{margin:0;font-size:13px;color:var(--muted)}.sub-form{display:grid;grid-template-columns:1fr auto;gap:7px}.sub-form input{height:44px;min-width:0;border:1px solid #95a1ab;background:var(--paper);color:var(--ink);padding:0 12px}.sub-form button{height:44px;background:var(--blue);color:#fff;padding:0 18px;font-weight:800}.sub-status{grid-column:1/-1;min-height:16px;font-size:11px;color:var(--muted)}
footer{background:#edf2f5;border-top:4px solid var(--blue);color:#5d6a74}.dark footer{background:#0a1218}.foot{padding:25px 0}.foot-top{display:flex;align-items:center}.foot .brand-seal{width:42px;height:42px}.foot .brand-name{font-size:25px}.foot-links{margin-left:auto;display:flex;gap:20px;font-size:12px}.foot-links a:hover{color:var(--red)}.foot-bottom{margin-top:18px;padding-top:14px;border-top:1px solid #cbd5dc;display:flex;justify-content:space-between;font-size:11px}.dark .foot-bottom{border-color:#31414d}
.overlay{position:fixed;inset:0;z-index:150;background:rgba(0,0,0,.78);display:none;align-items:center;justify-content:center;padding:20px}.overlay.open{display:flex}.modal{width:min(800px,100%);background:var(--paper);color:var(--ink);box-shadow:0 18px 60px rgba(0,0,0,.45)}.modal-head{height:58px;background:var(--blue);color:#fff;padding:0 17px;display:flex;align-items:center}.live-dot{width:9px;height:9px;border-radius:50%;background:#ff4053;box-shadow:0 0 0 4px rgba(255,64,83,.25);margin-right:9px}.close{margin-left:auto;width:44px;height:44px;color:#fff;font-size:28px}.player{aspect-ratio:16/9;background:radial-gradient(circle,#28577a,#061d30 68%);color:#fff;display:grid;place-items:center;position:relative;overflow:hidden}.player::before,.player::after{content:"";position:absolute;border:1px solid rgba(255,255,255,.13);width:60%;height:60%;transform:rotate(45deg)}.player::after{width:36%;height:36%}.player-copy{position:relative;z-index:2;text-align:center}.player-copy b{display:block;font:900 29px var(--serif)}.player-copy span{color:#c7d8e4}.modal-foot{padding:14px 18px;display:flex;justify-content:space-between;font-size:13px;color:var(--muted)}
.drawer{position:fixed;inset:0;z-index:160;background:rgba(0,0,0,.72);display:none}.drawer.open{display:block}.drawer-panel{height:100%;width:min(390px,90vw);background:var(--paper);padding:20px;transform:translateX(-100%);transition:transform .22s}.drawer.open .drawer-panel{transform:none}.drawer-head{display:flex;align-items:center;border-bottom:3px solid var(--blue);padding-bottom:15px}.drawer-head .brand-seal{width:46px;height:46px}.drawer-head .brand-name{font-size:26px;margin-left:9px}.drawer-head .close{color:var(--ink)}.drawer-links{display:grid;grid-template-columns:1fr 1fr}.drawer-links a{padding:13px 6px;border-bottom:1px solid var(--line);font-weight:700}.drawer-links a:hover{color:var(--red)}.toast{position:fixed;right:18px;bottom:18px;z-index:180;background:#111;color:#fff;padding:12px 16px;font-size:13px;transform:translateY(100px);opacity:0;transition:.22s}.toast.show{transform:none;opacity:1}
.settings-overlay{position:fixed;inset:0;z-index:400;display:none;align-items:center;justify-content:center;padding:30px;background:rgba(4,15,25,.84);backdrop-filter:blur(4px)}.settings-overlay.open{display:flex}.json-settings-modal{width:min(1340px,100%);height:min(820px,calc(100vh - 60px));background:#0a1625;color:#e9f4ff;border:1px solid #3a7ca7;box-shadow:0 24px 80px rgba(0,0,0,.5);display:grid;grid-template-rows:auto 1fr auto}.settings-head{min-height:108px;padding:22px 28px;border-bottom:1px solid #274865;display:flex;align-items:center}.settings-kicker{display:block;color:#42bdf4;font-size:13px;font-weight:900;letter-spacing:.11em}.settings-head h2{margin:5px 0 0;font-size:27px}.settings-close{margin-left:auto;width:48px;height:48px;border:1px solid #4382a8;color:#fff;font-size:29px}.settings-body{min-height:0;display:grid;grid-template-columns:285px 1fr;gap:22px;padding:22px 28px}.module-tabs{min-height:0;overflow:auto}.module-tabs h3{margin:0 0 10px;color:#96b7d1;font-size:14px}.module-tab{display:block;width:100%;padding:11px 14px;margin-bottom:7px;text-align:left;border:1px solid #284e6d;background:#0d2033;color:#d4e6f4}.module-tab strong,.module-tab span{display:block}.module-tab strong{font-size:15px}.module-tab span{margin-top:2px;color:#83a3bb;font-size:11px}.module-tab.active{border-color:#34b8f3;background:#12314a;box-shadow:inset 3px 0 #34b8f3}.editor-pane{min-width:0;min-height:0;display:grid;grid-template-rows:auto 1fr auto}.editor-title{display:flex;justify-content:space-between;align-items:center;margin-bottom:9px}.editor-title span,.editor-hint{color:#85a3bb;font-size:12px}.json-editor{width:100%;min-height:0;resize:none;border:1px solid #2d6d95;background:#020b13;color:#dff5ff;padding:18px;font:14px/1.55 Consolas,"Courier New",monospace;tab-size:2}.editor-hint{display:flex;justify-content:space-between;margin-top:9px}.json-status.valid{color:#5de2b2}.json-status.invalid{color:#ff8b8b}.settings-foot{min-height:86px;border-top:1px solid #274865;padding:18px 28px;display:flex;justify-content:flex-end;align-items:center;gap:10px}.editor-button{height:44px;padding:0 20px;border:1px solid #4382a8;color:#e9f4ff;background:#0d2033}.editor-button.primary{background:#35b8ef;color:#04121e;border-color:#35b8ef;font-weight:900}
@media(max-width:1000px){.motto{display:none}.primary-nav a:nth-last-child(-n+4){display:none}.series .wrap{grid-template-columns:105px repeat(3,1fr)}.series-item:last-child{display:none}.spotlight{grid-template-columns:1.4fr repeat(3,1fr)}.spot-card:last-child{display:none}.focus-grid{grid-template-columns:1fr 1fr}.focus-col:last-child{display:none}.focus-col:nth-child(2){border:0;padding-right:0}.named-grid{grid-template-columns:1fr 1fr}.named-item:nth-child(3){border-top:1px solid var(--line)}.topic-grid,.studio-grid{grid-template-columns:1fr 1fr}.triple{grid-template-columns:1fr 1fr}.column-box:last-child{grid-column:1/-1}.local-content{grid-template-columns:1fr}.industry-grid{grid-template-columns:repeat(3,1fr)}.industry:nth-child(4n){border-right:1px solid var(--line)}.industry:nth-child(3n){border-right:0}.matrix{grid-template-columns:1.2fr repeat(2,1fr)}.matrix-item:nth-last-child(-n+2){display:none}.settings-body{grid-template-columns:235px 1fr}}
@media(max-width:720px){.wrap{width:calc(100% - 28px)}.network{display:none}.mast{height:70px}.mast .wrap{width:100%;padding:0 11px}.mobile-menu{display:flex}.brand-seal{width:45px;height:45px}.brand-name{font-size:27px}.brand-en{display:none}.mast-tools{gap:0}.tool{padding:0}.tool span{display:none}.mast-tools .client-tool{display:none}.primary-nav .wrap{width:100%;padding:0 5px;overflow-x:auto}.primary-nav a{padding:0 13px}.primary-nav a:nth-child(n+7){display:none}.primary-nav a:last-child{display:flex;margin-left:0}.settings-trigger{right:10px;top:126px;width:40px;height:40px}.series{overflow:hidden}.series .wrap{width:100%;grid-template-columns:90px repeat(2,230px);overflow-x:auto}.series-item:nth-child(n+4){display:none}.headline{padding:20px 0 15px}.headline h1{font-size:30px;line-height:1.28}.headline-dek{font-size:14px}.headline-links{justify-content:flex-start;text-align:left;gap:6px}.headline-links a{width:100%}.spotlight-wrap{padding:10px 0}.spotlight{display:flex;overflow-x:auto;scroll-snap-type:x mandatory;gap:9px;padding-bottom:4px}.spot-card{min-width:82%;height:190px;scroll-snap-align:center}.spot-card:first-child .spot-cap{font-size:18px}.latest .wrap{width:100%;grid-template-columns:auto 1fr}.latest time{display:none}.focus-tabs{overflow-x:auto}.focus-tabs button{padding:0 18px}.focus-grid{display:block}.focus-col{padding:0!important;border:0}.focus-col+.focus-col{margin-top:18px;padding-top:16px!important;border-top:1px solid var(--line)}.focus-col:last-child{display:block}.named-shell{display:block}.named-brand{min-height:auto;margin-bottom:14px}.named-brand span{margin-top:20px}.named-grid{display:block}.named-item:nth-child(-n+3){border-top:1px solid var(--line)}.named-item:first-child{border-top:0}.topic-grid,.studio-grid{grid-template-columns:1fr 1fr;gap:10px}.studio{display:block}.avatar{margin-bottom:9px}.triple{display:block}.column-box+.column-box{margin-top:24px}.local-content{padding:13px}.local-lead{grid-template-columns:1fr}.local-lead .visual{aspect-ratio:16/9}.local-list{grid-template-columns:1fr}.industry-grid{grid-template-columns:1fr 1fr}.industry:nth-child(3n){border-right:1px solid var(--line)}.industry:nth-child(even){border-right:0}.matrix{grid-template-columns:1fr 1fr}.matrix-intro{grid-column:1/-1}.matrix-item:nth-last-child(-n+2){display:flex}.newsletter{grid-template-columns:1fr}.foot-top,.foot-bottom{display:block}.foot-links{margin:16px 0 0;display:grid;grid-template-columns:1fr 1fr;gap:9px}.foot-bottom span{display:block;margin-top:6px}.settings-overlay{padding:0}.json-settings-modal{height:100vh;width:100%;border:0}.settings-head{min-height:78px;padding:14px 16px}.settings-head h2{font-size:22px}.settings-body{display:block;padding:14px 16px;overflow:auto}.module-tabs{display:flex;gap:7px;overflow-x:auto;margin-bottom:12px}.module-tabs h3{display:none}.module-tab{min-width:145px;margin:0}.json-editor{height:54vh}.settings-foot{padding:10px 16px;overflow-x:auto;justify-content:flex-start}.editor-button{white-space:nowrap}}
@media(max-width:720px){.settings-trigger{top:calc(var(--df-generated-header-height,0px) + 126px)}}
@media(max-width:420px){.topic-grid,.studio-grid{grid-template-columns:1fr}.industry-grid{display:block}.industry{border-right:0!important;border-bottom:1px solid var(--line)!important}.industry:last-child{border-bottom:0!important}.sub-form{display:block}.sub-form input,.sub-form button{width:100%;margin-bottom:8px}.modal-foot{display:block}.modal-foot button{margin-top:8px}}
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important;animation:none!important}}
.skip{transform:translateY(calc(-100% - var(--df-generated-header-height,0px) - 24px))}.skip:focus{transform:none}
.overlay,.drawer{z-index:1200}.settings-overlay{z-index:1300}
</style>
</head>
<body id="top">
<a class="skip" href="#main">跳到主要内容</a>
<header>
<div class="network"><div class="wrap"><nav class="network-links" id="networkLeft" aria-label="国际语言"></nav><nav class="network-links" id="networkRight" aria-label="机构服务"></nav></div></div>
<div class="mast"><div class="wrap">
<button class="tool mobile-menu" id="menuOpen" aria-label="打开菜单"><svg viewBox="0 0 24 24"><path d="M4 7h16M4 12h16M4 17h16"/></svg></button>
<a class="brand" href="#top" id="brandLink"><span class="brand-seal"><svg viewBox="0 0 64 64" aria-hidden="true"><path d="M8 42c14-2 24-12 31-30 1 15 7 25 17 31-12-2-22 1-30 10 2-8 0-14-5-19-2 5-6 8-13 8Z" fill="#fff"/><path d="M17 45c12-4 20-11 24-21" stroke="#fff" stroke-width="3" fill="none"/></svg></span><span><span class="brand-name" id="brandName"></span><span class="brand-en" id="brandEnglish"></span></span></a>
<div class="motto" id="motto"></div>
<div class="mast-tools"><button class="tool" id="theme"><svg viewBox="0 0 24 24"><path d="M20.5 14.4A8.6 8.6 0 0 1 9.6 3.5a8.7 8.7 0 1 0 10.9 10.9Z"/></svg><span id="themeLabel">夜间</span></button><button class="tool client-tool"><svg viewBox="0 0 24 24"><path d="M6 3h12v18H6Z"/><path d="M10 17h4"/></svg><span id="clientLabel"></span></button><button class="tool" id="searchOpen" aria-label="搜索"><svg viewBox="0 0 24 24"><circle cx="10.8" cy="10.8" r="6.8"/><path d="m19.5 19.5-4-4"/></svg><span>搜索</span></button></div>
</div></div>
<nav class="primary-nav" aria-label="主导航"><div class="wrap" id="primaryNav"></div></nav>
<div class="search-panel" id="searchPanel"><form class="wrap search-form" id="searchForm"><label id="searchLabel" for="search"></label><input id="search" type="search"><button id="searchButton"></button></form><div class="wrap search-status" id="searchStatus" aria-live="polite"></div></div>
</header>
<button class="settings-trigger" id="openSettings" aria-label="编辑页面 JSON" title="编辑页面 JSON"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3.5"/><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-.3A1.7 1.7 0 0 0 14 21v.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"/></svg></button>
<main id="main" tabindex="-1">
<section class="series"><div class="wrap"><div class="series-title"><span id="seriesTitle"></span><small id="seriesEnglish"></small></div><div id="seriesItems" style="display:contents"></div></div></section>
<section class="headline wrap"><div class="headline-label" id="headlineKicker"></div><h1 id="headlineTitle"></h1><p class="headline-dek" id="headlineSummary"></p><div class="headline-links" id="headlineLinks"></div></section>
<section class="spotlight-wrap"><div class="wrap"><div class="spotlight" id="spotlight" role="list" aria-label="焦点图集"></div><div class="spot-title" id="spotTitle"></div></div></section>
<div class="latest"><div class="wrap"><b id="latestLabel"></b><a id="latestTitle"></a><time id="latestTime"></time></div></div>
<section class="section wrap" id="focus"><div class="section-title"><h2 id="focusTitle"></h2><a id="focusMore" href="#focus"></a></div><div class="focus-tabs" id="focusTabs" role="tablist"></div><div class="focus-grid" id="focusGrid"></div></section>
<section class="section wrap" id="features"><div class="named-shell"><div class="named-brand"><h2 id="columnTitle"></h2><span id="columnSubtitle"></span></div><div><div class="named-tags" id="featureTags"></div><div class="named-grid" id="featureArticles"></div></div></div></section>
<section class="section topics" id="topics"><div class="wrap"><div class="section-title"><h2 id="topicsTitle"></h2><a id="topicsMore" href="#topics"></a></div><div class="topic-grid" id="topicGrid"></div></div></section>
<section class="section wrap" id="studios"><div class="section-title"><h2 id="studiosTitle"></h2><a id="studiosMore" href="#studios"></a></div><div class="studio-grid" id="studioGrid"></div></section>
<section class="section wrap" id="media"><div class="triple" id="editorialColumns"></div></section>
<section class="section wrap" id="local"><div class="section-title"><h2 id="localTitle"></h2><a id="localMore" href="#local"></a></div><div class="local-shell"><div class="province-bar" id="provinceBar"></div><div class="local-content" id="localContent"></div></div></section>
<section class="section wrap" id="industry"><div class="section-title"><h2 id="industryTitle"></h2><a id="industryMore" href="#industry"></a></div><div class="industry-grid" id="industryGrid"></div></section>
<section class="section wrap" id="services"><div class="matrix" id="mediaMatrix"></div></section>
<section class="newsletter wrap" id="newsletter"><div><h2 id="newsletterTitle"></h2><p id="newsletterText"></p></div><form class="sub-form" id="subForm"><label class="sr-only" for="email">邮箱地址</label><input id="email" type="email" required><button id="newsletterButton"></button><div class="sub-status" id="subStatus" aria-live="polite"></div></form></section>
</main>
<footer id="about"><div class="wrap foot"><div class="foot-top"><a class="brand" href="#top"><span class="brand-seal"><svg viewBox="0 0 64 64" aria-hidden="true"><path d="M8 42c14-2 24-12 31-30 1 15 7 25 17 31-12-2-22 1-30 10 2-8 0-14-5-19-2 5-6 8-13 8Z" fill="#fff"/></svg></span><span class="brand-name" id="footerBrand"></span></a><nav class="foot-links" id="footerLinks"></nav></div><div class="foot-bottom"><span id="copyright"></span><span id="legal"></span></div></div></footer>
<div class="overlay" id="liveModal" role="dialog" aria-modal="true" aria-labelledby="liveTitle"><div class="modal"><div class="modal-head"><span class="live-dot"></span><b id="liveTitle"></b><button class="close" id="liveClose" aria-label="关闭直播">×</button></div><div class="player"><div class="player-copy"><b id="streamTitle"></b><span id="streamSubtitle"></span></div></div><div class="modal-foot"><span id="currentProgram"></span><button id="caption">CC 字幕:开</button></div></div></div>
<div class="drawer" id="drawer" role="dialog" aria-modal="true" aria-label="移动端导航"><aside class="drawer-panel"><div class="drawer-head"><span class="brand-seal"><svg viewBox="0 0 64 64" aria-hidden="true"><path d="M8 42c14-2 24-12 31-30 1 15 7 25 17 31-12-2-22 1-30 10 2-8 0-14-5-19-2 5-6 8-13 8Z" fill="#fff"/></svg></span><span class="brand-name" id="drawerBrand"></span><button class="close" id="menuClose" aria-label="关闭菜单">×</button></div><nav class="drawer-links" id="drawerLinks"></nav></aside></div>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<div class="settings-overlay" id="settingsOverlay" aria-hidden="true"><section class="json-settings-modal" role="dialog" aria-modal="true" aria-labelledby="settingsTitle"><header class="settings-head"><div><span class="settings-kicker">XINHUA TEMPLATE CONTROL</span><h2 id="settingsTitle">JSON 编辑器</h2></div><button class="settings-close" id="closeSettings" aria-label="关闭 JSON 编辑器">×</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="xinhuaPageData">__XINHUA_PAGE_DATA__</script>
<script>__XINHUA_PAGE_RUNTIME__</script>
</body>
</html>
@@ -0,0 +1,25 @@
# 新华社页面 JSON 契约
顶层必须完整包含 `site`、`navigation`、`specials`、`headline`、`focus`、`features`、`channels`、`local`、`services`、`footer`。弹窗按十个模块分别编辑,应用时重新校验完整文档。
## 通用规则
- 所有标题、标签、摘要和时间为字符串;关键展示字段不能为空。
- 列表有数量上限,同一业务列表中的 `id` 必须唯一。
- `href` 只允许以 `#` 开头的页面内锚点。
- JSON 文本不能包含 HTML、脚本、直接 iframe 或可执行代码。具有 `visual` 的对象可增加 `media` 替换视觉:图片 `{type:"image", mediaUrl, alt?, pageUrl?}`;视频 `{type:"video", mediaUrl, posterUrl?, alt?, pageUrl?}`;网页 `{type:"webpage", pageUrl, title, description?, mediaUrl?, embed?}`。仅这些媒体 URL 字段允许 `http(s)`,图片/视频也允许对应的 `data:` URL。
## 模块
- `site`:机构名称、英文名、页面标题、描述、口号、客户端文案和 `theme`(`light`/`dark`/`auto`)。
- `navigation`:多语种顶栏左右链接、1–16 个主导航、1–16 个移动菜单链接,以及搜索文案。
- `specials`:1–4 条报道专集、1–5 个焦点图和一条最新播报。焦点图 `visual` 为 `harvest`、`railway`、`satellite`、`culture`、`wetland`。
- `headline`:总头条标签、标题、摘要和 1–6 条关联阅读。
- `focus.tabs`:1–5 个分类;每类包含 1–4 列,每列有主标题、摘要、视觉类型和 1–5 条短链接。视觉类型为 `city`、`economy`、`world`、`green`、`technology`。
- `features`:名专栏标签与文章、1–12 个热点专题、1–8 个记者工作室。
- `channels`:1–5 个网评/访谈/视频栏目和 1–12 个行业频道;栏目视觉类型为 `commentary`、`interview`、`video`,其中 `live: true` 打开直播弹窗。
- `local.provinces`:1–16 个地区;每个地区包含主标题、摘要、视觉类型和 1–8 条地方报道。视觉类型为 `capital`、`coast`、`mountain`、`river`、`bay`。
- `services`:1–4 个媒体矩阵入口,`icon` 为 `app`、`video`、`platform`、`radio`;另含直播弹窗和早报订阅文案。
- `footer.links`:1–10 个机构链接;另有版权与服务说明。
JSON 使用双引号,不允许注释、Markdown 围栏或尾逗号。`assets/default-data.json` 只是结构和演示内容,不是事实来源。
@@ -0,0 +1,11 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "_shared"))
import render_xinhua_page as renderer
from fast_patch_page import run
if __name__ == "__main__":
sys.exit(run(renderer, output_stem="xinhua-page"))
@@ -0,0 +1,631 @@
#!/usr/bin/env python3
"""Validate Xinhua page data and render the bundled self-contained template."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
SKILL_DIR = Path(__file__).resolve().parents[1]
ASSETS_DIR = SKILL_DIR / "assets"
DEFAULT_DATA_PATH = ASSETS_DIR / "default-data.json"
TEMPLATE_PATH = ASSETS_DIR / "xinhua-template.html"
RUNTIME_PATH = ASSETS_DIR / "xinhua-runtime.js"
MODULES = (
"site",
"navigation",
"specials",
"headline",
"focus",
"features",
"channels",
"local",
"services",
"footer",
)
SPOT_VISUALS = {"harvest", "railway", "satellite", "culture", "wetland"}
FOCUS_VISUALS = {"city", "economy", "world", "green", "technology"}
CHANNEL_VISUALS = {"commentary", "interview", "video"}
LOCAL_VISUALS = {"capital", "coast", "mountain", "river", "bay"}
SERVICE_ICONS = {"app", "video", "platform", "radio"}
FORBIDDEN_TEXT = ("<script", "<iframe", "javascript:", "http://", "https://")
REMOTE_MEDIA_TYPES = {"image", "video", "webpage"}
MEDIA_URL_KEYS = {"mediaUrl", "posterUrl", "pageUrl"}
class DataValidationError(ValueError):
"""Raised when page JSON does not satisfy the fixed template contract."""
def _read_json(path: Path) -> dict[str, Any]:
try:
value = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError as exc:
raise DataValidationError(f"input 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(value, dict):
raise DataValidationError("top-level JSON value must be an object")
return value
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],
*,
minimum: int = 0,
maximum: int | None = None,
) -> list[Any]:
if not isinstance(value, list):
errors.append(f"{path} must be an array")
return []
if len(value) < minimum:
errors.append(f"{path} must contain at least {minimum} item(s)")
if maximum is not None and len(value) > maximum:
errors.append(f"{path} must contain at most {maximum} item(s)")
return value
def _required_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 _string(value: Any, path: str, errors: list[str]) -> None:
if not isinstance(value, str):
errors.append(f"{path} must be a string")
def _href(value: Any, path: str, errors: list[str]) -> None:
_required_string(value, path, errors)
if isinstance(value, str) and not value.startswith("#"):
errors.append(f"{path} must be an in-page anchor beginning with #")
def _unique_id(item: dict[str, Any], path: str, seen: set[str], errors: list[str]) -> None:
item_id = item.get("id")
_required_string(item_id, f"{path}.id", errors)
if isinstance(item_id, str):
if item_id in seen:
errors.append(f"{path}.id duplicates {item_id!r}")
seen.add(item_id)
def _strings(
value: Any,
path: str,
errors: list[str],
*,
minimum: int = 0,
maximum: int | None = None,
) -> list[Any]:
values = _array(value, path, errors, minimum=minimum, maximum=maximum)
for index, item in enumerate(values):
_required_string(item, f"{path}[{index}]", errors)
return values
def _links(
value: Any,
path: str,
errors: list[str],
*,
minimum: int,
maximum: int,
) -> list[Any]:
items = _array(value, path, errors, minimum=minimum, maximum=maximum)
for index, raw in enumerate(items):
item = _mapping(raw, f"{path}[{index}]", errors)
_required_string(item.get("label"), f"{path}[{index}].label", errors)
_href(item.get("href"), f"{path}[{index}].href", errors)
return items
def _id_title_items(
value: Any,
path: str,
errors: list[str],
*,
minimum: int,
maximum: int,
) -> list[Any]:
items = _array(value, path, errors, minimum=minimum, maximum=maximum)
seen: set[str] = set()
for index, raw in enumerate(items):
item_path = f"{path}[{index}]"
item = _mapping(raw, item_path, errors)
_unique_id(item, item_path, seen, errors)
_required_string(item.get("title"), f"{item_path}.title", errors)
return items
def _validate_no_remote_or_markup(value: Any, path: str, errors: list[str]) -> None:
if isinstance(value, dict):
for key, item in value.items():
if key in MEDIA_URL_KEYS:
continue
_validate_no_remote_or_markup(item, f"{path}.{key}", errors)
elif isinstance(value, list):
for index, item in enumerate(value):
_validate_no_remote_or_markup(item, f"{path}[{index}]", errors)
elif isinstance(value, str):
lowered = value.lower()
if any(token in lowered for token in FORBIDDEN_TEXT):
errors.append(f"{path} must not contain HTML, script, iframe, or remote URLs")
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_tree(value: Any, path: str, errors: list[str]) -> None:
if isinstance(value, list):
for index, item in enumerate(value):
_validate_remote_media_tree(item, f"{path}[{index}]", errors)
return
if not isinstance(value, dict):
return
media = value.get("media")
if isinstance(media, dict) and "type" in media:
media_path = f"{path}.media"
media_data = _mapping(media, media_path, errors)
media_type = media_data.get("type")
if media_type not in REMOTE_MEDIA_TYPES:
errors.append(f"{media_path}.type must be one of: {', '.join(sorted(REMOTE_MEDIA_TYPES))}")
elif media_type in {"image", "video"}:
_remote_url(media_data.get("mediaUrl"), f"{media_path}.mediaUrl", errors, required=True, data_prefix=f"data:{media_type}/")
if media_type == "video":
_remote_url(media_data.get("posterUrl"), f"{media_path}.posterUrl", errors, data_prefix="data:image/")
if media_type == "webpage":
_remote_url(media_data.get("pageUrl"), f"{media_path}.pageUrl", errors, required=True)
_remote_url(media_data.get("mediaUrl"), f"{media_path}.mediaUrl", errors, data_prefix="data:image/")
if "embed" in media_data and not isinstance(media_data.get("embed"), bool):
errors.append(f"{media_path}.embed must be a boolean")
elif media_type in {"image", "video"}:
_remote_url(media_data.get("pageUrl"), f"{media_path}.pageUrl", errors)
for key, item in value.items():
if key != "media":
_validate_remote_media_tree(item, f"{path}.{key}", errors)
def validate_document(data: dict[str, Any]) -> dict[str, int]:
errors: list[str] = []
missing = [name for name in MODULES if name not in data]
extra = [name for name in data if name not in MODULES]
if missing:
errors.append("missing top-level module(s): " + ", ".join(missing))
if extra:
errors.append("unknown top-level module(s): " + ", ".join(extra))
site = _mapping(data.get("site"), "site", errors)
for key in (
"brandName",
"brandEnglish",
"pageTitle",
"description",
"motto",
"clientLabel",
):
_required_string(site.get(key), f"site.{key}", errors)
if site.get("theme") not in {"light", "dark", "auto"}:
errors.append("site.theme must be light, dark, or auto")
navigation = _mapping(data.get("navigation"), "navigation", errors)
network_left = _links(
navigation.get("networkLeft"),
"navigation.networkLeft",
errors,
minimum=1,
maximum=8,
)
network_right = _links(
navigation.get("networkRight"),
"navigation.networkRight",
errors,
minimum=1,
maximum=6,
)
primary = _links(
navigation.get("primary"),
"navigation.primary",
errors,
minimum=1,
maximum=16,
)
drawer = _links(
navigation.get("drawer"),
"navigation.drawer",
errors,
minimum=1,
maximum=16,
)
for key in ("searchLabel", "searchPlaceholder", "searchButton"):
_required_string(navigation.get(key), f"navigation.{key}", errors)
specials = _mapping(data.get("specials"), "specials", errors)
_required_string(specials.get("seriesTitle"), "specials.seriesTitle", errors)
_required_string(specials.get("seriesEnglish"), "specials.seriesEnglish", errors)
series_items = _array(
specials.get("seriesItems"),
"specials.seriesItems",
errors,
minimum=1,
maximum=4,
)
seen_series: set[str] = set()
for index, raw in enumerate(series_items):
item_path = f"specials.seriesItems[{index}]"
item = _mapping(raw, item_path, errors)
_unique_id(item, item_path, seen_series, errors)
_required_string(item.get("title"), f"{item_path}.title", errors)
_href(item.get("href"), f"{item_path}.href", errors)
_required_string(specials.get("spotlightLabel"), "specials.spotlightLabel", errors)
spotlight_items = _array(
specials.get("spotlightItems"),
"specials.spotlightItems",
errors,
minimum=1,
maximum=5,
)
seen_spotlight: set[str] = set()
for index, raw in enumerate(spotlight_items):
item_path = f"specials.spotlightItems[{index}]"
item = _mapping(raw, item_path, errors)
_unique_id(item, item_path, seen_spotlight, errors)
_required_string(item.get("title"), f"{item_path}.title", errors)
_string(item.get("tag"), f"{item_path}.tag", errors)
if item.get("visual") not in SPOT_VISUALS:
errors.append(f"{item_path}.visual must be one of {sorted(SPOT_VISUALS)}")
latest = _mapping(specials.get("latest"), "specials.latest", errors)
for key in ("label", "title", "time"):
_required_string(latest.get(key), f"specials.latest.{key}", errors)
_href(latest.get("href"), "specials.latest.href", errors)
headline = _mapping(data.get("headline"), "headline", errors)
for key in ("kicker", "title", "summary"):
_required_string(headline.get(key), f"headline.{key}", errors)
headline_links = _links(
headline.get("links"),
"headline.links",
errors,
minimum=1,
maximum=6,
)
focus = _mapping(data.get("focus"), "focus", errors)
_required_string(focus.get("title"), "focus.title", errors)
_required_string(focus.get("moreLabel"), "focus.moreLabel", errors)
tabs = _array(focus.get("tabs"), "focus.tabs", errors, minimum=1, maximum=5)
seen_tabs: set[str] = set()
focus_columns = 0
for tab_index, raw_tab in enumerate(tabs):
tab_path = f"focus.tabs[{tab_index}]"
tab = _mapping(raw_tab, tab_path, errors)
_unique_id(tab, tab_path, seen_tabs, errors)
_required_string(tab.get("label"), f"{tab_path}.label", errors)
columns = _array(
tab.get("columns"),
f"{tab_path}.columns",
errors,
minimum=1,
maximum=4,
)
focus_columns += len(columns)
seen_columns: set[str] = set()
for column_index, raw_column in enumerate(columns):
column_path = f"{tab_path}.columns[{column_index}]"
column = _mapping(raw_column, column_path, errors)
_unique_id(column, column_path, seen_columns, errors)
_required_string(column.get("leadTitle"), f"{column_path}.leadTitle", errors)
_required_string(column.get("summary"), f"{column_path}.summary", errors)
if column.get("visual") not in FOCUS_VISUALS:
errors.append(
f"{column_path}.visual must be one of {sorted(FOCUS_VISUALS)}"
)
_strings(
column.get("links"),
f"{column_path}.links",
errors,
minimum=1,
maximum=5,
)
features = _mapping(data.get("features"), "features", errors)
for key in (
"columnTitle",
"columnSubtitle",
"topicsTitle",
"topicsMoreLabel",
"studiosTitle",
"studiosMoreLabel",
):
_required_string(features.get(key), f"features.{key}", errors)
tags = _strings(features.get("tags"), "features.tags", errors, minimum=1, maximum=10)
articles = _id_title_items(
features.get("articles"),
"features.articles",
errors,
minimum=1,
maximum=12,
)
for index, raw in enumerate(articles):
item = _mapping(raw, f"features.articles[{index}]", errors)
_required_string(item.get("meta"), f"features.articles[{index}].meta", errors)
topics = _id_title_items(
features.get("topics"),
"features.topics",
errors,
minimum=1,
maximum=12,
)
for index, raw in enumerate(topics):
item = _mapping(raw, f"features.topics[{index}]", errors)
_required_string(item.get("summary"), f"features.topics[{index}].summary", errors)
studios = _array(
features.get("studios"),
"features.studios",
errors,
minimum=1,
maximum=8,
)
seen_studios: set[str] = set()
for index, raw in enumerate(studios):
item_path = f"features.studios[{index}]"
item = _mapping(raw, item_path, errors)
_unique_id(item, item_path, seen_studios, errors)
for key in ("initial", "name", "bio"):
_required_string(item.get(key), f"{item_path}.{key}", errors)
if isinstance(item.get("initial"), str) and len(item["initial"]) > 2:
errors.append(f"{item_path}.initial must contain at most 2 characters")
channels = _mapping(data.get("channels"), "channels", errors)
editorial = _array(
channels.get("editorialColumns"),
"channels.editorialColumns",
errors,
minimum=1,
maximum=5,
)
seen_editorial: set[str] = set()
live_count = 0
for index, raw in enumerate(editorial):
item_path = f"channels.editorialColumns[{index}]"
item = _mapping(raw, item_path, errors)
_unique_id(item, item_path, seen_editorial, errors)
for key in ("accent", "title", "feature"):
_required_string(item.get(key), f"{item_path}.{key}", errors)
if item.get("visual") not in CHANNEL_VISUALS:
errors.append(f"{item_path}.visual must be one of {sorted(CHANNEL_VISUALS)}")
if not isinstance(item.get("live"), bool):
errors.append(f"{item_path}.live must be a boolean")
elif item["live"]:
live_count += 1
_strings(item.get("links"), f"{item_path}.links", errors, minimum=1, maximum=6)
_required_string(channels.get("industryTitle"), "channels.industryTitle", errors)
_required_string(channels.get("industryMoreLabel"), "channels.industryMoreLabel", errors)
industries = _array(
channels.get("industries"),
"channels.industries",
errors,
minimum=1,
maximum=12,
)
seen_industries: set[str] = set()
for index, raw in enumerate(industries):
item_path = f"channels.industries[{index}]"
item = _mapping(raw, item_path, errors)
_unique_id(item, item_path, seen_industries, errors)
_required_string(item.get("title"), f"{item_path}.title", errors)
_strings(item.get("items"), f"{item_path}.items", errors, minimum=1, maximum=6)
local = _mapping(data.get("local"), "local", errors)
for key in ("title", "moreLabel", "selectorLabel"):
_required_string(local.get(key), f"local.{key}", errors)
provinces = _array(
local.get("provinces"),
"local.provinces",
errors,
minimum=1,
maximum=16,
)
seen_provinces: set[str] = set()
for index, raw in enumerate(provinces):
item_path = f"local.provinces[{index}]"
item = _mapping(raw, item_path, errors)
_unique_id(item, item_path, seen_provinces, errors)
for key in ("name", "leadTitle", "summary"):
_required_string(item.get(key), f"{item_path}.{key}", errors)
if item.get("visual") not in LOCAL_VISUALS:
errors.append(f"{item_path}.visual must be one of {sorted(LOCAL_VISUALS)}")
_strings(item.get("links"), f"{item_path}.links", errors, minimum=1, maximum=8)
services = _mapping(data.get("services"), "services", errors)
_required_string(services.get("matrixTitle"), "services.matrixTitle", errors)
_required_string(services.get("matrixSubtitle"), "services.matrixSubtitle", errors)
matrix_items = _array(
services.get("matrixItems"),
"services.matrixItems",
errors,
minimum=1,
maximum=4,
)
seen_services: set[str] = set()
for index, raw in enumerate(matrix_items):
item_path = f"services.matrixItems[{index}]"
item = _mapping(raw, item_path, errors)
_unique_id(item, item_path, seen_services, errors)
for key in ("title", "caption"):
_required_string(item.get(key), f"{item_path}.{key}", errors)
if item.get("icon") not in SERVICE_ICONS:
errors.append(f"{item_path}.icon must be one of {sorted(SERVICE_ICONS)}")
live_modal = _mapping(services.get("liveModal"), "services.liveModal", errors)
for key in ("title", "streamTitle", "streamSubtitle", "currentProgram"):
_required_string(live_modal.get(key), f"services.liveModal.{key}", errors)
newsletter = _mapping(services.get("newsletter"), "services.newsletter", errors)
for key in ("title", "text", "placeholder", "button", "successPrefix"):
_required_string(newsletter.get(key), f"services.newsletter.{key}", errors)
footer = _mapping(data.get("footer"), "footer", errors)
footer_links = _links(
footer.get("links"), "footer.links", errors, minimum=1, maximum=10
)
_required_string(footer.get("copyright"), "footer.copyright", errors)
_required_string(footer.get("legal"), "footer.legal", errors)
_validate_remote_media_tree(data, "$", errors)
_validate_no_remote_or_markup(data, "$", errors)
if errors:
raise DataValidationError("\n".join(f"- {error}" for error in errors))
return {
"network_links": len(network_left) + len(network_right),
"primary_navigation": len(primary),
"drawer_navigation": len(drawer),
"series": len(series_items),
"spotlight": len(spotlight_items),
"headline_links": len(headline_links),
"focus_tabs": len(tabs),
"focus_columns": focus_columns,
"feature_tags": len(tags),
"feature_articles": len(articles),
"topics": len(topics),
"studios": len(studios),
"editorial_columns": len(editorial),
"live_columns": live_count,
"industries": len(industries),
"provinces": len(provinces),
"matrix_items": len(matrix_items),
"footer_links": len(footer_links),
}
def render_document(data: dict[str, Any], template: str, runtime: str) -> str:
validate_document(data)
data_text = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
data_text = data_text.replace("</script", "<\\/script")
if template.count("__XINHUA_PAGE_DATA__") != 1:
raise DataValidationError("template must contain one __XINHUA_PAGE_DATA__ marker")
if template.count("__XINHUA_PAGE_RUNTIME__") != 1:
raise DataValidationError(
"template must contain one __XINHUA_PAGE_RUNTIME__ marker"
)
rendered = template.replace("__XINHUA_PAGE_DATA__", data_text).replace(
"__XINHUA_PAGE_RUNTIME__", runtime
)
if "__XINHUA_PAGE_" in rendered:
raise DataValidationError("unresolved template marker remains in rendered HTML")
return rendered
def _write_new(path: Path, content: str) -> None:
if path.exists():
raise DataValidationError(
f"refusing to overwrite existing file: {path}; choose a new path"
)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8", newline="\n")
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)
counts = validate_document(data)
_write_new(output, json.dumps(data, ensure_ascii=False, indent=2) + "\n")
return {
"status": "ok",
"action": "init",
"output": str(output),
"modules": list(MODULES),
"counts": counts,
}
def _command_validate(input_path: Path) -> dict[str, Any]:
counts = validate_document(_read_json(input_path))
return {
"status": "ok",
"action": "validate",
"input": str(input_path),
"modules": list(MODULES),
"counts": counts,
}
def _command_render(input_path: Path, output: Path) -> dict[str, Any]:
data = _read_json(input_path)
counts = validate_document(data)
template = TEMPLATE_PATH.read_text(encoding="utf-8")
runtime = RUNTIME_PATH.read_text(encoding="utf-8")
_write_new(output, render_document(data, template, runtime))
return {
"status": "ok",
"action": "render",
"input": str(input_path),
"output": str(output),
"modules": list(MODULES),
"counts": counts,
}
def _build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Initialize, validate, and render Xinhua-style news portal JSON."
)
subparsers = parser.add_subparsers(dest="command", required=True)
init_parser = subparsers.add_parser("init", help="write a fresh default JSON file")
init_parser.add_argument("--output", required=True, type=Path)
validate_parser = subparsers.add_parser("validate", help="validate a JSON file")
validate_parser.add_argument("--input", required=True, type=Path)
render_parser = subparsers.add_parser(
"render", help="render a validated JSON file into the fixed HTML template"
)
render_parser.add_argument("--input", required=True, type=Path)
render_parser.add_argument("--output", required=True, type=Path)
return parser
def main(argv: list[str] | None = None) -> int:
parser = _build_parser()
args = parser.parse_args(argv)
try:
if args.command == "init":
payload = _command_init(args.output)
elif args.command == "validate":
payload = _command_validate(args.input)
else:
payload = _command_render(args.input, args.output)
_emit(payload)
return 0
except (DataValidationError, OSError) as exc:
_emit({"status": "error", "action": args.command, "message": str(exc)})
return 1
if __name__ == "__main__":
sys.exit(main())