designsnitch 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/check.js CHANGED
@@ -2,19 +2,19 @@ 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 { normalizeHex } from "./core/color.js";
5
+ import { colorLabel, normalizeColor, parseColor } from "./core/color.js";
6
6
  import { findCssColors } from "./core/css.js";
7
- import { cssColorPrefixes, recommendColorCandidate, selectColorTokens, utilityColorPrefixes } from "./core/tokens.js";
7
+ import { cssColorPrefixes, recommendColorCandidate, selectColorTokens, tokenVar, utilityColorPrefixes } from "./core/tokens.js";
8
8
  import { createEngine } from "./engine.js";
9
9
  import { splitPaths } from "./files.js";
10
10
  import plugin from "./index.js";
11
11
  import { messages, resolveLang } from "./messages.js";
12
12
  import { loadTokens } from "./rules/load-tokens.js";
13
- import uncheckedHex from "./rules/unchecked-hex.js";
13
+ import uncheckedColors from "./rules/unchecked-colors.js";
14
14
 
15
15
  const RULE_PREFIX = "designsnitch/";
16
- const UNCHECKED_RULE = "designsnitch-internal/unchecked-hex";
17
- const internalPlugin = { rules: { "unchecked-hex": uncheckedHex } };
16
+ const UNCHECKED_RULE = "designsnitch-internal/unchecked-colors";
17
+ const internalPlugin = { rules: { "unchecked-colors": uncheckedColors } };
18
18
  const MAX_DECISION_LOCATIONS = 5;
19
19
 
20
20
  /**
@@ -30,8 +30,9 @@ const MAX_DECISION_LOCATIONS = 5;
30
30
  * @property {string} found 위반한 코드 조각 (클래스나 태그 이름)
31
31
  * @property {string[]} candidates 대신 쓸 클래스나 컴포넌트. 없으면 빈 배열
32
32
  * @property {string | null} recommended 바로 바꿀 후보 또는 역할에 맞는 유일한 후보
33
- * @property {"replace" | "ask" | "repair"} action 이 위반을 어떻게 다룰지.
34
- * replace: found 를 candidates 의 값으로 바꿀 수 있다 (교체가 안전하고 후보가 하나뿐인 오류)
33
+ * @property {"replace" | "migrate" | "ask" | "repair"} action 이 위반을 어떻게 다룰지.
34
+ * replace: found 를 candidates 의 값으로 바꿔도 화면과 동작이 같다 (후보가 하나뿐인 색 오류)
35
+ * migrate: raw 태그를 하나뿐인 후보 컴포넌트로 옮긴다. 컴포넌트를 읽고 props 와 스타일을 맞춰야 한다
35
36
  * ask: 사람이 정해야 한다 (교체가 확실하지 않거나 후보가 하나가 아닌 경우)
36
37
  * repair: 파일을 읽지 못했다. 문법 오류부터 고쳐야 한다
37
38
  */
@@ -46,7 +47,7 @@ const MAX_DECISION_LOCATIONS = 5;
46
47
  * @property {Pick<Violation, "file" | "line" | "column">[]} locations 위반 위치 최대 다섯 곳
47
48
  * @property {string[]} candidates
48
49
  * @property {string | null} recommended 각 위치에서 추천이 같을 때 그 후보
49
- * @property {("multiple-candidates" | "no-token" | "themed-token" | "dynamic-props")[]} reasons
50
+ * @property {("multiple-candidates" | "no-token" | "themed-token" | "class-only-token" | "dynamic-props")[]} reasons
50
51
  */
51
52
 
