misc.js 8.85 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
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define([
    'underscore',
    'jquery',
    'FormData'
], function (_, $) {
    'use strict';

    var defaultAttributes,
        ajaxSettings,
        map;

    defaultAttributes = {
        method: 'post',
        enctype: 'multipart/form-data'
    };

    ajaxSettings = {
        default: {
            method: 'POST',
            cache: false,
            processData: false,
            contentType: false
        },
        simple: {
            method: 'POST',
            dataType: 'json'
        }
    };

    map = {
        'D': 'DDD',
        'dd': 'DD',
        'd': 'D',
        'EEEE': 'dddd',
        'EEE': 'ddd',
        'e': 'd',
        'yyyy': 'YYYY',
        'yy': 'YY',
        'y': 'YYYY',
        'a': 'A'
    };

    return {

        /**
         * Generates a unique identifier.
         *
         * @param {Number} [size=7] - Length of a resulting identifier.
         * @returns {String}
         */
        uniqueid: function (size) {
            var code = Math.random() * 25 + 65 | 0,
                idstr = String.fromCharCode(code);

            size = size || 7;

            while (idstr.length < size) {
                code = Math.floor(Math.random() * 42 + 48);

                if (code < 58 || code > 64) {
                    idstr += String.fromCharCode(code);
                }
            }

            return idstr;
        },

        /**
         * Limits function call.
         *
         * @param {Object} owner
         * @param {String} target
         * @param {Number} limit
         */
        limit: function (owner, target, limit) {
            var fn = owner[target];

            owner[target] = _.debounce(fn.bind(owner), limit);
        },

        /**
         * Converts mage date format to a moment.js format.
         *
         * @param {String} mageFormat
         * @returns {String}
         */
        normalizeDate: function (mageFormat) {
            var result = mageFormat;

            _.each(map, function (moment, mage) {
                result = result.replace(mage, moment);
            });

            return result;
        },

        /**
         * Puts provided value in range of min and max parameters.
         *
         * @param {Number} value - Value to be located.
         * @param {Number} min - Min value.
         * @param {Number} max - Max value.
         * @returns {Number}
         */
        inRange: function (value, min, max) {
            return Math.min(Math.max(min, value), max);
        },

        /**
         * Serializes and sends data via POST request.
         *
         * @param {Object} options - Options object that consists of
         *      a 'url' and 'data' properties.
         * @param {Object} attrs - Attributes that will be added to virtual form.
         */
        submit: function (options, attrs) {
            var form        = document.createElement('form'),
                data        = this.serialize(options.data),
                attributes  = _.extend({}, defaultAttributes, attrs || {});

            if (!attributes.action) {
                attributes.action = options.url;
            }

            data['form_key'] = window.FORM_KEY;

            _.each(attributes, function (value, name) {
                form.setAttribute(name, value);
            });

            data = _.map(
                data,
                function (value, name) {
                    return '<input type="hidden" ' +
                        'name="' + _.escape(name) + '" ' +
                        'value="' + _.escape(value) + '"' +
                        ' />';
                }
            ).join('');

            form.insertAdjacentHTML('afterbegin', data);
            document.body.appendChild(form);

            form.submit();
        },

        /**
         * Serializes and sends data via AJAX POST request.
         *
         * @param {Object} options - Options object that consists of
         *      a 'url' and 'data' properties.
         * @param {Object} config
         */
        ajaxSubmit: function (options, config) {
            var t = new Date().getTime(),
                settings;

            options.data['form_key'] = window.FORM_KEY;
            options.data = this.prepareFormData(options.data, config.ajaxSaveType);
            settings = _.extend({}, ajaxSettings[config.ajaxSaveType], options || {});

            if (!config.ignoreProcessEvents) {
                $('body').trigger('processStart');
            }

            return $.ajax(settings)
                .done(function (data) {
                    if (config.response) {
                        data.t = t;
                        config.response.data(data);
                        config.response.status(undefined);
                        config.response.status(!data.error);
                    }
                })
                .fail(function () {
                    config.response.status(undefined);
                    config.response.status(false);
                    config.response.data({
                        error: true,
                        messages: 'Something went wrong.',
                        t: t
                    });
                })
                .always(function () {
                    if (!config.ignoreProcessEvents) {
                        $('body').trigger('processStop');
                    }
                });
        },

        /**
         * Creates FormData object and append this data.
         *
         * @param {Object} data
         * @param {String} type
         * @returns {FormData}
         */
        prepareFormData: function (data, type) {
            var formData;

            if (type === 'default') {
                formData = new FormData();
                _.each(this.serialize(data), function (val, name) {
                    formData.append(name, val);
                });
            } else if (type === 'simple') {
                formData = this.serialize(data);
            }

            return formData;
        },

        /**
         * Filters data object. Finds properties with suffix
         * and sets their values to properties with the same name without suffix.
         *
         * @param {Object} data - The data object that should be filtered
         * @param {String} suffix - The string by which data object should be filtered
         * @param {String} separator - The string that is separator between property and suffix
         *
         * @returns {Object} Filtered data object
         */
        filterFormData: function (data, suffix, separator) {
            data = data || {};
            suffix = suffix || 'prepared-for-send';
            separator = separator || '-';

            _.each(data, function (value, key) {
                if (_.isObject(value) && !value.length) {
                    this.filterFormData(value, suffix, separator);
                } else if (_.isString(key) && ~key.indexOf(suffix)) {
                    data[key.split(separator)[0]] = value;
                    delete data[key];
                }
            }, this);

            return data;
        },

        /**
         * Replaces symbol codes with their unescaped counterparts.
         *
         * @param {String} data
         *
         * @returns {String}
         */
        unescape: function (data) {
            var unescaped = _.unescape(data),
                mapCharacters = {
                    '&#039;': '\''
                };

            _.each(mapCharacters, function (value, key) {
                unescaped = unescaped.replace(key, value);
            });

            return unescaped;
        },

        /**
         * Converts PHP IntlFormatter format to moment format.
         *
         * @param {String} format - PHP format
         * @returns {String} - moment compatible formatting
         */
        convertToMomentFormat: function (format) {
            var newFormat;

            newFormat = format.replace(/yyyy|yy|y/, 'YYYY'); // replace the year
            newFormat = newFormat.replace(/dd|d/g, 'DD'); // replace the date

            return newFormat;
        },

        /**
         * Get Url Parameters.
         *
         * @param {String} url - Url string
         * @returns {Object}
         */
        getUrlParameters: function (url) {
            var params = {},
                queries = url.split('?'),
                temp,
                i,
                l;

            if (!queries[1]) {
                return params;
            }

            queries = queries[1].split('&');

            for (i = 0, l = queries.length; i < l; i++) {
                temp = queries[i].split('=');

                if (temp[1]) {
                    params[temp[0]] = decodeURIComponent(temp[1].replace(/\+/g, '%20'));
                } else {
                    params[temp[0]] = '';
                }
            }

            return params;
        }
    };
});