Skip to content

Commit

Permalink
Add throwWhenCannotReduce option
Browse files Browse the repository at this point in the history
  • Loading branch information
jamiebuilds committed Jan 6, 2016
1 parent d8e2755 commit 2ca864f
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
9 changes: 9 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@ var reduceCSSCalc = require("reduce-css-calc")
var helpers = require("postcss-message-helpers")
var postcss = require("postcss")

var CONTAINS_CALC = /calc\(.*\)/

/**
* PostCSS plugin to reduce calc() function calls.
*/
module.exports = postcss.plugin("postcss-calc", function(options) {
options = options || {}
var precision = options.precision
var preserve = options.preserve
var throwWhenCannotReduce = options.throwWhenCannotReduce

return function(style) {

style.walkDecls(function transformDecl(decl) {
if (!decl.value || decl.value.indexOf("calc(") === -1) {
return
Expand All @@ -22,6 +26,11 @@ module.exports = postcss.plugin("postcss-calc", function(options) {
helpers.try(function transformCSSCalc() {
var value = reduceCSSCalc(decl.value, precision)

if (throwWhenCannotReduce && CONTAINS_CALC.test(value)) {
throw decl.error("Could not reduce expression: " + decl.value,
{plugin: "postcss-calc"})
}

if (!preserve) {
decl.value = value
return
Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/throwWhenCannotReduce.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
calc {
unresolved: calc(1.125rem - 1px);
}
10 changes: 10 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,15 @@ test("calc", function(t) {
"should have a preserve option that allow to keep original calc() usage"
)

t.throws(function() {
var name = "throwWhenCannotReduce"

postcss()
.use(calc({throwWhenCannotReduce: true}))
.process(fixture(name), {from: fixturePath(name)})
.css
}, "should have throwWhenCannotReduce option that throws when calc() " +
"cannot be reduced")

t.end()
})

0 comments on commit 2ca864f

Please sign in to comment.