Skip to content

Commit 91dc6ea

Browse files
committed
Support viewing source of JSON
1 parent 9c12062 commit 91dc6ea

File tree

2 files changed

+46
-2
lines changed

2 files changed

+46
-2
lines changed

lib/components_guide/fetch/response.ex

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,15 @@ defmodule ComponentsGuide.Fetch.Response do
3636
def add_error(receiver = %__MODULE__{}, error) do
3737
put_in(receiver.error, error)
3838
end
39+
40+
def find_header(receiver = %__MODULE__{}, header_name) when is_binary(header_name) do
41+
header_name = String.downcase(header_name)
42+
43+
Enum.find_value(receiver.headers, fn {name, value} ->
44+
case String.downcase(name) do
45+
^header_name -> value
46+
_ -> nil
47+
end
48+
end)
49+
end
3950
end

lib/components_guide_web/live/view_source.ex

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,8 @@ defmodule ComponentsGuideWeb.ViewSourceLive do
102102
<.headers_preview headers={@state.response.headers}>
103103
</.headers_preview>
104104
<%= if (@state.response.body || "") != "" do %>
105-
<.html_preview html={@state.response.body}>
106-
</.html_preview>
105+
<.body_preview content_type={Fetch.Response.find_header(@state.response, "content-type")} data={@state.response.body}>
106+
</.body_preview>
107107
<% end %>
108108
<% end %>
109109
</output>
@@ -112,6 +112,25 @@ defmodule ComponentsGuideWeb.ViewSourceLive do
112112
display: none;
113113
}
114114
</style>
115+
<script type="module">
116+
const lazyPrismObserver = new IntersectionObserver((entries) => {
117+
entries.forEach(entry => {
118+
if (entry.isIntersecting && !entry.target.dataset.highlighted) {
119+
entry.target.dataset.highlighted = '1';
120+
window.Prism.highlightAllUnder(entry.target);
121+
}
122+
});
123+
});
124+
window.customElements.define('lazy-prism', class extends HTMLElement {
125+
connectedCallback() {
126+
lazyPrismObserver.observe(this);
127+
}
128+
129+
disconnectedCallback() {
130+
lazyPrismObserver.unobserve(this);
131+
}
132+
})
133+
</script>
115134
"""
116135
end
117136

@@ -164,6 +183,20 @@ defmodule ComponentsGuideWeb.ViewSourceLive do
164183
"""
165184
end
166185

186+
def body_preview(assigns) do
187+
~H"""
188+
<%= if @content_type == "application/json" do %>
189+
<h2>JSON</h2>
190+
<lazy-prism>
191+
<pre class="text-left"><code class="language-json"><%= @data %></code></pre>
192+
</lazy-prism>
193+
<% end %>
194+
<%= if @content_type in ["text/html", "text/html; charset=utf-8"] do %>
195+
<.html_preview html={@data} />
196+
<% end %>
197+
"""
198+
end
199+
167200
def html_preview(assigns) do
168201
~H"""
169202
<%= for {kind, values} <- list_html_features(@html) do %>

0 commit comments

Comments
 (0)