sync update from LAN repo (source master @ ca48c4ec)
This commit is contained in:
1 parent
8bc8b0e082
commit
ea9dcff9c0
873 files changed
+107866
-14011
No files matched your search
@@ -0,0 +1,82 @@
|
||||
---
|
||||
name: bbc-page-generator
|
||||
description: 生成或绘制 BBC 及 BBC 风格的可交付国际公共新闻门户 HTML 网页;仅在用户明确要求 BBC 网页、BBC 风格新闻首页或点名本技能时使用。先把材料或检索结果整理成十模块 JSON,再用内置模板确定性渲染,保留右上角可视化 JSON 编辑弹窗。
|
||||
allowed-tools:
|
||||
- read_file
|
||||
- write_file
|
||||
- bash
|
||||
- present_files
|
||||
- web_search
|
||||
---
|
||||
|
||||
# BBC 页面生成器
|
||||
|
||||
本技能使用固定模板生成单文件 BBC 风格国际公共新闻首页。模型只负责材料收集和 JSON,禁止重新手写页面结构、CSS 或运行时脚本。最终页面自带右上角设置按钮;用户可在弹窗中按模块编辑 JSON,并通过「应用并渲染」即时更新页面。
|
||||
|
||||
编辑弹窗还提供“上传图片/视频”:先把光标放进目标报道、帖子、视频或带 `visual`/`media` 的内容对象,上传文件会转换为 `data:` 地址并写入该对象的 `media` 字段。不设文件大小拦截;较大文件可能超过浏览器本地缓存容量,应同时下载 JSON 留存。
|
||||
|
||||
页面中已由 `media` 数据渲染的图片和视频还带悬浮上传图标:鼠标移入媒体后点击可任选图片或视频并直接替换,文件的实际类型会自动写入新的 `media.type`,结果同步写回页面 JSON 与浏览器缓存。头像、Logo 和无法映射回 JSON 的装饰图不会显示该入口;不按原媒体类型限制,也不设置文件大小拦截。
|
||||
|
||||
默认视觉直接复用模板原有的示例图:不要调用图像生成工具,不要让模型重新生成、拼装或内嵌新的内容型 SVG,也不要为了寻找“标准配图”延长检索。用户没有提供可直接使用的图片/视频且聚焦检索未得到可靠直链时,保留默认 JSON 的 `visual` 或内置视觉类型;这些是模板自带的静态示例,调用技能时不重新绘制。不要把大段 base64 示例图重复写进 JSON,图不合适时由用户在成品页面悬浮上传替换。
|
||||
|
||||
## 触发边界
|
||||
|
||||
- 用户明确说「生成/画/制作 BBC 网页」「BBC 风格新闻首页/国际公共媒体门户」或点名 `bbc-page-generator` 时使用。
|
||||
- 仅讨论 BBC、总结 BBC 报道、分析新闻机构或普通文本中出现 BBC 时不要使用。
|
||||
- 这是 BBC 风格单页公共新闻门户,不改用 CNN、新华社或通用多页门户模板。
|
||||
|
||||
## 极速工作流(默认)
|
||||
|
||||
页面结构已经固定。完成必要检索或材料整理后,模型只写一份小型规格 JSON;未写字段继续使用模板默认数据与示例视觉,脚本在一次进程内合并、校验并渲染。
|
||||
|
||||
1. 用 `write_file` 创建 `/mnt/user-data/outputs/bbc-page-spec.json`。直接写模块对象会递归合并;修改现有数组项优先用 `$set`:
|
||||
|
||||
```json
|
||||
{"site":{"pageTitle":"BBC · 中文新闻专题"},"$set":{"breaking.text":"中文快讯","lead.title":"中文头条","lead.summary":"中文摘要"}}
|
||||
```
|
||||
|
||||
2. 只执行一次 `python /mnt/skills/public/bbc-page-generator/scripts/fast_page.py --spec /mnt/user-data/outputs/bbc-page-spec.json --output-dir /mnt/user-data/outputs`。
|
||||
3. stdout 为 `status: ok` 后立即用 `present_files` 交付完整 JSON 与 HTML,最终只回复一句完成说明。
|
||||
|
||||
规格只允许本技能十个模块和 `$set`;路径必须指向默认 JSON 的已存在字段。读者可见新闻内容使用简体中文,品牌名可保留。未提供媒体直链时保留模板示例视觉。禁止读取默认数据、契约、模板、运行时或脚本源码,禁止 `--help`、独立 `init/validate/render`、生成后打补丁、临时脚本和冗长过程说明。规格报错时只修正一次并重跑。只有用户明确要求改变模块结构或批量重建完整数组时,才使用下面的完整工作流。
|
||||
|
||||
## 完整工作流(仅限结构改造)
|
||||
|
||||
1. 读取当前会话材料、上传附件和已有产物,确定站点、双层导航、快讯、头条、今日焦点、视频音频、更多新闻、地区天气、简报和页脚。
|
||||
2. 用户要求基于公开资料、主题涉及近期事件,或明确要求检索时,先做聚焦检索并将可靠事实整理为新闻文案;用户明确说不要检索时不得联网。没有材料时使用中性示例,不把模拟时间、天气或节目状态描述成实时数据。
|
||||
3. 初始化新的完整 JSON:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/bbc-page-generator/scripts/render_bbc_page.py init --output /mnt/user-data/outputs/bbc-page-data.json
|
||||
```
|
||||
|
||||
4. 只修改 JSON。十个顶层模块必须全部保留:`site`、`navigation`、`breaking`、`lead`、`focus`、`media`、`moreNews`、`regions`、`newsletter`、`footer`。字段不确定时读取 [references/data-schema.md](references/data-schema.md)。
|
||||
5. 校验 JSON:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/bbc-page-generator/scripts/render_bbc_page.py validate --input /mnt/user-data/outputs/bbc-page-data.json
|
||||
```
|
||||
|
||||
6. 确定性渲染到 `outputs/`:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/bbc-page-generator/scripts/render_bbc_page.py render --input /mnt/user-data/outputs/bbc-page-data.json --output /mnt/user-data/outputs/bbc-page.html
|
||||
```
|
||||
|
||||
7. 检查 stdout 的 `status` 为 `ok`、HTML 存在且占位符已经消失,再用 `present_files` 同时交付 HTML 与源 JSON。不要在聊天中粘贴完整 HTML。
|
||||
|
||||
## 内容映射
|
||||
|
||||
- 最高优先级报道放入 `lead`;四宫格焦点放入 `focus.items`;较短报道和排行放入 `moreNews`。
|
||||
- 视频直播和音频节目统一放入 `media`,不要把节目卡片混入普通新闻。
|
||||
- 地区标题和静态天气快照放入 `regions`;没有可靠来源时必须明确为示例或静态快照。
|
||||
- `visual` 继续作为内置后备视觉;需要替换时,可在对应内容对象增加受校验的 `media`(`image`、`video`、`webpage`)。所有外部文本由模板转义,不得包含 HTML、脚本或直接 iframe。
|
||||
- 页面引用近期事实时以检索材料为准;模板默认内容只是结构示例。
|
||||
|
||||
## 重要约束
|
||||
|
||||
- 只编辑 JSON,不修改 `assets/bbc-template.html` 或 `assets/bbc-runtime.js`,不复制模板后手改 DOM。
|
||||
- 初始化与渲染默认拒绝覆盖已有文件;路径存在时换新文件名,不删除旧产物。
|
||||
- 页面结构、样式和脚本完全自包含,不依赖 BBC API、CDN 或 npm;仅当 JSON 明确提供受校验的媒体 URL 时加载图片、视频或网页。
|
||||
- 保留双层导航、搜索、快讯、直播弹窗、字幕切换、音频播放进度、移动抽屉、地区天气和订阅反馈。
|
||||
- 浏览器缓存以初始 JSON 指纹隔离;沙箱禁止持久存储时必须继续使用内嵌 JSON 正常渲染。
|
||||
+810
@@ -0,0 +1,810 @@
|
||||
(() => {
|
||||
"use strict";
|
||||
|
||||
const qs = (selector, root = document) => root.querySelector(selector);
|
||||
const qsa = (selector, root = document) => Array.from(root.querySelectorAll(selector));
|
||||
const clone = (value) => JSON.parse(JSON.stringify(value));
|
||||
const MODULES = ["site", "navigation", "breaking", "lead", "focus", "media", "moreNews", "regions", "newsletter", "footer"];
|
||||
const MODULE_META = {
|
||||
site: ["站点信息", "字标、标题、账户与日期"],
|
||||
navigation: ["导航", "全站、频道、搜索与抽屉"],
|
||||
breaking: ["快讯", "快讯标签、标题与时间"],
|
||||
lead: ["头条", "主报道与关联阅读"],
|
||||
focus: ["今日焦点", "焦点新闻宫格"],
|
||||
media: ["视听节目", "直播、字幕与新闻音频"],
|
||||
moreNews: ["更多新闻", "短新闻和热门排行"],
|
||||
regions: ["地区天气", "地区标题与城市天气"],
|
||||
newsletter: ["新闻简报", "订阅文案与反馈"],
|
||||
footer: ["页脚", "链接、版权与法律文案"]
|
||||
};
|
||||
const VISUAL_TYPES = new Set(["research-ship", "harbor", "satellite", "creative-city", "station", "studio", "bulletin", "ocean", "logistics", "market", "device", "energy"]);
|
||||
const embeddedData = JSON.parse(qs("#bbcPageData").textContent);
|
||||
const initialData = clone(embeddedData);
|
||||
|
||||
const fingerprint = (text) => {
|
||||
let hash = 2166136261;
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
hash ^= text.charCodeAt(index);
|
||||
hash = Math.imul(hash, 16777619);
|
||||
}
|
||||
return (hash >>> 0).toString(36);
|
||||
};
|
||||
const pageFingerprint = fingerprint(JSON.stringify(initialData));
|
||||
const storageKey = "bbc-page-data-v1:" + pageFingerprint;
|
||||
const themeKey = "bbc-page-theme-v1:" + pageFingerprint;
|
||||
|
||||
const readStorage = (key) => {
|
||||
try {
|
||||
return window.localStorage ? window.localStorage.getItem(key) : null;
|
||||
} catch (_error) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const writeStorage = (key, value) => {
|
||||
try {
|
||||
if (window.localStorage) window.localStorage.setItem(key, value);
|
||||
return true;
|
||||
} catch (_error) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const removeStorage = (key) => {
|
||||
try {
|
||||
if (window.localStorage) window.localStorage.removeItem(key);
|
||||
} catch (_error) {
|
||||
/* Opaque previews may intentionally deny storage. */
|
||||
}
|
||||
};
|
||||
const isObject = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value));
|
||||
const isCompleteData = (value) => Boolean(isObject(value) && MODULES.every((name) => isObject(value[name])));
|
||||
const cachedData = readStorage(storageKey);
|
||||
let pageData = initialData;
|
||||
if (cachedData) {
|
||||
try {
|
||||
const parsed = JSON.parse(cachedData);
|
||||
if (isCompleteData(parsed)) pageData = parsed;
|
||||
} catch (_error) {
|
||||
pageData = initialData;
|
||||
}
|
||||
}
|
||||
|
||||
const escapeHTML = (value) => String(value == null ? "" : value).replace(/[&<>'"]/g, (character) => ({
|
||||
"&": "&", "<": "<", ">": ">", "'": "'", '"': """
|
||||
})[character]);
|
||||
const safeHref = (value) => /^#[a-z0-9_-]+$/i.test(String(value || "")) ? escapeHTML(value) : "#top";
|
||||
const safeRemoteUrl = (value, kind = "link") => {
|
||||
const source = String(value || "").trim();
|
||||
if (!source) return "";
|
||||
const lowered = source.toLowerCase();
|
||||
if (kind === "image" && lowered.startsWith("data:image/")) return source;
|
||||
if (kind === "video" && lowered.startsWith("data:video/")) return source;
|
||||
try { const url = new URL(source); return ["http:", "https:"].includes(url.protocol) ? url.href : ""; }
|
||||
catch (_error) { return ""; }
|
||||
};
|
||||
const validateRemoteMediaTree = (value, path = "当前模块") => {
|
||||
if (Array.isArray(value)) return value.forEach((item, index) => validateRemoteMediaTree(item, path + "[" + index + "]"));
|
||||
if (!isObject(value)) return;
|
||||
const media = value.media;
|
||||
if (media && ["image", "video", "webpage"].includes(media.type)) {
|
||||
if (["image", "video"].includes(media.type) && !safeRemoteUrl(media.mediaUrl, media.type)) throw new Error(path + ".media.mediaUrl 无效");
|
||||
if (media.type === "webpage" && !safeRemoteUrl(media.pageUrl)) throw new Error(path + ".media.pageUrl 无效");
|
||||
if (media.posterUrl && !safeRemoteUrl(media.posterUrl, "image")) throw new Error(path + ".media.posterUrl 无效");
|
||||
}
|
||||
Object.entries(value).forEach(([key, item]) => { if (key !== "media") validateRemoteMediaTree(item, path + "." + key); });
|
||||
};
|
||||
const safeVisual = (value, fallback) => VISUAL_TYPES.has(value) ? value : fallback;
|
||||
const logoMarkup = () => (Array.isArray(pageData.site.brandLetters) ? pageData.site.brandLetters : ["B", "B", "C"])
|
||||
.map((letter) => "<span>" + escapeHTML(letter) + "</span>").join("");
|
||||
const toast = qs("#toast");
|
||||
let toastTimer = 0;
|
||||
const note = (message) => {
|
||||
if (document.body.classList.contains("settings-open")) {
|
||||
const status = qs("#jsonStatus");
|
||||
if (status) {
|
||||
status.textContent = message;
|
||||
status.className = "json-status valid";
|
||||
}
|
||||
return;
|
||||
}
|
||||
window.clearTimeout(toastTimer);
|
||||
toast.textContent = message;
|
||||
toast.classList.add("show");
|
||||
toastTimer = window.setTimeout(() => toast.classList.remove("show"), 2300);
|
||||
};
|
||||
const saveData = () => writeStorage(storageKey, JSON.stringify(pageData));
|
||||
|
||||
document.head.insertAdjacentHTML("beforeend", '<style data-external-media>.visual>img,.visual>video,.visual>iframe{width:100%;height:100%;display:block;border:0;object-fit:cover;background:#000}.visual>iframe{object-fit:initial}.visual .external-open{position:absolute;right:10px;bottom:10px;z-index:3;padding:7px 11px;border-radius:2px;color:#fff;background:rgba(0,0,0,.75);text-decoration:none;font-size:12px;font-weight:700}.visual .external-copy{position:absolute;left:10px;right:10px;bottom:10px;padding:10px;color:#fff;background:rgba(0,0,0,.75);text-decoration:none}.visual .external-copy strong,.visual .external-copy span{display:block}.visual .external-copy span{margin-top:3px;font-size:12px}</style>');
|
||||
const externalMediaMarkup = (media, label) => {
|
||||
if (!isObject(media)) return "";
|
||||
if (media.type === "image") {
|
||||
const source = safeRemoteUrl(media.mediaUrl, "image");
|
||||
if (!source) return "";
|
||||
const pageUrl = safeRemoteUrl(media.pageUrl);
|
||||
return '<img src="' + escapeHTML(source) + '" alt="' + escapeHTML(media.alt || label || "新闻图片") + '" loading="lazy" referrerpolicy="no-referrer"/>' + (pageUrl ? '<a class="external-open" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer">打开来源</a>' : "");
|
||||
}
|
||||
if (media.type === "video") {
|
||||
const source = safeRemoteUrl(media.mediaUrl, "video");
|
||||
if (!source) return "";
|
||||
const poster = safeRemoteUrl(media.posterUrl, "image");
|
||||
return '<video src="' + escapeHTML(source) + '"' + (poster ? ' poster="' + escapeHTML(poster) + '"' : "") + ' controls playsinline preload="metadata" aria-label="' + escapeHTML(media.alt || label || "新闻视频") + '"></video>';
|
||||
}
|
||||
if (media.type === "webpage") {
|
||||
const pageUrl = safeRemoteUrl(media.pageUrl);
|
||||
if (!pageUrl) return "";
|
||||
const preview = safeRemoteUrl(media.mediaUrl, "image");
|
||||
const body = media.embed === true ? '<iframe src="' + escapeHTML(pageUrl) + '" title="' + escapeHTML(media.title || "网页预览") + '" loading="lazy" referrerpolicy="no-referrer" sandbox="allow-forms allow-popups allow-scripts"></iframe>' : (preview ? '<img src="' + escapeHTML(preview) + '" alt="' + escapeHTML(media.alt || media.title || "网页预览图") + '" loading="lazy" referrerpolicy="no-referrer"/>' : "");
|
||||
return body + '<a class="external-copy" href="' + escapeHTML(pageUrl) + '" target="_blank" rel="noopener noreferrer"><strong>' + escapeHTML(media.title || label || "打开网页") + '</strong><span>' + escapeHTML(media.description || "新窗口打开") + "</span></a>";
|
||||
}
|
||||
return "";
|
||||
};
|
||||
const visualSvg = (requested, label) => {
|
||||
if (isObject(requested)) {
|
||||
const external = externalMediaMarkup(requested, label);
|
||||
if (external) return external;
|
||||
requested = "harbor";
|
||||
}
|
||||
const type = safeVisual(requested, "harbor");
|
||||
const title = escapeHTML(label || type);
|
||||
let background = "#cbd7d8";
|
||||
let content = "";
|
||||
if (type === "research-ship") {
|
||||
background = "#9fc5cf";
|
||||
content = '<circle cx="555" cy="88" r="48" fill="#f2e4b5"/><path d="M0 305c130-31 225-23 343 2 145 31 270 24 457-18v161H0Z" fill="#214e5d"/><path d="M0 345c148-31 255-20 363 7 126 31 274 20 437-18" stroke="#9fcbd0" stroke-opacity=".65" stroke-width="8" fill="none"/><g transform="translate(225 185)"><path d="M0 96h326l-49 73H49Z" fill="#edf0ed"/><path d="M70 50h154v46H70Z" fill="#e8e9e4"/><path d="M92 61h35v22H92Zm53 0h35v22h-35Zm53 0h20v22h-20Z" fill="#305160"/><path d="M149 50V7m0 0 59 43" stroke="#202c31" stroke-width="7"/><rect x="84" y="110" width="124" height="11" fill="#b80000"/></g>';
|
||||
} else if (type === "harbor") {
|
||||
background = "#ced9d9";
|
||||
content = '<path d="M0 300 145 168l102 73 168-128 285 205v132H0Z" fill="#72887b"/><path d="M0 366c151-55 298-59 448-17 116 33 186 28 252 11v90H0Z" fill="#3f6c58"/><path d="M120 332h470" stroke="#e1ded1" stroke-width="18"/><g fill="#303a3d"><rect x="205" y="270" width="116" height="74"/><rect x="367" y="247" width="136" height="97"/></g><g fill="#f5d27d"><rect x="226" y="286" width="22" height="25"/><rect x="272" y="286" width="22" height="25"/><rect x="394" y="268" width="25" height="29"/></g>';
|
||||
} else if (type === "satellite") {
|
||||
background = "#16191e";
|
||||
content = '<circle cx="370" cy="205" r="130" fill="#35536f"/><path d="M270 258c59-140 202-162 274-124-66 33-92 79-120 130-28 48-90 54-154-6Z" fill="#65a4bf"/><g fill="#fff"><circle cx="100" cy="87" r="4"/><circle cx="560" cy="72" r="3"/><circle cx="620" cy="310" r="4"/></g><path d="M85 365h530" stroke="#b80000" stroke-width="8"/>';
|
||||
} else if (type === "creative-city") {
|
||||
background = "#eadfc8";
|
||||
content = '<path d="M40 375h620" stroke="#27282a" stroke-width="14"/><rect x="125" y="115" width="170" height="258" fill="#554c43"/><rect x="365" y="65" width="195" height="308" fill="#6f665b"/><g fill="#eac170"><rect x="155" y="155" width="39" height="45"/><rect x="225" y="155" width="39" height="45"/><rect x="396" y="108" width="46" height="52"/><rect x="480" y="108" width="46" height="52"/><rect x="396" y="195" width="46" height="52"/></g>';
|
||||
} else if (type === "station") {
|
||||
background = "#b9d2d7";
|
||||
content = '<path d="M0 335c142-50 245-71 370-44 122 26 219 0 330-51v210H0Z" fill="#4e796c"/><path d="M155 310V135h390v175" fill="#e8e4da"/><path d="M125 135h450L497 65H203Z" fill="#a64436"/><path d="M205 178h95v132h-95Zm195 0h95v132h-95Z" fill="#345361"/>';
|
||||
} else if (type === "studio") {
|
||||
background = "#1f2c3b";
|
||||
content = '<path d="M0 352h700" stroke="#d13b3b" stroke-width="12"/><path d="M72 80h556v270H72Z" fill="none" stroke="#8395a8" stroke-opacity=".55" stroke-width="3"/><path d="M118 132h205v156H118Z" fill="#b80000"/><path d="M365 132h214v20H365Zm0 56h170v20H365Zm0 56h192v20H365Z" fill="#e8eaec" opacity=".82"/><circle cx="220" cy="210" r="47" fill="#e9d1bc"/>';
|
||||
} else if (type === "bulletin") {
|
||||
background = "#233344";
|
||||
content = '<circle cx="350" cy="225" r="150" fill="none" stroke="#7591aa" stroke-width="3"/><circle cx="350" cy="225" r="100" fill="#b80000"/><path d="M210 225h280M350 85v280" stroke="#fff" stroke-opacity=".7" stroke-width="7"/>';
|
||||
} else if (type === "ocean") {
|
||||
background = "#326779";
|
||||
content = '<g fill="#b9e5e8" opacity=".72"><circle cx="110" cy="95" r="10"/><circle cx="155" cy="145" r="6"/><circle cx="530" cy="82" r="8"/></g><path d="M70 365c105-72 190-61 275-29 102 38 190 23 280-25v139H70Z" fill="#153f43"/><path d="M300 95v215m0-165h125l35 47-160 12" stroke="#dce7df" stroke-width="13" fill="none"/>';
|
||||
} else if (type === "logistics") {
|
||||
background = "#dde4e0";
|
||||
content = '<path d="M70 380h560" stroke="#303a3c" stroke-width="18"/><path d="M170 360V125h360v235" fill="#758b8a"/><path d="M220 170h90v115h-90Zm165 0h90v115h-90Z" fill="#f0d48f"/>';
|
||||
} else if (type === "market") {
|
||||
background = "#d8cbb6";
|
||||
content = '<circle cx="350" cy="220" r="135" fill="#a5392f"/><path d="M130 370h440M175 320h350M225 270h250" stroke="#2d2b29" stroke-width="18"/>';
|
||||
} else if (type === "device") {
|
||||
background = "#163143";
|
||||
content = '<path d="M75 350 210 235l110 58 150-190 150 98" stroke="#71c7dd" stroke-width="22" fill="none"/><circle cx="470" cy="103" r="23" fill="#fff"/>';
|
||||
} else {
|
||||
background = "#c8d9d1";
|
||||
content = '<path d="M0 330c175-94 365-106 700-3v123H0Z" fill="#47705a"/><g fill="#edf0e7"><rect x="120" y="170" width="86" height="180"/><rect x="292" y="105" width="98" height="245"/><rect x="500" y="195" width="75" height="155"/></g>';
|
||||
}
|
||||
return '<svg viewBox="0 0 700 450" preserveAspectRatio="xMidYMid slice" role="img" aria-label="' + title + '"><rect width="700" height="450" fill="' + background + '"/>' + content + "</svg>";
|
||||
};
|
||||
|
||||
let themeInitialized = false;
|
||||
const applyInitialTheme = () => {
|
||||
if (themeInitialized) return;
|
||||
themeInitialized = true;
|
||||
const configured = pageData.site.theme;
|
||||
const stored = readStorage(themeKey);
|
||||
const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme:dark)").matches;
|
||||
const dark = stored === "dark" || (!stored && (configured === "dark" || (configured === "auto" && prefersDark)));
|
||||
document.body.classList.toggle("dark", dark);
|
||||
syncThemeLabel();
|
||||
};
|
||||
const syncThemeLabel = () => {
|
||||
qs("#theme").setAttribute("aria-label", document.body.classList.contains("dark") ? "切换浅色模式" : "切换深色模式");
|
||||
};
|
||||
const toggleTheme = () => {
|
||||
const dark = document.body.classList.toggle("dark");
|
||||
writeStorage(themeKey, dark ? "dark" : "light");
|
||||
syncThemeLabel();
|
||||
note(dark ? "深色模式已开启" : "浅色模式已开启");
|
||||
};
|
||||
|
||||
const renderSite = () => {
|
||||
const site = pageData.site || {};
|
||||
document.title = site.pageTitle || "BBC 新闻";
|
||||
qs('meta[name="description"]').content = site.description || "";
|
||||
const logo = logoMarkup();
|
||||
qs("#brandLogo").innerHTML = logo;
|
||||
qs("#brandLogo").setAttribute("aria-label", (site.brandLetters || []).join("") + " 首页");
|
||||
qs("#drawerLogo").innerHTML = logo;
|
||||
qs("#footerLogo").innerHTML = logo;
|
||||
qs("#accountLabel").textContent = site.accountLabel || "";
|
||||
qs("#pageDate").textContent = site.updatedDate || "";
|
||||
applyInitialTheme();
|
||||
};
|
||||
|
||||
const navMarkup = (items, activeFirst) => (Array.isArray(items) ? items : []).map((item, index) =>
|
||||
'<a class="' + (activeFirst && index === 0 ? "active" : "") + '" href="' + safeHref(item.href) + '">' +
|
||||
escapeHTML(item.label) + "</a>"
|
||||
).join("");
|
||||
const renderNavigation = () => {
|
||||
const data = pageData.navigation || {};
|
||||
qs("#globalNav").innerHTML = navMarkup(data.global, false);
|
||||
qs("#channelTitle").textContent = data.channelTitle || "";
|
||||
qs("#channelNav").innerHTML = navMarkup(data.channel, true) +
|
||||
'<a class="more-link" href="#more">' + escapeHTML(data.moreLabel) +
|
||||
' <svg viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg></a>';
|
||||
qs("#searchLabel").textContent = data.searchLabel || "";
|
||||
qs("#search").placeholder = data.searchPlaceholder || "";
|
||||
qs("#searchButton").textContent = data.searchButton || "";
|
||||
qs("#drawerLinks").innerHTML = navMarkup(data.drawer, false);
|
||||
};
|
||||
|
||||
const renderBreaking = () => {
|
||||
const data = pageData.breaking || {};
|
||||
qs("#breakingLabel").textContent = data.label || "";
|
||||
qs("#breakingText").textContent = data.text || "";
|
||||
qs("#breakingTime").textContent = data.time || "";
|
||||
};
|
||||
|
||||
const renderLead = () => {
|
||||
const data = pageData.lead || {};
|
||||
const related = Array.isArray(data.related) ? data.related : [];
|
||||
qs("#leadLayout").innerHTML = '<div class="lead-copy"><div class="label">' + escapeHTML(data.kicker) +
|
||||
"</div><h1>" + escapeHTML(data.title) + '</h1><p class="dek">' + escapeHTML(data.summary) +
|
||||
'</p><ul class="headline-links">' + related.map((item) =>
|
||||
'<li><a href="' + safeHref(item.href) + '">' + escapeHTML(item.label) + "</a></li>"
|
||||
).join("") + '</ul><div class="meta"><strong>' + escapeHTML(data.byline) + "</strong><span>" +
|
||||
escapeHTML(data.time) + '</span><a href="' + safeHref(data.sectionHref) + '">' + escapeHTML(data.section) +
|
||||
'</a></div></div><div class="visual lead-visual">' + visualSvg(data.media || data.visual, data.visualLabel) +
|
||||
'<span class="live-stamp">' + escapeHTML(data.stamp) + '</span><span class="credit">' +
|
||||
escapeHTML(data.credit) + "</span></div>";
|
||||
};
|
||||
|
||||
const renderFocus = () => {
|
||||
const data = pageData.focus || {};
|
||||
qs("#focusTitle").textContent = data.title || "";
|
||||
qs("#focusMore").textContent = data.moreLabel || "";
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#focusGrid").innerHTML = items.map((item, index) =>
|
||||
'<article class="story' + (index === 0 ? " feature" : "") + '"><div class="visual story-media">' +
|
||||
visualSvg(item.media || item.visual, item.title) + '</div><div class="label">' + escapeHTML(item.kicker) +
|
||||
"</div><" + (index === 0 ? "h2" : "h3") + '><a href="' + safeHref(item.href) + '">' +
|
||||
escapeHTML(item.title) + "</a></" + (index === 0 ? "h2" : "h3") + ">" +
|
||||
(item.summary ? "<p>" + escapeHTML(item.summary) + "</p>" : "") +
|
||||
'<div class="meta"><span>' + escapeHTML(item.time) + '</span><a href="' + safeHref(item.href) + '">' +
|
||||
escapeHTML(item.section) + "</a></div></article>"
|
||||
).join("");
|
||||
};
|
||||
|
||||
let playing = false;
|
||||
let audioSeconds = 0;
|
||||
let audioTimer = 0;
|
||||
const stopAudio = (reset) => {
|
||||
window.clearInterval(audioTimer);
|
||||
playing = false;
|
||||
const button = qs("#audioPlay");
|
||||
if (button) {
|
||||
button.classList.remove("playing");
|
||||
button.setAttribute("aria-label", "播放今日新闻播客");
|
||||
}
|
||||
if (reset) {
|
||||
audioSeconds = 0;
|
||||
if (qs("#audioTime")) qs("#audioTime").textContent = "00:00";
|
||||
if (qs("#audioBar")) qs("#audioBar").style.width = "0%";
|
||||
}
|
||||
};
|
||||
const renderMedia = () => {
|
||||
stopAudio(true);
|
||||
const data = pageData.media || {};
|
||||
qs("#mediaTitle").textContent = data.title || "";
|
||||
qs("#mediaMore").textContent = data.moreLabel || "";
|
||||
const videos = Array.isArray(data.videos) ? data.videos : [];
|
||||
qs("#mediaGrid").innerHTML = videos.map((item) =>
|
||||
'<article class="live-card" data-video-id="' + escapeHTML(item.id) + '"><button class="visual story-media open-live" aria-label="播放' +
|
||||
escapeHTML(item.title) + '">' + visualSvg(item.media || item.visual, item.title) +
|
||||
'<span class="play"><svg viewBox="0 0 24 24"><path d="m7 4 13 8-13 8Z"/></svg></span></button><h3>' +
|
||||
escapeHTML(item.title) + '</h3><div class="live-meta">' +
|
||||
(item.live ? '<span class="live-now">正在直播</span> · ' + escapeHTML(String(item.meta || "").replace(/^正在直播\s*·\s*/, "")) : escapeHTML(item.meta)) +
|
||||
"</div></article>"
|
||||
).join("");
|
||||
const modal = data.modal || {};
|
||||
qs("#liveTitle").textContent = modal.title || "";
|
||||
qs("#streamTitle").textContent = modal.streamTitle || "";
|
||||
qs("#streamSubtitle").textContent = modal.streamSubtitle || "";
|
||||
qs("#currentProgram").textContent = modal.currentProgram || "";
|
||||
const audio = data.audio || {};
|
||||
qs("#audioTitle").textContent = audio.sectionTitle || "";
|
||||
qs("#audioName").textContent = audio.title || "";
|
||||
qs("#audioMeta").textContent = audio.meta || "";
|
||||
qs("#audioDuration").textContent = audio.durationLabel || "";
|
||||
};
|
||||
|
||||
const renderMoreNews = () => {
|
||||
const data = pageData.moreNews || {};
|
||||
qs("#moreTitle").textContent = data.title || "";
|
||||
qs("#moreLink").textContent = data.moreLabel || "";
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#moreList").innerHTML = items.map((item) =>
|
||||
'<article class="compact"><div class="visual compact-media">' + visualSvg(item.media || item.visual, item.title) +
|
||||
'</div><div><div class="label">' + escapeHTML(item.kicker) + "</div><h3>" +
|
||||
escapeHTML(item.title) + '</h3><div class="meta">' + escapeHTML(item.time) + "</div></div></article>"
|
||||
).join("");
|
||||
qs("#rankingTitle").textContent = data.rankingTitle || "";
|
||||
const ranking = Array.isArray(data.ranking) ? data.ranking : [];
|
||||
qs("#rankingList").innerHTML = ranking.map((item, index) =>
|
||||
'<div class="rank-item"><span class="rank">' + (index + 1) + '</span><a href="' +
|
||||
safeHref(item.href) + '">' + escapeHTML(item.title) + "</a></div>"
|
||||
).join("");
|
||||
};
|
||||
|
||||
const renderRegions = () => {
|
||||
const data = pageData.regions || {};
|
||||
qs("#regionsTitle").textContent = data.title || "";
|
||||
qs("#regionsMore").textContent = data.moreLabel || "";
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#regionsGrid").innerHTML = items.map((item) =>
|
||||
'<div class="region"><strong>' + escapeHTML(item.region) + '</strong><a href="#regions">' +
|
||||
escapeHTML(item.title) + "</a></div>"
|
||||
).join("");
|
||||
qs("#weatherTitle").textContent = data.weatherTitle || "";
|
||||
const weather = Array.isArray(data.weather) ? data.weather : [];
|
||||
qs("#weatherGrid").innerHTML = '<div class="weather-title">' + escapeHTML(data.weatherLabel) + "</div>" +
|
||||
weather.map((item) => '<div class="city"><b>' + escapeHTML(item.city) + '</b><div class="temp">' +
|
||||
escapeHTML(item.temperature) + '</div><div class="condition">' + escapeHTML(item.condition) + "</div></div>"
|
||||
).join("");
|
||||
};
|
||||
|
||||
const renderNewsletter = () => {
|
||||
const data = pageData.newsletter || {};
|
||||
qs("#newsletterTitle").textContent = data.title || "";
|
||||
qs("#newsletterText").textContent = data.text || "";
|
||||
qs("#email").placeholder = data.placeholder || "";
|
||||
qs("#newsletterButton").textContent = data.button || "";
|
||||
};
|
||||
|
||||
const renderFooter = () => {
|
||||
const data = pageData.footer || {};
|
||||
const links = Array.isArray(data.links) ? data.links : [];
|
||||
qs("#footerLinks").innerHTML = links.map((item) =>
|
||||
'<a href="' + safeHref(item.href) + '">' + escapeHTML(item.label) + "</a>"
|
||||
).join("");
|
||||
qs("#copyright").textContent = data.copyright || "";
|
||||
qs("#legal").textContent = data.legal || "";
|
||||
};
|
||||
|
||||
const renderAll = () => {
|
||||
renderSite();
|
||||
renderNavigation();
|
||||
renderBreaking();
|
||||
renderLead();
|
||||
renderFocus();
|
||||
renderMedia();
|
||||
renderMoreNews();
|
||||
renderRegions();
|
||||
renderNewsletter();
|
||||
renderFooter();
|
||||
bindDynamicInteractions();
|
||||
};
|
||||
|
||||
const modal = qs("#liveModal");
|
||||
let lastFocus = null;
|
||||
function openLive() {
|
||||
lastFocus = document.activeElement;
|
||||
modal.classList.add("open");
|
||||
document.body.style.overflow = "hidden";
|
||||
qs("#liveClose").focus();
|
||||
}
|
||||
const closeLive = () => {
|
||||
modal.classList.remove("open");
|
||||
document.body.style.overflow = "";
|
||||
if (lastFocus) lastFocus.focus();
|
||||
};
|
||||
const drawer = qs("#drawer");
|
||||
const openMenu = () => {
|
||||
drawer.classList.add("open");
|
||||
document.body.style.overflow = "hidden";
|
||||
qs("#menuClose").focus();
|
||||
};
|
||||
const closeMenu = () => {
|
||||
drawer.classList.remove("open");
|
||||
document.body.style.overflow = "";
|
||||
qs("#menuOpen").focus();
|
||||
};
|
||||
const bindDynamicInteractions = () => {
|
||||
qsa(".open-live").forEach((button) => {
|
||||
if (button.dataset.liveBound) return;
|
||||
button.dataset.liveBound = "true";
|
||||
button.addEventListener("click", openLive);
|
||||
});
|
||||
qsa(".drawer-links a").forEach((link) => link.addEventListener("click", closeMenu));
|
||||
};
|
||||
|
||||
qs("#theme").addEventListener("click", toggleTheme);
|
||||
qs("#searchOpen").addEventListener("click", () => {
|
||||
const area = qs("#searchArea");
|
||||
area.classList.toggle("open");
|
||||
if (area.classList.contains("open")) window.setTimeout(() => qs("#search").focus(), 20);
|
||||
});
|
||||
qs("#searchForm").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const queryRaw = qs("#search").value.trim();
|
||||
const query = queryRaw.toLocaleLowerCase();
|
||||
const corpus = [
|
||||
pageData.breaking.text,
|
||||
pageData.lead.title,
|
||||
pageData.lead.summary,
|
||||
...(pageData.lead.related || []).map((item) => item.label),
|
||||
...(pageData.focus.items || []).flatMap((item) => [item.title, item.summary]),
|
||||
...(pageData.media.videos || []).map((item) => item.title),
|
||||
pageData.media.audio.title,
|
||||
...(pageData.moreNews.items || []).map((item) => item.title),
|
||||
...(pageData.moreNews.ranking || []).map((item) => item.title),
|
||||
...(pageData.regions.items || []).map((item) => item.title)
|
||||
];
|
||||
const count = query ? corpus.filter((value) => String(value || "").toLocaleLowerCase().includes(query)).length : 0;
|
||||
const result = qs("#searchResult");
|
||||
result.classList.add("show");
|
||||
result.textContent = query ? "与“" + queryRaw + "”相关的报道:共 " + count + " 条" : "请输入搜索内容";
|
||||
});
|
||||
qs("#liveClose").addEventListener("click", closeLive);
|
||||
modal.addEventListener("click", (event) => {
|
||||
if (event.target === modal) closeLive();
|
||||
});
|
||||
qs("#caption").addEventListener("click", (event) => {
|
||||
const on = event.currentTarget.textContent.includes("开");
|
||||
event.currentTarget.textContent = "CC 字幕:" + (on ? "关" : "开");
|
||||
note(on ? "字幕已关闭" : "字幕已开启");
|
||||
});
|
||||
qs("#menuOpen").addEventListener("click", openMenu);
|
||||
qs("#menuClose").addEventListener("click", closeMenu);
|
||||
drawer.addEventListener("click", (event) => {
|
||||
if (event.target === drawer) closeMenu();
|
||||
});
|
||||
qs("#audioPlay").addEventListener("click", () => {
|
||||
const audio = pageData.media.audio || {};
|
||||
const duration = Math.max(1, Number(audio.durationSeconds) || 1);
|
||||
playing = !playing;
|
||||
qs("#audioPlay").classList.toggle("playing", playing);
|
||||
qs("#audioPlay").setAttribute("aria-label", playing ? "暂停今日新闻播客" : "播放今日新闻播客");
|
||||
window.clearInterval(audioTimer);
|
||||
if (!playing) return;
|
||||
audioTimer = window.setInterval(() => {
|
||||
audioSeconds = Math.min(audioSeconds + 1, duration);
|
||||
qs("#audioBar").style.width = (audioSeconds / duration * 100) + "%";
|
||||
qs("#audioTime").textContent = String(Math.floor(audioSeconds / 60)).padStart(2, "0") + ":" + String(audioSeconds % 60).padStart(2, "0");
|
||||
if (audioSeconds >= duration) stopAudio(false);
|
||||
}, 1000);
|
||||
});
|
||||
qs("#subForm").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const email = qs("#email").value.trim();
|
||||
qs("#subStatus").textContent = (pageData.newsletter.successPrefix || "") + " " + email;
|
||||
event.currentTarget.reset();
|
||||
});
|
||||
|
||||
const settingsOverlay = qs("#settingsOverlay");
|
||||
const jsonEditor = qs("#jsonEditor");
|
||||
const jsonStatus = qs("#jsonStatus");
|
||||
let activeModule = MODULES[0];
|
||||
let editorDraft = clone(pageData);
|
||||
const validateEditor = () => {
|
||||
try {
|
||||
const parsed = JSON.parse(jsonEditor.value);
|
||||
if (!isObject(parsed)) throw new Error("模块必须是 JSON 对象");
|
||||
validateRemoteMediaTree(parsed);
|
||||
jsonStatus.textContent = "JSON 有效";
|
||||
jsonStatus.className = "json-status valid";
|
||||
return parsed;
|
||||
} catch (error) {
|
||||
jsonStatus.textContent = "JSON 无效:" + error.message;
|
||||
jsonStatus.className = "json-status invalid";
|
||||
return null;
|
||||
}
|
||||
};
|
||||
const storeActiveDraft = () => {
|
||||
const parsed = validateEditor();
|
||||
if (!parsed) return false;
|
||||
editorDraft[activeModule] = parsed;
|
||||
return true;
|
||||
};
|
||||
const selectModule = (name, force) => {
|
||||
if (!force && !storeActiveDraft()) return;
|
||||
activeModule = name;
|
||||
qsa(".module-tab").forEach((tab) => tab.classList.toggle("active", tab.dataset.module === name));
|
||||
qs("#editorModuleTitle").textContent = MODULE_META[name][0];
|
||||
jsonEditor.value = JSON.stringify(editorDraft[name], null, 2);
|
||||
validateEditor();
|
||||
};
|
||||
const renderModuleTabs = () => {
|
||||
qs("#moduleTabs").innerHTML = "<h3>页面模块</h3>" + MODULES.map((name) =>
|
||||
'<button class="module-tab' + (name === activeModule ? " active" : "") + '" data-module="' + name +
|
||||
'"><strong>' + MODULE_META[name][0] + "</strong><span>" + MODULE_META[name][1] + "</span></button>"
|
||||
).join("");
|
||||
qsa(".module-tab").forEach((tab) => tab.addEventListener("click", () => selectModule(tab.dataset.module, false)));
|
||||
};
|
||||
const openSettings = () => {
|
||||
editorDraft = clone(pageData);
|
||||
activeModule = MODULES[0];
|
||||
renderModuleTabs();
|
||||
selectModule(activeModule, true);
|
||||
settingsOverlay.classList.add("open");
|
||||
settingsOverlay.setAttribute("aria-hidden", "false");
|
||||
document.body.classList.add("settings-open");
|
||||
document.body.style.overflow = "hidden";
|
||||
window.setTimeout(() => jsonEditor.focus(), 80);
|
||||
};
|
||||
const closeSettings = () => {
|
||||
settingsOverlay.classList.remove("open");
|
||||
settingsOverlay.setAttribute("aria-hidden", "true");
|
||||
document.body.classList.remove("settings-open");
|
||||
document.body.style.overflow = "";
|
||||
qs("#openSettings").focus();
|
||||
};
|
||||
qs("#openSettings").addEventListener("click", openSettings);
|
||||
qs("#closeSettings").addEventListener("click", closeSettings);
|
||||
settingsOverlay.addEventListener("click", (event) => {
|
||||
if (event.target === settingsOverlay) closeSettings();
|
||||
});
|
||||
jsonEditor.addEventListener("input", validateEditor);
|
||||
jsonEditor.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Tab") {
|
||||
event.preventDefault();
|
||||
jsonEditor.setRangeText(" ", jsonEditor.selectionStart, jsonEditor.selectionEnd, "end");
|
||||
validateEditor();
|
||||
}
|
||||
});
|
||||
qs("#applyJson").addEventListener("click", () => {
|
||||
if (!storeActiveDraft() || !isCompleteData(editorDraft)) {
|
||||
note("请修正 JSON 后再应用");
|
||||
return;
|
||||
}
|
||||
pageData = clone(editorDraft);
|
||||
saveData();
|
||||
renderAll();
|
||||
note("JSON 已应用到页面");
|
||||
});
|
||||
qs("#resetJson").addEventListener("click", () => {
|
||||
pageData = clone(initialData);
|
||||
editorDraft = clone(initialData);
|
||||
removeStorage(storageKey);
|
||||
removeStorage(themeKey);
|
||||
themeInitialized = false;
|
||||
renderAll();
|
||||
renderModuleTabs();
|
||||
selectModule(activeModule, true);
|
||||
note("已恢复初始 JSON");
|
||||
});
|
||||
qs("#copyJson").addEventListener("click", async () => {
|
||||
if (!storeActiveDraft()) return;
|
||||
const text = JSON.stringify(editorDraft, null, 2);
|
||||
try {
|
||||
if (navigator.clipboard) await navigator.clipboard.writeText(text);
|
||||
note("完整 JSON 已复制");
|
||||
} catch (_error) {
|
||||
jsonEditor.focus();
|
||||
jsonEditor.select();
|
||||
note("已选中当前模块,请手动复制");
|
||||
}
|
||||
});
|
||||
qs("#downloadJson").addEventListener("click", () => {
|
||||
if (!storeActiveDraft()) return;
|
||||
const blob = new Blob([JSON.stringify(editorDraft, null, 2) + "\n"], {type: "application/json"});
|
||||
const link = document.createElement("a");
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = "bbc-page-data.json";
|
||||
link.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(link.href), 0);
|
||||
note("JSON 已下载");
|
||||
});
|
||||
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape") {
|
||||
if (modal.classList.contains("open")) closeLive();
|
||||
if (drawer.classList.contains("open")) closeMenu();
|
||||
if (settingsOverlay.classList.contains("open")) closeSettings();
|
||||
}
|
||||
});
|
||||
|
||||
renderAll();
|
||||
function installJsonMediaUpload(){
|
||||
const editor=document.getElementById("jsonEditor"),apply=document.getElementById("applyJson");if(!editor||!apply||document.getElementById("uploadJsonMedia"))return;
|
||||
const actions=apply.parentElement,button=document.createElement("button"),input=document.createElement("input"),reference=actions.querySelector("#downloadJson,#copyJson,#validateJson,#resetJson");button.type="button";button.id="uploadJsonMedia";button.className=reference?reference.className:apply.className;button.textContent="上传图片/视频";button.title="先把光标放进要替换的内容对象,再选择图片或视频";input.type="file";input.accept="image/*,video/*";input.hidden=true;actions.insertBefore(button,apply);actions.appendChild(input);
|
||||
const report=(message)=>{const status=document.getElementById("settingsStatus")||document.getElementById("jsonError")||document.getElementById("jsonStatus");if(status)status.textContent=message};
|
||||
const findTarget=(text,cursor)=>{const stack=[],matches=[];let quoted=false,escaped=false;for(let index=0;index<text.length;index+=1){const char=text[index];if(quoted){if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char==='"')quoted=false;continue}if(char==='"'){quoted=true;continue}if(char==="{")stack.push(index);else if(char==="}"){const start=stack.pop();if(start===undefined||cursor<start||cursor>index+1)continue;try{const value=JSON.parse(text.slice(start,index+1)),own=(key)=>Object.prototype.hasOwnProperty.call(value,key);if(value&&!Array.isArray(value)&&(own("media")||own("visual")||(own("id")&&(own("text")||own("title"))&&(own("author")||own("channel")||own("user")))))matches.push({start,end:index+1,value})}catch(_error){/* full validator handles malformed JSON */}}}return matches.sort((left,right)=>(left.end-left.start)-(right.end-right.start))[0]||null};
|
||||
button.addEventListener("click",()=>{input.value="";report("请选择图片或视频;文件会写入光标所在内容对象的 media 字段。");input.click()});
|
||||
input.addEventListener("change",()=>{const file=input.files&&input.files[0];if(!file)return;const type=file.type.startsWith("image/")?"image":file.type.startsWith("video/")?"video":"";if(!type){report("仅支持图片或视频文件。");return}const target=findTarget(editor.value,editor.selectionStart);if(!target){report("请先把光标放进带 visual/media 的内容对象,或带 id 的帖子/视频对象内。");return}const reader=new FileReader();reader.onerror=()=>report("文件读取失败,请重新选择。");reader.onload=()=>{const previous=target.value.media&&typeof target.value.media==="object"?target.value.media:{},media={type,mediaUrl:String(reader.result)};for(const key of ["alt","label","caption","pageUrl"])if(typeof previous[key]==="string")media[key]=previous[key];if(!media.alt)media.alt=type==="image"?"用户上传的图片":"用户上传的视频";target.value.media=media;const lineStart=editor.value.lastIndexOf("\n",target.start-1)+1,indent=(editor.value.slice(lineStart,target.start).match(/^\s*/)||[""])[0],replacement=JSON.stringify(target.value,null,2).split("\n").map((line,index)=>index?indent+line:line).join("\n");editor.value=editor.value.slice(0,target.start)+replacement+editor.value.slice(target.end);editor.dispatchEvent(new Event("input",{bubbles:true}));const mediaIndex=replacement.indexOf('"media"');editor.focus();editor.setSelectionRange(target.start+Math.max(mediaIndex,0),target.start+Math.max(mediaIndex,0));report(`已把 ${file.name} 写入 JSON,请点击“应用并渲染”。${file.size>2*1024*1024?" 文件较大,建议同时下载 JSON 保存。":""}`)};reader.readAsDataURL(file)});
|
||||
}
|
||||
installJsonMediaUpload();
|
||||
function installInlineMediaReplace() {
|
||||
if (document.getElementById("dfInlineMediaInput")) return;
|
||||
const visualHostSelector = ".post-media,.video-visual,.thumbnail-visual,.short-thumb,.watch-visual,.thread-media,.visual,.lead-visual,.mini-visual,.compact-media,.card-art,.story-visual,.art,.video-art,.media-art,.player-stage,.thumbnail,.thumb,.list-thumb,.focus-thumb,.involve-bg,.hero-art,#heroArt,#adminArt";
|
||||
const getRootData = () => {
|
||||
if (typeof pageData !== "undefined") return pageData;
|
||||
if (typeof data !== "undefined") return data;
|
||||
return null;
|
||||
};
|
||||
const input = document.createElement("input");
|
||||
input.id = "dfInlineMediaInput";
|
||||
input.type = "file";
|
||||
input.hidden = true;
|
||||
document.body.appendChild(input);
|
||||
const style = document.createElement("style");
|
||||
style.dataset.dfInlineMediaReplace = "true";
|
||||
style.textContent = ".df-inline-media-host{position:relative!important}.df-inline-media-button{position:absolute;z-index:40;top:10px;right:10px;width:40px;height:40px;padding:0;border:1px solid rgba(255,255,255,.55);border-radius:50%;display:grid;place-items:center;color:#fff;background:rgba(8,15,28,.78);box-shadow:0 8px 24px rgba(0,0,0,.28);backdrop-filter:blur(8px);cursor:pointer;opacity:0;transform:translateY(-4px);transition:opacity .16s,transform .16s,background .16s}.df-inline-media-button:hover{background:rgba(20,110,240,.92)}.df-inline-media-button svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}.df-inline-media-host:hover>.df-inline-media-button,.df-inline-media-host:focus-within>.df-inline-media-button,.df-inline-media-button:focus-visible{opacity:1;transform:none}@media(hover:none){.df-inline-media-button{opacity:1;transform:none}}.df-inline-media-toast{position:fixed;z-index:2147483647;left:50%;bottom:28px;max-width:min(88vw,520px);padding:10px 14px;border-radius:10px;color:#fff;background:rgba(15,23,42,.94);box-shadow:0 12px 32px rgba(0,0,0,.28);font:600 13px/1.45 system-ui,sans-serif;transform:translateX(-50%)}";
|
||||
document.head.appendChild(style);
|
||||
const notify = (message) => {
|
||||
if (typeof showToast === "function") { showToast(message); return; }
|
||||
if (typeof toast === "function") { toast(message); return; }
|
||||
let notice = document.getElementById("dfInlineMediaToast");
|
||||
if (!notice) {
|
||||
notice = document.createElement("div");
|
||||
notice.id = "dfInlineMediaToast";
|
||||
notice.className = "df-inline-media-toast";
|
||||
document.body.appendChild(notice);
|
||||
}
|
||||
notice.textContent = message;
|
||||
window.clearTimeout(notice._timer);
|
||||
notice._timer = window.setTimeout(() => notice.remove(), 2600);
|
||||
};
|
||||
const sameSource = (value, source, absolute) => {
|
||||
if (typeof value !== "string") return false;
|
||||
if (value === source || value === absolute) return true;
|
||||
try { return new URL(value, location.href).href === absolute; } catch (_error) { return false; }
|
||||
};
|
||||
const findMatches = (source, absolute) => {
|
||||
const matches = [];
|
||||
const stack = [];
|
||||
const visit = (value) => {
|
||||
if (Array.isArray(value)) { value.forEach(visit); return; }
|
||||
if (!value || typeof value !== "object") return;
|
||||
stack.push(value);
|
||||
Object.entries(value).forEach(([key, item]) => {
|
||||
if ((key === "mediaUrl" || key === "posterUrl") && sameSource(item, source, absolute)) {
|
||||
const ancestors = stack.slice(0, -1).reverse();
|
||||
const owner = ancestors.find((candidate) => candidate && typeof candidate === "object" && !Array.isArray(candidate) && ("id" in candidate || "title" in candidate || "text" in candidate || "name" in candidate || "author" in candidate)) || ancestors[0] || value;
|
||||
matches.push({ owner, previous: value, key });
|
||||
}
|
||||
if (item && typeof item === "object") visit(item);
|
||||
});
|
||||
stack.pop();
|
||||
};
|
||||
visit(getRootData());
|
||||
return matches;
|
||||
};
|
||||
const visualOwners = () => {
|
||||
const owners = [];
|
||||
const seen = new Set();
|
||||
const visit = (value) => {
|
||||
if (Array.isArray(value)) { value.forEach(visit); return; }
|
||||
if (!value || typeof value !== "object") return;
|
||||
const hasVisual = Object.prototype.hasOwnProperty.call(value, "visual") || (value.media && typeof value.media === "object");
|
||||
const hasIdentity = ["id", "title", "text", "leadTitle", "feature", "name", "author"].some((key) => typeof value[key] === "string" && value[key].trim());
|
||||
if (hasVisual && hasIdentity && !seen.has(value)) { seen.add(value); owners.push(value); }
|
||||
Object.values(value).forEach((item) => { if (item && typeof item === "object") visit(item); });
|
||||
};
|
||||
visit(getRootData());
|
||||
return owners;
|
||||
};
|
||||
const domIdentifiers = (element) => {
|
||||
const values = new Set();
|
||||
let cursor = element;
|
||||
for (let depth = 0; cursor && cursor !== document.body && depth < 8; depth += 1, cursor = cursor.parentElement) {
|
||||
Object.values(cursor.dataset || {}).forEach((value) => { if (value) values.add(String(value)); });
|
||||
}
|
||||
return values;
|
||||
};
|
||||
const chooseVisualTarget = (element) => {
|
||||
const identifiers = domIdentifiers(element);
|
||||
const context = element.closest("article,button,[data-post-id],[data-video-id],[data-short-id],.post,.video-card,.news-card,.story-card,.lead-story,.hero") || element.parentElement || element;
|
||||
const contextText = String(context.textContent || "").replace(/\s+/g, " ").trim();
|
||||
const visualNode = element.closest("[data-visual]") || element.querySelector && element.querySelector("[data-visual]");
|
||||
const visualValue = visualNode && visualNode.dataset ? visualNode.dataset.visual : "";
|
||||
let best = null;
|
||||
let bestScore = 0;
|
||||
visualOwners().forEach((owner) => {
|
||||
let score = 0;
|
||||
Object.entries(owner).forEach(([key, value]) => {
|
||||
if (/id$/i.test(key) && identifiers.has(String(value))) score += 100;
|
||||
});
|
||||
["title", "text", "leadTitle", "feature", "visualLabel", "label", "author", "name", "summary"].forEach((key) => {
|
||||
const value = typeof owner[key] === "string" ? owner[key].trim() : "";
|
||||
if (value.length >= 2 && contextText.includes(value)) score += Math.min(40, value.length);
|
||||
});
|
||||
if (visualValue && owner.visual === visualValue) score += 20;
|
||||
if (score > bestScore) { best = owner; bestScore = score; }
|
||||
});
|
||||
if (!best || bestScore <= 0) return null;
|
||||
return { owner: best, previous: best.media && typeof best.media === "object" ? best.media : { type: "image" }, key: "mediaUrl" };
|
||||
};
|
||||
const chooseTarget = (element) => {
|
||||
const source = element.getAttribute("src") || "";
|
||||
const absolute = element.currentSrc || element.src || source;
|
||||
const matches = findMatches(source, absolute);
|
||||
if (!matches.length) return null;
|
||||
const identifiers = domIdentifiers(element);
|
||||
return matches.find(({ owner }) => Object.entries(owner).some(([key, value]) => /id$/i.test(key) && identifiers.has(String(value)))) || matches[0];
|
||||
};
|
||||
const persist = () => {
|
||||
const root = getRootData();
|
||||
if (typeof saveData === "function") return saveData();
|
||||
if (typeof writeStorage === "function" && typeof storageKey !== "undefined") return writeStorage(storageKey, JSON.stringify(root));
|
||||
if (typeof writeStorage === "function" && typeof dataKey !== "undefined") return writeStorage(dataKey, JSON.stringify(root));
|
||||
return false;
|
||||
};
|
||||
let active = null;
|
||||
const attachButton = (host, target) => {
|
||||
if (!host || !target || host.querySelector(":scope > .df-inline-media-button")) return;
|
||||
host.classList.add("df-inline-media-host");
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "df-inline-media-button";
|
||||
button.setAttribute("aria-label", "替换图片或视频");
|
||||
button.title = "上传图片或视频并替换";
|
||||
button.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 16V4m0 0L7.5 8.5M12 4l4.5 4.5"/><path d="M5 14v4a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4"/></svg>';
|
||||
button.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
active = { ...target };
|
||||
input.accept = "image/*,video/*";
|
||||
input.value = "";
|
||||
input.click();
|
||||
});
|
||||
host.appendChild(button);
|
||||
};
|
||||
const decorateBuiltInVisuals = () => {
|
||||
document.querySelectorAll(visualHostSelector).forEach((host) => {
|
||||
if (host.querySelector("img[src],video[src],iframe[src],:scope > .df-inline-media-button")) return;
|
||||
if (!host.querySelector("svg") && !host.dataset.visual) return;
|
||||
const target = chooseVisualTarget(host);
|
||||
if (!target) return;
|
||||
attachButton(host, target);
|
||||
});
|
||||
};
|
||||
const decorate = () => {
|
||||
decorateBuiltInVisuals();
|
||||
document.querySelectorAll("img[src],video[src]").forEach((media) => {
|
||||
if (media.dataset.dfInlineMediaReady === "true") return;
|
||||
const target = chooseTarget(media);
|
||||
if (!target) return;
|
||||
const host = media.closest(visualHostSelector) || media.parentElement;
|
||||
if (!host) return;
|
||||
media.dataset.dfInlineMediaReady = "true";
|
||||
attachButton(host, target);
|
||||
});
|
||||
};
|
||||
input.addEventListener("change", () => {
|
||||
const file = input.files && input.files[0];
|
||||
if (!file || !active) return;
|
||||
const uploadedType = file.type.startsWith("image/") ? "image" : file.type.startsWith("video/") ? "video" : "";
|
||||
if (!uploadedType) {
|
||||
notify("请选择图片或视频文件。");
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.onerror = () => notify("文件读取失败,请重新选择。");
|
||||
reader.onload = () => {
|
||||
const next = { ...(active.previous || {}) };
|
||||
const result = String(reader.result);
|
||||
next.type = uploadedType;
|
||||
next.mediaUrl = result;
|
||||
delete next.posterUrl;
|
||||
if (!next.alt) next.alt = uploadedType === "video" ? "用户上传的视频" : "用户上传的图片";
|
||||
active.owner.media = next;
|
||||
const stored = persist();
|
||||
renderAll();
|
||||
notify(stored === false ? "媒体已替换;浏览器未能缓存,请下载 JSON 留存。" : "媒体已替换并写入页面 JSON。");
|
||||
active = null;
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
let queued = false;
|
||||
const queueDecorate = () => {
|
||||
if (queued) return;
|
||||
queued = true;
|
||||
requestAnimationFrame(() => { queued = false; decorate(); });
|
||||
};
|
||||
new MutationObserver(queueDecorate).observe(document.body, { childList: true, subtree: true });
|
||||
decorate();
|
||||
}
|
||||
installInlineMediaReplace();
|
||||
})();
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<meta name="description" content="NORTH 公共新闻——原创国际公共媒体风格新闻首页。" />
|
||||
<meta name="theme-color" content="#111111" />
|
||||
<title>NORTH 新闻 — 看见正在发生的世界</title>
|
||||
<style>
|
||||
:root{--red:#b80000;--red2:#d31313;--ink:#121212;--paper:#fff;--panel:#f4f4f4;--muted:#5a5a5a;--line:#d6d6d6;--yellow:#ffda1a;--blue:#1769a3;--max:1240px;--sans:Arial,'Noto Sans SC','Microsoft YaHei',sans-serif}
|
||||
*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.45 var(--sans)}body.dark{--ink:#f4f4f4;--paper:#151515;--panel:#232323;--muted:#b8b8b8;--line:#464646;--blue:#70b7e8}button,input{font:inherit}button,a{cursor:pointer}button{border:0;background:none;color:inherit}a{color:inherit;text-decoration:none}svg{display:block;width:100%;height:100%}:focus-visible{outline:4px solid var(--yellow);outline-offset:2px}.wrap{width:min(var(--max),calc(100% - 40px));margin:auto}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.skip{position:fixed;left:12px;top:calc(var(--df-generated-header-height,0px) + 8px);z-index:200;background:#fff;color:#111;padding:10px 14px;font-weight:800;transform:translateY(-150%);transition:.2s}.skip:focus{transform:none}
|
||||
.global-head{background:#111;color:#fff}.global-head .wrap{height:64px;display:flex;align-items:center;gap:20px}.tile-logo{display:flex;gap:4px;align-items:center}.tile-logo span{width:31px;height:31px;display:grid;place-items:center;background:#fff;color:#111;font-size:20px;font-weight:900;line-height:1}.account{display:flex;align-items:center;gap:9px;height:44px;padding:0 13px;border-left:1px solid #555;border-right:1px solid #555;font-weight:700;font-size:14px}.account svg{width:23px;height:23px;fill:none;stroke:currentColor;stroke-width:2}.global-nav{display:flex;align-items:center;height:100%;font-size:14px;font-weight:700}.global-nav a{height:100%;display:flex;align-items:center;padding:0 14px;border-right:1px solid #444;transition:background .2s}.global-nav a:hover{background:#303030}.global-actions{margin-left:auto;display:flex;align-items:center;gap:5px}.icon-btn{width:44px;height:44px;display:grid;place-items:center;transition:background .2s}.icon-btn:hover{background:#333}.icon-btn svg{width:22px;height:22px;fill:none;stroke:currentColor;stroke-width:2}.mobile-menu{display:none}
|
||||
.channel{background:var(--red);color:#fff}.channel-top{height:76px;display:flex;align-items:end;padding-bottom:11px}.channel-title{font-size:42px;font-weight:300;letter-spacing:-1.5px}.channel-nav{border-top:1px solid rgba(255,255,255,.3)}.channel-nav .wrap{height:43px;display:flex;align-items:center;overflow:hidden}.channel-nav a{font-size:14px;font-weight:700;padding:0 15px;height:25px;display:flex;align-items:center;border-right:1px solid rgba(255,255,255,.35);white-space:nowrap}.channel-nav a:first-child{padding-left:0}.channel-nav a.active{border-bottom:4px solid #fff}.channel-nav a:hover{text-decoration:underline}.more-link{margin-left:auto!important;border:0!important;gap:6px}.more-link svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2}
|
||||
.search-area{display:none;background:#202020;color:#fff;border-bottom:5px solid var(--red)}.search-area.open{display:block}.search-row{min-height:86px;display:flex;align-items:center;gap:10px}.search-row label{font-size:18px;font-weight:800}.search-row input{min-width:0;flex:1;height:48px;border:0;background:#fff;color:#111;padding:0 15px;font-size:17px}.search-row button{height:48px;background:var(--red);color:#fff;padding:0 24px;font-weight:800}.search-result{display:none;padding:0 0 14px 96px;color:#ddd;font-size:14px}.search-result.show{display:block}
|
||||
.breaking{background:#f2f2f2;color:#111;border-bottom:1px solid #ccc}.breaking .wrap{min-height:42px;display:flex;align-items:center}.breaking b{align-self:stretch;background:#171717;color:#fff;display:flex;align-items:center;padding:0 13px;font-size:13px}.breaking span{padding:9px 14px;font-weight:700;font-size:14px}.breaking time{margin-left:auto;font-size:12px;color:#666;white-space:nowrap}
|
||||
.page-date{font-size:12px;color:var(--muted);padding:20px 0 9px}.lead-layout{display:grid;grid-template-columns:1.1fr 1.4fr;gap:24px;padding:20px 0 28px;border-top:1px solid var(--line);border-bottom:1px solid var(--line)}.lead-copy{display:flex;flex-direction:column}.label{color:var(--red);font-size:13px;font-weight:900;margin-bottom:8px}.lead-copy h1{font-size:clamp(34px,4vw,55px);line-height:1.03;letter-spacing:-2px;margin:0 0 14px}.lead-copy .dek{font-size:18px;color:var(--muted);margin:0 0 18px;max-width:560px}.meta{font-size:12px;color:var(--muted);margin-top:auto;padding-top:12px;display:flex;gap:9px;flex-wrap:wrap}.meta strong{color:var(--ink)}.meta a{color:var(--blue);font-weight:700}.visual{position:relative;overflow:hidden;background:#26313a}.lead-visual{aspect-ratio:16/9}.visual svg{width:100%;height:100%}.credit{position:absolute;right:6px;bottom:5px;background:rgba(0,0,0,.68);color:white;padding:2px 5px;font-size:10px}.live-stamp{position:absolute;left:0;top:0;background:var(--red);color:#fff;padding:7px 10px;font-size:12px;font-weight:900}.headline-links{margin:15px 0 0;padding:0;list-style:none;border-top:1px solid var(--line)}.headline-links li{padding:10px 0;border-bottom:1px solid var(--line);font-size:14px;font-weight:700}.headline-links a:hover{text-decoration:underline}
|
||||
.section{padding:28px 0;border-bottom:1px solid var(--line)}.section-title{border-top:4px solid var(--ink);padding-top:8px;margin:0 0 18px;font-size:26px;letter-spacing:-.6px;display:flex;align-items:center;justify-content:space-between}.section-title a{font-size:13px;color:var(--blue);letter-spacing:0}.news-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:20px}.story+.story{border-left:1px solid var(--line);padding-left:20px}.story-media{aspect-ratio:16/9;margin-bottom:11px}.story h2,.story h3{font-size:20px;line-height:1.16;letter-spacing:-.4px;margin:5px 0 8px}.story p{font-size:14px;color:var(--muted);margin:0 0 10px}.story .meta{padding-top:0}.story h2 a:hover,.story h3 a:hover{text-decoration:underline}.feature{grid-column:span 2}.feature h2{font-size:30px}.feature .story-media{aspect-ratio:16/8.5}
|
||||
.live-band{background:#1b1b1b;color:#fff}.live-band .section{border:0}.live-band .section-title{border-color:var(--red)}.live-grid{display:grid;grid-template-columns:1.4fr 1fr 1fr;gap:20px}.live-card+.live-card{border-left:1px solid #555;padding-left:20px}.live-card .story-media{position:relative}.play{position:absolute;left:10px;bottom:10px;width:48px;height:48px;background:#fff;color:#111;display:grid;place-items:center;transition:background .2s}.play:hover{background:var(--yellow)}.play svg{width:23px;height:23px;fill:currentColor;margin-left:3px}.live-card h3{font-size:20px;line-height:1.15;margin:10px 0 5px}.live-card:first-child h3{font-size:27px}.live-meta{font-size:12px;color:#c3c3c3}.live-now{color:#ff6969;font-weight:800}
|
||||
.split{display:grid;grid-template-columns:2fr 1fr;gap:30px}.compact-list{display:grid;grid-template-columns:1fr 1fr;gap:0 22px}.compact{display:grid;grid-template-columns:125px 1fr;gap:13px;padding:15px 0;border-top:1px solid var(--line)}.compact:nth-child(-n+2){border-top:0;padding-top:0}.compact-media{aspect-ratio:1.25/1}.compact h3{font-size:17px;line-height:1.2;margin:4px 0 7px}.most-read{background:var(--panel);padding:20px}.most-read h2{font-size:22px;border-bottom:3px solid var(--red);padding-bottom:9px;margin-bottom:0}.rank-item{display:grid;grid-template-columns:36px 1fr;gap:10px;padding:13px 0;border-bottom:1px solid var(--line);align-items:start}.rank{font-size:30px;font-weight:300;color:var(--red);line-height:1}.rank-item a{font-weight:700;font-size:14px}.rank-item a:hover{text-decoration:underline}
|
||||
.audio-strip{background:#e8e8e8;color:#111;padding:19px 20px;display:grid;grid-template-columns:auto 1fr auto;gap:17px;align-items:center}.audio-play{width:52px;height:52px;border-radius:50%;background:#111;color:#fff;display:grid;place-items:center}.audio-play svg{width:22px;height:22px;fill:currentColor}.audio-play.playing svg{display:none}.audio-play.playing::after{content:'Ⅱ';font-weight:900;font-size:18px}.audio-copy b{display:block;font-size:18px}.audio-copy span{font-size:13px;color:#555}.audio-progress{display:flex;align-items:center;gap:9px;font-size:12px}.track{width:150px;height:5px;background:#aaa}.track span{display:block;width:0;height:100%;background:var(--red);transition:width .2s linear}
|
||||
.regions{display:grid;grid-template-columns:repeat(5,1fr);border:1px solid var(--line)}.region{padding:17px;border-right:1px solid var(--line)}.region:last-child{border-right:0}.region strong{display:block;font-size:12px;text-transform:uppercase;color:var(--red);margin-bottom:7px}.region a{font-weight:800;line-height:1.25}.region a:hover{text-decoration:underline}.weather{display:grid;grid-template-columns:auto repeat(5,1fr);align-items:stretch;border:1px solid var(--line)}.weather-title{background:var(--ink);color:var(--paper);padding:18px;font-weight:900;display:flex;align-items:center}.city{padding:12px 15px;border-left:1px solid var(--line)}.city b{display:block;font-size:13px}.temp{font-size:24px;font-weight:300;margin:3px 0}.condition{font-size:11px;color:var(--muted)}
|
||||
.newsletter{margin:30px auto;background:var(--panel);border-left:8px solid var(--red);padding:24px;display:grid;grid-template-columns:1fr 1fr;gap:30px;align-items:center}.newsletter h2{font-size:27px;margin:0 0 5px}.newsletter p{margin:0;color:var(--muted)}.sub-form{display:grid;grid-template-columns:1fr auto;gap:7px}.sub-form input{min-width:0;height:48px;border:1px solid #777;background:var(--paper);color:var(--ink);padding:0 13px}.sub-form button{background:var(--ink);color:var(--paper);padding:0 20px;font-weight:800}.sub-status{grid-column:1/-1;min-height:18px;font-size:12px;color:var(--muted)}
|
||||
footer{background:#222;color:#eee;margin-top:30px}.foot-top{padding:28px 0}.foot-logo{margin-bottom:20px}.foot-logo span{width:27px;height:27px;font-size:17px}.foot-grid{display:grid;grid-template-columns:repeat(6,1fr);border-top:1px solid #666;border-bottom:1px solid #666}.foot-grid a{padding:13px 10px;border-right:1px solid #555;font-size:13px;font-weight:700}.foot-grid a:last-child{border:0}.foot-grid a:hover{text-decoration:underline}.legal{padding-top:18px;font-size:11px;color:#bbb;display:flex;justify-content:space-between}
|
||||
.overlay{position:fixed;inset:0;z-index:100;background:rgba(0,0,0,.77);display:none;align-items:center;justify-content:center;padding:20px}.overlay.open{display:flex}.modal{width:min(820px,100%);background:var(--paper);color:var(--ink);box-shadow:0 20px 70px rgba(0,0,0,.45)}.modal-head{height:62px;background:#111;color:#fff;display:flex;align-items:center;padding:0 18px}.modal-head b{font-size:20px}.modal-head .dot{margin-right:10px}.close{margin-left:auto;width:44px;height:44px;font-size:28px;color:#fff}.stream{aspect-ratio:16/9;background:radial-gradient(circle at center,#3b4650,#101216 64%);position:relative;display:grid;place-items:center;color:#fff;overflow:hidden}.stream::before,.stream::after{content:'';position:absolute;border:1px solid rgba(255,255,255,.12);width:58%;height:58%;transform:rotate(45deg)}.stream::after{width:35%;height:35%}.stream-copy{position:relative;z-index:2;text-align:center}.stream-copy b{display:block;font-size:30px}.stream-copy span{color:#ccc}.modal-foot{padding:16px 18px;display:flex;justify-content:space-between;color:var(--muted);font-size:13px}.dot{width:9px;height:9px;border-radius:50%;background:#ef2929;box-shadow:0 0 0 4px rgba(239,41,41,.2)}
|
||||
.drawer{position:fixed;inset:0;z-index:110;background:rgba(0,0,0,.72);display:none}.drawer.open{display:block}.drawer-panel{height:100%;width:min(380px,90vw);background:#111;color:#fff;padding:18px;transform:translateX(-100%);transition:transform .22s}.drawer.open .drawer-panel{transform:none}.drawer-head{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #555;padding-bottom:15px}.drawer-links a{display:block;padding:14px 4px;border-bottom:1px solid #3b3b3b;font-size:20px;font-weight:700}.drawer-links a:hover{background:#292929}.toast{position:fixed;right:18px;bottom:18px;background:#111;color:#fff;padding:12px 16px;z-index:160;transform:translateY(90px);opacity:0;transition:.22s}.toast.show{transform:none;opacity:1}
|
||||
@media(max-width:1000px){.global-nav a:nth-last-child(-n+3){display:none}.news-grid{grid-template-columns:repeat(3,1fr)}.news-grid .story:last-child{display:none}.live-grid{grid-template-columns:1.35fr 1fr}.live-grid .live-card:last-child{display:none}.foot-grid{grid-template-columns:repeat(3,1fr)}.foot-grid a:nth-child(3){border-right:0}.split{grid-template-columns:1.6fr 1fr}.regions{grid-template-columns:repeat(3,1fr)}.region:nth-child(3){border-right:0}.region:nth-child(-n+3){border-bottom:1px solid var(--line)}}
|
||||
@media(max-width:720px){.wrap{width:calc(100% - 28px)}.global-head .wrap{height:56px;width:100%;padding:0 12px;gap:12px}.tile-logo span{width:27px;height:27px;font-size:17px}.account,.global-nav{display:none}.mobile-menu{display:grid}.global-actions{margin-left:auto}.channel-top{height:64px}.channel-title{font-size:36px}.channel-nav .wrap{width:100%;padding:0 14px;overflow-x:auto}.channel-nav a:nth-child(n+5){display:none}.more-link{display:flex!important}.breaking .wrap{width:100%}.breaking time{display:none}.breaking span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:12px}.search-row{display:grid;grid-template-columns:1fr auto;padding:13px 0}.search-row label{grid-column:1/-1;font-size:14px}.search-row button{padding:0 16px}.search-result{padding-left:0}.lead-layout{grid-template-columns:1fr;padding-top:14px}.lead-copy h1{font-size:38px}.lead-visual{grid-row:1}.lead-copy{grid-row:2}.lead-copy .dek{font-size:17px}.news-grid{grid-template-columns:1fr 1fr;gap:16px}.story+.story{padding-left:16px}.feature{grid-column:1/-1}.feature h2{font-size:27px}.story h3{font-size:18px}.story p{display:none}.live-grid{grid-template-columns:1fr 1fr;gap:15px}.live-card+.live-card{padding-left:15px}.live-card:first-child h3{font-size:21px}.split{grid-template-columns:1fr}.compact-list{display:block}.compact:nth-child(2){border-top:1px solid var(--line);padding-top:15px}.regions{grid-template-columns:1fr 1fr}.region,.region:nth-child(3){border-right:1px solid var(--line);border-bottom:1px solid var(--line)}.region:nth-child(even){border-right:0}.weather{grid-template-columns:1fr 1fr}.weather-title{grid-column:1/-1}.city{border-top:1px solid var(--line)}.newsletter{grid-template-columns:1fr;padding:20px}.foot-grid{grid-template-columns:1fr 1fr}.foot-grid a,.foot-grid a:nth-child(3){border-right:1px solid #555}.foot-grid a:nth-child(even){border-right:0}.legal{display:block;line-height:1.9}.audio-strip{grid-template-columns:auto 1fr}.audio-progress{grid-column:1/-1}.track{flex:1}}
|
||||
@media(max-width:350px){.global-head .tile-logo span:nth-last-child(-n+2){display:none}}
|
||||
@media(max-width:420px){.channel-nav a:nth-child(n+4){display:none}.news-grid,.live-grid{display:block}.story,.live-card{padding:0 0 18px!important;margin:0 0 18px;border-left:0!important;border-bottom:1px solid var(--line)}.live-card{border-color:#555!important}.compact{grid-template-columns:105px 1fr}.regions{display:block}.region{border-right:0!important}.newsletter{margin-left:14px;margin-right:14px}.sub-form{display:block}.sub-form input,.sub-form button{width:100%;margin-bottom:8px}.audio-copy b{font-size:16px}}
|
||||
@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;animation:none!important;transition:none!important}}
|
||||
|
||||
.global-actions{padding-right:52px}
|
||||
.settings-trigger{position:fixed;z-index:70;top:calc(var(--df-generated-header-height,0px) + 10px);right:16px;width:44px;height:44px;border:1px solid #555;display:grid;place-items:center;color:#fff;background:#1c1c1c;transition:transform .18s,background .18s}
|
||||
.settings-trigger:hover{background:#333;transform:rotate(12deg)}.settings-trigger svg{width:21px;height:21px;fill:none;stroke:currentColor;stroke-width:2}
|
||||
.settings-overlay{position:fixed;z-index:220;inset:0;padding:30px;display:grid;place-items:center;background:#171c25;opacity:0;visibility:hidden;transition:opacity .2s,visibility .2s}.settings-overlay.open{opacity:1;visibility:visible}body.settings-open>:not(.settings-overlay){visibility:hidden!important}
|
||||
.json-settings-modal{width:min(1280px,100%);height:min(790px,calc(100dvh - 60px));display:grid;grid-template-rows:auto 1fr auto;overflow:hidden;border:1px solid #2a6382;border-radius:8px;color:#e8f3ff;background:#071321;box-shadow:0 30px 100px rgba(0,0,0,.52)}.settings-head,.settings-body,.settings-foot{background:#071321}
|
||||
.settings-head{min-height:82px;padding:16px 24px;display:flex;align-items:center;gap:14px;border-bottom:1px solid #21455d}.settings-head-copy{flex:1}.settings-kicker{display:block;margin-bottom:3px;color:#35b8ff;font-size:13px;font-weight:800;letter-spacing:.1em}.settings-head h2{margin:0;color:#f7fbff;font-size:25px}.settings-close{width:46px;height:46px;border:1px solid #2e708f;display:grid;place-items:center;color:#f2f8ff;background:#0b1d30;font-size:25px}.settings-close:hover{background:#12304b}
|
||||
.settings-body{min-height:0;padding:18px 24px;display:grid;grid-template-columns:255px minmax(0,1fr);gap:18px}.module-tabs{min-height:0;overflow:auto}.module-tabs h3{margin:0 0 10px;color:#8fa9bf;font-size:13px}.module-tab{width:100%;min-height:54px;margin-bottom:6px;padding:8px 12px;border:1px solid #1d4660;display:block;color:#b7cada;background:#0a1929;text-align:left}.module-tab:hover{background:#0d2338}.module-tab.active{border-color:#25adf2;color:#fff;background:#0d2a42;box-shadow:inset 3px 0 #28b6ff}.module-tab strong,.module-tab span{display:block}.module-tab span{margin-top:2px;color:#7e9aae;font-size:11px}
|
||||
.editor-pane{min-width:0;min-height:0;display:grid;grid-template-rows:auto 1fr auto}.editor-title{min-height:37px;display:flex;align-items:flex-start;justify-content:space-between;color:#8fa9bf;font-size:12px}.editor-title strong{color:#eef8ff;font-size:16px}.json-editor{width:100%;min-height:0;padding:16px;resize:none;border:1px solid #28526b;outline:0;color:#d6f1ff;background:#020a12;font:14px/1.62 ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",monospace;tab-size:2}.json-editor:focus{border-color:#28b6ff;box-shadow:0 0 0 3px rgba(40,182,255,.16)}
|
||||
.editor-hint{min-height:40px;padding-top:9px;display:flex;justify-content:space-between;gap:12px;color:#7894aa;font-size:12px}.json-status{font-weight:750}.json-status.valid{color:#48d8a0}.json-status.invalid{color:#ff7189}
|
||||
.settings-foot{min-height:74px;padding:13px 24px;display:flex;align-items:center;justify-content:flex-end;gap:10px;border-top:1px solid #21455d}.editor-button{min-height:44px;padding:0 17px;border:1px solid #2d7292;color:#e5f4ff;background:#0b1e30;font-weight:700}.editor-button:hover{background:#12334f}.editor-button.primary{border-color:#2ab8ff;color:#03131e;background:#33b9fa}.editor-button.primary:hover{background:#67caff}
|
||||
@media(max-width:720px){.settings-trigger{top:calc(var(--df-generated-header-height,0px) + 7px);right:62px;width:42px;height:42px}.settings-overlay{padding:0}.json-settings-modal{width:100%;height:100dvh;border:0}.settings-head{min-height:68px;padding:10px 14px}.settings-head h2{font-size:20px}.settings-body{padding:12px;grid-template-columns:1fr;grid-template-rows:auto minmax(0,1fr)}.module-tabs{display:flex;gap:7px;overflow-x:auto}.module-tabs h3{display:none}.module-tab{width:auto;min-width:116px;margin:0}.settings-foot{padding:10px 12px;flex-wrap:wrap}.editor-button{flex:1;padding-inline:10px}}
|
||||
.skip{transform:translateY(calc(-100% - var(--df-generated-header-height,0px) - 24px))}.skip:focus{transform:none}
|
||||
.overlay,.drawer{z-index:1200}.settings-overlay{z-index:1300}
|
||||
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body id="top">
|
||||
<a class="skip" href="#main">跳到主要内容</a>
|
||||
<header>
|
||||
<div class="global-head"><div class="wrap">
|
||||
<button class="icon-btn mobile-menu" id="menuOpen" aria-label="打开菜单"><svg viewBox="0 0 24 24"><path d="M4 7h16M4 12h16M4 17h16"/></svg></button>
|
||||
<a class="tile-logo" id="brandLogo" href="#top"></a>
|
||||
<button class="account"><svg viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"/><path d="M4 21c.8-4.4 3.5-7 8-7s7.2 2.6 8 7"/></svg><span id="accountLabel"></span></button>
|
||||
<nav class="global-nav" id="globalNav" aria-label="全站导航"></nav>
|
||||
<div class="global-actions"><button class="icon-btn" id="theme" aria-label="切换深色模式"><svg viewBox="0 0 24 24"><path d="M20.5 14.4A8.6 8.6 0 0 1 9.6 3.5a8.7 8.7 0 1 0 10.9 10.9Z"/></svg></button><button class="icon-btn" id="searchOpen" aria-label="搜索"><svg viewBox="0 0 24 24"><circle cx="10.8" cy="10.8" r="6.8"/><path d="m19.5 19.5-4-4"/></svg></button></div>
|
||||
</div></div>
|
||||
<div class="channel"><div class="wrap channel-top"><div class="channel-title" id="channelTitle"></div></div><nav class="channel-nav" aria-label="新闻频道"><div class="wrap" id="channelNav"></div></nav></div>
|
||||
<div class="search-area" id="searchArea"><form class="wrap search-row" id="searchForm"><label id="searchLabel" for="search"></label><input id="search" type="search"/><button id="searchButton"></button></form><div class="wrap search-result" id="searchResult" aria-live="polite"></div></div>
|
||||
<div class="breaking"><div class="wrap"><b id="breakingLabel"></b><span id="breakingText"></span><time id="breakingTime"></time></div></div>
|
||||
</header>
|
||||
<button class="settings-trigger" id="openSettings" aria-label="编辑页面 JSON" title="编辑页面 JSON"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3.5"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1-2.8 2.8-.1-.1a1.7 1.7 0 0 0-1.9-.3A1.7 1.7 0 0 0 14 21v.2h-4V21a1.7 1.7 0 0 0-1-1.6 1.7 1.7 0 0 0-1.9.3l-.1.1L4.2 17l.1-.1a1.7 1.7 0 0 0 .3-1.9A1.7 1.7 0 0 0 3 14H2.8v-4H3a1.7 1.7 0 0 0 1.6-1 1.7 1.7 0 0 0-.3-1.9L4.2 7 7 4.2l.1.1a1.7 1.7 0 0 0 1.9.3A1.7 1.7 0 0 0 10 3V2.8h4V3a1.7 1.7 0 0 0 1 1.6 1.7 1.7 0 0 0 1.9-.3l.1-.1L19.8 7l-.1.1a1.7 1.7 0 0 0-.3 1.9 1.7 1.7 0 0 0 1.6 1h.2v4H21a1.7 1.7 0 0 0-1.6 1Z"/></svg></button>
|
||||
|
||||
<main id="main" tabindex="-1">
|
||||
<div class="wrap" id="news"><div class="page-date" id="pageDate"></div><section class="lead-layout" id="leadLayout" aria-label="头条新闻"></section></div>
|
||||
<section class="section wrap" id="world"><h2 class="section-title"><span id="focusTitle"></span><a id="focusMore" href="#world"></a></h2><div class="news-grid" id="focusGrid"></div></section>
|
||||
<div class="live-band" id="live"><section class="section wrap"><h2 class="section-title"><span id="mediaTitle"></span><a id="mediaMore" href="#live"></a></h2><div class="live-grid" id="mediaGrid"></div></section></div>
|
||||
<section class="section wrap" id="business"><h2 class="section-title"><span id="moreTitle"></span><a id="moreLink" href="#business"></a></h2><div class="split"><div class="compact-list" id="moreList"></div><aside class="most-read"><h2 id="rankingTitle"></h2><div id="rankingList"></div></aside></div></section>
|
||||
<section class="section wrap" id="audio"><h2 class="section-title" id="audioTitle"></h2><div class="audio-strip"><button class="audio-play" id="audioPlay" aria-label="播放今日新闻播客"><svg viewBox="0 0 24 24"><path d="m7 4 13 8-13 8Z"/></svg></button><div class="audio-copy"><b id="audioName"></b><span id="audioMeta"></span></div><div class="audio-progress"><span id="audioTime">00:00</span><div class="track"><span id="audioBar"></span></div><span id="audioDuration"></span></div></div></section>
|
||||
<section class="section wrap" id="regions"><h2 class="section-title"><span id="regionsTitle"></span><a id="regionsMore" href="#regions"></a></h2><div class="regions" id="regionsGrid"></div></section>
|
||||
<section class="section wrap" id="weather"><h2 class="section-title" id="weatherTitle"></h2><div class="weather" id="weatherGrid"></div></section>
|
||||
<section class="newsletter wrap"><div><h2 id="newsletterTitle"></h2><p id="newsletterText"></p></div><form class="sub-form" id="subForm"><label class="sr-only" for="email">邮箱地址</label><input id="email" type="email" required/><button id="newsletterButton"></button><div class="sub-status" id="subStatus" aria-live="polite"></div></form></section>
|
||||
</main>
|
||||
|
||||
<footer><div class="wrap foot-top"><div class="tile-logo foot-logo" id="footerLogo"></div><div class="foot-grid" id="footerLinks"></div><div class="legal"><span id="copyright"></span><span id="legal"></span></div></div></footer>
|
||||
<div class="overlay" id="liveModal" role="dialog" aria-modal="true" aria-labelledby="liveTitle"><div class="modal"><div class="modal-head"><span class="dot"></span><b id="liveTitle"></b><button class="close" id="liveClose" aria-label="关闭直播">×</button></div><div class="stream"><div class="stream-copy"><b id="streamTitle"></b><span id="streamSubtitle"></span></div></div><div class="modal-foot"><span id="currentProgram"></span><button id="caption">CC 字幕:开</button></div></div></div>
|
||||
<div class="drawer" id="drawer" role="dialog" aria-modal="true" aria-label="移动端菜单"><aside class="drawer-panel"><div class="drawer-head"><div class="tile-logo" id="drawerLogo"></div><button class="close" id="menuClose" aria-label="关闭菜单">×</button></div><nav class="drawer-links" id="drawerLinks"></nav></aside></div>
|
||||
<div class="toast" id="toast" role="status" aria-live="polite"></div>
|
||||
|
||||
<div class="settings-overlay" id="settingsOverlay" aria-hidden="true"><section class="json-settings-modal" role="dialog" aria-modal="true" aria-labelledby="settingsTitle"><header class="settings-head"><div class="settings-head-copy"><span class="settings-kicker">BBC TEMPLATE CONTROL</span><h2 id="settingsTitle">JSON 编辑器</h2></div><button class="settings-close" id="closeSettings" aria-label="关闭 JSON 编辑器">×</button></header><div class="settings-body"><nav class="module-tabs" id="moduleTabs" aria-label="JSON 模块"><h3>页面模块</h3></nav><div class="editor-pane"><div class="editor-title"><strong id="editorModuleTitle">站点信息</strong><span>只编辑当前模块</span></div><textarea class="json-editor" id="jsonEditor" spellcheck="false" aria-label="当前模块 JSON"></textarea><div class="editor-hint"><span>修改后先校验,再应用到页面。</span><span class="json-status valid" id="jsonStatus">JSON 有效</span></div></div></div><footer class="settings-foot"><button class="editor-button" id="resetJson">恢复初始</button><button class="editor-button" id="copyJson">复制 JSON</button><button class="editor-button" id="downloadJson">下载 JSON</button><button class="editor-button primary" id="applyJson">应用并渲染</button></footer></section></div>
|
||||
|
||||
<script type="application/json" id="bbcPageData">__BBC_PAGE_DATA__</script>
|
||||
<script>__BBC_PAGE_RUNTIME__</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
{
|
||||
"site": {
|
||||
"brandLetters": ["B", "B", "C"],
|
||||
"pageTitle": "BBC 新闻 — 看见正在发生的世界",
|
||||
"description": "一个 BBC 风格的中文国际公共新闻首页示例页面。",
|
||||
"theme": "light",
|
||||
"accountLabel": "账户",
|
||||
"updatedDate": "2026年10月26日 · 更新于 09:36"
|
||||
},
|
||||
"navigation": {
|
||||
"global": [
|
||||
{"label": "首页", "href": "#top"},
|
||||
{"label": "新闻", "href": "#news"},
|
||||
{"label": "视频", "href": "#live"},
|
||||
{"label": "音频", "href": "#audio"},
|
||||
{"label": "地区", "href": "#regions"},
|
||||
{"label": "天气", "href": "#weather"}
|
||||
],
|
||||
"channelTitle": "新闻",
|
||||
"channel": [
|
||||
{"label": "头条", "href": "#news"},
|
||||
{"label": "世界", "href": "#world"},
|
||||
{"label": "商业", "href": "#business"},
|
||||
{"label": "科技", "href": "#science"},
|
||||
{"label": "文化", "href": "#culture"},
|
||||
{"label": "地区", "href": "#regions"}
|
||||
],
|
||||
"moreLabel": "更多",
|
||||
"searchLabel": "搜索 BBC",
|
||||
"searchPlaceholder": "输入新闻、地点或人物",
|
||||
"searchButton": "搜索",
|
||||
"drawer": [
|
||||
{"label": "新闻", "href": "#news"},
|
||||
{"label": "世界", "href": "#world"},
|
||||
{"label": "商业", "href": "#business"},
|
||||
{"label": "科技", "href": "#science"},
|
||||
{"label": "视频", "href": "#live"},
|
||||
{"label": "音频", "href": "#audio"},
|
||||
{"label": "地区", "href": "#regions"},
|
||||
{"label": "天气", "href": "#weather"}
|
||||
]
|
||||
},
|
||||
"breaking": {
|
||||
"label": "快讯",
|
||||
"text": "多国科研团队公布开放海洋观测计划,首批数据将于本周上线",
|
||||
"time": "11分钟前"
|
||||
},
|
||||
"lead": {
|
||||
"kicker": "世界",
|
||||
"title": "一项跨越海洋的观测计划,正在重新连接科学与公众",
|
||||
"summary": "来自18个国家的研究机构将开放实时数据,让沿海社区第一次直接参与海洋变化监测。",
|
||||
"related": [
|
||||
{"label": "图解:海洋传感器如何共同工作", "href": "#world"},
|
||||
{"label": "现场声音:跟随科考船出发的第一天", "href": "#audio"}
|
||||
],
|
||||
"byline": "陈叙 报道",
|
||||
"time": "3小时前",
|
||||
"section": "世界",
|
||||
"sectionHref": "#world",
|
||||
"visual": "research-ship",
|
||||
"visualLabel": "海洋科考船在晨光中航行的插画",
|
||||
"stamp": "特别报道",
|
||||
"credit": "BBC / 视觉新闻"
|
||||
},
|
||||
"focus": {
|
||||
"title": "今日焦点",
|
||||
"moreLabel": "查看全部 →",
|
||||
"items": [
|
||||
{"id": "public-harbor", "kicker": "城市", "title": "一座旧港口如何变成全年开放的公共客厅", "summary": "设计团队保留了船坞的工业结构,并把防洪设施藏进步道与花园。", "time": "47分钟前", "section": "世界", "href": "#world", "visual": "harbor"},
|
||||
{"id": "small-satellite", "kicker": "科学", "title": "更小、更快的新型卫星将如何观察极端天气", "summary": "", "time": "1小时前", "section": "科学", "href": "#science", "visual": "satellite"},
|
||||
{"id": "creative-economy", "kicker": "经济", "title": "创意产业为何成为中型城市的新增长引擎", "summary": "", "time": "2小时前", "section": "商业", "href": "#business", "visual": "creative-city"},
|
||||
{"id": "station-archive", "kicker": "文化", "title": "百年车站重开,建筑档案也首次面向公众", "summary": "", "time": "3小时前", "section": "文化", "href": "#culture", "visual": "station"}
|
||||
]
|
||||
},
|
||||
"media": {
|
||||
"title": "观看与收听",
|
||||
"moreLabel": "所有节目 →",
|
||||
"videos": [
|
||||
{"id": "world-live", "title": "BBC 世界新闻:全天候直播", "meta": "正在直播 · 提供中文字幕", "live": true, "visual": "studio"},
|
||||
{"id": "evening-brief", "title": "三分钟晚间新闻简报", "meta": "视频 · 03:12", "live": false, "visual": "bulletin"},
|
||||
{"id": "blue-frontier", "title": "深入蓝色边界:海上72小时", "meta": "纪录片 · 18:44", "live": false, "visual": "ocean"}
|
||||
],
|
||||
"modal": {
|
||||
"title": "BBC 直播",
|
||||
"streamTitle": "世界新闻直播",
|
||||
"streamSubtitle": "演示画面 · 中文字幕已开启",
|
||||
"currentProgram": "当前节目:环球新闻一小时"
|
||||
},
|
||||
"audio": {
|
||||
"sectionTitle": "BBC 声音",
|
||||
"title": "今日世界:海洋数据为何属于每一个人",
|
||||
"meta": "主持人 林岚 · 24分钟",
|
||||
"durationSeconds": 1440,
|
||||
"durationLabel": "24:00"
|
||||
}
|
||||
},
|
||||
"moreNews": {
|
||||
"title": "更多新闻",
|
||||
"moreLabel": "浏览全部 →",
|
||||
"items": [
|
||||
{"id": "digital-customs", "kicker": "商业", "title": "数字通关让区域物流等待时间缩短一半", "time": "36分钟前", "visual": "logistics"},
|
||||
{"id": "asian-markets", "kicker": "市场", "title": "亚洲主要股指涨跌互现,运输板块领涨", "time": "1小时前", "visual": "market"},
|
||||
{"id": "offline-assistant", "kicker": "科技", "title": "设备端智能助手进入离线运行时代", "time": "2小时前", "visual": "device"},
|
||||
{"id": "distributed-energy", "kicker": "环境", "title": "分布式能源如何帮助偏远社区保持供电", "time": "3小时前", "visual": "energy"}
|
||||
],
|
||||
"rankingTitle": "热门排行",
|
||||
"ranking": [
|
||||
{"title": "研究人员为何开始重新绘制世界洋流图", "href": "#world"},
|
||||
{"title": "一座火车站的百年建筑档案", "href": "#culture"},
|
||||
{"title": "小型卫星带来的天气预报革命", "href": "#science"},
|
||||
{"title": "城市创意产业的五个关键数字", "href": "#business"},
|
||||
{"title": "本周值得关注的五座城市", "href": "#regions"}
|
||||
]
|
||||
},
|
||||
"regions": {
|
||||
"title": "地区与语言",
|
||||
"moreLabel": "选择地区 →",
|
||||
"items": [
|
||||
{"region": "亚太", "title": "区域铁路网络迎来新一轮升级"},
|
||||
{"region": "欧洲", "title": "文化遗产保护计划扩大合作范围"},
|
||||
{"region": "非洲", "title": "太阳能微电网连接偏远医疗站"},
|
||||
{"region": "美洲", "title": "城市河流复育进入第二阶段"},
|
||||
{"region": "中东", "title": "新公共图书馆网络正式启用"}
|
||||
],
|
||||
"weatherTitle": "世界天气",
|
||||
"weatherLabel": "主要城市",
|
||||
"weather": [
|
||||
{"city": "北京", "temperature": "18°", "condition": "晴间多云"},
|
||||
{"city": "伦敦", "temperature": "12°", "condition": "阵雨"},
|
||||
{"city": "新加坡", "temperature": "30°", "condition": "雷雨"},
|
||||
{"city": "内罗毕", "temperature": "24°", "condition": "晴"},
|
||||
{"city": "纽约", "temperature": "16°", "condition": "多云"}
|
||||
]
|
||||
},
|
||||
"newsletter": {
|
||||
"title": "每天,理解世界多一点",
|
||||
"text": "订阅 BBC 早间简报,精选重要新闻与深度解读。",
|
||||
"placeholder": "邮箱地址",
|
||||
"button": "订阅简报",
|
||||
"successPrefix": "订阅成功,确认邮件已发送至"
|
||||
},
|
||||
"footer": {
|
||||
"links": [
|
||||
{"label": "新闻", "href": "#news"},
|
||||
{"label": "视频", "href": "#live"},
|
||||
{"label": "音频", "href": "#audio"},
|
||||
{"label": "地区", "href": "#regions"},
|
||||
{"label": "天气", "href": "#weather"},
|
||||
{"label": "关于 BBC", "href": "#top"}
|
||||
],
|
||||
"copyright": "© 2026 BBC Public Media · 本页面为概念设计",
|
||||
"legal": "使用条款 · 隐私 · Cookie · 无障碍"
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
# BBC 页面 JSON 契约
|
||||
|
||||
顶层必须完整包含 `site`、`navigation`、`breaking`、`lead`、`focus`、`media`、`moreNews`、`regions`、`newsletter`、`footer`。弹窗按十个模块分别编辑,应用时重新校验完整文档。
|
||||
|
||||
## 通用规则
|
||||
|
||||
- 所有标题、标签、摘要和时间为字符串;关键展示字段不能为空。
|
||||
- 列表有数量上限,所属列表中的 `id` 必须唯一。
|
||||
- `href` 只允许以 `#` 开头的页面内锚点。
|
||||
- JSON 文本不能包含 HTML、脚本或直接 iframe。具有 `visual` 的内容对象可增加 `media` 来替换内置视觉:图片 `{type:"image", mediaUrl, alt?, pageUrl?}`;视频 `{type:"video", mediaUrl, posterUrl?, alt?, pageUrl?}`;网页 `{type:"webpage", pageUrl, title, description?, mediaUrl?, embed?}`。URL 只接受 `http(s)`,图片/视频也允许对应的 `data:` URL。
|
||||
|
||||
## 模块
|
||||
|
||||
- `site`:`brandLetters` 必须为 2–6 个单字符方块字标;包含页面标题、描述、`theme`(`light`/`dark`/`auto`)、账户文案和更新时间。
|
||||
- `navigation`:全站导航、频道导航和移动抽屉分别为 1–12 个 `{label,href}`;另含频道标题、搜索和更多文案。
|
||||
- `breaking`:`label/text/time`。
|
||||
- `lead`:头条标签、标题、摘要、0–6 条关联阅读、署名、时间、频道、视觉说明和标记;`visual` 固定为 `research-ship`。
|
||||
- `focus.items`:1–8 条,视觉类型为 `harbor`、`satellite`、`creative-city`、`station`。
|
||||
- `media.videos`:1–6 条,视觉类型为 `studio`、`bulletin`、`ocean`;`modal` 配置直播弹窗;`audio.durationSeconds` 为 1–86400。
|
||||
- `moreNews.items`:1–12 条,视觉类型为 `logistics`、`market`、`device`、`energy`;`ranking` 为 1–10 条排行链接。
|
||||
- `regions.items`:1–10 个地区标题;`weather` 为 1–10 个 `{city,temperature,condition}`。
|
||||
- `newsletter`:标题、说明、邮箱占位、按钮和成功提示前缀。
|
||||
- `footer.links`:1–12 个页脚链接;另有版权与法律文案。
|
||||
|
||||
JSON 使用双引号,不允许注释、Markdown 围栏或尾逗号。`assets/default-data.json` 只是结构和演示内容,不是事实来源。
|
||||
+11
@@ -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_bbc_page as renderer
|
||||
from fast_patch_page import run
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(run(renderer, output_stem="bbc-page"))
|
||||
+576
@@ -0,0 +1,576 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate BBC page data and inject it into the bundled HTML template."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import html as html_lib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
SKILL_ROOT = Path(__file__).resolve().parent.parent
|
||||
ASSETS_DIR = SKILL_ROOT / "assets"
|
||||
DEFAULT_DATA_PATH = ASSETS_DIR / "default-data.json"
|
||||
TEMPLATE_PATH = ASSETS_DIR / "bbc-template.html"
|
||||
RUNTIME_PATH = ASSETS_DIR / "bbc-runtime.js"
|
||||
DATA_MARKER = "__BBC_PAGE_DATA__"
|
||||
RUNTIME_MARKER = "__BBC_PAGE_RUNTIME__"
|
||||
TITLE_RE = re.compile(r"<title>[^<]*</title>", re.IGNORECASE)
|
||||
MODULES = (
|
||||
"site",
|
||||
"navigation",
|
||||
"breaking",
|
||||
"lead",
|
||||
"focus",
|
||||
"media",
|
||||
"moreNews",
|
||||
"regions",
|
||||
"newsletter",
|
||||
"footer",
|
||||
)
|
||||
THEMES = {"auto", "light", "dark"}
|
||||
FOCUS_VISUALS = {"harbor", "satellite", "creative-city", "station"}
|
||||
MEDIA_VISUALS = {"studio", "bulletin", "ocean"}
|
||||
MORE_VISUALS = {"logistics", "market", "device", "energy"}
|
||||
REMOTE_MEDIA_TYPES = {"image", "video", "webpage"}
|
||||
|
||||
|
||||
class DataValidationError(ValueError):
|
||||
"""Raised when the BBC page JSON cannot satisfy the template contract."""
|
||||
|
||||
|
||||
def _read_json(path: Path) -> dict[str, Any]:
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError as exc:
|
||||
raise DataValidationError(f"JSON file does not exist: {path}") from exc
|
||||
except json.JSONDecodeError as exc:
|
||||
raise DataValidationError(
|
||||
f"Invalid JSON at line {exc.lineno}, column {exc.colno}: {exc.msg}"
|
||||
) from exc
|
||||
if not isinstance(data, dict):
|
||||
raise DataValidationError("Top-level JSON value must be an object")
|
||||
return data
|
||||
|
||||
|
||||
def _mapping(value: Any, path: str, errors: list[str]) -> dict[str, Any]:
|
||||
if not isinstance(value, dict):
|
||||
errors.append(f"{path} must be an object")
|
||||
return {}
|
||||
return value
|
||||
|
||||
|
||||
def _array(
|
||||
value: Any,
|
||||
path: str,
|
||||
errors: list[str],
|
||||
*,
|
||||
limit: int | None = None,
|
||||
) -> list[Any]:
|
||||
if not isinstance(value, list):
|
||||
errors.append(f"{path} must be an array")
|
||||
return []
|
||||
if limit is not None and len(value) > limit:
|
||||
errors.append(f"{path} may contain at most {limit} items")
|
||||
return value
|
||||
|
||||
|
||||
def _non_empty_string(value: Any, path: str, errors: list[str]) -> None:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
errors.append(f"{path} must be a non-empty string")
|
||||
|
||||
|
||||
def _remote_url(value: Any, path: str, errors: list[str], *, required: bool = False, data_prefix: str = "") -> None:
|
||||
if value in (None, "") and not required:
|
||||
return
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
errors.append(f"{path} must be a non-empty URL")
|
||||
return
|
||||
candidate = value.strip()
|
||||
if data_prefix and candidate.lower().startswith(data_prefix):
|
||||
return
|
||||
parsed = urlparse(candidate)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
errors.append(f"{path} must use an http(s) URL")
|
||||
|
||||
|
||||
def _validate_remote_media_tree(value: Any, path: str, errors: list[str]) -> None:
|
||||
if isinstance(value, list):
|
||||
for index, item in enumerate(value):
|
||||
_validate_remote_media_tree(item, f"{path}[{index}]", errors)
|
||||
return
|
||||
if not isinstance(value, dict):
|
||||
return
|
||||
media = value.get("media")
|
||||
if isinstance(media, dict) and "type" in media:
|
||||
media_path = f"{path}.media"
|
||||
media_data = _mapping(media, media_path, errors)
|
||||
media_type = media_data.get("type")
|
||||
if media_type not in REMOTE_MEDIA_TYPES:
|
||||
errors.append(f"{media_path}.type must be one of: {', '.join(sorted(REMOTE_MEDIA_TYPES))}")
|
||||
elif media_type in {"image", "video"}:
|
||||
_remote_url(media_data.get("mediaUrl"), f"{media_path}.mediaUrl", errors, required=True, data_prefix=f"data:{media_type}/")
|
||||
if media_type == "video":
|
||||
_remote_url(media_data.get("posterUrl"), f"{media_path}.posterUrl", errors, data_prefix="data:image/")
|
||||
if media_type == "webpage":
|
||||
_remote_url(media_data.get("pageUrl"), f"{media_path}.pageUrl", errors, required=True)
|
||||
_remote_url(media_data.get("mediaUrl"), f"{media_path}.mediaUrl", errors, data_prefix="data:image/")
|
||||
if "embed" in media_data and not isinstance(media_data.get("embed"), bool):
|
||||
errors.append(f"{media_path}.embed must be a boolean")
|
||||
elif media_type in {"image", "video"}:
|
||||
_remote_url(media_data.get("pageUrl"), f"{media_path}.pageUrl", errors)
|
||||
for key, item in value.items():
|
||||
if key != "media":
|
||||
_validate_remote_media_tree(item, f"{path}.{key}", errors)
|
||||
|
||||
|
||||
def _string(value: Any, path: str, errors: list[str]) -> None:
|
||||
if not isinstance(value, str):
|
||||
errors.append(f"{path} must be a string")
|
||||
|
||||
|
||||
def _strings(
|
||||
value: dict[str, Any],
|
||||
keys: tuple[str, ...],
|
||||
path: str,
|
||||
errors: list[str],
|
||||
) -> None:
|
||||
for key in keys:
|
||||
_non_empty_string(value.get(key), f"{path}.{key}", errors)
|
||||
|
||||
|
||||
def _href(value: Any, path: str, errors: list[str]) -> None:
|
||||
_non_empty_string(value, path, errors)
|
||||
if isinstance(value, str) and not value.startswith("#"):
|
||||
errors.append(f"{path} must be an in-page anchor starting with #")
|
||||
|
||||
|
||||
def _validate_links(
|
||||
value: Any,
|
||||
path: str,
|
||||
errors: list[str],
|
||||
*,
|
||||
limit: int,
|
||||
require_items: bool,
|
||||
) -> list[Any]:
|
||||
items = _array(value, path, errors, limit=limit)
|
||||
if require_items and not items:
|
||||
errors.append(f"{path} must contain at least one item")
|
||||
for index, link_value in enumerate(items):
|
||||
item_path = f"{path}[{index}]"
|
||||
link = _mapping(link_value, item_path, errors)
|
||||
_non_empty_string(link.get("label"), f"{item_path}.label", errors)
|
||||
_href(link.get("href"), f"{item_path}.href", errors)
|
||||
return items
|
||||
|
||||
|
||||
def _validate_story_items(
|
||||
value: Any,
|
||||
path: str,
|
||||
errors: list[str],
|
||||
*,
|
||||
limit: int,
|
||||
visuals: set[str],
|
||||
focus: bool = False,
|
||||
media: bool = False,
|
||||
) -> list[Any]:
|
||||
items = _array(value, path, errors, limit=limit)
|
||||
if not items:
|
||||
errors.append(f"{path} must contain at least one item")
|
||||
seen: set[str] = set()
|
||||
for index, item_value in enumerate(items):
|
||||
item_path = f"{path}[{index}]"
|
||||
item = _mapping(item_value, item_path, errors)
|
||||
item_id = item.get("id")
|
||||
_non_empty_string(item_id, f"{item_path}.id", errors)
|
||||
if isinstance(item_id, str):
|
||||
if item_id in seen:
|
||||
errors.append(f"{item_path}.id must be unique")
|
||||
seen.add(item_id)
|
||||
keys = ("title", "meta") if media else ("kicker", "title", "time")
|
||||
_strings(item, keys, item_path, errors)
|
||||
if focus:
|
||||
_string(item.get("summary"), f"{item_path}.summary", errors)
|
||||
_strings(item, ("section",), item_path, errors)
|
||||
_href(item.get("href"), f"{item_path}.href", errors)
|
||||
if media and not isinstance(item.get("live"), bool):
|
||||
errors.append(f"{item_path}.live must be a boolean")
|
||||
if item.get("visual") not in visuals:
|
||||
errors.append(
|
||||
f"{item_path}.visual must be one of: "
|
||||
f"{', '.join(sorted(visuals))}"
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def validate_document(data: dict[str, Any]) -> dict[str, Any]:
|
||||
errors: list[str] = []
|
||||
_validate_remote_media_tree(data, "$", errors)
|
||||
for module in MODULES:
|
||||
if module not in data:
|
||||
errors.append(f"Missing top-level module: {module}")
|
||||
|
||||
site = _mapping(data.get("site"), "site", errors)
|
||||
_strings(
|
||||
site,
|
||||
("pageTitle", "description", "accountLabel", "updatedDate"),
|
||||
"site",
|
||||
errors,
|
||||
)
|
||||
if site.get("theme") not in THEMES:
|
||||
errors.append("site.theme must be one of: auto, dark, light")
|
||||
brand_letters = _array(
|
||||
site.get("brandLetters"),
|
||||
"site.brandLetters",
|
||||
errors,
|
||||
limit=6,
|
||||
)
|
||||
if len(brand_letters) < 2:
|
||||
errors.append("site.brandLetters must contain at least 2 letters")
|
||||
for index, letter in enumerate(brand_letters):
|
||||
if not isinstance(letter, str) or len(letter.strip()) != 1:
|
||||
errors.append(
|
||||
f"site.brandLetters[{index}] must be a single character"
|
||||
)
|
||||
|
||||
navigation = _mapping(data.get("navigation"), "navigation", errors)
|
||||
_strings(
|
||||
navigation,
|
||||
(
|
||||
"channelTitle",
|
||||
"moreLabel",
|
||||
"searchLabel",
|
||||
"searchPlaceholder",
|
||||
"searchButton",
|
||||
),
|
||||
"navigation",
|
||||
errors,
|
||||
)
|
||||
global_links = _validate_links(
|
||||
navigation.get("global"),
|
||||
"navigation.global",
|
||||
errors,
|
||||
limit=12,
|
||||
require_items=True,
|
||||
)
|
||||
channel_links = _validate_links(
|
||||
navigation.get("channel"),
|
||||
"navigation.channel",
|
||||
errors,
|
||||
limit=12,
|
||||
require_items=True,
|
||||
)
|
||||
drawer_links = _validate_links(
|
||||
navigation.get("drawer"),
|
||||
"navigation.drawer",
|
||||
errors,
|
||||
limit=12,
|
||||
require_items=True,
|
||||
)
|
||||
|
||||
breaking = _mapping(data.get("breaking"), "breaking", errors)
|
||||
_strings(breaking, ("label", "text", "time"), "breaking", errors)
|
||||
|
||||
lead = _mapping(data.get("lead"), "lead", errors)
|
||||
_strings(
|
||||
lead,
|
||||
(
|
||||
"kicker",
|
||||
"title",
|
||||
"summary",
|
||||
"byline",
|
||||
"time",
|
||||
"section",
|
||||
"visualLabel",
|
||||
"stamp",
|
||||
"credit",
|
||||
),
|
||||
"lead",
|
||||
errors,
|
||||
)
|
||||
_href(lead.get("sectionHref"), "lead.sectionHref", errors)
|
||||
if lead.get("visual") != "research-ship":
|
||||
errors.append("lead.visual must be: research-ship")
|
||||
related = _validate_links(
|
||||
lead.get("related"),
|
||||
"lead.related",
|
||||
errors,
|
||||
limit=6,
|
||||
require_items=False,
|
||||
)
|
||||
|
||||
focus = _mapping(data.get("focus"), "focus", errors)
|
||||
_strings(focus, ("title", "moreLabel"), "focus", errors)
|
||||
focus_items = _validate_story_items(
|
||||
focus.get("items"),
|
||||
"focus.items",
|
||||
errors,
|
||||
limit=8,
|
||||
visuals=FOCUS_VISUALS,
|
||||
focus=True,
|
||||
)
|
||||
|
||||
media = _mapping(data.get("media"), "media", errors)
|
||||
_strings(media, ("title", "moreLabel"), "media", errors)
|
||||
video_items = _validate_story_items(
|
||||
media.get("videos"),
|
||||
"media.videos",
|
||||
errors,
|
||||
limit=6,
|
||||
visuals=MEDIA_VISUALS,
|
||||
media=True,
|
||||
)
|
||||
modal = _mapping(media.get("modal"), "media.modal", errors)
|
||||
_strings(
|
||||
modal,
|
||||
("title", "streamTitle", "streamSubtitle", "currentProgram"),
|
||||
"media.modal",
|
||||
errors,
|
||||
)
|
||||
audio = _mapping(media.get("audio"), "media.audio", errors)
|
||||
_strings(
|
||||
audio,
|
||||
("sectionTitle", "title", "meta", "durationLabel"),
|
||||
"media.audio",
|
||||
errors,
|
||||
)
|
||||
duration = audio.get("durationSeconds")
|
||||
if (
|
||||
not isinstance(duration, int)
|
||||
or isinstance(duration, bool)
|
||||
or not 1 <= duration <= 86400
|
||||
):
|
||||
errors.append(
|
||||
"media.audio.durationSeconds must be an integer from 1 to 86400"
|
||||
)
|
||||
|
||||
more_news = _mapping(data.get("moreNews"), "moreNews", errors)
|
||||
_strings(
|
||||
more_news,
|
||||
("title", "moreLabel", "rankingTitle"),
|
||||
"moreNews",
|
||||
errors,
|
||||
)
|
||||
more_items = _validate_story_items(
|
||||
more_news.get("items"),
|
||||
"moreNews.items",
|
||||
errors,
|
||||
limit=12,
|
||||
visuals=MORE_VISUALS,
|
||||
)
|
||||
ranking = _array(
|
||||
more_news.get("ranking"),
|
||||
"moreNews.ranking",
|
||||
errors,
|
||||
limit=10,
|
||||
)
|
||||
if not ranking:
|
||||
errors.append("moreNews.ranking must contain at least one item")
|
||||
for index, item_value in enumerate(ranking):
|
||||
item_path = f"moreNews.ranking[{index}]"
|
||||
item = _mapping(item_value, item_path, errors)
|
||||
_non_empty_string(item.get("title"), f"{item_path}.title", errors)
|
||||
_href(item.get("href"), f"{item_path}.href", errors)
|
||||
|
||||
regions = _mapping(data.get("regions"), "regions", errors)
|
||||
_strings(
|
||||
regions,
|
||||
("title", "moreLabel", "weatherTitle", "weatherLabel"),
|
||||
"regions",
|
||||
errors,
|
||||
)
|
||||
region_items = _array(
|
||||
regions.get("items"),
|
||||
"regions.items",
|
||||
errors,
|
||||
limit=10,
|
||||
)
|
||||
if not region_items:
|
||||
errors.append("regions.items must contain at least one item")
|
||||
for index, item_value in enumerate(region_items):
|
||||
item = _mapping(item_value, f"regions.items[{index}]", errors)
|
||||
_strings(
|
||||
item,
|
||||
("region", "title"),
|
||||
f"regions.items[{index}]",
|
||||
errors,
|
||||
)
|
||||
weather_items = _array(
|
||||
regions.get("weather"),
|
||||
"regions.weather",
|
||||
errors,
|
||||
limit=10,
|
||||
)
|
||||
if not weather_items:
|
||||
errors.append("regions.weather must contain at least one item")
|
||||
for index, item_value in enumerate(weather_items):
|
||||
item = _mapping(item_value, f"regions.weather[{index}]", errors)
|
||||
_strings(
|
||||
item,
|
||||
("city", "temperature", "condition"),
|
||||
f"regions.weather[{index}]",
|
||||
errors,
|
||||
)
|
||||
|
||||
newsletter = _mapping(data.get("newsletter"), "newsletter", errors)
|
||||
_strings(
|
||||
newsletter,
|
||||
("title", "text", "placeholder", "button", "successPrefix"),
|
||||
"newsletter",
|
||||
errors,
|
||||
)
|
||||
|
||||
footer = _mapping(data.get("footer"), "footer", errors)
|
||||
_strings(footer, ("copyright", "legal"), "footer", errors)
|
||||
footer_links = _validate_links(
|
||||
footer.get("links"),
|
||||
"footer.links",
|
||||
errors,
|
||||
limit=12,
|
||||
require_items=True,
|
||||
)
|
||||
|
||||
if errors:
|
||||
raise DataValidationError("; ".join(errors))
|
||||
|
||||
return {
|
||||
"modules": list(MODULES),
|
||||
"counts": {
|
||||
"global_navigation": len(global_links),
|
||||
"channel_navigation": len(channel_links),
|
||||
"drawer_navigation": len(drawer_links),
|
||||
"related": len(related),
|
||||
"focus": len(focus_items),
|
||||
"videos": len(video_items),
|
||||
"more_news": len(more_items),
|
||||
"ranking": len(ranking),
|
||||
"regions": len(region_items),
|
||||
"weather": len(weather_items),
|
||||
"footer_links": len(footer_links),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def render_document(data: dict[str, Any], template: str, runtime: str) -> str:
|
||||
validate_document(data)
|
||||
if template.count(DATA_MARKER) != 1:
|
||||
raise DataValidationError(
|
||||
"Bundled template must contain exactly one data marker"
|
||||
)
|
||||
if template.count(RUNTIME_MARKER) != 1:
|
||||
raise DataValidationError(
|
||||
"Bundled template must contain exactly one runtime marker"
|
||||
)
|
||||
serialized = json.dumps(data, ensure_ascii=False, indent=2).replace(
|
||||
"</",
|
||||
"<\\/",
|
||||
)
|
||||
safe_runtime = runtime.replace("</script", "<\\/script")
|
||||
rendered = template.replace(DATA_MARKER, serialized)
|
||||
rendered = rendered.replace(RUNTIME_MARKER, safe_runtime)
|
||||
page_title = str((data.get("site") or {}).get("pageTitle") or "").strip()
|
||||
if page_title:
|
||||
rendered = TITLE_RE.sub(
|
||||
f"<title>{html_lib.escape(page_title)}</title>",
|
||||
rendered,
|
||||
count=1,
|
||||
)
|
||||
return rendered
|
||||
|
||||
|
||||
def _write_new(path: Path, content: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
with path.open("x", encoding="utf-8", newline="\n") as handle:
|
||||
handle.write(content)
|
||||
except FileExistsError as exc:
|
||||
raise DataValidationError(
|
||||
f"Refusing to overwrite existing file: {path}"
|
||||
) from exc
|
||||
|
||||
|
||||
def _emit(payload: dict[str, Any]) -> None:
|
||||
print(json.dumps(payload, ensure_ascii=False))
|
||||
|
||||
|
||||
def _command_init(output: Path) -> dict[str, Any]:
|
||||
data = _read_json(DEFAULT_DATA_PATH)
|
||||
summary = validate_document(data)
|
||||
_write_new(
|
||||
output,
|
||||
json.dumps(data, ensure_ascii=False, indent=2) + "\n",
|
||||
)
|
||||
return {"status": "ok", "action": "init", "output": str(output), **summary}
|
||||
|
||||
|
||||
def _command_validate(input_path: Path) -> dict[str, Any]:
|
||||
data = _read_json(input_path)
|
||||
summary = validate_document(data)
|
||||
return {"status": "ok", "action": "validate", "input": str(input_path), **summary}
|
||||
|
||||
|
||||
def _command_render(input_path: Path, output: Path) -> dict[str, Any]:
|
||||
data = _read_json(input_path)
|
||||
template = TEMPLATE_PATH.read_text(encoding="utf-8")
|
||||
runtime = RUNTIME_PATH.read_text(encoding="utf-8")
|
||||
rendered = render_document(data, template, runtime)
|
||||
_write_new(output, rendered)
|
||||
summary = validate_document(data)
|
||||
return {
|
||||
"status": "ok",
|
||||
"action": "render",
|
||||
"input": str(input_path),
|
||||
"output": str(output),
|
||||
**summary,
|
||||
}
|
||||
|
||||
|
||||
def _build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
init_parser = subparsers.add_parser(
|
||||
"init",
|
||||
help="Create a new editable JSON document",
|
||||
)
|
||||
init_parser.add_argument("--output", type=Path, required=True)
|
||||
|
||||
validate_parser = subparsers.add_parser(
|
||||
"validate",
|
||||
help="Validate an existing JSON document",
|
||||
)
|
||||
validate_parser.add_argument("--input", type=Path, required=True)
|
||||
|
||||
render_parser = subparsers.add_parser(
|
||||
"render",
|
||||
help="Render validated JSON into the bundled HTML template",
|
||||
)
|
||||
render_parser.add_argument("--input", type=Path, required=True)
|
||||
render_parser.add_argument("--output", type=Path, required=True)
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = _build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
if args.command == "init":
|
||||
result = _command_init(args.output)
|
||||
elif args.command == "validate":
|
||||
result = _command_validate(args.input)
|
||||
else:
|
||||
result = _command_render(args.input, args.output)
|
||||
except (DataValidationError, OSError) as exc:
|
||||
_emit({"status": "error", "action": args.command, "error": str(exc)})
|
||||
return 2
|
||||
_emit(result)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
Reference in new issue
Block a user