{-| Contains all utilities related to markdown processing
-}
module Dhall.Docs.Markdown
    ( MarkdownParseError(..)
    , markdownToHtml
    ) where

import Data.Text       (Text)
import Lucid
import Path            (File, Path, Rel)
import Text.Megaparsec (ParseErrorBundle (..))
import Text.MMark      (MMarkErr)

import qualified Path
import qualified Text.MMark as MMark

-- | Wrapper around `MMarkErr` errors
newtype MarkdownParseError = MarkdownParseError
    { MarkdownParseError -> ParseErrorBundle Text MMarkErr
unwrap :: ParseErrorBundle Text MMarkErr
    }

{-| Takes a text that could contain markdown and returns the generated HTML.
    If an error occurs while parsing, it also returns the error information.
-}
markdownToHtml
    :: Path Rel File -- ^ Used by `Mmark.parse` for error messages
    -> Text          -- ^ Text to parse
    -> Either MarkdownParseError (Html ())
markdownToHtml :: Path Rel File -> Text -> Either MarkdownParseError (Html ())
markdownToHtml Path Rel File
relFile Text
contents =
    case FilePath -> Text -> Either (ParseErrorBundle Text MMarkErr) MMark
MMark.parse (Path Rel File -> FilePath
Path.fromRelFile Path Rel File
relFile) Text
contents of
        Left ParseErrorBundle Text MMarkErr
err -> MarkdownParseError -> Either MarkdownParseError (Html ())
forall a b. a -> Either a b
Left MarkdownParseError :: ParseErrorBundle Text MMarkErr -> MarkdownParseError
MarkdownParseError { unwrap :: ParseErrorBundle Text MMarkErr
unwrap = ParseErrorBundle Text MMarkErr
err }
        Right MMark
mmark -> Html () -> Either MarkdownParseError (Html ())
forall a b. b -> Either a b
Right (Html () -> Either MarkdownParseError (Html ()))
-> Html () -> Either MarkdownParseError (Html ())
forall a b. (a -> b) -> a -> b
$ MMark -> Html ()
MMark.render MMark
mmark