@first-ch/tools-mcp 0.4.1 → 0.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/color.mjs ADDED
@@ -0,0 +1,629 @@
1
+ // Colorコード変換&アルファ透過(tools.first-ch.com/color/ と同一ロジック)
2
+ // 正本は site 側の site/color/app.js(FirstCHTools リポジトリ)。
3
+ // 変換コア(clParseColor / clHex / clRgbStr / clHslStr / clOklchStr / clFlatten /
4
+ // clContrast / clAlphaRows / clPalette)はそちらとバイト単位で同じ内容を保つこと。
5
+ // 完全ローカル処理・ネットワーク送信なし。
6
+
7
+ /* ==================== ここから変換コア(site / MCP で同一) ==================== */
8
+
9
+ const CL_MAX_DECIMALS = 6;
10
+ // OKLCH の彩度を % で書いたときの基準(CSS Color 4: 100% = 0.4)
11
+ const CL_OKLCH_C_PCT = 0.4;
12
+
13
+ // CSSの名前付き色(148色)。値は Chrome の getComputedStyle から取得した実測値
14
+ const CL_NAMED_SRC =
15
+ 'aliceblue f0f8ff,antiquewhite faebd7,aqua 00ffff,aquamarine 7fffd4,azure f0ffff,beige f5f5dc,' +
16
+ 'bisque ffe4c4,black 000000,blanchedalmond ffebcd,blue 0000ff,blueviolet 8a2be2,brown a52a2a,' +
17
+ 'burlywood deb887,cadetblue 5f9ea0,chartreuse 7fff00,chocolate d2691e,coral ff7f50,' +
18
+ 'cornflowerblue 6495ed,cornsilk fff8dc,crimson dc143c,cyan 00ffff,darkblue 00008b,darkcyan 008b8b,' +
19
+ 'darkgoldenrod b8860b,darkgray a9a9a9,darkgreen 006400,darkgrey a9a9a9,darkkhaki bdb76b,' +
20
+ 'darkmagenta 8b008b,darkolivegreen 556b2f,darkorange ff8c00,darkorchid 9932cc,darkred 8b0000,' +
21
+ 'darksalmon e9967a,darkseagreen 8fbc8f,darkslateblue 483d8b,darkslategray 2f4f4f,' +
22
+ 'darkslategrey 2f4f4f,darkturquoise 00ced1,darkviolet 9400d3,deeppink ff1493,deepskyblue 00bfff,' +
23
+ 'dimgray 696969,dimgrey 696969,dodgerblue 1e90ff,firebrick b22222,floralwhite fffaf0,' +
24
+ 'forestgreen 228b22,fuchsia ff00ff,gainsboro dcdcdc,ghostwhite f8f8ff,gold ffd700,goldenrod daa520,' +
25
+ 'gray 808080,green 008000,greenyellow adff2f,grey 808080,honeydew f0fff0,hotpink ff69b4,' +
26
+ 'indianred cd5c5c,indigo 4b0082,ivory fffff0,khaki f0e68c,lavender e6e6fa,lavenderblush fff0f5,' +
27
+ 'lawngreen 7cfc00,lemonchiffon fffacd,lightblue add8e6,lightcoral f08080,lightcyan e0ffff,' +
28
+ 'lightgoldenrodyellow fafad2,lightgray d3d3d3,lightgreen 90ee90,lightgrey d3d3d3,lightpink ffb6c1,' +
29
+ 'lightsalmon ffa07a,lightseagreen 20b2aa,lightskyblue 87cefa,lightslategray 778899,' +
30
+ 'lightslategrey 778899,lightsteelblue b0c4de,lightyellow ffffe0,lime 00ff00,limegreen 32cd32,' +
31
+ 'linen faf0e6,magenta ff00ff,maroon 800000,mediumaquamarine 66cdaa,mediumblue 0000cd,' +
32
+ 'mediumorchid ba55d3,mediumpurple 9370db,mediumseagreen 3cb371,mediumslateblue 7b68ee,' +
33
+ 'mediumspringgreen 00fa9a,mediumturquoise 48d1cc,mediumvioletred c71585,midnightblue 191970,' +
34
+ 'mintcream f5fffa,mistyrose ffe4e1,moccasin ffe4b5,navajowhite ffdead,navy 000080,oldlace fdf5e6,' +
35
+ 'olive 808000,olivedrab 6b8e23,orange ffa500,orangered ff4500,orchid da70d6,palegoldenrod eee8aa,' +
36
+ 'palegreen 98fb98,paleturquoise afeeee,palevioletred db7093,papayawhip ffefd5,peachpuff ffdab9,' +
37
+ 'peru cd853f,pink ffc0cb,plum dda0dd,powderblue b0e0e6,purple 800080,rebeccapurple 663399,' +
38
+ 'red ff0000,rosybrown bc8f8f,royalblue 4169e1,saddlebrown 8b4513,salmon fa8072,sandybrown f4a460,' +
39
+ 'seagreen 2e8b57,seashell fff5ee,sienna a0522d,silver c0c0c0,skyblue 87ceeb,slateblue 6a5acd,' +
40
+ 'slategray 708090,slategrey 708090,snow fffafa,springgreen 00ff7f,steelblue 4682b4,tan d2b48c,' +
41
+ 'teal 008080,thistle d8bfd8,tomato ff6347,turquoise 40e0d0,violet ee82ee,wheat f5deb3,' +
42
+ 'white ffffff,whitesmoke f5f5f5,yellow ffff00,yellowgreen 9acd32';
43
+
44
+ const CL_NAMED = Object.create(null);
45
+ const CL_NAME_OF = Object.create(null);
46
+ for (const entry of CL_NAMED_SRC.split(',')) {
47
+ const sp = entry.indexOf(' ');
48
+ const name = entry.slice(0, sp);
49
+ const hex = entry.slice(sp + 1);
50
+ CL_NAMED[name] = hex;
51
+ // 同じ値に複数の名前がある場合(aqua/cyan・gray/grey 等)は先に出てくる方を代表にする
52
+ if (!CL_NAME_OF[hex]) CL_NAME_OF[hex] = name;
53
+ }
54
+
55
+ // 明度パレットの段。sRGBで表現できる範囲になるよう彩度は自動で落とす
56
+ const CL_TONES = [
57
+ { key: '50', l: 0.971 }, { key: '100', l: 0.936 }, { key: '200', l: 0.885 },
58
+ { key: '300', l: 0.828 }, { key: '400', l: 0.75 }, { key: '500', l: 0.665 },
59
+ { key: '600', l: 0.59 }, { key: '700', l: 0.51 }, { key: '800', l: 0.44 },
60
+ { key: '900', l: 0.378 }, { key: '950', l: 0.272 },
61
+ ];
62
+
63
+ const clClamp = (n, lo, hi) => (n < lo ? lo : n > hi ? hi : n);
64
+
65
+ /** 小数 d 桁で四捨五入した数値(JSONへ入れる数値用) */
66
+ const clRound = (n, d) => {
67
+ const p = Math.pow(10, clClamp(Math.trunc(d), 0, CL_MAX_DECIMALS));
68
+ return Math.round(n * p) / p;
69
+ };
70
+
71
+ /** 数値を小数 d 桁までで文字列に(末尾の0は落とす。-0 は 0) */
72
+ function clFix(n, d) {
73
+ if (!Number.isFinite(n)) return '0';
74
+ let s = n.toFixed(clClamp(Math.trunc(d), 0, CL_MAX_DECIMALS));
75
+ if (s.indexOf('.') !== -1) s = s.replace(/0+$/, '').replace(/\.$/, '');
76
+ return /^-0$/.test(s) ? '0' : s;
77
+ }
78
+
79
+ /* ---- 解析 ---- */
80
+
81
+ const CL_HEX_RE = /^#?([0-9a-f]+)$/i;
82
+
83
+ /** #rgb / #rgba / #rrggbb / #rrggbbaa を読む(3,4,6,8桁以外は不正) */
84
+ function clParseHex(input) {
85
+ const m = CL_HEX_RE.exec(String(input).trim());
86
+ if (!m) return null;
87
+ const h = m[1].toLowerCase();
88
+ const n = h.length;
89
+ if (n !== 3 && n !== 4 && n !== 6 && n !== 8) return null;
90
+ if (n <= 4) {
91
+ const d = (i) => parseInt(h.charAt(i) + h.charAt(i), 16);
92
+ return { r: d(0), g: d(1), b: d(2), a: n === 4 ? d(3) / 255 : 1, format: 'hex' };
93
+ }
94
+ const p = (i) => parseInt(h.substr(i, 2), 16);
95
+ return { r: p(0), g: p(2), b: p(4), a: n === 8 ? p(6) / 255 : 1, format: 'hex' };
96
+ }
97
+
98
+ const CL_NUM_RE = /^([+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?)(%?)$/i;
99
+ const CL_ANGLE_RE = /^([+-]?(?:\d+(?:\.\d+)?|\.\d+))(deg|grad|rad|turn)?$/i;
100
+
101
+ /** 数値トークンを読む。% なら pctBase を 100% とみなす。`none` は 0(CSS Color 4) */
102
+ function clScalar(token, pctBase) {
103
+ const t = String(token).trim().toLowerCase();
104
+ if (t === 'none') return 0;
105
+ const m = CL_NUM_RE.exec(t);
106
+ if (!m) return null;
107
+ const v = Number(m[1]);
108
+ if (!Number.isFinite(v)) return null;
109
+ return m[2] ? (v / 100) * pctBase : v;
110
+ }
111
+
112
+ /** 角度トークンを 0〜360 の度数へ(deg / grad / rad / turn と単位なしに対応) */
113
+ function clAngle(token) {
114
+ const t = String(token).trim().toLowerCase();
115
+ if (t === 'none') return 0;
116
+ const m = CL_ANGLE_RE.exec(t);
117
+ if (!m) return null;
118
+ const v = Number(m[1]);
119
+ if (!Number.isFinite(v)) return null;
120
+ const u = (m[2] || 'deg').toLowerCase();
121
+ const deg = u === 'deg' ? v : u === 'grad' ? v * 0.9 : u === 'rad' ? (v * 180) / Math.PI : v * 360;
122
+ return ((deg % 360) + 360) % 360;
123
+ }
124
+
125
+ /** アルファのトークン(0〜1 か 0%〜100%)を 0〜1 へ */
126
+ function clAlphaToken(token) {
127
+ const v = clScalar(token, 1);
128
+ return v === null ? null : clClamp(v, 0, 1);
129
+ }
130
+
131
+ /** rgb() / hsl() / oklch() / oklab() の中身を読む。旧記法(カンマ)と新記法(空白+/)の両対応 */
132
+ function clParseFn(name, body) {
133
+ if (body.indexOf('(') !== -1) return null; // var() や calc() の入れ子は扱わない
134
+ let head = body;
135
+ let alphaTok = null;
136
+ const slash = body.indexOf('/');
137
+ if (slash !== -1) {
138
+ head = body.slice(0, slash);
139
+ alphaTok = body.slice(slash + 1).trim();
140
+ if (!alphaTok) return null;
141
+ }
142
+ const parts = head.split(/[\s,]+/).filter(Boolean);
143
+ if (alphaTok === null && parts.length === 4) alphaTok = parts.pop();
144
+ if (parts.length !== 3) return null;
145
+
146
+ let a = 1;
147
+ if (alphaTok !== null) {
148
+ a = clAlphaToken(alphaTok);
149
+ if (a === null) return null;
150
+ }
151
+
152
+ if (name === 'rgb' || name === 'rgba') {
153
+ const v = parts.map((t) => clScalar(t, 255));
154
+ if (v.indexOf(null) !== -1) return null;
155
+ return { r: clClamp(v[0], 0, 255), g: clClamp(v[1], 0, 255), b: clClamp(v[2], 0, 255), a, format: 'rgb' };
156
+ }
157
+ if (name === 'hsl' || name === 'hsla') {
158
+ const h = clAngle(parts[0]);
159
+ const s = clScalar(parts[1], 100);
160
+ const l = clScalar(parts[2], 100);
161
+ if (h === null || s === null || l === null) return null;
162
+ const c = clHslToRgb(h, clClamp(s, 0, 100), clClamp(l, 0, 100));
163
+ return { r: c.r, g: c.g, b: c.b, a, format: 'hsl' };
164
+ }
165
+ if (name === 'hwb') {
166
+ const h = clAngle(parts[0]);
167
+ const w = clScalar(parts[1], 100);
168
+ const bl = clScalar(parts[2], 100);
169
+ if (h === null || w === null || bl === null) return null;
170
+ const c = clHwbToRgb(h, clClamp(w, 0, 100), clClamp(bl, 0, 100));
171
+ return { r: c.r, g: c.g, b: c.b, a, format: 'hwb' };
172
+ }
173
+ if (name === 'oklch') {
174
+ const L = clScalar(parts[0], 1);
175
+ const C = clScalar(parts[1], CL_OKLCH_C_PCT);
176
+ const H = clAngle(parts[2]);
177
+ if (L === null || C === null || H === null) return null;
178
+ const c = clOklchToRgb(clClamp(L, 0, 1), Math.max(0, C), H);
179
+ return { r: c.r, g: c.g, b: c.b, a, format: 'oklch', clipped: c.clipped };
180
+ }
181
+ if (name === 'oklab') {
182
+ const L = clScalar(parts[0], 1);
183
+ const A = clScalar(parts[1], CL_OKLCH_C_PCT);
184
+ const B = clScalar(parts[2], CL_OKLCH_C_PCT);
185
+ if (L === null || A === null || B === null) return null;
186
+ const lch = clOklabToOklch(clClamp(L, 0, 1), A, B);
187
+ const c = clOklchToRgb(lch.l, lch.c, lch.h);
188
+ return { r: c.r, g: c.g, b: c.b, a, format: 'oklab', clipped: c.clipped };
189
+ }
190
+ return null;
191
+ }
192
+
193
+ /**
194
+ * 色の文字列を {r,g,b(0〜255), a(0〜1), format} へ。読めなければ null。
195
+ * HEX(3/4/6/8桁)・rgb()/rgba()・hsl()/hsla()・oklch()・oklab()・CSSの名前付き色・transparent に対応。
196
+ */
197
+ function clParseColor(input) {
198
+ const raw = String(input === undefined || input === null ? '' : input).trim();
199
+ if (!raw) return null;
200
+ const low = raw.toLowerCase();
201
+ if (low === 'transparent') return { r: 0, g: 0, b: 0, a: 0, format: 'named', name: 'transparent' };
202
+ if (CL_NAMED[low]) {
203
+ const c = clParseHex(CL_NAMED[low]);
204
+ c.format = 'named';
205
+ c.name = low;
206
+ return c;
207
+ }
208
+ const fn = /^([a-z]+)\(([^]*)\)$/i.exec(low);
209
+ if (fn) return clParseFn(fn[1].toLowerCase(), fn[2]);
210
+ return clParseHex(low);
211
+ }
212
+
213
+ /* ---- 色空間の変換 ---- */
214
+
215
+ /** HSL(h:0-360 / s,l:0-100)→ RGB(0-255) */
216
+ function clHslToRgb(h, s, l) {
217
+ const hh = ((h % 360) + 360) % 360;
218
+ const ss = s / 100;
219
+ const ll = l / 100;
220
+ const k = (n) => (n + hh / 30) % 12;
221
+ const aa = ss * Math.min(ll, 1 - ll);
222
+ const f = (n) => ll - aa * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
223
+ return { r: f(0) * 255, g: f(8) * 255, b: f(4) * 255 };
224
+ }
225
+
226
+ /** HWB(h:0-360 / w,b:0-100)→ RGB(0-255)。白と黒の合計が100%以上なら灰色になる */
227
+ function clHwbToRgb(h, w, b) {
228
+ const W = w / 100;
229
+ const B = b / 100;
230
+ if (W + B >= 1) {
231
+ const g = (W / (W + B)) * 255;
232
+ return { r: g, g, b: g };
233
+ }
234
+ const pure = clHslToRgb(h, 100, 50);
235
+ const mix = (v) => (v / 255) * (1 - W - B) * 255 + W * 255;
236
+ return { r: mix(pure.r), g: mix(pure.g), b: mix(pure.b) };
237
+ }
238
+
239
+ /** RGB(0-255)→ HSL(h:0-360 / s,l:0-100) */
240
+ function clRgbToHsl(r, g, b) {
241
+ const R = r / 255;
242
+ const G = g / 255;
243
+ const B = b / 255;
244
+ const max = Math.max(R, G, B);
245
+ const min = Math.min(R, G, B);
246
+ const d = max - min;
247
+ let h = 0;
248
+ if (d > 0) {
249
+ if (max === R) h = ((G - B) / d) % 6;
250
+ else if (max === G) h = (B - R) / d + 2;
251
+ else h = (R - G) / d + 4;
252
+ h *= 60;
253
+ if (h < 0) h += 360;
254
+ }
255
+ const l = (max + min) / 2;
256
+ const s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));
257
+ return { h, s: clClamp(s * 100, 0, 100), l: clClamp(l * 100, 0, 100) };
258
+ }
259
+
260
+ // sRGB のガンマ(符号つき。ガモット外の負値も折り返さずそのまま返す)
261
+ const clLinear = (c) => {
262
+ const v = c / 255;
263
+ const s = v < 0 ? -1 : 1;
264
+ const x = Math.abs(v);
265
+ return s * (x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4));
266
+ };
267
+ const clGamma = (c) => {
268
+ const s = c < 0 ? -1 : 1;
269
+ const x = Math.abs(c);
270
+ return 255 * s * (x <= 0.0031308 ? x * 12.92 : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
271
+ };
272
+
273
+ /** RGB(0-255)→ OKLab(Björn Ottosson の行列) */
274
+ function clRgbToOklab(r, g, b) {
275
+ const R = clLinear(r);
276
+ const G = clLinear(g);
277
+ const B = clLinear(b);
278
+ const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B);
279
+ const m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B);
280
+ const s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B);
281
+ return {
282
+ L: 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
283
+ a: 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
284
+ b: 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s,
285
+ };
286
+ }
287
+
288
+ /** OKLab → RGB(0-255・クランプなし=ガモット外は範囲外の値のまま返す) */
289
+ function clOklabToRgbRaw(L, a, b) {
290
+ const l = Math.pow(L + 0.3963377774 * a + 0.2158037573 * b, 3);
291
+ const m = Math.pow(L - 0.1055613458 * a - 0.0638541728 * b, 3);
292
+ const s = Math.pow(L - 0.0894841775 * a - 1.2914855480 * b, 3);
293
+ return {
294
+ r: clGamma(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
295
+ g: clGamma(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
296
+ b: clGamma(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s),
297
+ };
298
+ }
299
+
300
+ function clOklabToOklch(L, a, b) {
301
+ const c = Math.sqrt(a * a + b * b);
302
+ let h = c < 1e-7 ? 0 : (Math.atan2(b, a) * 180) / Math.PI;
303
+ if (h < 0) h += 360;
304
+ return { l: L, c, h };
305
+ }
306
+
307
+ /** RGB(0-255)→ OKLCH(l:0-1 / c:0- / h:0-360) */
308
+ function clRgbToOklch(r, g, b) {
309
+ const lab = clRgbToOklab(r, g, b);
310
+ return clOklabToOklch(lab.L, lab.a, lab.b);
311
+ }
312
+
313
+ const CL_GAMUT_EPS = 1e-4;
314
+ const clInGamut = (c) =>
315
+ c.r >= -CL_GAMUT_EPS && c.r <= 255 + CL_GAMUT_EPS &&
316
+ c.g >= -CL_GAMUT_EPS && c.g <= 255 + CL_GAMUT_EPS &&
317
+ c.b >= -CL_GAMUT_EPS && c.b <= 255 + CL_GAMUT_EPS;
318
+
319
+ function clOklchToRgbRaw(l, c, h) {
320
+ const rad = (h * Math.PI) / 180;
321
+ return clOklabToRgbRaw(l, c * Math.cos(rad), c * Math.sin(rad));
322
+ }
323
+
324
+ /**
325
+ * OKLCH → sRGB。sRGBで表現できない色は、明度と色相を保ったまま彩度だけを二分探索で下げて収める
326
+ * (CSS Color 4 のガモットマッピングを簡略化したもの。単純にRGBを切り詰めると色相がずれるため)。
327
+ */
328
+ function clOklchToRgb(l, c, h) {
329
+ const L = clClamp(l, 0, 1);
330
+ const C = Math.max(0, c);
331
+ const raw = clOklchToRgbRaw(L, C, h);
332
+ if (clInGamut(raw)) {
333
+ return { r: clClamp(raw.r, 0, 255), g: clClamp(raw.g, 0, 255), b: clClamp(raw.b, 0, 255), clipped: false };
334
+ }
335
+ let lo = 0;
336
+ let hi = C;
337
+ for (let i = 0; i < 24; i++) {
338
+ const mid = (lo + hi) / 2;
339
+ if (clInGamut(clOklchToRgbRaw(L, mid, h))) lo = mid; else hi = mid;
340
+ }
341
+ const fit = clOklchToRgbRaw(L, lo, h);
342
+ return {
343
+ r: clClamp(fit.r, 0, 255),
344
+ g: clClamp(fit.g, 0, 255),
345
+ b: clClamp(fit.b, 0, 255),
346
+ clipped: true,
347
+ chroma: lo,
348
+ };
349
+ }
350
+
351
+ /* ---- 書き出し ---- */
352
+
353
+ const CL_DEF = { alpha: 'auto', legacy: false, upper: false, alphaPercent: false };
354
+ const clOpt = (o, key) => (o && o[key] !== undefined ? o[key] : CL_DEF[key]);
355
+
356
+ const clShowAlpha = (color, o) => {
357
+ const mode = clOpt(o, 'alpha');
358
+ return mode === 'always' || (mode !== 'never' && color.a < 1 - 1e-9);
359
+ };
360
+
361
+ const clAlphaStr = (a, o) =>
362
+ (clOpt(o, 'alphaPercent') ? clFix(a * 100, 2) + '%' : clFix(a, 4));
363
+
364
+ /** HEX(#rrggbb / #rrggbbaa) */
365
+ function clHex(color, o) {
366
+ const h = (n) => clClamp(Math.round(n), 0, 255).toString(16).padStart(2, '0');
367
+ let s = h(color.r) + h(color.g) + h(color.b);
368
+ if (clShowAlpha(color, o)) s += h(color.a * 255);
369
+ return '#' + (clOpt(o, 'upper') ? s.toUpperCase() : s);
370
+ }
371
+
372
+ /** rgb() / rgba()。legacy=true でカンマ区切りの従来記法 */
373
+ function clRgbStr(color, o) {
374
+ const v = [color.r, color.g, color.b].map((n) => clClamp(Math.round(n), 0, 255));
375
+ const withA = clShowAlpha(color, o);
376
+ if (clOpt(o, 'legacy')) {
377
+ return withA
378
+ ? `rgba(${v[0]}, ${v[1]}, ${v[2]}, ${clAlphaStr(color.a, o)})`
379
+ : `rgb(${v[0]}, ${v[1]}, ${v[2]})`;
380
+ }
381
+ return withA ? `rgb(${v[0]} ${v[1]} ${v[2]} / ${clAlphaStr(color.a, o)})` : `rgb(${v[0]} ${v[1]} ${v[2]})`;
382
+ }
383
+
384
+ /** hsl() / hsla() */
385
+ function clHslStr(color, o) {
386
+ const h = clRgbToHsl(color.r, color.g, color.b);
387
+ const H = clFix(h.h, 2);
388
+ const S = clFix(h.s, 2);
389
+ const L = clFix(h.l, 2);
390
+ const withA = clShowAlpha(color, o);
391
+ if (clOpt(o, 'legacy')) {
392
+ return withA
393
+ ? `hsla(${H}, ${S}%, ${L}%, ${clAlphaStr(color.a, o)})`
394
+ : `hsl(${H}, ${S}%, ${L}%)`;
395
+ }
396
+ return withA ? `hsl(${H} ${S}% ${L}% / ${clAlphaStr(color.a, o)})` : `hsl(${H} ${S}% ${L}%)`;
397
+ }
398
+
399
+ /** oklch()。CSSの慣例に合わせて明度は % で書く */
400
+ function clOklchStr(color, o) {
401
+ const c = clRgbToOklch(color.r, color.g, color.b);
402
+ const body = `${clFix(c.l * 100, 2)}% ${clFix(c.c, 4)} ${clFix(c.h, 2)}`;
403
+ return clShowAlpha(color, o) ? `oklch(${body} / ${clAlphaStr(color.a, o)})` : `oklch(${body})`;
404
+ }
405
+
406
+ /* ---- 合成・コントラスト ---- */
407
+
408
+ /** 背景の上に重ねたときに実際に見える色(アルファ合成) */
409
+ function clFlatten(fg, bg) {
410
+ const a = clClamp(fg.a === undefined ? 1 : fg.a, 0, 1);
411
+ const ba = clClamp(bg && bg.a !== undefined ? bg.a : 1, 0, 1);
412
+ const outA = a + ba * (1 - a);
413
+ if (outA <= 0) return { r: 0, g: 0, b: 0, a: 0 };
414
+ const mix = (f, b) => (f * a + b * ba * (1 - a)) / outA;
415
+ return { r: mix(fg.r, bg.r), g: mix(fg.g, bg.g), b: mix(fg.b, bg.b), a: outA };
416
+ }
417
+
418
+ function clLuminance(c) {
419
+ const f = (v) => {
420
+ const x = clClamp(v, 0, 255) / 255;
421
+ return x <= 0.03928 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
422
+ };
423
+ return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b);
424
+ }
425
+
426
+ /** WCAG 2.1 のコントラスト比(小数2桁。透過色は背景に重ねてから渡すこと) */
427
+ function clContrast(c1, c2) {
428
+ const l1 = clLuminance(c1);
429
+ const l2 = clLuminance(c2);
430
+ const ratio = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
431
+ return Math.round(ratio * 100) / 100;
432
+ }
433
+
434
+ /** アルファを step% 刻みで振った表(背景に重ねた実際の色つき) */
435
+ function clAlphaRows(color, bg, step) {
436
+ const st = clClamp(Number(step) || 10, 1, 50);
437
+ const rows = [];
438
+ for (let p = 100; p >= 0; p -= st) {
439
+ const a = Math.round(p) / 100;
440
+ const c = { r: color.r, g: color.g, b: color.b, a };
441
+ rows.push({ percent: Math.round(p), alpha: a, color: c, flat: clFlatten(c, bg) });
442
+ }
443
+ if (rows.length && rows[rows.length - 1].percent !== 0) {
444
+ const c = { r: color.r, g: color.g, b: color.b, a: 0 };
445
+ rows.push({ percent: 0, alpha: 0, color: c, flat: clFlatten(c, bg) });
446
+ }
447
+ return rows;
448
+ }
449
+
450
+ /** 色相と彩度を保ったまま明度だけを振った11段のパレット(sRGB外は彩度を自動で下げる) */
451
+ function clPalette(color) {
452
+ const base = clRgbToOklch(color.r, color.g, color.b);
453
+ let nearest = 0;
454
+ CL_TONES.forEach((t, i) => {
455
+ if (Math.abs(t.l - base.l) < Math.abs(CL_TONES[nearest].l - base.l)) nearest = i;
456
+ });
457
+ return CL_TONES.map((t, i) => {
458
+ const c = clOklchToRgb(t.l, base.c, base.h);
459
+ const rgb = { r: c.r, g: c.g, b: c.b, a: 1 };
460
+ return {
461
+ key: t.key,
462
+ l: t.l,
463
+ chroma: c.clipped ? c.chroma : base.c,
464
+ hue: base.h,
465
+ color: rgb,
466
+ clipped: !!c.clipped,
467
+ base: i === nearest,
468
+ on_white: clContrast(rgb, { r: 255, g: 255, b: 255 }),
469
+ on_black: clContrast(rgb, { r: 0, g: 0, b: 0 }),
470
+ };
471
+ });
472
+ }
473
+
474
+ // 指摘事項のコードを日本語の文へ
475
+ const CL_NOTE_TEXT = {
476
+ NAMED: (n) => `CSSの名前付き色 ${n} と同じ値です。`,
477
+ GRAY: () => '彩度が0の無彩色です。hsl() と oklch() の色相の値に意味はありません。',
478
+ CLIPPED: () => '指定された色はsRGBの範囲外だったため、明度と色相を保ったまま彩度を下げて収めました(RGBを切り詰めると色相までずれるためです)。',
479
+ ALPHA: (p) => `アルファが ${p}% なので、実際の見え方は背景しだいです。flattened(背景に重ねた実際の色)を使ってください。`,
480
+ HEX8: () => '8桁HEX(#rrggbbaa)は現行ブラウザではすべて使えます。IE 11だけが非対応なので、必要な場合は rgba() を使ってください。',
481
+ CONTRAST: (w, b) => `白とのコントラスト比は ${w}:1、黒とは ${b}:1 です(WCAG 2.1の本文基準は4.5:1)。`,
482
+ BG_ALPHA: () => '背景色にもアルファが指定されているため、背景の透過も含めて合成しています(結果のアルファは1未満になります)。',
483
+ };
484
+
485
+ export class ColorError extends Error {}
486
+
487
+ const clNote = (code, a, b) => ({ code, message: CL_NOTE_TEXT[code] ? CL_NOTE_TEXT[code](a, b) : code });
488
+
489
+ /**
490
+ * 色コードを HEX / RGB / HSL / OKLCH へ相互変換し、アルファ付きの rgba() / hsla() と
491
+ * 背景に重ねたときの実際の色(アルファ合成の結果)・コントラスト比・明度パレットを返す。
492
+ *
493
+ * @param {object} opts
494
+ * @param {string} opts.color 変換する色('#c8501f' / 'rgb(200 80 31)' / 'hsl(17 73% 45%)' / 'oklch(56% 0.16 41)' / 'tomato' など)
495
+ * @param {number|string} [opts.alpha] アルファ(0〜1・'50%'・0〜100 のいずれか。指定すると color 側のアルファを上書きする)
496
+ * @param {string} [opts.background='#ffffff'] 重ねる背景色
497
+ * @param {'modern'|'legacy'} [opts.syntax='modern'] rgb(200 80 31 / 50%) か rgba(200, 80, 31, 0.5) か
498
+ * @param {boolean} [opts.uppercase=false] HEXを大文字にする
499
+ * @param {boolean} [opts.alphaPercent=false] アルファをパーセントで書く
500
+ * @param {number} [opts.step=10] アルファ表の刻み(%)
501
+ * @param {boolean} [opts.alphaTable=true] アルファ表を返すか
502
+ * @param {boolean} [opts.palette=true] 明度パレットを返すか
503
+ */
504
+ export function colorConvert(opts = {}) {
505
+ const input = opts.color;
506
+ if (input === undefined || input === null || String(input).trim() === '') {
507
+ throw new ColorError('color(変換する色)を渡してください(例: "#c8501f" / "rgb(200 80 31)" / "oklch(56% 0.16 41)" / "tomato")');
508
+ }
509
+ const parsed = clParseColor(input);
510
+ if (!parsed) {
511
+ throw new ColorError(`色として読めません: ${input}(HEX 3/4/6/8桁・rgb()・hsl()・hwb()・oklch()・oklab()・CSSの色名・transparent に対応)`);
512
+ }
513
+
514
+ if (opts.alpha !== undefined && opts.alpha !== null && String(opts.alpha).trim() !== '') {
515
+ const raw = String(opts.alpha).trim();
516
+ const a = clAlphaToken(raw);
517
+ if (a === null) throw new ColorError(`alpha は 0〜1 か 0%〜100% で指定してください: ${opts.alpha}`);
518
+ const num = Number(raw.replace('%', ''));
519
+ // 0〜1 でも 0〜100 でも受ける(0.4 / 40 / '40%' はすべて 40%)
520
+ parsed.a = raw.indexOf('%') === -1 && num > 1 ? clClamp(num / 100, 0, 1) : a;
521
+ }
522
+
523
+ const bgInput = opts.background === undefined || opts.background === null || String(opts.background).trim() === ''
524
+ ? '#ffffff'
525
+ : opts.background;
526
+ const bg = clParseColor(bgInput);
527
+ if (!bg) throw new ColorError(`background を色として読めません: ${opts.background}`);
528
+
529
+ const step = opts.step === undefined || opts.step === null ? 10 : Number(opts.step);
530
+ if (!Number.isFinite(step) || step < 1 || step > 50) {
531
+ throw new ColorError(`step は 1〜50 の数値で指定してください: ${opts.step}`);
532
+ }
533
+ if (opts.syntax !== undefined && opts.syntax !== 'modern' && opts.syntax !== 'legacy') {
534
+ throw new ColorError(`syntax は modern か legacy: ${opts.syntax}`);
535
+ }
536
+
537
+ const o = {
538
+ legacy: opts.syntax === 'legacy',
539
+ upper: opts.uppercase === true,
540
+ alphaPercent: opts.alphaPercent === true,
541
+ };
542
+ const withA = (extra) => Object.assign({}, o, extra);
543
+ const solid = { r: parsed.r, g: parsed.g, b: parsed.b, a: 1 };
544
+ const lch = clRgbToOklch(parsed.r, parsed.g, parsed.b);
545
+ const hsl = clRgbToHsl(parsed.r, parsed.g, parsed.b);
546
+ const flat = clFlatten(parsed, bg);
547
+ const onWhite = clContrast(solid, { r: 255, g: 255, b: 255 });
548
+ const onBlack = clContrast(solid, { r: 0, g: 0, b: 0 });
549
+ const hexKey = clHex(solid, { alpha: 'never' }).slice(1);
550
+
551
+ const notes = [];
552
+ if (CL_NAME_OF[hexKey]) notes.push(clNote('NAMED', CL_NAME_OF[hexKey]));
553
+ if (parsed.clipped) notes.push(clNote('CLIPPED'));
554
+ if (lch.c < 0.002) notes.push(clNote('GRAY'));
555
+ if (parsed.a < 1 - 1e-9) {
556
+ notes.push(clNote('ALPHA', clFix(parsed.a * 100, 1)));
557
+ notes.push(clNote('HEX8'));
558
+ }
559
+ if (bg.a < 1 - 1e-9) notes.push(clNote('BG_ALPHA'));
560
+ notes.push(clNote('CONTRAST', onWhite.toFixed(2), onBlack.toFixed(2)));
561
+
562
+ const result = {
563
+ input: { value: String(input), format: parsed.format, name: parsed.name },
564
+ alpha: parsed.a,
565
+ rgb: {
566
+ r: clClamp(Math.round(parsed.r), 0, 255),
567
+ g: clClamp(Math.round(parsed.g), 0, 255),
568
+ b: clClamp(Math.round(parsed.b), 0, 255),
569
+ },
570
+ hsl: { h: clRound(hsl.h, 2), s: clRound(hsl.s, 2), l: clRound(hsl.l, 2) },
571
+ oklch: { l: clRound(lch.l, 4), c: clRound(lch.c, 4), h: clRound(lch.h, 2) },
572
+ formats: {
573
+ hex: clHex(solid, withA({ alpha: 'never' })),
574
+ hex8: clHex(parsed, withA({ alpha: 'always' })),
575
+ rgb: clRgbStr(solid, withA({ alpha: 'never' })),
576
+ rgba: clRgbStr(parsed, withA({ alpha: 'always' })),
577
+ hsl: clHslStr(solid, withA({ alpha: 'never' })),
578
+ hsla: clHslStr(parsed, withA({ alpha: 'always' })),
579
+ oklch: clOklchStr(parsed, withA({ alpha: 'auto' })),
580
+ },
581
+ background: {
582
+ input: String(bgInput),
583
+ hex: clHex(bg, withA({ alpha: 'auto' })),
584
+ },
585
+ flattened: {
586
+ hex: clHex(flat, withA({ alpha: 'never' })),
587
+ rgb: clRgbStr({ r: flat.r, g: flat.g, b: flat.b, a: 1 }, withA({ alpha: 'never' })),
588
+ alpha: clRound(flat.a, 4),
589
+ contrast_with_background: clContrast(flat, { r: bg.r, g: bg.g, b: bg.b }),
590
+ },
591
+ contrast: {
592
+ on_white: onWhite,
593
+ on_black: onBlack,
594
+ aa_text_color: onWhite >= 4.5 && onBlack >= 4.5 ? 'both' : onWhite >= 4.5 ? 'white' : onBlack >= 4.5 ? 'black' : 'none',
595
+ },
596
+ css: `:root {\n --color: ${clHex(solid, withA({ alpha: 'never' }))};\n --color-a: ${clRgbStr(parsed, withA({ alpha: 'always' }))};\n --color-oklch: ${clOklchStr(solid, withA({ alpha: 'never' }))};\n}`,
597
+ notes,
598
+ };
599
+
600
+ if (opts.alphaTable !== false) {
601
+ result.alpha_table = clAlphaRows(parsed, bg, step).map((row) => ({
602
+ percent: row.percent,
603
+ alpha: row.alpha,
604
+ rgba: clRgbStr(row.color, withA({ alpha: 'always' })),
605
+ hsla: clHslStr(row.color, withA({ alpha: 'always' })),
606
+ hex8: clHex(row.color, withA({ alpha: 'always' })),
607
+ flattened: clHex(row.flat, withA({ alpha: 'never' })),
608
+ }));
609
+ }
610
+
611
+ if (opts.palette !== false) {
612
+ result.palette = clPalette(parsed).map((row) => ({
613
+ key: row.key,
614
+ hex: clHex(row.color, withA({ alpha: 'never' })),
615
+ oklch: clOklchStr(row.color, withA({ alpha: 'never' })),
616
+ on_white: row.on_white,
617
+ on_black: row.on_black,
618
+ base: row.base,
619
+ chroma_reduced: row.clipped,
620
+ }));
621
+ }
622
+
623
+ return result;
624
+ }
625
+
626
+ export {
627
+ clParseColor, clHex, clRgbStr, clHslStr, clOklchStr, clFlatten, clContrast,
628
+ clAlphaRows, clPalette, clRgbToHsl, clHslToRgb, clRgbToOklch, clOklchToRgb, clFix,
629
+ };