forked from ndbroadbent/alpaca
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlpaca.js
More file actions
4210 lines (3622 loc) · 139 KB
/
Alpaca.js
File metadata and controls
4210 lines (3622 loc) · 139 KB
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
/*jshint -W004 */ // duplicate variables
/*jshint -W083 */ // inline functions are used safely
/**
* Alpaca forms engine for jQuery
*/
(function($) {
/**
* Renders an Alpaca field instance that is bound to a DOM element.
*
* The basic syntax is:
*
* <code>
* <pre>
* Alpaca(el, config);
* </pre>
* </code>
*
* The full syntax is:
*
* <code>
* <pre>
* Alpaca(el, {
* "data" : {Any} field data (optional),
* "schema": {Object} field schema (optional),
* "options" : {Object} field options (optional),
* "view": {Object|String} field view (object or id reference) (optional),
* "render": {Function} callback function for replacing default rendering method (optional),
* "postRender": {Function} callback function for post-rendering (optional),
* "error": {Function} callback function for error handling (optional),
* "connector": {Alpaca.Connector} connector for retrieving or storing data, schema, options, view and templates. (optional)
* });
* </pre>
* </code>
*
* @returns {*}
*/
var Alpaca = function()
{
var args = Alpaca.makeArray(arguments);
if (args.length === 0) {
// illegal
return Alpaca.throwDefaultError("You must supply at least one argument. This argument can either be a DOM element against which Alpaca will generate a form or it can be a function name. See http://www.alpacajs.org for more details.");
}
// element is the first argument (either a string or a DOM element)
var el = args[0];
if (el && Alpaca.isString(el)) {
el = $("#" + el);
}
// other arguments we may want to figure out
var data = null;
var schema = null;
var options = null;
var view = null;
var callback = null;
var renderedCallback = null;
var errorCallback = null;
var connector = null;
var notTopLevel = false;
var initialSettings = {};
// if these options are provided, then data, schema, options and source are loaded via connector
var dataSource = null;
var schemaSource = null;
var optionsSource = null;
var viewSource = null;
/**
* Finds the Alpaca field instance bound to the dom element.
*
* First considers the immediate dom element and then looks 1 level deep to children and then up to parent.
*
* @returns {*}
*/
var findExistingAlpacaBinding = function(domElement, skipPivot)
{
var existing = null;
// look at "data-alpaca-field-id"
var alpacaFieldId = $(domElement).attr("data-alpaca-field-id");
if (alpacaFieldId)
{
var alpacaField = Alpaca.fieldInstances[alpacaFieldId];
if (alpacaField)
{
existing = alpacaField;
}
}
// if not found, look at "data-alpaca-form-id"
if (!existing)
{
var formId = $(domElement).attr("data-alpaca-form-id");
if (formId)
{
var subElements = $(domElement).find(":first");
if (subElements.length > 0)
{
var subFieldId = $(subElements[0]).attr("data-alpaca-field-id");
if (subFieldId)
{
var subField = Alpaca.fieldInstances[subFieldId];
if (subField)
{
existing = subField;
}
}
}
}
}
// if not found, check for children 0th element
if (!existing && !skipPivot)
{
var childDomElements = $(el).find(":first");
if (childDomElements.length > 0)
{
var childField = findExistingAlpacaBinding(childDomElements[0], true);
if (childField)
{
existing = childField;
}
}
}
// if not found, check parent
if (!existing && !skipPivot)
{
var parentEl = $(el).parent();
if (parentEl)
{
var parentField = findExistingAlpacaBinding(parentEl, true);
if (parentField)
{
existing = parentField;
}
}
}
return existing;
};
var specialFunctionNames = ["get", "exists", "destroy"];
var isSpecialFunction = (args.length > 1 && Alpaca.isString(args[1]) && (specialFunctionNames.indexOf(args[1]) > -1));
var existing = findExistingAlpacaBinding(el);
if (existing || isSpecialFunction)
{
if (isSpecialFunction)
{
// second argument must be a special function name
var specialFunctionName = args[1];
if ("get" === specialFunctionName) {
return existing;
}
else if ("exists" === specialFunctionName) {
return (existing ? true : false);
}
else if ("destroy" === specialFunctionName) {
if (existing) {
existing.destroy();
}
return;
}
return Alpaca.throwDefaultError("Unknown special function: " + specialFunctionName);
}
return existing;
}
else
{
var config = null;
// just a dom element, no other args?
if (args.length === 1)
{
// grab the data inside of the element and use that for config
var jsonString = $(el).text();
config = JSON.parse(jsonString);
$(el).html("");
}
else
{
if (Alpaca.isObject(args[1]))
{
config = args[1];
}
else if (Alpaca.isFunction(args[1]))
{
config = args[1]();
}
else
{
config = {
"data": args[1]
};
}
}
if (!config)
{
return Alpaca.throwDefaultError("Unable to determine Alpaca configuration");
}
data = config.data;
schema = config.schema;
options = config.options;
view = config.view;
callback = config.render;
if (config.callback) {
callback = config.callback;
}
renderedCallback = config.postRender;
errorCallback = config.error;
connector = config.connector;
// sources
dataSource = config.dataSource;
schemaSource = config.schemaSource;
optionsSource = config.optionsSource;
viewSource = config.viewSource;
// other
if (config.ui) {
initialSettings["ui"] = config.ui;
}
if (config.type) {
initialSettings["type"] = config.type;
}
if (!Alpaca.isEmpty(config.notTopLevel)) {
notTopLevel = config.notTopLevel;
}
}
// if no error callback is provided, we fall back to a browser alert
if (Alpaca.isEmpty(errorCallback)) {
errorCallback = Alpaca.defaultErrorCallback;
}
// instantiate the connector (if not already instantiated)
// if config is passed in (as object), we instantiate
if (!connector || !connector.connect)
{
var connectorId = "default";
var connectorConfig = {};
if (Alpaca.isString(connector)) {
connectorId = connector;
}
else if (Alpaca.isObject(connector) && connector.id) {
connectorId = connector.id;
if (connector.config) {
connectorConfig = connector.config;
}
}
var ConnectorClass = Alpaca.getConnectorClass(connectorId);
if (!ConnectorClass) {
ConnectorClass = Alpaca.getConnectorClass("default");
}
connector = new ConnectorClass(connectorId, connectorConfig);
}
// For second or deeper level of fields, default loader should be the one to do loadAll
// since schema, data, options and view should have already been loaded.
// Unless we want to load individual fields (other than the templates) using the provided
// loader, this should be good enough. The benefit is saving time on loader format checking.
var loadAllConnector = connector;
if (notTopLevel) {
var LoadAllConnectorClass = Alpaca.getConnectorClass("default");
loadAllConnector = new LoadAllConnectorClass("default");
}
if (!options) {
options = {};
}
// resets the hideInitValidationError back to default state after first render
var _resetInitValidationError = function(field)
{
// if this is the top-level alpaca field, then we call for validation state to be recalculated across
// all child fields
if (!field.parent)
{
// final call to update validation state
// only do this if we're not supposed to suspend initial validation errors
if (!field.hideInitValidationError)
{
field.refreshValidationState(true);
}
// force hideInitValidationError to false for field and all children
if (field.view.type !== 'view')
{
Alpaca.fieldApplyFieldAndChildren(field, function(field) {
// set to false after first validation (even if in CREATE mode, we only force init validation error false on first render)
field.hideInitValidationError = false;
});
}
}
};
// wrap rendered callback to allow for UI treatment (dom focus, etc)
var _renderedCallback = function(field)
{
// if top level, apply a unique observable scope id
if (!field.parent)
{
field.observableScope = Alpaca.generateId();
}
// if we are the top-most control
// fire "ready" event on every control
// go down depth first and fire to lowest controls before trickling back up
if (!field.parent)
{
Alpaca.fireReady(field);
}
// if top level and focus has not been specified, then auto-set
if (Alpaca.isUndefined(options.focus) && !field.parent) {
options.focus = Alpaca.defaultFocus;
}
// auto-set the focus?
if (options && options.focus)
{
window.setTimeout(function() {
var doFocus = function(__field)
{
__field.suspendBlurFocus = true;
__field.focus();
__field.suspendBlurFocus = false;
};
if (options.focus)
{
if (field.isControlField && field.isAutoFocusable())
{
// just focus on this one
doFocus(field);
}
else if (field.isContainerField)
{
// if focus = true, then focus on the first child control if it is auto-focusable
// and not read-only
if (options.focus === true)
{
// pick first element in form
if (field.children && field.children.length > 0)
{
/*
for (var z = 0; z < field.children.length; z++)
{
if (field.children[z].isControlField)
{
if (field.children[z].isAutoFocusable() && !field.children[z].options.readonly)
{
doFocus(field.children[z]);
break;
}
}
}
*/
doFocus(field);
}
}
else if (typeof(options.focus) === "string")
{
// assume it is a path to the child
var child = field.getControlByPath(options.focus);
if (child && child.isControlField && child.isAutoFocusable())
{
doFocus(child);
}
}
}
_resetInitValidationError(field);
}
}, 500);
}
else
{
_resetInitValidationError(field);
}
if (renderedCallback)
{
renderedCallback(field);
}
};
loadAllConnector.loadAll({
"data": data,
"schema": schema,
"options": options,
"view": view,
"dataSource": dataSource,
"schemaSource": schemaSource,
"optionsSource": optionsSource,
"viewSource": viewSource
}, function(loadedData, loadedOptions, loadedSchema, loadedView) {
// for cases where things could not be loaded via source loaders, fall back to what may have been passed
// in directly as values
loadedData = loadedData ? loadedData : data;
loadedSchema = loadedSchema ? loadedSchema: schema;
loadedOptions = loadedOptions ? loadedOptions : options;
loadedView = loadedView ? loadedView : view;
// some defaults for the case where data is null
// if schema + options are not provided, we assume a text field
if (Alpaca.isEmpty(loadedData))
{
if (Alpaca.isEmpty(loadedSchema) && (Alpaca.isEmpty(loadedOptions) || Alpaca.isEmpty(loadedOptions.type)))
{
loadedData = "";
if (Alpaca.isEmpty(loadedOptions))
{
loadedOptions = "text";
}
else if (options && Alpaca.isObject(options))
{
loadedOptions.type = "text";
}
}
}
if (loadedOptions.view && !view)
{
loadedView = loadedOptions.view;
}
// init alpaca
return Alpaca.init(el, loadedData, loadedOptions, loadedSchema, loadedView, initialSettings, callback, _renderedCallback, connector, errorCallback);
}, function (loadError) {
errorCallback(loadError);
return null;
});
};
/**
* @namespace Namespace for all Alpaca Field Class Implementations.
*/
Alpaca.Fields = { };
/**
* @namespace Namespace for all Alpaca Connector Class Implementations.
*/
Alpaca.Connectors = { };
Alpaca.Extend = $.extend;
Alpaca.Create = function()
{
var args = Array.prototype.slice.call(arguments);
args.unshift({});
return $.extend.apply(this, args);
};
// static methods and properties
Alpaca.Extend(Alpaca,
/** @lends Alpaca */
{
/**
* Makes an array.
*
* @param {Any} nonArray A non-array variable.
* @returns {Array} Array out of the non-array variable.
*/
makeArray : function(nonArray) {
return Array.prototype.slice.call(nonArray);
},
/**
* Finds whether the type of a variable is function.
* @param {Any} obj The variable being evaluated.
* @returns {Boolean} True if the variable is a function, false otherwise.
*/
isFunction: function(obj) {
return Object.prototype.toString.call(obj) === "[object Function]";
},
/**
* Finds whether the type of a variable is string.
* @param {Any} obj The variable being evaluated.
* @returns {Boolean} True if the variable is a string, false otherwise.
*/
isString: function(obj) {
return (typeof obj === "string");
},
/**
* Finds whether the type of a variable is object.
* @param {Any} obj The variable being evaluated.
* @returns {Boolean} True if the variable is an object, false otherwise.
*/
isObject: function(obj) {
return !Alpaca.isUndefined(obj) && Object.prototype.toString.call(obj) === '[object Object]';
},
/**
* Finds whether the type of a variable is a plain, non-prototyped object.
* @param {Any} obj The variable being evaluated.
* @returns {Boolean} True if the variable is a plain object, false otherwise.
*/
isPlainObject: function(obj) {
return $.isPlainObject(obj);
},
/**
* Finds whether the type of a variable is number.
* @param {Any} obj The variable being evaluated.
* @returns {Boolean} True if the variable is a number, false otherwise.
*/
isNumber: function(obj) {
return (typeof obj === "number");
},
/**
* Finds whether the type of a variable is array.
* @param {Any} obj The variable being evaluated.
* @returns {Boolean} True if the variable is an array, false otherwise.
*/
isArray: function(obj) {
return Object.prototype.toString.call(obj) == "[object Array]";
},
/**
* Finds whether the type of a variable is boolean.
* @param {Any} obj The variable being evaluated.
* @returns {Boolean} True if the variable is a boolean, false otherwise.
*/
isBoolean: function(obj) {
return (typeof obj === "boolean");
},
/**
* Finds whether the type of a variable is undefined.
* @param {Any} obj The variable being evaluated.
* @returns {Boolean} True if the variable is a undefined, false otherwise.
*/
isUndefined: function(obj) {
return (typeof obj == "undefined");
},
/**
* Strips any excess whitespace characters from the given text.
* Returns the trimmed string.
*
* @param str
*
* @return trimmed string
*/
trim: function(text)
{
var trimmed = text;
if (trimmed && Alpaca.isString(trimmed))
{
trimmed = trimmed.replace(/^\s+|\s+$/g, '');
}
return trimmed;
},
/**
* Provides a safe conversion of an HTML textual string into a DOM object.
*
* @param x
* @return {*}
*/
safeDomParse: function(x)
{
if (x && Alpaca.isString(x))
{
x = Alpaca.trim(x);
// convert to dom
var converted = null;
try
{
converted = $(x);
}
catch (e)
{
// make another attempt to account for safety in some browsers
x = "<div>" + x + "</div>";
converted = $(x).children();
}
return converted;
}
return x;
},
/**
* Finds whether a variable is empty.
* @param {Any} obj The variable being evaluated.
* @param [boolean] includeFunctions whether to include functions in any counts
* @returns {Boolean} True if the variable is empty, false otherwise.
*/
isEmpty: function(obj, includeFunctions) {
var self = this;
if (Alpaca.isUndefined(obj))
{
return true;
}
else if (obj === null)
{
return true;
}
if (obj && Alpaca.isObject(obj))
{
var count = self.countProperties(obj, includeFunctions);
if (count === 0)
{
return true;
}
}
return false;
},
/**
* Counts the number of properties in an object.
*
* @param obj
* @param includeFunctions
*
* @returns {number}
*/
countProperties: function(obj, includeFunctions) {
var count = 0;
if (obj && Alpaca.isObject(obj))
{
for (var k in obj)
{
if (obj.hasOwnProperty(k))
{
if (includeFunctions) {
count++;
} else {
if (typeof(obj[k]) !== "function") {
count++;
}
}
}
}
}
return count;
},
/**
* Produces a copy of the given JS value.
*
* If the value is a simple array or a simple object, then a pure copy is produced.
*
* If it's a complex object or a function, then the reference is copied (i.e. not truly a copy).
*
* @param thing
* @return {*}
*/
copyOf: function(thing)
{
var copy = thing;
if (Alpaca.isArray(thing))
{
copy = [];
for (var i = 0; i < thing.length; i++)
{
copy.push(Alpaca.copyOf(thing[i]));
}
}
else if (Alpaca.isObject(thing))
{
if (thing instanceof Date)
{
// date
return new Date(thing.getTime());
}
else if (thing instanceof RegExp)
{
// regular expression
return new RegExp(thing);
}
else if (thing.nodeType && "cloneNode" in thing)
{
// DOM node
copy = thing.cloneNode(true);
}
else if ($.isPlainObject(thing))
{
copy = {};
for (var k in thing)
{
if (thing.hasOwnProperty(k))
{
copy[k] = Alpaca.copyOf(thing[k]);
}
}
}
else
{
// otherwise, it's some other kind of object so we just do a referential copy
// in other words, not a copy
}
}
return copy;
},
copyInto: function(target, source)
{
for (var i in source)
{
if (source.hasOwnProperty(i) && !this.isFunction(this[i]))
{
target[i] = source[i];
}
}
},
/**
* Retained for legacy purposes. Alias for copyOf().
*
* @param object
* @returns {*}
*/
cloneObject: function(object)
{
return Alpaca.copyOf(object);
},
/**
* Splices a string.
*
* @param {String} source Source string to be spliced.
* @param {Integer} splicePoint Splice location.
* @param {String} splice String to be spliced in.
* @returns {String} Spliced string
*/
spliceIn: function(source, splicePoint, splice) {
return source.substring(0, splicePoint) + splice + source.substring(splicePoint, source.length);
},
/**
* Compacts an array.
*
* @param {Array} arr Source array to be compacted.
* @returns {Array} Compacted array.
*/
compactArray: function(arr) {
var n = [], l = arr.length,i;
for (i = 0; i < l; i++) {
if (!lang.isNull(arr[i]) && !lang.isUndefined(arr[i])) {
n.push(arr[i]);
}
}
return n;
},
/**
* Removes accents from a string.
*
* @param {String} str Source string.
* @returns {String} Cleaned string without accents.
*/
removeAccents: function(str) {
return str.replace(/[àáâãäå]/g, "a").replace(/[èéêë]/g, "e").replace(/[ìíîï]/g, "i").replace(/[òóôõö]/g, "o").replace(/[ùúûü]/g, "u").replace(/[ýÿ]/g, "y").replace(/[ñ]/g, "n").replace(/[ç]/g, "c").replace(/[œ]/g, "oe").replace(/[æ]/g, "ae");
},
/**
* @private
* @param el
* @param arr
* @param fn
*/
indexOf: function(el, arr, fn) {
var l = arr.length,i;
if (!Alpaca.isFunction(fn)) {
/**
* @ignore
* @param elt
* @param arrElt
*/
fn = function(elt, arrElt) {
return elt === arrElt;
};
}
for (i = 0; i < l; i++) {
if (fn.call({}, el, arr[i])) {
return i;
}
}
return -1;
},
/**
* Static counter for generating a unique ID.
*/
uniqueIdCounter: 0,
/**
* Default Locale.
*/
defaultLocale: "en_US",
/**
* Whether to set focus by default
*/
defaultFocus: true,
/**
* The default sort function to use for enumerations.
*/
defaultSort: function(a, b) {
if (a.text > b.text) {
return 1;
}
else if (a.text < b.text) {
return -1;
}
return 0;
},
/**
* Sets the default Locale.
*
* @param {String} locale New default locale.
*/
setDefaultLocale: function(locale) {
this.defaultLocale = locale;
},
/**
* Field Type to Schema Type Mappings.
*/
defaultSchemaFieldMapping: {},
/**
* Registers a field type to schema data type mapping.
*
* @param {String} schemaType Schema data type.
* @param {String} fieldType Field type.
*/
registerDefaultSchemaFieldMapping: function(schemaType, fieldType) {
if (schemaType && fieldType) {
this.defaultSchemaFieldMapping[schemaType] = fieldType;
}
},
/**
* Field Type to Schema Format Mappings.
*/
defaultFormatFieldMapping: {},
/**
* Registers a field type to schema format mapping.
*
* @param {String} format Schema format.
* @param {String} fieldType Field type.
*/
registerDefaultFormatFieldMapping: function(format, fieldType) {
if (format && fieldType) {
this.defaultFormatFieldMapping[format] = fieldType;
}
},
/**
* Gets schema type of a variable.
*
* @param {Any} data The variable.
* @returns {String} Schema type of the variable.
*/
getSchemaType: function(data) {
var schemaType = null;
// map data types to default field types
if (Alpaca.isEmpty(data)) {
schemaType = "string";
}
else if (Alpaca.isArray(data)) {
schemaType = "array";
}
else if (Alpaca.isObject(data)) {
schemaType = "object";
}
else if (Alpaca.isString(data)) {
schemaType = "string";
}
else if (Alpaca.isNumber(data)) {
schemaType = "number";
}
else if (Alpaca.isBoolean(data)) {
schemaType = "boolean";
}
// Last check for data that carries functions -- GitanaConnector case.
if (!schemaType && (typeof data === 'object')) {
schemaType = "object";
}
return schemaType;
},
/**
* Returns the first non-null type for optional fields where schema.type is an array.
* (type: ["string", "null"] is a valid way of defining an optional field type.)
* If the array only contains a single value, then returns that value.
* Returns schemaType if the value is not an array.
* @param schemaType
* @returns {string} the field type
*/
schemaTypeFromArray: function(schemaType)
{
if (!Alpaca.isArray(schemaType)) { return schemaType }
if (schemaType.length === 1) { return schemaType[0] }
for (var i = 0; i < schemaType.length; i++) {
if (schemaType[i] === 'null') continue;
return schemaType[i];
}
return null;
},
/**
* Makes a best guess at the options field type if none provided.
*
* @param schema
* @returns {string} the field type
*/
guessOptionsType: function(schema)
{
// check if it has format defined
if (schema.format && Alpaca.defaultFormatFieldMapping[schema.format])
{
return Alpaca.defaultFormatFieldMapping[schema.format];
}
if (schema && typeof(schema["enum"]) !== "undefined")
{
if (schema["enum"].length > 3)
{
return "select";
}
else
{
return "radio";
}
}
// type: ["string", "null"] is a valid way of defining an optional
// field that can be either a string, or null. Use the first non-null type.
var schemaType = Alpaca.schemaTypeFromArray(schema.type)
return Alpaca.defaultSchemaFieldMapping[schemaType];
},
/**
* Alpaca Views.
*/
views: {},
/**
* Generates a valid view id.
*
* @returns {String} A valid unique view id.
*/
generateViewId : function () {