"""Offline Playwright Chromium verification for React Ch29 (tailwind)."""
import json
import re
from playwright.sync_api import sync_playwright
def launch_browser(p):
for kwargs in (
dict(headless=True),
dict(headless=True, channel="chrome"),
dict(headless=True, channel="msedge"),
):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No Chromium/Chrome/Edge browser executable available")
TAILWIND_UTILITY_CSS = """
*, ::before, ::after { box-sizing: border-box; border: 0 solid #e5e7eb; }
body { margin: 0; font-family: system-ui, -apple-system, sans-serif; }
.min-h-screen { min-height: 100vh; }
.bg-gray-100 { background-color: rgb(243, 244, 246); }
.bg-white { background-color: rgb(255, 255, 255); }
.bg-blue-500 { background-color: rgb(59, 130, 246); }
.bg-emerald-600 { background-color: rgb(5, 150, 105); }
.hover\\:bg-blue-700:hover { background-color: rgb(29, 78, 216); }
.flex { display: flex; }
.items-center { align-items: center; }
.justify-center { justify-content: center; }
.p-8 { padding: 32px; }
.py-2 { padding-top: 8px; padding-bottom: 8px; }
.px-4 { padding-left: 16px; padding-right: 16px; }
.mt-4 { margin-top: 16px; }
.mt-6 { margin-top: 24px; }
.rounded { border-radius: 4px; }
.rounded-lg { border-radius: 8px; }
.shadow-lg { box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1); }
.text-2xl { font-size: 24px; line-height: 32px; }
.font-bold { font-weight: 700; }
.text-gray-900 { color: rgb(17, 24, 39); }
.text-gray-600 { color: rgb(75, 85, 99); }
.text-white { color: rgb(255, 255, 255); }
"""
def case_tailwind_card_utility_layout_and_typography(page):
html = f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TAILWIND_UTILITY_CSS}</style></head>
<body>
<div id="shell" class="min-h-screen bg-gray-100 flex items-center justify-center">
<div id="card" class="bg-white p-8 rounded-lg shadow-lg">
<h1 id="title" class="text-2xl font-bold text-gray-900">Hello, React + Tailwind!</h1>
<p id="desc" class="mt-4 text-gray-600">实用工具优先样式在 JSX className 中直接组合。</p>
<button id="cta" class="mt-6 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-700">点我试试</button>
</div>
</div>
</body></html>"""
page.set_content(html)
actual = page.evaluate("""() => {
const shell = getComputedStyle(document.getElementById('shell'));
const card = getComputedStyle(document.getElementById('card'));
const title = getComputedStyle(document.getElementById('title'));
const btn = getComputedStyle(document.getElementById('cta'));
return {
shellDisplay: shell.display,
shellAlign: shell.alignItems,
shellJustify: shell.justifyContent,
shellBg: shell.backgroundColor,
cardPadding: card.paddingTop,
cardRadius: card.borderTopLeftRadius,
titleSize: title.fontSize,
titleWeight: title.fontWeight,
btnBg: btn.backgroundColor,
btnPadY: btn.paddingTop,
btnPadX: btn.paddingLeft,
};
}""")
expected = {
"shellDisplay": "flex",
"shellAlign": "center",
"shellJustify": "center",
"shellBg": "rgb(243, 244, 246)",
"cardPadding": "32px",
"cardRadius": "8px",
"titleSize": "24px",
"titleWeight": "700",
"btnBg": "rgb(59, 130, 246)",
"btnPadY": "8px",
"btnPadX": "16px",
}
return dict(name="tailwind_card_utility_layout_and_typography", expected=expected, actual=actual, passed=(actual == expected))
def case_tailwind_hover_state_and_dynamic_classname(page):
html = f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TAILWIND_UTILITY_CSS}</style></head>
<body>
<div id="root"></div>
<script>
let active = false;
function render() {{
const cls = active
? 'mt-6 bg-emerald-600 text-white py-2 px-4 rounded'
: 'mt-6 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-700';
document.getElementById('root').innerHTML = `<button id="cta" class="${{cls}}">点我试试</button>`;
document.getElementById('cta').addEventListener('click', () => {{
active = !active;
render();
}});
}}
render();
</script>
</body></html>"""
page.set_content(html)
normal_bg = page.evaluate("getComputedStyle(document.getElementById('cta')).backgroundColor")
page.hover("#cta")
hover_bg = page.evaluate("getComputedStyle(document.getElementById('cta')).backgroundColor")
page.click("#cta")
clicked_bg = page.evaluate("getComputedStyle(document.getElementById('cta')).backgroundColor")
actual = {"normalBg": normal_bg, "hoverBg": hover_bg, "clickedBg": clicked_bg}
expected = {
"normalBg": "rgb(59, 130, 246)",
"hoverBg": "rgb(29, 78, 216)",
"clickedBg": "rgb(5, 150, 105)",
}
return dict(name="tailwind_hover_state_and_dynamic_classname", expected=expected, actual=actual, passed=(actual == expected))
def case_tailwind_content_scan_tree_shaking_model(page):
jsx_source = """
const App = () => (
<div className="min-h-screen bg-gray-100 flex items-center justify-center">
<div className="bg-white p-8 rounded-lg shadow-lg">
<h1 className="text-2xl font-bold text-gray-900">Title</h1>
<button className={`bg-${color}-500 text-white`}>Go</button>
</div>
</div>
);
"""
catalog = [
"min-h-screen", "bg-gray-100", "flex", "items-center", "justify-center",
"bg-white", "p-8", "rounded-lg", "shadow-lg", "text-2xl", "font-bold",
"text-gray-900", "text-white", "bg-red-500", "bg-purple-500", "p-2", "mt-10", "hidden"
]
tokens = set(re.findall(r"[a-zA-Z0-9_:/-]+", jsx_source))
kept = [c for c in catalog if c in tokens]
pruned = [c for c in catalog if c not in tokens]
actual = {
"catalogCount": len(catalog),
"keptCount": len(kept),
"prunedCount": len(pruned),
"dynamicBgRedDetected": "bg-red-500" in kept,
"textWhiteDetected": "text-white" in kept,
}
expected = {
"catalogCount": 18,
"keptCount": 13,
"prunedCount": 5,
"dynamicBgRedDetected": False,
"textWhiteDetected": True,
}
return dict(name="tailwind_content_scan_tree_shaking_model", expected=expected, actual=actual, passed=(actual == expected))
def main():
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page()
cases = [
case_tailwind_card_utility_layout_and_typography(page),
case_tailwind_hover_state_and_dynamic_classname(page),
case_tailwind_content_scan_tree_shaking_model(page),
]
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-tailwind-lab/explore-tailwind.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tailwind.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3190.zip
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip