designsnitch 0.6.2 → 0.6.4
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 +90 -17
- package/README.md +90 -17
- package/package.json +1 -1
- package/skills/designsnitch-check/SKILL.md +1 -1
- package/skills/designsnitch-hooks/SKILL.md +6 -1
- package/skills/designsnitch-setup/SKILL.md +1 -1
- package/src/check.js +8 -3
- package/src/core/tokens.js +10 -0
- package/src/install.js +21 -1
- package/src/messages.js +5 -2
- package/src/rules/color-unknown.js +2 -1
- package/src/rules/color-use-token.js +2 -1
- package/src/rules/load-tokens.js +39 -13
- package/src/rules/tailwind-config.js +14 -7
package/README.ko.md
CHANGED
|
@@ -2,24 +2,56 @@
|
|
|
2
2
|
|
|
3
3
|
[English](./README.md) | 한국어
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
**모든 개발자가 좋은 디자인 시스템이 있는 환경에서 일하지는 않습니다.**
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
디자인 시스템이 아예 없는 프로젝트가 있고, 있어도 이름뿐인 프로젝트가 있습니다. 디자이너가 없는 팀, 마감에 쫓겨 화면부터 만든 서비스, 토큰 파일(`--color-primary: #3B82F6`처럼 색에 이름을 붙여 모아 둔 파일)은 있는데 아무도 따르지 않는 코드가 그렇습니다. 잘 갖춰진 디자인 시스템을 전제로 한 도구는 이런 프로젝트에서 쓸 수 없습니다.
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
AI 에이전트가 코드를 쓰면 이 문제는 더 빨리 커집니다. 에이전트는 그럴듯한 화면을 금방 만들지만, 기준이 없으면 화면마다 따로 고릅니다.
|
|
10
|
+
|
|
11
|
+
- 같은 파란색이 어떤 화면에서는 `#3B82F6`이고 다른 화면에서는 `#3B82F5`입니다.
|
|
12
|
+
- 색 하나가 백 군데에 직접 적혀 있어서, 브랜드 색을 바꾸거나 다크 모드를 넣으려면 전부 찾아야 합니다.
|
|
13
|
+
- 공용 버튼이 있는데도 화면마다 `<button>`으로 버튼을 새로 만들어서 조금씩 다릅니다.
|
|
14
|
+
|
|
15
|
+
그 결과 코드는 관리하기 어려워지고, 서비스는 일관되게 유지하기 어려워집니다. 기준이 없으니 새 코드를 무엇에 비춰 검사할지도 없습니다.
|
|
16
|
+
|
|
17
|
+
**designsnitch의 목표는 이런 프로젝트에서도 AI가 쓴 UI 코드를 관리할 수 있고 일관되게 유지하는 것입니다.** 디자이너나 Figma 파일 없이, 코드 안에서 세 가지를 합니다.
|
|
18
|
+
|
|
19
|
+
1. **기준을 세웁니다.** 코드가 이미 쓰고 있는 색을 모아서 토큰으로 정리할 수 있게 합니다. 없는 기준을 새로 만들지 않고, 지금 쓰는 것에서 출발합니다.
|
|
20
|
+
2. **기준을 지킵니다.** 새 코드가 그 기준을 따르는지 확인하고, 무엇으로 바꾸면 되는지 알려줍니다. 에이전트가 코드를 쓰는 동안 막습니다.
|
|
11
21
|
3. **정리합니다.** 이미 흩어진 코드를 기준에 맞게 되돌리는 일을 돕습니다.
|
|
12
22
|
|
|
13
|
-
무엇을 기준으로 삼을지는 개발자가 정합니다. 도구는
|
|
23
|
+
무엇을 기준으로 삼을지는 개발자가 정합니다. 도구는 대신 정하지 않습니다. 어디에 몇 번 쓰였는지, 바꾸면 화면이 달라지는지 같은 판단에 필요한 것을 가져와서 묻습니다.
|
|
24
|
+
|
|
25
|
+
## 예를 들면
|
|
26
|
+
|
|
27
|
+
프로젝트에 색 토큰 `--color-primary: #3b82f6`이 있다고 합시다. 에이전트가 버튼을 만들면서 색을 직접 씁니다.
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
<a className="rounded bg-[#3B82F6] px-4 py-2 text-white">Start</a>
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
에이전트가 파일을 고치자마자 designsnitch 훅(에이전트가 파일을 고칠 때마다 자동으로 실행되는 검사)이 에이전트에게 이렇게 돌려줍니다.
|
|
14
34
|
|
|
15
|
-
|
|
35
|
+
```text
|
|
36
|
+
designsnitch: 방금 고친 파일에 디자인 시스템 오류가 1건 있습니다.
|
|
37
|
+
|
|
38
|
+
src/app/Hero.tsx:2:32 bg-[#3B82F6]의 색은 토큰 --color-primary의 값입니다. 대신 사용: bg-primary [replace]
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
이 오류가 남아 있으면 에이전트는 작업을 끝내지 못하므로, 토큰 클래스로 바꿉니다. 같은 색이라 화면은 그대로입니다.
|
|
42
|
+
|
|
43
|
+
```tsx
|
|
44
|
+
<a className="rounded bg-primary px-4 py-2 text-white">Start</a>
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## 구성
|
|
16
48
|
|
|
17
49
|
| 부분 | 목적 |
|
|
18
50
|
| --- | --- |
|
|
19
51
|
| CLI | AI 에이전트가 쓰는 도구입니다. 쓰이는 색을 모으고, 코드를 검사하고, 위반마다 무엇을 하면 되는지 알려줍니다. |
|
|
20
|
-
| 에이전트 스킬 |
|
|
52
|
+
| 에이전트 스킬 | 에이전트가 읽고 따르는 작업 안내서(Markdown 파일)입니다. 프로젝트를 어떻게 설정하고, 언제 CLI를 실행하고, 무엇을 고치고, 무엇을 사람에게 물을지 알려줍니다. |
|
|
21
53
|
| ESLint 플러그인 | 막고 경고합니다. 같은 규칙이 에디터와 lint 단계에서 오류와 경고로 나옵니다. |
|
|
22
|
-
| 에이전트 훅 | 코드를 쓰는 동안 막습니다. 에이전트는 파일을 고칠 때마다 오류를 전달받고,
|
|
54
|
+
| 에이전트 훅 | 코드를 쓰는 동안 막습니다. 에이전트는 파일을 고칠 때마다 새로 생긴 오류를 전달받고, 바로 바꿀 수 있는 오류가 남아 있으면 작업을 끝내지 못합니다. |
|
|
23
55
|
|
|
24
56
|
**Tailwind CSS v4를 쓰는 React/Next.js 프로젝트**를 지원합니다. Tailwind v3 프로젝트도 검사하지만 후보가 적습니다([Tailwind v3](#tailwind-v3) 참고).
|
|
25
57
|
|
|
@@ -67,21 +99,47 @@ Codex, Gemini CLI, Grok Build는 새 프로젝트 훅을 승인하거나 프로
|
|
|
67
99
|
|
|
68
100
|
그 뒤로는 이렇게 됩니다.
|
|
69
101
|
|
|
70
|
-
- 에이전트는 파일을 고칠 때마다 오류를 전달받고,
|
|
102
|
+
- 에이전트는 파일을 고칠 때마다 새로 생긴 오류를 전달받고, 바로 바꿀 수 있는 오류가 남아 있으면 작업을 끝내지 못합니다. 세션 전부터 있던 오류는 세지 않습니다.
|
|
71
103
|
- 오류가 있으면 lint 단계가 실패하고, 에디터에도 표시됩니다.
|
|
72
104
|
- `npx designsnitch check`로 코드의 현재 상태를 언제든 볼 수 있습니다.
|
|
73
105
|
|
|
74
106
|
에이전트 없이 하려면 [직접 설정하기](#직접-설정하기)를 보세요.
|
|
75
107
|
|
|
76
|
-
##
|
|
108
|
+
## 내 컴퓨터에만 깔아 쓰기
|
|
77
109
|
|
|
78
|
-
|
|
110
|
+
위의 방법은 designsnitch를 프로젝트에 세팅합니다. git으로 공유되므로 팀원 모두에게 적용됩니다. 개인용 에이전트 스킬처럼 내 컴퓨터에만 둘 수도 있습니다. 프로젝트에는 아무것도 설치하지 않고 `designsnitch.config.json` 하나만 생깁니다. 팀에 도입하기 전에 내 작업에서 먼저 써 보기에 좋습니다.
|
|
79
111
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
112
|
+
1. **스킬을 사용자 폴더에 설치합니다.** 표준 설치 도구에 전역 옵션이 있습니다.
|
|
113
|
+
|
|
114
|
+
```sh
|
|
115
|
+
npx skills add icecokel/designsnitch -g
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
2. **훅을 사용자 설정에 등록합니다.** Claude Code는 `~/.claude/settings.json`입니다. 버전을 고정해 줄 프로젝트 사본이 없으므로 `@latest`로 적습니다.
|
|
119
|
+
|
|
120
|
+
```json
|
|
121
|
+
{
|
|
122
|
+
"hooks": {
|
|
123
|
+
"PostToolUse": [
|
|
124
|
+
{ "matcher": "Edit|Write|MultiEdit", "hooks": [{ "type": "command", "command": "npx -y designsnitch@latest hook" }] }
|
|
125
|
+
],
|
|
126
|
+
"Stop": [{ "hooks": [{ "type": "command", "command": "npx -y designsnitch@latest hook" }] }],
|
|
127
|
+
"SessionStart": [{ "hooks": [{ "type": "command", "command": "npx -y designsnitch@latest hook" }] }]
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Codex는 같은 내용을 `~/.codex/hooks.json`에 두고, matcher는 `apply_patch`입니다. 훅은 `designsnitch.config.json`이 없는 프로젝트에서는 아무것도 하지 않으므로, 켜 둔 채로 두어도 됩니다.
|
|
133
|
+
|
|
134
|
+
3. **프로젝트에서 에이전트에게, 아무것도 설치하지 말고 설정하라고 요청합니다.**
|
|
135
|
+
|
|
136
|
+
> 이 프로젝트에 designsnitch를 설정해 줘. 프로젝트에는 아무것도 설치하지 말고, ESLint 연결은 건너뛰어.
|
|
83
137
|
|
|
84
|
-
|
|
138
|
+
이 말이 없으면 setup 스킬이 패키지를 프로젝트에 추가하고 ESLint를 연결합니다. 그것은 팀용 세팅입니다.
|
|
139
|
+
|
|
140
|
+
포기하는 것: ESLint 플러그인과 CI는 프로젝트에 패키지가 있어야 하므로, 다른 팀원의 코드나 다른 팀원의 에이전트는 막지 못합니다. 명령은 처음 한 번 `npx`가 받아 오고 그 뒤로는 캐시에서 실행합니다(훅 한 번에 약 0.5초).
|
|
141
|
+
|
|
142
|
+
확인한 방법: `node_modules`가 없는 프로젝트에서 `check`와 `hook`을 실행했고, 빈 홈 폴더에 `-g`로 스킬을 설치해 봤고, 훅을 프로젝트 밖에 등록한 실제 Claude Code와 Codex 세션이 `bg-[#3B82F6]`을 썼다가 훅에 막혀 토큰 클래스로 고쳤습니다. 이 실행들은 실제 사용자 설정을 건드리지 않았습니다. Claude Code에는 훅을 `--settings`로 넘겼고, Codex는 같은 `hooks.json`을 둔 임시 Codex 홈으로 돌렸습니다. Codex는 새 훅을 승인한 뒤에만 실행합니다.
|
|
85
143
|
|
|
86
144
|
## 무엇을 잡는가
|
|
87
145
|
|
|
@@ -106,7 +164,7 @@ Codex, Gemini CLI, Grok Build는 새 프로젝트 훅을 승인하거나 프로
|
|
|
106
164
|
|
|
107
165
|
| 명령 | 하는 일 |
|
|
108
166
|
| --- | --- |
|
|
109
|
-
| `designsnitch install` | 스킬을 복사하고 에이전트 훅을 프로젝트에 등록합니다. `--agent claude`(기본), `codex`, `gemini`, `grok`, `all`을 받습니다. |
|
|
167
|
+
| `designsnitch install` | 스킬을 복사하고 에이전트 훅을 프로젝트에 등록합니다. Claude Code에는 `check`와 `colors` 명령도 허용해 둡니다. `--agent claude`(기본), `codex`, `gemini`, `grok`, `all`을 받습니다. |
|
|
110
168
|
| `designsnitch colors` | 코드가 쓰는 색을 모아 보여줍니다. 설정 파일이 없어도 됩니다. |
|
|
111
169
|
| `designsnitch check` | 코드를 기준에 비춰 검사하고, 위반마다 무엇을 하면 되는지 알려줍니다. |
|
|
112
170
|
| `designsnitch hook` | 에이전트의 훅에서 부릅니다. 에이전트가 방금 바꾼 파일을 검사합니다. |
|
|
@@ -256,7 +314,15 @@ Tailwind 기본 팔레트
|
|
|
256
314
|
|
|
257
315
|
v3 프로젝트는 색을 `tailwind.config.js`에 두고, CSS는 `@tailwind base`로 시작합니다. `tokens`는 평소처럼 CSS 파일을 가리키면 됩니다. 그 CSS가 `@tailwind`를 쓰면 `designsnitch.config.json` 옆의 `tailwind.config.js`(또는 `.cjs`, `.mjs`, `.ts`)를 읽습니다. `tokens`에 설정 파일을 직접 적어도 됩니다. `"palette": "tailwind"`는 v3 팔레트를 `tailwindcss/colors`에서 읽습니다.
|
|
258
316
|
|
|
259
|
-
v3는 색에 CSS 변수를 만들지 않으므로
|
|
317
|
+
v3는 색에 CSS 변수를 만들지 않으므로 가리킬 `var()`가 없습니다. 대신 색이 어디에 쓰였는지에 따라 후보가 달라집니다.
|
|
318
|
+
|
|
319
|
+
| 색이 쓰인 곳 | 후보 |
|
|
320
|
+
| --- | --- |
|
|
321
|
+
| 임의 값 색 클래스 `bg-[#3B82F6]` | 토큰 클래스 `bg-brand-500` |
|
|
322
|
+
| CSS 선언 `color: #3B82F6` | `theme("colors.brand.500")` |
|
|
323
|
+
| 인라인 스타일 | 없음. `theme()`은 CSS 밖에서 동작하지 않으므로 사람이 정합니다. |
|
|
324
|
+
|
|
325
|
+
Tailwind v3는 CSS 파일을 처리할 때 `theme("colors.brand.500")`을 토큰의 값으로 바꾸므로, 빌드된 CSS는 달라지지 않습니다. Tailwind 3.4.17 앱에서 확인했습니다. 바꾸기 전과 후에 빌드한 CSS가 바이트 단위로 같았습니다. Tailwind가 처리하는 CSS에서만 동작하며, Next.js 프로젝트에서는 PostCSS를 거치는 모든 CSS 파일이 해당합니다.
|
|
260
326
|
|
|
261
327
|
## 언어
|
|
262
328
|
|
|
@@ -469,10 +535,17 @@ CLI와 스킬은 AI 에이전트가 제대로 할 수 있는 상태를 만들어
|
|
|
469
535
|
"hooks": [{ "type": "command", "command": "npx designsnitch hook" }]
|
|
470
536
|
}
|
|
471
537
|
]
|
|
538
|
+
},
|
|
539
|
+
"permissions": {
|
|
540
|
+
"allow": ["Bash(npx designsnitch check *)", "Bash(npx designsnitch colors *)"]
|
|
472
541
|
}
|
|
473
542
|
}
|
|
474
543
|
```
|
|
475
544
|
|
|
545
|
+
`permissions`는 스킬이 쓰는 두 명령 `check`와 `colors`를 Claude Code가 매번 묻지 않고 실행하게 합니다. 둘 다 파일을 읽기만 합니다. 이미 있는 규칙은 그대로 두고, `Bash(npx designsnitch *)`처럼 더 넓은 규칙이 있으면 아무것도 더하지 않습니다.
|
|
546
|
+
|
|
547
|
+
Claude Code는 프로젝트의 `.claude/settings.json`에 있는 허용 규칙을, 그 프로젝트의 신뢰 확인을 수락한 뒤에만 씁니다. 신뢰 확인은 터미널에서 프로젝트를 처음 열 때 나옵니다. 그렇게 열어 본 적이 없는 프로젝트에서는, 예를 들어 새로 받은 저장소에서 `claude -p`로 실행하면, 이 규칙을 버리고 다시 승인을 요청합니다. 그럴 때는 `--allowedTools "Bash(npx designsnitch check *)"`를 넘기세요. Claude Code 2.1.329에서 확인했습니다. 규칙이 있을 때 신뢰한 폴더에서는 묻지 않고 실행했고, 신뢰하지 않은 폴더에서는 거부됐습니다.
|
|
548
|
+
|
|
476
549
|
`designsnitch hook`은 에이전트가 방금 바꾼 파일만 검사하고, 그 변경으로 새로 생긴 오류만 막습니다.
|
|
477
550
|
|
|
478
551
|
- 파일마다 git `HEAD` 버전과 비교합니다. 같은 규칙, 같은 코드의 오류가 `HEAD`보다 많아졌으면 새 오류입니다. 원래 있던 오류는 줄이 밀려도 막지 않습니다. `HEAD`에 아직 없는 파일은 모든 오류가 새것입니다.
|
package/README.md
CHANGED
|
@@ -2,24 +2,56 @@
|
|
|
2
2
|
|
|
3
3
|
English | [Korean](./README.ko.md)
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
**Not every developer gets to work with a good design system.**
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Some projects have no design system at all, and some have one in name only: a team with no designer, a product whose screens were built against a deadline, a token file (a file that gives colors names, such as `--color-primary: #3B82F6`) that nobody follows. Tools that assume a well-kept design system have nothing to work with there.
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
9
|
+
AI agents make this grow faster. An agent produces a plausible screen in minutes, and with no standard to follow, every screen makes its own choices.
|
|
10
|
+
|
|
11
|
+
- The same blue is `#3B82F6` on one screen and `#3B82F5` on another.
|
|
12
|
+
- A color is written by hand in a hundred places, so changing the brand color or adding dark mode means finding every one of them.
|
|
13
|
+
- A shared button exists, and each screen still builds its own from `<button>`, each a little different.
|
|
14
|
+
|
|
15
|
+
The result is a codebase that is hard to manage and a product that is hard to keep consistent. And with no standard, there is nothing to check new code against.
|
|
16
|
+
|
|
17
|
+
**The goal of designsnitch is to keep AI-written UI code manageable and consistent in exactly these projects.** It works inside the code, with no designer or Figma file required, and does three things.
|
|
18
|
+
|
|
19
|
+
1. **Establish a standard.** It collects the colors the code already uses so you can turn them into tokens. It starts from what is there instead of inventing a standard.
|
|
20
|
+
2. **Keep to it.** It checks new code against that standard and tells you what to use instead. It blocks while the agent is writing.
|
|
11
21
|
3. **Clean up.** It helps bring code that has already drifted back to the standard.
|
|
12
22
|
|
|
13
|
-
Deciding what the standard is stays with the developer. The tool
|
|
23
|
+
Deciding what the standard is stays with the developer. The tool does not decide for you. It brings what the decision needs, such as how often a color is used and whether a change would alter the screen, and asks.
|
|
24
|
+
|
|
25
|
+
## An example
|
|
26
|
+
|
|
27
|
+
Say the project has a color token, `--color-primary: #3b82f6`. An agent building a button writes the color by hand.
|
|
28
|
+
|
|
29
|
+
```tsx
|
|
30
|
+
<a className="rounded bg-[#3B82F6] px-4 py-2 text-white">Start</a>
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Right after the agent edits the file, the designsnitch hook (a check that runs automatically every time the agent edits a file) sends it this.
|
|
14
34
|
|
|
15
|
-
|
|
35
|
+
```text
|
|
36
|
+
designsnitch: 1 design system error in the files you just changed.
|
|
37
|
+
|
|
38
|
+
src/app/Hero.tsx:2:32 bg-[#3B82F6] has the same color as --color-primary. Use instead: bg-primary [replace]
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The agent cannot finish while this error remains, so it switches to the token class. The color is the same, so the screen does not change.
|
|
42
|
+
|
|
43
|
+
```tsx
|
|
44
|
+
<a className="rounded bg-primary px-4 py-2 text-white">Start</a>
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## What is in it
|
|
16
48
|
|
|
17
49
|
| Part | What it is for |
|
|
18
50
|
| --- | --- |
|
|
19
51
|
| CLI | A tool for the AI agent. It collects the colors in use, checks code, and says what to do with each violation. |
|
|
20
|
-
| Agent skills |
|
|
52
|
+
| Agent skills | Instructions the agent reads and follows (Markdown files). They tell it how to set the project up, when to run the CLI, what to fix, and what to ask a person about. |
|
|
21
53
|
| ESLint plugin | Blocks and warns. The same rules show up as errors and warnings in the editor and in the lint step. |
|
|
22
|
-
| Agent hook | Blocks while the code is being written. The agent is told about errors after each edit and cannot finish while errors it can
|
|
54
|
+
| Agent hook | Blocks while the code is being written. The agent is told about new errors after each edit and cannot finish while errors it can replace right away remain. |
|
|
23
55
|
|
|
24
56
|
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
57
|
|
|
@@ -67,21 +99,47 @@ The agent follows the `designsnitch-setup` skill and does the rest.
|
|
|
67
99
|
|
|
68
100
|
From then on:
|
|
69
101
|
|
|
70
|
-
- The agent is told about errors right after it edits a file, and cannot finish while errors it can
|
|
102
|
+
- The agent is told about new errors right after it edits a file, and cannot finish while errors it can replace right away remain. Errors that were there before the session do not count.
|
|
71
103
|
- Errors fail the lint step, and show up in the editor.
|
|
72
104
|
- `npx designsnitch check` reports where the code stands at any time.
|
|
73
105
|
|
|
74
106
|
To do any of this without an agent, see [Setting up by hand](#setting-up-by-hand).
|
|
75
107
|
|
|
76
|
-
##
|
|
108
|
+
## Using it on your own machine only
|
|
77
109
|
|
|
78
|
-
|
|
110
|
+
The steps above set designsnitch up in the project, so everyone on the team gets it through git. You can also keep it on your own machine, the way a personal agent skill works: nothing is installed into the project, and only `designsnitch.config.json` is added to it. This is a good way to try it on your own work first.
|
|
79
111
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
112
|
+
1. **Install the skills for your user.** The standard installer has a global option.
|
|
113
|
+
|
|
114
|
+
```sh
|
|
115
|
+
npx skills add icecokel/designsnitch -g
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
2. **Register the hook in your user settings.** For Claude Code that is `~/.claude/settings.json`. Use `@latest` here, because there is no project copy to pin the version.
|
|
119
|
+
|
|
120
|
+
```json
|
|
121
|
+
{
|
|
122
|
+
"hooks": {
|
|
123
|
+
"PostToolUse": [
|
|
124
|
+
{ "matcher": "Edit|Write|MultiEdit", "hooks": [{ "type": "command", "command": "npx -y designsnitch@latest hook" }] }
|
|
125
|
+
],
|
|
126
|
+
"Stop": [{ "hooks": [{ "type": "command", "command": "npx -y designsnitch@latest hook" }] }],
|
|
127
|
+
"SessionStart": [{ "hooks": [{ "type": "command", "command": "npx -y designsnitch@latest hook" }] }]
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Codex has the same file at `~/.codex/hooks.json`, with `apply_patch` as the matcher. The hook does nothing in a project that has no `designsnitch.config.json`, so it is safe to leave on everywhere.
|
|
133
|
+
|
|
134
|
+
3. **In a project, ask the agent to set it up without installing anything.**
|
|
135
|
+
|
|
136
|
+
> Set up designsnitch in this project. Do not install anything into the project, and skip ESLint.
|
|
83
137
|
|
|
84
|
-
|
|
138
|
+
Without that sentence the setup skill adds the package to the project and wires ESLint, which is the team setup.
|
|
139
|
+
|
|
140
|
+
What you give up: the ESLint plugin and CI need the package in the project, so nothing stops a teammate's code or a teammate's agent. Each command is fetched by `npx` the first time and runs from its cache after that (about half a second per hook call).
|
|
141
|
+
|
|
142
|
+
How this was checked: `check` and `hook` were run in a project with no `node_modules`, the skills were installed with `-g` into a clean home directory, and real Claude Code and Codex sessions with the hook registered outside the project wrote `bg-[#3B82F6]`, were stopped by the hook, and switched to the token class. Those runs did not touch the real user settings: Claude Code got the hook through `--settings`, and Codex ran with a temporary Codex home that had the same `hooks.json`. Codex runs a new hook only after you approve it.
|
|
85
143
|
|
|
86
144
|
## What it catches
|
|
87
145
|
|
|
@@ -106,7 +164,7 @@ Every error comes with what to use instead: a class or component in JS and TS fi
|
|
|
106
164
|
|
|
107
165
|
| Command | What it does |
|
|
108
166
|
| --- | --- |
|
|
109
|
-
| `designsnitch install` | Copies the skills and registers the agent hook in the project. `--agent claude` (default), `codex`, `gemini`, `grok` or `all`. |
|
|
167
|
+
| `designsnitch install` | Copies the skills and registers the agent hook in the project. For Claude Code it also allows the `check` and `colors` commands. `--agent claude` (default), `codex`, `gemini`, `grok` or `all`. |
|
|
110
168
|
| `designsnitch colors` | Lists the colors the code uses. Works without a config file. |
|
|
111
169
|
| `designsnitch check` | Checks code against the standard and says what to do with each violation. |
|
|
112
170
|
| `designsnitch hook` | Called from the agent's hook. Checks the files the agent just changed. |
|
|
@@ -255,7 +313,15 @@ Tokens are also read from where Tailwind itself reads them.
|
|
|
255
313
|
|
|
256
314
|
A v3 project keeps its colors in `tailwind.config.js`, and its CSS starts with `@tailwind base`. Point `tokens` at the CSS file as usual: when it uses `@tailwind`, the `tailwind.config.js` (or `.cjs`, `.mjs`, `.ts`) next to `designsnitch.config.json` is read. You can also point `tokens` straight at the config file. `"palette": "tailwind"` reads the v3 palette from `tailwindcss/colors`.
|
|
257
315
|
|
|
258
|
-
v3 makes no CSS variables for its colors, so
|
|
316
|
+
v3 makes no CSS variables for its colors, so there is no `var()` to point at. What you get instead depends on where the color is written.
|
|
317
|
+
|
|
318
|
+
| Where the color is | Candidate |
|
|
319
|
+
| --- | --- |
|
|
320
|
+
| An arbitrary color class, `bg-[#3B82F6]` | The token class, `bg-brand-500` |
|
|
321
|
+
| A CSS declaration, `color: #3B82F6` | `theme("colors.brand.500")` |
|
|
322
|
+
| An inline style | None. `theme()` does not work outside CSS, so a person decides. |
|
|
323
|
+
|
|
324
|
+
Tailwind v3 turns `theme("colors.brand.500")` into the token's value when it processes the CSS file, so the compiled CSS does not change. This was checked on a Tailwind 3.4.17 app: the CSS built before and after the replacement was identical, byte for byte. It works only in CSS that Tailwind processes, which in a Next.js project is every CSS file that goes through PostCSS.
|
|
259
325
|
|
|
260
326
|
## Language
|
|
261
327
|
|
|
@@ -468,10 +534,17 @@ A skill is advice that an agent may not follow. A hook is run by the agent's run
|
|
|
468
534
|
"hooks": [{ "type": "command", "command": "npx designsnitch hook" }]
|
|
469
535
|
}
|
|
470
536
|
]
|
|
537
|
+
},
|
|
538
|
+
"permissions": {
|
|
539
|
+
"allow": ["Bash(npx designsnitch check *)", "Bash(npx designsnitch colors *)"]
|
|
471
540
|
}
|
|
472
541
|
}
|
|
473
542
|
```
|
|
474
543
|
|
|
544
|
+
The `permissions` part lets Claude Code run the two commands the skills use, `check` and `colors`, without asking each time. Both only read files. Rules that are already there are kept, and nothing is added when a wider rule such as `Bash(npx designsnitch *)` covers them.
|
|
545
|
+
|
|
546
|
+
Claude Code uses allow rules from a project's `.claude/settings.json` only after you have accepted its trust prompt for that project, which it shows the first time you open the project in the terminal. In a project that was never opened that way, for example in `claude -p` on a fresh checkout, it drops them and the agent is asked again. There, pass `--allowedTools "Bash(npx designsnitch check *)"`. Checked with Claude Code 2.1.329: with the rule, the command ran without a prompt in a trusted folder and was denied in an untrusted one.
|
|
547
|
+
|
|
475
548
|
`designsnitch hook` checks only the files the agent just changed, and blocks only errors the change added.
|
|
476
549
|
|
|
477
550
|
- 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.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "designsnitch",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.4",
|
|
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",
|
|
@@ -69,7 +69,7 @@ The exit code is 0 (no errors), 1 (errors found), or 2 (could not run). On 2, re
|
|
|
69
69
|
|
|
70
70
|
- `next` lists what to do, in order. `next` and `message` are sentences, in English or in Korean depending on the project's `lang` setting. The fields below carry the same information, so you never need to parse them.
|
|
71
71
|
- `action` says how to handle each violation. Section 3 covers each value.
|
|
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.
|
|
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. In a Tailwind v3 project, which has no CSS variables for its colors, the candidate in a `.css` file is `theme("colors.token")`: Tailwind turns it into the same value when it builds the CSS.
|
|
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
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.
|
|
@@ -26,7 +26,7 @@ A skill is advice: an agent may or may not follow it. A hook is run by the agent
|
|
|
26
26
|
|
|
27
27
|
## 1. Register the hook in Claude Code
|
|
28
28
|
|
|
29
|
-
Run the installer. It adds the hook to `.claude/settings.json`, keeps any hooks and settings that are already there, and can be run again safely.
|
|
29
|
+
Run the installer. It adds the hook to `.claude/settings.json`, allows the two read-only commands the skills run, keeps any hooks and settings that are already there, and can be run again safely.
|
|
30
30
|
|
|
31
31
|
```sh
|
|
32
32
|
npx designsnitch install
|
|
@@ -55,10 +55,15 @@ If you need to do it by hand, this is what it adds to `.claude/settings.json`.
|
|
|
55
55
|
"hooks": [{ "type": "command", "command": "npx designsnitch hook" }]
|
|
56
56
|
}
|
|
57
57
|
]
|
|
58
|
+
},
|
|
59
|
+
"permissions": {
|
|
60
|
+
"allow": ["Bash(npx designsnitch check *)", "Bash(npx designsnitch colors *)"]
|
|
58
61
|
}
|
|
59
62
|
}
|
|
60
63
|
```
|
|
61
64
|
|
|
65
|
+
The `permissions` part lets Claude Code run `npx designsnitch check` and `npx designsnitch colors` without asking each time. Both only read files. Claude Code uses these rules only in a project whose trust prompt the user has accepted. If the check command still waits for approval, the project was never opened in the terminal and trusted: tell the user that, do not work around it.
|
|
66
|
+
|
|
62
67
|
`.claude/settings.json` is shared with the team through git, so the hook applies to everyone who uses Claude Code in this project. If the user wants the hook only for themselves, do not run the installer: add the entries above to `.claude/settings.local.json` by hand.
|
|
63
68
|
|
|
64
69
|
## 2. Register the hook in Codex
|
|
@@ -14,7 +14,7 @@ Create the file when it is missing. This does not need the user's approval: it o
|
|
|
14
14
|
designsnitch supports React or Next.js projects that use Tailwind CSS. Look at `package.json` and the global CSS file.
|
|
15
15
|
|
|
16
16
|
- Tailwind v4 has `tailwindcss` version 4 in `package.json` and `@import "tailwindcss"` in a CSS file. This is the full case.
|
|
17
|
-
- Tailwind v3 has `tailwindcss` version 3, `@tailwind base` in a CSS file and its colors in `tailwind.config.js`. It is checked too: point `tokens` at the CSS file, and the `tailwind.config.js` in the same directory as `designsnitch.config.json` is read. Tell the user what is different: v3 has no CSS variables for its colors, so
|
|
17
|
+
- Tailwind v3 has `tailwindcss` version 3, `@tailwind base` in a CSS file and its colors in `tailwind.config.js`. It is checked too: point `tokens` at the CSS file, and the `tailwind.config.js` in the same directory as `designsnitch.config.json` is read. Tell the user what is different: v3 has no CSS variables for its colors, so a color written by hand in a CSS declaration gets `theme("colors.brand.500")` as its candidate instead of `var()`, one written in an inline style is reported without a candidate, and the `designsnitch-palette` skill, which writes `@theme` tokens, does not apply. New colors go into `tailwind.config.js`, with the user's approval.
|
|
18
18
|
- If the project does not use Tailwind or React at all, stop and tell the user that designsnitch does not support it yet.
|
|
19
19
|
|
|
20
20
|
Then make sure the package is a dependency of the project. The commands below and the agent hook both run `npx designsnitch`, which should use the project's own copy.
|
package/src/check.js
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
lookupColor,
|
|
10
10
|
recommendColorCandidate,
|
|
11
11
|
selectColorTokens,
|
|
12
|
+
themeValue,
|
|
12
13
|
tokenClass,
|
|
13
14
|
tokenValue,
|
|
14
15
|
utilityColorPrefixes,
|
|
@@ -185,10 +186,14 @@ function checkCss(file, source, tokens, m, options) {
|
|
|
185
186
|
const found = text ?? value;
|
|
186
187
|
const prefixes = utility ? utilityColorPrefixes(utility) : cssColorPrefixes(prop);
|
|
187
188
|
const { names: known, opacity } = lookupColor(tokens.colors, value);
|
|
188
|
-
|
|
189
|
-
|
|
189
|
+
// CSS 변수가 없는 토큰도 Tailwind v3 의 CSS 에서는 theme() 으로 같은 값을 쓸 수 있다.
|
|
190
|
+
const viaTheme = (name) => tokens.classOnly.has(name) && tokens.themePaths.has(name);
|
|
191
|
+
const toCandidate = (name) => {
|
|
192
|
+
if (utility) return tokenClass(utility, name, opacity);
|
|
193
|
+
return viaTheme(name) ? themeValue(tokens.themePaths.get(name), opacity) : tokenValue(name, tokens.prefix, opacity);
|
|
194
|
+
};
|
|
190
195
|
// 클래스로만 쓸 수 있는 토큰은 선언의 값을 대신할 수 없다. 그래도 직접 쓴 색이라는 것은 알린다.
|
|
191
|
-
const usable = utility ? known : known.filter((name) => !tokens.classOnly.has(name));
|
|
196
|
+
const usable = utility ? known : known.filter((name) => !tokens.classOnly.has(name) || viaTheme(name));
|
|
192
197
|
if (known.length > 0 && usable.length === 0) {
|
|
193
198
|
return {
|
|
194
199
|
file,
|
package/src/core/tokens.js
CHANGED
|
@@ -135,6 +135,16 @@ export function tokenValue(name, prefix, opacity) {
|
|
|
135
135
|
return opacity === null ? reference : `color-mix(in srgb, ${reference} ${opacity}%, transparent)`;
|
|
136
136
|
}
|
|
137
137
|
|
|
138
|
+
/**
|
|
139
|
+
* Tailwind v3 의 CSS 에서 설정의 색을 가리키는 표기. 예: theme("colors.brand.500"), theme("colors.brand.500 / 50%")
|
|
140
|
+
* @param {string[]} path 설정의 키 경로
|
|
141
|
+
* @param {number | null} opacity
|
|
142
|
+
*/
|
|
143
|
+
export function themeValue(path, opacity) {
|
|
144
|
+
const keys = path.map((key) => (/^[\w-]+$/.test(key) ? `.${key}` : `[${key}]`)).join("");
|
|
145
|
+
return `theme("colors${keys}${opacity === null ? "" : ` / ${opacity}%`}")`;
|
|
146
|
+
}
|
|
147
|
+
|
|
138
148
|
/** 토큰을 클래스로 쓰는 표기. 불투명도는 Tailwind 의 /50 꼴로 붙인다. 예: bg-brand/50 */
|
|
139
149
|
export function tokenClass(utility, name, opacity) {
|
|
140
150
|
const className = `${utility}-${name.replace(/^--color-/, "")}`;
|
package/src/install.js
CHANGED
|
@@ -24,6 +24,8 @@ const AGENTS = {
|
|
|
24
24
|
editTools: "Edit|Write|MultiEdit",
|
|
25
25
|
hook: { type: "command", command: HOOK_COMMAND },
|
|
26
26
|
approval: null,
|
|
27
|
+
// 검사와 색 수집은 읽기만 한다. 허용해 두지 않으면 에이전트가 스킬대로 실행하려다 승인을 기다리며 멈춘다.
|
|
28
|
+
allow: ["Bash(npx designsnitch check *)", "Bash(npx designsnitch colors *)"],
|
|
27
29
|
},
|
|
28
30
|
codex: {
|
|
29
31
|
skillsDir: ".agents/skills",
|
|
@@ -98,12 +100,14 @@ export function install({ cwd, lang, agent = "claude" }) {
|
|
|
98
100
|
|
|
99
101
|
const file = path.join(cwd, target.hooksFile);
|
|
100
102
|
const added = addHooks(settings.get(target), target);
|
|
101
|
-
|
|
103
|
+
const allowed = target.allow ? addPermissions(settings.get(target), target.allow) : false;
|
|
104
|
+
if (added || allowed) {
|
|
102
105
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
103
106
|
fs.writeFileSync(file, `${JSON.stringify(settings.get(target), null, 2)}\n`);
|
|
104
107
|
}
|
|
105
108
|
|
|
106
109
|
lines.push(added ? m.hookRegistered({ file: target.hooksFile }) : m.hookAlready({ file: target.hooksFile }));
|
|
110
|
+
if (allowed) lines.push(m.commandsAllowed({ file: target.hooksFile }));
|
|
107
111
|
if (added && target.approval) steps.push(m[target.approval]());
|
|
108
112
|
}
|
|
109
113
|
|
|
@@ -126,6 +130,22 @@ function readJson(file, m) {
|
|
|
126
130
|
throw new Error(m.settingsUnreadable({ file }));
|
|
127
131
|
}
|
|
128
132
|
|
|
133
|
+
/**
|
|
134
|
+
* 읽기만 하는 명령을 권한 허용 목록에 더한다. 이미 있거나 더 넓게 허용돼 있으면 그대로 둔다. 더했으면 true.
|
|
135
|
+
* @param {Record<string, any>} settings
|
|
136
|
+
* @param {string[]} rules
|
|
137
|
+
*/
|
|
138
|
+
function addPermissions(settings, rules) {
|
|
139
|
+
const existing = settings.permissions?.allow;
|
|
140
|
+
const current = Array.isArray(existing) ? existing : [];
|
|
141
|
+
// 예: Bash(npx designsnitch *), Bash(npx designsnitch:*), Bash(npx *)
|
|
142
|
+
const covered = current.some((rule) => /^Bash\(npx(?: designsnitch)?\s*[:\s]?\*\)$/.test(rule));
|
|
143
|
+
const missing = covered ? [] : rules.filter((rule) => !current.includes(rule));
|
|
144
|
+
if (missing.length === 0) return false;
|
|
145
|
+
settings.permissions = { ...settings.permissions, allow: [...current, ...missing] };
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
|
|
129
149
|
/** 훅이 없는 이벤트에만 더한다. 하나라도 더했으면 true. */
|
|
130
150
|
function addHooks(settings, target) {
|
|
131
151
|
const entries = {
|
package/src/messages.js
CHANGED
|
@@ -38,7 +38,7 @@ const en = {
|
|
|
38
38
|
useTokenData: ({ found, tokens, candidates }) =>
|
|
39
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}`,
|
|
40
40
|
useTokenClassOnly: ({ found, tokens }) =>
|
|
41
|
-
`${found} has the same color as ${tokens}, but
|
|
41
|
+
`${found} has the same color as ${tokens}, but Tailwind makes no CSS variable for that token, so there is no var() to use here.`,
|
|
42
42
|
unknownColor: ({ found }) => `The color of ${found} is not in the tokens.`,
|
|
43
43
|
unknownCssColor: ({ value }) => `The color ${value} is not in the tokens.`,
|
|
44
44
|
useComponent: ({ tag, component, path }) =>
|
|
@@ -152,6 +152,8 @@ const en = {
|
|
|
152
152
|
skillsCopied: ({ n, dir }) => `Copied ${count(n, "skill")} to ${dir}.`,
|
|
153
153
|
hookRegistered: ({ file }) => `Registered the hook in ${file}.`,
|
|
154
154
|
hookAlready: ({ file }) => `The hook is already registered in ${file}.`,
|
|
155
|
+
commandsAllowed: ({ file }) =>
|
|
156
|
+
`Allowed the check commands (npx designsnitch check, colors) in ${file}, so the agent can run them without asking.`,
|
|
155
157
|
codexTrust: () =>
|
|
156
158
|
"Codex runs project hooks only in a trusted project, and only hooks you have approved. Open Codex in this project and approve the project and the hook when it asks.",
|
|
157
159
|
geminiTrust: () =>
|
|
@@ -193,7 +195,7 @@ const ko = {
|
|
|
193
195
|
useTokenData: ({ found, tokens, candidates }) =>
|
|
194
196
|
`${found}의 색은 토큰 ${tokens}의 값입니다. 스타일이 아닌 자리라서, 이 값을 쓰는 곳에서 var()가 통하는지 확인해야 합니다. 후보: ${candidates}`,
|
|
195
197
|
useTokenClassOnly: ({ found, tokens }) =>
|
|
196
|
-
`${found}의 색은 토큰 ${tokens}의 값이지만, 이
|
|
198
|
+
`${found}의 색은 토큰 ${tokens}의 값이지만, Tailwind가 이 토큰의 CSS 변수를 만들지 않아서 여기에 쓸 var()가 없습니다.`,
|
|
197
199
|
unknownColor: ({ found }) => `${found}의 색은 토큰에 없습니다.`,
|
|
198
200
|
unknownCssColor: ({ value }) => `${value}의 색은 토큰에 없습니다.`,
|
|
199
201
|
useComponent: ({ tag, component, path }) =>
|
|
@@ -300,6 +302,7 @@ const ko = {
|
|
|
300
302
|
skillsCopied: ({ n, dir }) => `스킬 ${n}개를 ${dir} 에 복사했습니다.`,
|
|
301
303
|
hookRegistered: ({ file }) => `훅을 ${file} 에 등록했습니다.`,
|
|
302
304
|
hookAlready: ({ file }) => `훅은 이미 ${file} 에 등록되어 있습니다.`,
|
|
305
|
+
commandsAllowed: ({ file }) => `검사 명령(npx designsnitch check, colors)을 ${file} 의 허용 목록에 넣었습니다.`,
|
|
303
306
|
codexTrust: () =>
|
|
304
307
|
"Codex는 신뢰한 프로젝트에서, 사용자가 승인한 훅만 실행합니다. 이 프로젝트에서 Codex를 열고 프로젝트 신뢰와 훅 승인을 요청받으면 승인하세요.",
|
|
305
308
|
geminiTrust: () =>
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { findArbitraryColors } from "../core/classes.js";
|
|
2
2
|
import { lookupColor } from "../core/tokens.js";
|
|
3
|
-
import { loadTokens } from "./load-tokens.js";
|
|
3
|
+
import { definesTokens, loadTokens } from "./load-tokens.js";
|
|
4
4
|
import { ruleMessages, TEXT } from "./suggest.js";
|
|
5
5
|
import { visitStrings } from "./visit-strings.js";
|
|
6
6
|
import { mergeVisitors, visitInlineStyleColors } from "./visit-style.js";
|
|
@@ -21,6 +21,7 @@ export default {
|
|
|
21
21
|
// 토큰 설정 문제는 color-use-token 에서만 보고한다.
|
|
22
22
|
return {};
|
|
23
23
|
}
|
|
24
|
+
if (definesTokens(tokens, context.filename)) return {};
|
|
24
25
|
const m = ruleMessages(context);
|
|
25
26
|
const { colors } = tokens;
|
|
26
27
|
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
tokenValue,
|
|
8
8
|
utilityColorPrefixes,
|
|
9
9
|
} from "../core/tokens.js";
|
|
10
|
-
import { loadTokens } from "./load-tokens.js";
|
|
10
|
+
import { definesTokens, loadTokens } from "./load-tokens.js";
|
|
11
11
|
import { ruleMessages, suggestClasses, TEXT } from "./suggest.js";
|
|
12
12
|
import { visitStrings } from "./visit-strings.js";
|
|
13
13
|
import { mergeVisitors, visitInlineStyleColors } from "./visit-style.js";
|
|
@@ -40,6 +40,7 @@ export default {
|
|
|
40
40
|
},
|
|
41
41
|
};
|
|
42
42
|
}
|
|
43
|
+
if (definesTokens(tokens, context.filename)) return {};
|
|
43
44
|
const m = ruleMessages(context);
|
|
44
45
|
const { colors, themed, prefer, classOnly } = tokens;
|
|
45
46
|
|
package/src/rules/load-tokens.js
CHANGED
|
@@ -17,13 +17,29 @@ import { flattenColors, loadConfigColors } from "./tailwind-config.js";
|
|
|
17
17
|
* @property {string | null} prefix Tailwind 접두어. @import "tailwindcss" prefix(tw) 의 tw
|
|
18
18
|
* @property {Set<string>} classOnly 클래스로만 쓸 수 있는 토큰 이름들. JavaScript 설정의 색에는 CSS 변수가 없다
|
|
19
19
|
* @property {string[]} problems 토큰을 다 읽지 못하게 만든 문제. 예: 불러오지 못한 JavaScript 설정
|
|
20
|
+
* @property {Map<string, string[]>} themePaths Tailwind v3 에서 CSS 변수가 없는 토큰의 설정 키 경로.
|
|
21
|
+
* v3 의 CSS 에서는 theme("colors.brand.500") 으로 그 값을 쓸 수 있다. v3 가 아니면 비어 있다
|
|
20
22
|
*/
|
|
21
23
|
|
|
22
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* 이 파일이 토큰을 정의하는 JavaScript 설정인지. 그 안의 색은 토큰의 값이지 직접 쓴 색이 아니다.
|
|
26
|
+
* @param {Tokens} tokens
|
|
27
|
+
* @param {string} filename 절대 경로
|
|
28
|
+
*/
|
|
29
|
+
export function definesTokens(tokens, filename) {
|
|
30
|
+
if (tokens.files.has(filename)) return true;
|
|
31
|
+
try {
|
|
32
|
+
return tokens.files.has(fs.realpathSync(filename));
|
|
33
|
+
} catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** @typedef {ReturnType<typeof parseColorTokenData> & Pick<Tokens, "files" | "prefix" | "classOnly" | "problems" | "themePaths"> & { tailwindV3: boolean }} ProjectTokens */
|
|
23
39
|
|
|
24
40
|
/** @type {Map<string, { deps: [string, number][], tokens: ProjectTokens }>} */
|
|
25
41
|
const cache = new Map();
|
|
26
|
-
/** @type {Map<string, { mtimeMs: number, result: { palette: Map<string, string>, classOnly: boolean } }>} */
|
|
42
|
+
/** @type {Map<string, { mtimeMs: number, result: { palette: Map<string, string>, classOnly: boolean, paths: Map<string, string[]> } }>} */
|
|
27
43
|
const paletteCache = new Map();
|
|
28
44
|
|
|
29
45
|
/**
|
|
@@ -42,8 +58,8 @@ export function loadTokens(settings, cwd) {
|
|
|
42
58
|
const root = path.resolve(cwd, settings?.designsnitch?.root ?? ".");
|
|
43
59
|
const file = path.resolve(root, tokensPath);
|
|
44
60
|
const project = readProjectTokens(file, root, exclude, m);
|
|
45
|
-
const { files, prefix, classOnly, problems } = project;
|
|
46
|
-
const shared = { prefer, files, prefix, classOnly, problems };
|
|
61
|
+
const { files, prefix, classOnly, problems, themePaths } = project;
|
|
62
|
+
const shared = { prefer, files, prefix, classOnly, problems, themePaths };
|
|
47
63
|
if (settings?.designsnitch?.palette !== "tailwind") {
|
|
48
64
|
return { colors: project.colors, themed: project.themed, paletteNames: new Set(), ...shared };
|
|
49
65
|
}
|
|
@@ -118,13 +134,16 @@ function readProjectTokens(file, root, exclude, m) {
|
|
|
118
134
|
|
|
119
135
|
// import 된 파일의 선언이 먼저 오도록 뒤집어 합친다. 순서는 결과에 영향을 주지 않지만 읽기 쉽다.
|
|
120
136
|
const parsed = parseColorTokenData(sources.map(([, css]) => css).reverse().join("\n"), exclude);
|
|
121
|
-
const { classOnly, problems } = addConfigColors(parsed, configFiles, exclude, m);
|
|
137
|
+
const { classOnly, problems, paths } = addConfigColors(parsed, configFiles, exclude, m);
|
|
138
|
+
// theme() 은 Tailwind v3 의 CSS 에서 쓰는 방법이다. v4 에서는 권하지 않는 함수라 후보로 내지 않는다.
|
|
139
|
+
const tailwindV3 = usesV3Directives || isConfig;
|
|
140
|
+
const themePaths = tailwindV3 ? paths : new Map();
|
|
122
141
|
// 기준으로 적은 설정을 못 읽으면 판정할 것이 없다. @config 로 딸려 온 설정이면 알리기만 하고 계속한다.
|
|
123
142
|
if (isConfig && problems.length > 0) throw new Error(problems[0]);
|
|
124
143
|
// 링크된 경로로 들어와도 같은 파일로 알아보도록 실제 경로로 적어 둔다.
|
|
125
144
|
const deps = [...sources.map(([cssFile]) => cssFile), ...configFiles];
|
|
126
145
|
const files = new Set(deps.filter((dep) => fs.existsSync(dep)).map((dep) => fs.realpathSync(dep)));
|
|
127
|
-
const tokens = { ...parsed, files, prefix, classOnly, problems };
|
|
146
|
+
const tokens = { ...parsed, files, prefix, classOnly, problems, themePaths, tailwindV3 };
|
|
128
147
|
cache.set(key, { deps: deps.map((dep) => [dep, mtimeOf(dep)]), tokens });
|
|
129
148
|
return tokens;
|
|
130
149
|
}
|
|
@@ -139,6 +158,7 @@ const V3_CONFIG_NAMES = ["tailwind.config.js", "tailwind.config.cjs", "tailwind.
|
|
|
139
158
|
function addConfigColors(parsed, configFiles, exclude, m) {
|
|
140
159
|
const classOnly = new Set();
|
|
141
160
|
const problems = [];
|
|
161
|
+
const paths = new Map();
|
|
142
162
|
const excluded = (name) => exclude.some((p) => (p.endsWith("*") ? name.startsWith(p.slice(0, -1)) : name === p));
|
|
143
163
|
for (const file of configFiles) {
|
|
144
164
|
let config;
|
|
@@ -153,10 +173,11 @@ function addConfigColors(parsed, configFiles, exclude, m) {
|
|
|
153
173
|
if (parsed.names.has(name) || excluded(name)) continue;
|
|
154
174
|
parsed.names.add(name);
|
|
155
175
|
classOnly.add(name);
|
|
176
|
+
paths.set(name, config.paths.get(name));
|
|
156
177
|
parsed.colors.set(color, [...(parsed.colors.get(color) ?? []), name]);
|
|
157
178
|
}
|
|
158
179
|
}
|
|
159
|
-
return { classOnly, problems };
|
|
180
|
+
return { classOnly, problems, paths };
|
|
160
181
|
}
|
|
161
182
|
|
|
162
183
|
function mtimeOf(file) {
|
|
@@ -202,13 +223,14 @@ function readTailwindPalette(tokensFile, m) {
|
|
|
202
223
|
const cached = paletteCache.get(file);
|
|
203
224
|
if (cached?.mtimeMs === mtimeMs) return cached.result;
|
|
204
225
|
let palette;
|
|
226
|
+
const paths = new Map();
|
|
205
227
|
if (classOnly) {
|
|
206
228
|
const module = require(file);
|
|
207
|
-
palette = flattenColors(module.default ?? module);
|
|
229
|
+
palette = flattenColors(module.default ?? module, new Map(), paths);
|
|
208
230
|
} else {
|
|
209
231
|
palette = parsePaletteColors(fs.readFileSync(file, "utf8"));
|
|
210
232
|
}
|
|
211
|
-
const result = { palette, classOnly };
|
|
233
|
+
const result = { palette, classOnly, paths };
|
|
212
234
|
paletteCache.set(file, { mtimeMs, result });
|
|
213
235
|
return result;
|
|
214
236
|
}
|
|
@@ -219,10 +241,11 @@ function readTailwindPalette(tokensFile, m) {
|
|
|
219
241
|
* - 프로젝트가 --color-*: initial, --*: initial 같은 선언으로 비운 네임스페이스의 색
|
|
220
242
|
* - exclude 에 걸린 색
|
|
221
243
|
* @param {ProjectTokens} project
|
|
222
|
-
* @param {{ palette: Map<string, string>, classOnly: boolean }} tailwind
|
|
244
|
+
* @param {{ palette: Map<string, string>, classOnly: boolean, paths: Map<string, string[]> }} tailwind
|
|
245
|
+
* classOnly 면 팔레트 색에 CSS 변수가 없다 (v3). 그때 paths 에 theme() 으로 가리킬 키 경로가 있다
|
|
223
246
|
* @param {string[]} exclude
|
|
224
247
|
*/
|
|
225
|
-
function withPalette(project, { palette, classOnly: paletteIsClassOnly }, exclude) {
|
|
248
|
+
function withPalette(project, { palette, classOnly: paletteIsClassOnly, paths }, exclude) {
|
|
226
249
|
const matches = (name, pattern) => (pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
|
|
227
250
|
const excluded = (name) => [...exclude, ...project.resets].some((pattern) => matches(name, pattern));
|
|
228
251
|
const colors = new Map([...project.colors].map(([hex, names]) => [hex, [...names]]));
|
|
@@ -232,6 +255,9 @@ function withPalette(project, { palette, classOnly: paletteIsClassOnly }, exclud
|
|
|
232
255
|
paletteNames.add(name);
|
|
233
256
|
colors.set(hex, [...(colors.get(hex) ?? []), name]);
|
|
234
257
|
}
|
|
235
|
-
|
|
236
|
-
|
|
258
|
+
if (!paletteIsClassOnly) return { colors, themed: project.themed, paletteNames, classOnly: project.classOnly };
|
|
259
|
+
const classOnly = new Set([...project.classOnly, ...paletteNames]);
|
|
260
|
+
const themePaths = new Map(project.themePaths);
|
|
261
|
+
for (const name of paletteNames) themePaths.set(name, paths.get(name));
|
|
262
|
+
return { colors, themed: project.themed, paletteNames, classOnly, themePaths };
|
|
237
263
|
}
|
|
@@ -8,7 +8,8 @@ import { normalizeColor } from "../core/color.js";
|
|
|
8
8
|
* - 이 색들은 클래스(bg-brand-500)로만 쓸 수 있다. Tailwind 가 CSS 변수를 만들지 않기 때문이다.
|
|
9
9
|
* 설정 파일을 실행하므로, 그 파일이 require 하는 것이 설치되어 있어야 한다.
|
|
10
10
|
* @param {string} file 설정 파일의 절대 경로
|
|
11
|
-
* @returns {{ colors: Map<string, string>, replacesPalette: boolean }}
|
|
11
|
+
* @returns {{ colors: Map<string, string>, paths: Map<string, string[]>, replacesPalette: boolean }}
|
|
12
|
+
* colors 는 토큰 이름(--color-brand-500) → 비교용 색 표기, paths 는 토큰 이름 → 설정의 키 경로(["brand", "500"])
|
|
12
13
|
* @throws 설정을 불러오지 못했을 때
|
|
13
14
|
*/
|
|
14
15
|
export function loadConfigColors(file) {
|
|
@@ -26,7 +27,7 @@ export function loadConfigColors(file) {
|
|
|
26
27
|
// tailwindcss/colors 를 쓰지 않는 설정이면 없어도 된다.
|
|
27
28
|
}
|
|
28
29
|
|
|
29
|
-
const result = { colors: new Map(), replacesPalette: false };
|
|
30
|
+
const result = { colors: new Map(), paths: new Map(), replacesPalette: false };
|
|
30
31
|
collect(loaded?.default ?? loaded, palette, result);
|
|
31
32
|
return result;
|
|
32
33
|
}
|
|
@@ -47,9 +48,10 @@ function collect(config, palette, result) {
|
|
|
47
48
|
if (replaced && typeof replaced === "object") {
|
|
48
49
|
result.replacesPalette = true;
|
|
49
50
|
result.colors.clear();
|
|
50
|
-
|
|
51
|
+
result.paths.clear();
|
|
52
|
+
flattenColors(replaced, result.colors, result.paths);
|
|
51
53
|
}
|
|
52
|
-
flattenColors(section(config.theme?.extend?.colors), result.colors);
|
|
54
|
+
flattenColors(section(config.theme?.extend?.colors), result.colors, result.paths);
|
|
53
55
|
}
|
|
54
56
|
|
|
55
57
|
/**
|
|
@@ -58,9 +60,11 @@ function collect(config, palette, result) {
|
|
|
58
60
|
* getter 는 읽지 않는다. tailwindcss/colors 의 옛 이름(lightBlue 등)은 읽기만 해도 경고를 찍는다.
|
|
59
61
|
* @param {unknown} colors
|
|
60
62
|
* @param {Map<string, string>} [out]
|
|
63
|
+
* @param {Map<string, string[]>} [paths] 주면 토큰 이름마다 키 경로를 적는다. theme("colors.brand.500") 을 만들 때 쓴다
|
|
61
64
|
* @param {string} [prefix]
|
|
65
|
+
* @param {string[]} [path]
|
|
62
66
|
*/
|
|
63
|
-
export function flattenColors(colors, out = new Map(), prefix = "--color") {
|
|
67
|
+
export function flattenColors(colors, out = new Map(), paths = new Map(), prefix = "--color", path = []) {
|
|
64
68
|
if (!colors || typeof colors !== "object") return out;
|
|
65
69
|
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(colors))) {
|
|
66
70
|
if (!descriptor.enumerable || !("value" in descriptor)) continue;
|
|
@@ -68,9 +72,12 @@ export function flattenColors(colors, out = new Map(), prefix = "--color") {
|
|
|
68
72
|
const name = key === "DEFAULT" ? prefix : `${prefix}-${key}`;
|
|
69
73
|
if (typeof value === "string") {
|
|
70
74
|
const color = normalizeColor(value);
|
|
71
|
-
if (color && name !== "--color")
|
|
75
|
+
if (color && name !== "--color") {
|
|
76
|
+
out.set(name, color);
|
|
77
|
+
paths.set(name, [...path, key]);
|
|
78
|
+
}
|
|
72
79
|
} else {
|
|
73
|
-
flattenColors(value, out, name);
|
|
80
|
+
flattenColors(value, out, paths, name, [...path, key]);
|
|
74
81
|
}
|
|
75
82
|
}
|
|
76
83
|
return out;
|