Skip to content

Commit

Permalink
clean up pseudo-class handling
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Nov 17, 2015
1 parent 08b8fbc commit 0e9eb7f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 18 deletions.
5 changes: 4 additions & 1 deletion Changes
@@ -1,5 +1,8 @@

6.32 2015-11-16
6.32 2015-11-17
- Improved Mojo::DOM::CSS performance slightly. (jamadam)
- Fixed a few case-sensitivity and An+B notation issues in Mojo::DOM::CSS.
(jamadam)

6.31 2015-11-13
- Improved documentation browser CSS.
Expand Down
27 changes: 13 additions & 14 deletions lib/Mojo/DOM/CSS.pm
Expand Up @@ -98,24 +98,23 @@ sub _compile {
push @$last, ['attr', _name($1), _value($2 // '', $3 // $4 // $5, $6)];
}

# Pseudo-class (":not" contains more selectors)
# Pseudo-class
elsif ($css =~ /\G:([\w\-]+)(?:\(((?:\([^)]+\)|[^)])+)\))?/gcs) {
my ($name, $args) = (lc $1, $2);
if ($name eq 'not') {
push @$last, ['pc', $name, _compile($args)];
}

# ":first-*" or ":last-*" (rewrite with equation)
# ":not" (contains more selectors)
if ($name eq 'not') { push @$last, ['pc', $name, _compile($args)] }

# ":first-*" or ":last-*" (rewrite to ":nth-*")
elsif ($name =~ s/^(?:(first)|last)-//) {
push @$last,
['pc', 'nth-' . ($1 ? '' : 'last-') . $name, $1 ? [0, 1] : [-1, 1]];
}
elsif ($name =~ /^nth-/) {
push @$last, ['pc', $name, _equation($args)];
}
else {
push @$last, ['pc', $name];
['pc', $1 ? ("nth-$name", [0, 1]) : ("nth-last-$name", [-1, 1])];
}

# "nth-*"
elsif ($name =~ /^nth-/) { push @$last, ['pc', $name, _equation($args)] }

else { push @$last, ['pc', $name] }
}

# Tag
Expand Down Expand Up @@ -143,8 +142,8 @@ sub _equation {
# "4", "+4" or "-4"
return [0, $1] if $equation =~ /^\s*((?:\+|-)?\d+)\s*$/;

# "n", "4n", "+4n", "-4n", "n+1" or "4n-1"
return
# "n", "4n", "+4n", "-4n", "n+1", "4n-1", "+4n-1" (and other variations)
return [0, 0]
unless $equation =~ /^\s*((?:\+|-)?(?:\d+)?)?n\s*((?:\+|-)\s*\d+)?\s*$/i;
return [$1 eq '-' ? -1 : $1 eq '' ? 1 : $1, join('', split(' ', $2 // 0))];
}
Expand Down
7 changes: 4 additions & 3 deletions t/mojo/dom.t
Expand Up @@ -1059,9 +1059,10 @@ is_deeply \@li, [qw(A B C D E F G)], 'found all li elements';
@li = ();
$dom->find('li:nth-child(0n+1)')->each(sub { push @li, shift->text });
is_deeply \@li, [qw(A)], 'found first li element';
is $dom->find('li:nth-child(0n+0)')->size, 0, 'no results';
is $dom->find('li:nth-child(0)')->size, 0, 'no results';
is $dom->find('li:nth-child()')->size, 0, 'no results';
is $dom->find('li:nth-child(0n+0)')->size, 0, 'no results';
is $dom->find('li:nth-child(0)')->size, 0, 'no results';
is $dom->find('li:nth-child()')->size, 0, 'no results';
is $dom->find('li:nth-child(whatever)')->size, 0, 'no results';

# Even more pseudo-classes
$dom = Mojo::DOM->new(<<EOF);
Expand Down

0 comments on commit 0e9eb7f

Please sign in to comment.