nex_animation/reports/ui_evidence/nex-p19/deadcss_lib.py

108 lines
3.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""阶段 19 死 CSS 判定共用库:CSS 转义还原、选择器类名抽取、类位置词元穷举。"""
import os, re
HEX = "0123456789abcdefABCDEF"
def css_unescape(s: str) -> str:
"""按 CSS Syntax 还原转义:\\. -> . ;\\XX -> 码点(可带一个空白终止符)。"""
out, i = [], 0
while i < len(s):
c = s[i]
if c != "\\":
out.append(c); i += 1; continue
i += 1
if i >= len(s):
out.append("\\"); break
if s[i] in HEX:
j = i
while j < len(s) and (j - i) < 6 and s[j] in HEX:
j += 1
if j < len(s) and s[j] in " \t\n":
j += 1
out.append(chr(int(s[i:j], 16) if s[i:j] else 0))
i = j
else:
out.append(s[i]); i += 1
return "".join(out)
def selector_tokens(s: str) -> set:
"""选择器里的类名,还原转义并保留 important 变体的 `!`(.fixed\\! -> 'fixed!')。"""
out = set()
for m in re.finditer(r"\.(\\.|[_\w\u00a0-\uffff-])+", s):
name = css_unescape(m.group(0)[1:])
j, tail = m.end(), ""
while j < len(s) and s[j] == "!":
tail += "!"; j += 1
if name:
out.add(name + tail)
return out
ANCHOR = re.compile(r"\b(className|class)\s*=\s*|\b(?:cn|clsx|cx|twMerge)\s*\(")
LIT = re.compile(r"""(?:"([^"\\\n]*)"|'([^'\\\n]*)'|`([^`$]*)`)""")
def _window(txt, i, limit=900):
depth, out = 0, []
for j in range(i, min(len(txt), i + limit)):
c = txt[j]
out.append(c)
if c in "{([":
depth += 1
elif c in "})]":
depth -= 1
if depth <= 0:
break
elif c == ">" and depth == 0:
break
return "".join(out)
def class_tokens(src):
"""只在类位置取词元(刻意取超集)。返回 (词元集, 文件数)。"""
toks, n = set(), 0
for d, _, fs in os.walk(src):
if "node_modules" in d:
continue
for f in fs:
if not f.endswith((".tsx", ".jsx")):
continue
p = os.path.join(d, f)
txt = open(p, encoding="utf-8").read()
n += 1
for m in ANCHOR.finditer(txt):
for lm in LIT.finditer(_window(txt, m.start())):
body = next((g for g in lm.groups() if g is not None), "")
for t in re.split(r"[\s,]+", body):
t = t.strip().strip("'\"`,;(){}[]")
if t and len(t) < 60:
toks.add(t)
return toks, n
ID_RE = re.compile(r"[^\s\"'`;,:{}()\[\]<>=?&|+*/%!~^#@$\u00a0-\uffff]*"
r"[_A-Za-z\u00a0-\uffff][^\s\"'`;,:{}()\[\]<>=?&|+*/%~^#@$\u00a0-\uffff]*")
def static_tokens(src):
"""全文切词(保守粗筛,会混进 CSS 属性名/属性值/注释散文,只作诊断用)。"""
toks, files = set(), []
for d, sub, fs in os.walk(src):
if "node_modules" in d or "/dist" in d:
continue
for f in fs:
if f.endswith((".ts", ".tsx", ".js", ".jsx", ".css", ".html", ".mjs")):
files.append(os.path.join(d, f))
for f in files:
try:
txt = open(f, encoding="utf-8").read().replace("\\!", "\x01")
except Exception:
continue
for m in ID_RE.finditer(txt):
t = m.group(0).replace("\x01", "!")
if t:
toks.add(t)
return toks, len(files)