Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ new TinyColor('#f00').greyscale().toString(); // "#808080"

```ts
new TinyColor('#f00').spin(180).toString(); // "#00ffff"
new TinyColor('#f00').spin(-90).toString(); // "#7f00ff"
new TinyColor('#f00').spin(-90).toString(); // "#8000ff"
new TinyColor('#f00').spin(90).toString(); // "#80ff00"

// spin(0) and spin(360) do nothing
Expand Down Expand Up @@ -615,7 +615,7 @@ colors.map(t => t.toHexString()); // [ "#ff0000", "#00ff00", "#0000ff" ]

```ts
const colors = new TinyColor('#f00').tetrad();
colors.map(t => t.toHexString()); // [ "#ff0000", "#80ff00", "#00ffff", "#7f00ff" ]
colors.map(t => t.toHexString()); // [ "#ff0000", "#80ff00", "#00ffff", "#8000ff" ]
```

### polyad
Expand All @@ -624,7 +624,7 @@ colors.map(t => t.toHexString()); // [ "#ff0000", "#80ff00", "#00ffff", "#7f00ff

```ts
const colors = new TinyColor('#f00').polyad(4);
colors.map(t => t.toHexString()); // [ "#ff0000", "#80ff00", "#00ffff", "#7f00ff" ]
colors.map(t => t.toHexString()); // [ "#ff0000", "#80ff00", "#00ffff", "#8000ff" ]
```

### complement
Expand Down
8 changes: 4 additions & 4 deletions src/conversion.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { HSL, HSV, Numberify, OKLCH, RGB } from './interfaces.js';
import { bound01, pad2 } from './util.js';
import { bound01, pad2, removeNoise } from './util.js';

// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <https://gist.github.com/mjackson/5311256>
Expand Down Expand Up @@ -120,7 +120,7 @@ export function hslToRgb(
b = hue2rgb(p, q, h - 1 / 3);
}

return { r: r * 255, g: g * 255, b: b * 255 };
return { r: removeNoise(r * 255), g: removeNoise(g * 255), b: removeNoise(b * 255) };
}

/**
Expand Down Expand Up @@ -189,7 +189,7 @@ export function hsvToRgb(
const g = [t, v, v, q, p, p][mod];
const b = [p, p, t, v, v, q][mod];

return { r: r * 255, g: g * 255, b: b * 255 };
return { r: removeNoise(r * 255), g: removeNoise(g * 255), b: removeNoise(b * 255) };
}

/** Char code of a hex digit 0-15, "0"-"9" then "a"-"f" */
Expand Down Expand Up @@ -293,7 +293,7 @@ export function cmykToRgb(c: number, m: number, y: number, k: number) {
const g = 255 * (1 - mConv) * (1 - kConv);
const b = 255 * (1 - yConv) * (1 - kConv);

return { r, g, b };
return { r: removeNoise(r), g: removeNoise(g), b: removeNoise(b) };
}

export function rgbToCmyk(r: number, g: number, b: number) {
Expand Down
9 changes: 9 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,15 @@ export function convertToPercentageNumber(n: number | string): number | string {
return (scaled >= 1e-6 ? Math.trunc(scaled) : parseInt(String(scaled), 10)) / 100;
}

/**
* Remove the floating point noise from a channel in [0, 255]. A channel that is exactly half,
* like 127.5, often comes out of a conversion as 127.49999999999999 and is rounded down
* @hidden
*/
export function removeNoise(n: number): number {
return Math.round(n * 1e9) / 1e9;
}

/**
* Force a hex value to have 2 characters
* @hidden
Expand Down
134 changes: 134 additions & 0 deletions test/exact-halves.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import { describe, expect, it } from 'vitest';

import { TinyColor } from '../src/public_api.js';

/**
* hsl() to sRGB as CSS Color 4 describes it, in integer arithmetic so nothing is lost to floating
* point. `h` is in whole degrees, `s` and `l` are whole percents. Each channel is rounded half up,
* which is what browsers do.
*/
function hslToRgbExact(h: number, s: number, l: number): number[] {
return [0, 8, 4].map(n => {
// k and m of the CSS formula, both multiplied by 30
const k = (30 * n + h) % 360;
const m = Math.max(-30, Math.min(k - 90, 270 - k, 30));
// the channel in 1 / 300000
const channel = 3000 * l - s * Math.min(l, 100 - l) * m;
return Math.floor((255 * channel + 150000) / 300000);
});
}

/** The same for hsv(), with the channels in 1 / 600000 */
function hsvToRgbExact(h: number, s: number, v: number): number[] {
const rest = h % 60;
const max = v * 6000;
const min = v * (100 - s) * 60;
const falling = v * (6000 - rest * s);
const rising = v * (6000 - (60 - rest) * s);
const sector = Math.floor(h / 60) % 6;
return [
[max, falling, min, min, rising, max][sector],
[rising, max, max, falling, min, min][sector],
[min, min, rising, max, max, falling][sector],
].map(channel => Math.floor((255 * channel + 300000) / 600000));
}

/** The same for cmyk(), with the channels in 1 / 10000 */
function cmykToRgbExact(c: number, m: number, y: number, k: number): number[] {
return [c, m, y].map(n => Math.floor((255 * (100 - n) * (100 - k) + 5000) / 10000));
}

describe('Exact halves in hsl(), hsv() and cmyk()', () => {
// A channel that is exactly 127.5 or 25.5 rounds up. It used to come out as 127.49999999999999
// and 25.499999999999996, and was rounded down
it.each([
['hsl(60, 100%, 25%)', 'olive'],
['hsl(180, 100%, 25%)', 'teal'],
['hsl(300, 100%, 25%)', 'purple'],
])('%s is %s', (input, name) => {
expect(new TinyColor(input).toHexString()).toBe(new TinyColor(name).toHexString());
});

it.each([
['hsl(0, 50%, 20%)', '#4d1a1a'],
['hsl(0, 60%, 25%)', '#661a1a'],
['hsl(0, 75%, 40%)', '#b31a1a'],
['hsl(0, 75%, 60%)', '#e64d4d'],
['hsl(0, 100%, 95%)', '#ffe6e6'],
['hsl(270, 60%, 70%)', '#b385e0'],
['hsl(270, 100%, 50%)', '#8000ff'],
['hsv(0, 80%, 50%)', '#801a1a'],
['hsv(0, 90%, 100%)', '#ff1a1a'],
['hsv(60, 80%, 50%)', '#80801a'],
['hsv(120, 50%, 50%)', '#408040'],
['cmyk(0, 0, 0, 90)', '#1a1a1a'],
['cmyk(90, 0, 0, 0)', '#1affff'],
['cmyk(0, 0, 0, 70)', '#4d4d4d'],
])('%s is %s', (input, hex) => {
expect(new TinyColor(input).toHexString()).toBe(hex);
});

it('should round the objects the same way', () => {
expect(new TinyColor({ h: 60, s: 1, l: 0.25 }).toHexString()).toBe('#808000');
expect(new TinyColor({ h: 0, s: 0.5, l: 0.2 }).toRgb()).toEqual({ r: 77, g: 26, b: 26, a: 1 });
expect(new TinyColor({ h: 0, s: 0.8, v: 0.5 }).toRgb()).toEqual({ r: 128, g: 26, b: 26, a: 1 });
expect(new TinyColor({ c: 0, m: 0, y: 0, k: 90 }).toRgb()).toEqual({
r: 26,
g: 26,
b: 26,
a: 1,
});
});

it('should give the exact rgb for the hsl() of every whole percent', () => {
const wrong: string[] = [];
for (let h = 0; h < 360; h += 30) {
for (let s = 0; s <= 100; s++) {
for (let l = 0; l <= 100; l++) {
const { r, g, b } = new TinyColor(`hsl(${h}, ${s}%, ${l}%)`).toRgb();
const exact = hslToRgbExact(h, s, l);
if (r !== exact[0] || g !== exact[1] || b !== exact[2]) {
wrong.push(`hsl(${h}, ${s}%, ${l}%) gave ${[r, g, b]}, not ${exact}`);
}
}
}
}

expect(wrong.slice(0, 10)).toEqual([]);
});

it('should give the exact rgb for the hsv() of every whole percent', () => {
const wrong: string[] = [];
for (let h = 0; h < 360; h += 30) {
for (let s = 0; s <= 100; s++) {
for (let v = 0; v <= 100; v++) {
const { r, g, b } = new TinyColor(`hsv(${h}, ${s}%, ${v}%)`).toRgb();
const exact = hsvToRgbExact(h, s, v);
if (r !== exact[0] || g !== exact[1] || b !== exact[2]) {
wrong.push(`hsv(${h}, ${s}%, ${v}%) gave ${[r, g, b]}, not ${exact}`);
}
}
}
}

expect(wrong.slice(0, 10)).toEqual([]);
});

it('should give the exact rgb for the cmyk() of every whole percent', () => {
const wrong: string[] = [];
for (let c = 0; c <= 100; c++) {
for (let k = 0; k <= 100; k++) {
// m and y move against c so every channel sees the whole range
const m = 100 - c;
const y = (c * 37) % 101;
const { r, g, b } = new TinyColor(`cmyk(${c}, ${m}, ${y}, ${k})`).toRgb();
const exact = cmykToRgbExact(c, m, y, k);
if (r !== exact[0] || g !== exact[1] || b !== exact[2]) {
wrong.push(`cmyk(${c}, ${m}, ${y}, ${k}) gave ${[r, g, b]}, not ${exact}`);
}
}
}

expect(wrong.slice(0, 10)).toEqual([]);
});
});
4 changes: 2 additions & 2 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,7 @@ describe('TinyColor', () => {
a: 0.5,
});
// keeps precision that toRgb rounds away
const color = new TinyColor('hsl(210, 50%, 40%)');
const color = new TinyColor('hsl(210, 50%, 41%)');
expect(color.toRgbRatio().r).toBeCloseTo(color.r / 255, 10);
expect(color.toRgbRatio().r * 255).not.toBe(color.toRgb().r);
});
Expand Down Expand Up @@ -924,7 +924,7 @@ describe('TinyColor', () => {

it('tetrad', () => {
const combination = new TinyColor('red').tetrad();
expect(colorsToHexString(combination)).toBe('ff0000,80ff00,00ffff,7f00ff');
expect(colorsToHexString(combination)).toBe('ff0000,80ff00,00ffff,8000ff');
});

it('legacy random', () => {
Expand Down
4 changes: 2 additions & 2 deletions test/modifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const DESATURATIONS = [
'e91616',
'e81717',
'e71818',
'e61919',
'e61a1a',
'e41b1b',
'e31c1c',
'e21d1d',
Expand Down Expand Up @@ -255,7 +255,7 @@ export const LIGHTENS = [
'ffd6d6',
'ffdbdb',
'ffe0e0',
'ffe5e5',
'ffe6e6',
'ffebeb',
'fff0f0',
'fff5f5',
Expand Down
6 changes: 3 additions & 3 deletions test/percentage-hue.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ describe('Percentage hue', () => {
['hsl(1.0%, 100%, 50%)', '#ff0f00'],
['hsl(25%, 100%, 50%)', '#80ff00'],
['hsl(50%, 100%, 50%)', '#00ffff'],
['hsla(75%, 100%, 50%, 0.5)', '#7f00ff80'],
['hsla(75%, 100%, 50%, 0.5)', '#8000ff80'],
['hsl(100%, 100%, 50%)', '#ff0000'],
['hsv(0%, 100%, 100%)', '#ff0000'],
['hsv(1.0%, 100%, 100%)', '#ff0f00'],
Expand All @@ -34,9 +34,9 @@ describe('Percentage hue', () => {
});

it.each([
['hsl(-25%, 100%, 50%)', '#7f00ff'],
['hsl(-25%, 100%, 50%)', '#8000ff'],
['hsv(125%, 100%, 100%)', '#80ff00'],
['hsl(-90, 100%, 50%)', '#7f00ff'],
['hsl(-90, 100%, 50%)', '#8000ff'],
['hsv(450, 100%, 100%)', '#80ff00'],
])('should wrap the hue in %s', (input, expected) => {
expect(new TinyColor(input).toHexString()).toBe(expected);
Expand Down
Loading