designsnitch 0.5.0 → 0.6.1
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 +24 -9
- package/README.md +24 -9
- package/bin/designsnitch.js +5 -3
- package/package.json +2 -2
- package/skills/designsnitch-check/SKILL.md +4 -3
- package/skills/designsnitch-hooks/SKILL.md +21 -3
- package/src/check.js +22 -7
- package/src/colors.js +2 -2
- package/src/core/classes.js +2 -2
- package/src/core/color.js +7 -1
- package/src/core/tokens.js +66 -10
- package/src/hook.js +62 -11
- package/src/install.js +6 -0
- package/src/messages.js +8 -0
- package/src/rules/color-unknown.js +3 -2
- package/src/rules/color-use-token.js +35 -14
- package/src/rules/unchecked-colors.js +4 -2
- package/src/rules/visit-style.js +75 -20
package/README.ko.md
CHANGED
|
@@ -23,7 +23,7 @@ designsnitch는 디자인 시스템이 없거나 이름뿐인 프로젝트에서
|
|
|
23
23
|
|
|
24
24
|
**Tailwind CSS v4를 쓰는 React/Next.js 프로젝트**를 지원합니다. Tailwind v3 프로젝트도 검사하지만 후보가 적습니다([Tailwind v3](#tailwind-v3) 참고).
|
|
25
25
|
|
|
26
|
-
> **상태:** MVP(0.
|
|
26
|
+
> **상태:** MVP(0.6.x). 지금은 색과 공용 컴포넌트를 검사합니다. 간격, 폰트 크기, radius는 아직 검사하지 않습니다([검사 범위](#검사-범위) 참고). 메시지는 기본이 영어이고 한국어로 바꿀 수 있습니다. 이 문서의 출력 예시는 한국어로 설정했을 때의 모습입니다. [언어](#언어)를 보세요.
|
|
27
27
|
|
|
28
28
|
## 시작하기
|
|
29
29
|
|
|
@@ -32,7 +32,7 @@ npm install --save-dev designsnitch
|
|
|
32
32
|
npx designsnitch install
|
|
33
33
|
```
|
|
34
34
|
|
|
35
|
-
두 번째 명령은 에이전트 스킬을 설치하고 에이전트 훅을 등록합니다. Node.js
|
|
35
|
+
두 번째 명령은 에이전트 스킬을 설치하고 에이전트 훅을 등록합니다. Node.js 20.19 이상이 필요합니다.
|
|
36
36
|
|
|
37
37
|
| 에이전트 | 명령 | 스킬 위치 | 훅 위치 |
|
|
38
38
|
| --- | --- | --- | --- |
|
|
@@ -240,6 +240,12 @@ Tailwind 기본 팔레트
|
|
|
240
240
|
}
|
|
241
241
|
```
|
|
242
242
|
|
|
243
|
+
변수를 어디에 선언했는지도 봅니다.
|
|
244
|
+
|
|
245
|
+
- `--color-*` 변수는 `@theme` 안이나 어디서나 적용되는 규칙(`:root`, `html`, `:host`)에 선언돼 있어야 토큰입니다. `.promo { --color-promo: ... }`처럼 다른 선택자 안에만 선언된 변수는 토큰이 아닙니다. 그 선택자 밖에는 없는 변수이기 때문입니다.
|
|
246
|
+
- 토큰을 선택자나 미디어 쿼리 안(`.dark`, `@media (prefers-color-scheme: dark)`)에서 다시 선언하면 테마마다 값이 다른 토큰이고, 색을 그 토큰으로 바꾸는 것은 `ask`로 표시합니다.
|
|
247
|
+
- `var(--raw, #fff)`는 `--raw`가 없는 곳에서 fallback을 씁니다. `--raw`가 일부 선택자 안에만 있으면 fallback과 그 값을 모두 토큰의 값으로 보므로, 이것도 `ask`가 됩니다.
|
|
248
|
+
|
|
243
249
|
토큰은 Tailwind가 읽는 곳에서도 읽습니다.
|
|
244
250
|
|
|
245
251
|
- **import한 CSS.** 토큰 CSS가 다른 CSS 파일을 불러오면(`@import "../brand/theme.css"`나 패키지) 그 파일의 `@theme` 토큰도 읽습니다.
|
|
@@ -354,8 +360,8 @@ src/PayButton.tsx
|
|
|
354
360
|
| `violations[].found` | 위반한 코드 조각 |
|
|
355
361
|
| `violations[].candidates` | 대신 쓸 클래스나 컴포넌트. 없으면 빈 배열입니다. |
|
|
356
362
|
| `violations[].recommended` | 색을 쓰는 용도에 맞는 후보입니다. `text-` 클래스면 텍스트용 이름의 토큰, 테두리면 테두리용 이름의 토큰입니다. 맞는 후보가 정확히 하나일 때만 채우고, 추천일 뿐이라 `ask`는 그대로 `ask`입니다. `replace`와 `migrate`면 그 후보입니다. |
|
|
357
|
-
| `violations[].action` | 이 위반을 어떻게 다룰지입니다. `replace`: `found`를 하나뿐인 후보로 바꿔도 화면과 동작이 같습니다. 색 오류만 해당합니다. `migrate`: raw 태그를 옮길 디자인 시스템 컴포넌트가 하나뿐입니다. 컴포넌트가 같은 props를 넘기는지, 기본 스타일이 같은지는 도구가 알 수 없으므로 컴포넌트를 먼저 읽고 태그의 props를 옮기고 컴포넌트가 이미 주는 클래스는 지웁니다.
|
|
358
|
-
| `decisions` | `ask`인 위반을 질문 단위로 묶은 것입니다. 색이나 태그와 후보가 같으면 하나로 묶습니다. 각 항목에 얼마나 나오는지(`uses`, `files`), 위치 최대 다섯 곳(`locations`), 후보(`candidates`), 모든 위치에서 추천이 같을 때의 추천(`recommended`), 사람이 정해야 하는 이유(`reasons`: `multiple-candidates`, `no-token`, `themed-token`, `class-only-token`, `dynamic-props`)가 있습니다. 많이 나오는 순서입니다. |
|
|
363
|
+
| `violations[].action` | 이 위반을 어떻게 다룰지입니다. `replace`: `found`를 하나뿐인 후보로 바꿔도 화면과 동작이 같습니다. 색 오류만 해당합니다. `migrate`: raw 태그를 옮길 디자인 시스템 컴포넌트가 하나뿐입니다. 컴포넌트가 같은 props를 넘기는지, 기본 스타일이 같은지는 도구가 알 수 없으므로 컴포넌트를 먼저 읽고 태그의 props를 옮기고 컴포넌트가 이미 주는 클래스는 지웁니다. 훅은 고친 직후에 알리기만 하고, 이것 때문에 에이전트가 끝내는 것을 막지는 않습니다. `ask`: 사람이 정해야 합니다. 후보가 여러 개이거나, 토큰이 없는 색이거나, 테마마다 값이 다른 토큰이거나, 컴포넌트의 속성이 동적이거나 spread된 경우입니다. `repair`: 파일을 읽지 못했습니다. |
|
|
364
|
+
| `decisions` | `ask`인 위반을 질문 단위로 묶은 것입니다. 색이나 태그와 후보가 같으면 하나로 묶습니다. 각 항목에 얼마나 나오는지(`uses`, `files`), 위치 최대 다섯 곳(`locations`), 후보(`candidates`), 모든 위치에서 추천이 같을 때의 추천(`recommended`), 사람이 정해야 하는 이유(`reasons`: `multiple-candidates`, `no-token`, `themed-token`, `translucent`, `not-a-style`, `class-only-token`, `dynamic-props`)가 있습니다. 많이 나오는 순서입니다. |
|
|
359
365
|
| `next` | 이 결과를 받은 에이전트가 할 일을 순서대로 적은 것 |
|
|
360
366
|
| `unchecked` | 검사하지 못한 다른 문자열 속 색의 개수(`colors`)와 파일 수(`files`). 하나라도 있으면 글 출력에 한 줄이 붙습니다. |
|
|
361
367
|
|
|
@@ -457,6 +463,11 @@ CLI와 스킬은 AI 에이전트가 제대로 할 수 있는 상태를 만들어
|
|
|
457
463
|
{
|
|
458
464
|
"hooks": [{ "type": "command", "command": "npx designsnitch hook" }]
|
|
459
465
|
}
|
|
466
|
+
],
|
|
467
|
+
"SessionStart": [
|
|
468
|
+
{
|
|
469
|
+
"hooks": [{ "type": "command", "command": "npx designsnitch hook" }]
|
|
470
|
+
}
|
|
460
471
|
]
|
|
461
472
|
}
|
|
462
473
|
}
|
|
@@ -466,11 +477,12 @@ CLI와 스킬은 AI 에이전트가 제대로 할 수 있는 상태를 만들어
|
|
|
466
477
|
|
|
467
478
|
- 파일마다 git `HEAD` 버전과 비교합니다. 같은 규칙, 같은 코드의 오류가 `HEAD`보다 많아졌으면 새 오류입니다. 원래 있던 오류는 줄이 밀려도 막지 않습니다. `HEAD`에 아직 없는 파일은 모든 오류가 새것입니다.
|
|
468
479
|
- 파일을 고친 뒤 새 오류가 있으면, 에이전트는 오류와 다음에 할 일을 전달받습니다.
|
|
469
|
-
- 에이전트가 작업을 끝내려 할
|
|
480
|
+
- 에이전트가 작업을 끝내려 할 때, 바꿔도 화면과 동작이 같은 새 오류(`replace`와 읽지 못한 파일)가 남아 있으면 끝내지 못합니다. 사람이 정해야 하는 오류(`ask`)는 막지 않습니다. 물어보려면 멈춰야 하기 때문입니다. 컴포넌트로 옮길 태그(`migrate`)도 막지 않습니다. 컴포넌트가 똑같이 동작하는지 도구가 알 수 없으므로, 고친 직후에 알리기만 하고 판단은 에이전트와 사용자에게 맡깁니다.
|
|
481
|
+
- 세션이 시작되기 전부터 작업 폴더에 있던 오류는 커밋하지 않았더라도 새 오류로 치지 않습니다. 훅이 세션이 시작될 때(`SessionStart`) 적어 둡니다. 그 이벤트가 없으면 세션의 첫 수정 때, 방금 고친 파일을 뺀 나머지 바뀐 파일을 적어 둡니다. 에이전트가 세션 id를 보내 줘야 합니다.
|
|
470
482
|
- 경고는 막지 않고, 에이전트가 건드리지 않은 파일은 보지 않습니다.
|
|
471
483
|
- git 저장소가 아니거나 첫 커밋 전이면, 바꾼 파일의 오류를 모두 셉니다.
|
|
472
484
|
|
|
473
|
-
Codex에는 `npx designsnitch install --agent codex`가 같은
|
|
485
|
+
Codex에는 `npx designsnitch install --agent codex`가 같은 훅들을 `.codex/hooks.json`에 씁니다. 파일 수정 쪽은 `apply_patch`에 걸립니다. Codex는 셸 명령으로 파일을 고치는 일이 많은데, 그런 수정은 이 조건에 걸리지 않습니다. 대신 Codex가 작업을 끝내려 할 때 잡힙니다. 그때 훅이 git에서 바뀐 파일을 모두 검사하기 때문입니다.
|
|
474
486
|
|
|
475
487
|
Gemini CLI에는 `npx designsnitch install --agent gemini`가 훅을 `.gemini/settings.json`에 씁니다. 이벤트 이름이 다릅니다. 파일 수정 직후는 `write_file`과 `replace`에 걸리는 `AfterTool`이고, 답하기 직전은 `AfterAgent`입니다. `AfterAgent`에서 종료 코드 2를 받으면 Gemini CLI는 오류를 피드백 삼아 다시 시도합니다. 공식 Gemini CLI 문서를 기준으로 만들었고, Gemini CLI에서 테스트하지 못했습니다.
|
|
476
488
|
|
|
@@ -504,7 +516,10 @@ Tailwind 기본 팔레트(`bg-slate-100`, `text-indigo-600`)를 기준으로 쓰
|
|
|
504
516
|
|
|
505
517
|
## 검사 범위
|
|
506
518
|
|
|
507
|
-
- **JS와 TS에서 보는 곳:** 문자열과 템플릿 리터럴 안의 임의 값 색 클래스(`className`과 `cn()`, `clsx()`, `cva()`의 인자 포함)와,
|
|
519
|
+
- **JS와 TS에서 보는 곳:** 문자열과 템플릿 리터럴 안의 임의 값 색 클래스(`className`과 `cn()`, `clsx()`, `cva()`의 인자 포함)와, 색을 받는 자리에 문자열로 적은 색입니다. `a ? "#fff" : "#000"`이나 `x || "#fff"`처럼 고르는 식의 값도 봅니다. 주석은 보지 않습니다.
|
|
520
|
+
- **스타일:** JSX `style` 객체와 `CSSProperties` 타입의 객체입니다. 여기서는 `var(--토큰)`이 통하므로 다른 색과 똑같이 검사합니다. `cardStyle` 같은 변수 이름은 근거로 삼지 않습니다. 차트 설정 묶음일 수 있기 때문입니다.
|
|
521
|
+
- **그 밖의 색 속성:** 이름이 CSS 색 속성이거나 `Color`로 끝나는 속성과 JSX 속성입니다. 차트 옵션의 `backgroundColor`, SVG 요소의 `stroke` 같은 것입니다. 색은 알리고 `var(--토큰)`을 후보로 주지만 `ask`로 표시합니다. 캔버스처럼 `var()`가 통하지 않는 곳에 쓰일 수 있기 때문입니다.
|
|
522
|
+
- **나머지:** 다른 이름의 키(`{ primary: "#3B82F6" }`)와 배열 안의 색은 코드만 보고 용도를 알 수 없어 검사하지 않습니다. 대신 있다는 것을 알 수 있도록 `unchecked`에 개수를 세고, `designsnitch colors`로 목록을 볼 수 있습니다.
|
|
508
523
|
- **CSS에서 보는 곳:** `.css` 파일(CSS Modules 포함)의 선언 값에 있는 색과 `@apply`의 임의 값 색 클래스입니다. 토큰 CSS에서는 변수를 정의하는 선언(`--이름: ...`)을 토큰을 정의하는 곳으로 보고 건너뜁니다. 다른 CSS 파일에서는 변수 선언도 일반 선언처럼 검사합니다. CSS에서는 아직 색만 검사합니다.
|
|
509
524
|
- **테마:** 토큰이 테마마다 다른 값을 가지면 그 값들을 모두 그 토큰의 값으로 봅니다. 색을 그런 토큰으로 바꾸면 다른 테마에서 색이 바뀌므로 `ask`로 표시합니다.
|
|
510
525
|
- **수정:** designsnitch는 후보를 알려줄 뿐, 후보가 하나여도 코드를 직접 고치지 않습니다.
|
|
@@ -513,7 +528,7 @@ Tailwind 기본 팔레트(`bg-slate-100`, `text-indigo-600`)를 기준으로 쓰
|
|
|
513
528
|
|
|
514
529
|
감지는 하지만 토큰과 맞추지는 못하는 것:
|
|
515
530
|
|
|
516
|
-
- 반투명한 색(`#3B82F680`, `rgb(0 0 0 / 50%)`)은 불투명한
|
|
531
|
+
- 반투명한 색(`#3B82F680`, `rgb(0 0 0 / 50%)`)은 불투명한 색의 토큰에 불투명도를 붙인 후보를 받습니다. 클래스는 `bg-brand/50`, 스타일과 CSS 선언은 `color-mix(in srgb, var(--color-brand) 50%, transparent)`입니다. 불투명도를 정수 퍼센트로 반올림하므로 `ask`로 표시합니다. `rgba(0, 0, 0, 0)`처럼 완전히 투명한 값은 색을 쓴 것이 아니므로 건너뜁니다.
|
|
517
532
|
- Tailwind 플러그인이 더하는 색은 토큰으로 알지 못합니다. 그 색을 직접 쓰면 토큰 없는 색으로 알립니다.
|
|
518
533
|
- `hwb()`, `lab()`, `lch()`, `oklab()`, `color()` 값과 sRGB 밖의 `oklch()` 색은 같은 값으로 적은 토큰과만 맞춥니다. 같은 색을 내는 hex가 없기 때문입니다.
|
|
519
534
|
- 색 이름은 색 속성(`color`, `background`, `border` 등), 임의 값 클래스(`bg-[white]`), 값 전체가 색 이름인 변수 선언에서만 읽습니다. 다른 곳의 `red` 같은 단어는 색으로 보지 않습니다.
|
|
@@ -522,7 +537,7 @@ Tailwind 기본 팔레트(`bg-slate-100`, `text-indigo-600`)를 기준으로 쓰
|
|
|
522
537
|
|
|
523
538
|
- 색 팔레트를 뺀 Tailwind 기본 테마의 값
|
|
524
539
|
- 토큰이 없는 색에 가장 가까운 토큰 제시
|
|
525
|
-
-
|
|
540
|
+
- 색을 뜻하지 않는 이름의 키에 적은 색(`{ primary: "#3B82F6" }`)과 배열 안의 색. `unchecked`에 개수로만 셉니다.
|
|
526
541
|
- SCSS 같은 전처리기
|
|
527
542
|
- 간격, 폰트 크기, radius. 이번 버전에서는 일부러 뺐습니다.
|
|
528
543
|
- 직접 만든 컴포넌트와 디자인 시스템 컴포넌트의 스타일 비교
|
package/README.md
CHANGED
|
@@ -23,7 +23,7 @@ It has four parts.
|
|
|
23
23
|
|
|
24
24
|
It supports **React/Next.js projects that use Tailwind CSS v4**. Tailwind v3 projects are checked too, with fewer candidates (see [Tailwind v3](#tailwind-v3)).
|
|
25
25
|
|
|
26
|
-
> **Status:** MVP (0.
|
|
26
|
+
> **Status:** MVP (0.6.x). It checks colors and shared components for now. Spacing, font size and radius are not checked yet (see [Scope](#scope)). Messages are in English by default and can be switched to Korean. See [Language](#language).
|
|
27
27
|
|
|
28
28
|
## Getting started
|
|
29
29
|
|
|
@@ -32,7 +32,7 @@ npm install --save-dev designsnitch
|
|
|
32
32
|
npx designsnitch install
|
|
33
33
|
```
|
|
34
34
|
|
|
35
|
-
The second command installs the agent skills and registers the agent hook. Node.js
|
|
35
|
+
The second command installs the agent skills and registers the agent hook. Node.js 20.19 or later is required.
|
|
36
36
|
|
|
37
37
|
| Agent | Command | Skills go to | Hook goes to |
|
|
38
38
|
| --- | --- | --- | --- |
|
|
@@ -239,6 +239,12 @@ Both of these shapes work.
|
|
|
239
239
|
}
|
|
240
240
|
```
|
|
241
241
|
|
|
242
|
+
Where a variable is declared matters.
|
|
243
|
+
|
|
244
|
+
- A `--color-*` variable is a token when it is declared in `@theme`, or in a rule that applies everywhere (`:root`, `html`, `:host`). One declared only inside another selector, such as `.promo { --color-promo: ... }`, is not a token: it does not exist outside that selector.
|
|
245
|
+
- When a token is declared again inside a selector or a media query (`.dark`, `@media (prefers-color-scheme: dark)`), it has a value per theme, and replacing a color with it is marked `ask`.
|
|
246
|
+
- `var(--raw, #fff)` uses its fallback wherever `--raw` is not set. If `--raw` is set only inside some selector, both the fallback and that value count as the token's values, so it is also marked `ask`.
|
|
247
|
+
|
|
242
248
|
Tokens are also read from where Tailwind itself reads them.
|
|
243
249
|
|
|
244
250
|
- **Imported CSS.** If the token CSS imports other CSS files (`@import "../brand/theme.css"`, or a package), their `@theme` tokens are read too.
|
|
@@ -353,8 +359,8 @@ The first line shows how many tokens and components were read from the config. A
|
|
|
353
359
|
| `violations[].found` | The offending piece of code |
|
|
354
360
|
| `violations[].candidates` | The classes or components to use instead. Empty when there are none. |
|
|
355
361
|
| `violations[].recommended` | The candidate that fits how the color is used: a `text-` class gets the token named for text, a border gets the one named for borders. Only set when exactly one candidate fits, and only a suggestion: an `ask` stays an `ask`. For `replace` and `migrate`, it is the candidate. |
|
|
356
|
-
| `violations[].action` | How to handle the violation. `replace`: replacing `found` with the only candidate keeps the screen and the behavior the same. Only color errors get this. `migrate`: a raw tag with exactly one design system component to move to. The tool cannot tell whether the component passes on the same props or renders the same default styles, so read the component first, then move the tag's props and drop classes the component already applies. The
|
|
357
|
-
| `decisions` | The `ask` violations grouped into questions: one per color or tag with the same candidates. Each has how often it comes up (`uses`, `files`), up to five `locations`, the `candidates`, a `recommended` candidate when every location agrees, and the `reasons` a person has to decide: `multiple-candidates`, `no-token`, `themed-token`, `class-only-token` or `dynamic-props`. Most used first. |
|
|
362
|
+
| `violations[].action` | How to handle the violation. `replace`: replacing `found` with the only candidate keeps the screen and the behavior the same. Only color errors get this. `migrate`: a raw tag with exactly one design system component to move to. The tool cannot tell whether the component passes on the same props or renders the same default styles, so read the component first, then move the tag's props and drop classes the component already applies. The hook reports it after an edit but does not stop the agent from finishing over it. `ask`: a person has to decide: several candidates, a color with no token, a token whose value differs between themes, or a component whose props are dynamic or spread. `repair`: the file could not be parsed. |
|
|
363
|
+
| `decisions` | The `ask` violations grouped into questions: one per color or tag with the same candidates. Each has how often it comes up (`uses`, `files`), up to five `locations`, the `candidates`, a `recommended` candidate when every location agrees, and the `reasons` a person has to decide: `multiple-candidates`, `no-token`, `themed-token`, `translucent`, `not-a-style`, `class-only-token` or `dynamic-props`. Most used first. |
|
|
358
364
|
| `next` | What an agent should do with this result, in order |
|
|
359
365
|
| `unchecked` | Colors in other strings that were not checked (`colors`), and how many files they are in (`files`). The text output adds a line when there are any. |
|
|
360
366
|
|
|
@@ -456,6 +462,11 @@ A skill is advice that an agent may not follow. A hook is run by the agent's run
|
|
|
456
462
|
{
|
|
457
463
|
"hooks": [{ "type": "command", "command": "npx designsnitch hook" }]
|
|
458
464
|
}
|
|
465
|
+
],
|
|
466
|
+
"SessionStart": [
|
|
467
|
+
{
|
|
468
|
+
"hooks": [{ "type": "command", "command": "npx designsnitch hook" }]
|
|
469
|
+
}
|
|
459
470
|
]
|
|
460
471
|
}
|
|
461
472
|
}
|
|
@@ -465,11 +476,12 @@ A skill is advice that an agent may not follow. A hook is run by the agent's run
|
|
|
465
476
|
|
|
466
477
|
- It compares each file with its version in git `HEAD`. An error counts as new when there are more of it (the same rule and the same code) than in `HEAD`. Errors that were already there do not block, even if lines moved. A file that is not in `HEAD` yet has only new errors.
|
|
467
478
|
- After an edit, if the file has new errors, the agent receives them along with what to do next.
|
|
468
|
-
- When the agent is about to finish, it is stopped if new errors it can fix
|
|
479
|
+
- When the agent is about to finish, it is stopped if new errors remain that it can fix with the same screen and behavior (`replace`, and files that could not be parsed). Errors that need a person's decision (`ask`) do not stop it, because it has to stop in order to ask. Tags to move to a component (`migrate`) do not stop it either: the tool cannot tell whether the component behaves the same, so it reports them after the edit and leaves the call to the agent and the user.
|
|
480
|
+
- Errors that were in the working tree before the session started do not count as new, even when they are not committed. The hook notes them when the session starts (`SessionStart`). Without that event, it notes them at the first edit of the session, for every changed file except the one just edited. This needs the session id the agent sends.
|
|
469
481
|
- Warnings never block, and files the agent did not touch are left alone.
|
|
470
482
|
- Outside a git repository, or before the first commit, every error in the changed files counts.
|
|
471
483
|
|
|
472
|
-
For Codex, `npx designsnitch install --agent codex` writes the same
|
|
484
|
+
For Codex, `npx designsnitch install --agent codex` writes the same hooks to `.codex/hooks.json`, with `apply_patch` as the matcher. Codex often edits files with shell commands, which that matcher does not see. Those edits are caught when Codex is about to finish, because the hook then checks every file git reports as changed.
|
|
473
485
|
|
|
474
486
|
For Gemini CLI, `npx designsnitch install --agent gemini` writes the hooks to `.gemini/settings.json` under Gemini CLI's own event names: `AfterTool` for `write_file` and `replace`, and `AfterAgent` for when it is about to answer, where exit code 2 makes it try again with the errors as feedback. This follows the official Gemini CLI documentation and has not been tested with Gemini CLI.
|
|
475
487
|
|
|
@@ -503,7 +515,10 @@ Without `palette`, designsnitch does not flag default palette classes, and does
|
|
|
503
515
|
|
|
504
516
|
## Scope
|
|
505
517
|
|
|
506
|
-
- **Where it looks in JS and TS:** arbitrary color classes in string literals and template literals, which covers `className` and the arguments of `cn()`, `clsx()` and `cva()`, and colors written as strings
|
|
518
|
+
- **Where it looks in JS and TS:** arbitrary color classes in string literals and template literals, which covers `className` and the arguments of `cn()`, `clsx()` and `cva()`, and colors written as strings where a color is expected, including the branches of `a ? "#fff" : "#000"` and `x || "#fff"`. Comments are ignored.
|
|
519
|
+
- **Styles:** a JSX `style` object and an object typed `CSSProperties`. `var(--token)` works there, so these are checked like any other color. A variable name such as `cardStyle` is not taken as proof: it may hold chart settings.
|
|
520
|
+
- **Other color properties:** a property or JSX attribute whose name is a CSS color property or ends in `Color`, such as `backgroundColor` in chart options or `stroke` on an SVG element. The color is reported, with `var(--token)` as a candidate, but marked `ask`: the tool cannot tell whether `var()` works where the value ends up, for example on a canvas.
|
|
521
|
+
- **Everything else:** colors under other keys (`{ primary: "#3B82F6" }`) and in arrays are not checked, because their purpose cannot be told from the code. The check counts them in `unchecked` so that you know they are there, and `designsnitch colors` lists them.
|
|
507
522
|
- **Where it looks in CSS:** colors in declaration values and arbitrary color classes in `@apply`, in `.css` files including CSS Modules. In the token CSS, declarations that define a variable (`--name: ...`) are skipped, since that is where tokens are defined. In every other CSS file they are checked like any other declaration. Only colors are checked in CSS for now.
|
|
508
523
|
- **Themes:** when a token has different values per theme, all of them count as that token's value. Replacing a color with such a token changes the color in the other themes, so those errors are marked `ask`.
|
|
509
524
|
- **Fixes:** designsnitch reports candidates and never rewrites code by itself, even when there is only one candidate.
|
|
@@ -512,7 +527,7 @@ Without `palette`, designsnitch does not flag default palette classes, and does
|
|
|
512
527
|
|
|
513
528
|
These are detected, but not matched to a token:
|
|
514
529
|
|
|
515
|
-
- Translucent colors (`#3B82F680`, `rgb(0 0 0 / 50%)`)
|
|
530
|
+
- Translucent colors (`#3B82F680`, `rgb(0 0 0 / 50%)`) get the token of the opaque color with an opacity: `bg-brand/50` for a class, `color-mix(in srgb, var(--color-brand) 50%, transparent)` for a style or a CSS declaration. The opacity is rounded to a whole percent, so these are marked `ask`. Fully transparent values such as `rgba(0, 0, 0, 0)` are not colors in use and are skipped.
|
|
516
531
|
- Colors a Tailwind plugin adds are not known as tokens, so writing one by hand is reported as a color with no token.
|
|
517
532
|
- `hwb()`, `lab()`, `lch()`, `oklab()` and `color()` values, and `oklch()` colors outside sRGB, match only a token written with the same value: no hex color renders the same.
|
|
518
533
|
- Color names are read in color properties (`color`, `background`, `border`, ...), in arbitrary classes (`bg-[white]`), and as a whole custom property value. Elsewhere a word such as `red` is not taken for a color.
|
|
@@ -521,7 +536,7 @@ These are not checked:
|
|
|
521
536
|
|
|
522
537
|
- Values from Tailwind's default theme other than the color palette
|
|
523
538
|
- The nearest token for a color that has none
|
|
524
|
-
-
|
|
539
|
+
- Colors under keys that do not say color, such as `{ primary: "#3B82F6" }`, and colors in arrays. They are counted in `unchecked`.
|
|
525
540
|
- SCSS and other preprocessors
|
|
526
541
|
- Spacing, font size and radius. They were left out of this version on purpose.
|
|
527
542
|
- Comparing a hand-made component's styles with the design system component
|
package/bin/designsnitch.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// ESLint 10 의 최소 버전과 같다. 이보다 낮으면 ESM 으로 쓴 Tailwind 설정을 require 로 읽지 못한다.
|
|
4
|
+
const MINIMUM_NODE = [20, 19];
|
|
4
5
|
|
|
5
6
|
/** @param {string} version process.versions.node 와 같은 형식의 버전 */
|
|
6
7
|
export function isSupportedNodeVersion(version) {
|
|
7
|
-
|
|
8
|
+
const [major, minor] = version.split(".").map(Number);
|
|
9
|
+
return major > MINIMUM_NODE[0] || (major === MINIMUM_NODE[0] && minor >= MINIMUM_NODE[1]);
|
|
8
10
|
}
|
|
9
11
|
|
|
10
12
|
const version = process.versions.node;
|
|
@@ -30,7 +32,7 @@ async function main() {
|
|
|
30
32
|
}
|
|
31
33
|
const { messages, resolveLang } = await import("../src/messages.js");
|
|
32
34
|
const message = messages(resolveLang(flagLang)).nodeVersionUnsupported;
|
|
33
|
-
process.stderr.write(`${message({ minimum:
|
|
35
|
+
process.stderr.write(`${message({ minimum: MINIMUM_NODE.join("."), version })}\n`);
|
|
34
36
|
process.exitCode = 2;
|
|
35
37
|
return;
|
|
36
38
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "designsnitch",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"description": "Keep AI-written UI code manageable and consistent, even without a design system. CLI, agent skills, ESLint plugin and agent hook for React/Next.js with Tailwind CSS v4.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"designsnitch": "bin/designsnitch.js"
|
|
27
27
|
},
|
|
28
28
|
"engines": {
|
|
29
|
-
"node": ">=
|
|
29
|
+
"node": ">=20.19"
|
|
30
30
|
},
|
|
31
31
|
"repository": {
|
|
32
32
|
"type": "git",
|
|
@@ -71,7 +71,7 @@ The exit code is 0 (no errors), 1 (errors found), or 2 (could not run). On 2, re
|
|
|
71
71
|
- `action` says how to handle each violation. Section 3 covers each value.
|
|
72
72
|
- `found` is the offending piece of code. `candidates` lists what to use instead: classes or components in JS and TS files, and `var(--token)` in inline styles and `.css` files.
|
|
73
73
|
- `recommended` is the candidate whose token is named for how the color is used here, such as the text token for a `text-` class. It is a suggestion to put in front of the user, not permission to replace.
|
|
74
|
-
- `decisions` groups every `ask` violation into questions: one per color or tag with the same candidates, most used first. Each has `uses`, `files`, up to five `locations`, the `candidates`, a `recommended` candidate when all locations agree, and `reasons` (`multiple-candidates`, `no-token`, `themed-token`, `class-only-token`, `dynamic-props`). Ask the user about decisions, not about single violations.
|
|
74
|
+
- `decisions` groups every `ask` violation into questions: one per color or tag with the same candidates, most used first. Each has `uses`, `files`, up to five `locations`, the `candidates`, a `recommended` candidate when all locations agree, and `reasons` (`multiple-candidates`, `no-token`, `themed-token`, `translucent`, `not-a-style`, `class-only-token`, `dynamic-props`). Ask the user about decisions, not about single violations.
|
|
75
75
|
- `unchecked` counts colors in other strings, such as theme objects and chart options, that the check could not judge. They are not violations. If the count is large and those strings feed the UI, mention it to the user: `npx designsnitch colors` lists them.
|
|
76
76
|
- `designSystem` counts the tokens and components read from the config. `paletteColors` is the number of Tailwind default palette colors in the standard, when the config has `"palette": "tailwind"`. `colorTokens` 0 means the project has no color tokens that can be read: follow the `designsnitch-palette` skill to establish them before touching any color.
|
|
77
77
|
- A non-empty `problems` means the config is broken and the results cannot be trusted. Tell the user before fixing anything.
|
|
@@ -88,8 +88,8 @@ The exit code is 0 (no errors), 1 (errors found), or 2 (could not run). On 2, re
|
|
|
88
88
|
| `action` | What it means | What to do |
|
|
89
89
|
| --- | --- | --- |
|
|
90
90
|
| `replace` | A color error whose only candidate keeps the screen and the behavior the same. | Replace `found` with the candidate. |
|
|
91
|
-
| `migrate` | A raw tag with exactly one design system component to move to. Whether the component behaves like the tag is not known. |
|
|
92
|
-
| `ask` | A person has to decide: several candidates, a color that has no token, a token whose value differs between themes, a token that exists only as a class (no CSS variable to use in a style or a CSS declaration), or a component whose props are dynamic or spread. `message` says which. | Do not change it. Ask the user as described in section 4. |
|
|
91
|
+
| `migrate` | A raw tag with exactly one design system component to move to. Whether the component behaves like the tag is not known. | Read the component, then move the tag to it as described below. If the component cannot do what the tag did, such as not passing on `type="submit"` or an event handler, leave the tag and tell the user. The hook does not force this one. |
|
|
92
|
+
| `ask` | A person has to decide: several candidates, a color that has no token, a token whose value differs between themes, a translucent color (the candidate rounds its opacity), a color in a property that is not a style (such as chart options, where `var()` may not work: read how the value is used before replacing), a token that exists only as a class (no CSS variable to use in a style or a CSS declaration), or a component whose props are dynamic or spread. `message` says which. | Do not change it. Ask the user as described in section 4. |
|
|
93
93
|
| `repair` | The file could not be parsed. | Fix the syntax error, then check again. |
|
|
94
94
|
|
|
95
95
|
For `migrate`, replacing means more than renaming the tag. Read the design system component file to learn its props, add the import, pass on the tag's props the component accepts, and remove className values that duplicate styles the component already has. Check that event handlers such as `onClick` and attributes such as `type` still reach the rendered element.
|
|
@@ -130,3 +130,4 @@ Report what you fixed and what you left, separately. For what you left, use the
|
|
|
130
130
|
- Do not edit `designsnitch.config.json` or the token CSS to make the check pass. They are the standard the code is judged against. If one of them seems wrong, explain why and ask the user.
|
|
131
131
|
- Do not add `eslint-disable` or `designsnitch-disable-next-line` comments, lower a rule's severity, or turn a rule off to make the check pass. If an exception seems necessary, ask the user.
|
|
132
132
|
- Do not pick one of several candidates on your own.
|
|
133
|
+
- Do not change how the tokens are declared, such as turning `@theme` into `@theme static`, to make a `var(--token)` candidate work. Tailwind outputs a theme variable as soon as a class, a style or a CSS file uses it. A variable missing from the compiled CSS before the replacement is expected.
|
|
@@ -11,15 +11,17 @@ A skill is advice: an agent may or may not follow it. A hook is run by the agent
|
|
|
11
11
|
|
|
12
12
|
## What the hook does
|
|
13
13
|
|
|
14
|
-
`npx designsnitch hook` checks only the files the agent just changed, and blocks only errors the change added. It compares each file with its version in git `HEAD
|
|
14
|
+
`npx designsnitch hook` checks only the files the agent just changed, and blocks only errors the change added. It compares each file with its version in git `HEAD`, and with what the working tree looked like when the session started: errors that were already there do not block, committed or not.
|
|
15
15
|
|
|
16
16
|
| When it runs | What happens |
|
|
17
17
|
| --- | --- |
|
|
18
18
|
| Right after the agent edits a file | If that file has errors, the agent receives them with what to do next. |
|
|
19
|
-
| When the
|
|
19
|
+
| When the session starts | The errors already in the changed files are noted, so they are not blamed on this session. Nothing is reported. |
|
|
20
|
+
| When the agent is about to finish | If `replace` errors, or files that cannot be parsed, remain in the changed files, the agent is not allowed to finish. |
|
|
20
21
|
|
|
21
22
|
- Warnings never block.
|
|
22
23
|
- Errors that need a person's decision (`ask`) are reported after an edit, but do not stop the agent from finishing. The agent has to stop in order to ask.
|
|
24
|
+
- Tags to move to a component (`migrate`) are reported after an edit, but do not stop the agent from finishing either. The tool cannot tell whether the component behaves like the tag, so that call is left to the agent and the user.
|
|
23
25
|
- Files the agent did not touch are left alone. Errors that were already in the files it touched are reported only if the change added more of them.
|
|
24
26
|
|
|
25
27
|
## 1. Register the hook in Claude Code
|
|
@@ -47,6 +49,11 @@ If you need to do it by hand, this is what it adds to `.claude/settings.json`.
|
|
|
47
49
|
{
|
|
48
50
|
"hooks": [{ "type": "command", "command": "npx designsnitch hook" }]
|
|
49
51
|
}
|
|
52
|
+
],
|
|
53
|
+
"SessionStart": [
|
|
54
|
+
{
|
|
55
|
+
"hooks": [{ "type": "command", "command": "npx designsnitch hook" }]
|
|
56
|
+
}
|
|
50
57
|
]
|
|
51
58
|
}
|
|
52
59
|
}
|
|
@@ -75,6 +82,11 @@ It adds the hook to `.codex/hooks.json` and copies the skills into `.agents/skil
|
|
|
75
82
|
{
|
|
76
83
|
"hooks": [{ "type": "command", "command": "npx designsnitch hook", "timeout": 60 }]
|
|
77
84
|
}
|
|
85
|
+
],
|
|
86
|
+
"SessionStart": [
|
|
87
|
+
{
|
|
88
|
+
"hooks": [{ "type": "command", "command": "npx designsnitch hook", "timeout": 60 }]
|
|
89
|
+
}
|
|
78
90
|
]
|
|
79
91
|
}
|
|
80
92
|
}
|
|
@@ -106,6 +118,11 @@ It adds the hook to `.gemini/settings.json` and copies the skills into `.agents/
|
|
|
106
118
|
{
|
|
107
119
|
"hooks": [{ "name": "designsnitch", "type": "command", "command": "npx designsnitch hook", "timeout": 60000 }]
|
|
108
120
|
}
|
|
121
|
+
],
|
|
122
|
+
"SessionStart": [
|
|
123
|
+
{
|
|
124
|
+
"hooks": [{ "name": "designsnitch", "type": "command", "command": "npx designsnitch hook", "timeout": 60000 }]
|
|
125
|
+
}
|
|
109
126
|
]
|
|
110
127
|
}
|
|
111
128
|
}
|
|
@@ -122,7 +139,7 @@ Tell the user that Gemini CLI warns before it runs a new project hook, and that
|
|
|
122
139
|
npx designsnitch install --agent grok
|
|
123
140
|
```
|
|
124
141
|
|
|
125
|
-
It writes `.grok/hooks/designsnitch.json` with the same `PostToolUse` and `Stop` hooks as Claude Code (`timeout` in seconds), and copies the skills into `.grok/skills`. Grok Build sends the hook its input in camelCase (`hookEventName`, `toolInput`), which `designsnitch hook` understands.
|
|
142
|
+
It writes `.grok/hooks/designsnitch.json` with the same `PostToolUse` and `Stop` hooks as Claude Code, without `SessionStart`, which the xAI documentation does not confirm (`timeout` in seconds), and copies the skills into `.grok/skills`. Grok Build sends the hook its input in camelCase (`hookEventName`, `toolInput`), which `designsnitch hook` understands.
|
|
126
143
|
|
|
127
144
|
Tell the user two things.
|
|
128
145
|
|
|
@@ -136,6 +153,7 @@ Tell the user two things.
|
|
|
136
153
|
- `tool_input.file_path`: the file that was just edited. Without it, the files that git reports as changed are checked.
|
|
137
154
|
- `hook_event_name` (or `hookEventName`): `Stop`, `SubagentStop` or `AfterAgent` means the agent is about to finish.
|
|
138
155
|
- `stop_hook_active`: when true, the hook does not block again.
|
|
156
|
+
- `session_id` (or `sessionId`): lets the hook remember which errors were there before the session. `hook_event_name` `SessionStart` notes them and reports nothing.
|
|
139
157
|
|
|
140
158
|
It exits with 2 and writes what to fix to stderr when it blocks, and exits with 0 otherwise. If the agent in use supports command hooks with these conventions, register the same command there. Check that agent's hook documentation for the file and the event names, and tell the user if you could not confirm that it works.
|
|
141
159
|
|
package/src/check.js
CHANGED
|
@@ -2,9 +2,17 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { replacementNames, tokenSettings } from "./config.js";
|
|
4
4
|
import { findArbitraryColors, tokenToClass } from "./core/classes.js";
|
|
5
|
-
import { colorLabel,
|
|
5
|
+
import { colorLabel, parseColor } from "./core/color.js";
|
|
6
6
|
import { findCssColors } from "./core/css.js";
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
cssColorPrefixes,
|
|
9
|
+
lookupColor,
|
|
10
|
+
recommendColorCandidate,
|
|
11
|
+
selectColorTokens,
|
|
12
|
+
tokenClass,
|
|
13
|
+
tokenValue,
|
|
14
|
+
utilityColorPrefixes,
|
|
15
|
+
} from "./core/tokens.js";
|
|
8
16
|
import { createEngine } from "./engine.js";
|
|
9
17
|
import { splitPaths } from "./files.js";
|
|
10
18
|
import plugin from "./index.js";
|
|
@@ -47,7 +55,7 @@ const MAX_DECISION_LOCATIONS = 5;
|
|
|
47
55
|
* @property {Pick<Violation, "file" | "line" | "column">[]} locations 위반 위치 최대 다섯 곳
|
|
48
56
|
* @property {string[]} candidates
|
|
49
57
|
* @property {string | null} recommended 각 위치에서 추천이 같을 때 그 후보
|
|
50
|
-
* @property {("multiple-candidates" | "no-token" | "themed-token" | "class-only-token" | "dynamic-props")[]} reasons
|
|
58
|
+
* @property {("multiple-candidates" | "no-token" | "themed-token" | "class-only-token" | "translucent" | "not-a-style" | "dynamic-props")[]} reasons
|
|
51
59
|
*/
|
|
52
60
|
|
|
53
61
|
/**
|
|
@@ -176,8 +184,9 @@ function checkCss(file, source, tokens, m, options) {
|
|
|
176
184
|
// @apply 의 클래스는 JS 의 클래스처럼 토큰 클래스로, 선언의 값은 var(--토큰) 으로 바꾼다.
|
|
177
185
|
const found = text ?? value;
|
|
178
186
|
const prefixes = utility ? utilityColorPrefixes(utility) : cssColorPrefixes(prop);
|
|
179
|
-
const
|
|
180
|
-
const
|
|
187
|
+
const { names: known, opacity } = lookupColor(tokens.colors, value);
|
|
188
|
+
const toCandidate = (name) =>
|
|
189
|
+
utility ? tokenClass(utility, name, opacity) : tokenValue(name, tokens.prefix, opacity);
|
|
181
190
|
// 클래스로만 쓸 수 있는 토큰은 선언의 값을 대신할 수 없다. 그래도 직접 쓴 색이라는 것은 알린다.
|
|
182
191
|
const usable = utility ? known : known.filter((name) => !tokens.classOnly.has(name));
|
|
183
192
|
if (known.length > 0 && usable.length === 0) {
|
|
@@ -196,7 +205,8 @@ function checkCss(file, source, tokens, m, options) {
|
|
|
196
205
|
const tokenNames = selectColorTokens(usable, tokens.prefer, prefixes);
|
|
197
206
|
const candidates = tokenNames.map(toCandidate);
|
|
198
207
|
const recommendedToken = recommendColorCandidate(tokenNames, prefixes);
|
|
199
|
-
const messageId =
|
|
208
|
+
const messageId =
|
|
209
|
+
opacity !== null ? "useTokenAlpha" : tokenNames.some((name) => tokens.themed.has(name)) ? "useTokenThemed" : "useToken";
|
|
200
210
|
return {
|
|
201
211
|
file,
|
|
202
212
|
...location,
|
|
@@ -209,6 +219,7 @@ function checkCss(file, source, tokens, m, options) {
|
|
|
209
219
|
found,
|
|
210
220
|
tokens: tokenNames.join(", "),
|
|
211
221
|
candidates: candidates.join(", "),
|
|
222
|
+
opacity,
|
|
212
223
|
}),
|
|
213
224
|
}
|
|
214
225
|
: {
|
|
@@ -233,7 +244,9 @@ function realPath(file) {
|
|
|
233
244
|
|
|
234
245
|
function actionFor({ rule, severity, candidates }, messageId) {
|
|
235
246
|
if (rule === "parse-error") return "repair";
|
|
236
|
-
|
|
247
|
+
// 반투명한 색은 불투명도를 반올림해 후보를 내므로, 바꿔도 같은 색이라고 보장할 수 없다.
|
|
248
|
+
// 스타일이 아닌 자리의 색은 var() 가 통하는지 알 수 없다.
|
|
249
|
+
if (["useComponentAsk", "useTokenThemed", "useTokenAlpha", "useTokenData"].includes(messageId)) return "ask";
|
|
237
250
|
if (severity !== "error" || candidates.length !== 1) return "ask";
|
|
238
251
|
// 컴포넌트는 props 와 기본 스타일이 태그와 다를 수 있어서, 바꿔도 같다고 보장할 수 없다.
|
|
239
252
|
return rule === "use-ds-component" ? "migrate" : "replace";
|
|
@@ -271,6 +284,8 @@ function groupDecisions(violations) {
|
|
|
271
284
|
if (rule === "color-unknown") decision.reasons.add("no-token");
|
|
272
285
|
if (messageId === "useTokenThemed") decision.reasons.add("themed-token");
|
|
273
286
|
if (messageId === "useTokenClassOnly") decision.reasons.add("class-only-token");
|
|
287
|
+
if (messageId === "useTokenAlpha") decision.reasons.add("translucent");
|
|
288
|
+
if (messageId === "useTokenData") decision.reasons.add("not-a-style");
|
|
274
289
|
if (messageId === "useComponentAsk") decision.reasons.add("dynamic-props");
|
|
275
290
|
}
|
|
276
291
|
|
package/src/colors.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { findArbitraryColors, findPaletteClasses } from "./core/classes.js";
|
|
4
|
-
import { colorLabel, isColorProperty, isNamedColor,
|
|
4
|
+
import { colorLabel, isColorProperty, isNamedColor, isVisibleColor } from "./core/color.js";
|
|
5
5
|
import { findCssColors } from "./core/css.js";
|
|
6
6
|
import { createEngine } from "./engine.js";
|
|
7
7
|
import { splitPaths } from "./files.js";
|
|
@@ -37,7 +37,7 @@ const collectRule = {
|
|
|
37
37
|
// 문자열 전체가 색인 경우. 예: style={{ color: "#3B82F6" }}
|
|
38
38
|
// 색 이름은 인라인 스타일의 색 속성에서만 색으로 센다. 다른 곳에서는 그냥 단어일 수 있다.
|
|
39
39
|
const isColor = (value) =>
|
|
40
|
-
|
|
40
|
+
isVisibleColor(value) && (!isNamedColor(value) || isColorProperty(inlineStyleProperty(node) ?? ""));
|
|
41
41
|
if (typeof node.value === "string" && isColor(node.value)) {
|
|
42
42
|
report(node.loc, { kind: "hex", key: colorLabel(node.value), utility: null });
|
|
43
43
|
return;
|
package/src/core/classes.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isVisibleColor } from "./color.js";
|
|
2
2
|
|
|
3
3
|
// 예: bg-[#3B82F6], ring-offset-[#fff], text-[rgb(59,130,246)], bg-[oklch(62.3%_0.214_259.815)], bg-[white]
|
|
4
4
|
const ARBITRARY_COLOR =
|
|
@@ -11,7 +11,7 @@ const ARBITRARY_COLOR =
|
|
|
11
11
|
*/
|
|
12
12
|
export function findArbitraryColors(text) {
|
|
13
13
|
return [...text.matchAll(ARBITRARY_COLOR)]
|
|
14
|
-
.filter((match) =>
|
|
14
|
+
.filter((match) => isVisibleColor(match[2]))
|
|
15
15
|
.map((match) => ({
|
|
16
16
|
index: match.index,
|
|
17
17
|
text: match[0],
|
package/src/core/color.js
CHANGED
|
@@ -57,6 +57,12 @@ export function parseColor(value) {
|
|
|
57
57
|
return { key: `#${rgb.map(toByte).join("")}`, alpha, opaque: alpha >= 1 };
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
/** 색으로 읽히고 완전히 투명하지 않은 값인지. rgba(0, 0, 0, 0) 은 색을 쓴 것이 아니다. */
|
|
61
|
+
export function isVisibleColor(value) {
|
|
62
|
+
const color = parseColor(value);
|
|
63
|
+
return color !== null && color.alpha > 0;
|
|
64
|
+
}
|
|
65
|
+
|
|
60
66
|
/**
|
|
61
67
|
* 색을 세거나 묶을 때 쓰는 이름. 표기가 달라도 같은 색이면 같은 이름이 된다.
|
|
62
68
|
* 불투명한 색은 normalizeColor 와 같고, 반투명한 색은 #rrggbbaa 다. 색이 아니면 소문자로만 맞춘다.
|
|
@@ -89,7 +95,7 @@ export function normalizeColor(value) {
|
|
|
89
95
|
export function findColorValues(text, { named = false } = {}) {
|
|
90
96
|
const matches = [...text.matchAll(COLOR_VALUE), ...(named ? text.matchAll(NAMED_VALUE) : [])];
|
|
91
97
|
return matches
|
|
92
|
-
.filter((match) =>
|
|
98
|
+
.filter((match) => isVisibleColor(match[0]))
|
|
93
99
|
.sort((a, b) => a.index - b.index)
|
|
94
100
|
.map((match) => ({ index: match.index, text: match[0], value: match[0] }));
|
|
95
101
|
}
|
package/src/core/tokens.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import postcss from "postcss";
|
|
2
|
-
import { normalizeColor } from "./color.js";
|
|
2
|
+
import { normalizeColor, parseColor } from "./color.js";
|
|
3
3
|
|
|
4
4
|
const COLOR_TOKEN = /^--color-/;
|
|
5
5
|
const ROLE_PREFIXES = {
|
|
@@ -7,6 +7,27 @@ const ROLE_PREFIXES = {
|
|
|
7
7
|
border: ["--color-border-"],
|
|
8
8
|
bg: ["--color-bg-", "--color-surface", "--color-background"],
|
|
9
9
|
};
|
|
10
|
+
// 값을 정할 수 없다는 표시. 가리키는 변수가 없고 fallback 도 없는 경우다.
|
|
11
|
+
const UNRESOLVED = "";
|
|
12
|
+
// 조건이 맞을 때만 적용되는 at-rule. 그 안의 선언은 전역이 아니다.
|
|
13
|
+
const CONDITIONAL_AT_RULES = new Set(["media", "supports", "container", "scope", "starting-style"]);
|
|
14
|
+
// 문서 전체에 적용되는 선택자
|
|
15
|
+
const GLOBAL_SELECTOR = /^(?::root|html|:host|\*)$/;
|
|
16
|
+
|
|
17
|
+
/** 선언이 어디서나 적용되는지. @theme 안이거나, 조건 없는 :root, html, :host 규칙 안이다. */
|
|
18
|
+
function isGlobal(decl) {
|
|
19
|
+
let rule = null;
|
|
20
|
+
for (let node = decl.parent; node && node.type !== "root"; node = node.parent) {
|
|
21
|
+
if (node.type === "atrule") {
|
|
22
|
+
if (node.name === "theme") return true;
|
|
23
|
+
if (CONDITIONAL_AT_RULES.has(node.name)) return false;
|
|
24
|
+
} else if (node.type === "rule") {
|
|
25
|
+
rule ??= node;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return !rule || rule.selectors.every((selector) => GLOBAL_SELECTOR.test(selector.trim()));
|
|
29
|
+
}
|
|
30
|
+
|
|
10
31
|
// var(--name) 또는 var(--name, 대체값)
|
|
11
32
|
const VAR_REFERENCE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/s;
|
|
12
33
|
|
|
@@ -30,42 +51,51 @@ export function parseColorTokens(css) {
|
|
|
30
51
|
* names 는 값을 읽었든 못 읽었든 선언된 --color-* 이름, resets 는 initial 로 비운 네임스페이스(예: "--color-*")
|
|
31
52
|
*/
|
|
32
53
|
export function parseColorTokenData(css, exclude = []) {
|
|
33
|
-
/** @type {Map<string, string[]>} 변수 이름 → 선언된 값들 */
|
|
54
|
+
/** @type {Map<string, { global: string[], scoped: string[] }>} 변수 이름 → 전역에서 선언된 값들과 일부에서만 선언된 값들 */
|
|
34
55
|
const declared = new Map();
|
|
35
56
|
postcss.parse(css).walkDecls(/^--/, (decl) => {
|
|
36
|
-
const values = declared.get(decl.prop) ?? [];
|
|
37
|
-
values.push(decl.value);
|
|
57
|
+
const values = declared.get(decl.prop) ?? { global: [], scoped: [] };
|
|
58
|
+
values[isGlobal(decl) ? "global" : "scoped"].push(decl.value);
|
|
38
59
|
declared.set(decl.prop, values);
|
|
39
60
|
});
|
|
40
61
|
|
|
41
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* 값이 결국 가리키는 값들. 값을 정할 수 없는 경우가 있으면 UNRESOLVED 가 섞인다.
|
|
64
|
+
* @returns {string[]}
|
|
65
|
+
*/
|
|
42
66
|
function resolve(value, visiting) {
|
|
43
67
|
const trimmed = value.trim();
|
|
44
68
|
const reference = VAR_REFERENCE.exec(trimmed);
|
|
45
69
|
if (!reference) return [trimmed];
|
|
46
70
|
const [, name, fallback] = reference;
|
|
47
71
|
if (visiting.has(name)) return [];
|
|
48
|
-
|
|
72
|
+
const whenMissing = () => (fallback ? resolve(fallback, visiting) : [UNRESOLVED]);
|
|
73
|
+
const target = declared.get(name);
|
|
74
|
+
if (!target) return whenMissing();
|
|
49
75
|
|
|
50
76
|
const next = new Set(visiting).add(name);
|
|
51
|
-
|
|
77
|
+
const values = [...target.global, ...target.scoped].flatMap((item) => resolve(item, next));
|
|
78
|
+
// 변수가 일부 선택자에만 있으면, 그 밖에서는 fallback 이 쓰인다.
|
|
79
|
+
return target.global.length === 0 ? [...whenMissing(), ...values] : values;
|
|
52
80
|
}
|
|
53
81
|
|
|
54
82
|
const colors = new Map();
|
|
55
83
|
const themed = new Set();
|
|
56
84
|
const names = new Set();
|
|
57
85
|
const resets = [];
|
|
58
|
-
for (const [name,
|
|
86
|
+
for (const [name, { global, scoped }] of declared) {
|
|
59
87
|
// Tailwind 는 --color-*: initial 처럼 네임스페이스를 비울 수 있다. 토큰이 아니라 기본 테마를 지우는 선언이다.
|
|
60
88
|
if (name.endsWith("*")) {
|
|
61
|
-
if (
|
|
89
|
+
if ([...global, ...scoped].some((value) => value.trim() === "initial")) resets.push(name);
|
|
62
90
|
continue;
|
|
63
91
|
}
|
|
64
92
|
if (!COLOR_TOKEN.test(name)) continue;
|
|
93
|
+
// .promo { --color-promo: ... } 처럼 일부에서만 선언된 변수는 어디서나 쓸 수 있는 토큰이 아니다.
|
|
94
|
+
if (global.length === 0) continue;
|
|
65
95
|
names.add(name);
|
|
66
96
|
if (exclude.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern)) continue;
|
|
67
97
|
const resolved = new Set();
|
|
68
|
-
for (const value of
|
|
98
|
+
for (const value of [...global, ...scoped].flatMap((value) => resolve(value, new Set([name])))) {
|
|
69
99
|
const color = normalizeColor(value);
|
|
70
100
|
// 색으로 읽지 못한 값도 테마 차이는 만들 수 있지만 색 후보로는 쓰지 않는다.
|
|
71
101
|
const key = color ?? value;
|
|
@@ -85,6 +115,32 @@ export function tokenVar(name, prefix) {
|
|
|
85
115
|
return `var(${prefix ? name.replace(/^--/, `--${prefix}-`) : name})`;
|
|
86
116
|
}
|
|
87
117
|
|
|
118
|
+
/**
|
|
119
|
+
* 색 값에 맞는 토큰을 찾는다. 반투명한 색이면 불투명한 색의 토큰과 불투명도를 함께 준다.
|
|
120
|
+
* @param {Map<string, string[]>} colors 색 값 → 토큰 이름들
|
|
121
|
+
* @param {string} value
|
|
122
|
+
* @returns {{ names: string[], opacity: number | null }} opacity 는 반투명할 때의 불투명도(%). 불투명하면 null
|
|
123
|
+
*/
|
|
124
|
+
export function lookupColor(colors, value) {
|
|
125
|
+
const color = parseColor(value);
|
|
126
|
+
if (!color) return { names: [], opacity: null };
|
|
127
|
+
// 0 은 아니지만 반올림하면 0% 가 되는 값은 1% 로 본다. 0% 는 완전히 투명하다는 다른 뜻이다.
|
|
128
|
+
const opacity = color.opaque ? null : Math.max(1, Math.round(color.alpha * 100));
|
|
129
|
+
return { names: colors.get(color.key) ?? [], opacity };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 토큰을 CSS 값으로 쓰는 표기. 불투명도가 있으면 투명과 섞는다. */
|
|
133
|
+
export function tokenValue(name, prefix, opacity) {
|
|
134
|
+
const reference = tokenVar(name, prefix);
|
|
135
|
+
return opacity === null ? reference : `color-mix(in srgb, ${reference} ${opacity}%, transparent)`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** 토큰을 클래스로 쓰는 표기. 불투명도는 Tailwind 의 /50 꼴로 붙인다. 예: bg-brand/50 */
|
|
139
|
+
export function tokenClass(utility, name, opacity) {
|
|
140
|
+
const className = `${utility}-${name.replace(/^--color-/, "")}`;
|
|
141
|
+
return opacity === null ? className : `${className}/${opacity}`;
|
|
142
|
+
}
|
|
143
|
+
|
|
88
144
|
export function utilityColorPrefixes(utility) {
|
|
89
145
|
const kind = utility.toLowerCase().split("-", 1)[0];
|
|
90
146
|
if (["border", "ring", "outline", "divide"].includes(kind)) return ROLE_PREFIXES.border;
|
package/src/hook.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { execFileSync } from "node:child_process";
|
|
2
|
+
import crypto from "node:crypto";
|
|
2
3
|
import fs from "node:fs";
|
|
3
4
|
import os from "node:os";
|
|
4
5
|
import path from "node:path";
|
|
@@ -9,13 +10,19 @@ import { messages, resolveLang } from "./messages.js";
|
|
|
9
10
|
const CHECKABLE = /\.(?:[cm]?[jt]s|[jt]sx|css)$/;
|
|
10
11
|
// Claude Code, Codex 는 Stop, Gemini CLI 는 AfterAgent 가 "작업을 끝내려 할 때"다.
|
|
11
12
|
const STOP_EVENTS = new Set(["Stop", "SubagentStop", "AfterAgent"]);
|
|
13
|
+
const SESSION_START = "SessionStart";
|
|
14
|
+
// 에이전트가 스스로 할 수 있고, 해도 화면과 동작이 같다고 볼 수 있는 일. 이것만 끝내는 것을 막는다.
|
|
15
|
+
const SAFE_TO_INSIST = new Set(["replace", "repair"]);
|
|
12
16
|
|
|
13
17
|
/**
|
|
14
18
|
* 코딩 에이전트의 훅에서 부르는 검사. 에이전트가 방금 고친 파일만 본다.
|
|
15
19
|
*
|
|
16
|
-
* - 파일을 고친 직후:
|
|
17
|
-
* - 작업을 끝내려 할 때(Stop):
|
|
18
|
-
* 사람이 정해야 하는
|
|
20
|
+
* - 파일을 고친 직후: 새 오류가 있으면 종료 코드 2와 함께 stderr 로 알린다.
|
|
21
|
+
* - 작업을 끝내려 할 때(Stop): 바꿔도 화면과 동작이 같은 새 오류(replace, repair)가 남아 있으면 2로 막는다.
|
|
22
|
+
* 사람이 정해야 하는 오류(ask)와 컴포넌트로 옮길 오류(migrate)만 남았으면 막지 않는다.
|
|
23
|
+
* 물어보려면 멈춰야 하고, 옮겨도 동작이 같은지는 도구가 알 수 없기 때문이다.
|
|
24
|
+
* - "새 오류"의 기준은 HEAD 와, 세션이 시작될 때 이미 바뀌어 있던 파일의 상태다.
|
|
25
|
+
* 세션 시작(SessionStart) 때, 없었으면 세션의 첫 수정 때 그 상태를 적어 둔다.
|
|
19
26
|
* - 경고는 막지 않는다. 설정 파일이 없는 프로젝트에서는 아무것도 하지 않는다.
|
|
20
27
|
*
|
|
21
28
|
* @param {object} options
|
|
@@ -32,34 +39,54 @@ export async function runHook({ cwd, input = "", configPath = CONFIG_FILE, lang
|
|
|
32
39
|
const eventName = event.hook_event_name ?? event.hookEventName;
|
|
33
40
|
const toolInput = event.tool_input ?? event.toolInput;
|
|
34
41
|
const stopping = STOP_EVENTS.has(eventName);
|
|
42
|
+
const sessionId = event.session_id ?? event.sessionId;
|
|
35
43
|
|
|
36
44
|
// 이미 한 번 막아서 에이전트가 고치는 중이면 다시 막지 않는다.
|
|
37
45
|
if (stopping && (event.stop_hook_active ?? event.stopHookActive)) return pass;
|
|
38
46
|
if (!fs.existsSync(path.resolve(cwd, configPath))) return pass;
|
|
39
47
|
|
|
48
|
+
const checkable = (list) =>
|
|
49
|
+
list
|
|
50
|
+
.map((file) => path.resolve(cwd, file))
|
|
51
|
+
.filter((file) => isInside(cwd, file) && CHECKABLE.test(file) && fs.existsSync(file))
|
|
52
|
+
.map((file) => path.relative(cwd, file));
|
|
40
53
|
const edited = toolInput?.file_path ?? toolInput?.filePath;
|
|
41
|
-
const files = (typeof edited === "string" ? [edited] : changedFiles(cwd))
|
|
42
|
-
.map((file) => path.resolve(cwd, file))
|
|
43
|
-
.filter((file) => isInside(cwd, file) && CHECKABLE.test(file) && fs.existsSync(file))
|
|
44
|
-
.map((file) => path.relative(cwd, file));
|
|
45
|
-
if (files.length === 0) return pass;
|
|
54
|
+
const files = eventName === SESSION_START ? [] : checkable(typeof edited === "string" ? [edited] : changedFiles(cwd));
|
|
46
55
|
|
|
47
|
-
const canBlock = (v) => v.severity === "error" && (!stopping || v.action
|
|
56
|
+
const canBlock = (v) => v.severity === "error" && (!stopping || SAFE_TO_INSIST.has(v.action));
|
|
48
57
|
let result;
|
|
49
58
|
let errors;
|
|
50
59
|
try {
|
|
51
60
|
const config = loadConfig(cwd, configPath, resolveLang(lang));
|
|
52
61
|
lang = resolveLang(lang, config.lang);
|
|
62
|
+
|
|
63
|
+
// 세션이 시작될 때 이미 있던 위반은 이번 작업이 만든 것이 아니다. 처음 한 번만 적어 둔다.
|
|
64
|
+
let session = sessionId ? readSession(cwd, sessionId) : new Map();
|
|
65
|
+
if (sessionId && !session && !stopping) {
|
|
66
|
+
// 세션 시작 때는 바뀐 파일 전부를, 첫 수정 때는 방금 고친 파일을 뺀 나머지를 적는다.
|
|
67
|
+
// 고친 파일을 모르면 무엇이 이번 작업인지 가릴 수 없으니 적지 않는다.
|
|
68
|
+
const own = path.relative(cwd, path.resolve(cwd, typeof edited === "string" ? edited : "."));
|
|
69
|
+
const canTell = eventName === SESSION_START || typeof edited === "string";
|
|
70
|
+
const before = canTell ? checkable(changedFiles(cwd)).filter((file) => file !== own) : [];
|
|
71
|
+
const found = before.length > 0 ? (await check({ cwd, config, paths: before, lang })).violations : [];
|
|
72
|
+
session = countViolations(found);
|
|
73
|
+
writeSession(cwd, sessionId, session);
|
|
74
|
+
}
|
|
75
|
+
if (files.length === 0) return pass;
|
|
76
|
+
|
|
53
77
|
result = await check({ cwd, config, paths: files, lang });
|
|
54
78
|
if (!result.violations.some(canBlock)) return pass;
|
|
55
79
|
|
|
56
|
-
const
|
|
80
|
+
const head = countViolations(await checkHead({ cwd, config, files, lang }));
|
|
57
81
|
const current = countViolations(result.violations);
|
|
58
82
|
errors = result.violations.filter((v) => {
|
|
59
83
|
const key = violationKey(v);
|
|
60
|
-
|
|
84
|
+
const baseline = Math.max(head.get(key) ?? 0, session?.get(key) ?? 0);
|
|
85
|
+
return v.severity === "error" && current.get(key) > baseline;
|
|
61
86
|
});
|
|
62
87
|
} catch (error) {
|
|
88
|
+
// 세션 시작은 알리기만 하는 자리가 아니다. 설정 문제는 첫 수정 때 알린다.
|
|
89
|
+
if (eventName === SESSION_START) return pass;
|
|
63
90
|
return { stderr: `${error.message}\n`, exitCode: 2 };
|
|
64
91
|
}
|
|
65
92
|
|
|
@@ -103,6 +130,30 @@ async function checkHead({ cwd, config, files, lang }) {
|
|
|
103
130
|
}
|
|
104
131
|
}
|
|
105
132
|
|
|
133
|
+
function sessionFile(cwd, sessionId) {
|
|
134
|
+
const id = crypto.createHash("sha256").update(`${fs.realpathSync(cwd)}\0${sessionId}`).digest("hex").slice(0, 40);
|
|
135
|
+
return path.join(os.tmpdir(), "designsnitch-sessions", `${id}.json`);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** @returns {Map<string, number> | null} 세션이 시작될 때의 위반 개수. 적어 둔 것이 없으면 null */
|
|
139
|
+
function readSession(cwd, sessionId) {
|
|
140
|
+
try {
|
|
141
|
+
return new Map(JSON.parse(fs.readFileSync(sessionFile(cwd, String(sessionId)), "utf8")));
|
|
142
|
+
} catch {
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function writeSession(cwd, sessionId, counts) {
|
|
148
|
+
try {
|
|
149
|
+
const file = sessionFile(cwd, String(sessionId));
|
|
150
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
151
|
+
fs.writeFileSync(file, JSON.stringify([...counts]));
|
|
152
|
+
} catch {
|
|
153
|
+
// 적어 두지 못하면 HEAD 만 기준으로 삼는다.
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
106
157
|
function violationKey({ file, rule, found }) {
|
|
107
158
|
return JSON.stringify([file, rule, found]);
|
|
108
159
|
}
|
package/src/install.js
CHANGED
|
@@ -11,6 +11,8 @@ const HOOK_COMMAND = "npx designsnitch hook";
|
|
|
11
11
|
* 에이전트마다 스킬을 읽는 곳, 훅을 등록하는 파일, 이벤트 이름이 다르다.
|
|
12
12
|
* 훅이 하는 일(표준 입력의 JSON 을 읽고, 막을 때 종료 코드 2와 stderr)은 같다.
|
|
13
13
|
* editEvent 는 파일을 고친 직후, stopEvent 는 작업을 끝내려 할 때다.
|
|
14
|
+
* startEvent 는 세션이 시작될 때다. 그때 이미 있던 위반을 적어 두어, 이번 작업이 만든 위반만 막는다.
|
|
15
|
+
* 문서에서 이 이벤트를 확인하지 못한 에이전트에는 등록하지 않는다. 없어도 첫 수정 때 대신 적는다.
|
|
14
16
|
*/
|
|
15
17
|
const AGENTS = {
|
|
16
18
|
claude: {
|
|
@@ -18,6 +20,7 @@ const AGENTS = {
|
|
|
18
20
|
hooksFile: ".claude/settings.json",
|
|
19
21
|
editEvent: "PostToolUse",
|
|
20
22
|
stopEvent: "Stop",
|
|
23
|
+
startEvent: "SessionStart",
|
|
21
24
|
editTools: "Edit|Write|MultiEdit",
|
|
22
25
|
hook: { type: "command", command: HOOK_COMMAND },
|
|
23
26
|
approval: null,
|
|
@@ -27,6 +30,7 @@ const AGENTS = {
|
|
|
27
30
|
hooksFile: ".codex/hooks.json",
|
|
28
31
|
editEvent: "PostToolUse",
|
|
29
32
|
stopEvent: "Stop",
|
|
33
|
+
startEvent: "SessionStart",
|
|
30
34
|
// Codex 는 셸 명령으로도 파일을 고친다. 그런 수정은 Stop 훅이 git 에서 바뀐 파일을 보고 잡는다.
|
|
31
35
|
editTools: "apply_patch",
|
|
32
36
|
hook: { type: "command", command: HOOK_COMMAND, timeout: 60 },
|
|
@@ -39,6 +43,7 @@ const AGENTS = {
|
|
|
39
43
|
hooksFile: ".gemini/settings.json",
|
|
40
44
|
editEvent: "AfterTool",
|
|
41
45
|
stopEvent: "AfterAgent",
|
|
46
|
+
startEvent: "SessionStart",
|
|
42
47
|
editTools: "write_file|replace",
|
|
43
48
|
hook: { name: "designsnitch", type: "command", command: HOOK_COMMAND, timeout: 60000 },
|
|
44
49
|
// 새 프로젝트 훅은 실행하기 전에 경고하고 허용을 받는다.
|
|
@@ -126,6 +131,7 @@ function addHooks(settings, target) {
|
|
|
126
131
|
const entries = {
|
|
127
132
|
[target.editEvent]: { matcher: target.editTools, hooks: [target.hook] },
|
|
128
133
|
[target.stopEvent]: { hooks: [target.hook] },
|
|
134
|
+
...(target.startEvent ? { [target.startEvent]: { hooks: [target.hook] } } : {}),
|
|
129
135
|
};
|
|
130
136
|
settings.hooks ??= {};
|
|
131
137
|
let added = false;
|
package/src/messages.js
CHANGED
|
@@ -33,6 +33,10 @@ const en = {
|
|
|
33
33
|
useTokenThemed: ({ found, tokens, candidates }) =>
|
|
34
34
|
`${found} has the same color as ${tokens}. Candidates: ${candidates}. ` +
|
|
35
35
|
"A candidate token has different values across themes. Using it can change the color in another theme.",
|
|
36
|
+
useTokenAlpha: ({ found, tokens, opacity, candidates }) =>
|
|
37
|
+
`${found} is ${tokens} at ${opacity}% opacity. Use instead: ${candidates}`,
|
|
38
|
+
useTokenData: ({ found, tokens, candidates }) =>
|
|
39
|
+
`${found} has the same color as ${tokens}. It is not in a style, so check that var() works where this value is used. Candidate: ${candidates}`,
|
|
36
40
|
useTokenClassOnly: ({ found, tokens }) =>
|
|
37
41
|
`${found} has the same color as ${tokens}, but that token can only be used as a class: Tailwind makes no CSS variable for it.`,
|
|
38
42
|
unknownColor: ({ found }) => `The color of ${found} is not in the tokens.`,
|
|
@@ -184,6 +188,10 @@ const ko = {
|
|
|
184
188
|
useTokenThemed: ({ found, tokens, candidates }) =>
|
|
185
189
|
`${found}의 색은 토큰 ${tokens}의 값입니다. 후보: ${candidates}. ` +
|
|
186
190
|
"후보 중 테마마다 값이 다른 토큰이 있어 그 토큰으로 바꾸면 다른 테마에서 색이 바뀔 수 있습니다.",
|
|
191
|
+
useTokenAlpha: ({ found, tokens, opacity, candidates }) =>
|
|
192
|
+
`${found}의 색은 토큰 ${tokens}에 불투명도 ${opacity}%를 준 값입니다. 대신 사용: ${candidates}`,
|
|
193
|
+
useTokenData: ({ found, tokens, candidates }) =>
|
|
194
|
+
`${found}의 색은 토큰 ${tokens}의 값입니다. 스타일이 아닌 자리라서, 이 값을 쓰는 곳에서 var()가 통하는지 확인해야 합니다. 후보: ${candidates}`,
|
|
187
195
|
useTokenClassOnly: ({ found, tokens }) =>
|
|
188
196
|
`${found}의 색은 토큰 ${tokens}의 값이지만, 이 토큰은 클래스로만 쓸 수 있습니다. Tailwind가 CSS 변수를 만들지 않습니다.`,
|
|
189
197
|
unknownColor: ({ found }) => `${found}의 색은 토큰에 없습니다.`,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { findArbitraryColors } from "../core/classes.js";
|
|
2
|
-
import {
|
|
2
|
+
import { lookupColor } from "../core/tokens.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";
|
|
@@ -25,7 +25,8 @@ export default {
|
|
|
25
25
|
const { colors } = tokens;
|
|
26
26
|
|
|
27
27
|
function report(found, { loc }) {
|
|
28
|
-
|
|
28
|
+
// 반투명한 색도 불투명한 색에 토큰이 있으면 color-use-token 이 맡는다.
|
|
29
|
+
if (lookupColor(colors, found.value).names.length > 0) return;
|
|
29
30
|
context.report({ loc, messageId: "unknown", data: { text: m.unknownColor({ found: found.text }) } });
|
|
30
31
|
}
|
|
31
32
|
|
|
@@ -1,6 +1,12 @@
|
|
|
1
|
-
import { findArbitraryColors
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { findArbitraryColors } from "../core/classes.js";
|
|
2
|
+
import {
|
|
3
|
+
cssColorPrefixes,
|
|
4
|
+
lookupColor,
|
|
5
|
+
selectColorTokens,
|
|
6
|
+
tokenClass,
|
|
7
|
+
tokenValue,
|
|
8
|
+
utilityColorPrefixes,
|
|
9
|
+
} from "../core/tokens.js";
|
|
4
10
|
import { loadTokens } from "./load-tokens.js";
|
|
5
11
|
import { ruleMessages, suggestClasses, TEXT } from "./suggest.js";
|
|
6
12
|
import { visitStrings } from "./visit-strings.js";
|
|
@@ -13,7 +19,15 @@ export default {
|
|
|
13
19
|
docs: { description: "Use the token instead of writing its color as a hex value" },
|
|
14
20
|
hasSuggestions: true,
|
|
15
21
|
schema: [],
|
|
16
|
-
messages: {
|
|
22
|
+
messages: {
|
|
23
|
+
useToken: TEXT,
|
|
24
|
+
useTokenThemed: TEXT,
|
|
25
|
+
useTokenAlpha: TEXT,
|
|
26
|
+
useTokenData: TEXT,
|
|
27
|
+
useTokenClassOnly: TEXT,
|
|
28
|
+
replace: TEXT,
|
|
29
|
+
tokensConfig: TEXT,
|
|
30
|
+
},
|
|
17
31
|
},
|
|
18
32
|
create(context) {
|
|
19
33
|
let tokens;
|
|
@@ -29,13 +43,20 @@ export default {
|
|
|
29
43
|
const m = ruleMessages(context);
|
|
30
44
|
const { colors, themed, prefer, classOnly } = tokens;
|
|
31
45
|
|
|
32
|
-
function report(found, { loc, range }, tokenNames, candidates) {
|
|
33
|
-
const messageId =
|
|
46
|
+
function report(found, { loc, range }, tokenNames, candidates, opacity) {
|
|
47
|
+
const messageId =
|
|
48
|
+
opacity !== null
|
|
49
|
+
? "useTokenAlpha"
|
|
50
|
+
: found.kind === "data"
|
|
51
|
+
? "useTokenData"
|
|
52
|
+
: tokenNames.some((name) => themed.has(name))
|
|
53
|
+
? "useTokenThemed"
|
|
54
|
+
: "useToken";
|
|
34
55
|
context.report({
|
|
35
56
|
loc,
|
|
36
57
|
messageId,
|
|
37
58
|
data: {
|
|
38
|
-
text: m[messageId]({ found: found.text, tokens: tokenNames.join(", "), candidates: candidates.join(", ") }),
|
|
59
|
+
text: m[messageId]({ found: found.text, tokens: tokenNames.join(", "), candidates: candidates.join(", "), opacity }),
|
|
39
60
|
},
|
|
40
61
|
suggest: suggestClasses(range, candidates, m),
|
|
41
62
|
});
|
|
@@ -43,15 +64,15 @@ export default {
|
|
|
43
64
|
|
|
44
65
|
return mergeVisitors(
|
|
45
66
|
visitStrings(context, findArbitraryColors, (found, where) => {
|
|
46
|
-
const names = colors
|
|
47
|
-
if (
|
|
67
|
+
const { names, opacity } = lookupColor(colors, found.value);
|
|
68
|
+
if (names.length === 0) return;
|
|
48
69
|
const tokenNames = selectColorTokens(names, prefer, utilityColorPrefixes(found.utility));
|
|
49
|
-
report(found, where, tokenNames, tokenNames.map((name) =>
|
|
70
|
+
report(found, where, tokenNames, tokenNames.map((name) => tokenClass(found.utility, name, opacity)), opacity);
|
|
50
71
|
}),
|
|
51
|
-
//
|
|
72
|
+
// 스타일과 색 속성의 값은 클래스가 아니라 var(--토큰) 으로 바꾼다. Tailwind 는 소스에서 쓴 var() 의 변수를 내보낸다.
|
|
52
73
|
visitInlineStyleColors(context, (found, where) => {
|
|
53
|
-
const known = colors
|
|
54
|
-
if (
|
|
74
|
+
const { names: known, opacity } = lookupColor(colors, found.value);
|
|
75
|
+
if (known.length === 0) return;
|
|
55
76
|
// 클래스로만 쓸 수 있는 토큰은 스타일 값을 대신할 수 없다. 그래도 직접 쓴 색이라는 것은 알린다.
|
|
56
77
|
const names = known.filter((name) => !classOnly.has(name));
|
|
57
78
|
if (names.length === 0) {
|
|
@@ -60,7 +81,7 @@ export default {
|
|
|
60
81
|
return;
|
|
61
82
|
}
|
|
62
83
|
const tokenNames = selectColorTokens(names, prefer, cssColorPrefixes(found.property));
|
|
63
|
-
report(found, where, tokenNames, tokenNames.map((name) =>
|
|
84
|
+
report(found, where, tokenNames, tokenNames.map((name) => tokenValue(name, tokens.prefix, opacity)), opacity);
|
|
64
85
|
}),
|
|
65
86
|
);
|
|
66
87
|
},
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { findArbitraryColors } from "../core/classes.js";
|
|
2
2
|
import { findColorValues } from "../core/color.js";
|
|
3
3
|
import { visitStrings } from "./visit-strings.js";
|
|
4
|
-
import {
|
|
4
|
+
import { colorContext } from "./visit-style.js";
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* 검사 규칙이 보지 않는 문자열 속 색을 알린다. 위반이 아니라 check 가 개수를 세는 데 쓴다.
|
|
@@ -18,8 +18,10 @@ export default {
|
|
|
18
18
|
const visitor = visitStrings(context, findUnchecked, (found, { loc }) =>
|
|
19
19
|
context.report({ loc, messageId: "unchecked", data: { color: found.value } }),
|
|
20
20
|
);
|
|
21
|
+
const { sourceCode } = context;
|
|
22
|
+
// 색을 받는 자리의 값은 다른 규칙이 검사한다.
|
|
21
23
|
const skipStyle = (handler) => (node) => {
|
|
22
|
-
if (
|
|
24
|
+
if (colorContext(node, sourceCode) === null && colorContext(node.parent ?? {}, sourceCode) === null) handler(node);
|
|
23
25
|
};
|
|
24
26
|
return { Literal: skipStyle(visitor.Literal), TemplateElement: skipStyle(visitor.TemplateElement) };
|
|
25
27
|
},
|
package/src/rules/visit-style.js
CHANGED
|
@@ -1,12 +1,21 @@
|
|
|
1
1
|
import { findColorValues, isColorProperty } from "../core/color.js";
|
|
2
2
|
|
|
3
|
+
// 색을 받는 이름. CSS 의 색 속성이거나 Color 로 끝난다. 예: backgroundColor, stroke, pointHoverBackgroundColor
|
|
4
|
+
const isColorKey = (name) => isColorProperty(name) || /color$/i.test(name);
|
|
5
|
+
const STYLE_TYPE = /CSSProperties/;
|
|
6
|
+
|
|
3
7
|
/**
|
|
4
|
-
* 노드가
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
+
* 노드가 색을 값으로 받는 자리에 있는지 본다.
|
|
9
|
+
* - style: 스타일로 쓰이는 객체의 값. JSX 의 style 속성과 CSSProperties 타입의 객체.
|
|
10
|
+
* 여기서는 var(--토큰) 이 통한다. 변수 이름(cardStyle, VARIANT_STYLES)은 근거로 삼지 않는다.
|
|
11
|
+
* 이름만 그럴 뿐 차트 설정 묶음일 수 있고, 그러면 var() 로 바꾸는 것이 안전하지 않다.
|
|
12
|
+
* - data: 그 밖에 색을 받는 이름의 속성이나 JSX 속성. 예: 차트 옵션의 backgroundColor, <Line stroke="...">.
|
|
13
|
+
* 색인 것은 분명하지만 var() 가 통하는지는 알 수 없다.
|
|
14
|
+
* @param {import("estree").Node & { parent?: any }} node 문자열이나 템플릿 리터럴
|
|
15
|
+
* @param {import("eslint").SourceCode} [sourceCode] 주면 타입 표기(CSSProperties)도 본다
|
|
16
|
+
* @returns {{ property: string, kind: "style" | "data" } | null}
|
|
8
17
|
*/
|
|
9
|
-
export function
|
|
18
|
+
export function colorContext(node, sourceCode) {
|
|
10
19
|
// color: on ? "#fff" : "#000", color: x || "#fff" 처럼 값이 고르는 식이면 그 식을 거슬러 올라간다.
|
|
11
20
|
while (
|
|
12
21
|
(node.parent?.type === "ConditionalExpression" && node.parent.test !== node) ||
|
|
@@ -14,30 +23,76 @@ export function inlineStyleProperty(node) {
|
|
|
14
23
|
) {
|
|
15
24
|
node = node.parent;
|
|
16
25
|
}
|
|
26
|
+
|
|
27
|
+
const holder = node.parent?.type === "JSXExpressionContainer" ? node.parent.parent : node.parent;
|
|
28
|
+
if (holder?.type === "JSXAttribute") {
|
|
29
|
+
const name = holder.name?.name;
|
|
30
|
+
return typeof name === "string" && isColorKey(name) ? { property: name, kind: "data" } : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
17
33
|
const property = node.parent;
|
|
18
34
|
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
35
|
const { key } = property;
|
|
24
|
-
|
|
25
|
-
|
|
36
|
+
const name = key.type === "Identifier" ? key.name : typeof key.value === "string" ? key.value : null;
|
|
37
|
+
if (name === null || property.parent?.type !== "ObjectExpression") return null;
|
|
38
|
+
|
|
39
|
+
const style = styleObjectKind(property.parent, sourceCode);
|
|
40
|
+
if (style === "jsx") return { property: name, kind: "style" };
|
|
41
|
+
if (!isColorKey(name)) return null;
|
|
42
|
+
return { property: name, kind: style ? "style" : "data" };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 객체가 스타일로 쓰이는지. JSX 의 style 속성이면 "jsx", CSSProperties 타입이면 "typed", 아니면 null. */
|
|
46
|
+
function styleObjectKind(object, sourceCode) {
|
|
47
|
+
const typed = (annotation) => Boolean(annotation && sourceCode && STYLE_TYPE.test(sourceCode.getText(annotation)));
|
|
48
|
+
for (let node = object; node; node = node.parent) {
|
|
49
|
+
const parent = node.parent;
|
|
50
|
+
if (!parent) return null;
|
|
51
|
+
if (parent.type === "TSAsExpression" || parent.type === "TSSatisfiesExpression") {
|
|
52
|
+
if (typed(parent.typeAnnotation)) return "typed";
|
|
53
|
+
} else if (parent.type === "JSXExpressionContainer") {
|
|
54
|
+
const attribute = parent.parent;
|
|
55
|
+
return attribute?.type === "JSXAttribute" && attribute.name?.name === "style" ? "jsx" : null;
|
|
56
|
+
} else if (parent.type === "Property" && parent.value === node && parent.parent?.type === "ObjectExpression") {
|
|
57
|
+
// styles = { title: { color: ... } } 처럼 스타일 객체 안에 들어 있는 객체
|
|
58
|
+
node = parent;
|
|
59
|
+
} else if (parent.type === "VariableDeclarator" && parent.init === node) {
|
|
60
|
+
const { id } = parent;
|
|
61
|
+
if (id.type !== "Identifier") return null;
|
|
62
|
+
return typed(id.typeAnnotation) ? "typed" : null;
|
|
63
|
+
} else {
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 노드가 스타일 객체의 값이면 CSS 속성 이름을, 아니면 null 을 돌려준다.
|
|
72
|
+
* 예: <div style={{ color: "#fff" }} /> 의 "#fff" → "color"
|
|
73
|
+
* @param {import("estree").Node & { parent?: any }} node
|
|
74
|
+
* @returns {string | null}
|
|
75
|
+
*/
|
|
76
|
+
export function inlineStyleProperty(node) {
|
|
77
|
+
const context = colorContext(node);
|
|
78
|
+
return context?.kind === "style" ? context.property : null;
|
|
26
79
|
}
|
|
27
80
|
|
|
28
81
|
/**
|
|
29
|
-
*
|
|
82
|
+
* 색을 값으로 받는 자리에 문자열로 적은 색마다 onFound 를 부르는 visitor 를 만든다.
|
|
30
83
|
* @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
|
|
84
|
+
* @param {(found: { text: string, value: string, property: string, kind: "style" | "data" }, where: { loc: import("estree").SourceLocation, range: [number, number] }) => void} onFound
|
|
32
85
|
*/
|
|
33
86
|
export function visitInlineStyleColors(context, onFound) {
|
|
34
87
|
const { sourceCode } = context;
|
|
35
88
|
|
|
36
|
-
function scan(node, property) {
|
|
37
|
-
|
|
89
|
+
function scan(node, { property, kind }) {
|
|
90
|
+
// 색 이름은 스타일의 색 속성에서만 색으로 본다. <Badge color="red"> 의 red 는 변형 이름일 수 있다.
|
|
91
|
+
const named = kind === "style" && isColorProperty(property);
|
|
92
|
+
for (const found of findColorValues(sourceCode.getText(node), { named })) {
|
|
38
93
|
const start = node.range[0] + found.index;
|
|
39
94
|
const end = start + found.text.length;
|
|
40
|
-
onFound({ ...found, property }, {
|
|
95
|
+
onFound({ ...found, property, kind }, {
|
|
41
96
|
loc: { start: sourceCode.getLocFromIndex(start), end: sourceCode.getLocFromIndex(end) },
|
|
42
97
|
range: [start, end],
|
|
43
98
|
});
|
|
@@ -47,13 +102,13 @@ export function visitInlineStyleColors(context, onFound) {
|
|
|
47
102
|
return {
|
|
48
103
|
Literal(node) {
|
|
49
104
|
if (typeof node.value !== "string") return;
|
|
50
|
-
const
|
|
51
|
-
if (
|
|
105
|
+
const where = colorContext(node, sourceCode);
|
|
106
|
+
if (where) scan(node, where);
|
|
52
107
|
},
|
|
53
108
|
TemplateLiteral(node) {
|
|
54
|
-
const
|
|
109
|
+
const where = colorContext(node, sourceCode);
|
|
55
110
|
// ${} 안의 코드는 다른 노드가 맡는다. 문자열 부분만 본다.
|
|
56
|
-
if (
|
|
111
|
+
if (where) for (const quasi of node.quasis) scan(quasi, where);
|
|
57
112
|
},
|
|
58
113
|
};
|
|
59
114
|
}
|