-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueueView.js
executable file
·1873 lines (1741 loc) · 65.4 KB
/
queueView.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 _ from "lodash";
import Config from "config"; // COMPS: disable this import
import * as repro from "./demo/data/repro.json"; // COMPS: "../data/repro.json"
/**
* QueueView
* Dashboard visualiser of cluster traffic
*
* @author psylwester(at)idmod(dot)org
* @version 2.7.1, 2019/10/23
* @requires ES6, lodash
*
*/
const QueueView = function(props) {
/* STATIC */
const MODE = {
Simulations: "Simulations",
WorkItems: "WorkItems"
};
const REPRO = {
enabled: false,
mode: MODE.Simulations,
data: _.get(repro, "default", { Highest:[],AboveNormal:[],Normal:[],BelowNormal:[],Lowest:[] }),
toggle: function(mode) {
this.mode = mode;
this.enabled = !this.enabled
}
};
const PRIORITY = {
1: {
key: "Highest",
name: "Highest Priority"
},
2: {
key: "AboveNormal",
name: "Above Normal"
},
3: {
key: "Normal",
name: "Normal Priority"
},
4: {
key: "BelowNormal",
name: "Below Normal"
},
5: {
key: "Lowest",
name: "Lowest Priority"
}
};
const STATE = {
"PreActive": [
"Orphan",
"Created",
"QueuedForCommission",
"CommissionRequested",
"Commissioned",
"Provisioning",
"Validating"
],
"Active": [
"Running",
"Waiting",
"QueuedForResume",
"ResumeRequested",
"Resumed",
"Retry"
],
"PostActive": [
"CancelRequested",
"Canceling",
"Canceled",
"Failed",
"Succeeded"
]
};
/**
* nullAuth supplants COMPS-UI-Auth when unavailable (e/g when dev without access to private repositories).
* @see this.config.auth
* @property {Function} getToken
* @property {Function} getUserName // add username here to demo
* @property {Function} tokenIsWaning
* @property {Function} refreshCredentials
*/
const nullAuth = {
getToken: () => "",
getUserName: () => "psylwester",
tokenIsWaning: () => false,
refreshCredentials: function(token, successHandler, failureHandler) {
if (!!successHandler && successHandler instanceof Function) {
successHandler();
}
}
};
/* CONFIG */
/**
* config are application settings, populated/overriden as necessary upon instantiation.
* NOTE: Setters here will process incoming values of the same key as the setter name.
*
* @private
* @property {Function} auth() will call whatever auth exists for project, or nullAuth when none.
* @property {String} cacheToken (and set/get) stores Token for looping fetches.
* @property {Function} api will call the instantiator with an intent and argument(s) (e/g intent:"refresh").
* @property {String} entity (and set/get) is the entity type being charted.
* @property {Integer} scoreSize (and set/get) is differentiating scale factor (range:0-100, default:24).
* @property {Boolean} mocked (and set/get) is flag for diverting from API to mocked Response data (default:false).
* @property {String} mockRoot is variable path to the mocked Response resources.
* @property {String} mockPath is the directory path of the current mocked resource.
* @property {String} endpoint is the relative or absolute path to API.
* @property {Float} workFlowScopeInDays (and get/set) is DateCreated ago to search for Work Items (default:0).
* @property {Boolean} workFlowsActiveOnly (and get/set) filters Work Items to active or all (default:false).
* @property {Integer} truncateMin is the number of items viewable in any Priority Bucket prior to truncation.
* @property {Integer} truncateMax is the maximum number of items total to be shown in a queue.
* @property {Boolean} debug (and get/set) when true, traces JSON.stringify(collection.last) per render.
* @property {Boolean} cancelable (and getter) when true, allows state change (to CancelRequested) of active items.
*/
const config = Object.assign({
auth: function () { return "comps" in window ? window.comps.auth : "idmauth" in window ? window.idmauth : nullAuth},
cacheToken: "",
recycleToken: function(erase) {
this.cacheToken = erase ? "" : this.auth().getToken();
},
get token () {
return this.cacheToken;
},
api: function(intent,...args) {
console.error("An API was not established by the instantiator for this intent:", intent, ...args);
return false;
},
entity: MODE.Simulations,
scoreSize: 24,
mocked: false,
mockRoot: ("comps" in window ? "/app/dashboard/data/" : "/data/"),
mockPath: "",
endpoint: ("comps" in window ? "/api/" : _.get(Config, "endpoint", "https://comps-dev.idmod.org/api/")),
workFlowScopeInDays: 0,
workFlowsActiveOnly: true,
truncateMin: 6,
truncateMax: 100,
set workFlowScope (num) {
this.workFlowScopeInDays = /^\d+\.?\d*$/.test(num) ? parseFloat(num) : 1; // default
},
get daysOfWorkFlows () {
return this.workFlowScopeInDays;
},
set workFlowsActive (boo) {
this.workFlowsActiveOnly = !!boo;
},
get activeWorkFlowsOnly () {
return this.workFlowsActiveOnly;
},
set modeEntity (val) {
this.entity = /work/i.test(val) ? MODE.WorkItems : MODE.Simulations;
},
set mockChoice (val) {
this.mockPath = val;
},
set useMockData (opt) {
if (this.mocked) {
// local wins
} else {
this.mocked = !!opt;
}
},
get isMocked () {
return this.mocked;
},
get mockURL () {
return (this.mockRoot + this.mockPath).replace(/\/\//,"/");
},
get isSimulations () {
return this.entity === MODE.Simulations;
},
get isWorkItems () {
return this.entity === MODE.WorkItems;
},
get mode () {
return this.entity;
},
cancelable: false,
set isCancelable (boo) {
this.cancelable = !!boo;
},
get isCancelable () {
return this.cancelable;
},
debug: false,
set logging (boo) {
this.debug = !!boo;
},
get debugging () {
return this.debug;
}
}, (props||{}));
/**
* view is the resource of DOM elements of concern here.
*
* @private
* @property {HTMLElement} root (get/set parent) is the templated element.
* @property {HTMLElement} output (get/set chart) is the chart container.
* @property {HTMLElement} figure (getter) is the intermediate element.
*
*/
const view = {
root: document.querySelector("[itemid=QueueView]"),
ouput: null,
set parent(ele) {
this.root = ele;
},
set chart(ele) {
this.output = ele;
},
get parent() {
return this.root;
},
get figure() {
return this.root.querySelector("figure") || this.root;
},
get chart() {
return this.output;
}
};
/**
* collection receives, transforms, and supplies data for display.
*
* @private
* @property {Object} input (unused) is internal cache of Request Response.
* @property {Object} output is the coalesced and transformed data for display.
*/
const collection = {
input: {
/* @TODO: Cache inputs for diff and refresh (of same) */
},
output: {},
/**
* groomDates prepares Date values for human consumption.
* @param {Object} data is the source of values to groom.
* @return {Object} the groomed data.
*/
groomDates: function (data) {
const vitalizeMockDate = function (dateString) {
let yesterday = new Date(Date.now() - (36 * 60 * 60 * 1000));
let yesterdate = yesterday.toISOString().split("T")[0];
let recently = new Date(Date.parse(yesterdate + "T" + dateString.split("T")[1]) + (16 * 60 * 60 * 1000));
return recently.toISOString();
};
const dateTransform = function (node) {
/* preprocess dates from service-supplied GMT to ui-conducive Local */
let basisDate, basisString, elapsedTime;
let basisISOString = _.get(node, "LastCreateTime", _.get(node, "DateCreated", null));
if (_.has(node, "Related")) {
basisISOString = _.get(_.first(node.Related), "DateCreated", null);
node["RelatedCount"] = node["Related"].length || 0;
}
if (!!basisISOString) {
if (config.isMocked) {
basisISOString = vitalizeMockDate(basisISOString);
}
basisDate = new Date(Date.parse(basisISOString));
basisString = basisDate.toLocaleDateString("en-US",{ month: "short", day: "numeric", hour:"2-digit", minute:"2-digit", second:"2-digit" });
elapsedTime = Date.now() - basisDate;
node["Elapsed"] = abbreviateTimeSpan(elapsedTime);
node["ElapsedTitle"] = "since: " + basisString;
}
};
if ("LastCreateTime" in data || "DateCreated" in data) {
// likely a simple entity node
dateTransform(data);
} else if (_.intersection(_.map(PRIORITY, "key"), Object.keys(data)).length > 0) {
// likely a root collection of priority buckets
Object.values(data).forEach(value => {
if (Array.isArray(value)) {
value.forEach(item => {
dateTransform(item);
});
}
});
} else if (Array.isArray(data)) {
// likely a collection update
data.forEach(item => {
dateTransform(item);
});
}
return data;
},
/**
* prepPriorities establishes priority buckets and scoring.
* @param {Object} data is likely a QueueState API Response.
* @return {Object} the prepped data.
*/
prepPriorities: function (data) {
const scoreSizes = function (splits, max=config.scoreSize) {
let result = [0];
let split = max/Math.max(1, splits-1);
let last = 0;
while (last < max) {
result.push(parseFloat((last+=split).toFixed(1)));
}
return result;
};
Object.values(PRIORITY).forEach(bucket => {
if (bucket.key in data) {
let counts = data[bucket.key].map((item) => { return item["SimulationCount"]; });
let scores = counts.filter((v,i) => counts.indexOf(v) === i).sort((a,b)=>a-b).reverse();
let sizes = scoreSizes(scores.length);
data[bucket.key].forEach(function(item) {
item.ViewSize = sizes[scores.indexOf(item["SimulationCount"])];
});
} else {
// Response data won't have empty buckets.
data[bucket.key] = [];
}
});
return data;
},
/**
* merge assigns new info to any Collection by aligning existing Ids with incoming Ids.
* @param {Object} data is the new info to merge into this Collection.
*/
merge: function(data) {
let updates = this.groomDates(data);
Object.values(this.output).forEach(value => {
if (Array.isArray(value)) {
value.forEach(item => {
if ("ExperimentId" in item && item.ExperimentId in updates) {
Object.assign(item, updates[item.ExperimentId]);
} else if ("Id" in item && item.Id in updates) {
Object.assign(item, updates[item.Id]); // TODO: SortOn LastCreateTime
}
});
}
});
},
/**
* findItemById is a deep search for a node containing the given GUID.
* @param {String} guid is the identifier to search for.
* @returns {null|Object} the node found, or null if not.
*/
findItemById: function(guid) {
let found = null;
for (let bucket in this.output) {
let related, entity = _.find(this.output[bucket], function(item) {
let match = guid === item.Id || guid === item.ExperimentId;
if (!match && _.has(item, "Flow.Related")) {
item.Flow.Related.forEach(relation => {
if (guid === relation.Id || guid === relation.ExperimentId) {
related = relation;
}
});
}
return match;
});
if (!!entity || !!related) {
found = entity||related;
break;
}
}
return found;
},
/**
* findItemsById is a deep search for node(s) containing the given GUID.
* @param {String} guid is the identifier to search for.
* @returns {Collection} an Array of node(s) found, or [] if none.
*/
findItemsById: function(guid) {
let found = [];
for (let bucket in this.output) {
this.output[bucket].forEach(item => {
if (guid === item.Id || guid === item.ExperimentId) {
found.push(item);
} else if (_.has(item, "Flow.Related")) {
item.Flow.Related.forEach(relation => {
if (guid === relation.Id || guid === relation.ExperimentId) {
found.push(relation);
}
});
}
});
}
return found;
},
/**
* augment puts new info at a known target of data.
* @param {Object} target is the destination of new info.
* @param {Object} source is the new info.
* @param {Boolean} pristine maintains new info without grooming dates.
*/
augment: function(target, source, pristine) {
Object.assign(target, !!pristine ? source : this.groomDates(source));
},
/**
* advance emulates a passage of time by moving mock data through states toward completion.
* @param {Number} rate is the relative speed to progress items (default:0.1).
*/
advance: function (rate=.1) {
Object.values(this.output).forEach(value => {
if (Array.isArray(value)) {
value.forEach(item => {
let advancing = Math.max(1,Math.ceil(item["SimulationCount"]*rate));
for (let state in item["SimulationStateCount"]) {
["Active","PreActive"].forEach(stage => {
if (STATE[stage].indexOf(state) > -1) {
let cohort = Math.min(item["SimulationStateCount"][state], advancing);
let upgrade = /Pre/.test(stage)?"Running":"Succeeded";
if (item["SimulationStateCount"][state] > cohort) {
item["SimulationStateCount"][state] -= cohort;
} else {
delete item["SimulationStateCount"][state];
}
// @TODO: Fail some?
if (upgrade in item["SimulationStateCount"]) {
item["SimulationStateCount"][upgrade] += cohort;
} else {
item["SimulationStateCount"][upgrade] = cohort;
}
}
});
}
});
}
});
},
/**
* update is the primary setter of new Request Response data.
* @param data
* @return {collection.output|{}}
*/
update: function (data) {
this.output = this.prepPriorities(this.groomDates(data));
return this.output;
},
reset: function () {
this.output = {};
},
get count () {
return _.flatMap(Object.values(this.output)).length;
},
/**
* latest provides the currently assembled data of queue.
* NOTE: Can by hijacked by REPRO settings to render repro.json.
* @returns {Collection} the Object of Arrays of Objects.
*/
get latest () {
if (REPRO.enabled) {
if (REPRO.mode === MODE.Simulations && config.isSimulations) {
return REPRO.data;
} else if (REPRO.mode === MODE.WorkItems && config.isWorkItems) {
return REPRO.data;
}
}
return this.output;
}
};
/* UTILITIES */
/**
* wait is essentially a setTimeout Promise.
* @usage wait(200).then(() => { doSomething(); });
* @param {Integer} time (required) is milliseconds of wait.
* @returns {Promise}
*/
const wait = time => new Promise((resolve) => setTimeout(resolve, time));
/**
* abbreviateTimeSpan makes human-legible time-span in units of mins, hrs, or days (as appropriate).
* NOTE: >48 hrs is in "days", >90 mins is in "hrs", >60 secs is in "mins", else "secs".
* @param {Integer} ms (required) is the time-span in milliseconds.
* @param {String} unit (optional) will force the given unit (e/g "days","hrs","mins","secs").
* @returns {String}
* }
*/
const abbreviateTimeSpan = function (ms, unit) {
let lingo = "unknown";
let forced = /^(sec|min|hr|day)/i.test(unit);
let secs = Math.round(Math.max(parseInt(ms||1),1000)/1000);
if ((secs > 60*60*48 && !forced) || /^day/i.test(unit)) {
lingo = (secs/60/60/24).toFixed(2) + " days";
} else if ((secs > 60*90 && !forced) || /^hr/i.test(unit)) {
lingo = (secs/60/60).toFixed(2) + " hrs";
} else if ((secs > 60 && !forced) || /^min/i.test(unit)) {
lingo = (secs/60).toFixed(2) + " mins";
} else if ((secs > 0 && !forced) || /^sec/i.test(unit)) {
lingo = secs + " secs";
}
return lingo;
};
/**
* scopeDateFilter supplies URL-compliant parameter for search filter.
* @returns {String} assumed to be a comma-delineated component of "?filters=" argument.
*/
const scopeDateFilter = function () {
let iso,hours = 24 * config.daysOfWorkFlows;
if (hours > 0) {
iso = new Date(Date.now()-Math.floor(1000*60*60*hours)).toISOString();
return `,DateCreated%3E=${iso}`;
} else {
return "";
}
};
/**
* deduceEntityType is a convenience standard for determining entity from expected properties.
* @param {Object} obj (required) is the data node containing expected properties.
* @returns {String} the entity type.
*/
const deduceEntityType = function (obj) {
if ("ExperimentId" in obj) {
return "Experiment";
} else if ("Worker" in obj) {
return "WorkItem";
} else if ("ObjectType" in obj) {
return obj.ObjectType;
} else {
return "Simulation";
}
};
/**
* isValidGuid determines validity of GUID string.
* @param {String} candidate (required) is the GUID to test.
* @returns {Boolean} true when valid.
*/
const isValidGuid = function (candidate) {
if (arguments.length > 0) {
return /[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}/.test(candidate);
} else {
return false;
}
};
/**
* breakCamelCase improves human-legibility of property keys.
* @param {String} value (required) is the property key to parse.
* @return {String} the human-legible term.
*/
const breakCamelCase = function(value) {
if (/^ExperimentId$/.test(value)) { value = "ExpId"; }
return !!value ? value.split(/(?=[A-Z])/).join(" ") : "";
};
/* EVENT-HANDLERS */
/**
* onClick handles view's click interactions.
* @param {Event}
*/
const onClick = function(event) {
if (event.target.nodeName == "A") {
event.stopPropagation();
event.stopImmediatePropagation();
} else if (event.target.nodeName == "DATA") {
event.stopPropagation();
event.stopImmediatePropagation();
if (window.getSelection && document.createRange) {
let range, selection = window.getSelection();
if (selection.toString().length < 1) {
window.setTimeout(function () {
range = document.createRange();
range.selectNodeContents(event.target);
selection.removeAllRanges();
selection.addRange(range);
}, 1);
}
}
} else if (event.target.nodeName == "BUTTON") {
event.stopPropagation();
event.preventDefault();
let guid, item, state, ele = event.target.closest("[itemid]");
if (!!ele) {
guid = ele.getAttribute("itemid");
item = collection.findItemById(guid);
state = event.target.getAttribute("data-state");
if (!!item && !!state) {
config.api("cancel", state, item);
} else {
config.api("notify", "Sorry, but that action could not be performed.", { level:"error" });
}
}
} else {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
let ele = event.target.closest("li[itemid]");
if (!!ele && !ele.classList.contains("block")) {
let guid = ele.getAttribute("itemid");
ele.classList.toggle("active");
ele.querySelector("dfn.tooltip").removeAttribute("style");
if (!ele.classList.contains("active")) {
ele.classList.add("closed");
wait(500).then(() => ele.classList.remove("closed"));
}
if (config.isSimulations && !ele.classList.contains("detailed")) {
if (isValidGuid(guid)) {
fetchItemDetail(guid, 2, data => {
distributeItemDetail(ele, data);
});
}
}
} else {
// click-away...
view.chart.querySelectorAll("li[itemid].active").forEach(tooltip => {
tooltip.classList.remove("active");
});
}
}
};
/**
* unClick removes the onClick listener.
* @param {HTMLElement} holder (required) is the element with listener attached.
*/
const unClick = function(holder) {
holder.removeEventListener("click", onClick);
};
/**
* onScroll (and global scrolling interval) flags scrolling elements as they scroll.
* @param {Event} the scroll event.
*/
let scrolling = 0;
const onScroll = function (event) {
if (!scrolling) {
event.target.classList.add("scrolling");
event.target.querySelectorAll("li[itemid].active").forEach(tooltip => {
// TODO: try harder to allow scroll of tooltips!
tooltip.classList.remove("active");
})
} else {
clearInterval(scrolling);
}
scrolling = setInterval(function () {
event.target.classList.remove("scrolling");
scrolling = 0;
}, 500);
};
/**
* unScroll removes the onScroll listener.
* @param {HTMLElement} holder (required) is the element with listener attached.
*/
const unScroll = function (holder) {
holder.removeEventListener("scroll", onScroll);
};
/**
* onMouseEnter is the primary trigger for engagement with charted items.
* @param {Event} the mouseenter event.
*/
const onMouseEnter = function (event) {
let ele = event.target.closest("li[itemid]");
if (!!ele) {
event.stopPropagation();
let guid = ele.getAttribute("itemid");
let rect = ele.getBoundingClientRect();
let width = parseInt(ele.querySelector("dfn.tooltip dl").offsetWidth);
let left = parseInt(rect.left);
let indent = parseInt(ele.querySelector("li.block").offsetWidth);
let mleft = Math.max(0, Math.max(event.pageX, (left + indent)) - left - indent - width);
let mtop = view.chart.scrollTop;
if (!ele.classList.contains("active")) {
ele.querySelector("dfn.tooltip").style.marginLeft = `${mleft}px`;
}
if (!!mtop) {
ele.querySelector("dfn.tooltip").style.marginTop = `-${mtop}px`;
}
// @TODO: Verify this is no longer needed...
// let top = parseInt(ele.closest("output").getBoundingClientRect().top);
// marginTop: !!ff ? 0 : -top /* FF-specific adjustment (due to scrollTop) */
if (!ele.classList.contains("detailed")) {
if (isValidGuid(guid)) {
fetchItemDetail(guid, 0, data => {
distributeItemDetail(ele, data);
});
fetchItemDetail(guid, 2, data => {
distributeItemDetail(ele, data);
});
}
}
}
};
/**
* unMouseEnter removes the onMouseEnter listener.
* @param {HTMLElement} holder (required) is the element with listener attached.
*/
const unMouseEnter = function (holder) {
holder.removeEventListener("mouseenter", onMouseEnter);
};
/* VIEW */
/**
* render executes all DOM-related mutations.
* @callback is passed the rendered view's container element.
*/
const render = function(callback) {
let owner = config.auth().getUserName();
const setQueueBucket = function (parent, name) {
let div = document.createElement("DIV");
let ol = document.createElement("OL");
let label = document.createElement("LABEL");
label.appendChild(document.createTextNode(name));
div.appendChild(label);
div.appendChild(ol);
div.classList.add("queue-bucket");
parent.prepend(div);
return div;
};
const setQueueItems = function (parent, key) {
let doc = document.createDocumentFragment();
let ol = parent.querySelector("OL");
let data = collection.latest[key]||[];
if (config.isWorkItems) {
data = data.filter(item => {
if (!config.activeWorkFlowsOnly) {
return true;
} else {
let thisActive = _.has(item, "State") && _.intersection(_.concat(STATE.PreActive,STATE.Active),[item.State]).length > 0;
let relatedActive = _.has(item, "Active") && item.Active;
return thisActive || relatedActive;
}
});
}
if (_.isEmpty(data)) {
let li = document.createElement("LI");
li.appendChild(document.createTextNode("empty"));
ol.appendChild(li);
parent.classList.add("empty");
} else {
data.some((item,index) => {
if (index == config.truncateMin && !view.figure.classList.contains("untruncated")) {
view.figure.classList.add("truncated");
return true;
}
if (index == config.truncateMax) {
return true;
}
let li = document.createElement("LI");
let ul = document.createElement("UL");
let block = document.createElement("LI");
let more = document.createElement("LI");
let icon = document.createElement("I");
icon.classList.add("material-icons");
// icon.setAttribute("title", "Pin/Unpin Details");
icon.appendChild(document.createTextNode("more_vert"));
more.appendChild(icon);
more.classList.add("more");
block.appendChild(document.createElement("DFN"));
block.classList.add("block");
block.style.width = `${item.ViewSize}%`;
doc.appendChild(li);
li.appendChild(ul);
ul.appendChild(block);
ul.appendChild(more);
if ("Owner" in item && !!owner && item.Owner === owner) {
ul.classList.add("owner");
}
if (_.has(item, "SimulationStateCount")) {
li.setAttribute("itemid", item["ExperimentId"]);
setQueueItemDetails(block, item);
setQueueItemSegments(ul, item);
} else if (_.has(item, "Flow")) {
li.setAttribute("itemid", item["Id"]);
setQueueItemDetails(block, item);
setQueueItemFlow(ul, item.Flow);
} else {
li.setAttribute("itemid", "orphan");
collection.augment(item, {"SimulationStateCount":{"Orphan":1}}, true);
setQueueItemDetails(block, item);
setQueueItemSegments(ul, item);
}
});
ol.appendChild(doc);
}
};
const setQueueItemSegments = function (fragment, item) {
let info = item["SimulationStateCount"];
let tip = document.createElement("INS");
tip.appendChild(document.createElement("B"));
tip.classList.add("arrow");
if (!info) return;
["PreActive","Active","PostActive"].forEach(stage => {
STATE[stage].forEach(status => {
if (status in info) {
let a = document.createElement("A");
let li = document.createElement("LI");
let val = document.createElement("VAR");
// li.setAttribute("title", status);
li.classList.add(status);
li.style.flexGrow = info[status];
if (stage == "Active") {
li.classList.add("process"); /* @TODO: consider the stage as className */
}
if (/Orphan/.test(status)) {
a.setAttribute("href",`/#explore/Simulations?filters=Owner=${item.Owner}&offset=0`);
// a.setAttribute("title", `Explore ${item.Owner}'s Simulations`);
} else {
a.setAttribute("href",`/#explore/Simulations?filters=ExperimentId=${item.ExperimentId},SimulationState=${status}&offset=0`);
// a.setAttribute("title", info[status] > 1 ? `Explore These ${status} Simulations` : `Explore This ${status} Simulation`);
}
val.appendChild(document.createTextNode(info[status]));
a.appendChild(val);
li.appendChild(a);
if (/Succeeded/.test(status)) {
let median = document.createElement("TIME");
median.classList.add("median");
median.appendChild(document.createTextNode("0:00"))
li.appendChild(median);
}
fragment.appendChild(li);
li.addEventListener("mouseenter", onMouseEnter);
}
});
});
fragment.querySelector("li:last-of-type").appendChild(tip);
};
const setQueueItemFlow = function (fragment, info) {
let id = info["Ancestors"][0].Id;
_.concat(info["Ancestors"],info["Related"])
.filter(item => item["ObjectType"] != "AssetCollection")
.forEach(member => {
let a = document.createElement("A");
let li = document.createElement("LI");
let val = document.createElement("VAR");
let tip = document.createElement("INS");
let type = member.ObjectType || "WorkItem";
if (/^Experiment$/i.test(type)) {
if ("SimulationStateCount" in member) {
setQueueItemSegments(fragment, member);
} else {
fetchItemDetail(id, 1,function(){
setQueueItemSegments(fragment, member);
});
}
fragment.querySelector("li:last-of-type").style.marginRight = "22px";
} else {
tip.appendChild(document.createElement("B"));
tip.classList.add("arrow");
val.appendChild(document.createTextNode("Worker" in member ? member.Worker.Name : type));
a.appendChild(val);
a.setAttribute("href",`/#explore/WorkItems?filters=Id=${id}&related=true&offset=0`);
// a.setAttribute("title", `Explore This Workflow`);
li.appendChild(a);
li.appendChild(tip);
// li.setAttribute("title", member.Name);
li.classList.add(member["State"]||member["SimulationState"]||"DefaultState", type);
if (_.intersection(STATE.Active,li.classList.value.split(" ")).length > 0) {
li.classList.add("process");
}
li.style.flexGrow = /work/i.test(type) ? 1 : 10;
li.style.marginRight = "22px";
fragment.appendChild(li);
li.addEventListener("mouseenter", onMouseEnter);
}
});
fragment.querySelector("li:last-of-type").style.marginRight = "0";
};
const setQueueItemDetails = function (fragment, info) {
/* TODO: coalesce/call appendTooltip(); */
const implement = function (key, index, arr, obj) {
let dd = document.createElement("DD");
let name = document.createElement("VAR");
let value = document.createElement("DATA");
if (key === Object(key)) {
for (let k in key) { implement(k,index,arr,key); }
} else if (/^-$/.test(key)) {
let divider = document.createElement("HR");
dd.appendChild(divider);
dl.appendChild(dd);
} else {
name.appendChild(document.createTextNode(breakCamelCase(key)));
value.appendChild(document.createTextNode(!!obj?obj[key]:info[key]));
if (key+"Title" in (obj||info)) {
dd.setAttribute("title", (obj||info)[key+"Title"]);
}
dd.setAttribute("itemprop", key);
dd.appendChild(name);
dd.appendChild(value);
dl.appendChild(dd);
}
};
const implementAction = function () {
let dd = document.createElement("DD");
let button = document.createElement("BUTTON");
button.appendChild(document.createTextNode("Option to Cancel..."));
button.setAttribute("title", "Stop Processing...");
button.setAttribute("aria-label", "Cancel");
button.setAttribute("data-state", "CancelRequested");
button.classList.add("Stoppable");
dd.setAttribute("itemprop", "Action");
dd.appendChild(button);
dl.appendChild(dd);
};
let dfn = fragment.querySelector("DFN");
let dl = document.createElement("DL");
let dt = document.createElement("DT");
let a = document.createElement("A");
dt.appendChild(a);
dl.appendChild(dt);
// dl.setAttribute("title", "pin/unpin this info");
if (_.has(info, "ExperimentId")) {
a.appendChild(document.createTextNode("Experiment"));
a.setAttribute("href",`/#explore/Simulations?filters=ExperimentId=${info.ExperimentId}&offset=0`);
// a.setAttribute("title", "Explore This Experiment");
[
"Owner","ExperimentId","NodeGroup","Elapsed","SimulationCount",
"-",{"Runtime":"Stats as work completes..."},
"-",{"Utilization":"Details when available..."}
].forEach(implement);
if (config.isCancelable && "Owner" in info && !!owner && info.Owner === owner) {
implementAction();
}
} else if (_.has(info, "Flow")) {
a.appendChild(document.createTextNode(info["Name"]||"Workflow"));
a.setAttribute("href",`/#explore/WorkItems?filters=Id=${info.Id}&related=true&offset=0`);
// a.setAttribute("title", `Explore This Workflow`);
["Owner","Id","EnvironmentName","Elapsed","RelatedCount"].forEach(implement);
if (_.has(info.Flow, "Related") && info.Flow.Related.length > 0) {
info.Flow.Related.forEach(relation => {
implement("-",0,[],relation);
implement("ObjectType",0,[],relation);
if (_.has(relation, "Worker.Name")) {
implement("Worker",0,[],{"Worker":_.get(relation, "Worker.Name")});
}
implement("Id",0,[],relation);
});
}
} else {
a.appendChild(document.createTextNode("Orphan Simulation"));
a.setAttribute("href",`/#explore/Simulations?filters=Owner=${info.Owner}&offset=0`);
// a.setAttribute("title", `Explore ${info.Owner}'s Simulations`);
["Owner","NodeGroup","Elapsed"].forEach(implement);
}
dfn.classList.add("tooltip");
dfn.appendChild(dl);
appendPin(dl);
};
wait(0)
.then(() => destroy())
.then(() => {
view.parent = document.querySelector(config.selector);
view.chart = view.parent.querySelector(config.chartContainer);
view.chart.addEventListener("scroll", onScroll);
view.chart.addEventListener("click", onClick);