"""Offline Playwright Chromium lab for React Ch 32: Vite Project Init, JSX Rules & Blog Skeleton."""
import json
from playwright.sync_api import sync_playwright
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>React Blog Project Init Lab</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; color: #333; }
.navbar { display: flex; justify-content: space-between; align-items: center; padding: 16px 40px; background: #fff; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.logo { font-size: 24px; color: #61dafb; }
.navbar nav a { margin-left: 20px; text-decoration: none; color: #333; }
.container { max-width: 960px; margin: 40px auto; padding: 0 20px; }
.footer { text-align: center; padding: 20px; color: #999; border-top: 1px solid #eee; }
</style>
</head>
<body>
<div id="root"></div>
<div id="jsx-lab"></div>
<div id="case-rule-lab"></div>
<script>
// Minimal offline createElement + createRoot + StrictMode renderer
const StrictMode = Symbol("StrictMode");
function h(type, props, ...children) {
const flat = children.flat(Infinity).filter((c) => c !== null && c !== undefined && c !== false && c !== true);
return { type, props: { ...(props || {}), children: flat } };
}
function renderToDom(vnode, inStrict) {
if (typeof vnode === "string" || typeof vnode === "number") {
return document.createTextNode(String(vnode));
}
if (vnode.type === StrictMode) {
const frag = document.createDocumentFragment();
vnode.props.children.forEach((child) => frag.appendChild(renderToDom(child, true)));
return frag;
}
if (typeof vnode.type === "function") {
// React StrictMode double-invokes function components in dev to detect impure renders
if (inStrict) vnode.type(vnode.props);
return renderToDom(vnode.type(vnode.props), inStrict);
}
const el = document.createElement(vnode.type);
const props = vnode.props || {};
for (const [k, v] of Object.entries(props)) {
if (k === "children") continue;
if (k === "className") el.setAttribute("class", v);
else if (k === "htmlFor") el.setAttribute("for", v);
else if (k === "style" && typeof v === "object") Object.assign(el.style, v);
else if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2).toLowerCase(), v);
else el.setAttribute(k, String(v));
}
for (const child of props.children || []) {
el.appendChild(renderToDom(child, inStrict));
}
return el;
}
function createRoot(container) {
return {
render(vnode) {
container.innerHTML = "";
container.appendChild(renderToDom(vnode, false));
}
};
}
// 1. StrictMode & Vite project structure check
window.runMountAndStrictCheck = () => {
let devInvokes = 0;
let prodInvokes = 0;
function DevProbe() { devInvokes += 1; return h("span", { id: "probe-dev" }, "dev"); }
function ProdProbe() { prodInvokes += 1; return h("span", { id: "probe-prod" }, "prod"); }
const host = document.createElement("div");
createRoot(host).render(h(StrictMode, null, h(DevProbe, null)));
const devMountedText = host.textContent;
createRoot(host).render(h(ProdProbe, null));
const prodMountedText = host.textContent;
const expectedFiles = [
"index.html", "package.json", "vite.config.js",
"public/", "src/main.jsx", "src/App.jsx", "src/App.css", "src/index.css", "src/assets/"
];
return {
rootContainerId: document.getElementById("root").id,
devStrictInvokes: devInvokes,
prodInvokes,
devMountedText,
prodMountedText,
viteFileCount: expectedFiles.length
};
};
// 2. JSX vs HTML differences
window.runJsxDiffCheck = () => {
let clicks = 0;
function Greeting() {
const name = "BlueSky";
const isLoggedIn = true;
return h("div", { className: "greeting container" },
h("h1", { id: "greet-title" }, "Hello, ", name, "!"),
h("label", { id: "greet-label", htmlFor: "nick-input" }, "昵称"),
h("input", { id: "nick-input", type: "text", value: name }),
h("img", { id: "greet-img", src: "data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=", alt: "demo" }),
h("p", { id: "greet-style", style: { color: "red", fontSize: "18px" } }, "样式测试"),
isLoggedIn && h("p", { id: "greet-welcome" }, "欢迎回来!"),
h("button", { id: "greet-btn", onClick: () => { clicks += 1; } }, "点击")
);
}
const host = document.getElementById("jsx-lab");
createRoot(host).render(h(Greeting, null));
document.getElementById("greet-btn").click();
const st = getComputedStyle(document.getElementById("greet-style"));
return {
classAttr: host.firstElementChild.getAttribute("class"),
forAttr: document.getElementById("greet-label").getAttribute("for"),
headingText: document.getElementById("greet-title").textContent,
welcomeText: document.getElementById("greet-welcome").textContent,
imgTag: document.getElementById("greet-img").tagName.toLowerCase(),
computedColor: st.color,
computedFontSize: st.fontSize,
onClickCount: clicks
};
};
// 3. Uppercase component vs lowercase HTML tag rule
window.runComponentCaseCheck = () => {
function BlogHeader() {
return h("header", { className: "custom-hdr" }, h("h1", null, "BlueSky Blog"));
}
const host = document.getElementById("case-rule-lab");
createRoot(host).render(
h("div", null,
h(BlogHeader, null),
h("blogheader", { className: "raw-tag" }, "fallback-text")
)
);
return {
uppercaseRenderedTag: host.querySelector("header.custom-hdr h1").textContent,
lowercaseRenderedTag: host.querySelector("blogheader.raw-tag").tagName.toLowerCase(),
lowercaseInnerText: host.querySelector("blogheader.raw-tag").textContent
};
};
// 4. Render Blog Skeleton into #root
function App() {
return h("div", { className: "app" },
h("header", { className: "navbar" },
h("h1", { className: "logo" }, "BlueSky Blog"),
h("nav", null,
h("a", { href: "/" }, "首页"),
h("a", { href: "#about" }, "关于")
)
),
h("main", { className: "container" },
h("p", { id: "main-placeholder" }, "博客内容将在这里展示")
),
h("footer", { className: "footer" },
h("p", null, "© 2026 BlueSky Blog. Powered by React.")
)
);
}
createRoot(document.getElementById("root")).render(h(StrictMode, null, h(App, null)));
</script>
</body>
</html>
"""
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 1280, "height": 800})
page.set_content(HTML)
c1_actual = page.evaluate("() => window.runMountAndStrictCheck()")
c1_expected = {
"rootContainerId": "root",
"devStrictInvokes": 2,
"prodInvokes": 1,
"devMountedText": "dev",
"prodMountedText": "prod",
"viteFileCount": 9,
}
cases.append({
"name": "vite_project_mount_and_strict_mode",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
})
c2_actual = page.evaluate("() => window.runJsxDiffCheck()")
c2_expected = {
"classAttr": "greeting container",
"forAttr": "nick-input",
"headingText": "Hello, BlueSky!",
"welcomeText": "欢迎回来!",
"imgTag": "img",
"computedColor": "rgb(255, 0, 0)",
"computedFontSize": "18px",
"onClickCount": 1,
}
cases.append({
"name": "jsx_vs_html_differences",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
})
c3_actual = page.evaluate("() => window.runComponentCaseCheck()")
c3_expected = {
"uppercaseRenderedTag": "BlueSky Blog",
"lowercaseRenderedTag": "blogheader",
"lowercaseInnerText": "fallback-text",
}
cases.append({
"name": "component_function_uppercase_rule",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
})
c4_actual = page.evaluate("""() => {
const nav = document.querySelector('#root .navbar');
const logo = document.querySelector('#root .logo');
const main = document.querySelector('#root main.container');
const footer = document.querySelector('#root footer.footer');
return {
navbarDisplay: getComputedStyle(nav).display,
navbarJustify: getComputedStyle(nav).justifyContent,
logoColor: getComputedStyle(logo).color,
navLinks: Array.from(nav.querySelectorAll('nav a')).map(a => a.textContent),
containerMaxWidth: getComputedStyle(main).maxWidth,
mainText: document.getElementById('main-placeholder').textContent,
footerAlign: getComputedStyle(footer).textAlign
};
}""")
c4_expected = {
"navbarDisplay": "flex",
"navbarJustify": "space-between",
"logoColor": "rgb(97, 218, 251)",
"navLinks": ["首页", "关于"],
"containerMaxWidth": "960px",
"mainText": "博客内容将在这里展示",
"footerAlign": "center",
}
cases.append({
"name": "blog_skeleton_layout_and_css",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_expected,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/react-blog-project-init-lab/explore-blog-project-init.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-blog-project-init.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3156.zip