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 ($name, $value) = $self->_parse_attribute_args(@_);
33 my $a = (my $evt = $_[0])->{attrs};
34 my $e = exists $a->{$name};
35 +{ %$evt, raw => undef, raw_attrs => undef,
36 attrs => { %$a, $name => $value },
37 ($e # add to name list if not present
39 : (attr_names => [ @{$evt->{attr_names}}, $name ]))
44 sub _parse_attribute_args {
47 die "Long form arg (name => 'class', value => 'x') is no longer supported"
48 if(@_ == 1 && $_[0]->{'name'} && $_[0]->{'value'});
49 my ($name, $value) = @_ > 1 ? @_ : @{$_[0]}{qw(name value)};
50 return ($name, $self->_zconfig->parser->html_escape($value));
54 die "renamed to add_to_attribute. killing this entirely for 1.0";
57 sub add_class { shift->add_to_attribute('class',@_) }
59 sub remove_class { shift->remove_from_attribute('class',@_) }
61 sub set_class { shift->set_attribute('class',@_) }
63 sub set_id { shift->set_attribute('id',@_) }
65 sub add_to_attribute {
67 my ($name, $value) = $self->_parse_attribute_args(@_);
69 my $a = (my $evt = $_[0])->{attrs};
70 my $e = exists $a->{$name};
71 +{ %$evt, raw => undef, raw_attrs => undef,
74 $name => join(' ', ($e ? $a->{$name} : ()), $value)
76 ($e # add to name list if not present
78 : (attr_names => [ @{$evt->{attr_names}}, $name ]))
83 sub remove_from_attribute {
85 my $attr = $self->_parse_attribute_args(@_);
87 my $a = (my $evt = $_[0])->{attrs};
88 +{ %$evt, raw => undef, raw_attrs => undef,
91 #TODO needs to support multiple removes
92 map { my $tar = $_; $_ => join ' ',
93 map {$attr->{$tar} ne $_} split ' ', $a->{$_} }
94 grep {exists $a->{$_}} keys %$attr
100 sub remove_attribute {
101 my ($self, $args) = @_;
102 my $name = (ref($args) eq 'HASH') ? $args->{name} : $args;
104 my $a = (my $evt = $_[0])->{attrs};
105 return $evt unless exists $a->{$name};
106 $a = { %$a }; delete $a->{$name};
107 +{ %$evt, raw => undef, raw_attrs => undef,
109 attr_names => [ grep $_ ne $name, @{$evt->{attr_names}} ]
114 sub transform_attribute {
116 my ( $name, $code ) = @_ > 1 ? @_ : @{$_[0]}{qw(name code)};
120 my %a = %{ $evt->{attrs} };
121 my @names = @{ $evt->{attr_names} };
123 my $existed_before = exists $a{$name};
124 my $v = $code->( $a{$name} );
125 my $deleted = $existed_before && ! defined $v;
126 my $added = ! $existed_before && defined $v;
133 @names = grep $_ ne $name, @names;
137 +{ %$evt, raw => undef, raw_attrs => undef,
140 ? (attr_names => \@names )
147 my ($self, $options) = @_;
148 my ($into, $passthrough, $content, $filter, $flush_before) =
149 @{$options}{qw(into passthrough content filter flush_before)};
151 my ($evt, $stream) = @_;
152 # We wipe the contents of @$into here so that other actions depending
153 # on this (such as a repeater) can be invoked multiple times easily.
154 # I -suspect- it's better for that state reset to be managed here; if it
155 # ever becomes painful the decision should be revisited
157 @$into = $content ? () : ($evt);
159 if ($evt->{is_in_place_close}) {
160 return $evt if $passthrough || $content;
163 my $name = $evt->{name};
165 my $_next = $content ? 'peek' : 'next';
168 $stream = do { local $_ = $stream; $filter->($stream) };
171 local $_ = $self->_stream_concat(
172 $self->_stream_from_array($evt),
177 $evt = $stream->next;
180 my $collector = $self->_stream_from_code(sub {
181 return unless $stream;
182 while (my ($evt) = $stream->$_next) {
183 $depth++ if ($evt->{type} eq 'OPEN');
184 $depth-- if ($evt->{type} eq 'CLOSE');
188 push(@$into, $evt) if $into;
189 return $evt if $passthrough;
192 push(@$into, $evt) if $into;
193 $stream->next if $content;
194 return $evt if $passthrough;
196 die "Never saw closing </${name}> before end of source";
199 if ($passthrough||$content) {
200 $evt = { %$evt, flush => 1 };
202 $evt = { type => 'EMPTY', flush => 1 };
205 return ($passthrough||$content||$flush_before)
206 ? [ $evt, $collector ]
211 sub collect_content {
212 my ($self, $options) = @_;
213 $self->collect({ %{$options||{}}, content => 1 })
217 my ($self, $events) = @_;
218 my $coll_proto = $self->collect({ passthrough => 1 });
220 my $emit = $self->_stream_from_proto($events);
221 my $coll = &$coll_proto;
223 if(ref $coll eq 'ARRAY') {
224 my $firstbit = $self->_stream_from_proto([$coll->[0]]);
225 return $self->_stream_concat($emit, $firstbit, $coll->[1]);
226 } elsif(ref $coll eq 'HASH') {
227 return [$emit, $coll];
229 return $self->_stream_concat($emit, $coll);
231 } else { return $emit }
236 my ($self, $events) = @_;
237 my $coll_proto = $self->collect({ passthrough => 1 });
240 my $emit = $self->_stream_from_proto($events);
241 my $coll = &$coll_proto;
242 return ref($coll) eq 'HASH' # single event, no collect
244 : [ $coll->[0], $self->_stream_concat($coll->[1], $emit) ];
248 sub prepend_content {
249 my ($self, $events) = @_;
250 my $coll_proto = $self->collect({ passthrough => 1, content => 1 });
253 my $emit = $self->_stream_from_proto($events);
254 if ($evt->{is_in_place_close}) {
255 $evt = { %$evt }; delete @{$evt}{qw(raw is_in_place_close)};
256 return [ $evt, $self->_stream_from_array(
257 $emit->next, { type => 'CLOSE', name => $evt->{name} }
260 my $coll = &$coll_proto;
261 return [ $coll->[0], $self->_stream_concat($emit, $coll->[1]) ];
266 my ($self, $events) = @_;
267 my $coll_proto = $self->collect({ passthrough => 1, content => 1 });
270 my $emit = $self->_stream_from_proto($events);
271 if ($evt->{is_in_place_close}) {
272 $evt = { %$evt }; delete @{$evt}{qw(raw is_in_place_close)};
273 return [ $evt, $self->_stream_from_array(
274 $emit->next, { type => 'CLOSE', name => $evt->{name} }
277 my $coll = &$coll_proto;
278 return [ $coll->[0], $self->_stream_concat($coll->[1], $emit) ];
283 my ($self, $replace_with, $options) = @_;
284 my $coll_proto = $self->collect($options);
286 my ($evt, $stream) = @_;
287 my $emit = $self->_stream_from_proto($replace_with);
288 my $coll = &$coll_proto;
289 # if we're replacing the contents of an in place close
290 # then we need to handle that here
291 if ($options->{content}
292 && ref($coll) eq 'HASH'
293 && $coll->{is_in_place_close}
295 my $close = $stream->next;
296 # shallow copy and nuke in place and raw (to force smart print)
297 $_ = { %$_ }, delete @{$_}{qw(is_in_place_close raw)} for ($coll, $close);
298 $emit = $self->_stream_concat(
300 $self->_stream_from_array($close),
303 # For a straightforward replace operation we can, in fact, do the emit
304 # -before- the collect, and my first cut did so. However in order to
305 # use the captured content in generating the new content, we need
306 # the collect stage to happen first - and it seems highly unlikely
307 # that in normal operation the collect phase will take long enough
308 # for the difference to be noticeable
311 ? (ref $coll eq 'ARRAY' # [ event, stream ]
312 ? [ $coll->[0], $self->_stream_concat($coll->[1], $emit) ]
313 : (ref $coll eq 'HASH' # event or stream?
315 : $self->_stream_concat($coll, $emit))
322 sub replace_content {
323 my ($self, $replace_with, $options) = @_;
324 $self->replace($replace_with, { %{$options||{}}, content => 1 })
328 my ($self, $repeat_for, $options) = @_;
329 $options->{into} = \my @into;
331 my $repeat_between = delete $options->{repeat_between};
332 if ($repeat_between) {
333 $options->{filter} = sub {
334 $_->select($repeat_between)->collect({ into => \@between })
338 my $s = $self->_stream_from_proto($repeat_for);
339 # We have to test $repeat_between not @between here because
340 # at the point we're constructing our return stream @between
341 # hasn't been populated yet - but we can test @between in the
342 # map routine because it has been by then and that saves us doing
343 # the extra stream construction if we don't need it.
344 $self->_flatten_stream_of_streams(do {
345 if ($repeat_between) {
347 local $_ = $self->_stream_from_array(@into);
348 (@between && $s->peek)
349 ? $self->_stream_concat(
350 $_[0]->($_), $self->_stream_from_array(@between)
356 local $_ = $self->_stream_from_array(@into);
362 $self->replace($repeater, $options);
366 my ($self, $repeat_for, $options) = @_;
367 $self->repeat($repeat_for, { %{$options||{}}, content => 1 })
374 HTML::Zoom::FilterBuilder - Add Filters to a Stream
378 Create an L<HTML::Zoom> instance:
381 my $root = HTML::Zoom
385 <title>Default Title</title>
387 <body bad_attr='junk'>
393 Create a new attribute on the C<body> tag:
397 ->set_attribute(class=>'main');
399 Add a extra value to an existing attribute:
403 ->add_to_attribute(class=>'one-column');
405 Set the content of the C<title> tag:
409 ->replace_content('Hello World');
411 Set content from another L<HTML::Zoom> instance:
413 my $body = HTML::Zoom
417 <p id="p2">Is the Time</p>
423 ->replace_content($body);
425 Set an attribute on multiple matches:
429 ->set_attribute(class=>'para');
435 ->remove_attribute('bad_attr');
441 my $output = $root->to_html;
448 <title>Hello World</title>
450 <body class="main one-column"><div id="stuff">
451 <p class="para">Well Now</p>
452 <p id="p2" class="para">Is the Time</p>
460 is($output, $expect, 'Synopsis code works ok');
466 Given a L<HTML::Zoom> stream, provide methods to apply filters which
467 alter the content of that stream.
471 This class defines the following public API
475 Sets an attribute of a given name to a given value for all matching selections.
479 ->set_attribute(class=>'paragraph')
481 ->set_attribute({class=>'paragraph', name=>'divider'});
483 Overrides existing values, if such exist. When multiple L</set_attribute>
484 calls are made against the same or overlapping selection sets, the final
487 =head2 add_to_attribute
489 Adds a value to an existing attribute, or creates one if the attribute does not
490 yet exist. You may call this method with either an Array or HashRef of Args.
494 ->set_attribute({class => 'paragraph', name => 'test'})
496 ->add_to_attribute(class=>'divider');
498 Attributes with more than one value will have a dividing space.
500 =head2 remove_attribute
502 Removes an attribute and all its values.
506 ->set_attribute(class=>'paragraph')
508 ->remove_attribute('class');
510 =head2 remove_from_attribute
512 Removes a value from existing attribute
516 ->set_attribute(class=>'paragraph lead')
518 ->remove_from_attribute('class' => 'lead');
520 Removes attributes from the original stream or events already added.
524 Add to a class attribute
528 Remove from a class attribute
530 =head2 transform_attribute
532 Transforms (or creates or deletes) an attribute by running the passed
533 coderef on it. If the coderef returns nothing, the attribute is
538 ->transform_attribute( href => sub {
539 ( my $a = shift ) =~ s/localhost/example.com/;
546 Collects and extracts results of L<HTML::Zoom/select>. It takes the following
547 optional common options as hash reference.
551 =item into [ARRAY REFERENCE]
553 Where to save collected events (selected elements).
555 $z1->select('#main-content')
556 ->collect({ into => \@body })
558 $z2->select('#main-content')
564 Run filter on collected elements (locally setting $_ to stream, and passing
565 stream as an argument to given code reference). Filtered stream would be
570 filter => sub { $_->select('.inner')->replace_content('bar!') },
574 It can be used to further filter selection. For example
578 filter => sub { $_->select('td') },
582 is equivalent to (not implemented yet) descendant selector combination, i.e.
586 =item passthrough [BOOLEAN]
588 Extract copy of elements; the stream is unchanged (it does not remove collected
589 elements). For example without 'passthrough'
591 HTML::Zoom->from_html('<foo><bar /></foo>')
593 ->collect({ content => 1 })
596 returns '<foo></foo>', while with C<passthrough> option
598 HTML::Zoom->from_html('<foo><bar /></foo>')
600 ->collect({ content => 1, passthough => 1 })
603 returns '<foo><bar /></foo>'.
605 =item content [BOOLEAN]
607 Collect content of the element, and not the element itself.
611 HTML::Zoom->from_html('<h1>Title</h1><p>foo</p>')
616 would return '<p>foo</p>', while
618 HTML::Zoom->from_html('<h1>Title</h1><p>foo</p>')
620 ->collect({ content => 1 })
623 would return '<h1></h1><p>foo</p>'.
625 See also L</collect_content>.
627 =item flush_before [BOOLEAN]
629 Generate C<flush> event before collecting, to ensure that the HTML generated up
630 to selected element being collected is flushed throught to the browser. Usually
631 used in L</repeat> or L</repeat_content>.
635 =head2 collect_content
637 Collects contents of L<HTML::Zoom/select> result.
639 HTML::Zoom->from_file($foo)
640 ->select('#main-content')
641 ->collect_content({ into => \@foo_body })
644 ->replace_content(\@foo_body)
647 Equivalent to running L</collect> with C<content> option set.
651 Given a L<HTML::Zoom/select> result, add given content (which might be string,
652 array or another L<HTML::Zoom> object) before it.
655 ->select('input[name="foo"]')
656 ->add_before(\ '<span class="warning">required field</span>');
660 Like L</add_before>, only after L<HTML::Zoom/select> result.
666 You can add zoom events directly
670 ->add_after([ { type => 'TEXT', raw => 'O HAI' } ]);
672 =head2 prepend_content
674 Similar to add_before, but adds the content to the match.
677 ->from_html(q[<p>World</p>])
679 ->prepend_content("Hello ")
682 ## <p>Hello World</p>
684 Acceptable values are strings, scalar refs and L<HTML::Zoom> objects
686 =head2 append_content
688 Similar to add_after, but adds the content to the match.
691 ->from_html(q[<p>Hello </p>])
693 ->prepend_content("World")
696 ## <p>Hello World</p>
698 Acceptable values are strings, scalar refs and L<HTML::Zoom> objects
702 Given a L<HTML::Zoom/select> result, replace it with a string, array or another
703 L<HTML::Zoom> object. It takes the same optional common options as L</collect>
704 (via hash reference).
706 =head2 replace_content
708 Given a L<HTML::Zoom/select> result, replace the content with a string, array
709 or another L<HTML::Zoom> object.
712 ->select('title, #greeting')
713 ->replace_content('Hello world!');
717 For a given selection, repeat over transformations, typically for the purposes
718 of populating lists. Takes either an array of anonymous subroutines or a zoom-
719 able object consisting of transformation.
721 Example of array reference style (when it doesn't matter that all iterations are
724 $zoom->select('table')->repeat([
728 $_->select('td')->replace_content($e);
733 Subroutines would be run with $_ localized to result of L<HTML::Zoom/select> (of
734 collected elements), and with said result passed as parameter to subroutine.
736 You might want to use CodeStream when you don't have all elements upfront
738 $zoom->select('.contents')->repeat(sub {
739 HTML::Zoom::CodeStream->new({
741 while (my $line = $fh->getline) {
743 $_->select('.lno')->replace_content($fh->input_line_number)
744 ->select('.line')->replace_content($line)
752 In addition to common options as in L</collect>, it also supports:
756 =item repeat_between [SELECTOR]
758 Selects object to be repeated between items. In the case of array this object
759 is put between elements, in case of iterator it is put between results of
760 subsequent iterations, in the case of streamable it is put between events
763 See documentation for L</repeat_content>
767 =head2 repeat_content
769 Given a L<HTML::Zoom/select> result, run provided iterator passing content of
770 this result to this iterator. Accepts the same options as L</repeat>.
772 Equivalent to using C<contents> option with L</repeat>.
779 $_->select('.name')->replace_content('Matt')
780 ->select('.age')->replace_content('26')
783 $_->select('.name')->replace_content('Mark')
784 ->select('.age')->replace_content('0x29')
787 $_->select('.name')->replace_content('Epitaph')
788 ->select('.age')->replace_content('<redacted>')
791 { repeat_between => '.between' }
801 See L<HTML::Zoom> for authors.
805 See L<HTML::Zoom> for the license.