minor fix
[plewww.git] / plekit / table / table.js
1 var debug=false;
2
3 /* for debugging purposes */
4 function plc_timestamp () {
5   var now = new Date();
6   return now.getMinutes() + ':' + now.getSeconds() + '.' + now.getMilliseconds() ; 
7 }
8
9 function plc_message (message) {
10   console.log ( plc_timestamp() + ' : ' + message);
11 }
12
13 /* when a table gets paginated, displays context info */
14 function plekit_table_paginator (opts,table_id) {
15
16   if(!("currentPage" in opts)) { return; }
17     
18   var p = document.createElement('p');
19   var table=$(table_id);
20   var t = $(table_id+'-fdtablePaginaterWrapTop');
21   var b = $(table_id+'-fdtablePaginaterWrapBottom');
22
23   /* when there's no visible entry, the pagination code removes the wrappers */
24   if ( (!t) || (!b) ) return;
25
26   /* get how many entries are matching:
27      opts.visibleRows only holds the contents of the current page
28      so we store the number of matching entries in the table 'matching' attribute
29   */
30   var totalMatches = opts.totalRows;
31   var matching=table['matching'];
32   if (matching) totalMatches = matching;
33
34   var label;
35
36   var matches_text;
37   if (totalMatches != opts.totalRows) {
38     matches_text = totalMatches + "/" + opts.totalRows;
39   } else {
40     matches_text = opts.totalRows;
41   }
42   var first = ((opts.currentPage-1) * opts.rowsPerPage) +1;
43   var last = Math.min((opts.currentPage * opts.rowsPerPage),totalMatches);
44   var items_text = "Items [" + first + " - " + last + "] of " + matches_text;
45   var page_text = "Page " + opts.currentPage + " of " + Math.ceil(totalMatches / opts.rowsPerPage);
46   label = items_text + " -- " + page_text;
47
48   p.className = "paginationText";    
49   p.appendChild(document.createTextNode(label));
50
51   /*  t.insertBefore(p.cloneNode(true), t.firstChild); */
52   b.appendChild(p);
53 }
54
55
56 /* locates a table from its id and alters the classname to reflect new table size */
57 function plekit_pagesize_set (table_id,size_id,def_size) {
58   var table=document.getElementById(table_id);
59   var size_area=document.getElementById(size_id);
60   if ( ! size_area.value ) {
61     size_area.value=def_size;
62   }
63   var size=size_area.value;
64   table.className=table.className.replace(/paginate-\d+/,"paginate-"+size); 
65   tablePaginater.init(table_id);
66 }
67
68 function plekit_pagesize_reset(table_id, size_id, size) {
69   var table=document.getElementById(table_id);
70   var size_area=document.getElementById(size_id);
71   size_area.value=size;
72   table.className=table.className.replace(/paginate-\d+/,"paginate-"+size); 
73   tablePaginater.init(table_id);
74 }
75   
76 /* set or clear the ' invisibleRow' in the tr's classname, according to visible */
77 function plekit_table_row_visible (row,visible) {
78   var cn=row.className;
79   /* clear */
80   cn=cn.replace("invisibleRow","");
81   cn.strip();
82   if (! visible) cn += " invisibleRow";
83   row.className=cn;
84 }
85
86 // Working around MSIE...
87 if ('undefined' == typeof Node)
88     Node = { ELEMENT_NODE: 1, TEXT_NODE: 3 };
89
90 // Extract actual text from a DOM node (remove internal tags and so on)
91 function getInnerText(node) {
92     if (node==undefined) return "";
93     var result = '';
94     if (Node.TEXT_NODE == node.nodeType)
95         return node.nodeValue;
96     if (Node.ELEMENT_NODE != node.nodeType)
97         return '';
98     for (var index = 0; index < node.childNodes.length; ++index)
99         result += getInnerText(node.childNodes.item(index));
100     return result;
101 } // getInnerText
102
103 // cache in the <tr> node the concatenation of the innerTexts of its cells
104 function plekit_tr_text (tr) {
105   // if cached, use it
106   if (tr['text_to_match']) return tr['text_to_match'];
107   // otherwise compute it
108   var text="";
109   var cells=tr.cells;
110   for (var i=0; i<cells.length; i++) 
111     text += getInnerText(cells[i]) + " ";
112   text = text.strip().toLowerCase();
113   tr['text_to_match'] = text;
114   return text;
115 }
116
117 var plekit_table_filter_timeout = null;
118 /* scan the table, and mark as visible 
119    the rows that match (either AND or OR the patterns) */
120 function plekit_table_filter(table_id,pattern_id,and_id) {
121   clearTimeout(plekit_table_filter_timeout);
122   plekit_table_filter_timeout = setTimeout(function() {
123                                              plekit_lazy_table_filter(table_id,pattern_id,and_id)
124                                            },
125                                            200);
126 }
127
128 function plekit_lazy_table_filter (table_id,pattern_id,and_id) {
129
130   if (debug) plc_message ('entering plekit_lazy_table_filter');
131
132   var table=$(table_id);
133   var css='#'+table_id+'>tbody';
134   var rows = $$(css)[0].rows;
135   var pattern_area = $(pattern_id);
136   var pattern_text = pattern_area.value;
137   var matching_entries=0;
138   var and_button=$(and_id);
139   var and_if_true=and_button.checked;
140
141   // canonicalize white spaces 
142   pattern_text = pattern_text.replace(/^\s+/, '').replace(/\s+$/, '').replace(/\s+/g,' ');
143   
144   if (pattern_text.indexOf ("&") != -1) {
145     pattern_text = pattern_text.replace(/&/," ");
146     pattern_area.value=pattern_text;
147     and_button.checked=true;
148     return;
149   } else if (pattern_text.indexOf ("|") != -1 ) {
150     pattern_text = pattern_text.replace(/\|/," ");
151     pattern_area.value=pattern_text;
152     and_button.checked=false;
153     return;
154   }
155     
156   var match_attempts=0;
157   var start=(new Date).getTime();
158
159   // if we're running with the same pattern
160   var previous_pattern=table['previous_pattern'];
161   var previous_mode=table['previous_mode'];
162   if ( (previous_pattern == pattern_text) && (previous_mode == and_if_true) ) {
163     return;
164   }
165
166   if (debug) plc_message ('inside plekit_lazy_table_filter');
167
168   var searches=new Array();
169   var patterns=new Array();
170   if (pattern_text.length > 0) {
171       // re compile all patterns 
172       var pattern_texts = pattern_text.strip().split(" ");
173       for (var i=0; i < pattern_texts.length; i++) {
174           // ignore case
175           searches[i]=pattern_texts[i].toLowerCase();
176           patterns[i]=new RegExp(pattern_texts[i],"i");
177       }
178   }
179
180   // scan rows, elaborate 'visible'
181   for (var row_index = 0; row_index < rows.length ; row_index++) {
182     var tr=rows[row_index];
183     var visible=false;
184     
185     /*empty pattern */
186     if (patterns.length == 0) {
187       visible=true;
188     } else if (and_if_true) {
189       /* AND mode: all patterns must match */
190       visible=true;
191       var against=plekit_tr_text (tr);
192       for (var search_index=0; search_index<searches.length; search_index++) {
193         var search=searches[search_index];
194         match_attempts++;
195         if ( against.search(search) < 0) {
196           visible=false;
197           break;          
198         }
199       }
200     } else {
201       /* OR mode: any match is good enough */
202       visible=false;
203       var against = plekit_tr_text(tr);
204       for (var search_index=0; search_index < searches.length; search_index++) {
205         var search=searches[search_index];
206         match_attempts++;
207         if (against.search(search) >= 0) {
208           visible=true;
209           break;
210         }
211       }
212     }
213
214     plekit_table_row_visible(tr,visible);
215     if (visible) matching_entries +=1;
216   }
217   // save for next run
218   table['previous_pattern']=pattern_text;
219   table['previous_mode']=and_if_true;
220   
221   var end=(new Date).getTime();
222   var match_ms=end-start;
223
224   if (debug) plc_message ('almost at end of plekit_lazy_table_filter');
225
226   // optimize useless calls to init, by comparing # of matching entries
227   var previous_matching=table['previous_matching'];
228   if (matching_entries == previous_matching) {
229     return;
230   }
231   
232   table['matching']=matching_entries;
233   table['match_attempts']=match_attempts;
234   tablePaginater.init(table_id);
235   var end2=(new Date).getTime();
236   var paginate_ms=end2-end;
237
238   if (debug) plc_message ('exiting plekit_lazy_table_filter with paginate_ms=' + paginate_ms);
239
240 }
241
242 function plekit_table_filter_reset (table_id, pattern_id,and_id) {
243   /* reset pattern */
244   document.getElementById(pattern_id).value="";
245   plekit_table_filter (table_id, pattern_id,and_id);
246 }