designsnitch 0.3.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.
@@ -1,8 +1,10 @@
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
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 {
@@ -25,25 +27,34 @@ export default {
25
27
  };
26
28
  }
27
29
  const m = ruleMessages(context);
28
- const { colors, themed } = tokens;
30
+ const { colors, themed, prefer } = tokens;
29
31
 
30
- return visitStrings(context, findArbitraryColors, (found, { loc, range }) => {
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, classes, m),
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(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
+ );
48
59
  },
49
60
  };
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { invalidTokenField, tokenSettings } from "../config.js";
3
4
  import { parseColorTokenData } from "../core/tokens.js";
4
5
  import { messages, resolveLang } from "../messages.js";
5
6
 
@@ -7,9 +8,10 @@ import { messages, resolveLang } from "../messages.js";
7
8
  * @typedef {object} Tokens
8
9
  * @property {Map<string, string[]>} colors 색 값 → 토큰 이름들
9
10
  * @property {Set<string>} themed 테마마다 값이 다른 토큰 이름들
11
+ * @property {string[]} prefer 먼저 적용할 토큰 접두어
10
12
  */
11
13
 
12
- /** @type {Map<string, { mtimeMs: number, tokens: Tokens }>} */
14
+ /** @type {Map<string, { mtimeMs: number, tokens: Omit<Tokens, "prefer"> }>} */
13
15
  const cache = new Map();
14
16
 
15
17
  /**
@@ -19,18 +21,22 @@ const cache = new Map();
19
21
  */
20
22
  export function loadTokens(settings, cwd) {
21
23
  const m = messages(resolveLang(settings?.designsnitch?.lang));
22
- const tokensPath = settings?.designsnitch?.tokens;
23
- if (typeof tokensPath !== "string") throw new Error(m.tokensSettingMissing());
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 }));
24
28
 
25
- const file = path.resolve(cwd, tokensPath);
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]);
26
32
  try {
27
33
  const { mtimeMs } = fs.statSync(file);
28
- const cached = cache.get(file);
29
- if (cached?.mtimeMs === mtimeMs) return cached.tokens;
34
+ const cached = cache.get(key);
35
+ if (cached?.mtimeMs === mtimeMs) return { ...cached.tokens, prefer };
30
36
 
31
- const tokens = parseColorTokenData(fs.readFileSync(file, "utf8"));
32
- cache.set(file, { mtimeMs, tokens });
33
- return tokens;
37
+ const parsed = parseColorTokenData(fs.readFileSync(file, "utf8"), exclude);
38
+ cache.set(key, { mtimeMs, tokens: parsed });
39
+ return { ...parsed, prefer };
34
40
  } catch (error) {
35
41
  if (error.code === "ENOENT" || error.code === "ENOTDIR") {
36
42
  throw new Error(m.tokensFileMissing({ file }));
@@ -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
+ };
@@ -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?.components;
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,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
+ }