Skip to content

Commit

Permalink
fix: hex rgba regex matcher lazy, catch and warn colorjs error (#135)
Browse files Browse the repository at this point in the history
  • Loading branch information
jorenbroekema committed May 26, 2023
1 parent 4f2fd48 commit 01d45fd
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/smart-pandas-dress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tokens-studio/sd-transforms': patch
---

Fix hex rgba regex matcher to be lazier about some character matching, warn for errors from colorjs.io hex parsing.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 8 additions & 3 deletions src/css/transformHEXRGBa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,16 @@ export function transformHEXRGBaForCSS(value: string | undefined): string | unde
if (value === undefined) {
return value;
}
const match = /rgba\((?<hex>#.+),\s*(?<alpha>.+)\)/g.exec(value);
const match = /rgba\((?<hex>#.+?),\s*?(?<alpha>\d.*?)\)/g.exec(value);
if (match && match.groups) {
const { hex, alpha } = match.groups;
const [r, g, b] = parseToRgba(hex);
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
try {
const [r, g, b] = parseToRgba(hex);
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
} catch (e) {
console.warn(`Tried parsing "${hex}" as a hex value, but failed.`);
return value;
}
}
return value;
}
4 changes: 4 additions & 0 deletions test/spec/css/transformHEXRGBa.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,8 @@ describe('transform HEXRGBa', () => {
it("does not transform if it's already rgba() format", () => {
expect(transformHEXRGBaForCSS('rgba(0,0,0,1)')).to.equal('rgba(0,0,0,1)');
});

it('does not transform if the hex value cannot be interpreted properly', () => {
expect(transformHEXRGBaForCSS('rgba(#000000abcd, 0.3)')).to.equal('rgba(#000000abcd, 0.3)');
});
});

0 comments on commit 01d45fd

Please sign in to comment.