sync update from LAN repo (source master @ ca48c4ec)

This commit is contained in:
gozeros committed 2026-11-05 10:53:54 +08:00
1 parent 8bc8b0e082
commit ea9dcff9c0
873 files changed
+107866 -14011

No files matched your search

@@ -0,0 +1,84 @@
---
name: yahoo-japan-page-generator
description: 生成或绘制中文 Yahoo! JAPAN 风格日本综合门户的可交付单文件 HTML;仅在用户明确要求制作雅虎日本、Yahoo Japan 网页或点名本技能时使用。先把材料或检索结果整理成读者文案全中文的十模块 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,图不合适时由用户在成品页面悬浮上传替换。
## 触发边界
- 用户明确说“生成/画/制作雅虎日本、Yahoo! JAPAN、Yahoo Japan 网页、日本综合门户”或点名 `yahoo-japan-page-generator` 时使用。
- 仅讨论雅虎日本、总结日本新闻或普通文本中出现 Yahoo 时不要使用。
- 这是雅虎日本风格的概念门户,不改用新闻机构模板或通用页面模板,也不得声称是官方网站。
## 极速工作流(默认)
页面结构已经固定。完成必要检索或材料整理后,模型只写一份小型规格 JSON;未写字段继续使用模板默认数据与示例视觉,脚本在一次进程内合并、校验并渲染。
1. 用 `write_file` 创建 `/mnt/user-data/outputs/yahoo-japan-page-spec.json`。直接写模块对象会递归合并;修改现有数组项优先用 `$set`:
```json
{"site":{"pageTitle":"Yahoo! JAPAN · 中文专题"},"$set":{"news.feature.kicker":"今日关注","news.feature.title":"中文头条","news.feature.summary":"中文摘要"}}
```
2. 只执行一次 `python /mnt/skills/public/yahoo-japan-page-generator/scripts/fast_page.py --spec /mnt/user-data/outputs/yahoo-japan-page-spec.json --output-dir /mnt/user-data/outputs`。
3. stdout 为 `status: ok` 后立即用 `present_files` 交付完整 JSON 与 HTML,最终只回复一句完成说明。
规格只允许本技能十个模块和 `$set`;路径必须指向默认 JSON 的已存在字段。品牌 `Yahoo! JAPAN` 可保留,其余读者可见内容必须是简体中文。未提供媒体直链时保留模板示例视觉。禁止读取默认数据、契约、模板、运行时或脚本源码,禁止 `--help`、独立 `init/validate/render`、生成后打补丁、临时脚本和冗长过程说明。规格报错时只修正一次并重跑。只有用户明确要求改变模块结构或批量重建完整数组时,才使用下面的完整工作流。
## 完整工作流(仅限结构改造)
1. 读取当前会话材料、上传附件和已有产物,确定品牌、搜索、服务、新闻、账户、天气、交通与市场、购物、体育热榜和页脚内容。
2. 用户要求当前新闻、实时天气、真实行情或近期事件时,必须先检索可靠来源再填 JSON;用户明确说不要检索时不得联网。日文或英文资料必须先准确翻译成简体中文。没有材料时使用中文中性演示内容,并在页脚明确说明不是官方网站。
3. 初始化完整 JSON:
```text
python /mnt/skills/public/yahoo-japan-page-generator/scripts/render_yahoo_japan_page.py init --output /mnt/user-data/outputs/yahoo-japan-page-data.json
```
4. 只修改 JSON。十个顶层模块必须全部保留:`site`、`search`、`services`、`news`、`account`、`weather`、`utilities`、`shopping`、`pulse`、`footer`。JSON 键名、`id`、`href`、`visual`、`theme` 等技术值保持契约格式;品牌 `Yahoo! JAPAN` 可以保留,其余读者可见文案必须使用简体中文,`site.language` 固定为 `zh-CN`。字段不确定时读取 [references/data-schema.md](references/data-schema.md)。
5. 校验 JSON:
```text
python /mnt/skills/public/yahoo-japan-page-generator/scripts/render_yahoo_japan_page.py validate --input /mnt/user-data/outputs/yahoo-japan-page-data.json
```
6. 确定性渲染:
```text
python /mnt/skills/public/yahoo-japan-page-generator/scripts/render_yahoo_japan_page.py render --input /mnt/user-data/outputs/yahoo-japan-page-data.json --output /mnt/user-data/outputs/yahoo-japan-page.html
```
7. 检查 stdout 的 `status` 为 `ok`、HTML 存在且占位符已经消失,再用 `present_files` 同时交付 HTML 与源 JSON。不要在聊天中粘贴完整 HTML。
## 内容映射
- 品牌、日期、工具链接、顶部操作、公告和明暗模式文案放入 `site`。
- 搜索类型、热门词和搜索反馈放入 `search`;常用与扩展服务放入 `services`。
- 分类新闻、主专题和推荐内容放入 `news`;登录卡片与演示登录弹窗放入 `account`。
- 城市天气与灾害入口放入 `weather`;路线查询和市场行情放入 `utilities`。
- 商品卡片放入 `shopping`;体育比分和实时热榜放入 `pulse`;抽屉与页脚放入 `footer`。
- `visual` 继续作为内置后备;具有视觉的对象可增加受校验的 `media`(`image`、`video`、`webpage`)替换当前视觉。所有文本由模板转义,不得包含 HTML、脚本或直接 iframe。
## 重要约束
- 只编辑 JSON,不修改 `assets/yahoo-japan-template.html` 或 `assets/yahoo-japan-runtime.js`。
- 初始化与渲染默认拒绝覆盖已有文件;路径存在时换新文件名,不删除旧产物。
- 页面结构、样式和脚本完全自包含,不依赖新闻、天气、市场、购物或账户接口,也不依赖 CDN;仅当 JSON 明确提供受校验媒体 URL 时加载图片、视频或网页。
- 保留搜索优先、红蓝品牌、密集双栏门户、服务入口、分类新闻、天气、交通、行情、购物、体育和热榜交互。
- 除品牌 `Yahoo! JAPAN` 外,不得生成日文或英文读者文案;外文来源必须先翻译为自然、准确的简体中文。
- 浏览器缓存以初始 JSON 指纹隔离;沙箱禁止持久存储时必须继续使用内嵌 JSON 正常渲染。
@@ -0,0 +1,138 @@
{
"site": {
"brandPrimary": "Yahoo!",
"brandAccent": "JAPAN",
"tagline": "每天连接日本生活",
"pageTitle": "Yahoo! JAPAN 中文综合门户",
"description": "采用雅虎日本门户结构设计的中文概念页面,汇集搜索、新闻、天气、交通、市场、体育与购物信息。",
"language": "zh-CN",
"theme": "light",
"skipLabel": "跳转到主要内容",
"dateLabel": "2026年10月30日 星期五 · 日本",
"utilityLeft": [{"id":"start","label":"设为起始页","href":"#footer"},{"id":"kids","label":"儿童版","href":"#services"},{"id":"help","label":"帮助中心","href":"#footer"}],
"utilityRight": [{"id":"travel","label":"旅行","href":"#shopping"},{"id":"card","label":"信用卡","href":"#shopping"},{"id":"mail","label":"邮箱","href":"#account"},{"id":"shop","label":"购物","href":"#shopping"}],
"loginLabel": "登录",
"mailLabel": "邮箱",
"mailCount": "3封",
"menuLabel": "打开菜单",
"themeLabel": "切换明暗模式",
"themeDarkMessage": "已切换到深色模式。",
"themeLightMessage": "已切换到浅色模式。",
"notice": {"label":"通知","text":"关东甲信地区今晚可能出现强降雨,请及时查看天气与交通信息。","href":"#weather"}
},
"search": {
"title": "搜索",
"tabs": [{"id":"web","label":"网页"},{"id":"smart","label":"智能模式"},{"id":"image","label":"图片"},{"id":"video","label":"视频"},{"id":"qa","label":"问答"},{"id":"map","label":"地图"},{"id":"realtime","label":"实时"}],
"placeholderSuffix": "搜索",
"button": "搜索",
"hotLabel": "热门:",
"suggestions": ["红叶最佳观赏期","新干线运行信息","日本职业棒球决赛"],
"emptyMessage": "请输入搜索关键词。",
"resultPrefix": "已执行演示搜索,类型为",
"resultKeyword": "关键词"
},
"services": {
"title": "主要服务",
"allLabel": "服务总览",
"allHref": "#services",
"moreLabel": "展开更多",
"lessLabel": "收起服务",
"primary": [
{"id":"shopping","label":"购物","href":"#shopping","visual":"shopping"},{"id":"auction","label":"拍卖","href":"#shopping","visual":"auction"},{"id":"weather","label":"天气与灾害","href":"#weather","visual":"weather"},{"id":"news","label":"新闻","href":"#news","visual":"news"},{"id":"sports","label":"体育","href":"#sports","visual":"sports"},{"id":"finance","label":"财经","href":"#finance","visual":"finance"},{"id":"transit","label":"路线信息","href":"#transit","visual":"transit"},{"id":"property","label":"房产","href":"#services","visual":"property"},{"id":"car","label":"汽车","href":"#services","visual":"car"},{"id":"travel","label":"旅行","href":"#shopping","visual":"travel"}
],
"extra": [
{"id":"calendar","label":"日历","href":"#services","visual":"calendar"},{"id":"community","label":"生活问答","href":"#services","visual":"community"},{"id":"tax","label":"家乡税","href":"#services","visual":"tax"},{"id":"jobs","label":"招聘","href":"#services","visual":"jobs"},{"id":"books","label":"电子书","href":"#services","visual":"books"}
]
},
"news": {
"title": "新闻",
"updated": "10月30日 14:05更新",
"tabs": [
{"id":"top","label":"主要","items":[{"id":"network","tag":"快讯","title":"新的广域交通网络将在年内部分开通","time":"13:58","href":"#news","isNew":true},{"id":"wages","tag":"","title":"中小企业加薪支持方案正式公布","time":"13:44","href":"#news","isNew":false},{"id":"autumn","tag":"","title":"北陆山区进入红叶最佳观赏期","time":"13:21","href":"#news","isNew":false},{"id":"train","tag":"","title":"下一代新干线启动载客试运行","time":"12:52","href":"#news","isNew":false},{"id":"library","tag":"","title":"全国图书馆开展夜间开放试点","time":"12:18","href":"#news","isNew":false}]},
{"id":"domestic","label":"国内","items":[{"id":"disaster-app","tag":"","title":"区域防灾应用在十二座城市启动联动","time":"13:48","href":"#news","isNew":false},{"id":"ferry","tag":"","title":"连接濑户内岛屿的电动渡轮投入运营","time":"12:37","href":"#news","isNew":false},{"id":"heritage","tag":"","title":"秋季文化遗产特别开放活动启动","time":"11:15","href":"#news","isNew":false}]},
{"id":"economy","label":"经济","items":[{"id":"stocks","tag":"","title":"日经平均指数小幅上涨,出口板块表现稳健","time":"13:51","href":"#finance","isNew":false},{"id":"startup","tag":"","title":"面向地方初创企业的投资继续扩大","time":"12:29","href":"#finance","isNew":false}]},
{"id":"culture","label":"文娱","items":[{"id":"film","tag":"","title":"国际电影节将在全国八座城市同步举行","time":"13:20","href":"#news","isNew":false},{"id":"literature","tag":"","title":"青年作家文学奖公布入围作品","time":"12:14","href":"#news","isNew":false}]},
{"id":"sports","label":"体育","items":[{"id":"women-final","tag":"","title":"日本女队晋级亚洲赛事决赛","time":"13:46","href":"#sports","isNew":false},{"id":"draft","tag":"","title":"职业棒球新秀发表赛季目标","time":"12:01","href":"#sports","isNew":false}]},
{"id":"world","label":"国际","items":[{"id":"heat","tag":"","title":"亚洲主要城市发布联合高温应对宣言","time":"13:09","href":"#news","isNew":false},{"id":"ocean","tag":"","title":"世界遗产会议设立海洋保护基金","time":"11:38","href":"#news","isNew":false}]}
],
"feature": {"kicker":"图解专题","title":"新交通枢纽实现铁路、巴士与渡轮一票换乘","summary":"一张图了解新的出行方式将怎样改变城市生活。","visual":"transit-map","href":"#news"},
"moreLabel": "查看更多",
"moreHref": "#news",
"topicsLabel": "专题列表",
"topicsHref": "#news",
"recommendTitle": "推荐阅读",
"refreshLabel": "换一批",
"refreshMessage": "推荐内容已经更新。",
"recommendations": [{"id":"trail","title":"沿着古道寻找秋日小旅行","category":"旅行","visual":"trail"},{"id":"recipe","title":"用当季蔬菜制作十分钟料理","category":"生活","visual":"recipe"},{"id":"plaza","title":"车站再开发带来更多公共空间","category":"新闻专题","visual":"plaza"}]
},
"account": {
"title": "登录后使用更多服务",
"text": "在同一页面查看邮箱、日程和已收藏内容。",
"loginLabel": "登录",
"newIdLabel": "注册新账户",
"newIdHref": "#account",
"profileLabel": "账户信息",
"profileHref": "#footer",
"statuses": [{"id":"mail","label":"邮箱 3封","href":"#account","visual":"mail"},{"id":"points","label":"积分 240点","href":"#shopping","visual":"points"}],
"modalTitle": "Yahoo! JAPAN 登录",
"welcome": "欢迎回来",
"demoNote": "这是概念演示页面,输入内容不会保存或发送。",
"emailLabel": "电子邮箱",
"passwordLabel": "密码",
"submitLabel": "登录",
"resultMessage": "演示页面不会执行真实登录。",
"closeLabel": "关闭登录窗口"
},
"weather": {
"title": "今明天气",
"regionLabel": "选择地区",
"locations": [
{"id":"tokyo","city":"东京都港区","today":{"label":"今天 10月30日","high":"21°","low":"16°","summary":"雨转阴 · 降水概率90%"},"tomorrow":{"label":"明天 10月31日","high":"23°","low":"16°","summary":"多云 · 降水概率40%"}},
{"id":"osaka","city":"大阪市北区","today":{"label":"今天 10月30日","high":"24°","low":"17°","summary":"晴间多云 · 降水概率20%"},"tomorrow":{"label":"明天 10月31日","high":"25°","low":"18°","summary":"晴 · 降水概率10%"}},
{"id":"fukuoka","city":"福冈市中央区","today":{"label":"今天 10月30日","high":"23°","low":"18°","summary":"多云 · 降水概率30%"},"tomorrow":{"label":"明天 10月31日","high":"24°","low":"17°","summary":"晴间多云 · 降水概率20%"}}
],
"updatedMessage": "天气信息已更新。",
"links": [{"id":"radar","label":"降雨雷达","message":"已打开降雨雷达演示。"},{"id":"alerts","label":"预警信息","message":"已打开气象预警演示。"},{"id":"typhoon","label":"台风信息","message":"已打开台风信息演示。"}]
},
"utilities": {
"transit": {"title":"运行信息与路线查询","detailLabel":"详情","detailHref":"#transit","status":"首都圈主要线路当前正常运行。","fromLabel":"出发站","toLabel":"到达站","buttonLabel":"查询路线","emptyMessage":"输入车站名称即可查询路线。","resultPrefix":"演示路线","resultDetail":"预计28分钟,换乘1次。"},
"finance": {"title":"财经行情","moreLabel":"市场总览","moreHref":"#finance","updated":"10月30日 14:00","previousPrefix":"上一交易日收盘","markets":[{"id":"nikkei","label":"日经平均指数","value":"39,842.16","change":"+126.42 ▲0.32%","previous":"39,715.74"},{"id":"usd","label":"美元兑日元","value":"149.28","change":"+0.18 ▲0.12%","previous":"149.10"},{"id":"topix","label":"东证指数","value":"2,784.51","change":"+8.32 ▲0.30%","previous":"2,776.19"}]}
},
"shopping": {
"title": "购物推荐",
"moreLabel": "查看更多",
"moreHref": "#shopping",
"saveLabel": "加入收藏",
"removeLabel": "取消收藏",
"savedMessage": "商品已加入收藏。",
"removedMessage": "商品已移出收藏。",
"products": [{"id":"backpack","title":"轻量日用背包 18升","price":"¥4,980","visual":"backpack"},{"id":"clock","title":"静音指针时钟","price":"¥2,640","visual":"clock"},{"id":"umbrella","title":"折叠晴雨两用伞","price":"¥3,280","visual":"umbrella"},{"id":"mill","title":"木制手摇咖啡磨","price":"¥6,500","visual":"mill"},{"id":"purifier","title":"桌面空气净化器","price":"¥8,800","visual":"purifier"}]
},
"pulse": {
"sportsTitle": "体育快讯",
"sportsMoreLabel": "体育频道",
"sportsMoreHref": "#sports",
"sportsTabs": [
{"id":"baseball","label":"职业棒球","games":[{"id":"game-one","home":"福冈雄鹰队","homeNote":"18:00开始","score":"–","away":"横滨星队","awayNote":"东京巨蛋"},{"id":"game-two","home":"大阪猛牛队","homeNote":"比赛结束","score":"4 – 2","away":"千叶海洋队","awayNote":"大阪巨蛋"}]},
{"id":"football","label":"职业足球","games":[{"id":"game-three","home":"东京联队","homeNote":"下半场32分钟","score":"2 – 1","away":"大阪蓝队","awayNote":"国立竞技场"}]},
{"id":"volleyball","label":"排球","games":[{"id":"game-four","home":"日本队","homeNote":"比赛结束","score":"3 – 1","away":"菲律宾队","awayNote":"亚洲锦标赛"}]}
],
"trendsTitle": "实时热榜",
"refreshLabel": "14:00更新",
"refreshMessage": "实时热榜已经更新。",
"trendTabs": [
{"id":"rising","label":"热度上升","items":[{"id":"trend-one","rank":"1","title":"新干线试运行","meta":"热度4.2万","href":"#news"},{"id":"trend-two","rank":"2","title":"秋雨锋面","meta":"热度3.1万","href":"#weather"},{"id":"trend-three","rank":"3","title":"日本职业棒球决赛","meta":"热度2.5万","href":"#sports"}]},
{"id":"news","label":"新闻","items":[{"id":"trend-four","rank":"1","title":"广域交通网络","meta":"快讯","href":"#news"},{"id":"trend-five","rank":"2","title":"日经平均指数","meta":"经济","href":"#finance"}]},
{"id":"culture","label":"文娱","items":[{"id":"trend-six","rank":"1","title":"国际电影节","meta":"电影","href":"#news"},{"id":"trend-seven","rank":"2","title":"秋季新剧","meta":"电视","href":"#news"}]}
]
},
"footer": {
"drawerTitle": "日本生活服务",
"drawerText": "集中查看搜索、新闻、天气、交通、购物和体育内容。",
"drawerLinks": [{"id":"services","label":"服务","href":"#services"},{"id":"news","label":"新闻","href":"#news"},{"id":"weather","label":"天气与灾害","href":"#weather"},{"id":"transit","label":"路线信息","href":"#transit"},{"id":"finance","label":"财经","href":"#finance"},{"id":"sports","label":"体育","href":"#sports"},{"id":"shopping","label":"购物","href":"#shopping"},{"id":"help","label":"帮助","href":"#footer"}],
"links": [{"id":"company","label":"公司信息","href":"#footer"},{"id":"terms","label":"使用条款","href":"#footer"},{"id":"privacy","label":"隐私政策","href":"#footer"},{"id":"ads","label":"广告合作","href":"#footer"},{"id":"contact","label":"联系我们","href":"#footer"},{"id":"accessibility","label":"无障碍说明","href":"#footer"},{"id":"all","label":"服务总览","href":"#services"}],
"copyright": "© 2026 Yahoo! JAPAN 风格中文概念门户",
"legal": "本页面仅用于界面演示,不是 Yahoo! JAPAN 官方网站,也不提供真实账户、交易或搜索服务。",
"backTopLabel": "返回页面顶部"
}
}
@@ -0,0 +1,297 @@
(() => {
"use strict";
const MODULES = ["site", "search", "services", "news", "account", "weather", "utilities", "shopping", "pulse", "footer"];
const MODULE_META = {site:"站点信息",search:"门户搜索",services:"主要服务",news:"新闻推荐",account:"账户登录",weather:"天气信息",utilities:"交通与行情",shopping:"购物推荐",pulse:"体育与热榜",footer:"抽屉与页脚"};
const node = (id) => document.getElementById(id);
const clone = (value) => JSON.parse(JSON.stringify(value));
const initialText = node("yahooJapanPageData").textContent;
const initialData = JSON.parse(initialText);
const fingerprint = (() => { let hash=2166136261; for(let i=0;i<initialText.length;i+=1){hash^=initialText.charCodeAt(i);hash=Math.imul(hash,16777619)} return (hash>>>0).toString(36) })();
const dataKey = "yahoo-japan-page-data-v1:" + fingerprint;
const themeKey = "yahoo-japan-page-theme-v1:" + fingerprint;
const readStorage = (key) => { try{return window.localStorage.getItem(key)}catch(_error){return null} };
const writeStorage = (key,value) => { try{window.localStorage.setItem(key,value);return true}catch(_error){return false} };
const removeStorage = (key) => { try{window.localStorage.removeItem(key)}catch(_error){/* optional storage */} };
let data=clone(initialData);
try{const saved=readStorage(dataKey);if(saved)data=JSON.parse(saved)}catch(_error){data=clone(initialData)}
let activeSearch="web",activeNews="top",activeWeather="tokyo",activeMarket="nikkei",activeSport="baseball",activeTrend="rising",currentModule=MODULES[0],toastTimer=0;
const esc = (value) => String(value??"").replace(/[&<>'"]/g,(char)=>({"&":"&amp;","<":"&lt;",">":"&gt;","'":"&#39;",'"':"&quot;"})[char]);
const safeHref = (value) => typeof value==="string"&&value.startsWith("#")?value:"#main";
const safeRemoteUrl=(value,kind="link")=>{const source=String(value||"").trim();if(!source)return"";const lower=source.toLowerCase();if(kind==="image"&&lower.startsWith("data:image/"))return source;if(kind==="video"&&lower.startsWith("data:video/"))return source;try{const url=new URL(source);return["http:","https:"].includes(url.protocol)?url.href:""}catch(_error){return""}};
const setText = (id,value) => {const el=node(id);if(el)el.textContent=value??""};
const setLink = (id,label,href) => {const el=node(id);if(el){el.textContent=label??"";el.href=safeHref(href)}};
const links = (items) => (items||[]).map((item)=>`<a href="${esc(safeHref(item.href))}">${esc(item.label)}</a>`).join("");
function toast(message){const el=node("toast");el.textContent=message;el.classList.add("show");clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove("show"),2200)}
function openLayer(id){node(id).classList.add("open");document.body.classList.add("locked")}
function closeLayer(id){node(id).classList.remove("open");if(!document.querySelector(".drawer.open,.modal.open,.settings-overlay.open"))document.body.classList.remove("locked")}
function renderSite(){
document.documentElement.lang=data.site.language;document.title=data.site.pageTitle;document.querySelector('meta[name="description"]').content=data.site.description;
setText("skipLink",data.site.skipLabel);setText("brandPrimary",data.site.brandPrimary);setText("brandAccent",data.site.brandAccent);setText("tagline",data.site.tagline);setText("drawerBrand",`${data.site.brandPrimary} ${data.site.brandAccent}`);
node("utilityLeft").innerHTML=`<span>${esc(data.site.dateLabel)}</span>${links(data.site.utilityLeft)}`;node("utilityRight").innerHTML=links(data.site.utilityRight);
setText("headerLogin",data.site.loginLabel);setText("mailLabel",data.site.mailLabel);setText("mailCount",data.site.mailCount);node("menuOpen").setAttribute("aria-label",data.site.menuLabel);node("themeToggle").setAttribute("aria-label",data.site.themeLabel);
setText("noticeLabel",data.site.notice.label);setLink("noticeLink",data.site.notice.text,data.site.notice.href);
const preferred=readStorage(themeKey);document.body.classList.toggle("dark",preferred==="dark"||(!preferred&&data.site.theme==="dark"));
}
function renderSearch(){
setText("searchTitle",data.search.title);if(!data.search.tabs.some((item)=>item.id===activeSearch))activeSearch=data.search.tabs[0]?.id;node("searchTabs").innerHTML=data.search.tabs.map((item)=>`<button class="${item.id===activeSearch?"active":""}" data-search="${esc(item.id)}">${esc(item.label)}</button>`).join("");const tab=data.search.tabs.find((item)=>item.id===activeSearch)||data.search.tabs[0];node("searchInput").placeholder=`${tab.label}${data.search.placeholderSuffix}`;setText("searchButton",data.search.button);node("suggestions").innerHTML=`<span>${esc(data.search.hotLabel)}</span>${data.search.suggestions.map((item)=>`<button data-suggestion="${esc(item)}">${esc(item)}</button>`).join("")}`;
}
document.head.insertAdjacentHTML("beforeend",'<style data-external-media>.external-media{position:relative;overflow:hidden}.external-media::before,.external-media::after{display:none!important}.external-media>img,.external-media>video,.external-media>iframe{position:relative;z-index:1;width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}.external-media>iframe{object-fit:initial}.external-open{position:absolute;right:10px;bottom:10px;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 art=(item,className,mediaPath="")=>{const mediaMarkup=externalMedia(item.media,item.title),path=mediaPath?` data-media-path="${esc(mediaPath)}"`:"";return `<div class="${className}${mediaMarkup?" external-media":""}" data-visual="${esc(item.visual)}"${path} aria-hidden="${mediaMarkup?"false":"true"}">${mediaMarkup}</div>`};
const serviceCard=(item)=>`<a class="service" href="${esc(safeHref(item.href))}"><span class="service-icon" data-visual="${esc(item.visual)}">${esc(item.label.slice(0,1))}</span><span>${esc(item.label)}</span></a>`;
function renderServices(){setText("servicesTitle",data.services.title);setLink("servicesAll",data.services.allLabel,data.services.allHref);node("servicePrimary").innerHTML=data.services.primary.map(serviceCard).join("");node("serviceExtra").innerHTML=data.services.extra.map(serviceCard).join("");const open=node("serviceExtra").classList.contains("open");setText("serviceMore",open?data.services.lessLabel:data.services.moreLabel);node("serviceMore").setAttribute("aria-expanded",String(open))}
function renderNews(){
setText("newsTitle",data.news.title);setText("newsUpdated",data.news.updated);if(!data.news.tabs.some((item)=>item.id===activeNews))activeNews=data.news.tabs[0]?.id;node("newsTabs").innerHTML=data.news.tabs.map((tab)=>`<button class="${tab.id===activeNews?"active":""}" data-news="${esc(tab.id)}">${esc(tab.label)}</button>`).join("");node("newsLists").innerHTML=data.news.tabs.map((tab)=>`<div class="news-list${tab.id===activeNews?" active":""}" data-news-panel="${esc(tab.id)}">${tab.items.map((item)=>`<div class="news-item">${item.tag?`<span class="tag">${esc(item.tag)}</span>`:""}<a href="${esc(safeHref(item.href))}">${esc(item.title)}</a>${item.isNew?'<span class="new">新</span>':""}<time>${esc(item.time)}</time></div>`).join("")}</div>`).join("");
const feature=data.news.feature;node("newsFeature").innerHTML=`${art(feature,"feature-art","news.feature")}<div><span class="tag">${esc(feature.kicker)}</span><h3><a href="${esc(safeHref(feature.href))}">${esc(feature.title)}</a></h3><p>${esc(feature.summary)}</p></div>`;setLink("newsMore",data.news.moreLabel,data.news.moreHref);setLink("newsTopics",data.news.topicsLabel,data.news.topicsHref);setText("recommendTitle",data.news.recommendTitle);setText("recRefresh",data.news.refreshLabel);node("recommendGrid").innerHTML=data.news.recommendations.map((item,index)=>`<article class="recommend">${art(item,"rec-art",`news.recommendations.${index}`)}<div class="rec-copy"><h3>${esc(item.title)}</h3><span>${esc(item.category)}</span></div></article>`).join("");
}
function renderAccount(){setText("accountTitle",data.account.title);setText("accountText",data.account.text);setText("accountLogin",data.account.loginLabel);setLink("accountNew",data.account.newIdLabel,data.account.newIdHref);setLink("accountProfile",data.account.profileLabel,data.account.profileHref);node("accountStatuses").innerHTML=data.account.statuses.map((item)=>`<a class="status-link" href="${esc(safeHref(item.href))}">${esc(item.label)}</a>`).join("");setText("loginModalTitle",data.account.modalTitle);setText("loginWelcome",data.account.welcome);setText("loginNote",data.account.demoNote);setText("emailLabel",data.account.emailLabel);setText("passwordLabel",data.account.passwordLabel);setText("loginSubmit",data.account.submitLabel);node("loginModal").querySelector(".close").setAttribute("aria-label",data.account.closeLabel)}
function renderWeather(){setText("weatherTitle",data.weather.title);node("weatherSelect").setAttribute("aria-label",data.weather.regionLabel);if(!data.weather.locations.some((item)=>item.id===activeWeather))activeWeather=data.weather.locations[0]?.id;node("weatherSelect").innerHTML=data.weather.locations.map((item)=>`<option value="${esc(item.id)}"${item.id===activeWeather?" selected":""}>${esc(item.city)}</option>`).join("");const item=data.weather.locations.find((value)=>value.id===activeWeather)||data.weather.locations[0];setText("todayLabel",item.today.label);setText("todayHigh",item.today.high);setText("todayLow",item.today.low);setText("todaySummary",item.today.summary);setText("tomorrowLabel",item.tomorrow.label);setText("tomorrowHigh",item.tomorrow.high);setText("tomorrowLow",item.tomorrow.low);setText("tomorrowSummary",item.tomorrow.summary);node("weatherLinks").innerHTML=data.weather.links.map((link)=>`<button data-weather-link="${esc(link.id)}">${esc(link.label)}</button>`).join("")}
function renderUtilities(){const transit=data.utilities.transit;setText("transitTitle",transit.title);setLink("transitDetail",transit.detailLabel,transit.detailHref);setText("transitStatus",transit.status);node("fromStation").placeholder=transit.fromLabel;node("fromStation").setAttribute("aria-label",transit.fromLabel);node("toStation").placeholder=transit.toLabel;node("toStation").setAttribute("aria-label",transit.toLabel);setText("routeButton","→");node("routeButton").setAttribute("aria-label",transit.buttonLabel);if(!node("routeResult").textContent)setText("routeResult",transit.emptyMessage);const finance=data.utilities.finance;setText("financeTitle",finance.title);setLink("financeMore",finance.moreLabel,finance.moreHref);if(!finance.markets.some((item)=>item.id===activeMarket))activeMarket=finance.markets[0]?.id;node("marketTabs").innerHTML=finance.markets.map((item)=>`<button class="${item.id===activeMarket?"active":""}" data-market="${esc(item.id)}">${esc(item.label)}</button>`).join("");const market=finance.markets.find((item)=>item.id===activeMarket)||finance.markets[0];setText("marketValue",market.value);setText("marketChange",market.change);setText("marketUpdated",finance.updated);setText("marketPrevious",`${finance.previousPrefix} ${market.previous}`)}
function renderShopping(){setText("shoppingTitle",data.shopping.title);setLink("shoppingMore",data.shopping.moreLabel,data.shopping.moreHref);node("productGrid").innerHTML=data.shopping.products.map((item,index)=>`<article class="product"><button class="heart" data-product="${esc(item.id)}" aria-label="${esc(data.shopping.saveLabel)}">♡</button>${art(item,"product-art",`shopping.products.${index}`)}<div class="product-copy"><h3>${esc(item.title)}</h3><strong>${esc(item.price)}</strong></div></article>`).join("")}
function renderPulse(){setText("sportsTitle",data.pulse.sportsTitle);setLink("sportsMore",data.pulse.sportsMoreLabel,data.pulse.sportsMoreHref);if(!data.pulse.sportsTabs.some((item)=>item.id===activeSport))activeSport=data.pulse.sportsTabs[0]?.id;node("sportsTabs").innerHTML=data.pulse.sportsTabs.map((tab)=>`<button class="${tab.id===activeSport?"active":""}" data-sport="${esc(tab.id)}">${esc(tab.label)}</button>`).join("");node("scorePanels").innerHTML=data.pulse.sportsTabs.map((tab)=>`<div class="score-panel${tab.id===activeSport?" active":""}" data-sport-panel="${esc(tab.id)}">${tab.games.map((game)=>`<div class="game"><div class="team">${esc(game.home)}<time>${esc(game.homeNote)}</time></div><div class="score">${esc(game.score)}</div><div class="team">${esc(game.away)}<time>${esc(game.awayNote)}</time></div></div>`).join("")}</div>`).join("");setText("trendsTitle",data.pulse.trendsTitle);setText("trendRefresh",data.pulse.refreshLabel);if(!data.pulse.trendTabs.some((item)=>item.id===activeTrend))activeTrend=data.pulse.trendTabs[0]?.id;node("trendTabs").innerHTML=data.pulse.trendTabs.map((tab)=>`<button class="${tab.id===activeTrend?"active":""}" data-trend="${esc(tab.id)}">${esc(tab.label)}</button>`).join("");node("trendPanels").innerHTML=data.pulse.trendTabs.map((tab)=>`<div class="trend-panel${tab.id===activeTrend?" active":""}" data-trend-panel="${esc(tab.id)}">${tab.items.map((item)=>`<div class="trend-item"><b>${esc(item.rank)}</b><a href="${esc(safeHref(item.href))}">${esc(item.title)}</a><span>${esc(item.meta)}</span></div>`).join("")}</div>`).join("")}
function renderFooter(){setText("drawerTitle",data.footer.drawerTitle);setText("drawerText",data.footer.drawerText);node("drawerNav").innerHTML=links(data.footer.drawerLinks);node("footerLinks").innerHTML=links(data.footer.links);setText("copyright",data.footer.copyright);setText("legal",data.footer.legal);node("backTop").setAttribute("aria-label",data.footer.backTopLabel)}
function renderAll(){renderSite();renderSearch();renderServices();renderNews();renderAccount();renderWeather();renderUtilities();renderShopping();renderPulse();renderFooter()}
function validateClient(candidate){
if(!candidate||typeof candidate!=="object"||Array.isArray(candidate))throw new Error("顶层 JSON 必须是对象。");const keys=Object.keys(candidate),missing=MODULES.filter((name)=>!keys.includes(name)),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 raw=JSON.stringify(candidate).toLowerCase();if(["<script","<iframe","javascript:"].some((token)=>raw.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 technical=new Set(["id","href","visual","theme","language","brandPrimary","brandAccent","value","price","score","change","previous","rank","type","mediaUrl","posterUrl","pageUrl"]);const walk=(value,key="")=>{if(Array.isArray(value))value.forEach((item)=>walk(item,key));else if(value&&typeof value==="object")Object.entries(value).forEach(([child,item])=>walk(item,child));else if(typeof value==="string"&&!technical.has(key)&&!key.toLowerCase().endsWith("id")&&!key.toLowerCase().endsWith("href")&&!key.toLowerCase().endsWith("url")&&(/[\u3040-\u30ff]/.test(value)||(/[A-Za-z]/.test(value)&&!/[\u3400-\u9fff]/.test(value))))throw new Error("除品牌 Yahoo! JAPAN 外,所有读者可见文案必须使用简体中文。")};walk(candidate);return true;
}
function renderSettingsTabs(){node("moduleTabs").innerHTML=MODULES.map((name)=>`<button class="module-tab${name===currentModule?" active":""}" data-module="${name}">${MODULE_META[name]}</button>`).join("");showModule(currentModule)}
function showModule(name){currentModule=name;node("moduleTabs").querySelectorAll("button").forEach((button)=>button.classList.toggle("active",button.dataset.module===name));setText("editorModule",MODULE_META[name]);node("jsonEditor").value=JSON.stringify(data[name],null,2);setText("jsonValidity","JSON 有效")}
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}}
const setStatus=(message)=>setText("settingsStatus",message);
function applyEditor(){try{const candidate={...data,[currentModule]:parseEditor()};validateClient(candidate);data=candidate;writeStorage(dataKey,JSON.stringify(data));renderAll();renderSettingsTabs();setStatus("JSON 已应用并完成渲染。")}catch(error){setStatus(error.message);setText("jsonValidity","JSON 无效")}}
async function copyJson(){const candidate={...data,[currentModule]:parseEditor()};validateClient(candidate);const text=JSON.stringify(candidate,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()};validateClient(candidate);const blob=new Blob([JSON.stringify(candidate,null,2)+"\n"],{type:"application/json"}),url=URL.createObjectURL(blob),anchor=document.createElement("a");anchor.href=url;anchor.download="yahoo-japan-page-data.json";anchor.click();URL.revokeObjectURL(url);setStatus("JSON 下载文件已生成。")}
node("searchForm").addEventListener("submit",(event)=>{event.preventDefault();const raw=node("searchInput").value.trim(),tab=data.search.tabs.find((item)=>item.id===activeSearch)||data.search.tabs[0];setText("searchStatus",raw?`${data.search.resultPrefix}${tab.label},${data.search.resultKeyword}“${raw}”。`:data.search.emptyMessage)});
node("serviceMore").addEventListener("click",()=>{node("serviceExtra").classList.toggle("open");renderServices()});
node("weatherSelect").addEventListener("change",(event)=>{activeWeather=event.target.value;renderWeather();toast(data.weather.updatedMessage)});
node("routeForm").addEventListener("submit",(event)=>{event.preventDefault();const from=node("fromStation").value.trim(),to=node("toStation").value.trim();setText("routeResult",`${data.utilities.transit.resultPrefix}:${from} → ${to},${data.utilities.transit.resultDetail}`)});
node("loginForm").addEventListener("submit",(event)=>{event.preventDefault();setText("loginStatus",data.account.resultMessage)});
node("themeToggle").addEventListener("click",()=>{const on=document.body.classList.toggle("dark");writeStorage(themeKey,on?"dark":"light");toast(on?data.site.themeDarkMessage:data.site.themeLightMessage)});
node("menuOpen").addEventListener("click",()=>openLayer("drawer"));node("backTop").addEventListener("click",()=>scrollTo({top:0,behavior:"smooth"}));window.addEventListener("scroll",()=>node("backTop").classList.toggle("show",scrollY>500),{passive:true});
document.addEventListener("click",(event)=>{const close=event.target.closest("[data-close]");if(close){closeLayer(close.dataset.close);return}const login=event.target.closest("[data-login]");if(login){if(node("drawer").classList.contains("open"))closeLayer("drawer");openLayer("loginModal");return}const search=event.target.closest("[data-search]");if(search){activeSearch=search.dataset.search;renderSearch();return}const suggestion=event.target.closest("[data-suggestion]");if(suggestion){node("searchInput").value=suggestion.dataset.suggestion;node("searchInput").focus();return}const news=event.target.closest("[data-news]");if(news){activeNews=news.dataset.news;renderNews();return}const weather=event.target.closest("[data-weather-link]");if(weather){const item=data.weather.links.find((value)=>value.id===weather.dataset.weatherLink);if(item)toast(item.message);return}const market=event.target.closest("[data-market]");if(market){activeMarket=market.dataset.market;renderUtilities();return}const product=event.target.closest("[data-product]");if(product){const saved=product.classList.toggle("saved");product.textContent=saved?"♥":"♡";product.setAttribute("aria-label",saved?data.shopping.removeLabel:data.shopping.saveLabel);toast(saved?data.shopping.savedMessage:data.shopping.removedMessage);return}const sport=event.target.closest("[data-sport]");if(sport){activeSport=sport.dataset.sport;renderPulse();return}const trend=event.target.closest("[data-trend]");if(trend){activeTrend=trend.dataset.trend;renderPulse();return}const module=event.target.closest("[data-module]");if(module&&module.closest("#moduleTabs"))showModule(module.dataset.module)});
node("recRefresh").addEventListener("click",()=>{const first=data.news.recommendations.shift();data.news.recommendations.push(first);renderNews();toast(data.news.refreshMessage)});node("trendRefresh").addEventListener("click",()=>toast(data.pulse.refreshMessage));
["drawer","loginModal","settingsOverlay"].forEach((id)=>node(id).addEventListener("click",(event)=>{if(event.target===node(id))closeLayer(id)}));document.addEventListener("keydown",(event)=>{if(event.key==="Escape")["drawer","loginModal","settingsOverlay"].forEach((id)=>{if(node(id).classList.contains("open"))closeLayer(id)})});
node("openSettings").addEventListener("click",()=>{renderSettingsTabs();setStatus("");openLayer("settingsOverlay")});node("validateJson").addEventListener("click",()=>{try{const candidate={...data,[currentModule]:parseEditor()};validateClient(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);activeSearch="web";activeNews="top";activeWeather="tokyo";activeMarket="nikkei";activeSport="baseball";activeTrend="rising";currentModule=MODULES[0];renderAll();renderSettingsTabs();setStatus("已恢复内嵌初始 JSON。");});node("applyJson").addEventListener("click",applyEditor);
validateClient(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 = "[data-media-path],.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,58 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="description" content="中文日本综合门户概念页面">
<meta name="theme-color" content="#ffffff">
<title>Yahoo! JAPAN 中文综合门户</title>
<style>
:root{--red:#e60012;--red2:#b8000e;--blue:#315d9c;--blue2:#17447e;--ink:#202124;--muted:#66717d;--page:#f3f4f6;--card:#fff;--soft:#f7f8fa;--line:#d9dde3;--yellow:#f6b800;--green:#17855c;--max:1120px;--sans:-apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif;--ease:180ms ease}
*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:var(--page);color:var(--ink);font:14px/1.55 var(--sans)}body.dark{--page:#111820;--card:#1b242e;--soft:#232e3a;--ink:#f4f6f8;--muted:#acb7c1;--line:#3a4652}body.locked{overflow:hidden}a{color:inherit;text-decoration:none}button,input,select{font:inherit}button{border:0;background:none;color:inherit}button,a{cursor:pointer;touch-action:manipulation}:focus-visible{outline:3px solid var(--yellow);outline-offset:2px}.wrap{width:min(var(--max),calc(100% - 32px));margin:auto}.card{background:var(--card);border:1px solid var(--line)}.skip{position:fixed;z-index:400;left:12px;top:8px;background:#fff;color:#111;padding:9px 13px;font-weight:800;transform:translateY(-160%)}.skip:focus{transform:none}.settings-button{position:fixed;z-index:210;right:20px;top:20px;width:46px;height:46px;border-radius:50%;background:var(--blue2);color:#fff;font-size:19px;box-shadow:0 6px 20px #0004}.settings-button:hover{background:var(--red)}
.utility{background:var(--card);border-bottom:1px solid var(--line)}.utility-row{height:34px;display:flex;align-items:center;justify-content:space-between;font-size:11px;color:var(--muted)}.utility-links{display:flex;gap:18px}.utility a:hover{color:var(--red);text-decoration:underline}.header{background:var(--card)}.head-row{height:84px;display:flex;align-items:center;justify-content:space-between}.brand{display:flex;align-items:center;gap:10px}.brand-mark{width:50px;height:50px;border-radius:50%;position:relative;background:radial-gradient(circle at 50% 50%,#fff 0 25%,var(--red) 27% 45%,transparent 47%),conic-gradient(from 0deg,var(--yellow),var(--red),var(--yellow));box-shadow:inset 0 0 0 7px #fff}.brand-copy strong{display:block;font:900 31px/.9 Arial,sans-serif;letter-spacing:-.055em;color:var(--red)}.brand-copy strong span{color:var(--blue)}.brand-copy small{display:block;font-size:9px;letter-spacing:.16em;color:var(--muted);font-weight:800;margin-top:8px}.head-actions{display:flex;align-items:center;gap:8px}.head-link,.icon-btn{height:44px;display:flex;align-items:center;justify-content:center;border:1px solid var(--line);background:var(--card);font-size:12px;font-weight:700;color:var(--blue);padding:0 13px}.head-link:hover,.icon-btn:hover{background:var(--soft)}.icon-btn{width:44px;padding:0}.mail-badge{display:inline-grid;place-items:center;min-width:22px;height:18px;padding:0 4px;border-radius:9px;background:var(--red);color:#fff;font-size:9px;margin-left:5px}.mobile-menu{display:none}
.search-zone{background:var(--card);padding:3px 0 20px;border-bottom:1px solid var(--line)}.search-tabs{display:flex;overflow:auto;margin-left:7px}.search-tabs button{min-height:38px;padding:0 15px;color:var(--blue);font-size:12px;font-weight:700;white-space:nowrap}.search-tabs button.active{color:var(--red);border-bottom:3px solid var(--red)}.search-tabs button:hover{background:var(--soft)}.search-form{display:flex;height:52px;border:3px solid var(--red);background:#fff}.search-form input{flex:1;min-width:0;border:0;padding:0 15px;font-size:16px;color:#111;outline:0}.search-form button{width:112px;background:var(--red);color:#fff;font-size:15px;font-weight:900}.search-form button:hover{background:var(--red2)}.search-under{min-height:31px;display:flex;align-items:center;justify-content:space-between;margin-top:4px;color:var(--muted);font-size:11px}.suggestions{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.suggestions button{color:var(--blue);padding:3px}.search-status{color:var(--red);font-weight:700}.notice{background:#fff6cf;border-bottom:1px solid #e5d07c}.notice-row{min-height:39px;display:flex;align-items:center;gap:12px;font-size:12px}.notice-badge{background:var(--yellow);color:#111;padding:4px 8px;font-weight:800;font-size:10px}.notice a{color:var(--blue);font-weight:700}
main{padding:18px 0 46px}.portal-grid{display:grid;grid-template-columns:minmax(0,1fr) 325px;gap:16px}.left-col,.right-col{display:flex;flex-direction:column;gap:16px}.module-head{min-height:46px;display:flex;align-items:center;justify-content:space-between;padding:0 15px;border-bottom:2px solid var(--blue)}.module-head h2{font-size:16px;margin:0}.module-head a,.module-head button,.module-head span{color:var(--blue);font-size:11px;font-weight:700}.services-body{padding:14px}.service-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:6px}.service{min-height:79px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;border:1px solid transparent;transition:background var(--ease),border var(--ease)}.service:hover{background:var(--soft);border-color:var(--line)}.service-icon{width:38px;height:38px;border-radius:10px;background:#e8f0fb;color:var(--blue);display:grid;place-items:center;font-weight:900;font-size:15px}.service:nth-child(3n+2) .service-icon{background:#fff0f1;color:var(--red)}.service:nth-child(3n) .service-icon{background:#edf7e9;color:var(--green)}.service span:last-child{font-size:11px;font-weight:700}.extra-services{display:none;border-top:1px solid var(--line);margin-top:10px;padding-top:10px}.extra-services.open{display:grid}.service-more{width:100%;min-height:42px;color:var(--blue);font-size:11px;font-weight:700;border-top:1px solid var(--line);margin-top:8px}
.news-tabs,.sports-tabs,.trend-tabs{display:flex;border-bottom:1px solid var(--line);padding:0 10px;overflow:auto}.news-tabs button,.sports-tabs button,.trend-tabs button{min-height:42px;padding:0 13px;color:var(--blue);font-weight:700;white-space:nowrap}.news-tabs button.active,.sports-tabs button.active,.trend-tabs button.active{color:var(--red);border-bottom:3px solid var(--red)}.news-body{padding:14px;display:grid;grid-template-columns:minmax(0,1fr) 190px;gap:14px}.news-list{display:none}.news-list.active{display:block}.news-item{display:flex;align-items:flex-start;gap:7px;min-height:34px;padding:5px 0;border-bottom:1px dotted var(--line)}.news-item a{font-size:14px;font-weight:600;line-height:1.35}.news-item time{color:var(--muted);font-size:10px;white-space:nowrap;margin-left:auto}.tag{font-size:10px;color:var(--red);font-weight:800}.new{background:var(--red);color:#fff;font-size:8px;padding:1px 4px;border-radius:2px}.feature-art,.rec-art,.product-art{position:relative;overflow:hidden;background:linear-gradient(145deg,#b8cad8,#eef2f5)}.feature-art{height:118px}.feature-art:before{content:"";position:absolute;left:16%;right:10%;bottom:15%;height:36%;background:linear-gradient(160deg,#fff 0 45%,#315d7d 46% 58%,#e8bd42 59%);clip-path:polygon(0 100%,20% 0,74% 0,100% 100%)}.news-feature h3{font-size:13px;line-height:1.35;margin:8px 0 0}.news-feature p{font-size:10px;color:var(--muted);margin:5px 0}.news-footer{border-top:1px solid var(--line);padding:9px 14px;display:flex;justify-content:flex-end;gap:15px;color:var(--blue);font-size:11px}.recommend-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:11px;padding:14px}.recommend{border:1px solid var(--line)}.rec-art{height:100px}.rec-art[data-visual="trail"]{background:linear-gradient(140deg,#b7cbaa 0 50%,#5a7759 51%)}.rec-art[data-visual="recipe"]{background:radial-gradient(circle,#d8754e 0 35%,#ead9b9 36%)}.rec-art[data-visual="plaza"]{background:linear-gradient(90deg,#b9cddd 0 30%,#315d83 31% 35%,#eaf0f4 36% 65%,#315d83 66% 70%,#b9cddd 71%)}.rec-copy{padding:10px}.rec-copy h3{font-size:12px;line-height:1.4;margin:0}.rec-copy span{font-size:9px;color:var(--muted)}
.login{padding:17px}.login h2{font-size:16px;margin:0 0 7px}.login p{font-size:11px;color:var(--muted)}.btn{min-height:44px;padding:0 17px;background:var(--red);color:#fff;font-weight:800}.login .btn{width:100%}.login-links{display:flex;justify-content:space-between;color:var(--blue);font-size:10px;margin-top:10px}.status-row{display:grid;grid-template-columns:1fr 1fr;border-top:1px solid var(--line);margin-top:14px}.status-link{padding:11px 7px 0;color:var(--blue);font-size:11px}.weather-select{border:0;background:transparent;color:var(--blue);font-size:11px;font-weight:700;max-width:150px}.weather-body,.transit-body,.finance-body{padding:14px}.weather-main{display:grid;grid-template-columns:1fr 1fr;gap:10px}.day-weather{border-right:1px solid var(--line);padding-right:10px}.day-weather:last-child{border:0;padding-right:0}.weather-label{font-size:11px;font-weight:700}.weather-visual{display:flex;align-items:center;justify-content:space-between;margin:8px 0}.sun-cloud{width:48px;height:34px;position:relative}.sun-cloud:before{content:"";position:absolute;width:24px;height:24px;border-radius:50%;background:var(--yellow);left:0;top:0}.sun-cloud:after{content:"";position:absolute;width:36px;height:18px;border-radius:18px;background:#c7d5df;right:0;bottom:0}.temp{font-size:20px;font-weight:800}.high{color:var(--red)}.low{color:var(--blue)}.weather-meta{font-size:9px;color:var(--muted)}.weather-links{display:flex;gap:11px;border-top:1px solid var(--line);padding-top:10px;margin-top:12px;color:var(--blue);font-size:10px;flex-wrap:wrap}.transit-status{padding:9px;background:#eaf7ef;color:#146b4b;font-size:11px;font-weight:700}.route-form{display:grid;grid-template-columns:1fr auto 1fr;gap:6px;margin-top:11px}.route-form input{height:40px;min-width:0;border:1px solid var(--line);padding:0 8px;background:var(--card);color:var(--ink)}.route-form button{height:40px;background:var(--blue);color:#fff;padding:0 12px}.route-result{font-size:10px;color:var(--muted);min-height:18px;margin-top:8px}.market-tabs{display:flex;gap:5px;overflow:auto}.market-tabs button{min-height:38px;padding:0 10px;background:var(--soft);color:var(--blue);font-size:10px;font-weight:700;white-space:nowrap}.market-tabs button.active{background:var(--blue);color:#fff}.market-value{display:flex;justify-content:space-between;align-items:flex-end;margin-top:10px}.market-value strong{font-size:23px}.market-value span{color:var(--green);font-size:11px;font-weight:700}.mini-chart{height:65px;margin:7px 0;position:relative;background:linear-gradient(180deg,transparent 0 65%,#1a875a18 66%)}.mini-chart:after{content:"";position:absolute;inset:8px 3px;clip-path:polygon(0 85%,10% 72%,20% 76%,30% 49%,40% 57%,50% 28%,60% 44%,70% 20%,80% 36%,90% 12%,100% 22%,100% 28%,90% 18%,80% 42%,70% 26%,60% 50%,50% 34%,40% 63%,30% 55%,20% 82%,10% 78%,0 91%);background:var(--green)}.market-sub{display:flex;justify-content:space-between;border-top:1px solid var(--line);padding-top:9px;color:var(--muted);font-size:10px}
.wide-section{margin-top:16px}.commerce-grid{display:grid;grid-template-columns:repeat(5,1fr);gap:10px;padding:14px}.product{border:1px solid var(--line);position:relative}.product-art{height:130px}.product-art:before{content:"";position:absolute;inset:23% 25%;border-radius:10px;background:var(--blue)}.product-art[data-visual="clock"]:before{border-radius:50%;background:#fff;border:6px solid #d9c8aa}.product-art[data-visual="umbrella"]:before{clip-path:polygon(50% 0,100% 70%,55% 70%,55% 100%,45% 100%,45% 70%,0 70%);background:#4c815f}.product-art[data-visual="mill"]:before{background:#d5b47c;clip-path:polygon(20% 0,80% 0,100% 100%,0 100%)}.product-art[data-visual="purifier"]:before{background:repeating-linear-gradient(#365d80 0 8px,#e8eef4 9px 15px)}.product-copy{padding:9px}.product-copy h3{font-size:11px;margin:0}.product-copy strong{display:block;color:var(--red);font-size:15px;margin-top:5px}.heart{position:absolute;right:7px;top:7px;width:35px;height:35px;border-radius:50%;background:#fff;color:#6b7280;font-size:18px;box-shadow:0 1px 5px #0002}.heart.saved{color:var(--red);background:#fff0f1}.info-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px}.score-panel,.trend-panel{display:none;padding:12px 14px}.score-panel.active,.trend-panel.active{display:block}.game{display:grid;grid-template-columns:1fr auto 1fr;align-items:center;text-align:center;padding:11px 0;border-bottom:1px solid var(--line)}.team{font-size:12px;font-weight:700}.team time{display:block;font-size:9px;color:var(--muted)}.score{font-size:18px;font-weight:900;color:var(--blue);padding:0 12px}.trend-item{display:grid;grid-template-columns:25px 1fr auto;gap:8px;align-items:center;padding:8px 0;border-bottom:1px solid var(--line)}.trend-item b{color:var(--red);font-size:17px}.trend-item a{font-weight:700;font-size:12px}.trend-item span{font-size:9px;color:var(--muted)}
.footer{background:var(--card);border-top:1px solid var(--line)}.footer-links{display:flex;justify-content:center;gap:18px;flex-wrap:wrap;padding:24px 0 14px;color:var(--blue);font-size:10px}.copyright,.legal{text-align:center;color:var(--muted);font-size:9px}.legal{padding:7px 0 25px}.backtop{position:fixed;right:20px;bottom:20px;width:46px;height:46px;border-radius:50%;background:var(--blue);color:#fff;z-index:90;opacity:0;pointer-events:none}.backtop.show{opacity:1;pointer-events:auto}.drawer,.modal,.settings-overlay{position:fixed;inset:0;z-index:300;background:#0b1627b8;display:none}.drawer.open,.modal.open,.settings-overlay.open{display:block}.drawer-panel{width:min(390px,90vw);height:100%;background:var(--card);margin-left:auto;padding:22px}.drawer-head,.modal-head,.settings-head{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);padding-bottom:16px}.close{width:42px;height:42px;border:1px solid var(--line);font-size:24px}.drawer-nav{display:flex;flex-direction:column;margin-top:12px}.drawer-nav a{padding:14px 4px;border-bottom:1px solid var(--line);font-size:17px;font-weight:800}.drawer-copy{padding:18px 0;color:var(--muted)}.modal{place-items:center}.modal.open{display:grid}.modal-card{width:min(480px,calc(100% - 32px));background:var(--card);padding:22px}.modal-body h2{margin-bottom:4px}.modal-body p{color:var(--muted)}.login-form{display:grid;gap:8px}.login-form input{height:44px;border:1px solid var(--line);padding:0 11px;background:var(--card);color:var(--ink)}.modal-status{min-height:24px;color:var(--red);font-weight:700}.toast{position:fixed;z-index:500;left:50%;bottom:24px;transform:translate(-50%,30px);opacity:0;background:#101827;color:#fff;padding:11px 16px;pointer-events:none;transition:.2s}.toast.show{opacity:1;transform:translate(-50%,0)}
.settings-overlay{place-items:center;padding:24px}.settings-overlay.open{display:grid}.settings-card{width:min(1360px,100%);height:min(900px,96vh);background:#071526;color:#eaf3ff;border:1px solid #2a6c94;display:grid;grid-template-rows:auto 1fr auto}.settings-head{padding:22px 28px;border-color:#244863}.settings-head small{color:#ffd43b;font-weight:800}.settings-head h2{margin:6px 0 0;font-size:28px}.settings-main{min-height:0;display:grid;grid-template-columns:250px 1fr}.module-tabs{padding:18px;border-right:1px solid #244863;overflow:auto}.module-tab{display:block;width:100%;text-align:left;padding:14px 16px;margin-bottom:8px;background:#0d2940;color:#dcecff;border:1px solid #315773;font-weight:800}.module-tab.active{background:#25aee4;color:#03131e}.editor-wrap{padding:18px;min-width:0;display:grid;grid-template-rows:auto 1fr auto}.editor-meta{display:flex;justify-content:space-between;color:#9fb5c9;margin-bottom:9px}.json-editor{width:100%;height:100%;resize:none;background:#020b13;color:#d9f3ff;border:1px solid #315773;padding:18px;font:15px/1.55 Consolas,monospace;tab-size:2}.editor-help{color:#91a8bc;margin-top:8px}.settings-actions{display:flex;justify-content:flex-end;align-items:center;gap:10px;padding:16px 28px;border-top:1px solid #244863}.settings-actions button{min-height:44px;padding:0 18px;border:1px solid #3e789c;color:#fff;font-weight:800}.settings-actions .apply{background:#ffc928;color:#071526;border-color:#ffc928}.settings-status{margin-right:auto;color:#9fd8f5}
@media(max-width:880px){.utility{display:none}.head-row{height:70px}.head-actions .head-link{display:none}.mobile-menu{display:flex}.brand-mark{width:42px;height:42px}.brand-copy strong{font-size:25px}.portal-grid{grid-template-columns:1fr}.right-col{display:grid;grid-template-columns:1fr 1fr}.commerce-grid{grid-template-columns:repeat(3,1fr)}.settings-main{grid-template-columns:190px 1fr}.settings-button{top:auto;bottom:76px}}
@media(max-width:620px){.wrap{width:min(100% - 20px,var(--max))}.brand-copy small{display:none}.search-tabs button{padding:0 12px}.search-under{align-items:flex-start;gap:6px;flex-direction:column}.notice-row{padding:7px 0}.service-grid{grid-template-columns:repeat(3,1fr)}.news-body{grid-template-columns:1fr}.news-feature{display:grid;grid-template-columns:120px 1fr;gap:10px}.feature-art{height:86px}.recommend-grid{grid-template-columns:1fr}.recommend{display:grid;grid-template-columns:110px 1fr}.rec-art{height:80px}.right-col{display:flex}.commerce-grid{grid-template-columns:repeat(2,1fr)}.info-grid{grid-template-columns:1fr}.settings-overlay{padding:0}.settings-card{height:100vh}.settings-main{grid-template-columns:1fr;grid-template-rows:auto 1fr}.module-tabs{display:flex;border-right:0;border-bottom:1px solid #244863;padding:10px;overflow:auto}.module-tab{width:auto;min-width:106px;margin:0 6px 0 0;padding:10px}.editor-wrap{padding:10px}.settings-actions{padding:10px;flex-wrap:wrap}.settings-status{width:100%}.settings-actions button{padding:0 11px}.settings-head{padding:14px}.settings-head h2{font-size:22px}}
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}
.skip{top:calc(var(--df-generated-header-height,0px) + 8px)}
.settings-button{top:calc(var(--df-generated-header-height,0px) + 20px)}
@media(max-width:880px){.settings-button{top:auto}}
.skip{transform:translateY(calc(-100% - var(--df-generated-header-height,0px) - 24px))}.skip:focus{transform:none}
.drawer,.modal{z-index:1200}.settings-overlay{z-index:1300}
</style>
</head>
<body>
<a class="skip" id="skipLink" href="#main"></a><button class="settings-button" id="openSettings" aria-label="编辑页面 JSON" title="编辑页面 JSON">⚙</button>
<div class="utility"><div class="wrap utility-row"><div class="utility-links" id="utilityLeft"></div><div class="utility-links" id="utilityRight"></div></div></div>
<header class="header"><div class="wrap head-row"><a class="brand" href="#main"><span class="brand-mark"></span><span class="brand-copy"><strong><span id="brandPrimary"></span> <span id="brandAccent"></span></strong><small id="tagline"></small></span></a><div class="head-actions"><button class="head-link" data-login id="headerLogin"></button><a class="head-link" href="#account"><span id="mailLabel"></span><span class="mail-badge" id="mailCount"></span></a><button class="icon-btn" id="themeToggle">◐</button><button class="icon-btn mobile-menu" id="menuOpen">☰</button></div></div></header>
<section class="search-zone"><div class="wrap"><h1 id="searchTitle" hidden></h1><div class="search-tabs" id="searchTabs"></div><form class="search-form" id="searchForm"><input id="searchInput" type="search"><button id="searchButton"></button></form><div class="search-under"><div class="suggestions" id="suggestions"></div><span class="search-status" id="searchStatus"></span></div></div></section>
<div class="notice"><div class="wrap notice-row"><span class="notice-badge" id="noticeLabel"></span><a id="noticeLink"></a></div></div>
<main id="main" tabindex="-1"><div class="wrap"><div class="portal-grid"><div class="left-col">
<section class="card" id="services"><div class="module-head"><h2 id="servicesTitle"></h2><a id="servicesAll"></a></div><div class="services-body"><div class="service-grid" id="servicePrimary"></div><div class="service-grid extra-services" id="serviceExtra"></div><button class="service-more" id="serviceMore"></button></div></section>
<section class="card" id="news"><div class="module-head"><h2 id="newsTitle"></h2><span id="newsUpdated"></span></div><div class="news-tabs" id="newsTabs"></div><div class="news-body"><div id="newsLists"></div><article class="news-feature" id="newsFeature"></article></div><div class="news-footer"><a id="newsMore"></a><a id="newsTopics"></a></div></section>
<section class="card"><div class="module-head"><h2 id="recommendTitle"></h2><button id="recRefresh"></button></div><div class="recommend-grid" id="recommendGrid"></div></section>
</div><aside class="right-col">
<section class="card login" id="account"><h2 id="accountTitle"></h2><p id="accountText"></p><button class="btn" data-login id="accountLogin"></button><div class="login-links"><a id="accountNew"></a><a id="accountProfile"></a></div><div class="status-row" id="accountStatuses"></div></section>
<section class="card" id="weather"><div class="module-head"><h2 id="weatherTitle"></h2><select class="weather-select" id="weatherSelect"></select></div><div class="weather-body"><div class="weather-main"><div class="day-weather"><div class="weather-label" id="todayLabel"></div><div class="weather-visual"><span class="sun-cloud"></span><div class="temp"><span class="high" id="todayHigh"></span>/<span class="low" id="todayLow"></span></div></div><div class="weather-meta" id="todaySummary"></div></div><div class="day-weather"><div class="weather-label" id="tomorrowLabel"></div><div class="weather-visual"><span class="sun-cloud"></span><div class="temp"><span class="high" id="tomorrowHigh"></span>/<span class="low" id="tomorrowLow"></span></div></div><div class="weather-meta" id="tomorrowSummary"></div></div></div><div class="weather-links" id="weatherLinks"></div></div></section>
<section class="card" id="transit"><div class="module-head"><h2 id="transitTitle"></h2><a id="transitDetail"></a></div><div class="transit-body"><div class="transit-status" id="transitStatus"></div><form class="route-form" id="routeForm"><input id="fromStation" required><button id="routeButton"></button><input id="toStation" required></form><div class="route-result" id="routeResult"></div></div></section>
<section class="card" id="finance"><div class="module-head"><h2 id="financeTitle"></h2><a id="financeMore"></a></div><div class="finance-body"><div class="market-tabs" id="marketTabs"></div><div class="market-value"><strong id="marketValue"></strong><span id="marketChange"></span></div><div class="mini-chart"></div><div class="market-sub"><span id="marketUpdated"></span><span id="marketPrevious"></span></div></div></section>
</aside></div>
<section class="card wide-section" id="shopping"><div class="module-head"><h2 id="shoppingTitle"></h2><a id="shoppingMore"></a></div><div class="commerce-grid" id="productGrid"></div></section>
<div class="info-grid wide-section"><section class="card" id="sports"><div class="module-head"><h2 id="sportsTitle"></h2><a id="sportsMore"></a></div><div class="sports-tabs" id="sportsTabs"></div><div id="scorePanels"></div></section><section class="card"><div class="module-head"><h2 id="trendsTitle"></h2><button id="trendRefresh"></button></div><div class="trend-tabs" id="trendTabs"></div><div id="trendPanels"></div></section></div>
</div></main>
<footer class="footer" id="footer"><div class="wrap"><nav class="footer-links" id="footerLinks"></nav><div class="copyright" id="copyright"></div><div class="legal" id="legal"></div></div></footer>
<button class="backtop" id="backTop">↑</button>
<div class="drawer" id="drawer"><div class="drawer-panel"><div class="drawer-head"><span class="brand-copy"><strong><span id="drawerBrand"></span></strong></span><button class="close" data-close="drawer">×</button></div><div class="drawer-copy"><h2 id="drawerTitle"></h2><p id="drawerText"></p></div><nav class="drawer-nav" id="drawerNav"></nav></div></div>
<div class="modal" id="loginModal"><div class="modal-card"><div class="modal-head"><strong id="loginModalTitle"></strong><button class="close" data-close="loginModal">×</button></div><div class="modal-body"><h2 id="loginWelcome"></h2><p id="loginNote"></p><form class="login-form" id="loginForm"><label id="emailLabel" for="loginId"></label><input id="loginId" type="email" required><label id="passwordLabel" for="loginPass"></label><input id="loginPass" type="password" required><button class="btn" id="loginSubmit"></button><div class="modal-status" id="loginStatus"></div></form></div></div></div>
<div class="toast" id="toast"></div>
<div class="settings-overlay" id="settingsOverlay"><div class="settings-card"><div class="settings-head"><div><small>雅虎日本页面模板控制台</small><h2>JSON 编辑器</h2></div><button class="close" data-close="settingsOverlay">×</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="settings-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="yahooJapanPageData">__YAHOO_JAPAN_PAGE_DATA__</script>
<script>__YAHOO_JAPAN_PAGE_RUNTIME__</script>
</body>
</html>
@@ -0,0 +1,31 @@
# 雅虎日本中文页面 JSON 契约
顶层只允许以下十个对象:
`site`、`search`、`services`、`news`、`account`、`weather`、`utilities`、`shopping`、`pulse`、`footer`。
## 中文内容规则
- `site.language` 固定为 `zh-CN`。
- 品牌 `Yahoo! JAPAN` 可以保留;其余栏目、标题、摘要、按钮、日期、天气、交通、市场、商品、体育和页脚文案必须使用简体中文。
- JSON 键名及 `id`、`href`、`visual`、`theme` 等技术值保持英文;数字、时间、温度、百分比、价格和比分可以保持数据格式。
## 模块说明
- `site`:品牌、口号、页面信息、主题、顶部链接、操作按钮和公告。
- `search`:搜索类型、输入提示、热门词和结果反馈文案。
- `services`:5–12 个常用服务与 1–8 个扩展服务。
- `news`:2–8 个新闻分类、主专题和 1–6 条推荐内容。
- `account`:登录卡片、账户状态和演示登录弹窗。
- `weather`:2–6 个地区的今明天气及 1–6 个天气入口。
- `utilities`:路线查询文案和 2–6 个市场行情。
- `shopping`:2–8 个商品卡片与收藏反馈。
- `pulse`:2–5 个体育分类及 2–5 个实时热榜分类。
- `footer`:移动抽屉、页脚链接、版权和概念站说明。
## 通用限制
- 文本必须是纯文本,不得包含 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 时才加载对应媒体。
- JSON 使用双引号,不允许注释、Markdown 围栏或尾逗号。
@@ -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_yahoo_japan_page as renderer
from fast_patch_page import run
if __name__ == "__main__":
sys.exit(run(renderer, output_stem="yahoo-japan-page"))
@@ -0,0 +1,422 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
SKILL_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_DATA = SKILL_ROOT / "assets" / "default-data.json"
TEMPLATE_PATH = SKILL_ROOT / "assets" / "yahoo-japan-template.html"
RUNTIME_PATH = SKILL_ROOT / "assets" / "yahoo-japan-runtime.js"
MODULES = (
"site",
"search",
"services",
"news",
"account",
"weather",
"utilities",
"shopping",
"pulse",
"footer",
)
SERVICE_VISUALS = {
"shopping", "auction", "weather", "news", "sports", "finance", "transit",
"property", "car", "travel", "calendar", "community", "tax", "jobs", "books",
}
RECOMMEND_VISUALS = {"trail", "recipe", "plaza"}
PRODUCT_VISUALS = {"backpack", "clock", "umbrella", "mill", "purifier"}
FEATURE_VISUALS = {"transit-map"}
REMOTE_MEDIA_TYPES = {"image", "video", "webpage"}
MEDIA_URL_KEYS = {"mediaUrl", "posterUrl", "pageUrl"}
TECHNICAL_KEYS = {
"id", "href", "visual", "theme", "language", "brandPrimary", "brandAccent",
"value", "price", "score", "change", "previous", "rank", "type",
"mediaUrl", "posterUrl", "pageUrl",
}
LATIN_RE = re.compile(r"[A-Za-z]")
KANA_RE = re.compile(r"[\u3040-\u30ff]")
CJK_RE = re.compile(r"[\u3400-\u9fff]")
REMOTE_RE = re.compile(r"(?:https?://|javascript:|<\s*(?:script|iframe)\b)", re.I)
class DataValidationError(ValueError):
pass
def _read_json(path: Path) -> dict[str, Any]:
try:
value = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise DataValidationError(f"unable to read valid JSON from {path}: {exc}") from exc
if not isinstance(value, dict):
raise DataValidationError("top-level JSON 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 _list(value: Any, path: str, errors: list[str], minimum: int = 0, maximum: int = 99) -> list[Any]:
if not isinstance(value, list):
errors.append(f"{path} must be an array")
return []
if not minimum <= len(value) <= maximum:
errors.append(f"{path} must contain {minimum}-{maximum} items")
return value
def _strings(obj: dict[str, Any], path: str, keys: tuple[str, ...], errors: list[str]) -> None:
for key in keys:
if not isinstance(obj.get(key), str) or not obj[key].strip():
errors.append(f"{path}.{key} must be a non-empty string")
def _href(value: Any, path: str, errors: list[str]) -> None:
if not isinstance(value, str) or not value.startswith("#"):
errors.append(f"{path} must start with #")
def _items(
value: Any,
path: str,
errors: list[str],
*,
minimum: int,
maximum: int,
string_keys: tuple[str, ...],
href_key: str | None = None,
visual_key: str | None = None,
visuals: set[str] | None = None,
) -> list[dict[str, Any]]:
raw = _list(value, path, errors, minimum, maximum)
result: list[dict[str, Any]] = []
ids: list[str] = []
for index, item in enumerate(raw):
current = _mapping(item, f"{path}[{index}]", errors)
_strings(current, f"{path}[{index}]", ("id",) + string_keys, errors)
item_id = current.get("id")
if isinstance(item_id, str):
ids.append(item_id)
if href_key:
_href(current.get(href_key), f"{path}[{index}].{href_key}", errors)
if visual_key and current.get(visual_key) not in (visuals or set()):
errors.append(f"{path}[{index}].{visual_key} must be one of {sorted(visuals or set())}")
result.append(current)
duplicates = sorted({item_id for item_id in ids if ids.count(item_id) > 1})
if duplicates:
errors.append(f"{path} id duplicates: {', '.join(duplicates)}")
return result
def _walk_no_remote(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
_walk_no_remote(item, f"{path}.{key}", errors)
elif isinstance(value, list):
for index, item in enumerate(value):
_walk_no_remote(item, f"{path}[{index}]", errors)
elif isinstance(value, str) and REMOTE_RE.search(value):
errors.append(f"{path} must not contain remote URLs, scripts, or iframes")
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, media_type = f"{path}.media", media.get("type")
if media_type not in REMOTE_MEDIA_TYPES:
errors.append(
f"{media_path}.type must be one of: "
f"{', '.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 _walk_chinese(value: Any, path: str, errors: list[str], key: str = "") -> None:
if isinstance(value, dict):
for child, item in value.items():
_walk_chinese(item, f"{path}.{child}", errors, child)
elif isinstance(value, list):
for index, item in enumerate(value):
_walk_chinese(item, f"{path}[{index}]", errors, key)
elif (
isinstance(value, str)
and key not in TECHNICAL_KEYS
and not key.lower().endswith(("id", "href", "url"))
and (KANA_RE.search(value) or (LATIN_RE.search(value) and not CJK_RE.search(value)))
):
errors.append(f"{path} must use Simplified Chinese reader-facing copy")
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(f"missing top-level module(s): {', '.join(missing)}")
if extra:
errors.append(f"unknown top-level module(s): {', '.join(extra)}")
site = _mapping(data.get("site"), "site", errors)
_strings(
site,
"site",
(
"brandPrimary", "brandAccent", "tagline", "pageTitle", "description",
"language", "theme", "skipLabel", "dateLabel", "loginLabel",
"mailLabel", "mailCount", "menuLabel", "themeLabel",
"themeDarkMessage", "themeLightMessage",
),
errors,
)
if site.get("language") != "zh-CN":
errors.append("site.language must be zh-CN")
utility_left = _items(site.get("utilityLeft"), "site.utilityLeft", errors, minimum=1, maximum=8, string_keys=("label",), href_key="href")
utility_right = _items(site.get("utilityRight"), "site.utilityRight", errors, minimum=1, maximum=8, string_keys=("label",), href_key="href")
notice = _mapping(site.get("notice"), "site.notice", errors)
_strings(notice, "site.notice", ("label", "text"), errors)
_href(notice.get("href"), "site.notice.href", errors)
search = _mapping(data.get("search"), "search", errors)
_strings(search, "search", ("title", "placeholderSuffix", "button", "hotLabel", "emptyMessage", "resultPrefix", "resultKeyword"), errors)
search_tabs = _items(search.get("tabs"), "search.tabs", errors, minimum=2, maximum=10, string_keys=("label",))
suggestions = _list(search.get("suggestions"), "search.suggestions", errors, 1, 8)
if any(not isinstance(item, str) or not item.strip() for item in suggestions):
errors.append("search.suggestions must contain non-empty strings")
services = _mapping(data.get("services"), "services", errors)
_strings(services, "services", ("title", "allLabel", "moreLabel", "lessLabel"), errors)
_href(services.get("allHref"), "services.allHref", errors)
service_primary = _items(services.get("primary"), "services.primary", errors, minimum=5, maximum=12, string_keys=("label", "visual"), href_key="href", visual_key="visual", visuals=SERVICE_VISUALS)
service_extra = _items(services.get("extra"), "services.extra", errors, minimum=1, maximum=8, string_keys=("label", "visual"), href_key="href", visual_key="visual", visuals=SERVICE_VISUALS)
news = _mapping(data.get("news"), "news", errors)
_strings(news, "news", ("title", "updated", "moreLabel", "topicsLabel", "recommendTitle", "refreshLabel", "refreshMessage"), errors)
_href(news.get("moreHref"), "news.moreHref", errors)
_href(news.get("topicsHref"), "news.topicsHref", errors)
news_tabs = _items(news.get("tabs"), "news.tabs", errors, minimum=2, maximum=8, string_keys=("label",))
news_items = 0
for index, tab in enumerate(news_tabs):
items = _items(tab.get("items"), f"news.tabs[{index}].items", errors, minimum=1, maximum=8, string_keys=("title", "time"), href_key="href")
news_items += len(items)
for item_index, item in enumerate(items):
if not isinstance(item.get("tag"), str):
errors.append(f"news.tabs[{index}].items[{item_index}].tag must be a string")
if not isinstance(item.get("isNew"), bool):
errors.append(f"news.tabs[{index}].items[{item_index}].isNew must be boolean")
feature = _mapping(news.get("feature"), "news.feature", errors)
_strings(feature, "news.feature", ("kicker", "title", "summary", "visual"), errors)
_href(feature.get("href"), "news.feature.href", errors)
if feature.get("visual") not in FEATURE_VISUALS:
errors.append(f"news.feature.visual must be one of {sorted(FEATURE_VISUALS)}")
recommendations = _items(news.get("recommendations"), "news.recommendations", errors, minimum=1, maximum=6, string_keys=("title", "category", "visual"), visual_key="visual", visuals=RECOMMEND_VISUALS)
account = _mapping(data.get("account"), "account", errors)
_strings(account, "account", ("title", "text", "loginLabel", "newIdLabel", "profileLabel", "modalTitle", "welcome", "demoNote", "emailLabel", "passwordLabel", "submitLabel", "resultMessage", "closeLabel"), errors)
_href(account.get("newIdHref"), "account.newIdHref", errors)
_href(account.get("profileHref"), "account.profileHref", errors)
statuses = _items(account.get("statuses"), "account.statuses", errors, minimum=1, maximum=4, string_keys=("label", "visual"), href_key="href")
weather = _mapping(data.get("weather"), "weather", errors)
_strings(weather, "weather", ("title", "regionLabel", "updatedMessage"), errors)
locations = _items(weather.get("locations"), "weather.locations", errors, minimum=2, maximum=6, string_keys=("city",))
for index, location in enumerate(locations):
for day_name in ("today", "tomorrow"):
day = _mapping(location.get(day_name), f"weather.locations[{index}].{day_name}", errors)
_strings(day, f"weather.locations[{index}].{day_name}", ("label", "high", "low", "summary"), errors)
weather_links = _items(weather.get("links"), "weather.links", errors, minimum=1, maximum=6, string_keys=("label", "message"))
utilities = _mapping(data.get("utilities"), "utilities", errors)
transit = _mapping(utilities.get("transit"), "utilities.transit", errors)
_strings(transit, "utilities.transit", ("title", "detailLabel", "status", "fromLabel", "toLabel", "buttonLabel", "emptyMessage", "resultPrefix", "resultDetail"), errors)
_href(transit.get("detailHref"), "utilities.transit.detailHref", errors)
finance = _mapping(utilities.get("finance"), "utilities.finance", errors)
_strings(finance, "utilities.finance", ("title", "moreLabel", "updated", "previousPrefix"), errors)
_href(finance.get("moreHref"), "utilities.finance.moreHref", errors)
markets = _items(finance.get("markets"), "utilities.finance.markets", errors, minimum=2, maximum=6, string_keys=("label", "value", "change", "previous"))
shopping = _mapping(data.get("shopping"), "shopping", errors)
_strings(shopping, "shopping", ("title", "moreLabel", "saveLabel", "removeLabel", "savedMessage", "removedMessage"), errors)
_href(shopping.get("moreHref"), "shopping.moreHref", errors)
products = _items(shopping.get("products"), "shopping.products", errors, minimum=2, maximum=8, string_keys=("title", "price", "visual"), visual_key="visual", visuals=PRODUCT_VISUALS)
pulse = _mapping(data.get("pulse"), "pulse", errors)
_strings(pulse, "pulse", ("sportsTitle", "sportsMoreLabel", "trendsTitle", "refreshLabel", "refreshMessage"), errors)
_href(pulse.get("sportsMoreHref"), "pulse.sportsMoreHref", errors)
sports_tabs = _items(pulse.get("sportsTabs"), "pulse.sportsTabs", errors, minimum=2, maximum=5, string_keys=("label",))
sports_games = 0
for index, tab in enumerate(sports_tabs):
games = _items(tab.get("games"), f"pulse.sportsTabs[{index}].games", errors, minimum=1, maximum=5, string_keys=("home", "homeNote", "score", "away", "awayNote"))
sports_games += len(games)
trend_tabs = _items(pulse.get("trendTabs"), "pulse.trendTabs", errors, minimum=2, maximum=5, string_keys=("label",))
trend_items = 0
for index, tab in enumerate(trend_tabs):
items = _items(tab.get("items"), f"pulse.trendTabs[{index}].items", errors, minimum=1, maximum=8, string_keys=("rank", "title", "meta"), href_key="href")
trend_items += len(items)
footer = _mapping(data.get("footer"), "footer", errors)
_strings(footer, "footer", ("drawerTitle", "drawerText", "copyright", "legal", "backTopLabel"), errors)
drawer_links = _items(footer.get("drawerLinks"), "footer.drawerLinks", errors, minimum=2, maximum=12, string_keys=("label",), href_key="href")
footer_links = _items(footer.get("links"), "footer.links", errors, minimum=2, maximum=12, string_keys=("label",), href_key="href")
_validate_remote_media_tree(data, "$", errors)
_walk_no_remote(data, "$", errors)
_walk_chinese(data, "$", errors)
if errors:
raise DataValidationError("\n".join(f"- {error}" for error in errors))
return {
"utility_links": len(utility_left) + len(utility_right),
"search_tabs": len(search_tabs),
"suggestions": len(suggestions),
"services": len(service_primary) + len(service_extra),
"news_tabs": len(news_tabs),
"news_items": news_items,
"recommendations": len(recommendations),
"account_statuses": len(statuses),
"weather_locations": len(locations),
"weather_links": len(weather_links),
"markets": len(markets),
"products": len(products),
"sports_tabs": len(sports_tabs),
"sports_games": sports_games,
"trend_tabs": len(trend_tabs),
"trend_items": trend_items,
"drawer_links": len(drawer_links),
"footer_links": len(footer_links),
}
def render_document(data: dict[str, Any], template: str, runtime: str) -> str:
validate_document(data)
rendered = template.replace(
"__YAHOO_JAPAN_PAGE_DATA__",
json.dumps(data, ensure_ascii=False, separators=(",", ":")),
).replace("__YAHOO_JAPAN_PAGE_RUNTIME__", runtime)
if "__YAHOO_JAPAN_PAGE_" in rendered:
raise DataValidationError("template placeholders remain after rendering")
return rendered
def _write_new(path: Path, text: str) -> None:
if path.exists():
raise DataValidationError(f"refusing to overwrite existing path: {path}")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
def _init(output: Path) -> dict[str, Any]:
data = _read_json(DEFAULT_DATA)
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 _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 _render(input_path: Path, output: Path) -> dict[str, Any]:
data = _read_json(input_path)
counts = validate_document(data)
html = render_document(data, TEMPLATE_PATH.read_text(encoding="utf-8"), RUNTIME_PATH.read_text(encoding="utf-8"))
_write_new(output, html)
return {"status":"ok","action":"render","input":str(input_path),"output":str(output),"modules":list(MODULES),"counts":counts}
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Render the bundled Chinese Yahoo! JAPAN-style portal")
subparsers = parser.add_subparsers(dest="action", required=True)
init_parser = subparsers.add_parser("init")
init_parser.add_argument("--output", type=Path, required=True)
validate_parser = subparsers.add_parser("validate")
validate_parser.add_argument("--input", type=Path, required=True)
render_parser = subparsers.add_parser("render")
render_parser.add_argument("--input", type=Path, required=True)
render_parser.add_argument("--output", type=Path, required=True)
return parser
def main() -> int:
args = _parser().parse_args()
try:
if args.action == "init":
result = _init(args.output)
elif args.action == "validate":
result = _validate(args.input)
else:
result = _render(args.input, args.output)
except DataValidationError as exc:
print(json.dumps({"status":"error","message":str(exc)}, ensure_ascii=False), file=sys.stderr)
return 2
print(json.dumps(result, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())