-
Notifications
You must be signed in to change notification settings - Fork 0
/
ruleGUI.html
2230 lines (1962 loc) · 74.3 KB
/
ruleGUI.html
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
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rule Creator</title>
<link rel="stylesheet" type="text/css" href="style/main.css" />
<link rel="stylesheet" type="text/css" href="./Assets/Autocompleter.css" />
<link rel="icon"
type="image/png"
href="favicon.jpg"/>
</head>
<body>
<h1>Rule Creation</h1>
<script src = "./Source/mootools.js"></script>
<script src = "./Source/mootools-more.js"></script>
<p style="color:red; display:block; font-size:100%" id="error"></p>
<button id="memberShow" class="circle" style="width:200px">Make Member Rule</button>
<button id="eachShow" class="circle" style="width:200px">Make Iteration Rule</button>
<div id="specRuleChoices">
<div id="memberSelect" style="display:none;">
<p> Apply rules to every member of</p>
<ul id="curMembers" class="compList" style="width:15%"></ul>
</div>
<div id="eachSelect" style="display:none;">
<p> Apply rules to identifier groups</p>
<ul id="curEach" class="compList" style="width:15%"></ul>
</div>
</div>
<div style="float:left">
<span id="autoDraggable" class="draggable"></span>
<br/>
<input id="autoComplete"></input>
</div>
<ul id="curRule" class="compList" style="width:80%;"></ul>
<button class="circle" id="finishRule" onclick="publishRule();">Finish Rule</button>
<br/><br/>
<div id="std" style="float:left; display:inline; width:55%">
<div id="options" style="display:inline">
<button id="itemShow" class="circle">Item</button>
<button id="fieldShow" class="circle">Field</button>
<button id="yearShow" class="circle">Year</button>
<button id="setShow" class="circle">Set Operations</button>
<button id="opShow" class="circle">Operator</button>
<button id="compShow" class="circle">Comparator</button>
<button id="valueShow" class="circle">Value</button>
</div>
<br/>
<div id="choices">
<div id="itemSelect" style="display:none;">
<div id="dropdowns" class="dropdowns" style="display:inline-block;"></div>
<br/>
<div style="display:inline-block; position:static;">
<div id="itemBox" style="float:left;width:23%;margin:20px"></div>
<div id="newItem" style="float:left;margin:20px">
<strong style="width:100%">Create New Item</strong><br/>
Name: <input class="rounded" id="newItemName" size="8"></input><br/>
<ul id="itemVar" class="compList" style="width:75%"></ul>
<button class="circle" id="createNewItem" onclick="createVariable('item')">Create</button><br/>
<button class="circle" id="deleteValue" onclick="deleteVariable('item')">Delete</button>
</div>
<div id="itemConst" style="float:left;margin:20px">
</div>
</div>
</div>
<div id="fieldSelect" style="display:none;">
<div id="fieldBox" style="float:left;width:13%;margin:20px"></div>
</div>
<div id="yearSelect" style="display:none;">
<div style="float:left;margin:20px">
<input class="rounded" id="yearsAgoValue" size="3"></input> Years Ago <br/>
<span id="yearsAgo" class="draggable year">x Years Ago</span>
</div>
<div style="float:left;margin:20px">
Year <input class="rounded" id="yearConstValue" size="4"></input><br/>
<span id="yearConst" class="draggable year">Year x</span>
</div>
<div style="float:left;margin:20px">
<br/><br/>
<span id="lastYear" class="draggable year">Last Year</span>
</div>
</div>
<div id="setSelect" style="display:none;">
<span id="sumSet" class="draggable set" >Sum</span> <span id="meanSet" class="draggable set">Mean</span> <br/>
<span id="medianSet" class="draggable set">Median</span> <span id="stdDevSet" class="draggable set">Standard Deviation</span> <br/>
<span id="minSet" class="draggable set">Minimum</span> <span id="maxSet" class="draggable set">Maximum</span> <br/>
</div>
<div id="opSelect" style="display:none;">
<span id="addOp" class="draggable operator" >+</span> <span id="subOp" class="draggable operator">-</span> <br/>
<span id="multOp" class="draggable operator">X</span> <span id="divOp" class="draggable operator">÷</span> <br/>
</div>
<div id="compSelect" style="display:none;">
<span id="ltComp" class="draggable comparator"><</span> <span id="gtComp" class="draggable comparator">></span> <br/>
<span id="eqComp" class="draggable comparator">=</span> <span id="assignComp" class="draggable comparator">assign</span> <br/>
</div>
<div id="valueSelect" style="display:none;">
<div id="valueBox" style="float:left;width:15%;margin:20px"></div>
<div id="newValue" style="float:left;margin:20px">
<strong style="width:100%">Create New Variable</strong><br/>
Name: <input class="rounded" id="newValueName" size="8"></input><br/>
Value: <input class="rounded" id="newValueAmt" size="8"></input><br/>
<button class="circle" id="createNewValue" onclick="createVariable('value')">Create</button><br/>
<button class="circle" id="deleteValue" onclick="deleteVariable('value')">Delete</button>
</div>
<div id="constant" style="float:left;margin:20px">
<strong style="width:100%">Specify Constant</strong><br/>
<input class="rounded" id="constValue" size="14"></input><br/>
<span class="draggable value" id="selectConst"></span>
</div>
</div>
</div>
</div>
<div id="cond" style="float:left; display:inline; width:45%">
<button id="condShow" style="display:inline;" class="circle">Conditions</button>
<div id="condSelect" style="display:none;">
<div id="condBox" style="float:left;width:25%;margin:20px"></div>
<div id="condCreation" style = "width:65%;float:right;">
<!-- this eval is a little specific, worth taking note of -->
<button class="circle" id="clearCond" onclick="clearCompList(curCond)">Clear Current Condition</button>
<ul id="curCond" class="compList"></ul>
<br/>
<div id = "condCreation" style="float:left; width:35%">
<strong style="width:100%">Create New Condition</strong><br/>
Name: <input class="rounded" id="newConditionName" size="8"></input><br/>
<button class="circle" id="createNewCond" onclick="createVariable('condition')">Create</button><br/>
<button class="circle" id="deleteCond" onclick="deleteVariable('condition')">Delete</button>
</div>
<div style="float:right; width:40%">
<span class="draggable condition" id="selectCond">Condition</span>
</div>
</div>
</div>
</div>
<script src = "varselect.js"></script>
<script src = "data.js"></script>
<script type="text/javascript" src="./Source/Observer.js"></script>
<script type="text/javascript" src="./Source/Autocompleter.js"></script>
<script type="text/javascript" src="./Source/Autocompleter.Local.js"></script>
<script type="text/javascript" onclick="">
var tokens = [];
var uniqueFields = ["amount"];
//Initialization Code;
//Defines a time (in milliseconds) that constitutes a click.
CLICKTIME = 100;
//Defines the timeout for error messages
ERRORTIME = 10000;
errorTimeout = null;
errorArea = $$($('error'));
/*Attach specs to draggables. These specify what the various
draggable components represent for the purpose of code
generation. Also attaches type, which specifies the type
of component that it is.
*/
addOp = $('addOp');
addOp.store('spec','+');
addOp.store('type','operator');
subOp = $('subOp');
subOp.store('spec','-');
subOp.store('type','operator');
multOp = $('multOp');
multOp.store('spec','*');
multOp.store('type','operator');
divOp = $('divOp');
divOp.store('spec','/');
divOp.store('type','operator');
ltComp = $('ltComp')
ltComp.store('spec','<');
ltComp.store('type','comparator');
gtComp = $('gtComp');
gtComp.store('spec','>');
gtComp.store('type','comparator');
eqComp = $('eqComp');
eqComp.store('spec','==');
eqComp.store('type','comparator');
assignComp = $('assignComp')
assignComp.store('spec','=');
assignComp.store('type','comparator');
sumSet = $('sumSet');
sumSet.store('spec','sum');
sumSet.store('type','set');
meanSet = $('meanSet');
meanSet.store('spec','mean');
meanSet.store('type','set');
medianSet = $('medianSet');
medianSet.store('spec','median');
medianSet.store('type','set');
stdDevSet = $('stdDevSet');
stdDevSet.store('spec','standard_deviation');
stdDevSet.store('type','set');
minSet = $('minSet');
minSet.store('spec','minimum');
minSet.store('type','set');
maxSet = $('maxSet');
maxSet.store('spec','maximum');
maxSet.store('type','set');
$('selectCond').store('type', 'condition');
lastYearDrag = $('lastYear')
lastYearDrag.store('type', 'year');
lastYearDrag.store('spec', '(current_year-1)');
selConst = $('selectConst');
selConst.store('type', 'value');
constVal = $('constValue');
//When values are entered in the constant input box, the draggable
//representation reflect those changes.
constVal.onkeyup = function(){
selConst.set('text', constVal.value);
selConst.store('spec', constVal.value)
};
yearsAgoValue = $('yearsAgoValue');
yearConstValue = $('yearConstValue');
yearsAgo = $('yearsAgo');
yearConst = $('yearConst')
yearsAgo.store('spec', undefined);
yearConst.store('spec', undefined);
/* This function sets the values for the years ago draggable.
It reads the value of the corresponding years ago text field,
and if it's a positive integer sets the draggable spec accordingly.
If the spec is invalid, the element is not draggable */
yearsAgoValue.onkeyup = function() {
var val = toNum(yearsAgoValue.value.trim());
if (isNaN(val) || val < 1 || !isInt(val)) {
yearsAgo.store('spec', undefined);
yearsAgo.set('text', 'x Years Ago');
return;
}
yearsAgo.store('spec', 'current_year - ' + val);
if (val === 1)
yearsAgo.set('text', val + ' Year Ago');
else
yearsAgo.set('text', val + ' Years Ago');
}
/* Similar to the relative year specification, except for
absolute years */
yearConstValue.onkeyup = function() {
var val = toNum(yearConstValue.value.trim());
if (isNaN(val) || val < 1 || !isInt(val)) {
yearConst.store('spec', undefined);
yearConst.set('text', 'Year x');
return;
}
yearConst.store('spec', val);
yearConst.set('text', 'Year ' + val);
}
//Sets onclicks for the options buttons such that they show their respective selector views.
$('itemShow').onclick=function(){showChoices('itemSelect')};
$('fieldShow').onclick=function(){showChoices('fieldSelect')};
$('yearShow').onclick=function(){showChoices('yearSelect')};
$('setShow').onclick=function(){showChoices('setSelect')};
$('opShow').onclick=function(){showChoices('opSelect')};
$('compShow').onclick=function(){showChoices('compSelect')};
$('valueShow').onclick=function(){showChoices('valueSelect')};
//Sets onclick for the condition button so that it shows the condition sandbox
var condSelect = $('condSelect');
$('condShow').onclick=function() {
if (condSelect.style.display == 'none')
condSelect.style.display = '';
else
condSelect.style.display = 'none';
};
//TODO: combine these onclicks
//Sets onclick for the member button so that it shows member options
var curMembers = $('curMembers');
var memberSelect = $('memberSelect');
$('memberShow').onclick=function() {
if (memberSelect.style.display == 'none') {
memberSelect.style.display = '';
eachSelect.style.display = 'none';
clearFor('each');
} else {
memberSelect.style.display = 'none';
clearFor('members')
}
};
//Sets onclick for the member button so that it shows member options
var curEach = $('curEach');
var eachSelect = $('eachSelect');
$('eachShow').onclick=function() {
if (eachSelect.style.display == 'none') {
eachSelect.style.display = '';
memberSelect.style.display = 'none';
clearFor('members')
} else {
memberSelect.style.display = 'none';
clearFor('each');
}
};
//Initializes a searchable select box for variables, saved conditions, saved items, and fields
valueSel = new VarSelect($('valueBox'));
valueSel.title.set('html', 'Variables');
conditionSel = new VarSelect($('condBox'));
conditionSel.title.set('html', 'Conditions');
itemSel = new VarSelect($('itemBox'));
itemSel.title.set('html', 'Items');
fieldSel = new VarSelect($('fieldBox'));
fieldSel.title.set('html', 'Fields');
//initializes the field selector by adding values.
//TODO: pull these values from the back end
function initFields(fields) {
for (var i = 0; i < fields.length; i++) {
listDraggable(fieldSel.addOption(fields[i]), 'field', 'field');
var token = {value: fields[i], type: 'field', spec: fields[i]};
tokens.push(token);
}
}
initFields(uniqueFields);
date = new Date();
curView = '';
/* A dictionary which defines all variables for a session.
TODO: We probably want a way to make these persistence
across sessions. Also deletion. */
var variables = {};
/* Returns the number form of a passed in string, removing commas
(and possibly doing other special handling). Returns NaN if string
cannot be represented as a number */
function toNum(numStr){
numStr = numStr.replace(/,/g, '');
return numStr.toFloat()
}
/*Function called when clicking one of the specifier buttons. It
makes the specific panel for that specifier visible (based on
the argument passed in), clears the current rule component
if clear is true, and also does some special handling for
the various cases.
*/
function showChoices(toShow, div){
if (!div)
div = 'choices';
switch(toShow) {
case 'comparator': toShow = 'compSelect'; break;
case 'value': toShow = 'valueSelect'; break;
case 'operator': toShow = 'opSelect'; break;
case 'item': toShow = 'itemSelect'; break;
}
//if we're already in a given view, do nothing
if (toShow == curView)
return;
curView = toShow;
//Hide all the divs
$(div).getChildren('div').each(function(childDiv) {
childDiv.setStyle('display','none');
});
$(toShow).style.display = '';
}
/* Encapsulates the components of a condition into an array of identifiers,
allowing the condition components to be reconstructed and allowing for
JSON translation */
function capCondition() {
if (validSemantics(curCond)) {
var children = curCond.getChildren();
var spec = new Array();
children.each(function(component) {
spec.push({type:component.retrieve('type'), spec: component.retrieve('spec'), html: component.innerHTML});
});
return spec;
}
return null;
}
/* Displays the error given in msg above the rule.
Error messages dissapear after a certain amount of time */
function displayError(msg) {
if (errorTimeout)
window.clearTimeout(errorTimeout);
errorArea.set('html', msg);
errorTimeout = setTimeout(function() {
errorArea.set('html', '');
}, ERRORTIME);
}
/*Locks in and displays a value for the current rule, represented either
symbolically or numerically. Takes the value to display, and checks its
validity.
*/
function validValue(value) {
if (!(value in variables)) {
value = toNum(value);
if (isNaN(value)) {
displayError('Values must either correspond to a created variable or be numerical');
return false;
}
}
return true;
};
nouns = new Array('value', 'item', 'field');
verbs = new Array('operator', 'comparator', 'nothing');
ordering = {operator: nouns, value: verbs, item: verbs, field:verbs, comparator: nouns};
/*Determines if the current rule following some basic semantics. As of now, operators and comparators
can only follow nouns, nouns cannot follow eachother, and fields must have at least one item coming
before (they are assumed to use that items specifiers if not attached to a particular item).
There must be exactly one comparator in a rule. (right now, rules that are 'both
less than x and greater than y' are not supported, but could easily be added). There must be at least
one budget item. Rules must end in a noun. Assignments are only valid after a single item.
This function also handles condition, although conditions have some slight differences. Items in
conditions are replaced with fields, and some rules, such as fields having to follow an item, do
not apply. */
function validSemantics(compList) {
var cond = (compList === curCond);
var components = compList.getChildren();
var prevType = 'nothing';
var cmpCount = 0;
var itemCount = 0;
var afterComparator = false;
var afterCount = 0;
for (var i = 0; i < components.length; i++) {
if (afterComparator)
afterCount++;
var component = components[i];
var type = component.retrieve('type');
//Variables need to be translated to their actual types.
if (type == 'variable')
type = variables[component.retrieve('spec')].type;
/* Special handling for a few cases. Right now just increments counters */
switch(type) {
case 'comparator':
if (component.retrieve('spec') === '=') {
if (cond) {
displayError('Assignments not allowed in conditions');
return false;
}
if (!curRule.hasClass('members')) {
displayError('Assignments are only allowed in member rules');
return false;
}
if (itemCount !== 1 && i != 2) {
displayError('Assignments must follow immediately follow single item');
return false;
}
}
afterComparator = true;
cmpCount++;
break;
case 'item':
itemCount++;
break;
case 'field':
itemCount++;
/*
else if (itemCount === 0) {
displayError('Error at Component' + i + ': Stand-alone fields may only be used in a rule following an item, and are assumed to take that items specifiers');
return false;
}*/
}
//The rest of the code in the function just prints various error messages
if (!ordering[type].contains(prevType)) {
errMsg = 'Error at Component ' + i + ': ' + type +'s may only follow components of the type ' + ordering[type].join(', ') + '. Currently the component follows ' + prevType + '.';
displayError(errMsg);
return false;
}
prevType = type;
}
if (cmpCount != 1) {
if (cond)
errMsg = 'There must be exactly one comparator in the condition. Currently there are ' + cmpCount + '.';
else
errMsg = 'There must be exactly one comparator or assignment in the rule. Currently there are ' + cmpCount + '.';
displayError(errMsg);
return false;
}
if (itemCount < 1) {
if (cond)
errMsg = 'There must be at least one field in the condition.';
else
errMsg = 'There must be at least one budget item in the rule.';
displayError(errMsg);
return false;
}
if (!nouns.contains(type)) {
if (cond)
errMsg = 'Conditions cannot end in operators or comparators';
else
errMsg = 'Rules cannot end in operators, comparators or assignments';
displayError(errMsg);
return false;
}
return true;
}
/* Adds a mouseover animation to elements */
//WARNING: bit hacky on mouseleave
function addHover(element) {
element.addEvents({
'mouseenter': function(event){
event.stop();
element.addClass('hovered');
element.getParent().removeClass('hovered');
},
'mouseleave': function(event){
event.stop();
//TODO: fix parent not rehighlight
element.removeClass('hovered');
}
});
}
//WARNING: The name is a bit of a misnomer as it does not clone all storage
/* Clones draggable objects while retaining the stored specifications, so
that they may be read in again when forming the JS/JSON. Also reattaches
hover events. */
function cloneWithStorage(element) {
var clone = element.clone();
clone.store('spec', element.retrieve('spec'));
clone.store('type', element.retrieve('type'));
addHover(clone);
return clone;
}
/* Measures if a component element is outside of its container, and returns
true if it is (to mark it for deletion). Also deletes its draggable clone
*/
function destroyOutside(element, container) {
var position = element.getPosition(container);
var containerDims = container.getSize();
var compDims = container.getSize();
if (position.y < -30-compDims.y || position.y > (containerDims.y + 30) || position.x < -30-compDims.x || position.x > (containerDims.x + 30)) {
/* This destroys the clone, not the actual element. We need to handle element
deletion at the oncomplete */
element.destroy();
return true;
}
return false;
}
/* Makes a list of components (right now either the rule or a condition) a mootools
Sortable so that the components in them can be dragged around and ordered.
Also defines: A click behavior that edits variable a drag away to destroy behavior */
function makeSortable(list) {
var destroyIt;
var clickStart;
list.sortable = new Sortables(list, {
revert: true,
clone: true,
opacity: 0.7,
dragOptions: {
/* We want to be able to distinguish between a click and a drag, so we
measure the time here and at the complete, and if it was sufficiently
short we treat it as a click */
onBeforeStart: function(element) {
clickStart = date.getTime();
},
/* When an component in the sortable is dropped sufficiently far away from the container,
we want to destroy it. */
onDrop: function(element) {
destroyIt = destroyOutside(element, list);
}
},
onComplete: function(element) {
/* Destroys an element if it was marked for deletion. */
if (destroyIt) {
list.sortable.removeItems(element);
element.destroy();
destroyIt = false;
}
//If our click was less than clicktime, then we register a click, and see if we can edit the component
else if(date.getTime() - clickStart < CLICKTIME) {
if (element.retrieve('type') == 'variable')
editVariable(element.retrieve('spec'));
//TODO: We need to decide if we want changes in the sandbox to be persistent
if (element.retrieve('type') == 'item')
editItem(element.retrieve('spec'));
}
},
});
}
//We apply sortability and resizability to the sandboxes.
var curRule = $('curRule');
var curCond = $('curCond');
makeSortable(curRule);
makeSortable(curCond);
/*
curRule.makeResizable({
modifiers:{x: 'width', y:false}
});
curCond.makeResizable({
modifiers:{x: 'width', y:false}
});*/
newConditionNameBox = $('newConditionName');
/* Clears a sandbox */
function clearCompList(compList) {
$$(compList).getChildren().each(function(element){element.destroy()});
}
//TODO: type and class are like the same
/* Given an array of objects with the fields type, html, spec, and ch, regenerates
the draggable components and returns them in an array */
function regenerateItems(specList) {
var components = new Array();
for (var i = 0; i < specList.length; i++) {
var compSpec = specList[i];
var text = compSpec.html;
var comp = new Element('span', {class:'draggable', html:text});
var type = compSpec.type;
var dragClass = type;
if (type === 'variable') {
comp.onclick = function() {editVariable(text)};
dragClass = variables[text].type
}
comp.store('spec', compSpec.spec)
comp.store('type', type)
comp.addClass(dragClass);
if ('ch' in compSpec) {
var modifiers = regenerateItems(compSpec.ch);
modifiers.each(function(mod) {
mod.inject(comp);
});
}
addHover(comp);
components.push(comp);
}
return components;
}
/* Opens a condition for editting. Takes a condition spec and composes it in
the condition sandbox, and makes the sandbox viewable if it isn't
already*/
function editCondition(condSpec) {
clearCompList(curCond);
var components = regenerateItems(condSpec);
components.each(function (comp) {
curCond.adopt(comp);
curCond.sortable.addItems(comp);
});
condSelect.style.display = '';
}
newValueNameBox = $('newValueName');
newValueAmtBox = $('newValueAmt');
newItemNameBox = $('newItemName');
//TODO: variables named <script> don't work
function makeSafe(text) {
return text.replace(/\W/g, function (chr) {
return '&#' + chr.charCodeAt(0) + ';';
});
};
itemVar = $('itemVar');
/*Creates a variable for rule use. Rejects empty variable names
and non-number values. Assigning a variable twice overwrites
the previous value.
//TODO: integrate with back-end
*/
function createVariable(type) {
var variableName = makeSafe(window['new' + type.capitalize() + 'NameBox'].value.trim());
if (variableName in variables && variables[variableName].type !== type) {
displayError('Name in use as ' + variables[variableName].type);
return;
}
if (variableName == '') {
displayError('Variable name must not be empty');
return;
}
var spec;
switch(type) {
case 'value':
spec = toNum(newValueAmtBox.value);
if (isNaN(spec)) {
displayError('Variable must have a valid numeric amount');
return;
}
newValueAmtBox.value = '';
break;
case 'item':
var item = itemVar.getChildren()[0];
if (item)
spec = item.retrieve('spec');
else {
displayError('An item must be specified in order to save a variable');
return;
}
break;
case 'condition':
spec = capCondition();
if (spec == null)
return;
break;
}
if (!(variableName in variables)) {
//create the variable and make it's representative option draggable
listDraggable(window[type + 'Sel'].addOption(variableName), type);
}
variables[variableName] = {type: type,
spec: spec,
html: variableName};
window['new' + type.capitalize() + 'NameBox'].value = '';
}
/* Creates conditions upon pressing enter while the condition name box is in focus*/
newConditionNameBox.addEvent('keydown', function(event){
if (event.key == 'enter')
createVariable('condition');
});
/* Deletes a variable with the name typed in the variable box. Does not cross variable type.
TODO: Potentially will not allow deletion of variables currently in use.
*/
function deleteVariable(type) {
var variableName = window['new' + type.capitalize() + 'NameBox'].value.trim();
if (!variableName in variables) {
displayError('Variable does not exist');
} else if (!variables[variableName].type == 'value') {
displayError('Name in use as ' + variables[variableName].type + ', cannot delete as ' + type + '.');
return;
} else {
window[type + 'Sel'].removeOption(variableName);
delete variables[variableName];
}
}
/* Adds on enter-key behavior the the variable name and
value boxes such that it creates a variable */
newValueNameBox.addEvent('keydown', function(event){
if (event.key == 'enter')
createVariable('value');
});
newValueAmtBox.addEvent('keydown', function(event){
if (event.key == 'enter') {
createVariable('value');
newValueNameBox.focus();
}
});
/*This function serves as the onlick for the variable selector,
and causes the selected variable to be displayed in the variable
creation fields, either for editting or simply viewing */
function editVariable(variableName) {
if (!variableName)
return;
var variable = variables[variableName];
if (!variable)
return;
var type = variable.type;
if (type == 'condition') {
newConditionNameBox.value = variableName;
editCondition(variable.spec);
condSelect.style.display = '';
} else if (type == 'item') {
editItem(variable.spec);
newItemNameBox.value = variableName;
showChoices('itemSelect');
} else if (type == 'value') {
//This is kind of poor form, as it relies on value being
//undefined to filter out bad clicks
newValueNameBox.value = variableName;
newValueAmtBox.value = variable.spec;
showChoices('valueSelect');
}
}
function switchVar(comp, type) {
var cur = window[type + 'Var'];
clearCompList(cur);
var cl = cloneWithStorage(comp);
cl.inject(cur);
addModDrag(cur, cl);
}
function clearFor(type) {
clearCompList(window['cur' + type.capitalize()]);
curRule.removeClass(type);
//We want to destroy every draggable item with a this specifier, as they won't probably apply anymore
var thisItems = document.getElements('.this');
if (thisItems)
thisItems.destroy();
}
/* Switches the current active member for member rules with the one specified in the argument */
function switchSpecial(comp, type) {
clearFor(type);
//Add member class to curRule
curRule.addClass(type);
var cur = window['cur' + type.capitalize()];
//Add visual
var cl = cloneWithStorage(comp);
cl.inject(cur);
cl.removeClass('item');
cl.addClass(type)
addModDrag(cur, cl);
var spec = comp.retrieve('spec');
var dataSet = getFirstKey(spec);
spec = spec[dataSet];
//TODO: This code isn't really readable
var injectToDropDown = function(specArray, key, leaf) {
var id = '';
specArray.each(function(ident) {
id += ident;
});
var injectThisIdent = function(item) {
var dset = getFirstKey(item.retrieve('spec'));
var spec = {};
var spoint = (spec[dset] = {});
for (var i = 0; i < specArray.length; i++) {
spoint = (spoint[specArray[i]] = {});
}
//TODO: each. Again, current handling could be much cleaner
spoint[key] = {};
var li = createDropDownItem(spec, 'val' + dset + id + key, key, leaf);
var parentMenu = item.getChildren('ul.dropMenu')[0];
if (!parentMenu) {
var ul = Element('ul', { 'class': 'dropMenu' });
ul.inject(item);
parentMenu = ul;
}
li.inject(parentMenu, 'top');
li.setStyle('display', 'block');
}
for (dataset in categories) {
if (!hasOwnProperty.call(categories, dataset))
continue;
var parentItem = $('val' + dataset + id);
if (parentItem)
injectThisIdent(parentItem);
}
}
//TOOO: department, fund, etc shouldn't be draggable
if (type === 'each') {
var eachRecurseCheck = function(value, key, specArray, identHier, identIndex) {
if (key.substring(0,7) === '-EACH- ') {
while (true) {
var leaf = isEmpty(value)
var thiskey = '-THIS- ' + identHier[identIndex];
injectToDropDown(specArray, thiskey, leaf);
specArray.push(thiskey);
identIndex++;
if (leaf)
break;
value = value[getFirstKey(value)];
}
} else {
var newSpecArray = specArray.clone();
newSpecArray.push(key);
Object.each(value, function(value, key) {
eachRecurseCheck(value, key, newSpecArray, identHier, identIndex + 1)
});
}
}
Object.each(spec, function(value, identifier) {
eachRecurseCheck(value, identifier, new Array(), identHierarchy[identifier], -1);
});
}
/*We want to add a this specifier to the highest unspecified level*/
if (type === 'members') {
var membersRecurseCheck = function(value, key, specArray, identHier, identIndex) {
if (isEmpty(value) && specArray.length !== 1) {
for (var i = identIndex; i < identHier.length; i++) {
var leaf = (i === (identHier.length-1))
var thiskey = '-THIS- ' + identHier[i];
injectToDropDown(specArray, thiskey, leaf);
specArray.push(thiskey);
}
} else {
Object.each(value, function(value, key) {
var newSpecArray = specArray.clone();
newSpecArray.push(key);
membersRecurseCheck(value, key, newSpecArray, identHier, identIndex + 1)
});
}
}
Object.each(spec, function(value, identifier) {
var identHier = identHierarchy[identifier];
tempSpecArray = new Array(identifier);
for (var i = 0; i < identHier.length; i++) {
var leaf = (i === (identHier.length-1))
var thiskey = '-THIS- ' + identHier[i];
injectToDropDown(tempSpecArray, thiskey, leaf);
tempSpecArray.push(thiskey);
}
membersRecurseCheck(value, identifier, new Array(identifier), identHier, 0);
});
}
}
/* Makes it such that you can grab the options in a variable list and they turn into components
for a rule or condition. Defines a seperate clicking and dragging behavior based on click duration.
Optional argument dragClassOverride allows a css class to be added the element, giving it different behaviors.
Optional argument typeOverride allows the type variable to be overridden in favor of another type
Optional argument specOverride allows the spec of the variable to be overridden.
Optional mouseUp override allows the click functionality to be changed*/
function listDraggable(elem, dragClassOverride, typeOverride, specOverride, mouseUpOverride){
var timeout;
var fired;
var varName;
var dragClass = dragClassOverride ? dragClassOverride : 'value';
var type = typeOverride ? typeOverride : 'variable';
var varName = elem.get('text');
var spec = specOverride ? specOverride : varName;
var mouseUp = mouseUpOverride ? mouseUpOverride : function () {
elem.set('selected', true);
editVariable(varName);
};
elem.addEvent('mousedown', function(event){
event.stop();
fired = false;
timeout = setTimeout(function() {
fired = true;