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

离线 Chromium 实测 usePosts 独立实例复用、useDarkMode CSS 变量+刷新持久化与 Hook 顺序守卫

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-blog-custom-hooks.py
explore-blog-custom-hooks.py347 行
"""Offline Playwright Chromium lab for React Ch 39: Custom Hooks (usePosts, useDarkMode, Hook Rules)."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from playwright.sync_api import sync_playwright


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


POSTS_JSON = json.dumps([
    {"id": 1, "title": "React 入门完全指南", "summary": "学习 React Hooks 核心概念", "category": "React", "date": "2024-05-10"},
    {"id": 2, "title": "JavaScript 异步编程详解", "summary": "理解 Promise 与微任务", "category": "JavaScript", "date": "2024-05-08"},
    {"id": 3, "title": "CSS Grid 布局实战", "summary": "用 Grid 实现响应式网格", "category": "CSS", "date": "2024-05-05"},
], ensure_ascii=False).encode("utf-8")


HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>React Custom Hooks Lab</title>
<style>
:root {
  --bg-primary: #f5f5f5;
  --bg-card: #ffffff;
  --text-primary: #333333;
  --border-color: #eeeeee;
}
html.dark {
  --bg-primary: #1a1a2e;
  --bg-card: #16213e;
  --text-primary: #e0e0e0;
  --border-color: #2a2a4a;
}
body { background: var(--bg-primary); color: var(--text-primary); font-family: system-ui, sans-serif; }
.article-card { background: var(--bg-card); border: 1px solid var(--border-color); padding: 10px; margin: 6px 0; }
</style>
</head>
<body>
  <header class="navbar">
    <span class="logo">BlueSky Blog</span>
    <button id="theme-btn" class="theme-btn"></button>
  </header>
  <main>
    <input id="home-search" placeholder="搜索..." />
    <div id="home-cats"></div>
    <p id="home-count"></p>
    <div id="home-list"></div>
    <hr />
    <div id="post-detail"></div>
  </main>

<script>
// Independent custom hook factory: each call creates its own state & fetch lifecycle
function createUsePostsInstance(onUpdate) {
  const state = {
    articles: [],
    isLoading: true,
    error: null,
    activeCategory: "全部",
    keyword: ""
  };

  fetch("/posts.json")
    .then((r) => {
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      return r.json();
    })
    .then((data) => {
      state.articles = data;
      state.isLoading = false;
      onUpdate();
    })
    .catch((err) => {
      state.error = err.message;
      state.isLoading = false;
      onUpdate();
    });

  return {
    getState: () => state,
    setActiveCategory: (cat) => { state.activeCategory = cat; onUpdate(); },
    setKeyword: (kw) => { state.keyword = kw; onUpdate(); },
    getCategories: () => ["全部", ...new Set(state.articles.map((a) => a.category))],
    getFilteredArticles: () => {
      let list = state.articles;
      if (state.activeCategory !== "全部") list = list.filter((a) => a.category === state.activeCategory);
      if (state.keyword.trim()) {
        const kw = state.keyword.trim().toLowerCase();
        list = list.filter((a) => a.title.toLowerCase().includes(kw) || a.summary.toLowerCase().includes(kw));
      }
      return list;
    },
    getArticleById: (id) => state.articles.find((a) => a.id === Number(id)) || null
  };
}

// Custom hook: useDarkMode synced with html.dark and localStorage('blog-theme')
let isDark = localStorage.getItem("blog-theme") === "dark";
function syncDarkMode() {
  if (isDark) {
    document.documentElement.classList.add("dark");
    localStorage.setItem("blog-theme", "dark");
  } else {
    document.documentElement.classList.remove("dark");
    localStorage.setItem("blog-theme", "light");
  }
  document.getElementById("theme-btn").textContent = isDark ? "☀ 亮色" : "☾ 暗黑";
}
document.getElementById("theme-btn").addEventListener("click", () => {
  isDark = !isDark;
  syncDarkMode();
});
syncDarkMode();

// Mount two independent instances of usePosts(): HomePage and PostPage
const homePosts = createUsePostsInstance(renderHome);
const detailPosts = createUsePostsInstance(renderDetail);

function renderHome() {
  const st = homePosts.getState();
  const listEl = document.getElementById("home-list");
  const catsEl = document.getElementById("home-cats");
  const countEl = document.getElementById("home-count");
  if (st.isLoading) {
    countEl.textContent = "加载中...";
    return;
  }
  catsEl.innerHTML = "";
  homePosts.getCategories().forEach((cat) => {
    const b = document.createElement("button");
    b.dataset.cat = cat;
    b.textContent = cat;
    b.addEventListener("click", () => homePosts.setActiveCategory(cat));
    catsEl.appendChild(b);
  });
  const filtered = homePosts.getFilteredArticles();
  countEl.textContent = `共 ${filtered.length} 篇`;
  listEl.innerHTML = "";
  filtered.forEach((a) => {
    const div = document.createElement("div");
    div.className = "article-card";
    div.textContent = a.title;
    listEl.appendChild(div);
  });
}

function renderDetail() {
  const st = detailPosts.getState();
  const box = document.getElementById("post-detail");
  if (st.isLoading) {
    box.textContent = "详情加载中...";
    return;
  }
  const art = detailPosts.getArticleById("2");
  box.textContent = art ? `详情页:${art.title}` : "文章不存在";
}

document.getElementById("home-search").addEventListener("input", (e) => {
  homePosts.setKeyword(e.target.value);
});

window.getHomeArticleById1 = () => {
  const a = homePosts.getArticleById("1");
  return a ? a.title : null;
};

// Hook Rules demonstration: conditional Hook call violates call-order invariant
window.runHookOrderGuardCheck = () => {
  const expectedTypes = ["useState", "useEffect", "useMemo"];
  function simulateRender(callOrder) {
    if (callOrder.length !== expectedTypes.length) {
      return { ok: false, reason: "Hook count mismatch across renders" };
    }
    for (let i = 0; i < expectedTypes.length; i++) {
      if (callOrder[i] !== expectedTypes[i]) {
        return { ok: false, reason: `Hook order mismatch at slot ${i}` };
      }
    }
    return { ok: true, reason: "stable" };
  }
  return {
    topLevelRender: simulateRender(["useState", "useEffect", "useMemo"]),
    conditionalSkippedRender: simulateRender(["useEffect", "useMemo"])
  };
};
</script>
</body>
</html>
"""


