From 843b16e9467b00e8f2c46de2ecf57c97bedb760a Mon Sep 17 00:00:00 2001 From: Adrian Salamon Date: Tue, 11 Jul 2023 22:49:22 +0200 Subject: [PATCH] made markdown header ids to slugs ala github markdown --- lib/haj/markdown.ex | 29 ++++++++++++++++--- .../live/responsibility_live/show.html.heex | 6 ++-- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/lib/haj/markdown.ex b/lib/haj/markdown.ex index cf3d1d7..85ad4a4 100644 --- a/lib/haj/markdown.ex +++ b/lib/haj/markdown.ex @@ -6,7 +6,7 @@ defmodule Haj.Markdown do case with_ids do true -> - Earmark.Transform.map_ast_with(ast, 1, &transformer/2, true) + Earmark.Transform.map_ast_with(ast, {1, %{}}, &transformer/2, true) false -> ast @@ -15,13 +15,34 @@ defmodule Haj.Markdown do |> Earmark.as_html!() end - defp transformer({tag, attrs, _, m}, count) do + defp transformer({tag, attrs, data, m}, {count, map} = acc) when is_binary(tag) do case Regex.match?(~r{h[1-6]}, tag) do true -> - {{tag, Earmark.AstTools.merge_atts(attrs, id: "heading-#{count}"), nil, m}, count + 1} + slug = slugify(data) + + # Save a map of counts for each slug to keep track of duplicates + map = Map.update(map, slug, 0, &(&1 + 1)) + + slug = if map[slug] > 0, do: slug <> "-" <> Integer.to_string(map[slug]), else: slug + + {{tag, + Earmark.AstTools.merge_atts(attrs, [ + {"data-heading-index", "#{count}"}, + id: "#{slug}" + ]), nil, m}, {count + 1, map}} false -> - {{tag, attrs, nil, m}, count} + {{tag, attrs, nil, m}, acc} end end + + defp transformer({tag, attrs, _, m}, acc) when is_atom(tag), + do: {{tag, attrs, nil, m}, acc} + + defp slugify(data) when is_list(data) do + Enum.join(data, "") + |> String.replace(~r/[^\p{L}\p{M}\p{Nd}\p{Nl}\p{Pc}\- ]/u, "") + |> String.downcase() + |> String.replace(~r/ /, "-") + end end diff --git a/lib/haj_web/live/responsibility_live/show.html.heex b/lib/haj_web/live/responsibility_live/show.html.heex index a9326d3..d4c1b0a 100644 --- a/lib/haj_web/live/responsibility_live/show.html.heex +++ b/lib/haj_web/live/responsibility_live/show.html.heex @@ -46,7 +46,7 @@
<%= raw(@responsibility.description_html) %> @@ -187,7 +187,7 @@
-
+
<%= raw(comment.text_html) %>