Skip to content

Commit 6b326f5

Browse files
committed
Add down for simple markdown
1 parent 0643bc6 commit 6b326f5

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
defmodule ComponentsGuideWeb.DownView do
2+
use ComponentsGuideWeb, :view
3+
4+
defmodule ParserState do
5+
defstruct bold: false, italics: false, html: []
6+
7+
@spec parse(binary) ::
8+
{:safe,
9+
binary
10+
| maybe_improper_list(
11+
binary | maybe_improper_list(any, binary | []) | byte,
12+
binary | []
13+
)}
14+
def parse(input) when is_binary(input) do
15+
next(%__MODULE__{}, input)
16+
end
17+
18+
defp next(state = %__MODULE__{italics: true}, <<"_"::utf8>> <> rest) do
19+
%__MODULE__{state | html: [state.html], italics: false}
20+
|> next(rest)
21+
end
22+
23+
defp next(state = %__MODULE__{italics: false}, <<"_"::utf8>> <> rest) do
24+
%__MODULE__{state | html: ["<em1>" | state.html], italics: true}
25+
|> next(rest)
26+
end
27+
28+
defp next(state = %__MODULE__{}, <<char::utf8>> <> rest) do
29+
%__MODULE__{state | html: [<<char::utf8>> | state.html]}
30+
|> next(rest)
31+
end
32+
33+
defp next(state = %__MODULE__{italics: italics}, "") do
34+
html = Enum.reverse(state.html) |> Enum.join()
35+
36+
html =
37+
case italics do
38+
true ->
39+
html <> "</em>"
40+
41+
false ->
42+
html
43+
end
44+
45+
Phoenix.HTML.raw(html)
46+
end
47+
end
48+
49+
def down(input) when is_binary(input) do
50+
ParserState.parse(input)
51+
end
52+
end
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
defmodule ComponentsGuideWeb.DownViewTest do
2+
use ComponentsGuideWeb.ConnCase, async: true
3+
4+
alias ComponentsGuideWeb.DownView, as: Subject
5+
use Phoenix.HTML
6+
7+
describe "humanize_bytes/1" do
8+
test "plain text" do
9+
assert Subject.down("plain text") == raw("plain text")
10+
end
11+
12+
test "italics" do
13+
assert Subject.down("plain _text_") == raw("plain <em>text</em>")
14+
end
15+
end
16+
end

0 commit comments

Comments
 (0)