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

离线 Chromium 核验八类工具类计算值及 ChitChat 传统 CSS 与工具类卡片对比

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-utility-first.py
explore-utility-first.py288 行
"""Offline Playwright Chromium lab for Tailwind CSS Ch 08 (utility-first)."""
import json
import os
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; }
p, h1, h4 { margin: 0; }
.text-center { text-align: center; }
.text-lg { font-size: 1.125rem; line-height: 1.75rem; }
.text-xl { font-size: 1.25rem; line-height: 1.75rem; }
.font-medium { font-weight: 500; }
.font-bold { font-weight: 700; }
.text-red-500 { color: #ef4444; }
.text-white { color: #ffffff; }
.text-black { color: #000000; }
.text-slate-500 { color: #64748b; }
.bg-white { background-color: #ffffff; }
.bg-blue-500 { --tw-bg-opacity: 1; background-color: rgb(59 130 246 / var(--tw-bg-opacity)); }
.bg-opacity-50 { --tw-bg-opacity: 0.5; }
.bg-cover { background-size: cover; }
.p-4 { padding: 1rem; }
.p-6 { padding: 1.5rem; }
.m-8 { margin: 2rem; }
.mt-4 { margin-top: 1rem; }
.mx-auto { margin-left: auto; margin-right: auto; }
.max-w-sm { max-width: 24rem; }
.size-12 { width: 3rem; height: 3rem; }
.flex { display: flex; }
.shrink-0 { flex-shrink: 0; }
.items-center { align-items: center; }
.justify-between { justify-content: space-between; }
.gap-x-4 { column-gap: 1rem; }
.border { border-width: 1px; border-style: solid; border-color: #e5e7eb; }
.border-2 { border-width: 2px; border-style: solid; border-color: #e5e7eb; }
.rounded-lg { border-radius: 0.5rem; }
.rounded-xl { border-radius: 0.75rem; }
.shadow-lg { box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1); }
.hover\\:bg-blue-700:hover { background-color: #1d4ed8; }
.focus\\:outline-none:focus { outline: 2px solid transparent; outline-offset: 2px; }
.active\\:bg-red-500:active { background-color: #ef4444; }
@media (min-width: 640px) { .sm\\:bg-green-500 { background-color: #22c55e; } }
@media (min-width: 1024px) { .lg\\:bg-red-500 { background-color: #ef4444; } }

/* Traditional custom CSS for ChitChat comparison */
.chat-notification {
  display: flex;
  align-items: center;
  max-width: 24rem;
  margin: 0 auto;
  padding: 1.5rem;
  border-radius: 0.5rem;
  background-color: #fff;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}
.chat-notification-logo-wrapper { flex-shrink: 0; }
.chat-notification-logo { height: 3rem; width: 3rem; }
.chat-notification-content { margin-left: 1.5rem; }
.chat-notification-title { color: #1a202c; font-size: 1.25rem; line-height: 1.25; }
.chat-notification-message { color: #718096; font-size: 1rem; line-height: 1.5; }
"""


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": 800, "height": 600})

        # Case 1: Text, Background opacity/cover, Spacing utilities
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <p id="t" class="text-center text-lg font-bold text-red-500">Hello, Tailwind!</p>
  <div id="bg" class="bg-blue-500 bg-opacity-50 bg-cover p-4"><h1 class="text-white">Welcome</h1></div>
  <div id="sp" class="m-8 p-4 mt-4"><p>Box</p></div>
</body></html>""")
        actual1 = page.evaluate("""() => {
            const st = getComputedStyle(document.getElementById('t'));
            const sb = getComputedStyle(document.getElementById('bg'));
            const ss = getComputedStyle(document.getElementById('sp'));
            return {
                textAlign: st.textAlign,
                fontSize: st.fontSize,
                fontWeight: st.fontWeight,
                textColor: st.color,
                bgRgba: sb.backgroundColor,
                bgSize: sb.backgroundSize,
                padding: ss.paddingTop,
                marginTop: ss.marginTop,
                marginLeft: ss.marginLeft,
            };
        }""")
        expected1 = {
            "textAlign": "center",
            "fontSize": "18px",
            "fontWeight": "700",
            "textColor": "rgb(239, 68, 68)",
            "bgRgba": "rgba(59, 130, 246, 0.5)",
            "bgSize": "cover",
            "padding": "16px",
            "marginTop": "16px",
            "marginLeft": "32px",
        }
        cases.append(dict(
            name="text_bg_spacing_utilities",
            expected=expected1,
            actual=actual1,
            passed=(actual1 == expected1),
        ))

        # Case 2: Flex layout, Border & Radius, Shadow utilities
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <div id="fl" class="flex items-center justify-between" style="width:400px">
    <div class="bg-blue-500 text-white p-4">Item 1</div>
    <div class="bg-blue-500 text-white p-4">Item 2</div>
  </div>
  <div id="bd" class="border border-2 rounded-lg p-4">Bordered</div>
  <div id="sh" class="shadow-lg p-6">Shadowed</div>
</body></html>""")
        actual2 = page.evaluate("""() => {
            const sf = getComputedStyle(document.getElementById('fl'));
            const sb = getComputedStyle(document.getElementById('bd'));
            const ss = getComputedStyle(document.getElementById('sh'));
            return {
                display: sf.display,
                alignItems: sf.alignItems,
                justifyContent: sf.justifyContent,
                borderWidth: sb.borderTopWidth,
                borderRadius: sb.borderRadius,
                shadowPresent: ss.boxShadow !== 'none',
                shadowPadding: ss.paddingTop,
            };
        }""")
        expected2 = {
            "display": "flex",
            "alignItems": "center",
            "justifyContent": "space-between",
            "borderWidth": "2px",
            "borderRadius": "8px",
            "shadowPresent": True,
            "shadowPadding": "24px",
        }
        cases.append(dict(
            name="layout_border_shadow_utilities",
            expected=expected2,
            actual=actual2,
            passed=(actual2 == expected2),
        ))

        # Case 3: Responsive breakpoints & interactive hover/focus/active states
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <div id="rb" class="bg-blue-500 sm:bg-green-500 lg:bg-red-500 p-4">Responsive</div>
  <button id="btn" class="bg-blue-500 text-white hover:bg-blue-700 focus:outline-none active:bg-red-500">Hover or Focus Me!</button>
</body></html>""")
        page.set_viewport_size({"width": 500, "height": 600})
        bg_500 = page.eval_on_selector("#rb", "el => getComputedStyle(el).backgroundColor")
        page.set_viewport_size({"width": 640, "height": 600})
        bg_640 = page.eval_on_selector("#rb", "el => getComputedStyle(el).backgroundColor")
        page.set_viewport_size({"width": 1024, "height": 600})
        bg_1024 = page.eval_on_selector("#rb", "el => getComputedStyle(el).backgroundColor")

        page.hover("#btn")
        btn_hover = page.eval_on_selector("#btn", "el => getComputedStyle(el).backgroundColor")
        page.focus("#btn")
        btn_outline = page.eval_on_selector("#btn", "el => getComputedStyle(el).outlineColor")
        box = page.locator("#btn").bounding_box()
        page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
        page.mouse.down()
        btn_active = page.eval_on_selector("#btn", "el => getComputedStyle(el).backgroundColor")
        page.mouse.up()

        actual3 = {
            "bg500": bg_500,
            "bg640": bg_640,
            "bg1024": bg_1024,
            "btnHoverBg": btn_hover,
            "btnFocusOutline": btn_outline,
            "btnActiveBg": btn_active,
        }
        expected3 = {
            "bg500": "rgb(59, 130, 246)",
            "bg640": "rgb(34, 197, 94)",
            "bg1024": "rgb(239, 68, 68)",
            "btnHoverBg": "rgb(29, 78, 216)",
            "btnFocusOutline": "rgba(0, 0, 0, 0)",
            "btnActiveBg": "rgb(239, 68, 68)",
        }
        cases.append(dict(
            name="responsive_and_state_utilities",
            expected=expected3,
            actual=actual3,
            passed=(actual3 == expected3),
        ))

        # Case 4: ChitChat notification card — Traditional CSS vs Tailwind Utility-First
        page.set_viewport_size({"width": 800, "height": 600})
        svg_data = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 48 48'%3E%3Ccircle cx='24' cy='24' r='22' fill='%233b82f6'/%3E%3C/svg%3E"
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <div id="trad" class="chat-notification">
    <div class="chat-notification-logo-wrapper">
      <img id="trad-img" class="chat-notification-logo" src="{svg_data}" alt="ChitChat Logo">
    </div>
    <div class="chat-notification-content">
      <h4 class="chat-notification-title">ChitChat</h4>
      <p class="chat-notification-message">You have a new message!</p>
    </div>
  </div>
  <div id="tw" class="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-lg flex items-center gap-x-4">
    <div id="tw-wrap" class="shrink-0">
      <img id="tw-img" class="size-12" src="{svg_data}" alt="ChitChat Logo">
    </div>
    <div>
      <div id="tw-title" class="text-xl font-medium text-black">ChitChat</div>
      <p id="tw-msg" class="text-slate-500">You have a new message!</p>
    </div>
  </div>
</body></html>""")
        actual4 = page.evaluate("""() => {
            const tr = document.getElementById('trad');
            const tw = document.getElementById('tw');
            const st = getComputedStyle(tw);
            const sw = getComputedStyle(document.getElementById('tw-wrap'));
            const si = document.getElementById('tw-img').getBoundingClientRect();
            const stitle = getComputedStyle(document.getElementById('tw-title'));
            const smsg = getComputedStyle(document.getElementById('tw-msg'));
            return {
                tradWidth: Math.round(tr.getBoundingClientRect().width),
                twWidth: Math.round(tw.getBoundingClientRect().width),
                twCentered: st.marginLeft === st.marginRight && parseFloat(st.marginLeft) > 0,
                twPadding: st.paddingTop,
                twRadius: st.borderRadius,
                twGap: st.columnGap,
                logoShrink: sw.flexShrink,
                logoSizePx: [Math.round(si.width), Math.round(si.height)],
                titleSize: stitle.fontSize,
                titleWeight: stitle.fontWeight,
                titleColor: stitle.color,
                msgColor: smsg.color,
            };
        }""")
        expected4 = {
            "tradWidth": 384,
            "twWidth": 384,
            "twCentered": True,
            "twPadding": "24px",
            "twRadius": "12px",
            "twGap": "16px",
            "logoShrink": "0",
            "logoSizePx": [48, 48],
            "titleSize": "20px",
            "titleWeight": "500",
            "titleColor": "rgb(0, 0, 0)",
            "msgColor": "rgb(100, 116, 139)",
        }
        cases.append(dict(
            name="chitchat_traditional_vs_tailwind",
            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-utility-first-lab/explore-utility-first.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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