-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebSystemObject.js
4413 lines (3807 loc) · 136 KB
/
WebSystemObject.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'fs';
export class WebSystemObject extends Object {
// Poner esto a true si vas a depurar (via debugMode).
static #apiDebugVerboseMode = true;
// Clase básica de trabajo, poner aquí las funciones más generales
// equality under permissive range.
static epsilon = Math.pow(2, -52);
// @property lastId: Number
// Last unique ID used by [`stamp()`](#util-stamp)
static lastId = 0;
// static $ = document.querySelector.bind(document);
constructor(multimedia = false) {
super();
if (multimedia) {
this.initializeMedia(); // La reasignación de eventos necesita validación.
}
}
// some thing like a class method...
// debug time
static get debugMode() {
return WebSystemObject.#apiDebugVerboseMode;
}
static set debugMode(m) {
WebSystemObject.#apiDebugVerboseMode = m;
}
// modo productivo, quieto pancho... quieto (nada de mensajes en la consola).
get quiet() {
return !WebSystemObject.debugMode;
}
set quiet(m) {
WebSystemObject.debugMode = !m;
}
// Obtener elegantemente el valor de una propiedad profunda anidada de nun objeto.
getNestedProp(key, obj = this) {
return key.split('.').reduce((o, x) =>
(typeof o == 'undefined' || o === null) ? o : o[x]
, obj);
}
get maxint() {
Math.pow(2, 53);
}
get pausedAudio() {
return this.audio.paused;
}
get muteAudio() {
return this.audio.muted = value;
}
set muteAudio(value) {
try {
this.audio.muted = value;
console.log('Muting audio ' + this.audio);
} catch (err) {
console.log('Failed to muting, error: ' + err);
}
}
// medias
get speakPaused() {
return this.synth.paused;
}
set speakPaused(value) {
if (value !== this.synth.paused) {
if (value) {
this.speakPause();
} else {
this.speakResume();
}
} // is ok
}
// @function stamp(obj: Object, onFieldName: String): Number
asString() {
return JSON.stringifyObject(this);
}
asJson(argumento) {
var className = this.GetClass(argumento);
if (className === 'Boolean') {
return '' + argumento;
} else if (className === 'Number') {
return window.isNaN(argumento) ? 'null' : '' + argumento;
} else if (className === 'String') {
var escapedStr = '' + argumento;
return '"' + escapedStr.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"';
}
if (typeof argumento === 'object') {
var str = '';
if (className === 'Array' || className === 'Array Iterator') {
for (var index = 0, length = argumento.length; index < length; ++index) {
str += this.asJson(argumento[index]) + ',';
}
return '[' + str.slice(0, -1) + ']';
} else {
for (var property in argumento) {
if (argumento.hasOwnProperty(property)) {
str += '"' + property + '":' + this.asJson(argumento[property]) + ',';
}
}
return '{' + str.slice(0, -1) + '}';
}
}
return undef;
}
// interactividad
ask(caption, target = this) {
if (!caption) {
caption = this.GetClass(target);
if (target.id) {
caption += '(' + caption.id + ')';
} else {
(target.name);
}
{
caption += '(' + caption.name + ')';
}
}
this.asString = this.seConfirma('¿' + caption + '?', this.asString);
return this;
}
askFor(some = this) {
return this.ask('', some);
}
/**
* @function
* @description Deep clone a class instance.
* @param {object} instance The class instance you want to clone.
* @returns {object} A new cloned instance.
*/
clone(instance) {
return Object.assign(Object.create(// Set the prototype of the new object to the prototype of the instance.
// Used to allow new object behave like class instance.
Object.getPrototypeOf(instance)), // Prevent shallow copies of nested structures like arrays, etc
JSON.parse(JSON.stringify(instance)));
}
// clone me
copy() {
return this.clone(this);
}
/**
* @returns the protocol, http or https for the document if possible.
**/
checkProtocol() {
let _protocol = 'http:';
if (typeof document !== 'undefined' && document.location && 'https:' === document.location.protocol) {
_protocol = 'https:';
}
return _protocol;
}
// flow predicate %check functions
hasArgs(value) {
return arguments.length !== 0 && typeof value !== 'undefined';
}
hasNoArgs(value) {
return arguments.length === 0 || typeof value === 'undefined';
}
isStringArg(value) {
return arguments.length !== 0 && typeof value === 'string';
}
isNumArg(value) {
return typeof value === 'number';
}
isNonEmptyStringArg(value) {
return arguments.length !== 0 && isStringArg(value) && value.length !== 0;
}
/**
* Converts name and value into a html query parameter, with appending ampersand.
*
* @param name parameter name
* @param val parameter value
* @returns formated query parameter
*/
makeParam(name, val) {
return name + '=' + encodeURIComponent(stringify(val)) + '&';
}
/*
* String representation of input. This is kind of dumb but makes
* flow happier.
*
* @param value any kind of thing that can be turned into a string
* @returns a string
*/
stringify(value) {
if (typeof value === 'string') {
return value;
} else if (typeof value === 'number') {
return value.toString();
} else if (typeof value === 'boolean') {
return value ? 'true' : 'false';
} else if (typeof value === 'undefined') {
return 'undefined';
} else if (typeof value === 'function') {
return 'function ' + value.name;
} else if (typeof value === 'object') {
if (value) {
if (value instanceof Date) {
return value.toISOString();
} else {
return value.constructor.name + ' ' + value.toString();
}
} else {
return 'null';
}
// symbol not yet supported by flow
// } else if (typeof value === 'symbol') {
// return value.toString();
} else {
return '<unknown' + (typeof value) + '???>';
}
}
// Calculo de lo longitud de un lapso de tiempo en milisegundos
static lapso(anhos = 0, meses = 0, dias = 0, horas = 0, minutos = 0, segundos = 0, milisegundos = 0) {
let phase = milisegundos + (1000 * segundos) + (1000 * 60 * minutos) + (1000 * 60 * 60 * horas) + (1000 * 60 * 60 * 24 * dias) + (1000 * 60 * 60 * 24 * (146097 / 4800) * meses) + (1000 * 60 * 60 * 24 * 365.25 * anhos);
return new Date(Number(desde) + phase);
};
// Propagación del tiempo actual a un antes o a un después...
moment(desde = new Date(), anhos = 0, meses = 0, dias = 0, horas = 0, minutos = 0, segundos = 0, milisegundos = 0) {
return new Date(Number(desde) + WebSystemObject.lapso(...arguments.shift()));
};
tellMeTheTime() {
// this.initializeSpeaker();
let momento = new Date();
this.speak(`La hora es ${momento.getHours()} horas, y ${momento.getMinutes()} minutos `);
}
// I think this the better way to engineer a sleep in JavaScript (stack - overflow)
sleep(millis) {
try {
var fromMoment = new Date();
var now = null;
do {
now = new Date();
// app.ProcessMessages;
/* Here should go the javascript, C++ Application.ProcessMessages equivalent (the programmings doc said that)
Interrupts the execution of an application so that it can process the application dedicated operating system message queue.
Call ProcessMessages to permit the application to process messages that are currently in the message queue.
ProcessMessages cycles the Windows message loop until it is empty, and then returns control to the application.
Note: Neglecting message processing affects only the application calling ProcessMessages, not other applications.
In lengthy operations, calling ProcessMessages periodically allows the application to respond to paint and other messages.
Note: ProcessMessages does not allow the application to go idle, whereas HandleMessage does.
*/
} while (now - fromMoment < millis);
} catch (e) {
throw new Error(`Error ${String(e)}, al inducir una espera de ${millis} milisegundos.`);
}
}
delay(d) {
this.sleep(d);
}
// Algunos efectos y funciones para el web
// Solamente milisegundos, para esperar mas de un segundo usa otra cosa.
waitMilliSeconds(iMilliSeconds) { // rename to dalay
var counter = 0, start = new Date().getTime(), end = 0;
while (counter < iMilliSeconds) {
end = new Date().getTime();
counter = end - start;
}
}
is_IE() {
/**
* Checks if the current browser is any version of IE
* @returns {*|boolean}
*/
return window.ActiveXObject || 'ActiveXObject' in window;
}
// Identificador de navegador
isAndroid() {
return navigator.userAgent.match(/Android/i);
};
iswebOS() {
return navigator.userAgent.match(/webOS/i);
};
isiPhone() {
return navigator.userAgent.match(/iPhone/i);
};
isIos() {
return navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i);
};
isiPad() {
return navigator.userAgent.match(/iPad/i);
};
isBlackBerry() {
return navigator.userAgent.match(/BlackBerry/i);
};
isMobile() {
return isAndroid() || iswebOS() || isiPhone() || isiPad() || isBlackBerry() || isMobile();
};
#mailSeparator() {
let result;
let defaultSeparator = '?';
if (this.isAndroid()) {
result = defaultSeparator;
} else if (this.isIos()) {
let iOsVersion_major = +(navigator.userAgent).match(/OS (\d)?\d_\d(_\d)?/i)[0].split('_')[0].replace('OS ', '');
result = iOsVersion_major < 8 ? ';' : '&';
} else {
result = defaultSeparator;
}
return result;
}
// función para enviar correo electrónico
sendMail(address, message = null, subject = null, inSitu = false) {
let protocol = `mailto`;
let sep = this.#mailSeparator();
let sub = encodeURIComponent(subject || '');
let body = encodeURIComponent(message || '');
let content_ = `${protocol}:${address}${sep}subject=${sub}${sep}body=${body}`;
if (inSitu) {
window.location.href = content_;
} else {
window.open(content_);
}
}
fadeOut(element) {
element.style.opacity = 1;
(function fade() {
element.style.opacity -= 0.1;
if (element.style.opacity < 0) {
element.style.display = 'none';
} else {
requestAnimationFrame(fade);
}
})();
}
fadeIn(element, display) {
element.style.opacity = 0;
element.style.display = display || 'block';
(function fade() {
let val = parseFloat(element.style.opacity) + 0.1;
if (val <= 1) {
element.style.opacity = val;
requestAnimationFrame(fade);
}
})();
}
docReady(fn) {
if (document.readyState === 'complete' || document.readyState === 'interactive') {
setTimeout(fn, 1); // Ni te embarres
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
addEventListenersToElements(elements, event, listener) {
elements.forEach((el) => el.addEventListener(event, listener));
}
// dame todos los scripts de esta página...
scripts() {
return document.getElementsByTagName('script');
}
// eliminar un script (true if).
removeScript(name) {
let s = this.scripts();
s.forEach(scriptNode, function(scriptNode) {
if (scriptNode.getAttribute('data-requiremodule') === name && scriptNode.getAttribute('data-requirecontext') === context.contextName) {
scriptNode.parentNode.removeChild(scriptNode);
return true;
}
});
return false;
}
// buena esa
static loadScript(url, callback) {
var head = document.querySelector('head');
var script = document.createElement('script');
script.async = true;
script.src = url;
script.onload = callback;
head.appendChild(script);
}
// btoa() and atob() are two Base64 helper functions that are a core part of the HTML specification and available in all modern browsers.
base64ToString(b) {
return btoa(b);
}
stringToBase64(s) {
return atob(s);
}
// Piotr Bonk (Polonia):
// Nalin Bhasin:
// Ossama Rafique:
imageToBase64(htmlElement, {type, quality} = {type: 'png', quality: 1}) {
const [imageHeight, imageWidth] = [htmlElement.width, htmlElement.height];
const base64 = htmlElement.toDataURL('image/' + type, quality);
return {base, type, imageHeight, imageWidth};
}
// Incrustar una imagen codificada en base64
// Piotr Bonk (Polonia):
// Nalin Bhasin:
// Ossama Rafique:
imageFromBase64(base, type = 'gif', alt = `embedded ${type} image`, width, height) {
let inWidth = width ? `width="${Number(width).toFixed(0)}"` : '';
let inHeight = height ? `height="${Number(height).toFixed(0)}"` : '';
let inAlt = height ? `alt="${alt}"` : '';
return `<img src="data:image/${type};base64,${base}"${inWidth} ${inHeight} ${inAlt} alt="Cannot render image">`;
}
style(el, style) {
var value = el.style[style];
if (!value && el.currentStyle) {
value = el.currentStyle[style];
}
if ((!value || value === 'auto') && document.defaultView) {
var css = document.defaultView.getComputedStyle(el, null);
value = css ? css[style] : null;
}
return value === 'auto' ? null : value;
}
getViewportOffset(element) {
var top = 0,
left = 0,
el = element,
docBody = document.body,
docEl = document.documentElement,
pos;
do {
top += el.offsetTop || 0;
left += el.offsetLeft || 0;
//add borders
top += parseInt(this.style(el, 'borderTopWidth'), 10) || 0;
left += parseInt(this.style(el, 'borderLeftWidth'), 10) || 0;
pos = this.style(el, 'position');
if (el.offsetParent === docBody && pos === 'absolute') {
break;
}
if (pos === 'fixed') {
top += docBody.scrollTop || docEl.scrollTop || 0;
left += docBody.scrollLeft || docEl.scrollLeft || 0;
break;
}
if (pos === 'relative' && !el.offsetLeft) {
var width = this.style(el, 'width'),
maxWidth = this.style(el, 'max-width'),
r = el.getBoundingClientRect();
if (width !== 'none' || maxWidth !== 'none') {
left += r.left + el.clientLeft;
}
//calculate full y offset since we're breaking out of the loop
top += r.top + (docBody.scrollTop || docEl.scrollTop || 0);
break;
}
el = el.offsetParent;
} while (el);
el = element;
do {
if (el === docBody) {
break;
}
top -= el.scrollTop || 0;
left -= el.scrollLeft || 0;
el = el.parentNode;
} while (el);
return {left, top};
}
isTagged(s, pattern = '<>') {
let tmp = String(s).trim();
return s.length >= 2 && s[0] === pattern[0] && s[s.length - 1] === pattern[1];
}
create(tagName, className, container) {
var el = document.createElement(tagName);
el.className = className;
if (container) {
container.appendChild(el);
}
return el;
}
setOpacity(el, value) {
if ('opacity' in el.style) {
el.style.opacity = value;
} else if ('filter' in el.style) {
var filter = false,
filterName = 'DXImageTransform.Microsoft.Alpha';
// filters collection throws an error if we try to retrieve a filter that doesn't exist
try {
filter = el.filters.item(filterName);
} catch (e) {
// don't set opacity to 1 if we haven't already set an opacity,
// it isn't needed and breaks transparent pngs.
if (value === 1) {
return;
}
}
value = Math.round(value * 100);
if (filter) {
filter.Enabled = (value !== 100);
filter.Opacity = value;
} else {
el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
}
}
}
testProp(props) {
var style = document.documentElement.style;
for (var i = 0; i < props.length; i++) {
if (props[i] in style) {
return props[i];
}
}
return false;
}
// No funciona arreglar
readFromFile(filename, mode = 'ASTEXT') {
var resultado;
try {
if (fs) {
switch (mode) {
case 'ASTEXT':
resultado = fs.read(filename, 'utf8');
break;
default:
resultado = fs.read(filename);
break;
}
} else {
throw new Error(`File system cannot access ${filename}.`);
}
} catch (e) {
console.warn(e);
}
return resultado;
}
writeToFile(fileName, contenido) {
let resultado;
try {
if (fs) {
const
magicNumber = 0o777;
fs.writeFileSync(fileName, contenido, {mode: magicNumber});
} else {
throw new Error(`File system cannot access ${filename}.`);
}
} catch (e) {
console.warn(e);
}
}
fileExists(filename) {
try {
if (fs) {
return fs.exists(filename);
}
} catch (e) {
console.warn(e);
}
return false;
}
copyFile(from, to) {
fs.copyFile();
}
// Ejecuta una partitura y devuelve la pista...
async playAudio(path) {
this.audio = new Audio(path);
this.audio.type = 'audio/mp3';
this.audio.crossOrigin = 'anonymous';
this.audio.load();
try {
await this.audio.play();
console.log('Playing audio ' + path);
} catch (err) {
console.log('Failed to play, error: ' + err);
}
return this.audio;
}
// pausa... and resume
async pauseAudio() {
try {
await this.audio.pause();
console.log('Pausing audio ' + this.audio);
} catch (err) {
console.log('Failed to pause, error: ' + err);
}
}
// > - ###### For vibration pattern
// > We can also provide multiple values to the array such that starting with 0, even indices are the time for vibration and odd index are for interval between vibration.
// > ```js
// > window.navigator.vibrate([500,250,500,250,500]);
async resumeAudio() {
try {
await this.audio.play();
console.log('Pausing audio ' + this.audio);
} catch (err) {
console.log('Failed to pause, error: ' + err);
}
}
// Todos los objetos no necesitan utilizar los medios y dispositivos, con ese fin:
initializeMedia() {
this.initializeSpeaker();
// Utiliza funciones anónimas para eventos elementales...
if (navigator.ononline) {
this.keepOnOnLine = navigator.ononline;
}
navigator.ononline = function(e) {
this.online = navigator.onLine;
this.connectionType = navigator.connection.type; // "bluetooth" | "cellular" | "ethernet" | "mixed" | "none" | "other" | "unknown" | "wifi";
if (this.keepOnOnLine) this.keepOnOnLine(e);
};
if (navigator.onoffline) {
this.keepOnOffLine = navigator.onoffline;
}
navigator.onoffline = function(e) {
this.online = navigator.onLine;
if (this.keepOnOffLine) this.keepOnOffLine(e);
};
// Check if the device supports the Vibration API
this.vibra = window.navigator.vibrate;
if (!this.vibra) {
console.log('No se encuentra el dispositivo de vibración....'); // no hay de eso que tú conoces.
}
// En este ejemplo, observamos los cambios en el estado de la carga (este o no conectado y cargando)
// y en el nivel de la batería. Esto se hace escuchando el evento chargingchange y el evento levelchange respectivamente.
this.battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery;
if (this.battery) {
// Battery status (Este evento se dispara cuando hay un cambio en el nivel de la bateria del móvil)
// is an event
this._updateBatteryStatus = function(event) {
this.BatteryLevel = this.battery.level;
this.LineOverlap = this.battery.lineOverlap; // ¿Indica situación de corte en las líneas, o cortocircuito?
console.log('El estado de la batería es de ' + this.BatteryLevel * 100 + ' %');
this.BatteryCharging = this.battery.charging;
if (this.BatteryCharging) {
console.log('La batería está cargándose.');
} else {
this.DischargingTime = this.battery.dischargingTime;
console.log(`La batería no está cargándose y se estima que tiene carga suficiente para ${this.DischargingTime / 60} minutos.`);
}
};
this.attachEventToDOM('online', navigator, this._updateBatteryStatus, true);
this.attachEventToDOM('levelchange', navigator, this._updateBatteryStatus, true);
this.attachEventToDOM('ondischargingtimechange', navigator, this._updateBatteryStatus, true);
// this.battery.addEventListener("chargingchange", this._updateBatteryStatus);
// this.battery.addEventListener("levelchange", this._updateBatteryStatus);
// this.battery.addEventListener("ondischargingtimechange", this._updateBatteryStatus);
this._updateBatteryStatus();
} else {
console.log('No se encuentra el dispositivo de administración de batería...'); // no hay de eso que tú conoces.
}
// Assigning the Event Handler to a Listener
this._beforeDistance = -1;
this._deviceProximityHandler = function(event) {
this.proximityDistance = event.value;
if (this._beforeDistance !== -1 && this._beforeDistance !== this.proximityDistance) {
if (this.proximityDistance - this._beforeDistance > 0) {
console.log(`Se ha detectado un objeto físico alejándose del móvil.`);
} else if (this.proximityDistance - this._beforeDistance < 0) {
console.log(`Se ha detectado un objeto físico acercándose al móvil.`);
}
}
if (this.proximityDistance === 0) {
console.log('Se ha detectado un objeto físico en la proximidad del móvil.');
this.speak('¡¡¡ Deténgase !!!');
this.sosVibrate(); // do something, or make a 911, phone call...
}
console.log(`Se detecta proximidad entre ${event.near ? event.near : event.min} y ${event.max}.`);
this._beforeDistance = this.proximityDistance;
};
window.addEventListener('deviceproximity', this._deviceProximityHandler);
// Monitoreo de luz ambiental
this._beforeAambientLightValue = -1;
this._deviceLightHandler = function(event) {
this.ambientLightValue = event.value; // in lux.
console.log(`Cambio en la intensidad de la luz ambiental a ${this.ambientLightValue} lux.`);
if (this._beforeAambientLightValue !== -1 && this._beforeAambientLightValue !== this.ambientLightValue) {
if (this._beforeAambientLightValue > this.ambientLightValue) {
console.log(`La luz ambiental está oscureciéndose en ${this._beforeAambientLightValue - this.ambientLightValue} lux.`);
} else {
console.log(`La luz ambiental está aclarándose en ${this.ambientLightValue - this._beforeAambientLightValue} lux.`);
}
}
this._beforeAambientLightValue = this.ambientLightValue;
};
window.addEventListener('devicelight', this._deviceLightHandler);
// Monitoreo de la temperatura (lectura y seguimiento del termostato)
// Pueden agregarse algoritmos predictivos sencillos en función del tiempo, tanto para este, como para los otros sensores.
// Para saber si está subiendo o bajando demasiado rápido., en una magnitud considerable o si el usuario está sufriendo de algún tipo de calentura...
this._beforeThermostatTemperature = -273;
this._thermostatHandler = function(event) {
this.thermostatTemperature = event.value; // In Celcius (C°)
console.log(`Cambio en la temperatura, temperatura = ${event.value} C°`);
if (this._beforeThermostatTemperature !== -273 && this._beforeThermostatTemperature !== this.thermostatTemperature) {
if (this._beforeThermostatTemperature > this.thermostatTemperature) {
console.log(`La temperatura está bajando en ${this._beforeThermostatTemperature - this.thermostatTemperature} C°.`);
} else {
console.log(`La temperatura esta subiendo en ${this.thermostatTemperature - this._beforeThermostatTemperature} C°.`);
}
}
this._beforeThermostatTemperature = this.thermostatTemperature;
};
window.addEventListener('ambienttemperature', this._thermostatHandler);
// navigator.system.watch("AmbientTemperature", this._thermostatHandler);
// Draft: propuesta de monitoreo de la Humedad relativa (especulativo, se esperaba que así fuera en December 2013 [Tran 2013]).
this._beforeRelativeHumidity = -1;
this._humidityHandler = function(event) {
this.relativeHumidity = event.value;
console.log(`Cambio en la humedad relativa, ahora es del ${this.relativeHumidity} %.`);
if (this._beforeRelativeHumidity !== -1 && this._beforeRelativeHumidity !== this.relativeHumidity) {
if (this._beforeRelativeHumidity > this.relativeHumidity) {
console.log(`La humedad relativa está bajando en un ${this._beforeRelativeHumidity - this.relativeHumidity} %.`);
} else {
console.log(`La humedad relativa esta subiendo en un ${this.relativeHumidity - this._beforeRelativeHumidity} %.`);
}
}
this._beforeRelativeHumidity = this.relativeHumidity;
};
window.addEventListener('ambienthumidity', this._humidityHandler);
// Draft: propuesta de monitoreo de la presión atmosférica (especulativo, se esperaba que así fuera en December 2013 [Tran 2013]).
this._beforeAtmosphericPressure = -1;
this._atmosphericPressureHandler = function(event) {
this.atmosphericPressure = event.value;
console.log(`Cambio en la presión atmosférica, ahora es del ${this.atmosphericPressure} kP.`);
if (this._beforeAtmosphericPressure !== -1 && this._beforeAtmosphericPressure !== this.atmosphericPressure) {
if (this._beforeAtmosphericPressure > this.atmosphericPressure) {
console.log(`La presión atmosférica está bajando en ${this._beforeAtmosphericPressure - this.atmosphericPressure} kP.`);
} else {
console.log(`La presión atmosférica esta subiendo en ${this.atmosphericPressure - this._beforeAtmosphericPressure} kP.`);
}
}
this._beforeAtmosphericPressure = this.atmosphericPressure;
};
window.addEventListener('AtmPressure', this._atmosphericPressureHandler);
// navigator.system.watch("AmbientAtmosphericPressure", this._atmosphericPressureHandler);
// Swipe (screen touches)
this.touches = {
'touchstart': {'x': -1, 'y': -1},
'touchmove': {'x': -1, 'y': -1},
'touchend': false,
'direction': 'undetermined',
};
this.handler = function(event) {
var touch;
if (typeof event !== 'undefined') {
event.preventDefault();
if (typeof event.touches !== 'undefined') {
touch = event.touches[0];
switch (event.type) {
case 'touchstart':
case 'touchmove':
this.touches[event.type].x = touch.pageX;
this.touches[event.type].y = touch.pageY;
break;
case 'touchend':
this.touches[event.type] = true;
if (this.touches.touchstart.x > -1 && this.touches.touchmove.x > -1) {
this.touches.direction = this.touches.touchstart.x < this.touches.touchmove.x ? 'right' : 'left';
// DO STUFF HERE
alert(this.touches.direction);
}
break;
default:
break;
}
}
}
};
// Init swipe
if (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)) {
document.addEventListener('touchstart', this.handler, false);
document.addEventListener('touchmove', this.handler, false);
document.addEventListener('touchend', this.handler, false);
}
// Vibratios api extensions
// ## Simple implementation of Vibration Web API
// Vibration Web API is the API to control vibration of the device. Currently (May 18th 2021), this API is not supported on IOS devices. Although, device supports the API but does not have vibration mechanism, then also it does not work.
// Now for vibration logic, window.navigator.vibrate method is responsible with accepts an array with multiple values.
// > - ###### For static vibration
// > if we provide single valued array, then it will vibrate for provided interval and then stops.
// > ```js
// > window.navigator.vibrate([500]);
// >```
// > In this example, device will vibrate for 500ms and then stops.
}
// Returns the unique ID of an object, assigning it one if it doesn't have it (if exists, uses onFieldName instead of ID field).
stamp(onFieldName) {
/* eslint-disable */
var newId = ++WebSystemObject.lastId;
if (onFieldName) {
this[onFieldName] = this[onFieldName] || newId;
} else {
this.id = this.id || newId;
}
/* eslint-enable */
}
// Russell Gooday (Generar números consecutivos, desde start hasta end)
consecutives(end, start = 1) {
return [...function* () {
while (start <= end) yield start++;
}()];
};
// intercambiar dos elementos (por referencia, not tested)
interchange(x, y) {
[x, y] = [y, x];
};
// Función para generar un autonumérico a partir de una lista de id's.
autoNum(array) {
// Javascript program to find the smallest elements missing in a sorted array.
function findFirstMissing(array, start = 0, end = array.length - 1) {
if (start > end) return end + 1;
if (start !== array[start]) return start;
let mid = parseInt((start + end) / 2, 10);
// Left half has all elements from 0 to mid
if (array[mid] === mid) return findFirstMissing(array, mid + 1, end);
return findFirstMissing(array, start, mid);
}
return findFirstMissing(array.sort((a, b) => a - b));
}
// Función para generar un autonumérico a partir de los valores de un campo en una lista.
autoField(array, fieldName = 'id') {
let tmp = array.map((element) => element[fieldName]);
return this.autoNum(tmp);
}
// >```
vibrate(pattern) {
if (!this.vibra) {
console('Su navegador o su hard, no tiene una chapa que vibre...');
return;
}
pattern = pattern ? pattern : [];
window.navigator.vibrate(pattern);
}
//Vibrate normally for 500ms (Older Iphone Vibration pattern.).
normalVibrate() {
this.vibrate([500]);
};
//Vibrate pattern 1 (Legacy samsung phone's vibration pattern).
pattern1Vibrate() {
// > In this example, device will vibrate for 500ms waits 250ms , again vibrates 500ms and waits 250ms and so on.
// This flexibility allows us to program different vibration patterns. Below others vibration patterns.
this.vibrate([250, 250, 250, 250, 250, 800, 250, 250, 250, 250, 250, 250]);
};
// speech technology
//Vibrate pattern 2
pattern2Vibrate() {
this.vibrate([1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000]);
};
// Vibrate SOS in morse code.
sosVibrate() {
this.vibrate([100, 30, 100, 30, 100, 30, 200, 30, 200, 30, 200, 30, 100, 30, 100, 30, 100]);
};
stopVibration() {
this.vibrate([]);
}
initializeSpeaker() {
// Con Speech synth API?
this.synth = window.speechSynthesis;
if (this.synth) {
// detect speech voices change (is an event).
this._populateVoices = function(event) {
this.voices = this.synth.getVoices().sort(function(a, b) {
const aname = a.name.toUpperCase(), bname = b.name.toUpperCase();
if (aname < bname) return -1; else if (aname === bname) return 0; else return +1;
});
};
if (this.synth.onvoiceschanged) {
this.synth.onvoiceschanged = this._populateVoices;
}
}
this._populateVoices();