Current section
Files
Jump to
Current section
Files
src/htmb.erl
-module(htmb).
-compile([no_auto_import, nowarn_unused_vars]).
-export([escape/1, dangerous_unescaped_fragment/1, text/1, render/1, render_page/2, h/3]).
-export_type([html/0]).
-type html() :: any().
-spec do_escape(binary(), binary()) -> binary().
do_escape(Escaped, Content) ->
case gleam@string:pop_grapheme(Content) of
{ok, {<<"<"/utf8>>, Xs}} ->
do_escape(<<Escaped/binary, "<"/utf8>>, Xs);
{ok, {<<">"/utf8>>, Xs@1}} ->
do_escape(<<Escaped/binary, ">"/utf8>>, Xs@1);
{ok, {<<"&"/utf8>>, Xs@2}} ->
do_escape(<<Escaped/binary, "&"/utf8>>, Xs@2);
{ok, {X, Xs@3}} ->
do_escape(<<Escaped/binary, X/binary>>, Xs@3);
{error, _} ->
<<Escaped/binary, Content/binary>>
end.
-spec escape(binary()) -> binary().
escape(Content) ->
do_escape(<<""/utf8>>, Content).
-spec attribute(binary(), {binary(), binary()}) -> binary().
attribute(Content, Attribute) ->
<<<<<<<<<<Content/binary, " "/utf8>>/binary,
(erlang:element(1, Attribute))/binary>>/binary,
"=\""/utf8>>/binary,
(erlang:element(2, Attribute))/binary>>/binary,
"\""/utf8>>.
-spec dangerous_unescaped_fragment(gleam@string_builder:string_builder()) -> html().
dangerous_unescaped_fragment(S) ->
htmb_ffi:identity(S).
-spec text(binary()) -> html().
text(Content) ->
_pipe = Content,
_pipe@1 = do_escape(<<""/utf8>>, _pipe),
_pipe@2 = gleam@string_builder:from_string(_pipe@1),
htmb_ffi:identity(_pipe@2).
-spec render(html()) -> gleam@string_builder:string_builder().
render(Element) ->
htmb_ffi:identity(Element).
-spec render_page(html(), binary()) -> gleam@string_builder:string_builder().
render_page(Html, Doctype) ->
_pipe = htmb_ffi:identity(Html),
gleam@string_builder:prepend(
_pipe,
<<<<"<!DOCTYPE "/utf8, Doctype/binary>>/binary, ">"/utf8>>
).
-spec child(gleam@string_builder:string_builder(), html()) -> gleam@string_builder:string_builder().
child(Siblings, Child) ->
gleam@string_builder:append_builder(Siblings, htmb_ffi:identity(Child)).
-spec h(binary(), list({binary(), binary()}), list(html())) -> html().
h(Tag, Attributes, Children) ->
_pipe = <<"<"/utf8>>,
_pipe@1 = gleam@string:append(_pipe, Tag),
_pipe@2 = gleam@list:fold(Attributes, _pipe@1, fun attribute/2),
_pipe@3 = gleam@string:append(_pipe@2, <<">"/utf8>>),
_pipe@4 = gleam@string_builder:from_string(_pipe@3),
_pipe@5 = gleam@list:fold(Children, _pipe@4, fun child/2),
_pipe@6 = gleam@string_builder:append(
_pipe@5,
<<<<"</"/utf8, Tag/binary>>/binary, ">"/utf8>>
),
htmb_ffi:identity(_pipe@6).