-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathangular-schema-form-material.js
4310 lines (3641 loc) · 164 KB
/
angular-schema-form-material.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
/*!
* angular-schema-form-material
* @version 1.0.0-alpha.5
* @link https://github.com/json-schema-form/angular-schema-form-material
* @license MIT
* Copyright (c) 2016 JSON Schema Form
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("angular"), require("tv4"));
else if(typeof define === 'function' && define.amd)
define(["angular", "tv4"], factory);
else {
var a = typeof exports === 'object' ? factory(require("angular"), require("tv4")) : factory(root["angular"], root["tv4"]);
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_3__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(1);
__webpack_require__(4);
__webpack_require__(5);
__webpack_require__(6);
__webpack_require__(7);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
/*!
* angular-schema-form
* @version 1.0.0-alpha.2
* @link https://github.com/json-schema-form/angular-schema-form
* @license MIT
* Copyright (c) 2016 JSON Schema Form
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(true)
module.exports = factory(__webpack_require__(2), __webpack_require__(3));
else if(typeof define === 'function' && define.amd)
define(["angular", "tv4"], factory);
else {
var a = typeof exports === 'object' ? factory(require("angular"), require("tv4")) : factory(root["angular"], root["tv4"]);
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_8__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(1);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _angular = __webpack_require__(2);
var _angular2 = _interopRequireDefault(_angular);
var _builder = __webpack_require__(3);
var _builder2 = _interopRequireDefault(_builder);
var _decorators = __webpack_require__(4);
var _decorators2 = _interopRequireDefault(_decorators);
var _schemaForm = __webpack_require__(5);
var _schemaForm2 = _interopRequireDefault(_schemaForm);
var _jsonSchemaFormCore = __webpack_require__(6);
var _validator = __webpack_require__(7);
var _validator2 = _interopRequireDefault(_validator);
var _errors = __webpack_require__(9);
var _errors2 = _interopRequireDefault(_errors);
var _sfPath = __webpack_require__(10);
var _sfPath2 = _interopRequireDefault(_sfPath);
var _array = __webpack_require__(11);
var _array2 = _interopRequireDefault(_array);
var _changed = __webpack_require__(12);
var _changed2 = _interopRequireDefault(_changed);
var _field = __webpack_require__(13);
var _field2 = _interopRequireDefault(_field);
var _message = __webpack_require__(14);
var _message2 = _interopRequireDefault(_message);
var _newArray = __webpack_require__(15);
var _newArray2 = _interopRequireDefault(_newArray);
var _schemaForm3 = __webpack_require__(16);
var _schemaForm4 = _interopRequireDefault(_schemaForm3);
var _schemaValidate = __webpack_require__(17);
var _schemaValidate2 = _interopRequireDefault(_schemaValidate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Deps is sort of a problem for us, maybe in the future we will ask the user to depend
// on modules for add-ons
var deps = [];
try {
//This throws an expection if module does not exist.
_angular2.default.module('ngSanitize');
deps.push('ngSanitize');
} catch (e) {}
try {
//This throws an expection if module does not exist.
_angular2.default.module('ui.sortable');
deps.push('ui.sortable');
} catch (e) {}
try {
//This throws an expection if module does not exist.
_angular2.default.module('angularSpectrumColorpicker');
deps.push('angularSpectrumColorpicker');
} catch (e) {}
_angular2.default.module('schemaForm', deps)
// Providers and services
.provider('sfPath', _sfPath2.default).provider('sfBuilder', ['sfPathProvider', _builder2.default]).provider('schemaFormDecorators', ['$compileProvider', 'sfPathProvider', _decorators2.default]).provider('sfErrorMessage', _errors2.default).provider('schemaForm', ['sfPathProvider', _schemaForm2.default]).factory('sfSelect', function () {
return _jsonSchemaFormCore.select;
}).factory('sfValidator', _validator2.default)
// Directives
.directive('sfArray', ['sfSelect', 'schemaForm', 'sfValidator', 'sfPath', _array2.default]).directive('sfChanged', _changed2.default).directive('sfField', ['$parse', '$compile', '$http', '$templateCache', '$interpolate', '$q', 'sfErrorMessage', 'sfPath', 'sfSelect', _field2.default]).directive('sfMessage', ['$injector', 'sfErrorMessage', _message2.default]).directive('sfNewArray', ['sfSelect', 'sfPath', 'schemaForm', _newArray2.default]).directive('sfSchema', ['$compile', '$http', '$templateCache', '$q', 'schemaForm', 'schemaFormDecorators', 'sfSelect', 'sfPath', 'sfBuilder', _schemaForm4.default]).directive('schemaValidate', ['sfValidator', '$parse', 'sfSelect', _schemaValidate2.default]);
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = angular;
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (sfPathProvider) {
var SNAKE_CASE_REGEXP = /[A-Z]/g;
var snakeCase = function snakeCase(name, separator) {
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function (letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
};
var formId = 0;
var builders = {
sfField: function sfField(args) {
args.fieldFrag.firstChild.setAttribute('sf-field', formId);
// We use a lookup table for easy access to our form.
args.lookup['f' + formId] = args.form;
formId++;
},
ngModel: function ngModel(args) {
if (!args.form.key) {
return;
}
var key = args.form.key;
// Redact part of the key, used in arrays
// KISS keyRedaction is a number.
if (args.state.keyRedaction) {
key = key.slice(args.state.keyRedaction);
}
// Stringify key.
var modelValue;
if (!args.state.modelValue) {
var strKey = sfPathProvider.stringify(key).replace(/"/g, '"');
modelValue = args.state.modelName || 'model';
if (strKey) {
// Sometimes, like with arrays directly in arrays strKey is nothing.
modelValue += (strKey[0] !== '[' ? '.' : '') + strKey;
}
} else {
// Another builder, i.e. array has overriden the modelValue
modelValue = args.state.modelValue;
}
// Find all sf-field-value attributes.
// No value means a add a ng-model.
// sf-field-value="replaceAll", loop over attributes and replace $$value$$ in each.
// sf-field-value="attrName", replace or set value of that attribute.
var nodes = args.fieldFrag.querySelectorAll('[sf-field-model]');
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
var conf = n.getAttribute('sf-field-model');
if (!conf || conf === '') {
n.setAttribute('ng-model', modelValue);
} else if (conf === 'replaceAll') {
var attributes = n.attributes;
for (var j = 0; j < attributes.length; j++) {
if (attributes[j].value && attributes[j].value.indexOf('$$value') !== -1) {
attributes[j].value = attributes[j].value.replace(/\$\$value\$\$/g, modelValue);
}
}
} else {
var val = n.getAttribute(conf);
if (val && val.indexOf('$$value$$')) {
n.setAttribute(conf, val.replace(/\$\$value\$\$/g, modelValue));
} else {
n.setAttribute(conf, modelValue);
}
}
}
},
simpleTransclusion: function simpleTransclusion(args) {
var children = args.build(args.form.items, args.path + '.items', args.state);
args.fieldFrag.firstChild.appendChild(children);
},
// Patch on ngModelOptions, since it doesn't like waiting for its value.
ngModelOptions: function ngModelOptions(args) {
if (args.form.ngModelOptions && Object.keys(args.form.ngModelOptions).length > 0) {
args.fieldFrag.firstChild.setAttribute('ng-model-options', JSON.stringify(args.form.ngModelOptions));
}
},
transclusion: function transclusion(args) {
var transclusions = args.fieldFrag.querySelectorAll('[sf-field-transclude]');
if (transclusions.length) {
for (var i = 0; i < transclusions.length; i++) {
var n = transclusions[i];
// The sf-transclude attribute is not a directive,
// but has the name of what we're supposed to
// traverse. Default to `items`
var sub = n.getAttribute('sf-field-transclude') || 'items';
var items = args.form[sub];
if (items) {
var childFrag = args.build(items, args.path + '.' + sub, args.state);
n.appendChild(childFrag);
}
}
}
},
condition: function condition(args) {
// Do we have a condition? Then we slap on an ng-if on all children,
// but be nice to existing ng-if.
if (args.form.condition) {
var evalExpr = 'evalExpr(' + args.path + '.condition, { model: model, "arrayIndex": $index})';
if (args.form.key) {
var strKey = sfPathProvider.stringify(args.form.key);
var arrayDepth = args.form.key.filter(function (e) {
return e === '';
}).length;
var arrayIndices = arrayDepth > 1 ? Array(arrayDepth - 1).join('$parent.$parent.$parent.') + '$parent.$parent.$index,' : '';
for (var i = arrayDepth; i > 2; i--) {
arrayIndices += Array(i - 1).join('$parent.$parent.$parent.') + '$index,';
}
arrayIndices += '$index';
evalExpr = 'evalExpr(' + args.path + '.condition,{ model: model, "arrayIndex": $index, ' + '"arrayIndices": [' + arrayIndices + '],' + '"modelValue": model' + (strKey[0] === '[' ? '' : '.') + strKey + '})';
}
var children = args.fieldFrag.children || args.fieldFrag.childNodes;
for (var i = 0; i < children.length; i++) {
var child = children[i];
var ngIf = child.getAttribute('ng-if');
child.setAttribute('ng-if', ngIf ? '(' + ngIf + ') || (' + evalExpr + ')' : evalExpr);
}
}
},
array: function array(args) {
var items = args.fieldFrag.querySelector('[schema-form-array-items]');
if (items) {
var state = angular.copy(args.state);
state.keyRedaction = 0;
state.keyRedaction += args.form.key.length + 1;
// Special case, an array with just one item in it that is not an object.
// So then we just override the modelValue
if (args.form.schema && args.form.schema.items && args.form.schema.items.type && args.form.schema.items.type.indexOf('object') === -1 && args.form.schema.items.type.indexOf('array') === -1) {
var strKey = sfPathProvider.stringify(args.form.key).replace(/"/g, '"') + '[$index]';
state.modelValue = 'modelArray[$index]';
} else {
state.modelName = 'item';
}
// Flag to the builder that where in an array.
// This is needed for compatabiliy if a "old" add-on is used that
// hasn't been transitioned to the new builder.
state.arrayCompatFlag = true;
var childFrag = args.build(args.form.items, args.path + '.items', state);
items.appendChild(childFrag);
}
},
numeric: function numeric(args) {
var inputFrag = args.fieldFrag.querySelector('input');
var maximum = args.form.maximum || false;
var exclusiveMaximum = args.form.exclusiveMaximum || false;
var minimum = args.form.minimum || false;
var exclusiveMinimum = args.form.exclusiveMinimum || false;
var multipleOf = args.form.multipleOf || false;
if (inputFrag) {
if (multipleOf !== false) {
inputFrag.setAttribute('step', multipleOf);
};
if (maximum !== false) {
if (exclusiveMaximum !== false && multipleOf !== false) {
maximum = maximum - multipleOf;
};
inputFrag.setAttribute('max', maximum);
};
if (minimum !== false) {
if (exclusiveMinimum !== false && multipleOf !== false) {
minimum = minimum + multipleOf;
};
inputFrag.setAttribute('min', minimum);
};
};
}
};
this.builders = builders;
var stdBuilders = [builders.sfField, builders.ngModel, builders.ngModelOptions, builders.condition];
this.stdBuilders = stdBuilders;
this.$get = ['$templateCache', 'schemaFormDecorators', 'sfPath', function ($templateCache, schemaFormDecorators, sfPath) {
var checkForSlot = function checkForSlot(form, slots) {
// Finally append this field to the frag.
// Check for slots
if (form.key) {
var slot = slots[sfPath.stringify(form.key)];
if (slot) {
while (slot.firstChild) {
slot.removeChild(slot.firstChild);
}
return slot;
}
}
};
var _build = function _build(items, decorator, templateFn, slots, path, state, lookup) {
state = state || {};
lookup = lookup || Object.create(null);
path = path || 'schemaForm.form';
var container = document.createDocumentFragment();
items.reduce(function (frag, f, index) {
// Sanity check.
if (!f.type) {
return frag;
}
var field = decorator[f.type] || decorator['default'];
if (!field.replace) {
// Backwards compatability build
var n = document.createElement(snakeCase(decorator.__name, '-'));
if (state.arrayCompatFlag) {
n.setAttribute('form', 'copyWithIndex($index)');
} else {
n.setAttribute('form', path + '[' + index + ']');
}
(checkForSlot(f, slots) || frag).appendChild(n);
} else {
var tmpl;
// Reset arrayCompatFlag, it's only valid for direct children of the array.
state.arrayCompatFlag = false;
// TODO: Create a couple of testcases, small and large and
// measure optmization. A good start is probably a
// cache of DOM nodes for a particular template
// that can be cloned instead of using innerHTML
var div = document.createElement('div');
var template = templateFn(f, field) || templateFn(f, decorator['default']);
div.innerHTML = template;
// Move node to a document fragment, we don't want the div.
tmpl = document.createDocumentFragment();
while (div.childNodes.length > 0) {
tmpl.appendChild(div.childNodes[0]);
}
// Possible builder, often a noop
var args = {
fieldFrag: tmpl,
form: f,
lookup: lookup,
state: state,
path: path + '[' + index + ']',
// Recursive build fn
build: function build(items, path, state) {
return _build(items, decorator, templateFn, slots, path, state, lookup);
}
};
// Let the form definiton override builders if it wants to.
var builderFn = f.builder || field.builder;
// Builders are either a function or a list of functions.
if (typeof builderFn === 'function') {
builderFn(args);
} else {
builderFn.forEach(function (fn) {
fn(args);
});
}
// Append
(checkForSlot(f, slots) || frag).appendChild(tmpl);
}
return frag;
}, container);
return container;
};
return {
/**
* Builds a form from a canonical form definition
*/
build: function build(form, decorator, slots, lookup) {
return _build(form, decorator, function (form, field) {
if (form.type === 'template') {
return form.template;
}
return $templateCache.get(field.template);
}, slots, undefined, undefined, lookup);
},
builder: builders,
stdBuilders: stdBuilders,
internalBuild: _build
};
}];
};
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function ($compileProvider, sfPathProvider) {
var defaultDecorator = '';
var decorators = {};
// Map template after decorator and type.
var templateUrl = function templateUrl(name, form) {
//schemaDecorator is alias for whatever is set as default
if (name === 'sfDecorator') {
name = defaultDecorator;
}
var decorator = decorators[name];
if (decorator[form.type]) {
return decorator[form.type].template;
}
//try default
return decorator['default'].template;
};
/**************************************************
* DEPRECATED *
* The new builder and sf-field is preferred, but *
* we keep this in during a transitional period *
* so that add-ons that don't use the new builder *
* works. *
**************************************************/
//TODO: Move to a compatability extra script.
var createDirective = function createDirective(name) {
$compileProvider.directive(name, ['$parse', '$compile', '$http', '$templateCache', '$interpolate', '$q', 'sfErrorMessage', 'sfPath', 'sfSelect', function ($parse, $compile, $http, $templateCache, $interpolate, $q, sfErrorMessage, sfPath, sfSelect) {
return {
restrict: 'AE',
replace: false,
transclude: false,
scope: true,
require: '?^sfSchema',
link: function link(scope, element, attrs, sfSchema) {
//The ngModelController is used in some templates and
//is needed for error messages,
scope.$on('schemaFormPropagateNgModelController', function (event, ngModel) {
event.stopPropagation();
event.preventDefault();
scope.ngModel = ngModel;
});
//Keep error prone logic from the template
scope.showTitle = function () {
return scope.form && scope.form.notitle !== true && scope.form.title;
};
scope.listToCheckboxValues = function (list) {
var values = {};
_angular2.default.forEach(list, function (v) {
values[v] = true;
});
return values;
};
scope.checkboxValuesToList = function (values) {
var lst = [];
_angular2.default.forEach(values, function (v, k) {
if (v) {
lst.push(k);
}
});
return lst;
};
scope.buttonClick = function ($event, form) {
if (_angular2.default.isFunction(form.onClick)) {
form.onClick($event, form);
} else if (_angular2.default.isString(form.onClick)) {
if (sfSchema) {
//evaluating in scope outside of sfSchemas isolated scope
sfSchema.evalInParentScope(form.onClick, { '$event': $event, form: form });
} else {
scope.$eval(form.onClick, { '$event': $event, form: form });
};
};
};
/**
* Evaluate an expression, i.e. scope.$eval
* but do it in sfSchemas parent scope sf-schema directive is used
*
* @param {string} expression
* @param {Object} locals (optional)
* @return {Any} the result of the expression
*/
scope.evalExpr = function (expression, locals) {
if (sfSchema) {
//evaluating in scope outside of sfSchemas isolated scope
return sfSchema.evalInParentScope(expression, locals);
}
return scope.$eval(expression, locals);
};
/**
* Evaluate an expression, i.e. scope.$eval
* in this decorators scope
*
* @param {string} expression
* @param {Object} locals (optional)
* @return {Any} the result of the expression
*/
scope.evalInScope = function (expression, locals) {
if (expression) {
return scope.$eval(expression, locals);
}
};
/**
* Interpolate the expression.
* Similar to `evalExpr()` and `evalInScope()`
* but will not fail if the expression is
* text that contains spaces.
*
* Use the Angular `{{ interpolation }}`
* braces to access properties on `locals`.
*
* @param {string} expression The string to interpolate.
* @param {Object} locals (optional) Properties that may be accessed in the
* `expression` string.
* @return {Any} The result of the expression or `undefined`.
*/
scope.interp = function (expression, locals) {
return expression && $interpolate(expression)(locals);
};
//This works since we ot the ngModel from the array or the schema-validate directive.
scope.hasSuccess = function () {
if (!scope.ngModel) {
return false;
}
if (scope.options && scope.options.pristine && scope.options.pristine.success === false) {
return scope.ngModel.$valid && !scope.ngModel.$pristine && !scope.ngModel.$isEmpty(scope.ngModel.$modelValue);
} else {
return scope.ngModel.$valid && (!scope.ngModel.$pristine || !scope.ngModel.$isEmpty(scope.ngModel.$modelValue));
}
};
scope.hasError = function () {
if (!scope.ngModel) {
return false;
}
return scope.ngModel.$invalid && !scope.ngModel.$pristine;
};
/**
* DEPRECATED: use sf-messages instead.
* Error message handler
* An error can either be a schema validation message or a angular js validtion
* error (i.e. required)
*/
scope.errorMessage = function (schemaError) {
return sfErrorMessage.interpolate(schemaError && schemaError.code + '' || 'default', scope.ngModel && scope.ngModel.$modelValue || '', scope.ngModel && scope.ngModel.$viewValue || '', scope.form, scope.options && scope.options.validationMessage);
};
// Rebind our part of the form to the scope.
var once = scope.$watch(attrs.form, function (form) {
if (form) {
// Workaround for 'updateOn' error from ngModelOptions
// see https://github.com/Textalk/angular-schema-form/issues/255
// and https://github.com/Textalk/angular-schema-form/issues/206
form.ngModelOptions = form.ngModelOptions || {};
scope.form = form;
//ok let's replace that template!
//We do this manually since we need to bind ng-model properly and also
//for fieldsets to recurse properly.
var templatePromise;
// type: "template" is a special case. It can contain a template inline or an url.
// otherwise we find out the url to the template and load them.
if (form.type === 'template' && form.template) {
templatePromise = $q.when(form.template);
} else {
var url = form.type === 'template' ? form.templateUrl : templateUrl(name, form);
templatePromise = $http.get(url, { cache: $templateCache }).then(function (res) {
return res.data;
});
}
templatePromise.then(function (template) {
if (form.key) {
var key = form.key ? sfPathProvider.stringify(form.key).replace(/"/g, '"') : '';
template = template.replace(/\$\$value\$\$/g, 'model' + (key[0] !== '[' ? '.' : '') + key);
}
element.html(template);
// Do we have a condition? Then we slap on an ng-if on all children,
// but be nice to existing ng-if.
if (form.condition) {
var evalExpr = 'evalExpr(form.condition,{ model: model, "arrayIndex": arrayIndex})';
if (form.key) {
evalExpr = 'evalExpr(form.condition, {' + 'model: model, "arrayIndex": arrayIndex, "modelValue": model' + sfPath.stringify(form.key) + '})';
}
_angular2.default.forEach(element.children(), function (child) {
var ngIf = child.getAttribute('ng-if');
child.setAttribute('ng-if', ngIf ? '(' + ngIf + ') || (' + evalExpr + ')' : evalExpr);
});
}
$compile(element.contents())(scope);
});
// Where there is a key there is probably a ngModel
if (form.key) {
// It looks better with dot notation.
scope.$on('schemaForm.error.' + form.key.join('.'), function (event, error, validationMessage, validity, formName) {
// validationMessage and validity are mutually exclusive
formName = validity;
if (validationMessage === true || validationMessage === false) {
validity = validationMessage;
validationMessage = undefined;
};
// If we have specified a form name, and this model is not within
// that form, then leave things be.
if (formName != undefined && scope.ngModel.$$parentForm.$name !== formName) {
return;
};
if (scope.ngModel && error) {
if (scope.ngModel.$setDirty) {
scope.ngModel.$setDirty();
} else {
// FIXME: Check that this actually works on 1.2
scope.ngModel.$dirty = true;
scope.ngModel.$pristine = false;
};
// Set the new validation message if one is supplied
// Does not work when validationMessage is just a string.
if (validationMessage) {
if (!form.validationMessage) {
form.validationMessage = {};
}
form.validationMessage[error] = validationMessage;
}
scope.ngModel.$setValidity(error, validity === true);
if (validity === true) {
// Re-trigger model validator, that model itself would be re-validated
scope.ngModel.$validate();
// Setting or removing a validity can change the field to believe its valid
// but its not. So lets trigger its validation as well.
scope.$broadcast('schemaFormValidate');
}
}
});
// Clean up the model when the corresponding form field is $destroy-ed.
// Default behavior can be supplied as a globalOption, and behavior can be overridden
// in the form definition.
scope.$on('$destroy', function () {
// If the entire schema form is destroyed we don't touch the model
if (!scope.externalDestructionInProgress) {
var destroyStrategy = form.destroyStrategy || scope.options && scope.options.destroyStrategy || 'remove';
// No key no model, and we might have strategy 'retain'
if (form.key && destroyStrategy !== 'retain') {
// Get the object that has the property we wan't to clear.
var obj = scope.model;
if (form.key.length > 1) {
obj = sfSelect(form.key.slice(0, form.key.length - 1), obj);
}
// We can get undefined here if the form hasn't been filled out entirely
if (obj === undefined) {
return;
}
// Type can also be a list in JSON Schema
var type = form.schema && form.schema.type || '';
// Empty means '',{} and [] for appropriate types and undefined for the rest
if (destroyStrategy === 'empty' && type.indexOf('string') !== -1) {
obj[form.key.slice(-1)] = '';
} else if (destroyStrategy === 'empty' && type.indexOf('object') !== -1) {
obj[form.key.slice(-1)] = {};
} else if (destroyStrategy === 'empty' && type.indexOf('array') !== -1) {
obj[form.key.slice(-1)] = [];
} else if (destroyStrategy === 'null') {
obj[form.key.slice(-1)] = null;
} else {
delete obj[form.key.slice(-1)];
}
}
}
});
}
once();
}
});
}
};
}]);
};
var createManualDirective = function createManualDirective(type, templateUrl, transclude) {
transclude = _angular2.default.isDefined(transclude) ? transclude : false;
$compileProvider.directive('sf' + _angular2.default.uppercase(type[0]) + type.substr(1), function () {
return {
restrict: 'EAC',
scope: true,
replace: true,
transclude: transclude,
template: '<sf-decorator form="form"></sf-decorator>',
link: function link(scope, element, attrs) {
var watchThis = {
'items': 'c',
'titleMap': 'c',
'schema': 'c'
};
var form = { type: type };
var once = true;
_angular2.default.forEach(attrs, function (value, name) {
if (name[0] !== '$' && name.indexOf('ng') !== 0 && name !== 'sfField') {
var updateForm = function updateForm(val) {
if (_angular2.default.isDefined(val) && val !== form[name]) {
form[name] = val;
//when we have type, and if specified key we apply it on scope.
if (once && form.type && (form.key || _angular2.default.isUndefined(attrs.key))) {
scope.form = form;
once = false;
}
}
};
if (name === 'model') {
//"model" is bound to scope under the name "model" since this is what the decorators
//know and love.
scope.$watch(value, function (val) {
if (val && scope.model !== val) {
scope.model = val;
}
});
} else if (watchThis[name] === 'c') {
//watch collection
scope.$watchCollection(value, updateForm);
} else {
//$observe
attrs.$observe(name, updateForm);
}
}
});
}
};
});
};
/**
* DEPRECATED: use defineDecorator instead.
* Create a decorator directive and its sibling "manual" use decorators.
* The directive can be used to create form fields or other form entities.
* It can be used in conjunction with <schema-form> directive in which case the decorator is
* given it's configuration via a the "form" attribute.
*
* ex. Basic usage
* <sf-decorator form="myform"></sf-decorator>
**
* @param {string} name directive name (CamelCased)
* @param {Object} templates, an object that maps "type" => "templateUrl"
*/
this.createDecorator = function (name, templates) {
//console.warn('schemaFormDecorators.createDecorator is DEPRECATED, use defineDecorator instead.');
decorators[name] = { '__name': name };
_angular2.default.forEach(templates, function (url, type) {
decorators[name][type] = { template: url, replace: false, builder: [] };
});
if (!decorators[defaultDecorator]) {
defaultDecorator = name;
}
createDirective(name);
};
/**
* Define a decorator. A decorator is a set of form types with templates and builder functions
* that help set up the form.
*
* @param {string} name directive name (CamelCased)
* @param {Object} fields, an object that maps "type" => `{ template, builder, replace}`.
attributes `builder` and `replace` are optional, and replace defaults to true.
`template` should be the key of the template to load and it should be pre-loaded
in `$templateCache`.
`builder` can be a function or an array of functions. They will be called in
the order they are supplied.
`replace` (DEPRECATED) is for backwards compatability. If false the builder
will use the "old" way of building that form field using a <sf-decorator>
directive.
*/
this.defineDecorator = function (name, fields) {
decorators[name] = { '__name': name }; // TODO: this feels like a hack, come up with a better way.
_angular2.default.forEach(fields, function (field, type) {
field.builder = field.builder || [];
field.replace = _angular2.default.isDefined(field.replace) ? field.replace : true;
decorators[name][type] = field;
});
if (!decorators[defaultDecorator]) {
defaultDecorator = name;
}
createDirective(name);
};
/**
* DEPRECATED
* Creates a directive of a decorator
* Usable when you want to use the decorators without using <schema-form> directive.
* Specifically when you need to reuse styling.
*
* ex. createDirective('text','...')
* <sf-text title="foobar" model="person" key="name" schema="schema"></sf-text>
*
* @param {string} type The type of the directive, resulting directive will have sf- prefixed
* @param {string} templateUrl
* @param {boolean} transclude (optional) sets transclude option of directive, defaults to false.
*/
this.createDirective = createManualDirective;
/**
* DEPRECATED
* Same as createDirective, but takes an object where key is 'type' and value is 'templateUrl'
* Useful for batching.