]> iEval git - html-element-library.git/blob - lib/HTML/Element/Library.pm
first commit
[html-element-library.git] / lib / HTML / Element / Library.pm
1 package HTML::Element::Library;
2
3 use 5.006001;
4 use strict;
5 use warnings;
6
7
8 our $DEBUG = 0;
9 #our $DEBUG = 1;
10
11 use Array::Group qw(:all);
12 use Carp qw(confess);
13 use Data::Dumper;
14 use HTML::Element;
15 use List::MoreUtils qw/:all/;
16 use Params::Validate qw(:all);
17 use Scalar::Listify;
18 #use Tie::Cycle;
19 use List::Rotation::Cycle;
20
21 our %EXPORT_TAGS = ( 'all' => [ qw() ] );
22 our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
23 our @EXPORT = qw();
24
25
26
27 our $VERSION = '3.51';
28
29
30 # Preloaded methods go here.
31
32 sub HTML::Element::siblings {
33 my $element = shift;
34 my $p = $element->parent;
35 return () unless $p;
36 $p->content_list;
37 }
38
39 sub HTML::Element::sibdex {
40
41 my $element = shift;
42 firstidx { $_ eq $element } $element->siblings
43
44 }
45
46 sub HTML::Element::addr { goto &HTML::Element::sibdex }
47
48 sub HTML::Element::replace_content {
49 my $elem = shift;
50 $elem->delete_content;
51 $elem->push_content(@_);
52 }
53
54 sub HTML::Element::wrap_content {
55 my($self, $wrap) = @_;
56 my $content = $self->content;
57 if (ref $content) {
58 $wrap->push_content(@$content);
59 @$content = ($wrap);
60 }
61 else {
62 $self->push_content($wrap);
63 }
64 $wrap;
65 }
66
67 sub HTML::Element::Library::super_literal {
68 my($text) = @_;
69
70 HTML::Element->new('~literal', text => $text);
71 }
72
73
74 sub HTML::Element::position {
75 # Report coordinates by chasing addr's up the
76 # HTML::ElementSuper tree. We know we've reached
77 # the top when a) there is no parent, or b) the
78 # parent is some HTML::Element unable to report
79 # it's position.
80 my $p = shift;
81 my @pos;
82 while ($p) {
83 my $a = $p->addr;
84 unshift(@pos, $a) if defined $a;
85 $p = $p->parent;
86 }
87 @pos;
88 }
89
90
91 sub HTML::Element::content_handler {
92 my ($tree, $id_name, $content) = @_;
93
94 $tree->set_child_content(id => $id_name, $content);
95
96 }
97
98
99 sub make_counter {
100 my $i = 1;
101 sub {
102 shift() . ':' . $i++
103 }
104 }
105
106
107 sub HTML::Element::iter {
108 my ($tree, $p, @data) = @_;
109
110 # warn 'P: ' , $p->attr('id') ;
111 # warn 'H: ' , $p->as_HTML;
112
113 # my $id_incr = make_counter;
114 my @item = map {
115 my $new_item = clone $p;
116 $new_item->replace_content($_);
117 # $new_item->attr('id', $id_incr->( $p->attr('id') ));
118 $new_item;
119 } @data;
120
121 $p->replace_with(@item);
122
123 }
124
125
126 sub HTML::Element::iter2 {
127
128 my $tree = shift;
129
130 #warn "INPUT TO TABLE2: ", Dumper \@_;
131
132 my %p = validate(
133 @_, {
134 wrapper_ld => { default => ['_tag' => 'dl'] },
135 wrapper_data => 1,
136 wrapper_proc => { default => undef },
137 item_ld => { default => sub {
138 my $tree = shift;
139 [
140 $tree->look_down('_tag' => 'dt'),
141 $tree->look_down('_tag' => 'dd')
142 ];
143 }
144 },
145 item_data => { default => sub { my ($wrapper_data) = @_;
146 shift(@{$wrapper_data}) ;
147 }},
148 item_proc => {
149 default => sub {
150 my ($item_elems, $item_data, $row_count) = @_;
151 $item_elems->[$_]->replace_content($item_data->[$_]) for (0,1) ;
152 $item_elems;
153 }},
154 splice => { default => sub {
155 my ($container, @item_elems) = @_;
156 $container->splice_content(0, 2, @item_elems);
157 }
158 },
159 debug => {default => 0}
160 }
161 );
162
163 warn "wrapper_data: " . Dumper $p{wrapper_data} if $p{debug} ;
164
165 my $container = ref_or_ld($tree, $p{wrapper_ld});
166 warn "wrapper_(preproc): " . $container->as_HTML if $p{debug} ;
167 $p{wrapper_proc}->($container) if defined $p{wrapper_proc} ;
168 warn "wrapper_(postproc): " . $container->as_HTML if $p{debug} ;
169
170 my $_item_elems = $p{item_ld}->($container);
171
172
173
174 my $row_count;
175 my @item_elem;
176 {
177 my $item_data = $p{item_data}->($p{wrapper_data});
178 last unless defined $item_data;
179
180 warn Dumper("item_data", $item_data);
181
182
183 my $item_elems = [ map { $_->clone } @{$_item_elems} ] ;
184
185 if ($p{debug}) {
186 for (@{$item_elems}) {
187 warn "ITEM_ELEMS ", $_->as_HTML;
188 }
189 }
190
191 my $new_item_elems = $p{item_proc}->($item_elems, $item_data, ++$row_count);
192
193 if ($p{debug}) {
194 for (@{$new_item_elems}) {
195 warn "NEWITEM_ELEMS ", $_->as_HTML;
196 }
197 }
198
199
200 push @item_elem, @{$new_item_elems} ;
201
202 redo;
203 }
204
205 warn "pushing " . @item_elem . " elems " if $p{debug} ;
206
207 $p{splice}->($container, @item_elem);
208
209 }
210
211 sub HTML::Element::dual_iter {
212 my ($parent, $data) = @_;
213
214 my ($prototype_a, $prototype_b) = $parent->content_list;
215
216 # my $id_incr = make_counter;
217
218 my $i;
219
220 @$data %2 == 0 or
221 confess 'dataset does not contain an even number of members';
222
223 my @iterable_data = ngroup 2 => @$data;
224
225 my @item = map {
226 my ($new_a, $new_b) = map { clone $_ } ($prototype_a, $prototype_b) ;
227 $new_a->splice_content(0,1, $_->[0]);
228 $new_b->splice_content(0,1, $_->[1]);
229 #$_->attr('id', $id_incr->($_->attr('id'))) for ($new_a, $new_b) ;
230 ($new_a, $new_b)
231 } @iterable_data;
232
233 $parent->splice_content(0, 2, @item);
234
235 }
236
237
238 sub HTML::Element::set_child_content {
239 my $tree = shift;
240 my $content = pop;
241 my @look_down = @_;
242
243 my $content_tag = $tree->look_down(@look_down);
244
245 unless ($content_tag) {
246 warn "criteria [@look_down] not found";
247 return;
248 }
249
250 $content_tag->replace_content($content);
251
252 }
253
254 sub HTML::Element::highlander {
255 my ($tree, $local_root_id, $aref, @arg) = @_;
256
257 ref $aref eq 'ARRAY' or confess
258 "must supply array reference";
259
260 my @aref = @$aref;
261 @aref % 2 == 0 or confess
262 "supplied array ref must have an even number of entries";
263
264 warn __PACKAGE__ if $DEBUG;
265
266 my $survivor;
267 while (my ($id, $test) = splice @aref, 0, 2) {
268 warn $id if $DEBUG;
269 if ($test->(@arg)) {
270 $survivor = $id;
271 last;
272 }
273 }
274
275
276 my @id_survivor = (id => $survivor);
277 my $survivor_node = $tree->look_down(@id_survivor);
278 # warn $survivor;
279 # warn $local_root_id;
280 # warn $node;
281
282 warn "survivor: $survivor" if $DEBUG;
283 warn "tree: " . $tree->as_HTML if $DEBUG;
284
285 $survivor_node or die "search for @id_survivor failed in tree($tree): " . $tree->as_HTML;
286
287 my $survivor_node_parent = $survivor_node->parent;
288 $survivor_node = $survivor_node->clone;
289 $survivor_node_parent->replace_content($survivor_node);
290
291 warn "new tree: " . $tree->as_HTML if $DEBUG;
292
293 $survivor_node;
294 }
295
296
297 sub HTML::Element::highlander2 {
298 my $tree = shift;
299
300 my %p = validate(@_, {
301 cond => { type => ARRAYREF },
302 cond_arg => { type => ARRAYREF,
303 default => []
304 },
305 debug => { default => 0 }
306 }
307 );
308
309
310 my @cond = @{$p{cond}};
311 @cond % 2 == 0 or confess
312 "supplied array ref must have an even number of entries";
313
314 warn __PACKAGE__ if $p{debug};
315
316 my @cond_arg = @{$p{cond_arg}};
317
318 my $survivor; my $then;
319 while (my ($id, $if_then) = splice @cond, 0, 2) {
320
321 warn $id if $p{debug};
322 my ($if, $_then);
323
324 if (ref $if_then eq 'ARRAY') {
325 ($if, $_then) = @$if_then;
326 } else {
327 ($if, $_then) = ($if_then, sub {});
328 }
329
330 if ($if->(@cond_arg)) {
331 $survivor = $id;
332 $then = $_then;
333 last;
334 }
335
336 }
337
338 my @ld = (ref $survivor eq 'ARRAY')
339 ? @$survivor
340 : (id => $survivor)
341 ;
342
343 warn "survivor: ", $survivor if $p{debug};
344 warn "survivor_ld: ", Dumper \@ld if $p{debug};
345
346
347 my $survivor_node = $tree->look_down(@ld);
348
349 $survivor_node or confess
350 "search for @ld failed in tree($tree): " . $tree->as_HTML;
351
352 my $survivor_node_parent = $survivor_node->parent;
353 $survivor_node = $survivor_node->clone;
354 $survivor_node_parent->replace_content($survivor_node);
355
356
357 # **************** NEW FUNCTIONALITY *******************
358
359 # apply transforms on survivor node
360
361
362 warn "SURV::pre_trans " . $survivor_node->as_HTML if $p{debug};
363 $then->($survivor_node, @cond_arg);
364 warn "SURV::post_trans " . $survivor_node->as_HTML if $p{debug};
365
366 # **************** NEW FUNCTIONALITY *******************
367
368
369
370
371 $survivor_node;
372 }
373
374
375 sub overwrite_action {
376 my ($mute_node, %X) = @_;
377
378 $mute_node->attr($X{local_attr}{name} => $X{local_attr}{value}{new});
379 }
380
381
382 sub HTML::Element::overwrite_attr {
383 my $tree = shift;
384
385 $tree->mute_elem(@_, \&overwrite_action);
386 }
387
388
389
390 sub HTML::Element::mute_elem {
391 my ($tree, $mute_attr, $closures, $post_hook) = @_;
392
393 warn "my mute_node = $tree->look_down($mute_attr => qr/.*/) ;";
394 my @mute_node = $tree->look_down($mute_attr => qr/.*/) ;
395
396 for my $mute_node (@mute_node) {
397 my ($local_attr,$mute_key) = split /\s+/, $mute_node->attr($mute_attr);
398 my $local_attr_value_current = $mute_node->attr($local_attr);
399 my $local_attr_value_new = $closures->{$mute_key}->($tree, $mute_node, $local_attr_value_current);
400 $post_hook->(
401 $mute_node,
402 tree => $tree,
403 local_attr => {
404 name => $local_attr,
405 value => {
406 current => $local_attr_value_current,
407 new => $local_attr_value_new
408 }
409 }
410 ) if ($post_hook) ;
411 }
412 }
413
414
415
416 sub HTML::Element::table {
417
418 my ($s, %table) = @_;
419
420 my $table = {};
421
422 # use Data::Dumper; warn Dumper \%table;
423
424 # ++$DEBUG if $table{debug} ;
425
426
427 # Get the table element
428 $table->{table_node} = $s->look_down(id => $table{gi_table});
429 $table->{table_node} or confess
430 "table tag not found via (id => $table{gi_table}";
431
432 # Get the prototype tr element(s)
433 my @table_gi_tr = listify $table{gi_tr} ;
434 my @iter_node = map
435 {
436 my $tr = $table->{table_node}->look_down(id => $_);
437 $tr or confess "tr with id => $_ not found";
438 $tr;
439 } @table_gi_tr;
440
441 warn "found " . @iter_node . " iter nodes " if $DEBUG;
442 # tie my $iter_node, 'Tie::Cycle', \@iter_node;
443 my $iter_node = List::Rotation::Cycle->new(@iter_node);
444
445 # warn $iter_node;
446 warn Dumper ($iter_node, \@iter_node) if $DEBUG;
447
448 # $table->{content} = $table{content};
449 #$table->{parent} = $table->{table_node}->parent;
450
451
452 # $table->{table_node}->detach;
453 # $_->detach for @iter_node;
454
455 my @table_rows;
456
457 {
458 my $row = $table{tr_data}->($table, $table{table_data});
459 last unless defined $row;
460
461 # get a sample table row and clone it.
462 my $I = $iter_node->next;
463 warn "I: $I" if $DEBUG;
464 my $new_iter_node = $I->clone;
465
466
467 $table{td_data}->($new_iter_node, $row);
468 push @table_rows, $new_iter_node;
469
470 redo;
471 }
472
473 if (@table_rows) {
474
475 my $replace_with_elem = $s->look_down(id => shift @table_gi_tr) ;
476 for (@table_gi_tr) {
477 $s->look_down(id => $_)->detach;
478 }
479
480 $replace_with_elem->replace_with(@table_rows);
481
482 }
483
484 }
485
486 sub ref_or_ld {
487
488 my ($tree, $slot) = @_;
489
490 if (ref($slot) eq 'CODE') {
491 $slot->($tree);
492 } else {
493 $tree->look_down(@$slot);
494 }
495 }
496
497
498
499 sub HTML::Element::table2 {
500
501 my $tree = shift;
502
503
504
505 my %p = validate(
506 @_, {
507 table_ld => { default => ['_tag' => 'table'] },
508 table_data => 1,
509 table_proc => { default => undef },
510
511 tr_ld => { default => ['_tag' => 'tr'] },
512 tr_data => { default => sub { my ($self, $data) = @_;
513 shift(@{$data}) ;
514 }},
515 tr_base_id => { default => undef },
516 tr_proc => { default => sub {} },
517 td_proc => 1,
518 debug => {default => 0}
519 }
520 );
521
522 warn "INPUT TO TABLE2: ", Dumper \@_ if $p{debug};
523
524 warn "table_data: " . Dumper $p{table_data} if $p{debug} ;
525
526 my $table = {};
527
528 # use Data::Dumper; warn Dumper \%table;
529
530 # ++$DEBUG if $table{debug} ;
531
532 # Get the table element
533 warn 1;
534 $table->{table_node} = ref_or_ld( $tree, $p{table_ld} ) ;
535 warn 2;
536 $table->{table_node} or confess
537 "table tag not found via " . Dumper($p{table_ld}) ;
538
539 warn "table: " . $table->{table_node}->as_HTML if $p{debug};
540
541
542 # Get the prototype tr element(s)
543 my @proto_tr = ref_or_ld( $table->{table_node}, $p{tr_ld} ) ;
544
545 warn "found " . @proto_tr . " iter nodes " if $p{debug};
546
547 @proto_tr or return ;
548
549 if ($p{debug}) {
550 warn $_->as_HTML for @proto_tr;
551 }
552 my $proto_tr = List::Rotation::Cycle->new(@proto_tr);
553
554 my $tr_parent = $proto_tr[0]->parent;
555 warn "parent element of trs: " . $tr_parent->as_HTML if $p{debug};
556
557 my $row_count;
558
559 my @table_rows;
560
561 {
562 my $row = $p{tr_data}->($table, $p{table_data}, $row_count);
563 warn "data row: " . Dumper $row if $p{debug};
564 last unless defined $row;
565
566 # wont work: my $new_iter_node = $table->{iter_node}->clone;
567 my $new_tr_node = $proto_tr->next->clone;
568 warn "new_tr_node: $new_tr_node" if $p{debug};
569
570 $p{tr_proc}->($tree, $new_tr_node, $row, $p{tr_base_id}, ++$row_count)
571 if defined $p{tr_proc};
572
573 warn "data row redux: " . Dumper $row if $p{debug};
574 warn 3.3;
575
576 $p{td_proc}->($new_tr_node, $row);
577 push @table_rows, $new_tr_node;
578
579 warn 4.4;
580
581 redo;
582 }
583
584 $_->detach for @proto_tr;
585
586 $tr_parent->push_content(@table_rows) if (@table_rows) ;
587
588 }
589
590
591 sub HTML::Element::unroll_select {
592
593 my ($s, %select) = @_;
594
595 my $select = {};
596
597 my $select_node = $s->look_down(id => $select{select_label});
598
599 my $option = $select_node->look_down('_tag' => 'option');
600
601 # warn $option;
602
603
604 $option->detach;
605
606 while (my $row = $select{data_iter}->($select{data}))
607 {
608 # warn Dumper($row);
609 my $o = $option->clone;
610 $o->attr('value', $select{option_value}->($row));
611 $o->attr('SELECTED', 1) if ($select{option_selected}->($row)) ;
612
613 $o->replace_content($select{option_content}->($row));
614 $select_node->push_content($o);
615 }
616
617
618 }
619
620
621
622 sub HTML::Element::set_sibling_content {
623 my ($elt, $content) = @_;
624
625 $elt->parent->splice_content($elt->pindex + 1, 1, $content);
626
627 }
628
629 sub HTML::TreeBuilder::parse_string {
630 my ($package, $string) = @_;
631
632 my $h = HTML::TreeBuilder->new;
633 HTML::TreeBuilder->parse($string);
634
635 }
636
637
638
639 1;
640 __END__
641 # Below is stub documentation for your module. You'd better edit it!
642
643 =head1 NAME
644
645 HTML::Element::Library - HTML::Element convenience functions
646
647 =head1 SYNOPSIS
648
649 use HTML::Element::Library;
650 use HTML::TreeBuilder;
651
652 =head1 DESCRIPTION
653
654 This method provides API calls for common actions on trees when using
655 L<HTML::Tree>.
656
657 =head1 METHODS
658
659 The test suite contains examples of each of these methods in a
660 file C<t/$method.t>
661
662 =head2 Positional Querying Methods
663
664 =head3 $elem->siblings
665
666 Return a list of all nodes under the same parent.
667
668 =head3 $elem->sibdex
669
670 Return the index of C<$elem> into the array of siblings of which it is
671 a part. L<HTML::ElementSuper> calls this method C<addr> but I don't think
672 that is a descriptive name. And such naming is deceptively close to the
673 C<address> function of C<HTML::Element>. HOWEVER, in the interest of
674 backwards compatibility, both methods are available.
675
676 =head3 $elem->addr
677
678 Same as sibdex
679
680 =head3 $elem->position()
681
682 Returns the coordinates of this element in the tree it inhabits.
683 This is accomplished by succesively calling addr() on ancestor
684 elements until either a) an element that does not support these
685 methods is found, or b) there are no more parents. The resulting
686 list is the n-dimensional coordinates of the element in the tree.
687
688 =head2 Element Decoration Methods
689
690 =head3 HTML::Element::Library::super_literal($text)
691
692 In L<HTML::Element>, Sean Burke discusses super-literals. They are
693 text which does not get escaped. Great for includng Javascript in
694 HTML. Also great for including foreign language into a document.
695
696 So, you basically toss C<super_literal> your text and back comes
697 your text wrapped in a C<~literal> element.
698
699 One of these days, I'll around to writing a nice C<EXPORT> section.
700
701 =head2 Tree Rewriting Methods
702
703 =head3 $elem->replace_content(@new_elem)
704
705 Replaces all of C<$elem>'s content with C<@new_elem>.
706
707 =head3 $elem->wrap_content($wrapper_element)
708
709 Wraps the existing content in the provided element. If the provided element
710 happens to be a non-element, a push_content is performed instead.
711
712 =head3 $elem->set_child_content(@look_down, $content)
713
714 This method looks down $tree using the criteria specified in @look_down using the the HTML::Element look_down() method.
715
716 After finding the node, it detaches the node's content and pushes $content as the node's content.
717
718 =head3 $tree->content_handler($sid_value , $content)
719
720 This is a convenience method. Because the look_down criteria will often simply be:
721
722 id => 'fixme'
723
724 to find things like:
725
726 <a id=fixme href=http://www.somesite.org>replace_content</a>
727
728 You can call this method to shorten your typing a bit. You can simply type
729
730 $elem->content_handler( fixme => 'new text' )
731
732 Instead of typing:
733
734 $elem->set_child_content(sid => 'fixme', 'new text')
735
736 =head3 $tree->highlander($subtree_span_id, $conditionals, @conditionals_args)
737
738 This allows for "if-then-else" style processing. Highlander was a movie in
739 which only one would survive. Well, in terms of a tree when looking at a
740 structure that you want to process in C<if-then-else> style, only one child
741 will survive. For example, given this HTML template:
742
743 <span klass="highlander" id="age_dialog">
744 <span id="under10">
745 Hello, does your mother know you're
746 using her AOL account?
747 </span>
748 <span id="under18">
749 Sorry, you're not old enough to enter
750 (and too dumb to lie about your age)
751 </span>
752 <span id="welcome">
753 Welcome
754 </span>
755 </span>
756
757 We only want one child of the C<span> tag with id C<age_dialog> to remain
758 based on the age of the person visiting the page.
759
760 So, let's setup a call that will prune the subtree as a function of age:
761
762 sub process_page {
763 my $age = shift;
764 my $tree = HTML::TreeBuilder->new_from_file('t/html/highlander.html');
765
766 $tree->highlander
767 (age_dialog =>
768 [
769 under10 => sub { $_[0] < 10} ,
770 under18 => sub { $_[0] < 18} ,
771 welcome => sub { 1 }
772 ],
773 $age
774 );
775
776 And there we have it. If the age is less than 10, then the node with
777 id C<under10> remains. For age less than 18, the node with id C<under18>
778 remains.
779 Otherwise our "else" condition fires and the child with id C<welcome> remains.
780
781 =head3 $tree->highlander2($tree, $conditionals, @conditionals_args)
782
783 Right around the same time that C<table2()> came into being, Seamstress
784 began to tackle tougher and tougher processing problems. It became clear that
785 a more powerful highlander was needed... one that not only snipped the tree
786 of the nodes that should not survive, but one that allows for
787 post-processing of the survivor node. And one that was more flexible with
788 how to find the nodes to snip.
789
790 Thus (drum roll) C<highlander2()>.
791
792 So let's look at our HTML which requires post-selection processing:
793
794 <span klass="highlander" id="age_dialog">
795 <span id="under10">
796 Hello, little <span id=age>AGE</span>-year old,
797 does your mother know you're using her AOL account?
798 </span>
799 <span id="under18">
800 Sorry, you're only <span id=age>AGE</span>
801 (and too dumb to lie about your age)
802 </span>
803 <span id="welcome">
804 Welcome, isn't it good to be <span id=age>AGE</span> years old?
805 </span>
806 </span>
807
808 In this case, a branch survives, but it has dummy data in it. We must take
809 the surviving segment of HTML and rewrite the age C<span> with the age.
810 Here is how we use C<highlander2()> to do so:
811
812 sub replace_age {
813 my $branch = shift;
814 my $age = shift;
815 $branch->look_down(id => 'age')->replace_content($age);
816 }
817
818 my $if_then = $tree->look_down(id => 'age_dialog');
819
820 $if_then->highlander2(
821 cond => [
822 under10 => [
823 sub { $_[0] < 10} ,
824 \&replace_age
825 ],
826 under18 => [
827 sub { $_[0] < 18} ,
828 \&replace_age
829 ],
830 welcome => [
831 sub { 1 },
832 \&replace_age
833 ]
834 ],
835 cond_arg => [ $age ]
836 );
837
838 We pass it the tree (C<$if_then>), an arrayref of conditions
839 (C<cond>) and an arrayref of arguments which are passed to the
840 C<cond>s and to the replacement subs.
841
842 The C<under10>, C<under18> and C<welcome> are id attributes in the
843 tree of the siblings of which only one will survive. However,
844 should you need to do
845 more complex look-downs to find the survivor,
846 then supply an array ref instead of a simple
847 scalar:
848
849
850 $if_then->highlander2(
851 cond => [
852 [class => 'r12'] => [
853 sub { $_[0] < 10} ,
854 \&replace_age
855 ],
856 [class => 'z22'] => [
857 sub { $_[0] < 18} ,
858 \&replace_age
859 ],
860 [class => 'w88'] => [
861 sub { 1 },
862 \&replace_age
863 ]
864 ],
865 cond_arg => [ $age ]
866 );
867
868
869 =head3 $tree->overwrite_attr($mutation_attr => $mutating_closures)
870
871 This method is designed for taking a tree and reworking a set of nodes in
872 a stereotyped fashion. For instance let's say you have 3 remote image
873 archives, but you don't want to put long URLs in your img src
874 tags for reasons of abstraction, re-use and brevity. So instead you do this:
875
876 <img src="/img/smiley-face.jpg" fixup="src lnc">
877 <img src="/img/hot-babe.jpg" fixup="src playboy">
878 <img src="/img/footer.jpg" fixup="src foobar">
879
880 and then when the tree of HTML is being processed, you make this call:
881
882 my %closures = (
883 lnc => sub { my ($tree, $mute_node, $attr_value)= @_; "http://lnc.usc.edu$attr_value" },
884 playboy => sub { my ($tree, $mute_node, $attr_value)= @_; "http://playboy.com$attr_value" }
885 foobar => sub { my ($tree, $mute_node, $attr_value)= @_; "http://foobar.info$attr_value" }
886 )
887
888 $tree->overwrite_attr(fixup => \%closures) ;
889
890 and the tags come out modified like so:
891
892 <img src="http://lnc.usc.edu/img/smiley-face.jpg" fixup="src lnc">
893 <img src="http://playboy.com/img/hot-babe.jpg" fixup="src playboy">
894 <img src="http://foobar.info/img/footer.jpg" fixup="src foobar">
895
896 =head3 $tree->mute_elem($mutation_attr => $mutating_closures, [ $post_hook ] )
897
898 This is a generalization of C<overwrite_attr>. C<overwrite_attr>
899 assumes the return value of the
900 closure is supposed overwrite an attribute value and does it for you.
901 C<mute_elem> is a more general function which does nothing but
902 hand the closure the element and let it mutate it as it jolly well pleases :)
903
904 In fact, here is the implementation of C<overwrite_attr>
905 to give you a taste of how C<mute_attr> is used:
906
907 sub overwrite_action {
908 my ($mute_node, %X) = @_;
909
910 $mute_node->attr($X{local_attr}{name} => $X{local_attr}{value}{new});
911 }
912
913
914 sub HTML::Element::overwrite_attr {
915 my $tree = shift;
916
917 $tree->mute_elem(@_, \&overwrite_action);
918 }
919
920
921
922
923 =head2 Tree-Building Methods: Unrolling an array via a single sample element (<ul> container)
924
925 This is best described by example. Given this HTML:
926
927 <strong>Here are the things I need from the store:</strong>
928 <ul>
929 <li class="store_items">Sample item</li>
930 </ul>
931
932 We can unroll it like so:
933
934 my $li = $tree->look_down(class => 'store_items');
935
936 my @items = qw(bread butter vodka);
937
938 $tree->iter($li => @items);
939
940 To produce this:
941
942
943 <html>
944 <head></head>
945 <body>Here are the things I need from the store:
946 <ul>
947 <li class="store_items">bread</li>
948 <li class="store_items">butter</li>
949 <li class="store_items">vodka</li>
950 </ul>
951 </body>
952 </html>
953
954 =head2 Tree-Building Methods: Unrolling an array via n sample elements (<dl> container)
955
956 C<iter()> was fine for awhile, but some things
957 (e.g. definition lists) need a more general function to make them easy to
958 do. Hence C<iter2()>. This function will be explained by example of unrolling
959 a simple definition list.
960
961 So here's our mock-up HTML from the designer:
962
963 <dl class="dual_iter" id="service_plan">
964 <dt>
965 Artist
966 </dt>
967 <dd>
968 A person who draws blood.
969 </dd>
970
971 <dt>
972 Musician
973 </dt>
974 <dd>
975 A clone of Iggy Pop.
976 </dd>
977
978 <dt>
979 Poet
980 </dt>
981 <dd>
982 A relative of Edgar Allan Poe.
983 </dd>
984
985 <dt class="adstyle">sample header</dt>
986 <dd class="adstyle2">sample data</dd>
987
988 </dl>
989
990
991 And we want to unroll our data set:
992
993 my @items = (
994 ['the pros' => 'never have to worry about service again'],
995 ['the cons' => 'upfront extra charge on purchase'],
996 ['our choice' => 'go with the extended service plan']
997 );
998
999
1000 Now, let's make this problem a bit harder to show off the power of C<iter2()>.
1001 Let's assume that we want only the last <dt> and it's accompanying <dd>
1002 (the one with "sample data") to be used as the sample data
1003 for unrolling with our data set. Let's further assume that we want them to
1004 remain in the final output.
1005
1006 So now, the API to C<iter2()> will be discussed and we will explain how our
1007 goal of getting our data into HTML fits into the API.
1008
1009 =over 4
1010
1011 =item * wrapper_ld
1012
1013 This is how to look down and find the container of all the elements we will
1014 be unrolling. The <dl> tag is the container for the dt and dd tags we will be
1015 unrolling.
1016
1017 If you pass an anonymous subroutine, then it is presumed that execution of
1018 this subroutine will return the HTML::Element representing the container tag.
1019 If you pass an array ref, then this will be dereferenced and passed to
1020 C<HTML::Element::look_down()>.
1021
1022 default value: C<< ['_tag' => 'dl'] >>
1023
1024 Based on the mock HTML above, this default is fine for finding our container
1025 tag. So let's move on.
1026
1027 =item * wrapper_data
1028
1029 This is an array reference of data that we will be putting into the container.
1030 You must supply this. C<@items> above is our C<wrapper_data>.
1031
1032 =item * wrapper_proc
1033
1034 After we find the container via C<wrapper_ld>, we may want to pre-process
1035 some aspect of this tree. In our case the first two sets of dt and dd need
1036 to be removed, leaving the last dt and dd. So, we supply a C<wrapper_proc>
1037 which will do this.
1038
1039 default: undef
1040
1041 =item * item_ld
1042
1043 This anonymous subroutine returns an array ref of C<HTML::Element>s that will
1044 be cloned and populated with item data
1045 (item data is a "row" of C<wrapper_data>).
1046
1047 default: returns an arrayref consisting of the dt and dd element inside the
1048 container.
1049
1050 =item * item_data
1051
1052 This is a subroutine that takes C<wrapper_data> and retrieves one "row"
1053 to be "pasted" into the array ref of C<HTML::Element>s found via C<item_ld>.
1054 I hope that makes sense.
1055
1056 default: shifts C<wrapper_data>.
1057
1058 =item * item_proc
1059
1060 This is a subroutine that takes the C<item_data> and the C<HTML::Element>s
1061 found via C<item_ld> and produces an arrayref of C<HTML::Element>s which will
1062 eventually be spliced into the container.
1063
1064 Note that this subroutine MUST return the new items. This is done
1065 So that more items than were passed in can be returned. This is
1066 useful when, for example, you must return 2 dts for an input data item.
1067 And when would you do this? When a single term has multiple spellings
1068 for instance.
1069
1070 default: expects C<item_data> to be an arrayref of two elements and
1071 C<item_elems> to be an arrayref of two C<HTML::Element>s. It replaces the
1072 content of the C<HTML::Element>s with the C<item_data>.
1073
1074 =item * splice
1075
1076 After building up an array of C<@item_elems>, the subroutine passed as
1077 C<splice> will be given the parent container HTML::Element and the
1078 C<@item_elems>. How the C<@item_elems> end up in the container is up to this
1079 routine: it could put half of them in. It could unshift them or whatever.
1080
1081 default: C<< $container->splice_content(0, 2, @item_elems) >>
1082 In other words, kill the 2 sample elements with the newly generated
1083 @item_elems
1084
1085 =back
1086
1087 So now that we have documented the API, let's see the call we need:
1088
1089 $tree->iter2(
1090 # default wrapper_ld ok.
1091 wrapper_data => \@items,
1092 wrapper_proc => sub {
1093 my ($container) = @_;
1094
1095 # only keep the last 2 dts and dds
1096 my @content_list = $container->content_list;
1097 $container->splice_content(0, @content_list - 2);
1098 },
1099
1100 # default item_ld is fine.
1101 # default item_data is fine.
1102 # default item_proc is fine.
1103 splice => sub {
1104 my ($container, @item_elems) = @_;
1105 $container->unshift_content(@item_elems);
1106 },
1107 debug => 1,
1108 );
1109
1110
1111 =head2 Tree-Building Methods: Select Unrolling
1112
1113 The C<unroll_select> method has this API:
1114
1115 $tree->unroll_select(
1116 select_label => $id_label,
1117 option_value => $closure, # how to get option value from data row
1118 option_content => $closure, # how to get option content from data row
1119 option_selected => $closure, # boolean to decide if SELECTED
1120 data => $data # the data to be put into the SELECT
1121 data_iter => $closure # the thing that will get a row of data
1122 );
1123
1124 Here's an example:
1125
1126 $tree->unroll_select(
1127 select_label => 'clan_list',
1128 option_value => sub { my $row = shift; $row->clan_id },
1129 option_content => sub { my $row = shift; $row->clan_name },
1130 option_selected => sub { my $row = shift; $row->selected },
1131 data => \@query_results,
1132 data_iter => sub { my $data = shift; $data->next }
1133 )
1134
1135
1136
1137 =head2 Tree-Building Methods: Table Generation
1138
1139 Matthew Sisk has a much more intuitive (imperative)
1140 way to generate tables via his module
1141 L<HTML::ElementTable|HTML::ElementTable>.
1142 However, for those with callback fever, the following
1143 method is available. First, we look at a nuts and bolts way to build a table
1144 using only standard L<HTML::Tree> API calls. Then the C<table> method
1145 available here is discussed.
1146
1147 =head3 Sample Model
1148
1149 package Simple::Class;
1150
1151 use Set::Array;
1152
1153 my @name = qw(bob bill brian babette bobo bix);
1154 my @age = qw(99 12 44 52 12 43);
1155 my @weight = qw(99 52 80 124 120 230);
1156
1157
1158 sub new {
1159 my $this = shift;
1160 bless {}, ref($this) || $this;
1161 }
1162
1163 sub load_data {
1164 my @data;
1165
1166 for (0 .. 5) {
1167 push @data, {
1168 age => $age[rand $#age] + int rand 20,
1169 name => shift @name,
1170 weight => $weight[rand $#weight] + int rand 40
1171 }
1172 }
1173
1174 Set::Array->new(@data);
1175 }
1176
1177
1178 1;
1179
1180
1181 =head4 Sample Usage:
1182
1183 my $data = Simple::Class->load_data;
1184 ++$_->{age} for @$data
1185
1186 =head3 Inline Code to Unroll a Table
1187
1188 =head4 HTML
1189
1190 <html>
1191
1192 <table id="load_data">
1193
1194 <tr> <th>name</th><th>age</th><th>weight</th> </tr>
1195
1196 <tr id="iterate">
1197
1198 <td id="name"> NATURE BOY RIC FLAIR </td>
1199 <td id="age"> 35 </td>
1200 <td id="weight"> 220 </td>
1201
1202 </tr>
1203
1204 </table>
1205
1206 </html>
1207
1208
1209 =head4 The manual way (*NOT* recommended)
1210
1211 require 'simple-class.pl';
1212 use HTML::Seamstress;
1213
1214 # load the view
1215 my $seamstress = HTML::Seamstress->new_from_file('simple.html');
1216
1217 # load the model
1218 my $o = Simple::Class->new;
1219 my $data = $o->load_data;
1220
1221 # find the <table> and <tr>
1222 my $table_node = $seamstress->look_down('id', 'load_data');
1223 my $iter_node = $table_node->look_down('id', 'iterate');
1224 my $table_parent = $table_node->parent;
1225
1226
1227 # drop the sample <table> and <tr> from the HTML
1228 # only add them in if there is data in the model
1229 # this is achieved via the $add_table flag
1230
1231 $table_node->detach;
1232 $iter_node->detach;
1233 my $add_table;
1234
1235 # Get a row of model data
1236 while (my $row = shift @$data) {
1237
1238 # We got row data. Set the flag indicating ok to hook the table into the HTML
1239 ++$add_table;
1240
1241 # clone the sample <tr>
1242 my $new_iter_node = $iter_node->clone;
1243
1244 # find the tags labeled name age and weight and
1245 # set their content to the row data
1246 $new_iter_node->content_handler($_ => $row->{$_})
1247 for qw(name age weight);
1248
1249 $table_node->push_content($new_iter_node);
1250
1251 }
1252
1253 # reattach the table to the HTML tree if we loaded data into some table rows
1254
1255 $table_parent->push_content($table_node) if $add_table;
1256
1257 print $seamstress->as_HTML;
1258
1259
1260
1261 =head3 $tree->table() : API call to Unroll a Table
1262
1263 require 'simple-class.pl';
1264 use HTML::Seamstress;
1265
1266 # load the view
1267 my $seamstress = HTML::Seamstress->new_from_file('simple.html');
1268 # load the model
1269 my $o = Simple::Class->new;
1270
1271 $seamstress->table
1272 (
1273 # tell seamstress where to find the table, via the method call
1274 # ->look_down('id', $gi_table). Seamstress detaches the table from the
1275 # HTML tree automatically if no table rows can be built
1276
1277 gi_table => 'load_data',
1278
1279 # tell seamstress where to find the tr. This is a bit useless as
1280 # the <tr> usually can be found as the first child of the parent
1281
1282 gi_tr => 'iterate',
1283
1284 # the model data to be pushed into the table
1285
1286 table_data => $o->load_data,
1287
1288 # the way to take the model data and obtain one row
1289 # if the table data were a hashref, we would do:
1290 # my $key = (keys %$data)[0]; my $val = $data->{$key}; delete $data->{$key}
1291
1292 tr_data => sub { my ($self, $data) = @_;
1293 shift(@{$data}) ;
1294 },
1295
1296 # the way to take a row of data and fill the <td> tags
1297
1298 td_data => sub { my ($tr_node, $tr_data) = @_;
1299 $tr_node->content_handler($_ => $tr_data->{$_})
1300 for qw(name age weight) }
1301
1302 );
1303
1304
1305 print $seamstress->as_HTML;
1306
1307
1308
1309 =head4 Looping over Multiple Sample Rows
1310
1311 * HTML
1312
1313 <html>
1314
1315 <table id="load_data" CELLPADDING=8 BORDER=2>
1316
1317 <tr> <th>name</th><th>age</th><th>weight</th> </tr>
1318
1319 <tr id="iterate1" BGCOLOR="white" >
1320
1321 <td id="name"> NATURE BOY RIC FLAIR </td>
1322 <td id="age"> 35 </td>
1323 <td id="weight"> 220 </td>
1324
1325 </tr>
1326 <tr id="iterate2" BGCOLOR="#CCCC99">
1327
1328 <td id="name"> NATURE BOY RIC FLAIR </td>
1329 <td id="age"> 35 </td>
1330 <td id="weight"> 220 </td>
1331
1332 </tr>
1333
1334 </table>
1335
1336 </html>
1337
1338
1339 * Only one change to last API call.
1340
1341 This:
1342
1343 gi_tr => 'iterate',
1344
1345 becomes this:
1346
1347 gi_tr => ['iterate1', 'iterate2']
1348
1349 =head3 $tree->table2() : New API Call to Unroll a Table
1350
1351 After 2 or 3 years with C<table()>, I began to develop
1352 production websites with it and decided it needed a cleaner
1353 interface, particularly in the area of handling the fact that
1354 C<id> tags will be the same after cloning a table row.
1355
1356 First, I will give a dry listing of the function's argument parameters.
1357 This will not be educational most likely. A better way to understand how
1358 to use the function is to read through the incremental unrolling of the
1359 function's interface given in conversational style after the dry listing.
1360 But take your pick. It's the same information given in two different
1361 ways.
1362
1363 =head4 Dry/technical parameter documentation
1364
1365 C<< $tree->table2(%param) >> takes the following arguments:
1366
1367 =over
1368
1369 =item * C<< table_ld => $look_down >> : optional
1370
1371 How to find the C<table> element in C<$tree>. If C<$look_down> is an
1372 arrayref, then use C<look_down>. If it is a CODE ref, then call it,
1373 passing it C<$tree>.
1374
1375 Defaults to C<< ['_tag' => 'table'] >> if not passed in.
1376
1377 =item * C<< table_data => $tabular_data >> : required
1378
1379 The data to fill the table with. I<Must> be passed in.
1380
1381 =item * C<< table_proc => $code_ref >> : not implemented
1382
1383 A subroutine to do something to the table once it is found.
1384 Not currently implemented. Not obviously necessary. Just
1385 created because there is a C<tr_proc> and C<td_proc>.
1386
1387 =item * C<< tr_ld => $look_down >> : optional
1388
1389 Same as C<table_ld> but for finding the table row elements. Please note
1390 that the C<tr_ld> is done on the table node that was found I<instead>
1391 of the whole HTML tree. This makes sense. The C<tr>s that you want exist
1392 below the table that was just found.
1393
1394 Defaults to C<< ['_tag' => 'tr'] >> if not passed in.
1395
1396 =item * C<< tr_data => $code_ref >> : optional
1397
1398 How to take the C<table_data> and return a row. Defaults to:
1399
1400 sub { my ($self, $data) = @_;
1401 shift(@{$data}) ;
1402 }
1403
1404 =item * C<< tr_proc => $code_ref >> : optional
1405
1406 Something to do to the table row we are about to add to the
1407 table we are making. Defaults to a routine which makes the C<id>
1408 attribute unique:
1409
1410 sub {
1411 my ($self, $tr, $tr_data, $tr_base_id, $row_count) = @_;
1412 $tr->attr(id => sprintf "%s_%d", $tr_base_id, $row_count);
1413 }
1414
1415 =item * C<< td_proc => $code_ref >> : required
1416
1417 This coderef will take the row of data and operate on the C<td> cells that
1418 are children of the C<tr>. See C<t/table2.t> for several usage examples.
1419
1420 Here's a sample one:
1421
1422 sub {
1423 my ($tr, $data) = @_;
1424 my @td = $tr->look_down('_tag' => 'td');
1425 for my $i (0..$#td) {
1426 $td[$i]->splice_content(0, 1, $data->[$i]);
1427 }
1428 }
1429
1430 =cut
1431
1432 =head4 Conversational parameter documentation
1433
1434 The first thing you need is a table. So we need a look down for that. If you
1435 don't give one, it defaults to
1436
1437 ['_tag' => 'table']
1438
1439 What good is a table to display in without data to display?!
1440 So you must supply a scalar representing your tabular
1441 data source. This scalar might be an array reference, a C<next>able iterator,
1442 a DBI statement handle. Whatever it is, it can be iterated through to build
1443 up rows of table data.
1444 These two required fields (the way to find the table and the data to
1445 display in the table) are C<table_ld> and C<table_data>
1446 respectively. A little more on C<table_ld>. If this happens to be a CODE ref,
1447 then execution
1448 of the code ref is presumed to return the C<HTML::Element>
1449 representing the table in the HTML tree.
1450
1451 Next, we get the row or rows which serve as sample C<tr> elements by doing
1452 a C<look_down> from the C<table_elem>. While normally one sample row
1453 is enough to unroll a table, consider when you have alternating
1454 table rows. This API call would need one of each row so that it can
1455 cycle through the
1456 sample rows as it loops through the data.
1457 Alternatively, you could always just use one row and
1458 make the necessary changes to the single C<tr> row by
1459 mutating the element in C<tr_proc>,
1460 discussed below. The default C<tr_ld> is
1461 C<< ['_tag' => 'tr'] >> but you can overwrite it. Note well, if you overwrite
1462 it with a subroutine, then it is expected that the subroutine will return
1463 the C<HTML::Element>(s)
1464 which are C<tr> element(s).
1465 The reason a subroutine might be preferred is in the case
1466 that the HTML designers gave you 8 sample C<tr> rows but only one
1467 prototype row is needed.
1468 So you can write a subroutine, to splice out the 7 rows you don't need
1469 and leave the one sample
1470 row remaining so that this API call can clone it and supply it to
1471 the C<tr_proc> and C<td_proc> calls.
1472
1473 Now, as we move through the table rows with table data,
1474 we need to do two different things on
1475 each table row:
1476
1477 =over 4
1478
1479 =item * get one row of data from the C<table_data> via C<tr_data>
1480
1481 The default procedure assumes the C<table_data> is an array reference and
1482 shifts a row off of it:
1483
1484 sub { my ($self, $data) = @_;
1485 shift(@{$data}) ;
1486 }
1487
1488 Your function MUST return undef when there is no more rows to lay out.
1489
1490 =item * take the C<tr> element and mutate it via C<tr_proc>
1491
1492 The default procedure simply makes the id of the table row unique:
1493
1494 sub { my ($self, $tr, $tr_data, $row_count, $root_id) = @_;
1495 $tr->attr(id => sprintf "%s_%d", $root_id, $row_count);
1496 }
1497
1498 =back
1499
1500 Now that we have our row of data, we call C<td_proc> so that it can
1501 take the data and the C<td> cells in this C<tr> and process them.
1502 This function I<must> be supplied.
1503
1504
1505 =head3 Whither a Table with No Rows
1506
1507 Often when a table has no rows, we want to display a message
1508 indicating this to the view. Use conditional processing to decide what
1509 to display:
1510
1511 <span id=no_data>
1512 <table><tr><td>No Data is Good Data</td></tr></table>
1513 </span>
1514 <span id=load_data>
1515 <html>
1516
1517 <table id="load_data">
1518
1519 <tr> <th>name</th><th>age</th><th>weight</th> </tr>
1520
1521 <tr id="iterate">
1522
1523 <td id="name"> NATURE BOY RIC FLAIR </td>
1524 <td id="age"> 35 </td>
1525 <td id="weight"> 220 </td>
1526
1527 </tr>
1528
1529 </table>
1530
1531 </html>
1532
1533 </span>
1534
1535
1536
1537
1538 =head1 SEE ALSO
1539
1540 =over
1541
1542 =item * L<HTML::Tree>
1543
1544 A perl package for creating and manipulating HTML trees
1545
1546 =item * L<HTML::ElementTable>
1547
1548 An L<HTML::Tree> - based module which allows for manipulation of HTML
1549 trees using cartesian coordinations.
1550
1551 =item * L<HTML::Seamstress>
1552
1553 An L<HTML::Tree> - based module inspired by
1554 XMLC (L<http://xmlc.enhydra.org>), allowing for dynamic
1555 HTML generation via tree rewriting.
1556
1557 =head1 TODO
1558
1559 =over
1560
1561 =item * highlander2
1562
1563 currently the API expects the subtrees to survive or be pruned to be
1564 identified by id:
1565
1566 $if_then->highlander2([
1567 under10 => sub { $_[0] < 10} ,
1568 under18 => sub { $_[0] < 18} ,
1569 welcome => [
1570 sub { 1 },
1571 sub {
1572 my $branch = shift;
1573 $branch->look_down(id => 'age')->replace_content($age);
1574 }
1575 ]
1576 ],
1577 $age
1578 );
1579
1580 but, it should be more flexible. the C<under10>, and C<under18> are
1581 expected to be ids in the tree... but it is not hard to have a check to
1582 see if this field is an array reference and if it, then to do a look
1583 down instead:
1584
1585 $if_then->highlander2([
1586 [class => 'under10'] => sub { $_[0] < 10} ,
1587 [class => 'under18'] => sub { $_[0] < 18} ,
1588 [class => 'welcome'] => [
1589 sub { 1 },
1590 sub {
1591 my $branch = shift;
1592 $branch->look_down(id => 'age')->replace_content($age);
1593 }
1594 ]
1595 ],
1596 $age
1597 );
1598
1599
1600
1601 =cut
1602
1603 =head1 SEE ALSO
1604
1605 L<HTML::Seamstress>
1606
1607 =head1 AUTHOR
1608
1609 Terrence Brannon, E<lt>tbone@cpan.orgE<gt>
1610
1611 Many thanks to BARBIE for his RT bug report.
1612
1613 =head1 COPYRIGHT AND LICENSE
1614
1615 Copyright (C) 2004 by Terrence Brannon
1616
1617 This library is free software; you can redistribute it and/or modify
1618 it under the same terms as Perl itself, either Perl version 5.8.4 or,
1619 at your option, any later version of Perl 5 you may have available.
1620
1621
1622 =cut
This page took 0.090108 seconds and 4 git commands to generate.