Debian Codegraph @

js/widgets/widget-filter.js

raw symbols SCIP
1 /*! Widget: filter - updated 2018-03-18 (v2.30.0) *//*
2 * Requires tablesorter v2.8+ and jQuery 1.7+
3 * by Rob Garrison
4 */
5 ;( function ( $ ) {
6 'use strict';
7 var tsf, tsfRegex,
8 ts = $.tablesorter || {},
9 tscss = ts.css,
10 tskeyCodes = ts.keyCodes;
11
12 $.extend( tscss, {
13 filterRow : 'tablesorter-filter-row',
14 filter : 'tablesorter-filter',
15 filterDisabled : 'disabled',
16 filterRowHide : 'hideme'
17 });
18
19 $.extend( tskeyCodes, {
20 backSpace : 8,
21 escape : 27,
22 space : 32,
23 left : 37,
24 down : 40
25 });
26
27 ts.addWidget({
28 id: 'filter',
29 priority: 50,
30 options : {
31 filter_cellFilter : '', // css class name added to the filter cell ( string or array )
32 filter_childRows : false, // if true, filter includes child row content in the search
33 filter_childByColumn : false, // ( filter_childRows must be true ) if true = search child rows by column; false = search all child row text grouped
34 filter_childWithSibs : true, // if true, include matching child row siblings
35 filter_columnAnyMatch: true, // if true, allows using '#:{query}' in AnyMatch searches ( column:query )
36 filter_columnFilters : true, // if true, a filter will be added to the top of each table column
37 filter_cssFilter : '', // css class name added to the filter row & each input in the row ( tablesorter-filter is ALWAYS added )
38 filter_defaultAttrib : 'data-value', // data attribute in the header cell that contains the default filter value
39 filter_defaultFilter : {}, // add a default column filter type '~{query}' to make fuzzy searches default; '{q1} AND {q2}' to make all searches use a logical AND.
40 filter_excludeFilter : {}, // filters to exclude, per column
41 filter_external : '', // jQuery selector string ( or jQuery object ) of external filters
42 filter_filteredRow : 'filtered', // class added to filtered rows; define in css with "display:none" to hide the filtered-out rows
43 filter_filterLabel : 'Filter "{{label}}" column by...', // Aria-label added to filter input/select; see #1495
44 filter_formatter : null, // add custom filter elements to the filter row
45 filter_functions : null, // add custom filter functions using this option
46 filter_hideEmpty : true, // hide filter row when table is empty
47 filter_hideFilters : false, // collapse filter row when mouse leaves the area
48 filter_ignoreCase : true, // if true, make all searches case-insensitive
49 filter_liveSearch : true, // if true, search column content while the user types ( with a delay )
50 filter_matchType : { 'input': 'exact', 'select': 'exact' }, // global query settings ('exact' or 'match'); overridden by "filter-match" or "filter-exact" class
51 filter_onlyAvail : 'filter-onlyAvail', // a header with a select dropdown & this class name will only show available ( visible ) options within the drop down
52 filter_placeholder : { search : '', select : '' }, // default placeholder text ( overridden by any header 'data-placeholder' setting )
53 filter_reset : null, // jQuery selector string of an element used to reset the filters
54 filter_resetOnEsc : true, // Reset filter input when the user presses escape - normalized across browsers
55 filter_saveFilters : false, // Use the $.tablesorter.storage utility to save the most recent filters
56 filter_searchDelay : 300, // typing delay in milliseconds before starting a search
57 filter_searchFiltered: true, // allow searching through already filtered rows in special circumstances; will speed up searching in large tables if true
58 filter_selectSource : null, // include a function to return an array of values to be added to the column filter select
59 filter_selectSourceSeparator : '|', // filter_selectSource array text left of the separator is added to the option value, right into the option text
60 filter_serversideFiltering : false, // if true, must perform server-side filtering b/c client-side filtering is disabled, but the ui and events will still be used.
61 filter_startsWith : false, // if true, filter start from the beginning of the cell contents
62 filter_useParsedData : false // filter all data using parsed content
63 },
64 format: function( table, c, wo ) {
65 if ( !c.$table.hasClass( 'hasFilters' ) ) {
66 tsf.init( table, c, wo );
67 }
68 },
69 remove: function( table, c, wo, refreshing ) {
70 var tbodyIndex, $tbody,
71 $table = c.$table,
72 $tbodies = c.$tbodies,
73 events = (
74 'addRows updateCell update updateRows updateComplete appendCache filterReset ' +
75 'filterAndSortReset filterFomatterUpdate filterEnd search stickyHeadersInit '
76 ).split( ' ' ).join( c.namespace + 'filter ' );
77 $table
78 .removeClass( 'hasFilters' )
79 // add filter namespace to all BUT search
80 .unbind( events.replace( ts.regex.spaces, ' ' ) )
81 // remove the filter row even if refreshing, because the column might have been moved
82 .find( '.' + tscss.filterRow ).remove();
83 wo.filter_initialized = false;
84 if ( refreshing ) { return; }
85 for ( tbodyIndex = 0; tbodyIndex < $tbodies.length; tbodyIndex++ ) {
86 $tbody = ts.processTbody( table, $tbodies.eq( tbodyIndex ), true ); // remove tbody
87 $tbody.children().removeClass( wo.filter_filteredRow ).show();
88 ts.processTbody( table, $tbody, false ); // restore tbody
89 }
90 if ( wo.filter_reset ) {
91 $( document ).undelegate( wo.filter_reset, 'click' + c.namespace + 'filter' );
92 }
93 }
94 });
95
96 tsf = ts.filter = {
97
98 // regex used in filter 'check' functions - not for general use and not documented
99 regex: {
100 regex : /^\/((?:\\\/|[^\/])+)\/([migyu]{0,5})?$/, // regex to test for regex
101 child : /tablesorter-childRow/, // child row class name; this gets updated in the script
102 filtered : /filtered/, // filtered (hidden) row class name; updated in the script
103 type : /undefined|number/, // check type
104 exact : /(^[\"\'=]+)|([\"\'=]+$)/g, // exact match (allow '==')
105 operators : /[<>=]/g, // replace operators
106 query : '(q|query)', // replace filter queries
107 wild01 : /\?/g, // wild card match 0 or 1
108 wild0More : /\*/g, // wild care match 0 or more
109 quote : /\"/g,
110 isNeg1 : /(>=?\s*-\d)/,
111 isNeg2 : /(<=?\s*\d)/
112 },
113 // function( c, data ) { }
114 // c = table.config
115 // data.$row = jQuery object of the row currently being processed
116 // data.$cells = jQuery object of all cells within the current row
117 // data.filters = array of filters for all columns ( some may be undefined )
118 // data.filter = filter for the current column
119 // data.iFilter = same as data.filter, except lowercase ( if wo.filter_ignoreCase is true )
120 // data.exact = table cell text ( or parsed data if column parser enabled; may be a number & not a string )
121 // data.iExact = same as data.exact, except lowercase ( if wo.filter_ignoreCase is true; may be a number & not a string )
122 // data.cache = table cell text from cache, so it has been parsed ( & in all lower case if c.ignoreCase is true )
123 // data.cacheArray = An array of parsed content from each table cell in the row being processed
124 // data.index = column index; table = table element ( DOM )
125 // data.parsed = array ( by column ) of boolean values ( from filter_useParsedData or 'filter-parsed' class )
126 types: {
127 or : function( c, data, vars ) {
128 // look for "|", but not if it is inside of a regular expression
129 if ( ( tsfRegex.orTest.test( data.iFilter ) || tsfRegex.orSplit.test( data.filter ) ) &&
130 // this test for regex has potential to slow down the overall search
131 !tsfRegex.regex.test( data.filter ) ) {
132 var indx, filterMatched, query, regex,
133 // duplicate data but split filter
134 data2 = $.extend( {}, data ),
135 filter = data.filter.split( tsfRegex.orSplit ),
136 iFilter = data.iFilter.split( tsfRegex.orSplit ),
137 len = filter.length;
138 for ( indx = 0; indx < len; indx++ ) {
139 data2.nestedFilters = true;
140 data2.filter = '' + ( tsf.parseFilter( c, filter[ indx ], data ) || '' );
141 data2.iFilter = '' + ( tsf.parseFilter( c, iFilter[ indx ], data ) || '' );
142 query = '(' + ( tsf.parseFilter( c, data2.filter, data ) || '' ) + ')';
143 try {
144 // use try/catch, because query may not be a valid regex if "|" is contained within a partial regex search,
145 // e.g "/(Alex|Aar" -> Uncaught SyntaxError: Invalid regular expression: /(/(Alex)/: Unterminated group
146 regex = new RegExp( data.isMatch ? query : '^' + query + '$', c.widgetOptions.filter_ignoreCase ? 'i' : '' );
147 // filterMatched = data2.filter === '' && indx > 0 ? true
148 // look for an exact match with the 'or' unless the 'filter-match' class is found
149 filterMatched = regex.test( data2.exact ) || tsf.processTypes( c, data2, vars );
150 if ( filterMatched ) {
151 return filterMatched;
152 }
153 } catch ( error ) {
154 return null;
155 }
156 }
157 // may be null from processing types
158 return filterMatched || false;
159 }
160 return null;
161 },
162 // Look for an AND or && operator ( logical and )
163 and : function( c, data, vars ) {
164 if ( tsfRegex.andTest.test( data.filter ) ) {
165 var indx, filterMatched, result, query, regex,
166 // duplicate data but split filter
167 data2 = $.extend( {}, data ),
168 filter = data.filter.split( tsfRegex.andSplit ),
169 iFilter = data.iFilter.split( tsfRegex.andSplit ),
170 len = filter.length;
171 for ( indx = 0; indx < len; indx++ ) {
172 data2.nestedFilters = true;
173 data2.filter = '' + ( tsf.parseFilter( c, filter[ indx ], data ) || '' );
174 data2.iFilter = '' + ( tsf.parseFilter( c, iFilter[ indx ], data ) || '' );
175 query = ( '(' + ( tsf.parseFilter( c, data2.filter, data ) || '' ) + ')' )
176 // replace wild cards since /(a*)/i will match anything
177 .replace( tsfRegex.wild01, '\\S{1}' ).replace( tsfRegex.wild0More, '\\S*' );
178 try {
179 // use try/catch just in case RegExp is invalid
180 regex = new RegExp( data.isMatch ? query : '^' + query + '$', c.widgetOptions.filter_ignoreCase ? 'i' : '' );
181 // look for an exact match with the 'and' unless the 'filter-match' class is found
182 result = ( regex.test( data2.exact ) || tsf.processTypes( c, data2, vars ) );
183 if ( indx === 0 ) {
184 filterMatched = result;
185 } else {
186 filterMatched = filterMatched && result;
187 }
188 } catch ( error ) {
189 return null;
190 }
191 }
192 // may be null from processing types
193 return filterMatched || false;
194 }
195 return null;
196 },
197 // Look for regex
198 regex: function( c, data ) {
199 if ( tsfRegex.regex.test( data.filter ) ) {
200 var matches,
201 // cache regex per column for optimal speed
202 regex = data.filter_regexCache[ data.index ] || tsfRegex.regex.exec( data.filter ),
203 isRegex = regex instanceof RegExp;
204 try {
205 if ( !isRegex ) {
206 // force case insensitive search if ignoreCase option set?
207 // if ( c.ignoreCase && !regex[2] ) { regex[2] = 'i'; }
208 data.filter_regexCache[ data.index ] = regex = new RegExp( regex[1], regex[2] );
209 }
210 matches = regex.test( data.exact );
211 } catch ( error ) {
212 matches = false;
213 }
214 return matches;
215 }
216 return null;
217 },
218 // Look for operators >, >=, < or <=
219 operators: function( c, data ) {
220 // ignore empty strings... because '' < 10 is true
221 if ( tsfRegex.operTest.test( data.iFilter ) && data.iExact !== '' ) {
222 var cachedValue, result, txt,
223 table = c.table,
224 parsed = data.parsed[ data.index ],
225 query = ts.formatFloat( data.iFilter.replace( tsfRegex.operators, '' ), table ),
226 parser = c.parsers[ data.index ] || {},
227 savedSearch = query;
228 // parse filter value in case we're comparing numbers ( dates )
229 if ( parsed || parser.type === 'numeric' ) {
230 txt = $.trim( '' + data.iFilter.replace( tsfRegex.operators, '' ) );
231 result = tsf.parseFilter( c, txt, data, true );
232 query = ( typeof result === 'number' && result !== '' && !isNaN( result ) ) ? result : query;
233 }
234 // iExact may be numeric - see issue #149;
235 // check if cached is defined, because sometimes j goes out of range? ( numeric columns )
236 if ( ( parsed || parser.type === 'numeric' ) && !isNaN( query ) &&
237 typeof data.cache !== 'undefined' ) {
238 cachedValue = data.cache;
239 } else {
240 txt = isNaN( data.iExact ) ? data.iExact.replace( ts.regex.nondigit, '' ) : data.iExact;
241 cachedValue = ts.formatFloat( txt, table );
242 }
243 if ( tsfRegex.gtTest.test( data.iFilter ) ) {
244 result = tsfRegex.gteTest.test( data.iFilter ) ? cachedValue >= query : cachedValue > query;
245 } else if ( tsfRegex.ltTest.test( data.iFilter ) ) {
246 result = tsfRegex.lteTest.test( data.iFilter ) ? cachedValue <= query : cachedValue < query;
247 }
248 // keep showing all rows if nothing follows the operator
249 if ( !result && savedSearch === '' ) {
250 result = true;
251 }
252 return result;
253 }
254 return null;
255 },
256 // Look for a not match
257 notMatch: function( c, data ) {
258 if ( tsfRegex.notTest.test( data.iFilter ) ) {
259 var indx,
260 txt = data.iFilter.replace( '!', '' ),
261 filter = tsf.parseFilter( c, txt, data ) || '';
262 if ( tsfRegex.exact.test( filter ) ) {
263 // look for exact not matches - see #628
264 filter = filter.replace( tsfRegex.exact, '' );
265 return filter === '' ? true : $.trim( filter ) !== data.iExact;
266 } else {
267 indx = data.iExact.search( $.trim( filter ) );
268 return filter === '' ? true :
269 // return true if not found
270 data.anyMatch ? indx < 0 :
271 // return false if found
272 !( c.widgetOptions.filter_startsWith ? indx === 0 : indx >= 0 );
273 }
274 }
275 return null;
276 },
277 // Look for quotes or equals to get an exact match; ignore type since iExact could be numeric
278 exact: function( c, data ) {
279 /*jshint eqeqeq:false */
280 if ( tsfRegex.exact.test( data.iFilter ) ) {
281 var txt = data.iFilter.replace( tsfRegex.exact, '' ),
282 filter = tsf.parseFilter( c, txt, data ) || '';
283 // eslint-disable-next-line eqeqeq
284 return data.anyMatch ? $.inArray( filter, data.rowArray ) >= 0 : filter == data.iExact;
285 }
286 return null;
287 },
288 // Look for a range ( using ' to ' or ' - ' ) - see issue #166; thanks matzhu!
289 range : function( c, data ) {
290 if ( tsfRegex.toTest.test( data.iFilter ) ) {
291 var result, tmp, range1, range2,
292 table = c.table,
293 index = data.index,
294 parsed = data.parsed[index],
295 // make sure the dash is for a range and not indicating a negative number
296 query = data.iFilter.split( tsfRegex.toSplit );
297
298 tmp = query[0].replace( ts.regex.nondigit, '' ) || '';
299 range1 = ts.formatFloat( tsf.parseFilter( c, tmp, data ), table );
300 tmp = query[1].replace( ts.regex.nondigit, '' ) || '';
301 range2 = ts.formatFloat( tsf.parseFilter( c, tmp, data ), table );
302 // parse filter value in case we're comparing numbers ( dates )
303 if ( parsed || c.parsers[ index ].type === 'numeric' ) {
304 result = c.parsers[ index ].format( '' + query[0], table, c.$headers.eq( index ), index );
305 range1 = ( result !== '' && !isNaN( result ) ) ? result : range1;
306 result = c.parsers[ index ].format( '' + query[1], table, c.$headers.eq( index ), index );
307 range2 = ( result !== '' && !isNaN( result ) ) ? result : range2;
308 }
309 if ( ( parsed || c.parsers[ index ].type === 'numeric' ) && !isNaN( range1 ) && !isNaN( range2 ) ) {
310 result = data.cache;
311 } else {
312 tmp = isNaN( data.iExact ) ? data.iExact.replace( ts.regex.nondigit, '' ) : data.iExact;
313 result = ts.formatFloat( tmp, table );
314 }
315 if ( range1 > range2 ) {
316 tmp = range1; range1 = range2; range2 = tmp; // swap
317 }
318 return ( result >= range1 && result <= range2 ) || ( range1 === '' || range2 === '' );
319 }
320 return null;
321 },
322 // Look for wild card: ? = single, * = multiple, or | = logical OR
323 wild : function( c, data ) {
324 if ( tsfRegex.wildOrTest.test( data.iFilter ) ) {
325 var query = '' + ( tsf.parseFilter( c, data.iFilter, data ) || '' );
326 // look for an exact match with the 'or' unless the 'filter-match' class is found
327 if ( !tsfRegex.wildTest.test( query ) && data.nestedFilters ) {
328 query = data.isMatch ? query : '^(' + query + ')$';
329 }
330 // parsing the filter may not work properly when using wildcards =/
331 try {
332 return new RegExp(
333 query.replace( tsfRegex.wild01, '\\S{1}' ).replace( tsfRegex.wild0More, '\\S*' ),
334 c.widgetOptions.filter_ignoreCase ? 'i' : ''
335 )
336 .test( data.exact );
337 } catch ( error ) {
338 return null;
339 }
340 }
341 return null;
342 },
343 // fuzzy text search; modified from https://github.com/mattyork/fuzzy ( MIT license )
344 fuzzy: function( c, data ) {
345 if ( tsfRegex.fuzzyTest.test( data.iFilter ) ) {
346 var indx,
347 patternIndx = 0,
348 len = data.iExact.length,
349 txt = data.iFilter.slice( 1 ),
350 pattern = tsf.parseFilter( c, txt, data ) || '';
351 for ( indx = 0; indx < len; indx++ ) {
352 if ( data.iExact[ indx ] === pattern[ patternIndx ] ) {
353 patternIndx += 1;
354 }
355 }
356 return patternIndx === pattern.length;
357 }
358 return null;
359 }
360 },
361 init: function( table ) {
362 // filter language options
363 ts.language = $.extend( true, {}, {
364 to : 'to',
365 or : 'or',
366 and : 'and'
367 }, ts.language );
368
369 var options, string, txt, $header, column, val, fxn, noSelect,
370 c = table.config,
371 wo = c.widgetOptions,
372 processStr = function(prefix, str, suffix) {
373 str = str.trim();
374 // don't include prefix/suffix if str is empty
375 return str === '' ? '' : (prefix || '') + str + (suffix || '');
376 };
377 c.$table.addClass( 'hasFilters' );
378 c.lastSearch = [];
379
380 // define timers so using clearTimeout won't cause an undefined error
381 wo.filter_searchTimer = null;
382 wo.filter_initTimer = null;
383 wo.filter_formatterCount = 0;
384 wo.filter_formatterInit = [];
385 wo.filter_anyColumnSelector = '[data-column="all"],[data-column="any"]';
386 wo.filter_multipleColumnSelector = '[data-column*="-"],[data-column*=","]';
387
388 val = '\\{' + tsfRegex.query + '\\}';
389 $.extend( tsfRegex, {
390 child : new RegExp( c.cssChildRow ),
391 filtered : new RegExp( wo.filter_filteredRow ),
392 alreadyFiltered : new RegExp( '(\\s+(-' + processStr('|', ts.language.or) + processStr('|', ts.language.to) + ')\\s+)', 'i' ),
393 toTest : new RegExp( '\\s+(-' + processStr('|', ts.language.to) + ')\\s+', 'i' ),
394 toSplit : new RegExp( '(?:\\s+(?:-' + processStr('|', ts.language.to) + ')\\s+)', 'gi' ),
395 andTest : new RegExp( '\\s+(' + processStr('', ts.language.and, '|') + '&&)\\s+', 'i' ),
396 andSplit : new RegExp( '(?:\\s+(?:' + processStr('', ts.language.and, '|') + '&&)\\s+)', 'gi' ),
397 orTest : new RegExp( '(\\|' + processStr('|\\s+', ts.language.or, '\\s+') + ')', 'i' ),
398 orSplit : new RegExp( '(?:\\|' + processStr('|\\s+(?:', ts.language.or, ')\\s+') + ')', 'gi' ),
399 iQuery : new RegExp( val, 'i' ),
400 igQuery : new RegExp( val, 'ig' ),
401 operTest : /^[<>]=?/,
402 gtTest : />/,
403 gteTest : />=/,
404 ltTest : /</,
405 lteTest : /<=/,
406 notTest : /^\!/,
407 wildOrTest : /[\?\*\|]/,
408 wildTest : /\?\*/,
409 fuzzyTest : /^~/,
410 exactTest : /[=\"\|!]/
411 });
412
413 // don't build filter row if columnFilters is false or all columns are set to 'filter-false'
414 // see issue #156
415 val = c.$headers.filter( '.filter-false, .parser-false' ).length;
416 if ( wo.filter_columnFilters !== false && val !== c.$headers.length ) {
417 // build filter row
418 tsf.buildRow( table, c, wo );
419 }
420
421 txt = 'addRows updateCell update updateRows updateComplete appendCache filterReset ' +
422 'filterAndSortReset filterResetSaved filterEnd search '.split( ' ' ).join( c.namespace + 'filter ' );
423 c.$table.bind( txt, function( event, filter ) {
424 val = wo.filter_hideEmpty &&
425 $.isEmptyObject( c.cache ) &&
426 !( c.delayInit && event.type === 'appendCache' );
427 // hide filter row using the 'filtered' class name
428 c.$table.find( '.' + tscss.filterRow ).toggleClass( wo.filter_filteredRow, val ); // fixes #450
429 if ( !/(search|filter)/.test( event.type ) ) {
430 event.stopPropagation();
431 tsf.buildDefault( table, true );
432 }
433 // Add filterAndSortReset - see #1361
434 if ( event.type === 'filterReset' || event.type === 'filterAndSortReset' ) {
435 c.$table.find( '.' + tscss.filter ).add( wo.filter_$externalFilters ).val( '' );
436 if ( event.type === 'filterAndSortReset' ) {
437 ts.sortReset( this.config, function() {
438 tsf.searching( table, [] );
439 });
440 } else {
441 tsf.searching( table, [] );
442 }
443 } else if ( event.type === 'filterResetSaved' ) {
444 ts.storage( table, 'tablesorter-filters', '' );
445 } else if ( event.type === 'filterEnd' ) {
446 tsf.buildDefault( table, true );
447 } else {
448 // send false argument to force a new search; otherwise if the filter hasn't changed,
449 // it will return
450 filter = event.type === 'search' ? filter :
451 event.type === 'updateComplete' ? c.$table.data( 'lastSearch' ) : '';
452 if ( /(update|add)/.test( event.type ) && event.type !== 'updateComplete' ) {
453 // force a new search since content has changed
454 c.lastCombinedFilter = null;
455 c.lastSearch = [];
456 // update filterFormatters after update (& small delay) - Fixes #1237
457 setTimeout(function() {
458 c.$table.triggerHandler( 'filterFomatterUpdate' );
459 }, 100);
460 }
461 // pass true ( skipFirst ) to prevent the tablesorter.setFilters function from skipping the first
462 // input ensures all inputs are updated when a search is triggered on the table
463 // $( 'table' ).trigger( 'search', [...] );
464 tsf.searching( table, filter, true );
465 }
466 return false;
467 });
468
469 // reset button/link
470 if ( wo.filter_reset ) {
471 if ( wo.filter_reset instanceof $ ) {
472 // reset contains a jQuery object, bind to it
473 wo.filter_reset.click( function() {
474 c.$table.triggerHandler( 'filterReset' );
475 });
476 } else if ( $( wo.filter_reset ).length ) {
477 // reset is a jQuery selector, use event delegation
478 $( document )
479 .undelegate( wo.filter_reset, 'click' + c.namespace + 'filter' )
480 .delegate( wo.filter_reset, 'click' + c.namespace + 'filter', function() {
481 // trigger a reset event, so other functions ( filter_formatter ) know when to reset
482 c.$table.triggerHandler( 'filterReset' );
483 });
484 }
485 }
486 if ( wo.filter_functions ) {
487 for ( column = 0; column < c.columns; column++ ) {
488 fxn = ts.getColumnData( table, wo.filter_functions, column );
489 if ( fxn ) {
490 // remove 'filter-select' from header otherwise the options added here are replaced with
491 // all options
492 $header = c.$headerIndexed[ column ].removeClass( 'filter-select' );
493 // don't build select if 'filter-false' or 'parser-false' set
494 noSelect = !( $header.hasClass( 'filter-false' ) || $header.hasClass( 'parser-false' ) );
495 options = '';
496 if ( fxn === true && noSelect ) {
497 tsf.buildSelect( table, column );
498 } else if ( typeof fxn === 'object' && noSelect ) {
499 // add custom drop down list
500 for ( string in fxn ) {
501 if ( typeof string === 'string' ) {
502 options += options === '' ?
503 '<option value="">' +
504 ( $header.data( 'placeholder' ) ||
505 $header.attr( 'data-placeholder' ) ||
506 wo.filter_placeholder.select ||
507 ''
508 ) +
509 '</option>' : '';
510 val = string;
511 txt = string;
512 if ( string.indexOf( wo.filter_selectSourceSeparator ) >= 0 ) {
513 val = string.split( wo.filter_selectSourceSeparator );
514 txt = val[1];
515 val = val[0];
516 }
517 options += '<option ' +
518 ( txt === val ? '' : 'data-function-name="' + string + '" ' ) +
519 'value="' + val + '">' + txt + '</option>';
520 }
521 }
522 c.$table
523 .find( 'thead' )
524 .find( 'select.' + tscss.filter + '[data-column="' + column + '"]' )
525 .append( options );
526 txt = wo.filter_selectSource;
527 fxn = typeof txt === 'function' ? true : ts.getColumnData( table, txt, column );
528 if ( fxn ) {
529 // updating so the extra options are appended
530 tsf.buildSelect( c.table, column, '', true, $header.hasClass( wo.filter_onlyAvail ) );
531 }
532 }
533 }
534 }
535 }
536 // not really updating, but if the column has both the 'filter-select' class &
537 // filter_functions set to true, it would append the same options twice.
538 tsf.buildDefault( table, true );
539
540 tsf.bindSearch( table, c.$table.find( '.' + tscss.filter ), true );
541 if ( wo.filter_external ) {
542 tsf.bindSearch( table, wo.filter_external );
543 }
544
545 if ( wo.filter_hideFilters ) {
546 tsf.hideFilters( c );
547 }
548
549 // show processing icon
550 if ( c.showProcessing ) {
551 txt = 'filterStart filterEnd '.split( ' ' ).join( c.namespace + 'filter-sp ' );
552 c.$table
553 .unbind( txt.replace( ts.regex.spaces, ' ' ) )
554 .bind( txt, function( event, columns ) {
555 // only add processing to certain columns to all columns
556 $header = ( columns ) ?
557 c.$table
558 .find( '.' + tscss.header )
559 .filter( '[data-column]' )
560 .filter( function() {
561 return columns[ $( this ).data( 'column' ) ] !== '';
562 }) : '';
563 ts.isProcessing( table, event.type === 'filterStart', columns ? $header : '' );
564 });
565 }
566
567 // set filtered rows count ( intially unfiltered )
568 c.filteredRows = c.totalRows;
569
570 // add default values
571 txt = 'tablesorter-initialized pagerBeforeInitialized '.split( ' ' ).join( c.namespace + 'filter ' );
572 c.$table
573 .unbind( txt.replace( ts.regex.spaces, ' ' ) )
574 .bind( txt, function() {
575 tsf.completeInit( this );
576 });
577 // if filter widget is added after pager has initialized; then set filter init flag
578 if ( c.pager && c.pager.initialized && !wo.filter_initialized ) {
579 c.$table.triggerHandler( 'filterFomatterUpdate' );
580 setTimeout( function() {
581 tsf.filterInitComplete( c );
582 }, 100 );
583 } else if ( !wo.filter_initialized ) {
584 tsf.completeInit( table );
585 }
586 },
587 completeInit: function( table ) {
588 // redefine 'c' & 'wo' so they update properly inside this callback
589 var c = table.config,
590 wo = c.widgetOptions,
591 filters = tsf.setDefaults( table, c, wo ) || [];
592 if ( filters.length ) {
593 // prevent delayInit from triggering a cache build if filters are empty
594 if ( !( c.delayInit && filters.join( '' ) === '' ) ) {
595 ts.setFilters( table, filters, true );
596 }
597 }
598 c.$table.triggerHandler( 'filterFomatterUpdate' );
599 // trigger init after setTimeout to prevent multiple filterStart/End/Init triggers
600 setTimeout( function() {
601 if ( !wo.filter_initialized ) {
602 tsf.filterInitComplete( c );
603 }
604 }, 100 );
605 },
606
607 // $cell parameter, but not the config, is passed to the filter_formatters,
608 // so we have to work with it instead
609 formatterUpdated: function( $cell, column ) {
610 // prevent error if $cell is undefined - see #1056
611 var $table = $cell && $cell.closest( 'table' );
612 var config = $table.length && $table[0].config,
613 wo = config && config.widgetOptions;
614 if ( wo && !wo.filter_initialized ) {
615 // add updates by column since this function
616 // may be called numerous times before initialization
617 wo.filter_formatterInit[ column ] = 1;
618 }
619 },
620 filterInitComplete: function( c ) {
621 var indx, len,
622 wo = c.widgetOptions,
623 count = 0,
624 completed = function() {
625 wo.filter_initialized = true;
626 // update lastSearch - it gets cleared often
627 c.lastSearch = c.$table.data( 'lastSearch' );
628 c.$table.triggerHandler( 'filterInit', c );
629 tsf.findRows( c.table, c.lastSearch || [] );
630 if (ts.debug(c, 'filter')) {
631 console.log('Filter >> Widget initialized');
632 }
633 };
634 if ( $.isEmptyObject( wo.filter_formatter ) ) {
635 completed();
636 } else {
637 len = wo.filter_formatterInit.length;
638 for ( indx = 0; indx < len; indx++ ) {
639 if ( wo.filter_formatterInit[ indx ] === 1 ) {
640 count++;
641 }
642 }
643 clearTimeout( wo.filter_initTimer );
644 if ( !wo.filter_initialized && count === wo.filter_formatterCount ) {
645 // filter widget initialized
646 completed();
647 } else if ( !wo.filter_initialized ) {
648 // fall back in case a filter_formatter doesn't call
649 // $.tablesorter.filter.formatterUpdated( $cell, column ), and the count is off
650 wo.filter_initTimer = setTimeout( function() {
651 completed();
652 }, 500 );
653 }
654 }
655 },
656 // encode or decode filters for storage; see #1026
657 processFilters: function( filters, encode ) {
658 var indx,
659 // fixes #1237; previously returning an encoded "filters" value
660 result = [],
661 mode = encode ? encodeURIComponent : decodeURIComponent,
662 len = filters.length;
663 for ( indx = 0; indx < len; indx++ ) {
664 if ( filters[ indx ] ) {
665 result[ indx ] = mode( filters[ indx ] );
666 }
667 }
668 return result;
669 },
670 setDefaults: function( table, c, wo ) {
671 var isArray, saved, indx, col, $filters,
672 // get current ( default ) filters
673 filters = ts.getFilters( table ) || [];
674 if ( wo.filter_saveFilters && ts.storage ) {
675 saved = ts.storage( table, 'tablesorter-filters' ) || [];
676 isArray = $.isArray( saved );
677 // make sure we're not just getting an empty array
678 if ( !( isArray && saved.join( '' ) === '' || !isArray ) ) {
679 filters = tsf.processFilters( saved );
680 }
681 }
682 // if no filters saved, then check default settings
683 if ( filters.join( '' ) === '' ) {
684 // allow adding default setting to external filters
685 $filters = c.$headers.add( wo.filter_$externalFilters )
686 .filter( '[' + wo.filter_defaultAttrib + ']' );
687 for ( indx = 0; indx <= c.columns; indx++ ) {
688 // include data-column='all' external filters
689 col = indx === c.columns ? 'all' : indx;
690 filters[ indx ] = $filters
691 .filter( '[data-column="' + col + '"]' )
692 .attr( wo.filter_defaultAttrib ) || filters[indx] || '';
693 }
694 }
695 c.$table.data( 'lastSearch', filters );
696 return filters;
697 },
698 parseFilter: function( c, filter, data, parsed ) {
699 return parsed || data.parsed[ data.index ] ?
700 c.parsers[ data.index ].format( filter, c.table, [], data.index ) :
701 filter;
702 },
703 buildRow: function( table, c, wo ) {
704 var $filter, col, column, $header, makeSelect, disabled, name, ffxn, tmp,
705 // c.columns defined in computeThIndexes()
706 cellFilter = wo.filter_cellFilter,
707 columns = c.columns,
708 arry = $.isArray( cellFilter ),
709 buildFilter = '<tr role="search" class="' + tscss.filterRow + ' ' + c.cssIgnoreRow + '">';
710 for ( column = 0; column < columns; column++ ) {
711 if ( c.$headerIndexed[ column ].length ) {
712 // account for entire column set with colspan. See #1047
713 tmp = c.$headerIndexed[ column ] && c.$headerIndexed[ column ][0].colSpan || 0;
714 if ( tmp > 1 ) {
715 buildFilter += '<td data-column="' + column + '-' + ( column + tmp - 1 ) + '" colspan="' + tmp + '"';
716 } else {
717 buildFilter += '<td data-column="' + column + '"';
718 }
719 if ( arry ) {
720 buildFilter += ( cellFilter[ column ] ? ' class="' + cellFilter[ column ] + '"' : '' );
721 } else {
722 buildFilter += ( cellFilter !== '' ? ' class="' + cellFilter + '"' : '' );
723 }
724 buildFilter += '></td>';
725 }
726 }
727 c.$filters = $( buildFilter += '</tr>' )
728 .appendTo( c.$table.children( 'thead' ).eq( 0 ) )
729 .children( 'td' );
730 // build each filter input
731 for ( column = 0; column < columns; column++ ) {
732 disabled = false;
733 // assuming last cell of a column is the main column
734 $header = c.$headerIndexed[ column ];
735 if ( $header && $header.length ) {
736 // $filter = c.$filters.filter( '[data-column="' + column + '"]' );
737 $filter = tsf.getColumnElm( c, c.$filters, column );
738 ffxn = ts.getColumnData( table, wo.filter_functions, column );
739 makeSelect = ( wo.filter_functions && ffxn && typeof ffxn !== 'function' ) ||
740 $header.hasClass( 'filter-select' );
741 // get data from jQuery data, metadata, headers option or header class name
742 col = ts.getColumnData( table, c.headers, column );
743 disabled = ts.getData( $header[0], col, 'filter' ) === 'false' ||
744 ts.getData( $header[0], col, 'parser' ) === 'false';
745
746 if ( makeSelect ) {
747 buildFilter = $( '<select>' ).appendTo( $filter );
748 } else {
749 ffxn = ts.getColumnData( table, wo.filter_formatter, column );
750 if ( ffxn ) {
751 wo.filter_formatterCount++;
752 buildFilter = ffxn( $filter, column );
753 // no element returned, so lets go find it
754 if ( buildFilter && buildFilter.length === 0 ) {
755 buildFilter = $filter.children( 'input' );
756 }
757 // element not in DOM, so lets attach it
758 if ( buildFilter && ( buildFilter.parent().length === 0 ||
759 ( buildFilter.parent().length && buildFilter.parent()[0] !== $filter[0] ) ) ) {
760 $filter.append( buildFilter );
761 }
762 } else {
763 buildFilter = $( '<input type="search">' ).appendTo( $filter );
764 }
765 if ( buildFilter ) {
766 tmp = $header.data( 'placeholder' ) ||
767 $header.attr( 'data-placeholder' ) ||
768 wo.filter_placeholder.search || '';
769 buildFilter.attr( 'placeholder', tmp );
770 }
771 }
772 if ( buildFilter ) {
773 // add filter class name
774 name = ( $.isArray( wo.filter_cssFilter ) ?
775 ( typeof wo.filter_cssFilter[column] !== 'undefined' ? wo.filter_cssFilter[column] || '' : '' ) :
776 wo.filter_cssFilter ) || '';
777 // copy data-column from table cell (it will include colspan)
778 buildFilter.addClass( tscss.filter + ' ' + name );
779 name = wo.filter_filterLabel;
780 tmp = name.match(/{{([^}]+?)}}/g);
781 if (!tmp) {
782 tmp = [ '{{label}}' ];
783 }
784 $.each(tmp, function(indx, attr) {
785 var regex = new RegExp(attr, 'g'),
786 data = $header.attr('data-' + attr.replace(/{{|}}/g, '')),
787 text = typeof data === 'undefined' ? $header.text() : data;
788 name = name.replace( regex, $.trim( text ) );
789 });
790 buildFilter.attr({
791 'data-column': $filter.attr( 'data-column' ),
792 'aria-label': name
793 });
794 if ( disabled ) {
795 buildFilter.attr( 'placeholder', '' ).addClass( tscss.filterDisabled )[0].disabled = true;
796 }
797 }
798 }
799 }
800 },
801 bindSearch: function( table, $el, internal ) {
802 table = $( table )[0];
803 $el = $( $el ); // allow passing a selector string
804 if ( !$el.length ) { return; }
805 var tmp,
806 c = table.config,
807 wo = c.widgetOptions,
808 namespace = c.namespace + 'filter',
809 $ext = wo.filter_$externalFilters;
810 if ( internal !== true ) {
811 // save anyMatch element
812 tmp = wo.filter_anyColumnSelector + ',' + wo.filter_multipleColumnSelector;
813 wo.filter_$anyMatch = $el.filter( tmp );
814 if ( $ext && $ext.length ) {
815 wo.filter_$externalFilters = wo.filter_$externalFilters.add( $el );
816 } else {
817 wo.filter_$externalFilters = $el;
818 }
819 // update values ( external filters added after table initialization )
820 ts.setFilters( table, c.$table.data( 'lastSearch' ) || [], internal === false );
821 }
822 // unbind events
823 tmp = ( 'keypress keyup keydown search change input '.split( ' ' ).join( namespace + ' ' ) );
824 $el
825 // use data attribute instead of jQuery data since the head is cloned without including
826 // the data/binding
827 .attr( 'data-lastSearchTime', new Date().getTime() )
828 .unbind( tmp.replace( ts.regex.spaces, ' ' ) )
829 .bind( 'keydown' + namespace, function( event ) {
830 if ( event.which === tskeyCodes.escape && !table.config.widgetOptions.filter_resetOnEsc ) {
831 // prevent keypress event
832 return false;
833 }
834 })
835 .bind( 'keyup' + namespace, function( event ) {
836 wo = table.config.widgetOptions; // make sure "wo" isn't cached
837 var column = parseInt( $( this ).attr( 'data-column' ), 10 ),
838 liveSearch = typeof wo.filter_liveSearch === 'boolean' ? wo.filter_liveSearch :
839 ts.getColumnData( table, wo.filter_liveSearch, column );
840 if ( typeof liveSearch === 'undefined' ) {
841 liveSearch = wo.filter_liveSearch.fallback || false;
842 }
843 $( this ).attr( 'data-lastSearchTime', new Date().getTime() );
844 // emulate what webkit does.... escape clears the filter
845 if ( event.which === tskeyCodes.escape ) {
846 // make sure to restore the last value on escape
847 this.value = wo.filter_resetOnEsc ? '' : c.lastSearch[column];
848 // don't return if the search value is empty ( all rows need to be revealed )
849 } else if ( this.value !== '' && (
850 // liveSearch can contain a min value length; ignore arrow and meta keys, but allow backspace
851 ( typeof liveSearch === 'number' && this.value.length < liveSearch ) ||
852 // let return & backspace continue on, but ignore arrows & non-valid characters
853 ( event.which !== tskeyCodes.enter && event.which !== tskeyCodes.backSpace &&
854 ( event.which < tskeyCodes.space || ( event.which >= tskeyCodes.left && event.which <= tskeyCodes.down ) ) ) ) ) {
855 return;
856 // live search
857 } else if ( liveSearch === false ) {
858 if ( this.value !== '' && event.which !== tskeyCodes.enter ) {
859 return;
860 }
861 }
862 // change event = no delay; last true flag tells getFilters to skip newest timed input
863 tsf.searching( table, true, true, column );
864 })
865 // include change for select - fixes #473
866 .bind( 'search change keypress input blur '.split( ' ' ).join( namespace + ' ' ), function( event ) {
867 // don't get cached data, in case data-column changes dynamically
868 var column = parseInt( $( this ).attr( 'data-column' ), 10 ),
869 eventType = event.type,
870 liveSearch = typeof wo.filter_liveSearch === 'boolean' ?
871 wo.filter_liveSearch :
872 ts.getColumnData( table, wo.filter_liveSearch, column );
873 if ( table.config.widgetOptions.filter_initialized &&
874 // immediate search if user presses enter
875 ( event.which === tskeyCodes.enter ||
876 // immediate search if a "search" or "blur" is triggered on the input
877 ( eventType === 'search' || eventType === 'blur' ) ||
878 // change & input events must be ignored if liveSearch !== true
879 ( eventType === 'change' || eventType === 'input' ) &&
880 // prevent search if liveSearch is a number
881 ( liveSearch === true || liveSearch !== true && event.target.nodeName !== 'INPUT' ) &&
882 // don't allow 'change' or 'input' event to process if the input value
883 // is the same - fixes #685
884 this.value !== c.lastSearch[column]
885 )
886 ) {
887 event.preventDefault();
888 // init search with no delay
889 $( this ).attr( 'data-lastSearchTime', new Date().getTime() );
890 tsf.searching( table, eventType !== 'keypress' || event.which === tskeyCodes.enter, true, column );
891 }
892 });
893 },
894 searching: function( table, filter, skipFirst, column ) {
895 var liveSearch,
896 wo = table.config.widgetOptions;
897 if (typeof column === 'undefined') {
898 // no delay
899 liveSearch = false;
900 } else {
901 liveSearch = typeof wo.filter_liveSearch === 'boolean' ?
902 wo.filter_liveSearch :
903 // get column setting, or set to fallback value, or default to false
904 ts.getColumnData( table, wo.filter_liveSearch, column );
905 if ( typeof liveSearch === 'undefined' ) {
906 liveSearch = wo.filter_liveSearch.fallback || false;
907 }
908 }
909 clearTimeout( wo.filter_searchTimer );
910 if ( typeof filter === 'undefined' || filter === true ) {
911 // delay filtering
912 wo.filter_searchTimer = setTimeout( function() {
913 tsf.checkFilters( table, filter, skipFirst );
914 }, liveSearch ? wo.filter_searchDelay : 10 );
915 } else {
916 // skip delay
917 tsf.checkFilters( table, filter, skipFirst );
918 }
919 },
920 equalFilters: function (c, filter1, filter2) {
921 var indx,
922 f1 = [],
923 f2 = [],
924 len = c.columns + 1; // add one to include anyMatch filter
925 filter1 = $.isArray(filter1) ? filter1 : [];
926 filter2 = $.isArray(filter2) ? filter2 : [];
927 for (indx = 0; indx < len; indx++) {
928 f1[indx] = filter1[indx] || '';
929 f2[indx] = filter2[indx] || '';
930 }
931 return f1.join(',') === f2.join(',');
932 },
933 checkFilters: function( table, filter, skipFirst ) {
934 var c = table.config,
935 wo = c.widgetOptions,
936 filterArray = $.isArray( filter ),
937 filters = ( filterArray ) ? filter : ts.getFilters( table, true ),
938 currentFilters = filters || []; // current filter values
939 // prevent errors if delay init is set
940 if ( $.isEmptyObject( c.cache ) ) {
941 // update cache if delayInit set & pager has initialized ( after user initiates a search )
942 if ( c.delayInit && ( !c.pager || c.pager && c.pager.initialized ) ) {
943 ts.updateCache( c, function() {
944 tsf.checkFilters( table, false, skipFirst );
945 });
946 }
947 return;
948 }
949 // add filter array back into inputs
950 if ( filterArray ) {
951 ts.setFilters( table, filters, false, skipFirst !== true );
952 if ( !wo.filter_initialized ) {
953 c.lastSearch = [];
954 c.lastCombinedFilter = '';
955 }
956 }
957 if ( wo.filter_hideFilters ) {
958 // show/hide filter row as needed
959 c.$table
960 .find( '.' + tscss.filterRow )
961 .triggerHandler( tsf.hideFiltersCheck( c ) ? 'mouseleave' : 'mouseenter' );
962 }
963 // return if the last search is the same; but filter === false when updating the search
964 // see example-widget-filter.html filter toggle buttons
965 if ( tsf.equalFilters(c, c.lastSearch, currentFilters) ) {
966 if ( filter !== false ) {
967 return;
968 } else {
969 // force filter refresh
970 c.lastCombinedFilter = '';
971 c.lastSearch = [];
972 }
973 }
974 // define filter inside it is false
975 filters = filters || [];
976 // convert filters to strings - see #1070
977 filters = Array.prototype.map ?
978 filters.map( String ) :
979 // for IE8 & older browsers - maybe not the best method
980 filters.join( '\ufffd' ).split( '\ufffd' );
981
982 if ( wo.filter_initialized ) {
983 c.$table.triggerHandler( 'filterStart', [ filters ] );
984 }
985 if ( c.showProcessing ) {
986 // give it time for the processing icon to kick in
987 setTimeout( function() {
988 tsf.findRows( table, filters, currentFilters );
989 return false;
990 }, 30 );
991 } else {
992 tsf.findRows( table, filters, currentFilters );
993 return false;
994 }
995 },
996 hideFiltersCheck: function( c ) {
997 if (typeof c.widgetOptions.filter_hideFilters === 'function') {
998 var val = c.widgetOptions.filter_hideFilters( c );
999 if (typeof val === 'boolean') {
1000 return val;
1001 }
1002 }
1003 return ts.getFilters( c.$table ).join( '' ) === '';
1004 },
1005 hideFilters: function( c, $table ) {
1006 var timer;
1007 ( $table || c.$table )
1008 .find( '.' + tscss.filterRow )
1009 .addClass( tscss.filterRowHide )
1010 .bind( 'mouseenter mouseleave', function( e ) {
1011 // save event object - http://bugs.jquery.com/ticket/12140
1012 var event = e,
1013 $row = $( this );
1014 clearTimeout( timer );
1015 timer = setTimeout( function() {
1016 if ( /enter|over/.test( event.type ) ) {
1017 $row.removeClass( tscss.filterRowHide );
1018 } else {
1019 // don't hide if input has focus
1020 // $( ':focus' ) needs jQuery 1.6+
1021 if ( $( document.activeElement ).closest( 'tr' )[0] !== $row[0] ) {
1022 // don't hide row if any filter has a value
1023 $row.toggleClass( tscss.filterRowHide, tsf.hideFiltersCheck( c ) );
1024 }
1025 }
1026 }, 200 );
1027 })
1028 .find( 'input, select' ).bind( 'focus blur', function( e ) {
1029 var event = e,
1030 $row = $( this ).closest( 'tr' );
1031 clearTimeout( timer );
1032 timer = setTimeout( function() {
1033 clearTimeout( timer );
1034 // don't hide row if any filter has a value
1035 $row.toggleClass( tscss.filterRowHide, tsf.hideFiltersCheck( c ) && event.type !== 'focus' );
1036 }, 200 );
1037 });
1038 },
1039 defaultFilter: function( filter, mask ) {
1040 if ( filter === '' ) { return filter; }
1041 var regex = tsfRegex.iQuery,
1042 maskLen = mask.match( tsfRegex.igQuery ).length,
1043 query = maskLen > 1 ? $.trim( filter ).split( /\s/ ) : [ $.trim( filter ) ],
1044 len = query.length - 1,
1045 indx = 0,
1046 val = mask;
1047 if ( len < 1 && maskLen > 1 ) {
1048 // only one 'word' in query but mask has >1 slots
1049 query[1] = query[0];
1050 }
1051 // replace all {query} with query words...
1052 // if query = 'Bob', then convert mask from '!{query}' to '!Bob'
1053 // if query = 'Bob Joe Frank', then convert mask '{q} OR {q}' to 'Bob OR Joe OR Frank'
1054 while ( regex.test( val ) ) {
1055 val = val.replace( regex, query[indx++] || '' );
1056 if ( regex.test( val ) && indx < len && ( query[indx] || '' ) !== '' ) {
1057 val = mask.replace( regex, val );
1058 }
1059 }
1060 return val;
1061 },
1062 getLatestSearch: function( $input ) {
1063 if ( $input ) {
1064 return $input.sort( function( a, b ) {
1065 return $( b ).attr( 'data-lastSearchTime' ) - $( a ).attr( 'data-lastSearchTime' );
1066 });
1067 }
1068 return $input || $();
1069 },
1070 findRange: function( c, val, ignoreRanges ) {
1071 // look for multiple columns '1-3,4-6,8' in data-column
1072 var temp, ranges, range, start, end, singles, i, indx, len,
1073 columns = [];
1074 if ( /^[0-9]+$/.test( val ) ) {
1075 // always return an array
1076 return [ parseInt( val, 10 ) ];
1077 }
1078 // process column range
1079 if ( !ignoreRanges && /-/.test( val ) ) {
1080 ranges = val.match( /(\d+)\s*-\s*(\d+)/g );
1081 len = ranges ? ranges.length : 0;
1082 for ( indx = 0; indx < len; indx++ ) {
1083 range = ranges[indx].split( /\s*-\s*/ );
1084 start = parseInt( range[0], 10 ) || 0;
1085 end = parseInt( range[1], 10 ) || ( c.columns - 1 );
1086 if ( start > end ) {
1087 temp = start; start = end; end = temp; // swap
1088 }
1089 if ( end >= c.columns ) {
1090 end = c.columns - 1;
1091 }
1092 for ( ; start <= end; start++ ) {
1093 columns[ columns.length ] = start;
1094 }
1095 // remove processed range from val
1096 val = val.replace( ranges[ indx ], '' );
1097 }
1098 }
1099 // process single columns
1100 if ( !ignoreRanges && /,/.test( val ) ) {
1101 singles = val.split( /\s*,\s*/ );
1102 len = singles.length;
1103 for ( i = 0; i < len; i++ ) {
1104 if ( singles[ i ] !== '' ) {
1105 indx = parseInt( singles[ i ], 10 );
1106 if ( indx < c.columns ) {
1107 columns[ columns.length ] = indx;
1108 }
1109 }
1110 }
1111 }
1112 // return all columns
1113 if ( !columns.length ) {
1114 for ( indx = 0; indx < c.columns; indx++ ) {
1115 columns[ columns.length ] = indx;
1116 }
1117 }
1118 return columns;
1119 },
1120 getColumnElm: function( c, $elements, column ) {
1121 // data-column may contain multiple columns '1-3,5-6,8'
1122 // replaces: c.$filters.filter( '[data-column="' + column + '"]' );
1123 return $elements.filter( function() {
1124 var cols = tsf.findRange( c, $( this ).attr( 'data-column' ) );
1125 return $.inArray( column, cols ) > -1;
1126 });
1127 },
1128 multipleColumns: function( c, $input ) {
1129 // look for multiple columns '1-3,4-6,8' in data-column
1130 var wo = c.widgetOptions,
1131 // only target 'all' column inputs on initialization
1132 // & don't target 'all' column inputs if they don't exist
1133 targets = wo.filter_initialized || !$input.filter( wo.filter_anyColumnSelector ).length,
1134 val = $.trim( tsf.getLatestSearch( $input ).attr( 'data-column' ) || '' );
1135 return tsf.findRange( c, val, !targets );
1136 },
1137 processTypes: function( c, data, vars ) {
1138 var ffxn,
1139 filterMatched = null,
1140 matches = null;
1141 for ( ffxn in tsf.types ) {
1142 if ( $.inArray( ffxn, vars.excludeMatch ) < 0 && matches === null ) {
1143 matches = tsf.types[ffxn]( c, data, vars );
1144 if ( matches !== null ) {
1145 data.matchedOn = ffxn;
1146 filterMatched = matches;
1147 }
1148 }
1149 }
1150 return filterMatched;
1151 },
1152 matchType: function( c, columnIndex ) {
1153 var isMatch,
1154 wo = c.widgetOptions,
1155 $el = c.$headerIndexed[ columnIndex ];
1156 // filter-exact > filter-match > filter_matchType for type
1157 if ( $el.hasClass( 'filter-exact' ) ) {
1158 isMatch = false;
1159 } else if ( $el.hasClass( 'filter-match' ) ) {
1160 isMatch = true;
1161 } else {
1162 // filter-select is not applied when filter_functions are used, so look for a select
1163 if ( wo.filter_columnFilters ) {
1164 $el = c.$filters
1165 .find( '.' + tscss.filter )
1166 .add( wo.filter_$externalFilters )
1167 .filter( '[data-column="' + columnIndex + '"]' );
1168 } else if ( wo.filter_$externalFilters ) {
1169 $el = wo.filter_$externalFilters.filter( '[data-column="' + columnIndex + '"]' );
1170 }
1171 isMatch = $el.length ?
1172 c.widgetOptions.filter_matchType[ ( $el[ 0 ].nodeName || '' ).toLowerCase() ] === 'match' :
1173 // default to exact, if no inputs found
1174 false;
1175 }
1176 return isMatch;
1177 },
1178 processRow: function( c, data, vars ) {
1179 var result, filterMatched,
1180 fxn, ffxn, txt,
1181 wo = c.widgetOptions,
1182 showRow = true,
1183 hasAnyMatchInput = wo.filter_$anyMatch && wo.filter_$anyMatch.length,
1184
1185 // if wo.filter_$anyMatch data-column attribute is changed dynamically
1186 // we don't want to do an "anyMatch" search on one column using data
1187 // for the entire row - see #998
1188 columnIndex = wo.filter_$anyMatch && wo.filter_$anyMatch.length ?
1189 // look for multiple columns '1-3,4-6,8'
1190 tsf.multipleColumns( c, wo.filter_$anyMatch ) :
1191 [];
1192 data.$cells = data.$row.children();
1193 data.matchedOn = null;
1194 if ( data.anyMatchFlag && columnIndex.length > 1 || ( data.anyMatchFilter && !hasAnyMatchInput ) ) {
1195 data.anyMatch = true;
1196 data.isMatch = true;
1197 data.rowArray = data.$cells.map( function( i ) {
1198 if ( $.inArray( i, columnIndex ) > -1 || ( data.anyMatchFilter && !hasAnyMatchInput ) ) {
1199 if ( data.parsed[ i ] ) {
1200 txt = data.cacheArray[ i ];
1201 } else {
1202 txt = data.rawArray[ i ];
1203 txt = $.trim( wo.filter_ignoreCase ? txt.toLowerCase() : txt );
1204 if ( c.sortLocaleCompare ) {
1205 txt = ts.replaceAccents( txt );
1206 }
1207 }
1208 return txt;
1209 }
1210 }).get();
1211 data.filter = data.anyMatchFilter;
1212 data.iFilter = data.iAnyMatchFilter;
1213 data.exact = data.rowArray.join( ' ' );
1214 data.iExact = wo.filter_ignoreCase ? data.exact.toLowerCase() : data.exact;
1215 data.cache = data.cacheArray.slice( 0, -1 ).join( ' ' );
1216 vars.excludeMatch = vars.noAnyMatch;
1217 filterMatched = tsf.processTypes( c, data, vars );
1218 if ( filterMatched !== null ) {
1219 showRow = filterMatched;
1220 } else {
1221 if ( wo.filter_startsWith ) {
1222 showRow = false;
1223 // data.rowArray may not contain all columns
1224 columnIndex = Math.min( c.columns, data.rowArray.length );
1225 while ( !showRow && columnIndex > 0 ) {
1226 columnIndex--;
1227 showRow = showRow || data.rowArray[ columnIndex ].indexOf( data.iFilter ) === 0;
1228 }
1229 } else {
1230 showRow = ( data.iExact + data.childRowText ).indexOf( data.iFilter ) >= 0;
1231 }
1232 }
1233 data.anyMatch = false;
1234 // no other filters to process
1235 if ( data.filters.join( '' ) === data.filter ) {
1236 return showRow;
1237 }
1238 }
1239
1240 for ( columnIndex = 0; columnIndex < c.columns; columnIndex++ ) {
1241 data.filter = data.filters[ columnIndex ];
1242 data.index = columnIndex;
1243
1244 // filter types to exclude, per column
1245 vars.excludeMatch = vars.excludeFilter[ columnIndex ];
1246
1247 // ignore if filter is empty or disabled
1248 if ( data.filter ) {
1249 data.cache = data.cacheArray[ columnIndex ];
1250 result = data.parsed[ columnIndex ] ? data.cache : data.rawArray[ columnIndex ] || '';
1251 data.exact = c.sortLocaleCompare ? ts.replaceAccents( result ) : result; // issue #405
1252 data.iExact = !tsfRegex.type.test( typeof data.exact ) && wo.filter_ignoreCase ?
1253 data.exact.toLowerCase() : data.exact;
1254 data.isMatch = tsf.matchType( c, columnIndex );
1255
1256 result = showRow; // if showRow is true, show that row
1257
1258 // in case select filter option has a different value vs text 'a - z|A through Z'
1259 ffxn = wo.filter_columnFilters ?
1260 c.$filters.add( wo.filter_$externalFilters )
1261 .filter( '[data-column="' + columnIndex + '"]' )
1262 .find( 'select option:selected' )
1263 .attr( 'data-function-name' ) || '' : '';
1264 // replace accents - see #357
1265 if ( c.sortLocaleCompare ) {
1266 data.filter = ts.replaceAccents( data.filter );
1267 }
1268
1269 // replace column specific default filters - see #1088
1270 if ( wo.filter_defaultFilter && tsfRegex.iQuery.test( vars.defaultColFilter[ columnIndex ] ) ) {
1271 data.filter = tsf.defaultFilter( data.filter, vars.defaultColFilter[ columnIndex ] );
1272 }
1273
1274 // data.iFilter = case insensitive ( if wo.filter_ignoreCase is true ),
1275 // data.filter = case sensitive
1276 data.iFilter = wo.filter_ignoreCase ? ( data.filter || '' ).toLowerCase() : data.filter;
1277 fxn = vars.functions[ columnIndex ];
1278 filterMatched = null;
1279 if ( fxn ) {
1280 if ( typeof fxn === 'function' ) {
1281 // filter callback( exact cell content, parser normalized content,
1282 // filter input value, column index, jQuery row object )
1283 filterMatched = fxn( data.exact, data.cache, data.filter, columnIndex, data.$row, c, data );
1284 } else if ( typeof fxn[ ffxn || data.filter ] === 'function' ) {
1285 // selector option function
1286 txt = ffxn || data.filter;
1287 filterMatched =
1288 fxn[ txt ]( data.exact, data.cache, data.filter, columnIndex, data.$row, c, data );
1289 }
1290 }
1291 if ( filterMatched === null ) {
1292 // cycle through the different filters
1293 // filters return a boolean or null if nothing matches
1294 filterMatched = tsf.processTypes( c, data, vars );
1295 // select with exact match; ignore "and" or "or" within the text; fixes #1486
1296 txt = fxn === true && (data.matchedOn === 'and' || data.matchedOn === 'or');
1297 if ( filterMatched !== null && !txt) {
1298 result = filterMatched;
1299 // Look for match, and add child row data for matching
1300 } else {
1301 // check fxn (filter-select in header) after filter types are checked
1302 // without this, the filter + jQuery UI selectmenu demo was breaking
1303 if ( fxn === true ) {
1304 // default selector uses exact match unless 'filter-match' class is found
1305 result = data.isMatch ?
1306 // data.iExact may be a number
1307 ( '' + data.iExact ).search( data.iFilter ) >= 0 :
1308 data.filter === data.exact;
1309 } else {
1310 txt = ( data.iExact + data.childRowText ).indexOf( tsf.parseFilter( c, data.iFilter, data ) );
1311 result = ( ( !wo.filter_startsWith && txt >= 0 ) || ( wo.filter_startsWith && txt === 0 ) );
1312 }
1313 }
1314 } else {
1315 result = filterMatched;
1316 }
1317 showRow = ( result ) ? showRow : false;
1318 }
1319 }
1320 return showRow;
1321 },
1322 findRows: function( table, filters, currentFilters ) {
1323 if (
1324 tsf.equalFilters(table.config, table.config.lastSearch, currentFilters) ||
1325 !table.config.widgetOptions.filter_initialized
1326 ) {
1327 return;
1328 }
1329 var len, norm_rows, rowData, $rows, $row, rowIndex, tbodyIndex, $tbody, columnIndex,
1330 isChild, childRow, lastSearch, showRow, showParent, time, val, indx,
1331 notFiltered, searchFiltered, query, injected, res, id, txt,
1332 storedFilters = $.extend( [], filters ),
1333 c = table.config,
1334 wo = c.widgetOptions,
1335 debug = ts.debug(c, 'filter'),
1336 // data object passed to filters; anyMatch is a flag for the filters
1337 data = {
1338 anyMatch: false,
1339 filters: filters,
1340 // regex filter type cache
1341 filter_regexCache : []
1342 },
1343 vars = {
1344 // anyMatch really screws up with these types of filters
1345 noAnyMatch: [ 'range', 'operators' ],
1346 // cache filter variables that use ts.getColumnData in the main loop
1347 functions : [],
1348 excludeFilter : [],
1349 defaultColFilter : [],
1350 defaultAnyFilter : ts.getColumnData( table, wo.filter_defaultFilter, c.columns, true ) || ''
1351 };
1352 // parse columns after formatter, in case the class is added at that point
1353 data.parsed = [];
1354 for ( columnIndex = 0; columnIndex < c.columns; columnIndex++ ) {
1355 data.parsed[ columnIndex ] = wo.filter_useParsedData ||
1356 // parser has a "parsed" parameter
1357 ( c.parsers && c.parsers[ columnIndex ] && c.parsers[ columnIndex ].parsed ||
1358 // getData may not return 'parsed' if other 'filter-' class names exist
1359 // ( e.g. <th class="filter-select filter-parsed"> )
1360 ts.getData && ts.getData( c.$headerIndexed[ columnIndex ],
1361 ts.getColumnData( table, c.headers, columnIndex ), 'filter' ) === 'parsed' ||
1362 c.$headerIndexed[ columnIndex ].hasClass( 'filter-parsed' ) );
1363
1364 vars.functions[ columnIndex ] =
1365 ts.getColumnData( table, wo.filter_functions, columnIndex ) ||
1366 c.$headerIndexed[ columnIndex ].hasClass( 'filter-select' );
1367 vars.defaultColFilter[ columnIndex ] =
1368 ts.getColumnData( table, wo.filter_defaultFilter, columnIndex ) || '';
1369 vars.excludeFilter[ columnIndex ] =
1370 ( ts.getColumnData( table, wo.filter_excludeFilter, columnIndex, true ) || '' ).split( /\s+/ );
1371 }
1372
1373 if ( debug ) {
1374 console.log( 'Filter >> Starting filter widget search', filters );
1375 time = new Date();
1376 }
1377 // filtered rows count
1378 c.filteredRows = 0;
1379 c.totalRows = 0;
1380 currentFilters = ( storedFilters || [] );
1381
1382 for ( tbodyIndex = 0; tbodyIndex < c.$tbodies.length; tbodyIndex++ ) {
1383 $tbody = ts.processTbody( table, c.$tbodies.eq( tbodyIndex ), true );
1384 // skip child rows & widget added ( removable ) rows - fixes #448 thanks to @hempel!
1385 // $rows = $tbody.children( 'tr' ).not( c.selectorRemove );
1386 columnIndex = c.columns;
1387 // convert stored rows into a jQuery object
1388 norm_rows = c.cache[ tbodyIndex ].normalized;
1389 $rows = $( $.map( norm_rows, function( el ) {
1390 return el[ columnIndex ].$row.get();
1391 }) );
1392
1393 if ( currentFilters.join('') === '' || wo.filter_serversideFiltering ) {
1394 $rows
1395 .removeClass( wo.filter_filteredRow )
1396 .not( '.' + c.cssChildRow )
1397 .css( 'display', '' );
1398 } else {
1399 // filter out child rows
1400 $rows = $rows.not( '.' + c.cssChildRow );
1401 len = $rows.length;
1402
1403 if ( ( wo.filter_$anyMatch && wo.filter_$anyMatch.length ) ||
1404 typeof filters[c.columns] !== 'undefined' ) {
1405 data.anyMatchFlag = true;
1406 data.anyMatchFilter = '' + (
1407 filters[ c.columns ] ||
1408 wo.filter_$anyMatch && tsf.getLatestSearch( wo.filter_$anyMatch ).val() ||
1409 ''
1410 );
1411 if ( wo.filter_columnAnyMatch ) {
1412 // specific columns search
1413 query = data.anyMatchFilter.split( tsfRegex.andSplit );
1414 injected = false;
1415 for ( indx = 0; indx < query.length; indx++ ) {
1416 res = query[ indx ].split( ':' );
1417 if ( res.length > 1 ) {
1418 // make the column a one-based index ( non-developers start counting from one :P )
1419 if ( isNaN( res[0] ) ) {
1420 $.each( c.headerContent, function( i, txt ) {
1421 // multiple matches are possible
1422 if ( txt.toLowerCase().indexOf( res[0] ) > -1 ) {
1423 id = i;
1424 filters[ id ] = res[1];
1425 }
1426 });
1427 } else {
1428 id = parseInt( res[0], 10 ) - 1;
1429 }
1430 if ( id >= 0 && id < c.columns ) { // if id is an integer
1431 filters[ id ] = res[1];
1432 query.splice( indx, 1 );
1433 indx--;
1434 injected = true;
1435 }
1436 }
1437 }
1438 if ( injected ) {
1439 data.anyMatchFilter = query.join( ' && ' );
1440 }
1441 }
1442 }
1443
1444 // optimize searching only through already filtered rows - see #313
1445 searchFiltered = wo.filter_searchFiltered;
1446 lastSearch = c.lastSearch || c.$table.data( 'lastSearch' ) || [];
1447 if ( searchFiltered ) {
1448 // cycle through all filters; include last ( columnIndex + 1 = match any column ). Fixes #669
1449 for ( indx = 0; indx < columnIndex + 1; indx++ ) {
1450 val = filters[indx] || '';
1451 // break out of loop if we've already determined not to search filtered rows
1452 if ( !searchFiltered ) { indx = columnIndex; }
1453 // search already filtered rows if...
1454 searchFiltered = searchFiltered && lastSearch.length &&
1455 // there are no changes from beginning of filter
1456 val.indexOf( lastSearch[indx] || '' ) === 0 &&
1457 // if there is NOT a logical 'or', or range ( 'to' or '-' ) in the string
1458 !tsfRegex.alreadyFiltered.test( val ) &&
1459 // if we are not doing exact matches, using '|' ( logical or ) or not '!'
1460 !tsfRegex.exactTest.test( val ) &&
1461 // don't search only filtered if the value is negative
1462 // ( '> -10' => '> -100' will ignore hidden rows )
1463 !( tsfRegex.isNeg1.test( val ) || tsfRegex.isNeg2.test( val ) ) &&
1464 // if filtering using a select without a 'filter-match' class ( exact match ) - fixes #593
1465 !( val !== '' && c.$filters && c.$filters.filter( '[data-column="' + indx + '"]' ).find( 'select' ).length &&
1466 !tsf.matchType( c, indx ) );
1467 }
1468 }
1469 notFiltered = $rows.not( '.' + wo.filter_filteredRow ).length;
1470 // can't search when all rows are hidden - this happens when looking for exact matches
1471 if ( searchFiltered && notFiltered === 0 ) { searchFiltered = false; }
1472 if ( debug ) {
1473 console.log( 'Filter >> Searching through ' +
1474 ( searchFiltered && notFiltered < len ? notFiltered : 'all' ) + ' rows' );
1475 }
1476 if ( data.anyMatchFlag ) {
1477 if ( c.sortLocaleCompare ) {
1478 // replace accents
1479 data.anyMatchFilter = ts.replaceAccents( data.anyMatchFilter );
1480 }
1481 if ( wo.filter_defaultFilter && tsfRegex.iQuery.test( vars.defaultAnyFilter ) ) {
1482 data.anyMatchFilter = tsf.defaultFilter( data.anyMatchFilter, vars.defaultAnyFilter );
1483 // clear search filtered flag because default filters are not saved to the last search
1484 searchFiltered = false;
1485 }
1486 // make iAnyMatchFilter lowercase unless both filter widget & core ignoreCase options are true
1487 // when c.ignoreCase is true, the cache contains all lower case data
1488 data.iAnyMatchFilter = !( wo.filter_ignoreCase && c.ignoreCase ) ?
1489 data.anyMatchFilter :
1490 data.anyMatchFilter.toLowerCase();
1491 }
1492
1493 // loop through the rows
1494 for ( rowIndex = 0; rowIndex < len; rowIndex++ ) {
1495
1496 txt = $rows[ rowIndex ].className;
1497 // the first row can never be a child row
1498 isChild = rowIndex && tsfRegex.child.test( txt );
1499 // skip child rows & already filtered rows
1500 if ( isChild || ( searchFiltered && tsfRegex.filtered.test( txt ) ) ) {
1501 continue;
1502 }
1503
1504 data.$row = $rows.eq( rowIndex );
1505 data.rowIndex = rowIndex;
1506 data.cacheArray = norm_rows[ rowIndex ];
1507 rowData = data.cacheArray[ c.columns ];
1508 data.rawArray = rowData.raw;
1509 data.childRowText = '';
1510
1511 if ( !wo.filter_childByColumn ) {
1512 txt = '';
1513 // child row cached text
1514 childRow = rowData.child;
1515 // so, if 'table.config.widgetOptions.filter_childRows' is true and there is
1516 // a match anywhere in the child row, then it will make the row visible
1517 // checked here so the option can be changed dynamically
1518 for ( indx = 0; indx < childRow.length; indx++ ) {
1519 txt += ' ' + childRow[indx].join( ' ' ) || '';
1520 }
1521 data.childRowText = wo.filter_childRows ?
1522 ( wo.filter_ignoreCase ? txt.toLowerCase() : txt ) :
1523 '';
1524 }
1525
1526 showRow = false;
1527 showParent = tsf.processRow( c, data, vars );
1528 $row = rowData.$row;
1529
1530 // don't pass reference to val
1531 val = showParent ? true : false;
1532 childRow = rowData.$row.filter( ':gt(0)' );
1533 if ( wo.filter_childRows && childRow.length ) {
1534 if ( wo.filter_childByColumn ) {
1535 if ( !wo.filter_childWithSibs ) {
1536 // hide all child rows
1537 childRow.addClass( wo.filter_filteredRow );
1538 // if only showing resulting child row, only include parent
1539 $row = $row.eq( 0 );
1540 }
1541 // cycle through each child row
1542 for ( indx = 0; indx < childRow.length; indx++ ) {
1543 data.$row = childRow.eq( indx );
1544 data.cacheArray = rowData.child[ indx ];
1545 data.rawArray = data.cacheArray;
1546 val = tsf.processRow( c, data, vars );
1547 // use OR comparison on child rows
1548 showRow = showRow || val;
1549 if ( !wo.filter_childWithSibs && val ) {
1550 childRow.eq( indx ).removeClass( wo.filter_filteredRow );
1551 }
1552 }
1553 }
1554 // keep parent row match even if no child matches... see #1020
1555 showRow = showRow || showParent;
1556 } else {
1557 showRow = val;
1558 }
1559 $row
1560 .toggleClass( wo.filter_filteredRow, !showRow )[0]
1561 .display = showRow ? '' : 'none';
1562 }
1563 }
1564 c.filteredRows += $rows.not( '.' + wo.filter_filteredRow ).length;
1565 c.totalRows += $rows.length;
1566 ts.processTbody( table, $tbody, false );
1567 }
1568 // lastCombinedFilter is no longer used internally
1569 c.lastCombinedFilter = storedFilters.join(''); // save last search
1570 // don't save 'filters' directly since it may have altered ( AnyMatch column searches )
1571 c.lastSearch = storedFilters;
1572 c.$table.data( 'lastSearch', storedFilters );
1573 if ( wo.filter_saveFilters && ts.storage ) {
1574 ts.storage( table, 'tablesorter-filters', tsf.processFilters( storedFilters, true ) );
1575 }
1576 if ( debug ) {
1577 console.log( 'Filter >> Completed search' + ts.benchmark(time) );
1578 }
1579 if ( wo.filter_initialized ) {
1580 c.$table.triggerHandler( 'filterBeforeEnd', c );
1581 c.$table.triggerHandler( 'filterEnd', c );
1582 }
1583 setTimeout( function() {
1584 ts.applyWidget( c.table ); // make sure zebra widget is applied
1585 }, 0 );
1586 },
1587 getOptionSource: function( table, column, onlyAvail ) {
1588 table = $( table )[0];
1589 var c = table.config,
1590 wo = c.widgetOptions,
1591 arry = false,
1592 source = wo.filter_selectSource,
1593 last = c.$table.data( 'lastSearch' ) || [],
1594 fxn = typeof source === 'function' ? true : ts.getColumnData( table, source, column );
1595
1596 if ( onlyAvail && last[column] !== '' ) {
1597 onlyAvail = false;
1598 }
1599
1600 // filter select source option
1601 if ( fxn === true ) {
1602 // OVERALL source
1603 arry = source( table, column, onlyAvail );
1604 } else if ( fxn instanceof $ || ( $.type( fxn ) === 'string' && fxn.indexOf( '</option>' ) >= 0 ) ) {
1605 // selectSource is a jQuery object or string of options
1606 return fxn;
1607 } else if ( $.isArray( fxn ) ) {
1608 arry = fxn;
1609 } else if ( $.type( source ) === 'object' && fxn ) {
1610 // custom select source function for a SPECIFIC COLUMN
1611 arry = fxn( table, column, onlyAvail );
1612 // abort - updating the selects from an external method
1613 if (arry === null) {
1614 return null;
1615 }
1616 }
1617 if ( arry === false ) {
1618 // fall back to original method
1619 arry = tsf.getOptions( table, column, onlyAvail );
1620 }
1621
1622 return tsf.processOptions( table, column, arry );
1623
1624 },
1625 processOptions: function( table, column, arry ) {
1626 if ( !$.isArray( arry ) ) {
1627 return false;
1628 }
1629 table = $( table )[0];
1630 var cts, txt, indx, len, parsedTxt, str,
1631 c = table.config,
1632 validColumn = typeof column !== 'undefined' && column !== null && column >= 0 && column < c.columns,
1633 direction = validColumn ? c.$headerIndexed[ column ].hasClass( 'filter-select-sort-desc' ) : false,
1634 parsed = [];
1635 // get unique elements and sort the list
1636 // if $.tablesorter.sortText exists ( not in the original tablesorter ),
1637 // then natural sort the list otherwise use a basic sort
1638 arry = $.grep( arry, function( value, indx ) {
1639 if ( value.text ) {
1640 return true;
1641 }
1642 return $.inArray( value, arry ) === indx;
1643 });
1644 if ( validColumn && c.$headerIndexed[ column ].hasClass( 'filter-select-nosort' ) ) {
1645 // unsorted select options
1646 return arry;
1647 } else {
1648 len = arry.length;
1649 // parse select option values
1650 for ( indx = 0; indx < len; indx++ ) {
1651 txt = arry[ indx ];
1652 // check for object
1653 str = txt.text ? txt.text : txt;
1654 // sortNatural breaks if you don't pass it strings
1655 parsedTxt = ( validColumn && c.parsers && c.parsers.length &&
1656 c.parsers[ column ].format( str, table, [], column ) || str ).toString();
1657 parsedTxt = c.widgetOptions.filter_ignoreCase ? parsedTxt.toLowerCase() : parsedTxt;
1658 // parse array data using set column parser; this DOES NOT pass the original
1659 // table cell to the parser format function
1660 if ( txt.text ) {
1661 txt.parsed = parsedTxt;
1662 parsed[ parsed.length ] = txt;
1663 } else {
1664 parsed[ parsed.length ] = {
1665 text : txt,
1666 // check parser length - fixes #934
1667 parsed : parsedTxt
1668 };
1669 }
1670 }
1671 // sort parsed select options
1672 cts = c.textSorter || '';
1673 parsed.sort( function( a, b ) {
1674 var x = direction ? b.parsed : a.parsed,
1675 y = direction ? a.parsed : b.parsed;
1676 if ( validColumn && typeof cts === 'function' ) {
1677 // custom OVERALL text sorter
1678 return cts( x, y, true, column, table );
1679 } else if ( validColumn && typeof cts === 'object' && cts.hasOwnProperty( column ) ) {
1680 // custom text sorter for a SPECIFIC COLUMN
1681 return cts[column]( x, y, true, column, table );
1682 } else if ( ts.sortNatural ) {
1683 // fall back to natural sort
1684 return ts.sortNatural( x, y );
1685 }
1686 // using an older version! do a basic sort
1687 return true;
1688 });
1689 // rebuild arry from sorted parsed data
1690 arry = [];
1691 len = parsed.length;
1692 for ( indx = 0; indx < len; indx++ ) {
1693 arry[ arry.length ] = parsed[indx];
1694 }
1695 return arry;
1696 }
1697 },
1698 getOptions: function( table, column, onlyAvail ) {
1699 table = $( table )[0];
1700 var rowIndex, tbodyIndex, len, row, cache, indx, child, childLen,
1701 c = table.config,
1702 wo = c.widgetOptions,
1703 arry = [];
1704 for ( tbodyIndex = 0; tbodyIndex < c.$tbodies.length; tbodyIndex++ ) {
1705 cache = c.cache[tbodyIndex];
1706 len = c.cache[tbodyIndex].normalized.length;
1707 // loop through the rows
1708 for ( rowIndex = 0; rowIndex < len; rowIndex++ ) {
1709 // get cached row from cache.row ( old ) or row data object
1710 // ( new; last item in normalized array )
1711 row = cache.row ?
1712 cache.row[ rowIndex ] :
1713 cache.normalized[ rowIndex ][ c.columns ].$row[0];
1714 // check if has class filtered
1715 if ( onlyAvail && row.className.match( wo.filter_filteredRow ) ) {
1716 continue;
1717 }
1718 // get non-normalized cell content
1719 if ( wo.filter_useParsedData ||
1720 c.parsers[column].parsed ||
1721 c.$headerIndexed[column].hasClass( 'filter-parsed' ) ) {
1722 arry[ arry.length ] = '' + cache.normalized[ rowIndex ][ column ];
1723 // child row parsed data
1724 if ( wo.filter_childRows && wo.filter_childByColumn ) {
1725 childLen = cache.normalized[ rowIndex ][ c.columns ].$row.length - 1;
1726 for ( indx = 0; indx < childLen; indx++ ) {
1727 arry[ arry.length ] = '' + cache.normalized[ rowIndex ][ c.columns ].child[ indx ][ column ];
1728 }
1729 }
1730 } else {
1731 // get raw cached data instead of content directly from the cells
1732 arry[ arry.length ] = cache.normalized[ rowIndex ][ c.columns ].raw[ column ];
1733 // child row unparsed data
1734 if ( wo.filter_childRows && wo.filter_childByColumn ) {
1735 childLen = cache.normalized[ rowIndex ][ c.columns ].$row.length;
1736 for ( indx = 1; indx < childLen; indx++ ) {
1737 child = cache.normalized[ rowIndex ][ c.columns ].$row.eq( indx ).children().eq( column );
1738 arry[ arry.length ] = '' + ts.getElementText( c, child, column );
1739 }
1740 }
1741 }
1742 }
1743 }
1744 return arry;
1745 },
1746 buildSelect: function( table, column, arry, updating, onlyAvail ) {
1747 table = $( table )[0];
1748 column = parseInt( column, 10 );
1749 if ( !table.config.cache || $.isEmptyObject( table.config.cache ) ) {
1750 return;
1751 }
1752
1753 var indx, val, txt, t, $filters, $filter, option,
1754 c = table.config,
1755 wo = c.widgetOptions,
1756 node = c.$headerIndexed[ column ],
1757 // t.data( 'placeholder' ) won't work in jQuery older than 1.4.3
1758 options = '<option value="">' +
1759 ( node.data( 'placeholder' ) ||
1760 node.attr( 'data-placeholder' ) ||
1761 wo.filter_placeholder.select || ''
1762 ) + '</option>',
1763 // Get curent filter value
1764 currentValue = c.$table
1765 .find( 'thead' )
1766 .find( 'select.' + tscss.filter + '[data-column="' + column + '"]' )
1767 .val();
1768
1769 // nothing included in arry ( external source ), so get the options from
1770 // filter_selectSource or column data
1771 if ( typeof arry === 'undefined' || arry === '' ) {
1772 arry = tsf.getOptionSource( table, column, onlyAvail );
1773 // abort, selects are updated by an external method
1774 if (arry === null) {
1775 return;
1776 }
1777 }
1778
1779 if ( $.isArray( arry ) ) {
1780 // build option list
1781 for ( indx = 0; indx < arry.length; indx++ ) {
1782 option = arry[ indx ];
1783 if ( option.text ) {
1784 // OBJECT!! add data-function-name in case the value is set in filter_functions
1785 option['data-function-name'] = typeof option.value === 'undefined' ? option.text : option.value;
1786
1787 // support jQuery < v1.8, otherwise the below code could be shortened to
1788 // options += $( '<option>', option )[ 0 ].outerHTML;
1789 options += '<option';
1790 for ( val in option ) {
1791 if ( option.hasOwnProperty( val ) && val !== 'text' ) {
1792 options += ' ' + val + '="' + option[ val ].replace( tsfRegex.quote, '&quot;' ) + '"';
1793 }
1794 }
1795 if ( !option.value ) {
1796 options += ' value="' + option.text.replace( tsfRegex.quote, '&quot;' ) + '"';
1797 }
1798 options += '>' + option.text.replace( tsfRegex.quote, '&quot;' ) + '</option>';
1799 // above code is needed in jQuery < v1.8
1800
1801 // make sure we don't turn an object into a string (objects without a "text" property)
1802 } else if ( '' + option !== '[object Object]' ) {
1803 txt = option = ( '' + option ).replace( tsfRegex.quote, '&quot;' );
1804 val = txt;
1805 // allow including a symbol in the selectSource array
1806 // 'a-z|A through Z' so that 'a-z' becomes the option value
1807 // and 'A through Z' becomes the option text
1808 if ( txt.indexOf( wo.filter_selectSourceSeparator ) >= 0 ) {
1809 t = txt.split( wo.filter_selectSourceSeparator );
1810 val = t[0];
1811 txt = t[1];
1812 }
1813 // replace quotes - fixes #242 & ignore empty strings
1814 // see http://stackoverflow.com/q/14990971/145346
1815 options += option !== '' ?
1816 '<option ' +
1817 ( val === txt ? '' : 'data-function-name="' + option + '" ' ) +
1818 'value="' + val + '">' + txt +
1819 '</option>' : '';
1820 }
1821 }
1822 // clear arry so it doesn't get appended twice
1823 arry = [];
1824 }
1825
1826 // update all selects in the same column ( clone thead in sticky headers &
1827 // any external selects ) - fixes 473
1828 $filters = ( c.$filters ? c.$filters : c.$table.children( 'thead' ) )
1829 .find( '.' + tscss.filter );
1830 if ( wo.filter_$externalFilters ) {
1831 $filters = $filters && $filters.length ?
1832 $filters.add( wo.filter_$externalFilters ) :
1833 wo.filter_$externalFilters;
1834 }
1835 $filter = $filters.filter( 'select[data-column="' + column + '"]' );
1836
1837 // make sure there is a select there!
1838 if ( $filter.length ) {
1839 $filter[ updating ? 'html' : 'append' ]( options );
1840 if ( !$.isArray( arry ) ) {
1841 // append options if arry is provided externally as a string or jQuery object
1842 // options ( default value ) was already added
1843 $filter.append( arry ).val( currentValue );
1844 }
1845 $filter.val( currentValue );
1846 }
1847 },
1848 buildDefault: function( table, updating ) {
1849 var columnIndex, $header, noSelect,
1850 c = table.config,
1851 wo = c.widgetOptions,
1852 columns = c.columns;
1853 // build default select dropdown
1854 for ( columnIndex = 0; columnIndex < columns; columnIndex++ ) {
1855 $header = c.$headerIndexed[columnIndex];
1856 noSelect = !( $header.hasClass( 'filter-false' ) || $header.hasClass( 'parser-false' ) );
1857 // look for the filter-select class; build/update it if found
1858 if ( ( $header.hasClass( 'filter-select' ) ||
1859 ts.getColumnData( table, wo.filter_functions, columnIndex ) === true ) && noSelect ) {
1860 tsf.buildSelect( table, columnIndex, '', updating, $header.hasClass( wo.filter_onlyAvail ) );
1861 }
1862 }
1863 }
1864 };
1865
1866 // filter regex variable
1867 tsfRegex = tsf.regex;
1868
1869 ts.getFilters = function( table, getRaw, setFilters, skipFirst ) {
1870 var i, $filters, $column, cols,
1871 filters = [],
1872 c = table ? $( table )[0].config : '',
1873 wo = c ? c.widgetOptions : '';
1874 if ( ( getRaw !== true && wo && !wo.filter_columnFilters ) ||
1875 // setFilters called, but last search is exactly the same as the current
1876 // fixes issue #733 & #903 where calling update causes the input values to reset
1877 ( $.isArray(setFilters) && tsf.equalFilters(c, setFilters, c.lastSearch) )
1878 ) {
1879 return $( table ).data( 'lastSearch' ) || [];
1880 }
1881 if ( c ) {
1882 if ( c.$filters ) {
1883 $filters = c.$filters.find( '.' + tscss.filter );
1884 }
1885 if ( wo.filter_$externalFilters ) {
1886 $filters = $filters && $filters.length ?
1887 $filters.add( wo.filter_$externalFilters ) :
1888 wo.filter_$externalFilters;
1889 }
1890 if ( $filters && $filters.length ) {
1891 filters = setFilters || [];
1892 for ( i = 0; i < c.columns + 1; i++ ) {
1893 cols = ( i === c.columns ?
1894 // 'all' columns can now include a range or set of columms ( data-column='0-2,4,6-7' )
1895 wo.filter_anyColumnSelector + ',' + wo.filter_multipleColumnSelector :
1896 '[data-column="' + i + '"]' );
1897 $column = $filters.filter( cols );
1898 if ( $column.length ) {
1899 // move the latest search to the first slot in the array
1900 $column = tsf.getLatestSearch( $column );
1901 if ( $.isArray( setFilters ) ) {
1902 // skip first ( latest input ) to maintain cursor position while typing
1903 if ( skipFirst && $column.length > 1 ) {
1904 $column = $column.slice( 1 );
1905 }
1906 if ( i === c.columns ) {
1907 // prevent data-column='all' from filling data-column='0,1' ( etc )
1908 cols = $column.filter( wo.filter_anyColumnSelector );
1909 $column = cols.length ? cols : $column;
1910 }
1911 $column
1912 .val( setFilters[ i ] )
1913 // must include a namespace here; but not c.namespace + 'filter'?
1914 .trigger( 'change' + c.namespace );
1915 } else {
1916 filters[i] = $column.val() || '';
1917 // don't change the first... it will move the cursor
1918 if ( i === c.columns ) {
1919 // don't update range columns from 'all' setting
1920 $column
1921 .slice( 1 )
1922 .filter( '[data-column*="' + $column.attr( 'data-column' ) + '"]' )
1923 .val( filters[ i ] );
1924 } else {
1925 $column
1926 .slice( 1 )
1927 .val( filters[ i ] );
1928 }
1929 }
1930 // save any match input dynamically
1931 if ( i === c.columns && $column.length ) {
1932 wo.filter_$anyMatch = $column;
1933 }
1934 }
1935 }
1936 }
1937 }
1938 return filters;
1939 };
1940
1941 ts.setFilters = function( table, filter, apply, skipFirst ) {
1942 var c = table ? $( table )[0].config : '',
1943 valid = ts.getFilters( table, true, filter, skipFirst );
1944 // default apply to "true"
1945 if ( typeof apply === 'undefined' ) {
1946 apply = true;
1947 }
1948 if ( c && apply ) {
1949 // ensure new set filters are applied, even if the search is the same
1950 c.lastCombinedFilter = null;
1951 c.lastSearch = [];
1952 tsf.searching( c.table, filter, skipFirst );
1953 c.$table.triggerHandler( 'filterFomatterUpdate' );
1954 }
1955 return valid.length !== 0;
1956 };
1957
1958 })( jQuery );