marschro

marschro

Style formatting for nested elements with earmark or earmark_parser

Hello,

so I started to integrate markdown editing in my app and I ended up integrating earmark, which works fine for me.

Currently I have a utility function that I can call everywhere in my LiveViews in order to generate html from markdown.

Here how his looks ( I reuse styles, defined in my CoreComponents):

@doc """
  parse markdown to styled html

  """
  def markdown(nil), do: nil

  def markdown(content) do
    case Earmark.Parser.as_ast(content) do
      {:ok, ast, _warnings} ->
        ast
        |> parse_ast()
        |> Earmark.Transform.transform()

      {:error, _ast, warnings} ->
        {:warning, _id, msg} = List.first(warnings)
        "Invalid markup: #{msg}"
    end
  end

  defp parse_ast(ast) do
    ast
    |> Earmark.Transform.map_ast(fn node -> parse_node(node) end, ignore_strings: true)
    |> List.flatten()
  end

  defp parse_node({_tag, _attrs, _children_or_content, _meta} = node) do
    add = fn class_list ->
      fn node -> Earmark.AstTools.merge_atts_in_node(node, class: Enum.join(class_list, " ")) end
    end

    processors = [
      {"h1", add.(PortalWeb.CoreComponents.typography(:h1))},
      {"h2", add.(PortalWeb.CoreComponents.typography(:h2))},
      {"h3", add.(PortalWeb.CoreComponents.typography(:h3))},
      {"h4", add.(PortalWeb.CoreComponents.typography(:h4))},
      {"p", add.(PortalWeb.CoreComponents.typography(:p))},
      {"ul", add.(PortalWeb.CoreComponents.typography(:ul))},
      {"ol", add.(PortalWeb.CoreComponents.typography(:ol))},
      {"li", add.(PortalWeb.CoreComponents.typography(:li))},
      {"a", add.(PortalWeb.CoreComponents.typography(:a))},
      {"strong", add.(PortalWeb.CoreComponents.typography(:strong))},
      {"em", add.(PortalWeb.CoreComponents.typography(:em))},
      {"u", add.(PortalWeb.CoreComponents.typography(:u))},
      {"img", add.(PortalWeb.CoreComponents.typography(:img))},
      {"blockquote", add.(PortalWeb.CoreComponents.typography(:blockquote))},
      {"hr", add.(PortalWeb.CoreComponents.typography(:hr))},
      {"code", add.(PortalWeb.CoreComponents.typography(:code))},
      {"pre", add.(PortalWeb.CoreComponents.typography(:pre))}
    ]

    postprocessor =
      Earmark.Options.make_options!(registered_processors: processors)
      |> Earmark.Transform.make_postprocessor()

    postprocessor.(node)
  end

No I have two questions:

  1. I ran into the thing, that earmark_parser was extracted from earmark. So if I only use earmark_parser - how do I generate html markup from the generated ast ? With floki? How is that done.
  2. Also I struggle with styling nested elements like lists in list. Has anyone a good example how that can be achieved? Currently I only can add classes to every
  3. element but cannot differntiate if this is a list of 1st or second level… (don’t want to do that via css but with tailwind classes…)

Any advice appreciated :slight_smile:

… also how is such a cool editor done like this one I am typing in…

Most Liked

RobertDober

RobertDober

There is no built in way to do this easily as far as I remember, the idea is that you need to transform the ast yourself, here is a draft of how this should work

    defp add_level_att(tag, atts, inner, meta, level) do
      {
        tag,
        Keyword.put(atts, :class, "list-level-#{level}"),
        recursive_map(inner, level+1),
        meta
      }
    end

    defp recursive_map(ast, level)
    defp recursive_map(list, level) when is_list(list), do: Enum.map(list, &recursive_map(&1, level))
    defp recursive_map(leaf, _) when is_binary(leaf), do: leaf
    defp recursive_map({"ol", atts, inner, meta}, level), do: add_level_att("ol", atts, inner, meta, level)
    defp recursive_map({"ul", atts, inner, meta}, level), do: add_level_att("ul", atts, inner, meta, level)
    defp recursive_map({tag, atts, inner, meta}, level), do: {tag, atts, recursive_map(inner, level), meta}

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

Other popular topics Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New

We're in Beta

About us Mission Statement