]> wagnertech.de Git - mfinanz.git/blobdiff - SL/Template/Plugin/L.pm
Controller-Helfer für das halbautomatische Sortieren von Listenansichten
[mfinanz.git] / SL / Template / Plugin / L.pm
index 5a59e025d3a81eb7d288bc552a04e4b396a4b2cd..fdb22b31a636b9307776b576a043ff6b7c0fe87a 100644 (file)
@@ -4,6 +4,7 @@ use base qw( Template::Plugin );
 use Template::Plugin;
 use List::MoreUtils qw(apply);
 use List::Util qw(max);
+use Scalar::Util qw(blessed);
 
 use strict;
 
@@ -12,10 +13,15 @@ use strict;
   # Do not use these id's to store information across requests.
 my $_id_sequence = int rand 1e7;
 sub _tag_id {
-  return $_id_sequence = ($_id_sequence + 1) % 1e7;
+  return "id_" . ( $_id_sequence = ($_id_sequence + 1) % 1e7 );
 }
 }
 
+my %_valueless_attributes = map { $_ => 1 } qw(
+  checked compact declare defer disabled ismap multiple noresize noshade nowrap
+  readonly selected
+);
+
 sub _H {
   my $string = shift;
   return $::locale->quote_special_chars('HTML', $string);
@@ -61,9 +67,9 @@ sub attributes {
   my @result = ();
   while (my ($name, $value) = each %options) {
     next unless $name;
-    next if $name eq 'disabled' && !$value;
+    next if $_valueless_attributes{$name} && !$value;
     $value = '' if !defined($value);
-    push @result, _H($name) . '="' . _H($value) . '"';
+    push @result, $_valueless_attributes{$name} ? _H($name) : _H($name) . '="' . _H($value) . '"';
   }
 
   return @result ? ' ' . join(' ', @result) : '';
@@ -73,7 +79,7 @@ sub html_tag {
   my ($self, $tag, $content, @slurp) = @_;
   my $attributes = $self->attributes(@slurp);
 
-  return "<${tag}${attributes}/>" unless defined($content);
+  return "<${tag}${attributes}>" unless defined($content);
   return "<${tag}${attributes}>${content}</${tag}>";
 }
 
@@ -94,6 +100,8 @@ sub textarea_tag {
   my %attributes      = _hashify(@slurp);
 
   $attributes{id}   ||= $self->name_to_id($name);
+  $attributes{rows}  *= 1; # required by standard
+  $attributes{cols}  *= 1; # required by standard
   $content            = $content ? _H($content) : '';
 
   return $self->html_tag('textarea', $content, %attributes, name => $name);
@@ -106,6 +114,7 @@ sub checkbox_tag {
   $attributes{id}    ||= $self->name_to_id($name);
   $attributes{value}   = 1 unless defined $attributes{value};
   my $label            = delete $attributes{label};
+  my $checkall         = delete $attributes{checkall};
 
   if ($attributes{checked}) {
     $attributes{checked} = 'checked';
@@ -115,6 +124,7 @@ sub checkbox_tag {
 
   my $code  = $self->html_tag('input', undef,  %attributes, name => $name, type => 'checkbox');
   $code    .= $self->html_tag('label', $label, for => $attributes{id}) if $label;
+  $code    .= $self->javascript(qq|\$('#$attributes{id}').checkall('$checkall');|) if $checkall;
 
   return $code;
 }
@@ -191,7 +201,10 @@ sub button_tag {
   my ($self, $onclick, $value, @slurp) = @_;
   my %attributes = _hashify(@slurp);
 
-  return $self->input_tag(undef, $value, %attributes, type => 'button', onclick => $onclick);
+  $attributes{id}   ||= $self->name_to_id($attributes{name}) if $attributes{name};
+  $attributes{type} ||= 'button';
+
+  return $self->html_tag('input', undef, %attributes, value => $value, onclick => $onclick);
 }
 
 sub options_for_select {
@@ -222,7 +235,7 @@ sub options_for_select {
   my @elements = ();
   push @elements, [ undef, $options{empty_title} || '' ] if $options{with_empty};
   push @elements, map [
-    $value_title_sub ? $value_title_sub->($_) : (
+    $value_title_sub ? @{ $value_title_sub->($_) } : (
       $access->($_, 0, $value_key, $value_sub),
       $access->($_, 1, $title_key, $title_sub),
     )
@@ -239,6 +252,14 @@ sub options_for_select {
   return $code;
 }
 
+sub yes_no_tag {
+  my ($self, $name, $value) = splice @_, 0, 3;
+  my %attributes            = _hashify(@_);
+
+  my $options               = $self->options_for_select([ [ 1, $::locale->text('Yes') ], [ 0, $::locale->text('No') ] ], default => $value ? 1 : 0);
+  return $self->select_tag($name, $options, %attributes);
+}
+
 sub javascript {
   my ($self, $data) = @_;
   return $self->html_tag('script', $data, type => 'text/javascript');
@@ -269,26 +290,96 @@ sub date_tag {
     s/y+/\%Y/gi;
   } $::myconfig{"dateformat"};
 
-  $params{cal_align} ||= 'BR';
+  my $cal_align = delete $params{cal_align} || 'BR';
+  my $onchange  = delete $params{onchange};
+  my $str_value = blessed $value ? $value->to_lxoffice : $value;
 
-  $self->input_tag($name, $value,
+  $self->input_tag($name, $str_value,
     id     => $name_e,
     size   => 11,
     title  => _H($::myconfig{dateformat}),
     onBlur => 'check_right_date_format(this)',
+    ($onchange ? (
+    onChange => $onchange,
+    ) : ()),
     %params,
-  ) . ((!$params{no_cal}) ?
+  ) . ((!$params{no_cal} && !$params{readonly}) ?
   $self->html_tag('img', undef,
     src    => 'image/calendar.png',
+    alt    => $::locale->text('Calendar'),
     id     => "trigger$seq",
     title  => _H($::myconfig{dateformat}),
     %params,
   ) .
   $self->javascript(
-    "Calendar.setup({ inputField: '$name_e', ifFormat: '$datefmt', align: '$params{cal_align}', button: 'trigger$seq' });"
+    "Calendar.setup({ inputField: '$name_e', ifFormat: '$datefmt', align: '$cal_align', button: 'trigger$seq' });"
   ) : '');
 }
 
+sub customer_picker {
+  my ($self, $name, $value, %params) = @_;
+  my $name_e    = _H($name);
+
+  $self->hidden_tag($name, (ref $value && $value->can('id')) ? $value->id : '') .
+  $self->input_tag("$name_e\_name", (ref $value && $value->can('name')) ? $value->name : '', %params) .
+  $self->javascript(<<JS);
+function autocomplete_customer (selector, column) {
+  \$(function(){ \$(selector).autocomplete({
+    source: function(req, rsp) {
+      \$.ajax({
+        url: 'controller.pl?action=Customer/ajax_autocomplete',
+        dataType: "json",
+        data: {
+          column: column,
+          term: req.term,
+          current: function() { \$('#$name_e').val() },
+          obsolete: 0,
+        },
+        success: function (data){ rsp(data) }
+      });
+    },
+    limit: 20,
+    delay: 50,
+    select: function(event, ui) {
+      \$('#$name_e').val(ui.item.id);
+      \$('#$name_e\_name').val(ui.item.name);
+    },
+  })});
+}
+autocomplete_customer('#$name_e\_name');
+JS
+}
+
+# simple version with select_tag
+sub vendor_selector {
+  my ($self, $name, $value, %params) = @_;
+
+  my $actual_vendor_id = (defined $::form->{"$name"})? ((ref $::form->{"$name"}) ? $::form->{"$name"}->id : $::form->{"$name"}) :
+                         (ref $value && $value->can('id')) ? $value->id : '';
+  my $options_str = $self->options_for_select(SL::DB::Manager::Vendor->get_all(),
+                                              default      => $actual_vendor_id,
+                                              title_sub    => sub { $_[0]->vendornumber . " : " . $_[0]->name },
+                                              'with_empty' => 1);
+
+  return $self->select_tag($name, $options_str, %params);
+}
+
+
+# simple version with select_tag
+sub part_selector {
+  my ($self, $name, $value, %params) = @_;
+
+  my $actual_part_id = (defined $::form->{"$name"})? ((ref $::form->{"$name"})? $::form->{"$name"}->id : $::form->{"$name"}) :
+                       (ref $value && $value->can('id')) ? $value->id : '';
+  my $options_str = $self->options_for_select(SL::DB::Manager::Part->get_all(),
+                                              default      => $actual_part_id,
+                                              title_sub    => sub { $_[0]->partnumber . " : " . $_[0]->description },
+                                              'with_empty' => 1);
+
+  return $self->select_tag($name, $options_str, %params);
+}
+
+
 sub javascript_tag {
   my $self = shift;
   my $code = '';
@@ -368,12 +459,19 @@ sub areainput_tag {
   my ($self, $name, $value, @slurp) = @_;
   my %attributes      = _hashify(@slurp);
 
-  my $rows = delete $attributes{rows}     || 1;
+  my ($rows, $cols);
   my $min  = delete $attributes{min_rows} || 1;
 
+  if (exists $attributes{cols}) {
+    $cols = delete $attributes{cols};
+    $rows = $::form->numtextrows($value, $cols);
+  } else {
+    $rows = delete $attributes{rows} || 1;
+  }
+
   return $rows > 1
-    ? $self->textarea_tag($name, $value, %attributes, rows => max $rows, $min)
-    : $self->input_tag($name, $value, %attributes);
+    ? $self->textarea_tag($name, $value, %attributes, rows => max($rows, $min), ($cols ? (cols => $cols) : ()))
+    : $self->input_tag($name, $value, %attributes, ($cols ? (size => $cols) : ()));
 }
 
 sub multiselect2side {
@@ -410,19 +508,35 @@ sub sortable_element {
     }
 JAVASCRIPT
 
+  my $stop_event = '';
+
   if ($params{url} && $params{with}) {
     my $as      = $params{as} || $params{with};
     my $filter  = ".filter(function(idx) { return this.substr(0, " . length($params{with}) . ") == '$params{with}'; })";
     $filter    .= ".map(function(idx, str) { return str.replace('$params{with}_', ''); })";
 
+    $stop_event = <<JAVASCRIPT;
+        \$.post('$params{url}', { '${as}[]': \$(\$('${selector}').sortable('toArray'))${filter}.toArray() });
+JAVASCRIPT
+  }
+
+  if (!$params{dont_recolor}) {
+    $stop_event .= <<JAVASCRIPT;
+        \$('${selector}>*:odd').removeClass('listrow1').removeClass('listrow0').addClass('listrow0');
+        \$('${selector}>*:even').removeClass('listrow1').removeClass('listrow0').addClass('listrow1');
+JAVASCRIPT
+  }
+
+  if ($stop_event) {
     $attributes{stop} = <<JAVASCRIPT;
       function(event, ui) {
-        \$.post('$params{url}', { '${as}[]': \$(\$('${selector}').sortable('toArray'))${filter}.toArray() });
+        ${stop_event}
         return ui;
       }
 JAVASCRIPT
   }
 
+  $params{handle}     = '.dragdrop' unless exists $params{handle};
   $attributes{handle} = "'$params{handle}'" if $params{handle};
 
   my $attr_str = join(', ', map { "${_}: $attributes{$_}" } keys %attributes);
@@ -447,7 +561,7 @@ sub online_help_tag {
 
   die 'malformed help tag' unless $tag =~ /^[a-zA-Z0-9_]+$/;
   return unless -f $file;
-  return $self->html_tag('a', $text, href => $file, target => '_blank');
+  return $self->html_tag('a', $text, href => $file, class => 'jqModal')
 }
 
 sub dump {
@@ -456,6 +570,41 @@ sub dump {
   return '<pre>' . Data::Dumper::Dumper(@_) . '</pre>';
 }
 
+sub truncate {
+  my ($self, $text, @slurp) = @_;
+  my %params                = _hashify(@slurp);
+
+  $params{at}             ||= 50;
+  $params{at}               =  3 if 3 > $params{at};
+  $params{at}              -= 3;
+
+  return $text if length($text) < $params{at};
+  return substr($text, 0, $params{at}) . '...';
+}
+
+sub sortable_table_header {
+  my ($self, $by, @slurp) = @_;
+  my %params              = _hashify(@slurp);
+
+  my $controller          = $self->{CONTEXT}->stash->get('SELF');
+  my $sort_spec           = $controller->get_sort_spec;
+  my $by_spec             = $sort_spec->{$by};
+  my %current_sort_params = $controller->get_current_sort_params;
+  my ($image, $new_dir)   = ('', $current_sort_params{dir});
+  my $title               = delete($params{title}) || $by_spec->{title};
+
+  if ($current_sort_params{by} eq $by) {
+    my $current_dir = $current_sort_params{dir} ? 'up' : 'down';
+    $image          = '<img border="0" src="image/' . $current_dir . '.png">';
+    $new_dir        = 1 - ($current_sort_params{dir} || 0);
+  }
+
+  $params{ $sort_spec->{FORM_PARAMS}->[0] } = $by;
+  $params{ $sort_spec->{FORM_PARAMS}->[1] } = ($new_dir ? '1' : '0');
+
+  return '<a href="' . $controller->get_callback(%params) . '">' . _H($title) . $image . '</a>';
+}
+
 1;
 
 __END__
@@ -523,6 +672,13 @@ L</options_for_select> function. If C<$options_string> is an array
 reference then it will be passed to L</options_for_select>
 automatically.
 
+=item C<yes_no_tag $name, $value, %attributes>
+
+Creates a HTML 'select' tag with the two entries C<yes> and C<no> by
+calling L<select_tag> and L<options_for_select>. C<$value> determines
+which entry is selected. The C<%attributes> are passed through to
+L<select_tag>.
+
 =item C<input_tag $name, $value, %attributes>
 
 Creates a HTML 'input type=text' tag named C<$name> with the value
@@ -562,6 +718,10 @@ If C<%attributes> contains a key C<label> then a HTML 'label' tag is
 created with said C<label>. No attribute named C<label> is created in
 that case.
 
+If C<%attributes> contains a key C<checkall> then the value is taken as a
+JQuery selector and clicking this checkbox will also toggle all checkboxes
+matching the selector.
+
 =item C<date_tag $name, $value, cal_align =E<gt> $align_code, %attributes>
 
 Creates a date input field, with an attached javascript that will open a
@@ -618,7 +778,8 @@ should be selected by default.
 =item C<areainput_tag $name, $content, %PARAMS>
 
 Creates a generic input tag or textarea tag, depending on content size. The
-mount of desired rows must be given with C<rows> parameter, Accpeted parameters
+amount of desired rows must be either given with the C<rows> parameter or can
+be computed from the value and the C<cols> paramter, Accepted parameters
 include C<min_rows> for rendering a minimum of rows if a textarea is displayed.
 
 You can force input by setting rows to 1, and you can force textarea by setting
@@ -682,9 +843,17 @@ element (see C<$params{with}>).
 =item C<handle>
 
 An optional jQuery selector specifying which part of the child element
-is dragable. If nothing is given then the whole child element is
-dragable, and clicks through to underlying elements like inputs or
-links might not work.
+is dragable. If the parameter is not given then it defaults to
+C<.dragdrop> matching DOM elements with the class C<dragdrop>.  If the
+parameter is set and empty then the whole child element is dragable,
+and clicks through to underlying elements like inputs or links might
+not work.
+
+=item C<dont_recolor>
+
+If trueish then the children will not be recolored. The default is to
+recolor the children by setting the class C<listrow0> on odd and
+C<listrow1> on even entries.
 
 =back
 
@@ -704,9 +873,10 @@ Example:
   <table>
 
   [% L.sortable_element('#thing_list tbody',
-                        'url'  => 'controller.pl?action=SystemThings/reorder',
-                        'with' => 'thingy',
-                        'as'   => 'thing_ids') %]
+                        url          => 'controller.pl?action=SystemThings/reorder',
+                        with         => 'thingy',
+                        as           => 'thing_ids',
+                        recolor_rows => 1) %]
 
 After dropping e.g. the third element at the top of the list a POST
 request would be made to the C<reorder> action of the C<SystemThings>
@@ -717,6 +887,22 @@ containing the values C<[ 6, 2, 15 ]>.
 
 Dumps the Argument using L<Data::Dumper> into a E<lt>preE<gt> block.
 
+=item C<sortable_table_header $by, %params>
+
+Create a link and image suitable for placement in a table
+header. C<$by> must be an index set up by the controller with
+L<SL::Controller::Helper::make_sorted>.
+
+The optional parameter C<$params{title}> can override the column title
+displayed to the user. Otherwise the column title from the
+controller's sort spec is used.
+
+The other parameters in C<%params> are passed unmodified to the
+underlying call to L<SL::Controller::Base::url_for>.
+
+See the documentation of L<SL::Controller::Helper::Sorted> for an
+overview and further usage instructions.
+
 =back
 
 =head2 CONVERSION FUNCTIONS
@@ -783,6 +969,16 @@ the resulting tab will get ignored by C<tabbed>:
 
   L.tab('Awesome tab wih much info', '_much_info.html', if => SELF.wants_all)
 
+=item C<truncate $text, %params>
+
+Returns the C<$text> truncated after a certain number of
+characters.
+
+The number of characters to truncate at is determined by the parameter
+C<at> which defaults to 50. If the text is longer than C<$params{at}>
+then it will be truncated and postfixed with '...'. Otherwise it will
+be returned unmodified.
+
 =back
 
 =head1 MODULE AUTHORS