initial outline code
This commit is contained in:
parent
e8b4db9340
commit
419a58a48e
2 changed files with 41 additions and 0 deletions
21
lib/chiya_web/outline.ex
Normal file
21
lib/chiya_web/outline.ex
Normal 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
|
20
test/chiya_web/outline_test.exs
Normal file
20
test/chiya_web/outline_test.exs
Normal 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
|
Loading…
Reference in a new issue