Commit 38d56377 authored by Rebecca Blundell's avatar Rebecca Blundell Committed by Rebecca Blundell

Bug 1635503: Add JSON editor for SmartEvidence

This adds a visual JSON editor for SmartEvidence
frameworks allowing site administrators to create
such frameworks more easily by copying and pasting
rather than needing to know the JSON file syntax.

behatnotneeded

Change-Id: Ief74375a6c5d23ab05e12f08d07dd3209e89c948
parent 2c82fcdd
The MIT License (MIT)
Copyright (c) 2013 Jeremy Dorn
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
JSONeditor in Mahara
=================
Website: https://github.com/json-editor/json-editor/
Version: 1.3
This library is used by SmartEvidence, to provide a user-friendly way
of editing a framework, without relying on a json upload.
In order to work, the JSONeditor needs a dist folder with jsoneditor.js and
jsoneditor.js.map in it.
It's not in the github repo for some reason, but can be found here:
https://www.jsdelivr.com/package/npm/@json-editor/json-editor?path=dist&version=1.3.0
Changes:
Removed .github, tests and docs folders; Gruntfile.js, package.json,
package-lock.json, .gitattributes, .gitignore, npmignore, .npmrc and travis.yml
From src/iconlibs, removed bootstrap2.js, foundation2-3.js, materialicons.js
src/styles
src/templates - all but default
src/themes bootstrap2.js, foundation.js, materialize.js
To allow changing of the text on the Edit JSON button:
in src/defaults.js, added:
/**
* Title on Edit JSON buttons
*/
button_edit : "Edit raw"
in src/dist/jsoneditor.js
replaced this.editjson_button = this.getButton('JSON','edit','Edit JSON');
with this.editjson_button = this.getButton('','edit', this.translate('button_edit'));
added button_edit: "Edit raw", to the JSONEditor.defualts.languages.en JSON
To stop the editor displaying undefined in the Standard Elements header when the parent
id is undefined:
in src/dist/jsoneditor.js - added the asterisked line to the following:
// The compiled function
return function(vars) {
var ret = template+"";
var r;
for(i=0; i<l; i++) {
r = replacements[i];
ret = ret.replace(r.s, r.r(vars));
}
* ret = ret.replace(/undefined\./gi, '');
return ret;
Because Mahara requires just an initial capital letter on titles, added the asterisked
lines to the JSONEditor.defaults.translate function:
if(variables) {
for(var i=0; i<variables.length; i++) {
string = string.replace(new RegExp('\\{\\{'+i+'}}','g'),variables[i]);
* string = string.toLowerCase();
* string = string.charAt(0).toUpperCase() + string.slice(1);
}
}
This diff is collapsed.
/*jshint loopfunc: true */
/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
var Class;
(function(){
var initializing = false, fnTest = /xyz/.test(function(){window.postMessage("xyz");}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
Class = function(){};
// Create a new Class that inherits from this class
Class.extend = function extend(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
// And make this class extendable
Class.extend = extend;
return Class;
};
return Class;
})();
var JSONEditor = function(element,options) {
if (!(element instanceof Element)) {
throw new Error('element should be an instance of Element');
}
options = $extend({},JSONEditor.defaults.options,options||{});
this.element = element;
this.options = options;
this.init();
};
JSONEditor.prototype = {
// necessary since we remove the ctor property by doing a literal assignment. Without this
// the $isplainobject function will think that this is a plain object.
constructor: JSONEditor,
init: function() {
var self = this;
this.ready = false;
this.copyClipboard = null;
var theme_class = JSONEditor.defaults.themes[this.options.theme || JSONEditor.defaults.theme];
if(!theme_class) throw "Unknown theme " + (this.options.theme || JSONEditor.defaults.theme);
this.schema = this.options.schema;
this.theme = new theme_class();
this.template = this.options.template;
this.refs = this.options.refs || {};
this.uuid = 0;
this.__data = {};
var icon_class = JSONEditor.defaults.iconlibs[this.options.iconlib || JSONEditor.defaults.iconlib];
if(icon_class) this.iconlib = new icon_class();
this.root_container = this.theme.getContainer();
this.element.appendChild(this.root_container);
this.translate = this.options.translate || JSONEditor.defaults.translate;
// Fetch all external refs via ajax
this._loadExternalRefs(this.schema, function() {
self._getDefinitions(self.schema);
// Validator options
var validator_options = {};
if(self.options.custom_validators) {
validator_options.custom_validators = self.options.custom_validators;
}
self.validator = new JSONEditor.Validator(self,null,validator_options);
// Create the root editor
var schema = self.expandRefs(self.schema);
var editor_class = self.getEditorClass(schema);
self.root = self.createEditor(editor_class, {
jsoneditor: self,
schema: schema,
required: true,
container: self.root_container
});
self.root.preBuild();
self.root.build();
self.root.postBuild();
// Starting data
if(self.options.hasOwnProperty('startval')) self.root.setValue(self.options.startval);
self.validation_results = self.validator.validate(self.root.getValue());
self.root.showValidationErrors(self.validation_results);
self.ready = true;
// Fire ready event asynchronously
window.requestAnimationFrame(function() {
if(!self.ready) return;
self.validation_results = self.validator.validate(self.root.getValue());
self.root.showValidationErrors(self.validation_results);
self.trigger('ready');
self.trigger('change');
});
});
},
getValue: function() {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before getting the value";
return this.root.getValue();
},
setValue: function(value) {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before setting the value";
this.root.setValue(value);
return this;
},
validate: function(value) {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before validating";
// Custom value
if(arguments.length === 1) {
return this.validator.validate(value);
}
// Current value (use cached result)
else {
return this.validation_results;
}
},
destroy: function() {
if(this.destroyed) return;
if(!this.ready) return;
this.schema = null;
this.options = null;
this.root.destroy();
this.root = null;
this.root_container = null;
this.validator = null;
this.validation_results = null;
this.theme = null;
this.iconlib = null;
this.template = null;
this.__data = null;
this.ready = false;
this.element.innerHTML = '';
this.destroyed = true;
},
on: function(event, callback) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = this.callbacks[event] || [];
this.callbacks[event].push(callback);
return this;
},
off: function(event, callback) {
// Specific callback
if(event && callback) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = this.callbacks[event] || [];
var newcallbacks = [];
for(var i=0; i<this.callbacks[event].length; i++) {
if(this.callbacks[event][i]===callback) continue;
newcallbacks.push(this.callbacks[event][i]);
}
this.callbacks[event] = newcallbacks;
}
// All callbacks for a specific event
else if(event) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = [];
}
// All callbacks for all events
else {
this.callbacks = {};
}
return this;
},
trigger: function(event) {
if(this.callbacks && this.callbacks[event] && this.callbacks[event].length) {
for(var i=0; i<this.callbacks[event].length; i++) {
this.callbacks[event][i].apply(this, []);
}
}
return this;
},
setOption: function(option, value) {
if(option === "show_errors") {
this.options.show_errors = value;
this.onChange();
}
// Only the `show_errors` option is supported for now
else {
throw "Option "+option+" must be set during instantiation and cannot be changed later";
}
return this;
},
getEditorClass: function(schema) {
var classname;
schema = this.expandSchema(schema);
$each(JSONEditor.defaults.resolvers,function(i,resolver) {
var tmp = resolver(schema);
if(tmp) {
if(JSONEditor.defaults.editors[tmp]) {
classname = tmp;
return false;
}
}
});
if(!classname) throw "Unknown editor for schema "+JSON.stringify(schema);
if(!JSONEditor.defaults.editors[classname]) throw "Unknown editor "+classname;
return JSONEditor.defaults.editors[classname];
},
createEditor: function(editor_class, options) {
options = $extend({},editor_class.options||{},options);
return new editor_class(options);
},
onChange: function() {
if(!this.ready) return;
if(this.firing_change) return;
this.firing_change = true;
var self = this;
window.requestAnimationFrame(function() {
self.firing_change = false;
if(!self.ready) return;
// Validate and cache results
self.validation_results = self.validator.validate(self.root.getValue());
if(self.options.show_errors !== "never") {
self.root.showValidationErrors(self.validation_results);
}
else {
self.root.showValidationErrors([]);
}
// Fire change event
self.trigger('change');
});
return this;
},
compileTemplate: function(template, name) {
name = name || JSONEditor.defaults.template;
var engine;
// Specifying a preset engine
if(typeof name === 'string') {
if(!JSONEditor.defaults.templates[name]) throw "Unknown template engine "+name;
engine = JSONEditor.defaults.templates[name]();
if(!engine) throw "Template engine "+name+" missing required library.";
}
// Specifying a custom engine
else {
engine = name;
}
if(!engine) throw "No template engine set";
if(!engine.compile) throw "Invalid template engine set";
return engine.compile(template);
},
_data: function(el,key,value) {
// Setting data
if(arguments.length === 3) {
var uuid;
if(el.hasAttribute('data-jsoneditor-'+key)) {
uuid = el.getAttribute('data-jsoneditor-'+key);
}
else {
uuid = this.uuid++;
el.setAttribute('data-jsoneditor-'+key,uuid);
}
this.__data[uuid] = value;
}
// Getting data
else {
// No data stored
if(!el.hasAttribute('data-jsoneditor-'+key)) return null;
return this.__data[el.getAttribute('data-jsoneditor-'+key)];
}
},
registerEditor: function(editor) {
this.editors = this.editors || {};
this.editors[editor.path] = editor;
return this;
},
unregisterEditor: function(editor) {
this.editors = this.editors || {};
this.editors[editor.path] = null;
return this;
},
getEditor: function(path) {
if(!this.editors) return;
return this.editors[path];
},
watch: function(path,callback) {
this.watchlist = this.watchlist || {};
this.watchlist[path] = this.watchlist[path] || [];
this.watchlist[path].push(callback);
return this;
},
unwatch: function(path,callback) {
if(!this.watchlist || !this.watchlist[path]) return this;
// If removing all callbacks for a path
if(!callback) {
this.watchlist[path] = null;
return this;
}
var newlist = [];
for(var i=0; i<this.watchlist[path].length; i++) {
if(this.watchlist[path][i] === callback) continue;
else newlist.push(this.watchlist[path][i]);
}
this.watchlist[path] = newlist.length? newlist : null;
return this;
},
notifyWatchers: function(path) {
if(!this.watchlist || !this.watchlist[path]) return this;
for(var i=0; i<this.watchlist[path].length; i++) {
this.watchlist[path][i]();
}
},
isEnabled: function() {
return !this.root || this.root.isEnabled();
},
enable: function() {
this.root.enable();
},
disable: function() {
this.root.disable();
},
_getDefinitions: function(schema,path) {
path = path || '#/definitions/';
if(schema.definitions) {
for(var i in schema.definitions) {
if(!schema.definitions.hasOwnProperty(i)) continue;
this.refs[path+i] = schema.definitions[i];
if(schema.definitions[i].definitions) {
this._getDefinitions(schema.definitions[i],path+i+'/definitions/');
}
}
}
},
_getExternalRefs: function(schema) {
var refs = {};
var merge_refs = function(newrefs) {
for(var i in newrefs) {
if(newrefs.hasOwnProperty(i)) {
refs[i] = true;
}
}
};
if(schema.$ref && typeof schema.$ref !== "object" && schema.$ref.substr(0,1) !== "#" && !this.refs[schema.$ref]) {
refs[schema.$ref] = true;
}
for(var i in schema) {
if(!schema.hasOwnProperty(i)) continue;
if(schema[i] && typeof schema[i] === "object" && Array.isArray(schema[i])) {
for(var j=0; j<schema[i].length; j++) {
if(schema[i][j] && typeof schema[i][j]==="object") {
merge_refs(this._getExternalRefs(schema[i][j]));
}
}
}
else if(schema[i] && typeof schema[i] === "object") {
merge_refs(this._getExternalRefs(schema[i]));
}
}
return refs;
},
_getFileBase: function() {
var fileBase = this.options.ajaxBase;
if (typeof fileBase === 'undefined') {
fileBase = this._getFileBaseFromFileLocation(document.location.toString());
}
return fileBase;
},
_getFileBaseFromFileLocation: function(fileLocationString) {
var pathItems = fileLocationString.split("/");
pathItems.pop();
return pathItems.join("/")+"/";
},
_loadExternalRefs: function(schema, callback, fileBase) {
fileBase = fileBase || this._getFileBase();
var self = this;
var refs = this._getExternalRefs(schema);
var done = 0, waiting = 0, callback_fired = false;
$each(refs,function(url) {
if(self.refs[url]) return;
if(!self.options.ajax) throw "Must set ajax option to true to load external ref "+url;
self.refs[url] = 'loading';
waiting++;
var fetchUrl=url;
if( fileBase!=url.substr(0,fileBase.length) && "http"!=url.substr(0,4) && "/"!=url.substr(0,1)) fetchUrl=fileBase+url;
var r = new XMLHttpRequest();
r.open("GET", fetchUrl, true);
if(self.options.ajaxCredentials) r.withCredentials=self.options.ajaxCredentials;
r.onreadystatechange = function () {
if (r.readyState != 4) return;
// Request succeeded
if(r.status === 200) {
var response;
try {
response = JSON.parse(r.responseText);
}
catch(e) {
window.console.log(e);
throw "Failed to parse external ref "+fetchUrl;
}
if(!response || typeof response !== "object") throw "External ref does not contain a valid schema - "+fetchUrl;
self.refs[url] = response;
self._loadExternalRefs(response,function() {
done++;
if(done >= waiting && !callback_fired) {
callback_fired = true;
callback();
}
}, self._getFileBaseFromFileLocation(fetchUrl));
}
// Request failed
else {
window.console.log(r);