forked from forms-angular/forms-angular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforms-angular.js
More file actions
3760 lines (3759 loc) · 218 KB
/
Copy pathforms-angular.js
File metadata and controls
3760 lines (3759 loc) · 218 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
/// <reference path="../typings/angularjs/angular.d.ts" />
/// <reference path="../../typings/angularjs/angular.d.ts" />
/// <reference path="../fng-types.ts" />
var fng;
(function (fng) {
var controllers;
(function (controllers) {
/*@ngInject*/
BaseCtrl.$inject = ["$scope", "$rootScope", "$location", "$filter", "$uibModal", "$data", "routingService", "formGenerator", "recordHandler"];
function BaseCtrl($scope, $rootScope, $location, $filter, $uibModal, $data, routingService, formGenerator, recordHandler) {
var sharedStuff = $data;
var ctrlState = {
master: {},
fngInvalidRequired: 'fng-invalid-required',
allowLocationChange: true // Set when the data arrives..
};
angular.extend($scope, routingService.parsePathFunc()($location.$$path));
$scope.modelNameDisplay = sharedStuff.modelNameDisplay || $filter('titleCase')($scope.modelName);
$rootScope.$broadcast('fngFormLoadStart', $scope);
formGenerator.decorateScope($scope, formGenerator, recordHandler, sharedStuff);
recordHandler.decorateScope($scope, $uibModal, recordHandler, ctrlState);
recordHandler.fillFormWithBackendSchema($scope, formGenerator, recordHandler, ctrlState);
// Tell the 'model controllers' that they can start fiddling with basescope
for (var i = 0; i < sharedStuff.modelControllers.length; i++) {
if (sharedStuff.modelControllers[i].onBaseCtrlReady) {
sharedStuff.modelControllers[i].onBaseCtrlReady($scope);
}
}
}
controllers.BaseCtrl = BaseCtrl;
})(controllers = fng.controllers || (fng.controllers = {}));
})(fng || (fng = {}));
/// <reference path="../../typings/angularjs/angular.d.ts" />
var fng;
(function (fng) {
var controllers;
(function (controllers) {
/*@ngInject*/
SaveChangesModalCtrl.$inject = ["$scope", "$uibModalInstance"];
function SaveChangesModalCtrl($scope, $uibModalInstance) {
$scope.yes = function () {
$uibModalInstance.close(true);
};
$scope.no = function () {
$uibModalInstance.close(false);
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
}
controllers.SaveChangesModalCtrl = SaveChangesModalCtrl;
})(controllers = fng.controllers || (fng.controllers = {}));
})(fng || (fng = {}));
/// <reference path="../../typings/angularjs/angular.d.ts" />
var fng;
(function (fng) {
var controllers;
(function (controllers) {
/*@ngInject*/
ModelCtrl.$inject = ["$scope", "$http", "$location", "routingService"];
function ModelCtrl($scope, $http, $location, routingService) {
$scope.models = [];
$http.get('/api/models').success(function (data) {
$scope.models = data;
}).error(function () {
$location.path('/404');
});
$scope.newUrl = function (model) {
return routingService.buildUrl(model + '/new');
};
$scope.listUrl = function (model) {
return routingService.buildUrl(model);
};
}
controllers.ModelCtrl = ModelCtrl;
})(controllers = fng.controllers || (fng.controllers = {}));
})(fng || (fng = {}));
/// <reference path="../../typings/angularjs/angular.d.ts" />
var fng;
(function (fng) {
var controllers;
(function (controllers) {
/*@ngInject*/
NavCtrl.$inject = ["$scope", "$data", "$location", "$filter", "$controller", "routingService", "cssFrameworkService"];
function NavCtrl($scope, $data, $location, $filter, $controller, routingService, cssFrameworkService) {
$scope.items = [];
/* isCollapsed and showShortcuts are used to control how the menu is displayed in a responsive environment and whether the shortcut keystrokes help should be displayed */
$scope.isCollapsed = true;
$scope.showShortcuts = false;
$scope.shortcuts = [
{ key: '?', act: 'Show shortcuts' },
{ key: '/', act: 'Jump to search' },
{ key: 'Ctrl+Shift+S', act: 'Save the current record' },
{ key: 'Ctrl+Shift+Esc', act: 'Cancel changes on the current record' },
{ key: 'Ctrl+Shift+Ins', act: 'Create a new record' },
{ key: 'Ctrl+Shift+X', act: 'Delete the current record' }
];
$scope.markupShortcut = function (keys) {
return '<span class="key">' + keys.split('+').join('</span> + <span class="key">') + '</span>';
};
$scope.globalShortcuts = function (event) {
function deferredBtnClick(id) {
var btn = document.getElementById(id);
if (btn) {
if (!btn.disabled) {
setTimeout(function () {
btn.click();
});
}
event.preventDefault();
}
}
function filter(event) {
var tagName = (event.target || event.srcElement).tagName;
return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
}
//console.log(event.keyCode, event.ctrlKey, event.shiftKey, event.altKey, event.metaKey);
if (event.keyCode === 191 && (filter(event) || (event.ctrlKey && !event.altKey && !event.metaKey))) {
if (event.ctrlKey || !event.shiftKey) {
var searchInput = document.getElementById('searchinput');
if (searchInput) {
searchInput.focus();
event.preventDefault();
}
}
else {
$scope.showShortcuts = true;
}
}
else if (event.keyCode === 83 && event.ctrlKey && event.shiftKey && !event.altKey && !event.metaKey) {
deferredBtnClick('saveButton'); // Ctrl+Shift+S saves changes
}
else if (event.keyCode === 27 && ((event.ctrlKey && event.shiftKey && !event.altKey && !event.metaKey) || $scope.showShortcuts)) {
if (event.ctrlKey && event.shiftKey && !event.altKey && !event.metaKey) {
deferredBtnClick('cancelButton'); // Ctrl+Shift+Esc cancels updates
}
else {
$scope.showShortcuts = false;
}
}
else if (event.keyCode === 45 && event.ctrlKey && event.shiftKey && !event.altKey && !event.metaKey) {
deferredBtnClick('newButton'); // Ctrl+Shift+Ins creates New record
}
else if (event.keyCode === 88 && event.ctrlKey && event.shiftKey && event.altKey && !event.metaKey) {
deferredBtnClick('deleteButton'); // Ctrl+Shift+X deletes record
}
};
$scope.css = function (fn, arg) {
var result;
if (typeof cssFrameworkService[fn] === 'function') {
result = cssFrameworkService[fn](arg);
}
else {
result = 'error text-error';
}
return result;
};
function loadControllerAndMenu(controllerName, level, needDivider) {
var locals = {}, addThis;
controllerName += 'Ctrl';
locals.$scope = $data.modelControllers[level] = $scope.$new();
try {
$controller(controllerName, locals);
if ($scope.routing.newRecord) {
addThis = 'creating';
}
else if ($scope.routing.id) {
addThis = 'editing';
}
else {
addThis = 'listing';
}
if (angular.isObject(locals.$scope.contextMenu)) {
angular.forEach(locals.$scope.contextMenu, function (value) {
if (value.divider) {
needDivider = true;
}
else if (value[addThis]) {
if (needDivider) {
needDivider = false;
$scope.items.push({ divider: true });
}
$scope.items.push(value);
}
});
}
}
catch (error) {
// Check to see if error is no such controller - don't care
if (!(/is not a function, got undefined/.test(error.message))) {
console.log('Unable to instantiate ' + controllerName + ' - ' + error.message);
}
}
}
$scope.$on('$locationChangeSuccess', function () {
$scope.routing = routingService.parsePathFunc()($location.$$path);
$scope.items = [];
if ($scope.routing.analyse) {
$scope.contextMenu = 'Report';
$scope.items = [
{
broadcast: 'exportToPDF',
text: 'PDF'
},
{
broadcast: 'exportToCSV',
text: 'CSV'
}
];
}
else if ($scope.routing.modelName) {
angular.forEach($data.modelControllers, function (value) {
value.$destroy();
});
$data.modelControllers = [];
$data.record = {};
$data.disableFunctions = {};
$data.dataEventFunctions = {};
delete $data.dropDownDisplay;
delete $data.modelNameDisplay;
// Now load context menu. For /person/client/:id/edit we need
// to load PersonCtrl and PersonClientCtrl
var modelName = $filter('titleCase')($scope.routing.modelName, true);
var needDivider = false;
loadControllerAndMenu(modelName, 0, needDivider);
if ($scope.routing.formName) {
loadControllerAndMenu(modelName + $filter('titleCase')($scope.routing.formName, true), 1, needDivider);
}
$scope.contextMenu = $data.dropDownDisplay || $data.modelNameDisplay || $filter('titleCase')($scope.routing.modelName, false);
}
});
$scope.doClick = function (index, event) {
var option = angular.element(event.target);
var item = $scope.items[index];
if (item.divider || option.parent().hasClass('disabled')) {
event.preventDefault();
}
else if (item.broadcast) {
$scope.$broadcast(item.broadcast);
}
else {
// Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
var args = item.args || [], fn = item.fn;
switch (args.length) {
case 0:
fn();
break;
case 1:
fn(args[0]);
break;
case 2:
fn(args[0], args[1]);
break;
case 3:
fn(args[0], args[1], args[2]);
break;
case 4:
fn(args[0], args[1], args[2], args[3]);
break;
}
}
};
$scope.isHidden = function (index) {
return $scope.items[index].isHidden ? $scope.items[index].isHidden() : false;
};
$scope.isDisabled = function (index) {
return $scope.items[index].isDisabled ? $scope.items[index].isDisabled() : false;
};
$scope.buildUrl = function (path) {
return routingService.buildUrl(path);
};
$scope.dropdownClass = function (index) {
var item = $scope.items[index];
var thisClass = '';
if (item.divider) {
thisClass = 'divider';
}
else if ($scope.isDisabled(index)) {
thisClass = 'disabled';
}
return thisClass;
};
}
controllers.NavCtrl = NavCtrl;
})(controllers = fng.controllers || (fng.controllers = {}));
})(fng || (fng = {}));
/// <reference path="../../typings/angularjs/angular.d.ts" />
var fng;
(function (fng) {
var controllers;
(function (controllers) {
/*@ngInject*/
SearchCtrl.$inject = ["$scope", "$http", "$location", "routingService"];
function SearchCtrl($scope, $http, $location, routingService) {
var currentRequest = '';
var _isNotMobile;
_isNotMobile = (function () {
var check = false;
(function (a) {
/* tslint:disable:max-line-length */
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) {
/* tslint:enable:max-line-length */
check = true;
}
})(navigator.userAgent || navigator.vendor || window['opera']);
return !check;
})();
$scope.searchPlaceholder = _isNotMobile ? 'Ctrl + / to Search' : 'Search';
$scope.handleKey = function (event) {
if (event.keyCode === 27 && $scope.searchTarget && $scope.searchTarget.length > 0) {
$scope.searchTarget = '';
}
else if ($scope.results.length > 0) {
switch (event.keyCode) {
case 38:
// up arrow pressed
if ($scope.focus > 0) {
$scope.setFocus($scope.focus - 1);
}
if (typeof event.preventDefault === 'function') {
event.preventDefault();
}
break;
case 40:
// down arrow pressed
if ($scope.results.length > $scope.focus + 1) {
$scope.setFocus($scope.focus + 1);
}
if (typeof event.preventDefault === 'function') {
event.preventDefault();
}
break;
case 13:
if ($scope.focus != null) {
$scope.selectResult($scope.focus);
}
break;
}
}
};
$scope.setFocus = function (index) {
if ($scope.focus !== null) {
delete $scope.results[$scope.focus].focussed;
}
$scope.results[index].focussed = true;
$scope.focus = index;
};
$scope.selectResult = function (resultNo) {
var result = $scope.results[resultNo];
var newURL = routingService.prefix() + '/' + result.resource + '/' + result.id + '/edit';
if (result.resourceTab) {
newURL += '/' + result.resourceTab;
}
$location.url(newURL);
};
$scope.resultClass = function (index) {
var resultClass = 'search-result';
if ($scope.results && $scope.results[index].focussed) {
resultClass += ' focus';
}
return resultClass;
};
var clearSearchResults = function () {
$scope.moreCount = 0;
$scope.errorClass = '';
$scope.results = [];
$scope.focus = null;
};
$scope.$watch('searchTarget', function (newValue) {
if (newValue && newValue.length > 0) {
currentRequest = newValue;
$http.get('/api/search?q=' + newValue).success(function (data) {
// Check that we haven't fired off a subsequent request, in which
// case we are no longer interested in these results
if (currentRequest === newValue) {
if ($scope.searchTarget.length > 0) {
$scope.results = data.results;
$scope.moreCount = data.moreCount;
if (data.results.length > 0) {
$scope.errorClass = '';
$scope.setFocus(0);
}
$scope.errorClass = $scope.results.length === 0 ? 'error has-error' : '';
}
else {
clearSearchResults();
}
}
}).error(function (data, status) {
console.log('Error in searchbox.js : ' + data + ' (status=' + status + ')');
});
}
else {
clearSearchResults();
}
}, true);
$scope.$on('$routeChangeStart', function () {
$scope.searchTarget = '';
});
}
controllers.SearchCtrl = SearchCtrl;
})(controllers = fng.controllers || (fng.controllers = {}));
})(fng || (fng = {}));
/// <reference path="../../typings/angularjs/angular.d.ts" />
var fng;
(function (fng) {
var directives;
(function (directives) {
/*@ngInject*/
function modelControllerDropdown() {
return {
restrict: 'AE',
replace: true,
template: '<li ng-show="items.length > 0" class="mcdd" uib-dropdown>' +
' <a uib-dropdown-toggle>' +
' {{contextMenu}} <b class="caret"></b>' +
' </a>' +
' <ul class="uib-dropdown-menu dropdown-menu">' +
' <li ng-repeat="choice in items" ng-hide="isHidden($index)" ng-class="dropdownClass($index)">' +
' <a ng-show="choice.text" class="dropdown-option" ng-href="{{choice.url}}" ng-click="doClick($index, $event)">' +
' {{choice.text}}' +
' </a>' +
' </li>' +
' </ul>' +
'</li>'
};
}
directives.modelControllerDropdown = modelControllerDropdown;
})(directives = fng.directives || (fng.directives = {}));
})(fng || (fng = {}));
/// <reference path="../../typings/angularjs/angular.d.ts" />
var fng;
(function (fng) {
var directives;
(function (directives) {
/*@ngInject*/
function errorDisplay() {
return {
restrict: 'E',
template: '<div id="display-error" ng-show="errorMessage" ng-class="css(\'rowFluid\')">' +
' <div class="alert alert-error col-lg-offset-3 offset3 col-lg-6 col-xs-12 span6 alert-warning alert-dismissable">' +
' <button type="button" class="close" ng-click="dismissError()">×</button>' +
' <h4>{{alertTitle}}</h4>' +
' <div ng-bind-html="errorMessage"></div>' +
' </div>' +
'</div>'
};
}
directives.errorDisplay = errorDisplay;
})(directives = fng.directives || (fng.directives = {}));
})(fng || (fng = {}));
/// <reference path="../../typings/angularjs/angular.d.ts" />
var fng;
(function (fng) {
var directives;
(function (directives) {
/*@ngInject*/
fngLink.$inject = ["routingService", "SubmissionsService"];
function fngLink(routingService, SubmissionsService) {
return {
restrict: 'E',
scope: { dataSrc: '&model' },
link: function (scope, element, attrs) {
var ref = attrs['ref'];
var form = attrs['form'];
scope['readonly'] = attrs['readonly'];
form = form ? form + '/' : '';
if (attrs['text'] && attrs['text'].length > 0) {
scope['text'] = attrs['text'];
}
var index = scope['$parent']['$index'];
scope.$watch('dataSrc()', function (newVal) {
if (newVal) {
if (typeof index !== 'undefined' && angular.isArray(newVal)) {
newVal = newVal[index];
}
scope['link'] = routingService.buildUrl(ref + '/' + form + newVal + '/edit');
if (!scope['text']) {
SubmissionsService.getListAttributes(ref, newVal).success(function (data) {
if (data.success === false) {
scope['text'] = data.err;
}
else {
scope['text'] = data.list;
}
}).error(function (status, err) {
scope['text'] = 'Error ' + status + ': ' + err;
});
}
}
}, true);
},
template: function (element, attrs) {
return attrs.readonly ? '<span class="fng-link">{{text}}</span>' : '<a href="{{ link }}" class="fng-link">{{text}}</a>';
}
};
}
directives.fngLink = fngLink;
})(directives = fng.directives || (fng.directives = {}));
})(fng || (fng = {}));
/// <reference path="../../typings/angularjs/angular.d.ts" />
/// <reference path="../../typings/underscore/underscore.d.ts" />
/// <reference path="../fng-types.ts" />
var fng;
(function (fng) {
var directives;
(function (directives) {
formInput.$inject = ["$compile", "$rootScope", "$filter", "$data", "$timeout", "cssFrameworkService", "formGenerator", "formMarkupHelper"];
var tabsSetupState;
(function (tabsSetupState) {
tabsSetupState[tabsSetupState["Y"] = 0] = "Y";
tabsSetupState[tabsSetupState["N"] = 1] = "N";
tabsSetupState[tabsSetupState["Forced"] = 2] = "Forced";
})(tabsSetupState || (tabsSetupState = {}));
/*@ngInject*/
function formInput($compile, $rootScope, $filter, $data, $timeout, cssFrameworkService, formGenerator, formMarkupHelper) {
return {
restrict: 'EA',
link: function (scope, element, attrs) {
// generate markup for bootstrap forms
//
// Bootstrap 3
// Horizontal (default)
// <div class="form-group">
// <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
// <div class="col-sm-10">
// <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
// </div>
// </div>
//
// Vertical
// <div class="form-group">
// <label for="exampleInputEmail1">Email address</label>
// <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
// </div>
//
// Inline
// <div class="form-group">
// <label class="sr-only" for="exampleInputEmail2">Email address</label>
// <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Enter email">
// </div>
// Bootstrap 2
// Horizontal (default)
// <div class="control-group">
// <label class="control-label" for="inputEmail">Email</label>
// <div class="controls">
// <input type="text" id="inputEmail" placeholder="Email">
// </div>
// </div>
//
// Vertical
// <label>Label name</label>
// <input type="text" placeholder="Type something…">
// <span class="help-block">Example block-level help text here.</span>
//
// Inline
// <input type="text" class="input-small" placeholder="Email">
var subkeys = [];
var tabsSetup = tabsSetupState.N;
var generateInput = function (fieldInfo, modelString, isRequired, idString, options) {
function generateEnumInstructions() {
var enumInstruction;
if (angular.isArray(scope[fieldInfo.options])) {
enumInstruction = { repeat: fieldInfo.options, value: 'option' };
}
else if (scope[fieldInfo.options] && angular.isArray(scope[fieldInfo.options].values)) {
if (angular.isArray(scope[fieldInfo.options].labels)) {
enumInstruction = {
repeat: fieldInfo.options + '.values',
value: fieldInfo.options + '.values[$index]',
label: fieldInfo.options + '.labels[$index]'
};
}
else {
enumInstruction = {
repeat: fieldInfo.options + '.values',
value: fieldInfo.options + '.values[$index]'
};
}
}
else {
throw new Error('Invalid enumeration setup in field ' + fieldInfo.name);
}
return enumInstruction;
}
var nameString;
if (!modelString) {
var modelBase = (options.model || 'record') + '.';
modelString = modelBase;
if (options.subschema && fieldInfo.name.indexOf('.') !== -1) {
// Schema handling - need to massage the ngModel and the id
var compoundName = fieldInfo.name;
var root = options.subschemaroot;
var lastPart = compoundName.slice(root.length + 1);
if (options.index) {
modelString += root + '[' + options.index + '].' + lastPart;
idString = 'f_' + modelString.slice(modelBase.length).replace(/(\.|\[|\]\.)/g, '-');
}
else {
modelString += root;
if (options.subkey) {
idString = modelString.slice(modelBase.length).replace(/\./g, '-') + '-subkey' + options.subkeyno + '-' + lastPart;
modelString += '[' + '$_arrayOffset_' + root.replace(/\./g, '_') + '_' + options.subkeyno + '].' + lastPart;
}
else {
modelString += '[$index].' + lastPart;
idString = null;
nameString = compoundName.replace(/\./g, '-');
}
}
}
else {
modelString += fieldInfo.name;
}
}
var allInputsVars = formMarkupHelper.allInputsVars(scope, fieldInfo, options, modelString, idString, nameString);
var common = allInputsVars.common;
var value;
var requiredStr = (isRequired || fieldInfo.required) ? ' required' : '';
var enumInstruction;
switch (fieldInfo.type) {
case 'select':
if (fieldInfo.select2) {
common += 'class="fng-select2' + allInputsVars.formControl + allInputsVars.compactClass + allInputsVars.sizeClassBS2 + '"';
common += (fieldInfo.readonly ? ' readonly' : '');
common += (fieldInfo.required ? ' ng-required="true"' : '');
common += fieldInfo.add ? (' ' + fieldInfo.add + ' ') : '';
if (fieldInfo.select2.fngAjax) {
if (cssFrameworkService.framework() === 'bs2') {
value = '<div class="input-append">';
value += '<input ui-select2="' + fieldInfo.select2.fngAjax + '" ' + common + '>';
value += '<button class="btn" type="button" data-select2-open="' + idString + '" ng-click="openSelect2($event)"><i class="icon-search"></i></button>';
value += '</div>';
}
else {
value = '<div class="input-group">';
value += '<input ui-select2="' + fieldInfo.select2.fngAjax + '" ' + common + '>';
value += '<span class="input-group-addon' + allInputsVars.compactClass + '" data-select2-open="' + idString + '" ';
value += ' ng-click="openSelect2($event)"><i class="glyphicon glyphicon-search"></i></span>';
value += '</div>';
}
}
else if (fieldInfo.select2) {
value = '<input ui-select2="' + fieldInfo.select2.s2query + '" ' + common + '>';
}
}
else {
common += (fieldInfo.readonly ? 'disabled ' : '');
common += fieldInfo.add ? (' ' + fieldInfo.add + ' ') : '';
value = '<select ' + common + 'class="' + allInputsVars.formControl.trim() + allInputsVars.compactClass + allInputsVars.sizeClassBS2 + '" ' + requiredStr + '>';
if (!isRequired) {
value += '<option></option>';
}
if (angular.isArray(fieldInfo.options)) {
angular.forEach(fieldInfo.options, function (optValue) {
if (_.isObject(optValue)) {
value += '<option value="' + (optValue.val || optValue.id) + '">' + (optValue.label || optValue.text) + '</option>';
}
else {
value += '<option>' + optValue + '</option>';
}
});
}
else {
enumInstruction = generateEnumInstructions();
value += '<option ng-repeat="option in ' + enumInstruction.repeat + '"';
if (enumInstruction.label) {
value += ' value="{{' + enumInstruction.value + '}}"> {{ ' + enumInstruction.label + ' }} </option> ';
}
else {
value += '>{{' + enumInstruction.value + '}}</option> ';
}
}
value += '</select>';
}
break;
case 'link':
value = '<fng-link model="' + modelString + '" ref="' + fieldInfo.ref + '"';
if (fieldInfo.form) {
value += ' form="' + fieldInfo.form + '"';
}
if (fieldInfo.linkText) {
value += ' text="' + fieldInfo.linkText + '"';
}
if (fieldInfo.readonly) {
value += ' readonly="true"';
}
value += '></fng-link>';
break;
case 'radio':
value = '';
common += requiredStr + (fieldInfo.readonly ? ' disabled ' : ' ');
var separateLines = options.formstyle === 'vertical' || (options.formstyle !== 'inline' && !fieldInfo.inlineRadio);
if (angular.isArray(fieldInfo.options)) {
if (options.subschema) {
common = common.replace('name="', 'name="{{$index}}-');
}
angular.forEach(fieldInfo.options, function (optValue) {
value += '<input ' + common + 'type="radio"';
value += ' value="' + optValue + '">' + optValue;
if (separateLines) {
value += '<br />';
}
});
}
else {
var tagType = separateLines ? 'div' : 'span';
if (options.subschema) {
common = common.replace('$index', '$parent.$index').replace('name="', 'name="{{$parent.$index}}-');
}
enumInstruction = generateEnumInstructions();
value += '<' + tagType + ' ng-repeat="option in ' + enumInstruction.repeat + '"><input ' + common + ' type="radio" value="{{' + enumInstruction.value + '}}"> {{';
value += enumInstruction.label || enumInstruction.value;
value += ' }} </' + tagType + '> ';
}
break;
case 'checkbox':
common += requiredStr + (fieldInfo.readonly ? ' disabled ' : ' ');
if (cssFrameworkService.framework() === 'bs3') {
value = '<div class="checkbox"><input ' + common + 'type="checkbox"></div>';
}
else {
value = formMarkupHelper.generateSimpleInput(common, fieldInfo, options);
}
break;
default:
common += formMarkupHelper.addTextInputMarkup(allInputsVars, fieldInfo, requiredStr);
if (fieldInfo.type === 'textarea') {
if (fieldInfo.rows) {
if (fieldInfo.rows === 'auto') {
common += 'msd-elastic="\n" class="ng-animate" ';
}
else {
common += 'rows = "' + fieldInfo.rows + '" ';
}
}
if (fieldInfo.editor === 'ckEditor') {
common += 'ckeditor = "" ';
if (cssFrameworkService.framework() === 'bs3') {
allInputsVars.sizeClassBS3 = 'col-xs-12';
}
}
value = '<textarea ' + common + ' />';
}
else {
value = formMarkupHelper.generateSimpleInput(common, fieldInfo, options);
}
}
return formMarkupHelper.inputChrome(value, fieldInfo, options, allInputsVars);
};
var convertFormStyleToClass = function (aFormStyle) {
var result;
switch (aFormStyle) {
case 'horizontal':
result = 'form-horizontal';
break;
case 'vertical':
result = '';
break;
case 'inline':
result = 'form-inline';
break;
case 'horizontalCompact':
result = 'form-horizontal compact';
break;
default:
result = 'form-horizontal compact';
break;
}
return result;
};
var containerInstructions = function (info) {
var result = { before: '', after: '' };
if (typeof info.containerType === 'function') {
result = info.containerType(info);
}
else {
switch (info.containerType) {
case 'tab':
var tabNo = -1;
for (var i = 0; i < scope.tabs.length; i++) {
if (scope.tabs[i].title === info.title) {
tabNo = i;
break;
}
}
if (tabNo >= 0) {
result.before = '<uib-tab select="updateQueryForTab(\'' + info.title + '\')" heading="' + info.title + '"';
if (tabNo > 0) {
result.before += 'active="tabs[' + tabNo + '].active"';
}
result.before += '>';
result.after = '</uib-tab>';
}
else {
result.before = '<p>Error! Tab ' + info.title + ' not found in tab list</p>';
result.after = '';
}
break;
case 'tabset':
result.before = '<uib-tabset>';
result.after = '</uib-tabset>';
break;
case 'well':
result.before = '<div class="well">';
if (info.title) {
result.before += '<h4>' + info.title + '</h4>';
}
result.after = '</div>';
break;
case 'well-large':
result.before = '<div class="well well-lg well-large">';
result.after = '</div>';
break;
case 'well-small':
result.before = '<div class="well well-sm well-small">';
result.after = '</div>';
break;
case 'fieldset':
result.before = '<fieldset>';
if (info.title) {
result.before += '<legend>' + info.title + '</legend>';
}
result.after = '</fieldset>';
break;
case undefined:
break;
case null:
break;
case '':
break;
default:
result.before = '<div class="' + info.containerType + '">';
if (info.title) {
var titleLook = info.titleTagOrClass || 'h4';
if (titleLook.match(/h[1-6]/)) {
result.before += '<' + titleLook + '>' + info.title + '</' + titleLook + '>';
}
else {
result.before += '<p class="' + titleLook + '">' + info.title + '</p>';
}
}
result.after = '</div>';
break;
}
}
return result;
};
var handleField = function (info, options) {
var fieldChrome = formMarkupHelper.fieldChrome(scope, info, options);
var template = fieldChrome.template;
if (info.schema) {
var niceName = info.name.replace(/\./g, '_');
var schemaDefName = '$_schema_' + niceName;
scope[schemaDefName] = info.schema;
if (info.schema) {
//schemas (which means they are arrays in Mongoose)
// Check for subkey - selecting out one or more of the array
if (info.subkey) {
info.subkey.path = info.name;
scope[schemaDefName + '_subkey'] = info.subkey;
var subKeyArray = angular.isArray(info.subkey) ? info.subkey : [info.subkey];
for (var arraySel = 0; arraySel < subKeyArray.length; arraySel++) {
var topAndTail = containerInstructions(subKeyArray[arraySel]);
template += topAndTail.before;
template += processInstructions(info.schema, null, {
subschema: 'true',
formstyle: options.formstyle,
subkey: schemaDefName + '_subkey',
subkeyno: arraySel,
subschemaroot: info.name
});
template += topAndTail.after;
}
subkeys.push(info);
}
else {
if (options.subschema) {
console.log('Attempts at supporting deep nesting have been removed - will hopefully be re-introduced at a later date');
}
else {
template += '<div class="schema-head">' + info.label;
if (info.unshift) {
template += '<button id="unshift_' + info.id + '_btn" class="add-btn btn btn-default btn-xs btn-mini form-btn" ng-click="unshift(\'' + info.name + '\',$event)">' +
'<i class="' + formMarkupHelper.glyphClass() + '-plus"></i> Add</button>';
}
template += '</div>' +
'<div ng-form class="' + (cssFrameworkService.framework() === 'bs2' ? 'row-fluid ' : '') +
convertFormStyleToClass(info.formStyle) + '" name="form_' + niceName + '{{$index}}" class="sub-doc well" id="' + info.id + 'List_{{$index}}" ' +
' ng-repeat="subDoc in ' + (options.model || 'record') + '.' + info.name + ' track by $index">' +
' <div class="' + (cssFrameworkService.framework() === 'bs2' ? 'row-fluid' : 'row') + ' sub-doc">';
if (!info.noRemove || info.customSubDoc) {
template += ' <div class="sub-doc-btns">';
if (info.customSubDoc) {
template += info.customSubDoc;
}
if (!info.noRemove) {
template += '<button name="remove_' + info.id + '_btn" class="remove-btn btn btn-mini btn-default btn-xs form-btn" ng-click="remove(\'' + info.name + '\',$index,$event)">' +
'<i class="' + formMarkupHelper.glyphClass() + '-minus"></i> Remove</button>';
}
template += ' </div> ';
}
template += processInstructions(info.schema, false, {
subschema: 'true',
formstyle: info.formStyle,
model: options.model,
subschemaroot: info.name
});
template += ' </div>' +
'</div>';
if (!info.noAdd || info.customFooter) {
template += '<div class = "schema-foot">';
if (info.customFooter) {
template += info.customFooter;
}
if (!info.noAdd) {
template += '<button id="add_' + info.id + '_btn" class="add-btn btn btn-default btn-xs btn-mini form-btn" ng-click="add(\'' + info.name + '\',$event)">' +
'<i class="' + formMarkupHelper.glyphClass() + '-plus"></i> Add</button>';
}
template += '</div>';
}
}
}
}
}
else {
// Handle arrays here
var controlDivClasses = formMarkupHelper.controlDivClasses(options);
if (info.array) {
controlDivClasses.push('fng-array');
if (options.formstyle === 'inline') {
throw new Error('Cannot use arrays in an inline form');
}
template += formMarkupHelper.label(scope, info, info.type !== 'link', options);
template += formMarkupHelper.handleArrayInputAndControlDiv(generateInput(info, info.type === 'link' ? null : 'arrayItem.x', true, info.id + '_{{$index}}', options), controlDivClasses, info, options);
}
else {
// Single fields here
template += formMarkupHelper.label(scope, info, null, options);
if (options.required) {
console.log("********* Options required - found it ********");
}
template += formMarkupHelper.handleInputAndControlDiv(generateInput(info, null, options.required, info.id, options), controlDivClasses);
}
}
template += fieldChrome.closeTag;
return template;
};
var inferMissingProperties = function (info) {
// infer missing values
info.type = info.type || 'text';
if (info.id) {
if (typeof info.id === 'number' || (info.id[0] >= 0 && info.id <= '9')) {
info.id = '_' + info.id;
}
}
else {
info.id = 'f_' + info.name.replace(/\./g, '_');
}
info.label = (info.label !== undefined) ? (info.label === null ? '' : info.label) : $filter('titleCase')(info.name.split('.').slice(-1)[0]);
};
// var processInstructions = function (instructionsArray, topLevel, groupId) {
// removing groupId as it was only used when called by containerType container, which is removed for now
var processInstructions = function (instructionsArray, topLevel, options) {
var result = '';
if (instructionsArray) {
for (var anInstruction = 0; anInstruction < instructionsArray.length; anInstruction++) {
var info = instructionsArray[anInstruction];
if (anInstruction === 0 && topLevel && !options.schema.match(/$_schema_/) && typeof info.add !== 'object') {
info.add = info.add ? ' ' + info.add + ' ' : '';
if (info.add.indexOf('ui-date') === -1 && !options.noautofocus && !info.containerType) {
info.add = info.add + 'autofocus ';
}
}
var callHandleField = true;
if (info.directive) {
var directiveName = info.directive;
var newElement = '<' + directiveName + ' model="' + (options.model || 'record') + '"';
var thisElement = element[0];
inferMissingProperties(info);
for (var i = 0; i < thisElement.attributes.length; i++) {
var thisAttr = thisElement.attributes[i];
switch (thisAttr.nodeName) {
case 'class':
var classes = thisAttr.value.replace('ng-scope', '');
if (classes.length > 0) {
newElement += ' class="' + classes + '"';
}
break;
case 'schema':
var bespokeSchemaDefName = ('bespoke_' + info.name).replace(/\./g, '_');
scope[bespokeSchemaDefName] = angular.copy(info);
delete scope[bespokeSchemaDefName].directive;
newElement += ' schema="' + bespokeSchemaDefName + '"';
break;
default:
newElement += ' ' + thisAttr.nodeName + '="' + thisAttr.value + '"';
}
}
newElement += ' ';