module Web.CSS.Escaping
( escapeIdentifier
, escapeString
) where
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB
import qualified Data.Text.Lazy.Builder.Int as TLBI
escapeChar :: Char -> TL.Text
escapeChar =
TL.cons '\\' .
TL.justifyRight 6 '0' .
TLB.toLazyText .
TLBI.hexadecimal .
fromEnum
escapeIdentifier :: TL.Text -> TL.Text
escapeIdentifier = TL.concatMap escape
where
escape c | c >= 'a' && c <= 'z' = TL.singleton c
escape c | c >= 'A' && c <= 'Z' = TL.singleton c
escape c | c >= '0' && c <= '9' = TL.singleton c
escape c @ '_' = TL.singleton c
escape c @ '-' = TL.singleton c
escape c | c >= ' ' && c <= '~' = TL.pack ['\\', c]
escape c = escapeChar c
escapeString :: TL.Text -> TL.Text
escapeString s =
TL.concat [ TL.pack "\""
, TL.concatMap escape s
, TL.pack "\""
]
where
escape c | c < ' ' = escapeChar c
escape c | c > '~' = escapeChar c
escape c @ '"' = TL.pack ['\\', c]
escape c = TL.singleton c