-
Notifications
You must be signed in to change notification settings - Fork 649
/
Copy pathschema-form.js
631 lines (549 loc) · 20 KB
/
schema-form.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
/**
* Schema form service.
* This service is not that useful outside of schema form directive
* but makes the code more testable.
*/
angular.module('schemaForm').provider('schemaForm',
['sfPathProvider', function(sfPathProvider) {
var stripNullType = function(type) {
if (Array.isArray(type) && type.length > 1) {
var filtered = type.filter(function (type) {
return type !== 'null'
});
if (filtered.length == 1)
return filtered[0];
return filtered;
}
return type;
};
//Creates an default titleMap list from an enum, i.e. a list of strings.
var enumToTitleMap = function(enm) {
var titleMap = []; //canonical titleMap format is a list.
enm.forEach(function(name) {
titleMap.push({name: name, value: name});
});
return titleMap;
};
// Takes a titleMap in either object or list format and returns one in
// in the list format.
var canonicalTitleMap = function(titleMap, originalEnum) {
if (!angular.isArray(titleMap)) {
var canonical = [];
if (originalEnum) {
angular.forEach(originalEnum, function(value, index) {
canonical.push({name: titleMap[value], value: value});
});
} else {
angular.forEach(titleMap, function(name, value) {
canonical.push({name: name, value: value});
});
}
return canonical;
}
return titleMap;
};
var extendSchemas = function(obj1, obj2) {
obj1 = angular.extend({}, obj1);
obj2 = angular.extend({}, obj2);
var self = this;
var extended = {};
angular.forEach(obj1, function(val,prop) {
// If this key is also defined in obj2, merge them
if(typeof obj2[prop] !== 'undefined') {
// Required arrays should be unioned together
if(prop === 'required' && typeof val === 'object' && Array.isArray(val)) {
// Union arrays and unique
extended.required = val.concat(obj2[prop]).reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
}
// Type should be intersected and is either an array or string
else if(prop === 'type' && (typeof val === 'string' || Array.isArray(val))) {
// Make sure we're dealing with arrays
if(typeof val === 'string') val = [val];
if(typeof obj2.type === 'string') obj2.type = [obj2.type];
extended.type = val.filter(function(n) {
return obj2.type.indexOf(n) !== -1;
});
// If there's only 1 type, use a string instead of array
if(extended.type.length === 1) {
extended.type = extended.type[0];
}
}
// All other arrays should be intersected (enum, etc.)
else if(typeof val === 'object' && Array.isArray(val)){
extended[prop] = val.filter(function(n) {
return obj2[prop].indexOf(n) !== -1;
});
}
// Objects should be recursively merged
else if(typeof val === 'object' && val !== null) {
extended[prop] = extendSchemas(val, obj2[prop]);
}
// Otherwise, use the first value
else {
extended[prop] = val;
}
}
// Otherwise, just use the one in obj1
else {
extended[prop] = val;
}
});
// Properties in obj2 that aren't in obj1
angular.forEach(obj2, function(val, prop) {
if(typeof obj1[prop] === 'undefined') {
extended[prop] = val;
}
});
return extended;
};
var defaultFormDefinition = function(name, schema, options) {
var rules = defaults['any'].concat(defaults[stripNullType(schema.type)]);
if (rules) {
var def;
for (var i = 0; i < rules.length; i++) {
def = rules[i](name, schema, options);
//first handler in list that actually returns something is our handler!
if (def) {
// Do we have form defaults in the schema under the x-schema-form-attribute?
if (def.schema['x-schema-form'] && angular.isObject(def.schema['x-schema-form'])) {
def = angular.extend(def, def.schema['x-schema-form']);
}
return def;
}
}
}
};
//Creates a form object with all common properties
var stdFormObj = function(name, schema, options) {
options = options || {};
var f = options.global && options.global.formDefaults ?
angular.copy(options.global.formDefaults) : {};
if (options.global && options.global.supressPropertyTitles === true) {
f.title = schema.title;
} else {
f.title = schema.title || name;
}
if (schema.description) { f.description = schema.description; }
if (options.required === true || schema.required === true) { f.required = true; }
if (schema.maxLength) { f.maxlength = schema.maxLength; }
if (schema.minLength) { f.minlength = schema.minLength; }
if (schema.readOnly || schema.readonly) { f.readonly = true; }
if (schema.minimum) { f.minimum = schema.minimum + (schema.exclusiveMinimum ? 1 : 0); }
if (schema.maximum) { f.maximum = schema.maximum - (schema.exclusiveMaximum ? 1 : 0); }
// Non standard attributes (DONT USE DEPRECATED)
// If you must set stuff like this in the schema use the x-schema-form attribute
if (schema.validationMessage) { f.validationMessage = schema.validationMessage; }
if (schema.enumNames) { f.titleMap = canonicalTitleMap(schema.enumNames, schema['enum']); }
f.schema = schema;
// Ng model options doesn't play nice with undefined, might be defined
// globally though
f.ngModelOptions = f.ngModelOptions || {};
return f;
};
var text = function(name, schema, options) {
if (stripNullType(schema.type) === 'string' && !schema['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'text';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
//default in json form for number and integer is a text field
//input type="number" would be more suitable don't ya think?
var number = function(name, schema, options) {
if (stripNullType(schema.type) === 'number') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'number';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var integer = function(name, schema, options) {
if (stripNullType(schema.type) === 'integer') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'number';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var checkbox = function(name, schema, options) {
if (stripNullType(schema.type) === 'boolean') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'checkbox';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var select = function(name, schema, options) {
if (stripNullType(schema.type) === 'string' && schema['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'select';
if (!f.titleMap) {
f.titleMap = enumToTitleMap(schema['enum']);
}
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var checkboxes = function(name, schema, options) {
if (stripNullType(schema.type) === 'array' && schema.items && schema.items['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'checkboxes';
if (!f.titleMap) {
f.titleMap = enumToTitleMap(schema.items['enum']);
}
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var fieldset = function(name, schema, options) {
if (stripNullType(schema.type) === 'object') {
var f = stdFormObj(name, schema, options);
f.type = 'fieldset';
f.items = [];
options.lookup[sfPathProvider.stringify(options.path)] = f;
//recurse down into properties
angular.forEach(schema.properties, function(v, k) {
var path = options.path.slice();
path.push(k);
if (options.ignore[sfPathProvider.stringify(path)] !== true) {
var required = schema.required && schema.required.indexOf(k) !== -1;
var def = defaultFormDefinition(k, v, {
path: path,
required: required || false,
lookup: options.lookup,
ignore: options.ignore,
global: options.global
});
if (def) {
f.items.push(def);
}
}
});
return f;
}
};
var array = function(name, schema, options) {
if (stripNullType(schema.type) === 'array') {
var f = stdFormObj(name, schema, options);
f.type = 'array';
f.key = options.path;
options.lookup[sfPathProvider.stringify(options.path)] = f;
var required = schema.required &&
schema.required.indexOf(options.path[options.path.length - 1]) !== -1;
// The default is to always just create one child. This works since if the
// schemas items declaration is of type: "object" then we get a fieldset.
// We also follow json form notatation, adding empty brackets "[]" to
// signify arrays.
var arrPath = options.path.slice();
arrPath.push('');
f.items = [defaultFormDefinition(name, schema.items, {
path: arrPath,
required: required || false,
lookup: options.lookup,
ignore: options.ignore,
global: options.global
})];
return f;
}
};
var formselect = function(name, schema, options) {
var types = stripNullType(schema.type);
if (!(schema.oneOf || schema.anyOf || angular.isArray(types))) { return; }
var f = stdFormObj(name, schema, options);
f.type = 'formselect';
f.key = options.path;
var schemas = [];
// TODO: What if there are more than one of these keys in the same schema?
if (angular.isArray(types)) {
angular.forEach(types, function(type) {
schemas.push(extendSchemas({type: type}, schema));
});
} else {
angular.forEach(schema.anyOf || schema.oneOf, function(value) {
var extended = extendSchemas(value, schema);
delete extended.oneOf;
delete extended.anyOf;
schemas.push(extended);
});
}
f.titleMap = [];
f.items = [];
angular.forEach(schemas, function(s, index) {
var subPath = options.path.slice();
subPath.push('{' + index + '}');
f.titleMap.push({
name: s.title || f.title + ' ' + index,
value: index
});
var subForm = defaultFormDefinition(name, s, {
path: subPath,
required: options.required || false,
lookup: options.lookup,
ignore: options.ignore,
global: options.global
});
// FIXME: I'm not sure if the title should be on top of the select or not /d
subForm.notitle = true;
f.items.push(subForm);
});
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
};
var allof = function(name, schema, options) {
if (schema.allOf) {
var extended = schema;
var allOf = schema.allOf;
delete schema.allOf;
angular.forEach(allOf, function(s) {
extended = extendSchemas(s, extended);
});
return defaultFormDefinition(name, extended, options);
}
};
//First sorted by schema type then a list.
//Order has importance. First handler returning an form snippet will be used.
var defaults = {
any: [allof, formselect],
string: [select, text],
object: [fieldset],
number: [number],
integer: [integer],
boolean: [checkbox],
array: [checkboxes, array]
};
var postProcessFn = function(form) { return form; };
/**
* Provider API
*/
this.defaults = defaults;
this.stdFormObj = stdFormObj;
this.defaultFormDefinition = defaultFormDefinition;
/**
* Register a post process function.
* This function is called with the fully merged
* form definition (i.e. after merging with schema)
* and whatever it returns is used as form.
*/
this.postProcess = function(fn) {
postProcessFn = fn;
};
/**
* Append default form rule
* @param {string} type json schema type
* @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
* definition or undefined
*/
this.appendRule = function(type, rule) {
if (!defaults[type]) {
defaults[type] = [];
}
defaults[type].push(rule);
};
/**
* Prepend default form rule
* @param {string} type json schema type
* @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
* definition or undefined
*/
this.prependRule = function(type, rule) {
if (!defaults[type]) {
defaults[type] = [];
}
defaults[type].unshift(rule);
};
/**
* Utility function to create a standard form object.
* This does *not* set the type of the form but rather all shared attributes.
* You probably want to start your rule with creating the form with this method
* then setting type and any other values you need.
* @param {Object} schema
* @param {Object} options
* @return {Object} a form field defintion
*/
this.createStandardForm = stdFormObj;
/* End Provider API */
this.$get = function() {
var service = {};
service.merge = function(schema, form, ignore, options, readonly, asyncTemplates) {
form = form || ['*'];
options = options || {};
// Get readonly from root object
readonly = readonly || schema.readonly || schema.readOnly;
var stdForm = service.defaults(schema, ignore, options);
//simple case, we have a "*", just put the stdForm there
var idx = form.indexOf('*');
if (idx !== -1) {
form = form.slice(0, idx)
.concat(stdForm.form)
.concat(form.slice(idx + 1));
}
//ok let's merge!
//We look at the supplied form and extend it with schema standards
var lookup = stdForm.lookup;
return postProcessFn(form.map(function(obj) {
//handle the shortcut with just a name
if (typeof obj === 'string') {
obj = {key: obj};
}
if (Array.isArray(obj)) {
obj = {type: 'fieldset', items: obj};
}
if (obj.key) {
if (typeof obj.key === 'string') {
obj.key = sfPathProvider.parse(obj.key);
}
}
//If it has a titleMap make sure it's a list
if (obj.titleMap) {
obj.titleMap = canonicalTitleMap(obj.titleMap);
}
//
if (obj.itemForm) {
obj.items = [];
var str = sfPathProvider.stringify(obj.key);
var stdForm = lookup[str];
angular.forEach(stdForm.items, function(item) {
var o = angular.copy(obj.itemForm);
o.key = item.key;
obj.items.push(o);
});
}
//extend with std form from schema.
if (obj.key) {
var strid = sfPathProvider.stringify(obj.key);
if (lookup[strid]) {
var schemaDefaults = lookup[strid];
angular.forEach(schemaDefaults, function(value, attr) {
if (obj[attr] === undefined) {
obj[attr] = schemaDefaults[attr];
}
});
}
}
// Are we inheriting readonly?
if (readonly === true) { // Inheriting false is not cool.
obj.readonly = true;
}
//if it's a type with items, merge 'em!
if (obj.items) {
obj.items = service.merge(schema, obj.items, ignore, options, obj.readonly, asyncTemplates);
}
//if its has tabs, merge them also!
if (obj.tabs) {
angular.forEach(obj.tabs, function(tab) {
tab.items = service.merge(schema, tab.items, ignore, options, obj.readonly, asyncTemplates);
});
}
// Special case: checkbox
// Since have to ternary state we need a default
if (obj.type === 'checkbox' && angular.isUndefined(obj.schema['default'])) {
obj.schema['default'] = false;
}
// Special case: template type with tempplateUrl that's needs to be loaded before rendering
// TODO: this is not a clean solution. Maybe something cleaner can be made when $ref support
// is introduced since we need to go async then anyway
if (asyncTemplates && obj.type === 'template' && !obj.template && obj.templateUrl) {
asyncTemplates.push(obj);
}
// After merge, we don't want the formselect indexes in the keys anymore
if (obj.key) {
obj.key = obj.key.filter(function(keypart) {return keypart.indexOf('{') != 0;});
}
return obj;
}));
};
/**
* Create form defaults from schema
*/
service.defaults = function(schema, ignore, globalOptions) {
var form = [];
var lookup = {}; //Map path => form obj for fast lookup in merging
ignore = ignore || {};
globalOptions = globalOptions || {};
if (stripNullType(schema.type) === 'object') {
angular.forEach(schema.properties, function(v, k) {
if (ignore[k] !== true) {
var required = schema.required && schema.required.indexOf(k) !== -1;
var def = defaultFormDefinition(k, v, {
path: [k], // Path to this property in bracket notation.
lookup: lookup, // Extra map to register with. Optimization for merger.
ignore: ignore, // The ignore list of paths (sans root level name)
required: required, // Is it required? (v4 json schema style)
global: globalOptions // Global options, including form defaults
});
if (def) {
form.push(def);
}
}
});
} else {
throw new Error('Not implemented. Only type "object" allowed at root level of schema.');
}
return {form: form, lookup: lookup};
};
//Utility functions
/**
* Traverse a schema, applying a function(schema,path) on every sub schema
* i.e. every property of an object.
*/
service.traverseSchema = function(schema, fn, path, ignoreArrays) {
ignoreArrays = angular.isDefined(ignoreArrays) ? ignoreArrays : true;
path = path || [];
var traverse = function(schema, fn, path) {
angular.forEach(schema.properties, function(prop, name) {
var currentPath = path.slice();
currentPath.push(name);
traverse(prop, fn, currentPath);
});
//Only support type "array" which have a schema as "items".
if (!ignoreArrays && schema.items) {
var arrPath = path.slice(); arrPath.push('');
traverse(schema.items, fn, arrPath);
}
if (schema.dependencies) {
angular.forEach(schema.dependencies, function(value, key) {
if(typeof value === "object" && !(Array.isArray(value))) {
traverse(value, fn, path);
}
});
}
if (schema.not) {
traverse(schema.not, fn, path)
}
angular.forEach(['allOf', 'oneOf', 'anyOf'], function(prop) {
if (schema[prop]) {
angular.forEach(schema[prop], function(value) {
traverse(value, fn, path);
})
}
});
fn(schema, path);
};
traverse(schema, fn, path || []);
};
service.traverseForm = function(form, fn) {
fn(form);
angular.forEach(form.items, function(f) {
service.traverseForm(f, fn);
});
if (form.tabs) {
angular.forEach(form.tabs, function(tab) {
angular.forEach(tab.items, function(f) {
service.traverseForm(f, fn);
});
});
}
};
return service;
};
}]);