-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
580 lines (527 loc) · 16.2 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
import { colors } from "@robust-ui/theme";
/**
* Represents an RGB color.
*/
interface RGBColor {
r: number;
g: number;
b: number;
}
/**
* Represents a color in the HSL (Hue, Saturation, Lightness) color model.
*/
interface HSLColor {
h: number;
s: number;
l: number;
}
/**
* Represents the variant options for colors.
*/
type Variant =
| "solid"
| "solidLight"
| "solidDark"
| "outline"
| "outlineLight"
| "outlineDark"
| "ghost"
| "ghostLight"
| "ghostDark"
| "link"
| "linkLight"
| "linkDark";
/**
* Converts a number to its corresponding hexadecimal representation.
* @param c - The number to convert.
* @returns The hexadecimal representation of the number.
*/
function componentToHex(c: number): string {
const hex = c.toString(16);
return hex.length === 1 ? "0" + hex : hex;
}
/**
* Converts an RGBA color to its hexadecimal representation.
* @param rgb - The RGB color values.
* @param a - The alpha value (optional).
* @returns The hexadecimal representation of the RGBA color.
*/
function rgbaToHex(rgb: RGBColor, a?: number): string {
const alphaHex = a !== undefined ? componentToHex(Math.round(a * 255)) : "";
return `#${componentToHex(rgb.r)}${componentToHex(rgb.g)}${componentToHex(
rgb.b,
)}${alphaHex}`;
}
/**
* Converts an HSL color to its corresponding hexadecimal representation.
* @param hsl - The HSL color to convert.
* @returns The hexadecimal representation of the HSL color.
*/
function hslToHex(hsl: HSLColor): string {
const { h, s, l } = hsl;
const c = (1 - Math.abs(2 * l - 1)) * s;
const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
const m = l - c / 2;
let r = 0;
let g = 0;
let b = 0;
switch (true) {
case h >= 0 && h < 60:
r = c;
g = x;
break;
case h >= 60 && h < 120:
r = x;
g = c;
break;
case h >= 120 && h < 180:
g = c;
b = x;
break;
case h >= 180 && h < 240:
g = x;
b = c;
break;
case h >= 240 && h < 300:
r = x;
b = c;
break;
default:
r = c;
b = x;
break;
}
return `#${componentToHex(Math.round((r + m) * 255))}${componentToHex(
Math.round((g + m) * 255),
)}${componentToHex(Math.round((b + m) * 255))}`;
}
/**
* Converts a CSS color value to its hexadecimal representation.
*
* @param color - The CSS color value to convert.
* @returns The hexadecimal representation of the color, or undefined if the color value is invalid.
*/
function cssColorToHex(color: string): string | undefined {
if (color.startsWith("#")) {
return color;
} else if (color.startsWith("rgb")) {
const match = color.match(
/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/,
);
if (match) {
const [, r, g, b, a] = match.map(Number);
const rgbColor = { r: r || 0, g: g || 0, b: b || 0 };
return rgbaToHex(
{ r: rgbColor.r, g: rgbColor.g, b: rgbColor.b },
a !== undefined ? a : 1,
);
}
} else if (color.startsWith("hsl")) {
const match = color.match(
/hsla?\((\d+),\s*(\d+)%,\s*(\d+)%(?:,\s*([\d.]+))?\)/,
);
if (match) {
const [, h, s, l] = match.map(Number);
const hslColor = { h: h || 0, s: s || 0, l: l || 0 };
return hslToHex({ h: hslColor.h, s: hslColor.s, l: hslColor.l });
}
}
return undefined;
}
/**
* Checks if a given color is a valid hexadecimal color.
* @param color - The color to be validated.
* @returns True if the color is a valid hexadecimal color, false otherwise.
*/
function isValidHexColor({ color }: { color: string }): boolean {
const hexColorRegex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
return hexColorRegex.test(color);
}
/**
* Adds opacity to a given color.
* @param {Object} options - The options for adding opacity.
* @param {string} options.color - The color to add opacity to.
* @param {number} options.opacity - The opacity value (between 0 and 1).
* @returns {string} The color with added opacity in the RGBA format.
* @throws {Error} If the color format is invalid.
*/
export function addOpacity({
color,
opacity,
}: {
color: string;
opacity: number;
}): string {
const colorRaw = colors[color as keyof typeof colors] || color;
if (!isValidHexColor({ color: colorRaw })) {
throw new Error("Invalid color format");
}
const r = parseInt(colorRaw.slice(1, 3), 16);
const g = parseInt(colorRaw.slice(3, 5), 16);
const b = parseInt(colorRaw.slice(5, 7), 16);
return `rgba(${r}, ${g}, ${b}, ${opacity})`;
}
/**
* Generates a contrasting color based on the provided base color.
* The base color should be in the RGBA format.
* If the base color is not in the expected format, an error will be thrown.
* The contrast color is calculated by determining the grayscale value of the base color,
* and then setting the brightness to either 0 or 255 based on the grayscale value.
* The contrast alpha is calculated by multiplying the base alpha by 2.5, with a maximum value of 1.
* @param baseColor The base color in the RGBA format.
* @returns The contrasting color in the RGBA format.
* @throws Error if the base color is not in the expected format.
*/
export function generateContrastingColor(baseColor: string): string {
// Regex for matching RGBA format
const rgbaMatch = baseColor.match(
/^rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)$/,
);
// Check if the input color is in the expected format
if (!rgbaMatch) {
throw new Error("Invalid color format. Please provide a valid RGBA color.");
}
// Extract RGBA components from the match
const baseRed = parseInt(rgbaMatch[1] || "0", 10);
const baseGreen = parseInt(rgbaMatch[2] || "0", 10);
const baseBlue = parseInt(rgbaMatch[3] || "0", 10);
const baseAlpha = parseFloat(rgbaMatch[4] || "1");
// Calculate grayscale value
const baseGrayscaleValue =
0.299 * baseRed + 0.587 * baseGreen + 0.114 * baseBlue;
// Calculate contrast brightness (either 0 or 255)
const contrastBrightness = baseGrayscaleValue > 128 ? 0 : 255;
// Calculate contrast alpha (limited to 1)
const contrastAlpha = Math.min(baseAlpha * 2.5, 1);
// Generate and return the contrasting color
const contrastColor = `rgba(${contrastBrightness}, ${contrastBrightness}, ${contrastBrightness}, ${contrastAlpha})`;
return contrastColor;
}
/**
* Calculates the complementary color of an RGBA color.
*
* @param rgbaColor - The RGBA color to calculate the complementary color for.
* @returns The complementary color in RGBA format.
* @throws Error if the provided color is not in valid RGBA format.
*/
function calculateComplementaryColor(rgbaColor: string): string {
const match = rgbaColor.match(
/^rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)$/,
);
if (!match) {
throw new Error("Invalid color format. Please provide a valid RGBA color.");
}
const red = parseInt(match[1] || "0", 10);
const green = parseInt(match[2] || "0", 10);
const blue = parseInt(match[3] || "0", 10);
const alpha = parseFloat(match[4] || "1");
// Calculate complementary colors
const complementaryRed = 255 - red;
const complementaryGreen = 255 - green;
const complementaryBlue = 255 - blue;
// Ensure alpha is within the valid range [0, 1]
const validAlpha = Math.min(Math.max(alpha, 0), 1);
// Generate and return the complementary color
const complementaryColor = `rgba(${complementaryRed}, ${complementaryGreen}, ${complementaryBlue}, ${validAlpha})`;
return complementaryColor;
}
/**
* Generates a random hexadecimal color code.
*
* @returns A string representing a random hexadecimal color code.
*/
export function getRandomHexColor(): string {
const randomColor = `#${Math.floor(Math.random() * 16777215)
.toString(16)
.padStart(6, "0")}`;
return randomColor;
}
/**
* Generates a color scheme based on the provided options.
*
* @param options - The options for generating the color scheme.
* @returns The generated color scheme.
*/
export function generateColorScheme({
complementaryColor = false,
isActivated = true,
isDisabled = false,
baseColor = "teal",
isInvalid = false,
isValid = false,
variant = "solid",
opacity = 0.7,
props,
}: {
baseColor?: keyof typeof colors | string;
complementaryColor?: boolean;
isActivated?: boolean;
isDisabled?: boolean;
isInvalid?: boolean;
isValid?: boolean;
variant: Variant;
opacity?: number;
props?: {
background?: boolean;
border?: boolean;
active?: boolean;
hover?: boolean;
focus?: boolean;
};
}) {
if (!isActivated) {
return {};
}
const variantWithoutMode = variant.replace("Light", "").replace("Dark", "");
const propsRaw = {
active: variantWithoutMode.includes("link") ? true : false,
hover: variantWithoutMode.includes("link") ? true : false,
focus: variantWithoutMode.includes("link") ? true : false,
background: true,
border: true,
...props,
};
const baseColorRaw = isDisabled
? colors["gray"]
: isInvalid
? colors["red"]
: isValid
? colors["green"]
: colors[baseColor as keyof typeof colors] || baseColor;
const colorHexa = cssColorToHex(baseColorRaw) || baseColorRaw;
const mainColorLowOpacity = addOpacity({
color: colorHexa,
opacity: opacity * 0.1,
});
const mainColorWithMiddleOpacity = addOpacity({
color: colorHexa,
opacity: opacity * 1.2,
});
const mainColorWithHighOpacity = addOpacity({
color: colorHexa,
opacity: opacity * 1.4,
});
const mainColorWithOpacity = addOpacity({ color: colorHexa, opacity });
const mainColorText =
variantWithoutMode === "link"
? colorHexa
: generateContrastingColor(mainColorWithOpacity);
const textColor = isDisabled
? mainColorText
: isInvalid || isValid
? variant.includes("Light")
? colors["white"]
: variant.includes("Dark")
? colors["black"]
: mainColorText
: variant.includes("Light")
? colors["white"]
: variant.includes("Dark")
? colors["black"]
: mainColorText;
if (isInvalid && isValid && !isDisabled) {
throw new Error(
"Input can't be invalid and valid at the same time. Please check your code.",
);
}
const variantStyles = {
link: {
backgroundRaw: "transparent",
colorRaw: textColor,
borderRadiusRaw: "0.5dvh",
outlineRaw: "none",
borderRaw: "0.5dvh solid transparent",
hoverRaw: propsRaw.hover
? {
outlineRaw: "none",
backgroundRaw: "transparent",
colorRaw: textColor,
borderBottom: `0.5dvh solid ${mainColorWithHighOpacity}`,
}
: {
outlineRaw: "none",
backgroundRaw: "transparent",
colorRaw: textColor,
borderRaw: "0.5dvh solid transparent",
},
focusRaw: propsRaw.focus
? {
outlineRaw: "none",
backgroundRaw: "transparent",
colorRaw: textColor,
borderBottom: `0.5dvh solid ${mainColorWithHighOpacity}`,
}
: {
outlineRaw: "none",
backgroundRaw: "transparent",
colorRaw: textColor,
borderRaw: "0.5dvh solid transparent",
},
activeRaw: propsRaw.active
? {
outlineRaw: "none",
backgroundRaw: "transparent",
colorRaw: textColor,
borderBottom: `0.5dvh solid ${mainColorWithHighOpacity}`,
}
: {
outlineRaw: "none",
backgroundRaw: "transparent",
colorRaw: textColor,
borderRaw: "0.5dvh solid transparent",
},
},
outline: {
backgroundRaw: propsRaw.background ? mainColorLowOpacity : "transparent",
colorRaw: mainColorWithOpacity,
outlineRaw: "none",
boxShadowRaw: "0 0.5dvh 1dvh rgba(0, 0, 0, 0.15)",
borderRaw: propsRaw.border
? `0.5dvh solid ${mainColorWithMiddleOpacity}`
: "0.5dvh solid transparent",
hoverRaw: propsRaw.hover
? {
outlineRaw: "none",
backgroundRaw: propsRaw.background
? mainColorWithOpacity
: "transparent",
colorRaw: textColor,
borderRaw: "0.5dvh solid transparent",
}
: {
outlineRaw: "none",
backgroundRaw: propsRaw.background
? mainColorLowOpacity
: "transparent",
colorRaw: mainColorWithOpacity,
borderRaw: propsRaw.border
? `0.5dvh solid ${mainColorWithMiddleOpacity}`
: "0.5dvh solid transparent",
},
focusRaw: propsRaw.focus
? {
outlineRaw: "none",
backgroundRaw: propsRaw.background
? mainColorWithOpacity
: "transparent",
colorRaw: textColor,
borderRaw: "0.5dvh solid transparent",
}
: {
outlineRaw: "none",
backgroundRaw: propsRaw.background
? mainColorLowOpacity
: "transparent",
colorRaw: mainColorWithOpacity,
borderRaw: propsRaw.border
? `0.5dvh solid ${mainColorWithMiddleOpacity}`
: "0.5dvh solid transparent",
},
activeRaw: propsRaw.active
? {
outlineRaw: "none",
backgroundRaw: propsRaw.background
? mainColorWithOpacity
: "transparent",
colorRaw: textColor,
borderRaw: "0.5dvh solid transparent",
}
: {
outlineRaw: "none",
backgroundRaw: propsRaw.background
? mainColorLowOpacity
: "transparent",
colorRaw: mainColorWithOpacity,
borderRaw: propsRaw.border
? `0.5dvh solid ${mainColorWithMiddleOpacity}`
: "0.5dvh solid transparent",
},
},
solid: {
backgroundRaw: propsRaw.background ? mainColorWithOpacity : "transparent",
colorRaw: textColor,
outlineRaw: "none",
boxShadowRaw: "0 0.5dvh 1dvh rgba(0, 0, 0, 0.15)",
borderRaw: "0.5dvh solid transparent",
hoverRaw: propsRaw.hover
? {
backgroundRaw: mainColorWithHighOpacity,
outlineRaw: "none",
}
: {
backgroundRaw: propsRaw.background
? mainColorWithOpacity
: "transparent",
outlineRaw: "none",
},
focusRaw: propsRaw.focus
? {
backgroundRaw: mainColorWithHighOpacity,
outlineRaw: "none",
}
: {
backgroundRaw: propsRaw.background
? mainColorWithOpacity
: "transparent",
outlineRaw: "none",
},
activeRaw: propsRaw.active
? {
backgroundRaw: mainColorWithHighOpacity,
outlineRaw: "none",
}
: {
backgroundRaw: propsRaw.background
? mainColorWithOpacity
: "transparent",
outlineRaw: "none",
},
},
ghost: {
backgroundRaw: "transparent",
colorRaw: textColor,
outlineRaw: "none",
boxShadowRaw: "none",
borderRaw: "0.5dvh solid transparent",
hoverRaw: propsRaw.hover
? {
backgroundRaw: mainColorWithOpacity,
outlineRaw: "none",
}
: {
backgroundRaw: "transparent",
outlineRaw: "none",
},
focusRaw: propsRaw.focus
? {
backgroundRaw: mainColorWithOpacity,
outlineRaw: "none",
}
: {
backgroundRaw: "transparent",
outlineRaw: "none",
},
activeRaw: propsRaw.active
? {
backgroundRaw: mainColorWithOpacity,
outlineRaw: "none",
}
: {
backgroundRaw: "transparent",
outlineRaw: "none",
},
},
};
if (!variantStyles[variantWithoutMode as keyof typeof variantStyles]) {
throw new Error(`Invalid variant: ${variant}`);
}
const result =
variantStyles[variantWithoutMode as keyof typeof variantStyles];
if (complementaryColor) {
return {
...variantStyles[variantWithoutMode as keyof typeof variantStyles],
complementaryColor: calculateComplementaryColor(mainColorWithOpacity),
};
}
return result;
}