gis-common 4.2.4 → 4.2.5

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.
@@ -165,580 +165,268 @@ class Cookie {
165
165
  }
166
166
  }
167
167
  }
168
- const MathUtils = {
169
- DEG2RAD: Math.PI / 180,
170
- RAD2DEG: 180 / Math.PI,
171
- randInt(low, high) {
172
- return low + Math.floor(Math.random() * (high - low + 1));
168
+ const CommUtils = {
169
+ /**
170
+ * 获取数据类型
171
+ *
172
+ * @param data 待判断的数据
173
+ * @returns 返回数据类型字符串
174
+ */
175
+ getDataType(data) {
176
+ return Object.prototype.toString.call(data).slice(8, -1);
173
177
  },
174
- randFloat(low, high) {
175
- return low + Math.random() * (high - low);
178
+ asArray(obj) {
179
+ return this.isEmpty(obj) ? [] : Array.isArray(obj) ? obj : [obj];
180
+ },
181
+ asNumber(a) {
182
+ return Number.isNaN(Number(a)) ? 0 : Number(a);
176
183
  },
177
184
  /**
178
- * 角度转弧度
185
+ * 将值转换为字符串
179
186
  *
180
- * @param {*} degrees
181
- * @returns {*}
187
+ * @param value 要转换的值
188
+ * @returns 转换后的字符串,如果值为空,则返回空字符串
182
189
  */
183
- deg2Rad(degrees) {
184
- return degrees * this.DEG2RAD;
190
+ asString(value) {
191
+ if (this.isEmpty(value)) {
192
+ return "";
193
+ } else {
194
+ switch (this.getDataType(value)) {
195
+ case "Object":
196
+ case "Array":
197
+ return JSON.stringify(value);
198
+ default:
199
+ return value;
200
+ }
201
+ }
185
202
  },
186
203
  /**
187
- * 弧度转角度
204
+ * 判断传入的值是否为空
188
205
  *
189
- * @param {*} radians
190
- * @returns {*}
206
+ * @param value 待判断的值
207
+ * @returns 返回布尔值,表示是否为空
191
208
  */
192
- rad2Deg(radians) {
193
- return radians * this.RAD2DEG;
209
+ isEmpty(value) {
210
+ if (value == null) {
211
+ return true;
212
+ }
213
+ const type = this.getDataType(value);
214
+ switch (type) {
215
+ case "String":
216
+ return value.trim() === "";
217
+ case "Array":
218
+ return !value.length;
219
+ case "Object":
220
+ return !Object.keys(value).length;
221
+ case "Boolean":
222
+ return !value;
223
+ default:
224
+ return false;
225
+ }
194
226
  },
195
- round(value, n = 2) {
196
- return Math.round(value * Math.pow(10, n)) / Math.pow(10, n);
227
+ /**
228
+ * 将JSON对象转换为FormData对象
229
+ *
230
+ * @param json 待转换的JSON对象,其属性值为字符串或Blob类型
231
+ * @returns 转换后的FormData对象
232
+ */
233
+ json2form(json) {
234
+ const formData = new FormData();
235
+ Object.keys(json).forEach((key) => {
236
+ formData.append(key, json[key] instanceof Object ? JSON.stringify(json[key]) : json[key]);
237
+ });
238
+ return formData;
197
239
  },
198
240
  /**
199
- * 将数值限制在指定范围内
241
+ * 生成GUID
200
242
  *
201
- * @param val 需要限制的数值
202
- * @param min 最小值
203
- * @param max 最大值
204
- * @returns 返回限制后的数值
243
+ * @returns 返回一个由8个16进制数组成的GUID字符串
205
244
  */
206
- clamp(val, min, max) {
207
- return Math.min(Math.max(val, min), max);
208
- }
209
- };
210
- class CanvasDrawer {
211
- constructor(el) {
212
- __publicField(this, "context", null);
213
- if (typeof el === "string") {
214
- el = document.querySelector("#" + el);
215
- if (!el) {
216
- throw new Error("Element not found");
245
+ guid() {
246
+ const S4 = function() {
247
+ return ((1 + Math.random()) * 65536 | 0).toString(16).substring(1);
248
+ };
249
+ return S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4();
250
+ },
251
+ /**
252
+ * 将参数进行解码并返回解码后的字符串
253
+ *
254
+ * @param args 参数
255
+ * @returns 解码后的字符串
256
+ */
257
+ decodeDict(...args) {
258
+ let res = "";
259
+ if (args.length > 1) {
260
+ const items = args.slice(1, args.length % 2 === 0 ? args.length - 1 : args.length);
261
+ for (let i = 0; i < items.length; i = i + 2) {
262
+ const item = items[i];
263
+ if (args[0] === item) {
264
+ res = items[i + 1];
265
+ }
217
266
  }
218
- }
219
- if (el instanceof HTMLElement) {
220
- const canvas = el;
221
- if (canvas.getContext) {
222
- this.context = canvas.getContext("2d");
223
- } else {
224
- throw new Error("getContext is not available on this element");
267
+ if (!res && args.length % 2 === 0) {
268
+ res = args[args.length - 1];
225
269
  }
226
270
  } else {
227
- throw new Error("Element is not an HTMLElement");
271
+ res = args[0];
228
272
  }
229
- }
273
+ return res;
274
+ },
230
275
  /**
231
- * 绘制线条
276
+ * 将一个或多个对象的所有可枚举属性复制到目标对象。
232
277
  *
233
- * @param start 起始坐标点
234
- * @param end 终止坐标点
235
- * @param options 绘制选项,包括线条宽度和颜色
236
- * @throws 当画布上下文不存在时抛出错误
278
+ * @param dest 目标对象,用于接收复制的属性。
279
+ * @param args 一个或多个源对象,用于提供要复制的属性。
280
+ * @returns 返回目标对象,包含所有复制的属性。
237
281
  */
238
- drawLine({ x: startX, y: startY }, { x: endX, y: endY }, options = {}) {
239
- if (!this.context) {
240
- throw new Error("Canvas context is null or undefined");
282
+ extend(dest, ...args) {
283
+ let i, j, len, src;
284
+ for (j = 0, len = args.length; j < len; j++) {
285
+ src = args[j];
286
+ for (i in src) {
287
+ dest[i] = src[i];
288
+ }
241
289
  }
242
- this.context.beginPath();
243
- const width = options.width || 1;
244
- const color = options.color || "#000";
245
- this.context.lineWidth = width;
246
- this.context.strokeStyle = color;
247
- this.context.moveTo(startX, startY);
248
- this.context.lineTo(endX, endY);
249
- this.context.stroke();
250
- }
290
+ return dest;
291
+ },
251
292
  /**
252
- * 绘制圆弧
293
+ * 将扁平化数组转换为树形结构数组
253
294
  *
254
- * @param x 圆心x坐标
255
- * @param y 圆心y坐标
256
- * @param radius 半径
257
- * @param startAngle 起始角度(度)
258
- * @param endAngle 结束角度(度)
259
- * @param anticlockwise 是否逆时针绘制
260
- * @param isFill 是否填充
261
- * @param bgColor 背景颜色
262
- * @throws 当Canvas context为null或undefined时抛出错误
295
+ * @param data 扁平化数组
296
+ * @param idPropertyName 数据中标识id的字段名,默认为'id'
297
+ * @param parentIdPropertyName 数据中标识父节点id的字段名,默认为'parentId'
298
+ * @param childrenPropertyName 树形结构中标识子节点的字段名,默认为'children'
299
+ * @returns 转换后的树形结构数组
263
300
  */
264
- drawArc({ x, y }, radius, startAngle, endAngle, anticlockwise, isFill, bgColor) {
265
- if (!this.context) {
266
- throw new Error("Canvas context is null or undefined");
267
- }
268
- if (isFill) {
269
- this.context.fillStyle = bgColor;
270
- this.context.beginPath();
271
- this.context.arc(x, y, radius, MathUtils.deg2Rad(startAngle), MathUtils.deg2Rad(endAngle), anticlockwise);
272
- this.context.fill();
273
- } else {
274
- this.context.strokeStyle = bgColor;
275
- this.context.beginPath();
276
- this.context.arc(x, y, radius, MathUtils.deg2Rad(startAngle), MathUtils.deg2Rad(endAngle), anticlockwise);
277
- this.context.stroke();
278
- }
279
- }
280
- static createCanvas(width = 1, height = 1) {
281
- const canvas = document.createElement("canvas");
282
- if (width) {
283
- canvas.width = width;
284
- }
285
- if (height) {
286
- canvas.height = height;
287
- }
288
- return canvas;
289
- }
290
- }
291
- class EventDispatcher {
292
- constructor() {
293
- __publicField(this, "_listeners");
294
- __publicField(this, "_mutex", {});
295
- __publicField(this, "_context");
296
- }
297
- addEventListener(type, listener, context, mutexStatus) {
298
- if (this._listeners === void 0) this._listeners = {};
299
- this._context = context;
300
- const mutex = this._mutex;
301
- const listeners = this._listeners;
302
- if (listeners[type] === void 0) {
303
- listeners[type] = [];
304
- }
305
- if (listeners[type].indexOf(listener) === -1) {
306
- if (mutexStatus) {
307
- mutex[type] = listener;
301
+ convertToTree2(data, idPropertyName = "id", parentIdPropertyName = "parentId", childrenPropertyName = "children") {
302
+ const result = [];
303
+ function buildChildren(item) {
304
+ const children = data.filter((item2) => item2[parentIdPropertyName] === item[idPropertyName]).map((child) => {
305
+ if (!result.some((r) => r[idPropertyName] === child[idPropertyName])) {
306
+ buildChildren(child);
307
+ }
308
+ return child;
309
+ });
310
+ if (children.length > 0) {
311
+ item[childrenPropertyName] = children;
308
312
  }
309
- listeners[type].push(listener);
310
- }
311
- return this;
312
- }
313
- hasEventListener(type, listener) {
314
- if (this._listeners === null || this._listeners === void 0) return false;
315
- const listeners = this._listeners;
316
- return listeners[type] !== void 0 && listeners[type].indexOf(listener) !== -1;
317
- }
318
- removeEventListener(type, listener) {
319
- if (this._listeners === void 0) return;
320
- const listeners = this._listeners;
321
- const listenerArray = listeners[type];
322
- if (this._mutex[type] === listener) {
323
- this._mutex[type] = null;
324
313
  }
325
- if (listenerArray !== void 0) {
326
- const index = listenerArray.map((d) => d.toString()).indexOf(listener.toString());
327
- if (index !== -1) {
328
- listenerArray.splice(index, 1);
314
+ data.forEach((item) => {
315
+ if (!data.some((other) => other[parentIdPropertyName] === item[idPropertyName])) {
316
+ buildChildren(item);
317
+ result.push(item);
329
318
  }
330
- }
331
- }
332
- dispatchEvent(event) {
333
- if (this._listeners === void 0) return;
334
- const listeners = this._listeners;
335
- const listenerArray = listeners[event.type];
336
- if (listenerArray !== void 0) {
337
- event.target = this;
338
- const array = listenerArray.slice(0);
339
- if (this._mutex[event.type] !== void 0) {
340
- const find = array.find((item) => item === this._mutex[event.type]);
341
- if (find) {
342
- find.call(this._context || this, event);
343
- return;
344
- }
345
- }
346
- for (let i = 0, l = array.length; i < l; i++) {
347
- const item = array[i];
348
- if (typeof item === "function") {
349
- item.call(this._context || this, event);
350
- }
351
- }
352
- }
353
- }
354
- removeAllListener() {
355
- this._mutex = {};
356
- for (const key in this._listeners) {
357
- this._listeners[key] = [];
358
- }
359
- }
360
- }
361
- class HashMap extends Map {
362
- isEmpty() {
363
- return this.size === 0;
364
- }
365
- _values() {
366
- return Array.from(this.values());
367
- }
368
- _keys() {
369
- return Array.from(this.keys());
370
- }
371
- _entries() {
372
- return Array.from(this.entries());
373
- }
374
- fromEntries() {
375
- }
376
- }
377
- HashMap.prototype.fromEntries = function(array = []) {
378
- const hashMap = new HashMap();
379
- array.forEach((element) => {
380
- if (Array.isArray(element) && element.length === 2) {
381
- hashMap.set(element[0], element[1]);
382
- }
383
- });
384
- return hashMap;
385
- };
386
- class WebSocketClient extends EventDispatcher {
387
- constructor(url = "ws://127.0.0.1:10088") {
388
- super();
389
- __publicField(this, "maxCheckTimes", 10);
390
- __publicField(this, "url");
391
- __publicField(this, "checkTimes", 0);
392
- __publicField(this, "connectStatus", false);
393
- __publicField(this, "client", null);
394
- this.maxCheckTimes = 10;
395
- this.url = url;
396
- this.checkTimes = 0;
397
- this.connect();
398
- this.connCheckStatus(this.maxCheckTimes);
399
- }
400
- connect() {
401
- this.disconnect();
402
- if (this.url) {
319
+ });
320
+ return result;
321
+ },
322
+ /**
323
+ * 异步加载script
324
+ *
325
+ * @param {*} url
326
+ */
327
+ asyncLoadScript(url) {
328
+ return new Promise((resolve, reject) => {
403
329
  try {
404
- console.info("创建ws连接>>>" + this.url);
405
- this.client = new WebSocket(this.url);
406
- if (this.client) {
407
- const self = this;
408
- this.client.onopen = function(message) {
409
- self.dispatchEvent({
410
- type: EventType.WEB_SOCKET_CONNECT,
411
- message
412
- });
330
+ const oscript = document.createElement("script");
331
+ oscript.type = "text/javascript";
332
+ oscript.src = url;
333
+ if ("readyState" in oscript) {
334
+ oscript.onreadystatechange = function() {
335
+ if (oscript.readyState === "complete" || oscript.readyState === "loaded") {
336
+ resolve(oscript);
337
+ }
413
338
  };
414
- this.client.onmessage = function(message) {
415
- self.connectStatus = true;
416
- self.dispatchEvent({
417
- type: EventType.WEB_SOCKET_MESSAGE,
418
- message
419
- });
339
+ } else {
340
+ oscript.onload = function() {
341
+ resolve(oscript);
420
342
  };
421
- this.client.onclose = function(message) {
422
- self.dispatchEvent({
423
- type: EventType.WEB_SOCKET_CLOSE,
424
- message
425
- });
343
+ oscript.onerror = function() {
344
+ reject(new Error("Script failed to load for URL: " + url));
426
345
  };
427
- if (this.checkTimes === this.maxCheckTimes) {
428
- this.client.onerror = function(message) {
429
- self.dispatchEvent({
430
- type: EventType.WEB_SOCKET_ERROR,
431
- message
432
- });
433
- };
434
- }
435
346
  }
436
- } catch (ex) {
437
- console.error("创建ws连接失败" + this.url + ":" + ex);
438
- }
439
- }
440
- }
441
- disconnect() {
442
- if (this.client) {
443
- try {
444
- console.log("ws断开连接" + this.url);
445
- this.client.close();
446
- this.client = null;
447
- } catch (ex) {
448
- this.client = null;
449
- }
450
- }
451
- }
452
- connCheckStatus(times) {
453
- if (this.checkTimes > times) return;
454
- setTimeout(() => {
455
- this.checkTimes++;
456
- if (this.client && this.client.readyState !== 0 && this.client.readyState !== 1) {
457
- this.connect();
458
- }
459
- this.connCheckStatus(times);
460
- }, 2e3);
461
- }
462
- send(message) {
463
- if (this.client && this.client.readyState === 1) {
464
- this.client.send(message);
465
- return true;
466
- }
467
- console.error(this.url + "消息发送失败:" + message);
468
- return false;
469
- }
470
- heartbeat() {
471
- setTimeout(() => {
472
- if (this.client && this.client.readyState === 1) {
473
- this.send("HeartBeat");
347
+ document.body.appendChild(oscript);
348
+ } catch (error) {
349
+ reject(error);
474
350
  }
475
- console.log("HeartBeat," + this.url);
476
- setTimeout(this.heartbeat, 3e4);
477
- }, 1e3);
478
- }
479
- }
480
- const CommUtil = {
351
+ });
352
+ },
481
353
  /**
482
- * 获取数据类型
354
+ * 加载样式文件
483
355
  *
484
- * @param data 待判断的数据
485
- * @returns 返回数据类型字符串
356
+ * @param urls 样式文件URL数组
357
+ * @returns 无返回值
486
358
  */
487
- getDataType(data) {
488
- return Object.prototype.toString.call(data).slice(8, -1);
489
- },
490
- asArray(obj) {
491
- return this.isEmpty(obj) ? [] : Array.isArray(obj) ? obj : [obj];
359
+ loadStyle(urls) {
360
+ urls.forEach((url) => {
361
+ const css = document.createElement("link");
362
+ css.href = url;
363
+ css.rel = "stylesheet";
364
+ css.type = "text/css";
365
+ css.onerror = function() {
366
+ console.error(`Style loading failed for URL: ${url}`);
367
+ };
368
+ document.head.appendChild(css);
369
+ });
492
370
  },
493
- asNumber(a) {
494
- return Number.isNaN(Number(a)) ? 0 : Number(a);
371
+ /**
372
+ * 将模板字符串中的占位符替换为给定对象中的值
373
+ *
374
+ * @param str 模板字符串
375
+ * @param data 包含替换值的对象
376
+ * @returns 替换后的字符串
377
+ * @throws 当对象中没有找到与占位符对应的值时,抛出错误
378
+ */
379
+ template(str, data) {
380
+ const templateRe = /\{ *([\w_-]+) *\}/g;
381
+ return str.replace(templateRe, (match, key) => {
382
+ const value = data[key];
383
+ if (value === void 0) {
384
+ throw new Error(`${ErrorType.JSON_VALUE_ERROR}: ${match}`);
385
+ } else if (typeof value === "function") {
386
+ return value(data);
387
+ } else {
388
+ return value;
389
+ }
390
+ });
495
391
  },
496
392
  /**
497
- * 将值转换为字符串
393
+ * 删除对象中所有值为空的属性
498
394
  *
499
- * @param value 要转换的值
500
- * @returns 转换后的字符串,如果值为空,则返回空字符串
395
+ * @param data 待处理的对象
396
+ * @returns 返回处理后的对象
501
397
  */
502
- asString(value) {
503
- if (this.isEmpty(value)) {
504
- return "";
505
- } else {
506
- switch (this.getDataType(value)) {
507
- case "Object":
508
- case "Array":
509
- return JSON.stringify(value);
510
- default:
511
- return value;
398
+ deleteEmptyProperty(data) {
399
+ return Object.fromEntries(
400
+ Object.keys(data).filter((d) => !this.isEmpty(data[d])).map((i) => [i, data[i]])
401
+ );
402
+ },
403
+ deepAssign(target, ...sources) {
404
+ if (typeof target !== "object" || target === null) {
405
+ target = {};
406
+ }
407
+ for (const source of sources) {
408
+ if (typeof source === "object" && source !== null) {
409
+ for (const key in source) {
410
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
411
+ if (typeof source[key] === "object" && source[key] !== null) {
412
+ if (!target[key]) {
413
+ target[key] = Array.isArray(source[key]) ? [] : {};
414
+ }
415
+ this.deepAssign(target[key], source[key]);
416
+ } else {
417
+ target[key] = source[key];
418
+ }
419
+ }
420
+ }
512
421
  }
513
422
  }
423
+ return target;
514
424
  },
515
425
  /**
516
- * 判断传入的值是否为空
426
+ * 复制文本到剪贴板
517
427
  *
518
- * @param value 待判断的值
519
- * @returns 返回布尔值,表示是否为空
520
- */
521
- isEmpty(value) {
522
- if (value == null) {
523
- return true;
524
- }
525
- const type = this.getDataType(value);
526
- switch (type) {
527
- case "String":
528
- return value.trim() === "";
529
- case "Array":
530
- return !value.length;
531
- case "Object":
532
- return !Object.keys(value).length;
533
- case "Boolean":
534
- return !value;
535
- default:
536
- return false;
537
- }
538
- },
539
- /**
540
- * 将JSON对象转换为FormData对象
541
- *
542
- * @param json 待转换的JSON对象,其属性值为字符串或Blob类型
543
- * @returns 转换后的FormData对象
544
- */
545
- json2form(json) {
546
- const formData = new FormData();
547
- Object.keys(json).forEach((key) => {
548
- formData.append(key, json[key] instanceof Object ? JSON.stringify(json[key]) : json[key]);
549
- });
550
- return formData;
551
- },
552
- /**
553
- * 生成GUID
554
- *
555
- * @returns 返回一个由8个16进制数组成的GUID字符串
556
- */
557
- guid() {
558
- const S4 = function() {
559
- return ((1 + Math.random()) * 65536 | 0).toString(16).substring(1);
560
- };
561
- return S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4();
562
- },
563
- /**
564
- * 将参数进行解码并返回解码后的字符串
565
- *
566
- * @param args 参数
567
- * @returns 解码后的字符串
568
- */
569
- decodeDict(...args) {
570
- let res = "";
571
- if (args.length > 1) {
572
- const items = args.slice(1, args.length % 2 === 0 ? args.length - 1 : args.length);
573
- for (let i = 0; i < items.length; i = i + 2) {
574
- const item = items[i];
575
- if (args[0] === item) {
576
- res = items[i + 1];
577
- }
578
- }
579
- if (!res && args.length % 2 === 0) {
580
- res = args[args.length - 1];
581
- }
582
- } else {
583
- res = args[0];
584
- }
585
- return res;
586
- },
587
- /**
588
- * 将一个或多个对象的所有可枚举属性复制到目标对象。
589
- *
590
- * @param dest 目标对象,用于接收复制的属性。
591
- * @param args 一个或多个源对象,用于提供要复制的属性。
592
- * @returns 返回目标对象,包含所有复制的属性。
593
- */
594
- extend(dest, ...args) {
595
- let i, j, len, src;
596
- for (j = 0, len = args.length; j < len; j++) {
597
- src = args[j];
598
- for (i in src) {
599
- dest[i] = src[i];
600
- }
601
- }
602
- return dest;
603
- },
604
- /**
605
- * 将扁平化数组转换为树形结构数组
606
- *
607
- * @param data 扁平化数组
608
- * @param idPropertyName 数据中标识id的字段名,默认为'id'
609
- * @param parentIdPropertyName 数据中标识父节点id的字段名,默认为'parentId'
610
- * @param childrenPropertyName 树形结构中标识子节点的字段名,默认为'children'
611
- * @returns 转换后的树形结构数组
612
- */
613
- convertToTree2(data, idPropertyName = "id", parentIdPropertyName = "parentId", childrenPropertyName = "children") {
614
- const result = [];
615
- function buildChildren(item) {
616
- const children = data.filter((item2) => item2[parentIdPropertyName] === item[idPropertyName]).map((child) => {
617
- if (!result.some((r) => r[idPropertyName] === child[idPropertyName])) {
618
- buildChildren(child);
619
- }
620
- return child;
621
- });
622
- if (children.length > 0) {
623
- item[childrenPropertyName] = children;
624
- }
625
- }
626
- data.forEach((item) => {
627
- if (!data.some((other) => other[parentIdPropertyName] === item[idPropertyName])) {
628
- buildChildren(item);
629
- result.push(item);
630
- }
631
- });
632
- return result;
633
- },
634
- /**
635
- * 异步加载script
636
- *
637
- * @param {*} url
638
- */
639
- asyncLoadScript(url) {
640
- return new Promise((resolve, reject) => {
641
- try {
642
- const oscript = document.createElement("script");
643
- oscript.type = "text/javascript";
644
- oscript.src = url;
645
- if ("readyState" in oscript) {
646
- oscript.onreadystatechange = function() {
647
- if (oscript.readyState === "complete" || oscript.readyState === "loaded") {
648
- resolve(oscript);
649
- }
650
- };
651
- } else {
652
- oscript.onload = function() {
653
- resolve(oscript);
654
- };
655
- oscript.onerror = function() {
656
- reject(new Error("Script failed to load for URL: " + url));
657
- };
658
- }
659
- document.body.appendChild(oscript);
660
- } catch (error) {
661
- reject(error);
662
- }
663
- });
664
- },
665
- /**
666
- * 加载样式文件
667
- *
668
- * @param urls 样式文件URL数组
669
- * @returns 无返回值
670
- */
671
- loadStyle(urls) {
672
- urls.forEach((url) => {
673
- const css = document.createElement("link");
674
- css.href = url;
675
- css.rel = "stylesheet";
676
- css.type = "text/css";
677
- css.onerror = function() {
678
- console.error(`Style loading failed for URL: ${url}`);
679
- };
680
- document.head.appendChild(css);
681
- });
682
- },
683
- /**
684
- * 将模板字符串中的占位符替换为给定对象中的值
685
- *
686
- * @param str 模板字符串
687
- * @param data 包含替换值的对象
688
- * @returns 替换后的字符串
689
- * @throws 当对象中没有找到与占位符对应的值时,抛出错误
690
- */
691
- template(str, data) {
692
- const templateRe = /\{ *([\w_-]+) *\}/g;
693
- return str.replace(templateRe, (match, key) => {
694
- const value = data[key];
695
- if (value === void 0) {
696
- throw new Error(`${ErrorType.JSON_VALUE_ERROR}: ${match}`);
697
- } else if (typeof value === "function") {
698
- return value(data);
699
- } else {
700
- return value;
701
- }
702
- });
703
- },
704
- /**
705
- * 删除对象中所有值为空的属性
706
- *
707
- * @param data 待处理的对象
708
- * @returns 返回处理后的对象
709
- */
710
- deleteEmptyProperty(data) {
711
- return Object.fromEntries(
712
- Object.keys(data).filter((d) => !this.isEmpty(data[d])).map((i) => [i, data[i]])
713
- );
714
- },
715
- deepAssign(target, ...sources) {
716
- if (typeof target !== "object" || target === null) {
717
- target = {};
718
- }
719
- for (const source of sources) {
720
- if (typeof source === "object" && source !== null) {
721
- for (const key in source) {
722
- if (Object.prototype.hasOwnProperty.call(source, key)) {
723
- if (typeof source[key] === "object" && source[key] !== null) {
724
- if (!target[key]) {
725
- target[key] = Array.isArray(source[key]) ? [] : {};
726
- }
727
- this.deepAssign(target[key], source[key]);
728
- } else {
729
- target[key] = source[key];
730
- }
731
- }
732
- }
733
- }
734
- }
735
- return target;
736
- },
737
- /**
738
- * 复制文本到剪贴板
739
- *
740
- * @param text 要复制的文本
741
- * @returns 返回一个Promise,表示复制操作的结果
428
+ * @param text 要复制的文本
429
+ * @returns 返回一个Promise,表示复制操作的结果
742
430
  */
743
431
  handleCopyValue(text) {
744
432
  if (navigator.clipboard && window.isSecureContext) {
@@ -818,434 +506,119 @@ const ObjectUtil = {
818
506
  return JSON.parse(str);
819
507
  }
820
508
  };
821
- const myArray = Object.create(Array);
822
- myArray.groupBy = function(f) {
823
- var groups = {};
824
- this.forEach(function(o) {
825
- var group = JSON.stringify(f(o));
826
- groups[group] = groups[group] || [];
827
- groups[group].push(o);
828
- });
829
- return Object.keys(groups).map((group) => groups[group]);
830
- };
831
- myArray.distinct = function(f = (d) => d) {
832
- const arr = [];
833
- const obj = {};
834
- this.forEach((item) => {
835
- const val = f(item);
836
- const key = String(val);
837
- if (!obj[key]) {
838
- obj[key] = true;
839
- arr.push(item);
509
+ const ImageUtil = {
510
+ emptyImageUrl: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
511
+ /**
512
+ *
513
+ * @param image image,类型可以是HTMLCanvasElement、ImageData
514
+ * @returns
515
+ */
516
+ getURL(image) {
517
+ let _canvas;
518
+ if (/^data:/i.test(image.src)) {
519
+ return image.src;
840
520
  }
841
- });
842
- return arr;
843
- };
844
- myArray.prototype.max = function() {
845
- return Math.max.apply({}, this);
846
- };
847
- myArray.prototype.min = function() {
848
- return Math.min.apply({}, this);
849
- };
850
- myArray.sum = function() {
851
- return this.length > 0 ? this.reduce((prev = 0, curr = 0) => prev + curr) : 0;
852
- };
853
- myArray.avg = function() {
854
- return this.length ? this.sum() / this.length : 0;
855
- };
856
- myArray.desc = function(f = (d) => d) {
857
- return this.sort((n1, n2) => f(n2) - f(n1));
858
- };
859
- myArray.asc = function(f = (d) => d) {
860
- return this.sort((n1, n2) => f(n1) - f(n2));
861
- };
862
- myArray.remove = function(obj) {
863
- const i = this.indexOf(obj);
864
- if (i > -1) {
865
- this.splice(i, 1);
866
- }
867
- return this;
868
- };
869
- const ArrayUtil = {
870
- /**
871
- * 创建指定长度的数组,并返回其索引数组
872
- *
873
- * @param length 数组长度
874
- * @returns 索引数组
875
- */
876
- create(length) {
877
- return [...new Array(length).keys()];
878
- },
879
- /**
880
- * 合并多个数组,并去重
881
- *
882
- * @param args 需要合并的数组
883
- * @returns 合并后的去重数组
884
- */
885
- union(...args) {
886
- let res = [];
887
- args.forEach((arg) => {
888
- if (Array.isArray(arg)) {
889
- res = res.concat(arg.filter((v) => !res.includes(v)));
521
+ if (typeof HTMLCanvasElement === "undefined") {
522
+ return image.src;
523
+ }
524
+ let canvas;
525
+ if (image instanceof HTMLCanvasElement) {
526
+ canvas = image;
527
+ } else {
528
+ if (_canvas === void 0) _canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
529
+ _canvas.width = image.width;
530
+ _canvas.height = image.height;
531
+ const context = _canvas.getContext("2d");
532
+ if (context) {
533
+ if (image instanceof ImageData) {
534
+ context.putImageData(image, 0, 0);
535
+ } else {
536
+ context.drawImage(image, 0, 0, image.width, image.height);
537
+ }
890
538
  }
891
- });
892
- return res;
539
+ canvas = _canvas;
540
+ }
541
+ if (canvas.width > 2048 || canvas.height > 2048) {
542
+ console.warn("ImageUtil.getDataURL: Image converted to jpg for performance reasons", image);
543
+ return canvas.toDataURL("image/jpeg", 0.6);
544
+ } else {
545
+ return canvas.toDataURL("image/png");
546
+ }
893
547
  },
894
548
  /**
895
- * 求多个数组的交集
549
+ * 将图片的URL转换为Base64编码
896
550
  *
897
- * @param args 多个需要求交集的数组
898
- * @returns 返回多个数组的交集数组
551
+ * @param url 图片的URL地址
552
+ * @param width 图片的宽度,默认为图片原始宽度
553
+ * @param height 图片的高度,默认为图片原始高度
554
+ * @returns 返回Promise对象,解析后得到包含Base64编码数据的对象
899
555
  */
900
- intersection(...args) {
901
- let res = args[0] || [];
902
- args.forEach((arg) => {
903
- if (Array.isArray(arg)) {
904
- res = res.filter((v) => arg.includes(v));
905
- }
556
+ getBase64(url) {
557
+ return new Promise((resolve, reject) => {
558
+ let image = new Image();
559
+ image.setAttribute("crossOrigin", "Anonymous");
560
+ image.src = url;
561
+ image.onload = () => {
562
+ let dataURL = this.getURL(image);
563
+ resolve(dataURL);
564
+ };
565
+ image.onerror = reject;
906
566
  });
907
- return res;
908
567
  },
909
568
  /**
910
- * 将多个数组拼接为一个数组,并去除其中的空值。
569
+ * 解析base64编码
911
570
  *
912
- * @param args 需要拼接的数组列表。
913
- * @returns 拼接并去空后的数组。
571
+ * @param base64 base64编码字符串
572
+ * @returns 返回一个对象,包含type(类型)、ext(扩展名)和data(数据)字段,如果解析失败则返回null
914
573
  */
915
- unionAll(...args) {
916
- return [...args].flat().filter((d) => !!d);
574
+ parseBase64(base64) {
575
+ let re = new RegExp("data:(?<type>.*?);base64,(?<data>.*)");
576
+ let res = re.exec(base64);
577
+ if (res && res.groups) {
578
+ return {
579
+ type: res.groups.type,
580
+ ext: res.groups.type.split("/").slice(-1)[0],
581
+ data: res.groups.data
582
+ };
583
+ }
584
+ return null;
917
585
  },
918
586
  /**
919
- * 求差集
587
+ * 复制图片到剪贴板
920
588
  *
921
- * @param args 任意个集合
922
- * @returns 返回差集结果
589
+ * @param url 图片的URL地址
590
+ * @returns 无返回值
591
+ * @throws 如果解析base64数据失败,则抛出异常
923
592
  */
924
- difference(...args) {
925
- if (args.length === 0) return [];
926
- return this.union(...args).filter((d) => !this.intersection(...args).includes(d));
927
- }
928
- };
929
- const _MqttClient = class _MqttClient extends EventDispatcher {
930
- constructor(url = `ws://${window.document.domain}:20007/mqtt`, config = {}) {
931
- super();
932
- __publicField(this, "state");
933
- __publicField(this, "url");
934
- __publicField(this, "context");
935
- __publicField(this, "options");
936
- __publicField(this, "client");
937
- __publicField(this, "topics");
938
- this.context = CommUtil.extend(_MqttClient.defaultContext, config);
939
- this.options = {
940
- connectTimeout: this.context.MQTT_TIMEOUTM,
941
- clientId: CommUtil.guid(),
942
- username: this.context.MQTT_USERNAME,
943
- password: this.context.MQTT_PASSWORD,
944
- clean: true
945
- };
946
- this.url = url;
947
- this.client = connect(this.url, this.options);
948
- this._onConnect();
949
- this._onMessage();
950
- this.state = 0;
951
- this.topics = [];
952
- }
953
- _onConnect() {
954
- this.client.on("connect", () => {
955
- this.state = 1;
956
- console.log("链接mqtt成功==>" + this.url);
957
- this.dispatchEvent({ type: EventType.MQTT_CONNECT, message: this });
958
- });
959
- this.client.on("error", (err) => {
960
- console.log("链接mqtt报错", err);
961
- this.state = -1;
962
- this.dispatchEvent({ type: EventType.MQTT_ERROR, message: this });
963
- this.client.end();
964
- this.client.reconnect();
965
- });
966
- }
967
- _onMessage() {
968
- this.client.on("message", (topic, message) => {
969
- let dataString = message;
970
- let data = "";
971
- if (message instanceof Uint8Array) {
972
- dataString = message.toString();
593
+ async copyImage(url) {
594
+ try {
595
+ const base64Result = await this.getBase64(url);
596
+ const parsedBase64 = this.parseBase64(base64Result.dataURL);
597
+ if (!parsedBase64) {
598
+ throw new Error("Failed to parse base64 data.");
973
599
  }
974
- try {
975
- data = ObjectUtil.parse(dataString);
976
- } catch (error) {
977
- throw new Error(ErrorType.JSON_PARSE_ERROR);
600
+ let type = parsedBase64.type;
601
+ let bytes = atob(parsedBase64.data);
602
+ let ab = new ArrayBuffer(bytes.length);
603
+ let ua = new Uint8Array(ab);
604
+ for (let i = 0; i < bytes.length; i++) {
605
+ ua[i] = bytes.charCodeAt(i);
978
606
  }
979
- this.dispatchEvent({
980
- type: EventType.MQTT_MESSAGE,
981
- message: { topic, data }
982
- });
983
- });
984
- }
985
- sendMsg(topic, msg) {
986
- if (!this.client.connected) {
987
- console.error("客户端未连接");
988
- return;
607
+ let blob = new Blob([ab], { type });
608
+ await navigator.clipboard.write([new ClipboardItem({ [type]: blob })]);
609
+ } catch (error) {
610
+ console.error("Failed to copy image to clipboard:", error);
989
611
  }
990
- this.client.publish(topic, msg, { qos: 1, retain: true });
991
- }
992
- subscribe(topic) {
993
- this.state === 1 ? this.client.subscribe(topic, { qos: 1 }, (error, e) => {
994
- error instanceof Error ? console.error("订阅失败==>" + topic, error) : (this.topics = ArrayUtil.union(this.topics, topic), console.log("订阅成功==>" + topic));
995
- }) : this.addEventListener(EventType.MQTT_CONNECT, (res) => {
996
- this.client.subscribe(topic, { qos: 1 }, (error, e) => {
997
- error instanceof Error ? console.error("订阅失败==>" + topic, error) : (this.topics = ArrayUtil.union(this.topics, topic), console.log("订阅成功==>" + topic));
998
- });
999
- });
1000
- return this;
1001
- }
1002
- unsubscribe(topic) {
1003
- this.client.unsubscribe(topic, { qos: 1 }, (error, res) => {
1004
- if (error instanceof Error) {
1005
- console.error(`取消订阅失败==>${topic}`, error);
1006
- } else {
1007
- this.topics = ArrayUtil.difference(this.topics, topic);
1008
- console.log(`取消订阅成功==>${topic}`);
1009
- }
1010
- });
1011
- return this;
1012
- }
1013
- unsubscribeAll() {
1014
- this.unsubscribe(this.topics);
1015
- }
1016
- unconnect() {
1017
- this.client.end();
1018
- this.client = null;
1019
- this.dispatchEvent({ type: EventType.MQTT_CLOSE, message: null });
1020
- console.log("断开mqtt成功==>" + this.url);
1021
612
  }
1022
613
  };
1023
- /**
1024
- * Creates an instance of MqttClient.
1025
- * @param {*} config mqtt实例参数
1026
- */
1027
- __publicField(_MqttClient, "defaultContext", {
1028
- MQTT_USERNAME: "iRVMS-WEB",
1029
- MQTT_PASSWORD: "novasky888",
1030
- MQTT_TIMEOUTM: 2e4
1031
- });
1032
- let MqttClient = _MqttClient;
1033
- const _Storage = class _Storage {
614
+ const AjaxUtil = {
1034
615
  /**
1035
- * 将键值对存储到localStorage中
1036
- *
1037
- * @param key 键名
1038
- * @param value 值,默认为null
1039
- * @param options 存储选项,可选参数
1040
- * @param options.expires 过期时间,单位为毫秒,默认为null
1041
- */
1042
- static set(key, value = null, options = {}) {
1043
- var query_key = this._getPrefixedKey(key, options);
1044
- try {
1045
- const { expires } = options;
1046
- const data = { data: value };
1047
- if (expires) {
1048
- data.expires = expires;
1049
- }
1050
- localStorage.setItem(query_key, JSON.stringify(data));
1051
- } catch (e) {
1052
- if (console) console.warn(`Storage didn't successfully save the '{"${key}": "${value}"}' pair, because the localStorage is full.`);
1053
- }
1054
- }
1055
- /**
1056
- * 从localStorage中获取指定key的存储值
1057
- *
1058
- * @param key 存储键名
1059
- * @param missing 当获取不到指定key的存储值时返回的默认值
1060
- * @param options 其他配置选项
1061
- * @returns 返回指定key的存储值,若获取不到则返回missing参数指定的默认值
1062
- */
1063
- static get(key, missing, options) {
1064
- var query_key = this._getPrefixedKey(key, options), value;
1065
- try {
1066
- value = JSON.parse(localStorage.getItem(query_key) || "");
1067
- } catch (e) {
1068
- if (localStorage[query_key]) {
1069
- value = { data: localStorage.getItem(query_key) };
1070
- } else {
1071
- value = null;
1072
- }
1073
- }
1074
- if (!value) {
1075
- return missing;
1076
- } else if (typeof value === "object" && typeof value.data !== "undefined") {
1077
- const expires = value.expires;
1078
- if (expires && Date.now() > expires) {
1079
- return missing;
1080
- }
1081
- return value.data;
1082
- }
1083
- }
1084
- static keys() {
1085
- const keys = [];
1086
- var allKeys = Object.keys(localStorage);
1087
- if (_Storage.prefix.length === 0) {
1088
- return allKeys;
1089
- }
1090
- allKeys.forEach(function(key) {
1091
- if (key.indexOf(_Storage.prefix) !== -1) {
1092
- keys.push(key.replace(_Storage.prefix, ""));
1093
- }
1094
- });
1095
- return keys;
1096
- }
1097
- static getAll(includeKeys) {
1098
- var keys = _Storage.keys();
1099
- if (includeKeys) {
1100
- const result = [];
1101
- keys.forEach((key) => {
1102
- if (includeKeys.includes(key)) {
1103
- const tempObj = {};
1104
- tempObj[key] = _Storage.get(key, null, null);
1105
- result.push(tempObj);
1106
- }
1107
- });
1108
- return result;
1109
- }
1110
- return keys.map((key) => _Storage.get(key, null, null));
1111
- }
1112
- static remove(key, options) {
1113
- var queryKey = this._getPrefixedKey(key, options);
1114
- localStorage.removeItem(queryKey);
1115
- }
1116
- static clear(options) {
1117
- if (_Storage.prefix.length) {
1118
- this.keys().forEach((key) => {
1119
- localStorage.removeItem(this._getPrefixedKey(key, options));
1120
- });
1121
- } else {
1122
- localStorage.clear();
1123
- }
1124
- }
1125
- };
1126
- __publicField(_Storage, "prefix", "");
1127
- __publicField(_Storage, "_getPrefixedKey", function(key, options) {
1128
- options = options || {};
1129
- if (options.noPrefix) {
1130
- return key;
1131
- } else {
1132
- return _Storage.prefix + key;
1133
- }
1134
- });
1135
- let Storage = _Storage;
1136
- const ImageUtil = {
1137
- emptyImageUrl: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
1138
- /**
1139
- *
1140
- * @param image image,类型可以是HTMLCanvasElement、ImageData
1141
- * @returns
1142
- */
1143
- getURL(image) {
1144
- let _canvas;
1145
- if (/^data:/i.test(image.src)) {
1146
- return image.src;
1147
- }
1148
- if (typeof HTMLCanvasElement === "undefined") {
1149
- return image.src;
1150
- }
1151
- let canvas;
1152
- if (image instanceof HTMLCanvasElement) {
1153
- canvas = image;
1154
- } else {
1155
- if (_canvas === void 0) _canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
1156
- _canvas.width = image.width;
1157
- _canvas.height = image.height;
1158
- const context = _canvas.getContext("2d");
1159
- if (context) {
1160
- if (image instanceof ImageData) {
1161
- context.putImageData(image, 0, 0);
1162
- } else {
1163
- context.drawImage(image, 0, 0, image.width, image.height);
1164
- }
1165
- }
1166
- canvas = _canvas;
1167
- }
1168
- if (canvas.width > 2048 || canvas.height > 2048) {
1169
- console.warn("ImageUtil.getDataURL: Image converted to jpg for performance reasons", image);
1170
- return canvas.toDataURL("image/jpeg", 0.6);
1171
- } else {
1172
- return canvas.toDataURL("image/png");
1173
- }
1174
- },
1175
- /**
1176
- * 将图片的URL转换为Base64编码
1177
- *
1178
- * @param url 图片的URL地址
1179
- * @param width 图片的宽度,默认为图片原始宽度
1180
- * @param height 图片的高度,默认为图片原始高度
1181
- * @returns 返回Promise对象,解析后得到包含Base64编码数据的对象
1182
- */
1183
- getBase64(url) {
1184
- return new Promise((resolve, reject) => {
1185
- let image = new Image();
1186
- image.setAttribute("crossOrigin", "Anonymous");
1187
- image.src = url;
1188
- image.onload = () => {
1189
- let dataURL = this.getURL(image);
1190
- resolve(dataURL);
1191
- };
1192
- image.onerror = reject;
1193
- });
1194
- },
1195
- /**
1196
- * 解析base64编码
1197
- *
1198
- * @param base64 base64编码字符串
1199
- * @returns 返回一个对象,包含type(类型)、ext(扩展名)和data(数据)字段,如果解析失败则返回null
1200
- */
1201
- parseBase64(base64) {
1202
- let re = new RegExp("data:(?<type>.*?);base64,(?<data>.*)");
1203
- let res = re.exec(base64);
1204
- if (res && res.groups) {
1205
- return {
1206
- type: res.groups.type,
1207
- ext: res.groups.type.split("/").slice(-1)[0],
1208
- data: res.groups.data
1209
- };
1210
- }
1211
- return null;
1212
- },
1213
- /**
1214
- * 复制图片到剪贴板
1215
- *
1216
- * @param url 图片的URL地址
1217
- * @returns 无返回值
1218
- * @throws 如果解析base64数据失败,则抛出异常
1219
- */
1220
- async copyImage(url) {
1221
- try {
1222
- const base64Result = await this.getBase64(url);
1223
- const parsedBase64 = this.parseBase64(base64Result.dataURL);
1224
- if (!parsedBase64) {
1225
- throw new Error("Failed to parse base64 data.");
1226
- }
1227
- let type = parsedBase64.type;
1228
- let bytes = atob(parsedBase64.data);
1229
- let ab = new ArrayBuffer(bytes.length);
1230
- let ua = new Uint8Array(ab);
1231
- for (let i = 0; i < bytes.length; i++) {
1232
- ua[i] = bytes.charCodeAt(i);
1233
- }
1234
- let blob = new Blob([ab], { type });
1235
- await navigator.clipboard.write([new ClipboardItem({ [type]: blob })]);
1236
- } catch (error) {
1237
- console.error("Failed to copy image to clipboard:", error);
1238
- }
1239
- }
1240
- };
1241
- const AjaxUtil = {
1242
- /**
1243
- * Get JSON data by jsonp
1244
- * @param url - resource url
1245
- * @param callback - callback function when completed
616
+ * Get JSON data by jsonp
617
+ * @param url - resource url
618
+ * @param callback - callback function when completed
1246
619
  */
1247
620
  jsonp(url, callback) {
1248
- const name = "_jsonp_" + CommUtil.guid();
621
+ const name = "_jsonp_" + CommUtils.guid();
1249
622
  const head = document.getElementsByTagName("head")[0];
1250
623
  if (url.includes("?")) {
1251
624
  url += "&callback=" + name;
@@ -1284,7 +657,7 @@ const AjaxUtil = {
1284
657
  * );
1285
658
  */
1286
659
  get(url, options, cb) {
1287
- if (CommUtil.isFunction(options)) {
660
+ if (CommUtils.isFunction(options)) {
1288
661
  const t = cb;
1289
662
  cb = options;
1290
663
  options = t;
@@ -1416,7 +789,7 @@ const AjaxUtil = {
1416
789
  * );
1417
790
  */
1418
791
  getArrayBuffer(url, options, cb) {
1419
- if (CommUtil.isFunction(options)) {
792
+ if (CommUtils.isFunction(options)) {
1420
793
  const t = cb;
1421
794
  cb = options;
1422
795
  options = t;
@@ -1469,7 +842,7 @@ const AjaxUtil = {
1469
842
  * );
1470
843
  */
1471
844
  getJSON(url, options, cb) {
1472
- if (CommUtil.isFunction(options)) {
845
+ if (CommUtils.isFunction(options)) {
1473
846
  const t = cb;
1474
847
  cb = options;
1475
848
  options = t;
@@ -1486,6 +859,48 @@ const AjaxUtil = {
1486
859
  return this.get(url, options, callback);
1487
860
  }
1488
861
  };
862
+ const MathUtils = {
863
+ DEG2RAD: Math.PI / 180,
864
+ RAD2DEG: 180 / Math.PI,
865
+ randInt(low, high) {
866
+ return low + Math.floor(Math.random() * (high - low + 1));
867
+ },
868
+ randFloat(low, high) {
869
+ return low + Math.random() * (high - low);
870
+ },
871
+ /**
872
+ * 角度转弧度
873
+ *
874
+ * @param {*} degrees
875
+ * @returns {*}
876
+ */
877
+ deg2Rad(degrees) {
878
+ return degrees * this.DEG2RAD;
879
+ },
880
+ /**
881
+ * 弧度转角度
882
+ *
883
+ * @param {*} radians
884
+ * @returns {*}
885
+ */
886
+ rad2Deg(radians) {
887
+ return radians * this.RAD2DEG;
888
+ },
889
+ round(value, n = 2) {
890
+ return Math.round(value * Math.pow(10, n)) / Math.pow(10, n);
891
+ },
892
+ /**
893
+ * 将数值限制在指定范围内
894
+ *
895
+ * @param val 需要限制的数值
896
+ * @param min 最小值
897
+ * @param max 最大值
898
+ * @returns 返回限制后的数值
899
+ */
900
+ clamp(val, min, max) {
901
+ return Math.max(min, Math.min(max, val));
902
+ }
903
+ };
1489
904
  const GeoUtil = {
1490
905
  toRadian: Math.PI / 180,
1491
906
  R: 6371393,
@@ -1853,7 +1268,7 @@ const StringUtil = {
1853
1268
  */
1854
1269
  tag(strArray, ...args) {
1855
1270
  args = args.map((val) => {
1856
- switch (CommUtil.getDataType(val)) {
1271
+ switch (CommUtils.getDataType(val)) {
1857
1272
  case "Object":
1858
1273
  return val || "{}";
1859
1274
  case "Array":
@@ -1896,127 +1311,22 @@ const StringUtil = {
1896
1311
  return str;
1897
1312
  }
1898
1313
  };
1899
- const ColorUtil = {
1900
- random() {
1901
- let r = Math.floor(Math.random() * 256).toString(16);
1902
- let g = Math.floor(Math.random() * 256).toString(16);
1903
- let b = Math.floor(Math.random() * 256).toString(16);
1904
- r = r.length === 1 ? "0" + r : r;
1905
- g = g.length === 1 ? "0" + g : g;
1906
- b = b.length === 1 ? "0" + b : b;
1907
- return "#" + r + g + b;
1908
- },
1314
+ const TYPES = ["Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon"];
1315
+ const GeoJsonUtil = {
1909
1316
  /**
1910
- * 将RGB颜色值转换为十六进制颜色值
1317
+ * 获取GeoJSON要素的几何类型
1911
1318
  *
1912
- * @param rgb RGB颜色值数组,包含三个0-255之间的整数
1913
- * @returns 转换后的十六进制颜色值,以#开头
1319
+ * @param feature GeoJSONFeature 类型的要素
1320
+ * @returns 返回要素的几何类型,如果要素没有几何属性则返回 null
1914
1321
  */
1915
- rgb2hex(rgb) {
1916
- var hex = "#" + ((1 << 24) + (rgb[0] << 16) + (rgb[1] << 8) + rgb[2]).toString(16).slice(1);
1917
- return hex;
1322
+ getGeoJsonType(feature) {
1323
+ return feature.geometry ? feature.geometry.type : null;
1918
1324
  },
1919
1325
  /**
1920
- * 将RGB颜色值转换为RGBA颜色值,并返回转换后的颜色值。
1326
+ * 判断给定的GeoJSON要素是否为有效的GeoJSON格式
1921
1327
  *
1922
- * @param rgbValue RGB颜色值,格式为"rgb(r, g, b)"。
1923
- * @returns 转换后的RGBA颜色值,格式为"rgba(r, g, b, 1)"。如果输入值不符合RGB格式,则返回原值。
1924
- */
1925
- rgbToRgba(rgbValue) {
1926
- const rgb = /rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g.exec(rgbValue);
1927
- return rgb ? `rgba(${rgb[1]}, 1)` : rgbValue;
1928
- },
1929
- /**
1930
- * 将十六进制颜色值转换为rgba格式的颜色值
1931
- *
1932
- * @param hexValue 十六进制颜色值,可带或不带#前缀,支持3位和6位表示
1933
- * @returns 返回rgba格式的颜色值,格式为rgba(r,g,b,1)
1934
- */
1935
- hexToRgba(hexValue) {
1936
- const rgxShort = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
1937
- const hex = hexValue.replace(rgxShort, (m, r2, g2, b2) => r2 + r2 + g2 + g2 + b2 + b2);
1938
- const rgx = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
1939
- const rgb = rgx.exec(hex);
1940
- if (!rgb) {
1941
- return hexValue;
1942
- }
1943
- const r = parseInt(rgb[1], 16);
1944
- const g = parseInt(rgb[2], 16);
1945
- const b = parseInt(rgb[3], 16);
1946
- return `rgba(${r},${g},${b},1)`;
1947
- },
1948
- /**
1949
- * 将 HSL 颜色值转换为 RGBA 颜色值
1950
- *
1951
- * @param hslValue HSL 颜色值字符串,格式为 "hsl(h, s%, l%)" 或 "hsla(h, s%, l%, a)",其中 h 为色相,s 为饱和度,l 为亮度,a 为透明度(可选)。
1952
- * @returns 转换后的 RGBA 颜色值字符串,格式为 "rgba(r, g, b, a)",其中 r、g、b 为红绿蓝分量,a 为透明度。若输入为空或无效,则返回 null。
1953
- */
1954
- hslToRgba(hslValue) {
1955
- if (!hslValue) {
1956
- return null;
1957
- }
1958
- const hsl = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(hslValue) || /hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g.exec(hslValue);
1959
- if (!hsl) {
1960
- return null;
1961
- }
1962
- const h = parseInt(hsl[1], 10) / 360;
1963
- const s = parseInt(hsl[2], 10) / 100;
1964
- const l = parseInt(hsl[3], 10) / 100;
1965
- const a = hsl[4] ? parseFloat(hsl[4]) : 1;
1966
- function hue2rgb(p, q, t) {
1967
- if (t < 0) t += 1;
1968
- if (t > 1) t -= 1;
1969
- if (t < 1 / 6) return p + (q - p) * 6 * t;
1970
- if (t < 1 / 2) return q;
1971
- if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
1972
- return p;
1973
- }
1974
- let r, g, b;
1975
- if (s === 0) {
1976
- r = g = b = l;
1977
- } else {
1978
- const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
1979
- const p = 2 * l - q;
1980
- r = hue2rgb(p, q, h + 1 / 3);
1981
- g = hue2rgb(p, q, h);
1982
- b = hue2rgb(p, q, h - 1 / 3);
1983
- }
1984
- return `rgba(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)},${a})`;
1985
- },
1986
- isHex(a) {
1987
- return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(a);
1988
- },
1989
- isRgb(a) {
1990
- return /^rgb/.test(a);
1991
- },
1992
- isHsl(a) {
1993
- return /^hsl/.test(a);
1994
- },
1995
- isColor(a) {
1996
- return this.isHex(a) || this.isRgb(a) || this.isHsl(a);
1997
- },
1998
- colorToRgb(val) {
1999
- if (this.isRgb(val)) return this.rgbToRgba(val);
2000
- if (this.isHex(val)) return this.hexToRgba(val);
2001
- if (this.isHsl(val)) return this.hslToRgba(val);
2002
- }
2003
- };
2004
- const TYPES = ["Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon"];
2005
- const GeoJsonUtil = {
2006
- /**
2007
- * 获取GeoJSON要素的几何类型
2008
- *
2009
- * @param feature GeoJSONFeature 类型的要素
2010
- * @returns 返回要素的几何类型,如果要素没有几何属性则返回 null
2011
- */
2012
- getGeoJsonType(feature) {
2013
- return feature.geometry ? feature.geometry.type : null;
2014
- },
2015
- /**
2016
- * 判断给定的GeoJSON要素是否为有效的GeoJSON格式
2017
- *
2018
- * @param feature 要判断的GeoJSON要素
2019
- * @returns 如果为有效的GeoJSON格式则返回true,否则返回false
1328
+ * @param feature 要判断的GeoJSON要素
1329
+ * @returns 如果为有效的GeoJSON格式则返回true,否则返回false
2020
1330
  */
2021
1331
  isGeoJson(feature) {
2022
1332
  const type = this.getGeoJsonType(feature);
@@ -2245,42 +1555,42 @@ const GeoJsonUtil = {
2245
1555
  const AssertUtil = {
2246
1556
  assertEmpty(...arg) {
2247
1557
  arg.forEach((a) => {
2248
- if (CommUtil.isEmpty(a)) {
1558
+ if (CommUtils.isEmpty(a)) {
2249
1559
  throw Error(ErrorType.PARAMETER_ERROR_LACK + " -> " + a);
2250
1560
  }
2251
1561
  });
2252
1562
  },
2253
1563
  assertNumber(...arg) {
2254
1564
  arg.forEach((a) => {
2255
- if (!CommUtil.isNumber(a)) {
1565
+ if (!CommUtils.isNumber(a)) {
2256
1566
  throw Error(ErrorType.PARAMETER_ERROR_NUMBER + " -> " + a);
2257
1567
  }
2258
1568
  });
2259
1569
  },
2260
1570
  assertArray(...arg) {
2261
1571
  arg.forEach((a) => {
2262
- if (!CommUtil.isArray(a)) {
1572
+ if (!CommUtils.isArray(a)) {
2263
1573
  throw Error(ErrorType.PARAMETER_ERROR_ARRAY + " -> " + a);
2264
1574
  }
2265
1575
  });
2266
1576
  },
2267
1577
  assertFunction(...arg) {
2268
1578
  arg.forEach((a) => {
2269
- if (!CommUtil.isFunction(a)) {
1579
+ if (!CommUtils.isFunction(a)) {
2270
1580
  throw Error(ErrorType.PARAMETER_ERROR_FUNCTION + " -> " + a);
2271
1581
  }
2272
1582
  });
2273
1583
  },
2274
1584
  assertObject(...arg) {
2275
1585
  arg.forEach((a) => {
2276
- if (!CommUtil.isObject(a)) {
1586
+ if (!CommUtils.isObject(a)) {
2277
1587
  throw Error(ErrorType.PARAMETER_ERROR_OBJECT + " -> " + a);
2278
1588
  }
2279
1589
  });
2280
1590
  },
2281
1591
  assertColor(...arg) {
2282
1592
  arg.forEach((a) => {
2283
- if (!ColorUtil.isColor(a)) {
1593
+ if (!Color.isColor(a)) {
2284
1594
  throw Error(ErrorType.DATA_ERROR_COLOR + " -> " + a);
2285
1595
  }
2286
1596
  });
@@ -2377,6 +1687,117 @@ const AssertUtil = {
2377
1687
  }
2378
1688
  }
2379
1689
  };
1690
+ const myArray = Object.create(Array);
1691
+ myArray.groupBy = function(f) {
1692
+ var groups = {};
1693
+ this.forEach(function(o) {
1694
+ var group = JSON.stringify(f(o));
1695
+ groups[group] = groups[group] || [];
1696
+ groups[group].push(o);
1697
+ });
1698
+ return Object.keys(groups).map((group) => groups[group]);
1699
+ };
1700
+ myArray.distinct = function(f = (d) => d) {
1701
+ const arr = [];
1702
+ const obj = {};
1703
+ this.forEach((item) => {
1704
+ const val = f(item);
1705
+ const key = String(val);
1706
+ if (!obj[key]) {
1707
+ obj[key] = true;
1708
+ arr.push(item);
1709
+ }
1710
+ });
1711
+ return arr;
1712
+ };
1713
+ myArray.prototype.max = function() {
1714
+ return Math.max.apply({}, this);
1715
+ };
1716
+ myArray.prototype.min = function() {
1717
+ return Math.min.apply({}, this);
1718
+ };
1719
+ myArray.sum = function() {
1720
+ return this.length > 0 ? this.reduce((prev = 0, curr = 0) => prev + curr) : 0;
1721
+ };
1722
+ myArray.avg = function() {
1723
+ return this.length ? this.sum() / this.length : 0;
1724
+ };
1725
+ myArray.desc = function(f = (d) => d) {
1726
+ return this.sort((n1, n2) => f(n2) - f(n1));
1727
+ };
1728
+ myArray.asc = function(f = (d) => d) {
1729
+ return this.sort((n1, n2) => f(n1) - f(n2));
1730
+ };
1731
+ myArray.random = function() {
1732
+ return this[Math.floor(Math.random() * this.length)];
1733
+ };
1734
+ myArray.remove = function(obj) {
1735
+ const i = this.indexOf(obj);
1736
+ if (i > -1) {
1737
+ this.splice(i, 1);
1738
+ }
1739
+ return this;
1740
+ };
1741
+ const ArrayUtil = {
1742
+ /**
1743
+ * 创建指定长度的数组,并返回其索引数组
1744
+ *
1745
+ * @param length 数组长度
1746
+ * @returns 索引数组
1747
+ */
1748
+ create(length) {
1749
+ return [...new Array(length).keys()];
1750
+ },
1751
+ /**
1752
+ * 合并多个数组,并去重
1753
+ *
1754
+ * @param args 需要合并的数组
1755
+ * @returns 合并后的去重数组
1756
+ */
1757
+ union(...args) {
1758
+ let res = [];
1759
+ args.forEach((arg) => {
1760
+ if (Array.isArray(arg)) {
1761
+ res = res.concat(arg.filter((v) => !res.includes(v)));
1762
+ }
1763
+ });
1764
+ return res;
1765
+ },
1766
+ /**
1767
+ * 求多个数组的交集
1768
+ *
1769
+ * @param args 多个需要求交集的数组
1770
+ * @returns 返回多个数组的交集数组
1771
+ */
1772
+ intersection(...args) {
1773
+ let res = args[0] || [];
1774
+ args.forEach((arg) => {
1775
+ if (Array.isArray(arg)) {
1776
+ res = res.filter((v) => arg.includes(v));
1777
+ }
1778
+ });
1779
+ return res;
1780
+ },
1781
+ /**
1782
+ * 将多个数组拼接为一个数组,并去除其中的空值。
1783
+ *
1784
+ * @param args 需要拼接的数组列表。
1785
+ * @returns 拼接并去空后的数组。
1786
+ */
1787
+ unionAll(...args) {
1788
+ return [...args].flat().filter((d) => !!d);
1789
+ },
1790
+ /**
1791
+ * 求差集
1792
+ *
1793
+ * @param args 任意个集合
1794
+ * @returns 返回差集结果
1795
+ */
1796
+ difference(...args) {
1797
+ if (args.length === 0) return [];
1798
+ return this.union(...args).filter((d) => !this.intersection(...args).includes(d));
1799
+ }
1800
+ };
2380
1801
  const BrowserUtil = {
2381
1802
  /**
2382
1803
  * 获取浏览器类型
@@ -2607,18 +2028,26 @@ const CoordsUtil = {
2607
2028
  return ret;
2608
2029
  },
2609
2030
  /**
2610
- * 生成指定范围内的随机经纬度坐标
2031
+ * 生成一个介于两个坐标之间的随机坐标
2611
2032
  *
2612
- * @param min 最小坐标,包含属性 x y,分别表示最小经度和最小纬度
2613
- * @param max 最大坐标,包含属性 x y,分别表示最大经度和最大纬度
2614
- * @returns 返回生成的随机经纬度坐标,包含属性 lat lng,分别表示纬度和经度
2033
+ * @param start 起始坐标,包含x和y属性
2034
+ * @param end 结束坐标,包含x和y属性
2035
+ * @returns 返回一个包含xy属性的随机坐标
2615
2036
  */
2616
2037
  random({ x: minX, y: minY }, { x: maxX, y: maxY }) {
2617
2038
  return {
2618
- lat: Math.random() * (maxY - minY) + minY,
2619
- lng: Math.random() * (maxX - minX) + minX
2039
+ x: Math.random() * (maxX - minX) + minX,
2040
+ y: Math.random() * (maxY - minY) + minY
2620
2041
  };
2621
2042
  },
2043
+ /**
2044
+ * 对坐标数组进行解构并应用函数处理
2045
+ *
2046
+ * @param arr 待解构的数组
2047
+ * @param fn 处理函数
2048
+ * @param context 函数执行上下文,可选
2049
+ * @returns 处理后的数组
2050
+ */
2622
2051
  deCompose(arr, fn, context) {
2623
2052
  if (!Array.isArray(arr)) {
2624
2053
  return context ? fn.call(context, arr) : fn(arr);
@@ -2627,7 +2056,7 @@ const CoordsUtil = {
2627
2056
  let p, pp;
2628
2057
  for (let i = 0, len = arr.length; i < len; i++) {
2629
2058
  p = arr[i];
2630
- if (CommUtil.isNil(p)) {
2059
+ if (CommUtils.isNil(p)) {
2631
2060
  result.push(null);
2632
2061
  continue;
2633
2062
  }
@@ -3199,6 +2628,643 @@ const UrlUtil = {
3199
2628
  return obj;
3200
2629
  }
3201
2630
  };
2631
+ class Color {
2632
+ constructor(r, g, b, a) {
2633
+ __publicField(this, "_r");
2634
+ __publicField(this, "_g");
2635
+ __publicField(this, "_b");
2636
+ __publicField(this, "_alpha");
2637
+ this._validateColorChannel(r);
2638
+ this._validateColorChannel(g);
2639
+ this._validateColorChannel(b);
2640
+ this._r = r;
2641
+ this._g = g;
2642
+ this._b = b;
2643
+ this._alpha = MathUtils.clamp(a || 1, 0, 1);
2644
+ }
2645
+ _validateColorChannel(channel) {
2646
+ if (channel < 0 || channel > 255) {
2647
+ throw new Error("Color channel must be between 0 and 255.");
2648
+ }
2649
+ }
2650
+ // 获取颜色的RGB值
2651
+ get rgba() {
2652
+ return { r: this._r, g: this._g, b: this._b, a: this._alpha };
2653
+ }
2654
+ get hex() {
2655
+ return Color.rgb2hex(this._r, this._g, this._b, this._alpha);
2656
+ }
2657
+ // 设置颜色的RGB值
2658
+ setRgb(r, g, b, a) {
2659
+ this._validateColorChannel(r);
2660
+ this._validateColorChannel(g);
2661
+ this._validateColorChannel(b);
2662
+ this._r = r;
2663
+ this._g = g;
2664
+ this._b = b;
2665
+ this._alpha = MathUtils.clamp(a, 0, 1);
2666
+ return this;
2667
+ }
2668
+ /**
2669
+ * 从RGBA字符串创建Color对象
2670
+ *
2671
+ * @param rgbaValue RGBA颜色值字符串,格式为"rgba(r,g,b,a)"或"rgb(r,g,b)"
2672
+ * @returns 返回Color对象
2673
+ * @throws 如果rgbaValue不是有效的RGBA颜色值,则抛出错误
2674
+ */
2675
+ static fromRgba(rgbaValue) {
2676
+ const rgbaMatch = rgbaValue.match(/^rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([\d.]+))?\s*\)$/);
2677
+ if (!rgbaMatch) throw new Error("Invalid RGBA color value");
2678
+ const r = parseInt(rgbaMatch[1], 10);
2679
+ const g = parseInt(rgbaMatch[2], 10);
2680
+ const b = parseInt(rgbaMatch[3], 10);
2681
+ const a = rgbaMatch[5] ? parseFloat(rgbaMatch[5]) : 1;
2682
+ return new Color(r, g, b, a);
2683
+ }
2684
+ /**
2685
+ * 将十六进制颜色值转换为颜色对象
2686
+ *
2687
+ * @param hexValue 十六进制颜色值,可带或不带#前缀,支持3位和6位表示
2688
+ * @returns 返回颜色对象
2689
+ */
2690
+ static fromHex(hexValue, a = 1) {
2691
+ const rgxShort = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2692
+ const hex = hexValue.replace(rgxShort, (m, r2, g2, b2) => r2 + r2 + g2 + g2 + b2 + b2);
2693
+ const rgx = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
2694
+ const rgb = rgx.exec(hex);
2695
+ if (!rgb) {
2696
+ throw new Error("Invalid HEX color value");
2697
+ }
2698
+ const r = parseInt(rgb[1], 16);
2699
+ const g = parseInt(rgb[2], 16);
2700
+ const b = parseInt(rgb[3], 16);
2701
+ return new Color(r, g, b, a);
2702
+ }
2703
+ /**
2704
+ * 从 HSL 字符串创建颜色对象
2705
+ *
2706
+ * @param hsl HSL 字符串,格式为 hsl(h, s%, l%) 或 hsla(h, s%, l%, a)
2707
+ * @returns 返回颜色对象,如果 hsl 字符串无效则返回 null
2708
+ */
2709
+ static fromHsl(hslValue) {
2710
+ const hsl = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(hslValue) || /hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g.exec(hslValue);
2711
+ if (!hsl) {
2712
+ throw new Error("Invalid HSL color value");
2713
+ }
2714
+ const h = parseInt(hsl[1], 10) / 360;
2715
+ const s = parseInt(hsl[2], 10) / 100;
2716
+ const l = parseInt(hsl[3], 10) / 100;
2717
+ const a = hsl[4] ? parseFloat(hsl[4]) : 1;
2718
+ function hue2rgb(p, q, t) {
2719
+ if (t < 0) t += 1;
2720
+ if (t > 1) t -= 1;
2721
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
2722
+ if (t < 1 / 2) return q;
2723
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
2724
+ return p;
2725
+ }
2726
+ let r, g, b;
2727
+ if (s === 0) {
2728
+ r = g = b = l;
2729
+ } else {
2730
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
2731
+ const p = 2 * l - q;
2732
+ r = hue2rgb(p, q, h + 1 / 3);
2733
+ g = hue2rgb(p, q, h);
2734
+ b = hue2rgb(p, q, h - 1 / 3);
2735
+ }
2736
+ return new Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
2737
+ }
2738
+ /**
2739
+ * 从字符串中创建颜色对象
2740
+ *
2741
+ * @param str 字符串类型的颜色值,支持rgba、hex、hsl格式
2742
+ * @returns 返回创建的颜色对象
2743
+ * @throws 当颜色值无效时,抛出错误
2744
+ */
2745
+ static from(str) {
2746
+ if (this.isRgb(str)) {
2747
+ return this.fromRgba(str);
2748
+ } else if (this.isHex(str)) {
2749
+ return this.fromHex(str);
2750
+ } else if (this.isHsl(str)) {
2751
+ return this.fromHsl(str);
2752
+ } else {
2753
+ throw new Error("Invalid color value");
2754
+ }
2755
+ }
2756
+ /**
2757
+ * 将RGB颜色值转换为十六进制颜色值
2758
+ *
2759
+ * @param r 红色分量值,取值范围0-255
2760
+ * @param g 绿色分量值,取值范围0-255
2761
+ * @param b 蓝色分量值,取值范围0-255
2762
+ * @param a 可选参数,透明度分量值,取值范围0-1
2763
+ * @returns 十六进制颜色值,格式为#RRGGBB或#RRGGBBAA
2764
+ */
2765
+ static rgb2hex(r, g, b, a) {
2766
+ var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
2767
+ if (a !== void 0) {
2768
+ const alpha = Math.round(a * 255).toString(16).padStart(2, "0");
2769
+ return hex + alpha;
2770
+ }
2771
+ return hex;
2772
+ }
2773
+ static isHex(a) {
2774
+ return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(a);
2775
+ }
2776
+ static isRgb(a) {
2777
+ return /^rgb/.test(a);
2778
+ }
2779
+ static isHsl(a) {
2780
+ return /^hsl/.test(a);
2781
+ }
2782
+ static isColor(a) {
2783
+ return this.isHex(a) || this.isRgb(a) || this.isHsl(a);
2784
+ }
2785
+ static random() {
2786
+ let r = Math.floor(Math.random() * 256);
2787
+ let g = Math.floor(Math.random() * 256);
2788
+ let b = Math.floor(Math.random() * 256);
2789
+ let a = Math.random();
2790
+ return new Color(r, g, b, a);
2791
+ }
2792
+ }
2793
+ class CanvasDrawer {
2794
+ constructor(el) {
2795
+ __publicField(this, "context", null);
2796
+ if (typeof el === "string") {
2797
+ el = document.querySelector("#" + el);
2798
+ if (!el) {
2799
+ throw new Error("Element not found");
2800
+ }
2801
+ }
2802
+ if (el instanceof HTMLElement) {
2803
+ const canvas = el;
2804
+ if (canvas.getContext) {
2805
+ this.context = canvas.getContext("2d");
2806
+ } else {
2807
+ throw new Error("getContext is not available on this element");
2808
+ }
2809
+ } else {
2810
+ throw new Error("Element is not an HTMLElement");
2811
+ }
2812
+ }
2813
+ /**
2814
+ * 绘制线条
2815
+ *
2816
+ * @param start 起始坐标点
2817
+ * @param end 终止坐标点
2818
+ * @param options 绘制选项,包括线条宽度和颜色
2819
+ * @throws 当画布上下文不存在时抛出错误
2820
+ */
2821
+ drawLine({ x: startX, y: startY }, { x: endX, y: endY }, options = {}) {
2822
+ if (!this.context) {
2823
+ throw new Error("Canvas context is null or undefined");
2824
+ }
2825
+ this.context.beginPath();
2826
+ const width = options.width || 1;
2827
+ const color = options.color || "#000";
2828
+ this.context.lineWidth = width;
2829
+ this.context.strokeStyle = color;
2830
+ this.context.moveTo(startX, startY);
2831
+ this.context.lineTo(endX, endY);
2832
+ this.context.stroke();
2833
+ }
2834
+ /**
2835
+ * 绘制圆弧
2836
+ *
2837
+ * @param x 圆心x坐标
2838
+ * @param y 圆心y坐标
2839
+ * @param radius 半径
2840
+ * @param startAngle 起始角度(度)
2841
+ * @param endAngle 结束角度(度)
2842
+ * @param anticlockwise 是否逆时针绘制
2843
+ * @param isFill 是否填充
2844
+ * @param bgColor 背景颜色
2845
+ * @throws 当Canvas context为null或undefined时抛出错误
2846
+ */
2847
+ drawArc({ x, y }, radius, startAngle, endAngle, anticlockwise, isFill, bgColor) {
2848
+ if (!this.context) {
2849
+ throw new Error("Canvas context is null or undefined");
2850
+ }
2851
+ if (isFill) {
2852
+ this.context.fillStyle = bgColor;
2853
+ this.context.beginPath();
2854
+ this.context.arc(x, y, radius, MathUtils.deg2Rad(startAngle), MathUtils.deg2Rad(endAngle), anticlockwise);
2855
+ this.context.fill();
2856
+ } else {
2857
+ this.context.strokeStyle = bgColor;
2858
+ this.context.beginPath();
2859
+ this.context.arc(x, y, radius, MathUtils.deg2Rad(startAngle), MathUtils.deg2Rad(endAngle), anticlockwise);
2860
+ this.context.stroke();
2861
+ }
2862
+ }
2863
+ static createCanvas(width = 1, height = 1) {
2864
+ const canvas = document.createElement("canvas");
2865
+ if (width) {
2866
+ canvas.width = width;
2867
+ }
2868
+ if (height) {
2869
+ canvas.height = height;
2870
+ }
2871
+ return canvas;
2872
+ }
2873
+ }
2874
+ class EventDispatcher {
2875
+ constructor() {
2876
+ __publicField(this, "_listeners");
2877
+ __publicField(this, "_mutex", {});
2878
+ __publicField(this, "_context");
2879
+ }
2880
+ addEventListener(type, listener, context, mutexStatus) {
2881
+ if (this._listeners === void 0) this._listeners = {};
2882
+ this._context = context;
2883
+ const mutex = this._mutex;
2884
+ const listeners = this._listeners;
2885
+ if (listeners[type] === void 0) {
2886
+ listeners[type] = [];
2887
+ }
2888
+ if (listeners[type].indexOf(listener) === -1) {
2889
+ if (mutexStatus) {
2890
+ mutex[type] = listener;
2891
+ }
2892
+ listeners[type].push(listener);
2893
+ }
2894
+ return this;
2895
+ }
2896
+ hasEventListener(type, listener) {
2897
+ if (this._listeners === null || this._listeners === void 0) return false;
2898
+ const listeners = this._listeners;
2899
+ return listeners[type] !== void 0 && listeners[type].indexOf(listener) !== -1;
2900
+ }
2901
+ removeEventListener(type, listener) {
2902
+ if (this._listeners === void 0) return;
2903
+ const listeners = this._listeners;
2904
+ const listenerArray = listeners[type];
2905
+ if (this._mutex[type] === listener) {
2906
+ this._mutex[type] = null;
2907
+ }
2908
+ if (listenerArray !== void 0) {
2909
+ const index = listenerArray.map((d) => d.toString()).indexOf(listener.toString());
2910
+ if (index !== -1) {
2911
+ listenerArray.splice(index, 1);
2912
+ }
2913
+ }
2914
+ }
2915
+ dispatchEvent(event) {
2916
+ if (this._listeners === void 0) return;
2917
+ const listeners = this._listeners;
2918
+ const listenerArray = listeners[event.type];
2919
+ if (listenerArray !== void 0) {
2920
+ event.target = this;
2921
+ const array = listenerArray.slice(0);
2922
+ if (this._mutex[event.type] !== void 0) {
2923
+ const find = array.find((item) => item === this._mutex[event.type]);
2924
+ if (find) {
2925
+ find.call(this._context || this, event);
2926
+ return;
2927
+ }
2928
+ }
2929
+ for (let i = 0, l = array.length; i < l; i++) {
2930
+ const item = array[i];
2931
+ if (typeof item === "function") {
2932
+ item.call(this._context || this, event);
2933
+ }
2934
+ }
2935
+ }
2936
+ }
2937
+ removeAllListener() {
2938
+ this._mutex = {};
2939
+ for (const key in this._listeners) {
2940
+ this._listeners[key] = [];
2941
+ }
2942
+ }
2943
+ }
2944
+ class HashMap extends Map {
2945
+ isEmpty() {
2946
+ return this.size === 0;
2947
+ }
2948
+ _values() {
2949
+ return Array.from(this.values());
2950
+ }
2951
+ _keys() {
2952
+ return Array.from(this.keys());
2953
+ }
2954
+ _entries() {
2955
+ return Array.from(this.entries());
2956
+ }
2957
+ static fromEntries(array = []) {
2958
+ const hashMap = new HashMap();
2959
+ array.forEach((element) => {
2960
+ if (Array.isArray(element) && element.length === 2) {
2961
+ hashMap.set(element[0], element[1]);
2962
+ }
2963
+ });
2964
+ return hashMap;
2965
+ }
2966
+ }
2967
+ class WebSocketClient extends EventDispatcher {
2968
+ constructor(url = "ws://127.0.0.1:10088") {
2969
+ super();
2970
+ __publicField(this, "maxCheckTimes", 10);
2971
+ __publicField(this, "url");
2972
+ __publicField(this, "checkTimes", 0);
2973
+ __publicField(this, "connectStatus", false);
2974
+ __publicField(this, "client", null);
2975
+ this.maxCheckTimes = 10;
2976
+ this.url = url;
2977
+ this.checkTimes = 0;
2978
+ this.connect();
2979
+ this.connCheckStatus(this.maxCheckTimes);
2980
+ }
2981
+ connect() {
2982
+ this.disconnect();
2983
+ if (this.url) {
2984
+ try {
2985
+ console.info("创建ws连接>>>" + this.url);
2986
+ this.client = new WebSocket(this.url);
2987
+ if (this.client) {
2988
+ const self = this;
2989
+ this.client.onopen = function(message) {
2990
+ self.dispatchEvent({
2991
+ type: EventType.WEB_SOCKET_CONNECT,
2992
+ message
2993
+ });
2994
+ };
2995
+ this.client.onmessage = function(message) {
2996
+ self.connectStatus = true;
2997
+ self.dispatchEvent({
2998
+ type: EventType.WEB_SOCKET_MESSAGE,
2999
+ message
3000
+ });
3001
+ };
3002
+ this.client.onclose = function(message) {
3003
+ self.dispatchEvent({
3004
+ type: EventType.WEB_SOCKET_CLOSE,
3005
+ message
3006
+ });
3007
+ };
3008
+ if (this.checkTimes === this.maxCheckTimes) {
3009
+ this.client.onerror = function(message) {
3010
+ self.dispatchEvent({
3011
+ type: EventType.WEB_SOCKET_ERROR,
3012
+ message
3013
+ });
3014
+ };
3015
+ }
3016
+ }
3017
+ } catch (ex) {
3018
+ console.error("创建ws连接失败" + this.url + ":" + ex);
3019
+ }
3020
+ }
3021
+ }
3022
+ disconnect() {
3023
+ if (this.client) {
3024
+ try {
3025
+ console.log("ws断开连接" + this.url);
3026
+ this.client.close();
3027
+ this.client = null;
3028
+ } catch (ex) {
3029
+ this.client = null;
3030
+ }
3031
+ }
3032
+ }
3033
+ connCheckStatus(times) {
3034
+ if (this.checkTimes > times) return;
3035
+ setTimeout(() => {
3036
+ this.checkTimes++;
3037
+ if (this.client && this.client.readyState !== 0 && this.client.readyState !== 1) {
3038
+ this.connect();
3039
+ }
3040
+ this.connCheckStatus(times);
3041
+ }, 2e3);
3042
+ }
3043
+ send(message) {
3044
+ if (this.client && this.client.readyState === 1) {
3045
+ this.client.send(message);
3046
+ return true;
3047
+ }
3048
+ console.error(this.url + "消息发送失败:" + message);
3049
+ return false;
3050
+ }
3051
+ heartbeat() {
3052
+ setTimeout(() => {
3053
+ if (this.client && this.client.readyState === 1) {
3054
+ this.send("HeartBeat");
3055
+ }
3056
+ console.log("HeartBeat," + this.url);
3057
+ setTimeout(this.heartbeat, 3e4);
3058
+ }, 1e3);
3059
+ }
3060
+ }
3061
+ const _MqttClient = class _MqttClient extends EventDispatcher {
3062
+ constructor(url = `ws://${window.document.domain}:20007/mqtt`, config = {}) {
3063
+ super();
3064
+ __publicField(this, "state");
3065
+ __publicField(this, "url");
3066
+ __publicField(this, "context");
3067
+ __publicField(this, "options");
3068
+ __publicField(this, "client");
3069
+ __publicField(this, "topics");
3070
+ this.context = CommUtils.extend(_MqttClient.defaultContext, config);
3071
+ this.options = {
3072
+ connectTimeout: this.context.MQTT_TIMEOUTM,
3073
+ clientId: CommUtils.guid(),
3074
+ username: this.context.MQTT_USERNAME,
3075
+ password: this.context.MQTT_PASSWORD,
3076
+ clean: true
3077
+ };
3078
+ this.url = url;
3079
+ this.client = connect(this.url, this.options);
3080
+ this._onConnect();
3081
+ this._onMessage();
3082
+ this.state = 0;
3083
+ this.topics = [];
3084
+ }
3085
+ _onConnect() {
3086
+ this.client.on("connect", () => {
3087
+ this.state = 1;
3088
+ console.log("链接mqtt成功==>" + this.url);
3089
+ this.dispatchEvent({ type: EventType.MQTT_CONNECT, message: this });
3090
+ });
3091
+ this.client.on("error", (err) => {
3092
+ console.log("链接mqtt报错", err);
3093
+ this.state = -1;
3094
+ this.dispatchEvent({ type: EventType.MQTT_ERROR, message: this });
3095
+ this.client.end();
3096
+ this.client.reconnect();
3097
+ });
3098
+ }
3099
+ _onMessage() {
3100
+ this.client.on("message", (topic, message) => {
3101
+ let dataString = message;
3102
+ let data = "";
3103
+ if (message instanceof Uint8Array) {
3104
+ dataString = message.toString();
3105
+ }
3106
+ try {
3107
+ data = ObjectUtil.parse(dataString);
3108
+ } catch (error) {
3109
+ throw new Error(ErrorType.JSON_PARSE_ERROR);
3110
+ }
3111
+ this.dispatchEvent({
3112
+ type: EventType.MQTT_MESSAGE,
3113
+ message: { topic, data }
3114
+ });
3115
+ });
3116
+ }
3117
+ sendMsg(topic, msg) {
3118
+ if (!this.client.connected) {
3119
+ console.error("客户端未连接");
3120
+ return;
3121
+ }
3122
+ this.client.publish(topic, msg, { qos: 1, retain: true });
3123
+ }
3124
+ subscribe(topic) {
3125
+ this.state === 1 ? this.client.subscribe(topic, { qos: 1 }, (error, e) => {
3126
+ error instanceof Error ? console.error("订阅失败==>" + topic, error) : (this.topics = ArrayUtil.union(this.topics, topic), console.log("订阅成功==>" + topic));
3127
+ }) : this.addEventListener(EventType.MQTT_CONNECT, (res) => {
3128
+ this.client.subscribe(topic, { qos: 1 }, (error, e) => {
3129
+ error instanceof Error ? console.error("订阅失败==>" + topic, error) : (this.topics = ArrayUtil.union(this.topics, topic), console.log("订阅成功==>" + topic));
3130
+ });
3131
+ });
3132
+ return this;
3133
+ }
3134
+ unsubscribe(topic) {
3135
+ this.client.unsubscribe(topic, { qos: 1 }, (error, res) => {
3136
+ if (error instanceof Error) {
3137
+ console.error(`取消订阅失败==>${topic}`, error);
3138
+ } else {
3139
+ this.topics = ArrayUtil.difference(this.topics, topic);
3140
+ console.log(`取消订阅成功==>${topic}`);
3141
+ }
3142
+ });
3143
+ return this;
3144
+ }
3145
+ unsubscribeAll() {
3146
+ this.unsubscribe(this.topics);
3147
+ }
3148
+ unconnect() {
3149
+ this.client.end();
3150
+ this.client = null;
3151
+ this.dispatchEvent({ type: EventType.MQTT_CLOSE, message: null });
3152
+ console.log("断开mqtt成功==>" + this.url);
3153
+ }
3154
+ };
3155
+ /**
3156
+ * Creates an instance of MqttClient.
3157
+ * @param {*} config mqtt实例参数
3158
+ */
3159
+ __publicField(_MqttClient, "defaultContext", {
3160
+ MQTT_USERNAME: "iRVMS-WEB",
3161
+ MQTT_PASSWORD: "novasky888",
3162
+ MQTT_TIMEOUTM: 2e4
3163
+ });
3164
+ let MqttClient = _MqttClient;
3165
+ const _Storage = class _Storage {
3166
+ /**
3167
+ * 将键值对存储到localStorage中
3168
+ *
3169
+ * @param key 键名
3170
+ * @param value 值,默认为null
3171
+ * @param options 存储选项,可选参数
3172
+ * @param options.expires 过期时间,单位为毫秒,默认为null
3173
+ */
3174
+ static set(key, value = null, options = {}) {
3175
+ var query_key = this._getPrefixedKey(key, options);
3176
+ try {
3177
+ const { expires } = options;
3178
+ const data = { data: value };
3179
+ if (expires) {
3180
+ data.expires = expires;
3181
+ }
3182
+ localStorage.setItem(query_key, JSON.stringify(data));
3183
+ } catch (e) {
3184
+ if (console) console.warn(`Storage didn't successfully save the '{"${key}": "${value}"}' pair, because the localStorage is full.`);
3185
+ }
3186
+ }
3187
+ /**
3188
+ * 从localStorage中获取指定key的存储值
3189
+ *
3190
+ * @param key 存储键名
3191
+ * @param missing 当获取不到指定key的存储值时返回的默认值
3192
+ * @param options 其他配置选项
3193
+ * @returns 返回指定key的存储值,若获取不到则返回missing参数指定的默认值
3194
+ */
3195
+ static get(key, missing, options) {
3196
+ var query_key = this._getPrefixedKey(key, options), value;
3197
+ try {
3198
+ value = JSON.parse(localStorage.getItem(query_key) || "");
3199
+ } catch (e) {
3200
+ if (localStorage[query_key]) {
3201
+ value = { data: localStorage.getItem(query_key) };
3202
+ } else {
3203
+ value = null;
3204
+ }
3205
+ }
3206
+ if (!value) {
3207
+ return missing;
3208
+ } else if (typeof value === "object" && typeof value.data !== "undefined") {
3209
+ const expires = value.expires;
3210
+ if (expires && Date.now() > expires) {
3211
+ return missing;
3212
+ }
3213
+ return value.data;
3214
+ }
3215
+ }
3216
+ static keys() {
3217
+ const keys = [];
3218
+ var allKeys = Object.keys(localStorage);
3219
+ if (_Storage.prefix.length === 0) {
3220
+ return allKeys;
3221
+ }
3222
+ allKeys.forEach(function(key) {
3223
+ if (key.indexOf(_Storage.prefix) !== -1) {
3224
+ keys.push(key.replace(_Storage.prefix, ""));
3225
+ }
3226
+ });
3227
+ return keys;
3228
+ }
3229
+ static getAll(includeKeys) {
3230
+ var keys = _Storage.keys();
3231
+ if (includeKeys) {
3232
+ const result = [];
3233
+ keys.forEach((key) => {
3234
+ if (includeKeys.includes(key)) {
3235
+ const tempObj = {};
3236
+ tempObj[key] = _Storage.get(key, null, null);
3237
+ result.push(tempObj);
3238
+ }
3239
+ });
3240
+ return result;
3241
+ }
3242
+ return keys.map((key) => _Storage.get(key, null, null));
3243
+ }
3244
+ static remove(key, options) {
3245
+ var queryKey = this._getPrefixedKey(key, options);
3246
+ localStorage.removeItem(queryKey);
3247
+ }
3248
+ static clear(options) {
3249
+ if (_Storage.prefix.length) {
3250
+ this.keys().forEach((key) => {
3251
+ localStorage.removeItem(this._getPrefixedKey(key, options));
3252
+ });
3253
+ } else {
3254
+ localStorage.clear();
3255
+ }
3256
+ }
3257
+ };
3258
+ __publicField(_Storage, "prefix", "");
3259
+ __publicField(_Storage, "_getPrefixedKey", function(key, options) {
3260
+ options = options || {};
3261
+ if (options.noPrefix) {
3262
+ return key;
3263
+ } else {
3264
+ return _Storage.prefix + key;
3265
+ }
3266
+ });
3267
+ let Storage = _Storage;
3202
3268
  export {
3203
3269
  AjaxUtil,
3204
3270
  ArrayUtil,
@@ -3206,7 +3272,7 @@ export {
3206
3272
  AudioPlayer,
3207
3273
  BrowserUtil,
3208
3274
  CanvasDrawer,
3209
- ColorUtil,
3275
+ Color,
3210
3276
  Cookie,
3211
3277
  CoordsUtil,
3212
3278
  DateUtil,
@@ -3231,6 +3297,6 @@ export {
3231
3297
  Storage,
3232
3298
  StringUtil,
3233
3299
  UrlUtil,
3234
- CommUtil as Util,
3300
+ CommUtils as Util,
3235
3301
  WebSocketClient
3236
3302
  };