Skip to content
This repository was archived by the owner on Aug 5, 2021. It is now read-only.

Commit 7224daf

Browse files
committed
got working on IE
1 parent 3f3de5b commit 7224daf

File tree

8 files changed

+2859
-51
lines changed

8 files changed

+2859
-51
lines changed

.babelrc

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"plugins": [
3+
"@babel/plugin-transform-destructuring",
4+
"@babel/plugin-transform-template-literals",
5+
"@babel/plugin-proposal-class-properties",
6+
"@babel/plugin-transform-arrow-functions",
7+
"@babel/plugin-transform-classes"
8+
]
9+
}

dist/json-schema-validator.js

Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
1+
'use strict';
2+
/*global customElements*/
3+
4+
/*global HTMLElement*/
5+
6+
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
7+
8+
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
9+
10+
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
11+
12+
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
13+
14+
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15+
16+
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
17+
18+
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
19+
20+
function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
21+
22+
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
23+
24+
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
25+
26+
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
27+
28+
function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
29+
30+
function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
31+
32+
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
33+
34+
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
35+
36+
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
37+
38+
(function () {
39+
let JSONSchemaValidator =
40+
/*#__PURE__*/
41+
function (_HTMLElement) {
42+
_inherits(JSONSchemaValidator, _HTMLElement);
43+
44+
function JSONSchemaValidator() {
45+
var _this;
46+
47+
_classCallCheck(this, JSONSchemaValidator);
48+
49+
// establish prototype chain
50+
_this = _possibleConstructorReturn(this, _getPrototypeOf(JSONSchemaValidator).call(this));
51+
_this.default_ajv_url = 'https://unpkg.com/ajv@6.5.5/dist/ajv.min.js';
52+
_this.default_json_editor_url = 'https://unpkg.com/jsoneditor@5.25.0';
53+
_this.promises = {};
54+
return _this;
55+
}
56+
57+
_createClass(JSONSchemaValidator, [{
58+
key: "connectedCallback",
59+
// fires after the element has been attached to the DOM
60+
value: function connectedCallback() {
61+
const uid = Math.ceil((Math.random() * 10e10).toString());
62+
this.id = "schema-validator-".concat(uid);
63+
this.innerHTML = "<div>\n <div id=\"jsoneditor\" style=\"box-sizing: border-box; height: 500px; padding: 15px; width: 100%;\"></div>\n <div id=\"schema-validation-errors\" style=\"box-sizing: border-box; padding: 15px; width: 100%;\"></div>\n <link href=\"".concat(this.json_editor_url, "/dist/jsoneditor.min.css\" rel=\"stylesheet\" type=\"text/css\">\n </div>");
64+
this.update();
65+
}
66+
}, {
67+
key: "attributeChangedCallback",
68+
value: function attributeChangedCallback(attrName, oldVal, newVal) {
69+
if (attrName === 'schema') {
70+
this.update();
71+
}
72+
}
73+
}, {
74+
key: "getHTML",
75+
value: function getHTML() {
76+
return '<div><textarea onChange=style="box-sizing: border-box; height: 500px; padding: 15px; resize: none; width: 100%;"></textarea></div>';
77+
}
78+
}, {
79+
key: "getJSON",
80+
value: function getJSON(url) {
81+
return new Promise(function (resolve) {
82+
var xhr = new XMLHttpRequest();
83+
84+
xhr.onreadystatechange = function () {
85+
if (xhr.readyState === 4) {
86+
resolve(JSON.parse(xhr.response));
87+
}
88+
};
89+
90+
xhr.open('GET', url, true);
91+
xhr.send('');
92+
});
93+
}
94+
}, {
95+
key: "getMetaSchema",
96+
value: function getMetaSchema() {
97+
return this.getJSON(this.metaschemaurl);
98+
}
99+
}, {
100+
key: "getSchema",
101+
value: function getSchema() {
102+
return this.getJSON(this.schemaurl);
103+
}
104+
}, {
105+
key: "getAjv",
106+
value: function getAjv() {
107+
var _this2 = this;
108+
109+
return this.loadScript(this.ajv_url).then(function () {
110+
if (!_this2.ajv) {
111+
_this2.ajv = new window.Ajv({
112+
allErrors: true,
113+
schemaId: 'id'
114+
});
115+
}
116+
117+
return _this2.ajv;
118+
});
119+
}
120+
}, {
121+
key: "getJSONEditor",
122+
value: function getJSONEditor() {
123+
return this.loadScript(this.json_editor_url + '/dist/jsoneditor.min.js').then(function () {
124+
return window.JSONEditor;
125+
});
126+
}
127+
}, {
128+
key: "loadScript",
129+
value: function loadScript(url) {
130+
if (!this.promises[url]) {
131+
this.promises[url] = new Promise(function (resolve) {
132+
const script = document.createElement("script");
133+
script.src = url;
134+
script.onload = resolve;
135+
document.body.appendChild(script);
136+
});
137+
}
138+
139+
return Promise.resolve(this.promises[url]);
140+
}
141+
}, {
142+
key: "validateInput",
143+
value: function validateInput() {
144+
let errors;
145+
let parsed;
146+
console.log("starting validate");
147+
const text = this.querySelector('textarea').value;
148+
149+
try {
150+
parsed = JSON.parse(text);
151+
} catch (error) {
152+
console.error("Failed to parsed JSON. It appears that the user did not enter valid JSON");
153+
console.error(error);
154+
}
155+
156+
if (parsed) {
157+
this.validate(parsed);
158+
this.updateErrors(this.validate.errors);
159+
} else {
160+
this.updateErrors([{
161+
dataPath: "JSON File",
162+
message: "This does not appear to be a valid JSON file"
163+
}]);
164+
}
165+
}
166+
}, {
167+
key: "update",
168+
value: function update() {
169+
var _this3 = this;
170+
171+
this.ajv_url = this.getAttribute('ajv') || this.default_ajv_url;
172+
this.json_editor_url = this.getAttribute('jsoneditor') || this.default_json_editor_url;
173+
this.schemaurl = this.getAttribute('schema');
174+
this.metaschemaurl = this.getAttribute('metaschema');
175+
this.updated = Promise.all([this.getAjv(), this.getJSONEditor(), this.getMetaSchema(), this.getSchema()]).then(function (values) {
176+
const _values = _slicedToArray(values, 4),
177+
ajv = _values[0],
178+
JSONEditor = _values[1],
179+
metaschema = _values[2],
180+
schema = _values[3];
181+
182+
console.log("[ajv, JSONEditor, metaschema, schema]:", [ajv, JSONEditor, metaschema, schema]);
183+
184+
try {
185+
ajv.addMetaSchema(metaschema);
186+
} catch (error) {
187+
console.warn(error);
188+
}
189+
190+
if (!_this3.editor) {
191+
// create the editor
192+
var container = _this3.querySelector("#jsoneditor");
193+
194+
var options = {
195+
ajv: ajv,
196+
mode: 'text',
197+
modes: ['text', 'tree']
198+
};
199+
_this3.editor = new JSONEditor(container, options, '');
200+
201+
_this3.editor.setSchema(schema);
202+
203+
_this3.editor.setText('');
204+
}
205+
});
206+
}
207+
}, {
208+
key: "updateErrors",
209+
value: function updateErrors(errors) {
210+
const errorBox = document.getElementById("schema-validation-errors");
211+
console.log("err");
212+
213+
if (Array.isArray(errors) && errors.length > 0) {
214+
const numberOfProblems = errors.length;
215+
errorBox.innerHTML = "\n <div>Number of Problems: ".concat(numberOfProblems, "</div>\n ").concat(errors.map(function (error) {
216+
return "<div>".concat(error.dataPath, ": ").concat(error.message, "</div>");
217+
}).join(''), "\n ");
218+
} else {
219+
errorBox.innerHTML = '';
220+
}
221+
}
222+
}], [{
223+
key: "observedAttributes",
224+
get: function () {
225+
return ['ajv', 'jsoneditor', 'metaschema', 'schema'];
226+
}
227+
}]);
228+
229+
return JSONSchemaValidator;
230+
}(_wrapNativeSuper(HTMLElement)); // let the browser know about the custom element
231+
232+
233+
customElements.define('json-schema-validator', JSONSchemaValidator);
234+
})();

