dataTables.responsive.js 28.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
/*! Responsive 1.0.1
 * 2014 SpryMedia Ltd - datatables.net/license
 */

/**
 * @summary     Responsive
 * @description Responsive tables plug-in for DataTables
 * @version     1.0.1
 * @file        dataTables.responsive.js
 * @author      SpryMedia Ltd (www.sprymedia.co.uk)
 * @contact     www.sprymedia.co.uk/contact
 * @copyright   Copyright 2014 SpryMedia Ltd.
 *
 * This source file is free software, available under the following license:
 *   MIT license - http://datatables.net/license/mit
 *
 * This source file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
 *
 * For details please refer to: http://www.datatables.net
 */

(function(window, document, undefined) {


    var factory = function($, DataTable) {
        "use strict";

        /**
         * Responsive is a plug-in for the DataTables library that makes use of
         * DataTables' ability to change the visibility of columns, changing the
         * visibility of columns so the displayed columns fit into the table container.
         * The end result is that complex tables will be dynamically adjusted to fit
         * into the viewport, be it on a desktop, tablet or mobile browser.
         *
         * Responsive for DataTables has two modes of operation, which can used
         * individually or combined:
         *
         * * Class name based control - columns assigned class names that match the
         *   breakpoint logic can be shown / hidden as required for each breakpoint.
         * * Automatic control - columns are automatically hidden when there is no
         *   room left to display them. Columns removed from the right.
         *
         * In additional to column visibility control, Responsive also has built into
         * options to use DataTables' child row display to show / hide the information
         * from the table that has been hidden. There are also two modes of operation
         * for this child row display:
         *
         * * Inline - when the control element that the user can use to show / hide
         *   child rows is displayed inside the first column of the table.
         * * Column - where a whole column is dedicated to be the show / hide control.
         *
         * Initialisation of Responsive is performed by:
         *
         * * Adding the class `responsive` or `dt-responsive` to the table. In this case
         *   Responsive will automatically be initialised with the default configuration
         *   options when the DataTable is created.
         * * Using the `responsive` option in the DataTables configuration options. This
         *   can also be used to specify the configuration options, or simply set to
         *   `true` to use the defaults.
         *
         *  @class
         *  @param {object} settings DataTables settings object for the host table
         *  @param {object} [opts] Configuration options
         *  @requires jQuery 1.7+
         *  @requires DataTables 1.10.1+
         *
         *  @example
         *      $('#example').DataTable( {
         *        responsive: true
         *      } );
         *    } );
         */
        var Responsive = function(settings, opts) {
            // Sanity check that we are using DataTables 1.10 or newer
            if (!DataTable.versionCheck || !DataTable.versionCheck('1.10.1')) {
                throw 'DataTables Responsive requires DataTables 1.10.1 or newer';
            } else if (settings.responsive) {
                return;
            }

            this.s = {
                dt: new DataTable.Api(settings),
                columns: []
            };

            // details is an object, but for simplicity the user can give it as a string
            if (opts && typeof opts.details === 'string') {
                opts.details = {
                    type: opts.details
                };
            }

            this.c = $.extend(true, {}, Responsive.defaults, opts);
            settings.responsive = this;
            this._constructor();
        };

        Responsive.prototype = {
            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
             * Constructor
             */

            /**
             * Initialise the Responsive instance
             *
             * @private
             */
            _constructor: function() {
                var that = this;
                var dt = this.s.dt;

                dt.settings()[0]._responsive = this;

                // Use DataTables' private throttle function to avoid processor thrashing
                $(window).on('resize.dtr orientationchange.dtr', dt.settings()[0].oApi._fnThrottle(function() {
                    that._resize();
                }));

                // Destroy event handler
                dt.on('destroy.dtr', function() {
                    $(window).off('resize.dtr orientationchange.dtr');
                });

                // Reorder the breakpoints array here in case they have been added out
                // of order
                this.c.breakpoints.sort(function(a, b) {
                    return a.width < b.width ? 1 :
                        a.width > b.width ? -1 : 0;
                });

                this._classLogic();
                this._resizeAuto();

                // First pass - draw the table for the current viewport size
                this._resize();

                // Details handler
                var details = this.c.details;
                if (details.type) {
                    that._detailsInit();
                    this._detailsVis();

                    dt.on('column-visibility.dtr', function() {
                        that._detailsVis();
                    });

                    $(dt.table().node()).addClass('dtr-' + details.type);
                }
            },


            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
             * Private methods
             */

            /**
             * Calculate the visibility for the columns in a table for a given
             * breakpoint. The result is pre-determined based on the class logic if
             * class names are used to control all columns, but the width of the table
             * is also used if there are columns which are to be automatically shown
             * and hidden.
             *
             * @param  {string} breakpoint Breakpoint name to use for the calculation
             * @return {array} Array of boolean values initiating the visibility of each
             *   column.
             *  @private
             */
            _columnsVisiblity: function(breakpoint) {
                var dt = this.s.dt;
                var columns = this.s.columns;
                var i, ien;

                // Class logic - determine which columns are in this breakpoint based
                // on the classes. If no class control (i.e. `auto`) then `-` is used
                // to indicate this to the rest of the function
                var display = $.map(columns, function(col) {
                    return col.auto && col.minWidth === null ?
                        false :
                        col.auto === true ?
                        '-' :
                        col.includeIn.indexOf(breakpoint) !== -1;
                });

                // Auto column control - first pass: how much width is taken by the
                // ones that must be included from the non-auto columns
                var requiredWidth = 0;
                for (i = 0, ien = display.length; i < ien; i++) {
                    if (display[i] === true) {
                        requiredWidth += columns[i].minWidth;
                    }
                }

                // Second pass, use up any remaining width for other columns
                var widthAvailable = dt.table().container().offsetWidth;
                var usedWidth = widthAvailable - requiredWidth;

                for (i = 0, ien = display.length; i < ien; i++) {
                    // Control column needs to always be included. This makes it sub-
                    // optimal in terms of using the available with, but to stop layout
                    // thrashing or overflow
                    if (columns[i].control) {
                        usedWidth -= columns[i].minWidth;
                    } else if (display[i] === '-') {
                        // Otherwise, remove the width
                        display[i] = usedWidth - columns[i].minWidth < 0 ?
                            false :
                            true;

                        // Continue counting down the width, so a smaller column to the
                        // left won't be shown
                        usedWidth -= columns[i].minWidth;
                    }
                }

                // Determine if the 'control' column should be shown (if there is one).
                // This is the case when there is a hidden column (that is not the
                // control column). The two loops look inefficient here, but they are
                // trivial and will fly through. We need to know the outcome from the
                // first , before the action in the second can be taken
                var showControl = false;

                for (i = 0, ien = columns.length; i < ien; i++) {
                    if (!columns[i].control && !display[i]) {
                        showControl = true;
                        break;
                    }
                }

                for (i = 0, ien = columns.length; i < ien; i++) {
                    if (columns[i].control) {
                        display[i] = showControl;
                    }
                }

                return display;
            },


            /**
             * Create the internal `columns` array with information about the columns
             * for the table. This includes determining which breakpoints the column
             * will appear in, based upon class names in the column, which makes up the
             * vast majority of this method.
             *
             * @private
             */
            _classLogic: function() {
                var that = this;
                var calc = {};
                var breakpoints = this.c.breakpoints;
                var columns = this.s.dt.columns().eq(0).map(function(i) {
                    return {
                        className: this.column(i).header().className,
                        includeIn: [],
                        auto: false,
                        control: false
                    };
                });

                // Simply add a breakpoint to `includeIn` array, ensuring that there are
                // no duplicates
                var add = function(colIdx, name) {
                    var includeIn = columns[colIdx].includeIn;

                    if (includeIn.indexOf(name) === -1) {
                        includeIn.push(name);
                    }
                };

                var column = function(colIdx, name, operator, matched) {
                    var size, i, ien;

                    if (!operator) {
                        columns[colIdx].includeIn.push(name);
                    } else if (operator === 'max-') {
                        // Add this breakpoint and all smaller
                        size = that._find(name).width;

                        for (i = 0, ien = breakpoints.length; i < ien; i++) {
                            if (breakpoints[i].width <= size) {
                                add(colIdx, breakpoints[i].name);
                            }
                        }
                    } else if (operator === 'min-') {
                        // Add this breakpoint and all larger
                        size = that._find(name).width;

                        for (i = 0, ien = breakpoints.length; i < ien; i++) {
                            if (breakpoints[i].width >= size) {
                                add(colIdx, breakpoints[i].name);
                            }
                        }
                    } else if (operator === 'not-') {
                        // Add all but this breakpoint (xxx need extra information)

                        for (i = 0, ien = breakpoints.length; i < ien; i++) {
                            if (breakpoints[i].name.indexOf(matched) === -1) {
                                add(colIdx, breakpoints[i].name);
                            }
                        }
                    }
                };

                // Loop over each column and determine if it has a responsive control
                // class
                columns.each(function(col, i) {
                    var classNames = col.className.split(' ');
                    var hasClass = false;

                    // Split the class name up so multiple rules can be applied if needed
                    for (var k = 0, ken = classNames.length; k < ken; k++) {
                        var className = $.trim(classNames[k]);

                        if (className === 'all') {
                            // Include in all
                            hasClass = true;
                            col.includeIn = $.map(breakpoints, function(a) {
                                return a.name;
                            });
                            return;
                        } else if (className === 'none') {
                            // Include in none (default) and no auto
                            hasClass = true;
                            return;
                        } else if (className === 'control') {
                            // Special column that is only visible, when one of the other
                            // columns is hidden. This is used for the details control
                            hasClass = true;
                            col.control = true;
                            return;
                        }

                        $.each(breakpoints, function(j, breakpoint) {
                            // Does this column have a class that matches this breakpoint?
                            var brokenPoint = breakpoint.name.split('-');
                            var re = new RegExp('(min\\-|max\\-|not\\-)?(' + brokenPoint[0] + ')(\\-[_a-zA-Z0-9])?');
                            var match = className.match(re);

                            if (match) {
                                hasClass = true;

                                if (match[2] === brokenPoint[0] && match[3] === '-' + brokenPoint[1]) {
                                    // Class name matches breakpoint name fully
                                    column(i, breakpoint.name, match[1], match[2] + match[3]);
                                } else if (match[2] === brokenPoint[0] && !match[3]) {
                                    // Class name matched primary breakpoint name with no qualifier
                                    column(i, breakpoint.name, match[1], match[2]);
                                }
                            }
                        });
                    }

                    // If there was no control class, then automatic sizing is used
                    if (!hasClass) {
                        col.auto = true;
                    }
                });

                this.s.columns = columns;
            },


            /**
             * Initialisation for the details handler
             *
             * @private
             */
            _detailsInit: function() {
                var that = this;
                var dt = this.s.dt;
                var details = this.c.details;

                // The inline type always uses the first child as the target
                if (details.type === 'inline') {
                    details.target = 'td:first-child';
                }

                // type.target can be a string jQuery selector or a column index
                var target = details.target;
                var selector = typeof target === 'string' ? target : 'td';

                // Click handler to show / hide the details rows when they are available
                $(dt.table().body()).on('click', selector, function(e) {
                    // If the table is not collapsed (i.e. there is no hidden columns)
                    // then take no action
                    if (!$(dt.table().node()).hasClass('collapsed')) {
                        return;
                    }

                    // For column index, we determine if we should act or not in the
                    // handler - otherwise it is already okay
                    if (typeof target === 'number') {
                        var targetIdx = target < 0 ?
                            dt.columns().eq(0).length + target :
                            target;

                        if (dt.cell(this).index().column !== targetIdx) {
                            return;
                        }
                    }

                    // $().closest() includes itself in its check
                    var row = dt.row($(this).closest('tr'));

                    if (row.child.isShown()) {
                        row.child(false);
                        $(row.node()).removeClass('parent');
                    } else {
                        var info = that.c.details.renderer(dt, row[0]);
                        row.child(info, 'child').show();
                        $(row.node()).addClass('parent');
                    }
                });
            },


            /**
             * Update the child rows in the table whenever the column visibility changes
             *
             * @private
             */
            _detailsVis: function() {
                var that = this;
                var dt = this.s.dt;

                var hiddenColumns = dt.columns(':hidden').indexes().flatten();
                var haveHidden = true;

                if (hiddenColumns.length === 0 || (hiddenColumns.length === 1 && this.s.columns[hiddenColumns[0]].control)) {
                    haveHidden = false;
                }

                if (haveHidden) {
                    // Got hidden columns
                    $(dt.table().node()).addClass('collapsed');

                    // Show all existing child rows
                    dt.rows().eq(0).each(function(idx) {
                        var row = dt.row(idx);

                        if (row.child()) {
                            var info = that.c.details.renderer(dt, row[0]);

                            // The renderer can return false to have no child row
                            if (info === false) {
                                row.child.hide();
                            } else {
                                row.child(info, 'child').show();
                            }
                        }
                    });
                } else {
                    // No hidden columns
                    $(dt.table().node()).removeClass('collapsed');

                    // Hide all existing child rows
                    dt.rows().eq(0).each(function(idx) {
                        dt.row(idx).child.hide();
                    });
                }
            },


            /**
             * Find a breakpoint object from a name
             * @param  {string} name Breakpoint name to find
             * @return {object}      Breakpoint description object
             */
            _find: function(name) {
                var breakpoints = this.c.breakpoints;

                for (var i = 0, ien = breakpoints.length; i < ien; i++) {
                    if (breakpoints[i].name === name) {
                        return breakpoints[i];
                    }
                }
            },


            /**
             * Alter the table display for a resized viewport. This involves first
             * determining what breakpoint the window currently is in, getting the
             * column visibilities to apply and then setting them.
             *
             * @private
             */
            _resize: function() {
                var dt = this.s.dt;
                var width = $(window).width();
                var breakpoints = this.c.breakpoints;
                var breakpoint = breakpoints[0].name;

                // Determine what breakpoint we are currently at
                for (var i = breakpoints.length - 1; i >= 0; i--) {
                    if (width <= breakpoints[i].width) {
                        breakpoint = breakpoints[i].name;
                        break;
                    }
                }

                // Show the columns for that break point
                var columns = this._columnsVisiblity(breakpoint);

                dt.columns().eq(0).each(function(colIdx, i) {
                    dt.column(colIdx).visible(columns[i]);
                });
            },


            /**
             * Determine the width of each column in the table so the auto column hiding
             * has that information to work with. This method is never going to be 100%
             * perfect since column widths can change slightly per page, but without
             * seriously compromising performance this is quite effective.
             *
             * @private
             */
            _resizeAuto: function() {
                var dt = this.s.dt;
                var columns = this.s.columns;

                // Are we allowed to do auto sizing?
                if (!this.c.auto) {
                    return;
                }

                // Are there any columns that actually need auto-sizing, or do they all
                // have classes defined
                if ($.inArray(true, $.map(columns, function(c) {
                        return c.auto;
                    })) === -1) {
                    return;
                }

                // Clone the table with the current data in it
                var tableWidth = dt.table().node().offsetWidth;
                var columnWidths = dt.columns;
                var clonedTable = dt.table().node().cloneNode(false);
                var clonedHeader = $(dt.table().header().cloneNode(false)).appendTo(clonedTable);
                var clonedBody = $(dt.table().body().cloneNode(false)).appendTo(clonedTable);

                // This is a bit slow, but we need to get a clone of each row that
                // includes all columns. As such, try to do this as little as possible.
                dt.rows({
                    page: 'current'
                }).indexes().each(function(idx) {
                    var clone = dt.row(idx).node().cloneNode(true);

                    if (dt.columns(':hidden').flatten().length) {
                        $(clone).append(dt.cells(idx, ':hidden').nodes().to$().clone());
                    }

                    $(clone).appendTo(clonedBody);
                });

                var cells = dt.columns().header().to$().clone(false).wrapAll('tr').appendTo(clonedHeader);
                var inserted = $('<div/>')
                    .css({
                        width: 1,
                        height: 1,
                        overflow: 'hidden'
                    })
                    .append(clonedTable)
                    .insertBefore(dt.table().node());

                // The cloned header now contains the smallest that each column can be
                dt.columns().eq(0).each(function(idx) {
                    columns[idx].minWidth = cells[idx].offsetWidth || 0;
                });

                inserted.remove();
            }
        };


        /**
         * List of default breakpoints. Each item in the array is an object with two
         * properties:
         *
         * * `name` - the breakpoint name.
         * * `width` - the breakpoint width
         *
         * @name Responsive.breakpoints
         * @static
         */
        Responsive.breakpoints = [{
            name: 'desktop',
            width: Infinity
        }, {
            name: 'tablet-l',
            width: 1024
        }, {
            name: 'tablet-p',
            width: 768
        }, {
            name: 'mobile-l',
            width: 480
        }, {
            name: 'mobile-p',
            width: 320
        }];


        /**
         * Responsive default settings for initialisation
         *
         * @namespace
         * @name Responsive.defaults
         * @static
         */
        Responsive.defaults = {
            /**
             * List of breakpoints for the instance. Note that this means that each
             * instance can have its own breakpoints. Additionally, the breakpoints
             * cannot be changed once an instance has been creased.
             *
             * @type {Array}
             * @default Takes the value of `Responsive.breakpoints`
             */
            breakpoints: Responsive.breakpoints,

            /**
             * Enable / disable auto hiding calculations. It can help to increase
             * performance slightly if you disable this option, but all columns would
             * need to have breakpoint classes assigned to them
             *
             * @type {Boolean}
             * @default  `true`
             */
            auto: true,

            /**
             * Details control. If given as a string value, the `type` property of the
             * default object is set to that value, and the defaults used for the rest
             * of the object - this is for ease of implementation.
             *
             * The object consists of the following properties:
             *
             * * `renderer` - function that is called for display of the child row data.
             *   The default function will show the data from the hidden columns
             * * `target` - Used as the selector for what objects to attach the child
             *   open / close to
             * * `type` - `false` to disable the details display, `inline` or `column`
             *   for the two control types
             *
             * @type {Object|string}
             */
            details: {
                renderer: function(api, rowIdx) {
                    var data = api.cells(rowIdx, ':hidden').eq(0).map(function(cell) {
                        var header = $(api.column(cell.column).header());

                        if (header.hasClass('control')) {
                            return '';
                        }

                        return '<li>' +
                            '<span class="dtr-title">' +
                            header.text() + ':' +
                            '</span> ' +
                            '<span class="dtr-data">' +
                            api.cell(cell).data() +
                            '</span>' +
                            '</li>';
                    }).toArray().join('');

                    return data ?
                        $('<ul/>').append(data) :
                        false;
                },

                target: 0,

                type: 'inline'
            }
        };


        /*
         * API
         */
        var Api = $.fn.dataTable.Api;

        // Doesn't do anything - work around for a bug in DT... Not documented
        Api.register('responsive()', function() {
            return this;
        });

        Api.register('responsive.recalc()', function(rowIdx, intParse, virtual) {
            this.iterator('table', function(ctx) {
                if (ctx._responsive) {
                    ctx._responsive._resizeAuto();
                    ctx._responsive._resize();
                }
            });
        });


        /**
         * Version information
         *
         * @name Responsive.version
         * @static
         */
        Responsive.version = '1.0.1';


        $.fn.dataTable.Responsive = Responsive;
        $.fn.DataTable.Responsive = Responsive;

        // Attach a listener to the document which listens for DataTables initialisation
        // events so we can automatically initialise
        $(document).on('init.dt.dtr', function(e, settings, json) {
            if ($(settings.nTable).hasClass('responsive') ||
                $(settings.nTable).hasClass('dt-responsive') ||
                settings.oInit.responsive
            ) {
                var init = settings.oInit.responsive;

                if (init !== false) {
                    new Responsive(settings, $.isPlainObject(init) ? init : {});
                }
            }
        });

        return Responsive;
    }; // /factory


    // Define as an AMD module if possible
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'datatables'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS
        factory(require('jquery'), require('datatables'));
    } else if (jQuery && !jQuery.fn.dataTable.Responsive) {
        // Otherwise simply initialise as normal, stopping multiple evaluation
        factory(jQuery, jQuery.fn.dataTable);
    }


})(window, document);