"""Offline Playwright Chromium lab for React Ch 36: Client-side Router, Outlet, Link, useParams & useNavigate."""
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 Router v6 Offline Lab</title>
<style>
.post-view { max-width: 720px; margin: 0 auto; }
.category-tag { display: inline-block; padding: 4px 12px; background: #e3f2fd; color: #1976d2; border-radius: 12px; }
.not-found { text-align: center; padding: 40px 0; }
.card-link { display: block; border: 1px solid #ddd; padding: 10px; margin: 8px 0; text-decoration: none; color: #222; }
</style>
</head>
<body>
<div id="root"></div>
<script>
window.__SPA_BOOT_ID = "BOOT-REACT-ROUTER-36";
window.__LAST_PARAMS = null;
const ARTICLES = [
{ id: 1, title: "React 入门完全指南", summary: "从零学 React", category: "React", date: "2024-05-10",
content: "<h2>为什么学 React?</h2><p>组件化与声明式 UI 是现代前端基石。</p>" },
{ id: 2, title: "JS 异步编程详解", summary: "搞懂 Promise 和 async/await", category: "JavaScript", date: "2024-05-08",
content: "<h2>什么是异步?</h2><p>事件循环与微任务让主线程保持响应。</p>" },
{ id: 3, title: "CSS Grid 布局实战", summary: "用 Grid 实现响应式布局", category: "CSS", date: "2024-05-05",
content: "<h2>Grid 入门</h2><p>二维网格系统简化复杂排版。</p>" }
];
// Route matching for BrowserRouter & HashRouter patterns
function matchRoute(pathname) {
if (pathname === "/" || pathname === "") return { route: "home", params: {} };
const m = pathname.match(/^\/post\/([^/]+)$/);
if (m) return { route: "post", params: { id: m[1] } };
return { route: "404", params: {} };
}
function navigate(to) {
window.history.pushState({}, "", to);
renderRouter();
}
function createLink(to, className, contentNodeOrHtml) {
const a = document.createElement("a");
a.href = to;
if (className) a.className = className;
if (typeof contentNodeOrHtml === "string") a.innerHTML = contentNodeOrHtml;
else a.appendChild(contentNodeOrHtml);
a.addEventListener("click", (e) => {
e.preventDefault();
navigate(to);
});
return a;
}
function renderHomePage() {
const wrap = document.createElement("div");
wrap.id = "home-page";
wrap.innerHTML = `<h2 class="section-title">最新文章</h2>`;
const grid = document.createElement("div");
grid.className = "article-grid";
ARTICLES.forEach((a) => {
const card = createLink(`/post/${a.id}`, "card-link",
`<div class="card" data-id="${a.id}"><span class="tag">${a.category}</span><h3>${a.title}</h3><p>${a.summary}</p></div>`);
grid.appendChild(card);
});
wrap.appendChild(grid);
return wrap;
}
function renderPostPage(params) {
// useParams() returns string parameters
window.__LAST_PARAMS = { rawId: params.id, typeofId: typeof params.id, numericId: Number(params.id) };
const article = ARTICLES.find((a) => a.id === Number(params.id));
if (!article) {
const nf = document.createElement("div");
nf.className = "not-found";
nf.innerHTML = `<h2>文章不存在</h2><p>找不到 ID 为 ${params.id} 的文章</p>`;
const backBtn = document.createElement("button");
backBtn.id = "btn-nav-home";
backBtn.textContent = "编程式返回首页";
backBtn.addEventListener("click", () => navigate("/"));
nf.appendChild(backBtn);
return nf;
}
const art = document.createElement("article");
art.className = "post-view";
art.innerHTML = `
<span class="category-tag">${article.category}</span>
<h1>${article.title}</h1>
<time>${article.date}</time>
<div class="content">${article.content}</div>`;
art.appendChild(createLink("/", "back-link", "← 返回首页"));
return art;
}
function renderRouter() {
const effectivePath = window.location.hash.startsWith("#/")
? window.location.hash.slice(1)
: window.location.pathname;
const matched = matchRoute(effectivePath);
const root = document.getElementById("root");
// Preserve outer layout shell (App + NavBar + Outlet)
if (!document.getElementById("outlet")) {
root.innerHTML = `<div class="app"><header class="navbar"><span class="logo">BlueSky Blog</span></header><main id="outlet" class="container"></main><footer class="footer">© 2026 BlueSky Blog</footer></div>`;
}
const outlet = document.getElementById("outlet");
if (matched.route === "home") outlet.replaceChildren(renderHomePage());
else if (matched.route === "post") outlet.replaceChildren(renderPostPage(matched.params));
else {
const nf = document.createElement("div");
nf.className = "not-found";
nf.innerHTML = `<h2>404 页面不存在</h2>`;
outlet.replaceChildren(nf);
}
}
window.addEventListener("popstate", renderRouter);
window.addEventListener("hashchange", renderRouter);
window.navTo = navigate;
renderRouter();
</script>
</body>
</html>
"""
class SpaHandler(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), SpaHandler)
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()
base = f"http://127.0.0.1:{port}"
page.goto(base + "/")
# Case 1: Link navigation + Outlet swap without page reload + Hash fallback
boot_before = page.evaluate("() => window.__SPA_BOOT_ID")
page.locator('.card-link[href="/post/1"]').click()
url_after_click = page.evaluate("() => window.location.pathname")
boot_after = page.evaluate("() => window.__SPA_BOOT_ID")
post_title = page.locator(".post-view h1").inner_text()
navbar_persisted = page.locator(".navbar .logo").inner_text()
# Test hash router path resolution without reload
page.evaluate("() => { window.location.hash = '#/post/2'; }")
hash_title = page.locator(".post-view h1").inner_text()
page.evaluate("() => { window.location.hash = ''; window.navTo('/post/1'); }")
c1_actual = {
"url_after_click": url_after_click,
"same_document": boot_before == boot_after,
"post_title": post_title,
"navbar_persisted": navbar_persisted,
"hash_title": hash_title,
}
c1_expected = {
"url_after_click": "/post/1",
"same_document": True,
"post_title": "React 入门完全指南",
"navbar_persisted": "BlueSky Blog",
"hash_title": "JS 异步编程详解",
}
cases.append({
"name": "spa_history_link_and_outlet",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
})
# Case 2: useParams string type & Number(id) lookup + HTML content render
params_info = page.evaluate("() => window.__LAST_PARAMS")
content_h2 = page.locator(".post-view .content h2").inner_text()
post_max_w = page.locator(".post-view").evaluate("el => getComputedStyle(el).maxWidth")
c2_actual = {
"rawId": params_info["rawId"],
"typeofId": params_info["typeofId"],
"numericId": params_info["numericId"],
"content_h2": content_h2,
"post_max_w": post_max_w,
}
c2_expected = {
"rawId": "1",
"typeofId": "string",
"numericId": 1,
"content_h2": "为什么学 React?",
"post_max_w": "720px",
}
cases.append({
"name": "useparams_string_to_number",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
})
# Case 3: Missing article 404 branch & useNavigate programmatic redirect
page.evaluate("() => window.navTo('/post/999')")
nf_heading = page.locator(".not-found h2").inner_text()
nf_msg = page.locator(".not-found p").inner_text()
page.locator("#btn-nav-home").click()
back_path = page.evaluate("() => window.location.pathname")
home_cards = page.locator("#home-page .card").count()
c3_actual = {
"nf_heading": nf_heading,
"nf_msg": nf_msg,
"back_path": back_path,
"home_cards": home_cards,
"still_same_doc": page.evaluate("() => window.__SPA_BOOT_ID") == boot_before,
}
c3_expected = {
"nf_heading": "文章不存在",
"nf_msg": "找不到 ID 为 999 的文章",
"back_path": "/",
"home_cards": 3,
"still_same_doc": True,
}
cases.append({
"name": "not_found_and_usenavigate",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
})
# Case 4: Back link & browser history popstate navigation
page.locator('.card-link[href="/post/3"]').click()
p3_title = page.locator(".post-view h1").inner_text()
page.go_back()
restored_path = page.evaluate("() => window.location.pathname")
restored_section = page.locator("#home-page .section-title").inner_text()
c4_actual = {
"p3_title": p3_title,
"restored_path": restored_path,
"restored_section": restored_section,
}
c4_expected = {
"p3_title": "CSS Grid 布局实战",
"restored_path": "/",
"restored_section": "最新文章",
}
cases.append({
"name": "browser_back_popstate_navigation",
"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-router-lab/explore-blog-router.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-blog-router.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3158.zip