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

在无头 Chromium 中离线验证驼峰内联样式、状态高亮切换、全局样式覆盖与 CSS Modules 局部隔离

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-css.py
explore-css.py197 行
"""Offline Playwright Chromium verification for React Ch27 (css)."""
import json
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")


def case_inline_style_camelcase_and_numeric_px(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <div id="box"><h1 id="title">Hello Style!</h1><p id="sub">Add a little style!</p></div>
  <script>
    const UNITLESS = new Set(['opacity', 'zIndex', 'fontWeight', 'lineHeight', 'flex']);
    function applyReactStyle(el, styleObj) {
      for (const [k, v] of Object.entries(styleObj)) {
        el.style[k] = (typeof v === 'number' && !UNITLESS.has(k)) ? `${v}px` : String(v);
      }
    }
    const containerStyle = { padding: 20, backgroundColor: '#f0f0f0', opacity: 0.5 };
    const titleStyle = { fontSize: 24, color: '#333' };
    applyReactStyle(document.getElementById('box'), containerStyle);
    applyReactStyle(document.getElementById('title'), titleStyle);
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("""() => {
      const bs = getComputedStyle(document.getElementById('box'));
      const ts = getComputedStyle(document.getElementById('title'));
      return {
        boxBg: bs.backgroundColor,
        boxPadding: bs.paddingTop,
        boxOpacity: bs.opacity,
        titleSize: ts.fontSize,
        titleColor: ts.color,
      };
    }""")
    expected = {
        "boxBg": "rgb(240, 240, 240)",
        "boxPadding": "20px",
        "boxOpacity": "0.5",
        "titleSize": "24px",
        "titleColor": "rgb(51, 51, 51)",
    }
    return dict(name="inline_style_camelcase_and_numeric_px", expected=expected, actual=actual, passed=(actual == expected))


def case_dynamic_state_inline_style_toggle(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <div id="container">
    <h1>Hello, world!</h1>
    <button id="toggle-btn">Toggle Highlight</button>
  </div>
  <script>
    let isHighlighted = false;
    const box = document.getElementById('container');
    function render() {
      box.style.padding = '20px';
      box.style.backgroundColor = isHighlighted ? '#ffff99' : '#f0f0f0';
    }
    document.getElementById('toggle-btn').addEventListener('click', () => {
      isHighlighted = !isHighlighted;
      render();
    });
    render();
  </script>
</body></html>"""
    page.set_content(html)
    before = page.evaluate("getComputedStyle(document.getElementById('container')).backgroundColor")
    page.click("#toggle-btn")
    after = page.evaluate("getComputedStyle(document.getElementById('container')).backgroundColor")
    actual = {"initialBg": before, "highlightedBg": after}
    expected = {"initialBg": "rgb(240, 240, 240)", "highlightedBg": "rgb(255, 255, 153)"}
    return dict(name="dynamic_state_inline_style_toggle", expected=expected, actual=actual, passed=(actual == expected))


def case_external_stylesheet_global_cascade(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"><style>
  /* App.css global stylesheet */
  body {
    background-color: #282c34;
    color: white;
    padding: 40px;
    font-family: Sans-Serif;
    text-align: center;
  }
  .title { color: #61dafb; }
  /* Later global stylesheet overrides same class name */
  .title { color: #ff6b6b; }
</style></head>
<body>
  <h1 id="h1" class="title">Hello Style!</h1>
  <p>Add a little style!</p>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("""() => {
      const bodyCs = getComputedStyle(document.body);
      const h1Cs = getComputedStyle(document.getElementById('h1'));
      return {
        bodyBg: bodyCs.backgroundColor,
        bodyColor: bodyCs.color,
        bodyPadding: bodyCs.paddingTop,
        bodyAlign: bodyCs.textAlign,
        collidedTitleColor: h1Cs.color,
      };
    }""")
    expected = {
        "bodyBg": "rgb(40, 44, 52)",
        "bodyColor": "rgb(255, 255, 255)",
        "bodyPadding": "40px",
        "bodyAlign": "center",
        "collidedTitleColor": "rgb(255, 107, 107)",
    }
    return dict(name="external_stylesheet_global_cascade", expected=expected, actual=actual, passed=(actual == expected))


def case_css_modules_scoped_class_isolation(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"><style>
  /* Compiled MyComponent.module.css */
  .MyComponent_container__a1b2 { padding: 20px; background-color: #f0f0f0; }
  .MyComponent_title__c3d4 { font-size: 24px; color: #333333; }
  /* Compiled OtherComponent.module.css */
  .OtherComponent_title__e5f6 { font-size: 16px; color: #dc2626; }
</style></head>
<body>
  <div id="comp-a"></div>
  <div id="comp-b"></div>
  <script>
    const stylesA = { container: 'MyComponent_container__a1b2', title: 'MyComponent_title__c3d4' };
    const stylesB = { title: 'OtherComponent_title__e5f6' };
    document.getElementById('comp-a').innerHTML =
      `<div id="a-wrap" class="${stylesA.container}"><h1 id="a-title" class="${stylesA.title}">Hello, world!</h1></div>`;
    document.getElementById('comp-b').innerHTML =
      `<h1 id="b-title" class="${stylesB.title}">Other Title</h1>`;
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("""() => {
      const aWrap = getComputedStyle(document.getElementById('a-wrap'));
      const aTitle = getComputedStyle(document.getElementById('a-title'));
      const bTitle = getComputedStyle(document.getElementById('b-title'));
      return {
        aClass: document.getElementById('a-title').className,
        bClass: document.getElementById('b-title').className,
        aWrapBg: aWrap.backgroundColor,
        aTitleSize: aTitle.fontSize,
        aTitleColor: aTitle.color,
        bTitleSize: bTitle.fontSize,
        bTitleColor: bTitle.color,
      };
    }""")
    expected = {
        "aClass": "MyComponent_title__c3d4",
        "bClass": "OtherComponent_title__e5f6",
        "aWrapBg": "rgb(240, 240, 240)",
        "aTitleSize": "24px",
        "aTitleColor": "rgb(51, 51, 51)",
        "bTitleSize": "16px",
        "bTitleColor": "rgb(220, 38, 38)",
    }
    return dict(name="css_modules_scoped_class_isolation", 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_inline_style_camelcase_and_numeric_px(page),
                case_dynamic_state_inline_style_toggle(page),
                case_external_stylesheet_global_cascade(page),
                case_css_modules_scoped_class_isolation(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-css-lab/explore-css.py

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

下载课程关联工程包:React

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

下载课程关联工程包:React

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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