"""Offline Playwright Chromium lab for React Ch 06 (dumate-dev-react)."""
from __future__ import annotations
import json
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 hookIndex = 0;
function useState(initial) {
const root = currentRoot;
const idx = hookIndex++;
if (!(idx in root.hooks)) root.hooks[idx] = typeof initial === "function" ? initial() : initial;
const setState = (next) => {
root.hooks[idx] = typeof next === "function" ? next(root.hooks[idx]) : next;
root.rerender();
};
return [root.hooks[idx], setState];
}
function resolveTree(node) {
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") return resolveTree(node.type(node.props));
return { type: node.type, props: node.props, children: (node.props.children || []).map(resolveTree).filter(Boolean) };
}
function createDom(vnode) {
if (vnode.type === "#text") return document.createTextNode(vnode.text);
const svgTags = new Set(["svg", "rect"]);
const el = svgTags.has(vnode.type)
? document.createElementNS("http://www.w3.org/2000/svg", vnode.type)
: 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 === "value" && (el.tagName === "TEXTAREA" || el.tagName === "INPUT")) el.value = 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;
hookIndex = 0;
const resolved = resolveTree(this.lastElement);
this.container.innerHTML = "";
if (resolved) this.container.appendChild(createDom(resolved));
currentRoot = null;
},
};
}
return { createElement, useState, createRoot };
})();
var ReactDOM = { createRoot: React.createRoot };
"""
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 = []
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
# Case 1: Validate standard AI-generated Vite + React project entry structure (qr-code-studio)
page.set_content("""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8" /><title>二维码工坊 · 在线二维码生成工具</title></head>
<body><div id="root"></div><script type="module" data-src="/src/main.jsx"></script></body>
</html>""")
actual1 = page.evaluate("""() => ({
title: document.title,
hasRoot: Boolean(document.getElementById("root")),
entry: document.querySelector("script[type='module']").getAttribute("data-src"),
devUrl: "http://127.0.0.1:5173/"
})""")
expected1 = {
"title": "二维码工坊 · 在线二维码生成工具",
"hasRoot": True,
"entry": "/src/main.jsx",
"devUrl": "http://127.0.0.1:5173/",
}
cases.append({
"name": "ai_generated_vite_qr_skeleton",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2 & 3: Offline React QR tool UI render + interactive state reconciliation
page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
function computeBits(text, level) {{
let hash = 2166136261;
const src = text + "|" + level;
for (let i = 0; i < src.length; i++) {{
hash ^= src.charCodeAt(i);
hash = Math.imul(hash, 16777619) >>> 0;
}}
const cells = [];
for (let r = 0; r < 7; r++) {{
for (let c = 0; c < 7; c++) {{
const bit = ((hash >>> ((r * 7 + c) % 29)) ^ (r + c)) & 1;
if (bit) cells.push([r, c]);
}}
}}
return {{ hash: hash.toString(16), cells }};
}}
function QrStudio() {{
const [content, setContent] = React.useState("https://example.com");
const [level, setLevel] = React.useState("M");
const [size] = React.useState(320);
const grid = computeBits(content, level);
return React.createElement(
"main", null,
React.createElement("h1", null, "二维码工坊"),
React.createElement("textarea", {{ id: "qr-input", value: content }}),
React.createElement("button", {{ id: "set-text", onClick: () => setContent("https://react.dev") }}, "切换网址"),
React.createElement("button", {{ id: "set-level-h", onClick: () => setLevel("H") }}, "容错 H"),
React.createElement("p", {{ id: "summary" }}, size + "px · " + level + " · " + content),
React.createElement(
"svg", {{ id: "qr-svg", width: size, height: size, "data-hash": grid.hash }},
grid.cells.map(([r, c]) => React.createElement("rect", {{ x: c * 10, y: r * 10, width: 10, height: 10 }}))
)
);
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(QrStudio, null));
</script></body></html>""")
initial_qr = page.evaluate("""() => ({
title: document.querySelector("h1").textContent,
summary: document.getElementById("summary").textContent,
rectCount: document.querySelectorAll("#qr-svg rect").length,
hash: document.getElementById("qr-svg").getAttribute("data-hash")
})""")
expected2 = {
"title": "二维码工坊",
"summary": "320px · M · https://example.com",
"hasRects": True,
}
actual2 = {
"title": initial_qr["title"],
"summary": initial_qr["summary"],
"hasRects": initial_qr["rectCount"] > 0,
}
cases.append({
"name": "react_qr_tool_ui_render",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
page.click("#set-text")
page.click("#set-level-h")
updated_qr = page.evaluate("""() => ({
summary: document.getElementById("summary").textContent,
hash: document.getElementById("qr-svg").getAttribute("data-hash")
})""")
actual3 = {
"summary": updated_qr["summary"],
"hashChanged": updated_qr["hash"] != initial_qr["hash"],
}
expected3 = {
"summary": "320px · H · https://react.dev",
"hashChanged": True,
}
cases.append({
"name": "react_qr_state_reconciliation",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Clean self-authored React copy feedback state (not executing any source script)
page.set_content(f"""<!DOCTYPE html>
<html><body><div id="cp"></div>
<script>{MICRO_REACT_JS}
function CopyButton({{ text }}) {{
const [copied, setCopied] = React.useState(false);
return React.createElement(
"button",
{{ id: "cp-btn", "data-payload": text, onClick: () => setCopied(true) }},
copied ? "已复制" : "复制"
);
}}
ReactDOM.createRoot(document.getElementById("cp")).render(
React.createElement(CopyButton, {{ text: "npm run dev" }})
);
</script></body></html>""")
before_cp = page.text_content("#cp-btn")
page.click("#cp-btn")
after_cp = page.text_content("#cp-btn")
actual4 = {"before": before_cp, "after": after_cp}
expected4 = {"before": "复制", "after": "已复制"}
cases.append({
"name": "clipboard_copy_pattern_isolated",
"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-dumate-dev-react-lab/explore-dumate-dev-react.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-dumate-dev-react.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3170.zip