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

离线 Chromium 核验交互态、组合态、结构伪类、表单/Group 联动与伪元素/媒体偏好修饰符

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-state.py
explore-state.py283 行
"""Offline Playwright Chromium lab for Tailwind CSS Ch 09 (state)."""
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; }
ul { list-style: none; margin: 0; padding: 0; }
.px-4 { padding-left: 1rem; padding-right: 1rem; }
.py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; }
.p-2 { padding: 0.5rem; }
.bg-blue-500 { background-color: #3b82f6; }
.text-white { color: #ffffff; }
.border { border-width: 1px; border-style: solid; border-color: #d1d5db; }
.hover\\:bg-sky-700:hover { background-color: #0369a1; }
.active\\:bg-green-700:active { background-color: #15803d; }
.focus\\:outline-none:focus { outline: 2px solid transparent; outline-offset: 2px; }
.focus\\:ring-2:focus { --tw-ring-width: 2px; box-shadow: 0 0 0 var(--tw-ring-width) var(--tw-ring-color, #2563eb); }
.focus\\:ring-blue-600:focus { --tw-ring-color: #2563eb; }
.focus-within\\:border-blue-500:focus-within { border-color: #3b82f6; }
.dark .dark\\:bg-gray-800 { background-color: #1f2937; }
.dark .dark\\:hover\\:bg-fuchsia-600:hover { background-color: #c026d3; }
@media (min-width: 640px) {
  .sm\\:hover\\:bg-blue-700:hover { background-color: #1d4ed8; }
}
@media (min-width: 768px) {
  .md\\:focus\\:ring-2:focus { box-shadow: 0 0 0 2px #3b82f6; }
}
.first\\:text-red-500:first-child { color: #ef4444; }
.first\\:font-bold:first-child { font-weight: 700; }
.last\\:font-bold:last-child { font-weight: 700; }
.last\\:font-light:last-child { font-weight: 300; }
.odd\\:bg-gray-100:nth-child(odd) { background-color: #f3f4f6; }
.even\\:bg-gray-200:nth-child(even) { background-color: #e5e7eb; }
.empty\\:bg-gray-50:empty { background-color: #f9fafb; }
.required\\:border-red-500:required { border-color: #ef4444; }
.invalid\\:border-yellow-500:invalid { border-color: #eab308; }
.disabled\\:bg-gray-300:disabled { background-color: #d1d5db; }
.disabled\\:opacity-50:disabled { opacity: 0.5; }
.enabled\\:border-blue-500:enabled { border-color: #3b82f6; }
.checked\\:bg-blue-500:checked { background-color: #3b82f6; }
.group:hover .group-hover\\:bg-gray-300 { background-color: #d1d5db; }
.before\\:content-star::before { content: '*'; color: #ef4444; }
.after\\:content-bang::after { content: '!'; color: #22c55e; }
[dir="rtl"] .rtl\\:text-right, .rtl\\:text-right[dir="rtl"] { text-align: right; }
.aria-checked\\:bg-green-500[aria-checked="true"] { background-color: #22c55e; }
.target\\:bg-yellow-500:target { background-color: #eab308; }
@media (prefers-reduced-motion: no-preference) {
  .motion-safe\\:duration-500 { transition-duration: 500ms; }
}
"""


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: hover, focus, active, focus-within
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <button id="bh" class="px-4 py-2 bg-blue-500 text-white hover:bg-sky-700">Hover</button>
  <button id="ba" class="px-4 py-2 bg-blue-500 text-white active:bg-green-700">Click</button>
  <div id="fw" class="border p-2 focus-within:border-blue-500">
    <input id="fi" class="border p-2 focus:outline-none focus:ring-2 focus:ring-blue-600" type="text" />
  </div>
</body></html>""")
        bh_def = page.eval_on_selector("#bh", "el => getComputedStyle(el).backgroundColor")
        page.hover("#bh")
        bh_hov = page.eval_on_selector("#bh", "el => getComputedStyle(el).backgroundColor")
        box = page.locator("#ba").bounding_box()
        page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
        page.mouse.down()
        ba_act = page.eval_on_selector("#ba", "el => getComputedStyle(el).backgroundColor")
        page.mouse.up()
        page.focus("#fi")
        fi_ring = page.eval_on_selector("#fi", "el => getComputedStyle(el).boxShadow")
        fw_border = page.eval_on_selector("#fw", "el => getComputedStyle(el).borderTopColor")
        actual1 = {
            "hoverDefault": bh_def,
            "hoverActive": bh_hov,
            "activeBg": ba_act,
            "focusRingShadow": fi_ring,
            "focusWithinBorder": fw_border,
        }
        expected1 = {
            "hoverDefault": "rgb(59, 130, 246)",
            "hoverActive": "rgb(3, 105, 161)",
            "activeBg": "rgb(21, 128, 61)",
            "focusRingShadow": "rgb(37, 99, 235) 0px 0px 0px 2px",
            "focusWithinBorder": "rgb(59, 130, 246)",
        }
        cases.append(dict(
            name="hover_focus_active_interactions",
            expected=expected1,
            actual=actual1,
            passed=(actual1 == expected1),
        ))

        # Case 2: Combined dark + responsive + interactive states
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <button id="cb" class="px-4 py-2 bg-blue-500 text-white hover:bg-sky-700 dark:hover:bg-fuchsia-600">Combo</button>
  <button id="rb" class="px-4 py-2 bg-blue-500 text-white dark:bg-gray-800 sm:hover:bg-blue-700 md:focus:ring-2">RespDark</button>
</body></html>""")
        page.hover("#cb")
        light_hover = page.eval_on_selector("#cb", "el => getComputedStyle(el).backgroundColor")
        page.evaluate("document.documentElement.classList.add('dark')")
        page.hover("#cb")
        dark_hover = page.eval_on_selector("#cb", "el => getComputedStyle(el).backgroundColor")
        page.set_viewport_size({"width": 768, "height": 600})
        rb_dark_bg = page.eval_on_selector("#rb", "el => getComputedStyle(el).backgroundColor")
        page.hover("#rb")
        rb_sm_hover = page.eval_on_selector("#rb", "el => getComputedStyle(el).backgroundColor")
        page.focus("#rb")
        rb_md_focus = page.eval_on_selector("#rb", "el => getComputedStyle(el).boxShadow")
        actual2 = {
            "lightHover": light_hover,
            "darkHover": dark_hover,
            "respDarkBg": rb_dark_bg,
            "smHoverBg": rb_sm_hover,
            "mdFocusRing": rb_md_focus,
        }
        expected2 = {
            "lightHover": "rgb(3, 105, 161)",
            "darkHover": "rgb(192, 38, 211)",
            "respDarkBg": "rgb(31, 41, 55)",
            "smHoverBg": "rgb(29, 78, 216)",
            "mdFocusRing": "rgb(59, 130, 246) 0px 0px 0px 2px",
        }
        cases.append(dict(
            name="combined_responsive_dark_states",
            expected=expected2,
            actual=actual2,
            passed=(actual2 == expected2),
        ))

        # Case 3: Structural pseudo-classes first, last, odd, even, empty
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <ul id="lst">
    <li class="first:text-red-500 last:font-bold odd:bg-gray-100 even:bg-gray-200">Item 1</li>
    <li class="first:text-red-500 last:font-bold odd:bg-gray-100 even:bg-gray-200">Item 2</li>
    <li class="first:text-red-500 last:font-bold odd:bg-gray-100 even:bg-gray-200">Item 3</li>
    <li class="first:text-red-500 last:font-bold odd:bg-gray-100 even:bg-gray-200">Item 4</li>
  </ul>
  <div id="emp" class="empty:bg-gray-50"></div>
</body></html>""")
        actual3 = page.evaluate("""() => {
            const items = [...document.querySelectorAll('#lst li')].map(li => {
                const s = getComputedStyle(li);
                return { color: s.color, weight: s.fontWeight, bg: s.backgroundColor };
            });
            return {
                firstColor: items[0].color,
                lastWeight: items[3].weight,
                oddBgs: [items[0].bg, items[2].bg],
                evenBgs: [items[1].bg, items[3].bg],
                emptyBg: getComputedStyle(document.getElementById('emp')).backgroundColor,
            };
        }""")
        expected3 = {
            "firstColor": "rgb(239, 68, 68)",
            "lastWeight": "700",
            "oddBgs": ["rgb(243, 244, 246)", "rgb(243, 244, 246)"],
            "evenBgs": ["rgb(229, 231, 235)", "rgb(229, 231, 235)"],
            "emptyBg": "rgb(249, 250, 251)",
        }
        cases.append(dict(
            name="structural_pseudo_first_last_odd_even",
            expected=expected3,
            actual=actual3,
            passed=(actual3 == expected3),
        ))

        # Case 4: Form states (required, invalid, disabled, enabled, checked) & group-hover
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <input id="req" class="border p-2 required:border-red-500 invalid:border-yellow-500" type="email" value="not-an-email" required />
  <input id="req-ok" class="border p-2 required:border-red-500 invalid:border-yellow-500" type="email" value="a@b.com" required />
  <input id="dis" class="border p-2 disabled:bg-gray-300 disabled:opacity-50" type="text" disabled />
  <input id="en" class="border p-2 enabled:border-blue-500" type="text" />
  <input id="chk" class="checked:bg-blue-500" type="checkbox" checked />
  <div id="grp" class="group" style="padding:20px; width:260px;">
    <button id="grp-btn" class="px-4 py-2 bg-blue-500 text-white group-hover:bg-gray-300">Child</button>
  </div>
</body></html>""")
        before_grp = page.eval_on_selector("#grp-btn", "el => getComputedStyle(el).backgroundColor")
        gbox = page.locator("#grp").bounding_box()
        page.mouse.move(gbox["x"] + 5, gbox["y"] + 5)
        after_grp = page.eval_on_selector("#grp-btn", "el => getComputedStyle(el).backgroundColor")
        actual4 = page.evaluate("""(grp) => ({
            invalidBorder: getComputedStyle(document.getElementById('req')).borderTopColor,
            validRequiredBorder: getComputedStyle(document.getElementById('req-ok')).borderTopColor,
            disabledBg: getComputedStyle(document.getElementById('dis')).backgroundColor,
            disabledOpacity: getComputedStyle(document.getElementById('dis')).opacity,
            enabledBorder: getComputedStyle(document.getElementById('en')).borderTopColor,
            checkedMatches: document.getElementById('chk').matches(':checked'),
            groupBeforeBg: grp.before,
            groupHoverBg: grp.after,
        })""", {"before": before_grp, "after": after_grp})
        expected4 = {
            "invalidBorder": "rgb(234, 179, 8)",
            "validRequiredBorder": "rgb(239, 68, 68)",
            "disabledBg": "rgb(209, 213, 219)",
            "disabledOpacity": "0.5",
            "enabledBorder": "rgb(59, 130, 246)",
            "checkedMatches": True,
            "groupBeforeBg": "rgb(59, 130, 246)",
            "groupHoverBg": "rgb(209, 213, 219)",
        }
        cases.append(dict(
            name="form_and_group_states",
            expected=expected4,
            actual=actual4,
            passed=(actual4 == expected4),
        ))

        # Case 5: Pseudo-elements (before/after), rtl, aria-checked, :target, motion-safe
        page.emulate_media(reduced_motion="no-preference")
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
  <div id="pe" class="before:content-star after:content-bang">Label</div>
  <div id="rtl" dir="rtl" class="rtl:text-right">RTL</div>
  <div id="aria" aria-checked="true" class="aria-checked:bg-green-500">ARIA</div>
  <div id="sec" class="target:bg-yellow-500">Target</div>
  <div id="mot" class="motion-safe:duration-500">Motion</div>
</body></html>""")
        page.evaluate("location.hash = '#sec'")
        dur_safe = page.eval_on_selector("#mot", "el => getComputedStyle(el).transitionDuration")
        page.emulate_media(reduced_motion="reduce")
        dur_reduced = page.eval_on_selector("#mot", "el => getComputedStyle(el).transitionDuration")
        actual5 = page.evaluate("""(m) => ({
            beforeContent: getComputedStyle(document.getElementById('pe'), '::before').content,
            afterContent: getComputedStyle(document.getElementById('pe'), '::after').content,
            rtlAlign: getComputedStyle(document.getElementById('rtl')).textAlign,
            ariaBg: getComputedStyle(document.getElementById('aria')).backgroundColor,
            targetBg: getComputedStyle(document.getElementById('sec')).backgroundColor,
            motionSafeDuration: m.safe,
            motionReduceDuration: m.reduced,
        })""", {"safe": dur_safe, "reduced": dur_reduced})
        expected5 = {
            "beforeContent": '"*"',
            "afterContent": '"!"',
            "rtlAlign": "right",
            "ariaBg": "rgb(34, 197, 94)",
            "targetBg": "rgb(234, 179, 8)",
            "motionSafeDuration": "0.5s",
            "motionReduceDuration": "0s",
        }
        cases.append(dict(
            name="pseudo_elements_dir_aria_motion",
            expected=expected5,
            actual=actual5,
            passed=(actual5 == expected5),
        ))

        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-state-lab/explore-state.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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