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

在离线 Chromium 中验证在线生成风格的 React 多模块目录、Payload 编码与组件状态联动

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-online.py
explore-online.py228 行
"""Offline Playwright Chromium lab for React Ch 08 (online)."""
from __future__ import annotations

import json
from playwright.sync_api import sync_playwright

MICRO_REACT_JS = r"""
const 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 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.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 };
})();
const 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: Online-generated Vite 5 + React 18 multi-module skeleton verification
            project_files = [
                "index.html",
                "package.json",
                "vite.config.js",
                "src/main.jsx",
                "src/App.jsx",
                "src/index.css",
                "src/components/Controls.jsx",
                "src/components/Preview.jsx",
                "src/utils/payload.js",
            ]
            actual1 = {
                "fileCount": len(project_files),
                "hasComponentsDir": any(f.startswith("src/components/") for f in project_files),
                "hasUtilsDir": any(f.startswith("src/utils/") for f in project_files),
                "defaultPort": 5173,
            }
            expected1 = {
                "fileCount": 9,
                "hasComponentsDir": True,
                "hasUtilsDir": True,
                "defaultPort": 5173,
            }
            cases.append({
                "name": "online_generated_project_layout",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Case 2: buildPayload utility across text, url, wifi, mailto modes
            page.set_content("""<!DOCTYPE html>
<html><body><script>
function buildPayload(mode, data) {
  if (mode === "url") {
    const raw = (data.url || "").trim();
    return /^https?:\\/\\//i.test(raw) ? raw : "https://" + raw;
  }
  if (mode === "wifi") {
    return "WIFI:T:" + (data.auth || "WPA") + ";S:" + data.ssid + ";P:" + data.password + ";;";
  }
  if (mode === "email") {
    return "mailto:" + data.to + "?subject=" + encodeURIComponent(data.subject || "");
  }
  return data.text || "";
}
window.__payloads = {
  text: buildPayload("text", { text: "Hello React" }),
  urlAutoHttps: buildPayload("url", { url: "example.com" }),
  wifi: buildPayload("wifi", { auth: "WPA", ssid: "LabNet", password: "pass123" }),
  email: buildPayload("email", { to: "dev@example.com", subject: "QR" })
};
</script></body></html>""")
            actual2 = page.evaluate("() => window.__payloads")
            expected2 = {
                "text": "Hello React",
                "urlAutoHttps": "https://example.com",
                "wifi": "WIFI:T:WPA;S:LabNet;P:pass123;;",
                "email": "mailto:dev@example.com?subject=QR",
            }
            cases.append({
                "name": "payload_builder_modes",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            # Case 3 & 4: Composed Controls + Preview React app with interactive mode/level switch
            page.set_content(f"""<!DOCTYPE html>
<html><body><div id="root"></div>
<script>{MICRO_REACT_JS}
const defaultStyle = {{ size: 280, fgColor: "#111827", bgColor: "#ffffff", level: "M", margin: 2 }};
function buildPayload(mode) {{
  if (mode === "wifi") return "WIFI:T:WPA;S:Studio;P:12345678;;";
  return "https://example.com";
}}
function Controls({{ mode, level, onModeChange, onLevelChange }}) {{
  return React.createElement(
    "section", {{ id: "controls" }},
    React.createElement("button", {{ id: "mode-url", onClick: () => onModeChange("url") }}, "网址"),
    React.createElement("button", {{ id: "mode-wifi", onClick: () => onModeChange("wifi") }}, "WiFi"),
    React.createElement("button", {{ id: "level-q", onClick: () => onLevelChange("Q") }}, "Q · 25%")
  );
}}
function Preview({{ payload, style }}) {{
  return React.createElement(
    "section", {{ id: "preview" }},
    React.createElement("p", {{ id: "meta" }}, style.size + " × " + style.size + " px · 容错 " + style.level + " · 边距 " + style.margin),
    React.createElement("code", {{ id: "encoded" }}, payload)
  );
}}
function App() {{
  const [mode, setMode] = React.useState("url");
  const [level, setLevel] = React.useState(defaultStyle.level);
  const style = Object.assign({{}}, defaultStyle, {{ level }});
  const payload = buildPayload(mode);
  return React.createElement(
    "div", null,
    React.createElement(Controls, {{ mode, level, onModeChange: setMode, onLevelChange: setLevel }}),
    React.createElement(Preview, {{ payload, style }})
  );
}}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(App, null));
</script></body></html>""")
            actual3 = {
                "meta": page.text_content("#meta"),
                "encoded": page.text_content("#encoded"),
            }
            expected3 = {
                "meta": "280 × 280 px · 容错 M · 边距 2",
                "encoded": "https://example.com",
            }
            cases.append({
                "name": "controls_and_preview_composition",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            page.click("#mode-wifi")
            page.click("#level-q")
            actual4 = {
                "meta": page.text_content("#meta"),
                "encoded": page.text_content("#encoded"),
            }
            expected4 = {
                "meta": "280 × 280 px · 容错 Q · 边距 2",
                "encoded": "WIFI:T:WPA;S:Studio;P:12345678;;",
            }
            cases.append({
                "name": "interactive_mode_and_style_update",
                "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-online-lab/explore-online.py

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

下载课程关联工程包:React

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

下载课程关联工程包:React

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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