Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix regex in resolve-value.js to allow nested CSS functions #97

Merged
merged 17 commits into from
Nov 25, 2019
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
58 changes: 36 additions & 22 deletions lib/resolve-value.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
var balanced = require('balanced-match');

var generateScopeList = require('./generate-scope-list');
var isNodeUnderScope = require('./is-node-under-scope');
var gatherVariableDependencies = require('./gather-variable-dependencies');

var findNodeAncestorWithSelector = require('./find-node-ancestor-with-selector');
var cloneSpliceParentOntoNodeWhen = require('./clone-splice-parent-onto-node-when');



// var() = var( <custom-property-name> [, <any-value> ]? )
// matches `name[, fallback]`, captures "name" and "fallback"
// See: http://dev.w3.org/csswg/css-variables/#funcdef-var
var RE_VAR_FUNC = (/var\(\s*(--[^,\s]+?)(?:\s*,\s*(.+))?\s*\)/);
// regex to capture variable names
var RE_VAR_FUNC = (/var\(\s*(--[^,\s)]+)/);

function toString(value) {
return String(value);
}

function filterDistinct(value, index, self) {
return self.indexOf(value) === index;
}
juliovedovatto marked this conversation as resolved.
Show resolved Hide resolved

// Pass in a value string to parse/resolve and a map of available values
// and we can figure out the final value
//
Expand All @@ -27,26 +29,39 @@ function toString(value) {
var resolveValue = function(decl, map, /*optional*/ignorePseudoScope, /*internal debugging*/_debugIsInternal) {
var debugIndent = _debugIsInternal ? '\t' : '';

var matchingVarDecl = undefined;
var RE_VAR_FUNC_G = new RegExp(RE_VAR_FUNC.source, 'g');
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can get rid of RE_VAR_FUNC_G and RE_VAR_FUNC now

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

RE_VAR_FUNC_G was removed.

But, It seems we can't remove RE_VAR_FUNC, since it is being called in index.js.

var doesRuleUseVariables = rule.nodes.some(function(node) {
if(node.type === 'decl') {
var decl = node;
// If it uses variables
// and is not a variable declarations that we may be preserving from earlier
if(resolveValue.RE_VAR_FUNC.test(decl.value) && !RE_VAR_PROP.test(decl.prop)) {
return true;
}
}
return false;
});

var resultantValue = toString(decl.value);
var warnings = [];


var variablesUsedInValueMap = {};
// Use `replace` as a loop to go over all occurrences with the `g` flag
resultantValue.replace(new RegExp(RE_VAR_FUNC.source, 'g'), function(match, variableName, fallback) {
variablesUsedInValueMap[variableName] = true;
});
var variablesUsedInValue = Object.keys(variablesUsedInValueMap);
// match all variables first, to gather all available variables in decl.value
MadLittleMods marked this conversation as resolved.
Show resolved Hide resolved
var variablesUsedInValue = [];
while ((matchingVarDecl = RE_VAR_FUNC_G.exec(resultantValue))) {
MadLittleMods marked this conversation as resolved.
Show resolved Hide resolved
variablesUsedInValue.push(matchingVarDecl[1]);
juliovedovatto marked this conversation as resolved.
Show resolved Hide resolved
}
// remove duplicates from array
variablesUsedInValue = variablesUsedInValue.filter(filterDistinct);

//console.log(debugIndent, (_debugIsInternal ? '' : 'Try resolving'), generateScopeList(decl.parent, true), `ignorePseudoScope=${ignorePseudoScope}`, '------------------------');

// Resolve any var(...) substitutons
var isResultantValueUndefined = false;
resultantValue = resultantValue.replace(new RegExp(RE_VAR_FUNC.source, 'g'), function(match, variableName, fallback) {
// Loop through the list of declarations for that value and find the one that best matches
// By best match, we mean, the variable actually applies. Criteria:
// - is under the same scope
// - The latest defined `!important` if any
var matchingVarDeclMapItem;
juliovedovatto marked this conversation as resolved.
Show resolved Hide resolved

// var() = var( <custom-property-name> [, <any-value> ]? )
// matches `name[, fallback]`, captures "name" and "fallback"
// See: http://dev.w3.org/csswg/css-variables/#funcdef-var
while ((matchingVarDecl = balanced('var(', ')', resultantValue))) {
var matchingVarDeclMapItem = undefined;

// Split at the comma to find variable name and fallback value
// There may be other commas in the values so this isn't necessary just 2 pieces
MadLittleMods marked this conversation as resolved.
Show resolved Hide resolved
var variableFallbackSplitPieces = matchingVarDecl.body.split(',');

// get variable name and fallback, filtering empty items
var variableName = variableFallbackSplitPieces[0].trim();
var fallback = variableFallbackSplitPieces.length > 1 ? variableFallbackSplitPieces.slice(1).join(',').trim() : undefined;

(map[variableName] || []).forEach(function(varDeclMapItem) {
// Make sure the variable declaration came from the right spot
// And if the current matching variable is already important, a new one to replace it has to be important
Expand Down Expand Up @@ -97,10 +112,9 @@ var resolveValue = function(decl, map, /*optional*/ignorePseudoScope, /*internal
warnings.push(['variable ' + variableName + ' is undefined and used without a fallback', { node: decl }]);
}

//console.log(debugIndent, 'replaceValue', replaceValue);

return replaceValue;
});
// replace original declaration
resultantValue = (matchingVarDecl.pre || '') + replaceValue + (matchingVarDecl.post || '')
}

return {
// The resolved value
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"url": "https://github.com/MadLittleMods/postcss-css-variables.git"
},
"dependencies": {
"balanced-match": "^1.0.0",
"escape-string-regexp": "^1.0.3",
"extend": "^3.0.1",
"postcss": "^6.0.8"
Expand Down
16 changes: 16 additions & 0 deletions test/fixtures/nested-inside-calc-func-with-fallback-var.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
:root {
--some-width: 150px;
--some-other-width: 50px;
}

.box-foo {
width: calc(58.3333333333% - var(--missing, var(--some-width, 100px)));
}

.box-foo {
width: calc(58.3333333333% - var(--missing, var(--missing2, 100px)));
}

.box-foo {
width: calc(58.3333333333% - var(--missing, var(--missing2, var(--some-other-width))));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.box-foo {
width: calc(58.3333333333% - 150px);
}

.box-foo {
width: calc(58.3333333333% - 100px);
}

.box-foo {
width: calc(58.3333333333% - 50px);
}
11 changes: 11 additions & 0 deletions test/fixtures/nested-inside-calc-func-with-fallback.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
:root {
--some-width: 150px;
}

.box-foo {
width: calc(58.3333333333% - var(--some-width, 100px));
}

.box-foo {
width: calc(58.3333333333% - var(--missing, 100px));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.box-foo {
width: calc(58.3333333333% - 150px);
}

.box-foo {
width: calc(58.3333333333% - 100px);
}
23 changes: 23 additions & 0 deletions test/fixtures/nested-inside-calc-func.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
:root {
--some-width: 150px;
--some-other-width: 50px;
}

.box-foo {
width: calc(1000% - var(--some-width));
}

.box-foo {
width: calc(1000% - var(--missing-width));
}

.box-foo {
width: calc(var(--some-width) - var(--some-other-width));
}

.box-foo {
--widthA: 100px;
--widthB: calc(var(--widthA) / 2);
--widthC: calc(var(--widthB) / 2);
width: var(--widthC);
}
15 changes: 15 additions & 0 deletions test/fixtures/nested-inside-calc-func.expected.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.box-foo {
width: calc(1000% - 150px);
}

.box-foo {
width: undefined;
}

.box-foo {
width: calc(150px - 50px);
}

.box-foo {
width: calc(calc(100px / 2) / 2);
}
9 changes: 9 additions & 0 deletions test/fixtures/nested-inside-other-func-with-fallback.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
:root {
--some-color: red;
}
.box-foo {
background-color: color(var(--missing, white));
}
.box-foo {
background-color: color(var(--some-color, white));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.box-foo {
background-color: color(white);
}
.box-foo {
background-color: color(red);
}
15 changes: 14 additions & 1 deletion test/fixtures/nested-inside-other-func.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
:root {
--some-color: red;
--some-opacity: 0.3;
}

.box-foo {
background-color: color(var(--some-color));
}

.box-foo {
background-color: color(var(--some-color, white));
background-color: rgba(255, 0, 0, var(--some-opacity));
}
juliovedovatto marked this conversation as resolved.
Show resolved Hide resolved

.box-foo {
background-color: hsla(120,100%,50%, var(--missing-opacity));
}
MadLittleMods marked this conversation as resolved.
Show resolved Hide resolved
10 changes: 9 additions & 1 deletion test/fixtures/nested-inside-other-func.expected.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
.box-foo {
background-color: color(white);
background-color: color(red);
}

.box-foo {
background-color: rgba(255, 0, 0, 0.3);
}

.box-foo {
background-color: undefined;
}
4 changes: 4 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,10 @@ describe('postcss-css-variables', function() {
test('should use fallback variable if provided with missing variables calc', 'missing-variable-should-fallback-calc');
test('should use fallback variable if provided with missing variables nested', 'missing-variable-should-fallback-nested');
test('should not mangle outer function parentheses', 'nested-inside-other-func');
test('should not mangle outer function parentheses - with fallback', 'nested-inside-other-func-with-fallback');
test('should not mangle outer function parentheses - calc', 'nested-inside-calc-func');
test('should not mangle outer function parentheses - calc with fallback', 'nested-inside-calc-func-with-fallback');
test('should not mangle outer function parentheses - calc with fallback var()', 'nested-inside-calc-func-with-fallback-var');
});

test('should accept whitespace in var() declarations', 'whitespace-in-var-declaration' )
Expand Down