This repository has been archived by the owner on Sep 24, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 38
/
includes.js
1159 lines (960 loc) · 174 KB
/
includes.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
(function(window){
"use strict";
// replace the define method from requirejs, if there is any.
// this is necessary to avoid modifying the minified underscore and jquery source.
// it's not possible to 'delete' the property.
// the define method is restored (if was existing) after the underscore and jquery library was registered
var originalDefine = window.define;
if (originalDefine) window.define = function nop() { };
var MiniProfiler = (function () {
"use strict";
var $,
_
;
var options,
container,
controls,
tmplCache = {},
fetchedIds = [],
fetchingIds = [], // so we never pull down a profiler twice
ajaxStartTime,
savedJson = []
;
var hasLocalStorage = function () {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
};
var getVersionedKey = function (keyPrefix) {
return keyPrefix + '-' + options.version;
};
var save = function (keyPrefix, value) {
if (!hasLocalStorage()) { return; }
// clear old keys with this prefix, if any
for (var i = 0; i < localStorage.length; i++) {
if ((localStorage.key(i) || '').indexOf(keyPrefix) > -1) {
localStorage.removeItem(localStorage.key(i));
}
}
// save under this version
localStorage[getVersionedKey(keyPrefix)] = value;
};
var load = function (keyPrefix) {
// for local dev, allow easy bypassing of cache
if (!hasLocalStorage() || window.location.href.indexOf('mpnocache=') > -1) { return null; }
return localStorage[getVersionedKey(keyPrefix)];
};
var fetchTemplates = function (success) {
var key = 'templates',
cached = load(key);
if (cached) {
$('body').append(cached);
success();
}
else {
$.get(options.path + 'includes.tmpl?v=' + options.version, function (data) {
if (data) {
save(key, data);
$('body').append(data);
success();
}
});
}
};
var getClientPerformance = function() {
return window.performance == null ? null : window.performance;
};
var fetchResults = function (ids) {
var clientPerformance, clientProbes, i, j, p, id, idx;
for (i = 0; i < ids.length; i++) {
id = ids[i];
clientPerformance = null;
clientProbes = null;
if (window.mPt) {
clientProbes = mPt.results();
for (j = 0; j < clientProbes.length; j++) {
clientProbes[j].d = clientProbes[j].d.getTime();
}
mPt.flush();
}
if (id == options.currentId) {
clientPerformance = getClientPerformance();
if (clientPerformance != null) {
// ie is buggy strip out functions
var copy = { navigation: {}, timing: {} };
var timing = $.extend({}, clientPerformance.timing);
for (p in timing) {
if (timing.hasOwnProperty(p) && !$.isFunction(timing[p])) {
copy.timing[p] = timing[p];
}
}
if (clientPerformance.navigation) {
copy.navigation.redirectCount = clientPerformance.navigation.redirectCount;
}
clientPerformance = copy;
// hack to add chrome timings
if (window.chrome && window.chrome.loadTimes) {
var chromeTimes = window.chrome.loadTimes();
if (chromeTimes.firstPaintTime) {
clientPerformance.timing["First Paint Time"] = Math.round(chromeTimes.firstPaintTime * 1000);
}
if (chromeTimes.firstPaintTime) {
clientPerformance.timing["First Paint After Load Time"] = Math.round(chromeTimes.firstPaintAfterLoadTime * 1000);
}
}
}
} else if (ajaxStartTime != null && clientProbes && clientProbes.length > 0) {
clientPerformance = { timing: { navigationStart: ajaxStartTime.getTime() } };
ajaxStartTime = null;
}
if ($.inArray(id, fetchedIds) < 0 && $.inArray(id, fetchingIds) < 0) {
idx = fetchingIds.push(id) - 1;
$.ajax({
url: options.path + 'results',
data: { id: id, clientPerformance: clientPerformance, clientProbes: clientProbes, popup: 1 },
dataType: 'json',
type: 'POST',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
success: function (json) {
fetchedIds.push(id);
if (json != "hidden") {
buttonShow(json);
}
},
complete: function () {
fetchingIds.splice(idx, 1);
}
});
}
}
};
var processJson = function (json) {
json.HasDuplicateCustomTimings = false;
json.HasCustomTimings = false;
json.HasTrivialTimings = false;
json.CustomTimingStats = {};
json.CustomLinks = json.CustomLinks || {};
json.TrivialMilliseconds = options.trivialMilliseconds;
json.Root.ParentTimingId = json.Id;
// different serializers handle dates differently
switch (typeof json.Started) {
case 'number':
json.Started = new Date(json.Started);
break;
case 'string':
// .NET's JavaScriptSerializer sends dates as /Date(1308024322065)/
var array = /-?\d+/.exec(json.Started);
if (array.length == 1) {
json.Started = new Date(parseInt(array[0]));
}
break;
}
processTiming(json, json.Root, 0);
};
var processTiming = function (json, timing, depth) {
timing.DurationWithoutChildrenMilliseconds = timing.DurationMilliseconds;
timing.Depth = depth;
timing.HasCustomTimings = timing.CustomTimings ? true : false;
timing.HasDuplicateCustomTimings = {};
json.HasCustomTimings = json.HasCustomTimings || timing.HasCustomTimings;
if (timing.Children) {
for (var i = 0; i < timing.Children.length; i++) {
timing.Children[i].ParentTimingId = timing.Id;
processTiming(json, timing.Children[i], depth + 1);
timing.DurationWithoutChildrenMilliseconds -= timing.Children[i].DurationMilliseconds;
}
} else {
timing.Children = [];
}
// do this after subtracting child durations
timing.IsTrivial = timing.DurationWithoutChildrenMilliseconds < options.trivialMilliseconds;
json.HasTrivialTimings = json.HasTrivialTimings || timing.IsTrivial;
if (timing.CustomTimings) {
timing.CustomTimingStats = {};
for (var customType in timing.CustomTimings) {
var customTimings = timing.CustomTimings[customType];
var customStat = {
Duration: 0,
Count: 0
};
var duplicates = {};
for (var i = 0; i < customTimings.length; i++) {
var customTiming = customTimings[i];
customTiming.ParentTimingId = timing.Id;
customStat.Duration += customTiming.DurationMilliseconds;
customStat.Count++;
if (customTiming.CommandString && duplicates[customTiming.CommandString]) {
customTiming.IsDuplicate = true;
timing.HasDuplicateCustomTimings[customType] = true;
json.HasDuplicateCustomTimings = true;
} else {
duplicates[customTiming.CommandString] = true;
}
}
timing.CustomTimingStats[customType] = customStat;
if (!json.CustomTimingStats[customType]) {
json.CustomTimingStats[customType] = {
Duration: 0,
Count: 0
};
}
json.CustomTimingStats[customType].Duration += customStat.Duration;
json.CustomTimingStats[customType].Count += customStat.Count;
}
} else {
timing.CustomTimings = {};
}
};
var renderTemplate = function (json) {
processJson(json);
return $($.trim(template('#profilerTemplate', json)));
};
var template = function (name, o) {
try {
var tmpl = tmplCache[name] || (tmplCache[name] = _.template($(name).html()));
o._self = o;
var html = tmpl(o);
return html;
} catch (e) {
console.log("error with: " + name + ": " + e);
}
};
var buttonShow = function (json) {
if (!container) {
// container not rendered yet
savedJson.push(json);
return;
}
var result = renderTemplate(json);
if (controls)
result.insertBefore(controls);
else
result.appendTo(container);
var button = result.find('.profiler-button'),
popup = result.find('.profiler-popup');
// button will appear in corner with the total profiling duration - click to show details
button.click(function () { buttonClick(button, popup); });
// small duration steps and the column with aggregate durations are hidden by default; allow toggling
toggleHidden(popup);
// lightbox in the queries
popup.find('.profiler-queries-show').click(function () { queriesShow($(this), result); });
// limit count
if (container.find('.profiler-result').length > options.maxTracesToShow)
resultRemove(container.find('.profiler-result').first());
// use this rather than .show() as .show won't set it properly if the css hasn't loaded yet
button.css('display', 'block');
};
var toggleHidden = function (popup) {
var trivial = popup.find('.profiler-toggle-trivial'),
toggleColumns = popup.find('.profiler-toggle-hidden-columns'),
trivialGaps = popup.parent().find('.profiler-toggle-trivial-gaps');
var toggleIt = function (node) {
var link = $(node),
klass = link.data('toggle-class'),
hideText = link.data('hide-text'),
showText = link.data('show-text'), // first call will be null
isHidden = link.text() != hideText;
// save our initial text to allow reverting
if (!showText) {
showText = link.text();
link.data('show-text', showText);
}
popup.parent().find('.' + klass).toggle(isHidden);
link.text(isHidden ? hideText : showText);
popupPreventHorizontalScroll(popup);
};
toggleColumns.add(trivial).add(trivialGaps).click(function () {
toggleIt(this);
});
// if option is set or all our timings are trivial, go ahead and show them
if (options.showTrivial || trivial.data('show-on-load')) {
toggleIt(trivial);
}
// if option is set, go ahead and show time with children
if (options.showChildrenTime) {
toggleIt(toggleColumns);
}
};
var buttonClick = function (button, popup) {
// we're toggling this button/popup
if (popup.is(':visible')) {
popupHide(button, popup);
}
else {
var visiblePopups = container.find('.profiler-popup:visible'),
theirButtons = visiblePopups.siblings('.profiler-button');
// hide any other popups
popupHide(theirButtons, visiblePopups);
// before showing the one we clicked
popupShow(button, popup);
}
};
var popupShow = function (button, popup) {
button.addClass('profiler-button-active');
popupSetDimensions(button, popup);
popup.show();
popupPreventHorizontalScroll(popup);
};
var popupSetDimensions = function (button, popup) {
var top = button.position().top - 1, // position next to the button we clicked
windowHeight = $(window).height(),
maxHeight = windowHeight - top - 40, // make sure the popup doesn't extend below the fold
isBottom = options.renderPosition.indexOf("bottom") != -1; // is this rendering on the bottom (if no, then is top by default)
if (isBottom) {
var bottom = $(window).height() - button.offset().top - button.outerHeight() + $(window).scrollTop(), // get bottom of button
isLeft = options.renderPosition.indexOf("left") != -1;
var horizontalPosition = isLeft ? "left" : "right";
popup
.css({ 'bottom': bottom, 'max-height': maxHeight })
.css(horizontalPosition, button.outerWidth() - 3); // move left or right, based on config
}
else {
popup
.css({ 'top': top, 'max-height': maxHeight })
.css(options.renderPosition, button.outerWidth() - 3); // move left or right, based on config
}
};
var popupPreventHorizontalScroll = function (popup) {
var childrenHeight = 0;
popup.children().each(function () { childrenHeight += $(this).height(); });
popup.css({ 'padding-right': childrenHeight > popup.height() ? 40 : 10 });
};
var popupHide = function (button, popup) {
button.removeClass('profiler-button-active');
popup.hide();
};
var resultRemove = function (result) {
var bg = $('.profiler-queries-bg'),
queries = result.find('.profiler-queries');
var hideQueries = bg.is(':visible') && queries.is(":visible");
if (hideQueries) {
bg.remove();
}
result.remove();
}
var queriesShow = function (link, result) {
var px = 30,
win = $(window),
height = win.height() - 2 * px,
queries = result.find('.profiler-queries');
// opaque background
$('<div class="profiler-queries-bg"/>').appendTo('body').css({ 'height': $(document).height() }).show();
// center the queries and ensure long content is scrolled
queries.css({ 'max-height': height });
// have to show everything before we can get a position for the first query
queries.show();
queriesScrollIntoView(link, queries, queries);
// syntax highlighting
prettyPrint();
};
var queriesScrollIntoView = function (link, queries, whatToScroll) {
var id = link.closest('tr').attr('data-timing-id'),
cells = queries.find('tr[data-timing-id="' + id + '"] td');
// ensure they're in view
whatToScroll.scrollTop(whatToScroll.scrollTop() + cells.first().position().top - 100);
// highlight and then fade back to original bg color; do it ourselves to prevent any conflicts w/ jquery.UI or other implementations of Resig's color plugin
cells.each(function () {
var cell = $(this),
highlightHex = '#FFFFBB',
highlightRgb = getRGB(highlightHex),
originalRgb = getRGB(cell.css('background-color')),
getColorDiff = function (fx, i) {
// adapted from John Resig's color plugin: http://plugins.jquery.com/project/color
return Math.max(Math.min(parseInt((fx.pos * (originalRgb[i] - highlightRgb[i])) + highlightRgb[i]), 255), 0);
};
// we need to animate some other property to piggy-back on the step function, so I choose you, opacity!
cell.css({ 'opacity': 1, 'background-color': highlightHex })
.animate({ 'opacity': 1 }, { duration: 2000, step: function (now, fx) {
fx.elem.style['backgroundColor'] = "rgb(" + [getColorDiff(fx, 0), getColorDiff(fx, 1), getColorDiff(fx, 2)].join(",") + ")";
}
});
});
};
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
var getRGB = function (color) {
var result;
// Check if we're already dealing with an array of colors
if (color && color.constructor == Array && color.length == 3) return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)) return [parseFloat(result[1]) * 2.55, parseFloat(result[2]) * 2.55, parseFloat(result[3]) * 2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) return [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) return [parseInt(result[1] + result[1], 16), parseInt(result[2] + result[2], 16), parseInt(result[3] + result[3], 16)];
// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
if (result = /rgba\(0, 0, 0, 0\)/.exec(color)) return colors['transparent'];
return null;
};
var bindDocumentEvents = function () {
$(document).bind('click keyup', function (e) {
// this happens on every keystroke, and :visible is crazy expensive in IE <9
// and in this case, the display:none check is sufficient.
var popup = $('.profiler-popup').filter(function () { return $(this).css("display") !== "none"; });
if (!popup.length) {
return;
}
var button = popup.siblings('.profiler-button'),
queries = popup.closest('.profiler-result').find('.profiler-queries'),
bg = $('.profiler-queries-bg'),
isEscPress = e.type == 'keyup' && e.which == 27,
hidePopup = false,
hideQueries = false;
if (bg.is(':visible')) {
hideQueries = isEscPress || (e.type == 'click' && !$.contains(queries[0], e.target) && !$.contains(popup[0], e.target));
}
else if (popup.is(':visible')) {
hidePopup = isEscPress || (e.type == 'click' && !$.contains(popup[0], e.target) && !$.contains(button[0], e.target) && button[0] != e.target);
}
if (hideQueries) {
bg.remove();
queries.hide();
}
if (hidePopup) {
popupHide(button, popup);
}
});
if (options.toggleShortcut && !options.toggleShortcut.match(/^None$/i)) {
$(document).bind('keydown', options.toggleShortcut, function(e) {
$('.profiler-results').toggle();
});
}
};
var initFullView = function () {
// first, get jquery tmpl, then render and bind handlers
fetchTemplates(function () {
// profiler will be defined in the full page's head
renderTemplate(profiler).appendTo(container);
var popup = $('.profiler-popup');
toggleHidden(popup);
prettyPrint();
// since queries are already shown, just highlight and scroll when clicking a "1 sql" link
popup.find('.profiler-queries-show').click(function () {
queriesScrollIntoView($(this), $('.profiler-queries'), $(document));
});
});
};
var initControls = function (container) {
if (options.showControls) {
controls = $('<div class="profiler-controls"><span class="profiler-min-max">m</span><span class="profiler-clear">c</span></div>').appendTo(container);
$('.profiler-controls .profiler-min-max').click(function () {
container.toggleClass('profiler-min');
});
container.hover(function () {
if ($(this).hasClass('profiler-min')) {
$(this).find('.profiler-min-max').show();
}
},
function () {
if ($(this).hasClass('profiler-min')) {
$(this).find('.profiler-min-max').hide();
}
});
$('.profiler-controls .profiler-clear').click(function () {
container.find('.profiler-result').remove();
});
}
else {
container.addClass('profiler-no-controls');
}
};
var installAjaxHandlers = function () {
var jQueryAjaxComplete = function (e, xhr, settings) {
if (xhr) {
// should be an array of strings, e.g. ["008c4813-9bd7-443d-9376-9441ec4d6a8c","16ff377b-8b9c-4c20-a7b5-97cd9fa7eea7"]
var stringIds = xhr.getResponseHeader('X-MiniProfiler-Ids');
if (stringIds) {
var ids = typeof JSON != 'undefined' ? JSON.parse(stringIds) : eval(stringIds);
fetchResults(ids);
}
}
};
// we need to attach our ajax complete handler to the window's (profiled app's) copy, not our internal, no conflict version
var window$ = window.jQuery;
// fetch profile results for any ajax calls
if (window$ && window$(document) && window$(document).ajaxComplete) {
window$(document).ajaxComplete(jQueryAjaxComplete);
if (window$.ajaxStart) {
window$(document).ajaxStart(function () { ajaxStartTime = new Date(); });
}
}
// fetch results after ASP Ajax calls
if (typeof (Sys) != 'undefined' && typeof (Sys.WebForms) != 'undefined' && typeof (Sys.WebForms.PageRequestManager) != 'undefined') {
// Get the instance of PageRequestManager.
var PageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
PageRequestManager.add_endRequest(function (sender, args) {
if (args) {
var response = args.get_response();
if (response.get_responseAvailable() && response._xmlHttpRequest != null) {
var stringIds = args.get_response().getResponseHeader('X-MiniProfiler-Ids');
if (stringIds) {
var ids = typeof JSON != 'undefined' ? JSON.parse(stringIds) : eval(stringIds);
fetchResults(ids);
}
}
}
});
}
// more Asp.Net callbacks
if (typeof (WebForm_ExecuteCallback) == "function") {
WebForm_ExecuteCallback = (function (callbackObject) {
// Store original function
var original = WebForm_ExecuteCallback;
return function (callbackObject) {
original(callbackObject);
var stringIds = callbackObject.xmlRequest.getResponseHeader('X-MiniProfiler-Ids');
if (stringIds) {
var ids = typeof JSON != 'undefined' ? JSON.parse(stringIds) : eval(stringIds);
fetchResults(ids);
}
}
})();
}
// also fetch results after ExtJS requests, in case it is being used
if (typeof (Ext) != 'undefined' && typeof (Ext.Ajax) != 'undefined' && typeof (Ext.Ajax.on) != 'undefined') {
// Ext.Ajax is a singleton, so we just have to attach to its 'requestcomplete' event
Ext.Ajax.on('requestcomplete', function(e, xhr, settings) {
//iframed file uploads don't have headers
if (!xhr || !xhr.getResponseHeader) {
return;
}
var stringIds = xhr.getResponseHeader('X-MiniProfiler-Ids');
if (stringIds) {
var ids = typeof JSON != 'undefined' ? JSON.parse(stringIds) : eval(stringIds);
fetchResults(ids);
}
});
}
if (typeof (MooTools) != 'undefined' && typeof (Request) != 'undefined') {
Request.prototype.addEvents({
onComplete: function() {
var stringIds = this.xhr.getResponseHeader('X-MiniProfiler-Ids');
if (stringIds) {
var ids = typeof JSON != 'undefined' ? JSON.parse(stringIds) : eval(stringIds);
fetchResults(ids);
}
}
});
}
// add support for AngularJS, which uses the basic XMLHttpRequest object.
if (window.angular && typeof (XMLHttpRequest) != 'undefined') {
var _send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function sendReplacement(data) {
if (this.onreadystatechange) {
if (typeof (this.miniprofiler) == 'undefined' || typeof (this.miniprofiler.prev_onreadystatechange) == 'undefined') {
this.miniprofiler = { prev_onreadystatechange: this.onreadystatechange };
this.onreadystatechange = function onReadyStateChangeReplacement() {
if (this.readyState == 4) {
var stringIds = this.getResponseHeader('X-MiniProfiler-Ids');
if (stringIds) {
var ids = typeof JSON != 'undefined' ? JSON.parse(stringIds) : eval(stringIds);
fetchResults(ids);
}
}
if (this.miniprofiler.prev_onreadystatechange != null)
return this.miniprofiler.prev_onreadystatechange.apply(this, arguments);
};
}
}
else if (this.onload) {
if (typeof (this.miniprofiler) == 'undefined' || typeof (this.miniprofiler.prev_onload) == 'undefined') {
this.miniprofiler = { prev_onload: this.onload };
this.onload = function onLoadReplacement() {
var stringIds = this.getResponseHeader('X-MiniProfiler-Ids');
if (stringIds) {
var ids = typeof JSON != 'undefined' ? JSON.parse(stringIds) : eval(stringIds);
fetchResults(ids);
}
if (this.miniprofiler.prev_onload != null)
return this.miniprofiler.prev_onload.apply(this, arguments);
};
}
}
return _send.apply(this, arguments);
}
}
// some elements want to be hidden on certain doc events
bindDocumentEvents();
};
var initPopupView = function () {
if (options.authorized) {
// all fetched profilings will go in here
container = $('<div class="profiler-results"/>').appendTo('body');
// MiniProfiler.RenderIncludes() sets which corner to render in - default is upper left
container.addClass("profiler-" + options.renderPosition);
//initialize the controls
initControls(container);
// we'll render results json via a jquery.tmpl - after we get the templates, we'll fetch the initial json to populate it
fetchTemplates(function () {
// get master page profiler results
fetchResults(options.ids);
});
if (options.startHidden) container.hide();
// if any data came in before the view popped up, render now
for (var i = 0; i < savedJson.length; i++) {
buttonShow(savedJson[i]);
}
}
else {
fetchResults(options.ids);
}
};
return {
init: function () {
var script = document.getElementById('mini-profiler');
if (!script || !script.getAttribute) return;
$ = MiniProfiler.$;
_ = MiniProfiler._;
options = (function () {
var version = script.getAttribute('data-version');
var path = script.getAttribute('data-path');
var currentId = script.getAttribute('data-current-id');
var ids = script.getAttribute('data-ids');
if (ids) ids = ids.split(',');
var position = script.getAttribute('data-position');
var toggleShortcut = script.getAttribute('data-toggle-shortcut');
if (script.getAttribute('data-max-traces'))
var maxTraces = parseInt(script.getAttribute('data-max-traces'));
if (script.getAttribute('data-trivial-milliseconds'))
var trivialMilliseconds = parseInt(script.getAttribute('data-trivial-milliseconds'));
if (script.getAttribute('data-trivial') === 'true') var trivial = true;
if (script.getAttribute('data-children') == 'true') var children = true;
if (script.getAttribute('data-controls') == 'true') var controls = true;
if (script.getAttribute('data-authorized') == 'true') var authorized = true;
if (script.getAttribute('data-start-hidden') == 'true') var startHidden = true;
return {
ids: ids,
path: path,
version: version,
renderPosition: position,
showTrivial: trivial,
trivialMilliseconds: trivialMilliseconds,
showChildrenTime: children,
maxTracesToShow: maxTraces,
showControls: controls,
currentId: currentId,
authorized: authorized,
toggleShortcut: toggleShortcut,
startHidden: startHidden
}
})();
var doInit = function () {
// when rendering a shared, full page, this div will exist
container = $('.profiler-result-full');
if (container.length) {
if (window.location.href.indexOf("&trivial=1") > 0) {
options.showTrivial = true
}
initFullView();
}
else {
initPopupView();
}
};
var wait = 0;
var finish = false;
var deferInit = function() {
if (finish) return;
if (window.performance && window.performance.timing && window.performance.timing.loadEventEnd == 0 && wait < 10000) {
setTimeout(deferInit, 100);
wait += 100;
} else {
finish = true;
init();
}
};
var init = function() {
if (options.authorized) {
var url = options.path + "includes.css?v=" + options.version;
if (document.createStyleSheet) {
document.createStyleSheet(url);
} else {
$('head').append($('<link rel="stylesheet" type="text/css" href="' + url + '" />'));
}
}
doInit();
};
$(installAjaxHandlers);
$(deferInit);
},
tmpl: function (name, o) {
return template(name, o);
},
getClientTimingByName: function (clientTiming, name) {
for (var i = 0; i < clientTiming.Timings.length; i++) {
if (clientTiming.Timings[i].Name == name) {
return clientTiming.Timings[i];
}
}
return { Name: name, Duration: "", Start: "" };
},
renderIndent: function (depth) {
var result = '';
for (var i = 0; i < depth; i++) {
result += ' ';
}
return result;
},
shareUrl: function (id) {
return options.path + 'results?id=' + id;
},
getClientTimings: function (clientTimings) {
var list = [];
var t;
if (!clientTimings.Timings) return [];
for (var i = 0; i < clientTimings.Timings.length; i++) {
t = clientTimings.Timings[i];
var trivial = t.Name != "Dom Complete" && t.Name != "Response" && t.Name != "First Paint Time";
trivial = t.Duration < 2 ? trivial : false;
list.push(
{
isTrivial: trivial,
name: t.Name,
duration: t.Duration,
start: t.Start
});
}
list.sort(function (a, b) { return a.start - b.start; });
return list;
},
getCustomTimings: function (root) {
var result = [],
addToResults = function (timing) {
if (timing.CustomTimings) {
for (var customType in timing.CustomTimings)
{
var customTimings = timing.CustomTimings[customType];
for (var i = 0, customTiming; i < customTimings.length; i++) {
customTiming = customTimings[i];
// HACK: add info about the parent Timing to each CustomTiming so UI can render
customTiming.ParentTimingName = timing.Name;
customTiming.CallType = customType;
result.push(customTiming);
}
}
}
if (timing.Children) {
for (var i = 0; i < timing.Children.length; i++) {
addToResults(timing.Children[i]);
}
}
};
// start adding at the root and recurse down
addToResults(root);
result.sort(function(a, b) {
return a.StartMilliseconds - b.StartMilliseconds;
});
var removeDuration = function(list, duration) {
var newList = [];
for (var i = 0; i < list.length; i++) {
var item = list[i];
if (duration.start > item.start) {
if (duration.start > item.finish) {
newList.push(item);
continue;
}
newList.push({ start: item.start, finish: duration.start });
}
if (duration.finish < item.finish) {
if (duration.finish < item.start) {
newList.push(item);
continue;
}
newList.push({ start: duration.finish, finish: item.finish });
}
}
return newList;
};
var processTimes = function (elem, parent) {
var duration = { start: elem.StartMilliseconds, finish: (elem.StartMilliseconds + elem.DurationMilliseconds) };
elem.richTiming = [duration];
if (parent != null) {
elem.parent = parent;
elem.parent.richTiming = removeDuration(elem.parent.richTiming, duration);
}
if (elem.Children) {
for (var i = 0; i < elem.Children.length; i++) {
processTimes(elem.Children[i], elem);
}
}
};
processTimes(root, null);
// sort results by time
result.sort(function (a, b) { return a.StartMilliseconds - b.StartMilliseconds; });
var determineOverlap = function(gap, node) {
var overlap = 0;
for (var i = 0; i < node.richTiming.length; i++) {
var current = node.richTiming[i];
if (current.start > gap.finish) {
break;
}
if (current.finish < gap.start) {
continue;
}
overlap += Math.min(gap.finish, current.finish) - Math.max(gap.start, current.start);
}
return overlap;
};
var determineGap = function (gap, node, match) {
var overlap = determineOverlap(gap, node);
if (match == null || overlap > match.duration) {
match = { name: node.Name, duration: overlap };
}
else if (match.name == node.Name) {
match.duration += overlap;
}
if (node.Children) {
for (var i = 0; i < node.Children.length; i++) {
match = determineGap(gap, node.Children[i], match);
}
}
return match;
};
var time = 0;
var prev = null;
$.each(result, function () {
this.prevGap = {
duration: (this.StartMilliseconds - time).toFixed(2),
start: time,
finish: this.StartMilliseconds
};