misc.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /**
  2. * Copyright © Magento, Inc. All rights reserved.
  3. * See COPYING.txt for license details.
  4. */
  5. define([
  6. 'underscore',
  7. 'jquery',
  8. 'FormData'
  9. ], function (_, $) {
  10. 'use strict';
  11. var defaultAttributes,
  12. ajaxSettings,
  13. map;
  14. defaultAttributes = {
  15. method: 'post',
  16. enctype: 'multipart/form-data'
  17. };
  18. ajaxSettings = {
  19. default: {
  20. method: 'POST',
  21. cache: false,
  22. processData: false,
  23. contentType: false
  24. },
  25. simple: {
  26. method: 'POST',
  27. dataType: 'json'
  28. }
  29. };
  30. map = {
  31. 'D': 'DDD',
  32. 'dd': 'DD',
  33. 'd': 'D',
  34. 'EEEE': 'dddd',
  35. 'EEE': 'ddd',
  36. 'e': 'd',
  37. 'yyyy': 'YYYY',
  38. 'yy': 'YY',
  39. 'y': 'YYYY',
  40. 'a': 'A'
  41. };
  42. return {
  43. /**
  44. * Generates a unique identifier.
  45. *
  46. * @param {Number} [size=7] - Length of a resulting identifier.
  47. * @returns {String}
  48. */
  49. uniqueid: function (size) {
  50. var code = Math.random() * 25 + 65 | 0,
  51. idstr = String.fromCharCode(code);
  52. size = size || 7;
  53. while (idstr.length < size) {
  54. code = Math.floor(Math.random() * 42 + 48);
  55. if (code < 58 || code > 64) {
  56. idstr += String.fromCharCode(code);
  57. }
  58. }
  59. return idstr;
  60. },
  61. /**
  62. * Limits function call.
  63. *
  64. * @param {Object} owner
  65. * @param {String} target
  66. * @param {Number} limit
  67. */
  68. limit: function (owner, target, limit) {
  69. var fn = owner[target];
  70. owner[target] = _.debounce(fn.bind(owner), limit);
  71. },
  72. /**
  73. * Converts mage date format to a moment.js format.
  74. *
  75. * @param {String} mageFormat
  76. * @returns {String}
  77. */
  78. normalizeDate: function (mageFormat) {
  79. var result = mageFormat;
  80. _.each(map, function (moment, mage) {
  81. result = result.replace(mage, moment);
  82. });
  83. return result;
  84. },
  85. /**
  86. * Puts provided value in range of min and max parameters.
  87. *
  88. * @param {Number} value - Value to be located.
  89. * @param {Number} min - Min value.
  90. * @param {Number} max - Max value.
  91. * @returns {Number}
  92. */
  93. inRange: function (value, min, max) {
  94. return Math.min(Math.max(min, value), max);
  95. },
  96. /**
  97. * Serializes and sends data via POST request.
  98. *
  99. * @param {Object} options - Options object that consists of
  100. * a 'url' and 'data' properties.
  101. * @param {Object} attrs - Attributes that will be added to virtual form.
  102. */
  103. submit: function (options, attrs) {
  104. var form = document.createElement('form'),
  105. data = this.serialize(options.data),
  106. attributes = _.extend({}, defaultAttributes, attrs || {});
  107. if (!attributes.action) {
  108. attributes.action = options.url;
  109. }
  110. data['form_key'] = window.FORM_KEY;
  111. _.each(attributes, function (value, name) {
  112. form.setAttribute(name, value);
  113. });
  114. data = _.map(
  115. data,
  116. function (value, name) {
  117. return '<input type="hidden" ' +
  118. 'name="' + _.escape(name) + '" ' +
  119. 'value="' + _.escape(value) + '"' +
  120. ' />';
  121. }
  122. ).join('');
  123. form.insertAdjacentHTML('afterbegin', data);
  124. document.body.appendChild(form);
  125. form.submit();
  126. },
  127. /**
  128. * Serializes and sends data via AJAX POST request.
  129. *
  130. * @param {Object} options - Options object that consists of
  131. * a 'url' and 'data' properties.
  132. * @param {Object} config
  133. */
  134. ajaxSubmit: function (options, config) {
  135. var t = new Date().getTime(),
  136. settings;
  137. options.data['form_key'] = window.FORM_KEY;
  138. options.data = this.prepareFormData(options.data, config.ajaxSaveType);
  139. settings = _.extend({}, ajaxSettings[config.ajaxSaveType], options || {});
  140. if (!config.ignoreProcessEvents) {
  141. $('body').trigger('processStart');
  142. }
  143. return $.ajax(settings)
  144. .done(function (data) {
  145. if (config.response) {
  146. data.t = t;
  147. config.response.data(data);
  148. config.response.status(undefined);
  149. config.response.status(!data.error);
  150. }
  151. })
  152. .fail(function () {
  153. config.response.status(undefined);
  154. config.response.status(false);
  155. config.response.data({
  156. error: true,
  157. messages: 'Something went wrong.',
  158. t: t
  159. });
  160. })
  161. .always(function () {
  162. if (!config.ignoreProcessEvents) {
  163. $('body').trigger('processStop');
  164. }
  165. });
  166. },
  167. /**
  168. * Creates FormData object and append this data.
  169. *
  170. * @param {Object} data
  171. * @param {String} type
  172. * @returns {FormData}
  173. */
  174. prepareFormData: function (data, type) {
  175. var formData;
  176. if (type === 'default') {
  177. formData = new FormData();
  178. _.each(this.serialize(data), function (val, name) {
  179. formData.append(name, val);
  180. });
  181. } else if (type === 'simple') {
  182. formData = this.serialize(data);
  183. }
  184. return formData;
  185. },
  186. /**
  187. * Filters data object. Finds properties with suffix
  188. * and sets their values to properties with the same name without suffix.
  189. *
  190. * @param {Object} data - The data object that should be filtered
  191. * @param {String} suffix - The string by which data object should be filtered
  192. * @param {String} separator - The string that is separator between property and suffix
  193. *
  194. * @returns {Object} Filtered data object
  195. */
  196. filterFormData: function (data, suffix, separator) {
  197. data = data || {};
  198. suffix = suffix || 'prepared-for-send';
  199. separator = separator || '-';
  200. _.each(data, function (value, key) {
  201. if (_.isObject(value) && !value.length) {
  202. this.filterFormData(value, suffix, separator);
  203. } else if (_.isString(key) && ~key.indexOf(suffix)) {
  204. data[key.split(separator)[0]] = value;
  205. delete data[key];
  206. }
  207. }, this);
  208. return data;
  209. },
  210. /**
  211. * Replaces symbol codes with their unescaped counterparts.
  212. *
  213. * @param {String} data
  214. *
  215. * @returns {String}
  216. */
  217. unescape: function (data) {
  218. var unescaped = _.unescape(data),
  219. mapCharacters = {
  220. '&#039;': '\''
  221. };
  222. _.each(mapCharacters, function (value, key) {
  223. unescaped = unescaped.replace(key, value);
  224. });
  225. return unescaped;
  226. },
  227. /**
  228. * Converts PHP IntlFormatter format to moment format.
  229. *
  230. * @param {String} format - PHP format
  231. * @returns {String} - moment compatible formatting
  232. */
  233. convertToMomentFormat: function (format) {
  234. var newFormat;
  235. newFormat = format.replace(/yyyy|yy|y/, 'YYYY'); // replace the year
  236. newFormat = newFormat.replace(/dd|d/g, 'DD'); // replace the date
  237. return newFormat;
  238. },
  239. /**
  240. * Get Url Parameters.
  241. *
  242. * @param {String} url - Url string
  243. * @returns {Object}
  244. */
  245. getUrlParameters: function (url) {
  246. var params = {},
  247. queries = url.split('?'),
  248. temp,
  249. i,
  250. l;
  251. if (!queries[1]) {
  252. return params;
  253. }
  254. queries = queries[1].split('&');
  255. for (i = 0, l = queries.length; i < l; i++) {
  256. temp = queries[i].split('=');
  257. if (temp[1]) {
  258. params[temp[0]] = decodeURIComponent(temp[1].replace(/\+/g, '%20'));
  259. } else {
  260. params[temp[0]] = '';
  261. }
  262. }
  263. return params;
  264. }
  265. };
  266. });