def main():
    fetch_counter = {"count": 0}

    class LabHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            if self.path == "/":
                body = HTML.encode("utf-8")
                self.send_response(200)
                self.send_header("Content-Type", "text/html; charset=utf-8")
                self.send_header("Content-Length", str(len(body)))
                self.end_headers()
                self.wfile.write(body)
            elif self.path == "/posts.json":
                fetch_counter["count"] += 1
                self.send_response(200)
                self.send_header("Content-Type", "application/json; charset=utf-8")
                self.send_header("Content-Length", str(len(POSTS_JSON)))
                self.end_headers()
                self.wfile.write(POSTS_JSON)
            else:
                self.send_response(404)
                self.end_headers()

        def log_message(self, format, *args):
            return

    server = ThreadingHTTPServer(("127.0.0.1", 0), LabHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            page = browser.new_page()
            page.goto(f"http://127.0.0.1:{port}/")
            page.locator("#home-list .article-card").first.wait_for(state="visible", timeout=5000)
            page.wait_for_function("() => document.getElementById('post-detail').textContent.includes('JavaScript')", timeout=5000)

            # Case 1: Independent usePosts instances (each calls its own fetch, isolated state)
            initial_fetches = fetch_counter["count"]
            page.locator('#home-cats button[data-cat="React"]').click()
            home_filtered_count = page.locator("#home-count").inner_text()
            detail_unaffected = page.locator("#post-detail").inner_text()
            c1_actual = {
                "initial_fetches": initial_fetches,
                "home_filtered_count": home_filtered_count,
                "detail_unaffected": detail_unaffected,
            }
            c1_expected = {
                "initial_fetches": 2,
                "home_filtered_count": "共 1 篇",
                "detail_unaffected": "详情页:JavaScript 异步编程详解",
            }
            cases.append({
                "name": "useposts_independent_instances",
                "expected": c1_expected,
                "actual": c1_actual,
                "passed": c1_actual == c1_expected,
            })

            # Case 2: usePosts categories, search, and getArticleById
            page.locator('#home-cats button[data-cat="CSS"]').click()
            page.locator("#home-search").fill("Grid")
            css_grid_titles = page.locator("#home-list .article-card").all_inner_texts()
            by_id_1 = page.evaluate("() => window.getHomeArticleById1()")
            cats = page.locator("#home-cats button").all_inner_texts()
            c2_actual = {
                "categories": cats,
                "css_grid_titles": css_grid_titles,
                "by_id_1": by_id_1,
            }
            c2_expected = {
                "categories": ["全部", "React", "JavaScript", "CSS"],
                "css_grid_titles": ["CSS Grid 布局实战"],
                "by_id_1": "React 入门完全指南",
            }
            cases.append({
                "name": "useposts_search_and_category",
                "expected": c2_expected,
                "actual": c2_actual,
                "passed": c2_actual == c2_expected,
            })

            # Case 3: useDarkMode CSS variables + localStorage persistence across reload
            light_bg = page.evaluate("() => getComputedStyle(document.body).backgroundColor")
            light_btn = page.locator("#theme-btn").inner_text()
            page.locator("#theme-btn").click()
            dark_has_class = page.evaluate("() => document.documentElement.classList.contains('dark')")
            dark_bg = page.evaluate("() => getComputedStyle(document.body).backgroundColor")
            dark_card_bg = page.locator("#home-list .article-card").first.evaluate(
                "el => getComputedStyle(el).backgroundColor"
            )
            dark_storage = page.evaluate("() => localStorage.getItem('blog-theme')")
            page.reload()
            page.locator("#home-list .article-card").first.wait_for(state="visible", timeout=5000)
            after_reload_dark = page.evaluate("() => document.documentElement.classList.contains('dark')")
            after_reload_btn = page.locator("#theme-btn").inner_text()
            c3_actual = {
                "light_bg": light_bg,
                "light_btn": light_btn,
                "dark_has_class": dark_has_class,
                "dark_bg": dark_bg,
                "dark_card_bg": dark_card_bg,
                "dark_storage": dark_storage,
                "after_reload_dark": after_reload_dark,
                "after_reload_btn": after_reload_btn,
            }
            c3_expected = {
                "light_bg": "rgb(245, 245, 245)",
                "light_btn": "☾ 暗黑",
                "dark_has_class": True,
                "dark_bg": "rgb(26, 26, 46)",
                "dark_card_bg": "rgb(22, 33, 62)",
                "dark_storage": "dark",
                "after_reload_dark": True,
                "after_reload_btn": "☀ 亮色",
            }
            cases.append({
                "name": "usedarkmode_css_vars_and_reload",
                "expected": c3_expected,
                "actual": c3_actual,
                "passed": c3_actual == c3_expected,
            })

            # Case 4: Rules of Hooks call-order invariant check
            c4_actual = page.evaluate("() => window.runHookOrderGuardCheck()")
            c4_expected = {
                "topLevelRender": {"ok": True, "reason": "stable"},
                "conditionalSkippedRender": {"ok": False, "reason": "Hook count mismatch across renders"},
            }
            cases.append({
                "name": "hook_rules_call_order_guard",
                "expected": c4_expected,
                "actual": c4_actual,
                "passed": c4_actual == c4_expected,
            })

            browser.close()
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/react-blog-custom-hooks-lab/explore-blog-custom-hooks.py

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

下载课程关联工程包:React

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

下载课程关联工程包:React

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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