mazey 4.13.2 → 5.0.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.d.ts CHANGED
@@ -143,7 +143,7 @@ type SingleValueUrlParams = {
143
143
 
144
144
  type ThrottleFunc<T extends (...args: any[]) => any> = (...args: Parameters<T>) => ReturnType<T> | null;
145
145
 
146
- type DebounceFunc<T extends (...args: any[]) => any> = (...args: Parameters<T>) => ReturnType<T>;
146
+ type DebounceFunc<T extends (...args: any[]) => any> = (...args: Parameters<T>) => ReturnType<T> | null;
147
147
 
148
148
  interface IsNumberOptions {
149
149
  isNaNAsNumber?: boolean;
@@ -170,7 +170,7 @@ interface RepeatUntilOptions {
170
170
  args?: Array<any>;
171
171
  }
172
172
 
173
- type LoadScriptReturns = Promise<boolean | string | Error | void>;
173
+ type LoadScriptReturns = Promise<string>;
174
174
 
175
175
  type SimpleType = string | number | boolean | null | undefined;
176
176
 
@@ -203,6 +203,9 @@ interface OnURLChangeOptions {
203
203
  /**
204
204
  * Copy/Clone Object deeply.
205
205
  *
206
+ * Custom class instances are copied as plain objects containing their own
207
+ * properties. Unsupported native instances are preserved by reference.
208
+ *
206
209
  * Usage:
207
210
  *
208
211
  * ```javascript
@@ -578,7 +581,7 @@ declare function floatToPercent(num: number, fixSize?: number): string;
578
581
  *
579
582
  * @category Util
580
583
  */
581
- declare function floatFixed(num: string, size?: number): string;
584
+ declare function floatFixed(num: number | string, size?: number): string;
582
585
  /**
583
586
  * EN: Throttle, used to limit the frequency of function execution over time.
584
587
  *
@@ -621,37 +624,56 @@ declare function throttle<T extends (...args: MazeyFnParams) => MazeyFnReturn>(f
621
624
  */
622
625
  declare function debounce<T extends (...args: MazeyFnParams) => MazeyFnReturn>(func: T, wait: number, immediate?: boolean): DebounceFunc<T>;
623
626
  /**
624
- * EN: Get interval time.
627
+ * Calculate the interval between two dates or timestamps.
625
628
  *
626
- * ZH: 获取间隔时间。
629
+ * The default `d` type returns the number of whole days. The `text` type
630
+ * returns an English duration using days, hours, minutes, and seconds while
631
+ * omitting zero-valued units. A zero interval returns `"0 seconds"`. Any other
632
+ * type returns the number of whole seconds. Negative intervals and invalid
633
+ * dates return an empty string.
627
634
  *
628
635
  * Usage:
629
636
  *
630
637
  * ```javascript
631
- * import { getFriendlyInterval } from "mazey";
638
+ * import { getDateDifference } from "mazey";
632
639
  *
633
- * const ret1 = getFriendlyInterval(new Date("2020-03-28 00:09:27"), new Date("2023-04-18 10:54:00"), { type: "d" });
634
- * const ret2 = getFriendlyInterval(1585325367000, 1681786440000, { type: "text" });
635
- * const ret3 = getFriendlyInterval("2020-03-28 00:09:27", "2023-04-18 10:54:00", { type: "text" });
636
- * console.log(ret1);
637
- * console.log(ret2);
638
- * console.log(ret3);
640
+ * const days = getDateDifference(0, 90061000);
641
+ * const text = getDateDifference(0, 90061000, { type: "text" });
642
+ * const compactText = getDateDifference(0, 90060000, { type: "text" });
643
+ * const dateStringDays = getDateDifference(
644
+ * "2020-03-28 00:09:27",
645
+ * "2023-04-18 10:54:00"
646
+ * );
647
+ * console.log(days);
648
+ * console.log(text);
649
+ * console.log(compactText);
650
+ * console.log(dateStringDays);
639
651
  * ```
640
652
  *
641
653
  * Output:
642
654
  *
643
655
  * ```text
656
+ * 1
657
+ * 1 day 1 hour 1 minute 1 second
658
+ * 1 day 1 hour 1 minute
644
659
  * 1116
645
- * 1116 天 10 时 44 分 33 秒
646
- * 1116 天 10 时 44 分 33 秒
647
660
  * ```
648
661
  *
649
- * @param {number/Date} start 开始时间戳 1585325367122
650
- * @param {number/Date} end 结束时间戳 1585325367122
651
- * @param {string} options.type 返回类型 d: 2(天) text: 2 天 4 时...
652
- * @returns {string/number} 取决于 type
662
+ * @param start Start date or timestamp.
663
+ * @param end End date or timestamp.
664
+ * @param options Formatting options. Use `d` for whole days or `text` for an English duration.
665
+ * @returns Whole days, whole seconds, an English duration, or an empty string for a negative or invalid interval.
666
+ * @remarks Strings in `YYYY-MM-DD HH:mm:ss` format are normalized and parsed as local time. Other date strings use the runtime's native `Date` parser; use timestamps or ISO strings with an explicit timezone when parsing must be portable.
653
667
  * @category Util
654
668
  */
669
+ declare function getDateDifference(start?: number | string | Date, end?: number | string | Date, options?: {
670
+ type?: string;
671
+ }): number | string;
672
+ /**
673
+ * Alias of `getDateDifference`.
674
+ *
675
+ * @hidden
676
+ */
655
677
  declare function getFriendlyInterval(start?: number | string | Date, end?: number | string | Date, options?: {
656
678
  type?: string;
657
679
  }): number | string;
@@ -704,8 +726,7 @@ declare function formatDurationFromMs(durationMs: number): string;
704
726
  * ```
705
727
  *
706
728
  * @param {*} num 被判断的值
707
- * @param {boolean} options.isNaNAsNumber 是否 NaN 算数字(默认不算)
708
- * @param {boolean} options.isInfinityAsNumber 是否 无限 算数字(默认不算)
729
+ * @param options Controls whether `NaN`, `Infinity`, or other non-finite values count as numbers.
709
730
  * @returns {boolean} true 是数字
710
731
  * @category Util
711
732
  */
@@ -728,13 +749,13 @@ declare function isNumber(num: unknown, options?: IsNumberOptions): boolean;
728
749
  * @param {function} fn 等待被执行的未知是否有效的函数
729
750
  * @category Util
730
751
  */
731
- declare function invokeFn(fn: MazeyFunction, ...params: Parameters<MazeyFunction>): ReturnType<MazeyFunction> | null;
752
+ declare function invokeFn(fn: MazeyFunction | null | undefined, ...params: Parameters<MazeyFunction>): ReturnType<MazeyFunction> | null;
732
753
  /**
733
754
  * Alias of `invokeFn`.
734
755
  *
735
756
  * @hidden
736
757
  */
737
- declare function doFn(fn: MazeyFunction, ...params: Parameters<MazeyFunction>): ReturnType<MazeyFunction> | null;
758
+ declare function doFn(fn: MazeyFunction | null | undefined, ...params: Parameters<MazeyFunction>): ReturnType<MazeyFunction> | null;
738
759
  /**
739
760
  * Verify the validity of a non-empty array.
740
761
  *
@@ -1099,7 +1120,7 @@ declare function unsanitize(str: string): string;
1099
1120
  * @returns {string} 返回截取后的字符串
1100
1121
  * @category Util
1101
1122
  */
1102
- declare function cutZHString(str: string, len: number, options?: {
1123
+ declare function cutZHString(str: string | null | undefined, len: number, options?: {
1103
1124
  hasDot?: boolean;
1104
1125
  dotText?: string;
1105
1126
  }): string;
@@ -1126,13 +1147,13 @@ declare function cutZHString(str: string, len: number, options?: {
1126
1147
  * @returns {string} 返回截取后的字符串
1127
1148
  * @hidden
1128
1149
  */
1129
- declare function truncateZHString(str: string, len: number, hasDot?: boolean): string;
1150
+ declare function truncateZHString(str: string | null | undefined, len: number, hasDot?: boolean): string;
1130
1151
  /**
1131
1152
  * Alias of `truncateZHString`.
1132
1153
  *
1133
1154
  * @hidden
1134
1155
  */
1135
- declare function cutCHSString(str: string, len: number, hasDot?: boolean): string;
1156
+ declare function cutCHSString(str: string | null | undefined, len: number, hasDot?: boolean): string;
1136
1157
  /**
1137
1158
  * Verify the validity of axios response.
1138
1159
  *
@@ -1141,7 +1162,7 @@ declare function cutCHSString(str: string, len: number, hasDot?: boolean): strin
1141
1162
  * @category Util
1142
1163
  * @hidden
1143
1164
  */
1144
- declare function zAxiosIsValidRes(res: ZResResponse | undefined, options?: ZResIsValidResOptions): boolean;
1165
+ declare function zAxiosIsValidRes(res: ZResResponse | undefined, options?: ZResIsValidResOptions | null): boolean;
1145
1166
  /**
1146
1167
  * Determine the validity of the data.
1147
1168
  *
@@ -1226,9 +1247,61 @@ declare function getFileSize(size: number): string;
1226
1247
  * @category Util
1227
1248
  */
1228
1249
  declare function genHashCode(str: string): number;
1250
+ /**
1251
+ * Check whether an unknown value represents a valid date.
1252
+ *
1253
+ * Valid inputs include `Date` instances, finite millisecond timestamps,
1254
+ * structured local date strings, and ISO 8601 strings with `Z` or a numeric
1255
+ * timezone offset. Structured strings are parsed into numeric components and
1256
+ * validated strictly, so invalid calendar dates are not normalized.
1257
+ *
1258
+ * Supported string forms are `YYYY-MM-DD`, `YYYY-MM-DD HH:mm[:ss]`,
1259
+ * `YYYY-MM-DDTHH:mm[:ss]`, and the same `T`-separated date-time with `Z` or
1260
+ * a `+HH:mm`/`-HH:mm` offset. Zoned strings may include 1-3 millisecond digits.
1261
+ *
1262
+ * Usage:
1263
+ *
1264
+ * ```javascript
1265
+ * import { isValidDate } from "mazey";
1266
+ *
1267
+ * const ret1 = isValidDate(1577877720000);
1268
+ * const ret2 = isValidDate("2020-01-01 11:22");
1269
+ * const ret3 = isValidDate("2020-02-30");
1270
+ * const ret4 = isValidDate(new Date("invalid"));
1271
+ *
1272
+ * console.log(ret1, ret2, ret3, ret4);
1273
+ * ```
1274
+ *
1275
+ * Output:
1276
+ *
1277
+ * ```text
1278
+ * true true false false
1279
+ * ```
1280
+ *
1281
+ * @param value A `Date`, millisecond timestamp, or supported structured date string.
1282
+ * @returns Whether the value represents a valid date.
1283
+ * @category Util
1284
+ */
1285
+ declare function isValidDate(value: unknown): boolean;
1229
1286
  /**
1230
1287
  * Return the formatted date string in the given format.
1231
1288
  *
1289
+ * Supported format tokens:
1290
+ *
1291
+ * | Token | Meaning | Range or example |
1292
+ * | ------ | -------------------------------------- | ---------------- |
1293
+ * | `yyyy` | Four-digit year | `2022` |
1294
+ * | `MM` | Two-digit month | `01`–`12` |
1295
+ * | `dd` | Two-digit day of the month | `01`–`31` |
1296
+ * | `HH` | Two-digit hour using the 24-hour clock | `00`–`23` |
1297
+ * | `hh` | Two-digit hour using the 12-hour clock | `01`–`12` |
1298
+ * | `mm` | Two-digit minute | `00`–`59` |
1299
+ * | `ss` | Two-digit second | `00`–`59` |
1300
+ * | `a` | Uppercase meridiem indicator | `AM` or `PM` |
1301
+ *
1302
+ * The function creates a native `Date` and reads its local date and time
1303
+ * fields. Timestamp output can therefore differ between runtime time zones.
1304
+ *
1232
1305
  * Usage:
1233
1306
  *
1234
1307
  * ```javascript
@@ -1253,14 +1326,15 @@ declare function genHashCode(str: string): number;
1253
1326
  * Date formatDate value: 02/11/2014
1254
1327
  * ```
1255
1328
  *
1256
- * @param {MazeyDate} dateIns Original Date
1257
- * @param {string} format Format String
1258
- * @returns {string} Return the formatted date string.
1329
+ * @param {MazeyDate} dateIns Original date value. Defaults to the current date and time.
1330
+ * @param {string} format Format string composed of supported format tokens. Defaults to `yyyy-MM-dd`.
1331
+ * @returns {string} The formatted date string.
1332
+ * @throws {RangeError} If `dateIns` is not a valid date.
1259
1333
  * @category Util
1260
1334
  */
1261
1335
  declare function formatDate(dateIns?: MazeyDate, format?: string): string;
1262
1336
  /**
1263
- * Generate a Calendar Versioning string from a date.
1337
+ * Generate a local-time Calendar Versioning string from a date.
1264
1338
  *
1265
1339
  * The conceptual format is `yyyy.MMdd.HHmmss`. Leading zeroes are removed
1266
1340
  * from each segment to keep numeric Semantic Versioning identifiers valid.
@@ -1282,6 +1356,7 @@ declare function formatDate(dateIns?: MazeyDate, format?: string): string;
1282
1356
  *
1283
1357
  * @param {MazeyDate} dateIns Original date. Defaults to the current date.
1284
1358
  * @returns {string} Return the generated calendar version.
1359
+ * @throws {RangeError} If `dateIns` is not a valid date.
1285
1360
  * @category Util
1286
1361
  */
1287
1362
  declare function generateCalendarVersion(dateIns?: MazeyDate): string;
@@ -1391,11 +1466,7 @@ declare function getCurrentVersion(): string;
1391
1466
  * ```
1392
1467
  *
1393
1468
  * @param callback The callback function to fire.
1394
- * @param options An object containing the options for the function.
1395
- * @param options.interval The interval between each firing of the callback function, in milliseconds. Defaults to 1000.
1396
- * @param options.times The maximum number of times to fire the callback function. Defaults to 10.
1397
- * @param options.context The context to use when calling the callback function. Defaults to null.
1398
- * @param options.args An array of arguments to pass to the callback function.
1469
+ * @param options Controls the interval, maximum invocation count, callback context, and callback arguments.
1399
1470
  * @param condition A function that takes the result of the callback function as its argument and returns a boolean value indicating whether the condition has been met. Defaults to a function that always returns true.
1400
1471
  * @category Util
1401
1472
  */
@@ -2214,7 +2285,7 @@ declare function fireEvent(type: string, params?: MazeyObject): void;
2214
2285
  *
2215
2286
  * @hidden
2216
2287
  */
2217
- declare function invokeEvent(type: string): void;
2288
+ declare function invokeEvent(type: string, params?: MazeyObject): void;
2218
2289
  /**
2219
2290
  * Remove event.
2220
2291
  *
@@ -2230,7 +2301,7 @@ declare function invokeEvent(type: string): void;
2230
2301
  * @param fn
2231
2302
  * @category Event
2232
2303
  */
2233
- declare function removeEvent(type: string, fn: MazeyFn): void;
2304
+ declare function removeEvent(type: string, fn?: MazeyFn): void;
2234
2305
 
2235
2306
  /**
2236
2307
  * EN: Handle Storage (Keep fit for JSON, it can transfer format automatically).
@@ -2503,7 +2574,7 @@ declare function delCookie(name: string): void;
2503
2574
  */
2504
2575
  declare function loadCSS(url: string, options?: {
2505
2576
  id?: string;
2506
- }): Promise<unknown>;
2577
+ }): Promise<string>;
2507
2578
  /**
2508
2579
  * EN: Load a JavaScript file from the server and execute it.
2509
2580
  *
@@ -2590,7 +2661,7 @@ declare function loadScript(url: string, options?: {
2590
2661
  * @returns {Promise<string>} document is loaded? "complete" "load" / "timeout"
2591
2662
  * @category Load
2592
2663
  */
2593
- declare function windowLoaded(timeout?: number): Promise<string | Error>;
2664
+ declare function windowLoaded(timeout?: number): Promise<string>;
2594
2665
  /**
2595
2666
  * Load an image from the given URL.
2596
2667
  *
@@ -2815,7 +2886,6 @@ declare function getTTFB(): Promise<number>;
2815
2886
  * @remarks
2816
2887
  * This function uses the [`PerformanceNavigationTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming) API to get page load time data.
2817
2888
  * The `PerformanceNavigationTiming` API provides more accurate and detailed information about page load time than the deprecated [`PerformanceTiming`](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming) API.
2818
- * If you are using an older browser that does not support `PerformanceNavigationTiming`, you can still use the `PerformanceTiming` API by using the previous version of this library ([`v3.9.7`](https://github.com/chengchuu/mazey/releases/tag/v3.9.7)).
2819
2889
  *
2820
2890
  * Usage:
2821
2891
  *
@@ -2857,7 +2927,7 @@ declare function getTTFB(): Promise<number>;
2857
2927
  * @returns {Promise<object>} 加载数据
2858
2928
  * @category Perf
2859
2929
  */
2860
- declare function getPerformance(camelCase?: boolean): Promise<WebPerformance | Error>;
2930
+ declare function getPerformance(camelCase?: boolean): Promise<WebPerformance>;
2861
2931
 
2862
2932
  /**
2863
2933
  * Detect whether the current browser document provides the minimum
@@ -2886,7 +2956,7 @@ declare function getPerformance(camelCase?: boolean): Promise<WebPerformance | E
2886
2956
  * true
2887
2957
  * ```
2888
2958
  *
2889
- * @environment Browser
2959
+ * @remarks Browser only.
2890
2960
  * @returns Whether the detectable minimum PWA prerequisites are satisfied.
2891
2961
  * @category Browser Information
2892
2962
  */
@@ -2933,7 +3003,7 @@ declare function isSafePWAEnv(): boolean;
2933
3003
  * const isMobileQQ = ["android", "ios"].includes(system) && ["qq_browser", "qq_app"].includes(shell);
2934
3004
  * ```
2935
3005
  *
2936
- * @environment Browser
3006
+ * @remarks Browser only.
2937
3007
  * @returns Browser information
2938
3008
  * @category Browser Information
2939
3009
  */
@@ -2958,7 +3028,7 @@ declare function getBrowserInfo(): BrowserInfo;
2958
3028
  * ["windows", "desktop", "webkit", "chrome"]
2959
3029
  * ```
2960
3030
  *
2961
- * @environment Browser
3031
+ * @remarks Browser only.
2962
3032
  * @param {string} prefix
2963
3033
  * @returns {array} Browser attributes
2964
3034
  * @category Browser Information
@@ -3063,4 +3133,4 @@ declare const mazeyCon: Console;
3063
3133
  */
3064
3134
  declare const timeCon: Console;
3065
3135
 
3066
- export { addClass, addEvent, addStyle, calLongestCommonSubsequence, calLongestCommonSubstring, camelCase2Underscore, camelCaseToKebabCase, cancelBubble, clearHTML, clearHtml, convert10To26, convertCamelToKebab, convertCamelToUnder, convertHttpToHttps, convertKebabToCamel, convertObjectToQuery, convertToHtmlBreaks, convertUnderToCamel, cutCHSString, cutZHString, debounce, deepCopy, deepCopyObject, deepFreeze, delCookie, doFn, fireEvent, floatFixed, floatToPercent, formatDate, formatDurationFromMs, genBrowserAttrs, genCustomConsole, genHashCode, genRndNumString, genStyleString, genUniqueNumString, generateCalendarVersion, generateRndNum, generateUniqueNum, getAllQueryParams, getBrowserInfo, getCLS, getCookie, getCurrentVersion, getDefineListeners, getDomain, getFCP, getFID, getFP, getFileSize, getFriendlyInterval, getHashQueryParam, getLCP, getLocalStorage, getPageMeta, getPerformance, getQueryParam, getScriptQueryParam, getSessionStorage, getTTFB, getUrlFileType, getUrlHost, getUrlParam, getUrlPath, hasClass, inRate, invokeEvent, invokeFn, isArray, isBool, isBoolean, isBrowser, isFunction, isHit, isJSONString, isJsonString, isNonEmptyArray, isNonEmptyObject, isNumber, isPureObject, isSafePWAEnv, isString, isSupportWebp, isSupportedEntryType, isUdfOrNul, isValidData, isValidEmail, isValidHttpUrl, isValidPhoneNumber, isValidUrl, loadCSS, loadImage, loadScript, loadScriptIfUndefined, longestComSubsequence, longestComSubstring, mNow, mTrim, mazeyCon, newLine, onURLChange, removeClass, removeCookie, removeEvent, removeHTML, removeHtml, repeatUntilConditionMet, replaceHttp, sanitizeInput, setClass, setCookie, setImgSizeBySrc, setImgWidHeiBySrc, setLocalStorage, setSessionStorage, sleep, throttle, timeCon, truncateZHString, unsanitize, unsanitizeInput, updateQueryParam, waitTime, windowLoaded, zAxiosIsValidRes };
3136
+ export { addClass, addEvent, addStyle, calLongestCommonSubsequence, calLongestCommonSubstring, camelCase2Underscore, camelCaseToKebabCase, cancelBubble, clearHTML, clearHtml, convert10To26, convertCamelToKebab, convertCamelToUnder, convertHttpToHttps, convertKebabToCamel, convertObjectToQuery, convertToHtmlBreaks, convertUnderToCamel, cutCHSString, cutZHString, debounce, deepCopy, deepCopyObject, deepFreeze, delCookie, doFn, fireEvent, floatFixed, floatToPercent, formatDate, formatDurationFromMs, genBrowserAttrs, genCustomConsole, genHashCode, genRndNumString, genStyleString, genUniqueNumString, generateCalendarVersion, generateRndNum, generateUniqueNum, getAllQueryParams, getBrowserInfo, getCLS, getCookie, getCurrentVersion, getDateDifference, getDefineListeners, getDomain, getFCP, getFID, getFP, getFileSize, getFriendlyInterval, getHashQueryParam, getLCP, getLocalStorage, getPageMeta, getPerformance, getQueryParam, getScriptQueryParam, getSessionStorage, getTTFB, getUrlFileType, getUrlHost, getUrlParam, getUrlPath, hasClass, inRate, invokeEvent, invokeFn, isArray, isBool, isBoolean, isBrowser, isFunction, isHit, isJSONString, isJsonString, isNonEmptyArray, isNonEmptyObject, isNumber, isPureObject, isSafePWAEnv, isString, isSupportWebp, isSupportedEntryType, isUdfOrNul, isValidData, isValidDate, isValidEmail, isValidHttpUrl, isValidPhoneNumber, isValidUrl, loadCSS, loadImage, loadScript, loadScriptIfUndefined, longestComSubsequence, longestComSubstring, mNow, mTrim, mazeyCon, newLine, onURLChange, removeClass, removeCookie, removeEvent, removeHTML, removeHtml, repeatUntilConditionMet, replaceHttp, sanitizeInput, setClass, setCookie, setImgSizeBySrc, setImgWidHeiBySrc, setLocalStorage, setSessionStorage, sleep, throttle, timeCon, truncateZHString, unsanitize, unsanitizeInput, updateQueryParam, waitTime, windowLoaded, zAxiosIsValidRes };