gis-common 2.2.19 → 3.1.2

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.
@@ -0,0 +1,93 @@
1
+ function EventDispatcher() {}
2
+
3
+ Object.assign(EventDispatcher.prototype, {
4
+ /**
5
+ * 添加监听器
6
+ * @param type{string}
7
+ * @param listener{function}
8
+ * @param mutexStatus{boolean}
9
+ */
10
+ addEventListener(type, listener, context, mutexStatus = false) {
11
+ if (this._listeners === undefined) this._listeners = {}
12
+ this._mutex = this._mutex || {}
13
+ this._context = context
14
+ const mutex = this._mutex
15
+ const listeners = this._listeners
16
+
17
+ if (listeners[type] === undefined) {
18
+ listeners[type] = []
19
+ }
20
+
21
+ if (listeners[type].indexOf(listener) === -1) {
22
+ // 如果启用功能独占
23
+ if (mutexStatus) {
24
+ mutex[type] = listener
25
+ }
26
+ listeners[type].push(listener)
27
+ }
28
+ return this
29
+ },
30
+
31
+ hasEventListener(type, listener) {
32
+ if (this._listeners === undefined) return false
33
+
34
+ const listeners = this._listeners
35
+
36
+ return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1
37
+ },
38
+
39
+ removeEventListener(type, listener) {
40
+ if (this._listeners === undefined) return
41
+
42
+ const listeners = this._listeners
43
+ const listenerArray = listeners[type]
44
+
45
+ // 移除指定的功能独占
46
+ if (this._mutex[type] === listener) {
47
+ this._mutex[type] = null
48
+ }
49
+
50
+ if (listenerArray !== undefined) {
51
+ const index = listenerArray.map((d) => d.toString()).indexOf(listener.toString())
52
+
53
+ if (index !== -1) {
54
+ listenerArray.splice(index, 1)
55
+ }
56
+ }
57
+ },
58
+
59
+ /**
60
+ * 派发事件
61
+ * @param event{{type: string, message: {}}}
62
+ */
63
+ dispatchEvent(event) {
64
+ if (this._listeners === undefined) return
65
+
66
+ const listeners = this._listeners
67
+ const listenerArray = listeners[event.type]
68
+
69
+ if (listenerArray !== undefined) {
70
+ event.target = this
71
+
72
+ // Make a copy, in case listeners are removed while iterating.
73
+ const array = listenerArray.slice(0)
74
+ if (this._mutex[event.type]) {
75
+ const find = array.find((item) => item === this._mutex[event.type])
76
+ find.call(this._context || this, event)
77
+ return
78
+ }
79
+ for (let i = 0, l = array.length; i < l; i++) {
80
+ array[i].call(this._context || this, event)
81
+ }
82
+ }
83
+ },
84
+
85
+ removeAllListener() {
86
+ this._mutex = {}
87
+ for (const key in this._listeners) {
88
+ this._listeners[key] = []
89
+ }
90
+ },
91
+ })
92
+
93
+ export default EventDispatcher
@@ -0,0 +1,26 @@
1
+ Object.assign(Map.prototype, {
2
+ isEmpty() {
3
+ return this.size === 0
4
+ },
5
+ _values() {
6
+ return Array.from(Map.prototype.values.call(this))
7
+ },
8
+ _keys() {
9
+ return Array.from(Map.prototype.keys.call(this))
10
+ },
11
+ _entries() {
12
+ return Array.from(Map.prototype.entries.call(this))
13
+ },
14
+ })
15
+ export default function HashMap() {
16
+ return new Map()
17
+ }
18
+ HashMap.fromEntries = function (array = []) {
19
+ const hashMap = new HashMap()
20
+ array.forEach((element) => {
21
+ if (Array.isArray(element) && element.length === 2) {
22
+ hashMap.set(element[0], element[1])
23
+ }
24
+ })
25
+ return hashMap
26
+ }
@@ -0,0 +1,108 @@
1
+ import ErrorType from "../constant/ErrorTypeConstant";
2
+ import EventType from "../constant/EventTypeConstant";
3
+ import CommUtils from "../utils/CommUtils";
4
+ import EventDispatcher from "./EventDispatcher";
5
+ import { connect } from "mqtt";
6
+ export default class MqttClient extends EventDispatcher {
7
+ /**
8
+ * Creates an instance of MqttClient.
9
+ * @param {*} config mqtt实例参数
10
+ */
11
+ constructor(config = {}) {
12
+ super();
13
+ this.context = CommUtils.extend(MqttClient.defaultContext, config);
14
+ this.options = {
15
+ connectTimeout: this.context.MQTT_TIMEOUTM,
16
+ clientId: CommUtils.generateGuid(),
17
+ username: this.context.MQTT_USERNAME,
18
+ password: this.context.MQTT_PASSWORD,
19
+ clean: true,
20
+ };
21
+ this.client = connect(this.context.MQTT_SERVICE, this.options);
22
+ this._onConnect();
23
+ this._onMessage();
24
+ MqttClient.instance = this;
25
+ }
26
+ _onConnect() {
27
+ this.client.on("connect", () => {
28
+ console.log("链接mqtt成功==>" + this.context.MQTT_SERVICE);
29
+ this.dispatchEvent({ type: EventType.MQTT_CONNECT, message: this });
30
+ });
31
+ this.client.on("error", (err) => {
32
+ console.log("链接mqtt报错", err);
33
+ this.dispatchEvent({ type: EventType.MQTT_ERROR, message: this });
34
+ this.client.end();
35
+ this.client.reconnect();
36
+ });
37
+ }
38
+ _onMessage() {
39
+ this.client.on("message", (topic, message) => {
40
+ let dataString = message;
41
+ let data = "";
42
+ if (message instanceof Uint8Array) {
43
+ dataString = message.toString();
44
+ }
45
+ try {
46
+ data = JSON.parse(dataString);
47
+ } catch (error) {
48
+ throw new Error(ErrorType.JSON_PARSE_ERROR);
49
+ }
50
+ this.dispatchEvent({
51
+ type: EventType.MQTT_MESSAGE,
52
+ message: { topic, data },
53
+ });
54
+ });
55
+ }
56
+ sendMsg(topic, msg) {
57
+ if (!this.client.connected) {
58
+ console.error("客户端未连接");
59
+ return;
60
+ }
61
+ this.client.publish(topic, msg, { qos: 1, retain: true });
62
+ }
63
+ subscribe(topic) {
64
+ this.client.subscribe(topic, { qos: 1 }, (error, res) => {
65
+ if (error instanceof Error || res.length === 0) {
66
+ console.error(`订阅失败==>${topic}`, error);
67
+ } else {
68
+ console.log(`订阅成功==>${topic}`);
69
+ }
70
+ });
71
+ return this;
72
+ }
73
+ unsubscribe(topic) {
74
+ this.client.unsubscribe(topic, { qos: 1 }, (error, res) => {
75
+ if (error instanceof Error || res.length === 0) {
76
+ console.error(`取消订阅失败==>${topic}`, error);
77
+ } else {
78
+ console.log(`取消订阅成功==>${topic}`);
79
+ }
80
+ });
81
+ return this;
82
+ }
83
+ unconnect() {
84
+ this.client.end();
85
+ this.client = null;
86
+ this.dispatchEvent({ type: EventType.MQTT_CLOSE, message: null });
87
+ console.log("断开mqtt成功==>" + this.context.MQTT_SERVICE);
88
+ }
89
+ /**
90
+ * @description 获取并冻结mqtt实例
91
+ * @static
92
+ * @param {*} [config={}]
93
+ * @returns {MqttClient}
94
+ */
95
+ static getInstance(config = {}) {
96
+ if (MqttClient.instance) {
97
+ return Object.freeze(MqttClient.instance);
98
+ } else {
99
+ return Object.freeze(new MqttClient(config));
100
+ }
101
+ }
102
+ }
103
+ MqttClient.defaultContext = {
104
+ MQTT_TIMEOUTM: 20000,
105
+ MQTT_USERNAME: "iRVMS-WEB",
106
+ MQTT_PASSWORD: "novasky888",
107
+ MQTT_SERVICE: `ws://${window.document.domain}:20007/mqtt`,
108
+ };
@@ -0,0 +1,104 @@
1
+ import EventType from '../constant/EventTypeConstant'
2
+ import EventDispatcher from './EventDispatcher'
3
+ export default class WebSocketClient extends EventDispatcher {
4
+ constructor(url = 'ws://127.0.0.1:10088') {
5
+ super()
6
+ this.maxCheckTimes = 10
7
+ this.url = url
8
+ this.checkTimes = 0
9
+ this.connectStatus = false
10
+ this.connect()
11
+ this.connCheckStatus(this.maxCheckTimes)
12
+ // this.heartbeat()
13
+ WebSocketClient.instance = this
14
+ }
15
+ connect() {
16
+ this.disconnect()
17
+ if (this.url) {
18
+ try {
19
+ console.info('创建ws连接>>>' + this.url)
20
+ this.client = new WebSocket(this.url)
21
+ if (this.client) {
22
+ const self = this
23
+ this.client.onopen = function (message) {
24
+ self.dispatchEvent({
25
+ type: EventType.WEB_SOCKET_CONNECT,
26
+ message,
27
+ })
28
+ }
29
+ this.client.onmessage = function (message) {
30
+ self.connectStatus = true
31
+ self.dispatchEvent({
32
+ type: EventType.WEB_SOCKET_MESSAGE,
33
+ message,
34
+ })
35
+ }
36
+ this.client.onclose = function (message) {
37
+ self.dispatchEvent({
38
+ type: EventType.WEB_SOCKET_CLOSE,
39
+ message,
40
+ })
41
+ }
42
+ if (this.checkTimes === this.maxCheckTimes) {
43
+ this.client.onerror = function (message) {
44
+ self.dispatchEvent({
45
+ type: EventType.WEB_SOCKET_ERROR,
46
+ message,
47
+ })
48
+ }
49
+ }
50
+ }
51
+ } catch (ex) {
52
+ console.error('创建ws连接失败' + this.url + ':' + ex)
53
+ }
54
+ }
55
+ }
56
+ disconnect() {
57
+ if (this.client) {
58
+ try {
59
+ console.log('ws断开连接' + this.url)
60
+ this.client.close()
61
+ this.client = null
62
+ } catch (ex) {
63
+ this.client = null
64
+ }
65
+ }
66
+ }
67
+ connCheckStatus(times) {
68
+ if (this.checkTimes > times) return
69
+ setTimeout(() => {
70
+ this.checkTimes++
71
+ if (this.client && this.client.readyState !== 0 && this.client.readyState !== 1) {
72
+ this.connect()
73
+ }
74
+ this.connCheckStatus(times)
75
+ }, 2000)
76
+ }
77
+ send(message) {
78
+ if (this.client && this.client.readyState === 1) {
79
+ this.client.send(message)
80
+ return true
81
+ }
82
+ console.error(this.url + '消息发送失败:' + message)
83
+ return false
84
+ }
85
+ heartbeat() {
86
+ setTimeout(() => {
87
+ if (this.client && this.client.readyState === 1) {
88
+ this.send('HeartBeat')
89
+ }
90
+ console.log('HeartBeat,' + this.url)
91
+ setTimeout(this.heartbeat, 30000)
92
+ }, 1000)
93
+ }
94
+ static getInstance() {
95
+ if (WebSocketClient.instance) {
96
+ return WebSocketClient.instance
97
+ } else {
98
+ return Object.freeze(new WebSocketClient())
99
+ }
100
+ }
101
+ static get _instance() {
102
+ return this.getInstance()
103
+ }
104
+ }
@@ -0,0 +1,73 @@
1
+ import ErrorType from "../constant/ErrorTypeConstant";
2
+ export default class WebStorage {
3
+ constructor(type = 1) {
4
+ this.cacheType = type;
5
+ if (type === 1) {
6
+ this.storage = window.localStorage;
7
+ } else if (type === 2) {
8
+ this.storage = window.sessionStorage;
9
+ } else {
10
+ throw new Error(ErrorType.PARAMETER_ERROR);
11
+ }
12
+ }
13
+
14
+ /**
15
+ * 设置带过期时间的LocalStorage
16
+ * @param key 缓存关键字
17
+ * @param value 缓存对象,可以是任意类型
18
+ * @param expired 以秒为单位,默认为1小时
19
+ * @returns {Object}
20
+ */
21
+ setItem(key, value, expired) {
22
+ const tempObj = { key, value };
23
+ if (this.cacheType === 1) {
24
+ const currTime = Date.now();
25
+ if (expired) {
26
+ tempObj.expired = currTime + expired * 1000;
27
+ }
28
+ }
29
+ this.storage[key] = JSON.stringify(tempObj);
30
+ return tempObj;
31
+ }
32
+
33
+ /***
34
+ * 获取带过期时间的缓存
35
+ * @param key
36
+ * @returns {null|*}
37
+ */
38
+ getItem(key) {
39
+ const storageData = this.storage.getItem(key) || null;
40
+ const tempObj = JSON.parse(storageData) || {};
41
+ if (this.cacheType === 1) {
42
+ const expired = tempObj.expired || Date.now();
43
+ if (Date.now() > expired) {
44
+ this.remove(key);
45
+ return null;
46
+ }
47
+ }
48
+ return tempObj.value;
49
+ }
50
+
51
+ /**
52
+ * 移除指定缓存
53
+ * @param keys
54
+ */
55
+ remove(keys) {
56
+ if (keys) {
57
+ if (keys.indexOf(",") > -1) {
58
+ keys.split(",").forEach(key => {
59
+ this.storage.removeItem(key);
60
+ });
61
+ } else {
62
+ this.storage.removeItem(keys);
63
+ }
64
+ }
65
+ }
66
+
67
+ /**
68
+ * 移出全部缓存
69
+ */
70
+ clear() {
71
+ this.storage.clear();
72
+ }
73
+ }
package/src/index.js ADDED
@@ -0,0 +1,10 @@
1
+ export * from './utils'
2
+ export * from './constant'
3
+ export { default as AudioPlayer } from './core/AudioPlayer'
4
+ export { default as CanvasDrawer } from './core/CanvasDrawer'
5
+ // export { default as ElQuery } from './core/ElQuery'
6
+ export { default as EventDispatcher } from './core/EventDispatcher'
7
+ export { default as HashMap } from './core/HashMap'
8
+ export { default as WebSocketClient } from './core/WebSocketClient'
9
+ export { default as WebStorage } from './core/WebStorage'
10
+ export { default as DevicePixelRatio } from './core/DevicePixelRatio'
@@ -0,0 +1,78 @@
1
+ export default {
2
+ /**
3
+ * 多属性的动画函数
4
+ * @param {*} ele 需要运动的节点
5
+ * @param {*} attr_options 传入的是一个需要运动的属性包括运动的目标值,操作的节点属性
6
+ * @param {*} timefn 运动的形式,默认是缓冲运动
7
+ * @param {*} speed 运动的速度
8
+ */
9
+ animate(ele, attr_options, callback, timefn = "swing", speed = 5) {
10
+ for (var attr in attr_options) {
11
+ attr_options[attr] = {
12
+ target:
13
+ attr === "opacity"
14
+ ? parseInt(attr_options[attr] * 100)
15
+ : attr_options[attr],
16
+ // 需要计算得到
17
+ iNow:
18
+ attr === "opacity"
19
+ ? parseInt(getComputedStyle(ele)[attr] * 100)
20
+ : parseInt(getComputedStyle(ele)[attr])
21
+ };
22
+ }
23
+
24
+ // 判断是不是匀速运动
25
+ if (timefn === "liner") {
26
+ speed =
27
+ attr_options[attr].iNow < attr_options[attr].target
28
+ ? Math.abs(speed)
29
+ : -Math.abs(speed);
30
+ }
31
+ // 为了防止每个节点的定时器冲突,每次进入的时候我们需要先清理下节点的定时器
32
+ clearInterval(ele.timer);
33
+ // 然后再去设置定时器
34
+ ele.timer = setInterval(function() {
35
+ // 因为是多属性运动,我们首先循环遍历每一个属性
36
+ for (var attr in attr_options) {
37
+ var target = attr_options[attr].target;
38
+
39
+ var iNow = attr_options[attr].iNow;
40
+
41
+ // 计算speed 判断是不是缓冲运动
42
+ if (timefn === "swing") {
43
+ speed = (target - iNow) / 20;
44
+ // 为了防止速度无法达到一个整数
45
+ speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
46
+ }
47
+
48
+ // 运动之中条件的判断
49
+ if (Math.abs(target - iNow) <= Math.abs(speed)) {
50
+ if (attr === "opacity") {
51
+ ele.style[attr] = target / 100;
52
+ } else {
53
+ ele.style[attr] = target + "px";
54
+ }
55
+
56
+ // 每次一个属性运动完成之后我们就直接将它删除
57
+ delete attr_options[attr];
58
+
59
+ // 每次都去循环看一下还有没有属性需要操作
60
+ for (var num in attr_options) {
61
+ return false;
62
+ }
63
+ // 清理定时器 因为我们是一个定时器绑定多个属性操作所以我们需要保证所有的属性都完成之后我们才可以将定时器清除
64
+ clearInterval(ele.timer);
65
+ // 等结束之后我们需要判断这个回到函数是函数我们就回调
66
+ typeof callback === "function" ? callback() : "";
67
+ } else {
68
+ attr_options[attr].iNow += speed;
69
+ if (attr === "opacity") {
70
+ ele.style[attr] = attr_options[attr].iNow / 100;
71
+ } else {
72
+ ele.style[attr] = attr_options[attr].iNow + "px";
73
+ }
74
+ }
75
+ }
76
+ }, 30);
77
+ }
78
+ };
@@ -0,0 +1,82 @@
1
+ import CommUtils from './CommUtils'
2
+ /**
3
+ * 分组函数,暂时无法进行多层分组。如有需要可以使用groupBy+map+flat方法打平
4
+ * @param {*} f
5
+ */
6
+ Array.prototype.groupBy = function (f) {
7
+ var groups = {}
8
+ this.forEach(function (o) {
9
+ var group = JSON.stringify(f(o))
10
+ groups[group] = groups[group] || []
11
+ groups[group].push(o)
12
+ })
13
+ return Object.keys(groups).map((group) => groups[group])
14
+ }
15
+ /**
16
+ * 用于数组对象去重
17
+ * 单纯数组可用[...new Set(arr)]
18
+ * @param {*} f
19
+ */
20
+ Array.prototype.distinct = function (f = (d) => d) {
21
+ const arr = [],
22
+ obj = {}
23
+ this.forEach((item) => {
24
+ const val = f(item)
25
+ !obj[val] && (obj[val] = arr.push(item))
26
+ })
27
+ return arr
28
+ }
29
+ Array.prototype.max = function () {
30
+ return Math.max.apply({}, this)
31
+ }
32
+ Array.prototype.min = function () {
33
+ return Math.min.apply({}, this)
34
+ }
35
+ Array.prototype.sum = function () {
36
+ return this.length > 0 ? this.reduce((prev = 0, curr = 0) => prev + curr) : 0
37
+ }
38
+ Array.prototype.avg = function () {
39
+ return this.length ? this.sum() / this.length : 0
40
+ }
41
+ Array.prototype.desc = function (f = (d) => d) {
42
+ return this.sort((n1, n2) => f(n2) - f(n1))
43
+ }
44
+ Array.prototype.asc = function (f = (d) => d) {
45
+ return this.sort((n1, n2) => f(n1) - f(n2))
46
+ }
47
+ Array.prototype.clear = function () {
48
+ this.length = 0
49
+ return this
50
+ }
51
+ export default {
52
+ asArray(obj) {
53
+ return CommUtils.isEmpty(obj) ? [] : Array.isArray(obj) ? obj : [obj]
54
+ },
55
+ generateArray(length) {
56
+ return [...new Array(length).keys()]
57
+ },
58
+ union(...args) {
59
+ let res = []
60
+ args.forEach((arg) => {
61
+ if (Array.isArray(arg)) {
62
+ res = res.concat(arg.filter((v) => !res.includes(v)))
63
+ }
64
+ })
65
+ return res
66
+ },
67
+ intersection(...args) {
68
+ let res = args[0] || []
69
+ args.forEach((arg) => {
70
+ if (Array.isArray(arg)) {
71
+ res = res.filter((v) => arg.includes(v))
72
+ }
73
+ })
74
+ return res
75
+ },
76
+ unionAll(...args) {
77
+ return [...args].flat().filter((d) => !!d)
78
+ },
79
+ difference(...args) {
80
+ return this.union(...args).filter((d) => !this.intersection(...args).includes(d))
81
+ },
82
+ }
@@ -0,0 +1,112 @@
1
+ import GeoUtils from './GeoUtils'
2
+ import CommUtils from './CommUtils'
3
+ import ErrorType from '../constant/ErrorTypeConstant'
4
+ import StringUtils from './StringUtils'
5
+ export default {
6
+ notNull(data) {
7
+ if (CommUtils.isEmpty(data)) {
8
+ throw Error('不能为空:>>>' + data)
9
+ }
10
+ },
11
+ legalLnglat(lng, lat) {
12
+ if (!GeoUtils.isLnglat(lng, lat)) {
13
+ throw Error(ErrorType.COORDINATE_ERROR)
14
+ }
15
+ },
16
+ contain(str, ...args) {
17
+ let res = false
18
+ const len = args.length || 0
19
+ for (let i = 0, l = len; i < l; i++) {
20
+ res = str.indexOf(args[i]) >= 0
21
+ }
22
+ if (res) {
23
+ throw Error(ErrorType.STRING_CHECK_LOSS)
24
+ }
25
+ },
26
+ verify: {
27
+ array(data) {
28
+ if (CommUtils.getDataType(data) !== 'Array') {
29
+ throw Error(ErrorType.PARAMETER_ERROR_ARRAY + ':>>>' + data)
30
+ }
31
+ },
32
+ function(data) {
33
+ if (CommUtils.getDataType(data) !== 'Function') {
34
+ throw Error(ErrorType.PARAMETER_ERROR_FUNCTION + ':>>>' + data)
35
+ }
36
+ },
37
+ object(data) {
38
+ if (CommUtils.getDataType(data) !== 'Object') {
39
+ throw Error(ErrorType.PARAMETER_ERROR_OBJECT + ':>>>' + data)
40
+ }
41
+ },
42
+ },
43
+ legalJSON(data) {
44
+ try {
45
+ JSON.parse(data)
46
+ } catch (err) {
47
+ throw Error(ErrorType.JSON_PARSE_ERROR + ':>>>' + data)
48
+ }
49
+ },
50
+ legalData(data, type) {
51
+ const bool = StringUtils.checkStr(data, type)
52
+ let typename = ''
53
+ switch (type) {
54
+ case 'phone':
55
+ typename = '电话'
56
+ break
57
+ case 'tel':
58
+ typename = '座机'
59
+ break
60
+ case 'card':
61
+ typename = '身份证'
62
+ break
63
+ case 'pwd':
64
+ typename = '密码'
65
+ break
66
+ case 'postal':
67
+ typename = '邮政编码'
68
+ break
69
+ case 'QQ':
70
+ typename = 'QQ'
71
+ break
72
+ case 'email':
73
+ typename = '邮箱'
74
+ break
75
+ case 'money':
76
+ typename = '金额'
77
+ break
78
+ case 'URL':
79
+ typename = '网址'
80
+ break
81
+ case 'IP':
82
+ typename = 'IP'
83
+ break
84
+ case 'date':
85
+ typename = '日期时间'
86
+ break
87
+ case 'number':
88
+ typename = '数字'
89
+ break
90
+ case 'english':
91
+ typename = '英文'
92
+ break
93
+ case 'chinese':
94
+ typename = '中文'
95
+ break
96
+ case 'lower':
97
+ typename = '小写'
98
+ break
99
+ case 'upper':
100
+ typename = '大写'
101
+ break
102
+ case 'HTML':
103
+ typename = 'HTML标记'
104
+ break
105
+ default:
106
+ break
107
+ }
108
+ if (!bool) {
109
+ throw Error(ErrorType.PARAMETER_ERROR + ':>>>不是' + typename)
110
+ }
111
+ },
112
+ }