Debian Codegraph @

debian/missing-sources/footable.js

raw
1 /*
2 * FooTable v3 - FooTable is a jQuery plugin that aims to make HTML tables on smaller devices look awesome.
3 * @version 3.1.6
4 * @link http://fooplugins.com
5 * @copyright Steven Usher & Brad Vincent 2015
6 * @license Released under the GPLv3 license.
7 */
8 (function($, F){
9 // add in console we use in case it's missing
10 window.console = window.console || { log:function(){}, error:function(){} };
11
12 /**
13 * The jQuery plugin initializer.
14 * @function jQuery.fn.footable
15 * @param {(object|FooTable.Defaults)} [options] - The options to initialize the plugin with.
16 * @param {function} [ready] - A callback function to execute for each initialized plugin.
17 * @returns {jQuery}
18 */
19 $.fn.footable = function (options, ready) {
20 options = options || {};
21 // make sure we only work with tables
22 return this.filter('table').each(function (i, tbl) {
23 F.init(tbl, options, ready);
24 });
25 };
26
27 var debug_defaults = {
28 events: []
29 };
30 F.__debug__ = JSON.parse(localStorage.getItem('footable_debug')) || false;
31 F.__debug_options__ = JSON.parse(localStorage.getItem('footable_debug_options')) || debug_defaults;
32
33 /**
34 * Gets or sets the internal debug variable which enables some additional logging to the console.
35 * When enabled this value is stored in the localStorage so it can persist across page reloads.
36 * @param {boolean} value - Whether or not to enable additional logging.
37 * @param {object} [options] - Any debug specific options.
38 * @returns {(boolean|undefined)}
39 */
40 F.debug = function(value, options){
41 if (!F.is.boolean(value)) return F.__debug__;
42 F.__debug__ = value;
43 if (F.__debug__){
44 localStorage.setItem('footable_debug', JSON.stringify(F.__debug__));
45 F.__debug_options__ = $.extend(true, {}, debug_defaults, options || {});
46 if (F.is.hash(options)){
47 localStorage.setItem('footable_debug_options', JSON.stringify(F.__debug_options__));
48 }
49 } else {
50 localStorage.removeItem('footable_debug');
51 localStorage.removeItem('footable_debug_options');
52 }
53 };
54
55 /**
56 * Gets the FooTable instance of the supplied table if one exists.
57 * @param {(jQuery|jQuery.selector|HTMLTableElement)} table - The jQuery table object, selector or the HTMLTableElement to retrieve FooTable from.
58 * @returns {(FooTable.Table|undefined)}
59 */
60 F.get = function(table){
61 return $(table).first().data('__FooTable__');
62 };
63
64 /**
65 * Initializes a new instance of FooTable on the supplied table.
66 * @param {(jQuery|jQuery.selector|HTMLTableElement)} table - The jQuery table object, selector or the HTMLTableElement to initialize FooTable on.
67 * @param {object} options - The options to initialize FooTable with.
68 * @param {function} [ready] - A callback function to execute once the plugin is initialized.
69 * @returns {FooTable.Table}
70 */
71 F.init = function(table, options, ready){
72 var ft = F.get(table);
73 if (ft instanceof F.Table) ft.destroy();
74 return new F.Table(table, options, ready);
75 };
76
77 /**
78 * Gets the FooTable.Row instance for the supplied element.
79 * @param {(jQuery|jQuery.selector|HTMLTableElement)} element - A jQuery object, selector or the HTMLElement of an element to retrieve the FooTable.Row for.
80 * @returns {FooTable.Row}
81 */
82 F.getRow = function(element){
83 // to get the FooTable.Row object simply walk up the DOM, find the TR and grab the __FooTableRow__ data value
84 var $row = $(element).closest('tr');
85 // if this is a detail row get the previous row in the table to get the main TR element
86 if ($row.hasClass('footable-detail-row')){
87 $row = $row.prev();
88 }
89 // grab the row object
90 return $row.data('__FooTableRow__');
91 };
92
93 // The below are external type definitions mainly used as pointers to jQuery docs for important information
94 /**
95 * jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API
96 * that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.
97 * @name jQuery
98 * @constructor
99 * @returns {jQuery}
100 * @see {@link http://api.jquery.com/}
101 */
102
103 /**
104 * This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, and state) to prevent users from changing the state of the Deferred.
105 * @typedef {object} jQuery.Promise
106 * @see {@link http://api.jquery.com/Types/#Promise}
107 */
108
109 /**
110 * As of jQuery 1.5, the Deferred object provides a way to register multiple callbacks into self-managed callback queues, invoke callback queues as appropriate,
111 * and relay the success or failure state of any synchronous or asynchronous function.
112 * @typedef {object} jQuery.Deferred
113 * @see {@link http://api.jquery.com/Types/#Deferred}
114 */
115
116 /**
117 * jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler. Most properties from
118 * the original event are copied over and normalized to the new event object.
119 * @typedef {object} jQuery.Event
120 * @see {@link http://api.jquery.com/category/events/event-object/}
121 */
122
123 /**
124 * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.
125 * @memberof jQuery
126 * @function when
127 * @param {...jQuery.Deferred} deferreds - Any number of deferred objects to wait for.
128 * @returns {jQuery.Promise}
129 * @see {@link http://api.jquery.com/jQuery.when/}
130 */
131
132 /**
133 * The jQuery.fn namespace used to register plugins with jQuery.
134 * @memberof jQuery
135 * @namespace fn
136 * @see {@link http://learn.jquery.com/plugins/basic-plugin-creation/}
137 */
138 })(
139 jQuery,
140 /**
141 * The core FooTable namespace containing all the plugin code.
142 * @namespace
143 */
144 FooTable = window.FooTable || {}
145 );
146 (function(F){
147 var returnTrue = function(){ return true; };
148
149 /**
150 * This namespace contains commonly used array utility methods.
151 * @namespace {object} FooTable.arr
152 */
153 F.arr = {};
154
155 /**
156 * Iterates over each item in the supplied array and performs the supplied function passing in the current item as the first argument.
157 * @memberof FooTable.arr
158 * @function each
159 * @param {Array} array - The array to iterate
160 * @param {function} func - The function to execute for each item. The first argument supplied to this function is the current item and the second is the current index.
161 */
162 F.arr.each = function (array, func) {
163 if (!F.is.array(array) || !F.is.fn(func)) return;
164 for (var i = 0, len = array.length; i < len; i++) {
165 if (func(array[i], i) === false) break;
166 }
167 };
168
169 /**
170 * Get all items in the supplied array that optionally matches the supplied where function. If no items are found an empty array is returned.
171 * @memberof FooTable.arr
172 * @function get
173 * @param {Array} array - The array to get items from.
174 * @param {function} where - This function must return a boolean value, true includes the item in the result array.
175 * @returns {Array}
176 */
177 F.arr.get = function (array, where) {
178 var result = [];
179 if (!F.is.array(array)) return result;
180 if (!F.is.fn(where)) return array;
181 for (var i = 0, len = array.length; i < len; i++) {
182 if (where(array[i], i)) result.push(array[i]);
183 }
184 return result;
185 };
186
187 /**
188 * Get a boolean value indicating if any item exists in the supplied array that optionally matches the supplied where function.
189 * @memberof FooTable.arr
190 * @function any
191 * @param {Array} array - The array to check.
192 * @param {function} [where] - [Optional] This function must return a boolean value, true indicates that the current item is a valid match.
193 * @returns {boolean}
194 */
195 F.arr.any = function (array, where) {
196 if (!F.is.array(array)) return false;
197 where = F.is.fn(where) ? where : returnTrue;
198 for (var i = 0, len = array.length; i < len; i++) {
199 if (where(array[i], i)) return true;
200 }
201 return false;
202 };
203
204 /**
205 * Checks if the supplied value exists in the array.
206 * @memberof FooTable.arr
207 * @function contains
208 * @param {Array} array - The array to check.
209 * @param {*} value - The value to check for.
210 * @returns {boolean}
211 */
212 F.arr.contains = function(array, value){
213 if (!F.is.array(array) || F.is.undef(value)) return false;
214 for (var i = 0, len = array.length; i < len; i++) {
215 if (array[i] == value) return true;
216 }
217 return false;
218 };
219
220 /**
221 * Get the first item in the supplied array that optionally matches the supplied where function. If no item is found null is returned.
222 * @memberof FooTable.arr
223 * @function first
224 * @param {Array} array - The array to get the item from.
225 * @param {function} [where] - [Optional] This function must return a boolean value, true indicates that the current item can be returned.
226 * @returns {(*|null)}
227 */
228 F.arr.first = function (array, where) {
229 if (!F.is.array(array)) return null;
230 where = F.is.fn(where) ? where : returnTrue;
231 for (var i = 0, len = array.length; i < len; i++) {
232 if (where(array[i], i)) return array[i];
233 }
234 return null;
235 };
236
237 /**
238 * Creates a new array from the results of the supplied getter function. If no items are found an empty array is returned, to exclude an item from the results return null.
239 * @memberof FooTable.arr
240 * @function map
241 * @param {Array} array - The array to iterate.
242 * @param {function} getter - This function must return either a new value or null.
243 * The first argument is the result being returned at this point in the iteration. The second argument is the current item being iterated.
244 * @returns {(*|null)}
245 */
246 F.arr.map = function (array, getter) {
247 var result = [], returned = null;
248 if (!F.is.array(array) || !F.is.fn(getter)) return result;
249 for (var i = 0, len = array.length; i < len; i++) {
250 if ((returned = getter(array[i], i)) != null) result.push(returned);
251 }
252 return result;
253 };
254
255 /**
256 * Removes items from the array matching the supplied where function. All removed items are returned in a new array.
257 * @memberof FooTable.arr
258 * @function remove
259 * @param {Array} array - The array to iterate and remove items from.
260 * @param {function} where - This function must return a boolean value, true includes the item in the result array.
261 * @returns {*}
262 */
263 F.arr.remove = function (array, where) {
264 var remove = [], removed = [];
265 if (!F.is.array(array) || !F.is.fn(where)) return removed;
266 var i = 0, len = array.length;
267 for (; i < len; i++) {
268 if (where(array[i], i, removed)){
269 remove.push(i);
270 removed.push(array[i]);
271 }
272 }
273 // sort the indexes to be removed from largest to smallest
274 remove.sort(function(a, b){ return b - a; });
275 i = 0; len = remove.length;
276 for(; i < len; i++){
277 var index = remove[i] - i;
278 array.splice(index, 1);
279 }
280 return removed;
281 };
282
283 /**
284 * Deletes a single item from the array. The item if removed is returned.
285 * @memberof FooTable.arr
286 * @function delete
287 * @param {Array} array - The array to iterate and delete the item from.
288 * @param {*} item - The item to find and delete.
289 * @returns {(*|null)}
290 */
291 F.arr.delete = function(array, item){
292 var remove = -1, removed = null;
293 if (!F.is.array(array) || F.is.undef(item)) return removed;
294 var i = 0, len = array.length;
295 for (; i < len; i++) {
296 if (array[i] == item){
297 remove = i;
298 removed = array[i];
299 break;
300 }
301 }
302 if (remove != -1) array.splice(remove, 1);
303 return removed;
304 };
305
306 /**
307 * Replaces a single item in the array with a new one.
308 * @memberof FooTable.arr
309 * @function replace
310 * @param {Array} array - The array to iterate and replace the item in.
311 * @param {*} oldItem - The item to be replaced.
312 * @param {*} newItem - The item to be inserted.
313 */
314 F.arr.replace = function(array, oldItem, newItem){
315 var index = array.indexOf(oldItem);
316 if (index !== -1) array[index] = newItem;
317 };
318
319 })(FooTable);
320 (function (F) {
321
322 /**
323 * This namespace contains commonly used 'is' type methods that return boolean values.
324 * @namespace FooTable.is
325 */
326 F.is = {};
327
328 /**
329 * Checks if the type of the value is the same as that supplied.
330 * @memberof FooTable.is
331 * @function type
332 * @param {*} value - The value to check the type of.
333 * @param {string} type - The type to check for.
334 * @returns {boolean}
335 */
336 F.is.type = function (value, type) {
337 return typeof value === type;
338 };
339
340 /**
341 * Checks if the value is defined.
342 * @memberof FooTable.is
343 * @function defined
344 * @param {*} value - The value to check is defined.
345 * @returns {boolean}
346 */
347 F.is.defined = function (value) {
348 return typeof value !== 'undefined';
349 };
350
351 /**
352 * Checks if the value is undefined.
353 * @memberof FooTable.is
354 * @function undef
355 * @param {*} value - The value to check is undefined.
356 * @returns {boolean}
357 */
358 F.is.undef = function (value) {
359 return typeof value === 'undefined';
360 };
361
362 /**
363 * Checks if the value is an array.
364 * @memberof FooTable.is
365 * @function array
366 * @param {*} value - The value to check.
367 * @returns {boolean}
368 */
369 F.is.array = function (value) {
370 return '[object Array]' === Object.prototype.toString.call(value);
371 };
372
373 /**
374 * Checks if the value is a date.
375 * @memberof FooTable.is
376 * @function date
377 * @param {*} value - The value to check.
378 * @returns {boolean}
379 */
380 F.is.date = function (value) {
381 return '[object Date]' === Object.prototype.toString.call(value) && !isNaN(value.getTime());
382 };
383
384 /**
385 * Checks if the value is a boolean.
386 * @memberof FooTable.is
387 * @function boolean
388 * @param {*} value - The value to check.
389 * @returns {boolean}
390 */
391 F.is.boolean = function (value) {
392 return '[object Boolean]' === Object.prototype.toString.call(value);
393 };
394
395 /**
396 * Checks if the value is a string.
397 * @memberof FooTable.is
398 * @function string
399 * @param {*} value - The value to check.
400 * @returns {boolean}
401 */
402 F.is.string = function (value) {
403 return '[object String]' === Object.prototype.toString.call(value);
404 };
405
406 /**
407 * Checks if the value is a number.
408 * @memberof FooTable.is
409 * @function number
410 * @param {*} value - The value to check.
411 * @returns {boolean}
412 */
413 F.is.number = function (value) {
414 return '[object Number]' === Object.prototype.toString.call(value) && !isNaN(value);
415 };
416
417 /**
418 * Checks if the value is a function.
419 * @memberof FooTable.is
420 * @function fn
421 * @param {*} value - The value to check.
422 * @returns {boolean}
423 */
424 F.is.fn = function (value) {
425 return (F.is.defined(window) && value === window.alert) || '[object Function]' === Object.prototype.toString.call(value);
426 };
427
428 /**
429 * Checks if the value is an error.
430 * @memberof FooTable.is
431 * @function error
432 * @param {*} value - The value to check.
433 * @returns {boolean}
434 */
435 F.is.error = function (value) {
436 return '[object Error]' === Object.prototype.toString.call(value);
437 };
438
439 /**
440 * Checks if the value is an object.
441 * @memberof FooTable.is
442 * @function object
443 * @param {*} value - The value to check.
444 * @returns {boolean}
445 */
446 F.is.object = function (value) {
447 return '[object Object]' === Object.prototype.toString.call(value);
448 };
449
450 /**
451 * Checks if the value is a hash.
452 * @memberof FooTable.is
453 * @function hash
454 * @param {*} value - The value to check.
455 * @returns {boolean}
456 */
457 F.is.hash = function (value) {
458 return F.is.object(value) && value.constructor === Object && !value.nodeType && !value.setInterval;
459 };
460
461 /**
462 * Checks if the supplied object is an HTMLElement
463 * @memberof FooTable.is
464 * @function element
465 * @param {object} obj - The object to check.
466 * @returns {boolean}
467 */
468 F.is.element = function (obj) {
469 return typeof HTMLElement === 'object'
470 ? obj instanceof HTMLElement
471 : obj && typeof obj === 'object' && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === 'string';
472 };
473
474 /**
475 * This is a simple check to determine if an object is a jQuery promise object. It simply checks the object has a "then" and "promise" function defined.
476 * The promise object is created as an object literal inside of jQuery.Deferred.
477 * It has no prototype, nor any other truly unique properties that could be used to distinguish it.
478 * This method should be a little more accurate than the internal jQuery one that simply checks for a "promise" method.
479 * @memberof FooTable.is
480 * @function promise
481 * @param {object} obj - The object to check.
482 * @returns {boolean}
483 */
484 F.is.promise = function(obj){
485 return F.is.object(obj) && F.is.fn(obj.then) && F.is.fn(obj.promise);
486 };
487
488 /**
489 * Checks if the supplied object is an instance of a jQuery object.
490 * @memberof FooTable.is
491 * @function jq
492 * @param {object} obj - The object to check.
493 * @returns {boolean}
494 */
495 F.is.jq = function(obj){
496 return F.is.defined(window.jQuery) && obj instanceof jQuery && obj.length > 0;
497 };
498
499 /**
500 * Checks if the supplied object is a moment.js date object.
501 * @memberof FooTable.is
502 * @function moment
503 * @param {object} obj - The object to check.
504 * @returns {boolean}
505 */
506 F.is.moment = function(obj){
507 return F.is.defined(window.moment) && F.is.object(obj) && F.is.boolean(obj._isAMomentObject)
508 };
509
510 /**
511 * Checks if the supplied value is an object and if it is empty.
512 * @memberof FooTable.is
513 * @function emptyObject
514 * @param {*} value - The value to check.
515 * @returns {boolean}
516 */
517 F.is.emptyObject = function(value){
518 if (!F.is.hash(value)) return false;
519 for(var prop in value) {
520 if(value.hasOwnProperty(prop))
521 return false;
522 }
523 return true;
524 };
525
526 /**
527 * Checks if the supplied value is an array and if it is empty.
528 * @memberof FooTable.is
529 * @function emptyArray
530 * @param {*} value - The value to check.
531 * @returns {boolean}
532 */
533 F.is.emptyArray = function(value){
534 return F.is.array(value) ? value.length === 0 : true;
535 };
536
537 /**
538 * Checks if the supplied value is a string and if it is empty.
539 * @memberof FooTable.is
540 * @function emptyString
541 * @param {*} value - The value to check.
542 * @returns {boolean}
543 */
544 F.is.emptyString = function(value){
545 return F.is.string(value) ? value.length === 0 : true;
546 };
547
548 })(FooTable);
549 (function (F) {
550 /**
551 * This namespace contains commonly used string utility methods.
552 * @namespace FooTable.str
553 */
554 F.str = {};
555
556 /**
557 * Checks if the supplied string contains the given substring.
558 * @memberof FooTable.str
559 * @function contains
560 * @param {string} str - The string to check.
561 * @param {string} contains - The string to check for.
562 * @param {boolean} [ignoreCase=false] - Whether or not to ignore casing when performing the check.
563 * @returns {boolean}
564 */
565 F.str.contains = function (str, contains, ignoreCase) {
566 if (F.is.emptyString(str) || F.is.emptyString(contains)) return false;
567 return contains.length <= str.length
568 && (ignoreCase ? str.toUpperCase().indexOf(contains.toUpperCase()) : str.indexOf(contains)) !== -1;
569 };
570
571 /**
572 * Checks if the supplied string contains the exact given substring.
573 * @memberof FooTable.str
574 * @function contains
575 * @param {string} str - The string to check.
576 * @param {string} contains - The string to check for.
577 * @param {boolean} [ignoreCase=false] - Whether or not to ignore casing when performing the check.
578 * @returns {boolean}
579 */
580 F.str.containsExact = function (str, contains, ignoreCase) {
581 if (F.is.emptyString(str) || F.is.emptyString(contains) || contains.length > str.length) return false;
582 return new RegExp('\\b'+ F.str.escapeRegExp(contains)+'\\b', ignoreCase ? 'i' : '').test(str);
583 };
584
585 /**
586 * Checks if the supplied string contains the given word.
587 * @memberof FooTable.str
588 * @function containsWord
589 * @param {string} str - The string to check.
590 * @param {string} word - The word to check for.
591 * @param {boolean} [ignoreCase=false] - Whether or not to ignore casing when performing the check.
592 * @returns {boolean}
593 */
594 F.str.containsWord = function(str, word, ignoreCase){
595 if (F.is.emptyString(str) || F.is.emptyString(word) || str.length < word.length)
596 return false;
597 var parts = str.split(/\W/);
598 for (var i = 0, len = parts.length; i < len; i++){
599 if (ignoreCase ? parts[i].toUpperCase() == word.toUpperCase() : parts[i] == word) return true;
600 }
601 return false;
602 };
603
604 /**
605 * Returns the remainder of a string split on the first index of the given substring.
606 * @memberof FooTable.str
607 * @function from
608 * @param {string} str - The string to split.
609 * @param {string} from - The substring to split on.
610 * @returns {string}
611 */
612 F.str.from = function (str, from) {
613 if (F.is.emptyString(str)) return str;
614 return F.str.contains(str, from) ? str.substring(str.indexOf(from) + 1) : str;
615 };
616
617 /**
618 * Checks if a string starts with the supplied prefix.
619 * @memberof FooTable.str
620 * @function startsWith
621 * @param {string} str - The string to check.
622 * @param {string} prefix - The prefix to check for.
623 * @returns {boolean}
624 */
625 F.str.startsWith = function (str, prefix) {
626 if (F.is.emptyString(str)) return str == prefix;
627 return str.slice(0, prefix.length) == prefix;
628 };
629
630 /**
631 * Takes the supplied string and converts it to camel case.
632 * @memberof FooTable.str
633 * @function toCamelCase
634 * @param {string} str - The string to camel case.
635 * @returns {string}
636 */
637 F.str.toCamelCase = function (str) {
638 if (F.is.emptyString(str)) return str;
639 if (str.toUpperCase() === str) return str.toLowerCase();
640 return str.replace(/^([A-Z])|[-\s_](\w)/g, function (match, p1, p2) {
641 if (F.is.string(p2)) return p2.toUpperCase();
642 return p1.toLowerCase();
643 });
644 };
645
646 /**
647 * Generates a random string 9 characters long using the optional prefix if supplied.
648 * @memberof FooTable.str
649 * @function random
650 * @param {string} [prefix] - The prefix to append to the 9 random characters.
651 * @returns {string}
652 */
653 F.str.random = function(prefix){
654 prefix = F.is.emptyString(prefix) ? '' : prefix;
655 return prefix + Math.random().toString(36).substr(2, 9);
656 };
657
658 /**
659 * Escapes a string for use in a regular expression.
660 * @memberof FooTable.str
661 * @function escapeRegExp
662 * @param {string} str - The string to escape.
663 * @returns {string}
664 */
665 F.str.escapeRegExp = function(str){
666 if (F.is.emptyString(str)) return str;
667 return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
668 };
669
670 })(FooTable);
671 (function (F) {
672 "use strict";
673
674 if (!Object.create) {
675 Object.create = (function () {
676 var Object = function () {};
677 return function (prototype) {
678 if (arguments.length > 1)
679 throw Error('Second argument not supported');
680
681 if (!F.is.object(prototype))
682 throw TypeError('Argument must be an object');
683
684 Object.prototype = prototype;
685 var result = new Object();
686 Object.prototype = null;
687 return result;
688 };
689 })();
690 }
691
692 /**
693 * This base implementation does nothing except provide access to the {@link FooTable.Class#extend} method.
694 * @constructs FooTable.Class
695 * @classdesc This class is based off of John Resig's [Simple JavaScript Inheritance]{@link http://ejohn.org/blog/simple-javascript-inheritance} but it has been updated to be ES 5.1
696 * compatible by implementing an [Object.create polyfill]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill}
697 * for older browsers.
698 * @see {@link http://ejohn.org/blog/simple-javascript-inheritance}
699 * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Polyfill}
700 * @returns {FooTable.Class}
701 */
702 function Class() {}
703
704 var __extendable__ = /xyz/.test(function () {xyz;}) ? /\b_super\b/ : /.*/;
705
706 // this._super() within the context of the new function is a pointer to the original function
707 // except if the hook param is specified then the this._super variable is the result of the original function
708 Class.__extend__ = function(proto, name, func, original){
709 // to all who venture here, here be dragons!
710 proto[name] = F.is.fn(original) && __extendable__.test(func) ?
711 (function (name, fn) {
712 return function () {
713 var tmp, ret;
714 tmp = this._super;
715 this._super = original;
716 ret = fn.apply(this, arguments);
717 this._super = tmp;
718 return ret;
719 };
720 })(name, func) : func;
721 };
722
723 /**
724 * Creates a new class that inherits from this class which in turn allows itself to be extended or if a name and function is supplied extends only that specific function on the class.
725 * @param {(object|string)} arg1 - An object containing any new methods/members to implement or the name of the method to extend.
726 * @param {function} arg2 - If the first argument is a method name then this is the new function to replace it with.
727 * @returns {FooTable.Class} A new class that inherits from the base class.
728 * @example <caption>The below shows an example of how to implement inheritance using this method.</caption>
729 * var Person = FooTable.Class.extend({
730 * construct: function(isDancing){
731 * this.dancing = isDancing;
732 * },
733 * dance: function(){
734 * return this.dancing;
735 * }
736 * });
737 *
738 * var Ninja = Person.extend({
739 * construct: function(){
740 * this._super( false );
741 * },
742 * dance: function(){
743 * // Call the inherited version of dance()
744 * return this._super();
745 * },
746 * swingSword: function(){
747 * return true;
748 * }
749 * });
750 *
751 * var p = new Person(true);
752 * p.dance(); // => true
753 *
754 * var n = new Ninja();
755 * n.dance(); // => false
756 * n.swingSword(); // => true
757 *
758 * // Should all be true
759 * p instanceof Person && p instanceof FooTable.Class &&
760 * n instanceof Ninja && n instanceof Person && n instanceof FooTable.Class
761 */
762 Class.extend = function (arg1 , arg2) {
763 var args = Array.prototype.slice.call(arguments);
764 arg1 = args.shift();
765 arg2 = args.shift();
766
767 function __extend__(proto, name, func, original){
768 // to all who venture here, here be dragons!
769 proto[name] = F.is.fn(original) && __extendable__.test(func) ?
770 (function (name, fn, ofn) {
771 return function () {
772 var tmp, ret;
773 tmp = this._super;
774 this._super = ofn;
775 ret = fn.apply(this, arguments);
776 this._super = tmp;
777 return ret;
778 };
779 })(name, func, original) : func;
780 }
781
782 if (F.is.hash(arg1)){
783 var proto = Object.create(this.prototype),
784 _super = this.prototype;
785 for (var name in arg1) {
786 if (name === '__ctor__') continue;
787 __extend__(proto, name, arg1[name], _super[name]);
788 }
789 var obj = F.is.fn(proto.__ctor__) ? proto.__ctor__ : function () {
790 if (!F.is.fn(this.construct))
791 throw new SyntaxError('FooTable class objects must be constructed with the "new" keyword.');
792 this.construct.apply(this, arguments);
793 };
794 proto.construct = F.is.fn(proto.construct) ? proto.construct : function(){};
795 obj.prototype = proto;
796 proto.constructor = obj;
797 obj.extend = Class.extend;
798 return obj;
799 } else if (F.is.string(arg1) && F.is.fn(arg2)) {
800 __extend__(this.prototype, arg1, arg2, this.prototype[arg1]);
801 }
802 };
803
804 F.Class = Class;
805
806 F.ClassFactory = F.Class.extend(/** @lends FooTable.ClassFactory */{
807 /**
808 * This is a simple factory for {@link FooTable.Class} objects allowing them to be registered using a friendly name
809 * and then new instances can be created using this friendly name.
810 * @constructs
811 * @extends FooTable.Class
812 * @returns {FooTable.ClassFactory}
813 * @this FooTable.ClassFactory
814 */
815 construct: function(){
816 /**
817 * An object containing all registered classes.
818 * @type {{}}
819 */
820 this.registered = {};
821 },
822 /**
823 * Checks if the factory contains a class registered using the supplied name.
824 * @instance
825 * @param {string} name - The name of the class to check.
826 * @returns {boolean}
827 * @this FooTable.ClassFactory
828 */
829 contains: function(name){
830 return F.is.defined(this.registered[name]);
831 },
832 /**
833 * Gets an array of all registered names.
834 * @instance
835 * @returns {Array.<string>}
836 * @this FooTable.ClassFactory
837 */
838 names: function(){
839 var names = [], name;
840 for (name in this.registered){
841 if (!this.registered.hasOwnProperty(name)) continue;
842 names.push(name);
843 }
844 return names;
845 },
846 /**
847 * Registers a class object using the supplied friendly name and priority. The priority is only taken into account when loading all registered classes
848 * using the {@link FooTable.ClassFactory#load} method.
849 * @instance
850 * @param {string} name - The friendly name of the class.
851 * @param {function} klass - The class to register.
852 * @param {number} priority - This determines the order that the class is created when using the {@link FooTable.ClassFactory#load} method, higher values are loaded first.
853 * @this FooTable.ClassFactory
854 */
855 register: function(name, klass, priority){
856 if (!F.is.string(name) || !F.is.fn(klass)) return;
857 var current = this.registered[name];
858 this.registered[name] = {
859 name: name,
860 klass: klass,
861 priority: F.is.number(priority) ? priority : (F.is.defined(current) ? current.priority : 0)
862 };
863 },
864 /**
865 * Creates new instances of all registered classes using there priority and the supplied arguments to return them in an array.
866 * @instance
867 * @param {object} subs - An object containing classes to substitute on load.
868 * @param {*} arg1 - The first argument to supply when creating new instances of all registered classes.
869 * @param {*} [argN...] - Any number of additional arguments to supply when creating new instances of all registered classes.
870 * @returns {Array.<FooTable.Class>}
871 * @this FooTable.ClassFactory
872 */
873 load: function(subs, arg1, argN){
874 var self = this, args = Array.prototype.slice.call(arguments), reg = [], loaded = [], name, klass;
875 subs = args.shift() || {};
876 for (name in self.registered){
877 if (!self.registered.hasOwnProperty(name)) continue;
878 var component = self.registered[name];
879 if (subs.hasOwnProperty(name)){
880 klass = subs[name];
881 if (F.is.string(klass)) klass = F.getFnPointer(subs[name]);
882 if (F.is.fn(klass)){
883 component = {name: name, klass: klass, priority: self.registered[name].priority};
884 }
885 }
886 reg.push(component);
887 }
888 for (name in subs){
889 if (!subs.hasOwnProperty(name) || self.registered.hasOwnProperty(name)) continue;
890 klass = subs[name];
891 if (F.is.string(klass)) klass = F.getFnPointer(subs[name]);
892 if (F.is.fn(klass)){
893 reg.push({name: name, klass: klass, priority: 0});
894 }
895 }
896 reg.sort(function(a, b){ return b.priority - a.priority; });
897 F.arr.each(reg, function(r){
898 if (F.is.fn(r.klass)){
899 loaded.push(self._make(r.klass, args));
900 }
901 });
902 return loaded;
903 },
904 /**
905 * Create a new instance of a single class using the supplied name and arguments.
906 * @instance
907 * @param {string} name - The name of the class to create.
908 * @param {*} arg1 - The first argument to supply to the new instance.
909 * @param {*} [argN...] - Any number of additional arguments to supply to the new instance.
910 * @returns {FooTable.Class}
911 * @this FooTable.ClassFactory
912 */
913 make: function(name, arg1, argN){
914 var self = this, args = Array.prototype.slice.call(arguments), reg;
915 name = args.shift();
916 reg = self.registered[name];
917 if (F.is.fn(reg.klass)){
918 return self._make(reg.klass, args);
919 }
920 return null;
921 },
922 /**
923 * This in effect lets us use the "apply" method on a function using the "new" keyword.
924 * @instance
925 * @private
926 * @param {function} klass
927 * @param args
928 * @returns {FooTable.Class}
929 * @this FooTable.ClassFactory
930 */
931 _make: function(klass, args){
932 function Class() {
933 return klass.apply(this, args);
934 }
935 Class.prototype = klass.prototype;
936 return new Class();
937 }
938 });
939
940 })(FooTable);
941 (function($, F){
942
943 /**
944 * Converts the supplied cssText string into JSON object.
945 * @param {string} cssText - The cssText to convert to a JSON object.
946 * @returns {object}
947 */
948 F.css2json = function(cssText){
949 if (F.is.emptyString(cssText)) return {};
950 var json = {}, props = cssText.split(';'), pair, key, value;
951 for (var i = 0, i_len = props.length; i < i_len; i++){
952 if (F.is.emptyString(props[i])) continue;
953 pair = props[i].split(':');
954 if (F.is.emptyString(pair[0]) || F.is.emptyString(pair[1])) continue;
955 key = F.str.toCamelCase($.trim(pair[0]));
956 value = $.trim(pair[1]);
957 json[key] = value;
958 }
959 return json;
960 };
961
962 /**
963 * Attempts to retrieve a function pointer using the given name.
964 * @param {string} functionName - The name of the function to fetch a pointer to.
965 * @returns {(function|object|null)}
966 */
967 F.getFnPointer = function(functionName){
968 if (F.is.emptyString(functionName)) return null;
969 var pointer = window,
970 parts = functionName.split('.');
971 F.arr.each(parts, function(part){
972 if (pointer[part]) pointer = pointer[part];
973 });
974 return F.is.fn(pointer) ? pointer : null;
975 };
976
977 /**
978 * Checks the value for function properties such as the {@link FooTable.Column#formatter} option which could also be specified using just the name
979 * and attempts to return the correct function pointer or null if none was found matching the value.
980 * @param {FooTable.Class} self - The class to use as the 'this' keyword within the context of the function.
981 * @param {(function|string)} value - The actual function or the name of the function for the property.
982 * @param {function} [def] - A default function to return if none is found.
983 * @returns {(function|null)}
984 */
985 F.checkFnValue = function(self, value, def){
986 def = F.is.fn(def) ? def : null;
987 function wrap(t, fn, d){
988 if (!F.is.fn(fn)) return d;
989 return function(){
990 return fn.apply(t, arguments);
991 };
992 }
993 return F.is.fn(value) ? wrap(self, value, def) : (F.is.type(value, 'string') ? wrap(self, F.getFnPointer(value), def) : def);
994 };
995
996 })(jQuery, FooTable);
997 (function($, F){
998
999 F.Cell = F.Class.extend(/** @lends FooTable.Cell */{
1000 /**
1001 * The cell class containing all the properties for cells.
1002 * @constructs
1003 * @extends FooTable.Class
1004 * @param {FooTable.Table} table - The root {@link FooTable.Table} this cell belongs to.
1005 * @param {FooTable.Row} row - The parent {@link FooTable.Row} this cell belongs to.
1006 * @param {FooTable.Column} column - The {@link FooTable.Column} this cell falls under.
1007 * @param {(*|HTMLElement|jQuery)} valueOrElement - Either the value or the element for the cell.
1008 * @returns {FooTable.Cell}
1009 * @this FooTable.Cell
1010 */
1011 construct: function (table, row, column, valueOrElement) {
1012 /**
1013 * The root {@link FooTable.Table} for the cell.
1014 * @instance
1015 * @readonly
1016 * @type {FooTable.Table}
1017 */
1018 this.ft = table;
1019 /**
1020 * The parent {@link FooTable.Row} for the cell.
1021 * @instance
1022 * @readonly
1023 * @type {FooTable.Row}
1024 */
1025 this.row = row;
1026 /**
1027 * The {@link FooTable.Column} this cell falls under.
1028 * @instance
1029 * @readonly
1030 * @type {FooTable.Column}
1031 */
1032 this.column = column;
1033 this.created = false;
1034 this.define(valueOrElement);
1035 },
1036 /**
1037 * This is supplied either the value or the cell element/jQuery object if it exists.
1038 * If supplied the element we need set the $el property and parse the value from it.
1039 * @instance
1040 * @protected
1041 * @param {(*|jQuery)} valueOrElement - The value or element to define the cell.
1042 * @this FooTable.Cell
1043 */
1044 define: function(valueOrElement){
1045 /**
1046 * The jQuery table cell object this instance wraps.
1047 * @instance
1048 * @type {jQuery}
1049 */
1050 this.$el = F.is.element(valueOrElement) || F.is.jq(valueOrElement) ? $(valueOrElement) : null;
1051 /**
1052 * The jQuery row object that represents this cell in the details table.
1053 * @type {jQuery}
1054 */
1055 this.$detail = null;
1056
1057 var hasOptions = F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options) && F.is.defined(valueOrElement.value);
1058
1059 /**
1060 * The value of the cell.
1061 * @instance
1062 * @type {*}
1063 */
1064 this.value = this.column.parser.call(this.column, F.is.jq(this.$el) ? this.$el : (hasOptions ? valueOrElement.value : valueOrElement), this.ft.o);
1065
1066 /**
1067 * Contains any options for the cell. These are the options supplied through the plugin constructor as part of the row object itself.
1068 * @type {object}
1069 */
1070 this.o = $.extend(true, {
1071 classes: null,
1072 style: null
1073 }, hasOptions ? valueOrElement.options : {});
1074 /**
1075 * An array of CSS classes for the cell.
1076 * @instance
1077 * @protected
1078 * @type {Array.<string>}
1079 */
1080 this.classes = F.is.jq(this.$el) && this.$el.attr('class') ? this.$el.attr('class').match(/\S+/g) : (F.is.array(this.o.classes) ? this.o.classes : (F.is.string(this.o.classes) ? this.o.classes.match(/\S+/g) : []));
1081 /**
1082 * The inline styles for the cell.
1083 * @instance
1084 * @protected
1085 * @type {object}
1086 */
1087 this.style = F.is.jq(this.$el) && this.$el.attr('style') ? F.css2json(this.$el.attr('style')) : (F.is.hash(this.o.style) ? this.o.style : (F.is.string(this.o.style) ? F.css2json(this.o.style) : {}));
1088 },
1089 /**
1090 * After the cell has been defined this ensures that the $el and #detail properties are jQuery objects by either creating or updating them.
1091 * @instance
1092 * @protected
1093 * @this FooTable.Cell
1094 */
1095 $create: function(){
1096 if (this.created) return;
1097 (this.$el = F.is.jq(this.$el) ? this.$el : $('<td/>'))
1098 .data('value', this.value)
1099 .contents().detach().end()
1100 .append(this.format(this.value));
1101
1102 this._setClasses(this.$el);
1103 this._setStyle(this.$el);
1104
1105 this.$detail = $('<tr/>').addClass(this.row.classes.join(' '))
1106 .data('__FooTableCell__', this)
1107 .append($('<th/>'))
1108 .append($('<td/>'));
1109
1110 this.created = true;
1111 },
1112 /**
1113 * Collapses this cell and displays it in the details row.
1114 * @instance
1115 * @protected
1116 */
1117 collapse: function(){
1118 if (!this.created) return;
1119 this.$detail.children('th').html(this.column.title);
1120 this.$el.clone()
1121 .attr('id', this.$el.attr('id') ? this.$el.attr('id') + '-detail' : undefined)
1122 .css('display', 'table-cell')
1123 .html('')
1124 .append(this.$el.contents().detach())
1125 .replaceAll(this.$detail.children('td').first());
1126
1127 if (!F.is.jq(this.$detail.parent()))
1128 this.$detail.appendTo(this.row.$details.find('.footable-details > tbody'));
1129 },
1130 /**
1131 * Restores this cell from a detail row back into the normal row.
1132 * @instance
1133 * @protected
1134 */
1135 restore: function(){
1136 if (!this.created) return;
1137 if (F.is.jq(this.$detail.parent())){
1138 var $cell = this.$detail.children('td').first();
1139 this.$el
1140 .attr('class', $cell.attr('class'))
1141 .attr('style', $cell.attr('style'))
1142 .css('display', (this.column.hidden || !this.column.visible) ? 'none' : 'table-cell')
1143 .append($cell.contents().detach());
1144 }
1145 this.$detail.detach();
1146 },
1147 /**
1148 * Helper method to call this cell's column parser function supplying the required parameters.
1149 * @instance
1150 * @protected
1151 * @returns {*}
1152 * @see FooTable.Column#parser
1153 * @this FooTable.Cell
1154 */
1155 parse: function(){
1156 return this.column.parser.call(this.column, this.$el, this.ft.o);
1157 },
1158 /**
1159 * Helper method to call this cell's column formatter function using the supplied value and any additional required parameters.
1160 * @instance
1161 * @protected
1162 * @param {*} value - The value to format.
1163 * @returns {(string|HTMLElement|jQuery)}
1164 * @see FooTable.Column#formatter
1165 * @this FooTable.Cell
1166 */
1167 format: function(value){
1168 return this.column.formatter.call(this.column, value, this.ft.o, this.row.value);
1169 },
1170 /**
1171 * Allows easy access to getting or setting the cell's value. If the value is set all associated properties are also updated along with the actual element.
1172 * Using this method also allows us to supply an object containing options and the value for the cell.
1173 * @instance
1174 * @param {*} [value] - The value to set for the cell. If not supplied the current value of the cell is returned.
1175 * @param {boolean} [redraw=true] - Whether or not to redraw the row once the value has been set.
1176 * @param {boolean} [redrawSelf=true] - Whether or not to redraw the cell itself once the value has been set, if `false` this will override the supplied `redraw` value and prevent the row from redrawing as well.
1177 * @returns {(*|undefined)}
1178 * @this FooTable.Cell
1179 */
1180 val: function(value, redraw, redrawSelf){
1181 if (F.is.undef(value)){
1182 // get
1183 return this.value;
1184 }
1185 // set
1186 var self = this, hasOptions = F.is.hash(value) && F.is.hash(value.options) && F.is.defined(value.value);
1187 this.o = $.extend(true, {
1188 classes: self.classes,
1189 style: self.style
1190 }, hasOptions ? value.options : {});
1191
1192 this.value = hasOptions ? value.value : value;
1193 this.classes = F.is.array(this.o.classes) ? this.o.classes : (F.is.string(this.o.classes) ? this.o.classes.match(/\S+/g) : []);
1194 this.style = F.is.hash(this.o.style) ? this.o.style : (F.is.string(this.o.style) ? F.css2json(this.o.style) : {});
1195
1196 redrawSelf = F.is.boolean(redrawSelf) ? redrawSelf : true;
1197 if (this.created && redrawSelf){
1198 this.$el.data('value', this.value).empty();
1199
1200 var $detail = this.$detail.children('td').first().empty(),
1201 $target = F.is.jq(this.$detail.parent()) ? $detail : this.$el;
1202
1203 $target.append(this.format(this.value));
1204
1205 this._setClasses($target);
1206 this._setStyle($target);
1207
1208 if (F.is.boolean(redraw) ? redraw : true) this.row.draw();
1209 }
1210 },
1211 _setClasses: function($el){
1212 var hasColClasses = !F.is.emptyArray(this.column.classes),
1213 hasClasses = !F.is.emptyArray(this.classes),
1214 classes = null;
1215 $el.removeAttr('class');
1216 if (!hasColClasses && !hasClasses) return;
1217 if (hasColClasses && hasClasses){
1218 classes = this.classes.concat(this.column.classes).join(' ');
1219 } else if (hasColClasses) {
1220 classes = this.column.classes.join(' ');
1221 } else if (hasClasses){
1222 classes = this.classes.join(' ');
1223 }
1224 if (!F.is.emptyString(classes)){
1225 $el.addClass(classes);
1226 }
1227 },
1228 _setStyle: function($el){
1229 var hasColStyle = !F.is.emptyObject(this.column.style),
1230 hasStyle = !F.is.emptyObject(this.style),
1231 style = null;
1232 $el.removeAttr('style');
1233 if (!hasColStyle && !hasStyle) return;
1234 if (hasColStyle && hasStyle){
1235 style = $.extend({}, this.column.style, this.style);
1236 } else if (hasColStyle) {
1237 style = this.column.style;
1238 } else if (hasStyle){
1239 style = this.style;
1240 }
1241 if (F.is.hash(style)){
1242 $el.css(style);
1243 }
1244 }
1245 });
1246
1247 })(jQuery, FooTable);
1248 (function($, F){
1249
1250 F.Column = F.Class.extend(/** @lends FooTable.Column */{
1251 /**
1252 * The column class containing all the properties for columns. All members marked as "readonly" should not be used when defining {@link FooTable.Defaults#columns}.
1253 * @constructs
1254 * @extends FooTable.Class
1255 * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this component belongs to.
1256 * @param {object} definition - An object containing all the properties to set for the column.
1257 * @param {string} [type] - The type of column, "text" by default.
1258 * @returns {FooTable.Column}
1259 * @this FooTable.Column
1260 */
1261 construct: function(instance, definition, type){
1262 /**
1263 * The root {@link FooTable.Table} for the column.
1264 * @instance
1265 * @readonly
1266 * @type {FooTable.Table}
1267 */
1268 this.ft = instance;
1269 /**
1270 * The type of data displayed by the column.
1271 * @instance
1272 * @readonly
1273 * @type {string}
1274 */
1275 this.type = F.is.emptyString(type) ? 'text' : type;
1276 /**
1277 * Whether or not the column was parsed from a standard table row containing data instead of from an actual header row.
1278 * @instance
1279 * @readonly
1280 * @type {boolean}
1281 */
1282 this.virtual = F.is.boolean(definition.virtual) ? definition.virtual : false;
1283 /**
1284 * The jQuery cell object for the column header.
1285 * @instance
1286 * @readonly
1287 * @type {jQuery}
1288 */
1289 this.$el = F.is.jq(definition.$el) ? definition.$el : null;
1290 /**
1291 * The index of the column in the table. This is set by the plugin during initialization.
1292 * @instance
1293 * @readonly
1294 * @type {number}
1295 * @default -1
1296 */
1297 this.index = F.is.number(definition.index) ? definition.index : -1;
1298 /**
1299 * Whether or not this in an internal only column.
1300 * @instance
1301 * @readonly
1302 * @type {boolean}
1303 * @description Internal columns or there cells will not be returned when calling methods such as `FooTable.Row#val`.
1304 */
1305 this.internal = false;
1306 this.define(definition);
1307 this.$create();
1308 },
1309 /**
1310 * This is supplied the column definition in the form of a simple object created by merging options supplied via the plugin constructor with those parsed from the DOM.
1311 * @instance
1312 * @protected
1313 * @param {object} definition - The object containing the column definition.
1314 * @this FooTable.Column
1315 */
1316 define: function(definition){
1317 /**
1318 * Whether or not this column is hidden from view and appears in the details row.
1319 * @type {boolean}
1320 * @default false
1321 */
1322 this.hidden = F.is.boolean(definition.hidden) ? definition.hidden : false;
1323 /**
1324 * Whether or not this column is completely hidden from view and will not appear in the details row.
1325 * @type {boolean}
1326 * @default true
1327 */
1328 this.visible = F.is.boolean(definition.visible) ? definition.visible : true;
1329
1330 /**
1331 * The name of the column. This name must correspond to the property name of the JSON row data.
1332 * @type {string}
1333 * @default null
1334 */
1335 this.name = F.is.string(definition.name) ? definition.name : null;
1336 if (this.name == null) this.name = 'col'+(definition.index+1);
1337 /**
1338 * The title to display in the column header, this can be HTML.
1339 * @type {string}
1340 * @default null
1341 */
1342 this.title = F.is.string(definition.title) ? definition.title : null;
1343 if (!this.virtual && this.title == null && F.is.jq(this.$el)) this.title = this.$el.html();
1344 if (this.title == null) this.title = 'Column '+(definition.index+1);
1345 /**
1346 * The styles to apply to all cells in this column.
1347 * @type {object}
1348 */
1349 this.style = F.is.hash(definition.style) ? definition.style : (F.is.string(definition.style) ? F.css2json(definition.style) : {});
1350 /**
1351 * The classes to apply to all cells in this column.
1352 * @type {Array.<string>}
1353 */
1354 this.classes = F.is.array(definition.classes) ? definition.classes : (F.is.string(definition.classes) ? definition.classes.match(/\S+/g) : []);
1355
1356 // override any default functions ensuring when they are executed "this" within the context of the function points to the instance of this object.
1357 this.parser = F.checkFnValue(this, definition.parser, this.parser);
1358 this.formatter = F.checkFnValue(this, definition.formatter, this.formatter);
1359 },
1360 /**
1361 * After the column has been defined this ensures that the $el property is a jQuery object by either creating or updating the current value.
1362 * @instance
1363 * @protected
1364 * @this FooTable.Column
1365 */
1366 $create: function(){
1367 (this.$el = !this.virtual && F.is.jq(this.$el) ? this.$el : $('<th/>')).html(this.title).addClass(this.classes.join(' ')).css(this.style);
1368 },
1369 /**
1370 * This is supplied either the cell value or jQuery object to parse. Any value can be returned from this method and will be provided to the {@link FooTable.Column#format} function
1371 * to generate the cell contents.
1372 * @instance
1373 * @protected
1374 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
1375 * @returns {string}
1376 * @this FooTable.Column
1377 */
1378 parser: function(valueOrElement){
1379 if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){ // use jQuery to get the value
1380 var data = $(valueOrElement).data('value');
1381 return F.is.defined(data) ? data : $(valueOrElement).html();
1382 }
1383 if (F.is.defined(valueOrElement) && valueOrElement != null) return valueOrElement+''; // use the native toString of the value
1384 return null; // otherwise we have no value so return null
1385 },
1386 /**
1387 * This is supplied the value retrieved from the {@link FooTable.Column#parse} function and must return a string, HTMLElement or jQuery object.
1388 * The return value from this function is what is displayed in the cell in the table.
1389 * @instance
1390 * @protected
1391 * @param {string} value - The value to format.
1392 * @param {object} options - The current plugin options.
1393 * @param {object} rowData - An object containing the current row data.
1394 * @returns {(string|HTMLElement|jQuery)}
1395 * @this FooTable.Column
1396 */
1397 formatter: function(value, options, rowData){
1398 return value == null ? '' : value;
1399 },
1400 /**
1401 * Creates a cell for this column from the supplied {@link FooTable.Row} object. This allows different column types to return different types of cells.
1402 * @instance
1403 * @protected
1404 * @param {FooTable.Row} row - The row to create the cell from.
1405 * @returns {FooTable.Cell}
1406 * @this FooTable.Column
1407 */
1408 createCell: function(row){
1409 var element = F.is.jq(row.$el) ? row.$el.children('td,th').get(this.index) : null,
1410 data = F.is.hash(row.value) ? row.value[this.name] : null;
1411 return new F.Cell(this.ft, row, this, element || data);
1412 }
1413 });
1414
1415 F.columns = new F.ClassFactory();
1416
1417 F.columns.register('text', F.Column);
1418
1419 })(jQuery, FooTable);
1420 (function ($, F) {
1421
1422 F.Component = F.Class.extend(/** @lends FooTable.Component */{
1423 /**
1424 * The base class for all FooTable components.
1425 * @constructs
1426 * @extends FooTable.Class
1427 * @param {FooTable.Table} instance - The parent {@link FooTable.Table} object for the component.
1428 * @param {boolean} enabled - Whether or not the component is enabled.
1429 * @throws {TypeError} The instance parameter must be an instance of {@link FooTable.Table}.
1430 * @returns {FooTable.Component}
1431 */
1432 construct: function (instance, enabled) {
1433 if (!(instance instanceof F.Table))
1434 throw new TypeError('The instance parameter must be an instance of FooTable.Table.');
1435
1436 /**
1437 * The parent {@link FooTable.Table} for the component.
1438 * @type {FooTable.Table}
1439 */
1440 this.ft = instance;
1441 /**
1442 * Whether or not this component is enabled. Disabled components only have there preinit method called allowing for this value to be overridden.
1443 * @type {boolean}
1444 */
1445 this.enabled = F.is.boolean(enabled) ? enabled : false;
1446 },
1447 /**
1448 * The preinit method is called during the parent {@link FooTable.Table} constructor call.
1449 * @param {object} data - The jQuery.data() object of the root table.
1450 * @instance
1451 * @protected
1452 * @function
1453 */
1454 preinit: function(data){},
1455 /**
1456 * The init method is called during the parent {@link FooTable.Table} constructor call.
1457 * @instance
1458 * @protected
1459 * @function
1460 */
1461 init: function(){},
1462 /**
1463 * This method is called from the {@link FooTable.Table#destroy} method.
1464 * @instance
1465 * @protected
1466 * @function
1467 */
1468 destroy: function(){},
1469 /**
1470 * This method is called from the {@link FooTable.Table#draw} method.
1471 * @instance
1472 * @protected
1473 * @function
1474 */
1475 predraw: function(){},
1476 /**
1477 * This method is called from the {@link FooTable.Table#draw} method.
1478 * @instance
1479 * @protected
1480 * @function
1481 */
1482 draw: function(){},
1483 /**
1484 * This method is called from the {@link FooTable.Table#draw} method.
1485 * @instance
1486 * @protected
1487 * @function
1488 */
1489 postdraw: function(){}
1490 });
1491
1492 F.components = new F.ClassFactory();
1493
1494 })(jQuery, FooTable);
1495 (function ($, F) {
1496 /**
1497 * Contains all the available options for the FooTable plugin.
1498 * @name FooTable.Defaults
1499 * @function
1500 * @constructor
1501 * @returns {FooTable.Defaults}
1502 */
1503 F.Defaults = function () {
1504 /**
1505 * Whether or not events raised using the {@link FooTable.Table#raise} method are propagated up the DOM. By default this is set to false and all events bubble up the DOM as per usual
1506 * however the reason for this option is if we have nested tables. If false the parent table would receive all the events raised by it's children and any handlers bound to both the
1507 * parent and child would be triggered which is not the desired behavior.
1508 * @type {boolean}
1509 * @default false
1510 */
1511 this.stopPropagation = false;
1512 /**
1513 * An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).
1514 * @type {object.<string, function>}
1515 * @default NULL
1516 * @example <caption>This example shows how to pass an object containing the events and handlers.</caption>
1517 * "on": {
1518 * "click": function(e){
1519 * // bind a custom click event to do something whenever the table is clicked
1520 * },
1521 * "init.ft.table": function(e, ft){
1522 * // bind to the FooTable initialize event to do something
1523 * }
1524 * }
1525 */
1526 this.on = null;
1527 };
1528
1529 /**
1530 * Contains all the default options for the plugin.
1531 * @type {FooTable.Defaults}
1532 */
1533 F.defaults = new F.Defaults();
1534
1535 })(jQuery, FooTable);
1536 (function($, F){
1537
1538 F.Row = F.Class.extend(/** @lends FooTable.Row */{
1539 /**
1540 * The row class containing all the properties for a row and its' cells.
1541 * @constructs
1542 * @extends FooTable.Class
1543 * @param {FooTable.Table} table - The parent {@link FooTable.Table} this component belongs to.
1544 * @param {Array.<FooTable.Column>} columns - The array of {@link FooTable.Column} for this row.
1545 * @param {(*|HTMLElement|jQuery)} dataOrElement - Either the data for the row (create) or the element (parse) for the row.
1546 * @returns {FooTable.Row}
1547 */
1548 construct: function (table, columns, dataOrElement) {
1549 /**
1550 * The {@link FooTable.Table} for the row.
1551 * @type {FooTable.Table}
1552 */
1553 this.ft = table;
1554 /**
1555 * The array of {@link FooTable.Column} for this row.
1556 * @type {Array.<FooTable.Column>}
1557 */
1558 this.columns = columns;
1559
1560 this.created = false;
1561 this.define(dataOrElement);
1562 },
1563 /**
1564 * This is supplied either the object containing the values for the row or the row element/jQuery object if it exists.
1565 * If supplied the element we need to set the $el property and parse the cells from it using the column index.
1566 * If we have an object we parse the cells from it using the column name.
1567 * @param {(object|jQuery)} dataOrElement - The row object or element to define the row.
1568 */
1569 define: function(dataOrElement){
1570 /**
1571 * The jQuery table row object this instance wraps.
1572 * @instance
1573 * @protected
1574 * @type {jQuery}
1575 */
1576 this.$el = F.is.element(dataOrElement) || F.is.jq(dataOrElement) ? $(dataOrElement) : null;
1577 /**
1578 * The jQuery toggle element for the row.
1579 * @instance
1580 * @protected
1581 * @type {jQuery}
1582 */
1583 this.$toggle = $('<span/>', {'class': 'footable-toggle fooicon fooicon-plus'});
1584
1585 var isObj = F.is.hash(dataOrElement),
1586 hasOptions = isObj && F.is.hash(dataOrElement.options) && F.is.hash(dataOrElement.value);
1587
1588 /**
1589 * The value of the row.
1590 * @instance
1591 * @protected
1592 * @type {Object}
1593 */
1594 this.value = isObj ? (hasOptions ? dataOrElement.value : dataOrElement) : null;
1595
1596 /**
1597 * Contains any options for the row.
1598 * @type {object}
1599 */
1600 this.o = $.extend(true, {
1601 expanded: false,
1602 classes: null,
1603 style: null
1604 }, hasOptions ? dataOrElement.options : {});
1605
1606 /**
1607 * Whether or not this row is expanded and will display it's detail row when there are any hidden columns.
1608 * @instance
1609 * @protected
1610 * @type {boolean}
1611 */
1612 this.expanded = F.is.jq(this.$el) ? (this.$el.data('expanded') || this.o.expanded) : this.o.expanded;
1613 /**
1614 * An array of CSS classes for the row.
1615 * @instance
1616 * @protected
1617 * @type {Array.<string>}
1618 */
1619 this.classes = F.is.jq(this.$el) && this.$el.attr('class') ? this.$el.attr('class').match(/\S+/g) : (F.is.array(this.o.classes) ? this.o.classes : (F.is.string(this.o.classes) ? this.o.classes.match(/\S+/g) : []));
1620 /**
1621 * The inline styles for the row.
1622 * @instance
1623 * @protected
1624 * @type {object}
1625 */
1626 this.style = F.is.jq(this.$el) && this.$el.attr('style') ? F.css2json(this.$el.attr('style')) : (F.is.hash(this.o.style) ? this.o.style : (F.is.string(this.o.style) ? F.css2json(this.o.style) : {}));
1627
1628 /**
1629 * The cells array. This is populated before the call to the {@link FooTable.Row#$create} method.
1630 * @instance
1631 * @type {Array.<FooTable.Cell>}
1632 */
1633 this.cells = this.createCells();
1634
1635 // this ensures the value contains the parsed cell values and not the supplied values
1636 var self = this;
1637 self.value = {};
1638 F.arr.each(self.cells, function(cell){
1639 self.value[cell.column.name] = cell.val();
1640 });
1641 },
1642 /**
1643 * After the row has been defined this ensures that the $el property is a jQuery object by either creating or updating the current value.
1644 * @instance
1645 * @protected
1646 * @this FooTable.Row
1647 */
1648 $create: function(){
1649 if (this.created) return;
1650 (this.$el = F.is.jq(this.$el) ? this.$el : $('<tr/>'))
1651 .data('__FooTableRow__', this);
1652
1653 this._setClasses(this.$el);
1654 this._setStyle(this.$el);
1655
1656 if (this.ft.rows.toggleColumn == 'last') this.$toggle.addClass('last-column');
1657
1658 this.$details = $('<tr/>', { 'class': 'footable-detail-row' })
1659 .append($('<td/>', { colspan: this.ft.columns.visibleColspan })
1660 .append($('<table/>', { 'class': 'footable-details ' + this.ft.classes.join(' ') })
1661 .append('<tbody/>')));
1662
1663 var self = this;
1664 F.arr.each(self.cells, function(cell){
1665 if (!cell.created) cell.$create();
1666 self.$el.append(cell.$el);
1667 });
1668 self.$el.off('click.ft.row').on('click.ft.row', { self: self }, self._onToggle);
1669 this.created = true;
1670 },
1671 /**
1672 * This is called during the construct method and uses the current column definitions to create an array of {@link FooTable.Cell} objects for the row.
1673 * @instance
1674 * @protected
1675 * @returns {Array.<FooTable.Cell>}
1676 * @this FooTable.Row
1677 */
1678 createCells: function(){
1679 var self = this;
1680 return F.arr.map(self.columns, function(col){
1681 return col.createCell(self);
1682 });
1683 },
1684 /**
1685 * Allows easy access to getting or setting the row's data. If the data is set all associated properties are also updated along with the actual element.
1686 * Using this method also allows us to supply an object containing options and the data for the row at the same time.
1687 * @instance
1688 * @param {object} [data] - The data to set for the row. If not supplied the current value of the row is returned.
1689 * @param {boolean} [redraw=true] - Whether or not to redraw the table once the value has been set.
1690 * @param {boolean} [redrawSelf=true] - Whether or not to redraw the row itself once the value has been set, if `false` this will override the supplied `redraw` value and prevent the table from redrawing as well.
1691 * @returns {(*|undefined)}
1692 */
1693 val: function(data, redraw, redrawSelf){
1694 var self = this;
1695 if (!F.is.hash(data)){
1696 // get - check the value property and build it from the cells if required.
1697 if (!F.is.hash(this.value) || F.is.emptyObject(this.value)){
1698 this.value = {};
1699 F.arr.each(this.cells, function(cell){
1700 if (!cell.column.internal){
1701 self.value[cell.column.name] = cell.val();
1702 }
1703 });
1704 }
1705 return this.value;
1706 }
1707 // set
1708 this.collapse(false);
1709 var isObj = F.is.hash(data),
1710 hasOptions = isObj && F.is.hash(data.options) && F.is.hash(data.value);
1711
1712 this.o = $.extend(true, {
1713 expanded: self.expanded,
1714 classes: self.classes,
1715 style: self.style
1716 }, hasOptions ? data.options : {});
1717
1718 this.expanded = this.o.expanded;
1719 this.classes = F.is.array(this.o.classes) ? this.o.classes : (F.is.string(this.o.classes) ? this.o.classes.match(/\S+/g) : []);
1720 this.style = F.is.hash(this.o.style) ? this.o.style : (F.is.string(this.o.style) ? F.css2json(this.o.style) : {});
1721 if (isObj) {
1722 if ( hasOptions ) data = data.value;
1723 if (F.is.hash(this.value)){
1724 for (var prop in data) {
1725 if (!data.hasOwnProperty(prop)) continue;
1726 this.value[prop] = data[prop];
1727 }
1728 } else {
1729 this.value = data;
1730 }
1731 } else {
1732 this.value = null;
1733 }
1734
1735 redrawSelf = F.is.boolean(redrawSelf) ? redrawSelf : true;
1736 F.arr.each(this.cells, function(cell){
1737 if (!cell.column.internal && F.is.defined(self.value[cell.column.name])){
1738 cell.val(self.value[cell.column.name], false, redrawSelf);
1739 }
1740 });
1741
1742 if (this.created && redrawSelf){
1743 this._setClasses(this.$el);
1744 this._setStyle(this.$el);
1745 if (F.is.boolean(redraw) ? redraw : true) this.draw();
1746 }
1747 },
1748 _setClasses: function($el){
1749 var hasClasses = !F.is.emptyArray(this.classes),
1750 classes = null;
1751 $el.removeAttr('class');
1752 if (!hasClasses) return;
1753 else classes = this.classes.join(' ');
1754 if (!F.is.emptyString(classes)){
1755 $el.addClass(classes);
1756 }
1757 },
1758 _setStyle: function($el){
1759 var hasStyle = !F.is.emptyObject(this.style),
1760 style = null;
1761 $el.removeAttr('style');
1762 if (!hasStyle) return;
1763 else style = this.style;
1764 if (F.is.hash(style)){
1765 $el.css(style);
1766 }
1767 },
1768 /**
1769 * Sets the current row to an expanded state displaying any hidden columns in a detail row just below it.
1770 * @instance
1771 * @fires FooTable.Row#"expand.ft.row"
1772 */
1773 expand: function(){
1774 if (!this.created) return;
1775 var self = this;
1776 /**
1777 * The expand.ft.row event is raised before the the row is expanded.
1778 * Calling preventDefault on this event will stop the row being expanded.
1779 * @event FooTable.Row#"expand.ft.row"
1780 * @param {jQuery.Event} e - The jQuery.Event object for the event.
1781 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
1782 * @param {FooTable.Row} row - The row about to be expanded.
1783 */
1784 self.ft.raise('expand.ft.row',[self]).then(function(){
1785 self.__hidden__ = F.arr.map(self.cells, function(cell){
1786 return cell.column.hidden && cell.column.visible ? cell : null;
1787 });
1788
1789 if (self.__hidden__.length > 0){
1790 self.$details.insertAfter(self.$el)
1791 .children('td').first()
1792 .attr('colspan', self.ft.columns.visibleColspan);
1793
1794 F.arr.each(self.__hidden__, function(cell){
1795 cell.collapse();
1796 });
1797 }
1798 self.$el.attr('data-expanded', true);
1799 self.$toggle.removeClass('fooicon-plus').addClass('fooicon-minus');
1800 self.expanded = true;
1801 self.ft.raise('expanded.ft.row', [self]);
1802 });
1803 },
1804 /**
1805 * Sets the current row to a collapsed state removing the detail row if it exists.
1806 * @instance
1807 * @param {boolean} [setExpanded] - Whether or not to set the {@link FooTable.Row#expanded} property to false.
1808 * @fires FooTable.Row#"collapse.ft.row"
1809 */
1810 collapse: function(setExpanded){
1811 if (!this.created) return;
1812 var self = this;
1813 /**
1814 * The collapse.ft.row event is raised before the the row is collapsed.
1815 * Calling preventDefault on this event will stop the row being collapsed.
1816 * @event FooTable.Row#"collapse.ft.row"
1817 * @param {jQuery.Event} e - The jQuery.Event object for the event.
1818 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
1819 * @param {FooTable.Row} row - The row about to be expanded.
1820 */
1821 self.ft.raise('collapse.ft.row',[self]).then(function(){
1822 F.arr.each(self.__hidden__, function(cell){
1823 cell.restore();
1824 });
1825 self.$details.detach();
1826 self.$el.removeAttr('data-expanded');
1827 self.$toggle.removeClass('fooicon-minus').addClass('fooicon-plus');
1828 if (F.is.boolean(setExpanded) ? setExpanded : true) self.expanded = false;
1829 self.ft.raise('collapsed.ft.row', [self]);
1830 });
1831 },
1832 /**
1833 * Prior to drawing this moves the details contents back to there original cells and detaches the toggle element from the row.
1834 * @instance
1835 * @param {boolean} [detach] - Whether or not to detach the row.
1836 * @this FooTable.Row
1837 */
1838 predraw: function(detach){
1839 if (this.created){
1840 if (this.expanded){
1841 this.collapse(false);
1842 }
1843 this.$toggle.detach();
1844 detach = F.is.boolean(detach) ? detach : true;
1845 if (detach) this.$el.detach();
1846 }
1847 },
1848 /**
1849 * Draws the current row and cells.
1850 * @instance
1851 * @this FooTable.Row
1852 */
1853 draw: function($parent){
1854 if (!this.created) this.$create();
1855 if (F.is.jq($parent)) $parent.append(this.$el);
1856 var self = this;
1857 F.arr.each(self.cells, function(cell){
1858 cell.$el.css('display', (cell.column.hidden || !cell.column.visible ? 'none' : 'table-cell'));
1859 if (self.ft.rows.showToggle && self.ft.columns.hasHidden){
1860 if ((self.ft.rows.toggleColumn == 'first' && cell.column.index == self.ft.columns.firstVisibleIndex)
1861 || (self.ft.rows.toggleColumn == 'last' && cell.column.index == self.ft.columns.lastVisibleIndex)) {
1862 cell.$el.prepend(self.$toggle);
1863 }
1864 }
1865 cell.$el.add(cell.column.$el).removeClass('footable-first-visible footable-last-visible');
1866 if (cell.column.index == self.ft.columns.firstVisibleIndex){
1867 cell.$el.add(cell.column.$el).addClass('footable-first-visible');
1868 }
1869 if (cell.column.index == self.ft.columns.lastVisibleIndex){
1870 cell.$el.add(cell.column.$el).addClass('footable-last-visible');
1871 }
1872 });
1873 if (this.expanded){
1874 this.expand();
1875 }
1876 },
1877 /**
1878 * Toggles the row between it's expanded and collapsed state if there are hidden columns.
1879 * @instance
1880 * @this FooTable.Row
1881 */
1882 toggle: function(){
1883 if (this.created && this.ft.columns.hasHidden){
1884 if (this.expanded) this.collapse();
1885 else this.expand();
1886 }
1887 },
1888 /**
1889 * Handles the toggle click event for rows.
1890 * @instance
1891 * @param {jQuery.Event} e - The jQuery.Event object for the click event.
1892 * @private
1893 * @this jQuery
1894 */
1895 _onToggle: function (e) {
1896 var self = e.data.self;
1897 // only execute the toggle if the event.target is one of the approved initiators
1898 if ($(e.target).is(self.ft.rows.toggleSelector)){
1899 self.toggle();
1900 }
1901 }
1902 });
1903
1904 })(jQuery, FooTable);
1905
1906 (function ($, F) {
1907
1908 /**
1909 * An array of all currently loaded instances of the plugin.
1910 * @protected
1911 * @readonly
1912 * @type {Array.<FooTable.Table>}
1913 */
1914 F.instances = [];
1915
1916 F.Table = F.Class.extend(/** @lends FooTable.Table */{
1917 /**
1918 * This class is the core of the plugin and drives the logic of all components.
1919 * @constructs
1920 * @this FooTable.Table
1921 * @extends FooTable.Class
1922 * @param {(HTMLTableElement|jQuery)} element - The element or jQuery table object to bind the plugin to.
1923 * @param {object} options - The options to initialize the plugin with.
1924 * @param {function} [ready] - A callback function to execute once the plugin is initialized.
1925 * @returns {FooTable.Table}
1926 */
1927 construct: function (element, options, ready) {
1928 //BEGIN MEMBERS
1929 /**
1930 * The timeout ID for the resize event.
1931 * @instance
1932 * @private
1933 * @type {?number}
1934 */
1935 this._resizeTimeout = null;
1936 /**
1937 * The ID of the FooTable instance.
1938 * @instance
1939 * @type {number}
1940 */
1941 this.id = F.instances.push(this);
1942 /**
1943 * Whether or not the plugin and all components and add-ons are fully initialized.
1944 * @instance
1945 * @type {boolean}
1946 */
1947 this.initialized = false;
1948 /**
1949 * The jQuery table object the plugin is bound to.
1950 * @instance
1951 * @type {jQuery}
1952 */
1953 this.$el = (F.is.jq(element) ? element : $(element)).first(); // ensure one table, one instance
1954 /**
1955 * A loader jQuery instance
1956 * @instance
1957 * @type {jQuery}
1958 */
1959 this.$loader = $('<div/>', { 'class': 'footable-loader' }).append($('<span/>', {'class': 'fooicon fooicon-loader'}));
1960 /**
1961 * The options for the plugin. This is a merge of user defined options and the default options.
1962 * @instance
1963 * @type {object}
1964 */
1965 this.o = $.extend(true, {}, F.defaults, options);
1966 /**
1967 * The jQuery data object for the table at initialization.
1968 * @instance
1969 * @type {object}
1970 */
1971 this.data = this.$el.data() || {};
1972 /**
1973 * An array of all CSS classes on the table that do not start with "footable".
1974 * @instance
1975 * @protected
1976 * @type {Array.<string>}
1977 */
1978 this.classes = [];
1979 /**
1980 * All components for this instance of the plugin. These are executed in the order they appear in the array for the initialize phase and in reverse order for the destroy phase of the plugin.
1981 * @instance
1982 * @protected
1983 * @type {object}
1984 * @prop {Array.<FooTable.Component>} internal - The internal components for the plugin. These are executed either before all other components in the initialize phase or after them in the destroy phase of the plugin.
1985 * @prop {Array.<FooTable.Component>} core - The core components for the plugin. These are executed either after the internal components in the initialize phase or before them in the destroy phase of the plugin.
1986 * @prop {Array.<FooTable.Component>} custom - The custom components for the plugin. These are executed either after the core components in the initialize phase or before them in the destroy phase of the plugin.
1987 */
1988 this.components = F.components.load((F.is.hash(this.data.components) ? this.data.components : this.o.components), this);
1989 /**
1990 * The breakpoints component for this instance of the plugin.
1991 * @instance
1992 * @type {FooTable.Breakpoints}
1993 */
1994 this.breakpoints = this.use(FooTable.Breakpoints);
1995 /**
1996 * The columns component for this instance of the plugin.
1997 * @instance
1998 * @type {FooTable.Columns}
1999 */
2000 this.columns = this.use(FooTable.Columns);
2001 /**
2002 * The rows component for this instance of the plugin.
2003 * @instance
2004 * @type {FooTable.Rows}
2005 */
2006 this.rows = this.use(FooTable.Rows);
2007
2008 //END MEMBERS
2009 this._construct(ready);
2010 },
2011 /**
2012 * Once all properties are set this performs the actual initialization of the plugin calling the {@link FooTable.Table#_preinit} and
2013 * {@link FooTable.Table#_init} methods as well as raising the {@link FooTable.Table#"ready.ft.table"} event.
2014 * @this FooTable.Table
2015 * @instance
2016 * @param {function} [ready] - A callback function to execute once the plugin is initialized.
2017 * @private
2018 * @returns {jQuery.Promise}
2019 * @fires FooTable.Table#"ready.ft.table"
2020 */
2021 _construct: function(ready){
2022 var self = this;
2023 return this._preinit().then(function(){
2024 return self._init().then(function(){
2025 /**
2026 * The ready.ft.table event is raised after the plugin has been initialized and the table drawn.
2027 * Calling preventDefault on this event will stop the ready callback being executed.
2028 * @event FooTable.Table#"ready.ft.table"
2029 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2030 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2031 */
2032 return self.raise('ready.ft.table').then(function(){
2033 if (F.is.fn(ready)) ready.call(self, self);
2034 });
2035 });
2036 }).always(function(arg){
2037 self.$el.show();
2038 if (F.is.error(arg)){
2039 console.error('FooTable: unhandled error thrown during initialization.', arg);
2040 }
2041 });
2042 },
2043 /**
2044 * The preinit method is called prior to the plugins actual initialization and provides itself and it's components an opportunity to parse any additional option values.
2045 * @instance
2046 * @private
2047 * @returns {jQuery.Promise}
2048 * @fires FooTable.Table#"preinit.ft.table"
2049 */
2050 _preinit: function(){
2051 var self = this;
2052 /**
2053 * The preinit.ft.table event is raised before any components.
2054 * Calling preventDefault on this event will disable the entire plugin.
2055 * @event FooTable.Table#"preinit.ft.table"
2056 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2057 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2058 * @param {object} data - The jQuery data object from the root table element.
2059 */
2060 return this.raise('preinit.ft.table', [self.data]).then(function(){
2061 var classes = (self.$el.attr('class') || '').match(/\S+/g) || [];
2062
2063 self.o.ajax = F.checkFnValue(self, self.data.ajax, self.o.ajax);
2064 self.o.stopPropagation = F.is.boolean(self.data.stopPropagation)
2065 ? self.data.stopPropagation
2066 : self.o.stopPropagation;
2067
2068 for (var i = 0, len = classes.length; i < len; i++){
2069 if (!F.str.startsWith(classes[i], 'footable')) self.classes.push(classes[i]);
2070 }
2071
2072 self.$el.hide().after(self.$loader);
2073 return self.execute(false, false, 'preinit', self.data);
2074 });
2075 },
2076 /**
2077 * Initializes this instance of the plugin and calls the callback function if one is supplied once complete.
2078 * @this FooTable.Table
2079 * @instance
2080 * @private
2081 * @return {jQuery.Promise}
2082 * @fires FooTable.Table#"init.ft.table"
2083 */
2084 _init: function(){
2085 var self = this;
2086 /**
2087 * The init.ft.table event is raised before any components are initialized.
2088 * Calling preventDefault on this event will disable the entire plugin.
2089 * @event FooTable.Table#"init.ft.table"
2090 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2091 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2092 */
2093 return self.raise('init.ft.table').then(function(){
2094 var $thead = self.$el.children('thead'),
2095 $tbody = self.$el.children('tbody'),
2096 $tfoot = self.$el.children('tfoot');
2097 self.$el.addClass('footable footable-' + self.id);
2098 if (F.is.hash(self.o.on)) self.$el.on(self.o.on);
2099 if ($tfoot.length == 0) self.$el.append($tfoot = $('<tfoot/>'));
2100 if ($tbody.length == 0) self.$el.append('<tbody/>');
2101 if ($thead.length == 0) self.$el.prepend($thead = $('<thead/>'));
2102 return self.execute(false, true, 'init').then(function(){
2103 self.$el.data('__FooTable__', self);
2104 if ($tfoot.children('tr').length == 0) $tfoot.remove();
2105 if ($thead.children('tr').length == 0) $thead.remove();
2106
2107 /**
2108 * The postinit.ft.table event is raised after any components are initialized but before the table is
2109 * drawn for the first time.
2110 * Calling preventDefault on this event will disable the initial drawing of the table.
2111 * @event FooTable.Table#"postinit.ft.table"
2112 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2113 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2114 */
2115 return self.raise('postinit.ft.table').then(function(){
2116 return self.draw();
2117 }).always(function(){
2118 $(window).off('resize.ft'+self.id, self._onWindowResize)
2119 .on('resize.ft'+self.id, { self: self }, self._onWindowResize);
2120 self.initialized = true;
2121 });
2122 });
2123 });
2124 },
2125 /**
2126 * Destroys this plugin removing it from the table.
2127 * @this FooTable.Table
2128 * @instance
2129 * @fires FooTable.Table#"destroy.ft.table"
2130 */
2131 destroy: function () {
2132 var self = this;
2133 /**
2134 * The destroy.ft.table event is called before all core components.
2135 * Calling preventDefault on this event will prevent the entire plugin from being destroyed.
2136 * @event FooTable.Table#"destroy.ft.table"
2137 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2138 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2139 */
2140 return self.raise('destroy.ft.table').then(function(){
2141 return self.execute(true, true, 'destroy').then(function () {
2142 self.$el.removeData('__FooTable__').removeClass('footable-' + self.id);
2143 if (F.is.hash(self.o.on)) self.$el.off(self.o.on);
2144 $(window).off('resize.ft'+self.id, self._onWindowResize);
2145 self.initialized = false;
2146 F.instances[self.id] = null;
2147 });
2148 }).fail(function(err){
2149 if (F.is.error(err)){
2150 console.error('FooTable: unhandled error thrown while destroying the plugin.', err);
2151 }
2152 });
2153 },
2154 /**
2155 * Raises an event on this instance supplying the args array as additional parameters to the handlers.
2156 * @this FooTable.Table
2157 * @instance
2158 * @param {string} eventName - The name of the event to raise, this can include namespaces.
2159 * @param {Array} [args] - An array containing additional parameters to be passed to any bound handlers.
2160 * @returns {jQuery.Event}
2161 */
2162 raise: function(eventName, args){
2163 var self = this,
2164 debug = F.__debug__ && (F.is.emptyArray(F.__debug_options__.events) || F.arr.any(F.__debug_options__.events, function(name){ return F.str.contains(eventName, name); }));
2165 args = args || [];
2166 args.unshift(this);
2167 return $.Deferred(function(d){
2168 var evt = $.Event(eventName);
2169 if (self.o.stopPropagation == true){
2170 self.$el.one(eventName, function (e) {e.stopPropagation();});
2171 }
2172 if (debug) console.log('FooTable:'+eventName+': ', args);
2173 self.$el.trigger(evt, args);
2174 if (evt.isDefaultPrevented()){
2175 if (debug) console.log('FooTable: default prevented for the "'+eventName+'" event.');
2176 d.reject(evt);
2177 } else d.resolve(evt);
2178 });
2179 },
2180 /**
2181 * Attempts to retrieve the instance of the supplied component type for this instance.
2182 * @this FooTable.Table
2183 * @instance
2184 * @param {object} type - The content type to retrieve for this instance.
2185 * @returns {(*|null)}
2186 */
2187 use: function(type){
2188 for (var i = 0, len = this.components.length; i < len; i++){
2189 if (this.components[i] instanceof type) return this.components[i];
2190 }
2191 return null;
2192 },
2193 /**
2194 * Performs the drawing of the table.
2195 * @this FooTable.Table
2196 * @instance
2197 * @protected
2198 * @returns {jQuery.Promise}
2199 * @fires FooTable.Table#"predraw.ft.table"
2200 * @fires FooTable.Table#"draw.ft.table"
2201 * @fires FooTable.Table#"postdraw.ft.table"
2202 */
2203 draw: function () {
2204 var self = this;
2205
2206 // Clone the current table and insert it into the original's place
2207 var $elCopy = self.$el.clone().insertBefore(self.$el);
2208
2209 // Detach `self.$el` from the DOM, retaining its event handlers
2210 self.$el.detach();
2211
2212 // when drawing the order that the components are executed is important so chain the methods but use promises to retain async safety.
2213 return self.execute(false, true, 'predraw').then(function(){
2214 /**
2215 * The predraw.ft.table event is raised after all core components and add-ons have executed there predraw functions but before they execute there draw functions.
2216 * @event FooTable.Table#"predraw.ft.table"
2217 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2218 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2219 */
2220 return self.raise('predraw.ft.table').then(function(){
2221 return self.execute(false, true, 'draw').then(function(){
2222 /**
2223 * The draw.ft.table event is raised after all core components and add-ons have executed there draw functions.
2224 * @event FooTable.Table#"draw.ft.table"
2225 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2226 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2227 */
2228 return self.raise('draw.ft.table').then(function(){
2229 return self.execute(false, true, 'postdraw').then(function(){
2230 /**
2231 * The postdraw.ft.table event is raised after all core components and add-ons have executed there postdraw functions.
2232 * @event FooTable.Table#"postdraw.ft.table"
2233 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2234 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2235 */
2236 return self.raise('postdraw.ft.table');
2237 });
2238 });
2239 });
2240 });
2241 }).fail(function(err){
2242 if (F.is.error(err)){
2243 console.error('FooTable: unhandled error thrown during a draw operation.', err);
2244 }
2245 }).always(function(){
2246 // Replace the copy that we added above with the modified `self.$el`
2247 $elCopy.replaceWith(self.$el);
2248 self.$loader.remove();
2249 });
2250 },
2251 /**
2252 * Executes the specified method with the optional number of parameters on all components and waits for the promise from each to be resolved before executing the next.
2253 * @this FooTable.Table
2254 * @instance
2255 * @protected
2256 * @param {boolean} reverse - Whether or not to execute the component methods in the reverse order to what they were registered in.
2257 * @param {boolean} enabled - Whether or not to execute the method on enabled components only.
2258 * @param {string} methodName - The name of the method to execute.
2259 * @param {*} [param1] - The first parameter for the method.
2260 * @param {...*} [paramN] - Any number of additional parameters for the method.
2261 * @returns {jQuery.Promise}
2262 */
2263 execute: function(reverse, enabled, methodName, param1, paramN){
2264 var self = this, args = Array.prototype.slice.call(arguments);
2265 reverse = args.shift();
2266 enabled = args.shift();
2267 var components = enabled ? F.arr.get(self.components, function(c){ return c.enabled; }) : self.components.slice(0);
2268 args.unshift(reverse ? components.reverse() : components);
2269 return self._execute.apply(self, args);
2270 },
2271 /**
2272 * Executes the specified method with the optional number of parameters on all supplied components waiting for the result of each before executing the next.
2273 * @this FooTable.Table
2274 * @instance
2275 * @private
2276 * @param {Array.<FooTable.Component>} components - The components to call the method on.
2277 * @param {string} methodName - The name of the method to execute
2278 * @param {*} [param1] - The first parameter for the method.
2279 * @param {...*} [paramN] - Any additional parameters for the method.
2280 * @returns {jQuery.Promise}
2281 */
2282 _execute: function(components, methodName, param1, paramN){
2283 if (!components || !components.length) return $.when();
2284 var self = this, args = Array.prototype.slice.call(arguments),
2285 component;
2286 components = args.shift();
2287 methodName = args.shift();
2288 component = components.shift();
2289
2290 if (!F.is.fn(component[methodName]))
2291 return self._execute.apply(self, [components, methodName].concat(args));
2292
2293 return $.Deferred(function(d){
2294 try {
2295 var result = component[methodName].apply(component, args);
2296 if (F.is.promise(result)){
2297 return result.then(d.resolve, d.reject);
2298 } else {
2299 d.resolve(result);
2300 }
2301 } catch (err) {
2302 d.reject(err);
2303 }
2304 }).then(function(){
2305 return self._execute.apply(self, [components, methodName].concat(args));
2306 });
2307 },
2308 /**
2309 * Listens to the window resize event and performs a check to see if the breakpoint has changed.
2310 * @this window
2311 * @instance
2312 * @private
2313 * @fires FooTable.Table#"resize.ft.table"
2314 */
2315 _onWindowResize: function (e) {
2316 var self = e.data.self;
2317 if (self._resizeTimeout != null) { clearTimeout(self._resizeTimeout); }
2318 self._resizeTimeout = setTimeout(function () {
2319 self._resizeTimeout = null;
2320 /**
2321 * The resize event is raised a short time after window resize operations cease.
2322 * @event FooTable.Table#"resize.ft.table"
2323 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2324 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2325 */
2326 self.raise('resize.ft.table').then(function(){
2327 self.breakpoints.check();
2328 });
2329 }, 300);
2330 }
2331 });
2332
2333 })(jQuery, FooTable);
2334 (function($, F){
2335
2336 F.ArrayColumn = F.Column.extend(/** @lends FooTable.ArrayColumn */{
2337 /**
2338 * @summary A column to handle Array values.
2339 * @constructs
2340 * @extends FooTable.Column
2341 * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
2342 * @param {object} definition - An object containing all the properties to set for the column.
2343 */
2344 construct: function(instance, definition) {
2345 this._super(instance, definition, 'array');
2346 },
2347 /**
2348 * @summary Parses the supplied value or element to retrieve a column value.
2349 * @description This is supplied either the cell value or jQuery object to parse. This method will return either the Array containing the values or null.
2350 * @instance
2351 * @protected
2352 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
2353 * @returns {(array|null)}
2354 */
2355 parser: function(valueOrElement){
2356 if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){ // use jQuery to get the value
2357 var $el = $(valueOrElement), data = $el.data('value'); // .data() will automatically convert a JSON string to an array
2358 if (F.is.array(data)) return data;
2359 data = $el.html();
2360 try {
2361 data = JSON.parse(data);
2362 } catch(err) {
2363 data = null;
2364 }
2365 return F.is.array(data) ? data : null; // if we have an array return it
2366 }
2367 if (F.is.array(valueOrElement)) return valueOrElement; // if we have an array return it
2368 return null; // otherwise we have no value so return null
2369 },
2370 /**
2371 * @summary Formats the column value and creates the HTML seen within a cell.
2372 * @description This is supplied the value retrieved from the {@link FooTable.ArrayColumn#parser} function and must return a string, HTMLElement or jQuery object.
2373 * The return value from this function is what is displayed in the cell in the table.
2374 * @instance
2375 * @protected
2376 * @param {?Array} value - The value to format.
2377 * @param {object} options - The current plugin options.
2378 * @param {object} rowData - An object containing the current row data.
2379 * @returns {(string|HTMLElement|jQuery)}
2380 */
2381 formatter: function(value, options, rowData){
2382 return F.is.array(value) ? JSON.stringify(value) : '';
2383 }
2384 });
2385
2386 F.columns.register('array', F.ArrayColumn);
2387
2388 })(jQuery, FooTable);
2389 (function($, F){
2390
2391 if (F.is.undef(window.moment)){
2392 // The DateColumn requires moment.js to parse and format date values. Goto http://momentjs.com/ to get it.
2393 return;
2394 }
2395
2396 F.DateColumn = F.Column.extend(/** @lends FooTable.DateColumn */{
2397 /**
2398 * The date column class is used to handle date values. This column is dependent on [moment.js]{@link http://momentjs.com/} to provide date parsing and formatting functionality.
2399 * @constructs
2400 * @extends FooTable.Column
2401 * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
2402 * @param {object} definition - An object containing all the properties to set for the column.
2403 * @returns {FooTable.DateColumn}
2404 */
2405 construct: function(instance, definition){
2406 this._super(instance, definition, 'date');
2407 /**
2408 * The format string to use when parsing and formatting dates.
2409 * @instance
2410 * @type {string}
2411 */
2412 this.formatString = F.is.string(definition.formatString) ? definition.formatString : 'MM-DD-YYYY';
2413 },
2414 /**
2415 * This is supplied either the cell value or jQuery object to parse. Any value can be returned from this method and will be provided to the {@link FooTable.DateColumn#format} function
2416 * to generate the cell contents.
2417 * @instance
2418 * @protected
2419 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
2420 * @returns {(moment|null)}
2421 * @this FooTable.DateColumn
2422 */
2423 parser: function(valueOrElement){
2424 if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
2425 var data = $(valueOrElement).data('value');
2426 valueOrElement = F.is.defined(data) ? data : $(valueOrElement).text();
2427 if (F.is.string(valueOrElement)) valueOrElement = isNaN(valueOrElement) ? valueOrElement : +valueOrElement;
2428 }
2429 if (F.is.date(valueOrElement)) return moment(valueOrElement);
2430 if (F.is.object(valueOrElement) && F.is.boolean(valueOrElement._isAMomentObject)) return valueOrElement;
2431 if (F.is.string(valueOrElement)){
2432 // if it looks like a number convert it and do nothing else otherwise create a new moment using the string value and formatString
2433 if (isNaN(valueOrElement)){
2434 return moment(valueOrElement, this.formatString);
2435 } else {
2436 valueOrElement = +valueOrElement;
2437 }
2438 }
2439 if (F.is.number(valueOrElement)){
2440 return moment(valueOrElement);
2441 }
2442 return null;
2443 },
2444 /**
2445 * This is supplied the value retrieved from the {@link FooTable.DateColumn#parser} function and must return a string, HTMLElement or jQuery object.
2446 * The return value from this function is what is displayed in the cell in the table.
2447 * @instance
2448 * @protected
2449 * @param {*} value - The value to format.
2450 * @param {object} options - The current plugin options.
2451 * @param {object} rowData - An object containing the current row data.
2452 * @returns {(string|HTMLElement|jQuery)}
2453 * @this FooTable.DateColumn
2454 */
2455 formatter: function(value, options, rowData){
2456 return F.is.object(value) && F.is.boolean(value._isAMomentObject) && value.isValid() ? value.format(this.formatString) : '';
2457 },
2458 /**
2459 * This is supplied either the cell value or jQuery object to parse. A string value must be returned from this method and will be used during filtering operations.
2460 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
2461 * @returns {string}
2462 * @this FooTable.DateColumn
2463 */
2464 filterValue: function(valueOrElement){
2465 // if we have an element or a jQuery object use jQuery to get the value
2466 if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)) valueOrElement = $(valueOrElement).data('filterValue') || $(valueOrElement).text();
2467 // if options are supplied with the value
2468 if (F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options)){
2469 if (F.is.string(valueOrElement.options.filterValue)) valueOrElement = valueOrElement.options.filterValue;
2470 if (F.is.defined(valueOrElement.value)) valueOrElement = valueOrElement.value;
2471 }
2472 // if the value is a moment object just return the formatted value
2473 if (F.is.object(valueOrElement) && F.is.boolean(valueOrElement._isAMomentObject)) return valueOrElement.format(this.formatString);
2474 // if its a string
2475 if (F.is.string(valueOrElement)){
2476 // if its not a number return it
2477 if (isNaN(valueOrElement)){
2478 return valueOrElement;
2479 } else { // otherwise convert it and carry on
2480 valueOrElement = +valueOrElement;
2481 }
2482 }
2483 // if the value is a number or date convert to a moment object and return the formatted result.
2484 if (F.is.number(valueOrElement) || F.is.date(valueOrElement)){
2485 return moment(valueOrElement).format(this.formatString);
2486 }
2487 // try use the native toString of the value if its not undefined or null
2488 if (F.is.defined(valueOrElement) && valueOrElement != null) return valueOrElement+'';
2489 return ''; // otherwise we have no value so return an empty string
2490 }
2491 });
2492
2493 F.columns.register('date', F.DateColumn);
2494
2495 })(jQuery, FooTable);
2496
2497 (function($, F){
2498
2499 F.HTMLColumn = F.Column.extend(/** @lends FooTable.HTMLColumn */{
2500 /**
2501 * The HTML column class is used to handle any raw HTML columns.
2502 * @constructs
2503 * @extends FooTable.Column
2504 * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
2505 * @param {object} definition - An object containing all the properties to set for the column.
2506 * @returns {FooTable.HTMLColumn}
2507 */
2508 construct: function(instance, definition){
2509 this._super(instance, definition, 'html');
2510 },
2511 /**
2512 * This is supplied either the cell value or jQuery object to parse. Any value can be returned from this method and will be provided to the {@link FooTable.HTMLColumn#format} function
2513 * to generate the cell contents.
2514 * @instance
2515 * @protected
2516 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
2517 * @returns {(jQuery|null)}
2518 * @this FooTable.HTMLColumn
2519 */
2520 parser: function(valueOrElement){
2521 if (F.is.string(valueOrElement)) valueOrElement = $($.trim(valueOrElement));
2522 if (F.is.element(valueOrElement)) valueOrElement = $(valueOrElement);
2523 if (F.is.jq(valueOrElement)){
2524 var tagName = valueOrElement.prop('tagName').toLowerCase();
2525 if (tagName == 'td' || tagName == 'th'){
2526 var data = valueOrElement.data('value');
2527 return F.is.defined(data) ? data : valueOrElement.contents();
2528 }
2529 return valueOrElement;
2530 }
2531 return null;
2532 }
2533 });
2534
2535 F.columns.register('html', F.HTMLColumn);
2536
2537 })(jQuery, FooTable);
2538 (function($, F){
2539
2540 F.NumberColumn = F.Column.extend(/** @lends FooTable.NumberColumn */{
2541 /**
2542 * The number column class is used to handle simple number columns.
2543 * @constructs
2544 * @extends FooTable.Column
2545 * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
2546 * @param {object} definition - An object containing all the properties to set for the column.
2547 * @returns {FooTable.NumberColumn}
2548 */
2549 construct: function(instance, definition){
2550 this._super(instance, definition, 'number');
2551 this.decimalSeparator = F.is.string(definition.decimalSeparator) ? definition.decimalSeparator : '.';
2552 this.thousandSeparator = F.is.string(definition.thousandSeparator) ? definition.thousandSeparator : ',';
2553 this.decimalSeparatorRegex = new RegExp(F.str.escapeRegExp(this.decimalSeparator), 'g');
2554 this.thousandSeparatorRegex = new RegExp(F.str.escapeRegExp(this.thousandSeparator), 'g');
2555 this.cleanRegex = new RegExp('[^\-0-9' + F.str.escapeRegExp(this.decimalSeparator) + ']', 'g');
2556 },
2557 /**
2558 * This is supplied either the cell value or jQuery object to parse. Any value can be returned from this method and will be provided to the {@link FooTable.Column#formatter} function
2559 * to generate the cell contents.
2560 * @instance
2561 * @protected
2562 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
2563 * @returns {(number|null)}
2564 * @this FooTable.NumberColumn
2565 */
2566 parser: function(valueOrElement){
2567 if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
2568 var data = $(valueOrElement).data('value');
2569 valueOrElement = F.is.defined(data) ? data : $(valueOrElement).text().replace(this.cleanRegex, '');
2570 }
2571 if (F.is.string(valueOrElement)){
2572 valueOrElement = valueOrElement.replace(this.thousandSeparatorRegex, '').replace(this.decimalSeparatorRegex, '.');
2573 valueOrElement = parseFloat(valueOrElement);
2574 }
2575 if (F.is.number(valueOrElement)) return valueOrElement;
2576 return null;
2577 },
2578 /**
2579 * This is supplied the value retrieved from the {@link FooTable.NumberColumn#parse} function and must return a string, HTMLElement or jQuery object.
2580 * The return value from this function is what is displayed in the cell in the table.
2581 * @instance
2582 * @protected
2583 * @param {number} value - The value to format.
2584 * @param {object} options - The current plugin options.
2585 * @param {object} rowData - An object containing the current row data.
2586 * @returns {(string|HTMLElement|jQuery)}
2587 * @this FooTable.NumberColumn
2588 */
2589 formatter: function(value, options, rowData){
2590 if (value == null) return '';
2591 var s = (value + '').split('.');
2592 if (s.length == 2 && s[0].length > 3) {
2593 s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, this.thousandSeparator);
2594 }
2595 return s.join(this.decimalSeparator);
2596 }
2597 });
2598
2599 F.columns.register('number', F.NumberColumn);
2600
2601 })(jQuery, FooTable);
2602 (function($, F){
2603
2604 F.ObjectColumn = F.Column.extend(/** @lends FooTable.ObjectColumn */{
2605 /**
2606 * @summary A column to handle Object values.
2607 * @constructs
2608 * @extends FooTable.Column
2609 * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
2610 * @param {object} definition - An object containing all the properties to set for the column.
2611 */
2612 construct: function(instance, definition) {
2613 this._super(instance, definition, 'object');
2614 },
2615 /**
2616 * @summary Parses the supplied value or element to retrieve a column value.
2617 * @description This is supplied either the cell value or jQuery object to parse. This method will return either the Object containing the values or null.
2618 * @instance
2619 * @protected
2620 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
2621 * @returns {(object|null)}
2622 */
2623 parser: function(valueOrElement){
2624 if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){ // use jQuery to get the value
2625 var $el = $(valueOrElement), data = $el.data('value'); // .data() will automatically convert a JSON string to an object
2626 if (F.is.object(data)) return data;
2627 data = $el.html();
2628 try {
2629 data = JSON.parse(data);
2630 } catch(err) {
2631 data = null;
2632 }
2633 return F.is.object(data) ? data : null; // if we have an object return it
2634 }
2635 if (F.is.object(valueOrElement)) return valueOrElement; // if we have an object return it
2636 return null; // otherwise we have no value so return null
2637 },
2638 /**
2639 * @summary Formats the column value and creates the HTML seen within a cell.
2640 * @description This is supplied the value retrieved from the {@link FooTable.ObjectColumn#parser} function and must return a string, HTMLElement or jQuery object.
2641 * The return value from this function is what is displayed in the cell in the table.
2642 * @instance
2643 * @protected
2644 * @param {*} value - The value to format.
2645 * @param {object} options - The current plugin options.
2646 * @param {object} rowData - An object containing the current row data.
2647 * @returns {(string|HTMLElement|jQuery)}
2648 */
2649 formatter: function(value, options, rowData){
2650 return F.is.object(value) ? JSON.stringify(value) : '';
2651 }
2652 });
2653
2654 F.columns.register('object', F.ObjectColumn);
2655
2656 })(jQuery, FooTable);
2657 (function($, F){
2658
2659 F.Breakpoint = F.Class.extend(/** @lends FooTable.Breakpoint */{
2660 /**
2661 * The breakpoint class containing the name and maximum width for the breakpoint.
2662 * @constructs
2663 * @extends FooTable.Class
2664 * @param {string} name - The name of the breakpoint. Must contain no spaces or special characters.
2665 * @param {number} width - The width of the breakpoint in pixels.
2666 * @returns {FooTable.Breakpoint}
2667 */
2668 construct: function(name, width){
2669 /**
2670 * The name of the breakpoint.
2671 * @type {string}
2672 */
2673 this.name = name;
2674 /**
2675 * The maximum width of the breakpoint in pixels.
2676 * @type {number}
2677 */
2678 this.width = width;
2679 }
2680 });
2681
2682 })(jQuery, FooTable);
2683 (function($, F){
2684 F.Breakpoints = F.Component.extend(/** @lends FooTable.Breakpoints */{
2685 /**
2686 * Contains the logic to calculate and apply breakpoints for the plugin.
2687 * @constructs
2688 * @extends FooTable.Component
2689 * @param {FooTable.Table} table - The parent {@link FooTable.Table} this component belongs to.
2690 * @returns {FooTable.Breakpoints}
2691 */
2692 construct: function(table){
2693 // call the base class constructor
2694 this._super(table, true);
2695
2696 /* PROTECTED */
2697 /**
2698 * This provides a shortcut to the {@link FooTable.Table#options} object.
2699 * @protected
2700 * @type {FooTable.Table#options}
2701 */
2702 this.o = table.o;
2703
2704 /* PUBLIC */
2705 /**
2706 * The current breakpoint.
2707 * @type {FooTable.Breakpoint}
2708 */
2709 this.current = null;
2710 /**
2711 * An array of {@link FooTable.Breakpoint} objects created from parsing the options.
2712 * @type {Array.<FooTable.Breakpoint>}
2713 */
2714 this.array = [];
2715 /**
2716 * Whether or not breakpoints cascade. When set to true all breakpoints larger than the current will be hidden along with it.
2717 * @type {boolean}
2718 */
2719 this.cascade = this.o.cascade;
2720 /**
2721 * Whether or not to calculate breakpoints on the width of the parent element rather than the viewport.
2722 * @type {boolean}
2723 */
2724 this.useParentWidth = this.o.useParentWidth;
2725 /**
2726 * This value is updated each time the current breakpoint changes and contains a space delimited string of the names of the current breakpoint and all those smaller than it.
2727 * @type {string}
2728 */
2729 this.hidden = null;
2730
2731 /* PRIVATE */
2732 /**
2733 * This value is set once when the {@link FooTable.Breakpoints#array} is generated and contains a space delimited string of all the breakpoint class names.
2734 * @type {string}
2735 * @private
2736 */
2737 this._classNames = '';
2738
2739 // check if a function was supplied to override the default getWidth
2740 this.getWidth = F.checkFnValue(this, this.o.getWidth, this.getWidth);
2741 },
2742
2743 /* PROTECTED */
2744 /**
2745 * Checks the supplied data and options for the breakpoints component.
2746 * @instance
2747 * @protected
2748 * @param {object} data - The jQuery data object from the parent table.
2749 * @fires FooTable.Breakpoints#"preinit.ft.breakpoints"
2750 */
2751 preinit: function(data){
2752 var self = this;
2753 /**
2754 * The preinit.ft.breakpoints event is raised before any UI is created and provides the tables jQuery data object for additional options parsing.
2755 * Calling preventDefault on this event will disable the entire plugin.
2756 * @event FooTable.Breakpoints#"preinit.ft.breakpoints"
2757 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2758 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2759 * @param {object} data - The jQuery data object of the table raising the event.
2760 */
2761 return this.ft.raise('preinit.ft.breakpoints', [data]).then(function(){
2762 self.cascade = F.is.boolean(data.cascade) ? data.cascade : self.cascade;
2763 self.o.breakpoints = F.is.hash(data.breakpoints) ? data.breakpoints : self.o.breakpoints;
2764 self.getWidth = F.checkFnValue(self, data.getWidth, self.getWidth);
2765 if (self.o.breakpoints == null) self.o.breakpoints = { "xs": 480, "sm": 768, "md": 992, "lg": 1200 };
2766 // Create a nice friendly array to work with out of the breakpoints object.
2767 for (var name in self.o.breakpoints) {
2768 if (!self.o.breakpoints.hasOwnProperty(name)) continue;
2769 self.array.push(new F.Breakpoint(name, self.o.breakpoints[name]));
2770 self._classNames += 'breakpoint-' + name + ' ';
2771 }
2772 // Sort the breakpoints so the largest is checked first
2773 self.array.sort(function (a, b) {
2774 return b.width - a.width;
2775 });
2776 });
2777 },
2778 /**
2779 * Initializes the class parsing the options into a sorted array of {@link FooTable.Breakpoint} objects.
2780 * @instance
2781 * @protected
2782 * @fires FooTable.Breakpoints#"init.ft.breakpoints"
2783 */
2784 init: function(){
2785 var self = this;
2786 /**
2787 * The init.ft.breakpoints event is raised before any UI is generated.
2788 * Calling preventDefault on this event will disable the entire plugin.
2789 * @event FooTable.Breakpoints#"init.ft.breakpoints"
2790 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2791 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2792 */
2793 return this.ft.raise('init.ft.breakpoints').then(function(){
2794 self.current = self.get();
2795 });
2796 },
2797 /**
2798 * Whenever the table is drawn this ensures the correct breakpoint class is applied to the table.
2799 * @instance
2800 * @protected
2801 */
2802 draw: function(){
2803 this.ft.$el.removeClass(this._classNames).addClass('breakpoint-' + this.current.name);
2804 },
2805
2806 /* PUBLIC */
2807 /**
2808 * Calculates the current breakpoint from the {@link FooTable.Breakpoints#array} and sets the {@link FooTable.Breakpoints#current} property.
2809 * @instance
2810 * @returns {FooTable.Breakpoint}
2811 */
2812 calculate: function(){
2813 var self = this, current = null, hidden = [], breakpoint, prev = null, width = self.getWidth();
2814 for (var i = 0, len = self.array.length; i < len; i++) {
2815 breakpoint = self.array[i];
2816 // if the width is smaller than the smallest breakpoint set the smallest as the current.
2817 // if the width is larger than the largest breakpoint set the largest as the current.
2818 // otherwise if the width is somewhere in between check all breakpoints testing if the width
2819 // is greater than the current but smaller than the previous.
2820 if ((!current && i == len -1)
2821 || (width >= breakpoint.width && (prev instanceof F.Breakpoint ? width < prev.width : true))) {
2822 current = breakpoint;
2823 }
2824 if (!current) hidden.push(breakpoint.name);
2825 prev = breakpoint;
2826 }
2827 hidden.push(current.name);
2828 self.hidden = hidden.join(' ');
2829 return current;
2830 },
2831 /**
2832 * Supplied a columns breakpoints this returns a boolean value indicating whether or not the column is visible.
2833 * @param {string} breakpoints - A space separated string of breakpoint names.
2834 * @returns {boolean}
2835 */
2836 visible: function(breakpoints){
2837 if (F.is.emptyString(breakpoints)) return true;
2838 if (breakpoints === 'all') return false;
2839 var parts = breakpoints.split(' '), i = 0, len = parts.length;
2840 for (; i < len; i++){
2841 if (this.cascade ? F.str.containsWord(this.hidden, parts[i]) : parts[i] == this.current.name) return false;
2842 }
2843 return true;
2844 },
2845 /**
2846 * Performs a check between the current breakpoint and the previous breakpoint and performs a redraw if they differ.
2847 * @instance
2848 * @fires FooTable.Breakpoints#"before.ft.breakpoints"
2849 * @fires FooTable.Breakpoints#"after.ft.breakpoints"
2850 */
2851 check: function(){
2852 var self = this, bp = self.get();
2853 if (!(bp instanceof F.Breakpoint)
2854 || bp == self.current)
2855 return;
2856
2857 /**
2858 * The before.ft.breakpoints event is raised if the breakpoint has changed but before the UI is redrawn and is supplied both the current breakpoint
2859 * and the next "new" one that is about to be applied.
2860 * Calling preventDefault on this event will prevent the next breakpoint from being applied.
2861 * @event FooTable.Breakpoints#"before.ft.breakpoints"
2862 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2863 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2864 * @param {FooTable.Breakpoint} current - The current breakpoint.
2865 * @param {FooTable.Breakpoint} next - The breakpoint that is about to be applied.
2866 */
2867 self.ft.raise('before.ft.breakpoints', [self.current, bp]).then(function(){
2868 var previous = self.current;
2869 self.current = bp;
2870 return self.ft.draw().then(function(){
2871 /**
2872 * The after.ft.breakpoints event is raised after the breakpoint has changed and the UI is redrawn and is supplied both the "new" current breakpoint
2873 * and the previous one that was replaced.
2874 * @event FooTable.Breakpoints#"after.ft.breakpoints"
2875 * @param {jQuery.Event} e - The jQuery.Event object for the event.
2876 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
2877 * @param {FooTable.Breakpoint} current - The current breakpoint.
2878 * @param {FooTable.Breakpoint} previous - The breakpoint that was just replaced.
2879 */
2880 self.ft.raise('after.ft.breakpoints', [self.current, previous]);
2881 });
2882 });
2883 },
2884 /**
2885 * Attempts to return a {@link FooTable.Breakpoint} instance when passed a {@link FooTable.Breakpoint},
2886 * the {@link FooTable.Breakpoint#name} string or if nothing is supplied the current breakpoint.
2887 * @instance
2888 * @param {(FooTable.Breakpoint|string|number)} [breakpoint] - The breakpoint to retrieve.
2889 * @returns {FooTable.Breakpoint}
2890 */
2891 get: function(breakpoint){
2892 if (F.is.undef(breakpoint)) return this.calculate();
2893 if (breakpoint instanceof F.Breakpoint) return breakpoint;
2894 if (F.is.string(breakpoint)) return F.arr.first(this.array, function (bp) { return bp.name == breakpoint; });
2895 if (F.is.number(breakpoint)) return breakpoint >= 0 && breakpoint < this.array.length ? this.array[breakpoint] : null;
2896 return null;
2897 },
2898 /**
2899 * Gets the width used to determine breakpoints whether it be from the viewport, parent or a custom function.
2900 * @instance
2901 * @returns {number}
2902 */
2903 getWidth: function(){
2904 if (F.is.fn(this.o.getWidth)) return this.o.getWidth(this.ft);
2905 if (this.useParentWidth == true) return this.getParentWidth();
2906 return this.getViewportWidth();
2907 },
2908 /**
2909 * Gets the tables direct parents width.
2910 * @instance
2911 * @returns {number}
2912 */
2913 getParentWidth: function(){
2914 return this.ft.$el.parent().width();
2915 },
2916 /**
2917 * Gets the current viewport width.
2918 * @instance
2919 * @returns {number}
2920 */
2921 getViewportWidth: function(){
2922 return Math.max(document.documentElement.clientWidth, window.innerWidth, 0);
2923 }
2924 });
2925
2926 F.components.register('breakpoints', F.Breakpoints, 1000);
2927
2928 })(jQuery, FooTable);
2929 (function(F){
2930 /**
2931 * A space delimited string of breakpoint names that specify when the column will be hidden. You can also specify "all" to make a column permanently display in an expandable detail row.
2932 * @type {string}
2933 * @default null
2934 * @example <caption>The below shows how this value would be set</caption>
2935 * breakpoints: "md"
2936 */
2937 F.Column.prototype.breakpoints = null;
2938
2939 F.Column.prototype.__breakpoints_define__ = function(definition){
2940 this.breakpoints = F.is.emptyString(definition.breakpoints) ? null : definition.breakpoints;
2941 };
2942
2943 F.Column.extend('define', function(definition){
2944 this._super(definition);
2945 this.__breakpoints_define__(definition);
2946 });
2947 })(FooTable);
2948 (function(F){
2949 /**
2950 * An object containing the breakpoints for the plugin.
2951 * @type {object.<string, number>}
2952 * @default { "xs": 480, "sm": 768, "md": 992, "lg": 1200 }
2953 */
2954 F.Defaults.prototype.breakpoints = null;
2955
2956 /**
2957 * Whether or not breakpoints cascade. When set to true all breakpoints larger than the current will also be hidden along with it.
2958 * @type {boolean}
2959 * @default false
2960 */
2961 F.Defaults.prototype.cascade = false;
2962
2963 /**
2964 * Whether or not to calculate breakpoints on the width of the parent element rather than the viewport.
2965 * @type {boolean}
2966 * @default false
2967 */
2968 F.Defaults.prototype.useParentWidth = false;
2969
2970 /**
2971 * A function used to override the default getWidth function with a custom one.
2972 * @type {function}
2973 * @default null
2974 * @example <caption>The below shows what the default getWidth function would look like.</caption>
2975 * getWidth: function(instance){
2976 * if (instance.o.useParentWidth == true) return instance.$el.parent().width();
2977 * return instance.breakpoints.getViewportWidth();
2978 * }
2979 */
2980 F.Defaults.prototype.getWidth = null;
2981 })(FooTable);
2982 (function($, F){
2983 F.Columns = F.Component.extend(/** @lends FooTable.Columns */{
2984 /**
2985 * The columns class contains all the logic for handling columns.
2986 * @constructs
2987 * @extends FooTable.Component
2988 * @param {FooTable.Table} table - The parent {@link FooTable.Table} this component belongs to.
2989 * @returns {FooTable.Columns}
2990 */
2991 construct: function(table){
2992 // call the base class constructor
2993 this._super(table, true);
2994
2995 /* PROTECTED */
2996 /**
2997 * This provides a shortcut to the {@link FooTable.Table#options} object.
2998 * @protected
2999 * @type {FooTable.Table#options}
3000 */
3001 this.o = table.o;
3002
3003 /* PUBLIC */
3004 /**
3005 * An array of {@link FooTable.Column} objects created from parsing the options and/or DOM.
3006 * @type {Array.<FooTable.Column>}
3007 */
3008 this.array = [];
3009 /**
3010 * The jQuery header row object.
3011 * @type {jQuery}
3012 */
3013 this.$header = null;
3014 /**
3015 * Whether or not to display the header row.
3016 * @type {boolean}
3017 */
3018 this.showHeader = table.o.showHeader;
3019
3020 this._fromHTML = F.is.emptyArray(table.o.columns) && !F.is.promise(table.o.columns);
3021 },
3022
3023 /* PROTECTED */
3024 /**
3025 * This parses the columns from either the tables rows or the supplied options.
3026 * @instance
3027 * @protected
3028 * @param {object} data - The tables jQuery data object.
3029 * @returns {jQuery.Promise}
3030 * @this FooTable.Columns
3031 */
3032 parse: function(data){
3033 var self = this;
3034 return $.Deferred(function(d){
3035 function merge(cols1, cols2){
3036 var merged = [];
3037 // check if either of the arrays is empty as it can save us having to merge them by index.
3038 if (cols1.length == 0 || cols2.length == 0){
3039 merged = cols1.concat(cols2);
3040 } else {
3041 // at this point we have two arrays of column definitions, we now need to merge them based on there index properties
3042 // first figure out the highest column index provided so we can loop that many times to merge all columns and provide
3043 // defaults where nothing was specified (fill in the gaps in the array as it were).
3044 var highest = 0;
3045 F.arr.each(cols1.concat(cols2), function(c){
3046 if (c.index > highest) highest = c.index;
3047 });
3048 highest++;
3049 for (var i = 0, cols1_c, cols2_c; i < highest; i++){
3050 cols1_c = {};
3051 F.arr.each(cols1, function(c){
3052 if (c.index == i){
3053 cols1_c = c;
3054 return false;
3055 }
3056 });
3057 cols2_c = {};
3058 F.arr.each(cols2, function(c){
3059 if (c.index == i){
3060 cols2_c = c;
3061 return false;
3062 }
3063 });
3064 merged.push($.extend(true, {}, cols1_c, cols2_c));
3065 }
3066 }
3067 return merged;
3068 }
3069
3070 var json = [], html = [];
3071 // get the column options from the content
3072 var $header = self.ft.$el.find('tr.footable-header, thead > tr:last:has([data-breakpoints]), tbody > tr:first:has([data-breakpoints]), thead > tr:last, tbody > tr:first').first(), $cell, cdata;
3073 if ($header.length > 0){
3074 var virtual = $header.parent().is('tbody') && $header.children().length == $header.children('td').length;
3075 if (!virtual) self.$header = $header.addClass('footable-header');
3076 $header.children('td,th').each(function(i, cell){
3077 $cell = $(cell);
3078 cdata = $cell.data();
3079 cdata.index = i;
3080 cdata.$el = $cell;
3081 cdata.virtual = virtual;
3082 html.push(cdata);
3083 });
3084 if (virtual) self.showHeader = false;
3085 }
3086 // get the supplied column options
3087 if (F.is.array(self.o.columns) && !F.is.emptyArray(self.o.columns)){
3088 F.arr.each(self.o.columns, function(c, i){
3089 c.index = i;
3090 json.push(c);
3091 });
3092 self.parseFinalize(d, merge(json, html));
3093 } else if (F.is.promise(self.o.columns)){
3094 self.o.columns.then(function(cols){
3095 F.arr.each(cols, function(c, i){
3096 c.index = i;
3097 json.push(c);
3098 });
3099 self.parseFinalize(d, merge(json, html));
3100 }, function(xhr){
3101 d.reject(Error('Columns ajax request error: ' + xhr.status + ' (' + xhr.statusText + ')'));
3102 });
3103 } else {
3104 self.parseFinalize(d, merge(json, html));
3105 }
3106 });
3107 },
3108 /**
3109 * Used to finalize the parsing of columns it is supplied the parse deferred object which must be resolved with an array of {@link FooTable.Column} objects
3110 * or rejected with an error.
3111 * @instance
3112 * @protected
3113 * @param {jQuery.Deferred} deferred - The deferred object used for parsing.
3114 * @param {Array.<object>} cols - An array of all merged column definitions.
3115 */
3116 parseFinalize: function(deferred, cols){
3117 // we now have a merged array of all column definitions supplied to the plugin, time to make the objects.
3118 var self = this, columns = [], column;
3119 F.arr.each(cols, function(def){
3120 // if we have a column registered using the definition type then create an instance of that column otherwise just create a default text column.
3121 if (column = F.columns.contains(def.type) ? F.columns.make(def.type, self.ft, def) : new F.Column(self.ft, def))
3122 columns.push(column);
3123 });
3124 if (F.is.emptyArray(columns)){
3125 deferred.reject(Error("No columns supplied."));
3126 } else {
3127 // make sure to sort by the column index as the merge process may have mixed them up
3128 columns.sort(function(a, b){ return a.index - b.index; });
3129 deferred.resolve(columns);
3130 }
3131 },
3132 /**
3133 * The columns preinit method is used to parse and check the column options supplied from both static content and through the constructor.
3134 * @instance
3135 * @protected
3136 * @param {object} data - The jQuery data object from the root table element.
3137 * @this FooTable.Columns
3138 */
3139 preinit: function(data){
3140 var self = this;
3141 /**
3142 * The preinit.ft.columns event is raised before any UI is created and provides the tables jQuery data object for additional options parsing.
3143 * Calling preventDefault on this event will disable the entire plugin.
3144 * @event FooTable.Columns#"preinit.ft.columns"
3145 * @param {jQuery.Event} e - The jQuery.Event object for the event.
3146 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
3147 * @param {object} data - The jQuery data object of the table raising the event.
3148 */
3149 return self.ft.raise('preinit.ft.columns', [data]).then(function(){
3150 return self.parse(data).then(function(columns){
3151 self.array = columns;
3152 self.showHeader = F.is.boolean(data.showHeader) ? data.showHeader : self.showHeader;
3153 });
3154 });
3155 },
3156 /**
3157 * Initializes the columns creating the table header if required.
3158 * @instance
3159 * @protected
3160 * @fires FooTable.Columns#"init.ft.columns"
3161 * @this FooTable.Columns
3162 */
3163 init: function(){
3164 var self = this;
3165 /**
3166 * The init.ft.columns event is raised after the header row is created/parsed for column data.
3167 * @event FooTable.Columns#"init.ft.columns"
3168 * @param {jQuery.Event} e - The jQuery.Event object for the event.
3169 * @param {FooTable.Table} instance - The instance of the plugin raising the event.
3170 * @param {Array.<FooTable.Column>} columns - The array of {@link FooTable.Column} objects parsed from the options and/or DOM.
3171 */
3172 return this.ft.raise('init.ft.columns', [ self.array ]).then(function(){
3173 self.$create();
3174 });
3175 },
3176 /**
3177 * Destroys the columns component removing any UI generated from the table.
3178 * @instance
3179 * @protected
3180 * @fires FooTable.Columns#"destroy.ft.columns"
3181 */
3182 destroy: function(){
3183 /**
3184 * The destroy.ft.columns event is raised before its UI is removed.
3185 * Calling preventDefault on this event will prevent the component from being destroyed.
3186 * @event FooTable.Columns#"destroy.ft.columns"
3187 * @param {jQuery.Event} e - The jQuery.Event object for the event.
3188 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
3189 */
3190 var self = this;
3191 this.ft.raise('destroy.ft.columns').then(function(){
3192 if (!self._fromHTML) self.$header.remove();
3193 });
3194 },
3195 /**
3196 * The predraw method called from within the {@link FooTable.Table#draw} method.
3197 * @instance
3198 * @protected
3199 * @this FooTable.Columns
3200 */
3201 predraw: function(){
3202 var self = this, first = true;
3203 self.visibleColspan = 0;
3204 self.firstVisibleIndex = 0;
3205 self.lastVisibleIndex = 0;
3206 self.hasHidden = false;
3207 F.arr.each(self.array, function(col){
3208 col.hidden = !self.ft.breakpoints.visible(col.breakpoints);
3209 if (!col.hidden && col.visible){
3210 if (first){
3211 self.firstVisibleIndex = col.index;
3212 first = false;
3213 }
3214 self.lastVisibleIndex = col.index;
3215 self.visibleColspan++;
3216 }
3217 if (col.hidden) self.hasHidden = true;
3218 });
3219 self.ft.$el.toggleClass('breakpoint', self.hasHidden);
3220 },
3221 /**
3222 * Performs the actual drawing of the columns, hiding or displaying them depending on there breakpoints.
3223 * @instance
3224 * @protected
3225 * @this FooTable.Columns
3226 */
3227 draw: function(){
3228 F.arr.each(this.array, function(col){
3229 col.$el.css('display', (col.hidden || !col.visible ? 'none' : 'table-cell'));
3230 });
3231 if (!this.showHeader && F.is.jq(this.$header.parent())){
3232 this.$header.detach();
3233 }
3234 },
3235 /**
3236 * Creates the header row for the table from the parsed column definitions.
3237 * @instance
3238 * @protected
3239 * @this FooTable.Columns
3240 */
3241 $create: function(){
3242 var self = this;
3243 self.$header = F.is.jq(self.$header) ? self.$header : $('<tr/>', {'class': 'footable-header'});
3244 self.$header.children('th,td').detach();
3245 F.arr.each(self.array, function(col){
3246 self.$header.append(col.$el);
3247 });
3248 if (self.showHeader && !F.is.jq(self.$header.parent())){
3249 self.ft.$el.children('thead').append(self.$header);
3250 }
3251 },
3252 /**
3253 * Attempts to return a {@link FooTable.Column} instance when passed the {@link FooTable.Column} instance, the {@link FooTable.Column#name} string or the {@link FooTable.Column#index} number.
3254 * If supplied a function this will return an array by iterating all columns passing the index and column itself to the supplied callback as arguments.
3255 * Returning true in the callback will include the column in the result.
3256 * @instance
3257 * @param {(FooTable.Column|string|number|function)} column - The column to retrieve.
3258 * @returns {(Array.<FooTable.Column>|FooTable.Column|null)} The column if one is found otherwise it returns NULL.
3259 * @example <caption>This example shows retrieving a column by name assuming a column called "id" exists. The <code>columns</code> object is an instance of {@link FooTable.Columns}.</caption>
3260 * var column = columns.get('id');
3261 * if (column instanceof FooTable.Column){
3262 * // found the "id" column
3263 * } else {
3264 * // no column with a name of "id" exists
3265 * }
3266 * // to get an array of all hidden columns
3267 * var columns = columns.get(function(col){
3268 * return col.hidden;
3269 * });
3270 */
3271 get: function(column){
3272 if (column instanceof F.Column) return column;
3273 if (F.is.string(column)) return F.arr.first(this.array, function (col) { return col.name == column; });
3274 if (F.is.number(column)) return F.arr.first(this.array, function (col) { return col.index == column; });
3275 if (F.is.fn(column)) return F.arr.get(this.array, column);
3276 return null;
3277 },
3278 /**
3279 * Takes an array of column names, index's or actual {@link FooTable.Column} and ensures that an array of only {@link FooTable.Column} is returned.
3280 * @instance
3281 * @param {(Array.<string>|Array.<number>|Array.<FooTable.Column>)} columns - The array of column names, index's or {@link FooTable.Column} to check.
3282 * @returns {Array.<FooTable.Column>}
3283 */
3284 ensure: function(columns){
3285 var self = this, result = [];
3286 if (!F.is.array(columns)) return result;
3287 F.arr.each(columns, function(name){
3288 result.push(self.get(name));
3289 });
3290 return result;
3291 }
3292 });
3293
3294 F.components.register('columns', F.Columns, 900);
3295
3296 })(jQuery, FooTable);
3297 (function(F){
3298 /**
3299 * An array containing the column options or a jQuery promise that resolves returning the columns. The index of the definitions must match the index of each column as it should appear in the table. For more information on the options available see the {@link FooTable.Column} object.
3300 * @type {(Array.<object>|jQuery.Promise)}
3301 * @default []
3302 * @example <caption>The below shows column definitions for a row defined as <code>{ id: Number, name: String, age: Number }</code>. The ID column has a fixed width, the table is initially sorted on the Name column and the Age column will be hidden on phones.</caption>
3303 * columns: [
3304 * { name: 'id', title: 'ID', type: 'number' },
3305 * { name: 'name', title: 'Name', sorted: true, direction: 'ASC' }
3306 * { name: 'age', title: 'Age', type: 'number', breakpoints: 'xs' }
3307 * ]
3308 */
3309 F.Defaults.prototype.columns = [];
3310
3311 /**
3312 * Specifies whether or not the column headers should be displayed.
3313 * @type {boolean}
3314 * @default true
3315 */
3316 F.Defaults.prototype.showHeader = true;
3317 })(FooTable);
3318 (function ($, F) {
3319 F.Rows = F.Component.extend(/** @lends FooTable.Rows */{
3320 /**
3321 * The rows class contains all the logic for handling rows.
3322 * @constructs
3323 * @extends FooTable.Component
3324 * @param {FooTable.Table} table - The parent {@link FooTable.Table} this component belongs to.
3325 * @returns {FooTable.Rows}
3326 */
3327 construct: function (table) {
3328 // call the base class constructor
3329 this._super(table, true);
3330
3331 /**
3332 * This provides a shortcut to the {@link FooTable.Table#options} object.
3333 * @instance
3334 * @protected
3335 * @type {FooTable.Table#options}
3336 */
3337 this.o = table.o;
3338 /**
3339 * The current working array of {@link FooTable.Row} objects.
3340 * @instance
3341 * @protected
3342 * @type {Array.<FooTable.Row>}
3343 * @default []
3344 */
3345 this.array = [];
3346 /**
3347 * The base array of rows parsed from either the DOM or the constructor options.
3348 * The {@link FooTable.Rows#current} member is populated with a shallow clone of this array
3349 * during the predraw operation before any core or custom components are executed.
3350 * @instance
3351 * @protected
3352 * @type {Array.<FooTable.Row>}
3353 * @default []
3354 */
3355 this.all = [];
3356 /**
3357 * Whether or not to display a toggle in each row when it contains hidden columns.
3358 * @type {boolean}
3359 * @default true
3360 */
3361 this.showToggle = table.o.showToggle;
3362 /**
3363 * The CSS selector used to filter row click events. If the event.target property matches the selector the row will be toggled.
3364 * @type {string}
3365 * @default "tr,td,.footable-toggle"
3366 */
3367 this.toggleSelector = table.o.toggleSelector;
3368 /**
3369 * Specifies which column the row toggle is appended to. Supports only two values; "first" and "last"
3370 * @type {string}
3371 */
3372 this.toggleColumn = table.o.toggleColumn;
3373 /**
3374 * The text to display when the table has no rows.
3375 * @type {string}
3376 */
3377 this.emptyString = table.o.empty;
3378 /**
3379 * Whether or not the first rows details are expanded by default when displayed on a device that hides any columns.
3380 * @type {boolean}
3381 */
3382 this.expandFirst = table.o.expandFirst;
3383 /**
3384 * Whether or not all row details are expanded by default when displayed on a device that hides any columns.
3385 * @type {boolean}
3386 */
3387 this.expandAll = table.o.expandAll;
3388 /**
3389 * The jQuery object that contains the empty row control.
3390 * @type {jQuery}
3391 */
3392 this.$empty = null;
3393 this._fromHTML = F.is.emptyArray(table.o.rows) && !F.is.promise(table.o.rows);
3394 },
3395 /**
3396 * This parses the rows from either the tables rows or the supplied options.
3397 * @instance
3398 * @protected
3399 * @returns {jQuery.Promise}
3400 */
3401 parse: function(){
3402 var self = this;
3403 return $.Deferred(function(d){
3404 var $rows = self.ft.$el.children('tbody').children('tr');
3405 if (F.is.array(self.o.rows) && self.o.rows.length > 0){
3406 self.parseFinalize(d, self.o.rows);
3407 } else if (F.is.promise(self.o.rows)){
3408 self.o.rows.then(function(rows){
3409 self.parseFinalize(d, rows);
3410 }, function(xhr){
3411 d.reject(Error('Rows ajax request error: ' + xhr.status + ' (' + xhr.statusText + ')'));
3412 });
3413 } else if (F.is.jq($rows)){
3414 self.parseFinalize(d, $rows);
3415 $rows.detach();
3416 } else {
3417 self.parseFinalize(d, []);
3418 }
3419 });
3420 },
3421 /**
3422 * Used to finalize the parsing of rows it is supplied the parse deferred object which must be resolved with an array of {@link FooTable.Row} objects
3423 * or rejected with an error.
3424 * @instance
3425 * @protected
3426 * @param {jQuery.Deferred} deferred - The deferred object used for parsing.
3427 * @param {(Array.<object>|jQuery)} rows - An array of row values and options or the jQuery object containing all rows.
3428 */
3429 parseFinalize: function(deferred, rows){
3430 var self = this, result = $.map(rows, function(r){
3431 return new F.Row(self.ft, self.ft.columns.array, r);
3432 });
3433 deferred.resolve(result);
3434 },
3435 /**
3436 * The columns preinit method is used to parse and check the column options supplied from both static content and through the constructor.
3437 * @instance
3438 * @protected
3439 * @param {object} data - The jQuery data object from the root table element.
3440 * @fires FooTable.Rows#"preinit.ft.rows"
3441 */
3442 preinit: function(data){
3443 var self = this;
3444 /**
3445 * The preinit.ft.rows event is raised before any UI is created and provides the tables jQuery data object for additional options parsing.
3446 * Calling preventDefault on this event will disable the entire plugin.
3447 * @event FooTable.Rows#"preinit.ft.rows"
3448 * @param {jQuery.Event} e - The jQuery.Event object for the event.
3449 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
3450 * @param {object} data - The jQuery data object of the table raising the event.
3451 */
3452 return self.ft.raise('preinit.ft.rows', [data]).then(function(){
3453 return self.parse().then(function(rows){
3454 self.all = rows;
3455 self.array = self.all.slice(0);
3456 self.showToggle = F.is.boolean(data.showToggle) ? data.showToggle : self.showToggle;
3457 self.toggleSelector = F.is.string(data.toggleSelector) ? data.toggleSelector : self.toggleSelector;
3458 self.toggleColumn = F.is.string(data.toggleColumn) ? data.toggleColumn : self.toggleColumn;
3459 if (self.toggleColumn != "first" && self.toggleColumn != "last") self.toggleColumn = "first";
3460 self.emptyString = F.is.string(data.empty) ? data.empty : self.emptyString;
3461 self.expandFirst = F.is.boolean(data.expandFirst) ? data.expandFirst : self.expandFirst;
3462 self.expandAll = F.is.boolean(data.expandAll) ? data.expandAll : self.expandAll;
3463 });
3464 });
3465 },
3466 /**
3467 * Initializes the rows class using the supplied table and options.
3468 * @instance
3469 * @protected
3470 * @fires FooTable.Rows#"init.ft.rows"
3471 */
3472 init: function () {
3473 var self = this;
3474 /**
3475 * The init.ft.rows event is raised after the the rows are parsed from either the DOM or the options.
3476 * Calling preventDefault on this event will disable the entire plugin.
3477 * @event FooTable.Rows#"init.ft.rows"
3478 * @param {jQuery.Event} e - The jQuery.Event object for the event.
3479 * @param {FooTable.Table} instance - The instance of the plugin raising the event.
3480 * @param {Array.<FooTable.Row>} rows - The array of {@link FooTable.Row} objects parsed from the DOM or the options.
3481 */
3482 return self.ft.raise('init.ft.rows', [self.all]).then(function(){
3483 self.$create();
3484 });
3485 },
3486 /**
3487 * Destroys the rows component removing any UI generated from the table.
3488 * @instance
3489 * @protected
3490 * @fires FooTable.Rows#"destroy.ft.rows"
3491 */
3492 destroy: function(){
3493 /**
3494 * The destroy.ft.rows event is raised before its UI is removed.
3495 * Calling preventDefault on this event will prevent the component from being destroyed.
3496 * @event FooTable.Rows#"destroy.ft.rows"
3497 * @param {jQuery.Event} e - The jQuery.Event object for the event.
3498 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
3499 */
3500 var self = this;
3501 this.ft.raise('destroy.ft.rows').then(function(){
3502 F.arr.each(self.array, function(row){
3503 row.predraw(!self._fromHTML);
3504 });
3505 self.all = self.array = [];
3506 });
3507 },
3508 /**
3509 * Performs the predraw operations that are required including creating the shallow clone of the {@link FooTable.Rows#array} to work with.
3510 * @instance
3511 * @protected
3512 */
3513 predraw: function(){
3514 F.arr.each(this.array, function(row){
3515 row.predraw();
3516 });
3517 this.array = this.all.slice(0);
3518 },
3519 $create: function(){
3520 this.$empty = $('<tr/>', { 'class': 'footable-empty' }).append($('<td/>').text(this.emptyString));
3521 },
3522 /**
3523 * Performs the actual drawing of the table rows.
3524 * @instance
3525 * @protected
3526 */
3527 draw: function(){
3528 var self = this, $tbody = self.ft.$el.children('tbody'), first = true;
3529 // if we have rows
3530 if (self.array.length > 0){
3531 self.$empty.detach();
3532 // loop through them appending to the tbody and then drawing
3533 F.arr.each(self.array, function(row){
3534 if ((self.expandFirst && first) || self.expandAll){
3535 row.expanded = true;
3536 first = false;
3537 }
3538 row.draw($tbody);
3539 });
3540 } else {
3541 // otherwise display the $empty row
3542 self.$empty.children('td').attr('colspan', self.ft.columns.visibleColspan);
3543 $tbody.append(self.$empty);
3544 }
3545 },
3546 /**
3547 * Loads a JSON array of row objects into the table
3548 * @instance
3549 * @param {Array.<object>} data - An array of row objects to load.
3550 * @param {boolean} [append=false] - Whether or not to append the new rows to the current rows array or to replace them entirely.
3551 */
3552 load: function(data, append){
3553 var self = this, rows = $.map(data, function(r){
3554 return new F.Row(self.ft, self.ft.columns.array, r);
3555 });
3556 F.arr.each(this.array, function(row){
3557 row.predraw();
3558 });
3559 this.all = (F.is.boolean(append) ? append : false) ? this.all.concat(rows) : rows;
3560 this.array = this.all.slice(0);
3561 this.ft.draw();
3562 },
3563 /**
3564 * Expands all visible rows.
3565 * @instance
3566 */
3567 expand: function(){
3568 F.arr.each(this.array, function(row){
3569 row.expand();
3570 });
3571 },
3572 /**
3573 * Collapses all visible rows.
3574 * @instance
3575 */
3576 collapse: function(){
3577 F.arr.each(this.array, function(row){
3578 row.collapse();
3579 });
3580 }
3581 });
3582
3583 F.components.register('rows', F.Rows, 800);
3584
3585 })(jQuery, FooTable);
3586 (function(F){
3587 /**
3588 * An array of JSON objects containing the row data or a jQuery promise that resolves returning the row data.
3589 * @type {(Array.<object>|jQuery.Promise)}
3590 * @default []
3591 */
3592 F.Defaults.prototype.rows = [];
3593
3594 /**
3595 * A string to display when there are no rows in the table.
3596 * @type {string}
3597 * @default "No results"
3598 */
3599 F.Defaults.prototype.empty = 'No results';
3600
3601 /**
3602 * Whether or not the toggle is appended to each row.
3603 * @type {boolean}
3604 * @default true
3605 */
3606 F.Defaults.prototype.showToggle = true;
3607
3608 /**
3609 * The CSS selector used to filter row click events. If the event.target property matches the selector the row will be toggled.
3610 * @type {string}
3611 * @default "tr,td,.footable-toggle"
3612 */
3613 F.Defaults.prototype.toggleSelector = 'tr,td,.footable-toggle';
3614
3615 /**
3616 * Specifies which column to display the row toggle in. The only supported values are "first" or "last".
3617 * @type {string}
3618 * @default "first"
3619 */
3620 F.Defaults.prototype.toggleColumn = 'first';
3621
3622 /**
3623 * Whether or not the first rows details are expanded by default when displayed on a device that hides any columns.
3624 * @type {boolean}
3625 */
3626 F.Defaults.prototype.expandFirst = false;
3627
3628 /**
3629 * Whether or not all row details are expanded by default when displayed on a device that hides any columns.
3630 * @type {boolean}
3631 */
3632 F.Defaults.prototype.expandAll = false;
3633 })(FooTable);
3634 (function(F){
3635 /**
3636 * Loads a JSON array of row objects into the table
3637 * @param {Array.<object>} data - An array of row objects to load.
3638 * @param {boolean} [append=false] - Whether or not to append the new rows to the current rows array or to replace them entirely.
3639 */
3640 F.Table.prototype.loadRows = function(data, append){
3641 this.rows.load(data, append);
3642 };
3643 })(FooTable);
3644 (function(F){
3645 F.Filter = F.Class.extend(/** @lends FooTable.Filter */{
3646 /**
3647 * The filter object contains the query to filter by and the columns to apply it to.
3648 * @constructs
3649 * @extends FooTable.Class
3650 * @param {string} name - The name for the filter.
3651 * @param {(string|FooTable.Query)} query - The query for the filter.
3652 * @param {Array.<FooTable.Column>} columns - The columns to apply the query to.
3653 * @param {string} [space="AND"] - How the query treats space chars.
3654 * @param {boolean} [connectors=true] - Whether or not to replace phrase connectors (+.-_) with spaces.
3655 * @param {boolean} [ignoreCase=true] - Whether or not ignore case when matching.
3656 * @param {boolean} [hidden=true] - Whether or not this is a hidden filter.
3657 * @returns {FooTable.Filter}
3658 */
3659 construct: function(name, query, columns, space, connectors, ignoreCase, hidden){
3660 /**
3661 * The name of the filter.
3662 * @instance
3663 * @type {string}
3664 */
3665 this.name = name;
3666 /**
3667 * A string specifying how the filter treats space characters. Can be either "OR" or "AND".
3668 * @instance
3669 * @type {string}
3670 */
3671 this.space = F.is.string(space) && (space == 'OR' || space == 'AND') ? space : 'AND';
3672 /**
3673 * Whether or not to replace phrase connectors (+.-_) with spaces before executing the query.
3674 * @instance
3675 * @type {boolean}
3676 */
3677 this.connectors = F.is.boolean(connectors) ? connectors : true;
3678 /**
3679 * Whether or not ignore case when matching.
3680 * @instance
3681 * @type {boolean}
3682 */
3683 this.ignoreCase = F.is.boolean(ignoreCase) ? ignoreCase : true;
3684 /**
3685 * Whether or not this is a hidden filter.
3686 * @instance
3687 * @type {boolean}
3688 */
3689 this.hidden = F.is.boolean(hidden) ? hidden : false;
3690 /**
3691 * The query for the filter.
3692 * @instance
3693 * @type {(string|FooTable.Query)}
3694 */
3695 this.query = query instanceof F.Query ? query : new F.Query(query, this.space, this.connectors, this.ignoreCase);
3696 /**
3697 * The columns to apply the query to.
3698 * @instance
3699 * @type {Array.<FooTable.Column>}
3700 */
3701 this.columns = columns;
3702 },
3703 /**
3704 * Checks if the current filter matches the supplied string.
3705 * If the current query property is a string it will be auto converted to a {@link FooTable.Query} object to perform the match.
3706 * @instance
3707 * @param {string} str - The string to check.
3708 * @returns {boolean}
3709 */
3710 match: function(str){
3711 if (!F.is.string(str)) return false;
3712 if (F.is.string(this.query)){
3713 this.query = new F.Query(this.query, this.space, this.connectors, this.ignoreCase);
3714 }
3715 return this.query instanceof F.Query ? this.query.match(str) : false;
3716 },
3717 /**
3718 * Checks if the current filter matches the supplied {@link FooTable.Row}.
3719 * @instance
3720 * @param {FooTable.Row} row - The row to check.
3721 * @returns {boolean}
3722 */
3723 matchRow: function(row){
3724 var self = this, text = F.arr.map(row.cells, function(cell){
3725 return F.arr.contains(self.columns, cell.column) ? cell.filterValue : null;
3726 }).join(' ');
3727 return self.match(text);
3728 }
3729 });
3730
3731 })(FooTable);
3732 (function ($, F) {
3733 F.Filtering = F.Component.extend(/** @lends FooTable.Filtering */{
3734 /**
3735 * The filtering component adds a search input and column selector dropdown to the table allowing users to filter the using space delimited queries.
3736 * @constructs
3737 * @extends FooTable.Component
3738 * @param {FooTable.Table} table - The parent {@link FooTable.Table} object for the component.
3739 * @returns {FooTable.Filtering}
3740 */
3741 construct: function (table) {
3742 // call the constructor of the base class
3743 this._super(table, table.o.filtering.enabled);
3744
3745 /* PUBLIC */
3746 /**
3747 * The filters to apply to the current {@link FooTable.Rows#array}.
3748 * @instance
3749 * @type {Array.<FooTable.Filter>}
3750 */
3751 this.filters = table.o.filtering.filters;
3752 /**
3753 * The delay in milliseconds before the query is auto applied after a change.
3754 * @instance
3755 * @type {number}
3756 */
3757 this.delay = table.o.filtering.delay;
3758 /**
3759 * The minimum number of characters allowed in the search input before it is auto applied.
3760 * @instance
3761 * @type {number}
3762 */
3763 this.min = table.o.filtering.min;
3764 /**
3765 * Specifies how whitespace in a filter query is handled.
3766 * @instance
3767 * @type {string}
3768 */
3769 this.space = table.o.filtering.space;
3770 /**
3771 * Whether or not to replace phrase connectors (+.-_) with spaces before executing the query.
3772 * @instance
3773 * @type {boolean}
3774 */
3775 this.connectors = table.o.filtering.connectors;
3776 /**
3777 * Whether or not ignore case when matching.
3778 * @instance
3779 * @type {boolean}
3780 */
3781 this.ignoreCase = table.o.filtering.ignoreCase;
3782 /**
3783 * Whether or not search queries are treated as phrases when matching.
3784 * @instance
3785 * @type {boolean}
3786 */
3787 this.exactMatch = table.o.filtering.exactMatch;
3788 /**
3789 * The placeholder text to display within the search $input.
3790 * @instance
3791 * @type {string}
3792 */
3793 this.placeholder = table.o.filtering.placeholder;
3794 /**
3795 * The title to display at the top of the search input column select.
3796 * @type {string}
3797 */
3798 this.dropdownTitle = table.o.filtering.dropdownTitle;
3799 /**
3800 * The position of the $search input within the filtering rows cell.
3801 * @type {string}
3802 */
3803 this.position = table.o.filtering.position;
3804 /**
3805 * Whether or not to focus the search input after the search/clear button is clicked or after auto applying the search input query.
3806 * @type {boolean}
3807 */
3808 this.focus = table.o.filtering.focus;
3809 /**
3810 * A selector specifying where to place the filtering components form, if null the form is displayed within a row in the head of the table.
3811 * @type {string}
3812 */
3813 this.container = table.o.filtering.container;
3814 /**
3815 * The jQuery object of the element containing the entire filtering form.
3816 * @instance
3817 * @type {jQuery}
3818 */
3819 this.$container = null;
3820 /**
3821 * The jQuery row object that contains all the filtering specific elements.
3822 * @instance
3823 * @type {jQuery}
3824 */
3825 this.$row = null;
3826 /**
3827 * The jQuery cell object that contains the search input and column selector.
3828 * @instance
3829 * @type {jQuery}
3830 */
3831 this.$cell = null;
3832 /**
3833 * The jQuery form object of the form that contains the search input and column selector.
3834 * @instance
3835 * @type {jQuery}
3836 */
3837 this.$form = null;
3838 /**
3839 * The jQuery object of the column selector dropdown.
3840 * @instance
3841 * @type {jQuery}
3842 */
3843 this.$dropdown = null;
3844 /**
3845 * The jQuery object of the search input.
3846 * @instance
3847 * @type {jQuery}
3848 */
3849 this.$input = null;
3850 /**
3851 * The jQuery object of the search button.
3852 * @instance
3853 * @type {jQuery}
3854 */
3855 this.$button = null;
3856
3857 /* PRIVATE */
3858 /**
3859 * The timeout ID for the filter changed event.
3860 * @instance
3861 * @private
3862 * @type {?number}
3863 */
3864 this._filterTimeout = null;
3865 /**
3866 * The regular expression used to check for encapsulating quotations.
3867 * @instance
3868 * @private
3869 * @type {RegExp}
3870 */
3871 this._exactRegExp = /^"(.*?)"$/;
3872 },
3873
3874 /* PROTECTED */
3875 /**
3876 * Checks the supplied data and options for the filtering component.
3877 * @instance
3878 * @protected
3879 * @param {object} data - The jQuery data object from the parent table.
3880 * @fires FooTable.Filtering#"preinit.ft.filtering"
3881 */
3882 preinit: function(data){
3883 var self = this;
3884 /**
3885 * The preinit.ft.filtering event is raised before the UI is created and provides the tables jQuery data object for additional options parsing.
3886 * Calling preventDefault on this event will disable the component.
3887 * @event FooTable.Filtering#"preinit.ft.filtering"
3888 * @param {jQuery.Event} e - The jQuery.Event object for the event.
3889 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
3890 * @param {object} data - The jQuery data object of the table raising the event.
3891 */
3892 return self.ft.raise('preinit.ft.filtering').then(function(){
3893 // first check if filtering is enabled via the class being applied
3894 if (self.ft.$el.hasClass('footable-filtering'))
3895 self.enabled = true;
3896 // then check if the data-filtering-enabled attribute has been set
3897 self.enabled = F.is.boolean(data.filtering)
3898 ? data.filtering
3899 : self.enabled;
3900
3901 // if filtering is not enabled exit early as we don't need to do anything else
3902 if (!self.enabled) return;
3903
3904 self.space = F.is.string(data.filterSpace)
3905 ? data.filterSpace
3906 : self.space;
3907
3908 self.min = F.is.number(data.filterMin)
3909 ? data.filterMin
3910 : self.min;
3911
3912 self.connectors = F.is.boolean(data.filterConnectors)
3913 ? data.filterConnectors
3914 : self.connectors;
3915
3916 self.ignoreCase = F.is.boolean(data.filterIgnoreCase)
3917 ? data.filterIgnoreCase
3918 : self.ignoreCase;
3919
3920 self.exactMatch = F.is.boolean(data.filterExactMatch)
3921 ? data.filterExactMatch
3922 : self.exactMatch;
3923
3924 self.focus = F.is.boolean(data.filterFocus)
3925 ? data.filterFocus
3926 : self.focus;
3927
3928 self.delay = F.is.number(data.filterDelay)
3929 ? data.filterDelay
3930 : self.delay;
3931
3932 self.placeholder = F.is.string(data.filterPlaceholder)
3933 ? data.filterPlaceholder
3934 : self.placeholder;
3935
3936 self.dropdownTitle = F.is.string(data.filterDropdownTitle)
3937 ? data.filterDropdownTitle
3938 : self.dropdownTitle;
3939
3940 self.container = F.is.string(data.filterContainer)
3941 ? data.filterContainer
3942 : self.container;
3943
3944 self.filters = F.is.array(data.filterFilters)
3945 ? self.ensure(data.filterFilters)
3946 : self.ensure(self.filters);
3947
3948 if (self.ft.$el.hasClass('footable-filtering-left'))
3949 self.position = 'left';
3950 if (self.ft.$el.hasClass('footable-filtering-center'))
3951 self.position = 'center';
3952 if (self.ft.$el.hasClass('footable-filtering-right'))
3953 self.position = 'right';
3954
3955 self.position = F.is.string(data.filterPosition)
3956 ? data.filterPosition
3957 : self.position;
3958 },function(){
3959 self.enabled = false;
3960 });
3961 },
3962 /**
3963 * Initializes the filtering component for the plugin.
3964 * @instance
3965 * @protected
3966 * @fires FooTable.Filtering#"init.ft.filtering"
3967 */
3968 init: function () {
3969 var self = this;
3970 /**
3971 * The init.ft.filtering event is raised before its UI is generated.
3972 * Calling preventDefault on this event will disable the component.
3973 * @event FooTable.Filtering#"init.ft.filtering"
3974 * @param {jQuery.Event} e - The jQuery.Event object for the event.
3975 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
3976 */
3977 return self.ft.raise('init.ft.filtering').then(function(){
3978 self.$create();
3979 }, function(){
3980 self.enabled = false;
3981 });
3982 },
3983 /**
3984 * Destroys the filtering component removing any UI from the table.
3985 * @instance
3986 * @protected
3987 * @fires FooTable.Filtering#"destroy.ft.filtering"
3988 */
3989 destroy: function () {
3990 var self = this;
3991 /**
3992 * The destroy.ft.filtering event is raised before its UI is removed.
3993 * Calling preventDefault on this event will prevent the component from being destroyed.
3994 * @event FooTable.Filtering#"destroy.ft.filtering"
3995 * @param {jQuery.Event} e - The jQuery.Event object for the event.
3996 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
3997 */
3998 return self.ft.raise('destroy.ft.filtering').then(function(){
3999 self.ft.$el.removeClass('footable-filtering')
4000 .find('thead > tr.footable-filtering').remove();
4001 });
4002 },
4003 /**
4004 * Creates the filtering UI from the current options setting the various jQuery properties of this component.
4005 * @instance
4006 * @protected
4007 * @this FooTable.Filtering
4008 */
4009 $create: function () {
4010 var self = this;
4011 // generate the cell that actually contains all the UI.
4012 var $form_grp = $('<div/>', {'class': 'form-group footable-filtering-search'})
4013 .append($('<label/>', {'class': 'sr-only', text: 'Search'})),
4014 $input_grp = $('<div/>', {'class': 'input-group'}).appendTo($form_grp),
4015 $input_grp_btn = $('<div/>', {'class': 'input-group-btn'}),
4016 $dropdown_toggle = $('<button/>', {type: 'button', 'class': 'btn btn-default dropdown-toggle'})
4017 .on('click', { self: self }, self._onDropdownToggleClicked)
4018 .append($('<span/>', {'class': 'caret'})),
4019 position;
4020
4021 switch (self.position){
4022 case 'left': position = 'footable-filtering-left'; break;
4023 case 'center': position = 'footable-filtering-center'; break;
4024 default: position = 'footable-filtering-right'; break;
4025 }
4026 self.ft.$el.addClass('footable-filtering').addClass(position);
4027
4028 self.$container = self.container === null ? $() : $(self.container).first();
4029 if (!self.$container.length){
4030 // add it to a row and then populate it with the search input and column selector dropdown.
4031 self.$row = $('<tr/>', {'class': 'footable-filtering'}).prependTo(self.ft.$el.children('thead'));
4032 self.$cell = $('<th/>').attr('colspan', self.ft.columns.visibleColspan).appendTo(self.$row);
4033 self.$container = self.$cell;
4034 } else {
4035 self.$container.addClass('footable-filtering-external').addClass(position);
4036 }
4037 self.$form = $('<form/>', {'class': 'form-inline'}).append($form_grp).appendTo(self.$container);
4038
4039 self.$input = $('<input/>', {type: 'text', 'class': 'form-control', placeholder: self.placeholder});
4040
4041 self.$button = $('<button/>', {type: 'button', 'class': 'btn btn-primary'})
4042 .on('click', { self: self }, self._onSearchButtonClicked)
4043 .append($('<span/>', {'class': 'fooicon fooicon-search'}));
4044
4045 self.$dropdown = $('<ul/>', {'class': 'dropdown-menu dropdown-menu-right'});
4046 if (!F.is.emptyString(self.dropdownTitle)){
4047 self.$dropdown.append($('<li/>', {'class': 'dropdown-header','text': self.dropdownTitle}));
4048 }
4049 self.$dropdown.append(
4050 F.arr.map(self.ft.columns.array, function (col) {
4051 return col.filterable ? $('<li/>').append(
4052 $('<a/>', {'class': 'checkbox'}).append(
4053 $('<label/>', {html: col.title}).prepend(
4054 $('<input/>', {type: 'checkbox', checked: true}).data('__FooTableColumn__', col)
4055 )
4056 )
4057 ) : null;
4058 })
4059 );
4060
4061 if (self.delay > 0){
4062 self.$input.on('keypress keyup paste', { self: self }, self._onSearchInputChanged);
4063 self.$dropdown.on('click', 'input[type="checkbox"]', {self: self}, self._onSearchColumnClicked);
4064 }
4065
4066 $input_grp_btn.append(self.$button, $dropdown_toggle, self.$dropdown);
4067 $input_grp.append(self.$input, $input_grp_btn);
4068 },
4069 /**
4070 * Performs the filtering of rows before they are appended to the page.
4071 * @instance
4072 * @protected
4073 */
4074 predraw: function(){
4075 if (F.is.emptyArray(this.filters))
4076 return;
4077
4078 var self = this;
4079 self.ft.rows.array = $.grep(self.ft.rows.array, function(r){
4080 return r.filtered(self.filters);
4081 });
4082 },
4083 /**
4084 * As the rows are drawn by the {@link FooTable.Rows#draw} method this simply updates the colspan for the UI.
4085 * @instance
4086 * @protected
4087 */
4088 draw: function(){
4089 if (F.is.jq(this.$cell)){
4090 this.$cell.attr('colspan', this.ft.columns.visibleColspan);
4091 }
4092 var search = this.find('search');
4093 if (search instanceof F.Filter){
4094 var query = search.query.val();
4095 if (this.exactMatch && this._exactRegExp.test(query)){
4096 query = query.replace(this._exactRegExp, '$1');
4097 }
4098 this.$input.val(query);
4099 } else {
4100 this.$input.val(null);
4101 }
4102 this.setButton(!F.arr.any(this.filters, function(f){ return !f.hidden; }));
4103 },
4104
4105 /* PUBLIC */
4106 /**
4107 * Adds or updates the filter using the supplied name, query and columns.
4108 * @instance
4109 * @param {(string|FooTable.Filter|object)} nameOrFilter - The name for the filter or the actual filter object itself.
4110 * @param {(string|FooTable.Query)} [query] - The query for the filter. This is only optional when the first parameter is a filter object.
4111 * @param {(Array.<number>|Array.<string>|Array.<FooTable.Column>)} [columns] - The columns to apply the filter to.
4112 * If not supplied the filter will be applied to all selected columns in the search input dropdown.
4113 * @param {boolean} [ignoreCase=true] - Whether or not ignore case when matching.
4114 * @param {boolean} [connectors=true] - Whether or not to replace phrase connectors (+.-_) with spaces.
4115 * @param {string} [space="AND"] - How the query treats space chars.
4116 * @param {boolean} [hidden=true] - Whether or not this is a hidden filter.
4117 */
4118 addFilter: function(nameOrFilter, query, columns, ignoreCase, connectors, space, hidden){
4119 var f = this.createFilter(nameOrFilter, query, columns, ignoreCase, connectors, space, hidden);
4120 if (f instanceof F.Filter){
4121 this.removeFilter(f.name);
4122 this.filters.push(f);
4123 }
4124 },
4125 /**
4126 * Removes the filter using the supplied name if it exists.
4127 * @instance
4128 * @param {string} name - The name of the filter to remove.
4129 */
4130 removeFilter: function(name){
4131 F.arr.remove(this.filters, function(f){ return f.name == name; });
4132 },
4133 /**
4134 * Performs the required steps to handle filtering including the raising of the {@link FooTable.Filtering#"before.ft.filtering"} and {@link FooTable.Filtering#"after.ft.filtering"} events.
4135 * @instance
4136 * @param {boolean} [focus=false] - Whether or not to set the focus to the input once filtering is complete.
4137 * @returns {jQuery.Promise}
4138 * @fires FooTable.Filtering#"before.ft.filtering"
4139 * @fires FooTable.Filtering#"after.ft.filtering"
4140 */
4141 filter: function(focus){
4142 var self = this;
4143 self.filters = self.ensure(self.filters);
4144 /**
4145 * The before.ft.filtering event is raised before a filter is applied and allows listeners to modify the filter or cancel it completely by calling preventDefault on the jQuery.Event object.
4146 * @event FooTable.Filtering#"before.ft.filtering"
4147 * @param {jQuery.Event} e - The jQuery.Event object for the event.
4148 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
4149 * @param {Array.<FooTable.Filter>} filters - The filters that are about to be applied.
4150 */
4151 return self.ft.raise('before.ft.filtering', [self.filters]).then(function(){
4152 self.filters = self.ensure(self.filters);
4153 if (focus){
4154 var start = self.$input.prop('selectionStart'),
4155 end = self.$input.prop('selectionEnd');
4156 }
4157 return self.ft.draw().then(function(){
4158 if (focus){
4159 self.$input.focus().prop({
4160 selectionStart: start,
4161 selectionEnd: end
4162 });
4163 }
4164 /**
4165 * The after.ft.filtering event is raised after a filter has been applied.
4166 * @event FooTable.Filtering#"after.ft.filtering"
4167 * @param {jQuery.Event} e - The jQuery.Event object for the event.
4168 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
4169 * @param {FooTable.Filter} filter - The filters that were applied.
4170 */
4171 self.ft.raise('after.ft.filtering', [self.filters]);
4172 });
4173 });
4174 },
4175 /**
4176 * Removes the current search filter.
4177 * @instance
4178 * @returns {jQuery.Promise}
4179 * @fires FooTable.Filtering#"before.ft.filtering"
4180 * @fires FooTable.Filtering#"after.ft.filtering"
4181 */
4182 clear: function(){
4183 this.filters = F.arr.get(this.filters, function(f){ return f.hidden; });
4184 return this.filter(this.focus);
4185 },
4186 /**
4187 * Toggles the button icon between the search and clear icons based on the supplied value.
4188 * @instance
4189 * @param {boolean} search - Whether or not to display the search icon.
4190 */
4191 setButton: function(search){
4192 if (!search){
4193 this.$button.children('.fooicon').removeClass('fooicon-search').addClass('fooicon-remove');
4194 } else {
4195 this.$button.children('.fooicon').removeClass('fooicon-remove').addClass('fooicon-search');
4196 }
4197 },
4198 /**
4199 * Finds a filter by name.
4200 * @param {string} name - The name of the filter to find.
4201 * @returns {(FooTable.Filter|null)}
4202 */
4203 find: function(name){
4204 return F.arr.first(this.filters, function(f){ return f.name == name; });
4205 },
4206 /**
4207 * Gets an array of {@link FooTable.Column} to apply the search filter to. This also doubles as the default columns for filters which do not specify any columns.
4208 * @instance
4209 * @returns {Array.<FooTable.Column>}
4210 */
4211 columns: function(){
4212 if (F.is.jq(this.$dropdown)){
4213 // if we have a dropdown containing the column names get the selected columns from there
4214 return this.$dropdown.find('input:checked').map(function(){
4215 return $(this).data('__FooTableColumn__');
4216 }).get();
4217 } else {
4218 // otherwise find all columns that are set to be filterable.
4219 return this.ft.columns.get(function(c){ return c.filterable; });
4220 }
4221 },
4222 /**
4223 * Takes an array of plain objects containing the filter values or actual {@link FooTable.Filter} objects and ensures that an array of only {@link FooTable.Filter} is returned.
4224 * If supplied a plain object that object must contain a name, query and columns properties which are used to create a new {@link FooTable.Filter}.
4225 * @instance
4226 * @param {({name: string, query: (string|FooTable.Query), columns: (Array.<string>|Array.<number>|Array.<FooTable.Column>)}|Array.<FooTable.Filter>)} filters - The array of filters to check.
4227 * @returns {Array.<FooTable.Filter>}
4228 */
4229 ensure: function(filters){
4230 var self = this, parsed = [], filterable = self.columns();
4231 if (!F.is.emptyArray(filters)){
4232 F.arr.each(filters, function(f){
4233 f = self._ensure(f, filterable);
4234 if (f instanceof F.Filter) parsed.push(f);
4235 });
4236 }
4237 return parsed;
4238 },
4239
4240 /**
4241 * Creates a new filter using the supplied object or individual parameters to populate it.
4242 * @instance
4243 * @param {(string|FooTable.Filter|object)} nameOrObject - The name for the filter or the actual filter object itself.
4244 * @param {(string|FooTable.Query)} [query] - The query for the filter. This is only optional when the first parameter is a filter object.
4245 * @param {(Array.<number>|Array.<string>|Array.<FooTable.Column>)} [columns] - The columns to apply the filter to.
4246 * If not supplied the filter will be applied to all selected columns in the search input dropdown.
4247 * @param {boolean} [ignoreCase=true] - Whether or not ignore case when matching.
4248 * @param {boolean} [connectors=true] - Whether or not to replace phrase connectors (+.-_) with spaces.
4249 * @param {string} [space="AND"] - How the query treats space chars.
4250 * @param {boolean} [hidden=true] - Whether or not this is a hidden filter.
4251 * @returns {*}
4252 */
4253 createFilter: function(nameOrObject, query, columns, ignoreCase, connectors, space, hidden){
4254 if (F.is.string(nameOrObject)){
4255 nameOrObject = {name: nameOrObject, query: query, columns: columns, ignoreCase: ignoreCase, connectors: connectors, space: space, hidden: hidden};
4256 }
4257 return this._ensure(nameOrObject, this.columns());
4258 },
4259
4260 /* PRIVATE */
4261 _ensure: function(filter, selectedColumns){
4262 if ((F.is.hash(filter) || filter instanceof F.Filter) && !F.is.emptyString(filter.name) && (!F.is.emptyString(filter.query) || filter.query instanceof F.Query)){
4263 filter.columns = F.is.emptyArray(filter.columns) ? selectedColumns : this.ft.columns.ensure(filter.columns);
4264 filter.ignoreCase = F.is.boolean(filter.ignoreCase) ? filter.ignoreCase : this.ignoreCase;
4265 filter.connectors = F.is.boolean(filter.connectors) ? filter.connectors : this.connectors;
4266 filter.hidden = F.is.boolean(filter.hidden) ? filter.hidden : false;
4267 filter.space = F.is.string(filter.space) && (filter.space === 'AND' || filter.space === 'OR') ? filter.space : this.space;
4268 filter.query = F.is.string(filter.query) ? new F.Query(filter.query, filter.space, filter.connectors, filter.ignoreCase) : filter.query;
4269 return (filter instanceof F.Filter)
4270 ? filter
4271 : new F.Filter(filter.name, filter.query, filter.columns, filter.space, filter.connectors, filter.ignoreCase, filter.hidden);
4272 }
4273 return null;
4274 },
4275 /**
4276 * Handles the change event for the {@link FooTable.Filtering#$input}.
4277 * @instance
4278 * @private
4279 * @param {jQuery.Event} e - The event object for the event.
4280 */
4281 _onSearchInputChanged: function (e) {
4282 var self = e.data.self;
4283 var alpha = e.type == 'keypress' && !F.is.emptyString(String.fromCharCode(e.charCode)),
4284 ctrl = e.type == 'keyup' && (e.which == 8 || e.which == 46),
4285 paste = e.type == 'paste'; // backspace & delete
4286
4287 // if alphanumeric characters or specific control characters
4288 if(alpha || ctrl || paste) {
4289 if (e.which == 13) e.preventDefault();
4290 if (self._filterTimeout != null) clearTimeout(self._filterTimeout);
4291 self._filterTimeout = setTimeout(function(){
4292 self._filterTimeout = null;
4293 var query = self.$input.val();
4294 if (query.length >= self.min){
4295 if (self.exactMatch && !self._exactRegExp.test(query)){
4296 query = '"' + query + '"';
4297 }
4298 self.addFilter('search', query);
4299 self.filter(self.focus);
4300 } else if (F.is.emptyString(query)){
4301 self.clear();
4302 }
4303 }, self.delay);
4304 }
4305 },
4306 /**
4307 * Handles the click event for the {@link FooTable.Filtering#$button}.
4308 * @instance
4309 * @private
4310 * @param {jQuery.Event} e - The event object for the event.
4311 */
4312 _onSearchButtonClicked: function (e) {
4313 e.preventDefault();
4314 var self = e.data.self;
4315 if (self._filterTimeout != null) clearTimeout(self._filterTimeout);
4316 var $icon = self.$button.children('.fooicon');
4317 if ($icon.hasClass('fooicon-remove')) self.clear();
4318 else {
4319 var query = self.$input.val();
4320 if (query.length >= self.min){
4321 if (self.exactMatch && !self._exactRegExp.test(query)){
4322 query = '"' + query + '"';
4323 }
4324 self.addFilter('search', query);
4325 self.filter(self.focus);
4326 }
4327 }
4328 },
4329 /**
4330 * Handles the click event for the column checkboxes in the {@link FooTable.Filtering#$dropdown}.
4331 * @instance
4332 * @private
4333 * @param {jQuery.Event} e - The event object for the event.
4334 */
4335 _onSearchColumnClicked: function (e) {
4336 var self = e.data.self;
4337 if (self._filterTimeout != null) clearTimeout(self._filterTimeout);
4338 self._filterTimeout = setTimeout(function(){
4339 self._filterTimeout = null;
4340 var $icon = self.$button.children('.fooicon');
4341 if ($icon.hasClass('fooicon-remove')){
4342 $icon.removeClass('fooicon-remove').addClass('fooicon-search');
4343 self.addFilter('search', self.$input.val());
4344 self.filter();
4345 }
4346 }, self.delay);
4347 },
4348 /**
4349 * Handles the click event for the {@link FooTable.Filtering#$dropdown} toggle.
4350 * @instance
4351 * @private
4352 * @param {jQuery.Event} e - The event object for the event.
4353 */
4354 _onDropdownToggleClicked: function (e) {
4355 e.preventDefault();
4356 e.stopPropagation();
4357 var self = e.data.self;
4358 self.$dropdown.parent().toggleClass('open');
4359 if (self.$dropdown.parent().hasClass('open')) $(document).on('click.footable', { self: self }, self._onDocumentClicked);
4360 else $(document).off('click.footable', self._onDocumentClicked);
4361 },
4362 /**
4363 * Checks all click events when the dropdown is visible and closes the menu if the target is not the dropdown.
4364 * @instance
4365 * @private
4366 * @param {jQuery.Event} e - The event object for the event.
4367 */
4368 _onDocumentClicked: function(e){
4369 if ($(e.target).closest('.dropdown-menu').length == 0){
4370 e.preventDefault();
4371 var self = e.data.self;
4372 self.$dropdown.parent().removeClass('open');
4373 $(document).off('click.footable', self._onDocumentClicked);
4374 }
4375 }
4376 });
4377
4378 F.components.register('filtering', F.Filtering, 500);
4379
4380 })(jQuery, FooTable);
4381
4382 (function(F){
4383 F.Query = F.Class.extend(/** @lends FooTable.Query */{
4384 /**
4385 * The query object is used to parse and test the filtering component's queries
4386 * @constructs
4387 * @extends FooTable.Class
4388 * @param {string} query - The string value of the query.
4389 * @param {string} [space="AND"] - How the query treats whitespace.
4390 * @param {boolean} [connectors=true] - Whether or not to replace phrase connectors (+.-_) with spaces.
4391 * @param {boolean} [ignoreCase=true] - Whether or not ignore case when matching.
4392 * @returns {FooTable.Query}
4393 */
4394 construct: function(query, space, connectors, ignoreCase){
4395 /* PRIVATE */
4396 /**
4397 * Holds the previous value of the query and is used internally in the {@link FooTable.Query#val} method.
4398 * @type {string}
4399 * @private
4400 */
4401 this._original = null;
4402 /**
4403 * Holds the value for the query. Access to this variable is provided through the {@link FooTable.Query#val} method.
4404 * @type {string}
4405 * @private
4406 */
4407 this._value = null;
4408 /* PUBLIC */
4409 /**
4410 * A string specifying how the query treats whitespace. Can be either "OR" or "AND".
4411 * @type {string}
4412 */
4413 this.space = F.is.string(space) && (space == 'OR' || space == 'AND') ? space : 'AND';
4414 /**
4415 * Whether or not to replace phrase connectors (+.-_) with spaces before executing the query.
4416 * @instance
4417 * @type {boolean}
4418 */
4419 this.connectors = F.is.boolean(connectors) ? connectors : true;
4420 /**
4421 * Whether or not ignore case when matching.
4422 * @instance
4423 * @type {boolean}
4424 */
4425 this.ignoreCase = F.is.boolean(ignoreCase) ? ignoreCase : true;
4426 /**
4427 * The left side of the query if one exists. OR takes precedence over AND.
4428 * @type {FooTable.Query}
4429 * @example <caption>The below shows what is meant by the "left" side of a query</caption>
4430 * query = "Dave AND Mary" - "Dave" is the left side of the query.
4431 * query = "Dave AND Mary OR John" - "Dave and Mary" is the left side of the query.
4432 */
4433 this.left = null;
4434 /**
4435 * The right side of the query if one exists. OR takes precedence over AND.
4436 * @type {FooTable.Query}
4437 * @example <caption>The below shows what is meant by the "right" side of a query</caption>
4438 * query = "Dave AND Mary" - "Mary" is the right side of the query.
4439 * query = "Dave AND Mary OR John" - "John" is the right side of the query.
4440 */
4441 this.right = null;
4442 /**
4443 * The parsed parts of the query. This contains the information used to actually perform a match against a string.
4444 * @type {Array}
4445 */
4446 this.parts = [];
4447 /**
4448 * The type of operand to apply to the results of the individual parts of the query.
4449 * @type {string}
4450 */
4451 this.operator = null;
4452 this.val(query);
4453 },
4454 /**
4455 * Gets or sets the value for the query. During set the value is parsed setting all properties as required.
4456 * @param {string} [value] - If supplied the value to set for this query.
4457 * @returns {(string|undefined)}
4458 */
4459 val: function(value){
4460 // get
4461 if (F.is.emptyString(value)) return this._value;
4462
4463 // set
4464 if (F.is.emptyString(this._original)) this._original = value;
4465 else if (this._original == value) return;
4466
4467 this._value = value;
4468 this._parse();
4469 },
4470 /**
4471 * Tests the supplied string against the query.
4472 * @param {string} str - The string to test.
4473 * @returns {boolean}
4474 */
4475 match: function(str){
4476 if (F.is.emptyString(this.operator) || this.operator === 'OR')
4477 return this._left(str, false) || this._match(str, false) || this._right(str, false);
4478 if (this.operator === 'AND')
4479 return this._left(str, true) && this._match(str, true) && this._right(str, true);
4480 },
4481 /**
4482 * Matches this queries parts array against the supplied string.
4483 * @param {string} str - The string to test.
4484 * @param {boolean} def - The default value to return based on the operand.
4485 * @returns {boolean}
4486 * @private
4487 */
4488 _match: function(str, def){
4489 var self = this, result = false, empty = F.is.emptyString(str);
4490 if (F.is.emptyArray(self.parts) && self.left instanceof F.Query) return def;
4491 if (F.is.emptyArray(self.parts)) return result;
4492 if (self.space === 'OR'){
4493 // with OR we give the str every part to test and if any match it is a success, we do exit early if a negated match occurs
4494 F.arr.each(self.parts, function(p){
4495 if (p.empty && empty){
4496 result = true;
4497 if (p.negate){
4498 result = false;
4499 return result;
4500 }
4501 } else {
4502 var match = (p.exact ? F.str.containsExact : F.str.contains)(str, p.query, self.ignoreCase);
4503 if (match && !p.negate) result = true;
4504 if (match && p.negate) {
4505 result = false;
4506 return result;
4507 }
4508 }
4509 });
4510 } else {
4511 // otherwise with AND we check until the first failure and then exit
4512 result = true;
4513 F.arr.each(self.parts, function(p){
4514 if (p.empty){
4515 if ((!empty && !p.negate) || (empty && p.negate)) result = false;
4516 return result;
4517 } else {
4518 var match = (p.exact ? F.str.containsExact : F.str.contains)(str, p.query, self.ignoreCase);
4519 if ((!match && !p.negate) || (match && p.negate)) result = false;
4520 return result;
4521 }
4522 });
4523 }
4524 return result;
4525 },
4526 /**
4527 * Matches the left side of the query if one exists with the supplied string.
4528 * @param {string} str - The string to test.
4529 * @param {boolean} def - The default value to return based on the operand.
4530 * @returns {boolean}
4531 * @private
4532 */
4533 _left: function(str, def){
4534 return (this.left instanceof F.Query) ? this.left.match(str) : def;
4535 },
4536 /**
4537 * Matches the right side of the query if one exists with the supplied string.
4538 * @param {string} str - The string to test.
4539 * @param {boolean} def - The default value to return based on the operand.
4540 * @returns {boolean}
4541 * @private
4542 */
4543 _right: function(str, def){
4544 return (this.right instanceof F.Query) ? this.right.match(str) : def;
4545 },
4546 /**
4547 * Parses the private {@link FooTable.Query#_value} property and populates the object.
4548 * @private
4549 */
4550 _parse: function(){
4551 if (F.is.emptyString(this._value)) return;
4552 // OR takes precedence so test for it first
4553 if (/\sOR\s/.test(this._value)){
4554 // we have an OR so split the value on the first occurrence of OR to get the left and right sides of the statement
4555 this.operator = 'OR';
4556 var or = this._value.split(/(?:\sOR\s)(.*)?/);
4557 this.left = new F.Query(or[0], this.space, this.connectors, this.ignoreCase);
4558 this.right = new F.Query(or[1], this.space, this.connectors, this.ignoreCase);
4559 } else if (/\sAND\s/.test(this._value)) {
4560 // there are no more OR's so start with AND
4561 this.operator = 'AND';
4562 var and = this._value.split(/(?:\sAND\s)(.*)?/);
4563 this.left = new F.Query(and[0], this.space, this.connectors, this.ignoreCase);
4564 this.right = new F.Query(and[1], this.space, this.connectors, this.ignoreCase);
4565 } else {
4566 // we have no more statements to parse so set the parts array by parsing each part of the remaining query
4567 var self = this;
4568 this.parts = F.arr.map(this._value.match(/(?:[^\s"]+|"[^"]*")+/g), function(str){
4569 return self._part(str);
4570 });
4571 }
4572 },
4573 /**
4574 * Parses a single part of a query into an object to use during matching.
4575 * @param {string} str - The string representation of the part.
4576 * @returns {{query: string, negate: boolean, phrase: boolean, exact: boolean}}
4577 * @private
4578 */
4579 _part: function(str){
4580 var p = {
4581 query: str,
4582 negate: false,
4583 phrase: false,
4584 exact: false,
4585 empty: false
4586 };
4587 // support for NEGATE operand - (minus sign). Remove this first so we can get onto phrase checking
4588 if (F.str.startsWith(p.query, '-')){
4589 p.query = F.str.from(p.query, '-');
4590 p.negate = true;
4591 }
4592 // support for PHRASES (exact matches)
4593 if (/^"(.*?)"$/.test(p.query)){ // if surrounded in quotes strip them and nothing else
4594 p.query = p.query.replace(/^"(.*?)"$/, '$1');
4595 p.phrase = true;
4596 p.exact = true;
4597 } else if (this.connectors && /(?:\w)+?([-_\+\.])(?:\w)+?/.test(p.query)) { // otherwise replace supported phrase connectors (-_+.) with spaces
4598 p.query = p.query.replace(/(?:\w)+?([-_\+\.])(?:\w)+?/g, function(match, p1){
4599 return match.replace(p1, ' ');
4600 });
4601 p.phrase = true;
4602 }
4603 p.empty = p.phrase && F.is.emptyString(p.query);
4604 return p;
4605 }
4606 });
4607
4608 })(FooTable);
4609 (function(F){
4610
4611 /**
4612 * The value used by the filtering component during filter operations. Must be a string and can be set using the data-filter-value attribute on the cell itself.
4613 * If this is not supplied it is set to the result of the toString method called on the value for the cell. Added by the {@link FooTable.Filtering} component.
4614 * @type {string}
4615 * @default null
4616 */
4617 F.Cell.prototype.filterValue = null;
4618
4619 // this is used to define the filtering specific properties on cell creation
4620 F.Cell.prototype.__filtering_define__ = function(valueOrElement){
4621 this.filterValue = this.column.filterValue.call(this.column, valueOrElement);
4622 };
4623
4624 // this is used to update the filterValue property whenever the cell value is changed
4625 F.Cell.prototype.__filtering_val__ = function(value){
4626 if (F.is.defined(value)){
4627 // set only
4628 this.filterValue = this.column.filterValue.call(this.column, value);
4629 }
4630 };
4631
4632 // overrides the public define method and replaces it with our own
4633 F.Cell.extend('define', function(valueOrElement){
4634 this._super(valueOrElement);
4635 this.__filtering_define__(valueOrElement);
4636 });
4637 // overrides the public val method and replaces it with our own
4638 F.Cell.extend('val', function(value, redraw, redrawSelf){
4639 var val = this._super(value, redraw, redrawSelf);
4640 this.__filtering_val__(value);
4641 return val;
4642 });
4643 })(FooTable);
4644 (function($, F){
4645 /**
4646 * Whether or not the column can be used during filtering. Added by the {@link FooTable.Filtering} component.
4647 * @type {boolean}
4648 * @default true
4649 */
4650 F.Column.prototype.filterable = true;
4651
4652 /**
4653 * This is supplied either the cell value or jQuery object to parse. A string value must be returned from this method and will be used during filtering operations.
4654 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
4655 * @returns {string}
4656 * @this FooTable.Column
4657 */
4658 F.Column.prototype.filterValue = function(valueOrElement){
4659 // if we have an element or a jQuery object use jQuery to get the value
4660 if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
4661 var data = $(valueOrElement).data('filterValue');
4662 return F.is.defined(data) ? ''+data : $(valueOrElement).text();
4663 }
4664 // if options are supplied with the value
4665 if (F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options)){
4666 if (F.is.string(valueOrElement.options.filterValue)) return valueOrElement.options.filterValue;
4667 if (F.is.defined(valueOrElement.value)) valueOrElement = valueOrElement.value;
4668 }
4669 if (F.is.defined(valueOrElement) && valueOrElement != null) return valueOrElement+''; // use the native toString of the value
4670 return ''; // otherwise we have no value so return an empty string
4671 };
4672
4673 // this is used to define the filtering specific properties on column creation
4674 F.Column.prototype.__filtering_define__ = function(definition){
4675 this.filterable = F.is.boolean(definition.filterable) ? definition.filterable : this.filterable;
4676 this.filterValue = F.checkFnValue(this, definition.filterValue, this.filterValue);
4677 };
4678
4679 // overrides the public define method and replaces it with our own
4680 F.Column.extend('define', function(definition){
4681 this._super(definition); // call the base so we don't have to redefine any previously set properties
4682 this.__filtering_define__(definition); // then call our own
4683 });
4684 })(jQuery, FooTable);
4685 (function(F){
4686 /**
4687 * An object containing the filtering options for the plugin. Added by the {@link FooTable.Filtering} component.
4688 * @type {object}
4689 * @prop {boolean} enabled=false - Whether or not to allow filtering on the table.
4690 * @prop {({name: string, query: (string|FooTable.Query), columns: (Array.<string>|Array.<number>|Array.<FooTable.Column>)}|Array.<FooTable.Filter>)} filters - The filters to apply to the current {@link FooTable.Rows#array}.
4691 * @prop {number} delay=1200 - The delay in milliseconds before the query is auto applied after a change (any value equal to or less than zero will disable this).
4692 * @prop {number} min=1 - The minimum number of characters allowed in the search input before it is auto applied.
4693 * @prop {string} space="AND" - Specifies how whitespace in a filter query is handled.
4694 * @prop {string} placeholder="Search" - The string used as the placeholder for the search input.
4695 * @prop {string} dropdownTitle=null - The title to display at the top of the search input column select.
4696 * @prop {string} position="right" - The string used to specify the alignment of the search input.
4697 * @prop {string} connectors=true - Whether or not to replace phrase connectors (+.-_) with space before executing the query.
4698 * @prop {boolean} ignoreCase=true - Whether or not ignore case when matching.
4699 * @prop {boolean} exactMatch=false - Whether or not search queries are treated as phrases when matching.
4700 * @prop {boolean} focus=true - Whether or not to focus the search input after the search/clear button is clicked or after auto applying the search input query.
4701 * @prop {string} container=null - A selector specifying where to place the filtering components form, if null the form is displayed within a row in the head of the table.
4702 */
4703 F.Defaults.prototype.filtering = {
4704 enabled: false,
4705 filters: [],
4706 delay: 1200,
4707 min: 1,
4708 space: 'AND',
4709 placeholder: 'Search',
4710 dropdownTitle: null,
4711 position: 'right',
4712 connectors: true,
4713 ignoreCase: true,
4714 exactMatch: false,
4715 focus: true,
4716 container: null
4717 };
4718 })(FooTable);
4719 (function(F){
4720 /**
4721 * Checks if the row is filtered using the supplied filters.
4722 * @this FooTable.Row
4723 * @param {Array.<FooTable.Filter>} filters - The filters to apply.
4724 * @returns {boolean}
4725 */
4726 F.Row.prototype.filtered = function(filters){
4727 var result = true, self = this;
4728 F.arr.each(filters, function(f){
4729 if ((result = f.matchRow(self)) == false) return false;
4730 });
4731 return result;
4732 };
4733 })(FooTable);
4734 (function($, F){
4735
4736 F.Sorter = F.Class.extend(/** @lends FooTable.Sorter */{
4737 /**
4738 * The sorter object contains the column and direction to sort by.
4739 * @constructs
4740 * @extends FooTable.Class
4741 * @param {FooTable.Column} column - The column to sort.
4742 * @param {string} direction - The direction to sort by.
4743 * @returns {FooTable.Sorter}
4744 */
4745 construct: function(column, direction){
4746 /**
4747 * The column to sort.
4748 * @type {FooTable.Column}
4749 */
4750 this.column = column;
4751 /**
4752 * The direction to sort by.
4753 * @type {string}
4754 */
4755 this.direction = direction;
4756 }
4757 });
4758
4759 })(jQuery, FooTable);
4760 (function ($, F) {
4761 F.Sorting = F.Component.extend(/** @lends FooTable.Sorting */{
4762 /**
4763 * The sorting component adds a small sort button to specified column headers allowing users to sort those columns in the table.
4764 * @constructs
4765 * @extends FooTable.Component
4766 * @param {FooTable.Table} table - The parent {@link FooTable.Table} object for the component.
4767 * @returns {FooTable.Sorting}
4768 */
4769 construct: function (table) {
4770 // call the constructor of the base class
4771 this._super(table, table.o.sorting.enabled);
4772
4773 /* PROTECTED */
4774 /**
4775 * This provides a shortcut to the {@link FooTable.Table#options}.[sorting]{@link FooTable.Defaults#sorting} object.
4776 * @instance
4777 * @protected
4778 * @type {object}
4779 */
4780 this.o = table.o.sorting;
4781 /**
4782 * The current sorted column.
4783 * @instance
4784 * @type {FooTable.Column}
4785 */
4786 this.column = null;
4787 /**
4788 * Whether or not to allow sorting to occur, should be set using the {@link FooTable.Sorting#toggleAllowed} method.
4789 * @instance
4790 * @type {boolean}
4791 */
4792 this.allowed = true;
4793 /**
4794 * The initial sort state of the table, this value is used for determining if the sorting has occurred or to reset the state to default.
4795 * @instance
4796 * @type {{isset: boolean, rows: Array.<FooTable.Row>, column: string, direction: ?string}}
4797 */
4798 this.initial = null;
4799 },
4800
4801 /* PROTECTED */
4802 /**
4803 * Checks the supplied data and options for the sorting component.
4804 * @instance
4805 * @protected
4806 * @param {object} data - The jQuery data object from the parent table.
4807 * @fires FooTable.Sorting#"preinit.ft.sorting"
4808 * @this FooTable.Sorting
4809 */
4810 preinit: function(data){
4811 var self = this;
4812 /**
4813 * The preinit.ft.sorting event is raised before the UI is created and provides the tables jQuery data object for additional options parsing.
4814 * Calling preventDefault on this event will disable the component.
4815 * @event FooTable.Sorting#"preinit.ft.sorting"
4816 * @param {jQuery.Event} e - The jQuery.Event object for the event.
4817 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
4818 * @param {object} data - The jQuery data object of the table raising the event.
4819 */
4820 this.ft.raise('preinit.ft.sorting', [data]).then(function(){
4821 if (self.ft.$el.hasClass('footable-sorting'))
4822 self.enabled = true;
4823 self.enabled = F.is.boolean(data.sorting)
4824 ? data.sorting
4825 : self.enabled;
4826 if (!self.enabled) return;
4827 self.column = F.arr.first(self.ft.columns.array, function(col){ return col.sorted; });
4828 }, function(){
4829 self.enabled = false;
4830 });
4831 },
4832 /**
4833 * Initializes the sorting component for the plugin using the supplied table and options.
4834 * @instance
4835 * @protected
4836 * @fires FooTable.Sorting#"init.ft.sorting"
4837 * @this FooTable.Sorting
4838 */
4839 init: function () {
4840 /**
4841 * The init.ft.sorting event is raised before its UI is generated.
4842 * Calling preventDefault on this event will disable the component.
4843 * @event FooTable.Sorting#"init.ft.sorting"
4844 * @param {jQuery.Event} e - The jQuery.Event object for the event.
4845 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
4846 */
4847 var self = this;
4848 this.ft.raise('init.ft.sorting').then(function(){
4849 if (!self.initial){
4850 var isset = !!self.column;
4851 self.initial = {
4852 isset: isset,
4853 // grab a shallow copy of the rows array prior to sorting - allows us to reset without an initial sort
4854 rows: self.ft.rows.all.slice(0),
4855 // if there is a sorted column store its name and direction
4856 column: isset ? self.column.name : null,
4857 direction: isset ? self.column.direction : null
4858 }
4859 }
4860 F.arr.each(self.ft.columns.array, function(col){
4861 if (col.sortable){
4862 col.$el.addClass('footable-sortable').append($('<span/>', {'class': 'fooicon fooicon-sort'}));
4863 }
4864 });
4865 self.ft.$el.on('click.footable', '.footable-sortable', { self: self }, self._onSortClicked);
4866 }, function(){
4867 self.enabled = false;
4868 });
4869 },
4870 /**
4871 * Destroys the sorting component removing any UI generated from the table.
4872 * @instance
4873 * @protected
4874 * @fires FooTable.Sorting#"destroy.ft.sorting"
4875 */
4876 destroy: function () {
4877 /**
4878 * The destroy.ft.sorting event is raised before its UI is removed.
4879 * Calling preventDefault on this event will prevent the component from being destroyed.
4880 * @event FooTable.Sorting#"destroy.ft.sorting"
4881 * @param {jQuery.Event} e - The jQuery.Event object for the event.
4882 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
4883 */
4884 var self = this;
4885 this.ft.raise('destroy.ft.paging').then(function(){
4886 self.ft.$el.off('click.footable', '.footable-sortable', self._onSortClicked);
4887 self.ft.$el.children('thead').children('tr.footable-header')
4888 .children('.footable-sortable').removeClass('footable-sortable footable-asc footable-desc')
4889 .find('span.fooicon').remove();
4890 });
4891 },
4892 /**
4893 * Performs the actual sorting against the {@link FooTable.Rows#current} array.
4894 * @instance
4895 * @protected
4896 */
4897 predraw: function () {
4898 if (!this.column) return;
4899 var self = this, col = self.column;
4900 self.ft.rows.array.sort(function (a, b) {
4901 return col.direction == 'DESC'
4902 ? col.sorter(b.cells[col.index].sortValue, a.cells[col.index].sortValue)
4903 : col.sorter(a.cells[col.index].sortValue, b.cells[col.index].sortValue);
4904 });
4905 },
4906 /**
4907 * Updates the sorting UI setting the state of the sort buttons.
4908 * @instance
4909 * @protected
4910 */
4911 draw: function () {
4912 if (!this.column) return;
4913 var self = this,
4914 $sortable = self.ft.$el.find('thead > tr > .footable-sortable'),
4915 $active = self.column.$el;
4916
4917 $sortable.removeClass('footable-asc footable-desc').children('.fooicon').removeClass('fooicon-sort fooicon-sort-asc fooicon-sort-desc');
4918 $sortable.not($active).children('.fooicon').addClass('fooicon-sort');
4919 $active.addClass(self.column.direction == 'DESC' ? 'footable-desc' : 'footable-asc')
4920 .children('.fooicon').addClass(self.column.direction == 'DESC' ? 'fooicon-sort-desc' : 'fooicon-sort-asc');
4921 },
4922
4923 /* PUBLIC */
4924 /**
4925 * Sets the sorting options and calls the {@link FooTable.Table#draw} method to perform the actual sorting.
4926 * @instance
4927 * @param {(string|number|FooTable.Column)} column - The column name, index or the actual {@link FooTable.Column} object to sort by.
4928 * @param {string} [direction="ASC"] - The direction to sort by, either ASC or DESC.
4929 * @returns {jQuery.Promise}
4930 * @fires FooTable.Sorting#"before.ft.sorting"
4931 * @fires FooTable.Sorting#"after.ft.sorting"
4932 */
4933 sort: function(column, direction){
4934 return this._sort(column, direction);
4935 },
4936 /**
4937 * Toggles whether or not sorting is currently allowed.
4938 * @param {boolean} [state] - You can optionally specify the state you want it to be, if not supplied the current value is flipped.
4939 */
4940 toggleAllowed: function(state){
4941 state = F.is.boolean(state) ? state : !this.allowed;
4942 this.allowed = state;
4943 this.ft.$el.toggleClass('footable-sorting-disabled', !this.allowed);
4944 },
4945 /**
4946 * Checks whether any sorting has occurred for the table.
4947 * @returns {boolean}
4948 */
4949 hasChanged: function(){
4950 return !(!this.initial || !this.column ||
4951 (this.column.name === this.initial.column &&
4952 (this.column.direction === this.initial.direction || (this.initial.direction === null && this.column.direction === 'ASC')))
4953 );
4954 },
4955 /**
4956 * Resets the table sorting to the initial state recorded in the components init method.
4957 */
4958 reset: function(){
4959 if (!!this.initial){
4960 if (this.initial.isset){
4961 // if the initial value specified a column, sort by it
4962 this.sort(this.initial.column, this.initial.direction);
4963 } else {
4964 // if there was no initial column then we need to reset the rows to there original order
4965 if (!!this.column){
4966 // if there is a currently sorted column remove the asc/desc classes and set it to null.
4967 this.column.$el.removeClass('footable-asc footable-desc');
4968 this.column = null;
4969 }
4970 // replace the current all rows array with the one stored in the initial value
4971 this.ft.rows.all = this.initial.rows;
4972 // force the table to redraw itself using the updated rows array
4973 this.ft.draw();
4974 }
4975 }
4976 },
4977
4978 /* PRIVATE */
4979 /**
4980 * Performs the required steps to handle sorting including the raising of the {@link FooTable.Sorting#"before.ft.sorting"} and {@link FooTable.Sorting#"after.ft.sorting"} events.
4981 * @instance
4982 * @private
4983 * @param {(string|number|FooTable.Column)} column - The column name, index or the actual {@link FooTable.Column} object to sort by.
4984 * @param {string} [direction="ASC"] - The direction to sort by, either ASC or DESC.
4985 * @returns {jQuery.Promise}
4986 * @fires FooTable.Sorting#"before.ft.sorting"
4987 * @fires FooTable.Sorting#"after.ft.sorting"
4988 */
4989 _sort: function(column, direction){
4990 if (!this.allowed) return $.Deferred().reject('sorting disabled');
4991 var self = this;
4992 var sorter = new F.Sorter(self.ft.columns.get(column), F.Sorting.dir(direction));
4993 /**
4994 * The before.ft.sorting event is raised before a sort is applied and allows listeners to modify the sorter or cancel it completely by calling preventDefault on the jQuery.Event object.
4995 * @event FooTable.Sorting#"before.ft.sorting"
4996 * @param {jQuery.Event} e - The jQuery.Event object for the event.
4997 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
4998 * @param {FooTable.Sorter} sorter - The sorter that is about to be applied.
4999 */
5000 return self.ft.raise('before.ft.sorting', [sorter]).then(function(){
5001 F.arr.each(self.ft.columns.array, function(col){
5002 if (col != self.column) col.direction = null;
5003 });
5004 self.column = self.ft.columns.get(sorter.column);
5005 if (self.column) self.column.direction = F.Sorting.dir(sorter.direction);
5006 return self.ft.draw().then(function(){
5007 /**
5008 * The after.ft.sorting event is raised after a sorter has been applied.
5009 * @event FooTable.Sorting#"after.ft.sorting"
5010 * @param {jQuery.Event} e - The jQuery.Event object for the event.
5011 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
5012 * @param {FooTable.Sorter} sorter - The sorter that has been applied.
5013 */
5014 self.ft.raise('after.ft.sorting', [sorter]);
5015 });
5016 });
5017 },
5018 /**
5019 * Handles the sort button clicked event.
5020 * @instance
5021 * @private
5022 * @param {jQuery.Event} e - The event object for the event.
5023 */
5024 _onSortClicked: function (e) {
5025 var self = e.data.self, $header = $(this).closest('th,td'),
5026 direction = $header.is('.footable-asc, .footable-desc')
5027 ? ($header.hasClass('footable-desc') ? 'ASC' : 'DESC')
5028 : 'ASC';
5029 self._sort($header.index(), direction);
5030 }
5031 });
5032
5033 /**
5034 * Checks the supplied string is a valid direction and if not returns ASC as default.
5035 * @static
5036 * @protected
5037 * @param {string} str - The string to check.
5038 */
5039 F.Sorting.dir = function(str){
5040 return F.is.string(str) && (str == 'ASC' || str == 'DESC') ? str : 'ASC';
5041 };
5042
5043 F.components.register('sorting', F.Sorting, 600);
5044
5045 })(jQuery, FooTable);
5046 (function(F){
5047
5048 /**
5049 * The value used by the sorting component during sort operations. Can be set using the data-sort-value attribute on the cell itself.
5050 * If this is not supplied it is set to the result of the toString method called on the value for the cell. Added by the {@link FooTable.Sorting} component.
5051 * @type {string}
5052 * @default null
5053 */
5054 F.Cell.prototype.sortValue = null;
5055
5056 // this is used to define the sorting specific properties on cell creation
5057 F.Cell.prototype.__sorting_define__ = function(valueOrElement){
5058 this.sortValue = this.column.sortValue.call(this.column, valueOrElement);
5059 };
5060
5061 // this is used to update the sortValue property whenever the cell value is changed
5062 F.Cell.prototype.__sorting_val__ = function(value){
5063 if (F.is.defined(value)){
5064 // set only
5065 this.sortValue = this.column.sortValue.call(this.column, value);
5066 }
5067 };
5068
5069 // overrides the public define method and replaces it with our own
5070 F.Cell.extend('define', function(valueOrElement){
5071 this._super(valueOrElement);
5072 this.__sorting_define__(valueOrElement);
5073 });
5074 // overrides the public val method and replaces it with our own
5075 F.Cell.extend('val', function(value, redraw, redrawSelf){
5076 var val = this._super(value, redraw, redrawSelf);
5077 this.__sorting_val__(value);
5078 return val;
5079 });
5080 })(FooTable);
5081 (function($, F){
5082 /**
5083 * The direction to sort if the {@link FooTable.Column#sorted} property is set to true. Can be "ASC", "DESC" or NULL. Added by the {@link FooTable.Sorting} component.
5084 * @type {string}
5085 * @default null
5086 */
5087 F.Column.prototype.direction = null;
5088 /**
5089 * Whether or not the column can be sorted. Added by the {@link FooTable.Sorting} component.
5090 * @type {boolean}
5091 * @default true
5092 */
5093 F.Column.prototype.sortable = true;
5094 /**
5095 * Whether or not the column is sorted. Added by the {@link FooTable.Sorting} component.
5096 * @type {boolean}
5097 * @default false
5098 */
5099 F.Column.prototype.sorted = false;
5100
5101 /**
5102 * This is supplied two values from the column for a comparison to be made and the result returned. Added by the {@link FooTable.Sorting} component.
5103 * @param {*} a - The first value to be compared.
5104 * @param {*} b - The second value to compare to the first.
5105 * @returns {number}
5106 * @example <caption>This example shows using pseudo code what a sort function would look like.</caption>
5107 * "sorter": function(a, b){
5108 * if (a is less than b by some ordering criterion) {
5109 * return -1;
5110 * }
5111 * if (a is greater than b by the ordering criterion) {
5112 * return 1;
5113 * }
5114 * // a must be equal to b
5115 * return 0;
5116 * }
5117 */
5118 F.Column.prototype.sorter = function(a, b){
5119 if (typeof a === 'string') a = a.toLowerCase();
5120 if (typeof b === 'string') b = b.toLowerCase();
5121 if (a === b) return 0;
5122 if (a < b) return -1;
5123 return 1;
5124 };
5125
5126 /**
5127 * This is supplied either the cell value or jQuery object to parse. A value must be returned from this method and will be used during sorting operations.
5128 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
5129 * @returns {*}
5130 * @this FooTable.Column
5131 */
5132 F.Column.prototype.sortValue = function(valueOrElement){
5133 // if we have an element or a jQuery object use jQuery to get the value
5134 if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
5135 var data = $(valueOrElement).data('sortValue');
5136 return F.is.defined(data) ? data : this.parser(valueOrElement);
5137 }
5138 // if options are supplied with the value
5139 if (F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options)){
5140 if (F.is.string(valueOrElement.options.sortValue)) return valueOrElement.options.sortValue;
5141 if (F.is.defined(valueOrElement.value)) valueOrElement = valueOrElement.value;
5142 }
5143 if (F.is.defined(valueOrElement) && valueOrElement != null) return valueOrElement;
5144 return null;
5145 };
5146
5147 // this is used to define the sorting specific properties on column creation
5148 F.Column.prototype.__sorting_define__ = function(definition){
5149 this.sorter = F.checkFnValue(this, definition.sorter, this.sorter);
5150 this.direction = F.is.type(definition.direction, 'string') ? F.Sorting.dir(definition.direction) : null;
5151 this.sortable = F.is.boolean(definition.sortable) ? definition.sortable : true;
5152 this.sorted = F.is.boolean(definition.sorted) ? definition.sorted : false;
5153 this.sortValue = F.checkFnValue(this, definition.sortValue, this.sortValue);
5154 };
5155
5156 // overrides the public define method and replaces it with our own
5157 F.Column.extend('define', function(definition){
5158 this._super(definition);
5159 this.__sorting_define__(definition);
5160 });
5161
5162 })(jQuery, FooTable);
5163 (function(F){
5164 /**
5165 * An object containing the sorting options for the plugin. Added by the {@link FooTable.Sorting} component.
5166 * @type {object}
5167 * @prop {boolean} enabled=false - Whether or not to allow sorting on the table.
5168 */
5169 F.Defaults.prototype.sorting = {
5170 enabled: false
5171 };
5172 })(FooTable);
5173 (function($, F){
5174
5175 F.HTMLColumn.extend('__sorting_define__', function(definition){
5176 this._super(definition);
5177 this.sortUse = F.is.string(definition.sortUse) && $.inArray(definition.sortUse, ['html','text']) !== -1 ? definition.sortUse : 'html';
5178 });
5179
5180 /**
5181 * This is supplied either the cell value or jQuery object to parse. A value must be returned from this method and will be used during sorting operations.
5182 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
5183 * @returns {*}
5184 * @this FooTable.HTMLColumn
5185 */
5186 F.HTMLColumn.prototype.sortValue = function(valueOrElement){
5187 // if we have an element or a jQuery object use jQuery to get the data value or pass it off to the parser
5188 if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
5189 var data = $(valueOrElement).data('sortValue');
5190 return F.is.defined(data) ? data : this.parser(valueOrElement);
5191 }
5192 // if options are supplied with the value
5193 if (F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options)){
5194 if (F.is.string(valueOrElement.options.sortValue)) return valueOrElement.options.sortValue;
5195 if (F.is.defined(valueOrElement.value)) valueOrElement = valueOrElement.value;
5196 }
5197 if (F.is.defined(valueOrElement) && valueOrElement != null) return valueOrElement;
5198 return null;
5199 };
5200
5201 })(jQuery, FooTable);
5202 (function($, F){
5203
5204 /**
5205 * This is supplied either the cell value or jQuery object to parse. A value must be returned from this method and will be used during sorting operations.
5206 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
5207 * @returns {*}
5208 */
5209 F.NumberColumn.prototype.sortValue = function(valueOrElement){
5210 // if we have an element or a jQuery object use jQuery to get the data value or pass it off to the parser
5211 if (F.is.element(valueOrElement) || F.is.jq(valueOrElement)){
5212 var data = $(valueOrElement).data('sortValue');
5213 return F.is.number(data) ? data : this.parser(valueOrElement);
5214 }
5215 // if options are supplied with the value
5216 if (F.is.hash(valueOrElement) && F.is.hash(valueOrElement.options)){
5217 if (F.is.string(valueOrElement.options.sortValue)) return this.parser(valueOrElement);
5218 if (F.is.number(valueOrElement.options.sortValue)) return valueOrElement.options.sortValue;
5219 if (F.is.number(valueOrElement.value)) return valueOrElement.value;
5220 }
5221 if (F.is.string(valueOrElement)) return this.parser(valueOrElement);
5222 if (F.is.number(valueOrElement)) return valueOrElement;
5223 return null;
5224 };
5225
5226 })(jQuery, FooTable);
5227 (function(F){
5228 /**
5229 * Sort the table using the specified column and direction. Added by the {@link FooTable.Sorting} component.
5230 * @instance
5231 * @param {(string|number|FooTable.Column)} column - The column name, index or the actual {@link FooTable.Column} object to sort by.
5232 * @param {string} [direction="ASC"] - The direction to sort by, either ASC or DESC.
5233 * @returns {jQuery.Promise}
5234 * @fires FooTable.Sorting#"change.ft.sorting"
5235 * @fires FooTable.Sorting#"changed.ft.sorting"
5236 * @see FooTable.Sorting#sort
5237 */
5238 F.Table.prototype.sort = function(column, direction){
5239 return this.use(F.Sorting).sort(column, direction);
5240 };
5241 })(FooTable);
5242 (function($, F){
5243
5244 F.Pager = F.Class.extend(/** @lends FooTable.Pager */{
5245 /**
5246 * The pager object contains the page number and direction to page to.
5247 * @constructs
5248 * @extends FooTable.Class
5249 * @param {number} total - The total number of pages available.
5250 * @param {number} current - The current page number.
5251 * @param {number} size - The number of rows per page.
5252 * @param {number} page - The page number to goto.
5253 * @param {boolean} forward - A boolean indicating the direction of paging, TRUE = forward, FALSE = back.
5254 * @returns {FooTable.Pager}
5255 */
5256 construct: function(total, current, size, page, forward){
5257 /**
5258 * The total number of pages available.
5259 * @type {number}
5260 */
5261 this.total = total;
5262 /**
5263 * The current page number.
5264 * @type {number}
5265 */
5266 this.current = current;
5267 /**
5268 * The number of rows per page.
5269 * @type {number}
5270 */
5271 this.size = size;
5272 /**
5273 * The page number to goto.
5274 * @type {number}
5275 */
5276 this.page = page;
5277 /**
5278 * A boolean indicating the direction of paging, TRUE = forward, FALSE = back.
5279 * @type {boolean}
5280 */
5281 this.forward = forward;
5282 }
5283 });
5284
5285 })(jQuery, FooTable);
5286 (function($, F){
5287 F.Paging = F.Component.extend(/** @lends FooTable.Paging */{
5288 /**
5289 * The paging component adds a pagination control to the table allowing users to navigate table rows via pages.
5290 * @constructs
5291 * @extends FooTable.Component
5292 * @param {FooTable.Table} table - The parent {@link FooTable.Table} object for the component.
5293 * @returns {FooTable.Filtering}
5294 */
5295 construct: function(table){
5296 // call the base constructor
5297 this._super(table, table.o.paging.enabled);
5298
5299 /* PROTECTED */
5300 /**
5301 * An object containing the strings used by the paging buttons.
5302 * @type {{ first: string, prev: string, next: string, last: string }}
5303 */
5304 this.strings = table.o.paging.strings;
5305
5306 /* PUBLIC */
5307 /**
5308 * The current page number to display.
5309 * @instance
5310 * @type {number}
5311 */
5312 this.current = table.o.paging.current;
5313 /**
5314 * The number of rows to display per page.
5315 * @instance
5316 * @type {number}
5317 */
5318 this.size = table.o.paging.size;
5319 /**
5320 * The maximum number of page links to display at once.
5321 * @instance
5322 * @type {number}
5323 */
5324 this.limit = table.o.paging.limit;
5325 /**
5326 * The position of the pagination control within the paging rows cell.
5327 * @instance
5328 * @type {string}
5329 */
5330 this.position = table.o.paging.position;
5331 /**
5332 * The format string used to generate the text displayed under the pagination control.
5333 * @instance
5334 * @type {string}
5335 */
5336 this.countFormat = table.o.paging.countFormat;
5337 /**
5338 * A selector specifying where to place the paging components UI, if null the UI is displayed within a row in the foot of the table.
5339 * @instance
5340 * @type {string}
5341 */
5342 this.container = table.o.paging.container;
5343 /**
5344 * The total number of pages.
5345 * @instance
5346 * @type {number}
5347 */
5348 this.total = -1;
5349 /**
5350 * The number of rows in the {@link FooTable.Rows#array} before paging is applied.
5351 * @instance
5352 * @type {number}
5353 */
5354 this.totalRows = 0;
5355 /**
5356 * A number indicating the previous page displayed.
5357 * @instance
5358 * @type {number}
5359 */
5360 this.previous = -1;
5361 /**
5362 * The count string generated using the {@link FooTable.Filtering#countFormat} option. This value is only set after the first call to the {@link FooTable.Filtering#predraw} method.
5363 * @instance
5364 * @type {string}
5365 */
5366 this.formattedCount = null;
5367 /**
5368 * The jQuery object of the element containing the entire paging UI.
5369 * @instance
5370 * @type {jQuery}
5371 */
5372 this.$container = null;
5373 /**
5374 * The jQuery object of the element wrapping all the paging UI elements.
5375 * @instance
5376 * @type {jQuery}
5377 */
5378 this.$wrapper = null;
5379 /** +
5380 * The jQuery row object that contains all the paging specific elements.
5381 * @instance
5382 * @type {jQuery}
5383 */
5384 this.$row = null;
5385 /**
5386 * The jQuery cell object that contains the pagination control and total count.
5387 * @instance
5388 * @type {jQuery}
5389 */
5390 this.$cell = null;
5391 /**
5392 * The jQuery object that contains the links for the pagination control.
5393 * @instance
5394 * @type {jQuery}
5395 */
5396 this.$pagination = null;
5397 /**
5398 * The jQuery object that contains the row count.
5399 * @instance
5400 * @type {jQuery}
5401 */
5402 this.$count = null;
5403 /**
5404 * Whether or not the pagination row is detached from the table.
5405 * @instance
5406 * @type {boolean}
5407 */
5408 this.detached = true;
5409
5410 /* PRIVATE */
5411 /**
5412 * Used to hold the number of page links created.
5413 * @instance
5414 * @type {number}
5415 * @private
5416 */
5417 this._createdLinks = 0;
5418 },
5419
5420 /* PROTECTED */
5421 /**
5422 * Checks the supplied data and options for the paging component.
5423 * @instance
5424 * @protected
5425 * @param {object} data - The jQuery data object from the parent table.
5426 * @fires FooTable.Paging#"preinit.ft.paging"
5427 */
5428 preinit: function(data){
5429 var self = this;
5430 /**
5431 * The preinit.ft.paging event is raised before the UI is created and provides the tables jQuery data object for additional options parsing.
5432 * Calling preventDefault on this event will disable the component.
5433 * @event FooTable.Paging#"preinit.ft.paging"
5434 * @param {jQuery.Event} e - The jQuery.Event object for the event.
5435 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
5436 * @param {object} data - The jQuery data object of the table raising the event.
5437 */
5438 this.ft.raise('preinit.ft.paging', [data]).then(function(){
5439 if (self.ft.$el.hasClass('footable-paging'))
5440 self.enabled = true;
5441 self.enabled = F.is.boolean(data.paging)
5442 ? data.paging
5443 : self.enabled;
5444
5445 if (!self.enabled) return;
5446
5447 self.size = F.is.number(data.pagingSize)
5448 ? data.pagingSize
5449 : self.size;
5450
5451 self.current = F.is.number(data.pagingCurrent)
5452 ? data.pagingCurrent
5453 : self.current;
5454
5455 self.limit = F.is.number(data.pagingLimit)
5456 ? data.pagingLimit
5457 : self.limit;
5458
5459 if (self.ft.$el.hasClass('footable-paging-left'))
5460 self.position = 'left';
5461 if (self.ft.$el.hasClass('footable-paging-center'))
5462 self.position = 'center';
5463 if (self.ft.$el.hasClass('footable-paging-right'))
5464 self.position = 'right';
5465
5466 self.position = F.is.string(data.pagingPosition)
5467 ? data.pagingPosition
5468 : self.position;
5469
5470 self.countFormat = F.is.string(data.pagingCountFormat)
5471 ? data.pagingCountFormat
5472 : self.countFormat;
5473
5474 self.container = F.is.string(data.pagingContainer)
5475 ? data.pagingContainer
5476 : self.container;
5477
5478 self.total = Math.ceil(self.ft.rows.all.length / self.size);
5479 }, function(){
5480 self.enabled = false;
5481 });
5482 },
5483 /**
5484 * Initializes the paging component for the plugin using the supplied table and options.
5485 * @instance
5486 * @protected
5487 * @fires FooTable.Paging#"init.ft.paging"
5488 */
5489 init: function(){
5490 /**
5491 * The init.ft.paging event is raised before its UI is generated.
5492 * Calling preventDefault on this event will disable the component.
5493 * @event FooTable.Paging#"init.ft.paging"
5494 * @param {jQuery.Event} e - The jQuery.Event object for the event.
5495 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
5496 */
5497 var self = this;
5498 this.ft.raise('init.ft.paging').then(function(){
5499 self.$create();
5500 }, function(){
5501 self.enabled = false;
5502 });
5503 },
5504 /**
5505 * Destroys the paging component removing any UI generated from the table.
5506 * @instance
5507 * @protected
5508 * @fires FooTable.Paging#"destroy.ft.paging"
5509 */
5510 destroy: function () {
5511 /**
5512 * The destroy.ft.paging event is raised before its UI is removed.
5513 * Calling preventDefault on this event will prevent the component from being destroyed.
5514 * @event FooTable.Paging#"destroy.ft.paging"
5515 * @param {jQuery.Event} e - The jQuery.Event object for the event.
5516 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
5517 */
5518 var self = this;
5519 this.ft.raise('destroy.ft.paging').then(function(){
5520 self.ft.$el.removeClass('footable-paging')
5521 .find('tfoot > tr.footable-paging').remove();
5522 self.detached = true;
5523 self._createdLinks = 0;
5524 });
5525 },
5526 /**
5527 * Performs the actual paging against the {@link FooTable.Rows#current} array removing all rows that are not on the current visible page.
5528 * @instance
5529 * @protected
5530 */
5531 predraw: function(){
5532 this.total = Math.ceil(this.ft.rows.array.length / this.size);
5533 this.current = this.current > this.total ? this.total : (this.current < 1 ? 1 : this.current);
5534 this.totalRows = this.ft.rows.array.length;
5535 if (this.totalRows > this.size){
5536 this.ft.rows.array = this.ft.rows.array.splice((this.current - 1) * this.size, this.size);
5537 }
5538 this.formattedCount = this.format(this.countFormat);
5539 },
5540 /**
5541 * Updates the paging UI setting the state of the pagination control.
5542 * @instance
5543 * @protected
5544 */
5545 draw: function(){
5546 if (this.total <= 1){
5547 if (!this.detached){
5548 if (this.$row){
5549 this.$row.detach();
5550 } else {
5551 this.$wrapper.detach();
5552 }
5553 this.detached = true;
5554 }
5555 } else {
5556 if (this.detached){
5557 if (this.$row){
5558 var $tfoot = this.ft.$el.children('tfoot');
5559 if ($tfoot.length == 0){
5560 $tfoot = $('<tfoot/>');
5561 this.ft.$el.append($tfoot);
5562 }
5563 this.$row.appendTo($tfoot);
5564 } else {
5565 this.$wrapper.appendTo(this.$container);
5566 }
5567 this.detached = false;
5568 }
5569 if (F.is.jq(this.$cell)){
5570 this.$cell.attr('colspan', this.ft.columns.visibleColspan);
5571 }
5572 this._createLinks();
5573 this._setVisible(this.current, this.current > this.previous);
5574 this._setNavigation(true);
5575 this.$count.text(this.formattedCount);
5576 }
5577 },
5578 /**
5579 * Creates the paging UI from the current options setting the various jQuery properties of this component.
5580 * @instance
5581 * @protected
5582 */
5583 $create: function(){
5584 this._createdLinks = 0;
5585 var position = 'footable-paging-center';
5586 switch (this.position){
5587 case 'left': position = 'footable-paging-left'; break;
5588 case 'right': position = 'footable-paging-right'; break;
5589 }
5590 this.ft.$el.addClass('footable-paging').addClass(position);
5591
5592 this.$container = this.container === null ? null : $(this.container).first();
5593 if (!F.is.jq(this.$container)){
5594 var $tfoot = this.ft.$el.children('tfoot');
5595 if ($tfoot.length == 0){
5596 $tfoot = $('<tfoot/>');
5597 this.ft.$el.append($tfoot);
5598 }
5599 // add it to a row and then populate it with the search input and column selector dropdown.
5600 this.$row = $('<tr/>', {'class': 'footable-paging'}).prependTo($tfoot);
5601 this.$container = this.$cell = $('<td/>').attr('colspan', this.ft.columns.visibleColspan).appendTo(this.$row);
5602 } else {
5603 this.$container.addClass('footable-paging-external').addClass(position);
5604 }
5605 this.$wrapper = $('<div/>', {'class': 'footable-pagination-wrapper'}).appendTo(this.$container);
5606 this.$pagination = $('<ul/>', { 'class': 'pagination' }).on('click.footable', 'a.footable-page-link', { self: this }, this._onPageClicked);
5607 this.$count = $('<span/>', { 'class': 'label label-default' });
5608 this.$wrapper.append(this.$pagination, $('<div/>', {'class': 'divider'}), this.$count);
5609 this.detached = false;
5610 },
5611
5612 /* PUBLIC */
5613 /**
5614 * @summary Uses the supplied format string and replaces the placeholder strings with the current values.
5615 * @description This method is used to generate the short description label for the pagination control. i.e. Showing X of Y records. The placeholders for this string are the following:
5616 * * {CP} - The current page number.
5617 * * {TP} - The total number of pages.
5618 * * {PF} - The first row of the current page.
5619 * * {PL} - The last row of the current page.
5620 * * {TR} - The total rows available.
5621 * These placeholders can be supplied in a string like; "Showing {PF} to {PL} of {TR} rows."
5622 * @param {string} formatString - The string to be formatted with the paging specific variables.
5623 * @returns {string}
5624 */
5625 format: function(formatString){
5626 var firstRow = (this.size * (this.current - 1)) + 1,
5627 lastRow = this.size * this.current;
5628 if (this.ft.rows.array.length == 0){
5629 firstRow = 0;
5630 lastRow = 0;
5631 } else {
5632 lastRow = lastRow > this.totalRows ? this.totalRows : lastRow;
5633 }
5634 return formatString.replace(/\{CP}/g, this.current)
5635 .replace(/\{TP}/g, this.total)
5636 .replace(/\{PF}/g, firstRow)
5637 .replace(/\{PL}/g, lastRow)
5638 .replace(/\{TR}/g, this.totalRows);
5639 },
5640 /**
5641 * Pages to the first page.
5642 * @instance
5643 * @returns {jQuery.Promise}
5644 * @fires FooTable.Paging#"before.ft.paging"
5645 * @fires FooTable.Paging#"after.ft.paging"
5646 */
5647 first: function(){
5648 return this._set(1);
5649 },
5650 /**
5651 * Pages to the previous page.
5652 * @instance
5653 * @returns {jQuery.Promise}
5654 * @fires FooTable.Paging#"before.ft.paging"
5655 * @fires FooTable.Paging#"after.ft.paging"
5656 */
5657 prev: function(){
5658 return this._set(this.current - 1 > 0 ? this.current - 1 : 1);
5659 },
5660 /**
5661 * Pages to the next page.
5662 * @instance
5663 * @returns {jQuery.Promise}
5664 * @fires FooTable.Paging#"before.ft.paging"
5665 * @fires FooTable.Paging#"after.ft.paging"
5666 */
5667 next: function(){
5668 return this._set(this.current + 1 < this.total ? this.current + 1 : this.total);
5669 },
5670 /**
5671 * Pages to the last page.
5672 * @instance
5673 * @returns {jQuery.Promise}
5674 * @fires FooTable.Paging#"before.ft.paging"
5675 * @fires FooTable.Paging#"after.ft.paging"
5676 */
5677 last: function(){
5678 return this._set(this.total);
5679 },
5680 /**
5681 * Pages to the specified page.
5682 * @instance
5683 * @param {number} page - The page number to go to.
5684 * @returns {jQuery.Promise}
5685 * @fires FooTable.Paging#"before.ft.paging"
5686 * @fires FooTable.Paging#"after.ft.paging"
5687 */
5688 goto: function(page){
5689 return this._set(page > this.total ? this.total : (page < 1 ? 1 : page));
5690 },
5691 /**
5692 * Shows the previous X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit option value.
5693 * @instance
5694 */
5695 prevPages: function(){
5696 var page = this.$pagination.children('li.footable-page.visible:first').data('page') - 1;
5697 this._setVisible(page, true);
5698 this._setNavigation(false);
5699 },
5700 /**
5701 * Shows the next X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit option value.
5702 * @instance
5703 */
5704 nextPages: function(){
5705 var page = this.$pagination.children('li.footable-page.visible:last').data('page') + 1;
5706 this._setVisible(page, false);
5707 this._setNavigation(false);
5708 },
5709 /**
5710 * Gets or sets the current page size.
5711 * @instance
5712 * @param {(number|string)} [value] - The new page size to use, this value is supplied to `parseInt` so strings can be used. If not supplied or an invalid valid the current page size is returned.
5713 * @returns {(number|undefined)}
5714 */
5715 pageSize: function(value){
5716 value = parseInt(value);
5717 if (isNaN(value)){
5718 return this.size;
5719 }
5720 this.size = value;
5721 this.total = Math.ceil(this.ft.rows.all.length / this.size);
5722 if (F.is.jq(this.$wrapper)){
5723 if (this.$container.is("td")){
5724 this.$row.remove();
5725 } else {
5726 this.$wrapper.remove();
5727 }
5728 }
5729 this.$create();
5730 this.ft.draw();
5731 },
5732
5733 /* PRIVATE */
5734 /**
5735 * Performs the required steps to handle paging including the raising of the {@link FooTable.Paging#"before.ft.paging"} and {@link FooTable.Paging#"after.ft.paging"} events.
5736 * @instance
5737 * @private
5738 * @param {number} page - The page to set.
5739 * @returns {jQuery.Promise}
5740 * @fires FooTable.Paging#"before.ft.paging"
5741 * @fires FooTable.Paging#"after.ft.paging"
5742 */
5743 _set: function(page){
5744 var self = this,
5745 pager = new F.Pager(self.total, self.current, self.size, page, page > self.current);
5746 /**
5747 * The before.ft.paging event is raised before a sort is applied and allows listeners to modify the pager or cancel it completely by calling preventDefault on the jQuery.Event object.
5748 * @event FooTable.Paging#"before.ft.paging"
5749 * @param {jQuery.Event} e - The jQuery.Event object for the event.
5750 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
5751 * @param {FooTable.Pager} pager - The pager that is about to be applied.
5752 */
5753 return self.ft.raise('before.ft.paging', [pager]).then(function(){
5754 pager.page = pager.page > pager.total ? pager.total : pager.page;
5755 pager.page = pager.page < 1 ? 1 : pager.page;
5756 if (self.current == page) return $.when();
5757 self.previous = self.current;
5758 self.current = pager.page;
5759 return self.ft.draw().then(function(){
5760 /**
5761 * The after.ft.paging event is raised after a pager has been applied.
5762 * @event FooTable.Paging#"after.ft.paging"
5763 * @param {jQuery.Event} e - The jQuery.Event object for the event.
5764 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
5765 * @param {FooTable.Pager} pager - The pager that has been applied.
5766 */
5767 self.ft.raise('after.ft.paging', [pager]);
5768 });
5769 });
5770 },
5771 /**
5772 * Creates the pagination links using the current state of the plugin. If the total number of pages is the same as
5773 * the last time this function was executed it does nothing.
5774 * @instance
5775 * @private
5776 */
5777 _createLinks: function(){
5778 if (this._createdLinks === this.total) return;
5779 var self = this,
5780 multiple = self.total > 1,
5781 link = function(attr, html, klass){
5782 return $('<li/>', {
5783 'class': klass
5784 }).attr('data-page', attr)
5785 .append($('<a/>', {
5786 'class': 'footable-page-link',
5787 href: '#'
5788 }).data('page', attr).html(html));
5789 };
5790 self.$pagination.empty();
5791 if (multiple) {
5792 self.$pagination.append(link('first', self.strings.first, 'footable-page-nav'));
5793 self.$pagination.append(link('prev', self.strings.prev, 'footable-page-nav'));
5794 if (self.limit > 0 && self.limit < self.total){
5795 self.$pagination.append(link('prev-limit', self.strings.prevPages, 'footable-page-nav'));
5796 }
5797 }
5798 for (var i = 0, $li; i < self.total; i++){
5799 $li = link(i + 1, i + 1, 'footable-page');
5800 self.$pagination.append($li);
5801 }
5802 if (multiple){
5803 if (self.limit > 0 && self.limit < self.total){
5804 self.$pagination.append(link('next-limit', self.strings.nextPages, 'footable-page-nav'));
5805 }
5806 self.$pagination.append(link('next', self.strings.next, 'footable-page-nav'));
5807 self.$pagination.append(link('last', self.strings.last, 'footable-page-nav'));
5808 }
5809 self._createdLinks = self.total;
5810 },
5811 /**
5812 * Sets the state for the navigation links of the pagination control and optionally sets the active class state on the current page link.
5813 * @instance
5814 * @private
5815 * @param {boolean} active - Whether or not to set the active class state on the individual page links.
5816 */
5817 _setNavigation: function(active){
5818 if (this.current == 1) {
5819 this.$pagination.children('li[data-page="first"],li[data-page="prev"]').addClass('disabled');
5820 } else {
5821 this.$pagination.children('li[data-page="first"],li[data-page="prev"]').removeClass('disabled');
5822 }
5823
5824 if (this.current == this.total) {
5825 this.$pagination.children('li[data-page="next"],li[data-page="last"]').addClass('disabled');
5826 } else {
5827 this.$pagination.children('li[data-page="next"],li[data-page="last"]').removeClass('disabled');
5828 }
5829
5830 if ((this.$pagination.children('li.footable-page.visible:first').data('page') || 1) == 1) {
5831 this.$pagination.children('li[data-page="prev-limit"]').addClass('disabled');
5832 } else {
5833 this.$pagination.children('li[data-page="prev-limit"]').removeClass('disabled');
5834 }
5835
5836 if ((this.$pagination.children('li.footable-page.visible:last').data('page') || this.limit) == this.total) {
5837 this.$pagination.children('li[data-page="next-limit"]').addClass('disabled');
5838 } else {
5839 this.$pagination.children('li[data-page="next-limit"]').removeClass('disabled');
5840 }
5841
5842 if (this.limit > 0 && this.total < this.limit){
5843 this.$pagination.children('li[data-page="prev-limit"],li[data-page="next-limit"]').css('display', 'none');
5844 } else {
5845 this.$pagination.children('li[data-page="prev-limit"],li[data-page="next-limit"]').css('display', '');
5846 }
5847
5848 if (active){
5849 this.$pagination.children('li.footable-page').removeClass('active').filter('li[data-page="' + this.current + '"]').addClass('active');
5850 }
5851 },
5852 /**
5853 * Sets the visible page using the supplied parameters.
5854 * @instance
5855 * @private
5856 * @param {number} page - The page to make visible.
5857 * @param {boolean} right - If set to true the supplied page will be the right most visible pagination link.
5858 */
5859 _setVisible: function(page, right){
5860 if (this.limit > 0 && this.total > this.limit){
5861 if (!this.$pagination.children('li.footable-page[data-page="'+page+'"]').hasClass('visible')){
5862 var start = 0, end = 0;
5863 if (right == true){
5864 end = page > this.total ? this.total : page;
5865 start = end - this.limit;
5866 } else {
5867 start = page < 1 ? 0 : page - 1;
5868 end = start + this.limit;
5869 }
5870 if (start < 0){
5871 start = 0;
5872 end = this.limit > this.total ? this.total : this.limit;
5873 }
5874 if (end > this.total){
5875 end = this.total;
5876 start = this.total - this.limit < 0 ? 0 : this.total - this.limit;
5877 }
5878 this.$pagination.children('li.footable-page').removeClass('visible').slice(start, end).addClass('visible');
5879 }
5880 } else {
5881 this.$pagination.children('li.footable-page').removeClass('visible').slice(0, this.total).addClass('visible');
5882 }
5883 },
5884 /**
5885 * Handles the click event for all links in the pagination control.
5886 * @instance
5887 * @private
5888 * @param {jQuery.Event} e - The event object for the event.
5889 */
5890 _onPageClicked: function(e){
5891 e.preventDefault();
5892 if ($(e.target).closest('li').is('.active,.disabled')) return;
5893
5894 var self = e.data.self, page = $(this).data('page');
5895 switch(page){
5896 case 'first': self.first();
5897 return;
5898 case 'prev': self.prev();
5899 return;
5900 case 'next': self.next();
5901 return;
5902 case 'last': self.last();
5903 return;
5904 case 'prev-limit': self.prevPages();
5905 return;
5906 case 'next-limit': self.nextPages();
5907 return;
5908 default: self._set(page);
5909 return;
5910 }
5911 }
5912 });
5913
5914 F.components.register('paging', F.Paging, 400);
5915
5916 })(jQuery, FooTable);
5917 (function(F){
5918 /**
5919 * An object containing the paging options for the plugin. Added by the {@link FooTable.Paging} component.
5920 * @type {object}
5921 * @prop {boolean} enabled=false - Whether or not to allow paging on the table.
5922 * @prop {string} countFormat="{CP} of {TP}" - A string format used to generate the page count text.
5923 * @prop {number} current=1 - The page number to display.
5924 * @prop {number} limit=5 - The maximum number of page links to display at once.
5925 * @prop {string} position="center" - The string used to specify the alignment of the pagination control.
5926 * @prop {number} size=10 - The number of rows displayed per page.
5927 * @prop {string} container=null - A selector specifying where to place the paging components UI, if null the UI is displayed within a row in the foot of the table.
5928 * @prop {object} strings - An object containing the strings used by the paging buttons.
5929 * @prop {string} strings.first="&laquo;" - The string used for the 'first' button.
5930 * @prop {string} strings.prev="&lsaquo;" - The string used for the 'previous' button.
5931 * @prop {string} strings.next="&rsaquo;" - The string used for the 'next' button.
5932 * @prop {string} strings.last="&raquo;" - The string used for the 'last' button.
5933 * @prop {string} strings.prevPages="..." - The string used for the 'previous X pages' button.
5934 * @prop {string} strings.nextPages="..." - The string used for the 'next X pages' button.
5935 */
5936 F.Defaults.prototype.paging = {
5937 enabled: false,
5938 countFormat: '{CP} of {TP}',
5939 current: 1,
5940 limit: 5,
5941 position: 'center',
5942 size: 10,
5943 container: null,
5944 strings: {
5945 first: '&laquo;',
5946 prev: '&lsaquo;',
5947 next: '&rsaquo;',
5948 last: '&raquo;',
5949 prevPages: '...',
5950 nextPages: '...'
5951 }
5952 };
5953 })(FooTable);
5954 (function(F){
5955 /**
5956 * Navigates to the specified page number. Added by the {@link FooTable.Paging} component.
5957 * @instance
5958 * @param {number} num - The page number to go to.
5959 * @returns {jQuery.Promise}
5960 * @fires FooTable.Paging#paging_changing
5961 * @fires FooTable.Paging#paging_changed
5962 * @see FooTable.Paging#goto
5963 */
5964 F.Table.prototype.gotoPage = function(num){
5965 return this.use(F.Paging).goto(num);
5966 };
5967
5968 /**
5969 * Navigates to the next page. Added by the {@link FooTable.Paging} component.
5970 * @instance
5971 * @returns {jQuery.Promise}
5972 * @fires FooTable.Paging#paging_changing
5973 * @fires FooTable.Paging#paging_changed
5974 * @see FooTable.Paging#next
5975 */
5976 F.Table.prototype.nextPage = function(){
5977 return this.use(F.Paging).next();
5978 };
5979
5980 /**
5981 * Navigates to the previous page. Added by the {@link FooTable.Paging} component.
5982 * @instance
5983 * @returns {jQuery.Promise}
5984 * @fires FooTable.Paging#paging_changing
5985 * @fires FooTable.Paging#paging_changed
5986 * @see FooTable.Paging#prev
5987 */
5988 F.Table.prototype.prevPage = function(){
5989 return this.use(F.Paging).prev();
5990 };
5991
5992 /**
5993 * Navigates to the first page. Added by the {@link FooTable.Paging} component.
5994 * @instance
5995 * @returns {jQuery.Promise}
5996 * @fires FooTable.Paging#paging_changing
5997 * @fires FooTable.Paging#paging_changed
5998 * @see FooTable.Paging#first
5999 */
6000 F.Table.prototype.firstPage = function(){
6001 return this.use(F.Paging).first();
6002 };
6003
6004 /**
6005 * Navigates to the last page. Added by the {@link FooTable.Paging} component.
6006 * @instance
6007 * @returns {jQuery.Promise}
6008 * @fires FooTable.Paging#paging_changing
6009 * @fires FooTable.Paging#paging_changed
6010 * @see FooTable.Paging#last
6011 */
6012 F.Table.prototype.lastPage = function(){
6013 return this.use(F.Paging).last();
6014 };
6015
6016 /**
6017 * Shows the next X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit.size option value. Added by the {@link FooTable.Paging} component.
6018 * @instance
6019 * @see FooTable.Paging#nextPages
6020 */
6021 F.Table.prototype.nextPages = function(){
6022 return this.use(F.Paging).nextPages();
6023 };
6024
6025 /**
6026 * Shows the previous X number of pages in the pagination control where X is the value set by the {@link FooTable.Defaults#paging} - limit.size option value. Added by the {@link FooTable.Paging} component.
6027 * @instance
6028 * @see FooTable.Paging#prevPages
6029 */
6030 F.Table.prototype.prevPages = function(){
6031 return this.use(F.Paging).prevPages();
6032 };
6033
6034 /**
6035 * Gets or sets the current page size
6036 * @instance
6037 * @param {number} [value] - The new page size to use.
6038 * @returns {(number|undefined)}
6039 * @see FooTable.Paging#pageSize
6040 */
6041 F.Table.prototype.pageSize = function(value){
6042 return this.use(F.Paging).pageSize(value);
6043 };
6044 })(FooTable);
6045 (function($, F){
6046
6047 F.Editing = F.Component.extend(/** @lends FooTable.Editing */{
6048 /**
6049 * The editing component adds a column with edit and delete buttons to each row as well as a single add row button in the footer.
6050 * @constructs
6051 * @extends FooTable.Component
6052 * @param {FooTable.Table} table - The parent {@link FooTable.Table} object for the component.
6053 * @returns {FooTable.Editing}
6054 */
6055 construct: function(table){
6056 // call the base constructor
6057 this._super(table, table.o.editing.enabled);
6058
6059 /**
6060 * Whether or not to automatically page to a new row when it is added to the table.
6061 * @type {boolean}
6062 */
6063 this.pageToNew = table.o.editing.pageToNew;
6064
6065 /**
6066 * Whether or not the editing column and add row button are always visible.
6067 * @type {boolean}
6068 */
6069 this.alwaysShow = table.o.editing.alwaysShow;
6070
6071 /**
6072 * The options for the editing column. @see {@link FooTable.EditingColumn} for more info.
6073 * @type {object}
6074 * @prop {string} classes="footable-editing" - A space separated string of class names to apply to all cells in the column.
6075 * @prop {string} name="editing" - The name of the column.
6076 * @prop {string} title="" - The title displayed in the header row of the table for the column.
6077 * @prop {boolean} filterable=false - Whether or not the column should be filterable when using the filtering component.
6078 * @prop {boolean} sortable=false - Whether or not the column should be sortable when using the sorting component.
6079 */
6080 this.column = $.extend(true, {}, table.o.editing.column, {visible: this.alwaysShow});
6081
6082 /**
6083 * The position of the editing column in the table as well as the alignment of the buttons.
6084 * @type {string}
6085 */
6086 this.position = table.o.editing.position;
6087
6088
6089 /**
6090 * The text that appears in the show button. This can contain HTML.
6091 * @type {string}
6092 */
6093 this.showText = table.o.editing.showText;
6094
6095 /**
6096 * The text that appears in the hide button. This can contain HTML.
6097 * @type {string}
6098 */
6099 this.hideText = table.o.editing.hideText;
6100
6101 /**
6102 * The text that appears in the add button. This can contain HTML.
6103 * @type {string}
6104 */
6105 this.addText = table.o.editing.addText;
6106
6107 /**
6108 * The text that appears in the edit button. This can contain HTML.
6109 * @type {string}
6110 */
6111 this.editText = table.o.editing.editText;
6112
6113 /**
6114 * The text that appears in the delete button. This can contain HTML.
6115 * @type {string}
6116 */
6117 this.deleteText = table.o.editing.deleteText;
6118
6119 /**
6120 * The text that appears in the view button. This can contain HTML.
6121 * @type {string}
6122 */
6123 this.viewText = table.o.editing.viewText;
6124
6125 /**
6126 * Whether or not to show the Add Row button.
6127 * @type {boolean}
6128 */
6129 this.allowAdd = table.o.editing.allowAdd;
6130
6131 /**
6132 * Whether or not to show the Edit Row button.
6133 * @type {boolean}
6134 */
6135 this.allowEdit = table.o.editing.allowEdit;
6136
6137 /**
6138 * Whether or not to show the Delete Row button.
6139 * @type {boolean}
6140 */
6141 this.allowDelete = table.o.editing.allowDelete;
6142
6143 /**
6144 * Whether or not to show the View Row button.
6145 * @type {boolean}
6146 */
6147 this.allowView = table.o.editing.allowView;
6148
6149 /**
6150 * Caches the row button elements to help with performance.
6151 * @type {(null|jQuery)}
6152 * @private
6153 */
6154 this._$buttons = null;
6155
6156 /**
6157 * This object is used to contain the callbacks for the add, edit and delete row buttons.
6158 * @type {object}
6159 * @prop {function} addRow
6160 * @prop {function} editRow
6161 * @prop {function} deleteRow
6162 * @prop {function} viewRow
6163 */
6164 this.callbacks = {
6165 addRow: F.checkFnValue(this, table.o.editing.addRow),
6166 editRow: F.checkFnValue(this, table.o.editing.editRow),
6167 deleteRow: F.checkFnValue(this, table.o.editing.deleteRow),
6168 viewRow: F.checkFnValue(this, table.o.editing.viewRow)
6169 };
6170 },
6171 /* PROTECTED */
6172 /**
6173 * Checks the supplied data and options for the editing component.
6174 * @instance
6175 * @protected
6176 * @param {object} data - The jQuery data object from the parent table.
6177 * @fires FooTable.Editing#"preinit.ft.editing"
6178 */
6179 preinit: function(data){
6180 var self = this;
6181 /**
6182 * The preinit.ft.editing event is raised before the UI is created and provides the tables jQuery data object for additional options parsing.
6183 * Calling preventDefault on this event will disable the component.
6184 * @event FooTable.Editing#"preinit.ft.editing"
6185 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6186 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
6187 * @param {object} data - The jQuery data object of the table raising the event.
6188 */
6189 this.ft.raise('preinit.ft.editing', [data]).then(function(){
6190 if (self.ft.$el.hasClass('footable-editing'))
6191 self.enabled = true;
6192
6193 self.enabled = F.is.boolean(data.editing)
6194 ? data.editing
6195 : self.enabled;
6196
6197 if (!self.enabled) return;
6198
6199 self.pageToNew = F.is.boolean(data.editingPageToNew) ? data.editingPageToNew : self.pageToNew;
6200
6201 self.alwaysShow = F.is.boolean(data.editingAlwaysShow) ? data.editingAlwaysShow : self.alwaysShow;
6202
6203 self.position = F.is.string(data.editingPosition) ? data.editingPosition : self.position;
6204
6205 self.showText = F.is.string(data.editingShowText) ? data.editingShowText : self.showText;
6206
6207 self.hideText = F.is.string(data.editingHideText) ? data.editingHideText : self.hideText;
6208
6209 self.addText = F.is.string(data.editingAddText) ? data.editingAddText : self.addText;
6210
6211 self.editText = F.is.string(data.editingEditText) ? data.editingEditText : self.editText;
6212
6213 self.deleteText = F.is.string(data.editingDeleteText) ? data.editingDeleteText : self.deleteText;
6214
6215 self.viewText = F.is.string(data.editingViewText) ? data.editingViewText : self.viewText;
6216
6217 self.allowAdd = F.is.boolean(data.editingAllowAdd) ? data.editingAllowAdd : self.allowAdd;
6218
6219 self.allowEdit = F.is.boolean(data.editingAllowEdit) ? data.editingAllowEdit : self.allowEdit;
6220
6221 self.allowDelete = F.is.boolean(data.editingAllowDelete) ? data.editingAllowDelete : self.allowDelete;
6222
6223 self.allowView = F.is.boolean(data.editingAllowView) ? data.editingAllowView : self.allowView;
6224
6225 self.column = new F.EditingColumn(self.ft, self, $.extend(true, {}, self.column, data.editingColumn, {visible: self.alwaysShow}));
6226
6227 if (self.ft.$el.hasClass('footable-editing-left'))
6228 self.position = 'left';
6229
6230 if (self.ft.$el.hasClass('footable-editing-right'))
6231 self.position = 'right';
6232
6233 if (self.position === 'right'){
6234 self.column.index = self.ft.columns.array.length;
6235 } else {
6236 self.column.index = 0;
6237 for (var i = 0, len = self.ft.columns.array.length; i < len; i++){
6238 self.ft.columns.array[i].index += 1;
6239 }
6240 }
6241 self.ft.columns.array.push(self.column);
6242 self.ft.columns.array.sort(function(a, b){ return a.index - b.index; });
6243
6244 self.callbacks.addRow = F.checkFnValue(self, data.editingAddRow, self.callbacks.addRow);
6245 self.callbacks.editRow = F.checkFnValue(self, data.editingEditRow, self.callbacks.editRow);
6246 self.callbacks.deleteRow = F.checkFnValue(self, data.editingDeleteRow, self.callbacks.deleteRow);
6247 self.callbacks.viewRow = F.checkFnValue(self, data.editingViewRow, self.callbacks.viewRow);
6248 }, function(){
6249 self.enabled = false;
6250 });
6251 },
6252 /**
6253 * Initializes the editing component for the plugin using the supplied table and options.
6254 * @instance
6255 * @protected
6256 * @fires FooTable.Editing#"init.ft.editing"
6257 */
6258 init: function(){
6259 /**
6260 * The init.ft.editing event is raised before its UI is generated.
6261 * Calling preventDefault on this event will disable the component.
6262 * @event FooTable.Editing#"init.ft.editing"
6263 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6264 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
6265 */
6266 var self = this;
6267 this.ft.raise('init.ft.editing').then(function(){
6268 self.$create();
6269 }, function(){
6270 self.enabled = false;
6271 });
6272 },
6273 /**
6274 * Destroys the editing component removing any UI generated from the table.
6275 * @instance
6276 * @protected
6277 * @fires FooTable.Editing#"destroy.ft.editing"
6278 */
6279 destroy: function () {
6280 /**
6281 * The destroy.ft.editing event is raised before its UI is removed.
6282 * Calling preventDefault on this event will prevent the component from being destroyed.
6283 * @event FooTable.Editing#"destroy.ft.editing"
6284 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6285 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
6286 */
6287 var self = this;
6288 this.ft.raise('destroy.ft.editing').then(function(){
6289 self.ft.$el.removeClass('footable-editing footable-editing-always-show footable-editing-no-add footable-editing-no-edit footable-editing-no-delete footable-editing-no-view')
6290 .off('click.ft.editing').find('tfoot > tr.footable-editing').remove();
6291 });
6292 },
6293 /**
6294 * Creates the editing UI from the current options setting the various jQuery properties of this component.
6295 * @instance
6296 * @protected
6297 */
6298 $create: function(){
6299 var self = this, position = self.position === 'right' ? 'footable-editing-right' : 'footable-editing-left';
6300 self.ft.$el.addClass('footable-editing').addClass(position)
6301 .on('click.ft.editing', '.footable-show', {self: self}, self._onShowClick)
6302 .on('click.ft.editing', '.footable-hide', {self: self}, self._onHideClick)
6303 .on('click.ft.editing', '.footable-edit', {self: self}, self._onEditClick)
6304 .on('click.ft.editing', '.footable-delete', {self: self}, self._onDeleteClick)
6305 .on('click.ft.editing', '.footable-view', {self: self}, self._onViewClick)
6306 .on('click.ft.editing', '.footable-add', {self: self}, self._onAddClick);
6307
6308 self.$cell = $('<td/>').attr('colspan', self.ft.columns.visibleColspan).append(self.$buttonShow());
6309 if (self.allowAdd){
6310 self.$cell.append(self.$buttonAdd());
6311 }
6312 self.$cell.append(self.$buttonHide());
6313
6314 if (self.alwaysShow){
6315 self.ft.$el.addClass('footable-editing-always-show');
6316 }
6317
6318 if (!self.allowAdd) self.ft.$el.addClass('footable-editing-no-add');
6319 if (!self.allowEdit) self.ft.$el.addClass('footable-editing-no-edit');
6320 if (!self.allowDelete) self.ft.$el.addClass('footable-editing-no-delete');
6321 if (!self.allowView) self.ft.$el.addClass('footable-editing-no-view');
6322
6323 var $tfoot = self.ft.$el.children('tfoot');
6324 if ($tfoot.length == 0){
6325 $tfoot = $('<tfoot/>');
6326 self.ft.$el.append($tfoot);
6327 }
6328 self.$row = $('<tr/>', { 'class': 'footable-editing' }).append(self.$cell).appendTo($tfoot);
6329 },
6330 /**
6331 * Creates the show button for the editing component.
6332 * @instance
6333 * @protected
6334 * @returns {(string|HTMLElement|jQuery)}
6335 */
6336 $buttonShow: function(){
6337 return '<button type="button" class="btn btn-primary footable-show">' + this.showText + '</button>';
6338 },
6339 /**
6340 * Creates the hide button for the editing component.
6341 * @instance
6342 * @protected
6343 * @returns {(string|HTMLElement|jQuery)}
6344 */
6345 $buttonHide: function(){
6346 return '<button type="button" class="btn btn-default footable-hide">' + this.hideText + '</button>';
6347 },
6348 /**
6349 * Creates the add button for the editing component.
6350 * @instance
6351 * @protected
6352 * @returns {(string|HTMLElement|jQuery)}
6353 */
6354 $buttonAdd: function(){
6355 return '<button type="button" class="btn btn-primary footable-add">' + this.addText + '</button> ';
6356 },
6357 /**
6358 * Creates the edit button for the editing component.
6359 * @instance
6360 * @protected
6361 * @returns {(string|HTMLElement|jQuery)}
6362 */
6363 $buttonEdit: function(){
6364 return '<button type="button" class="btn btn-default footable-edit">' + this.editText + '</button> ';
6365 },
6366 /**
6367 * Creates the delete button for the editing component.
6368 * @instance
6369 * @protected
6370 * @returns {(string|HTMLElement|jQuery)}
6371 */
6372 $buttonDelete: function(){
6373 return '<button type="button" class="btn btn-default footable-delete">' + this.deleteText + '</button>';
6374 },
6375 /**
6376 * Creates the view button for the editing component.
6377 * @instance
6378 * @protected
6379 * @returns {(string|HTMLElement|jQuery)}
6380 */
6381 $buttonView: function(){
6382 return '<button type="button" class="btn btn-default footable-view">' + this.viewText + '</button> ';
6383 },
6384 /**
6385 * Creates the button group for the row buttons.
6386 * @instance
6387 * @protected
6388 * @returns {(string|HTMLElement|jQuery)}
6389 */
6390 $rowButtons: function(){
6391 if (F.is.jq(this._$buttons)) return this._$buttons.clone();
6392 this._$buttons = $('<div class="btn-group btn-group-xs" role="group"></div>');
6393 if (this.allowView) this._$buttons.append(this.$buttonView());
6394 if (this.allowEdit) this._$buttons.append(this.$buttonEdit());
6395 if (this.allowDelete) this._$buttons.append(this.$buttonDelete());
6396 return this._$buttons;
6397 },
6398 /**
6399 * Performs the drawing of the component.
6400 */
6401 draw: function(){
6402 this.$cell.attr('colspan', this.ft.columns.visibleColspan);
6403 },
6404 /**
6405 * Handles the edit button click event.
6406 * @instance
6407 * @private
6408 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6409 * @fires FooTable.Editing#"edit.ft.editing"
6410 */
6411 _onEditClick: function(e){
6412 e.preventDefault();
6413 var self = e.data.self, row = $(this).closest('tr').data('__FooTableRow__');
6414 if (row instanceof F.Row){
6415 /**
6416 * The edit.ft.editing event is raised before its callback is executed.
6417 * Calling preventDefault on this event will prevent the callback from being executed.
6418 * @event FooTable.Editing#"edit.ft.editing"
6419 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6420 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
6421 * @param {FooTable.Row} row - The row to be edited.
6422 */
6423 self.ft.raise('edit.ft.editing', [row]).then(function(){
6424 self.callbacks.editRow.call(self.ft, row);
6425 });
6426 }
6427 },
6428 /**
6429 * Handles the delete button click event.
6430 * @instance
6431 * @private
6432 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6433 * @fires FooTable.Editing#"delete.ft.editing"
6434 */
6435 _onDeleteClick: function(e){
6436 e.preventDefault();
6437 var self = e.data.self, row = $(this).closest('tr').data('__FooTableRow__');
6438 if (row instanceof F.Row){
6439 /**
6440 * The delete.ft.editing event is raised before its callback is executed.
6441 * Calling preventDefault on this event will prevent the callback from being executed.
6442 * @event FooTable.Editing#"delete.ft.editing"
6443 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6444 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
6445 * @param {FooTable.Row} row - The row to be deleted.
6446 */
6447 self.ft.raise('delete.ft.editing', [row]).then(function(){
6448 self.callbacks.deleteRow.call(self.ft, row);
6449 });
6450 }
6451 },
6452 /**
6453 * Handles the view button click event.
6454 * @instance
6455 * @private
6456 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6457 * @fires FooTable.Editing#"view.ft.editing"
6458 */
6459 _onViewClick: function(e){
6460 e.preventDefault();
6461 var self = e.data.self, row = $(this).closest('tr').data('__FooTableRow__');
6462 if (row instanceof F.Row){
6463 /**
6464 * The view.ft.editing event is raised before its callback is executed.
6465 * Calling preventDefault on this event will prevent the callback from being executed.
6466 * @event FooTable.Editing#"view.ft.editing"
6467 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6468 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
6469 * @param {FooTable.Row} row - The row to be viewed.
6470 */
6471 self.ft.raise('view.ft.editing', [row]).then(function(){
6472 self.callbacks.viewRow.call(self.ft, row);
6473 });
6474 }
6475 },
6476 /**
6477 * Handles the add button click event.
6478 * @instance
6479 * @private
6480 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6481 * @fires FooTable.Editing#"add.ft.editing"
6482 */
6483 _onAddClick: function(e){
6484 e.preventDefault();
6485 var self = e.data.self;
6486 /**
6487 * The add.ft.editing event is raised before its callback is executed.
6488 * Calling preventDefault on this event will prevent the callback from being executed.
6489 * @event FooTable.Editing#"add.ft.editing"
6490 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6491 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
6492 */
6493 self.ft.raise('add.ft.editing').then(function(){
6494 self.callbacks.addRow.call(self.ft);
6495 });
6496 },
6497 /**
6498 * Handles the show button click event.
6499 * @instance
6500 * @private
6501 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6502 * @fires FooTable.Editing#"show.ft.editing"
6503 */
6504 _onShowClick: function(e){
6505 e.preventDefault();
6506 var self = e.data.self;
6507 /**
6508 * The show.ft.editing event is raised before its callback is executed.
6509 * Calling preventDefault on this event will prevent the callback from being executed.
6510 * @event FooTable.Editing#"show.ft.editing"
6511 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6512 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
6513 */
6514 self.ft.raise('show.ft.editing').then(function(){
6515 self.ft.$el.addClass('footable-editing-show');
6516 self.column.visible = true;
6517 self.ft.draw();
6518 });
6519 },
6520 /**
6521 * Handles the hide button click event.
6522 * @instance
6523 * @private
6524 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6525 * @fires FooTable.Editing#"show.ft.editing"
6526 */
6527 _onHideClick: function(e){
6528 e.preventDefault();
6529 var self = e.data.self;
6530 /**
6531 * The hide.ft.editing event is raised before its callback is executed.
6532 * Calling preventDefault on this event will prevent the callback from being executed.
6533 * @event FooTable.Editing#"hide.ft.editing"
6534 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6535 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
6536 */
6537 self.ft.raise('hide.ft.editing').then(function(){
6538 self.ft.$el.removeClass('footable-editing-show');
6539 self.column.visible = false;
6540 self.ft.draw();
6541 });
6542 }
6543 });
6544
6545 F.components.register('editing', F.Editing, 850);
6546
6547 })(jQuery, FooTable);
6548
6549 (function($, F){
6550
6551 F.EditingColumn = F.Column.extend(/** @lends FooTable.EditingColumn */{
6552 /**
6553 * The Editing column class is used to create the column containing the editing buttons.
6554 * @constructs
6555 * @extends FooTable.Column
6556 * @param {FooTable.Table} instance - The parent {@link FooTable.Table} this column belongs to.
6557 * @param {FooTable.Editing} editing - The parent {@link FooTable.Editing} component this column is used with.
6558 * @param {object} definition - An object containing all the properties to set for the column.
6559 * @returns {FooTable.EditingColumn}
6560 */
6561 construct: function(instance, editing, definition){
6562 this._super(instance, definition, 'editing');
6563 this.editing = editing;
6564 this.internal = true;
6565 },
6566 /**
6567 * After the column has been defined this ensures that the $el property is a jQuery object by either creating or updating the current value.
6568 * @instance
6569 * @protected
6570 * @this FooTable.Column
6571 */
6572 $create: function(){
6573 (this.$el = !this.virtual && F.is.jq(this.$el) ? this.$el : $('<th/>', {'class': 'footable-editing'})).html(this.title);
6574 },
6575 /**
6576 * This is supplied either the cell value or jQuery object to parse. Any value can be returned from this method and
6577 * will be provided to the {@link FooTable.EditingColumn#format} function
6578 * to generate the cell contents.
6579 * @instance
6580 * @protected
6581 * @param {(*|jQuery)} valueOrElement - The value or jQuery cell object.
6582 * @returns {(jQuery)}
6583 */
6584 parser: function(valueOrElement){
6585 if (F.is.string(valueOrElement)) valueOrElement = $($.trim(valueOrElement));
6586 if (F.is.element(valueOrElement)) valueOrElement = $(valueOrElement);
6587 if (F.is.jq(valueOrElement)){
6588 var tagName = valueOrElement.prop('tagName').toLowerCase();
6589 if (tagName == 'td' || tagName == 'th') return valueOrElement.data('value') || valueOrElement.contents();
6590 return valueOrElement;
6591 }
6592 return null;
6593 },
6594 /**
6595 * Creates a cell to be used in the supplied row for this column.
6596 * @param {FooTable.Row} row - The row to create the cell for.
6597 * @returns {FooTable.Cell}
6598 */
6599 createCell: function(row){
6600 var $buttons = this.editing.$rowButtons(), $cell = $('<td/>').append($buttons);
6601 if (F.is.jq(row.$el)){
6602 if (this.index === 0){
6603 $cell.prependTo(row.$el);
6604 } else {
6605 $cell.insertAfter(row.$el.children().eq(this.index-1));
6606 }
6607 }
6608 return new F.Cell(this.ft, row, this, $cell || $cell.html());
6609 }
6610 });
6611
6612 F.columns.register('editing', F.EditingColumn);
6613
6614 })(jQuery, FooTable);
6615 (function($, F) {
6616
6617 /**
6618 * An object containing the editing options for the plugin. Added by the {@link FooTable.Editing} component.
6619 * @type {object}
6620 * @prop {boolean} enabled=false - Whether or not to allow editing on the table.
6621 * @prop {boolean} pageToNew=true - Whether or not to automatically page to a new row when it is added to the table.
6622 * @prop {string} position="right" - The position of the editing column in the table as well as the alignment of the buttons.
6623 * @prop {boolean} alwaysShow=false - Whether or not the editing column and add row button are always visible.
6624 * @prop {function} addRow - The callback function to execute when the add row button is clicked.
6625 * @prop {function} editRow - The callback function to execute when the edit row button is clicked.
6626 * @prop {function} deleteRow - The callback function to execute when the delete row button is clicked.
6627 * @prop {function} viewRow - The callback function to execute when the view row button is clicked.
6628 * @prop {string} showText - The text that appears in the show button. This can contain HTML.
6629 * @prop {string} hideText - The text that appears in the hide button. This can contain HTML.
6630 * @prop {string} addText - The text that appears in the add button. This can contain HTML.
6631 * @prop {string} editText - The text that appears in the edit button. This can contain HTML.
6632 * @prop {string} deleteText - The text that appears in the delete button. This can contain HTML.
6633 * @prop {string} viewText - The text that appears in the view button. This can contain HTML.
6634 * @prop {boolean} allowAdd - Whether or not to show the Add Row button.
6635 * @prop {boolean} allowEdit - Whether or not to show the Edit Row button.
6636 * @prop {boolean} allowDelete - Whether or not to show the Delete Row button.
6637 * @prop {boolean} allowView - Whether or not to show the View Row button.
6638 * @prop {object} column - The options for the editing column. @see {@link FooTable.EditingColumn} for more info.
6639 * @prop {string} column.classes="footable-editing" - A space separated string of class names to apply to all cells in the column.
6640 * @prop {string} column.name="editing" - The name of the column.
6641 * @prop {string} column.title="" - The title displayed in the header row of the table for the column.
6642 * @prop {boolean} column.filterable=false - Whether or not the column should be filterable when using the filtering component.
6643 * @prop {boolean} column.sortable=false - Whether or not the column should be sortable when using the sorting component.
6644 */
6645 F.Defaults.prototype.editing = {
6646 enabled: false,
6647 pageToNew: true,
6648 position: 'right',
6649 alwaysShow: false,
6650 addRow: function(){},
6651 editRow: function(row){},
6652 deleteRow: function(row){},
6653 viewRow: function(row){},
6654 showText: '<span class="fooicon fooicon-pencil" aria-hidden="true"></span> Edit rows',
6655 hideText: 'Cancel',
6656 addText: 'New row',
6657 editText: '<span class="fooicon fooicon-pencil" aria-hidden="true"></span>',
6658 deleteText: '<span class="fooicon fooicon-trash" aria-hidden="true"></span>',
6659 viewText: '<span class="fooicon fooicon-stats" aria-hidden="true"></span>',
6660 allowAdd: true,
6661 allowEdit: true,
6662 allowDelete: true,
6663 allowView: false,
6664 column: {
6665 classes: 'footable-editing',
6666 name: 'editing',
6667 title: '',
6668 filterable: false,
6669 sortable: false
6670 }
6671 };
6672
6673 })(jQuery, FooTable);
6674
6675 (function($, F){
6676
6677 if (F.is.defined(F.Paging)){
6678 /**
6679 * Holds a shallow clone of the un-paged {@link FooTable.Rows#array} value before paging occurs and superfluous rows are removed. Added by the {@link FooTable.Editing} component.
6680 * @instance
6681 * @public
6682 * @type {Array<FooTable.Row>}
6683 */
6684 F.Paging.prototype.unpaged = [];
6685
6686 // override the default predraw method with one that sets the unpaged property.
6687 F.Paging.extend('predraw', function(){
6688 this.unpaged = this.ft.rows.array.slice(0); // create a shallow clone for later use
6689 this._super(); // call the original method
6690 });
6691 }
6692
6693 })(jQuery, FooTable);
6694 (function($, F){
6695
6696 /**
6697 * Adds the row to the table.
6698 * @param {boolean} [redraw=true] - Whether or not to redraw the table, defaults to true but for bulk operations this
6699 * can be set to false and then followed by a call to the {@link FooTable.Table#draw} method.
6700 * @returns {jQuery.Deferred}
6701 */
6702 F.Row.prototype.add = function(redraw){
6703 redraw = F.is.boolean(redraw) ? redraw : true;
6704 var self = this;
6705 return $.Deferred(function(d){
6706 var index = self.ft.rows.all.push(self) - 1;
6707 if (redraw){
6708 return self.ft.draw().then(function(){
6709 d.resolve(index);
6710 });
6711 } else {
6712 d.resolve(index);
6713 }
6714 });
6715 };
6716
6717 /**
6718 * Removes the row from the table.
6719 * @param {boolean} [redraw=true] - Whether or not to redraw the table, defaults to true but for bulk operations this
6720 * can be set to false and then followed by a call to the {@link FooTable.Table#draw} method.
6721 * @returns {jQuery.Deferred}
6722 */
6723 F.Row.prototype.delete = function(redraw){
6724 redraw = F.is.boolean(redraw) ? redraw : true;
6725 var self = this;
6726 return $.Deferred(function(d){
6727 var index = self.ft.rows.all.indexOf(self);
6728 if (F.is.number(index) && index >= 0 && index < self.ft.rows.all.length){
6729 self.ft.rows.all.splice(index, 1);
6730 if (redraw){
6731 return self.ft.draw().then(function(){
6732 d.resolve(self);
6733 });
6734 }
6735 }
6736 d.resolve(self);
6737 });
6738 };
6739
6740 if (F.is.defined(F.Paging)){
6741 // override the default add method with one that supports paging
6742 F.Row.extend('add', function(redraw){
6743 redraw = F.is.boolean(redraw) ? redraw : true;
6744 var self = this,
6745 added = this._super(redraw),
6746 editing = self.ft.use(F.Editing),
6747 paging;
6748 if (editing && editing.pageToNew && (paging = self.ft.use(F.Paging)) && redraw){
6749 return added.then(function(){
6750 var index = paging.unpaged.indexOf(self); // find this row in the unpaged array (this array will be sorted and filtered)
6751 var page = Math.ceil((index + 1) / paging.size); // calculate the page the new row is on
6752 if (paging.current !== page){ // goto the page if we need to
6753 return paging.goto(page);
6754 }
6755 });
6756 }
6757 return added;
6758 });
6759 }
6760
6761 if (F.is.defined(F.Sorting)){
6762 // override the default val method with one that supports sorting and paging
6763 F.Row.extend('val', function(data, redraw){
6764 redraw = F.is.boolean(redraw) ? redraw : true;
6765 var result = this._super(data);
6766 if (!F.is.hash(data)){
6767 return result;
6768 }
6769 var self = this;
6770 if (redraw){
6771 self.ft.draw().then(function(){
6772 var editing = self.ft.use(F.Editing), paging;
6773 if (F.is.defined(F.Paging) && editing && editing.pageToNew && (paging = self.ft.use(F.Paging))){
6774 var index = paging.unpaged.indexOf(self); // find this row in the unpaged array (this array will be sorted and filtered)
6775 var page = Math.ceil((index + 1) / paging.size); // calculate the page the new row is on
6776 if (paging.current !== page){ // goto the page if we need to
6777 return paging.goto(page);
6778 }
6779 }
6780 });
6781 }
6782 return result;
6783 });
6784 }
6785
6786 })(jQuery, FooTable);
6787 (function(F){
6788
6789 /**
6790 * Adds a row to the underlying {@link FooTable.Rows#all} array.
6791 * @param {(object|FooTable.Row)} dataOrRow - A hash containing the row values or an actual {@link FooTable.Row} object.
6792 * @param {boolean} [redraw=true] - Whether or not to redraw the table, defaults to true but for bulk operations this
6793 * can be set to false and then followed by a call to the {@link FooTable.Table#draw} method.
6794 */
6795 F.Rows.prototype.add = function(dataOrRow, redraw){
6796 var row = dataOrRow;
6797 if (F.is.hash(dataOrRow)){
6798 row = new FooTable.Row(this.ft, this.ft.columns.array, dataOrRow);
6799 }
6800 if (row instanceof FooTable.Row){
6801 row.add(redraw);
6802 }
6803 };
6804
6805 /**
6806 * Updates a row in the underlying {@link FooTable.Rows#all} array.
6807 * @param {(number|FooTable.Row)} indexOrRow - The index to update or the actual {@link FooTable.Row} object.
6808 * @param {object} data - A hash containing the new row values.
6809 * @param {boolean} [redraw=true] - Whether or not to redraw the table, defaults to true but for bulk operations this
6810 * can be set to false and then followed by a call to the {@link FooTable.Table#draw} method.
6811 */
6812 F.Rows.prototype.update = function(indexOrRow, data, redraw){
6813 var len = this.ft.rows.all.length,
6814 row = indexOrRow;
6815 if (F.is.number(indexOrRow) && indexOrRow >= 0 && indexOrRow < len){
6816 row = this.ft.rows.all[indexOrRow];
6817 }
6818 if (row instanceof FooTable.Row && F.is.hash(data)){
6819 row.val(data, redraw);
6820 }
6821 };
6822
6823 /**
6824 * Deletes a row from the underlying {@link FooTable.Rows#all} array.
6825 * @param {(number|FooTable.Row)} indexOrRow - The index to delete or the actual {@link FooTable.Row} object.
6826 * @param {boolean} [redraw=true] - Whether or not to redraw the table, defaults to true but for bulk operations this
6827 * can be set to false and then followed by a call to the {@link FooTable.Table#draw} method.
6828 */
6829 F.Rows.prototype.delete = function(indexOrRow, redraw){
6830 var len = this.ft.rows.all.length,
6831 row = indexOrRow;
6832 if (F.is.number(indexOrRow) && indexOrRow >= 0 && indexOrRow < len){
6833 row = this.ft.rows.all[indexOrRow];
6834 }
6835 if (row instanceof FooTable.Row){
6836 row.delete(redraw);
6837 }
6838 };
6839
6840 })(FooTable);
6841
6842 (function($, F){
6843
6844 // global int to use if the table has no ID
6845 var _uid = 0,
6846 // a hash value for the current url
6847 _url_hash = (function(str){
6848 var i, l, hval = 0x811c9dc5;
6849 for (i = 0, l = str.length; i < l; i++) {
6850 hval ^= str.charCodeAt(i);
6851 hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
6852 }
6853 return hval >>> 0;
6854 })(location.origin + location.pathname);
6855
6856 F.State = F.Component.extend(/** @lends FooTable.State */{
6857 /**
6858 * The state component adds the ability for the table to remember its basic state for filtering, paging and sorting.
6859 * @constructs
6860 * @extends FooTable.Component
6861 * @param {FooTable.Table} table - The parent {@link FooTable.Table} object for the component.
6862 * @returns {FooTable.State}
6863 */
6864 construct: function(table){
6865 // call the constructor of the base class
6866 this._super(table, table.o.state.enabled);
6867 // Change this value if an update to this component requires any stored data to be reset
6868 this._key = '1';
6869 /**
6870 * The key to use to store the state for this table.
6871 * @type {(null|string)}
6872 */
6873 this.key = this._key + (F.is.string(table.o.state.key) ? table.o.state.key : this._uid());
6874 /**
6875 * Whether or not to allow the filtering component to store it's state.
6876 * @type {boolean}
6877 */
6878 this.filtering = F.is.boolean(table.o.state.filtering) ? table.o.state.filtering : true;
6879 /**
6880 * Whether or not to allow the paging component to store it's state.
6881 * @type {boolean}
6882 */
6883 this.paging = F.is.boolean(table.o.state.paging) ? table.o.state.paging : true;
6884 /**
6885 * Whether or not to allow the sorting component to store it's state.
6886 * @type {boolean}
6887 */
6888 this.sorting = F.is.boolean(table.o.state.sorting) ? table.o.state.sorting : true;
6889 },
6890 /* PROTECTED */
6891 /**
6892 * Checks the supplied data and options for the state component.
6893 * @instance
6894 * @protected
6895 * @param {object} data - The jQuery data object from the parent table.
6896 * @fires FooTable.State#"preinit.ft.state"
6897 * @this FooTable.State
6898 */
6899 preinit: function(data){
6900 var self = this;
6901 /**
6902 * The preinit.ft.state event is raised before the UI is created and provides the tables jQuery data object for additional options parsing.
6903 * Calling preventDefault on this event will disable the component.
6904 * @event FooTable.State#"preinit.ft.state"
6905 * @param {jQuery.Event} e - The jQuery.Event object for the event.
6906 * @param {FooTable.Table} ft - The instance of the plugin raising the event.
6907 * @param {object} data - The jQuery data object of the table raising the event.
6908 */
6909 this.ft.raise('preinit.ft.state', [data]).then(function(){
6910
6911 self.enabled = F.is.boolean(data.state)
6912 ? data.state
6913 : self.enabled;
6914
6915 if (!self.enabled) return;
6916
6917 self.key = self._key + (F.is.string(data.stateKey) ? data.stateKey : self.key);
6918
6919 self.filtering = F.is.boolean(data.stateFiltering) ? data.stateFiltering : self.filtering;
6920
6921 self.paging = F.is.boolean(data.statePaging) ? data.statePaging : self.paging;
6922
6923 self.sorting = F.is.boolean(data.stateSorting) ? data.stateSorting : self.sorting;
6924
6925 }, function(){
6926 self.enabled = false;
6927 });
6928 },
6929 /**
6930 * Gets the state value for the specified key for this table.
6931 * @instance
6932 * @param {string} key - The key to get the value for.
6933 * @returns {(*|null)}
6934 */
6935 get: function(key){
6936 return JSON.parse(localStorage.getItem(this.key + ':' + key));
6937 },
6938 /**
6939 * Sets the state value for the specified key for this table.
6940 * @instance
6941 * @param {string} key - The key to set the value for.
6942 * @param {*} data - The value to store for the key. This value must be JSON.stringify friendly.
6943 */
6944 set: function(key, data){
6945 localStorage.setItem(this.key + ':' + key, JSON.stringify(data));
6946 },
6947 /**
6948 * Clears the state value for the specified key for this table.
6949 * @instance
6950 * @param {string} key - The key to clear the value for.
6951 */
6952 remove: function(key){
6953 localStorage.removeItem(this.key + ':' + key);
6954 },
6955 /**
6956 * Executes the {@link FooTable.Component#readState} function on all components.
6957 * @instance
6958 */
6959 read: function(){
6960 this.ft.execute(false, true, 'readState');
6961 },
6962 /**
6963 * Executes the {@link FooTable.Component#writeState} function on all components.
6964 * @instance
6965 */
6966 write: function(){
6967 this.ft.execute(false, true, 'writeState');
6968 },
6969 /**
6970 * Executes the {@link FooTable.Component#clearState} function on all components.
6971 * @instance
6972 */
6973 clear: function(){
6974 this.ft.execute(false, true, 'clearState');
6975 },
6976 /**
6977 * Generates a unique identifier for the current {@link FooTable.Table} if one is not supplied through the options.
6978 * This value is a combination of the url hash and either the element ID or an incremented global int value.
6979 * @instance
6980 * @returns {*}
6981 * @private
6982 */
6983 _uid: function(){
6984 var id = this.ft.$el.attr('id');
6985 return _url_hash + '_' + (F.is.string(id) ? id : ++_uid);
6986 }
6987 });
6988
6989 F.components.register('state', F.State, 700);
6990
6991 })(jQuery, FooTable);
6992 (function(F){
6993
6994 /**
6995 * This method is called from the {@link FooTable.State#read} method and allows a component to retrieve its' stored state.
6996 * @instance
6997 * @protected
6998 * @function
6999 */
7000 F.Component.prototype.readState = function(){};
7001
7002 /**
7003 * This method is called from the {@link FooTable.State#write} method and allows a component to write its' current state to the store.
7004 * @instance
7005 * @protected
7006 * @function
7007 */
7008 F.Component.prototype.writeState = function(){};
7009
7010 /**
7011 * This method is called from the {@link FooTable.State#clear} method and allows a component to clear any stored state.
7012 * @instance
7013 * @protected
7014 * @function
7015 */
7016 F.Component.prototype.clearState = function(){};
7017
7018 })(FooTable);
7019 (function(F){
7020
7021 /**
7022 * An object containing the state options for the plugin. Added by the {@link FooTable.State} component.
7023 * @type {object}
7024 * @prop {boolean} enabled=false - Whether or not to allow state to be stored for the table. This overrides the individual component enable options.
7025 * @prop {boolean} filtering=true - Whether or not to allow the filtering state to be stored.
7026 * @prop {boolean} paging=true - Whether or not to allow the filtering state to be stored.
7027 * @prop {boolean} sorting=true - Whether or not to allow the filtering state to be stored.
7028 * @prop {string} key=null - The unique key to use to store the table's data.
7029 */
7030 F.Defaults.prototype.state = {
7031 enabled: false,
7032 filtering: true,
7033 paging: true,
7034 sorting: true,
7035 key: null
7036 };
7037
7038 })(FooTable);
7039 (function(F){
7040
7041 if (!F.Filtering) return;
7042
7043 /**
7044 * Allows the filtering component to retrieve its' stored state.
7045 */
7046 F.Filtering.prototype.readState = function(){
7047 if (this.ft.state.filtering){
7048 var state = this.ft.state.get('filtering');
7049 if (F.is.hash(state) && !F.is.emptyArray(state.filters)){
7050 this.filters = this.ensure(state.filters);
7051 }
7052 }
7053 };
7054
7055 /**
7056 * Allows the filtering component to write its' current state to the store.
7057 */
7058 F.Filtering.prototype.writeState = function(){
7059 if (this.ft.state.filtering) {
7060 var filters = F.arr.map(this.filters, function (f) {
7061 return {
7062 name: f.name,
7063 query: f.query instanceof F.Query ? f.query.val() : f.query,
7064 columns: F.arr.map(f.columns, function (c) {
7065 return c.name;
7066 }),
7067 hidden: f.hidden,
7068 space: f.space,
7069 connectors: f.connectors,
7070 ignoreCase: f.ignoreCase
7071 };
7072 });
7073 this.ft.state.set('filtering', {filters: filters});
7074 }
7075 };
7076
7077 /**
7078 * Allows the filtering component to clear any stored state.
7079 */
7080 F.Filtering.prototype.clearState = function(){
7081 if (this.ft.state.filtering) {
7082 this.ft.state.remove('filtering');
7083 }
7084 };
7085
7086 })(FooTable);
7087 (function(F){
7088
7089 if (!F.Paging) return;
7090
7091 /**
7092 * Allows the paging component to retrieve its' stored state.
7093 */
7094 F.Paging.prototype.readState = function(){
7095 if (this.ft.state.paging) {
7096 var state = this.ft.state.get('paging');
7097 if (F.is.hash(state)) {
7098 this.current = state.current;
7099 this.size = state.size;
7100 }
7101 }
7102 };
7103
7104 /**
7105 * Allows the paging component to write its' current state to the store.
7106 */
7107 F.Paging.prototype.writeState = function(){
7108 if (this.ft.state.paging) {
7109 this.ft.state.set('paging', {
7110 current: this.current,
7111 size: this.size
7112 });
7113 }
7114 };
7115
7116 /**
7117 * Allows the paging component to clear any stored state.
7118 */
7119 F.Paging.prototype.clearState = function(){
7120 if (this.ft.state.paging) {
7121 this.ft.state.remove('paging');
7122 }
7123 };
7124
7125 })(FooTable);
7126 (function(F){
7127
7128 if (!F.Sorting) return;
7129
7130 /**
7131 * Allows the sorting component to retrieve its' stored state.
7132 */
7133 F.Sorting.prototype.readState = function(){
7134 if (this.ft.state.sorting) {
7135 var state = this.ft.state.get('sorting');
7136 if (F.is.hash(state)) {
7137 var column = this.ft.columns.get(state.column);
7138 if (column instanceof F.Column) {
7139 this.column = column;
7140 this.column.direction = state.direction;
7141 }
7142 }
7143 }
7144 };
7145
7146 /**
7147 * Allows the sorting component to write its' current state to the store.
7148 */
7149 F.Sorting.prototype.writeState = function(){
7150 if (this.ft.state.sorting && this.column instanceof F.Column){
7151 this.ft.state.set('sorting', {
7152 column: this.column.name,
7153 direction: this.column.direction
7154 });
7155 }
7156 };
7157
7158 /**
7159 * Allows the sorting component to clear any stored state.
7160 */
7161 F.Sorting.prototype.clearState = function(){
7162 if (this.ft.state.sorting) {
7163 this.ft.state.remove('sorting');
7164 }
7165 };
7166
7167 })(FooTable);
7168 (function(F){
7169
7170 // hook into the _construct method so we can add the state property to the table.
7171 F.Table.extend('_construct', function(ready){
7172 this.state = this.use(FooTable.State);
7173 return this._super(ready);
7174 });
7175
7176 // hook into the _preinit method so we can trigger a plugin wide read state operation.
7177 F.Table.extend('_preinit', function(){
7178 var self = this;
7179 return self._super().then(function(){
7180 if (self.state.enabled){
7181 self.state.read();
7182 }
7183 });
7184 });
7185
7186 // hook into the draw method so we can trigger a plugin wide write state operation.
7187 F.Table.extend('draw', function(){
7188 var self = this;
7189 return self._super().then(function(){
7190 if (self.state.enabled){
7191 self.state.write();
7192 }
7193 });
7194 });
7195
7196 })(FooTable);
7197 (function($, F){
7198
7199 F.Export = F.Component.extend(/** @lends FooTable.Export */{
7200 /**
7201 * @summary This component provides some basic export functionality.
7202 * @memberof FooTable
7203 * @constructs Export
7204 * @param {FooTable.Table} table - The current instance of the plugin.
7205 */
7206 construct: function(table){
7207 // call the constructor of the base class
7208 this._super(table, true);
7209 /**
7210 * @summary A snapshot of the working set of rows prior to being trimmed by the paging component.
7211 * @memberof FooTable.Export#
7212 * @name snapshot
7213 * @type {FooTable.Row[]}
7214 */
7215 this.snapshot = [];
7216 },
7217 /**
7218 * @summary Hooks into the predraw pipeline after sorting and filtering have taken place but prior to paging.
7219 * @memberof FooTable.Export#
7220 * @function predraw
7221 * @description This method allows us to take a snapshot of the working set of rows before they are trimmed by the paging component and is called by the plugin instance.
7222 */
7223 predraw: function(){
7224 this.snapshot = this.ft.rows.array.slice(0);
7225 },
7226 /**
7227 * @summary Return the columns as simple JavaScript objects in an array.
7228 * @memberof FooTable.Export#
7229 * @function columns
7230 * @returns {Object[]}
7231 */
7232 columns: function(){
7233 var result = [];
7234 F.arr.each(this.ft.columns.array, function(column){
7235 if (!column.internal){
7236 result.push({
7237 type: column.type,
7238 name: column.name,
7239 title: column.title,
7240 visible: column.visible,
7241 hidden: column.hidden,
7242 classes: column.classes,
7243 style: column.style
7244 });
7245 }
7246 });
7247 return result;
7248 },
7249 /**
7250 * @summary Return the rows as simple JavaScript objects in an array.
7251 * @memberof FooTable.Export#
7252 * @function rows
7253 * @param {boolean} [filtered=false] - Whether or not to exclude filtered rows from the result.
7254 * @returns {Object[]}
7255 */
7256 rows: function(filtered){
7257 filtered = F.is.boolean(filtered) ? filtered : false;
7258 var rows = filtered ? this.ft.rows.all : this.snapshot, result = [];
7259 F.arr.each(rows, function(row){
7260 result.push(row.val());
7261 });
7262 return result;
7263 },
7264 /**
7265 * @summary Return the columns and rows as a properly formatted JSON object.
7266 * @memberof FooTable.Export#
7267 * @function json
7268 * @param {boolean} [filtered=false] - Whether or not to exclude filtered rows from the result.
7269 * @returns {Object}
7270 */
7271 json: function(filtered){
7272 return JSON.parse(JSON.stringify({columns: this.columns(),rows: this.rows(filtered)}));
7273 },
7274 /**
7275 * @summary Return the columns and rows as a properly formatted CSV value.
7276 * @memberof FooTable.Export#
7277 * @function csv
7278 * @param {boolean} [filtered=false] - Whether or not to exclude filtered rows from the result.
7279 * @returns {string}
7280 */
7281 csv: function(filtered){
7282 var csv = "", columns = this.columns(), value, escaped;
7283 F.arr.each(columns, function(column, i){
7284 escaped = '"' + column.title.replace(/"/g, '""') + '"';
7285 csv += (i === 0 ? escaped : "," + escaped);
7286 });
7287 csv += "\n";
7288
7289 var rows = filtered ? this.ft.rows.all : this.snapshot;
7290 F.arr.each(rows, function(row){
7291 F.arr.each(row.cells, function(cell, i){
7292 if (!cell.column.internal){
7293 value = cell.column.stringify.call(cell.column, cell.value, cell.ft.o, cell.row.value);
7294 escaped = '"' + value.replace(/"/g, '""') + '"';
7295 csv += (i === 0 ? escaped : "," + escaped);
7296 }
7297 });
7298 csv += "\n";
7299 });
7300 return csv;
7301 }
7302 });
7303
7304 // register the component using a priority of 490 which falls just after filtering (500) and before paging (400).
7305 F.components.register("export", F.Export, 490);
7306
7307 })(jQuery, FooTable);
7308 (function(F){
7309 // this is used to define the filtering specific properties on column creation
7310 F.Column.prototype.__export_define__ = function(definition){
7311 this.stringify = F.checkFnValue(this, definition.stringify, this.stringify);
7312 };
7313
7314 // overrides the public define method and replaces it with our own
7315 F.Column.extend('define', function(definition){
7316 this._super(definition); // call the base so we don't have to redefine any previously set properties
7317 this.__export_define__(definition); // then call our own
7318 });
7319
7320 /**
7321 * @summary Return the supplied value as a string.
7322 * @memberof FooTable.Column#
7323 * @function stringify
7324 * @returns {string}
7325 */
7326 F.Column.prototype.stringify = function(value, options, rowData){
7327 return value + "";
7328 };
7329
7330 if (F.is.defined(F.DateColumn)){
7331 // override the base method for DateColumns
7332 F.DateColumn.prototype.stringify = function(value, options, rowData){
7333 return F.is.object(value) && F.is.boolean(value._isAMomentObject) && value.isValid() ? value.format(this.formatString) : '';
7334 };
7335 }
7336
7337 // override the base method for ObjectColumns
7338 F.ObjectColumn.prototype.stringify = function(value, options, rowData){
7339 return F.is.object(value) ? JSON.stringify(value) : "";
7340 };
7341
7342 // override the base method for ArrayColumns
7343 F.ArrayColumn.prototype.stringify = function(value, options, rowData){
7344 return F.is.array(value) ? JSON.stringify(value) : "";
7345 };
7346
7347 })(FooTable);
7348 (function(F){
7349 /**
7350 * @summary Return the columns and rows as a properly formatted JSON object.
7351 * @memberof FooTable.Table#
7352 * @function toJSON
7353 * @param {boolean} [filtered=false] - Whether or not to exclude filtered rows from the result.
7354 * @returns {Object}
7355 */
7356 F.Table.prototype.toJSON = function(filtered){
7357 return this.use(F.Export).json(filtered);
7358 };
7359
7360 /**
7361 * @summary Return the columns and rows as a properly formatted CSV value.
7362 * @memberof FooTable.Table#
7363 * @function toCSV
7364 * @param {boolean} [filtered=false] - Whether or not to exclude filtered rows from the result.
7365 * @returns {string}
7366 */
7367 F.Table.prototype.toCSV = function(filtered){
7368 return this.use(F.Export).csv(filtered);
7369 };
7370
7371 })(FooTable);