Skip to content

Commit

Permalink
fix(core): only pass color values to color parsers
Browse files Browse the repository at this point in the history
  • Loading branch information
dackmin committed Mar 13, 2023
1 parent 8e0071f commit e22545a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
14 changes: 12 additions & 2 deletions packages/core/lib/colors/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,18 @@ declare interface COLORS {
}

export type COLOR_PARSERS = Array<{
parse: RegExp | string,
regex: Function
parse: ((r: string, g: string, b: string, a?: string) => {
r: number;
g: number;
b: number;
a: number;
}) | ((h: string, s: string, l: string, a?: string) => {
h: number;
s: number;
l: number;
a: number;
}),
regex: RegExp,
}>;

export function hsva2hsla({ h, s, v, a }: {
Expand Down
14 changes: 7 additions & 7 deletions packages/core/lib/colors/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,32 +62,32 @@ export const COLORS = {
};

const COLOR_PARSERS = [{
regex: /(rgb)a?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*%?,\s*(\d{1,3})\s*%?(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,
parse: ([_useless, _alsoUseless, r, g, b, a]) => ({
regex: /(?:rgb)a?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*%?,\s*(\d{1,3})\s*%?(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,
parse: (r, g, b, a) => ({
r: parseInt(r, 10) / 255,
g: parseInt(g, 10) / 255,
b: parseInt(b, 10) / 255,
a: isNaN(parseFloat(a)) ? 1 : parseFloat(a),
}),
}, {
regex: /(hsl)a?\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,
parse: ([_useless, _alsoUseless, h, s, l, a]) => ({
regex: /(?:hsl)a?\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,
parse: (h, s, l, a) => ({
h: parseInt(h, 10) / 360,
s: parseInt(s, 10) / 100,
l: parseInt(l, 10) / 100,
a: isNaN(parseFloat(a)) ? 1 : parseFloat(a),
}),
}, {
regex: /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})$/,
parse: ([_useless, r, g, b]) => ({
parse: (r, g, b) => ({
r: parseInt(r, 16) / 255,
g: parseInt(g, 16) / 255,
b: parseInt(b, 16) / 255,
a: 1,
}),
}, {
regex: /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])$/,
parse: ([_useless, r, g, b]) => ({
parse: (r, g, b) => ({
r: parseInt(r + r, 16) / 255,
g: parseInt(g + g, 16) / 255,
b: parseInt(b + b, 16) / 255,
Expand Down Expand Up @@ -245,7 +245,7 @@ export const parseColor = (color = '') => {

for (const parser of COLOR_PARSERS) {
const match = parser.regex.exec(color);
const parsed = match && parser.parse(match);
const parsed = match && parser.parse(...match.slice(1));

if (parsed) {
/* istanbul ignore else: ignored unrecognized format */
Expand Down

0 comments on commit e22545a

Please sign in to comment.