"""Offline Playwright Chromium lab for React Ch 07 (vscode)."""
from __future__ import annotations
import json
import re
from playwright.sync_api import sync_playwright
MICRO_REACT_JS = r"""
var React = (() => {
function createElement(type, props, ...children) {
const flat = [];
const push = (c) => {
if (Array.isArray(c)) c.forEach(push);
else if (c !== null && c !== undefined && c !== false && c !== true) flat.push(c);
};
children.forEach(push);
return { type, props: Object.assign({}, props || {}, { children: flat }) };
}
let currentRoot = null;
let currentPath = "";
let hookIndex = 0;
function useState(initial) {
const root = currentRoot;
const key = currentPath + "#" + (hookIndex++);
if (!(key in root.hooks)) root.hooks[key] = typeof initial === "function" ? initial() : initial;
const setState = (next) => {
root.hooks[key] = typeof next === "function" ? next(root.hooks[key]) : next;
root.rerender();
};
return [root.hooks[key], setState];
}
function resolveTree(node, path) {
if (node === null || node === undefined || typeof node === "boolean") return null;
if (typeof node === "string" || typeof node === "number") return { type: "#text", text: String(node) };
if (typeof node.type === "function") {
const prevPath = currentPath;
const prevIdx = hookIndex;
currentPath = path + "/" + (node.type.name || "Fn");
hookIndex = 0;
const out = resolveTree(node.type(node.props), currentPath);
currentPath = prevPath;
hookIndex = prevIdx;
return out;
}
const children = [];
(node.props.children || []).forEach((c, i) => {
const r = resolveTree(c, path + "." + i);
if (r) children.push(r);
});
return { type: node.type, props: node.props, children };
}
function createDom(vnode) {
if (vnode.type === "#text") return document.createTextNode(vnode.text);
const el = document.createElement(vnode.type);
for (const [k, v] of Object.entries(vnode.props || {})) {
if (k === "children" || k === "key") continue;
if (k === "className") el.setAttribute("class", 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));
}
vnode.children.forEach((c) => el.appendChild(createDom(c)));
return el;
}
function createRoot(container) {
return {
container,
hooks: {},
lastElement: null,
render(element) { this.lastElement = element; this.rerender(); },
rerender() {
currentRoot = this;
const resolved = resolveTree(this.lastElement, "root");
this.container.innerHTML = "";
if (resolved) this.container.appendChild(createDom(resolved));
currentRoot = null;
},
};
}
return { createElement, useState, createRoot };
})();
var ReactDOM = { createRoot: React.createRoot };
"""
VSCODE_SETTINGS_JSONC = """{
// 保存时自动格式化
"editor.formatOnSave": true,
// 默认使用 Prettier 格式化
"editor.defaultFormatter": "esbenp.prettier-vscode",
// ESLint 自动修复
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
// JSX/TSX 文件也应用 Prettier
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
// 显示行号、缩进指南
"editor.rulers": [80],
"editor.guides.indentation": true
}"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main() -> None:
cases = []
# Case 1: Validate .vscode/settings.json (strip JSONC single-line comments)
stripped = re.sub(r"^\s*//.*$", "", VSCODE_SETTINGS_JSONC, flags=re.MULTILINE)
parsed = json.loads(stripped)
actual1 = {
"formatOnSave": parsed["editor.formatOnSave"],
"defaultFormatter": parsed["editor.defaultFormatter"],
"eslintFix": parsed["editor.codeActionsOnSave"]["source.fixAll.eslint"],
"jsxFormatter": parsed["[javascriptreact]"]["editor.defaultFormatter"],
"rulers": parsed["editor.rulers"],
"indentGuides": parsed["editor.guides.indentation"],
}
expected1 = {
"formatOnSave": True,
"defaultFormatter": "esbenp.prettier-vscode",
"eslintFix": "explicit",
"jsxFormatter": "esbenp.prettier-vscode",
"rulers": [80],
"indentGuides": True,
}
cases.append({
"name": "vscode_settings_json_validation",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
# Case 2: Greeting component with default prop & isolated instance state
page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
const Greeting = ({{ name = "陌生人" }}) => {{
const [count, setCount] = React.useState(0);
return React.createElement(
"div", {{ className: "greeting", style: {{ padding: "20px", border: "1px solid #ccc" }} }},
React.createElement("h2", null, "你好," + name + "!"),
React.createElement("p", null, "你已经点击了 " + count + " 次"),
React.createElement("button", {{ onClick: () => setCount(count + 1) }}, "点击我 +1")
);
}};
function App() {{
return React.createElement(
"div", null,
React.createElement(Greeting, {{ name: "React" }}),
React.createElement(Greeting, {{}})
);
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App, null));
</script></body></html>""")
page.locator(".greeting").nth(0).locator("button").click()
page.locator(".greeting").nth(0).locator("button").click()
actual2 = page.evaluate("""() => Array.from(document.querySelectorAll(".greeting")).map(g => ({
heading: g.querySelector("h2").textContent,
countText: g.querySelector("p").textContent
}))""")
expected2 = [
{"heading": "你好,React!", "countText": "你已经点击了 2 次"},
{"heading": "你好,陌生人!", "countText": "你已经点击了 0 次"},
]
cases.append({
"name": "rafce_greeting_state_and_default_prop",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Card component conditional image rendering (imageUrl && <img ... />)
page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
const svgImg = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='120' height='60'><rect width='120' height='60' fill='%2361dafb'/></svg>";
const Card = ({{ title, content, imageUrl }}) => React.createElement(
"div", {{ className: "card", style: {{ width: "300px", border: "1px solid #ccc", borderRadius: "12px", overflow: "hidden" }} }},
imageUrl && React.createElement("img", {{ src: imageUrl, alt: title, style: {{ width: "100%", height: "200px", objectFit: "cover" }} }}),
React.createElement("div", {{ style: {{ padding: "20px" }} }},
React.createElement("h3", null, title),
React.createElement("p", null, content)
)
);
ReactDOM.createRoot(document.getElementById("root")).render(
React.createElement("div", null,
React.createElement(Card, {{ title: "带图卡片", content: "包含顶部封面", imageUrl: svgImg }}),
React.createElement(Card, {{ title: "纯文卡片", content: "未传入 imageUrl" }})
)
);
</script></body></html>""")
actual3 = page.evaluate("""() => {
const cards = Array.from(document.querySelectorAll(".card"));
return {
withImageCount: cards[0].querySelectorAll("img").length,
withImageAlt: cards[0].querySelector("img").getAttribute("alt"),
withoutImageCount: cards[1].querySelectorAll("img").length,
titles: cards.map(c => c.querySelector("h3").textContent)
};
}""")
expected3 = {
"withImageCount": 1,
"withImageAlt": "带图卡片",
"withoutImageCount": 0,
"titles": ["带图卡片", "纯文卡片"],
}
cases.append({
"name": "card_component_conditional_image",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: App flex-wrap card gallery layout
page.goto("about:blank")
page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
const svgA = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='80' height='80'><circle cx='40' cy='40' r='30' fill='%2300d8ff'/></svg>";
const svgB = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='80' height='80'><polygon points='40,5 75,75 5,75' fill='%23646cff'/></svg>";
const Card = ({{ title, content, imageUrl }}) => React.createElement(
"div", {{ className: "card", style: {{ width: "300px", borderRadius: "12px", backgroundColor: "#fff" }} }},
imageUrl && React.createElement("img", {{ src: imageUrl, alt: title }}),
React.createElement("h3", null, title),
React.createElement("p", null, content)
);
function App() {{
return React.createElement(
"div",
{{ id: "gallery", style: {{ display: "flex", flexWrap: "wrap", justifyContent: "center", padding: "40px", backgroundColor: "#f0f0f0", minHeight: "100vh" }} }},
React.createElement(Card, {{ title: "React 是什么?", content: "用于构建用户界面的 JavaScript 库。", imageUrl: svgA }}),
React.createElement(Card, {{ title: "Vite 的优势", content: "基于原生 ESM 的现代构建工具。", imageUrl: svgB }})
);
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App, null));
</script></body></html>""")
actual4 = page.evaluate("""() => {
const g = document.getElementById("gallery");
const cs = getComputedStyle(g);
return {
display: cs.display,
flexWrap: cs.flexWrap,
justifyContent: cs.justifyContent,
cardCount: g.querySelectorAll(".card").length,
titles: Array.from(g.querySelectorAll(".card h3")).map(h => h.textContent)
};
}""")
expected4 = {
"display": "flex",
"flexWrap": "wrap",
"justifyContent": "center",
"cardCount": 2,
"titles": ["React 是什么?", "Vite 的优势"],
}
cases.append({
"name": "app_flex_card_gallery_layout",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/react-vscode-lab/explore-vscode.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-vscode.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3193.zip