My space on the web https://inhji.de
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

55 lines
1.3 KiB

defmodule Mirage.Markdown do
import Ecto.Changeset, only: [get_change: 2, put_change: 3]
def maybe_render_markdown(changeset, markdown_field, html_field) do
if markdown = get_change(changeset, markdown_field) do
html = render(markdown)
put_change(changeset, html_field, html)
else
changeset
end
end
@crossref_regex ~r/\[\[(?<id>\d+)(?:\|([\w\d\s]+))?\]\]/
def get_references(markdown) do
@crossref_regex
|> Regex.scan(markdown, capture: :all_but_first)
end
def render(markdown) do
options = %Earmark.Options{
code_class_prefix: "lang- language-"
}
markdown
|> get_references()
|> Enum.reduce(markdown, &replace_with_link/2)
|> Earmark.as_html!(options)
end
def replace_with_link([note_id, title], markdown) do
case Mirage.Notes.get_note(note_id) do
nil ->
markdown
note ->
Regex.replace(@crossref_regex, markdown, get_link(note.id, title), global: false)
end
end
def replace_with_link([note_id], markdown) do
case Mirage.Notes.get_note(note_id) do
nil ->
markdown
note ->
String.replace(markdown, "[[#{note_id}]]", get_link(note.id, note.title))
end
end
def get_link(id, title) do
"[#{title}](/notes/#{id})"
end
end