Skip to content

Commit

Permalink
Fix number parsing (#508)
Browse files Browse the repository at this point in the history
* Fix number parsing

Ref #507

* export regex parsing constants and adjust numerical format test title
  • Loading branch information
facelessuser authored May 1, 2024
1 parent 4a962dd commit a77e080
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
19 changes: 11 additions & 8 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ const angleFactor = {
turn: 360,
};

export const regex = {
function: /^([a-z]+)\((.+?)\)$/i,
number: /^([-+]?(?:[0-9]*\.)?[0-9]+(e[-+]?[0-9]+)?)$/i,
unitValue: /%|deg|g?rad|turn$/,
singleArgument: /\/?\s*(none|[-+\w.]+(?:%|deg|g?rad|turn)?)/g,
};

/**
* Parse a CSS function, regardless of its name and arguments
* @param String str String to parse
Expand All @@ -85,17 +92,13 @@ export function parseFunction (str) {

str = str.trim();

const isFunctionRegex = /^([a-z]+)\((.+?)\)$/i;
const isNumberRegex = /^-?[\d.]+$/;
const unitValueRegex = /%|deg|g?rad|turn$/;
const singleArgument = /\/?\s*(none|[-\w.]+(?:%|deg|g?rad|turn)?)/g;
let parts = str.match(isFunctionRegex);
let parts = str.match(regex.function);

if (parts) {
// It is a function, parse args
let args = [];
parts[2].replace(singleArgument, ($0, rawArg) => {
let match = rawArg.match(unitValueRegex);
parts[2].replace(regex.singleArgument, ($0, rawArg) => {
let match = rawArg.match(regex.unitValue);
let arg = rawArg;

if (match) {
Expand All @@ -115,7 +118,7 @@ export function parseFunction (str) {
arg.unit = unit;
}
}
else if (isNumberRegex.test(arg)) {
else if (regex.number.test(arg)) {
// Convert numerical args to numbers
arg = new Number(arg);
arg.type = "<number>";
Expand Down
29 changes: 29 additions & 0 deletions test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,35 @@ const tests = {
},
],
},
{
name: "Different number formats",
tests: [
{
args: "color(srgb +0.9 0 0)",
expect: '{"spaceId":"srgb","coords":[0.9,0,0],"alpha":1}',
},
{
args: "color(srgb .9 0 0)",
expect: '{"spaceId":"srgb","coords":[0.9,0,0],"alpha":1}',
},
{
args: "color(srgb 9e-1 0 0)",
expect: '{"spaceId":"srgb","coords":[0.9,0,0],"alpha":1}',
},
{
args: "color(srgb 9E-1 0 0)",
expect: '{"spaceId":"srgb","coords":[0.9,0,0],"alpha":1}',
},
{
args: "color(srgb 0.09e+1 0 0)",
expect: '{"spaceId":"srgb","coords":[0.9,0,0],"alpha":1}',
},
{
args: "color(srgb 0.09e1 0 0)",
expect: '{"spaceId":"srgb","coords":[0.9,0,0],"alpha":1}',
},
],
},
],
};

Expand Down

0 comments on commit a77e080

Please sign in to comment.