chiark / gitweb /
Javascript sorting for query_age
[ypp-sc-tools.db-live.git] / yarrg / web / tabsort
diff --git a/yarrg/web/tabsort b/yarrg/web/tabsort
new file mode 100644 (file)
index 0000000..8f48b25
--- /dev/null
@@ -0,0 +1,95 @@
+<%args>
+$table => 'ts_table'
+$sortkeys => 'ts_sortkeys'
+$cols
+</%args>
+
+<%doc>
+       NoSort
+       DoReverse
+</%doc>
+
+<&| script &>
+
+%      my $sortfn= "ts_sort__$table";
+function <% $sortfn %>(compar) {
+  debug('sorting compar='+compar);
+  var table= document.getElementById('<% $table %>');
+  var firstrow= table.getElementsByTagName('tr').item(0);
+  var tbody= firstrow.parentNode
+  var rows= tbody.childNodes
+  var newrows= new Array;
+  for (var rowix=0; rowix < rows.length; rowix++) {
+    var row= rows.item(rowix);
+    debug('process row '+rowix+' [[ '+row+' ]] id='+row.id)
+    if (!row.id) continue;
+    if (row.tagName != 'TR') continue;
+    newrows.push(row);
+  }
+  newrows.sort(compar);
+  for (var rowix=0; rowix < newrows.length; rowix++) {
+    var row= newrows[rowix];
+    debug('add row '+rowix+' [[ '+row+' ]]');
+    tbody.appendChild(row);
+  }
+}
+
+% my %add_heads;
+% foreach my $cix (0..$#$cols) {
+%      my $col= $cols->[$cix];
+%      my $thhtml= '';
+%      next if $col->{NoSort};
+
+%      my $mapfn= "ts_compar${cix}_map__$table";
+function <% $mapfn %>(rowelement) {
+  var rowid = rowelement.id;
+%      if ($col->{SortKey}) {
+  var sk = <% $col->{SortKey} %>;
+  debug('map rowid='+rowid+' sk='+sk);
+  return sk;
+%      } else {
+  return <% $sortkeys %>[<% $cix %>][rowid];
+%      }
+}
+
+%      my $comparefn= "ts_compar${cix}_cmp0__$table";
+function <% $comparefn %>(a,b) {
+  var a_key = <% $mapfn %>(a);
+  var b_key = <% $mapfn %>(b);
+%      if ($col->{Numeric}) {
+  return a_key - b_key
+%      } else {
+  if (a_key < b_key) return -1;
+  if (a_key > b_key) return +1;
+  return 0;
+%      }
+}
+
+%      foreach my $reverse (qw(0 1)) {
+%              my $tcomparefn= "ts_compar${cix}_cmp${reverse}__$table";
+%              if ($reverse) {
+%                      next unless $col->{DoReverse};
+function <% $tcomparefn %>(a,b) { return -<% $comparefn %>(a,b); }
+%              }
+%              $thhtml .= "<a href=\"javascript:$sortfn($tcomparefn)\">".
+%                              ($reverse ? '&or;' : '&and;'). '</a>';
+%      }
+%      if (length $thhtml) {
+%              $add_heads{$cix}= $thhtml;
+%      }
+% }
+
+function ts_onload__<% $table %>() {
+  var ts_add_heads= <% to_json_protecttags(\%add_heads) %>;
+  var table= document.getElementById('<% $table %>');
+  var firstth= table.getElementsByTagName('th').item(0);
+  var thlist= firstth.parentNode.getElementsByTagName('th');
+  debug('thlist='+thlist);
+  debug('thlist.item(2)=' + thlist.item(2));
+  for (var cix in ts_add_heads) {
+    var ah = ts_add_heads[cix];
+    debug('appending to cix='+cix+' ah='+ah);
+    thlist.item(cix).innerHTML += ah;
+  }
+}
+</&>