index.html

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,37 @@
22
<html>
33
<head>
44
<title>JSON Schema Validator Web Component Demo</title>
5-
<script src="./index.js"></script>
5+
<script src="polyfills/custom-elements.js"></script>
6+
<script src="polyfills/babel-polyfill.js"></script>
7+
<script src="dist/json-schema-validator.js"></script>
68
</head>
79
<body style="box-sizing: border-box; margin: 0 auto; max-width: 900px; padding: 50px; width: 100%;">
810
<div>
9-
<json-schema-validator jsoneditor="./node_modules/jsoneditor" metaschema="./json-schema-draft-04.json" schema="./example-schema.json" />
11+
<json-schema-validator jsoneditor="./node_modules/jsoneditor" metaschema="./json-schema-draft-04.json" schema="./example-schema.json"></json-schema-validator>
1012
</div>
1113
<script>
12-
setTimeout(() => {
13-
fetch("./example-data.json")
14-
.then(response => response.text())
15-
.then(text => {
16-
const validator = document.querySelector("json-schema-validator");
17-
validator.editor.setText(text)
14+
15+
/*
16+
I'd prefer to use fetch, but need to get demo to work on IE :-(
17+
*/
18+
function getText(url, callback) {
19+
var xhr = new XMLHttpRequest();
20+
21+
xhr.onreadystatechange = function() {
22+
if (xhr.readyState === 4) {
23+
callback(xhr.response);
24+
}
25+
}
26+
27+
xhr.open('GET', url, true);
28+
xhr.send('');
29+
}
30+
31+
setTimeout(function(){
32+
getText("./example-data.json", function(text) {
33+
document.querySelector("json-schema-validator").editor.setText(text);
1834
})
19-
}, 1000)
35+
}, 1000);
2036
</script>
2137
</body>
2238
</html>

0 commit comments

Comments
 (0)