designsnitch 0.3.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/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, ' 같은 것은 색이 아니다.
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,19 +1,22 @@
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
- * --로 시작하는 선언은 토큰이나 변수를 정의하는 곳이므로 건너뛴다.
10
+ * CSS 의 선언 값에서 색(hex 와 rgb(), hsl(), oklch())을 찾는다. 줄과 열은 1부터 시작하고, 끝 열은 색 바로 다음 칸이다.
11
+ * 토큰 CSS 에서는 옵션을 켜서 사용자 정의 속성 선언을 건너뛸 수 있다.
11
12
  * 바로 앞에 designsnitch-disable-next-line 주석이 있는 선언의 색은 disabled 로 표시한다.
12
13
  * @param {string} css
13
- * @returns {{ line: number, column: number, endLine: number, endColumn: number, value: string, prop: string, disabled: boolean }[]}
14
+ * @param {{ skipCustomProperties?: boolean }} [options]
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 }[]}
14
17
  * @throws {import("postcss").CssSyntaxError} CSS 를 읽지 못했을 때
15
18
  */
16
- export function findCssColors(css) {
19
+ export function findCssColors(css, { skipCustomProperties = false } = {}) {
17
20
  const lineStarts = [0];
18
21
  for (let i = 0; i < css.length; i += 1) {
19
22
  if (css[i] === "\n") lineStarts.push(i + 1);
@@ -25,30 +28,56 @@ export function findCssColors(css) {
25
28
  };
26
29
 
27
30
  const found = [];
28
- postcss.parse(css).walkDecls((decl) => {
29
- if (decl.prop.startsWith("--")) return;
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) => {
57
+ if (skipCustomProperties && decl.prop.startsWith("--")) return;
30
58
 
31
- const previous = decl.prev();
32
- const disabled = previous?.type === "comment" && previous.text.includes(DISABLE_NEXT_LINE);
59
+ const disabled = isDisabled(decl);
33
60
 
34
61
  // 위치를 정확히 잡으려고 정리된 값이 아니라 원본 텍스트에서 찾는다.
35
62
  const raw = decl.raws.value?.raw ?? decl.value;
36
63
  const valueStart = decl.source.start.offset + decl.prop.length + decl.raws.between.length;
37
64
  const masked = raw.replace(NOT_A_VALUE, (skipped) => " ".repeat(skipped.length));
38
65
 
39
- 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 })) {
40
69
  const start = position(valueStart + match.index);
41
- const end = position(valueStart + match.index + match[0].length);
70
+ const end = position(valueStart + match.index + match.text.length);
42
71
  found.push({
43
72
  line: start.line,
44
73
  column: start.column,
45
74
  endLine: end.line,
46
75
  endColumn: end.column,
47
- value: match[0],
76
+ value: match.text,
48
77
  prop: decl.prop,
49
78
  disabled,
50
79
  });
51
80
  }
52
81
  });
53
- return found;
82
+ return found.sort((a, b) => a.line - b.line || a.column - b.column);
54
83
  }
