-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsite.hs
More file actions
331 lines (278 loc) · 13.4 KB
/
site.hs
File metadata and controls
331 lines (278 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
{-# LANGUAGE OverloadedStrings, TupleSections #-}
-- Initial Author: Massimo Zaniboni <massimo.zaniboni@docmelody.com>
-- Code partially based on https://github.com/gislik/gisli.hamstur.is
import Data.Typeable (Typeable)
import Data.Binary (Binary)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>), mconcat)
import Data.List (intercalate, intersperse, isSuffixOf, elemIndex)
import Data.Char (toLower, toUpper)
import Data.Time.Clock (UTCTime (..))
import Control.Monad (msum, filterM, (<=<), filterM)
import Data.Time.Format (TimeLocale, defaultTimeLocale, parseTimeM, formatTime)
import Text.Blaze.Html (toHtml, toValue, (!))
import Text.Blaze.Html.Renderer.String (renderHtml)
import qualified Data.Map as M
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import System.FilePath
import Hakyll
--------------------------------------------------------------------------------
main :: IO ()
main =
hakyll $ do
categories <- buildCategories blogPattern (fromCapture "*/index.html")
tags <- buildTags blogPattern (fromCapture "*/index.html")
pages <- buildPages Nothing blogPattern
-- static content
match ("*.png" .||. "*.txt" .||. "images/**" .||. "*.ico" .||. "css/**" .||. "js/**" .||. "fonts/**") $ do
route idRoute
compile copyFileCompiler
-- blogs
match blogPattern $ do
route blogRoute
compile $ pandocCompiler
>>= saveSnapshot blogSnapshot
>>= loadAndApplyTemplate "templates/blog.html" (blogDetailCtx categories tags)
>>= loadAndApplyTemplate "templates/default.html" (defaultCtx Nothing categories tags)
-- index
match "index.html" $ do
route idRoute
compile $
getResourceBody
>>= applyAsTemplate (pageCtx (Just "home") 1 pages categories tags)
>>= loadAndApplyTemplate "templates/default.html" (indexCtx (Just "home") categories tags)
match "about.md" $ do
route pageRoute
compile $ pandocCompiler
>>= loadAndApplyTemplate "templates/page.html" (defaultCtx (Just "about") categories tags)
>>= loadAndApplyTemplate "templates/default.html" (defaultCtx (Just "about") categories tags)
-- pages
paginateRules pages $ \i _ -> do
route idRoute
compile $ makeItem (show i)
>>= loadAndApplyTemplate "templates/blog-list.html" (pageCtx Nothing i pages categories tags)
>>= loadAndApplyTemplate "templates/default.html" (defaultCtx Nothing categories tags)
-- category index
tagsRules categories $ \category patt -> do
catPages <- buildPages (Just category) patt
route idRoute
compile $
makeItem category
>>= loadAndApplyTemplate "templates/blog-list.html" (pageCtx (Just category) 1 catPages categories tags)
>>= loadAndApplyTemplate "templates/default.html" (indexCtx (Just category) categories tags)
-- category pages
paginateRules catPages $ \i _ -> do
route idRoute
compile $
makeItem category
>>= loadAndApplyTemplate "templates/blog-list.html" (pageCtx (Just category) i catPages categories tags)
>>= loadAndApplyTemplate "templates/default.html" (defaultCtx (Just category) categories tags)
-- feeds
create ["atom.xml"] $ do
route idRoute
compile $ renderBlogAtom <=< fmap (take 20) . loadBlogs $ blogPattern
-- templates
match "templates/*.html" $ compile templateCompiler
--------------------------------------------------------------------------------
-- CONFIGURATION
--------------------------------------------------------------------------------
-- | The settings used for generating Atom Feeds.
myFeedConfiguration :: FeedConfiguration
myFeedConfiguration = FeedConfiguration
{ feedTitle = "Haskell-ITA"
, feedDescription = "The Italian Community of Haskell Programmers"
, feedAuthorName = "Haskell-ITA"
, feedAuthorEmail = "info@haskell-ita.it"
, feedRoot = "http://www.haskell-ita.it"
}
blogPattern :: Pattern
blogPattern = "posts/**"
blogSnapshot :: Snapshot
blogSnapshot = "blog-content"
blogPerPage :: Int
blogPerPage = 10
blogOrder :: (MonadMetadata m, Functor m) => [Item a] -> m [Item a]
blogOrder = recentFirst
--------------------------------------------------------------------------------
-- CONTEXTS
--------------------------------------------------------------------------------
indexCtx :: Maybe String -> Tags -> Tags -> Context String
indexCtx activeSection categories tags =
prettyTitleField "title" <>
bodyField "body" <>
metadataField <>
urlField "url" <>
pathField "path" <>
missingField <>
defaultCtx activeSection categories tags
-- | Add categories as top menu, and tags to the context.
-- DEV-NOTE: I generated directly the "categoriesEntries" in the HTML format requested from the template.
-- This is not elegant, but I was not able to generate a list of distinct high-level attributes to use in
-- the template for formatting the produced HTML page.
defaultCtx :: Maybe String -> Tags -> Tags -> Context String
defaultCtx activeSection categories tags =
field "categoriesEntries" (const (renderTagListForTopMenu activeSection categories)) <>
field "tagsEntries" (const (renderTagListForTopMenu Nothing tags)) <>
defaultContext
pageCtx :: Maybe String -> PageNumber -> Paginate -> Tags -> Tags -> Context String
pageCtx activeSection i pages categories tags =
blogListField "blogs" categories (loadBlogs patt) <>
field "categories" (const . renderTagList' $ categories) <>
constField "title" "Pagination" <>
paginateContext' pages i <>
defaultCtx activeSection categories tags
where
patt = fromList . fromMaybe [] . M.lookup i . paginateMap $ pages
paginateContext' pages i = mapContextP (isSuffixOf "Url") dropFileName (paginateContext pages i)
blogListField name categories = listField name (blogDetailCtx categories tags)
blogDetailCtx :: Tags -> Tags -> Context String
blogDetailCtx categories tags =
dateField "date" "%Y-%m-%d" <>
mapContext dropFileName (urlField "url") <>
categoryField' "category" categories <>
teaserField "teaser" blogSnapshot <>
defaultCtx Nothing categories tags
feedsCtx :: Context String
feedsCtx =
cdataContext metadataField <>
bodyField "description" <>
urlField "url" <>
defaultContext
where
cdataContext = mapContext (\s -> "<![CDATA[" <> s <> "]]>")
getPeople :: MonadMetadata m => Identifier -> m [String]
getPeople identifier = do
metadata <- getMetadata identifier
return $ maybe [] (map trim . splitAll ",") $ lookupString "author" metadata
--------------------------------------------------------------------------------
-- ROUTES
--------------------------------------------------------------------------------
blogRoute :: Routes
blogRoute =
customRoute (takeFileName . toFilePath) `composeRoutes`
metadataRoute dateRoute `composeRoutes`
dropDateRoute `composeRoutes`
pageRoute
where
dateRoute metadata = customRoute $ \id' -> joinPath [dateFolder id' metadata, toFilePath id']
dateFolder id' = maybe mempty (formatTime defaultTimeLocale "%Y/%m") . tryParseDate id'
dropDateRoute = gsubRoute "[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}-" (const mempty)
pageRoute :: Routes
pageRoute = removeExtension `composeRoutes` addIndex
where
removeExtension = setExtension mempty
addIndex = postfixRoute "index.html"
postfixRoute postfix = customRoute $ (</> postfix) . toFilePath
--------------------------------------------------------------------------------
-- HELPERS
--------------------------------------------------------------------------------
-- contexts
mapContextP :: (String -> Bool) -> (String -> String) -> Context a -> Context a
mapContextP p f c'@(Context c) = Context $ \k a i ->
if p k
then unContext (mapContext f c') k a i
else c k a i
prettyTitleField :: String -> Context a
prettyTitleField = mapContext (defaultTitle . pageTitle) . pathField
where
pageTitle :: String -> String
pageTitle = intercalate " ❯❯= " . splitDirectories . capitalize . dropFileName
defaultTitle :: String -> String
defaultTitle "." = "Blog"
defaultTitle x = x
capitalize :: String -> String
capitalize [] = []
capitalize (x:xs) = toUpper x : map toLower xs
categoryField' :: String -> Tags -> Context a -- drops the filename from the link
categoryField' = tagsFieldWith getCategory simpleRenderLink (mconcat . intersperse ", ")
where
getCategory :: Identifier -> Compiler [String]
getCategory = return . return . takeBaseName . takeDirectory . toFilePath
-- compilers
loadBlogs :: (Typeable a, Binary a) => Pattern -> Compiler [Item a]
loadBlogs = blogOrder <=< flip loadAllSnapshots blogSnapshot
buildPages :: (MonadMetadata m, Functor m) => Maybe String -> Pattern -> m Paginate
buildPages mprefix patt =
buildPaginateWith
(fmap (paginateEvery blogPerPage) . sortRecentFirst)
patt
(asIdentifier mprefix . show)
where
asIdentifier :: Maybe String -> String -> Identifier
asIdentifier Nothing = fromCapture "*/index.html"
asIdentifier (Just pre) = fromCapture . fromGlob $ pre <> "/*/index.html"
renderTagList' :: Tags -> Compiler String -- drops the filename from the link
renderTagList' = renderTags makeLink unwords
where
makeLink tag url count _ _ = renderHtml $
H.a ! A.href (toValue . dropFileName $ url) $ toHtml (tag ++ " (" ++ show count ++ ")")
-- | Create an HTML list in the format specifically requested from the template.
-- This function contains also all the definitions for the Top menu of the BLOG
renderTagListForTopMenu :: Maybe String -> Tags -> Compiler String
renderTagListForTopMenu activeSection tags = do
let s1 = makeLi "home" "Home" "/"
let s2 = makeLi "about" "Chi Siamo" "/about/index.html"
s3 <- renderTags makeLink unwords orderedTags
return $ s1 ++ " " ++ s2 ++ " " ++ s3
where
makeLi :: String -> String -> String -> String
makeLi tag nameOnMenu url =
let classStr = if Just tag == activeSection
then "blog-nav-item active"
else "blog-nav-item"
in renderHtml $ H.a ! A.href (toValue url) ! A.class_ classStr $ toHtml nameOnMenu
-- | Convert names from English to Italian
fromTagToMenuName :: String -> String
fromTagToMenuName "coding" = "Codice Haskell"
fromTagToMenuName "events" = "Eventi"
fromTagToMenuName "tools" = "Come Iniziare"
fromTagToMenuName n = n
-- | Order entries on the top down menu
menuOrder :: [String]
menuOrder = ["events", "tools", "coding"]
tagOrder :: String -> String -> Ordering
tagOrder x y
= case elemIndex x menuOrder of
Nothing -> GT
Just xx
-> case elemIndex y menuOrder of
Nothing -> LT
Just yy -> compare xx yy
orderedTags = sortTagsBy (\x y -> tagOrder (fst x) (fst y)) tags
makeLink tag url _ _ _ = makeLi tag (fromTagToMenuName tag) (dropFileName url)
renderBlogAtom :: [Item String] -> Compiler (Item String)
renderBlogAtom = renderAtom myFeedConfiguration feedsCtx
-- metadata
includeTagM :: MonadMetadata m => String -> [Identifier] -> m [Identifier]
includeTagM tag = filterTagsM (return . elem tag)
filterTagsM :: MonadMetadata m => ([String] -> m Bool) -> [Identifier] -> m [Identifier]
filterTagsM p = filterM $ p <=< getTags
-- html
simpleRenderLink :: String -> Maybe FilePath -> Maybe H.Html
simpleRenderLink _ Nothing = Nothing
simpleRenderLink tag (Just filePath) =
Just $ H.a ! A.href (toValue $ toUrl . dropFileName $ filePath) $ toHtml tag
-- dates
tryParseDate :: Identifier -> Metadata -> Maybe UTCTime
tryParseDate = tryParseDateWithLocale defaultTimeLocale
tryParseDateWithLocale :: TimeLocale -> Identifier -> Metadata -> Maybe UTCTime
tryParseDateWithLocale locale id' metadata = do
let tryField k fmt = lookupString k metadata >>= parseTime' fmt
fn = takeFileName $ toFilePath id'
maybe empty' return $ msum $
[tryField "published" fmt | fmt <- formats] ++
[tryField "date" fmt | fmt <- formats] ++
[parseTime' "%Y-%m-%d" $ intercalate "-" $ take 3 $ splitAll "-" fn]
where
empty' = fail $ "Hakyll.Web.Template.Context.getItemUTC: "
++ "could not parse time for " ++ show id'
parseTime' = parseTimeM True locale
formats =
[ "%a, %d %b %Y %H:%M:%S %Z"
, "%Y-%m-%dT%H:%M:%S%Z"
, "%Y-%m-%d %H:%M:%S%Z"
, "%Y-%m-%d"
, "%B %e, %Y %l:%M %p"
, "%B %e, %Y"
]