forked from Meteor-Community-Packages/meteor-autoform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautoform.js
1423 lines (1224 loc) · 43.5 KB
/
autoform.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
defaultFormId = "_afGenericID";
formPreserve = new FormPreserve("autoforms");
formData = {}; //for looking up autoform data by form ID
var templatesById = {}; //keep a reference of autoForm templates by form `id` for AutoForm.getFormValues
var arrayFields = {}; //track # of array fields per form
var formValues = {}; //for reactive show/hide based on current value of a field
var fd = new FormData();
arrayTracker = new ArrayTracker();
AutoForm = AutoForm || {}; //exported
/**
* @method AutoForm.addHooks
* @public
* @param {String[]|String|null} formIds Form `id` or array of form IDs to which these hooks apply. Specify `null` to add hooks that will run for every form.
* @param {Object} hooks Hooks to add, where supported names are "before", "after", "formToDoc", "docToForm", "onSubmit", "onSuccess", and "onError".
* @returns {undefined}
*
* Defines hooks to be used by one or more forms. Extends hooks lists if called multiple times for the same
* form.
*/
AutoForm.addHooks = function autoFormAddHooks(formIds, hooks, replace) {
if (typeof formIds === "string") {
formIds = [formIds];
}
// If formIds is null, add global hooks
if (!formIds) {
Hooks.addHooksToList(Hooks.global, hooks, replace);
} else {
_.each(formIds, function (formId) {
// Init the hooks object if not done yet
Hooks.form[formId] = Hooks.form[formId] || {
before: {},
after: {},
formToDoc: [],
docToForm: [],
onSubmit: [],
onSuccess: [],
onError: [],
beginSubmit: [],
endSubmit: []
};
Hooks.addHooksToList(Hooks.form[formId], hooks, replace);
});
}
};
/**
* @method AutoForm.hooks
* @public
* @param {Object} hooks
* @returns {undefined}
*
* Defines hooks by form id. Extends hooks lists if called multiple times for the same
* form.
*/
AutoForm.hooks = function autoFormHooks(hooks, replace) {
_.each(hooks, function(hooksObj, formId) {
AutoForm.addHooks(formId, hooksObj, replace);
});
};
/**
* @method AutoForm.resetForm
* @public
* @param {String} formId
* @returns {undefined}
*
* Resets validation for an autoform.
*/
AutoForm.resetForm = function autoFormResetForm(formId) {
if (typeof formId !== "string") {
return;
}
formPreserve.unregisterForm(formId);
// Reset array counts
arrayTracker.resetForm(formId);
if (formData[formId]) {
formData[formId].ss && formData[formId].ss.namedContext(formId).resetValidation();
// If simpleSchema is undefined, we haven't yet rendered the form, and therefore
// there is no need to reset validation for it. No error need be thrown.
}
};
var deps = {};
var defaultTemplate = "bootstrap3";
deps.defaultTemplate = new Deps.Dependency;
AutoForm.setDefaultTemplate = function autoFormSetDefaultTemplate(template) {
defaultTemplate = template;
deps.defaultTemplate.changed();
};
AutoForm.getDefaultTemplate = function autoFormGetDefaultTemplate() {
deps.defaultTemplate.depend();
return defaultTemplate;
};
// All use global template by default
var defaultTypeTemplates = {
quickForm: null,
afFieldLabel: null,
afFieldSelect: null,
afCheckboxGroup: null,
afRadioGroup: null,
afSelect: null,
afTextarea: null,
afContenteditable: null,
afCheckbox: null,
afRadio: null,
afInput: null,
afDeleteButton: null,
afQuickField: null,
afObjectField: null,
afArrayField: null
};
deps.defaultTypeTemplates = {
quickForm: new Deps.Dependency,
afFieldLabel: new Deps.Dependency,
afFieldSelect: new Deps.Dependency,
afCheckboxGroup: new Deps.Dependency,
afRadioGroup: new Deps.Dependency,
afSelect: new Deps.Dependency,
afTextarea: new Deps.Dependency,
afContenteditable: new Deps.Dependency,
afCheckbox: new Deps.Dependency,
afRadio: new Deps.Dependency,
afInput: new Deps.Dependency,
afDeleteButton: new Deps.Dependency,
afQuickField: new Deps.Dependency,
afObjectField: new Deps.Dependency,
afArrayField: new Deps.Dependency
};
/**
* @method AutoForm.setDefaultTemplateForType
* @public
* @param {String} type
* @param {String} template
*/
AutoForm.setDefaultTemplateForType = function autoFormSetDefaultTemplateForType(type, template) {
if (!deps.defaultTypeTemplates[type]) {
throw new Error("invalid template type: " + type);
}
if (template !== null && !Template[type + "_" + template]) {
throw new Error("setDefaultTemplateForType can't set default template to \"" + template + "\" for type \"" + type + "\" because there is no defined template with the name \"" + type + "_" + template + "\"");
}
defaultTypeTemplates[type] = template;
deps.defaultTypeTemplates[type].changed();
};
/**
* @method AutoForm.getDefaultTemplateForType
* @public
* @param {String} type
* @return {String} Template name
*
* Reactive.
*/
AutoForm.getDefaultTemplateForType = function autoFormGetDefaultTemplateForType(type) {
if (!deps.defaultTypeTemplates[type]) {
throw new Error("invalid template type: " + type);
}
deps.defaultTypeTemplates[type].depend();
return defaultTypeTemplates[type];
};
/**
* @method AutoForm.getFormValues
* @public
* @param {String} formId The `id` attribute of the `autoForm` you want current values for.
* @return {Object}
*
* Returns an object representing the current values of all schema-based fields in the form.
* The returned object contains two properties, "insertDoc" and "updateDoc", which represent
* the field values as a normal object and as a MongoDB modifier, respectively.
*/
AutoForm.getFormValues = function autoFormGetFormValues(formId) {
var template = templatesById[formId];
if (!template || template._notInDOM) {
throw new Error("getFormValues: There is currently no autoForm template rendered for the form with id " + formId);
}
// Get a reference to the SimpleSchema instance that should be used for
// determining what types we want back for each field.
var context = template.data;
var ss = Utility.getSimpleSchemaFromContext(context, formId);
return getFormValues(template, formId, ss);
};
/**
* @method AutoForm.getFieldValue
* @public
* @param {String} formId The `id` attribute of the `autoForm` you want current values for.
* @param {String} fieldName The name of the field for which you want the current value.
* @return {Any}
*
* Returns the value of the field (the value that would be used if the form were submitted right now).
* This is a reactive method that will rerun whenever the current value of the requested field changes.
*/
AutoForm.getFieldValue = function autoFormGetFieldValue(formId, fieldName) {
return getTrackedFieldValue(formId, fieldName);
};
/*
* Shared
*/
UI.registerHelper('_af_findAutoForm', function afFindAutoForm(name) {
var afContext, i = 1;
do {
afContext = arguments[i];
i++;
} while (afContext && !afContext._af);
if (!afContext)
throw new Error(name + " must be used within an autoForm block");
return afContext;
});
Template.afFieldInput.getTemplate =
Template.afFieldLabel.getTemplate =
Template.afFieldSelect.getTemplate =
Template.afDeleteButton.getTemplate =
Template.afQuickField.getTemplate =
Template.afObjectField.getTemplate =
Template.afArrayField.getTemplate =
Template.quickForm.getTemplate =
function afGenericGetTemplate(templateType, templateName) {
var result;
var defaultTemplate = AutoForm.getDefaultTemplateForType(templateType) || AutoForm.getDefaultTemplate();
// Determine template name
if (templateName) {
var result = Template[templateType + '_' + templateName];
if (!result) {
console.warn(templateType + ': "' + templateName + '" is not a valid template name. Falling back to default template, "' + defaultTemplate + '".');
}
}
if (!result) {
result = Template[templateType + '_' + defaultTemplate];
if (!result) {
throw new Error(templateType + ': "' + defaultTemplate + '" is not a valid template name');
}
}
// Return the template instance that we want to use
return result;
};
/*
* autoForm
*/
Template.autoForm.atts = function autoFormTplAtts() {
var context = _.clone(this);
// By default, we add the `novalidate="novalidate"` attribute to our form,
// unless the user passes `validation="browser"`.
if (context.validation !== "browser" && !context.novalidate) {
context.novalidate = "novalidate";
}
// After removing all of the props we know about, everything else should
// become a form attribute.
return _.omit(context, "schema", "collection", "validation", "doc", "resetOnSuccess", "type", "template");
};
Template.autoForm.innerContext = function autoFormTplInnerContext(outerContext) {
var context = this;
var formId = context.id || defaultFormId;
var collection = Utility.lookup(context.collection);
var ss = Utility.getSimpleSchemaFromContext(context, formId);
// Retain doc values after a "hot code push", if possible
var retrievedDoc = formPreserve.getDocument(formId);
if (retrievedDoc !== false) {
context.doc = retrievedDoc;
}
var mDoc;
if (context.doc && !_.isEmpty(context.doc)) {
// Clone doc
var copy = _.clone(context.doc);
// Pass doc through docToForm hooks
_.each(Hooks.getHooks(formId, 'docToForm'), function autoFormEachDocToForm(func) {
copy = func(copy, ss, formId);
});
// Create a "flat doc" that can be used to easily get values for corresponding
// form fields.
mDoc = new MongoObject(copy);
fd.sourceDoc(formId, mDoc);
} else {
fd.sourceDoc(formId, null);
}
// Set up the context to be used for everything within the autoform.
var innerContext = {_af: {
formId: formId,
collection: collection,
ss: ss,
doc: context.doc,
mDoc: mDoc,
validationType: context.validation || "submitThenKeyup",
submitType: context.type,
resetOnSuccess: context.resetOnSuccess
}};
// Cache context for lookup by formId
formData[formId] = innerContext._af;
// When we change the form, loading a different doc, reloading the current doc, etc.,
// we also want to reset the array counts for the form
arrayTracker.resetForm(formId);
// Preserve outer context, allowing access within autoForm block without needing ..
_.extend(innerContext, outerContext);
return innerContext;
};
Template.autoForm.created = function autoFormCreated() {
var self = this;
var formId = self.data.id || defaultFormId;
// Add to templatesById list
templatesById[formId] = self;
};
Template.autoForm.destroyed = function autoFormDestroyed() {
var self = this;
self._notInDOM = true;
var formId = self.data.id || defaultFormId;
// Remove from templatesById list
if (templatesById[formId]) {
delete templatesById[formId];
}
// Remove from data list
if (formData[formId]) {
delete formData[formId];
}
// Remove from array fields list
arrayTracker.untrackForm(formId);
// Remove from field values
if (formValues[formId]) {
delete formValues[formId];
}
// Unregister form preservation
formPreserve.unregisterForm(formId);
};
/*
* quickForm
*/
UI.registerHelper('quickForm', function quickFormHelper() {
throw new Error('Use the new syntax {{> quickForm}} rather than {{quickForm}}');
});
Template.quickForm.qfContext = function quickFormContext(atts) {
// Pass along quickForm context to autoForm context, minus a few
// properties that are specific to quickForms.
var qfAutoFormContext = _.omit(atts, "buttonContent", "buttonClasses", "fields", "omitFields");
return _.extend({
qfFormFields: qfFormFields,
qfNeedsButton: qfNeedsButton,
qfAutoFormContext: qfAutoFormContext
}, atts);
};
function qfFormFields() {
var context = this;
var ss = context._af.ss;
// Get the list of fields we want included
var fieldList;
if (context.fields) {
fieldList = context.fields;
if (typeof fieldList === "string") {
fieldList = fieldList.replace(/ /g, '').split(',');
}
if (!_.isArray(fieldList)) {
throw new Error('AutoForm: fields attribute must be an array or a string containing a comma-delimited list of fields');
}
} else {
// If we weren't given a fieldList, use all first level schema keys by default
fieldList = ss.firstLevelSchemaKeys() || [];
}
// If user wants to omit some fields, remove those from the array
if (context.omitFields) {
var omitFields = stringToArray(context.omitFields);
if (!_.isArray(omitFields)) {
throw new Error('AutoForm: omitFields attribute must be an array or a string containing a comma-delimited list of fields');
}
fieldList = _.difference(fieldList, omitFields);
}
return quickFieldFormFields(fieldList, context._af, true);
}
function quickFieldFormFields(fieldList, afContext, useAllowedValuesAsOptions) {
var ss = afContext.ss;
var addedFields = [];
// Filter out fields we truly don't want
fieldList = _.filter(fieldList, function shouldIncludeField(field) {
var fieldDefs = ss.schema(field);
// Don't include fields with denyInsert=true when it's an insert form
if (fieldDefs.denyInsert && afContext.submitType === "insert")
return false;
// Don't include fields with denyUpdate=true when it's an update form
if (fieldDefs.denyUpdate && afContext.submitType === "update")
return false;
return true;
});
// If we've filtered out all fields, we're done
if (!fieldList || !fieldList.length)
return [];
// Define extra properties to be added to all fields
var extendedAtts = {
autoform: {_af: afContext}
};
if (afContext.submitType === "disabled") {
extendedAtts.disabled = "";
} else if (afContext.submitType === "readonly") {
extendedAtts.readonly = "";
}
// Define a function to get the necessary info for each requested field
function infoForField(field, extendedProps) {
// Ensure fields are not added more than once
if (_.contains(addedFields, field))
return;
// Get schema definitions for this field
var fieldDefs = ss.schema(field);
var info = {name: field};
// If there are allowedValues defined, use them as select element options
if (useAllowedValuesAsOptions) {
var av = fieldDefs.type === Array ? ss.schema(field + ".$").allowedValues : fieldDefs.allowedValues;
if (_.isArray(av)) {
info.options = "allowed";
}
}
addedFields.push(field);
// Return the field info along with the extra properties that
// all fields should have
return _.extend(info, extendedProps);
}
// Return info for all requested fields
return _.map(fieldList, function autoFormFormFieldsListEach(field) {
return infoForField(field, extendedAtts);
});
}
function qfNeedsButton() {
var context = this;
var needsButton = true;
switch (context._af.submitType) {
case "readonly":
case "disabled":
needsButton = false;
break;
default:
needsButton = true;
break;
}
return needsButton;
}
/*
* afFieldLabel
*/
UI.registerHelper('afFieldLabel', function afFieldLabelHelper() {
throw new Error('Use the new syntax {{> afFieldLabel name="name"}} rather than {{afFieldLabel "name"}}');
});
function getLabel() {
var c = Utility.normalizeContext(this, "afFieldLabel");
return c.af.ss.label(c.atts.name);
}
Template.afFieldLabel.labelContext = function getLabelContext(autoform, atts) {
return {
autoform: autoform,
atts: atts,
label: getLabel
};
};
/*
* afFieldSelect
*/
UI.registerHelper('afFieldSelect', function afFieldSelectHelper() {
throw new Error('Use the new syntax {{> afFieldSelect name="name"}} rather than {{afFieldSelect "name"}}');
});
Template.afFieldSelect.inputContext = function afFieldSelectInputContext(options) {
var ctx = ((options || {}).hash || {});
var c = ctx.outerContext;
var iData = getInputData(c.defs, c.atts, c.value, "select", c.ss.label(c.atts.name), c.expectsArray);
return _.extend({contentBlock: ctx.contentBlock}, iData);
};
/*
* afFieldInput
*/
UI.registerHelper('afFieldInput', function afFieldInputHelper() {
throw new Error('Use the new syntax {{> afFieldInput name="name"}} rather than {{afFieldInput "name"}}');
});
Template.afFieldInput.inputOuterContext =
Template.afFieldSelect.inputOuterContext =
function (options) {
var c = Utility.normalizeContext(options.hash, "afFieldInput");
var ss = c.af.ss;
var defs = Utility.getDefs(ss, c.atts.name); //defs will not be undefined
// Get schema type
var schemaType = defs.type;
// Adjust for array fields if necessary
var expectsArray = false;
var defaultValue = defs.defaultValue; //make sure to use pre-adjustment defaultValue for arrays
if (schemaType === Array) {
defs = ss.schema(c.atts.name + ".$");
schemaType = defs.type;
//if the user overrides the type to anything,
//then we won't be using a select box and
//we won't be expecting an array for the current value
expectsArray = !c.atts.type;
}
// Get input value
var value = getInputValue(c.atts.name, c.atts.value, c.af.mDoc, expectsArray, defaultValue);
// Track field's value for reactive show/hide of other fields by value
updateTrackedFieldValue(c.af.formId, c.atts.name, value);
// Get type
var type = getInputType(c.atts, defs, value);
// Get template type
var templateType = getInputTemplateType(c.atts, type, schemaType, expectsArray);
return {
defs: defs,
ss: ss,
atts: c.atts,
type: type,
value: value,
expectsArray: expectsArray,
templateType: templateType
};
};
Template.afFieldInput.inputContext = function (options) {
var c = ((options || {}).hash || {}).outerContext;
return getInputData(c.defs, c.atts, c.value, c.type, c.ss.label(c.atts.name), c.expectsArray);
};
/*
* afDeleteButton
*/
UI.registerHelper('afDeleteButton', function afDeleteButtonHelper() {
throw new Error('Use the syntax {{> afDeleteButton collection=collection doc=doc}}');
});
Template.afDeleteButton.innerContext = function afDeleteButtonInnerContext(ctx, contentBlock) {
return _.extend(ctx, {contentBlock: contentBlock});
};
/*
* afArrayField
*/
UI.registerHelper('afArrayField', function afArrayFieldHelper() {
throw new Error('Use the syntax {{> afArrayField name="name"}} rather than {{afArrayField "name"}}');
});
Template.afArrayField.innerContext = function (options) {
var c = Utility.normalizeContext(options.hash, "afArrayField");
var name = c.atts.name;
var fieldMinCount = c.atts.minCount || 0;
var fieldMaxCount = c.atts.maxCount || Infinity;
var ss = c.af.ss;
var formId = c.af.formId;
// Init the array tracking for this field
var docCount = fd.getDocCountForField(formId, name);
arrayTracker.initField(formId, name, ss, docCount, fieldMinCount, fieldMaxCount);
return {
name: name,
label: ss.label(name),
autoform: c.afc
};
};
/*
* afObjectField
*/
UI.registerHelper('afObjectField', function afObjectFieldHelper() {
throw new Error('Use the syntax {{> afObjectField name="name"}} rather than {{afObjectField "name"}}');
});
Template.afObjectField.innerContext = function (options) {
var c = Utility.normalizeContext(options.hash, "afObjectField");
var name = c.atts.name;
var ss = c.af.ss;
// Get list of field names that are descendants of this field's name
var fields = autoFormChildKeys(ss, name);
// Tack child field name on to end of parent field name. This
// ensures that we keep the desired array index for array items.
fields = _.map(fields, function (field) {
return name + "." + field;
});
// Get rid of nested fields specified in omitFields
if(typeof c.afc.omitFields !== "undefined"){
var omitFields = stringToArray(c.afc.omitFields);
fields = _.reject(fields,function(f){
return _.contains(omitFields,SimpleSchema._makeGeneric(f))
});
}
var formFields = quickFieldFormFields(fields, c.af, true);
return {
fields: formFields,
label: ss.label(name)
};
};
function stringToArray(s){
if (typeof s === "string") {
return s.replace(/ /g, '').split(',');
}else{
return s;
}
};
/*
* afQuickField
*/
UI.registerHelper('afQuickField', function afQuickFieldHelper() {
throw new Error('Use the new syntax {{> afQuickField name="name"}} rather than {{afQuickField "name"}}');
});
function quickFieldLabelAtts(context, autoform) {
// Remove unwanted props from the hash
context = _.omit(context, 'label');
// Separate label options from input options; label items begin with "label-"
var labelContext = {
name: context.name,
template: context.template,
autoform: autoform
};
_.each(context, function autoFormLabelContextEach(val, key) {
if (key.indexOf("label-") === 0) {
labelContext[key.substring(6)] = val;
}
});
return labelContext;
}
function quickFieldInputAtts(context, autoform) {
// Remove unwanted props from the hash
context = _.omit(context, 'label');
// Separate label options from input options; label items begin with "label-"
var inputContext = {autoform: autoform};
_.each(context, function autoFormInputContextEach(val, key) {
if (key.indexOf("label-") !== 0) {
inputContext[key] = val;
}
});
return inputContext;
}
Template.afQuickField.innerContext = function afQuickFieldInnerContext(options) {
var c = Utility.normalizeContext(options.hash, "afQuickField");
var ss = c.af.ss;
var labelAtts = quickFieldLabelAtts(c.atts, c.afc);
var inputAtts = quickFieldInputAtts(c.atts, c.afc);
var defs = Utility.getDefs(ss, c.atts.name); //defs will not be undefined
return {
skipLabel: (c.atts.label === false || (defs.type === Boolean && !("select" in c.atts) && !("radio" in c.atts))),
afFieldLabelAtts: labelAtts,
afFieldInputAtts: inputAtts,
atts: {name: inputAtts.name, autoform: inputAtts.autoform}
};
};
Template.afQuickField.isGroup = function afQuickFieldIsGroup(options) {
var c = Utility.normalizeContext(options.hash, "afQuickField");
var ss = c.af.ss;
var defs = Utility.getDefs(ss, c.atts.name); //defs will not be undefined
return (defs.type === Object);
};
Template.afQuickField.isFieldArray = function afQuickFieldIsFieldArray(options) {
var c = Utility.normalizeContext(options.hash, "afQuickField");
var ss = c.af.ss;
var defs = Utility.getDefs(ss, c.atts.name); //defs will not be undefined
// Render an array of fields if we expect an array and we don't have options
return (defs.type === Array && !c.atts.options);
};
/*
* afEachArrayItem
*/
Template.afEachArrayItem.innerContext = function afEachArrayItemInnerContext(name, af, minCount, maxCount) {
if (!af || !af._af) {
throw new Error(name + " must be used within an autoForm block");
}
var afContext = af._af;
var ss = afContext.ss;
var formId = afContext.formId;
var docCount = fd.getDocCountForField(formId, name);
arrayTracker.initField(formId, name, ss, docCount, minCount, maxCount);
return arrayTracker.getField(formId, name);
};
/*
* afFieldMessage
*/
UI.registerHelper('afFieldMessage', function autoFormFieldMessage(options) {
//help users transition from positional name arg
if (typeof options === "string") {
throw new Error('Use the new syntax {{afFieldMessage name="name"}} rather than {{afFieldMessage "name"}}');
}
var hash = (options || {}).hash || {};
var afContext = hash.autoform && hash.autoform._af || this && this._af;
var ss = afContext.ss;
if (!ss) {
throw new Error("afFieldMessage helper must be used within an autoForm block");
}
Utility.getDefs(ss, hash.name); //for side effect of throwing errors when name is not in schema
return ss.namedContext(afContext.formId).keyErrorMessage(hash.name);
});
/*
* afFieldIsInvalid
*/
UI.registerHelper('afFieldIsInvalid', function autoFormFieldIsInvalid(options) {
//help users transition from positional name arg
if (typeof options === "string") {
throw new Error('Use the new syntax {{#if afFieldIsInvalid name="name"}} rather than {{#if afFieldIsInvalid "name"}}');
}
var hash = (options || {}).hash || {};
var afContext = hash.autoform && hash.autoform._af || this && this._af;
var ss = afContext.ss;
if (!ss) {
throw new Error("afFieldIsInvalid helper must be used within an autoForm block");
}
Utility.getDefs(ss, hash.name); //for side effect of throwing errors when name is not in schema
return ss.namedContext(afContext.formId).keyIsInvalid(hash.name);
});
/*
* afArrayFieldHasMoreThanMinimum
*/
UI.registerHelper('afArrayFieldHasMoreThanMinimum', function autoFormArrayFieldHasMoreThanMinimum(options) {
var hash = (options || {}).hash || {};
var afContext = hash.autoform && hash.autoform._af || this && this._af;
var ss = afContext.ss;
if (!ss) {
throw new Error("afArrayFieldHasMoreThanMinimum helper must be used within an autoForm block");
}
Utility.getDefs(ss, hash.name); //for side effect of throwing errors when name is not in schema
var range = arrayTracker.getMinMax(ss, hash.name, hash.minCount, hash.maxCount);
var visibleCount = arrayTracker.getVisibleCount(afContext.formId, hash.name);
return (visibleCount > range.minCount);
});
/*
* afArrayFieldHasLessThanMaximum
*/
UI.registerHelper('afArrayFieldHasLessThanMaximum', function autoFormArrayFieldHasLessThanMaximum(options) {
var hash = (options || {}).hash || {};
var afContext = hash.autoform && hash.autoform._af || this && this._af;
var ss = afContext.ss;
if (!ss) {
throw new Error("afArrayFieldHasLessThanMaximum helper must be used within an autoForm block");
}
Utility.getDefs(ss, hash.name); //for side effect of throwing errors when name is not in schema
var range = arrayTracker.getMinMax(ss, hash.name, hash.minCount, hash.maxCount);
var visibleCount = arrayTracker.getVisibleCount(afContext.formId, hash.name);
return (visibleCount < range.maxCount);
});
/*
* afFieldValueIs
*/
UI.registerHelper('afFieldValueIs', function autoFormFieldValueIs(options) {
var hash = (options || {}).hash || {};
var afContext = hash.autoform && hash.autoform._af || this && this._af;
var ss = afContext.ss;
if (!ss) {
throw new Error("afFieldValueIs helper must be used within an autoForm block");
}
Utility.getDefs(ss, hash.name); //for side effect of throwing errors when name is not in schema
return getTrackedFieldValue(afContext.formId, hash.name) === hash.value;
});
/*
* afFieldValueContains
*/
UI.registerHelper('afFieldValueContains', function autoFormFieldValueContains(options) {
var hash = (options || {}).hash || {};
var afContext = hash.autoform && hash.autoform._af || this && this._af;
var ss = afContext.ss;
if (!ss) {
throw new Error("afFieldValueContains helper must be used within an autoForm block");
}
Utility.getDefs(ss, hash.name); //for side effect of throwing errors when name is not in schema
var currentValue = getTrackedFieldValue(afContext.formId, hash.name);
return _.isArray(currentValue) && _.contains(currentValue, hash.value);
});
/*
* Private Helper Functions
*/
function getFieldsValues(fields) {
var doc = {};
fields.each(function formValuesEach() {
var field = $(this);
var fieldName = field.attr("data-schema-key");
// use custom handlers first, and then use built-in handlers
_.every([customInputValueHandlers, defaultInputValueHandlers], function (handlerList) {
return _.every(handlerList, function (handler, selector) {
if (field.filter(selector).length === 1) {
// Special handling for checkboxes that create arrays
// XXX maybe there is a way to do this better
var isArrayCheckBox = (field.hasClass("autoform-array-item"));
if (isArrayCheckBox) {
// Add empty array no matter what,
// to ensure that unchecking all boxes
// will empty the array.
if (!_.isArray(doc[fieldName])) {
doc[fieldName] = [];
}
}
var val = handler.call(field);
if (val !== void 0) {
if (isArrayCheckBox) {
doc[fieldName].push(val);
} else {
doc[fieldName] = val;
}
}
return false;
}
return true;
});
});
});
return doc;
}
getFieldValue = function getFieldValue(template, key) {
var doc = getFieldsValues(template.$('[data-schema-key="' + key + '"], [data-schema-key^="' + key + '."]'));
return doc && doc[key];
};
getFormValues = function getFormValues(template, formId, ss) {
var doc = getFieldsValues(template.$("[data-schema-key]").not("[disabled]"));
// Expand the object
doc = Utility.expandObj(doc);
// As array items are removed, gaps can appear in the numbering,
// which results in arrays that have undefined items. Here we
// remove any array items that are undefined.
Utility.compactArrays(doc);
// Pass expanded doc through formToDoc hooks
var transforms = Hooks.getHooks(formId, 'formToDoc');
_.each(transforms, function formValuesTransform(transform) {
doc = transform(doc, ss, formId);
});
// We return doc, insertDoc, and updateDoc.
// For insertDoc, delete any properties that are null, undefined, or empty strings.
// For updateDoc, convert to modifier object with $set and $unset.
// Do not add auto values to either.
var result = {
insertDoc: ss.clean(Utility.cleanNulls(doc), {
isModifier: false,
getAutoValues: false
}),
updateDoc: ss.clean(Utility.docToModifier(doc), {
isModifier: true,
getAutoValues: false
})
};
return result;
};
function getInputValue(name, value, mDoc, expectsArray, defaultValue) {
if (typeof value === "undefined") {
// Get the value for this key in the current document
if (mDoc) {
var valueInfo = mDoc.getInfoForKey(name);
if (valueInfo) {
value = valueInfo.value;
}
}
// Only if there is no current document, use the schema defaultValue
else if (defaultValue !== null && defaultValue !== undefined) {
value = defaultValue;
}
}
// Change null or undefined to an empty string
value = (value == null) ? '' : value;
function stringValue(val, skipDates) {
if (val instanceof Date) {
if (skipDates) {
return val;
} else {
return Utility.dateToDateStringUTC(val);
}
} else if (val.toString) {
return val.toString();
} else {
return val;
}
}
// If we're expecting value to be an array, and it's not, make it one
if (expectsArray && !_.isArray(value)) {
if (typeof value === "string") {