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,83 @@
|
||||
---
|
||||
name: cnn-page-generator
|
||||
description: 生成或绘制 CNN 及 CNN 风格的可交付全球新闻门户 HTML 网页;仅在用户明确要求 CNN 网页、CNN 风格新闻首页或点名本技能时使用。先把材料或检索结果整理成十模块 JSON,再用内置模板确定性渲染,保留右上角可视化 JSON 编辑弹窗。
|
||||
allowed-tools:
|
||||
- read_file
|
||||
- write_file
|
||||
- bash
|
||||
- present_files
|
||||
- web_search
|
||||
---
|
||||
|
||||
# CNN 页面生成器
|
||||
|
||||
本技能使用固定模板生成单文件 CNN 风格全球新闻首页。模型只负责材料收集和 JSON,禁止重新手写页面结构、CSS 或运行时脚本。最终页面自带右上角设置按钮;用户可在弹窗中按模块编辑 JSON,并通过「应用并渲染」即时更新页面。
|
||||
|
||||
编辑弹窗还提供“上传图片/视频”:先把光标放进目标报道、帖子、视频或带 `visual`/`media` 的内容对象,上传文件会转换为 `data:` 地址并写入该对象的 `media` 字段。不设文件大小拦截;较大文件可能超过浏览器本地缓存容量,应同时下载 JSON 留存。
|
||||
|
||||
页面中已由 `media` 数据渲染的图片和视频还带悬浮上传图标:鼠标移入媒体后点击可任选图片或视频并直接替换,文件的实际类型会自动写入新的 `media.type`,结果同步写回页面 JSON 与浏览器缓存。头像、Logo 和无法映射回 JSON 的装饰图不会显示该入口;不按原媒体类型限制,也不设置文件大小拦截。
|
||||
|
||||
默认视觉直接复用模板原有的示例图:不要调用图像生成工具,不要让模型重新生成、拼装或内嵌新的内容型 SVG,也不要为了寻找“标准配图”延长检索。用户没有提供可直接使用的图片/视频且聚焦检索未得到可靠直链时,保留默认 JSON 的 `visual` 或内置视觉类型;这些是模板自带的静态示例,调用技能时不重新绘制。不要把大段 base64 示例图重复写进 JSON,图不合适时由用户在成品页面悬浮上传替换。
|
||||
|
||||
## 触发边界
|
||||
|
||||
- 用户明确说「生成/画/制作 CNN 网页」「CNN 风格新闻首页/全球新闻门户」或点名 `cnn-page-generator` 时使用。
|
||||
- 仅讨论 CNN、分析新闻机构、总结新闻或普通文本中出现 CNN 时不要使用。
|
||||
- 这是单页电视新闻门户模板,不改用新华社、BBC、白宫官网或通用多页门户模板。
|
||||
|
||||
## 极速工作流(默认)
|
||||
|
||||
页面结构已经固定。模型只写新闻主题和少量可选文案;脚本负责生成完整中文十模块、栏目新闻、视频标题、专题分析和明确标注的非实时示意数据,并在一次进程内完成校验与渲染。
|
||||
|
||||
1. 用 `write_file` 创建 `/mnt/user-data/outputs/cnn-page-spec.json`。最小规格只有一个高层字段:
|
||||
|
||||
```json
|
||||
{"topic":"茂达蛋 IP"}
|
||||
```
|
||||
|
||||
需要精确控制头条时可增加 `headline`、`headlineSummary`、`breaking`;需要指定栏目标题时可增加 `latestHeadlines`、`videoHeadlines`、`worldHeadlines` 字符串数组。不得写十模块 JSON、`$set` 或深层字段路径。
|
||||
2. 只执行一次 `python /mnt/skills/public/cnn-page-generator/scripts/fast_page.py --spec /mnt/user-data/outputs/cnn-page-spec.json --output-dir /mnt/user-data/outputs`。
|
||||
3. stdout 为 `status: ok` 后立即用 `present_files` 交付返回的完整 JSON 与 HTML;不要重命名、复制或清理输出文件,最终只回复一句完成说明。
|
||||
|
||||
`topic` 必填;显式提供的新闻、摘要、快讯、栏目标题和分析正文必须使用简体中文,品牌名与必要专名可保留。没有可靠实时数据时只写主题,脚本会自动使用“中文示意、非实时”内容。未提供媒体直链时不要写 `media`,脚本会保留模板示例视觉供用户上传替换。禁止读取默认数据、契约、生成后的 JSON/HTML、模板、运行时或脚本源码,禁止探路渲染、`--help`、独立 `init/validate/render`、二次渲染、生成后打补丁、重命名清理、临时脚本和冗长过程说明。规格报错时只修正规格一次并重跑。只有用户明确要求改变模块结构或批量重建完整数组时,才使用下面的完整工作流。
|
||||
|
||||
## 完整工作流(仅限结构改造)
|
||||
|
||||
1. 读取当前会话材料、上传附件和已有产物,确定站点、导航、突发新闻、头条、最新报道、视频、全球商业、市场、简报和页脚。
|
||||
2. 用户要求基于公开资料、主题涉及近期事件,或明确要求检索时,先做聚焦检索并把来源事实转为页面文案;用户明确说不要检索时不得联网。没有材料时使用中性示例并明确为示例,不把模拟时间或市场数据描述成实时数据。
|
||||
3. 初始化新的完整 JSON:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/cnn-page-generator/scripts/render_cnn_page.py init --output /mnt/user-data/outputs/cnn-page-data.json
|
||||
```
|
||||
|
||||
4. 只修改 JSON。十个顶层模块必须全部保留:`site`、`navigation`、`breaking`、`lead`、`latest`、`video`、`world`、`markets`、`newsletter`、`footer`。字段不确定时读取 [references/data-schema.md](references/data-schema.md)。
|
||||
5. 校验 JSON:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/cnn-page-generator/scripts/render_cnn_page.py validate --input /mnt/user-data/outputs/cnn-page-data.json
|
||||
```
|
||||
|
||||
6. 确定性渲染到 `outputs/`:
|
||||
|
||||
```text
|
||||
python /mnt/skills/public/cnn-page-generator/scripts/render_cnn_page.py render --input /mnt/user-data/outputs/cnn-page-data.json --output /mnt/user-data/outputs/cnn-page.html
|
||||
```
|
||||
|
||||
7. 检查 stdout 的 `status` 为 `ok`、HTML 存在且占位符已经消失,再用 `present_files` 同时交付 HTML 与源 JSON。不要在聊天中粘贴完整 HTML。
|
||||
|
||||
## 内容映射
|
||||
|
||||
- 最高优先级的单条报道放入 `lead.primary`;头条旁的补充报道放入 `lead.sideStories`。
|
||||
- 普通报道分配到 `latest.items` 或 `world.items`;视频内容放入 `video.items`,不要混用。
|
||||
- `visual` 继续作为内置后备视觉;需要替换时,可在对应内容对象增加受校验的 `media`(`image`、`video`、`webpage`)。外部文本不得包含 HTML、脚本或直接 iframe。
|
||||
- 市场涨跌方向使用 `up`、`down` 或 `flat`。没有可靠来源时使用示例值或明确的静态快照,不冒充实时行情。
|
||||
- 页面引用近期事实时必须以检索材料为准;模板内置内容只是结构示例。
|
||||
|
||||
## 重要约束
|
||||
|
||||
- 只编辑 JSON,不修改 `assets/cnn-template.html` 或 `assets/cnn-runtime.js`,不复制模板后手改 DOM。
|
||||
- 初始化与渲染默认拒绝覆盖已有文件;路径存在时换新文件名,不删除旧产物。
|
||||
- 页面结构、样式和脚本完全自包含,不依赖 CNN API、CDN 或 npm;仅当 JSON 明确提供受校验的媒体 URL 时加载图片、视频或网页。
|
||||
- 保留突发条、搜索、直播弹窗、字幕切换、收藏、分享、移动菜单、市场快照、订阅表单与响应式布局。
|
||||
- 浏览器缓存以初始 JSON 指纹隔离;沙箱禁止持久存储时必须继续使用内嵌 JSON 正常渲染。
|
||||
+792
@@ -0,0 +1,792 @@
|
||||
(() => {
|
||||
"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", "latest", "video", "world", "markets", "newsletter", "footer"];
|
||||
const MODULE_META = {
|
||||
site: ["站点信息", "品牌、日期与工具栏"],
|
||||
navigation: ["导航", "频道、搜索与移动菜单"],
|
||||
breaking: ["突发新闻", "突发标签、标题与时间"],
|
||||
lead: ["头条", "主报道、侧栏与实时更新"],
|
||||
latest: ["最新报道", "新闻卡片与摘要"],
|
||||
video: ["视频现场", "直播弹窗与视频卡片"],
|
||||
world: ["全球商业", "列表报道与分析评论"],
|
||||
markets: ["市场快照", "行情名称、数值与涨跌"],
|
||||
newsletter: ["新闻简报", "订阅文案与反馈"],
|
||||
footer: ["页脚", "栏目链接与版权信息"]
|
||||
};
|
||||
const VISUAL_TYPES = new Set(["summit", "train", "coast", "city", "deep-sea", "night-city", "space", "music", "trade", "market", "payments", "energy"]);
|
||||
const embeddedData = JSON.parse(qs("#cnnPageData").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 = "cnn-page-data-v1:" + pageFingerprint;
|
||||
const themeKey = "cnn-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) {
|
||||
/* Sandboxed 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 toast = qs("#toast");
|
||||
let toastTimer = 0;
|
||||
const showToast = (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"), 2400);
|
||||
};
|
||||
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:999px;color:#fff;background:rgba(0,0,0,.72);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,.72);border-radius:8px}.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 = "city";
|
||||
}
|
||||
const type = safeVisual(requested, "city");
|
||||
const title = escapeHTML(label || type);
|
||||
let content = "";
|
||||
let background = "#253440";
|
||||
if (type === "summit") {
|
||||
background = "#425a70";
|
||||
content = '<circle cx="610" cy="88" r="55" fill="#f3d3a0" opacity=".75"/><path d="M0 360 140 322l126 28 104-70 157 64 132-84 155 68 186-91v283H0Z" fill="#18252d"/><path d="M130 520V240l170-75 174 82v273Z" fill="#111b22"/><path d="M150 258 300 193l154 67v145H150Z" fill="#9cb3c0" opacity=".68"/><path d="M168 282h266M168 325h266M205 234v170M275 205v199M350 216v188M410 250v154" stroke="#eaf1f2" stroke-opacity=".42" stroke-width="5"/><rect x="525" y="335" width="245" height="185" fill="#25333d"/><path d="M545 370h205M545 410h205M545 450h205" stroke="#e9b77f" stroke-opacity=".65" stroke-width="7"/><path d="M0 450c190-42 345-27 525 10 173 35 307 28 475-18v78H0Z" fill="#0a1014"/>';
|
||||
} else if (type === "train") {
|
||||
background = "#b8d7df";
|
||||
content = '<path d="M0 190 130 86l120 95L395 62l305 175v93H0Z" fill="#516e62"/><path d="M0 250c180-64 350-35 700 18v62H0Z" fill="#2c4538"/><path d="M50 284c190-48 360-37 600 20" stroke="#d4d1c4" stroke-width="10" fill="none"/><g transform="translate(260 225) rotate(5)"><path d="M0 0h225l38 34-8 31H0Z" fill="#eee9dc"/><path d="M16 12h184v25H16Z" fill="#334f5b"/><path d="M220 5l31 29h-40Z" fill="#c60000"/></g>';
|
||||
} else if (type === "coast") {
|
||||
background = "#acd5e6";
|
||||
content = '<path d="M0 310c113-55 173-65 276-35 125 36 237-8 524-138v313H0Z" fill="#315f6a"/><path d="M0 337c125-47 195-41 313-5 122 37 293-20 487-104" stroke="#e9f0e8" stroke-width="18" fill="none" opacity=".8"/><path d="M570 215v128h-86V235Z" fill="#d0b180"/><path d="M538 145 590 215h-104Z" fill="#7d3f31"/><rect x="526" y="271" width="17" height="72" fill="#4c3027"/><circle cx="536" cy="162" r="11" fill="#ffd66f"/>';
|
||||
} else if (type === "city") {
|
||||
background = "#d7d1c5";
|
||||
content = '<path d="M0 330 170 135l120 83L438 73l262 217v160H0Z" fill="#6e756a"/><path d="M75 450V180h175v270M370 450V122h190v328" fill="#373d3c"/><g fill="#e8c675"><rect x="105" y="220" width="34" height="42"/><rect x="175" y="220" width="34" height="42"/><rect x="400" y="165" width="41" height="50"/><rect x="485" y="165" width="41" height="50"/></g><path d="M0 385h700" stroke="#be302d" stroke-width="8"/>';
|
||||
} else if (type === "deep-sea") {
|
||||
background = "#10141c";
|
||||
content = '<circle cx="405" cy="220" r="145" fill="#263853"/><path d="M285 270c52-132 188-205 312-183-55 41-84 89-108 148-40 100-89 137-204 35Z" fill="#4e80ac"/><g fill="#b6dbff"><circle cx="315" cy="165" r="5"/><circle cx="484" cy="110" r="4"/><circle cx="590" cy="240" r="5"/><circle cx="195" cy="268" r="4"/></g><path d="M100 374c150-40 420-48 565 5" stroke="#c60000" stroke-width="7" fill="none"/><circle cx="500" cy="360" r="14" fill="#fff"/>';
|
||||
} else if (type === "night-city") {
|
||||
background = "#071525";
|
||||
content = '<g fill="#203247"><rect x="35" y="155" width="108" height="295"/><rect x="164" y="92" width="116" height="358"/><rect x="300" y="185" width="96" height="265"/><rect x="420" y="55" width="148" height="395"/><rect x="590" y="137" width="92" height="313"/></g><g fill="#e6ad69"><path d="M57 191h64v7H57Zm0 45h64v7H57Zm130-93h70v7h-70Zm0 49h70v7h-70Zm258-91h98v8h-98Zm0 57h98v8h-98Z"/></g><path d="M0 376c190-76 370-76 700-7" stroke="#dd1b2e" stroke-width="8" fill="none"/><path d="M0 397c210-67 430-54 700 2" stroke="#fff" stroke-opacity=".55" stroke-width="3" fill="none"/>';
|
||||
} else if (type === "space") {
|
||||
background = "#080b13";
|
||||
content = '<circle cx="575" cy="100" r="65" fill="#94b7d3"/><g transform="translate(345 230) rotate(-14)"><rect x="-105" y="-35" width="210" height="70" rx="8" fill="#d9dce0"/><rect x="-215" y="-62" width="94" height="124" fill="#355a82"/><rect x="121" y="-62" width="94" height="124" fill="#355a82"/><circle cx="12" cy="0" r="22" fill="#8ea1b3"/></g><g fill="#fff"><circle cx="90" cy="75" r="3"/><circle cx="180" cy="355" r="3"/><circle cx="500" cy="315" r="3"/></g>';
|
||||
} else if (type === "music") {
|
||||
background = "#79143b";
|
||||
content = '<path d="M140 340V90h420v250" stroke="#101018" stroke-width="28" fill="none"/><g fill="#f2c247"><circle cx="220" cy="130" r="20"/><circle cx="350" cy="130" r="20"/><circle cx="480" cy="130" r="20"/></g><path d="M344 148v140m-32-85h64" stroke="#fff" stroke-width="15"/><g fill="#12131b"><circle cx="92" cy="410" r="48"/><circle cx="205" cy="400" r="53"/><circle cx="330" cy="416" r="49"/><circle cx="475" cy="399" r="55"/><circle cx="610" cy="414" r="50"/></g>';
|
||||
} else if (type === "trade") {
|
||||
background = "#c9dae0";
|
||||
content = '<path d="M0 330 210 95l150 175 120-84 220 155v109H0Z" fill="#6a837c"/><path d="M60 390h580" stroke="#fff" stroke-width="16"/><path d="M180 370V240h350v130" fill="#24343c"/>';
|
||||
} else if (type === "market") {
|
||||
background = "#ead7bd";
|
||||
content = '<circle cx="350" cy="160" r="105" fill="#c60000" opacity=".82"/><path d="M80 380h540M120 320h460M165 260h370" stroke="#31353a" stroke-width="22"/>';
|
||||
} else if (type === "payments") {
|
||||
background = "#18232b";
|
||||
content = '<rect x="90" y="70" width="520" height="310" rx="24" fill="#314b5e"/><path d="M155 315 255 215l82 45 150-145" stroke="#7ee0a0" stroke-width="24" fill="none"/><circle cx="487" cy="115" r="24" fill="#7ee0a0"/>';
|
||||
} else {
|
||||
background = "#bdd4d5";
|
||||
content = '<path d="M0 315c210-82 375-112 700-35v170H0Z" fill="#4f7b6b"/><g fill="#edf2e9"><rect x="115" y="155" width="82" height="180"/><rect x="280" y="100" width="92" height="235"/><rect x="485" y="175" width="76" height="160"/></g><path d="M156 155V85m170 15V28m197 147v-62" stroke="#edf2e9" stroke-width="14"/>';
|
||||
}
|
||||
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 = () => {
|
||||
const dark = document.body.classList.contains("dark");
|
||||
qs("#themeToggle").setAttribute("aria-label", dark ? "切换浅色模式" : "切换深色模式");
|
||||
};
|
||||
const toggleTheme = () => {
|
||||
const dark = document.body.classList.toggle("dark");
|
||||
writeStorage(themeKey, dark ? "dark" : "light");
|
||||
syncThemeLabel();
|
||||
showToast(dark ? "已切换至深色模式" : "已切换至浅色模式");
|
||||
};
|
||||
|
||||
const renderSite = () => {
|
||||
const site = pageData.site || {};
|
||||
document.title = site.pageTitle || site.brand || "CNN";
|
||||
qs('meta[name="description"]').content = site.description || "";
|
||||
qs("#brandText").textContent = site.brand || "CNN";
|
||||
qs("#brandLink").setAttribute("aria-label", (site.brand || "CNN") + " 首页");
|
||||
qs("#drawerBrand").textContent = site.brand || "CNN";
|
||||
const utilityLinks = Array.isArray(site.utilityLinks) ? site.utilityLinks : [];
|
||||
qs("#utilityLeft").innerHTML = "<span>" + escapeHTML(site.date) + "</span>" + utilityLinks.map((label, index) =>
|
||||
'<a href="' + (index === 0 ? "#markets" : "#newsletter") + '">' + escapeHTML(label) + "</a>"
|
||||
).join("");
|
||||
const marketSummary = Array.isArray(site.marketSummary) ? site.marketSummary : [];
|
||||
qs("#utilityRight").innerHTML = marketSummary.map((item) =>
|
||||
"<span>" + escapeHTML(item.label) + ' <b class="market-' + (item.direction === "down" ? "down" : item.direction === "flat" ? "flat" : "up") + '">' +
|
||||
escapeHTML(item.value) + "</b></span>"
|
||||
).join("") + "<span>" + escapeHTML(site.weather) + "</span>";
|
||||
qs("#frontLabel").textContent = site.frontLabel || "";
|
||||
applyInitialTheme();
|
||||
};
|
||||
|
||||
const renderNavigation = () => {
|
||||
const navigation = pageData.navigation || {};
|
||||
const items = Array.isArray(navigation.items) ? navigation.items : [];
|
||||
const markup = items.map((item, index) => '<a class="' + (index === 0 ? "active" : "") + '" href="' +
|
||||
safeHref(item.href) + '">' + escapeHTML(item.label) + "</a>").join("");
|
||||
qs("#desktopNav").innerHTML = markup;
|
||||
qs("#drawerLinks").innerHTML = markup;
|
||||
qs("#searchInput").placeholder = navigation.searchPlaceholder || "";
|
||||
qs("#searchSubmit").textContent = navigation.searchButton || "搜索";
|
||||
qs("#liveLabel").textContent = navigation.liveLabel || "直播";
|
||||
qs("#drawerFooter").textContent = navigation.drawerFooter || "";
|
||||
};
|
||||
|
||||
const renderBreaking = () => {
|
||||
const data = pageData.breaking || {};
|
||||
qs("#breakingLabel").textContent = data.label || "";
|
||||
qs("#breakingCopy").textContent = data.text || "";
|
||||
qs("#breakingTime").textContent = data.time || "";
|
||||
};
|
||||
|
||||
const storyTools = () => '<div class="story-tools"><button class="tool-btn save-btn"><svg viewBox="0 0 24 24"><path d="M6 4h12v17l-6-4-6 4Z"/></svg><span>收藏</span></button><button class="tool-btn share-btn"><svg viewBox="0 0 24 24"><circle cx="18" cy="5" r="2.5"/><circle cx="6" cy="12" r="2.5"/><circle cx="18" cy="19" r="2.5"/><path d="m8.2 10.8 7.5-4.4M8.2 13.2l7.5 4.4"/></svg><span>分享</span></button></div>';
|
||||
const renderLead = () => {
|
||||
const data = pageData.lead || {};
|
||||
const primary = data.primary || {};
|
||||
const sideStories = Array.isArray(data.sideStories) ? data.sideStories : [];
|
||||
const updates = Array.isArray(data.updates) ? data.updates : [];
|
||||
qs("#leadGrid").innerHTML = '<article class="lead-story"><div class="kicker">' + escapeHTML(primary.kicker) +
|
||||
"</div><h1>" + escapeHTML(primary.title) + '</h1><p class="dek">' + escapeHTML(primary.summary) +
|
||||
'</p><div class="story-meta"><strong>' + escapeHTML(primary.byline) + "</strong><span>·</span><time>" +
|
||||
escapeHTML(primary.updated) + "</time><span>·</span><span>" + escapeHTML(primary.readingTime) +
|
||||
'</span></div><div class="visual lead-visual">' + visualSvg(primary.media || primary.visual, primary.visualLabel) +
|
||||
'<span class="visual-tag">' + escapeHTML(primary.tag) + '</span><span class="visual-credit">' +
|
||||
escapeHTML(primary.credit) + "</span></div>" + storyTools() + '</article><aside class="side-stack">' +
|
||||
sideStories.map((story) => '<article class="side-story">' +
|
||||
(story.visual ? '<div class="visual mini-visual">' + visualSvg(story.media || story.visual, story.title) + "</div>" : "") +
|
||||
'<div class="kicker">' + escapeHTML(story.kicker) + "</div><h2>" + escapeHTML(story.title) +
|
||||
"</h2><p>" + escapeHTML(story.summary) + "</p></article>").join("") +
|
||||
'<div class="live-list"><div class="live-list-head"><span>' + escapeHTML(data.updatesTitle) +
|
||||
'</span><button class="open-live">打开直播 →</button></div>' + updates.map((item) =>
|
||||
'<div class="live-item"><time>' + escapeHTML(item.time) + "</time><span>" + escapeHTML(item.text) + "</span></div>"
|
||||
).join("") + "</div></aside>";
|
||||
};
|
||||
|
||||
const renderLatest = () => {
|
||||
const data = pageData.latest || {};
|
||||
qs("#latestTitle").textContent = data.title || "";
|
||||
qs("#latestMore").textContent = data.moreLabel || "";
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#latestGrid").innerHTML = items.map((item, index) =>
|
||||
'<article class="news-card' + (index === 0 ? " feature" : "") + '" data-searchable><div class="card-visual visual">' +
|
||||
visualSvg(item.media || item.visual, item.title) + '</div><div class="kicker">' + escapeHTML(item.kicker) + "</div><h3>" +
|
||||
escapeHTML(item.title) + "</h3><p>" + escapeHTML(item.summary) + '</p><span class="timestamp">' +
|
||||
escapeHTML(item.time) + "</span></article>"
|
||||
).join("");
|
||||
};
|
||||
|
||||
const renderVideo = () => {
|
||||
const data = pageData.video || {};
|
||||
qs("#videoTitle").textContent = data.title || "";
|
||||
qs("#videoMore").textContent = data.moreLabel || "";
|
||||
qs("#liveTitle").textContent = data.modalTitle || "";
|
||||
qs("#playerTitle").textContent = data.liveTitle || "";
|
||||
qs("#playerSubtitle").textContent = data.liveSubtitle || "";
|
||||
qs("#modalNote").textContent = data.modalNote || "";
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#videoGrid").innerHTML = items.map((item, index) =>
|
||||
'<article class="video-card' + (index === 0 ? " feature" : "") + '" data-searchable><button class="card-visual visual 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="m8 5 11 7-11 7Z"/></svg></span><span class="duration">' +
|
||||
escapeHTML(item.duration) + "</span></button><h3>" + escapeHTML(item.title) + '</h3><span class="timestamp">' +
|
||||
escapeHTML(item.meta) + "</span></article>"
|
||||
).join("");
|
||||
};
|
||||
|
||||
const renderWorld = () => {
|
||||
const data = pageData.world || {};
|
||||
qs("#worldTitle").textContent = data.title || "";
|
||||
qs("#worldMore").textContent = data.moreLabel || "";
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#worldList").innerHTML = items.map((item) =>
|
||||
'<article class="list-item" data-searchable><div class="list-thumb">' + visualSvg(item.media || item.visual, item.title) +
|
||||
'</div><div><div class="kicker">' + escapeHTML(item.kicker) + "</div><h3>" + escapeHTML(item.title) +
|
||||
'</h3><span class="timestamp">' + escapeHTML(item.time) + "</span></div></article>"
|
||||
).join("");
|
||||
const analysis = data.analysis || {};
|
||||
qs("#opinion").innerHTML = '<div class="kicker">' + escapeHTML(analysis.kicker) + "</div><h3>" +
|
||||
escapeHTML(analysis.title) + "</h3><p>" + escapeHTML(analysis.text) +
|
||||
'</p><div class="author"><span class="author-mark">' + escapeHTML(analysis.initial) + "</span><span>" +
|
||||
escapeHTML(analysis.author) + "<br><small>" + escapeHTML(analysis.role) + "</small></span></div>";
|
||||
};
|
||||
|
||||
const renderMarkets = () => {
|
||||
const data = pageData.markets || {};
|
||||
qs("#marketsTitle").textContent = data.title || "";
|
||||
qs("#marketsMore").textContent = data.moreLabel || "";
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
qs("#marketsGrid").innerHTML = items.map((item) =>
|
||||
'<div class="market"><div class="market-name">' + escapeHTML(item.name) + '</div><div class="market-val">' +
|
||||
escapeHTML(item.value) + '</div><div class="market-change market-' +
|
||||
(item.direction === "down" ? "down" : item.direction === "flat" ? "flat" : "up") + '">' +
|
||||
escapeHTML(item.change) + "</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 columns = Array.isArray(data.columns) ? data.columns : [];
|
||||
qs("#footerGrid").innerHTML = '<div><div class="footer-brand">' + escapeHTML(pageData.site.brand) +
|
||||
"</div><p>" + escapeHTML(data.tagline) + "</p></div>" + columns.map((column) =>
|
||||
"<div><h3>" + escapeHTML(column.title) + "</h3>" + (Array.isArray(column.links) ? column.links : []).map((link) =>
|
||||
'<a href="' + safeHref(link.href) + '">' + escapeHTML(link.label) + "</a>"
|
||||
).join("") + "</div>"
|
||||
).join("");
|
||||
qs("#copyright").textContent = data.copyright || "";
|
||||
qs("#legal").textContent = data.legal || "";
|
||||
};
|
||||
|
||||
const renderAll = () => {
|
||||
renderSite();
|
||||
renderNavigation();
|
||||
renderBreaking();
|
||||
renderLead();
|
||||
renderLatest();
|
||||
renderVideo();
|
||||
renderWorld();
|
||||
renderMarkets();
|
||||
renderNewsletter();
|
||||
renderFooter();
|
||||
bindDynamicInteractions();
|
||||
};
|
||||
|
||||
const liveModal = qs("#liveModal");
|
||||
let lastFocus = null;
|
||||
function openLive() {
|
||||
lastFocus = document.activeElement;
|
||||
liveModal.classList.add("open");
|
||||
document.body.style.overflow = "hidden";
|
||||
qs("#liveClose").focus();
|
||||
}
|
||||
const closeLive = () => {
|
||||
liveModal.classList.remove("open");
|
||||
document.body.style.overflow = "";
|
||||
if (lastFocus) lastFocus.focus();
|
||||
};
|
||||
const drawer = qs("#drawer");
|
||||
const openDrawer = () => {
|
||||
drawer.classList.add("open");
|
||||
document.body.style.overflow = "hidden";
|
||||
qs("#drawerClose").focus();
|
||||
};
|
||||
const closeDrawer = () => {
|
||||
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(".save-btn").forEach((button) => button.addEventListener("click", () => {
|
||||
const saved = button.classList.toggle("saved");
|
||||
qs("span", button).textContent = saved ? "已收藏" : "收藏";
|
||||
showToast(saved ? "报道已加入收藏" : "已取消收藏");
|
||||
}));
|
||||
qsa(".share-btn").forEach((button) => button.addEventListener("click", async () => {
|
||||
try {
|
||||
if (navigator.share) {
|
||||
await navigator.share({title: document.title, url: location.href});
|
||||
} else if (navigator.clipboard) {
|
||||
await navigator.clipboard.writeText(location.href);
|
||||
showToast("链接已复制");
|
||||
} else {
|
||||
showToast("可复制浏览器地址进行分享");
|
||||
}
|
||||
} catch (_error) {
|
||||
/* User cancellation is not an error state. */
|
||||
}
|
||||
}));
|
||||
qsa(".drawer-links a").forEach((link) => link.addEventListener("click", closeDrawer));
|
||||
};
|
||||
|
||||
qs("#themeToggle").addEventListener("click", toggleTheme);
|
||||
qs("#searchToggle").addEventListener("click", () => {
|
||||
const panel = qs("#searchPanel");
|
||||
panel.classList.toggle("open");
|
||||
if (panel.classList.contains("open")) window.setTimeout(() => qs("#searchInput").focus(), 20);
|
||||
});
|
||||
qs("#searchForm").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const query = qs("#searchInput").value.trim().toLocaleLowerCase();
|
||||
const corpus = [
|
||||
pageData.breaking.text,
|
||||
pageData.lead.primary.title,
|
||||
pageData.lead.primary.summary,
|
||||
...(pageData.lead.sideStories || []).flatMap((item) => [item.title, item.summary]),
|
||||
...(pageData.latest.items || []).flatMap((item) => [item.title, item.summary]),
|
||||
...(pageData.video.items || []).map((item) => item.title),
|
||||
...(pageData.world.items || []).map((item) => item.title),
|
||||
pageData.world.analysis.title,
|
||||
pageData.world.analysis.text
|
||||
];
|
||||
const matches = query ? corpus.filter((value) => String(value || "").toLocaleLowerCase().includes(query)).length : 0;
|
||||
const result = qs("#searchResults");
|
||||
result.classList.add("show");
|
||||
result.textContent = query ? "找到与“" + qs("#searchInput").value.trim() + "”相关的 " + matches + " 篇报道" : "请输入搜索关键词";
|
||||
});
|
||||
qs("#liveClose").addEventListener("click", closeLive);
|
||||
liveModal.addEventListener("click", (event) => {
|
||||
if (event.target === liveModal) closeLive();
|
||||
});
|
||||
qs("#captionToggle").addEventListener("click", (event) => {
|
||||
const isOn = event.currentTarget.textContent.includes("开");
|
||||
event.currentTarget.textContent = "CC 字幕:" + (isOn ? "关" : "开");
|
||||
showToast(isOn ? "字幕已关闭" : "字幕已开启");
|
||||
});
|
||||
qs("#menuOpen").addEventListener("click", openDrawer);
|
||||
qs("#drawerClose").addEventListener("click", closeDrawer);
|
||||
drawer.addEventListener("click", (event) => {
|
||||
if (event.target === drawer) closeDrawer();
|
||||
});
|
||||
qs("#newsletterForm").addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const email = qs("#email").value.trim();
|
||||
qs("#formStatus").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)) {
|
||||
showToast("请修正 JSON 后再应用");
|
||||
return;
|
||||
}
|
||||
pageData = clone(editorDraft);
|
||||
saveData();
|
||||
renderAll();
|
||||
showToast("JSON 已应用到页面");
|
||||
});
|
||||
qs("#resetJson").addEventListener("click", () => {
|
||||
pageData = clone(initialData);
|
||||
editorDraft = clone(initialData);
|
||||
removeStorage(storageKey);
|
||||
removeStorage(themeKey);
|
||||
themeInitialized = false;
|
||||
renderAll();
|
||||
renderModuleTabs();
|
||||
selectModule(activeModule, true);
|
||||
showToast("已恢复初始 JSON");
|
||||
});
|
||||
qs("#copyJson").addEventListener("click", async () => {
|
||||
if (!storeActiveDraft()) return;
|
||||
const text = JSON.stringify(editorDraft, null, 2);
|
||||
try {
|
||||
if (navigator.clipboard) await navigator.clipboard.writeText(text);
|
||||
showToast("完整 JSON 已复制");
|
||||
} catch (_error) {
|
||||
jsonEditor.focus();
|
||||
jsonEditor.select();
|
||||
showToast("已选中当前模块,请手动复制");
|
||||
}
|
||||
});
|
||||
qs("#downloadJson").addEventListener("click", () => {
|
||||
if (!storeActiveDraft()) return;
|
||||
const blob = new Blob([JSON.stringify(editorDraft, null, 2) + "\n"], {type: "application/json"});
|
||||
const link = document.createElement("a");
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = "cnn-page-data.json";
|
||||
link.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(link.href), 0);
|
||||
showToast("JSON 已下载");
|
||||
});
|
||||
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape") {
|
||||
if (liveModal.classList.contains("open")) closeLive();
|
||||
if (drawer.classList.contains("open")) closeDrawer();
|
||||
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();
|
||||
})();
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
<!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="AXIS 全球新闻——原创电视新闻风格首页,汇集突发、全球、商业、科技、文化与观点。" />
|
||||
<meta name="theme-color" content="#c60000" />
|
||||
<title>AXIS — 全球新闻现场</title>
|
||||
<style>
|
||||
:root {
|
||||
--red:#c60000; --red-2:#e11; --ink:#101010; --paper:#fff; --soft:#f3f3f3;
|
||||
--line:#d8d8d8; --muted:#666; --nav:#0c0c0c; --blue:#135c9c; --max:1240px;
|
||||
--serif: Georgia, 'Times New Roman', serif; --sans: Arial, Helvetica, sans-serif;
|
||||
--shadow:0 20px 60px rgba(0,0,0,.22);
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
html{scroll-behavior:smooth}
|
||||
body{margin:0;background:var(--paper);color:var(--ink);font-family:var(--sans);font-size:16px;line-height:1.45}
|
||||
body.dark{--paper:#111;--ink:#f6f6f6;--soft:#1b1b1b;--line:#383838;--muted:#aaa;--nav:#050505;--blue:#65aee9}
|
||||
button,input{font:inherit}
|
||||
button,a{cursor:pointer}
|
||||
a{color:inherit;text-decoration:none}
|
||||
img,svg{display:block;max-width:100%}
|
||||
button{border:0;background:none;color:inherit}
|
||||
:focus-visible{outline:3px solid #2d8ee3;outline-offset:3px}
|
||||
.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-link{position:fixed;left:12px;top:calc(var(--df-generated-header-height,0px) + 10px);z-index:200;background:#fff;color:#111;padding:10px 14px;font-weight:800;transform:translateY(-160%);transition:transform .2s}.skip-link:focus{transform:none}
|
||||
.wrap{width:min(var(--max),calc(100% - 40px));margin:auto}
|
||||
|
||||
.utility{background:#000;color:#ddd;font-size:12px;border-bottom:1px solid #333}
|
||||
.utility .wrap{height:30px;display:flex;align-items:center;justify-content:space-between;gap:16px}
|
||||
.utility-links{display:flex;gap:18px;align-items:center}
|
||||
.market-up{color:#6dd392;font-weight:700}.market-down{color:#ff8b8b;font-weight:700}
|
||||
.market-flat{color:var(--muted);font-weight:700}
|
||||
.topbar{background:var(--nav);color:white;position:sticky;top:var(--df-generated-header-height,0px);z-index:30;border-bottom:1px solid #303030}
|
||||
.topbar .wrap{height:64px;display:flex;align-items:center;gap:20px}
|
||||
.brand{align-self:stretch;background:var(--red);display:grid;place-items:center;padding:0 18px;font-weight:900;font-size:28px;letter-spacing:-2px;transform:skew(-6deg)}
|
||||
.brand span{transform:skew(6deg)}
|
||||
.nav{display:flex;gap:22px;align-items:center;font-weight:700;font-size:14px;white-space:nowrap}
|
||||
.nav a{padding:23px 0 19px;border-bottom:4px solid transparent;transition:border-color .2s,color .2s}
|
||||
.nav a:hover,.nav a.active{border-color:var(--red-2);color:#fff}
|
||||
.top-actions{margin-left:auto;display:flex;align-items:center;gap:7px}
|
||||
.icon-btn{width:44px;height:44px;display:grid;place-items:center;border-radius:50%;transition:background .2s;color:inherit}
|
||||
.icon-btn:hover{background:rgba(255,255,255,.14)}
|
||||
.icon-btn svg{width:21px;height:21px;stroke:currentColor;fill:none;stroke-width:2}
|
||||
.live-btn{height:38px;padding:0 14px;border:1px solid #777;border-radius:3px;color:white;font-weight:800;display:flex;align-items:center;gap:8px;transition:background .2s,border-color .2s}
|
||||
.live-btn:hover{background:var(--red);border-color:var(--red)}
|
||||
.live-dot{width:8px;height:8px;background:#f22;border-radius:50%;box-shadow:0 0 0 4px rgba(255,34,34,.2);animation:pulse 2s infinite}
|
||||
.menu-btn{display:none}
|
||||
@keyframes pulse{50%{box-shadow:0 0 0 8px rgba(255,34,34,0)}}
|
||||
|
||||
.breaking{border-bottom:1px solid var(--line);background:var(--paper)}
|
||||
.breaking .wrap{min-height:44px;display:grid;grid-template-columns:auto 1fr auto;align-items:center}
|
||||
.breaking-label{align-self:stretch;background:var(--red);color:#fff;font-size:12px;font-weight:900;letter-spacing:.08em;display:flex;align-items:center;padding:0 14px;text-transform:uppercase}
|
||||
.breaking-copy{font-size:14px;font-weight:700;padding:0 16px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}
|
||||
.breaking-time{font-size:12px;color:var(--muted);padding-left:14px;border-left:1px solid var(--line)}
|
||||
|
||||
.search-panel{display:none;background:var(--soft);border-bottom:1px solid var(--line)}
|
||||
.search-panel.open{display:block}
|
||||
.search-inner{min-height:86px;display:flex;align-items:center;gap:12px}
|
||||
.search-inner input{flex:1;height:48px;border:1px solid var(--line);background:var(--paper);color:var(--ink);padding:0 16px;font-size:18px}
|
||||
.search-inner button{height:48px;padding:0 22px;background:var(--ink);color:var(--paper);font-weight:800}
|
||||
.search-results{padding-bottom:15px;display:none;color:var(--muted);font-size:14px}.search-results.show{display:block}
|
||||
|
||||
.date-line{padding:18px 0 10px;color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.09em;font-weight:700}
|
||||
.lead-grid{display:grid;grid-template-columns:minmax(0,2fr) minmax(285px,.85fr);gap:24px;padding-bottom:26px;border-bottom:4px solid var(--ink)}
|
||||
.lead-story{padding-right:24px;border-right:1px solid var(--line)}
|
||||
.kicker{color:var(--red);font-size:12px;font-weight:900;letter-spacing:.1em;text-transform:uppercase;margin-bottom:7px}
|
||||
h1,h2,h3,p{margin-top:0}
|
||||
h1{font-family:var(--serif);font-size:clamp(38px,4.7vw,68px);line-height:.98;letter-spacing:-.035em;margin-bottom:15px;max-width:920px}
|
||||
.dek{font-family:var(--serif);font-size:20px;line-height:1.35;color:var(--muted);max-width:820px;margin-bottom:17px}
|
||||
.story-meta{font-size:12px;color:var(--muted);display:flex;align-items:center;gap:12px;margin-bottom:18px}
|
||||
.story-meta strong{color:var(--ink)}
|
||||
.visual{position:relative;overflow:hidden;background:#20252c}
|
||||
.lead-visual{aspect-ratio:16/8.6}
|
||||
.visual svg{width:100%;height:100%}
|
||||
.visual-credit{position:absolute;right:8px;bottom:7px;color:white;background:rgba(0,0,0,.6);font-size:10px;padding:3px 6px}
|
||||
.visual-tag{position:absolute;left:0;top:0;background:var(--red);color:#fff;font-size:11px;font-weight:900;padding:7px 10px;letter-spacing:.08em}
|
||||
.story-tools{display:flex;gap:6px;margin-top:10px;justify-content:flex-end}
|
||||
.tool-btn{min-width:44px;height:38px;border:1px solid var(--line);display:flex;align-items:center;justify-content:center;gap:7px;font-weight:700;font-size:12px;transition:background .2s,color .2s,border .2s}
|
||||
.tool-btn:hover,.tool-btn.saved{background:var(--ink);color:var(--paper);border-color:var(--ink)}
|
||||
.tool-btn svg{width:17px;height:17px;fill:none;stroke:currentColor;stroke-width:2}
|
||||
|
||||
.side-stack{display:flex;flex-direction:column}
|
||||
.side-story{padding:0 0 18px;margin-bottom:18px;border-bottom:1px solid var(--line)}
|
||||
.side-story:last-of-type{margin-bottom:8px}
|
||||
.side-story h2{font-family:var(--serif);font-size:26px;line-height:1.08;letter-spacing:-.02em;margin:7px 0 8px}
|
||||
.side-story p{font-size:14px;color:var(--muted);margin-bottom:0}
|
||||
.mini-visual{aspect-ratio:16/7.5;margin-bottom:12px}
|
||||
.live-list{background:var(--soft);padding:15px}
|
||||
.live-list-head{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;font-size:13px;font-weight:900}
|
||||
.live-list-head span:first-child{color:var(--red)}
|
||||
.live-item{display:grid;grid-template-columns:52px 1fr;gap:8px;padding:9px 0;border-top:1px solid var(--line);font-size:13px;font-weight:700}
|
||||
.live-item time{color:var(--red);font-weight:900}
|
||||
|
||||
.section{padding:28px 0;border-bottom:1px solid var(--line)}
|
||||
.section-head{display:flex;align-items:end;justify-content:space-between;border-top:5px solid var(--ink);padding-top:9px;margin-bottom:18px}
|
||||
.section-head h2{font-size:25px;line-height:1;margin:0;text-transform:uppercase;letter-spacing:-.02em}
|
||||
.section-head a{font-size:13px;color:var(--blue);font-weight:800}
|
||||
.latest-grid{display:grid;grid-template-columns:1.3fr 1fr 1fr;gap:22px}
|
||||
.news-card{position:relative}
|
||||
.news-card+.news-card{border-left:1px solid var(--line);padding-left:22px}
|
||||
.card-visual{aspect-ratio:16/9;margin-bottom:12px;overflow:hidden;background:#222}
|
||||
.news-card h3{font-family:var(--serif);font-size:23px;line-height:1.12;margin:6px 0 8px;letter-spacing:-.01em}
|
||||
.news-card.feature h3{font-size:31px}
|
||||
.news-card p{font-size:14px;color:var(--muted);margin-bottom:8px}
|
||||
.timestamp{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.06em}
|
||||
.dark-band{background:#0c0c0c;color:#fff;margin-top:0}
|
||||
.dark-band .section{border-bottom:0}
|
||||
.dark-band .section-head{border-color:#fff}
|
||||
.dark-band .section-head a{color:#8cc8ff}
|
||||
.video-grid{display:grid;grid-template-columns:1.6fr 1fr 1fr;gap:18px}
|
||||
.video-card{position:relative}
|
||||
.video-card+.video-card{border-left:1px solid #444;padding-left:18px}
|
||||
.video-card h3{font-family:var(--serif);font-size:21px;line-height:1.15;margin:10px 0 5px}
|
||||
.video-card.feature h3{font-size:30px}
|
||||
.play{position:absolute;left:12px;bottom:12px;width:46px;height:46px;border-radius:50%;background:rgba(198,0,0,.95);display:grid;place-items:center;box-shadow:0 0 0 4px rgba(255,255,255,.18)}
|
||||
.play svg{width:22px;height:22px;fill:white;margin-left:3px}
|
||||
.duration{position:absolute;right:8px;bottom:8px;background:#000;padding:3px 6px;font-size:11px}
|
||||
.video-card .card-visual{position:relative}
|
||||
|
||||
.world-grid{display:grid;grid-template-columns:2fr 1fr;gap:28px}
|
||||
.story-list{display:grid;grid-template-columns:1fr 1fr;column-gap:22px}
|
||||
.list-item{display:grid;grid-template-columns:116px 1fr;gap:13px;padding:14px 0;border-top:1px solid var(--line)}
|
||||
.list-item:nth-child(-n+2){border-top:0;padding-top:0}
|
||||
.list-thumb{aspect-ratio:1.25/1;background:var(--soft);overflow:hidden}
|
||||
.list-item h3{font-family:var(--serif);font-size:18px;line-height:1.12;margin:0 0 6px}
|
||||
.analysis-box{border-left:6px solid var(--red);background:var(--soft);padding:22px}
|
||||
.analysis-box h3{font-family:var(--serif);font-size:27px;line-height:1.1;margin:8px 0 12px}
|
||||
.analysis-box p{color:var(--muted);font-size:14px}
|
||||
.author{display:flex;align-items:center;gap:10px;margin-top:18px;font-size:12px;font-weight:800}
|
||||
.author-mark{width:38px;height:38px;border-radius:50%;background:var(--ink);color:var(--paper);display:grid;place-items:center;font-family:var(--serif);font-size:18px}
|
||||
|
||||
.markets{display:grid;grid-template-columns:repeat(4,1fr);border:1px solid var(--line)}
|
||||
.market{padding:14px 16px;border-right:1px solid var(--line)}
|
||||
.market:last-child{border-right:0}.market-name{font-size:11px;color:var(--muted);font-weight:800}.market-val{font-family:var(--serif);font-size:22px;font-weight:700;margin-top:3px}.market-change{font-size:12px;font-weight:800}
|
||||
|
||||
.newsletter{margin:34px auto;background:var(--red);color:white;display:grid;grid-template-columns:1fr 1fr;align-items:center;padding:26px 30px;gap:30px}
|
||||
.newsletter h2{font-family:var(--serif);font-size:32px;line-height:1;margin:0 0 8px}.newsletter p{margin:0;color:#ffdada}
|
||||
.news-form{display:grid;grid-template-columns:1fr auto;gap:8px}.news-form label{display:none}.news-form input{min-width:0;height:48px;background:white;border:0;padding:0 14px}.news-form button{height:48px;background:#111;color:white;padding:0 20px;font-weight:900}.form-status{grid-column:1/-1;font-size:12px;min-height:18px}
|
||||
|
||||
footer{background:#090909;color:#bbb;padding:34px 0 20px}
|
||||
.footer-grid{display:grid;grid-template-columns:1.6fr repeat(4,1fr);gap:25px}
|
||||
.footer-brand{color:#fff;font-size:32px;font-weight:900;letter-spacing:-2px}.footer-grid h3{color:#fff;font-size:13px;text-transform:uppercase;margin-bottom:12px}.footer-grid a{display:block;font-size:13px;margin:8px 0}.footer-grid a:hover{color:#fff;text-decoration:underline}.footer-bottom{border-top:1px solid #333;margin-top:30px;padding-top:16px;display:flex;justify-content:space-between;font-size:11px}
|
||||
|
||||
.modal-layer,.drawer-layer{position:fixed;inset:0;z-index:80;background:rgba(0,0,0,.76);display:none;align-items:center;justify-content:center;padding:20px}.modal-layer.open,.drawer-layer.open{display:flex}.modal{width:min(820px,100%);background:var(--paper);color:var(--ink);box-shadow:var(--shadow)}
|
||||
.modal-head{height:58px;background:#0b0b0b;color:#fff;display:flex;align-items:center;padding:0 18px;gap:12px}.modal-head strong{font-size:18px}.modal-head .live-dot{margin-left:4px}.modal-close{margin-left:auto;width:44px;height:44px;display:grid;place-items:center;font-size:26px}.player{aspect-ratio:16/9;background:radial-gradient(circle at 50% 45%,#3b3d44 0,#18191c 40%,#050505 100%);position:relative;display:grid;place-items:center;overflow:hidden}.player::before{content:'';position:absolute;width:55%;height:55%;border:1px solid rgba(255,255,255,.15);transform:rotate(45deg)}.player-message{text-align:center;z-index:2}.player-message strong{display:block;color:#fff;font-family:var(--serif);font-size:32px}.player-message span{color:#bbb}.modal-copy{padding:18px;display:flex;justify-content:space-between;gap:20px}.modal-copy p{margin:0;color:var(--muted)}
|
||||
.toast{position:fixed;right:20px;bottom:20px;background:#111;color:#fff;padding:13px 18px;font-size:14px;font-weight:700;z-index:99;transform:translateY(120px);opacity:0;transition:.25s}.toast.show{transform:none;opacity:1}
|
||||
.mobile-drawer{width:min(390px,90vw);height:100%;margin-left:0;margin-right:auto;background:#111;color:white;padding:24px;transform:translateX(-100%);transition:transform .25s}.drawer-layer.open .mobile-drawer{transform:none}.drawer-layer{padding:0;justify-content:flex-start}.drawer-head{display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #444;padding-bottom:18px}.drawer-links a{display:block;font-family:var(--serif);font-size:28px;padding:13px 0;border-bottom:1px solid #333}.drawer-close{font-size:30px;width:44px;height:44px}.drawer-foot{margin-top:24px;font-size:12px;color:#999}
|
||||
|
||||
@media (max-width:980px){
|
||||
.nav a:nth-last-child(-n+3){display:none}.lead-grid{grid-template-columns:1fr .65fr}.lead-story{padding-right:18px}.latest-grid,.video-grid{grid-template-columns:1.35fr 1fr}.latest-grid .news-card:last-child,.video-grid .video-card:last-child{display:none}.world-grid{grid-template-columns:1fr}.footer-grid{grid-template-columns:1.4fr repeat(2,1fr)}.footer-grid>div:nth-last-child(-n+2){display:none}
|
||||
}
|
||||
@media (max-width:720px){
|
||||
.wrap{width:min(100% - 28px,var(--max))}.utility{display:none}.topbar .wrap{height:56px;width:100%;padding:0 12px}.brand{padding:0 13px;font-size:24px}.nav{display:none}.menu-btn{display:grid}.live-btn{margin-left:auto}.top-actions{margin-left:0}.top-actions .icon-btn:nth-child(2){display:none}.breaking .wrap{width:100%;grid-template-columns:auto 1fr}.breaking-time{display:none}.breaking-copy{font-size:12px}.date-line{padding-top:14px}.lead-grid{display:block}.lead-story{border-right:0;padding-right:0}.side-stack{margin-top:23px;border-top:1px solid var(--line);padding-top:20px}h1{font-size:40px}.dek{font-size:18px}.lead-visual{aspect-ratio:4/3}.side-story h2{font-size:24px}.latest-grid,.video-grid{grid-template-columns:1fr 1fr;gap:14px}.news-card+.news-card,.video-card+.video-card{padding-left:14px}.news-card.feature h3,.video-card.feature h3{font-size:23px}.news-card h3,.video-card h3{font-size:19px}.news-card p{display:none}.world-grid{gap:18px}.story-list{display:block}.list-item:nth-child(2){border-top:1px solid var(--line);padding-top:14px}.markets{grid-template-columns:1fr 1fr}.market:nth-child(2){border-right:0}.market:nth-child(-n+2){border-bottom:1px solid var(--line)}.newsletter{grid-template-columns:1fr;padding:22px 18px}.footer-grid{grid-template-columns:1fr 1fr}.footer-grid>div:first-child{grid-column:1/-1}.footer-bottom{display:block;line-height:1.8}.search-inner{min-height:76px}.search-inner input{font-size:16px}.search-inner button{padding:0 14px}
|
||||
}
|
||||
@media (max-width:420px){
|
||||
.live-btn{font-size:0;width:44px;padding:0;justify-content:center}.lead-grid{padding-bottom:20px}.latest-grid,.video-grid{display:block}.news-card,.video-card{padding-bottom:18px;margin-bottom:18px;border-bottom:1px solid var(--line)}.news-card+.news-card,.video-card+.video-card{border-left:0;padding-left:0}.story-list .list-item{grid-template-columns:100px 1fr}.modal-copy{display:block}.modal-copy p+button{margin-top:10px}
|
||||
}
|
||||
@media (prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;animation:none!important;transition:none!important}}
|
||||
|
||||
.top-actions{padding-right:54px}
|
||||
.settings-trigger{position:fixed;z-index:70;top:calc(var(--df-generated-header-height,0px) + 39px);right:16px;width:44px;height:44px;border:1px solid #555;border-radius:50%;display:grid;place-items:center;color:#fff;background:#171717;box-shadow:0 8px 24px rgba(0,0,0,.24);transition:transform .18s,background .18s}
|
||||
.settings-trigger:hover{background:#2b2b2b;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:10px;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-family:var(--sans);font-size:25px;letter-spacing:0}
|
||||
.settings-close{width:46px;height:46px;border:1px solid #2e708f;border-radius:7px;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-family:var(--sans);font-size:13px;font-weight:650}
|
||||
.module-tab{width:100%;min-height:54px;margin-bottom:6px;padding:8px 12px;border:1px solid #1d4660;border-radius:7px;display:block;color:#b7cada;background:#0a1929;text-align:left}.module-tab:hover{background:#0d2338}.module-tab.active{border-color:#25adf2;color:#fff;background:#0d2a42;box-shadow:inset 3px 0 #28b6ff}.module-tab strong,.module-tab span{display:block}.module-tab span{margin-top:2px;color:#7e9aae;font-size:11px}
|
||||
.editor-pane{min-width:0;min-height:0;display:grid;grid-template-rows:auto 1fr auto}.editor-title{min-height:37px;display:flex;align-items:flex-start;justify-content:space-between;color:#8fa9bf;font-size:12px}.editor-title strong{color:#eef8ff;font-size:16px}.json-editor{width:100%;min-height:0;padding:16px;resize:none;border:1px solid #28526b;border-radius:8px;outline:0;color:#d6f1ff;background:#020a12;font:14px/1.62 ui-monospace,SFMono-Regular,Consolas,"Liberation Mono",monospace;tab-size:2}.json-editor:focus{border-color:#28b6ff;box-shadow:0 0 0 3px rgba(40,182,255,.16)}
|
||||
.editor-hint{min-height:40px;padding-top:9px;display:flex;justify-content:space-between;gap:12px;color:#7894aa;font-size:12px}.json-status{font-weight:750}.json-status.valid{color:#48d8a0}.json-status.invalid{color:#ff7189}
|
||||
.settings-foot{min-height:74px;padding:13px 24px;display:flex;align-items:center;justify-content:flex-end;gap:10px;border-top:1px solid #21455d}.editor-button{min-height:44px;padding:0 17px;border:1px solid #2d7292;border-radius:7px;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) + 6px);right:64px;width:42px;height:42px}.settings-overlay{padding:0}.json-settings-modal{width:100%;height:100dvh;border:0;border-radius:0}.settings-head{min-height:68px;padding:10px 14px}.settings-head h2{font-size:20px}.settings-body{padding:12px;grid-template-columns:1fr;grid-template-rows:auto minmax(0,1fr)}.module-tabs{display:flex;gap:7px;overflow-x:auto}.module-tabs h3{display:none}.module-tab{width:auto;min-width:116px;margin:0}.settings-foot{padding:10px 12px;flex-wrap:wrap}.editor-button{flex:1;padding-inline:10px}}
|
||||
.skip-link{transform:translateY(calc(-100% - var(--df-generated-header-height,0px) - 24px))}.skip-link:focus{transform:none}
|
||||
.modal-layer,.drawer-layer{z-index:1200}.settings-overlay{z-index:1300}
|
||||
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body id="top">
|
||||
<a class="skip-link" href="#main-content">跳到主要内容</a>
|
||||
<header>
|
||||
<div class="utility"><div class="wrap"><div class="utility-links" id="utilityLeft"></div><div class="utility-links" id="utilityRight"></div></div></div>
|
||||
<div class="topbar"><div class="wrap">
|
||||
<button class="icon-btn menu-btn" id="menuOpen" aria-label="打开菜单"><svg viewBox="0 0 24 24"><path d="M4 7h16M4 12h16M4 17h16"/></svg></button>
|
||||
<a class="brand" id="brandLink" href="#top"><span id="brandText">CNN</span></a>
|
||||
<nav class="nav" id="desktopNav" aria-label="主导航"></nav>
|
||||
<div class="top-actions">
|
||||
<button class="icon-btn" id="searchToggle" aria-label="搜索"><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/></svg></button>
|
||||
<button class="icon-btn" id="themeToggle" aria-label="切换深色模式"><svg viewBox="0 0 24 24"><path d="M20.5 14.2A8.5 8.5 0 0 1 9.8 3.5 8.5 8.5 0 1 0 20.5 14.2Z"/></svg></button>
|
||||
<button class="live-btn open-live" id="headerLive"><span class="live-dot"></span><span id="liveLabel"></span></button>
|
||||
</div>
|
||||
</div></div>
|
||||
<div class="breaking"><div class="wrap"><div class="breaking-label" id="breakingLabel"></div><div class="breaking-copy" id="breakingCopy"></div><time class="breaking-time" id="breakingTime"></time></div></div>
|
||||
<div class="search-panel" id="searchPanel"><div class="wrap"><form class="search-inner" id="searchForm"><label class="sr-only" for="searchInput">搜索新闻</label><input id="searchInput" type="search" autocomplete="off"/><button id="searchSubmit" type="submit"></button></form><div class="search-results" id="searchResults"></div></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-content" tabindex="-1">
|
||||
<div class="wrap"><div class="date-line" id="frontLabel"></div><section class="lead-grid" id="leadGrid" aria-label="头条新闻"></section></div>
|
||||
<section class="section wrap" id="world"><div class="section-head"><h2 id="latestTitle"></h2><a id="latestMore" href="#world"></a></div><div class="latest-grid" id="latestGrid"></div></section>
|
||||
<div class="dark-band" id="technology"><section class="section wrap"><div class="section-head"><h2 id="videoTitle"></h2><a id="videoMore" href="#technology"></a></div><div class="video-grid" id="videoGrid"></div></section></div>
|
||||
<section class="section wrap" id="business"><div class="section-head"><h2 id="worldTitle"></h2><a id="worldMore" href="#business"></a></div><div class="world-grid"><div class="story-list" id="worldList"></div><aside class="analysis-box" id="opinion"></aside></div></section>
|
||||
<section class="section wrap" id="markets"><div class="section-head"><h2 id="marketsTitle"></h2><a id="marketsMore" href="#markets"></a></div><div class="markets" id="marketsGrid"></div></section>
|
||||
<section class="newsletter wrap" id="newsletter"><div><h2 id="newsletterTitle"></h2><p id="newsletterText"></p></div><form class="news-form" id="newsletterForm"><label for="email">邮箱地址</label><input id="email" type="email" required/><button id="newsletterButton" type="submit"></button><div class="form-status" id="formStatus" aria-live="polite"></div></form></section>
|
||||
</main>
|
||||
|
||||
<footer><div class="wrap"><div class="footer-grid" id="footerGrid"></div><div class="footer-bottom"><span id="copyright"></span><span id="legal"></span></div></div></footer>
|
||||
|
||||
<div class="modal-layer" id="liveModal" role="dialog" aria-modal="true" aria-labelledby="liveTitle"><div class="modal"><div class="modal-head"><span class="live-dot"></span><strong id="liveTitle"></strong><button class="modal-close" id="liveClose" aria-label="关闭直播">×</button></div><div class="player"><div class="player-message"><strong id="playerTitle"></strong><span id="playerSubtitle"></span></div></div><div class="modal-copy"><p id="modalNote"></p><button class="tool-btn" id="captionToggle">CC 字幕:开</button></div></div></div>
|
||||
<div class="drawer-layer" id="drawer" role="dialog" aria-modal="true" aria-label="移动端导航"><aside class="mobile-drawer"><div class="drawer-head"><div class="footer-brand" id="drawerBrand"></div><button class="drawer-close" id="drawerClose" aria-label="关闭菜单">×</button></div><nav class="drawer-links" id="drawerLinks"></nav><div class="drawer-foot" id="drawerFooter"></div></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">CNN 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="cnnPageData">__CNN_PAGE_DATA__</script>
|
||||
<script>__CNN_PAGE_RUNTIME__</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"site": {
|
||||
"brand": "CNN",
|
||||
"pageTitle": "CNN — 全球新闻现场",
|
||||
"description": "一个 CNN 风格的中文全球新闻首页示例页面。",
|
||||
"theme": "light",
|
||||
"date": "2026年10月26日 · 星期一",
|
||||
"utilityLinks": ["市场", "新闻简报"],
|
||||
"marketSummary": [
|
||||
{"label": "沪指", "value": "+0.42%", "direction": "up"},
|
||||
{"label": "恒指", "value": "−0.18%", "direction": "down"}
|
||||
],
|
||||
"weather": "天气 18°C",
|
||||
"frontLabel": "头版 · 全球焦点"
|
||||
},
|
||||
"navigation": {
|
||||
"items": [
|
||||
{"label": "首页", "href": "#top"},
|
||||
{"label": "全球", "href": "#world"},
|
||||
{"label": "商业", "href": "#business"},
|
||||
{"label": "科技", "href": "#technology"},
|
||||
{"label": "文化", "href": "#culture"},
|
||||
{"label": "观点", "href": "#opinion"}
|
||||
],
|
||||
"searchPlaceholder": "搜索新闻、人物或地点",
|
||||
"searchButton": "搜索",
|
||||
"liveLabel": "直播",
|
||||
"drawerFooter": "CNN · 从现场出发"
|
||||
},
|
||||
"breaking": {
|
||||
"label": "突发",
|
||||
"text": "全球城市峰会达成新框架,首轮联合行动将在下月启动",
|
||||
"time": "9分钟前"
|
||||
},
|
||||
"lead": {
|
||||
"primary": {
|
||||
"kicker": "特别报道",
|
||||
"title": "世界城市正在重新绘制一张共同生活的蓝图",
|
||||
"summary": "从能源网络到公共交通,来自32座城市的代表在海湾会议上公布了一份跨区域协作计划。",
|
||||
"byline": "林知远 发自海湾城",
|
||||
"updated": "更新于 12 分钟前",
|
||||
"readingTime": "阅读 6 分钟",
|
||||
"visual": "summit",
|
||||
"visualLabel": "傍晚的国际会议中心和城市天际线插画",
|
||||
"tag": "现场",
|
||||
"credit": "CNN / 视觉报道"
|
||||
},
|
||||
"sideStories": [
|
||||
{"kicker": "交通", "title": "夜行列车回归:一场跨越大陆的旅行复兴", "summary": "新线路把六座首都重新连接起来,首班车票已售罄。", "visual": "train"},
|
||||
{"kicker": "科技", "title": "小型语言模型走进设备端,隐私成为新卖点", "summary": "无需联网的智能助手,正改变手机与可穿戴设备的竞争方式。", "visual": null}
|
||||
],
|
||||
"updatesTitle": "实时更新",
|
||||
"updates": [
|
||||
{"time": "09:42", "text": "峰会代表开始回答记者提问"},
|
||||
{"time": "09:31", "text": "联合声明全文正式公布"},
|
||||
{"time": "09:18", "text": "首批合作城市名单确认"}
|
||||
]
|
||||
},
|
||||
"latest": {
|
||||
"title": "最新报道",
|
||||
"moreLabel": "查看全部 →",
|
||||
"items": [
|
||||
{"id": "living-coastline", "kicker": "气候", "title": "沿海社区如何用一条“活的海岸线”抵御风暴", "summary": "工程师放弃单一水泥墙,转向沙丘、湿地与可移动公共空间组成的新防线。", "time": "35分钟前 · 视觉故事", "visual": "coast"},
|
||||
{"id": "urban-lab", "kicker": "欧洲", "title": "旧工业区变身城市实验室,年轻居民正在回流", "summary": "空置厂房成为工作室、实验室与可负担住房。", "time": "1小时前", "visual": "city"},
|
||||
{"id": "deep-sea", "kicker": "科学", "title": "新型观测网络首次捕捉深海热流的完整路径", "summary": "数据将帮助研究人员改进区域气候预测。", "time": "2小时前", "visual": "deep-sea"}
|
||||
]
|
||||
},
|
||||
"video": {
|
||||
"title": "CNN 现场",
|
||||
"moreLabel": "更多视频 →",
|
||||
"modalTitle": "CNN LIVE",
|
||||
"liveTitle": "正在直播",
|
||||
"liveSubtitle": "全球城市峰会记者会",
|
||||
"modalNote": "直播画面为互动演示。字幕与音量控制可在正式播放器中使用。",
|
||||
"items": [
|
||||
{"id": "future-city", "title": "连接未来:城市基础设施如何在地下完成升级", "meta": "纪录短片", "duration": "08:24", "visual": "night-city"},
|
||||
{"id": "space-lab", "title": "轨道实验室迎来全新材料实验", "meta": "科学现场", "duration": "03:18", "visual": "space"},
|
||||
{"id": "coast-festival", "title": "海岸音乐节将社区带回公共空间", "meta": "文化", "duration": "05:06", "visual": "music"}
|
||||
]
|
||||
},
|
||||
"world": {
|
||||
"title": "全球与商业",
|
||||
"moreLabel": "进入频道 →",
|
||||
"items": [
|
||||
{"id": "trade-corridor", "kicker": "亚洲", "title": "区域贸易走廊启用数字通关系统", "time": "24分钟前", "visual": "trade"},
|
||||
{"id": "market-rise", "kicker": "市场", "title": "能源与运输板块推动主要指数走高", "time": "41分钟前", "visual": "market"},
|
||||
{"id": "instant-pay", "kicker": "金融", "title": "即时支付网络跨境测试扩展至八个市场", "time": "1小时前", "visual": "payments"},
|
||||
{"id": "clean-grid", "kicker": "能源", "title": "分布式电网让小城成为清洁能源节点", "time": "2小时前", "visual": "energy"}
|
||||
],
|
||||
"analysis": {
|
||||
"kicker": "CNN 分析",
|
||||
"title": "这份城市协作框架真正改变了什么?",
|
||||
"text": "它没有许诺一夜之间解决问题,而是建立了一套可度量、可复制的合作机制。关键考验将在资金与执行层面。",
|
||||
"author": "周观澜",
|
||||
"role": "国际事务主编",
|
||||
"initial": "周"
|
||||
}
|
||||
},
|
||||
"markets": {
|
||||
"title": "市场快照",
|
||||
"moreLabel": "数据中心 →",
|
||||
"items": [
|
||||
{"name": "上证指数", "value": "3,472.18", "change": "+0.42%", "direction": "up"},
|
||||
{"name": "恒生指数", "value": "24,118.70", "change": "−0.18%", "direction": "down"},
|
||||
{"name": "布伦特原油", "value": "$71.36", "change": "+0.81%", "direction": "up"},
|
||||
{"name": "黄金", "value": "$2,741.50", "change": "+0.27%", "direction": "up"}
|
||||
]
|
||||
},
|
||||
"newsletter": {
|
||||
"title": "重要新闻,直达你的收件箱",
|
||||
"text": "每天早晚两次,5分钟读懂世界正在发生什么。",
|
||||
"placeholder": "name@example.com",
|
||||
"button": "免费订阅",
|
||||
"successPrefix": "订阅成功,确认邮件已发送至"
|
||||
},
|
||||
"footer": {
|
||||
"tagline": "从现场出发,看见世界的全貌。",
|
||||
"columns": [
|
||||
{"title": "新闻", "links": [{"label": "全球", "href": "#world"}, {"label": "商业", "href": "#business"}, {"label": "科技", "href": "#technology"}]},
|
||||
{"title": "栏目", "links": [{"label": "观点", "href": "#opinion"}, {"label": "新闻简报", "href": "#newsletter"}, {"label": "市场", "href": "#markets"}]},
|
||||
{"title": "关于", "links": [{"label": "关于 CNN", "href": "#top"}, {"label": "编辑准则", "href": "#top"}, {"label": "联系我们", "href": "#top"}]},
|
||||
{"title": "关注", "links": [{"label": "视频", "href": "#technology"}, {"label": "播客", "href": "#top"}, {"label": "移动应用", "href": "#top"}]}
|
||||
],
|
||||
"copyright": "© 2026 CNN News. 本页面为概念设计。",
|
||||
"legal": "隐私 · 条款 · Cookie 设置"
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
# CNN 页面 JSON 契约
|
||||
|
||||
顶层必须完整包含 `site`、`navigation`、`breaking`、`lead`、`latest`、`video`、`world`、`markets`、`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`:品牌、页面标题、描述、`theme`(`light`/`dark`/`auto`)、日期、工具栏链接、市场摘要、天气和头版标签。市场方向为 `up`/`down`/`flat`。
|
||||
- `navigation`:1–10 个 `{label, href}` 导航项,以及搜索、直播和移动抽屉文案。
|
||||
- `breaking`:`label`、`text`、`time`。
|
||||
- `lead.primary`:`kicker/title/summary/byline/updated/readingTime/visual/visualLabel/tag/credit`;`visual` 必须为 `summit`。
|
||||
- `lead.sideStories`:0–4 条,`visual` 可为 `train` 或 `null`;`updates` 为 0–12 条 `{time,text}`。
|
||||
- `latest.items`:1–12 条,视觉类型为 `coast`、`city`、`deep-sea`。
|
||||
- `video.items`:1–8 条,视觉类型为 `night-city`、`space`、`music`,并包含 `duration`。
|
||||
- `world.items`:1–16 条,视觉类型为 `trade`、`market`、`payments`、`energy`;`analysis` 包含评论标题、正文和作者信息。
|
||||
- `markets.items`:1–8 条 `{name,value,change,direction}`,方向为 `up`、`down` 或 `flat`。
|
||||
- `newsletter`:标题、说明、邮箱占位、按钮和成功提示前缀。
|
||||
- `footer.columns`:0–6 栏,每栏 0–8 个 `{label,href}`;另有 `tagline/copyright/legal`。
|
||||
|
||||
JSON 使用双引号,不允许注释、Markdown 围栏或尾逗号。`assets/default-data.json` 只是结构和演示内容,不是事实来源。
|
||||
+372
@@ -0,0 +1,372 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate a complete CNN-style Chinese page from a high-level JSON spec."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
|
||||
import render_cnn_page as renderer
|
||||
|
||||
LATEST_VISUALS = ("coast", "city", "deep-sea")
|
||||
VIDEO_VISUALS = ("night-city", "space", "music")
|
||||
WORLD_VISUALS = ("trade", "market", "payments", "energy")
|
||||
|
||||
|
||||
def _read_spec(path: Path) -> dict[str, object]:
|
||||
try:
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError as exc:
|
||||
raise renderer.DataValidationError(f"Invalid spec JSON: {exc}") from exc
|
||||
if not isinstance(value, dict):
|
||||
raise renderer.DataValidationError("Spec JSON must be an object")
|
||||
return value
|
||||
|
||||
|
||||
def _string(value: object, path: str, *, required: bool = False) -> str:
|
||||
if value is None and not required:
|
||||
return ""
|
||||
if not isinstance(value, str) or (required and not value.strip()):
|
||||
suffix = "a non-empty string" if required else "a string"
|
||||
raise renderer.DataValidationError(f"{path} must be {suffix}")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _strings(value: object, path: str, *, limit: int) -> list[str]:
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list) or not 1 <= len(value) <= limit:
|
||||
raise renderer.DataValidationError(f"{path} must contain between 1 and {limit} strings")
|
||||
result: list[str] = []
|
||||
for index, item in enumerate(value):
|
||||
text = _string(item, f"{path}[{index}]", required=True)
|
||||
_require_chinese(text, f"{path}[{index}]")
|
||||
result.append(text)
|
||||
return result
|
||||
|
||||
|
||||
def _require_chinese(value: str, path: str) -> None:
|
||||
if not any("\u3400" <= char <= "\u9fff" for char in value):
|
||||
raise renderer.DataValidationError(f"{path} must contain Simplified Chinese reader-visible text")
|
||||
|
||||
|
||||
def _optional_chinese(spec: Mapping[str, object], key: str) -> str:
|
||||
value = _string(spec.get(key), key)
|
||||
if value:
|
||||
_require_chinese(value, key)
|
||||
return value
|
||||
|
||||
|
||||
def _media(value: object) -> dict[str, object] | None:
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, Mapping):
|
||||
raise renderer.DataValidationError("media must be an object or null")
|
||||
media_type = _string(value.get("type"), "media.type") or "image"
|
||||
if media_type not in {"image", "video", "webpage"}:
|
||||
raise renderer.DataValidationError("media.type must be image, video, or webpage")
|
||||
media: dict[str, object] = {"type": media_type}
|
||||
if media_type == "webpage":
|
||||
media["pageUrl"] = _string(
|
||||
value.get("pageUrl"),
|
||||
"media.pageUrl",
|
||||
required=True,
|
||||
)
|
||||
media["title"] = _string(
|
||||
value.get("title"),
|
||||
"media.title",
|
||||
required=True,
|
||||
)
|
||||
if value.get("description"):
|
||||
media["description"] = _string(
|
||||
value.get("description"),
|
||||
"media.description",
|
||||
)
|
||||
media["embed"] = bool(value.get("embed", False))
|
||||
else:
|
||||
media["mediaUrl"] = _string(
|
||||
value.get("url"),
|
||||
"media.url",
|
||||
required=True,
|
||||
)
|
||||
media["alt"] = _string(value.get("alt"), "media.alt") or "用户提供的新闻媒体"
|
||||
if value.get("pageUrl"):
|
||||
media["pageUrl"] = _string(value.get("pageUrl"), "media.pageUrl")
|
||||
if media_type == "video" and value.get("posterUrl"):
|
||||
media["posterUrl"] = _string(
|
||||
value.get("posterUrl"),
|
||||
"media.posterUrl",
|
||||
)
|
||||
return media
|
||||
|
||||
|
||||
def _replace_story_titles(
|
||||
defaults: list[dict[str, object]],
|
||||
titles: list[str],
|
||||
*,
|
||||
prefix: str,
|
||||
visuals: tuple[str, ...],
|
||||
include_summary: bool,
|
||||
topic: str,
|
||||
) -> list[dict[str, object]]:
|
||||
items: list[dict[str, object]] = []
|
||||
for index, title in enumerate(titles):
|
||||
item = copy.deepcopy(defaults[index % len(defaults)])
|
||||
item["id"] = f"{prefix}-{index + 1:02d}"
|
||||
item["title"] = title
|
||||
item["visual"] = visuals[index % len(visuals)]
|
||||
if include_summary:
|
||||
item["kicker"] = "专题"
|
||||
item["summary"] = f"围绕{topic}整理的中文示意报道,页面内容可在设置中继续编辑。"
|
||||
item["time"] = f"{index + 1} 小时前 · 示意"
|
||||
elif "meta" in item:
|
||||
item["meta"] = "视频示意"
|
||||
item["duration"] = f"0{index + 3}:1{index}"
|
||||
else:
|
||||
item["kicker"] = "观察"
|
||||
item["time"] = f"{index + 1} 小时前 · 示意"
|
||||
items.append(item)
|
||||
return items
|
||||
|
||||
|
||||
def build_document(spec: dict[str, object]) -> dict[str, object]:
|
||||
allowed = {
|
||||
"topic",
|
||||
"headline",
|
||||
"headlineSummary",
|
||||
"breaking",
|
||||
"pageTitle",
|
||||
"description",
|
||||
"theme",
|
||||
"kicker",
|
||||
"byline",
|
||||
"latestHeadlines",
|
||||
"videoHeadlines",
|
||||
"worldHeadlines",
|
||||
"sideHeadlines",
|
||||
"updates",
|
||||
"analysisTitle",
|
||||
"analysisText",
|
||||
"media",
|
||||
}
|
||||
unknown = sorted(set(spec) - allowed)
|
||||
if unknown:
|
||||
raise renderer.DataValidationError("Unknown spec keys: " + ", ".join(unknown))
|
||||
|
||||
topic = _string(spec.get("topic"), "topic", required=True)
|
||||
headline = _optional_chinese(spec, "headline") or f"{topic}发布最新计划,中文专题页面同步上线"
|
||||
headline_summary = _optional_chinese(spec, "headlineSummary") or (f"本页面围绕{topic}整理品牌动态、内容观察与社区反馈,所有新闻和数据均为中文示意内容。")
|
||||
breaking = _optional_chinese(spec, "breaking") or f"{topic}成为今日中文专题关注焦点"
|
||||
page_title = _optional_chinese(spec, "pageTitle") or f"CNN 中文专题 · {topic}"
|
||||
description = _optional_chinese(spec, "description") or f"围绕{topic}制作的 CNN 风格中文新闻示意页面。"
|
||||
kicker = _optional_chinese(spec, "kicker") or "特别报道 · 中文示意"
|
||||
byline = _string(spec.get("byline"), "byline") or "CNN 中文编辑台"
|
||||
theme = _string(spec.get("theme"), "theme") or "light"
|
||||
if theme not in renderer.THEMES:
|
||||
raise renderer.DataValidationError("theme must be auto, light, or dark")
|
||||
|
||||
latest_titles = _strings(spec.get("latestHeadlines"), "latestHeadlines", limit=12) or [
|
||||
f"{topic}推出新计划,首批体验活动正式启动",
|
||||
f"从创意到产品:{topic}团队分享设计思路",
|
||||
f"社区观察:用户如何参与{topic}内容共创",
|
||||
]
|
||||
video_titles = _strings(spec.get("videoHeadlines"), "videoHeadlines", limit=8) or [
|
||||
f"现场直击:走进{topic}的创作空间",
|
||||
f"三分钟了解{topic}最新进展",
|
||||
f"幕后故事:{topic}团队讲述项目历程",
|
||||
]
|
||||
world_titles = _strings(spec.get("worldHeadlines"), "worldHeadlines", limit=16) or [
|
||||
f"{topic}跨区域合作计划公布",
|
||||
f"市场观察:{topic}相关讨论持续升温",
|
||||
f"数字内容让{topic}触达更多社区",
|
||||
f"可持续实践成为{topic}下一阶段重点",
|
||||
]
|
||||
side_titles = _strings(spec.get("sideHeadlines"), "sideHeadlines", limit=4) or [
|
||||
f"{topic}如何把创意转化为日常体验",
|
||||
f"团队访谈:{topic}背后的设计选择",
|
||||
]
|
||||
update_titles = _strings(spec.get("updates"), "updates", limit=12) or [
|
||||
f"{topic}专题页面完成首轮内容更新",
|
||||
"中文示意报道与栏目内容已同步",
|
||||
"读者可通过设置按钮继续编辑页面数据",
|
||||
]
|
||||
analysis_title = _optional_chinese(spec, "analysisTitle") or f"{topic}为何能够持续获得关注?"
|
||||
analysis_text = _optional_chinese(spec, "analysisText") or (f"{topic}把清晰的内容表达、稳定的视觉识别和持续的社区互动结合起来。真正的考验在于后续内容能否保持一致,并形成可持续的参与机制。")
|
||||
|
||||
data = renderer._read_json(renderer.DEFAULT_DATA_PATH)
|
||||
data["site"].update(
|
||||
{
|
||||
"pageTitle": page_title,
|
||||
"description": description,
|
||||
"theme": theme,
|
||||
"date": "中文示意页面 · 非实时新闻",
|
||||
"utilityLinks": ["专题", "新闻简报"],
|
||||
"marketSummary": [
|
||||
{"label": "关注度", "value": "示意", "direction": "flat"},
|
||||
{"label": "讨论度", "value": "非实时", "direction": "flat"},
|
||||
],
|
||||
"weather": "页面内容为中文示意",
|
||||
"frontLabel": f"头版 · {topic}",
|
||||
}
|
||||
)
|
||||
data["navigation"]["drawerFooter"] = "CNN 中文专题 · 概念页面"
|
||||
data["breaking"].update({"label": "快讯", "text": breaking, "time": "刚刚 · 示意"})
|
||||
|
||||
primary = data["lead"]["primary"]
|
||||
primary.update(
|
||||
{
|
||||
"kicker": kicker,
|
||||
"title": headline,
|
||||
"summary": headline_summary,
|
||||
"byline": byline,
|
||||
"updated": "更新于刚刚 · 示意",
|
||||
"readingTime": "阅读 5 分钟",
|
||||
"visualLabel": f"{topic}中文专题示意视觉",
|
||||
"tag": "专题",
|
||||
"credit": "CNN / 中文示意视觉",
|
||||
}
|
||||
)
|
||||
if "media" in spec:
|
||||
media = _media(spec.get("media"))
|
||||
if media is None:
|
||||
primary.pop("media", None)
|
||||
else:
|
||||
primary["media"] = media
|
||||
|
||||
data["lead"]["sideStories"] = [
|
||||
{
|
||||
"kicker": "延伸阅读",
|
||||
"title": title,
|
||||
"summary": f"从不同角度理解{topic}的内容表达与用户体验。",
|
||||
"visual": "train" if index == 0 else None,
|
||||
}
|
||||
for index, title in enumerate(side_titles)
|
||||
]
|
||||
data["lead"]["updatesTitle"] = "专题更新"
|
||||
data["lead"]["updates"] = [{"time": f"0{9 + index}:0{index}", "text": text} for index, text in enumerate(update_titles)]
|
||||
|
||||
data["latest"]["title"] = "最新报道"
|
||||
data["latest"]["items"] = _replace_story_titles(
|
||||
data["latest"]["items"],
|
||||
latest_titles,
|
||||
prefix="latest",
|
||||
visuals=LATEST_VISUALS,
|
||||
include_summary=True,
|
||||
topic=topic,
|
||||
)
|
||||
data["video"].update(
|
||||
{
|
||||
"title": "视频与现场",
|
||||
"modalTitle": "CNN 中文视频",
|
||||
"liveTitle": "专题视频",
|
||||
"liveSubtitle": f"正在播放:{topic}",
|
||||
"modalNote": "视频内容为互动示意,可通过上传按钮替换素材。",
|
||||
}
|
||||
)
|
||||
data["video"]["items"] = _replace_story_titles(
|
||||
data["video"]["items"],
|
||||
video_titles,
|
||||
prefix="video",
|
||||
visuals=VIDEO_VISUALS,
|
||||
include_summary=False,
|
||||
topic=topic,
|
||||
)
|
||||
data["world"]["title"] = f"{topic}与相关观察"
|
||||
data["world"]["items"] = _replace_story_titles(
|
||||
data["world"]["items"],
|
||||
world_titles,
|
||||
prefix="world",
|
||||
visuals=WORLD_VISUALS,
|
||||
include_summary=False,
|
||||
topic=topic,
|
||||
)
|
||||
data["world"]["analysis"].update(
|
||||
{
|
||||
"kicker": "CNN 中文分析 · 示意",
|
||||
"title": analysis_title,
|
||||
"text": analysis_text,
|
||||
"author": "中文专题编辑部",
|
||||
"role": "页面内容策划",
|
||||
"initial": "编",
|
||||
}
|
||||
)
|
||||
data["markets"].update(
|
||||
{
|
||||
"title": "趋势快照 · 示意数据",
|
||||
"moreLabel": "非实时数据 →",
|
||||
"items": [
|
||||
{"name": "内容关注", "value": "示意", "change": "非实时", "direction": "flat"},
|
||||
{"name": "社区讨论", "value": "示意", "change": "非实时", "direction": "flat"},
|
||||
{"name": "视频热度", "value": "示意", "change": "非实时", "direction": "flat"},
|
||||
{"name": "专题更新", "value": "示意", "change": "非实时", "direction": "flat"},
|
||||
],
|
||||
}
|
||||
)
|
||||
data["newsletter"].update(
|
||||
{
|
||||
"title": f"订阅{topic}中文专题更新",
|
||||
"text": "接收页面内容更新提醒;本表单仅用于交互演示。",
|
||||
"button": "演示订阅",
|
||||
"successPrefix": "演示订阅信息已记录:",
|
||||
}
|
||||
)
|
||||
data["footer"].update(
|
||||
{
|
||||
"tagline": f"从中文专题出发,持续关注{topic}。",
|
||||
"copyright": "© 2026 CNN 风格概念页面。本页面内容均为中文示意。",
|
||||
"legal": "隐私 · 条款 · 内容说明",
|
||||
}
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
def _next_paths(output_dir: Path) -> tuple[Path, Path]:
|
||||
for index in range(1, 1001):
|
||||
stem = "cnn-page" if index == 1 else f"cnn-page-{index}"
|
||||
data_path = output_dir / f"{stem}-data.json"
|
||||
html_path = output_dir / f"{stem}.html"
|
||||
if not data_path.exists() and not html_path.exists():
|
||||
return data_path, html_path
|
||||
raise renderer.DataValidationError("Unable to allocate output filenames")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--spec", type=Path, required=True)
|
||||
parser.add_argument("--output-dir", type=Path, required=True)
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
data = build_document(_read_spec(args.spec))
|
||||
summary = renderer.validate_document(data)
|
||||
rendered = renderer.render_document(
|
||||
data,
|
||||
renderer.TEMPLATE_PATH.read_text(encoding="utf-8"),
|
||||
renderer.RUNTIME_PATH.read_text(encoding="utf-8"),
|
||||
)
|
||||
data_path, html_path = _next_paths(args.output_dir)
|
||||
renderer._write_new(
|
||||
data_path,
|
||||
json.dumps(data, ensure_ascii=False, indent=2) + "\n",
|
||||
)
|
||||
renderer._write_new(html_path, rendered)
|
||||
except (renderer.DataValidationError, OSError, UnicodeError) as exc:
|
||||
renderer._emit({"status": "error", "action": "fast-cnn-page", "error": str(exc)})
|
||||
return 2
|
||||
renderer._emit(
|
||||
{
|
||||
"status": "ok",
|
||||
"action": "fast-cnn-page",
|
||||
"data": str(data_path),
|
||||
"html": str(html_path),
|
||||
**summary,
|
||||
}
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+571
@@ -0,0 +1,571 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate CNN 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 / "cnn-template.html"
|
||||
RUNTIME_PATH = ASSETS_DIR / "cnn-runtime.js"
|
||||
DATA_MARKER = "__CNN_PAGE_DATA__"
|
||||
RUNTIME_MARKER = "__CNN_PAGE_RUNTIME__"
|
||||
TITLE_RE = re.compile(r"<title>[^<]*</title>", re.IGNORECASE)
|
||||
MODULES = (
|
||||
"site",
|
||||
"navigation",
|
||||
"breaking",
|
||||
"lead",
|
||||
"latest",
|
||||
"video",
|
||||
"world",
|
||||
"markets",
|
||||
"newsletter",
|
||||
"footer",
|
||||
)
|
||||
THEMES = {"auto", "light", "dark"}
|
||||
DIRECTIONS = {"up", "down", "flat"}
|
||||
LATEST_VISUALS = {"coast", "city", "deep-sea"}
|
||||
VIDEO_VISUALS = {"night-city", "space", "music"}
|
||||
WORLD_VISUALS = {"trade", "market", "payments", "energy"}
|
||||
REMOTE_MEDIA_TYPES = {"image", "video", "webpage"}
|
||||
|
||||
|
||||
class DataValidationError(ValueError):
|
||||
"""Raised when the CNN 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 _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 _direction(value: Any, path: str, errors: list[str]) -> None:
|
||||
if value not in DIRECTIONS:
|
||||
errors.append(f"{path} must be one of: down, flat, up")
|
||||
|
||||
|
||||
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 _validate_story_items(
|
||||
items: list[Any],
|
||||
path: str,
|
||||
errors: list[str],
|
||||
*,
|
||||
visuals: set[str],
|
||||
include_summary: bool,
|
||||
include_duration: bool = False,
|
||||
) -> None:
|
||||
seen: set[str] = set()
|
||||
for index, value in enumerate(items):
|
||||
item_path = f"{path}[{index}]"
|
||||
item = _mapping(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"]
|
||||
if include_summary:
|
||||
keys.extend(["kicker", "summary", "time"])
|
||||
elif include_duration:
|
||||
keys.extend(["meta", "duration"])
|
||||
else:
|
||||
keys.extend(["kicker", "time"])
|
||||
_strings(item, tuple(keys), item_path, errors)
|
||||
if item.get("visual") not in visuals:
|
||||
errors.append(
|
||||
f"{item_path}.visual must be one of: "
|
||||
f"{', '.join(sorted(visuals))}"
|
||||
)
|
||||
|
||||
|
||||
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,
|
||||
("brand", "pageTitle", "description", "date", "weather", "frontLabel"),
|
||||
"site",
|
||||
errors,
|
||||
)
|
||||
if site.get("theme") not in THEMES:
|
||||
errors.append("site.theme must be one of: auto, dark, light")
|
||||
utility_links = _array(
|
||||
site.get("utilityLinks"),
|
||||
"site.utilityLinks",
|
||||
errors,
|
||||
limit=6,
|
||||
)
|
||||
for index, value in enumerate(utility_links):
|
||||
_non_empty_string(value, f"site.utilityLinks[{index}]", errors)
|
||||
summary_items = _array(
|
||||
site.get("marketSummary"),
|
||||
"site.marketSummary",
|
||||
errors,
|
||||
limit=6,
|
||||
)
|
||||
for index, value in enumerate(summary_items):
|
||||
item = _mapping(value, f"site.marketSummary[{index}]", errors)
|
||||
_strings(
|
||||
item,
|
||||
("label", "value"),
|
||||
f"site.marketSummary[{index}]",
|
||||
errors,
|
||||
)
|
||||
_direction(
|
||||
item.get("direction"),
|
||||
f"site.marketSummary[{index}].direction",
|
||||
errors,
|
||||
)
|
||||
|
||||
navigation = _mapping(data.get("navigation"), "navigation", errors)
|
||||
_strings(
|
||||
navigation,
|
||||
("searchPlaceholder", "searchButton", "liveLabel", "drawerFooter"),
|
||||
"navigation",
|
||||
errors,
|
||||
)
|
||||
nav_items = _array(
|
||||
navigation.get("items"),
|
||||
"navigation.items",
|
||||
errors,
|
||||
limit=10,
|
||||
)
|
||||
if not nav_items:
|
||||
errors.append("navigation.items must contain at least one item")
|
||||
for index, value in enumerate(nav_items):
|
||||
item = _mapping(value, f"navigation.items[{index}]", errors)
|
||||
_non_empty_string(
|
||||
item.get("label"),
|
||||
f"navigation.items[{index}].label",
|
||||
errors,
|
||||
)
|
||||
_href(item.get("href"), f"navigation.items[{index}].href", errors)
|
||||
|
||||
breaking = _mapping(data.get("breaking"), "breaking", errors)
|
||||
_strings(breaking, ("label", "text", "time"), "breaking", errors)
|
||||
|
||||
lead = _mapping(data.get("lead"), "lead", errors)
|
||||
primary = _mapping(lead.get("primary"), "lead.primary", errors)
|
||||
_strings(
|
||||
primary,
|
||||
(
|
||||
"kicker",
|
||||
"title",
|
||||
"summary",
|
||||
"byline",
|
||||
"updated",
|
||||
"readingTime",
|
||||
"visualLabel",
|
||||
"tag",
|
||||
"credit",
|
||||
),
|
||||
"lead.primary",
|
||||
errors,
|
||||
)
|
||||
if primary.get("visual") != "summit":
|
||||
errors.append("lead.primary.visual must be: summit")
|
||||
side_stories = _array(
|
||||
lead.get("sideStories"),
|
||||
"lead.sideStories",
|
||||
errors,
|
||||
limit=4,
|
||||
)
|
||||
for index, value in enumerate(side_stories):
|
||||
item_path = f"lead.sideStories[{index}]"
|
||||
item = _mapping(value, item_path, errors)
|
||||
_strings(item, ("kicker", "title", "summary"), item_path, errors)
|
||||
if item.get("visual") not in {None, "train"}:
|
||||
errors.append(f"{item_path}.visual must be train or null")
|
||||
_non_empty_string(
|
||||
lead.get("updatesTitle"),
|
||||
"lead.updatesTitle",
|
||||
errors,
|
||||
)
|
||||
updates = _array(
|
||||
lead.get("updates"),
|
||||
"lead.updates",
|
||||
errors,
|
||||
limit=12,
|
||||
)
|
||||
for index, value in enumerate(updates):
|
||||
item = _mapping(value, f"lead.updates[{index}]", errors)
|
||||
_strings(item, ("time", "text"), f"lead.updates[{index}]", errors)
|
||||
|
||||
latest = _mapping(data.get("latest"), "latest", errors)
|
||||
_strings(latest, ("title", "moreLabel"), "latest", errors)
|
||||
latest_items = _array(
|
||||
latest.get("items"),
|
||||
"latest.items",
|
||||
errors,
|
||||
limit=12,
|
||||
)
|
||||
if not latest_items:
|
||||
errors.append("latest.items must contain at least one item")
|
||||
_validate_story_items(
|
||||
latest_items,
|
||||
"latest.items",
|
||||
errors,
|
||||
visuals=LATEST_VISUALS,
|
||||
include_summary=True,
|
||||
)
|
||||
|
||||
video = _mapping(data.get("video"), "video", errors)
|
||||
_strings(
|
||||
video,
|
||||
(
|
||||
"title",
|
||||
"moreLabel",
|
||||
"modalTitle",
|
||||
"liveTitle",
|
||||
"liveSubtitle",
|
||||
"modalNote",
|
||||
),
|
||||
"video",
|
||||
errors,
|
||||
)
|
||||
video_items = _array(
|
||||
video.get("items"),
|
||||
"video.items",
|
||||
errors,
|
||||
limit=8,
|
||||
)
|
||||
if not video_items:
|
||||
errors.append("video.items must contain at least one item")
|
||||
_validate_story_items(
|
||||
video_items,
|
||||
"video.items",
|
||||
errors,
|
||||
visuals=VIDEO_VISUALS,
|
||||
include_summary=False,
|
||||
include_duration=True,
|
||||
)
|
||||
|
||||
world = _mapping(data.get("world"), "world", errors)
|
||||
_strings(world, ("title", "moreLabel"), "world", errors)
|
||||
world_items = _array(
|
||||
world.get("items"),
|
||||
"world.items",
|
||||
errors,
|
||||
limit=16,
|
||||
)
|
||||
if not world_items:
|
||||
errors.append("world.items must contain at least one item")
|
||||
_validate_story_items(
|
||||
world_items,
|
||||
"world.items",
|
||||
errors,
|
||||
visuals=WORLD_VISUALS,
|
||||
include_summary=False,
|
||||
)
|
||||
analysis = _mapping(world.get("analysis"), "world.analysis", errors)
|
||||
_strings(
|
||||
analysis,
|
||||
("kicker", "title", "text", "author", "role", "initial"),
|
||||
"world.analysis",
|
||||
errors,
|
||||
)
|
||||
|
||||
markets = _mapping(data.get("markets"), "markets", errors)
|
||||
_strings(markets, ("title", "moreLabel"), "markets", errors)
|
||||
market_items = _array(
|
||||
markets.get("items"),
|
||||
"markets.items",
|
||||
errors,
|
||||
limit=8,
|
||||
)
|
||||
if not market_items:
|
||||
errors.append("markets.items must contain at least one item")
|
||||
for index, value in enumerate(market_items):
|
||||
item = _mapping(value, f"markets.items[{index}]", errors)
|
||||
_strings(
|
||||
item,
|
||||
("name", "value", "change"),
|
||||
f"markets.items[{index}]",
|
||||
errors,
|
||||
)
|
||||
_direction(
|
||||
item.get("direction"),
|
||||
f"markets.items[{index}].direction",
|
||||
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, ("tagline", "copyright", "legal"), "footer", errors)
|
||||
columns = _array(
|
||||
footer.get("columns"),
|
||||
"footer.columns",
|
||||
errors,
|
||||
limit=6,
|
||||
)
|
||||
for index, value in enumerate(columns):
|
||||
column_path = f"footer.columns[{index}]"
|
||||
column = _mapping(value, column_path, errors)
|
||||
_non_empty_string(column.get("title"), f"{column_path}.title", errors)
|
||||
links = _array(
|
||||
column.get("links"),
|
||||
f"{column_path}.links",
|
||||
errors,
|
||||
limit=8,
|
||||
)
|
||||
for link_index, link_value in enumerate(links):
|
||||
link_path = f"{column_path}.links[{link_index}]"
|
||||
link = _mapping(link_value, link_path, errors)
|
||||
_non_empty_string(link.get("label"), f"{link_path}.label", errors)
|
||||
_href(link.get("href"), f"{link_path}.href", errors)
|
||||
|
||||
if errors:
|
||||
raise DataValidationError("; ".join(errors))
|
||||
|
||||
return {
|
||||
"modules": list(MODULES),
|
||||
"counts": {
|
||||
"navigation": len(nav_items),
|
||||
"side_stories": len(side_stories),
|
||||
"updates": len(updates),
|
||||
"latest": len(latest_items),
|
||||
"videos": len(video_items),
|
||||
"world": len(world_items),
|
||||
"markets": len(market_items),
|
||||
"footer_columns": len(columns),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
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