Skip to content

Commit

Permalink
Prevent stripping zero unit in calc function
Browse files Browse the repository at this point in the history
  • Loading branch information
TrySound authored and ben-eb committed Feb 26, 2017
1 parent fe5d57f commit a3bbd49
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 14 deletions.
10 changes: 7 additions & 3 deletions packages/postcss-convert-values/src/__tests__/index.js
Expand Up @@ -67,8 +67,12 @@ let tests = [{
expected: 'h1{z-index:5}'
}, {
message: 'should operate in calc values',
fixture: 'h1{width:calc(192px + 2em)}',
expected: 'h1{width:calc(2in + 2em)}'
fixture: 'h1{width:calc(192px + 2em - (0px * 4))}',
expected: 'h1{width:calc(2in + 2em - (0px * 4))}'
}, {
message: 'should not convert zero values in calc',
fixture: 'h1{width:calc(0em)}',
expected: 'h1{width:calc(0em)}'
}, {
message: 'should not mangle values outside of its domain',
fixture: 'h1{background:url(a.png)}',
Expand All @@ -84,7 +88,7 @@ let tests = [{
}, {
message: 'should optimise fractions inside calc',
fixture: 'h1{width:calc(10.px + .0px)}',
expected: 'h1{width:calc(10px + 0)}'
expected: 'h1{width:calc(10px + 0px)}'
}, {
message: 'should handle leading zero in rem values',
fixture: '.one{top:0.25rem}',
Expand Down
36 changes: 25 additions & 11 deletions packages/postcss-convert-values/src/index.js
Expand Up @@ -4,6 +4,19 @@ import postcss from 'postcss';
import convert from './lib/convert';
import valueParser, {unit} from 'postcss-value-parser';

function parseWord (node, opts, stripZeroUnit) {
let pair = unit(node.value);
if (pair) {
let num = Number(pair.number);
let u = pair.unit.toLowerCase();
if (num === 0) {
node.value = (stripZeroUnit || u === 'ms' || u === 's') ? 0 + u : 0;
} else {
node.value = convert(num, u, opts);
}
}
}

function transform (opts) {
return decl => {
if (~decl.prop.indexOf('flex')) {
Expand All @@ -12,18 +25,19 @@ function transform (opts) {

decl.value = valueParser(decl.value).walk(function (node) {
if (node.type === 'word') {
let pair = unit(node.value);
if (pair) {
let num = Number(pair.number);
let u = pair.unit.toLowerCase();
if (num === 0) {
node.value = (u === 'ms' || u === 's') ? 0 + u : 0;
} else {
node.value = convert(num, u, opts);
}
}
parseWord(node, opts);
}
if (node.type === 'function' && node.value !== 'calc') {
if (node.type === 'function') {
if (node.value === 'calc') {
node.nodes.forEach(function walkNodes (node) {
if (node.type === 'word') {
parseWord(node, opts, true);
}
if (node.type === 'function') {
node.nodes.forEach(walkNodes);
}
});
}
return false;
}
}).toString();
Expand Down

0 comments on commit a3bbd49

Please sign in to comment.