diff --git a/lib/music_library_web/components/notes_component.ex b/lib/music_library_web/components/notes_component.ex index d0940f98..b770e3f1 100644 --- a/lib/music_library_web/components/notes_component.ex +++ b/lib/music_library_web/components/notes_component.ex @@ -3,6 +3,7 @@ defmodule MusicLibraryWeb.NotesComponent do alias MusicLibrary.Notes alias MusicLibrary.Notes.Note + alias MusicLibraryWeb.Markdown def open(id), do: Fluxon.open_dialog(id) @@ -148,7 +149,7 @@ defmodule MusicLibraryWeb.NotesComponent do defp render_notes(notes) do (notes || "") - |> Earmark.as_html!(%Earmark.Options{gfm: true}) + |> Markdown.to_html() |> raw() end end diff --git a/lib/music_library_web/markdown.ex b/lib/music_library_web/markdown.ex new file mode 100644 index 00000000..1c91b976 --- /dev/null +++ b/lib/music_library_web/markdown.ex @@ -0,0 +1,42 @@ +defmodule MusicLibraryWeb.Markdown do + @moduledoc """ + Custom markdown processor that handles double square bracket links. + + Text wrapped in double square brackets like `[[Foo]]` will be rendered as + search links to the collection page. + """ + + @doc """ + Converts markdown with custom `[[link]]` syntax to HTML. + + Double square brackets are converted to search links before the markdown is processed. + """ + def to_html(markdown_text) when is_binary(markdown_text) do + markdown_text + |> process_double_bracket_links() + |> Earmark.as_html!(%Earmark.Options{gfm: true}) + end + + def to_html(nil), do: "" + + @doc """ + Processes text to convert [[text]] patterns into markdown links. + + ## Examples + + iex> MusicLibraryWeb.Markdown.process_double_bracket_links("Check out [[Porcupine Tree]]") + "Check out [Porcupine Tree](/collection?query=Porcupine+Tree)" + + iex> MusicLibraryWeb.Markdown.process_double_bracket_links("Albums like [[Steven Wilson - The Raven That Refused to Sing (and Other Stories) (2013)]] are great") + "Albums like [Steven Wilson - The Raven That Refused to Sing (and Other Stories) (2013)](/collection?query=Steven+Wilson+-+The+Raven+That+Refused+to+Sing+%28and+Other+Stories%29+%282013%29) are great" + """ + def process_double_bracket_links(text) do + # Regex to match [[text]] patterns + ~r/\[\[([^\]]+)\]\]/ + |> Regex.replace(text, fn _match, content -> + # URL encode the content for the search query + encoded_content = URI.encode_www_form(content) + "[#{content}](/collection?query=#{encoded_content})" + end) + end +end diff --git a/test/music_library_web/markdown_test.exs b/test/music_library_web/markdown_test.exs new file mode 100644 index 00000000..c16a921c --- /dev/null +++ b/test/music_library_web/markdown_test.exs @@ -0,0 +1,5 @@ +defmodule MusicLibraryWeb.MarkdownTest do + use ExUnit.Case, async: true + + doctest MusicLibraryWeb.Markdown +end