Packages

A CSS selector parser and evaluator

Current section

Files

Jump to
css_select src css_select@selector.erl
Raw

src/css_select@selector.erl

-module(css_select@selector).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/css_select/selector.gleam").
-export([to_string/1]).
-export_type([tag_selector/0, attribute_selector/0, selector/0]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
-type tag_selector() :: any | {tag, binary()}.
-type attribute_selector() :: {id, binary()} |
{class, binary()} |
{attribute_exists, binary()} |
{attribute_equal, binary(), binary()} |
{attribute_prefix, binary(), binary()} |
{attribute_suffix, binary(), binary()} |
{attribute_includes, binary(), binary()} |
{psuedo, binary()}.
-type selector() :: {element_selector,
tag_selector(),
list(attribute_selector())}.
-file("src/css_select/selector.gleam", 45).
?DOC(
" Convert a `Selector` back to its CSS selector string representation.\n"
"\n"
" ```gleam\n"
" let assert Ok(selector) = css_select.parse_simple_selector(\"div#foo.bar\")\n"
" css_select.to_string(selector)\n"
" // -> \"div#foo.bar\"\n"
" ```\n"
).
-spec to_string(selector()) -> binary().
to_string(Selector) ->
{element_selector, Tag, Attrs} = Selector,
T = case Tag of
any ->
<<""/utf8>>;
{tag, Tag@1} ->
Tag@1
end,
Attr_matches = begin
_pipe = gleam@list:map(Attrs, fun(Attr) -> case Attr of
{id, Id} ->
<<"#"/utf8, Id/binary>>;
{class, Class} ->
<<"."/utf8, Class/binary>>;
{psuedo, Str} ->
<<":"/utf8, Str/binary>>;
{attribute_exists, K} ->
<<<<"["/utf8, K/binary>>/binary, "]"/utf8>>;
{attribute_equal, K@1, V} ->
<<<<<<<<"["/utf8, K@1/binary>>/binary, "=\""/utf8>>/binary,
V/binary>>/binary,
"\"]"/utf8>>;
{attribute_prefix, K@2, V@1} ->
<<<<<<<<"["/utf8, K@2/binary>>/binary, "^=\""/utf8>>/binary,
V@1/binary>>/binary,
"\"]"/utf8>>;
{attribute_suffix, K@3, V@2} ->
<<<<<<<<"["/utf8, K@3/binary>>/binary, "$=\""/utf8>>/binary,
V@2/binary>>/binary,
"\"]"/utf8>>;
{attribute_includes, K@4, V@3} ->
<<<<<<<<"["/utf8, K@4/binary>>/binary, "*=\""/utf8>>/binary,
V@3/binary>>/binary,
"\"]"/utf8>>
end end),
gleam@string:join(_pipe, <<""/utf8>>)
end,
<<T/binary, Attr_matches/binary>>.