designsnitch 0.3.0 → 0.5.0
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/README.ko.md +128 -33
- package/README.md +128 -33
- package/package.json +1 -1
- package/skills/designsnitch-check/SKILL.md +38 -13
- package/skills/designsnitch-eslint/SKILL.md +2 -0
- package/skills/designsnitch-palette/SKILL.md +11 -9
- package/skills/designsnitch-setup/SKILL.md +23 -8
- package/src/check.js +175 -35
- package/src/cli.js +2 -2
- package/src/colors.js +17 -12
- package/src/config.js +26 -3
- package/src/core/classes.js +13 -9
- package/src/core/color.js +133 -9
- package/src/core/css.js +42 -13
- package/src/core/named-colors.js +35 -0
- package/src/core/oklch.js +58 -0
- package/src/core/tokens.js +74 -6
- package/src/format.js +5 -3
- package/src/hook.js +1 -5
- package/src/messages.js +60 -12
- package/src/rules/color-unknown.js +8 -9
- package/src/rules/color-use-token.js +32 -14
- package/src/rules/load-tokens.js +203 -14
- package/src/rules/tailwind-config.js +77 -0
- package/src/rules/unchecked-colors.js +26 -0
- package/src/rules/use-ds-component.js +2 -2
- package/src/rules/visit-style.js +71 -0
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { findArbitraryColors } from "../core/classes.js";
|
|
2
|
-
import {
|
|
2
|
+
import { normalizeColor } from "../core/color.js";
|
|
3
3
|
import { loadTokens } from "./load-tokens.js";
|
|
4
4
|
import { ruleMessages, TEXT } from "./suggest.js";
|
|
5
5
|
import { visitStrings } from "./visit-strings.js";
|
|
6
|
+
import { mergeVisitors, visitInlineStyleColors } from "./visit-style.js";
|
|
6
7
|
|
|
7
8
|
/** @type {import("eslint").Rule.RuleModule} */
|
|
8
9
|
export default {
|
|
@@ -23,13 +24,11 @@ export default {
|
|
|
23
24
|
const m = ruleMessages(context);
|
|
24
25
|
const { colors } = tokens;
|
|
25
26
|
|
|
26
|
-
|
|
27
|
-
if (colors.has(
|
|
28
|
-
context.report({
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
});
|
|
33
|
-
});
|
|
27
|
+
function report(found, { loc }) {
|
|
28
|
+
if (colors.has(normalizeColor(found.value))) return;
|
|
29
|
+
context.report({ loc, messageId: "unknown", data: { text: m.unknownColor({ found: found.text }) } });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return mergeVisitors(visitStrings(context, findArbitraryColors, report), visitInlineStyleColors(context, report));
|
|
34
33
|
},
|
|
35
34
|
};
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { findArbitraryColors, tokenToClass } from "../core/classes.js";
|
|
2
|
-
import {
|
|
2
|
+
import { normalizeColor } from "../core/color.js";
|
|
3
|
+
import { cssColorPrefixes, selectColorTokens, tokenVar, utilityColorPrefixes } from "../core/tokens.js";
|
|
3
4
|
import { loadTokens } from "./load-tokens.js";
|
|
4
5
|
import { ruleMessages, suggestClasses, TEXT } from "./suggest.js";
|
|
5
6
|
import { visitStrings } from "./visit-strings.js";
|
|
7
|
+
import { mergeVisitors, visitInlineStyleColors } from "./visit-style.js";
|
|
6
8
|
|
|
7
9
|
/** @type {import("eslint").Rule.RuleModule} */
|
|
8
10
|
export default {
|
|
@@ -11,7 +13,7 @@ export default {
|
|
|
11
13
|
docs: { description: "Use the token instead of writing its color as a hex value" },
|
|
12
14
|
hasSuggestions: true,
|
|
13
15
|
schema: [],
|
|
14
|
-
messages: { useToken: TEXT, useTokenThemed: TEXT, replace: TEXT, tokensConfig: TEXT },
|
|
16
|
+
messages: { useToken: TEXT, useTokenThemed: TEXT, useTokenClassOnly: TEXT, replace: TEXT, tokensConfig: TEXT },
|
|
15
17
|
},
|
|
16
18
|
create(context) {
|
|
17
19
|
let tokens;
|
|
@@ -25,25 +27,41 @@ export default {
|
|
|
25
27
|
};
|
|
26
28
|
}
|
|
27
29
|
const m = ruleMessages(context);
|
|
28
|
-
const { colors, themed } = tokens;
|
|
30
|
+
const { colors, themed, prefer, classOnly } = tokens;
|
|
29
31
|
|
|
30
|
-
|
|
31
|
-
const tokenNames = colors.get(normalizeHex(found.value));
|
|
32
|
-
if (!tokenNames) return;
|
|
33
|
-
const classes = tokenNames.map((name) => tokenToClass(found.utility, name));
|
|
32
|
+
function report(found, { loc, range }, tokenNames, candidates) {
|
|
34
33
|
const messageId = tokenNames.some((name) => themed.has(name)) ? "useTokenThemed" : "useToken";
|
|
35
34
|
context.report({
|
|
36
35
|
loc,
|
|
37
36
|
messageId,
|
|
38
37
|
data: {
|
|
39
|
-
text: m[messageId]({
|
|
40
|
-
found: found.text,
|
|
41
|
-
tokens: tokenNames.join(", "),
|
|
42
|
-
candidates: classes.join(", "),
|
|
43
|
-
}),
|
|
38
|
+
text: m[messageId]({ found: found.text, tokens: tokenNames.join(", "), candidates: candidates.join(", ") }),
|
|
44
39
|
},
|
|
45
|
-
suggest: suggestClasses(range,
|
|
40
|
+
suggest: suggestClasses(range, candidates, m),
|
|
46
41
|
});
|
|
47
|
-
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return mergeVisitors(
|
|
45
|
+
visitStrings(context, findArbitraryColors, (found, where) => {
|
|
46
|
+
const names = colors.get(normalizeColor(found.value));
|
|
47
|
+
if (!names) return;
|
|
48
|
+
const tokenNames = selectColorTokens(names, prefer, utilityColorPrefixes(found.utility));
|
|
49
|
+
report(found, where, tokenNames, tokenNames.map((name) => tokenToClass(found.utility, name)));
|
|
50
|
+
}),
|
|
51
|
+
// 인라인 스타일은 클래스가 아니라 var(--토큰) 으로 바꾼다. Tailwind 는 소스에서 쓴 var() 의 변수를 내보낸다.
|
|
52
|
+
visitInlineStyleColors(context, (found, where) => {
|
|
53
|
+
const known = colors.get(normalizeColor(found.value));
|
|
54
|
+
if (!known) return;
|
|
55
|
+
// 클래스로만 쓸 수 있는 토큰은 스타일 값을 대신할 수 없다. 그래도 직접 쓴 색이라는 것은 알린다.
|
|
56
|
+
const names = known.filter((name) => !classOnly.has(name));
|
|
57
|
+
if (names.length === 0) {
|
|
58
|
+
const text = m.useTokenClassOnly({ found: found.text, tokens: known.join(", ") });
|
|
59
|
+
context.report({ loc: where.loc, messageId: "useTokenClassOnly", data: { text } });
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const tokenNames = selectColorTokens(names, prefer, cssColorPrefixes(found.property));
|
|
63
|
+
report(found, where, tokenNames, tokenNames.map((name) => tokenVar(name, tokens.prefix)));
|
|
64
|
+
}),
|
|
65
|
+
);
|
|
48
66
|
},
|
|
49
67
|
};
|
package/src/rules/load-tokens.js
CHANGED
|
@@ -1,16 +1,30 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
2
3
|
import path from "node:path";
|
|
3
|
-
import
|
|
4
|
+
import postcss from "postcss";
|
|
5
|
+
import { invalidTokenField, tokenSettings } from "../config.js";
|
|
6
|
+
import { parseColorTokenData, parsePaletteColors } from "../core/tokens.js";
|
|
4
7
|
import { messages, resolveLang } from "../messages.js";
|
|
8
|
+
import { flattenColors, loadConfigColors } from "./tailwind-config.js";
|
|
5
9
|
|
|
6
10
|
/**
|
|
7
11
|
* @typedef {object} Tokens
|
|
8
12
|
* @property {Map<string, string[]>} colors 색 값 → 토큰 이름들
|
|
9
13
|
* @property {Set<string>} themed 테마마다 값이 다른 토큰 이름들
|
|
14
|
+
* @property {string[]} prefer 먼저 적용할 토큰 접두어
|
|
15
|
+
* @property {Set<string>} paletteNames 기본 팔레트에서 온 토큰 이름들. palette 설정이 없으면 비어 있다
|
|
16
|
+
* @property {Set<string>} files 토큰을 읽은 파일들의 절대 경로. 토큰 CSS, 그것이 @import 한 CSS, Tailwind JavaScript 설정
|
|
17
|
+
* @property {string | null} prefix Tailwind 접두어. @import "tailwindcss" prefix(tw) 의 tw
|
|
18
|
+
* @property {Set<string>} classOnly 클래스로만 쓸 수 있는 토큰 이름들. JavaScript 설정의 색에는 CSS 변수가 없다
|
|
19
|
+
* @property {string[]} problems 토큰을 다 읽지 못하게 만든 문제. 예: 불러오지 못한 JavaScript 설정
|
|
10
20
|
*/
|
|
11
21
|
|
|
12
|
-
/** @
|
|
22
|
+
/** @typedef {ReturnType<typeof parseColorTokenData> & Pick<Tokens, "files" | "prefix" | "classOnly" | "problems">} ProjectTokens */
|
|
23
|
+
|
|
24
|
+
/** @type {Map<string, { deps: [string, number][], tokens: ProjectTokens }>} */
|
|
13
25
|
const cache = new Map();
|
|
26
|
+
/** @type {Map<string, { mtimeMs: number, result: { palette: Map<string, string>, classOnly: boolean } }>} */
|
|
27
|
+
const paletteCache = new Map();
|
|
14
28
|
|
|
15
29
|
/**
|
|
16
30
|
* settings.designsnitch.tokens 에 적힌 CSS를 읽어 토큰을 돌려준다.
|
|
@@ -19,30 +33,205 @@ const cache = new Map();
|
|
|
19
33
|
*/
|
|
20
34
|
export function loadTokens(settings, cwd) {
|
|
21
35
|
const m = messages(resolveLang(settings?.designsnitch?.lang));
|
|
22
|
-
const
|
|
23
|
-
|
|
36
|
+
const tokens = settings?.designsnitch?.tokens;
|
|
37
|
+
const invalidField = invalidTokenField(tokens);
|
|
38
|
+
if (invalidField === "tokens") throw new Error(m.tokensSettingMissing());
|
|
39
|
+
if (invalidField) throw new Error(m.invalidTokenSetting({ field: invalidField }));
|
|
24
40
|
|
|
25
|
-
const file =
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
41
|
+
const { file: tokensPath, exclude = [], prefer = [] } = tokenSettings(tokens);
|
|
42
|
+
const root = path.resolve(cwd, settings?.designsnitch?.root ?? ".");
|
|
43
|
+
const file = path.resolve(root, tokensPath);
|
|
44
|
+
const project = readProjectTokens(file, root, exclude, m);
|
|
45
|
+
const { files, prefix, classOnly, problems } = project;
|
|
46
|
+
const shared = { prefer, files, prefix, classOnly, problems };
|
|
47
|
+
if (settings?.designsnitch?.palette !== "tailwind") {
|
|
48
|
+
return { colors: project.colors, themed: project.themed, paletteNames: new Set(), ...shared };
|
|
49
|
+
}
|
|
50
|
+
return { ...shared, ...withPalette(project, readTailwindPalette(file, m), exclude) };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** @returns {ProjectTokens} */
|
|
54
|
+
function readProjectTokens(file, root, exclude, m) {
|
|
55
|
+
const key = JSON.stringify([file, exclude]);
|
|
56
|
+
const cached = cache.get(key);
|
|
57
|
+
if (cached && cached.deps.every(([dep, mtimeMs]) => mtimeOf(dep) === mtimeMs)) return cached.tokens;
|
|
30
58
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
59
|
+
// tokens 에 tailwind.config.js 같은 JavaScript 설정을 직접 적은 경우. Tailwind v3 프로젝트가 그렇다.
|
|
60
|
+
const isConfig = JS_FILE.test(file);
|
|
61
|
+
const sources = [];
|
|
62
|
+
const configFiles = isConfig ? [file] : [];
|
|
63
|
+
let prefix = null;
|
|
64
|
+
let usesV3Directives = false;
|
|
65
|
+
let current = file;
|
|
66
|
+
try {
|
|
67
|
+
if (isConfig && !fs.existsSync(file)) throw Object.assign(new Error("missing"), { code: "ENOENT" });
|
|
68
|
+
// 토큰 CSS 가 @import 한 CSS 도 토큰을 정의할 수 있다. 예: @import "../brand/theme.css"
|
|
69
|
+
const visit = (cssFile) => {
|
|
70
|
+
if (sources.some(([seen]) => seen === cssFile)) return;
|
|
71
|
+
current = cssFile;
|
|
72
|
+
const css = fs.readFileSync(cssFile, "utf8");
|
|
73
|
+
const entry = [cssFile, css];
|
|
74
|
+
sources.push(entry);
|
|
75
|
+
const sheet = postcss.parse(css, { from: cssFile });
|
|
76
|
+
sheet.walkAtRules("tailwind", () => {
|
|
77
|
+
usesV3Directives = true;
|
|
78
|
+
});
|
|
79
|
+
sheet.walkAtRules("config", (rule) => {
|
|
80
|
+
const spec = /^["']([^"']+)["']/.exec(rule.params)?.[1];
|
|
81
|
+
if (spec) configFiles.push(path.resolve(path.dirname(cssFile), spec));
|
|
82
|
+
});
|
|
83
|
+
sheet.walkAtRules("import", (rule) => {
|
|
84
|
+
const spec = /^(?:url\(\s*)?["']([^"']+)["']/.exec(rule.params)?.[1];
|
|
85
|
+
if (!spec) return;
|
|
86
|
+
if (spec === "tailwindcss") {
|
|
87
|
+
prefix = /\bprefix\(\s*([\w-]+)\s*\)/.exec(rule.params)?.[1] ?? prefix;
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
// Tailwind 자신의 CSS 는 palette 설정이 맡는다.
|
|
91
|
+
if (spec.startsWith("tailwindcss/") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(spec)) return;
|
|
92
|
+
const imported = resolveImport(cssFile, spec);
|
|
93
|
+
if (imported) visit(imported);
|
|
94
|
+
});
|
|
95
|
+
current = cssFile;
|
|
96
|
+
};
|
|
97
|
+
if (!isConfig) visit(file);
|
|
34
98
|
} catch (error) {
|
|
35
99
|
if (error.code === "ENOENT" || error.code === "ENOTDIR") {
|
|
36
|
-
throw new Error(m.tokensFileMissing({ file }));
|
|
100
|
+
throw new Error(m.tokensFileMissing({ file: current }));
|
|
37
101
|
}
|
|
38
102
|
// 기준이 되는 파일이 깨져 있으면 무엇도 판정할 수 없다. 어디가 깨졌는지 알려준다.
|
|
39
103
|
throw new Error(
|
|
40
104
|
m.tokensUnreadable({
|
|
41
|
-
file,
|
|
105
|
+
file: current,
|
|
42
106
|
line: error.line ?? 1,
|
|
43
107
|
column: error.column ?? 1,
|
|
44
108
|
reason: error.reason ?? error.message,
|
|
45
109
|
}),
|
|
46
110
|
);
|
|
47
111
|
}
|
|
112
|
+
|
|
113
|
+
// Tailwind v3 는 @config 없이 프로젝트 루트의 tailwind.config 를 읽는다. @tailwind 지시어가 v3 의 표시다.
|
|
114
|
+
if (usesV3Directives && configFiles.length === 0) {
|
|
115
|
+
const found = V3_CONFIG_NAMES.map((name) => path.join(root, name)).find((candidate) => fs.existsSync(candidate));
|
|
116
|
+
if (found) configFiles.push(found);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// import 된 파일의 선언이 먼저 오도록 뒤집어 합친다. 순서는 결과에 영향을 주지 않지만 읽기 쉽다.
|
|
120
|
+
const parsed = parseColorTokenData(sources.map(([, css]) => css).reverse().join("\n"), exclude);
|
|
121
|
+
const { classOnly, problems } = addConfigColors(parsed, configFiles, exclude, m);
|
|
122
|
+
// 기준으로 적은 설정을 못 읽으면 판정할 것이 없다. @config 로 딸려 온 설정이면 알리기만 하고 계속한다.
|
|
123
|
+
if (isConfig && problems.length > 0) throw new Error(problems[0]);
|
|
124
|
+
// 링크된 경로로 들어와도 같은 파일로 알아보도록 실제 경로로 적어 둔다.
|
|
125
|
+
const deps = [...sources.map(([cssFile]) => cssFile), ...configFiles];
|
|
126
|
+
const files = new Set(deps.filter((dep) => fs.existsSync(dep)).map((dep) => fs.realpathSync(dep)));
|
|
127
|
+
const tokens = { ...parsed, files, prefix, classOnly, problems };
|
|
128
|
+
cache.set(key, { deps: deps.map((dep) => [dep, mtimeOf(dep)]), tokens });
|
|
129
|
+
return tokens;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const JS_FILE = /\.[cm]?[jt]s$/;
|
|
133
|
+
const V3_CONFIG_NAMES = ["tailwind.config.js", "tailwind.config.cjs", "tailwind.config.mjs", "tailwind.config.ts"];
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* @config 로 불러온 JavaScript 설정의 색을 CSS 에서 읽은 토큰에 더한다. 같은 이름이면 CSS 가 이긴다.
|
|
137
|
+
* @param {ReturnType<typeof parseColorTokenData>} parsed 여기에 더한다
|
|
138
|
+
*/
|
|
139
|
+
function addConfigColors(parsed, configFiles, exclude, m) {
|
|
140
|
+
const classOnly = new Set();
|
|
141
|
+
const problems = [];
|
|
142
|
+
const excluded = (name) => exclude.some((p) => (p.endsWith("*") ? name.startsWith(p.slice(0, -1)) : name === p));
|
|
143
|
+
for (const file of configFiles) {
|
|
144
|
+
let config;
|
|
145
|
+
try {
|
|
146
|
+
config = loadConfigColors(file);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
problems.push(m.tailwindConfigFailed({ file, reason: error.message.split("\n")[0] }));
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (config.replacesPalette) parsed.resets.push("--color-*");
|
|
152
|
+
for (const [name, color] of config.colors) {
|
|
153
|
+
if (parsed.names.has(name) || excluded(name)) continue;
|
|
154
|
+
parsed.names.add(name);
|
|
155
|
+
classOnly.add(name);
|
|
156
|
+
parsed.colors.set(color, [...(parsed.colors.get(color) ?? []), name]);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return { classOnly, problems };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function mtimeOf(file) {
|
|
163
|
+
try {
|
|
164
|
+
return fs.statSync(file).mtimeMs;
|
|
165
|
+
} catch {
|
|
166
|
+
return -1;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** @import 의 경로를 파일로 푼다. CSS 처럼 상대 경로를 먼저 보고, 없으면 패키지에서 찾는다. 못 찾으면 null. */
|
|
171
|
+
function resolveImport(fromFile, spec) {
|
|
172
|
+
const relative = path.resolve(path.dirname(fromFile), spec);
|
|
173
|
+
if (fs.existsSync(relative) && fs.statSync(relative).isFile()) return relative;
|
|
174
|
+
if (spec.startsWith(".") || spec.startsWith("/")) return null;
|
|
175
|
+
try {
|
|
176
|
+
return createRequire(fromFile).resolve(spec);
|
|
177
|
+
} catch {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 프로젝트에 설치된 tailwindcss 의 theme.css 에서 기본 팔레트를 읽는다.
|
|
184
|
+
* 토큰 CSS 가 tailwindcss 를 불러오는 파일이므로, 그 위치에서 찾는다.
|
|
185
|
+
*/
|
|
186
|
+
function readTailwindPalette(tokensFile, m) {
|
|
187
|
+
const require = createRequire(tokensFile);
|
|
188
|
+
let file;
|
|
189
|
+
let classOnly = false;
|
|
190
|
+
try {
|
|
191
|
+
file = require.resolve("tailwindcss/theme.css");
|
|
192
|
+
} catch {
|
|
193
|
+
// v3 에는 theme.css 가 없다. 팔레트는 tailwindcss/colors 에 있고, CSS 변수가 없어 클래스로만 쓴다.
|
|
194
|
+
try {
|
|
195
|
+
file = require.resolve("tailwindcss/colors");
|
|
196
|
+
classOnly = true;
|
|
197
|
+
} catch {
|
|
198
|
+
throw new Error(m.paletteMissing({ root: path.dirname(tokensFile) }));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const { mtimeMs } = fs.statSync(file);
|
|
202
|
+
const cached = paletteCache.get(file);
|
|
203
|
+
if (cached?.mtimeMs === mtimeMs) return cached.result;
|
|
204
|
+
let palette;
|
|
205
|
+
if (classOnly) {
|
|
206
|
+
const module = require(file);
|
|
207
|
+
palette = flattenColors(module.default ?? module);
|
|
208
|
+
} else {
|
|
209
|
+
palette = parsePaletteColors(fs.readFileSync(file, "utf8"));
|
|
210
|
+
}
|
|
211
|
+
const result = { palette, classOnly };
|
|
212
|
+
paletteCache.set(file, { mtimeMs, result });
|
|
213
|
+
return result;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 프로젝트 토큰 뒤에 팔레트 색을 더한다. 다음 색은 뺀다.
|
|
218
|
+
* - 프로젝트가 같은 이름을 다시 정의한 색 (값을 읽지 못했어도 기본값은 더 이상 쓰이지 않는다)
|
|
219
|
+
* - 프로젝트가 --color-*: initial, --*: initial 같은 선언으로 비운 네임스페이스의 색
|
|
220
|
+
* - exclude 에 걸린 색
|
|
221
|
+
* @param {ProjectTokens} project
|
|
222
|
+
* @param {{ palette: Map<string, string>, classOnly: boolean }} tailwind classOnly 면 팔레트 색에 CSS 변수가 없다 (v3)
|
|
223
|
+
* @param {string[]} exclude
|
|
224
|
+
*/
|
|
225
|
+
function withPalette(project, { palette, classOnly: paletteIsClassOnly }, exclude) {
|
|
226
|
+
const matches = (name, pattern) => (pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
|
|
227
|
+
const excluded = (name) => [...exclude, ...project.resets].some((pattern) => matches(name, pattern));
|
|
228
|
+
const colors = new Map([...project.colors].map(([hex, names]) => [hex, [...names]]));
|
|
229
|
+
const paletteNames = new Set();
|
|
230
|
+
for (const [name, hex] of palette) {
|
|
231
|
+
if (project.names.has(name) || excluded(name)) continue;
|
|
232
|
+
paletteNames.add(name);
|
|
233
|
+
colors.set(hex, [...(colors.get(hex) ?? []), name]);
|
|
234
|
+
}
|
|
235
|
+
const classOnly = paletteIsClassOnly ? new Set([...project.classOnly, ...paletteNames]) : project.classOnly;
|
|
236
|
+
return { colors, themed: project.themed, paletteNames, classOnly };
|
|
48
237
|
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { normalizeColor } from "../core/color.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @config 로 불러오는 Tailwind JavaScript 설정에서 색을 읽는다. Tailwind v4 의 동작을 따른다.
|
|
6
|
+
* - theme.extend.colors 는 색을 더한다. theme.colors 는 기본 팔레트를 대체한다.
|
|
7
|
+
* - 프리셋(presets)의 색도 같은 방식으로 합친다.
|
|
8
|
+
* - 이 색들은 클래스(bg-brand-500)로만 쓸 수 있다. Tailwind 가 CSS 변수를 만들지 않기 때문이다.
|
|
9
|
+
* 설정 파일을 실행하므로, 그 파일이 require 하는 것이 설치되어 있어야 한다.
|
|
10
|
+
* @param {string} file 설정 파일의 절대 경로
|
|
11
|
+
* @returns {{ colors: Map<string, string>, replacesPalette: boolean }} colors 는 토큰 이름(--color-brand-500) → 비교용 색 표기
|
|
12
|
+
* @throws 설정을 불러오지 못했을 때
|
|
13
|
+
*/
|
|
14
|
+
export function loadConfigColors(file) {
|
|
15
|
+
const require = createRequire(file);
|
|
16
|
+
const resolved = require.resolve(file);
|
|
17
|
+
// 에디터처럼 오래 떠 있는 프로세스에서도 바뀐 설정을 다시 읽는다. ESM 설정은 Node 가 캐시를 비워 주지 않는다.
|
|
18
|
+
delete require.cache[resolved];
|
|
19
|
+
const loaded = require(resolved);
|
|
20
|
+
|
|
21
|
+
let palette = {};
|
|
22
|
+
try {
|
|
23
|
+
const module = require("tailwindcss/colors");
|
|
24
|
+
palette = module.default ?? module;
|
|
25
|
+
} catch {
|
|
26
|
+
// tailwindcss/colors 를 쓰지 않는 설정이면 없어도 된다.
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const result = { colors: new Map(), replacesPalette: false };
|
|
30
|
+
collect(loaded?.default ?? loaded, palette, result);
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function collect(config, palette, result) {
|
|
35
|
+
if (!config || typeof config !== "object") return;
|
|
36
|
+
for (const preset of Array.isArray(config.presets) ? config.presets : []) collect(preset?.default ?? preset, palette, result);
|
|
37
|
+
|
|
38
|
+
const section = (value) => {
|
|
39
|
+
if (typeof value !== "function") return value;
|
|
40
|
+
try {
|
|
41
|
+
return value({ colors: palette, theme: () => undefined });
|
|
42
|
+
} catch {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const replaced = section(config.theme?.colors);
|
|
47
|
+
if (replaced && typeof replaced === "object") {
|
|
48
|
+
result.replacesPalette = true;
|
|
49
|
+
result.colors.clear();
|
|
50
|
+
flattenColors(replaced, result.colors);
|
|
51
|
+
}
|
|
52
|
+
flattenColors(section(config.theme?.extend?.colors), result.colors);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Tailwind 의 색 객체를 토큰 이름 → 비교용 색 표기로 편다.
|
|
57
|
+
* 예: { brand: { DEFAULT: "#f00", 500: "#a00" } } → --color-brand, --color-brand-500
|
|
58
|
+
* getter 는 읽지 않는다. tailwindcss/colors 의 옛 이름(lightBlue 등)은 읽기만 해도 경고를 찍는다.
|
|
59
|
+
* @param {unknown} colors
|
|
60
|
+
* @param {Map<string, string>} [out]
|
|
61
|
+
* @param {string} [prefix]
|
|
62
|
+
*/
|
|
63
|
+
export function flattenColors(colors, out = new Map(), prefix = "--color") {
|
|
64
|
+
if (!colors || typeof colors !== "object") return out;
|
|
65
|
+
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(colors))) {
|
|
66
|
+
if (!descriptor.enumerable || !("value" in descriptor)) continue;
|
|
67
|
+
const { value } = descriptor;
|
|
68
|
+
const name = key === "DEFAULT" ? prefix : `${prefix}-${key}`;
|
|
69
|
+
if (typeof value === "string") {
|
|
70
|
+
const color = normalizeColor(value);
|
|
71
|
+
if (color && name !== "--color") out.set(name, color);
|
|
72
|
+
} else {
|
|
73
|
+
flattenColors(value, out, name);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { findArbitraryColors } from "../core/classes.js";
|
|
2
|
+
import { findColorValues } from "../core/color.js";
|
|
3
|
+
import { visitStrings } from "./visit-strings.js";
|
|
4
|
+
import { inlineStyleProperty } from "./visit-style.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 검사 규칙이 보지 않는 문자열 속 색을 알린다. 위반이 아니라 check 가 개수를 세는 데 쓴다.
|
|
8
|
+
* 임의 값 클래스(bg-[#fff])와 인라인 스타일의 색은 다른 규칙이 검사하므로 빼고 센다.
|
|
9
|
+
* @type {import("eslint").Rule.RuleModule}
|
|
10
|
+
*/
|
|
11
|
+
export default {
|
|
12
|
+
meta: { type: "suggestion", schema: [], messages: { unchecked: "{{color}}" } },
|
|
13
|
+
create(context) {
|
|
14
|
+
const findUnchecked = (text) => {
|
|
15
|
+
const inClasses = findArbitraryColors(text).map(({ index, text: found }) => [index, index + found.length]);
|
|
16
|
+
return findColorValues(text).filter(({ index }) => !inClasses.some(([start, end]) => index >= start && index < end));
|
|
17
|
+
};
|
|
18
|
+
const visitor = visitStrings(context, findUnchecked, (found, { loc }) =>
|
|
19
|
+
context.report({ loc, messageId: "unchecked", data: { color: found.value } }),
|
|
20
|
+
);
|
|
21
|
+
const skipStyle = (handler) => (node) => {
|
|
22
|
+
if (inlineStyleProperty(node) === null && inlineStyleProperty(node.parent ?? {}) === null) handler(node);
|
|
23
|
+
};
|
|
24
|
+
return { Literal: skipStyle(visitor.Literal), TemplateElement: skipStyle(visitor.TemplateElement) };
|
|
25
|
+
},
|
|
26
|
+
};
|
|
@@ -11,12 +11,12 @@ export default {
|
|
|
11
11
|
messages: { useComponent: TEXT, useComponentAsk: TEXT },
|
|
12
12
|
},
|
|
13
13
|
create(context) {
|
|
14
|
-
const components = context.settings?.designsnitch
|
|
14
|
+
const { components, root } = context.settings?.designsnitch ?? {};
|
|
15
15
|
if (!components?.path || !components.replaces) return {};
|
|
16
16
|
const m = ruleMessages(context);
|
|
17
17
|
|
|
18
18
|
// 디자인 시스템 컴포넌트는 raw 태그로 만들어지므로 그 경로 안은 검사하지 않는다.
|
|
19
|
-
const dsDir = path.resolve(context.cwd, components.path);
|
|
19
|
+
const dsDir = path.resolve(context.cwd, root ?? ".", components.path);
|
|
20
20
|
const file = path.resolve(context.cwd, context.filename);
|
|
21
21
|
if (file.startsWith(dsDir + path.sep)) return {};
|
|
22
22
|
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { findColorValues, isColorProperty } from "../core/color.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 노드가 JSX style 속성 객체의 값이면 CSS 속성 이름을, 아니면 null 을 돌려준다.
|
|
5
|
+
* 예: <div style={{ color: "#fff" }} /> 의 "#fff" → "color"
|
|
6
|
+
* @param {import("estree").Node & { parent?: any }} node
|
|
7
|
+
* @returns {string | null}
|
|
8
|
+
*/
|
|
9
|
+
export function inlineStyleProperty(node) {
|
|
10
|
+
// color: on ? "#fff" : "#000", color: x || "#fff" 처럼 값이 고르는 식이면 그 식을 거슬러 올라간다.
|
|
11
|
+
while (
|
|
12
|
+
(node.parent?.type === "ConditionalExpression" && node.parent.test !== node) ||
|
|
13
|
+
node.parent?.type === "LogicalExpression"
|
|
14
|
+
) {
|
|
15
|
+
node = node.parent;
|
|
16
|
+
}
|
|
17
|
+
const property = node.parent;
|
|
18
|
+
if (property?.type !== "Property" || property.value !== node || property.computed) return null;
|
|
19
|
+
const object = property.parent;
|
|
20
|
+
if (object?.type !== "ObjectExpression" || object.parent?.type !== "JSXExpressionContainer") return null;
|
|
21
|
+
const attribute = object.parent.parent;
|
|
22
|
+
if (attribute?.type !== "JSXAttribute" || attribute.name?.name !== "style") return null;
|
|
23
|
+
const { key } = property;
|
|
24
|
+
if (key.type === "Identifier") return key.name;
|
|
25
|
+
return typeof key.value === "string" ? key.value : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* JSX style 속성에 문자열로 적은 색마다 onFound 를 부르는 visitor 를 만든다.
|
|
30
|
+
* @param {import("eslint").Rule.RuleContext} context
|
|
31
|
+
* @param {(found: { text: string, value: string, property: string }, where: { loc: import("estree").SourceLocation, range: [number, number] }) => void} onFound
|
|
32
|
+
*/
|
|
33
|
+
export function visitInlineStyleColors(context, onFound) {
|
|
34
|
+
const { sourceCode } = context;
|
|
35
|
+
|
|
36
|
+
function scan(node, property) {
|
|
37
|
+
for (const found of findColorValues(sourceCode.getText(node), { named: isColorProperty(property) })) {
|
|
38
|
+
const start = node.range[0] + found.index;
|
|
39
|
+
const end = start + found.text.length;
|
|
40
|
+
onFound({ ...found, property }, {
|
|
41
|
+
loc: { start: sourceCode.getLocFromIndex(start), end: sourceCode.getLocFromIndex(end) },
|
|
42
|
+
range: [start, end],
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return {
|
|
48
|
+
Literal(node) {
|
|
49
|
+
if (typeof node.value !== "string") return;
|
|
50
|
+
const property = inlineStyleProperty(node);
|
|
51
|
+
if (property !== null) scan(node, property);
|
|
52
|
+
},
|
|
53
|
+
TemplateLiteral(node) {
|
|
54
|
+
const property = inlineStyleProperty(node);
|
|
55
|
+
// ${} 안의 코드는 다른 노드가 맡는다. 문자열 부분만 본다.
|
|
56
|
+
if (property !== null) for (const quasi of node.quasis) scan(quasi, property);
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 같은 노드 종류를 여러 visitor 가 보도록 합친다. */
|
|
62
|
+
export function mergeVisitors(...visitors) {
|
|
63
|
+
const merged = {};
|
|
64
|
+
for (const visitor of visitors) {
|
|
65
|
+
for (const [type, handler] of Object.entries(visitor)) {
|
|
66
|
+
const previous = merged[type];
|
|
67
|
+
merged[type] = previous ? (node) => { previous(node); handler(node); } : handler;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return merged;
|
|
71
|
+
}
|