Skip to content

Commit

Permalink
Add a method parameter to toGamut (#288)
Browse files Browse the repository at this point in the history
  • Loading branch information
nex3 committed Apr 19, 2024
1 parent 6e9368e commit 7d44ff3
Showing 1 changed file with 27 additions and 10 deletions.
37 changes: 27 additions & 10 deletions lib/src/value/color.ts
Expand Up @@ -90,6 +90,12 @@ type HueInterpolationMethod =
| '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;
Expand Down Expand Up @@ -153,6 +159,14 @@ function encodeSpaceForColorJs(space?: KnownColorSpace): string | undefined {
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.
Expand Down Expand Up @@ -714,18 +728,21 @@ export class SassColor extends Value {

/**
* 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 the
* recommended [CSS Gamut Mapping Algorithm][css-mapping] to map out-of-gamut
* colors into the desired gamut with as little perceptual change as possible.
*
* [css-mapping]:
* https://www.w3.org/TR/css-color-4/#css-gamut-mapping-algorithm
* `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?: KnownColorSpace): SassColor {
toGamut({
space,
method,
}: {
space?: KnownColorSpace;
method: GamutMapMethod;
}): SassColor {
if (this.isInGamut(space)) return this;
const color = this.color
.clone()
.toGamut({space: encodeSpaceForColorJs(space)});
const color = this.color.clone().toGamut({
space: encodeSpaceForColorJs(space),
method: encodeGamutMapMethodForColorJs(method),
});
return new SassColor({color, space: space ?? this.space});
}

Expand Down

0 comments on commit 7d44ff3

Please sign in to comment.