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

离线 Chromium 核验原子类计算样式、响应式/悬停/暗色修饰符及按需裁剪

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-intro.py
explore-intro.py174 行
"""Offline Playwright Chromium lab for Tailwind CSS Ch 02 (intro)."""
import json
import os
import re
from playwright.sync_api import sync_playwright

TW_CSS = """
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; font-size: 16px; }
.bg-blue-500 { background-color: #3b82f6; }
.bg-blue-700 { background-color: #1d4ed8; }
.text-white { color: #ffffff; }
.text-center { text-align: center; }
.p-4 { padding: 1rem; }
.mt-4 { margin-top: 1rem; }
.rounded-lg { border-radius: 0.5rem; }
.hover\\:bg-blue-700:hover { background-color: #1d4ed8; }
.dark .dark\\:bg-slate-900 { background-color: #0f172a; }
.dark .dark\\:text-slate-100 { color: #f1f5f9; }
@media (min-width: 768px) {
  .md\\:p-8 { padding: 2rem; }
}
"""


def launch_browser(p):
    exe = p.chromium.executable_path
    if exe and os.path.exists(exe):
        return p.chromium.launch(headless=True)
    for ch in ("chrome", "msedge"):
        try:
            return p.chromium.launch(channel=ch, headless=True)
        except Exception:
            continue
    return p.chromium.launch(headless=True)


def run():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 600, "height": 600})

        # Case 1: Intro card atomic classes
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <div id="intro-card" class="bg-blue-500 text-white p-4 rounded-lg">
    Hello, Tailwind CSS!
  </div>
</body></html>""")
        actual1 = page.eval_on_selector("#intro-card", """el => {
            const s = getComputedStyle(el);
            return {
                backgroundColor: s.backgroundColor,
                color: s.color,
                padding: s.padding,
                borderRadius: s.borderRadius,
            };
        }""")
        expected1 = {
            "backgroundColor": "rgb(59, 130, 246)",
            "color": "rgb(255, 255, 255)",
            "padding": "16px",
            "borderRadius": "8px",
        }
        cases.append(dict(
            name="intro_card_atomic_classes",
            expected=expected1,
            actual=actual1,
            passed=(actual1 == expected1),
        ))

        # Case 2: Core utility classes text-center and mt-4
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <div id="banner" class="text-center mt-4">Utility First</div>
</body></html>""")
        actual2 = page.eval_on_selector("#banner", """el => {
            const s = getComputedStyle(el);
            return { textAlign: s.textAlign, marginTop: s.marginTop };
        }""")
        expected2 = {"textAlign": "center", "marginTop": "16px"}
        cases.append(dict(
            name="core_utility_text_and_spacing",
            expected=expected2,
            actual=actual2,
            passed=(actual2 == expected2),
        ))

        # Case 3: Responsive md:p-8, hover:bg-blue-700, dark:bg-slate-900
        page.set_content(f"""<!doctype html>
<html id="root"><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <button id="demo-btn" class="bg-blue-500 text-white p-4 md:p-8 rounded-lg hover:bg-blue-700 dark:bg-slate-900 dark:text-slate-100">
    Interactive Card
  </button>
</body></html>""")
        pad_600 = page.eval_on_selector("#demo-btn", "el => getComputedStyle(el).paddingTop")
        bg_default = page.eval_on_selector("#demo-btn", "el => getComputedStyle(el).backgroundColor")
        page.hover("#demo-btn")
        bg_hover = page.eval_on_selector("#demo-btn", "el => getComputedStyle(el).backgroundColor")
        page.mouse.move(0, 0)
        page.set_viewport_size({"width": 800, "height": 600})
        pad_800 = page.eval_on_selector("#demo-btn", "el => getComputedStyle(el).paddingTop")
        page.evaluate("document.documentElement.classList.add('dark')")
        dark_styles = page.eval_on_selector("#demo-btn", "el => ({ bg: getComputedStyle(el).backgroundColor, fg: getComputedStyle(el).color })")
        actual3 = {
            "padAt600": pad_600,
            "padAt800": pad_800,
            "bgDefault": bg_default,
            "bgHover": bg_hover,
            "darkBg": dark_styles["bg"],
            "darkColor": dark_styles["fg"],
        }
        expected3 = {
            "padAt600": "16px",
            "padAt800": "32px",
            "bgDefault": "rgb(59, 130, 246)",
            "bgHover": "rgb(29, 78, 216)",
            "darkBg": "rgb(15, 23, 42)",
            "darkColor": "rgb(241, 245, 249)",
        }
        cases.append(dict(
            name="responsive_hover_and_dark_modifiers",
            expected=expected3,
            actual=actual3,
            passed=(actual3 == expected3),
        ))

        # Case 4: On-demand utility pruning (tree-shaking unused rules)
        catalog = {
            "bg-blue-500": ".bg-blue-500{background-color:#3b82f6}",
            "bg-red-500": ".bg-red-500{background-color:#ef4444}",
            "bg-green-500": ".bg-green-500{background-color:#22c55e}",
            "text-white": ".text-white{color:#fff}",
            "text-black": ".text-black{color:#000}",
            "p-4": ".p-4{padding:1rem}",
            "p-8": ".p-8{padding:2rem}",
            "mt-4": ".mt-4{margin-top:1rem}",
            "rounded-lg": ".rounded-lg{border-radius:.5rem}",
            "shadow-lg": ".shadow-lg{box-shadow:0 10px 15px -3px rgb(0 0 0/.1)}",
        }
        html_src = '<div class="bg-blue-500 text-white p-4 rounded-lg">Hello, Tailwind CSS!</div>'
        used_tokens = sorted(set(re.findall(r'class="([^"]+)"', html_src)[0].split()))
        purged_css = "".join(catalog[t] for t in used_tokens if t in catalog)
        full_css = "".join(catalog.values())
        actual4 = {
            "totalDefined": len(catalog),
            "usedRetained": len(used_tokens),
            "usedTokens": used_tokens,
            "purgedSmaller": len(purged_css) < len(full_css),
        }
        expected4 = {
            "totalDefined": 10,
            "usedRetained": 4,
            "usedTokens": ["bg-blue-500", "p-4", "rounded-lg", "text-white"],
            "purgedSmaller": True,
        }
        cases.append(dict(
            name="atomic_utility_pruning",
            expected=expected4,
            actual=actual4,
            passed=(actual4 == expected4),
        ))

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


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

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

入口文件:projects/tailwindcss-intro-lab/explore-intro.py

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

下载课程关联工程包:Tailwind CSS

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

下载课程关联工程包:Tailwind CSS

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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