All files / web/bundles/pimdatagrid/js/datagrid grid.js

91.53% Statements 108/118
71.43% Branches 30/42
91.18% Functions 31/34
91.53% Lines 108/118

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    1123x                                                                                         1123x                                                                                                                                     1245x     1245x     1245x   1245x         1245x   1245x   1245x   1245x   1052x     1245x 1245x   1245x   1245x     1245x 1245x 1245x   1245x                 1245x 1245x 1067x                       1245x                         1245x 1245x                     1245x                 279x 279x                                   1245x                 1245x 1128x 1128x 1128x 1128x 1099x 1099x       1245x   1245x 557x                   1245x 64x 64x                     64x 22x       22x 22x 22x                 1245x   1245x 130x     1245x       1245x 2946x 3076x     3076x           1245x                 1245x   1245x       1245x 1245x 1245x           1245x   1245x             1245x   1245x 1245x     1245x             1245x 1245x                 2326x       2326x       2326x       2326x 2326x   2326x             2326x 2326x   2326x 180x 180x     2326x 2326x             157x 157x 157x                 1128x 1128x                 1099x 1099x 1081x   1081x         1081x               1130x             1083x                 2326x 1737x 1737x 1737x   589x 589x 589x                                       287x 287x 64x     287x                 157x 157x 157x          
/*jslint nomen: true, vars: true*/
/*global define*/
define(
    [
        'jquery',
        'underscore',
        'backgrid',
        'translator-lib',
        'oro/translator',
        'oro/mediator',
        'oro/loading-mask',
        'oro/datagrid/header',
        'oro/datagrid/body',
        'oro/datagrid/action-column',
        'oro/datagrid/select-row-cell',
        'oro/datagrid/select-all-header-cell',
        'pim/template/common/no-data',
        'pim/template/common/grid'
    ],
    function (
        $,
        _,
        Backgrid,
        Translator,
        __,
        mediator,
        LoadingMask,
        GridHeader,
        GridBody,
        ActionColumn,
        SelectRowCell,
        SelectAllHeaderCell,
        noDataTemplate,
        template
    ) {
        'use strict';
 
        /**
         * Basic grid class.
         *
         * Triggers events:
         *  - "rowClicked" when row of grid body is clicked
         *
         * @export  oro/datagrid/grid
         * @class   oro.datagrid.Grid
         * @extends Backgrid.Grid
         */
        return Backgrid.Grid.extend({
            /** @property {String} */
            name: 'datagrid',
 
            /** @property {String} */
            tagName: 'div',
 
            /** @property {int} */
            requestsCount: 0,
 
            /** @property {String} */
            className: 'clearfix',
 
            /** @property */
            template: _.template(template),
 
            /** @property */
            noDataTemplate: _.template(noDataTemplate),
 
            /** @property {Object} */
            selectors: {
                grid:        '.grid',
                noDataBlock: '.no-data',
                loadingMask: '.loading-mask',
                toolbar:     '[data-drop-zone="toolbar"]'
            },
 
            /** @property {oro.datagrid.Header} */
            header: GridHeader,
 
            /** @property {oro.datagrid.Body} */
            body: GridBody,
 
            /** @property {oro.LoadingMask} */
            loadingMask: LoadingMask,
 
            /** @property {oro.datagrid.ActionColumn} */
            actionsColumn: ActionColumn,
 
            /**
             * @property {Object} Default properties values
             */
            defaults: {
                rowClickActionClass: 'row-click-action',
                rowClassName:        'AknGrid-bodyRow',
                rowClickAction:      undefined,
                multipleSorting:     true,
                rowActions:          [],
                massActionsGroups:   [],
                massActions:         [],
                emptyGridOptions: null
            },
 
            /**
             * Initialize grid
             *
             * @param {Object} options
             * @param {Backbone.Collection} options.collection
             * @param {(Backbone.Collection|Array)} options.columns
             * @param {String} [options.rowClickActionClass] CSS class for row with click action
             * @param {String} [options.rowClassName] CSS class for row
             * @param {Array<oro.datagrid.AbstractAction>} [options.rowActions] Array of row actions prototypes
             * @param {Array<oro.datagrid.AbstractAction>} [options.massActions] Array of mass actions prototypes
             * @param {oro.datagrid.AbstractAction} [options.rowClickAction] Prototype for action that handles row click
             * @throws {TypeError} If mandatory options are undefined
             */
            initialize: function (options) {
                options = options || {};
 
                // Check required options
                Iif (!options.collection) {
                    throw new TypeError("'collection' is required");
                }
                this.collection = options.collection;
 
                Iif (!options.columns) {
                    throw new TypeError("'columns' is required");
                }
 
                // Init properties values based on options and defaults
                _.extend(this, this.defaults, options);
 
                this.collection.multipleSorting = this.multipleSorting;
 
                this._initRowActions();
 
                if (this.rowClickAction) {
                    // This option property is used in oro.datagrid.Body
                    options.rowClassName = this.rowClickActionClass + ' ' + this.rowClassName;
                }
 
                options.columns.push(this._createActionsColumn());
                options.columns.unshift(this._getMassActionsColumn());
 
                this.loadingMask = this._createLoadingMask();
 
                Backgrid.Grid.prototype.initialize.apply(this, arguments);
 
                // Listen and proxy events
                this._listenToCollectionEvents();
                this._listenToBodyEvents();
                this._listenToCommands();
 
                mediator.trigger('grid_load:start', this.collection, this);
            },
 
            /**
             * Inits this.rowActions and this.rowClickAction
             *
             * @private
             */
            _initRowActions: function () {
                Eif (!this.rowClickAction) {
                    this.rowClickAction = _.find(this.rowActions, function (action) {
                        return Boolean(action.prototype.rowAction);
                    });
                }
            },
 
            /**
             * Creates actions column
             *
             * @return {Backgrid.Column}
             * @private
             */
            _createActionsColumn: function () {
                return new this.actionsColumn({
                    actions:  this.rowActions,
                    datagrid: this
                });
            },
 
            /**
             * Creates mass actions column
             *
             * @return {Backgrid.Column}
             * @private
             */
            _getMassActionsColumn: function () {
                Eif (!this.massActionsColumn) {
                    this.massActionsColumn = new Backgrid.Column({
                        name:       "massAction",
                        label:      __("Selected Rows"),
                        renderable: !_.isEmpty(this.massActions),
                        sortable:   false,
                        editable:   false,
                        cell:       SelectRowCell,
                        headerCell: SelectAllHeaderCell
                    });
                }
 
                return this.massActionsColumn;
            },
 
            /**
             * Gets selection state
             *
             * @returns {{selectedModels: *, inset: boolean}}
             */
            getSelectionState: function () {
                var selectAllHeader = this.header.row.cells[0];
                return selectAllHeader.getSelectionState();
            },
 
            /**
             * Resets selection state
             */
            resetSelectionState: function () {
                var selectAllHeader = this.header.row.cells[0];
                return selectAllHeader.selectNone();
            },
 
            /**
             * Creates loading mask
             *
             * @return {oro.LoadingMask}
             * @private
             */
            _createLoadingMask: function () {
                return new this.loadingMask();
            },
 
            /**
             * Listen to events of collection
             *
             * @private
             */
            _listenToCollectionEvents: function () {
                this.collection.on('request', function (model, xhr, options) {
                    this._beforeRequest();
                    var self = this;
                    var always = xhr.always;
                    xhr.always = function () {
                        always.apply(this, arguments);
                        self._afterRequest();
                    };
                }, this);
 
                this.collection.on('remove', this._onRemove, this);
 
                this.collection.on('change', function (model) {
                    this.$el.trigger('datagrid:change:' + this.name, model);
                }.bind(this));
            },
 
            /**
             * Listen to events of body, proxies events "rowClicked", handle run of rowClickAction if required
             *
             * @private
             */
            _listenToBodyEvents: function () {
                this.listenTo(this.body, 'rowClicked', function (row) {
                    this.trigger('rowClicked', this, row);
                    this._runRowClickAction(row);
                });
            },
 
            /**
             * Create row click action
             *
             * @param {oro.datagrid.Row} row
             * @private
             */
            _runRowClickAction: function (row) {
                if (this.rowClickAction) {
                    var action = new this.rowClickAction({
                            datagrid: this,
                            model:    row.model
                        }),
                        actionConfiguration = row.model.get('action_configuration');
                    Eif (!actionConfiguration || actionConfiguration[action.name] !== false) {
                        action.run();
                    }
                }
            },
 
            /**
             * Listen to commands on mediator
             */
            _listenToCommands: function () {
                var grid = this;
 
                mediator.on('datagrid:setParam:' + grid.name, function (param, value) {
                    grid.setAdditionalParameter(param, value);
                });
 
                mediator.on('datagrid:removeParam:' + grid.name, function (param) {
                    grid.removeAdditionalParameter(param);
                });
 
                mediator.on('datagrid:restoreState:' + grid.name, function (columnName, dataField, included, excluded) {
                    grid.collection.each(function (model) {
                        Iif (_.indexOf(included, model.get(dataField)) !== -1) {
                            model.set(columnName, true);
                        }
                        Iif (_.indexOf(excluded, model.get(dataField)) !== -1) {
                            model.set(columnName, false);
                        }
                    });
                });
 
                mediator.on('datagrid:doRefresh:' + grid.name, this.refreshCollection.bind(this));
            },
 
            /**
             * Renders the grid, no data block and loading mask
             *
             * @return {*}
             */
            render: function () {
                this.$el.empty();
 
                this.$el = this.$el.append($(this.template({
                    hasCheckbox: this.massActionsColumn.get('renderable') === true
                })));
 
                this.renderGrid();
                this.renderNoDataBlock();
                this.renderLoadingMask();
 
                /**
                 * Backbone event. Fired when the grid has been successfully rendered.
                 * @event rendered
                 */
                this.trigger("rendered");
 
                return this;
            },
 
            /**
             * Renders the grid's header, then footer, then finally the body.
             */
            renderGrid: function () {
                var $el = this.$(this.selectors.grid);
 
                $el.append(this.header.render().$el);
                Iif (this.footer) {
                    $el.append(this.footer.render().$el);
                }
                $el.append(this.body.render().$el);
            },
 
            /**
             * Renders loading mask.
             */
            renderLoadingMask: function () {
                this.$(this.selectors.loadingMask).append(this.loadingMask.render().$el);
                this.loadingMask.hide();
            },
 
            /**
             * Returns the messages to display when there is no results.
             *
             * @returns {{hint, subHint: *, imageClass: string}}
             */
            getDefaultNoDataOptions() {
                const entityHint = (this.entityHint ?
                    this.entityHint.replace(/_/, ' ') :
                    __('pim_datagrid.entity_hint')
                ).toLowerCase();
                let key = _.isEmpty(this.collection.state.filters) ?
                    'pim_datagrid.no_entities' :
                    'pim_datagrid.no_results';
 
                Iif (Translator.has('jsmessages:' + key + '.' + entityHint)) {
                    key += '.' + entityHint;
                }
 
                const hint = __(key, {entityHint: entityHint}).replace('\n', '<br />');
                const subHint = 'pim_datagrid.no_results_subtitle';
 
                return { hint, subHint, imageClass: '', __ };
            },
 
            /**
             * Render no data block.
             */
            renderNoDataBlock: function () {
                const customOptions = this.emptyGridOptions;
                let options = this.getDefaultNoDataOptions();
 
                if (null !== customOptions && undefined !== customOptions) {
                    options = customOptions;
                    options.__ = __;
                }
 
                this.$(this.selectors.noDataBlock).html($(this.noDataTemplate(options))).hide();
                this._updateNoDataBlock();
            },
 
            /**
             * Refresh datagrid collection, triggers for datagrid:doRefresh events
             */
            refreshCollection: function() {
                this.setAdditionalParameter('refresh', true);
                this.collection.fetch();
                this.removeAdditionalParameter('refresh');
            },
 
            /**
             * Triggers when collection "request" event fired
             *
             * @private
             */
            _beforeRequest: function () {
                this.requestsCount += 1;
                this.showLoading();
            },
 
            /**
             * Triggers when collection request is done
             *
             * @private
             */
            _afterRequest: function () {
                this.requestsCount -= 1;
                if (this.requestsCount === 0) {
                    this.hideLoading();
                    // render block instead of update in order to change message depending on filter state
                    this.renderNoDataBlock();
                    /**
                     * Backbone event. Fired when data for grid has been successfully rendered.
                     * @event grid_load:complete
                     */
                    mediator.trigger("grid_load:complete", this.collection, this);
                }
            },
 
            /**
             * Show loading mask and disable toolbar
             */
            showLoading: function () {
                this.loadingMask.show();
            },
 
            /**
             * Hide loading mask and enable toolbar
             */
            hideLoading: function () {
                this.loadingMask.hide();
            },
 
            /**
             * Update no data block status
             *
             * @private
             */
            _updateNoDataBlock: function () {
                if (this.collection.models.length > 0) {
                    this.$(this.selectors.grid).show();
                    $(this.selectors.toolbar).show();
                    this.$(this.selectors.noDataBlock).hide();
                } else {
                    this.$(this.selectors.grid).hide();
                    $(this.selectors.toolbar).hide();
                    this.$(this.selectors.noDataBlock).show();
                }
            },
 
            /**
             * Triggers when collection "remove" event fired
             *
             * @private
             */
            _onRemove: function () {
                this.collection.fetch();
            },
 
            /**
             * Set additional parameter to send on server
             *
             * @param {String} name
             * @param value
             */
            setAdditionalParameter: function (name, value) {
                var state = this.collection.state;
                if (!_.has(state, 'parameters')) {
                    state.parameters = {};
                }
 
                state.parameters[name] = value;
            },
 
            /**
             * Remove additional parameter
             *
             * @param {String} name
             */
            removeAdditionalParameter: function (name) {
                var state = this.collection.state;
                Eif (_.has(state, 'parameters')) {
                    delete state.parameters[name];
                }
            }
        });
    });