-
Notifications
You must be signed in to change notification settings - Fork 1
/
meteor-flexiforms.js
887 lines (781 loc) · 37 KB
/
meteor-flexiforms.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
/**
* Created by pavlovich on 4/14/14.
*/
/**
* Given a key representing the 'stock' name of a template (meteor/spacebars template, that is), check to see if the
* user of the framework has registered a 'replacement' template to use in place of the 'stock' one. If so, return
* the replacement template. Otherwise, return the corresponding stock template.
*/
var getTemplateForKey = function(key){
var templateKey = ngMeteorForms.templateRegistry[key] ? ngMeteorForms.templateRegistry[key] : key;
var result = Package.templating.Template[templateKey];
// TODO :: Not sure why this is a to do? Maybe we need to externalize the error message? Dunno. ::: console.log("Couldn't find a template with name: '" + templateKey + "' which you indicated should override the framework template named '" + key + "'. Using the framework template as a fallback");
return result ? result : Package.templating.Template[key];
};
////////////////////////////////////////////////////////////////////
/**
* Register global template helpers
*/
////////////////////////////////////////////////////////////////////
/**
* Register a helper function which returns the template to render for the element currently being processed.
* Specifically, return a field group template if the current element represents a nested model. This is indicated by
* the current element having a 'type' attribute value which matches the name of an existing FlexiType document.
* Otherwise, return a generic field element template.
*/
Package.ui.UI.registerHelper("mffAutoformElementTemplate", function () {
var templateName = '_mffAutoformField';
if(!this.isCollection()){
if(FlexiSpecs.isDefined(this.getTypeName())){
templateName = '_mffAutoformFieldGroup';
}
}
return getTemplateForKey(templateName);
});
/**
* If the current element has 'inline' set to true, output the string 'inline' to be output as a marker attribute for the current element.
* Otherwise, output an empty string.
*/
Package.ui.UI.registerHelper("mffInline", function () {
if(this.inline){
return " inline";
}else{
return "";
}
});
////////////////////////////////////////////////////////////////////
/**
* Define 'helper' functions used by the directives defined below.
*/
////////////////////////////////////////////////////////////////////
/**
* As we prepare the fields of a flexispec to be used by the framework, we attach this function as the value of the
* 'getTemplate' attribute. This allows us to later call this function in order to determine which template we should
* use to replace the generated field element with a real html input element or radio group. We assign this function
*
*/
var fieldGetTemplate = function () {
if (this.template) {
if (typeof this.template == 'string') {
return this.template;
} else {
if (typeof this.template == 'function') {
return this.template.call(this);
}
if (this.template.name) {
return this.template.name;
}
}
}
var result = null;
if (!this.isCollection()) {
result = ngMeteorForms.templateMapping[this.getTypeName()];
if (result) {
if (typeof result == 'function') {
return result.call(this);
} else {
return result;
}
}
}else{
if(this.isCollection()){
result = ngMeteorForms.templateMapping['collection'];
if (result) {
if (typeof result == 'function') {
return result.call(this);
} else {
return result;
}
}
}
}
return this.getTypeName() ? this.getTypeName() : null;
};
/**
* Given a 'dataId' representing the full 'path' to a given field definition, replace the first component of this path
* with the string 'model'. For example, assume you have a 'person' flexispec which has an 'address' field of type 'address'.
* Assume that you have another flexispec named 'address' which has a 'region' field of type 'region'. And then suppose
* that you have another flexispec named 'region' which has a 'zipCode' field of type 'text'. Then, if you were looking
* at the zipCode field for a person's address, its 'full path' would be 'person.address.region.zipCode'. In this case,
* this function would return 'model.address.region.zipCode'.
*
* This allows us to assume a single, uniformly named attribute defined on our directives' scopes named 'model' exists
* and holds our data model which is used to populate our form.
*
* TODO This works well for single-model-single-form scenarios. For more complex scenarios, perhaps we need to explore having a model on the scope which has top level attributes named 'person' or 'registration' etc which each hold a given document of that type. This would allow forms to 'operate' on more than one model at a time.
*/
var getModelId = function(dataId) {
var res = 'model';
var tempId = dataId.split('.');
_.each(_.rest(tempId), function(ele){
res = res + '.' + ele;
});
return res;
};
/**
* Given a 'fieldId', such as 'person.address.region.zipCode' (from the comment to the 'getModelId' function defined above),
* return the actual field specification by traversing the flexispecs implied by the components of that fieldId.
*
* In more detail, it is assumed that the first component is the name of a top-level flexispec, in this case, 'person'.
* Furthermore, it is assumed that the 'person' flexispec has a field named 'address'. Since 'address' is not the last
* component in the fieldId, it is further assumed that the 'address' field has a type attribute, the value of which is
* the name of yet another flexispec and this new flexispec has a field named 'region'. Since 'region' is not the final
* component of the fieldId, it is then assumed that the 'region' field definition has a 'type' atribute whose value is
* the name of yet another flexispec which, itself, has a field with name 'zipCode'. Since 'zipCode' is the last
* component of the fieldId, it is assumed that it is a 'primitive' type ('text', 'boolean', 'single', 'multi', etc).
*/
getField = function (fieldId) {
var attributeMap = fieldId.split('.');
var typeName = _.first(attributeMap);
var type = FlexiSpecs.createDummy(typeName);
_.each(_.initial(attributeMap), function(attributeName){
//TODO clean this up by moving the "getTypeForFieldNamed(xxx)" into the prototype for type.
var theField = type.getField(attributeName);
typeName = type.getField(attributeName).getTypeName();
type = FlexiSpecs.findByName(typeName);
if(!type){return null};
});
var field = type.getField(_.last(attributeMap));
field.getTemplateName = fieldGetTemplate;
return field;
};
/**
* Return a template suitable to use in replacing the supplied <element> and accompanying <attributes>.
*
* In more detail, we take the supplied element and, since it is a jQuery-wrapped element, we extract the
* 'real' element using 'element.context'. Next, we get the element's local name (which is just the name of the element
* as it appears right after the '<' in the HTML notation for that element). We then convert that element name to
* camel case (since it is most likely in x-y-z format). This name is assumed to be the name of the default,
* package-provided template associated with the given element name. We then check to see if the package user has
* registered their own custom replacement template to use in place of our 'stock' template. This is done using the
* 'getTemplateForKey' function which checks the internal registry which maps standard element names to the name of the
* template to use when replacing those elements. Next we grab the template associated with whatever template name we
* have arrived at thus far. We then check to see if that template defines a method named 'mffTemplate'. If so, it is
* assumed that this function will act as an 'override' function and we will call that function, passing the same
* arguments that we received as parameters to our own calling. We expect this override function to return the final
* template for use to use in replacing the current element. If no override function is defined for the arrived at
* template, we just return the template we had arrived at prior to this last check.
*
* Note that users of the framework can define the same 'override' function on their own templates which they register
* as 'overrides' to their own 'stock' templates. Their override functions will be called at this point just as they are called
* with the package-supplied templates. This feature is used to allow users of the package to dynamically replace the 'stock'
* field template with a template of the package consumer's choice.
*/
var getMffElementTemplate = function(element, attributes){
var templateName = element.context.localName.toCamel();
var template = getTemplateForKey(templateName);
template = (template.mffTemplate && typeof template.mffTemplate == 'function') ? template.mffTemplate(element, attributes) : template;
return template;
};
/**
* Replace the supplied <element> in the DOM with the result of fully rendering the template which has been registered as
* the replacement for that supplied <element>, qualified, where appropriate, by the values of its <attributes>.
*
* In detail, we first obtain the appropriate (meteor/spacebars) template, then create an appropriate object to act as
* our context for the rendering of that template and then render that template in the context of that object.
* Then we replace the <element> in the DOM with the result of that rendering.
*
* Note that we say 'fully rendering' here because we don't simply render the template in the 'meteor way'.
* We do that, but then the result of that initial meteor rendering is then evaluated by Angular which applies any
* appropriate directives or filters. Of course, applying those directives could result in additional DOM changes which call for
* some of the new elements to be, in turn, replaced by further meteor template rendering the results of each of which
* themselves will be processed by angular themselves possibly resulting in yet another round. And so on. Once all possible
* renderings by both meteor/spacebars as well as Angular have completed recursively, we add that final result into the
* DOM after the original <element> and then remove the original <element> from the DOM.
*/
var expandElement = function(element, attributes) {
var template = getMffElementTemplate(element, attributes);
var context = template.createContext(element, attributes);
var theElement = element[0];
var theParent = theElement.parentNode;
if(theParent) {
Blaze.renderWithData(template, context, theParent, theElement);
element.remove();
}
};
/**
* Set the value of the 'formName' attribute of the supplied 'receiver' (typically, a field definition) to be
* the name of the 'closest' form element (ancestor-wise) to the supplied element.
*/
var setFormName = function(receiver, element){
var formName = null;
try {
var form = $(element).closest('ng-form').get(0);
formName = form.getAttribute('name');
}catch(e){
console.log("Unable to find a form enclosing the given element: " + element);
}
receiver.formName = formName;
};
/**
* Set the 'field' attribute of <scope> to hold a representation of the field object obtained by traversing the appropriate
* path through the graph of defined Flexispecs as specified by the value of the supplied 'id' attribute which may be
* held in either the 'modelId' attribute (in the case of this being our top-level field definition for the form)
* or the 'id' attribute (in all other cases). In the case where we are dealing with a field specifiying a collection-type
* value, as indicated by <attributes> having an 'unwrapped' value set to true, we then hold a deep copy as the
* field object will serve as we need to modify the type attribute to not be an array but, rather, whatever single element
* the original array contained (e.g. 'email' as opposed to ['email']) and we don't want to make that change in the original.
*/
var setField = function(scope, attributes){
var modelId = (attributes.id == 'model') ? attributes.modelId : attributes.id;
var theField = getField(modelId);
if(theField.isCollection() && attributes.unwrapped){
theField = owl.deepCopy(theField);
theField.holdsCollection = false;
}
scope.field = theField;
return theField;
};
/**
* Operating on the supplied object, <obj>, (typically a model object being edited in a given form), return the value
* of the attribute specified by the given <path> after, optionally, setting the value of that attribute to a supplied value.
*
* In detail, For the supplied object, <obj>, follow down the supplied <path> (a dot-separated chain of attributes names).
* When reaching the end of that chain, if <overwrite> is true, set the attribute's value to <value>. Otherwise,
* check to see if a value already has been set there. If so, do not change it. Finally, return the then current value
* of the specified attribute (after setting it to the new value if so called for).
* @param obj The base object on which to set an attribute's value
* @param path The path or chain of attribute names as a dot-separated list which leads to the attribute whose value you wish to set.
* @param value The value to set for the attribute.
* @param overwrite If true, set the value for the attribute regardless of whether a value has already been set. If false, only set a value if one has not been already set.
* @returns The resulting value stored in the attribute in question (could be the previously set value or the newly provided one depending on options. Could be null.
*/
var _setValueOfPath = function(obj, path, value, overwrite){
var result = value;
var pathComponents = path.split('.');
_.reduce(pathComponents,
function(memo, key){
if(this == key){
if(memo[key]){
if(overwrite){
memo[key] = value;
}
result = memo[key];
return result;
}
memo[key] = value;
return value;
}else{
if(memo[key]){
return memo[key]
}else{
memo[key] = {};
return memo[key]
}
}
}, obj, _.last(pathComponents));
return result;
};
/**
* We are going to process an angular directive against a dynamically generated template. Prepare the <scope> appropriately.
*
* In detail, set a field attribute to hold the field object as specified by the 'id' in the supplied <attributes>.
* If that field represents a collection of things we can edit in-line, we set the scope's 'collection' attribute to
* point to the current collection of objects held by the model being edited (or an empty array, if not yet initialized).
* Also, set the 'myIndex' attribute to null (indicating that we are currently not actually editing any of the objects
* in that nested collection attribute). Also, in this case, we must decide if the collection of 'things' we are editing
* is composed of primitive values (strings, dates, numbers, etc) or other complex model objects of a particular type.
* If the type for the field is specified as an array of something which is the name of an existing Flexispec, then we
* know we have a collection of complex model objects not of primitive objects.
*
* If field type is not an array, but is either 'single' or 'multi', then the field represents either a single or
* multiple selection from a collection of pre-defined 'things'. That being the case, we then determine if the collection
* of "things" we will be picking one or more items from is from a hard-coded collection specified literally in the
* relevant Flexispec (as indicated by the 'collectionName' attribute holding the value 'string'), from a specific
* collection of Fleximodel instances (indicated by the field's collectionName attribute being set to the name of an
* existing Flexispec) or from a collection defined in the Global name space (as indicated by the collectionName being
* set to the name of a defined global value. In any case, once the collection is found, set the scope's 'options'
* attribute to point to that collection.
*/
var updateScope = function(scope, attributes){
var field = setField(scope, attributes);
if(_.isNull(field) || _.isUndefined(field)){
// No field associated with a non-data-oriented element (like a DIV). Do nothing to the scope.
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> should not get here")
}else {
if(field.isCollection()){
scope.collection = _setValueOfPath(scope, getModelId(attributes.id), [], false);
scope.myIndex = null;
//TODO singleMode should be renamed to something like 'editItemInCollectionMode' (which is an accurate description when this is true vs. 'editWholeCollectionMode' which is accurate when the current variable is false.
scope.singleMode = !field.referencesValidModel();
}else{
field.initializeCollection();
}
scope.options = field.getMyCollection();
}
};
/**
* Answer the value stored in the Global variable with the supplied name. If on the client, look for the global on the
* 'window' object, otherwise look in the delegate (this). This function is used to 'find' or 'discover' existing
* meteor/mongo collections/subscriptions and is used in creating context objects used when rendering meteor templates.
*/
var getGlobal = function(globalName){
var self = this;
if(Meteor.isClient){
self = window;
}
var result = self[globalName];
return result ? result : undefined;
};
/**
* Return a new base context which is the starting point for all contexts used by the framework when rendering meteor
* spacebars templates. This function creates a new context object which is populated with the attribute values
* supplied in the 'attrs' parameter + a new attribute, 'contents', which has the value of the innerHTML of the original
* element.
*/
var createNonFieldContext = function(element, attrs){
var context = owl.deepCopy(attrs);
context.contents = element.context.innerHTML;
return context;
};
/**
* Construct a context object based on a field definition for use in rendering field replacement templates.
*
* In detail, we retrieve an appropriate field object and clone it to act as our model. We then augment its attributes
* with some additional data based on the attributes of the element we are replacing and then return the updated,
* cloned field object.
*/
var getFieldAsContextObject = function(element, attrs){
var modelId = attrs.id;
if(modelId == 'model'){
modelId = attrs.modelId;
}
var field = getField(modelId);
if(field) {
field = owl.deepCopy(field);
setFormName(field, element);
if(field.isCollection && attrs.unwrapped){
field.unwrapped = true;
field.holdsCollection = false;
}
if(field.unwrapped && !FlexiSpecs.isDefined(field.getTypeName())){
field.modelId = "model[myIndex]"
}else{
field.modelId = getModelId(attrs.id);
}
field.id = modelId;
field.fieldId = attrs.id.replace(/\./g,'');
field.inline = attrs.inline;
field.showLabel = (field.inline || field.unwrapped) ? false : true;
}else{
console.log("unable to find field with id: " + modelId);
}
field.validateCollectionInfo();
return field;
};
/**
* Define compile pre-link and controller functions for mffField directive
*/
var mffFieldController = function($scope){
var self = $scope;
var setFocusToNewCollectionModelFirstEntryField = function($event){
var element = $($event.currentTarget).closest('.mff-collection-field').find('.mff-new-model').find('input:not([type=hidden]):first');
setTimeout(function(){
element.focus();
}, 1);
};
$scope.isSelectedRow = function(index){
return index == this.myIndex;
};
$scope.isInvalidRow = function(index){
var errors = {};
var myType = self.field.getTypeName();
if(!myType){
return true;
}
var doc = this.collection && this.collection[index] ? this.collection[index] : null;
var mySpec = FlexiSpecs.findByName(myType);
if(mySpec) {
var spec = (myType) ? mySpec : null;
if (!doc || !spec) {
return true;
};
FlexiSpecs.verifyRules(doc, spec, null, errors);
}else{
mySpec = FlexiSpecs.typeMapping[myType];
if(mySpec && doc){
if(_.isFunction(mySpec.flexiValidate)) {
mySpec.flexiValidate(doc, self.field, 'test', errors);
}else{
// no validation defined.
// TODO we need to validate regex!
}
}else{
return true;
}
}
return !_.isEmpty(errors);
};
$scope.hasAvailableCollection = function(aCollection){
return aCollection && !_.isEmpty(aCollection);
};
$scope.radioFocus = function($event){
var widget = $event.target;
$(widget).closest(".radio-group").addClass("focus");
};
$scope.radioBlur = function($event){
var widget = $event.target;
$(widget).closest(".radio-group").removeClass("focus");
};
$scope.showErrorMessageFor = function(errorType){
return self.field.hasValidationOfType(errorType)
};
$scope.setSelectedIndex = function(index){
// self.$apply(function(){
self.myIndex = index;
// });
};
$scope.switchModel = function(index, $event){
self.setSelectedIndex(index);
if(!self.singleMode){
var formScope = angular.element($($event.currentTarget).closest('.mff-collection-field').find('ng-form').parent().parent()).scope();
formScope.model = self.collection[index];
}
setFocusToNewCollectionModelFirstEntryField($event);
};
$scope.removeModel = function(index){
self.collection.splice(index, 1);
self.setSelectedIndex(null);
};
$scope.addModel = function(collectionx, $event){
var formScope = angular.element($($event.currentTarget).closest('.mff-collection-field').find('ng-form').parent().parent()).scope();
var newSpec = self.field.getTypeName();
var newObj = FlexiSpecs.create(newSpec);
if(!self.singleMode) {
self.collection.push(newObj);
self.setSelectedIndex(self.collection.length - 1);
formScope.model = newObj;
}else{
if(self.collection != formScope.model){
formScope.model = self.collection;
}
formScope.model.push(newObj);
self.setSelectedIndex(formScope.model.length - 1);
}
setFocusToNewCollectionModelFirstEntryField($event);
};
$scope.getDisplayString = function(myItem, internal, index, selectedIndex, identifier, field) {
var result = null;
var theIdentifier = identifier;
if (theIdentifier && ngMeteorForms.displayStringRegistry[theIdentifier] && typeof ngMeteorForms.displayStringRegistry[theIdentifier] == "function") {
result = (ngMeteorForms.displayStringRegistry[theIdentifier])(myItem);
} else {
if (field && field.isCollection()) {
theIdentifier = field.getTypeName();
if (theIdentifier && ngMeteorForms.displayStringRegistry[theIdentifier] && typeof ngMeteorForms.displayStringRegistry[theIdentifier] == "function") {
result = (ngMeteorForms.displayStringRegistry[theIdentifier])(myItem);
}
}
}
if(_.isNull(result)) {
if (myItem && typeof myItem.toMffDisplayString == 'function') {
result = myItem.toMffDisplayString();
} else {
result = _.reduce(myItem, function (memo, value, attribute) {
if (value) {
if (!_.startsWith(attribute, '$') && !(_.startsWith(attribute, '_'))) {
var addOnString = "";
if (typeof value.toMffDisplayString == 'function') {
addOnString = value.toMffDisplayString();
} else {
if (typeof value == 'object') {
addOnString = this.getDisplayString(value, true);
} else {
addOnString = value;
}
}
if (addOnString && !_.isEmpty(addOnString)) {
if (memo && !_.isEmpty(memo)) {
return memo + ", " + addOnString;
}
return addOnString;
}
}
}
return memo;
}, "", this);
}
}
if (internal || (result && !_.isEmpty(result))) {
return result;
}
if (index == selectedIndex) {
if(myItem)
return "Please enter some data ..."
} else {
return "New entry! Please select to add some data!";
}
};
};
var mffFieldPreLink = function preLink(scope, iElement, iAttrs, controller) {
scope.xid = iAttrs.id;
scope.modelId = getModelId(iAttrs.id);
var comp = Deps.autorun(function(){
if(!scope.$$phase) {
scope.$apply(function () {
updateScope(scope, iAttrs);
})
}else{
updateScope(scope, iAttrs);
}
});
scope.$on('$destroy', function(){
comp.stop();
});
};
var mffFieldCompile = function compile(element, attrs) {
expandElement(element, attrs);
return {
pre: mffFieldPreLink
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Define angular directives to handle the replacement of template elements with their expanded, re-rendered contents.
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ngMeteorForms
/**
* The 'mffField' directive replaces 'mff-field' elements with an appropriate input-type field based on the field
* definition specified by the value of the 'data-id' attribute of this HTML element.
*/
.directive('mffField', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: true,
controller: ['$scope', mffFieldController],
compile: mffFieldCompile
};
}])
.directive('mffMaxcount', function (){
return {
restrict: 'A',
require: 'ngModel',
link: ['$scope', function(scope, elem, attr, ngModel) {
if(attr.mffMaxcount) {
//For DOM -> model validation
ngModel.$parsers.unshift(function (value) {
var valid = attr.mffMaxCount < value.length;
ngModel.$setValidity('mffMaxCount', valid);
return valid ? value : value;
});
//For model -> DOM validation
ngModel.$formatters.unshift(function (value) {
ngModel.$setValidity('mffMaxCount', attr.mffMaxCount < value.length);
return value;
});
}
}]
}
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* At startup, augment selected templates with additional functions and attributes which override default behaviors.
* Also, for non-field and non-autoform templates, define directives to handle the replacement of the corresponding
* HTML element with the result of 'fully rendering' the appropriate meteor spacebars template.
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Package.meteor.Meteor.startup(function(){
/**
* Populate two temporary register hashes with the names of templates: One for 'field-oriented' templates,
* the other for 'non-field' or 'other' templates.
*/
var fieldTemplateNames = [];
var otherMffTemplateNames = [];
for(key in Package.templating.Template){
if(key.match('^(mff).+')) {
if (key.match('^(mff).*(Field)$')) {
fieldTemplateNames.push(key);
} else {
otherMffTemplateNames.push(key);
}
}
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Define common, standard 'createContext' and 'mffTemplate' functions.
*/
var standardCompile = function compile(element, attrs){
expandElement(element, attrs);
};
var standardMffTemplate = function(element, attrs){return this};
/**
* Define compile pre-link and controller functions for mffAutoform directive
*/
var mffAutoformController = function($scope){
console.log($scope);
var self = $scope;
$scope.getModel = function(){
return this.model;
};
$scope.setModel = function(value){
self.model = value;
};
$scope.save = function(){
this.preSave();
console.log("Built-in Save happening now!");
var baseObj = this.getModel();
//TODO have to validate yet.
FlexiModels.meteorInsert(this.flexiModelname, baseObj);
console.log("Built-in Save complete.");
this.postSave();
};
$scope.preSave = function(){
console.log('preSave from internal controller');
};
$scope.postSave = function(){
console.log('postSave from internal controller');
};
if(!$scope.model) {
$scope.setModel({})
}
};
var mffAutoformPreLink = function preLink(scope, iElement, iAttrs, controller){
var comp = Deps.autorun(function(){
scope.flexiModelname = iAttrs['model'];
scope.unwrapped = iAttrs['unwrapped'];
if(scope.unwrapped){
if(scope.singleMode){
scope.model = scope.collection;
}
}
});
scope.$on('$destroy', function(){
comp.stop();
});
};
var mffAutoformCompile = function compile(element, attrs){
expandElement(element, attrs);
return {
pre: mffAutoformPreLink
}
};
/**
* For each non-field-oriented template, define a directive for that template which simply replaces the corresponding
* elements with the results of rendering that template in an appropriate context. Also augment each of these templates
* providing them with a createContext and a mffTemplate function.
*/
_.each(otherMffTemplateNames, function(directiveName){
var directiveDefinition = {
restrict: 'E',
compile: standardCompile
};
/**
* The 'mffAutoform' directive replaces the 'mff-autoform' element with a fully functional input/edit form based on
* the model specified by the flexispec whose name matches the value of the 'model' attribute of this HTML element.
*/
if(directiveName == 'mffAutoform'){
directiveDefinition.compile = mffAutoformCompile;
directiveDefinition.controller = mffAutoformController;
directiveDefinition.scope = true;
}
ngMeteorForms.directive(directiveName, function(){return directiveDefinition});
var template = getTemplateForKey(directiveName);
template.createContext = createNonFieldContext;
template.mffTemplate = standardMffTemplate;
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Define common field 'createContext' and 'mffTemplate' functions
*/
var mffFieldCreateContext = function(element, attrs){
var result = getFieldAsContextObject(element, attrs);
var theName = getAttributeFromElement(element, 'field');
if(theName){
theName = _getModelFieldBaseName(theName) + 'Form';
result.formName = theName;
}
return result;
};
var getTemplateForFieldTypeName = function(fieldTypeName){
var template = null;
if(fieldTypeName) {
var mffTemplateKey = 'mff' + _.capitalize(fieldTypeName) + 'Field';
template = getTemplateForKey(mffTemplateKey);
}
return template ? template : getTemplateForKey('mffTextField');
};
/**
* Return the appropriate template for the provided <element>
* @param element
* @param attrs
*/
var mffFieldMffTemplate = function(element, attrs){
var templateName = null;
var context = getFieldAsContextObject(element, attrs);
if(context){
templateName = context.getTemplateName();
}else{
console.log('Could not get field for element/attributes:')
console.log(element);
console.log(attrs);
console.log("------");
}
return getTemplateForFieldTypeName(templateName);
};
/**
* For each field-oriented template, simply augment the template with an appropriate 'createContext' and 'mffTemplate'
* function.
*/
_.each(fieldTemplateNames, function(templateName){
var mffFieldTemplate = getTemplateForKey(templateName);
mffFieldTemplate.createContext = mffFieldCreateContext;
mffFieldTemplate.mffTemplate = mffFieldMffTemplate;
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* For the radio field template (actually a radio button group), customize the 'createContext' function.
*/
var radioField = getTemplateForKey('mffRadioField');
radioField.createContext = function(element, attrs){
var context = getFieldAsContextObject(element, attrs);
context.orientation = '';
if(context.template && context.template.options && context.template.options.orientation){
context.orientation = context.template.options.orientation;
}
var myOptions = context.getMyCollectionContents();
_.each(myOptions, function(option){
option._modelId = context.modelId;
option._name = context.name;
option._id = context.name + "." + option[context.getCollectionValueAttributeName()];
option._value = option[context.getCollectionValueAttributeName()];
option._label = option[context.getCollectionLabelAttributeName()];
});
context.collection = myOptions;
return context;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* For the radio button template, customize the 'createContext' function.
*/
var radioButton = getTemplateForKey('mffRadioButton');
radioButton.createContext = function(element, attrs){
return owl.deepCopy(attrs);
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* For the mffAutoForm template, customize the 'createContext' function.
*/
var mffAutoform = getTemplateForKey('mffAutoform');
mffAutoform.createContext = function(element, attrs){
var context = createNonFieldContext(element, attrs);
var modelNameString = attrs['model'] ? (_.capitalize(attrs['model']) + " ") : "";
context.formTitle = "New " + modelNameString + "Information";
return context;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* For the collection field template, customize the 'createContext' function.
*/
var collectionField = getTemplateForKey('mffCollectionField');
collectionField.createContext = function(element, attrs){
var context = getFieldAsContextObject(element, attrs);
context.myIndex = 0;
return context;
};
});
/**
* Replace the default ngMeteor flexistrap configuration so that the ngMeteor module is NOT bootstrapped into the
* main document and so that the ngMeteorForms module is bootstrapped into any div with the class 'meteor-form' for all routes.
*/
ngMeteor.addFlexistrap('div.meteor-form', 'ngMeteorForms', '*', true);