@shopgate/pwa-common
Version:
Common library for the Shopgate Connect PWA.
93 lines • 10.1 kB
JavaScript
function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _toArray(arr){return _arrayWithHoles(arr)||_iterableToArray(arr)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance");}function _iterableToArray(iter){if(Symbol.iterator in Object(iter)||Object.prototype.toString.call(iter)==="[object Arguments]")return Array.from(iter);}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}import{logger}from'@shopgate/pwa-core/helpers';import{isAndroidOs}from'@shopgate/pwa-core';import{isObject,isArray}from"../validation";/**
* Tests if the prop is an object or an array.
* @param {*} prop The property to test.
* @return {boolean}
*/var isObjectOrArray=function isObjectOrArray(prop){return isObject(prop)||isArray(prop);};/**
* Remove the first element of the array.
* @param {Array} array The array to remove the first element from.
* @returns {Array} The reduced array.
*/export var shift=function shift(_ref){var _ref2=_toArray(_ref),newArray=_ref2.slice(1);return newArray;};/**
* Returns a new object without certain keys.
* @param {Object} obj The original object.
* @param {Array} [keys=[]] An array of unwanted keys.
* @return {Object} The reduced object.
*/export var objectWithoutProps=function objectWithoutProps(obj){var keys=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];var target={};Object.keys(obj).forEach(function(key){if(!keys.includes(key)){target[key]=obj[key];}});return target;};/**
* Checks if a URL is an external URL.
* @param {string} url The URL to check.
* @return {boolean}
*/export var isExternal=function isExternal(url){return url.includes('http://')||url.includes('https://')||url.includes('//');};/**
* Checks whether the url is an HTTPS url.
* @param {string} url The url to open.
* @return {boolean}
*/export var isHTTPS=function isHTTPS(){var url=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';return url.startsWith('https://');};/**
* Returns the actual url to the image, by adding url parameters with the dimensions for img-cdn
* @param {string} src Source to the image.
* @param {Object} dimension Dimension of the requested image.
* @param {number} dimension.width Width in pixels.
* @param {number} dimension.height Height in pixels.
* @deprecated use @engage/core/helpers/getFullImageSource instead
* @returns {string}
*/export var getActualImageSource=function getActualImageSource(src,_ref3){var width=_ref3.width,height=_ref3.height;if(src&&src.includes('images.shopgate.services/v2/images')){var fillColor='FFFFFF,1';var format=isAndroidOs?'webp':'jpeg';return"".concat(src,"&format=").concat(format,"&width=").concat(width,"&height=").concat(height,"&quality=75&fill=").concat(fillColor.replace('#',''));}if(src&&src.startsWith('https://img-cdn.shopgate.com')&&!src.includes('?')){return"".concat(src,"?w=").concat(width,"&h=").concat(height,"&q=70&zc=resize&fillc=FFFFFF");}return src;};/**
* Finds the index of a property inside an array.
* @param {Array} arr The array to check.
* @param {Function} fn The callback function to filter inside the array.
* @return {number} The index of the property.
*/export var findIndex=function findIndex(arr,fn){if(Array.isArray(arr)){for(var i=0;i<arr.length;i+=1){if(fn(arr[i])){return i;}}}return-1;};/**
* Convert binary data into hexadecimal representation
* @param {string|number} str The string that shall be encoded
* @see http://locutus.io/php/strings/bin2hex/
* @return {string} The hexadecimal representation of the given string
*/export var bin2hex=function bin2hex(str){var s="".concat(str);var i;var l;var o='';var n;for(i=0,l=s.length;i<l;i+=1){n=s.charCodeAt(i).toString(16);o+=n.length<2?"0".concat(n):n;}return o;};/**
* Decodes a hexadecimal encoded binary string
* @param {string} str The string that shall be decoded
* @see http://locutus.io/php/strings/hex2bin/
* @returns {string|boolean} Hexadecimal representation of data. FALSE if decoding failed.
*/export var hex2bin=function hex2bin(str){var s="".concat(str);var ret=[];var i=0;var l;for(l=s.length;i<l;i+=2){var c=parseInt(s.substr(i,1),16);var k=parseInt(s.substr(i+1,1),16);if(Number.isNaN(c)||Number.isNaN(k)){return false;}// eslint-disable-next-line no-bitwise
ret.push(c<<4|k);}// eslint-disable-next-line prefer-spread
return String.fromCharCode.apply(String,ret);};/**
* Compares two strings of object keys for object sorting.
* @param {string} a The first key.
* @param {string} b The second key.
* @return {number} The sort order.
*/var defaultKeySortFn=function defaultKeySortFn(a,b){return a.localeCompare(b);};/**
* Deep sorts an object by its keys.
* @param {Object} src The object to sort.
* @param {Function} [comparator=defaultKeySortFn] The sorting operator callback.
* @return {Object} The sorted object.
*/export var sortObject=function sortObject(src){var comparator=arguments.length>1&&arguments[1]!==undefined?arguments[1]:defaultKeySortFn;if(Array.isArray(src)){return src.map(function(item){return sortObject(item,comparator);});}if(isObject(src)){return Object.keys(src).sort(comparator).reduce(function(obj,key){return _extends({},obj,_defineProperty({},key,sortObject(src[key],comparator)));},{});}return src;};/**
* Transforms widget display options to match pipeline specifications.
* @param {string} displayOptions The display options as specified by the widget settings.
* @returns {string} The transformed string compatible with the pipeline requests.
*/export var transformDisplayOptions=function transformDisplayOptions(displayOptions){switch(displayOptions){case'relevance_asc':case'relevance_desc':return'relevance';case'price_asc':return'priceAsc';case'price_desc':return'priceDesc';case'name_asc':return'nameAsc';case'name_desc':return'nameDesc';default:return displayOptions;}};/**
* Validates all parameters. The selector will return null if one parameter is invalid.
* @param {Function} selector The original selector.
* @param {Object} [defaultResult] The result when the selector fails.
* @return {Function}
*/export var validateSelectorParams=function validateSelectorParams(selector){var defaultResult=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;return function(){for(var _len=arguments.length,params=new Array(_len),_key=0;_key<_len;_key++){params[_key]=arguments[_key];}if(params.some(function(param){return param===null||typeof param==='undefined';})){return defaultResult;}return selector.apply(void 0,params);};};/**
* @callback ArrayItemComparator
* @param {string} path
* @param {*} prev
* @param {*} next
* @param {number} prevIndex
* @param {number} nextIndex
* @returns {boolean}
*/ /**
* Takes a destination object and a source and merges the source object into the destination.
* Differing properties will replaced. References are kept where possible.
* @param {Object} destination Object to mutate
* @param {Object} source Object which contains the properties to assign to the destination
* @param {boolean} [warn] Enables log output on mismatching types. Defaults to 'true'.
* @param {ArrayItemComparator|null} [arrayComparator] Defines how to compare array items.
* @param {string} [path] Path that specifies the position of a given merge within the object tree.
*/export function assignObjectDeep(destination,source){var warn=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;var arrayComparator=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var path=arguments.length>4&&arguments[4]!==undefined?arguments[4]:'';// Avoids eslint warning on param mutation, which is necessary
var dest=destination;var src=source;// Don't do anything when types are scalar (can occur in recursion)
if(_typeof(dest)!=='object'||_typeof(src)!=='object'){return;}Object.keys(src).forEach(function(key){var keyPath="".concat(path,".").concat(key).replace(/^\./,'');var prop=src[key];if(!isObjectOrArray(dest[key])||!isObjectOrArray(prop)){// output a warning if only one of both is an object (undefined dest is fine -> no warning)
if(warn&&dest[key]!==undefined&&(!isObjectOrArray(dest[key])?isObjectOrArray(prop):!isObjectOrArray(prop))){logger.warn('Trying to merge object properties with mixed object types: ',prop,dest[key]);}// Overwrite always if one of the props is not an object or array
dest[key]=prop;return;}// Both structures are objects but one or both can be an array
if(isArray(prop)&&isArray(dest[key])){// Try to keep reference of as many array items as possible
prop.forEach(function(element,destIndex){var itemPath="".concat(keyPath,".").concat(destIndex);// Check if a maching array item exists for merging
var existing=dest[key].find(function(prev,prevIndex){return arrayComparator(itemPath,prev,element,prevIndex,destIndex);});// Merge into existing if found or add to array otherwise
if(existing!==undefined){// Scalar types can't be merged and will be ignored when an equal exists
assignObjectDeep(existing,element,warn,arrayComparator,itemPath);}else{dest[key].push(element);}});}else if(!isArray(prop)&&!isArray(dest[key])){// Merge objects
assignObjectDeep(dest[key],prop,warn,arrayComparator,keyPath);}else{// Object types differ, print a warning
if(warn){logger.warn('Merging object properties with mixed object types: ',prop,dest[key]);}dest[key]=prop;}});}