Skip to content

Commit 0ef7471

Browse files
WIP Implement Inspect protocol
1 parent 3215f53 commit 0ef7471

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

lib/floki/html_tree.ex

+48
Original file line numberDiff line numberDiff line change
@@ -328,4 +328,52 @@ defmodule Floki.HTMLTree do
328328
do_reduce(tree, fun.(head_node, acc), fun)
329329
end
330330
end
331+
332+
defimpl Inspect do
333+
import Inspect.Algebra
334+
335+
def inspect(html_tree, opts) do
336+
open = "%HTMLTree{"
337+
close = "}"
338+
container_opts = [separator: "", break: :flex]
339+
container_doc(open, html_tree.nodes, close, opts, &fun/2, container_opts)
340+
end
341+
342+
defp fun({tag, attributes, content}, opts) do
343+
tag_color = :map
344+
attribute_color = :map
345+
346+
attributes =
347+
for {name, value} <- attributes do
348+
concat([
349+
color(" #{name}=", attribute_color, opts),
350+
color("\"#{value}\"", :string, opts)
351+
])
352+
end
353+
|> concat()
354+
355+
open =
356+
concat([
357+
color("<#{tag}", tag_color, opts),
358+
attributes,
359+
color(">", tag_color, opts)
360+
])
361+
362+
close = color("</#{tag}>", tag_color, opts)
363+
container_opts = [separator: "", break: :strict]
364+
container_doc(open, content, close, opts, &fun/2, container_opts)
365+
end
366+
367+
defp fun({:comment, content}, opts) do
368+
color("<!-- #{content} -->", :comment, opts)
369+
end
370+
371+
defp fun(string, opts) when is_binary(string) do
372+
color(string, :string, opts)
373+
end
374+
375+
defp fun(other, _opts) do
376+
raise inspect(other)
377+
end
378+
end
331379
end

test/floki/html_tree_test.exs

+14
Original file line numberDiff line numberDiff line change
@@ -256,4 +256,18 @@ defmodule Floki.HTMLTreeTest do
256256
refute Enum.member?(html_tree, %{html_node3 | type: "marquee"})
257257
refute Enum.member?(html_tree, 42)
258258
end
259+
260+
test "Inspect works with HTMLTree" do
261+
html_tree = %HTMLTree{
262+
root_nodes_ids: [2, 1],
263+
node_ids: [2, 1],
264+
nodes: %{
265+
1 => %Text{content: "hello", node_id: 1},
266+
2 => %Text{content: " world", node_id: 2}
267+
}
268+
}
269+
270+
assert inspect(html_tree) ==
271+
~s|%HTMLTree{%Text{content: "hello", node_id: 1}<em>%Text{content: " world", node_id: 2}}|
272+
end
259273
end

0 commit comments

Comments
 (0)