UNPKG

2.14 kBJavaScriptView Raw
1
2var Tag = require('./tag'),
3 wrappers = require('./wrappers');
4
5var Fieldgroup = module.exports = function Fieldgroup (options, elements) {
6
7 this.options = options || {};
8 this.elements = elements || [];
9 this.options.theme = this.options.theme || {};
10
11 // handle the label tag
12 if (this.options.label !== undefined && typeof this.options.label === 'string') {
13 this.options.label = {
14 label: this.options.label
15 };
16 }
17
18 // handle the helpText
19 if (this.options.helpText !== undefined && typeof this.options.helpText === 'string') {
20 this.options.helpText = {
21 text: this.options.helpText
22 }
23 }
24
25};
26
27Fieldgroup.prototype.render = function(theme) {
28
29 var label,
30 small,
31 content = '',
32 fieldsContent = '',
33 _theme = copy(theme);
34
35 // handle the label for the field group
36 if (this.options.label) {
37
38 // we want to append to the attributes, so default if it wasn't passed in
39 var attributes = this.options.label.attributes || {};
40
41 // generate the label tag and render it before the field itself
42 label = new Tag('label', attributes, this.options.label.label);
43
44 }
45
46 // this there some help text?
47 if (this.options.helpText) {
48
49 attributes = this.options.helpText.attributes || { 'class': 'help-text' };
50
51 small = new Tag((this.options.helpText.tag || 'small'), attributes, this.options.helpText.text);
52
53 }
54
55 // we want to have a different default theme.field function for nested fields
56 _theme.field = this.options.theme.field || theme.fieldgroup.field;
57
58 // loop through each nested Field element, and render it
59 for (var i = 0; i < this.elements.length; i++) {
60
61 // each Field, call render
62 fieldsContent += this.elements[i].render(_theme);
63
64 }
65
66 // generate the fields content (which is label + elements)
67 content = (this.options.theme.fields || theme.fieldgroup.fields)(fieldsContent, this.elements);
68
69 return (this.options.theme.group || theme.fieldgroup.group)((label !== undefined ? label.render() : ''), content, (small !== undefined ? small.render() : ''), this);
70
71};
72
73var copy = function (obj) {
74
75 var newObj = {};
76
77 Object.keys(obj).forEach(function (key) {
78 newObj[key] = obj[key];
79 });
80
81 return newObj;
82
83};