-
Notifications
You must be signed in to change notification settings - Fork 16
/
formulaic.js
2256 lines (1912 loc) · 92.2 KB
/
formulaic.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
var formulaic = {
newFormulaic : function(params) {
return edges.instantiate(formulaic.Formulaic, params);
},
Formulaic : function(params) {
// Construction Arguments
///////////////////////////////////////////////////////
// jquery selector for the form we're working with
this.formSelector = edges.getParam(params.formSelector, "#formulaic");
// the fieldsets configuration for this form
this.fieldsets = edges.getParam(params.fieldsets, {});
// a mapping from short strings to function paths for the functions used by this form
this.functions = edges.getParam(params.functions, {});
// should we apply front-end validation
this.doValidation = edges.getParam(params.doValidation, true);
// should we autosave? Enter 0 for no, or the number of milliseconds between each save
this.autoSave = edges.getParam(params.autoSave, 0);
this.controlSelect = edges.getParam(params.controlSelect, formulaic.newDefaultControlSelect());
this.controlSelect.set_formuaic(this);
// Internal properties
///////////////////////////////////////////////////////
// jquery handle on the form
this.context = $(this.formSelector);
// list of fields whose values are synchronised
this.synchronised = {};
// an inverted map of conditionals: keys are fields which are conditions of other fields
this.conditionals = {};
// internal variable for holding reference to the parsley validator for the form
this.activeParsley = false;
// hold references to widgets that we have loaded
this.widgetRefs = {};
// hold references to instantiated widgets
this.activeWidgets = {};
// references to exclusive checkboxes
this.exclusive = {};
this.lastSaveVal = "";
/**
* Construct the Formulaic instance
*/
this.init = function() {
// set up the save button
this.bindSave();
// first detect any sychronised fields and register them
this.registerSynchronised();
// bind any conditional fields
this.bindConditional();
// attach any widgets to the form
this.applyWidgets();
// find any checkboxes that
this.bindExclusiveCheckboxes();
// Note that we don't bind parsley validation on init, because we don't want to
// always validate. Instead Parsley is inited later when the user attempts an initial
// submit
};
// Object utility functions
////////////////////////////////////////////////
/*
this._controlSelect = function(params) {
var context = this.context;
if (params.fieldset) {
context = $("#" + params.fieldset, this.context);
}
if (params.name) {
return $("[name=" + params.name + "], [data-formulaic-sync=" + params.name + "]", context).filter(":input");
} else if (params.id) {
return $("#" + params.id, context).filter(":input");
} else if (params.syncName) {
return $("[data-formulaic-sync=" + params.syncName + "]", context).filter(":input");
}
};*/
this.getElementName = function(element) {
var name = element.attr("data-formulaic-sync");
if (!name) {
name = element.attr("name");
}
return name;
};
this.getFieldDefinition = function(params) {
var field = params.field;
for (var i = 0; i < this.fieldsets.length; i++) {
var fieldset = this.fieldsets[i];
for (var j = 0; j < fieldset.fields.length; j++) {
var fieldDef = fieldset.fields[j];
if (fieldDef.name === field) {
return fieldDef;
}
}
}
return false;
};
////////////////////////////////////////////////
//////////////////////////////////////////////
// Functions for handling save
this.bindSave = function() {
edges.on(this.context.find(".formulaic-complete"), "click.Complete", this, "saveComplete", false, false, false);
edges.on(this.context.find(".formulaic-draft"), "click.Draft", this, "saveDraftAndComplete", false, false, false);
if (this.autoSave > 0) {
setTimeout(this.backgroundSaveClosure(), this.autoSave);
}
};
this.backgroundSaveClosure = function() {
var that = this;
return function() {
that.save({validate: false, additional : {"draft" : "true", "async" : "true"}, complete: false});
setTimeout(that.backgroundSaveClosure(), that.autoSave);
};
};
this.saveComplete = function(element, event) {
this.save({event: event});
};
this.saveDraftAndComplete = function(element, event) {
this.save({validate: false, additional : {"draft" : "true", "async" : "true"}, event: event});
};
this.save = function(params) {
if (!params) { params = {};}
var validate = edges.getParam(params.validate, this.doValidation);
var additional_params = edges.getParam(params.additional, {});
var complete = edges.getParam(params.complete, true);
var event = params.event;
if (validate) {
this.bounceParsley();
} else {
this.destroyParsley();
}
if (!validate || (this.activeParsley && this.activeParsley.isValid())) {
if (!complete) {
if (event) {
event.preventDefault();
}
var submit_data = this.context.serialize();
if (submit_data === this.lastSaveVal) {
return;
}
var full_data = $.param(additional_params) + "&" + submit_data;
var that = this;
$.post({
url: this.context.attr("action"),
data: full_data,
error: function() {/*alert("background save failed")*/},
success: function(response_data) {
that.lastSaveVal = submit_data;
var rd = JSON.parse(response_data);
that.setId(rd);
}
});
}
// otherwise, event propagates and form is submitted by the browser
} else {
if (event) {
event.preventDefault();
}
if (this.activeParsley) {
this.activeParsley.validate();
}
}
};
this.setId = function(params) {
var id = params.id;
var existing = this.context.find("[name=id]");
if (existing.length > 0) {
existing.attr("value", id);
} else {
this.context.append('<input type="hidden" name="id" value="' + id + '">');
}
};
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
// Functions for handling synchronised fields
this.registerSynchronised = function() {
var fieldRegister = [];
for (var i = 0; i < this.fieldsets.length; i++) {
var fieldset = this.fieldsets[i];
for (var j = 0; j < fieldset.fields.length; j++) {
var field = fieldset.fields[j];
if ($.inArray(field.name, fieldRegister) === -1) {
fieldRegister.push(field.name);
} else {
if ($.inArray(field.name, Object.keys(this.synchronised)) === -1) {
this.synchronised[field.name] = [fieldset.name];
} else {
this.synchronised[field.name].push(fieldset.name);
}
}
}
}
var fields = Object.keys(this.synchronised);
for (var i = 0; i < fields.length; i++) {
var name = fields[i];
var allByName = this.controlSelect.input({name: name});
allByName.each(function() {
var that = $(this);
var current_id = that.attr("id");
that.attr("data-formulaic-sync", name).attr("data-formulaic-id", current_id);
});
var fieldsets = this.synchronised[name];
for (var j = 0; j < fieldsets.length; j++) {
var fieldset = fieldsets[j];
var elements = this.controlSelect.input({fieldset: fieldset, name: name});
elements.each(function() {
var newname = fieldset + "__" + name;
var newid = fieldset + "__" + $(this).attr("id");
$(this).attr("name", newname).attr("id", newid);
});
}
edges.on(allByName, "change.Synchronise", this, "synchroniseChange");
}
};
this.synchroniseChange = function(element) {
var that = $(element);
var name = that.attr("data-formulaic-sync");
var original_id = that.attr("data-formulaic-id");
var type = that.attr("type");
// TODO: we currently only synchronise radio and checkboxes, so if you need to synchronise
// other fields, this will need extending
if (type === "radio" || type === "checkbox") {
var checked = that.is(":checked");
var toSync = this.controlSelect.input({syncName: name});
toSync.each(function() {
var el = $(this);
if (el.attr("data-formulaic-id") === original_id) {
el.prop("checked", checked);
} else {
el.prop("checked", !checked);
}
});
}
};
///////////////////////////////////////////////////////
// Functions for conditional fields
///////////////////////////////////////////////////////
this.bindConditional = function() {
for (var i = 0; i < this.fieldsets.length; i++) {
var fieldset = this.fieldsets[i];
for (var j = 0; j < fieldset.fields.length; j++) {
var field = fieldset.fields[j];
if (!field.hasOwnProperty("conditional")) {
continue;
}
for (var k = 0; k < field.conditional.length; k++) {
var condition = field.conditional[k];
var condField = condition.field;
// register the conditional relationship
if (this.conditionals.hasOwnProperty(condField)) {
if ($.inArray(field, this.conditionals[condField]) === -1) {
this.conditionals[condField].push(field.name);
}
} else {
this.conditionals[condField] = [field.name];
}
// bind a change event for checking conditionals
var element = this.controlSelect.input({name: condField});
edges.on(element, "change.Conditional", this, "checkConditional");
// then actually check the conditional
this.checkConditional(element);
}
}
}
};
this.checkConditional = function(element) {
var name = this.getElementName($(element));
var downstream = this.conditionals[name];
for (var i = 0; i < downstream.length; i++) {
var field = downstream[i];
if (this.isConditionSatisfied({field: field})) {
this.controlSelect.container({name: field}).show();
} else {
this.removeValues(this.controlSelect.container({name: field}));
this.controlSelect.container({name: field}).hide();
}
}
};
this.removeValues = (container) => {
let inputs = $(container).find("input");
inputs.each((idx, inp) => {
let el = $(inp);
let type = el.attr("type");
if (type === "checkbox" || type === "radio") {
el.prop("checked", false);
} else {
el.val("");
}
});
let selects = $(container).find("select");
selects.each((idx, sel) => {
$(sel).val("").change();
});
};
this.isConditionSatisfied = function(params) {
var field = params.field;
var definition = this.getFieldDefinition(params);
for (var i = 0; i < definition.conditional.length; i++) {
var condField = definition.conditional[i];
var elements = this.controlSelect.input({name: condField.field});
var type = elements.attr("type");
var val = condField.value;
if (type === "radio" || type === "checkbox") {
var checkedValues = [];
elements.each(function() {
var that = $(this);
if (that.is(":checked")) {
checkedValues.push(that.val());
}
});
if ($.inArray(val, checkedValues) !== -1) {
return true;
}
}
}
return false;
};
///////////////////////////////////////////////////////
// Functions for widget handling
///////////////////////////////////////////////////////
this.applyWidgets = function() {
for (var i = 0; i < this.fieldsets.length; i++) {
var fieldset = this.fieldsets[i];
for (var j = 0; j < fieldset.fields.length; j++) {
var fieldDef = fieldset.fields[j];
if (fieldDef.hasOwnProperty("widgets")) {
for (var k = 0; k < fieldDef.widgets.length; k++) {
var widgetDef = fieldDef.widgets[k];
var widgetName = false;
var widgetArgs = {};
if (typeof widgetDef === "string") {
widgetName = widgetDef
} else {
widgetName = Object.keys(widgetDef)[0];
widgetArgs = widgetDef[widgetName];
}
var widget = this.getWidget(widgetName);
if (!widget) {
continue;
}
var active = widget({
fieldDef: fieldDef,
formulaic: this,
args: widgetArgs
});
if (this.activeWidgets.hasOwnProperty(fieldDef.name)) {
this.activeWidgets[fieldDef.name].push(active);
} else {
this.activeWidgets[fieldDef.name] = [active]
}
}
}
}
}
};
this.getWidget = function(widgetName) {
if (this.widgetRefs[widgetName]) {
return this.widgetRefs[widgetName];
}
var functionPath = this.functions[widgetName];
if (!functionPath) {
return false;
}
var bits = functionPath.split(".");
var context = window;
for (var i = 0; i < bits.length; i++) {
var bit = bits[i];
context = context[bit];
if (!context) {
console.log("Unable to load " + widgetName + " from path " + functionPath);
return false;
}
}
return context;
};
//////////////////////////////////////////////////////
// Functions for exclusive checkboxes
//////////////////////////////////////////////////////
this.bindExclusiveCheckboxes = function() {
// first register all the exclusive elements and values
for (var i = 0; i < this.fieldsets.length; i++) {
var fieldset = this.fieldsets[i];
for (var j = 0; j < fieldset.fields.length; j++) {
var field = fieldset.fields[j];
if (field.hasOwnProperty("options")) {
for (var k = 0; k < field.options.length; k++) {
var opt = field.options[k];
if (opt.hasOwnProperty("exclusive") && opt.exclusive) {
if (this.exclusive.hasOwnProperty(field.name)) {
if ($.inArray(opt.value, this.exclusive) === -1) {
this.exclusive[field.name].push(opt.value);
}
} else {
this.exclusive[field.name] = [opt.value];
}
}
}
}
}
}
var exclusiveFields = Object.keys(this.exclusive);
for (var i = 0; i < exclusiveFields.length; i++) {
var name = exclusiveFields[i];
var elements = this.controlSelect.input({name: name});
edges.on(elements, "change.Exclusive", this, "checkExclusive");
for (var j = 0; j < elements.length; j++) {
this.checkExclusive(elements[j]);
}
}
};
this.checkExclusive = function(element) {
var jqel = $(element);
var name = jqel.attr("name");
var value = jqel.val();
if (!this.exclusive.hasOwnProperty(name)) {
return;
}
var values = this.exclusive[name];
if ($.inArray(value, values) === -1) {
return;
}
var checked = jqel.is(":checked");
var elements = this.controlSelect.input({name: name});
var that = this;
elements.each(function() {
if (checked && $(this).val() !== value) {
$(this).prop("checked", false);
$(this).prop('disabled', true);
that.checkConditional(this);
} else {
$(this).prop('disabled', false);
}
});
};
////////////////////////////////////////////////////
// Parsley state management
////////////////////////////////////////////////////
this.destroyParsley = function() {
if (!this.doValidation) { return; }
if (this.activeParsley) {
this.activeParsley.destroy();
this.activeParsley = false;
this.context.off("submit.Parsley");
}
// $(".has-error").removeClass("has-error");
};
this.bounceParsley = function() {
if (!this.doValidation) { return; }
this.destroyParsley();
this.activeParsley = this.context.parsley();
};
////////////////////////////////////////////////////
// call the init function to complete construction
this.init();
},
newDefaultControlSelect : function(params) {
return edges.instantiate(formulaic.DefaultControlSelect, params);
},
DefaultControlSelect : function(params) {
this.containerClassTemplate = edges.getParam(params.containerClassTemplate, "{name}__container");
this.groupSeparator = edges.getParam(params.groupSeparator, "-");
this.formulaic = false;
this.set_formuaic = function(f) {
this.formulaic = f;
};
this.get_context = function(params) {
var context = this.formulaic.context;
if (params.fieldset) {
context = $("#" + params.fieldset, context);
}
return context;
};
this.localiseName = function(params) {
var name = params.name;
var def = this.formulaic.getFieldDefinition({field: name});
if (def.hasOwnProperty("group")) {
var upperChain = this.localiseName({name: def.group});
return upperChain + this.groupSeparator + name;
} else {
return name;
}
};
this.input = function(params) {
var context = this.get_context(params);
if (params.name) {
var name = this.localiseName({name : params.name});
return $("[name=" + name + "], [data-formulaic-sync=" + name + "]", context).filter(":input");
} else if (params.id) {
return $("#" + params.id, context).filter(":input");
} else if (params.syncName) {
} else if (params.syncName) {
return $("[data-formulaic-sync=" + params.syncName + "]", context).filter(":input");
}
};
this.container = function(params) {
var context = this.get_context(params);
var name = params.name || params.syncName;
var selector = "." + this.containerClassTemplate.replace("{name}", name);
return $(selector, context);
};
this.widgetsContainer = function(params) {
var context = this.get_context(params);
return $("#" + params.name + "_widgets-container", context)
}
},
edges : {
newTreeBrowser : function(params) {
return edges.instantiate(formulaic.edges.TreeBrowser, params, edges.newComponent);
},
TreeBrowser : function(params) {
this.tree = edges.getParam(params.tree, {});
this.sourceInput = edges.getParam(params.sourceInput, false);
this.nodeMatch = edges.getParam(params.nodeMatch, false);
this.filterMatch = edges.getParam(params.filterMatch, false);
this.nodeIndex = edges.getParam(params.nodeIndex, false);
this.syncTree = [];
this.parentIndex = {};
this.nodeCount = 0;
this.selected = [];
this.init = function(edge) {
// first kick the request up to the superclass
edges.newSelector().init.call(this, edge);
var text = this.sourceInput.val();
if (text !== "") {
this.selected = text.split(",").map(function(x) {return x.trim()})
} else {
this.selected = [];
}
};
this.synchronise = function() {
this.syncTree = $.extend(true, [], this.tree);
var selected = this.selected;
var that = this;
function recurse(tree, path) {
var anySelected = false;
var childCount = 0;
for (var i = 0; i < tree.length; i++) {
var node = tree[i];
that.nodeCount++;
that.parentIndex[node.value] = $.extend(true, [], path);
if (that.filterMatch(node, selected)) {
node.selected = true;
anySelected = true;
}
if (that.nodeIndex) {
node.index = that.nodeIndex(node);
} else {
node.index = node.display;
}
if (node.children) {
path.push(node.value);
var childReport = recurse(node.children, path);
path.pop();
if (childReport.anySelected) {
node.selected = true;
anySelected = true;
}
childCount += childReport.childCount;
node.childCount = childReport.childCount;
} else {
node.childCount = 0;
}
}
return {anySelected: anySelected, childCount: childCount}
}
var path = [];
recurse(this.syncTree, path);
};
this.addFilter = function(params) {
var value = params.value;
var parents = this.parentIndex[value];
var terms = [params.value];
var clearOthers = edges.getParam(params.clearOthers, false);
var newValues = $.extend(true, [], this.selected);
// if there is, just add the term to it (removing and parent terms along the way)
if (newValues.length > 0) {
newValues.sort();
// if this is an exclusive filter that clears all others, just do that
if (clearOthers) {
newValues = [];
}
// next, if there are any terms left, remove all the parent terms
for (var i = 0; i < parents.length; i++) {
var parent = parents[i];
var location = $.inArray(parent, newValues);
if (location !== -1) {
newValues.splice(location, 1);
}
}
// now add all the provided terms
var hadTermAlready = 0;
for (var i = 0; i < terms.length; i++) {
var term = terms[i];
if ($.inArray(term, newValues) !== -1) {
hadTermAlready++;
} else {
newValues.push(term);
}
}
} else {
newValues = terms;
}
// store the new values on the object and in the form
this.selected = newValues;
this.sourceInput.val(newValues.join(","));
this.sourceInput.trigger("change");
this.edge.cycle();
return true;
};
this.removeFilter = function(params) {
var term = params.value;
var newValues = $.extend(true, [], this.selected);
if (newValues.length > 0) {
var location = $.inArray(term, newValues);
if (location !== -1) {
// the filter we are being asked to remove is the actual selected one
newValues.splice(location, 1);
} else {
// the filter we are being asked to remove may be a parent of the actual selected one
// first get all the parent sets of the values that are currently in force
var removes = [];
for (var i = 0; i < newValues.length; i++) {
var val = newValues[i];
var parentSet = this.parentIndex[val];
if ($.inArray(term, parentSet) > -1) {
removes.push(val);
}
}
for (var i = 0; i < removes.length; i++) {
var location = $.inArray(removes[i], newValues);
if (location !== -1) {
newValues.splice(location, 1);
}
}
}
var grandparents = this.parentIndex[term];
if (grandparents.length > 0) {
var immediate = grandparents[grandparents.length - 1];
var sharedParent = false;
for (var i = 0; i < newValues.length;i ++) {
var aunts = this.parentIndex[newValues[i]];
if (aunts.length > 0 && aunts[aunts.length - 1] === immediate) {
sharedParent = true;
break;
}
}
if (!sharedParent && $.inArray(immediate, newValues) === -1) {
newValues.push(immediate);
}
}
}
// reset the search page to the start and then trigger the next query
// store the new values on the object and in the form
this.selected = newValues;
this.sourceInput.val(newValues.join(","));
this.sourceInput.trigger("change");
this.edge.cycle();
};
},
newSubjectBrowser : function(params) {
return edges.instantiate(formulaic.edges.SubjectBrowser, params, edges.newRenderer);
},
SubjectBrowser : function(params) {
this.title = edges.getParam(params.title, "");
this.hideEmpty = edges.getParam(params.hideEmpty, false);
this.expanded = [];
this.lastScroll = 0;
this.namespace = "formulaic-subject-browser";
this.draw = function() {
// for convenient short references ...
var st = this.component.syncTree;
var namespace = this.namespace;
// var that = this;
// var checkboxClass = edges.css_classes(namespace, "selector", this);
// var countClass = edges.css_classes(namespace, "count", this);
var treeReport = this._renderTree({tree: st, selectedPathOnly: false, showOneLevel: true});
var treeFrag = treeReport.frag;
if (treeFrag === "") {
treeFrag = "Loading...";
}
var toggleId = edges.css_id(namespace, "toggle", this);
var resultsId = edges.css_id(namespace, "results", this);
var searchId = edges.css_id(namespace, "search", this);
var filteredId = edges.css_id(namespace, "filtered", this);
var mainListId = edges.css_id(namespace, "main", this);
var toggle = "";
if (this.togglable) {
toggle = '<span data-feather="chevron-down" aria-hidden="true"></span>';
}
var frag = '<h3 class="label label--secondary filter__heading" type="button" id="' + toggleId + '">' + this.title + toggle + '</h3>\
<div class="filter__body collapse in" aria-expanded="false" id="' + resultsId + '">\
<label for="' + searchId + '" class="sr-only">Search subjects</label>\
<input type="text" name="' + searchId + '" id="' + searchId + '" class="filter__search" placeholder="Search subjects">\
<ul class="filter__choices" id="' + filteredId + '" style="display:none"></ul>\
<ul class="filter__choices" id="' + mainListId + '">{{FILTERS}}</ul>\
</div>';
// substitute in the component parts
frag = frag.replace(/{{FILTERS}}/g, treeFrag);
// now render it into the page
this.component.context.html(frag);
feather.replace();
var mainListSelector = edges.css_id_selector(namespace, "main", this);
this.component.jq(mainListSelector).scrollTop(this.lastScroll);
var checkboxSelector = edges.css_class_selector(namespace, "selector", this);
edges.on(checkboxSelector, "change", this, "filterToggle");
var searchSelector = edges.css_id_selector(namespace, "search", this);
edges.on(searchSelector, "keyup", this, "filterSubjects");
var fieldSelector = edges.css_class_selector(namespace, "field-toggle", this);
edges.on(fieldSelector, "click", this, "fieldToggle");
};
this._renderTree = function(params) {
var st = edges.getParam(params.tree, []);
var selectedPathOnly = edges.getParam(params.selectedPathOnly, true);
var showOneLevel = edges.getParam(params.showOneLevel, true);
var that = this;
var checkboxClass = edges.css_classes(this.namespace, "selector", this);
var toggleClass = edges.css_classes(that.namespace, "field-toggle", this);
function renderEntry(entry) {
if (that.hideEmpty && entry.count === 0 && entry.childCount === 0) {
return "";
}
var id = edges.safeId(entry.value);
var checked = "";
if (entry.selected) {
checked = ' checked="checked" ';
}
// the various rules to do with how this will toggle.
// - whether the toggle is linked -> only when clickng it will have an effect
// - whether the thing is togglable at all -> only when there are children
var toggle = "";
var chevron = "";
var togglable = false;
if (entry.children) {
chevron = "chevron-right";
togglable = true;
if (entry.expanded) {
chevron = "chevron-down";
}
if (entry.selected) {
togglable = false;
}
}
if (togglable) {
toggle = '<span data-feather="' + chevron + '" aria-hidden="true"></span>';
toggle = '<span role="button" class="' + toggleClass + '" data-value="' + edges.escapeHtml(entry.value) + '">' + toggle + '<span class="sr-only">Toggle this subject</span></span>';
}
// FIXME: putting this in for the moment, just so we can use it in dev
// var count = ' <span class="' + countClass + '">(' + entry.count + '/' + entry.childCount + ')</span>';
var count = "";
var frag = '<input class="' + checkboxClass + '" data-value="' + edges.escapeHtml(entry.value) + '" id="' + id + '" type="checkbox" name="' + id + '"' + checked + '>\
<label for="' + id + '" class="filter__label">' + entry.display + count + toggle + '</label>';
return frag;
}
function recurse(tree) {
var selected = tree;
// first check to see if there are any elements at this level that are selected. If there are,
// that is the only element that we'll render
if (selectedPathOnly) {
for (var i = 0; i < tree.length; i++) {
var entry = tree[i];
if (entry.selected) {
selected = [entry];
break;
}
}
}
// now go through either this tree level or just the selected elements, and render the relevant
// bits of the sub-tree
var anySelected = false;
var rFrag = "";
for (var i = 0; i < selected.length; i++) {
var entry = selected[i];
entry.expanded = $.inArray(entry.value, that.expanded) > -1;
var entryFrag = renderEntry(entry);
if (entryFrag === "") {
continue;
}
if (entry.selected) {
anySelected = true;
}
if (entry.children) {
var childReport = recurse(entry.children);
if (childReport.anySelected) {
anySelected = true;
}
// only attach the children frag if, first any of these are true:
// - one of the children is selected
// - the entry itself is selected
// - we don't want to only show the selected path
// - the entry has been expanded
if (!selectedPathOnly || childReport.anySelected || entry.selected || entry.expanded) {
// Then, another level (separated out to save my brain from the tortuous logic)
// only attach the children frag if, any of these are true:
// - the entry or one of its children is selected
// - we want to show more than one level at a time
// - the entry has been expanded
if (childReport.anySelected || entry.selected || !showOneLevel || entry.expanded) {
var cFrag = childReport.frag;
if (cFrag !== "") {
entryFrag += '<ul class="filter__choices">';
entryFrag += cFrag;
entryFrag += '</ul>';
}
}
}
}
rFrag += '<li>';
rFrag += entryFrag;
rFrag += '</li>';
}
return {frag : rFrag, anySelected: anySelected};
}
return recurse(st);
};
this.fieldToggle = function(element) {
var value = this.component.jq(element).attr("data-value");
var existing = $.inArray(value, this.expanded);
if (existing > -1) {
this.expanded.splice(existing, 1);
} else {
this.expanded.push(value);
}
var mainListSelector = edges.css_id_selector(this.namespace, "main", this);
this.lastScroll = this.component.jq(mainListSelector).scrollTop();
this.component.edge.cycle();
};
this.filterToggle = function(element) {
var mainListSelector = edges.css_id_selector(this.namespace, "main", this);
this.lastScroll = this.component.jq(mainListSelector).scrollTop();
// var filter_id = this.component.jq(element).attr("id");
var checked = this.component.jq(element).is(":checked");
var value = this.component.jq(element).attr("data-value");
if (checked) {
this.component.addFilter({value: value});
} else {
this.component.removeFilter({value: value});
}
};
this.filterSubjects = function(element) {
var st = this.component.syncTree;
var term = $(element).val();
var that = this;
var filterSelector = edges.css_id_selector(this.namespace, "filtered", this);
var mainSelector = edges.css_id_selector(this.namespace, "main", this);
var filterEl = this.component.jq(filterSelector);
var mainEl = this.component.jq(mainSelector);