Merge branch 'b-3.6.1' of ../kivitendo-erp_20220811
[kivitendo-erp.git] / SL / Presenter / JavascriptMenu.pm
1 package SL::Presenter::JavascriptMenu;
2
3 use strict;
4 use SL::Presenter::EscapedText qw(escape is_escaped);
5 use SL::Presenter::Tag qw( html_tag link_tag);
6 use SL::Locale::String qw(t8);
7 use SL::System::ResourceCache;
8
9 use List::Util qw(max);
10
11 use Exporter qw(import);
12 our @EXPORT_OK = qw(render_menu);
13
14 sub render_menu {
15   my ($menu) = @_;
16
17   html_tag('div', '', id => 'main_menu_div') .
18   html_tag('ul', render_children($menu, 100, $menu->{tree}),
19     id    => "main_menu_model",
20     style => 'display:none',
21   );
22 }
23
24 sub render_node {
25   my ($menu, $node, $id) = @_;
26   return '' if !$node->{visible};
27
28   my $icon = get_icon($node->{icon});
29   my $link = $menu->href_for_node($node) || '#';
30   my $name = $menu->name_for_node($node);
31
32   html_tag('li',
33       link_tag($link, $name, target => $node->{target})
34     . html_tag('ul', render_children($menu, $id * 100, $node->{children} // []),
35         width => max_width($node)
36       ),
37     id        => $id,
38     (itemIcon => $icon)x!!$icon,
39   )
40 }
41
42 sub render_children {
43   my ($menu, $id, $children) = @_;
44   my $sub_id = 1;
45
46   join '', map {
47     render_node($menu, $_, 100 * $id + $sub_id++)
48   } @$children
49 }
50
51 sub max_width {
52   11 * ( max( map { length $::locale->text($_->{name}) } @{ $_[0]{children} || [] } ) // 1 )
53 }
54
55 sub get_icon {
56   my $name = $_[0];
57
58   return undef if !defined $name;
59
60   my $simg = "image/icons/svg/$name.svg";
61   my $pimg = "image/icons/16x16/$name.png";
62
63     SL::System::ResourceCache->get($simg) ? $simg
64   : SL::System::ResourceCache->get($pimg) ? $pimg
65   :                                         ();
66 }
67
68 1;
69
70