"""Offline Playwright Chromium lab for React Ch 02 (intro)."""
from __future__ import annotations
import json
from playwright.sync_api import sync_playwright
MICRO_REACT_JS = r"""
var React = (() => {
const Fragment = Symbol("Fragment");
const StrictMode = Symbol("StrictMode");
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) => {
const prev = root.hooks[idx];
root.hooks[idx] = typeof next === "function" ? next(prev) : 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 (node.type === Fragment || node.type === StrictMode) {
return {
type: "#fragment",
children: (node.props.children || []).map(resolveTree).filter(Boolean),
};
}
if (typeof node.type === "function") return resolveTree(node.type(node.props));
const children = [];
for (const c of node.props.children || []) {
const r = resolveTree(c);
if (!r) continue;
if (r.type === "#fragment") children.push(...r.children);
else children.push(r);
}
return { type: node.type, props: node.props, children };
}
function applyProps(el, nextProps, prevProps) {
const prev = prevProps || {};
for (const [k, v] of Object.entries(nextProps || {})) {
if (k === "children" || k === "key") continue;
if (prev[k] === v) 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") {
const evt = k.slice(2).toLowerCase();
if (prev[k]) el.removeEventListener(evt, prev[k]);
el.addEventListener(evt, v);
} else el.setAttribute(k, String(v));
}
}
function createDom(vnode) {
if (vnode.type === "#text") {
const tn = document.createTextNode(vnode.text);
vnode.dom = tn;
return tn;
}
const el = document.createElement(vnode.type);
applyProps(el, vnode.props, {});
vnode.children.forEach((c) => el.appendChild(createDom(c)));
vnode.dom = el;
return el;
}
function patch(parent, oldNode, newNode, stats) {
if (!oldNode && newNode) {
const dom = createDom(newNode);
newNode.dom = dom;
parent.appendChild(dom);
stats.created += 1;
return;
}
if (oldNode && !newNode) {
parent.removeChild(oldNode.dom);
stats.removed += 1;
return;
}
if (oldNode.type !== newNode.type) {
const dom = createDom(newNode);
newNode.dom = dom;
parent.replaceChild(dom, oldNode.dom);
stats.replaced += 1;
return;
}
if (newNode.type === "#text") {
newNode.dom = oldNode.dom;
if (oldNode.text !== newNode.text) {
oldNode.dom.nodeValue = newNode.text;
stats.textUpdated += 1;
}
return;
}
const el = oldNode.dom;
newNode.dom = el;
applyProps(el, newNode.props, oldNode.props);
const maxLen = Math.max(oldNode.children.length, newNode.children.length);
for (let i = 0; i < maxLen; i++) {
patch(el, oldNode.children[i], newNode.children[i], stats);
}
}
function createRoot(container) {
return {
container,
hooks: {},
prevTree: null,
lastElement: null,
lastStats: { created: 0, removed: 0, replaced: 0, textUpdated: 0 },
render(element) {
this.lastElement = element;
this.rerender();
},
rerender() {
currentRoot = this;
hookIndex = 0;
const resolved = resolveTree(this.lastElement);
const stats = { created: 0, removed: 0, replaced: 0, textUpdated: 0 };
patch(this.container, this.prevTree, resolved, stats);
this.prevTree = resolved;
this.lastStats = stats;
currentRoot = null;
},
};
}
return { createElement, Fragment, StrictMode, 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: Imperative vs Declarative counter
page.set_content(f"""<!DOCTYPE html>
<html><body>
<button id="myButton">Inc</button><span id="counter">0</span>
<div id="decl-root"></div>
<script>{MICRO_REACT_JS}
const button = document.getElementById("myButton");
button.addEventListener("click", function() {{
const counter = document.getElementById("counter");
const currentValue = parseInt(counter.textContent, 10);
counter.textContent = currentValue + 1;
}});
function Counter() {{
const [count, setCount] = React.useState(0);
return React.createElement("button", {{ id: "declBtn", onClick: () => setCount(count + 1) }}, count);
}}
ReactDOM.createRoot(document.getElementById("decl-root")).render(React.createElement(Counter, null));
</script></body></html>""")
for _ in range(3):
page.click("#myButton")
page.click("#declBtn")
actual1 = {
"imperative": page.text_content("#counter"),
"declarative": page.text_content("#declBtn"),
}
expected1 = {"imperative": "3", "declarative": "3"}
cases.append({
"name": "imperative_vs_declarative_counter",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: Component reuse and composition (Welcome x3)
page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="comp-root"></div>
<script>{MICRO_REACT_JS}
function Welcome({{ name }}) {{
return React.createElement("h1", null, "Hello, " + name + "!");
}}
function App() {{
return React.createElement(
"div",
null,
React.createElement(Welcome, {{ name: "Alice" }}),
React.createElement(Welcome, {{ name: "Bob" }}),
React.createElement(Welcome, {{ name: "Charlie" }})
);
}}
ReactDOM.createRoot(document.getElementById("comp-root")).render(React.createElement(App, null));
</script></body></html>""")
actual2 = page.evaluate("""() => Array.from(document.querySelectorAll("#comp-root h1")).map(el => el.textContent)""")
expected2 = ["Hello, Alice!", "Hello, Bob!", "Hello, Charlie!"]
cases.append({
"name": "component_reuse_composition",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Virtual DOM diff/patch on 1000-item list
page.goto("about:blank")
page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="list-root"></div>
<script>{MICRO_REACT_JS}
const baseItems = Array.from({{ length: 1000 }}, (_, i) => String(i));
function ItemList({{ items }}) {{
return React.createElement(
"ul",
{{ id: "items" }},
items.map((item, idx) => React.createElement("li", {{ key: idx }}, item))
);
}}
const listRoot = ReactDOM.createRoot(document.getElementById("list-root"));
listRoot.render(React.createElement(ItemList, {{ items: baseItems }}));
const beforeNodes = Array.from(document.querySelectorAll("#items li"));
const nextItems = baseItems.slice();
nextItems[0] = "0-updated";
nextItems[999] = "999-updated";
listRoot.render(React.createElement(ItemList, {{ items: nextItems }}));
const afterNodes = Array.from(document.querySelectorAll("#items li"));
let preserved = 0;
for (let i = 0; i < 1000; i++) {{
if (beforeNodes[i] === afterNodes[i]) preserved += 1;
}}
window.__listResult = {{
totalItems: afterNodes.length,
firstText: afterNodes[0].textContent,
lastText: afterNodes[999].textContent,
preservedDomNodes: preserved,
textMutations: listRoot.lastStats.textUpdated,
nodesCreatedOnUpdate: listRoot.lastStats.created
}};
</script></body></html>""")
actual3 = page.evaluate("() => window.__listResult")
expected3 = {
"totalItems": 1000,
"firstText": "0-updated",
"lastText": "999-updated",
"preservedDomNodes": 1000,
"textMutations": 2,
"nodesCreatedOnUpdate": 0,
}
cases.append({
"name": "virtual_dom_diff_patch_1000",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: Unidirectional data flow Parent -> Child with callback upward
page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="flow-root"></div>
<script>{MICRO_REACT_JS}
function Child({{ message, onUpdate }}) {{
return React.createElement(
"div",
null,
React.createElement("p", {{ id: "msg" }}, message),
React.createElement("button", {{ id: "upd", onClick: () => onUpdate("Updated!") }}, "Update")
);
}}
function Parent() {{
const [message, setMessage] = React.useState("Hello");
return React.createElement(Child, {{ message, onUpdate: setMessage }});
}}
ReactDOM.createRoot(document.getElementById("flow-root")).render(React.createElement(Parent, null));
</script></body></html>""")
initial_msg = page.text_content("#msg")
page.click("#upd")
updated_msg = page.text_content("#msg")
actual4 = {"initial": initial_msg, "afterCallback": updated_msg}
expected4 = {"initial": "Hello", "afterCallback": "Updated!"}
cases.append({
"name": "unidirectional_data_flow_callback",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
# Case 5: Multi-level top-down prop chain (Parent -> Child -> GrandChild)
page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="chain-root"></div>
<script>{MICRO_REACT_JS}
function GrandChild({{ theme }}) {{
return React.createElement("span", {{ id: "leaf" }}, "theme=" + theme);
}}
function MidChild({{ theme }}) {{
return React.createElement("div", {{ className: "mid" }}, React.createElement(GrandChild, {{ theme }}));
}}
function TopParent() {{
return React.createElement(MidChild, {{ theme: "ocean-blue" }});
}}
ReactDOM.createRoot(document.getElementById("chain-root")).render(React.createElement(TopParent, null));
</script></body></html>""")
actual5 = {
"leafText": page.text_content("#leaf"),
"depth": page.evaluate("""() => {
const leaf = document.getElementById("leaf");
return leaf.parentElement.className === "mid" ? 2 : 0;
}"""),
}
expected5 = {"leafText": "theme=ocean-blue", "depth": 2}
cases.append({
"name": "framework_comparison_model_check",
"expected": expected5,
"actual": actual5,
"passed": actual5 == expected5,
})
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-intro-lab/explore-intro.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-intro.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3176.zip