蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在离线 Chromium 中验证 React 18 createRoot 挂载、单向数据流与虚拟 DOM 最小补丁

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial.py
explore-tutorial.py324 行
"""Offline Playwright Chromium lab for React Ch 01 (tutorial)."""
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");
  class Component {
    constructor(props) {
      this.props = props || {};
      this.state = {};
    }
    render() { return null; }
  }
  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") {
      if (node.type.prototype && node.type.prototype.isReactClass) {
        const inst = new node.type(node.props);
        return resolveTree(inst.render());
      }
      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 };
  }
  Component.prototype.isReactClass = true;

  function applyProps(el, nextProps, prevProps) {
    const prev = prevProps || {};
    for (const k of Object.keys(prev)) {
      if (k === "children" || k === "key") continue;
      if (!(k in nextProps)) {
        if (k === "className") el.removeAttribute("class");
        else if (k.startsWith("on") && typeof prev[k] === "function") {
          el.removeEventListener(k.slice(2).toLowerCase(), prev[k]);
        } else if (k === "style") el.removeAttribute("style");
        else el.removeAttribute(k);
      }
    }
    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) {
    const root = {
      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 root;
  }

  return { createElement, Fragment, StrictMode, Component, 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: CDN-style createRoot render into #example
            page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="example"></div>
<script>{MICRO_REACT_JS}
(() => {{
function App() {{
  return React.createElement("h1", null, "Hello, React!");
}}
const root = ReactDOM.createRoot(document.getElementById("example"));
root.render(React.createElement(App, null));
}})();
</script></body></html>""")
            actual1 = page.evaluate("""() => {
              const h1 = document.querySelector("#example h1");
              return { tag: h1 ? h1.tagName : null, text: h1 ? h1.textContent : null };
            }""")
            expected1 = {"tag": "H1", "text": "Hello, React!"}
            cases.append({
                "name": "cdn_root_render_app",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Case 2: CRA-style Hello component rendered into #root
            page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="root"></div>
<script>{MICRO_REACT_JS}
(() => {{
function Hello(props) {{
  return React.createElement("h1", null, "Hello World!");
}}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(React.createElement(Hello, null));
}})();
</script></body></html>""")
            actual2 = page.evaluate("""() => {
              const h1 = document.querySelector("#root h1");
              return { tag: h1 ? h1.tagName : null, text: h1 ? h1.textContent : null };
            }""")
            expected2 = {"tag": "H1", "text": "Hello World!"}
            cases.append({
                "name": "cra_hello_component_render",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            # Case 3: Declarative state + unidirectional props flow
            page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="app"></div>
<script>{MICRO_REACT_JS}
(() => {{
function Badge(props) {{
  return React.createElement("span", {{ id: "badge" }}, props.label + ": " + props.value);
}}
function CounterApp() {{
  const [count, setCount] = React.useState(0);
  return React.createElement(
    "div",
    null,
    React.createElement(Badge, {{ label: "Clicks", value: count }}),
    React.createElement("button", {{ id: "inc", onClick: () => setCount((c) => c + 1) }}, "+1")
  );
}}
ReactDOM.createRoot(document.getElementById("app")).render(React.createElement(CounterApp, null));
}})();
</script></body></html>""")
            before = page.text_content("#badge")
            page.click("#inc")
            page.click("#inc")
            after = page.text_content("#badge")
            actual3 = {"before": before, "after": after}
            expected3 = {"before": "Clicks: 0", "after": "Clicks: 2"}
            cases.append({
                "name": "declarative_unidirectional_flow",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            # Case 4: Virtual DOM minimal patch preserving sibling DOM node identity
            page.set_content(f"""<!DOCTYPE html>
<html><body>
<div id="vdom"></div>
<script>{MICRO_REACT_JS}
(() => {{
function Demo() {{
  const [ver, setVer] = React.useState("18.2.0");
  return React.createElement(
    "section",
    null,
    React.createElement("h2", {{ id: "title" }}, "React"),
    React.createElement("p", {{ id: "ver" }}, "Version: " + ver),
    React.createElement("button", {{ id: "up", onClick: () => setVer("19.0.0") }}, "Upgrade")
  );
}}
window.__root = ReactDOM.createRoot(document.getElementById("vdom"));
window.__root.render(React.createElement(Demo, null));
window.__titleNode = document.getElementById("title");
}})();
</script></body></html>""")
            page.click("#up")
            actual4 = page.evaluate("""() => ({
              sameTitleNode: document.getElementById("title") === window.__titleNode,
              updatedVersion: document.getElementById("ver").textContent,
              patchStats: window.__root.lastStats
            })""")
            expected4 = {
                "sameTitleNode": True,
                "updatedVersion": "Version: 19.0.0",
                "patchStats": {"created": 0, "removed": 0, "replaced": 0, "textUpdated": 1},
            }
            cases.append({
                "name": "vdom_minimal_dom_patch",
                "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-tutorial-lab/explore-tutorial.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:React

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip

下载课程关联工程包:React

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3191.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习