nani.wtf/ssg/src/Formats/Gogen.hs

69 lines
2.0 KiB
Haskell
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

{-# LANGUAGE QuasiQuotes, FlexibleContexts #-}
module Formats.Gogen (
convertFuriganaTitle,
convertFuriganaTitleHtml,
gogenCtx,
) where
import Hakyll
import Debug.Trace (traceId)
import Data.Maybe (fromMaybe)
import Text.Regex.PCRE.Heavy (gsub, re)
--------------------------------------------------------------------------------
-- FURIGANA CONVERSION
type FuriganaTemplate = String
convertTitle = updateFieldWith "title" "???"
convertFuriganaTitle :: Item a -> Compiler String
convertFuriganaTitle = convertTitle replaceFuriganaWithKanji
convertFuriganaTitleHtml :: Item a -> Compiler String
convertFuriganaTitleHtml = convertTitle replaceFuriganaWithHtml
updateFieldWith :: String -> String -> (String -> String) -> Item a -> Compiler String
updateFieldWith field defaultPreviousValue f =
fmap updateField . getMetadata . itemIdentifier
where
updateField :: Metadata -> String
updateField = traceId . f . fromMaybe defaultPreviousValue . lookupString field
replaceFuriganaWithKanji :: FuriganaTemplate -> String
replaceFuriganaWithKanji = gsub [re|\[(.*?)\]\((.*?)\)|] (\(kanji:kana:_) -> kanji :: String)
replaceFuriganaWithHtml :: FuriganaTemplate -> String
replaceFuriganaWithHtml = between "<ruby>" "</ruby>" . gsub regex matchToHtml
where
regex = [re|\[(.*?)\]\((.*?)\)|]
between :: String -> String -> String -> String
between x y s = x ++ s ++ y
matchToHtml :: [String] -> String
matchToHtml (kanji:kana:_) =
let defaultKanji = if kanji == "" then "" else kanji
in foldr1 (++) ["<rb>", defaultKanji, "</rb> <rp>(</rp><rt>", kana, "</rt><rp>)</rp>"]
{- |
title: String
titleHtml: String
finished: Boolean
updated: String
lang: String
antonyms: Maybe [String]
synonyms: Maybe [String]
leads_here: Maybe [String]
alternatives: Maybe [String]
see_also: Maybe [String]
-}
gogenCtx :: Context String
gogenCtx =
dateField "date" "%Y-%m-%d"
<> field "titleHtml" convertFuriganaTitleHtml
<> defaultContext
<> constField "lang" "en"