52
53
  /**
@@ -82,8 +83,8 @@ export async function check({ cwd, config, paths = ["."], lang, sourceCwd = cwd
82
83
  }
83
84
  }
84
85
  const designSystem = describeDesignSystem(tokens, config);
85
- const problems = [];
86
- if (designSystem.colorTokens === 0) {
86
+ const problems = [...tokens.problems];
87
+ if (designSystem.colorTokens + designSystem.paletteColors === 0) {
87
88
  problems.push(m.noColorTokens({ tokens: tokenSettings(config.tokens).file }));
88
89
  }
89
90
 
@@ -100,21 +101,22 @@ export async function check({ cwd, config, paths = ["."], lang, sourceCwd = cwd
100
101
  },
101
102
  });
102
103
  const results = scriptPaths.length > 0 ? await eslint.lintFiles(scriptPaths) : [];
103
- // 검사하지 못한 hex 색은 위반이 아니라 개수로만 알린다. 놓친 것이 있다는 사실을 숨기지 않기 위해서다.
104
+ // 검사하지 못한 색은 위반이 아니라 개수로만 알린다. 놓친 것이 있다는 사실을 숨기지 않기 위해서다.
104
105
  const uncheckedFiles = results
106
+ // 토큰을 정의하는 파일(tailwind.config.js)의 색은 놓친 색이 아니다.
107
+ .filter((result) => !tokens.files.has(realPath(result.filePath)))
105
108
  .map((result) => result.messages.filter((message) => message.ruleId === UNCHECKED_RULE).length)
106
109
  .filter((n) => n > 0);
107
- const unchecked = { hexColors: uncheckedFiles.reduce((a, b) => a + b, 0), files: uncheckedFiles.length };
110
+ const unchecked = { colors: uncheckedFiles.reduce((a, b) => a + b, 0), files: uncheckedFiles.length };
108
111
  const scriptViolations = results.flatMap((result) => {
109
112
  const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
110
113
  return result.messages
111
114
  .filter(isOurs)
112
115
  .map((message) => toViolation(file, result.source, message, config));
113
116
  });
114
- const tokenFile = path.resolve(root, tokenSettings(config.tokens).file);
115
117
  const cssViolations = cssFiles.flatMap((file) => {
116
118
  const source = fs.readFileSync(path.resolve(cwd, file), "utf8");
117
- const skipCustomProperties = path.resolve(sourceCwd, file) === tokenFile;
119
+ const skipCustomProperties = tokens.files.has(realPath(path.resolve(sourceCwd, file)));
118
120
  return checkCss(file, source, tokens, m, { skipCustomProperties });
119
121
  });
120
122
 
@@ -122,7 +124,7 @@ export async function check({ cwd, config, paths = ["."], lang, sourceCwd = cwd
122
124
  .sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column)
123
125
  .map((finding) => {
124
126
  const action = actionFor(finding, finding.messageId);
125
- const recommended = action === "replace" ? finding.candidates[0] : finding.recommended ?? null;
127
+ const recommended = action === "replace" || action === "migrate" ? finding.candidates[0] : finding.recommended ?? null;
126
128
  return { ...finding, action, recommended };
127
129
  });
128
130
  const violations = findings.map(({ messageId, ...violation }) => violation);
@@ -144,7 +146,7 @@ export async function check({ cwd, config, paths = ["."], lang, sourceCwd = cwd
144
146
  }
145
147
 
146
148
  /**
147
- * CSS 파일 하나의 hex 색을 토큰과 비교한다. 대체 후보는 var(--토큰) 이다.
149
+ * CSS 파일 하나의 색을 토큰과 비교한다. 대체 후보는 선언에서는 var(--토큰), @apply 에서는 토큰 클래스다.
148
150
  * @returns {(Omit<Violation, "action" | "recommended"> & { recommended?: string | null, messageId?: string })[]}
149
151
  */
