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/README.ko.md +58 -23
- package/README.md +58 -23
- package/package.json +1 -1
- package/skills/designsnitch-check/SKILL.md +9 -8
- package/skills/designsnitch-palette/SKILL.md +3 -3
- package/skills/designsnitch-setup/SKILL.md +10 -7
- package/src/check.js +66 -34
- package/src/cli.js +3 -4
- package/src/colors.js +16 -13
- package/src/config.js +1 -0
- package/src/core/classes.js +13 -21
- package/src/core/color.js +133 -9
- package/src/core/css.js +38 -10
- package/src/core/named-colors.js +35 -0
- package/src/core/oklch.js +58 -0
- package/src/core/tokens.js +34 -5
- package/src/format.js +2 -2
- package/src/messages.js +38 -14
- package/src/rules/color-unknown.js +2 -2
- package/src/rules/color-use-token.js +15 -8
- package/src/rules/load-tokens.js +195 -12
- package/src/rules/tailwind-config.js +77 -0
- package/src/rules/{unchecked-hex.js → unchecked-colors.js} +5 -4
- package/src/rules/visit-style.js +10 -3
|
@@ -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
|
+
}
|
package/src/core/tokens.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import postcss from "postcss";
|
|
2
|
-
import {
|
|
2
|
+
import { normalizeColor } from "./color.js";
|
|
3
3
|
|
|
4
4
|
const COLOR_TOKEN = /^--color-/;
|
|
5
5
|
const ROLE_PREFIXES = {
|
|
@@ -26,7 +26,8 @@ export function parseColorTokens(css) {
|
|
|
26
26
|
* 색 값 → 토큰 표와 서로 다른 최종 값이 있는 토큰 이름을 함께 읽는다.
|
|
27
27
|
* @param {string} css
|
|
28
28
|
* @param {string[]} [exclude] 정확한 이름 또는 끝에 *가 붙은 이름 패턴
|
|
29
|
-
* @returns {{ colors: Map<string, string[]>, themed: Set<string
|
|
29
|
+
* @returns {{ colors: Map<string, string[]>, themed: Set<string>, names: Set<string>, resets: string[] }}
|
|
30
|
+
* names 는 값을 읽었든 못 읽었든 선언된 --color-* 이름, resets 는 initial 로 비운 네임스페이스(예: "--color-*")
|
|
30
31
|
*/
|
|
31
32
|
export function parseColorTokenData(css, exclude = []) {
|
|
32
33
|
/** @type {Map<string, string[]>} 변수 이름 → 선언된 값들 */
|
|
@@ -52,13 +53,21 @@ export function parseColorTokenData(css, exclude = []) {
|
|
|
52
53
|
|
|
53
54
|
const colors = new Map();
|
|
54
55
|
const themed = new Set();
|
|
56
|
+
const names = new Set();
|
|
57
|
+
const resets = [];
|
|
55
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
|
+
}
|
|
56
64
|
if (!COLOR_TOKEN.test(name)) continue;
|
|
65
|
+
names.add(name);
|
|
57
66
|
if (exclude.some((pattern) => pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern)) continue;
|
|
58
67
|
const resolved = new Set();
|
|
59
68
|
for (const value of values.flatMap((value) => resolve(value, new Set([name])))) {
|
|
60
|
-
const color =
|
|
61
|
-
//
|
|
69
|
+
const color = normalizeColor(value);
|
|
70
|
+
// 색으로 읽지 못한 값도 테마 차이는 만들 수 있지만 색 후보로는 쓰지 않는다.
|
|
62
71
|
const key = color ?? value;
|
|
63
72
|
if (resolved.has(key)) continue;
|
|
64
73
|
resolved.add(key);
|
|
@@ -68,7 +77,12 @@ export function parseColorTokenData(css, exclude = []) {
|
|
|
68
77
|
}
|
|
69
78
|
if (resolved.size > 1) themed.add(name);
|
|
70
79
|
}
|
|
71
|
-
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})`;
|
|
72
86
|
}
|
|
73
87
|
|
|
74
88
|
export function utilityColorPrefixes(utility) {
|
|
@@ -102,3 +116,18 @@ export function recommendColorCandidate(candidates, rolePrefixes) {
|
|
|
102
116
|
const matching = candidates.filter((candidate) => startsWithAny(candidate, rolePrefixes));
|
|
103
117
|
return matching.length === 1 ? matching[0] : null;
|
|
104
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;
|
|
133
|
+
}
|
package/src/format.js
CHANGED
|
@@ -9,7 +9,7 @@ export function formatText({ designSystem, problems, summary, violations, decisi
|
|
|
9
9
|
const m = messages(lang);
|
|
10
10
|
// 첫 줄은 설정에서 무엇을 읽었는지다. 경로를 잘못 적으면 여기서 0개로 드러난다.
|
|
11
11
|
const header = [m.designSystem(designSystem), ...problems.map(m.notice), ""];
|
|
12
|
-
const uncheckedLine = unchecked?.
|
|
12
|
+
const uncheckedLine = unchecked?.colors > 0 ? [m.unchecked(unchecked)] : [];
|
|
13
13
|
|
|
14
14
|
if (violations.length === 0) {
|
|
15
15
|
return [...header, m.noViolations(summary), ...uncheckedLine, ""].join("\n");
|
|
@@ -37,7 +37,7 @@ export function formatText({ designSystem, problems, summary, violations, decisi
|
|
|
37
37
|
...header,
|
|
38
38
|
...sections,
|
|
39
39
|
m.summary(summary),
|
|
40
|
-
m.actions({ replace: count("replace"), ask: count("ask"), repair: count("repair"), decisions: decisions.length }),
|
|
40
|
+
m.actions({ replace: count("replace"), migrate: count("migrate"), ask: count("ask"), repair: count("repair"), decisions: decisions.length }),
|
|
41
41
|
...uncheckedLine,
|
|
42
42
|
"",
|
|
43
43
|
].join("\n");
|
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 }) =>
|
|
@@ -81,17 +83,24 @@ const en = {
|
|
|
81
83
|
configBadWhenValues: ({ tag, attribute, file }) =>
|
|
82
84
|
`"components.replaces.${tag}.when.${attribute}" in the config file must be an array of strings or null values: ${file}`,
|
|
83
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".`,
|
|
84
91
|
settingsUnreadable: ({ file }) => `Could not read ${file}. Fix the JSON and run again.`,
|
|
85
92
|
|
|
86
93
|
// check
|
|
87
94
|
noColorTokens: ({ tokens }) =>
|
|
88
95
|
`No color token could be read from ${tokens}. ` +
|
|
89
|
-
"A --color-* variable is read when its value is a hex color or a var() that leads to one. " +
|
|
90
|
-
'Until then every
|
|
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".',
|
|
91
98
|
nextNoTokens: () =>
|
|
92
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.",
|
|
93
100
|
nextRepair: (n) => `action "repair" (${n}): fix the syntax error in that file first.`,
|
|
94
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.`,
|
|
95
104
|
nextAsk: (n) =>
|
|
96
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.`,
|
|
97
106
|
hookNextAsk: (n) =>
|
|
@@ -100,22 +109,25 @@ const en = {
|
|
|
100
109
|
nextNone: () => "No violations.",
|
|
101
110
|
|
|
102
111
|
// 사람용 출력
|
|
103
|
-
designSystem: ({ colorTokens, components }) =>
|
|
104
|
-
`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
|
+
", " +
|
|
105
116
|
(components > 0 ? count(components, "component") : "no components configured"),
|
|
106
117
|
notice: (problem) => `Note: ${problem}`,
|
|
107
118
|
severity: { error: "error", warning: "warning" },
|
|
108
119
|
summary: ({ errors, warnings, files }) =>
|
|
109
120
|
`${count(errors, "error")}, ${count(warnings, "warning")} (${count(files, "file")} checked)`,
|
|
110
|
-
actions: ({ replace, ask, repair, decisions }) =>
|
|
121
|
+
actions: ({ replace, migrate = 0, ask, repair, decisions }) =>
|
|
111
122
|
[
|
|
112
123
|
`${replace} can be replaced right away`,
|
|
124
|
+
...(migrate > 0 ? [`${migrate} to move to a component`] : []),
|
|
113
125
|
`${ask} ${needs(ask)} a person's decision (${count(decisions, "decision")})`,
|
|
114
126
|
...(repair > 0 ? [`${repair} ${needs(repair)} a syntax fix`] : []),
|
|
115
127
|
].join(", "),
|
|
116
128
|
noViolations: ({ files }) => `No violations. (${count(files, "file")} checked)`,
|
|
117
|
-
unchecked: ({
|
|
118
|
-
`Not checked: ${count(
|
|
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.`,
|
|
119
131
|
|
|
120
132
|
// colors
|
|
121
133
|
colorsNone: ({ files }) => `No colors found in the code. (${count(files, "file")} checked)`,
|
|
@@ -172,6 +184,8 @@ const ko = {
|
|
|
172
184
|
useTokenThemed: ({ found, tokens, candidates }) =>
|
|
173
185
|
`${found}의 색은 토큰 ${tokens}의 값입니다. 후보: ${candidates}. ` +
|
|
174
186
|
"후보 중 테마마다 값이 다른 토큰이 있어 그 토큰으로 바꾸면 다른 테마에서 색이 바뀔 수 있습니다.",
|
|
187
|
+
useTokenClassOnly: ({ found, tokens }) =>
|
|
188
|
+
`${found}의 색은 토큰 ${tokens}의 값이지만, 이 토큰은 클래스로만 쓸 수 있습니다. Tailwind가 CSS 변수를 만들지 않습니다.`,
|
|
175
189
|
unknownColor: ({ found }) => `${found}의 색은 토큰에 없습니다.`,
|
|
176
190
|
unknownCssColor: ({ value }) => `${value}의 색은 토큰에 없습니다.`,
|
|
177
191
|
useComponent: ({ tag, component, path }) =>
|
|
@@ -218,16 +232,23 @@ const ko = {
|
|
|
218
232
|
configBadWhenValues: ({ tag, attribute, file }) =>
|
|
219
233
|
`설정 파일의 "components.replaces.${tag}.when.${attribute}"는 문자열 또는 null을 담은 배열이어야 합니다: ${file}`,
|
|
220
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"를 지우세요.`,
|
|
221
240
|
settingsUnreadable: ({ file }) => `${file} 을 읽을 수 없습니다. JSON 형식을 고친 뒤 다시 실행하세요.`,
|
|
222
241
|
|
|
223
242
|
noColorTokens: ({ tokens }) =>
|
|
224
243
|
`색 토큰을 하나도 읽지 못했습니다: ${tokens}. ` +
|
|
225
|
-
"--color-* 변수의 값이 hex
|
|
226
|
-
'지금은
|
|
244
|
+
"--color-* 변수의 값이 hex, rgb(), hsl(), oklch() 색이거나, var()로 그런 값을 가리켜야 읽을 수 있습니다. " +
|
|
245
|
+
'지금은 직접 쓴 색이 모두 "토큰에 없음" 경고로 나옵니다.',
|
|
227
246
|
nextNoTokens: () =>
|
|
228
247
|
"색 토큰이 없어서 색을 판정할 기준이 없습니다. 색을 고치기 전에 `designsnitch colors`로 쓰이는 색을 모아 토큰부터 정하세요.",
|
|
229
248
|
nextRepair: (n) => `action이 repair인 ${n}건은 그 파일의 문법 오류부터 고치세요.`,
|
|
230
249
|
nextReplace: (n) => `action이 replace인 ${n}건은 found를 candidates의 값으로 바꾸세요.`,
|
|
250
|
+
nextMigrate: (n) =>
|
|
251
|
+
`action이 migrate인 ${n}건은 태그를 candidates의 컴포넌트로 바꾸세요. 먼저 그 컴포넌트를 읽고, import를 더하고, 컴포넌트가 받는 props를 넘기고, 컴포넌트가 이미 주는 className은 지우세요. 태그가 하던 일을 컴포넌트가 못 하면 바꾸지 말고 사용자에게 물으세요.`,
|
|
231
252
|
nextAsk: (n) =>
|
|
232
253
|
`변경하기 전에 decisions의 ${n}건을 사용자에게 물으세요. 사용 횟수와 후보, 확인이 필요한 이유를 함께 알려 주세요.`,
|
|
233
254
|
hookNextAsk: (n) =>
|
|
@@ -235,22 +256,25 @@ const ko = {
|
|
|
235
256
|
nextRerun: () => "고친 뒤 같은 명령을 다시 실행하세요.",
|
|
236
257
|
nextNone: () => "위반이 없습니다.",
|
|
237
258
|
|
|
238
|
-
designSystem: ({ colorTokens, components }) =>
|
|
239
|
-
`디자인 시스템: 색 토큰 ${colorTokens}
|
|
259
|
+
designSystem: ({ colorTokens, paletteColors = 0, components }) =>
|
|
260
|
+
`디자인 시스템: 색 토큰 ${colorTokens}개` +
|
|
261
|
+
(paletteColors > 0 ? `와 Tailwind 기본 팔레트(색 ${paletteColors}개)` : "") +
|
|
262
|
+
", " +
|
|
240
263
|
(components > 0 ? `컴포넌트 ${components}개` : "컴포넌트 설정 없음"),
|
|
241
264
|
notice: (problem) => `주의: ${problem}`,
|
|
242
265
|
severity: { error: "오류", warning: "경고" },
|
|
243
266
|
summary: ({ errors, warnings, files }) =>
|
|
244
267
|
`오류 ${errors}개, 경고 ${warnings}개 (파일 ${files}개 검사)`,
|
|
245
|
-
actions: ({ replace, ask, repair, decisions }) =>
|
|
268
|
+
actions: ({ replace, migrate = 0, ask, repair, decisions }) =>
|
|
246
269
|
[
|
|
247
270
|
`바로 바꿀 수 있는 것 ${replace}건`,
|
|
271
|
+
...(migrate > 0 ? [`컴포넌트로 옮길 것 ${migrate}건`] : []),
|
|
248
272
|
`사람이 정해야 하는 것 ${ask}건 (결정 ${decisions}개)`,
|
|
249
273
|
...(repair > 0 ? [`문법을 고쳐야 하는 것 ${repair}건`] : []),
|
|
250
274
|
].join(", "),
|
|
251
275
|
noViolations: ({ files }) => `위반이 없습니다. (파일 ${files}개 검사)`,
|
|
252
|
-
unchecked: ({
|
|
253
|
-
`검사하지 못함: 테마 객체나 차트 옵션 같은 다른 문자열에
|
|
276
|
+
unchecked: ({ colors, files }) =>
|
|
277
|
+
`검사하지 못함: 테마 객체나 차트 옵션 같은 다른 문자열에 색 ${colors}개 (파일 ${files}개). \`designsnitch colors\`로 볼 수 있습니다.`,
|
|
254
278
|
|
|
255
279
|
colorsNone: ({ files }) => `코드에서 색을 찾지 못했습니다. (파일 ${files}개 검사)`,
|
|
256
280
|
colorsSummary: ({ colors, paletteColors, uses, files }) =>
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { findArbitraryColors } from "../core/classes.js";
|
|
2
|
-
import {
|
|
2
|
+
import { normalizeColor } from "../core/color.js";
|
|
3
3
|
import { loadTokens } from "./load-tokens.js";
|
|
4
4
|
import { ruleMessages, TEXT } from "./suggest.js";
|
|
5
5
|
import { visitStrings } from "./visit-strings.js";
|
|
@@ -25,7 +25,7 @@ export default {
|
|
|
25
25
|
const { colors } = tokens;
|
|
26
26
|
|
|
27
27
|
function report(found, { loc }) {
|
|
28
|
-
if (colors.has(
|
|
28
|
+
if (colors.has(normalizeColor(found.value))) return;
|
|
29
29
|
context.report({ loc, messageId: "unknown", data: { text: m.unknownColor({ found: found.text }) } });
|
|
30
30
|
}
|
|
31
31
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { findArbitraryColors, tokenToClass } from "../core/classes.js";
|
|
2
|
-
import {
|
|
3
|
-
import { cssColorPrefixes, selectColorTokens, utilityColorPrefixes } from "../core/tokens.js";
|
|
2
|
+
import { normalizeColor } from "../core/color.js";
|
|
3
|
+
import { cssColorPrefixes, selectColorTokens, tokenVar, utilityColorPrefixes } from "../core/tokens.js";
|
|
4
4
|
import { loadTokens } from "./load-tokens.js";
|
|
5
5
|
import { ruleMessages, suggestClasses, TEXT } from "./suggest.js";
|
|
6
6
|
import { visitStrings } from "./visit-strings.js";
|
|
@@ -13,7 +13,7 @@ export default {
|
|
|
13
13
|
docs: { description: "Use the token instead of writing its color as a hex value" },
|
|
14
14
|
hasSuggestions: true,
|
|
15
15
|
schema: [],
|
|
16
|
-
messages: { useToken: TEXT, useTokenThemed: TEXT, replace: TEXT, tokensConfig: TEXT },
|
|
16
|
+
messages: { useToken: TEXT, useTokenThemed: TEXT, useTokenClassOnly: TEXT, replace: TEXT, tokensConfig: TEXT },
|
|
17
17
|
},
|
|
18
18
|
create(context) {
|
|
19
19
|
let tokens;
|
|
@@ -27,7 +27,7 @@ export default {
|
|
|
27
27
|
};
|
|
28
28
|
}
|
|
29
29
|
const m = ruleMessages(context);
|
|
30
|
-
const { colors, themed, prefer } = tokens;
|
|
30
|
+
const { colors, themed, prefer, classOnly } = tokens;
|
|
31
31
|
|
|
32
32
|
function report(found, { loc, range }, tokenNames, candidates) {
|
|
33
33
|
const messageId = tokenNames.some((name) => themed.has(name)) ? "useTokenThemed" : "useToken";
|
|
@@ -43,17 +43,24 @@ export default {
|
|
|
43
43
|
|
|
44
44
|
return mergeVisitors(
|
|
45
45
|
visitStrings(context, findArbitraryColors, (found, where) => {
|
|
46
|
-
const names = colors.get(
|
|
46
|
+
const names = colors.get(normalizeColor(found.value));
|
|
47
47
|
if (!names) return;
|
|
48
48
|
const tokenNames = selectColorTokens(names, prefer, utilityColorPrefixes(found.utility));
|
|
49
49
|
report(found, where, tokenNames, tokenNames.map((name) => tokenToClass(found.utility, name)));
|
|
50
50
|
}),
|
|
51
51
|
// 인라인 스타일은 클래스가 아니라 var(--토큰) 으로 바꾼다. Tailwind 는 소스에서 쓴 var() 의 변수를 내보낸다.
|
|
52
52
|
visitInlineStyleColors(context, (found, where) => {
|
|
53
|
-
const
|
|
54
|
-
if (!
|
|
53
|
+
const known = colors.get(normalizeColor(found.value));
|
|
54
|
+
if (!known) return;
|
|
55
|
+
// 클래스로만 쓸 수 있는 토큰은 스타일 값을 대신할 수 없다. 그래도 직접 쓴 색이라는 것은 알린다.
|
|
56
|
+
const names = known.filter((name) => !classOnly.has(name));
|
|
57
|
+
if (names.length === 0) {
|
|
58
|
+
const text = m.useTokenClassOnly({ found: found.text, tokens: known.join(", ") });
|
|
59
|
+
context.report({ loc: where.loc, messageId: "useTokenClassOnly", data: { text } });
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
55
62
|
const tokenNames = selectColorTokens(names, prefer, cssColorPrefixes(found.property));
|
|
56
|
-
report(found, where, tokenNames, tokenNames.map((name) =>
|
|
63
|
+
report(found, where, tokenNames, tokenNames.map((name) => tokenVar(name, tokens.prefix)));
|
|
57
64
|
}),
|
|
58
65
|
);
|
|
59
66
|
},
|
package/src/rules/load-tokens.js
CHANGED
|
@@ -1,18 +1,30 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
2
3
|
import path from "node:path";
|
|
4
|
+
import postcss from "postcss";
|
|
3
5
|
import { invalidTokenField, tokenSettings } from "../config.js";
|
|
4
|
-
import { parseColorTokenData } from "../core/tokens.js";
|
|
6
|
+
import { parseColorTokenData, parsePaletteColors } from "../core/tokens.js";
|
|
5
7
|
import { messages, resolveLang } from "../messages.js";
|
|
8
|
+
import { flattenColors, loadConfigColors } from "./tailwind-config.js";
|
|
6
9
|
|
|
7
10
|
/**
|
|
8
11
|
* @typedef {object} Tokens
|
|
9
12
|
* @property {Map<string, string[]>} colors 색 값 → 토큰 이름들
|
|
10
13
|
* @property {Set<string>} themed 테마마다 값이 다른 토큰 이름들
|
|
11
14
|
* @property {string[]} prefer 먼저 적용할 토큰 접두어
|
|
15
|
+
* @property {Set<string>} paletteNames 기본 팔레트에서 온 토큰 이름들. palette 설정이 없으면 비어 있다
|
|
16
|
+
* @property {Set<string>} files 토큰을 읽은 파일들의 절대 경로. 토큰 CSS, 그것이 @import 한 CSS, Tailwind JavaScript 설정
|
|
17
|
+
* @property {string | null} prefix Tailwind 접두어. @import "tailwindcss" prefix(tw) 의 tw
|
|
18
|
+
* @property {Set<string>} classOnly 클래스로만 쓸 수 있는 토큰 이름들. JavaScript 설정의 색에는 CSS 변수가 없다
|
|
19
|
+
* @property {string[]} problems 토큰을 다 읽지 못하게 만든 문제. 예: 불러오지 못한 JavaScript 설정
|
|
12
20
|
*/
|
|
13
21
|
|
|
14
|
-
/** @
|
|
22
|
+
/** @typedef {ReturnType<typeof parseColorTokenData> & Pick<Tokens, "files" | "prefix" | "classOnly" | "problems">} ProjectTokens */
|
|
23
|
+
|
|
24
|
+
/** @type {Map<string, { deps: [string, number][], tokens: ProjectTokens }>} */
|
|
15
25
|
const cache = new Map();
|
|
26
|
+
/** @type {Map<string, { mtimeMs: number, result: { palette: Map<string, string>, classOnly: boolean } }>} */
|
|
27
|
+
const paletteCache = new Map();
|
|
16
28
|
|
|
17
29
|
/**
|
|
18
30
|
* settings.designsnitch.tokens 에 적힌 CSS를 읽어 토큰을 돌려준다.
|
|
@@ -27,28 +39,199 @@ export function loadTokens(settings, cwd) {
|
|
|
27
39
|
if (invalidField) throw new Error(m.invalidTokenSetting({ field: invalidField }));
|
|
28
40
|
|
|
29
41
|
const { file: tokensPath, exclude = [], prefer = [] } = tokenSettings(tokens);
|
|
30
|
-
const
|
|
42
|
+
const root = path.resolve(cwd, settings?.designsnitch?.root ?? ".");
|
|
43
|
+
const file = path.resolve(root, tokensPath);
|
|
44
|
+
const project = readProjectTokens(file, root, exclude, m);
|
|
45
|
+
const { files, prefix, classOnly, problems } = project;
|
|
46
|
+
const shared = { prefer, files, prefix, classOnly, problems };
|
|
47
|
+
if (settings?.designsnitch?.palette !== "tailwind") {
|
|
48
|
+
return { colors: project.colors, themed: project.themed, paletteNames: new Set(), ...shared };
|
|
49
|
+
}
|
|
50
|
+
return { ...shared, ...withPalette(project, readTailwindPalette(file, m), exclude) };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** @returns {ProjectTokens} */
|
|
54
|
+
function readProjectTokens(file, root, exclude, m) {
|
|
31
55
|
const key = JSON.stringify([file, exclude]);
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const cached = cache.get(key);
|
|
35
|
-
if (cached?.mtimeMs === mtimeMs) return { ...cached.tokens, prefer };
|
|
56
|
+
const cached = cache.get(key);
|
|
57
|
+
if (cached && cached.deps.every(([dep, mtimeMs]) => mtimeOf(dep) === mtimeMs)) return cached.tokens;
|
|
36
58
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
59
|
+
// tokens 에 tailwind.config.js 같은 JavaScript 설정을 직접 적은 경우. Tailwind v3 프로젝트가 그렇다.
|
|
60
|
+
const isConfig = JS_FILE.test(file);
|
|
61
|
+
const sources = [];
|
|
62
|
+
const configFiles = isConfig ? [file] : [];
|
|
63
|
+
let prefix = null;
|
|
64
|
+
let usesV3Directives = false;
|
|
65
|
+
let current = file;
|
|
66
|
+
try {
|
|
67
|
+
if (isConfig && !fs.existsSync(file)) throw Object.assign(new Error("missing"), { code: "ENOENT" });
|
|
68
|
+
// 토큰 CSS 가 @import 한 CSS 도 토큰을 정의할 수 있다. 예: @import "../brand/theme.css"
|
|
69
|
+
const visit = (cssFile) => {
|
|
70
|
+
if (sources.some(([seen]) => seen === cssFile)) return;
|
|
71
|
+
current = cssFile;
|
|
72
|
+
const css = fs.readFileSync(cssFile, "utf8");
|
|
73
|
+
const entry = [cssFile, css];
|
|
74
|
+
sources.push(entry);
|
|
75
|
+
const sheet = postcss.parse(css, { from: cssFile });
|
|
76
|
+
sheet.walkAtRules("tailwind", () => {
|
|
77
|
+
usesV3Directives = true;
|
|
78
|
+
});
|
|
79
|
+
sheet.walkAtRules("config", (rule) => {
|
|
80
|
+
const spec = /^["']([^"']+)["']/.exec(rule.params)?.[1];
|
|
81
|
+
if (spec) configFiles.push(path.resolve(path.dirname(cssFile), spec));
|
|
82
|
+
});
|
|
83
|
+
sheet.walkAtRules("import", (rule) => {
|
|
84
|
+
const spec = /^(?:url\(\s*)?["']([^"']+)["']/.exec(rule.params)?.[1];
|
|
85
|
+
if (!spec) return;
|
|
86
|
+
if (spec === "tailwindcss") {
|
|
87
|
+
prefix = /\bprefix\(\s*([\w-]+)\s*\)/.exec(rule.params)?.[1] ?? prefix;
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
// Tailwind 자신의 CSS 는 palette 설정이 맡는다.
|
|
91
|
+
if (spec.startsWith("tailwindcss/") || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(spec)) return;
|
|
92
|
+
const imported = resolveImport(cssFile, spec);
|
|
93
|
+
if (imported) visit(imported);
|
|
94
|
+
});
|
|
95
|
+
current = cssFile;
|
|
96
|
+
};
|
|
97
|
+
if (!isConfig) visit(file);
|
|
40
98
|
} catch (error) {
|
|
41
99
|
if (error.code === "ENOENT" || error.code === "ENOTDIR") {
|
|
42
|
-
throw new Error(m.tokensFileMissing({ file }));
|
|
100
|
+
throw new Error(m.tokensFileMissing({ file: current }));
|
|
43
101
|
}
|
|
44
102
|
// 기준이 되는 파일이 깨져 있으면 무엇도 판정할 수 없다. 어디가 깨졌는지 알려준다.
|
|
45
103
|
throw new Error(
|
|
46
104
|
m.tokensUnreadable({
|
|
47
|
-
file,
|
|
105
|
+
file: current,
|
|
48
106
|
line: error.line ?? 1,
|
|
49
107
|
column: error.column ?? 1,
|
|
50
108
|
reason: error.reason ?? error.message,
|
|
51
109
|
}),
|
|
52
110
|
);
|
|
53
111
|
}
|
|
112
|
+
|
|
113
|
+
// Tailwind v3 는 @config 없이 프로젝트 루트의 tailwind.config 를 읽는다. @tailwind 지시어가 v3 의 표시다.
|
|
114
|
+
if (usesV3Directives && configFiles.length === 0) {
|
|
115
|
+
const found = V3_CONFIG_NAMES.map((name) => path.join(root, name)).find((candidate) => fs.existsSync(candidate));
|
|
116
|
+
if (found) configFiles.push(found);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// import 된 파일의 선언이 먼저 오도록 뒤집어 합친다. 순서는 결과에 영향을 주지 않지만 읽기 쉽다.
|
|
120
|
+
const parsed = parseColorTokenData(sources.map(([, css]) => css).reverse().join("\n"), exclude);
|
|
121
|
+
const { classOnly, problems } = addConfigColors(parsed, configFiles, exclude, m);
|
|
122
|
+
// 기준으로 적은 설정을 못 읽으면 판정할 것이 없다. @config 로 딸려 온 설정이면 알리기만 하고 계속한다.
|
|
123
|
+
if (isConfig && problems.length > 0) throw new Error(problems[0]);
|
|
124
|
+
// 링크된 경로로 들어와도 같은 파일로 알아보도록 실제 경로로 적어 둔다.
|
|
125
|
+
const deps = [...sources.map(([cssFile]) => cssFile), ...configFiles];
|
|
126
|
+
const files = new Set(deps.filter((dep) => fs.existsSync(dep)).map((dep) => fs.realpathSync(dep)));
|
|
127
|
+
const tokens = { ...parsed, files, prefix, classOnly, problems };
|
|
128
|
+
cache.set(key, { deps: deps.map((dep) => [dep, mtimeOf(dep)]), tokens });
|
|
129
|
+
return tokens;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const JS_FILE = /\.[cm]?[jt]s$/;
|
|
133
|
+
const V3_CONFIG_NAMES = ["tailwind.config.js", "tailwind.config.cjs", "tailwind.config.mjs", "tailwind.config.ts"];
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* @config 로 불러온 JavaScript 설정의 색을 CSS 에서 읽은 토큰에 더한다. 같은 이름이면 CSS 가 이긴다.
|
|
137
|
+
* @param {ReturnType<typeof parseColorTokenData>} parsed 여기에 더한다
|
|
138
|
+
*/
|
|
139
|
+
function addConfigColors(parsed, configFiles, exclude, m) {
|
|
140
|
+
const classOnly = new Set();
|
|
141
|
+
const problems = [];
|
|
142
|
+
const excluded = (name) => exclude.some((p) => (p.endsWith("*") ? name.startsWith(p.slice(0, -1)) : name === p));
|
|
143
|
+
for (const file of configFiles) {
|
|
144
|
+
let config;
|
|
145
|
+
try {
|
|
146
|
+
config = loadConfigColors(file);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
problems.push(m.tailwindConfigFailed({ file, reason: error.message.split("\n")[0] }));
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (config.replacesPalette) parsed.resets.push("--color-*");
|
|
152
|
+
for (const [name, color] of config.colors) {
|
|
153
|
+
if (parsed.names.has(name) || excluded(name)) continue;
|
|
154
|
+
parsed.names.add(name);
|
|
155
|
+
classOnly.add(name);
|
|
156
|
+
parsed.colors.set(color, [...(parsed.colors.get(color) ?? []), name]);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return { classOnly, problems };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function mtimeOf(file) {
|
|
163
|
+
try {
|
|
164
|
+
return fs.statSync(file).mtimeMs;
|
|
165
|
+
} catch {
|
|
166
|
+
return -1;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** @import 의 경로를 파일로 푼다. CSS 처럼 상대 경로를 먼저 보고, 없으면 패키지에서 찾는다. 못 찾으면 null. */
|
|
171
|
+
function resolveImport(fromFile, spec) {
|
|
172
|
+
const relative = path.resolve(path.dirname(fromFile), spec);
|
|
173
|
+
if (fs.existsSync(relative) && fs.statSync(relative).isFile()) return relative;
|
|
174
|
+
if (spec.startsWith(".") || spec.startsWith("/")) return null;
|
|
175
|
+
try {
|
|
176
|
+
return createRequire(fromFile).resolve(spec);
|
|
177
|
+
} catch {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 프로젝트에 설치된 tailwindcss 의 theme.css 에서 기본 팔레트를 읽는다.
|
|
184
|
+
* 토큰 CSS 가 tailwindcss 를 불러오는 파일이므로, 그 위치에서 찾는다.
|
|
185
|
+
*/
|
|
186
|
+
function readTailwindPalette(tokensFile, m) {
|
|
187
|
+
const require = createRequire(tokensFile);
|
|
188
|
+
let file;
|
|
189
|
+
let classOnly = false;
|
|
190
|
+
try {
|
|
191
|
+
file = require.resolve("tailwindcss/theme.css");
|
|
192
|
+
} catch {
|
|
193
|
+
// v3 에는 theme.css 가 없다. 팔레트는 tailwindcss/colors 에 있고, CSS 변수가 없어 클래스로만 쓴다.
|
|
194
|
+
try {
|
|
195
|
+
file = require.resolve("tailwindcss/colors");
|
|
196
|
+
classOnly = true;
|
|
197
|
+
} catch {
|
|
198
|
+
throw new Error(m.paletteMissing({ root: path.dirname(tokensFile) }));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const { mtimeMs } = fs.statSync(file);
|
|
202
|
+
const cached = paletteCache.get(file);
|
|
203
|
+
if (cached?.mtimeMs === mtimeMs) return cached.result;
|
|
204
|
+
let palette;
|
|
205
|
+
if (classOnly) {
|
|
206
|
+
const module = require(file);
|
|
207
|
+
palette = flattenColors(module.default ?? module);
|
|
208
|
+
} else {
|
|
209
|
+
palette = parsePaletteColors(fs.readFileSync(file, "utf8"));
|
|
210
|
+
}
|
|
211
|
+
const result = { palette, classOnly };
|
|
212
|
+
paletteCache.set(file, { mtimeMs, result });
|
|
213
|
+
return result;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 프로젝트 토큰 뒤에 팔레트 색을 더한다. 다음 색은 뺀다.
|
|
218
|
+
* - 프로젝트가 같은 이름을 다시 정의한 색 (값을 읽지 못했어도 기본값은 더 이상 쓰이지 않는다)
|
|
219
|
+
* - 프로젝트가 --color-*: initial, --*: initial 같은 선언으로 비운 네임스페이스의 색
|
|
220
|
+
* - exclude 에 걸린 색
|
|
221
|
+
* @param {ProjectTokens} project
|
|
222
|
+
* @param {{ palette: Map<string, string>, classOnly: boolean }} tailwind classOnly 면 팔레트 색에 CSS 변수가 없다 (v3)
|
|
223
|
+
* @param {string[]} exclude
|
|
224
|
+
*/
|
|
225
|
+
function withPalette(project, { palette, classOnly: paletteIsClassOnly }, exclude) {
|
|
226
|
+
const matches = (name, pattern) => (pattern.endsWith("*") ? name.startsWith(pattern.slice(0, -1)) : name === pattern);
|
|
227
|
+
const excluded = (name) => [...exclude, ...project.resets].some((pattern) => matches(name, pattern));
|
|
228
|
+
const colors = new Map([...project.colors].map(([hex, names]) => [hex, [...names]]));
|
|
229
|
+
const paletteNames = new Set();
|
|
230
|
+
for (const [name, hex] of palette) {
|
|
231
|
+
if (project.names.has(name) || excluded(name)) continue;
|
|
232
|
+
paletteNames.add(name);
|
|
233
|
+
colors.set(hex, [...(colors.get(hex) ?? []), name]);
|
|
234
|
+
}
|
|
235
|
+
const classOnly = paletteIsClassOnly ? new Set([...project.classOnly, ...paletteNames]) : project.classOnly;
|
|
236
|
+
return { colors, themed: project.themed, paletteNames, classOnly };
|
|
54
237
|
}
|