Skip to content
This repository has been archived by the owner on Jul 17, 2022. It is now read-only.

Added spaces to the operators for CSS calc functions after CSS compression #43

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/main/groovy/com/eriwen/gradle/css/CssMinifier.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package com.eriwen.gradle.css

import com.yahoo.platform.yui.compressor.CssCompressor

import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* Utility class that houses minification logic.
*
Expand Down Expand Up @@ -38,5 +40,41 @@ class CssMinifier {
writer.close()
}
}

fixCalcFunc(outputFile)
}

/**
* Fix issues related to calc function that came after CSS compression
* @param file File where function calc shall be fixed
*/
private void fixCalcFunc(File file) {
String text = file.text
file.withWriter(CHARSET) { writer ->
writer << addSpacesToOperatorsInCalcFunc(text)
}
}

/**
* Adds spaces to the operators for CSS calc functions
* @param string Input string
* @return Result
*/
private String addSpacesToOperatorsInCalcFunc(String string) {
StringBuffer stringBuffer = new StringBuffer()
Pattern pattern = ~/calc\([^\)]*\)/
Matcher matcher = pattern.matcher(string)
while (matcher.find()) {
String calcStr = matcher.group()

calcStr = calcStr.replaceAll(~/(?<=[%|px|em|rem|vw|\d]+)\+/, " + ")
calcStr = calcStr.replaceAll(~/(?<=[%|px|em|rem|vw|\d]+)-/ , " - ")
calcStr = calcStr.replaceAll(~/(?<=[%|px|em|rem|vw|\d]+)\*/, " * ")
calcStr = calcStr.replaceAll(~/(?<=[%|px|em|rem|vw|\d]+)\//, " / ")

matcher.appendReplacement(stringBuffer, calcStr)
}
matcher.appendTail(stringBuffer)
stringBuffer.toString()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class CssPluginFunctionalTest extends FunctionalSpec {
and:
tempProjectDir.newFolder('src', 'custom', 'css')
tempProjectDir.newFile("src/custom/css/file1.css") << "#id1 { color: green; }"
tempProjectDir.newFile("src/custom/css/file2.css") << ".class1 { color: red; }"
tempProjectDir.newFile("src/custom/css/file2.css") << ".class1 { color: red; width: calc(90% + 50px); }"

when:
BuildResult result = build('minifyCss')
Expand All @@ -38,7 +38,7 @@ class CssPluginFunctionalTest extends FunctionalSpec {
File minifiedCss = new File(projectDir, 'build/all-min.css')
minifiedCss.exists()
minifiedCss.text.indexOf('#id1{color:green}') > -1
minifiedCss.text.indexOf('.class1{color:red}') > -1
minifiedCss.text.indexOf('.class1{color:red;width:calc(90% + 50px)}') > -1

and:
result.task(':combineCss').outcome == TaskOutcome.SUCCESS
Expand Down