150
152
  function checkCss(file, source, tokens, m, options) {
@@ -170,10 +172,29 @@ function checkCss(file, source, tokens, m, options) {
170
172
 
171
173
  return colors
172
174
  .filter((color) => !color.disabled)
173
- .map(({ value, prop, disabled, ...location }) => {
174
- const prefixes = cssColorPrefixes(prop);
175
- const tokenNames = selectColorTokens(tokens.colors.get(normalizeHex(value)) ?? [], tokens.prefer, prefixes);
176
- const candidates = tokenNames.map((name) => `var(${name})`);
175
+ .map(({ value, prop, utility, text, disabled, ...location }) => {
176
+ // @apply 의 클래스는 JS 의 클래스처럼 토큰 클래스로, 선언의 값은 var(--토큰) 으로 바꾼다.
177
+ const found = text ?? value;
178
+ const prefixes = utility ? utilityColorPrefixes(utility) : cssColorPrefixes(prop);
179
+ const toCandidate = (name) => (utility ? tokenToClass(utility, name) : tokenVar(name, tokens.prefix));
180
+ const known = tokens.colors.get(normalizeColor(value)) ?? [];
181
+ // 클래스로만 쓸 수 있는 토큰은 선언의 값을 대신할 수 없다. 그래도 직접 쓴 색이라는 것은 알린다.
182
+ const usable = utility ? known : known.filter((name) => !tokens.classOnly.has(name));
183
+ if (known.length > 0 && usable.length === 0) {
184
+ return {
185
+ file,
186
+ ...location,
187
+ rule: "color-use-token",
188
+ severity: "error",
189
+ messageId: "useTokenClassOnly",
190
+ message: m.useTokenClassOnly({ found, tokens: known.join(", ") }),
191
+ found,
192
+ candidates: [],
193
+ recommended: null,
194
+ };
195
+ }
196
+ const tokenNames = selectColorTokens(usable, tokens.prefer, prefixes);
197
+ const candidates = tokenNames.map(toCandidate);
177
198
  const recommendedToken = recommendColorCandidate(tokenNames, prefixes);
178
199
  const messageId = tokenNames.some((name) => tokens.themed.has(name)) ? "useTokenThemed" : "useToken";
179
200
  return {
@@ -185,7 +206,7 @@ function checkCss(file, source, tokens, m, options) {
185
206
  severity: "error",
186
207
  messageId,
187
208
  message: m[messageId]({
188
- found: value,
209
+ found,
189
210
  tokens: tokenNames.join(", "),
190
211
  candidates: candidates.join(", "),
191
212
  }),
@@ -193,27 +214,35 @@ function checkCss(file, source, tokens, m, options) {
193
214
  : {
194
215
  rule: "color-unknown",
195
216
  severity: "warning",
196
- message: m.unknownCssColor({ value }),
217
+ message: utility ? m.unknownColor({ found }) : m.unknownCssColor({ value }),
197
218
  }),
198
- found: value,
219
+ found,
199
220
  candidates,
200
- recommended: recommendedToken ? `var(${recommendedToken})` : null,
221
+ recommended: recommendedToken ? toCandidate(recommendedToken) : null,
201
222
  };
202
223
  });
203
224
  }
204
225
 
226
+ function realPath(file) {
227
+ try {
228
+ return fs.realpathSync(file);
229
+ } catch {
230
+ return file; // HEAD 비교처럼 원본 위치에 파일이 없을 수 있다
231
+ }
232
+ }
233
+
205
234
  function actionFor({ rule, severity, candidates }, messageId) {
206
235
  if (rule === "parse-error") return "repair";
207
236
  if (messageId === "useComponentAsk" || messageId === "useTokenThemed") return "ask";
208
- return severity === "error" && candidates.length === 1 ? "replace" : "ask";
237
+ if (severity !== "error" || candidates.length !== 1) return "ask";
238
+ // 컴포넌트는 props 와 기본 스타일이 태그와 다를 수 있어서, 바꿔도 같다고 보장할 수 없다.
239
+ return rule === "use-ds-component" ? "migrate" : "replace";
209
240
  }
210
241
 
211
242
  function decisionSubject({ rule, found }) {
212
243
  if (rule === "use-ds-component") return `<${found}>`;
213
- const value = found.startsWith("#") ? found : findArbitraryColors(found)[0]?.value;
214
- if (!value) return found;
215
- const hex = value.toLowerCase();
216
- return normalizeHex(hex) ?? (hex.length === 5 ? hex.replace(/[0-9a-f]/g, "$&$&") : hex);
244
+ const value = parseColor(found) ? found : findArbitraryColors(found)[0]?.value;
245
+ return value ? colorLabel(value) : found;
217
246
  }
218
247
 
219
248
  /**
@@ -241,6 +270,7 @@ function groupDecisions(violations) {
241
270
  if (candidates.length > 1) decision.reasons.add("multiple-candidates");
242
271
  if (rule === "color-unknown") decision.reasons.add("no-token");
243
272
  if (messageId === "useTokenThemed") decision.reasons.add("themed-token");
273
+ if (messageId === "useTokenClassOnly") decision.reasons.add("class-only-token");
244
274
  if (messageId === "useComponentAsk") decision.reasons.add("dynamic-props");
245
275
  }
246
276
 
@@ -264,13 +294,13 @@ function groupDecisions(violations) {
264
294
  */
265
295
  export function nextSteps(designSystem, violations, lang, decisions) {
266
296
  const m = messages(lang);
267
- const noColorTokens = designSystem.colorTokens === 0;
297
+ const noColorTokens = designSystem.colorTokens + (designSystem.paletteColors ?? 0) === 0;
268
298
  // 색 토큰이 없으면 색 위반은 하나씩 다룰 일이 아니라 토큰을 정하는 일 하나로 묶인다.
269
299
  const actionable = noColorTokens
270
300
  ? violations.filter((v) => !v.rule.startsWith("color-"))
271
301
  : violations;
272
302
  const count = (action) => actionable.filter((v) => v.action === action).length;
273
- const [repair, replace] = ["repair", "replace"].map(count);
303
+ const [repair, replace, migrate] = ["repair", "replace", "migrate"].map(count);
274
304
  const ask = decisions === undefined
275
305
  ? count("ask")
276
306
  : decisions.filter((decision) => !noColorTokens || !decision.rule.startsWith("color-")).length;
@@ -279,17 +309,19 @@ export function nextSteps(designSystem, violations, lang, decisions) {
279
309
  if (noColorTokens) steps.push(m.nextNoTokens());
280
310
  if (repair > 0) steps.push(m.nextRepair(repair));
281
311
  if (replace > 0) steps.push(m.nextReplace(replace));
312
+ if (migrate > 0) steps.push(m.nextMigrate(migrate));
282
313
  if (ask > 0) steps.push(decisions === undefined ? m.hookNextAsk(ask) : m.nextAsk(ask));
283
- if (repair + replace > 0) steps.push(m.nextRerun());
314
+ if (repair + replace + migrate > 0) steps.push(m.nextRerun());
284
315
 
285
316
  return steps.length > 0 ? steps : [m.nextNone()];
286
317
  }
287
318
 
288
319
  function describeDesignSystem(tokens, config) {
289
- const countNames = (map) => new Set([...map.values()].flat()).size;
290
320
  const replaces = Object.values(config.components?.replaces ?? {});
321
+ const names = new Set([...tokens.colors.values()].flat());
291
322
  return {
292
- colorTokens: countNames(tokens.colors),
323
+ colorTokens: [...names].filter((name) => !tokens.paletteNames.has(name)).length,
324
+ paletteColors: tokens.paletteNames.size,
293
325
  components: new Set(replaces.flatMap(replacementNames)).size,
294
326
  replacedTags: replaces.length,
295
327
  };
package/src/cli.js CHANGED
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import { check } from "./check.js";
5
5
  import { collectColors } from "./colors.js";
6
- import { CONFIG_FILE, loadConfig, tokenSettings } from "./config.js";
6
+ import { CONFIG_FILE, loadConfig } from "./config.js";
7
7
  import { formatColorsText, formatText } from "./format.js";
8
8
  import { runHook } from "./hook.js";
9
9
  import { AGENT_CHOICES, install } from "./install.js";
@@ -29,9 +29,8 @@ const COMMANDS = {
29
29
  const hasConfig = configPath !== undefined || fs.existsSync(path.resolve(cwd, CONFIG_FILE));
30
30
  const config = hasConfig ? loadConfig(cwd, configPath, resolveLang(flagLang)) : undefined;
31
31
  const lang = resolveLang(flagLang, config?.lang);
32
- const tokens = config ? loadTokens({ designsnitch: { ...config, lang } }, cwd).colors : undefined;
33
- const tokenFile = config ? path.resolve(config.root, tokenSettings(config.tokens).file) : undefined;
34
- const result = await collectColors({ cwd, paths, tokens, tokenFile });
32
+ const tokens = config ? loadTokens({ designsnitch: { ...config, lang } }, cwd) : undefined;
33
+ const result = await collectColors({ cwd, paths, tokens: tokens?.colors, tokenFiles: tokens?.files });
35
34
  return { stdout: format === "json" ? json(result) : formatColorsText(result, lang), exitCode: 0 };
36
35
  },
37
36
 
package/src/colors.js CHANGED
@@ -1,23 +1,21 @@
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 { normalizeHex } from "./core/color.js";
4
+ import { colorLabel, isColorProperty, isNamedColor, parseColor } 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";
8
8
  import { visitStrings } from "./rules/visit-strings.js";
9
+ import { inlineStyleProperty } from "./rules/visit-style.js";
9
10
 
10
11
  const RULE_ID = "designsnitch-internal/collect-colors";
11
- const HEX_LITERAL = /^#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})$/i;
12
12
  const MAX_EXAMPLES = 3;
13
13
 
14
- // 알파가 붙은 hex 는 6자리로 펼칠 수 없으니 소문자로만 맞춘다.
15
- const colorKey = (hex) => normalizeHex(hex) ?? hex.toLowerCase();
16
14
 
17
15
  const findColors = (text) => [
18
16
  ...findArbitraryColors(text).map((found) => ({
19
17
  ...found,
20
- payload: { kind: "hex", key: colorKey(found.value), utility: found.utility },
18
+ payload: { kind: "hex", key: colorLabel(found.value), utility: found.utility },
21
19
  })),
22
20
  ...findPaletteClasses(text).map((found) => ({
23
21
  ...found,
@@ -36,9 +34,12 @@ const collectRule = {
36
34
  return {
37
35
  ...visitor,
38
36
  Literal(node) {
39
- // 문자열 전체가 hex 색인 경우. 예: style={{ color: "#3B82F6" }}
40
- if (typeof node.value === "string" && HEX_LITERAL.test(node.value)) {
41
- report(node.loc, { kind: "hex", key: colorKey(node.value), utility: null });
37
+ // 문자열 전체가 색인 경우. 예: style={{ color: "#3B82F6" }}
38
+ // 색 이름은 인라인 스타일의 색 속성에서만 색으로 센다. 다른 곳에서는 그냥 단어일 수 있다.
39
+ const isColor = (value) =>
40
+ parseColor(value) !== null && (!isNamedColor(value) || isColorProperty(inlineStyleProperty(node) ?? ""));
41
+ if (typeof node.value === "string" && isColor(node.value)) {
42
+ report(node.loc, { kind: "hex", key: colorLabel(node.value), utility: null });
42
43
  return;
43
44
  }
44
45
  visitor.Literal(node);
@@ -61,7 +62,7 @@ const collectRule = {
61
62
  * @param {string} options.cwd 프로젝트 디렉터리
62
63
  * @param {string[]} [options.paths] 검사할 파일이나 디렉터리 (cwd 기준)
63
64
  * @param {Map<string, string[]>} [options.tokens] 색 값 → 토큰 이름들. 주면 색마다 tokens 를 붙인다
64
- * @param {string} [options.tokenFile] 사용자 정의 속성 선언을 건너뛸 토큰 CSS 의 절대 경로
65
+ * @param {Set<string>} [options.tokenFiles] 토큰을 정의하는 파일들의 절대 경로. CSS 는 변수 선언을, JS 설정은 통째로 건너뛴다
65
66
  * @returns {Promise<{
66
67
  * summary: { files: number, colors: number, paletteColors: number, uses: number },
67
68
  * colors: (ColorUse & { color: string, literals: number, properties: Record<string, number>, tokens?: string[] })[],
@@ -69,7 +70,7 @@ const collectRule = {
69
70
  * }>} colors 는 hex 색, palette 는 Tailwind 기본 팔레트 색. 둘 다 많이 쓰인 순서.
70
71
  * literals 는 문자열 전체가 hex 인 곳의 수, properties 는 CSS 속성별 횟수
71
72
  */
72
- export async function collectColors({ cwd, paths = ["."], tokens, tokenFile }) {
73
+ export async function collectColors({ cwd, paths = ["."], tokens, tokenFiles }) {
73
74
  const eslint = createEngine({
74
75
  cwd,
75
76
  // 수집이 목적이므로 eslint-disable 주석이 있어도 빠뜨리지 않는다.
@@ -86,6 +87,8 @@ export async function collectColors({ cwd, paths = ["."], tokens, tokenFile }) {
86
87
  /** @type {{ file: string, line: number, kind: "hex" | "palette", key: string, utility?: string | null, prop?: string }[]} */
87
88
  const uses = [];
88
89
  for (const result of results) {
90
+ // 토큰을 정의하는 파일(tailwind.config.js)의 색은 코드가 쓰는 색이 아니다.
91
+ if (tokenFiles?.has(fs.realpathSync(result.filePath))) continue;
89
92
  const file = path.relative(cwd, result.filePath).split(path.sep).join("/");
90
93
  for (const message of result.messages) {
91
94
  if (message.ruleId !== RULE_ID) continue;
@@ -96,12 +99,12 @@ export async function collectColors({ cwd, paths = ["."], tokens, tokenFile }) {
96
99
  const absolute = path.resolve(cwd, file);
97
100
  let found;
98
101
  try {
99
- found = findCssColors(fs.readFileSync(absolute, "utf8"), { skipCustomProperties: absolute === tokenFile });
102
+ found = findCssColors(fs.readFileSync(absolute, "utf8"), { skipCustomProperties: tokenFiles?.has(fs.realpathSync(absolute)) ?? false });
100
103
  } catch {
101
104
  continue; // 읽지 못한 CSS 는 건너뛴다
102
105
  }
103
- for (const { line, value, prop } of found) {
104
- uses.push({ file, line, kind: "hex", key: colorKey(value), prop });
106
+ for (const { line, value, prop, utility } of found) {
107
+ uses.push({ file, line, kind: "hex", key: colorLabel(value), prop, utility });
105
108
  }
106
109
  }
107
110
  uses.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
package/src/config.js CHANGED
@@ -71,6 +71,7 @@ export function loadConfig(cwd, configPath = CONFIG_FILE, lang) {
71
71
  if (tokenField === "tokens") throw new Error(m.configNoTokens({ file }));
72
72
  if (tokenField) throw new Error(m.invalidTokenSetting({ field: tokenField, file }));
73
73
  if (config.lang !== undefined && !isLang(config.lang)) throw new Error(m.configBadLang({ file }));
74
+ if (config.palette !== undefined && config.palette !== "tailwind") throw new Error(m.configBadPalette({ file }));
74
75
  if (config.components !== undefined) validateComponents(config.components, file, m);
75
76
  return { ...config, root: path.dirname(file) };
76
77
  }
@@ -1,19 +1,23 @@
1
- // 예: bg-[#3B82F6], ring-offset-[#fff]
1
+ import { parseColor } from "./color.js";
2
+
3
+ // 예: bg-[#3B82F6], ring-offset-[#fff], text-[rgb(59,130,246)], bg-[oklch(62.3%_0.214_259.815)], bg-[white]
2
4
  const ARBITRARY_COLOR =
3
- /(?<![\w-])([a-z][a-z0-9]*(?:-[a-z0-9]+)*)-\[(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4}))\]/gi;
5
+ /(?<![\w-])([a-z][a-z0-9]*(?:-[a-z0-9]+)*)-\[(#[0-9a-f]{3,8}|(?:rgba?|hsla?|oklch|hwb|lab|lch|oklab|color)\([^()[\]\s]*\)|[a-z]+)\]/gi;
4
6
 
5
7
  /**
6
- * 문자열에서 hex를 임의 값으로 쓴 Tailwind 클래스를 찾는다.
8
+ * 문자열에서 색을 임의 값으로 쓴 Tailwind 클래스를 찾는다.
7
9
  * @param {string} text
8
10
  * @returns {{ index: number, text: string, utility: string, value: string }[]}
9
11
  */
10
12
  export function findArbitraryColors(text) {
11
- return [...text.matchAll(ARBITRARY_COLOR)].map((match) => ({
12
- index: match.index,
13
- text: match[0],
14
- utility: match[1],
15
- value: match[2],
16
- }));
13
+ return [...text.matchAll(ARBITRARY_COLOR)]
14
+ .filter((match) => parseColor(match[2]) !== null)
15
+ .map((match) => ({
16
+ index: match.index,
17
+ text: match[0],
18
+ utility: match[1],
19
+ value: match[2],
20
+ }));
17
21
  }
18
22
 
19
23
  /** 예: ("bg", "--color-primary-500") → "bg-primary-500" */
@@ -44,15 +48,3 @@ export function findPaletteClasses(text) {
44
48
  name: match[2],
45
49
  }));
46
50
  }
47
-
48
- // 예: "#3B82F6", "1px solid #fff". bg-[#fff] 의 hex 도 걸리므로 클래스 검사와 겹치지 않게 쓴다.
49
- const HEX_COLOR = /(?<![\w&#])#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})(?![\w-])/gi;
50
-
51
- /**
52
- * 문자열에서 hex 색 자체를 찾는다.
53
- * @param {string} text
54
- * @returns {{ index: number, text: string, value: string }[]}
55
- */
56
- export function findHexColors(text) {
57
- return [...text.matchAll(HEX_COLOR)].map((match) => ({ index: match.index, text: match[0], value: match[0] }));
58
- }
package/src/core/color.js CHANGED
@@ -1,13 +1,137 @@
1
- const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
1
+ import { NAMED_COLORS } from "./named-colors.js";
2
+ import { oklchKey } from "./oklch.js";
3
+
4
+ const HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
5
+ const FUNCTION = /^(rgba?|hsla?|oklch)\((.*)\)$/is;
6
+ // hex 로 바꾸지 않는 표기. 같은 표기끼리만 맞춘다.
7
+ const OTHER_FUNCTION = /^(hwb|lab|lch|oklab|color)\(([^()]*)\)$/is;
8
+ // 문자열 속의 색 값. 예: "#fff", "rgb(1, 2, 3)". a#top, &#39; 같은 것은 색이 아니다.
9
+ const COLOR_VALUE =
10
+ /(?<![\w&#])#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})(?![\w-])|(?<![\w-])(?:rgba?|hsla?|oklch|hwb|lab|lch|oklab|color)\([^()]*\)/gi;
11
+ // 색 이름. var(--red), .red, dark-red, red-500 같은 것은 색 이름이 아니다.
12
+ const NAMED_VALUE = new RegExp(
13
+ `(?<![\\w#.$@-])(?:${Object.keys(NAMED_COLORS).sort((a, b) => b.length - a.length).join("|")})(?![\\w(-])`,
14
+ "gi",
15
+ );
16
+ // 색을 값으로 받는 CSS 속성. 색 이름은 여기서만 색으로 본다.
17
+ const COLOR_PROPERTY =
18
+ /^(?:-(?:webkit|moz)-)?(?:color|background(?:-color|-image)?|border(?:-[a-z-]+)?|outline(?:-color)?|fill|stroke|box-shadow|text-shadow|caret-color|accent-color|text-decoration(?:-color)?|text-emphasis(?:-color)?|column-rule(?:-color)?|scrollbar-color|stop-color|flood-color|lighting-color|text-fill-color|text-stroke(?:-color)?|tap-highlight-color)$/;
19
+
20
+ /** 색을 값으로 받는 CSS 속성인지. backgroundColor 같은 JS 표기도 받는다. */
21
+ export function isColorProperty(property) {
22
+ return COLOR_PROPERTY.test(property.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`));
23
+ }
24
+
25
+ /** white, red 같은 CSS 색 이름인지. */
26
+ export function isNamedColor(value) {
27
+ return Object.hasOwn(NAMED_COLORS, value.trim().toLowerCase());
28
+ }
2
29
 
3
30
  /**
4
- * hex 색을 비교할 수 있는 형태(소문자 6자리)로 바꾼다.
5
- * 알파가 있는 hex(4, 8자리)와 hex가 아닌 값은 null.
31
+ * 색 값을 읽는다. 읽을 수 없으면 null.
32
+ * @param {string} value 예: "#3B82F6", "rgb(59 130 246)", "hsl(217, 91%, 60%)", "oklch(55.4% 0.046 257.417)", "white"
33
+ * @returns {{ key: string, alpha: number, opaque: boolean } | null} key 는 비교용 표기. sRGB 색은 소문자 6자리 hex,
34
+ * sRGB 밖의 oklch 는 표기를 맞춘 oklch(...). opaque 가 false 면 반투명이다
6
35
  */
7
- export function normalizeHex(value) {
8
- const hex = value.trim();
9
- if (!HEX.test(hex)) return null;
10
- const digits = hex.slice(1).toLowerCase();
11
- if (digits.length === 6) return `#${digits}`;
12
- return `#${[...digits].map((d) => d + d).join("")}`;
36
+ export function parseColor(value) {
37
+ const text = value.trim();
38
+ if (text.startsWith("#")) return parseHex(text);
39
+ // Tailwind 임의 값은 공백 대신 _ 를 쓴다.
40
+ if (isNamedColor(text)) return { key: `#${NAMED_COLORS[text.toLowerCase()]}`, alpha: 1, opaque: true };
41
+ const spaced = text.replaceAll("_", " ");
42
+ const other = OTHER_FUNCTION.exec(spaced);
43
+ if (other) {
44
+ const args = other[2].trim().replace(/\s+/g, " ").toLowerCase();
45
+ return args ? { key: `${other[1].toLowerCase()}(${args})`, alpha: 1, opaque: !args.includes("/") } : null;
46
+ }
47
+ const match = FUNCTION.exec(spaced);
48
+ if (!match) return null;
49
+ const name = match[1].toLowerCase();
50
+ if (name === "oklch") return oklchKey(`oklch(${match[2]})`);
51
+
52
+ const parts = match[2].trim().split(/\s*[,/]\s*|\s+/);
53
+ if (parts.length !== 3 && parts.length !== 4) return null;
54
+ const alpha = parts.length === 4 ? unit(parts[3], 1) : 1;
55
+ const rgb = name.startsWith("rgb") ? parts.slice(0, 3).map((part) => unit(part, 255)) : hslToRgb(parts);
56
+ if (alpha === null || !rgb || rgb.some((channel) => channel === null)) return null;
57
+ return { key: `#${rgb.map(toByte).join("")}`, alpha, opaque: alpha >= 1 };
13
58
  }
59
+
60
+ /**
61
+ * 색을 세거나 묶을 때 쓰는 이름. 표기가 달라도 같은 색이면 같은 이름이 된다.
62
+ * 불투명한 색은 normalizeColor 와 같고, 반투명한 색은 #rrggbbaa 다. 색이 아니면 소문자로만 맞춘다.
63
+ * @param {string} value
64
+ */
65
+ export function colorLabel(value) {
66
+ const color = parseColor(value);
67
+ if (!color) return value.toLowerCase();
68
+ if (color.opaque) return color.key;
69
+ return color.key.startsWith("#") ? `${color.key}${toByte(color.alpha * 255)}` : color.key.replace(")", ` / ${color.alpha})`);
70
+ }
71
+
72
+ /**
73
+ * 색 값을 비교할 수 있는 표기로 바꾼다. 반투명한 색과 색이 아닌 값은 null.
74
+ * @param {string} value
75
+ * @returns {string | null}
76
+ */
77
+ export function normalizeColor(value) {
78
+ const color = parseColor(value);
79
+ return color?.opaque ? color.key : null;
80
+ }
81
+
82
+ /**
83
+ * 문자열에서 색 값(hex 와 rgb(), hsl(), oklch() 같은 색 함수)을 찾는다. 반투명한 색도 찾는다.
84
+ * @param {string} text
85
+ * @param {{ named?: boolean }} [options] named 가 true 면 white 같은 색 이름도 찾는다.
86
+ * 색을 값으로 받는 자리에서만 켠다. 일반 문자열에서는 그냥 단어일 수 있다
87
+ * @returns {{ index: number, text: string, value: string }[]}
88
+ */
89
+ export function findColorValues(text, { named = false } = {}) {
90
+ const matches = [...text.matchAll(COLOR_VALUE), ...(named ? text.matchAll(NAMED_VALUE) : [])];
91
+ return matches
92
+ .filter((match) => parseColor(match[0]) !== null)
93
+ .sort((a, b) => a.index - b.index)
94
+ .map((match) => ({ index: match.index, text: match[0], value: match[0] }));
95
+ }
96
+
97
+ function parseHex(text) {
98
+ if (!HEX.test(text)) return null;
99
+ let digits = text.slice(1).toLowerCase();
100
+ if (digits.length <= 4) digits = [...digits].map((d) => d + d).join("");
101
+ const alpha = digits.length === 8 ? parseInt(digits.slice(6), 16) / 255 : 1;
102
+ return { key: `#${digits.slice(0, 6)}`, alpha, opaque: alpha >= 1 };
103
+ }
104
+
105
+ /** "50%" → max 의 절반, "128" → 128. 숫자가 아니면 null. */
106
+ function unit(text, max) {
107
+ const match = /^(-?[\d.]+)(%?)$/.exec(text);
108
+ if (!match || Number.isNaN(Number(match[1]))) return null;
109
+ const number = Number(match[1]);
110
+ return match[2] ? (number / 100) * max : number;
111
+ }
112
+
113
+ function hslToRgb([hue, saturation, lightness]) {
114
+ const h = /^(-?[\d.]+)(?:deg)?$/i.exec(hue);
115
+ const s = unit(saturation.replace(/%$/, ""), 1);
116
+ const l = unit(lightness.replace(/%$/, ""), 1);
117
+ if (!h || s === null || l === null) return null;
118
+ const [sat, light] = [s / 100, l / 100];
119
+ const chroma = (1 - Math.abs(2 * light - 1)) * sat;
120
+ const sector = (((Number(h[1]) % 360) + 360) % 360) / 60;
121
+ const x = chroma * (1 - Math.abs((sector % 2) - 1));
122
+ const [r, g, b] = [
123
+ [chroma, x, 0],
124
+ [x, chroma, 0],
125
+ [0, chroma, x],
126
+ [0, x, chroma],
127
+ [x, 0, chroma],
128
+ [chroma, 0, x],
129
+ ][Math.floor(sector) % 6];
130
+ const m = light - chroma / 2;
131
+ return [r, g, b].map((channel) => (channel + m) * 255);
132
+ }
133
+
134
+ const toByte = (channel) =>
135
+ Math.round(Math.min(255, Math.max(0, channel)))
136
+ .toString(16)
137
+ .padStart(2, "0");
package/src/core/css.js CHANGED
@@ -1,17 +1,19 @@
1
1
  import postcss from "postcss";
2
+ import { findArbitraryColors } from "./classes.js";
3
+ import { findColorValues, isColorProperty, isNamedColor } from "./color.js";
2
4
 
3
- const HEX_COLOR = /(?<![\w-])#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3,4})(?![\w-])/gi;
4
5
  // 색이 아닌 # 이 들어갈 수 있는 곳: url(#id), "문자열", /* 주석 */
5
6
  const NOT_A_VALUE = /url\([^)]*\)|"[^"]*"|'[^']*'|\/\*[\s\S]*?\*\//g;
6
7
  const DISABLE_NEXT_LINE = "designsnitch-disable-next-line";
7
8
 
8
9
  /**
9
- * CSS 의 선언 값에서 hex 색을 찾는다. 줄과 열은 1부터 시작하고, 끝 열은 색 바로 다음 칸이다.
10
+ * CSS 의 선언 값에서 색(hex 와 rgb(), hsl(), oklch())을 찾는다. 줄과 열은 1부터 시작하고, 끝 열은 색 바로 다음 칸이다.
10
11
  * 토큰 CSS 에서는 옵션을 켜서 사용자 정의 속성 선언을 건너뛸 수 있다.
11
12
  * 바로 앞에 designsnitch-disable-next-line 주석이 있는 선언의 색은 disabled 로 표시한다.
12
13
  * @param {string} css
13
14
  * @param {{ skipCustomProperties?: boolean }} [options]
14
- * @returns {{ line: number, column: number, endLine: number, endColumn: number, value: string, prop: string, disabled: boolean }[]}
15
+ * @apply 에 쓴 임의 값 색 클래스도 찾는다. 그때는 prop 대신 utility 와 클래스 전체(text)가 붙는다.
16
+ * @returns {{ line: number, column: number, endLine: number, endColumn: number, value: string, prop?: string, utility?: string, text?: string, disabled: boolean }[]}
15
17
  * @throws {import("postcss").CssSyntaxError} CSS 를 읽지 못했을 때
16
18
  */
17
19
  export function findCssColors(css, { skipCustomProperties = false } = {}) {
@@ -26,30 +28,56 @@ export function findCssColors(css, { skipCustomProperties = false } = {}) {
26
28
  };
27
29
 
28
30
  const found = [];
29
- postcss.parse(css).walkDecls((decl) => {
31
+ const root = postcss.parse(css);
32
+ const isDisabled = (node) => {
33
+ const previous = node.prev();
34
+ return previous?.type === "comment" && previous.text.includes(DISABLE_NEXT_LINE);
35
+ };
36
+
37
+ root.walkAtRules("apply", (rule) => {
38
+ const raw = rule.raws.params?.raw ?? rule.params;
39
+ const paramsStart = rule.source.start.offset + 1 + rule.name.length + (rule.raws.afterName ?? "").length;
40
+ for (const match of findArbitraryColors(raw)) {
41
+ const start = position(paramsStart + match.index);
42
+ const end = position(paramsStart + match.index + match.text.length);
43
+ found.push({
44
+ line: start.line,
45
+ column: start.column,
46
+ endLine: end.line,
47
+ endColumn: end.column,
48
+ value: match.value,
49
+ utility: match.utility,
50
+ text: match.text,
51
+ disabled: isDisabled(rule),
52
+ });
53
+ }
54
+ });
55
+
56
+ root.walkDecls((decl) => {
30
57
  if (skipCustomProperties && decl.prop.startsWith("--")) return;
31
58
 
32
- const previous = decl.prev();
33
- const disabled = previous?.type === "comment" && previous.text.includes(DISABLE_NEXT_LINE);
59
+ const disabled = isDisabled(decl);
34
60
 
35
61
  // 위치를 정확히 잡으려고 정리된 값이 아니라 원본 텍스트에서 찾는다.
36
62
  const raw = decl.raws.value?.raw ?? decl.value;
37
63
  const valueStart = decl.source.start.offset + decl.prop.length + decl.raws.between.length;
38
64
  const masked = raw.replace(NOT_A_VALUE, (skipped) => " ".repeat(skipped.length));
39
65
 
40
- for (const match of masked.matchAll(HEX_COLOR)) {
66
+ // 색 이름은 색 속성에서만, 변수 선언에서는 값 전체가 색 이름일 때만 색으로 본다.
67
+ const named = decl.prop.startsWith("--") ? isNamedColor(raw) : isColorProperty(decl.prop);
68
+ for (const match of findColorValues(masked, { named })) {
41
69
  const start = position(valueStart + match.index);
42
- const end = position(valueStart + match.index + match[0].length);
70
+ const end = position(valueStart + match.index + match.text.length);
43
71
  found.push({
44
72
  line: start.line,
45
73
  column: start.column,
46
74
  endLine: end.line,
47
75
  endColumn: end.column,
48
- value: match[0],
76
+ value: match.text,
49
77
  prop: decl.prop,
50
78
  disabled,
51
79
  });
52
80
  }
53
81
  });
54
- return found;
82
+ return found.sort((a, b) => a.line - b.line || a.column - b.column);
55
83
  }