2015-12-05 14:12:20 +01:00
|
|
|
module Text.Pandoc.CSS ( foldOrElse
|
|
|
|
, pickStyleAttrProps
|
|
|
|
, pickStylesToKVs
|
2015-07-24 02:53:17 -04:00
|
|
|
)
|
|
|
|
where
|
|
|
|
|
|
|
|
import Text.Pandoc.Shared (trim)
|
|
|
|
import Text.Parsec
|
|
|
|
import Text.Parsec.String
|
|
|
|
|
|
|
|
ruleParser :: Parser (String, String)
|
|
|
|
ruleParser = do
|
|
|
|
p <- many1 (noneOf ":") <* char ':'
|
2017-06-02 15:06:14 +02:00
|
|
|
v <- many1 (noneOf ":;") <* optional (char ';') <* spaces
|
2015-07-24 02:53:17 -04:00
|
|
|
return (trim p, trim v)
|
|
|
|
|
|
|
|
styleAttrParser :: Parser [(String, String)]
|
2015-11-22 07:38:51 -08:00
|
|
|
styleAttrParser = many1 ruleParser
|
2015-07-24 02:53:17 -04:00
|
|
|
|
|
|
|
orElse :: Eq a => a -> a -> a -> a
|
|
|
|
orElse v x y = if v == x then y else x
|
|
|
|
|
|
|
|
foldOrElse :: Eq a => a -> [a] -> a
|
|
|
|
foldOrElse v xs = foldr (orElse v) v xs
|
|
|
|
|
|
|
|
eitherToMaybe :: Either a b -> Maybe b
|
|
|
|
eitherToMaybe (Right x) = Just x
|
2017-03-04 13:03:41 +01:00
|
|
|
eitherToMaybe _ = Nothing
|
2015-07-24 02:53:17 -04:00
|
|
|
|
2015-12-05 14:12:20 +01:00
|
|
|
-- | takes a list of keys/properties and a CSS string and
|
|
|
|
-- returns the corresponding key-value-pairs.
|
|
|
|
pickStylesToKVs :: [String] -> String -> [(String, String)]
|
|
|
|
pickStylesToKVs props styleAttr =
|
|
|
|
case parse styleAttrParser "" styleAttr of
|
2017-03-04 13:03:41 +01:00
|
|
|
Left _ -> []
|
2015-12-05 14:12:20 +01:00
|
|
|
Right styles -> filter (\s -> fst s `elem` props) styles
|
|
|
|
|
|
|
|
-- | takes a list of key/property synonyms and a CSS string and maybe
|
|
|
|
-- returns the value of the first match (in order of the supplied list)
|
2015-07-24 02:53:17 -04:00
|
|
|
pickStyleAttrProps :: [String] -> String -> Maybe String
|
|
|
|
pickStyleAttrProps lookupProps styleAttr = do
|
|
|
|
styles <- eitherToMaybe $ parse styleAttrParser "" styleAttr
|
|
|
|
foldOrElse Nothing $ map (flip lookup styles) lookupProps
|