Skip to content

Commit ad34f22

Browse files
committed
Chapter 5.1 - Convert markup to HTML
1 parent 9f951a0 commit ad34f22

4 files changed

Lines changed: 41 additions & 13 deletions

File tree

Convert.hs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
-- Convert.hs
2+
3+
module Convert where
4+
5+
import qualified Markup
6+
import qualified Html
7+
8+
convert :: Html.Title -> Markup.Document -> Html.Html
9+
convert title = Html.html_ title . foldMap convertStructure
10+
11+
convertStructure :: Markup.Structure -> Html.Structure
12+
convertStructure structure =
13+
case structure of
14+
Markup.Heading n txt ->
15+
Html.h_ n txt
16+
17+
Markup.Paragraph p ->
18+
Html.p_ p
19+
20+
Markup.UnorderedList list ->
21+
Html.ul_ $ map Html.p_ list
22+
23+
Markup.OrderedList list ->
24+
Html.ol_ $ map Html.p_ list
25+
26+
Markup.CodeBlock list ->
27+
Html.code_ (unlines list)

Html.hs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,11 @@ module Html
55
, Title
66
, Structure
77
, html_
8-
, h1_
8+
, h_
99
, p_
1010
, ul_
1111
, ol_
1212
, code_
13-
, append_
1413
, render
1514
)
1615
where

Html/Internal.hs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
module Html.Internal where
44

5+
import Numeric.Natural
6+
57
-- * Types
68

79
newtype Html
@@ -27,8 +29,8 @@ html_ title content =
2729
p_ :: String -> Structure
2830
p_ = Structure . el "p" . escape
2931

30-
h1_ :: String -> Structure
31-
h1_ = Structure . el "h1" . escape
32+
h_ :: Natural -> String -> Structure
33+
h_ n = Structure . el ("h" <> show n) . escape
3234

3335
ul_ :: [Structure] -> Structure
3436
ul_ =
@@ -41,9 +43,12 @@ ol_ =
4143
code_ :: String -> Structure
4244
code_ = Structure . el "pre" . escape
4345

44-
append_ :: Structure -> Structure -> Structure
45-
append_ c1 c2 =
46-
Structure (getStructureString c1 <> getStructureString c2)
46+
instance Semigroup Structure where
47+
(<>) c1 c2 =
48+
Structure (getStructureString c1 <> getStructureString c2)
49+
50+
instance Monoid Structure where
51+
mempty = Structure ""
4752

4853
-- * Render
4954

hello.hs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,7 @@ myhtml :: Html
99
myhtml =
1010
html_
1111
"My title"
12-
( append_
13-
(h1_ "Heading")
14-
( append_
15-
(p_ "Paragraph #1")
16-
(p_ "Paragraph #2")
17-
)
12+
( h_ 1 "Heading"
13+
<> p_ "Paragraph #1"
14+
<> p_ "Paragraph #2"
1815
)

0 commit comments

Comments
 (0)