Javascript/Menu.pm

filter: Statementstmt 66.6% 4 / 6 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 75.0% 6 / 8 CC 1 SCAR 1.4
CC
1
Cov
67%
BEGIN
1.3
BEGIN
1.0
CRAP 1.1
« Tree/Numbered.pm ↑ Summary
1 package Javascript::Menu;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 0 ▶use CGI;
Subroutine BEGIN: called CC=1 SCAR=2.6
6 use Tree::Numbered;
7  
8 use constant DEFAULT_STYLES => {caption => 'caption',
9 Mmenu => 'Mmenu',
10 Smenu => 'Smenu'};
11  
12 our $VERSION = '2.02';
13 our @ISA = qw(Tree::Numbered);
14  
15 # package stuff:
16 my $cgi = CGI->new; # Just for HTML shortcuts.
17  
18 # A default action generator. See the args passed to it:
19 my $default_action = sub {
20 my $self = shift;
21 my ($level, $unique) = @_;
22  
23 return '';
24 };
25  
26 # <new> constructs a new tree or node.
27 # Arguments: By name:
28 # value - the value to be stored in the node.
29 # action - a perl sub that is responsible for generating Javascript
30 # code to be executed on click. The sub will be called as
31 # a method ($self->generator) so you have access to the
32 # object data when you construct the action (optional).
33 # URL - a url to navigate to on click (optional).
34 # Returns: The tree object.
35  
36 sub new {
37 my $parent = shift;
38 my %args = @_;
39  
40 my $parent_serial;
41 my $class;
42
43 my %nargs = (Value => $args{value});
44 $nargs{URL} = $args{URL} if (exists $args{URL});
45 my $properties = $parent->SUPER::new(%nargs);
46  
47 my $action = $args{action};
48 if ($class = ref($parent)) {
49 $properties->{_Parent} = $parent->{_Serial};
50 $action = $parent->getAction unless (defined $action);
51 } else {
52 $class = $parent;
53 $properties->{_Parent} = 0;
54 }
55  
56 $properties->addField('Action'); # Does nothing if exists.
57 $properties->setAction((defined $action) ? $action : $default_action);
58 return $properties;
59 }
60  
61 # <convert> takes a Tree::Numbered and makes it a Javascript::Menu.
62 # Arguments: By name:
63 # tree - the tree to be converted to a menu.
64 # action - an action generator, as described in <new>.
65 # parent - (not for the user) sets the _Parent property.
66 # base_URL - a url that will be appended later by a relative one.
67 # Returns: the tree, modified and re-blessed as a Javascript::Menu.
68  
69 sub convert {
70 my $parent = shift;
71 my $class = (ref($parent) or $parent);
72  
73 my %args = @_;
74 my ($tree, $parent_num) = @args{'tree', 'parent'};
75 my $def_action = (exists $args{action}) ? $args{action} : $default_action;
76 $parent_num ||= 0;
77  
78 # Won't change existing setting of 'Action' and 'URL' if it's there.
79 $tree->addField('Action', $def_action);
80 $tree->addField('URL', $args{base_URL}) if (exists $args{'base_URL'});
81 $tree->{_Parent} = $parent_num;
82  
83 for (@{ $tree->{Items} }) {
84 my %inargs = (tree => $_, action => $def_action,
85 parent => $tree->getNumber);
86 $inargs{base_URL} = $args{base_URL} if (exists $args{'base_URL'});
87 $parent->convert(%inargs);
88 }
89 return bless $tree, $class;
90 }
91  
92 # <readDB> constructs a new Javascript::Menu from a table in a DB using
93 # Tree::Numbered::DB.
94 # Arguments: By name:
95 # source_name - table name.
96 # source - a DB handle to work with.
97 # action - an action generator, as described in <new>.
98 # cols - ref to a hash with mappings (see Tree::Numbered::DB).
99 # URL_col - shortcut to add the URL column to the cols.
100 # Returns: the tree, modified and re-blessed as a Javascript::Menu.
101  
102 sub readDB {
103 my $parent = shift;
104 my $class = (ref($parent) or $parent);
105 my %args = @_;
106  
107 my ($table, $dbh) = @args{'source_name', 'source'};
108 return undef unless ($table && $dbh);
109  
110 my $def_action = (exists $args{action}) ? $args{action} : $default_action;
111 my $cols = $args{cols};
112 $cols->{URL_col} = $args{URL_col} if ($args{URL_col});
113 # Default creation of Value is no longer used because we request a field.
114 $cols->{Value_col} ||= 'name';
115  
116 require Tree::Numbered::DB;
117 my @args = ($table, $dbh);
118 push @args, $cols if $cols;
119 #read -> revert -> convert: construct a DB tree, loose DBness, make Menu.
120 my $tree = Tree::Numbered::DB->read(@args);
121 $tree->revert;
122 return $class->convert(tree => $tree, action => $def_action);
123 }
124  
125  
126 # <getHTML> returns the HTML and Javascript that show the menu.
127 # Arguments: By name:
128 # styles - alternative set of styles. Default will be used if this isn't
129 # supplied or malformed.
130 # caption - a starting caption. Optional.
131 # no_ie - if true, no anchor tags will be added to captions.
132 # Returns: In list context returns a list of HTML lines to print. In scalar
133 # context returns a reference to same list.
134  
135 sub getHTML {
136 my $self = shift;
137 my %args = @_;
138  
139 my $caption = (exists $args{caption}) ? $args{caption} : $self->getValue;
140 $caption = $self->getFullCap($args{no_ie}, $caption);
141  
142 my $styles = $args{styles};
143 $styles = DEFAULT_STYLES unless(ref $styles eq 'HASH'
144 and $styles->{caption}
145 and $styles->{Mmenu}
146 and $styles->{Smenu});
147 my $unique = $self->getUniqueId;
148 my $action = $self->getAction()->($self, -1, $unique);
149 $action =~ s/([^;])\s*$/$1;/;
150 my @html; # return value.
151  
152 push @html, $cgi->div({-class => $styles->{caption},
153 -id => "caption_$unique",
154 -onMouseOver => "showMenu(1, 0, 'main_$unique', " .
155 "this, 'main_$unique')",
156 -onMouseOut => "outOfMenu()",
157 -onClick => "${action}hideMenus(0)"
158 }, $caption);
159 $self->buildTable(1, 0, $unique, \@html, $args{no_ie}, %$styles);
160  
161 return @html if (wantarray);
162 return \@html;
163 }
164  
165 # Helper for <getHTML> (actually does the real work).
166 # Recursively builds tables for each submenu and pushes the HTML into
167 # @html which is used as a stack.
168 # Arguments: $ismain - used to determine table style.
169 # $level - the submenu's level (main is 0),
170 # $unique - the menue's unique identifier. This is an argument so
171 # changing the uniquifing rule, will only be in <getHTML>.
172 # $id - The menu's HTML name, used for identification by JavaScript
173 # functions.
174 # $html - a reference to the stack.
175 # $no_ie - no anchor tags will be added around the caption.
176 # %styles - a hash of style names.
177 # Returns: Nothing. Modifies buffer directly.
178  
179 sub buildTable {
180 my $self = shift;
181 my $serial = $self->{_Serial};
182 my ($ismain, $level, $unique, $html, $no_ie, %styles) = @_;
183
184 my ($style, $name);
185 if ($ismain) {
186 $style = $styles{Mmenu};
187 $name = "main_$unique";
188 } else {
189 $style = $styles{Smenu};
190 $name = "s_${serial}_$unique"
191 }
192  
193 my $htmlstr = $cgi->start_table({-class => $style, -id => $name});
194 my $next_level = $level + 1;
195
196 $self->savePlace;
197 $self->reset;
198  
199 while (my $item = $self->nextNode) {
200 # '~n' is a placeholder
201 my $onMouse = "showMenu(0, ~1, 's_~2_$unique', this, 'main_$unique');";
202 my $onClick = $item->getAction()->($item, $level, $unique);
203  
204 if ($item->childCount) {
205 # '~1' = _next_ menu's level. '~2' = branch serial.
206 $onMouse =~ s/~2/$item->{_Serial}/;
207 $onMouse =~ s/~1/$next_level/e;
208  
209 $item->buildTable(0, $next_level, $unique, $html, $no_ie, %styles);
210 } else {$onMouse = "stopTimer();hideMenus($next_level);";}
211  
212 my $caption = $item->getFullCap($no_ie);
213 $onClick =~ s/([^;])\s*$/$1;/;
214 $htmlstr .= $cgi->Tr($cgi->td({-onMouseOver => $onMouse,
215 -onClick => "${onClick}hideMenus(0)",
216 -onMouseOut => 'outOfMenu()'},
217 $caption ));
218 }
219 $self->restorePlace;
220 $htmlstr .= $cgi->end_table;
221 push @$html, $htmlstr;
222 }
223  
224 sub getFullCap {
225 my ($item, $no_ie, $caption) = @_;
226 my $value = $caption || $item->getValue;
227 my $href = $item->getURL || '"javascript:void(0)"';
228 if ($no_ie && !$item->getURL) { return $value; }
229 else { return "<a href=$href>$value</a>";}
230 }
231  
232 # <getUniqueId> returns the html suffix id of the menu.
233 # Arguments: None.
234 # Returns: A unique suffix for HTML names which includes the lucky number and
235 # the root node's serial number.
236  
237 sub getUniqueId {
238 my $self = shift;
239 return "$self->{_LuckyNumber}__$self->{_Serial}";
240 }
241  
242 # <setAction> sets the action on an item. if no action is given, the default
243 # do-nothing action is used.
244 # Arguments: $action - an action, or nothing - implies default.
245 # Returns: Nothing.
246  
247 sub setAction {
248 my $self = shift;
249 my $action = shift;
250
251 $action ||= $default_action;
252 $self->setField('Action', $action);
253 }
254  
255 # <set/getURL> are here to make sure nobody dies when they're called even if
256 # the field doesn't exist.
257  
258 sub getURL {
259 my $self = shift;
260 return $self->getField('URL');
261 }
262  
263 sub setURL {
264 my $self = shift;
265 return $self->setField('URL', @_);
266 }
267  
268 #**************************************************************
269 # Class methods for generating required JavaScript and CSS.
270  
271 # <baseCSS> returns the base style to be used with this module - some
272 # definitions are esential, such as visibility. Note that using just the base
273 # style will yield a transparent and ugly menu.
274 # Arguments: None.
275 # Returns: a hash containing for each required element (caption, Mmenu,
276 # Smenu) another hash with property - value pairs. modify at will,
277 # then print map {"$_: $hash->{$_};"} keys $hash; where $hash is the
278 # properties hash for an element.
279  
280 sub baseCSS {
281 my $self = shift; # Never used - class method.
282 return {caption => {},
283 Mmenu => {position => 'absolute', top => '1', left => '1',
284 'z-index' => 10, visibility => 'hidden'},
285 Smenu => {position => 'absolute', top => '1', left => '1',
286 'z-index' => 10, visibility => 'hidden'}
287 };
288 }
289  
290 # <reasonableCSS> does the same thing as <baseCSS> only with more properties.
291 # Arguments: None.
292 # Returns: See <baseCSS>.
293  
294 sub reasonableCSS {
295 my $self = shift; # Never used - class method.
296 return {caption => {_border => 'solid 1px black',
297 'text-decoration' => 'none',
298 background => 'blue', width => '10%',
299 color => 'white', 'font-weight' => 'bold'},
300 Mmenu => {position => 'absolute', top => '1', left => '1',
301 background => 'cyan', 'z-index' => 10,
302 visibility => 'hidden', 'text-decoration' => 'none'},
303 Smenu => {position => 'absolute', top => '1', left => '1',
304 background => 'cyan', 'z-index' => 10,
305 visibility => 'hidden', 'text-decoration' => 'none'},
306 _Mmenu => {background => 'blue', 'z-index' => 10,
307 color=>'white'},
308 _Smenu => {background => 'blue', 'z-index' => 10,
309 color => 'white'}
310  
311 };
312 }
313  
314 # <buildCSS> turns the datastructure provided by the previous two subs into
315 # valid CSS. Hash keys are converted into classes, and hash keys preceded
316 # with an underscore are converted into the "class td:hover" syntax.
317 # Arguments: $raw_css - The datastructure described in <baseCSS>.
318 # $no_ie - no anchor style will be added to the hover style if true.
319 # $no_autolink - prevents generation af a:link if true.
320 # Returns: A string containing the CSS.
321  
322 sub buildCSS {
323 my $self = shift; # Never used - class method.
324 my ($raw_css, $no_ie, $no_autolink) = @_;
325 my $css = '';
326 my $ie_bloat = ($no_ie) ? '' : ' a';
327
328 for my $class (keys %$raw_css) {
329 my %props = %{ $raw_css->{$class} };
330 my $hover = ($class =~ s/^_//) ? 1 : 0;
331  
332 $css .= ".$class ";
333 $css .= "td${ie_bloat}:hover" if ($hover);
334 $css .= " {\n";
335 $css .= join "\n",
336 map {my $under=$_; s/^_//; "\t$_: $props{$under};"}
337 keys %props;
338 $css .= "\n}\n\n";
339  
340 # Generate link style for IE6 support...
341 unless ($hover || $no_ie || $no_autolink) {
342 my %hprops = %props;
343 delete @hprops{'position', 'top', 'left', 'right', 'bottom',
344 'visibility', 'z-index'};
345 %hprops = map {$_=>$hprops{$_}} grep /^[^_]/, keys %hprops;
346 $css .= ".$class a:link, .$class a:visited ";
347 $css .= " {\n";
348 $css .= join "\n", map {"\t$_: $hprops{$_};"} keys %hprops;
349 $css .= "\n}\n\n";
350 }
351 }
352 return $css;
353 }
354  
355 # <baseJS> generates required Javascript code for use with this module.
356 # Arguments: $rtl - if right-to-left menu.
357 # $menu_delay - option to manually set microseconds of delay
358 # before a menu closes. Default is 500ms.
359 # Returns: Only the code. You can put this inside a <script> tag or print
360 # to a .js file.
361  
362 sub baseJS {
363 my $self = shift; # Never used.
364 my $rtl = shift;
365 my $menu_delay = shift || 500;
366  
367 my ($place, $right_anchor, $right_anchor_mo);
368 if ($rtl) {
369 $place = '- smenu.offsetWidth - 4';
370 $right_anchor = '(smenu.offsetWidth - caller.offsetWidth)';
371 } else {
372 $place = '+ caller.offsetWidth + 4';
373 $right_anchor = '0';
374 }
375 return <<EndJS;
376 //functions for a dynamic tree-menu.
377 //Main menu (child of the BOX) is in level 0.
378 //Every menu passes to showMenu the number of the *next* level.
379 // (this is done by Perl, baby...)
380  
381 var openMenus = new Array(); //A stack of open menus.
382 var collapseMenusTimer; //Next two vars used for closing all menus.
383 var isCollapsing = false;
384  
385 function getCrossBrowser(name) {
386 return document.getElementById(name); //Now it works on all of them...
387 }
388  
389 function showMenu (isMain, level, name, caller, coordSpaceId) {
390 var smenu = getCrossBrowser(name);
391 var coordSpace = getCrossBrowser(coordSpaceId);
392  
393 if (isCollapsing) {
394 clearTimeout(collapseMenusTimer);
395 isCollapsing = false;
396 }
397
398 //Now that that is out of the way...
399 hideMenus(level);
400 smenu.style.visibility = "visible";
401  
402 if (isMain) {
403 smenu.style.left = findPosX(caller, coordSpace) -
404 $right_anchor + "px";
405 smenu.style.top = findPosY(caller, coordSpace) +
406 caller.offsetHeight + "px";
407 } else {
408 smenu.style.top = findPosY(caller, coordSpace) + "px";
409 smenu.style.left = findPosX(caller, coordSpace) $place + "px";
410 }
411 openMenus[openMenus.length] = smenu;
412 }
413  
414 function hideMenus(level) {
415 for (i = openMenus.length - 1; i >= level; i--) {
416 openMenus[i].style.visibility = "hidden";
417 openMenus = openMenus.slice(0, i);
418 }
419 }
420  
421 function outOfMenu() {
422 if (isCollapsing) {
423 clearTimeout(collapseMenusTimer);
424 isCollapsing = false;
425 }
426  
427 collapseMenusTimer = setTimeout("hideMenus(0)", $menu_delay);
428 isCollapsing = true;
429 }
430  
431 function stopTimer() {
432 if (isCollapsing) {
433 clearTimeout(collapseMenusTimer);
434 isCollapsing = false;
435 }
436 }
437  
438 //Two functions for finding absolute position of an element on the page:
439 //coordSpace is the item whose parent determines the coordinate space.
440  
441 function findPosX(obj, coordSpace) {
442 var curleft = 0;
443 if (obj.offsetParent)
444 {
445 while(obj.offsetParent)
446 {
447 curleft += obj.offsetLeft
448 if (obj.offsetParent == coordSpace.offsetParent)
449 break;
450 obj = obj.offsetParent;
451 }
452 }
453 else if (obj.x)
454 curleft += obj.x;
455 return curleft;
456 }
457  
458 function findPosY(obj, coordSpace) {
459 var curtop = 0;
460 if (obj.offsetParent)
461 {
462 while (obj.offsetParent)
463 {
464 curtop += obj.offsetTop
465 if (obj.offsetParent == coordSpace.offsetParent)
466 break;
467 obj = obj.offsetParent;
468 }
469 }
470 else if (obj.y)
471 curtop += obj.y;
472 return curtop;
473 }
474  
475 EndJS
476  
477 }
478  
479 1;
480  
481 =head1 NAME
482  
483 Javascript::Menu - a NumberedTree that generates HTML and Javascript code for
484 a menu.
485  
486 =head1 SYNOPSIS
487  
488 use Javascript::Menu;
489  
490 # Give it something to do (example changes the menu's caption):
491  
492 my $action = sub {
493 my $self = shift;
494 my ($level, $unique) = @_;
495
496 my $value = $self->getValue;
497 return "getElementById(caption_$unique).innerHTML='$value'";
498 };
499  
500  
501 # Build the tree:
502  
503 my $menu = Javascript::Menu->convert(tree => $otherTree, action => $action);
504
505 my $menu = Javascript::Menu->readDB(source_name => $table, source => $dbh,
506 action => $action);
507
508 my $menu = Javascript::Menu->new(value => 'Please select a parrot',
509 action => $action);
510  
511 my $blue = $menu->append(value => 'Norwegian Blue');
512 $blue->append(value => 'Pushing up the daisies');
513 $menu->append(value => 'A Snail');
514  
515 # Or maybe you just want a navigational menu?
516  
517 my $menu = Javascript::Menu->new(value => 'Please select a prime minister');
518 $menu->append(value => 'Ariel Sharon',
519 URL => 'www.corruption.org/ariel_sharon.htm');
520  
521 $menu->append(value => 'Benjamin Netanyahu',
522 URL => 'www.corruption.org/bibi.htm');
523  
524 $menu->append(value => 'Shaul Mofaz', URL => 'www.martial_law.org');
525  
526
527 # Print it out as a right-to-left menu:
528  
529 my $css = $menu->buildCSS($menu->reasonableCSS);
530 print $cgi->start_html(-script => $menu->baseJS('rtl'),
531 -style => $css); #CSS plays an important role.
532 print $tree->getHTML;
533
534 =head1 DESCRIPTION
535  
536 Javascript::Menu is an object that helps in creating the HTML, Javascript, and some of the CSS required for a table-based menu. There are a few other modules that deal with menus, But as I browsed through them, I found that none of them exactly fitted my needs. So I designed this module, with the following goals in mind:
537  
538 =over 4
539  
540 =item Flexibility
541  
542 The main feature of this module is the ability to supply all nodes or any specific node with a subroutine that is activated in time of the code generation to help decide what the item will do when it is clicked. This allows customisation far beyond associating a link with every item. Multy-level selection menus become very easy to do (and this is, in fact, what I needed when I started writing this).
543  
544 =item I18n
545  
546 Working with i18n (internationalization) can be a big headache. Working with Hebrew (or Arabic) forces you not only to change your charachters, but also to change your direction of writing. I incorporated into this module the ability to produce right-to-left menus and tested it using a legacy ASCII-based encoding (iso-8859-8).
547  
548 =item Object Hierarchy
549  
550 I designed the module to work with two other modules of mine, Tree::Numbered and Tree::Numbered::DB, which simplify the task of building the menu and allow for construction of a menu from database information.
551  
552 =back
553  
554 The current version adds support for highlighting the item that's hovered over. You'll find that having made some preliminary steps, like tweaking the CSS to look the way you like it to, the rest is fairly easy.
555  
556 So, how do we use this module?
557  
558 =head2 What should you expect to see?
559  
560 The generated menu will be visible as a div that shows the caption line for the menu. As you hover with the mouse over the caption, the main menu will appear under the caption. Hovering over any item with childs will open a sub-menu either to the right or left of the main menu, depending on the direction you chose for the menu. Clicking on any item will hide all menus, leaving only the caption, and fire the action you assigned to the item.
561  
562 =head2 Some naming rules.
563  
564 The following rules decide on the names (id attributes) of generated HTML elements:
565  
566 Every generated menu recieves a unique suffix. Let's call this $unique. this is added to the name of every part of the same menu.
567  
568 Every node has a number, unlike any other node on the same tree. Let's call that $number. For reasons why, see the documentation for NumberedTree or just read on.
569  
570 The caption line is called caption_$unique, The main menu is called main_$unique, Every sub menu is called s_$number_$unique.
571  
572 =head2 CSS classes
573  
574 Every part of the menu is associated with a class name, that defines its style (the class attribute). By default the caption's class is 'caption', the main menu's class is 'Mmenu' and sub menus get the class 'Smenu'. If this does not suit you, you are welcome to create the menu with different style associations (see B<getHTML>).
575  
576 =head2 Setting up the supporting code
577  
578 Javascript::Menu requires some supporting code to work. First, as implied by its name, certain Javascript functions must be available. This is, however, the easiest thing to set up. The code is returned in its entirety, as one giant multiline string, by the class method I<baseJS> (see below). use this in your head tag, or do like me and dump this to a .js file.
579  
580 The second thing that needs to be set up is the CSS. except for a few settings, you are pretty free to style the menu as you see fit, but that also means some work for you. The class method I<baseCSS> returns only the basic settings, those you can't change. You must tweak it some more to look good. The class method I<reasonableCSS> returns some example CSS that doesn't look too bad. Again, you should tweak this as described below under I<buildCSS>.
581  
582 Finally, I included a convenience class method called I<buildCSS> that stringifies the data structure supplied by these two functions into valid CSS and also generates extra CSS to deal with the special oddities of Internet Explorer 6.
583  
584 =head2 Building the tree
585  
586 To get the tree that represents the structure of the menu, you have 3 ways:
587  
588 =over 4
589  
590 =item The hard way: Javascript::Menu->new
591  
592 This builds the root node, with your desired value and action, URL or both (which will be the default for all children of this node). You add nodes with $tree->I<append>, and descend the hierarchy using methods found in the parent class - Tree::Numbered. For each element you supply the value (what is shown on the screen) and possibly an action.
593  
594 =item The easier way: Javascript::Menu->convert
595  
596 This just takes an existing Tree::Numbered and blesses it as a Menu, adding an action to each node. This is easier if you already have the data structure for something else, and you want to make a menu out of it.
597  
598 =item A nice shortcut: Javascript::Menu->readDB
599  
600 If you have the module Tree::Numbered::DB (another one of mine) and you use it to store trees in a database, this method allows you to read such table directly and convert it to a menu. This is extremely useful, trust me :)
601  
602 =back
603  
604 =head2 But what are these actions and how do I generate them?
605  
606 An action is basically a piece of Javascript code that is executed when the user clicks on an item. It is added to the onClick attribute of the item. However, actions in this module are not plain strings. Instead, an action is a subroutine reference that is called when the item's HTML code is being processed. It does what it does, then returns a string containing the Javascript code. In order for this sub to be able to do anything useful, it gets 3 arguments passed to it:
607  
608 =over 4
609  
610 =item 1
611  
612 A reference to the node being processed, so you can get information on the node via object methods.
613  
614 =item 2
615  
616 The item's level in the hierarchy - the main menu is at level 0, the caption is at level -1.
617  
618 =item 3
619  
620 The menu's unique suffix.
621  
622 =back
623  
624 To make an item do nothing except for showing its submenu, use $item->I<setAction>
625  
626 B<I18n alert!> What this all means is that you supply some of the strings the module will be working with. This means you could, by mistake, send strings that are mixed utf8 (perl's internal encoding) and your encoding. This might break things, so if something breaks, see that your strings are in one encoding. A bitch, eh? That's the way it is when you're not in the USA or Britain.
627  
628 =head2 But I don't need all this stuff! I just want a navigational menu!
629  
630 Cool. Just set the URL property of an object either in the constructor call or using I<setURL>. Menu items will be created with that URL. You can also combine a URL with an action.
631  
632 =head2 Printing the HTML
633  
634 Now all you have to do is $tree->getHTML. this will return an array so you can shift out the caption and locate it inside some div while the rest of the menu is located outside, avoiding width constraints. You can also push other stuff inside and create a widget for your script.
635  
636 =head1 METHODS
637  
638 This section only describes methods that are not the same as in Tree::Numbered. Obligatory arguments are marked.
639  
640 =head2 Constructors
641  
642 There are three of them:
643  
644 =over 4
645  
646 =item new (I<value> => $value, action => $action, URL => $url)
647  
648 Creates a new tree with one root element, whose text is specified by the value argument. If an action is not supplied, the package's default do-nothig action will be used. You'll have to add nodes manually via the I<append> method.
649  
650 If a URL is supplied, the node will be an anchor reffering to that URL.
651  
652 =item convert (I<tree> => $tree, action => $action, base_URL => $url)
653  
654 Converts a tree (given in the I<tree> argument) into an instance of Javascript::Menu. You will lose the original tree of course, so if you still need it, first use $tree->clone (see Tree::Numbered).
655  
656 Giving a value to base_URL will copy that value to the URL field of every node in the tree. you can add to this using I<deepProcess>.
657  
658 As in new, if action is not specified, one will be created for you.
659  
660 =item readDB (I<source_name> => $table, I<source> => $dbh, cols => $cols, action => $action, URL_col => $urlcol);
661  
662 Creates a new menu from a table that contains tree data as specified in Tree::Numbered::DB. Arguments are the same as to I<new>, except for the required source_name, which specifies the name of the table to be read, and source, which is a DBI database handle.
663  
664 The cols argument allows you to supply field mappings for the tree (see Tree::Numberd::DB). URL_col is a shortcut for giving a mapping to a collumn containing the URLs of nodes (if that's what you need). If you provide this argument, it will override any collision in the $cols hashref.
665  
666 =back
667  
668 =head2 append (value => I<$value>, action => $action, URL => $url)
669  
670 Adds a new child with the value (caption) $value. An action or a URL are optional, as described in I<new>. If one of those is not given, the value is taken from its parent (if its parent has one).
671  
672 =head2 getHTML (styles => $styles, caption => 'altCaption', no_ie => true)
673  
674 This method returns the HTML for a menu whose caption is the node the method was invoked on. The menu's caption will be the root element's value unless the caption argument is given.
675  
676 the optional styles argument allows you to change default style names described above. This should be a hash reference, with a key for each style, specifying the new name. Like:
677  
678 $styles = { caption => 'mycap', Mmenu => 'myM', Smenu => 'myS' };
679  
680 unless you specify the option no_ie as true, items of your menu will be wrapped with anchor tags so the :hover CSS pseudo-class will be aplicable to them even on Internet Explorer 6. Any node that has a URL will become an anchor even if no_ie => true.
681  
682 =head2 Accessors
683  
684 Javascript::Menu adds to the methods of its base class the following accessors:
685  
686 =over 4
687  
688 =item getUniqueId
689  
690 Returns the unique Id that the menu will recieve when built with this node as root.
691  
692 =item getAction / setAction ($action)
693  
694 gets and sets the item's action. If no action is given to setAction, the default do-nothing action is used.
695  
696 =item getURL / setURL ($url)
697  
698 gets and sets the item's URL.
699  
700 =back
701  
702 =head2 Class methods
703  
704 The following class methods help you generate supporting code for your menus:
705  
706 =over 4
707  
708 =item baseJS ($rtl, $menu_delay)
709  
710 Returns the basic Javascript code for use with this module. If the optional $rtl is true, the code will generate right-to-left menus. $menu_delay allows you to set the time (in miliseconds) that a submenu stays open when the mouse is not hovering above it. The default is 500ms (0.5 seconds).
711  
712 =item baseCSS
713  
714 Returns the minimum required CSS for the menu to work properly, as a reference to the data structure described below in I<buildCSS>. It is up to you to add properties to this structure to make your menu look good.
715  
716 =item reasonableCSS
717  
718 Returns the same data structure as in baseCSS, only with more properties. Using the properties provided by this function will result in a black-bordered, blue caption box with white text, and cyan menus with black text. Again, you can tweak this to your satisfaction.
719  
720 =item buildCSS ($css, $no_ie, $no_autolink)
721  
722 Takes a data structure and returns a string with valid CSS you can incorporate into your document.
723  
724 The data structure is as follows:
725  
726 A main hash with one key for each element of the menu (caption, main menu, sub menus). The value for each key is again a hash with CSS property - value pairs, like top => 1, left => 1 etc. If a key is preceded by an underscore, it is converted into the :hover definition for the class of that name (this should be a name given to one of the other classes).
727  
728 Unless $no_ie is true, buildCSS will generate IE6 compatible style for hover classes. This will also generate CSS for links inside the menu. To inhibit that, set $no_autolink to true.
729  
730 If you know you'll have anchors in your menu and you don't want them to duplicate some property found in the CSS for the element they are contained in, prefix that property with an underscore. See how it's done in I<reasonableCSS> and try it without the leading underscore to see the difference (a border appears inside the caption and around it too).
731  
732 =back
733  
734 =head1 METHOD SUMMARY (NEW + INHERITED)
735  
736 The following is a categorized list of all available meyhods, for quick reference. Methods that do not appear in the source of this module are marked:
737  
738 =over 4
739  
740 =item Object lifecycle:
741  
742 new, readDB, *delete, *append.
743  
744 =item Iterating and managing children:
745  
746 *nextNode, *reset, *savePlace, *restorePlace, *childCount, *getSubTree, *follow
747  
748 =item Generating code:
749  
750 baseCSS, reasonableCSS, buildCSS, baseJS, getHTML
751  
752 =item Fields:
753  
754 *addField, *removeField, *setField, *setFields, *getField, *getFields, *hasField.
755  
756 =back
757  
758  
759 =head1 BROWSER COMPATIBILITY
760  
761 Tested on IE6, IE5 and Mozilla 1.4 and worked. On Konqueror it's about 70% OK, and I'm working on it. If you test it on other browsers, please let me know what is the result.
762  
763 =head1 EXAMPLES
764  
765 I included two examples, both create a right to left menu:
766  
767 =over 4
768  
769 =item examples/nav_ex.pl
770  
771 Creates a navigational menu that links to the white house site. Demonstrates the use of another tree to build a menu on, and the use of deepProcess to asign URLs.
772  
773 =item examples/action_ex.pl
774  
775 Shows how to create an action-based menu. The example changes the menu's caption whenever an item is clicked.
776  
777 =back
778  
779 =head1 BUGS
780  
781 Please report through CPAN:
782 E<lt>http://rt.cpan.org/NoAuth/Bugs.html?Dist=Tree-Numbered-DBE<gt>
783 or send mail to E<lt>bug-Tree-Numbered-DB#rt.cpan.orgE<gt>
784  
785 =head1 SEE ALSO
786  
787 Tree::Numbered, Tree::Numbered::DB.
788  
789 =head1 AUTHOR
790  
791 Yosef Meller, E<lt>mellerf@netvision.net.ilE<gt>
792  
793 =head1 CREDITS
794  
795 Louis Campos de Carvalho raised the subject of support for Internet Explorer 5 and tested the patch.
796  
797 =head1 COPYRIGHT AND LICENSE
798  
799 Copyright 2003 by Yosef Meller
800  
801 This library is free software; you can redistribute it and/or modify
802 it under the same terms as Perl itself.
803  
804 =cut
« Tree/Numbered.pm ↑ Summary