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,85 @@
---
name: manila-times-page-generator
description: 生成或绘制中文马尼拉时报、The Manila Times 风格菲律宾大报门户的可交付单文件 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,图不合适时由用户在成品页面悬浮上传替换。
## 触发边界
- 用户明确说“生成/画/制作马尼拉时报”“The Manila Times 风格网页/菲律宾大报门户”或点名 `manila-times-page-generator` 时使用。
- 仅讨论菲律宾新闻、总结马尼拉时报消息或普通文本中出现 The Manila Times 时不要使用。
- 这是马尼拉时报风格单页门户,不改用 CNN、BBC、新华社或通用新闻模板。
## 极速工作流(默认)
页面结构已经固定。完成必要检索或材料整理后,模型只写一份小型规格 JSON;未写字段继续使用模板默认数据与示例视觉,脚本在一次进程内合并、校验并渲染。
1. 用 `write_file` 创建 `/mnt/user-data/outputs/manila-times-page-spec.json`。直接写模块对象会递归合并;修改现有数组项优先用 `$set`:
```json
{"site":{"pageTitle":"马尼拉时报 · 中文专题"},"$set":{"ticker.text":"中文快讯","lead.main.title":"中文头条","lead.main.summary":"中文摘要"}}
```
2. 只执行一次 `python /mnt/skills/public/manila-times-page-generator/scripts/fast_page.py --spec /mnt/user-data/outputs/manila-times-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. 用户要求当前新闻、实时市场、真实作者或近期事件时,必须先检索可靠来源再填 JSON;用户明确说不要检索时不得联网。检索到英文或菲律宾语资料时先准确翻译成简体中文再写入 JSON,不得直接复制外文标题、摘要、按钮或日期。没有材料时使用中文中性演示内容,并在页脚明确说明不是官方网站。
3. 初始化完整 JSON:
```text
python /mnt/skills/public/manila-times-page-generator/scripts/render_manila_times_page.py init --output /mnt/user-data/outputs/manila-times-page-data.json
```
4. 只修改 JSON。十个顶层模块必须全部保留:`site`、`navigation`、`ticker`、`lead`、`pulse`、`regions`、`opinion`、`sections`、`media`、`footer`。JSON 键名、`id`、`href`、`visual`、`direction`、`theme` 等技术值继续使用契约规定的英文标识;除此之外,所有面向读者的报头、栏目、标题、摘要、作者、按钮、日期、地区、活动和页脚文案必须使用简体中文,`site.language` 固定为 `zh-CN`。字段不确定时读取 [references/data-schema.md](references/data-schema.md)。
5. 校验 JSON:
```text
python /mnt/skills/public/manila-times-page-generator/scripts/render_manila_times_page.py validate --input /mnt/user-data/outputs/manila-times-page-data.json
```
6. 确定性渲染到 `outputs/`:
```text
python /mnt/skills/public/manila-times-page-generator/scripts/render_manila_times_page.py render --input /mnt/user-data/outputs/manila-times-page-data.json --output /mnt/user-data/outputs/manila-times-page.html
```
7. 检查 stdout 的 `status` 为 `ok`、HTML 存在且占位符已消失,再用 `present_files` 同时交付 HTML 与源 JSON。不要在聊天中粘贴完整 HTML。
## 内容映射
- 报头、日期、版次、天气和主题放入 `site`;工具链接、主分类、抽屉与搜索文案放入 `navigation`。
- 快讯放入 `ticker`;主头条、两篇侧栏和最新/热门列表放入 `lead`。
- 市场与经济指标放入 `pulse.items`;吕宋、维萨亚、棉兰老和马尼拉报道放入 `regions.tabs`。
- 评论作者与观点放入 `opinion.columns`;商业、体育和市场看板放入 `sections`。
- 视频、字幕、数字报翻页和订阅表单放入 `media`;说明、栏目链接和法律文案放入 `footer`。
- `visual` 继续作为内置后备;具有视觉的对象可增加受校验的 `media`(`image`、`video`、`webpage`)替换当前视觉。所有外部文本由模板转义,不得包含 HTML、脚本或直接 iframe。
## 重要约束
- 只编辑 JSON,不修改 `assets/manila-times-template.html` 或 `assets/manila-times-runtime.js`,不复制模板后手改 DOM。
- 不得生成英文或菲律宾语读者文案。外文来源必须翻译为自然、准确的简体中文;只有 JSON 键名、稳定 `id`、锚点、视觉枚举、涨跌枚举和主题枚举保留英文技术值。
- 初始化与渲染默认拒绝覆盖已有文件;路径存在时换新文件名,不删除旧产物。
- 页面结构、样式和脚本完全自包含,不依赖新闻 API、CDN 或 npm;仅当 JSON 明确提供受校验的媒体 URL 时加载图片、视频或网页。
- 保留菲律宾旗色带、深蓝工具栏、衬线报头、三栏头条、地区切换、评论、商业体育、视频弹窗、数字报翻页和订阅反馈。
- 浏览器缓存以初始 JSON 指纹隔离;沙箱禁止持久存储时必须继续使用内嵌 JSON 正常渲染。
@@ -0,0 +1,261 @@
{
"site": {
"brandPrefix": "马尼拉",
"brandAccent": "时报",
"kicker": "菲律宾独立新闻",
"tagline": "记录群岛每一天",
"dateLabel": "2026年10月30日 星期五",
"editionLabel": "马尼拉都会版",
"pageTitle": "马尼拉时报——菲律宾新闻门户",
"description": "以菲律宾英文大报视觉为基础制作的中文新闻门户概念页面。",
"language": "zh-CN",
"skipLabel": "跳转到头条新闻",
"theme": "light",
"weather": [
{"id": "manila", "city": "马尼拉", "temp": "31°", "condition": "局部多云"},
{"id": "cebu", "city": "宿务", "temp": "29°", "condition": "小雨"},
{"id": "davao", "city": "达沃", "temp": "30°", "condition": "微风温暖"}
]
},
"navigation": {
"menuLabel": "全部栏目",
"searchLabel": "搜索",
"themeLightLabel": "日间模式",
"themeDarkLabel": "夜间模式",
"utilityLeft": [
{"label": "数字报", "href": "#edition"},
{"label": "新闻简报", "href": "#newsletter"}
],
"utilityRight": [
{"label": "关于我们", "href": "#footer"},
{"label": "订阅", "href": "#newsletter"}
],
"primary": [
{"label": "头条", "href": "#top-stories"},
{"label": "全国", "href": "#regions"},
{"label": "商业", "href": "#business"},
{"label": "评论", "href": "#opinion"},
{"label": "体育", "href": "#sports"},
{"label": "视频", "href": "#watch"}
],
"drawer": {
"eyebrow": "晨间新闻简报",
"title": "读懂菲律宾群岛每一天",
"text": "从全国事务和地方新闻,到商业、体育与文化,一站浏览各新闻板块。",
"ctaLabel": "阅读头条",
"ctaHref": "#top-stories"
},
"search": {
"title": "搜索新闻",
"placeholder": "可搜索交通、经济、群岛等关键词",
"hint": "搜索本页面中的全部新闻内容。",
"emptyMessage": "暂未找到相关新闻。",
"resultPrefix": "条相关新闻"
}
},
"ticker": {
"label": "突发",
"text": "多地交通部门就节假日出行时刻表达成协调安排。",
"time": "上午8:42",
"href": "#top-stories"
},
"lead": {
"datelineLeft": "马尼拉 · 全国新闻部",
"datelineRight": "全天持续更新",
"main": {
"id": "lead-transit",
"kicker": "基础设施",
"title": "新交通网络有望缩短首都居民的日常通勤时间",
"summary": "一项轨道交通与公交协同计划进入新阶段,将通勤者、社区接驳和清晰的公共信息置于核心位置。",
"byline": "记者 玛拉·维拉纽瓦",
"time": "18分钟前",
"visual": "bay-transit"
},
"sideStories": [
{
"id": "port-upgrade",
"kicker": "贸易",
"title": "港口为小型出口商开通数字化通道",
"summary": "试点计划将海关、物流企业与地方生产商连接起来。",
"byline": "商业新闻部",
"time": "42分钟前",
"visual": "port"
},
{
"id": "city-schools",
"kicker": "教育",
"title": "城市学校将闲置庭院改造成清凉学习空间",
"summary": "教师与规划人员在夏季到来前测试带遮阳设施的户外课堂。",
"byline": "都会新闻部",
"time": "1小时前",
"visual": "city"
}
],
"feeds": [
{
"id": "latest",
"label": "最新",
"items": [
{"time": "09:14", "title": "渡轮航线增加清晨班次"},
{"time": "08:56", "title": "菲律宾央行维持现行政策不变"},
{"time": "08:31", "title": "社区诊所延长周末服务时间"},
{"time": "07:48", "title": "国家队启动青少年训练营"}
]
},
{
"id": "trending",
"label": "热榜",
"items": [
{"time": "1", "title": "海岛食品市场成为周末热门目的地"},
{"time": "2", "title": "读者共同绘制马尼拉林荫步行路线"},
{"time": "3", "title": "青年创业者重塑社区配送服务"},
{"time": "4", "title": "排球决赛创下本地收视新高"}
]
}
]
},
"pulse": {
"label": "经济脉搏",
"title": "市场与经济",
"items": [
{"id": "psei", "label": "菲律宾综合指数", "value": "7,112.48", "change": "+0.72%", "direction": "up"},
{"id": "peso", "label": "比索/美元", "value": "57.24", "change": "−0.08", "direction": "down"},
{"id": "fuel", "label": "燃料指数", "value": "98.6", "change": "持平", "direction": "flat"},
{"id": "rice", "label": "大米价格监测", "value": "₱51.20", "change": "−1.1%", "direction": "down"}
]
},
"regions": {
"eyebrow": "走遍菲律宾",
"title": "来自各大岛群的新闻",
"moreLabel": "浏览全国新闻",
"moreHref": "#regions",
"tabs": [
{
"id": "luzon",
"label": "吕宋岛",
"feature": {"kicker": "北吕宋", "title": "山区农场在雨季前协调农产品运输路线", "summary": "合作社共享仓储资源、天气信息和运输计划。", "visual": "luzon"},
"items": [
{"location": "碧瑶", "title": "夜市扩大零废弃试点范围", "summary": "商贩共同使用可循环周转箱和垃圾分类站。"},
{"location": "比科尔", "title": "沿海城镇恢复红树林自然课堂", "summary": "学生每周与海洋研究人员共同开展野外学习。"}
]
},
{
"id": "visayas",
"label": "维萨亚群岛",
"feature": {"kicker": "中维萨亚", "title": "跨岛渡轮枢纽试行一票式换乘服务", "summary": "试点将海上交通与地方公交班次连接起来。", "visual": "visayas"},
"items": [
{"location": "宿务", "title": "设计工作室让地方编织图案焕发新生", "summary": "新系列将传统工艺与现代设计相结合。"},
{"location": "伊洛伊洛", "title": "滨河步道最后一座公共花园开放", "summary": "本土树木和防洪步道共同构成新的公共公园。"}
]
},
{
"id": "mindanao",
"label": "棉兰老岛",
"feature": {"kicker": "南棉兰老", "title": "可可种植户共建质量检测实验室", "summary": "小型农场如今可以在当地完成发酵与风味检测。", "visual": "mindanao"},
"items": [
{"location": "达沃", "title": "食品集散中心增设农户直销摊位", "summary": "种植户可通过合作社服务台预约摊位。"},
{"location": "布基农", "title": "太阳能冷库减少蔬菜采后损耗", "summary": "偏远社区获得了更长的市场销售窗口。"}
]
},
{
"id": "metro",
"label": "马尼拉都会区",
"feature": {"kicker": "首都地区", "title": "社区委员会发布夜间安全出行路线", "summary": "新的照明设施和夜间公交站点按街区完成标注。", "visual": "metro"},
"items": [
{"location": "奎松市", "title": "图书馆延长晚间自习服务时间", "summary": "三家分馆增设安静阅读室和通勤者学习区。"},
{"location": "帕西格", "title": "无车星期日路线延伸至河滨地区", "summary": "扩展后的环线连接多个公园和社区市场。"}
]
}
]
},
"opinion": {
"eyebrow": "评论",
"title": "思考变化中的共和国",
"summary": "汇集新闻部内外的专栏、分析与观点。",
"columns": [
{"id": "public-trust", "initial": "林", "name": "安娜·雷耶斯", "title": "公众信任源于每一个细节", "summary": "当公众能够看见服务流程和时间安排时,每一项公共服务都会得到改善。"},
{"id": "island-economy", "initial": "陈", "name": "米格尔·桑托斯", "title": "群岛经济需要的不只是桥梁", "summary": "可靠的班次和共享的信息同样属于基础设施。"},
{"id": "young-cities", "initial": "苏", "name": "莉娅·克鲁兹", "title": "与年轻人共同设计城市", "summary": "最好的公共空间始于建设前的认真倾听。"}
]
},
"sections": {
"business": {
"eyebrow": "商业",
"title": "企业与市场",
"moreLabel": "更多商业新闻",
"moreHref": "#business",
"items": [
{"id": "retail-data", "kicker": "零售", "title": "独立商店共享社区消费需求数据", "summary": "合作式数据平台帮助小型商店更合理地安排库存。", "visual": "market"},
{"id": "green-factory", "kicker": "工业", "title": "工业园区联合采购清洁能源", "summary": "多家制造企业签署共同可再生能源供应协议。", "visual": "factory"},
{"id": "shipping-tech", "kicker": "物流", "title": "航运企业为微型出口商简化单证", "summary": "统一表格减少了不同承运商之间的重复填报。", "visual": "shipping"}
]
},
"sports": {
"eyebrow": "体育",
"title": "全民赛场",
"moreLabel": "更多体育新闻",
"moreHref": "#sports",
"hero": {"id": "basketball-final", "kicker": "篮球", "title": "年轻后卫在总决赛揭幕战中掌控比赛节奏", "summary": "积极防守和果断投篮让最后一节成为全场焦点。", "visual": "basketball"},
"items": [
{"id": "road-running", "kicker": "跑步", "title": "城市路跑增设林荫社区赛道", "visual": "running"},
{"id": "volleyball-camp", "kicker": "排球", "title": "国家训练营迎来规模最大的青少年学员", "visual": "volleyball"}
]
},
"market": {
"title": "市场行情",
"items": [
{"label": "金融", "value": "+1.18%", "direction": "up"},
{"label": "工业", "value": "+0.34%", "direction": "up"},
{"label": "房地产", "value": "−0.41%", "direction": "down"}
]
}
},
"media": {
"watch": {
"eyebrow": "视频",
"title": "今日影像",
"moreLabel": "全部视频",
"moreHref": "#watch",
"videos": [
{"id": "morning-brief", "duration": "04:18", "kicker": "新闻部", "title": "晨间简报:今天值得关注的五条新闻", "summary": "编辑解读影响今天的重要新闻。", "visual": "studio"},
{"id": "island-route", "duration": "02:46", "kicker": "新闻解读", "title": "跨岛交通线路如何协同运行", "summary": "通过图解了解班次、港口和接驳方式。", "visual": "islands"},
{"id": "night-market", "duration": "03:22", "kicker": "文化", "title": "夜幕下的马尼拉社区市场", "summary": "城市灯光下的美食、音乐和小型商业。", "visual": "city-night"}
],
"modal": {"title": "马尼拉时报视频", "streamSubtitle": "演示视频", "captionsOn": "字幕:已开启", "captionsOff": "字幕:已关闭"}
},
"edition": {
"eyebrow": "数字报",
"title": "按报纸原版版式阅读",
"summary": "在当前文件中翻阅一份由四个版面组成的演示数字报。",
"openLabel": "打开今日数字报",
"subscribeLabel": "立即订阅",
"subscribeHref": "#newsletter",
"modalTitle": "今日数字报",
"date": "2026年10月30日",
"pages": [
{"id": "front", "label": "头版", "headline": "更顺畅的首都交通始于高效连接", "text": "交通部门、地方政府和社区服务机构共同制定新的公共出行时刻表。"},
{"id": "nation", "label": "全国", "headline": "各岛群共同建设气候信息记录平台", "text": "地方研究人员为农场、港口和学校发布实用观测信息。"},
{"id": "business", "label": "商业", "headline": "小型出口商获得更便捷的市场通道", "text": "数字单证和共享物流服务减少了重复流程。"},
{"id": "sports", "label": "体育", "headline": "青年队伍为总决赛注入全新活力", "text": "新一代运动员在篮球和排球赛场成为焦点。"}
]
},
"newsletter": {
"eyebrow": "晨间简报",
"title": "从充分了解开始新一天",
"text": "用一份精简简报掌握全国、地方与商业新闻。",
"placeholder": "请输入电子邮箱",
"button": "订阅晨间简报",
"successPrefix": "已为以下邮箱预留简报订阅"
}
},
"footer": {
"description": "用于展示马尼拉大报风格新闻门户的中文编辑概念页面。本页面并非马尼拉时报官方网站。",
"columns": [
{"id": "news", "title": "新闻", "links": [{"label": "头条", "href": "#top-stories"}, {"label": "地区新闻", "href": "#regions"}, {"label": "商业", "href": "#business"}]},
{"id": "voices", "title": "观点与文体", "links": [{"label": "评论", "href": "#opinion"}, {"label": "体育", "href": "#sports"}, {"label": "视频", "href": "#watch"}]},
{"id": "reader", "title": "读者服务", "links": [{"label": "数字报", "href": "#edition"}, {"label": "新闻简报", "href": "#newsletter"}, {"label": "关于本演示页", "href": "#footer"}]}
],
"copyright": "© 2026 海港新闻概念页面",
"legal": "仅供演示 · 与马尼拉时报无隶属或合作关系"
}
}
@@ -0,0 +1,519 @@
(() => {
"use strict";
const MODULES = ["site", "navigation", "ticker", "lead", "pulse", "regions", "opinion", "sections", "media", "footer"];
const MODULE_META = {
site: "站点信息",
navigation: "页面导航",
ticker: "突发快讯",
lead: "头条新闻",
pulse: "经济脉搏",
regions: "地区新闻",
opinion: "评论观点",
sections: "商业体育",
media: "视频与数字报",
footer: "页面页脚"
};
const node = (id) => document.getElementById(id);
const initialText = node("manilaTimesPageData").textContent;
const initialData = JSON.parse(initialText);
const clone = (value) => JSON.parse(JSON.stringify(value));
const fingerprint = (() => {
let hash = 2166136261;
for (let index = 0; index < initialText.length; index += 1) {
hash ^= initialText.charCodeAt(index);
hash = Math.imul(hash, 16777619);
}
return (hash >>> 0).toString(36);
})();
const dataKey = "manila-times-page-data-v1:" + fingerprint;
const themeKey = "manila-times-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); return true; } catch (_error) { return false; }
};
const saved = readStorage(dataKey);
let data = initialData;
if (saved) {
try { data = JSON.parse(saved); } catch (_error) { data = initialData; }
}
let currentModule = MODULES[0];
let activeFeed = "latest";
let activeRegion = data.regions.tabs[0]?.id || "";
let weatherIndex = 0;
let editionIndex = 0;
let captionsOn = true;
const savedStories = new Set();
const esc = (value) => String(value ?? "").replace(/[&<>'"]/g, (character) => ({"&":"&amp;","<":"&lt;",">":"&gt;","'":"&#39;",'"':"&quot;"})[character]);
const safeHref = (value) => typeof value === "string" && value.startsWith("#") ? value : "#";
const safeRemoteUrl = (value, kind = "link") => {
const source = String(value || "").trim(); if (!source) return ""; const lowered = source.toLowerCase();
if (kind === "image" && lowered.startsWith("data:image/")) return source; if (kind === "video" && lowered.startsWith("data:video/")) return source;
try { const url = new URL(source); return ["http:","https:"].includes(url.protocol) ? url.href : ""; } catch (_error) { return ""; }
};
const linkMarkup = (item) => `<a href="${esc(safeHref(item.href))}">${esc(item.label)}</a>`;
const setText = (id, value) => { const element = node(id); if (element) element.textContent = value ?? ""; };
const setLink = (id, item) => { const element = node(id); if (!element) return; element.textContent = item.label ?? ""; element.href = safeHref(item.href); };
const allText = (value, output = []) => {
if (Array.isArray(value)) value.forEach((item) => allText(item, output));
else if (value && typeof value === "object") Object.values(value).forEach((item) => allText(item, output));
else if (typeof value === "string") output.push(value);
return output;
};
document.head.insertAdjacentHTML("beforeend", '<style data-external-media>[data-visual]>img,[data-visual]>video,[data-visual]>iframe{position:absolute;inset:0;z-index:1;width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}[data-visual]>iframe{object-fit:initial}[data-visual].has-external-media::before,[data-visual].has-external-media::after{display:none!important}[data-visual].has-external-media>.duration{z-index:3}.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 externalMedia = (media, label) => {
if (!media || typeof media !== "object") return "";
if (media.type === "image") { const source=safeRemoteUrl(media.mediaUrl,"image"),page=safeRemoteUrl(media.pageUrl); return source ? `<img src="${esc(source)}" alt="${esc(media.alt||label||"新闻图片")}" loading="lazy" referrerpolicy="no-referrer">${page?`<a class="external-open" href="${esc(page)}" target="_blank" rel="noopener noreferrer">打开来源</a>`:""}` : ""; }
if (media.type === "video") { const source=safeRemoteUrl(media.mediaUrl,"video"),poster=safeRemoteUrl(media.posterUrl,"image"); return source ? `<video src="${esc(source)}"${poster?` poster="${esc(poster)}"`:""} controls playsinline preload="metadata" aria-label="${esc(media.alt||label||"新闻视频")}"></video>` : ""; }
if (media.type === "webpage") { const page=safeRemoteUrl(media.pageUrl),preview=safeRemoteUrl(media.mediaUrl,"image"); if(!page)return ""; const body=media.embed===true?`<iframe src="${esc(page)}" title="${esc(media.title||"网页预览")}" loading="lazy" referrerpolicy="no-referrer" sandbox="allow-forms allow-popups allow-scripts"></iframe>`:(preview?`<img src="${esc(preview)}" alt="${esc(media.alt||media.title||"网页预览图")}" loading="lazy" referrerpolicy="no-referrer">`:""); return `${body}<a class="external-copy" href="${esc(page)}" target="_blank" rel="noopener noreferrer"><strong>${esc(media.title||label||"打开网页")}</strong><span>${esc(media.description||"新窗口打开")}</span></a>`; }
return "";
};
const visual = (kind, className = "story-visual", media = null, extra = "", mediaPath = "") => {
const mediaMarkup = externalMedia(media, media?.title);
const classes = `${className}${mediaMarkup ? " has-external-media" : ""}`;
const pathAttribute = mediaPath ? ` data-media-path="${esc(mediaPath)}"` : "";
return `<div class="${classes}" data-visual="${esc(kind)}"${pathAttribute} aria-hidden="true">${mediaMarkup}${extra}</div>`;
};
function renderChrome() {
document.documentElement.lang = data.site.language;
document.title = data.site.pageTitle;
document.querySelector('meta[name="description"]')?.setAttribute("content", data.site.description);
setText("skipLink", data.site.skipLabel);
setText("brandKicker", data.site.kicker); setText("brandPrefix", data.site.brandPrefix); setText("brandAccent", data.site.brandAccent); setText("brandTagline", data.site.tagline);
setText("dateLabel", data.site.dateLabel); setText("editionLabel", data.site.editionLabel); setText("menuLabel", data.navigation.menuLabel); setText("searchLabel", data.navigation.searchLabel);
node("utilityLeft").innerHTML = data.navigation.utilityLeft.map(linkMarkup).join("");
node("utilityRight").innerHTML = data.navigation.utilityRight.map(linkMarkup).join("") + `<button class="nav-action" id="themeToggle" type="button"></button>`;
node("primaryLinks").innerHTML = data.navigation.primary.map(linkMarkup).join("");
setText("tickerLabel", data.ticker.label); setLink("tickerText", {label:data.ticker.text,href:data.ticker.href}); setText("tickerTime", data.ticker.time);
const storedTheme = readStorage(themeKey);
const initialTheme = storedTheme || (data.site.theme === "auto" ? (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light") : data.site.theme);
applyTheme(initialTheme);
node("themeToggle").addEventListener("click", () => applyTheme(document.body.classList.contains("night") ? "light" : "dark", true));
setText("drawerBrand", `${data.site.brandPrefix} ${data.site.brandAccent}`); setText("searchBrand", `${data.site.brandPrefix} ${data.site.brandAccent}`);
setText("drawerEyebrow", data.navigation.drawer.eyebrow); setText("drawerTitle", data.navigation.drawer.title); setText("drawerText", data.navigation.drawer.text); setLink("drawerCta", {label:data.navigation.drawer.ctaLabel,href:data.navigation.drawer.ctaHref});
node("drawerLinks").innerHTML = data.navigation.primary.map(linkMarkup).join("");
setText("searchTitle", data.navigation.search.title); node("searchInput").placeholder = data.navigation.search.placeholder;
setText("footerBrand", `${data.site.brandPrefix} ${data.site.brandAccent}`);
renderWeather();
}
function applyTheme(theme, persist = false) {
const dark = theme === "dark";
document.body.classList.toggle("night", dark);
const button = node("themeToggle");
if (button) button.textContent = dark ? `☀ ${data.navigation.themeLightLabel}` : `◐ ${data.navigation.themeDarkLabel}`;
if (persist) writeStorage(themeKey, dark ? "dark" : "light");
}
function renderWeather() {
const items = data.site.weather;
if (!items.length) return;
weatherIndex %= items.length;
const weather = items[weatherIndex];
setText("weatherCity", weather.city); setText("weatherTemp", weather.temp); setText("weatherNote", weather.condition);
}
function saveButton(id) {
const saved = savedStories.has(id);
return `<button class="save-btn${saved ? " saved" : ""}" data-save="${esc(id)}" aria-label="${saved ? "取消收藏" : "收藏新闻"}">${saved ? "✓" : "+"}</button>`;
}
function renderLead() {
setText("datelineLeft", data.lead.datelineLeft); setText("datelineRight", data.lead.datelineRight);
const story = data.lead.main;
node("leadMain").innerHTML = `${saveButton(story.id)}<div class="kicker">${esc(story.kicker)}</div><h1 class="lead-title">${esc(story.title)}</h1><p class="summary">${esc(story.summary)}</p><div class="byline">${esc(story.byline)} · ${esc(story.time)}</div>${visual(story.visual,"story-visual",story.media,"","lead.main")}`;
node("sideStories").innerHTML = data.lead.sideStories.map((item, index) => `<article class="side-story">${saveButton(item.id)}${visual(item.visual,"story-visual",item.media,"",`lead.sideStories.${index}`)}<div class="kicker">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3><p class="summary">${esc(item.summary)}</p><div class="byline">${esc(item.byline)} · ${esc(item.time)}</div></article>`).join("");
if (!data.lead.feeds.some((feed) => feed.id === activeFeed)) activeFeed = data.lead.feeds[0]?.id;
node("feedTabs").innerHTML = data.lead.feeds.map((feed) => `<button class="feed-tab${feed.id === activeFeed ? " active" : ""}" data-feed="${esc(feed.id)}">${esc(feed.label)}</button>`).join("");
const feed = data.lead.feeds.find((item) => item.id === activeFeed) || data.lead.feeds[0];
node("feedItems").innerHTML = feed.items.map((item) => `<li class="feed-item"><span class="feed-time">${esc(item.time)}</span><span>${esc(item.title)}</span></li>`).join("");
}
function renderPulse() {
setText("pulseLabel", data.pulse.label); setText("pulseTitle", data.pulse.title);
node("pulseItems").innerHTML = data.pulse.items.map((item) => `<div class="pulse-item"><div class="pulse-label">${esc(item.label)}</div><div class="pulse-value">${esc(item.value)}</div><div class="direction-${esc(item.direction)}">${esc(item.change)}</div></div>`).join("");
}
function renderRegions() {
setText("regionsEyebrow", data.regions.eyebrow); setText("regionsTitle", data.regions.title); setLink("regionsMore", {label:data.regions.moreLabel,href:data.regions.moreHref});
if (!data.regions.tabs.some((tab) => tab.id === activeRegion)) activeRegion = data.regions.tabs[0]?.id;
node("regionTabs").innerHTML = data.regions.tabs.map((tab) => `<button class="region-tab${tab.id === activeRegion ? " active" : ""}" data-region="${esc(tab.id)}">${esc(tab.label)}</button>`).join("");
const tab = data.regions.tabs.find((item) => item.id === activeRegion) || data.regions.tabs[0];
const feature = tab.feature;
const tabIndex = data.regions.tabs.indexOf(tab);
node("regionContent").innerHTML = `<article class="region-feature"><div class="region-copy"><div class="kicker">${esc(feature.kicker)}</div><h3>${esc(feature.title)}</h3><p class="summary">${esc(feature.summary)}</p></div>${visual(feature.visual,"region-visual",feature.media,"",`regions.tabs.${tabIndex}.feature`)}</article><div class="region-list">${tab.items.map((item) => `<article class="region-story"><div class="region-location">${esc(item.location)}</div><h3>${esc(item.title)}</h3><p>${esc(item.summary)}</p></article>`).join("")}</div>`;
}
function renderOpinion() {
setText("opinionEyebrow", data.opinion.eyebrow); setText("opinionTitle", data.opinion.title); setText("opinionSummary", data.opinion.summary);
node("opinionGrid").innerHTML = data.opinion.columns.map((item) => `<article class="opinion-card"><div class="author"><span class="author-initial">${esc(item.initial)}</span><span>${esc(item.name)}</span></div><h3>${esc(item.title)}</h3><p>${esc(item.summary)}</p></article>`).join("");
}
function renderSections() {
const business = data.sections.business;
setText("businessEyebrow", business.eyebrow); setText("businessTitle", business.title); setLink("businessMore", {label:business.moreLabel,href:business.moreHref});
node("businessItems").innerHTML = business.items.map((item, index) => `<article class="story-card">${visual(item.visual,"mini-visual",item.media,"",`sections.business.items.${index}`)}<div><div class="kicker">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3><p class="summary">${esc(item.summary)}</p></div></article>`).join("");
const sports = data.sections.sports;
setText("sportsEyebrow", sports.eyebrow); setText("sportsTitle", sports.title); setLink("sportsMore", {label:sports.moreLabel,href:sports.moreHref});
node("sportsHero").innerHTML = `<div class="kicker">${esc(sports.hero.kicker)}</div><h3>${esc(sports.hero.title)}</h3><p>${esc(sports.hero.summary)}</p>`;
node("sportsItems").innerHTML = sports.items.map((item, index) => `<article class="story-card">${visual(item.visual,"mini-visual",item.media,"",`sections.sports.items.${index}`)}<div><div class="kicker">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3></div></article>`).join("");
node("marketBoard").innerHTML = `<h3>${esc(data.sections.market.title)}</h3><div class="market-board">${data.sections.market.items.map((item) => `<div class="market-cell"><span>${esc(item.label)}</span><strong class="direction-${esc(item.direction)}">${esc(item.value)}</strong></div>`).join("")}</div>`;
}
function renderMedia() {
const watch = data.media.watch;
setText("watchEyebrow", watch.eyebrow); setText("watchTitle", watch.title); setLink("watchMore", {label:watch.moreLabel,href:watch.moreHref});
node("videoGrid").innerHTML = watch.videos.map((item, index) => `<button class="video-card" data-video="${esc(item.id)}">${visual(item.visual,"video-visual",item.media,`<span class="duration">${esc(item.duration)}</span>`,`media.watch.videos.${index}`)}<div class="video-copy"><div class="kicker">${esc(item.kicker)}</div><h3>${esc(item.title)}</h3><p>${esc(item.summary)}</p></div></button>`).join("");
setText("videoModalTitle", watch.modal.title); setText("videoSubtitle", watch.modal.streamSubtitle);
const edition = data.media.edition;
setText("editionEyebrow", edition.eyebrow); setText("editionTitle", edition.title); setText("editionSummary", edition.summary); setText("openEdition", edition.openLabel); setLink("editionSubscribe", {label:edition.subscribeLabel,href:edition.subscribeHref}); setText("editionModalTitle", edition.modalTitle);
const newsletter = data.media.newsletter;
setText("newsletterEyebrow", newsletter.eyebrow); setText("newsletterTitle", newsletter.title); setText("newsletterText", newsletter.text); node("newsletterEmail").placeholder = newsletter.placeholder; setText("newsletterButton", newsletter.button);
}
function renderFooter() {
setText("footerDescription", data.footer.description); setText("footerCopyright", data.footer.copyright); setText("footerLegal", data.footer.legal);
node("footerColumns").innerHTML = data.footer.columns.map((column) => `<div><h3>${esc(column.title)}</h3>${column.links.map(linkMarkup).join("")}</div>`).join("");
}
function renderAll() {
renderChrome(); renderLead(); renderPulse(); renderRegions(); renderOpinion(); renderSections(); renderMedia(); renderFooter(); bindDynamicControls();
}
function bindDynamicControls() {
document.querySelectorAll("[data-save]").forEach((button) => button.addEventListener("click", () => { const id = button.dataset.save; savedStories.has(id) ? savedStories.delete(id) : savedStories.add(id); renderLead(); bindDynamicControls(); }));
document.querySelectorAll("[data-feed]").forEach((button) => button.addEventListener("click", () => { activeFeed = button.dataset.feed; renderLead(); bindDynamicControls(); }));
document.querySelectorAll("[data-region]").forEach((button) => button.addEventListener("click", () => { activeRegion = button.dataset.region; renderRegions(); bindDynamicControls(); }));
document.querySelectorAll("[data-video]").forEach((button) => button.addEventListener("click", () => openVideo(button.dataset.video)));
}
function openOverlay(id) {
const overlay = node(id); overlay.classList.add("open"); overlay.setAttribute("aria-hidden", "false"); document.body.style.overflow = "hidden";
}
function closeOverlay(id) {
const overlay = node(id); overlay.classList.remove("open"); overlay.setAttribute("aria-hidden", "true");
if (!document.querySelector(".screen-overlay.open,.modal-overlay.open,.settings-overlay.open")) document.body.style.overflow = "";
}
function openVideo(id) {
const item = data.media.watch.videos.find((video) => video.id === id); if (!item) return;
captionsOn = true; setText("videoPlayingTitle", item.title); setText("videoCaption", item.summary); updateCaption(); openOverlay("videoOverlay");
}
function updateCaption() {
setText("captionToggle", captionsOn ? data.media.watch.modal.captionsOn : data.media.watch.modal.captionsOff);
node("videoCaption").hidden = !captionsOn;
}
function renderEditionPage() {
const pages = data.media.edition.pages; editionIndex = Math.max(0, Math.min(editionIndex, pages.length - 1)); const page = pages[editionIndex];
node("editionPage").innerHTML = `<div class="paper-brand">${esc(data.site.brandPrefix)} ${esc(data.site.brandAccent)}</div><div class="kicker">${esc(page.label)} · ${esc(data.media.edition.date)}</div><h2>${esc(page.headline)}</h2><p>${esc(page.text)}</p>`;
setText("editionPageCount", `${editionIndex + 1} / ${pages.length}`); node("editionPrev").disabled = editionIndex === 0; node("editionNext").disabled = editionIndex === pages.length - 1;
}
function searchStories() {
const query = node("searchInput").value.trim().toLowerCase();
const candidates = [];
const collect = (value) => {
if (Array.isArray(value)) value.forEach(collect);
else if (value && typeof value === "object") { if (typeof value.title === "string") candidates.push({title:value.title,kicker:value.kicker || value.location || "Story"}); Object.values(value).forEach(collect); }
};
collect({lead:data.lead,regions:data.regions,opinion:data.opinion,sections:data.sections,media:data.media.watch});
const unique = Array.from(new Map(candidates.map((item) => [item.title,item])).values());
const results = query ? unique.filter((item) => `${item.title} ${item.kicker}`.toLowerCase().includes(query)) : unique.slice(0,8);
setText("searchMeta", results.length ? `${results.length} ${data.navigation.search.resultPrefix}` : data.navigation.search.emptyMessage);
node("searchResults").innerHTML = results.map((item) => `<button class="search-result"><span class="kicker">${esc(item.kicker)}</span><br>${esc(item.title)}</button>`).join("");
}
function validateClientDocument(candidate) {
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) throw new Error("顶层 JSON 必须是对象。");
const keys = Object.keys(candidate); const missing = MODULES.filter((name) => !keys.includes(name)); const extra = keys.filter((name) => !MODULES.includes(name));
if (missing.length) throw new Error(`缺少模块:${missing.join("、")}`); if (extra.length) throw new Error(`存在未知模块:${extra.join("、")}`);
MODULES.forEach((name) => { if (!candidate[name] || typeof candidate[name] !== "object" || Array.isArray(candidate[name])) throw new Error(`${name} 必须是对象。`); });
const text = JSON.stringify(candidate).toLowerCase(); if (["<script","<iframe","javascript:"].some((token) => text.includes(token))) throw new Error("不允许使用 HTML 或脚本。");
const validateMedia=(value,path="当前模块")=>{if(Array.isArray(value))return value.forEach((item,index)=>validateMedia(item,`${path}[${index}]`));if(!value||typeof value!=="object")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")validateMedia(item,`${path}.${key}`)})};validateMedia(candidate);
if (candidate.site.language !== "zh-CN") throw new Error("site.language 必须是 zh-CN。");
const technicalKeys = new Set(["id","href","visual","direction","theme","language","type","mediaUrl","posterUrl","pageUrl"]);
const checkChinese = (value, key = "") => {
if (Array.isArray(value)) value.forEach((item) => checkChinese(item, key));
else if (value && typeof value === "object") Object.entries(value).forEach(([childKey,item]) => checkChinese(item, childKey));
else if (typeof value === "string" && !technicalKeys.has(key) && !key.toLowerCase().endsWith("id") && !key.toLowerCase().endsWith("href") && !key.toLowerCase().endsWith("url")) {
if (/[A-Za-z]/.test(value) && !/[\u3400-\u9fff]/.test(value)) throw new Error("所有读者可见文案必须使用简体中文。");
}
};
checkChinese(candidate);
if (!Array.isArray(candidate.regions.tabs) || !candidate.regions.tabs.length) throw new Error("regions.tabs 不能为空。");
if (!Array.isArray(candidate.media.edition.pages) || !candidate.media.edition.pages.length) throw new Error("media.edition.pages 不能为空。");
return true;
}
function showModule(name) {
currentModule = name; node("jsonEditor").value = JSON.stringify(data[name], null, 2); setText("editorModule", MODULE_META[name]); setText("jsonValidity", "JSON 有效");
node("moduleTabs").querySelectorAll("button").forEach((button) => button.classList.toggle("active", button.dataset.module === name));
}
function renderSettingsTabs() {
node("moduleTabs").innerHTML = MODULES.map((name) => `<button class="module-tab" data-module="${name}">${MODULE_META[name]}</button>`).join("");
node("moduleTabs").querySelectorAll("button").forEach((button) => button.addEventListener("click", () => showModule(button.dataset.module))); showModule(currentModule);
}
function parseEditor() {
try { const value = JSON.parse(node("jsonEditor").value); if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("当前模块必须是对象。"); setText("jsonValidity", "JSON 有效"); return value; }
catch (error) { setText("jsonValidity", "JSON 无效"); throw error; }
}
function setStatus(message) { setText("settingsStatus", message); }
async function copyJson() {
const text = JSON.stringify({...data,[currentModule]:parseEditor()}, null, 2);
try { await navigator.clipboard.writeText(text); setStatus("完整 JSON 已复制。"); }
catch (_error) { node("jsonEditor").select(); document.execCommand("copy"); setStatus("已选中当前模块,可手动复制。"); }
}
function downloadJson() {
const candidate = {...data,[currentModule]:parseEditor()}; validateClientDocument(candidate); const blob = new Blob([JSON.stringify(candidate,null,2)+"\n"],{type:"application/json"}); const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href=url; anchor.download="manila-times-page-data.json"; anchor.click(); URL.revokeObjectURL(url); setStatus("JSON 下载文件已生成。");
}
function applyEditor() {
try { const candidate = {...data,[currentModule]:parseEditor()}; validateClientDocument(candidate); data=candidate; writeStorage(dataKey,JSON.stringify(data)); renderAll(); renderSettingsTabs(); setStatus("JSON 已应用并完成渲染。"); }
catch (error) { setStatus(error.message); setText("jsonValidity","JSON 无效"); }
}
node("weatherButton").addEventListener("click", () => { weatherIndex += 1; renderWeather(); });
node("openDrawer").addEventListener("click", () => openOverlay("drawerOverlay"));
node("openSearch").addEventListener("click", () => { openOverlay("searchOverlay"); searchStories(); setTimeout(() => node("searchInput").focus(),0); });
node("searchInput").addEventListener("input", searchStories);
node("captionToggle").addEventListener("click", () => { captionsOn = !captionsOn; updateCaption(); });
node("openEdition").addEventListener("click", () => { editionIndex=0; renderEditionPage(); openOverlay("editionOverlay"); });
node("editionPrev").addEventListener("click", () => { editionIndex -= 1; renderEditionPage(); });
node("editionNext").addEventListener("click", () => { editionIndex += 1; renderEditionPage(); });
node("newsletterForm").addEventListener("submit", (event) => { event.preventDefault(); setText("newsletterNote", `${data.media.newsletter.successPrefix} ${node("newsletterEmail").value}.`); });
node("openSettings").addEventListener("click", () => { renderSettingsTabs(); setStatus(""); openOverlay("settingsOverlay"); });
node("validateJson").addEventListener("click", () => { try { const candidate={...data,[currentModule]:parseEditor()}; validateClientDocument(candidate); setStatus("完整 JSON 校验通过。"); } catch(error) { setStatus(error.message); } });
node("copyJson").addEventListener("click", () => copyJson().catch((error) => setStatus(error.message)));
node("downloadJson").addEventListener("click", () => { try { downloadJson(); } catch(error) { setStatus(error.message); } });
node("resetJson").addEventListener("click", () => { data=clone(initialData); removeStorage(dataKey); removeStorage(themeKey); currentModule=MODULES[0]; activeFeed="latest"; activeRegion=data.regions.tabs[0].id; renderAll(); renderSettingsTabs(); setStatus("已恢复内嵌初始 JSON。"); });
node("applyJson").addEventListener("click", applyEditor);
document.querySelectorAll("[data-close]").forEach((button) => button.addEventListener("click", () => closeOverlay(button.dataset.close)));
["drawerOverlay","searchOverlay","videoOverlay","editionOverlay","settingsOverlay"].forEach((id) => node(id).addEventListener("click", (event) => { if (event.target === node(id)) closeOverlay(id); }));
document.addEventListener("keydown", (event) => { if (event.key === "Escape") document.querySelectorAll(".screen-overlay.open,.modal-overlay.open,.settings-overlay.open").forEach((overlay) => closeOverlay(overlay.id)); });
window.addEventListener("scroll", () => node("primaryNav").classList.toggle("stuck", window.scrollY > 180), {passive:true});
document.addEventListener("click", (event) => { const anchor=event.target.closest("a[href^='#']"); if (anchor && anchor.closest(".screen-overlay")) closeOverlay(anchor.closest(".screen-overlay").id); });
validateClientDocument(data);
renderAll();
function installJsonMediaUpload(){
const editor=document.getElementById("jsonEditor"),apply=document.getElementById("applyJson");if(!editor||!apply||document.getElementById("uploadJsonMedia"))return;
const actions=apply.parentElement,button=document.createElement("button"),input=document.createElement("input"),reference=actions.querySelector("#downloadJson,#copyJson,#validateJson,#resetJson");button.type="button";button.id="uploadJsonMedia";button.className=reference?reference.className:apply.className;button.textContent="上传图片/视频";button.title="先把光标放进要替换的内容对象,再选择图片或视频";input.type="file";input.accept="image/*,video/*";input.hidden=true;actions.insertBefore(button,apply);actions.appendChild(input);
const report=(message)=>{const status=document.getElementById("settingsStatus")||document.getElementById("jsonError")||document.getElementById("jsonStatus");if(status)status.textContent=message};
const findTarget=(text,cursor)=>{const stack=[],matches=[];let quoted=false,escaped=false;for(let index=0;index<text.length;index+=1){const char=text[index];if(quoted){if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char==='"')quoted=false;continue}if(char==='"'){quoted=true;continue}if(char==="{")stack.push(index);else if(char==="}"){const start=stack.pop();if(start===undefined||cursor<start||cursor>index+1)continue;try{const value=JSON.parse(text.slice(start,index+1)),own=(key)=>Object.prototype.hasOwnProperty.call(value,key);if(value&&!Array.isArray(value)&&(own("media")||own("visual")||(own("id")&&(own("text")||own("title"))&&(own("author")||own("channel")||own("user")))))matches.push({start,end:index+1,value})}catch(_error){/* full validator handles malformed JSON */}}}return matches.sort((left,right)=>(left.end-left.start)-(right.end-right.start))[0]||null};
button.addEventListener("click",()=>{input.value="";report("请选择图片或视频;文件会写入光标所在内容对象的 media 字段。");input.click()});
input.addEventListener("change",()=>{const file=input.files&&input.files[0];if(!file)return;const type=file.type.startsWith("image/")?"image":file.type.startsWith("video/")?"video":"";if(!type){report("仅支持图片或视频文件。");return}const target=findTarget(editor.value,editor.selectionStart);if(!target){report("请先把光标放进带 visual/media 的内容对象,或带 id 的帖子/视频对象内。");return}const reader=new FileReader();reader.onerror=()=>report("文件读取失败,请重新选择。");reader.onload=()=>{const previous=target.value.media&&typeof target.value.media==="object"?target.value.media:{},media={type,mediaUrl:String(reader.result)};for(const key of ["alt","label","caption","pageUrl"])if(typeof previous[key]==="string")media[key]=previous[key];if(!media.alt)media.alt=type==="image"?"用户上传的图片":"用户上传的视频";target.value.media=media;const lineStart=editor.value.lastIndexOf("\n",target.start-1)+1,indent=(editor.value.slice(lineStart,target.start).match(/^\s*/)||[""])[0],replacement=JSON.stringify(target.value,null,2).split("\n").map((line,index)=>index?indent+line:line).join("\n");editor.value=editor.value.slice(0,target.start)+replacement+editor.value.slice(target.end);editor.dispatchEvent(new Event("input",{bubbles:true}));const mediaIndex=replacement.indexOf('"media"');editor.focus();editor.setSelectionRange(target.start+Math.max(mediaIndex,0),target.start+Math.max(mediaIndex,0));report(`已把 ${file.name} 写入 JSON,请点击“应用并渲染”。${file.size>2*1024*1024?" 文件较大,建议同时下载 JSON 保存。":""}`)};reader.readAsDataURL(file)});
}
installJsonMediaUpload();
function installInlineMediaReplace() {
if (document.getElementById("dfInlineMediaInput")) return;
const visualHostSelector = ".post-media,.video-visual,.thumbnail-visual,.short-thumb,.watch-visual,.thread-media,.visual,.lead-visual,.mini-visual,.compact-media,.card-art,.story-visual,.art,.video-art,.media-art,.player-stage,.thumbnail,.thumb,.list-thumb,.focus-thumb,.involve-bg,.hero-art,#heroArt,#adminArt";
const getRootData = () => {
if (typeof pageData !== "undefined") return pageData;
if (typeof data !== "undefined") return data;
return null;
};
const input = document.createElement("input");
input.id = "dfInlineMediaInput";
input.type = "file";
input.hidden = true;
document.body.appendChild(input);
const style = document.createElement("style");
style.dataset.dfInlineMediaReplace = "true";
style.textContent = ".df-inline-media-host{position:relative!important}.df-inline-media-button{position:absolute;z-index:40;top:10px;right:10px;width:40px;height:40px;padding:0;border:1px solid rgba(255,255,255,.55);border-radius:50%;display:grid;place-items:center;color:#fff;background:rgba(8,15,28,.78);box-shadow:0 8px 24px rgba(0,0,0,.28);backdrop-filter:blur(8px);cursor:pointer;opacity:0;transform:translateY(-4px);transition:opacity .16s,transform .16s,background .16s}.df-inline-media-button:hover{background:rgba(20,110,240,.92)}.df-inline-media-button svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}.df-inline-media-host:hover>.df-inline-media-button,.df-inline-media-host:focus-within>.df-inline-media-button,.df-inline-media-button:focus-visible{opacity:1;transform:none}@media(hover:none){.df-inline-media-button{opacity:1;transform:none}}.df-inline-media-toast{position:fixed;z-index:2147483647;left:50%;bottom:28px;max-width:min(88vw,520px);padding:10px 14px;border-radius:10px;color:#fff;background:rgba(15,23,42,.94);box-shadow:0 12px 32px rgba(0,0,0,.28);font:600 13px/1.45 system-ui,sans-serif;transform:translateX(-50%)}";
document.head.appendChild(style);
const 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 exactPathTarget = (element) => {
const host = element.closest("[data-media-path]");
const path = host && host.dataset ? host.dataset.mediaPath : "";
if (!path) return null;
const owner = path.split(".").reduce((value, segment) => {
if (Array.isArray(value)) return value[Number(segment)];
return value && typeof value === "object" ? value[segment] : null;
}, getRootData());
if (!owner || typeof owner !== "object" || Array.isArray(owner)) return null;
return { owner, previous: owner.media && typeof owner.media === "object" ? owner.media : { type: "image" }, key: "mediaUrl" };
};
const chooseVisualTarget = (element) => {
const exact = exactPathTarget(element);
if (exact) return exact;
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 exact = exactPathTarget(element);
if (exact) return exact;
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,69 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>马尼拉时报——菲律宾新闻门户</title>
<style>
:root{--paper:#f4f0e7;--paper-2:#fffdf7;--ink:#132033;--muted:#69717b;--navy:#071a32;--navy-2:#102b4c;--red:#bd1e2d;--blue:#16559a;--gold:#c79a43;--line:#c8c0b2;--panel:#ebe5d8;--shadow:0 18px 60px rgba(7,26,50,.18);--serif:Georgia,"Times New Roman",serif;--sans:Arial,"Helvetica Neue",sans-serif}
*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:var(--paper);color:var(--ink);font-family:var(--serif);line-height:1.55}button,input{font:inherit}button,a{color:inherit}a{text-decoration:none}button{cursor:pointer}.skip-link{position:fixed;left:16px;top:-80px;z-index:300;background:#fff;color:#071a32;padding:10px 16px;font-family:var(--sans);font-weight:700}.skip-link:focus{top:10px}.flag-line{height:5px;background:linear-gradient(90deg,#18559b 0 42%,#fff 42% 58%,#bd1e2d 58%)}
.utility{background:var(--navy);color:#fff;font:700 11px/1 var(--sans);letter-spacing:.08em;text-transform:uppercase}.utility-inner,.masthead-inner,.nav-inner,.ticker-inner,.page-shell{width:min(1180px,calc(100% - 40px));margin:auto}.utility-inner{height:36px;display:flex;align-items:center;justify-content:space-between;gap:20px}.utility-links{display:flex;gap:20px}.utility a:hover{text-decoration:underline}.masthead{background:var(--paper-2);border-bottom:1px solid var(--line)}.masthead-inner{min-height:136px;display:grid;grid-template-columns:210px 1fr 210px;align-items:center;gap:24px}.weather{display:flex;align-items:center;gap:12px;font-family:var(--sans)}.weather-icon{width:43px;height:43px;border:1px solid var(--line);border-radius:50%;display:grid;place-items:center;background:linear-gradient(135deg,#f9d670,#9fd2e9)}.weather-city{font-size:12px;font-weight:800;text-transform:uppercase;letter-spacing:.08em}.weather-temp{font-size:21px;font-weight:800}.weather-note{font-size:11px;color:var(--muted)}.brand{text-align:center}.brand-kicker{font:800 10px/1 var(--sans);letter-spacing:.22em;text-transform:uppercase;color:var(--red);margin-bottom:9px}.brand-name{font-size:clamp(40px,6vw,74px);line-height:.84;letter-spacing:-.065em;font-weight:900;white-space:nowrap}.brand-accent{color:var(--red);font-style:italic}.brand-tagline{margin-top:13px;font:700 10px/1 var(--sans);letter-spacing:.28em;text-transform:uppercase;color:var(--muted)}.edition{text-align:right;font-family:var(--sans)}.edition-date{font-size:12px;font-weight:800}.edition-label{font-size:11px;color:var(--muted);margin-top:5px}.edition-rule{width:60px;height:2px;background:var(--red);margin:10px 0 0 auto}
.primary-nav{height:50px;background:var(--paper-2);border-bottom:1px solid var(--line);position:relative;z-index:80}.primary-nav.stuck{position:fixed;left:0;right:0;top:0;box-shadow:0 7px 24px rgba(7,26,50,.15)}.nav-inner{height:100%;display:grid;grid-template-columns:130px 1fr 130px;align-items:center}.nav-action{border:0;background:transparent;font:800 11px/1 var(--sans);text-transform:uppercase;letter-spacing:.08em;display:flex;align-items:center;gap:8px}.nav-action.right{justify-content:flex-end}.nav-links{display:flex;align-items:center;justify-content:center;height:100%;gap:clamp(18px,3vw,38px);font:800 11px/1 var(--sans);letter-spacing:.06em;text-transform:uppercase}.nav-links a{height:100%;display:flex;align-items:center;border-bottom:3px solid transparent}.nav-links a:hover{border-bottom-color:var(--red)}.ticker{background:var(--red);color:white}.ticker-inner{min-height:40px;display:flex;align-items:center;gap:14px;font-family:var(--sans);font-size:12px}.ticker-label{font-weight:900;letter-spacing:.12em;text-transform:uppercase;border-right:1px solid rgba(255,255,255,.45);padding-right:14px}.ticker-text{font-weight:700;flex:1}.ticker-time{opacity:.78}
.page-shell{padding:32px 0 70px}.dateline{display:flex;justify-content:space-between;gap:20px;border-top:3px double var(--ink);border-bottom:1px solid var(--line);padding:8px 0;font:800 10px/1 var(--sans);letter-spacing:.14em;color:var(--muted)}.lead-grid{display:grid;grid-template-columns:minmax(0,1.75fr) minmax(230px,.8fr) minmax(230px,.75fr);gap:24px;padding:24px 0 32px;border-bottom:1px solid var(--ink)}.kicker,.eyebrow{font:900 10px/1 var(--sans);letter-spacing:.14em;text-transform:uppercase;color:var(--red)}.lead-title{font-size:clamp(32px,4.3vw,60px);line-height:.95;letter-spacing:-.04em;margin:11px 0 15px}.summary{color:#4f5964}.byline{font:700 10px/1.4 var(--sans);text-transform:uppercase;letter-spacing:.08em;margin-top:18px}.story-visual{position:relative;overflow:hidden;background:var(--navy);min-height:180px;margin-top:18px}.story-visual::before,.story-visual::after{content:"";position:absolute}.story-visual::before{inset:0;background:linear-gradient(145deg,#244d73,#a5c4cf 56%,#cfab68)}.story-visual::after{left:-8%;right:-8%;bottom:-35%;height:72%;background:var(--paper);border-radius:50% 50% 0 0;box-shadow:0 -32px 0 rgba(7,26,50,.55),0 -55px 0 rgba(255,255,255,.25)}.story-visual[data-visual="port"]::before{background:linear-gradient(150deg,#789ab0 0 52%,#164464 52% 70%,#d98b42 70%)}.story-visual[data-visual="city"]::before{background:linear-gradient(90deg,#1b3551 0 12%,#7d93a2 12% 26%,#233b55 26% 42%,#bd7c55 42% 55%,#18304d 55% 73%,#9ba8ad 73%)}.story-visual[data-visual="city"]::after{display:none}.save-btn{border:1px solid var(--line);background:transparent;border-radius:50%;width:34px;height:34px;font:800 15px/1 var(--sans);float:right}.save-btn.saved{background:var(--red);color:white;border-color:var(--red)}.side-list{display:grid;gap:22px}.side-story{border-bottom:1px solid var(--line);padding-bottom:20px}.side-story h3{font-size:24px;line-height:1.05;margin:9px 0}.side-story .story-visual{min-height:115px}.feed-panel{border-left:1px solid var(--line);padding-left:22px}.feed-tabs{display:flex;border-bottom:2px solid var(--ink)}.feed-tab{flex:1;border:0;background:transparent;padding:10px 4px;font:900 11px/1 var(--sans);letter-spacing:.1em;text-transform:uppercase}.feed-tab.active{color:var(--red);border-bottom:4px solid var(--red);margin-bottom:-3px}.feed-items{list-style:none;margin:0;padding:0}.feed-item{display:grid;grid-template-columns:40px 1fr;gap:9px;padding:15px 0;border-bottom:1px solid var(--line)}.feed-time{font:800 10px/1.4 var(--sans);color:var(--red)}.feed-item span:last-child{font-weight:700;line-height:1.18}
.pulse{margin:28px 0 58px;background:var(--navy);color:white;display:grid;grid-template-columns:180px 1fr}.pulse-head{padding:22px;border-right:1px solid rgba(255,255,255,.2)}.pulse-head strong{display:block;font-size:22px}.pulse-items{display:grid;grid-template-columns:repeat(4,1fr)}.pulse-item{padding:20px;border-right:1px solid rgba(255,255,255,.16)}.pulse-item:last-child{border:0}.pulse-label{font:800 10px/1 var(--sans);letter-spacing:.12em;text-transform:uppercase;color:#b8c9dc}.pulse-value{font:800 21px/1.4 var(--sans)}.direction-up{color:#65d2a0}.direction-down{color:#f49a92}.direction-flat{color:#f4cb74}.section{padding:56px 0;border-top:1px solid var(--ink)}.section-head{display:flex;align-items:end;justify-content:space-between;gap:30px;margin-bottom:28px}.section-head h2{font-size:clamp(35px,5vw,58px);letter-spacing:-.045em;line-height:.94;margin:8px 0 0}.section-head p{max-width:470px;margin:0;color:var(--muted)}.text-link{font:900 10px/1 var(--sans);letter-spacing:.12em;text-transform:uppercase;border-bottom:2px solid var(--red);padding-bottom:5px;white-space:nowrap}
.region-tabs{display:flex;gap:8px;border-bottom:1px solid var(--line);margin-bottom:24px;overflow:auto}.region-tab{border:0;background:transparent;padding:12px 22px;font:900 11px/1 var(--sans);letter-spacing:.08em;text-transform:uppercase;white-space:nowrap}.region-tab.active{background:var(--navy);color:white}.region-layout{display:grid;grid-template-columns:1.4fr 1fr;gap:30px}.region-feature{display:grid;grid-template-columns:1fr 1fr;background:var(--paper-2);border:1px solid var(--line)}.region-copy{padding:30px}.region-copy h3{font-size:34px;line-height:1.02;margin:10px 0}.region-visual{min-height:330px;position:relative;overflow:hidden;background:linear-gradient(160deg,#457c9b,#d4c98c)}.region-visual::before{content:"";position:absolute;inset:15% 20%;background:#f0e6bc;clip-path:polygon(52% 0,68% 16%,61% 35%,79% 48%,65% 62%,72% 82%,48% 100%,29% 83%,37% 64%,17% 48%,38% 33%,31% 13%)}.region-visual[data-visual="visayas"]::before{clip-path:polygon(19% 4%,39% 18%,28% 36%,49% 45%,64% 20%,82% 34%,70% 52%,88% 71%,58% 89%,43% 69%,17% 93%,25% 58%,6% 42%)}.region-visual[data-visual="mindanao"]::before{clip-path:polygon(45% 3%,68% 15%,76% 36%,92% 49%,74% 70%,57% 66%,44% 94%,26% 80%,19% 57%,4% 42%,29% 28%)}.region-visual[data-visual="metro"]::before{clip-path:none;background:repeating-linear-gradient(90deg,#152d45 0 22px,#8e9cac 22px 39px);inset:35% 8% 0}.region-list{display:grid}.region-story{padding:20px 0;border-bottom:1px solid var(--line)}.region-location{font:900 9px/1 var(--sans);color:var(--red);text-transform:uppercase;letter-spacing:.14em}.region-story h3{font-size:24px;line-height:1.08;margin:8px 0}.region-story p{margin:0;color:var(--muted)}
.opinion{background:var(--navy);color:white;margin-left:calc(50% - 50vw);margin-right:calc(50% - 50vw);padding-left:max(20px,calc((100vw - 1180px)/2));padding-right:max(20px,calc((100vw - 1180px)/2))}.opinion .section-head p{color:#b7c3d2}.opinion-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:1px;background:#39506b}.opinion-card{background:var(--navy);padding:30px}.author{display:flex;align-items:center;gap:14px;font:800 11px/1.2 var(--sans);text-transform:uppercase;letter-spacing:.08em}.author-initial{width:48px;height:48px;border-radius:50%;background:var(--red);display:grid;place-items:center;font:800 20px/1 var(--serif)}.opinion-card h3{font-size:28px;line-height:1.05;margin:22px 0 10px}.opinion-card p{color:#b7c3d2}.split-sections{display:grid;grid-template-columns:1fr 1fr;gap:42px}.cards{display:grid;gap:18px}.story-card{display:grid;grid-template-columns:150px 1fr;gap:18px;border-top:1px solid var(--line);padding-top:18px}.mini-visual{min-height:105px;background:linear-gradient(145deg,#163b5e,#ca9b55);position:relative;overflow:hidden}.mini-visual::after{content:"";position:absolute;left:15%;right:15%;bottom:0;height:64%;background:repeating-linear-gradient(90deg,rgba(255,255,255,.75) 0 13px,transparent 13px 22px)}.mini-visual[data-visual="factory"]{background:linear-gradient(160deg,#8ba5af,#273c51)}.mini-visual[data-visual="shipping"]{background:linear-gradient(#8fc0d1 0 60%,#1d526e 60%)}.mini-visual[data-visual="running"]{background:linear-gradient(135deg,#d1865e,#233f60)}.mini-visual[data-visual="volleyball"]{background:linear-gradient(135deg,#d8b560,#8d2d32)}.story-card h3{font-size:22px;line-height:1.06;margin:7px 0}.sports-hero{background:var(--navy);color:white;padding:25px;margin-bottom:18px;min-height:280px;position:relative;overflow:hidden}.sports-hero::after{content:"";position:absolute;width:180px;height:180px;border:17px solid rgba(255,255,255,.15);border-radius:50%;right:-20px;bottom:-25px}.sports-hero h3{font-size:35px;line-height:1;margin:10px 0;max-width:440px}.sports-hero p{color:#c2cfdb;max-width:430px}.market-board{display:grid;grid-template-columns:repeat(3,1fr);border:1px solid var(--line);margin-top:24px}.market-cell{padding:14px 18px;border-right:1px solid var(--line);font-family:var(--sans)}.market-cell:last-child{border:0}.market-cell span{display:block;font-size:10px;text-transform:uppercase;color:var(--muted);font-weight:800}.market-cell strong{font-size:17px}
.watch-grid{display:grid;grid-template-columns:1.3fr 1fr 1fr;gap:18px}.video-card{border:0;text-align:left;background:var(--paper-2);padding:0;color:inherit;box-shadow:0 0 0 1px var(--line)}.video-visual{height:205px;background:linear-gradient(140deg,#102b49,#a66d48);position:relative;overflow:hidden}.video-card:first-child .video-visual{height:280px}.video-visual::before{content:"▶";position:absolute;left:20px;bottom:18px;width:48px;height:48px;border-radius:50%;background:var(--red);color:#fff;display:grid;place-items:center;padding-left:3px;font:800 16px/1 var(--sans);z-index:2}.video-visual[data-visual="studio"]::after{content:"";position:absolute;inset:18% 14%;border:1px solid rgba(255,255,255,.35);background:linear-gradient(90deg,transparent 49%,rgba(255,255,255,.18) 50%,transparent 51%)}.video-visual[data-visual="islands"]{background:linear-gradient(155deg,#2e8fa4,#092948)}.video-visual[data-visual="city-night"]{background:repeating-linear-gradient(90deg,#0b1c34 0 33px,#8b3953 33px 48px,#16314f 48px 72px)}.duration{position:absolute;right:12px;bottom:12px;background:#071a32;color:white;padding:4px 7px;font:800 10px/1 var(--sans)}.video-copy{padding:20px}.video-copy h3{font-size:24px;line-height:1.05;margin:8px 0}.video-copy p{margin:0;color:var(--muted)}
.edition{background:var(--panel);text-align:left;padding:52px;display:grid;grid-template-columns:1fr .9fr;align-items:center;gap:50px}.edition h2{font-size:50px;line-height:.96;margin:10px 0 16px}.edition-preview{height:330px;background:var(--paper-2);box-shadow:var(--shadow);transform:rotate(2deg);padding:20px;border-top:7px solid var(--red);position:relative}.edition-preview::before{content:"THE MANILA TIMES";font:900 30px/1 var(--serif);letter-spacing:-.04em}.edition-preview::after{content:"";position:absolute;left:20px;right:20px;top:70px;bottom:20px;background:linear-gradient(#17354f 0 42%,transparent 42%),repeating-linear-gradient(90deg,#d0c8bb 0 2px,transparent 2px 7px);background-size:100% 58%,100% 47%;background-position:0 0,0 100%;background-repeat:no-repeat}.actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:22px}.btn{border:1px solid var(--ink);background:transparent;padding:12px 18px;font:900 10px/1 var(--sans);letter-spacing:.1em;text-transform:uppercase}.btn.primary{background:var(--red);border-color:var(--red);color:white}.newsletter{background:var(--red);color:white;padding:36px 42px;display:grid;grid-template-columns:1fr 1fr;gap:45px;align-items:center}.newsletter h2{font-size:38px;line-height:1;margin:6px 0}.newsletter-form{display:flex}.newsletter input{width:100%;border:0;padding:15px 16px;background:#fff;color:#071a32;min-width:0}.newsletter button{border:0;background:var(--navy);color:white;padding:15px 20px;font:800 10px/1 var(--sans);text-transform:uppercase;letter-spacing:.08em}.form-note{font:700 11px/1.4 var(--sans);margin-top:8px;min-height:16px}
.footer{background:var(--navy);color:white;padding:55px max(20px,calc((100vw - 1180px)/2)) 28px}.footer-top{display:grid;grid-template-columns:1.4fr 2fr;gap:70px}.footer-brand{font-size:34px;font-weight:900;line-height:1}.footer-description{color:#b9c6d4;max-width:430px}.footer-columns{display:grid;grid-template-columns:repeat(3,1fr);gap:30px}.footer-columns h3{font:900 10px/1 var(--sans);text-transform:uppercase;letter-spacing:.12em;color:#e6b252}.footer-columns a{display:block;color:#c8d2dd;margin:9px 0;font-size:14px}.footer-bottom{border-top:1px solid #344b65;margin-top:38px;padding-top:20px;display:flex;justify-content:space-between;gap:20px;color:#92a4b8;font:700 10px/1.4 var(--sans)}
.screen-overlay,.modal-overlay,.settings-overlay{position:fixed;inset:0;z-index:160;background:rgba(5,16,31,.92);color:white;display:none}.screen-overlay.open,.modal-overlay.open,.settings-overlay.open{display:block}.screen-panel{width:min(1100px,calc(100% - 40px));margin:auto;padding:45px 0}.overlay-top{display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #52647a;padding-bottom:18px}.overlay-close{border:1px solid #65778b;background:transparent;color:white;width:42px;height:42px;font-size:25px}.drawer-layout{display:grid;grid-template-columns:1fr 1.4fr;gap:70px;padding-top:50px}.drawer-layout h2,.search-panel h2{font-size:55px;line-height:.95;margin:10px 0}.drawer-links{display:grid;grid-template-columns:1fr 1fr;gap:12px}.drawer-links a{border-bottom:1px solid #3b516c;padding:13px 0;font-size:23px}.search-panel{width:min(850px,calc(100% - 40px));margin:8vh auto}.search-input{width:100%;border:0;border-bottom:2px solid white;background:transparent;color:white;padding:15px 0;font-size:32px;outline:none}.search-meta{font:700 11px/1 var(--sans);color:#9eb0c3;margin:16px 0}.search-results{display:grid;gap:4px;max-height:55vh;overflow:auto}.search-result{border:0;border-bottom:1px solid #38506b;background:transparent;color:white;text-align:left;padding:14px 0;font-size:20px}.modal-overlay{padding:4vh 20px;background:rgba(3,10,18,.85)}.modal-card{width:min(900px,100%);max-height:92vh;overflow:auto;margin:auto;background:var(--paper-2);color:var(--ink);box-shadow:var(--shadow)}.modal-head{background:var(--navy);color:white;padding:18px 22px;display:flex;justify-content:space-between;align-items:center}.modal-body{padding:28px}.video-stage{min-height:390px;background:linear-gradient(145deg,#071a32,#815143);display:grid;place-items:center;color:white;text-align:center}.video-stage strong{display:block;font-size:35px}.caption{background:#071a32;color:white;padding:8px 14px;margin-top:18px;text-align:center}.edition-page{min-height:480px;background:#f4f0e7;padding:40px;border:1px solid var(--line)}.edition-page .paper-brand{font-size:40px;font-weight:900;border-bottom:4px double var(--ink)}.edition-page h2{font-size:48px;line-height:.95}.page-controls{display:flex;justify-content:space-between;align-items:center;margin-top:18px}
.settings-button{position:fixed;right:18px;top:18px;z-index:145;width:45px;height:45px;border-radius:50%;border:1px solid rgba(255,255,255,.5);background:#071a32;color:white;box-shadow:0 7px 22px rgba(0,0,0,.25);font-size:19px}.settings-overlay{background:rgba(3,12,23,.82);padding:24px}.settings-card{height:calc(100vh - 48px);max-width:1500px;margin:auto;background:#071426;color:#eef6ff;border:1px solid #2b739e;display:grid;grid-template-rows:auto 1fr auto;box-shadow:0 0 50px rgba(0,0,0,.5)}.settings-head{padding:22px 28px;border-bottom:1px solid #24516f;display:flex;justify-content:space-between;align-items:center}.settings-head small{display:block;color:#35b6ed;font:800 11px/1 var(--sans);letter-spacing:.13em;text-transform:uppercase;margin-bottom:8px}.settings-head h2{margin:0;font:800 26px/1 var(--sans)}.settings-main{display:grid;grid-template-columns:270px 1fr;min-height:0}.module-tabs{padding:18px;border-right:1px solid #24516f;overflow:auto;display:grid;align-content:start;gap:7px}.module-tab{border:1px solid #244b68;background:#0b2035;color:#c5d8e7;text-align:left;padding:12px 14px;font:800 12px/1 var(--sans);text-transform:uppercase;letter-spacing:.08em}.module-tab.active{background:#1aa9e8;color:#041322;border-color:#1aa9e8}.editor-wrap{min-width:0;padding:18px;display:grid;grid-template-rows:auto 1fr auto;gap:10px}.editor-meta{display:flex;justify-content:space-between;color:#94afc5;font:700 12px/1 var(--sans)}.json-editor{width:100%;height:100%;resize:none;background:#020b14;color:#d6efff;border:1px solid #244b68;padding:18px;font:14px/1.55 Consolas,monospace;outline:none;tab-size:2}.editor-help{color:#829db2;font:12px/1.4 var(--sans)}.settings-actions{padding:16px 28px;border-top:1px solid #24516f;display:flex;justify-content:flex-end;gap:10px}.settings-actions button{border:1px solid #3381ab;background:transparent;color:white;padding:12px 17px;font:800 11px/1 var(--sans)}.settings-actions .apply{background:#27b0ec;color:#03111d;border-color:#27b0ec}.status{margin-right:auto;align-self:center;color:#8bd2f2;font:700 12px/1.4 var(--sans)}
.edition-preview::before{content:"马尼拉时报"}
body.night{--paper:#111820;--paper-2:#17222d;--ink:#eef1f3;--muted:#aab5bd;--line:#42505b;--panel:#1d2b37}.night .story-visual::after{background:#17222d}.night .edition-preview,.night .edition-page{color:#132033}.night .region-visual::before{background:#e1d9ab}.night .btn{border-color:var(--ink)}
@media(max-width:1000px){.masthead-inner{grid-template-columns:150px 1fr 150px}.lead-grid{grid-template-columns:1.4fr .8fr}.feed-panel{grid-column:1/-1;border-left:0;border-top:1px solid var(--line);padding:20px 0 0}.feed-items{display:grid;grid-template-columns:1fr 1fr}.pulse{grid-template-columns:1fr}.pulse-head{border-right:0;border-bottom:1px solid rgba(255,255,255,.2)}.region-layout,.split-sections{grid-template-columns:1fr}.watch-grid{grid-template-columns:1fr 1fr}.watch-grid .video-card:first-child{grid-column:1/-1}.edition{grid-template-columns:1fr 1fr}.drawer-layout{gap:30px}.settings-main{grid-template-columns:210px 1fr}}
@media(max-width:720px){.utility-inner{justify-content:center}.utility-links:first-child,.weather,.edition{display:none}.masthead-inner{display:block;min-height:auto;padding:30px 0}.brand-name{white-space:normal;font-size:48px}.nav-inner{grid-template-columns:80px 1fr 80px}.nav-links{display:none}.ticker-time{display:none}.page-shell{width:min(100% - 28px,1180px);padding-top:20px}.dateline span:last-child{display:none}.lead-grid{grid-template-columns:1fr}.lead-title{font-size:42px}.side-list{grid-template-columns:1fr 1fr}.feed-panel{grid-column:auto}.pulse-items{grid-template-columns:1fr 1fr}.section{padding:42px 0}.section-head{display:block}.section-head .text-link{display:inline-block;margin-top:18px}.region-feature{grid-template-columns:1fr}.region-visual{min-height:220px}.opinion-grid{grid-template-columns:1fr}.watch-grid{grid-template-columns:1fr}.watch-grid .video-card:first-child{grid-column:auto}.edition{grid-template-columns:1fr;padding:30px}.edition-preview{display:none}.newsletter{grid-template-columns:1fr;padding:30px}.footer-top{grid-template-columns:1fr;gap:30px}.drawer-layout{grid-template-columns:1fr}.drawer-layout h2,.search-panel h2{font-size:38px}.drawer-links{grid-template-columns:1fr}.settings-overlay{padding:8px}.settings-card{height:calc(100vh - 16px)}.settings-main{grid-template-columns:1fr;grid-template-rows:auto 1fr}.module-tabs{grid-auto-flow:column;grid-auto-columns:max-content;overflow-x:auto;border-right:0;border-bottom:1px solid #24516f;padding:10px}.settings-head{padding:16px}.settings-actions{padding:12px;overflow:auto}.settings-actions button{white-space:nowrap}.status{display:none}}
@media(max-width:460px){.side-list{grid-template-columns:1fr}.feed-items{grid-template-columns:1fr}.pulse-items{grid-template-columns:1fr}.story-card{grid-template-columns:105px 1fr}.market-board{grid-template-columns:1fr}.market-cell{border-right:0;border-bottom:1px solid var(--line)}.footer-columns{grid-template-columns:1fr}.footer-bottom{display:block}.newsletter-form{display:block}.newsletter button{width:100%}.settings-button{right:10px;top:10px}.brand-name{font-size:41px}}
@media(prefers-reduced-motion:reduce){html{scroll-behavior:auto}*,*::before,*::after{animation:none!important;transition:none!important}}
.skip-link:focus{top:calc(var(--df-generated-header-height,0px) + 10px)}
.primary-nav.stuck{top:var(--df-generated-header-height,0px)}
.settings-button{top:calc(var(--df-generated-header-height,0px) + 18px)}
@media(max-width:460px){.settings-button{top:calc(var(--df-generated-header-height,0px) + 10px)}}
.screen-overlay,.modal-overlay{z-index:1200}.settings-overlay{z-index:1300}
</style>
</head>
<body>
<a class="skip-link" id="skipLink" href="#top-stories">跳转到头条新闻</a>
<button class="settings-button" id="openSettings" aria-label="编辑页面 JSON" title="编辑页面 JSON">⚙</button>
<div class="flag-line"></div>
<header>
<div class="utility"><div class="utility-inner"><nav class="utility-links" id="utilityLeft"></nav><nav class="utility-links" id="utilityRight"></nav></div></div>
<div class="masthead"><div class="masthead-inner">
<button class="weather nav-action" id="weatherButton" aria-label="切换城市天气"><span class="weather-icon">☀</span><span><span class="weather-city" id="weatherCity"></span><span class="weather-temp" id="weatherTemp"></span><span class="weather-note" id="weatherNote"></span></span></button>
<div class="brand"><div class="brand-kicker" id="brandKicker"></div><div class="brand-name"><span id="brandPrefix"></span> <span class="brand-accent" id="brandAccent"></span></div><div class="brand-tagline" id="brandTagline"></div></div>
<div class="edition"><div class="edition-date" id="dateLabel"></div><div class="edition-label" id="editionLabel"></div><div class="edition-rule"></div></div>
</div></div>
<div class="primary-nav" id="primaryNav"><div class="nav-inner"><button class="nav-action" id="openDrawer">☰ <span id="menuLabel"></span></button><nav class="nav-links" id="primaryLinks"></nav><button class="nav-action right" id="openSearch"><span id="searchLabel"></span> ⌕</button></div></div>
<div class="ticker"><div class="ticker-inner"><span class="ticker-label" id="tickerLabel"></span><a class="ticker-text" id="tickerText"></a><span class="ticker-time" id="tickerTime"></span></div></div>
</header>
<main class="page-shell" id="mainContent">
<section id="top-stories"><div class="dateline"><span id="datelineLeft"></span><span id="datelineRight"></span></div><div class="lead-grid"><article id="leadMain"></article><div class="side-list" id="sideStories"></div><aside class="feed-panel"><div class="feed-tabs" id="feedTabs"></div><ol class="feed-items" id="feedItems"></ol></aside></div></section>
<section class="pulse" id="pulse"><div class="pulse-head"><span class="eyebrow" id="pulseLabel"></span><strong id="pulseTitle"></strong></div><div class="pulse-items" id="pulseItems"></div></section>
<section class="section" id="regions"><div class="section-head"><div><div class="eyebrow" id="regionsEyebrow"></div><h2 id="regionsTitle"></h2></div><a class="text-link" id="regionsMore"></a></div><div class="region-tabs" id="regionTabs"></div><div class="region-layout" id="regionContent"></div></section>
<section class="section opinion" id="opinion"><div class="section-head"><div><div class="eyebrow" id="opinionEyebrow"></div><h2 id="opinionTitle"></h2></div><p id="opinionSummary"></p></div><div class="opinion-grid" id="opinionGrid"></div></section>
<section class="section split-sections"><div id="business"><div class="section-head"><div><div class="eyebrow" id="businessEyebrow"></div><h2 id="businessTitle"></h2></div><a class="text-link" id="businessMore"></a></div><div class="cards" id="businessItems"></div></div><div id="sports"><div class="section-head"><div><div class="eyebrow" id="sportsEyebrow"></div><h2 id="sportsTitle"></h2></div><a class="text-link" id="sportsMore"></a></div><article class="sports-hero" id="sportsHero"></article><div class="cards" id="sportsItems"></div><div id="marketBoard"></div></div></section>
<section class="section" id="watch"><div class="section-head"><div><div class="eyebrow" id="watchEyebrow"></div><h2 id="watchTitle"></h2></div><a class="text-link" id="watchMore"></a></div><div class="watch-grid" id="videoGrid"></div></section>
<section class="section" id="edition"><div class="edition"><div><div class="eyebrow" id="editionEyebrow"></div><h2 id="editionTitle"></h2><p class="summary" id="editionSummary"></p><div class="actions"><button class="btn primary" id="openEdition"></button><a class="btn" id="editionSubscribe"></a></div></div><div class="edition-preview" aria-hidden="true"></div></div></section>
<section class="newsletter" id="newsletter"><div><div class="eyebrow" id="newsletterEyebrow"></div><h2 id="newsletterTitle"></h2><p id="newsletterText"></p></div><div><form class="newsletter-form" id="newsletterForm"><input type="email" id="newsletterEmail" required><button id="newsletterButton"></button></form><div class="form-note" id="newsletterNote" role="status"></div></div></section>
</main>
<footer class="footer" id="footer"><div class="footer-top"><div><div class="footer-brand" id="footerBrand"></div><p class="footer-description" id="footerDescription"></p></div><div class="footer-columns" id="footerColumns"></div></div><div class="footer-bottom"><span id="footerCopyright"></span><span id="footerLegal"></span></div></footer>
<div class="screen-overlay" id="drawerOverlay" aria-hidden="true"><div class="screen-panel"><div class="overlay-top"><strong id="drawerBrand"></strong><button class="overlay-close" data-close="drawerOverlay" aria-label="关闭">×</button></div><div class="drawer-layout"><div><div class="eyebrow" id="drawerEyebrow"></div><h2 id="drawerTitle"></h2><p id="drawerText"></p><a class="btn primary" id="drawerCta"></a></div><nav class="drawer-links" id="drawerLinks"></nav></div></div></div>
<div class="screen-overlay" id="searchOverlay" aria-hidden="true"><div class="search-panel"><div class="overlay-top"><strong id="searchBrand"></strong><button class="overlay-close" data-close="searchOverlay" aria-label="关闭">×</button></div><h2 id="searchTitle"></h2><input class="search-input" id="searchInput"><div class="search-meta" id="searchMeta"></div><div class="search-results" id="searchResults"></div></div></div>
<div class="modal-overlay" id="videoOverlay" aria-hidden="true"><div class="modal-card"><div class="modal-head"><strong id="videoModalTitle"></strong><button class="overlay-close" data-close="videoOverlay" aria-label="关闭">×</button></div><div class="modal-body"><div class="video-stage"><div><strong id="videoPlayingTitle"></strong><span id="videoSubtitle"></span></div></div><button class="btn" id="captionToggle"></button><div class="caption" id="videoCaption"></div></div></div></div>
<div class="modal-overlay" id="editionOverlay" aria-hidden="true"><div class="modal-card"><div class="modal-head"><strong id="editionModalTitle"></strong><button class="overlay-close" data-close="editionOverlay" aria-label="关闭">×</button></div><div class="modal-body"><article class="edition-page" id="editionPage"></article><div class="page-controls"><button class="btn" id="editionPrev">← 上一版</button><span id="editionPageCount"></span><button class="btn" id="editionNext">下一版 →</button></div></div></div></div>
<div class="settings-overlay" id="settingsOverlay" aria-hidden="true"><div class="settings-card"><div class="settings-head"><div><small>马尼拉时报页面模板控制台</small><h2>JSON 编辑器</h2></div><button class="overlay-close" data-close="settingsOverlay" aria-label="关闭">×</button></div><div class="settings-main"><div class="module-tabs" id="moduleTabs"></div><div class="editor-wrap"><div class="editor-meta"><span id="editorModule"></span><span id="jsonValidity">JSON 有效</span></div><textarea class="json-editor" id="jsonEditor" spellcheck="false"></textarea><div class="editor-help">编辑当前模块并完成校验后,即可应用到页面。缓存数据会按照当前文件的初始 JSON 指纹隔离。</div></div></div><div class="settings-actions"><span class="status" id="settingsStatus"></span><button id="validateJson">校验</button><button id="copyJson">复制 JSON</button><button id="downloadJson">下载 JSON</button><button id="resetJson">重置</button><button class="apply" id="applyJson">应用并渲染</button></div></div></div>
<script type="application/json" id="manilaTimesPageData">__MANILA_TIMES_PAGE_DATA__</script>
<script>__MANILA_TIMES_PAGE_RUNTIME__</script>
</body>
</html>
@@ -0,0 +1,30 @@
# 马尼拉时报页面 JSON 契约
顶层只允许以下十个对象,任何模块都不能删除:
`site`、`navigation`、`ticker`、`lead`、`pulse`、`regions`、`opinion`、`sections`、`media`、`footer`。
## 模块说明
- `site`:`brandPrefix/brandAccent/kicker/tagline/dateLabel/editionLabel/pageTitle/description/language/skipLabel/theme/weather[]`。`theme` 为 `light|dark|auto`;天气项含唯一 `id`、`city/temp/condition`。
- `navigation`:`menuLabel/searchLabel/themeLightLabel/themeDarkLabel/utilityLeft[]/utilityRight[]/primary[]/drawer/search`。所有链接只允许 `#锚点`。
- `ticker`:`label/text/time/href`。
- `lead`:`datelineLeft/datelineRight/main/sideStories[]/feeds[]`。头条和侧栏含 `id/kicker/title/summary/byline/time/visual`;feed 含唯一 `id`、`label` 和新闻项。
- `pulse`:`label/title/items[]`,指标项含唯一 `id`、`label/value/change/direction`,`direction` 为 `up|down|flat`。
- `regions`:`eyebrow/title/moreLabel/moreHref/tabs[]`。每个标签含唯一 `id`、`label`、`feature` 和 `items[]`。
- `opinion`:`eyebrow/title/summary/columns[]`,专栏含唯一 `id`、`initial/name/title/summary`。
- `sections`:`business/sports/market`。商业卡片使用 `market|factory|shipping`;体育视觉使用 `basketball|running|volleyball`。
- `media`:`watch/edition/newsletter`。视频视觉使用 `studio|islands|city-night`;数字报页含唯一 `id`、`label/headline/text`。
- `footer`:`description/columns[]/copyright/legal`。
## 通用限制
- `site.language` 固定为 `zh-CN`。
- 所有报头、栏目、标题、摘要、作者、按钮、日期、地区、活动和页脚等读者可见文案必须使用简体中文;英文或菲律宾语来源先翻译后再写入 JSON。
- JSON 键名以及 `id`、`href`、`visual`、`direction`、`theme` 等技术值按契约保留英文,不要翻译或改名;数字、时间、百分比和货币值可以保持数据格式。
- 文本必须是纯文本,不得包含 HTML 或 `javascript:`。具有 `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。
- 所有 `href` 必须以 `#` 开头。
- 同一数组中的 `id` 必须唯一。
- 页面不加载远程字体、脚本或接口;默认视觉由模板内置 CSS 图形生成,只有明确提供受校验媒体 URL 时才加载对应媒体。
- 内容数组有上限,校验脚本报错时以报错字段为准。
@@ -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_manila_times_page as renderer
from fast_patch_page import run
if __name__ == "__main__":
sys.exit(run(renderer, output_stem="manila-times-page"))
@@ -0,0 +1,547 @@
#!/usr/bin/env python3
"""Validate Manila Times-style page data and render the bundled 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 / "manila-times-template.html"
RUNTIME_PATH = ASSETS_DIR / "manila-times-runtime.js"
MODULES = (
"site",
"navigation",
"ticker",
"lead",
"pulse",
"regions",
"opinion",
"sections",
"media",
"footer",
)
LEAD_VISUALS = {"bay-transit", "port", "city"}
REGION_VISUALS = {"luzon", "visayas", "mindanao", "metro"}
BUSINESS_VISUALS = {"market", "factory", "shipping"}
SPORTS_VISUALS = {"basketball", "running", "volleyball"}
VIDEO_VISUALS = {"studio", "islands", "city-night"}
FORBIDDEN_TEXT = ("<script", "<iframe", "javascript:", "http://", "https://")
REMOTE_MEDIA_TYPES = {"image", "video", "webpage"}
MEDIA_URL_KEYS = {"mediaUrl", "posterUrl", "pageUrl"}
TECHNICAL_TEXT_KEYS = {"id", "href", "visual", "direction", "theme", "language", "type", "mediaUrl", "posterUrl", "pageUrl"}
class DataValidationError(ValueError):
"""Raised when JSON does not satisfy the fixed page 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,
maximum: int,
) -> 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 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 _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 _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 _strings(item: dict[str, Any], path: str, keys: tuple[str, ...], errors: list[str]) -> None:
for key in keys:
_required_string(item.get(key), f"{path}.{key}", errors)
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_type = media.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.get("mediaUrl"), f"{media_path}.mediaUrl", errors, required=True, data_prefix=f"data:{media_type}/")
if media_type == "video":
_remote_url(media.get("posterUrl"), f"{media_path}.posterUrl", errors, data_prefix="data:image/")
if media_type == "webpage":
_remote_url(media.get("pageUrl"), f"{media_path}.pageUrl", errors, required=True)
_remote_url(media.get("mediaUrl"), f"{media_path}.mediaUrl", errors, data_prefix="data:image/")
if "embed" in media and not isinstance(media.get("embed"), bool):
errors.append(f"{media_path}.embed must be a boolean")
elif media_type in {"image", "video"}:
_remote_url(media.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_chinese_reader_copy(
value: Any,
path: str,
errors: list[str],
*,
key: str | None = None,
) -> None:
if isinstance(value, dict):
for child_key, item in value.items():
_validate_chinese_reader_copy(
item,
f"{path}.{child_key}",
errors,
key=child_key,
)
elif isinstance(value, list):
for index, item in enumerate(value):
_validate_chinese_reader_copy(item, f"{path}[{index}]", errors, key=key)
elif (
isinstance(value, str)
and key not in TECHNICAL_TEXT_KEYS
and not (key and key.lower().endswith(("id", "href", "url")))
):
has_latin = any(
"a" <= character.lower() <= "z" for character in value
)
has_cjk = any("\u3400" <= character <= "\u9fff" for character in value)
if has_latin and not has_cjk:
errors.append(f"{path} must use Simplified Chinese reader-facing copy")
def _story(
value: Any,
path: str,
errors: list[str],
seen: set[str],
visuals: set[str],
) -> dict[str, Any]:
item = _mapping(value, path, errors)
_unique_id(item, path, seen, errors)
_strings(item, path, ("kicker", "title", "summary", "visual"), errors)
if item.get("visual") not in visuals:
errors.append(f"{path}.visual must be one of {sorted(visuals)}")
return item
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)
_strings(
site,
"site",
(
"brandPrefix",
"brandAccent",
"kicker",
"tagline",
"dateLabel",
"editionLabel",
"pageTitle",
"description",
"language",
"skipLabel",
),
errors,
)
if site.get("theme") not in {"light", "dark", "auto"}:
errors.append("site.theme must be light, dark, or auto")
if site.get("language") != "zh-CN":
errors.append("site.language must be zh-CN")
weather = _array(site.get("weather"), "site.weather", errors, minimum=1, maximum=6)
seen_weather: set[str] = set()
for index, raw in enumerate(weather):
path = f"site.weather[{index}]"
item = _mapping(raw, path, errors)
_unique_id(item, path, seen_weather, errors)
_strings(item, path, ("city", "temp", "condition"), errors)
navigation = _mapping(data.get("navigation"), "navigation", errors)
_strings(
navigation,
"navigation",
("menuLabel", "searchLabel", "themeLightLabel", "themeDarkLabel"),
errors,
)
utility_left = _links(
navigation.get("utilityLeft"),
"navigation.utilityLeft",
errors,
minimum=1,
maximum=5,
)
utility_right = _links(
navigation.get("utilityRight"),
"navigation.utilityRight",
errors,
minimum=1,
maximum=5,
)
primary = _links(
navigation.get("primary"),
"navigation.primary",
errors,
minimum=3,
maximum=9,
)
drawer = _mapping(navigation.get("drawer"), "navigation.drawer", errors)
_strings(drawer, "navigation.drawer", ("eyebrow", "title", "text", "ctaLabel"), errors)
_href(drawer.get("ctaHref"), "navigation.drawer.ctaHref", errors)
search = _mapping(navigation.get("search"), "navigation.search", errors)
_strings(search, "navigation.search", ("title", "placeholder", "hint", "emptyMessage", "resultPrefix"), errors)
ticker = _mapping(data.get("ticker"), "ticker", errors)
_strings(ticker, "ticker", ("label", "text", "time"), errors)
_href(ticker.get("href"), "ticker.href", errors)
lead = _mapping(data.get("lead"), "lead", errors)
_strings(lead, "lead", ("datelineLeft", "datelineRight"), errors)
seen_lead: set[str] = set()
main = _story(lead.get("main"), "lead.main", errors, seen_lead, LEAD_VISUALS)
_strings(main, "lead.main", ("byline", "time"), errors)
side_stories = _array(lead.get("sideStories"), "lead.sideStories", errors, minimum=1, maximum=4)
for index, raw in enumerate(side_stories):
path = f"lead.sideStories[{index}]"
item = _story(raw, path, errors, seen_lead, LEAD_VISUALS)
_strings(item, path, ("byline", "time"), errors)
feeds = _array(lead.get("feeds"), "lead.feeds", errors, minimum=2, maximum=3)
seen_feeds: set[str] = set()
feed_items = 0
for feed_index, raw_feed in enumerate(feeds):
feed_path = f"lead.feeds[{feed_index}]"
feed = _mapping(raw_feed, feed_path, errors)
_unique_id(feed, feed_path, seen_feeds, errors)
_required_string(feed.get("label"), f"{feed_path}.label", errors)
items = _array(feed.get("items"), f"{feed_path}.items", errors, minimum=1, maximum=8)
feed_items += len(items)
for item_index, raw_item in enumerate(items):
item_path = f"{feed_path}.items[{item_index}]"
item = _mapping(raw_item, item_path, errors)
_strings(item, item_path, ("time", "title"), errors)
pulse = _mapping(data.get("pulse"), "pulse", errors)
_strings(pulse, "pulse", ("label", "title"), errors)
pulse_items = _array(pulse.get("items"), "pulse.items", errors, minimum=2, maximum=8)
seen_pulse: set[str] = set()
for index, raw in enumerate(pulse_items):
path = f"pulse.items[{index}]"
item = _mapping(raw, path, errors)
_unique_id(item, path, seen_pulse, errors)
_strings(item, path, ("label", "value", "change"), errors)
if item.get("direction") not in {"up", "down", "flat"}:
errors.append(f"{path}.direction must be up, down, or flat")
regions = _mapping(data.get("regions"), "regions", errors)
_strings(regions, "regions", ("eyebrow", "title", "moreLabel"), errors)
_href(regions.get("moreHref"), "regions.moreHref", errors)
region_tabs = _array(regions.get("tabs"), "regions.tabs", errors, minimum=2, maximum=6)
seen_regions: set[str] = set()
region_stories = 0
for tab_index, raw_tab in enumerate(region_tabs):
tab_path = f"regions.tabs[{tab_index}]"
tab = _mapping(raw_tab, tab_path, errors)
_unique_id(tab, tab_path, seen_regions, errors)
_required_string(tab.get("label"), f"{tab_path}.label", errors)
feature = _mapping(tab.get("feature"), f"{tab_path}.feature", errors)
_strings(feature, f"{tab_path}.feature", ("kicker", "title", "summary", "visual"), errors)
if feature.get("visual") not in REGION_VISUALS:
errors.append(f"{tab_path}.feature.visual must be one of {sorted(REGION_VISUALS)}")
items = _array(tab.get("items"), f"{tab_path}.items", errors, minimum=1, maximum=6)
region_stories += len(items)
for item_index, raw_item in enumerate(items):
item_path = f"{tab_path}.items[{item_index}]"
item = _mapping(raw_item, item_path, errors)
_strings(item, item_path, ("location", "title", "summary"), errors)
opinion = _mapping(data.get("opinion"), "opinion", errors)
_strings(opinion, "opinion", ("eyebrow", "title", "summary"), errors)
columns = _array(opinion.get("columns"), "opinion.columns", errors, minimum=2, maximum=6)
seen_columns: set[str] = set()
for index, raw in enumerate(columns):
path = f"opinion.columns[{index}]"
item = _mapping(raw, path, errors)
_unique_id(item, path, seen_columns, errors)
_strings(item, path, ("initial", "name", "title", "summary"), errors)
sections = _mapping(data.get("sections"), "sections", errors)
business = _mapping(sections.get("business"), "sections.business", errors)
_strings(business, "sections.business", ("eyebrow", "title", "moreLabel"), errors)
_href(business.get("moreHref"), "sections.business.moreHref", errors)
business_items = _array(business.get("items"), "sections.business.items", errors, minimum=2, maximum=6)
seen_business: set[str] = set()
for index, raw in enumerate(business_items):
_story(raw, f"sections.business.items[{index}]", errors, seen_business, BUSINESS_VISUALS)
sports = _mapping(sections.get("sports"), "sections.sports", errors)
_strings(sports, "sections.sports", ("eyebrow", "title", "moreLabel"), errors)
_href(sports.get("moreHref"), "sections.sports.moreHref", errors)
seen_sports: set[str] = set()
_story(sports.get("hero"), "sections.sports.hero", errors, seen_sports, SPORTS_VISUALS)
sports_items = _array(sports.get("items"), "sections.sports.items", errors, minimum=1, maximum=5)
for index, raw in enumerate(sports_items):
item = _mapping(raw, f"sections.sports.items[{index}]", errors)
_unique_id(item, f"sections.sports.items[{index}]", seen_sports, errors)
_strings(item, f"sections.sports.items[{index}]", ("kicker", "title", "visual"), errors)
if item.get("visual") not in SPORTS_VISUALS:
errors.append(f"sections.sports.items[{index}].visual must be one of {sorted(SPORTS_VISUALS)}")
market = _mapping(sections.get("market"), "sections.market", errors)
_required_string(market.get("title"), "sections.market.title", errors)
market_items = _array(market.get("items"), "sections.market.items", errors, minimum=1, maximum=6)
for index, raw in enumerate(market_items):
path = f"sections.market.items[{index}]"
item = _mapping(raw, path, errors)
_strings(item, path, ("label", "value"), errors)
if item.get("direction") not in {"up", "down", "flat"}:
errors.append(f"{path}.direction must be up, down, or flat")
media = _mapping(data.get("media"), "media", errors)
watch = _mapping(media.get("watch"), "media.watch", errors)
_strings(watch, "media.watch", ("eyebrow", "title", "moreLabel"), errors)
_href(watch.get("moreHref"), "media.watch.moreHref", errors)
videos = _array(watch.get("videos"), "media.watch.videos", errors, minimum=1, maximum=6)
seen_videos: set[str] = set()
for index, raw in enumerate(videos):
path = f"media.watch.videos[{index}]"
item = _mapping(raw, path, errors)
_unique_id(item, path, seen_videos, errors)
_strings(item, path, ("duration", "kicker", "title", "summary", "visual"), errors)
if item.get("visual") not in VIDEO_VISUALS:
errors.append(f"{path}.visual must be one of {sorted(VIDEO_VISUALS)}")
modal = _mapping(watch.get("modal"), "media.watch.modal", errors)
_strings(modal, "media.watch.modal", ("title", "streamSubtitle", "captionsOn", "captionsOff"), errors)
edition = _mapping(media.get("edition"), "media.edition", errors)
_strings(edition, "media.edition", ("eyebrow", "title", "summary", "openLabel", "subscribeLabel", "modalTitle", "date"), errors)
_href(edition.get("subscribeHref"), "media.edition.subscribeHref", errors)
pages = _array(edition.get("pages"), "media.edition.pages", errors, minimum=2, maximum=8)
seen_pages: set[str] = set()
for index, raw in enumerate(pages):
path = f"media.edition.pages[{index}]"
item = _mapping(raw, path, errors)
_unique_id(item, path, seen_pages, errors)
_strings(item, path, ("label", "headline", "text"), errors)
newsletter = _mapping(media.get("newsletter"), "media.newsletter", errors)
_strings(newsletter, "media.newsletter", ("eyebrow", "title", "text", "placeholder", "button", "successPrefix"), errors)
footer = _mapping(data.get("footer"), "footer", errors)
_strings(footer, "footer", ("description", "copyright", "legal"), errors)
footer_columns = _array(footer.get("columns"), "footer.columns", errors, minimum=1, maximum=5)
seen_footer: set[str] = set()
footer_links = 0
for index, raw in enumerate(footer_columns):
path = f"footer.columns[{index}]"
item = _mapping(raw, path, errors)
_unique_id(item, path, seen_footer, errors)
_required_string(item.get("title"), f"{path}.title", errors)
footer_links += len(_links(item.get("links"), f"{path}.links", errors, minimum=1, maximum=8))
_validate_remote_media_tree(data, "$", errors)
_validate_no_remote_or_markup(data, "$", errors)
_validate_chinese_reader_copy(data, "$", errors)
if errors:
raise DataValidationError("\n".join(f"- {error}" for error in errors))
return {
"weather_locations": len(weather),
"navigation_links": len(utility_left) + len(utility_right) + len(primary),
"lead_stories": 1 + len(side_stories),
"feeds": len(feeds),
"feed_items": feed_items,
"pulse_items": len(pulse_items),
"region_tabs": len(region_tabs),
"region_stories": region_stories,
"opinion_columns": len(columns),
"business_stories": len(business_items),
"sports_stories": 1 + len(sports_items),
"market_items": len(market_items),
"videos": len(videos),
"edition_pages": len(pages),
"footer_columns": len(footer_columns),
"footer_links": 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("__MANILA_TIMES_PAGE_DATA__") != 1:
raise DataValidationError("template must contain one __MANILA_TIMES_PAGE_DATA__ marker")
if template.count("__MANILA_TIMES_PAGE_RUNTIME__") != 1:
raise DataValidationError("template must contain one __MANILA_TIMES_PAGE_RUNTIME__ marker")
rendered = template.replace("__MANILA_TIMES_PAGE_DATA__", data_text).replace("__MANILA_TIMES_PAGE_RUNTIME__", runtime)
if "__MANILA_TIMES_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 Manila Times-style 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 validated JSON 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())