modal-component.js 9.8 KB
Newer Older
Ketan's avatar
Ketan committed
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
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define([
    'Magento_Ui/js/lib/view/utils/async',
    'uiCollection',
    'uiRegistry',
    'underscore',
    './modal'
], function ($, Collection, registry, _) {
    'use strict';

    return Collection.extend({
        defaults: {
            template: 'ui/modal/modal-component',
            title: '',
            subTitle: '',
            options: {
                modalClass: '',
                title: '',
                subTitle: '',
                buttons: [],
                keyEventHandlers: {}
            },
            valid: true,
            links: {
                title: 'options.title',
                subTitle: 'options.subTitle'
            },
            listens: {
                state: 'onState',
                title: 'setTitle',
                'options.subTitle': 'setSubTitle'
            },
            modalClass: 'modal-component',
            onCancel: 'closeModal'
        },

        /**
         * Initializes component.
         *
         * @returns {Object} Chainable.
         */
        initialize: function () {
            this._super();
            _.bindAll(this,
                'initModal',
                'openModal',
                'closeModal',
                'toggleModal',
                'setPrevValues',
                'validate');
            this.initializeContent();

            return this;
        },

        /**
         * Initializes modal configuration
         *
         * @returns {Object} Chainable.
         */
        initConfig: function () {
            return this._super()
                .initSelector()
                .initModalEvents();
        },

        /**
         * Configure modal selector
         *
         * @returns {Object} Chainable.
         */
        initSelector: function () {
            var modalClass = this.name.replace(/\./g, '_');

            this.contentSelector = '.' + this.modalClass;
            this.options.modalClass = this.options.modalClass + ' ' + modalClass;
            this.rootSelector = '.' + modalClass;

            return this;
        },

        /**
         * Configure modal keyboard handlers
         * and outer click
         *
         * @returns {Object} Chainable.
         */
        initModalEvents: function () {
            this.options.keyEventHandlers.escapeKey = this.options.outerClickHandler = this[this.onCancel].bind(this);

            return this;
        },

        /**
         * Initialize modal's content components
         */
        initializeContent: function () {
            $.async({
                component: this.name
            }, this.initModal);
        },

        /**
         * Init toolbar section so other components will be able to place something in it
         */
        initToolbarSection: function () {
            this.set('toolbarSection', this.modal.data('mage-modal').modal.find('header').get(0));
        },

        /**
         * Initializes observable properties.
         *
         * @returns {Object} Chainable.
         */
        initObservable: function () {
            this._super();
            this.observe(['state', 'focused']);

            return this;
        },

        /**
         * Wrap content in a modal of certain type
         *
         * @param {HTMLElement} element
         * @returns {Object} Chainable.
         */
        initModal: function (element) {
            if (!this.modal) {
                this.overrideModalButtonCallback();
                this.options.modalCloseBtnHandler = this[this.onCancel].bind(this);
                this.modal = $(element).modal(this.options);
                this.initToolbarSection();

                if (this.waitCbk) {
                    this.waitCbk();
                    this.waitCbk = null;
                }
            }

            return this;
        },

        /**
         * Open modal
         */
        openModal: function () {
            if (this.modal) {
                this.state(true);
            } else {
                this.waitCbk = this.openModal;
            }
        },

        /**
         * Close modal
         */
        closeModal: function () {
            if (this.modal) {
                this.state(false);
            } else {
                this.waitCbk = this.closeModal;
            }
        },

        /**
         * Toggle modal
         */
        toggleModal: function () {
            if (this.modal) {
                this.state(!this.state());
            } else {
                this.waitCbk = this.toggleModal;
            }
        },

        /**
         * Sets title for modal
         *
         * @param {String} title
         */
        setTitle: function (title) {
            if (this.title !== title) {
                this.title = title;
            }

            if (this.modal) {
                this.modal.modal('setTitle', title);
            }
        },

        /**
         * Sets subTitle for modal
         *
         * @param {String} subTitle
         */
        setSubTitle: function (subTitle) {
            if (this.subTitle !== subTitle) {
                this.subTitle = subTitle;
            }

            if (this.modal) {
                this.modal.modal('setSubTitle', subTitle);
            }
        },

        /**
         * Wrap content in a modal of certain type
         *
         * @param {Boolean} state
         */
        onState: function (state) {
            if (state) {
                this.modal.modal('openModal');
                this.applyData();
            } else {
                this.modal.modal('closeModal');
            }
        },

        /**
         * Validate everything validatable in modal
         */
        validate: function (elem) {
            if (typeof elem === 'undefined') {
                return;
            }

            if (typeof elem.validate === 'function') {
                this.valid = this.valid & elem.validate().valid;
            } else if (elem.elems) {
                elem.elems().forEach(this.validate, this);
            }
        },

        /**
         * Reset data from provider
         */
        resetData: function () {
            this.elems().forEach(this.resetValue, this);
        },

        /**
         * Update 'applied' property with data from modal content
         */
        applyData: function () {
            var applied = {};

            this.elems().forEach(this.gatherValues.bind(this, applied), this);
            this.applied = applied;
        },

        /**
         * Gather values from modal content
         *
         * @param {Array} applied
         * @param {HTMLElement} elem
         */
        gatherValues: function (applied, elem) {
            if (typeof elem.value === 'function') {
                applied[elem.name] = elem.value();
            } else if (elem.elems) {
                elem.elems().forEach(this.gatherValues.bind(this, applied), this);
            }
        },

        /**
         * Set to previous values from modal content
         *
         * @param {HTMLElement} elem
         */
        setPrevValues: function (elem) {
            if (typeof elem.value === 'function') {
                this.modal.focus();
                elem.value(this.applied[elem.name]);
            } else if (elem.elems) {
                elem.elems().forEach(this.setPrevValues, this);
            }
        },

        /**
         * Triggers some method in every modal child elem, if this method is defined
         *
         * @param {Object} action - action configuration,
         * must contain actionName and targetName and
         * can contain params
         */
        triggerAction: function (action) {
            var targetName = action.targetName,
                params = action.params || [],
                actionName = action.actionName,
                target;

            target = registry.async(targetName);

            if (target && typeof target === 'function' && actionName) {
                params.unshift(actionName);
                target.apply(target, params);
            }
        },

        /**
         * Override modal buttons callback placeholders with real callbacks
         */
        overrideModalButtonCallback: function () {
            var buttons = this.options.buttons;

            if (buttons && buttons.length) {
                buttons.forEach(function (button) {
                    button.click = this.getButtonClickHandler(button.actions);
                }, this);
            }
        },

        /**
         * Generate button click handler based on button's 'actions' configuration
         */
        getButtonClickHandler: function (actionsConfig) {
            var actions = actionsConfig.map(
                function (actionConfig) {
                    if (_.isObject(actionConfig)) {
                        return this.triggerAction.bind(this, actionConfig);
                    }

                    return this[actionConfig] ? this[actionConfig].bind(this) : function () {};
                }, this);

            return function () {
                actions.forEach(
                    function (action) {
                        action();
                    }
                );
            };
        },

        /**
         * Cancels changes in modal:
         * returning elems values to the previous state,
         * and close modal
         */
        actionCancel: function () {
            this.elems().forEach(this.setPrevValues, this);
            this.closeModal();
        },

        /**
         * Accept changes in modal by not preventing them.
         * Can be extended by exporting 'gatherValues' result somewhere
         */
        actionDone: function () {
            this.valid = true;
            this.elems().forEach(this.validate, this);

            if (this.valid) {
                this.closeModal();
            }
        }
    });
});