Skip to content

Commit

Permalink
WIP Implement Inspect protocol
Browse files Browse the repository at this point in the history
  • Loading branch information
vittoriabitton committed Feb 28, 2024
1 parent 3215f53 commit c0c20d1
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
49 changes: 49 additions & 0 deletions lib/floki/html_tree.ex
Original file line number Diff line number Diff line change
Expand Up @@ -328,4 +328,53 @@ defmodule Floki.HTMLTree do
do_reduce(tree, fun.(head_node, acc), fun)
end
end

defimpl Inspect do
import Inspect.Algebra

def inspect(html_tree, opts) do
open = "%HTMLTree{"
close = "}"
container_opts = [separator: "", break: :flex]

container_doc(open, Floki.HTMLTree.to_tuple_list(html_tree), close, opts, &fun/2, container_opts)
end

defp fun({tag, attributes, content}, opts) do
tag_color = :map
attribute_color = :map

attributes =
for {name, value} <- attributes do
concat([
color(" #{name}=", attribute_color, opts),
color("\"#{value}\"", :string, opts)
])
end
|> concat()

open =
concat([
color("<#{tag}", tag_color, opts),
attributes,
color(">", tag_color, opts)
])

close = color("</#{tag}>", tag_color, opts)
container_opts = [separator: "", break: :strict]
container_doc(open, content, close, opts, &fun/2, container_opts)
end

defp fun({:comment, content}, opts) do
color("<!-- #{content} -->", :comment, opts)
end

defp fun(string, opts) when is_binary(string) do
color(string, :string, opts)
end

defp fun(other, _opts) do
raise inspect(other)
end
end
end
14 changes: 14 additions & 0 deletions test/floki/html_tree_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -256,4 +256,18 @@ defmodule Floki.HTMLTreeTest do
refute Enum.member?(html_tree, %{html_node3 | type: "marquee"})
refute Enum.member?(html_tree, 42)
end

test "Inspect works with HTMLTree" do

Check failure on line 260 in test/floki/html_tree_test.exs

View workflow job for this annotation

GitHub Actions / Elixir 1.13 / OTP 22.3 with fast_html

test Inspect works with HTMLTree (Floki.HTMLTreeTest)

Check failure on line 260 in test/floki/html_tree_test.exs

View workflow job for this annotation

GitHub Actions / Elixir 1.13 / OTP 22.3 with html5ever

test Inspect works with HTMLTree (Floki.HTMLTreeTest)

Check failure on line 260 in test/floki/html_tree_test.exs

View workflow job for this annotation

GitHub Actions / Elixir 1.13 / OTP 22.3 with mochiweb

test Inspect works with HTMLTree (Floki.HTMLTreeTest)
html_tree = %HTMLTree{
root_nodes_ids: [2, 1],
node_ids: [2, 1],
nodes: %{
1 => %Text{content: "hello", node_id: 1},
2 => %Text{content: " world", node_id: 2}
}
}

assert inspect(html_tree) ==
~s|%HTMLTree{%Text{content: "hello", node_id: 1}<em>%Text{content: " world", node_id: 2}}|
end
end

0 comments on commit c0c20d1

Please sign in to comment.