@wxhccc/es-util 1.5.1 → 1.7.0
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/README.md +22 -0
- package/dist/event-target-emitter.d.ts +45 -0
- package/dist/event-target-emitter.js +126 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.esm.js +236 -18
- package/dist/index.js +240 -17
- package/dist/index.min.js +3 -3
- package/dist/object-array.d.ts +6 -8
- package/dist/object-array.js +19 -9
- package/dist/optional.d.ts +8 -3
- package/dist/page-communicate.d.ts +27 -0
- package/dist/page-communicate.js +70 -0
- package/dist/promise.js +2 -2
- package/dist/types.d.ts +4 -0
- package/dist/validate.js +2 -2
- package/dist/value-string-switch/index.d.ts +1 -0
- package/dist/value-string-switch/mask-data.d.ts +22 -0
- package/dist/value-string-switch.js +47 -2
- package/package.json +5 -5
- package/types/array-tree-switch.d.ts +0 -49
- package/types/index.d.ts +0 -6
- package/types/object-array.d.ts +0 -33
- package/types/optional.d.ts +0 -45
- package/types/promise.d.ts +0 -44
- package/types/validate.d.ts +0 -2
- package/types/value-string-switch/byte-string.d.ts +0 -12
- package/types/value-string-switch/index.d.ts +0 -1
package/README.md
CHANGED
|
@@ -439,5 +439,27 @@ wrap promise or a function return promise with lock method to control UI or forb
|
|
|
439
439
|
|
|
440
440
|
an plugin object for vue
|
|
441
441
|
|
|
442
|
+
|
|
443
|
+
## event-target-emitter module
|
|
444
|
+
|
|
445
|
+
> v1.7.0 add
|
|
446
|
+
|
|
447
|
+
### `eventTargetEmitter(options)`
|
|
448
|
+
|
|
449
|
+
return an emitter instance with `on`, `off` and some other methods to handle with EventTarget
|
|
450
|
+
|
|
451
|
+
**parameters:**
|
|
452
|
+
- **options** {ConfigOptions}
|
|
453
|
+
- **name** {string} the name of current emitter. can used to limit message received from
|
|
454
|
+
- **customHanlderCreator** {(watchers) => Function} custome handler creator, you can handle message distribute logic as you want.
|
|
455
|
+
|
|
456
|
+
## event-target-emitter module
|
|
457
|
+
|
|
458
|
+
> v1.7.0 add
|
|
459
|
+
|
|
460
|
+
### `pageCommunicate(options)`
|
|
461
|
+
|
|
462
|
+
return an instance which can used to communicate between same-origin pages, powered by `eventTargetEmitter`
|
|
463
|
+
|
|
442
464
|
## License
|
|
443
465
|
MIT
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { AnyFunction } from "./types";
|
|
2
|
+
export interface EventPayload<T = any> {
|
|
3
|
+
/** method name to be listenered */
|
|
4
|
+
method: string;
|
|
5
|
+
/** carry data */
|
|
6
|
+
data?: T;
|
|
7
|
+
/** where the event emit from */
|
|
8
|
+
originEmitterName?: string;
|
|
9
|
+
/** which emitter can recived the event */
|
|
10
|
+
targetEmitterName?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare type WatchersMap = Map<string | symbol, Set<AnyFunction>>;
|
|
13
|
+
export interface ConfigOptions {
|
|
14
|
+
/** the name of current emitter */
|
|
15
|
+
name?: string;
|
|
16
|
+
/** creator to return custom event handler */
|
|
17
|
+
customHanlderCreator?: (watchers: WatchersMap) => <T = any>(payload: EventPayload<T>) => void;
|
|
18
|
+
}
|
|
19
|
+
export interface BindOptions {
|
|
20
|
+
/** 限制消息来源 */
|
|
21
|
+
limitFrom?: string;
|
|
22
|
+
/** 事件所在命名空间 */
|
|
23
|
+
namespace?: string;
|
|
24
|
+
}
|
|
25
|
+
export declare const NOMETHOD: symbol;
|
|
26
|
+
/**
|
|
27
|
+
* 创建emitter形式的实例,可以通过实例封装事件对象,比如websocket,得到一个更便捷的方法,具体可参考page-communicate.js文件内容
|
|
28
|
+
* @param options 配置项
|
|
29
|
+
* @returns
|
|
30
|
+
*/
|
|
31
|
+
export declare function eventTargetEmitter(options?: ConfigOptions): {
|
|
32
|
+
name: string | undefined;
|
|
33
|
+
rootEventListener: <T = any>(payload: EventPayload<T>) => void;
|
|
34
|
+
on: <T_1>(method: string | symbol, listener: (data: T_1) => any, options?: BindOptions | undefined) => void;
|
|
35
|
+
off: (method: string | symbol, callback?: AnyFunction<any> | undefined, options?: BindOptions | undefined) => void;
|
|
36
|
+
emit: (methodOrPayload: string | EventPayload<any>, data?: any, target?: string | undefined) => void;
|
|
37
|
+
createPayload: (methodOrPayload: string | EventPayload, data?: any, target?: string | undefined) => EventPayload<any>;
|
|
38
|
+
removeAllListeners: () => void;
|
|
39
|
+
getMethodNames: {
|
|
40
|
+
(all?: false | undefined): string[];
|
|
41
|
+
(all: true): string[][];
|
|
42
|
+
};
|
|
43
|
+
getListeners: (method: string | symbol, options?: BindOptions | undefined) => AnyFunction<any>[];
|
|
44
|
+
};
|
|
45
|
+
export default eventTargetEmitter;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* @wxhccc/es-util v1.7.0
|
|
3
|
+
* (c) 2022 wxhccc
|
|
4
|
+
* @license MIT
|
|
5
|
+
*/
|
|
6
|
+
'use strict';
|
|
7
|
+
|
|
8
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
9
|
+
|
|
10
|
+
const isStr = (val) => typeof val === 'string';
|
|
11
|
+
const NOMETHOD = Symbol('NOMETHOD');
|
|
12
|
+
/**
|
|
13
|
+
* 创建emitter形式的实例,可以通过实例封装事件对象,比如websocket,得到一个更便捷的方法,具体可参考page-communicate.js文件内容
|
|
14
|
+
* @param options 配置项
|
|
15
|
+
* @returns
|
|
16
|
+
*/
|
|
17
|
+
function eventTargetEmitter(options) {
|
|
18
|
+
const watchers = new Map([[NOMETHOD, new Set()]]);
|
|
19
|
+
const { name: currentName, customHanlderCreator } = options || {};
|
|
20
|
+
const customHanlder = customHanlderCreator instanceof Function ? customHanlderCreator(watchers) : null;
|
|
21
|
+
const splitRegExp = /\|-[a-z]+-\|/;
|
|
22
|
+
const listenerSafeRun = (listener, ...args) => {
|
|
23
|
+
try {
|
|
24
|
+
listener(...args);
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
console.error(e);
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const defaultHanlder = (payload) => {
|
|
31
|
+
const { method, data, originEmitterName: from, targetEmitterName: to } = payload || [];
|
|
32
|
+
if (method && typeof method === 'string') {
|
|
33
|
+
const matchListeners = [];
|
|
34
|
+
watchers.forEach((value, key) => {
|
|
35
|
+
if (typeof key === 'string' && key.startsWith(method)) {
|
|
36
|
+
const [, eFrom,] = key.split(splitRegExp);
|
|
37
|
+
if (!eFrom || !from || eFrom === from) {
|
|
38
|
+
matchListeners.push(...value);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
if (matchListeners.length && (!currentName || !to || currentName === to)) {
|
|
43
|
+
matchListeners.forEach(listener => listenerSafeRun(listener, data));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const noMethodListeners = watchers.get(NOMETHOD);
|
|
47
|
+
if (noMethodListeners) {
|
|
48
|
+
noMethodListeners.forEach(listener => listenerSafeRun(listener, data, payload));
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
const rootEventListener = customHanlder instanceof Function ? customHanlder : defaultHanlder;
|
|
52
|
+
const getFullMethodName = (method, options) => {
|
|
53
|
+
const { limitFrom = '', namespace = '' } = options || {};
|
|
54
|
+
return (limitFrom || namespace) && typeof method === 'string' ? `${method}|-from-|${limitFrom}|-ns-|${namespace}` : method;
|
|
55
|
+
};
|
|
56
|
+
const on = (method, listener, options) => {
|
|
57
|
+
if (typeof method === 'symbol' && method !== NOMETHOD) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const trueMethod = getFullMethodName(method, options);
|
|
61
|
+
if (!watchers.has(trueMethod)) {
|
|
62
|
+
watchers.set(trueMethod, new Set());
|
|
63
|
+
}
|
|
64
|
+
const listeners = watchers.get(trueMethod);
|
|
65
|
+
listeners?.add(listener);
|
|
66
|
+
};
|
|
67
|
+
const off = (method, callback, options) => {
|
|
68
|
+
if (typeof method === 'symbol' && method !== NOMETHOD) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const { limitFrom, namespace } = options || {};
|
|
72
|
+
if (namespace && !method) {
|
|
73
|
+
watchers.forEach((_value, key) => {
|
|
74
|
+
if (typeof key === 'string' && key.endsWith(namespace)) {
|
|
75
|
+
watchers.delete(key);
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const trueMethod = getFullMethodName(method, options);
|
|
81
|
+
if (!callback) {
|
|
82
|
+
watchers.delete(trueMethod);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
watchers.get(trueMethod)?.delete(callback);
|
|
86
|
+
};
|
|
87
|
+
const removeAllListeners = () => {
|
|
88
|
+
watchers.clear();
|
|
89
|
+
};
|
|
90
|
+
const createPayload = (methodOrPayload, data, target) => {
|
|
91
|
+
return isStr(methodOrPayload) ? {
|
|
92
|
+
method: methodOrPayload,
|
|
93
|
+
data,
|
|
94
|
+
...(target && isStr(target) ? { targetEmitterName: target } : {}),
|
|
95
|
+
...(currentName && isStr(currentName) ? { originEmitterName: currentName } : {})
|
|
96
|
+
} : methodOrPayload;
|
|
97
|
+
};
|
|
98
|
+
const emit = (...args) => {
|
|
99
|
+
const payload = createPayload(...args);
|
|
100
|
+
rootEventListener(payload);
|
|
101
|
+
};
|
|
102
|
+
/** 获取当前所有监听方法的方法名,默认仅返回函数名,设置all为true可以返回具体来源限制和命名空间字段 */
|
|
103
|
+
const getMethodNames = (all) => {
|
|
104
|
+
if (!all) {
|
|
105
|
+
const result = [];
|
|
106
|
+
watchers.forEach((_v, key) => isStr(key) && result.push(key.split(splitRegExp)));
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
const result = [];
|
|
110
|
+
watchers.forEach((_v, key) => isStr(key) && result.push(key));
|
|
111
|
+
return result;
|
|
112
|
+
};
|
|
113
|
+
const getListeners = (method, options) => {
|
|
114
|
+
if (typeof method === 'symbol') {
|
|
115
|
+
return method === NOMETHOD ? Array.from(watchers.get(NOMETHOD) || []) : [];
|
|
116
|
+
}
|
|
117
|
+
const trueMethod = getFullMethodName(method, options);
|
|
118
|
+
const listeners = watchers.get(trueMethod);
|
|
119
|
+
return listeners ? Array.from(listeners) : [];
|
|
120
|
+
};
|
|
121
|
+
return { name: currentName, rootEventListener, on, off, emit, createPayload, removeAllListeners, getMethodNames, getListeners };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
exports.NOMETHOD = NOMETHOD;
|
|
125
|
+
exports.default = eventTargetEmitter;
|
|
126
|
+
exports.eventTargetEmitter = eventTargetEmitter;
|
package/dist/index.d.ts
CHANGED
package/dist/index.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*!
|
|
2
|
-
* @wxhccc/es-util v1.
|
|
3
|
-
* (c)
|
|
2
|
+
* @wxhccc/es-util v1.7.0
|
|
3
|
+
* (c) 2022 wxhccc
|
|
4
4
|
* @license MIT
|
|
5
5
|
*/
|
|
6
6
|
const { hasOwnProperty: hasOwnProperty$1 } = Object.prototype;
|
|
@@ -18,13 +18,14 @@ function createNode(children, value = []) {
|
|
|
18
18
|
* @param {boolean | string} parentRefKey parent reference key of node
|
|
19
19
|
*/
|
|
20
20
|
function array2tree(array, options = {}) {
|
|
21
|
-
const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } =
|
|
21
|
+
const { primaryKey: id, parentKey: pid, childrenKey: children, createRoot, parentRefKey } = {
|
|
22
22
|
primaryKey: 'id',
|
|
23
23
|
parentKey: 'pid',
|
|
24
24
|
childrenKey: 'children',
|
|
25
25
|
createRoot: false,
|
|
26
|
-
parentRefKey: false
|
|
27
|
-
|
|
26
|
+
parentRefKey: false,
|
|
27
|
+
...options
|
|
28
|
+
};
|
|
28
29
|
const pRefKey = parentRefKey && (typeof parentRefKey === 'string' ? parentRefKey : '_parent');
|
|
29
30
|
let nodeMap = {};
|
|
30
31
|
let treeNodes = [];
|
|
@@ -33,7 +34,7 @@ function array2tree(array, options = {}) {
|
|
|
33
34
|
hasOwnProperty$1.call(nodeMap, item[pid]) && nodeMap[item[pid]][children].push(Object.assign(nodeMap[item[id]], pRefKey ? { [pRefKey]: nodeMap[item[pid]] } : {}));
|
|
34
35
|
!item[pid] && treeNodes.push(nodeMap[item[id]]);
|
|
35
36
|
});
|
|
36
|
-
if (
|
|
37
|
+
if (createRoot instanceof Function) {
|
|
37
38
|
return createRoot(treeNodes);
|
|
38
39
|
}
|
|
39
40
|
else if (createRoot) {
|
|
@@ -150,7 +151,7 @@ function formulaValidate(string, variables) {
|
|
|
150
151
|
}
|
|
151
152
|
|
|
152
153
|
function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
|
|
153
|
-
|
|
154
|
+
const result = {};
|
|
154
155
|
Array.isArray(objectArray) && keyProp && valueProp
|
|
155
156
|
&& [keyProp, valueProp].every(val => ['string', 'function'].includes(typeof val))
|
|
156
157
|
&& objectArray.forEach((item, index) => {
|
|
@@ -160,15 +161,24 @@ function mapToObject(objectArray, keyProp = 'key', valueProp = 'value') {
|
|
|
160
161
|
});
|
|
161
162
|
return result;
|
|
162
163
|
}
|
|
164
|
+
const isObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]';
|
|
165
|
+
/**
|
|
166
|
+
* checkout values form object as an array
|
|
167
|
+
*
|
|
168
|
+
* @param {Object} object
|
|
169
|
+
* @param {string[] | Object} keys
|
|
170
|
+
* @param {string} valueProp
|
|
171
|
+
*/
|
|
163
172
|
function checkoutBy(object, keys, mergeFn) {
|
|
164
|
-
if (!(object
|
|
173
|
+
if (!isObject(object)) {
|
|
165
174
|
return [];
|
|
175
|
+
}
|
|
166
176
|
if (Array.isArray(keys)) {
|
|
167
|
-
return keys.map(item =>
|
|
177
|
+
return keys.map(item => object[item]);
|
|
168
178
|
}
|
|
169
|
-
else if (keys && keys
|
|
170
|
-
return Object.keys(keys).map(item => (object[item]
|
|
171
|
-
? (mergeFn ? mergeFn({}, object[item], keys[item]) : Object.assign({}, object[item], keys[item]))
|
|
179
|
+
else if (keys && isObject(keys)) {
|
|
180
|
+
return Object.keys(keys).map(item => (isObject(object[item]) && isObject(keys[item]))
|
|
181
|
+
? (mergeFn ? mergeFn({}, (object)[item], (keys)[item]) : Object.assign({}, object[item], keys[item]))
|
|
172
182
|
: (keys[item] || object[item]));
|
|
173
183
|
}
|
|
174
184
|
return Object.values(object);
|
|
@@ -180,8 +190,9 @@ function checkoutBy(object, keys, mergeFn) {
|
|
|
180
190
|
* @param {Object} keysMap
|
|
181
191
|
*/
|
|
182
192
|
function pickRenameKeys(object, keysMap) {
|
|
183
|
-
if (!object || !(object
|
|
193
|
+
if (!object || !isObject(object) || !keysMap || !isObject(keysMap)) {
|
|
184
194
|
return;
|
|
195
|
+
}
|
|
185
196
|
let result = {};
|
|
186
197
|
for (let i in object) {
|
|
187
198
|
(i in keysMap) && (result[keysMap[i]] = object[i]);
|
|
@@ -249,6 +260,50 @@ function byteStringify(byteNum, options) {
|
|
|
249
260
|
function byteParse(byteStr, options = {}) {
|
|
250
261
|
}
|
|
251
262
|
|
|
263
|
+
const modeIndexs = {
|
|
264
|
+
telphone: { startCharIndex: -8, endCharIndex: -5 },
|
|
265
|
+
idcard: { startCharIndex: -12, endCharIndex: -5 }
|
|
266
|
+
};
|
|
267
|
+
/**
|
|
268
|
+
* 对给定的字符串进行脱敏处理
|
|
269
|
+
* @param data 需要处理的字符串
|
|
270
|
+
* @param options 配置参数对象
|
|
271
|
+
* @returns
|
|
272
|
+
*/
|
|
273
|
+
function maskData(data, options) {
|
|
274
|
+
if (typeof data !== 'string' || !data) {
|
|
275
|
+
return '';
|
|
276
|
+
}
|
|
277
|
+
const modeOpts = options && options.mode && modeIndexs[options.mode] ? modeIndexs[options.mode] : {};
|
|
278
|
+
const { maskWith, startCharIndex: start = 0, endCharIndex: end, startFrom, endUntil } = { maskWith: '*', ...modeOpts, ...options };
|
|
279
|
+
let handleData = data;
|
|
280
|
+
let beforeChars = '';
|
|
281
|
+
let afterChars = '';
|
|
282
|
+
const startFromIndex = startFrom ? data.indexOf(startFrom) : -1;
|
|
283
|
+
if (startFromIndex > -1) {
|
|
284
|
+
const index = startFromIndex + startFrom.length;
|
|
285
|
+
handleData = handleData.slice(index);
|
|
286
|
+
beforeChars = data.slice(0, index);
|
|
287
|
+
}
|
|
288
|
+
const endUtilIndex = endUntil ? data.lastIndexOf(endUntil) : -1;
|
|
289
|
+
if (endUtilIndex > -1) {
|
|
290
|
+
handleData = handleData.slice(0, endUtilIndex);
|
|
291
|
+
afterChars = data.slice(endUtilIndex);
|
|
292
|
+
}
|
|
293
|
+
const chars = handleData.split('');
|
|
294
|
+
const newChars = [beforeChars];
|
|
295
|
+
const charLen = chars.length;
|
|
296
|
+
const indexs = [start >= 0 ? start : charLen + start, end !== undefined ? (end >= 0 ? end : charLen + end) : charLen - 1];
|
|
297
|
+
let [startIdx, endIdx] = indexs;
|
|
298
|
+
endIdx = endIdx > 0 && endIdx < charLen ? endIdx : charLen - 1;
|
|
299
|
+
startIdx = startIdx >= 0 && startIdx <= endIdx ? startIdx : 0;
|
|
300
|
+
chars.forEach((char, idx) => {
|
|
301
|
+
newChars.push(idx >= startIdx && idx <= endIdx ? maskWith : char);
|
|
302
|
+
});
|
|
303
|
+
newChars.push(afterChars);
|
|
304
|
+
return newChars.join('');
|
|
305
|
+
}
|
|
306
|
+
|
|
252
307
|
const { hasOwnProperty, toString: toString$1 } = Object.prototype;
|
|
253
308
|
const objType = (val) => {
|
|
254
309
|
const typeKeys = toString$1.call(val).match(/^\[object (.*)\]$/);
|
|
@@ -473,7 +528,7 @@ const switchNullToUndefined = (data) => {
|
|
|
473
528
|
* 将搜素条件里的数组字段转换为其他格式,通常用于搜索表单的字段转换
|
|
474
529
|
* @param formData 传入参数
|
|
475
530
|
* @param maps 转换的映射关系,eg:{ date: ['startTime', 'endTime'] }
|
|
476
|
-
* @param
|
|
531
|
+
* @param options 额外的配置参数
|
|
477
532
|
*/
|
|
478
533
|
const formParamsSwitch = (formData, maps, options) => {
|
|
479
534
|
const dateKeys = Object.keys(maps);
|
|
@@ -495,10 +550,10 @@ const formParamsSwitch = (formData, maps, options) => {
|
|
|
495
550
|
const { filterNullable: filterNullableValue, dateFormat } = { filterNullable: true, ...options };
|
|
496
551
|
const handleData = accessKeys.reduce((acc, key) => {
|
|
497
552
|
const values = dateData[key];
|
|
498
|
-
|
|
553
|
+
const mapValue = maps[key];
|
|
554
|
+
if (!values || !mapValue) {
|
|
499
555
|
return acc;
|
|
500
556
|
}
|
|
501
|
-
const mapValue = maps[key];
|
|
502
557
|
// 数组合并操作/取最后一位操作
|
|
503
558
|
if (mapValue === 'join' || mapValue === 'pop') {
|
|
504
559
|
if (Array.isArray(values) && values.length) {
|
|
@@ -523,6 +578,169 @@ const formParamsSwitch = (formData, maps, options) => {
|
|
|
523
578
|
...handleData
|
|
524
579
|
};
|
|
525
580
|
return filterNullableValue ? filterNullable(result) : result;
|
|
526
|
-
};
|
|
581
|
+
};
|
|
582
|
+
/** 创建一个绑定了默认时间格式转换函数的formParamsSwitch函数 */
|
|
583
|
+
const formParamsSwitchCreator = (dateFormat) => (formData, maps, options) => formParamsSwitch(formData, maps, { dateFormat, ...options });
|
|
584
|
+
|
|
585
|
+
const isStr = (val) => typeof val === 'string';
|
|
586
|
+
const NOMETHOD = Symbol('NOMETHOD');
|
|
587
|
+
/**
|
|
588
|
+
* 创建emitter形式的实例,可以通过实例封装事件对象,比如websocket,得到一个更便捷的方法,具体可参考page-communicate.js文件内容
|
|
589
|
+
* @param options 配置项
|
|
590
|
+
* @returns
|
|
591
|
+
*/
|
|
592
|
+
function eventTargetEmitter(options) {
|
|
593
|
+
const watchers = new Map([[NOMETHOD, new Set()]]);
|
|
594
|
+
const { name: currentName, customHanlderCreator } = options || {};
|
|
595
|
+
const customHanlder = customHanlderCreator instanceof Function ? customHanlderCreator(watchers) : null;
|
|
596
|
+
const splitRegExp = /\|-[a-z]+-\|/;
|
|
597
|
+
const listenerSafeRun = (listener, ...args) => {
|
|
598
|
+
try {
|
|
599
|
+
listener(...args);
|
|
600
|
+
}
|
|
601
|
+
catch (e) {
|
|
602
|
+
console.error(e);
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
const defaultHanlder = (payload) => {
|
|
606
|
+
const { method, data, originEmitterName: from, targetEmitterName: to } = payload || [];
|
|
607
|
+
if (method && typeof method === 'string') {
|
|
608
|
+
const matchListeners = [];
|
|
609
|
+
watchers.forEach((value, key) => {
|
|
610
|
+
if (typeof key === 'string' && key.startsWith(method)) {
|
|
611
|
+
const [, eFrom,] = key.split(splitRegExp);
|
|
612
|
+
if (!eFrom || !from || eFrom === from) {
|
|
613
|
+
matchListeners.push(...value);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
});
|
|
617
|
+
if (matchListeners.length && (!currentName || !to || currentName === to)) {
|
|
618
|
+
matchListeners.forEach(listener => listenerSafeRun(listener, data));
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
const noMethodListeners = watchers.get(NOMETHOD);
|
|
622
|
+
if (noMethodListeners) {
|
|
623
|
+
noMethodListeners.forEach(listener => listenerSafeRun(listener, data, payload));
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
const rootEventListener = customHanlder instanceof Function ? customHanlder : defaultHanlder;
|
|
627
|
+
const getFullMethodName = (method, options) => {
|
|
628
|
+
const { limitFrom = '', namespace = '' } = options || {};
|
|
629
|
+
return (limitFrom || namespace) && typeof method === 'string' ? `${method}|-from-|${limitFrom}|-ns-|${namespace}` : method;
|
|
630
|
+
};
|
|
631
|
+
const on = (method, listener, options) => {
|
|
632
|
+
if (typeof method === 'symbol' && method !== NOMETHOD) {
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
const trueMethod = getFullMethodName(method, options);
|
|
636
|
+
if (!watchers.has(trueMethod)) {
|
|
637
|
+
watchers.set(trueMethod, new Set());
|
|
638
|
+
}
|
|
639
|
+
const listeners = watchers.get(trueMethod);
|
|
640
|
+
listeners?.add(listener);
|
|
641
|
+
};
|
|
642
|
+
const off = (method, callback, options) => {
|
|
643
|
+
if (typeof method === 'symbol' && method !== NOMETHOD) {
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
const { limitFrom, namespace } = options || {};
|
|
647
|
+
if (namespace && !method) {
|
|
648
|
+
watchers.forEach((_value, key) => {
|
|
649
|
+
if (typeof key === 'string' && key.endsWith(namespace)) {
|
|
650
|
+
watchers.delete(key);
|
|
651
|
+
}
|
|
652
|
+
});
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
const trueMethod = getFullMethodName(method, options);
|
|
656
|
+
if (!callback) {
|
|
657
|
+
watchers.delete(trueMethod);
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
watchers.get(trueMethod)?.delete(callback);
|
|
661
|
+
};
|
|
662
|
+
const removeAllListeners = () => {
|
|
663
|
+
watchers.clear();
|
|
664
|
+
};
|
|
665
|
+
const createPayload = (methodOrPayload, data, target) => {
|
|
666
|
+
return isStr(methodOrPayload) ? {
|
|
667
|
+
method: methodOrPayload,
|
|
668
|
+
data,
|
|
669
|
+
...(target && isStr(target) ? { targetEmitterName: target } : {}),
|
|
670
|
+
...(currentName && isStr(currentName) ? { originEmitterName: currentName } : {})
|
|
671
|
+
} : methodOrPayload;
|
|
672
|
+
};
|
|
673
|
+
const emit = (...args) => {
|
|
674
|
+
const payload = createPayload(...args);
|
|
675
|
+
rootEventListener(payload);
|
|
676
|
+
};
|
|
677
|
+
/** 获取当前所有监听方法的方法名,默认仅返回函数名,设置all为true可以返回具体来源限制和命名空间字段 */
|
|
678
|
+
const getMethodNames = (all) => {
|
|
679
|
+
if (!all) {
|
|
680
|
+
const result = [];
|
|
681
|
+
watchers.forEach((_v, key) => isStr(key) && result.push(key.split(splitRegExp)));
|
|
682
|
+
return result;
|
|
683
|
+
}
|
|
684
|
+
const result = [];
|
|
685
|
+
watchers.forEach((_v, key) => isStr(key) && result.push(key));
|
|
686
|
+
return result;
|
|
687
|
+
};
|
|
688
|
+
const getListeners = (method, options) => {
|
|
689
|
+
if (typeof method === 'symbol') {
|
|
690
|
+
return method === NOMETHOD ? Array.from(watchers.get(NOMETHOD) || []) : [];
|
|
691
|
+
}
|
|
692
|
+
const trueMethod = getFullMethodName(method, options);
|
|
693
|
+
const listeners = watchers.get(trueMethod);
|
|
694
|
+
return listeners ? Array.from(listeners) : [];
|
|
695
|
+
};
|
|
696
|
+
return { name: currentName, rootEventListener, on, off, emit, createPayload, removeAllListeners, getMethodNames, getListeners };
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/**
|
|
700
|
+
* 创建同源页面之间通信的封装实例,默认使用BroadcastChannel实现,在不支持的浏览器环境中会使用localstorage实现
|
|
701
|
+
* @param options 配置对象
|
|
702
|
+
* @returns
|
|
703
|
+
*/
|
|
704
|
+
function pageCommunicate(options) {
|
|
705
|
+
const { messageHanlder, currentPage } = options || {};
|
|
706
|
+
const { emit, on, off, createPayload, removeAllListeners } = eventTargetEmitter({ name: currentPage, customHanlderCreator: messageHanlder });
|
|
707
|
+
const onMessage = (event) => emit(event.data);
|
|
708
|
+
let bc;
|
|
709
|
+
const ls = window.localStorage;
|
|
710
|
+
const channelName = 'PAGE_COMMUNICATE_CHANNEL';
|
|
711
|
+
if (typeof BroadcastChannel !== undefined) {
|
|
712
|
+
bc = new BroadcastChannel(channelName);
|
|
713
|
+
bc.addEventListener('message', onMessage);
|
|
714
|
+
}
|
|
715
|
+
else {
|
|
716
|
+
const onStorageMessage = () => {
|
|
717
|
+
const payload = safeJsonParse(ls.getItem(channelName) || '');
|
|
718
|
+
if (payload) {
|
|
719
|
+
emit(payload);
|
|
720
|
+
}
|
|
721
|
+
};
|
|
722
|
+
window.addEventListener('storage', onStorageMessage);
|
|
723
|
+
}
|
|
724
|
+
const send = (...args) => {
|
|
725
|
+
const payload = createPayload(...args);
|
|
726
|
+
if (bc) {
|
|
727
|
+
bc.postMessage(payload);
|
|
728
|
+
}
|
|
729
|
+
else {
|
|
730
|
+
const payloadWitchTs = JSON.stringify({ ...payload, ts: +new Date() });
|
|
731
|
+
ls.setItem(channelName, payloadWitchTs);
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
const destory = () => {
|
|
735
|
+
removeAllListeners();
|
|
736
|
+
if (bc) {
|
|
737
|
+
bc.close();
|
|
738
|
+
}
|
|
739
|
+
else {
|
|
740
|
+
ls.removeItem(channelName);
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
return { on, off, send, destory };
|
|
744
|
+
}
|
|
527
745
|
|
|
528
|
-
export { ChinaIdCardValid, array2tree, awaitWrapper, byteParse, byteStringify, checkoutBy, filterNullable, formParamsSwitch, formulaValidate, isNullable, mapToObject, objType, pickRenameKeys, safeJsonParse, switchNullToUndefined, tree2array, wp, wpVuePlugin };
|
|
746
|
+
export { ChinaIdCardValid, NOMETHOD, array2tree, awaitWrapper, byteParse, byteStringify, checkoutBy, eventTargetEmitter, filterNullable, formParamsSwitch, formParamsSwitchCreator, formulaValidate, isNullable, mapToObject, maskData, objType, pageCommunicate, pickRenameKeys, safeJsonParse, switchNullToUndefined, tree2array, wp, wpVuePlugin };
|