-
Notifications
You must be signed in to change notification settings - Fork 649
/
Copy pathsf-builder.provider.js
344 lines (300 loc) · 11.5 KB
/
sf-builder.provider.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
// FIXME: type template (using custom builder)
export default function(sfPathProvider) {
var SNAKE_CASE_REGEXP = /[A-Z]/g;
var snakeCase = function(name, separator) {
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
};
var formId = 0;
if (!("firstElementChild" in document.createDocumentFragment())) {
Object.defineProperty(DocumentFragment.prototype, "firstElementChild", {
get: function () {
for (var nodes = this.childNodes, n, i = 0, l = nodes.length; i < l; ++i)
if (n = nodes[i], 1 === n.nodeType) return n;
return null;
}
});
}
var builders = {
sfField: function(args) {
args.fieldFrag.firstElementChild.setAttribute('sf-field', formId);
// We use a lookup table for easy access to our form.
args.lookup['f' + formId] = args.form;
formId++;
},
ngModel: function(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(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(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(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(args) {
let strKey = '';
let strModel = 'undefined';
let ngIf = '';
// 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) {
if (args.form.key) {
strKey = sfPathProvider.stringify(args.form.key);
strModel = 'model' + (strKey[0] === '[' ? '' : '.') + strKey;
}
let evalExpr = 'evalExpr(' + args.path + '.condition, { model: model, ' +
'"arrayIndex": $index, ' +
'"arrayIndices": arrayIndices, ' +
'"path": path, ' +
'"$i": $i, ' +
'"$index": $index, ' +
'"modelValue": ' + strModel + '})';
let children = args.fieldFrag.children || args.fieldFrag.childNodes;
for (let i = 0; i < children.length; i++) {
let child = children[i];
if(child.hasAttribute && child.hasAttribute('ng-if')) {
ngIf = child.getAttribute('ng-if');
};
if(child.setAttribute) {
child.setAttribute('ng-if',
ngIf
? '(' + ngIf + ') || (' + evalExpr + ')'
: evalExpr
);
};
}
}
},
array: function(args) {
var items = args.fieldFrag.querySelector('[schema-form-array-items]');
if (args.form.key) {
var arrayDepth = args.form.key.filter(function(e) { return e === '' }).length;
}
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 we're 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(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(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(items, decorator, templateFn, slots, path, state, lookup) {
state = state || {};
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(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(form, decorator, slots, lookup) {
return build(form, decorator, function(form, field) {
if (form.type === 'template') {
return form.template;
}
if (field.type === 'template') {
return field.template;
}
return $templateCache.get(field.template);
}, slots, undefined, undefined, lookup);
},
builder: builders,
stdBuilders: stdBuilders,
internalBuild: build
};
}];
}