@@ -0,0 +1,35 @@
1
+ // CSS 의 색 이름 → hex (CSS Color Module Level 4). transparent 와 currentColor 는 색 값이 아니라서 없다.
2
+ export const NAMED_COLORS = {
3
+ aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "00ffff", aquamarine: "7fffd4", azure: "f0ffff",
4
+ beige: "f5f5dc", bisque: "ffe4c4", black: "000000", blanchedalmond: "ffebcd", blue: "0000ff",
5
+ blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", cadetblue: "5f9ea0", chartreuse: "7fff00",
6
+ chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c",
7
+ cyan: "00ffff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9",
8
+ darkgreen: "006400", darkgrey: "a9a9a9", darkkhaki: "bdb76b", darkmagenta: "8b008b",
9
+ darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000",
10
+ darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f",
11
+ darkslategrey: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493",
12
+ deepskyblue: "00bfff", dimgray: "696969", dimgrey: "696969", dodgerblue: "1e90ff", firebrick: "b22222",
13
+ floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "ff00ff", gainsboro: "dcdcdc", ghostwhite: "f8f8ff",
14
+ gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f",
15
+ grey: "808080", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082",
16
+ ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00",
17
+ lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff",
18
+ lightgoldenrodyellow: "fafad2", lightgray: "d3d3d3", lightgreen: "90ee90", lightgrey: "d3d3d3",
19
+ lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa",
20
+ lightslategray: "778899", lightslategrey: "778899", lightsteelblue: "b0c4de", lightyellow: "ffffe0",
21
+ lime: "00ff00", limegreen: "32cd32", linen: "faf0e6", magenta: "ff00ff", maroon: "800000",
22
+ mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370db",
23
+ mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a",
24
+ mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa",
25
+ mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6",
26
+ olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6",
27
+ palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "db7093",
28
+ papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd",
29
+ powderblue: "b0e0e6", purple: "800080", rebeccapurple: "663399", red: "ff0000", rosybrown: "bc8f8f",
30
+ royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57",
31
+ seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd",
32
+ slategray: "708090", slategrey: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4",
33
+ tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee",
34
+ wheat: "f5deb3", white: "ffffff", whitesmoke: "f5f5f5", yellow: "ffff00", yellowgreen: "9acd32",
35
+ };
@@ -0,0 +1,58 @@
1
+ // oklch(L C H) → sRGB hex. 공식은 CSS Color 4 의 OKLab 정의를 따른다.
2
+ // 값 대신 none 을 쓸 수 있다(CSS Color 4). Tailwind 4.3.5 부터 회색의 색상(hue)을 none 으로 적는다.
3
+ const OKLCH =
4
+ /^oklch\(\s*([\d.]+|none)(%?)\s+([\d.]+|none)\s+([\d.]+|none)(?:deg)?\s*(?:\/\s*([\d.]+%?|none)\s*)?\)$/i;
5
+ // none 은 계산할 때 0 으로 본다.
6
+ const num = (text) => (text.toLowerCase() === "none" ? 0 : Number(text));
7
+ // 반올림 오차로 범위를 조금 넘는 것은 sRGB 안으로 본다.
8
+ const EPSILON = 0.0005;
9
+ const round = (number, digits) => Number(number.toFixed(digits));
10
+
11
+ /**
12
+ * oklch 색을 비교용 표기로 읽는다. oklch 가 아니면 null.
13
+ * @param {string} value
14
+ * @returns {{ key: string, alpha: number, opaque: boolean } | null} key 는 sRGB 안이면 소문자 6자리 hex,
15
+ * 밖이면 자릿수를 맞춘 "oklch(L C H)". 같은 색을 내는 hex 가 없기 때문이다
16
+ */
17
+ export function oklchKey(value) {
18
+ const match = OKLCH.exec(value.trim());
19
+ if (!match) return null;
20
+ const L = num(match[1]) / (match[2] ? 100 : 1);
21
+ const C = num(match[3]);
22
+ const H = num(match[4]);
23
+ const alpha = match[5] === undefined ? 1 : match[5].endsWith("%") ? Number(match[5].slice(0, -1)) / 100 : num(match[5]);
24
+ const h = (H * Math.PI) / 180;
25
+ const a = C * Math.cos(h);
26
+ const b = C * Math.sin(h);
27
+
28
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
29
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
30
+ const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
31
+ const linear = [
32
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
33
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
34
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
35
+ ];
36
+ const opaque = alpha >= 1;
37
+ if (linear.some((c) => c < -EPSILON || c > 1 + EPSILON)) {
38
+ const hue = C === 0 ? 0 : round(((H % 360) + 360) % 360, 3);
39
+ return { key: `oklch(${round(L, 4)} ${round(C, 4)} ${hue})`, alpha, opaque };
40
+ }
41
+
42
+ const toByte = (c) => {
43
+ const v = Math.min(1, Math.max(0, c));
44
+ const srgb = v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055;
45
+ return Math.round(srgb * 255).toString(16).padStart(2, "0");
46
+ };
47
+ return { key: `#${linear.map(toByte).join("")}`, alpha, opaque };
48
+ }
49
+
50
+ /**
51
+ * oklch 색을 sRGB hex(소문자 6자리)로 바꾼다. sRGB 밖의 색이거나 oklch 가 아니면 null.
52
+ * @param {string} value
53
+ * @returns {string | null}
54
+ */
55
+ export function oklchToHex(value) {
56
+ const color = oklchKey(value);
57
+ return color?.opaque && color.key.startsWith("#") ? color.key : null;
58
+ }
@@ -1,7 +1,12 @@
1
1
  import postcss from "postcss";
