forked from graphite-project/graphite-web
/
composer_widgets.js
1319 lines (1186 loc) · 44.5 KB
/
composer_widgets.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
/* Copyright 2008 Orbitz WorldWide
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* ======================================================================
*
* PLEASE DO NOT USE A COMMA AFTER THE FINAL ITEM IN A LIST.
*
* ======================================================================
*
* It works fine in FF / Chrome, but completely breaks Internet Explorer.
* Thank you.
*
*/
var DEFAULT_WINDOW_WIDTH = 600;
var DEFAULT_WINDOW_HEIGHT = 400;
var Composer;
function createComposerWindow(myComposer) {
//This global is an ugly hack, probly need to make these widgets into more formal objects
//and keep their associated Composer object as an attribute.
Composer = myComposer;
//Can't define this inline because I need a reference in a closure below
var timeDisplay = new Ext.Toolbar.TextItem({text: "Now showing the past 24 hours"});
var topToolbar = [
createToolbarButton('Update Graph', 'updateGraph.gif', updateGraph),
'-',
createToolbarButton('Select a Date Range', 'calBt.gif', toggleWindow(createCalendarWindow) ),
createToolbarButton('Select Recent Data', 'arrow1.gif', toggleWindow(createRecentWindow) ),
createToolbarButton('Open in GraphPlot', 'line_chart.png', function() { window.open('/graphlot/?' + Composer.url.queryString,'_blank') }),
'-',
timeDisplay
];
if (GraphiteConfig.showMyGraphs) {
var saveButton = createToolbarButton('Save to My Graphs', 'save.gif', saveMyGraph);
var deleteButton = createToolbarButton('Delete from My Graphs', 'delete.gif', deleteMyGraph);
topToolbar.splice(0, 0, saveButton, deleteButton);
}
var bottomToolbar = [
{ text: "Graph Options", menu: createOptionsMenu() },
{ text: "Graph Data", handler: toggleWindow(GraphDataWindow.create.createDelegate(GraphDataWindow)) },
{ text: "Auto-Refresh", id: 'autorefresh_button', enableToggle: true, toggleHandler: toggleAutoRefresh }
];
var win = new Ext.Window({
width: DEFAULT_WINDOW_WIDTH,
height: DEFAULT_WINDOW_HEIGHT,
title: "Graphite Composer",
layout: "border",
region: "center",
maximizable: true,
closable: false,
tbar: topToolbar,
buttons: bottomToolbar,
buttonAlign: 'left',
items: { html: "<img id='image-viewer' src='/render'/>", region: "center" },
listeners: {
activate: keepDataWindowOnTop,
show: fitImageToWindow,
resize: fitImageToWindow
}
});
// Tack on some convenience closures
win.updateTimeDisplay = function (time) {
var text;
if (time.mode == 'date-range') {
text = "<b>From</b> " + time.startDate.toLocaleString();
text += " <b>Until</b> " + time.endDate.toLocaleString();
text = text.replace(/:00 /g, " "); // Strip out the seconds
} else if (time.mode == 'recent') {
text = "Now showing the past " + time.quantity + " " + time.units;
}
timeDisplay.getEl().dom.innerHTML = text;
};
win.updateUI = function () {
var toggled = Composer.url.getParam('autorefresh') ? true : false;
Ext.getCmp('autorefresh_button').toggle(toggled);
updateCheckItems();
};
win.getImage = function () {
return Ext.getDom('image-viewer');
};
return win;
}
function toggleWindow(createFunc) { // Convenience for lazily creating toggled dialogs
function toggler (button, e) {
if (!button.window) { //First click, create the window
button.window = createFunc();
}
if (button.window.isVisible()) {
button.window.hide();
} else {
button.window.show();
}
}
return toggler;
}
function ifEnter(func) { // Convenience decorator for specialkey listener definitions
return function (widget, e) {
if (e.getCharCode() == Ext.EventObject.RETURN) {
func(widget);
}
}
}
function keepDataWindowOnTop () {
if (GraphDataWindow.window && GraphDataWindow.window.isVisible()) {
GraphDataWindow.window.toFront();
}
}
function fitImageToWindow(win) {
Composer.url.setParam('width', win.getInnerWidth());
Composer.url.setParam('height', win.getInnerHeight());
try {
Composer.updateImage();
} catch (err) {
//An exception gets thrown when the initial resize event
//occurs prior to rendering the image viewer. Safe to ignore.
}
}
/* Toolbar stuff */
function createToolbarButton(tip, icon, handler) {
return new Ext.Toolbar.Button({
style: "padding-left:10pt; background:transparent url(../content/img/" + icon + ") no-repeat scroll 0% 50%",
handler: handler,
handleMouseEvents: false,
text: " ",
listeners: {
render: function (button) {
button.el.toolTip = new Ext.ToolTip({
html: tip,
showDelay: 100,
dismissDelay: 10000,
target: button.el
});
}
}
});
}
/* "Date Range" Calendar */
function createCalendarWindow() {
// Start/End labels
var style = "font-family: tahoma,arial,verdana,sans-serif; font-size:11px;";
var startDateHeader = {
html: "<center><span id='startDate' style=\"" + style + "\">Start Date</span></center>"
};
var endDateHeader = {
html: "<center><span id='endDate' style=\"" + style + "\">End Date</span></center>"
};
// Date controls
var startDateControl = new Ext.DatePicker({
id: 'start-date',
maxDate: new Date()
});
var endDateControl = new Ext.DatePicker({
id: 'end-date',
maxDate: new Date()
});
startDateControl.on('select', calendarSelectionMade);
endDateControl.on('select', calendarSelectionMade);
// Time controls
startTimeControl = new Ext.form.TimeField({
id: 'start-time',
increment: 30,
allowBlank: false,
value: "12:00 AM",
listeners: {select: calendarSelectionMade, specialkey: ifEnter(calendarSelectionMade)}
});
endTimeControl = new Ext.form.TimeField({
id: 'end-time',
allowBlank: false,
value: "11:59 PM",
listeners: {select: calendarSelectionMade, specialkey: ifEnter(calendarSelectionMade)}
});
var myWindow;
var resizeStuff = function () {
startTimeControl.setWidth( startDateControl.el.getWidth() );
endTimeControl.setWidth( endDateControl.el.getWidth() );
myWindow.setWidth( startDateControl.el.getWidth() + endDateControl.el.getWidth() + myWindow.getFrameWidth() );
//myWindow.setHeight( startDateControl.el.getHeight() + startTimeControl.el.getHeight() + myWindow.getFrameHeight() );
};
myWindow = new Ext.Window({
title: "Select Date Range",
layout: 'table',
height: 300,
width: 400,
layoutConfig: { columns: 2 },
closeAction: 'hide',
items: [
startDateHeader,
endDateHeader,
startDateControl,
endDateControl,
startTimeControl,
endTimeControl
],
listeners: {show: resizeStuff}
});
return myWindow;
}
function calendarSelectionMade(datePicker, selectedDate) {
var startDate = getCalendarSelection('start');
var endDate = getCalendarSelection('end');
Composer.url.setParam('from', asDateString(startDate) );
Composer.url.setParam('until', asDateString(endDate) );
Composer.updateImage();
Composer.window.updateTimeDisplay({
mode: 'date-range',
startDate: startDate,
endDate: endDate
});
}
function getCalendarSelection(which) {
var myDate = Ext.getCmp(which + '-date').getValue();
var myTime = Ext.getCmp(which + '-time').getEl().dom.value; // Need to grab the raw textfield value, which may not be selected
var myHour = myTime.match(/(\d+):/)[1];
var myMinute = myTime.match(/:(\d+)/)[1];
if (myTime.match(/\bAM\b/i) && myHour == '12') {
myHour = 0;
}
if (myTime.match(/\bPM\b/i) && myHour != '12') {
myHour = parseInt(myHour) + 12;
}
return myDate.add(Date.HOUR, myHour).add(Date.MINUTE, myMinute);
}
function asDateString(dateObj) {
return dateObj.format('H:i_Ymd');
}
/* "Recent Data" dialog */
function toggleWindow(createFunc) {
function toggler (button, e) {
if (!button.window) { //First click, create the window
button.window = createFunc();
}
if (button.window.isVisible()) {
button.window.hide();
} else {
button.window.show();
}
}
return toggler;
}
function createRecentWindow() {
var quantityField = new Ext.form.NumberField({
id: 'time-quantity',
grow: true,
value: 24,
listeners: {change: recentSelectionMade, specialkey: ifEnter(recentSelectionMade)}
});
var unitSelector = new Ext.form.ComboBox({
id: 'time-units',
editable: false,
triggerAction: 'all',
mode: 'local',
store: ['minutes', 'hours', 'days', 'weeks', 'months', 'years'],
width: 75,
value: 'hours',
listeners: {select: recentSelectionMade}
});
return new Ext.Window({
title: "Select a Recent Time Range",
layout: 'table',
height: 60, //there's gotta be a way to auto-size these windows!
width: 235,
layoutConfig: { columns: 3 },
closeAction: 'hide',
items: [
{
html: "<div style=\"border: none; background-color: rgb(223,232,246)\">View the past</div>",
style: "border: none; background-color: rgb(223,232,246)"
},
quantityField,
unitSelector
]
});
}
function recentSelectionMade(combo, record, index) {
var quantity = Ext.getCmp('time-quantity').getValue();
var units = Ext.getCmp('time-units').getValue();
var fromString = '-' + quantity + units;
Composer.url.setParam('from', fromString);
Composer.url.removeParam('until');
Composer.updateImage();
Composer.window.updateTimeDisplay({
mode: 'recent',
quantity: quantity,
units: units
});
}
/* "Save to MyGraphs" */
function saveMyGraph(button, e) {
var myGraphName = "";
if (Composer.state.myGraphName) {
myGraphName = Composer.state.myGraphName;
var tmpArray = myGraphName.split('.');
if (tmpArray.length > 1) {
tmpArray = tmpArray.slice(1, tmpArray.length);
myGraphName = tmpArray.join('.');
}
}
Ext.MessageBox.prompt(
"Save to My Graphs", //title
"Please enter a name for your Graph", //prompt message
function (button, text) { //handler
if (button != 'ok') {
return;
}
if (!text) {
Ext.Msg.alert("You must enter a graph name!");
return;
}
if (text.charAt(text.length - 1) == '.') {
Ext.Msg.alert("Graph names cannot end in a period.");
return;
}
//Save the name for future use and re-load the "My Graphs" tree
Composer.state.myGraphName = text;
Browser.trees.mygraphs.reload();
//Send the request
Ext.Ajax.request({
method: 'GET',
url: '../composer/mygraph/',
params: {action: 'save', graphName: text, url: Composer.url.getURL()},
callback: handleSaveMyGraphResponse
});
},
this, //scope
false, //multiline
myGraphName ? myGraphName : "" //default value
);
}
function handleSaveMyGraphResponse(options, success, response) {
var message;
if (success) {
message = "Graph saved successfully";
} else {
message = "There was an error saving your Graph, please try again later.";
}
Ext.MessageBox.show({
title: "Save to My Graphs - Result",
msg: message,
buttons: Ext.MessageBox.OK
});
}
function deleteMyGraph() {
Ext.MessageBox.prompt(
"Delete a saved My Graph", //title
"Please enter the name of the My Graph you wish to delete", //prompt message
function (button, text) { //handler
if (button != 'ok') {
return;
}
if (!text) {
Ext.Msg.alert("Invalid My Graph name!");
return;
}
Browser.trees.mygraphs.reload();
//Send the request
Ext.Ajax.request({
method: 'GET',
url: '../composer/mygraph/',
params: {action: 'delete', graphName: text},
callback: function (options, success, response) {
var message = success ? "Graph deleted successfully" : "There was an error performing the operation.";
Ext.Msg.show({
title: 'Delete My Graph',
msg: message,
buttons: Ext.Msg.OK
});
}
});
},
this, //scope
false, //multiline
Composer.state.myGraphName ? Composer.state.myGraphName : "" //default value
);
}
/* Graph Data dialog */
var GraphDataWindow = {
create: function () {
var _this = this;
this.targetList = new Ext.ListView({
store: TargetStore,
multiSelect: true,
emptyText: "No graph targets",
reserveScrollOffset: true,
columnSort: false,
hideHeaders: true,
width: 385,
height: 140,
columns: [ {header: "Graph Targets", width: 1.0, dataIndex: "value"} ],
listeners: {
contextmenu: this.targetContextMenu,
afterrender: this.targetChanged,
selectionchange: this.targetChanged,
dblclick: function (targetList, index, node, e) {
targetList.select(index);
this.editTarget();
},
scope: this
}
});
var targetsPanel = new Ext.Panel({
region: 'center',
width: 400,
height: 200,
layout: 'fit',
items: this.targetList
});
var buttonPanel = new Ext.Panel({
region: 'east',
width: 100,
baseCls: 'x-window-mc',
layout: {
type: 'vbox',
align: 'stretch'
},
defaults: { xtype: 'button', disabled: true },
items: [
{
text: 'Add',
handler: this.addTarget.createDelegate(this),
disabled: false
}, {
text: 'Edit',
id: 'editTargetButton',
handler: this.editTarget.createDelegate(this)
}, {
text: 'Remove',
id: 'removeTargetButton',
handler: this.removeTarget.createDelegate(this)
}, {
text: 'Apply Function',
id: 'applyFunctionButton',
menuAlign: 'tr-tl',
menu: {
subMenuAlign: 'tr-tl',
defaults: {
defaultAlign: 'tr-tl'
},
items: createFunctionsMenu()
}
}, {
text: 'Undo Function',
handler: this.removeOuterCall.createDelegate(this),
id: 'undoFunctionButton'
}
]
});
this.window = new Ext.Window({
title: "Graph Data",
height: 200,
width: 600,
closeAction: 'hide',
layout: 'border',
items: [
targetsPanel,
buttonPanel
],
listeners: {
afterrender: function () {
if (_this.targetList.getNodes().length > 0) {
_this.targetList.select(0);
}
}
}
});
return this.window;
},
targetChanged: function () {
if (!this.targetList) { return; } // Ignore initial call
var selected;
try {
selected = this.getSelectedTargets().length;
} catch (e) {
return;
}
if (selected == 0) {
Ext.getCmp('editTargetButton').disable();
Ext.getCmp('removeTargetButton').disable();
Ext.getCmp('applyFunctionButton').disable();
Ext.getCmp('undoFunctionButton').disable();
} else {
Ext.getCmp('editTargetButton').enable();
Ext.getCmp('removeTargetButton').enable();
Ext.getCmp('applyFunctionButton').enable();
Ext.getCmp('undoFunctionButton').enable();
}
},
targetContextMenu: function (targetList, index, node, e) {
/* Select the right-clicked row unless it is already selected */
if (! targetList.isSelected(index) ) {
targetList.select(index);
}
var removeItem = {text: "Remove", handler: this.removeTarget.createDelegate(this)};
var editItem = {text: "Edit", handler: this.editTarget.createDelegate(this)};
if (this.getSelectedTargets().length == 0) {
removeItem.disabled = true;
editItem.disabled = true;
}
var contextMenu = new Ext.menu.Menu({ items: [removeItem, editItem] });
contextMenu.showAt( e.getXY() );
e.stopEvent();
},
applyFuncToEach: function (funcName, extraArg) {
var _this = this;
function applyFunc() {
Ext.each(_this.getSelectedTargets(),
function (target) {
var newTarget;
if (extraArg) {
newTarget = funcName + '(' + target + ',' + extraArg + ')';
} else {
newTarget = funcName + '(' + target + ')';
}
replaceTarget(target, newTarget);
_this.targetList.select( TargetStore.findExact('value', newTarget), true);
}
);
Composer.syncTargetList();
Composer.updateImage();
}
return applyFunc;
},
applyFuncToEachWithInput: function (funcName, question, options) {
if (options == null) {
options = {};
}
function applyFunc() {
Ext.MessageBox.prompt(
"Input Required", //title
question, //message
function (button, inputValue) { //handler
if (button == 'ok' && (options.allowBlank || inputValue != '')) {
if (options.quote) {
inputValue = '"' + inputValue + '"';
}
applyFuncToEach(funcName, inputValue)();
}
},
this, //scope
false, //multiline
"" //initial value
);
}
applyFunc = applyFunc.createDelegate(this);
return applyFunc;
},
applyFuncToAll: function (funcName) {
function applyFunc() {
var args = this.getSelectedTargets().join(',');
var oldTargets = this.getSelectedTargets();
var firstTarget = oldTargets.shift();
var newTarget = funcName + '(' + args + ')';
// Insert new target where the first selected was
replaceTarget(firstTarget,newTarget);
Ext.each(oldTargets,
function (target) {
removeTarget(target);
}
);
Composer.syncTargetList();
Composer.updateImage();
this.targetList.select( TargetStore.findExact('value', newTarget), true);
}
applyFunc = applyFunc.createDelegate(this);
return applyFunc;
},
removeOuterCall: function () {
/* It turns out that this is a big pain in the ass to do properly.
* The following code is *almost* correct. It will fail if there is
* an argument with a quoted parenthesis in it. Who cares... */
var _this = this;
Ext.each(this.getSelectedTargets(),
function (target) {
var args = [];
var i, c;
var lastArg = 0;
var depth = 0;
var argString = target.replace(/^[^(]+\((.+)\)/, "$1"); //First we strip it down to just args
for (i = 0; i < argString.length; i++) {
switch (argString.charAt(i)) {
case '(': depth += 1; break;
case '{': depth += 1; break;
case ')': depth -= 1; break;
case '}': depth -= 1; break;
case ',':
if (depth > 0) { continue; }
if (depth < 0) { Ext.Msg.alert("Malformed target, cannot remove outer call."); return; }
args.push( argString.substring(lastArg, i).replace(/^\s+/, '').replace(/\s+$/, '') );
lastArg = i + 1;
break;
}
}
args.push( argString.substring(lastArg, i) );
var firstIndex = indexOfTarget(target);
removeTarget(target);
args.reverse()
Ext.each(args, function (arg) {
if (!arg.match(/^([0123456789\.]+|".+"|'.*')$/)) { //Skip string and number literals
insertTarget(firstIndex, arg);
_this.targetList.select( TargetStore.findExact('value', arg), true);
}
});
Composer.syncTargetList();
Composer.updateImage();
}
);
},
addTarget: function (target) {
var metricCompleter;
var win;
metricCompleter = new MetricCompleter({
listeners: {
specialkey: function (field, e) {
if (e.getKey() == e.ENTER) {
var target = metricCompleter.getValue();
addTarget(target);
Composer.syncTargetList();
Composer.updateImage();
win.close();
e.stopEvent();
return false;
}
},
afterrender: function (field) {
metricCompleter.focus('', 500);
}
}
});
win = new Ext.Window({
title: "Add a new Graph Target",
id: 'addTargetWindow',
modal: true,
width: 400,
height: 115,
layout: {
type: 'vbox',
align:'stretch',
pack: 'center'
},
items: [
{xtype: 'label', text: "Type the path of your new Graph Target."},
metricCompleter
],
buttonAlign: 'center',
buttons: [
{
xtype: 'button',
text: 'OK',
handler: function () {
var target = metricCompleter.getValue();
addTarget(target);
Composer.syncTargetList();
Composer.updateImage();
win.close();
}
}, {
xtype: 'button',
text: 'Cancel',
handler: function () {
Ext.getCmp('addTargetWindow').close();
}
}
]
});
win.show();
},
removeTarget: function (item, e) {
Ext.each(this.getSelectedTargets(), function (target) {
removeTarget(target);
});
Composer.syncTargetList();
Composer.updateImage();
},
editTarget: function (item, e) {
var selected = this.targetList.getSelectedRecords();
if (selected.length != 1) {
Ext.MessageBox.show({
title: "Error",
msg: "You must select exactly one target to edit.",
icon: Ext.MessageBox.ERROR,
buttons: Ext.MessageBox.OK
});
return;
}
var record = selected[0];
var metricCompleter;
var win;
metricCompleter = new MetricCompleter({
value: record.get('value'),
listeners: {
specialkey: function (field, e) {
if (e.getKey() == e.ENTER) {
var target = metricCompleter.getValue();
record.set('value', target);
record.commit();
Composer.syncTargetList();
Composer.updateImage();
win.close();
e.stopEvent();
return false;
}
},
afterrender: function (field) {
metricCompleter.focus('', 500);
}
}
});
function editHandler () {
var newValue = metricCompleter.getValue();
if (newValue != '') {
record.set('value', newValue);
record.commit();
Composer.syncTargetList();
Composer.updateImage();
}
win.close();
}
editHandler = editHandler.createDelegate(this); //dynamic scoping can really be a bitch
win = new Ext.Window({
title: "Edit Graph Target",
id: 'editTargetWindow',
modal: true,
width: 400,
height: 115,
layout: {
type: 'vbox',
align:'stretch',
pack: 'center'
},
items: [
{xtype: 'label', text: "Edit the path of your Graph Target."},
metricCompleter
],
buttonAlign: 'center',
buttons: [
{
xtype: 'button',
text: 'OK',
handler: editHandler
}, {
xtype: 'button',
text: 'Cancel',
handler: function () {
win.close();
}
}
]
});
win.show();
},
addWlSelected: function (item, e) {
Ext.Ajax.request({
url: "/whitelist/add",
method: "POST",
success: function () { Ext.Msg.alert("Result", "Successfully added metrics to whitelist."); },
failure: function () { Ext.Msg.alert("Result", "Failed to add metrics to whitelist."); },
params: {metrics: this.getSelectedTargets().join("\n") }
});
},
removeWlSelected: function (item, e) {
Ext.Ajax.request({
url: "/whitelist/remove",
method: "POST",
success: function () { Ext.Msg.alert("Result", "Successfully removed metrics from whitelist."); },
failure: function () { Ext.Msg.alert("Result", "Failed to remove metrics from whitelist."); },
params: {metrics: this.getSelectedTargets().join("\n") }
});
},
getSelectedTargets: function () {
var targets = [];
Ext.each(this.targetList.getSelectedRecords(), function (record) {
targets.push( record.get('value') );
});
return targets;
}
};
/* Yet another ghetto api hack */
var applyFuncToAll = GraphDataWindow.applyFuncToAll.createDelegate(GraphDataWindow);
var applyFuncToEach = GraphDataWindow.applyFuncToEach.createDelegate(GraphDataWindow);
var applyFuncToEachWithInput = GraphDataWindow.applyFuncToEachWithInput.createDelegate(GraphDataWindow);
function createFunctionsMenu() {
return [{
text: 'Combine',
menu: [
{text: 'Sum', handler: applyFuncToAll('sumSeries')},
{text: 'Average', handler: applyFuncToAll('averageSeries')},
{text: 'Product', handler: applyFuncToAll('multiplySeries')},
{text: 'Min Values', handler: applyFuncToAll('minSeries')},
{text: 'Max Values', handler: applyFuncToAll('maxSeries')},
{text: 'Group', handler: applyFuncToAll('group')},
{text: 'Range', handler: applyFuncToAll('rangeOfSeries')},
{text: 'Count', handler: applyFuncToEach('countSeries')}
]
}, {
text: 'Transform',
menu: [
{text: 'Scale', handler: applyFuncToEachWithInput('scale', 'Please enter a scale factor')},
{text: 'ScaleToSeconds', handler: applyFuncToEachWithInput('scaleToSeconds', 'Please enter a number of seconds to scale to')},
{text: 'Offset', handler: applyFuncToEachWithInput('offset', 'Please enter the value to offset Y-values by')},
{text: 'Derivative', handler: applyFuncToEach('derivative')},
{text: 'Time-adjusted Derivative', handler: applyFuncToEachWithInput('perSecond', "Please enter a maximum value if this metric is a wrapping counter (or just leave this blank)", {allowBlank: true})},
{text: 'Integral', handler: applyFuncToEach('integral')},
{text: 'Percentile Values', handler: applyFuncToEachWithInput('percentileOfSeries', "Please enter the percentile to use")},
{text: 'Non-negative Derivative', handler: applyFuncToEachWithInput('nonNegativeDerivative', "Please enter a maximum value if this metric is a wrapping counter (or just leave this blank)", {allowBlank: true})},
{text: 'Log', handler: applyFuncToEachWithInput('log', 'Please enter a base')},
{text: 'Absolute Value', handler: applyFuncToEach('absolute')},
{text: 'timeShift', handler: applyFuncToEachWithInput('timeShift', 'Shift this metric ___ back in time (examples: 10min, 7d, 2w)', {quote: true})},
{text: 'Summarize', handler: applyFuncToEachWithInput('summarize', 'Please enter a summary interval (examples: 10min, 1h, 7d)', {quote: true})},
{text: 'Hit Count', handler: applyFuncToEachWithInput('hitcount', 'Please enter a summary interval (examples: 10min, 1h, 7d)', {quote: true})}
]
}, {
text: 'Calculate',
menu: [
{text: 'Moving Average', handler: applyFuncToEachWithInput('movingAverage', 'Moving average for the last ___ data points')},
{text: 'Moving Median', handler: applyFuncToEachWithInput('movingMedian', 'Moving median for the last ___ data points')},
{text: 'Moving Standard Deviation', handler: applyFuncToEachWithInput('stdev', 'Moving standard deviation for the last ___ data points')},
{text: 'Holt-Winters Forecast', handler: applyFuncToEach('holtWintersForecast')},
{text: 'Holt-Winters Confidence Bands', handler: applyFuncToEach('holtWintersConfidenceBands')},
{text: 'Holt-Winters Aberration', handler: applyFuncToEach('holtWintersAberration')},
{text: 'As Percent', handler: applyFuncToEachWithInput('asPercent', 'Please enter the value that corresponds to 100% or leave blank to use the total', {allowBlank: true})},
{text: 'Difference (of 2 series)', handler: applyFuncToAll('diffSeries')},
{text: 'Ratio (of 2 series)', handler: applyFuncToAll('divideSeries')}
]
}, {
text: 'Filter',
menu: [
{
text: 'Data Filters',
menu: [
{text: 'Remove Above Value', handler: applyFuncToEachWithInput('removeAboveValue', 'Set any values above ___ to None')},
{text: 'Remove Above Percentile', handler: applyFuncToEachWithInput('removeAbovePercentile', 'Set any values above the ___th percentile to None')},
{text: 'Remove Below Value', handler: applyFuncToEachWithInput('removeBelowValue', 'Set any values below ___ to None')},
{text: 'Remove Below Percentile', handler: applyFuncToEachWithInput('removeBelowPercentile', 'Set any values below the ___th percentile to None')}
]
},
{text: 'Most Deviant', handler: applyFuncToEachWithInput('mostDeviant', 'Draw the ___ metrics with the highest standard deviation')},
{text: 'Highest Current Value', handler: applyFuncToEachWithInput('highestCurrent', 'Draw the ___ metrics with the highest current value')},
{text: 'Lowest Current Value', handler: applyFuncToEachWithInput('lowestCurrent', 'Draw the ___ metrics with the lowest current value')},
{text: 'Highest Maximum Value', handler: applyFuncToEachWithInput('highestMax', 'Draw the ___ metrics with the highest maximum value')},
{text: 'Nth Percentile Value', handler: applyFuncToEachWithInput('nPercentile', 'Draw the ___th Percentile for each metric.')},
{text: 'Current Value Above', handler: applyFuncToEachWithInput('currentAbove', 'Draw all metrics whose current value is above ___')},
{text: 'Current Value Below', handler: applyFuncToEachWithInput('currentBelow', 'Draw all metrics whose current value is below ___')},
{text: 'Highest Average Value', handler: applyFuncToEachWithInput('highestAverage', 'Draw the ___ metrics with the highest average value')},
{text: 'Lowest Average Value', handler: applyFuncToEachWithInput('lowestAverage', 'Draw the ___ metrics with the lowest average value')},
{text: 'Average Value Above', handler: applyFuncToEachWithInput('averageAbove', 'Draw all metrics whose average value is above ___')},
{text: 'Average Value Below', handler: applyFuncToEachWithInput('averageBelow', 'Draw all metrics whose average value is below ___')},
{text: 'Maximum Value Above', handler: applyFuncToEachWithInput('maximumAbove', 'Draw all metrics whose maximum value is above ___')},
{text: 'Maximum Value Below', handler: applyFuncToEachWithInput('maximumBelow', 'Draw all metrics whose maximum value is below ___')},
{text: 'Minimum Value Above', handler: applyFuncToEachWithInput('minimumAbove', 'Draw all metrics whose minimum value is above ___')},
{text: 'sortByMaxima', handler: applyFuncToEach('sortByMaxima')},
{text: 'sortByMinima', handler: applyFuncToEach('sortByMinima')},
{text: 'limit', handler: applyFuncToEachWithInput('limit', 'Limit to first ___ of a list of metrics')},
{text: 'Exclude', handler: applyFuncToEachWithInput('exclude', 'Exclude metrics that match a regular expression')}
{text: 'Grep', handler: applyFuncToEachWithInput('grep', 'Exclude metrics that don\'t match a regular expression')}
]
}, {
text: 'Special',
menu: [
{text: 'Set Legend Name', handler: applyFuncToEachWithInput('alias', 'Enter a legend label for this graph target', {quote: true})},
{text: 'Set Legend Name By Metric', handler: applyFuncToEach('aliasByMetric')},
{text: 'Set Legend Name By Node', handler: applyFuncToEachWithInput('aliasByNode', 'Enter the 0-indexed node to display')},
{text: 'Add Values to Legend Name',
menu: [
{text: "Cacti Style Legend", handler: applyFuncToEach('cactiStyle')},
{text: "Last Value", handler: applyFuncToEach('legendValue', '"last"')},
{text: "Average Value", handler: applyFuncToEach('legendValue', '"avg"')},
{text: "Total Value", handler: applyFuncToEach('legendValue', '"total"')},
{text: "Min Value", handler: applyFuncToEach('legendValue', '"min"')},
{text: "Max Value", handler: applyFuncToEach('legendValue', '"max"')}
]},
{text: 'Color', handler: applyFuncToEachWithInput('color', 'Set the color for this graph target', {quote: true})},
{text: 'Alpha', handler: applyFuncToEachWithInput('alpha', 'Set the alpha (transparency) for this graph target (between 0.0 and 1.0)')},
{text: 'Consolidate By',
menu: [
{text: "Sum", handler: applyFuncToEach('consolidateBy', '"sum"')},
{text: "Max", handler: applyFuncToEach('consolidateBy', '"max"')},
{text: "Min", handler: applyFuncToEach('consolidateBy', '"min"')}
]},
{text: 'Draw non-zero As Infinite', handler: applyFuncToEach('drawAsInfinite')},
{text: 'Line Width', handler: applyFuncToEachWithInput('lineWidth', 'Please enter a line width for this graph target')},
{text: 'Dashed Line', handler: applyFuncToEach('dashed')},
{text: 'Keep Last Value', handler: applyFuncToEachWithInput('keepLastValue', 'Please enter the maximum number of "None" datapoints to overwrite, or leave empty for no limit. (default: empty)', {allowBlank: true})},
{text: 'Transform Nulls', handler: applyFuncToEachWithInput('transformNull', 'Please enter the value to transform null values to')},
{text: 'Substring', handler: applyFuncToEachWithInput('substr', 'Enter a starting position')},
{text: 'Group', handler: applyFuncToAll('group')},
{text: 'Area Between', handler: applyFuncToEach('areaBetween')},
// {text: 'GroupByNode', handler: applyFuncToEachWithInput('group')}, // requires 2 parameters
// {text: 'Add Threshold Line', handler: applyFuncToEachWithInput('threshold', 'Enter a threshold value')},
{text: 'Draw Stacked', handler: applyFuncToEach('stacked')},
{text: 'Draw in Second Y Axis', handler: applyFuncToEach('secondYAxis')}
]
}