@nokecy/qc-ui 2.0.0-beta.16 → 2.0.0-beta.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lint/cli.cjs ADDED
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /**
4
+ * qc-ui-lint:用项目自己安装的 ESLint(8 或 9)与 stylelint,只跑 qc-ui 的设计规范规则。
5
+ * 不读取、也不改动项目原有的 lint 配置,因此 Umi `max lint` 项目也能直接用。
6
+ *
7
+ * npx qc-ui-lint # 默认检查 src
8
+ * npx qc-ui-lint src/pages/a.tsx # 只查指定文件 / 目录
9
+ * npx qc-ui-lint --max-warnings 0
10
+ *
11
+ * 主题单源文件(允许写色值的那一两份,DESIGN.md §1 原则 3)在项目 package.json 中登记排除:
12
+ * "qc-ui-lint": { "ignore": ["src/theme/palette.ts", "src/styles/tokens.less"] }
13
+ *
14
+ * 退出码:0 通过;1 有错误(或警告超过 --max-warnings);2 运行失败。
15
+ */
16
+ const path = require('node:path');
17
+ const fs = require('node:fs');
18
+ const plugin = require('./index.cjs');
19
+ const { dropForeignRuleNotices } = require('./results.cjs');
20
+
21
+ const cwd = process.cwd();
22
+ const SCRIPT_EXT = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs']);
23
+ const STYLE_EXT = new Set(['.less', '.css']);
24
+ const BASE_IGNORES = ['**/node_modules/**', '**/dist/**', '**/.umi/**', '**/.umi-production/**', '**/.umi-test/**', '**/__tests__/**', '**/*.test.*', '**/*.spec.*'];
25
+
26
+ /** 项目 package.json 的 "qc-ui-lint".ignore:主题单源文件等经登记的例外。 */
27
+ function projectIgnores() {
28
+ try {
29
+ const pkg = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
30
+ const list = pkg['qc-ui-lint'] && pkg['qc-ui-lint'].ignore;
31
+ return Array.isArray(list) ? list.filter((x) => typeof x === 'string') : [];
32
+ } catch {
33
+ return [];
34
+ }
35
+ }
36
+ const IGNORES = [...BASE_IGNORES, ...projectIgnores()];
37
+
38
+ function parseArgs(argv) {
39
+ const out = { paths: [], maxWarnings: -1 };
40
+ for (let i = 0; i < argv.length; i++) {
41
+ if (argv[i] === '--max-warnings') out.maxWarnings = Number(argv[++i]);
42
+ else if (argv[i] === '-h' || argv[i] === '--help') out.help = true;
43
+ else out.paths.push(argv[i]);
44
+ }
45
+ if (!out.paths.length) out.paths.push('src');
46
+ return out;
47
+ }
48
+
49
+ function tryResolve(ids) {
50
+ for (const id of ids) {
51
+ try {
52
+ return require.resolve(id, { paths: [cwd] });
53
+ } catch {}
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /** 把参数拆成脚本目标与样式目标;目录同时交给两边。 */
59
+ function splitTargets(paths) {
60
+ const scripts = [];
61
+ const styles = [];
62
+ for (const p of paths) {
63
+ const abs = path.resolve(cwd, p);
64
+ if (!fs.existsSync(abs)) continue;
65
+ if (fs.statSync(abs).isDirectory()) {
66
+ scripts.push(p);
67
+ styles.push(path.posix.join(p.split(path.sep).join('/'), '**/*.{less,css}'));
68
+ continue;
69
+ }
70
+ const ext = path.extname(p);
71
+ if (SCRIPT_EXT.has(ext)) scripts.push(p);
72
+ else if (STYLE_EXT.has(ext)) styles.push(p);
73
+ }
74
+ return { scripts, styles };
75
+ }
76
+
77
+ async function lintScripts(targets) {
78
+ const eslintPath = tryResolve(['eslint']);
79
+ if (!eslintPath) throw new Error('未找到 eslint:请在项目中安装 eslint(8 或 9)。');
80
+ const eslintMod = require(eslintPath);
81
+ const major = Number(require(tryResolve(['eslint/package.json'])).version.split('.')[0]);
82
+ const parserPath = tryResolve(['@typescript-eslint/parser', '@umijs/lint/node_modules/@typescript-eslint/parser']);
83
+ if (!parserPath) throw new Error('未找到 @typescript-eslint/parser:请在项目中安装(Umi 项目随 @umijs/lint 提供)。');
84
+ const parserOptions = { ecmaVersion: 'latest', sourceType: 'module', ecmaFeatures: { jsx: true } };
85
+
86
+ let eslint;
87
+ if (major >= 9) {
88
+ const ESLint = eslintMod.loadESLint ? await eslintMod.loadESLint({ useFlatConfig: true }) : eslintMod.ESLint;
89
+ eslint = new ESLint({
90
+ cwd,
91
+ overrideConfigFile: true,
92
+ errorOnUnmatchedPattern: false,
93
+ overrideConfig: [
94
+ { ignores: IGNORES },
95
+ {
96
+ files: ['**/*.{js,jsx,ts,tsx,mjs,cjs}'],
97
+ languageOptions: { parser: require(parserPath), parserOptions },
98
+ plugins: { 'qc-ui': plugin },
99
+ rules: plugin.recommendedRules,
100
+ linterOptions: { reportUnusedDisableDirectives: 'off' },
101
+ },
102
+ ],
103
+ });
104
+ } else {
105
+ eslint = new eslintMod.ESLint({
106
+ cwd,
107
+ useEslintrc: false,
108
+ errorOnUnmatchedPattern: false,
109
+ extensions: [...SCRIPT_EXT],
110
+ plugins: { 'qc-ui': plugin },
111
+ overrideConfig: {
112
+ parser: parserPath,
113
+ parserOptions,
114
+ plugins: ['qc-ui'],
115
+ rules: plugin.recommendedRules,
116
+ ignorePatterns: IGNORES,
117
+ },
118
+ });
119
+ }
120
+ // 显式点名但命中忽略规则的文件(如测试文件)只会得到一条「File ignored」提示,不计入结果
121
+ const isIgnoredNotice = (r) => r.messages.length === 1 && !r.messages[0].ruleId && /ignore pattern/.test(r.messages[0].message);
122
+ const results = dropForeignRuleNotices((await eslint.lintFiles(targets)).filter((r) => !isIgnoredNotice(r)));
123
+ const formatter = await eslint.loadFormatter('stylish');
124
+ return {
125
+ output: await formatter.format(results),
126
+ errors: results.reduce((n, r) => n + r.errorCount, 0),
127
+ warnings: results.reduce((n, r) => n + r.warningCount, 0),
128
+ };
129
+ }
130
+
131
+ async function lintStyles(targets) {
132
+ const stylelintPath = tryResolve(['stylelint']);
133
+ if (!stylelintPath) return { output: '', errors: 0, warnings: 0, skipped: '未安装 stylelint,跳过 .less / .css 检查。' };
134
+ const syntaxPath = tryResolve(['postcss-less', '@umijs/lint/compiled/postcss-less']);
135
+ const stylelint = require(stylelintPath);
136
+ const result = await stylelint.lint({
137
+ files: targets,
138
+ cwd,
139
+ config: require('./stylelint.cjs'),
140
+ configBasedir: __dirname,
141
+ customSyntax: syntaxPath || undefined,
142
+ allowEmptyInput: true,
143
+ ignorePattern: IGNORES,
144
+ formatter: 'string',
145
+ });
146
+ const warnings = result.results.flatMap((r) => r.warnings);
147
+ return {
148
+ output: result.output || result.report || '',
149
+ errors: warnings.filter((w) => w.severity === 'error').length,
150
+ warnings: warnings.filter((w) => w.severity !== 'error').length,
151
+ skipped: syntaxPath ? '' : '未找到 postcss-less,.less 按 CSS 语法解析,可能误报。',
152
+ };
153
+ }
154
+
155
+ async function main() {
156
+ const args = parseArgs(process.argv.slice(2));
157
+ if (args.help) {
158
+ console.log('用法:qc-ui-lint [文件或目录…] [--max-warnings N] 默认检查 src');
159
+ return 0;
160
+ }
161
+ const { scripts, styles } = splitTargets(args.paths);
162
+ let errors = 0;
163
+ let warnings = 0;
164
+ if (scripts.length) {
165
+ const r = await lintScripts(scripts);
166
+ if (r.output.trim()) process.stdout.write(r.output);
167
+ errors += r.errors;
168
+ warnings += r.warnings;
169
+ }
170
+ if (styles.length) {
171
+ const r = await lintStyles(styles);
172
+ if (r.skipped) console.error(`[qc-ui-lint] ${r.skipped}`);
173
+ if (r.output.trim()) process.stdout.write(r.output);
174
+ errors += r.errors;
175
+ warnings += r.warnings;
176
+ }
177
+ if (errors || (args.maxWarnings >= 0 && warnings > args.maxWarnings)) {
178
+ console.error(`[qc-ui-lint] 未通过:${errors} 个错误,${warnings} 个警告。规则说明见 DESIGN.md 对应章节。`);
179
+ return 1;
180
+ }
181
+ return 0;
182
+ }
183
+
184
+ main().then(
185
+ (code) => process.exit(code),
186
+ (err) => {
187
+ console.error(`[qc-ui-lint] ${err.message}`);
188
+ process.exit(2);
189
+ },
190
+ );
package/lint/index.cjs ADDED
@@ -0,0 +1,45 @@
1
+ 'use strict';
2
+ /**
3
+ * 工业界面设计规范(DESIGN.md)的可静态判定部分,做成 ESLint 规则。
4
+ *
5
+ * - ESLint 9 flat:`import qcUi from '@nokecy/qc-ui/eslint-plugin'`,把 `qcUi.configs.recommended` 放进配置数组。
6
+ * - ESLint 8 legacy(Umi `max lint`):插件名无法从子路径解析,改用 `npx qc-ui-lint`,它用项目自己的 ESLint 只跑这些规则。
7
+ *
8
+ * 只覆盖能从源码判定的条款;布局、文案、交互类规则仍靠评审清单。
9
+ */
10
+ const pkg = require('../package.json');
11
+
12
+ const rules = {
13
+ 'no-hardcoded-color': require('./rules/no-hardcoded-color.cjs'),
14
+ 'no-table-row-height': require('./rules/no-table-row-height.cjs'),
15
+ 'no-viewport-calc': require('./rules/no-viewport-calc.cjs'),
16
+ 'no-status-tag': require('./rules/no-status-tag.cjs'),
17
+ 'formily-feedback-layout': require('./rules/formily-feedback-layout.cjs'),
18
+ 'width-4px-grid': require('./rules/width-4px-grid.cjs'),
19
+ 'no-compact-algorithm': require('./rules/no-compact-algorithm.cjs'),
20
+ };
21
+
22
+ const recommendedRules = {
23
+ 'qc-ui/no-hardcoded-color': 'error',
24
+ 'qc-ui/no-table-row-height': 'error',
25
+ 'qc-ui/no-viewport-calc': 'error',
26
+ 'qc-ui/no-status-tag': 'error',
27
+ 'qc-ui/formily-feedback-layout': 'error',
28
+ 'qc-ui/width-4px-grid': 'warn',
29
+ 'qc-ui/no-compact-algorithm': 'error',
30
+ };
31
+
32
+ const plugin = {
33
+ meta: { name: '@nokecy/qc-ui/eslint-plugin', version: pkg.version },
34
+ rules,
35
+ recommendedRules,
36
+ configs: {},
37
+ };
38
+
39
+ plugin.configs.recommended = {
40
+ name: 'qc-ui/recommended',
41
+ plugins: { 'qc-ui': plugin },
42
+ rules: recommendedRules,
43
+ };
44
+
45
+ module.exports = plugin;
@@ -0,0 +1,28 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * qc-ui-lint 只加载 qc-ui 的规则。项目源码里原有的 `eslint-disable … react-hooks/exhaustive-deps`
5
+ * 这类注释指向未加载的规则,ESLint 会为每一处报「Definition for rule '…' was not found」。
6
+ * 这些提示与设计规范无关,从结果里剔除,并按剩余消息重算计数。
7
+ */
8
+ const isForeignRuleNotice = (m) =>
9
+ typeof m.ruleId === 'string' && !m.ruleId.startsWith('qc-ui/') && /^Definition for rule /.test(m.message);
10
+
11
+ function dropForeignRuleNotices(results) {
12
+ return results.map((r) => {
13
+ const messages = r.messages.filter((m) => !isForeignRuleNotice(m));
14
+ if (messages.length === r.messages.length) return r;
15
+ const count = (pred) => messages.filter(pred).length;
16
+ return {
17
+ ...r,
18
+ messages,
19
+ errorCount: count((m) => m.severity === 2),
20
+ warningCount: count((m) => m.severity === 1),
21
+ fatalErrorCount: count((m) => m.fatal),
22
+ fixableErrorCount: count((m) => m.severity === 2 && m.fix),
23
+ fixableWarningCount: count((m) => m.severity === 1 && m.fix),
24
+ };
25
+ });
26
+ }
27
+
28
+ module.exports = { dropForeignRuleNotices };
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+ const { staticText, jsxValue, propKey, cite } = require('../utils.cjs');
3
+
4
+ module.exports = {
5
+ meta: {
6
+ type: 'problem',
7
+ docs: { description: "Formily 的 feedbackLayout 统一取 'terse'" },
8
+ schema: [],
9
+ messages: {
10
+ terse: `feedbackLayout 统一取 'terse'(当前为「{{value}}」):错误文字以悬浮提示呈现,不占表单行高${cite('§6.4')}`,
11
+ },
12
+ },
13
+ create(context) {
14
+ const check = (valueNode) => {
15
+ const text = staticText(valueNode);
16
+ if (text != null && text !== 'terse') context.report({ node: valueNode, messageId: 'terse', data: { value: text } });
17
+ };
18
+ return {
19
+ JSXAttribute(node) {
20
+ if (node.name.name === 'feedbackLayout') check(jsxValue(node));
21
+ },
22
+ Property(node) {
23
+ if (propKey(node) === 'feedbackLayout') check(node.value);
24
+ },
25
+ };
26
+ },
27
+ };
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+ const { cite } = require('../utils.cjs');
3
+
4
+ module.exports = {
5
+ meta: {
6
+ type: 'problem',
7
+ docs: { description: '不用 antd compactAlgorithm,密度由主题包三档显式定标' },
8
+ schema: [],
9
+ messages: {
10
+ compact: `不要用 compactAlgorithm:它会把种子 Token 再压一档(13px→10px、28→24);密度只在 Provider / 路由级选三档之一${cite('§2')}`,
11
+ },
12
+ },
13
+ create(context) {
14
+ return {
15
+ 'MemberExpression[property.name="compactAlgorithm"]'(node) {
16
+ context.report({ node, messageId: 'compact' });
17
+ },
18
+ 'ImportSpecifier[imported.name="compactAlgorithm"]'(node) {
19
+ context.report({ node, messageId: 'compact' });
20
+ },
21
+ };
22
+ },
23
+ };
@@ -0,0 +1,34 @@
1
+ 'use strict';
2
+ const { staticText, jsxValue, propKey, cite } = require('../utils.cjs');
3
+
4
+ const COLOR = /#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})(?![0-9a-zA-Z_-])|\b(?:rgba?|hsla?)\s*\(/;
5
+ const COLOR_KEY = /color|background|border|outline|^fill$|^stroke$|shadow/i;
6
+ const COLOR_ATTR = new Set(['color', 'fill', 'stroke', 'background', 'bgColor', 'backgroundColor']);
7
+
8
+ module.exports = {
9
+ meta: {
10
+ type: 'problem',
11
+ docs: { description: '业务代码不写色值,颜色从主题 Token / CSS 变量取' },
12
+ schema: [],
13
+ messages: {
14
+ color: `不要写死色值「{{value}}」:改用主题 Token(theme.useToken())或 var(--ind-*) 变量;状态色走 statusKey,类别色取身份色板${cite('§1 原则 3、§3.1')}`,
15
+ },
16
+ },
17
+ create(context) {
18
+ const check = (node) => {
19
+ const text = staticText(node);
20
+ if (text == null || /^\s*var\(/.test(text)) return;
21
+ const m = text.match(COLOR);
22
+ if (m) context.report({ node, messageId: 'color', data: { value: text.trim().slice(0, 40) } });
23
+ };
24
+ return {
25
+ Property(node) {
26
+ const key = propKey(node);
27
+ if (key && COLOR_KEY.test(key)) check(node.value);
28
+ },
29
+ JSXAttribute(node) {
30
+ if (node.name.type === 'JSXIdentifier' && COLOR_ATTR.has(node.name.name)) check(jsxValue(node));
31
+ },
32
+ };
33
+ },
34
+ };
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+ const { elementName, jsxValue, staticText, propKey, cite } = require('../utils.cjs');
3
+
4
+ /**
5
+ * 只检查从 antd 导入的 Tag / Badge,避免误伤同名业务组件。
6
+ * Tag 只在 color 取 antd 语义预设(success / processing / error / warning / default)时报:
7
+ * 状态不用 Tag;类别标签可以用 Tag,但不得借用语义色(§3.3),其余颜色由身份色板与 no-hardcoded-color 约束。
8
+ */
9
+ const STATUS_PRESETS = new Set(['success', 'processing', 'error', 'warning', 'default']);
10
+ const STATUS_KEYS = new Set(['wait', 'running', 'done', 'warning', 'alarm', 'closed']);
11
+ /** 枚举项的形状:同一对象里还有 label 或 value,避免误伤接口参数里的 status 字段。 */
12
+ const isEnumItem = (obj) => obj.properties.some((p) => ['label', 'value'].includes(propKey(p)));
13
+ module.exports = {
14
+ meta: {
15
+ type: 'problem',
16
+ docs: { description: '业务状态用 StatusText / 枚举项 statusKey(文字 + 颜色)呈现,不用 Tag 语义色、Badge 状态点、已弃用的 StatusPill 与枚举项 status' },
17
+ schema: [],
18
+ messages: {
19
+ tag: `Tag 的语义色「{{value}}」不能用:状态是文字 + 颜色,不用 Tag,页面用 StatusText,表格枚举列用 valueEnum 的 statusKey;类别标签不得借用语义色,改取身份色板${cite('§3.2、§3.3、§3.4')}`,
20
+ badge: `不要用 Badge 的 status 画状态点:状态是文字 + 颜色,不自绘圆点;页面用 StatusText,表格枚举列用 valueEnum 的 statusKey${cite('§3.2、§3.3')}`,
21
+ enumStatus: `枚举项的 status 已弃用(渲染图标 + 底色胶囊,不符合 v1.6):改为 statusKey: '{{value}}',按文字 + 颜色渲染${cite('§3.2、§3.3')}`,
22
+ pill: `StatusPill 已弃用(图标 + 底色,不符合 v1.6 文字 + 颜色):页面改用 StatusText,表格枚举项改配 statusKey${cite('§3.2')}`,
23
+ },
24
+ },
25
+ create(context) {
26
+ const local = { Tag: new Set(), Badge: new Set() };
27
+ return {
28
+ ImportDeclaration(node) {
29
+ if (typeof node.source.value === 'string' && node.source.value.startsWith('@nokecy/qc-ui')) {
30
+ for (const s of node.specifiers) {
31
+ if (s.type === 'ImportSpecifier' && s.imported.name === 'StatusPill') context.report({ node: s, messageId: 'pill' });
32
+ }
33
+ }
34
+ if (node.source.value !== 'antd') return;
35
+ for (const s of node.specifiers) {
36
+ if (s.type === 'ImportSpecifier' && local[s.imported.name]) local[s.imported.name].add(s.local.name);
37
+ }
38
+ },
39
+ Property(node) {
40
+ if (propKey(node) !== 'status' || node.parent.type !== 'ObjectExpression' || !isEnumItem(node.parent)) return;
41
+ const value = staticText(node.value);
42
+ if (value != null && STATUS_KEYS.has(value)) context.report({ node, messageId: 'enumStatus', data: { value } });
43
+ },
44
+ JSXOpeningElement(node) {
45
+ const name = elementName(node);
46
+ const attr = (n) => node.attributes.find((a) => a.type === 'JSXAttribute' && a.name.name === n);
47
+ if (local.Tag.has(name) && attr('color')) {
48
+ const value = staticText(jsxValue(attr('color')));
49
+ if (value != null && STATUS_PRESETS.has(value)) context.report({ node, messageId: 'tag', data: { value } });
50
+ }
51
+ if (local.Badge.has(name) && attr('status')) context.report({ node, messageId: 'badge' });
52
+ },
53
+ };
54
+ },
55
+ };
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+ const { elementName, propKey, cite } = require('../utils.cjs');
3
+
4
+ const HEIGHT_PROPS = new Set(['rowHeight', 'headerHeight', 'groupHeaderHeight', 'floatingFiltersHeight', 'getRowHeight']);
5
+ /**
6
+ * 只认表格组件:`*Table`(Table / ProTable / ArrayTable / EditableProTable)与名称含 AgGrid 的
7
+ * (AgGridReact / AgGridPlus / StandardAgGridPlus / BaseAgGridPlus)。
8
+ * react-grid-layout 的 GridLayout / ResponsiveGridLayout 也有 rowHeight,那是看板格高,不是表格行高。
9
+ */
10
+ const TABLE_LIKE = /Table$|AgGrid/;
11
+
12
+ module.exports = {
13
+ meta: {
14
+ type: 'problem',
15
+ docs: { description: '表格行高、表头高由 Provider 按密度注入,页面不自设' },
16
+ schema: [],
17
+ messages: {
18
+ height: `不要在页面里设置 {{name}}:行高与表头高由 Provider 按密度统一注入(AG Grid 同理)${cite('§2')}`,
19
+ },
20
+ },
21
+ create(context) {
22
+ return {
23
+ JSXAttribute(node) {
24
+ if (node.name.type !== 'JSXIdentifier' || !HEIGHT_PROPS.has(node.name.name)) return;
25
+ const name = elementName(node.parent);
26
+ if (name && TABLE_LIKE.test(name)) context.report({ node, messageId: 'height', data: { name: node.name.name } });
27
+ },
28
+ // gridOptions={{ rowHeight: 40 }}
29
+ 'JSXAttribute[name.name="gridOptions"] Property'(node) {
30
+ const key = propKey(node);
31
+ if (key && HEIGHT_PROPS.has(key)) context.report({ node, messageId: 'height', data: { name: key } });
32
+ },
33
+ };
34
+ },
35
+ };
@@ -0,0 +1,25 @@
1
+ 'use strict';
2
+ const { staticText, cite } = require('../utils.cjs');
3
+
4
+ const VIEWPORT_CALC = /calc\(\s*100[sdl]?vh\s*-/;
5
+
6
+ module.exports = {
7
+ meta: {
8
+ type: 'problem',
9
+ docs: { description: '禁止 calc(100vh - NNNpx) 这类魔数,表格高度由容器实际尺寸计算' },
10
+ schema: [],
11
+ messages: {
12
+ calc: `不要写 calc(100vh - …):列表页内容区固定为视口高,表格占满剩余高度并在内部滚动,高度由容器实际尺寸计算${cite('§4.0 铺满规则')}`,
13
+ },
14
+ },
15
+ create(context) {
16
+ const check = (node) => {
17
+ const text = staticText(node);
18
+ if (text != null && VIEWPORT_CALC.test(text)) context.report({ node, messageId: 'calc' });
19
+ };
20
+ return {
21
+ Literal: check,
22
+ TemplateLiteral: check,
23
+ };
24
+ },
25
+ };
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+ const { jsxValue, propKey, elementName, cite } = require('../utils.cjs');
3
+
4
+ const WIDTH_KEYS = new Set(['width', 'minWidth', 'maxWidth']);
5
+
6
+ /** 数字或 'NNpx' 字符串 → 像素值;百分比、关键字等返回 null。 */
7
+ function pixels(node) {
8
+ if (!node || node.type !== 'Literal') return null;
9
+ if (typeof node.value === 'number') return node.value;
10
+ const m = typeof node.value === 'string' && node.value.trim().match(/^(\d+(?:\.\d+)?)px$/);
11
+ return m ? Number(m[1]) : null;
12
+ }
13
+
14
+ module.exports = {
15
+ meta: {
16
+ type: 'suggestion',
17
+ docs: { description: '宽度取 4px 栅格整数倍' },
18
+ schema: [],
19
+ messages: {
20
+ grid: `宽度 {{value}} 不是 4 的整数倍:字段宽度取 4px 栅格,不出现 163、177 这类碎数${cite('§6.3')}`,
21
+ },
22
+ },
23
+ create(context) {
24
+ const check = (node) => {
25
+ const px = pixels(node);
26
+ if (px != null && px > 4 && px % 4 !== 0) context.report({ node, messageId: 'grid', data: { value: String(px) } });
27
+ };
28
+ return {
29
+ Property(node) {
30
+ const key = propKey(node);
31
+ if (key && WIDTH_KEYS.has(key)) check(node.value);
32
+ },
33
+ JSXAttribute(node) {
34
+ if (!WIDTH_KEYS.has(node.name.name)) return;
35
+ const name = elementName(node.parent);
36
+ // 只看组件(大写开头),svg / img 等原生元素的 width 属性不受此约束
37
+ if (name && /^[A-Z]/.test(name)) check(jsxValue(node));
38
+ },
39
+ };
40
+ },
41
+ };
@@ -0,0 +1,19 @@
1
+ 'use strict';
2
+ /**
3
+ * `.less` / `.css` 里的同一组红线(ESLint 读不到样式文件)。
4
+ * 只用 stylelint 核心规则,兼容 Umi 固定的 stylelint 14。
5
+ * 主题单源文件(定义 Token 的那一两份)在项目 package.json 的 "qc-ui-lint".ignore 中登记排除。
6
+ */
7
+ module.exports = {
8
+ rules: {
9
+ 'declaration-property-value-disallowed-list': [
10
+ {
11
+ '/color|background|border|outline|^fill$|^stroke$|shadow/': ['/#[0-9a-fA-F]{3,8}\\b/', '/\\b(rgba?|hsla?)\\(/'],
12
+ '/^(height|min-height|max-height)$/': ['/calc\\(\\s*100[sdl]?vh\\s*-/'],
13
+ },
14
+ {
15
+ message: '不要写死色值或 calc(100vh - …):颜色用 var(--ind-*) / Less 变量,表格高度由容器实际尺寸计算(DESIGN.md §3.1、§4.0)',
16
+ },
17
+ ],
18
+ },
19
+ };
package/lint/utils.cjs ADDED
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+
3
+ /** 取字面量或模板字符串的文本;模板里的表达式以空串占位,便于做模式匹配。 */
4
+ function staticText(node) {
5
+ if (!node) return null;
6
+ if (node.type === 'Literal' && typeof node.value === 'string') return node.value;
7
+ if (node.type === 'TemplateLiteral') return node.quasis.map((q) => q.value.cooked ?? q.value.raw).join('');
8
+ return null;
9
+ }
10
+
11
+ /** JSX 属性值:`a="x"`、`a={'x'}`、`a={10}` 统一取出表达式节点。 */
12
+ function jsxValue(attr) {
13
+ const v = attr.value;
14
+ if (!v) return null;
15
+ if (v.type === 'JSXExpressionContainer') return v.expression;
16
+ return v;
17
+ }
18
+
19
+ /** 对象属性的键名(标识符或字符串键)。 */
20
+ function propKey(prop) {
21
+ if (!prop || prop.type !== 'Property' || prop.computed) return null;
22
+ if (prop.key.type === 'Identifier') return prop.key.name;
23
+ if (prop.key.type === 'Literal') return String(prop.key.value);
24
+ return null;
25
+ }
26
+
27
+ /** JSX 元素名的最后一段:`<Foo.Bar>` → `Bar`。 */
28
+ function elementName(opening) {
29
+ let n = opening.name;
30
+ while (n && n.type === 'JSXMemberExpression') n = n.property;
31
+ return n && n.type === 'JSXIdentifier' ? n.name : null;
32
+ }
33
+
34
+ const SPEC = '(工业界面设计规范 DESIGN.md';
35
+ const cite = (section) => `${SPEC} ${section})`;
36
+
37
+ module.exports = { staticText, jsxValue, propKey, elementName, cite };
package/package.json CHANGED
@@ -1,12 +1,15 @@
1
1
  {
2
2
  "name": "@nokecy/qc-ui",
3
- "version": "2.0.0-beta.16",
3
+ "version": "2.0.0-beta.18",
4
4
  "description": "Backward-compatible QC_UI public API",
5
5
  "license": "MIT",
6
6
  "private": false,
7
7
  "main": "dist/cjs/index.js",
8
8
  "module": "dist/esm/index.js",
9
9
  "types": "dist/esm/index.d.ts",
10
+ "bin": {
11
+ "qc-ui-lint": "lint/cli.cjs"
12
+ },
10
13
  "exports": {
11
14
  ".": {
12
15
  "types": "./dist/esm/index.d.ts",
@@ -15,6 +18,8 @@
15
18
  },
16
19
  "./package.json": "./package.json",
17
20
  "./dist/*": "./dist/*",
21
+ "./eslint-plugin": "./lint/index.cjs",
22
+ "./stylelint-config": "./lint/stylelint.cjs",
18
23
  "./*": {
19
24
  "types": "./dist/esm/*.d.ts",
20
25
  "import": "./dist/esm/*.js",
@@ -2277,6 +2282,8 @@
2277
2282
  ],
2278
2283
  "files": [
2279
2284
  "dist",
2285
+ "lint",
2286
+ "agent",
2280
2287
  "LICENSE*",
2281
2288
  "README.md"
2282
2289
  ],
@@ -2285,9 +2292,9 @@
2285
2292
  "typecheck": "tsc --noEmit -p tsconfig.json"
2286
2293
  },
2287
2294
  "dependencies": {
2288
- "@nokecy/qc-ui-business": "2.0.0-beta.16",
2289
- "@nokecy/qc-ui-components": "2.0.0-beta.16",
2290
- "@nokecy/qc-ui-form-designer": "2.0.0-beta.16"
2295
+ "@nokecy/qc-ui-business": "2.0.0-beta.18",
2296
+ "@nokecy/qc-ui-components": "2.0.0-beta.18",
2297
+ "@nokecy/qc-ui-form-designer": "2.0.0-beta.18"
2291
2298
  },
2292
2299
  "peerDependencies": {
2293
2300
  "react": ">=19.0.0 <20",