Line data Source code
1 : export type ColorFormat = 'hex' | 'rgb' | 'hsb'
2 : import { memoize } from 'es-toolkit/compat'
3 :
4 : type RGB = { r: number; g: number; b: number }
5 : interface HSB {
6 : h: number
7 : s: number
8 : b: number
9 : }
10 : export interface HSVA {
11 : h: number
12 : s: number
13 : v: number
14 : a: number
15 : }
16 : type HSL = { h: number; s: number; l: number }
17 : type HSLA = { h: number; s: number; l: number; a: number }
18 : type ColorFormatInternal = 'hex' | 'rgb' | 'rgba' | 'hsl' | 'hsla'
19 : interface HSV {
20 : h: number
21 : s: number
22 : v: number
23 : }
24 :
25 : export interface ColorAdjustOptions {
26 : lightness?: number
27 : opacity?: number
28 : }
29 :
30 0 : export function isTransparent(color: string) {
31 0 : if (color === 'transparent') return true
32 0 : if (color[0] === '#') {
33 0 : if (color.length === 5) return color[4] === '0'
34 0 : if (color.length === 9) return color.substring(7) === '00'
35 : }
36 0 : return false
37 : }
38 :
39 27421 : export function rgbToHsl({ r, g, b }: RGB): HSL {
40 27421 : r /= 255
41 27421 : g /= 255
42 27421 : b /= 255
43 27421 : const max = Math.max(r, g, b),
44 27421 : min = Math.min(r, g, b)
45 27421 : let h = 0,
46 27421 : s = 0
47 27421 : const l: number = (max + min) / 2
48 :
49 27421 : if (max !== min) {
50 19384 : const d = max - min
51 19384 : s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
52 19384 : switch (max) {
53 : case r:
54 9747 : h = (g - b) / d + (g < b ? 6 : 0)
55 9747 : break
56 : case g:
57 4801 : h = (b - r) / d + 2
58 4801 : break
59 : case b:
60 4836 : h = (r - g) / d + 4
61 : break
62 : }
63 19384 : h /= 6
64 : }
65 :
66 27421 : return { h, s, l }
67 : }
68 :
69 28828 : export function hexToRgb(hex: string): RGB {
70 28828 : let r = 0,
71 28828 : g = 0,
72 28828 : b = 0
73 28828 : if (hex.length === 4 || hex.length === 5) {
74 18555 : r = parseInt(hex[1] + hex[1], 16)
75 18555 : g = parseInt(hex[2] + hex[2], 16)
76 18555 : b = parseInt(hex[3] + hex[3], 16)
77 10273 : } else if (hex.length === 7 || hex.length === 9) {
78 10273 : r = parseInt(hex.slice(1, 3), 16)
79 10273 : g = parseInt(hex.slice(3, 5), 16)
80 10273 : b = parseInt(hex.slice(5, 7), 16)
81 : }
82 28828 : return { r, g, b }
83 : }
84 :
85 1 : export function hexToInt(hex: string): number {
86 1 : const { r, g, b } = hexToRgb(hex)
87 1 : return (r << 16) | (g << 8) | b
88 : }
89 :
90 232 : export function intToHex(value: number): string {
91 : const normalized = Number.isFinite(value)
92 : ? Math.max(0, Math.min(0xffffff, Math.round(value)))
93 : : 0
94 232 : return `#${normalized.toString(16).padStart(6, '0')}`
95 : }
96 :
97 28 : export function rgbToHex({ r, g, b }: RGB): string {
98 28 : const toHex = (n: number) =>
99 : Math.max(0, Math.min(255, Math.round(n)))
100 : .toString(16)
101 : .padStart(2, '0')
102 28 : return `#${toHex(r)}${toHex(g)}${toHex(b)}`
103 : }
104 :
105 1348 : export function luminance({ r, g, b }: RGB): number {
106 1348 : return 0.299 * r + 0.587 * g + 0.114 * b
107 : }
108 :
109 5 : export function readableTextColor(hex: string): string {
110 5 : const rgb = hexToRgb(hex)
111 5 : let { r, g, b } = rgb
112 5 : const lum = luminance(rgb)
113 5 : const MIN = 130
114 5 : if (lum < MIN) {
115 5 : const t = (MIN - lum) / (255 - lum)
116 5 : r = Math.round(r + (255 - r) * t)
117 5 : g = Math.round(g + (255 - g) * t)
118 5 : b = Math.round(b + (255 - b) * t)
119 : }
120 5 : return `rgb(${r},${g},${b})`
121 : }
122 :
123 1238 : export function textOnColor(hex: string): string {
124 1238 : return luminance(hexToRgb(hex)) > 140 ? '#000' : '#fff'
125 : }
126 :
127 19 : export function hsbToRgb({ h, s, b }: HSB): RGB {
128 : // Normalize
129 19 : const hh = ((h % 360) + 360) % 360
130 19 : const ss = Math.max(0, Math.min(100, s)) / 100
131 19 : const vv = Math.max(0, Math.min(100, b)) / 100
132 :
133 19 : const c = vv * ss
134 19 : const x = c * (1 - Math.abs(((hh / 60) % 2) - 1))
135 19 : const m = vv - c
136 :
137 19 : let rp: number, gp: number, bp: number
138 :
139 19 : if (hh < 60) {
140 5 : rp = c
141 5 : gp = x
142 5 : bp = 0
143 14 : } else if (hh < 120) {
144 0 : rp = x
145 0 : gp = c
146 0 : bp = 0
147 14 : } else if (hh < 180) {
148 5 : rp = 0
149 5 : gp = c
150 5 : bp = x
151 9 : } else if (hh < 240) {
152 0 : rp = 0
153 0 : gp = x
154 0 : bp = c
155 9 : } else if (hh < 300) {
156 8 : rp = x
157 8 : gp = 0
158 8 : bp = c
159 : } else {
160 1 : rp = c
161 1 : gp = 0
162 1 : bp = x
163 : }
164 :
165 19 : return {
166 : r: Math.floor((rp + m) * 255),
167 : g: Math.floor((gp + m) * 255),
168 : b: Math.floor((bp + m) * 255)
169 : }
170 : }
171 :
172 : /**
173 : * Normalize various color inputs (hex, rgb/rgba, hsl/hsla, hsb string/object)
174 : * into lowercase #rrggbb. Falls back to #000000 on invalid inputs.
175 : */
176 0 : export function parseToRgb(color: string): RGB {
177 0 : const format = identifyColorFormat(color)
178 0 : if (!format) return { r: 0, g: 0, b: 0 }
179 :
180 0 : const hsla = parseToHSLA(color, format)
181 0 : if (!isHSLA(hsla)) return { r: 0, g: 0, b: 0 }
182 :
183 : // Convert HSL to RGB
184 0 : const h = hsla.h / 360
185 0 : const s = hsla.s / 100
186 0 : const l = hsla.l / 100
187 :
188 0 : const c = (1 - Math.abs(2 * l - 1)) * s
189 0 : const x = c * (1 - Math.abs(((h * 6) % 2) - 1))
190 0 : const m = l - c / 2
191 :
192 0 : let r: number, g: number, b: number
193 :
194 0 : if (h < 1 / 6) {
195 0 : r = c
196 0 : g = x
197 0 : b = 0
198 0 : } else if (h < 2 / 6) {
199 0 : r = x
200 0 : g = c
201 0 : b = 0
202 0 : } else if (h < 3 / 6) {
203 0 : r = 0
204 0 : g = c
205 0 : b = x
206 0 : } else if (h < 4 / 6) {
207 0 : r = 0
208 0 : g = x
209 0 : b = c
210 0 : } else if (h < 5 / 6) {
211 0 : r = x
212 0 : g = 0
213 0 : b = c
214 : } else {
215 0 : r = c
216 0 : g = 0
217 0 : b = x
218 : }
219 :
220 0 : return {
221 : r: Math.round((r + m) * 255),
222 : g: Math.round((g + m) * 255),
223 : b: Math.round((b + m) * 255)
224 : }
225 : }
226 :
227 2356 : const identifyColorFormat = (color: string): ColorFormatInternal | null => {
228 27421 : if (!color) return null
229 27421 : if (
230 : color.startsWith('#') &&
231 : (color.length === 4 ||
232 : color.length === 5 ||
233 : color.length === 7 ||
234 : color.length === 9)
235 : )
236 27417 : return 'hex'
237 4 : if (/rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*/.test(color))
238 4 : return color.includes('rgba') ? 'rgba' : 'rgb'
239 0 : if (/hsla?\(\s*\d+(\.\d+)?\s*,\s*\d+(\.\d+)?%\s*,\s*\d+(\.\d+)?%/.test(color))
240 0 : return color.includes('hsla') ? 'hsla' : 'hsl'
241 0 : return null
242 : }
243 :
244 2356 : const isHSLA = (color: unknown): color is HSLA => {
245 27421 : if (typeof color !== 'object' || color === null) return false
246 :
247 27421 : return ['h', 's', 'l', 'a'].every(
248 : (key) =>
249 : typeof (color as Record<string, unknown>)[key] === 'number' &&
250 : !isNaN((color as Record<string, number>)[key])
251 : )
252 : }
253 :
254 2 : export function isColorFormat(v: unknown): v is ColorFormat {
255 2 : return v === 'hex' || v === 'rgb' || v === 'hsb'
256 : }
257 :
258 0 : function isHSBObject(v: unknown): v is HSB {
259 0 : if (!v || typeof v !== 'object') return false
260 0 : const rec = v as Record<string, unknown>
261 0 : return (
262 : typeof rec.h === 'number' &&
263 : Number.isFinite(rec.h) &&
264 : typeof rec.s === 'number' &&
265 : Number.isFinite(rec.s) &&
266 : typeof rec.b === 'number' &&
267 : Number.isFinite(rec.b)
268 : )
269 : }
270 :
271 0 : function isHSVObject(v: unknown): v is HSV {
272 0 : if (!v || typeof v !== 'object') return false
273 0 : const rec = v as Record<string, unknown>
274 0 : return (
275 : typeof rec.h === 'number' &&
276 : Number.isFinite(rec.h) &&
277 : typeof rec.s === 'number' &&
278 : Number.isFinite(rec.s) &&
279 : typeof rec.v === 'number' &&
280 : Number.isFinite(rec.v)
281 : )
282 : }
283 :
284 65 : export function toHexFromFormat(val: unknown, format: ColorFormat): string {
285 65 : if (format === 'hex' && typeof val === 'string') {
286 65 : const raw = val.trim().toLowerCase()
287 65 : if (!raw) return '#000000'
288 65 : if (/^[0-9a-f]{3,4}$/.test(raw)) return `#${raw}`
289 65 : if (/^#[0-9a-f]{3,4}$/.test(raw)) return raw
290 65 : if (/^[0-9a-f]{6}$/.test(raw)) return `#${raw}`
291 65 : if (/^#[0-9a-f]{6}$/.test(raw)) return raw
292 0 : if (/^[0-9a-f]{8}$/.test(raw)) return `#${raw}`
293 0 : if (/^#[0-9a-f]{8}$/.test(raw)) return raw
294 0 : return '#000000'
295 : }
296 :
297 65 : if (format === 'rgb' && typeof val === 'string') {
298 : const rgb = parseToRgb(val)
299 0 : return rgbToHex(rgb).toLowerCase()
300 : }
301 :
302 0 : if (format === 'hsb') {
303 0 : if (isHSBObject(val)) {
304 0 : return rgbToHex(hsbToRgb(val)).toLowerCase()
305 : }
306 0 : if (isHSVObject(val)) {
307 0 : const { h, s, v } = val
308 0 : return rgbToHex(hsbToRgb({ h, s, b: v })).toLowerCase()
309 : }
310 0 : if (typeof val === 'string') {
311 0 : const nums = val.match(/\d+(?:\.\d+)?/g)?.map(Number) || []
312 0 : if (nums.length >= 3) {
313 0 : return rgbToHex(
314 : hsbToRgb({ h: nums[0], s: nums[1], b: nums[2] })
315 : ).toLowerCase()
316 : }
317 : }
318 : }
319 0 : return '#000000'
320 : }
321 :
322 27421 : function parseToHSLA(color: string, format: ColorFormatInternal): HSLA | null {
323 27421 : let match: RegExpMatchArray | null
324 :
325 27421 : switch (format) {
326 : case 'hex': {
327 27417 : let a = 1
328 27417 : let hexColor = color
329 27417 : if (color.length === 9) {
330 0 : a = parseInt(color.slice(7, 9), 16) / 255
331 0 : hexColor = color.slice(0, 7)
332 27417 : } else if (color.length === 5) {
333 0 : const aChar = color[4]
334 0 : a = parseInt(aChar + aChar, 16) / 255
335 0 : hexColor = color.slice(0, 4)
336 : }
337 27417 : const hsl = rgbToHsl(hexToRgb(hexColor))
338 27417 : return {
339 : h: Math.round(hsl.h * 360),
340 : s: +(hsl.s * 100).toFixed(1),
341 : l: +(hsl.l * 100).toFixed(1),
342 : a
343 : }
344 : }
345 :
346 : case 'rgb':
347 : case 'rgba': {
348 4 : match = color.match(/\d+(\.\d+)?/g)
349 4 : if (!match || match.length < 3) return null
350 4 : const [r, g, b] = match.map(Number)
351 4 : const hsl = rgbToHsl({ r, g, b })
352 :
353 4 : const a = format === 'rgba' && match[3] ? parseFloat(match[3]) : 1
354 :
355 4 : return {
356 : h: Math.round(hsl.h * 360),
357 : s: +(hsl.s * 100).toFixed(1),
358 : l: +(hsl.l * 100).toFixed(1),
359 : a
360 : }
361 : }
362 :
363 : case 'hsl':
364 : case 'hsla': {
365 0 : match = color.match(/\d+(\.\d+)?/g)
366 0 : if (!match || match.length < 3) return null
367 0 : const [h, s, l] = match.map(Number)
368 : const a = format === 'hsla' && match[3] ? parseFloat(match[3]) : 1
369 0 : return { h, s, l, a }
370 : }
371 : default:
372 0 : return null
373 : }
374 : }
375 :
376 8 : export function rgbToHsv({ r, g, b }: RGB): {
377 : h: number
378 : s: number
379 : v: number
380 : } {
381 8 : r /= 255
382 8 : g /= 255
383 8 : b /= 255
384 8 : const max = Math.max(r, g, b)
385 : const min = Math.min(r, g, b)
386 8 : const d = max - min
387 8 : let h = 0
388 8 : const s = max === 0 ? 0 : (d / max) * 100
389 8 : const v = max * 100
390 :
391 8 : if (d !== 0) {
392 4 : switch (max) {
393 : case r:
394 1 : h = ((g - b) / d + (g < b ? 6 : 0)) * 60
395 1 : break
396 : case g:
397 2 : h = ((b - r) / d + 2) * 60
398 2 : break
399 : case b:
400 1 : h = ((r - g) / d + 4) * 60
401 : break
402 : }
403 : }
404 8 : return { h, s, v }
405 : }
406 :
407 1 : export function normalizeHex(value: string): string | null {
408 1 : const digits = value.trim().replace(/^#/, '')
409 1 : return /^([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(digits) ? `#${digits}` : null
410 : }
411 :
412 8 : export function hexToHsva(hex: string): HSVA {
413 8 : const normalized = hex.startsWith('#') ? hex : `#${hex}`
414 8 : let a = 100
415 8 : let hexColor = normalized
416 :
417 8 : if (normalized.length === 9) {
418 0 : a = Math.round((parseInt(normalized.slice(7, 9), 16) / 255) * 100)
419 0 : hexColor = normalized.slice(0, 7)
420 8 : } else if (normalized.length === 5) {
421 0 : const aChar = normalized[4]
422 0 : a = Math.round((parseInt(aChar + aChar, 16) / 255) * 100)
423 0 : hexColor = normalized.slice(0, 4)
424 : }
425 :
426 : const rgb = hexToRgb(hexColor)
427 : const hsv = rgbToHsv(rgb)
428 8 : return { ...hsv, a }
429 : }
430 :
431 4 : export function hsvaToHex(hsva: HSVA): string {
432 : const rgb = hsbToRgb({ h: hsva.h, s: hsva.s, b: hsva.v })
433 4 : const hex = rgbToHex(rgb)
434 4 : if (hsva.a >= 100) return hex.toLowerCase()
435 : const alphaHex = Math.round((hsva.a / 100) * 255)
436 : .toString(16)
437 : .padStart(2, '0')
438 0 : return `${hex}${alphaHex}`.toLowerCase()
439 : }
440 :
441 2356 : const applyColorAdjustments = (
442 : color: string,
443 : options: ColorAdjustOptions
444 : ): string => {
445 27421 : if (!Object.keys(options).length) return color
446 :
447 27421 : const format = identifyColorFormat(color)
448 27421 : if (!format) {
449 0 : console.warn(`Unsupported color format in color palette: ${color}`)
450 0 : return color
451 : }
452 :
453 27421 : const hsla = parseToHSLA(color, format)
454 27421 : if (!isHSLA(hsla)) {
455 0 : console.warn(`Invalid color values in color palette: ${color}`)
456 0 : return color
457 : }
458 :
459 27421 : if (options.lightness) {
460 24007 : hsla.l = Math.max(0, Math.min(100, hsla.l + options.lightness * 100.0))
461 : }
462 :
463 27421 : if (options.opacity) {
464 1777 : hsla.a = Math.max(0, Math.min(1, options.opacity))
465 : }
466 :
467 27421 : return `hsla(${hsla.h}, ${hsla.s}%, ${hsla.l}%, ${hsla.a})`
468 : }
469 :
470 2356 : export const adjustColor: (
471 : color: string,
472 : options: ColorAdjustOptions
473 : ) => string = memoize(
474 : applyColorAdjustments,
475 : (color: string, options: ColorAdjustOptions): string =>
476 : `${color}-${JSON.stringify(options)}`
477 : )
|