Debian Codegraph @

src/Lucid/Base.hs

raw symbols SCIP
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE BangPatterns #-}
3 {-# LANGUAGE FunctionalDependencies #-}
4 {-# LANGUAGE FlexibleInstances #-}
5 {-# LANGUAGE MultiParamTypeClasses #-}
6 {-# LANGUAGE GADTs #-}
7 {-# LANGUAGE TypeOperators #-}
8
9 -- Search for UndecidableInstances to see why this is needed
10 {-# LANGUAGE UndecidableInstances #-}
11
12 -- | Base types and combinators.
13
14 module Lucid.Base
15 (-- * Rendering
16 renderText
17 ,renderBS
18 ,renderTextT
19 ,renderBST
20 ,renderToFile
21 -- * Running
22 ,execHtmlT
23 ,evalHtmlT
24 ,runHtmlT
25 ,relaxHtmlT
26 ,commuteHtmlT
27 -- * Combinators
28 ,makeElement
29 ,makeElementNoEnd
30 ,makeXmlElementNoEnd
31 ,makeAttribute
32 -- * Types
33 ,Html
34 ,HtmlT(HtmlT)
35 ,Attribute(..)
36 -- * Classes
37 ,Term(..)
38 ,TermRaw(..)
39 ,ToHtml(..)
40 ,With(..))
41 where
42
43 import Blaze.ByteString.Builder (Builder)
44 import qualified Blaze.ByteString.Builder as Blaze
45 import qualified Blaze.ByteString.Builder.Html.Utf8 as Blaze
46 import Control.Applicative
47 import Control.Monad
48 import Control.Monad.Morph (MFunctor(..))
49 import Control.Monad.Reader (MonadReader(..))
50 import Control.Monad.IO.Class (MonadIO(..))
51 import Control.Monad.Fix (MonadFix(..))
52 import Control.Monad.Trans (MonadTrans(..))
53 import Control.Monad.Error.Class (MonadError(..))
54 import Control.Monad.State.Class (MonadState(..))
55 import Control.Monad.Writer.Class (MonadWriter(..))
56 import Data.ByteString.Lazy (ByteString)
57 import qualified Data.ByteString.Lazy as L
58 import qualified Data.ByteString as S
59 import Data.Functor.Identity
60 import qualified Data.Map.Strict as M
61 import Data.Hashable (Hashable(..))
62 import Data.Semigroup (Semigroup (..))
63 import Data.Monoid (Monoid (..))
64 import Data.String
65 import Data.Text (Text)
66 import qualified Data.Text.Lazy as LT
67 import qualified Data.Text.Lazy.Encoding as LT
68 import qualified Data.Text.Encoding as T
69 import Prelude
70 import Data.Maybe
71 import Data.Sequence (Seq)
72 import qualified Data.Sequence as Seq
73 import Data.Foldable (toList)
74 import qualified Data.Set as Set
75
76 --------------------------------------------------------------------------------
77 -- Types
78
79 -- | A simple attribute. Don't use the constructor, use
80 -- 'makeAttribute'. Attributes are case sensitive, so if you want
81 -- attributes to be merged properly, use a single case representation.
82 data Attribute = Attribute !Text !Text
83 deriving (Show,Eq)
84
85 instance Hashable Attribute where
86 hashWithSalt salt (Attribute a b) = salt `hashWithSalt` a `hashWithSalt` b
87
88 -- | Simple HTML builder type. Defined in terms of 'HtmlT'. Check out
89 -- that type for instance information.
90 --
91 -- Simple use-cases will just use this type. But if you want to
92 -- transformer over Reader or something, you can go and use 'HtmlT'.
93 type Html = HtmlT Identity
94
95 -- | A monad transformer that generates HTML. Use the simpler 'Html'
96 -- type if you don't want to transform over some other monad.
97 --
98 -- Don't rely on the internal representation of this type. Use the
99 -- monad and functor classes.
100 newtype HtmlT m a =
101 HtmlT {runHtmlT :: m (Seq Attribute -> Builder,a)
102 -- ^ This is the low-level way to run the HTML transformer,
103 -- finally returning an element builder and a value. You can
104 -- pass 'mempty' for this argument for a top-level call. See
105 -- 'evalHtmlT' and 'execHtmlT' for easier to use functions.
106 }
107
108 -- | @since 2.9.5
109 instance MFunctor HtmlT where
110 hoist f (HtmlT xs) = HtmlT (f xs)
111
112 -- | @since 2.9.7
113 instance (a ~ (),Applicative m) => Semigroup (HtmlT m a) where
114 (<>) = liftA2 (<>)
115
116 -- | Monoid is right-associative, a la the 'Builder' in it.
117 instance (a ~ (),Applicative m) => Monoid (HtmlT m a) where
118 mempty = pure mempty
119 mappend = liftA2 mappend
120
121 -- | Based on the monad instance.
122 instance Applicative m => Applicative (HtmlT m) where
123 pure a = HtmlT (pure (mempty,a))
124 {-# INLINE pure #-}
125
126 f <*> x = HtmlT $ mk <$> runHtmlT f <*> runHtmlT x
127 where mk ~(g, f') ~(h, x') = (g <> h, f' x')
128 {-# INLINE (<*>) #-}
129
130 m *> n = HtmlT $ mk <$> runHtmlT m <*> runHtmlT n
131 where mk ~(g, _) ~(h, b) = (g <> h, b)
132 {-# INLINE (*>) #-}
133
134 m <* n = HtmlT $ mk <$> runHtmlT m <*> runHtmlT n
135 where mk ~(g, a) ~(h, _) = (g <> h, a)
136 {-# INLINE (<*) #-}
137
138 -- | Just re-uses Monad.
139 instance Functor m => Functor (HtmlT m) where
140 fmap f = HtmlT . fmap (fmap f) . runHtmlT
141
142 (<$) = fmap . const
143 {-# INLINE (<$) #-}
144
145 -- | Basically acts like Writer.
146 instance Monad m => Monad (HtmlT m) where
147 return a = HtmlT (return (mempty,a))
148 {-# INLINE return #-}
149
150 m >>= f = HtmlT $ do
151 ~(g,a) <- runHtmlT m
152 ~(h,b) <- runHtmlT (f a)
153 return (g <> h,b)
154 {-# INLINE (>>=) #-}
155
156 m >> n = HtmlT $ do
157 ~(g, _) <- runHtmlT m
158 ~(h, b) <- runHtmlT n
159 return (g <> h, b)
160 {-# INLINE (>>) #-}
161
162 -- | Used for 'lift'.
163 instance MonadTrans HtmlT where
164 lift m =
165 HtmlT (do a <- m
166 return (\_ -> mempty,a))
167
168 instance MonadFix m => MonadFix (HtmlT m) where
169 mfix m = HtmlT $ mfix $ \ ~(_, a) -> runHtmlT $ m a
170
171 -- MonadReader, MonadState etc instances need UndecidableInstances,
172 -- because they do not satisfy the coverage condition.
173
174 -- | @since 2.9.7
175 instance MonadReader r m => MonadReader r (HtmlT m) where
176 ask = lift ask
177 local f (HtmlT a) = HtmlT (local f a)
178
179 -- | @since 2.9.7
180 instance MonadState s m => MonadState s (HtmlT m) where
181 get = lift get
182 put = lift . put
183 state = lift . state
184
185 -- | @since 2.9.9
186 instance MonadError e m => MonadError e (HtmlT m) where
187 throwError = lift . throwError
188 catchError (HtmlT m) h = HtmlT $ catchError m (runHtmlT . h)
189
190 -- | @since 2.9.9
191 instance MonadWriter w m => MonadWriter w (HtmlT m) where
192 tell = lift . tell
193 listen (HtmlT x) = HtmlT $ fmap reassoc $ listen x
194 where reassoc ((a, b), c) = (a, (b, c))
195 pass (HtmlT p) = HtmlT $ pass $ fmap assoc p
196 where assoc (a, (b, c)) = ((a, b), c)
197
198 -- | If you want to use IO in your HTML generation.
199 instance MonadIO m => MonadIO (HtmlT m) where
200 liftIO = lift . liftIO
201
202 -- | We pack it via string. Could possibly encode straight into a
203 -- builder. That might be faster.
204 instance (Monad m,a ~ ()) => IsString (HtmlT m a) where
205 fromString = toHtml
206
207 -- | Just calls 'renderText'.
208 instance (m ~ Identity) => Show (HtmlT m a) where
209 show = LT.unpack . renderText
210
211 -- | Can be converted to HTML.
212 class ToHtml a where
213 -- | Convert to HTML, doing HTML escaping.
214 toHtml :: Monad m => a -> HtmlT m ()
215 -- | Convert to HTML without any escaping.
216 toHtmlRaw :: Monad m => a -> HtmlT m ()
217
218 -- | @since 2.9.8
219 instance (a ~ (), m ~ Identity) => ToHtml (HtmlT m a) where
220 toHtml = relaxHtmlT
221 toHtmlRaw = relaxHtmlT
222
223 instance ToHtml String where
224 toHtml = build . Blaze.fromHtmlEscapedString
225 toHtmlRaw = build . Blaze.fromString
226
227 instance ToHtml Text where
228 toHtml = build . Blaze.fromHtmlEscapedText
229 toHtmlRaw = build . Blaze.fromText
230
231 instance ToHtml LT.Text where
232 toHtml = build . Blaze.fromHtmlEscapedLazyText
233 toHtmlRaw = build . Blaze.fromLazyText
234
235 -- | This instance requires the ByteString to contain UTF-8 encoded
236 -- text, for the 'toHtml' method. The 'toHtmlRaw' method doesn't care,
237 -- but the overall HTML rendering methods in this module assume UTF-8.
238 --
239 -- @since 2.9.5
240 instance ToHtml S.ByteString where
241 toHtml = build . Blaze.fromHtmlEscapedText . T.decodeUtf8
242 toHtmlRaw = build . Blaze.fromByteString
243
244 -- | This instance requires the ByteString to contain UTF-8 encoded
245 -- text, for the 'toHtml' method. The 'toHtmlRaw' method doesn't care,
246 -- but the overall HTML rendering methods in this module assume UTF-8.
247 --
248 -- @since 2.9.5
249 instance ToHtml L.ByteString where
250 toHtml = build . Blaze.fromHtmlEscapedLazyText . LT.decodeUtf8
251 toHtmlRaw = build . Blaze.fromLazyByteString
252
253 -- | Create an 'HtmlT' directly from a 'Builder'.
254 build :: Monad m => Builder -> HtmlT m ()
255 build b = HtmlT (return (const b,()))
256 {-# INLINE build #-}
257
258 -- | Used to construct HTML terms.
259 --
260 -- Simplest use: p_ = term "p" yields 'Lucid.Html5.p_'.
261 --
262 -- Very overloaded for three cases:
263 --
264 -- * The first case is the basic @arg@ of @[(Text,Text)]@ which will
265 -- return a function that wants children.
266 -- * The second is an @arg@ which is @HtmlT m ()@, in which case the
267 -- term accepts no attributes and just the children are used for the
268 -- element.
269 -- * Finally, this is also used for overloaded attributes, like
270 -- `Lucid.Html5.style_` or `Lucid.Html5.title_`. If a return type of @(Text,Text)@ is inferred
271 -- then an attribute will be made.
272 --
273 -- The instances look intimidating but actually the constraints make
274 -- it very general so that type inference works well even in the
275 -- presence of things like @OverloadedLists@ and such.
276 class Term arg result | result -> arg where
277 -- | Used for constructing elements e.g. @term "p"@ yields 'Lucid.Html5.p_'.
278 term :: Text -- ^ Name of the element or attribute.
279 -> arg -- ^ Either an attribute list or children.
280 -> result -- ^ Result: either an element or an attribute.
281 term = flip termWith []
282 {-# INLINE term #-}
283
284 -- | Use this if you want to make an element which inserts some
285 -- pre-prepared attributes into the element.
286 termWith :: Text -- ^ Name.
287 -> [Attribute] -- ^ Attribute transformer.
288 -> arg -- ^ Some argument.
289 -> result -- ^ Result: either an element or an attribute.
290
291 -- | Given attributes, expect more child input.
292 instance (Applicative m,f ~ HtmlT m a) => Term [Attribute] (f -> HtmlT m a) where
293 termWith name f = with (makeElement name) . (<> f)
294
295 -- | Given children immediately, just use that and expect no
296 -- attributes.
297 instance (Applicative m) => Term (HtmlT m a) (HtmlT m a) where
298 termWith name f = with (makeElement name) f
299 {-# INLINE termWith #-}
300
301 -- | Some terms (like 'Lucid.Html5.style_', 'Lucid.Html5.title_') can be used for
302 -- attributes as well as elements.
303 instance Term Text Attribute where
304 termWith key _ value = makeAttribute key value
305
306 -- | Same as the 'Term' class, but will not HTML escape its
307 -- children. Useful for elements like 'Lucid.Html5.style_' or
308 -- 'Lucid.Html5.script_'.
309 class TermRaw arg result | result -> arg where
310 -- | Used for constructing elements e.g. @termRaw "p"@ yields 'Lucid.Html5.p_'.
311 termRaw :: Text -- ^ Name of the element or attribute.
312 -> arg -- ^ Either an attribute list or children.
313 -> result -- ^ Result: either an element or an attribute.
314 termRaw = flip termRawWith []
315 -- | Use this if you want to make an element which inserts some
316 -- pre-prepared attributes into the element.
317 termRawWith :: Text -- ^ Name.
318 -> [Attribute] -- ^ Attribute transformer.
319 -> arg -- ^ Some argument.
320 -> result -- ^ Result: either an element or an attribute.
321
322 -- | Given attributes, expect more child input.
323 instance (Monad m,ToHtml f, a ~ ()) => TermRaw [Attribute] (f -> HtmlT m a) where
324 termRawWith name f attrs = with (makeElement name) (attrs <> f) . toHtmlRaw
325
326 -- | Given children immediately, just use that and expect no
327 -- attributes.
328 instance (Monad m,a ~ ()) => TermRaw Text (HtmlT m a) where
329 termRawWith name f = with (makeElement name) f . toHtmlRaw
330
331 -- | Some termRaws (like 'Lucid.Html5.style_', 'Lucid.Html5.title_') can be used for
332 -- attributes as well as elements.
333 instance TermRaw Text Attribute where
334 termRawWith key _ value = makeAttribute key value
335
336 -- | With an element use these attributes. An overloaded way of adding
337 -- attributes either to an element accepting attributes-and-children
338 -- or one that just accepts attributes. See the two instances.
339 class With a where
340 -- | With the given element(s), use the given attributes.
341 with :: a -- ^ Some element, either @Html a@ or @Html a -> Html a@.
342 -> [Attribute]
343 -> a
344
345 -- | For the contentless elements: 'Lucid.Html5.br_'
346 instance (Functor m) => With (HtmlT m a) where
347 with f = \attr -> HtmlT (mk attr <$> runHtmlT f)
348 where
349 mk attr ~(f',a) = (\attr' -> f' (attr' <> Seq.fromList attr)
350 ,a)
351
352 -- | For the contentful elements: 'Lucid.Html5.div_'
353 instance (Functor m) => With (HtmlT m a -> HtmlT m a) where
354 with f = \attr inner -> HtmlT (mk attr <$> runHtmlT (f inner))
355 where
356 mk attr ~(f',a) = (\attr' -> f' (attr' <> Seq.fromList attr)
357 ,a)
358
359 --------------------------------------------------------------------------------
360 -- Running
361
362 -- | Render the HTML to a lazy 'ByteString'.
363 --
364 -- This is a convenience function defined in terms of 'execHtmlT',
365 -- 'runIdentity' and 'Blaze.toLazyByteString'. Check the source if
366 -- you're interested in the lower-level behaviour.
367 --
368 renderToFile :: FilePath -> Html a -> IO ()
369 renderToFile fp = L.writeFile fp . Blaze.toLazyByteString . runIdentity . execHtmlT
370
371 -- | Render the HTML to a lazy 'ByteString'.
372 --
373 -- This is a convenience function defined in terms of 'execHtmlT',
374 -- 'runIdentity' and 'Blaze.toLazyByteString'. Check the source if
375 -- you're interested in the lower-level behaviour.
376 --
377 renderBS :: Html a -> ByteString
378 renderBS = Blaze.toLazyByteString . runIdentity . execHtmlT
379
380 -- | Render the HTML to a lazy 'Text'.
381 --
382 -- This is a convenience function defined in terms of 'execHtmlT',
383 -- 'runIdentity' and 'Blaze.toLazyByteString', and
384 -- 'LT.decodeUtf8'. Check the source if you're interested in the
385 -- lower-level behaviour.
386 --
387 renderText :: Html a -> LT.Text
388 renderText = LT.decodeUtf8 . Blaze.toLazyByteString . runIdentity . execHtmlT
389
390 -- | Render the HTML to a lazy 'ByteString', but in a monad.
391 --
392 -- This is a convenience function defined in terms of 'execHtmlT' and
393 -- 'Blaze.toLazyByteString'. Check the source if you're interested in
394 -- the lower-level behaviour.
395 --
396 renderBST :: Monad m => HtmlT m a -> m ByteString
397 renderBST = fmap Blaze.toLazyByteString . execHtmlT
398
399 -- | Render the HTML to a lazy 'Text', but in a monad.
400 --
401 -- This is a convenience function defined in terms of 'execHtmlT' and
402 -- 'Blaze.toLazyByteString', and 'LT.decodeUtf8'. Check the source if
403 -- you're interested in the lower-level behaviour.
404 --
405 renderTextT :: Monad m => HtmlT m a -> m LT.Text
406 renderTextT = fmap (LT.decodeUtf8 . Blaze.toLazyByteString) . execHtmlT
407
408 --------------------------------------------------------------------------------
409 -- Running, transformer versions
410
411 -- | Build the HTML. Analogous to @execState@.
412 --
413 -- You might want to use this is if you want to do something with the
414 -- raw 'Builder'. Otherwise for simple cases you can just use
415 -- 'renderText' or 'renderBS'.
416 execHtmlT :: Monad m
417 => HtmlT m a -- ^ The HTML to generate.
418 -> m Builder -- ^ The @a@ is discarded.
419 execHtmlT m =
420 do (f,_) <- runHtmlT m
421 return (f mempty)
422
423 -- | Generalize the underlying monad.
424 --
425 -- Some builders are happy to deliver results in a pure underlying
426 -- monad, here 'Identity', but have trouble maintaining the polymorphic
427 -- type. This utility generalizes from 'Identity'.
428 --
429 -- @since 2.9.6
430 relaxHtmlT :: Monad m
431 => HtmlT Identity a -- ^ The HTML generated purely.
432 -> HtmlT m a -- ^ Same HTML accessible in a polymorphic context.
433 relaxHtmlT = hoist go
434 where
435 go :: Monad m => Identity a -> m a
436 go = return . runIdentity
437
438 -- | Commute inner @m@ to the front.
439 --
440 -- This is useful when you have impure HTML generation, e.g. using `StateT`.
441 -- Recall, there is `MonadState s HtmlT` instance.
442 --
443 -- @
444 -- exampleHtml :: MonadState Int m => HtmlT m ()
445 -- exampleHtml = ul_ $ replicateM_ 5 $ do
446 -- x <- get
447 -- put (x + 1)
448 -- li_ $ toHtml $ show x
449 --
450 -- exampleHtml' :: Monad m => HtmlT m ()
451 -- exampleHtml' = evalState (commuteHtmlT exampleHtml) 1
452 -- @
453 --
454 -- @since 2.9.9
455 commuteHtmlT :: (Functor m, Monad n)
456 => HtmlT m a -- ^ unpurely generated HTML
457 -> m (HtmlT n a) -- ^ Commuted monads. /Note:/ @n@ can be 'Identity'
458 commuteHtmlT (HtmlT xs) = fmap (HtmlT . return) xs
459
460 -- | Evaluate the HTML to its return value. Analogous to @evalState@.
461 --
462 -- Use this if you want to ignore the HTML output of an action
463 -- completely and just get the result.
464 --
465 -- For using with the 'Html' type, you'll need 'runIdentity' e.g.
466 --
467 -- >>> runIdentity (evalHtmlT (p_ "Hello!"))
468 -- ()
469 --
470 evalHtmlT :: Monad m
471 => HtmlT m a -- ^ HTML monad to evaluate.
472 -> m a -- ^ Ignore the HTML output and just return the value.
473 evalHtmlT m =
474 do (_,a) <- runHtmlT m
475 return a
476
477 --------------------------------------------------------------------------------
478 -- Combinators
479
480 -- | Make an attribute builder.
481 makeAttribute :: Text -- ^ Attribute name.
482 -> Text -- ^ Attribute value.
483 -> Attribute
484 makeAttribute x y = Attribute x y
485
486 -- | Make an HTML builder.
487 makeElement :: Functor m
488 => Text -- ^ Name.
489 -> HtmlT m a -- ^ Children HTML.
490 -> HtmlT m a -- ^ A parent element.
491 {-# INLINE[1] makeElement #-}
492 makeElement name = \m' -> HtmlT (mk <$> runHtmlT m')
493 where
494 mk ~(f,a) =
495 (\attr ->
496 s "<" <> Blaze.fromText name
497 <> foldlMapWithKey buildAttr attr <> s ">"
498 <> f mempty
499 <> s "</" <> Blaze.fromText name <> s ">"
500 ,a)
501
502 -- | Make an HTML builder for elements which have no ending tag.
503 makeElementNoEnd :: Applicative m
504 => Text -- ^ Name.
505 -> HtmlT m () -- ^ A parent element.
506 makeElementNoEnd name =
507 HtmlT (pure (\attr -> s "<" <> Blaze.fromText name
508 <> foldlMapWithKey buildAttr attr <> s ">",
509 ()))
510
511 -- | Make an XML builder for elements which have no ending tag.
512 makeXmlElementNoEnd :: Applicative m
513 => Text -- ^ Name.
514 -> HtmlT m () -- ^ A parent element.
515 makeXmlElementNoEnd name =
516 HtmlT (pure (\attr -> s "<" <> Blaze.fromText name
517 <> foldlMapWithKey buildAttr attr <> s "/>",
518 ()))
519
520 -- | Build and encode an attribute.
521 buildAttr :: Text -> Text -> Builder
522 buildAttr key val =
523 s " " <>
524 Blaze.fromText key <>
525 if val == mempty
526 then mempty
527 else s "=\"" <> Blaze.fromHtmlEscapedText val <> s "\""
528
529 -- | Folding and monoidally appending attributes.
530 foldlMapWithKey :: (Text -> Text -> Builder) -> Seq Attribute -> Builder
531 foldlMapWithKey f attributes =
532 case nubOrdMaybe (map fst pairs) of
533 Just keyList ->
534 foldMap (\k -> fromMaybe mempty (fmap (f k) (M.lookup k values))) keyList
535 where values = M.fromListWith (<>) pairs
536 Nothing -> foldMap (\(Attribute k v) -> f k v) attributes
537 where
538 pairs = map (\(Attribute k v) -> (k,v)) (toList attributes)
539
540 -- | Do a nubOrd, but only return Maybe if it actually removes anything.
541 nubOrdMaybe :: Ord a => [a] -> Maybe [a]
542 nubOrdMaybe = go False Set.empty []
543 where
544 go (!removed) set acc (x:xs)
545 | x `Set.member` set = go True set acc xs
546 | otherwise = go removed (Set.insert x set) (x : acc) xs
547 go removed _set acc [] =
548 if removed
549 then pure (reverse acc)
550 else Nothing
551
552 -- | Convenience function for constructing builders.
553 s :: String -> Builder
554 s = Blaze.fromString
555 {-# INLINE s #-}