fixes, styling improvement including inlined code

This commit is contained in:
Adam Piontek 2021-04-06 14:45:54 -04:00
parent 97f9c4a9f2
commit 816fdbb484
5 changed files with 121 additions and 27 deletions
lib
home73k
home73k_web/live

View file

@ -63,7 +63,7 @@ defmodule Home73k.Blog.Post do
# """ parse_body/1
# Convert body markdown to html, and highlight code fence blocks
defp parse_body({fm, md}) do
html = Earmark.as_html!(md) |> Highlighter.highlight_code_blocks()
html = Earmark.as_html!(md) |> Highlighter.highlight_all()
Map.put(fm, :body, html)
end

View file

@ -8,7 +8,14 @@ defmodule Home73k.Highlighter do
@chroma_bin Home73k.app_chroma_bin() |> Path.expand()
@doc """
Highlights all code block in an already generated HTML document.
Highlights all code in HTML (fenced code blocks and inlined code)
"""
def highlight_all(html) do
highlight_code_blocks(html) |> highlight_code_inlined()
end
@doc """
Highlights fenced code blocks in HTML document
"""
def highlight_code_blocks(html) do
~r/<pre><code(?:\s+class="(\w*)")?>([^<]*)<\/code><\/pre>/
@ -16,6 +23,31 @@ defmodule Home73k.Highlighter do
end
defp highlight_code_block(_full_block, lang, code) do
# perform the code highlighting
highlighted = highlight_code(lang, code)
# return properly wrapped highlighted code
~s(<pre class="chroma"><code class="language-#{lang}">#{highlighted}</code></pre>)
end
@doc """
Highlights inlined code in HTML document
"""
def highlight_code_inlined(html) do
~r/<code(?:\s+class="inline lang-(\w*)")?>([^<]*)<\/code>/
|> Regex.replace(html, &highlight_code_inline(&1, &2, &3))
end
defp highlight_code_inline(_full_block, lang, code) do
# perform the code highlighting
highlighted = highlight_code(lang, code)
# return properly wrapped highlighted code
~s(<code class="inline chroma language-#{lang}">#{highlighted}</code>)
end
# """
# Performs code highlighting using chroma
# """
defp highlight_code(lang, code) do
# unescape the code
unescaped_code = unescape_html(code) |> IO.iodata_to_binary()
@ -25,12 +57,12 @@ defmodule Home73k.Highlighter do
# use chroma to highlight the code via temp file
bin_args = ["-l", lang, "-f", "html", "--html-only", "--html-prevent-surrounding-pre", tmp_file]
{highlighted, _} = System.cmd(@chroma_bin, bin_args)
# return properly wrapped highlighted code
~s(<pre class="chroma"><code class="language-#{lang}">#{highlighted}</code></pre>)
System.cmd(@chroma_bin, bin_args) |> elem(0)
end
# """
# Code below for unescaping html, since it's escaped by Earmark markdown parsing
# """
entities = [{"&amp;", ?&}, {"&lt;", ?<}, {"&gt;", ?>}, {"&quot;", ?"}, {"&#39;", ?'}]
for {encoded, decoded} <- entities do

View file

@ -60,7 +60,7 @@ defmodule Home73kWeb.BlogLive do
defp init_per_live_action(:show, socket, %{"id" => id}) do
post = Blog.get_post_by_id!(id)
socket
|> assign(:page_title, "Blog \\ post.title")
|> assign(:page_title, "Blog \\ #{post.title}")
|> assign(:posts, [post])
|> assign(:page_count, nil)
|> assign_prev_next(0)