ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
+161
View File
@@ -0,0 +1,161 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'underscore',
'./strings'
], function (_, utils) {
'use strict';
/**
* Defines index of an item in a specified container.
*
* @param {*} item - Item whose index should be defined.
* @param {Array} container - Container upon which to perform search.
* @returns {Number}
*/
function getIndex(item, container) {
var index = container.indexOf(item);
if (~index) {
return index;
}
return _.findIndex(container, function (value) {
return value && value.name === item;
});
}
return {
/**
* Facade method to remove/add value from/to array
* without creating a new instance.
*
* @param {Array} arr - Array to be modified.
* @param {*} value - Value to add/remove.
* @param {Boolean} add - Flag that specfies operation.
* @returns {Utils} Chainable.
*/
toggle: function (arr, value, add) {
return add ?
this.add(arr, value) :
this.remove(arr, value);
},
/**
* Removes the incoming value from array in case
* without creating a new instance of it.
*
* @param {Array} arr - Array to be modified.
* @param {*} value - Value to be removed.
* @returns {Utils} Chainable.
*/
remove: function (arr, value) {
var index = arr.indexOf(value);
if (~index) {
arr.splice(index, 1);
}
return this;
},
/**
* Adds the incoming value to array if
* it's not alredy present in there.
*
* @param {Array} arr - Array to be modifed.
* @param {...*} arguments - Values to be added.
* @returns {Utils} Chainable.
*/
add: function (arr) {
var values = _.toArray(arguments).slice(1);
values.forEach(function (value) {
if (!~arr.indexOf(value)) {
arr.push(value);
}
});
return this;
},
/**
* Inserts specified item into container at a specified position.
*
* @param {*} item - Item to be inserted into container.
* @param {Array} container - Container of items.
* @param {*} [position=-1] - Position at which item should be inserted.
* Position can represent:
* - specific index in container
* - item which might already be present in container
* - structure with one of these properties: after, before
* @returns {Boolean|*}
* - true if element has changed its' position
* - false if nothing has changed
* - inserted value if it wasn't present in container
*/
insert: function (item, container, position) {
var currentIndex = getIndex(item, container),
newIndex,
target;
if (typeof position === 'undefined') {
position = -1;
} else if (typeof position === 'string') {
position = isNaN(+position) ? position : +position;
}
newIndex = position;
if (~currentIndex) {
target = container.splice(currentIndex, 1)[0];
if (typeof item === 'string') {
item = target;
}
}
if (typeof position !== 'number') {
target = position.after || position.before || position;
newIndex = getIndex(target, container);
if (~newIndex && (position.after || newIndex >= currentIndex)) {
newIndex++;
}
}
if (newIndex < 0) {
newIndex += container.length + 1;
}
container[newIndex] ?
container.splice(newIndex, 0, item) :
container[newIndex] = item;
return !~currentIndex ? item : currentIndex !== newIndex;
},
/**
* @param {Array} elems
* @param {Number} offset
* @return {Number|*}
*/
formatOffset: function (elems, offset) {
if (utils.isEmpty(offset)) {
offset = -1;
}
offset = +offset;
if (offset < 0) {
offset += elems.length + 1;
}
return offset;
}
};
});
+225
View File
@@ -0,0 +1,225 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'underscore',
'mage/utils/objects'
], function (_, utils) {
'use strict';
var result = [];
/**
* Checks if all of the provided arrays contains equal values.
*
* @param {(Boolean|Array)} [keepOrder=false]
* @param {Array} target
* @returns {Boolean}
*/
function equalArrays(keepOrder, target) {
var args = _.toArray(arguments),
arrays;
if (!Array.isArray(keepOrder)) {
arrays = args.slice(2);
} else {
target = keepOrder;
keepOrder = false;
arrays = args.slice(1);
}
if (!arrays.length) {
return true;
}
return arrays.every(function (array) {
if (array === target) {
return true;
} else if (array.length !== target.length) {
return false;
} else if (!keepOrder) {
return !_.difference(target, array).length;
}
return array.every(function (value, index) {
return target[index] === value;
});
});
}
/**
* Checks if two values are different.
*
* @param {*} a - First value.
* @param {*} b - Second value.
* @returns {Boolean}
*/
function isDifferent(a, b) {
var oldIsPrimitive = utils.isPrimitive(a);
if (Array.isArray(a) && Array.isArray(b)) {
return !equalArrays(true, a, b);
}
return oldIsPrimitive ? a !== b : true;
}
/**
* @param {String} prefix
* @param {String} part
*/
function getPath(prefix, part) {
return prefix ? prefix + '.' + part : part;
}
/**
* Checks if object has own specified property.
*
* @param {*} obj - Value to be checked.
* @param {String} key - Key of the property.
* @returns {Boolean}
*/
function hasOwn(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
/**
* @param {Array} changes
*/
function getContainers(changes) {
var containers = {},
indexed = _.indexBy(changes, 'path');
_.each(indexed, function (change, name) {
var path;
name.split('.').forEach(function (part) {
path = getPath(path, part);
if (path in indexed) {
return;
}
(containers[path] = containers[path] || []).push(change);
});
});
return containers;
}
/**
* @param {String} path
* @param {String} name
* @param {String} type
* @param {String} newValue
* @param {String} oldValue
*/
function addChange(path, name, type, newValue, oldValue) {
var data;
data = {
path: path,
name: name,
type: type
};
if (type !== 'remove') {
data.value = newValue;
data.oldValue = oldValue;
} else {
data.oldValue = newValue;
}
result.push(data);
}
/**
* @param {String} ns
* @param {String} name
* @param {String} type
* @param {String} iterator
* @param {String} placeholder
*/
function setAll(ns, name, type, iterator, placeholder) {
var key;
if (arguments.length > 4) {
type === 'add' ?
addChange(ns, name, 'update', iterator, placeholder) :
addChange(ns, name, 'update', placeholder, iterator);
} else {
addChange(ns, name, type, iterator);
}
if (!utils.isObject(iterator)) {
return;
}
for (key in iterator) {
if (hasOwn(iterator, key)) {
setAll(getPath(ns, key), key, type, iterator[key]);
}
}
}
/*eslint-disable max-depth*/
/**
* @param {Object} old
* @param {Object} current
* @param {String} ns
* @param {String} name
*/
function compare(old, current, ns, name) {
var key,
oldIsObj = utils.isObject(old),
newIsObj = utils.isObject(current);
if (oldIsObj && newIsObj) {
for (key in old) {
if (hasOwn(old, key) && !hasOwn(current, key)) {
setAll(getPath(ns, key), key, 'remove', old[key]);
}
}
for (key in current) {
if (hasOwn(current, key)) {
hasOwn(old, key) ?
compare(old[key], current[key], getPath(ns, key), key) :
setAll(getPath(ns, key), key, 'add', current[key]);
}
}
} else if (oldIsObj) {
setAll(ns, name, 'remove', old, current);
} else if (newIsObj) {
setAll(ns, name, 'add', current, old);
} else if (isDifferent(old, current)) {
addChange(ns, name, 'update', current, old);
}
}
/*eslint-enable max-depth*/
return {
/**
*
* @returns {Object}
*/
compare: function () {
var changes;
compare.apply(null, arguments);
changes = result.splice(0);
return {
containers: getContainers(changes),
changes: changes,
equal: !changes.length
};
},
equalArrays: equalArrays
};
});
+25
View File
@@ -0,0 +1,25 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define(function (require) {
'use strict';
var utils = {},
_ = require('underscore'),
root = typeof self == 'object' && self.self === self && self ||
typeof global == 'object' && global.global === global && global ||
Function('return this')() || {};
root._ = _;
return _.extend(
utils,
require('./arrays'),
require('./compare'),
require('./misc'),
require('./objects'),
require('./strings'),
require('./template')
);
});
+327
View File
@@ -0,0 +1,327 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'underscore',
'jquery',
'mage/utils/objects'
], function (_, $, utils) {
'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(
new RegExp(mage + '(?=([^\u0027]*\u0027[^\u0027]*\u0027)*[^\u0027]*$)'),
moment
);
});
result = result.replace(/'(.*?)'/g, '[$1]');
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 = utils.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 () {
if (config.response) {
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(utils.serialize(data), function (val, name) {
formData.append(name, val);
});
} else if (type === 'simple') {
formData = utils.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) && !Array.isArray(value)) {
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 special characters with their corresponding HTML entities.
*
* @param {String} string - Text to escape.
* @returns {String} Escaped text.
*/
escape: function (string) {
return string ? $('<p></p>').text(string).html().replace(/"/g, '&quot;') : string;
},
/**
* 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;
}
};
});
+451
View File
@@ -0,0 +1,451 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'ko',
'jquery',
'underscore',
'mage/utils/strings'
], function (ko, $, _, stringUtils) {
'use strict';
var primitives = [
'undefined',
'boolean',
'number',
'string'
];
/**
* Sets nested property of a specified object.
* @private
*
* @param {Object} parent - Object to look inside for the properties.
* @param {Array} path - Splitted path the property.
* @param {*} value - Value of the last property in 'path' array.
* returns {*} New value for the property.
*/
function setNested(parent, path, value) {
var last = path.pop(),
len = path.length,
pi = 0,
part = path[pi];
for (; pi < len; part = path[++pi]) {
if (!_.isObject(parent[part])) {
parent[part] = {};
}
parent = parent[part];
}
if (typeof parent[last] === 'function') {
parent[last](value);
} else {
parent[last] = value;
}
return value;
}
/**
* Retrieves value of a nested property.
* @private
*
* @param {Object} parent - Object to look inside for the properties.
* @param {Array} path - Splitted path the property.
* @returns {*} Value of the property.
*/
function getNested(parent, path) {
var exists = true,
len = path.length,
pi = 0;
for (; pi < len && exists; pi++) {
parent = parent[path[pi]];
if (typeof parent === 'undefined') {
exists = false;
}
}
if (exists) {
if (ko.isObservable(parent)) {
parent = parent();
}
return parent;
}
}
/**
* Removes property from a specified object.
* @private
*
* @param {Object} parent - Object from which to remove property.
* @param {Array} path - Splitted path to the property.
*/
function removeNested(parent, path) {
var field = path.pop();
parent = getNested(parent, path);
if (_.isObject(parent)) {
delete parent[field];
}
}
return {
/**
* Retrieves or defines objects' property by a composite path.
*
* @param {Object} data - Container for the properties specified in path.
* @param {String} path - Objects' properties divided by dots.
* @param {*} [value] - New value for the last property.
* @returns {*} Returns value of the last property in chain.
*
* @example
* utils.nested({}, 'one.two', 3);
* => { one: {two: 3} }
*/
nested: function (data, path, value) {
var action = arguments.length > 2 ? setNested : getNested;
path = path ? path.split('.') : [];
return action(data, path, value);
},
/**
* Removes nested property from an object.
*
* @param {Object} data - Data source.
* @param {String} path - Path to the property e.g. 'one.two.three'
*/
nestedRemove: function (data, path) {
path = path.split('.');
removeNested(data, path);
},
/**
* Flattens objects' nested properties.
*
* @param {Object} data - Object to flatten.
* @param {String} [separator='.'] - Objects' keys separator.
* @returns {Object} Flattened object.
*
* @example Example with a default separator.
* utils.flatten({one: { two: { three: 'value'} }});
* => { 'one.two.three': 'value' };
*
* @example Example with a custom separator.
* utils.flatten({one: { two: { three: 'value'} }}, '=>');
* => {'one=>two=>three': 'value'};
*/
flatten: function (data, separator, parent, result) {
separator = separator || '.';
result = result || {};
if (!data) {
return result;
}
// UnderscoreJS each breaks when an object has a length property so we use Object.keys
_.each(Object.keys(data), function (name) {
var node = data[name];
if ({}.toString.call(node) === '[object Function]') {
return;
}
if (parent) {
name = parent + separator + name;
}
typeof node === 'object' ?
this.flatten(node, separator, name, result) :
result[name] = node;
}, this);
return result;
},
/**
* Opposite operation of the 'flatten' method.
*
* @param {Object} data - Previously flattened object.
* @param {String} [separator='.'] - Keys separator.
* @returns {Object} Object with nested properties.
*
* @example Example using custom separator.
* utils.unflatten({'one=>two': 'value'}, '=>');
* => {
* one: { two: 'value' }
* };
*/
unflatten: function (data, separator) {
var result = {};
separator = separator || '.';
_.each(data, function (value, nodes) {
nodes = nodes.split(separator);
setNested(result, nodes, value);
});
return result;
},
/**
* Same operation as 'flatten' method,
* but returns objects' keys wrapped in '[]'.
*
* @param {Object} data - Object that should be serialized.
* @returns {Object} Serialized data.
*
* @example
* utils.serialize({one: { two: { three: 'value'} }});
* => { 'one[two][three]': 'value' }
*/
serialize: function (data) {
var result = {};
data = this.flatten(data);
_.each(data, function (value, keys) {
keys = stringUtils.serializeName(keys);
value = _.isUndefined(value) ? '' : value;
result[keys] = value;
}, this);
return result;
},
/**
* Performs deep extend of specified objects.
*
* @returns {Object|Array} Extended object.
*/
extend: function () {
var args = _.toArray(arguments);
args.unshift(true);
return $.extend.apply($, args);
},
/**
* Performs a deep clone of a specified object.
*
* @param {(Object|Array)} data - Data that should be copied.
* @returns {Object|Array} Cloned object.
*/
copy: function (data) {
var result = data,
isArray = Array.isArray(data),
placeholder;
if (this.isObject(data) || isArray) {
placeholder = isArray ? [] : {};
result = this.extend(placeholder, data);
}
return result;
},
/**
* Performs a deep clone of a specified object.
* Doesn't save links to original object.
*
* @param {*} original - Object to clone
* @returns {*}
*/
hardCopy: function (original) {
if (original === null || typeof original !== 'object') {
return original;
}
return JSON.parse(JSON.stringify(original));
},
/**
* Removes specified nested properties from the target object.
*
* @param {Object} target - Object whose properties should be removed.
* @param {(...String|Array|Object)} list - List that specifies properties to be removed.
* @returns {Object} Modified object.
*
* @example Basic usage
* var obj = {a: {b: 2}, c: 'a'};
*
* omit(obj, 'a.b');
* => {'a.b': 2};
* obj => {a: {}, c: 'a'};
*
* @example Various syntaxes that would return same result
* omit(obj, ['a.b', 'c']);
* omit(obj, 'a.b', 'c');
* omit(obj, {'a.b': true, 'c': true});
*/
omit: function (target, list) {
var removed = {},
ignored = list;
if (this.isObject(list)) {
ignored = [];
_.each(list, function (value, key) {
if (value) {
ignored.push(key);
}
});
} else if (_.isString(list)) {
ignored = _.toArray(arguments).slice(1);
}
_.each(ignored, function (path) {
var value = this.nested(target, path);
if (!_.isUndefined(value)) {
removed[path] = value;
this.nestedRemove(target, path);
}
}, this);
return removed;
},
/**
* Checks if provided value is a plain object.
*
* @param {*} value - Value to be checked.
* @returns {Boolean}
*/
isObject: function (value) {
var objProto = Object.prototype;
return typeof value == 'object' ?
objProto.toString.call(value) === '[object Object]' :
false;
},
/**
*
* @param {*} value
* @returns {Boolean}
*/
isPrimitive: function (value) {
return value === null || ~primitives.indexOf(typeof value);
},
/**
* Iterates over obj props/array elems recursively, applying action to each one
*
* @param {Object|Array} data - Data to be iterated.
* @param {Function} action - Callback to be called with each item as an argument.
* @param {Number} [maxDepth=7] - Max recursion depth.
*/
forEachRecursive: function (data, action, maxDepth) {
maxDepth = typeof maxDepth === 'number' && !isNaN(maxDepth) ? maxDepth - 1 : 7;
if (!_.isFunction(action) || _.isFunction(data) || maxDepth < 0) {
return;
}
if (!_.isObject(data)) {
action(data);
return;
}
_.each(data, function (value) {
this.forEachRecursive(value, action, maxDepth);
}, this);
action(data);
},
/**
* Maps obj props/array elems recursively
*
* @param {Object|Array} data - Data to be iterated.
* @param {Function} action - Callback to transform each item.
* @param {Number} [maxDepth=7] - Max recursion depth.
*
* @returns {Object|Array}
*/
mapRecursive: function (data, action, maxDepth) {
var newData;
maxDepth = typeof maxDepth === 'number' && !isNaN(maxDepth) ? maxDepth - 1 : 7;
if (!_.isFunction(action) || _.isFunction(data) || maxDepth < 0) {
return data;
}
if (!_.isObject(data)) {
return action(data);
}
if (_.isArray(data)) {
newData = _.map(data, function (item) {
return this.mapRecursive(item, action, maxDepth);
}, this);
return action(newData);
}
newData = _.mapObject(data, function (val, key) {
if (data.hasOwnProperty(key)) {
return this.mapRecursive(val, action, maxDepth);
}
return val;
}, this);
return action(newData);
},
/**
* Removes empty(in common sence) obj props/array elems
*
* @param {*} data - Data to be cleaned.
* @returns {*}
*/
removeEmptyValues: function (data) {
if (!_.isObject(data)) {
return data;
}
if (_.isArray(data)) {
return data.filter(function (item) {
return !this.isEmptyObj(item);
}, this);
}
return _.omit(data, this.isEmptyObj.bind(this));
},
/**
* Checks that argument of any type is empty in common sence:
* empty string, string with spaces only, object without own props, empty array, null or undefined
*
* @param {*} val - Value to be checked.
* @returns {Boolean}
*/
isEmptyObj: function (val) {
return _.isObject(val) && _.isEmpty(val) ||
this.isEmpty(val) ||
val && val.trim && this.isEmpty(val.trim());
}
};
});
+152
View File
@@ -0,0 +1,152 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'underscore'
], function (_) {
'use strict';
var jsonRe = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/;
return {
/**
* Attempts to convert string to one of the primitive values,
* or to parse it as a valid json object.
*
* @param {String} str - String to be processed.
* @returns {*}
*/
castString: function (str) {
try {
str = str === 'true' ? true :
str === 'false' ? false :
str === 'null' ? null :
+str + '' === str ? +str :
jsonRe.test(str) ? JSON.parse(str) :
str;
} catch (e) {
}
return str;
},
/**
* Splits string by separator if it's possible,
* otherwise returns the incoming value.
*
* @param {(String|Array|*)} str - String to split.
* @param {String} [separator=' '] - Seperator based on which to split the string.
* @returns {Array|*} Splitted string or the incoming value.
*/
stringToArray: function (str, separator) {
separator = separator || ' ';
return typeof str === 'string' ?
str.split(separator) :
str;
},
/**
* Converts the incoming string which consists
* of a specified delimiters into a format commonly used in form elements.
*
* @param {String} name - The incoming string.
* @param {String} [separator='.']
* @returns {String} Serialized string.
*
* @example
* utils.serializeName('one.two.three');
* => 'one[two][three]';
*/
serializeName: function (name, separator) {
var result;
separator = separator || '.';
name = name.split(separator);
result = name.shift();
name.forEach(function (part) {
result += '[' + part + ']';
});
return result;
},
/**
* Checks wether the incoming value is not empty,
* e.g. not 'null' or 'undefined'
*
* @param {*} value - Value to check.
* @returns {Boolean}
*/
isEmpty: function (value) {
return value === '' || _.isUndefined(value) || _.isNull(value);
},
/**
* Adds 'prefix' to the 'part' value if it was provided.
*
* @param {String} prefix
* @param {String} part
* @returns {String}
*/
fullPath: function (prefix, part) {
return prefix ? prefix + '.' + part : part;
},
/**
* Splits incoming string and returns its' part specified by offset.
*
* @param {String} parts
* @param {Number} [offset]
* @param {String} [delimiter=.]
* @returns {String}
*/
getPart: function (parts, offset, delimiter) {
delimiter = delimiter || '.';
parts = parts.split(delimiter);
offset = this.formatOffset(parts, offset);
parts.splice(offset, 1);
return parts.join(delimiter) || '';
},
/**
* Converts nameThroughCamelCase to name-through-minus
*
* @param {String} string
* @returns {String}
*/
camelCaseToMinus: function camelCaseToMinus(string) {
return ('' + string)
.split('')
.map(function (symbol, index) {
return index ?
symbol.toUpperCase() === symbol ?
'-' + symbol.toLowerCase() :
symbol :
symbol.toLowerCase();
})
.join('');
},
/**
* Converts name-through-minus to nameThroughCamelCase
*
* @param {String} string
* @returns {String}
*/
minusToCamelCase: function minusToCamelCase(string) {
return ('' + string)
.split('-')
.map(function (part, index) {
return index ? part.charAt(0).toUpperCase() + part.slice(1) : part;
})
.join('');
}
};
});
+247
View File
@@ -0,0 +1,247 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* eslint-disable no-shadow */
define([
'jquery',
'underscore',
'mage/utils/objects',
'mage/utils/strings'
], function ($, _, utils, stringUtils) {
'use strict';
var tmplSettings = _.templateSettings,
interpolate = /\$\{([\s\S]+?)\}/g,
opener = '${',
template,
hasStringTmpls;
/**
* Identifies whether ES6 templates are supported.
*/
hasStringTmpls = (function () {
var testString = 'var foo = "bar"; return `${ foo }` === foo';
try {
return Function(testString)();
} catch (e) {
return false;
}
})();
/**
* Objects can specify how to use templating for their properties - getting that configuration.
*
* To disable rendering for all properties of your object add __disableTmpl: true.
* To disable for specific property add __disableTmpl: {propertyName: true}.
* To limit recursion for a specific property add __disableTmpl: {propertyName: numberOfCycles}.
*
* @param {String} tmpl
* @param {Object | undefined} target
* @returns {Boolean|Object}
*/
function isTmplIgnored(tmpl, target) {
var parsedTmpl;
try {
parsedTmpl = JSON.parse(tmpl);
if (typeof parsedTmpl === 'object') {
return tmpl.includes('__disableTmpl');
}
} catch (e) {
}
if (typeof target !== 'undefined') {
if (typeof target === 'object' && target.hasOwnProperty('__disableTmpl')) {
return target.__disableTmpl;
}
}
return false;
}
if (hasStringTmpls) {
/*eslint-disable no-unused-vars, no-eval*/
/**
* Evaluates template string using ES6 templates.
*
* @param {String} tmpl - Template string.
* @param {Object} $ - Data object used in a template.
* @returns {String} Compiled template.
*/
template = function (tmpl, $) {
return eval('`' + tmpl + '`');
};
/*eslint-enable no-unused-vars, no-eval*/
} else {
/**
* Fallback function used when ES6 templates are not supported.
* Uses underscore templates renderer.
*
* @param {String} tmpl - Template string.
* @param {Object} data - Data object used in a template.
* @returns {String} Compiled template.
*/
template = function (tmpl, data) {
var cached = tmplSettings.interpolate;
tmplSettings.interpolate = interpolate;
tmpl = _.template(tmpl, {
variable: '$'
})(data);
tmplSettings.interpolate = cached;
return tmpl;
};
}
/**
* Checks if provided value contains template syntax.
*
* @param {*} value - Value to be checked.
* @returns {Boolean}
*/
function isTemplate(value) {
return typeof value === 'string' &&
value.indexOf(opener) !== -1 &&
// the below pattern almost always indicates an accident which should not cause template evaluation
// refuse to evaluate
value.indexOf('${{') === -1;
}
/**
* Iteratively processes provided string
* until no templates syntax will be found.
*
* @param {String} tmpl - Template string.
* @param {Object} data - Data object used in a template.
* @param {Boolean} [castString=false] - Flag that indicates whether template
* should be casted after evaluation to a value of another type or
* that it should be leaved as a string.
* @param {Number|undefined} maxCycles - Maximum number of rendering cycles, can be 0.
* @returns {*} Compiled template.
*/
function render(tmpl, data, castString, maxCycles) {
var last = tmpl,
cycles = 0;
while (~tmpl.indexOf(opener) && (typeof maxCycles === 'undefined' || cycles < maxCycles)) {
if (!isTmplIgnored(tmpl)) {
tmpl = template(tmpl, data);
}
if (tmpl === last) {
break;
}
last = tmpl;
cycles++;
}
return castString ?
stringUtils.castString(tmpl) :
tmpl;
}
return {
/**
* Applies provided data to the template.
*
* @param {Object|String} tmpl
* @param {Object} [data] - Data object to match with template.
* @param {Boolean} [castString=false] - Flag that indicates whether template
* should be casted after evaluation to a value of another type or
* that it should be leaved as a string.
* @returns {*}
*
* @example Template defined as a string.
* var source = { foo: 'Random Stuff', bar: 'Some' };
*
* utils.template('${ $.bar } ${ $.foo }', source);
* => 'Some Random Stuff';
*
* @example Template defined as an object.
* var tmpl = {
* key: {'${ $.$data.bar }': '${ $.$data.foo }'},
* foo: 'bar',
* x1: 2, x2: 5,
* delta: '${ $.x2 - $.x1 }',
* baz: 'Upper ${ $.foo.toUpperCase() }'
* };
*
* utils.template(tmpl, source);
* => {
* key: {'Some': 'Random Stuff'},
* foo: 'bar',
* x1: 2, x2: 5,
* delta: 3,
* baz: 'Upper BAR'
* };
*/
template: function (tmpl, data, castString, dontClone) {
if (typeof tmpl === 'string') {
return render(tmpl, data, castString);
}
if (!dontClone) {
tmpl = utils.copy(tmpl);
}
tmpl.$data = data || {};
/**
* Template iterator function.
*/
_.each(tmpl, function iterate(value, key, list) {
var disabled,
maxCycles;
if (key === '$data') {
return;
}
if (isTemplate(key)) {
delete list[key];
key = render(key, tmpl);
list[key] = value;
}
if (isTemplate(value)) {
//Getting template disabling settings, can be true for all disabled and separate settings
//for each property.
disabled = isTmplIgnored(value, list);
if (typeof disabled === 'object' && disabled.hasOwnProperty(key) && disabled[key] !== false) {
//Checking if specific settings for a property provided.
maxCycles = disabled[key];
}
if (disabled === true || maxCycles === true) {
//Rendering for all properties is disabled.
maxCycles = 0;
}
list[key] = render(value, tmpl, castString, maxCycles);
} else if ($.isPlainObject(value) || Array.isArray(value)) {
_.each(value, iterate);
}
});
delete tmpl.$data;
return tmpl;
}
};
});
+158
View File
@@ -0,0 +1,158 @@
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Utility methods used to wrap and extend functions.
*
* @example Usage of a 'wrap' method with arguments delegation.
* var multiply = function (a, b) {
* return a * b;
* };
*
* multiply = module.wrap(multiply, function (orig) {
* return 'Result is: ' + orig();
* });
*
* multiply(2, 2);
* => 'Result is: 4'
*
* @example Usage of 'wrapSuper' method.
* var multiply = function (a, b) {
* return a * b;
* };
*
* var obj = {
* multiply: module.wrapSuper(multiply, function () {
* return 'Result is: ' + this._super();
* });
* };
*
* obj.multiply(2, 2);
* => 'Result is: 4'
*/
define([
'underscore'
], function (_) {
'use strict';
/**
* Checks if string has a '_super' substring.
*/
var superReg = /\b_super\b/;
return {
/**
* Wraps target function with a specified wrapper, which will receive
* reference to the original function as a first argument.
*
* @param {Function} target - Function to be wrapped.
* @param {Function} wrapper - Wrapper function.
* @returns {Function} Wrapper function.
*/
wrap: function (target, wrapper) {
if (!_.isFunction(target) || !_.isFunction(wrapper)) {
return wrapper;
}
return function () {
var args = _.toArray(arguments),
ctx = this,
_super;
/**
* Function that will be passed to the wrapper.
* If no arguments will be passed to it, then the original
* function will be called with an arguments of a wrapper function.
*/
_super = function () {
var superArgs = arguments.length ? arguments : args.slice(1);
return target.apply(ctx, superArgs);
};
args.unshift(_super);
return wrapper.apply(ctx, args);
};
},
/**
* Wraps the incoming function to implement support of the '_super' method.
*
* @param {Function} target - Function to be wrapped.
* @param {Function} wrapper - Wrapper function.
* @returns {Function} Wrapped function.
*/
wrapSuper: function (target, wrapper) {
if (!this.hasSuper(wrapper) || !_.isFunction(target)) {
return wrapper;
}
return function () {
var _super = this._super,
args = arguments,
result;
/**
* Temporary define '_super' method which
* contains call to the original function.
*/
this._super = function () {
var superArgs = arguments.length ? arguments : args;
return target.apply(this, superArgs);
};
result = wrapper.apply(this, args);
this._super = _super;
return result;
};
},
/**
* Checks wether the incoming method contains calls of the '_super' method.
*
* @param {Function} fn - Function to be checked.
* @returns {Boolean}
*/
hasSuper: function (fn) {
return _.isFunction(fn) && superReg.test(fn);
},
/**
* Extends target object with provided extenders.
* If property in target and extender objects is a function,
* then it will be wrapped using 'wrap' method.
*
* @param {Object} target - Object to be extended.
* @param {...Object} extenders - Multiple extenders objects.
* @returns {Object} Modified target object.
*/
extend: function (target) {
var extenders = _.toArray(arguments).slice(1),
iterator = this._extend.bind(this, target);
extenders.forEach(iterator);
return target;
},
/**
* Same as the 'extend' method, but operates only on one extender object.
*
* @private
* @param {Object} target
* @param {Object} extender
*/
_extend: function (target, extender) {
_.each(extender, function (value, key) {
target[key] = this.wrap(target[key], extender[key]);
}, this);
}
};
});