@patreon/studio
Version:
Patreon Studio Design System
114 lines • 3.34 kB
JavaScript
import { hcta2hex, hex2hcta } from '~/utilities/color';
/**
* A class that represents a color modification pipeline.
*
* We provide a fluent API for modifying a color using the
* HCT color space using the following methods:
*
* - `alpha` - Modify the alpha value.
* - `hue` - Modify the hue value.
* - `chroma` - Modify the chroma value.
* - `tone` - Modify the tone value.
*
* We provide this interface to provide a standardized way
* to modify colors. we want to abstract away the complexity
* of the HCT color space from engineers and still allow them
* to modify colors in a way that is easy to understand.
*
* @param color - The hex string to modify.
* @returns A new color modification pipeline.
*/
class ColorMod {
alphaValue;
hueValue;
chromaValue;
toneValue;
constructor(color) {
const { hue, chroma, tone, alpha } = hex2hcta(color);
this.hueValue = hue;
this.chromaValue = chroma;
this.toneValue = tone;
this.alphaValue = alpha;
}
hue(valueOrTransform) {
if (typeof valueOrTransform === 'function') {
this.hueValue = valueOrTransform(this.hueValue);
}
else {
this.hueValue = valueOrTransform;
}
return this;
}
chroma(valueOrTransform) {
if (typeof valueOrTransform === 'function') {
this.chromaValue = valueOrTransform(this.chromaValue);
}
else {
this.chromaValue = valueOrTransform;
}
return this;
}
tone(valueOrTransform) {
if (typeof valueOrTransform === 'function') {
this.toneValue = valueOrTransform(this.toneValue);
}
else {
this.toneValue = valueOrTransform;
}
return this;
}
alpha(valueOrTransform) {
if (typeof valueOrTransform === 'function') {
this.alphaValue = valueOrTransform(this.alphaValue);
}
else {
this.alphaValue = valueOrTransform;
}
return this;
}
value() {
if (this.alphaValue === undefined) {
return hcta2hex({
hue: this.hueValue,
chroma: this.chromaValue,
tone: this.toneValue,
});
}
return hcta2hex({
hue: this.hueValue,
chroma: this.chromaValue,
tone: this.toneValue,
alpha: this.alphaValue,
});
}
}
/**
* Takes a hex string and a transform pipeline and returns a new hex string.
* Don't worry about the limits of the values, we'll handle them for you.
* Hue is 0-360, chroma is 0-100, tone is 0-100, alpha is 0-1.
*
* Using static values:
* ```ts
* colorMod('#000000', (c) => c.alpha(0.5).hue(10).chroma(10).tone(10));
*```
*
* Computing values using a function:
* ```ts
* colorMod('#000000', (color) => (
* color
* .alpha(a => a * 0.5)
* .hue(h => h + 10)
* .chroma(c => c + 10)
* .tone(t => t + 10)
* ));
* ```
*
* @param color - The hex string to modify.
* @param transform - The transform pipeline to apply to the color.
* @returns A new hex string.
*/
export function colorMod(color, transform) {
const colorModInstance = new ColorMod(color);
return transform(colorModInstance).value();
}
//# sourceMappingURL=index.js.map