Files
danyang-match/scripts/lib/wxss-selectors.mjs
T

114 lines
3.5 KiB
JavaScript
Raw Normal View History

// 组件 WXSS 选择器检查(lib):供 CLI 与 UI 契约门禁共用。
//
// 规则来源:微信小程序**自定义组件**的 wxss 只允许类选择器。使用标签选择器(`image`/`view`…)、
// ID 选择器(`#id`)、属性选择器(`[attr]`)时开发者工具警告:
// [pages/index/index] Some selectors are not allowed in component wxss,
// including tag name selectors, ID selectors, and attribute selectors.
// (./components/recommend-card/index.wxss:1:1092)
//
// ⚠️ 作用域:**page 的 wxss 不受此限制**(页面不是组件)。
// 对 `miniapp/pages/` 套用本规则会产生误报,故只管 `miniapp/components/`。
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
/** 去掉注释,并用等长空白占位以保持原始字符偏移(报错行号才准) */
export function stripComments(src) {
return src.replace(/\/\*[\s\S]*?\*\//g, (m) => ' '.repeat(m.length));
}
/** 切出所有「选择器前置文本」(`{` 之前),跳过 at-rule 与声明块内部 */
export function extractSelectorPreludes(src) {
const preludes = [];
let depth = 0;
let buf = '';
let bufStart = 0;
for (let i = 0; i < src.length; i++) {
const c = src[i];
if (c === '{') {
if (depth === 0) preludes.push({ text: buf, index: bufStart });
depth++;
buf = '';
continue;
}
if (c === '}') {
depth = Math.max(0, depth - 1);
buf = '';
continue;
}
if (depth === 0) {
if (buf === '') bufStart = i;
buf += c;
}
}
return preludes;
}
/**
* 检查一段选择器前置文本是否含违规成分。
* @returns {string[]} 违规描述(去重)
*/
export function findViolations(selector) {
const bad = [];
const s = selector.trim();
if (!s) return bad;
if (s.startsWith('@')) return bad; // @media / @keyframes / @import 不是选择器
// 去掉伪类/伪元素及其函数括号内容,避免把 `:nth-child(2)` 里的标识符当标签
const cleaned = s.replace(/:{1,2}[a-zA-Z-]+(\([^)]*\))?/g, '').replace(/\([^)]*\)/g, '');
for (const part of cleaned.split(',')) {
const token = part.trim();
if (!token) continue;
const idMatch = token.match(/#[A-Za-z_][\w-]*/);
if (idMatch) bad.push(`ID 选择器 \`${idMatch[0]}\``);
const attrMatch = token.match(/\[[^\]]*\]/);
if (attrMatch) bad.push(`属性选择器 \`${attrMatch[0]}\``);
// 标签选择器:`>`/空格/`+`/`~` 之后紧跟的裸元素名
const tagMatch = token.match(/(^|[\s>+~])([a-zA-Z][\w-]*)/);
if (tagMatch) bad.push(`标签选择器 \`${tagMatch[2]}\``);
}
return [...new Set(bad)];
}
/**
* 检查单个 wxss 文件内容。
* @returns {{line:number, message:string}[]}
*/
export function checkWxss(src) {
const clean = stripComments(src);
const out = [];
for (const { text, index } of extractSelectorPreludes(clean)) {
for (const v of findViolations(text)) {
out.push({
line: clean.slice(0, index).split('\n').length,
message: `${v}(选择器原文 \`${text.trim().slice(0, 60)}\`)`,
});
}
}
return out;
}
export function walkWxss(dir, out = []) {
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return out;
}
for (const e of entries) {
const p = join(dir, e.name);
if (e.isDirectory()) {
if (!['node_modules', 'miniprogram_npm'].includes(e.name)) walkWxss(p, out);
} else if (e.name.endsWith('.wxss')) {
out.push(p);
}
}
return out;
}
export { readFileSync };