mazey 3.6.7 → 3.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * mazey v3.6.7
2
+ * mazey v3.7.1
3
3
  * (c) 2018-2023 Mazey Chu
4
4
  * Released under the MIT License.
5
5
  */
@@ -4358,34 +4358,32 @@ function getQueryParam(param) {
4358
4358
  return '';
4359
4359
  }
4360
4360
  /**
4361
- * Get the query param's value of the input URL.
4361
+ * Returns the value of the specified query parameter in the input URL.
4362
4362
  *
4363
+ * @example
4363
4364
  * ```
4364
- * getUrlParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't3'); // 3
4365
- * getUrlParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't4'); // 4
4365
+ * getUrlParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't3'); // Returns '3'
4366
+ * getUrlParam('http://example.com/?t1=1&t2=2&t3=3&t4=4', 't4'); // Returns '4'
4366
4367
  * ```
4367
4368
  *
4368
- * @param {string} url URL string.
4369
- * @param {string} param Query param.
4370
- * @returns {string} value
4369
+ * @param {string} url The URL string.
4370
+ * @param {string} param The query parameter to retrieve the value for.
4371
+ * @returns {string|string[]} The value of the specified query parameter, or an empty string if the parameter is not found.
4371
4372
  * @category URL
4372
4373
  */
