UNPKG

26.8 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
8
9var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
10
11exports.getDefaultRegistry = getDefaultRegistry;
12exports.getSchemaType = getSchemaType;
13exports.getWidget = getWidget;
14exports.getDefaultFormState = getDefaultFormState;
15exports.getUiOptions = getUiOptions;
16exports.isObject = isObject;
17exports.mergeObjects = mergeObjects;
18exports.asNumber = asNumber;
19exports.orderProperties = orderProperties;
20exports.isConstant = isConstant;
21exports.toConstant = toConstant;
22exports.isSelect = isSelect;
23exports.isMultiSelect = isMultiSelect;
24exports.isFilesArray = isFilesArray;
25exports.isFixedItems = isFixedItems;
26exports.allowAdditionalItems = allowAdditionalItems;
27exports.optionsList = optionsList;
28exports.retrieveSchema = retrieveSchema;
29exports.deepEquals = deepEquals;
30exports.shouldRender = shouldRender;
31exports.toIdSchema = toIdSchema;
32exports.parseDateString = parseDateString;
33exports.toDateString = toDateString;
34exports.pad = pad;
35exports.setState = setState;
36exports.dataURItoBlob = dataURItoBlob;
37exports.rangeSpec = rangeSpec;
38
39var _react = require("react");
40
41var _react2 = _interopRequireDefault(_react);
42
43require("setimmediate");
44
45var _validate = require("./validate");
46
47var _validate2 = _interopRequireDefault(_validate);
48
49function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
50
51function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
52
53function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
54
55function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
56
57var widgetMap = {
58 boolean: {
59 checkbox: "CheckboxWidget",
60 radio: "RadioWidget",
61 select: "SelectWidget",
62 hidden: "HiddenWidget"
63 },
64 string: {
65 text: "TextWidget",
66 password: "PasswordWidget",
67 email: "EmailWidget",
68 hostname: "TextWidget",
69 ipv4: "TextWidget",
70 ipv6: "TextWidget",
71 uri: "URLWidget",
72 "data-url": "FileWidget",
73 radio: "RadioWidget",
74 select: "SelectWidget",
75 textarea: "TextareaWidget",
76 hidden: "HiddenWidget",
77 date: "DateWidget",
78 datetime: "DateTimeWidget",
79 "date-time": "DateTimeWidget",
80 "alt-date": "AltDateWidget",
81 "alt-datetime": "AltDateTimeWidget",
82 color: "ColorWidget",
83 file: "FileWidget"
84 },
85 number: {
86 text: "TextWidget",
87 select: "SelectWidget",
88 updown: "UpDownWidget",
89 range: "RangeWidget",
90 radio: "RadioWidget",
91 hidden: "HiddenWidget"
92 },
93 integer: {
94 text: "TextWidget",
95 select: "SelectWidget",
96 updown: "UpDownWidget",
97 range: "RangeWidget",
98 radio: "RadioWidget",
99 hidden: "HiddenWidget"
100 },
101 array: {
102 select: "SelectWidget",
103 checkboxes: "CheckboxesWidget",
104 files: "FileWidget"
105 }
106};
107
108function getDefaultRegistry() {
109 return {
110 fields: require("./components/fields").default,
111 widgets: require("./components/widgets").default,
112 definitions: {},
113 formContext: {}
114 };
115}
116
117function getSchemaType(schema) {
118 var type = schema.type;
119
120 if (!type && schema.enum) {
121 type = "string";
122 }
123 return type;
124}
125
126function getWidget(schema, widget) {
127 var registeredWidgets = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
128
129 var type = getSchemaType(schema);
130
131 function mergeOptions(Widget) {
132 // cache return value as property of widget for proper react reconciliation
133 if (!Widget.MergedWidget) {
134 (function () {
135 var defaultOptions = Widget.defaultProps && Widget.defaultProps.options || {};
136 Widget.MergedWidget = function (_ref) {
137 var _ref$options = _ref.options,
138 options = _ref$options === undefined ? {} : _ref$options,
139 props = _objectWithoutProperties(_ref, ["options"]);
140
141 return _react2.default.createElement(Widget, _extends({ options: _extends({}, defaultOptions, options) }, props));
142 };
143 })();
144 }
145 return Widget.MergedWidget;
146 }
147
148 if (typeof widget === "function") {
149 return mergeOptions(widget);
150 }
151
152 if (typeof widget !== "string") {
153 throw new Error("Unsupported widget definition: " + (typeof widget === "undefined" ? "undefined" : _typeof(widget)));
154 }
155
156 if (registeredWidgets.hasOwnProperty(widget)) {
157 var registeredWidget = registeredWidgets[widget];
158 return getWidget(schema, registeredWidget, registeredWidgets);
159 }
160
161 if (!widgetMap.hasOwnProperty(type)) {
162 throw new Error("No widget for type \"" + type + "\"");
163 }
164
165 if (widgetMap[type].hasOwnProperty(widget)) {
166 var _registeredWidget = registeredWidgets[widgetMap[type][widget]];
167 return getWidget(schema, _registeredWidget, registeredWidgets);
168 }
169
170 throw new Error("No widget \"" + widget + "\" for type \"" + type + "\"");
171}
172
173function computeDefaults(schema, parentDefaults) {
174 var definitions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
175
176 // Compute the defaults recursively: give highest priority to deepest nodes.
177 var defaults = parentDefaults;
178 if (isObject(defaults) && isObject(schema.default)) {
179 // For object defaults, only override parent defaults that are defined in
180 // schema.default.
181 defaults = mergeObjects(defaults, schema.default);
182 } else if ("default" in schema) {
183 // Use schema defaults for this node.
184 defaults = schema.default;
185 } else if ("$ref" in schema) {
186 // Use referenced schema defaults for this node.
187 var refSchema = findSchemaDefinition(schema.$ref, definitions);
188 return computeDefaults(refSchema, defaults, definitions);
189 } else if (isFixedItems(schema)) {
190 defaults = schema.items.map(function (itemSchema) {
191 return computeDefaults(itemSchema, undefined, definitions);
192 });
193 }
194 // Not defaults defined for this node, fallback to generic typed ones.
195 if (typeof defaults === "undefined") {
196 defaults = schema.default;
197 }
198
199 switch (schema.type) {
200 // We need to recur for object schema inner default values.
201 case "object":
202 return Object.keys(schema.properties || {}).reduce(function (acc, key) {
203 // Compute the defaults for this node, with the parent defaults we might
204 // have from a previous run: defaults[key].
205 acc[key] = computeDefaults(schema.properties[key], (defaults || {})[key], definitions);
206 return acc;
207 }, {});
208
209 case "array":
210 if (schema.minItems) {
211 if (!isMultiSelect(schema, definitions)) {
212 var defaultsLength = defaults ? defaults.length : 0;
213 if (schema.minItems > defaultsLength) {
214 var defaultEntries = defaults || [];
215 // populate the array with the defaults
216 var fillerEntries = new Array(schema.minItems - defaultsLength).fill(computeDefaults(schema.items, schema.items.defaults, definitions));
217 // then fill up the rest with either the item default or empty, up to minItems
218
219 return defaultEntries.concat(fillerEntries);
220 }
221 } else {
222 return [];
223 }
224 }
225 }
226 return defaults;
227}
228
229function getDefaultFormState(_schema, formData) {
230 var definitions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
231
232 if (!isObject(_schema)) {
233 throw new Error("Invalid schema: " + _schema);
234 }
235 var schema = retrieveSchema(_schema, definitions, formData);
236 var defaults = computeDefaults(schema, _schema.default, definitions);
237 if (typeof formData === "undefined") {
238 // No form data? Use schema defaults.
239 return defaults;
240 }
241 if (isObject(formData)) {
242 // Override schema defaults with form data.
243 return mergeObjects(defaults, formData);
244 }
245 return formData || defaults;
246}
247
248function getUiOptions(uiSchema) {
249 // get all passed options from ui:widget, ui:options, and ui:<optionName>
250 return Object.keys(uiSchema).filter(function (key) {
251 return key.indexOf("ui:") === 0;
252 }).reduce(function (options, key) {
253 var value = uiSchema[key];
254
255 if (key === "ui:widget" && isObject(value)) {
256 console.warn("Setting options via ui:widget object is deprecated, use ui:options instead");
257 return _extends({}, options, value.options || {}, {
258 widget: value.component
259 });
260 }
261 if (key === "ui:options" && isObject(value)) {
262 return _extends({}, options, value);
263 }
264 return _extends({}, options, _defineProperty({}, key.substring(3), value));
265 }, {});
266}
267
268function isObject(thing) {
269 return (typeof thing === "undefined" ? "undefined" : _typeof(thing)) === "object" && thing !== null && !Array.isArray(thing);
270}
271
272function mergeObjects(obj1, obj2) {
273 var concatArrays = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
274
275 // Recursively merge deeply nested objects.
276 var acc = Object.assign({}, obj1); // Prevent mutation of source object.
277 return Object.keys(obj2).reduce(function (acc, key) {
278 var left = obj1[key],
279 right = obj2[key];
280 if (obj1.hasOwnProperty(key) && isObject(right)) {
281 acc[key] = mergeObjects(left, right, concatArrays);
282 } else if (concatArrays && Array.isArray(left) && Array.isArray(right)) {
283 acc[key] = left.concat(right);
284 } else {
285 acc[key] = right;
286 }
287 return acc;
288 }, acc);
289}
290
291function asNumber(value) {
292 if (value === "") {
293 return undefined;
294 }
295 if (/\.$/.test(value)) {
296 // "3." can't really be considered a number even if it parses in js. The
297 // user is most likely entering a float.
298 return value;
299 }
300 if (/\.0$/.test(value)) {
301 // we need to return this as a string here, to allow for input like 3.07
302 return value;
303 }
304 var n = Number(value);
305 var valid = typeof n === "number" && !Number.isNaN(n);
306
307 if (/\.\d*0$/.test(value)) {
308 // It's a number, that's cool - but we need it as a string so it doesn't screw
309 // with the user when entering dollar amounts or other values (such as those with
310 // specific precision or number of significant digits)
311 return value;
312 }
313
314 return valid ? n : value;
315}
316
317function orderProperties(properties, order) {
318 if (!Array.isArray(order)) {
319 return properties;
320 }
321
322 var arrayToHash = function arrayToHash(arr) {
323 return arr.reduce(function (prev, curr) {
324 prev[curr] = true;
325 return prev;
326 }, {});
327 };
328 var errorPropList = function errorPropList(arr) {
329 return arr.length > 1 ? "properties '" + arr.join("', '") + "'" : "property '" + arr[0] + "'";
330 };
331 var propertyHash = arrayToHash(properties);
332 var orderHash = arrayToHash(order);
333 var extraneous = order.filter(function (prop) {
334 return prop !== "*" && !propertyHash[prop];
335 });
336 if (extraneous.length) {
337 throw new Error("uiSchema order list contains extraneous " + errorPropList(extraneous));
338 }
339 var rest = properties.filter(function (prop) {
340 return !orderHash[prop];
341 });
342 var restIndex = order.indexOf("*");
343 if (restIndex === -1) {
344 if (rest.length) {
345 throw new Error("uiSchema order list does not contain " + errorPropList(rest));
346 }
347 return order;
348 }
349 if (restIndex !== order.lastIndexOf("*")) {
350 throw new Error("uiSchema order list contains more than one wildcard item");
351 }
352
353 var complete = [].concat(_toConsumableArray(order));
354 complete.splice.apply(complete, [restIndex, 1].concat(_toConsumableArray(rest)));
355 return complete;
356}
357
358/**
359 * This function checks if the given schema matches a single
360 * constant value.
361 */
362function isConstant(schema) {
363 return Array.isArray(schema.enum) && schema.enum.length === 1 || schema.hasOwnProperty("const");
364}
365
366function toConstant(schema) {
367 if (Array.isArray(schema.enum) && schema.enum.length === 1) {
368 return schema.enum[0];
369 } else if (schema.hasOwnProperty("const")) {
370 return schema.const;
371 } else {
372 throw new Error("schema cannot be inferred as a constant");
373 }
374}
375
376function isSelect(_schema) {
377 var definitions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
378
379 var schema = retrieveSchema(_schema, definitions);
380 var altSchemas = schema.oneOf || schema.anyOf;
381 if (Array.isArray(schema.enum)) {
382 return true;
383 } else if (Array.isArray(altSchemas)) {
384 return altSchemas.every(function (altSchemas) {
385 return isConstant(altSchemas);
386 });
387 }
388 return false;
389}
390
391function isMultiSelect(schema) {
392 var definitions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
393
394 if (!schema.uniqueItems || !schema.items) {
395 return false;
396 }
397 return isSelect(schema.items, definitions);
398}
399
400function isFilesArray(schema, uiSchema) {
401 var definitions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
402
403 if (uiSchema["ui:widget"] === "files") {
404 return true;
405 } else if (schema.items) {
406 var itemsSchema = retrieveSchema(schema.items, definitions);
407 return itemsSchema.type === "string" && itemsSchema.format === "data-url";
408 }
409 return false;
410}
411
412function isFixedItems(schema) {
413 return Array.isArray(schema.items) && schema.items.length > 0 && schema.items.every(function (item) {
414 return isObject(item);
415 });
416}
417
418function allowAdditionalItems(schema) {
419 if (schema.additionalItems === true) {
420 console.warn("additionalItems=true is currently not supported");
421 }
422 return isObject(schema.additionalItems);
423}
424
425function optionsList(schema) {
426 if (schema.enum) {
427 return schema.enum.map(function (value, i) {
428 var label = schema.enumNames && schema.enumNames[i] || String(value);
429 return { label: label, value: value };
430 });
431 } else {
432 var altSchemas = schema.oneOf || schema.anyOf;
433 return altSchemas.map(function (schema, i) {
434 var value = toConstant(schema);
435 var label = schema.title || String(value);
436 return { label: label, value: value };
437 });
438 }
439}
440
441function findSchemaDefinition($ref) {
442 var definitions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
443
444 // Extract and use the referenced definition if we have it.
445 var match = /^#\/definitions\/(.*)$/.exec($ref);
446 if (match && match[1]) {
447 var parts = match[1].split("/");
448 var current = definitions;
449 var _iteratorNormalCompletion = true;
450 var _didIteratorError = false;
451 var _iteratorError = undefined;
452
453 try {
454 for (var _iterator = parts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
455 var part = _step.value;
456
457 part = part.replace(/~1/g, "/").replace(/~0/g, "~");
458 if (current.hasOwnProperty(part)) {
459 current = current[part];
460 } else {
461 // No matching definition found, that's an error (bogus schema?)
462 throw new Error("Could not find a definition for " + $ref + ".");
463 }
464 }
465 } catch (err) {
466 _didIteratorError = true;
467 _iteratorError = err;
468 } finally {
469 try {
470 if (!_iteratorNormalCompletion && _iterator.return) {
471 _iterator.return();
472 }
473 } finally {
474 if (_didIteratorError) {
475 throw _iteratorError;
476 }
477 }
478 }
479
480 return current;
481 }
482
483 // No matching definition found, that's an error (bogus schema?)
484 throw new Error("Could not find a definition for " + $ref + ".");
485}
486
487function retrieveSchema(schema) {
488 var definitions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
489 var formData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
490
491 if (schema.hasOwnProperty("$ref")) {
492 // Retrieve the referenced schema definition.
493 var $refSchema = findSchemaDefinition(schema.$ref, definitions);
494 // Drop the $ref property of the source schema.
495
496 var $ref = schema.$ref,
497 localSchema = _objectWithoutProperties(schema, ["$ref"]);
498 // Update referenced schema definition with local schema properties.
499
500
501 return retrieveSchema(_extends({}, $refSchema, localSchema), definitions, formData);
502 } else if (schema.hasOwnProperty("dependencies")) {
503 var resolvedSchema = resolveDependencies(schema, definitions, formData);
504 return retrieveSchema(resolvedSchema, definitions, formData);
505 } else {
506 // No $ref or dependencies attribute found, returning the original schema.
507 return schema;
508 }
509}
510
511function resolveDependencies(schema, definitions, formData) {
512 // Drop the dependencies from the source schema.
513 var _schema$dependencies = schema.dependencies,
514 dependencies = _schema$dependencies === undefined ? {} : _schema$dependencies,
515 resolvedSchema = _objectWithoutProperties(schema, ["dependencies"]);
516 // Process dependencies updating the local schema properties as appropriate.
517
518
519 for (var dependencyKey in dependencies) {
520 // Skip this dependency if its trigger property is not present.
521 if (formData[dependencyKey] === undefined) {
522 continue;
523 }
524 var dependencyValue = dependencies[dependencyKey];
525 if (Array.isArray(dependencyValue)) {
526 resolvedSchema = withDependentProperties(resolvedSchema, dependencyValue);
527 } else if (isObject(dependencyValue)) {
528 resolvedSchema = withDependentSchema(resolvedSchema, definitions, formData, dependencyKey, dependencyValue);
529 }
530 }
531 return resolvedSchema;
532}
533
534function withDependentProperties(schema, additionallyRequired) {
535 if (!additionallyRequired) {
536 return schema;
537 }
538 var required = Array.isArray(schema.required) ? Array.from(new Set([].concat(_toConsumableArray(schema.required), _toConsumableArray(additionallyRequired)))) : additionallyRequired;
539 return _extends({}, schema, { required: required });
540}
541
542function withDependentSchema(schema, definitions, formData, dependencyKey, dependencyValue) {
543 var _retrieveSchema = retrieveSchema(dependencyValue, definitions, formData),
544 oneOf = _retrieveSchema.oneOf,
545 dependentSchema = _objectWithoutProperties(_retrieveSchema, ["oneOf"]);
546
547 schema = mergeSchemas(schema, dependentSchema);
548 return oneOf === undefined ? schema : withExactlyOneSubschema(schema, definitions, formData, dependencyKey, oneOf);
549}
550
551function withExactlyOneSubschema(schema, definitions, formData, dependencyKey, oneOf) {
552 if (!Array.isArray(oneOf)) {
553 throw new Error("invalid oneOf: it is some " + (typeof oneOf === "undefined" ? "undefined" : _typeof(oneOf)) + " instead of an array");
554 }
555 var validSubschemas = oneOf.filter(function (subschema) {
556 if (!subschema.properties) {
557 return false;
558 }
559 var conditionPropertySchema = subschema.properties[dependencyKey];
560
561 if (conditionPropertySchema) {
562 var conditionSchema = {
563 type: "object",
564 properties: _defineProperty({}, dependencyKey, conditionPropertySchema)
565 };
566
567 var _validateFormData = (0, _validate2.default)(formData, conditionSchema),
568 errors = _validateFormData.errors;
569
570 return errors.length === 0;
571 }
572 });
573 if (validSubschemas.length !== 1) {
574 console.warn("ignoring oneOf in dependencies because there isn't exactly one subschema that is valid");
575 return schema;
576 }
577 var subschema = validSubschemas[0];
578
579 var _subschema$properties = subschema.properties,
580 conditionPropertySchema = _subschema$properties[dependencyKey],
581 dependentSubschema = _objectWithoutProperties(_subschema$properties, [dependencyKey]);
582
583 var dependentSchema = _extends({}, subschema, { properties: dependentSubschema });
584 return mergeSchemas(schema, retrieveSchema(dependentSchema, definitions, formData));
585}
586
587function mergeSchemas(schema1, schema2) {
588 return mergeObjects(schema1, schema2, true);
589}
590
591function isArguments(object) {
592 return Object.prototype.toString.call(object) === "[object Arguments]";
593}
594
595function deepEquals(a, b) {
596 var ca = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
597 var cb = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
598
599 // Partially extracted from node-deeper and adapted to exclude comparison
600 // checks for functions.
601 // https://github.com/othiym23/node-deeper
602 if (a === b) {
603 return true;
604 } else if (typeof a === "function" || typeof b === "function") {
605 // Assume all functions are equivalent
606 // see https://github.com/mozilla-services/react-jsonschema-form/issues/255
607 return true;
608 } else if ((typeof a === "undefined" ? "undefined" : _typeof(a)) !== "object" || (typeof b === "undefined" ? "undefined" : _typeof(b)) !== "object") {
609 return false;
610 } else if (a === null || b === null) {
611 return false;
612 } else if (a instanceof Date && b instanceof Date) {
613 return a.getTime() === b.getTime();
614 } else if (a instanceof RegExp && b instanceof RegExp) {
615 return a.source === b.source && a.global === b.global && a.multiline === b.multiline && a.lastIndex === b.lastIndex && a.ignoreCase === b.ignoreCase;
616 } else if (isArguments(a) || isArguments(b)) {
617 if (!(isArguments(a) && isArguments(b))) {
618 return false;
619 }
620 var slice = Array.prototype.slice;
621 return deepEquals(slice.call(a), slice.call(b), ca, cb);
622 } else {
623 if (a.constructor !== b.constructor) {
624 return false;
625 }
626
627 var ka = Object.keys(a);
628 var kb = Object.keys(b);
629 // don't bother with stack acrobatics if there's nothing there
630 if (ka.length === 0 && kb.length === 0) {
631 return true;
632 }
633 if (ka.length !== kb.length) {
634 return false;
635 }
636
637 var cal = ca.length;
638 while (cal--) {
639 if (ca[cal] === a) {
640 return cb[cal] === b;
641 }
642 }
643 ca.push(a);
644 cb.push(b);
645
646 ka.sort();
647 kb.sort();
648 for (var j = ka.length - 1; j >= 0; j--) {
649 if (ka[j] !== kb[j]) {
650 return false;
651 }
652 }
653
654 var key = void 0;
655 for (var k = ka.length - 1; k >= 0; k--) {
656 key = ka[k];
657 if (!deepEquals(a[key], b[key], ca, cb)) {
658 return false;
659 }
660 }
661
662 ca.pop();
663 cb.pop();
664
665 return true;
666 }
667}
668
669function shouldRender(comp, nextProps, nextState) {
670 var props = comp.props,
671 state = comp.state;
672
673 return !deepEquals(props, nextProps) || !deepEquals(state, nextState);
674}
675
676function toIdSchema(schema, id, definitions) {
677 var formData = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
678 var idPrefix = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : "root";
679
680 var idSchema = {
681 $id: id || idPrefix
682 };
683 if ("$ref" in schema) {
684 var _schema = retrieveSchema(schema, definitions, formData);
685 return toIdSchema(_schema, id, definitions, formData, idPrefix);
686 }
687 if ("items" in schema && !schema.items.$ref) {
688 return toIdSchema(schema.items, id, definitions, formData, idPrefix);
689 }
690 if (schema.type !== "object") {
691 return idSchema;
692 }
693 for (var name in schema.properties || {}) {
694 var field = schema.properties[name];
695 var fieldId = idSchema.$id + "_" + name;
696 idSchema[name] = toIdSchema(field, fieldId, definitions, formData[name], idPrefix);
697 }
698 return idSchema;
699}
700
701function parseDateString(dateString) {
702 var includeTime = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
703
704 if (!dateString) {
705 return {
706 year: -1,
707 month: -1,
708 day: -1,
709 hour: includeTime ? -1 : 0,
710 minute: includeTime ? -1 : 0,
711 second: includeTime ? -1 : 0
712 };
713 }
714 var date = new Date(dateString);
715 if (Number.isNaN(date.getTime())) {
716 throw new Error("Unable to parse date " + dateString);
717 }
718 return {
719 year: date.getUTCFullYear(),
720 month: date.getUTCMonth() + 1, // oh you, javascript.
721 day: date.getUTCDate(),
722 hour: includeTime ? date.getUTCHours() : 0,
723 minute: includeTime ? date.getUTCMinutes() : 0,
724 second: includeTime ? date.getUTCSeconds() : 0
725 };
726}
727
728function toDateString(_ref2) {
729 var year = _ref2.year,
730 month = _ref2.month,
731 day = _ref2.day,
732 _ref2$hour = _ref2.hour,
733 hour = _ref2$hour === undefined ? 0 : _ref2$hour,
734 _ref2$minute = _ref2.minute,
735 minute = _ref2$minute === undefined ? 0 : _ref2$minute,
736 _ref2$second = _ref2.second,
737 second = _ref2$second === undefined ? 0 : _ref2$second;
738 var time = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
739
740 var utcTime = Date.UTC(year, month - 1, day, hour, minute, second);
741 var datetime = new Date(utcTime).toJSON();
742 return time ? datetime : datetime.slice(0, 10);
743}
744
745function pad(num, size) {
746 var s = String(num);
747 while (s.length < size) {
748 s = "0" + s;
749 }
750 return s;
751}
752
753function setState(instance, state, callback) {
754 var safeRenderCompletion = instance.props.safeRenderCompletion;
755
756 if (safeRenderCompletion) {
757 instance.setState(state, callback);
758 } else {
759 instance.setState(state);
760 setImmediate(callback);
761 }
762}
763
764function dataURItoBlob(dataURI) {
765 // Split metadata from data
766 var splitted = dataURI.split(",");
767 // Split params
768 var params = splitted[0].split(";");
769 // Get mime-type from params
770 var type = params[0].replace("data:", "");
771 // Filter the name property from params
772 var properties = params.filter(function (param) {
773 return param.split("=")[0] === "name";
774 });
775 // Look for the name and use unknown if no name property.
776 var name = void 0;
777 if (properties.length !== 1) {
778 name = "unknown";
779 } else {
780 // Because we filtered out the other property,
781 // we only have the name case here.
782 name = properties[0].split("=")[1];
783 }
784
785 // Built the Uint8Array Blob parameter from the base64 string.
786 var binary = atob(splitted[1]);
787 var array = [];
788 for (var i = 0; i < binary.length; i++) {
789 array.push(binary.charCodeAt(i));
790 }
791 // Create the blob object
792 var blob = new window.Blob([new Uint8Array(array)], { type: type });
793
794 return { blob: blob, name: name };
795}
796
797function rangeSpec(schema) {
798 var spec = {};
799 if (schema.multipleOf) {
800 spec.step = schema.multipleOf;
801 }
802 if (schema.minimum || schema.minimum === 0) {
803 spec.min = schema.minimum;
804 }
805 if (schema.maximum || schema.maximum === 0) {
806 spec.max = schema.maximum;
807 }
808 return spec;
809}
\No newline at end of file