@codady/utils 0.0.38 → 0.0.39
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/CHANGELOG.md +18 -0
- package/dist/utils.cjs.js +472 -23
- package/dist/utils.cjs.min.js +2 -2
- package/dist/utils.esm.js +472 -23
- package/dist/utils.esm.min.js +2 -2
- package/dist/utils.umd.js +472 -23
- package/dist/utils.umd.min.js +2 -2
- package/dist.zip +0 -0
- package/examples/ajax-get.html +59 -0
- package/examples/ajax-hook.html +55 -0
- package/examples/ajax-method.html +36 -0
- package/examples/ajax-post.html +37 -0
- package/examples/buildUrl.html +99 -0
- package/examples/getUrlHash.html +71 -0
- package/modules.js +13 -1
- package/modules.ts +13 -1
- package/package.json +1 -1
- package/src/ajax.js +363 -0
- package/src/ajax.ts +450 -0
- package/src/buildUrl.js +64 -0
- package/src/buildUrl.ts +86 -0
- package/src/capitalize - /345/211/257/346/234/254.js" +19 -0
- package/src/capitalize.js +19 -0
- package/src/capitalize.ts +20 -0
- package/src/cleanQueryString.js +19 -0
- package/src/cleanQueryString.ts +20 -0
- package/src/getBodyHTML.js +53 -0
- package/src/getBodyHTML.ts +61 -0
- package/src/getEl.js +1 -1
- package/src/getEl.ts +6 -5
- package/src/getEls.js +1 -1
- package/src/getEls.ts +5 -5
- package/src/getUrlHash.js +37 -0
- package/src/getUrlHash.ts +39 -0
- package/src/isEmpty.js +24 -23
- package/src/isEmpty.ts +26 -23
- package/src/sliceStrEnd.js +63 -0
- package/src/sliceStrEnd.ts +60 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
All changes to Utils including new features, updates, and removals are documented here.
|
|
4
4
|
|
|
5
|
+
## [v0.0.39] - 2026-1-20
|
|
6
|
+
|
|
7
|
+
### Distribution Files
|
|
8
|
+
* **JS**: https://unpkg.com/@codady/utils@0.0.20/dist/js/utils.js
|
|
9
|
+
* **Zip**:https://unpkg.com/@codady/utils@0.0.20/dist.zip
|
|
10
|
+
|
|
11
|
+
### Changes
|
|
12
|
+
|
|
13
|
+
#### Fixed
|
|
14
|
+
* Null
|
|
15
|
+
|
|
16
|
+
#### Added
|
|
17
|
+
* Added the functions `ajax`/`capitalize`/`buildUrl`/`cleanQueryString`/`getUrlHash`/`getBodyHTML`.新增 `ajax`/`capitalize`/`buildUrl`/`cleanQueryString`/`getUrlHash`/`getBodyHTML`函数。
|
|
18
|
+
|
|
19
|
+
#### Removed
|
|
20
|
+
* Null
|
|
21
|
+
|
|
22
|
+
|
|
5
23
|
## [v0.0.38] - 2026-1-16
|
|
6
24
|
|
|
7
25
|
### Distribution Files
|
package/dist/utils.cjs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
2
|
/*!
|
|
3
|
-
* @since Last modified: 2026-1-16
|
|
3
|
+
* @since Last modified: 2026-1-20 16:40:28
|
|
4
4
|
* @name Utils for web front-end.
|
|
5
5
|
* @version 0.0.38
|
|
6
6
|
* @author AXUI development team <3217728223@qq.com>
|
|
@@ -943,30 +943,31 @@ const isEmpty = (data) => {
|
|
|
943
943
|
let type = getDataType(data), flag;
|
|
944
944
|
if (!data) {
|
|
945
945
|
//0,'',false,undefined,null
|
|
946
|
-
|
|
946
|
+
return true;
|
|
947
947
|
}
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
//[null]|[undefined]|['']|[""]
|
|
951
|
-
//[]|{}
|
|
952
|
-
//Symbol()|Symbol.for()
|
|
953
|
-
//Set,Map
|
|
954
|
-
//Date/Regex
|
|
955
|
-
flag = (type === 'Object') ? (Object.keys(data).length === 0) :
|
|
956
|
-
(type === 'Array') ? data.join('') === '' :
|
|
957
|
-
(type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
|
|
958
|
-
(type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
|
|
959
|
-
(type === 'Set' || type === 'Map') ? data.size === 0 :
|
|
960
|
-
type === 'Date' ? isNaN(data.getTime()) :
|
|
961
|
-
type === 'RegExp' ? data.source === '' :
|
|
962
|
-
type === 'ArrayBuffer' ? data.byteLength === 0 :
|
|
963
|
-
(type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
|
|
964
|
-
('length' in data && typeof data.length === 'number') ? data.length === 0 :
|
|
965
|
-
('size' in data && typeof data.size === 'number') ? data.size === 0 :
|
|
966
|
-
(type === 'Error' || data instanceof Error) ? data.message === '' :
|
|
967
|
-
(type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
|
|
968
|
-
false;
|
|
948
|
+
if (['String', 'Number', 'Boolean'].includes(type)) {
|
|
949
|
+
return false;
|
|
969
950
|
}
|
|
951
|
+
//function(){}|()=>{}
|
|
952
|
+
//[null]|[undefined]|['']|[""]
|
|
953
|
+
//[]|{}
|
|
954
|
+
//Symbol()|Symbol.for()
|
|
955
|
+
//Set,Map
|
|
956
|
+
//Date/Regex
|
|
957
|
+
flag = (type === 'Object') ? (Object.keys(data).length === 0) :
|
|
958
|
+
(type === 'Array') ? data.join('') === '' :
|
|
959
|
+
(type === 'Function') ? (data.toString().replace(/\s+/g, '').match(/{.*}/g)[0] === '{}') :
|
|
960
|
+
(type === 'Symbol') ? (data.toString().replace(/\s+/g, '').match(/\(.*\)/g)[0] === '()') :
|
|
961
|
+
(type === 'Set' || type === 'Map') ? data.size === 0 :
|
|
962
|
+
type === 'Date' ? isNaN(data.getTime()) :
|
|
963
|
+
type === 'RegExp' ? data.source === '' :
|
|
964
|
+
type === 'ArrayBuffer' ? data.byteLength === 0 :
|
|
965
|
+
(type === 'NodeList' || type === 'HTMLCollection') ? data.length === 0 :
|
|
966
|
+
('length' in data && typeof data.length === 'number') ? data.length === 0 :
|
|
967
|
+
('size' in data && typeof data.size === 'number') ? data.size === 0 :
|
|
968
|
+
(type === 'Error' || data instanceof Error) ? data.message === '' :
|
|
969
|
+
(type.includes('Array') && (['Uint8Array', 'Int8Array', 'Uint16Array', 'Int16Array', 'Uint32Array', 'Int32Array', 'Float32Array', 'Float64Array'].includes(type))) ? data.length === 0 :
|
|
970
|
+
false;
|
|
970
971
|
return flag;
|
|
971
972
|
};
|
|
972
973
|
|
|
@@ -1340,6 +1341,448 @@ const decodeHtmlEntities = (text) => {
|
|
|
1340
1341
|
return textArea.value; // Get the decoded string from the text area
|
|
1341
1342
|
};
|
|
1342
1343
|
|
|
1344
|
+
const getBodyHTML = (htmlText, selector) => {
|
|
1345
|
+
// Return early if the input is not a valid string or doesn't look like HTML
|
|
1346
|
+
if (!htmlText || typeof htmlText !== 'string') {
|
|
1347
|
+
return '';
|
|
1348
|
+
}
|
|
1349
|
+
try {
|
|
1350
|
+
|
|
1351
|
+
const parser = new DOMParser(),
|
|
1352
|
+
|
|
1353
|
+
doc = parser.parseFromString(htmlText, 'text/html'),
|
|
1354
|
+
|
|
1355
|
+
bodyContent = doc.body.innerHTML;
|
|
1356
|
+
if (selector) {
|
|
1357
|
+
// Normalize hash: ensure it's a valid ID selector
|
|
1358
|
+
const targetEl = doc.querySelector(selector);
|
|
1359
|
+
if (targetEl) {
|
|
1360
|
+
return targetEl.innerHTML;
|
|
1361
|
+
}
|
|
1362
|
+
// If hash is provided but element not found, we fallback to body or warn
|
|
1363
|
+
console.warn(`Element with selector "${selector}" not found in the HTML.`);
|
|
1364
|
+
}
|
|
1365
|
+
return bodyContent ? bodyContent.trim() : htmlText;
|
|
1366
|
+
}
|
|
1367
|
+
catch (error) {
|
|
1368
|
+
|
|
1369
|
+
console.error("Failed to parse HTML content using DOMParser:", error);
|
|
1370
|
+
return htmlText;
|
|
1371
|
+
}
|
|
1372
|
+
};
|
|
1373
|
+
|
|
1374
|
+
const getUrlHash = (url) => {
|
|
1375
|
+
// Return empty if input is null, undefined, or not a string
|
|
1376
|
+
if (!url || typeof url !== 'string') {
|
|
1377
|
+
return '';
|
|
1378
|
+
}
|
|
1379
|
+
try {
|
|
1380
|
+
|
|
1381
|
+
const baseUrl = window?.location?.origin || 'https://www.axui.cn', urlObj = new URL(url, baseUrl);
|
|
1382
|
+
return urlObj.hash;
|
|
1383
|
+
}
|
|
1384
|
+
catch (error) {
|
|
1385
|
+
|
|
1386
|
+
return '';
|
|
1387
|
+
}
|
|
1388
|
+
};
|
|
1389
|
+
|
|
1390
|
+
const cleanQueryString = (data) => {
|
|
1391
|
+
return typeof data === 'string' && (data.startsWith('?') || data.startsWith('&'))
|
|
1392
|
+
? data.slice(1) // Remove the leading '?' or '&'
|
|
1393
|
+
: data; // Return the string as-is if no leading character is present
|
|
1394
|
+
};
|
|
1395
|
+
|
|
1396
|
+
const buildUrl = ({ url, data, cacheBustKey = '_t', appendCacheBust = true }) => {
|
|
1397
|
+
// 1. Extract and remove the hash (e.g., /page#section -> hash="#section")
|
|
1398
|
+
const hashIndex = url.indexOf('#');
|
|
1399
|
+
let hash = '', pureUrl = url;
|
|
1400
|
+
// If a hash exists, separate it from the base URL
|
|
1401
|
+
if (hashIndex !== -1) {
|
|
1402
|
+
hash = url.slice(hashIndex);
|
|
1403
|
+
pureUrl = url.slice(0, hashIndex);
|
|
1404
|
+
}
|
|
1405
|
+
// 2. Use the URL object to handle the base URL and existing query parameters.
|
|
1406
|
+
// `window.location.origin` ensures the support for relative paths (e.g., '/api/list').
|
|
1407
|
+
const urlObj = new URL(pureUrl, window.location.origin);
|
|
1408
|
+
// 3. Append business data (query parameters) to the URL if data is not empty
|
|
1409
|
+
if (!isEmpty(data)) {
|
|
1410
|
+
let params, dataType = getDataType(data);
|
|
1411
|
+
// If the data is a URLSearchParams object, directly use it
|
|
1412
|
+
if (dataType === 'URLSearchParams') {
|
|
1413
|
+
params = data;
|
|
1414
|
+
}
|
|
1415
|
+
else if (dataType === 'object') {
|
|
1416
|
+
// If the data is an object, convert it to URLSearchParams
|
|
1417
|
+
params = new URLSearchParams(data);
|
|
1418
|
+
}
|
|
1419
|
+
else {
|
|
1420
|
+
// If the data is a string, clean it up (remove leading '?' or '&')
|
|
1421
|
+
params = new URLSearchParams(cleanQueryString(data));
|
|
1422
|
+
}
|
|
1423
|
+
// Append new parameters to the existing URL search parameters
|
|
1424
|
+
params.forEach((value, key) => {
|
|
1425
|
+
urlObj.searchParams.append(key, value);
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
// 4. Optionally add the cache-busting parameter if the flag is set
|
|
1429
|
+
appendCacheBust && cacheBustKey && urlObj.searchParams.set(cacheBustKey, Date.now().toString());
|
|
1430
|
+
// 5. Return the final URL: base URL + query parameters + original hash (if any)
|
|
1431
|
+
return urlObj.toString() + hash;
|
|
1432
|
+
};
|
|
1433
|
+
|
|
1434
|
+
const capitalize = (str) => {
|
|
1435
|
+
// Check if the input string is empty or undefined
|
|
1436
|
+
if (!str)
|
|
1437
|
+
return str;
|
|
1438
|
+
// Capitalize the first letter and return the new string
|
|
1439
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
1440
|
+
};
|
|
1441
|
+
|
|
1442
|
+
const ajax = (options) => {
|
|
1443
|
+
// Validation
|
|
1444
|
+
if (isEmpty(options)) {
|
|
1445
|
+
return Promise.reject(new Error('Options are required'));
|
|
1446
|
+
}
|
|
1447
|
+
if (!options.url || typeof options.url !== 'string') {
|
|
1448
|
+
return Promise.reject(new Error('URL is required and must be a string'));
|
|
1449
|
+
}
|
|
1450
|
+
// Default configuration
|
|
1451
|
+
const config = {
|
|
1452
|
+
url: '',
|
|
1453
|
+
method: 'POST',
|
|
1454
|
+
async: true,
|
|
1455
|
+
selector: '',
|
|
1456
|
+
data: null,
|
|
1457
|
+
timeout: 3600000,
|
|
1458
|
+
headers: {},
|
|
1459
|
+
responseType: '',
|
|
1460
|
+
catchError: false,
|
|
1461
|
+
signal: null,
|
|
1462
|
+
xhrFields: {},
|
|
1463
|
+
cacheBustKey: '_t',
|
|
1464
|
+
//
|
|
1465
|
+
onAbort: null,
|
|
1466
|
+
onTimeout: null,
|
|
1467
|
+
//
|
|
1468
|
+
onBeforeSend: null,
|
|
1469
|
+
//
|
|
1470
|
+
onCreated: null,
|
|
1471
|
+
onOpened: null,
|
|
1472
|
+
onHeadersReceived: null,
|
|
1473
|
+
onLoading: null,
|
|
1474
|
+
//
|
|
1475
|
+
onSuccess: null,
|
|
1476
|
+
onFailure: null,
|
|
1477
|
+
onInformation: null,
|
|
1478
|
+
onRedirection: null,
|
|
1479
|
+
onClientError: null,
|
|
1480
|
+
onServerError: null,
|
|
1481
|
+
onUnknownError: null,
|
|
1482
|
+
onError: null,
|
|
1483
|
+
onFinish: null,
|
|
1484
|
+
//
|
|
1485
|
+
onDownload: null,
|
|
1486
|
+
onUpload: null,
|
|
1487
|
+
onComplete: null,
|
|
1488
|
+
};
|
|
1489
|
+
//合并参数
|
|
1490
|
+
Object.assign(config, options);
|
|
1491
|
+
//
|
|
1492
|
+
const method = config.method.toUpperCase() || 'POST', methodsWithoutBody = ['GET', 'HEAD', 'TRACE'];
|
|
1493
|
+
//创建XMLHttpRequest
|
|
1494
|
+
let xhr = new XMLHttpRequest(),
|
|
1495
|
+
//设置发送数据和预设请求头
|
|
1496
|
+
requestData = null, headerContentType = config?.headers?.['Content-Type'] || config?.headers?.['content-type'], removeHeader = () => {
|
|
1497
|
+
if (headerContentType) {
|
|
1498
|
+
delete config.headers['Content-Type'];
|
|
1499
|
+
delete config.headers['content-type'];
|
|
1500
|
+
}
|
|
1501
|
+
};
|
|
1502
|
+
if (!isEmpty(config.data)) {
|
|
1503
|
+
let dataType = getDataType(config.data);
|
|
1504
|
+
if (dataType === 'FormData') {
|
|
1505
|
+
//如果是new FormData格式,直接相等
|
|
1506
|
+
requestData = config.data;
|
|
1507
|
+
// 不需要手动设置Content-Type,浏览器会自动设置
|
|
1508
|
+
//config.contType = 'multipart/form-data';
|
|
1509
|
+
removeHeader();
|
|
1510
|
+
}
|
|
1511
|
+
else if (dataType === 'Object') {
|
|
1512
|
+
//如果是对象格式{name:'',age:''}
|
|
1513
|
+
//并且此时已经设置了contType
|
|
1514
|
+
if (!headerContentType) {
|
|
1515
|
+
//如果未设置则默认设为如下contType
|
|
1516
|
+
//Content-Type=application/x-www-form-urlencoded
|
|
1517
|
+
|
|
1518
|
+
requestData = new URLSearchParams(config.data).toString();
|
|
1519
|
+
//URLSearchParams.toString => `a=1&b=3`
|
|
1520
|
+
//非get、head方法修正content-type
|
|
1521
|
+
if (!methodsWithoutBody.includes(method)) {
|
|
1522
|
+
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
else if (headerContentType?.includes('application/json')) {
|
|
1526
|
+
//Content-Type=application/json或contentType=application/json
|
|
1527
|
+
requestData = JSON.stringify(config.data);
|
|
1528
|
+
}
|
|
1529
|
+
else {
|
|
1530
|
+
requestData = config.data;
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
else if (dataType === 'String') {
|
|
1534
|
+
//未设置或,已经设置了Content-Type=application/x-www-form-urlencoded
|
|
1535
|
+
if (!headerContentType || headerContentType.includes('urlencoded')) {
|
|
1536
|
+
//如果是name=''&age=''字符串
|
|
1537
|
+
//?name=''&age=''或&name=''&age=''统一去掉第一个&/?
|
|
1538
|
+
requestData = cleanQueryString(config.data.trim());
|
|
1539
|
+
//非get、head方法修正content-type
|
|
1540
|
+
if (!methodsWithoutBody.includes(method) && !headerContentType) {
|
|
1541
|
+
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
else {
|
|
1545
|
+
requestData = config.data;
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
else {
|
|
1549
|
+
requestData = config.data;
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
//设置超时时间
|
|
1553
|
+
xhr.timeout = config.timeout;
|
|
1554
|
+
// 响应类型
|
|
1555
|
+
if (config.responseType) {
|
|
1556
|
+
xhr.responseType = config.responseType;
|
|
1557
|
+
}
|
|
1558
|
+
//返回promise
|
|
1559
|
+
const result = new Promise((resolve, reject) => {
|
|
1560
|
+
//超时监听
|
|
1561
|
+
const timeoutHandler = () => {
|
|
1562
|
+
cleanup();
|
|
1563
|
+
let resp = { ...context, status: xhr.status, content: xhr.response, type: 'timeout' };
|
|
1564
|
+
//回调,status和content在此确认
|
|
1565
|
+
config?.onTimeout?.(resp);
|
|
1566
|
+
//reject只能接受一个参数
|
|
1567
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
1568
|
+
},
|
|
1569
|
+
//报错监听
|
|
1570
|
+
errorHandler = (resp) => {
|
|
1571
|
+
//这几个错误来自xhr.onreadystatechange
|
|
1572
|
+
if (resp.type === 'client-error') {
|
|
1573
|
+
config?.onClientError?.({ ...context });
|
|
1574
|
+
}
|
|
1575
|
+
else if (resp.type === 'server-error') {
|
|
1576
|
+
config?.onServerError?.({ ...context });
|
|
1577
|
+
}
|
|
1578
|
+
else if (resp.type === 'unknown-error') {
|
|
1579
|
+
config?.onUnknownError?.({ ...context });
|
|
1580
|
+
}
|
|
1581
|
+
//此外还会有xhr.onerror的错误,所以需要统一使用onError监听
|
|
1582
|
+
config?.onError?.(resp);
|
|
1583
|
+
//reject只能接受一个参数
|
|
1584
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
1585
|
+
},
|
|
1586
|
+
//取消监听
|
|
1587
|
+
abortHandler = () => {
|
|
1588
|
+
cleanup();
|
|
1589
|
+
const resp = { ...context, status: xhr.status, type: 'abort' };
|
|
1590
|
+
config.catchError ? reject(resp) : resolve(resp);
|
|
1591
|
+
//回调,status和content在此确认
|
|
1592
|
+
config?.onAbort?.(resp);
|
|
1593
|
+
}, abortHandlerWithSignal = () => {
|
|
1594
|
+
//先中止请求,防止触发其他 readystate 事件
|
|
1595
|
+
xhr.abort();
|
|
1596
|
+
abortHandler();
|
|
1597
|
+
},
|
|
1598
|
+
//成功监听
|
|
1599
|
+
successHandler = (resp) => {
|
|
1600
|
+
//成功回调
|
|
1601
|
+
config?.onSuccess?.(resp);
|
|
1602
|
+
//resolve只能接受一个参数
|
|
1603
|
+
resolve(resp);
|
|
1604
|
+
},
|
|
1605
|
+
//统一处理abort
|
|
1606
|
+
cleanup = () => {
|
|
1607
|
+
// 如果使用了AbortSignal,则移除它的事件监听器
|
|
1608
|
+
config.signal && config.signal.removeEventListener('abort', abortHandlerWithSignal);
|
|
1609
|
+
// 移除各类事件监听器
|
|
1610
|
+
config.onError && xhr.removeEventListener('error', errorHandler);
|
|
1611
|
+
config.onTimeout && xhr.removeEventListener('timeout', timeoutHandler);
|
|
1612
|
+
// 解绑上传/下载进度事件
|
|
1613
|
+
config.onUpload && xhr.upload.removeEventListener('progress', uploadProgressHandler);
|
|
1614
|
+
config.onDownload && xhr.removeEventListener('progress', downloadProgressHandler);
|
|
1615
|
+
//销毁
|
|
1616
|
+
xhr.onreadystatechange = null;
|
|
1617
|
+
},
|
|
1618
|
+
// Context object to track state
|
|
1619
|
+
context = {
|
|
1620
|
+
//原始xhr
|
|
1621
|
+
xhr,
|
|
1622
|
+
//发送的数据
|
|
1623
|
+
data: requestData,
|
|
1624
|
+
//可取消的函数
|
|
1625
|
+
abort: abortHandler,
|
|
1626
|
+
//xhr.status
|
|
1627
|
+
status: '',
|
|
1628
|
+
//响应的内容
|
|
1629
|
+
content: null,
|
|
1630
|
+
//0~4阶段编号
|
|
1631
|
+
stage: 0,
|
|
1632
|
+
//阶段名称
|
|
1633
|
+
type: 'unset',
|
|
1634
|
+
//上传和下载进度
|
|
1635
|
+
progress: {}
|
|
1636
|
+
},
|
|
1637
|
+
//定义进度函数
|
|
1638
|
+
progressHandler = (name, data, callback) => {
|
|
1639
|
+
if (data.lengthComputable) {
|
|
1640
|
+
const resp = { ...context, status: xhr.status }, ratio = data.loaded / data.total;
|
|
1641
|
+
resp.progress = {
|
|
1642
|
+
name,
|
|
1643
|
+
loaded: data.loaded,
|
|
1644
|
+
total: data.total,
|
|
1645
|
+
timestamp: (new Date(data.timeStamp)).getTime(),
|
|
1646
|
+
ratio,
|
|
1647
|
+
percent: Math.round(ratio * 100),
|
|
1648
|
+
};
|
|
1649
|
+
callback?.(resp);
|
|
1650
|
+
//到达100%执行complete
|
|
1651
|
+
if (resp.progress.percent >= 100) {
|
|
1652
|
+
resp.progress.percent = 100;
|
|
1653
|
+
config?.onComplete?.(resp);
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
}, uploadProgressHandler = (data) => {
|
|
1657
|
+
progressHandler('upload', data, (resp) => config.onUpload(resp));
|
|
1658
|
+
}, downloadProgressHandler = (data) => {
|
|
1659
|
+
progressHandler('download', data, (resp) => config.onDownload(resp));
|
|
1660
|
+
};
|
|
1661
|
+
//使用AbortSignal
|
|
1662
|
+
if (config.signal) {
|
|
1663
|
+
if (config.signal.aborted)
|
|
1664
|
+
return abortHandlerWithSignal();
|
|
1665
|
+
config.signal.addEventListener('abort', abortHandlerWithSignal);
|
|
1666
|
+
}
|
|
1667
|
+
//监听上传进度
|
|
1668
|
+
config.onUpload && xhr.upload.addEventListener('progress', uploadProgressHandler);
|
|
1669
|
+
//监听下载进度
|
|
1670
|
+
config.onDownload && xhr.addEventListener('progress', downloadProgressHandler);
|
|
1671
|
+
// 事件监听器
|
|
1672
|
+
config.onError && xhr.addEventListener('error', errorHandler);
|
|
1673
|
+
config.onTimeout && xhr.addEventListener('timeout', timeoutHandler);
|
|
1674
|
+
config.onAbort && xhr.addEventListener('abort', abortHandler);
|
|
1675
|
+
// 手动触发 Created 状态
|
|
1676
|
+
config.onCreated?.({ ...context, type: 'created' });
|
|
1677
|
+
//状态判断
|
|
1678
|
+
xhr.onreadystatechange = function () {
|
|
1679
|
+
context.stage = xhr.readyState;
|
|
1680
|
+
context.status = xhr.status;
|
|
1681
|
+
const statusMap = { 1: 'opened', 2: 'headersReceived', 3: 'loading' };
|
|
1682
|
+
//0=created放在外侧确保能触发,如果放在.onreadystatechange可能触发不了
|
|
1683
|
+
if (xhr.readyState < 4) {
|
|
1684
|
+
if (!xhr.readyState)
|
|
1685
|
+
return;
|
|
1686
|
+
context.type = statusMap[xhr.readyState];
|
|
1687
|
+
config[`on${capitalize(context.type)}`]?.({ ...context });
|
|
1688
|
+
return;
|
|
1689
|
+
}
|
|
1690
|
+
//已经请求成功,不会有timeout事件,也不需要abort了,所以移除abort事件
|
|
1691
|
+
cleanup();
|
|
1692
|
+
const isInformation = xhr.status >= 100 && xhr.status < 200, isSuccess = (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304, isRedirection = xhr.status >= 300 && xhr.status < 400, isClientError = xhr.status >= 400 && xhr.status < 500, isServerError = xhr.status >= 500 && xhr.status < 600;
|
|
1693
|
+
//已经获得返回数据
|
|
1694
|
+
if (isSuccess) {
|
|
1695
|
+
if (!config.responseType || xhr.responseType === 'text') {
|
|
1696
|
+
//可能返回字符串类型的对象,wordpress的REST API
|
|
1697
|
+
let trim = xhr.responseText.trim(), content = '';
|
|
1698
|
+
if ((trim.startsWith('[') && trim.endsWith(']')) || (trim.startsWith('{') && trim.endsWith('}'))) {
|
|
1699
|
+
//通过判断开头字符是{或[来确定异步页面是否是JSON内容,如果是则转成JSON对象
|
|
1700
|
+
try {
|
|
1701
|
+
content = JSON.parse(trim);
|
|
1702
|
+
}
|
|
1703
|
+
catch {
|
|
1704
|
+
console.warn('Malformed JSON detected, falling back to text.');
|
|
1705
|
+
content = xhr.responseText;
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
else if (/(<\/html>|<\/body>)/i.test(trim)) {
|
|
1709
|
+
//请求了一个HTML页面
|
|
1710
|
+
//返回文本类型DOMstring
|
|
1711
|
+
let urlHash = getUrlHash(config.url);
|
|
1712
|
+
content = getBodyHTML(trim, config.selector || urlHash);
|
|
1713
|
+
}
|
|
1714
|
+
else {
|
|
1715
|
+
//普通文本,不做任何处理
|
|
1716
|
+
content = xhr.responseText;
|
|
1717
|
+
}
|
|
1718
|
+
//content=文本字符串/json
|
|
1719
|
+
context.content = content;
|
|
1720
|
+
}
|
|
1721
|
+
else {
|
|
1722
|
+
//content=json、blob、document、arraybuffer等类型,如果知道服务器返回的XML, xhr.responseType应该为document
|
|
1723
|
+
context.content = xhr.response;
|
|
1724
|
+
}
|
|
1725
|
+
context.type = 'success';
|
|
1726
|
+
successHandler({ ...context });
|
|
1727
|
+
}
|
|
1728
|
+
else {
|
|
1729
|
+
//失败回调
|
|
1730
|
+
context.content = xhr.response;
|
|
1731
|
+
context.type = isInformation ? 'infomation' : isRedirection ? 'redirection' : isClientError ? 'client-error' : isServerError ? 'server-error' : 'unknown-error';
|
|
1732
|
+
//
|
|
1733
|
+
if (isInformation) {
|
|
1734
|
+
config?.onInformation?.({ ...context });
|
|
1735
|
+
}
|
|
1736
|
+
else if (isRedirection) {
|
|
1737
|
+
config?.onRedirection?.({ ...context });
|
|
1738
|
+
}
|
|
1739
|
+
else {
|
|
1740
|
+
errorHandler({ ...context });
|
|
1741
|
+
}
|
|
1742
|
+
//
|
|
1743
|
+
config?.onFailure?.({ ...context });
|
|
1744
|
+
}
|
|
1745
|
+
config?.onFinish?.({ ...context });
|
|
1746
|
+
};
|
|
1747
|
+
//发送异步请求
|
|
1748
|
+
let openParams = [method, config.url, config.async];
|
|
1749
|
+
if (methodsWithoutBody.includes(method)) {
|
|
1750
|
+
// 拼接url => xxx.com?a=0&b=1#hello
|
|
1751
|
+
const url = buildUrl({
|
|
1752
|
+
url: config.url,
|
|
1753
|
+
data: requestData,
|
|
1754
|
+
cacheBustKey: config.cacheBustKey,
|
|
1755
|
+
appendCacheBust: true,
|
|
1756
|
+
});
|
|
1757
|
+
openParams = [method, url, config.async];
|
|
1758
|
+
}
|
|
1759
|
+
//设置xhr其他字段
|
|
1760
|
+
for (let k in config.xhrFields) {
|
|
1761
|
+
config.xhrFields.hasOwnProperty(k) && (xhr[k] = config.xhrFields[k]);
|
|
1762
|
+
}
|
|
1763
|
+
//与服务器建立连接
|
|
1764
|
+
xhr.open(...openParams);
|
|
1765
|
+
//有则设置,仅跳过空内容
|
|
1766
|
+
for (let k in config.headers) {
|
|
1767
|
+
config.headers.hasOwnProperty(k) && !isEmpty(config.headers[k]) && xhr.setRequestHeader(k, config.headers[k]);
|
|
1768
|
+
}
|
|
1769
|
+
config?.onBeforeSend?.(({ ...context, status: xhr.status, type: 'beforeSend' }));
|
|
1770
|
+
//发送请求,get和head不需要发送数据
|
|
1771
|
+
xhr.send(methodsWithoutBody.includes(method) ? null : (requestData || null));
|
|
1772
|
+
//open和send阶段已经是异步了,无法使用try+catch捕获错误
|
|
1773
|
+
});
|
|
1774
|
+
//绑定xhr和abort
|
|
1775
|
+
result.xhr = xhr;
|
|
1776
|
+
result.abort = () => xhr.abort();
|
|
1777
|
+
return result;
|
|
1778
|
+
};
|
|
1779
|
+
// Static Helper Methods
|
|
1780
|
+
//get、head、trace是不需要发送数据的,data将被转为url参数处理
|
|
1781
|
+
['post', 'put', 'delete', 'patch', 'options', 'get', 'head', 'trace'].forEach(method => {
|
|
1782
|
+
ajax[method] = (url, data, options = { url: '' }) => ajax({ ...options, method, url, data });
|
|
1783
|
+
});
|
|
1784
|
+
ajax.all = (requests) => Promise.all(requests.map(ajax));
|
|
1785
|
+
|
|
1343
1786
|
const utils = {
|
|
1344
1787
|
//executeStr,
|
|
1345
1788
|
getDataType,
|
|
@@ -1383,6 +1826,12 @@ const utils = {
|
|
|
1383
1826
|
escapeHTML,
|
|
1384
1827
|
toSingleLine,
|
|
1385
1828
|
renderTpl,
|
|
1829
|
+
getBodyHTML,
|
|
1830
|
+
getUrlHash,
|
|
1831
|
+
buildUrl,
|
|
1832
|
+
ajax,
|
|
1833
|
+
capitalize,
|
|
1834
|
+
cleanQueryString,
|
|
1386
1835
|
};
|
|
1387
1836
|
|
|
1388
1837
|
module.exports = utils;
|