import React, { useLayoutEffect, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import html2canvas from "html2canvas";
import "./index.css";
const templates = [
{ section: "城市", headline: "北岸步道重新开放", subhead: "沿河更新进入下一阶段", summary: "新的休息区已开放,周末增设城市步行导览。", author: "林初", date: "2027-03-19" },
{ section: "文化", headline: "春季书展本周开幕", subhead: "独立书店发布活动日程", summary: "书展集合本地作者分享、旧书交换及儿童读书会。", author: "周宁", date: "2027-03-20" },
{ section: "交通", headline: "夜间公交调整班次", subhead: "测试运行覆盖三个片区", summary: "公交服务将在下周延长末班车时间,以便夜间通勤。", author: "陈青", date: "2027-03-21" },
];
const fields = [
["section", "分类", 12], ["headline", "标题", 30], ["subhead", "副标题", 40],
["summary", "摘要", 104], ["author", "作者", 18], ["date", "日期", 10],
];
function NewsCard({ card, photo, style }) {
return <article className="news-card bg-paper p-16 font-editorial" style={style}>
<div className="border-b-4 border-accent pb-4 text-2xl">城市简报 · {card.section}</div>
<div className="mt-10 flex items-start justify-between gap-12">
<div className="min-w-0 flex-1">
<h2 className="break-words text-[56px] font-bold leading-tight">{card.headline || "未填标题"}</h2>
<p className="mt-4 break-words text-[30px] leading-snug">{card.subhead}</p>
<p className="mt-6 break-words text-[25px] leading-snug text-[#504a3c]">{card.summary}</p>
<p className="mt-6 text-[21px]">{card.author} <time dateTime={card.date}>{card.date}</time></p>
</div>
{photo && <img className="image-section shrink-0" src={photo} alt="新闻配图" />}
</div>
</article>;
}
function App() {
const [card, setCard] = useState(templates[0]);
const [template, setTemplate] = useState("0");
const [photo, setPhoto] = useState("");
const [message, setMessage] = useState("");
const [exporting, setExporting] = useState(false);
const [scale, setScale] = useState(1);
const preview = useRef(null);
const exportStage = useRef(null);
const uploadVersion = useRef(0);
useLayoutEffect(() => {
const observer = new ResizeObserver(([size]) => setScale(size.contentRect.width / 1200));
observer.observe(preview.current);
return () => observer.disconnect();
}, []);
function acceptFile(file) {
if (!file) return;
const selected = ++uploadVersion.current;
if (!["image/png", "image/jpeg", "image/webp"].includes(file.type) || file.size > 5 * 1024 * 1024) {
setMessage("请选择 5 MB 以内的 PNG、JPEG 或 WebP 图片。");
return;
}
const reader = new FileReader();
reader.onerror = () => { if (selected === uploadVersion.current) setMessage("无法读取这张图片。"); };
reader.onload = async () => {
const image = new Image();
image.src = reader.result;
try {
await image.decode();
if (selected !== uploadVersion.current) return;
setPhoto(reader.result);
setMessage("已载入图片。");
} catch {
if (selected === uploadVersion.current) setMessage("图片内容无法解码。");
}
};
reader.readAsDataURL(file);
}
async function exportPng() {
setExporting(true);
setMessage("正在生成 PNG…");
try {
await document.fonts.ready;
const canvas = await html2canvas(exportStage.current.firstElementChild, { width: 1200, height: 630, scale: 1, logging: false });
const file = await new Promise((resolve) => canvas.toBlob(resolve, "image/png"));
if (!file) throw new Error("PNG encoding failed");
const url = URL.createObjectURL(file);
const link = document.createElement("a");
link.href = url;
link.download = "city-brief.png";
link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
setMessage("PNG 已生成。");
} catch {
setMessage("PNG 导出失败,请重试。");
} finally {
setExporting(false);
}
}
return <main className="mx-auto max-w-7xl px-4 py-7">
<h1 className="font-editorial text-3xl font-bold">城市简报卡片</h1>
<div className="mt-6 grid gap-6 lg:grid-cols-[21rem_minmax(0,1fr)]">
<section aria-label="编辑" className="grid gap-3 rounded border border-[#c7beaf] bg-paper p-5">
<label>预设模板<select value={template} onChange={(ev) => {
setTemplate(ev.target.value); setCard(templates[Number(ev.target.value)]);
}}><option value="0">城市更新</option><option value="1">文化活动</option><option value="2">交通提醒</option></select></label>
{fields.map(([key, label, max]) => {
const props = { value: card[key], maxLength: max, onChange: (ev) => setCard({ ...card, [key]: ev.target.value }) };
return <div key={key} className="grid gap-1"><label htmlFor={key}>{label}</label>{key === "summary" ? <textarea id={key} {...props} /> : <input id={key} {...props} type={key === "date" ? "date" : "text"} />}</div>;
})}
<div className="rounded border border-dashed border-accent p-3" data-testid="drop-area"
onDragOver={(event) => event.preventDefault()}
onDrop={(event) => { event.preventDefault(); acceptFile(event.dataTransfer.files[0]); }}>
<label>选择或拖入配图<input type="file" accept="image/png,image/jpeg,image/webp"
onChange={(event) => acceptFile(event.target.files[0])} /></label>
{photo && <button type="button" className="mt-2 underline" onClick={() => {
++uploadVersion.current; setPhoto(""); setMessage("已移除配图。");
}}>移除配图</button>}
</div>
<button type="button" className="rounded bg-ink px-4 py-2 text-white disabled:opacity-60"
disabled={exporting} onClick={exportPng}>{exporting ? "正在导出…" : "下载 PNG"}</button>
<p role="status" className="min-h-6">{message}</p>
</section>
<section aria-label="实时预览">
<div ref={preview} className="preview-frame"><NewsCard card={card} photo={photo} style={{ transform: "scale(" + scale + ")" }} /></div>
</section>
</div>
<div ref={exportStage} className="export-stage" aria-hidden="true"><NewsCard card={card} photo={photo} /></div>
</main>;
}
createRoot(document.getElementById("root")).render(<App />);
本例需在 React 18.3.1、Tailwind CSS 3.4.18、Vite 6.4.3、html2canvas 1.4.1、本机 Edge。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:React 18.3.1、Tailwind CSS 3.4.18、Vite 6.4.3、html2canvas 1.4.1、本机 Edge。
入口文件:projects/claude-code-news-card/src/main.jsx
本地运行步骤快速上手
- 点击上方“保存源码”保存为
main.jsx,或下载右侧课程工程包。 - 确认本地已准备 React 18.3.1、Tailwind CSS 3.4.18、Vite 6.4.3、html2canvas 1.4.1、本机 Edge。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3117.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3135.zip