defmodule Premailex do @external_resource "README.md" @moduledoc "README.md" |> File.read!() |> String.split("") |> Enum.fetch!(1) # Replace Markdown-linked HexDocs cross-references with plain # references so ExDoc can resolve links correctly. |> then(&Regex.replace(~r/\[(`[^`]+`)\]\([^)]+\)/, &1, "\\1")) # Convert Markdown OTP module references to ExDoc format. |> then(&Regex.replace(~r/`(:[a-z]+)`/, &1, "`m:\\1`")) require Logger @type html :: String.t() @type html_element :: {String.t(), [{String.t(), String.t()}], [html_node()]} @type html_node :: html_element() | {:comment, String.t()} | String.t() @type html_tree :: [html_node()] @doc """ Parses an HTML string into a `t:html_tree/0`. ## Options * `:html_parser` - HTML parser to use (see `Premailex.HTMLParser`); ## Examples iex> Premailex.parse(~s(
Hello
)) [{"p", [{"class", "lead"}], ["Hello"]}] """ @spec parse(html(), Keyword.t()) :: html_tree() def parse(html, options \\ []) do html_parser = Keyword.get_lazy(options, :html_parser, &html_parser/0) html_parser.parse(html) end defp html_parser do case Application.get_env(:premailex, :html_parser) || default_html_parser() do mod when is_atom(mod) -> mod other -> raise "Invalid `:html_parser` environment value: #{inspect(other)}" end end defp default_html_parser do cond do Code.ensure_loaded?(LazyHTML) -> Premailex.HTMLParser.LazyHTML Code.ensure_loaded?(Floki) -> Premailex.HTMLParser.Floki Code.ensure_loaded?(Meeseeks) -> Premailex.HTMLParser.Meeseeks true -> Premailex.HTMLParser.Xmerl end end @doc """ Converts a `t:html_tree/0` into an HTML string. ## Options * `:html_parser` - HTML parser to use (see `Premailex.HTMLParser`); ## Examples iex> Premailex.to_html([{"p", [{"class", "lead"}], ["Hello"]}]) ~s(Hello
) """ @spec to_html(html_tree(), Keyword.t()) :: html() def to_html(tree, options \\ []) do html_parser = Keyword.get_lazy(options, :html_parser, &html_parser/0) html_parser.to_html(tree) end @doc """ Adds inline styles to an HTML string or `t:html_tree/0`. ## Options * `:html_parser` - HTML parser to use (see `Premailex.HTMLParser`); * `:http_adapter` - HTTP adapter to use for fetching external stylesheets (see `Premailex.HTTPAdapter`); * `:remove_style_tags` - whether to remove the ` ...> ...>Text
...>