designsnitch 0.2.0 → 0.4.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 +139 -34
- package/README.md +159 -55
- package/bin/designsnitch.js +51 -17
- package/package.json +4 -4
- package/skills/designsnitch-check/SKILL.md +38 -14
- package/skills/designsnitch-eslint/SKILL.md +2 -0
- package/skills/designsnitch-hooks/SKILL.md +83 -8
- package/skills/designsnitch-palette/SKILL.md +8 -6
- package/skills/designsnitch-setup/SKILL.md +22 -2
- package/src/check.js +155 -45
- package/src/cli.js +33 -36
- package/src/colors.js +4 -2
- package/src/config.js +62 -26
- package/src/core/classes.js +12 -0
- package/src/core/css.js +4 -3
- package/src/core/tokens.js +66 -12
- package/src/format.js +29 -41
- package/src/hook.js +79 -20
- package/src/install.js +104 -46
- package/src/messages.js +299 -0
- package/src/rules/color-unknown.js +18 -8
- package/src/rules/color-use-token.js +39 -17
- package/src/rules/load-tokens.js +29 -24
- package/src/rules/suggest.js +12 -4
- package/src/rules/unchecked-hex.js +25 -0
- package/src/rules/use-ds-component.js +36 -12
- package/src/rules/visit-style.js +64 -0
|
@@ -1,24 +1,34 @@
|
|
|
1
1
|
import { findArbitraryColors } from "../core/classes.js";
|
|
2
2
|
import { normalizeHex } from "../core/color.js";
|
|
3
3
|
import { loadTokens } from "./load-tokens.js";
|
|
4
|
+
import { ruleMessages, TEXT } from "./suggest.js";
|
|
4
5
|
import { visitStrings } from "./visit-strings.js";
|
|
6
|
+
import { mergeVisitors, visitInlineStyleColors } from "./visit-style.js";
|
|
5
7
|
|
|
6
8
|
/** @type {import("eslint").Rule.RuleModule} */
|
|
7
9
|
export default {
|
|
8
10
|
meta: {
|
|
9
11
|
type: "suggestion",
|
|
10
|
-
docs: { description: "
|
|
12
|
+
docs: { description: "Report hex colors that have no matching token" },
|
|
11
13
|
schema: [],
|
|
12
|
-
messages: {
|
|
13
|
-
unknown: "{{found}}의 색은 토큰에 없습니다.",
|
|
14
|
-
},
|
|
14
|
+
messages: { unknown: TEXT },
|
|
15
15
|
},
|
|
16
16
|
create(context) {
|
|
17
|
-
|
|
17
|
+
let tokens;
|
|
18
|
+
try {
|
|
19
|
+
tokens = loadTokens(context.settings, context.cwd);
|
|
20
|
+
} catch {
|
|
21
|
+
// 토큰 설정 문제는 color-use-token 에서만 보고한다.
|
|
22
|
+
return {};
|
|
23
|
+
}
|
|
24
|
+
const m = ruleMessages(context);
|
|
25
|
+
const { colors } = tokens;
|
|
18
26
|
|
|
19
|
-
|
|
27
|
+
function report(found, { loc }) {
|
|
20
28
|
if (colors.has(normalizeHex(found.value))) return;
|
|
21
|
-
context.report({ loc, messageId: "unknown", data: { found: found.text } });
|
|
22
|
-
}
|
|
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));
|
|
23
33
|
},
|
|
24
34
|
};
|
|
@@ -1,38 +1,60 @@
|
|
|
1
1
|
import { findArbitraryColors, tokenToClass } from "../core/classes.js";
|
|
2
2
|
import { normalizeHex } from "../core/color.js";
|
|
3
|
+
import { cssColorPrefixes, selectColorTokens, utilityColorPrefixes } from "../core/tokens.js";
|
|
3
4
|
import { loadTokens } from "./load-tokens.js";
|
|
4
|
-
import {
|
|
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 {
|
|
9
11
|
meta: {
|
|
10
12
|
type: "problem",
|
|
11
|
-
docs: { description: "
|
|
13
|
+
docs: { description: "Use the token instead of writing its color as a hex value" },
|
|
12
14
|
hasSuggestions: true,
|
|
13
15
|
schema: [],
|
|
14
|
-
messages: {
|
|
15
|
-
...REPLACE_MESSAGES,
|
|
16
|
-
useToken: "{{found}}의 색은 토큰 {{tokens}}의 값입니다. 대신 사용: {{classes}}",
|
|
17
|
-
},
|
|
16
|
+
messages: { useToken: TEXT, useTokenThemed: TEXT, replace: TEXT, tokensConfig: TEXT },
|
|
18
17
|
},
|
|
19
18
|
create(context) {
|
|
20
|
-
|
|
19
|
+
let tokens;
|
|
20
|
+
try {
|
|
21
|
+
tokens = loadTokens(context.settings, context.cwd);
|
|
22
|
+
} catch (error) {
|
|
23
|
+
return {
|
|
24
|
+
Program(node) {
|
|
25
|
+
context.report({ node, messageId: "tokensConfig", data: { text: error.message } });
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
const m = ruleMessages(context);
|
|
30
|
+
const { colors, themed, prefer } = tokens;
|
|
21
31
|
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
if (!tokenNames) return;
|
|
25
|
-
const classes = tokenNames.map((name) => tokenToClass(found.utility, name));
|
|
32
|
+
function report(found, { loc, range }, tokenNames, candidates) {
|
|
33
|
+
const messageId = tokenNames.some((name) => themed.has(name)) ? "useTokenThemed" : "useToken";
|
|
26
34
|
context.report({
|
|
27
35
|
loc,
|
|
28
|
-
messageId
|
|
36
|
+
messageId,
|
|
29
37
|
data: {
|
|
30
|
-
found: found.text,
|
|
31
|
-
tokens: tokenNames.join(", "),
|
|
32
|
-
classes: classes.join(", "),
|
|
38
|
+
text: m[messageId]({ found: found.text, tokens: tokenNames.join(", "), candidates: candidates.join(", ") }),
|
|
33
39
|
},
|
|
34
|
-
suggest: suggestClasses(range,
|
|
40
|
+
suggest: suggestClasses(range, candidates, m),
|
|
35
41
|
});
|
|
36
|
-
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return mergeVisitors(
|
|
45
|
+
visitStrings(context, findArbitraryColors, (found, where) => {
|
|
46
|
+
const names = colors.get(normalizeHex(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 names = colors.get(normalizeHex(found.value));
|
|
54
|
+
if (!names) return;
|
|
55
|
+
const tokenNames = selectColorTokens(names, prefer, cssColorPrefixes(found.property));
|
|
56
|
+
report(found, where, tokenNames, tokenNames.map((name) => `var(${name})`));
|
|
57
|
+
}),
|
|
58
|
+
);
|
|
37
59
|
},
|
|
38
60
|
};
|
package/src/rules/load-tokens.js
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import {
|
|
3
|
+
import { invalidTokenField, tokenSettings } from "../config.js";
|
|
4
|
+
import { parseColorTokenData } from "../core/tokens.js";
|
|
5
|
+
import { messages, resolveLang } from "../messages.js";
|
|
4
6
|
|
|
5
7
|
/**
|
|
6
8
|
* @typedef {object} Tokens
|
|
7
9
|
* @property {Map<string, string[]>} colors 색 값 → 토큰 이름들
|
|
10
|
+
* @property {Set<string>} themed 테마마다 값이 다른 토큰 이름들
|
|
11
|
+
* @property {string[]} prefer 먼저 적용할 토큰 접두어
|
|
8
12
|
*/
|
|
9
13
|
|
|
10
|
-
/** @type {Map<string, { mtimeMs: number, tokens: Tokens }>} */
|
|
14
|
+
/** @type {Map<string, { mtimeMs: number, tokens: Omit<Tokens, "prefer"> }>} */
|
|
11
15
|
const cache = new Map();
|
|
12
16
|
|
|
13
17
|
/**
|
|
@@ -16,34 +20,35 @@ const cache = new Map();
|
|
|
16
20
|
* @returns {Tokens}
|
|
17
21
|
*/
|
|
18
22
|
export function loadTokens(settings, cwd) {
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
}
|
|
23
|
+
const m = messages(resolveLang(settings?.designsnitch?.lang));
|
|
24
|
+
const tokens = settings?.designsnitch?.tokens;
|
|
25
|
+
const invalidField = invalidTokenField(tokens);
|
|
26
|
+
if (invalidField === "tokens") throw new Error(m.tokensSettingMissing());
|
|
27
|
+
if (invalidField) throw new Error(m.invalidTokenSetting({ field: invalidField }));
|
|
25
28
|
|
|
26
|
-
const file =
|
|
27
|
-
|
|
29
|
+
const { file: tokensPath, exclude = [], prefer = [] } = tokenSettings(tokens);
|
|
30
|
+
const file = path.resolve(cwd, settings?.designsnitch?.root ?? ".", tokensPath);
|
|
31
|
+
const key = JSON.stringify([file, exclude]);
|
|
28
32
|
try {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const cached = cache.get(file);
|
|
35
|
-
if (cached?.mtimeMs === stat.mtimeMs) return cached.tokens;
|
|
33
|
+
const { mtimeMs } = fs.statSync(file);
|
|
34
|
+
const cached = cache.get(key);
|
|
35
|
+
if (cached?.mtimeMs === mtimeMs) return { ...cached.tokens, prefer };
|
|
36
36
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
const parsed = parseColorTokenData(fs.readFileSync(file, "utf8"), exclude);
|
|
38
|
+
cache.set(key, { mtimeMs, tokens: parsed });
|
|
39
|
+
return { ...parsed, prefer };
|
|
40
40
|
} catch (error) {
|
|
41
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR") {
|
|
42
|
+
throw new Error(m.tokensFileMissing({ file }));
|
|
43
|
+
}
|
|
41
44
|
// 기준이 되는 파일이 깨져 있으면 무엇도 판정할 수 없다. 어디가 깨졌는지 알려준다.
|
|
42
45
|
throw new Error(
|
|
43
|
-
|
|
46
|
+
m.tokensUnreadable({
|
|
47
|
+
file,
|
|
48
|
+
line: error.line ?? 1,
|
|
49
|
+
column: error.column ?? 1,
|
|
50
|
+
reason: error.reason ?? error.message,
|
|
51
|
+
}),
|
|
44
52
|
);
|
|
45
53
|
}
|
|
46
|
-
const tokens = { colors };
|
|
47
|
-
cache.set(file, { mtimeMs: stat.mtimeMs, tokens });
|
|
48
|
-
return tokens;
|
|
49
54
|
}
|
package/src/rules/suggest.js
CHANGED
|
@@ -1,16 +1,24 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { messages, resolveLang } from "../messages.js";
|
|
2
|
+
|
|
3
|
+
/** 규칙의 문장은 실행할 때 언어에 맞춰 만든다. meta.messages 에는 자리만 둔다. */
|
|
4
|
+
export const TEXT = "{{text}}";
|
|
5
|
+
|
|
6
|
+
/** 규칙이 쓸 언어의 문장들. settings.designsnitch.lang, 환경 변수, 영어 순으로 정한다. */
|
|
7
|
+
export function ruleMessages(context) {
|
|
8
|
+
return messages(resolveLang(context.settings?.designsnitch?.lang));
|
|
9
|
+
}
|
|
3
10
|
|
|
4
11
|
/**
|
|
5
12
|
* 찾은 클래스를 후보 클래스로 바꾸는 제안 목록을 만든다.
|
|
6
13
|
* 후보가 하나여도 자동 수정이 아니라 제안으로 둔다. 무엇으로 바꿀지는 쓰는 쪽이 정한다.
|
|
7
14
|
* @param {[number, number]} range 찾은 클래스의 소스 범위
|
|
8
15
|
* @param {string[]} classNames
|
|
16
|
+
* @param {ReturnType<typeof messages>} m
|
|
9
17
|
*/
|
|
10
|
-
export function suggestClasses(range, classNames) {
|
|
18
|
+
export function suggestClasses(range, classNames, m) {
|
|
11
19
|
return classNames.map((className) => ({
|
|
12
20
|
messageId: "replace",
|
|
13
|
-
data: { className },
|
|
21
|
+
data: { text: m.replaceWith({ className }) },
|
|
14
22
|
fix: (fixer) => fixer.replaceTextRange(range, className),
|
|
15
23
|
}));
|
|
16
24
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { findArbitraryColors, findHexColors } from "../core/classes.js";
|
|
2
|
+
import { visitStrings } from "./visit-strings.js";
|
|
3
|
+
import { inlineStyleProperty } from "./visit-style.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 검사 규칙이 보지 않는 문자열 속 hex 색을 알린다. 위반이 아니라 check 가 개수를 세는 데 쓴다.
|
|
7
|
+
* 임의 값 클래스(bg-[#fff])와 인라인 스타일의 hex 는 다른 규칙이 검사하므로 빼고 센다.
|
|
8
|
+
* @type {import("eslint").Rule.RuleModule}
|
|
9
|
+
*/
|
|
10
|
+
export default {
|
|
11
|
+
meta: { type: "suggestion", schema: [], messages: { unchecked: "{{color}}" } },
|
|
12
|
+
create(context) {
|
|
13
|
+
const findUnchecked = (text) => {
|
|
14
|
+
const inClasses = findArbitraryColors(text).map(({ index, text: found }) => [index, index + found.length]);
|
|
15
|
+
return findHexColors(text).filter(({ index }) => !inClasses.some(([start, end]) => index >= start && index < end));
|
|
16
|
+
};
|
|
17
|
+
const visitor = visitStrings(context, findUnchecked, (found, { loc }) =>
|
|
18
|
+
context.report({ loc, messageId: "unchecked", data: { color: found.value } }),
|
|
19
|
+
);
|
|
20
|
+
const skipStyle = (handler) => (node) => {
|
|
21
|
+
if (inlineStyleProperty(node) === null && inlineStyleProperty(node.parent ?? {}) === null) handler(node);
|
|
22
|
+
};
|
|
23
|
+
return { Literal: skipStyle(visitor.Literal), TemplateElement: skipStyle(visitor.TemplateElement) };
|
|
24
|
+
},
|
|
25
|
+
};
|
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
import { replacementNames } from "../config.js";
|
|
3
|
+
import { ruleMessages, TEXT } from "./suggest.js";
|
|
2
4
|
|
|
3
5
|
/** @type {import("eslint").Rule.RuleModule} */
|
|
4
6
|
export default {
|
|
5
7
|
meta: {
|
|
6
8
|
type: "problem",
|
|
7
|
-
docs: { description: "
|
|
9
|
+
docs: { description: "Use the design system component instead of a raw tag" },
|
|
8
10
|
schema: [],
|
|
9
|
-
messages: {
|
|
10
|
-
useComponent:
|
|
11
|
-
"<{{tag}}> 대신 디자인 시스템 컴포넌트를 사용하세요: {{component}} ({{path}})",
|
|
12
|
-
},
|
|
11
|
+
messages: { useComponent: TEXT, useComponentAsk: TEXT },
|
|
13
12
|
},
|
|
14
13
|
create(context) {
|
|
15
|
-
const components = context.settings?.designsnitch
|
|
14
|
+
const { components, root } = context.settings?.designsnitch ?? {};
|
|
16
15
|
if (!components?.path || !components.replaces) return {};
|
|
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
|
|
|
@@ -25,14 +25,38 @@ export default {
|
|
|
25
25
|
if (node.name.type !== "JSXIdentifier") return;
|
|
26
26
|
const tag = node.name.name;
|
|
27
27
|
if (!Object.hasOwn(components.replaces, tag)) return;
|
|
28
|
+
const replacement = components.replaces[tag];
|
|
29
|
+
const hasSpread = node.attributes.some((attr) => attr.type === "JSXSpreadAttribute");
|
|
30
|
+
let dynamicAttribute;
|
|
31
|
+
// spread 가 있으면 명시한 속성 값도 런타임에 덮어쓸 수 있다.
|
|
32
|
+
if (!hasSpread && replacement.when) {
|
|
33
|
+
for (const [name, allowed] of Object.entries(replacement.when)) {
|
|
34
|
+
const attr = node.attributes.findLast(
|
|
35
|
+
(attr) => attr.type === "JSXAttribute" && attr.name.name === name,
|
|
36
|
+
);
|
|
37
|
+
const value = attr?.value;
|
|
38
|
+
const literal = value?.type === "JSXExpressionContainer" ? value.expression : value;
|
|
39
|
+
if (literal && literal.type !== "Literal") {
|
|
40
|
+
dynamicAttribute ??= name;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
// null 조건은 속성이 아예 생략된 경우에만 맞는다.
|
|
44
|
+
const actual = attr ? literal?.value : null;
|
|
45
|
+
if ((attr && typeof actual !== "string") || !allowed.includes(actual)) return;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const messageId = hasSpread || dynamicAttribute !== undefined ? "useComponentAsk" : "useComponent";
|
|
28
50
|
context.report({
|
|
29
51
|
node: node.name,
|
|
30
|
-
messageId
|
|
52
|
+
messageId,
|
|
31
53
|
data: {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
54
|
+
text: m[messageId]({
|
|
55
|
+
tag,
|
|
56
|
+
component: replacementNames(replacement).join(", "),
|
|
57
|
+
path: components.path,
|
|
58
|
+
dynamicAttribute,
|
|
59
|
+
}),
|
|
36
60
|
},
|
|
37
61
|
});
|
|
38
62
|
},
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { findHexColors } from "../core/classes.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
|
+
const property = node.parent;
|
|
11
|
+
if (property?.type !== "Property" || property.value !== node || property.computed) return null;
|
|
12
|
+
const object = property.parent;
|
|
13
|
+
if (object?.type !== "ObjectExpression" || object.parent?.type !== "JSXExpressionContainer") return null;
|
|
14
|
+
const attribute = object.parent.parent;
|
|
15
|
+
if (attribute?.type !== "JSXAttribute" || attribute.name?.name !== "style") return null;
|
|
16
|
+
const { key } = property;
|
|
17
|
+
if (key.type === "Identifier") return key.name;
|
|
18
|
+
return typeof key.value === "string" ? key.value : null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* JSX style 속성에 문자열로 적은 hex 색마다 onFound 를 부르는 visitor 를 만든다.
|
|
23
|
+
* @param {import("eslint").Rule.RuleContext} context
|
|
24
|
+
* @param {(found: { text: string, value: string, property: string }, where: { loc: import("estree").SourceLocation, range: [number, number] }) => void} onFound
|
|
25
|
+
*/
|
|
26
|
+
export function visitInlineStyleColors(context, onFound) {
|
|
27
|
+
const { sourceCode } = context;
|
|
28
|
+
|
|
29
|
+
function scan(node, property) {
|
|
30
|
+
for (const found of findHexColors(sourceCode.getText(node))) {
|
|
31
|
+
const start = node.range[0] + found.index;
|
|
32
|
+
const end = start + found.text.length;
|
|
33
|
+
onFound({ ...found, property }, {
|
|
34
|
+
loc: { start: sourceCode.getLocFromIndex(start), end: sourceCode.getLocFromIndex(end) },
|
|
35
|
+
range: [start, end],
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
Literal(node) {
|
|
42
|
+
if (typeof node.value !== "string") return;
|
|
43
|
+
const property = inlineStyleProperty(node);
|
|
44
|
+
if (property !== null) scan(node, property);
|
|
45
|
+
},
|
|
46
|
+
TemplateLiteral(node) {
|
|
47
|
+
const property = inlineStyleProperty(node);
|
|
48
|
+
// ${} 안의 코드는 다른 노드가 맡는다. 문자열 부분만 본다.
|
|
49
|
+
if (property !== null) for (const quasi of node.quasis) scan(quasi, property);
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 같은 노드 종류를 여러 visitor 가 보도록 합친다. */
|
|
55
|
+
export function mergeVisitors(...visitors) {
|
|
56
|
+
const merged = {};
|
|
57
|
+
for (const visitor of visitors) {
|
|
58
|
+
for (const [type, handler] of Object.entries(visitor)) {
|
|
59
|
+
const previous = merged[type];
|
|
60
|
+
merged[type] = previous ? (node) => { previous(node); handler(node); } : handler;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return merged;
|
|
64
|
+
}
|