2
- import { normalizeHex } from "./color.js";
2
+ import { normalizeColor } from "./color.js";
3
3
 
4
4
  const COLOR_TOKEN = /^--color-/;
5
+ const ROLE_PREFIXES = {
6
+ text: ["--color-text-"],
7
+ border: ["--color-border-"],
8
+ bg: ["--color-bg-", "--color-surface", "--color-background"],
9
+ };
5
10
  // var(--name) 또는 var(--name, 대체값)
6
11
  const VAR_REFERENCE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/s;
7
12
 
@@ -20,9 +25,11 @@ export function parseColorTokens(css) {
20
25
  /**
21
26
  * 색 값 → 토큰 표와 서로 다른 최종 값이 있는 토큰 이름을 함께 읽는다.
22
27
  * @param {string} css
23
- * @returns {{ colors: Map<string, string[]>, themed: Set<string> }}
28
+ * @param {string[]} [exclude] 정확한 이름 또는 끝에 *가 붙은 이름 패턴
29
+ * @returns {{ colors: Map<string, string[]>, themed: Set<string>, names: Set<string>, resets: string[] }}
30
+ * names 는 값을 읽었든 못 읽었든 선언된 --color-* 이름, resets 는 initial 로 비운 네임스페이스(예: "--color-*")
24
31
  */
25
- export function parseColorTokenData(css) {
32
+ export function parseColorTokenData(css, exclude = []) {
26
33
  /** @type {Map<string, string[]>} 변수 이름 → 선언된 값들 */
27
34
  const declared = new Map();
28
35
  postcss.parse(css).walkDecls(/^--/, (decl) => {
@@ -46,12 +53,21 @@ export function parseColorTokenData(css) {
46
53
 
47
54
  const colors = new Map();
48
55
  const themed = new Set();
56
+ const names = new Set();
57
+ const resets = [];
49
58
  for (const [name, values] of declared) {
59
+ // Tailwind 는 --color-*: initial 처럼 네임스페이스를 비울 수 있다. 토큰이 아니라 기본 테마를 지우는 선언이다.
60
+ if (name.endsWith("*")) {
61
+ if (values.some((value) => value.trim() === "initial")) resets.push(name);
62
+ continue;
63
+ }
50
64
  if (!COLOR_TOKEN.test(name)) continue;
65
+ names.add(name);
66
+ if (exclude.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern)) continue;
51
67
  const resolved = new Set();
52
68
  for (const value of values.flatMap((value) => resolve(value, new Set([name])))) {
53
- const color = normalizeHex(value);
54
- // hex 가 아닌 값도 테마 차이는 만들 수 있지만 색 후보로는 쓰지 않는다.
69
+ const color = normalizeColor(value);
70
+ // 색으로 읽지 못한 값도 테마 차이는 만들 수 있지만 색 후보로는 쓰지 않는다.
55
71
  const key = color ?? value;
56
72
  if (resolved.has(key)) continue;
57
73
  resolved.add(key);
@@ -61,5 +77,57 @@ export function parseColorTokenData(css) {
61
77
  }
62
78
  if (resolved.size > 1) themed.add(name);
63
79
  }
64
- return { colors, themed };
80
+ return { colors, themed, names, resets };
81
+ }
82
+
83
+ /** 토큰을 CSS 에서 가리키는 표기. Tailwind 접두어가 있으면 변수 이름에 붙는다. 예: var(--tw-color-brand) */
84
+ export function tokenVar(name, prefix) {
85
+ return `var(${prefix ? name.replace(/^--/, `--${prefix}-`) : name})`;
86
+ }
87
+
88
+ export function utilityColorPrefixes(utility) {
89
+ const kind = utility.toLowerCase().split("-", 1)[0];
90
+ if (["border", "ring", "outline", "divide"].includes(kind)) return ROLE_PREFIXES.border;
91
+ return kind === "text" || kind === "bg" ? ROLE_PREFIXES[kind] : [];
92
+ }
93
+
94
+ export function cssColorPrefixes(property) {
95
+ const name = property.toLowerCase();
96
+ if (name === "color") return ROLE_PREFIXES.text;
97
+ if (name.startsWith("border")) return ROLE_PREFIXES.border;
98
+ if (name.startsWith("background")) return ROLE_PREFIXES.bg;
99
+ return [];
100
+ }
101
+
102
+ const startsWithAny = (name, prefixes) => prefixes.some((prefix) => name.startsWith(prefix));
103
+
104
+ export function selectColorTokens(names, prefer, rolePrefixes) {
105
+ const prefix = prefer.find((prefix) => names.some((name) => name.startsWith(prefix)));
106
+ if (prefix !== undefined) {
107
+ const preferred = names.filter((name) => name.startsWith(prefix));
108
+ if (preferred.length === 1) return preferred;
109
+ }
110
+
111
+ const matching = names.filter((name) => startsWithAny(name, rolePrefixes));
112
+ return [...matching, ...names.filter((name) => !startsWithAny(name, rolePrefixes))];
113
+ }
114
+
115
+ export function recommendColorCandidate(candidates, rolePrefixes) {
116
+ const matching = candidates.filter((candidate) => startsWithAny(candidate, rolePrefixes));
117
+ return matching.length === 1 ? matching[0] : null;
118
+ }
119
+
120
+ /**
121
+ * Tailwind theme.css 같은 팔레트 CSS 에서 --color-* 의 값을 비교용 표기로 읽는다.
122
+ * sRGB 안의 색은 hex 가 되고, 밖의 oklch 는 oklch 표기로 남아 같은 oklch 값과만 맞는다.
123
+ * @param {string} css
124
+ * @returns {Map<string, string>} 토큰 이름 → 비교용 색 표기
125
+ */
126
+ export function parsePaletteColors(css) {
127
+ const palette = new Map();
128
+ postcss.parse(css).walkDecls(COLOR_TOKEN, (decl) => {
129
+ const color = normalizeColor(decl.value);
130
+ if (color) palette.set(decl.prop, color);
131
+ });
132
+ return palette;
65
133
  }
package/src/format.js CHANGED
@@ -5,13 +5,14 @@ import { messages } from "./messages.js";
5
5
  * @param {Awaited<ReturnType<typeof import("./check.js").check>>} result
6
6
  * @param {"en" | "ko"} [lang]
7
7
  */
8
- export function formatText({ designSystem, problems, summary, violations }, lang) {
8
+ export function formatText({ designSystem, problems, summary, violations, decisions = [], unchecked }, lang) {
9
9
  const m = messages(lang);
10
10
  // 첫 줄은 설정에서 무엇을 읽었는지다. 경로를 잘못 적으면 여기서 0개로 드러난다.
11
11
  const header = [m.designSystem(designSystem), ...problems.map(m.notice), ""];
12
+ const uncheckedLine = unchecked?.colors > 0 ? [m.unchecked(unchecked)] : [];
12
13
 
13
14
  if (violations.length === 0) {
14
- return [...header, m.noViolations(summary), ""].join("\n");
15
+ return [...header, m.noViolations(summary), ...uncheckedLine, ""].join("\n");
15
16
  }
16
17
 
17
18
  const byFile = new Map();
@@ -36,7 +37,8 @@ export function formatText({ designSystem, problems, summary, violations }, lang
36
37
  ...header,
37
38
  ...sections,
38
39
  m.summary(summary),
39
- m.actions({ replace: count("replace"), ask: count("ask"), repair: count("repair") }),
40
+ m.actions({ replace: count("replace"), migrate: count("migrate"), ask: count("ask"), repair: count("repair"), decisions: decisions.length }),
41
+ ...uncheckedLine,
40
42
  "",
41
43
  ].join("\n");
42
44
  }
package/src/hook.js CHANGED
@@ -96,11 +96,7 @@ async function checkHead({ cwd, config, files, lang }) {
96
96
  }
97
97
  if (paths.length === 0) return [];
98
98
 
99
- const baselineConfig = { ...config, tokens: path.resolve(cwd, config.tokens) };
100
- if (config.components) {
101
- baselineConfig.components = { ...config.components, path: path.resolve(cwd, config.components.path) };
102
- }
103
- const result = await check({ cwd: temp, config: baselineConfig, paths, lang });
99
+ const result = await check({ cwd: temp, config, paths, lang, sourceCwd: cwd });
104
100
  return result.violations;
105
101
  } finally {
106
102
  if (temp) fs.rmSync(temp, { recursive: true, force: true });
package/src/messages.js CHANGED
@@ -33,6 +33,8 @@ 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
+ useTokenClassOnly: ({ found, tokens }) =>
37
+ `${found} has the same color as ${tokens}, but that token can only be used as a class: Tailwind makes no CSS variable for it.`,
36
38
  unknownColor: ({ found }) => `The color of ${found} is not in the tokens.`,
37
39
  unknownCssColor: ({ value }) => `The color ${value} is not in the tokens.`,
38
40
  useComponent: ({ tag, component, path }) =>
@@ -50,6 +52,14 @@ const en = {
50
52
  `Node.js ${minimum} or later is required (current version: ${version}).`,
51
53
  tokensSettingMissing: () =>
52
54
  "designsnitch: set settings.designsnitch.tokens to the path of the token CSS file.",
55
+ invalidTokenSetting: ({ field, file }) => {
56
+ const details = {
57
+ "tokens.file": "a non-empty token CSS file path",
58
+ "tokens.exclude": "an array of non-empty token names or patterns with a trailing *",
59
+ "tokens.prefer": "an array of non-empty token name prefixes without wildcards",
60
+ };
61
+ return `"${field}" must be ${details[field]}.${file ? ` (${file})` : ""}`;
62
+ },
53
63
  tokensFileMissing: ({ file }) => `designsnitch: token CSS file not found: ${file}`,
54
64
  tokensUnreadable: ({ file, line, column, reason }) =>
55
65
  `designsnitch: could not read the token CSS: ${file}:${line}:${column} ${reason}`,
@@ -73,37 +83,51 @@ const en = {
73
83
  configBadWhenValues: ({ tag, attribute, file }) =>
74
84
  `"components.replaces.${tag}.when.${attribute}" in the config file must be an array of strings or null values: ${file}`,
75
85
  configBadLang: ({ file }) => `"lang" in the config file must be "en" or "ko": ${file}`,
86
+ configBadPalette: ({ file }) => `"palette" in the config file must be "tailwind": ${file}`,
87
+ tailwindConfigFailed: ({ file, reason }) =>
88
+ `Could not load the Tailwind config ${file}: ${reason}. Colors defined there are not known, so they are reported as "not in the tokens".`,
89
+ paletteMissing: ({ root }) =>
90
+ `The config sets "palette": "tailwind", but tailwindcss could not be found from ${root}. Install the project's dependencies, or remove "palette".`,
76
91
  settingsUnreadable: ({ file }) => `Could not read ${file}. Fix the JSON and run again.`,
77
92
 
78
93
  // check
79
94
  noColorTokens: ({ tokens }) =>
80
95
  `No color token could be read from ${tokens}. ` +
81
- "A --color-* variable is read when its value is a hex color or a var() that leads to one. " +
82
- 'Until then every hex color is reported as "not in the tokens".',
96
+ "A --color-* variable is read when its value is a hex, rgb(), hsl() or oklch() color, or a var() that leads to one. " +
97
+ 'Until then every color written by hand is reported as "not in the tokens".',
83
98
  nextNoTokens: () =>
84
99
  "There are no color tokens, so there is nothing to judge colors against. Before fixing any color, collect the colors in use with `designsnitch colors` and decide the tokens.",
85
100
  nextRepair: (n) => `action "repair" (${n}): fix the syntax error in that file first.`,
86
101
  nextReplace: (n) => `action "replace" (${n}): replace found with the value in candidates.`,
102
+ nextMigrate: (n) =>
103
+ `action "migrate" (${n}): replace the tag with the component in candidates. Read that component first: add the import, pass on the props it accepts, and drop className values it already applies. If it cannot do what the tag did, ask the user instead.`,
87
104
  nextAsk: (n) =>
105
+ `Before making changes, ask the user about the ${count(n, "entry", "entries")} in decisions. Include how often each comes up, the candidates, and the reasons for asking.`,
106
+ hookNextAsk: (n) =>
88
107
  `action "ask" (${n}): do not change these. Ask the user, and include how often and for what each color is used, which \`designsnitch colors\` shows.`,
89
108
  nextRerun: () => "After fixing, run the same command again.",
90
109
  nextNone: () => "No violations.",
91
110
 
92
111
  // 사람용 출력
93
- designSystem: ({ colorTokens, components }) =>
94
- `Design system: ${count(colorTokens, "color token")}, ` +
112
+ designSystem: ({ colorTokens, paletteColors = 0, components }) =>
113
+ `Design system: ${count(colorTokens, "color token")}` +
114
+ (paletteColors > 0 ? ` and the Tailwind palette (${count(paletteColors, "color")})` : "") +
115
+ ", " +
95
116
  (components > 0 ? count(components, "component") : "no components configured"),
96
117
  notice: (problem) => `Note: ${problem}`,
97
118
  severity: { error: "error", warning: "warning" },
98
119
  summary: ({ errors, warnings, files }) =>
99
120
  `${count(errors, "error")}, ${count(warnings, "warning")} (${count(files, "file")} checked)`,
100
- actions: ({ replace, ask, repair }) =>
121
+ actions: ({ replace, migrate = 0, ask, repair, decisions }) =>
101
122
  [
102
123
  `${replace} can be replaced right away`,
103
- `${ask} ${needs(ask)} a person's decision`,
124
+ ...(migrate > 0 ? [`${migrate} to move to a component`] : []),
125
+ `${ask} ${needs(ask)} a person's decision (${count(decisions, "decision")})`,
104
126
  ...(repair > 0 ? [`${repair} ${needs(repair)} a syntax fix`] : []),
105
127
  ].join(", "),
106
128
  noViolations: ({ files }) => `No violations. (${count(files, "file")} checked)`,
129
+ unchecked: ({ colors, files }) =>
130
+ `Not checked: ${count(colors, "color")} in other strings in ${count(files, "file")}, such as theme objects and chart options. \`designsnitch colors\` lists them.`,
107
131
 
108
132
  // colors
109
133
  colorsNone: ({ files }) => `No colors found in the code. (${count(files, "file")} checked)`,
@@ -160,6 +184,8 @@ const ko = {
160
184
  useTokenThemed: ({ found, tokens, candidates }) =>
161
185
  `${found}의 색은 토큰 ${tokens}의 값입니다. 후보: ${candidates}. ` +
162
186
  "후보 중 테마마다 값이 다른 토큰이 있어 그 토큰으로 바꾸면 다른 테마에서 색이 바뀔 수 있습니다.",
187
+ useTokenClassOnly: ({ found, tokens }) =>
188
+ `${found}의 색은 토큰 ${tokens}의 값이지만, 이 토큰은 클래스로만 쓸 수 있습니다. Tailwind가 CSS 변수를 만들지 않습니다.`,
163
189
  unknownColor: ({ found }) => `${found}의 색은 토큰에 없습니다.`,
164
190
  unknownCssColor: ({ value }) => `${value}의 색은 토큰에 없습니다.`,
165
191
  useComponent: ({ tag, component, path }) =>
@@ -176,6 +202,14 @@ const ko = {
176
202
  `Node.js ${minimum} 이상이 필요합니다(현재 버전: ${version}).`,
177
203
  tokensSettingMissing: () =>
178
204
  "designsnitch: settings.designsnitch.tokens 에 토큰 CSS 파일 경로를 설정하세요.",
205
+ invalidTokenSetting: ({ field, file }) => {
206
+ const details = {
207
+ "tokens.file": "비어 있지 않은 토큰 CSS 파일 경로를 입력하세요",
208
+ "tokens.exclude": "비어 있지 않은 토큰 이름이나 끝에 *가 있는 패턴을 배열로 입력하세요",
209
+ "tokens.prefer": "와일드카드가 없는 토큰 이름 접두어를 배열로 입력하세요",
210
+ };
211
+ return `"${field}"에 ${details[field]}.${file ? ` (${file})` : ""}`;
212
+ },
179
213
  tokensFileMissing: ({ file }) => `designsnitch: 토큰 CSS 파일을 찾을 수 없습니다: ${file}`,
180
214
  tokensUnreadable: ({ file, line, column, reason }) =>
181
215
  `designsnitch: 토큰 CSS를 읽을 수 없습니다: ${file}:${line}:${column} ${reason}`,
@@ -198,35 +232,49 @@ const ko = {
198
232
  configBadWhenValues: ({ tag, attribute, file }) =>
199
233
  `설정 파일의 "components.replaces.${tag}.when.${attribute}"는 문자열 또는 null을 담은 배열이어야 합니다: ${file}`,
200
234
  configBadLang: ({ file }) => `설정 파일의 "lang"은 "en"이나 "ko"여야 합니다: ${file}`,
235
+ configBadPalette: ({ file }) => `설정 파일의 "palette"는 "tailwind"여야 합니다: ${file}`,
236
+ tailwindConfigFailed: ({ file, reason }) =>
237
+ `Tailwind 설정을 불러오지 못했습니다: ${file}: ${reason}. 거기에 정의된 색을 알 수 없어서 "토큰에 없음"으로 나옵니다.`,
238
+ paletteMissing: ({ root }) =>
239
+ `설정에 "palette": "tailwind"가 있지만 ${root}에서 tailwindcss를 찾지 못했습니다. 프로젝트의 의존성을 설치하거나 "palette"를 지우세요.`,
201
240
  settingsUnreadable: ({ file }) => `${file} 을 읽을 수 없습니다. JSON 형식을 고친 뒤 다시 실행하세요.`,
202
241
 
203
242
  noColorTokens: ({ tokens }) =>
204
243
  `색 토큰을 하나도 읽지 못했습니다: ${tokens}. ` +
205
- "--color-* 변수의 값이 hex이거나 var()로 hex를 가리켜야 읽을 수 있습니다. " +
206
- '지금은 모든 hex가 "토큰에 없음" 경고로 나옵니다.',
244
+ "--color-* 변수의 값이 hex, rgb(), hsl(), oklch() 색이거나, var()로 그런 값을 가리켜야 읽을 수 있습니다. " +
245
+ '지금은 직접 쓴 색이 모두 "토큰에 없음" 경고로 나옵니다.',
207
246
  nextNoTokens: () =>
208
247
  "색 토큰이 없어서 색을 판정할 기준이 없습니다. 색을 고치기 전에 `designsnitch colors`로 쓰이는 색을 모아 토큰부터 정하세요.",
209
248
  nextRepair: (n) => `action이 repair인 ${n}건은 그 파일의 문법 오류부터 고치세요.`,
210
249
  nextReplace: (n) => `action이 replace인 ${n}건은 found를 candidates의 값으로 바꾸세요.`,
250
+ nextMigrate: (n) =>
251
+ `action이 migrate인 ${n}건은 태그를 candidates의 컴포넌트로 바꾸세요. 먼저 그 컴포넌트를 읽고, import를 더하고, 컴포넌트가 받는 props를 넘기고, 컴포넌트가 이미 주는 className은 지우세요. 태그가 하던 일을 컴포넌트가 못 하면 바꾸지 말고 사용자에게 물으세요.`,
211
252
  nextAsk: (n) =>
253
+ `변경하기 전에 decisions의 ${n}건을 사용자에게 물으세요. 사용 횟수와 후보, 확인이 필요한 이유를 함께 알려 주세요.`,
254
+ hookNextAsk: (n) =>
212
255
  `action이 ask인 ${n}건은 바꾸지 말고 사용자에게 물으세요. 물을 때는 \`designsnitch colors\`로 그 색이 몇 곳에서 어떻게 쓰이는지 확인해서 근거로 함께 주세요.`,
213
256
  nextRerun: () => "고친 뒤 같은 명령을 다시 실행하세요.",
214
257
  nextNone: () => "위반이 없습니다.",
215
258
 
216
- designSystem: ({ colorTokens, components }) =>
217
- `디자인 시스템: 색 토큰 ${colorTokens}개, ` +
259
+ designSystem: ({ colorTokens, paletteColors = 0, components }) =>
260
+ `디자인 시스템: 색 토큰 ${colorTokens}개` +
261
+ (paletteColors > 0 ? `와 Tailwind 기본 팔레트(색 ${paletteColors}개)` : "") +
262
+ ", " +
218
263
  (components > 0 ? `컴포넌트 ${components}개` : "컴포넌트 설정 없음"),
219
264
  notice: (problem) => `주의: ${problem}`,
220
265
  severity: { error: "오류", warning: "경고" },
221
266
  summary: ({ errors, warnings, files }) =>
222
267
  `오류 ${errors}개, 경고 ${warnings}개 (파일 ${files}개 검사)`,
223
- actions: ({ replace, ask, repair }) =>
268
+ actions: ({ replace, migrate = 0, ask, repair, decisions }) =>
224
269
  [
225
270
  `바로 바꿀 수 있는 것 ${replace}건`,
226
- `사람이 정해야 하는 것 ${ask}건`,
271
+ ...(migrate > 0 ? [`컴포넌트로 옮길 것 ${migrate}건`] : []),
272
+ `사람이 정해야 하는 것 ${ask}건 (결정 ${decisions}개)`,
227
273
  ...(repair > 0 ? [`문법을 고쳐야 하는 것 ${repair}건`] : []),
228
274
  ].join(", "),
229
275
  noViolations: ({ files }) => `위반이 없습니다. (파일 ${files}개 검사)`,
276
+ unchecked: ({ colors, files }) =>
277
+ `검사하지 못함: 테마 객체나 차트 옵션 같은 다른 문자열에 색 ${colors}개 (파일 ${files}개). \`designsnitch colors\`로 볼 수 있습니다.`,
230
278
 
231
279
  colorsNone: ({ files }) => `코드에서 색을 찾지 못했습니다. (파일 ${files}개 검사)`,
232
280
  colorsSummary: ({ colors, paletteColors, uses, files }) =>