on 294fdfd help sign in
elk/compiler/Gen/GenerateHtml.hs
73 lines 2.6 kB history raw
1{-# LANGUAGE OverloadedStrings #-}
2module GenerateHtml (generateHtml,
3 modulesToHtml, linkedHtml,
4 JSStyle (..)
5 ) where
7import Data.List (intercalate)
8import Text.Blaze (preEscapedToMarkup)
9import Text.Blaze.Html (Html)
10import qualified Text.Blaze.Html5 as H
11import Text.Blaze.Html5 ((!))
12import qualified Text.Blaze.Html5.Attributes as A
14import Text.Jasmine (minify)
15import qualified Data.ByteString.Lazy.Char8 as BS
17import Ast
18import Initialize
19import CompileToJS
20import ExtractNoscript
22data JSStyle = Minified | Readable
24makeScript :: JSStyle -> Either String String -> H.Html
25makeScript _ (Left s) =
26 H.script ! A.type_ "text/javascript" ! A.src (H.toValue s) $ ""
27makeScript jsStyle (Right s) =
28 H.script ! A.type_ "text/javascript" $ preEscapedToMarkup content
29 where content = case jsStyle of
30 Minified -> BS.unpack . minify . BS.pack $ s
31 Readable -> s
33-- |This function compiles Elm code into simple HTML.
34--
35-- Usage example:
36--
37-- > generateHtml "/elm-min.js" "Some title" [elmFile|elm-source/somePage.elm|]
38generateHtml :: String -- ^ Location of elm-runtime.js as expected by the browser
39 -> String -- ^ The page title
40 -> String -- ^ The elm source code.
41 -> Html
42generateHtml libLoc title source =
43 case buildFromSource source of
44 Left err -> createHtml Readable libLoc title (Right $ showErr err) (H.noscript "") "Elm.Main"
45 Right modul -> modulesToHtml Readable title libLoc [] True [modul]
48modulesToHtml jsStyle title libLoc jss nscrpt modules =
49 createHtml jsStyle libLoc title' js noscript altTitle
50 where
51 js = Right $ jss ++ concatMap jsModule modules
52 noscript = if nscrpt then extractNoscript $ last modules else ""
53 title' = if null title then altTitle else title
54 altTitle = intercalate "." names
55 where Module names _ _ _ = last modules
58linkedHtml rtLoc jsLoc modules =
59 createHtml Readable rtLoc title (Left jsLoc) (H.noscript "") title
60 where
61 title = (\(Module names _ _ _) -> intercalate "." names) (last modules)
64createHtml jsStyle libLoc title js noscript moduleToLoad =
65 H.docTypeHtml $ do
66 H.head $ do
67 H.meta ! A.charset "UTF-8"
68 H.title . H.toHtml $ title
69 H.body $ do
70 makeScript Readable (Left libLoc)
71 makeScript jsStyle js
72 H.script ! A.type_ "text/javascript" $ preEscapedToMarkup ("Elm.init(Elm." ++ moduleToLoad ++ ")" :: String)
73 H.noscript $ preEscapedToMarkup noscript