module GalleryPage (make) where
import Control.Exception
import Data.Function (on, (&))
import Data.List (sortBy, groupBy)
import qualified Data.Text.Lazy as Lazy
import Data.Text.Lazy.Builder (Builder, toLazyText)
import System.FilePath ((>), takeDirectory)
import BuilderQQ
import Depend (thumbFile)
import Info
newtype NoThumb = NoThumb FilePath
deriving stock Eq deriving anyclass Exception
instance Show NoThumb where show (NoThumb dir) = "no thumbnail for " ++ dir
make :: Text -- ^ title
-> Bool -- ^ nsfw is included?
-> [(FilePath, Info)]
-> Lazy.Text
make title nsfw infos = toLazyText $ make' title nsfw infos
make' :: Text -> Bool -> [(FilePath, Info)] -> Builder
make' title nsfw infos = [b|@0
$*title
|]
where
items = map (uncurry $ makeYearItems nsfw) infosByYear
infosByYear =
infos & sortBy (cmpInfo `on` #second)
& map (\fi -> (fi, #year $ #second fi))
& groupBy ((==) `on` #second)
& map (\ys -> (#second (head ys), map #first ys))
cmpInfo (Info {date = d1, title = t1}) (Info {date = d2, title = t2}) =
compare d2 d1 <> compare t1 t2
makeYearItems :: Bool -- ^ nsfw
-> Integer -- ^ year
-> [(FilePath, Info)]
-> Builder
makeYearItems nsfw year infos = [b|@4
$^year
$4.items
|]
where items = map (uncurry $ makeItem nsfw) infos
makeItem :: Bool -> FilePath -> Info -> Builder
makeItem nsfw file info = [b|@4
|]
where
dir = takeDirectory file
thumb = maybe (throw $ NoThumb dir) (\t -> dir > thumbFile t) $ #thumb info
title = maybe mempty mkTitle $ #title info
mkTitle t = [b|@8
$*t
|]
cls | nsfw && #anyNsfw info = [b|class="item nsfw"|]
| otherwise = [b|class=item|]