Skip to content

Commit b72755f

Browse files
committed
Add helper method to adjust colour for opacity
1 parent ff46223 commit b72755f

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

dotcom-rendering/src/lib/colour.test.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { getContrast, isLight } from './colour';
1+
import { addAlpha, getContrast, isLight } from './colour';
22

33
const round = (value: number): number => Math.round(value * 100) / 100;
44

@@ -55,3 +55,18 @@ describe('getContrast', () => {
5555
expect(round(getContrast('#559861', '#1a1a1a'))).toEqual(5.01);
5656
});
5757
});
58+
59+
describe('addAlpha', () => {
60+
it('should return new colour adjusted for opacity against background colour', () => {
61+
expect(addAlpha('#da020e', '#ffffff', 1)).toBe('#da020e');
62+
expect(addAlpha('#da020e', '#1a1a1a', 1)).toBe('#da020e');
63+
expect(addAlpha('#da020e', '#ffffff', 0.1)).toBe('#fbe6e7');
64+
expect(addAlpha('#da020e', '#1a1a1a', 0.1)).toBe('#2d1819');
65+
expect(addAlpha('#023474', '#ffffff', 0.1)).toBe('#e6ebf1');
66+
expect(addAlpha('#023474', '#1a1a1a', 0.1)).toBe('#181d23');
67+
});
68+
it('should return fallback colour if invalid colour passed in', () => {
69+
expect(addAlpha('#xyz', '#ffffff', 1)).toBe('#7f7f7f');
70+
expect(addAlpha('#ffffff', '#xyz', 1)).toBe('#7f7f7f');
71+
});
72+
});

dotcom-rendering/src/lib/colour.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,26 @@ const hexToRgb = (
2323
: null;
2424
};
2525

26+
export const addAlpha = (
27+
colour: string,
28+
background: string,
29+
alpha: number,
30+
): string => {
31+
const rgbColour = hexToRgb(colour);
32+
const rgbBackground = hexToRgb(background);
33+
if (!rgbColour || !rgbBackground) return '#7f7f7f'; // fallback to mid grey
34+
35+
const bg = [rgbBackground.r, rgbBackground.g, rgbBackground.b];
36+
const alphaColour = [rgbColour.r, rgbColour.g, rgbColour.b].map(
37+
(channel, index) =>
38+
Math.round(alpha * channel + (1 - alpha) * bg[index]!)
39+
.toString(16)
40+
.padStart(2, '0'),
41+
);
42+
43+
return `#${alphaColour[0]}${alphaColour[1]}${alphaColour[2]}`;
44+
};
45+
2646
// https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
2747
// Based on: https://github.com/siege-media/contrast-ratio/blob/gh-pages/color.js
2848
const processLuminance = (channel: number): number => {

0 commit comments

Comments
 (0)