initial outline code

This commit is contained in:
Inhji 2023-07-09 19:59:47 +02:00
parent e8b4db9340
commit 419a58a48e
2 changed files with 41 additions and 0 deletions

21
lib/chiya_web/outline.ex Normal file
View file

@ -0,0 +1,21 @@
defmodule ChiyaWeb.Outline do
@outline_regex ~r/\#{1,6}\s.+/
@heading_regex ~r/^(#+)\s(.+)$/
def get(markdown) do
headings =
@outline_regex
|> Regex.scan(markdown, capture: :all)
Enum.chunk_by(headings, fn h -> nil end)
end
def level(heading) do
Regex.scan(@heading_regex, heading)
|> Enum.map(fn [_, level, heading] ->
[level_from_string(level), heading]
end)
end
defp level_from_string(string), do: String.length(string)
end

View file

@ -0,0 +1,20 @@
defmodule ChiyaWeb.OutlineTest do
use Chiya.SimpleCase
alias ChiyaWeb.Outline
describe "extract_outline/1" do
test "extracts headlines from markdown" do
markdown = "# Heading\nsome paragraph\n## Sub Heading\n# Second Heading"
assert [{1, "Heading", [{2, "Sub Heading", []}]}, {1, "Second Heading", []}] =
Outline.get(markdown)
end
end
describe "outline_level/1" do
test "extracts outline level" do
assert {1, "Heading"} = Outline.level("# Heading")
end
end
end