Current section

Files

Jump to
whistle lib whistle html.ex
Raw

lib/whistle/html.ex

defmodule Whistle.Html do
defp attributes_to_string(attributes) do
attributes
|> Enum.map(fn {key, value} ->
~s(#{key}="#{value}")
end)
|> Enum.join(" ")
end
def diff_text({key, {:text, [], text}}, {key, {:text, [], text}}) do
[]
end
def diff_text({key, {:text, [], text}}, {key, {:text, [], text2}}) do
[{:replace_text, [key], text2}]
end
def diff_text({_key, _}, {_key, _}) do
[]
end
def diff_tag({key, {tag, _, _}}, {key, {tag, _, _}}) do
[]
end
def diff_tag({key, {tag, _, _}}, {key, node}) do
[
{:replace_node, [], node}
]
end
def diff_children({key, {_, _, children}}, {key, {_, _, new_children}}) when is_list(children) and is_list(new_children) do
children
|> Enum.zip(new_children)
|> Enum.reduce([], fn {a, b}, ops ->
ops ++ diff([key], a, b)
end)
end
def diff_children({_key, _}, {_key, _}) do
[]
end
def diff(path, node1, node2) do
[]
|> Enum.concat(diff_text(node1, node2))
|> Enum.concat(diff_children(node1, node2))
|> Enum.concat(diff_tag(node1, node2))
|> Enum.map(fn {op, key, value} ->
{op, path ++ key, value}
end)
end
def to_string(node = {tag, attributes, content}) do
__MODULE__.to_string({0, node})
end
def to_string({_, {:text, [], content}}) do
content
end
def to_string({key, {tag, attributes, children}}) do
children =
children
|> Enum.map(&__MODULE__.to_string/1)
|> Enum.join("")
~s(<#{tag} key="#{key}" #{attributes_to_string(attributes)}>#{children}</#{tag}>)
end
def node(tag, attributes, children) do
children =
children
|> Enum.with_index()
|> Enum.map(fn {node, index} ->
{index, node}
end)
{tag, attributes, children}
end
def div(attributes, children) do
node("div", attributes, children)
end
def p(attributes, children) do
node("p", attributes, children)
end
def text(content) do
{:text, [], content}
end
end