"""Offline Playwright Chromium verification for React Ch28 (sass)."""
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")
def compile_simple_scss_vars(scss: str) -> str:
variables = {}
lines = []
for line in scss.splitlines():
m = re.match(r"^\s*(\$[a-zA-Z_][\w-]*)\s*:\s*([^;]+);\s*$", line)
if m:
variables[m.group(1)] = m.group(2).strip()
else:
lines.append(line)
out = "\n".join(lines)
for k, v in variables.items():
out = out.replace(k, v)
return out.strip()
def case_scss_variable_compilation_to_css(page):
scss = """$myColor: red;
h1 {
color: $myColor;
}"""
compiled_css = compile_simple_scss_vars(scss)
html = f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{compiled_css}</style></head>
<body>
<h1 id="hdr">Hello Style!</h1>
<p>Add a little style!</p>
</body></html>"""
page.set_content(html)
color = page.evaluate("getComputedStyle(document.getElementById('hdr')).color")
actual = {
"compiledCss": compiled_css,
"browserSeesDollarVar": "$" in compiled_css,
"h1Color": color,
}
expected = {
"compiledCss": "h1 {\n color: red;\n}",
"browserSeesDollarVar": False,
"h1Color": "rgb(255, 0, 0)",
}
return dict(name="scss_variable_compilation_to_css", expected=expected, actual=actual, passed=(actual == expected))
def case_scss_nesting_and_parent_selector(page):
# Equivalent compiled CSS of:
# $primary: #1d4ed8; $accent: #16a34a;
# .card { padding: 16px; border: 2px solid #cbd5e1; .title { color: $primary; } &.active { border-color: $accent; } }
compiled_css = """.card { padding: 16px; border: 2px solid #cbd5e1; }
.card .title { color: #1d4ed8; }
.card.active { border-color: #16a34a; }"""
html = f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{compiled_css}</style></head>
<body>
<div id="c1" class="card"><h2 id="t1" class="title">Default</h2></div>
<div id="c2" class="card active"><h2 id="t2" class="title">Active</h2></div>
</body></html>"""
page.set_content(html)
actual = page.evaluate("""() => ({
c1Padding: getComputedStyle(document.getElementById('c1')).paddingTop,
c1Border: getComputedStyle(document.getElementById('c1')).borderTopColor,
c2Border: getComputedStyle(document.getElementById('c2')).borderTopColor,
t1Color: getComputedStyle(document.getElementById('t1')).color,
})""")
expected = {
"c1Padding": "16px",
"c1Border": "rgb(203, 213, 225)",
"c2Border": "rgb(22, 163, 74)",
"t1Color": "rgb(29, 78, 216)",
}
return dict(name="scss_nesting_and_parent_selector", expected=expected, actual=actual, passed=(actual == expected))
def case_scss_mixin_and_math_equivalence(page):
# Equivalent compiled CSS of:
# $base-gap: 8px;
# @mixin pill($bg) { background-color: $bg; padding: $base-gap ($base-gap * 2); border-radius: 9999px; color: #fff; }
# .badge-info { @include pill(#2563eb); } .badge-warn { @include pill(#d97706); }
compiled_css = """.badge-info { background-color: #2563eb; padding: 8px 16px; border-radius: 9999px; color: #ffffff; display: inline-block; }
.badge-warn { background-color: #d97706; padding: 8px 16px; border-radius: 9999px; color: #ffffff; display: inline-block; }"""
html = f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{compiled_css}</style></head>
<body>
<span id="info" class="badge-info">Info</span>
<span id="warn" class="badge-warn">Warn</span>
</body></html>"""
page.set_content(html)
actual = page.evaluate("""() => {
const i = getComputedStyle(document.getElementById('info'));
const w = getComputedStyle(document.getElementById('warn'));
return {
infoBg: i.backgroundColor,
warnBg: w.backgroundColor,
padY: i.paddingTop,
padX: i.paddingLeft,
radius: i.borderTopLeftRadius,
};
}""")
expected = {
"infoBg": "rgb(37, 99, 235)",
"warnBg": "rgb(217, 119, 6)",
"padY": "8px",
"padX": "16px",
"radius": "9999px",
}
return dict(name="scss_mixin_and_math_equivalence", 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_scss_variable_compilation_to_css(page),
case_scss_nesting_and_parent_selector(page),
case_scss_mixin_and_math_equivalence(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-sass-lab/explore-sass.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-sass.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3188.zip
课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip