-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathforms-knockout-bindings.js
More file actions
1605 lines (1427 loc) · 64.8 KB
/
forms-knockout-bindings.js
File metadata and controls
1605 lines (1427 loc) · 64.8 KB
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
/**
* Custom knockout bindings used by the forms library
*/
(function() {
/**
* Exposes extra context to child bindings via the binding context.
* Used as a mechanism to allow clients to pass configuration to
* components rendered by this plugin.
*/
ko.bindingHandlers.withContext = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// Make a modified binding context, with a extra properties, and apply it to descendant elements
var innerBindingContext = bindingContext.extend(valueAccessor);
ko.applyBindingsToDescendants(innerBindingContext, element);
// Also tell KO *not* to bind the descendants itself, otherwise they will be bound twice
return { controlsDescendantBindings: true };
}
};
var image = function(props) {
var imageObj = {
id:props.id,
name:props.name,
size:props.size,
url: props.url,
thumbnail_url: props.thumbnail_url,
viewImage : function() {
window['showImageInViewer'](this.id, this.url, this.name);
}
};
return imageObj;
};
ko.bindingHandlers.photoPointUpload = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var defaultConfig = {
maxWidth: 300,
minWidth:150,
minHeight:150,
maxHeight: 300,
previewSelector: '.preview'
};
var size = ko.observable();
var progress = ko.observable();
var error = ko.observable();
var complete = ko.observable(true);
var uploadProperties = {
size: size,
progress: progress,
error:error,
complete:complete
};
var innerContext = bindingContext.createChildContext(bindingContext);
ko.utils.extend(innerContext, uploadProperties);
var config = valueAccessor();
config = $.extend({}, config, defaultConfig);
var dropzone = $(element);
var target = config.target; // Expected to be a ko.observableArray
$(element).fileupload({
url:config.url,
autoUpload:true,
dataType:'json',
dropZone: dropzone
}).on('fileuploadadd', function(e, data) {
complete(false);
progress(1);
}).on('fileuploadprocessalways', function(e, data) {
if (data.files[0].preview) {
if (config.previewSelector !== undefined) {
var previewElem = $(element).parent().find(config.previewSelector);
previewElem.append(data.files[0].preview);
}
}
}).on('fileuploadprogressall', function(e, data) {
progress(Math.floor(data.loaded / data.total * 100));
size(data.total);
}).on('fileuploaddone', function(e, data) {
// var resultText = $('pre', data.result).text();
// var result = $.parseJSON(resultText);
var result = data.result;
if (!result) {
result = {};
error('No response from server');
}
if (result.files[0]) {
target.push(result.files[0]);
complete(true);
}
else {
error(result.error);
}
}).on('fileuploadfail', function(e, data) {
var jqXHR = data.jqXHR;
if (jqXHR && (jqXHR.status === 422 || jqXHR.status === 500)) {
var resp = jqXHR.responseJSON || {};
error(resp.message || jqXHR.responseText || 'File upload failed');
}
else {
error(data.errorThrown);
}
});
ko.applyBindingsToDescendants(innerContext, element);
return { controlsDescendantBindings: true };
}
};
ko.bindingHandlers.imageUpload = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var defaultConfig = {
maxWidth: 300,
minWidth:150,
minHeight:150,
maxHeight: 300,
previewSelector: '.preview',
viewModel: viewModel
};
var size = ko.observable();
var progress = ko.observable();
var error = ko.observable();
var complete = ko.observable(true);
var config = valueAccessor();
config = $.extend({}, config, defaultConfig);
var target = config.target,
dropZone = $(element).find('.dropzone');
var context = config.context;
var uploadProperties = {
size: size,
progress: progress,
error:error,
complete:complete
};
var innerContext = bindingContext.createChildContext(bindingContext);
ko.utils.extend(innerContext, uploadProperties);
var previewElem = $(element).parent().find(config.previewSelector);
// For a reason I can't determine, when forms are loaded via ajax the
// fileupload widget gets a blank widgetEventPrefix. (normally it would be 'fileupload').
// This checks for this condition and registers the correct event listeners.
var eventPrefix = 'fileupload';
if ($.blueimp && $.blueimp.fileupload) {
eventPrefix = $.blueimp.fileupload.prototype.widgetEventPrefix;
}
$(element).fileupload({
url:config.url,
autoUpload:true,
dropZone: dropZone,
pasteZone: null,
dataType:'json'
}).on(eventPrefix+'add', function(e, data) {
previewElem.html('');
complete(false);
progress(1);
}).on(eventPrefix+'processalways', function(e, data) {
if (data.files[0].preview) {
if (config.previewSelector !== undefined) {
previewElem.append(data.files[0].preview);
}
}
}).on(eventPrefix+'progressall', function(e, data) {
progress(Math.floor(data.loaded / data.total * 100));
size(data.total);
}).on(eventPrefix+'done', function(e, data) {
var result = data.result;
var $doc = $(document);
if (!result) {
result = {};
error('No response from server');
}
if (result.files[0]) {
result.files.forEach(function( f ){
// flag to indicate the image is in biocollect and needs to be save to ecodata as a document
var data = {
thumbnailUrl: f.thumbnail_url,
url: f.url,
contentType: f.contentType,
filename: f.name,
name: f.name,
filesize: f.size,
dateTaken: f.isoDate,
staged: true,
attribution: f.attribution,
licence: f.licence
};
target.push(new ImageViewModel(data, true, context));
if(f.decimalLongitude && f.decimalLatitude){
$doc.trigger('imagelocation', {
decimalLongitude: f.decimalLongitude,
decimalLatitude: f.decimalLatitude
});
}
if(f.isoDate){
$doc.trigger('imagedatetime', {
date: f.isoDate
});
}
});
complete(true);
}
else {
error(result.error);
}
}).on(eventPrefix+'fail', function(e, data) {
var jqXHR = data.jqXHR;
if (jqXHR && (jqXHR.status === 422 || jqXHR.status === 500)) {
var resp = jqXHR.responseJSON || {};
error(resp.message || jqXHR.responseText || 'File upload failed');
}
else {
error(data.errorThrown);
}
});
ko.applyBindingsToDescendants(innerContext, element);
return { controlsDescendantBindings: true };
}
};
ko.bindingHandlers.editDocument = {
init:function(element, valueAccessor) {
if (ko.isObservable(valueAccessor())) {
var document = ko.utils.unwrapObservable(valueAccessor());
if (typeof document.status == 'function') {
document.status.subscribe(function(status) {
if (status == 'deleted') {
valueAccessor()(null);
}
});
}
}
var options = {
name:'documentEditTemplate',
data:valueAccessor()
};
return ko.bindingHandlers['template'].init(element, function() {return options;});
},
update:function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var options = {
name:'documentEditTemplate',
data:valueAccessor()
};
ko.bindingHandlers['template'].update(element, function() {return options;}, allBindings, viewModel, bindingContext);
}
};
ko.bindingHandlers.expression = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var expressionString = ko.utils.unwrapObservable(valueAccessor());
var result = ecodata.forms.expressionEvaluator.evaluate(expressionString, bindingContext);
$(element).text(result);
}
};
/*
* Fused Autocomplete supports two versions of autocomplete (original autocomplete implementation by Jorn Zaefferer and jquery_ui)
* Expects three parameters source, name and guid.
* Ajax response lists needs name attribute.
* Doco url: http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
* Note: Autocomplete implementation by Jorn Zaefferer is now been deprecated and its been migrated to jquery_ui.
*
*/
ko.bindingHandlers.fusedAutocomplete = {
init: function (element, params) {
var params = params();
var options = {};
var url = ko.utils.unwrapObservable(params.source);
options.source = function(request, response) {
$(element).addClass("ac_loading");
$.ajax({
url: url,
dataType:'json',
data: {q:request.term},
success: function(data) {
var items = $.map(data.autoCompleteList, function(item) {
return {
label:item.name,
value: item.name,
source: item
}
});
response(items);
},
error: function() {
items = [{label:"Error during species lookup", value:request.term, source: {listId:'error-unmatched', name: request.term}}];
response(items);
},
complete: function() {
$(element).removeClass("ac_loading");
}
});
};
options.select = function(event, ui) {
var selectedItem = ui.item;
params.name(selectedItem.source.name);
params.guid(selectedItem.source.guid);
};
if(!$(element).autocomplete(options).data("ui-autocomplete")){
// Fall back mechanism to handle deprecated version of autocomplete.
var options = {};
options.source = url;
options.matchSubset = false;
options.formatItem = function(row, i, n) {
return row.name;
};
options.highlight = false;
options.parse = function(data) {
var rows = new Array();
data = data.autoCompleteList;
for(var i=0; i < data.length; i++) {
rows[i] = {
data: data[i],
value: data[i],
result: data[i].name
};
}
return rows;
};
$(element).autocomplete(options.source, options).result(function(event, data, formatted) {
if (data) {
params.name(data.name);
params.guid(data.guid);
}
});
}
}
};
ko.bindingHandlers.speciesAutocomplete = {
init: function (element, params, allBindings, viewModel, bindingContext) {
var param = params();
var url = ko.utils.unwrapObservable(param.url);
var list = ko.utils.unwrapObservable(param.listId);
var valueCallback = ko.utils.unwrapObservable(param.valueChangeCallback)
var options = {};
var lastHeader;
function rowTitle(listId) {
if (listId == 'unmatched' || listId == 'error-unmatched') {
return '';
}
if (!listId) {
return 'Atlas of Living Australia';
}
return 'Species List';
}
var renderItem = function(row) {
var result = '';
var title = rowTitle(row.listId);
if (title && lastHeader !== title) {
result+='<div style="background:grey;color:white; padding-left:5px;"> '+title+'</div>';
}
// We are keeping track of list headers so we only render each one once.
lastHeader = title;
result+='<a class="speciesAutocompleteRow">';
if (row.listId && row.listId === 'unmatched') {
result += '<i>Unlisted or unknown species</i>';
}
else if (row.listId && row.listId === 'error-unmatched') {
result += '<i>Offline</i><div>Species:<b>'+row.name+'</b></div>';
}
else {
var commonNameMatches = row.commonNameMatches !== undefined ? row.commonNameMatches : "";
result += (row.scientificNameMatches && row.scientificNameMatches.length>0) ? row.scientificNameMatches[0] : commonNameMatches ;
if (row.name != result && row.rankString) {
result = result + "<div class='autoLine2'>" + row.rankString + ": " + row.name + "</div>";
} else if (row.rankString) {
result = result + "<div class='autoLine2'>" + row.rankString + "</div>";
} else {
result = result + "<div class='autoLine2'>" + row.name + "</div>";
}
}
result += '</a>';
return result;
};
function onlineQuery(url, data) {
return $.ajax({
url: url,
dataType:'json',
data: data
});
}
function offlineQuery(url, data) {
var deferred = $.Deferred()
if ( typeof URLSearchParams == 'function') {
var paramIndex = url.indexOf('?'),
paramsString = paramIndex > -1 ? url.substring(paramIndex + 1) : url,
params = new URLSearchParams(paramsString),
limit = parseInt(params.get('limit') || "10"),
projectActivityId = params.get('projectActivityId'),
dataFieldName = params.get('dataFieldName'),
outputName = params.get('output');
if (window.entities)
return window.entities.searchSpecies(projectActivityId, dataFieldName, outputName, data, limit);
}
deferred.resolve({autoCompleteList: []});
return deferred.promise();
}
function searchSpecies(url, data) {
return isOffline().then(function () {
return offlineQuery(url, data);
}, function () {
return onlineQuery(url, data);
})
}
options.source = function(request, response) {
$(element).addClass("ac_loading");
if (valueCallback !== undefined) {
valueCallback(request.term);
}
var data = {q:request.term};
if (list) {
$.extend(data, {listId: list});
}
searchSpecies(url,data).then(function(data) {
var items = $.map(data.autoCompleteList, function(item) {
return {
label:item.name,
value: item.name,
source: item
}
});
// add missing species last
items.push({label:"Missing or unidentified species", value:_.escape(request.term), source: {listId:'unmatched', name: _.escape(request.term), scientificName: _.escape(request.term)}});
response(items);
}).fail(function(e) {
items = [{label:"Error during species lookup", value:_.escape(request.term), source: {listId:'error-unmatched', name: _.escape(request.term), scientificName: _.escape(request.term)}}];
response(items);
}).always(function() {
$(element).removeClass("ac_loading");
});
};
options.select = function(event, ui) {
ko.utils.unwrapObservable(param.result)(event, ui.item.source);
};
if ($(element).autocomplete(options).data("ui-autocomplete")) {
$(element).autocomplete(options).data("ui-autocomplete")._renderItem = function(ul, item) {
var result = $('<li></li>').html(renderItem(item.source));
return result.appendTo(ul);
};
}
else {
$(element).autocomplete(options);
}
}
};
function forceSelect2ToRespectPercentageTableWidths(element, percentageWidth) {
var $parentColumn = $(element).parent('td');
var $parentTable = $parentColumn.closest('table');
var resizeHandler = null;
if ($parentColumn.length) {
var select2 = $parentColumn.find('.select2-container');
function calculateWidth() {
var parentWidth = $parentTable.width();
// If the table has overflowed due to long selections then we need to try and find a parent div
// as the div won't have overflowed.
var windowWidth = window.innerWidth;
if (parentWidth > windowWidth) {
var parent = $parentTable.parent('div');
if (parent.length) {
parentWidth = parent.width();
}
else {
parentWidth = windowWidth;
}
}
var columnWidth = parentWidth*percentageWidth/100;
if (columnWidth > 10) {
select2.css('max-width', columnWidth+'px');
$(element).validationEngine('updatePromptsPosition');
}
else {
// The table is not visible yet, so wait a bit and try again.
setTimeout(calculateWidth, 200);
}
}
resizeHandler = function() {
clearTimeout(calculateWidth);
setTimeout(calculateWidth, 300);
};
$(window).on('resize', resizeHandler);
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(window).off('resize', resizeHandler);
});
calculateWidth();
}
}
function applySelect2ValidationCompatibility(element) {
var $element = $(element);
var select2 = $element.next('.select2-container');
$element.on('select2:close', function(e) {
$element.validationEngine('validate');
}).attr("data-prompt-position", "topRight:"+select2.width());
}
/**
* Converts an array of data to the format expected by select2.
* @param dataArray - Array of objects or strings/numbers
* @param idField - The name of the field to use as the id for objects in the dataArray
* @param textField - The name of the field to use as the text for objects in the dataArray
* @param selectedValue - The value to mark as selected
* @returns {[{id: ... , text: ..., selected: true|false}, ...]} An array of objects with id and text attributes and optionally selected:true
*/
function convertDataArrayToSelect2Representation(dataArray, idField, textField, selectedValue) {
var result = [];
dataArray.forEach(function(item) {
var option;
if (typeof item === 'string' || typeof item === 'number') {
option = {id:item, text:item};
}
else if (typeof item === 'object') {
option = convertDataToSelect2Representation(item, idField, textField, selectedValue);
}
if (option) {
result.push(option);
}
});
return result;
}
/**
* Converts a single object to the format expected by select2.
* @param item - An object, string or number
* @param idField - The name of the field to use as the id for the object
* @param textField - The name of the field to use as the text for the object
* @returns {{id: *, text: *}|null}
*/
function convertDataToSelect2Representation(item, idField, textField, selectedValue) {
if (!item)
return null;
var option;
if (typeof item === 'string' || typeof item === 'number') {
option = {id:item, text:item};
} else if (typeof item === 'object') {
if (!idField || !textField || !item.hasOwnProperty(idField) || !item.hasOwnProperty(textField)) {
console.error("Either idField or textField is not specified or item does not have the specified fields");
return;
}
option = {id: item[idField], text: item[textField]};
}
if (option.id == selectedValue) {
option.selected = true;
}
return option;
}
/**
* Finds an option in an array of options by matching the idField to the supplied value.
* @param dataArray - Array of objects, strings or numbers
* @param idField - The name of the field to use as the id for objects in the dataArray
* @param value - The value to match against the idField
* @returns {*|null}
*/
function findOption(dataArray, idField, value) {
for (var i=0; i<dataArray.length; i++) {
var item = dataArray[i];
if (typeof item === 'object' && item.hasOwnProperty(idField)) {
if (dataArray[i][idField] == value) {
return dataArray[i];
}
}
else if (typeof item === 'string' || typeof item === 'number') {
if (item == value) {
return item;
}
}
}
return null;
}
ko.bindingHandlers.speciesSelect2 = {
select2AwareFormatter: function(data, container, delegate) {
if (data.text) {
return data.text;
}
return delegate(data);
},
init: function (element, valueAccessor) {
var self = ko.bindingHandlers.speciesSelect2;
var model = valueAccessor();
$.fn.select2.amd.require(['select2/species'], function(SpeciesAdapter) {
$(element).select2({
dataAdapter: SpeciesAdapter,
placeholder:{id:-1, text:'Start typing species name to search...'},
templateResult: function(data, container) { return self.select2AwareFormatter(data, container, model.formatSearchResult); },
templateSelection: function(data, container) { return self.select2AwareFormatter(data, container, model.formatSelectedSpecies); },
dropdownAutoWidth: true,
model:model,
escapeMarkup: function(markup) {
return markup; // We want to apply our own formatting so manually escape the user input.
},
ajax:{} // We want infinite scroll and this is how to get it.
});
applySelect2ValidationCompatibility(element);
})
},
update: function (element, valueAccessor) {}
};
/**
* Supports custom rendering of results in a Select2 dropdown.
*/
function constraintIconRenderer(config) {
return function(item) {
var constraint = item.id;
if (config[constraint]) {
var icon = config[constraint];
var iconElement;
if (icon.url) {
iconElement = $("<img/>").addClass('constraint-image').css("src", icon.url);
}
else {
iconElement = $("<span/>").addClass('constraint-icon');
if (icon.class) {
if (_.isArray(icon.class)) {
_.each(icon.class, function(val) {
iconElement.addClass(val);
});
}
else {
_.each(icon.class.split(" "), function (val) {
iconElement.addClass(icon.class);
});
}
}
if (icon.style) {
_.each(icon.style, function(value, key) {
iconElement.css(key, value);
});
}
}
return $("<span/>").append(iconElement).append($("<span/>").addClass('constraint-text').text(constraint));
}
return item.text;
};
};
/**
* Provides support for applying https://select2.org for options selection.
* The value supplied to this binding will be passed through as options to the select2
* widget. It is expected this binding will be used in conjunction with the value binding
* so that updates to the view model will be reflected in the select 2 component.
* @type {{init: ko.bindingHandlers.select2.init}}
*/
ko.bindingHandlers.select2 = {
init: function(element, valueAccessor, allBindings) {
var defaults = {
placeholder:'Please select...',
dropdownAutoWidth:true,
allowClear:true
};
var options = _.defaults(valueAccessor() || {}, defaults);
if (options.constraintIcons) {
var renderer = constraintIconRenderer(options.constraintIcons);
options.templateResult = renderer;
options.templateSelection = renderer;
}
var $element = $(element);
$element.select2(options);
applySelect2ValidationCompatibility(element);
// Listen for changes to the view model and ensure the select2 component is
// updated to reflect the change.
var valueBinding = allBindings.get('value');
if (ko.isObservable(valueBinding)) {
valueBinding.subscribe(function(newValue) {
// Depending on the order the bindings are declared (value before select2
// or vice versa), they can interfere with each other.
var currentValue = $element.val();
if (currentValue != newValue) {
// If the value is out of sync with the model, update the value.
$element.val(newValue);
}
// Make sure the select2 library is aware of the change.
$element.trigger('change');
});
}
if (options.preserveColumnWidth) {
forceSelect2ToRespectPercentageTableWidths(element, options.preserveColumnWidth);
}
else {
applySelect2ValidationCompatibility(element);
}
}
};
/**
* A more performant version of the select2 binding that is designed to work with large
* number of options. The options are supplied as an array via the dataArray option.
*
* @param {Array} dataArray An array of objects, string or number representing the options to be displayed.
* @param {String} optionsText The name of the field in the dataArray objects to use as the option text.
* @param {String} optionsValue The name of the field in the dataArray objects to use as the option value.
* @param {Observable} value An observable to be updated when the selection changes.
* @param {String} placeholder Placeholder text to display when no option is selected.
* @param * any other options supported by select2 can be supplied.
* @type {{init: ko.bindingHandlers.select2WithData.init}}
*/
ko.bindingHandlers.select2FromArray = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var defaults = {
placeholder:'Please select...',
dropdownAutoWidth:true,
allowClear:true,
pageSize:50
};
var options = _.defaults(valueAccessor() || {}, defaults);
var $element = $(element);
var valueObservable = options.value,
dataArray = options.dataArray || [],
dataArrayObservable = ko.isObservable(dataArray) ? dataArray : ko.observableArray(dataArray);
options.ajax = {
// Instead of using the ajax capabilities of select2 to call a remote service to get options,
// we are going to paginate and filter the dataArray supplied.
transport: function(params, success, failure) {
var term = params.data.term || '';
var page = params.data.page || 1;
var pageSize = options.pageSize;
var start = (page - 1) * pageSize;
var allOptions = ko.unwrap(dataArrayObservable),
selectedValue = ko.unwrap(valueObservable);
// Convert the data to select2 format with id and text attributes.
allOptions = convertDataArrayToSelect2Representation(allOptions, options.optionsValue, options.optionsText, selectedValue);
var filtered = [];
// Simple case-insensitive match.
allOptions.forEach(function (option) {
if (option.text.toLowerCase().indexOf(term.toLowerCase())>=0) {
filtered.push(option);
}
});
var results = filtered.slice(start, start + pageSize);
success({
results: results,
pagination: {
more: start + pageSize < filtered.length
}
});
}
}
$element.select2(options);
applySelect2ValidationCompatibility(element);
// Listen for changes to the view model and ensure the select2 component is
// updated to reflect the change.
if (ko.isObservable(valueObservable)) {
valueObservable.subscribe(initSelectOption);
$element.on('select2:select', function(e) {
var selected = e.params.data;
if (valueObservable() !== selected.id) {
valueObservable(selected.id);
}
})
}
if (options.preserveColumnWidth) {
forceSelect2ToRespectPercentageTableWidths(element, options.preserveColumnWidth);
}
else {
applySelect2ValidationCompatibility(element);
}
function initSelectOption(newValue) {
// Depending on the order the bindings are declared (value before select2
// or vice versa), they can interfere with each other.
var currentValue = $element.val();
if (currentValue != newValue) {
var option = convertDataToSelect2Representation(findOption(ko.unwrap(dataArrayObservable), options.optionsValue, newValue), options.optionsValue, options.optionsText, newValue);
if (option) {
$element.append(new Option(option.text, option.id, true, true));
}
// If the value is out of sync with the model, update the value.
$element.val(newValue);
}
// Make sure the select2 library is aware of the change.
$element.trigger('change');
}
initSelectOption(ko.unwrap(valueObservable));
}
};
ko.bindingHandlers.multiSelect2 = {
init: function(element, valueAccessor, allBindings) {
var defaults = {
placeholder:'Select all that apply...',
dropdownAutoWidth:true,
allowClear:false,
tags:true
};
var options = valueAccessor();
var model = options.value;
if (!ko.isObservable(model, ko.observableArray)) {
throw "The options require a key with name 'value' with a value of type ko.observableArray";
}
var constraints;
if (model.hasOwnProperty('constraints')) {
constraints = model.constraints;
}
else {
// Attempt to use the options binding to see if we can observe changes to the constraints
constraints = allBindings.get('options');
}
// Because constraints can be initialised by an AJAX call, constraints can be added after initialisation
// which can result in duplicate OPTIONS tags for pre-selected values, which confuses select2.
// Here we watch for changes to the model constraints and make sure any duplicates are removed.
if (constraints && ko.isObservable(constraints)) {
constraints.subscribe(function(val) {
var existing = {};
var duplicates = [];
var currentOptions = $(element).find("option").each(function() {
var val = $(this).val();
if (existing[val]) {
duplicates.push(this);
}
else {
existing[val] = true;
}
});
// Remove any duplicates
for (var i=0; i<duplicates.length; i++) {
element.removeChild(duplicates[i]);
}
});
}
delete options.value;
var options = _.defaults(valueAccessor() || {}, defaults);
$(element).select2(options).change(function(e) {
if (ko.isWritableObservable(model)) { // Don't try and write the value to a computed.
model($(element).val());
}
});
if (options.preserveColumnWidth) {
forceSelect2ToRespectPercentageTableWidths(element, options.preserveColumnWidth);
}
applySelect2ValidationCompatibility(element);
},
update: function(element, valueAccessor) {
var $element = $(element);
var data = valueAccessor().value();
var currentOptions = $element.find("option").map(function() {return $(this).val();}).get();
var extraOptions = _.difference(data, currentOptions);
for (var i=0; i<extraOptions.length; i++) {
$element.append($("<option>").val(extraOptions[i]).text(extraOptions[i]));
}
var elementValue = $element.val();
if (!_.isEqual(elementValue, data)) {
$element.val(valueAccessor().value()).trigger('change');
}
}
};
var popoverWarningOptions = {
placement:'auto',
trigger:'manual',
template: '<div class="popover warning"><h3 class="popover-header"></h3><div class="popover-body"></div><div class="arrow"></div></div>'
};
/**
* This binding requires that the observable has used the metadata extender. It is meant to work with the
* form rendering code so isn't very useful as a stand alone binding.
*
* @type {{init: ko.bindingHandlers.warning.init, update: ko.bindingHandlers.warning.update}}
*/
ko.bindingHandlers.warning = {
init: function(element, valueAccessor) {
var target = valueAccessor();
if (typeof target.checkWarnings !== 'function') {
throw "This binding requires the target observable to have used the \"metadata\" extender"
}
var $element = $(element);
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
let popover = bootstrap.Popover.getInstance(element);
if (popover) {
popover.dispose();
}
});
function isPopoverShown(element) {
const popoverId = $(element).attr("aria-describedby");
return $("#" + popoverId).length > 0;
}
// We are implementing the validation routine by adding a subscriber to avoid triggering the validation
// on initialisation.
target.subscribe(function() {
let valid = $element.validationEngine('validate');
let popover = bootstrap.Popover.getInstance(element);
// Only check warnings if the validation passes to avoid showing two sets of popups.
if (valid) {
var result = target.checkWarnings();
if (result) {
if (!popover) {
const options = _.extend({content:result.val[0]}, popoverWarningOptions);
popover = new bootstrap.Popover(element, options);
}
if (!isPopoverShown(element)) {
popover.show();
$element.on('shown.bs.popover', function() {
$(popover._getTipElement()).one('click', function() {
popover.hide();
})
})
}
}
else {
if (popover) {
popover.hide();
}
}
}