~alcinnz/haskell-stylist

70713fc6cd143e6cb67bd1e82d486e6686a6d621 — Adrian Cochrane 4 years ago b24d420
Fix compilation of Assets StyleSheets.
1 files changed, 11 insertions(+), 7 deletions(-)

M src/Data/CSS/Preprocessor/Assets.hs
M src/Data/CSS/Preprocessor/Assets.hs => src/Data/CSS/Preprocessor/Assets.hs +11 -7
@@ 1,3 1,5 @@
{-# LANGUAGE OverloadedStrings #-}
-- | Utilities for rewriting URLs referenced via CSS properties.
module Data.CSS.Preprocessor.Assets(StyleAssets(..), URIRewriter) where

-- TODO Unit test!


@@ 5,6 7,7 @@ import           Data.Text as Txt
import           Network.URI
import qualified Data.CSS.Syntax.StyleSheet as CSS
import qualified Data.CSS.Syntax.Tokens as CSSTok
import           Data.List (nub, elem)

-- | Extracts referenced URLs from specified properties.
data StyleAssets = StyleAssets {


@@ 15,25 18,26 @@ data StyleAssets = StyleAssets {
}

instance CSS.StyleSheet StyleAssets where
    addRule (StyleAssets filterProps self) (CSS.StyleRule _ props _) =
        StyleAssets filterProps $ nub (
            self ++ [uri | (prop, val) <- props,
                    prop `elem` filterProps,
    addRule self (CSS.StyleRule _ props _) =
        StyleAssets (filterProps self) $ nub (
            assets self ++ [uri | (prop, val) <- props,
                    prop `elem` filterProps self,
                    CSSTok.Url text <- val,
                    Just uri <- [parseAbsoluteURI $ Txt.unpack text]]
            )


-- | Substitutes in given URLs into a property value.
rewritePropertyVal :: [(URI, URI)] -> [CSSTok.Token] -> [CSSTok.Token] 
rewritePropertyVal rewrites (CSSTok.Url text:vals)
    | Just uri <- parseURIReference $ Txt.unpack text, Just rewrite <- uri `M.lookup` rewrites =
    | Just uri <- parseURIReference $ Txt.unpack text, Just rewrite <- uri `lookup` rewrites =
        CSSTok.Url (Txt.pack $ uriToString id rewrite "") : rewritePropertyVal rewrites vals
    | otherwise = CSSTok.Url "" : rewritePropertyVal rewrites vals
rewritePropertyVal rewrites (val:vals) = val:rewritePropertyVal rewrites vals
rewritePropertyVal _ [] = []

-- | Substitutes in given URLs into the inner stylesheet being parsed.
data URIRewriter s = URIRewriter (M.Map URI URI) s
data URIRewriter s = URIRewriter [(URI, URI)] s
instance CSS.StyleSheet s => CSS.StyleSheet (URIRewriter s) where
    setPriority p (URIRewriter r s) = URIRewriter r $ CSS.setPriority p s
    addRule (URIRewriter r s) (CSS.StyleRule sel props psuedo) =


@@ 41,4 45,4 @@ instance CSS.StyleSheet s => CSS.StyleSheet (URIRewriter s) where
            (prop, rewritePropertyVal r val) | (prop, val) <- props
        ] psuedo
    addAtRule (URIRewriter r s) name toks =
        let (self', toks') = CSS.addAtRule s name toks in (URIRewriter r s, toks)
        let (self', toks') = CSS.addAtRule s name toks in (URIRewriter r self', toks')