All files / web/bundles/pimui/js/grid view-selector.js

90.4% Statements 113/125
67.44% Branches 29/43
93.02% Functions 40/43
90.4% Lines 113/125

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                        299x                                                 299x                                               497x   497x             496x   496x 496x     496x 496x 496x 496x 496x   496x   496x     496x   496x               964x             495x 495x   495x           495x   495x               495x             495x   495x                     495x       495x 495x 5x 5x     495x                       5x 5x 5x 5x       5x 5x   5x       5x 5x   5x 5x 5x   5x 5x     5x                               9x 9x 9x 9x               500x     499x 499x   499x 499x 499x                                             495x 495x 495x   495x 495x       495x   15x       15x             480x       495x 495x   495x 495x   495x 15x 15x     495x 495x   495x     495x                       15x   15x                 487x                             495x     495x   495x                       5x       5x   5x               1065x 1065x       1065x 1063x 1063x     1065x                   8x 8x     8x                     2x               2x 2x             6x 6x                   15x           15x 15x 15x 15x                       5x                                     5x 4x   4x       4x               15x 15x 15x       10x          
'use strict';
 
/**
 * Main module for the Datagrid View Selector.
 * Mainly composed by a Select2 component with several extension points.
 *
 * Allow the user to search & select a Grid View in a list.
 *
 * @author    Adrien Pétremann <adrien.petremann@akeneo.com>
 * @copyright 2016 Akeneo SAS (http://www.akeneo.com)
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 */
define(
    [
        'jquery',
        'underscore',
        'oro/translator',
        'backbone',
        'pim/form',
        'pim/template/grid/view-selector',
        'pim/initselect2',
        'pim/datagrid/state',
        'pim/fetcher-registry',
        'pim/form-builder'
    ],
    function (
        $,
        _,
        __,
        Backbone,
        BaseForm,
        template,
        initSelect2,
        DatagridState,
        FetcherRegistry,
        FormBuilder
    ) {
        return BaseForm.extend({
            template: _.template(template),
            resultsPerPage: 20,
            queryTimer: null,
            config: {},
            currentViewType: null,
            currentView: null,
            initialView: null,
            defaultColumns: [],
            defaultUserView: null,
            gridAlias: null,
            select2Instance: null,
            viewTypeSwitcher: null,
            currentLoadingPage: null,
            currentLoadingTerm: null,
 
            events: {
                'click .view-type-item': 'switchViewType'
            },
 
            /**
             * {@inheritdoc}
             */
            initialize: function (meta) {
                this.config = meta.config;
 
                BaseForm.prototype.initialize.apply(this, arguments);
            },
 
            /**
             * {@inheritdoc}
             */
            configure: function (gridAlias) {
                this.gridAlias = gridAlias;
 
                Eif (_.has(__moduleConfig, 'forwarded-events')) {
                    this.forwardMediatorEvents(__moduleConfig['forwarded-events']);
                }
 
                this.listenTo(this.getRoot(), 'grid:view-selector:view-created', this.onViewCreated.bind(this));
                this.listenTo(this.getRoot(), 'grid:view-selector:view-saved', this.onViewSaved.bind(this));
                this.listenTo(this.getRoot(), 'grid:view-selector:view-removed', this.onViewRemoved.bind(this));
                this.listenTo(this.getRoot(), 'grid:view-selector:close-selector', this.closeSelect2.bind(this));
                this.listenTo(this.getRoot(), 'grid:product-grid:state_changed', this.onGridStateChange.bind(this));
 
                Backbone.Router.prototype.on('route', this.unbindEvents.bind(this));
 
                return FetcherRegistry.getFetcher('datagrid-view')
                    .defaultColumns(this.gridAlias)
                    .then(function (columns) {
                        this.defaultColumns = columns;
 
                        return BaseForm.prototype.configure.apply(this, arguments);
                    }.bind(this));
            },
 
            /**
             * Detach event listeners
             */
            unbindEvents: function () {
                this.off();
            },
 
            /**
             * {@inheritdoc}
             */
            render: function () {
                this.initializeSelection().then(function () {
                    this.initializeViewTypes();
 
                    this.$el.html(this.template({
                        __: __,
                        currentViewType: this.currentViewType,
                        displaySwitcher: (this.config.viewTypes.length > 1),
                        viewTypes: this.config.viewTypes
                    }));
                    this.initializeSelectWidget();
 
                    this.renderExtensions();
                }.bind(this));
            },
 
            /**
             * Initialize the view type to display at initialization.
             */
            initializeViewTypes: function () {
                this.currentViewType = 'view';
            },
 
            /**
             * Initialize the Select2 component and format elements.
             */
            initializeSelectWidget: function () {
                var $select = this.$('input[type="hidden"]');
 
                var options = {
                    dropdownCssClass: 'grid-view-selector',
                    closeOnSelect: false,
                    formatResult: this.formatResult.bind(this),
                    formatSelection: this.formatSelection.bind(this),
                    query: this.query.bind(this),
                    initSelection: function (element, callback) {
                        /**
                         * Initialize the select2 with current selected view. If no current view is selected,
                         * we select the user's one. If he doesn't have one, we create a default one for him!
                         */
                        callback(this.currentView);
                    }.bind(this)
                };
 
                this.select2Instance = initSelect2.init($select, options);
                this.select2Instance.on('select2-selecting', function (event) {
                    var view = event.object;
                    this.selectView(view);
                }.bind(this));
 
                this.select2Instance.on('select2-close', function () {
                    this.currentLoadingPage = null;
                    this.currentLoadingTerm = null;
                }.bind(this));
            },
 
            /**
             * Do the Select2 query for the selector view
             *
             * @param options
             */
            query: function (options) {
                clearTimeout(this.queryTimer);
                this.queryTimer = setTimeout(function () {
                    var page = 1;
                    Iif (options.context && options.context.page) {
                        page = options.context.page;
                    }
 
                    var searchParameters = this.getSelectSearchParameters(options.term, page);
                    var fetcher = this.config.fetchers[this.currentViewType];
 
                    Iif (this.currentLoadingPage === page && this.currentLoadingTerm === options.term) {
                        return;
                    }
 
                    this.currentLoadingPage = page;
                    this.currentLoadingTerm = options.term;
 
                    FetcherRegistry.getFetcher(fetcher).search(searchParameters).then(function (views) {
                        let choices = this.toSelect2Format(views);
                        const more = choices.length === this.getResultsPerPage();
 
                        Eif (page === 1 && !options.term) {
                            choices = this.ensureDefaultView(choices);
                        }
 
                        options.callback({
                            results: choices,
                            more: more,
                            context: {
                                page: page + 1
                            }
                        });
                    }.bind(this));
                }.bind(this), 400);
            },
 
            /**
             * Format result (datagrid view list) method of select2.
             * This way we can display views and their infos beside them.
             */
            formatResult: function (item, $container) {
                FormBuilder.build('pim-grid-view-selector-line').then(function (form) {
                    form.setParent(this);
                    form.setView(item, this.currentViewType, this.currentView.id);
                    $container.append(form.render().$el);
                }.bind(this));
            },
 
            /**
             * Format current selection method of select2.
             */
            formatSelection: function (item, $container) {
                FormBuilder.getFormMeta('pim-grid-view-selector-current')
                    .then(FormBuilder.buildForm)
                    .then(function (form) {
                        form.setParent(this);
                        form.setView(item);
 
                        return form.configure().then(function () {
                            $container.append(form.render().$el);
                            this.onGridStateChange();
                        }.bind(this));
                    }.bind(this));
            },
 
            /**
             * Method called on view type switching.
             *
             * @param {Event} event
             */
            switchViewType: function (event) {
                this.currentViewType = $(event.target).data('value');
 
                this.render();
            },
 
            /**
             * Initialize the Select2 selection based on the DatagridState.
             * Could be the User default one, or an existing view edited or whatever.
             *
             * @return {Promise}
             */
            initializeSelection: function () {
                var activeViewId = DatagridState.get(this.gridAlias, 'view');
                var isDefaultView = ('0' === activeViewId);
                var deferred = $.Deferred();
 
                this.getUserDefaultView().then(function (userDefaultView) {
                    Iif (userDefaultView && (!activeViewId || isDefaultView)) {
                        // User is on default view but has a custom default one
                        userDefaultView.text = userDefaultView.label;
                        deferred.resolve(userDefaultView);
                    } else if (activeViewId && !isDefaultView) {
                        // User is on an existing view
                        FetcherRegistry.getFetcher('datagrid-view')
                            .fetch(activeViewId, {alias: this.gridAlias, cached: false})
                            .then(this.postFetchDatagridView.bind(this))
                            .then(function (view) {
                                deferred.resolve(view);
                            })
                            .fail(function () {
                                this.selectView(userDefaultView ? userDefaultView : this.getDefaultView());
                            }.bind(this));
                    } else {
                        // Other, set the default view
                        deferred.resolve(this.getDefaultView());
                    }
                }.bind(this));
 
                deferred.then(function (initView) {
                    var datagridState = DatagridState.get(this.gridAlias, ['filters', 'columns']);
 
                    this.initialView = $.extend(true, {}, initView);
                    this.currentView = $.extend(true, {}, initView);
 
                    if (0 !== this.initialView.id && datagridState.columns !== null) {
                        this.currentView.filters = datagridState.filters;
                        this.currentView.columns = datagridState.columns.split(',');
                    }
 
                    DatagridState.set(this.gridAlias, { initialViewState: this.initialView.filters });
                    this.getRoot().trigger('grid:view-selector:initialized', this.currentView);
 
                    return initView;
                }.bind(this));
 
                return deferred;
            },
 
            /**
             * Method called right after fetching the view from the backend.
             * This is where we can handle the view before it goes to select2.
             *
             * @param {Object} view
             *
             * @return {Promise}
             */
            postFetchDatagridView: function (view) {
                view.text = view.label;
 
                return $.Deferred().resolve(view).promise();
            },
 
            /**
             * Return the default view object which contains default columns & no filter.
             *
             * @return {Object}
             */
            getDefaultView: function () {
                return {
                    id: 0,
                    text: __('pim_datagrid.view_selector.default_view'),
                    columns: this.defaultColumns,
                    type: 'view',
                    filters: ''
                };
            },
 
            /**
             * Return the default user view object.
             *
             * @return {Object}
             */
            getUserDefaultView: function () {
                return FetcherRegistry.getFetcher('datagrid-view')
                    .defaultUserView(this.gridAlias)
                    .then(function (defaultUserView) {
                        this.defaultUserView = defaultUserView.view;
 
                        return defaultUserView.view;
                    }.bind(this));
            },
 
            /**
             * Ensure given choices contain a default view if user doesn't have one.
             *
             * @param {array} choices
             *
             * @return {array}
             */
            ensureDefaultView: function (choices) {
                Iif (null !== this.defaultUserView || 'view' !== this.currentViewType) {
                    return choices;
                }
 
                choices.unshift(this.getDefaultView());
 
                return choices;
            },
 
            /**
             * Method called when the grid state changes.
             * It allows this selector to react to new filters / columns etc..
             */
            onGridStateChange: function () {
                var datagridState = DatagridState.get(this.gridAlias, ['filters', 'columns']);
                Iif (null === datagridState.columns) {
                    datagridState.columns = '';
                }
 
                if (null !== this.currentView) {
                    this.currentView.filters = datagridState.filters;
                    this.currentView.columns = datagridState.columns.split(',');
                }
 
                this.getRoot().trigger('grid:view-selector:state-changed', datagridState);
            },
 
            /**
             * Method called when a new view has been created.
             * This method fetches the newly created view thanks to its id, then selects it.
             *
             * @param {int} viewId
             */
            onViewCreated: function (viewId) {
                FetcherRegistry.getFetcher('datagrid-view').clear();
                FetcherRegistry.getFetcher('datagrid-view')
                    .fetch(viewId, {alias: this.gridAlias})
                    .then(function (view) {
                        this.selectView(view);
                    }.bind(this));
            },
 
            /**
             * Method called when a view has been saved.
             * This method fetches the saved view thanks to its id, then selects it.
             *
             * @param {int} viewId
             */
            onViewSaved: function (viewId) {
                this.onViewCreated(viewId);
            },
 
            /**
             * Method called when a view is removed.
             * We reset all filters on the grid.
             */
            onViewRemoved: function () {
                FetcherRegistry.getFetcher('datagrid-view').clear();
                this.selectView(this.getDefaultView());
            },
 
            /**
             * Close the Select2 instance of this View Selector
             */
            closeSelect2: function () {
                Eif (null !== this.select2Instance) {
                    this.select2Instance.select2('close');
                }
            },
 
            /**
             * Method called when the user selects a view through this selector.
             *
             * @param {Object} view The selected view
             */
            selectView: function (view) {
                DatagridState.set(this.gridAlias, {
                    view: view.id,
                    filters: view.filters,
                    columns: view.columns.join(',')
                });
 
                this.currentView = view;
                this.trigger('grid:view-selector:view-selected', view);
                FetcherRegistry.getFetcher('locale').clear();
                this.reloadPage();
            },
 
            /**
             * Get grid view fetcher search parameters by giving select2 search term & page
             *
             * @param {string} term
             * @param {int}    page
             *
             * @return {Object}
             */
            getSelectSearchParameters: function (term, page) {
                return $.extend(true, {}, this.config.searchParameters, {
                    search: term,
                    alias: this.gridAlias,
                    options: {
                        limit: this.getResultsPerPage(),
                        page: page
                    }
                });
            },
 
            /**
             * Take incoming data and format them to have all required parameters
             * to be used by the select2 module.
             *
             * @param {array} data
             *
             * @return {array}
             */
            toSelect2Format: function (data) {
                return _.map(data, function (view) {
                    view.text = view.label;
 
                    Iif (!_.has(view, 'id') && _.has(view, 'code')) {
                        view.id = view.code;
                    }
 
                    return view;
                });
            },
 
            /**
             * Reload the page.
             */
            reloadPage: function () {
                var url = window.location.hash;
                Backbone.history.fragment = new Date().getTime();
                Backbone.history.navigate(url, true);
            },
 
            getResultsPerPage: function () {
                return this.resultsPerPage;
            }
        });
    }
);