@raruto/leaflet-elevation 2.3.4 → 2.4.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/src/utils.js CHANGED
@@ -1,163 +1,203 @@
1
- /**
2
- * TODO: exget computed styles of theese values from actual "CSS vars"
3
- **/
4
- export const Colors = {
5
- 'lightblue': { area: '#3366CC', alpha: 0.45, stroke: '#3366CC' },
6
- 'magenta' : { area: '#FF005E' },
7
- 'yellow' : { area: '#FF0' },
8
- 'purple' : { area: '#732C7B' },
9
- 'steelblue': { area: '#4682B4' },
10
- 'red' : { area: '#F00' },
11
- 'lime' : { area: '#9CC222', line: '#566B13' }
12
- };
13
-
14
- const SEC = 1000;
15
- const MIN = SEC * 60;
16
- const HOUR = MIN * 60;
17
- const DAY = HOUR * 24;
18
-
19
- export function resolveURL(src, baseUrl) {
20
- return (new URL(src, (src.startsWith('../') || src.startsWith('./')) ? baseUrl : undefined)).toString()
21
- };
22
-
23
- /**
24
- * Convert a time (millis) to a human readable duration string (%Dd %H:%M'%S")
25
- */
26
- export function formatTime(t) {
27
- let d = Math.floor(t / DAY);
28
- let h = Math.floor( (t - d * DAY) / HOUR);
29
- let m = Math.floor( (t - d * DAY - h * HOUR) / MIN);
30
- let s = Math.round( (t - d * DAY - h * HOUR - m * MIN) / SEC);
31
- if ( s === 60 ) { m++; s = 0; }
32
- if ( m === 60 ) { h++; m = 0; }
33
- if ( h === 24 ) { d++; h = 0; }
34
- return (d ? d + "d " : '') + h.toString().padStart(2, 0) + ':' + m.toString().padStart(2, 0) + "'" + s.toString().padStart(2, 0) + '"';
35
- }
36
-
37
- /**
38
- * Convert a time (millis) to human readable date string (dd-mm-yyyy hh:mm:ss)
39
- */
40
- export function formatDate(format) {
41
- if (!format) {
42
- return (time) => (new Date(time)).toLocaleString().replaceAll('/', '-').replaceAll(',', ' ');
43
- } else if (format == 'time') {
44
- return (time) => (new Date(time)).toLocaleTimeString();
45
- } else if (format == 'date') {
46
- return (time) => (new Date(time)).toLocaleDateString();
47
- }
48
- return (time) => format(time);
49
- }
50
-
51
- /**
52
- * Generate download data event.
53
- */
54
- export function saveFile(dataURI, fileName) {
55
- let a = create('a', '', { href: dataURI, target: '_new', download: fileName || "", style: "display:none;" });
56
- let b = document.body;
57
- b.appendChild(a);
58
- a.click();
59
- b.removeChild(a);
60
- }
61
-
62
-
63
- /**
64
- * Convert SVG Path into Path2D and then update canvas
65
- */
66
- export function drawCanvas(ctx, path) {
67
- path.classed('canvas-path', true);
68
-
69
- ctx.beginPath();
70
- ctx.moveTo(0, 0);
71
- let p = new Path2D(path.attr('d'));
72
-
73
- ctx.strokeStyle = path.attr('stroke');
74
- ctx.fillStyle = path.attr('fill');
75
- ctx.lineWidth = 1.25;
76
- ctx.globalCompositeOperation = 'source-over';
77
-
78
- // stroke opacity
79
- ctx.globalAlpha = path.attr('stroke-opacity') || 0.3;
80
- ctx.stroke(p);
81
-
82
- // fill opacity
83
- ctx.globalAlpha = path.attr('fill-opacity') || 0.45;
84
- ctx.fill(p);
85
-
86
- ctx.globalAlpha = 1;
87
-
88
- ctx.closePath();
89
- }
90
-
91
- /**
92
- * Loop and extract GPX Extensions handled by "@tmcw/toGeoJSON" (eg. "coordinateProperties" > "times")
93
- */
94
- export function coordPropsToMeta(coordProps, name, parser) {
95
- return coordProps && (({props, point, id, isMulti }) => {
96
- if (props) {
97
- for (const key of coordProps) {
98
- if (key in props) {
99
- point.meta[name] = (parser || parseNumeric).call(this, (isMulti ? props[key][isMulti] : props[key]), id);
100
- break;
101
- }
102
- }
103
- }
104
- });
105
- }
106
-
107
- /**
108
- * Extract numeric property (id) from GeoJSON object
109
- */
110
- export const parseNumeric = (property, id) => parseInt((typeof property === 'object' ? property[id] : property));
111
-
112
- /**
113
- * Extract datetime property (id) from GeoJSON object
114
- */
115
- export const parseDate = (property, id) => new Date(Date.parse((typeof property === 'object' ? property[id] : property)));
116
-
117
- /**
118
- * A little bit shorter than L.DomUtil
119
- */
120
- export const addClass = (n, str) => n && str.split(" ").every(s => s && L.DomUtil.addClass(n, s));
121
- export const removeClass = (n, str) => n && str.split(" ").every(s => s && L.DomUtil.removeClass(n, s));
122
- export const toggleClass = (n, str, cond) => (cond ? addClass : removeClass)(n, str);
123
- export const replaceClass = (n, rem, add) => (rem && removeClass(n, rem)) || (add && addClass(n, add));
124
- export const style = (n, k, v) => (typeof v === "undefined" && L.DomUtil.getStyle(n, k)) || n.style.setProperty(k, v);
125
- export const toggleStyle = (n, k, v, cond) => style(n, k, cond ? v : '');
126
- export const setAttributes = (n, attrs) => { for (let k in attrs) { n.setAttribute(k, attrs[k]); } };
127
- export const toggleEvent = (el, e, fn, cond) => el[cond ? 'on' : 'off'](e, fn);
128
- export const create = (tag, str, attrs, n) => { let elem = L.DomUtil.create(tag, str || ""); if (attrs) setAttributes(elem, attrs); if (n) append(n, elem); return elem; };
129
- export const append = (n, c) => n.appendChild(c);
130
- export const insert = (n, c, pos) => n.insertAdjacentElement(pos, c);
131
- export const select = (str, n) => (n || document).querySelector(str);
132
- export const each = (obj, fn) => { for (let i in obj) fn(obj[i], i); };
133
- export const randomId = () => Math.random().toString(36).substr(2, 9);
134
-
135
- /**
136
- * TODO: use generators instead? (ie. "yield")
137
- */
138
- export const iMax = (iVal, max = -Infinity) => (iVal > max ? iVal : max);
139
- export const iMin = (iVal, min = +Infinity) => (iVal < min ? iVal : min);
140
- export const iAvg = (iVal, avg = 0, idx = 1) => (iVal + avg * (idx - 1)) / idx;
141
- export const iSum = (iVal, sum = 0) => iVal + sum;
142
-
143
- /**
144
- * Alias for some leaflet core functions
145
- */
146
- export const { on, off } = L.DomEvent;
147
- export const { throttle, wrapNum } = L.Util;
148
- export const { hasClass } = L.DomUtil;
149
-
150
- /**
151
- * Limit floating point precision
152
- */
153
- export const round = L.Util.formatNum;
154
-
155
- /**
156
- * Limit a number between min / max values
157
- */
158
- export const clamp = (val, range) => range ? (val < range[0] ? range[0] : val > range[1] ? range[1] : val) : val;
159
-
160
- /**
161
- * Limit a delta difference between two values
162
- */
163
- export const wrapDelta = (curr, prev, deltaMax) => Math.abs(curr - prev) > deltaMax ? prev + deltaMax * Math.sign(curr - prev) : curr;
1
+ /**
2
+ * TODO: exget computed styles of theese values from actual "CSS vars"
3
+ **/
4
+ export const Colors = {
5
+ 'lightblue': { area: '#3366CC', alpha: 0.45, stroke: '#3366CC' },
6
+ 'magenta' : { area: '#FF005E' },
7
+ 'yellow' : { area: '#FF0' },
8
+ 'purple' : { area: '#732C7B' },
9
+ 'steelblue': { area: '#4682B4' },
10
+ 'red' : { area: '#F00' },
11
+ 'lime' : { area: '#9CC222', line: '#566B13' }
12
+ };
13
+
14
+ const SEC = 1000;
15
+ const MIN = SEC * 60;
16
+ const HOUR = MIN * 60;
17
+ const DAY = HOUR * 24;
18
+
19
+ export function resolveURL(src, baseUrl) {
20
+ return (new URL(src, (src.startsWith('../') || src.startsWith('./')) ? baseUrl : undefined)).toString()
21
+ };
22
+
23
+ /**
24
+ * Convert a time (millis) to a human readable duration string (%Dd %H:%M'%S")
25
+ */
26
+ export function formatTime(t) {
27
+ let d = Math.floor(t / DAY);
28
+ let h = Math.floor( (t - d * DAY) / HOUR);
29
+ let m = Math.floor( (t - d * DAY - h * HOUR) / MIN);
30
+ let s = Math.round( (t - d * DAY - h * HOUR - m * MIN) / SEC);
31
+ if ( s === 60 ) { m++; s = 0; }
32
+ if ( m === 60 ) { h++; m = 0; }
33
+ if ( h === 24 ) { d++; h = 0; }
34
+ return (d ? d + "d " : '') + h.toString().padStart(2, 0) + ':' + m.toString().padStart(2, 0) + "'" + s.toString().padStart(2, 0) + '"';
35
+ }
36
+
37
+ /**
38
+ * Convert a time (millis) to human readable date string (dd-mm-yyyy hh:mm:ss)
39
+ */
40
+ export function formatDate(format) {
41
+ if (!format) {
42
+ return (time) => (new Date(time)).toLocaleString().replaceAll('/', '-').replaceAll(',', ' ');
43
+ } else if (format == 'time') {
44
+ return (time) => (new Date(time)).toLocaleTimeString();
45
+ } else if (format == 'date') {
46
+ return (time) => (new Date(time)).toLocaleDateString();
47
+ }
48
+ return (time) => format(time);
49
+ }
50
+
51
+ /**
52
+ * Generate download data event.
53
+ */
54
+ export function saveFile(dataURI, fileName) {
55
+ let a = create('a', '', { href: dataURI, target: '_new', download: fileName || "", style: "display:none;" });
56
+ let b = document.body;
57
+ b.appendChild(a);
58
+ a.click();
59
+ b.removeChild(a);
60
+ }
61
+
62
+
63
+ /**
64
+ * Convert SVG Path into Path2D and then update canvas
65
+ */
66
+ export function drawCanvas(ctx, path) {
67
+ path.classed('canvas-path', true);
68
+
69
+ ctx.beginPath();
70
+ ctx.moveTo(0, 0);
71
+ let p = new Path2D(path.attr('d'));
72
+
73
+ ctx.strokeStyle = path.attr('stroke');
74
+ ctx.fillStyle = path.attr('fill');
75
+ ctx.lineWidth = 1.25;
76
+ ctx.globalCompositeOperation = 'source-over';
77
+
78
+ // stroke opacity
79
+ ctx.globalAlpha = path.attr('stroke-opacity') || 0.3;
80
+ ctx.stroke(p);
81
+
82
+ // fill opacity
83
+ ctx.globalAlpha = path.attr('fill-opacity') || 0.45;
84
+ ctx.fill(p);
85
+
86
+ ctx.globalAlpha = 1;
87
+
88
+ ctx.closePath();
89
+ }
90
+
91
+ /**
92
+ * Loop and extract GPX Extensions handled by "@tmcw/toGeoJSON" (eg. "coordinateProperties" > "times")
93
+ */
94
+ export function coordPropsToMeta(coordProps, name, parser) {
95
+ return coordProps && (({props, point, id, isMulti }) => {
96
+ if (props) {
97
+ for (const key of coordProps) {
98
+ if (key in props) {
99
+ point.meta[name] = (parser || parseNumeric).call(this, (isMulti ? props[key][isMulti] : props[key]), id);
100
+ break;
101
+ }
102
+ }
103
+ }
104
+ });
105
+ }
106
+
107
+ /**
108
+ * Extract numeric property (id) from GeoJSON object
109
+ */
110
+ export const parseNumeric = (property, id) => parseInt((typeof property === 'object' ? property[id] : property));
111
+
112
+ /**
113
+ * Extract datetime property (id) from GeoJSON object
114
+ */
115
+ export const parseDate = (property, id) => new Date(Date.parse((typeof property === 'object' ? property[id] : property)));
116
+
117
+ /**
118
+ * A little bit shorter than L.DomUtil
119
+ */
120
+ export const addClass = (n, str) => n && str.split(" ").every(s => s && L.DomUtil.addClass(n, s));
121
+ export const removeClass = (n, str) => n && str.split(" ").every(s => s && L.DomUtil.removeClass(n, s));
122
+ export const toggleClass = (n, str, cond) => (cond ? addClass : removeClass)(n, str);
123
+ export const replaceClass = (n, rem, add) => (rem && removeClass(n, rem)) || (add && addClass(n, add));
124
+ export const style = (n, k, v) => (typeof v === "undefined" && L.DomUtil.getStyle(n, k)) || n.style.setProperty(k, v);
125
+ export const toggleStyle = (n, k, v, cond) => style(n, k, cond ? v : '');
126
+ export const setAttributes = (n, attrs) => { for (let k in attrs) { n.setAttribute(k, attrs[k]); } };
127
+ export const toggleEvent = (el, e, fn, cond) => el[cond ? 'on' : 'off'](e, fn);
128
+ export const create = (tag, str, attrs, n) => { let elem = L.DomUtil.create(tag, str || ""); if (attrs) setAttributes(elem, attrs); if (n) append(n, elem); return elem; };
129
+ export const append = (n, c) => n.appendChild(c);
130
+ export const insert = (n, c, pos) => n.insertAdjacentElement(pos, c);
131
+ export const select = (str, n) => (n || document).querySelector(str);
132
+ export const each = (obj, fn) => { for (let i in obj) fn(obj[i], i); };
133
+ export const randomId = () => Math.random().toString(36).substr(2, 9);
134
+
135
+ /**
136
+ * TODO: use generators instead? (ie. "yield")
137
+ */
138
+ export const iMax = (iVal, max = -Infinity) => (iVal > max ? iVal : max);
139
+ export const iMin = (iVal, min = +Infinity) => (iVal < min ? iVal : min);
140
+ export const iAvg = (iVal, avg = 0, idx = 1) => (iVal + avg * (idx - 1)) / idx;
141
+ export const iSum = (iVal, sum = 0) => iVal + sum;
142
+
143
+ /**
144
+ * Alias for some leaflet core functions
145
+ */
146
+ export const { on, off } = L.DomEvent;
147
+ export const { throttle, wrapNum } = L.Util;
148
+ export const { hasClass } = L.DomUtil;
149
+
150
+ /**
151
+ * Limit floating point precision
152
+ */
153
+ export const round = L.Util.formatNum;
154
+
155
+ /**
156
+ * Limit a number between min / max values
157
+ */
158
+ export const clamp = (val, range) => range ? (val < range[0] ? range[0] : val > range[1] ? range[1] : val) : val;
159
+
160
+ /**
161
+ * Limit a delta difference between two values
162
+ */
163
+ export const wrapDelta = (curr, prev, deltaMax) => Math.abs(curr - prev) > deltaMax ? prev + deltaMax * Math.sign(curr - prev) : curr;
164
+
165
+ /**
166
+ * A deep copy implementation that takes care of correct prototype chain and cycles, references
167
+ *
168
+ * @see https://web.dev/structured-clone/#features-and-limitations
169
+ */
170
+ export function cloneDeep(o, skipProps = [], cache = []) {
171
+ switch(!o || typeof o) {
172
+ case 'object':
173
+ const hit = cache.filter(c => o === c.original)[0];
174
+ if (hit) return hit.copy; // handle circular structures
175
+ const copy = Array.isArray(o) ? [] : Object.create(Object.getPrototypeOf(o));
176
+ cache.push({ original: o, copy });
177
+ Object
178
+ .getOwnPropertyNames(o)
179
+ .forEach(function (prop) {
180
+ const propdesc = Object.getOwnPropertyDescriptor(o, prop);
181
+ Object.defineProperty(
182
+ copy,
183
+ prop,
184
+ propdesc.get || propdesc.set
185
+ ? propdesc // just copy accessor properties
186
+ : { // deep copy data properties
187
+ writable: propdesc.writable,
188
+ configurable: propdesc.configurable,
189
+ enumerable: propdesc.enumerable,
190
+ value: skipProps.includes(prop) ? propdesc.value : cloneDeep(propdesc.value, skipProps, cache),
191
+ }
192
+ );
193
+ });
194
+ return copy;
195
+ case 'function':
196
+ case 'symbol':
197
+ console.warn('cloneDeep: ' + typeof o + 's not fully supported:', o);
198
+ case true:
199
+ // null, undefined or falsy primitive
200
+ default:
201
+ return o;
202
+ }
203
+ }