designsnitch 0.1.0 → 0.3.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,19 +1,19 @@
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: "디자인 시스템 컴포넌트가 있는 raw 태그를 직접 쓰지 않는다" },
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
14
  const components = context.settings?.designsnitch?.components;
16
15
  if (!components?.path || !components.replaces) return {};
16
+ const m = ruleMessages(context);
17
17
 
18
18
  // 디자인 시스템 컴포넌트는 raw 태그로 만들어지므로 그 경로 안은 검사하지 않는다.
19
19
  const dsDir = path.resolve(context.cwd, components.path);
@@ -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: "useComponent",
52
+ messageId,
31
53
  data: {
32
- tag,
33
- // 대체 컴포넌트는 하나(문자열)일 수도 여러 개(배열)일 수도 있다.
34
- component: [components.replaces[tag]].flat().join(", "),
35
- path: components.path,
54
+ text: m[messageId]({
55
+ tag,
56
+ component: replacementNames(replacement).join(", "),
57
+ path: components.path,
58
+ dynamicAttribute,
59
+ }),
36
60
  },
37
61
  });
38
62
  },
@@ -1,107 +0,0 @@
1
- ---
2
- name: designsnitch
3
- description: React/Next.js + Tailwind 프로젝트에서 UI 코드를 만들거나 고친 뒤, 디자인 시스템(토큰, 공용 컴포넌트)을 벗어난 곳을 검사하고 고친다. 컴포넌트나 페이지, className, 스타일을 수정했을 때, 또는 사용자가 디자인 시스템 준수, 토큰 사용, 디자인 검사를 말할 때 사용한다.
4
- ---
5
-
6
- # designsnitch
7
-
8
- UI 코드를 수정했으면 작업을 끝내기 전에 디자인 시스템 검사를 실행한다. 판정은 CLI가 하고, 이 문서는 언제 실행하고 결과를 어떻게 다룰지를 정한다.
9
-
10
- ## 1. 검사 실행
11
-
12
- 수정한 파일을 지정해서 실행한다. 경로를 생략하면 프로젝트 전체를 검사한다.
13
-
14
- ```sh
15
- npx designsnitch check src/features/checkout/PayButton.tsx --format json
16
- ```
17
-
18
- 종료 코드는 0(오류 없음), 1(오류 있음), 2(실행하지 못함)이다. 2로 끝나면 stderr의 메시지를 읽는다. 설정 파일이 없다는 메시지면 2절로 간다.
19
-
20
- ## 2. 설정 파일이 없을 때
21
-
22
- 프로젝트 루트에 `designsnitch.config.json`이 없으면 저장소를 읽어서 만든다.
23
-
24
- 1. **토큰 CSS를 찾는다.** `@theme` 블록이나 `--color-*` 변수가 있는 CSS 파일이다. 보통 `app/globals.css`나 `src/app/globals.css`다.
25
- 2. **공용 컴포넌트 경로를 찾는다.** 버튼, 입력창 같은 기본 UI 컴포넌트가 모여 있는 디렉터리다. 보통 `components/ui`다.
26
- 3. **각 컴포넌트가 대체하는 raw 태그를 적는다.** 그 디렉터리의 파일을 읽어서, 최상위 요소가 `button`, `input`, `select`, `textarea`, `dialog` 같은 raw 태그인 컴포넌트를 찾는다. 같은 태그를 대체하는 컴포넌트가 여러 개면 모두 적는다. 이름은 export된 컴포넌트 이름을 쓴다.
27
- 4. **파일을 쓴다.**
28
-
29
- ```json
30
- {
31
- "tokens": "./src/app/globals.css",
32
- "components": {
33
- "path": "./src/components/ui",
34
- "replaces": {
35
- "button": ["SolidButton", "GlassButton", "IconButton"],
36
- "input": "Input"
37
- }
38
- }
39
- }
40
- ```
41
-
42
- 5. **검사를 실행해서 설정이 맞는지 확인한다.** 결과의 `designSystem`에 읽어 낸 개수가 나온다. `colorTokens`가 0이거나 `problems`가 비어 있지 않으면 설정이 틀린 것이므로, 경로를 다시 확인하고 고친다.
43
- 6. **사용자에게 설정 파일을 보여준다.** 이 파일이 판정 기준이므로, 어떤 파일과 경로를 골랐는지와 `designSystem`의 개수를 함께 알린다.
44
-
45
- 찾지 못한 항목은 추측해서 채우지 않는다. 공용 컴포넌트 디렉터리가 없으면 `components`를 빼고 `tokens`만 적는다. 토큰 CSS를 찾지 못하면 사용자에게 묻는다.
46
-
47
- ## 3. 결과 읽기
48
-
49
- ```json
50
- {
51
- "designSystem": {
52
- "colorTokens": 175,
53
- "radiusTokens": 4,
54
- "textTokens": 0,
55
- "components": 4,
56
- "replacedTags": 2
57
- },
58
- "problems": [],
59
- "summary": { "files": 1, "errors": 2, "warnings": 1 },
60
- "violations": [
61
- {
62
- "file": "src/features/checkout/PayButton.tsx",
63
- "line": 7,
64
- "column": 28,
65
- "endLine": 7,
66
- "endColumn": 40,
67
- "rule": "color-use-token",
68
- "severity": "error",
69
- "message": "bg-[#3B82F6]의 색은 토큰 --color-primary-500의 값입니다. 대신 사용: bg-primary-500",
70
- "found": "bg-[#3B82F6]",
71
- "candidates": ["bg-primary-500"]
72
- }
73
- ]
74
- }
75
- ```
76
-
77
- - `designSystem`은 설정에서 읽어 낸 토큰과 컴포넌트의 개수다.
78
- - `problems`가 비어 있지 않으면 설정에 문제가 있어 결과를 믿을 수 없다. 위반을 고치기 전에 사용자에게 알린다.
79
- - `found`는 위반한 코드 조각이고, `candidates`는 대신 쓸 클래스나 컴포넌트다.
80
- - `severity`가 `error`면 디자인 시스템에 쓸 것이 있는데 쓰지 않은 것이다. `warning`이면 디자인 시스템에 없는 값이다.
81
-
82
- ## 4. 고치기
83
-
84
- 대체가 확실한 위반만 고친다.
85
-
86
- | 상황 | 할 일 |
87
- | --- | --- |
88
- | `error`이고 `candidates`가 하나 | `found`를 그 후보로 바꾼다. |
89
- | `error`이고 `candidates`가 둘 이상 | 바꾸지 않는다. 후보들과 그 코드가 쓰인 맥락(무엇의 배경인지, 무엇의 글자색인지)을 사용자에게 보여주고 고르게 한다. |
90
- | `warning` | 바꾸지 않는다. 새 값이 정말 필요한지 실수인지는 사용자가 정한다. 가까운 후보가 있으면 함께 보여준다. |
91
- | `rule`이 `parse-error` | 문법 오류부터 고친 뒤 다시 검사한다. |
92
-
93
- `rule`이 `use-ds-component`일 때는 태그 이름만 바꾸면 안 된다. 디자인 시스템 컴포넌트 파일을 읽어 props를 확인하고, import를 추가하고, 컴포넌트가 이미 가진 스타일과 겹치는 className을 정리한다.
94
-
95
- ## 5. 다시 검사
96
-
97
- 고친 뒤 같은 명령을 다시 실행한다. 남은 것이 사용자의 결정을 기다리는 항목뿐일 때 멈춘다.
98
-
99
- ## 6. 보고
100
-
101
- 고친 것과 남긴 것을 나눠서 알린다. 남긴 것은 파일과 줄, 후보, 남긴 이유를 함께 적는다.
102
-
103
- ## 하지 않는 것
104
-
105
- - 이미 있는 `designsnitch.config.json`을 고치지 않는다. 설정 파일은 판정 기준이다. 없을 때 새로 만드는 것은 되지만, 있는 것을 바꿔야 할 것 같으면 이유를 설명하고 사용자에게 묻는다.
106
- - 검사를 통과시키려고 `eslint-disable` 주석을 넣지 않는다. 예외가 필요해 보이면 사용자에게 묻는다.
107
- - 후보가 여러 개일 때 임의로 하나를 고르지 않는다.
package/src/core/scale.js DELETED
@@ -1,71 +0,0 @@
1
- const LENGTH = /^(\d*\.?\d+)(px|rem)$/;
2
- const ROOT_FONT_SIZE = 16;
3
-
4
- const SPACING_UTILITY = /^(?:[pm][xytrblse]?|gap(?:-[xy])?|space-[xy])$/;
5
- const RADIUS_UTILITY = /^rounded(?:-(?:[trblse]|tl|tr|br|bl|ss|se|ee|es))?$/;
6
-
7
- const round = (n) => Math.round(n * 1e4) / 1e4;
8
-
9
- /**
10
- * px, rem 길이를 px 숫자로 바꾼다. 다른 단위나 식은 null.
11
- */
12
- export function parseLength(value) {
13
- const match = LENGTH.exec(value.trim());
14
- if (!match) return null;
15
- const amount = Number(match[1]);
16
- return round(match[2] === "rem" ? amount * ROOT_FONT_SIZE : amount);
17
- }
18
-
19
- /**
20
- * 임의 값으로 쓴 길이가 스케일에 있는지 본다.
21
- * - 있으면 { kind, exact: [대신 쓸 클래스] }
22
- * - 없으면 { kind, nearest: [{ className, px }] } (바로 아래, 바로 위)
23
- * - 검사 대상이 아니거나 비교할 토큰이 없으면 null
24
- *
25
- * @param {string} utility 예: "p", "rounded-t", "text"
26
- * @param {number} px
27
- * @param {{ spacingUnit: number, radius: Map<number, string[]>, text: Map<number, string[]> }} scale
28
- */
29
- export function matchScale(utility, px, scale) {
30
- if (SPACING_UTILITY.test(utility)) {
31
- return { kind: "spacing", ...matchSpacing(utility, px, scale.spacingUnit) };
32
- }
33
- if (RADIUS_UTILITY.test(utility) && scale.radius.size > 0) {
34
- return { kind: "radius", ...matchTokens(utility, px, scale.radius, "--radius-") };
35
- }
36
- if (utility === "text" && scale.text.size > 0) {
37
- return { kind: "text", ...matchTokens(utility, px, scale.text, "--text-") };
38
- }
39
- return null;
40
- }
41
-
42
- // 간격은 단위의 0.5배수까지를 스케일로 본다 (p-0.5, p-1.5, p-4 ...). 1px 는 p-px.
43
- function matchSpacing(utility, px, unit) {
44
- const halfSteps = round((px / unit) * 2);
45
- if (Number.isInteger(halfSteps)) return { exact: [`${utility}-${halfSteps / 2}`] };
46
- if (px === 1) return { exact: [`${utility}-px`] };
47
-
48
- const lower = Math.floor(halfSteps) / 2;
49
- return {
50
- nearest: [lower, lower + 0.5].map((steps) => ({
51
- className: `${utility}-${steps}`,
52
- px: round(steps * unit),
53
- })),
54
- };
55
- }
56
-
57
- function matchTokens(utility, px, tokens, prefix) {
58
- const toClass = (name) => `${utility}-${name.slice(prefix.length)}`;
59
-
60
- const names = tokens.get(px);
61
- if (names) return { exact: names.map(toClass) };
62
-
63
- const values = [...tokens.keys()].sort((a, b) => a - b);
64
- const below = values.findLast((value) => value < px);
65
- const above = values.find((value) => value > px);
66
- return {
67
- nearest: [below, above]
68
- .filter((value) => value !== undefined)
69
- .map((value) => ({ className: toClass(tokens.get(value)[0]), px: value })),
70
- };
71
- }
@@ -1,6 +0,0 @@
1
- /** matchScale 의 kind 를 메시지에 쓸 이름으로 바꾼다. */
2
- export const SCALE_LABELS = {
3
- spacing: "간격 스케일",
4
- radius: "radius 토큰",
5
- text: "폰트 크기 토큰",
6
- };
@@ -1,43 +0,0 @@
1
- import { findArbitraryLengths } from "../core/classes.js";
2
- import { matchScale } from "../core/scale.js";
3
- import { loadTokens } from "./load-tokens.js";
4
- import { SCALE_LABELS } from "./scale-labels.js";
5
- import { REPLACE_MESSAGES, suggestClasses } from "./suggest.js";
6
- import { visitStrings } from "./visit-strings.js";
7
-
8
- /** @type {import("eslint").Rule.RuleModule} */
9
- export default {
10
- meta: {
11
- type: "suggestion",
12
- docs: { description: "스케일에 없는 간격, 폰트 크기, radius를 쓰면 알린다" },
13
- hasSuggestions: true,
14
- schema: [],
15
- messages: {
16
- ...REPLACE_MESSAGES,
17
- unknown: "{{found}}의 값은 {{scale}}에 없습니다. 가까운 값: {{nearest}}",
18
- },
19
- },
20
- create(context) {
21
- const { scale } = loadTokens(context.settings, context.cwd);
22
-
23
- return visitStrings(context, findArbitraryLengths, (found, { loc, range }) => {
24
- const match = matchScale(found.utility, found.px, scale);
25
- if (!match?.nearest) return;
26
- context.report({
27
- loc,
28
- messageId: "unknown",
29
- data: {
30
- found: found.text,
31
- scale: SCALE_LABELS[match.kind],
32
- nearest: match.nearest
33
- .map(({ className, px }) => `${className} (${px}px)`)
34
- .join(", "),
35
- },
36
- suggest: suggestClasses(
37
- range,
38
- match.nearest.map(({ className }) => className),
39
- ),
40
- });
41
- });
42
- },
43
- };
@@ -1,38 +0,0 @@
1
- import { findArbitraryLengths } from "../core/classes.js";
2
- import { matchScale } from "../core/scale.js";
3
- import { loadTokens } from "./load-tokens.js";
4
- import { SCALE_LABELS } from "./scale-labels.js";
5
- import { REPLACE_MESSAGES, suggestClasses } from "./suggest.js";
6
- import { visitStrings } from "./visit-strings.js";
7
-
8
- /** @type {import("eslint").Rule.RuleModule} */
9
- export default {
10
- meta: {
11
- type: "problem",
12
- docs: { description: "스케일에 있는 간격, 폰트 크기, radius를 임의 값으로 쓰지 않는다" },
13
- hasSuggestions: true,
14
- schema: [],
15
- messages: {
16
- ...REPLACE_MESSAGES,
17
- useToken: "{{found}}의 값은 {{scale}}에 있습니다. 대신 사용: {{classes}}",
18
- },
19
- },
20
- create(context) {
21
- const { scale } = loadTokens(context.settings, context.cwd);
22
-
23
- return visitStrings(context, findArbitraryLengths, (found, { loc, range }) => {
24
- const match = matchScale(found.utility, found.px, scale);
25
- if (!match?.exact) return;
26
- context.report({
27
- loc,
28
- messageId: "useToken",
29
- data: {
30
- found: found.text,
31
- scale: SCALE_LABELS[match.kind],
32
- classes: match.exact.join(", "),
33
- },
34
- suggest: suggestClasses(range, match.exact),
35
- });
36
- });
37
- },
38
- };