"""Offline Playwright Chromium lab for React Ch 40: Context + useReducer Global Favorites & Persistence."""
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")
HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>React Context + useReducer Favorites Lab</title>
<style>
.navbar { display: flex; justify-content: space-between; padding: 12px 20px; border-bottom: 1px solid #ddd; }
.fav-badge { background: #ef4444; color: #fff; border-radius: 12px; padding: 2px 10px; font-size: 13px; }
.card-link { display: block; border: 1px solid #ddd; padding: 12px; margin: 8px 0; text-decoration: none; color: #222; }
</style>
</head>
<body>
<div id="theme-ctx-root"></div>
<div id="blog-root"></div>
<script>
// 1. Minimal createContext / Provider / useContext runtime
function createContext(defaultValue) {
return { _currentValue: defaultValue };
}
function useContext(ctx) {
return ctx._currentValue;
}
// Pure favoriteReducer matching chapter code
function favoriteReducer(state, action) {
switch (action.type) {
case "TOGGLE":
if (state.includes(action.id)) {
return state.filter((id) => id !== action.id);
} else {
return [...state, action.id];
}
case "CLEAR":
return [];
default:
return state;
}
}
// Case 1 helper: ThemeContext skipping 3 intermediate layers + Provider guard check
const ThemeContext = createContext(null);
const FavoriteContext = createContext(null);
function useFavorites() {
const ctx = useContext(FavoriteContext);
if (!ctx) throw new Error("useFavorites 必须在 FavoriteProvider 内部使用");
return ctx;
}
window.runContextAndGuardCheck = () => {
// Guard check outside Provider
let outsideError = null;
try {
useFavorites();
} catch (err) {
outsideError = err.message;
}
// Deeply nested ThemeContext broadcast A -> B -> C -> ThemedButton
let theme = "light";
const toggleTheme = () => { theme = theme === "light" ? "dark" : "light"; renderThemeTree(); };
function ThemedButton() {
const ctx = useContext(ThemeContext);
const btn = document.createElement("button");
btn.id = "theme-ctx-btn";
btn.textContent = `当前主题:${ctx.theme}`;
btn.addEventListener("click", ctx.toggleTheme);
return btn;
}
function LayerC() { const d = document.createElement("div"); d.appendChild(ThemedButton()); return d; }
function LayerB() { const d = document.createElement("div"); d.appendChild(LayerC()); return d; }
function LayerA() { const d = document.createElement("div"); d.appendChild(LayerB()); return d; }
function renderThemeTree() {
ThemeContext._currentValue = { theme, toggleTheme };
document.getElementById("theme-ctx-root").replaceChildren(LayerA());
}
renderThemeTree();
const initialLabel = document.getElementById("theme-ctx-btn").textContent;
document.getElementById("theme-ctx-btn").click();
const toggledLabel = document.getElementById("theme-ctx-btn").textContent;
return { outsideError, initialLabel, toggledLabel };
};
// Case 2 helper: Pure useReducer dispatch transitions
window.runReducerUnitCheck = () => {
let st = [];
const s1 = favoriteReducer(st, { type: "TOGGLE", id: 1 });
const s2 = favoriteReducer(s1, { type: "TOGGLE", id: 2 });
const s3 = favoriteReducer(s2, { type: "TOGGLE", id: 1 });
const sUnknown = favoriteReducer(s3, { type: "NOOP" });
const s4 = favoriteReducer(s3, { type: "CLEAR" });
return {
afterAdd1: s1,
afterAdd2: s2,
afterRemove1: s3,
unknownPreservesRef: sUnknown === s3,
afterClear: s4
};
};
// Cases 3 & 4: Integrated FavoriteProvider wrapping Router (NavBar + HomePage/BlogCard + PostPage)
const ARTICLES = [
{ id: 1, title: "React 入门完全指南", summary: "从零学 React Hooks", category: "React", date: "2024-05-10" },
{ id: 2, title: "JS 异步编程详解", summary: "搞懂 Promise 与异步", category: "JavaScript", date: "2024-05-08" },
{ id: 3, title: "CSS Grid 布局实战", summary: "掌握二维网格布局", category: "CSS", date: "2024-05-05" }
];
let favoriteIds = (() => {
const saved = localStorage.getItem("blog-favorites");
return saved ? JSON.parse(saved) : [];
})();
let currentPath = "/";
function dispatchFavorite(action) {
favoriteIds = favoriteReducer(favoriteIds, action);
localStorage.setItem("blog-favorites", JSON.stringify(favoriteIds));
renderBlog();
}
function renderNavBar() {
const { favoriteCount } = useFavorites();
const header = document.createElement("header");
header.className = "navbar";
const badge = favoriteCount > 0 ? `<span id="nav-fav-badge" class="fav-badge">收藏 ${favoriteCount}</span>` : "";
header.innerHTML = `<span class="logo">BlueSky Blog</span><nav><a id="nav-home" href="/">首页</a> ${badge}</nav>`;
header.querySelector("#nav-home").addEventListener("click", (e) => {
e.preventDefault();
currentPath = "/";
renderBlog();
});
return header;
}
function renderBlogCard(article) {
const { isFavorite, toggleFavorite } = useFavorites();
const link = document.createElement("a");
link.href = `/post/${article.id}`;
link.className = "card-link";
link.dataset.id = String(article.id);
link.innerHTML = `<h3>${article.title}</h3><p>${article.summary}</p>`;
const btn = document.createElement("button");
btn.className = "fav-btn";
btn.dataset.favId = String(article.id);
btn.textContent = isFavorite(article.id) ? "♥" : "♡";
btn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
toggleFavorite(article.id);
});
link.appendChild(btn);
link.addEventListener("click", (e) => {
e.preventDefault();
currentPath = `/post/${article.id}`;
renderBlog();
});
return link;
}
function renderPostPage(id) {
const { isFavorite, toggleFavorite } = useFavorites();
const article = ARTICLES.find((a) => a.id === Number(id));
const art = document.createElement("article");
art.className = "post-view";
art.innerHTML = `<h1>${article.title}</h1>`;
const btn = document.createElement("button");
btn.id = "post-fav-btn";
btn.textContent = isFavorite(article.id) ? "♥ 已收藏" : "♡ 收藏";
btn.addEventListener("click", () => toggleFavorite(article.id));
art.appendChild(btn);
return art;
}
function renderBlog() {
FavoriteContext._currentValue = {
favoriteIds,
favoriteCount: favoriteIds.length,
toggleFavorite: (id) => dispatchFavorite({ type: "TOGGLE", id }),
isFavorite: (id) => favoriteIds.includes(id)
};
const root = document.getElementById("blog-root");
const app = document.createElement("div");
app.appendChild(renderNavBar());
const main = document.createElement("main");
if (currentPath === "/") {
ARTICLES.forEach((a) => main.appendChild(renderBlogCard(a)));
} else {
const id = currentPath.split("/")[2];
main.appendChild(renderPostPage(id));
}
app.appendChild(main);
root.replaceChildren(app);
}
window.getCurrentPath = () => currentPath;
window.mountFavoriteApp = () => renderBlog();
</script>
</body>
</html>
"""
class LabHandler(BaseHTTPRequestHandler):
def do_GET(self):
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)
def log_message(self, format, *args):
return
def main():
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}/")
# Case 1: Context broadcast skipping intermediate layers + guard outside Provider
c1_actual = page.evaluate("() => window.runContextAndGuardCheck()")
c1_expected = {
"outsideError": "useFavorites 必须在 FavoriteProvider 内部使用",
"initialLabel": "当前主题:light",
"toggledLabel": "当前主题:dark",
}
cases.append({
"name": "context_provider_broadcast_and_guard",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
})
# Case 2: Pure reducer transitions
c2_actual = page.evaluate("() => window.runReducerUnitCheck()")
c2_expected = {
"afterAdd1": [1],
"afterAdd2": [1, 2],
"afterRemove1": [2],
"unknownPreservesRef": True,
"afterClear": [],
}
cases.append({
"name": "usereducer_toggle_and_clear",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
})
# Case 3: Cross-component sync across BlogCard, PostPage, and NavBar
page.evaluate("() => window.mountFavoriteApp()")
badge_init = page.locator("#nav-fav-badge").count()
# Click favorite button inside BlogCard #1 -> preventDefault keeps route at '/'
page.locator('button.fav-btn[data-fav-id="1"]').click()
path_after_card_fav = page.evaluate("() => window.getCurrentPath()")
card1_icon = page.locator('button.fav-btn[data-fav-id="1"]').inner_text()
nav_badge_1 = page.locator("#nav-fav-badge").inner_text()
# Open PostPage #1 -> should show "♥ 已收藏"
page.locator('.card-link[data-id="1"] h3').click()
post_btn_fav = page.locator("#post-fav-btn").inner_text()
# Unfavorite on PostPage -> hides NavBar badge
page.locator("#post-fav-btn").click()
post_btn_unfav = page.locator("#post-fav-btn").inner_text()
badge_after_unfav = page.locator("#nav-fav-badge").count()
c3_actual = {
"badge_init": badge_init,
"path_after_card_fav": path_after_card_fav,
"card1_icon": card1_icon,
"nav_badge_1": nav_badge_1,
"post_btn_fav": post_btn_fav,
"post_btn_unfav": post_btn_unfav,
"badge_after_unfav": badge_after_unfav,
}
c3_expected = {
"badge_init": 0,
"path_after_card_fav": "/",
"card1_icon": "♥",
"nav_badge_1": "收藏 1",
"post_btn_fav": "♥ 已收藏",
"post_btn_unfav": "♡ 收藏",
"badge_after_unfav": 0,
}
cases.append({
"name": "favorites_cross_component_sync",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
})
# Case 4: localStorage persistence across full page reload
page.locator("#nav-home").click()
page.locator('button.fav-btn[data-fav-id="1"]').click()
page.locator('button.fav-btn[data-fav-id="3"]').click()
stored_json = page.evaluate("() => localStorage.getItem('blog-favorites')")
page.reload()
page.evaluate("() => window.mountFavoriteApp()")
reloaded_badge = page.locator("#nav-fav-badge").inner_text()
reloaded_card1 = page.locator('button.fav-btn[data-fav-id="1"]').inner_text()
reloaded_card2 = page.locator('button.fav-btn[data-fav-id="2"]').inner_text()
reloaded_card3 = page.locator('button.fav-btn[data-fav-id="3"]').inner_text()
c4_actual = {
"stored_json": stored_json,
"reloaded_badge": reloaded_badge,
"reloaded_icons": [reloaded_card1, reloaded_card2, reloaded_card3],
}
c4_expected = {
"stored_json": "[1,3]",
"reloaded_badge": "收藏 2",
"reloaded_icons": ["♥", "♡", "♥"],
}
cases.append({
"name": "favorites_localstorage_reload_persistence",
"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-context-reducer-lab/explore-blog-context-reducer.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-blog-context-reducer.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3153.zip