1 package HTML::Zoom::FilterBuilder;
4 use base qw(HTML::Zoom::SubObject);
5 use HTML::Zoom::CodeStream;
7 sub _stream_from_code {
8 shift->_zconfig->stream_utils->stream_from_code(@_)
11 sub _stream_from_array {
12 shift->_zconfig->stream_utils->stream_from_array(@_)
15 sub _stream_from_proto {
16 shift->_zconfig->stream_utils->stream_from_proto(@_)
20 shift->_zconfig->stream_utils->stream_concat(@_)
23 sub _flatten_stream_of_streams {
24 shift->_zconfig->stream_utils->flatten_stream_of_streams(@_)
27 sub set_attr { shift->set_attribute(@_); }
31 my $attr = $self->_parse_attribute_args(@_);
33 my $a = (my $evt = $_[0])->{attrs};
34 my @kadd = grep {!exists $a->{$_}} keys %$attr;
35 +{ %$evt, raw => undef, raw_attrs => undef,
36 attrs => { %$a, %$attr },
37 @kadd ? (attr_names => [ @{$evt->{attr_names}}, @kadd ]) : ()
42 sub _parse_attribute_args {
45 my $opts = ref($_[0]) eq 'HASH' ? $_[0] : {$_[0] => $_[1]};
46 for (values %{$opts}) { $self->_zconfig->parser->html_escape($_); }
51 die "renamed to add_to_attribute. killing this entirely for 1.0";
54 sub add_class { shift->add_to_attribute('class',@_) }
56 sub remove_class { shift->remove_from_attribute('class',@_) }
58 sub set_class { shift->set_attribute('class',@_) }
60 sub set_id { shift->set_attribute('id',@_) }
62 sub add_to_attribute {
64 my $attr = $self->_parse_attribute_args(@_);
66 my $a = (my $evt = $_[0])->{attrs};
67 my @kadd = grep {!exists $a->{$_}} keys %$attr;
68 +{ %$evt, raw => undef, raw_attrs => undef,
71 map {$_ => join(' ', (exists $a->{$_} ? $a->{$_} : ()), $attr->{$_}) }
74 @kadd ? (attr_names => [ @{$evt->{attr_names}}, @kadd ]) : ()
79 sub remove_from_attribute {
81 my $attr = $self->_parse_attribute_args(@_);
83 my $a = (my $evt = $_[0])->{attrs};
84 +{ %$evt, raw => undef, raw_attrs => undef,
87 #TODO needs to support multiple removes
88 map { my $tar = $_; $_ => join ' ',
89 map {$attr->{$tar} ne $_} split ' ', $a->{$_} }
90 grep {exists $a->{$_}} keys %$attr
96 sub remove_attribute {
97 my ($self, $args) = @_;
98 my $name = (ref($args) eq 'HASH') ? $args->{name} : $args;
100 my $a = (my $evt = $_[0])->{attrs};
101 return $evt unless exists $a->{$name};
102 $a = { %$a }; delete $a->{$name};
103 +{ %$evt, raw => undef, raw_attrs => undef,
105 attr_names => [ grep $_ ne $name, @{$evt->{attr_names}} ]
110 sub transform_attribute {
112 my ( $name, $code ) = @_ > 1 ? @_ : @{$_[0]}{qw(name code)};
116 my %a = %{ $evt->{attrs} };
117 my @names = @{ $evt->{attr_names} };
119 my $existed_before = exists $a{$name};
120 my $v = $code->( $a{$name} );
121 my $deleted = $existed_before && ! defined $v;
122 my $added = ! $existed_before && defined $v;
129 @names = grep $_ ne $name, @names;
133 +{ %$evt, raw => undef, raw_attrs => undef,
136 ? (attr_names => \@names )
143 my ($self, $options) = @_;
144 my ($into, $passthrough, $content, $filter, $flush_before) =
145 @{$options}{qw(into passthrough content filter flush_before)};
147 my ($evt, $stream) = @_;
148 # We wipe the contents of @$into here so that other actions depending
149 # on this (such as a repeater) can be invoked multiple times easily.
150 # I -suspect- it's better for that state reset to be managed here; if it
151 # ever becomes painful the decision should be revisited
153 @$into = $content ? () : ($evt);
155 if ($evt->{is_in_place_close}) {
156 return $evt if $passthrough || $content;
159 my $name = $evt->{name};
161 my $_next = $content ? 'peek' : 'next';
164 $stream = do { local $_ = $stream; $filter->($stream) };
167 local $_ = $self->_stream_concat(
168 $self->_stream_from_array($evt),
173 $evt = $stream->next;
176 my $collector = $self->_stream_from_code(sub {
177 return unless $stream;
178 while (my ($evt) = $stream->$_next) {
179 $depth++ if ($evt->{type} eq 'OPEN');
180 $depth-- if ($evt->{type} eq 'CLOSE');
184 push(@$into, $evt) if $into;
185 return $evt if $passthrough;
188 push(@$into, $evt) if $into;
189 $stream->next if $content;
190 return $evt if $passthrough;
192 die "Never saw closing </${name}> before end of source";
195 if ($passthrough||$content) {
196 $evt = { %$evt, flush => 1 };
198 $evt = { type => 'EMPTY', flush => 1 };
201 return ($passthrough||$content||$flush_before)
202 ? [ $evt, $collector ]
207 sub collect_content {
208 my ($self, $options) = @_;
209 $self->collect({ %{$options||{}}, content => 1 })
213 my ($self, $events) = @_;
214 my $coll_proto = $self->collect({ passthrough => 1 });
216 my $emit = $self->_stream_from_proto($events);
217 my $coll = &$coll_proto;
219 if(ref $coll eq 'ARRAY') {
220 my $firstbit = $self->_stream_from_proto([$coll->[0]]);
221 return $self->_stream_concat($emit, $firstbit, $coll->[1]);
222 } elsif(ref $coll eq 'HASH') {
223 return [$emit, $coll];
225 return $self->_stream_concat($emit, $coll);
227 } else { return $emit }
232 my ($self, $events) = @_;
233 my $coll_proto = $self->collect({ passthrough => 1 });
236 my $emit = $self->_stream_from_proto($events);
237 my $coll = &$coll_proto;
238 return ref($coll) eq 'HASH' # single event, no collect
240 : [ $coll->[0], $self->_stream_concat($coll->[1], $emit) ];
244 sub prepend_content {
245 my ($self, $events) = @_;
246 my $coll_proto = $self->collect({ passthrough => 1, content => 1 });
249 my $emit = $self->_stream_from_proto($events);
250 if ($evt->{is_in_place_close}) {
251 $evt = { %$evt }; delete @{$evt}{qw(raw is_in_place_close)};
252 return [ $evt, $self->_stream_from_array(
253 $emit->next, { type => 'CLOSE', name => $evt->{name} }
256 my $coll = &$coll_proto;
257 return [ $coll->[0], $self->_stream_concat($emit, $coll->[1]) ];
262 my ($self, $events) = @_;
263 my $coll_proto = $self->collect({ passthrough => 1, content => 1 });
266 my $emit = $self->_stream_from_proto($events);
267 if ($evt->{is_in_place_close}) {
268 $evt = { %$evt }; delete @{$evt}{qw(raw is_in_place_close)};
269 return [ $evt, $self->_stream_from_array(
270 $emit->next, { type => 'CLOSE', name => $evt->{name} }
273 my $coll = &$coll_proto;
274 return [ $coll->[0], $self->_stream_concat($coll->[1], $emit) ];
279 my ($self, $replace_with, $options) = @_;
280 my $coll_proto = $self->collect($options);
282 my ($evt, $stream) = @_;
283 my $emit = $self->_stream_from_proto($replace_with);
284 my $coll = &$coll_proto;
285 # if we're replacing the contents of an in place close
286 # then we need to handle that here
287 if ($options->{content}
288 && ref($coll) eq 'HASH'
289 && $coll->{is_in_place_close}
291 my $close = $stream->next;
292 # shallow copy and nuke in place and raw (to force smart print)
293 $_ = { %$_ }, delete @{$_}{qw(is_in_place_close raw)} for ($coll, $close);
294 $emit = $self->_stream_concat(
296 $self->_stream_from_array($close),
299 # For a straightforward replace operation we can, in fact, do the emit
300 # -before- the collect, and my first cut did so. However in order to
301 # use the captured content in generating the new content, we need
302 # the collect stage to happen first - and it seems highly unlikely
303 # that in normal operation the collect phase will take long enough
304 # for the difference to be noticeable
307 ? (ref $coll eq 'ARRAY' # [ event, stream ]
308 ? [ $coll->[0], $self->_stream_concat($coll->[1], $emit) ]
309 : (ref $coll eq 'HASH' # event or stream?
311 : $self->_stream_concat($coll, $emit))
318 sub replace_content {
319 my ($self, $replace_with, $options) = @_;
320 $self->replace($replace_with, { %{$options||{}}, content => 1 })
324 my ($self, $repeat_for, $options) = @_;
325 $options->{into} = \my @into;
327 my $repeat_between = delete $options->{repeat_between};
328 if ($repeat_between) {
329 $options->{filter} = sub {
330 $_->select($repeat_between)->collect({ into => \@between })
334 my $s = $self->_stream_from_proto($repeat_for);
335 # We have to test $repeat_between not @between here because
336 # at the point we're constructing our return stream @between
337 # hasn't been populated yet - but we can test @between in the
338 # map routine because it has been by then and that saves us doing
339 # the extra stream construction if we don't need it.
340 $self->_flatten_stream_of_streams(do {
341 if ($repeat_between) {
343 local $_ = $self->_stream_from_array(@into);
344 (@between && $s->peek)
345 ? $self->_stream_concat(
346 $_[0]->($_), $self->_stream_from_array(@between)
352 local $_ = $self->_stream_from_array(@into);
358 $self->replace($repeater, $options);
362 my ($self, $repeat_for, $options) = @_;
363 $self->repeat($repeat_for, { %{$options||{}}, content => 1 })
367 my ($self, $to) = @_;
370 push @$to, $evt->{'attrs'}->{'name'};
376 my ($self,$to,$fill) = @_;
380 $_->select('input')->validate_and_fill($to,$fill)
381 ->select('select')->validate_and_fill($to,$fill);
388 my ($self, $value) = @_;
389 #set value on an element. if its a select select its option
390 #if it's a checkbox check it otherwise set attr value
392 return $self->set_attribute(value => $value);
396 sub validate_and_fill {
397 my ($self, $to, $fill) = @_;
400 my $nm = $evt->{'attrs'}->{'name'};
401 if(defined $fill && $fill->{$nm}) {
402 $evt->{'raw'} = undef;
403 $evt->{'raw_attrs'} = undef;
404 push @{$evt->{'attr_names'}}, 'value' unless exists $evt->{'attrs'}->{'value'};
405 $evt->{'attrs'}->{'value'} = $fill->{$nm};
408 [split ' ', $evt->{'attrs'}->{'data-validate'}||""];
418 HTML::Zoom::FilterBuilder - Add Filters to a Stream
422 Create an L<HTML::Zoom> instance:
425 my $root = HTML::Zoom
429 <title>Default Title</title>
431 <body bad_attr='junk'>
437 Create a new attribute on the C<body> tag:
441 ->set_attribute(class=>'main');
443 Add a extra value to an existing attribute:
447 ->add_to_attribute(class=>'one-column');
449 Set the content of the C<title> tag:
453 ->replace_content('Hello World');
455 Set content from another L<HTML::Zoom> instance:
457 my $body = HTML::Zoom
461 <p id="p2">Is the Time</p>
467 ->replace_content($body);
469 Set an attribute on multiple matches:
473 ->set_attribute(class=>'para');
479 ->remove_attribute('bad_attr');
485 my $output = $root->to_html;
492 <title>Hello World</title>
494 <body class="main one-column"><div id="stuff">
495 <p class="para">Well Now</p>
496 <p id="p2" class="para">Is the Time</p>
504 is($output, $expect, 'Synopsis code works ok');
510 Given a L<HTML::Zoom> stream, provide methods to apply filters which
511 alter the content of that stream.
515 This class defines the following public API
519 Sets an attribute of a given name to a given value for all matching selections.
523 ->set_attribute(class=>'paragraph')
525 ->set_attribute({class=>'paragraph', name=>'divider'});
527 Overrides existing values, if such exist. When multiple L</set_attribute>
528 calls are made against the same or overlapping selection sets, the final
531 =head2 add_to_attribute
533 Adds a value to an existing attribute, or creates one if the attribute does not
534 yet exist. You may call this method with either an Array or HashRef of Args.
538 ->set_attribute({class => 'paragraph', name => 'test'})
540 ->add_to_attribute(class=>'divider');
542 Attributes with more than one value will have a dividing space.
544 =head2 remove_attribute
546 Removes an attribute and all its values.
550 ->set_attribute(class=>'paragraph')
552 ->remove_attribute('class');
554 =head2 remove_from_attribute
556 Removes a value from existing attribute
560 ->set_attribute(class=>'paragraph lead')
562 ->remove_from_attribute('class' => 'lead');
564 Removes attributes from the original stream or events already added.
568 Add to a class attribute
572 Remove from a class attribute
574 =head2 transform_attribute
576 Transforms (or creates or deletes) an attribute by running the passed
577 coderef on it. If the coderef returns nothing, the attribute is
582 ->transform_attribute( href => sub {
583 ( my $a = shift ) =~ s/localhost/example.com/;
590 Collects and extracts results of L<HTML::Zoom/select>. It takes the following
591 optional common options as hash reference.
595 =item into [ARRAY REFERENCE]
597 Where to save collected events (selected elements).
599 $z1->select('#main-content')
600 ->collect({ into => \@body })
602 $z2->select('#main-content')
608 Run filter on collected elements (locally setting $_ to stream, and passing
609 stream as an argument to given code reference). Filtered stream would be
614 filter => sub { $_->select('.inner')->replace_content('bar!') },
618 It can be used to further filter selection. For example
622 filter => sub { $_->select('td') },
626 is equivalent to (not implemented yet) descendant selector combination, i.e.
630 =item passthrough [BOOLEAN]
632 Extract copy of elements; the stream is unchanged (it does not remove collected
633 elements). For example without 'passthrough'
635 HTML::Zoom->from_html('<foo><bar /></foo>')
637 ->collect({ content => 1 })
640 returns '<foo></foo>', while with C<passthrough> option
642 HTML::Zoom->from_html('<foo><bar /></foo>')
644 ->collect({ content => 1, passthough => 1 })
647 returns '<foo><bar /></foo>'.
649 =item content [BOOLEAN]
651 Collect content of the element, and not the element itself.
655 HTML::Zoom->from_html('<h1>Title</h1><p>foo</p>')
660 would return '<p>foo</p>', while
662 HTML::Zoom->from_html('<h1>Title</h1><p>foo</p>')
664 ->collect({ content => 1 })
667 would return '<h1></h1><p>foo</p>'.
669 See also L</collect_content>.
671 =item flush_before [BOOLEAN]
673 Generate C<flush> event before collecting, to ensure that the HTML generated up
674 to selected element being collected is flushed throught to the browser. Usually
675 used in L</repeat> or L</repeat_content>.
679 =head2 collect_content
681 Collects contents of L<HTML::Zoom/select> result.
683 HTML::Zoom->from_file($foo)
684 ->select('#main-content')
685 ->collect_content({ into => \@foo_body })
688 ->replace_content(\@foo_body)
691 Equivalent to running L</collect> with C<content> option set.
695 Given a L<HTML::Zoom/select> result, add given content (which might be string,
696 array or another L<HTML::Zoom> object) before it.
699 ->select('input[name="foo"]')
700 ->add_before(\ '<span class="warning">required field</span>');
704 Like L</add_before>, only after L<HTML::Zoom/select> result.
710 You can add zoom events directly
714 ->add_after([ { type => 'TEXT', raw => 'O HAI' } ]);
716 =head2 prepend_content
718 Similar to add_before, but adds the content to the match.
721 ->from_html(q[<p>World</p>])
723 ->prepend_content("Hello ")
726 ## <p>Hello World</p>
728 Acceptable values are strings, scalar refs and L<HTML::Zoom> objects
730 =head2 append_content
732 Similar to add_after, but adds the content to the match.
735 ->from_html(q[<p>Hello </p>])
737 ->prepend_content("World")
740 ## <p>Hello World</p>
742 Acceptable values are strings, scalar refs and L<HTML::Zoom> objects
746 Given a L<HTML::Zoom/select> result, replace it with a string, array or another
747 L<HTML::Zoom> object. It takes the same optional common options as L</collect>
748 (via hash reference).
750 =head2 replace_content
752 Given a L<HTML::Zoom/select> result, replace the content with a string, array
753 or another L<HTML::Zoom> object.
756 ->select('title, #greeting')
757 ->replace_content('Hello world!');
761 For a given selection, repeat over transformations, typically for the purposes
762 of populating lists. Takes either an array of anonymous subroutines or a zoom-
763 able object consisting of transformation.
765 Example of array reference style (when it doesn't matter that all iterations are
768 $zoom->select('table')->repeat([
772 $_->select('td')->replace_content($e);
777 Subroutines would be run with $_ localized to result of L<HTML::Zoom/select> (of
778 collected elements), and with said result passed as parameter to subroutine.
780 You might want to use CodeStream when you don't have all elements upfront
782 $zoom->select('.contents')->repeat(sub {
783 HTML::Zoom::CodeStream->new({
785 while (my $line = $fh->getline) {
787 $_->select('.lno')->replace_content($fh->input_line_number)
788 ->select('.line')->replace_content($line)
796 In addition to common options as in L</collect>, it also supports:
800 =item repeat_between [SELECTOR]
802 Selects object to be repeated between items. In the case of array this object
803 is put between elements, in case of iterator it is put between results of
804 subsequent iterations, in the case of streamable it is put between events
807 See documentation for L</repeat_content>
811 =head2 repeat_content
813 Given a L<HTML::Zoom/select> result, run provided iterator passing content of
814 this result to this iterator. Accepts the same options as L</repeat>.
816 Equivalent to using C<contents> option with L</repeat>.
823 $_->select('.name')->replace_content('Matt')
824 ->select('.age')->replace_content('26')
827 $_->select('.name')->replace_content('Mark')
828 ->select('.age')->replace_content('0x29')
831 $_->select('.name')->replace_content('Epitaph')
832 ->select('.age')->replace_content('<redacted>')
835 { repeat_between => '.between' }
845 See L<HTML::Zoom> for authors.
849 See L<HTML::Zoom> for the license.