summaryrefslogtreecommitdiff
path: root/src/Text/Hakyll/CompressCSS.hs
blob: 87453682ec15c14d80867624940a10ef24d8444d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
module Text.Hakyll.CompressCSS
    ( compressCSS
    ) where

import Data.List (isPrefixOf)
import Text.Regex (subRegex, mkRegex)

-- | subRegex with arguments flipped for easy function composition.
subRegex' :: String -> String -> String -> String
subRegex' pattern replacement str = subRegex (mkRegex pattern) str replacement

-- | Compress CSS to speed up your site.
compressCSS :: String -> String
compressCSS = compressSeparators
            . compressWhitespace
            . stripComments

-- | Compresses certain forms of separators.
compressSeparators :: String -> String
compressSeparators = subRegex' ";\\s*}" "}" 
                   . subRegex' "\\s*([{};:])\\s*" "\\1"
                   . subRegex' ";;*" ";"

-- | Compresses all whitespace.
compressWhitespace :: String -> String
compressWhitespace = subRegex' "\\s\\s*" " "

-- | Function that strips CSS comments away.
stripComments :: String -> String
stripComments [] = []
stripComments str | isPrefixOf "/*" str = stripComments $ eatComments $ drop 2 str
                  | otherwise = (head str) : (stripComments $ tail str)
    where eatComments str' | null str' = []
                           | isPrefixOf "*/" str' = drop 2 str'
                           | otherwise = eatComments $ tail str'