Packages

A CSS selector parser and evaluator

Current section

Files

Jump to
css_select src css_select@simple_matcher.erl
Raw

src/css_select@simple_matcher.erl

-module(css_select@simple_matcher).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([match/2]).
-spec non_empty_string(binary()) -> boolean().
non_empty_string(Str) ->
_pipe = Str,
_pipe@1 = gleam@string:is_empty(_pipe),
gleam@bool:negate(_pipe@1).
-spec with_attribute(list({JIG, binary()}), JIG, JIH, fun((binary()) -> JIH)) -> JIH.
with_attribute(Attributes, Attribute, Default, Callback) ->
_pipe = Attributes,
_pipe@1 = gleam@list:key_find(_pipe, Attribute),
_pipe@2 = gleam@result:map(_pipe@1, Callback),
gleam@result:unwrap(_pipe@2, Default).
-spec class_list(list({binary(), binary()})) -> list(binary()).
class_list(Attributes) ->
with_attribute(
Attributes,
<<"class"/utf8>>,
[],
fun(Class_str) -> _pipe = Class_str,
_pipe@1 = gleam@string:split(_pipe, <<" "/utf8>>),
_pipe@2 = gleam@list:map(_pipe@1, fun gleam@string:trim/1),
gleam@list:filter(_pipe@2, fun non_empty_string/1) end
).
-spec match_attribute(
list({binary(), binary()}),
css_select@selector:attribute_selector()
) -> boolean().
match_attribute(Attributes, Selector) ->
case Selector of
{id, Id} ->
match_attribute(Attributes, {attribute_equal, <<"id"/utf8>>, Id});
{psuedo, Psuedo} ->
match_attribute(Attributes, {attribute_exists, Psuedo});
{class, Class} ->
_pipe = class_list(Attributes),
gleam@list:any(_pipe, fun(C) -> C =:= Class end);
{attribute_exists, Attribute} ->
with_attribute(Attributes, Attribute, false, fun(_) -> true end);
{attribute_equal, Attribute@1, Value} ->
with_attribute(
Attributes,
Attribute@1,
false,
fun(Attr_value) -> Attr_value =:= Value end
);
{attribute_prefix, Attribute@2, Prefix} ->
with_attribute(
Attributes,
Attribute@2,
false,
fun(Attr_value@1) ->
gleam@string:starts_with(Attr_value@1, Prefix)
end
);
{attribute_suffix, Attribute@3, Suffix} ->
with_attribute(
Attributes,
Attribute@3,
false,
fun(Attr_value@2) ->
gleam@string:ends_with(Attr_value@2, Suffix)
end
);
{attribute_includes, Attribute@4, Value@1} ->
with_attribute(
Attributes,
Attribute@4,
false,
fun(Attr_value@3) ->
gleam_stdlib:contains_string(Attr_value@3, Value@1)
end
)
end.
-spec match(
{binary(), list({binary(), binary()})},
css_select@selector:selector()
) -> boolean().
match(Element, Selector) ->
{T, Attrs} = Element,
case Selector of
{element_selector, any, Attr_selectors} ->
gleam@list:all(
Attr_selectors,
fun(_capture) -> match_attribute(Attrs, _capture) end
);
{element_selector, {tag, Tag}, Attr_selectors@1} ->
(Tag =:= T) andalso match(
Element,
{element_selector, any, Attr_selectors@1}
)
end.