From ad0d130fc84b6ed2c11e3a9ddd3108d257b3624e Mon Sep 17 00:00:00 2001 From: Inhji Date: Sat, 9 Sep 2023 23:46:37 +0200 Subject: [PATCH] improve outline rendering --- lib/chiya_web/controllers/page_html.ex | 24 ++-------------- lib/chiya_web/outline_renderer.ex | 38 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 22 deletions(-) create mode 100644 lib/chiya_web/outline_renderer.ex diff --git a/lib/chiya_web/controllers/page_html.ex b/lib/chiya_web/controllers/page_html.ex index 69fceae..d95c03b 100644 --- a/lib/chiya_web/controllers/page_html.ex +++ b/lib/chiya_web/controllers/page_html.ex @@ -1,6 +1,5 @@ defmodule ChiyaWeb.PageHTML do use ChiyaWeb, :html_public - import Phoenix.HTML.Tag, only: [content_tag: 3, content_tag: 2] import ChiyaWeb.Format, only: [pretty_datetime: 1, pretty_date: 1, datetime: 1] embed_templates "page_html/*" @@ -27,30 +26,11 @@ defmodule ChiyaWeb.PageHTML do def tag_list(assigns) def render_outline(note) do - note.content - |> ChiyaWeb.Outline.get() - |> Enum.map(&do_render_outline/1) - |> Enum.map(&safe_to_string/1) + ChiyaWeb.OutlineRenderer.render_outline(note.content) end def has_outline?(note) do - outline_empty = - note.content - |> ChiyaWeb.Outline.get() - |> Enum.empty?() - - !outline_empty - end - - def do_render_outline(%{text: text, children: children, level: _level}) do - slug = Slugger.slugify_downcase(text) - - content_tag(:ul, [class: "m-0"], - do: [ - content_tag(:li, do: content_tag(:a, text, href: "##{slug}")), - Enum.map(children, &do_render_outline/1) - ] - ) + ChiyaWeb.OutlineRenderer.has_outline?(note.content) end def group_tags(notes) do diff --git a/lib/chiya_web/outline_renderer.ex b/lib/chiya_web/outline_renderer.ex new file mode 100644 index 0000000..46fd183 --- /dev/null +++ b/lib/chiya_web/outline_renderer.ex @@ -0,0 +1,38 @@ +defmodule ChiyaWeb.OutlineRenderer do + import Phoenix.HTML, only: [safe_to_string: 1] + import Phoenix.HTML.Tag, only: [content_tag: 3, content_tag: 2] + + def render_outline(content) do + children = + content + |> ChiyaWeb.Outline.get() + |> Enum.map(&do_render_outline/1) + + root = content_tag(:ul, do: children) + + safe_to_string(root) + end + + def has_outline?(content) do + outline_empty = + content + |> ChiyaWeb.Outline.get() + |> Enum.empty?() + + !outline_empty + end + + def do_render_outline(%{text: text, children: children, level: _level}) do + slug = Slugger.slugify_downcase(text) + list_item = content_tag(:li, do: content_tag(:a, text, href: "##{slug}")) + + if Enum.empty?(children) do + [list_item] + else + [ + list_item, + content_tag(:ul, do: Enum.map(children, &do_render_outline/1)) + ] + end + end +end