Skip to content

Commit ed9febe

Browse files
authored
fix(mix): return valid colors with transparent values at weight extremes (#409)
1 parent 8acf0f4 commit ed9febe

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

src/mix.test.ts

+12
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,15 @@ test('mix blue and green', () => {
5151
);
5252
expect(mix('blue', 'green', 1)).toMatchInlineSnapshot(`"rgba(0, 128, 0, 1)"`);
5353
});
54+
55+
test('mix with transparent and weight 0%', () => {
56+
expect(mix('transparent', 'blue', 0)).toMatchInlineSnapshot(
57+
`"rgba(0, 0, 0, 0)"`
58+
);
59+
});
60+
61+
test('mix with transparent and weight 100%', () => {
62+
expect(mix('red', 'rgba(255, 0, 0, 0)', 1)).toMatchInlineSnapshot(
63+
`"rgba(255, 0, 0, 0)"`
64+
);
65+
});

src/mix.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@ function mix(color1: string, color2: string, weight: number): string {
1515
// The formula is copied from the original Sass implementation:
1616
// http://sass-lang.com/documentation/Sass/Script/Functions.html#mix-instance_method
1717
const alphaDelta = a2 - a1;
18-
const x = weight * 2 - 1;
19-
const y = x * alphaDelta === -1 ? x : x + alphaDelta;
20-
const z = 1 + x * alphaDelta;
21-
const weight2 = (y / z + 1) / 2.0;
18+
const normalizedWeight = weight * 2 - 1;
19+
const combinedWeight =
20+
normalizedWeight * alphaDelta === -1
21+
? normalizedWeight
22+
: normalizedWeight + alphaDelta / (1 + normalizedWeight * alphaDelta);
23+
const weight2 = (combinedWeight + 1) / 2;
2224
const weight1 = 1 - weight2;
2325

2426
const r = (r1 * weight1 + r2 * weight2) * 255;

0 commit comments

Comments
 (0)