-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviewify.js
More file actions
1085 lines (976 loc) · 30.2 KB
/
viewify.js
File metadata and controls
1085 lines (976 loc) · 30.2 KB
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
//# sourceURL=Viewify
const $ = require('jquery');
/// check if ?debug is in the URL. if so, turn on debug mode.
/// this will enable more complex logging
let debug = ((new URL(location.href)).searchParams.get('debug')) != null
if (debug) console.warn('Debug is turned on!!');
// minified md5 implemetation
window.md5 = function () {
var k = [], i = 0;
for (; i < 64;) k[i] = 0 | (Math.abs(Math.sin(++i)) * 4294967296);
function calcMD5(str) {
var b, c, d, j, x = [], str2 = unescape(encodeURI(str)),
a = str2.length, h = [b = 1732584193, c = -271733879, ~b, ~c], i = 0;
for (; i <= a;) x[i >> 2] |= (str2.charCodeAt(i) || 128) << 8 * (i++ % 4);
x[str = (a + 8 >> 6) * 16 + 14] = a * 8; i = 0; for (; i < str; i += 16) {
a = h; j = 0; for (; j < 64;) a = [d = a[3], ((b = a[1] | 0) + ((d = ((a[0] +
[b & (c = a[2]) | ~b & d, d & b | ~d & c, b ^ c ^ d, c ^ (b | ~d)][a = j >> 4])
+ (k[j] + (x[[j, 5 * j + 1, 3 * j + 5, 7 * j][a] % 16 + i] | 0)))) << (a = [
7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21][4 * a + j++ % 4
]) | d >>> 32 - a)), b, c]; for (j = 4; j;) h[--j] = h[j] + a[j];
} str = '';
for (; j < 32;) str += ((h[j >> 3] >> ((1 ^ j++ & 7) * 4)) & 15).toString(16);
return str;
} return calcMD5;
}();
// DIV, IMG, and STYLE are shorthand for making elements, wrapped in jquery
if (window.DIV == undefined)
/**
* @param {String?} selectorish the classes and ID to apply to the generated
* div; in the format of a css selector. passing a string without . or # will
* set the class attribute to the string, unprocessed. this behavior is deprecated
* and will throw a warning
*
*/
window.DIV = function DIV(selectorish) {
let elem = $(document.createElement('div'));
// debugger;
if (selectorish) {
if (selectorish.search(/[#\.]/) == -1) {
console.warn('calling DIV with a non selector string is deprecated.');
console.warn(`use DIV(.${selectorish}) instead`);
elem.addClass(selectorish);
return elem;
}
let params = selectorish.split(/(?=\.)/g);
for (let i in params) {
if (params[i].startsWith('#')) elem.attr('id', params[i].substr(1));
else if (params[i].startsWith('.')) elem.addClass(params[i].substr(1));
}
}
return elem;
};
if (window.STYLE == undefined) window.STYLE = function STYLE() {
return $(document.createElement('style'));
};
if (window.emptyImage == undefined) window.emptyImage = function emptyImage() {
let emptyImage;
emptyImage = $('#THISISANEMPTYIMAGEANDAUNIQUEIDPLSNOREUSE');
if (emptyImage.length == 1) return emptyImage[0];
emptyImage = IMG('https://placehold.it/1x1');
emptyImage.css('position', 'fixed');
emptyImage.css('left', '-100px');
emptyImage.css('top', '-100px');
emptyImage.attr('id', 'THISISANEMPTYIMAGEANDAUNIQUEIDPLSNOREUSE');
$(document.body).append(emptyImage);
return emptyImage[0];
};
if (window.IMG == undefined) window.IMG = function IMG(width, height, src) {
let elem = $(document.createElement('img'));
if (!height && !src) {
src = width;
} else if (!src) {
elem.css('width', width);
elem.css('height', height);
src = `https://placehold.it/${width}x${height}`;
}
elem.attr('src', src);
return elem;
};
// get root level cssVars
$.fn.extend({
cssVar: function (name) {
// debugger;
let color = com.Vlt.div.css('--text').trim().replace('#', '');
// color = 'C0FFEE';
if (color.length == 3) color = color[0] + color[0] + color[1] + color[1] + color[2] + color[2];
color = color.split("").reverse().join("");
let valueTable = "0123456789ABCDEF"
let result = 0;
for (let i = 0, digitValue = 1; i < color.length; i++ , digitValue *= 16) {
let onesValue = valueTable.indexOf(color[i]); // find the hex digits decimal value, using the above string.
let value = onesValue * digitValue; // find the value of this digit in its place.
result |= value; // value is effectively digit masked, and adding would involve sign errors...
}
return result;
}
});
if (window.Preprocessor == undefined) {
window.Preprocessor = class Preprocessor {
constructor(entity) {
this.view = entity;
this.template = '';
this._later = [];
}
async finish() {
this._div = $(this.template);
for (let fun of this._later) {
let ret = fun(); // because compatibility \/
if (ret instanceof Promise) await ret;
}
let hooks = this._div.find('[xgraph-hook]').addBack('[xgraph-hook]');
for (let elem of hooks) {
let data = {};
if (elem.attributes.getNamedItem('xgraph-data') !== null) {
data = JSON.parse(elem.attributes['xgraph-data'].nodeValue);
}
for (let attr of elem.attributes) {
let val = attr.nodeValue;
switch (attr.name) {
case 'xgraph-event-click': {
$(elem).on('click', _ => {
this.view.dispatch({ Cmd: val, Data: data, Element: elem }, (err) => {
if (err) {
console.warn('xgraph-event-click::ERR');
console.warn(err);
}
});
});
break;
}
case 'xgraph-event-change': {
$(elem).on('change', _ => {
this.view.dispatch({ Cmd: val, Checked: elem.checked, Data: data, Element: elem }, (err) => {
if (err) {
console.warn('xgraph-event-change::ERR');
console.warn(err);
}
});
});
break;
}
case 'xgraph-child-index': {
if (val in this.view.Vlt.viewDivs) {
$(elem).append(this.view.Vlt.viewDivs[val]);
}
break;
}
}
}
}
return this._div;
}
later(fun) {
this._later.push(fun);
}
/**
* @description create a button using an
* @param {any} name
* @param {any} command
*/
button(name, command) {
let id, type = "button";
if (typeof name == 'object') {
parseOptions(name);
} else if (typeof command == 'object') {
parseOptions(command);
}
function parseOptions(options) {
for (let key in options) {
switch (key) {
case "id": id = name[key]; break;
case "name": name = options[key]; break;
case "command": command = options[key]; break;
case "type": type = options[key]; break;
}
}
}
id = id || name.replace(/\s/g, '-')
// debugger;
//append the button with the right type
switch (type) {
case "button": {
this.append(`<button id="${id}" button>${name}</button>`);
break;
}
case "input": {
this.append(`<button id="${id}" button>${name}</button>`);
break;
}
case "anchor":
default: {
this.append(`<a href="#" id="${id}" button>${name}</a>`);
break;
}
}
this.later(_ => {
let button = this._div.find(`#${id}`);
// button.attr('ParHidden', 'true');
button.on('click', _ => {
this.view.dispatch({ Cmd: command, Name: name, Id: id })
});
});
}
append(text) {
this.template += `${text}`;
}
}
}
// ----------------------- Custom Errors
class ViewNotInitializedError extends Error { }
//Viewify..... ahem.... viewify!!!!!!!!!!!
module.exports.viewify =
module.exports.Viewify = function Viewify(_class) {
// will scan either a prototype of dispatch table
let child = typeof _class == 'function' ? _class.prototype : _class;
class View {
/**
* @description Creates the basic things
* a view needs, like its div, internal
* stylesheet and other elements.
*
* Overridable
* @param {any} com
* @param {any} fun
* @memberof View
*/
async Setup(com, fun) {
// debugger;
this.Par.$ = {};
let vlt = this.Vlt;
vlt.views = [];
vlt.viewDivs = [];
vlt.type = this.Par.Module.split(/[\.:\/]/g).pop();
vlt.rootID = '#' + this.Par.Pid.substr(24) + "-Root";
vlt._root = DIV(vlt.rootID);
vlt._root.attr('viewPid', this.Par.Pid);
vlt._root.css('height', '100%');
vlt._root.css('display', 'block');
vlt._root.css('box-sizing', 'border-box');
vlt._root.css('overflow', 'hidden');
// create compat vlt.root, will be removed if ver >= 4.0
vlt.root = vlt._root;
vlt.styletag = STYLE();
vlt.div = $('<div></div>');
vlt.div.addClass(vlt.type);
if ('ID' in this.Par) vlt.div.id(this.Par.ID);
else vlt.div.attr('id', `XGRAPH-${this.Par.Pid}`);
vlt.div.css('height', '100%');
vlt.div.css('display', 'block');
vlt.div.css('position', 'relative');
vlt.div.css('box-sizing', 'border-box');
vlt.div.css('overflow', 'hidden');
vlt.name = com.Name || this.Par.Name || "Untitled View";
vlt._root.append(vlt.styletag);
vlt._root.append(vlt.div);
//remove support for this.Vlt.root
this.Vlt.root = undefined;
//4.0 uses shadow dom
// debugger;
if (document.head.attachShadow) {
// if we have shadow dom, otherwise,
// idk, use shadyDOM or something
// TODO figure that out
this.Vlt._shadow = $(this.Vlt._root[0].attachShadow({ mode: "open" }));
this.Vlt.div.detach();
this.Vlt.styletag.detach();
this.Vlt.styletag.data('shadow', true);
this.Vlt._shadowStyle = STYLE();
this.Vlt._shadow.append(this.Vlt.div);
this.Vlt._shadow.append(this.Vlt.styletag);
this.Vlt._shadow.append(this.Vlt._shadowStyle);
await new Promise(resolve => {
this.getFile("styles.x.css", (err, dat) => {
if (err) return resolve();
this.Vlt._shadowStyle.html(dat);
resolve();
});
});
await new Promise(resolveFile => {
this.getFile("global.html", async (err, html) => {
if (err) return resolveFile();
let elements = $(html);
// let scripts = elements.find('script').addBack('script');
// let scriptLoadPromises = [];
// for(let script of scripts) {
// scriptLoadPromises.push(new Promise(scriptLoadedResolve => {
// script.onload = function() {
// scriptLoadedResolve();
// };
// }));
// }
$(document.head).append(elements);
resolveFile();
// Promise.all(scriptLoadPromises);
});
});
}
await this.ascend('Render', {}, this.Par.Pid);
fun(null, com);
}
async Start(com, fun) {
// debugger;
let that = this;
async function parseChildren(children = [], basePid = that.Par.Pid) {
async function parseView(view) {
if (typeof view === 'string') {
await that.ascend('AddView', { View: view }, basePid)
} else {
await that.ascend('AddView', { View: view.View }, basePid)
await parseChildren(view.Children, view.View);
}
}
if (Array.isArray(children)) {
if (children.length != 0) {
for (let child of children) {
await parseView(child);
}
} else {
// if('Root' in that.Par && that.Par.Root) await that.ascend('Render', {}, basePid);
}
} else {
await parseView(children);
}
}
// add to root if root true
await parseChildren(this.Par.Children);
if ('Root' in this.Par && this.Par.Root) {
$(document.body).append(this.Vlt._root);
await new Promise(async (resolve) => {
// await new Promise(resolve => this.send({ Cmd: 'GetViewRoot' }, this.Par.Pid, _ => resolve()));
await new Promise(resolve => this.send({ Cmd: 'ShowHierarchy' }, this.Par.Pid, _ => resolve()));
$('.removeOnLoad').remove();
// this.send({ Cmd: 'DOMLoaded' }, this.Par.Pid, (err, com) => {
// $(window).resize(() => {
// this.send({ Cmd: 'Resize' }, this.Par.Pid, (err, com) => { });
// });
resolve();
// });
});
fun(null, com);
}
else {
fun(null, com);
}
}
/**
* @description Returns back (in com.Root) the root
* of the view.
*
* Note: the root is different than this.Vlt.div.
* com.Root is the highest node in your View's
* DOM hierarchy.
*
* Not part of the public API. this
* command should stay internal
* @param {any} com
* @param {any} fun
* @memberof View
*/
GetViewRoot(com, fun) {
// debugger;
if (!this.Vlt._root) console.error(`ERR: trying to access root of ${this.Par.Module} before it is setup!`);
com.Div = this.Vlt._root;
// debugger;
fun(new ViewNotInitializedError(), com);
}
/**
* @description Returns this.Vlt.div
*
* Not part of the public API. this
* command should stay internal
* @param {any} com
* @param {any} fun
* @memberof View
*/
GetViewDiv(com, fun) {
com.Div = this.Vlt.div;
fun(null, com);
}
/**
* @description Used to be used to disable a title bar, which no longer exists.
*
* @deprecated
* @memberof View
*/
DisableTitleBar() {
console.warn('deprecated DisableTitleBar call');
console.warn(new Error().stack);
this.Vlt.titleBar.detach();
this.Vlt.disableTitleBar = true;
}
/**
* @description Reset the DOM hierarchy of your View
*
* @deprecated
* @param {any} com
* @param {any} fun
* @memberof View
*/
Clear(com, fun) {
console.warn('deprecated clear call');
console.warn(new Error().stack);
this.Vlt.div.children().detach();
this.Vlt._root.children().detach();
this.Vlt._root.append(this.Vlt.styletag);
if (!this.Vlt.disableTitleBar) this.Vlt._root.append(this.titleBar);
this.Vlt._root.append(this.Vlt.div);
fun(null, com);
}
/**
* @description Set the color of the View
*
* @deprecated
* @param {any} com
* @param {any} fun
* @memberof View
*/
SetColor(com, fun) {
console.warn('deprecated SetColor call');
console.warn(new Error().stack);
let value = com.Value || com.Color;
let border = com.Border || value;
this.Vlt._color = value;
this.Vlt._root.css('background-color', value);
fun(null, com);
}
/**
* @description Called when a child of this View has been destroyed. Overriding this command is not supported.
* @param {any} com
* @param {any} fun
* @memberof View
*/
async ChildDestroyed(com, fun) {
this.Vlt.views.splice(this.Vlt.views.indexOf(com.Pid), 1);
let views = this.Vlt.views.slice(0);
this.Vlt.viewDivs = [];
this.Vlt.views = [];
for (let pid of views)
await this.ascend('AddView', { View: pid }, this.Par.Pid);
await this.ascend('Render', {}, this.Par.Pid);
fun(null, com);
}
/**
* @description Add com.View as a Child View this forces a render after the child gives us its div.
* @param {any} com
* @param {string} com.View view pid
* @param {any} fun
* @memberof View
*/
AddView(com, fun) {
let that = this;
let vlt = this.Vlt;
if (!('views' in vlt)) vlt.views = [];
if (this.Vlt.views.indexOf(com.View) > -1) return fun(null, com);
vlt.views.push(com.View);
this.send({ Cmd: 'GetViewRoot' }, com.View, (err, cmd) => {
vlt.viewDivs.push(cmd.Div);
this.dispatch({ Cmd: 'Render' }, (err, cmd) => { fun(null, com) });
this.send({ Cmd: 'RegisterDestroyListener' }, com.View, _ => _);
});
}
/**
* @description Render the View. This is only called
* when something about the view has changed.
* typically, this means that your children
* have changed.
*
* Overridable
* @param {any} com
* @param {any} fun
* @memberof View
*/
async Render(com, fun) {
this.Vlt.div.children().remove();
await new Promise(async (resolveFile) => {
let elements = await this.partial('view.x.html');
this.Vlt.div.append(elements);
// give it time to render
setTimeout(_ => {
// elements with and ID and not ParHidden attribute, will be saved to Par.$
let parElements = elements.find('[id]:not([ParHidden])').addBack('[id]:not([ParHidden])');
for (let element of parElements) {
this.Par.$[$(element).attr('id')] = $(element);
}
resolveFile();
}, 0);
})
setTimeout(_ => {
fun(null, com);
}, 0);
}
/**
* @description returns the Type of view this is.
* View type is defined by the last token in the
* dot separated array this.Par.Module
*
* @deprecated
* @param {any} com
* @param {string} com.Type return value
* @param {any} fun
* @memberof View
*/
GetType(com, fun) {
console.warn('deprecated GetType call');
console.warn(new Error().stack);
com.Type = this.Vlt.type;
fun(null, com);
}
/**
* @description Event Command; fired when this view
* received focus.
*
* @deprecated
* @param {any} com
* @param {any} fun
* @memberof View
*/
Focus(com, fun) {
console.warn('deprecated Focus call');
console.warn(new Error().stack);
this.Vlt._root.addClass('Focus');
if (!this.Vlt.disableTitleBar) this.Vlt.titleBar.css('border-bottom', '1px solid var(--accent-color)');
fun(null, com);
}
/**
* @description Event command; fired when
* this viw lost focus
*
* @deprecated
* @param {any} com
* @param {any} fun
* @memberof View
*/
Blur(com, fun) {
this.Vlt._root.removeClass('Focus');
if (!this.Vlt.disableTitleBar) this.Vlt.titleBar.css('border-bottom', '1px solid var(--view-border-color)');
fun(null, com);
}
/**
* @description Event Command; Fired after the
* first Render cascade in a new View hierarchy
*
* Overridable
* @param {any} com
* @param {any} fun
* @memberof View
*/
async DOMLoaded(com, fun) {
let that = this;
for (let pid of this.Vlt.views) {
await new Promise((resolve, reject) => {
that.send({ Cmd: 'DOMLoaded' }, pid, () => {
resolve();
});
});
}
fun(null, com);
}
/**
* @description Event Commend; Called when your drawable area
* has been changed.
*
* Note: This is dispatched by a root view, so if you are
* creatin a root view, you need to manually start the
* Resize cascaded.
*
* Overridable
* @param {object} com
* @param {number} com.width
* @param {number} com.height
* @param {number} com.aspect
* @param {any} fun
* @memberof View
*/
async Resize(com, fun) {
com.width = this.Vlt.div.width();
com.height = this.Vlt.div.height();
com.aspect = 1 / (this.Vlt.div.height() / this.Vlt.div.width());
let that = this;
for (let pid of this.Vlt.views) {
await new Promise((resolve, reject) => {
that.send({ Cmd: 'Resize' }, pid, () => {
resolve();
});
});
}
fun(null, com);
}
/**
* @description ShowHierarchy creates a tree in the console
* @param {any} com
* @param {any} fun
* @memberof View
*/
async ShowHierarchy(com, fun) {
if (!debug) return fun(null, com);
var that = this;
let group = `[${this.Par.Pid.substr(0, 8)}] - ${this.Vlt.type}`;
console.group(group);
for (let pid of this.Vlt.views) {
await new Promise((resolve, reject) => {
that.send({ Cmd: 'ShowHierarchy' }, pid, () => {
resolve();
});
});
}
console.groupEnd(group);
fun(null, com);
}
/**
* @description Event Command; Fires when Something is
* dropped in this View.
*
* See Also: [Drag and Drop API](https://github.com/IntrospectiveSystems/xGraph/wiki/Viewify-Docs---Version-Info#drag-and-drop)
* @param {object} com
* @param {any} com.Data
* @param {string} com.Datatype
* @param {HTMLElement} com.DropArea
* @param {number} com.PageX
* @param {number} com.PageY
* @param {number} com.DivX
* @param {number} com.DivX
* @param {any} fun
* @memberof View
*/
Drop(com, fun) {
console.log('DROPPED', com);
fun(null, com);
}
/**
* @description make an element drag & droppable.
*
* com.Data and com.Datatype is the information
* and type of information that is tied to the element.
* i.e., if the element is dragged, when it is dropped,
* that data will be passed to the drop event.
*
* com.To is the Native Element to attach the listener to.
*
* com.CreateDragDom is an optional function to create what
* the drag handler will dragg around. for example, if you
* had a custom image you would like to drag, you could return
* and img element, with its src attribute set.
* @param {object} com
* @param {HTMLElement} com.To
* @param {function=} com.CreateDragDom
* @param {object} com.Data
* @param {string} com.Datatype
* @param {any} fun
* @returns
* @memberof View
*/
AttachDragListener(com, fun) {
let that = this;
let root = com.To || (console.log('com.To: <Native HTMLElement> is required!'));
if (!com.To) return fun('com.To: <Native HTMLElement> is required!', com);
let data = com.Data || {};
let datatype = com.Datatype || "HTMLElement";
// debugger;
$(root).attr('draggable', 'true');
let createDragDom;
createDragDom = com.CreateDragDom || null;
let div;
root.addEventListener('dragstart', function (evt) {
// debugger;
if (createDragDom) {
console.log(evt.dataTransfer.setDragImage(emptyImage(), 0, 0));
div = createDragDom();
event = evt;
div.css('pointer-events', 'none');
div.css('opacity', '.6');
div.css('position', 'fixed');
div.css('top', (evt.pageY + 20) + 'px');
div.css('left', (evt.pageX - (div.width() / 2)) + 'px');
$(document.body).append(div);
}
});
root.addEventListener('drag', function (evt) {
if (evt.pageX == 0 && evt.pageY == 0) {
return;
}
if (div) {
let pivotX = (div.width() / 2);
let pivotY = 20;
div.css('top', (evt.pageY + pivotY) + 'px');
div.css('left', (evt.pageX - pivotX) + 'px');
}
});
$(root).on('dragover', '*', ev => {
ev.preventDefault();
});
root.addEventListener('dragend', function (evt) {
if (div) {
div.remove();
}
let elem = $(document.elementFromPoint(evt.pageX, evt.pageY));
//count where in the page the shadow root is, so that
// we can account for it in DivX and DivY
let shadowX = 0, shadowY = 0;
//propagate up the tree
// i think you mean down the shadow tree
while (elem[0].shadowRoot) {
if (elem.hasClass('dropArea')) {
break;
}
elem = $(elem[0].shadowRoot.elementFromPoint(evt.pageX, evt.pageY));
}
shadowX += $(elem).offset().left;
shadowY += $(elem).offset().top;
while (elem.hasClass('dropArea') == null) {
elem = elem.parent();
}
let dropArea = elem;
while (!(elem[0].hasAttribute('viewpid') || ((elem[0].nodeName) && (elem[0].nodeName == "BODY")))) {
if (elem.parent().length > 0)
elem = elem.parent();
else
elem = $(elem[0].parentNode.host);
}
if (elem.attr('viewpid') == undefined) return;
let viewpid = elem.attr('viewpid');
that.send({
Cmd: "Drop",
Data: data,
Datatype: datatype,
PageX: evt.pageX,
PageY: evt.pageY,
DropArea: dropArea,
DivX: evt.pageX - elem.position().left - shadowX,
DivY: evt.pageY - elem.position().top - shadowY
}, viewpid, () => { });
});
fun(null, com);
}
/**
* @description Destroy will force a View to gracefully
* shut down. Sending itself a cleanup before garbage
* collection, if anything needs to be done.
* @param {any} com
* @param {any} fun
* @returns
* @memberof View
*/
async Destroy(com, fun) {
console.log(` ${this.emoji(0x1F4A3)} ${this.Vlt.type}::Destroy`);
if (this.Par.Destroying) return (console.log('This is a duplicate destroy, no action taken.'), fun(null, com));
this.Par.Destroying = true;
for (let item of this.Vlt.views)
await this.ascend('Destroy', {}, item);
try {
await this.ascend('Deconstruct');
} catch (e) { }
await this.ascend('Cleanup');
this.deleteEntity((err) => fun(null, com));
}
/**
* @description Event Command; sent right before a View will be garbage collected.
*
* Overridable
* @param {any} com
* @param {any} fun
* @memberof View
*/
Cleanup(com, fun) {
// debugger;
console.log("SUPER CLEANUP");
if ('DestroyListeners' in this.Par)
for (let pid of this.Par.DestroyListeners)
this.send({ Cmd: 'ChildDestroyed', Pid: this.Par.Pid }, pid, _ => _);
this.Vlt._root.remove();
fun(null, com);
}
/**
* @description Internal Private Command
*
* Subscribe to the event for when this View is destroyed.
* @param {any} com
* @param {any} fun
* @memberof View
*/
RegisterDestroyListener(com, fun) {
let pid = com.Passport.From;
if ('DestroyListeners' in this.Par) this.Par.DestroyListeners.push(pid);
else this.Par.DestroyListeners = [pid];
fun(null, com);
}
}
function injections() {
let that = this;
this.emoji = (char) => eval('\"\\u' + (0b1101100000000000 + (char - 0x10000
>>> 10)).toString(16) + '\\u' + (0b1101110000000000 +
(char & 0b1111111111)).toString(16) + "\"");
this.super = function (com, fun) {
if (com.Cmd in View.prototype) {
View.prototype[com.Cmd].call(this, com, fun);
} else {
fun('Command <' + com.Cmd + '> not in base class', com);
}
};
this.asuper = function (com) {
return new Promise((resolve, reject) => {
this.super(com, (err, cmd) => {
if (err) reject([err, cmd])
else resolve(cmd);
});
});
};
this.genModuleAsync = (modDef) => new Promise((resolve, reject) => {
this.genModule(modDef, (err, apx) => {
if (err) reject(err);
else resolve(apx);
});
});
this.evoke = async (pid) => {
this.send({
Cmd: 'Evoke'
}, pid, async (err, cmd) => {
if (cmd.Type == 'View') {
let newPar = {
View: cmd.View,
Par: cmd.Par || {},
Width: 500
};
let popup = await this.genModuleAsync({
Module: cmd.Container || 'xGraph.Popup',
Par: newPar
});
}
});
};
this.cdnImportCss = (url) => {
console.warn('cdnImportCss is deprecated, please use global.html to import globally, or use view.x.html to import locally.');
$(document.head).append($(`<link href="${url}" rel="stylesheet">`));
};
this.id = str => `XGRAPH-${this.Vlt.type}-${md5(this.Par.Pid + str)}-${str}`;
this.authenticate = async (cmd) => {
return (await this.ascend('Authenticate', { Command: cmd }, window.CommandAuthenticator)).Command;
}
this.evoke = async (pid, options) => {
this.send(Object.assign({
Cmd: 'Evoke'
}, options), pid, async (err, cmd) => {
if (cmd.Type == 'View') {
let newPar = {
View: cmd.View,
Par: cmd.Par || {},
Width: 500
};
let popup = await this.genModuleAsync({
Module: cmd.Container || 'xGraph.Popup',
Par: newPar
});
this.ascend('AddView', { View: popup }, this.Par.Pid);
}
});
};
//options no longer overrides Cmd param if it has a Cmd Key
this.ascend = (name, opts = {}, pid = this.Par.Pid) => new Promise((resolve, reject) => {
this.send(Object.assign(opts, { Cmd: name }), pid, (err, cmd) => {
if (err) reject([err, cmd]);
else resolve(cmd);
});
});
this.cdnImportJs = (url) => {
console.warn('cdnImportJs is deprecated, please use global.html to import globally, or use view.x.html to import locally.');
return new Promise(resolve => {
let script = $('<script></script>');
$(document.head).append(script);
script[0].onload = resolve;
script[0].src = url;
});
};
this.partial = (filepath, parameters = {}) => {
// log.v(`${this.Par.Module}: partial call for ${filepath}`);
// if its just the name of the file, sans extension, add that.
if (!filepath.endsWith('.x.html')) filepath += '.x.html';
// next, lets obtain that file
return new Promise(resolveFile => {
this.getFile(filepath, async (err, html) => {
if (err) return resolveFile();
// and split it up by either <~x or ~>, resulting in an array of alternating
// strings of html, javascript, html, ...etc
let parts = html.split(/<~x|~>/g);
// the generatorGenerator is the string of an IIFE that will return
// the generator of the HTML.
// everything from here is constructing this str to be eval'ed
let generatorGenrator = `//# sourceURL=${this.Vlt.type}-Generator\r\n(function() {`
// walk through the provided parameters, and add them
// to the IIFE scope
for (let key of Object.keys(parameters)) {
let val = parameters[key];
if (typeof val == 'string') val = `"${val}"`;
generatorGenrator += `let ${key} = ${val};\r\n`;
}
//enter the generator function that will be returned on eval
generatorGenrator += `\r\n\treturn async function(render) {\r\n`;
// loop over the alteranating html/js parts
for (let ipart = 0, state = 'HTML';
ipart < parts.length; ipart++ ,
state = (state == 'HTML' ? 'JS' : 'HTML')) {
let str = parts[ipart];
switch (state) {
case 'HTML': { // if its plain html, escape it properly,