Skip to content

Commit

Permalink
refactor: simplified color-parsing function
Browse files Browse the repository at this point in the history
  • Loading branch information
usefulthink committed Dec 7, 2022
1 parent b0a39a3 commit e7144a6
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions src/lib/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,31 @@ export type HSLColor = [number, number, number];
const colorCache: Record<string, RGBAColor> = {};

export function parseCssColorValue(color: string): RGBAColor {
if (!colorCache[color]) {
if (!helperDiv) {
helperDiv = document.createElement('div');
helperDiv.style.cssText = `
if (colorCache[color]) {
return colorCache[color].slice(0) as RGBAColor;
}

if (!helperDiv) {
helperDiv = document.createElement('div');
helperDiv.style.cssText = `
position: absolute;
visibility: hidden;
pointer-events: none;
`;
}
helperDiv.style.color = color;
document.body.appendChild(helperDiv);
const rgb = getComputedStyle(helperDiv).color;
const [r = 0, g = 0, b = 0, a = 1] = rgb
.slice(rgb.indexOf('(') + 1, rgb.indexOf(')'))
.split(/,\s*/)
.map(Number);
helperDiv.remove();
colorCache[color] = [r, g, b, a];
}
helperDiv.style.color = color;
document.body.appendChild(helperDiv);
const rgb = getComputedStyle(helperDiv).color;
const [r = 0, g = 0, b = 0, a = 1] = rgb
.slice(rgb.indexOf('(') + 1, rgb.indexOf(')'))
.split(/,\s*/)
.map(Number);
helperDiv.remove();

const rgba: RGBAColor = [r, g, b, a];

colorCache[color] = rgba;
return rgba;

return colorCache[color].slice(0) as RGBAColor;
}
Expand Down

0 comments on commit e7144a6

Please sign in to comment.