cc0a6ed015772985ad159bf4a75f6a30bf29de91
[kivitendo-erp.git] / SL / Template / Plugin / L.pm
1 package SL::Template::Plugin::L;
2
3 use base qw( Template::Plugin );
4 use Template::Plugin;
5 use List::MoreUtils qw(apply);
6
7 use strict;
8
9 { # This will give you an id for identifying html tags and such.
10   # It's guaranteed to be unique unless you exceed 10 mio calls per request.
11   # Do not use these id's to store information across requests.
12 my $_id_sequence = int rand 1e7;
13 sub _tag_id {
14   return $_id_sequence = ($_id_sequence + 1) % 1e7;
15 }
16 }
17
18 sub _H {
19   my $string = shift;
20   return $::locale->quote_special_chars('HTML', $string);
21 }
22
23 sub _hashify {
24   return (@_ && (ref($_[0]) eq 'HASH')) ? %{ $_[0] } : @_;
25 }
26
27 sub new {
28   my $class   = shift;
29   my $context = shift;
30
31   return bless { }, $class;
32 }
33
34 sub name_to_id {
35   my $self =  shift;
36   my $name =  shift;
37
38   $name    =~ s/[^\w_]/_/g;
39   $name    =~ s/_+/_/g;
40
41   return $name;
42 }
43
44 sub attributes {
45   my $self    = shift;
46   my %options = _hashify(@_);
47
48   my @result = ();
49   while (my ($name, $value) = each %options) {
50     next unless $name;
51     $value = '' if !defined($value);
52     push @result, _H($name) . '="' . _H($value) . '"';
53   }
54
55   return @result ? ' ' . join(' ', @result) : '';
56 }
57
58 sub html_tag {
59   my $self       = shift;
60   my $tag        = shift;
61   my $content    = shift;
62   my $attributes = $self->attributes(@_);
63
64   return "<${tag}${attributes}/>" unless defined($content);
65   return "<${tag}${attributes}>${content}</${tag}>";
66 }
67
68 sub select_tag {
69   my $self            = shift;
70   my $name            = shift;
71   my $options_str     = shift;
72   my %attributes      = _hashify(@_);
73
74   $attributes{id}   ||= $self->name_to_id($name);
75   $options_str        = $self->options_for_select($options_str) if ref $options_str;
76
77   return $self->html_tag('select', $options_str, %attributes, name => $name);
78 }
79
80 sub textarea_tag {
81   my $self            = shift;
82   my $name            = shift;
83   my $content         = shift;
84   my %attributes      = _hashify(@_);
85
86   $attributes{id}   ||= $self->name_to_id($name);
87   $content            = $content ? _H($content) : '';
88
89   return $self->html_tag('textarea', $content, %attributes, name => $name);
90 }
91
92 sub checkbox_tag {
93   my $self             = shift;
94   my $name             = shift;
95   my %attributes       = _hashify(@_);
96
97   $attributes{id}    ||= $self->name_to_id($name);
98   $attributes{value}   = 1 unless defined $attributes{value};
99   my $label            = delete $attributes{label};
100
101   if ($attributes{checked}) {
102     $attributes{checked} = 'checked';
103   } else {
104     delete $attributes{checked};
105   }
106
107   my $code  = $self->html_tag('input', undef,  %attributes, name => $name, type => 'checkbox');
108   $code    .= $self->html_tag('label', $label, for => $attributes{id}) if $label;
109
110   return $code;
111 }
112
113 sub radio_button_tag {
114   my $self             = shift;
115   my $name             = shift;
116   my %attributes       = _hashify(@_);
117
118   $attributes{value}   = 1 unless defined $attributes{value};
119   $attributes{id}    ||= $self->name_to_id($name . "_" . $attributes{value});
120   my $label            = delete $attributes{label};
121
122   if ($attributes{checked}) {
123     $attributes{checked} = 'checked';
124   } else {
125     delete $attributes{checked};
126   }
127
128   my $code  = $self->html_tag('input', undef,  %attributes, name => $name, type => 'radio');
129   $code    .= $self->html_tag('label', $label, for => $attributes{id}) if $label;
130
131   return $code;
132 }
133
134 sub input_tag {
135   my $self            = shift;
136   my $name            = shift;
137   my $value           = shift;
138   my %attributes      = _hashify(@_);
139
140   $attributes{id}   ||= $self->name_to_id($name);
141   $attributes{type} ||= 'text';
142
143   return $self->html_tag('input', undef, %attributes, name => $name, value => $value);
144 }
145
146 sub hidden_tag {
147   return shift->input_tag(@_, type => 'hidden');
148 }
149
150 sub submit_tag {
151   my $self             = shift;
152   my $name             = shift;
153   my $value            = shift;
154   my %attributes       = _hashify(@_);
155
156   $attributes{onclick} = "if (confirm('" . delete($attributes{confirm}) . "')) return true; else return false;" if $attributes{confirm};
157
158   return $self->input_tag($name, $value, %attributes, type => 'submit', class => 'submit');
159 }
160
161 sub options_for_select {
162   my $self            = shift;
163   my $collection      = shift;
164   my %options         = _hashify(@_);
165
166   my $value_key       = $options{value} || 'id';
167   my $title_key       = $options{title} || $value_key;
168
169   my $value_sub       = $options{value_sub};
170   my $title_sub       = $options{title_sub};
171
172   my $value_title_sub = $options{value_title_sub};
173
174   my $access = sub {
175     my ($element, $index, $key, $sub) = @_;
176     my $ref = ref $element;
177     return  $sub            ? $sub->($element)
178          : !$ref            ? $element
179          :  $ref eq 'ARRAY' ? $element->[$index]
180          :  $ref eq 'HASH'  ? $element->{$key}
181          :                    $element->$key;
182   };
183
184   my @elements = ();
185   push @elements, [ undef, $options{empty_title} || '' ] if $options{with_empty};
186   push @elements, map [
187     $value_title_sub ? $value_title_sub->($_) : (
188       $access->($_, 0, $value_key, $value_sub),
189       $access->($_, 1, $title_key, $title_sub),
190     )
191   ], @{ $collection } if $collection && ref $collection eq 'ARRAY';
192
193   my $code = '';
194   foreach my $result (@elements) {
195     my %attributes = ( value => $result->[0] );
196     $attributes{selected} = 'selected' if $options{default} && ($options{default} eq ($result->[0] || ''));
197
198     $code .= $self->html_tag('option', _H($result->[1]), %attributes);
199   }
200
201   return $code;
202 }
203
204 sub javascript {
205   my ($self, $data) = @_;
206   return $self->html_tag('script', $data, type => 'text/javascript');
207 }
208
209 sub date_tag {
210   my ($self, $name, $value, @slurp) = @_;
211   my %params   = _hashify(@slurp);
212   my $name_e   = _H($name);
213   my $seq      = _tag_id();
214   my $datefmt  = apply {
215     s/d+/\%d/gi;
216     s/m+/\%m/gi;
217     s/y+/\%Y/gi;
218   } $::myconfig{"dateformat"};
219
220   $params{cal_align} ||= 'BR';
221
222   $self->input_tag($name, $value,
223     id     => $name_e,
224     size   => 11,
225     title  => _H($::myconfig{dateformat}),
226     onBlur => 'check_right_date_format(this)',
227     %params,
228   ) . ((!$params{no_cal}) ?
229   $self->html_tag('img', undef,
230     src    => 'image/calendar.png',
231     id     => "trigger$seq",
232     title  => _H($::myconfig{dateformat}),
233     %params,
234   ) .
235   $self->javascript(
236     "Calendar.setup({ inputField: '$name_e', ifFormat: '$datefmt', align: '$params{cal_align}', button: 'trigger$seq'  });"
237   ) : '');
238
239 sub javascript_tag {
240   my $self = shift;
241   my $code = '';
242
243   foreach my $file (@_) {
244     $file .= '.js'        unless $file =~ m/\.js$/;
245     $file  = "js/${file}" unless $file =~ m|/|;
246
247     $code .= qq|<script type="text/javascript" src="${file}"></script>|;
248   }
249
250   return $code;
251 }
252
253 1;
254
255 __END__
256
257 =head1 NAME
258
259 SL::Templates::Plugin::L -- Layouting / tag generation
260
261 =head1 SYNOPSIS
262
263 Usage from a template:
264
265   [% USE L %]
266
267   [% L.select_tag('direction', [ [ 'left', 'To the left' ], [ 'right', 'To the right' ] ]) %]
268
269   [% L.select_tag('direction', L.options_for_select([ { direction => 'left',  display => 'To the left'  },
270                                                       { direction => 'right', display => 'To the right' } ],
271                                                     value => 'direction', title => 'display', default => 'right')) %]
272
273 =head1 DESCRIPTION
274
275 A module modeled a bit after Rails' ActionView helpers. Several small
276 functions that create HTML tags from various kinds of data sources.
277
278 =head1 FUNCTIONS
279
280 =head2 LOW-LEVEL FUNCTIONS
281
282 =over 4
283
284 =item C<name_to_id $name>
285
286 Converts a name to a HTML id by replacing various characters.
287
288 =item C<attributes %items>
289
290 Creates a string from all elements in C<%items> suitable for usage as
291 HTML tag attributes. Keys and values are HTML escaped even though keys
292 must not contain non-ASCII characters for browsers to accept them.
293
294 =item C<html_tag $tag_name, $content_string, %attributes>
295
296 Creates an opening and closing HTML tag for C<$tag_name> and puts
297 C<$content_string> between the two. If C<$content_string> is undefined
298 or empty then only a E<lt>tag/E<gt> tag will be created. Attributes
299 are key/value pairs added to the opening tag.
300
301 C<$content_string> is not HTML escaped.
302
303 =back
304
305 =head2 HIGH-LEVEL FUNCTIONS
306
307 =over 4
308
309 =item C<select_tag $name, $options_string, %attributes>
310
311 Creates a HTML 'select' tag named C<$name> with the contents
312 C<$options_string> and with arbitrary HTML attributes from
313 C<%attributes>. The tag's C<id> defaults to C<name_to_id($name)>.
314
315 The C<$options_string> is usually created by the
316 L</options_for_select> function. If C<$options_string> is an array
317 reference then it will be passed to L</options_for_select>
318 automatically.
319
320 =item C<input_tag $name, $value, %attributes>
321
322 Creates a HTML 'input type=text' tag named C<$name> with the value
323 C<$value> and with arbitrary HTML attributes from C<%attributes>. The
324 tag's C<id> defaults to C<name_to_id($name)>.
325
326 =item C<hidden_tag $name, $value, %attributes>
327
328 Creates a HTML 'input type=hidden' tag named C<$name> with the value
329 C<$value> and with arbitrary HTML attributes from C<%attributes>. The
330 tag's C<id> defaults to C<name_to_id($name)>.
331
332 =item C<submit_tag $name, $value, %attributes>
333
334 Creates a HTML 'input type=submit class=submit' tag named C<$name> with the
335 value C<$value> and with arbitrary HTML attributes from C<%attributes>. The
336 tag's C<id> defaults to C<name_to_id($name)>.
337
338 If C<$attributes{confirm}> is set then a JavaScript popup dialog will
339 be added via the C<onclick> handler asking the question given with
340 C<$attributes{confirm}>. If request is only submitted if the user
341 clicks the dialog's ok/yes button.
342
343 =item C<textarea_tag $name, $value, %attributes>
344
345 Creates a HTML 'textarea' tag named C<$name> with the content
346 C<$value> and with arbitrary HTML attributes from C<%attributes>. The
347 tag's C<id> defaults to C<name_to_id($name)>.
348
349 =item C<checkbox_tag $name, %attributes>
350
351 Creates a HTML 'input type=checkbox' tag named C<$name> with arbitrary
352 HTML attributes from C<%attributes>. The tag's C<id> defaults to
353 C<name_to_id($name)>. The tag's C<value> defaults to C<1>.
354
355 If C<%attributes> contains a key C<label> then a HTML 'label' tag is
356 created with said C<label>. No attribute named C<label> is created in
357 that case.
358
359 =item C<date_tag $name, $value, cal_align =E<gt> $align_code, %attributes>
360
361 Creates a date input field, with an attached javascript that will open a
362 calendar on click. The javascript ist by default anchoered at the bottom right
363 sight. This can be overridden with C<cal_align>, see Calendar documentation for
364 the details, usually you'll want a two letter abbreviation of the alignment.
365 Right + Bottom becomes C<BL>.
366
367 =item C<radio_button_tag $name, %attributes>
368
369 Creates a HTML 'input type=radio' tag named C<$name> with arbitrary
370 HTML attributes from C<%attributes>. The tag's C<value> defaults to
371 C<1>. The tag's C<id> defaults to C<name_to_id($name . "_" . $value)>.
372
373 If C<%attributes> contains a key C<label> then a HTML 'label' tag is
374 created with said C<label>. No attribute named C<label> is created in
375 that case.
376
377 =item C<javascript_tag $file1, $file2, $file3...>
378
379 Creates a HTML 'E<lt>script type="text/javascript" src="..."E<gt>'
380 tag for each file name parameter passed. Each file name will be
381 postfixed with '.js' if it isn't already and prefixed with 'js/' if it
382 doesn't contain a slash.
383
384 =back
385
386 =head2 CONVERSION FUNCTIONS
387
388 =over 4
389
390 =item C<options_for_select \@collection, %options>
391
392 Creates a string suitable for a HTML 'select' tag consisting of one
393 'E<lt>optionE<gt>' tag for each element in C<\@collection>. The value
394 to use and the title to display are extracted from the elements in
395 C<\@collection>. Each element can be one of four things:
396
397 =over 12
398
399 =item 1. An array reference with at least two elements. The first element is
400 the value, the second element is its title.
401
402 =item 2. A scalar. The scalar is both the value and the title.
403
404 =item 3. A hash reference. In this case C<%options> must contain
405 I<value> and I<title> keys that name the keys in the element to use
406 for the value and title respectively.
407
408 =item 4. A blessed reference. In this case C<%options> must contain
409 I<value> and I<title> keys that name functions called on the blessed
410 reference whose return values are used as the value and title
411 respectively.
412
413 =back
414
415 For cases 3 and 4 C<$options{value}> defaults to C<id> and
416 C<$options{title}> defaults to C<$options{value}>.
417
418 In addition to pure keys/method you can also provide coderefs as I<value_sub>
419 and/or I<title_sub>. If present, these take precedence over keys or methods,
420 and are called with the element as first argument. It must return the value or
421 title.
422
423 Lastly a joint coderef I<value_title_sub> may be provided, which in turn takes
424 precedence over each individual sub. It will only be called once for each
425 element and must return a list of value and title.
426
427 If the option C<with_empty> is set then an empty element (value
428 C<undef>) will be used as the first element. The title to display for
429 this element can be set with the option C<empty_title> and defaults to
430 an empty string.
431
432 =back
433
434 =head1 MODULE AUTHORS
435
436 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
437
438 L<http://linet-services.de>