4373
4374
  function getUrlParam(url, param) {
4374
4375
  var result = {};
4375
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
4376
- url.replace(/\??(\w+)=([^&]*)&?/g, function (a, k, v) {
4376
+ url.replace(/\??(\w+)=([^&]*)&?/g, function (_, k, v) {
4377
4377
  if (result[k] !== undefined) {
4378
4378
  var t = result[k];
4379
+ // Cast `t` to `string[]` to ensure that `concat` receives an array
4379
4380
  result[k] = [].concat(t, v);
4380
4381
  } else {
4381
4382
  result[k] = v;
4382
4383
  }
4384
+ // Return an empty string to satisfy the signature of the replace method
4385
+ return '';
4383
4386
  });
4384
- // if (param === undefined) {
4385
- // return result;
4386
- // } else {
4387
- // return result[param] || '';
4388
- // }
4389
4387
  return result[param] || '';
4390
4388
  }
4391
4389
  /**
@@ -4667,8 +4665,8 @@ function generateRndNum(n) {
4667
4665
  return ret;
4668
4666
  }
4669
4667
  /**
4670
- * @method generateUniqueNum
4671
- * @description 根据时间生成唯一标志的数字 mGenerateUniqueNum() => 1538324722364123。
4668
+ * 根据时间生成唯一标志的数字 mGenerateUniqueNum() => 1538324722364123
4669
+ *
4672
4670
  * @param {number} n 随机数的长度
4673
4671
  * @category Util
4674
4672
  */
@@ -4682,8 +4680,8 @@ function generateUniqueNum(n) {
4682
4680
  return now + rnd;
4683
4681
  }
4684
4682
  /**
4685
- * @method floatToPercent
4686
- * @description 浮点数转为百分比 0.2 => 20%。
4683
+ * 浮点数转为百分比 0.2 => 20%
4684
+ *
4687
4685
  * @param {number} num 浮点数
4688
4686
  * @param {number} fixSize 保留几位浮点数
4689
4687
  * @category Util
@@ -4701,8 +4699,8 @@ function floatToPercent(num, fixSize) {
4701
4699
  return "".concat(ret, "%");
4702
4700
  }
4703
4701
  /**
4704
- * @method floatFixed
4705
- * @description 浮点数保留指定位。
4702
+ * 浮点数保留指定位
4703
+ *
4706
4704
  * @category Util
4707
4705
  */
4708
4706
  function floatFixed(num, size) {
@@ -4712,9 +4710,9 @@ function floatFixed(num, size) {
4712
4710
  return parseFloat(num).toFixed(size);
4713
4711
  }
4714
4712
  /**
4715
- * @method cancelBubble
4716
- * @description 阻止冒泡。
4717
- * @category Util
4713
+ * 阻止冒泡
4714
+ *
4715
+ * @category Event
4718
4716
  */
4719
4717
  function cancelBubble(e) {
4720
4718
  var ev = e || window.event;
@@ -4825,8 +4823,6 @@ function throttle(func, wait, options) {
4825
4823
  options = {};
4826
4824
  }
4827
4825
  options = Object.assign({}, options);
4828
- // timeout: setTimeout Handle
4829
- // previous: 上次时间戳
4830
4826
  var context = null;
4831
4827
  var args = null;
4832
4828
  var timeout = null;
@@ -4836,7 +4832,7 @@ function throttle(func, wait, options) {
4836
4832
  var later = function later() {
4837
4833
  previous = options.leading === false ? 0 : mNow();
4838
4834
  timeout = null;
4839
- result = func.apply(context, args);
4835
+ result = func.apply(this, args);
4840
4836
  if (!timeout) {
4841
4837
  context = args = null;
4842
4838
  }
@@ -4864,7 +4860,7 @@ function throttle(func, wait, options) {
4864
4860
  context = args = null;
4865
4861
  }
4866
4862
  } else if (!timeout && options.trailing !== false) {
4867
- timeout = setTimeout(later, remaining);
4863
+ timeout = setTimeout(later.bind(context), remaining);
4868
4864
  }
4869
4865
  return result;
4870
4866
  };
@@ -4887,7 +4883,7 @@ function debounce(func, wait, immediate) {
4887
4883
  var timeout = null;
4888
4884
  var timestamp = null;
4889
4885
  var args = null;
4890
- var result = [null][0];
4886
+ var result = null;
4891
4887
  var later = function later() {
4892
4888
  var last = mNow() - timestamp;
4893
4889
  if (last < wait && last >= 0) {
@@ -4993,50 +4989,45 @@ function getFriendlyInterval(start, end, options) {
4993
4989
  * isNumber('123'); // false
4994
4990
  * // Default: NaN, Infinity is not Number
4995
4991
  * isNumber(Infinity); // false
4996
- * isNumber(Infinity, { isUnFiniteAsNumber: true }); // true
4992
+ * isNumber(Infinity, { isInfinityAsNumber: true }); // true
4997
4993
  * isNumber(NaN); // false
4998
- * isNumber(NaN, { isNaNAsNumber: true, isUnFiniteAsNumber: true }); // true
4994
+ * isNumber(NaN, { isNaNAsNumber: true, isInfinityAsNumber: true }); // true
4999
4995
  * ```
5000
4996
  *
5001
4997
  * @param {*} num 被判断的值
5002
4998
  * @param {boolean} options.isNaNAsNumber 是否 NaN 算数字(默认不算)
5003
- * @param {boolean} options.isUnFiniteAsNumber 是否 无限 算数字(默认不算)
4999
+ * @param {boolean} options.isInfinityAsNumber 是否 无限 算数字(默认不算)
5004
5000
  * @returns {boolean} true 是数字
5005
5001
  * @category Util
5006
5002
  */
5007
5003
  function isNumber(num, options) {
5008
5004
  if (options === void 0) {
5009
- options = {
5010
- isNaNAsNumber: false,
5011
- isUnFiniteAsNumber: false
5012
- };
5005
+ options = {};
5013
5006
  }
5014
- var _a = Object.assign({
5015
- isNaNAsNumber: false,
5016
- isUnFiniteAsNumber: false
5017
- }, options),
5018
- isNaNAsNumber = _a.isNaNAsNumber,
5019
- isUnFiniteAsNumber = _a.isUnFiniteAsNumber;
5020
- var ret = true;
5021
- // 数字类型
5007
+ var _a = options.isNaNAsNumber,
5008
+ isNaNAsNumber = _a === void 0 ? false : _a,
5009
+ _b = options.isInfinityAsNumber,
5010
+ isInfinityAsNumber = _b === void 0 ? false : _b,
5011
+ _c = options.isUnFiniteAsNumber,
5012
+ isUnFiniteAsNumber = _c === void 0 ? false : _c;
5022
5013
  if (typeof num !== 'number') {
5023
- ret = false;
5014
+ return false;
5024
5015
  }
5025
- // 无限值
5026
- if (isUnFiniteAsNumber === false && !isFinite(num)) {
5027
- // console.log('1333');
5028
- ret = false;
5016
+ if (!(isInfinityAsNumber === true || isUnFiniteAsNumber === true) && !isFinite(num)) {
5017
+ return false;
5029
5018
  }
5030
- // NaN
5031
- if (isNaNAsNumber === false && isNaN(num)) {
5032
- // console.log('2333');
5033
- ret = false;
5019
+ // Be compatible with previous versions.
5020
+ // if (!isUnFiniteAsNumber && !isFinite(num)) {
5021
+ // return false;
5022
+ // }
5023
+ if (!isNaNAsNumber && isNaN(num)) {
5024
+ return false;
5034
5025
  }
5035
- return ret;
5026
+ return true;
5036
5027
  }
5037
5028
  /**
5038
- * @method doFn
5039
- * @description 执行有效函数
5029
+ * 执行有效函数
5030
+ *
5040
5031
  * @param {function} fn 等待被执行的未知是否有效的函数
5041
5032
  * @category Util
5042
5033
  */
@@ -5074,7 +5065,7 @@ function doFn(fn) {
5074
5065
  * ```
5075
5066
  *
5076
5067
  * @param {string} key 键
5077
- * @returns {any} 返回值
5068
+ * @returns {void} 返回值
5078
5069
  * @category Cache Data
5079
5070
  */
5080
5071
  function setSessionStorage(key, value) {
@@ -5144,7 +5135,7 @@ function getSessionStorage(key) {
5144
5135
  * ```
5145
5136
  *
5146
5137
  * @param {string} key 键
5147
- * @returns {any} 返回值
5138
+ * @returns {void} 返回值
5148
5139
  * @category Cache Data
5149
5140
  */
5150
5141
  function setLocalStorage(key, value) {
@@ -5423,8 +5414,8 @@ function loadScript(url, options) {
5423
5414
  });
5424
5415
  }
5425
5416
  /**
5426
- * @method mNow
5427
- * @description 获取时间戳
5417
+ * 获取时间戳
5418
+ *
5428
5419
  * @category Util
5429
5420
  */
5430
5421
  function mNow() {
@@ -5450,11 +5441,11 @@ function mNow() {
5450
5441
  */
5451
5442
  function setCookie(name, value, days, domain) {
5452
5443
  var domainParts, expires;
5453
- var date;
5444
+ // let date: any;
5454
5445
  if (days) {
5455
- date = new Date();
5446
+ var date = new Date();
5456
5447
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
5457
- expires = '; expires=' + date.toGMTString();
5448
+ expires = '; expires=' + date.toUTCString();
5458
5449
  } else {
5459
5450
  expires = '';
5460
5451
  }
@@ -6099,14 +6090,50 @@ function getBrowserInfo() {
6099
6090
  }
6100
6091
  }
6101
6092
  /**
6102
- * @method clearHtml
6103
- * @description 去除HTML标签
6093
+ * 去除 HTML 标签
6094
+ *
6104
6095
  * @param {string} str 带html标签的字符串
6105
6096
  * @returns {string} 字符串
6106
6097
  * @category Util
6107
6098
  */
6108
- function clearHtml(str) {
6109
- return str.replace(/<\/?.+?>/g, '').replace(/[\r\n]/g, '');
6099
+ function clearHtml(str, options) {
6100
+ if (options === void 0) {
6101
+ options = {};
6102
+ }
6103
+ var _a = options.removeNewLine,
6104
+ removeNewLine = _a === void 0 ? false : _a;
6105
+ var ret = '';
6106
+ if (str) {
6107
+ ret = str.replace(/<\/?.+?>/g, '');
6108
+ if (removeNewLine) {
6109
+ ret = ret.replace(/[\r\n]/g, '');
6110
+ }
6111
+ }
6112
+ return ret;
6113
+ // return str.replace(/<\/?.+?>/g, '').replace(/[\r\n]/g, '');
6114
+ }
6115
+ /**
6116
+ * Sanitizes user input to prevent XSS attacks
6117
+ *
6118
+ * @param input - The input string to sanitize
6119
+ * @returns The sanitized input string
6120
+ */
6121
+ function sanitizeInput(input) {
6122
+ var regex = /[&<>"'/]/g;
6123
+ var replacements = {
6124
+ '&': '&amp;',
6125
+ '<': '&lt;',
6126
+ '>': '&gt;',
6127
+ '"': '&quot;',
6128
+ '\'': '&#x27;',
6129
+ '/': '&#x2F;'
6130
+ };
6131
+ if (typeof input !== 'string') {
6132
+ console.error('Input must be a string');
6133
+ }
6134
+ return input.replace(regex, function (match) {
6135
+ return replacements[match];
6136
+ });
6110
6137
  }
6111
6138
  /**
6112
6139
  * 截取字符串,中文算 2 个字节
@@ -6839,7 +6866,6 @@ function getUrlFileType(url) {
6839
6866
  * The `src` attribute should contain `width` and/or `height` values in the format "width=100" or "height=100".
6840
6867
  * If jQuery is available, this function uses jQuery to select the images. Otherwise, it uses pure JavaScript.
6841
6868
  *
6842
- *
6843
6869
  * @example
6844
6870
  * ```
6845
6871
  * // Example images with `src` attributes containing `width` and/or `height` values
@@ -6859,18 +6885,21 @@ function setImgWidHeiBySrc() {
6859
6885
  var $ = window.jQuery || window.$;
6860
6886
  if ($) {
6861
6887
  // Use jQuery to select all images on the page
6862
- $('img').each(function () {
6888
+ var images = $('img');
6889
+ if (!(images && images.length)) return false;
6890
+ images.each(function () {
6863
6891
  var $this = $(this);
6864
6892
  if (!$this) return;
6865
6893
  // Get the `src` attribute of the image
6866
6894
  var src = $this.attr('src');
6867
- if (!src) return;
6895
+ var canMatch = src && typeof src === 'string' && src.length;
6896
+ if (!canMatch) return;
6868
6897
  // Use regular expressions to extract the `width` and `height` values from the `src` attribute
6869
6898
  var width = src.match(/width=([0-9]+[a-z%]*)/);
6870
6899
  var height = src.match(/height=([0-9]+[a-z%]*)/);
6871
6900
  // Set the width and height of the image using jQuery's `width()` and `height()` methods
6872
- if (width && width[1]) $this.width(width[1]);
6873
- if (height && height[1]) $this.height(height[1]);
6901
+ if (width && isNonEmptyArray(width) && width[1]) $this.width(width[1]);
6902
+ if (height && isNonEmptyArray(height) && height[1]) $this.height(height[1]);
6874
6903
  });
6875
6904
  return true;
6876
6905
  } else {
@@ -6879,19 +6908,82 @@ function setImgWidHeiBySrc() {
6879
6908
  if (images.length > 0) {
6880
6909
  // Loop through each image and set its width and height based on the `src` attribute
6881
6910
  Array.from(images).forEach(function (img) {
6911
+ var $this = img;
6912
+ if (!$this) return;
6882
6913
  // Get the `src` attribute of the image
6883
- var src = img.getAttribute('src');
6914
+ var src = $this.getAttribute('src');
6915
+ var canMatch = src && typeof src === 'string' && src.length;
6916
+ if (!canMatch) return;
6884
6917
  // Use regular expressions to extract the `width` and `height` values from the `src` attribute
6885
- var width = src ? src.match(/width=([0-9]+[a-z%]*)/) : null;
6886
- var height = src ? src.match(/height=([0-9]+[a-z%]*)/) : null;
6918
+ var width = src.match(/width=([0-9]+[a-z%]*)/);
6919
+ var height = src.match(/height=([0-9]+[a-z%]*)/);
6887
6920
  // Set the width and height of the image using the `style.width` and `style.height` properties
6888
- if (width && width[1]) img.style.width = width[1];
6889
- if (height && height[1]) img.style.height = height[1];
6921
+ if (width && isNonEmptyArray(width) && width[1]) $this.style.width = width[1];
6922
+ if (height && isNonEmptyArray(height) && height[1]) $this.style.height = height[1];
6890
6923
  });
6891
6924
  return true;
6892
6925
  }
6893
6926
  }
6894
6927
  return false;
6895
6928
  }
6929
+ /**
6930
+ * Generate the inline style string from the given parameters, First parameter is the ClassNames, Second parameter is the style array.
6931
+ *
6932
+ * @example
6933
+ * ```js
6934
+ * console.log(genStyleString('a', [ 'color:red' ])); // '.a{color:red;}'
6935
+ * console.log(genStyleString('b', [ 'color:red', 'font-size:12px' ])); // '.b{color:red;font-size:12px;}'
6936
+ * ```
6937
+ *
6938
+ * @param {string} className
6939
+ * @param {Array} styleArray
6940
+ * @returns {string} Return the inline style string.
6941
+ * @category DOM
6942
+ */
6943
+ function genStyleString(className, styleArray) {
6944
+ var style = '';
6945
+ if (styleArray && styleArray.length > 0) {
6946
+ // It's wrong. Last item will not include `;`.
6947
+ // style = styleArray.join(';');
6948
+ style = styleArray.join(';') + ';';
6949
+ }
6950
+ return ".".concat(className, "{").concat(style, "}");
6951
+ }
6952
+ /**
6953
+ * Load the image from the given url.
6954
+ * The target image will be loaded in the background, and the Promise status will change after the image is loaded.
6955
+ * If the image fails to load, the Promise status will change to `reject`.
6956
+ * If the image is loaded successfully, the Promise status will change to `resolve`.
6957
+ * If the image is loaded successfully, the Promise will return the image object.
6958
+ * If the image fails to load, the Promise will return the error object.
6959
+ * The method will help Web to preload the image. And the image will be cached by the browser.
6960
+ * We can use it to implement the lazy loading of images.
6961
+ * The method will not add the image to the DOM.
6962
+ *
6963
+ * @example
6964
+ * ```js
6965
+ * loadImage('https://example.com/example.png').then((img) => {
6966
+ * console.log(img);
6967
+ * }).catch((err) => {
6968
+ * console.log(err);
6969
+ * });
6970
+ * ```
6971
+ *
6972
+ * @param {string} url - The image url.
6973
+ * @returns {Promise} Return the Promise object.
6974
+ * @category Load Resource
6975
+ */
6976
+ function loadImage(url) {
6977
+ return new Promise(function (resolve, reject) {
6978
+ var img = new Image();
6979
+ img.onload = function () {
6980
+ resolve(img);
6981
+ };
6982
+ img.onerror = function (err) {
6983
+ reject(err);
6984
+ };
6985
+ img.src = url;
6986
+ });
6987
+ }
6896
6988
 
6897
- export { addClass, addEvent, addStyle, calLongestCommonSubsequence, calLongestCommonSubstring, camelCase2Underscore, camelCaseToKebabCase, cancelBubble, clearHtml, convert10To26, convertCamelToKebab, convertCamelToUnder, cutCHSString, debounce, deepCopyObject, doFn, floatFixed, floatToPercent, formatDate, genCustomConsole, genHashCode, generateRndNum, generateUniqueNum, getBrowserInfo, getCookie, getDefineListeners, getDomain, getFileSize, getFriendlyInterval, getHashQueryParam, getLocalStorage, getPerformance, getQueryParam, getSessionStorage, getUrlFileType, getUrlParam, hasClass, inRate, invokeEvent, isJSONString, isJsonString, isNonEmptyArray, isNumber, isSafePWAEnv, isSupportWebp, isValidData, isValidEmail, isValidPhoneNumber, isValidUrl, loadCSS, loadScript, mNow, mTrim, newLine, removeClass, removeEvent, setCookie, setImgWidHeiBySrc, setLocalStorage, setSessionStorage, throttle, truncateZHString, updateQueryParam, windowLoaded, zAxiosIsValidRes };
6989
+ export { addClass, addEvent, addStyle, calLongestCommonSubsequence, calLongestCommonSubstring, camelCase2Underscore, camelCaseToKebabCase, cancelBubble, clearHtml, convert10To26, convertCamelToKebab, convertCamelToUnder, cutCHSString, debounce, deepCopyObject, doFn, floatFixed, floatToPercent, formatDate, genCustomConsole, genHashCode, genStyleString, generateRndNum, generateUniqueNum, getBrowserInfo, getCookie, getDefineListeners, getDomain, getFileSize, getFriendlyInterval, getHashQueryParam, getLocalStorage, getPerformance, getQueryParam, getSessionStorage, getUrlFileType, getUrlParam, hasClass, inRate, invokeEvent, isJSONString, isJsonString, isNonEmptyArray, isNumber, isSafePWAEnv, isSupportWebp, isValidData, isValidEmail, isValidPhoneNumber, isValidUrl, loadCSS, loadImage, loadScript, mNow, mTrim, newLine, removeClass, removeEvent, sanitizeInput, setCookie, setImgWidHeiBySrc, setLocalStorage, setSessionStorage, throttle, truncateZHString, updateQueryParam, windowLoaded, zAxiosIsValidRes };