-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathcolor.ts
More file actions
1189 lines (1089 loc) · 33.9 KB
/
color.ts
File metadata and controls
1189 lines (1089 loc) · 33.9 KB
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
// Copyright 2021 Google Inc. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import {Value} from './index';
import {deprecations, warnForHostSideDeprecation} from '../deprecations';
import {valueError} from '../utils';
import {
fuzzyAssertInRange,
fuzzyEquals,
fuzzyGreaterThanOrEquals,
fuzzyHashCode,
fuzzyLessThan,
fuzzyRound,
positiveMod,
} from './utils';
import {List, hash} from 'immutable';
import Color from 'colorjs.io';
/** The HSL color space name. */
type ColorSpaceHsl = 'hsl';
/** The HSL color space channel names. */
type ChannelNameHsl = 'hue' | 'saturation' | 'lightness' | 'alpha';
/** The HWB color space name. */
type ColorSpaceHwb = 'hwb';
/** The HWB color space channel names. */
type ChannelNameHwb = 'hue' | 'whiteness' | 'blackness' | 'alpha';
/** The Lab / Oklab color space names. */
type ColorSpaceLab = 'lab' | 'oklab';
/** The Lab / Oklab color space channel names. */
type ChannelNameLab = 'lightness' | 'a' | 'b' | 'alpha';
/** The LCH / Oklch color space names. */
type ColorSpaceLch = 'lch' | 'oklch';
/** The LCH / Oklch color space channel names. */
type ChannelNameLch = 'lightness' | 'chroma' | 'hue' | 'alpha';
/** Names of color spaces with RGB channels. */
type ColorSpaceRgb =
| 'a98-rgb'
| 'display-p3'
| 'display-p3-linear'
| 'prophoto-rgb'
| 'rec2020'
| 'rgb'
| 'srgb'
| 'srgb-linear';
/** RGB channel names. */
type ChannelNameRgb = 'red' | 'green' | 'blue' | 'alpha';
/** Names of color spaces with XYZ channels. */
type ColorSpaceXyz = 'xyz' | 'xyz-d50' | 'xyz-d65';
/** XYZ channel names. */
type ChannelNameXyz = 'x' | 'y' | 'z' | 'alpha';
/** All supported color space channel names. */
type ChannelName =
| ChannelNameHsl
| ChannelNameHwb
| ChannelNameLab
| ChannelNameLch
| ChannelNameRgb
| ChannelNameXyz;
/** All supported color space names. */
export type KnownColorSpace =
| ColorSpaceHsl
| ColorSpaceHwb
| ColorSpaceLab
| ColorSpaceLch
| ColorSpaceRgb
| ColorSpaceXyz;
/** Polar color space names (HSL, HWB, LCH, and Oklch spaces). */
type PolarColorSpace = ColorSpaceHsl | ColorSpaceHwb | ColorSpaceLch;
/**
* Methods by which two hues are adjusted when interpolating between polar
* colors.
*/
type HueInterpolationMethod =
| 'decreasing'
| 'increasing'
| 'longer'
| 'shorter';
/**
* Methods by which colors in bounded spaces can be mapped to within their
* gamut.
*/
type GamutMapMethod = 'clip' | 'local-minde';
/** Options for specifying any channel value. */
type ChannelOptions = {
[key in ChannelName]?: number | null;
};
/** Constructor options for specifying space and/or channel values. */
type ConstructorOptions = ChannelOptions & {space?: KnownColorSpace};
/** Constructor options for passing in existing ColorJS object and space. */
type OptionsWithColor = {color: Color; space: KnownColorSpace};
/** Legacy determination of color space by channel name. */
function getColorSpace(options: ChannelOptions): KnownColorSpace {
if (typeof options.red === 'number') return 'rgb';
if (typeof options.saturation === 'number') return 'hsl';
if (typeof options.whiteness === 'number') return 'hwb';
throw valueError('No color space found');
}
/** Convert from sRGB (0-1) to RGB (0-255) units. */
function coordToRgb(val: number | null): number | null {
return val === null ? val : val * 255;
}
/** Convert from RGB (0-255) to sRGB (0-1) units. */
function rgbToCoord(val: number | null): number | null {
return val === null ? val : val / 255;
}
/** Normalize `hue` values to be within the range `[0, 360)`. */
function normalizeHue(val: number | null): number | null {
return val === null ? val : positiveMod(val, 360);
}
/**
* Normalize discrepancies between Sass color spaces and ColorJS color space
* ids, converting Sass values to ColorJS values.
*/
function encodeSpaceForColorJs(space?: KnownColorSpace): string | undefined {
switch (space) {
case 'rgb':
return 'srgb';
case 'a98-rgb':
return 'a98rgb';
case 'display-p3':
return 'p3';
case 'display-p3-linear':
return 'p3-linear';
case 'prophoto-rgb':
return 'prophoto';
}
return space;
}
/**
* Normalize discrepancies between Sass's [GamutMapMethod] and Color.js's
* `method` option.
*/
function encodeGamutMapMethodForColorJs(method: GamutMapMethod): string {
return method === 'local-minde' ? 'css' : method;
}
/**
* Normalize discrepancies between Sass color spaces and ColorJS color space
* ids, converting ColorJS values to Sass values.
*/
function decodeSpaceFromColorJs(space: string, isRgb = false): KnownColorSpace {
switch (space) {
case 'srgb':
return isRgb ? 'rgb' : space;
case 'xyz-d65':
return 'xyz';
case 'a98rgb':
return 'a98-rgb';
case 'p3':
return 'display-p3';
case 'p3-linear':
return 'display-p3-linear';
case 'prophoto':
return 'prophoto-rgb';
}
return space as KnownColorSpace;
}
/**
* Normalize discrepancies between Sass channel names and ColorJS channel ids,
* converting Sass values to ColorJS values.
*
* @TODO Waiting on a new release of ColorJS that allows Lab spaces to accept
* `lightness` instead of only `l` and not as a channel name.
* Fixed in: https://github.com/LeaVerou/color.js/pull/348
*/
function encodeChannelForColorJs(channel: ChannelName): string {
if (channel === 'lightness') return 'l';
return channel;
}
/**
* Implement our own check of channel name validity for a given space, because
* ColorJS allows e.g. `b` for any of `blue`, `blackness`, or `b` channels.
*/
function validateChannelInSpace(
channel: ChannelName,
space: KnownColorSpace,
): void {
if (channel === 'alpha') return;
let valid = false;
switch (space) {
case 'rgb':
case 'srgb':
case 'srgb-linear':
case 'display-p3':
case 'display-p3-linear':
case 'a98-rgb':
case 'prophoto-rgb':
case 'rec2020':
valid = ['red', 'green', 'blue'].includes(channel);
break;
case 'hsl':
valid = ['hue', 'saturation', 'lightness'].includes(channel);
break;
case 'hwb':
valid = ['hue', 'whiteness', 'blackness'].includes(channel);
break;
case 'lab':
case 'oklab':
valid = ['lightness', 'a', 'b'].includes(channel);
break;
case 'lch':
case 'oklch':
valid = ['lightness', 'chroma', 'hue'].includes(channel);
break;
case 'xyz':
case 'xyz-d65':
case 'xyz-d50':
valid = ['x', 'y', 'z'].includes(channel);
break;
}
if (!valid) {
throw valueError(
`Unknown channel name "${channel}" for color space "${space}".`,
);
}
}
/** Determine whether the given space is a polar color space. */
function isPolarColorSpace(space: KnownColorSpace): space is PolarColorSpace {
switch (space) {
case 'hsl':
case 'hwb':
case 'lch':
case 'oklch':
return true;
default:
return false;
}
}
/**
* Convert from ColorJS coordinates (which use a range of `0-1` for `rgb`
* channel values) to Sass Color coordinates (which use a range of `0-255` for
* `rgb` channel values).
*/
function decodeCoordsFromColorJs(
coords: [number | null, number | null, number | null], // ColorJS coordinates
isRgb = false, // Whether this color is in the `rgb` color space
): [number | null, number | null, number | null] {
let newCoords = coords;
// If this color is in the `rgb` space, convert channel values to `0-255`
if (isRgb) {
newCoords = newCoords.map(coordToRgb) as [
number | null,
number | null,
number | null,
];
}
return newCoords;
}
/** Returns `true` if `val` is a `number` or `null`. */
function isNumberOrNull(val: undefined | null | number): val is number | null {
return val === null || typeof val === 'number';
}
/**
* Emit deprecation warnings when legacy color spaces set `alpha` or channel
* values to `null` without explicitly setting the `space`.
*/
function checkChangeDeprecations(
options: {
[key in ChannelName]?: number | null;
},
channels: ChannelName[],
): void {
if (options.alpha === null) emitNullAlphaDeprecation();
for (const channel of channels) {
if (options[channel] === null) emitColor4ApiChangeNullDeprecation(channel);
}
}
/** Warn users about legacy color channel getters. */
function emitColor4ApiGetterDeprecation(name: string): void {
warnForHostSideDeprecation(
`\`${name}\` is deprecated, use \`channel\` instead.` +
'\n' +
'More info: https://sass-lang.com/d/color-4-api',
deprecations['color-4-api'],
);
}
/**
* Warn users about changing channels not in the current color space without
* explicitly setting `space`.
*/
function emitColor4ApiChangeSpaceDeprecation(): void {
warnForHostSideDeprecation(
"Changing a channel not in this color's space without explicitly " +
'specifying the `space` option is deprecated.' +
'\n' +
'More info: https://sass-lang.com/d/color-4-api',
deprecations['color-4-api'],
);
}
/** Warn users about `null` channel values without setting `space`. */
function emitColor4ApiChangeNullDeprecation(channel: string): void {
warnForHostSideDeprecation(
`Passing \`${channel}: null\` without setting \`space\` is deprecated.` +
'\n' +
'More info: https://sass-lang.com/d/color-4-api',
deprecations['color-4-api'],
);
}
/** Warn users about null-alpha deprecation. */
function emitNullAlphaDeprecation(): void {
warnForHostSideDeprecation(
'Passing `alpha: null` without setting `space` is deprecated.' +
'\n' +
'More info: https://sass-lang.com/d/null-alpha',
deprecations['null-alpha'],
);
}
/**
* Determines whether the options passed to the Constructor include an existing
* ColorJS color object.
*/
function optionsHaveColor(
opts: OptionsWithColor | ConstructorOptions,
): opts is OptionsWithColor {
return (opts as OptionsWithColor).color instanceof Color;
}
/** A SassScript color. */
export class SassColor extends Value {
// ColorJS color object
private readonly color: Color;
// Boolean indicating whether this color is in RGB format
//
// ColorJS treats `rgb` as an output format of the `srgb` color space, while
// Sass treats it as its own color space. By internally tracking whether this
// color is `rgb` or not, we can use `srgb` consistently for ColorJS while
// still returning expected `rgb` values for Sass users.
private readonly isRgb: boolean = false;
// Names for the channels of this color
private channel0Id!: ChannelName;
private channel1Id!: ChannelName;
private channel2Id!: ChannelName;
// Sets channel names based on this color's color space
private setChannelIds(space: KnownColorSpace): void {
switch (space) {
case 'rgb':
case 'srgb':
case 'srgb-linear':
case 'display-p3':
case 'display-p3-linear':
case 'a98-rgb':
case 'prophoto-rgb':
case 'rec2020':
this.channel0Id = 'red';
this.channel1Id = 'green';
this.channel2Id = 'blue';
break;
case 'hsl':
this.channel0Id = 'hue';
this.channel1Id = 'saturation';
this.channel2Id = 'lightness';
break;
case 'hwb':
this.channel0Id = 'hue';
this.channel1Id = 'whiteness';
this.channel2Id = 'blackness';
break;
case 'lab':
case 'oklab':
this.channel0Id = 'lightness';
this.channel1Id = 'a';
this.channel2Id = 'b';
break;
case 'lch':
case 'oklch':
this.channel0Id = 'lightness';
this.channel1Id = 'chroma';
this.channel2Id = 'hue';
break;
case 'xyz':
case 'xyz-d65':
case 'xyz-d50':
this.channel0Id = 'x';
this.channel1Id = 'y';
this.channel2Id = 'z';
break;
}
}
constructor(options: OptionsWithColor);
constructor(options: ConstructorOptions);
constructor(optionsMaybeWithColor: OptionsWithColor | ConstructorOptions) {
super();
let options: ConstructorOptions;
// Use existing ColorJS color object from options for the new SassColor
if (optionsHaveColor(optionsMaybeWithColor)) {
const {color, space} = optionsMaybeWithColor;
if (space === 'rgb') this.isRgb = true;
this.setChannelIds(space);
this.color = color;
return;
} else {
options = optionsMaybeWithColor;
}
const space = options.space ?? getColorSpace(options);
this.setChannelIds(space);
if (space === 'rgb') this.isRgb = true;
let alpha: number | null;
if (options.alpha === null) {
if (!options.space) emitNullAlphaDeprecation();
alpha = null;
} else if (options.alpha === undefined) {
alpha = 1;
} else {
alpha = fuzzyAssertInRange(options.alpha, 0, 1, 'alpha');
}
switch (space) {
case 'rgb':
case 'srgb': {
const red = options.red ?? null;
const green = options.green ?? null;
const blue = options.blue ?? null;
if (this.isRgb) {
this.color = new Color({
spaceId: encodeSpaceForColorJs(space),
// convert from 0-255 to 0-1
coords: [red, green, blue].map(rgbToCoord) as [
number | null,
number | null,
number | null,
],
alpha,
});
} else {
this.color = new Color({
spaceId: encodeSpaceForColorJs(space),
coords: [red, green, blue],
alpha,
});
}
break;
}
case 'srgb-linear':
case 'display-p3':
case 'display-p3-linear':
case 'a98-rgb':
case 'prophoto-rgb':
case 'rec2020':
this.color = new Color({
spaceId: encodeSpaceForColorJs(space),
coords: [
options.red ?? null,
options.green ?? null,
options.blue ?? null,
],
alpha,
});
break;
case 'hsl': {
let hue = normalizeHue(options.hue ?? null);
let saturation = options.saturation ?? null;
const lightness = options.lightness ?? null;
if (saturation !== null && fuzzyLessThan(saturation, 0)) {
saturation = Math.abs(saturation);
if (hue !== null) {
hue = (hue + 180) % 360;
}
}
this.color = new Color({
spaceId: encodeSpaceForColorJs(space),
coords: [hue, saturation, lightness],
alpha,
});
break;
}
case 'hwb': {
const hue = normalizeHue(options.hue ?? null);
const whiteness = options.whiteness ?? null;
const blackness = options.blackness ?? null;
this.color = new Color({
spaceId: encodeSpaceForColorJs(space),
coords: [hue, whiteness, blackness],
alpha,
});
break;
}
case 'lab':
case 'oklab': {
const lightness = options.lightness ?? null;
const a = options.a ?? null;
const b = options.b ?? null;
this.color = new Color({
spaceId: encodeSpaceForColorJs(space),
coords: [lightness, a, b],
alpha,
});
break;
}
case 'lch':
case 'oklch': {
const lightness = options.lightness ?? null;
let chroma = options.chroma ?? null;
let hue = normalizeHue(options.hue ?? null);
if (chroma !== null && fuzzyLessThan(chroma, 0)) {
chroma = Math.abs(chroma);
if (hue !== null) {
hue = (hue + 180) % 360;
}
}
this.color = new Color({
spaceId: encodeSpaceForColorJs(space),
coords: [lightness, chroma, hue],
alpha,
});
break;
}
case 'xyz':
case 'xyz-d65':
case 'xyz-d50':
this.color = new Color({
spaceId: encodeSpaceForColorJs(space),
coords: [options.x ?? null, options.y ?? null, options.z ?? null],
alpha,
});
break;
}
}
/** This color's alpha channel, between `0` and `1`. */
get alpha(): number {
return this.color.alpha ?? 0;
}
/** The name of this color's color space. */
get space(): KnownColorSpace {
return decodeSpaceFromColorJs(this.color.spaceId, this.isRgb);
}
/**
* A boolean indicating whether this color is in a legacy color space (`rgb`,
* `hsl`, or `hwb`).
*/
get isLegacy(): boolean {
return ['rgb', 'hsl', 'hwb'].includes(this.space);
}
/**
* A list of this color's channel values (excluding alpha), with [missing
* channels] converted to `null`.
*
* [missing channels]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
*/
get channelsOrNull(): List<number | null> {
let coords = this.color.coords;
if (this.space === 'rgb') {
coords = coords.map(coordToRgb) as [
number | null,
number | null,
number | null,
];
}
return List(coords);
}
/**
* A list of this color's channel values (excluding alpha), with [missing
* channels] converted to `0`.
*
* [missing channels]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
*/
get channels(): List<number> {
let coords = this.color.coords;
if (this.space === 'rgb') {
coords = coords.map(coordToRgb) as [
number | null,
number | null,
number | null,
];
}
return List(coords.map(val => val ?? 0));
}
/**
* This color's red channel in the RGB color space, between `0` and `255`.
*
* @deprecated Use {@link channel} instead.
*/
get red(): number {
emitColor4ApiGetterDeprecation('red');
return fuzzyRound(coordToRgb(this.color.srgb.red)) ?? 0;
}
/**
* This color's green channel in the RGB color space, between `0` and `255`.
*
* @deprecated Use {@link channel} instead.
*/
get green(): number {
emitColor4ApiGetterDeprecation('green');
return fuzzyRound(coordToRgb(this.color.srgb.green)) ?? 0;
}
/**
* This color's blue channel in the RGB color space, between `0` and `255`.
*
* @deprecated Use {@link channel} instead.
*/
get blue(): number {
emitColor4ApiGetterDeprecation('blue');
return fuzzyRound(coordToRgb(this.color.srgb.blue)) ?? 0;
}
/**
* This color's hue in the HSL color space, between `0` and `360`.
*
* @deprecated Use {@link channel} instead.
*/
get hue(): number {
emitColor4ApiGetterDeprecation('hue');
return this.color.hsl.hue ?? 0;
}
/**
* This color's saturation in the HSL color space, between `0` and `100`.
*
* @deprecated Use {@link channel} instead.
*/
get saturation(): number {
emitColor4ApiGetterDeprecation('saturation');
return this.color.hsl.saturation ?? 0;
}
/**
* This color's lightness in the HSL color space, between `0` and `100`.
*
* @deprecated Use {@link channel} instead.
*/
get lightness(): number {
emitColor4ApiGetterDeprecation('lightness');
return this.color.hsl.lightness ?? 0;
}
/**
* This color's whiteness in the HWB color space, between `0` and `100`.
*
* @deprecated Use {@link channel} instead.
*/
get whiteness(): number {
emitColor4ApiGetterDeprecation('whiteness');
return this.color.hwb.whiteness ?? 0;
}
/**
* This color's blackness in the HWB color space, between `0` and `100`.
*
* @deprecated Use {@link channel} instead.
*/
get blackness(): number {
emitColor4ApiGetterDeprecation('blackness');
return this.color.hwb.blackness ?? 0;
}
assertColor(): SassColor {
return this;
}
/**
* Returns a new color that's the result of converting this color to the
* specified `space`.
*/
toSpace(space: KnownColorSpace): SassColor {
if (space === this.space) return this;
const color = this.color.to(encodeSpaceForColorJs(space) as string);
return new SassColor({color, space});
}
/**
* Returns a boolean indicating whether this color is in-gamut (as opposed to
* having one or more of its channels out of bounds) for the specified
* `space`, or its current color space if `space` is not specified.
*/
isInGamut(space?: KnownColorSpace): boolean {
return this.color.inGamut(encodeSpaceForColorJs(space));
}
/**
* Returns a copy of this color, modified so it is in-gamut for the specified
* `space`—or the current color space if `space` is not specified—using
* `method` to map out-of-gamut colors into the desired gamut.
*/
toGamut({
space,
method,
}: {
space?: KnownColorSpace;
method: GamutMapMethod;
}): SassColor {
if (this.isInGamut(space)) return this;
const color = this.color.clone().toGamut({
space: encodeSpaceForColorJs(space),
method: encodeGamutMapMethodForColorJs(method),
});
return new SassColor({color, space: space ?? this.space});
}
/**
* Returns the value of a single specified `channel` of this color (optionally
* after converting this color to the specified `space`), with [missing
* channels] converted to `0`.
*
* [missing channels]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
*/
channel(channel: ChannelName): number;
channel(channel: ChannelNameHsl, options: {space: ColorSpaceHsl}): number;
channel(channel: ChannelNameHwb, options: {space: ColorSpaceHwb}): number;
channel(channel: ChannelNameLab, options: {space: ColorSpaceLab}): number;
channel(channel: ChannelNameLch, options: {space: ColorSpaceLch}): number;
channel(channel: ChannelNameRgb, options: {space: ColorSpaceRgb}): number;
channel(channel: ChannelNameXyz, options: {space: ColorSpaceXyz}): number;
channel(channel: ChannelName, options?: {space: KnownColorSpace}): number {
if (channel === 'alpha') return this.alpha;
let val: number | null;
const space = options?.space ?? this.space;
validateChannelInSpace(channel, space);
if (options?.space) {
val = this.color.get({
space: encodeSpaceForColorJs(options.space) as string,
coordId: encodeChannelForColorJs(channel),
});
} else {
val = this.color.get({
space: this.color.spaceId,
coordId: encodeChannelForColorJs(channel),
});
}
if (space === 'rgb') val = coordToRgb(val);
return val ?? 0;
}
/**
* Returns a boolean indicating whether a given channel value is a [missing
* channel].
*
* [missing channel]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#missing_color_components
*/
isChannelMissing(channel: ChannelName): boolean {
if (channel === 'alpha') return this.color.alpha === null;
validateChannelInSpace(channel, this.space);
return (
this.color.get({
space: this.color.spaceId,
coordId: encodeChannelForColorJs(channel),
}) === null
);
}
/**
* Returns a boolean indicating whether a given `channel` is [powerless] in
* this color. This is a special state that's defined for individual color
* spaces, which indicates that a channel's value won't affect how a color is
* displayed.
*
* [powerless]: https://www.w3.org/TR/css-color-4/#powerless
*/
isChannelPowerless(
channel: ChannelNameHsl,
options?: {space: ColorSpaceHsl},
): boolean;
isChannelPowerless(
channel: ChannelNameHwb,
options?: {space: ColorSpaceHwb},
): boolean;
isChannelPowerless(
channel: ChannelNameLab,
options?: {space: ColorSpaceLab},
): boolean;
isChannelPowerless(
channel: ChannelNameLch,
options?: {space: ColorSpaceLch},
): boolean;
isChannelPowerless(
channel: ChannelNameRgb,
options?: {space: ColorSpaceRgb},
): boolean;
isChannelPowerless(
channel: ChannelNameXyz,
options?: {space: ColorSpaceXyz},
): boolean;
isChannelPowerless(
channel: ChannelName,
options?: {space: KnownColorSpace},
): boolean {
if (channel === 'alpha') return false;
const color = options?.space ? this.toSpace(options.space) : this;
validateChannelInSpace(channel, color.space);
const channels = color.channels.toArray();
switch (channel) {
case color.channel0Id:
if (color.space === 'hsl') return fuzzyEquals(channels[1], 0);
if (color.space === 'hwb') {
return fuzzyGreaterThanOrEquals(channels[1] + channels[2], 100);
}
return false;
case color.channel2Id:
switch (color.space) {
case 'lch':
case 'oklch':
return fuzzyEquals(channels[1], 0);
}
return false;
}
return false;
}
/**
* Returns a color partway between this color and `color2` according to
* `method`, as defined by the CSS Color 4 [color interpolation] procedure.
*
* [color interpolation]: https://www.w3.org/TR/css-color-4/#interpolation
*
* If `method` is missing and this color is in a polar color space (HSL, HWB,
* LCH, and Oklch spaces), `method` defaults to "shorter".
*
* The `weight` is a number between 0 and 1 that indicates how much of this
* color should be in the resulting color. If omitted, it defaults to 0.5.
*/
interpolate(
color2: SassColor,
options?: {
weight?: number;
method?: HueInterpolationMethod;
},
): SassColor {
const hueInterpolationMethod =
options?.method ??
(isPolarColorSpace(this.space) ? 'shorter' : undefined);
const weight = options?.weight ?? 0.5;
if (fuzzyEquals(weight, 0)) return color2;
if (fuzzyEquals(weight, 1)) return this;
if (weight < 0 || weight > 1) {
throw valueError(
`Expected \`weight\` between \`0\` and \`1\`, received \`${weight}\`.`,
);
}
// ColorJS inverses the `weight` argument, where `0` is `this` and `1` is
// `color2`.
const color = this.color.mix(color2.color, 1 - weight, {
space: encodeSpaceForColorJs(this.space),
hue: hueInterpolationMethod,
});
const coords = decodeCoordsFromColorJs(color.coords, this.space === 'rgb');
return new SassColor({
space: this.space,
[this.channel0Id]: coords[0],
[this.channel1Id]: coords[1],
[this.channel2Id]: coords[2],
alpha: this.color.alpha,
});
}
/** Legacy determination of color space by option channels. */
private getLegacyChangeSpace(options: ConstructorOptions): KnownColorSpace {
let space: KnownColorSpace | undefined;
if (
isNumberOrNull(options.whiteness) ||
isNumberOrNull(options.blackness) ||
(this.space === 'hwb' && isNumberOrNull(options.hue))
) {
space = 'hwb';
} else if (
isNumberOrNull(options.hue) ||
isNumberOrNull(options.saturation) ||
isNumberOrNull(options.lightness)
) {
space = 'hsl';
} else if (
isNumberOrNull(options.red) ||
isNumberOrNull(options.green) ||
isNumberOrNull(options.blue)
) {
space = 'rgb';
}
if (space !== this.space) emitColor4ApiChangeSpaceDeprecation();
return space ?? this.space;
}
/**
* Returns a new SassColor in the given `space` that's the result of changing
* one or more of this color's channels.
*/
private getChangedColor(
options: ConstructorOptions,
space: KnownColorSpace,
spaceSetExplicitly: boolean,
): SassColor {
const color = this.toSpace(space);
function getChangedValue(channel: ChannelName): number | null {
if (isNumberOrNull(options[channel])) return options[channel];
return color.channel(channel);
}
switch (space) {
case 'hsl':
if (spaceSetExplicitly) {
return new SassColor({
hue: getChangedValue('hue'),
saturation: getChangedValue('saturation'),
lightness: getChangedValue('lightness'),
alpha: getChangedValue('alpha'),
space,
});
} else {
checkChangeDeprecations(options, ['hue', 'saturation', 'lightness']);
return new SassColor({
hue: options.hue ?? color.channel('hue'),
saturation: options.saturation ?? color.channel('saturation'),
lightness: options.lightness ?? color.channel('lightness'),
alpha: options.alpha ?? color.channel('alpha'),
space,
});
}
case 'hwb':
if (spaceSetExplicitly) {
return new SassColor({
hue: getChangedValue('hue'),
whiteness: getChangedValue('whiteness'),
blackness: getChangedValue('blackness'),
alpha: getChangedValue('alpha'),
space,
});
} else {
checkChangeDeprecations(options, ['hue', 'whiteness', 'blackness']);
return new SassColor({
hue: options.hue ?? color.channel('hue'),
whiteness: options.whiteness ?? color.channel('whiteness'),
blackness: options.blackness ?? color.channel('blackness'),
alpha: options.alpha ?? color.channel('alpha'),
space,
});
}
case 'rgb':
if (spaceSetExplicitly) {
return new SassColor({
red: getChangedValue('red'),
green: getChangedValue('green'),
blue: getChangedValue('blue'),
alpha: getChangedValue('alpha'),
space,