Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

328 рядки
9.5 KiB

  1. /**
  2. * Copyright © Magento, Inc. All rights reserved.
  3. * See COPYING.txt for license details.
  4. */
  5. define([
  6. 'underscore',
  7. 'jquery',
  8. 'mage/utils/objects'
  9. ], function (_, $, utils) {
  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(
  82. new RegExp(mage + '(?=([^\u0027]*\u0027[^\u0027]*\u0027)*[^\u0027]*$)'),
  83. moment
  84. );
  85. });
  86. result = result.replace(/'(.*?)'/g, '[$1]');
  87. return result;
  88. },
  89. /**
  90. * Puts provided value in range of min and max parameters.
  91. *
  92. * @param {Number} value - Value to be located.
  93. * @param {Number} min - Min value.
  94. * @param {Number} max - Max value.
  95. * @returns {Number}
  96. */
  97. inRange: function (value, min, max) {
  98. return Math.min(Math.max(min, value), max);
  99. },
  100. /**
  101. * Serializes and sends data via POST request.
  102. *
  103. * @param {Object} options - Options object that consists of
  104. * a 'url' and 'data' properties.
  105. * @param {Object} attrs - Attributes that will be added to virtual form.
  106. */
  107. submit: function (options, attrs) {
  108. var form = document.createElement('form'),
  109. data = utils.serialize(options.data),
  110. attributes = _.extend({}, defaultAttributes, attrs || {});
  111. if (!attributes.action) {
  112. attributes.action = options.url;
  113. }
  114. data['form_key'] = window.FORM_KEY;
  115. _.each(attributes, function (value, name) {
  116. form.setAttribute(name, value);
  117. });
  118. data = _.map(
  119. data,
  120. function (value, name) {
  121. return '<input type="hidden" ' +
  122. 'name="' + _.escape(name) + '" ' +
  123. 'value="' + _.escape(value) + '"' +
  124. ' />';
  125. }
  126. ).join('');
  127. form.insertAdjacentHTML('afterbegin', data);
  128. document.body.appendChild(form);
  129. form.submit();
  130. },
  131. /**
  132. * Serializes and sends data via AJAX POST request.
  133. *
  134. * @param {Object} options - Options object that consists of
  135. * a 'url' and 'data' properties.
  136. * @param {Object} config
  137. */
  138. ajaxSubmit: function (options, config) {
  139. var t = new Date().getTime(),
  140. settings;
  141. options.data['form_key'] = window.FORM_KEY;
  142. options.data = this.prepareFormData(options.data, config.ajaxSaveType);
  143. settings = _.extend({}, ajaxSettings[config.ajaxSaveType], options || {});
  144. if (!config.ignoreProcessEvents) {
  145. $('body').trigger('processStart');
  146. }
  147. return $.ajax(settings)
  148. .done(function (data) {
  149. if (config.response) {
  150. data.t = t;
  151. config.response.data(data);
  152. config.response.status(undefined);
  153. config.response.status(!data.error);
  154. }
  155. })
  156. .fail(function () {
  157. if (config.response) {
  158. config.response.status(undefined);
  159. config.response.status(false);
  160. config.response.data({
  161. error: true,
  162. messages: 'Something went wrong.',
  163. t: t
  164. });
  165. }
  166. })
  167. .always(function () {
  168. if (!config.ignoreProcessEvents) {
  169. $('body').trigger('processStop');
  170. }
  171. });
  172. },
  173. /**
  174. * Creates FormData object and append this data.
  175. *
  176. * @param {Object} data
  177. * @param {String} type
  178. * @returns {FormData}
  179. */
  180. prepareFormData: function (data, type) {
  181. var formData;
  182. if (type === 'default') {
  183. formData = new FormData();
  184. _.each(utils.serialize(data), function (val, name) {
  185. formData.append(name, val);
  186. });
  187. } else if (type === 'simple') {
  188. formData = utils.serialize(data);
  189. }
  190. return formData;
  191. },
  192. /**
  193. * Filters data object. Finds properties with suffix
  194. * and sets their values to properties with the same name without suffix.
  195. *
  196. * @param {Object} data - The data object that should be filtered
  197. * @param {String} suffix - The string by which data object should be filtered
  198. * @param {String} separator - The string that is separator between property and suffix
  199. *
  200. * @returns {Object} Filtered data object
  201. */
  202. filterFormData: function (data, suffix, separator) {
  203. data = data || {};
  204. suffix = suffix || 'prepared-for-send';
  205. separator = separator || '-';
  206. _.each(data, function (value, key) {
  207. if (_.isObject(value) && !Array.isArray(value)) {
  208. this.filterFormData(value, suffix, separator);
  209. } else if (_.isString(key) && ~key.indexOf(suffix)) {
  210. data[key.split(separator)[0]] = value;
  211. delete data[key];
  212. }
  213. }, this);
  214. return data;
  215. },
  216. /**
  217. * Replaces special characters with their corresponding HTML entities.
  218. *
  219. * @param {String} string - Text to escape.
  220. * @returns {String} Escaped text.
  221. */
  222. escape: function (string) {
  223. return string ? $('<p></p>').text(string).html().replace(/"/g, '&quot;') : string;
  224. },
  225. /**
  226. * Replaces symbol codes with their unescaped counterparts.
  227. *
  228. * @param {String} data
  229. *
  230. * @returns {String}
  231. */
  232. unescape: function (data) {
  233. var unescaped = _.unescape(data),
  234. mapCharacters = {
  235. '&#039;': '\''
  236. };
  237. _.each(mapCharacters, function (value, key) {
  238. unescaped = unescaped.replace(key, value);
  239. });
  240. return unescaped;
  241. },
  242. /**
  243. * Converts PHP IntlFormatter format to moment format.
  244. *
  245. * @param {String} format - PHP format
  246. * @returns {String} - moment compatible formatting
  247. */
  248. convertToMomentFormat: function (format) {
  249. var newFormat;
  250. newFormat = format.replace(/yyyy|yy|y/, 'YYYY'); // replace the year
  251. newFormat = newFormat.replace(/dd|d/g, 'DD'); // replace the date
  252. return newFormat;
  253. },
  254. /**
  255. * Get Url Parameters.
  256. *
  257. * @param {String} url - Url string
  258. * @returns {Object}
  259. */
  260. getUrlParameters: function (url) {
  261. var params = {},
  262. queries = url.split('?'),
  263. temp,
  264. i,
  265. l;
  266. if (!queries[1]) {
  267. return params;
  268. }
  269. queries = queries[1].split('&');
  270. for (i = 0, l = queries.length; i < l; i++) {
  271. temp = queries[i].split('=');
  272. if (temp[1]) {
  273. params[temp[0]] = decodeURIComponent(temp[1].replace(/\+/g, '%20'));
  274. } else {
  275. params[temp[0]] = '';
  276. }
  277. }
  278. return params;
  279. }
  280. };
  281. });