sloane.sh/lib/sloane_sh/markdown.ex

40 lines
923 B
Elixir
Raw Normal View History

2024-02-16 22:28:13 -05:00
defmodule SloaneSH.Markdown do
@moduledoc """
Markdown parsing using `Earmark` and `Earmark.Parser`
"""
require Logger
use TypedStruct
2024-02-16 22:28:13 -05:00
alias SloaneSH.Context
2024-02-24 08:43:08 -05:00
alias SloaneSH.FrontMatter
alias __MODULE__
2024-02-16 22:28:13 -05:00
typedstruct do
field :attrs, map(), default: %{}
field :html, String.t(), default: ""
2024-02-24 10:32:07 -05:00
field :text, String.t(), default: ""
end
def transform(%Context{} = ctx, data) when is_binary(data) do
2024-02-24 10:32:07 -05:00
with {:ok, attrs, body} <- FrontMatter.parse(data, ctx),
{:ok, html, msgs} <- Earmark.as_html(body),
{:ok, html_tree} <- Floki.parse_fragment(html) do
for msg <- msgs, do: Logger.warning(msg)
{:ok,
%Markdown{
attrs: attrs,
2024-02-24 10:32:07 -05:00
html: html,
text: Floki.text(html_tree, sep: " ")
}}
else
{:error, _, msgs} ->
for msg <- msgs, do: Logger.error(msg)
:error
_ ->
:error
end
end
2024-02-16 22:28:13 -05:00
end