-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcouleur.ts
1914 lines (1620 loc) · 73.8 KB
/
couleur.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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ColorProperty, ColorSpace, ColorSpaceWithGamut, ColorSpaceWithoutGamut, default as colorSpaces } from './color-spaces.js';
import * as Contrasts from './contrasts.js';
import * as Conversions from './conversion.js';
import { CSSFormat, allFormats as allCssFormats, unitRegExps } from './css-formats.js';
import * as Distances from './distances.js';
import { default as Graph, GraphNode, PathNotFoundError, UndefinedNodeError } from './graph.js';
import namedColors from './named-colors.js';
import * as Utils from './utils.js';
/* Type definitions */
type colorString = string;
type colorArray = number[];
type colorObject = { r: number, g: number, b: number, a?: number };
type color = Couleur | colorObject | colorArray | colorString;
type cssColorFormatWithNamedProperties = 'srgb'|'rgb'|'rgba'|'hsl'|'hsla'|'hwb'|'lab'|'lch'|'oklab'|'oklch';
type colorSpaceID = string;
type colorSpaceOrID = ColorSpace | colorSpaceID;
type unparsedValue = number | string;
type unparsedAlphaValue = number | `${number}%`;
type unparsedPercentage = unparsedAlphaValue;
type parsedValue = number;
interface makeExprOptions {
precision?: number
}
interface exprOptions extends makeExprOptions {
clamp?: boolean;
}
type toGamutMethod = 'okchroma' | 'naive';
interface toGamutOptions {
method?: toGamutMethod;
}
type contrastMethod = 'apca' | 'wcag2';
interface contrastOptions {
method?: contrastMethod;
}
interface improveContrastOptions {
as?: 'text' | 'background';
lower?: boolean;
colorScheme?: 'light' | 'dark';
method?: contrastMethod;
}
type distanceMethod = 'ciede2000' | 'deltae2000' | 'deltaeok' | 'euclidean';
interface distanceOptions {
method?: distanceMethod;
alpha?: boolean;
}
interface sameOptions {
tolerance?: number;
method?: distanceMethod;
}
interface interpolateOptions {
ratio?: unparsedPercentage;
interpolationSpace?: colorSpaceOrID;
hueInterpolationMethod?: 'shorter' | 'longer' | 'increasing' | 'decreasing';
}
type mixOptions = Omit<interpolateOptions, 'ratio'>;
/* Error definitions */
export class InvalidColorStringError extends Error {
constructor(color: color) {
super(`${JSON.stringify(color)} is not a valid color format`);
}
}
export class InvalidColorPropValueError extends Error {
constructor (prop: ColorProperty, value: unparsedValue) {
super(`Invalid ${JSON.stringify(prop)} value: ${JSON.stringify(value)}`);
}
}
export class InvalidColorAngleValueError extends Error {
constructor(value: unparsedValue) {
super(`Invalid angle value: ${JSON.stringify(value)}`);
}
}
export class InvalidColorArbitraryValueError extends Error {
constructor(value: unparsedValue) {
super(`Invalid arbitrary value: ${JSON.stringify(value)}`);
}
}
export class ColorFormatHasNoSuchPropertyError extends Error {
constructor(format: string, prop: ColorProperty) {
super(`Format ${format} does not have a property called ${prop}`);
}
}
export class ImpossibleColorConversionError extends Error {
constructor(startSpace: ColorSpace, endSpace: ColorSpace) {
super(`Conversion from ${JSON.stringify(startSpace.id)} space to ${JSON.stringify(endSpace.id)} space is impossible`);
}
}
export class UnsupportedColorSpaceError extends Error {
constructor(id: string) {
super(`${JSON.stringify(id)} is not a supported color space`);
}
}
export class UndefinedConversionError extends Error {
constructor(functionName: string) {
super(`Conversion function ${functionName} does not exist`);
}
}
export class UnsupportedMethodError extends Error {
constructor(methodName: string, action: string) {
super(`${methodName} is not a supported method for ${action}`);
}
}
/** Graph with added cache for shortestPath() results. */
class GraphWithCachedPaths extends Graph {
#cache = new Map();
shortestPath(startID: string | number, endID: string | number): GraphNode[] {
const id = `${startID}_to_${endID}`;
let cachedPath = this.#cache.get(id);
// If the path from startID to endID isn't cached, check if the reverse path
// from endID to startID is cached. Since every conversion path is reversible,
// we only need to store half of them in cache!
if (!cachedPath) {
const reversedPath = this.#cache.get(`${endID}_to_${startID}`);
cachedPath = reversedPath ? [...reversedPath].reverse() : null;
}
if (cachedPath) return cachedPath;
const path = super.shortestPath(startID, endID);
this.#cache.set(id, path);
return path;
}
}
/**
* Colori module
* @author Remiscan <https://remiscan.fr>
* @module colori.js
*/
const colorSpacesGraph = new GraphWithCachedPaths(colorSpaces);
/** @class Couleur */
export default class Couleur {
#r: number = 0;
#g: number = 0;
#b: number = 0;
#a: number = 0;
#cache: Map<colorSpaceID, number[]> = new Map();
/**
* Creates a new Couleur object that contains r, g, b, a properties of the color.
* These properties will take their values from sRGB color space, even if they're out of bounds.
* (This means values <0 or >1 can be stored — they can be clamped to a specific color space when needed.)
* @param color Color expression in a supported type.
* @throws When the parameter is not of a supported type.
*/
constructor(color: color) {
if (color instanceof Couleur || (typeof color === 'object' && 'r' in color && 'g' in color && 'b' in color)) {
this.#r = color.r;
this.#g = color.g;
this.#b = color.b;
this.#a = typeof color.a === 'number' ? color.a : 1;
}
else if (Array.isArray(color) && (color.length == 3 || color.length == 4)) {
[this.#r, this.#g, this.#b] = color.slice(0, 3);
this.#a = Math.max(0, Math.min(Number(Utils.toUnparsedAlpha(color[3])), 1));
}
else if (typeof color === 'string') {
const format = Couleur.matchSyntax(color.trim());
switch (format.id) {
case 'hex':
this.setHex([format.data[1], format.data[2], format.data[3], Utils.toUnparsedAlpha(format.data[4], 'ff')]);
break;
case 'rgb':
case 'hsl':
case 'hwb':
case 'lab':
case 'lch':
case 'oklab':
case 'oklch': {
const values = [format.data[1], format.data[2], format.data[3], Utils.toUnparsedAlpha(format.data[4])];
const props: ColorProperty[] = [...Couleur.propertiesOf(format.id), 'a'];
const space = Couleur.getSpace(format.id);
this.set(values, props, space);
} break;
case 'color':
this.setColor(format.data[1], [format.data[2], format.data[3], format.data[4], Utils.toUnparsedAlpha(format.data[5])]);
break;
default:
throw new InvalidColorStringError(color);
}
}
else throw new Error(`Couleur objects can only be created from a string, an array of parsed values, or another Couleur object ; this is not one: ${JSON.stringify(color)}`);
}
/**
* Makes a Couleur from the argument if it's not one already.
* @param color
* @returns
*/
protected static makeInstance(color: color): Couleur {
if (color instanceof Couleur) return color;
else return new Couleur(color);
}
/**
* Matches the user input with supported color formats.
* @param colorString Color expression in a supported format.
* @returns Recognized syntax.
* @throws When colorString is not in a valid format.
*/
private static matchSyntax(colorString: colorString): { id: string, data: string[] } {
const tri = colorString.slice(0, 3);
// Predetermine the format, to save regex-matching time
let format: CSSFormat | undefined;
if (tri.slice(0, 1) === '#') format = allCssFormats[0];
else switch (tri) {
case 'rgb': format = allCssFormats[1]; break;
case 'hsl': format = allCssFormats[2]; break;
case 'hwb': format = allCssFormats[3]; break;
case 'lab': format = allCssFormats[4]; break;
case 'lch': format = allCssFormats[5]; break;
case 'okl': {
if (colorString.startsWith('oklab')) { format = allCssFormats[6]; }
else if (colorString.startsWith('oklch')) { format = allCssFormats[7]; }
} break;
case 'col': format = allCssFormats[8]; break;
default: format = allCssFormats[9];
}
if (format == null) throw new Error('No matching format');
// Check if the given string matches any color syntax
for (const syntaxe of format.syntaxes) {
const result = colorString.match(syntaxe);
if (result != null && result[0] === colorString) {
if (format.id === 'name') {
if (colorString === 'transparent') return { id: 'rgb', data: ['', '0', '0', '0', '0'] };
const allNames = Couleur.namedColors;
const hex = allNames.get(colorString.toLowerCase()) || null;
if (hex) return Couleur.matchSyntax(`#${hex}`);
} else {
return { id: format.id, data: result };
}
}
}
throw new InvalidColorStringError(colorString);
}
/**
* Parses a number / percentage / angle into the correct format to store it.
* @param value The value to parse.
* @param prop The color property that has n as its value.
* @param options
* @param options.clamp Whether the value should de clamped to its color space bounds.
* @returns The properly parsed number.
* @throws When the value isn't in a supported format for the corresponding property.
*/
private static parse(value: unparsedValue, prop: ColorProperty | null = null, { clamp = true } = {}): number {
const val = String(value);
const nval = parseFloat(val);
switch (prop) {
// Alpha values:
// from any % or any number
// clamped to [0, 100]% or [0, 1]
// to [0, 1]
case 'a': {
// If n is a percentage
if (new RegExp('^' + unitRegExps.percentage + '$').test(val)) {
if (clamp) return Math.max(0, Math.min(nval / 100, 1));
else return nval / 100;
}
// If n is a number
else if (new RegExp('^' + unitRegExps.number + '$').test(val)) {
if (clamp) return Math.max(0, Math.min(nval, 1));
else return nval;
}
else throw new InvalidColorPropValueError(prop, value);
}
// Red, green, blue values:
// from any % or any number
// clamped to [0, 100]% or [0, 255]
// to [0, 1]
case 'r':
case 'g':
case 'b': {
// If n is a percentage
if (new RegExp('^' + unitRegExps.percentage + '$').test(val)) {
if (clamp) return Math.max(0, Math.min(nval / 100, 1));
else return nval / 100;
}
// If n is a number
else if (new RegExp('^' + unitRegExps.number + '$').test(val)) {
if (clamp) return Math.max(0, Math.min(nval / 255, 1));
else return nval / 255;
}
else throw new InvalidColorPropValueError(prop, value);
}
// Hue and CIE hue values:
// from any angle or any number
// clamped to [0, 360]deg or [0, 400]grad or [0, 2π]rad or [0, 1]turn
// to [0, 360]
case 'h':
case 'cieh':
case 'okh': {
let h = nval;
// If n is a number
if (new RegExp('^' + unitRegExps.number + '$').test(val)) {
return Utils.angleToRange(h);
}
// If n is an angle
else if ((new RegExp('^' + unitRegExps.angle + '$').test(val))) {
if (val.slice(-3) === 'deg') {} // necessary to accept deg values
else if (val.slice(-4) === 'grad')
h = h * 360 / 400;
else if (val.slice(-3) === 'rad')
h = h * 180 / Math.PI;
else if (val.slice(-4) === 'turn')
h = h * 360;
else throw new InvalidColorAngleValueError(value);
return Utils.angleToRange(h);
}
else throw new InvalidColorPropValueError(prop, value);
}
// CIE and OK luminosity values:
// from any number or %
// to [0, 1]
case 'ciel':
case 'okl': {
// If n is a percentage
if (new RegExp('^' + unitRegExps.percentage + '$').test(val)) {
if (clamp) return Math.max(0, Math.min(nval / 100, 1));
else return nval / 100;
}
// If n is a number
else if (new RegExp('^' + unitRegExps.number + '$').test(val)) {
if (clamp) return Math.max(0, Math.min(nval, 1));
else return nval;
}
else throw new InvalidColorPropValueError(prop, value);
}
// CIE A and B axis values:
// from any number or %
// to any number (so that -100% becomes -125 and 100% becomes 125)
case 'ciea':
case 'cieb': {
// If n is a percentage
if (new RegExp('^' + unitRegExps.percentage + '$').test(val)) {
return 125 * nval / 100;
}
// If n is a number
else if (new RegExp('^' + unitRegExps.number + '$').test(val)) {
return nval;
}
else throw new InvalidColorPropValueError(prop, value);
}
// CIE chroma values:
// from any number or %
// to any number (so that 0% becomes 0 and 100% becomes 150)
case 'ciec': {
// If n is a percentage
if (new RegExp('^' + unitRegExps.percentage + '$').test(val)) {
if (clamp) return Math.max(0, 150 * nval / 100);
else return 150 * nval / 100;
}
// If n is a number
else if (new RegExp('^' + unitRegExps.number + '$').test(val)) {
if (clamp) return Math.max(0, nval);
else return nval;
}
else throw new InvalidColorPropValueError(prop, value);
}
// OK A and B axis values:
// from any number or %
// to any number (so that -100% becomes -0.4 and 100% becomes 0.4)
case 'oka':
case 'okb': {
// If n is a percentage
if (new RegExp('^' + unitRegExps.percentage + '$').test(val)) {
return 0.4 * nval / 100;
}
// If n is a number
else if (new RegExp('^' + unitRegExps.number + '$').test(val)) {
return nval;
}
else throw new InvalidColorPropValueError(prop, value);
}
// OK chroma values:
// from any number or %
// to any number (so that 0% becomes 0 and 100% becomes 0.4)
case 'okc': {
// If n is a percentage
if (new RegExp('^' + unitRegExps.percentage + '$').test(val)) {
if (clamp) return Math.max(0, 0.4 * nval / 100);
else return 0.4 * nval / 100;
}
// If n is a number
else if (new RegExp('^' + unitRegExps.number + '$').test(val)) {
if (clamp) return Math.max(0, nval);
else return nval;
}
else throw new InvalidColorPropValueError(prop, value);
}
// Percentage values:
// from any %
// clamped to [0, 100]%
// to [0, 1]
case 's':
case 'l':
case 'w':
case 'bk': {
// If n is a percentage
if (new RegExp('^' + unitRegExps.percentage + '$').test(val)) {
if (clamp) return Math.max(0, Math.min(nval / 100, 1));
else return nval / 100;
}
else throw new InvalidColorPropValueError(prop, value);
}
// Arbitrary values
// from any % or any number
// to any number (so that 0% becomes 0 and 100% becomes 1)
default: {
// If n is a percentage
if (new RegExp('^' + unitRegExps.percentage + '$').test(val)) {
return nval / 100;
}
// If n is a number
else if (new RegExp('^' + unitRegExps.number + '$').test(val)) {
return nval;
}
else throw new InvalidColorArbitraryValueError(value); // doesn't match any property value at all
}
}
}
/**
* Unparses a value to the format that would be used in a CSS expression.
* @param value Value to unparse.
* @param prop Name of the property that has the value.
* @param options
* @param options.precision How many decimals to display.
* @returns The unparsed value, ready to insert in a CSS expression.
*/
private static unparse(value: number, prop: ColorProperty | null, { precision = 0 } = {}): string {
switch (prop) {
case 'r':
case 'g':
case 'b':
return precision === null ? `${255 * value}` : `${Math.round(10**precision * 255 * value) / (10**precision)}`;
case 's':
case 'l':
case 'w':
case 'bk':
case 'ciel':
case 'okl':
return precision === null ? `${100 * value}%` : `${Math.round(10**precision * 100 * value) / (10**precision)}%`;
case 'ciea':
case 'cieb':
return precision === null ? `${100 * value / 125}%` : `${Math.round(10**precision * 100 * value / 125) / (10**precision)}%`;
case 'ciec':
return precision === null ? `${100 * value / 150}%` : `${Math.round(10**precision * 100 * value / 150) / (10**precision)}%`;
case 'oka':
case 'okb':
case 'okc':
return precision === null ? `${100 * value / .4}%` : `${Math.round(10**precision * 100 * value / .4) / (10**precision)}%`;
case 'a':
return precision === null ? `${value}` : `${Math.round(10**Math.max(precision, 2) * value) / (10**Math.max(precision, 2))}`;
default:
return precision === null ? `${value}` : `${Math.round(10**precision * value) / (10**precision)}`;
}
}
/**
* Calculates all properties of a color from given unparsed values in a given color space.
* @param data Array of unparsed values.
* @param props Array of color property names the values correspond to.
* @param sourceSpaceID Color space of the values, or its identifier.
* @param options
* @param options.parsed Whether the provided values are already parsed.
*/
private set(data: Array<string|number>, props: Array<ColorProperty|null>, sourceSpaceID: colorSpaceOrID, { parsed = false } = {}) {
const sourceSpace = Couleur.getSpace(sourceSpaceID);
const values = parsed ? data.map(v => Number(v)) : props.map((p, i) => Couleur.parse(data[i], p));
[this.#r, this.#g, this.#b] = Couleur.convert(sourceSpace, 'srgb', values);
this.#a = Couleur.parse(Utils.toUnparsedAlpha(data[3]), 'a');
}
/**
* Calculates all properties of the color from its hexadecimal expression.
* @param hexa The hexadecimal values of the r, g, b, a properties.
*/
private setHex(hexa: Array<string|number>) {
let [r, g, b] = hexa.map(v => String(v));
let a = String(hexa[3]) || 'ff';
const vals = Utils.fromHex([r, g, b, a])
.map((v, k) => k === 3 ? v : v * 255);
this.set(vals, ['r', 'g', 'b'], 'srgb');
}
/**
* Calculates all properties of the color from its functional color() expression.
* @param sourceSpaceID Identifier of the color space.
* @param values The parsed values of the color's properties.
* @throws When the color space is not supported.
*/
private setColor(sourceSpaceID: string, values: Array<string|number>): void {
let vals = values.slice(0, 3).map(v => Couleur.parse(v));
const a = Couleur.parse(values[3]);
vals = Couleur.convert(sourceSpaceID, 'srgb', vals);
const rgba = [...vals, a];
return this.set(rgba, [null, null, null], 'srgb');
}
/*****************************/
/* Getters for color formats */
/*****************************/
/* GENERAL EXPRESSION MAKER */
/**
* Creates a string containing the CSS expression of a color.
* @param format Identifier of the color space of the requested CSS expression.
* @param options @see Couleur.makeString
*/
public toString(format: string = 'rgb', { precision = 2, clamp = false }: exprOptions = {}): string {
format = format.toLowerCase();
const destinationSpaceID = format.replace('color-', '');
const destinationSpace = Couleur.getSpace(destinationSpaceID);
const props = Couleur.propertiesOf(destinationSpace.id);
let values = this.valuesTo(destinationSpace, { clamp }).map((v, k) => this.isPowerless(props[k]) ? 0 : v);
return Couleur.makeString(format, [...values, this.a], { precision });
}
/**
* Creates a string containing the CSS expression of a color from a list of values.
* @param format Identifier of the color space of the requested CSS expression.
* @param values The values of the properties in the given format.
* @param options
* @param options.precision How many decimals to display.
* @param options.clamp Which color space the values should be clamped to.
* @returns The expression of the color in the requested format.
*/
public static makeString(format: string, values: number[], { precision = 2 }: makeExprOptions = {}): string {
format = format.toLowerCase();
const destinationSpaceID = format.replace('color-', '');
const destinationSpace = Couleur.getSpace(destinationSpaceID);
const a = Number(Couleur.unparse(values[3] ?? 1, 'a', { precision }));
values = [...values.slice(0, 3), a];
// If the requested expression is of the color(space, ...) type
if (format.toLowerCase().slice(0, 5) === 'color') {
values = values.map(v => precision === null ? v : Math.round(10**precision * v) / (10**precision));
if (a < 1)
return `color(${destinationSpace.id} ${values.slice(0, -1).join(' ')} / ${a})`;
else
return `color(${destinationSpace.id} ${values.slice(0, -1).join(' ')})`;
}
// If the requested expression is of the ${format}(...) type
else {
const props = Couleur.propertiesOf(format);
if (props.length === 0) return Couleur.makeString(`color-${format}`, values, { precision });
const unparsedValues = props.map((p, k) => Couleur.unparse(values[k], p, { precision }));
switch (format.toLowerCase()) {
case 'rgb':
case 'rgba':
case 'hsl':
case 'hsla': {
if ((format.length > 3 && format.slice(-1) === 'a') || a < 1)
return `${format}(${unparsedValues.join(', ')}, ${a})`;
else
return `${format}(${unparsedValues.join(', ')})`;
}
default: {
if (a < 1) return `${format}(${unparsedValues.join(' ')} / ${a})`;
else return `${format}(${unparsedValues.join(' ')})`;
}
}
}
}
/* ALL VALUES (r, g, b) */
/** @returns The array of r, g, b values of the color in sRGB color space. */
public get values(): number[] { return [this.r, this.g, this.b]; }
/* NAME */
/** @returns The approximate name of the color. */
public get name(): string | null {
if (this.a === 1) {
const allNames = Couleur.namedColors;
const rgb1 = this.values;
const tolerance = .0004;
for (const [name, hex] of allNames.entries()) {
const rgb2 = Utils.fromHex([`${hex[0]}${hex[1]}`, `${hex[2]}${hex[3]}`, `${hex[4]}${hex[5]}`]);
// Euclidean distance isn't great but at least it's performant...
if (Distances.euclidean(rgb1, rgb2) < tolerance) return name;
}
return null;
}
else if (this.a === 0) return 'transparent';
else return null;
}
/** @returns The exact name of the color. */
public get exactName(): string | null {
if (this.a === 1) {
const allNames = Couleur.namedColors;
const hex6 = this.hex.slice(1);
for (const [name, hex] of allNames.entries()) {
if (hex === hex6) return name;
}
return null;
}
else if (this.a === 0) return 'transparent';
else return null;
}
/** @returns The name of the closest named color. */
public get closestName(): string {
if (this.a < .5) return 'transparent';
const allNames = Couleur.namedColors;
const rgb1 = this.values;
let closest: string = '';
let lastDistance = +Infinity;
for (const [name, hex] of allNames.entries()) {
const rgb2 = Utils.fromHex([`${hex[0]}${hex[1]}`, `${hex[2]}${hex[3]}`, `${hex[4]}${hex[5]}`]);
// Euclidean distance isn't great but at least it's performant...
const distance = Distances.euclidean(rgb1, rgb2);
if (distance < lastDistance) {
lastDistance = distance;
closest = name;
}
}
return closest;
}
/* CSS FORMATS */
/** @returns Hexadecimal expression of the color. */
public get hex(): string {
const values = Couleur.valuesToGamut('srgb', this.values);
const rgb = Utils.toHex([...values, this.a]);
if (this.a < 1) return `#${rgb[0]}${rgb[1]}${rgb[2]}${rgb[3]}`;
else return `#${rgb[0]}${rgb[1]}${rgb[2]}`;
}
/** @returns RGB expression of the color. */
public get rgb(): string { return this.toString('rgb', { precision: 2, clamp: true }); }
public get rgba(): string { return this.rgb; }
/** @returns HSL expression of the color. */
public get hsl(): string { return this.toString('hsl', { precision: 2, clamp: true }); }
public get hsla(): string { return this.hsl; }
/** @returns HWB expression of the color. */
public get hwb(): string { return this.toString('hwb', { precision: 2, clamp: true }); }
/** @returns LAB expression of the color. */
public get lab(): string { return this.toString('lab', { precision: 2, clamp: true }); }
/** @returns LCH expression of the color. */
public get lch(): string { return this.toString('lch', { precision: 2, clamp: true }); }
/** @returns OKLAB expression of the color. */
public get oklab(): string { return this.toString('oklab', { precision: 2, clamp: true }); }
/** @returns OKLCH expression of the color. */
public get oklch(): string { return this.toString('oklch', { precision: 2, clamp: true }); }
/********************************************/
/* Setters and getters for color properties */
/********************************************/
/**
* Recalculates the r, g, b properties of the color after modifying one of its other properties.
* @param val The parsed new value of the property.
* @param prop The property to change.
* @param format The id of the CSS format the property belongs to.
* @throws When the CSS format doesn't have the requested property.
*/
private recompute(val: number | string, prop: ColorProperty, format: string) {
const props: ColorProperty[] = [...Couleur.propertiesOf(format), 'a'];
if (!props.includes(prop))
throw new ColorFormatHasNoSuchPropertyError(format, prop);
const parsedVal = (typeof val === 'string') ? Couleur.parse(val, prop) : val;
const oldValues = [...this.valuesTo(format), this.a];
const newValues = props.map((p, k) => {
if (p === prop) return parsedVal;
else return oldValues[k];
});
this.set(newValues, props, format, { parsed: true });
this.#cache = new Map();
}
public set r(val: number | string) { this.recompute(val, 'r', 'rgb'); }
public set red(val: number | string) { this.r = val; }
public set g(val: number | string) { this.recompute(val, 'g', 'rgb'); }
public set green(val: number | string) { this.g = val; }
public set b(val: number | string) { this.recompute(val, 'b', 'rgb'); }
public set blue(val: number | string) { this.b = val; }
public set a(val: number | string) { this.recompute(val, 'a', 'rgb'); }
public set alpha(val: number | string) { this.a = val; }
public set opacity(val: number | string) { this.a = val; }
public set h(val: number | string) { this.recompute(val, 'h', 'hsl'); }
public set hue(val: number | string) { this.h = val; }
public set s(val: number | string) { this.recompute(val, 's', 'hsl'); }
public set saturation(val: number | string) { this.s = val; }
public set l(val: number | string) { this.recompute(val, 'l', 'hsl'); }
public set lightness(val: number | string) { this.l = val; }
public set w(val: number | string) { this.recompute(val, 'w', 'hwb'); }
public set whiteness(val: number | string) { this.w = val; }
public set bk(val: number | string) { this.recompute(val, 'bk', 'hwb'); }
public set blackness(val: number | string) { this.bk = val; }
public set ciel(val: number | string) { this.recompute(val, 'ciel', 'lab'); }
public set CIElightness(val: number | string) { this.ciel = val; }
public set ciea(val: number | string) { this.recompute(val, 'ciea', 'lab'); }
public set cieb(val: number | string) { this.recompute(val, 'cieb', 'lab'); }
public set ciec(val: number | string) { this.recompute(val, 'ciec', 'lch'); }
public set CIEchroma(val: number | string) { this.ciec = val; }
public set cieh(val: number | string) { this.recompute(val, 'cieh', 'lch'); }
public set CIEhue(val: number | string) { this.cieh = val; }
public set okl(val: number | string) { this.recompute(val, 'okl', 'oklab'); }
public set OKlightness(val: number | string) { this.okl = val; }
public set oka(val: number | string) { this.recompute(val, 'oka', 'oklab'); }
public set okb(val: number | string) { this.recompute(val, 'okb', 'oklab'); }
public set okc(val: number | string) { this.recompute(val, 'okc', 'oklch'); }
public set OKchroma(val: number | string) { this.okc = val; }
public set okh(val: number | string) { this.recompute(val, 'okh', 'oklch'); }
public set OKhue(val: number | string) { this.okh = val; }
/** @returns Gets the parsed value of one of the color properties. */
public get r(): number { return this.#r; }
public get red(): number { return this.r; }
public get g(): number { return this.#g; }
public get green(): number { return this.g; }
public get b(): number { return this.#b; }
public get blue(): number { return this.b; }
public get a(): number { return this.#a; }
public get alpha(): number { return this.a; }
public get opacity(): number { return this.a; }
public get h(): number { return this.valuesTo('hsl')[0]; }
public get hue(): number { return this.h; }
public get s(): number { return this.valuesTo('hsl')[1]; }
public get saturation(): number { return this.s; }
public get l(): number { return this.valuesTo('hsl')[2]; }
public get lightness(): number { return this.l; }
public get w(): number { return this.valuesTo('hwb')[1]; }
public get whiteness(): number { return this.w; }
public get bk(): number { return this.valuesTo('hwb')[2]; }
public get blackness(): number { return this.bk; }
public get ciel(): number { return this.valuesTo('lab')[0]; }
public get CIElightness(): number { return this.ciel; }
public get ciea(): number { return this.valuesTo('lab')[1]; }
public get cieb(): number { return this.valuesTo('lab')[2]; }
public get ciec(): number { return this.valuesTo('lch')[1]; }
public get CIEchroma(): number { return this.ciec; }
public get cieh(): number { return this.valuesTo('lch')[2]; }
public get CIEhue(): number { return this.cieh; }
public get okl(): number { return this.valuesTo('oklab')[0]; }
public get OKlightness(): number { return this.okl; }
public get oka(): number { return this.valuesTo('oklab')[1]; }
public get okb(): number { return this.valuesTo('oklab')[2]; }
public get okc(): number { return this.valuesTo('oklch')[1]; }
public get OKchroma(): number { return this.okc; }
public get okh(): number { return this.valuesTo('oklch')[2]; }
public get OKhue(): number { return this.okh; }
public set luminance(val: number | string) {
// Scale r, g, b to reach the desired luminance value
const [r, g, b] = this.values;
const oldLum = this.luminance;
const newLum = Couleur.parse(val, 'a', { clamp: true });
if (oldLum === 0) {
this.r = newLum;
this.g = newLum;
this.b = newLum;
} else {
const ratio = newLum / oldLum;
this.r = ratio * r;
this.g = ratio * g;
this.b = ratio * b;
}
}
public get luminance(): number {
if (this.a < 1) throw new Error(`The luminance of a transparent color would be meaningless`);
return Contrasts.luminance(this.values);
}
/**
* Returns whether a color property is powerless,
* i.e. has no effect on the color because of other properties.
* @param prop The color property to check.
* @param tolerance A safety margin.
*/
public isPowerless(prop: ColorProperty, { tolerance = .0001 } = {}): boolean {
switch (prop) {
case 'h':
return this.s <= 0 + tolerance || this.l <= 0 + tolerance || this.l >= 1 - tolerance;
case 's':
return this.l <= 0 + tolerance || this.l >= 1 - tolerance;
case 'ciea':
case 'cieb':
case 'cieh':
return this.ciel <= 0 + tolerance || this.ciel >= 1 - tolerance;
case 'oka':
case 'okb':
case 'okh':
return this.okl <= 0 + tolerance || this.okl >= 1 - tolerance;
case 'oksl':
return this.valuesTo('okhsl')[2] <= 0 + tolerance;
case 'oksv':
return this.valuesTo('okhsv')[2] <= 0 + tolerance;
default:
return false;
}
}
/***********************************/
/* Conversion between color spaces */
/***********************************/
/**
* Converts the color values from one color space to another.
* @param startSpaceID Starting color space, or its identifier.
* @param endSpaceID Color space to convert to, or its identifier.
* @param values Array of color values (without alpha) in startSpaceID color space.
* @returns Array of values in the new color space.
* @throws When one of the color spaces is not supported.
*/
public static convert(startSpaceID: colorSpaceOrID, endSpaceID: colorSpaceOrID, values: number[]): number[] {
if (
(typeof startSpaceID === typeof endSpaceID && startSpaceID === endSpaceID)
|| (typeof startSpaceID === 'string' && typeof endSpaceID !== 'string' && startSpaceID === endSpaceID.id)
|| (typeof startSpaceID !== 'string' && typeof endSpaceID === 'string' && startSpaceID.id === endSpaceID)
) return values;
const startSpace = Couleur.getSpace(startSpaceID);
const endSpace = Couleur.getSpace(endSpaceID);
// Find the shortest sequence of functions to convert between color spaces
let path;
const graph = colorSpacesGraph;
try { path = graph.shortestPath(startSpace.id, endSpace.id).map(node => node.id); }
catch (error) {
if (error instanceof PathNotFoundError) {
throw new ImpossibleColorConversionError(startSpace, endSpace);
} else if (error instanceof UndefinedNodeError) {
if (error.id === startSpace.id) throw new UnsupportedColorSpaceError(startSpace.id);
else if (error.id === endSpace.id) throw new UnsupportedColorSpaceError(endSpace.id);
else throw error;
} else throw error;
}
// Apply these functions to the color values.
let result = values;
while (path.length > 1) {
const start = path.shift();
const end = path[0];
const functionName = `${start}_to_${end}`.replace(/-/g, '');
const func = Conversions[functionName as keyof typeof Conversions];
if (typeof func !== 'function') throw new UndefinedConversionError(functionName);
result = func(result);
}
return result;
}
/**
* Converts the r, g, b values of the color to another color space.
* @param destinationSpaceID Desired color space, or its identifier.
* @param options
* @param options.clamp Whether to clamp the values to their new color space.
* @returns The array of converted values.
*/
public valuesTo(destinationSpaceID: colorSpaceOrID, { clamp = false } = {}): number[] {
const destinationSpace = Couleur.getSpace(destinationSpaceID);
let values = this.#cache.get(destinationSpace.id);
if (!values) {
values = Couleur.convert('srgb', destinationSpace, this.values);
this.#cache.set(destinationSpace.id, values);
}
if (clamp) values = Couleur.valuesToGamut(destinationSpace, values);
return values;
}
/* Clamping to a color space */
/**
* Checks whether parsed values in destinationSpaceID color space are in destinationSpace gamut.
* @param destinationSpaceID Color space whose gamut will be checked, or its identifier.
* @param values Array of parsed values.
* @returns Whether the corresponding color is in gamut.
*/
public static valuesInGamut(destinationSpaceID: colorSpaceOrID, values: number[] | Couleur, { tolerance = .0001 } = {}): boolean {
const destinationSpace = Couleur.getSpace(destinationSpaceID) as ColorSpaceWithoutGamut;
const gamutSpace = (
destinationSpace.gamutSpace ? Couleur.getSpace(destinationSpace.gamutSpace)
: destinationSpace
) as ColorSpaceWithGamut;
const convertedValues = values instanceof Couleur ? values.valuesTo(gamutSpace)
: Couleur.convert(destinationSpace, gamutSpace, values);
return convertedValues.every((v, k) => v >= (gamutSpace.gamut[k][0] - tolerance) && v <= (gamutSpace.gamut[k][1] + tolerance));
}