Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a method parameter to toGamut #288

Merged
merged 2 commits into from
Apr 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 27 additions & 10 deletions lib/src/value/color.ts
Original file line number Diff line number Diff line change
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