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